@fibteq/myrel-runner 0.28.1 → 0.28.2
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 +22 -22
- package/dist/index.js +20 -20
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -59,7 +59,7 @@ ${u}`:u:"",d=Function,p=`return (input) => {
|
|
|
59
59
|
${u}
|
|
60
60
|
}`,m;try{m=new d(...a,p)(...s)}catch(f){throw new M(`this schema (generated code failed to evaluate: ${f.message})`)}return t?.debug&&(m.code=l),m.definite=o.definite,m}function N(e,t){for(let[o,n]of e.constants)if(n===t)return o;let r=`c${e.constantCounter++}`;return e.constants.set(r,t),r}function Ut(e,t){return e.definite=!1,N(e,t)}function O(e){return`v${e.varCounter++}`}function Gx(e,t){let r=e._zod.run({value:t,issues:[]},{});if(r&&typeof r.then=="function")return he;let o=r;return o.issues.length===0?o.value:he}function fe(e,t,r,o,n=!0){let i=e.content.length,a=t.constants.size,s=t.constantCounter,u=t.varCounter;try{return Y(e,t,r,o,n)}catch(l){if(!(l instanceof M)||!l.islandable)throw l;if(e.content.length=i,t.constants.size>a){let d=Array.from(t.constants.keys()).slice(a);for(let p of d)t.constants.delete(p)}return t.constantCounter=s,t.varCounter=u,qx(e,t,r,o)}}function qx(e,t,r,o){t.definite=!1;let n=N(t,r),i=N(t,Gx),a=O(t);return e.write(`const ${a} = ${i}(${n}, ${o});`),e.write(`if (${a} === INVALID) return INVALID;`),a}var Hx=new Set(["max_size","min_size","size_equals","max_length","min_length","length_equals"]);function Xx(e,t,r,o){let n=r._zod.def.checks;if(!n||n.length===0)return o;let i=o;for(let a of n){let s=a._zod.def;if(s.when&&!Hx.has(s.check))throw new M('check with a custom "when" condition');switch(s.check){case"greater_than":Yx(e,t,s,i);break;case"less_than":Qx(e,t,s,i);break;case"multiple_of":ek(e,t,s,i);break;case"number_format":Ng(e,s,i);break;case"min_length":{let u=ft(s.minimum,"min_length"),l=Zu(e,t,i,`${i}.length >= ${u} && ${i}.length < ${s.minimum*2}`);e.write(`if (${l} < ${u}) return INVALID;`);break}case"max_length":{let u=ft(s.maximum,"max_length"),l=Zu(e,t,i,`${i}.length > ${u}`);e.write(`if (${l} > ${u}) return INVALID;`);break}case"length_equals":{let u=ft(s.length,"length_equals"),l=Zu(e,t,i,`${i}.length >= ${u} && ${i}.length <= ${s.length*2}`);e.write(`if (${l} !== ${u}) return INVALID;`);break}case"min_size":e.write(`if (${i}.size < ${ft(s.minimum,"min_size")}) return INVALID;`);break;case"max_size":e.write(`if (${i}.size > ${ft(s.maximum,"max_size")}) return INVALID;`);break;case"size_equals":e.write(`if (${i}.size !== ${ft(s.size,"size_equals")}) return INVALID;`);break;case"string_format":i=Dg(e,t,s,i);break;case"custom":i=ak(e,t,a,i);break;case"bigint_format":tk(e,s,i);break;case"mime_type":nk(e,t,s,i);break;case"property":ik(e,t,s,i);break;case"properties":rk(e,t,s,i);break;case"overwrite":{let u=O(t);ok(e,t,a,i,u),i=u;break}default:throw new M(`check type ${s.check}`)}}return i}function Zu(e,t,r,o){let n=N(t,At),i=O(t);return e.write(`const ${i} = typeof ${r} === "string" && ${o} ? ${n}(${r}) : ${r}.length;`),i}function ft(e,t){if(typeof e!="number"||!Number.isFinite(e))throw new M(`${t} bound of type ${typeof e}`);return`${e}`}function Tg(e,t){if(typeof t=="bigint")return`${t}n`;if(typeof t=="number"){if(Number.isNaN(t))throw new M("comparison check with NaN bound");return`${t}`}if(t instanceof Date){if(Number.isNaN(t.getTime()))throw new M("comparison check with Invalid Date bound");return N(e,t)}throw new M(`comparison check bound of type ${typeof t}`)}function Yx(e,t,r,o){let n=r.inclusive?"<":"<=";e.write(`if (${o} ${n} ${Tg(t,r.value)}) return INVALID;`)}function Qx(e,t,r,o){let n=r.inclusive?">":">=";e.write(`if (${o} ${n} ${Tg(t,r.value)}) return INVALID;`)}function ek(e,t,r,o){if(typeof r.value=="bigint"){if(r.value===BigInt(0))throw new M("multiple_of check with a zero divisor");e.write(`if (${o} % ${r.value}n !== 0n) return INVALID;`)}else{let n=N(t,er);e.write(`if (${n}(${o}, ${ft(r.value,"multiple_of")}) !== 0) return INVALID;`)}}function Ng(e,t,r){let o=t.format;switch(o){case"safeint":e.write(`if (!Number.isSafeInteger(${r})) return INVALID;`);break;case"int32":e.write(`if (!Number.isInteger(${r}) || ${r} < -2147483648 || ${r} > 2147483647) return INVALID;`);break;case"uint32":e.write(`if (!Number.isInteger(${r}) || ${r} < 0 || ${r} > 4294967295) return INVALID;`);break;case"float32":e.write(`if (!Number.isFinite(${r}) || ${r} < -3.4028234663852886e38 || ${r} > 3.4028234663852886e38) return INVALID;`);break;case"float64":e.write(`if (!Number.isFinite(${r})) return INVALID;`);break;default:throw new M(`number format ${o}`)}}function tk(e,t,r){let o=t.format;if(o)switch(o){case"int64":e.write(`if (${r} < -9223372036854775808n || ${r} > 9223372036854775807n) return INVALID;`);break;case"uint64":e.write(`if (${r} < 0n || ${r} > 18446744073709551615n) return INVALID;`);break;default:throw new M(`bigint format ${o}`)}}function nk(e,t,r,o){let n=r.mime;if(n&&n.length>0){let i=N(t,new Set(n));e.write(`if (!${i}.has(${o}.type)) return INVALID;`)}}function rk(e,t,r,o){if(r.when)throw new M('check with a custom "when" condition');e.write(`if (${o} == null) return INVALID;`);let n=r.shape;for(let i of Reflect.ownKeys(n)){let a=typeof i=="symbol"?N(t,i):me(i),s=O(t);e.write(`const ${s} = ${o}[${a}];`),fe(e,t,n[i],s,!1)}}function ik(e,t,r,o){let n=`${o}[${JSON.stringify(r.property)}]`;Y(e,t,r.schema,n)}function ok(e,t,r,o,n){let i=r._zod.def.tx;if(!i)throw new M("overwrite check without a transform function");if(Ct(i))throw new Re("z.compile: async overwrite transforms are not supported");let a=N(t,i);e.write(`const ${n} = ${a}(${o});`)}function Fu(){throw new ke}function Ju(e){this.issues.push(e)}function ak(e,t,r,o){let n=r._zod.def;if(n.fn){if(Ct(n.fn))throw new Re("z.compile: async .refine() predicates are not supported");let i=Ut(t,n.fn),a=N(t,Fu),s=O(t);return e.write(`const ${s} = ${i}(${o});`),e.write(`if (${s} instanceof Promise) ${a}();`),e.write(`if (!${s}) return INVALID;`),o}if(r._zod.check){if(Ct(r._zod.check))throw new Re("z.compile: async .superRefine() / check functions are not supported");let i=r._zod.check,s=Ut(t,l=>{let d={value:l,issues:[],addIssue:Ju};return i(d)instanceof Promise&&Fu(),d.issues.length===0?d.value:he}),u=O(t);return e.write(`const ${u} = ${s}(${o});`),e.write(`if (${u} === INVALID) return INVALID;`),u}throw new M("custom check without a predicate or check function")}var sk=new Set(["cidrv4","cuid","cuid2","date","datetime","duration","e164","email","emoji","ends_with","guid","includes","ipv4","ksuid","lowercase","mac","nanoid","regex","starts_with","time","ulid","uppercase","uuid","xid"]);function Dg(e,t,r,o,n=!0){let i=r.format;if(i==="base64"){let l=N(t,br);return e.write(`if (!${l}(${o})) return INVALID;`),o}if(i==="base64url"){let l=N(t,Ki);return e.write(`if (!${l}(${o})) return INVALID;`),o}if(i==="jwt"){let l=N(t,Wi),d=N(t,r.alg??null);return e.write(`if (!${l}(${o}, ${d})) return INVALID;`),o}if(i==="ipv6"){let l=N(t,$r);return e.write(`if (!${l}(${o})) return INVALID;`),o}if(i==="cidrv6"){let l=N(t,Fi);return e.write(`if (!${l}(${o})) return INVALID;`),o}if(i==="credit_card"){let l=N(t,Ji);return e.write(`if (!${l}(${o})) return INVALID;`),o}if(i==="iban"){let l=N(t,Bi);return e.write(`if (!${l}(${o})) return INVALID;`),o}let a=r;if(i==="url"||i==="httpurl"||a.normalize||a.hostname!==void 0||a.protocol!==void 0){let l=N(t,Mi),d=N(t,r),p=O(t),m=O(t);if(e.write(`const ${p} = ${o}.trim();`),e.write(`const ${m} = ${l}(${p}, ${d});`),e.write(`if (typeof ${m} === "number") return INVALID;`),a.hostname!==void 0){let y=N(t,Li);e.write(`if (!${y}(${m}, ${d}.hostname)) return INVALID;`)}if(a.protocol!==void 0){let y=N(t,Zi);e.write(`if (!${y}(${m}, ${d}.protocol)) return INVALID;`)}if(!n)return null;let f=O(t),v=a.normalize?`${m}.href`:`${N(t,yr)}(${p})`;return e.write(`const ${f} = ${v};`),f}let s=r.fn;if(s){if(Ct(s))throw new M(`async string format ${i}`);let l=N(t,s);return e.write(`if (!${l}(${o})) return INVALID;`),o}if(sk.has(i)&&r.pattern){let l=N(t,r.pattern);return e.write(`${l}.lastIndex = 0;`),e.write(`if (!${l}.test(${o})) return INVALID;`),o}let u=r.format;switch(u){case"regex":throw new M("regex format without a pattern");case"lowercase":e.write(`if (${o} !== ${o}.toLowerCase()) return INVALID;`);break;case"uppercase":e.write(`if (${o} !== ${o}.toUpperCase()) return INVALID;`);break;case"includes":e.write(`if (!${o}.includes(${me(r.includes)})) return INVALID;`);break;case"starts_with":{let l=r.prefix;e.write(`if (${o}.slice(0, ${l.length}) !== ${me(l)}) return INVALID;`);break}case"ends_with":{let l=r.suffix;e.write(`if (${o}.slice(-${l.length}) !== ${me(l)}) return INVALID;`);break}default:throw new M(`string format ${u}`)}return o}function Y(e,t,r,o,n=!0){let i=r._zod.def,a=i.type;if(i.coerce)throw new M(`coercion (z.coerce.${a}())`);let s=n||!!i.checks?.length,u;switch(a){case"string":u=ck(e,t,r,o,s);break;case"number":u=uk(e,r,o);break;case"boolean":u=lk(e,o);break;case"bigint":u=dk(e,r,o);break;case"symbol":u=pk(e,o);break;case"undefined":u=fk(e,o);break;case"null":u=mk(e,o);break;case"any":case"unknown":u=o;break;case"never":e.write("return INVALID;"),u=o;break;case"void":u=gk(e,o);break;case"nan":u=hk(e,o);break;case"date":u=vk(e,o);break;case"object":u=yk(e,t,r,o,s);break;case"optional":u=$k(e,t,r,o,s);break;case"nullable":u=xk(e,t,r,o,s);break;case"array":u=kk(e,t,r,o,s);break;case"literal":u=wk(e,t,r,o);break;case"enum":u=Sk(e,t,r,o);break;case"readonly":{let l=jg(e,t,r,o),d=O(t);e.write(`const ${d} = Object.freeze(${l});`),u=d;break}case"success":jg(e,t,r,o),u="true";break;case"default":case"prefault":u=Ik(e,t,r,o);break;case"nonoptional":u=zk(e,t,r,o);break;case"tuple":u=Pk(e,t,r,o);break;case"union":u=jk(e,t,r,o);break;case"intersection":u=Tk(e,t,r,o);break;case"record":u=Nk(e,t,r,o);break;case"map":u=Uk(e,t,r,o);break;case"set":u=Ck(e,t,r,o);break;case"file":u=Ek(e,o);break;case"template_literal":u=Rk(e,t,r,o);break;case"lazy":u=Mk(e,t,r,o);break;case"pipe":u=Lk(e,t,r,o);break;case"custom":u=Zk(e,t,r,o);break;case"transform":u=Kk(e,t,r,o);break;case"catch":u=Vk(e,t,r,o);break;default:throw new M(`schema type ${a}`)}return u===null?null:Xx(e,t,r,u)}function ck(e,t,r,o,n=!0){e.write(`if (typeof ${o} !== "string") return INVALID;`);let i=r._zod.def;return i.format===void 0?o:Dg(e,t,i,o,n)}function uk(e,t,r){e.write(`if (typeof ${r} !== "number" || !Number.isFinite(${r})) return INVALID;`);let o=t._zod.def;return o.check==="number_format"&&o.format&&Ng(e,{format:o.format},r),r}function lk(e,t){return e.write(`if (typeof ${t} !== "boolean") return INVALID;`),t}function dk(e,t,r){e.write(`if (typeof ${r} !== "bigint") return INVALID;`);let o=t._zod.def;if(o.format)switch(o.format){case"int64":e.write(`if (${r} < -9223372036854775808n || ${r} > 9223372036854775807n) return INVALID;`);break;case"uint64":e.write(`if (${r} < 0n || ${r} > 18446744073709551615n) return INVALID;`);break}return r}function pk(e,t){return e.write(`if (typeof ${t} !== "symbol") return INVALID;`),t}function fk(e,t){return e.write(`if (${t} !== undefined) return INVALID;`),t}function mk(e,t){return e.write(`if (${t} !== null) return INVALID;`),t}function gk(e,t){return e.write(`if (${t} !== undefined) return INVALID;`),t}function hk(e,t){return e.write(`if (typeof ${t} !== "number" || !Number.isNaN(${t})) return INVALID;`),t}function vk(e,t){return e.write(`if (!(${t} instanceof Date) || Number.isNaN(${t}.getTime())) return INVALID;`),t}function yk(e,t,r,o,n=!0){let i=r._zod.def;e.write(`if (typeof ${o} !== "object" || ${o} === null || Array.isArray(${o})) return INVALID;`);let a=i.shape,s=Object.keys(a),u=Object.getOwnPropertySymbols(a),l=u.length?[...s,...u]:s,d=P=>typeof P=="symbol"?N(t,P):me(P),p=P=>typeof P=="symbol"?`[${d(P)}]`:me(P),m=a;if(s.includes("__proto__"))throw new M('object shape key "__proto__"');let f=new Map;for(let P of l){let T=m[P],S=d(P),I=O(t);if(e.write(`const ${I} = ${o}[${S}];`),T._zod.optin!==void 0){let A=O(t);e.write(`let ${A} = (() => {`),e.indented(X=>{let Pe=fe(X,t,T,I);X.write(`return ${Pe};`)}),e.write("})();"),T._zod.optout==="optional"?(e.write(`if (${A} === INVALID) {`),e.indented(X=>{X.write(`if (${S} in ${o}) return INVALID;`),X.write(`${A} = undefined;`)}),e.write("}")):e.write(`if (${A} === INVALID) return INVALID;`),f.set(P,A)}else{_k(T)&&e.write(`if (!(${S} in ${o})) return INVALID;`);let A=fe(e,t,T,I,n);A!==null&&f.set(P,A)}}let v=i.catchall,y="none";if(v){let P=v._zod.def.type;if(P==="never"){let T=s.map(S=>`k !== ${me(S)}`).join(" && ")||"true";e.write(`for (const k in ${o}) {`),e.indented(S=>{S.write(`if (${T}) return INVALID;`)}),e.write("}")}else(P==="unknown"||P==="any")&&!v._zod.def.checks?.length?y="passthrough":y="schema"}let x=O(t),j=l.some(P=>Pg(m[P])||Vu(m[P]));if(!n){if(y==="schema"){let P=s.length>0?N(t,new Set(s)):null;e.write(`for (const k in ${o}) {`),e.indented(T=>{T.write('if (k === "__proto__") continue;'),P&&T.write(`if (${P}.has(k)) continue;`);let S=O(t);T.write(`const ${S} = ${o}[k];`),fe(T,t,v,S,!1)}),e.write("}")}return null}if(j){e.write(`const ${x} = {};`);for(let P of l){let T=d(P),S=f.get(P);Vu(m[P])?e.write(`if (${T} in ${o}) ${x}[${T}] = ${S};`):Pg(m[P])?e.write(`if (${S} !== undefined || ${T} in ${o}) ${x}[${T}] = ${S};`):e.write(`${x}[${T}] = ${S};`)}}else{let P=l.map(T=>`${p(T)}: ${f.get(T)}`).join(", ");e.write(`const ${x} = { ${P} };`)}if(y!=="none"){let P=s.length>0?N(t,new Set(s)):null;e.write(`for (const k in ${o}) {`),e.indented(T=>{if(T.write('if (k === "__proto__") continue;'),P&&T.write(`if (${P}.has(k)) continue;`),y==="passthrough")T.write(`${x}[k] = ${o}[k];`);else{let S=O(t);T.write(`const ${S} = ${o}[k];`);let I=fe(T,t,v,S);T.write(`${x}[k] = ${I};`)}}),e.write("}")}return x}function $k(e,t,r,o,n=!0){let i=r._zod.def;if(bk(r))return Y(e,t,i.innerType,o,n);if(i.innerType._zod.optin==="defaulted"){let s=O(t),u=O(t);return e.write(`let ${s};`),e.write(`if (${o} === undefined) {`),e.indented(l=>{l.write(`const ${u} = (() => {`),l.indented(d=>{let p=Y(d,t,i.innerType,o);d.write(`return ${p};`)}),l.write("})();"),l.write(`if (${u} !== INVALID) ${s} = ${u};`)}),e.write("} else {"),e.indented(l=>{let d=Y(l,t,i.innerType,o);l.write(`${s} = ${d};`)}),e.write("}"),s}let a=n?O(t):null;return a&&e.write(`let ${a};`),e.write(`if (${o} !== undefined) {`),e.indented(s=>{let u=Y(s,t,i.innerType,o,n);a&&u!==null&&s.write(`${a} = ${u};`)}),e.write("}"),a}function bk(e){return e._zod.traits?.has("$ZodExactOptional")===!0}function _k(e){return e._zod.optin===void 0&&Dt(e)}function Dt(e){if(e._zod.def.coerce)return!0;let t=e._zod.def;switch(t.type){case"any":case"unknown":case"undefined":case"void":case"default":case"prefault":case"transform":case"custom":case"lazy":return!0;case"string":case"number":case"boolean":case"bigint":case"symbol":case"null":case"never":case"nan":case"date":case"object":case"array":case"tuple":case"record":case"map":case"set":case"file":case"template_literal":return!1;case"nonoptional":return t.innerType?Dt(t.innerType):!1;case"literal":return!!t.values?.includes(void 0);case"enum":return!!e._zod.values?.has(void 0);case"optional":case"nullable":case"readonly":case"success":return t.innerType?Dt(t.innerType):!0;case"catch":return!0;case"union":return t.options?t.options.some(Dt):!0;case"intersection":return!t.left||!t.right?!0:Dt(t.left)&&Dt(t.right);case"pipe":return t.in?Dt(t.in):!0;default:return!0}}function Vu(e){return e._zod.optin==="optional"&&e._zod.optout==="optional"}function Pg(e){return(e._zod.optin!=="defaulted"||e._zod.optout==="optional")&&yn(e)}function yn(e){let t=e._zod.def;switch(t.type){case"string":case"number":case"boolean":case"bigint":case"symbol":case"null":case"nan":case"date":case"object":case"array":case"tuple":case"record":case"map":case"set":case"file":case"template_literal":case"never":case"success":return!1;case"literal":return!!t.values?.includes(void 0);case"enum":return!!e._zod.values?.has(void 0);case"optional":return!0;case"nullable":case"readonly":case"nonoptional":return t.innerType?yn(t.innerType):!0;case"union":return t.options?t.options.some(yn):!0;case"intersection":return!t.left||!t.right||yn(t.left)||yn(t.right);case"pipe":return t.out?yn(t.out):!0;default:return!0}}function xk(e,t,r,o,n=!0){let i=r._zod.def,a=n?O(t):null;return a&&e.write(`let ${a} = null;`),e.write(`if (${o} !== null) {`),e.indented(s=>{let u=Y(s,t,i.innerType,o,n);a&&u!==null&&s.write(`${a} = ${u};`)}),e.write("}"),a}function Bu(e,t,r){for(let[o,n]of cn(t._zod.def.checks))e.write(`if (${r} > ${ft(o,n._zod.def.check)}) return INVALID;`)}function kk(e,t,r,o,n=!0){let i=r._zod.def;e.write(`if (!Array.isArray(${o})) return INVALID;`),Bu(e,r,`${o}.length`);let a=n?O(t):null,s=O(t),u=O(t);return a&&e.write(`const ${a} = new Array(${o}.length);`),e.write(`for (let ${s} = 0; ${s} < ${o}.length; ${s}++) {`),e.indented(l=>{l.write(`const ${u} = ${o}[${s}];`);let d=fe(l,t,i.element,u,n);a&&d!==null&&l.write(`${a}[${s}] = ${d};`)}),e.write("}"),a}function wk(e,t,r,o){let i=r._zod.def.values;if(i.length!==1){let s=N(t,new Set(i));return e.write(`if (!${s}.has(${o})) return INVALID;`),o}let a=i[0];if(typeof a=="number"&&Number.isNaN(a)){let s=N(t,new Set(i));return e.write(`if (!${s}.has(${o})) return INVALID;`),o}if(typeof a=="string")e.write(`if (${o} !== ${me(a)}) return INVALID;`);else if(typeof a=="number"||typeof a=="boolean")e.write(`if (${o} !== ${a}) return INVALID;`);else if(a===null)e.write(`if (${o} !== null) return INVALID;`);else if(a===void 0)e.write(`if (${o} !== undefined) return INVALID;`);else if(typeof a=="bigint")e.write(`if (${o} !== ${a}n) return INVALID;`);else throw new M(`literal type ${typeof a}`);return o}function Sk(e,t,r,o){let n=r._zod.values;if(!n)throw new M("enum schema without enumerated values");let i=N(t,n);return e.write(`if (!${i}.has(${o})) return INVALID;`),o}function jg(e,t,r,o){let n=r._zod.def;return Y(e,t,n.innerType,o)}function Ik(e,t,r,o){let n=r._zod.def,a=Object.getOwnPropertyDescriptor(r._zod.def,"defaultValue")?()=>r._zod.def.defaultValue:void 0;if(r._zod.def.type==="prefault"){if(!a)return Y(e,t,n.innerType,o);let u=N(t,a),l=O(t);return e.write(`let ${l} = ${o};`),e.write(`if (${o} === undefined) ${l} = ${u}();`),Y(e,t,n.innerType,l)}let s=O(t);if(a){let u=N(t,a),l=N(t,tr);e.write(`let ${s};`),e.write(`if (${o} === undefined) {`),e.indented(d=>{d.write(`${s} = ${l}(${u}());`)}),e.write("} else {"),e.indented(d=>{let p=Y(d,t,n.innerType,o);d.write(`${s} = ${p} === undefined ? ${l}(${u}()) : ${p};`)}),e.write("}")}else e.write(`let ${s};`),e.write(`if (${o} !== undefined) {`),e.indented(u=>{let l=Y(u,t,n.innerType,o);u.write(`${s} = ${l};`)}),e.write("}");return s}function zk(e,t,r,o){let n=r._zod.def,i=Y(e,t,n.innerType,o),a=O(t);return e.write(`const ${a} = ${i};`),e.write(`if (${a} === undefined) return INVALID;`),a}function Pk(e,t,r,o){let n=r._zod.def,i=n.items,a=n.rest;e.write(`if (!Array.isArray(${o})) return INVALID;`);let s=Ag(i,"optin"),u=Ag(i,"optout");a?e.write(`if (${o}.length < ${s}) return INVALID;`):e.write(`if (${o}.length < ${s} || ${o}.length > ${i.length}) return INVALID;`);let l=O(t);e.write(`const ${l} = [];`);for(let d=0;d<i.length;d++){let p=i[d];if(d>=u)e.write(`if (${l}.length === ${d}) {`),e.indented(m=>{m.write(`if (${d} < ${o}.length) {`),m.indented(f=>{let v=O(t);f.write(`const ${v} = ${o}[${d}];`);let y=fe(f,t,p,v);f.write(`${l}[${d}] = ${y};`)}),m.write("} else {"),m.indented(f=>{if(Vu(p)){f.write(`${l}.length = ${d};`);return}let v=O(t),y=O(t);f.write(`const ${v} = undefined;`),f.write(`const ${y} = (() => {`),f.indented(x=>{let j=fe(x,t,p,v);x.write(`return ${j};`)}),f.write("})();"),f.write(`if (${y} === INVALID || ${y} === undefined) ${l}.length = ${d};`),f.write(`else ${l}[${d}] = ${y};`)}),m.write("}")}),e.write("}");else{let m=O(t);e.write(`const ${m} = ${o}[${d}];`);let f=fe(e,t,p,m);e.write(`${l}[${d}] = ${f};`)}}if(a){let d=O(t),p=O(t);e.write(`for (let ${d} = ${i.length}; ${d} < ${o}.length; ${d}++) {`),e.indented(m=>{m.write(`const ${p} = ${o}[${d}];`);let f=fe(m,t,a,p);m.write(`${l}[${d}] = ${f};`)}),e.write("}")}return l}function Ag(e,t){for(let r=e.length-1;r>=0;r--)if(!(t==="optin"?e[r]._zod.optin!==void 0:e[r]._zod.optout==="optional"))return r+1;return 0}function jk(e,t,r,o){let n=r._zod.def,i=n.options;if(n.discriminator)return Ak(e,t,n,o);if(n.inclusive===!1)throw new M("exclusive unions (z.xor)");if(i.length===0)return e.write("return INVALID;"),o;if(i.length===1)return Y(e,t,i[0],o);if(i.every(u=>u._zod.def.type==="literal"&&!u._zod.def.checks?.length)){let u=new Set(i.flatMap(d=>d._zod.def.values)),l=N(t,u);return e.write(`if (!${l}.has(${o})) return INVALID;`),o}let s=O(t);e.write(`let ${s};`);for(let u=0;u<i.length;u++){let l=i[u];u===0?e.write(`${s} = (() => {`):e.write(`if (${s} === INVALID) ${s} = (() => {`),e.indented(d=>{let p=Y(d,t,l,o);d.write(`return ${p};`)}),e.write("})();")}return e.write(`if (${s} === INVALID) return INVALID;`),s}function Ak(e,t,r,o){if(r.unionFallback)throw new M("discriminated union with unionFallback");if(r.options.length===0)return e.write("return INVALID;"),o;let n=O(t),i=O(t);e.write(`const ${n} = ${o}?.[${me(r.discriminator)}];`),e.write(`let ${i};`);let a=!0,s=new Set;for(let u of r.options){let l=u._zod.propValues?.[r.discriminator];if(!l||l.size===0)throw new M("discriminated union option without static discriminator values");for(let m of l){if(s.has(m))throw new M(`duplicate discriminator value ${String(m)}`);s.add(m)}let d=Array.from(l,m=>Ok(t,n,m)),p=a?"if":"else if";e.write(`${p} (${d.join(" || ")}) {`),e.indented(m=>{let f=Y(m,t,u,o);m.write(`${i} = ${f};`)}),e.write("}"),a=!1}return e.write("else { return INVALID; }"),i}function Ok(e,t,r){if(typeof r=="string")return`${t} === ${me(r)}`;if(typeof r=="number")return Number.isNaN(r)?`Number.isNaN(${t})`:`${t} === ${r}`;if(typeof r=="boolean")return`${t} === ${r}`;if(r===null)return`${t} === null`;if(r===void 0)return`${t} === undefined`;if(typeof r=="bigint")return`${t} === ${r}n`;if(typeof r=="symbol"){let o=N(e,r);return`${t} === ${o}`}throw new M(`literal discriminator value ${String(r)}`)}function Tk(e,t,r,o){let n=r._zod.def;t.definite=!1;let i=fe(e,t,n.left,o),a=fe(e,t,n.right,o),s=N(t,gn),u=O(t);return e.write(`const ${u} = ${s}(${i}, ${a});`),e.write(`if (!${u}.valid) return INVALID;`),`${u}.data`}function Nk(e,t,r,o){let n=r._zod.def,i=N(t,De);e.write(`if (!${i}(${o})) return INVALID;`);let a=O(t),s=O(t),u=O(t);e.write(`const ${a} = {};`);let l=n,d=l.partial?void 0:n.keyType._zod.values;if(d){let f=[];for(let y of d){if(!(typeof y=="string"||typeof y=="number"||typeof y=="symbol"))throw new M(`record key value ${String(y)}`);let x=typeof y=="number"?y.toString():y;if(x==="__proto__")throw new M('record key "__proto__"');f.push(x);let j=N(t,y),P=Y(e,t,n.keyType,j),T=O(t);e.write(`const ${T} = ${o}[${Dk(t,x)}];`);let S=fe(e,t,n.valueType,T);e.write(`${a}[${P}] = ${S};`)}let v=N(t,new Set(f));return e.write(`for (const ${s} in ${o}) {`),e.indented(y=>{y.write(`if (${v}.has(${s})) continue;`),l.mode==="loose"?y.write(`if (${s} !== "__proto__") ${a}[${s}] = ${o}[${s}];`):y.write("return INVALID;")}),e.write("}"),a}let p=n.keyType._zod.def;if(!(p.type==="string"&&p.format===void 0&&!p.coerce&&(p.checks?.length??0)===0)){let f=n.mode==="loose",v=po(n.keyType);v.definite===!1&&(t.definite=!1);let y=N(t,v),x=N(t,tt),j=O(t);return Og(e,t,o,s,P=>{P.write(`let ${j} = ${y}(${s});`),P.write(`if (${j} === INVALID && typeof ${s} === "string" && ${x}.test(${s})) ${j} = ${y}(Number(${s}));`),f?P.write(`if (${j} === INVALID) { ${a}[${s}] = ${o}[${s}]; continue; }`):P.write(`if (${j} === INVALID) return INVALID;`),P.write(`if (${j} === "__proto__") continue;`);let T=O(t);P.write(`const ${T} = ${o}[${s}];`);let S=fe(P,t,n.valueType,T);P.write(`${a}[${j}] = ${S};`)}),a}return Og(e,t,o,s,f=>{f.write(`const ${u} = ${o}[${s}];`);let v=fe(f,t,n.valueType,u);f.write(`${a}[${s}] = ${v};`)},"return INVALID;"),a}function Og(e,t,r,o,n,i){let a=N(t,Object.prototype.propertyIsEnumerable),s=O(t),u=O(t),l=O(t);e.write(`const ${s} = Object.getOwnPropertySymbols(${r});`),e.write(`const ${u} = Object.getOwnPropertyNames(${r});`),e.write(`for (let ${l} = 0; ${l} < ${u}.length; ${l}++) {`),e.indented(d=>{d.write(`const ${o} = ${u}[${l}];`),d.write(`if (${o} === "__proto__" || !${a}.call(${r}, ${o})) continue;`),n(d)}),e.write("}"),e.write(`for (let ${l} = 0; ${l} < ${s}.length; ${l}++) {`),e.indented(d=>{d.write(`const ${o} = ${s}[${l}];`),d.write(`if (!${a}.call(${r}, ${o})) continue;`),i?d.write(i):n(d)}),e.write("}")}function Dk(e,t){return typeof t=="string"?me(t):N(e,t)}function Uk(e,t,r,o){let n=r._zod.def;e.write(`if (!(${o} instanceof Map)) return INVALID;`),Bu(e,r,`${o}.size`);let i=O(t),a=O(t),s=O(t);return e.write(`const ${i} = new Map();`),e.write(`for (const [${a}, ${s}] of ${o}) {`),e.indented(u=>{let l=Y(u,t,n.keyType,a),d=Y(u,t,n.valueType,s);u.write(`${i}.set(${l}, ${d});`)}),e.write("}"),i}function Ck(e,t,r,o){let n=r._zod.def;e.write(`if (!(${o} instanceof Set)) return INVALID;`),Bu(e,r,`${o}.size`);let i=O(t),a=O(t);return e.write(`const ${i} = new Set();`),e.write(`for (const ${a} of ${o}) {`),e.indented(s=>{let u=Y(s,t,n.valueType,a);s.write(`${i}.add(${u});`)}),e.write("}"),i}function Ek(e,t){return e.write(`if (!(${t} instanceof File)) return INVALID;`),t}function Rk(e,t,r,o){e.write(`if (typeof ${o} !== "string") return INVALID;`);let n=r._zod.pattern;if(n){let i=N(t,n);e.write(`${i}.lastIndex = 0;`),e.write(`if (!${i}.test(${o})) return INVALID;`)}return o}function Mk(e,t,r,o){let n=r._zod.def,i=Ut(t,n.getter),a=N(t,{parser:null});e.write(`if (!${a}.parser) {`),e.indented(u=>{u.write(`const inner = ${i}();`),u.write(`${a}.parser = function(input) {`),u.indented(l=>{l.write("const result = inner._zod.run({ value: input, issues: [] }, {});"),l.write("return result.issues.length === 0 ? result.value : INVALID;")}),u.write("};")}),e.write("}");let s=O(t);return e.write(`const ${s} = ${a}.parser(${o});`),e.write(`if (${s} === INVALID) return INVALID;`),s}function Lk(e,t,r,o){let n=r._zod.def,i=Y(e,t,n.in,o);if(n.transform){if(Ct(n.transform))throw new Re("z.compile: async transforms in pipes are not supported");let a=n.transform,u=Ut(t,d=>{let p={value:d,issues:[],addIssue:Ju},m=a(d,p);return m instanceof Promise?he:p.issues.length===0?m:he}),l=O(t);return e.write(`const ${l} = ${u}(${i});`),e.write(`if (${l} === INVALID) return INVALID;`),Y(e,t,n.out,l)}else return Y(e,t,n.out,i)}function Ct(e){return typeof e=="function"&&(e.constructor.name==="AsyncFunction"||e[Symbol.toStringTag]==="AsyncFunction")}function Zk(e,t,r,o){let n=r._zod.def;if(n.fn){if(Ct(n.fn))throw new Re("z.compile: async custom predicates are not supported");let i=Ut(t,n.fn),a=N(t,Fu),s=O(t);e.write(`const ${s} = ${i}(${o});`),e.write(`if (${s} instanceof Promise) ${a}();`),e.write(`if (!${s}) return INVALID;`)}else throw new M("custom schema without a predicate function");return o}function Fk(e,t,r){let o=e._zod.run({value:r,issues:[]},{});if(o&&typeof o.then=="function")return he;let n=o;return n.issues.length===0?n.value:t()}function Vk(e,t,r,o){let n=r._zod.def;if(!n.catchValue[hi])throw new M("catch with a callback (only a constant catch value compiles)",!1);let i=O(t);e.write(`let ${i} = (() => {`),e.indented(l=>{let d=fe(l,t,n.innerType,o);l.write(`return ${d};`)}),e.write("})();");let a=N(t,n.innerType),s=Ut(t,n.catchValue),u=N(t,Fk);return e.write(`if (${i} === INVALID) {`),e.indented(l=>{l.write(`${i} = ${u}(${a}, ${s}, ${o});`),l.write(`if (${i} === INVALID) return INVALID;`)}),e.write("}"),i}function Kk(e,t,r,o){let n=r._zod.def;if(n.transform){if(Ct(n.transform))throw new Re("z.compile: async transforms are not supported");let i=n.transform,s=Ut(t,l=>{let d={value:l,issues:[],addIssue:Ju},p=i(l,d);return p instanceof Promise?he:d.issues.length===0?p:he}),u=O(t);return e.write(`const ${u} = ${s}(${o});`),e.write(`if (${u} === INVALID) return INVALID;`),u}return o}function fo(e){return e.checks&&(e.checks=[...e.checks]),e}function Wu(e,t){return new e(fo({type:"string",...k(t)}))}function Gu(e,t){return new e(fo({type:"string",coerce:!0,...k(t)}))}function mo(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...k(t)})}function go(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...k(t)})}function ho(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...k(t)})}function vo(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...k(t)})}function yo(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...k(t)})}function $o(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...k(t)})}function Or(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...k(t)})}function bo(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...k(t)})}function _o(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...k(t)})}function xo(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...k(t)})}function ko(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...k(t)})}function wo(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...k(t)})}function So(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...k(t)})}function Io(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...k(t)})}function zo(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...k(t)})}function Po(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...k(t)})}function qu(e,t){return new e({type:"string",format:"mac",check:"string_format",abort:!1,...k(t)})}function jo(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...k(t)})}function Ao(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...k(t)})}function Oo(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...k(t)})}function To(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...k(t)})}function No(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...k(t)})}function Hu(e,t){return new e({type:"string",format:"credit_card",check:"string_format",abort:!1,...k(t)})}function Xu(e,t){return new e({type:"string",format:"iban",check:"string_format",abort:!1,...k(t)})}function Do(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...k(t)})}var Yu={Any:null,Minute:-1,Second:0,Millisecond:3,Microsecond:6};function Tr(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...k(t)})}function Nr(e,t){return new e({type:"string",format:"date",check:"string_format",...k(t)})}function Dr(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...k(t)})}function Ur(e,t){return new e({type:"string",format:"duration",check:"string_format",...k(t)})}function Qu(e,t){return new e(fo({type:"number",checks:[],...k(t)}))}function el(e,t){return new e(fo({type:"number",coerce:!0,checks:[],...k(t)}))}function tl(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...k(t)})}function nl(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"float32",...k(t)})}function rl(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"float64",...k(t)})}function il(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"int32",...k(t)})}function ol(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"uint32",...k(t)})}function al(e,t){return new e({type:"boolean",...k(t)})}function sl(e,t){return new e({type:"boolean",coerce:!0,...k(t)})}function cl(e,t){return new e({type:"bigint",...k(t)})}function ul(e,t){return new e({type:"bigint",coerce:!0,...k(t)})}function ll(e,t){return new e({type:"bigint",check:"bigint_format",abort:!1,format:"int64",...k(t)})}function dl(e,t){return new e({type:"bigint",check:"bigint_format",abort:!1,format:"uint64",...k(t)})}function pl(e,t){return new e({type:"symbol",...k(t)})}function fl(e,t){return new e({type:"undefined",...k(t)})}function ml(e,t){return new e({type:"null",...k(t)})}function gl(e){return new e({type:"any"})}function hl(e){return new e({type:"unknown"})}function vl(e,t){return new e({type:"never",...k(t)})}function yl(e,t){return new e({type:"void",...k(t)})}function $l(e,t){return new e({type:"date",...k(t)})}function bl(e,t){return new e({type:"date",coerce:!0,...k(t)})}function _l(e,t){return new e({type:"nan",...k(t)})}function Ze(e,t){return new Ti({check:"less_than",...k(t),value:e,inclusive:!1})}function Ae(e,t){return new Ti({check:"less_than",...k(t),value:e,inclusive:!0})}function Fe(e,t){return new Ni({check:"greater_than",...k(t),value:e,inclusive:!1})}function Oe(e,t){return new Ni({check:"greater_than",...k(t),value:e,inclusive:!0})}function Uo(e){return Fe(0,e)}function Co(e){return Ze(0,e)}function Eo(e){return Ae(0,e)}function Ro(e){return Oe(0,e)}function mt(e,t){return new rc({check:"multiple_of",...k(t),value:e})}function gt(e,t){return new ac({check:"max_size",...k(t),maximum:e})}function Ve(e,t){return new sc({check:"min_size",...k(t),minimum:e})}function Et(e,t){return new cc({check:"size_equals",...k(t),size:e})}function Rt(e,t){return new uc({check:"max_length",...k(t),maximum:e})}function nt(e,t){return new lc({check:"min_length",...k(t),minimum:e})}function Mt(e,t){return new dc({check:"length_equals",...k(t),length:e})}function $n(e,t){return new pc({check:"string_format",format:"regex",...k(t),pattern:e})}function bn(e){return new fc({check:"string_format",format:"lowercase",...k(e)})}function _n(e){return new mc({check:"string_format",format:"uppercase",...k(e)})}function xn(e,t){return new gc({check:"string_format",format:"includes",...k(t),includes:e})}function kn(e,t){return new hc({check:"string_format",format:"starts_with",...k(t),prefix:e})}function wn(e,t){return new vc({check:"string_format",format:"ends_with",...k(t),suffix:e})}function Mo(e,t,r){return new yc({check:"property",property:e,schema:t,...k(r)})}function Sn(e,t){return new $c({check:"properties",shape:e,...k(t)})}function In(e,t){return new bc({check:"mime_type",mime:e,...k(t)})}function Me(e){return new _c({check:"overwrite",tx:e})}function zn(e){return Me(t=>t.normalize(e))}function Pn(){return Me(e=>e.trim())}function jn(){return Me(e=>e.toLowerCase())}function An(){return Me(e=>e.toUpperCase())}function On(){return Me(e=>os(e))}function xl(e,t,r){return new e({type:"array",element:t,...k(r)})}function Jk(e,t,r){return new e({type:"union",options:t,...k(r)})}function Bk(e,t,r){return new e({type:"union",options:t,inclusive:!1,...k(r)})}function Wk(e,t,r,o){return new e({type:"union",options:r,discriminator:t,...k(o)})}function Gk(e,t,r){return new e({type:"intersection",left:t,right:r})}function qk(e,t,r,o){let n=r instanceof D,i=n?o:r,a=n?r:null;return new e({type:"tuple",items:t,rest:a,...k(i)})}function Hk(e,t,r,o){return new e({type:"record",keyType:t,valueType:r,...k(o)})}function Xk(e,t,r,o){return new e({type:"map",keyType:t,valueType:r,...k(o)})}function Yk(e,t,r){return new e({type:"set",valueType:t,...k(r)})}function Qk(e,t,r){let o=Array.isArray(t)?Object.fromEntries(t.map(n=>[n,n])):t;return new e({type:"enum",entries:o,...k(r)})}function ew(e,t,r){return new e({type:"enum",entries:t,...k(r)})}function tw(e,t,r){return new e({type:"literal",values:Array.isArray(t)?t:[t],...k(r)})}function kl(e,t){return new e({type:"file",...k(t)})}function nw(e,t){return new e({type:"transform",transform:t})}function rw(e,t){return new e({type:"optional",innerType:t})}function iw(e,t){return new e({type:"nullable",innerType:t})}function ow(e,t,r){return new e({type:"default",innerType:t,get defaultValue(){return typeof r=="function"?r():tr(r)}})}function aw(e,t,r){return new e({type:"nonoptional",innerType:t,...k(r)})}function sw(e,t){return new e({type:"success",innerType:t})}function cw(e,t,r){return new e({type:"catch",innerType:t,catchValue:typeof r=="function"?r:ds(r)})}function uw(e,t,r){return new e({type:"pipe",in:t,out:r})}function lw(e,t){return new e({type:"readonly",innerType:t})}function dw(e,t,r){return new e({type:"template_literal",parts:t,...k(r)})}function pw(e,t){return new e({type:"lazy",getter:t})}function fw(e,t){return new e({type:"promise",innerType:t})}function wl(e,t,r){let o=k(r);return o.abort??(o.abort=!0),new e({type:"custom",check:"custom",fn:t,...o})}function Sl(e,t,r){return new e({type:"custom",check:"custom",fn:t,...k(r)})}function Il(e,t){let r=Ug(o=>(o.addIssue=n=>{if(typeof n=="string")o.issues.push(un(n,o.value,r._zod.def));else{let i=n;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),"input"in i||(i.input=o.value),i.inst??(i.inst=r),i.continue??(i.continue=!r._zod.def.abort),o.issues.push(un(i))}},e(o.value,o)),t);return r}function Ug(e,t){let r=new G({check:"custom",...k(t)});return r._zod.check=e,r}function zl(e){let t=new G({check:"describe"});return t._zod.onattach=[r=>{let o=le.get(r)??{};le.add(r,{...o,description:e})}],t._zod.check=()=>{},t}function Pl(e){let t=new G({check:"meta"});return t._zod.onattach=[r=>{let o=le.get(r)??{};le.add(r,{...o,...e})}],t._zod.check=()=>{},t}function jl(e,t){let r=k(t),o=r.truthy??["true","1","yes","on","y","enabled"],n=r.falsy??["false","0","no","off","n","disabled"];r.case!=="sensitive"&&(o=o.map(f=>typeof f=="string"?f.toLowerCase():f),n=n.map(f=>typeof f=="string"?f.toLowerCase():f));let i=new Set(o),a=new Set(n),s=e.Codec??wr,u=e.Boolean??xr,l=e.String??Nt,d=new l({type:"string",error:r.error}),p=new u({type:"boolean",error:r.error}),m=new s({type:"pipe",in:d,out:p,transform:((f,v)=>{let y=f;return r.case!=="sensitive"&&(y=y.toLowerCase()),i.has(y)?!0:a.has(y)?!1:(v.issues.push({code:"invalid_value",expected:"stringbool",values:[...i,...a],input:v.value,inst:m,continue:!1}),{})}),reverseTransform:((f,v)=>f===!0?o[0]||"true":n[0]||"false"),error:r.error});return m._zod.bag.truthy=o,m._zod.bag.falsy=n,m._zod.bag.case=r.case??"insensitive",m}function Lt(e,t,r,o={}){let n=k(o),i={check:"string_format",type:"string",format:t,fn:typeof r=="function"?r:s=>r.test(s),...n};return r instanceof RegExp&&(i.pattern=r),new e(i)}function Cr(e,...t){for(let r of t)for(let o of Reflect.ownKeys(r))Object.prototype.propertyIsEnumerable.call(r,o)&&ue(e,o,r[o]);return e}function ht(e){let t=e?.target??"draft-2020-12";return t==="draft-4"&&(t="draft-04"),t==="draft-7"&&(t="draft-07"),{processors:e.processors??{},metadataRegistry:e?.metadata??le,target:t,unrepresentable:e?.unrepresentable??"throw",override:e?.override??(()=>{}),io:e?.io??"output",counter:0,seen:new Map,sharedDefsExtractedFor:void 0,sharedEmitDoneFor:void 0,cycles:e?.cycles??"ref",reused:e?.reused??"inline",intersections:[],deferred:[],external:e?.external??void 0}}function oe(e,t,r,o,n){let i=typeof t.unrepresentable=="function"?t.unrepresentable({zodSchema:e,path:o.path,message:n}):t.unrepresentable;if(i==="any")return!1;if(i===void 0||i==="throw")throw new Error(n);return Object.assign(r,i),!0}function K(e,t,r={path:[],schemaPath:[]}){var o;let n=e._zod.def,i=t.seen.get(e);if(i)return i.count++,r.schemaPath.includes(e)&&(i.cycle=r.path),i.schema;let a={schema:{},count:1,cycle:void 0,path:r.path};t.seen.set(e,a),t.sharedDefsExtractedFor=void 0,t.sharedEmitDoneFor=void 0;let s=e._zod.toJSONSchema?.();if(s)a.schema=s;else{let d={...r,schemaPath:[...r.schemaPath,e],path:r.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,a.schema,d);else{let m=a.schema,f=t.processors[n.type];if(!f)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${n.type}`);f(e,t,m,d)}let p=e._zod.parent;p&&(a.ref||(a.ref=p),K(p,t,d),t.seen.get(p).isParent=!0)}let u=t.metadataRegistry.get(e);return u&&Cr(a.schema,u),t.io==="input"&&ve(e)&&(delete a.schema.examples,delete a.schema.default),t.io==="input"&&"_prefault"in a.schema&&((o=a.schema).default??(o.default=a.schema._prefault)),delete a.schema._prefault,t.seen.get(e).schema}function Cg(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}function vt(e,t){let r=e.seen.get(t);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");if(e.external&&e.sharedDefsExtractedFor===e.external)return;let o=new Map;for(let a of e.seen.entries()){let s=e.metadataRegistry.get(a[0])?.id;if(s){let u=o.get(s);if(u&&u!==a[0])throw new Error(`Duplicate schema id "${s}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);o.set(s,a[0])}}let n=a=>{let s=e.target==="draft-2020-12"?"$defs":"definitions";if(e.external){let p=e.external.registry.get(a[0])?.id,m=e.external.uri??(v=>v);if(p)return{ref:m(p)};let f=a[1].defId??a[1].schema.id??`schema${e.counter++}`;return a[1].defId=f,{defId:f,ref:`${m("__shared")}#/${s}/${Cg(f)}`}}let u="#",l=`${u}/${s}/`;if(a[1]===r&&!a[1].schema.id)return{ref:u};let d=a[1].schema.id??`__schema${e.counter++}`;return{defId:d,ref:l+Cg(d)}},i=a=>{if(a[1].schema.$ref)return;let s=a[1],{ref:u,defId:l}=n(a);s.def={...s.schema},l&&(s.defId=l);let d=s.schema;for(let p in d)delete d[p];d.$ref=u};if(e.cycles==="throw")for(let a of e.seen.entries()){let s=a[1];if(s.cycle)throw new Error(`Cycle detected: #/${s.cycle?.join("/")}/<root>
|
|
61
61
|
|
|
62
|
-
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let a of e.seen.entries()){let s=a[1];if(t===a[0]){i(a);continue}if(e.external){let l=e.external.registry.get(a[0])?.id;if(t!==a[0]&&l){i(a);continue}}if(e.metadataRegistry.get(a[0])?.id){i(a);continue}if(s.cycle){i(a);continue}s.count>1&&e.reused==="ref"&&i(a)}e.external&&(e.sharedDefsExtractedFor=e.external)}function Mg(e){let t=e.anyOf;if(!Array.isArray(t)||t.length===0||e.type!==void 0)return;let r=[];for(let o of t){if(!o||typeof o!="object")return;Mg(o);let n=Object.keys(o);if(n.length!==1||n[0]!=="type")return;let i=o.type;for(let a of Array.isArray(i)?i:[i]){if(typeof a!="string")return;r.includes(a)||r.push(a)}}delete e.anyOf,e.type=r.length===1?r[0]:r}var Lg=new Set(["type","properties","required","additionalProperties"]),Eg=["oneOf","anyOf"];function Rg(e){let t=e.additionalProperties;return t===void 0||t===!1||typeof t!="object"||t===null?null:Object.keys(t).length?t:null}function Al(e){let t=[];for(let i of e){if(typeof i!="object"||i.type!=="object")return null;for(let a in i)if(!Lg.has(a))return null;t.push(i)}let r={},o=new Set;for(let i of t){for(let a in i.properties){if(Object.prototype.hasOwnProperty.call(r,a))continue;let s=[];for(let l of t){let d=l.properties?.[a]??Rg(l);d!=null&&(s.some(p=>JSON.stringify(p)===JSON.stringify(d))||s.push(d))}let u=s.length===1?s[0]:Al(s)??{allOf:s};ue(r,a,u)}for(let a of i.required??[])o.add(a)}let n={type:"object",properties:r};if(o.size&&(n.required=[...o]),t.every(i=>i.additionalProperties===!1))n.additionalProperties=!1;else{let i=[];for(let a of t){let s=Rg(a);s&&!i.some(u=>JSON.stringify(u)===JSON.stringify(s))&&i.push(s)}i.length===1?n.additionalProperties=i[0]:i.length>1&&(n.additionalProperties={allOf:i})}return n}function mw(e){let t=e.allOf;if(!Array.isArray(t)||t.length<2)return;for(let n of Lg)if(n in e)return;let r=t.filter(n=>Eg.some(i=>Array.isArray(n[i]))),o=null;if(!r.length)o=Al(t);else{let n=r[0],i=Eg.find(u=>Array.isArray(n[u]));if(Object.keys(n).length!==1)return;let a=t.filter(u=>u!==n),s=n[i].map(u=>Al([...a,u]));if(s.some(u=>!u))return;o={[i]:s}}o&&(delete e.allOf,Cr(e,o))}function yt(e,t){let r=e.seen.get(t);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");let o=s=>{let u=e.seen.get(s);if(u.ref===null)return;let l=u.def??u.schema,d={...l},p=u.ref;if(u.ref=null,p){o(p);let f=e.seen.get(p),v=f.schema;if(v.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0")?(l.allOf=l.allOf??[],l.allOf.push(v)):Cr(l,v),Cr(l,d),s._zod.parent===p)for(let x in l)x==="$ref"||x==="allOf"||x in d||delete l[x];if(v.$ref&&f.def)for(let x in l)x==="$ref"||x==="allOf"||x in f.def&&JSON.stringify(l[x])===JSON.stringify(f.def[x])&&delete l[x]}let m=s._zod.parent;if(m&&m!==p){o(m);let f=e.seen.get(m);if(f?.schema.$ref&&(l.$ref=f.schema.$ref,f.def))for(let v in l)v==="$ref"||v==="allOf"||v in f.def&&JSON.stringify(l[v])===JSON.stringify(f.def[v])&&delete l[v]}e.override({zodSchema:s,jsonSchema:l,path:u.path??[]})};if(!e.external||e.sharedEmitDoneFor!==e.external){for(let s of[...e.seen.entries()].reverse())o(s[0]);if(e.target!=="openapi-3.0")for(let s of e.seen.entries())Mg(s[1].def??s[1].schema);for(let s of e.deferred)s();if(e.intersections.length){let s=new Map;for(let u of e.seen.values())for(let l of[u.schema,u.def]){let d=l?.allOf;if(!Array.isArray(d))continue;let p=s.get(d);p?p.push(l):s.set(d,[l])}for(let u of e.intersections)for(let l of s.get(u)??[])mw(l)}}let n={};if(e.target==="draft-2020-12"?n.$schema="https://json-schema.org/draft/2020-12/schema":e.target==="draft-07"?n.$schema="http://json-schema.org/draft-07/schema#":e.target==="draft-04"?n.$schema="http://json-schema.org/draft-04/schema#":e.target,e.external?.uri){let s=e.external.registry.get(t)?.id;if(!s)throw new Error("Schema is missing an `id` property");n.$id=e.external.uri(s)}Cr(n,r.defId?r.schema:r.def??r.schema);let i=e.metadataRegistry.get(t)?.id;i!==void 0&&n.id===i&&delete n.id;let a=e.external?.defs??{};if(!e.external||e.sharedEmitDoneFor!==e.external)for(let s of e.seen.entries()){let u=s[1];u.def&&u.defId&&(u.def.id===u.defId&&delete u.def.id,ue(a,u.defId,u.def))}e.external&&(e.sharedEmitDoneFor=e.external),e.external||Object.keys(a).length>0&&(e.target==="draft-2020-12"?n.$defs=a:n.definitions=a);try{let s=JSON.parse(JSON.stringify(n));return Object.defineProperty(s,"~standard",{value:{...t["~standard"],jsonSchema:{input:Tn(t,"input",e.processors),output:Tn(t,"output",e.processors)}},enumerable:!1,writable:!1}),s}catch{throw new Error("Error converting schema to JSON.")}}function ve(e,t){let r=t??{seen:new Set};if(r.seen.has(e))return!1;r.seen.add(e);let o=e._zod.def;if(o.type==="transform")return!0;if(o.type==="array")return ve(o.element,r);if(o.type==="set")return ve(o.valueType,r);if(o.type==="lazy")return ve(o.getter(),r);if(o.type==="promise"||o.type==="optional"||o.type==="nonoptional"||o.type==="nullable"||o.type==="readonly"||o.type==="default"||o.type==="prefault"||o.type==="catch")return ve(o.innerType,r);if(o.type==="intersection")return ve(o.left,r)||ve(o.right,r);if(o.type==="record"||o.type==="map")return ve(o.keyType,r)||ve(o.valueType,r);if(o.type==="pipe")return e._zod.traits.has("$ZodCodec")?!0:ve(o.in,r)||ve(o.out,r);if(o.type==="object"){for(let n in o.shape)if(ve(o.shape[n],r))return!0;return!1}if(o.type==="union"){for(let n of o.options)if(ve(n,r))return!0;return!1}if(o.type==="tuple"){for(let n of o.items)if(ve(n,r))return!0;return!!(o.rest&&ve(o.rest,r))}return!1}var Ol=(e,t={})=>r=>{let o=ht({...r,processors:t});return K(e,o),vt(o,e),yt(o,e)},Tn=(e,t,r={})=>o=>{let{libraryOptions:n,target:i}=o??{},a=ht({...n??{},target:i,io:t,processors:r});return K(e,a),vt(a,e),yt(a,e)};var Nn=(e,t,r)=>{(e[t]===void 0||r>e[t])&&(e[t]=r)},Dn=(e,t,r)=>{(e[t]===void 0||r<e[t])&&(e[t]=r)},Zg=(e,t)=>{Nn(e,"minimum",t),Dn(e,"maximum",t)},Jg=(e,t)=>{e.multipleOf??(e.multipleOf=[]),e.multipleOf.includes(t)||e.multipleOf.push(t)},Bg=(e,t)=>{e.patterns??(e.patterns=new Set),e.patterns.add(t)},Wg=(e,t)=>{e.mime=e.mime?e.mime.filter(r=>t.includes(r)):[...t]},Gg=(e,t)=>{e.format=t,t.includes("int")&&(e.isInt=!0)},Fg=(e,t)=>Nn(e,"minimum",t.minimum),Vg=(e,t)=>Dn(e,"maximum",t.maximum),Kg=e=>(t,r)=>{Gg(t,r.format);let[o,n]=e[r.format];Nn(t,"minimum",o),Dn(t,"maximum",n)},gw={greater_than:(e,t)=>Nn(e,t.inclusive?"minimum":"exclusiveMinimum",t.value),less_than:(e,t)=>Dn(e,t.inclusive?"maximum":"exclusiveMaximum",t.value),multiple_of:(e,t)=>Jg(e,t.value),number_format:Kg(rr),bigint_format:Kg(ir),min_length:Fg,max_length:Vg,length_equals:(e,t)=>Zg(e,t.length),min_size:Fg,max_size:Vg,size_equals:(e,t)=>Zg(e,t.size),string_format:(e,t)=>{Gg(e,t.format),t.pattern&&Bg(e,t.pattern),(t.format==="base64"||t.format==="base64url")&&(e.contentEncoding=t.format),(t.local||t.precision===-1)&&(e.laxFormat=!0)},mime_type:(e,t)=>Wg(e,t.mime)};function ae(e){let t={},r=e._zod.def,o=e._zod.traits.has("$ZodCheck")?[e,...r.checks??[]]:r.checks??[];for(let i of o)gw[i._zod.def.check]?.(t,i._zod.def);let n=e._zod.bag;n.minimum!==void 0&&Nn(t,"minimum",n.minimum),n.exclusiveMinimum!==void 0&&Nn(t,"exclusiveMinimum",n.exclusiveMinimum),n.maximum!==void 0&&Dn(t,"maximum",n.maximum),n.exclusiveMaximum!==void 0&&Dn(t,"exclusiveMaximum",n.exclusiveMaximum),n.multipleOf!==void 0&&Jg(t,n.multipleOf),n.format!==void 0&&(t.format??(t.format=n.format),n.format.includes("int")&&(t.isInt=!0)),n.mime&&Wg(t,n.mime);for(let i of n.patterns??[])Bg(t,i);return t}var hw={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},vw=new Map([[Vi,Es],[_r,Rs]]),qg=e=>vw.get(e)??e,Dl=(e,t,r,o)=>{let n=r;n.type="string";let{minimum:i,maximum:a,format:s,patterns:u,contentEncoding:l,laxFormat:d}=ae(e);if(typeof i=="number"&&(n.minLength=i),typeof a=="number"&&(n.maxLength=a),s&&(n.format=hw[s]??s,n.format===""&&delete n.format,(s==="time"||d)&&delete n.format),l&&(n.contentEncoding=l),u&&u.size>0){let p=[...u].map(qg);p.length===1?n.pattern=p[0].source:p.length>1&&(n.allOf=[...p.map(m=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:m.source}))])}},Ul=(e,t,r,o)=>{let n=r,{minimum:i,maximum:a,multipleOf:s,exclusiveMaximum:u,exclusiveMinimum:l,isInt:d}=ae(e);n.type=d?"integer":"number";let p=typeof l=="number"&&l>=(i??Number.NEGATIVE_INFINITY),m=typeof u=="number"&&u<=(a??Number.POSITIVE_INFINITY),f=t.target==="draft-04"||t.target==="openapi-3.0";if(p?f?(n.minimum=l,n.exclusiveMinimum=!0):n.exclusiveMinimum=l:typeof i=="number"&&(n.minimum=i),m?f?(n.maximum=u,n.exclusiveMaximum=!0):n.exclusiveMaximum=u:typeof a=="number"&&(n.maximum=a),s){let v=new Set;for(let j of s)Number.isFinite(j)&&j!==0?v.add(Math.abs(j)):oe(e,t,n,o,`A multipleOf divisor of ${j} cannot be represented in JSON Schema`);let[y,...x]=v;y!==void 0&&(n.multipleOf=y),x.length&&(n.allOf=[...n.allOf??[],...x.map(j=>({multipleOf:j}))])}},Cl=(e,t,r,o)=>{r.type="boolean"},El=(e,t,r,o)=>{oe(e,t,r,o,"BigInt cannot be represented in JSON Schema")},Rl=(e,t,r,o)=>{oe(e,t,r,o,"Symbols cannot be represented in JSON Schema")},Ml=(e,t,r,o)=>{t.target==="openapi-3.0"?(r.type="string",r.nullable=!0,r.enum=[null]):r.type="null"},Ll=(e,t,r,o)=>{oe(e,t,r,o,"Undefined cannot be represented in JSON Schema")},Zl=(e,t,r,o)=>{oe(e,t,r,o,"Void cannot be represented in JSON Schema")},Fl=(e,t,r,o)=>{r.not={}},Vl=(e,t,r,o)=>{},Kl=(e,t,r,o)=>{},Jl=(e,t,r,o)=>{oe(e,t,r,o,"Date cannot be represented in JSON Schema")},Bl=(e,t,r,o)=>{let n=e._zod.def,i=rn(n.entries);if(i.length===0){r.not={};return}i.every(a=>typeof a=="number")&&(r.type="number"),i.every(a=>typeof a=="string")&&(r.type="string"),r.enum=i},Wl=(e,t,r,o)=>{let n=e._zod.def;if(n.values.length===0){r.not={};return}let i=[];for(let a of n.values)if(a===void 0){if(oe(e,t,r,o,"Literal `undefined` cannot be represented in JSON Schema"))return}else if(typeof a=="bigint"){if(oe(e,t,r,o,"BigInt literals cannot be represented in JSON Schema"))return;i.push(Number(a))}else i.push(a);if(i.length!==0)if(i.length===1){let a=i[0];r.type=a===null?"null":typeof a,t.target==="draft-04"||t.target==="openapi-3.0"?r.enum=[a]:r.const=a}else i.every(a=>typeof a=="number")&&(r.type="number"),i.every(a=>typeof a=="string")&&(r.type="string"),i.every(a=>typeof a=="boolean")&&(r.type="boolean"),i.every(a=>a===null)&&(r.type="null"),r.enum=i},Gl=(e,t,r,o)=>{oe(e,t,r,o,"NaN cannot be represented in JSON Schema")},ql=(e,t,r,o)=>{let n=r,i=e._zod.pattern;if(!i)throw new Error("Pattern not found in template literal");n.type="string",n.pattern=i.source},Hl=(e,t,r,o)=>{let n=r;n.type="string",n.format="binary",n.contentEncoding="binary";let{minimum:i,maximum:a,mime:s}=ae(e);i!==void 0&&(n.minLength=i),a!==void 0&&(n.maxLength=a),s&&(s.length===0?n.not={}:s.length===1?n.contentMediaType=s[0]:n.anyOf=s.map(u=>({contentMediaType:u})))},Xl=(e,t,r,o)=>{r.type="boolean"},Yl=(e,t,r,o)=>{oe(e,t,r,o,"Custom types cannot be represented in JSON Schema")},Ql=(e,t,r,o)=>{oe(e,t,r,o,"Function types cannot be represented in JSON Schema")},ed=(e,t,r,o)=>{oe(e,t,r,o,"Transforms cannot be represented in JSON Schema")},td=(e,t,r,o)=>{oe(e,t,r,o,"Map cannot be represented in JSON Schema")},nd=(e,t,r,o)=>{oe(e,t,r,o,"Set cannot be represented in JSON Schema")},rd=(e,t,r,o)=>{let n=r,i=e._zod.def,{minimum:a,maximum:s}=ae(e);typeof a=="number"&&(n.minItems=a),typeof s=="number"&&(n.maxItems=s),n.type="array",n.items=K(i.element,t,{...o,path:[...o.path,"items"]})};function Er(e){let t=e._zod.def;return t.type==="pipe"&&t.in._zod.traits.has("$ZodTransform")?Er(t.out):t.type==="catch"?Er(t.innerType):e._zod.optin}var id=(e,t,r,o)=>{let n=r,i=e._zod.def,a=i.shape;if(Object.getOwnPropertySymbols(a).length&&oe(e,t,n,o,"Symbol keys cannot be represented in JSON Schema"))return;n.type="object",n.properties={};for(let l in a)ue(n.properties,l,K(a[l],t,{...o,path:[...o.path,"properties",l]}));let u=[];for(let l of Object.keys(a)){let d=i.shape[l];(t.io==="input"?Er(d)===void 0:d._zod.optout===void 0)&&u.push(l)}u.length>0&&(n.required=u),i.catchall?._zod.def.type==="never"?n.additionalProperties=!1:i.catchall?i.catchall&&(n.additionalProperties=K(i.catchall,t,{...o,path:[...o.path,"additionalProperties"]})):t.io==="output"&&(n.additionalProperties=!1)},Zo=(e,t,r,o)=>{let n=e._zod.def,i=n.inclusive===!1,a=n.options.map((s,u)=>K(s,t,{...o,path:[...o.path,i?"oneOf":"anyOf",u]}));i?r.oneOf=a:r.anyOf=a},od=(e,t,r,o)=>{let n=e._zod.def,i=K(n.left,t,{...o,path:[...o.path,"allOf",0]}),a=K(n.right,t,{...o,path:[...o.path,"allOf",1]}),s=l=>"allOf"in l&&Object.keys(l).length===1,u=[...s(i)?i.allOf:[i],...s(a)?a.allOf:[a]];r.allOf=u,t.intersections.push(u)},ad=(e,t,r,o)=>{let n=r,i=e._zod.def;n.type="array";let a=t.target==="draft-2020-12"?"prefixItems":"items",s=t.target==="draft-2020-12"||t.target==="openapi-3.0"?"items":"additionalItems",u=i.items.map((y,x)=>K(y,t,{...o,path:[...o.path,a,x]})),l=i.rest?K(i.rest,t,{...o,path:[...o.path,s,...t.target==="openapi-3.0"?[i.items.length]:[]]}):null,d=i.items.length;for(;d>0;){let y=i.items[d-1];if(!(t.io==="input"?Er(y)!==void 0:y._zod.optout==="optional"))break;d--}let p=i.items.length,m=!i.rest;t.target==="draft-2020-12"?(n.prefixItems=u,m?n.items=!1:l&&(n.items=l),d>0&&(n.minItems=d),m&&(n.maxItems=p)):t.target==="openapi-3.0"?(n.items={anyOf:u},l&&n.items.anyOf.push(l),d>0&&(n.minItems=d),m&&(n.maxItems=p)):(n.items=u,m?n.additionalItems=!1:l&&(n.additionalItems=l),d>0&&(n.minItems=d),m&&(n.maxItems=p));let{minimum:f,maximum:v}=ae(e);typeof f=="number"&&(n.minItems=f),typeof v=="number"&&(n.maxItems=v)};function Tl(e,t,r){if(t.$ref){if(r.has(t))return t;r.add(t);let v=e.get(t)?.def;if(!v)return t;let y=Tl(e,v,r);return y===v?t:y}for(let v of["anyOf","oneOf"]){let y=t[v];if(!Array.isArray(y))continue;let x=y.map(j=>Tl(e,j,r));x.some((j,P)=>j!==y[P])&&(t={...t,[v]:x})}let o=Array.isArray(t.type)?t.type:[t.type],n=!o.includes("string")&&o.some(v=>v==="number"||v==="integer"),i=t.enum??(t.const!==void 0?[t.const]:void 0);if(!n&&!i?.some(v=>typeof v=="number"))return t;let{minimum:a,maximum:s,exclusiveMinimum:u,exclusiveMaximum:l,multipleOf:d,format:p,id:m,...f}=t;return f.enum?f.enum=f.enum.map(v=>typeof v=="number"?String(v):v):typeof f.const=="number"&&(f.const=String(f.const)),n&&(f.type="string",i||(f.pattern=(o.includes("number")?tt:mr).source)),f}var Nl=new WeakMap;function yw(e){let t=new Map;for(let o of e.seen.values())o.def&&!t.has(o.schema)&&t.set(o.schema,o);let r=new Map;for(let o of Nl.get(e)??[]){let n=e.seen.get(o),i=(n?.def??n?.schema)?.propertyNames;if(!i||i===!0||r.has(i))continue;let a=Tl(t,i,new Set);a!==i&&r.set(i,a)}if(r.size)for(let o of e.seen.values())for(let n of[o.schema,o.def]){let i=n&&r.get(n.propertyNames);i&&(n.propertyNames=i)}}var sd=(e,t,r,o)=>{let n=r,i=e._zod.def;n.type="object";let a=i.keyType,s=ae(a).patterns;if(i.mode==="loose"&&s&&s.size>0){let d=K(i.valueType,t,{...o,path:[...o.path,"patternProperties","*"]});n.patternProperties={};for(let p of s)ue(n.patternProperties,qg(p).source,d)}else{if(t.target==="draft-07"||t.target==="draft-2020-12"){n.propertyNames=K(i.keyType,t,{...o,path:[...o.path,"propertyNames"]});let d=Nl.get(t);d||(d=[],Nl.set(t,d),t.deferred.push(()=>yw(t))),d.push(e)}n.additionalProperties=K(i.valueType,t,{...o,path:[...o.path,"additionalProperties"]})}let u=a._zod.values,l=t.io==="input"&&Er(i.valueType)!==void 0;if(u&&!i.partial&&!l){let d=[...u].filter(p=>typeof p=="string"||typeof p=="number");d.length>0&&(n.required=d.map(String))}},cd=(e,t,r,o)=>{let n=e._zod.def,i=K(n.innerType,t,o),a=t.seen.get(e);t.target==="openapi-3.0"?(a.ref=n.innerType,r.nullable=!0):r.anyOf=[i,{type:"null"}]},ud=(e,t,r,o)=>{let n=e._zod.def;K(n.innerType,t,o);let i=t.seen.get(e);i.ref=n.innerType},ld=Symbol();function Hg(e,t,r,o,n){let i=!1,a=JSON.stringify(e,(s,u)=>typeof u!="bigint"?u:(i=!0,null));return i?(oe(t,r,o,n,"BigInt defaults cannot be represented in JSON Schema"),ld):JSON.parse(a)}var dd=(e,t,r,o)=>{let n=e._zod.def;K(n.innerType,t,o);let i=t.seen.get(e);i.ref=n.innerType;let a=Hg(n.defaultValue,e,t,r,o);a!==ld&&(r.default=a)},pd=(e,t,r,o)=>{let n=e._zod.def;K(n.innerType,t,o);let i=t.seen.get(e);if(i.ref=n.innerType,t.io!=="input")return;let a=Hg(n.defaultValue,e,t,r,o);a!==ld&&(r._prefault=a)},fd=(e,t,r,o)=>{let n=e._zod.def;K(n.innerType,t,o);let i=t.seen.get(e);i.ref=n.innerType;let a;try{a=n.catchValue(void 0)}catch{oe(e,t,r,o,"Dynamic catch values are not supported in JSON Schema");return}r.default=a},md=(e,t,r,o)=>{let n=e._zod.def,i=n.in._zod.traits.has("$ZodTransform"),a=t.io==="input"?i?n.out:n.in:n.out;K(a,t,o);let s=t.seen.get(e);s.ref=a},gd=(e,t,r,o)=>{let n=e._zod.def;K(n.innerType,t,o);let i=t.seen.get(e);i.ref=n.innerType,r.readOnly=!0},hd=(e,t,r,o)=>{let n=e._zod.def;K(n.innerType,t,o);let i=t.seen.get(e);i.ref=n.innerType},Fo=(e,t,r,o)=>{let n=e._zod.def;K(n.innerType,t,o);let i=t.seen.get(e);i.ref=n.innerType},vd=(e,t,r,o)=>{let n=e._zod.innerType;K(n,t,o);let i=t.seen.get(e);i.ref=n},Lo={string:Dl,number:Ul,boolean:Cl,bigint:El,symbol:Rl,null:Ml,undefined:Ll,void:Zl,never:Fl,any:Vl,unknown:Kl,date:Jl,enum:Bl,literal:Wl,nan:Gl,template_literal:ql,file:Hl,success:Xl,custom:Yl,function:Ql,transform:ed,map:td,set:nd,array:rd,object:id,union:Zo,intersection:od,tuple:ad,record:sd,nullable:cd,nonoptional:ud,default:dd,prefault:pd,catch:fd,pipe:md,readonly:gd,promise:hd,optional:Fo,lazy:vd};function Vo(e,t){if("_idmap"in e){let o=e,n=ht({...t,processors:Lo}),i={};for(let u of o._idmap.entries()){let[l,d]=u;K(d,n)}let a={},s={registry:o,uri:t?.uri,defs:i};n.external=s;for(let u of o._idmap.entries()){let[l,d]=u;vt(n,d),ue(a,l,yt(n,d))}if(Object.keys(i).length>0){let u=n.target==="draft-2020-12"?"$defs":"definitions";a.__shared={[u]:i}}return{schemas:a}}let r=ht({...t,processors:Lo});return K(e,r),vt(r,e),yt(r,e)}var Ko=class{get metadataRegistry(){return this.ctx.metadataRegistry}get target(){return this.ctx.target}get unrepresentable(){return this.ctx.unrepresentable}get override(){return this.ctx.override}get io(){return this.ctx.io}get counter(){return this.ctx.counter}set counter(t){this.ctx.counter=t}get seen(){return this.ctx.seen}constructor(t){let r=t?.target??"draft-2020-12";r==="draft-4"&&(r="draft-04"),r==="draft-7"&&(r="draft-07"),this.ctx=ht({processors:Lo,target:r,...t?.metadata&&{metadata:t.metadata},...t?.unrepresentable&&{unrepresentable:t.unrepresentable},...t?.override&&{override:t.override},...t?.io&&{io:t.io}})}process(t,r={path:[],schemaPath:[]}){return K(t,this.ctx,r)}emit(t,r){r&&(r.cycles&&(this.ctx.cycles=r.cycles),r.reused&&(this.ctx.reused=r.reused),r.external&&(this.ctx.external=r.external)),this.ctx.sharedDefsExtractedFor=void 0,this.ctx.sharedEmitDoneFor=void 0,vt(this.ctx,t);let o=yt(this.ctx,t),{"~standard":n,...i}=o;return i}};var Xg={};var Fn={};Ye(Fn,{ZodAny:()=>Md,ZodArray:()=>Vd,ZodBase64:()=>ua,ZodBase64URL:()=>la,ZodBigInt:()=>Ln,ZodBigIntFormat:()=>fa,ZodBoolean:()=>Mn,ZodCIDRv4:()=>sa,ZodCIDRv6:()=>ca,ZodCUID:()=>ea,ZodCUID2:()=>ta,ZodCatch:()=>lp,ZodCodec:()=>Wr,ZodCreditCard:()=>Od,ZodCustom:()=>Gr,ZodCustomStringFormat:()=>Kt,ZodDate:()=>Zr,ZodDefault:()=>ip,ZodDiscriminatedUnion:()=>Jd,ZodE164:()=>da,ZodEmail:()=>Ho,ZodEmoji:()=>Yo,ZodEnum:()=>Cn,ZodExactOptional:()=>va,ZodFile:()=>ep,ZodFunction:()=>bp,ZodGUID:()=>Xo,ZodIBAN:()=>Td,ZodIPv4:()=>oa,ZodIPv6:()=>aa,ZodISODate:()=>bt,ZodISODateTime:()=>$t,ZodISODuration:()=>xt,ZodISOTime:()=>_t,ZodInstanceOf:()=>kp,ZodIntersection:()=>Bd,ZodJWT:()=>pa,ZodKSUID:()=>ia,ZodLazy:()=>vp,ZodLiteral:()=>Qd,ZodMAC:()=>Ad,ZodMap:()=>Xd,ZodNaN:()=>pp,ZodNanoID:()=>Qo,ZodNever:()=>Zd,ZodNonOptional:()=>ya,ZodNull:()=>Ed,ZodNullable:()=>rp,ZodNumber:()=>Rn,ZodNumberFormat:()=>Jt,ZodObject:()=>Vr,ZodOptional:()=>Jr,ZodPipe:()=>Br,ZodPrefault:()=>ap,ZodPreprocess:()=>fp,ZodPromise:()=>$p,ZodReadonly:()=>mp,ZodRecord:()=>Un,ZodSet:()=>Yd,ZodString:()=>En,ZodStringFormat:()=>W,ZodSuccess:()=>up,ZodSymbol:()=>Ud,ZodTemplateLiteral:()=>hp,ZodTransform:()=>tp,ZodTuple:()=>Gd,ZodType:()=>C,ZodULID:()=>na,ZodURL:()=>Lr,ZodUUID:()=>Ke,ZodUndefined:()=>Cd,ZodUnion:()=>Kr,ZodUnknown:()=>Ld,ZodVoid:()=>Fd,ZodXID:()=>ra,ZodXor:()=>Kd,_ZodString:()=>qo,_default:()=>op,_function:()=>uv,any:()=>Lh,array:()=>Fr,base64:()=>bh,base64url:()=>_h,bigint:()=>Uh,boolean:()=>Dd,catch:()=>dp,check:()=>lv,cidrv4:()=>yh,cidrv6:()=>$h,codec:()=>ov,creditCard:()=>kh,cuid:()=>lh,cuid2:()=>dh,currencyCode:()=>jh,custom:()=>dv,date:()=>Fh,describe:()=>pv,discriminatedUnion:()=>Gh,e164:()=>xh,email:()=>eh,emoji:()=>ch,enum:()=>ga,exactOptional:()=>np,file:()=>tv,float32:()=>Oh,float64:()=>Th,function:()=>uv,guid:()=>th,hash:()=>Ah,hex:()=>Ph,hostname:()=>zh,httpUrl:()=>sh,iban:()=>wh,instanceof:()=>mv,int:()=>Wo,int32:()=>Nh,int64:()=>Ch,intersection:()=>Wd,invertCodec:()=>av,ipv4:()=>gh,ipv6:()=>vh,json:()=>hv,jwt:()=>Sh,keyof:()=>Vh,ksuid:()=>mh,lazy:()=>yp,literal:()=>ev,looseObject:()=>Bh,looseRecord:()=>Hh,mac:()=>hh,map:()=>Xh,meta:()=>fv,nan:()=>iv,nanoid:()=>uh,nativeEnum:()=>Qh,never:()=>ma,nonoptional:()=>cp,null:()=>Rd,nullable:()=>Mr,nullish:()=>nv,number:()=>Nd,object:()=>Kh,optional:()=>Ft,partialRecord:()=>qh,pipe:()=>Go,prefault:()=>sp,preprocess:()=>vv,promise:()=>cv,readonly:()=>gp,record:()=>Hd,refine:()=>_p,set:()=>Yh,strictObject:()=>Jh,string:()=>Rr,stringFormat:()=>Ih,stringbool:()=>gv,success:()=>rv,superRefine:()=>xp,symbol:()=>Rh,templateLiteral:()=>sv,transform:()=>ha,tuple:()=>qd,uint32:()=>Dh,uint64:()=>Eh,ulid:()=>ph,undefined:()=>Mh,union:()=>Zn,unknown:()=>Zt,url:()=>ah,uuid:()=>nh,uuidv4:()=>rh,uuidv6:()=>ih,uuidv7:()=>oh,void:()=>Zh,xid:()=>fh,xor:()=>Wh});var Jo={};Ye(Jo,{endsWith:()=>wn,gt:()=>Fe,gte:()=>Oe,includes:()=>xn,length:()=>Mt,lowercase:()=>bn,lt:()=>Ze,lte:()=>Ae,maxLength:()=>Rt,maxSize:()=>gt,mime:()=>In,minLength:()=>nt,minSize:()=>Ve,multipleOf:()=>mt,negative:()=>Co,nonnegative:()=>Ro,nonpositive:()=>Eo,normalize:()=>zn,overwrite:()=>Me,positive:()=>Uo,properties:()=>Sn,property:()=>Mo,regex:()=>$n,size:()=>Et,slugify:()=>On,startsWith:()=>kn,toLowerCase:()=>jn,toUpperCase:()=>An,trim:()=>Pn,uppercase:()=>_n});var Yg=new WeakSet([Object.prototype,Error.prototype]);function Bo(e,t,r){Object.defineProperty(e,t,{configurable:!0,enumerable:!1,get(){let o=r(this);return Object.defineProperty(this,t,{value:o,configurable:!0,writable:!0}),o},set(o){Object.defineProperty(this,t,{value:o,configurable:!0,writable:!0})}})}var Qg=(e,t)=>{vs.init(e,t),e.name="ZodError";let r=Object.getPrototypeOf(e);Yg.has(r)||(Yg.add(r),Bo(r,"format",o=>n=>lr(o,n)),Bo(r,"flatten",o=>n=>ur(o,n)),Bo(r,"addIssue",o=>n=>{o.issues.push(n),o.message=JSON.stringify(o.issues,on,2)}),Bo(r,"addIssues",o=>n=>{o.issues.push(...n),o.message=JSON.stringify(o.issues,on,2)}),Object.defineProperty(r,"isEmpty",{configurable:!0,enumerable:!1,get(){return this.issues.length===0}}))},bw=g("ZodError",Qg),Se=g("ZodError",Qg,void 0,{Parent:Error});var yd=ln(Se),$d=dn(Se),bd=pn(Se),_d=fn(Se),xd=bi(Se),kd=_i(Se),wd=xi(Se),Sd=ki(Se),Id=wi(Se),zd=Si(Se),Pd=Ii(Se),jd=zi(Se);function xw(){se.localeError||te(oo())}function Vt(){se.memoizer||te({memoizer:Pr()})}var C=g("ZodType",(e,t)=>(xw(),D.init(e,t),e.def=t,e.type=t.type,e),{check(...e){let t=this.def;return this.clone($.mergeDefs(t,{checks:[...t.checks??[],...e.map(r=>typeof r=="function"?{_zod:{check:r,def:{check:"custom"},onattach:[]}}:r)]}),{parent:!0})},with(...e){return this.check(...e)},clone(e,t){return F(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},refine(e,t){return this.check(_p(e,t))},superRefine(e,t){return this.check(xp(e,t))},overwrite(e){return this.check(Me(e))},optional(){return Ft(this)},exactOptional(){return np(this)},nullable(){return Mr(this)},nullish(){return Ft(Mr(this))},nonoptional(e){return cp(this,e)},array(){return Fr(this)},or(e){return Zn([this,e])},and(e){return Wd(this,e)},transform(e){return Go(this,ha(e))},default(e){return op(this,e)},prefault(e){return sp(this,e)},catch(e){return dp(this,e)},pipe(e){return Go(this,e)},readonly(){return gp(this)},describe(e){let t=this.clone();return le.add(t,{description:e}),t},meta(...e){if(e.length===0)return le.get(this);let t=this.clone();return le.add(t,e[0]),t},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(e,...t){return t.length===0?e(this):e(this,...t)},get"~standard"(){return $.hide(this,"~standard",{...Ri(this),jsonSchema:{input:Tn(this,"input"),output:Tn(this,"output")}})},set"~standard"(e){$.own(this,"~standard",e)},parse:function e(t,r){return yd(this,t,r,{callee:e})},parseAsync:async function e(t,r){return await $d(this,t,r,{callee:e})},safeParse(e,t){return bd(this,e,t)},async safeParseAsync(e,t){return _d(this,e,t)},get spa(){return this?.safeParseAsync},set spa(e){$.own(this,"spa",e)},validate(e,t){return dr(this,e,t)},validateAsync(e,t){return pr(this,e,t)},encode:function e(t,r){return xd(this,t,r,{callee:e})},decode:function e(t,r){return kd(this,t,r,{callee:e})},encodeAsync:async function e(t,r){return await wd(this,t,r,{callee:e})},decodeAsync:async function e(t,r){return await Sd(this,t,r,{callee:e})},safeEncode(e,t){return Id(this,e,t)},safeDecode(e,t){return zd(this,e,t)},async safeEncodeAsync(e,t){return Pd(this,e,t)},async safeDecodeAsync(e,t){return jd(this,e,t)},toJSONSchema(e){return Ol(this,{})(e)},get description(){return le.get(this)?.description},get _def(){return this._zod.def}}),qo=g("_ZodString",(e,t)=>{Nt.init(e,t),C.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Dl(e,r,o,n)},$.derived({format:e=>ae(e).format??null,minLength:e=>ae(e).minimum??null,maxLength:e=>ae(e).maximum??null},{regex(...e){return this.check($n(...e))},includes(...e){return this.check(xn(...e))},startsWith(...e){return this.check(kn(...e))},endsWith(...e){return this.check(wn(...e))},min(...e){return this.check(nt(...e))},max(...e){return this.check(Rt(...e))},length(...e){return this.check(Mt(...e))},nonempty(...e){return this.check(nt(1,...e))},lowercase(e){return this.check(bn(e))},uppercase(e){return this.check(_n(e))},trim(){return this.check(Pn())},normalize(...e){return this.check(zn(...e))},toLowerCase(){return this.check(jn())},toUpperCase(){return this.check(An())},slugify(){return this.check(On())}})),En=g("ZodString",(e,t)=>{Nt.init(e,t),qo.init(e,t)},{email(e){return this.check(mo(Ho,e))},url(e){return this.check(Or(Lr,e))},jwt(e){return this.check(Do(pa,e))},emoji(e){return this.check(bo(Yo,e))},guid(e){return this.check(go(Xo,e))},uuid(e){return this.check(ho(Ke,e))},uuidv4(e){return this.check(vo(Ke,e))},uuidv6(e){return this.check(yo(Ke,e))},uuidv7(e){return this.check($o(Ke,e))},nanoid(e){return this.check(_o(Qo,e))},cuid(e){return this.check(xo(ea,e))},cuid2(e){return this.check(ko(ta,e))},ulid(e){return this.check(wo(na,e))},base64(e){return this.check(Oo(ua,e))},base64url(e){return this.check(To(la,e))},xid(e){return this.check(So(ra,e))},ksuid(e){return this.check(Io(ia,e))},ipv4(e){return this.check(zo(oa,e))},ipv6(e){return this.check(Po(aa,e))},cidrv4(e){return this.check(jo(sa,e))},cidrv6(e){return this.check(Ao(ca,e))},e164(e){return this.check(No(da,e))},datetime(e){return this.check(Tr($t,e))},date(e){return this.check(Nr(bt,e))},time(e){return this.check(Dr(_t,e))},duration(e){return this.check(Ur(xt,e))}});function Rr(e){return Wu(En,e)}var W=g("ZodStringFormat",(e,t)=>{V.init(e,t),qo.init(e,t)}),$t=g("ZodISODateTime",(e,t)=>{Ec.init(e,t),W.init(e,t)}),bt=g("ZodISODate",(e,t)=>{Rc.init(e,t),W.init(e,t)}),_t=g("ZodISOTime",(e,t)=>{Mc.init(e,t),W.init(e,t)}),xt=g("ZodISODuration",(e,t)=>{Lc.init(e,t),W.init(e,t)}),Ho=g("ZodEmail",(e,t)=>{Ic.init(e,t),W.init(e,t)});function eh(e){return mo(Ho,e)}var Xo=g("ZodGUID",(e,t)=>{wc.init(e,t),W.init(e,t)});function th(e){return go(Xo,e)}var Ke=g("ZodUUID",(e,t)=>{Sc.init(e,t),W.init(e,t)});function nh(e){return ho(Ke,e)}function rh(e){return vo(Ke,e)}function ih(e){return yo(Ke,e)}function oh(e){return $o(Ke,e)}var Lr=g("ZodURL",(e,t)=>{jc.init(e,t),W.init(e,t)});function ah(e){return Or(Lr,e)}function sh(e){return Or(Lr,{protocol:fr,hostname:Ls,...$.normalizeParams(e)})}var Yo=g("ZodEmoji",(e,t)=>{Ac.init(e,t),W.init(e,t)});function ch(e){return bo(Yo,e)}var Qo=g("ZodNanoID",(e,t)=>{Oc.init(e,t),W.init(e,t)});function uh(e){return _o(Qo,e)}var ea=g("ZodCUID",(e,t)=>{Tc.init(e,t),W.init(e,t)});function lh(e){return xo(ea,e)}var ta=g("ZodCUID2",(e,t)=>{Nc.init(e,t),W.init(e,t)});function dh(e){return ko(ta,e)}var na=g("ZodULID",(e,t)=>{Dc.init(e,t),W.init(e,t)});function ph(e){return wo(na,e)}var ra=g("ZodXID",(e,t)=>{Uc.init(e,t),W.init(e,t)});function fh(e){return So(ra,e)}var ia=g("ZodKSUID",(e,t)=>{Cc.init(e,t),W.init(e,t)});function mh(e){return Io(ia,e)}var oa=g("ZodIPv4",(e,t)=>{Zc.init(e,t),W.init(e,t)});function gh(e){return zo(oa,e)}var Ad=g("ZodMAC",(e,t)=>{Vc.init(e,t),W.init(e,t)});function hh(e){return qu(Ad,e)}var aa=g("ZodIPv6",(e,t)=>{Fc.init(e,t),W.init(e,t)});function vh(e){return Po(aa,e)}var sa=g("ZodCIDRv4",(e,t)=>{Kc.init(e,t),W.init(e,t)});function yh(e){return jo(sa,e)}var ca=g("ZodCIDRv6",(e,t)=>{Jc.init(e,t),W.init(e,t)});function $h(e){return Ao(ca,e)}var ua=g("ZodBase64",(e,t)=>{Bc.init(e,t),W.init(e,t)});function bh(e){return Oo(ua,e)}var la=g("ZodBase64URL",(e,t)=>{Wc.init(e,t),W.init(e,t)});function _h(e){return To(la,e)}var da=g("ZodE164",(e,t)=>{Gc.init(e,t),W.init(e,t)});function xh(e){return No(da,e)}var Od=g("ZodCreditCard",(e,t)=>{qc.init(e,t),W.init(e,t)});function kh(e){return Hu(Od,e)}var Td=g("ZodIBAN",(e,t)=>{Hc.init(e,t),W.init(e,t)});function wh(e){return Xu(Td,e)}var pa=g("ZodJWT",(e,t)=>{Xc.init(e,t),W.init(e,t)});function Sh(e){return Do(pa,e)}var Kt=g("ZodCustomStringFormat",(e,t)=>{Yc.init(e,t),W.init(e,t)});function Ih(e,t,r={}){return Lt(Kt,e,t,r)}function zh(e){return Lt(Kt,"hostname",Ms,e)}function Ph(e){return Lt(Kt,"hex",ec,e)}function jh(e){return Lt(Kt,"currency_code",Fs,e)}function Ah(e,t){let r=t?.enc??"hex",o=`${e}_${r}`,n=Ce[o];if(!n)throw new Error(`Unrecognized hash format: ${o}`);return Lt(Kt,o,n,t)}var Rn=g("ZodNumber",(e,t)=>{Gi.init(e,t),C.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Ul(e,r,o,n),e.isFinite=!0},$.derived({minValue:e=>{let{minimum:t,exclusiveMinimum:r}=ae(e);return Math.max(t??Number.NEGATIVE_INFINITY,r??Number.NEGATIVE_INFINITY)},maxValue:e=>{let{maximum:t,exclusiveMaximum:r}=ae(e);return Math.min(t??Number.POSITIVE_INFINITY,r??Number.POSITIVE_INFINITY)},isInt:e=>{let{isInt:t,multipleOf:r}=ae(e);return!!t||!!r?.some(Number.isSafeInteger)},format:e=>ae(e).format??null},{gt(e,t){return this.check(Fe(e,t))},gte(e,t){return this.check(Oe(e,t))},min(e,t){return this.check(Oe(e,t))},lt(e,t){return this.check(Ze(e,t))},lte(e,t){return this.check(Ae(e,t))},max(e,t){return this.check(Ae(e,t))},int(e){return this.check(Wo(e))},safe(e){return this.check(Wo(e))},positive(e){return this.check(Fe(0,e))},nonnegative(e){return this.check(Oe(0,e))},negative(e){return this.check(Ze(0,e))},nonpositive(e){return this.check(Ae(0,e))},multipleOf(e,t){return this.check(mt(e,t))},step(e,t){return this.check(mt(e,t))},finite(){return this}}));function Nd(e){return Qu(Rn,e)}var Jt=g("ZodNumberFormat",(e,t)=>{Qc.init(e,t),Rn.init(e,t)});function Wo(e){return tl(Jt,e)}function Oh(e){return nl(Jt,e)}function Th(e){return rl(Jt,e)}function Nh(e){return il(Jt,e)}function Dh(e){return ol(Jt,e)}var Mn=g("ZodBoolean",(e,t)=>{xr.init(e,t),C.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Cl(e,r,o,n)});function Dd(e){return al(Mn,e)}var Ln=g("ZodBigInt",(e,t)=>{qi.init(e,t),C.init(e,t),e._zod.processJSONSchema=(r,o,n)=>El(e,r,o,n)},$.derived({minValue:e=>ae(e).minimum??null,maxValue:e=>ae(e).maximum??null,format:e=>ae(e).format??null},{gte(e,t){return this.check(Oe(e,t))},min(e,t){return this.check(Oe(e,t))},gt(e,t){return this.check(Fe(e,t))},lt(e,t){return this.check(Ze(e,t))},lte(e,t){return this.check(Ae(e,t))},max(e,t){return this.check(Ae(e,t))},positive(e){return this.check(Fe(BigInt(0),e))},negative(e){return this.check(Ze(BigInt(0),e))},nonpositive(e){return this.check(Ae(BigInt(0),e))},nonnegative(e){return this.check(Oe(BigInt(0),e))},multipleOf(e,t){return this.check(mt(e,t))}}));function Uh(e){return cl(Ln,e)}var fa=g("ZodBigIntFormat",(e,t)=>{eu.init(e,t),Ln.init(e,t)});function Ch(e){return ll(fa,e)}function Eh(e){return dl(fa,e)}var Ud=g("ZodSymbol",(e,t)=>{tu.init(e,t),C.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Rl(e,r,o,n)});function Rh(e){return pl(Ud,e)}var Cd=g("ZodUndefined",(e,t)=>{nu.init(e,t),C.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Ll(e,r,o,n)});function Mh(e){return fl(Cd,e)}var Ed=g("ZodNull",(e,t)=>{ru.init(e,t),C.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Ml(e,r,o,n)});function Rd(e){return ml(Ed,e)}var Md=g("ZodAny",(e,t)=>{iu.init(e,t),C.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Vl(e,r,o,n)});function Lh(){return gl(Md)}var Ld=g("ZodUnknown",(e,t)=>{ou.init(e,t),C.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Kl(e,r,o,n)});function Zt(){return hl(Ld)}var Zd=g("ZodNever",(e,t)=>{au.init(e,t),C.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Fl(e,r,o,n)});function ma(e){return vl(Zd,e)}var Fd=g("ZodVoid",(e,t)=>{su.init(e,t),C.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Zl(e,r,o,n)});function Zh(e){return yl(Fd,e)}var Zr=g("ZodDate",(e,t)=>{cu.init(e,t),C.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Jl(e,r,o,n),e.min=(r,o)=>e.check(Oe(r,o)),e.max=(r,o)=>e.check(Ae(r,o))},$.derived({minDate:e=>{let{minimum:t}=ae(e);return t?new Date(t):null},maxDate:e=>{let{maximum:t}=ae(e);return t?new Date(t):null}},{}));function Fh(e){return $l(Zr,e)}var Vd=g("ZodArray",(e,t)=>{Vt(),lu.init(e,t),C.init(e,t),e._zod.processJSONSchema=(r,o,n)=>rd(e,r,o,n),e.element=t.element},{min(e,t){return this.check(nt(e,t))},nonempty(e){return this.check(nt(1,e))},max(e,t){return this.check(Rt(e,t))},length(e,t){return this.check(Mt(e,t))},unwrap(){return this.element}});function Fr(e,t){return xl(Vd,e,t)}function Vh(e){let t=e._zod.def.shape;return ga(Object.keys(t))}var Vr=g("ZodObject",(e,t)=>{Vt(),du.init(e,t),C.init(e,t),e._zod.processJSONSchema=(r,o,n)=>id(e,r,o,n),$.installLazyProp(e,"shape",r=>r._zod.def.shape,!1)},{keyof(){return ga(Object.keys(this._zod.def.shape))},catchall(e){return this.clone($.mergeDefs(this._zod.def,{catchall:e}))},passthrough(){return this.clone($.mergeDefs(this._zod.def,{catchall:Zt()}))},loose(){return this.clone($.mergeDefs(this._zod.def,{catchall:Zt()}))},strict(){return this.clone($.mergeDefs(this._zod.def,{catchall:ma()}))},strip(){return this.clone($.mergeDefs(this._zod.def,{catchall:void 0}))},extend(e){return $.extend(this,e)},safeExtend(e){return $.safeExtend(this,e)},merge(e){return $.merge(this,e)},pick(e){return $.pick(this,e)},omit(e){return $.omit(this,e)},partial(...e){return $.partial(Jr,this,e[0])},exactPartial(...e){return $.partial(va,this,e[0],"exactPartial")},required(...e){return $.required(ya,this,e[0])}});function Kh(e,t){let r={type:"object",shape:e??{},...$.normalizeParams(t)};return new Vr(r)}function Jh(e,t){return new Vr({type:"object",shape:e,catchall:ma(),...$.normalizeParams(t)})}function Bh(e,t){return new Vr({type:"object",shape:e,catchall:Zt(),...$.normalizeParams(t)})}var Kr=g("ZodUnion",(e,t)=>{kr.init(e,t),C.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Zo(e,r,o,n),e.options=t.options});function Zn(e,t){return new Kr({type:"union",options:e,...$.normalizeParams(t)})}var Kd=g("ZodXor",(e,t)=>{Kr.init(e,t),pu.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Zo(e,r,o,n),e.options=t.options});function Wh(e,t){return new Kd({type:"union",options:e,inclusive:!1,...$.normalizeParams(t)})}var Jd=g("ZodDiscriminatedUnion",(e,t)=>{Kr.init(e,t),mu.init(e,t)});function Gh(e,t,r){return new Jd({type:"union",options:t,discriminator:e,...$.normalizeParams(r)})}var Bd=g("ZodIntersection",(e,t)=>{gu.init(e,t),C.init(e,t),e._zod.processJSONSchema=(r,o,n)=>od(e,r,o,n)});function Wd(e,t){return new Bd({type:"intersection",left:e,right:t})}var Gd=g("ZodTuple",(e,t)=>{Vt(),Hi.init(e,t),C.init(e,t),e._zod.processJSONSchema=(r,o,n)=>ad(e,r,o,n)},{rest(e){return this.clone({...this._zod.def,rest:e})},partial(){let e=this._zod.def;if(e.checks?.length)throw new Error(".partial() cannot be used on tuple schemas containing refinements");return this.clone({...e,items:e.items.map(t=>new Jr({type:"optional",innerType:t}))})}});function qd(e,t,r){let o=t instanceof D,n=o?r:t,i=o?t:null;return new Gd({type:"tuple",items:e,rest:i,...$.normalizeParams(n)})}var Un=g("ZodRecord",(e,t)=>{Vt(),hu.init(e,t),C.init(e,t),e._zod.processJSONSchema=(r,o,n)=>sd(e,r,o,n),e.keyType=t.keyType,e.valueType=t.valueType});function Hd(e,t,r){return!t||!t._zod?new Un({type:"record",keyType:Rr(),valueType:e,...$.normalizeParams(t)}):new Un({type:"record",keyType:e,valueType:t,...$.normalizeParams(r)})}function qh(e,t,r){return new Un({type:"record",keyType:e,valueType:t,...$.normalizeParams(r),partial:!0})}function Hh(e,t,r){return new Un({type:"record",keyType:e,valueType:t,mode:"loose",...$.normalizeParams(r)})}var Xd=g("ZodMap",(e,t)=>{Vt(),vu.init(e,t),C.init(e,t),e._zod.processJSONSchema=(r,o,n)=>td(e,r,o,n),e.keyType=t.keyType,e.valueType=t.valueType,e.min=(...r)=>e.check(Ve(...r)),e.nonempty=r=>e.check(Ve(1,r)),e.max=(...r)=>e.check(gt(...r)),e.size=(...r)=>e.check(Et(...r))});function Xh(e,t,r){return new Xd({type:"map",keyType:e,valueType:t,...$.normalizeParams(r)})}var Yd=g("ZodSet",(e,t)=>{Vt(),yu.init(e,t),C.init(e,t),e._zod.processJSONSchema=(r,o,n)=>nd(e,r,o,n),e.min=(...r)=>e.check(Ve(...r)),e.nonempty=r=>e.check(Ve(1,r)),e.max=(...r)=>e.check(gt(...r)),e.size=(...r)=>e.check(Et(...r))});function Yh(e,t){return new Yd({type:"set",valueType:e,...$.normalizeParams(t)})}var Cn=g("ZodEnum",(e,t)=>{$u.init(e,t),C.init(e,t),e._zod.processJSONSchema=(o,n,i)=>Bl(e,o,n,i),e.enum=t.entries,e.options=[...e._zod.values];let r=new Set(Object.keys(t.entries));e.extract=(o,n)=>{let i={};for(let a of o)if(r.has(a))i[a]=t.entries[a];else throw new Error(`Key ${a} not found in enum`);return new Cn({...t,checks:[],...$.normalizeParams(n),entries:i})},e.exclude=(o,n)=>{let i={...t.entries};for(let a of o)if(r.has(a))delete i[a];else throw new Error(`Key ${a} not found in enum`);return new Cn({...t,checks:[],...$.normalizeParams(n),entries:i})}});function ga(e,t){let r=Array.isArray(e)?Object.fromEntries(e.map(o=>[o,o])):e;return new Cn({type:"enum",entries:r,...$.normalizeParams(t)})}function Qh(e,t){return new Cn({type:"enum",entries:e,...$.normalizeParams(t)})}var Qd=g("ZodLiteral",(e,t)=>{bu.init(e,t),C.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Wl(e,r,o,n),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 ev(e,t){return new Qd({type:"literal",values:Array.isArray(e)?e:[e],...$.normalizeParams(t)})}var ep=g("ZodFile",(e,t)=>{_u.init(e,t),C.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Hl(e,r,o,n),e.min=(r,o)=>e.check(Ve(r,o)),e.max=(r,o)=>e.check(gt(r,o)),e.mime=(r,o)=>e.check(In(Array.isArray(r)?r:[r],o))});function tv(e){return kl(ep,e)}var tp=g("ZodTransform",(e,t)=>{Vt(),xu.init(e,t),C.init(e,t),e._zod.processJSONSchema=(r,o,n)=>ed(e,r,o,n),e._zod.parse=(r,o)=>{if(o.direction==="backward")throw new pt(e.constructor.name);r.addIssue=i=>{if(typeof i=="string")r.issues.push($.issue(i,r.value,t));else{let a=i;a.fatal&&(a.continue=!1),a.code??(a.code="custom"),"input"in a||(a.input=r.value),a.inst??(a.inst=e),r.issues.push($.issue(a))}};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 tp({type:"transform",transform:e})}var Jr=g("ZodOptional",(e,t)=>{Xi.init(e,t),C.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Fo(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function Ft(e){return new Jr({type:"optional",innerType:e})}var va=g("ZodExactOptional",(e,t)=>{ku.init(e,t),C.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Fo(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function np(e){return new va({type:"optional",innerType:e})}var rp=g("ZodNullable",(e,t)=>{wu.init(e,t),C.init(e,t),e._zod.processJSONSchema=(r,o,n)=>cd(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function Mr(e){return new rp({type:"nullable",innerType:e})}function nv(e){return Ft(Mr(e))}var ip=g("ZodDefault",(e,t)=>{Su.init(e,t),C.init(e,t),e._zod.processJSONSchema=(r,o,n)=>dd(e,r,o,n),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function op(e,t){return new ip({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():$.shallowClone(t)}})}var ap=g("ZodPrefault",(e,t)=>{Iu.init(e,t),C.init(e,t),e._zod.processJSONSchema=(r,o,n)=>pd(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function sp(e,t){return new ap({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():$.shallowClone(t)}})}var ya=g("ZodNonOptional",(e,t)=>{zu.init(e,t),C.init(e,t),e._zod.processJSONSchema=(r,o,n)=>ud(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function cp(e,t){return new ya({type:"nonoptional",innerType:e,...$.normalizeParams(t)})}var up=g("ZodSuccess",(e,t)=>{Pu.init(e,t),C.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Xl(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function rv(e){return new up({type:"success",innerType:e})}var lp=g("ZodCatch",(e,t)=>{ju.init(e,t),C.init(e,t),e._zod.processJSONSchema=(r,o,n)=>fd(e,r,o,n),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function dp(e,t){return new lp({type:"catch",innerType:e,catchValue:typeof t=="function"?t:$.constantCatch(t)})}var pp=g("ZodNaN",(e,t)=>{Au.init(e,t),C.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Gl(e,r,o,n)});function iv(e){return _l(pp,e)}var Br=g("ZodPipe",(e,t)=>{Yi.init(e,t),C.init(e,t),e._zod.processJSONSchema=(r,o,n)=>md(e,r,o,n),e.in=t.in,e.out=t.out});function Go(e,t){return new Br({type:"pipe",in:e,out:t})}var Wr=g("ZodCodec",(e,t)=>{Br.init(e,t),wr.init(e,t)});function ov(e,t,r){return new Wr({type:"pipe",in:e,out:t,transform:r.decode,reverseTransform:r.encode})}function av(e){let t=e._zod.def;return new Wr({type:"pipe",in:t.out,out:t.in,transform:t.reverseTransform,reverseTransform:t.transform})}var fp=g("ZodPreprocess",(e,t)=>{Br.init(e,t),Ou.init(e,t)}),mp=g("ZodReadonly",(e,t)=>{Tu.init(e,t),C.init(e,t),e._zod.processJSONSchema=(r,o,n)=>gd(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function gp(e){return new mp({type:"readonly",innerType:e})}var hp=g("ZodTemplateLiteral",(e,t)=>{Nu.init(e,t),C.init(e,t),e._zod.processJSONSchema=(r,o,n)=>ql(e,r,o,n)});function sv(e,t){return new hp({type:"template_literal",parts:e,...$.normalizeParams(t)})}var vp=g("ZodLazy",(e,t)=>{Sr.init(e,t),C.init(e,t),e._zod.processJSONSchema=(r,o,n)=>vd(e,r,o,n),e.unwrap=()=>e._zod.def.getter()});function yp(e){return new vp({type:"lazy",getter:e})}var $p=g("ZodPromise",(e,t)=>{Uu.init(e,t),C.init(e,t),e._zod.processJSONSchema=(r,o,n)=>hd(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function cv(e){return new $p({type:"promise",innerType:e})}var bp=g("ZodFunction",(e,t)=>{Du.init(e,t),C.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Ql(e,r,o,n)});function uv(e){return new bp({type:"function",input:Array.isArray(e?.input)?qd(e?.input):e?.input??Fr(Zt()),output:e?.output??Zt()})}var Gr=g("ZodCustom",(e,t)=>{Cu.init(e,t),C.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Yl(e,r,o,n)});function lv(e){let t=new G({check:"custom"});return t._zod.check=e,t}function dv(e,t){return wl(Gr,e??(()=>!0),t)}function _p(e,t={}){return Sl(Gr,e,t)}function xp(e,t){return Il(e,t)}var pv=zl,fv=Pl,kp=g("ZodInstanceOf",(e,t)=>{Gr.init(e,t)},{properties(e,t){return this.check(Sn(e,t))}});function mv(e,t={}){let r=new kp({type:"custom",check:"custom",fn:o=>o instanceof e,abort:!0,...$.normalizeParams(t)});return r._zod.bag.Class=e,r._zod.check=o=>{o.value instanceof e||o.issues.push({code:"invalid_type",expected:e.name,input:o.value,inst:r,path:[...r._zod.def.path??[]]})},r}var gv=(...e)=>jl({Codec:Wr,Boolean:Mn,String:En},...e);function hv(e){let t=yp(()=>Zn([Rr(e),Nd(),Dd(),Rd(),Fr(t),Hd(Rr(),t)]));return t}function vv(e,t){return new fp({type:"pipe",in:ha(e),out:t})}var kw={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"};function ww(e){te({customError:e})}function Sw(){return te().customError}var wp;wp||(wp={});var qr={};Ye(qr,{ZodISODate:()=>bt,ZodISODateTime:()=>$t,ZodISODuration:()=>xt,ZodISOTime:()=>_t,date:()=>zw,datetime:()=>Iw,duration:()=>jw,time:()=>Pw});function Iw(e){return Tr($t,e)}function zw(e){return Nr(bt,e)}function Pw(e){return Dr(_t,e)}function jw(e){return Ur(xt,e)}var z={...Fn,...Jo,iso:qr},Aw=new Set(["$schema","$ref","$defs","definitions","$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor","type","enum","const","anyOf","oneOf","allOf","not","properties","required","additionalProperties","patternProperties","propertyNames","minProperties","maxProperties","items","prefixItems","additionalItems","minItems","maxItems","uniqueItems","contains","minContains","maxContains","minLength","maxLength","pattern","format","minimum","maximum","exclusiveMinimum","exclusiveMaximum","multipleOf","description","default","contentEncoding","contentMediaType","contentSchema","unevaluatedItems","unevaluatedProperties","if","then","else","dependentSchemas","dependentRequired","nullable","readOnly"]);function Ow(e,t){let r=e.$schema;return r==="https://json-schema.org/draft/2020-12/schema"?"draft-2020-12":r==="http://json-schema.org/draft-07/schema#"?"draft-7":r==="http://json-schema.org/draft-04/schema#"?"draft-4":t??"draft-2020-12"}function yv(e,t){return e.map((r,o)=>o<t?r:r.optional())}function Tw(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}function Nw(e,t){if(!e.startsWith("#"))throw new Error("External $ref is not supported, only local refs (#/...) are allowed");let r=e.slice(1).split("/").filter(Boolean);if(r.length===0)return t.rootSchema;let o=t.version==="draft-2020-12"?"$defs":"definitions";if(r[0]===o){let n=r[1]===void 0?void 0:Tw(r[1]);if(!n||!t.defs[n])throw new Error(`Reference not found: ${e}`);return t.defs[n]}throw new Error(`Reference not found: ${e}`)}function Dw(e,t){return z.transform(o=>o).check(o=>{let n=o.value;if(typeof n!="object"||n===null||Array.isArray(n))return;let i=Object.getOwnPropertyNames(n);if(t.minProperties!==void 0&&i.length<t.minProperties&&o.issues.push({origin:"object",code:"too_small",minimum:t.minProperties,inclusive:!0,message:`Too small: expected object to have >=${t.minProperties} properties`,input:n,inst:e,continue:!0}),t.maxProperties!==void 0&&i.length>t.maxProperties&&o.issues.push({origin:"object",code:"too_big",maximum:t.maxProperties,inclusive:!0,message:`Too big: expected object to have <=${t.maxProperties} properties`,input:n,inst:e,continue:!0}),t.keySchema)for(let a of i){let s=t.keySchema.safeParse(a);s.success||o.issues.push({code:"invalid_key",origin:"record",issues:s.error.issues,input:a,path:[a],continue:!0})}}).pipe(e)}function Sp(e,t){if(e===null)return"z";let r=typeof e;if(r!=="object"){if(r==="number"&&Number.isNaN(e))return null;let o=String(e);return`${r[0]}${o.length}:${o}`}if(t.has(e))return null;t.add(e);try{if(Array.isArray(e)){let i=[];for(let a of e){let s=Sp(a,t);if(s===null)return null;i.push(s)}return`a${i.length}:[${i.join(",")}]`}let o=Object.keys(e).sort(),n=[];for(let i of o){let a=Sp(e[i],t);if(a===null)return null;n.push(`${i.length}:${i}=${a}`)}return`o${n.length}:{${n.join(",")}}`}finally{t.delete(e)}}var Uw=new Set(["items","prefixItems","additionalItems","additionalProperties","contains","propertyNames","not","if","then","else","allOf","anyOf","oneOf","unevaluatedItems","unevaluatedProperties","contentSchema"]),Cw=new Set(["properties","patternProperties","dependentSchemas","dependencies","$defs","definitions"]);function Hr(e){return typeof e!="object"||e===null?!1:Array.isArray(e)?e.some(Hr):typeof e.$ref=="string"?!0:Object.entries(e).some(([t,r])=>Uw.has(t)?Hr(r):!Cw.has(t)||typeof r!="object"||r===null?!1:Object.values(r).some(Hr))}function $v(e){return e===1?"element":"elements"}function Ew(e,t){return z.transform(o=>o).check(o=>{let n=o.value;if(Array.isArray(n)){if(t.uniqueItems===!0){let i=new Map;for(let a=0;a<n.length;a++){let s=Sp(n[a],new Set);if(s===null)continue;let u=i.get(s);if(u===void 0){i.set(s,a);continue}o.issues.push({code:"custom",message:`Array items must be unique: element at index ${a} duplicates the one at index ${u}`,input:n,path:[a],continue:!0})}}if(t.containsSchema){let i=t.minContains??1,a=t.maxContains!==void 0?t.maxContains+1:Number.POSITIVE_INFINITY,s=0;for(let u of n)if(t.containsSchema.safeParse(u).success&&++s>=a)break;s<i&&o.issues.push({code:"custom",message:`Array must contain at least ${i} matching ${$v(i)}; found ${s}`,input:n,continue:!0}),t.maxContains!==void 0&&s>t.maxContains&&o.issues.push({code:"custom",message:`Array must contain at most ${t.maxContains} matching ${$v(t.maxContains)}`,input:n,continue:!0})}}}).pipe(e)}function bv(e,t){if(e!==!1)return e===void 0||e===!0?z.any():ye(e,t)}var Rw=/^(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:\.\d+)?(?:Z|[+-](?:[01]\d|2[0-3]):[0-5]\d)$/;function _v(e,t){if(e.not!==void 0){if(typeof e.not=="object"&&Object.keys(e.not).length===0)return z.never();throw new Error("not is not supported in Zod (except { not: {} } for never)")}if(e.unevaluatedItems!==void 0)throw new Error("unevaluatedItems is not supported");if(e.unevaluatedProperties!==void 0)throw new Error("unevaluatedProperties is not supported");if(e.if!==void 0||e.then!==void 0||e.else!==void 0)throw new Error("Conditional schemas (if/then/else) are not supported");if(e.dependentSchemas!==void 0||e.dependentRequired!==void 0)throw new Error("dependentSchemas and dependentRequired are not supported");if(e.$ref){let n=e.$ref;if(t.refs.has(n))return t.refs.get(n);if(t.processing.has(n))return z.lazy(()=>{if(!t.refs.has(n))throw new Error(`Circular reference not resolved: ${n}`);return t.refs.get(n)});t.processing.add(n);let i=Nw(n,t),a=ye(i,t);return t.refs.set(n,a),t.processing.delete(n),a}if(e.enum!==void 0){let n=e.enum;if(t.version==="openapi-3.0"&&e.nullable===!0&&n.length===1&&n[0]===null)return z.null();if(n.length===0)return z.never();if(n.length===1)return z.literal(n[0]);if(n.every(a=>typeof a=="string"))return z.enum(n);let i=n.map(a=>z.literal(a));return i.length<2?i[0]:z.union([i[0],i[1],...i.slice(2)])}if(e.const!==void 0)return z.literal(e.const);let r=e.type;if(Array.isArray(r)){let n=r.map(i=>{let a={...e,type:i};return _v(a,t)});return n.length===0?z.never():n.length===1?n[0]:z.union(n)}if(!r)return z.any();let o;switch(r){case"string":{let n=z.string();if(e.format){let i=e.format;i==="email"?n=n.check(z.email()):i==="uri"||i==="uri-reference"?n=n.check(z.url()):i==="uuid"||i==="guid"?n=n.check(z.uuid()):i==="date-time"?n=n.check(z.iso.datetime({offset:!0})):i==="date"?n=n.check(z.iso.date()):i==="time"?n=n.check(z.regex(Rw)):i==="duration"?n=n.check(z.iso.duration()):i==="hostname"?n=n.check(z.hostname()):i==="ipv4"?n=n.check(z.ipv4()):i==="ipv6"?n=n.check(z.ipv6()):i==="mac"?n=n.check(z.mac()):i==="cidr"?n=n.check(z.cidrv4()):i==="cidr-v6"?n=n.check(z.cidrv6()):i==="base64"?n=n.check(z.base64()):i==="base64url"?n=n.check(z.base64url()):i==="e164"?n=n.check(z.e164()):i==="credit_card"?n=n.check(z.creditCard()):i==="iban"?n=n.check(z.iban()):i==="jwt"?n=n.check(z.jwt()):i==="emoji"?n=n.check(z.emoji()):i==="nanoid"?n=n.check(z.nanoid()):i==="cuid"?n=n.check(z.cuid()):i==="cuid2"?n=n.check(z.cuid2()):i==="ulid"?n=n.check(z.ulid()):i==="xid"?n=n.check(z.xid()):i==="ksuid"&&(n=n.check(z.ksuid()))}typeof e.minLength=="number"&&(n=n.min(e.minLength)),typeof e.maxLength=="number"&&(n=n.max(e.maxLength)),e.pattern&&(n=n.regex(new RegExp(e.pattern))),o=n;break}case"number":case"integer":{let n=r==="integer"?z.number().int():z.number();typeof e.minimum=="number"&&e.exclusiveMinimum!==!0&&(n=n.min(e.minimum)),typeof e.maximum=="number"&&e.exclusiveMaximum!==!0&&(n=n.max(e.maximum)),typeof e.exclusiveMinimum=="number"?n=n.gt(e.exclusiveMinimum):e.exclusiveMinimum===!0&&typeof e.minimum=="number"&&(n=n.gt(e.minimum)),typeof e.exclusiveMaximum=="number"?n=n.lt(e.exclusiveMaximum):e.exclusiveMaximum===!0&&typeof e.maximum=="number"&&(n=n.lt(e.maximum)),typeof e.multipleOf=="number"&&(n=n.multipleOf(e.multipleOf)),o=n;break}case"boolean":{o=z.boolean();break}case"null":{o=z.null();break}case"object":{let n={},i=e.properties||{},a=new Set(e.required||[]),s=typeof e.additionalProperties=="object"?ye(e.additionalProperties,t):void 0;for(let[p,m]of Object.entries(i)){let f=ye(m,t);ue(n,p,a.has(p)?f:f.optional())}if(e.patternProperties){let p=e.patternProperties,m=Object.keys(p),f=[];for(let y of m){let x=ye(p[y],t),j=z.string().regex(new RegExp(y));f.push(z.looseRecord(j,x))}let v=[];if(Object.keys(n).length>0&&v.push(z.object(n).passthrough()),v.push(...f),v.length===0)o=z.object({}).passthrough();else if(v.length===1)o=v[0];else{let y=z.intersection(v[0],v[1]);for(let x=2;x<v.length;x++)y=z.intersection(y,v[x]);o=y}if(e.additionalProperties===!1){let y=Object.keys(n),x=m.map(P=>new RegExp(P)),j=o;o=o.check(P=>{if(!De(P.value))return;let T=[];for(let S of Object.keys(P.value))y.includes(S)||x.some(I=>I.test(S))||T.push(S);T.length&&P.issues.push({code:"unrecognized_keys",keys:T,input:P.value,inst:j})})}}else{let p=z.object(n);e.additionalProperties===!1?o=p.strict():s?o=p.catchall(s):o=p.passthrough()}let u=e.propertyNames!==void 0&&e.propertyNames!==!0,l=typeof e.minProperties=="number"?e.minProperties:void 0,d=typeof e.maxProperties=="number"?e.maxProperties:void 0;if(u||l!==void 0||d!==void 0){let p;if(u){let m=typeof e.propertyNames=="object"&&e.propertyNames.type===void 0?{type:"string",...e.propertyNames}:e.propertyNames;p=ye(m,t)}o=Dw(o,{keySchema:p,minProperties:l,maxProperties:d})}break}case"array":{let n=e.prefixItems,i=e.items;if(n&&Array.isArray(n)){let a=typeof e.minItems=="number"?e.minItems:0,s=n.map(p=>ye(p,t)),u=yv(s,a),l=Array.isArray(i)?void 0:bv(i,t),d=z.tuple(u);o=l?d.rest(l):d,typeof e.minItems=="number"&&(o=o.check(z.minLength(e.minItems))),typeof e.maxItems=="number"&&(o=o.check(z.maxLength(e.maxItems)))}else if(Array.isArray(i)){let a=typeof e.minItems=="number"?e.minItems:0,s=i.map(p=>ye(p,t)),u=yv(s,a),l=bv(e.additionalItems,t),d=z.tuple(u);o=l?d.rest(l):d,typeof e.minItems=="number"&&(o=o.check(z.minLength(e.minItems))),typeof e.maxItems=="number"&&(o=o.check(z.maxLength(e.maxItems)))}else if(i!==void 0){let a=ye(i,t),s=z.array(a);typeof e.minItems=="number"&&(s=s.min(e.minItems)),typeof e.maxItems=="number"&&(s=s.max(e.maxItems)),o=s}else o=z.array(z.any());(e.uniqueItems===!0||e.contains!==void 0)&&(o=Ew(o,{uniqueItems:e.uniqueItems===!0,containsSchema:e.contains!==void 0?ye(e.contains,t):void 0,minContains:typeof e.minContains=="number"?e.minContains:void 0,maxContains:typeof e.maxContains=="number"?e.maxContains:void 0}));break}default:throw new Error(`Unsupported type: ${r}`)}return o}function ye(e,t){if(typeof e=="boolean")return e?z.any():z.never();let r=_v(e,t),o=e.type||e.enum!==void 0||e.const!==void 0;if(e.anyOf&&Array.isArray(e.anyOf)){let s=e.anyOf.map(l=>ye(l,t)),u=z.union(s);r=o?z.intersection(r,u):u}if(e.oneOf&&Array.isArray(e.oneOf)){let s=e.oneOf.map(l=>ye(l,t)),u=z.xor(s);r=o?z.intersection(r,u):u}if(e.allOf&&Array.isArray(e.allOf))if(e.allOf.length===0)r=o?r:z.any();else{let s=o?r:ye(e.allOf[0],t),u=o?0:1;for(let l=u;l<e.allOf.length;l++)s=z.intersection(s,ye(e.allOf[l],t));r=s}e.nullable===!0&&t.version==="openapi-3.0"&&(r=z.nullable(r)),e.readOnly===!0&&(r=z.readonly(r)),e.default!==void 0&&(r=r.default(e.default));let n={},i=["$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor"];for(let s of i)s in e&&(n[s]=e[s]);let a=["contentEncoding","contentMediaType","contentSchema"];for(let s of a)s in e&&(n[s]=e[s]);if(e.type==="object"&&e.$ref===void 0){e.propertyNames!==void 0&&!Hr(e.propertyNames)&&(n.propertyNames=e.propertyNames);for(let s of["minProperties","maxProperties"])e[s]!==void 0&&(n[s]=e[s])}if(e.type==="array"&&e.$ref===void 0){e.contains!==void 0&&!Hr(e.contains)&&(n.contains=e.contains);for(let s of["uniqueItems","minContains","maxContains"])e[s]!==void 0&&(n[s]=e[s])}for(let s of Object.keys(e))Aw.has(s)||ue(n,s,e[s]);return Object.keys(n).length>0&&t.registry.add(r,n),e.description&&(r=r.describe(e.description)),r}function xv(e,t){if(typeof e=="boolean")return e?z.any():z.never();let r;try{r=JSON.parse(JSON.stringify(e))}catch{throw new Error("fromJSONSchema input is not valid JSON (possibly cyclic); use $defs/$ref for recursive schemas")}let o=Ow(r,t?.defaultTarget),n=r.$defs||r.definitions||{},i={version:o,defs:n,refs:new Map,processing:new Set,rootSchema:r,registry:t?.registry??le};return ye(r,i)}var kv=Symbol("z.visit/resolving");function Xr(e,t){let r=typeof t=="function"?t:(a,s)=>{let u=t[a._zod.def.type];return u?u(a,s):a},o=new Map;function n(a){let s=o.get(a);if(s===kv)return new Sr({type:"lazy",getter:()=>o.get(a)});if(s!==void 0)return s;o.set(a,kv);let u=i(a),l=r(u,u!==a);return o.set(a,l),l}function i(a){let s=a._zod.def,u=s.type;switch(u){case"object":{let l=s.shape,d=Object.keys(l),p=!1,m={};for(let v of d){let y=n(l[v]);y!==l[v]&&(p=!0),m[v]=y}let f=s.catchall;return s.catchall&&(f=n(s.catchall),f!==s.catchall&&(p=!0)),p?F(a,{...s,shape:m,catchall:f}):a}case"array":{let l=n(s.element);return l===s.element?a:F(a,{...s,element:l})}case"tuple":{let l=s.items,d=!1,p=[];for(let f of l){let v=n(f);v!==f&&(d=!0),p.push(v)}let m=s.rest;return s.rest&&(m=n(s.rest),m!==s.rest&&(d=!0)),d?F(a,{...s,items:p,rest:m}):a}case"record":case"map":{let l=n(s.keyType),d=n(s.valueType);return l===s.keyType&&d===s.valueType?a:F(a,{...s,keyType:l,valueType:d})}case"set":{let l=n(s.valueType);return l===s.valueType?a:F(a,{...s,valueType:l})}case"union":{let l=s.options,d=!1,p=[];for(let m of l){let f=n(m);f!==m&&(d=!0),p.push(f)}return d?F(a,{...s,options:p}):a}case"intersection":{let l=n(s.left),d=n(s.right);return l===s.left&&d===s.right?a:F(a,{...s,left:l,right:d})}case"optional":case"nullable":case"default":case"prefault":case"catch":case"readonly":case"nonoptional":case"promise":case"success":{let l=n(s.innerType);return l===s.innerType?a:F(a,{...s,innerType:l})}case"pipe":{let l=n(s.in),d=n(s.out);return l===s.in&&d===s.out?a:F(a,{...s,in:l,out:d})}case"function":{let l=n(s.input),d=n(s.output);return l===s.input&&d===s.output?a:F(a,{...s,input:l,output:d})}case"lazy":{let l=s.getter,{_cachedInner:d,...p}=s;return F(a,{...p,getter:()=>n(l())})}case"template_literal":case"string":case"number":case"int":case"boolean":case"bigint":case"symbol":case"undefined":case"null":case"void":case"never":case"any":case"unknown":case"date":case"nan":case"enum":case"literal":case"file":case"transform":case"custom":return a;default:return a}}return n(e)}function wv(e){return Xr(e,{object:t=>t.partial(),union:t=>{let r=t._zod.def;return r.discriminator===void 0?t:Zn(r.options)}})}function Mw(e,t){if(!t?.length)return e;let r=e._zod.def;return F(e,Ee(r,{checks:[...r.checks??[],...t]}),{parent:!0})}function Sv(e){return Mw(e.out,e.checks)}function Lw(e){return e.in._zod.traits.has("$ZodTransform")?Sv(e):e.in}function Iv(e){return Xr(e,{pipe:t=>Lw(t._zod.def),default:(t,r)=>r?Ft(t._zod.def.innerType):t,catch:(t,r)=>r?t._zod.def.innerType:t})}function zv(e){return Xr(e,{pipe:t=>Sv(t._zod.def),prefault:(t,r)=>r?t._zod.def.innerType:t})}var Ip={};Ye(Ip,{bigint:()=>Kw,boolean:()=>Vw,date:()=>Jw,number:()=>Fw,string:()=>Zw});function Zw(e){return Gu(En,e)}function Fw(e){return el(Rn,e)}function Vw(e){return sl(Mn,e)}function Kw(e){return ul(Ln,e)}function Jw(e){return bl(Zr,e)}var Vn=c.string().min(1).max(512).refine(Bw,"Invalid path: use segments like notes/plan.md, without .. or a leading /");function Bw(e){return/[\u0000-\u001f\u007f\\]/.test(e)?!1:e.split("/").every(r=>r.length>0&&r.length<=255&&r!=="."&&r!=="..")}var Yr=c.string().regex(pe("message")),q=c.string().regex(pe("thread")),Ie=c.string().regex(pe("project")),ze=c.string().regex(pe("task")),zp=c.string().regex(pe("artifact")),R=c.iso.datetime(),Qr=c.enum(["user","agent","system"]),Ww=c.object({path:Vn,name:c.string(),size:c.number().int().nonnegative(),contentType:c.string()}),Gw=c.object({artifactId:zp,version:c.number().int().positive(),title:c.string()}),Pv=c.enum(["cloud","local"]),H=c.number().int().nonnegative(),qw=c.object({title:c.string(),harness:c.string(),runtime:Pv,model:c.string().nullable(),durationMs:H,inputTokens:H,outputTokens:H,costMicros:H.nullable()}),Hw=c.object({chars:H,limit:H,parts:c.object({instructions:H,skills:H,knowledge:H,brief:H,conversation:H,notes:H,other:H}),droppedMessages:H,droppedNotes:H,cut:c.boolean()}),Xw=c.object({model:c.string(),durationMs:H,calls:H,inputTokens:H,cachedInputTokens:H,outputTokens:H,costMicros:H.nullable(),runtime:Pv,computer:c.string().optional(),harness:c.string().optional(),task:qw.optional(),prompt:Hw.optional()}),Yw=c.enum(["brief","follow_up","reply","relay","answer"]),Qw=c.object({kind:Yw,threadId:q,fromThreadId:q.optional(),note:c.string()}),$a=8,Bt=c.object({id:Yr,projectId:Ie,threadId:q.nullable(),authorKind:Qr,authorId:c.string().min(1),body:c.string(),attachments:c.array(Ww).optional(),artifacts:c.array(Gw).optional(),stats:Xw.optional(),relay:Qw.optional(),clis:c.array(c.string().max(40)).max($a).optional(),seq:c.number().int().positive(),createdAt:R,editedAt:R.optional()}),eS=c.enum(["working","blocked","review_ready","done","failed"]),tS=c.object({id:c.string().max(40),options:c.array(c.string().max(40)).max($a),by:c.enum(["person","coordinator"]),reason:c.string().max(300).nullable()}),nS=c.object({cli:c.string().max(40),model:c.string().max(200).nullable(),effort:c.string().max(20).nullable()}),jv="cloud",rS=c.object({id:c.string().max(60),by:c.enum(["person","auto","coordinator"]),reason:c.string().max(300).nullable().default(null)}),Pp=c.enum(["duplicate","misrouted","cancelled"]),iS=c.object({replies:H,usage:c.object({tokens:H,durationMs:H,costMicros:H.nullable()}).nullable(),planMessageId:Yr.nullable()}),jp=c.object({id:q,projectId:Ie,rootMessageId:Yr,ackMessageId:Yr.nullable().default(null),title:c.string(),status:eS,statusText:c.string().nullable(),resolved:c.boolean(),closeReason:Pp.nullable().default(null),duplicateOf:q.nullable().default(null),label:c.string().nullable(),cli:tS.nullable().default(null),runner:rS.nullable().default(null),model:nS.nullable().default(null),seenSeq:c.number().int().nonnegative().nullable().default(null),summary:iS.nullable().default(null),createdAt:R,updatedAt:R}),oS=c.enum(["running","done","failed","cancelled"]),Av=c.object({id:ze,threadId:q,title:c.string(),harness:c.string(),backend:c.string(),status:oS,prUrl:c.string().nullable(),summary:c.string().nullable(),createdAt:R,finishedAt:R.nullable()}),vT=c.object({ref:c.string(),commits:c.array(c.object({hash:c.string(),message:c.string(),at:c.string()})),entries:c.array(c.object({name:c.string(),path:c.string(),type:c.enum(["file","folder"])})).nullable(),file:c.object({path:c.string(),text:c.string().nullable(),size:c.number(),truncated:c.boolean()}).nullable()}),Ap=c.object({id:c.string().min(1).max(200),label:c.string().max(100),state:c.enum(["started","done","failed"]).optional(),model:c.string().max(200).optional(),tokens:c.number().int().nonnegative().optional()}),Ov=c.object({stream:c.enum(["stdout","stderr","system"]),text:c.string(),at:c.number().optional(),ms:c.number().nonnegative().optional(),tool:c.boolean().optional(),agent:Ap.optional()}),Op=c.object({messageId:Yr,emoji:c.string().min(1).max(32),authorKind:Qr,authorId:c.string().min(1)}),ba=c.enum(["owner","admin","member"]),aS=c.object({working:c.number().int().nonnegative(),waiting:c.number().int().nonnegative()}),sS=c.object({monthMicros:c.number().int().nonnegative(),totalMicros:c.number().int().nonnegative()}),_a=c.enum(["indigo","blue","teal","green","amber","orange","red","pink","purple","gray"]),xa=c.enum(["folder","rocket","code","terminal","globe","smartphone","server","database","cpu","bot","book","pen","palette","camera","music","gamepad","briefcase","cart","chart","shield","flask","leaf","heart","star","zap","home"]),yT=c.object({id:Ie,name:c.string().min(1).max(120),role:ba,icon:xa.nullable().optional(),color:_a.nullable().optional(),createdAt:R,activity:aS.optional(),cost:sS.optional(),pinned:c.boolean().optional()}),$T=c.object({pinned:c.boolean()}),bT=c.object({name:c.string().trim().min(1).max(120)}),_T=c.object({id:c.string(),name:c.string(),role:ba,email:c.string().optional()}),Tp=32e3,cS=c.object({id:c.number().int(),accountLogin:c.string(),accountType:c.enum(["User","Organization"]),accountAvatarUrl:c.string().nullable()}),xT=c.object({configured:c.boolean(),installUrl:c.string().nullable(),installations:c.array(cS)}),kT=c.object({id:c.number().int(),installationId:c.number().int(),fullName:c.string(),defaultBranch:c.string(),private:c.boolean(),description:c.string().nullable()}),wT=c.object({repoId:c.number().int(),installationId:c.number().int(),fullName:c.string(),defaultBranch:c.string(),private:c.boolean(),createdAt:R}),Tv=c.object({repo:c.string(),number:c.number().int(),url:c.string(),threadId:q,title:c.string(),state:c.enum(["open","closed","merged"]),draft:c.boolean(),checks:c.enum(["pending","success","failure"]).nullable(),review:c.enum(["approved","changes_requested"]).nullable(),conflict:c.boolean().default(!1),branch:c.string().default(""),additions:c.number().int().nullable().default(null),deletions:c.number().int().nullable().default(null),changedFiles:c.number().int().nullable().default(null),updatedAt:R}),uS=c.object({path:c.string(),previousPath:c.string().nullable(),status:c.enum(["added","removed","modified","renamed","copied","changed","unchanged"]),additions:c.number().int(),deletions:c.number().int(),patch:c.string().nullable()}),ST=c.object({files:c.array(uS),truncated:c.boolean()}),Nv=c.enum(["merge","squash","rebase"]),IT=c.object({permitted:c.boolean(),blocked:c.enum(["closed","draft","conflict","checks_failed","checks_pending","changes_requested","protected","checking"]).nullable(),methods:c.array(Nv),sha:c.string()}),zT=c.object({method:Nv,sha:c.string().min(1),deleteBranch:c.boolean().default(!1)}),PT=c.object({merged:c.literal(!0),branchDeleted:c.boolean(),branchKept:c.enum(["fork","default","protected","gone","in_use","reopened","failed"]).nullable()}),jT=c.object({installationId:c.number().int().positive(),repoId:c.number().int().positive()});var lS=16e3,dS=16e3,DT=25*1024*1024,Dv=10;var UT=c.object({path:Vn,size:c.number().int().nonnegative(),contentType:c.string(),updatedAt:R,updatedByKind:Qr,updatedBy:c.string()}),pS=c.string().trim().min(1).max(80).regex(/^[\p{L}\p{N}][\p{L}\p{N} _.-]*$/u,"Use letters, numbers, spaces, dots, dashes or underscores"),fS=c.enum(["ok","stale"]),mS=c.object({name:pS,description:c.string().max(300),content:c.string().max(dS),updatedAt:R,updatedByKind:Qr,updatedBy:c.string(),status:fS.default("ok"),staleReason:c.string().max(300).nullable().default(null),verifiedAt:R.nullable().default(null),previousContent:c.string().nullable().default(null),previousAt:R.nullable().default(null)}),CT=mS.pick({description:!0,content:!0}),ET=c.discriminatedUnion("status",[c.object({status:c.literal("ok")}),c.object({status:c.literal("stale"),reason:c.string().trim().min(1).max(300)})]),gS=c.object({text:c.string().max(lS),updatedAt:R.nullable(),updatedBy:c.string().nullable()}),RT=gS.pick({text:!0}),Uv=c.enum(["files","memory","instructions"]),Cv=c.enum(["auto","on","off"]),MT=c.object({mode:Cv,active:c.boolean(),lastRunAt:R.nullable(),threadsSince:c.number().int().nonnegative(),threadsNeeded:c.number().int().positive(),threadId:c.string().nullable()}),LT=c.object({mode:Cv});var Np=c.object({id:zp,projectId:Ie,threadId:q.nullable(),title:c.string(),description:c.string().nullable(),version:c.number().int().positive(),createdAt:R,updatedAt:R}),KT=c.object({version:c.number().int().positive(),size:c.number().int().nonnegative(),threadId:q.nullable(),createdAt:R}),JT=c.object({version:c.number().int().positive(),url:c.string().nullable(),expiresAt:R.nullable()}),BT=2*1024*1024;var Dp=c.string().regex(pe("routine")),hS=/^(\*|\d+(-\d+)?)(\/\d+)?(,(\*|\d+(-\d+)?)(\/\d+)?)*$/,vS=c.string().trim().refine(e=>{let t=e.split(/\s+/);return t.length===5&&t.every(r=>hS.test(r))},"Expected a five-field cron expression, e.g. 0 9 * * 1-5"),yS=c.string().min(1).max(64).refine(e=>{try{return new Intl.DateTimeFormat("en-US",{timeZone:e}),!0}catch{return!1}},"Unknown time zone"),Up=c.discriminatedUnion("kind",[c.object({kind:c.literal("cron"),cron:vS,timezone:yS.default("UTC")}),c.object({kind:c.literal("once"),at:R})]),Cp=c.discriminatedUnion("kind",[c.object({kind:c.literal("coordinator")}),c.object({kind:c.literal("thread"),threadId:q})]),Ep=c.object({id:Dp,projectId:Ie,name:c.string(),prompt:c.string(),target:Cp,schedule:Up,paused:c.boolean(),nextRunAt:R.nullable(),lastRunAt:R.nullable(),runCount:c.number().int().nonnegative(),createdBy:c.string(),createdAt:R}),XT=c.object({name:c.string().trim().min(1).max(120),prompt:c.string().trim().min(1).max(8e3),target:Cp.default({kind:"coordinator"}),schedule:Up}),YT=c.object({name:c.string().trim().min(1).max(120),prompt:c.string().trim().min(1).max(8e3),target:Cp,schedule:Up,paused:c.boolean()}).partial();var Rp=c.object({text:c.string(),until:c.string(),createdBy:c.string(),createdAt:c.string(),wakes:c.number().int().nonnegative(),threads:c.number().int().nonnegative(),idle:c.number().int().nonnegative()});var $S=c.string().regex(pe("sshHost")),Mp=c.string().regex(/^[a-z0-9][a-z0-9_-]{0,39}$/,"Use lowercase letters, digits, - and _ (up to 40)."),ka=c.string().trim().min(1).max(253).regex(/^(?:[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?(?:\.[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?)*\.?|\[?[0-9A-Fa-f:.]+\]?)$/,"Enter a host name or IP address."),Ev=c.string().trim().regex(/^[A-Za-z0-9_][A-Za-z0-9_.-]{0,63}$/,"Enter the user name on the server."),Rv=c.enum(["ask","off"]),oN=c.string().max(16e3).regex(/^(?:ssh|ecdsa|sk)-[\w@.-]+ [A-Za-z0-9+/=]+(?: .*)?$/),Mv=c.string().max(200).regex(/^SHA256:[A-Za-z0-9+/=]+$/),bS=c.object({id:$S,projectId:Ie,alias:Mp,host:c.string(),port:c.number().int(),user:c.string(),runnerId:c.string(),runnerName:c.string(),mine:c.boolean(),keySource:c.enum(["new","existing"]),publicKey:c.string().nullable(),keyFingerprint:c.string().nullable(),hostFingerprint:c.string().nullable(),rule:Rv,testedAt:R.nullable(),createdAt:R}),_S=c.object({id:c.string(),alias:c.string(),threadId:c.string().nullable(),command:c.string(),reason:c.string().nullable(),decision:c.enum(["once","turn","deny","timeout","failed"]),approvedBy:c.string().nullable(),exitCode:c.number().int().nullable(),ms:c.number().int().nullable(),at:R}),aN=c.object({hosts:c.array(bS),history:c.array(_S)}),sN=c.object({runnerId:c.string(),alias:Mp,host:ka,port:c.number().int().min(1).max(65535).default(22),user:Ev,existingKey:c.string().min(1).max(1024).optional()}),cN=c.object({rule:Rv}),uN=c.object({hostKey:c.string().min(1).max(16e3)}),Lv=c.object({type:c.string().max(60),key:c.string().max(16e3),fingerprint:Mv}),Zv=c.object({path:c.string().max(1024),name:c.string().max(255),type:c.string().max(60),fingerprint:Mv,comment:c.string().max(500)}),Fv=c.object({exitCode:c.number().int().nullable(),stdout:c.string(),stderr:c.string(),truncated:c.boolean(),ms:c.number().int().nonnegative(),error:c.enum(["hostkey","auth","connect","timeout","nokey","other"]).optional()}),Vv=300*1e3,Kv=200*1024,wa=c.object({projectId:Ie,alias:Mp}),Lp=wa.extend({host:ka,port:c.number().int().min(1).max(65535),user:Ev,hostKey:c.string().min(1).max(16e3)});var Wv=2,it=c.string().regex(pe("runner")),Je=c.enum(["claude","codex","antigravity","opencode","hermes","cursor","muse","kimi"]);var Gv=c.object({path:c.string().min(1).max(1024),name:c.string().max(255)}),xS=c.object({kind:c.string().max(40),usedPercent:c.number().min(0).max(1e3).nullable(),resetsAt:R.nullable()}),kS=c.object({status:c.enum(["ok","warning","limited"]).optional(),windows:c.array(xS).max(8),at:R});var wS=c.object({id:c.string().min(1).max(200),name:c.string().max(200),efforts:c.array(c.string().min(1).max(20)).max(10)});var SS=c.object({id:Je,version:c.string().max(200).nullable(),limits:kS.optional().catch(void 0),models:c.array(wS).max(100).optional().catch(void 0)}),IS=c.enum(["folders","cancel","agent","agent-clis","connectors","skills","project-folders","files","settings","update","models","github-token","git-token","steer","steer-claude","ssh"]),zS=c.discriminatedUnion("transport",[c.object({transport:c.literal("http"),name:c.string().regex(/^[a-z][a-z0-9_-]{0,40}$/),path:c.string().regex(/^\/api\/[\w/-]+$/).max(300)}),c.object({transport:c.literal("stdio"),name:c.string().regex(/^[a-z][a-z0-9_-]{0,40}$/),command:c.string().min(1).max(200),args:c.array(c.string().max(2e3)).max(50),env:c.record(c.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/),c.string().max(4e3))})]),PS=c.enum(["read","edit","auto","full"]),Fp=c.object({access:PS,worktrees:c.boolean(),autoUpdate:c.boolean(),remote:c.boolean()}),qv=Fp.omit({remote:!0}).partial(),jS=c.enum(["service","app","manual"]),Zp=c.object({state:c.enum(["waiting","downloading","restarting","failed","rolled-back"]),version:c.string().max(50),running:c.number().int().nonnegative().optional(),message:c.string().max(500).optional(),at:R}),Hv=c.object({version:c.string().max(50),hostname:c.string().max(255),platform:c.string().max(50),folders:c.array(Gv).max(200),clis:c.array(c.unknown()).max(10).transform(e=>e.flatMap(t=>{let r=SS.safeParse(t);return r.success?[r.data]:[]})),features:c.array(c.string().max(50)).max(20).default([]).transform(e=>e.filter(t=>IS.safeParse(t).success)),settings:Fp.optional().catch(void 0),updates:jS.optional().catch(void 0),update:Zp.optional().catch(void 0)}),Sa=1e5,Q=c.string().min(1).max(64),AS=c.object({name:c.string().max(255),path:c.string().max(1024)}),OS=c.object({path:c.string().max(1024),parent:c.string().max(1024).nullable(),home:c.string().max(1024),dirs:c.array(AS).max(1e3)}),Jv=c.object({inputTokens:c.number().int().nonnegative(),outputTokens:c.number().int().nonnegative(),model:c.string().max(200).optional()}),Vp=512*1024,TS=c.object({path:c.string().max(4096),size:c.number().int().nonnegative(),data:c.string().max(Math.ceil(Vp/3)*4+4),truncated:c.boolean()}),NS=c.object({model:c.string().min(1).max(200).optional(),effort:c.string().min(1).max(20).optional()}),Bv=c.object({token:c.string().min(20).max(4096),expiresAt:R,repos:c.array(c.string().regex(/^[\w.-]+\/[\w.-]+$/).max(200)).max(100)}),gN=c.discriminatedUnion("type",[Hv.extend({type:c.literal("hello"),protocol:c.number().int().positive(),running:c.array(ze).max(100).default([]),interrupted:c.array(ze).max(100).default([])}),c.object({type:c.literal("task.progress"),taskId:ze,text:c.string().max(2e3),usage:Jv.optional(),agent:Ap.optional(),ms:c.number().nonnegative().optional()}),c.object({type:c.literal("task.done"),taskId:ze,ok:c.boolean(),usage:Jv.optional(),result:c.string().max(Sa),cancelled:c.boolean().optional()}),c.object({type:c.literal("ping")}),c.object({type:c.literal("task.folders"),taskId:ze,folders:c.array(c.string().min(1).max(1024)).max(60)}),OS.extend({type:c.literal("dirs"),requestId:Q}),c.object({type:c.literal("folders"),requestId:Q,folders:c.array(Gv).max(200)}),c.object({type:c.literal("request.failed"),requestId:Q,message:c.string().max(500)}),TS.extend({type:c.literal("file"),requestId:Q}),c.object({type:c.literal("settings"),requestId:Q,settings:Fp}),c.object({type:c.literal("update.accepted"),requestId:Q,update:Zp}),c.object({type:c.literal("update.status"),update:Zp.nullable()}),c.object({type:c.literal("task.steered"),requestId:Q,taken:c.boolean()}),c.object({type:c.literal("ssh.key"),requestId:Q,publicKey:c.string().max(16e3),fingerprint:c.string().max(200),protected:c.boolean()}),c.object({type:c.literal("ssh.keylist"),requestId:Q,keys:c.array(Zv).max(100)}),c.object({type:c.literal("ssh.hostkeylist"),requestId:Q,keys:c.array(Lv).max(10)}),Fv.extend({type:c.literal("ssh.result"),requestId:Q})]),Xv=c.discriminatedUnion("type",[c.object({type:c.literal("welcome"),runnerId:it,name:c.string()}),c.object({type:c.literal("task.start"),taskId:ze,threadId:q,folder:c.string().min(1).max(1024),cli:Je,prompt:c.string().min(1).max(Sa),model:NS.optional(),folders:c.array(c.string().min(1).max(1024)).max(50).optional(),agent:c.object({mcpPath:c.string().regex(/^\/api\/[\w/-]+$/).max(300),token:c.string().min(20).max(200),connectors:c.array(zS).max(30).optional(),skills:c.object({path:c.string().regex(/^\/api\/[\w/-]+$/).max(300)}).optional(),resume:c.object({after:ze,prompt:c.string().min(1).max(Sa)}).optional()}).optional(),github:Bv.optional()}),c.object({type:c.literal("task.github"),taskId:ze,github:Bv}),c.object({type:c.literal("task.steer"),requestId:Q,taskId:ze,text:c.string().min(1).max(Sa)}),c.object({type:c.literal("task.cancel"),taskId:ze}),c.object({type:c.literal("pong")}),c.object({type:c.literal("dirs.list"),requestId:Q,path:c.string().max(1024).optional()}),c.object({type:c.literal("folder.share"),requestId:Q,path:c.string().min(1).max(1024)}),c.object({type:c.literal("folder.unshare"),requestId:Q,path:c.string().min(1).max(1024)}),c.object({type:c.literal("file.read"),requestId:Q,path:c.string().min(1).max(4096),folders:c.array(c.string().min(1).max(1024)).min(1).max(51),threadId:q.optional()}),c.object({type:c.literal("settings.set"),requestId:Q,settings:qv}),c.object({type:c.literal("runner.update"),requestId:Q,version:c.string().regex(/^\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?$/).max(50),now:c.boolean().default(!1)}),wa.extend({type:c.literal("ssh.keygen"),requestId:Q,comment:c.string().max(200),existing:c.string().min(1).max(1024).optional()}),c.object({type:c.literal("ssh.keys"),requestId:Q}),c.object({type:c.literal("ssh.hostkeys"),requestId:Q,host:ka,port:c.number().int().min(1).max(65535)}),c.object({type:c.literal("ssh.test"),requestId:Q,target:Lp}),c.object({type:c.literal("ssh.run"),requestId:Q,target:Lp,command:c.string().min(1).max(2e4)}),wa.extend({type:c.literal("ssh.forget"),requestId:Q})]),DS=Hv.extend({id:it,name:c.string(),version:c.string().nullable(),online:c.boolean(),lastSeenAt:R.nullable(),createdAt:R}),hN=c.object({name:c.string().trim().min(1).max(80).optional(),settings:qv.optional()}),vN=c.object({now:c.boolean().default(!1)}),yN=c.object({runners:c.array(DS),latestVersion:c.string().nullable()}),$N=c.object({code:c.string(),expiresAt:R}),bN=c.object({code:c.string().trim().min(4).max(20),name:c.string().trim().min(1).max(80),hostname:c.string().max(255).default(""),platform:c.string().max(50).default("")}),Yv=c.object({runner:c.object({id:it,name:c.string()}),token:c.string()}),_N=c.object({projectId:Ie,runnerId:it,runnerName:c.string(),path:c.string(),folders:c.array(c.string()).default([]),cli:Je,online:c.boolean(),isDefault:c.boolean().default(!0)}),xN=c.object({path:c.string().trim().min(1).max(1024)}),kN=c.object({runnerId:it,path:c.string().min(1).max(1024),cli:Je,add:c.boolean().optional()}),wN=c.object({path:c.string().min(1).max(1024),runnerId:it.optional()}),SN=c.object({runnerId:it});function Qv(e,t){let r=i=>i.split("-")[0].split(".").map(a=>Number.parseInt(a,10)||0),[o,n]=[r(e),r(t)];for(let i=0;i<3;i++)if((o[i]??0)!==(n[i]??0))return(o[i]??0)>(n[i]??0);return!1}var US=200,CS=c.object({threadId:q.nullable(),hasEarlier:c.boolean()});var UN=c.discriminatedUnion("type",[c.object({type:c.literal("message.send"),clientId:c.string().max(64).optional(),threadId:q.nullable().default(null),body:c.string().trim().max(Tp),attachments:c.array(Vn).max(Dv).default([]),clis:c.array(Je).max($a).optional()}).refine(e=>e.body.length>0||e.attachments.length>0,"Write something or attach a file"),c.object({type:c.literal("message.edit"),messageId:Bt.shape.id,body:c.string().trim().max(Tp)}),c.object({type:c.literal("thread.resolve"),threadId:q,resolved:c.boolean(),reason:Pp.optional()}),c.object({type:c.literal("thread.cli"),threadId:q,cli:Je.nullable()}),c.object({type:c.literal("thread.runner"),threadId:q,runnerId:c.union([it,c.literal(jv)]).nullable()}),c.object({type:c.literal("thread.model"),threadId:q,cli:Je,model:c.string().trim().min(1).max(200).nullable(),effort:c.string().trim().min(1).max(20).nullable()}),c.object({type:c.literal("goal.stop")}),c.object({type:c.literal("sync"),afterSeq:c.number().int().nonnegative(),all:c.boolean().optional(),recent:c.number().int().positive().max(US).optional()})]),CN=c.discriminatedUnion("type",[c.object({type:c.literal("message.created"),message:Bt}),c.object({type:c.literal("message.updated"),message:Bt}),c.object({type:c.literal("message.ack"),clientId:c.string(),messageId:Bt.shape.id,seq:Bt.shape.seq}),c.object({type:c.literal("sync.result"),messages:c.array(Bt),hasMore:c.boolean(),streamed:c.boolean().optional(),threads:c.array(jp).default([]),reactions:c.array(Op).default([]),artifacts:c.array(Np).default([]),routines:c.array(Ep).default([]),goal:Rp.nullable().optional(),windows:c.array(CS).optional(),reset:c.boolean().optional(),lastSeq:c.number().int().nonnegative().optional()}),c.object({type:c.literal("thread.updated"),thread:jp}),c.object({type:c.literal("reaction.added"),reaction:Op}),c.object({type:c.literal("artifact.updated"),artifact:Np}),c.object({type:c.literal("routine.updated"),routine:Ep}),c.object({type:c.literal("routine.deleted"),routineId:Dp}),c.object({type:c.literal("goal.updated"),goal:Rp.nullable()}),c.object({type:c.literal("agent.activity"),threadId:q.nullable(),active:c.boolean(),label:c.string().max(200).optional()}),c.object({type:c.literal("knowledge.changed"),kind:Uv}),c.object({type:c.literal("workspace.changed")}),c.object({type:c.literal("task.updated"),task:Av}),c.object({type:c.literal("task.output"),taskId:ze,threadId:q,lines:c.array(Ov)}),c.object({type:c.literal("pr.updated"),pullRequest:Tv}),c.object({type:c.literal("error"),code:c.string(),message:c.string()})]);var MN=c.object({app:c.literal("myrel"),apiVersion:c.number().int().positive(),name:c.string(),auth:c.object({emailPassword:c.boolean(),signUp:c.boolean().default(!0),emailVerification:c.boolean().default(!1),captcha:c.object({provider:c.literal("turnstile"),siteKey:c.string()}).nullable().default(null),passwordReset:c.boolean().default(!1)}),billing:c.boolean().default(!1),legal:c.object({terms:c.string().url(),privacy:c.string().url(),version:c.string()}).nullable().default(null)});var FN=c.object({question:c.string().min(1).max(300),options:c.array(c.object({label:c.string().min(1).max(40),consequence:c.string().max(200).default("")})).min(2).max(4),recommended:c.number().int().nonnegative().optional(),danger:c.boolean().optional()});var ei=c.enum(["fireworks","anthropic","openai"]),qN=c.object({id:ei,name:c.string(),defaultModel:c.string(),serverKey:c.boolean()}),HN=c.object({id:c.string(),provider:ei,label:c.string(),hint:c.string(),scope:c.enum(["user","instance"]),createdAt:c.iso.datetime()}),XN=c.object({provider:ei,label:c.string().trim().min(1).max(80),key:c.string().trim().min(8).max(500),scope:c.enum(["user","instance"]).default("user")}),ey=c.enum(["auto","local","cloud"]),ty=c.enum(["opencode","claude","codex"]),ES=c.object({model:c.string().trim().min(1).max(200).nullable(),effort:c.string().trim().min(1).max(20).nullable()}),ny=c.partialRecord(Je,ES),YN=c.object({name:c.string(),provider:ei.nullable(),model:c.string().nullable(),keyId:c.string().nullable(),taskTarget:ey,icon:xa.nullable().default(null),color:_a.nullable().default(null),cloudCli:ty.default("opencode"),cliModels:ny.default({})}),QN=c.object({name:c.string().trim().min(1).max(120).optional(),provider:ei.nullable().optional(),model:c.string().trim().max(200).nullable().optional(),keyId:c.string().nullable().optional(),taskTarget:ey.optional(),icon:xa.nullable().optional(),color:_a.nullable().optional(),cloudCli:ty.optional(),cliModels:ny.optional()}),ry=c.enum(["admin","member"]),eD=c.object({id:c.string(),projectId:c.string(),projectName:c.string(),email:c.string(),role:ry,invitedBy:c.string(),createdAt:c.iso.datetime()}),tD=c.object({email:c.email().trim().toLowerCase(),role:ry.default("member")}),nD=c.object({role:ba}),RS=c.enum(["admin","user"]),rD=c.enum(["computer","decision"]),iD=c.object({id:c.string(),name:c.string(),email:c.string(),role:RS,onboarded:c.boolean().optional(),tips:c.array(c.string()).optional()}),MS=c.object({signUpEnabled:c.boolean()}),LS=c.enum(["api","agent","cron","web","desktop","mobile"]),oD=c.object({platform:c.enum(["web","desktop","mobile"]),where:c.string().trim().min(1).max(200),name:c.string().max(100).default("Error"),message:c.string().max(500),stack:c.string().max(4e3).optional(),version:c.string().max(40).optional()}),aD=c.object({id:c.string(),source:LS,where:c.string(),name:c.string(),message:c.string(),stack:c.string().nullable(),count:c.number().int(),firstSeenAt:c.number(),lastSeenAt:c.number()}),sD=c.object({days:c.number().int(),signedUp:c.number().int(),verified:c.number().int(),inProject:c.number().int(),asked:c.number().int(),threadRan:c.number().int(),pairedComputer:c.number().int()}),cD=MS.partial();var iy=c.string().regex(pe("notification")),ZS=c.enum(["done","ready","decision","blocked","failed"]),fD=c.object({id:iy,projectId:Ie,threadId:q.nullable(),kind:ZS,title:c.string(),body:c.string(),url:c.string(),readAt:R.nullable(),createdAt:R}),mD=c.object({email:c.boolean(),push:c.boolean()}),gD=c.object({webPushKey:c.string().nullable(),email:c.boolean()}),FS=[/^fcm\.googleapis\.com$/,/^updates\.push\.services\.mozilla\.com$/,/^web\.push\.apple\.com$/,/^[a-z0-9-]+\.notify\.windows\.com$/];function VS(e){try{let t=new URL(e);return t.protocol==="https:"&&FS.some(r=>r.test(t.hostname))}catch{return!1}}var hD=c.discriminatedUnion("kind",[c.object({kind:c.literal("webpush"),endpoint:c.url().max(2048).refine(VS,"Not a browser push service"),keys:c.object({p256dh:c.string().min(1).max(256),auth:c.string().min(1).max(64)})}),c.object({kind:c.literal("expo"),token:c.string().regex(/^Expo(nent)?PushToken\[[^\]]+\]$/).max(256)})]),vD=c.union([c.object({ids:c.array(iy).min(1).max(200)}),c.object({all:c.literal(!0)})]);var KS=new RegExp(pe("thread").source.slice(1,-1)),kD=new RegExp(`^#(${KS.source})$`);var JS=c.enum(["http","stdio"]),BS=c.enum(["user","project"]),Jp=c.enum(["cloud","local","both"]),WS=c.enum(["unknown","ok","error","needs_auth"]),GS=c.enum(["none","headers","oauth"]),oy=c.string().regex(/^[a-z][a-z0-9_-]{0,31}$/).refine(e=>e!=="myrel","That name is taken by Myrel's own tools."),qS=c.object({name:c.string(),description:c.string().optional()}),HS=/^[A-Za-z_][\w-]{0,99}$/,XS=/^[A-Za-z_][A-Za-z0-9_]{0,99}$/,ay=(e,t,r)=>c.record(c.string().regex(e),c.string().max(4e3),{error:o=>o.code==="invalid_key"?`${t} name ${JSON.stringify(o.input)} is not valid: use only ${r}, with no spaces or ":". Put the value in its own field.`:void 0}),sy=ay(HS,"Header","letters, digits, - and _"),YS=ay(XS,"Variable","letters, digits and _"),ID=c.object({id:c.string(),name:c.string(),slug:c.string(),scope:BS,transport:JS,url:c.string().nullable(),auth:GS,command:c.string().nullable(),args:c.array(c.string()),runsOn:Jp,secretNames:c.array(c.string()),enabled:c.boolean(),status:WS,lastError:c.string().nullable(),tools:c.array(qS),canEdit:c.boolean(),createdAt:c.iso.datetime(),official:c.object({id:c.string(),title:c.string(),iconUrl:c.string().nullable()}).nullable().default(null)}),Kp=c.string().trim().min(1).max(60),zD=c.discriminatedUnion("transport",[c.object({transport:c.literal("http"),name:Kp,slug:oy.optional(),url:c.url({protocol:/^https$/}).max(2e3),auth:c.enum(["headers","oauth"]).default("headers"),headers:sy.default({})}),c.object({transport:c.literal("stdio"),name:Kp,slug:oy.optional(),command:c.string().trim().min(1).max(200),args:c.array(c.string().max(2e3)).max(50).default([]),env:YS.default({}),runsOn:Jp.default("both")})]),PD=c.object({name:Kp.optional(),enabled:c.boolean().optional(),url:c.url({protocol:/^https$/}).max(2e3).optional(),command:c.string().trim().min(1).max(200).optional(),args:c.array(c.string().max(2e3)).max(50).optional(),runsOn:Jp.optional(),secrets:sy.optional()});var jD=c.object({authorizeUrl:c.url()});var QS=["developer","productivity","communication","design","data","sales","finance","search","ai","other"],cy=c.enum(QS);var eI=c.object({id:c.string(),title:c.string(),description:c.string(),websiteUrl:c.string().nullable(),iconUrl:c.string().nullable(),url:c.string(),auth:c.enum(["oauth","headers"]),headerHint:c.object({name:c.string(),placeholder:c.string()}).nullable(),category:cy,official:c.boolean()}),AD=c.object({connectors:c.array(eI),nextOffset:c.number().nullable(),syncedAt:c.iso.datetime().nullable(),categories:c.array(c.object({id:cy,count:c.number()}))}),tI=[{id:"com.notion/mcp",category:"productivity"},{id:"app.linear/linear",category:"productivity"},{id:"com.atlassian/atlassian-mcp-server",category:"productivity"},{id:"com.figma.mcp/mcp",category:"design"},{id:"com.stripe/mcp",category:"finance"},{id:"com.canva.mcp/mcp",category:"design"},{id:"com.vercel/vercel-mcp",category:"developer"},{id:"com.gitlab/mcp",category:"developer"},{id:"io.github.PostHog/mcp",category:"data"},{id:"com.zapier/mcp",category:"productivity"},{id:"com.airtable/mcp",category:"data"},{id:"com.monday/monday.com",category:"productivity"},{id:"com.paypal.mcp/mcp",category:"finance"},{id:"com.webflow/mcp",category:"design"},{id:"com.wix/mcp",category:"design"},{id:"com.neon/mcp",category:"developer"},{id:"com.railway/mcp",category:"developer"},{id:"co.huggingface/hf-mcp-server",category:"ai"},{id:"com.cloudflare.mcp/mcp",category:"developer"},{id:"com.apify/apify-mcp-server",category:"search"},{id:"ai.exa/exa",category:"search"},{id:"com.microsoft/microsoft-learn-mcp",category:"search"}],OD=tI.map(e=>e.id);var nI=c.enum(["user","project"]),rI=c.string().max(64).regex(/^[a-z0-9]+(-[a-z0-9]+)*$/,"Use lowercase letters, digits and hyphens, like pdf-forms."),uy=c.string().trim().min(1).max(1024),iI=c.string().min(1).max(300).regex(/^[\w@+=,.~ -]+(\/[\w@+=,.~ -]+)*$/,"Invalid file path.").refine(e=>!e.split("/").some(t=>t==="."||t===".."),"Invalid file path."),ly={files:200,bytes:5*1024*1024,fileBytes:1024*1024};var oI=c.discriminatedUnion("kind",[c.object({kind:c.literal("write")}),c.object({kind:c.literal("upload")}),c.object({kind:c.literal("github"),repo:c.string(),path:c.string(),ref:c.string().optional(),commit:c.string()})]),aI=c.object({path:c.string(),size:c.number().int().nonnegative()}),sI=c.object({id:c.string(),name:c.string(),description:c.string(),scope:nI,source:oI,enabled:c.boolean(),files:c.array(aI),size:c.number().int().nonnegative(),canEdit:c.boolean(),createdAt:c.iso.datetime(),updatedAt:c.iso.datetime()}),DD=sI.extend({skillMd:c.string()}),cI=c.object({path:iI,content:c.string().max(Math.ceil(ly.fileBytes*4/3)+4)}),UD=c.discriminatedUnion("kind",[c.object({kind:c.literal("write"),name:rI,description:uy,instructions:c.string().max(1e5)}),c.object({kind:c.literal("upload"),files:c.array(cI).min(1).max(ly.files)}),c.object({kind:c.literal("github"),source:c.string().trim().min(3).max(500),skill:c.string().max(64).optional()})]),CD=c.object({error:c.literal("choose_skill"),skills:c.array(c.object({name:c.string(),description:c.string(),path:c.string()}))}),ED=c.object({enabled:c.boolean().optional(),description:uy.optional(),instructions:c.string().max(1e5).optional()}),RD=c.object({skills:c.array(c.object({name:c.string(),files:c.array(c.object({path:c.string(),content:c.string()}))}))});var MD=c.object({on:c.boolean()});var uI=c.object({id:c.string().min(1).max(200),name:c.string().min(1).max(80),description:c.string().max(300).default(""),url:c.string().max(2e3),auth:c.enum(["oauth","headers"]),headerHint:c.object({name:c.string(),placeholder:c.string()}).nullable().default(null),iconUrl:c.string().nullable().default(null),official:c.boolean().default(!1),featured:c.boolean().default(!1)}),lI=c.enum(["open","connected","dismissed"]),FD=c.object({id:c.string(),reason:c.string().min(1).max(400),offers:c.array(uI).min(1).max(3),state:lI.default("open"),connected:c.string().optional(),signIn:c.boolean().optional()});var VD=c.object({offerId:c.string().min(1).max(200),headers:c.record(c.string().regex(/^[A-Za-z_][\w-]{0,99}$/),c.string().min(1).max(4e3)).optional()}),KD=c.object({authorizeUrl:c.string().optional(),connected:c.boolean()});var dI=/^(?:\/(?:usr\/)?(?:local\/)?bin\/)?(?:ba|z|da|k)?sh\s+-l?c\s+(\S[\s\S]*)$/;function Kn(e){let t=dI.exec(e.trim());return t?pI(t[1])??e:e}function pI(e){let t="",r=0;for(;r<e.length;){let o=e[r];if(o==="'"){let n=e.indexOf("'",r+1);if(n<0)return null;t+=e.slice(r+1,n),r=n+1}else if(o==='"'){for(r++;;){if(r>=e.length)return null;let n=e[r];if(n==='"')break;n==="\\"&&r+1<e.length&&'"\\$`\n'.includes(e[r+1])?(t+=e[r+1],r+=2):(t+=n,r++)}r++}else if(o==="\\"){if(r+1>=e.length)return null;t+=e[r+1],r+=2}else{if(/\s/.test(o)||"|&;<>()$`".includes(o))return null;t+=o,r++}}return t}import{mkdir as fI,readFile as mI,rename as gI,writeFile as hI}from"node:fs/promises";import{homedir as fy}from"node:os";import{dirname as vI,join as dy}from"node:path";var my="MYREL_MCP_BRIDGE";function yI(e=fy()){return{mcp:dy(e,".gemini","config","mcp_config.json"),settings:dy(e,".gemini","antigravity-cli","settings.json")}}function ti(){let e=process.argv[1],t=!e||/\$bunfs|~BUN/.test(e);return{command:process.execPath,args:t?[]:[e]}}async function gy(e,t=fy()){let r=yI(t),o=ti(),n={command:o.command,args:[...o.args,"mcp-bridge"]};await py(r.mcp,a=>{let s=Bp(a.mcpServers)?a.mcpServers:{};return JSON.stringify(s[e])===JSON.stringify(n)?!1:(a.mcpServers={...s,[e]:n},!0)});let i=`mcp(${e}/*)`;await py(r.settings,a=>{let s=Bp(a.permissions)?a.permissions:{},u=Array.isArray(s.allow)?s.allow:[];return u.includes(i)?!1:(a.permissions={...s,allow:[...u,i]},!0)})}async function py(e,t){let r=await mI(e,"utf8").catch(i=>{if(i.code==="ENOENT")return"";throw i}),o={};if(r.trim())try{o=JSON.parse(r)}catch{throw new Error(`Could not read ${e} as JSON, so Myrel's tools were not added to Antigravity CLI. Fix the file and try again.`)}if(!Bp(o))throw new Error(`${e} is not a JSON object, so Myrel's tools were not added to Antigravity CLI.`);if(!t(o))return;await fI(vI(e),{recursive:!0});let n=`${e}.myrel-${process.pid}`;await hI(n,`${JSON.stringify(o,null,2)}
|
|
62
|
+
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let a of e.seen.entries()){let s=a[1];if(t===a[0]){i(a);continue}if(e.external){let l=e.external.registry.get(a[0])?.id;if(t!==a[0]&&l){i(a);continue}}if(e.metadataRegistry.get(a[0])?.id){i(a);continue}if(s.cycle){i(a);continue}s.count>1&&e.reused==="ref"&&i(a)}e.external&&(e.sharedDefsExtractedFor=e.external)}function Mg(e){let t=e.anyOf;if(!Array.isArray(t)||t.length===0||e.type!==void 0)return;let r=[];for(let o of t){if(!o||typeof o!="object")return;Mg(o);let n=Object.keys(o);if(n.length!==1||n[0]!=="type")return;let i=o.type;for(let a of Array.isArray(i)?i:[i]){if(typeof a!="string")return;r.includes(a)||r.push(a)}}delete e.anyOf,e.type=r.length===1?r[0]:r}var Lg=new Set(["type","properties","required","additionalProperties"]),Eg=["oneOf","anyOf"];function Rg(e){let t=e.additionalProperties;return t===void 0||t===!1||typeof t!="object"||t===null?null:Object.keys(t).length?t:null}function Al(e){let t=[];for(let i of e){if(typeof i!="object"||i.type!=="object")return null;for(let a in i)if(!Lg.has(a))return null;t.push(i)}let r={},o=new Set;for(let i of t){for(let a in i.properties){if(Object.prototype.hasOwnProperty.call(r,a))continue;let s=[];for(let l of t){let d=l.properties?.[a]??Rg(l);d!=null&&(s.some(p=>JSON.stringify(p)===JSON.stringify(d))||s.push(d))}let u=s.length===1?s[0]:Al(s)??{allOf:s};ue(r,a,u)}for(let a of i.required??[])o.add(a)}let n={type:"object",properties:r};if(o.size&&(n.required=[...o]),t.every(i=>i.additionalProperties===!1))n.additionalProperties=!1;else{let i=[];for(let a of t){let s=Rg(a);s&&!i.some(u=>JSON.stringify(u)===JSON.stringify(s))&&i.push(s)}i.length===1?n.additionalProperties=i[0]:i.length>1&&(n.additionalProperties={allOf:i})}return n}function mw(e){let t=e.allOf;if(!Array.isArray(t)||t.length<2)return;for(let n of Lg)if(n in e)return;let r=t.filter(n=>Eg.some(i=>Array.isArray(n[i]))),o=null;if(!r.length)o=Al(t);else{let n=r[0],i=Eg.find(u=>Array.isArray(n[u]));if(Object.keys(n).length!==1)return;let a=t.filter(u=>u!==n),s=n[i].map(u=>Al([...a,u]));if(s.some(u=>!u))return;o={[i]:s}}o&&(delete e.allOf,Cr(e,o))}function yt(e,t){let r=e.seen.get(t);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");let o=s=>{let u=e.seen.get(s);if(u.ref===null)return;let l=u.def??u.schema,d={...l},p=u.ref;if(u.ref=null,p){o(p);let f=e.seen.get(p),v=f.schema;if(v.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0")?(l.allOf=l.allOf??[],l.allOf.push(v)):Cr(l,v),Cr(l,d),s._zod.parent===p)for(let x in l)x==="$ref"||x==="allOf"||x in d||delete l[x];if(v.$ref&&f.def)for(let x in l)x==="$ref"||x==="allOf"||x in f.def&&JSON.stringify(l[x])===JSON.stringify(f.def[x])&&delete l[x]}let m=s._zod.parent;if(m&&m!==p){o(m);let f=e.seen.get(m);if(f?.schema.$ref&&(l.$ref=f.schema.$ref,f.def))for(let v in l)v==="$ref"||v==="allOf"||v in f.def&&JSON.stringify(l[v])===JSON.stringify(f.def[v])&&delete l[v]}e.override({zodSchema:s,jsonSchema:l,path:u.path??[]})};if(!e.external||e.sharedEmitDoneFor!==e.external){for(let s of[...e.seen.entries()].reverse())o(s[0]);if(e.target!=="openapi-3.0")for(let s of e.seen.entries())Mg(s[1].def??s[1].schema);for(let s of e.deferred)s();if(e.intersections.length){let s=new Map;for(let u of e.seen.values())for(let l of[u.schema,u.def]){let d=l?.allOf;if(!Array.isArray(d))continue;let p=s.get(d);p?p.push(l):s.set(d,[l])}for(let u of e.intersections)for(let l of s.get(u)??[])mw(l)}}let n={};if(e.target==="draft-2020-12"?n.$schema="https://json-schema.org/draft/2020-12/schema":e.target==="draft-07"?n.$schema="http://json-schema.org/draft-07/schema#":e.target==="draft-04"?n.$schema="http://json-schema.org/draft-04/schema#":e.target,e.external?.uri){let s=e.external.registry.get(t)?.id;if(!s)throw new Error("Schema is missing an `id` property");n.$id=e.external.uri(s)}Cr(n,r.defId?r.schema:r.def??r.schema);let i=e.metadataRegistry.get(t)?.id;i!==void 0&&n.id===i&&delete n.id;let a=e.external?.defs??{};if(!e.external||e.sharedEmitDoneFor!==e.external)for(let s of e.seen.entries()){let u=s[1];u.def&&u.defId&&(u.def.id===u.defId&&delete u.def.id,ue(a,u.defId,u.def))}e.external&&(e.sharedEmitDoneFor=e.external),e.external||Object.keys(a).length>0&&(e.target==="draft-2020-12"?n.$defs=a:n.definitions=a);try{let s=JSON.parse(JSON.stringify(n));return Object.defineProperty(s,"~standard",{value:{...t["~standard"],jsonSchema:{input:Tn(t,"input",e.processors),output:Tn(t,"output",e.processors)}},enumerable:!1,writable:!1}),s}catch{throw new Error("Error converting schema to JSON.")}}function ve(e,t){let r=t??{seen:new Set};if(r.seen.has(e))return!1;r.seen.add(e);let o=e._zod.def;if(o.type==="transform")return!0;if(o.type==="array")return ve(o.element,r);if(o.type==="set")return ve(o.valueType,r);if(o.type==="lazy")return ve(o.getter(),r);if(o.type==="promise"||o.type==="optional"||o.type==="nonoptional"||o.type==="nullable"||o.type==="readonly"||o.type==="default"||o.type==="prefault"||o.type==="catch")return ve(o.innerType,r);if(o.type==="intersection")return ve(o.left,r)||ve(o.right,r);if(o.type==="record"||o.type==="map")return ve(o.keyType,r)||ve(o.valueType,r);if(o.type==="pipe")return e._zod.traits.has("$ZodCodec")?!0:ve(o.in,r)||ve(o.out,r);if(o.type==="object"){for(let n in o.shape)if(ve(o.shape[n],r))return!0;return!1}if(o.type==="union"){for(let n of o.options)if(ve(n,r))return!0;return!1}if(o.type==="tuple"){for(let n of o.items)if(ve(n,r))return!0;return!!(o.rest&&ve(o.rest,r))}return!1}var Ol=(e,t={})=>r=>{let o=ht({...r,processors:t});return K(e,o),vt(o,e),yt(o,e)},Tn=(e,t,r={})=>o=>{let{libraryOptions:n,target:i}=o??{},a=ht({...n??{},target:i,io:t,processors:r});return K(e,a),vt(a,e),yt(a,e)};var Nn=(e,t,r)=>{(e[t]===void 0||r>e[t])&&(e[t]=r)},Dn=(e,t,r)=>{(e[t]===void 0||r<e[t])&&(e[t]=r)},Zg=(e,t)=>{Nn(e,"minimum",t),Dn(e,"maximum",t)},Jg=(e,t)=>{e.multipleOf??(e.multipleOf=[]),e.multipleOf.includes(t)||e.multipleOf.push(t)},Bg=(e,t)=>{e.patterns??(e.patterns=new Set),e.patterns.add(t)},Wg=(e,t)=>{e.mime=e.mime?e.mime.filter(r=>t.includes(r)):[...t]},Gg=(e,t)=>{e.format=t,t.includes("int")&&(e.isInt=!0)},Fg=(e,t)=>Nn(e,"minimum",t.minimum),Vg=(e,t)=>Dn(e,"maximum",t.maximum),Kg=e=>(t,r)=>{Gg(t,r.format);let[o,n]=e[r.format];Nn(t,"minimum",o),Dn(t,"maximum",n)},gw={greater_than:(e,t)=>Nn(e,t.inclusive?"minimum":"exclusiveMinimum",t.value),less_than:(e,t)=>Dn(e,t.inclusive?"maximum":"exclusiveMaximum",t.value),multiple_of:(e,t)=>Jg(e,t.value),number_format:Kg(rr),bigint_format:Kg(ir),min_length:Fg,max_length:Vg,length_equals:(e,t)=>Zg(e,t.length),min_size:Fg,max_size:Vg,size_equals:(e,t)=>Zg(e,t.size),string_format:(e,t)=>{Gg(e,t.format),t.pattern&&Bg(e,t.pattern),(t.format==="base64"||t.format==="base64url")&&(e.contentEncoding=t.format),(t.local||t.precision===-1)&&(e.laxFormat=!0)},mime_type:(e,t)=>Wg(e,t.mime)};function ae(e){let t={},r=e._zod.def,o=e._zod.traits.has("$ZodCheck")?[e,...r.checks??[]]:r.checks??[];for(let i of o)gw[i._zod.def.check]?.(t,i._zod.def);let n=e._zod.bag;n.minimum!==void 0&&Nn(t,"minimum",n.minimum),n.exclusiveMinimum!==void 0&&Nn(t,"exclusiveMinimum",n.exclusiveMinimum),n.maximum!==void 0&&Dn(t,"maximum",n.maximum),n.exclusiveMaximum!==void 0&&Dn(t,"exclusiveMaximum",n.exclusiveMaximum),n.multipleOf!==void 0&&Jg(t,n.multipleOf),n.format!==void 0&&(t.format??(t.format=n.format),n.format.includes("int")&&(t.isInt=!0)),n.mime&&Wg(t,n.mime);for(let i of n.patterns??[])Bg(t,i);return t}var hw={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},vw=new Map([[Vi,Es],[_r,Rs]]),qg=e=>vw.get(e)??e,Dl=(e,t,r,o)=>{let n=r;n.type="string";let{minimum:i,maximum:a,format:s,patterns:u,contentEncoding:l,laxFormat:d}=ae(e);if(typeof i=="number"&&(n.minLength=i),typeof a=="number"&&(n.maxLength=a),s&&(n.format=hw[s]??s,n.format===""&&delete n.format,(s==="time"||d)&&delete n.format),l&&(n.contentEncoding=l),u&&u.size>0){let p=[...u].map(qg);p.length===1?n.pattern=p[0].source:p.length>1&&(n.allOf=[...p.map(m=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:m.source}))])}},Ul=(e,t,r,o)=>{let n=r,{minimum:i,maximum:a,multipleOf:s,exclusiveMaximum:u,exclusiveMinimum:l,isInt:d}=ae(e);n.type=d?"integer":"number";let p=typeof l=="number"&&l>=(i??Number.NEGATIVE_INFINITY),m=typeof u=="number"&&u<=(a??Number.POSITIVE_INFINITY),f=t.target==="draft-04"||t.target==="openapi-3.0";if(p?f?(n.minimum=l,n.exclusiveMinimum=!0):n.exclusiveMinimum=l:typeof i=="number"&&(n.minimum=i),m?f?(n.maximum=u,n.exclusiveMaximum=!0):n.exclusiveMaximum=u:typeof a=="number"&&(n.maximum=a),s){let v=new Set;for(let j of s)Number.isFinite(j)&&j!==0?v.add(Math.abs(j)):oe(e,t,n,o,`A multipleOf divisor of ${j} cannot be represented in JSON Schema`);let[y,...x]=v;y!==void 0&&(n.multipleOf=y),x.length&&(n.allOf=[...n.allOf??[],...x.map(j=>({multipleOf:j}))])}},Cl=(e,t,r,o)=>{r.type="boolean"},El=(e,t,r,o)=>{oe(e,t,r,o,"BigInt cannot be represented in JSON Schema")},Rl=(e,t,r,o)=>{oe(e,t,r,o,"Symbols cannot be represented in JSON Schema")},Ml=(e,t,r,o)=>{t.target==="openapi-3.0"?(r.type="string",r.nullable=!0,r.enum=[null]):r.type="null"},Ll=(e,t,r,o)=>{oe(e,t,r,o,"Undefined cannot be represented in JSON Schema")},Zl=(e,t,r,o)=>{oe(e,t,r,o,"Void cannot be represented in JSON Schema")},Fl=(e,t,r,o)=>{r.not={}},Vl=(e,t,r,o)=>{},Kl=(e,t,r,o)=>{},Jl=(e,t,r,o)=>{oe(e,t,r,o,"Date cannot be represented in JSON Schema")},Bl=(e,t,r,o)=>{let n=e._zod.def,i=rn(n.entries);if(i.length===0){r.not={};return}i.every(a=>typeof a=="number")&&(r.type="number"),i.every(a=>typeof a=="string")&&(r.type="string"),r.enum=i},Wl=(e,t,r,o)=>{let n=e._zod.def;if(n.values.length===0){r.not={};return}let i=[];for(let a of n.values)if(a===void 0){if(oe(e,t,r,o,"Literal `undefined` cannot be represented in JSON Schema"))return}else if(typeof a=="bigint"){if(oe(e,t,r,o,"BigInt literals cannot be represented in JSON Schema"))return;i.push(Number(a))}else i.push(a);if(i.length!==0)if(i.length===1){let a=i[0];r.type=a===null?"null":typeof a,t.target==="draft-04"||t.target==="openapi-3.0"?r.enum=[a]:r.const=a}else i.every(a=>typeof a=="number")&&(r.type="number"),i.every(a=>typeof a=="string")&&(r.type="string"),i.every(a=>typeof a=="boolean")&&(r.type="boolean"),i.every(a=>a===null)&&(r.type="null"),r.enum=i},Gl=(e,t,r,o)=>{oe(e,t,r,o,"NaN cannot be represented in JSON Schema")},ql=(e,t,r,o)=>{let n=r,i=e._zod.pattern;if(!i)throw new Error("Pattern not found in template literal");n.type="string",n.pattern=i.source},Hl=(e,t,r,o)=>{let n=r;n.type="string",n.format="binary",n.contentEncoding="binary";let{minimum:i,maximum:a,mime:s}=ae(e);i!==void 0&&(n.minLength=i),a!==void 0&&(n.maxLength=a),s&&(s.length===0?n.not={}:s.length===1?n.contentMediaType=s[0]:n.anyOf=s.map(u=>({contentMediaType:u})))},Xl=(e,t,r,o)=>{r.type="boolean"},Yl=(e,t,r,o)=>{oe(e,t,r,o,"Custom types cannot be represented in JSON Schema")},Ql=(e,t,r,o)=>{oe(e,t,r,o,"Function types cannot be represented in JSON Schema")},ed=(e,t,r,o)=>{oe(e,t,r,o,"Transforms cannot be represented in JSON Schema")},td=(e,t,r,o)=>{oe(e,t,r,o,"Map cannot be represented in JSON Schema")},nd=(e,t,r,o)=>{oe(e,t,r,o,"Set cannot be represented in JSON Schema")},rd=(e,t,r,o)=>{let n=r,i=e._zod.def,{minimum:a,maximum:s}=ae(e);typeof a=="number"&&(n.minItems=a),typeof s=="number"&&(n.maxItems=s),n.type="array",n.items=K(i.element,t,{...o,path:[...o.path,"items"]})};function Er(e){let t=e._zod.def;return t.type==="pipe"&&t.in._zod.traits.has("$ZodTransform")?Er(t.out):t.type==="catch"?Er(t.innerType):e._zod.optin}var id=(e,t,r,o)=>{let n=r,i=e._zod.def,a=i.shape;if(Object.getOwnPropertySymbols(a).length&&oe(e,t,n,o,"Symbol keys cannot be represented in JSON Schema"))return;n.type="object",n.properties={};for(let l in a)ue(n.properties,l,K(a[l],t,{...o,path:[...o.path,"properties",l]}));let u=[];for(let l of Object.keys(a)){let d=i.shape[l];(t.io==="input"?Er(d)===void 0:d._zod.optout===void 0)&&u.push(l)}u.length>0&&(n.required=u),i.catchall?._zod.def.type==="never"?n.additionalProperties=!1:i.catchall?i.catchall&&(n.additionalProperties=K(i.catchall,t,{...o,path:[...o.path,"additionalProperties"]})):t.io==="output"&&(n.additionalProperties=!1)},Zo=(e,t,r,o)=>{let n=e._zod.def,i=n.inclusive===!1,a=n.options.map((s,u)=>K(s,t,{...o,path:[...o.path,i?"oneOf":"anyOf",u]}));i?r.oneOf=a:r.anyOf=a},od=(e,t,r,o)=>{let n=e._zod.def,i=K(n.left,t,{...o,path:[...o.path,"allOf",0]}),a=K(n.right,t,{...o,path:[...o.path,"allOf",1]}),s=l=>"allOf"in l&&Object.keys(l).length===1,u=[...s(i)?i.allOf:[i],...s(a)?a.allOf:[a]];r.allOf=u,t.intersections.push(u)},ad=(e,t,r,o)=>{let n=r,i=e._zod.def;n.type="array";let a=t.target==="draft-2020-12"?"prefixItems":"items",s=t.target==="draft-2020-12"||t.target==="openapi-3.0"?"items":"additionalItems",u=i.items.map((y,x)=>K(y,t,{...o,path:[...o.path,a,x]})),l=i.rest?K(i.rest,t,{...o,path:[...o.path,s,...t.target==="openapi-3.0"?[i.items.length]:[]]}):null,d=i.items.length;for(;d>0;){let y=i.items[d-1];if(!(t.io==="input"?Er(y)!==void 0:y._zod.optout==="optional"))break;d--}let p=i.items.length,m=!i.rest;t.target==="draft-2020-12"?(n.prefixItems=u,m?n.items=!1:l&&(n.items=l),d>0&&(n.minItems=d),m&&(n.maxItems=p)):t.target==="openapi-3.0"?(n.items={anyOf:u},l&&n.items.anyOf.push(l),d>0&&(n.minItems=d),m&&(n.maxItems=p)):(n.items=u,m?n.additionalItems=!1:l&&(n.additionalItems=l),d>0&&(n.minItems=d),m&&(n.maxItems=p));let{minimum:f,maximum:v}=ae(e);typeof f=="number"&&(n.minItems=f),typeof v=="number"&&(n.maxItems=v)};function Tl(e,t,r){if(t.$ref){if(r.has(t))return t;r.add(t);let v=e.get(t)?.def;if(!v)return t;let y=Tl(e,v,r);return y===v?t:y}for(let v of["anyOf","oneOf"]){let y=t[v];if(!Array.isArray(y))continue;let x=y.map(j=>Tl(e,j,r));x.some((j,P)=>j!==y[P])&&(t={...t,[v]:x})}let o=Array.isArray(t.type)?t.type:[t.type],n=!o.includes("string")&&o.some(v=>v==="number"||v==="integer"),i=t.enum??(t.const!==void 0?[t.const]:void 0);if(!n&&!i?.some(v=>typeof v=="number"))return t;let{minimum:a,maximum:s,exclusiveMinimum:u,exclusiveMaximum:l,multipleOf:d,format:p,id:m,...f}=t;return f.enum?f.enum=f.enum.map(v=>typeof v=="number"?String(v):v):typeof f.const=="number"&&(f.const=String(f.const)),n&&(f.type="string",i||(f.pattern=(o.includes("number")?tt:mr).source)),f}var Nl=new WeakMap;function yw(e){let t=new Map;for(let o of e.seen.values())o.def&&!t.has(o.schema)&&t.set(o.schema,o);let r=new Map;for(let o of Nl.get(e)??[]){let n=e.seen.get(o),i=(n?.def??n?.schema)?.propertyNames;if(!i||i===!0||r.has(i))continue;let a=Tl(t,i,new Set);a!==i&&r.set(i,a)}if(r.size)for(let o of e.seen.values())for(let n of[o.schema,o.def]){let i=n&&r.get(n.propertyNames);i&&(n.propertyNames=i)}}var sd=(e,t,r,o)=>{let n=r,i=e._zod.def;n.type="object";let a=i.keyType,s=ae(a).patterns;if(i.mode==="loose"&&s&&s.size>0){let d=K(i.valueType,t,{...o,path:[...o.path,"patternProperties","*"]});n.patternProperties={};for(let p of s)ue(n.patternProperties,qg(p).source,d)}else{if(t.target==="draft-07"||t.target==="draft-2020-12"){n.propertyNames=K(i.keyType,t,{...o,path:[...o.path,"propertyNames"]});let d=Nl.get(t);d||(d=[],Nl.set(t,d),t.deferred.push(()=>yw(t))),d.push(e)}n.additionalProperties=K(i.valueType,t,{...o,path:[...o.path,"additionalProperties"]})}let u=a._zod.values,l=t.io==="input"&&Er(i.valueType)!==void 0;if(u&&!i.partial&&!l){let d=[...u].filter(p=>typeof p=="string"||typeof p=="number");d.length>0&&(n.required=d.map(String))}},cd=(e,t,r,o)=>{let n=e._zod.def,i=K(n.innerType,t,o),a=t.seen.get(e);t.target==="openapi-3.0"?(a.ref=n.innerType,r.nullable=!0):r.anyOf=[i,{type:"null"}]},ud=(e,t,r,o)=>{let n=e._zod.def;K(n.innerType,t,o);let i=t.seen.get(e);i.ref=n.innerType},ld=Symbol();function Hg(e,t,r,o,n){let i=!1,a=JSON.stringify(e,(s,u)=>typeof u!="bigint"?u:(i=!0,null));return i?(oe(t,r,o,n,"BigInt defaults cannot be represented in JSON Schema"),ld):JSON.parse(a)}var dd=(e,t,r,o)=>{let n=e._zod.def;K(n.innerType,t,o);let i=t.seen.get(e);i.ref=n.innerType;let a=Hg(n.defaultValue,e,t,r,o);a!==ld&&(r.default=a)},pd=(e,t,r,o)=>{let n=e._zod.def;K(n.innerType,t,o);let i=t.seen.get(e);if(i.ref=n.innerType,t.io!=="input")return;let a=Hg(n.defaultValue,e,t,r,o);a!==ld&&(r._prefault=a)},fd=(e,t,r,o)=>{let n=e._zod.def;K(n.innerType,t,o);let i=t.seen.get(e);i.ref=n.innerType;let a;try{a=n.catchValue(void 0)}catch{oe(e,t,r,o,"Dynamic catch values are not supported in JSON Schema");return}r.default=a},md=(e,t,r,o)=>{let n=e._zod.def,i=n.in._zod.traits.has("$ZodTransform"),a=t.io==="input"?i?n.out:n.in:n.out;K(a,t,o);let s=t.seen.get(e);s.ref=a},gd=(e,t,r,o)=>{let n=e._zod.def;K(n.innerType,t,o);let i=t.seen.get(e);i.ref=n.innerType,r.readOnly=!0},hd=(e,t,r,o)=>{let n=e._zod.def;K(n.innerType,t,o);let i=t.seen.get(e);i.ref=n.innerType},Fo=(e,t,r,o)=>{let n=e._zod.def;K(n.innerType,t,o);let i=t.seen.get(e);i.ref=n.innerType},vd=(e,t,r,o)=>{let n=e._zod.innerType;K(n,t,o);let i=t.seen.get(e);i.ref=n},Lo={string:Dl,number:Ul,boolean:Cl,bigint:El,symbol:Rl,null:Ml,undefined:Ll,void:Zl,never:Fl,any:Vl,unknown:Kl,date:Jl,enum:Bl,literal:Wl,nan:Gl,template_literal:ql,file:Hl,success:Xl,custom:Yl,function:Ql,transform:ed,map:td,set:nd,array:rd,object:id,union:Zo,intersection:od,tuple:ad,record:sd,nullable:cd,nonoptional:ud,default:dd,prefault:pd,catch:fd,pipe:md,readonly:gd,promise:hd,optional:Fo,lazy:vd};function Vo(e,t){if("_idmap"in e){let o=e,n=ht({...t,processors:Lo}),i={};for(let u of o._idmap.entries()){let[l,d]=u;K(d,n)}let a={},s={registry:o,uri:t?.uri,defs:i};n.external=s;for(let u of o._idmap.entries()){let[l,d]=u;vt(n,d),ue(a,l,yt(n,d))}if(Object.keys(i).length>0){let u=n.target==="draft-2020-12"?"$defs":"definitions";a.__shared={[u]:i}}return{schemas:a}}let r=ht({...t,processors:Lo});return K(e,r),vt(r,e),yt(r,e)}var Ko=class{get metadataRegistry(){return this.ctx.metadataRegistry}get target(){return this.ctx.target}get unrepresentable(){return this.ctx.unrepresentable}get override(){return this.ctx.override}get io(){return this.ctx.io}get counter(){return this.ctx.counter}set counter(t){this.ctx.counter=t}get seen(){return this.ctx.seen}constructor(t){let r=t?.target??"draft-2020-12";r==="draft-4"&&(r="draft-04"),r==="draft-7"&&(r="draft-07"),this.ctx=ht({processors:Lo,target:r,...t?.metadata&&{metadata:t.metadata},...t?.unrepresentable&&{unrepresentable:t.unrepresentable},...t?.override&&{override:t.override},...t?.io&&{io:t.io}})}process(t,r={path:[],schemaPath:[]}){return K(t,this.ctx,r)}emit(t,r){r&&(r.cycles&&(this.ctx.cycles=r.cycles),r.reused&&(this.ctx.reused=r.reused),r.external&&(this.ctx.external=r.external)),this.ctx.sharedDefsExtractedFor=void 0,this.ctx.sharedEmitDoneFor=void 0,vt(this.ctx,t);let o=yt(this.ctx,t),{"~standard":n,...i}=o;return i}};var Xg={};var Fn={};Ye(Fn,{ZodAny:()=>Md,ZodArray:()=>Vd,ZodBase64:()=>ua,ZodBase64URL:()=>la,ZodBigInt:()=>Ln,ZodBigIntFormat:()=>fa,ZodBoolean:()=>Mn,ZodCIDRv4:()=>sa,ZodCIDRv6:()=>ca,ZodCUID:()=>ea,ZodCUID2:()=>ta,ZodCatch:()=>lp,ZodCodec:()=>Wr,ZodCreditCard:()=>Od,ZodCustom:()=>Gr,ZodCustomStringFormat:()=>Kt,ZodDate:()=>Zr,ZodDefault:()=>ip,ZodDiscriminatedUnion:()=>Jd,ZodE164:()=>da,ZodEmail:()=>Ho,ZodEmoji:()=>Yo,ZodEnum:()=>Cn,ZodExactOptional:()=>va,ZodFile:()=>ep,ZodFunction:()=>bp,ZodGUID:()=>Xo,ZodIBAN:()=>Td,ZodIPv4:()=>oa,ZodIPv6:()=>aa,ZodISODate:()=>bt,ZodISODateTime:()=>$t,ZodISODuration:()=>xt,ZodISOTime:()=>_t,ZodInstanceOf:()=>kp,ZodIntersection:()=>Bd,ZodJWT:()=>pa,ZodKSUID:()=>ia,ZodLazy:()=>vp,ZodLiteral:()=>Qd,ZodMAC:()=>Ad,ZodMap:()=>Xd,ZodNaN:()=>pp,ZodNanoID:()=>Qo,ZodNever:()=>Zd,ZodNonOptional:()=>ya,ZodNull:()=>Ed,ZodNullable:()=>rp,ZodNumber:()=>Rn,ZodNumberFormat:()=>Jt,ZodObject:()=>Vr,ZodOptional:()=>Jr,ZodPipe:()=>Br,ZodPrefault:()=>ap,ZodPreprocess:()=>fp,ZodPromise:()=>$p,ZodReadonly:()=>mp,ZodRecord:()=>Un,ZodSet:()=>Yd,ZodString:()=>En,ZodStringFormat:()=>W,ZodSuccess:()=>up,ZodSymbol:()=>Ud,ZodTemplateLiteral:()=>hp,ZodTransform:()=>tp,ZodTuple:()=>Gd,ZodType:()=>C,ZodULID:()=>na,ZodURL:()=>Lr,ZodUUID:()=>Ke,ZodUndefined:()=>Cd,ZodUnion:()=>Kr,ZodUnknown:()=>Ld,ZodVoid:()=>Fd,ZodXID:()=>ra,ZodXor:()=>Kd,_ZodString:()=>qo,_default:()=>op,_function:()=>uv,any:()=>Lh,array:()=>Fr,base64:()=>bh,base64url:()=>_h,bigint:()=>Uh,boolean:()=>Dd,catch:()=>dp,check:()=>lv,cidrv4:()=>yh,cidrv6:()=>$h,codec:()=>ov,creditCard:()=>kh,cuid:()=>lh,cuid2:()=>dh,currencyCode:()=>jh,custom:()=>dv,date:()=>Fh,describe:()=>pv,discriminatedUnion:()=>Gh,e164:()=>xh,email:()=>eh,emoji:()=>ch,enum:()=>ga,exactOptional:()=>np,file:()=>tv,float32:()=>Oh,float64:()=>Th,function:()=>uv,guid:()=>th,hash:()=>Ah,hex:()=>Ph,hostname:()=>zh,httpUrl:()=>sh,iban:()=>wh,instanceof:()=>mv,int:()=>Wo,int32:()=>Nh,int64:()=>Ch,intersection:()=>Wd,invertCodec:()=>av,ipv4:()=>gh,ipv6:()=>vh,json:()=>hv,jwt:()=>Sh,keyof:()=>Vh,ksuid:()=>mh,lazy:()=>yp,literal:()=>ev,looseObject:()=>Bh,looseRecord:()=>Hh,mac:()=>hh,map:()=>Xh,meta:()=>fv,nan:()=>iv,nanoid:()=>uh,nativeEnum:()=>Qh,never:()=>ma,nonoptional:()=>cp,null:()=>Rd,nullable:()=>Mr,nullish:()=>nv,number:()=>Nd,object:()=>Kh,optional:()=>Ft,partialRecord:()=>qh,pipe:()=>Go,prefault:()=>sp,preprocess:()=>vv,promise:()=>cv,readonly:()=>gp,record:()=>Hd,refine:()=>_p,set:()=>Yh,strictObject:()=>Jh,string:()=>Rr,stringFormat:()=>Ih,stringbool:()=>gv,success:()=>rv,superRefine:()=>xp,symbol:()=>Rh,templateLiteral:()=>sv,transform:()=>ha,tuple:()=>qd,uint32:()=>Dh,uint64:()=>Eh,ulid:()=>ph,undefined:()=>Mh,union:()=>Zn,unknown:()=>Zt,url:()=>ah,uuid:()=>nh,uuidv4:()=>rh,uuidv6:()=>ih,uuidv7:()=>oh,void:()=>Zh,xid:()=>fh,xor:()=>Wh});var Jo={};Ye(Jo,{endsWith:()=>wn,gt:()=>Fe,gte:()=>Oe,includes:()=>xn,length:()=>Mt,lowercase:()=>bn,lt:()=>Ze,lte:()=>Ae,maxLength:()=>Rt,maxSize:()=>gt,mime:()=>In,minLength:()=>nt,minSize:()=>Ve,multipleOf:()=>mt,negative:()=>Co,nonnegative:()=>Ro,nonpositive:()=>Eo,normalize:()=>zn,overwrite:()=>Me,positive:()=>Uo,properties:()=>Sn,property:()=>Mo,regex:()=>$n,size:()=>Et,slugify:()=>On,startsWith:()=>kn,toLowerCase:()=>jn,toUpperCase:()=>An,trim:()=>Pn,uppercase:()=>_n});var Yg=new WeakSet([Object.prototype,Error.prototype]);function Bo(e,t,r){Object.defineProperty(e,t,{configurable:!0,enumerable:!1,get(){let o=r(this);return Object.defineProperty(this,t,{value:o,configurable:!0,writable:!0}),o},set(o){Object.defineProperty(this,t,{value:o,configurable:!0,writable:!0})}})}var Qg=(e,t)=>{vs.init(e,t),e.name="ZodError";let r=Object.getPrototypeOf(e);Yg.has(r)||(Yg.add(r),Bo(r,"format",o=>n=>lr(o,n)),Bo(r,"flatten",o=>n=>ur(o,n)),Bo(r,"addIssue",o=>n=>{o.issues.push(n),o.message=JSON.stringify(o.issues,on,2)}),Bo(r,"addIssues",o=>n=>{o.issues.push(...n),o.message=JSON.stringify(o.issues,on,2)}),Object.defineProperty(r,"isEmpty",{configurable:!0,enumerable:!1,get(){return this.issues.length===0}}))},bw=g("ZodError",Qg),Se=g("ZodError",Qg,void 0,{Parent:Error});var yd=ln(Se),$d=dn(Se),bd=pn(Se),_d=fn(Se),xd=bi(Se),kd=_i(Se),wd=xi(Se),Sd=ki(Se),Id=wi(Se),zd=Si(Se),Pd=Ii(Se),jd=zi(Se);function xw(){se.localeError||te(oo())}function Vt(){se.memoizer||te({memoizer:Pr()})}var C=g("ZodType",(e,t)=>(xw(),D.init(e,t),e.def=t,e.type=t.type,e),{check(...e){let t=this.def;return this.clone($.mergeDefs(t,{checks:[...t.checks??[],...e.map(r=>typeof r=="function"?{_zod:{check:r,def:{check:"custom"},onattach:[]}}:r)]}),{parent:!0})},with(...e){return this.check(...e)},clone(e,t){return F(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},refine(e,t){return this.check(_p(e,t))},superRefine(e,t){return this.check(xp(e,t))},overwrite(e){return this.check(Me(e))},optional(){return Ft(this)},exactOptional(){return np(this)},nullable(){return Mr(this)},nullish(){return Ft(Mr(this))},nonoptional(e){return cp(this,e)},array(){return Fr(this)},or(e){return Zn([this,e])},and(e){return Wd(this,e)},transform(e){return Go(this,ha(e))},default(e){return op(this,e)},prefault(e){return sp(this,e)},catch(e){return dp(this,e)},pipe(e){return Go(this,e)},readonly(){return gp(this)},describe(e){let t=this.clone();return le.add(t,{description:e}),t},meta(...e){if(e.length===0)return le.get(this);let t=this.clone();return le.add(t,e[0]),t},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(e,...t){return t.length===0?e(this):e(this,...t)},get"~standard"(){return $.hide(this,"~standard",{...Ri(this),jsonSchema:{input:Tn(this,"input"),output:Tn(this,"output")}})},set"~standard"(e){$.own(this,"~standard",e)},parse:function e(t,r){return yd(this,t,r,{callee:e})},parseAsync:async function e(t,r){return await $d(this,t,r,{callee:e})},safeParse(e,t){return bd(this,e,t)},async safeParseAsync(e,t){return _d(this,e,t)},get spa(){return this?.safeParseAsync},set spa(e){$.own(this,"spa",e)},validate(e,t){return dr(this,e,t)},validateAsync(e,t){return pr(this,e,t)},encode:function e(t,r){return xd(this,t,r,{callee:e})},decode:function e(t,r){return kd(this,t,r,{callee:e})},encodeAsync:async function e(t,r){return await wd(this,t,r,{callee:e})},decodeAsync:async function e(t,r){return await Sd(this,t,r,{callee:e})},safeEncode(e,t){return Id(this,e,t)},safeDecode(e,t){return zd(this,e,t)},async safeEncodeAsync(e,t){return Pd(this,e,t)},async safeDecodeAsync(e,t){return jd(this,e,t)},toJSONSchema(e){return Ol(this,{})(e)},get description(){return le.get(this)?.description},get _def(){return this._zod.def}}),qo=g("_ZodString",(e,t)=>{Nt.init(e,t),C.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Dl(e,r,o,n)},$.derived({format:e=>ae(e).format??null,minLength:e=>ae(e).minimum??null,maxLength:e=>ae(e).maximum??null},{regex(...e){return this.check($n(...e))},includes(...e){return this.check(xn(...e))},startsWith(...e){return this.check(kn(...e))},endsWith(...e){return this.check(wn(...e))},min(...e){return this.check(nt(...e))},max(...e){return this.check(Rt(...e))},length(...e){return this.check(Mt(...e))},nonempty(...e){return this.check(nt(1,...e))},lowercase(e){return this.check(bn(e))},uppercase(e){return this.check(_n(e))},trim(){return this.check(Pn())},normalize(...e){return this.check(zn(...e))},toLowerCase(){return this.check(jn())},toUpperCase(){return this.check(An())},slugify(){return this.check(On())}})),En=g("ZodString",(e,t)=>{Nt.init(e,t),qo.init(e,t)},{email(e){return this.check(mo(Ho,e))},url(e){return this.check(Or(Lr,e))},jwt(e){return this.check(Do(pa,e))},emoji(e){return this.check(bo(Yo,e))},guid(e){return this.check(go(Xo,e))},uuid(e){return this.check(ho(Ke,e))},uuidv4(e){return this.check(vo(Ke,e))},uuidv6(e){return this.check(yo(Ke,e))},uuidv7(e){return this.check($o(Ke,e))},nanoid(e){return this.check(_o(Qo,e))},cuid(e){return this.check(xo(ea,e))},cuid2(e){return this.check(ko(ta,e))},ulid(e){return this.check(wo(na,e))},base64(e){return this.check(Oo(ua,e))},base64url(e){return this.check(To(la,e))},xid(e){return this.check(So(ra,e))},ksuid(e){return this.check(Io(ia,e))},ipv4(e){return this.check(zo(oa,e))},ipv6(e){return this.check(Po(aa,e))},cidrv4(e){return this.check(jo(sa,e))},cidrv6(e){return this.check(Ao(ca,e))},e164(e){return this.check(No(da,e))},datetime(e){return this.check(Tr($t,e))},date(e){return this.check(Nr(bt,e))},time(e){return this.check(Dr(_t,e))},duration(e){return this.check(Ur(xt,e))}});function Rr(e){return Wu(En,e)}var W=g("ZodStringFormat",(e,t)=>{V.init(e,t),qo.init(e,t)}),$t=g("ZodISODateTime",(e,t)=>{Ec.init(e,t),W.init(e,t)}),bt=g("ZodISODate",(e,t)=>{Rc.init(e,t),W.init(e,t)}),_t=g("ZodISOTime",(e,t)=>{Mc.init(e,t),W.init(e,t)}),xt=g("ZodISODuration",(e,t)=>{Lc.init(e,t),W.init(e,t)}),Ho=g("ZodEmail",(e,t)=>{Ic.init(e,t),W.init(e,t)});function eh(e){return mo(Ho,e)}var Xo=g("ZodGUID",(e,t)=>{wc.init(e,t),W.init(e,t)});function th(e){return go(Xo,e)}var Ke=g("ZodUUID",(e,t)=>{Sc.init(e,t),W.init(e,t)});function nh(e){return ho(Ke,e)}function rh(e){return vo(Ke,e)}function ih(e){return yo(Ke,e)}function oh(e){return $o(Ke,e)}var Lr=g("ZodURL",(e,t)=>{jc.init(e,t),W.init(e,t)});function ah(e){return Or(Lr,e)}function sh(e){return Or(Lr,{protocol:fr,hostname:Ls,...$.normalizeParams(e)})}var Yo=g("ZodEmoji",(e,t)=>{Ac.init(e,t),W.init(e,t)});function ch(e){return bo(Yo,e)}var Qo=g("ZodNanoID",(e,t)=>{Oc.init(e,t),W.init(e,t)});function uh(e){return _o(Qo,e)}var ea=g("ZodCUID",(e,t)=>{Tc.init(e,t),W.init(e,t)});function lh(e){return xo(ea,e)}var ta=g("ZodCUID2",(e,t)=>{Nc.init(e,t),W.init(e,t)});function dh(e){return ko(ta,e)}var na=g("ZodULID",(e,t)=>{Dc.init(e,t),W.init(e,t)});function ph(e){return wo(na,e)}var ra=g("ZodXID",(e,t)=>{Uc.init(e,t),W.init(e,t)});function fh(e){return So(ra,e)}var ia=g("ZodKSUID",(e,t)=>{Cc.init(e,t),W.init(e,t)});function mh(e){return Io(ia,e)}var oa=g("ZodIPv4",(e,t)=>{Zc.init(e,t),W.init(e,t)});function gh(e){return zo(oa,e)}var Ad=g("ZodMAC",(e,t)=>{Vc.init(e,t),W.init(e,t)});function hh(e){return qu(Ad,e)}var aa=g("ZodIPv6",(e,t)=>{Fc.init(e,t),W.init(e,t)});function vh(e){return Po(aa,e)}var sa=g("ZodCIDRv4",(e,t)=>{Kc.init(e,t),W.init(e,t)});function yh(e){return jo(sa,e)}var ca=g("ZodCIDRv6",(e,t)=>{Jc.init(e,t),W.init(e,t)});function $h(e){return Ao(ca,e)}var ua=g("ZodBase64",(e,t)=>{Bc.init(e,t),W.init(e,t)});function bh(e){return Oo(ua,e)}var la=g("ZodBase64URL",(e,t)=>{Wc.init(e,t),W.init(e,t)});function _h(e){return To(la,e)}var da=g("ZodE164",(e,t)=>{Gc.init(e,t),W.init(e,t)});function xh(e){return No(da,e)}var Od=g("ZodCreditCard",(e,t)=>{qc.init(e,t),W.init(e,t)});function kh(e){return Hu(Od,e)}var Td=g("ZodIBAN",(e,t)=>{Hc.init(e,t),W.init(e,t)});function wh(e){return Xu(Td,e)}var pa=g("ZodJWT",(e,t)=>{Xc.init(e,t),W.init(e,t)});function Sh(e){return Do(pa,e)}var Kt=g("ZodCustomStringFormat",(e,t)=>{Yc.init(e,t),W.init(e,t)});function Ih(e,t,r={}){return Lt(Kt,e,t,r)}function zh(e){return Lt(Kt,"hostname",Ms,e)}function Ph(e){return Lt(Kt,"hex",ec,e)}function jh(e){return Lt(Kt,"currency_code",Fs,e)}function Ah(e,t){let r=t?.enc??"hex",o=`${e}_${r}`,n=Ce[o];if(!n)throw new Error(`Unrecognized hash format: ${o}`);return Lt(Kt,o,n,t)}var Rn=g("ZodNumber",(e,t)=>{Gi.init(e,t),C.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Ul(e,r,o,n),e.isFinite=!0},$.derived({minValue:e=>{let{minimum:t,exclusiveMinimum:r}=ae(e);return Math.max(t??Number.NEGATIVE_INFINITY,r??Number.NEGATIVE_INFINITY)},maxValue:e=>{let{maximum:t,exclusiveMaximum:r}=ae(e);return Math.min(t??Number.POSITIVE_INFINITY,r??Number.POSITIVE_INFINITY)},isInt:e=>{let{isInt:t,multipleOf:r}=ae(e);return!!t||!!r?.some(Number.isSafeInteger)},format:e=>ae(e).format??null},{gt(e,t){return this.check(Fe(e,t))},gte(e,t){return this.check(Oe(e,t))},min(e,t){return this.check(Oe(e,t))},lt(e,t){return this.check(Ze(e,t))},lte(e,t){return this.check(Ae(e,t))},max(e,t){return this.check(Ae(e,t))},int(e){return this.check(Wo(e))},safe(e){return this.check(Wo(e))},positive(e){return this.check(Fe(0,e))},nonnegative(e){return this.check(Oe(0,e))},negative(e){return this.check(Ze(0,e))},nonpositive(e){return this.check(Ae(0,e))},multipleOf(e,t){return this.check(mt(e,t))},step(e,t){return this.check(mt(e,t))},finite(){return this}}));function Nd(e){return Qu(Rn,e)}var Jt=g("ZodNumberFormat",(e,t)=>{Qc.init(e,t),Rn.init(e,t)});function Wo(e){return tl(Jt,e)}function Oh(e){return nl(Jt,e)}function Th(e){return rl(Jt,e)}function Nh(e){return il(Jt,e)}function Dh(e){return ol(Jt,e)}var Mn=g("ZodBoolean",(e,t)=>{xr.init(e,t),C.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Cl(e,r,o,n)});function Dd(e){return al(Mn,e)}var Ln=g("ZodBigInt",(e,t)=>{qi.init(e,t),C.init(e,t),e._zod.processJSONSchema=(r,o,n)=>El(e,r,o,n)},$.derived({minValue:e=>ae(e).minimum??null,maxValue:e=>ae(e).maximum??null,format:e=>ae(e).format??null},{gte(e,t){return this.check(Oe(e,t))},min(e,t){return this.check(Oe(e,t))},gt(e,t){return this.check(Fe(e,t))},lt(e,t){return this.check(Ze(e,t))},lte(e,t){return this.check(Ae(e,t))},max(e,t){return this.check(Ae(e,t))},positive(e){return this.check(Fe(BigInt(0),e))},negative(e){return this.check(Ze(BigInt(0),e))},nonpositive(e){return this.check(Ae(BigInt(0),e))},nonnegative(e){return this.check(Oe(BigInt(0),e))},multipleOf(e,t){return this.check(mt(e,t))}}));function Uh(e){return cl(Ln,e)}var fa=g("ZodBigIntFormat",(e,t)=>{eu.init(e,t),Ln.init(e,t)});function Ch(e){return ll(fa,e)}function Eh(e){return dl(fa,e)}var Ud=g("ZodSymbol",(e,t)=>{tu.init(e,t),C.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Rl(e,r,o,n)});function Rh(e){return pl(Ud,e)}var Cd=g("ZodUndefined",(e,t)=>{nu.init(e,t),C.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Ll(e,r,o,n)});function Mh(e){return fl(Cd,e)}var Ed=g("ZodNull",(e,t)=>{ru.init(e,t),C.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Ml(e,r,o,n)});function Rd(e){return ml(Ed,e)}var Md=g("ZodAny",(e,t)=>{iu.init(e,t),C.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Vl(e,r,o,n)});function Lh(){return gl(Md)}var Ld=g("ZodUnknown",(e,t)=>{ou.init(e,t),C.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Kl(e,r,o,n)});function Zt(){return hl(Ld)}var Zd=g("ZodNever",(e,t)=>{au.init(e,t),C.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Fl(e,r,o,n)});function ma(e){return vl(Zd,e)}var Fd=g("ZodVoid",(e,t)=>{su.init(e,t),C.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Zl(e,r,o,n)});function Zh(e){return yl(Fd,e)}var Zr=g("ZodDate",(e,t)=>{cu.init(e,t),C.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Jl(e,r,o,n),e.min=(r,o)=>e.check(Oe(r,o)),e.max=(r,o)=>e.check(Ae(r,o))},$.derived({minDate:e=>{let{minimum:t}=ae(e);return t?new Date(t):null},maxDate:e=>{let{maximum:t}=ae(e);return t?new Date(t):null}},{}));function Fh(e){return $l(Zr,e)}var Vd=g("ZodArray",(e,t)=>{Vt(),lu.init(e,t),C.init(e,t),e._zod.processJSONSchema=(r,o,n)=>rd(e,r,o,n),e.element=t.element},{min(e,t){return this.check(nt(e,t))},nonempty(e){return this.check(nt(1,e))},max(e,t){return this.check(Rt(e,t))},length(e,t){return this.check(Mt(e,t))},unwrap(){return this.element}});function Fr(e,t){return xl(Vd,e,t)}function Vh(e){let t=e._zod.def.shape;return ga(Object.keys(t))}var Vr=g("ZodObject",(e,t)=>{Vt(),du.init(e,t),C.init(e,t),e._zod.processJSONSchema=(r,o,n)=>id(e,r,o,n),$.installLazyProp(e,"shape",r=>r._zod.def.shape,!1)},{keyof(){return ga(Object.keys(this._zod.def.shape))},catchall(e){return this.clone($.mergeDefs(this._zod.def,{catchall:e}))},passthrough(){return this.clone($.mergeDefs(this._zod.def,{catchall:Zt()}))},loose(){return this.clone($.mergeDefs(this._zod.def,{catchall:Zt()}))},strict(){return this.clone($.mergeDefs(this._zod.def,{catchall:ma()}))},strip(){return this.clone($.mergeDefs(this._zod.def,{catchall:void 0}))},extend(e){return $.extend(this,e)},safeExtend(e){return $.safeExtend(this,e)},merge(e){return $.merge(this,e)},pick(e){return $.pick(this,e)},omit(e){return $.omit(this,e)},partial(...e){return $.partial(Jr,this,e[0])},exactPartial(...e){return $.partial(va,this,e[0],"exactPartial")},required(...e){return $.required(ya,this,e[0])}});function Kh(e,t){let r={type:"object",shape:e??{},...$.normalizeParams(t)};return new Vr(r)}function Jh(e,t){return new Vr({type:"object",shape:e,catchall:ma(),...$.normalizeParams(t)})}function Bh(e,t){return new Vr({type:"object",shape:e,catchall:Zt(),...$.normalizeParams(t)})}var Kr=g("ZodUnion",(e,t)=>{kr.init(e,t),C.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Zo(e,r,o,n),e.options=t.options});function Zn(e,t){return new Kr({type:"union",options:e,...$.normalizeParams(t)})}var Kd=g("ZodXor",(e,t)=>{Kr.init(e,t),pu.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Zo(e,r,o,n),e.options=t.options});function Wh(e,t){return new Kd({type:"union",options:e,inclusive:!1,...$.normalizeParams(t)})}var Jd=g("ZodDiscriminatedUnion",(e,t)=>{Kr.init(e,t),mu.init(e,t)});function Gh(e,t,r){return new Jd({type:"union",options:t,discriminator:e,...$.normalizeParams(r)})}var Bd=g("ZodIntersection",(e,t)=>{gu.init(e,t),C.init(e,t),e._zod.processJSONSchema=(r,o,n)=>od(e,r,o,n)});function Wd(e,t){return new Bd({type:"intersection",left:e,right:t})}var Gd=g("ZodTuple",(e,t)=>{Vt(),Hi.init(e,t),C.init(e,t),e._zod.processJSONSchema=(r,o,n)=>ad(e,r,o,n)},{rest(e){return this.clone({...this._zod.def,rest:e})},partial(){let e=this._zod.def;if(e.checks?.length)throw new Error(".partial() cannot be used on tuple schemas containing refinements");return this.clone({...e,items:e.items.map(t=>new Jr({type:"optional",innerType:t}))})}});function qd(e,t,r){let o=t instanceof D,n=o?r:t,i=o?t:null;return new Gd({type:"tuple",items:e,rest:i,...$.normalizeParams(n)})}var Un=g("ZodRecord",(e,t)=>{Vt(),hu.init(e,t),C.init(e,t),e._zod.processJSONSchema=(r,o,n)=>sd(e,r,o,n),e.keyType=t.keyType,e.valueType=t.valueType});function Hd(e,t,r){return!t||!t._zod?new Un({type:"record",keyType:Rr(),valueType:e,...$.normalizeParams(t)}):new Un({type:"record",keyType:e,valueType:t,...$.normalizeParams(r)})}function qh(e,t,r){return new Un({type:"record",keyType:e,valueType:t,...$.normalizeParams(r),partial:!0})}function Hh(e,t,r){return new Un({type:"record",keyType:e,valueType:t,mode:"loose",...$.normalizeParams(r)})}var Xd=g("ZodMap",(e,t)=>{Vt(),vu.init(e,t),C.init(e,t),e._zod.processJSONSchema=(r,o,n)=>td(e,r,o,n),e.keyType=t.keyType,e.valueType=t.valueType,e.min=(...r)=>e.check(Ve(...r)),e.nonempty=r=>e.check(Ve(1,r)),e.max=(...r)=>e.check(gt(...r)),e.size=(...r)=>e.check(Et(...r))});function Xh(e,t,r){return new Xd({type:"map",keyType:e,valueType:t,...$.normalizeParams(r)})}var Yd=g("ZodSet",(e,t)=>{Vt(),yu.init(e,t),C.init(e,t),e._zod.processJSONSchema=(r,o,n)=>nd(e,r,o,n),e.min=(...r)=>e.check(Ve(...r)),e.nonempty=r=>e.check(Ve(1,r)),e.max=(...r)=>e.check(gt(...r)),e.size=(...r)=>e.check(Et(...r))});function Yh(e,t){return new Yd({type:"set",valueType:e,...$.normalizeParams(t)})}var Cn=g("ZodEnum",(e,t)=>{$u.init(e,t),C.init(e,t),e._zod.processJSONSchema=(o,n,i)=>Bl(e,o,n,i),e.enum=t.entries,e.options=[...e._zod.values];let r=new Set(Object.keys(t.entries));e.extract=(o,n)=>{let i={};for(let a of o)if(r.has(a))i[a]=t.entries[a];else throw new Error(`Key ${a} not found in enum`);return new Cn({...t,checks:[],...$.normalizeParams(n),entries:i})},e.exclude=(o,n)=>{let i={...t.entries};for(let a of o)if(r.has(a))delete i[a];else throw new Error(`Key ${a} not found in enum`);return new Cn({...t,checks:[],...$.normalizeParams(n),entries:i})}});function ga(e,t){let r=Array.isArray(e)?Object.fromEntries(e.map(o=>[o,o])):e;return new Cn({type:"enum",entries:r,...$.normalizeParams(t)})}function Qh(e,t){return new Cn({type:"enum",entries:e,...$.normalizeParams(t)})}var Qd=g("ZodLiteral",(e,t)=>{bu.init(e,t),C.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Wl(e,r,o,n),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 ev(e,t){return new Qd({type:"literal",values:Array.isArray(e)?e:[e],...$.normalizeParams(t)})}var ep=g("ZodFile",(e,t)=>{_u.init(e,t),C.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Hl(e,r,o,n),e.min=(r,o)=>e.check(Ve(r,o)),e.max=(r,o)=>e.check(gt(r,o)),e.mime=(r,o)=>e.check(In(Array.isArray(r)?r:[r],o))});function tv(e){return kl(ep,e)}var tp=g("ZodTransform",(e,t)=>{Vt(),xu.init(e,t),C.init(e,t),e._zod.processJSONSchema=(r,o,n)=>ed(e,r,o,n),e._zod.parse=(r,o)=>{if(o.direction==="backward")throw new pt(e.constructor.name);r.addIssue=i=>{if(typeof i=="string")r.issues.push($.issue(i,r.value,t));else{let a=i;a.fatal&&(a.continue=!1),a.code??(a.code="custom"),"input"in a||(a.input=r.value),a.inst??(a.inst=e),r.issues.push($.issue(a))}};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 tp({type:"transform",transform:e})}var Jr=g("ZodOptional",(e,t)=>{Xi.init(e,t),C.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Fo(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function Ft(e){return new Jr({type:"optional",innerType:e})}var va=g("ZodExactOptional",(e,t)=>{ku.init(e,t),C.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Fo(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function np(e){return new va({type:"optional",innerType:e})}var rp=g("ZodNullable",(e,t)=>{wu.init(e,t),C.init(e,t),e._zod.processJSONSchema=(r,o,n)=>cd(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function Mr(e){return new rp({type:"nullable",innerType:e})}function nv(e){return Ft(Mr(e))}var ip=g("ZodDefault",(e,t)=>{Su.init(e,t),C.init(e,t),e._zod.processJSONSchema=(r,o,n)=>dd(e,r,o,n),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function op(e,t){return new ip({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():$.shallowClone(t)}})}var ap=g("ZodPrefault",(e,t)=>{Iu.init(e,t),C.init(e,t),e._zod.processJSONSchema=(r,o,n)=>pd(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function sp(e,t){return new ap({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():$.shallowClone(t)}})}var ya=g("ZodNonOptional",(e,t)=>{zu.init(e,t),C.init(e,t),e._zod.processJSONSchema=(r,o,n)=>ud(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function cp(e,t){return new ya({type:"nonoptional",innerType:e,...$.normalizeParams(t)})}var up=g("ZodSuccess",(e,t)=>{Pu.init(e,t),C.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Xl(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function rv(e){return new up({type:"success",innerType:e})}var lp=g("ZodCatch",(e,t)=>{ju.init(e,t),C.init(e,t),e._zod.processJSONSchema=(r,o,n)=>fd(e,r,o,n),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function dp(e,t){return new lp({type:"catch",innerType:e,catchValue:typeof t=="function"?t:$.constantCatch(t)})}var pp=g("ZodNaN",(e,t)=>{Au.init(e,t),C.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Gl(e,r,o,n)});function iv(e){return _l(pp,e)}var Br=g("ZodPipe",(e,t)=>{Yi.init(e,t),C.init(e,t),e._zod.processJSONSchema=(r,o,n)=>md(e,r,o,n),e.in=t.in,e.out=t.out});function Go(e,t){return new Br({type:"pipe",in:e,out:t})}var Wr=g("ZodCodec",(e,t)=>{Br.init(e,t),wr.init(e,t)});function ov(e,t,r){return new Wr({type:"pipe",in:e,out:t,transform:r.decode,reverseTransform:r.encode})}function av(e){let t=e._zod.def;return new Wr({type:"pipe",in:t.out,out:t.in,transform:t.reverseTransform,reverseTransform:t.transform})}var fp=g("ZodPreprocess",(e,t)=>{Br.init(e,t),Ou.init(e,t)}),mp=g("ZodReadonly",(e,t)=>{Tu.init(e,t),C.init(e,t),e._zod.processJSONSchema=(r,o,n)=>gd(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function gp(e){return new mp({type:"readonly",innerType:e})}var hp=g("ZodTemplateLiteral",(e,t)=>{Nu.init(e,t),C.init(e,t),e._zod.processJSONSchema=(r,o,n)=>ql(e,r,o,n)});function sv(e,t){return new hp({type:"template_literal",parts:e,...$.normalizeParams(t)})}var vp=g("ZodLazy",(e,t)=>{Sr.init(e,t),C.init(e,t),e._zod.processJSONSchema=(r,o,n)=>vd(e,r,o,n),e.unwrap=()=>e._zod.def.getter()});function yp(e){return new vp({type:"lazy",getter:e})}var $p=g("ZodPromise",(e,t)=>{Uu.init(e,t),C.init(e,t),e._zod.processJSONSchema=(r,o,n)=>hd(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function cv(e){return new $p({type:"promise",innerType:e})}var bp=g("ZodFunction",(e,t)=>{Du.init(e,t),C.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Ql(e,r,o,n)});function uv(e){return new bp({type:"function",input:Array.isArray(e?.input)?qd(e?.input):e?.input??Fr(Zt()),output:e?.output??Zt()})}var Gr=g("ZodCustom",(e,t)=>{Cu.init(e,t),C.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Yl(e,r,o,n)});function lv(e){let t=new G({check:"custom"});return t._zod.check=e,t}function dv(e,t){return wl(Gr,e??(()=>!0),t)}function _p(e,t={}){return Sl(Gr,e,t)}function xp(e,t){return Il(e,t)}var pv=zl,fv=Pl,kp=g("ZodInstanceOf",(e,t)=>{Gr.init(e,t)},{properties(e,t){return this.check(Sn(e,t))}});function mv(e,t={}){let r=new kp({type:"custom",check:"custom",fn:o=>o instanceof e,abort:!0,...$.normalizeParams(t)});return r._zod.bag.Class=e,r._zod.check=o=>{o.value instanceof e||o.issues.push({code:"invalid_type",expected:e.name,input:o.value,inst:r,path:[...r._zod.def.path??[]]})},r}var gv=(...e)=>jl({Codec:Wr,Boolean:Mn,String:En},...e);function hv(e){let t=yp(()=>Zn([Rr(e),Nd(),Dd(),Rd(),Fr(t),Hd(Rr(),t)]));return t}function vv(e,t){return new fp({type:"pipe",in:ha(e),out:t})}var kw={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"};function ww(e){te({customError:e})}function Sw(){return te().customError}var wp;wp||(wp={});var qr={};Ye(qr,{ZodISODate:()=>bt,ZodISODateTime:()=>$t,ZodISODuration:()=>xt,ZodISOTime:()=>_t,date:()=>zw,datetime:()=>Iw,duration:()=>jw,time:()=>Pw});function Iw(e){return Tr($t,e)}function zw(e){return Nr(bt,e)}function Pw(e){return Dr(_t,e)}function jw(e){return Ur(xt,e)}var z={...Fn,...Jo,iso:qr},Aw=new Set(["$schema","$ref","$defs","definitions","$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor","type","enum","const","anyOf","oneOf","allOf","not","properties","required","additionalProperties","patternProperties","propertyNames","minProperties","maxProperties","items","prefixItems","additionalItems","minItems","maxItems","uniqueItems","contains","minContains","maxContains","minLength","maxLength","pattern","format","minimum","maximum","exclusiveMinimum","exclusiveMaximum","multipleOf","description","default","contentEncoding","contentMediaType","contentSchema","unevaluatedItems","unevaluatedProperties","if","then","else","dependentSchemas","dependentRequired","nullable","readOnly"]);function Ow(e,t){let r=e.$schema;return r==="https://json-schema.org/draft/2020-12/schema"?"draft-2020-12":r==="http://json-schema.org/draft-07/schema#"?"draft-7":r==="http://json-schema.org/draft-04/schema#"?"draft-4":t??"draft-2020-12"}function yv(e,t){return e.map((r,o)=>o<t?r:r.optional())}function Tw(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}function Nw(e,t){if(!e.startsWith("#"))throw new Error("External $ref is not supported, only local refs (#/...) are allowed");let r=e.slice(1).split("/").filter(Boolean);if(r.length===0)return t.rootSchema;let o=t.version==="draft-2020-12"?"$defs":"definitions";if(r[0]===o){let n=r[1]===void 0?void 0:Tw(r[1]);if(!n||!t.defs[n])throw new Error(`Reference not found: ${e}`);return t.defs[n]}throw new Error(`Reference not found: ${e}`)}function Dw(e,t){return z.transform(o=>o).check(o=>{let n=o.value;if(typeof n!="object"||n===null||Array.isArray(n))return;let i=Object.getOwnPropertyNames(n);if(t.minProperties!==void 0&&i.length<t.minProperties&&o.issues.push({origin:"object",code:"too_small",minimum:t.minProperties,inclusive:!0,message:`Too small: expected object to have >=${t.minProperties} properties`,input:n,inst:e,continue:!0}),t.maxProperties!==void 0&&i.length>t.maxProperties&&o.issues.push({origin:"object",code:"too_big",maximum:t.maxProperties,inclusive:!0,message:`Too big: expected object to have <=${t.maxProperties} properties`,input:n,inst:e,continue:!0}),t.keySchema)for(let a of i){let s=t.keySchema.safeParse(a);s.success||o.issues.push({code:"invalid_key",origin:"record",issues:s.error.issues,input:a,path:[a],continue:!0})}}).pipe(e)}function Sp(e,t){if(e===null)return"z";let r=typeof e;if(r!=="object"){if(r==="number"&&Number.isNaN(e))return null;let o=String(e);return`${r[0]}${o.length}:${o}`}if(t.has(e))return null;t.add(e);try{if(Array.isArray(e)){let i=[];for(let a of e){let s=Sp(a,t);if(s===null)return null;i.push(s)}return`a${i.length}:[${i.join(",")}]`}let o=Object.keys(e).sort(),n=[];for(let i of o){let a=Sp(e[i],t);if(a===null)return null;n.push(`${i.length}:${i}=${a}`)}return`o${n.length}:{${n.join(",")}}`}finally{t.delete(e)}}var Uw=new Set(["items","prefixItems","additionalItems","additionalProperties","contains","propertyNames","not","if","then","else","allOf","anyOf","oneOf","unevaluatedItems","unevaluatedProperties","contentSchema"]),Cw=new Set(["properties","patternProperties","dependentSchemas","dependencies","$defs","definitions"]);function Hr(e){return typeof e!="object"||e===null?!1:Array.isArray(e)?e.some(Hr):typeof e.$ref=="string"?!0:Object.entries(e).some(([t,r])=>Uw.has(t)?Hr(r):!Cw.has(t)||typeof r!="object"||r===null?!1:Object.values(r).some(Hr))}function $v(e){return e===1?"element":"elements"}function Ew(e,t){return z.transform(o=>o).check(o=>{let n=o.value;if(Array.isArray(n)){if(t.uniqueItems===!0){let i=new Map;for(let a=0;a<n.length;a++){let s=Sp(n[a],new Set);if(s===null)continue;let u=i.get(s);if(u===void 0){i.set(s,a);continue}o.issues.push({code:"custom",message:`Array items must be unique: element at index ${a} duplicates the one at index ${u}`,input:n,path:[a],continue:!0})}}if(t.containsSchema){let i=t.minContains??1,a=t.maxContains!==void 0?t.maxContains+1:Number.POSITIVE_INFINITY,s=0;for(let u of n)if(t.containsSchema.safeParse(u).success&&++s>=a)break;s<i&&o.issues.push({code:"custom",message:`Array must contain at least ${i} matching ${$v(i)}; found ${s}`,input:n,continue:!0}),t.maxContains!==void 0&&s>t.maxContains&&o.issues.push({code:"custom",message:`Array must contain at most ${t.maxContains} matching ${$v(t.maxContains)}`,input:n,continue:!0})}}}).pipe(e)}function bv(e,t){if(e!==!1)return e===void 0||e===!0?z.any():ye(e,t)}var Rw=/^(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:\.\d+)?(?:Z|[+-](?:[01]\d|2[0-3]):[0-5]\d)$/;function _v(e,t){if(e.not!==void 0){if(typeof e.not=="object"&&Object.keys(e.not).length===0)return z.never();throw new Error("not is not supported in Zod (except { not: {} } for never)")}if(e.unevaluatedItems!==void 0)throw new Error("unevaluatedItems is not supported");if(e.unevaluatedProperties!==void 0)throw new Error("unevaluatedProperties is not supported");if(e.if!==void 0||e.then!==void 0||e.else!==void 0)throw new Error("Conditional schemas (if/then/else) are not supported");if(e.dependentSchemas!==void 0||e.dependentRequired!==void 0)throw new Error("dependentSchemas and dependentRequired are not supported");if(e.$ref){let n=e.$ref;if(t.refs.has(n))return t.refs.get(n);if(t.processing.has(n))return z.lazy(()=>{if(!t.refs.has(n))throw new Error(`Circular reference not resolved: ${n}`);return t.refs.get(n)});t.processing.add(n);let i=Nw(n,t),a=ye(i,t);return t.refs.set(n,a),t.processing.delete(n),a}if(e.enum!==void 0){let n=e.enum;if(t.version==="openapi-3.0"&&e.nullable===!0&&n.length===1&&n[0]===null)return z.null();if(n.length===0)return z.never();if(n.length===1)return z.literal(n[0]);if(n.every(a=>typeof a=="string"))return z.enum(n);let i=n.map(a=>z.literal(a));return i.length<2?i[0]:z.union([i[0],i[1],...i.slice(2)])}if(e.const!==void 0)return z.literal(e.const);let r=e.type;if(Array.isArray(r)){let n=r.map(i=>{let a={...e,type:i};return _v(a,t)});return n.length===0?z.never():n.length===1?n[0]:z.union(n)}if(!r)return z.any();let o;switch(r){case"string":{let n=z.string();if(e.format){let i=e.format;i==="email"?n=n.check(z.email()):i==="uri"||i==="uri-reference"?n=n.check(z.url()):i==="uuid"||i==="guid"?n=n.check(z.uuid()):i==="date-time"?n=n.check(z.iso.datetime({offset:!0})):i==="date"?n=n.check(z.iso.date()):i==="time"?n=n.check(z.regex(Rw)):i==="duration"?n=n.check(z.iso.duration()):i==="hostname"?n=n.check(z.hostname()):i==="ipv4"?n=n.check(z.ipv4()):i==="ipv6"?n=n.check(z.ipv6()):i==="mac"?n=n.check(z.mac()):i==="cidr"?n=n.check(z.cidrv4()):i==="cidr-v6"?n=n.check(z.cidrv6()):i==="base64"?n=n.check(z.base64()):i==="base64url"?n=n.check(z.base64url()):i==="e164"?n=n.check(z.e164()):i==="credit_card"?n=n.check(z.creditCard()):i==="iban"?n=n.check(z.iban()):i==="jwt"?n=n.check(z.jwt()):i==="emoji"?n=n.check(z.emoji()):i==="nanoid"?n=n.check(z.nanoid()):i==="cuid"?n=n.check(z.cuid()):i==="cuid2"?n=n.check(z.cuid2()):i==="ulid"?n=n.check(z.ulid()):i==="xid"?n=n.check(z.xid()):i==="ksuid"&&(n=n.check(z.ksuid()))}typeof e.minLength=="number"&&(n=n.min(e.minLength)),typeof e.maxLength=="number"&&(n=n.max(e.maxLength)),e.pattern&&(n=n.regex(new RegExp(e.pattern))),o=n;break}case"number":case"integer":{let n=r==="integer"?z.number().int():z.number();typeof e.minimum=="number"&&e.exclusiveMinimum!==!0&&(n=n.min(e.minimum)),typeof e.maximum=="number"&&e.exclusiveMaximum!==!0&&(n=n.max(e.maximum)),typeof e.exclusiveMinimum=="number"?n=n.gt(e.exclusiveMinimum):e.exclusiveMinimum===!0&&typeof e.minimum=="number"&&(n=n.gt(e.minimum)),typeof e.exclusiveMaximum=="number"?n=n.lt(e.exclusiveMaximum):e.exclusiveMaximum===!0&&typeof e.maximum=="number"&&(n=n.lt(e.maximum)),typeof e.multipleOf=="number"&&(n=n.multipleOf(e.multipleOf)),o=n;break}case"boolean":{o=z.boolean();break}case"null":{o=z.null();break}case"object":{let n={},i=e.properties||{},a=new Set(e.required||[]),s=typeof e.additionalProperties=="object"?ye(e.additionalProperties,t):void 0;for(let[p,m]of Object.entries(i)){let f=ye(m,t);ue(n,p,a.has(p)?f:f.optional())}if(e.patternProperties){let p=e.patternProperties,m=Object.keys(p),f=[];for(let y of m){let x=ye(p[y],t),j=z.string().regex(new RegExp(y));f.push(z.looseRecord(j,x))}let v=[];if(Object.keys(n).length>0&&v.push(z.object(n).passthrough()),v.push(...f),v.length===0)o=z.object({}).passthrough();else if(v.length===1)o=v[0];else{let y=z.intersection(v[0],v[1]);for(let x=2;x<v.length;x++)y=z.intersection(y,v[x]);o=y}if(e.additionalProperties===!1){let y=Object.keys(n),x=m.map(P=>new RegExp(P)),j=o;o=o.check(P=>{if(!De(P.value))return;let T=[];for(let S of Object.keys(P.value))y.includes(S)||x.some(I=>I.test(S))||T.push(S);T.length&&P.issues.push({code:"unrecognized_keys",keys:T,input:P.value,inst:j})})}}else{let p=z.object(n);e.additionalProperties===!1?o=p.strict():s?o=p.catchall(s):o=p.passthrough()}let u=e.propertyNames!==void 0&&e.propertyNames!==!0,l=typeof e.minProperties=="number"?e.minProperties:void 0,d=typeof e.maxProperties=="number"?e.maxProperties:void 0;if(u||l!==void 0||d!==void 0){let p;if(u){let m=typeof e.propertyNames=="object"&&e.propertyNames.type===void 0?{type:"string",...e.propertyNames}:e.propertyNames;p=ye(m,t)}o=Dw(o,{keySchema:p,minProperties:l,maxProperties:d})}break}case"array":{let n=e.prefixItems,i=e.items;if(n&&Array.isArray(n)){let a=typeof e.minItems=="number"?e.minItems:0,s=n.map(p=>ye(p,t)),u=yv(s,a),l=Array.isArray(i)?void 0:bv(i,t),d=z.tuple(u);o=l?d.rest(l):d,typeof e.minItems=="number"&&(o=o.check(z.minLength(e.minItems))),typeof e.maxItems=="number"&&(o=o.check(z.maxLength(e.maxItems)))}else if(Array.isArray(i)){let a=typeof e.minItems=="number"?e.minItems:0,s=i.map(p=>ye(p,t)),u=yv(s,a),l=bv(e.additionalItems,t),d=z.tuple(u);o=l?d.rest(l):d,typeof e.minItems=="number"&&(o=o.check(z.minLength(e.minItems))),typeof e.maxItems=="number"&&(o=o.check(z.maxLength(e.maxItems)))}else if(i!==void 0){let a=ye(i,t),s=z.array(a);typeof e.minItems=="number"&&(s=s.min(e.minItems)),typeof e.maxItems=="number"&&(s=s.max(e.maxItems)),o=s}else o=z.array(z.any());(e.uniqueItems===!0||e.contains!==void 0)&&(o=Ew(o,{uniqueItems:e.uniqueItems===!0,containsSchema:e.contains!==void 0?ye(e.contains,t):void 0,minContains:typeof e.minContains=="number"?e.minContains:void 0,maxContains:typeof e.maxContains=="number"?e.maxContains:void 0}));break}default:throw new Error(`Unsupported type: ${r}`)}return o}function ye(e,t){if(typeof e=="boolean")return e?z.any():z.never();let r=_v(e,t),o=e.type||e.enum!==void 0||e.const!==void 0;if(e.anyOf&&Array.isArray(e.anyOf)){let s=e.anyOf.map(l=>ye(l,t)),u=z.union(s);r=o?z.intersection(r,u):u}if(e.oneOf&&Array.isArray(e.oneOf)){let s=e.oneOf.map(l=>ye(l,t)),u=z.xor(s);r=o?z.intersection(r,u):u}if(e.allOf&&Array.isArray(e.allOf))if(e.allOf.length===0)r=o?r:z.any();else{let s=o?r:ye(e.allOf[0],t),u=o?0:1;for(let l=u;l<e.allOf.length;l++)s=z.intersection(s,ye(e.allOf[l],t));r=s}e.nullable===!0&&t.version==="openapi-3.0"&&(r=z.nullable(r)),e.readOnly===!0&&(r=z.readonly(r)),e.default!==void 0&&(r=r.default(e.default));let n={},i=["$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor"];for(let s of i)s in e&&(n[s]=e[s]);let a=["contentEncoding","contentMediaType","contentSchema"];for(let s of a)s in e&&(n[s]=e[s]);if(e.type==="object"&&e.$ref===void 0){e.propertyNames!==void 0&&!Hr(e.propertyNames)&&(n.propertyNames=e.propertyNames);for(let s of["minProperties","maxProperties"])e[s]!==void 0&&(n[s]=e[s])}if(e.type==="array"&&e.$ref===void 0){e.contains!==void 0&&!Hr(e.contains)&&(n.contains=e.contains);for(let s of["uniqueItems","minContains","maxContains"])e[s]!==void 0&&(n[s]=e[s])}for(let s of Object.keys(e))Aw.has(s)||ue(n,s,e[s]);return Object.keys(n).length>0&&t.registry.add(r,n),e.description&&(r=r.describe(e.description)),r}function xv(e,t){if(typeof e=="boolean")return e?z.any():z.never();let r;try{r=JSON.parse(JSON.stringify(e))}catch{throw new Error("fromJSONSchema input is not valid JSON (possibly cyclic); use $defs/$ref for recursive schemas")}let o=Ow(r,t?.defaultTarget),n=r.$defs||r.definitions||{},i={version:o,defs:n,refs:new Map,processing:new Set,rootSchema:r,registry:t?.registry??le};return ye(r,i)}var kv=Symbol("z.visit/resolving");function Xr(e,t){let r=typeof t=="function"?t:(a,s)=>{let u=t[a._zod.def.type];return u?u(a,s):a},o=new Map;function n(a){let s=o.get(a);if(s===kv)return new Sr({type:"lazy",getter:()=>o.get(a)});if(s!==void 0)return s;o.set(a,kv);let u=i(a),l=r(u,u!==a);return o.set(a,l),l}function i(a){let s=a._zod.def,u=s.type;switch(u){case"object":{let l=s.shape,d=Object.keys(l),p=!1,m={};for(let v of d){let y=n(l[v]);y!==l[v]&&(p=!0),m[v]=y}let f=s.catchall;return s.catchall&&(f=n(s.catchall),f!==s.catchall&&(p=!0)),p?F(a,{...s,shape:m,catchall:f}):a}case"array":{let l=n(s.element);return l===s.element?a:F(a,{...s,element:l})}case"tuple":{let l=s.items,d=!1,p=[];for(let f of l){let v=n(f);v!==f&&(d=!0),p.push(v)}let m=s.rest;return s.rest&&(m=n(s.rest),m!==s.rest&&(d=!0)),d?F(a,{...s,items:p,rest:m}):a}case"record":case"map":{let l=n(s.keyType),d=n(s.valueType);return l===s.keyType&&d===s.valueType?a:F(a,{...s,keyType:l,valueType:d})}case"set":{let l=n(s.valueType);return l===s.valueType?a:F(a,{...s,valueType:l})}case"union":{let l=s.options,d=!1,p=[];for(let m of l){let f=n(m);f!==m&&(d=!0),p.push(f)}return d?F(a,{...s,options:p}):a}case"intersection":{let l=n(s.left),d=n(s.right);return l===s.left&&d===s.right?a:F(a,{...s,left:l,right:d})}case"optional":case"nullable":case"default":case"prefault":case"catch":case"readonly":case"nonoptional":case"promise":case"success":{let l=n(s.innerType);return l===s.innerType?a:F(a,{...s,innerType:l})}case"pipe":{let l=n(s.in),d=n(s.out);return l===s.in&&d===s.out?a:F(a,{...s,in:l,out:d})}case"function":{let l=n(s.input),d=n(s.output);return l===s.input&&d===s.output?a:F(a,{...s,input:l,output:d})}case"lazy":{let l=s.getter,{_cachedInner:d,...p}=s;return F(a,{...p,getter:()=>n(l())})}case"template_literal":case"string":case"number":case"int":case"boolean":case"bigint":case"symbol":case"undefined":case"null":case"void":case"never":case"any":case"unknown":case"date":case"nan":case"enum":case"literal":case"file":case"transform":case"custom":return a;default:return a}}return n(e)}function wv(e){return Xr(e,{object:t=>t.partial(),union:t=>{let r=t._zod.def;return r.discriminator===void 0?t:Zn(r.options)}})}function Mw(e,t){if(!t?.length)return e;let r=e._zod.def;return F(e,Ee(r,{checks:[...r.checks??[],...t]}),{parent:!0})}function Sv(e){return Mw(e.out,e.checks)}function Lw(e){return e.in._zod.traits.has("$ZodTransform")?Sv(e):e.in}function Iv(e){return Xr(e,{pipe:t=>Lw(t._zod.def),default:(t,r)=>r?Ft(t._zod.def.innerType):t,catch:(t,r)=>r?t._zod.def.innerType:t})}function zv(e){return Xr(e,{pipe:t=>Sv(t._zod.def),prefault:(t,r)=>r?t._zod.def.innerType:t})}var Ip={};Ye(Ip,{bigint:()=>Kw,boolean:()=>Vw,date:()=>Jw,number:()=>Fw,string:()=>Zw});function Zw(e){return Gu(En,e)}function Fw(e){return el(Rn,e)}function Vw(e){return sl(Mn,e)}function Kw(e){return ul(Ln,e)}function Jw(e){return bl(Zr,e)}var Vn=c.string().min(1).max(512).refine(Bw,"Invalid path: use segments like notes/plan.md, without .. or a leading /");function Bw(e){return/[\u0000-\u001f\u007f\\]/.test(e)?!1:e.split("/").every(r=>r.length>0&&r.length<=255&&r!=="."&&r!=="..")}var Yr=c.string().regex(pe("message")),q=c.string().regex(pe("thread")),Ie=c.string().regex(pe("project")),ze=c.string().regex(pe("task")),zp=c.string().regex(pe("artifact")),R=c.iso.datetime(),Qr=c.enum(["user","agent","system"]),Ww=c.object({path:Vn,name:c.string(),size:c.number().int().nonnegative(),contentType:c.string()}),Gw=c.object({artifactId:zp,version:c.number().int().positive(),title:c.string()}),Pv=c.enum(["cloud","local"]),H=c.number().int().nonnegative(),qw=c.object({title:c.string(),harness:c.string(),runtime:Pv,model:c.string().nullable(),durationMs:H,inputTokens:H,outputTokens:H,costMicros:H.nullable()}),Hw=c.object({chars:H,limit:H,parts:c.object({instructions:H,skills:H,knowledge:H,brief:H,conversation:H,notes:H,other:H}),droppedMessages:H,droppedNotes:H,cut:c.boolean()}),Xw=c.object({model:c.string(),durationMs:H,calls:H,inputTokens:H,cachedInputTokens:H,outputTokens:H,costMicros:H.nullable(),runtime:Pv,computer:c.string().optional(),harness:c.string().optional(),task:qw.optional(),prompt:Hw.optional()}),Yw=c.enum(["brief","follow_up","reply","relay","answer"]),Qw=c.object({kind:Yw,threadId:q,fromThreadId:q.optional(),note:c.string()}),$a=8,Bt=c.object({id:Yr,projectId:Ie,threadId:q.nullable(),authorKind:Qr,authorId:c.string().min(1),body:c.string(),attachments:c.array(Ww).optional(),artifacts:c.array(Gw).optional(),stats:Xw.optional(),relay:Qw.optional(),clis:c.array(c.string().max(40)).max($a).optional(),seq:c.number().int().positive(),createdAt:R,editedAt:R.optional()}),eS=c.enum(["working","blocked","review_ready","done","failed"]),tS=c.object({id:c.string().max(40),options:c.array(c.string().max(40)).max($a),by:c.enum(["person","coordinator"]),reason:c.string().max(300).nullable()}),nS=c.object({cli:c.string().max(40),model:c.string().max(200).nullable(),effort:c.string().max(20).nullable()}),jv="cloud",rS=c.object({id:c.string().max(60),by:c.enum(["person","auto","coordinator"]),reason:c.string().max(300).nullable().default(null)}),Pp=c.enum(["duplicate","misrouted","cancelled"]),iS=c.object({replies:H,usage:c.object({tokens:H,durationMs:H,costMicros:H.nullable()}).nullable(),planMessageId:Yr.nullable()}),jp=c.object({id:q,projectId:Ie,rootMessageId:Yr,ackMessageId:Yr.nullable().default(null),title:c.string(),status:eS,statusText:c.string().nullable(),resolved:c.boolean(),closeReason:Pp.nullable().default(null),duplicateOf:q.nullable().default(null),label:c.string().nullable(),cli:tS.nullable().default(null),runner:rS.nullable().default(null),model:nS.nullable().default(null),seenSeq:c.number().int().nonnegative().nullable().default(null),summary:iS.nullable().default(null),createdAt:R,updatedAt:R}),oS=c.enum(["running","done","failed","cancelled"]),Av=c.object({id:ze,threadId:q,title:c.string(),harness:c.string(),backend:c.string(),status:oS,prUrl:c.string().nullable(),summary:c.string().nullable(),createdAt:R,finishedAt:R.nullable()}),yT=c.object({ref:c.string(),commits:c.array(c.object({hash:c.string(),message:c.string(),at:c.string()})),entries:c.array(c.object({name:c.string(),path:c.string(),type:c.enum(["file","folder"])})).nullable(),file:c.object({path:c.string(),text:c.string().nullable(),size:c.number(),truncated:c.boolean()}).nullable()}),Ap=c.object({id:c.string().min(1).max(200),label:c.string().max(100),state:c.enum(["started","done","failed"]).optional(),model:c.string().max(200).optional(),tokens:c.number().int().nonnegative().optional()}),Ov=c.object({stream:c.enum(["stdout","stderr","system"]),text:c.string(),at:c.number().optional(),ms:c.number().nonnegative().optional(),tool:c.boolean().optional(),agent:Ap.optional()}),Op=c.object({messageId:Yr,emoji:c.string().min(1).max(32),authorKind:Qr,authorId:c.string().min(1)}),ba=c.enum(["owner","admin","member"]),aS=c.object({working:c.number().int().nonnegative(),waiting:c.number().int().nonnegative()}),sS=c.object({monthMicros:c.number().int().nonnegative(),totalMicros:c.number().int().nonnegative()}),_a=c.enum(["indigo","blue","teal","green","amber","orange","red","pink","purple","gray"]),xa=c.enum(["folder","rocket","code","terminal","globe","smartphone","server","database","cpu","bot","book","pen","palette","camera","music","gamepad","briefcase","cart","chart","shield","flask","leaf","heart","star","zap","home"]),$T=c.object({id:Ie,name:c.string().min(1).max(120),role:ba,icon:xa.nullable().optional(),color:_a.nullable().optional(),createdAt:R,activity:aS.optional(),cost:sS.optional(),pinned:c.boolean().optional()}),bT=c.object({pinned:c.boolean()}),_T=c.object({name:c.string().trim().min(1).max(120)}),xT=c.object({id:c.string(),name:c.string(),role:ba,email:c.string().optional()}),Tp=32e3,cS=c.object({id:c.number().int(),accountLogin:c.string(),accountType:c.enum(["User","Organization"]),accountAvatarUrl:c.string().nullable()}),kT=c.object({configured:c.boolean(),installUrl:c.string().nullable(),installations:c.array(cS)}),wT=c.object({id:c.number().int(),installationId:c.number().int(),fullName:c.string(),defaultBranch:c.string(),private:c.boolean(),description:c.string().nullable()}),ST=c.object({repoId:c.number().int(),installationId:c.number().int(),fullName:c.string(),defaultBranch:c.string(),private:c.boolean(),createdAt:R}),Tv=c.object({repo:c.string(),number:c.number().int(),url:c.string(),threadId:q,title:c.string(),state:c.enum(["open","closed","merged"]),draft:c.boolean(),checks:c.enum(["pending","success","failure"]).nullable(),review:c.enum(["approved","changes_requested"]).nullable(),conflict:c.boolean().default(!1),branch:c.string().default(""),additions:c.number().int().nullable().default(null),deletions:c.number().int().nullable().default(null),changedFiles:c.number().int().nullable().default(null),updatedAt:R}),uS=c.object({path:c.string(),previousPath:c.string().nullable(),status:c.enum(["added","removed","modified","renamed","copied","changed","unchanged"]),additions:c.number().int(),deletions:c.number().int(),patch:c.string().nullable()}),IT=c.object({files:c.array(uS),truncated:c.boolean()}),Nv=c.enum(["merge","squash","rebase"]),zT=c.object({permitted:c.boolean(),blocked:c.enum(["closed","draft","conflict","checks_failed","checks_pending","changes_requested","protected","checking"]).nullable(),methods:c.array(Nv),sha:c.string()}),PT=c.object({method:Nv,sha:c.string().min(1),deleteBranch:c.boolean().default(!1)}),jT=c.object({merged:c.literal(!0),branchDeleted:c.boolean(),branchKept:c.enum(["fork","default","protected","gone","in_use","reopened","failed"]).nullable()}),AT=c.object({installationId:c.number().int().positive(),repoId:c.number().int().positive()});var lS=16e3,dS=16e3,UT=25*1024*1024,Dv=10;var CT=c.object({path:Vn,size:c.number().int().nonnegative(),contentType:c.string(),updatedAt:R,updatedByKind:Qr,updatedBy:c.string()}),pS=c.string().trim().min(1).max(80).regex(/^[\p{L}\p{N}][\p{L}\p{N} _.-]*$/u,"Use letters, numbers, spaces, dots, dashes or underscores"),fS=c.enum(["ok","stale"]),mS=c.object({name:pS,description:c.string().max(300),content:c.string().max(dS),updatedAt:R,updatedByKind:Qr,updatedBy:c.string(),status:fS.default("ok"),staleReason:c.string().max(300).nullable().default(null),verifiedAt:R.nullable().default(null),previousContent:c.string().nullable().default(null),previousAt:R.nullable().default(null)}),ET=mS.pick({description:!0,content:!0}),RT=c.discriminatedUnion("status",[c.object({status:c.literal("ok")}),c.object({status:c.literal("stale"),reason:c.string().trim().min(1).max(300)})]),gS=c.object({text:c.string().max(lS),updatedAt:R.nullable(),updatedBy:c.string().nullable()}),MT=gS.pick({text:!0}),Uv=c.enum(["files","memory","instructions"]),Cv=c.enum(["auto","on","off"]),LT=c.object({mode:Cv,active:c.boolean(),lastRunAt:R.nullable(),threadsSince:c.number().int().nonnegative(),threadsNeeded:c.number().int().positive(),threadId:c.string().nullable()}),ZT=c.object({mode:Cv});var Np=c.object({id:zp,projectId:Ie,threadId:q.nullable(),title:c.string(),description:c.string().nullable(),version:c.number().int().positive(),createdAt:R,updatedAt:R}),JT=c.object({version:c.number().int().positive(),size:c.number().int().nonnegative(),threadId:q.nullable(),createdAt:R}),BT=c.object({version:c.number().int().positive(),url:c.string().nullable(),expiresAt:R.nullable()}),WT=2*1024*1024;var Dp=c.string().regex(pe("routine")),hS=/^(\*|\d+(-\d+)?)(\/\d+)?(,(\*|\d+(-\d+)?)(\/\d+)?)*$/,vS=c.string().trim().refine(e=>{let t=e.split(/\s+/);return t.length===5&&t.every(r=>hS.test(r))},"Expected a five-field cron expression, e.g. 0 9 * * 1-5"),yS=c.string().min(1).max(64).refine(e=>{try{return new Intl.DateTimeFormat("en-US",{timeZone:e}),!0}catch{return!1}},"Unknown time zone"),Up=c.discriminatedUnion("kind",[c.object({kind:c.literal("cron"),cron:vS,timezone:yS.default("UTC")}),c.object({kind:c.literal("once"),at:R})]),Cp=c.discriminatedUnion("kind",[c.object({kind:c.literal("coordinator")}),c.object({kind:c.literal("thread"),threadId:q})]),Ep=c.object({id:Dp,projectId:Ie,name:c.string(),prompt:c.string(),target:Cp,schedule:Up,paused:c.boolean(),nextRunAt:R.nullable(),lastRunAt:R.nullable(),runCount:c.number().int().nonnegative(),createdBy:c.string(),createdAt:R}),YT=c.object({name:c.string().trim().min(1).max(120),prompt:c.string().trim().min(1).max(8e3),target:Cp.default({kind:"coordinator"}),schedule:Up}),QT=c.object({name:c.string().trim().min(1).max(120),prompt:c.string().trim().min(1).max(8e3),target:Cp,schedule:Up,paused:c.boolean()}).partial();var Rp=c.object({text:c.string(),until:c.string(),createdBy:c.string(),createdAt:c.string(),wakes:c.number().int().nonnegative(),threads:c.number().int().nonnegative(),idle:c.number().int().nonnegative()});var $S=c.string().regex(pe("sshHost")),Mp=c.string().regex(/^[a-z0-9][a-z0-9_-]{0,39}$/,"Use lowercase letters, digits, - and _ (up to 40)."),ka=c.string().trim().min(1).max(253).regex(/^(?:[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?(?:\.[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?)*\.?|\[?[0-9A-Fa-f:.]+\]?)$/,"Enter a host name or IP address."),Ev=c.string().trim().regex(/^[A-Za-z0-9_][A-Za-z0-9_.-]{0,63}$/,"Enter the user name on the server."),Rv=c.enum(["ask","off"]),aN=c.string().max(16e3).regex(/^(?:ssh|ecdsa|sk)-[\w@.-]+ [A-Za-z0-9+/=]+(?: .*)?$/),Mv=c.string().max(200).regex(/^SHA256:[A-Za-z0-9+/=]+$/),bS=c.object({id:$S,projectId:Ie,alias:Mp,host:c.string(),port:c.number().int(),user:c.string(),runnerId:c.string(),runnerName:c.string(),mine:c.boolean(),keySource:c.enum(["new","existing"]),publicKey:c.string().nullable(),keyFingerprint:c.string().nullable(),hostFingerprint:c.string().nullable(),rule:Rv,testedAt:R.nullable(),createdAt:R}),_S=c.object({id:c.string(),alias:c.string(),threadId:c.string().nullable(),command:c.string(),reason:c.string().nullable(),decision:c.enum(["once","turn","deny","timeout","failed"]),approvedBy:c.string().nullable(),exitCode:c.number().int().nullable(),ms:c.number().int().nullable(),at:R}),sN=c.object({hosts:c.array(bS),history:c.array(_S)}),cN=c.object({runnerId:c.string(),alias:Mp,host:ka,port:c.number().int().min(1).max(65535).default(22),user:Ev,existingKey:c.string().min(1).max(1024).optional()}),uN=c.object({rule:Rv}),lN=c.object({hostKey:c.string().min(1).max(16e3)}),Lv=c.object({type:c.string().max(60),key:c.string().max(16e3),fingerprint:Mv}),Zv=c.object({path:c.string().max(1024),name:c.string().max(255),type:c.string().max(60),fingerprint:Mv,comment:c.string().max(500)}),Fv=c.object({exitCode:c.number().int().nullable(),stdout:c.string(),stderr:c.string(),truncated:c.boolean(),ms:c.number().int().nonnegative(),error:c.enum(["hostkey","auth","connect","timeout","nokey","other"]).optional()}),Vv=300*1e3,Kv=200*1024,wa=c.object({projectId:Ie,alias:Mp}),Lp=wa.extend({host:ka,port:c.number().int().min(1).max(65535),user:Ev,hostKey:c.string().min(1).max(16e3)});var Wv=2,it=c.string().regex(pe("runner")),Je=c.enum(["claude","codex","antigravity","opencode","hermes","cursor","muse","kimi"]);var Gv=c.object({path:c.string().min(1).max(1024),name:c.string().max(255)}),xS=c.object({kind:c.string().max(40),usedPercent:c.number().min(0).max(1e3).nullable(),resetsAt:R.nullable()}),kS=c.object({status:c.enum(["ok","warning","limited"]).optional(),windows:c.array(xS).max(8),at:R});var wS=c.object({id:c.string().min(1).max(200),name:c.string().max(200),efforts:c.array(c.string().min(1).max(20)).max(10)});var SS=c.object({id:Je,version:c.string().max(200).nullable(),limits:kS.optional().catch(void 0),models:c.array(wS).max(100).optional().catch(void 0)}),IS=c.enum(["folders","cancel","agent","agent-clis","connectors","skills","project-folders","files","settings","update","models","github-token","git-token","steer","steer-claude","ssh"]),zS=c.discriminatedUnion("transport",[c.object({transport:c.literal("http"),name:c.string().regex(/^[a-z][a-z0-9_-]{0,40}$/),path:c.string().regex(/^\/api\/[\w/-]+$/).max(300)}),c.object({transport:c.literal("stdio"),name:c.string().regex(/^[a-z][a-z0-9_-]{0,40}$/),command:c.string().min(1).max(200),args:c.array(c.string().max(2e3)).max(50),env:c.record(c.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/),c.string().max(4e3))})]),PS=c.enum(["read","edit","auto","full"]),Fp=c.object({access:PS,worktrees:c.boolean(),autoUpdate:c.boolean(),remote:c.boolean()}),qv=Fp.omit({remote:!0}).partial(),jS=c.enum(["service","app","manual"]),Zp=c.object({state:c.enum(["waiting","downloading","restarting","failed","rolled-back"]),version:c.string().max(50),running:c.number().int().nonnegative().optional(),message:c.string().max(500).optional(),at:R}),Hv=c.object({version:c.string().max(50),hostname:c.string().max(255),platform:c.string().max(50),folders:c.array(Gv).max(200),clis:c.array(c.unknown()).max(10).transform(e=>e.flatMap(t=>{let r=SS.safeParse(t);return r.success?[r.data]:[]})),features:c.array(c.string().max(50)).max(20).default([]).transform(e=>e.filter(t=>IS.safeParse(t).success)),settings:Fp.optional().catch(void 0),updates:jS.optional().catch(void 0),update:Zp.optional().catch(void 0)}),Sa=1e5,Q=c.string().min(1).max(64),AS=c.object({name:c.string().max(255),path:c.string().max(1024)}),OS=c.object({path:c.string().max(1024),parent:c.string().max(1024).nullable(),home:c.string().max(1024),dirs:c.array(AS).max(1e3)}),Jv=c.object({inputTokens:c.number().int().nonnegative(),outputTokens:c.number().int().nonnegative(),model:c.string().max(200).optional()}),Vp=512*1024,TS=c.object({path:c.string().max(4096),size:c.number().int().nonnegative(),data:c.string().max(Math.ceil(Vp/3)*4+4),truncated:c.boolean()}),NS=c.object({model:c.string().min(1).max(200).optional(),effort:c.string().min(1).max(20).optional()}),Bv=c.object({token:c.string().min(20).max(4096),expiresAt:R,repos:c.array(c.string().regex(/^[\w.-]+\/[\w.-]+$/).max(200)).max(100)}),hN=c.discriminatedUnion("type",[Hv.extend({type:c.literal("hello"),protocol:c.number().int().positive(),running:c.array(ze).max(100).default([]),interrupted:c.array(ze).max(100).default([])}),c.object({type:c.literal("task.progress"),taskId:ze,text:c.string().max(2e3),usage:Jv.optional(),agent:Ap.optional(),ms:c.number().nonnegative().optional()}),c.object({type:c.literal("task.done"),taskId:ze,ok:c.boolean(),usage:Jv.optional(),result:c.string().max(Sa),cancelled:c.boolean().optional()}),c.object({type:c.literal("ping")}),c.object({type:c.literal("task.folders"),taskId:ze,folders:c.array(c.string().min(1).max(1024)).max(60)}),OS.extend({type:c.literal("dirs"),requestId:Q}),c.object({type:c.literal("folders"),requestId:Q,folders:c.array(Gv).max(200)}),c.object({type:c.literal("request.failed"),requestId:Q,message:c.string().max(500)}),TS.extend({type:c.literal("file"),requestId:Q}),c.object({type:c.literal("settings"),requestId:Q,settings:Fp}),c.object({type:c.literal("update.accepted"),requestId:Q,update:Zp}),c.object({type:c.literal("update.status"),update:Zp.nullable()}),c.object({type:c.literal("task.steered"),requestId:Q,taken:c.boolean()}),c.object({type:c.literal("ssh.key"),requestId:Q,publicKey:c.string().max(16e3),fingerprint:c.string().max(200),protected:c.boolean()}),c.object({type:c.literal("ssh.keylist"),requestId:Q,keys:c.array(Zv).max(100)}),c.object({type:c.literal("ssh.hostkeylist"),requestId:Q,keys:c.array(Lv).max(10)}),Fv.extend({type:c.literal("ssh.result"),requestId:Q})]),Xv=c.discriminatedUnion("type",[c.object({type:c.literal("welcome"),runnerId:it,name:c.string()}),c.object({type:c.literal("task.start"),taskId:ze,threadId:q,folder:c.string().min(1).max(1024),cli:Je,prompt:c.string().min(1).max(Sa),model:NS.optional(),folders:c.array(c.string().min(1).max(1024)).max(50).optional(),agent:c.object({mcpPath:c.string().regex(/^\/api\/[\w/-]+$/).max(300),token:c.string().min(20).max(200),connectors:c.array(zS).max(30).optional(),skills:c.object({path:c.string().regex(/^\/api\/[\w/-]+$/).max(300)}).optional(),resume:c.object({after:ze,prompt:c.string().min(1).max(Sa)}).optional()}).optional(),github:Bv.optional()}),c.object({type:c.literal("task.github"),taskId:ze,github:Bv}),c.object({type:c.literal("task.steer"),requestId:Q,taskId:ze,text:c.string().min(1).max(Sa)}),c.object({type:c.literal("task.cancel"),taskId:ze}),c.object({type:c.literal("pong")}),c.object({type:c.literal("dirs.list"),requestId:Q,path:c.string().max(1024).optional()}),c.object({type:c.literal("folder.share"),requestId:Q,path:c.string().min(1).max(1024)}),c.object({type:c.literal("folder.unshare"),requestId:Q,path:c.string().min(1).max(1024)}),c.object({type:c.literal("file.read"),requestId:Q,path:c.string().min(1).max(4096),folders:c.array(c.string().min(1).max(1024)).min(1).max(51),threadId:q.optional()}),c.object({type:c.literal("settings.set"),requestId:Q,settings:qv}),c.object({type:c.literal("runner.update"),requestId:Q,version:c.string().regex(/^\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?$/).max(50),now:c.boolean().default(!1)}),wa.extend({type:c.literal("ssh.keygen"),requestId:Q,comment:c.string().max(200),existing:c.string().min(1).max(1024).optional()}),c.object({type:c.literal("ssh.keys"),requestId:Q}),c.object({type:c.literal("ssh.hostkeys"),requestId:Q,host:ka,port:c.number().int().min(1).max(65535)}),c.object({type:c.literal("ssh.test"),requestId:Q,target:Lp}),c.object({type:c.literal("ssh.run"),requestId:Q,target:Lp,command:c.string().min(1).max(2e4)}),wa.extend({type:c.literal("ssh.forget"),requestId:Q})]),DS=Hv.extend({id:it,name:c.string(),version:c.string().nullable(),online:c.boolean(),lastSeenAt:R.nullable(),createdAt:R}),vN=c.object({name:c.string().trim().min(1).max(80).optional(),settings:qv.optional()}),yN=c.object({now:c.boolean().default(!1)}),$N=c.object({runners:c.array(DS),latestVersion:c.string().nullable()}),bN=c.object({code:c.string(),expiresAt:R}),_N=c.object({code:c.string().trim().min(4).max(20),name:c.string().trim().min(1).max(80),hostname:c.string().max(255).default(""),platform:c.string().max(50).default("")}),Yv=c.object({runner:c.object({id:it,name:c.string()}),token:c.string()}),xN=c.object({projectId:Ie,runnerId:it,runnerName:c.string(),path:c.string(),folders:c.array(c.string()).default([]),cli:Je,online:c.boolean(),isDefault:c.boolean().default(!0)}),kN=c.object({path:c.string().trim().min(1).max(1024)}),wN=c.object({runnerId:it,path:c.string().min(1).max(1024),cli:Je,add:c.boolean().optional()}),SN=c.object({path:c.string().min(1).max(1024),runnerId:it.optional()}),IN=c.object({runnerId:it});function Qv(e,t){let r=i=>i.split("-")[0].split(".").map(a=>Number.parseInt(a,10)||0),[o,n]=[r(e),r(t)];for(let i=0;i<3;i++)if((o[i]??0)!==(n[i]??0))return(o[i]??0)>(n[i]??0);return!1}var US=200,CS=c.object({threadId:q.nullable(),hasEarlier:c.boolean()});var CN=c.discriminatedUnion("type",[c.object({type:c.literal("message.send"),clientId:c.string().max(64).optional(),threadId:q.nullable().default(null),body:c.string().trim().max(Tp),attachments:c.array(Vn).max(Dv).default([]),clis:c.array(Je).max($a).optional()}).refine(e=>e.body.length>0||e.attachments.length>0,"Write something or attach a file"),c.object({type:c.literal("message.edit"),messageId:Bt.shape.id,body:c.string().trim().max(Tp)}),c.object({type:c.literal("thread.resolve"),threadId:q,resolved:c.boolean(),reason:Pp.optional()}),c.object({type:c.literal("thread.cli"),threadId:q,cli:Je.nullable()}),c.object({type:c.literal("thread.runner"),threadId:q,runnerId:c.union([it,c.literal(jv)]).nullable()}),c.object({type:c.literal("thread.model"),threadId:q,cli:Je,model:c.string().trim().min(1).max(200).nullable(),effort:c.string().trim().min(1).max(20).nullable()}),c.object({type:c.literal("goal.stop")}),c.object({type:c.literal("sync"),afterSeq:c.number().int().nonnegative(),all:c.boolean().optional(),recent:c.number().int().positive().max(US).optional()})]),EN=c.discriminatedUnion("type",[c.object({type:c.literal("message.created"),message:Bt}),c.object({type:c.literal("message.updated"),message:Bt}),c.object({type:c.literal("message.ack"),clientId:c.string(),messageId:Bt.shape.id,seq:Bt.shape.seq}),c.object({type:c.literal("sync.result"),messages:c.array(Bt),hasMore:c.boolean(),streamed:c.boolean().optional(),threads:c.array(jp).default([]),reactions:c.array(Op).default([]),artifacts:c.array(Np).default([]),routines:c.array(Ep).default([]),goal:Rp.nullable().optional(),windows:c.array(CS).optional(),reset:c.boolean().optional(),lastSeq:c.number().int().nonnegative().optional()}),c.object({type:c.literal("thread.updated"),thread:jp}),c.object({type:c.literal("reaction.added"),reaction:Op}),c.object({type:c.literal("artifact.updated"),artifact:Np}),c.object({type:c.literal("routine.updated"),routine:Ep}),c.object({type:c.literal("routine.deleted"),routineId:Dp}),c.object({type:c.literal("goal.updated"),goal:Rp.nullable()}),c.object({type:c.literal("agent.activity"),threadId:q.nullable(),active:c.boolean(),label:c.string().max(200).optional()}),c.object({type:c.literal("knowledge.changed"),kind:Uv}),c.object({type:c.literal("workspace.changed")}),c.object({type:c.literal("task.updated"),task:Av}),c.object({type:c.literal("task.output"),taskId:ze,threadId:q,lines:c.array(Ov)}),c.object({type:c.literal("pr.updated"),pullRequest:Tv}),c.object({type:c.literal("error"),code:c.string(),message:c.string()})]);var LN=c.object({app:c.literal("myrel"),apiVersion:c.number().int().positive(),name:c.string(),auth:c.object({emailPassword:c.boolean(),signUp:c.boolean().default(!0),emailVerification:c.boolean().default(!1),captcha:c.object({provider:c.literal("turnstile"),siteKey:c.string()}).nullable().default(null),passwordReset:c.boolean().default(!1)}),billing:c.boolean().default(!1),legal:c.object({terms:c.string().url(),privacy:c.string().url(),version:c.string()}).nullable().default(null)});var VN=c.object({question:c.string().min(1).max(300),options:c.array(c.object({label:c.string().min(1).max(40),consequence:c.string().max(200).default("")})).min(2).max(4),recommended:c.number().int().nonnegative().optional(),danger:c.boolean().optional()});var ei=c.enum(["fireworks","anthropic","openai"]),HN=c.object({id:ei,name:c.string(),defaultModel:c.string(),serverKey:c.boolean()}),XN=c.object({id:c.string(),provider:ei,label:c.string(),hint:c.string(),scope:c.enum(["user","instance"]),createdAt:c.iso.datetime()}),YN=c.object({provider:ei,label:c.string().trim().min(1).max(80),key:c.string().trim().min(8).max(500),scope:c.enum(["user","instance"]).default("user")}),ey=c.enum(["auto","local","cloud"]),ty=c.enum(["opencode","claude","codex"]),ES=c.object({model:c.string().trim().min(1).max(200).nullable(),effort:c.string().trim().min(1).max(20).nullable()}),ny=c.partialRecord(Je,ES),QN=c.object({name:c.string(),provider:ei.nullable(),model:c.string().nullable(),keyId:c.string().nullable(),taskTarget:ey,icon:xa.nullable().default(null),color:_a.nullable().default(null),cloudCli:ty.default("opencode"),cliModels:ny.default({})}),eD=c.object({name:c.string().trim().min(1).max(120).optional(),provider:ei.nullable().optional(),model:c.string().trim().max(200).nullable().optional(),keyId:c.string().nullable().optional(),taskTarget:ey.optional(),icon:xa.nullable().optional(),color:_a.nullable().optional(),cloudCli:ty.optional(),cliModels:ny.optional()}),ry=c.enum(["admin","member"]),tD=c.object({id:c.string(),projectId:c.string(),projectName:c.string(),email:c.string(),role:ry,invitedBy:c.string(),createdAt:c.iso.datetime()}),nD=c.object({email:c.email().trim().toLowerCase(),role:ry.default("member")}),rD=c.object({role:ba}),RS=c.enum(["admin","user"]),iD=c.enum(["computer","decision"]),oD=c.object({id:c.string(),name:c.string(),email:c.string(),role:RS,onboarded:c.boolean().optional(),tips:c.array(c.string()).optional()}),MS=c.object({signUpEnabled:c.boolean()}),LS=c.enum(["api","agent","cron","web","desktop","mobile"]),aD=c.object({platform:c.enum(["web","desktop","mobile"]),where:c.string().trim().min(1).max(200),name:c.string().max(100).default("Error"),message:c.string().max(500),stack:c.string().max(4e3).optional(),version:c.string().max(40).optional()}),sD=c.object({id:c.string(),source:LS,where:c.string(),name:c.string(),message:c.string(),stack:c.string().nullable(),count:c.number().int(),firstSeenAt:c.number(),lastSeenAt:c.number()}),cD=c.object({days:c.number().int(),signedUp:c.number().int(),verified:c.number().int(),inProject:c.number().int(),asked:c.number().int(),threadRan:c.number().int(),pairedComputer:c.number().int()}),uD=MS.partial();var iy=c.string().regex(pe("notification")),ZS=c.enum(["done","ready","decision","blocked","failed"]),mD=c.object({id:iy,projectId:Ie,threadId:q.nullable(),kind:ZS,title:c.string(),body:c.string(),url:c.string(),readAt:R.nullable(),createdAt:R}),gD=c.object({email:c.boolean(),push:c.boolean()}),hD=c.object({webPushKey:c.string().nullable(),email:c.boolean()}),FS=[/^fcm\.googleapis\.com$/,/^updates\.push\.services\.mozilla\.com$/,/^web\.push\.apple\.com$/,/^[a-z0-9-]+\.notify\.windows\.com$/];function VS(e){try{let t=new URL(e);return t.protocol==="https:"&&FS.some(r=>r.test(t.hostname))}catch{return!1}}var vD=c.discriminatedUnion("kind",[c.object({kind:c.literal("webpush"),endpoint:c.url().max(2048).refine(VS,"Not a browser push service"),keys:c.object({p256dh:c.string().min(1).max(256),auth:c.string().min(1).max(64)})}),c.object({kind:c.literal("expo"),token:c.string().regex(/^Expo(nent)?PushToken\[[^\]]+\]$/).max(256)})]),yD=c.union([c.object({ids:c.array(iy).min(1).max(200)}),c.object({all:c.literal(!0)})]);var KS=new RegExp(pe("thread").source.slice(1,-1)),wD=new RegExp(`^#(${KS.source})$`);var JS=c.enum(["http","stdio"]),BS=c.enum(["user","project"]),Jp=c.enum(["cloud","local","both"]),WS=c.enum(["unknown","ok","error","needs_auth"]),GS=c.enum(["none","headers","oauth"]),oy=c.string().regex(/^[a-z][a-z0-9_-]{0,31}$/).refine(e=>e!=="myrel","That name is taken by Myrel's own tools."),qS=c.object({name:c.string(),description:c.string().optional()}),HS=/^[A-Za-z_][\w-]{0,99}$/,XS=/^[A-Za-z_][A-Za-z0-9_]{0,99}$/,ay=(e,t,r)=>c.record(c.string().regex(e),c.string().max(4e3),{error:o=>o.code==="invalid_key"?`${t} name ${JSON.stringify(o.input)} is not valid: use only ${r}, with no spaces or ":". Put the value in its own field.`:void 0}),sy=ay(HS,"Header","letters, digits, - and _"),YS=ay(XS,"Variable","letters, digits and _"),zD=c.object({id:c.string(),name:c.string(),slug:c.string(),scope:BS,transport:JS,url:c.string().nullable(),auth:GS,command:c.string().nullable(),args:c.array(c.string()),runsOn:Jp,secretNames:c.array(c.string()),enabled:c.boolean(),status:WS,lastError:c.string().nullable(),tools:c.array(qS),canEdit:c.boolean(),createdAt:c.iso.datetime(),official:c.object({id:c.string(),title:c.string(),iconUrl:c.string().nullable()}).nullable().default(null)}),Kp=c.string().trim().min(1).max(60),PD=c.discriminatedUnion("transport",[c.object({transport:c.literal("http"),name:Kp,slug:oy.optional(),url:c.url({protocol:/^https$/}).max(2e3),auth:c.enum(["headers","oauth"]).default("headers"),headers:sy.default({})}),c.object({transport:c.literal("stdio"),name:Kp,slug:oy.optional(),command:c.string().trim().min(1).max(200),args:c.array(c.string().max(2e3)).max(50).default([]),env:YS.default({}),runsOn:Jp.default("both")})]),jD=c.object({name:Kp.optional(),enabled:c.boolean().optional(),url:c.url({protocol:/^https$/}).max(2e3).optional(),command:c.string().trim().min(1).max(200).optional(),args:c.array(c.string().max(2e3)).max(50).optional(),runsOn:Jp.optional(),secrets:sy.optional()});var AD=c.object({authorizeUrl:c.url()});var QS=["developer","productivity","communication","design","data","sales","finance","search","ai","other"],cy=c.enum(QS);var eI=c.object({id:c.string(),title:c.string(),description:c.string(),websiteUrl:c.string().nullable(),iconUrl:c.string().nullable(),url:c.string(),auth:c.enum(["oauth","headers"]),headerHint:c.object({name:c.string(),placeholder:c.string()}).nullable(),category:cy,official:c.boolean()}),OD=c.object({connectors:c.array(eI),nextOffset:c.number().nullable(),syncedAt:c.iso.datetime().nullable(),categories:c.array(c.object({id:cy,count:c.number()}))}),tI=[{id:"com.notion/mcp",category:"productivity"},{id:"app.linear/linear",category:"productivity"},{id:"com.atlassian/atlassian-mcp-server",category:"productivity"},{id:"com.figma.mcp/mcp",category:"design"},{id:"com.stripe/mcp",category:"finance"},{id:"com.canva.mcp/mcp",category:"design"},{id:"com.vercel/vercel-mcp",category:"developer"},{id:"com.gitlab/mcp",category:"developer"},{id:"io.github.PostHog/mcp",category:"data"},{id:"com.zapier/mcp",category:"productivity"},{id:"com.airtable/mcp",category:"data"},{id:"com.monday/monday.com",category:"productivity"},{id:"com.paypal.mcp/mcp",category:"finance"},{id:"com.webflow/mcp",category:"design"},{id:"com.wix/mcp",category:"design"},{id:"com.neon/mcp",category:"developer"},{id:"com.railway/mcp",category:"developer"},{id:"co.huggingface/hf-mcp-server",category:"ai"},{id:"com.cloudflare.mcp/mcp",category:"developer"},{id:"com.apify/apify-mcp-server",category:"search"},{id:"ai.exa/exa",category:"search"},{id:"com.microsoft/microsoft-learn-mcp",category:"search"}],TD=tI.map(e=>e.id);var nI=c.enum(["user","project"]),rI=c.string().max(64).regex(/^[a-z0-9]+(-[a-z0-9]+)*$/,"Use lowercase letters, digits and hyphens, like pdf-forms."),uy=c.string().trim().min(1).max(1024),iI=c.string().min(1).max(300).regex(/^[\w@+=,.~ -]+(\/[\w@+=,.~ -]+)*$/,"Invalid file path.").refine(e=>!e.split("/").some(t=>t==="."||t===".."),"Invalid file path."),ly={files:200,bytes:5*1024*1024,fileBytes:1024*1024};var oI=c.discriminatedUnion("kind",[c.object({kind:c.literal("write")}),c.object({kind:c.literal("upload")}),c.object({kind:c.literal("github"),repo:c.string(),path:c.string(),ref:c.string().optional(),commit:c.string()})]),aI=c.object({path:c.string(),size:c.number().int().nonnegative()}),sI=c.object({id:c.string(),name:c.string(),description:c.string(),scope:nI,source:oI,enabled:c.boolean(),files:c.array(aI),size:c.number().int().nonnegative(),canEdit:c.boolean(),createdAt:c.iso.datetime(),updatedAt:c.iso.datetime()}),UD=sI.extend({skillMd:c.string()}),cI=c.object({path:iI,content:c.string().max(Math.ceil(ly.fileBytes*4/3)+4)}),CD=c.discriminatedUnion("kind",[c.object({kind:c.literal("write"),name:rI,description:uy,instructions:c.string().max(1e5)}),c.object({kind:c.literal("upload"),files:c.array(cI).min(1).max(ly.files)}),c.object({kind:c.literal("github"),source:c.string().trim().min(3).max(500),skill:c.string().max(64).optional()})]),ED=c.object({error:c.literal("choose_skill"),skills:c.array(c.object({name:c.string(),description:c.string(),path:c.string()}))}),RD=c.object({enabled:c.boolean().optional(),description:uy.optional(),instructions:c.string().max(1e5).optional()}),MD=c.object({skills:c.array(c.object({name:c.string(),files:c.array(c.object({path:c.string(),content:c.string()}))}))});var LD=c.object({on:c.boolean()});var uI=c.object({id:c.string().min(1).max(200),name:c.string().min(1).max(80),description:c.string().max(300).default(""),url:c.string().max(2e3),auth:c.enum(["oauth","headers"]),headerHint:c.object({name:c.string(),placeholder:c.string()}).nullable().default(null),iconUrl:c.string().nullable().default(null),official:c.boolean().default(!1),featured:c.boolean().default(!1)}),lI=c.enum(["open","connected","dismissed"]),VD=c.object({id:c.string(),reason:c.string().min(1).max(400),offers:c.array(uI).min(1).max(3),state:lI.default("open"),connected:c.string().optional(),signIn:c.boolean().optional()});var KD=c.object({offerId:c.string().min(1).max(200),headers:c.record(c.string().regex(/^[A-Za-z_][\w-]{0,99}$/),c.string().min(1).max(4e3)).optional()}),JD=c.object({authorizeUrl:c.string().optional(),connected:c.boolean()});var dI=/^(?:\/(?:usr\/)?(?:local\/)?bin\/)?(?:ba|z|da|k)?sh\s+-l?c\s+(\S[\s\S]*)$/;function Kn(e){let t=dI.exec(e.trim());return t?pI(t[1])??e:e}function pI(e){let t="",r=0;for(;r<e.length;){let o=e[r];if(o==="'"){let n=e.indexOf("'",r+1);if(n<0)return null;t+=e.slice(r+1,n),r=n+1}else if(o==='"'){for(r++;;){if(r>=e.length)return null;let n=e[r];if(n==='"')break;n==="\\"&&r+1<e.length&&'"\\$`\n'.includes(e[r+1])?(t+=e[r+1],r+=2):(t+=n,r++)}r++}else if(o==="\\"){if(r+1>=e.length)return null;t+=e[r+1],r+=2}else{if(/\s/.test(o)||"|&;<>()$`".includes(o))return null;t+=o,r++}}return t}import{mkdir as fI,readFile as mI,rename as gI,writeFile as hI}from"node:fs/promises";import{homedir as fy}from"node:os";import{dirname as vI,join as dy}from"node:path";var my="MYREL_MCP_BRIDGE";function yI(e=fy()){return{mcp:dy(e,".gemini","config","mcp_config.json"),settings:dy(e,".gemini","antigravity-cli","settings.json")}}function ti(){let e=process.argv[1],t=!e||/\$bunfs|~BUN/.test(e);return{command:process.execPath,args:t?[]:[e]}}async function gy(e,t=fy()){let r=yI(t),o=ti(),n={command:o.command,args:[...o.args,"mcp-bridge"]};await py(r.mcp,a=>{let s=Bp(a.mcpServers)?a.mcpServers:{};return JSON.stringify(s[e])===JSON.stringify(n)?!1:(a.mcpServers={...s,[e]:n},!0)});let i=`mcp(${e}/*)`;await py(r.settings,a=>{let s=Bp(a.permissions)?a.permissions:{},u=Array.isArray(s.allow)?s.allow:[];return u.includes(i)?!1:(a.permissions={...s,allow:[...u,i]},!0)})}async function py(e,t){let r=await mI(e,"utf8").catch(i=>{if(i.code==="ENOENT")return"";throw i}),o={};if(r.trim())try{o=JSON.parse(r)}catch{throw new Error(`Could not read ${e} as JSON, so Myrel's tools were not added to Antigravity CLI. Fix the file and try again.`)}if(!Bp(o))throw new Error(`${e} is not a JSON object, so Myrel's tools were not added to Antigravity CLI.`);if(!t(o))return;await fI(vI(e),{recursive:!0});let n=`${e}.myrel-${process.pid}`;await hI(n,`${JSON.stringify(o,null,2)}
|
|
63
63
|
`,{mode:384}),await gI(n,e)}function Bp(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}import{mkdir as $I,readFile as bI,rename as _I,writeFile as xI}from"node:fs/promises";import{homedir as kI}from"node:os";import{basename as wI,join as Wp,resolve as vy}from"node:path";function ne(){return process.env.MYREL_RUNNER_HOME||Wp(kI(),".myrel-runner")}var Jn=()=>Wp(ne(),"config.json");async function ni(){let e=await $e(Jn()),t={folders:[],access:"edit",...e};return process.env.MYREL_SERVER&&(t.server=process.env.MYREL_SERVER),process.env.MYREL_RUNNER_TOKEN&&(t.token=process.env.MYREL_RUNNER_TOKEN),t}var SI=["MYREL_RUNNER_TOKEN"],II=["SSH_AUTH_SOCK"];function kt(e){let t={...process.env,...e};for(let r of[...SI,...II])delete t[r];return t}async function za(e){let t={...e};process.env.MYREL_RUNNER_TOKEN&&t.token===process.env.MYREL_RUNNER_TOKEN&&(t.token=(await $e(Jn()))?.token),await Le(Jn(),t)}function yy(e,t){let r=vy(t);return e.folders.some(o=>o.path===r)?!1:(e.folders.push({path:r,name:wI(r)||r}),!0)}function $y(e,t){let r=vy(t),o=e.folders.length;return e.folders=e.folders.filter(n=>n.path!==r),e.folders.length!==o}var Ia=class{constructor(t=Wp(ne(),"sessions.json")){this.path=t}path;async get(t,r="claude"){let o=(await $e(this.path))?.[hy(t,r)];return typeof o=="string"?{id:o}:o}async set(t,r,o){let n=await $e(this.path)??{};n[hy(t,r)]=o,await Le(this.path,n)}},hy=(e,t)=>t==="claude"?e:`${t}:${e}`;async function $e(e){try{return JSON.parse(await bI(e,"utf8"))}catch(t){if(t.code==="ENOENT")return;throw t}}async function Le(e,t){await $I(ne(),{recursive:!0,mode:448});let r=`${e}.${process.pid}.tmp`;await xI(r,`${JSON.stringify(t,null,2)}
|
|
64
64
|
`,{mode:384}),await _I(r,e)}import{open as zI,readdir as PI,stat as jI}from"node:fs/promises";import{homedir as AI}from"node:os";import{join as Wt}from"node:path";var OI={five_hour:"session",seven_day:"weekly",seven_day_opus:"weekly_opus",seven_day_sonnet:"weekly_sonnet"},Bn=e=>typeof e=="number"&&Number.isFinite(e)?e:null,by=e=>e!==null&&e>0?new Date(e*1e3).toISOString():null,_y=e=>e===null?null:Math.min(1e3,Math.max(0,Math.round(e*10)/10));function xy(e,t){if(!e||typeof e!="object")return t;let r=e,o=new Map((t?.windows??[]).map(a=>[a.kind,a])),n=(a,s,u)=>{let l=typeof a=="string"?OI[a]:void 0;if(!l)return;let d=Bn(s),p=o.get(l);o.set(l,{kind:l,usedPercent:d===null?p?.usedPercent??null:_y(d*100),resetsAt:by(Bn(u))??p?.resetsAt??null})};if(n(r.rateLimitType,r.utilization,r.resetsAt),r.unifiedWindows&&typeof r.unifiedWindows=="object")for(let[a,s]of Object.entries(r.unifiedWindows))s&&typeof s=="object"&&n(a,s.utilization,s.resetsAt);let i={allowed:"ok",allowed_warning:"warning",rejected:"limited"}[String(r.status)];return!o.size&&!i?t:{...i&&{status:i},windows:[...o.values()].slice(0,8),at:new Date().toISOString()}}function TI(e){return e===300?"session":e===10080?"weekly":e?`${e}m`:"other"}function Gp(e,t){if(!e||typeof e!="object")return;let r=[];for(let n of["primary","secondary"]){let i=e[n];if(!i||typeof i!="object")continue;let a=Bn(i.resets_in_seconds),s=by(Bn(i.resets_at))??(a!==null?new Date(new Date(t).getTime()+a*1e3).toISOString():null);r.push({kind:TI(Bn(i.window_minutes)),usedPercent:_y(Bn(i.used_percent)),resetsAt:s})}return r.length?{status:r.some(n=>(n.usedPercent??0)>=100&&(!n.resetsAt||n.resetsAt>new Date().toISOString()))?"limited":"ok",windows:r,at:t}:void 0}function NI(){return process.env.CODEX_HOME||Wt(AI(),".codex")}async function Pa(e){return(await PI(e).catch(()=>[])).sort().reverse()}var DI=256*1024;async function UI(e){let t=await zI(e,"r").catch(()=>null);if(t)try{let{size:r}=await t.stat(),o=Math.min(r,DI),n=Buffer.alloc(o);await t.read(n,0,o,r-o);let i=n.toString("utf8").split(`
|
|
65
65
|
`).reverse();for(let a of i)if(a.includes('"rate_limits"'))try{let s=JSON.parse(a);if(s.payload?.type!=="token_count")continue;let u=typeof s.timestamp=="string"&&!Number.isNaN(Date.parse(s.timestamp))?new Date(s.timestamp).toISOString():(await jI(e)).mtime.toISOString(),l=Gp(s.payload.rate_limits,u);if(l)return l}catch{}return}finally{await t.close()}}async function ja(e){let t=Wt(NI(),"sessions"),r=0;for(let o of await Pa(t))for(let n of await Pa(Wt(t,o)))for(let i of await Pa(Wt(t,o,n))){let a=Wt(t,o,n,i);for(let s of await Pa(a)){if(!s.endsWith(".jsonl")||e&&!s.includes(e))continue;let u=await UI(Wt(a,s));if(u||e)return u;if(++r>=20)return}if(e&&++r>=14)return}}var ky=()=>Wt(ne(),"limits.json");async function wy(){return await $e(ky()).catch(()=>{})??{}}async function Sy(e){await Le(ky(),e)}import{execFile as CI}from"node:child_process";import{existsSync as EI}from"node:fs";import{homedir as RI}from"node:os";import{delimiter as Iy,dirname as MI,join as ot}from"node:path";async function zy(){let e=[MI(process.execPath),...process.platform==="win32"?[...await KI(),...JI()]:[]];process.env.PATH=LI(process.env.PATH??"",e,Iy,process.platform==="win32")}function LI(e,t,r=Iy,o=!1){let n=s=>{let u=s.trim().replace(/[\\/]+$/,"");return o?u.toLowerCase():u},i=e.split(r).filter(Boolean),a=new Set(i.map(n));for(let s of t)!s.trim()||a.has(n(s))||(a.add(n(s)),i.push(s.trim()));return i.join(r)}function ZI(e,t=process.env){let r=new Map(Object.entries(t).map(([o,n])=>[o.toLowerCase(),n]));return e.replace(/%([^%;]+)%/g,(o,n)=>r.get(n.toLowerCase())??o)}function FI(e){return e.split(/\r?\n/).find(r=>/^\s*Path\s+REG_(EXPAND_)?SZ\s/i.test(r))?.replace(/^\s*Path\s+REG_(EXPAND_)?SZ\s+/i,"").trim()||void 0}var VI=["HKLM\\SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment","HKCU\\Environment"];async function KI(){return(await Promise.all(VI.map(t=>new Promise(r=>{CI("reg",["query",t,"/v","Path"],{timeout:5e3,windowsHide:!0},(o,n)=>r(o?void 0:FI(n)))})))).flatMap(t=>t?ZI(t).split(";"):[])}function JI(){let e=RI(),t=process.env.APPDATA??ot(e,"AppData","Roaming"),r=process.env.LOCALAPPDATA??ot(e,"AppData","Local");return[ot(t,"npm"),process.env.PNPM_HOME??ot(r,"pnpm"),ot(e,".bun","bin"),ot(e,".local","bin"),ot(e,"scoop","shims"),ot(r,"Microsoft","WinGet","Links"),ot(r,"Volta","bin")].filter(o=>EI(o))}function ri(e,t,r){e.progress=t;let o=r&&BI(e,r);o?e.progressAgent=o:delete e.progressAgent}function Wn(e,t,r,o="",n={}){let i=e.agents??=new Map;if(i.has(t)||i.size>=100)return;let a=r.trim().slice(0,100)||`Agent ${i.size+1}`;i.set(t,{label:a,started:Date.now(),...n.background&&{background:!0},...n.model&&{model:n.model.slice(0,200)}}),(e.agentNotes??=[]).push({text:WI(o),agent:{id:t,label:a,state:"started"}})}function wt(e,t,r,o=""){let n=e.agents?.get(t);if(!n||n.done)return;n.done=!0;let i={id:t,label:n.label,state:r?"done":"failed",...n.model&&{model:n.model},...n.tokens&&{tokens:n.tokens}};(e.agentNotes??=[]).push({text:o.trim().slice(0,2e3),agent:i,ms:Date.now()-n.started})}function Aa(e,t,r,o){let n=e.agents?.get(t);n&&(n.tokens=(n.tokens??0)+Math.max(0,Math.round(r)),o&&!n.model&&(n.model=o.slice(0,200)))}function BI(e,t){e.agents?.has(t)||Wn(e,t,"");let r=e.agents?.get(t);return r&&{id:t,label:r.label}}function WI(e){return(e.trim().split(`
|
|
@@ -75,36 +75,36 @@ ${Oy[t]}`:e,agent:async e=>({args:[],mcpServers:Ly(e)}),line:(e,t)=>t.acp?.recei
|
|
|
75
75
|
${Ny[t]}`:e,agent:async e=>({args:[],mcpServers:Ly(e)}),line:(e,t)=>t.acp?.receive(e),isMine:e=>/^v?\d+\.\d+/.test(e),models:async()=>$z(await It("kimi",["provider","list","--json"])??"")};function $z(e){try{let{models:t}=JSON.parse(e);if(!t||typeof t!="object")return;let r=Object.entries(t).flatMap(([o,n])=>{if(!Be(o)||!n||typeof n!="object")return[];let u=((Array.isArray(n.capabilities)?n.capabilities:[]).some(d=>d==="thinking"||d==="always_thinking")&&Array.isArray(n.supportEfforts)?n.supportEfforts:[]).filter(d=>typeof d=="string"&&d!=="off"&&Be(d)),l=[n.displayName,n.model].find(d=>typeof d=="string"&&!!d)??o;return[{id:o,name:l,efforts:u}]});return r.length?r.slice(0,100):void 0}catch{return}}var oi={claude:nz,codex:rz,antigravity:oz,opencode:sz,hermes:uz,cursor:dz,muse:gz,kimi:yz},Xp=process.platform==="win32"?3e4:1e4;function Yp(e){return new Promise(t=>{qp(e,["--version"],{timeout:Xp,shell:process.platform==="win32",env:kt()},(r,o)=>{t(r?null:ii(o)||null)})})}var Dy=new Map;async function Zy(e){if(process.env.MYREL_CODEX_EXEC==="1")return!1;let t=await Yp(e);if(!t)return!1;let r=Dy.get(t);return r||(r=It(e,["app-server","--help"],1e4).then(o=>!!o?.includes("--listen")),Dy.set(t,r)),r}var Uy=new Map;async function Fy(e){if(process.env.MYREL_CLAUDE_ONESHOT==="1")return!1;let t=await Yp(e);if(!t)return!1;let r=Uy.get(t);return r||(r=It(e,["--help"],1e4).then(o=>!!o?.includes("--replay-user-messages")),Uy.set(t,r)),r}async function Qp(e){return await zy().catch(()=>{}),(await Promise.all(Object.values(oi).map(r=>new Promise(o=>{qp(r.bin,["--version"],{timeout:Xp,shell:process.platform==="win32",env:kt(),windowsHide:!0},(n,i,a)=>{if(n||r.isMine&&!r.isMine(ii(i)))return e?.push({id:r.id,reason:n?bz(n,a):`\`${r.bin} --version\` printed "${ii(i)}"`}),o(null);o({id:r.id,version:ii(i)||null})})})))).filter(r=>r!==null)}function bz(e,t=""){return e.killed?`no answer in ${Xp/1e3}s`:e.code==="ENOENT"?"not on PATH":ii(t)||e.message.split(`
|
|
76
76
|
`)[0]||"failed"}function re(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?Math.round(e):0}function Cy(e){let t=e??{};return{inputTokens:re(t.input_tokens)+re(t.cache_read_input_tokens)+re(t.cache_creation_input_tokens),outputTokens:re(t.output_tokens)}}function ef(e,t){let r=e.usage??={inputTokens:0,outputTokens:0};r.inputTokens+=t.inputTokens,r.outputTokens+=t.outputTokens}function Gn(e){if(!e.startsWith("{"))return null;try{return JSON.parse(e)}catch{return null}}function Vy(e){if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return}}var _z=new Set(["Agent","Task"]);function xz(e){return typeof e=="string"?e:Array.isArray(e)?e.map(t=>t.type==="text"?String(t.text??""):"").filter(Boolean).join(`
|
|
77
77
|
`):""}function St(e,t){let r=t??{},o=r.command??r.file_path??r.filePath??r.path??r.pattern??r.description;return typeof o=="string"?st(`${e}: ${o}`):e}function st(e){return e.trim().slice(0,2e3)}function ii(e){return(e.trim().split(`
|
|
78
|
-
`)[0]??"").slice(0,200)}import{readdir as kz,realpath as tf,stat as Ky}from"node:fs/promises";import{homedir as Jy}from"node:os";import{dirname as wz,isAbsolute as Sz,join as Iz,parse as zz}from"node:path";var Pz=1e3;async function By(e){let t=Jy(),r=await tf(e?Gy(e):t),n=(await kz(r,{withFileTypes:!0})).filter(u=>(u.isDirectory()||u.isSymbolicLink())&&!u.name.startsWith(".")).map(u=>({name:u.name,path:Iz(r,u.name)})),a=(await Promise.all(n.map(async u=>(await Ky(u.path).catch(()=>null))?.isDirectory()?u:null))).filter(u=>u!==null);a.sort((u,l)=>u.name.localeCompare(l.name,void 0,{sensitivity:"base"}));let s=wz(r);return{path:r,parent:s===r?null:s,home:t,dirs:a.slice(0,Pz)}}async function Wy(e){let t=await tf(Gy(e)).catch(()=>{throw new Error(`${e} does not exist on this computer.`)});if(!(await Ky(t)).isDirectory())throw new Error(`${e} is not a folder.`);if(t===zz(t).root||t===await tf(Jy()))throw new Error("Pick a project folder, not your whole home folder or disk.");return t}function Gy(e){if(!Sz(e))throw new Error(`${e} is not a full path.`);return e}import{watchFile as
|
|
78
|
+
`)[0]??"").slice(0,200)}import{readdir as kz,realpath as tf,stat as Ky}from"node:fs/promises";import{homedir as Jy}from"node:os";import{dirname as wz,isAbsolute as Sz,join as Iz,parse as zz}from"node:path";var Pz=1e3;async function By(e){let t=Jy(),r=await tf(e?Gy(e):t),n=(await kz(r,{withFileTypes:!0})).filter(u=>(u.isDirectory()||u.isSymbolicLink())&&!u.name.startsWith(".")).map(u=>({name:u.name,path:Iz(r,u.name)})),a=(await Promise.all(n.map(async u=>(await Ky(u.path).catch(()=>null))?.isDirectory()?u:null))).filter(u=>u!==null);a.sort((u,l)=>u.name.localeCompare(l.name,void 0,{sensitivity:"base"}));let s=wz(r);return{path:r,parent:s===r?null:s,home:t,dirs:a.slice(0,Pz)}}async function Wy(e){let t=await tf(Gy(e)).catch(()=>{throw new Error(`${e} does not exist on this computer.`)});if(!(await Ky(t)).isDirectory())throw new Error(`${e} is not a folder.`);if(t===zz(t).root||t===await tf(Jy()))throw new Error("Pick a project folder, not your whole home folder or disk.");return t}function Gy(e){if(!Sz(e))throw new Error(`${e} is not a full path.`);return e}import{watchFile as hP,unwatchFile as vP}from"node:fs";import{hostname as If,platform as Q$}from"node:os";import{open as f0,realpath as f$,stat as m0}from"node:fs/promises";import{isAbsolute as g0,join as h0,relative as v0,resolve as y0,sep as p$}from"node:path";import{spawn as u0}from"node:child_process";import{mkdtemp as a$,realpath as s$,rm as c$,writeFile as l0}from"node:fs/promises";import{tmpdir as u$}from"node:os";import{join as of}from"node:path";var Ca=class{constructor(t,r,o){this.io=t;this.opts=r;this.state=o}io;opts;state;nextId=0;pending=new Map;finished=!1;prompting=!1;start(){this.call("initialize",{protocolVersion:1,clientCapabilities:{fs:{readTextFile:!1,writeTextFile:!1},terminal:!1}},t=>{let{cwd:r,mcpServers:o,resume:n,dirs:i=[]}=this.opts,a=t?.agentCapabilities?.sessionCapabilities,s=i.length&&a?.additionalDirectories?{additionalDirectories:i}:{};n?this.call("session/resume",{sessionId:n,cwd:r,mcpServers:o},()=>this.opened(n)):this.call("session/new",{cwd:r,mcpServers:o,...s},u=>{this.configured(u),this.opened(String(u.sessionId??""))})})}receive(t){let r;try{r=JSON.parse(t)}catch{return}if(r.method&&r.id!==void 0)return this.answer(r);if(r.method==="session/update")return this.update(r.params?.update??{});if(typeof r.id=="number"){let o=this.pending.get(r.id);this.pending.delete(r.id),o?.(r)}}opened(t){if(!t)return this.fail("The agent started no session.");this.state.sessionId=t;let r=()=>{this.prompting=!0,this.call("session/prompt",{sessionId:t,prompt:[{type:"text",text:this.opts.prompt}]},i=>{let{stopReason:a,usage:s}=i??{};if(s){let u=l=>typeof l=="number"&&l>0?Math.round(l):0;this.state.usage={inputTokens:u(s.inputTokens),outputTokens:u(s.outputTokens)+u(s.thoughtTokens)}}this.state.failed=a==="refusal"||a==="cancelled",this.state.result=(this.state.draft??"").trim(),this.state.failed&&!this.state.result&&(this.state.result=`The agent stopped: ${String(a)}.`),this.finish()})},o=[...this.opts.config??[]],n=()=>{let i=o.shift();if(!i)return r();this.request("session/set_config_option",{sessionId:t,configId:i.id,value:i.value},a=>{a.error||this.configured(a.result),n()})};this.opts.mode?this.call("session/set_mode",{sessionId:t,modeId:this.opts.mode},n):n()}configured(t){let r=t?.configOptions;if(!Array.isArray(r))return;let o=r.find(n=>n.category==="model");typeof o?.currentValue=="string"&&o.currentValue&&(this.state.model=o.currentValue)}update(t){if(!this.prompting)return;let r=t.content;t.sessionUpdate==="agent_message_chunk"&&typeof r?.text=="string"&&(this.state.draft=(this.state.draft??"")+r.text,this.state.draft.trim()&&(this.state.progress=this.state.draft.trim().slice(0,2e3))),t.sessionUpdate==="tool_call"&&(this.state.draft=void 0,typeof t.title=="string"&&t.title&&(this.state.progress=t.title.slice(0,2e3)))}answer(t){if(t.method==="session/request_permission"){let r=t.params??{},o=r.options??[],n=this.opts.allow||this.ownTool(r.toolCall?.title),i=o.find(s=>s.kind===(n?"allow_once":"reject_once")),a=i?{outcome:"selected",optionId:i.optionId}:{outcome:"cancelled"};return this.send({jsonrpc:"2.0",id:t.id,result:{outcome:a}})}this.send({jsonrpc:"2.0",id:t.id,error:{code:-32601,message:`${t.method} is not offered by myrel-runner`}})}ownTool(t){let{serverTools:r,mcpServers:o}=this.opts;return!!r&&typeof t=="string"&&o.some(n=>t.startsWith(r(n.name)))}call(t,r,o){this.request(t,r,n=>n.error?this.fail(n.error.message||`${t} failed`):o(n.result))}request(t,r,o){let n=++this.nextId;this.pending.set(n,o),this.send({jsonrpc:"2.0",id:n,method:t,params:r})}fail(t){this.state.failed=!0,this.state.result=t,this.finish()}finish(){this.finished||(this.finished=!0,this.io.end())}send(t){this.io.write(`${JSON.stringify(t)}
|
|
79
79
|
`)}};import{request as jz}from"node:http";import{request as Az}from"node:https";var B=e=>e&&typeof e=="object"?e:{},J=e=>typeof e=="string"&&e?e:void 0,Ea=e=>typeof e=="number"&&Number.isFinite(e)&&e>0?Math.round(e):0,Oz=e=>e.trim().slice(0,2e3),Ra=class{constructor(t,r,o){this.io=t;this.opts=r;this.state=o}io;opts;state;nextId=0;pending=new Map;finished=!1;threadId;turnId;stopping=!1;steering=new Set;changes=new Map;start(){this.call("initialize",{clientInfo:{name:"myrel-runner",title:"Myrel",version:this.opts.clientVersion}},()=>{this.send({jsonrpc:"2.0",method:"initialized"});let{cwd:t,resume:r,sandbox:o,approvalPolicy:n,model:i,config:a}=this.opts,s={cwd:t,sandbox:o,approvalPolicy:n,...i?.model&&{model:i.model},...a&&{config:a}};r?this.call("thread/resume",{...s,threadId:r},u=>this.opened(u)):this.call("thread/start",s,u=>this.opened(u))})}interrupt(){return this.finished?!1:(this.stopping=!0,this.threadId&&this.turnId&&this.request("turn/interrupt",{threadId:this.threadId,turnId:this.turnId},()=>{}),!0)}steer(t){let{threadId:r,turnId:o}=this;return this.finished||this.stopping||!r||!o?Promise.resolve(!1):new Promise(n=>{let i=a=>{this.steering.delete(i),n(a)};this.steering.add(i),this.request("turn/steer",{threadId:r,expectedTurnId:o,input:[{type:"text",text:t}]},a=>i(!a.error))})}receive(t){if(!t.startsWith("{"))return;let r;try{r=JSON.parse(t)}catch{return}if(r.method&&r.id!==void 0)return void this.answer(r);if(r.method)return this.notified(r.method,B(r.params));if(typeof r.id=="number"){let o=this.pending.get(r.id);this.pending.delete(r.id),o?.(r)}}opened(t){let r=B(B(t).thread),o=J(r.id);if(!o)return this.fail("Codex started no session.");this.threadId=o,this.state.sessionId=o;let n=J(B(t).model)??J(r.model);n&&(this.state.model=n);let i=this.opts.model?.effort;this.call("turn/start",{threadId:o,input:[{type:"text",text:this.opts.prompt}],...i&&{effort:i}},a=>{this.turnId=J(B(B(a).turn).id),this.stopping&&this.interrupt()})}notified(t,r){if(this.threadId&&r.threadId!==void 0&&r.threadId!==this.threadId)return this.subagent(t,r,String(r.threadId));switch(t){case"item/started":case"item/completed":return this.item(t,B(r.item));case"thread/tokenUsage/updated":return this.addUsage(r);case"account/rateLimits/updated":{let o=Tz(r.rateLimits);o&&(this.state.limits=o);return}case"model/rerouted":{let o=J(r.toModel)??J(r.model);o&&(this.state.model=o);return}case"error":{let o=J(B(r.error).message);o&&(this.state.error=o);return}case"turn/completed":return this.completed(B(r.turn))}}subagent(t,r,o){if(t==="item/started"||t==="item/completed")return this.item(t,B(r.item),o);if(t==="thread/tokenUsage/updated"){let n=B(B(r.tokenUsage).last);return Aa(this.state,o,Ea(n.inputTokens)+Ea(n.outputTokens)),this.addUsage(r)}}addUsage(t){let r=B(B(t.tokenUsage).last),o=this.state.usage??={inputTokens:0,outputTokens:0};o.inputTokens+=Ea(r.inputTokens),o.outputTokens+=Ea(r.outputTokens)}item(t,r,o){let n=i=>ri(this.state,Oz(i),o);switch(r.type){case"commandExecution":{if(t!=="item/started")return;let a=J(B(r.commandActions?.[0]).command)??Kn(J(r.command)??"");a&&n(`$ ${a}`);return}case"fileChange":{let i=Array.isArray(r.changes)?r.changes.map(a=>J(B(a).path)).filter(a=>!!a):[];typeof r.id=="string"&&i.length&&this.changes.set(r.id,i),t==="item/started"&&i.length&&n(`Edit ${i.join(", ")}`);return}case"mcpToolCall":t==="item/started"&&n(`${J(r.server)??"mcp"}.${J(r.tool)??"tool"}`);return;case"webSearch":t==="item/started"&&J(r.query)&&n(`Search ${J(r.query)}`);return;case"agentMessage":{let i=J(r.text)?.trim();if(t!=="item/completed"||!i)return;n(i),o||(this.state.result=i);return}case"collabAgentToolCall":return this.collab(t,r);case"subAgentActivity":{let i=J(r.agentThreadId);if(!i)return;r.kind==="started"?Wn(this.state,i,Uz(r.agentPath),"",{model:J(r.model)}):r.kind==="completed"?wt(this.state,i,!0):r.kind==="interrupted"&&wt(this.state,i,!1);return}}}collab(t,r){let o=Array.isArray(r.receiverThreadIds)?r.receiverThreadIds.filter(n=>typeof n=="string"):[];if(r.tool==="spawnAgent")for(let n of o)Wn(this.state,n,"",J(r.prompt)??"",{model:J(r.model)});if(t==="item/completed")for(let[n,i]of Object.entries(B(r.agentsStates))){let a=B(i),s=J(a.message)??"";a.status==="completed"||a.status==="shutdown"?wt(this.state,n,!0,s):(a.status==="errored"||a.status==="interrupted")&&wt(this.state,n,!1,s)}}completed(t){if(this.turnId&&t.id!==void 0&&t.id!==this.turnId)return;let r=t.status;if(r!=="completed"){this.state.failed=!0;let o=J(B(t.error).message)??this.state.error;r==="interrupted"?this.state.result??="Codex stopped.":this.state.result=o??`Codex ended the turn: ${String(r)}.`}else this.state.failed=!1;this.finish()}async answer(t){let r=B(t.params),o=n=>this.send({jsonrpc:"2.0",id:t.id,result:n});switch(t.method){case"item/commandExecution/requestApproval":{let i=J(B(r.commandActions?.[0]).command)??Kn(J(r.command)??""),a=!!i&&await this.ask("Bash",{command:i,...J(r.reason)&&{description:J(r.reason)}});return o({decision:a?"accept":"decline"})}case"item/fileChange/requestApproval":{let n=[...J(r.grantRoot)?[J(r.grantRoot)]:[],...this.changes.get(String(r.itemId))??[]],i=n.length>0;for(let a of n)i&&(i=await this.ask("Edit",{file_path:a}));return o({decision:i?"accept":"decline"})}case"item/permissions/requestApproval":{let n=B(r.permissions),i=B(n.fileSystem),a=[...i.write??[],...i.read??[]].filter(l=>typeof l=="string"),s=B(n.network).enabled===!0,u=a.length>0||s;for(let l of a)u&&(u=await this.ask("Edit",{file_path:l}));return u&&s&&(u=await this.ask("Bash",{command:J(r.reason)??"network access"})),o({permissions:u?n:{},scope:"turn"})}case"mcpServer/elicitation/request":return o({action:"decline"});case"applyPatchApproval":case"execCommandApproval":return o({decision:"denied"});default:return this.send({jsonrpc:"2.0",id:t.id,error:{code:-32601,message:`${t.method} is not offered by myrel-runner`}})}}async ask(t,r){return!this.opts.ask||this.finished?!1:this.opts.ask(t,r).catch(()=>!1)}call(t,r,o){this.request(t,r,n=>n.error?this.fail(n.error.message||`${t} failed`):o(n.result))}request(t,r,o){let n=++this.nextId;this.pending.set(n,o),this.send({jsonrpc:"2.0",id:n,method:t,params:r})}fail(t){this.state.failed=!0,this.state.result=t,this.finish()}finish(){if(!this.finished){this.finished=!0;for(let t of[...this.steering])t(!1);this.io.end()}}send(t){this.finished||this.io.write(`${JSON.stringify(t)}
|
|
80
80
|
`)}};function Tz(e){let t=B(e),r=o=>{let n=B(o);return Object.keys(n).length?{used_percent:n.usedPercent,window_minutes:n.windowDurationMins,resets_at:n.resetsAt}:null};return Gp({primary:r(t.primary),secondary:r(t.secondary)},new Date().toISOString())}var Nz=900*1e3;function qy(e,t){return(r,o)=>new Promise(n=>{let i=JSON.stringify({jsonrpc:"2.0",id:1,method:"tools/call",params:{name:"approve_access",arguments:{tool_name:r,input:o}}}),s=(e.startsWith("https:")?Az:jz)(e,{method:"POST",headers:{"content-type":"application/json",accept:"application/json",authorization:`Bearer ${t}`,"content-length":Buffer.byteLength(i)},timeout:Nz},u=>{let l="";u.setEncoding("utf8"),u.on("data",d=>{l.length<1e6&&(l+=d)}),u.on("end",()=>n(u.statusCode===200&&Dz(l))),u.on("error",()=>n(!1))});s.on("timeout",()=>s.destroy()),s.on("error",()=>n(!1)),s.end(i)})}function Dz(e){try{let t=B(B(JSON.parse(e)).result).content,r=Array.isArray(t)?J(B(t[0]).text):void 0;return!!r&&B(JSON.parse(r)).behavior==="allow"}catch{return!1}}function Uz(e){return(J(e)??"").split("/").filter(Boolean).pop()??""}var Ma=class{constructor(t,r){this.io=t;this.prompt=r}io;prompt;written=0;echoed=0;ended=!1;stopping=!1;requests=0;start(){this.user(this.prompt)}steer(t){return this.ended||this.stopping?Promise.resolve(!1):(this.user(t),Promise.resolve(!0))}interrupt(){return this.ended?!1:(this.stopping=!0,this.io.write(`${JSON.stringify({type:"control_request",request_id:`myrel-${++this.requests}`,request:{subtype:"interrupt"}})}
|
|
81
81
|
`),!0)}receive(t){this.ended||(t.type==="user"&&t.isReplay===!0&&this.echoed++,t.type==="result"&&(this.stopping||this.echoed>=this.written)&&this.end())}end(){this.ended||(this.ended=!0,this.io.end())}user(t){this.written++;let r={type:"user",message:{role:"user",content:[{type:"text",text:t}]},parent_tool_use_id:null,session_id:""};this.io.write(`${JSON.stringify(r)}
|
|
82
82
|
`)}};import{randomBytes as Cz}from"node:crypto";import{createServer as Ez}from"node:http";var Rz="MYREL_GIT_CREDENTIALS",Mz=40,La=class{lent=new Map;keyOf=new Map;port=null;server=null;async lend(t,r){let o=Cz(32).toString("hex");this.keyOf.set(t,o),this.lent.set(o,{token:r.token,expiresAt:Date.parse(r.expiresAt)});try{return Lz(`http://127.0.0.1:${await this.listen()}/${o}`,r.repos)}catch(n){throw this.end(t),n}}renew(t,r){let o=this.keyOf.get(t);o&&this.lent.set(o,{token:r.token,expiresAt:Date.parse(r.expiresAt)})}end(t){let r=this.keyOf.get(t);r&&(this.keyOf.delete(t),this.lent.delete(r),this.lent.size===0&&this.server&&(this.server.close(),this.server=null,this.port=null))}listen(){return this.port??=new Promise((t,r)=>{let o=Ez((n,i)=>{let a=n.method==="GET"?this.lent.get((n.url??"").slice(1)):void 0;if(!a||a.expiresAt<=Date.now()){i.writeHead(404).end();return}i.writeHead(200,{"content-type":"text/plain","cache-control":"no-store"}),i.end(`username=x-access-token
|
|
83
83
|
password=${a.token}
|
|
84
|
-
`)});o.once("error",n=>{this.server=null,this.port=null,r(n)}),this.server=o,o.listen(0,"127.0.0.1",()=>{o.unref(),t(o.address().port)})}),this.port}};function Lz(e,t,r=process.env.GIT_CONFIG_PARAMETERS,o=ti()){let n=`!${[o.command,...o.args].map(Fz).join(" ")} git-credential`,i=[],a=[...new Set(t.slice(0,Mz).flatMap(u=>[u,u.toLowerCase()]))];for(let u of a){for(let l of[`https://github.com/${u}`,`https://github.com/${u}.git`])i.push([`credential.${l}.helper`,""],[`credential.${l}.helper`,n]);i.push([`url.https://github.com/${u}.git.insteadOf`,`git@github.com:${u}.git`],[`url.https://github.com/${u}.git.insteadOf`,`ssh://git@github.com/${u}.git`])}let s=i.map(([u,l])=>Zz(`${u}=${l}`)).join(" ");return{[Rz]:e,GIT_CONFIG_PARAMETERS:r?`${r} ${s}`:s}}var Zz=e=>`'${e.replaceAll("'","'\\''")}'`;function Fz(e){return`"${(process.platform==="win32"?e.replaceAll("\\","/"):e).replace(/["\\$`]/g,"\\$&")}"`}import{chmod as Vz,mkdir as Hy,writeFile as Xy}from"node:fs/promises";import{dirname as Kz,join as ai,resolve as Jz,sep as Bz}from"node:path";var Wz="myrel",Gz=/^[a-z0-9]+(-[a-z0-9]+)*$/;async function Yy(e,t,r,o=fetch){let n;try{let u=await o(e,{headers:{Authorization:`Bearer ${t}`}});if(!u.ok)return null;n=await u.json()}catch{return null}let i=ai(r,"plugin"),a=ai(i,"skills"),s=0;for(let u of n.skills??[]){if(!Gz.test(u.name))continue;let l=ai(a,u.name);for(let d of u.files??[]){let p=Jz(l,d.path);p.startsWith(l+Bz)&&(await Hy(Kz(p),{recursive:!0}),await Xy(p,Buffer.from(d.content,"base64")),(/\.(sh|py)$/.test(d.path)||d.path.startsWith("scripts/"))&&await Vz(p,493).catch(()=>{}))}s++}return s?(await Hy(ai(i,".claude-plugin"),{recursive:!0}),await Xy(ai(i,".claude-plugin","plugin.json"),JSON.stringify({name:Wz,description:"Skills added in Myrel for this run.",version:"1.0.0"})),{plugin:i,skills:a,count:s}):null}import{chmod as qz,mkdir as Hz,writeFile as nf}from"node:fs/promises";import{delimiter as
|
|
84
|
+
`)});o.once("error",n=>{this.server=null,this.port=null,r(n)}),this.server=o,o.listen(0,"127.0.0.1",()=>{o.unref(),t(o.address().port)})}),this.port}};function Lz(e,t,r=process.env.GIT_CONFIG_PARAMETERS,o=ti()){let n=`!${[o.command,...o.args].map(Fz).join(" ")} git-credential`,i=[],a=[...new Set(t.slice(0,Mz).flatMap(u=>[u,u.toLowerCase()]))];for(let u of a){for(let l of[`https://github.com/${u}`,`https://github.com/${u}.git`])i.push([`credential.${l}.helper`,""],[`credential.${l}.helper`,n]);i.push([`url.https://github.com/${u}.git.insteadOf`,`git@github.com:${u}.git`],[`url.https://github.com/${u}.git.insteadOf`,`ssh://git@github.com/${u}.git`])}let s=i.map(([u,l])=>Zz(`${u}=${l}`)).join(" ");return{[Rz]:e,GIT_CONFIG_PARAMETERS:r?`${r} ${s}`:s}}var Zz=e=>`'${e.replaceAll("'","'\\''")}'`;function Fz(e){return`"${(process.platform==="win32"?e.replaceAll("\\","/"):e).replace(/["\\$`]/g,"\\$&")}"`}import{chmod as Vz,mkdir as Hy,writeFile as Xy}from"node:fs/promises";import{dirname as Kz,join as ai,resolve as Jz,sep as Bz}from"node:path";var Wz="myrel",Gz=/^[a-z0-9]+(-[a-z0-9]+)*$/;async function Yy(e,t,r,o=fetch){let n;try{let u=await o(e,{headers:{Authorization:`Bearer ${t}`}});if(!u.ok)return null;n=await u.json()}catch{return null}let i=ai(r,"plugin"),a=ai(i,"skills"),s=0;for(let u of n.skills??[]){if(!Gz.test(u.name))continue;let l=ai(a,u.name);for(let d of u.files??[]){let p=Jz(l,d.path);p.startsWith(l+Bz)&&(await Hy(Kz(p),{recursive:!0}),await Xy(p,Buffer.from(d.content,"base64")),(/\.(sh|py)$/.test(d.path)||d.path.startsWith("scripts/"))&&await Vz(p,493).catch(()=>{}))}s++}return s?(await Hy(ai(i,".claude-plugin"),{recursive:!0}),await Xy(ai(i,".claude-plugin","plugin.json"),JSON.stringify({name:Wz,description:"Skills added in Myrel for this run.",version:"1.0.0"})),{plugin:i,skills:a,count:s}):null}import{chmod as qz,mkdir as Hz,writeFile as nf}from"node:fs/promises";import{delimiter as IU,join as Za}from"node:path";var Xz="MYREL_SSH_SHIM",Yz=["ssh","scp","sftp"],jU=960*1e3;async function Qy(e,t,r=process.platform){let o=Za(e,"ssh-bin");await Hz(o,{recursive:!0,mode:448});let n=ti();for(let s of Yz)if(r==="win32"){let u=[n.command,...n.args].map(l=>`"${l}"`).join(" ");await nf(Za(o,`${s}.cmd`),`@echo off\r
|
|
85
85
|
${u} ssh-shim ${s} %*\r
|
|
86
86
|
`,{mode:448})}else{let u=[n.command,...n.args].map(d=>`'${d.replaceAll("'","'\\''")}'`).join(" "),l=Za(o,s);await nf(l,`#!/bin/sh
|
|
87
87
|
exec ${u} ssh-shim ${s} "$@"
|
|
88
|
-
`,{mode:448}),await qz(l,448)}let i=Za(e,"ssh-shim.json");await nf(i,JSON.stringify(t),{mode:384});let a=Object.keys(process.env).find(s=>s.toUpperCase()==="PATH")??"PATH";return{[a]:[o,process.env[a]].filter(Boolean).join(r==="win32"?";":":"),[Xz]:i}}var
|
|
88
|
+
`,{mode:448}),await qz(l,448)}let i=Za(e,"ssh-shim.json");await nf(i,JSON.stringify(t),{mode:384});let a=Object.keys(process.env).find(s=>s.toUpperCase()==="PATH")??"PATH";return{[a]:[o,process.env[a]].filter(Boolean).join(r==="win32"?";":":"),[Xz]:i}}var AU=new Set("qTn46vxCa".split(""));import{execFile as Qz}from"node:child_process";import{createHash as e0}from"node:crypto";import{mkdir as t0,realpath as rf,stat as e$}from"node:fs/promises";import{basename as n0,join as Fa,relative as r0}from"node:path";import{promisify as i0}from"node:util";var o0=i0(Qz),a0=1440*60*1e3,t$=()=>Fa(ne(),"worktrees.json"),We=(e,t)=>o0("git",["-C",e,...t],{maxBuffer:4*1024*1024,env:kt()});async function si(){return await $e(t$())??[]}async function n$(e){await Le(t$(),e)}function s0(e){return`myrel/thr-${e.slice(-10).toLowerCase()}`}async function r$(e,t){let r=await We(e,["rev-parse","--show-toplevel"]).then(a=>rf(a.stdout.trim())).catch(()=>null);if(!r||!await We(r,["rev-parse","--verify","--quiet","HEAD"]).catch(()=>null))return null;let o=await si(),n=o.find(a=>a.repo===r&&a.threadId===t),i=!1;if(!n||!await e$(n.path).catch(()=>null)){let a=e0("sha256").update(r).digest("hex").slice(0,8),s=Fa(ne(),"worktrees",`${n0(r)}-${a}`);await t0(s,{recursive:!0,mode:448});let u=Fa(await rf(s),t.slice(-10).toLowerCase()),l=s0(t);await We(r,["worktree","prune"]).catch(()=>{});let d=await We(r,["rev-parse","--verify","--quiet",`refs/heads/${l}`]).catch(()=>null);await We(r,d?["worktree","add",u,l]:["worktree","add","-b",l,u,"HEAD"]),n={threadId:t,repo:r,path:u,branch:l,lastUsed:Date.now()},i=!0}return n.lastUsed=Date.now(),await n$([...o.filter(a=>!(a.repo===r&&a.threadId===t)),n]),{cwd:Fa(n.path,r0(r,await rf(e))),worktree:n,created:i}}async function i$(e){if(!await e$(e.path).catch(()=>null))return{missing:!0,dirty:!1,merged:!0};let t=await We(e.path,["status","--porcelain"]).catch(()=>null),r=await We(e.repo,["merge-base","--is-ancestor",e.branch,"HEAD"]).then(()=>!0).catch(()=>!1);return{missing:!1,dirty:t===null||t.stdout.trim()!=="",merged:r}}async function c0(e,{force:t=!1}={}){let r=await i$(e);if(r.dirty&&!t)throw new Error(`${e.path} has uncommitted changes. Commit them, or remove it with --force.`);r.missing||await We(e.repo,["worktree","remove",...t?["--force"]:[],e.path]),await We(e.repo,["worktree","prune"]).catch(()=>{}),r.merged&&await We(e.repo,["branch","-d",e.branch]).catch(()=>{}),await n$((await si()).filter(o=>o.path!==e.path))}async function o$(e=()=>!1,t=Date.now()){let r=[];for(let o of await si()){if(e(o)||t-o.lastUsed<a0)continue;let n=await i$(o).catch(()=>null);!n||n.dirty||!n.merged||await c0(o).then(()=>r.push(o)).catch(()=>{})}return r}var af=new Set(["claude","codex","antigravity","opencode","hermes","cursor","muse","kimi"]),l$=9e4,d0=1e3,Va=class{constructor(t){this.opts=t}opts;running=new Map;turns=new Map;worktrees=new Map;cancelled=new Set;interrupted=new Set;git=new La;send=()=>{};setSender(t){this.send=t}runningIds(){return[...this.running.keys()]}inUse(t){return[...this.worktrees.values()].includes(t.path)}async start(t){let r=S=>this.send({type:"task.done",taskId:t.taskId,ok:!1,result:S}),o=this.opts.config(),n=await Ka(o,t.folder);if(!n)return r(`The folder ${t.folder} is not shared on this computer. Run \`myrel-runner share\` in it.`);let i=null;if(o.worktrees!==!1&&o.access!=="read")try{i=await r$(n,t.threadId)}catch(S){return r(`Could not make a git worktree for this thread in ${n}: ${d$(S)}
|
|
89
89
|
To run tasks in the folder itself instead, run \`myrel-runner worktrees off\`.`)}let a=i?.cwd??n,s=this.opts.log??(()=>{}),u=a===n?[]:[n];for(let S of t.folders??[]){let I=await Ka(o,S);I?I!==a&&!u.includes(I)&&u.push(I):s(` skipping ${S}: not shared on this computer`)}let l=oi[t.cli],d=!!t.agent&&t.cli==="claude",p=af.has(t.cli)&&!i?.created?await this.opts.sessions.get(t.threadId,t.cli):void 0,m=p&&t.agent?.resume&&p.task===t.agent.resume.after?t.agent.resume.prompt:void 0;s(`\u25B6 ${l.id} in ${a}: ${t.prompt.split(`
|
|
90
90
|
`)[0].slice(0,80)}`);let f,v={args:[]},y=null,x;if(t.agent&&o.server){f=await a$(of(u$(),"myrel-agent-"));let S=o.server.replace(/\/$/,"");x=qy(`${S}${t.agent.mcpPath}`,t.agent.token);let I=(t.agent.connectors??[]).map(A=>A.transport==="http"?{transport:A.transport,name:A.name,url:`${S}${A.path}`}:A);y=t.agent.skills?await Yy(`${S}${t.agent.skills.path}`,t.agent.token,f):null,v=await l.agent({url:`${S}${t.agent.mcpPath}`,token:t.agent.token,dir:f,connectors:I,asks:d,access:o.access,dirs:u,...y&&{skills:{plugin:y.plugin,dir:y.skills}}})}let j=()=>f?c$(f,{recursive:!0,force:!0}).catch(()=>{}):Promise.resolve(),P=i?`
|
|
91
91
|
|
|
92
92
|
(myrel-runner: worked on branch ${i.worktree.branch} in ${i.cwd}, a git worktree of ${n}.)`:"";i&&this.worktrees.set(t.taskId,i.worktree.path),t.agent&&this.send({type:"task.folders",taskId:t.taskId,folders:[a,...u]});let T=t.github?{...v.env,...await this.git.lend(t.taskId,t.github)}:v.env;if(t.agent&&f&&o.server){let S=await Qy(f,{url:`${o.server.replace(/\/$/,"")}${t.agent.mcpPath}`,token:t.agent.token}).catch(I=>(s(` could not put Myrel's ssh on PATH: ${d$(I)}`),{}));T={...T,...S}}try{let S=l.appServer&&await Zy(l.bin)?{...l.appServer({access:o.access,dirs:u,asks:!!x}),ask:x}:void 0;S&&s(" as its app server");let I=!!l.streamInput&&await Fy(l.bin),A={cwd:a,adapter:l,agent:v,env:T,dirs:u,asks:d&&!!f,skills:y,where:P,cleanup:j,appServer:S,stream:I};await this.attempt(t,A,p?.id,m??t.prompt)&&(s(` could not resume the ${l.id} session; starting a new one`),await this.attempt(t,A,void 0,t.prompt))}finally{this.git.end(t.taskId)}}async steer(t,r){return await this.turns.get(t)?.steer(r)??!1}renewGithub(t,r){this.git.renew(t,r)}async attempt(t,r,o,n){let i=this.opts.config(),a=this.opts.log??(()=>{}),{cwd:s,adapter:u,agent:l,dirs:d,skills:p,where:m,cleanup:f}=r,v=p?`${n}
|
|
93
93
|
|
|
94
94
|
Skills folder for this run: ${p.skills}`:n,y=u.input?u.input(v,i.access):v,x=u.promptFile?await a$(of(u$(),"myrel-prompt-")):void 0,j=x?of(x,"prompt.md"):void 0;j&&await l0(j,y,{mode:384});let P=[...r.appServer?[]:My(u,t.model),...l.args],T=r.appServer?["app-server",...l.args]:u.args({access:i.access,resume:o,extra:P,dirs:d,asks:r.asks,promptFile:j,stream:r.stream}),S=(this.opts.spawn??u0)(u.bin,T,{cwd:s,env:kt(r.env),stdio:["pipe","pipe","pipe"],shell:process.platform==="win32"});if(x){let L=()=>{c$(x,{recursive:!0,force:!0}).catch(()=>{})};S.once("close",L),S.once("error",L)}this.running.set(t.taskId,S),this.opts.onChange?.(this.runningIds());let I={},A="",X="",Pe="",He=0,ut,Xe="",Yt,zt,Xn=L=>{!L||L===Yt||(Yt=L,this.opts.onLimits?.(t.cli,L))},Qt=()=>I.usage?{...I.usage,...I.model&&{model:I.model.slice(0,200)}}:void 0,di=()=>{for(let ie of I.agentNotes?.splice(0)??[])this.send({type:"task.progress",taskId:t.taskId,text:ie.text,agent:ie.agent,...ie.ms!==void 0&&{ms:ie.ms}});let L=Qt(),ee=L?JSON.stringify(L):"",de=!!I.progress&&I.progress!==ut;if(de||ee!==Xe){ut=I.progress,Xe=ee,He=Date.now();let ie=de&&I.progressAgent;this.send({type:"task.progress",taskId:t.taskId,text:de?I.progress:"",...L&&{usage:L},...ie&&{agent:ie}})}};if(S.stdout.setEncoding("utf8"),S.stdout.on("data",L=>{A.length<4*l$&&(A+=L),Pe+=L;let ee=Pe.split(`
|
|
95
|
-
`);Pe=ee.pop();for(let ie of ee)u.line(ie.trim(),I);Xn(I.limits),I.sessionId&&I.sessionId!==zt&&af.has(t.cli)&&(zt=I.sessionId,this.opts.sessions.set(t.threadId,t.cli,{id:I.sessionId,task:t.taskId}).catch(()=>{}));let de=Qt();(Date.now()-He>=d0||de&&JSON.stringify(de)!==Xe||I.agentNotes?.length)&&di()}),S.stderr.setEncoding("utf8"),S.stderr.on("data",L=>{X.length<2e4&&(X+=L)}),S.stdin.on("error",()=>{}),u.acp){let L={write:de=>{S.stdin.write(de)},end:()=>S.stdin.end()},ee={cwd:s,prompt:y,mcpServers:l.mcpServers??[],resume:o,dirs:d,...u.acp(i.access,Ua(t.model))};I.acp=new Ca(L,ee,I),I.acp.start()}else if(r.appServer){let L={write:de=>{S.stdin.write(de)},end:()=>S.stdin.end()},ee={cwd:s,prompt:y,resume:o,model:Ua(t.model),clientVersion:this.opts.version??"0",...r.appServer};I.appServer=new Ra(L,ee,I),this.turns.set(t.taskId,I.appServer),I.appServer.start()}else if(r.stream){let L={write:ee=>{S.stdin.write(ee)},end:()=>S.stdin.end()};I.claudeStream=new Ma(L,y),this.turns.set(t.taskId,I.claudeStream),I.claudeStream.start()}else S.stdin.end(j?"":y);let Yn=setTimeout(()=>S.kill("SIGTERM"),this.opts.timeoutMs??3600*1e3);return await new Promise(L=>{let ee=!1,de=(ie,w)=>{if(ee)return;if(ee=!0,clearTimeout(Yn),f(),this.running.delete(t.taskId),this.turns.delete(t.taskId),this.worktrees.delete(t.taskId),this.opts.onChange?.(this.runningIds()),this.interrupted.delete(t.taskId))return a(`\u25A0 ${u.id} task interrupted; it continues after the runner restarts`),L(!1);if(this.cancelled.delete(t.taskId))return a(`\u25A0 ${u.id} task stopped`),this.send({type:"task.done",taskId:t.taskId,ok:!1,cancelled:!0,result:"Stopped from Myrel."}),L(!1);a(`${ie?"\u2713":"\u2717"} ${u.id} task finished`);let U=Qt();this.send({type:"task.done",taskId:t.taskId,ok:ie,result:w.slice(0,l$-m.length)+m,...U&&{usage:U}}),L(!1)};S.on("error",ie=>{de(!1,ie.code==="ENOENT"?`${u.bin} is not installed on this computer, or not on PATH for myrel-runner.`:`Could not start ${u.bin}: ${ie.message}`)}),S.on("exit",()=>{(this.cancelled.has(t.taskId)||this.interrupted.has(t.taskId))&&de(!1,"")}),S.on("close",async(ie,w)=>{Pe.trim()&&u.line(Pe.trim(),I),u.end?.(A,I),Xn(I.limits??await u.limits?.(I).catch(()=>{}));let U=ie===0&&!I.failed;if(o&&!U&&!I.usage&&!I.progress&&!this.cancelled.has(t.taskId))return ee=!0,clearTimeout(Yn),this.running.delete(t.taskId),this.turns.delete(t.taskId),this.interrupted.has(t.taskId)?(this.interrupted.delete(t.taskId),this.worktrees.delete(t.taskId),this.opts.onChange?.(this.runningIds()),f(),L(!1)):L(!0);I.sessionId&&af.has(t.cli)&&await this.opts.sessions.set(t.threadId,t.cli,{id:I.sessionId,task:t.taskId}).catch(()=>{});let Z=I.result??(U?A.trim()
|
|
96
|
-
|
|
97
|
-
`
|
|
98
|
-
`,{mode:384})}import{spawn as
|
|
99
|
-
`,timeoutMs:15e3});if(o.code!==0||/error/i.test(o.stderr))throw new Error(`Keychain: ${o.stderr.trim()||`exit ${o.code}`}`)},async get(t){let r=await Ge("security",["find-generic-password","-a",t,"-s",qn,"-w"],{timeoutMs:15e3});return r.code===0?r.stdout.replace(/\n$/,""):null},async remove(t){await Ge("security",["delete-generic-password","-a",t,"-s",qn],{timeoutMs:15e3}).catch(()=>{})}}:e==="linux"?{async set(t,r){let o=await Ge("secret-tool",["store",`--label=Myrel SSH key ${t}`,"service",qn,"account",t],{input:r,timeoutMs:15e3});if(o.code!==0)throw new Error(`Secret Service: ${o.stderr.trim()||`exit ${o.code}`}`)},async get(t){let r=await Ge("secret-tool",["lookup","service",qn,"account",t],{timeoutMs:15e3});return r.code===0&&r.stdout?r.stdout.replace(/\n$/,""):null},async remove(t){await Ge("secret-tool",["clear","service",qn,"account",t],{timeoutMs:15e3}).catch(()=>{})}}:null}async function
|
|
100
|
-
`).pop()})`:""}.`);return o}var
|
|
101
|
-
`)){if(!o.trim()||o.startsWith("#"))continue;let[,n,i]=o.trim().split(/\s+/);if(!n||!i||!/^[A-Za-z0-9+/=]+$/.test(i))continue;let a=`${n} ${i}`;t.some(s=>s.key===a)||t.push({type:n,key:a,fingerprint:Ba(a)})}let r=o=>
|
|
95
|
+
`);Pe=ee.pop();for(let ie of ee)u.line(ie.trim(),I);Xn(I.limits),I.sessionId&&I.sessionId!==zt&&af.has(t.cli)&&(zt=I.sessionId,this.opts.sessions.set(t.threadId,t.cli,{id:I.sessionId,task:t.taskId}).catch(()=>{}));let de=Qt();(Date.now()-He>=d0||de&&JSON.stringify(de)!==Xe||I.agentNotes?.length)&&di()}),S.stderr.setEncoding("utf8"),S.stderr.on("data",L=>{X.length<2e4&&(X+=L)}),S.stdin.on("error",()=>{}),u.acp){let L={write:de=>{S.stdin.write(de)},end:()=>S.stdin.end()},ee={cwd:s,prompt:y,mcpServers:l.mcpServers??[],resume:o,dirs:d,...u.acp(i.access,Ua(t.model))};I.acp=new Ca(L,ee,I),I.acp.start()}else if(r.appServer){let L={write:de=>{S.stdin.write(de)},end:()=>S.stdin.end()},ee={cwd:s,prompt:y,resume:o,model:Ua(t.model),clientVersion:this.opts.version??"0",...r.appServer};I.appServer=new Ra(L,ee,I),this.turns.set(t.taskId,I.appServer),I.appServer.start()}else if(r.stream){let L={write:ee=>{S.stdin.write(ee)},end:()=>S.stdin.end()};I.claudeStream=new Ma(L,y),this.turns.set(t.taskId,I.claudeStream),I.claudeStream.start()}else S.stdin.end(j?"":y);let Yn=setTimeout(()=>S.kill("SIGTERM"),this.opts.timeoutMs??3600*1e3);return await new Promise(L=>{let ee=!1,de=(ie,w)=>{if(ee)return;if(ee=!0,clearTimeout(Yn),f(),this.running.delete(t.taskId),this.turns.delete(t.taskId),this.worktrees.delete(t.taskId),this.opts.onChange?.(this.runningIds()),this.interrupted.delete(t.taskId))return a(`\u25A0 ${u.id} task interrupted; it continues after the runner restarts`),L(!1);if(this.cancelled.delete(t.taskId))return a(`\u25A0 ${u.id} task stopped`),this.send({type:"task.done",taskId:t.taskId,ok:!1,cancelled:!0,result:"Stopped from Myrel."}),L(!1);a(`${ie?"\u2713":"\u2717"} ${u.id} task finished`);let U=Qt();this.send({type:"task.done",taskId:t.taskId,ok:ie,result:w.slice(0,l$-m.length)+m,...U&&{usage:U}}),L(!1)};S.on("error",ie=>{de(!1,ie.code==="ENOENT"?`${u.bin} is not installed on this computer, or not on PATH for myrel-runner.`:`Could not start ${u.bin}: ${ie.message}`)}),S.on("exit",()=>{(this.cancelled.has(t.taskId)||this.interrupted.has(t.taskId))&&de(!1,"")}),S.on("close",async(ie,w)=>{Pe.trim()&&u.line(Pe.trim(),I),u.end?.(A,I),Xn(I.limits??await u.limits?.(I).catch(()=>{}));let U=ie===0&&!I.failed;if(o&&!U&&!I.usage&&!I.progress&&!this.cancelled.has(t.taskId))return ee=!0,clearTimeout(Yn),this.running.delete(t.taskId),this.turns.delete(t.taskId),this.interrupted.has(t.taskId)?(this.interrupted.delete(t.taskId),this.worktrees.delete(t.taskId),this.opts.onChange?.(this.runningIds()),f(),L(!1)):L(!0);I.sessionId&&af.has(t.cli)&&await this.opts.sessions.set(t.threadId,t.cli,{id:I.sessionId,task:t.taskId}).catch(()=>{});let Z=I.result??(U?A.trim():p0(u.bin,ie,w,I.error??(X.trim()||A.trim())));de(U,Z||"(no output)")})})}cancel(t){let r=this.running.get(t);if(!r)return;this.cancelled.add(t);let o=this.turns.get(t)?.interrupt()?5e3:0,n=()=>{r.exitCode===null&&(r.kill("SIGTERM"),setTimeout(()=>r.exitCode===null&&r.kill("SIGKILL"),5e3).unref())};o?setTimeout(n,o).unref():n()}stopAll(){let t=this.runningIds();for(let[r,o]of this.running)this.interrupted.add(r),o.kill("SIGTERM");return t}};async function Ka(e,t){let r=await s$(t).catch(()=>null);if(!r)return null;for(let o of e.folders)if(await s$(o.path).catch(()=>null)===r)return r;return null}var d$=e=>(e.stderr||e.message||String(e)).trim().split(`
|
|
96
|
+
`).at(-1);function p0(e,t,r,o){return r==="SIGKILL"?`${e} was killed (SIGKILL), most likely because this computer ran out of memory. Stop programs it does not need (dev servers left running, say) or add swap, then send the message again.`:`${e} exited with ${r??`code ${t}`}.
|
|
97
|
+
${o}`}async function m$(e,t){let r=await $0(e,t.folders,t.threadId);if(!r.length)throw new Error("None of this project's folders is shared on this computer.");let o=b0(t.path),n=g0(o)?[o]:r.map(i=>y0(i,o));for(let i of n){let a=await f$(i).catch(()=>null);if(!a||!r.some(p=>g$(a,p)))continue;let s=await m0(a);if(!s.isFile())continue;let u=Math.min(s.size,Vp),l=Buffer.alloc(u),d=await f0(a,"r");try{await d.read(l,0,u,0)}finally{await d.close()}return{path:a,size:s.size,data:l.toString("base64"),truncated:s.size>u}}throw new Error(`${t.path} is not a file in this project's folders.`)}async function $0(e,t,r){let o=(await Promise.all(t.map(a=>Ka(e,a)))).filter(a=>a!==null),n=r?(await si()).filter(a=>a.threadId===r):[],i=[];for(let a of o)for(let s of n){if(!g$(a,s.repo))continue;let u=await f$(h0(s.path,v0(s.repo,a))).catch(()=>null);u&&i.push(u)}return[...i,...o]}function b0(e){let t=e.trim();t.startsWith("file://")&&(t=t.slice(7));try{t=decodeURIComponent(t)}catch{}return t.replace(/#L\d+(-L?\d+)?$/,"").replace(/(:\d+){1,2}$/,"")}function g$(e,t){return e===t||e.startsWith(t.endsWith(p$)?t:t+p$)}import{readFileSync as _0,rmSync as x0,writeFileSync as k0,mkdirSync as w0}from"node:fs";import{join as h$}from"node:path";var S0=3600*1e3,sf=()=>h$(ne(),"interrupted.json"),I0=()=>h$(ne(),"running.json");function v$(e,t=Date.now()){if(!e.length)return;let r=[...$$(t),...e.map(o=>({taskId:o,at:t}))];b$(sf(),r)}function y$(e=Date.now()){let t=[...new Set($$(e).map(r=>r.taskId))];return x0(sf(),{force:!0}),t}function $$(e){let t=z0(sf());return Array.isArray(t)?t.filter(r=>typeof r?.taskId=="string"&&e-r.at<S0):[]}function cf(e){try{b$(I0(),{pid:process.pid,running:e})}catch{}}function z0(e){try{return JSON.parse(_0(e,"utf8"))}catch{return}}function b$(e,t){w0(ne(),{recursive:!0,mode:448}),k0(e,`${JSON.stringify(t)}
|
|
98
|
+
`,{mode:384})}import{spawn as P0}from"node:child_process";import{createHash as j0,randomBytes as A0}from"node:crypto";import{access as df,chmod as O0,mkdir as Ja,readdir as T0,readFile as pf,rm as _$,writeFile as k$}from"node:fs/promises";import{homedir as w$}from"node:os";import{dirname as N0,join as ct,relative as D0,resolve as x$}from"node:path";var qt=()=>ct(ne(),"ssh"),ci=()=>ct(qt(),"keys.json"),uf=()=>ct(qt(),"known_hosts"),U0=()=>ct(qt(),"askpass.sh"),qn="myrel-runner-ssh",C0=3e4,ff=e=>ct(qt(),e.projectId,e.alias),Gt=e=>`${e.projectId}/${e.alias}`,S$=e=>`myrel.${e.projectId}.${e.alias}`;function Ba(e){let t=e.trim().split(/\s+/)[1]??"";return`SHA256:${j0("sha256").update(Buffer.from(t,"base64")).digest("base64").replace(/=+$/,"")}`}function Ge(e,t,r={}){let o=r.max??Kv;return new Promise((n,i)=>{let a=P0(e,t,{env:r.env??lf(),stdio:[r.input===void 0?"ignore":"pipe","pipe","pipe"],windowsHide:!0}),s="",u="",l=!1,d=!1,p=(f,v)=>f.length+v.length<=o?f+v:(l=!0,f+v.slice(0,Math.max(0,o-f.length)));a.stdout.setEncoding("utf8").on("data",f=>s=p(s,f)),a.stderr.setEncoding("utf8").on("data",f=>u=p(u,f));let m=r.timeoutMs?setTimeout(()=>{d=!0,a.kill("SIGKILL")},r.timeoutMs):void 0;a.once("error",f=>{clearTimeout(m),i(f)}),a.once("close",f=>{clearTimeout(m),n({code:f,stdout:s,stderr:u,truncated:l,timedOut:d})}),r.input!==void 0&&a.stdin.end(r.input)})}function lf(e={}){let t={...process.env,...e};for(let r of["SSH_AUTH_SOCK","SSH_AGENT_PID","SSH_ASKPASS","SSH_ASKPASS_REQUIRE","MYREL_RUNNER_TOKEN"])r in e||delete t[r];return t}function mf(e=process.platform){return e==="darwin"?{async set(t,r){let o=await Ge("security",["-i"],{input:`add-generic-password -U -a "${t}" -s "${qn}" -w "${r}"
|
|
99
|
+
`,timeoutMs:15e3});if(o.code!==0||/error/i.test(o.stderr))throw new Error(`Keychain: ${o.stderr.trim()||`exit ${o.code}`}`)},async get(t){let r=await Ge("security",["find-generic-password","-a",t,"-s",qn,"-w"],{timeoutMs:15e3});return r.code===0?r.stdout.replace(/\n$/,""):null},async remove(t){await Ge("security",["delete-generic-password","-a",t,"-s",qn],{timeoutMs:15e3}).catch(()=>{})}}:e==="linux"?{async set(t,r){let o=await Ge("secret-tool",["store",`--label=Myrel SSH key ${t}`,"service",qn,"account",t],{input:r,timeoutMs:15e3});if(o.code!==0)throw new Error(`Secret Service: ${o.stderr.trim()||`exit ${o.code}`}`)},async get(t){let r=await Ge("secret-tool",["lookup","service",qn,"account",t],{timeoutMs:15e3});return r.code===0&&r.stdout?r.stdout.replace(/\n$/,""):null},async remove(t){await Ge("secret-tool",["clear","service",qn,"account",t],{timeoutMs:15e3}).catch(()=>{})}}:null}async function E0(e,t,r){if(!e)return!1;try{return await e.set(t,r),await e.get(t)===r}catch{return!1}}async function I$(e,t,r,o=mf()){if(await Ja(qt(),{recursive:!0,mode:448}),await gf(e,o),r){let l=await R0(r),d=await Ge("ssh-keygen",["-y","-P","","-f",l],{timeoutMs:15e3});if(d.code!==0)throw new Error(/passphrase|incorrect/i.test(d.stderr)?"This key has a passphrase, so Myrel cannot use it on its own. Let Myrel make a new key instead.":`Could not read ${l}: ${d.stderr.trim()||`exit ${d.code}`}`);let p=await $e(ci())??{};p[Gt(e)]=l,await Le(ci(),p);let m=d.stdout.trim();return{publicKey:m,fingerprint:Ba(m),protected:!1}}let n=ff(e);await Ja(N0(n),{recursive:!0,mode:448});let i=A0(24).toString("base64url"),a=await E0(o,Gt(e),i),s=await Ge("ssh-keygen",["-q","-t","ed25519","-N",a?i:"","-C",t,"-f",n],{timeoutMs:3e4});if(s.code!==0)throw new Error(`ssh-keygen failed: ${s.stderr.trim()||`exit ${s.code}`}. Is OpenSSH installed on this computer?`);await O0(n,384).catch(()=>{});let u=(await pf(`${n}.pub`,"utf8")).trim();return{publicKey:u,fingerprint:Ba(u),protected:a}}async function R0(e,t=w$()){let r=ct(t,".ssh"),o=x$(r,e),n=D0(r,o);if(!n||n.startsWith("..")||x$(r,n)!==o)throw new Error("Only keys in ~/.ssh can be used.");return await df(o),o}async function z$(e=w$()){let t=ct(e,".ssh"),r=await T0(t).catch(()=>[]),o=[];for(let n of r.filter(i=>i.endsWith(".pub")).sort()){let i=ct(t,n.slice(0,-4));if(!await df(i).then(()=>!0,()=>!1))continue;let a=(await pf(ct(t,n),"utf8").catch(()=>"")).trim(),[s,u,...l]=a.split(/\s+/);!s||!u||o.push({path:i,name:n.slice(0,-4),type:s,fingerprint:Ba(a),comment:l.join(" ").slice(0,500)})}return o.slice(0,100)}async function gf(e,t=mf()){let r=ff(e);await _$(r,{force:!0}),await _$(`${r}.pub`,{force:!0}),await t?.remove(Gt(e));let o=await $e(ci());o&&Gt(e)in o&&(delete o[Gt(e)],await Le(ci(),o)),await j$(e,null)}async function M0(e,t){let r=(await $e(ci()))?.[Gt(e)];if(r)return{path:r,passphrase:null};let o=ff(e);return await df(o).then(()=>!0,()=>!1)?{path:o,passphrase:await t?.get(Gt(e)).catch(()=>null)??null}:null}async function P$(e,t){let r=await Ge("ssh-keyscan",["-T","10","-p",String(t),"-t","ed25519,ecdsa,rsa","--",e],{timeoutMs:3e4}),o=Z0(r.stdout);if(!o.length)throw new Error(`${e}:${t} did not answer with a server key${r.stderr.trim()?` (${r.stderr.trim().split(`
|
|
100
|
+
`).pop()})`:""}.`);return o}var L0=["ssh-ed25519","ecdsa-sha2-nistp256","ecdsa-sha2-nistp384","ecdsa-sha2-nistp521","rsa-sha2-512","ssh-rsa"];function Z0(e){let t=[];for(let o of e.split(`
|
|
101
|
+
`)){if(!o.trim()||o.startsWith("#"))continue;let[,n,i]=o.trim().split(/\s+/);if(!n||!i||!/^[A-Za-z0-9+/=]+$/.test(i))continue;let a=`${n} ${i}`;t.some(s=>s.key===a)||t.push({type:n,key:a,fingerprint:Ba(a)})}let r=o=>L0.indexOf(o)+1||99;return t.sort((o,n)=>r(o.type)-r(n.type)).slice(0,10)}async function j$(e,t,r=!0){let o=S$(e),n=(await pf(uf(),"utf8").catch(()=>"")).split(`
|
|
102
102
|
`).filter(Boolean),i=n.filter(u=>u.startsWith(`${o} `)),a=t?`${o} ${t.trim().split(/\s+/).slice(0,2).join(" ")}`:null;if(!r&&i.length){if(a&&i.includes(a))return;throw new Wa}let s=[...n.filter(u=>!u.startsWith(`${o} `)),...a?[a]:[]];!a&&!i.length||(await Ja(qt(),{recursive:!0,mode:448}),await k$(uf(),s.length?`${s.join(`
|
|
103
103
|
`)}
|
|
104
|
-
`:"",{mode:384}))}var Wa=class extends Error{constructor(){super("The server's key is not the one confirmed in Myrel.")}};function
|
|
104
|
+
`:"",{mode:384}))}var Wa=class extends Error{constructor(){super("The server's key is not the one confirmed in Myrel.")}};function F0(e,t,r){let o=n=>["-o",n];return["-F","none","-T","-n",...o(`BatchMode=${r.passphrase?"no":"yes"}`),...o("IdentitiesOnly=yes"),...o("IdentityAgent=none"),...o("PasswordAuthentication=no"),...o("KbdInteractiveAuthentication=no"),...o("StrictHostKeyChecking=yes"),...o(`UserKnownHostsFile=${uf()}`),...o(`GlobalKnownHostsFile=${process.platform==="win32"?"NUL":"/dev/null"}`),...o(`HostKeyAlias=${S$(e)}`),...o("UpdateHostKeys=no"),...o("ForwardAgent=no"),...o("ForwardX11=no"),...o("ClearAllForwardings=yes"),...o("PermitLocalCommand=no"),...o(`ConnectTimeout=${r.timeoutSec}`),"-i",t,"-p",String(e.port),"-l",e.user,"--",e.host]}async function hf(e,t,r={}){let o=Date.now(),n=(p,m)=>({exitCode:null,stdout:"",stderr:m,truncated:!1,ms:Date.now()-o,error:p}),i=r.keychain===void 0?mf():r.keychain,a=await M0(e,i);if(!a)return n("nokey","This computer has no key for this server. Set it up again in the project's SSH settings.");try{await j$(e,e.hostKey,!!r.trust)}catch(p){if(p instanceof Wa)return n("hostkey",p.message);throw p}let s=r.timeoutMs??Vv,u=a.passphrase?lf({SSH_ASKPASS:await K0(),SSH_ASKPASS_REQUIRE:"force",DISPLAY:process.env.DISPLAY||":0",MYREL_SSH_PASSPHRASE:a.passphrase}):lf(),l=await Ge("ssh",[...F0(e,a.path,{passphrase:!!a.passphrase,timeoutSec:15}),t],{env:u,timeoutMs:s}),d=Date.now()-o;return l.timedOut?{exitCode:null,stdout:l.stdout,stderr:l.stderr,truncated:l.truncated,ms:d,error:"timeout"}:{exitCode:l.code,stdout:l.stdout,stderr:l.stderr,truncated:l.truncated,ms:d,...l.code===255&&{error:V0(l.stderr)}}}var A$=(e,t)=>hf(e,"true",{trust:!0,keychain:t,timeoutMs:C0});function V0(e){return/REMOTE HOST IDENTIFICATION HAS CHANGED|Host key verification failed|No .* host key is known/i.test(e)?"hostkey":/Permission denied|Too many authentication failures|no mutual signature/i.test(e)?"auth":/Connection (refused|timed out|closed)|Could not resolve|No route to host|Network is unreachable|Operation timed out/i.test(e)?"connect":"other"}async function K0(){let e=U0();return await Ja(qt(),{recursive:!0,mode:448}),await k$(e,`#!/bin/sh
|
|
105
105
|
printf "%s\\n" "$MYREL_SSH_PASSPHRASE"
|
|
106
|
-
`,{mode:448}),e}import{execFile as
|
|
107
|
-
`).filter(Boolean).at(-1)}). Use \`myrel-runner start\` instead.`)}}else await Ga(i.file,
|
|
106
|
+
`,{mode:448}),e}import{execFile as oP}from"node:child_process";import{createHash as aP}from"node:crypto";import{copyFile as Z$,rename as sP,rm as F$,stat as V$,writeFile as cP}from"node:fs/promises";import{join as xf,resolve as uP}from"node:path";import{promisify as lP}from"node:util";import{gunzipSync as dP}from"node:zlib";import{execFile as J0,spawn as N$}from"node:child_process";import{copyFile as B0,mkdir as vf,readFile as W0,rm as D$,stat as G0,writeFile as Ga}from"node:fs/promises";import{homedir as Hn,platform as U$}from"node:os";import{delimiter as O$,join as qe}from"node:path";import{promisify as q0}from"node:util";var Ne=q0(J0),Ht="io.fibteq.myrel-runner",Xt="myrel-runner.service";async function kC(e){let t=qa(),r=li();await vf(qe(ne(),"bin"),{recursive:!0,mode:448}),e!==r&&await B0(e,r);let o=[process.execPath,r,"start"],n=X0(),i=await Ha(t);if(t==="launchd")await vf(qe(Hn(),"Library","LaunchAgents"),{recursive:!0}),await Ga(i.file,Y0(o,n,i.log)),await H0(i.file);else if(t==="systemd"){await vf(qe(Hn(),".config","systemd","user"),{recursive:!0}),await Ga(i.file,Q0(o,n));try{await Ne("systemctl",["--user","daemon-reload"]),await Ne("systemctl",["--user","enable",Xt]),await Ne("systemctl",["--user","restart",Xt])}catch(a){throw await D$(i.file,{force:!0}),new Error(`Could not register with systemd (${a.message.split(`
|
|
107
|
+
`).filter(Boolean).at(-1)}). Use \`myrel-runner start\` instead.`)}}else await Ga(i.file,tP(o,i.log)),N$("wscript.exe",[i.file],{detached:!0,stdio:"ignore"}).unref();return E$()}var li=()=>qe(ne(),"bin","myrel-runner.mjs");async function C$(){if(qa()!=="startup")return;let e=await Ha("startup");e.installed&&N$("wscript.exe",[e.file],{detached:!0,stdio:"ignore"}).unref()}async function H0(e){let t=`gui/${process.getuid?.()}`,r=()=>Ne("launchctl",["print",`${t}/${Ht}`]).then(()=>!0,()=>!1);await Ne("launchctl",["bootout",`${t}/${Ht}`]).catch(()=>{});for(let o=0;o<50&&await r();o++)await yf(100);for(let o=1;;o++)try{await Ne("launchctl",["bootstrap",t,e]);break}catch(n){if(o>=5)throw n;await yf(500*o)}for(let o=0;o<30;o++){if((await Ne("launchctl",["print",`${t}/${Ht}`]).catch(()=>null))?.stdout.includes("state = running"))return;await yf(100)}}var yf=e=>new Promise(t=>setTimeout(t,e));async function wC(){let e=qa(),t=await Ha(e);return e==="launchd"?await Ne("launchctl",["bootout",`gui/${process.getuid?.()}/${Ht}`]).catch(()=>{}):e==="systemd"&&await Ne("systemctl",["--user","disable","--now",Xt]).catch(()=>{}),await D$(t.file,{force:!0}),e==="systemd"&&await Ne("systemctl",["--user","daemon-reload"]).catch(()=>{}),E$()}async function E$(){let e=await Ha(qa());if(!e.installed)return{...e,running:!1};if(e.manager==="launchd"){let t=await Ne("launchctl",["print",`gui/${process.getuid?.()}/${Ht}`]).catch(()=>null);return{...e,running:!!t?.stdout.includes("state = running")}}if(e.manager==="systemd"){let t=await Ne("systemctl",["--user","is-active",Xt]).catch(()=>null);return{...e,running:t?.stdout.trim()==="active"}}return{...e,running:null}}function qa(){let e=U$();if(e==="darwin")return"launchd";if(e==="linux")return"systemd";if(e==="win32")return"startup";throw new Error(`Running in the background is not supported on ${e} yet. Use \`myrel-runner start\`.`)}async function Ha(e){let t=e==="launchd"?qe(Hn(),"Library","LaunchAgents",`${Ht}.plist`):e==="systemd"?qe(Hn(),".config","systemd","user",Xt):qe(process.env.APPDATA??qe(Hn(),"AppData","Roaming"),"Microsoft","Windows","Start Menu","Programs","Startup","myrel-runner.vbs"),r=e==="systemd"?`journalctl --user -u ${Xt}`:qe(ne(),"runner.log"),o=!!await G0(t).catch(()=>null);return{manager:e,file:t,installed:o,log:r}}function X0(){let t={PATH:(process.env.PATH??"").split(O$).filter(r=>r&&!/[\\/]_npx[\\/]/.test(r)).join(O$)};return process.env.MYREL_RUNNER_HOME&&(t.MYREL_RUNNER_HOME=process.env.MYREL_RUNNER_HOME),t}var ui=e=>e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""");function Y0(e,t,r){return`<?xml version="1.0" encoding="UTF-8"?>
|
|
108
108
|
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
109
109
|
<plist version="1.0">
|
|
110
110
|
<dict>
|
|
@@ -127,7 +127,7 @@ ${Object.entries(t).map(([o,n])=>` <key>${ui(o)}</key><string>${ui(n)}</strin
|
|
|
127
127
|
<key>StandardErrorPath</key><string>${ui(r)}</string>
|
|
128
128
|
</dict>
|
|
129
129
|
</plist>
|
|
130
|
-
`}var T$=e=>`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/%/g,"%%")}"`;function
|
|
130
|
+
`}var T$=e=>`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/%/g,"%%")}"`;function Q0(e,t){return`[Unit]
|
|
131
131
|
Description=Myrel runner (connects this computer to Myrel)
|
|
132
132
|
After=network-online.target
|
|
133
133
|
|
|
@@ -141,9 +141,9 @@ ${R$}
|
|
|
141
141
|
|
|
142
142
|
[Install]
|
|
143
143
|
WantedBy=default.target
|
|
144
|
-
`}var R$="OOMPolicy=continue";function
|
|
145
|
-
${R$}`)}async function M$(){if(U$()!=="linux")return;let e=qe(Hn(),".config","systemd","user",Xt),t=
|
|
144
|
+
`}var R$="OOMPolicy=continue";function eP(e){return/^OOMPolicy=/m.test(e)||!/^RestartSec=.*$/m.test(e)?null:e.replace(/^RestartSec=.*$/m,t=>`${t}
|
|
145
|
+
${R$}`)}async function M$(){if(U$()!=="linux")return;let e=qe(Hn(),".config","systemd","user",Xt),t=eP(await W0(e,"utf8").catch(()=>""));t&&(await Ga(e,t),await Ne("systemctl",["--user","daemon-reload"]))}function tP(e,t){return`' Starts myrel-runner at login. Remove with: myrel-runner service uninstall\r
|
|
146
146
|
CreateObject("WScript.Shell").Run "${`cmd.exe /c "${e.map(o=>`"${o}"`).join(" ")} >> "${t}" 2>&1"`.replace(/"/g,'""')}", 0, False\r
|
|
147
|
-
`}import{spawn as
|
|
148
|
-
`)[0]}), so it was not installed.`)}await V$(r).catch(()=>null)&&await Z$(r,_f()),await
|
|
149
|
-
`)[0].slice(0,80)}`),S({type:"ssh.result",requestId:U,...await hf(w.target,w.command)});if(w.type==="ssh.forget")return await gf({projectId:w.projectId,alias:w.alias}),t(`Forgot the SSH key for ${w.alias} (from Myrel)`),S({type:"ssh.result",requestId:U,exitCode:0,stdout:"",stderr:"",truncated:!1,ms:0});if(w.type==="runner.update"){if(x!=="service")throw new Error(x==="app"?"This runner came with the Myrel desktop app; it updates with the app.":"This runner was started in a terminal, so it cannot restart itself. Start it again with `npx myrel-runner@latest start`.");return t(`Updating to myrel-runner ${w.version} (from Myrel)${w.now?"":" once the running tasks finish"}`),S({type:"update.accepted",requestId:U,update:j.request(w.version,w.now)})}if(o=await ni(),w.type==="settings.set")return K$(o,w.settings),await za(o),t(`Settings changed from Myrel: ${Object.entries(w.settings).map(([Z,pi])=>`${Z} ${pi}`).join(", ")}`),S({type:"settings",requestId:U,settings:kf(o)});if(w.type==="folder.share"){let Z=await Wy(w.path);yy(o,Z)&&t(`Shared ${Z} (from Myrel)`)}else $y(o,w.path)&&t(`Stopped sharing ${w.path} (from Myrel)`);await za(o),S({type:"folders",requestId:U,folders:o.folders})},ie=()=>{if(m)return;let w=`${o.server.replace(/^http/,"ws")}/api/runner/connect`;r({state:"connecting"});let U=new WebSocket(w,{headers:{authorization:`Bearer ${o.token}`}});p=U;let Z=!1;U.onopen=()=>{Z=!0,f=0,I(),A()},U.onmessage=je=>{let en=JSON.parse(String(je.data)),es=Xv.safeParse(en);if(!es.success){let tn=en;if(tn?.type==="task.start"&&typeof tn.taskId=="string"){let Pf=es.error.issues[0],jf=`${Pf?.path.join(".")||"frame"}: ${Pf?.message??"invalid"}`;t(`\u2717 could not read task ${tn.taskId} (${jf})`),S({type:"task.done",taskId:tn.taskId,ok:!1,result:`myrel-runner ${Qa} could not read this task (${jf}). Update myrel-runner.`})}return}let be=es.data;be.type==="welcome"&&(t(`\u25CF Connected to ${o.server} as "${be.name}"`),r({state:"online",name:be.name}),j.confirmed()),be.type==="task.start"&&(r({state:"task",taskId:be.taskId,event:"started"}),u.start(be)),be.type==="task.cancel"&&u.cancel(be.taskId),be.type==="task.github"&&u.renewGithub(be.taskId,be.github),"requestId"in be&&de(be).catch(tn=>S({type:"request.failed",requestId:be.requestId,message:
|
|
147
|
+
`}import{spawn as nP}from"node:child_process";var rP="@fibteq/myrel-runner",$f="@fibteq%2Fmyrel-runner",iP=/^\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?$/;async function L$(e="https://registry.npmjs.org"){try{let t=await fetch(`${e}/${$f}/latest`,{signal:AbortSignal.timeout(1e4)});if(!t.ok)return null;let{version:r}=await t.json();return typeof r=="string"&&iP.test(r)?r:null}catch{return null}}var bf=Qv;function PC(e,t){let r=process.platform==="win32"?"npx.cmd":"npx";return new Promise((o,n)=>{let i=nP(r,["--yes",`--package=${rP}@${e}`,"--","myrel-runner",...t],{stdio:"inherit",shell:process.platform==="win32",env:{...process.env,MYREL_RUNNER_UPDATING:e}});i.on("error",n),i.on("exit",a=>o(a??1))})}var pP=lP(oP);function kf(e){return{access:e.access,worktrees:e.worktrees!==!1,autoUpdate:e.autoUpdate===!0,remote:e.remoteSettings!==!1}}function K$(e,t){if(e.remoteSettings===!1)throw new Error("Changing settings from Myrel is turned off on this computer. Turn it on there with `myrel-runner settings remote on`.");t.access&&(e.access=t.access),t.worktrees!==void 0&&(e.worktrees=t.worktrees),t.autoUpdate!==void 0&&(e.autoUpdate=t.autoUpdate)}function J$(e=process.argv[1]){return process.versions.bun?"app":e&&uP(e)===li()?"service":"manual"}var _f=()=>xf(ne(),"bin","myrel-runner.prev.mjs"),wf=()=>xf(ne(),"update.json"),B$=()=>$e(wf()).catch(()=>{}),Xa=e=>Le(wf(),e),Sf=()=>F$(wf(),{force:!0}),W$=1440*60*1e3;async function G$(e,t="https://registry.npmjs.org"){let r=await fetch(`${t}/${$f}/${e}`,{signal:AbortSignal.timeout(3e4)});if(!r.ok)throw new Error(`npm does not have myrel-runner ${e} (${r.status}).`);let{dist:o}=await r.json(),n=o?.integrity?.match(/^sha512-([A-Za-z0-9+/=]+)$/)?.[1];if(!o?.tarball||!n)throw new Error("npm sent no download for this version.");let i=await fetch(o.tarball,{signal:AbortSignal.timeout(12e4)});if(!i.ok)throw new Error(`Could not download myrel-runner ${e} (${i.status}).`);let a=Buffer.from(await i.arrayBuffer());if(aP("sha512").update(a).digest("base64")!==n)throw new Error("The download does not match npm's checksum, so it was not installed.");let s=fP(dP(a),"package/dist/cli.js");if(!s)throw new Error("The download has no dist/cli.js.");return s}function fP(e,t){let r;for(let o=0;o+512<=e.length;){let n=e.subarray(o,o+512);if(n.every(p=>p===0))return null;let i=(p,m)=>n.toString("utf8",p,p+m).replace(/\0.*$/s,""),a=Number.parseInt(i(124,12).trim()||"0",8),s=i(156,1),u=e.subarray(o+512,o+512+a);if(o+=512+Math.ceil(a/512)*512,s==="x"){r=u.toString("utf8").match(/^\d+ path=(.*)$/m)?.[1];continue}let l=i(345,155),d=r??(l?`${l}/${i(0,100)}`:i(0,100));if(r=void 0,(s==="0"||s==="")&&d===t)return Buffer.from(u)}return null}async function q$(e,t){let r=li(),o=xf(ne(),"bin","myrel-runner.next.mjs");await cP(o,e,{mode:448});try{let{stdout:n}=await pP(process.execPath,[o,"--version"],{timeout:3e4});if(n.trim()!==t)throw new Error(`it says it is ${n.trim()||"nothing"}`)}catch(n){throw await F$(o,{force:!0}),new Error(`The new version does not start (${n.message.split(`
|
|
148
|
+
`)[0]}), so it was not installed.`)}await V$(r).catch(()=>null)&&await Z$(r,_f()),await sP(o,r)}async function H$(){return await V$(_f()).catch(()=>null)?(await Z$(_f(),li()),!0):!1}var mP=600*1e3,gP=360*60*1e3,X$=120*1e3,Ya=class{constructor(t){this.opts=t}opts;current=null;pending=null;busy=!1;hurry=!1;until=0;get now(){return(this.opts.now??Date.now)()}state(){return this.current??void 0}async init(){let t=await B$();if(!t)return!1;if(t.state==="restarting"&&t.version===this.opts.version)return this.pending=t,!0;if(t.state==="restarting")return await this.fail(t.version,"The new version did not start, so this one kept running.","failed",!1),!1;if((t.state==="failed"||t.state==="rolled-back")&&this.now-Date.parse(t.at)<W$){let{from:r,...o}=t;return this.current=o,!1}return await Sf(),!1}async confirmed(){this.pending&&(this.opts.log(`\u25CF Updated myrel-runner from ${this.pending.from} to ${this.opts.version}.`),this.pending=null,this.current=null,await Sf(),this.opts.report(null))}async rollback(t){let r=this.pending;if(r){if(this.pending=null,!await(this.opts.restore??H$)().catch(()=>!1)){this.opts.log(`myrel-runner ${this.opts.version} could not connect (${t}), and there is no previous version to go back to.`);return}this.opts.log(`myrel-runner ${this.opts.version} could not connect (${t}); going back to ${r.from}.`),await Xa({state:"rolled-back",version:this.opts.version,from:r.from,message:t.slice(0,500),at:new Date(this.now).toISOString()}),this.opts.restart()}}get confirming(){return this.pending!==null}request(t,r=!1,o=!1){if(!bf(t,this.opts.version))throw new Error(`myrel-runner ${this.opts.version} is already up to date.`);let n=this.now+(o?this.opts.autoWaitMs??gP:this.opts.waitMs??mP);return this.busy?(r&&(this.hurry=!0),this.until=Math.min(this.until,n),this.current):(this.busy=!0,this.hurry=r,this.until=n,this.set({state:"waiting",version:t,running:this.opts.running().length}),this.run(t).finally(()=>{this.busy=!1}),this.current)}async checkNewest(){if(this.busy||this.pending)return;let t=await(this.opts.latest??L$)();!t||!bf(t,this.opts.version)||this.current&&this.current.version===t&&this.current.state!=="waiting"||(this.opts.log(`Installing myrel-runner ${t} (auto-update is on).`),this.request(t,!1,!0))}async run(t){for(let o=this.opts.running();o.length&&!this.hurry&&this.now<this.until;o=this.opts.running())o.length!==this.current?.running&&this.set({state:"waiting",version:t,running:o.length}),await new Promise(n=>setTimeout(n,this.opts.pollMs??2e3));try{this.set({state:"downloading",version:t});let o=await(this.opts.download??G$)(t);await(this.opts.install??q$)(o,t)}catch(o){await this.fail(t,o.message);return}let r={state:"restarting",version:t,from:this.opts.version,at:new Date(this.now).toISOString()};await Xa(r),this.set({state:"restarting",version:t}),this.opts.log(`Restarting on myrel-runner ${t}\u2026`),this.opts.restart()}async fail(t,r,o="failed",n=!0){n&&this.opts.log(`Could not update to myrel-runner ${t}: ${r}`);let i=new Date(this.now).toISOString();await Xa({state:o,version:t,from:this.opts.version,message:r.slice(0,500),at:i}).catch(()=>{}),this.set({state:o,version:t,message:r.slice(0,500)})}set(t){this.current={...t,at:new Date(this.now).toISOString()},this.opts.report(this.current)}};var Qa="0.28.2",yP=360*60*1e3;async function i6(e){let t=e.server.replace(/\/+$/,""),r=await fetch(`${t}/api/runner/pair`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({code:e.code,name:e.name||If(),hostname:If(),platform:Q$()})}),o=await r.json().catch(()=>null);if(!r.ok)throw new Error(o?.message??`Pairing failed (${r.status})`);let n=Yv.parse(o),i=await ni();return Object.assign(i,{server:t,runnerId:n.runner.id,token:n.token}),await za(i),i}async function Y$(e){if(!e.server||!e.token)return"invalid";try{let t=await fetch(`${e.server}/api/runner/me`,{headers:{authorization:`Bearer ${e.token}`},signal:AbortSignal.timeout(1e4)});return t.ok?"ok":t.status===401?"invalid":"unknown"}catch{return"unknown"}}var $P="This computer is not paired with Myrel any more (it was removed, or paired again elsewhere). Get a new code in Myrel > Devices and run `myrel-runner pair <code> --server <url>`.",bP=900*1e3,o6=75,_P=300*1e3;function xP(e,t){return e.length===t.length&&e.every(r=>t.some(o=>o.id===r.id&&o.version===r.version))}async function a6(e={}){let t=e.log??(w=>console.log(w)),r=e.onStatus??(()=>{}),o=await ni();if(!o.server||!o.token)throw new Error("This computer is not paired yet. Run `myrel-runner pair <code> --server <url>` first.");let n=await Qp(),i=await wy(),a=(w,U)=>{let Z=i[w];!U||Z&&Z.at>=U.at||(i[w]=U,Sy(i).catch(()=>{}),JSON.stringify({...Z,at:""})!==JSON.stringify({...U,at:""})&&A())},s=()=>{n.some(w=>w.id==="codex")&&ja().then(w=>a("codex",w),()=>{})},u=new Va({config:()=>o,sessions:new Ia,log:t,onLimits:a,onChange:cf,version:Qa}),l=y$();l.length&&t(`${l.length} task(s) stopped when the runner restarted; Myrel continues them.`),cf([]);let d="stopped",p=null,m=!1,f=0,v,y=new Promise(w=>v=w),x=J$();x==="service"&&M$().catch(()=>{});let j=new Ya({version:Qa,running:()=>u.runningIds(),report:w=>S({type:"update.status",update:w}),log:t,restart:()=>{C$().catch(()=>{}).finally(()=>{d="restart",ee()})}}),P;await j.init()&&(P=setTimeout(()=>{Y$(o).then(w=>{w==="ok"&&j.confirming&&j.rollback("it did not connect within 2 minutes")})},X$),P.unref?.());let T=new Map,S=w=>{w.type==="task.done"&&(r({state:"task",taskId:w.taskId,event:"done",ok:w.ok}),T.set(w.taskId,{frame:w,at:Date.now()})),p?.readyState===WebSocket.OPEN&&p.send(JSON.stringify(w))},I=()=>{for(let[w,{frame:U,at:Z}]of T)Date.now()-Z>bP?T.delete(w):S(U)},A=()=>S({type:"hello",protocol:Wv,version:Qa,hostname:If(),platform:Q$(),folders:o.folders,clis:n.map(w=>i[w.id]?{...w,limits:i[w.id]}:w),features:["folders","cancel","agent","agent-clis","connectors","skills","project-folders","files","settings","models","git-token","steer","steer-claude","ssh",...x==="service"?["update"]:[]],settings:kf(o),updates:x,...j.state()&&{update:j.state()},running:u.runningIds(),interrupted:l});u.setSender(S);let X=async()=>{o=await ni().catch(()=>o),A()};hP(Jn(),{interval:2e3},X);let Pe=setInterval(()=>S({type:"ping"}),25e3),He=()=>{Promise.all(n.map(async w=>{let U=await oi[w.id].models?.().catch(()=>{}),Z=JSON.stringify(U)!==JSON.stringify(w.models);return U&&(w.models=U),Z&&!!U})).then(w=>w.some(Boolean)&&A())};He(),s();let ut=()=>{Qp().then(w=>{if(xP(n,w))return;let U=new Map(n.map(Z=>[Z.id,Z]));n.splice(0,n.length,...w.map(Z=>U.get(Z.id)?.version===Z.version?U.get(Z.id):Z)),t(`CLIs found: ${n.map(Z=>Z.id).join(", ")||"none"}`),A(),He(),s()},()=>{})},Xe=setInterval(s,600*1e3),Yt=setInterval(He,360*60*1e3),zt=setInterval(ut,_P);Xe.unref?.(),zt.unref?.();let Xn=()=>{o$(w=>u.inUse(w)).then(w=>w.forEach(U=>t(`Removed the finished worktree ${U.path} (${U.branch})`))).catch(()=>{})};Xn();let Qt=setInterval(Xn,360*60*1e3);Qt.unref?.();let di=()=>{x==="service"&&o.autoUpdate&&j.checkNewest().catch(()=>{})},Yn=setTimeout(di,600*1e3);Yn.unref?.();let L=setInterval(di,yP);L.unref?.();let ee=()=>{m=!0,clearInterval(Pe),clearInterval(Qt),clearInterval(Xe),clearInterval(Yt),clearInterval(zt),clearInterval(L),clearTimeout(Yn),clearTimeout(P),vP(Jn(),X),v$(u.stopAll()),p?.close(1e3),r({state:"stopped",reason:d}),v(d)},de=async w=>{let{requestId:U}=w;if(w.type==="dirs.list")return S({type:"dirs",requestId:U,...await By(w.path)});if(w.type==="task.steer")return S({type:"task.steered",requestId:U,taken:await u.steer(w.taskId,w.text)});if(w.type==="file.read")return S({type:"file",requestId:U,...await m$(o,w)});if(w.type==="ssh.keygen"){let Z=await I$({projectId:w.projectId,alias:w.alias},w.comment,w.existing);return t(`${w.existing?"Using":"Made"} an SSH key for ${w.alias} (${Z.fingerprint}, from Myrel)`),S({type:"ssh.key",requestId:U,...Z})}if(w.type==="ssh.keys")return S({type:"ssh.keylist",requestId:U,keys:await z$()});if(w.type==="ssh.hostkeys")return S({type:"ssh.hostkeylist",requestId:U,keys:await P$(w.host,w.port)});if(w.type==="ssh.test")return S({type:"ssh.result",requestId:U,...await A$(w.target)});if(w.type==="ssh.run")return t(`SSH ${w.target.alias}: ${w.command.split(`
|
|
149
|
+
`)[0].slice(0,80)}`),S({type:"ssh.result",requestId:U,...await hf(w.target,w.command)});if(w.type==="ssh.forget")return await gf({projectId:w.projectId,alias:w.alias}),t(`Forgot the SSH key for ${w.alias} (from Myrel)`),S({type:"ssh.result",requestId:U,exitCode:0,stdout:"",stderr:"",truncated:!1,ms:0});if(w.type==="runner.update"){if(x!=="service")throw new Error(x==="app"?"This runner came with the Myrel desktop app; it updates with the app.":"This runner was started in a terminal, so it cannot restart itself. Start it again with `npx myrel-runner@latest start`.");return t(`Updating to myrel-runner ${w.version} (from Myrel)${w.now?"":" once the running tasks finish"}`),S({type:"update.accepted",requestId:U,update:j.request(w.version,w.now)})}if(o=await ni(),w.type==="settings.set")return K$(o,w.settings),await za(o),t(`Settings changed from Myrel: ${Object.entries(w.settings).map(([Z,pi])=>`${Z} ${pi}`).join(", ")}`),S({type:"settings",requestId:U,settings:kf(o)});if(w.type==="folder.share"){let Z=await Wy(w.path);yy(o,Z)&&t(`Shared ${Z} (from Myrel)`)}else $y(o,w.path)&&t(`Stopped sharing ${w.path} (from Myrel)`);await za(o),S({type:"folders",requestId:U,folders:o.folders})},ie=()=>{if(m)return;let w=`${o.server.replace(/^http/,"ws")}/api/runner/connect`;r({state:"connecting"});let U=new WebSocket(w,{headers:{authorization:`Bearer ${o.token}`}});p=U;let Z=!1;U.onopen=()=>{Z=!0,f=0,I(),A()},U.onmessage=je=>{let en=JSON.parse(String(je.data)),es=Xv.safeParse(en);if(!es.success){let tn=en;if(tn?.type==="task.start"&&typeof tn.taskId=="string"){let Pf=es.error.issues[0],jf=`${Pf?.path.join(".")||"frame"}: ${Pf?.message??"invalid"}`;t(`\u2717 could not read task ${tn.taskId} (${jf})`),S({type:"task.done",taskId:tn.taskId,ok:!1,result:`myrel-runner ${Qa} could not read this task (${jf}). Update myrel-runner.`})}return}let be=es.data;be.type==="welcome"&&(t(`\u25CF Connected to ${o.server} as "${be.name}"`),r({state:"online",name:be.name}),j.confirmed()),be.type==="task.start"&&(r({state:"task",taskId:be.taskId,event:"started"}),u.start(be)),be.type==="task.cancel"&&u.cancel(be.taskId),be.type==="task.github"&&u.renewGithub(be.taskId,be.github),"requestId"in be&&de(be).catch(tn=>S({type:"request.failed",requestId:be.requestId,message:kP(tn)}))};let pi=!1,zf=async je=>{if(pi||p!==U||m)return;if(pi=!0,!Z&&await Y$(o)==="invalid")return t($P),e.onRevoked?.(),d="revoked",ee();if(je.code===4401)return t("This computer was removed from Myrel. Pair it again with `myrel-runner pair`."),e.onRevoked?.(),d="revoked",ee();if(je.code===4e3)return t("myrel-runner was started somewhere else with this computer's login, so this one stops."),d="replaced",ee();if(je.code===4400)return t(`The server refused this runner: ${je.reason}`),j.confirming&&(await j.rollback(`the server refused it: ${je.reason}`),m)?void 0:(d="refused",ee());let en=Math.min(3e4,1e3*2**f++);t(`\u25CB Disconnected${je.reason?` (${je.reason})`:""}. Reconnecting in ${Math.round(en/1e3)}s\u2026`),r({state:"offline",reason:je.reason||`code ${je.code}`,retryInMs:en}),setTimeout(ie,en)};U.onclose=je=>{zf(je)},U.onerror=()=>{Z||zf({code:1006,reason:""})}};return ie(),t(`Sharing ${o.folders.length} folder(s); CLIs found: ${n.map(w=>w.id).join(", ")||"none"}`),{stop:ee,done:y}}function kP(e){return(e instanceof Error?e.message:String(e)).slice(0,500)}export{oi as ADAPTERS,YI as APPROVE_TOOL,Te as MYREL_MCP_SERVER,rP as PACKAGE_NAME,$f as PACKAGE_PATH,o6 as RESTART_EXIT_CODE,Qa as RUNNER_VERSION,Ht as SERVICE_NAME,Ia as SessionStore,Va as TaskRunner,s0 as branchFor,Y$ as checkPairing,kt as childEnv,Jn as configPath,fz as cursorConfig,Qp as detectClis,p0 as exitMessage,Zy as hasAppServer,Fy as hasStreamInput,kC as installService,bf as isNewer,L$ as latestVersion,Y0 as launchdPlist,By as listDirs,si as listWorktrees,ni as loadConfig,bz as missingReason,My as modelFlags,cz as opencodeServerArgs,i6 as pair,HI as parseClaudeHelp,XI as parseCodexModels,$z as parseKimiModels,Hp as parseModelLines,vz as parseMuseCatalog,o$ as pruneWorktrees,$e as readJson,C$ as relaunchService,c0 as removeWorktree,PC as runVersion,ne as runnerHome,Ua as safeModel,Be as safeModelArg,xP as sameClis,za as saveConfig,li as serviceBin,E$ as serviceStatus,yy as shareFolder,Wy as shareableFolder,Ka as sharedFolder,a6 as startRunner,tP as startupScript,Q0 as systemdUnit,r$ as threadWorktree,wC as uninstallService,$y as unshareFolder,M$ as upgradeService,eP as upgradeSystemdUnit,i$ as worktreeState,Le as writeJson};
|