@fibteq/myrel-runner 0.31.0 → 0.32.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -59,33 +59,33 @@ ${u}`:u:"",d=Function,p=`return (input) => {
59
59
  ${u}
60
60
  }`,f;try{f=new d(...a,p)(...s)}catch(m){throw new L(`this schema (generated code failed to evaluate: ${m.message})`)}return t?.debug&&(f.code=l),f.definite=o.definite,f}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 gk(e,t){let r=e._zod.run({value:t,issues:[]},{});if(r&&typeof r.then=="function")return ve;let o=r;return o.issues.length===0?o.value:ve}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 L)||!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,hk(e,t,r,o)}}function hk(e,t,r,o){t.definite=!1;let n=N(t,r),i=N(t,gk),a=O(t);return e.write(`const ${a} = ${i}(${n}, ${o});`),e.write(`if (${a} === INVALID) return INVALID;`),a}var vk=new Set(["max_size","min_size","size_equals","max_length","min_length","length_equals"]);function yk(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&&!vk.has(s.check))throw new L('check with a custom "when" condition');switch(s.check){case"greater_than":bk(e,t,s,i);break;case"less_than":$k(e,t,s,i);break;case"multiple_of":_k(e,t,s,i);break;case"number_format":Vg(e,s,i);break;case"min_length":{let u=gt(s.minimum,"min_length"),l=Gu(e,t,i,`${i}.length >= ${u} && ${i}.length < ${s.minimum*2}`);e.write(`if (${l} < ${u}) return INVALID;`);break}case"max_length":{let u=gt(s.maximum,"max_length"),l=Gu(e,t,i,`${i}.length > ${u}`);e.write(`if (${l} > ${u}) return INVALID;`);break}case"length_equals":{let u=gt(s.length,"length_equals"),l=Gu(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 < ${gt(s.minimum,"min_size")}) return INVALID;`);break;case"max_size":e.write(`if (${i}.size > ${gt(s.maximum,"max_size")}) return INVALID;`);break;case"size_equals":e.write(`if (${i}.size !== ${gt(s.size,"size_equals")}) return INVALID;`);break;case"string_format":i=Kg(e,t,s,i);break;case"custom":i=zk(e,t,a,i);break;case"bigint_format":xk(e,s,i);break;case"mime_type":kk(e,t,s,i);break;case"property":Sk(e,t,s,i);break;case"properties":wk(e,t,s,i);break;case"overwrite":{let u=O(t);Ik(e,t,a,i,u),i=u;break}default:throw new L(`check type ${s.check}`)}}return i}function Gu(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 gt(e,t){if(typeof e!="number"||!Number.isFinite(e))throw new L(`${t} bound of type ${typeof e}`);return`${e}`}function Fg(e,t){if(typeof t=="bigint")return`${t}n`;if(typeof t=="number"){if(Number.isNaN(t))throw new L("comparison check with NaN bound");return`${t}`}if(t instanceof Date){if(Number.isNaN(t.getTime()))throw new L("comparison check with Invalid Date bound");return N(e,t)}throw new L(`comparison check bound of type ${typeof t}`)}function bk(e,t,r,o){let n=r.inclusive?"<":"<=";e.write(`if (${o} ${n} ${Fg(t,r.value)}) return INVALID;`)}function $k(e,t,r,o){let n=r.inclusive?">":">=";e.write(`if (${o} ${n} ${Fg(t,r.value)}) return INVALID;`)}function _k(e,t,r,o){if(typeof r.value=="bigint"){if(r.value===BigInt(0))throw new L("multiple_of check with a zero divisor");e.write(`if (${o} % ${r.value}n !== 0n) return INVALID;`)}else{let n=N(t,nr);e.write(`if (${n}(${o}, ${gt(r.value,"multiple_of")}) !== 0) return INVALID;`)}}function Vg(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 L(`number format ${o}`)}}function xk(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 L(`bigint format ${o}`)}}function kk(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 wk(e,t,r,o){if(r.when)throw new L('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):ge(i),s=O(t);e.write(`const ${s} = ${o}[${a}];`),fe(e,t,n[i],s,!1)}}function Sk(e,t,r,o){let n=`${o}[${JSON.stringify(r.property)}]`;Y(e,t,r.schema,n)}function Ik(e,t,r,o,n){let i=r._zod.def.tx;if(!i)throw new L("overwrite check without a transform function");if(Ct(i))throw new Me("z.compile: async overwrite transforms are not supported");let a=N(t,i);e.write(`const ${n} = ${a}(${o});`)}function qu(){throw new we}function Yu(e){this.issues.push(e)}function zk(e,t,r,o){let n=r._zod.def;if(n.fn){if(Ct(n.fn))throw new Me("z.compile: async .refine() predicates are not supported");let i=Ut(t,n.fn),a=N(t,qu),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 Me("z.compile: async .superRefine() / check functions are not supported");let i=r._zod.check,s=Ut(t,l=>{let d={value:l,issues:[],addIssue:Yu};return i(d)instanceof Promise&&qu(),d.issues.length===0?d.value:ve}),u=O(t);return e.write(`const ${u} = ${s}(${o});`),e.write(`if (${u} === INVALID) return INVALID;`),u}throw new L("custom check without a predicate or check function")}var Pk=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 Kg(e,t,r,o,n=!0){let i=r.format;if(i==="base64"){let l=N(t,xr);return e.write(`if (!${l}(${o})) return INVALID;`),o}if(i==="base64url"){let l=N(t,Wi);return e.write(`if (!${l}(${o})) return INVALID;`),o}if(i==="jwt"){let l=N(t,Hi),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,Ji);return e.write(`if (!${l}(${o})) return INVALID;`),o}if(i==="credit_card"){let l=N(t,Gi);return e.write(`if (!${l}(${o})) return INVALID;`),o}if(i==="iban"){let l=N(t,qi);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,Fi),d=N(t,r),p=O(t),f=O(t);if(e.write(`const ${p} = ${o}.trim();`),e.write(`const ${f} = ${l}(${p}, ${d});`),e.write(`if (typeof ${f} === "number") return INVALID;`),a.hostname!==void 0){let $=N(t,Vi);e.write(`if (!${$}(${f}, ${d}.hostname)) return INVALID;`)}if(a.protocol!==void 0){let $=N(t,Ki);e.write(`if (!${$}(${f}, ${d}.protocol)) return INVALID;`)}if(!n)return null;let m=O(t),v=a.normalize?`${f}.href`:`${N(t,$r)}(${p})`;return e.write(`const ${m} = ${v};`),m}let s=r.fn;if(s){if(Ct(s))throw new L(`async string format ${i}`);let l=N(t,s);return e.write(`if (!${l}(${o})) return INVALID;`),o}if(Pk.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 L("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(${ge(r.includes)})) return INVALID;`);break;case"starts_with":{let l=r.prefix;e.write(`if (${o}.slice(0, ${l.length}) !== ${ge(l)}) return INVALID;`);break}case"ends_with":{let l=r.suffix;e.write(`if (${o}.slice(-${l.length}) !== ${ge(l)}) return INVALID;`);break}default:throw new L(`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 L(`coercion (z.coerce.${a}())`);let s=n||!!i.checks?.length,u;switch(a){case"string":u=jk(e,t,r,o,s);break;case"number":u=Ak(e,r,o);break;case"boolean":u=Tk(e,o);break;case"bigint":u=Ok(e,r,o);break;case"symbol":u=Nk(e,o);break;case"undefined":u=Dk(e,o);break;case"null":u=Uk(e,o);break;case"any":case"unknown":u=o;break;case"never":e.write("return INVALID;"),u=o;break;case"void":u=Ck(e,o);break;case"nan":u=Ek(e,o);break;case"date":u=Rk(e,o);break;case"object":u=Mk(e,t,r,o,s);break;case"optional":u=Lk(e,t,r,o,s);break;case"nullable":u=Vk(e,t,r,o,s);break;case"array":u=Kk(e,t,r,o,s);break;case"literal":u=Jk(e,t,r,o);break;case"enum":u=Bk(e,t,r,o);break;case"readonly":{let l=Mg(e,t,r,o),d=O(t);e.write(`const ${d} = Object.freeze(${l});`),u=d;break}case"success":Mg(e,t,r,o),u="true";break;case"default":case"prefault":u=Wk(e,t,r,o);break;case"nonoptional":u=Gk(e,t,r,o);break;case"tuple":u=qk(e,t,r,o);break;case"union":u=Hk(e,t,r,o);break;case"intersection":u=Qk(e,t,r,o);break;case"record":u=ew(e,t,r,o);break;case"map":u=nw(e,t,r,o);break;case"set":u=rw(e,t,r,o);break;case"file":u=iw(e,o);break;case"template_literal":u=ow(e,t,r,o);break;case"lazy":u=aw(e,t,r,o);break;case"pipe":u=sw(e,t,r,o);break;case"custom":u=cw(e,t,r,o);break;case"transform":u=dw(e,t,r,o);break;case"catch":u=lw(e,t,r,o);break;default:throw new L(`schema type ${a}`)}return u===null?null:yk(e,t,r,u)}function jk(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:Kg(e,t,i,o,n)}function Ak(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&&Vg(e,{format:o.format},r),r}function Tk(e,t){return e.write(`if (typeof ${t} !== "boolean") return INVALID;`),t}function Ok(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 Nk(e,t){return e.write(`if (typeof ${t} !== "symbol") return INVALID;`),t}function Dk(e,t){return e.write(`if (${t} !== undefined) return INVALID;`),t}function Uk(e,t){return e.write(`if (${t} !== null) return INVALID;`),t}function Ck(e,t){return e.write(`if (${t} !== undefined) return INVALID;`),t}function Ek(e,t){return e.write(`if (typeof ${t} !== "number" || !Number.isNaN(${t})) return INVALID;`),t}function Rk(e,t){return e.write(`if (!(${t} instanceof Date) || Number.isNaN(${t}.getTime())) return INVALID;`),t}function Mk(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=S=>typeof S=="symbol"?N(t,S):ge(S),p=S=>typeof S=="symbol"?`[${d(S)}]`:ge(S),f=a;if(s.includes("__proto__"))throw new L('object shape key "__proto__"');let m=new Map;for(let S of l){let T=f[S],z=d(S),C=O(t);if(e.write(`const ${C} = ${o}[${z}];`),T._zod.optin!==void 0){let j=O(t);e.write(`let ${j} = (() => {`),e.indented(A=>{let ue=fe(A,t,T,C);A.write(`return ${ue};`)}),e.write("})();"),T._zod.optout==="optional"?(e.write(`if (${j} === INVALID) {`),e.indented(A=>{A.write(`if (${z} in ${o}) return INVALID;`),A.write(`${j} = undefined;`)}),e.write("}")):e.write(`if (${j} === INVALID) return INVALID;`),m.set(S,j)}else{Fk(T)&&e.write(`if (!(${z} in ${o})) return INVALID;`);let j=fe(e,t,T,C,n);j!==null&&m.set(S,j)}}let v=i.catchall,$="none";if(v){let S=v._zod.def.type;if(S==="never"){let T=s.map(z=>`k !== ${ge(z)}`).join(" && ")||"true";e.write(`for (const k in ${o}) {`),e.indented(z=>{z.write(`if (${T}) return INVALID;`)}),e.write("}")}else(S==="unknown"||S==="any")&&!v._zod.def.checks?.length?$="passthrough":$="schema"}let k=O(t),P=l.some(S=>Rg(f[S])||Hu(f[S]));if(!n){if($==="schema"){let S=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;'),S&&T.write(`if (${S}.has(k)) continue;`);let z=O(t);T.write(`const ${z} = ${o}[k];`),fe(T,t,v,z,!1)}),e.write("}")}return null}if(P){e.write(`const ${k} = {};`);for(let S of l){let T=d(S),z=m.get(S);Hu(f[S])?e.write(`if (${T} in ${o}) ${k}[${T}] = ${z};`):Rg(f[S])?e.write(`if (${z} !== undefined || ${T} in ${o}) ${k}[${T}] = ${z};`):e.write(`${k}[${T}] = ${z};`)}}else{let S=l.map(T=>`${p(T)}: ${m.get(T)}`).join(", ");e.write(`const ${k} = { ${S} };`)}if($!=="none"){let S=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;'),S&&T.write(`if (${S}.has(k)) continue;`),$==="passthrough")T.write(`${k}[k] = ${o}[k];`);else{let z=O(t);T.write(`const ${z} = ${o}[k];`);let C=fe(T,t,v,z);T.write(`${k}[k] = ${C};`)}}),e.write("}")}return k}function Lk(e,t,r,o,n=!0){let i=r._zod.def;if(Zk(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 Zk(e){return e._zod.traits?.has("$ZodExactOptional")===!0}function Fk(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 Hu(e){return e._zod.optin==="optional"&&e._zod.optout==="optional"}function Rg(e){return(e._zod.optin!=="defaulted"||e._zod.optout==="optional")&&bn(e)}function bn(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?bn(t.innerType):!0;case"union":return t.options?t.options.some(bn):!0;case"intersection":return!t.left||!t.right||bn(t.left)||bn(t.right);case"pipe":return t.out?bn(t.out):!0;default:return!0}}function Vk(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 Qu(e,t,r){for(let[o,n]of un(t._zod.def.checks))e.write(`if (${r} > ${gt(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;`),Qu(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 Jk(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} !== ${ge(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 L(`literal type ${typeof a}`);return o}function Bk(e,t,r,o){let n=r._zod.values;if(!n)throw new L("enum schema without enumerated values");let i=N(t,n);return e.write(`if (!${i}.has(${o})) return INVALID;`),o}function Mg(e,t,r,o){let n=r._zod.def;return Y(e,t,n.innerType,o)}function Wk(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,rr);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 Gk(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 qk(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=Lg(i,"optin"),u=Lg(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(f=>{f.write(`if (${d} < ${o}.length) {`),f.indented(m=>{let v=O(t);m.write(`const ${v} = ${o}[${d}];`);let $=fe(m,t,p,v);m.write(`${l}[${d}] = ${$};`)}),f.write("} else {"),f.indented(m=>{if(Hu(p)){m.write(`${l}.length = ${d};`);return}let v=O(t),$=O(t);m.write(`const ${v} = undefined;`),m.write(`const ${$} = (() => {`),m.indented(k=>{let P=fe(k,t,p,v);k.write(`return ${P};`)}),m.write("})();"),m.write(`if (${$} === INVALID || ${$} === undefined) ${l}.length = ${d};`),m.write(`else ${l}[${d}] = ${$};`)}),f.write("}")}),e.write("}");else{let f=O(t);e.write(`const ${f} = ${o}[${d}];`);let m=fe(e,t,p,f);e.write(`${l}[${d}] = ${m};`)}}if(a){let d=O(t),p=O(t);e.write(`for (let ${d} = ${i.length}; ${d} < ${o}.length; ${d}++) {`),e.indented(f=>{f.write(`const ${p} = ${o}[${d}];`);let m=fe(f,t,a,p);f.write(`${l}[${d}] = ${m};`)}),e.write("}")}return l}function Lg(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 Hk(e,t,r,o){let n=r._zod.def,i=n.options;if(n.discriminator)return Xk(e,t,n,o);if(n.inclusive===!1)throw new L("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 Xk(e,t,r,o){if(r.unionFallback)throw new L("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}?.[${ge(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 L("discriminated union option without static discriminator values");for(let f of l){if(s.has(f))throw new L(`duplicate discriminator value ${String(f)}`);s.add(f)}let d=Array.from(l,f=>Yk(t,n,f)),p=a?"if":"else if";e.write(`${p} (${d.join(" || ")}) {`),e.indented(f=>{let m=Y(f,t,u,o);f.write(`${i} = ${m};`)}),e.write("}"),a=!1}return e.write("else { return INVALID; }"),i}function Yk(e,t,r){if(typeof r=="string")return`${t} === ${ge(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 L(`literal discriminator value ${String(r)}`)}function Qk(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,hn),u=O(t);return e.write(`const ${u} = ${s}(${i}, ${a});`),e.write(`if (!${u}.valid) return INVALID;`),`${u}.data`}function ew(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 m=[];for(let $ of d){if(!(typeof $=="string"||typeof $=="number"||typeof $=="symbol"))throw new L(`record key value ${String($)}`);let k=typeof $=="number"?$.toString():$;if(k==="__proto__")throw new L('record key "__proto__"');m.push(k);let P=N(t,$),S=Y(e,t,n.keyType,P),T=O(t);e.write(`const ${T} = ${o}[${tw(t,k)}];`);let z=fe(e,t,n.valueType,T);e.write(`${a}[${S}] = ${z};`)}let v=N(t,new Set(m));return e.write(`for (const ${s} in ${o}) {`),e.indented($=>{$.write(`if (${v}.has(${s})) continue;`),l.mode==="loose"?$.write(`if (${s} !== "__proto__") ${a}[${s}] = ${o}[${s}];`):$.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 m=n.mode==="loose",v=go(n.keyType);v.definite===!1&&(t.definite=!1);let $=N(t,v),k=N(t,rt),P=O(t);return Zg(e,t,o,s,S=>{S.write(`let ${P} = ${$}(${s});`),S.write(`if (${P} === INVALID && typeof ${s} === "string" && ${k}.test(${s})) ${P} = ${$}(Number(${s}));`),m?S.write(`if (${P} === INVALID) { ${a}[${s}] = ${o}[${s}]; continue; }`):S.write(`if (${P} === INVALID) return INVALID;`),S.write(`if (${P} === "__proto__") continue;`);let T=O(t);S.write(`const ${T} = ${o}[${s}];`);let z=fe(S,t,n.valueType,T);S.write(`${a}[${P}] = ${z};`)}),a}return Zg(e,t,o,s,m=>{m.write(`const ${u} = ${o}[${s}];`);let v=fe(m,t,n.valueType,u);m.write(`${a}[${s}] = ${v};`)},"return INVALID;"),a}function Zg(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 tw(e,t){return typeof t=="string"?ge(t):N(e,t)}function nw(e,t,r,o){let n=r._zod.def;e.write(`if (!(${o} instanceof Map)) return INVALID;`),Qu(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 rw(e,t,r,o){let n=r._zod.def;e.write(`if (!(${o} instanceof Set)) return INVALID;`),Qu(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 iw(e,t){return e.write(`if (!(${t} instanceof File)) return INVALID;`),t}function ow(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 aw(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 sw(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 Me("z.compile: async transforms in pipes are not supported");let a=n.transform,u=Ut(t,d=>{let p={value:d,issues:[],addIssue:Yu},f=a(d,p);return f instanceof Promise?ve:p.issues.length===0?f:ve}),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 cw(e,t,r,o){let n=r._zod.def;if(n.fn){if(Ct(n.fn))throw new Me("z.compile: async custom predicates are not supported");let i=Ut(t,n.fn),a=N(t,qu),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 L("custom schema without a predicate function");return o}function uw(e,t,r){let o=e._zod.run({value:r,issues:[]},{});if(o&&typeof o.then=="function")return ve;let n=o;return n.issues.length===0?n.value:t()}function lw(e,t,r,o){let n=r._zod.def;if(!n.catchValue[bi])throw new L("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,uw);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 dw(e,t,r,o){let n=r._zod.def;if(n.transform){if(Ct(n.transform))throw new Me("z.compile: async transforms are not supported");let i=n.transform,s=Ut(t,l=>{let d={value:l,issues:[],addIssue:Yu},p=i(l,d);return p instanceof Promise?ve:d.issues.length===0?p:ve}),u=O(t);return e.write(`const ${u} = ${s}(${o});`),e.write(`if (${u} === INVALID) return INVALID;`),u}return o}function ho(e){return e.checks&&(e.checks=[...e.checks]),e}function el(e,t){return new e(ho({type:"string",...w(t)}))}function tl(e,t){return new e(ho({type:"string",coerce:!0,...w(t)}))}function vo(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...w(t)})}function yo(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...w(t)})}function bo(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...w(t)})}function $o(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...w(t)})}function _o(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...w(t)})}function xo(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...w(t)})}function Nr(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...w(t)})}function ko(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...w(t)})}function wo(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...w(t)})}function So(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...w(t)})}function Io(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...w(t)})}function zo(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...w(t)})}function Po(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...w(t)})}function jo(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...w(t)})}function Ao(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...w(t)})}function To(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...w(t)})}function nl(e,t){return new e({type:"string",format:"mac",check:"string_format",abort:!1,...w(t)})}function Oo(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...w(t)})}function No(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...w(t)})}function Do(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...w(t)})}function Uo(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...w(t)})}function Co(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...w(t)})}function rl(e,t){return new e({type:"string",format:"credit_card",check:"string_format",abort:!1,...w(t)})}function il(e,t){return new e({type:"string",format:"iban",check:"string_format",abort:!1,...w(t)})}function Eo(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...w(t)})}var ol={Any:null,Minute:-1,Second:0,Millisecond:3,Microsecond:6};function Dr(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...w(t)})}function Ur(e,t){return new e({type:"string",format:"date",check:"string_format",...w(t)})}function Cr(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...w(t)})}function Er(e,t){return new e({type:"string",format:"duration",check:"string_format",...w(t)})}function al(e,t){return new e(ho({type:"number",checks:[],...w(t)}))}function sl(e,t){return new e(ho({type:"number",coerce:!0,checks:[],...w(t)}))}function cl(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...w(t)})}function ul(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"float32",...w(t)})}function ll(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"float64",...w(t)})}function dl(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"int32",...w(t)})}function pl(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"uint32",...w(t)})}function ml(e,t){return new e({type:"boolean",...w(t)})}function fl(e,t){return new e({type:"boolean",coerce:!0,...w(t)})}function gl(e,t){return new e({type:"bigint",...w(t)})}function hl(e,t){return new e({type:"bigint",coerce:!0,...w(t)})}function vl(e,t){return new e({type:"bigint",check:"bigint_format",abort:!1,format:"int64",...w(t)})}function yl(e,t){return new e({type:"bigint",check:"bigint_format",abort:!1,format:"uint64",...w(t)})}function bl(e,t){return new e({type:"symbol",...w(t)})}function $l(e,t){return new e({type:"undefined",...w(t)})}function _l(e,t){return new e({type:"null",...w(t)})}function xl(e){return new e({type:"any"})}function kl(e){return new e({type:"unknown"})}function wl(e,t){return new e({type:"never",...w(t)})}function Sl(e,t){return new e({type:"void",...w(t)})}function Il(e,t){return new e({type:"date",...w(t)})}function zl(e,t){return new e({type:"date",coerce:!0,...w(t)})}function Pl(e,t){return new e({type:"nan",...w(t)})}function Fe(e,t){return new Ui({check:"less_than",...w(t),value:e,inclusive:!1})}function Ae(e,t){return new Ui({check:"less_than",...w(t),value:e,inclusive:!0})}function Ve(e,t){return new Ci({check:"greater_than",...w(t),value:e,inclusive:!1})}function Te(e,t){return new Ci({check:"greater_than",...w(t),value:e,inclusive:!0})}function Ro(e){return Ve(0,e)}function Mo(e){return Fe(0,e)}function Lo(e){return Ae(0,e)}function Zo(e){return Te(0,e)}function ht(e,t){return new lc({check:"multiple_of",...w(t),value:e})}function vt(e,t){return new mc({check:"max_size",...w(t),maximum:e})}function Ke(e,t){return new fc({check:"min_size",...w(t),minimum:e})}function Et(e,t){return new gc({check:"size_equals",...w(t),size:e})}function Rt(e,t){return new hc({check:"max_length",...w(t),maximum:e})}function it(e,t){return new vc({check:"min_length",...w(t),minimum:e})}function Mt(e,t){return new yc({check:"length_equals",...w(t),length:e})}function $n(e,t){return new bc({check:"string_format",format:"regex",...w(t),pattern:e})}function _n(e){return new $c({check:"string_format",format:"lowercase",...w(e)})}function xn(e){return new _c({check:"string_format",format:"uppercase",...w(e)})}function kn(e,t){return new xc({check:"string_format",format:"includes",...w(t),includes:e})}function wn(e,t){return new kc({check:"string_format",format:"starts_with",...w(t),prefix:e})}function Sn(e,t){return new wc({check:"string_format",format:"ends_with",...w(t),suffix:e})}function Fo(e,t,r){return new Sc({check:"property",property:e,schema:t,...w(r)})}function In(e,t){return new Ic({check:"properties",shape:e,...w(t)})}function zn(e,t){return new zc({check:"mime_type",mime:e,...w(t)})}function Le(e){return new Pc({check:"overwrite",tx:e})}function Pn(e){return Le(t=>t.normalize(e))}function jn(){return Le(e=>e.trim())}function An(){return Le(e=>e.toLowerCase())}function Tn(){return Le(e=>e.toUpperCase())}function On(){return Le(e=>ps(e))}function jl(e,t,r){return new e({type:"array",element:t,...w(r)})}function pw(e,t,r){return new e({type:"union",options:t,...w(r)})}function mw(e,t,r){return new e({type:"union",options:t,inclusive:!1,...w(r)})}function fw(e,t,r,o){return new e({type:"union",options:r,discriminator:t,...w(o)})}function gw(e,t,r){return new e({type:"intersection",left:t,right:r})}function hw(e,t,r,o){let n=r instanceof U,i=n?o:r,a=n?r:null;return new e({type:"tuple",items:t,rest:a,...w(i)})}function vw(e,t,r,o){return new e({type:"record",keyType:t,valueType:r,...w(o)})}function yw(e,t,r,o){return new e({type:"map",keyType:t,valueType:r,...w(o)})}function bw(e,t,r){return new e({type:"set",valueType:t,...w(r)})}function $w(e,t,r){let o=Array.isArray(t)?Object.fromEntries(t.map(n=>[n,n])):t;return new e({type:"enum",entries:o,...w(r)})}function _w(e,t,r){return new e({type:"enum",entries:t,...w(r)})}function xw(e,t,r){return new e({type:"literal",values:Array.isArray(t)?t:[t],...w(r)})}function Al(e,t){return new e({type:"file",...w(t)})}function kw(e,t){return new e({type:"transform",transform:t})}function ww(e,t){return new e({type:"optional",innerType:t})}function Sw(e,t){return new e({type:"nullable",innerType:t})}function Iw(e,t,r){return new e({type:"default",innerType:t,get defaultValue(){return typeof r=="function"?r():rr(r)}})}function zw(e,t,r){return new e({type:"nonoptional",innerType:t,...w(r)})}function Pw(e,t){return new e({type:"success",innerType:t})}function jw(e,t,r){return new e({type:"catch",innerType:t,catchValue:typeof r=="function"?r:ys(r)})}function Aw(e,t,r){return new e({type:"pipe",in:t,out:r})}function Tw(e,t){return new e({type:"readonly",innerType:t})}function Ow(e,t,r){return new e({type:"template_literal",parts:t,...w(r)})}function Nw(e,t){return new e({type:"lazy",getter:t})}function Dw(e,t){return new e({type:"promise",innerType:t})}function Tl(e,t,r){let o=w(r);return o.abort??(o.abort=!0),new e({type:"custom",check:"custom",fn:t,...o})}function Ol(e,t,r){return new e({type:"custom",check:"custom",fn:t,...w(r)})}function Nl(e,t){let r=Jg(o=>(o.addIssue=n=>{if(typeof n=="string")o.issues.push(ln(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(ln(i))}},e(o.value,o)),t);return r}function Jg(e,t){let r=new q({check:"custom",...w(t)});return r._zod.check=e,r}function Dl(e){let t=new q({check:"describe"});return t._zod.onattach=[r=>{let o=de.get(r)??{};de.add(r,{...o,description:e})}],t._zod.check=()=>{},t}function Ul(e){let t=new q({check:"meta"});return t._zod.onattach=[r=>{let o=de.get(r)??{};de.add(r,{...o,...e})}],t._zod.check=()=>{},t}function Cl(e,t){let r=w(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(m=>typeof m=="string"?m.toLowerCase():m),n=n.map(m=>typeof m=="string"?m.toLowerCase():m));let i=new Set(o),a=new Set(n),s=e.Codec??Ir,u=e.Boolean??wr,l=e.String??Nt,d=new l({type:"string",error:r.error}),p=new u({type:"boolean",error:r.error}),f=new s({type:"pipe",in:d,out:p,transform:((m,v)=>{let $=m;return r.case!=="sensitive"&&($=$.toLowerCase()),i.has($)?!0:a.has($)?!1:(v.issues.push({code:"invalid_value",expected:"stringbool",values:[...i,...a],input:v.value,inst:f,continue:!1}),{})}),reverseTransform:((m,v)=>m===!0?o[0]||"true":n[0]||"false"),error:r.error});return f._zod.bag.truthy=o,f._zod.bag.falsy=n,f._zod.bag.case=r.case??"insensitive",f}function Lt(e,t,r,o={}){let n=w(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 Rr(e,...t){for(let r of t)for(let o of Reflect.ownKeys(r))Object.prototype.propertyIsEnumerable.call(r,o)&&le(e,o,r[o]);return e}function yt(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??de,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 J(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 f=a.schema,m=t.processors[n.type];if(!m)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${n.type}`);m(e,t,f,d)}let p=e._zod.parent;p&&(a.ref||(a.ref=p),J(p,t,d),t.seen.get(p).isParent=!0)}let u=t.metadataRegistry.get(e);return u&&Rr(a.schema,u),t.io==="input"&&ye(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 Bg(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}function bt(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,f=e.external.uri??(v=>v);if(p)return{ref:f(p)};let m=a[1].defId??a[1].schema.id??`schema${e.counter++}`;return a[1].defId=m,{defId:m,ref:`${f("__shared")}#/${s}/${Bg(m)}`}}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+Bg(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 qg(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;qg(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 Hg=new Set(["type","properties","required","additionalProperties"]),Wg=["oneOf","anyOf"];function Gg(e){let t=e.additionalProperties;return t===void 0||t===!1||typeof t!="object"||t===null?null:Object.keys(t).length?t:null}function El(e){let t=[];for(let i of e){if(typeof i!="object"||i.type!=="object")return null;for(let a in i)if(!Hg.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]??Gg(l);d!=null&&(s.some(p=>JSON.stringify(p)===JSON.stringify(d))||s.push(d))}let u=s.length===1?s[0]:El(s)??{allOf:s};le(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=Gg(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 Uw(e){let t=e.allOf;if(!Array.isArray(t)||t.length<2)return;for(let n of Hg)if(n in e)return;let r=t.filter(n=>Wg.some(i=>Array.isArray(n[i]))),o=null;if(!r.length)o=El(t);else{let n=r[0],i=Wg.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=>El([...a,u]));if(s.some(u=>!u))return;o={[i]:s}}o&&(delete e.allOf,Rr(e,o))}function $t(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 m=e.seen.get(p),v=m.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)):Rr(l,v),Rr(l,d),s._zod.parent===p)for(let k in l)k==="$ref"||k==="allOf"||k in d||delete l[k];if(v.$ref&&m.def)for(let k in l)k==="$ref"||k==="allOf"||k in m.def&&JSON.stringify(l[k])===JSON.stringify(m.def[k])&&delete l[k]}let f=s._zod.parent;if(f&&f!==p){o(f);let m=e.seen.get(f);if(m?.schema.$ref&&(l.$ref=m.schema.$ref,m.def))for(let v in l)v==="$ref"||v==="allOf"||v in m.def&&JSON.stringify(l[v])===JSON.stringify(m.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())qg(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)??[])Uw(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)}Rr(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,le(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:Nn(t,"input",e.processors),output:Nn(t,"output",e.processors)}},enumerable:!1,writable:!1}),s}catch{throw new Error("Error converting schema to JSON.")}}function ye(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 ye(o.element,r);if(o.type==="set")return ye(o.valueType,r);if(o.type==="lazy")return ye(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 ye(o.innerType,r);if(o.type==="intersection")return ye(o.left,r)||ye(o.right,r);if(o.type==="record"||o.type==="map")return ye(o.keyType,r)||ye(o.valueType,r);if(o.type==="pipe")return e._zod.traits.has("$ZodCodec")?!0:ye(o.in,r)||ye(o.out,r);if(o.type==="object"){for(let n in o.shape)if(ye(o.shape[n],r))return!0;return!1}if(o.type==="union"){for(let n of o.options)if(ye(n,r))return!0;return!1}if(o.type==="tuple"){for(let n of o.items)if(ye(n,r))return!0;return!!(o.rest&&ye(o.rest,r))}return!1}var Rl=(e,t={})=>r=>{let o=yt({...r,processors:t});return J(e,o),bt(o,e),$t(o,e)},Nn=(e,t,r={})=>o=>{let{libraryOptions:n,target:i}=o??{},a=yt({...n??{},target:i,io:t,processors:r});return J(e,a),bt(a,e),$t(a,e)};var Dn=(e,t,r)=>{(e[t]===void 0||r>e[t])&&(e[t]=r)},Un=(e,t,r)=>{(e[t]===void 0||r<e[t])&&(e[t]=r)},Xg=(e,t)=>{Dn(e,"minimum",t),Un(e,"maximum",t)},th=(e,t)=>{e.multipleOf??(e.multipleOf=[]),e.multipleOf.includes(t)||e.multipleOf.push(t)},nh=(e,t)=>{e.patterns??(e.patterns=new Set),e.patterns.add(t)},rh=(e,t)=>{e.mime=e.mime?e.mime.filter(r=>t.includes(r)):[...t]},ih=(e,t)=>{e.format=t,t.includes("int")&&(e.isInt=!0)},Yg=(e,t)=>Dn(e,"minimum",t.minimum),Qg=(e,t)=>Un(e,"maximum",t.maximum),eh=e=>(t,r)=>{ih(t,r.format);let[o,n]=e[r.format];Dn(t,"minimum",o),Un(t,"maximum",n)},Cw={greater_than:(e,t)=>Dn(e,t.inclusive?"minimum":"exclusiveMinimum",t.value),less_than:(e,t)=>Un(e,t.inclusive?"maximum":"exclusiveMaximum",t.value),multiple_of:(e,t)=>th(e,t.value),number_format:eh(or),bigint_format:eh(ar),min_length:Yg,max_length:Qg,length_equals:(e,t)=>Xg(e,t.length),min_size:Yg,max_size:Qg,size_equals:(e,t)=>Xg(e,t.size),string_format:(e,t)=>{ih(e,t.format),t.pattern&&nh(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)=>rh(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)Cw[i._zod.def.check]?.(t,i._zod.def);let n=e._zod.bag;n.minimum!==void 0&&Dn(t,"minimum",n.minimum),n.exclusiveMinimum!==void 0&&Dn(t,"exclusiveMinimum",n.exclusiveMinimum),n.maximum!==void 0&&Un(t,"maximum",n.maximum),n.exclusiveMaximum!==void 0&&Un(t,"exclusiveMaximum",n.exclusiveMaximum),n.multipleOf!==void 0&&th(t,n.multipleOf),n.format!==void 0&&(t.format??(t.format=n.format),n.format.includes("int")&&(t.isInt=!0)),n.mime&&rh(t,n.mime);for(let i of n.patterns??[])nh(t,i);return t}var Ew={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},Rw=new Map([[Bi,Ks],[kr,Js]]),oh=e=>Rw.get(e)??e,Zl=(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=Ew[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(oh);p.length===1?n.pattern=p[0].source:p.length>1&&(n.allOf=[...p.map(f=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:f.source}))])}},Fl=(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),f=typeof u=="number"&&u<=(a??Number.POSITIVE_INFINITY),m=t.target==="draft-04"||t.target==="openapi-3.0";if(p?m?(n.minimum=l,n.exclusiveMinimum=!0):n.exclusiveMinimum=l:typeof i=="number"&&(n.minimum=i),f?m?(n.maximum=u,n.exclusiveMaximum=!0):n.exclusiveMaximum=u:typeof a=="number"&&(n.maximum=a),s){let v=new Set;for(let P of s)Number.isFinite(P)&&P!==0?v.add(Math.abs(P)):oe(e,t,n,o,`A multipleOf divisor of ${P} cannot be represented in JSON Schema`);let[$,...k]=v;$!==void 0&&(n.multipleOf=$),k.length&&(n.allOf=[...n.allOf??[],...k.map(P=>({multipleOf:P}))])}},Vl=(e,t,r,o)=>{r.type="boolean"},Kl=(e,t,r,o)=>{oe(e,t,r,o,"BigInt cannot be represented in JSON Schema")},Jl=(e,t,r,o)=>{oe(e,t,r,o,"Symbols cannot be represented in JSON Schema")},Bl=(e,t,r,o)=>{t.target==="openapi-3.0"?(r.type="string",r.nullable=!0,r.enum=[null]):r.type="null"},Wl=(e,t,r,o)=>{oe(e,t,r,o,"Undefined cannot be represented in JSON Schema")},Gl=(e,t,r,o)=>{oe(e,t,r,o,"Void cannot be represented in JSON Schema")},ql=(e,t,r,o)=>{r.not={}},Hl=(e,t,r,o)=>{},Xl=(e,t,r,o)=>{},Yl=(e,t,r,o)=>{oe(e,t,r,o,"Date cannot be represented in JSON Schema")},Ql=(e,t,r,o)=>{let n=e._zod.def,i=on(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},ed=(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},td=(e,t,r,o)=>{oe(e,t,r,o,"NaN cannot be represented in JSON Schema")},nd=(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},rd=(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})))},id=(e,t,r,o)=>{r.type="boolean"},od=(e,t,r,o)=>{oe(e,t,r,o,"Custom types cannot be represented in JSON Schema")},ad=(e,t,r,o)=>{oe(e,t,r,o,"Function types cannot be represented in JSON Schema")},sd=(e,t,r,o)=>{oe(e,t,r,o,"Transforms cannot be represented in JSON Schema")},cd=(e,t,r,o)=>{oe(e,t,r,o,"Map cannot be represented in JSON Schema")},ud=(e,t,r,o)=>{oe(e,t,r,o,"Set cannot be represented in JSON Schema")},ld=(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=J(i.element,t,{...o,path:[...o.path,"items"]})};function Mr(e){let t=e._zod.def;return t.type==="pipe"&&t.in._zod.traits.has("$ZodTransform")?Mr(t.out):t.type==="catch"?Mr(t.innerType):e._zod.optin}var dd=(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)le(n.properties,l,J(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"?Mr(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=J(i.catchall,t,{...o,path:[...o.path,"additionalProperties"]})):t.io==="output"&&(n.additionalProperties=!1)},Ko=(e,t,r,o)=>{let n=e._zod.def,i=n.inclusive===!1,a=n.options.map((s,u)=>J(s,t,{...o,path:[...o.path,i?"oneOf":"anyOf",u]}));i?r.oneOf=a:r.anyOf=a},pd=(e,t,r,o)=>{let n=e._zod.def,i=J(n.left,t,{...o,path:[...o.path,"allOf",0]}),a=J(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)},md=(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(($,k)=>J($,t,{...o,path:[...o.path,a,k]})),l=i.rest?J(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 $=i.items[d-1];if(!(t.io==="input"?Mr($)!==void 0:$._zod.optout==="optional"))break;d--}let p=i.items.length,f=!i.rest;t.target==="draft-2020-12"?(n.prefixItems=u,f?n.items=!1:l&&(n.items=l),d>0&&(n.minItems=d),f&&(n.maxItems=p)):t.target==="openapi-3.0"?(n.items={anyOf:u},l&&n.items.anyOf.push(l),d>0&&(n.minItems=d),f&&(n.maxItems=p)):(n.items=u,f?n.additionalItems=!1:l&&(n.additionalItems=l),d>0&&(n.minItems=d),f&&(n.maxItems=p));let{minimum:m,maximum:v}=ae(e);typeof m=="number"&&(n.minItems=m),typeof v=="number"&&(n.maxItems=v)};function Ml(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 $=Ml(e,v,r);return $===v?t:$}for(let v of["anyOf","oneOf"]){let $=t[v];if(!Array.isArray($))continue;let k=$.map(P=>Ml(e,P,r));k.some((P,S)=>P!==$[S])&&(t={...t,[v]:k})}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:f,...m}=t;return m.enum?m.enum=m.enum.map(v=>typeof v=="number"?String(v):v):typeof m.const=="number"&&(m.const=String(m.const)),n&&(m.type="string",i||(m.pattern=(o.includes("number")?rt:hr).source)),m}var Ll=new WeakMap;function Mw(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 Ll.get(e)??[]){let n=e.seen.get(o),i=(n?.def??n?.schema)?.propertyNames;if(!i||i===!0||r.has(i))continue;let a=Ml(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 fd=(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=J(i.valueType,t,{...o,path:[...o.path,"patternProperties","*"]});n.patternProperties={};for(let p of s)le(n.patternProperties,oh(p).source,d)}else{if(t.target==="draft-07"||t.target==="draft-2020-12"){n.propertyNames=J(i.keyType,t,{...o,path:[...o.path,"propertyNames"]});let d=Ll.get(t);d||(d=[],Ll.set(t,d),t.deferred.push(()=>Mw(t))),d.push(e)}n.additionalProperties=J(i.valueType,t,{...o,path:[...o.path,"additionalProperties"]})}let u=a._zod.values,l=t.io==="input"&&Mr(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))}},gd=(e,t,r,o)=>{let n=e._zod.def,i=J(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"}]},hd=(e,t,r,o)=>{let n=e._zod.def;J(n.innerType,t,o);let i=t.seen.get(e);i.ref=n.innerType},vd=Symbol();function ah(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"),vd):JSON.parse(a)}var yd=(e,t,r,o)=>{let n=e._zod.def;J(n.innerType,t,o);let i=t.seen.get(e);i.ref=n.innerType;let a=ah(n.defaultValue,e,t,r,o);a!==vd&&(r.default=a)},bd=(e,t,r,o)=>{let n=e._zod.def;J(n.innerType,t,o);let i=t.seen.get(e);if(i.ref=n.innerType,t.io!=="input")return;let a=ah(n.defaultValue,e,t,r,o);a!==vd&&(r._prefault=a)},$d=(e,t,r,o)=>{let n=e._zod.def;J(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},_d=(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;J(a,t,o);let s=t.seen.get(e);s.ref=a},xd=(e,t,r,o)=>{let n=e._zod.def;J(n.innerType,t,o);let i=t.seen.get(e);i.ref=n.innerType,r.readOnly=!0},kd=(e,t,r,o)=>{let n=e._zod.def;J(n.innerType,t,o);let i=t.seen.get(e);i.ref=n.innerType},Jo=(e,t,r,o)=>{let n=e._zod.def;J(n.innerType,t,o);let i=t.seen.get(e);i.ref=n.innerType},wd=(e,t,r,o)=>{let n=e._zod.innerType;J(n,t,o);let i=t.seen.get(e);i.ref=n},Vo={string:Zl,number:Fl,boolean:Vl,bigint:Kl,symbol:Jl,null:Bl,undefined:Wl,void:Gl,never:ql,any:Hl,unknown:Xl,date:Yl,enum:Ql,literal:ed,nan:td,template_literal:nd,file:rd,success:id,custom:od,function:ad,transform:sd,map:cd,set:ud,array:ld,object:dd,union:Ko,intersection:pd,tuple:md,record:fd,nullable:gd,nonoptional:hd,default:yd,prefault:bd,catch:$d,pipe:_d,readonly:xd,promise:kd,optional:Jo,lazy:wd};function Bo(e,t){if("_idmap"in e){let o=e,n=yt({...t,processors:Vo}),i={};for(let u of o._idmap.entries()){let[l,d]=u;J(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;bt(n,d),le(a,l,$t(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=yt({...t,processors:Vo});return J(e,r),bt(r,e),$t(r,e)}var Wo=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=yt({processors:Vo,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 J(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,bt(this.ctx,t);let o=$t(this.ctx,t),{"~standard":n,...i}=o;return i}};var sh={};var Vn={};et(Vn,{ZodAny:()=>Bd,ZodArray:()=>Hd,ZodBase64:()=>pa,ZodBase64URL:()=>ma,ZodBigInt:()=>Zn,ZodBigIntFormat:()=>ha,ZodBoolean:()=>Ln,ZodCIDRv4:()=>la,ZodCIDRv6:()=>da,ZodCUID:()=>ra,ZodCUID2:()=>ia,ZodCatch:()=>vp,ZodCodec:()=>qr,ZodCreditCard:()=>Rd,ZodCustom:()=>Hr,ZodCustomStringFormat:()=>Kt,ZodDate:()=>Vr,ZodDefault:()=>dp,ZodDiscriminatedUnion:()=>Yd,ZodE164:()=>fa,ZodEmail:()=>Qo,ZodEmoji:()=>ta,ZodEnum:()=>En,ZodExactOptional:()=>$a,ZodFile:()=>sp,ZodFunction:()=>zp,ZodGUID:()=>ea,ZodIBAN:()=>Md,ZodIPv4:()=>ca,ZodIPv6:()=>ua,ZodISODate:()=>xt,ZodISODateTime:()=>_t,ZodISODuration:()=>wt,ZodISOTime:()=>kt,ZodInstanceOf:()=>Ap,ZodIntersection:()=>Qd,ZodJWT:()=>ga,ZodKSUID:()=>sa,ZodLazy:()=>wp,ZodLiteral:()=>ap,ZodMAC:()=>Ed,ZodMap:()=>ip,ZodNaN:()=>bp,ZodNanoID:()=>na,ZodNever:()=>Gd,ZodNonOptional:()=>_a,ZodNull:()=>Kd,ZodNullable:()=>lp,ZodNumber:()=>Mn,ZodNumberFormat:()=>Jt,ZodObject:()=>Jr,ZodOptional:()=>Wr,ZodPipe:()=>Gr,ZodPrefault:()=>mp,ZodPreprocess:()=>$p,ZodPromise:()=>Ip,ZodReadonly:()=>_p,ZodRecord:()=>Cn,ZodSet:()=>op,ZodString:()=>Rn,ZodStringFormat:()=>G,ZodSuccess:()=>hp,ZodSymbol:()=>Fd,ZodTemplateLiteral:()=>kp,ZodTransform:()=>cp,ZodTuple:()=>tp,ZodType:()=>E,ZodULID:()=>oa,ZodURL:()=>Fr,ZodUUID:()=>Je,ZodUndefined:()=>Vd,ZodUnion:()=>Br,ZodUnknown:()=>Wd,ZodVoid:()=>qd,ZodXID:()=>aa,ZodXor:()=>Xd,_ZodString:()=>Yo,_default:()=>pp,_function:()=>bv,any:()=>Hh,array:()=>Kr,base64:()=>Ah,base64url:()=>Th,bigint:()=>Jh,boolean:()=>Zd,catch:()=>yp,check:()=>$v,cidrv4:()=>Ph,cidrv6:()=>jh,codec:()=>gv,creditCard:()=>Nh,cuid:()=>$h,cuid2:()=>_h,currencyCode:()=>Mh,custom:()=>_v,date:()=>Yh,describe:()=>xv,discriminatedUnion:()=>iv,e164:()=>Oh,email:()=>lh,emoji:()=>yh,enum:()=>ya,exactOptional:()=>up,file:()=>dv,float32:()=>Zh,float64:()=>Fh,function:()=>bv,guid:()=>dh,hash:()=>Lh,hex:()=>Rh,hostname:()=>Eh,httpUrl:()=>vh,iban:()=>Dh,instanceof:()=>wv,int:()=>Ho,int32:()=>Vh,int64:()=>Bh,intersection:()=>ep,invertCodec:()=>hv,ipv4:()=>Sh,ipv6:()=>zh,json:()=>Iv,jwt:()=>Uh,keyof:()=>Qh,ksuid:()=>wh,lazy:()=>Sp,literal:()=>lv,looseObject:()=>nv,looseRecord:()=>av,mac:()=>Ih,map:()=>sv,meta:()=>kv,nan:()=>fv,nanoid:()=>bh,nativeEnum:()=>uv,never:()=>va,nonoptional:()=>gp,null:()=>Jd,nullable:()=>Zr,nullish:()=>pv,number:()=>Ld,object:()=>ev,optional:()=>Ft,partialRecord:()=>ov,pipe:()=>Xo,prefault:()=>fp,preprocess:()=>zv,promise:()=>yv,readonly:()=>xp,record:()=>rp,refine:()=>Pp,set:()=>cv,strictObject:()=>tv,string:()=>Lr,stringFormat:()=>Ch,stringbool:()=>Sv,success:()=>mv,superRefine:()=>jp,symbol:()=>Gh,templateLiteral:()=>vv,transform:()=>ba,tuple:()=>np,uint32:()=>Kh,uint64:()=>Wh,ulid:()=>xh,undefined:()=>qh,union:()=>Fn,unknown:()=>Zt,url:()=>hh,uuid:()=>ph,uuidv4:()=>mh,uuidv6:()=>fh,uuidv7:()=>gh,void:()=>Xh,xid:()=>kh,xor:()=>rv});var Go={};et(Go,{endsWith:()=>Sn,gt:()=>Ve,gte:()=>Te,includes:()=>kn,length:()=>Mt,lowercase:()=>_n,lt:()=>Fe,lte:()=>Ae,maxLength:()=>Rt,maxSize:()=>vt,mime:()=>zn,minLength:()=>it,minSize:()=>Ke,multipleOf:()=>ht,negative:()=>Mo,nonnegative:()=>Zo,nonpositive:()=>Lo,normalize:()=>Pn,overwrite:()=>Le,positive:()=>Ro,properties:()=>In,property:()=>Fo,regex:()=>$n,size:()=>Et,slugify:()=>On,startsWith:()=>wn,toLowerCase:()=>An,toUpperCase:()=>Tn,trim:()=>jn,uppercase:()=>xn});var ch=new WeakSet([Object.prototype,Error.prototype]);function qo(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 uh=(e,t)=>{ws.init(e,t),e.name="ZodError";let r=Object.getPrototypeOf(e);ch.has(r)||(ch.add(r),qo(r,"format",o=>n=>pr(o,n)),qo(r,"flatten",o=>n=>dr(o,n)),qo(r,"addIssue",o=>n=>{o.issues.push(n),o.message=JSON.stringify(o.issues,an,2)}),qo(r,"addIssues",o=>n=>{o.issues.push(...n),o.message=JSON.stringify(o.issues,an,2)}),Object.defineProperty(r,"isEmpty",{configurable:!0,enumerable:!1,get(){return this.issues.length===0}}))},Zw=g("ZodError",uh),Ie=g("ZodError",uh,void 0,{Parent:Error});var Sd=dn(Ie),Id=pn(Ie),zd=mn(Ie),Pd=fn(Ie),jd=ki(Ie),Ad=wi(Ie),Td=Si(Ie),Od=Ii(Ie),Nd=zi(Ie),Dd=Pi(Ie),Ud=ji(Ie),Cd=Ai(Ie);function Vw(){ce.localeError||ne(co())}function Vt(){ce.memoizer||ne({memoizer:Ar()})}var E=g("ZodType",(e,t)=>(Vw(),U.init(e,t),e.def=t,e.type=t.type,e),{check(...e){let t=this.def;return this.clone(y.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 V(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},refine(e,t){return this.check(Pp(e,t))},superRefine(e,t){return this.check(jp(e,t))},overwrite(e){return this.check(Le(e))},optional(){return Ft(this)},exactOptional(){return up(this)},nullable(){return Zr(this)},nullish(){return Ft(Zr(this))},nonoptional(e){return gp(this,e)},array(){return Kr(this)},or(e){return Fn([this,e])},and(e){return ep(this,e)},transform(e){return Xo(this,ba(e))},default(e){return pp(this,e)},prefault(e){return fp(this,e)},catch(e){return yp(this,e)},pipe(e){return Xo(this,e)},readonly(){return xp(this)},describe(e){let t=this.clone();return de.add(t,{description:e}),t},meta(...e){if(e.length===0)return de.get(this);let t=this.clone();return de.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 y.hide(this,"~standard",{...Zi(this),jsonSchema:{input:Nn(this,"input"),output:Nn(this,"output")}})},set"~standard"(e){y.own(this,"~standard",e)},parse:function e(t,r){return Sd(this,t,r,{callee:e})},parseAsync:async function e(t,r){return await Id(this,t,r,{callee:e})},safeParse(e,t){return zd(this,e,t)},async safeParseAsync(e,t){return Pd(this,e,t)},get spa(){return this?.safeParseAsync},set spa(e){y.own(this,"spa",e)},validate(e,t){return mr(this,e,t)},validateAsync(e,t){return fr(this,e,t)},encode:function e(t,r){return jd(this,t,r,{callee:e})},decode:function e(t,r){return Ad(this,t,r,{callee:e})},encodeAsync:async function e(t,r){return await Td(this,t,r,{callee:e})},decodeAsync:async function e(t,r){return await Od(this,t,r,{callee:e})},safeEncode(e,t){return Nd(this,e,t)},safeDecode(e,t){return Dd(this,e,t)},async safeEncodeAsync(e,t){return Ud(this,e,t)},async safeDecodeAsync(e,t){return Cd(this,e,t)},toJSONSchema(e){return Rl(this,{})(e)},get description(){return de.get(this)?.description},get _def(){return this._zod.def}}),Yo=g("_ZodString",(e,t)=>{Nt.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Zl(e,r,o,n)},y.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(kn(...e))},startsWith(...e){return this.check(wn(...e))},endsWith(...e){return this.check(Sn(...e))},min(...e){return this.check(it(...e))},max(...e){return this.check(Rt(...e))},length(...e){return this.check(Mt(...e))},nonempty(...e){return this.check(it(1,...e))},lowercase(e){return this.check(_n(e))},uppercase(e){return this.check(xn(e))},trim(){return this.check(jn())},normalize(...e){return this.check(Pn(...e))},toLowerCase(){return this.check(An())},toUpperCase(){return this.check(Tn())},slugify(){return this.check(On())}})),Rn=g("ZodString",(e,t)=>{Nt.init(e,t),Yo.init(e,t)},{email(e){return this.check(vo(Qo,e))},url(e){return this.check(Nr(Fr,e))},jwt(e){return this.check(Eo(ga,e))},emoji(e){return this.check(ko(ta,e))},guid(e){return this.check(yo(ea,e))},uuid(e){return this.check(bo(Je,e))},uuidv4(e){return this.check($o(Je,e))},uuidv6(e){return this.check(_o(Je,e))},uuidv7(e){return this.check(xo(Je,e))},nanoid(e){return this.check(wo(na,e))},cuid(e){return this.check(So(ra,e))},cuid2(e){return this.check(Io(ia,e))},ulid(e){return this.check(zo(oa,e))},base64(e){return this.check(Do(pa,e))},base64url(e){return this.check(Uo(ma,e))},xid(e){return this.check(Po(aa,e))},ksuid(e){return this.check(jo(sa,e))},ipv4(e){return this.check(Ao(ca,e))},ipv6(e){return this.check(To(ua,e))},cidrv4(e){return this.check(Oo(la,e))},cidrv6(e){return this.check(No(da,e))},e164(e){return this.check(Co(fa,e))},datetime(e){return this.check(Dr(_t,e))},date(e){return this.check(Ur(xt,e))},time(e){return this.check(Cr(kt,e))},duration(e){return this.check(Er(wt,e))}});function Lr(e){return el(Rn,e)}var G=g("ZodStringFormat",(e,t)=>{K.init(e,t),Yo.init(e,t)}),_t=g("ZodISODateTime",(e,t)=>{Kc.init(e,t),G.init(e,t)}),xt=g("ZodISODate",(e,t)=>{Jc.init(e,t),G.init(e,t)}),kt=g("ZodISOTime",(e,t)=>{Bc.init(e,t),G.init(e,t)}),wt=g("ZodISODuration",(e,t)=>{Wc.init(e,t),G.init(e,t)}),Qo=g("ZodEmail",(e,t)=>{Nc.init(e,t),G.init(e,t)});function lh(e){return vo(Qo,e)}var ea=g("ZodGUID",(e,t)=>{Tc.init(e,t),G.init(e,t)});function dh(e){return yo(ea,e)}var Je=g("ZodUUID",(e,t)=>{Oc.init(e,t),G.init(e,t)});function ph(e){return bo(Je,e)}function mh(e){return $o(Je,e)}function fh(e){return _o(Je,e)}function gh(e){return xo(Je,e)}var Fr=g("ZodURL",(e,t)=>{Cc.init(e,t),G.init(e,t)});function hh(e){return Nr(Fr,e)}function vh(e){return Nr(Fr,{protocol:gr,hostname:Ws,...y.normalizeParams(e)})}var ta=g("ZodEmoji",(e,t)=>{Ec.init(e,t),G.init(e,t)});function yh(e){return ko(ta,e)}var na=g("ZodNanoID",(e,t)=>{Rc.init(e,t),G.init(e,t)});function bh(e){return wo(na,e)}var ra=g("ZodCUID",(e,t)=>{Mc.init(e,t),G.init(e,t)});function $h(e){return So(ra,e)}var ia=g("ZodCUID2",(e,t)=>{Lc.init(e,t),G.init(e,t)});function _h(e){return Io(ia,e)}var oa=g("ZodULID",(e,t)=>{Zc.init(e,t),G.init(e,t)});function xh(e){return zo(oa,e)}var aa=g("ZodXID",(e,t)=>{Fc.init(e,t),G.init(e,t)});function kh(e){return Po(aa,e)}var sa=g("ZodKSUID",(e,t)=>{Vc.init(e,t),G.init(e,t)});function wh(e){return jo(sa,e)}var ca=g("ZodIPv4",(e,t)=>{Gc.init(e,t),G.init(e,t)});function Sh(e){return Ao(ca,e)}var Ed=g("ZodMAC",(e,t)=>{Hc.init(e,t),G.init(e,t)});function Ih(e){return nl(Ed,e)}var ua=g("ZodIPv6",(e,t)=>{qc.init(e,t),G.init(e,t)});function zh(e){return To(ua,e)}var la=g("ZodCIDRv4",(e,t)=>{Xc.init(e,t),G.init(e,t)});function Ph(e){return Oo(la,e)}var da=g("ZodCIDRv6",(e,t)=>{Yc.init(e,t),G.init(e,t)});function jh(e){return No(da,e)}var pa=g("ZodBase64",(e,t)=>{Qc.init(e,t),G.init(e,t)});function Ah(e){return Do(pa,e)}var ma=g("ZodBase64URL",(e,t)=>{eu.init(e,t),G.init(e,t)});function Th(e){return Uo(ma,e)}var fa=g("ZodE164",(e,t)=>{tu.init(e,t),G.init(e,t)});function Oh(e){return Co(fa,e)}var Rd=g("ZodCreditCard",(e,t)=>{nu.init(e,t),G.init(e,t)});function Nh(e){return rl(Rd,e)}var Md=g("ZodIBAN",(e,t)=>{ru.init(e,t),G.init(e,t)});function Dh(e){return il(Md,e)}var ga=g("ZodJWT",(e,t)=>{iu.init(e,t),G.init(e,t)});function Uh(e){return Eo(ga,e)}var Kt=g("ZodCustomStringFormat",(e,t)=>{ou.init(e,t),G.init(e,t)});function Ch(e,t,r={}){return Lt(Kt,e,t,r)}function Eh(e){return Lt(Kt,"hostname",Bs,e)}function Rh(e){return Lt(Kt,"hex",sc,e)}function Mh(e){return Lt(Kt,"currency_code",qs,e)}function Lh(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 Mn=g("ZodNumber",(e,t)=>{Xi.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Fl(e,r,o,n),e.isFinite=!0},y.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(Ve(e,t))},gte(e,t){return this.check(Te(e,t))},min(e,t){return this.check(Te(e,t))},lt(e,t){return this.check(Fe(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(Ho(e))},safe(e){return this.check(Ho(e))},positive(e){return this.check(Ve(0,e))},nonnegative(e){return this.check(Te(0,e))},negative(e){return this.check(Fe(0,e))},nonpositive(e){return this.check(Ae(0,e))},multipleOf(e,t){return this.check(ht(e,t))},step(e,t){return this.check(ht(e,t))},finite(){return this}}));function Ld(e){return al(Mn,e)}var Jt=g("ZodNumberFormat",(e,t)=>{au.init(e,t),Mn.init(e,t)});function Ho(e){return cl(Jt,e)}function Zh(e){return ul(Jt,e)}function Fh(e){return ll(Jt,e)}function Vh(e){return dl(Jt,e)}function Kh(e){return pl(Jt,e)}var Ln=g("ZodBoolean",(e,t)=>{wr.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Vl(e,r,o,n)});function Zd(e){return ml(Ln,e)}var Zn=g("ZodBigInt",(e,t)=>{Yi.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Kl(e,r,o,n)},y.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(Te(e,t))},min(e,t){return this.check(Te(e,t))},gt(e,t){return this.check(Ve(e,t))},lt(e,t){return this.check(Fe(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(Ve(BigInt(0),e))},negative(e){return this.check(Fe(BigInt(0),e))},nonpositive(e){return this.check(Ae(BigInt(0),e))},nonnegative(e){return this.check(Te(BigInt(0),e))},multipleOf(e,t){return this.check(ht(e,t))}}));function Jh(e){return gl(Zn,e)}var ha=g("ZodBigIntFormat",(e,t)=>{su.init(e,t),Zn.init(e,t)});function Bh(e){return vl(ha,e)}function Wh(e){return yl(ha,e)}var Fd=g("ZodSymbol",(e,t)=>{cu.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Jl(e,r,o,n)});function Gh(e){return bl(Fd,e)}var Vd=g("ZodUndefined",(e,t)=>{uu.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Wl(e,r,o,n)});function qh(e){return $l(Vd,e)}var Kd=g("ZodNull",(e,t)=>{lu.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Bl(e,r,o,n)});function Jd(e){return _l(Kd,e)}var Bd=g("ZodAny",(e,t)=>{du.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Hl(e,r,o,n)});function Hh(){return xl(Bd)}var Wd=g("ZodUnknown",(e,t)=>{pu.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Xl(e,r,o,n)});function Zt(){return kl(Wd)}var Gd=g("ZodNever",(e,t)=>{mu.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,o,n)=>ql(e,r,o,n)});function va(e){return wl(Gd,e)}var qd=g("ZodVoid",(e,t)=>{fu.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Gl(e,r,o,n)});function Xh(e){return Sl(qd,e)}var Vr=g("ZodDate",(e,t)=>{gu.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Yl(e,r,o,n),e.min=(r,o)=>e.check(Te(r,o)),e.max=(r,o)=>e.check(Ae(r,o))},y.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 Yh(e){return Il(Vr,e)}var Hd=g("ZodArray",(e,t)=>{Vt(),vu.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,o,n)=>ld(e,r,o,n),e.element=t.element},{min(e,t){return this.check(it(e,t))},nonempty(e){return this.check(it(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 Kr(e,t){return jl(Hd,e,t)}function Qh(e){let t=e._zod.def.shape;return ya(Object.keys(t))}var Jr=g("ZodObject",(e,t)=>{Vt(),yu.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,o,n)=>dd(e,r,o,n),y.installLazyProp(e,"shape",r=>r._zod.def.shape,!1)},{keyof(){return ya(Object.keys(this._zod.def.shape))},catchall(e){return this.clone(y.mergeDefs(this._zod.def,{catchall:e}))},passthrough(){return this.clone(y.mergeDefs(this._zod.def,{catchall:Zt()}))},loose(){return this.clone(y.mergeDefs(this._zod.def,{catchall:Zt()}))},strict(){return this.clone(y.mergeDefs(this._zod.def,{catchall:va()}))},strip(){return this.clone(y.mergeDefs(this._zod.def,{catchall:void 0}))},extend(e){return y.extend(this,e)},safeExtend(e){return y.safeExtend(this,e)},merge(e){return y.merge(this,e)},pick(e){return y.pick(this,e)},omit(e){return y.omit(this,e)},partial(...e){return y.partial(Wr,this,e[0])},exactPartial(...e){return y.partial($a,this,e[0],"exactPartial")},required(...e){return y.required(_a,this,e[0])}});function ev(e,t){let r={type:"object",shape:e??{},...y.normalizeParams(t)};return new Jr(r)}function tv(e,t){return new Jr({type:"object",shape:e,catchall:va(),...y.normalizeParams(t)})}function nv(e,t){return new Jr({type:"object",shape:e,catchall:Zt(),...y.normalizeParams(t)})}var Br=g("ZodUnion",(e,t)=>{Sr.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Ko(e,r,o,n),e.options=t.options});function Fn(e,t){return new Br({type:"union",options:e,...y.normalizeParams(t)})}var Xd=g("ZodXor",(e,t)=>{Br.init(e,t),bu.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Ko(e,r,o,n),e.options=t.options});function rv(e,t){return new Xd({type:"union",options:e,inclusive:!1,...y.normalizeParams(t)})}var Yd=g("ZodDiscriminatedUnion",(e,t)=>{Br.init(e,t),_u.init(e,t)});function iv(e,t,r){return new Yd({type:"union",options:t,discriminator:e,...y.normalizeParams(r)})}var Qd=g("ZodIntersection",(e,t)=>{xu.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,o,n)=>pd(e,r,o,n)});function ep(e,t){return new Qd({type:"intersection",left:e,right:t})}var tp=g("ZodTuple",(e,t)=>{Vt(),Qi.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,o,n)=>md(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 Wr({type:"optional",innerType:t}))})}});function np(e,t,r){let o=t instanceof U,n=o?r:t,i=o?t:null;return new tp({type:"tuple",items:e,rest:i,...y.normalizeParams(n)})}var Cn=g("ZodRecord",(e,t)=>{Vt(),ku.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,o,n)=>fd(e,r,o,n),e.keyType=t.keyType,e.valueType=t.valueType});function rp(e,t,r){return!t||!t._zod?new Cn({type:"record",keyType:Lr(),valueType:e,...y.normalizeParams(t)}):new Cn({type:"record",keyType:e,valueType:t,...y.normalizeParams(r)})}function ov(e,t,r){return new Cn({type:"record",keyType:e,valueType:t,...y.normalizeParams(r),partial:!0})}function av(e,t,r){return new Cn({type:"record",keyType:e,valueType:t,mode:"loose",...y.normalizeParams(r)})}var ip=g("ZodMap",(e,t)=>{Vt(),wu.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,o,n)=>cd(e,r,o,n),e.keyType=t.keyType,e.valueType=t.valueType,e.min=(...r)=>e.check(Ke(...r)),e.nonempty=r=>e.check(Ke(1,r)),e.max=(...r)=>e.check(vt(...r)),e.size=(...r)=>e.check(Et(...r))});function sv(e,t,r){return new ip({type:"map",keyType:e,valueType:t,...y.normalizeParams(r)})}var op=g("ZodSet",(e,t)=>{Vt(),Su.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,o,n)=>ud(e,r,o,n),e.min=(...r)=>e.check(Ke(...r)),e.nonempty=r=>e.check(Ke(1,r)),e.max=(...r)=>e.check(vt(...r)),e.size=(...r)=>e.check(Et(...r))});function cv(e,t){return new op({type:"set",valueType:e,...y.normalizeParams(t)})}var En=g("ZodEnum",(e,t)=>{Iu.init(e,t),E.init(e,t),e._zod.processJSONSchema=(o,n,i)=>Ql(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 En({...t,checks:[],...y.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 En({...t,checks:[],...y.normalizeParams(n),entries:i})}});function ya(e,t){let r=Array.isArray(e)?Object.fromEntries(e.map(o=>[o,o])):e;return new En({type:"enum",entries:r,...y.normalizeParams(t)})}function uv(e,t){return new En({type:"enum",entries:e,...y.normalizeParams(t)})}var ap=g("ZodLiteral",(e,t)=>{zu.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,o,n)=>ed(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 lv(e,t){return new ap({type:"literal",values:Array.isArray(e)?e:[e],...y.normalizeParams(t)})}var sp=g("ZodFile",(e,t)=>{Pu.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,o,n)=>rd(e,r,o,n),e.min=(r,o)=>e.check(Ke(r,o)),e.max=(r,o)=>e.check(vt(r,o)),e.mime=(r,o)=>e.check(zn(Array.isArray(r)?r:[r],o))});function dv(e){return Al(sp,e)}var cp=g("ZodTransform",(e,t)=>{Vt(),ju.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,o,n)=>sd(e,r,o,n),e._zod.parse=(r,o)=>{if(o.direction==="backward")throw new ft(e.constructor.name);r.addIssue=i=>{if(typeof i=="string")r.issues.push(y.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(y.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 ba(e){return new cp({type:"transform",transform:e})}var Wr=g("ZodOptional",(e,t)=>{eo.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Jo(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function Ft(e){return new Wr({type:"optional",innerType:e})}var $a=g("ZodExactOptional",(e,t)=>{Au.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Jo(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function up(e){return new $a({type:"optional",innerType:e})}var lp=g("ZodNullable",(e,t)=>{Tu.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,o,n)=>gd(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function Zr(e){return new lp({type:"nullable",innerType:e})}function pv(e){return Ft(Zr(e))}var dp=g("ZodDefault",(e,t)=>{Ou.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,o,n)=>yd(e,r,o,n),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function pp(e,t){return new dp({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():y.shallowClone(t)}})}var mp=g("ZodPrefault",(e,t)=>{Nu.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,o,n)=>bd(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function fp(e,t){return new mp({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():y.shallowClone(t)}})}var _a=g("ZodNonOptional",(e,t)=>{Du.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,o,n)=>hd(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function gp(e,t){return new _a({type:"nonoptional",innerType:e,...y.normalizeParams(t)})}var hp=g("ZodSuccess",(e,t)=>{Uu.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,o,n)=>id(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function mv(e){return new hp({type:"success",innerType:e})}var vp=g("ZodCatch",(e,t)=>{Cu.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,o,n)=>$d(e,r,o,n),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function yp(e,t){return new vp({type:"catch",innerType:e,catchValue:typeof t=="function"?t:y.constantCatch(t)})}var bp=g("ZodNaN",(e,t)=>{Eu.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,o,n)=>td(e,r,o,n)});function fv(e){return Pl(bp,e)}var Gr=g("ZodPipe",(e,t)=>{to.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,o,n)=>_d(e,r,o,n),e.in=t.in,e.out=t.out});function Xo(e,t){return new Gr({type:"pipe",in:e,out:t})}var qr=g("ZodCodec",(e,t)=>{Gr.init(e,t),Ir.init(e,t)});function gv(e,t,r){return new qr({type:"pipe",in:e,out:t,transform:r.decode,reverseTransform:r.encode})}function hv(e){let t=e._zod.def;return new qr({type:"pipe",in:t.out,out:t.in,transform:t.reverseTransform,reverseTransform:t.transform})}var $p=g("ZodPreprocess",(e,t)=>{Gr.init(e,t),Ru.init(e,t)}),_p=g("ZodReadonly",(e,t)=>{Mu.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,o,n)=>xd(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function xp(e){return new _p({type:"readonly",innerType:e})}var kp=g("ZodTemplateLiteral",(e,t)=>{Lu.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,o,n)=>nd(e,r,o,n)});function vv(e,t){return new kp({type:"template_literal",parts:e,...y.normalizeParams(t)})}var wp=g("ZodLazy",(e,t)=>{zr.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,o,n)=>wd(e,r,o,n),e.unwrap=()=>e._zod.def.getter()});function Sp(e){return new wp({type:"lazy",getter:e})}var Ip=g("ZodPromise",(e,t)=>{Fu.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,o,n)=>kd(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function yv(e){return new Ip({type:"promise",innerType:e})}var zp=g("ZodFunction",(e,t)=>{Zu.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,o,n)=>ad(e,r,o,n)});function bv(e){return new zp({type:"function",input:Array.isArray(e?.input)?np(e?.input):e?.input??Kr(Zt()),output:e?.output??Zt()})}var Hr=g("ZodCustom",(e,t)=>{Vu.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,o,n)=>od(e,r,o,n)});function $v(e){let t=new q({check:"custom"});return t._zod.check=e,t}function _v(e,t){return Tl(Hr,e??(()=>!0),t)}function Pp(e,t={}){return Ol(Hr,e,t)}function jp(e,t){return Nl(e,t)}var xv=Dl,kv=Ul,Ap=g("ZodInstanceOf",(e,t)=>{Hr.init(e,t)},{properties(e,t){return this.check(In(e,t))}});function wv(e,t={}){let r=new Ap({type:"custom",check:"custom",fn:o=>o instanceof e,abort:!0,...y.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 Sv=(...e)=>Cl({Codec:qr,Boolean:Ln,String:Rn},...e);function Iv(e){let t=Sp(()=>Fn([Lr(e),Ld(),Zd(),Jd(),Kr(t),rp(Lr(),t)]));return t}function zv(e,t){return new $p({type:"pipe",in:ba(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 Jw(e){ne({customError:e})}function Bw(){return ne().customError}var Tp;Tp||(Tp={});var Xr={};et(Xr,{ZodISODate:()=>xt,ZodISODateTime:()=>_t,ZodISODuration:()=>wt,ZodISOTime:()=>kt,date:()=>Gw,datetime:()=>Ww,duration:()=>Hw,time:()=>qw});function Ww(e){return Dr(_t,e)}function Gw(e){return Ur(xt,e)}function qw(e){return Cr(kt,e)}function Hw(e){return Er(wt,e)}var I={...Vn,...Go,iso:Xr},Xw=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 Yw(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 Pv(e,t){return e.map((r,o)=>o<t?r:r.optional())}function Qw(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}function eS(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:Qw(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 tS(e,t){return I.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 Op(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=Op(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=Op(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 nS=new Set(["items","prefixItems","additionalItems","additionalProperties","contains","propertyNames","not","if","then","else","allOf","anyOf","oneOf","unevaluatedItems","unevaluatedProperties","contentSchema"]),rS=new Set(["properties","patternProperties","dependentSchemas","dependencies","$defs","definitions"]);function Yr(e){return typeof e!="object"||e===null?!1:Array.isArray(e)?e.some(Yr):typeof e.$ref=="string"?!0:Object.entries(e).some(([t,r])=>nS.has(t)?Yr(r):!rS.has(t)||typeof r!="object"||r===null?!1:Object.values(r).some(Yr))}function jv(e){return e===1?"element":"elements"}function iS(e,t){return I.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=Op(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 ${jv(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 ${jv(t.maxContains)}`,input:n,continue:!0})}}}).pipe(e)}function Av(e,t){if(e!==!1)return e===void 0||e===!0?I.any():be(e,t)}var oS=/^(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:\.\d+)?(?:Z|[+-](?:[01]\d|2[0-3]):[0-5]\d)$/;function Tv(e,t){if(e.not!==void 0){if(typeof e.not=="object"&&Object.keys(e.not).length===0)return I.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 I.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=eS(n,t),a=be(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 I.null();if(n.length===0)return I.never();if(n.length===1)return I.literal(n[0]);if(n.every(a=>typeof a=="string"))return I.enum(n);let i=n.map(a=>I.literal(a));return i.length<2?i[0]:I.union([i[0],i[1],...i.slice(2)])}if(e.const!==void 0)return I.literal(e.const);let r=e.type;if(Array.isArray(r)){let n=r.map(i=>{let a={...e,type:i};return Tv(a,t)});return n.length===0?I.never():n.length===1?n[0]:I.union(n)}if(!r)return I.any();let o;switch(r){case"string":{let n=I.string();if(e.format){let i=e.format;i==="email"?n=n.check(I.email()):i==="uri"||i==="uri-reference"?n=n.check(I.url()):i==="uuid"||i==="guid"?n=n.check(I.uuid()):i==="date-time"?n=n.check(I.iso.datetime({offset:!0})):i==="date"?n=n.check(I.iso.date()):i==="time"?n=n.check(I.regex(oS)):i==="duration"?n=n.check(I.iso.duration()):i==="hostname"?n=n.check(I.hostname()):i==="ipv4"?n=n.check(I.ipv4()):i==="ipv6"?n=n.check(I.ipv6()):i==="mac"?n=n.check(I.mac()):i==="cidr"?n=n.check(I.cidrv4()):i==="cidr-v6"?n=n.check(I.cidrv6()):i==="base64"?n=n.check(I.base64()):i==="base64url"?n=n.check(I.base64url()):i==="e164"?n=n.check(I.e164()):i==="credit_card"?n=n.check(I.creditCard()):i==="iban"?n=n.check(I.iban()):i==="jwt"?n=n.check(I.jwt()):i==="emoji"?n=n.check(I.emoji()):i==="nanoid"?n=n.check(I.nanoid()):i==="cuid"?n=n.check(I.cuid()):i==="cuid2"?n=n.check(I.cuid2()):i==="ulid"?n=n.check(I.ulid()):i==="xid"?n=n.check(I.xid()):i==="ksuid"&&(n=n.check(I.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"?I.number().int():I.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=I.boolean();break}case"null":{o=I.null();break}case"object":{let n={},i=e.properties||{},a=new Set(e.required||[]),s=typeof e.additionalProperties=="object"?be(e.additionalProperties,t):void 0;for(let[p,f]of Object.entries(i)){let m=be(f,t);le(n,p,a.has(p)?m:m.optional())}if(e.patternProperties){let p=e.patternProperties,f=Object.keys(p),m=[];for(let $ of f){let k=be(p[$],t),P=I.string().regex(new RegExp($));m.push(I.looseRecord(P,k))}let v=[];if(Object.keys(n).length>0&&v.push(I.object(n).passthrough()),v.push(...m),v.length===0)o=I.object({}).passthrough();else if(v.length===1)o=v[0];else{let $=I.intersection(v[0],v[1]);for(let k=2;k<v.length;k++)$=I.intersection($,v[k]);o=$}if(e.additionalProperties===!1){let $=Object.keys(n),k=f.map(S=>new RegExp(S)),P=o;o=o.check(S=>{if(!De(S.value))return;let T=[];for(let z of Object.keys(S.value))$.includes(z)||k.some(C=>C.test(z))||T.push(z);T.length&&S.issues.push({code:"unrecognized_keys",keys:T,input:S.value,inst:P})})}}else{let p=I.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 f=typeof e.propertyNames=="object"&&e.propertyNames.type===void 0?{type:"string",...e.propertyNames}:e.propertyNames;p=be(f,t)}o=tS(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=>be(p,t)),u=Pv(s,a),l=Array.isArray(i)?void 0:Av(i,t),d=I.tuple(u);o=l?d.rest(l):d,typeof e.minItems=="number"&&(o=o.check(I.minLength(e.minItems))),typeof e.maxItems=="number"&&(o=o.check(I.maxLength(e.maxItems)))}else if(Array.isArray(i)){let a=typeof e.minItems=="number"?e.minItems:0,s=i.map(p=>be(p,t)),u=Pv(s,a),l=Av(e.additionalItems,t),d=I.tuple(u);o=l?d.rest(l):d,typeof e.minItems=="number"&&(o=o.check(I.minLength(e.minItems))),typeof e.maxItems=="number"&&(o=o.check(I.maxLength(e.maxItems)))}else if(i!==void 0){let a=be(i,t),s=I.array(a);typeof e.minItems=="number"&&(s=s.min(e.minItems)),typeof e.maxItems=="number"&&(s=s.max(e.maxItems)),o=s}else o=I.array(I.any());(e.uniqueItems===!0||e.contains!==void 0)&&(o=iS(o,{uniqueItems:e.uniqueItems===!0,containsSchema:e.contains!==void 0?be(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 be(e,t){if(typeof e=="boolean")return e?I.any():I.never();let r=Tv(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=>be(l,t)),u=I.union(s);r=o?I.intersection(r,u):u}if(e.oneOf&&Array.isArray(e.oneOf)){let s=e.oneOf.map(l=>be(l,t)),u=I.xor(s);r=o?I.intersection(r,u):u}if(e.allOf&&Array.isArray(e.allOf))if(e.allOf.length===0)r=o?r:I.any();else{let s=o?r:be(e.allOf[0],t),u=o?0:1;for(let l=u;l<e.allOf.length;l++)s=I.intersection(s,be(e.allOf[l],t));r=s}e.nullable===!0&&t.version==="openapi-3.0"&&(r=I.nullable(r)),e.readOnly===!0&&(r=I.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&&!Yr(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&&!Yr(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))Xw.has(s)||le(n,s,e[s]);return Object.keys(n).length>0&&t.registry.add(r,n),e.description&&(r=r.describe(e.description)),r}function Ov(e,t){if(typeof e=="boolean")return e?I.any():I.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=Yw(r,t?.defaultTarget),n=r.$defs||r.definitions||{},i={version:o,defs:n,refs:new Map,processing:new Set,rootSchema:r,registry:t?.registry??de};return be(r,i)}var Nv=Symbol("z.visit/resolving");function Qr(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===Nv)return new zr({type:"lazy",getter:()=>o.get(a)});if(s!==void 0)return s;o.set(a,Nv);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,f={};for(let v of d){let $=n(l[v]);$!==l[v]&&(p=!0),f[v]=$}let m=s.catchall;return s.catchall&&(m=n(s.catchall),m!==s.catchall&&(p=!0)),p?V(a,{...s,shape:f,catchall:m}):a}case"array":{let l=n(s.element);return l===s.element?a:V(a,{...s,element:l})}case"tuple":{let l=s.items,d=!1,p=[];for(let m of l){let v=n(m);v!==m&&(d=!0),p.push(v)}let f=s.rest;return s.rest&&(f=n(s.rest),f!==s.rest&&(d=!0)),d?V(a,{...s,items:p,rest:f}):a}case"record":case"map":{let l=n(s.keyType),d=n(s.valueType);return l===s.keyType&&d===s.valueType?a:V(a,{...s,keyType:l,valueType:d})}case"set":{let l=n(s.valueType);return l===s.valueType?a:V(a,{...s,valueType:l})}case"union":{let l=s.options,d=!1,p=[];for(let f of l){let m=n(f);m!==f&&(d=!0),p.push(m)}return d?V(a,{...s,options:p}):a}case"intersection":{let l=n(s.left),d=n(s.right);return l===s.left&&d===s.right?a:V(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:V(a,{...s,innerType:l})}case"pipe":{let l=n(s.in),d=n(s.out);return l===s.in&&d===s.out?a:V(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:V(a,{...s,input:l,output:d})}case"lazy":{let l=s.getter,{_cachedInner:d,...p}=s;return V(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 Dv(e){return Qr(e,{object:t=>t.partial(),union:t=>{let r=t._zod.def;return r.discriminator===void 0?t:Fn(r.options)}})}function aS(e,t){if(!t?.length)return e;let r=e._zod.def;return V(e,Re(r,{checks:[...r.checks??[],...t]}),{parent:!0})}function Uv(e){return aS(e.out,e.checks)}function sS(e){return e.in._zod.traits.has("$ZodTransform")?Uv(e):e.in}function Cv(e){return Qr(e,{pipe:t=>sS(t._zod.def),default:(t,r)=>r?Ft(t._zod.def.innerType):t,catch:(t,r)=>r?t._zod.def.innerType:t})}function Ev(e){return Qr(e,{pipe:t=>Uv(t._zod.def),prefault:(t,r)=>r?t._zod.def.innerType:t})}var Np={};et(Np,{bigint:()=>dS,boolean:()=>lS,date:()=>pS,number:()=>uS,string:()=>cS});function cS(e){return tl(Rn,e)}function uS(e){return sl(Mn,e)}function lS(e){return fl(Ln,e)}function dS(e){return hl(Zn,e)}function pS(e){return zl(Vr,e)}var Kn=c.string().min(1).max(512).refine(mS,"Invalid path: use segments like notes/plan.md, without .. or a leading /");function mS(e){return/[\u0000-\u001f\u007f\\]/.test(e)?!1:e.split("/").every(r=>r.length>0&&r.length<=255&&r!=="."&&r!=="..")}var ei=c.string().regex(me("message")),H=c.string().regex(me("thread")),ze=c.string().regex(me("project")),Pe=c.string().regex(me("task")),Dp=c.string().regex(me("artifact")),R=c.iso.datetime(),ti=c.enum(["user","agent","system"]),fS=c.object({path:Kn,name:c.string(),size:c.number().int().nonnegative(),contentType:c.string()}),gS=c.object({artifactId:Dp,version:c.number().int().positive(),title:c.string()}),Rv=c.enum(["cloud","local"]),X=c.number().int().nonnegative(),hS=c.object({title:c.string(),harness:c.string(),runtime:Rv,model:c.string().nullable(),durationMs:X,inputTokens:X,outputTokens:X,costMicros:X.nullable()}),vS=c.object({chars:X,limit:X,parts:c.object({instructions:X,skills:X,knowledge:X,brief:X,conversation:X,notes:X,other:X}),droppedMessages:X,droppedNotes:X,cut:c.boolean()}),yS=c.object({model:c.string(),durationMs:X,calls:X,inputTokens:X,cachedInputTokens:X,outputTokens:X,costMicros:X.nullable(),runtime:Rv,computer:c.string().optional(),harness:c.string().optional(),task:hS.optional(),prompt:vS.optional()}),bS=c.enum(["brief","follow_up","reply","relay","answer"]),$S=c.object({kind:bS,threadId:H,fromThreadId:H.optional(),note:c.string()}),xa=8,Bt=c.object({id:ei,projectId:ze,threadId:H.nullable(),authorKind:ti,authorId:c.string().min(1),body:c.string(),attachments:c.array(fS).optional(),artifacts:c.array(gS).optional(),stats:yS.optional(),relay:$S.optional(),clis:c.array(c.string().max(40)).max(xa).optional(),seq:c.number().int().positive(),createdAt:R,editedAt:R.optional()}),_S=c.enum(["working","blocked","review_ready","done","failed"]),xS=c.object({id:c.string().max(40),options:c.array(c.string().max(40)).max(xa),by:c.enum(["person","coordinator"]),reason:c.string().max(300).nullable()}),kS=c.object({cli:c.string().max(40),model:c.string().max(200).nullable(),effort:c.string().max(20).nullable()}),Mv="cloud",wS=c.object({id:c.string().max(60),by:c.enum(["person","auto","coordinator"]),reason:c.string().max(300).nullable().default(null)}),Up=c.enum(["duplicate","misrouted","cancelled"]),SS=c.object({replies:X,usage:c.object({tokens:X,durationMs:X,costMicros:X.nullable()}).nullable(),planMessageId:ei.nullable()}),Cp=c.object({id:H,projectId:ze,rootMessageId:ei,ackMessageId:ei.nullable().default(null),title:c.string(),status:_S,statusText:c.string().nullable(),resolved:c.boolean(),closeReason:Up.nullable().default(null),duplicateOf:H.nullable().default(null),label:c.string().nullable(),cli:xS.nullable().default(null),runner:wS.nullable().default(null),model:kS.nullable().default(null),seenSeq:c.number().int().nonnegative().nullable().default(null),summary:SS.nullable().default(null),createdAt:R,updatedAt:R}),IS=c.enum(["running","done","failed","cancelled"]),Lv=c.object({id:Pe,threadId:H,title:c.string(),harness:c.string(),backend:c.string(),status:IS,prUrl:c.string().nullable(),summary:c.string().nullable(),createdAt:R,finishedAt:R.nullable()}),uN=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()}),Ep=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()}),Zv=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:Ep.optional()}),Rp=c.object({messageId:ei,emoji:c.string().min(1).max(32),authorKind:ti,authorId:c.string().min(1)}),ka=c.enum(["owner","admin","member"]),zS=c.object({working:c.number().int().nonnegative(),waiting:c.number().int().nonnegative()}),PS=c.object({monthMicros:c.number().int().nonnegative(),totalMicros:c.number().int().nonnegative()}),wa=c.enum(["indigo","blue","teal","green","amber","orange","red","pink","purple","gray"]),Sa=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"]),lN=c.object({id:ze,name:c.string().min(1).max(120),role:ka,icon:Sa.nullable().optional(),color:wa.nullable().optional(),createdAt:R,activity:zS.optional(),cost:PS.optional(),pinned:c.boolean().optional()}),dN=c.object({pinned:c.boolean()}),pN=c.object({name:c.string().trim().min(1).max(120)}),mN=c.object({id:c.string(),name:c.string(),role:ka,email:c.string().optional()}),Mp=32e3,jS=c.object({id:c.number().int(),accountLogin:c.string(),accountType:c.enum(["User","Organization"]),accountAvatarUrl:c.string().nullable()}),fN=c.object({configured:c.boolean(),installUrl:c.string().nullable(),installations:c.array(jS)}),gN=c.object({id:c.number().int(),installationId:c.number().int(),fullName:c.string(),defaultBranch:c.string(),private:c.boolean(),description:c.string().nullable()}),hN=c.object({repoId:c.number().int(),installationId:c.number().int(),fullName:c.string(),defaultBranch:c.string(),private:c.boolean(),createdAt:R}),Fv=c.object({repo:c.string(),number:c.number().int(),url:c.string(),threadId:H,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}),AS=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()}),vN=c.object({files:c.array(AS),truncated:c.boolean()}),Vv=c.enum(["merge","squash","rebase"]),yN=c.object({permitted:c.boolean(),blocked:c.enum(["closed","draft","conflict","checks_failed","checks_pending","changes_requested","protected","checking"]).nullable(),methods:c.array(Vv),sha:c.string()}),bN=c.object({method:Vv,sha:c.string().min(1),deleteBranch:c.boolean().default(!1)}),$N=c.object({merged:c.literal(!0),branchDeleted:c.boolean(),branchKept:c.enum(["fork","default","protected","gone","in_use","reopened","failed"]).nullable()}),_N=c.object({installationId:c.number().int().positive(),repoId:c.number().int().positive()});var TS=16e3,OS=16e3,IN=25*1024*1024,Kv=10;var zN=c.object({path:Kn,size:c.number().int().nonnegative(),contentType:c.string(),updatedAt:R,updatedByKind:ti,updatedBy:c.string()}),NS=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"),DS=c.enum(["ok","stale"]),US=c.object({name:NS,description:c.string().max(300),content:c.string().max(OS),updatedAt:R,updatedByKind:ti,updatedBy:c.string(),status:DS.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)}),PN=US.pick({description:!0,content:!0}),jN=c.discriminatedUnion("status",[c.object({status:c.literal("ok")}),c.object({status:c.literal("stale"),reason:c.string().trim().min(1).max(300)})]),CS=c.object({text:c.string().max(TS),updatedAt:R.nullable(),updatedBy:c.string().nullable()}),AN=CS.pick({text:!0}),Jv=c.enum(["files","memory","instructions"]),Bv=c.enum(["auto","on","off"]),TN=c.object({mode:Bv,active:c.boolean(),lastRunAt:R.nullable(),threadsSince:c.number().int().nonnegative(),threadsNeeded:c.number().int().positive(),threadId:c.string().nullable()}),ON=c.object({mode:Bv});var Lp=c.object({id:Dp,projectId:ze,threadId:H.nullable(),title:c.string(),description:c.string().nullable(),version:c.number().int().positive(),createdAt:R,updatedAt:R}),CN=c.object({version:c.number().int().positive(),size:c.number().int().nonnegative(),threadId:H.nullable(),createdAt:R}),EN=c.object({version:c.number().int().positive(),url:c.string().nullable(),expiresAt:R.nullable()}),RN=2*1024*1024;var Zp=c.string().regex(me("routine")),ES=/^(\*|\d+(-\d+)?)(\/\d+)?(,(\*|\d+(-\d+)?)(\/\d+)?)*$/,RS=c.string().trim().refine(e=>{let t=e.split(/\s+/);return t.length===5&&t.every(r=>ES.test(r))},"Expected a five-field cron expression, e.g. 0 9 * * 1-5"),MS=c.string().min(1).max(64).refine(e=>{try{return new Intl.DateTimeFormat("en-US",{timeZone:e}),!0}catch{return!1}},"Unknown time zone"),Fp=c.discriminatedUnion("kind",[c.object({kind:c.literal("cron"),cron:RS,timezone:MS.default("UTC")}),c.object({kind:c.literal("once"),at:R})]),Vp=c.discriminatedUnion("kind",[c.object({kind:c.literal("coordinator")}),c.object({kind:c.literal("thread"),threadId:H})]),Kp=c.object({id:Zp,projectId:ze,name:c.string(),prompt:c.string(),target:Vp,schedule:Fp,paused:c.boolean(),nextRunAt:R.nullable(),lastRunAt:R.nullable(),runCount:c.number().int().nonnegative(),createdBy:c.string(),createdAt:R});var VN=c.object({name:c.string().trim().min(1).max(120),prompt:c.string().trim().min(1).max(8e3),target:Vp.default({kind:"coordinator"}),schedule:Fp}),KN=c.object({name:c.string().trim().min(1).max(120),prompt:c.string().trim().min(1).max(8e3),target:Vp,schedule:Fp,paused:c.boolean()}).partial();var Jp=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 LS=c.string().regex(me("sshHost")),Bp=c.string().regex(/^[a-z0-9][a-z0-9_-]{0,39}$/,"Use lowercase letters, digits, - and _ (up to 40)."),Ia=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."),Wv=c.string().trim().regex(/^[A-Za-z0-9_][A-Za-z0-9_.-]{0,63}$/,"Enter the user name on the server."),Gv=c.enum(["ask","off"]),XN=c.string().max(16e3).regex(/^(?:ssh|ecdsa|sk)-[\w@.-]+ [A-Za-z0-9+/=]+(?: .*)?$/),qv=c.string().max(200).regex(/^SHA256:[A-Za-z0-9+/=]+$/),ZS=c.object({id:LS,projectId:ze,alias:Bp,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:Gv,testedAt:R.nullable(),createdAt:R}),FS=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}),YN=c.object({hosts:c.array(ZS),history:c.array(FS)}),QN=c.object({runnerId:c.string(),alias:Bp,host:Ia,port:c.number().int().min(1).max(65535).default(22),user:Wv,existingKey:c.string().min(1).max(1024).optional()}),eD=c.object({rule:Gv}),tD=c.object({hostKey:c.string().min(1).max(16e3)}),Hv=c.object({type:c.string().max(60),key:c.string().max(16e3),fingerprint:qv}),Xv=c.object({path:c.string().max(1024),name:c.string().max(255),type:c.string().max(60),fingerprint:qv,comment:c.string().max(500)}),Yv=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()}),Qv=300*1e3,ey=200*1024,za=c.object({projectId:ze,alias:Bp}),Wp=za.extend({host:Ia,port:c.number().int().min(1).max(65535),user:Wv,hostKey:c.string().min(1).max(16e3)});var ry=2,at=c.string().regex(me("runner")),Be=c.enum(["claude","codex","antigravity","opencode","hermes","cursor","muse","kimi"]);var iy=c.object({path:c.string().min(1).max(1024),name:c.string().max(255)}),VS=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(VS).max(8),at:R});var JS=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 BS=c.object({id:Be,version:c.string().max(200).nullable(),limits:KS.optional().catch(void 0),models:c.array(JS).max(100).optional().catch(void 0)}),WS=c.enum(["folders","cancel","agent","agent-clis","connectors","skills","project-folders","files","settings","update","models","github-token","git-token","steer","steer-claude","ssh","stats"]),GS=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))})]),qS=c.enum(["read","edit","auto","full"]),qp=c.object({access:qS,worktrees:c.boolean(),autoUpdate:c.boolean(),remote:c.boolean()}),oy=qp.omit({remote:!0}).partial(),HS=c.enum(["service","app","manual"]),Gp=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}),ay=c.object({version:c.string().max(50),hostname:c.string().max(255),platform:c.string().max(50),folders:c.array(iy).max(200),clis:c.array(c.unknown()).max(10).transform(e=>e.flatMap(t=>{let r=BS.safeParse(t);return r.success?[r.data]:[]})),features:c.array(c.string().max(50)).max(20).default([]).transform(e=>e.filter(t=>WS.safeParse(t).success)),settings:qp.optional().catch(void 0),updates:HS.optional().catch(void 0),update:Gp.optional().catch(void 0)}),Wt=c.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),ja=c.object({at:R,cpu:c.object({percent:c.number().min(0).max(100).optional(),cores:c.number().int().min(1).max(1024)}),memory:c.object({total:Wt,available:Wt}),swap:c.object({total:Wt,used:Wt}).optional(),disk:c.object({total:Wt,free:Wt}).optional(),tasks:c.number().int().nonnegative().max(1e3),runnerMemory:Wt.optional()}),Pa=1e5,Q=c.string().min(1).max(64),XS=c.object({name:c.string().max(255),path:c.string().max(1024)}),YS=c.object({path:c.string().max(1024),parent:c.string().max(1024).nullable(),home:c.string().max(1024),dirs:c.array(XS).max(1e3)}),ty=c.object({inputTokens:c.number().int().nonnegative(),outputTokens:c.number().int().nonnegative(),model:c.string().max(200).optional()}),Hp=512*1024,QS=c.object({path:c.string().max(4096),size:c.number().int().nonnegative(),data:c.string().max(Math.ceil(Hp/3)*4+4),truncated:c.boolean()}),eI=c.object({model:c.string().min(1).max(200).optional(),effort:c.string().min(1).max(20).optional()}),ny=c.object({token:c.string().min(20).max(4096),expiresAt:R,repos:c.array(c.string().regex(/^[\w.-]+\/[\w.-]+$/).max(200)).max(100)}),sD=c.discriminatedUnion("type",[ay.extend({type:c.literal("hello"),protocol:c.number().int().positive(),running:c.array(Pe).max(100).default([]),interrupted:c.array(Pe).max(100).default([]),stats:ja.optional().catch(void 0)}),c.object({type:c.literal("task.progress"),taskId:Pe,text:c.string().max(2e3),usage:ty.optional(),agent:Ep.optional(),ms:c.number().nonnegative().optional()}),c.object({type:c.literal("task.done"),taskId:Pe,ok:c.boolean(),usage:ty.optional(),result:c.string().max(Pa),cancelled:c.boolean().optional()}),c.object({type:c.literal("ping"),stats:ja.optional().catch(void 0)}),c.object({type:c.literal("task.folders"),taskId:Pe,folders:c.array(c.string().min(1).max(1024)).max(60)}),YS.extend({type:c.literal("dirs"),requestId:Q}),c.object({type:c.literal("folders"),requestId:Q,folders:c.array(iy).max(200)}),c.object({type:c.literal("request.failed"),requestId:Q,message:c.string().max(500)}),QS.extend({type:c.literal("file"),requestId:Q}),c.object({type:c.literal("settings"),requestId:Q,settings:qp}),c.object({type:c.literal("update.accepted"),requestId:Q,update:Gp}),c.object({type:c.literal("update.status"),update:Gp.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(Xv).max(100)}),c.object({type:c.literal("ssh.hostkeylist"),requestId:Q,keys:c.array(Hv).max(10)}),Yv.extend({type:c.literal("ssh.result"),requestId:Q})]),sy=c.discriminatedUnion("type",[c.object({type:c.literal("welcome"),runnerId:at,name:c.string()}),c.object({type:c.literal("task.start"),taskId:Pe,threadId:H,folder:c.string().min(1).max(1024),cli:Be,prompt:c.string().min(1).max(Pa),model:eI.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(GS).max(30).optional(),skills:c.object({path:c.string().regex(/^\/api\/[\w/-]+$/).max(300)}).optional(),resume:c.object({after:Pe,prompt:c.string().min(1).max(Pa)}).optional()}).optional(),github:ny.optional()}),c.object({type:c.literal("task.github"),taskId:Pe,github:ny}),c.object({type:c.literal("task.steer"),requestId:Q,taskId:Pe,text:c.string().min(1).max(Pa)}),c.object({type:c.literal("task.cancel"),taskId:Pe}),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:H.optional()}),c.object({type:c.literal("settings.set"),requestId:Q,settings:oy}),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)}),za.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:Ia,port:c.number().int().min(1).max(65535)}),c.object({type:c.literal("ssh.test"),requestId:Q,target:Wp}),c.object({type:c.literal("ssh.run"),requestId:Q,target:Wp,command:c.string().min(1).max(2e4)}),za.extend({type:c.literal("ssh.forget"),requestId:Q})]),tI=ay.extend({id:at,name:c.string(),version:c.string().nullable(),online:c.boolean(),lastSeenAt:R.nullable(),createdAt:R,stats:ja.optional()}),cD=c.object({name:c.string().trim().min(1).max(80).optional(),settings:oy.optional()}),uD=c.object({now:c.boolean().default(!1)}),lD=c.object({runners:c.array(tI),latestVersion:c.string().nullable()}),dD=c.object({code:c.string(),expiresAt:R}),pD=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("")}),cy=c.object({runner:c.object({id:at,name:c.string()}),token:c.string()}),mD=c.object({projectId:ze,runnerId:at,runnerName:c.string(),path:c.string(),folders:c.array(c.string()).default([]),cli:Be,online:c.boolean(),isDefault:c.boolean().default(!0),stats:ja.optional()}),fD=c.object({path:c.string().trim().min(1).max(1024)}),gD=c.object({runnerId:at,path:c.string().min(1).max(1024),cli:Be,add:c.boolean().optional()}),hD=c.object({path:c.string().min(1).max(1024),runnerId:at.optional()}),vD=c.object({runnerId:at});function uy(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 nI=200,rI=c.object({threadId:H.nullable(),hasEarlier:c.boolean()});var zD=c.discriminatedUnion("type",[c.object({type:c.literal("message.send"),clientId:c.string().max(64).optional(),threadId:H.nullable().default(null),body:c.string().trim().max(Mp),attachments:c.array(Kn).max(Kv).default([]),clis:c.array(Be).max(xa).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(Mp)}),c.object({type:c.literal("thread.resolve"),threadId:H,resolved:c.boolean(),reason:Up.optional()}),c.object({type:c.literal("thread.cli"),threadId:H,cli:Be.nullable()}),c.object({type:c.literal("thread.runner"),threadId:H,runnerId:c.union([at,c.literal(Mv)]).nullable()}),c.object({type:c.literal("thread.model"),threadId:H,cli:Be,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(nI).optional()})]),PD=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(Cp).default([]),reactions:c.array(Rp).default([]),artifacts:c.array(Lp).default([]),routines:c.array(Kp).default([]),goal:Jp.nullable().optional(),windows:c.array(rI).optional(),reset:c.boolean().optional(),lastSeq:c.number().int().nonnegative().optional()}),c.object({type:c.literal("thread.updated"),thread:Cp}),c.object({type:c.literal("reaction.added"),reaction:Rp}),c.object({type:c.literal("artifact.updated"),artifact:Lp}),c.object({type:c.literal("routine.updated"),routine:Kp}),c.object({type:c.literal("routine.deleted"),routineId:Zp}),c.object({type:c.literal("goal.updated"),goal:Jp.nullable()}),c.object({type:c.literal("agent.activity"),threadId:H.nullable(),active:c.boolean(),label:c.string().max(200).optional()}),c.object({type:c.literal("knowledge.changed"),kind:Jv}),c.object({type:c.literal("workspace.changed")}),c.object({type:c.literal("task.updated"),task:Lv}),c.object({type:c.literal("task.output"),taskId:Pe,threadId:H,lines:c.array(Zv)}),c.object({type:c.literal("pr.updated"),pullRequest:Fv}),c.object({type:c.literal("error"),code:c.string(),message:c.string()})]);var TD=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 DD=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 ni=c.enum(["fireworks","anthropic","openai"]),ZD=c.object({id:ni,name:c.string(),defaultModel:c.string(),serverKey:c.boolean()}),FD=c.object({id:c.string(),provider:ni,label:c.string(),hint:c.string(),scope:c.enum(["user","instance"]),createdAt:c.iso.datetime()}),VD=c.object({provider:ni,label:c.string().trim().min(1).max(80),key:c.string().trim().min(8).max(500),scope:c.enum(["user","instance"]).default("user")}),ly=c.enum(["auto","local","cloud"]),dy=c.enum(["opencode","claude","codex"]),iI=c.object({model:c.string().trim().min(1).max(200).nullable(),effort:c.string().trim().min(1).max(20).nullable()}),py=c.partialRecord(Be,iI),KD=c.object({name:c.string(),provider:ni.nullable(),model:c.string().nullable(),keyId:c.string().nullable(),taskTarget:ly,icon:Sa.nullable().default(null),color:wa.nullable().default(null),cloudCli:dy.default("opencode"),cliModels:py.default({})}),JD=c.object({name:c.string().trim().min(1).max(120).optional(),provider:ni.nullable().optional(),model:c.string().trim().max(200).nullable().optional(),keyId:c.string().nullable().optional(),taskTarget:ly.optional(),icon:Sa.nullable().optional(),color:wa.nullable().optional(),cloudCli:dy.optional(),cliModels:py.optional()}),my=c.enum(["admin","member"]),BD=c.object({id:c.string(),projectId:c.string(),projectName:c.string(),email:c.string(),role:my,invitedBy:c.string(),createdAt:c.iso.datetime()}),WD=c.object({email:c.email().trim().toLowerCase(),role:my.default("member")}),GD=c.object({role:ka}),oI=c.enum(["admin","user"]),qD=c.enum(["computer","decision"]),HD=c.object({id:c.string(),name:c.string(),email:c.string(),role:oI,onboarded:c.boolean().optional(),tips:c.array(c.string()).optional()}),aI=c.object({signUpEnabled:c.boolean()}),sI=c.enum(["api","agent","cron","web","desktop","mobile"]),XD=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()}),YD=c.object({id:c.string(),source:sI,where:c.string(),name:c.string(),message:c.string(),stack:c.string().nullable(),count:c.number().int(),firstSeenAt:c.number(),lastSeenAt:c.number()}),QD=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()}),e4=aI.partial();var fy=c.string().regex(me("notification")),cI=c.enum(["done","ready","decision","blocked","failed"]),o4=c.object({id:fy,projectId:ze,threadId:H.nullable(),kind:cI,title:c.string(),body:c.string(),url:c.string(),readAt:R.nullable(),createdAt:R}),a4=c.object({email:c.boolean(),push:c.boolean()}),s4=c.object({webPushKey:c.string().nullable(),email:c.boolean()}),uI=[/^fcm\.googleapis\.com$/,/^updates\.push\.services\.mozilla\.com$/,/^web\.push\.apple\.com$/,/^[a-z0-9-]+\.notify\.windows\.com$/];function lI(e){try{let t=new URL(e);return t.protocol==="https:"&&uI.some(r=>r.test(t.hostname))}catch{return!1}}var c4=c.discriminatedUnion("kind",[c.object({kind:c.literal("webpush"),endpoint:c.url().max(2048).refine(lI,"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)})]),u4=c.union([c.object({ids:c.array(fy).min(1).max(200)}),c.object({all:c.literal(!0)})]);var dI=new RegExp(me("thread").source.slice(1,-1)),g4=new RegExp(`^#(${dI.source})$`);var pI=c.enum(["http","stdio"]),mI=c.enum(["user","project"]),Yp=c.enum(["cloud","local","both"]),fI=c.enum(["unknown","ok","error","needs_auth"]),gI=c.enum(["none","headers","oauth"]),gy=c.string().regex(/^[a-z][a-z0-9_-]{0,31}$/).refine(e=>e!=="myrel","That name is taken by Myrel's own tools."),hI=c.object({name:c.string(),description:c.string().optional()}),vI=/^[A-Za-z_][\w-]{0,99}$/,yI=/^[A-Za-z_][A-Za-z0-9_]{0,99}$/,hy=(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}),vy=hy(vI,"Header","letters, digits, - and _"),bI=hy(yI,"Variable","letters, digits and _"),y4=c.object({id:c.string(),name:c.string(),slug:c.string(),scope:mI,transport:pI,url:c.string().nullable(),auth:gI,command:c.string().nullable(),args:c.array(c.string()),runsOn:Yp,secretNames:c.array(c.string()),enabled:c.boolean(),status:fI,lastError:c.string().nullable(),tools:c.array(hI),canEdit:c.boolean(),createdAt:c.iso.datetime(),official:c.object({id:c.string(),title:c.string(),iconUrl:c.string().nullable()}).nullable().default(null)}),Xp=c.string().trim().min(1).max(60),b4=c.discriminatedUnion("transport",[c.object({transport:c.literal("http"),name:Xp,slug:gy.optional(),url:c.url({protocol:/^https$/}).max(2e3),auth:c.enum(["headers","oauth"]).default("headers"),headers:vy.default({})}),c.object({transport:c.literal("stdio"),name:Xp,slug:gy.optional(),command:c.string().trim().min(1).max(200),args:c.array(c.string().max(2e3)).max(50).default([]),env:bI.default({}),runsOn:Yp.default("both")})]),$4=c.object({name:Xp.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:Yp.optional(),secrets:vy.optional()});var _4=c.object({authorizeUrl:c.url()});var $I=["developer","productivity","communication","design","data","sales","finance","search","ai","other"],yy=c.enum($I);var _I=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:yy,official:c.boolean()}),x4=c.object({connectors:c.array(_I),nextOffset:c.number().nullable(),syncedAt:c.iso.datetime().nullable(),categories:c.array(c.object({id:yy,count:c.number()}))}),xI=[{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"}],k4=xI.map(e=>e.id);var kI=c.enum(["user","project"]),wI=c.string().max(64).regex(/^[a-z0-9]+(-[a-z0-9]+)*$/,"Use lowercase letters, digits and hyphens, like pdf-forms."),by=c.string().trim().min(1).max(1024),SI=c.string().min(1).max(300).regex(/^[\w@+=,.~ -]+(\/[\w@+=,.~ -]+)*$/,"Invalid file path.").refine(e=>!e.split("/").some(t=>t==="."||t===".."),"Invalid file path."),$y={files:200,bytes:5*1024*1024,fileBytes:1024*1024};var II=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()})]),zI=c.object({path:c.string(),size:c.number().int().nonnegative()}),PI=c.object({id:c.string(),name:c.string(),description:c.string(),scope:kI,source:II,enabled:c.boolean(),files:c.array(zI),size:c.number().int().nonnegative(),canEdit:c.boolean(),createdAt:c.iso.datetime(),updatedAt:c.iso.datetime()}),I4=PI.extend({skillMd:c.string()}),jI=c.object({path:SI,content:c.string().max(Math.ceil($y.fileBytes*4/3)+4)}),z4=c.discriminatedUnion("kind",[c.object({kind:c.literal("write"),name:wI,description:by,instructions:c.string().max(1e5)}),c.object({kind:c.literal("upload"),files:c.array(jI).min(1).max($y.files)}),c.object({kind:c.literal("github"),source:c.string().trim().min(3).max(500),skill:c.string().max(64).optional()})]),P4=c.object({error:c.literal("choose_skill"),skills:c.array(c.object({name:c.string(),description:c.string(),path:c.string()}))}),j4=c.object({enabled:c.boolean().optional(),description:by.optional(),instructions:c.string().max(1e5).optional()}),A4=c.object({skills:c.array(c.object({name:c.string(),files:c.array(c.object({path:c.string(),content:c.string()}))}))});var T4=c.object({on:c.boolean()});var AI=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)}),TI=c.enum(["open","connected","dismissed"]),D4=c.object({id:c.string(),reason:c.string().min(1).max(400),offers:c.array(AI).min(1).max(3),state:TI.default("open"),connected:c.string().optional(),signIn:c.boolean().optional()});var U4=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()}),C4=c.object({authorizeUrl:c.string().optional(),connected:c.boolean()});var OI=/^(?:\/(?:usr\/)?(?:local\/)?bin\/)?(?:ba|z|da|k)?sh\s+-l?c\s+(\S[\s\S]*)$/;function Jn(e){let t=OI.exec(e.trim());return t?NI(t[1])??e:e}function NI(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 DI,readFile as UI,rename as CI,writeFile as EI}from"node:fs/promises";import{homedir as ky}from"node:os";import{dirname as RI,join as _y}from"node:path";var wy="MYREL_MCP_BRIDGE";function MI(e=ky()){return{mcp:_y(e,".gemini","config","mcp_config.json"),settings:_y(e,".gemini","antigravity-cli","settings.json")}}function ri(){let e=process.argv[1],t=!e||/\$bunfs|~BUN/.test(e);return{command:process.execPath,args:t?[]:[e]}}async function Sy(e,t=ky()){let r=MI(t),o=ri(),n={command:o.command,args:[...o.args,"mcp-bridge"]};await xy(r.mcp,a=>{let s=Qp(a.mcpServers)?a.mcpServers:{};return JSON.stringify(s[e])===JSON.stringify(n)?!1:(a.mcpServers={...s,[e]:n},!0)});let i=`mcp(${e}/*)`;await xy(r.settings,a=>{let s=Qp(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 xy(e,t){let r=await UI(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(!Qp(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 DI(RI(e),{recursive:!0});let n=`${e}.myrel-${process.pid}`;await EI(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 qg(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;qg(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 Hg=new Set(["type","properties","required","additionalProperties"]),Wg=["oneOf","anyOf"];function Gg(e){let t=e.additionalProperties;return t===void 0||t===!1||typeof t!="object"||t===null?null:Object.keys(t).length?t:null}function El(e){let t=[];for(let i of e){if(typeof i!="object"||i.type!=="object")return null;for(let a in i)if(!Hg.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]??Gg(l);d!=null&&(s.some(p=>JSON.stringify(p)===JSON.stringify(d))||s.push(d))}let u=s.length===1?s[0]:El(s)??{allOf:s};le(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=Gg(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 Uw(e){let t=e.allOf;if(!Array.isArray(t)||t.length<2)return;for(let n of Hg)if(n in e)return;let r=t.filter(n=>Wg.some(i=>Array.isArray(n[i]))),o=null;if(!r.length)o=El(t);else{let n=r[0],i=Wg.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=>El([...a,u]));if(s.some(u=>!u))return;o={[i]:s}}o&&(delete e.allOf,Rr(e,o))}function $t(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 m=e.seen.get(p),v=m.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)):Rr(l,v),Rr(l,d),s._zod.parent===p)for(let k in l)k==="$ref"||k==="allOf"||k in d||delete l[k];if(v.$ref&&m.def)for(let k in l)k==="$ref"||k==="allOf"||k in m.def&&JSON.stringify(l[k])===JSON.stringify(m.def[k])&&delete l[k]}let f=s._zod.parent;if(f&&f!==p){o(f);let m=e.seen.get(f);if(m?.schema.$ref&&(l.$ref=m.schema.$ref,m.def))for(let v in l)v==="$ref"||v==="allOf"||v in m.def&&JSON.stringify(l[v])===JSON.stringify(m.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())qg(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)??[])Uw(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)}Rr(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,le(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:Nn(t,"input",e.processors),output:Nn(t,"output",e.processors)}},enumerable:!1,writable:!1}),s}catch{throw new Error("Error converting schema to JSON.")}}function ye(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 ye(o.element,r);if(o.type==="set")return ye(o.valueType,r);if(o.type==="lazy")return ye(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 ye(o.innerType,r);if(o.type==="intersection")return ye(o.left,r)||ye(o.right,r);if(o.type==="record"||o.type==="map")return ye(o.keyType,r)||ye(o.valueType,r);if(o.type==="pipe")return e._zod.traits.has("$ZodCodec")?!0:ye(o.in,r)||ye(o.out,r);if(o.type==="object"){for(let n in o.shape)if(ye(o.shape[n],r))return!0;return!1}if(o.type==="union"){for(let n of o.options)if(ye(n,r))return!0;return!1}if(o.type==="tuple"){for(let n of o.items)if(ye(n,r))return!0;return!!(o.rest&&ye(o.rest,r))}return!1}var Rl=(e,t={})=>r=>{let o=yt({...r,processors:t});return J(e,o),bt(o,e),$t(o,e)},Nn=(e,t,r={})=>o=>{let{libraryOptions:n,target:i}=o??{},a=yt({...n??{},target:i,io:t,processors:r});return J(e,a),bt(a,e),$t(a,e)};var Dn=(e,t,r)=>{(e[t]===void 0||r>e[t])&&(e[t]=r)},Un=(e,t,r)=>{(e[t]===void 0||r<e[t])&&(e[t]=r)},Xg=(e,t)=>{Dn(e,"minimum",t),Un(e,"maximum",t)},th=(e,t)=>{e.multipleOf??(e.multipleOf=[]),e.multipleOf.includes(t)||e.multipleOf.push(t)},nh=(e,t)=>{e.patterns??(e.patterns=new Set),e.patterns.add(t)},rh=(e,t)=>{e.mime=e.mime?e.mime.filter(r=>t.includes(r)):[...t]},ih=(e,t)=>{e.format=t,t.includes("int")&&(e.isInt=!0)},Yg=(e,t)=>Dn(e,"minimum",t.minimum),Qg=(e,t)=>Un(e,"maximum",t.maximum),eh=e=>(t,r)=>{ih(t,r.format);let[o,n]=e[r.format];Dn(t,"minimum",o),Un(t,"maximum",n)},Cw={greater_than:(e,t)=>Dn(e,t.inclusive?"minimum":"exclusiveMinimum",t.value),less_than:(e,t)=>Un(e,t.inclusive?"maximum":"exclusiveMaximum",t.value),multiple_of:(e,t)=>th(e,t.value),number_format:eh(or),bigint_format:eh(ar),min_length:Yg,max_length:Qg,length_equals:(e,t)=>Xg(e,t.length),min_size:Yg,max_size:Qg,size_equals:(e,t)=>Xg(e,t.size),string_format:(e,t)=>{ih(e,t.format),t.pattern&&nh(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)=>rh(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)Cw[i._zod.def.check]?.(t,i._zod.def);let n=e._zod.bag;n.minimum!==void 0&&Dn(t,"minimum",n.minimum),n.exclusiveMinimum!==void 0&&Dn(t,"exclusiveMinimum",n.exclusiveMinimum),n.maximum!==void 0&&Un(t,"maximum",n.maximum),n.exclusiveMaximum!==void 0&&Un(t,"exclusiveMaximum",n.exclusiveMaximum),n.multipleOf!==void 0&&th(t,n.multipleOf),n.format!==void 0&&(t.format??(t.format=n.format),n.format.includes("int")&&(t.isInt=!0)),n.mime&&rh(t,n.mime);for(let i of n.patterns??[])nh(t,i);return t}var Ew={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},Rw=new Map([[Bi,Ks],[kr,Js]]),oh=e=>Rw.get(e)??e,Zl=(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=Ew[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(oh);p.length===1?n.pattern=p[0].source:p.length>1&&(n.allOf=[...p.map(f=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:f.source}))])}},Fl=(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),f=typeof u=="number"&&u<=(a??Number.POSITIVE_INFINITY),m=t.target==="draft-04"||t.target==="openapi-3.0";if(p?m?(n.minimum=l,n.exclusiveMinimum=!0):n.exclusiveMinimum=l:typeof i=="number"&&(n.minimum=i),f?m?(n.maximum=u,n.exclusiveMaximum=!0):n.exclusiveMaximum=u:typeof a=="number"&&(n.maximum=a),s){let v=new Set;for(let P of s)Number.isFinite(P)&&P!==0?v.add(Math.abs(P)):oe(e,t,n,o,`A multipleOf divisor of ${P} cannot be represented in JSON Schema`);let[$,...k]=v;$!==void 0&&(n.multipleOf=$),k.length&&(n.allOf=[...n.allOf??[],...k.map(P=>({multipleOf:P}))])}},Vl=(e,t,r,o)=>{r.type="boolean"},Kl=(e,t,r,o)=>{oe(e,t,r,o,"BigInt cannot be represented in JSON Schema")},Jl=(e,t,r,o)=>{oe(e,t,r,o,"Symbols cannot be represented in JSON Schema")},Bl=(e,t,r,o)=>{t.target==="openapi-3.0"?(r.type="string",r.nullable=!0,r.enum=[null]):r.type="null"},Wl=(e,t,r,o)=>{oe(e,t,r,o,"Undefined cannot be represented in JSON Schema")},Gl=(e,t,r,o)=>{oe(e,t,r,o,"Void cannot be represented in JSON Schema")},ql=(e,t,r,o)=>{r.not={}},Hl=(e,t,r,o)=>{},Xl=(e,t,r,o)=>{},Yl=(e,t,r,o)=>{oe(e,t,r,o,"Date cannot be represented in JSON Schema")},Ql=(e,t,r,o)=>{let n=e._zod.def,i=on(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},ed=(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},td=(e,t,r,o)=>{oe(e,t,r,o,"NaN cannot be represented in JSON Schema")},nd=(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},rd=(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})))},id=(e,t,r,o)=>{r.type="boolean"},od=(e,t,r,o)=>{oe(e,t,r,o,"Custom types cannot be represented in JSON Schema")},ad=(e,t,r,o)=>{oe(e,t,r,o,"Function types cannot be represented in JSON Schema")},sd=(e,t,r,o)=>{oe(e,t,r,o,"Transforms cannot be represented in JSON Schema")},cd=(e,t,r,o)=>{oe(e,t,r,o,"Map cannot be represented in JSON Schema")},ud=(e,t,r,o)=>{oe(e,t,r,o,"Set cannot be represented in JSON Schema")},ld=(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=J(i.element,t,{...o,path:[...o.path,"items"]})};function Mr(e){let t=e._zod.def;return t.type==="pipe"&&t.in._zod.traits.has("$ZodTransform")?Mr(t.out):t.type==="catch"?Mr(t.innerType):e._zod.optin}var dd=(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)le(n.properties,l,J(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"?Mr(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=J(i.catchall,t,{...o,path:[...o.path,"additionalProperties"]})):t.io==="output"&&(n.additionalProperties=!1)},Ko=(e,t,r,o)=>{let n=e._zod.def,i=n.inclusive===!1,a=n.options.map((s,u)=>J(s,t,{...o,path:[...o.path,i?"oneOf":"anyOf",u]}));i?r.oneOf=a:r.anyOf=a},pd=(e,t,r,o)=>{let n=e._zod.def,i=J(n.left,t,{...o,path:[...o.path,"allOf",0]}),a=J(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)},md=(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(($,k)=>J($,t,{...o,path:[...o.path,a,k]})),l=i.rest?J(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 $=i.items[d-1];if(!(t.io==="input"?Mr($)!==void 0:$._zod.optout==="optional"))break;d--}let p=i.items.length,f=!i.rest;t.target==="draft-2020-12"?(n.prefixItems=u,f?n.items=!1:l&&(n.items=l),d>0&&(n.minItems=d),f&&(n.maxItems=p)):t.target==="openapi-3.0"?(n.items={anyOf:u},l&&n.items.anyOf.push(l),d>0&&(n.minItems=d),f&&(n.maxItems=p)):(n.items=u,f?n.additionalItems=!1:l&&(n.additionalItems=l),d>0&&(n.minItems=d),f&&(n.maxItems=p));let{minimum:m,maximum:v}=ae(e);typeof m=="number"&&(n.minItems=m),typeof v=="number"&&(n.maxItems=v)};function Ml(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 $=Ml(e,v,r);return $===v?t:$}for(let v of["anyOf","oneOf"]){let $=t[v];if(!Array.isArray($))continue;let k=$.map(P=>Ml(e,P,r));k.some((P,S)=>P!==$[S])&&(t={...t,[v]:k})}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:f,...m}=t;return m.enum?m.enum=m.enum.map(v=>typeof v=="number"?String(v):v):typeof m.const=="number"&&(m.const=String(m.const)),n&&(m.type="string",i||(m.pattern=(o.includes("number")?rt:hr).source)),m}var Ll=new WeakMap;function Mw(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 Ll.get(e)??[]){let n=e.seen.get(o),i=(n?.def??n?.schema)?.propertyNames;if(!i||i===!0||r.has(i))continue;let a=Ml(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 fd=(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=J(i.valueType,t,{...o,path:[...o.path,"patternProperties","*"]});n.patternProperties={};for(let p of s)le(n.patternProperties,oh(p).source,d)}else{if(t.target==="draft-07"||t.target==="draft-2020-12"){n.propertyNames=J(i.keyType,t,{...o,path:[...o.path,"propertyNames"]});let d=Ll.get(t);d||(d=[],Ll.set(t,d),t.deferred.push(()=>Mw(t))),d.push(e)}n.additionalProperties=J(i.valueType,t,{...o,path:[...o.path,"additionalProperties"]})}let u=a._zod.values,l=t.io==="input"&&Mr(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))}},gd=(e,t,r,o)=>{let n=e._zod.def,i=J(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"}]},hd=(e,t,r,o)=>{let n=e._zod.def;J(n.innerType,t,o);let i=t.seen.get(e);i.ref=n.innerType},vd=Symbol();function ah(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"),vd):JSON.parse(a)}var yd=(e,t,r,o)=>{let n=e._zod.def;J(n.innerType,t,o);let i=t.seen.get(e);i.ref=n.innerType;let a=ah(n.defaultValue,e,t,r,o);a!==vd&&(r.default=a)},bd=(e,t,r,o)=>{let n=e._zod.def;J(n.innerType,t,o);let i=t.seen.get(e);if(i.ref=n.innerType,t.io!=="input")return;let a=ah(n.defaultValue,e,t,r,o);a!==vd&&(r._prefault=a)},$d=(e,t,r,o)=>{let n=e._zod.def;J(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},_d=(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;J(a,t,o);let s=t.seen.get(e);s.ref=a},xd=(e,t,r,o)=>{let n=e._zod.def;J(n.innerType,t,o);let i=t.seen.get(e);i.ref=n.innerType,r.readOnly=!0},kd=(e,t,r,o)=>{let n=e._zod.def;J(n.innerType,t,o);let i=t.seen.get(e);i.ref=n.innerType},Jo=(e,t,r,o)=>{let n=e._zod.def;J(n.innerType,t,o);let i=t.seen.get(e);i.ref=n.innerType},wd=(e,t,r,o)=>{let n=e._zod.innerType;J(n,t,o);let i=t.seen.get(e);i.ref=n},Vo={string:Zl,number:Fl,boolean:Vl,bigint:Kl,symbol:Jl,null:Bl,undefined:Wl,void:Gl,never:ql,any:Hl,unknown:Xl,date:Yl,enum:Ql,literal:ed,nan:td,template_literal:nd,file:rd,success:id,custom:od,function:ad,transform:sd,map:cd,set:ud,array:ld,object:dd,union:Ko,intersection:pd,tuple:md,record:fd,nullable:gd,nonoptional:hd,default:yd,prefault:bd,catch:$d,pipe:_d,readonly:xd,promise:kd,optional:Jo,lazy:wd};function Bo(e,t){if("_idmap"in e){let o=e,n=yt({...t,processors:Vo}),i={};for(let u of o._idmap.entries()){let[l,d]=u;J(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;bt(n,d),le(a,l,$t(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=yt({...t,processors:Vo});return J(e,r),bt(r,e),$t(r,e)}var Wo=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=yt({processors:Vo,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 J(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,bt(this.ctx,t);let o=$t(this.ctx,t),{"~standard":n,...i}=o;return i}};var sh={};var Vn={};et(Vn,{ZodAny:()=>Bd,ZodArray:()=>Hd,ZodBase64:()=>pa,ZodBase64URL:()=>ma,ZodBigInt:()=>Zn,ZodBigIntFormat:()=>ha,ZodBoolean:()=>Ln,ZodCIDRv4:()=>la,ZodCIDRv6:()=>da,ZodCUID:()=>ra,ZodCUID2:()=>ia,ZodCatch:()=>vp,ZodCodec:()=>qr,ZodCreditCard:()=>Rd,ZodCustom:()=>Hr,ZodCustomStringFormat:()=>Kt,ZodDate:()=>Vr,ZodDefault:()=>dp,ZodDiscriminatedUnion:()=>Yd,ZodE164:()=>fa,ZodEmail:()=>Qo,ZodEmoji:()=>ta,ZodEnum:()=>En,ZodExactOptional:()=>$a,ZodFile:()=>sp,ZodFunction:()=>zp,ZodGUID:()=>ea,ZodIBAN:()=>Md,ZodIPv4:()=>ca,ZodIPv6:()=>ua,ZodISODate:()=>xt,ZodISODateTime:()=>_t,ZodISODuration:()=>wt,ZodISOTime:()=>kt,ZodInstanceOf:()=>Ap,ZodIntersection:()=>Qd,ZodJWT:()=>ga,ZodKSUID:()=>sa,ZodLazy:()=>wp,ZodLiteral:()=>ap,ZodMAC:()=>Ed,ZodMap:()=>ip,ZodNaN:()=>bp,ZodNanoID:()=>na,ZodNever:()=>Gd,ZodNonOptional:()=>_a,ZodNull:()=>Kd,ZodNullable:()=>lp,ZodNumber:()=>Mn,ZodNumberFormat:()=>Jt,ZodObject:()=>Jr,ZodOptional:()=>Wr,ZodPipe:()=>Gr,ZodPrefault:()=>mp,ZodPreprocess:()=>$p,ZodPromise:()=>Ip,ZodReadonly:()=>_p,ZodRecord:()=>Cn,ZodSet:()=>op,ZodString:()=>Rn,ZodStringFormat:()=>G,ZodSuccess:()=>hp,ZodSymbol:()=>Fd,ZodTemplateLiteral:()=>kp,ZodTransform:()=>cp,ZodTuple:()=>tp,ZodType:()=>E,ZodULID:()=>oa,ZodURL:()=>Fr,ZodUUID:()=>Je,ZodUndefined:()=>Vd,ZodUnion:()=>Br,ZodUnknown:()=>Wd,ZodVoid:()=>qd,ZodXID:()=>aa,ZodXor:()=>Xd,_ZodString:()=>Yo,_default:()=>pp,_function:()=>bv,any:()=>Hh,array:()=>Kr,base64:()=>Ah,base64url:()=>Th,bigint:()=>Jh,boolean:()=>Zd,catch:()=>yp,check:()=>$v,cidrv4:()=>Ph,cidrv6:()=>jh,codec:()=>gv,creditCard:()=>Nh,cuid:()=>$h,cuid2:()=>_h,currencyCode:()=>Mh,custom:()=>_v,date:()=>Yh,describe:()=>xv,discriminatedUnion:()=>iv,e164:()=>Oh,email:()=>lh,emoji:()=>yh,enum:()=>ya,exactOptional:()=>up,file:()=>dv,float32:()=>Zh,float64:()=>Fh,function:()=>bv,guid:()=>dh,hash:()=>Lh,hex:()=>Rh,hostname:()=>Eh,httpUrl:()=>vh,iban:()=>Dh,instanceof:()=>wv,int:()=>Ho,int32:()=>Vh,int64:()=>Bh,intersection:()=>ep,invertCodec:()=>hv,ipv4:()=>Sh,ipv6:()=>zh,json:()=>Iv,jwt:()=>Uh,keyof:()=>Qh,ksuid:()=>wh,lazy:()=>Sp,literal:()=>lv,looseObject:()=>nv,looseRecord:()=>av,mac:()=>Ih,map:()=>sv,meta:()=>kv,nan:()=>fv,nanoid:()=>bh,nativeEnum:()=>uv,never:()=>va,nonoptional:()=>gp,null:()=>Jd,nullable:()=>Zr,nullish:()=>pv,number:()=>Ld,object:()=>ev,optional:()=>Ft,partialRecord:()=>ov,pipe:()=>Xo,prefault:()=>fp,preprocess:()=>zv,promise:()=>yv,readonly:()=>xp,record:()=>rp,refine:()=>Pp,set:()=>cv,strictObject:()=>tv,string:()=>Lr,stringFormat:()=>Ch,stringbool:()=>Sv,success:()=>mv,superRefine:()=>jp,symbol:()=>Gh,templateLiteral:()=>vv,transform:()=>ba,tuple:()=>np,uint32:()=>Kh,uint64:()=>Wh,ulid:()=>xh,undefined:()=>qh,union:()=>Fn,unknown:()=>Zt,url:()=>hh,uuid:()=>ph,uuidv4:()=>mh,uuidv6:()=>fh,uuidv7:()=>gh,void:()=>Xh,xid:()=>kh,xor:()=>rv});var Go={};et(Go,{endsWith:()=>Sn,gt:()=>Ve,gte:()=>Te,includes:()=>kn,length:()=>Mt,lowercase:()=>_n,lt:()=>Fe,lte:()=>Ae,maxLength:()=>Rt,maxSize:()=>vt,mime:()=>zn,minLength:()=>it,minSize:()=>Ke,multipleOf:()=>ht,negative:()=>Mo,nonnegative:()=>Zo,nonpositive:()=>Lo,normalize:()=>Pn,overwrite:()=>Le,positive:()=>Ro,properties:()=>In,property:()=>Fo,regex:()=>$n,size:()=>Et,slugify:()=>On,startsWith:()=>wn,toLowerCase:()=>An,toUpperCase:()=>Tn,trim:()=>jn,uppercase:()=>xn});var ch=new WeakSet([Object.prototype,Error.prototype]);function qo(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 uh=(e,t)=>{ws.init(e,t),e.name="ZodError";let r=Object.getPrototypeOf(e);ch.has(r)||(ch.add(r),qo(r,"format",o=>n=>pr(o,n)),qo(r,"flatten",o=>n=>dr(o,n)),qo(r,"addIssue",o=>n=>{o.issues.push(n),o.message=JSON.stringify(o.issues,an,2)}),qo(r,"addIssues",o=>n=>{o.issues.push(...n),o.message=JSON.stringify(o.issues,an,2)}),Object.defineProperty(r,"isEmpty",{configurable:!0,enumerable:!1,get(){return this.issues.length===0}}))},Zw=g("ZodError",uh),Ie=g("ZodError",uh,void 0,{Parent:Error});var Sd=dn(Ie),Id=pn(Ie),zd=mn(Ie),Pd=fn(Ie),jd=ki(Ie),Ad=wi(Ie),Td=Si(Ie),Od=Ii(Ie),Nd=zi(Ie),Dd=Pi(Ie),Ud=ji(Ie),Cd=Ai(Ie);function Vw(){ce.localeError||ne(co())}function Vt(){ce.memoizer||ne({memoizer:Ar()})}var E=g("ZodType",(e,t)=>(Vw(),U.init(e,t),e.def=t,e.type=t.type,e),{check(...e){let t=this.def;return this.clone(y.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 V(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},refine(e,t){return this.check(Pp(e,t))},superRefine(e,t){return this.check(jp(e,t))},overwrite(e){return this.check(Le(e))},optional(){return Ft(this)},exactOptional(){return up(this)},nullable(){return Zr(this)},nullish(){return Ft(Zr(this))},nonoptional(e){return gp(this,e)},array(){return Kr(this)},or(e){return Fn([this,e])},and(e){return ep(this,e)},transform(e){return Xo(this,ba(e))},default(e){return pp(this,e)},prefault(e){return fp(this,e)},catch(e){return yp(this,e)},pipe(e){return Xo(this,e)},readonly(){return xp(this)},describe(e){let t=this.clone();return de.add(t,{description:e}),t},meta(...e){if(e.length===0)return de.get(this);let t=this.clone();return de.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 y.hide(this,"~standard",{...Zi(this),jsonSchema:{input:Nn(this,"input"),output:Nn(this,"output")}})},set"~standard"(e){y.own(this,"~standard",e)},parse:function e(t,r){return Sd(this,t,r,{callee:e})},parseAsync:async function e(t,r){return await Id(this,t,r,{callee:e})},safeParse(e,t){return zd(this,e,t)},async safeParseAsync(e,t){return Pd(this,e,t)},get spa(){return this?.safeParseAsync},set spa(e){y.own(this,"spa",e)},validate(e,t){return mr(this,e,t)},validateAsync(e,t){return fr(this,e,t)},encode:function e(t,r){return jd(this,t,r,{callee:e})},decode:function e(t,r){return Ad(this,t,r,{callee:e})},encodeAsync:async function e(t,r){return await Td(this,t,r,{callee:e})},decodeAsync:async function e(t,r){return await Od(this,t,r,{callee:e})},safeEncode(e,t){return Nd(this,e,t)},safeDecode(e,t){return Dd(this,e,t)},async safeEncodeAsync(e,t){return Ud(this,e,t)},async safeDecodeAsync(e,t){return Cd(this,e,t)},toJSONSchema(e){return Rl(this,{})(e)},get description(){return de.get(this)?.description},get _def(){return this._zod.def}}),Yo=g("_ZodString",(e,t)=>{Nt.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Zl(e,r,o,n)},y.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(kn(...e))},startsWith(...e){return this.check(wn(...e))},endsWith(...e){return this.check(Sn(...e))},min(...e){return this.check(it(...e))},max(...e){return this.check(Rt(...e))},length(...e){return this.check(Mt(...e))},nonempty(...e){return this.check(it(1,...e))},lowercase(e){return this.check(_n(e))},uppercase(e){return this.check(xn(e))},trim(){return this.check(jn())},normalize(...e){return this.check(Pn(...e))},toLowerCase(){return this.check(An())},toUpperCase(){return this.check(Tn())},slugify(){return this.check(On())}})),Rn=g("ZodString",(e,t)=>{Nt.init(e,t),Yo.init(e,t)},{email(e){return this.check(vo(Qo,e))},url(e){return this.check(Nr(Fr,e))},jwt(e){return this.check(Eo(ga,e))},emoji(e){return this.check(ko(ta,e))},guid(e){return this.check(yo(ea,e))},uuid(e){return this.check(bo(Je,e))},uuidv4(e){return this.check($o(Je,e))},uuidv6(e){return this.check(_o(Je,e))},uuidv7(e){return this.check(xo(Je,e))},nanoid(e){return this.check(wo(na,e))},cuid(e){return this.check(So(ra,e))},cuid2(e){return this.check(Io(ia,e))},ulid(e){return this.check(zo(oa,e))},base64(e){return this.check(Do(pa,e))},base64url(e){return this.check(Uo(ma,e))},xid(e){return this.check(Po(aa,e))},ksuid(e){return this.check(jo(sa,e))},ipv4(e){return this.check(Ao(ca,e))},ipv6(e){return this.check(To(ua,e))},cidrv4(e){return this.check(Oo(la,e))},cidrv6(e){return this.check(No(da,e))},e164(e){return this.check(Co(fa,e))},datetime(e){return this.check(Dr(_t,e))},date(e){return this.check(Ur(xt,e))},time(e){return this.check(Cr(kt,e))},duration(e){return this.check(Er(wt,e))}});function Lr(e){return el(Rn,e)}var G=g("ZodStringFormat",(e,t)=>{K.init(e,t),Yo.init(e,t)}),_t=g("ZodISODateTime",(e,t)=>{Kc.init(e,t),G.init(e,t)}),xt=g("ZodISODate",(e,t)=>{Jc.init(e,t),G.init(e,t)}),kt=g("ZodISOTime",(e,t)=>{Bc.init(e,t),G.init(e,t)}),wt=g("ZodISODuration",(e,t)=>{Wc.init(e,t),G.init(e,t)}),Qo=g("ZodEmail",(e,t)=>{Nc.init(e,t),G.init(e,t)});function lh(e){return vo(Qo,e)}var ea=g("ZodGUID",(e,t)=>{Tc.init(e,t),G.init(e,t)});function dh(e){return yo(ea,e)}var Je=g("ZodUUID",(e,t)=>{Oc.init(e,t),G.init(e,t)});function ph(e){return bo(Je,e)}function mh(e){return $o(Je,e)}function fh(e){return _o(Je,e)}function gh(e){return xo(Je,e)}var Fr=g("ZodURL",(e,t)=>{Cc.init(e,t),G.init(e,t)});function hh(e){return Nr(Fr,e)}function vh(e){return Nr(Fr,{protocol:gr,hostname:Ws,...y.normalizeParams(e)})}var ta=g("ZodEmoji",(e,t)=>{Ec.init(e,t),G.init(e,t)});function yh(e){return ko(ta,e)}var na=g("ZodNanoID",(e,t)=>{Rc.init(e,t),G.init(e,t)});function bh(e){return wo(na,e)}var ra=g("ZodCUID",(e,t)=>{Mc.init(e,t),G.init(e,t)});function $h(e){return So(ra,e)}var ia=g("ZodCUID2",(e,t)=>{Lc.init(e,t),G.init(e,t)});function _h(e){return Io(ia,e)}var oa=g("ZodULID",(e,t)=>{Zc.init(e,t),G.init(e,t)});function xh(e){return zo(oa,e)}var aa=g("ZodXID",(e,t)=>{Fc.init(e,t),G.init(e,t)});function kh(e){return Po(aa,e)}var sa=g("ZodKSUID",(e,t)=>{Vc.init(e,t),G.init(e,t)});function wh(e){return jo(sa,e)}var ca=g("ZodIPv4",(e,t)=>{Gc.init(e,t),G.init(e,t)});function Sh(e){return Ao(ca,e)}var Ed=g("ZodMAC",(e,t)=>{Hc.init(e,t),G.init(e,t)});function Ih(e){return nl(Ed,e)}var ua=g("ZodIPv6",(e,t)=>{qc.init(e,t),G.init(e,t)});function zh(e){return To(ua,e)}var la=g("ZodCIDRv4",(e,t)=>{Xc.init(e,t),G.init(e,t)});function Ph(e){return Oo(la,e)}var da=g("ZodCIDRv6",(e,t)=>{Yc.init(e,t),G.init(e,t)});function jh(e){return No(da,e)}var pa=g("ZodBase64",(e,t)=>{Qc.init(e,t),G.init(e,t)});function Ah(e){return Do(pa,e)}var ma=g("ZodBase64URL",(e,t)=>{eu.init(e,t),G.init(e,t)});function Th(e){return Uo(ma,e)}var fa=g("ZodE164",(e,t)=>{tu.init(e,t),G.init(e,t)});function Oh(e){return Co(fa,e)}var Rd=g("ZodCreditCard",(e,t)=>{nu.init(e,t),G.init(e,t)});function Nh(e){return rl(Rd,e)}var Md=g("ZodIBAN",(e,t)=>{ru.init(e,t),G.init(e,t)});function Dh(e){return il(Md,e)}var ga=g("ZodJWT",(e,t)=>{iu.init(e,t),G.init(e,t)});function Uh(e){return Eo(ga,e)}var Kt=g("ZodCustomStringFormat",(e,t)=>{ou.init(e,t),G.init(e,t)});function Ch(e,t,r={}){return Lt(Kt,e,t,r)}function Eh(e){return Lt(Kt,"hostname",Bs,e)}function Rh(e){return Lt(Kt,"hex",sc,e)}function Mh(e){return Lt(Kt,"currency_code",qs,e)}function Lh(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 Mn=g("ZodNumber",(e,t)=>{Xi.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Fl(e,r,o,n),e.isFinite=!0},y.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(Ve(e,t))},gte(e,t){return this.check(Te(e,t))},min(e,t){return this.check(Te(e,t))},lt(e,t){return this.check(Fe(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(Ho(e))},safe(e){return this.check(Ho(e))},positive(e){return this.check(Ve(0,e))},nonnegative(e){return this.check(Te(0,e))},negative(e){return this.check(Fe(0,e))},nonpositive(e){return this.check(Ae(0,e))},multipleOf(e,t){return this.check(ht(e,t))},step(e,t){return this.check(ht(e,t))},finite(){return this}}));function Ld(e){return al(Mn,e)}var Jt=g("ZodNumberFormat",(e,t)=>{au.init(e,t),Mn.init(e,t)});function Ho(e){return cl(Jt,e)}function Zh(e){return ul(Jt,e)}function Fh(e){return ll(Jt,e)}function Vh(e){return dl(Jt,e)}function Kh(e){return pl(Jt,e)}var Ln=g("ZodBoolean",(e,t)=>{wr.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Vl(e,r,o,n)});function Zd(e){return ml(Ln,e)}var Zn=g("ZodBigInt",(e,t)=>{Yi.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Kl(e,r,o,n)},y.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(Te(e,t))},min(e,t){return this.check(Te(e,t))},gt(e,t){return this.check(Ve(e,t))},lt(e,t){return this.check(Fe(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(Ve(BigInt(0),e))},negative(e){return this.check(Fe(BigInt(0),e))},nonpositive(e){return this.check(Ae(BigInt(0),e))},nonnegative(e){return this.check(Te(BigInt(0),e))},multipleOf(e,t){return this.check(ht(e,t))}}));function Jh(e){return gl(Zn,e)}var ha=g("ZodBigIntFormat",(e,t)=>{su.init(e,t),Zn.init(e,t)});function Bh(e){return vl(ha,e)}function Wh(e){return yl(ha,e)}var Fd=g("ZodSymbol",(e,t)=>{cu.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Jl(e,r,o,n)});function Gh(e){return bl(Fd,e)}var Vd=g("ZodUndefined",(e,t)=>{uu.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Wl(e,r,o,n)});function qh(e){return $l(Vd,e)}var Kd=g("ZodNull",(e,t)=>{lu.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Bl(e,r,o,n)});function Jd(e){return _l(Kd,e)}var Bd=g("ZodAny",(e,t)=>{du.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Hl(e,r,o,n)});function Hh(){return xl(Bd)}var Wd=g("ZodUnknown",(e,t)=>{pu.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Xl(e,r,o,n)});function Zt(){return kl(Wd)}var Gd=g("ZodNever",(e,t)=>{mu.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,o,n)=>ql(e,r,o,n)});function va(e){return wl(Gd,e)}var qd=g("ZodVoid",(e,t)=>{fu.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Gl(e,r,o,n)});function Xh(e){return Sl(qd,e)}var Vr=g("ZodDate",(e,t)=>{gu.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Yl(e,r,o,n),e.min=(r,o)=>e.check(Te(r,o)),e.max=(r,o)=>e.check(Ae(r,o))},y.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 Yh(e){return Il(Vr,e)}var Hd=g("ZodArray",(e,t)=>{Vt(),vu.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,o,n)=>ld(e,r,o,n),e.element=t.element},{min(e,t){return this.check(it(e,t))},nonempty(e){return this.check(it(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 Kr(e,t){return jl(Hd,e,t)}function Qh(e){let t=e._zod.def.shape;return ya(Object.keys(t))}var Jr=g("ZodObject",(e,t)=>{Vt(),yu.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,o,n)=>dd(e,r,o,n),y.installLazyProp(e,"shape",r=>r._zod.def.shape,!1)},{keyof(){return ya(Object.keys(this._zod.def.shape))},catchall(e){return this.clone(y.mergeDefs(this._zod.def,{catchall:e}))},passthrough(){return this.clone(y.mergeDefs(this._zod.def,{catchall:Zt()}))},loose(){return this.clone(y.mergeDefs(this._zod.def,{catchall:Zt()}))},strict(){return this.clone(y.mergeDefs(this._zod.def,{catchall:va()}))},strip(){return this.clone(y.mergeDefs(this._zod.def,{catchall:void 0}))},extend(e){return y.extend(this,e)},safeExtend(e){return y.safeExtend(this,e)},merge(e){return y.merge(this,e)},pick(e){return y.pick(this,e)},omit(e){return y.omit(this,e)},partial(...e){return y.partial(Wr,this,e[0])},exactPartial(...e){return y.partial($a,this,e[0],"exactPartial")},required(...e){return y.required(_a,this,e[0])}});function ev(e,t){let r={type:"object",shape:e??{},...y.normalizeParams(t)};return new Jr(r)}function tv(e,t){return new Jr({type:"object",shape:e,catchall:va(),...y.normalizeParams(t)})}function nv(e,t){return new Jr({type:"object",shape:e,catchall:Zt(),...y.normalizeParams(t)})}var Br=g("ZodUnion",(e,t)=>{Sr.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Ko(e,r,o,n),e.options=t.options});function Fn(e,t){return new Br({type:"union",options:e,...y.normalizeParams(t)})}var Xd=g("ZodXor",(e,t)=>{Br.init(e,t),bu.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Ko(e,r,o,n),e.options=t.options});function rv(e,t){return new Xd({type:"union",options:e,inclusive:!1,...y.normalizeParams(t)})}var Yd=g("ZodDiscriminatedUnion",(e,t)=>{Br.init(e,t),_u.init(e,t)});function iv(e,t,r){return new Yd({type:"union",options:t,discriminator:e,...y.normalizeParams(r)})}var Qd=g("ZodIntersection",(e,t)=>{xu.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,o,n)=>pd(e,r,o,n)});function ep(e,t){return new Qd({type:"intersection",left:e,right:t})}var tp=g("ZodTuple",(e,t)=>{Vt(),Qi.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,o,n)=>md(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 Wr({type:"optional",innerType:t}))})}});function np(e,t,r){let o=t instanceof U,n=o?r:t,i=o?t:null;return new tp({type:"tuple",items:e,rest:i,...y.normalizeParams(n)})}var Cn=g("ZodRecord",(e,t)=>{Vt(),ku.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,o,n)=>fd(e,r,o,n),e.keyType=t.keyType,e.valueType=t.valueType});function rp(e,t,r){return!t||!t._zod?new Cn({type:"record",keyType:Lr(),valueType:e,...y.normalizeParams(t)}):new Cn({type:"record",keyType:e,valueType:t,...y.normalizeParams(r)})}function ov(e,t,r){return new Cn({type:"record",keyType:e,valueType:t,...y.normalizeParams(r),partial:!0})}function av(e,t,r){return new Cn({type:"record",keyType:e,valueType:t,mode:"loose",...y.normalizeParams(r)})}var ip=g("ZodMap",(e,t)=>{Vt(),wu.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,o,n)=>cd(e,r,o,n),e.keyType=t.keyType,e.valueType=t.valueType,e.min=(...r)=>e.check(Ke(...r)),e.nonempty=r=>e.check(Ke(1,r)),e.max=(...r)=>e.check(vt(...r)),e.size=(...r)=>e.check(Et(...r))});function sv(e,t,r){return new ip({type:"map",keyType:e,valueType:t,...y.normalizeParams(r)})}var op=g("ZodSet",(e,t)=>{Vt(),Su.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,o,n)=>ud(e,r,o,n),e.min=(...r)=>e.check(Ke(...r)),e.nonempty=r=>e.check(Ke(1,r)),e.max=(...r)=>e.check(vt(...r)),e.size=(...r)=>e.check(Et(...r))});function cv(e,t){return new op({type:"set",valueType:e,...y.normalizeParams(t)})}var En=g("ZodEnum",(e,t)=>{Iu.init(e,t),E.init(e,t),e._zod.processJSONSchema=(o,n,i)=>Ql(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 En({...t,checks:[],...y.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 En({...t,checks:[],...y.normalizeParams(n),entries:i})}});function ya(e,t){let r=Array.isArray(e)?Object.fromEntries(e.map(o=>[o,o])):e;return new En({type:"enum",entries:r,...y.normalizeParams(t)})}function uv(e,t){return new En({type:"enum",entries:e,...y.normalizeParams(t)})}var ap=g("ZodLiteral",(e,t)=>{zu.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,o,n)=>ed(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 lv(e,t){return new ap({type:"literal",values:Array.isArray(e)?e:[e],...y.normalizeParams(t)})}var sp=g("ZodFile",(e,t)=>{Pu.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,o,n)=>rd(e,r,o,n),e.min=(r,o)=>e.check(Ke(r,o)),e.max=(r,o)=>e.check(vt(r,o)),e.mime=(r,o)=>e.check(zn(Array.isArray(r)?r:[r],o))});function dv(e){return Al(sp,e)}var cp=g("ZodTransform",(e,t)=>{Vt(),ju.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,o,n)=>sd(e,r,o,n),e._zod.parse=(r,o)=>{if(o.direction==="backward")throw new ft(e.constructor.name);r.addIssue=i=>{if(typeof i=="string")r.issues.push(y.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(y.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 ba(e){return new cp({type:"transform",transform:e})}var Wr=g("ZodOptional",(e,t)=>{eo.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Jo(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function Ft(e){return new Wr({type:"optional",innerType:e})}var $a=g("ZodExactOptional",(e,t)=>{Au.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Jo(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function up(e){return new $a({type:"optional",innerType:e})}var lp=g("ZodNullable",(e,t)=>{Tu.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,o,n)=>gd(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function Zr(e){return new lp({type:"nullable",innerType:e})}function pv(e){return Ft(Zr(e))}var dp=g("ZodDefault",(e,t)=>{Ou.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,o,n)=>yd(e,r,o,n),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function pp(e,t){return new dp({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():y.shallowClone(t)}})}var mp=g("ZodPrefault",(e,t)=>{Nu.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,o,n)=>bd(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function fp(e,t){return new mp({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():y.shallowClone(t)}})}var _a=g("ZodNonOptional",(e,t)=>{Du.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,o,n)=>hd(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function gp(e,t){return new _a({type:"nonoptional",innerType:e,...y.normalizeParams(t)})}var hp=g("ZodSuccess",(e,t)=>{Uu.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,o,n)=>id(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function mv(e){return new hp({type:"success",innerType:e})}var vp=g("ZodCatch",(e,t)=>{Cu.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,o,n)=>$d(e,r,o,n),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function yp(e,t){return new vp({type:"catch",innerType:e,catchValue:typeof t=="function"?t:y.constantCatch(t)})}var bp=g("ZodNaN",(e,t)=>{Eu.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,o,n)=>td(e,r,o,n)});function fv(e){return Pl(bp,e)}var Gr=g("ZodPipe",(e,t)=>{to.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,o,n)=>_d(e,r,o,n),e.in=t.in,e.out=t.out});function Xo(e,t){return new Gr({type:"pipe",in:e,out:t})}var qr=g("ZodCodec",(e,t)=>{Gr.init(e,t),Ir.init(e,t)});function gv(e,t,r){return new qr({type:"pipe",in:e,out:t,transform:r.decode,reverseTransform:r.encode})}function hv(e){let t=e._zod.def;return new qr({type:"pipe",in:t.out,out:t.in,transform:t.reverseTransform,reverseTransform:t.transform})}var $p=g("ZodPreprocess",(e,t)=>{Gr.init(e,t),Ru.init(e,t)}),_p=g("ZodReadonly",(e,t)=>{Mu.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,o,n)=>xd(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function xp(e){return new _p({type:"readonly",innerType:e})}var kp=g("ZodTemplateLiteral",(e,t)=>{Lu.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,o,n)=>nd(e,r,o,n)});function vv(e,t){return new kp({type:"template_literal",parts:e,...y.normalizeParams(t)})}var wp=g("ZodLazy",(e,t)=>{zr.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,o,n)=>wd(e,r,o,n),e.unwrap=()=>e._zod.def.getter()});function Sp(e){return new wp({type:"lazy",getter:e})}var Ip=g("ZodPromise",(e,t)=>{Fu.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,o,n)=>kd(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function yv(e){return new Ip({type:"promise",innerType:e})}var zp=g("ZodFunction",(e,t)=>{Zu.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,o,n)=>ad(e,r,o,n)});function bv(e){return new zp({type:"function",input:Array.isArray(e?.input)?np(e?.input):e?.input??Kr(Zt()),output:e?.output??Zt()})}var Hr=g("ZodCustom",(e,t)=>{Vu.init(e,t),E.init(e,t),e._zod.processJSONSchema=(r,o,n)=>od(e,r,o,n)});function $v(e){let t=new q({check:"custom"});return t._zod.check=e,t}function _v(e,t){return Tl(Hr,e??(()=>!0),t)}function Pp(e,t={}){return Ol(Hr,e,t)}function jp(e,t){return Nl(e,t)}var xv=Dl,kv=Ul,Ap=g("ZodInstanceOf",(e,t)=>{Hr.init(e,t)},{properties(e,t){return this.check(In(e,t))}});function wv(e,t={}){let r=new Ap({type:"custom",check:"custom",fn:o=>o instanceof e,abort:!0,...y.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 Sv=(...e)=>Cl({Codec:qr,Boolean:Ln,String:Rn},...e);function Iv(e){let t=Sp(()=>Fn([Lr(e),Ld(),Zd(),Jd(),Kr(t),rp(Lr(),t)]));return t}function zv(e,t){return new $p({type:"pipe",in:ba(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 Jw(e){ne({customError:e})}function Bw(){return ne().customError}var Tp;Tp||(Tp={});var Xr={};et(Xr,{ZodISODate:()=>xt,ZodISODateTime:()=>_t,ZodISODuration:()=>wt,ZodISOTime:()=>kt,date:()=>Gw,datetime:()=>Ww,duration:()=>Hw,time:()=>qw});function Ww(e){return Dr(_t,e)}function Gw(e){return Ur(xt,e)}function qw(e){return Cr(kt,e)}function Hw(e){return Er(wt,e)}var I={...Vn,...Go,iso:Xr},Xw=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 Yw(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 Pv(e,t){return e.map((r,o)=>o<t?r:r.optional())}function Qw(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}function eS(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:Qw(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 tS(e,t){return I.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 Op(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=Op(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=Op(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 nS=new Set(["items","prefixItems","additionalItems","additionalProperties","contains","propertyNames","not","if","then","else","allOf","anyOf","oneOf","unevaluatedItems","unevaluatedProperties","contentSchema"]),rS=new Set(["properties","patternProperties","dependentSchemas","dependencies","$defs","definitions"]);function Yr(e){return typeof e!="object"||e===null?!1:Array.isArray(e)?e.some(Yr):typeof e.$ref=="string"?!0:Object.entries(e).some(([t,r])=>nS.has(t)?Yr(r):!rS.has(t)||typeof r!="object"||r===null?!1:Object.values(r).some(Yr))}function jv(e){return e===1?"element":"elements"}function iS(e,t){return I.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=Op(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 ${jv(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 ${jv(t.maxContains)}`,input:n,continue:!0})}}}).pipe(e)}function Av(e,t){if(e!==!1)return e===void 0||e===!0?I.any():be(e,t)}var oS=/^(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:\.\d+)?(?:Z|[+-](?:[01]\d|2[0-3]):[0-5]\d)$/;function Tv(e,t){if(e.not!==void 0){if(typeof e.not=="object"&&Object.keys(e.not).length===0)return I.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 I.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=eS(n,t),a=be(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 I.null();if(n.length===0)return I.never();if(n.length===1)return I.literal(n[0]);if(n.every(a=>typeof a=="string"))return I.enum(n);let i=n.map(a=>I.literal(a));return i.length<2?i[0]:I.union([i[0],i[1],...i.slice(2)])}if(e.const!==void 0)return I.literal(e.const);let r=e.type;if(Array.isArray(r)){let n=r.map(i=>{let a={...e,type:i};return Tv(a,t)});return n.length===0?I.never():n.length===1?n[0]:I.union(n)}if(!r)return I.any();let o;switch(r){case"string":{let n=I.string();if(e.format){let i=e.format;i==="email"?n=n.check(I.email()):i==="uri"||i==="uri-reference"?n=n.check(I.url()):i==="uuid"||i==="guid"?n=n.check(I.uuid()):i==="date-time"?n=n.check(I.iso.datetime({offset:!0})):i==="date"?n=n.check(I.iso.date()):i==="time"?n=n.check(I.regex(oS)):i==="duration"?n=n.check(I.iso.duration()):i==="hostname"?n=n.check(I.hostname()):i==="ipv4"?n=n.check(I.ipv4()):i==="ipv6"?n=n.check(I.ipv6()):i==="mac"?n=n.check(I.mac()):i==="cidr"?n=n.check(I.cidrv4()):i==="cidr-v6"?n=n.check(I.cidrv6()):i==="base64"?n=n.check(I.base64()):i==="base64url"?n=n.check(I.base64url()):i==="e164"?n=n.check(I.e164()):i==="credit_card"?n=n.check(I.creditCard()):i==="iban"?n=n.check(I.iban()):i==="jwt"?n=n.check(I.jwt()):i==="emoji"?n=n.check(I.emoji()):i==="nanoid"?n=n.check(I.nanoid()):i==="cuid"?n=n.check(I.cuid()):i==="cuid2"?n=n.check(I.cuid2()):i==="ulid"?n=n.check(I.ulid()):i==="xid"?n=n.check(I.xid()):i==="ksuid"&&(n=n.check(I.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"?I.number().int():I.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=I.boolean();break}case"null":{o=I.null();break}case"object":{let n={},i=e.properties||{},a=new Set(e.required||[]),s=typeof e.additionalProperties=="object"?be(e.additionalProperties,t):void 0;for(let[p,f]of Object.entries(i)){let m=be(f,t);le(n,p,a.has(p)?m:m.optional())}if(e.patternProperties){let p=e.patternProperties,f=Object.keys(p),m=[];for(let $ of f){let k=be(p[$],t),P=I.string().regex(new RegExp($));m.push(I.looseRecord(P,k))}let v=[];if(Object.keys(n).length>0&&v.push(I.object(n).passthrough()),v.push(...m),v.length===0)o=I.object({}).passthrough();else if(v.length===1)o=v[0];else{let $=I.intersection(v[0],v[1]);for(let k=2;k<v.length;k++)$=I.intersection($,v[k]);o=$}if(e.additionalProperties===!1){let $=Object.keys(n),k=f.map(S=>new RegExp(S)),P=o;o=o.check(S=>{if(!De(S.value))return;let T=[];for(let z of Object.keys(S.value))$.includes(z)||k.some(C=>C.test(z))||T.push(z);T.length&&S.issues.push({code:"unrecognized_keys",keys:T,input:S.value,inst:P})})}}else{let p=I.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 f=typeof e.propertyNames=="object"&&e.propertyNames.type===void 0?{type:"string",...e.propertyNames}:e.propertyNames;p=be(f,t)}o=tS(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=>be(p,t)),u=Pv(s,a),l=Array.isArray(i)?void 0:Av(i,t),d=I.tuple(u);o=l?d.rest(l):d,typeof e.minItems=="number"&&(o=o.check(I.minLength(e.minItems))),typeof e.maxItems=="number"&&(o=o.check(I.maxLength(e.maxItems)))}else if(Array.isArray(i)){let a=typeof e.minItems=="number"?e.minItems:0,s=i.map(p=>be(p,t)),u=Pv(s,a),l=Av(e.additionalItems,t),d=I.tuple(u);o=l?d.rest(l):d,typeof e.minItems=="number"&&(o=o.check(I.minLength(e.minItems))),typeof e.maxItems=="number"&&(o=o.check(I.maxLength(e.maxItems)))}else if(i!==void 0){let a=be(i,t),s=I.array(a);typeof e.minItems=="number"&&(s=s.min(e.minItems)),typeof e.maxItems=="number"&&(s=s.max(e.maxItems)),o=s}else o=I.array(I.any());(e.uniqueItems===!0||e.contains!==void 0)&&(o=iS(o,{uniqueItems:e.uniqueItems===!0,containsSchema:e.contains!==void 0?be(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 be(e,t){if(typeof e=="boolean")return e?I.any():I.never();let r=Tv(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=>be(l,t)),u=I.union(s);r=o?I.intersection(r,u):u}if(e.oneOf&&Array.isArray(e.oneOf)){let s=e.oneOf.map(l=>be(l,t)),u=I.xor(s);r=o?I.intersection(r,u):u}if(e.allOf&&Array.isArray(e.allOf))if(e.allOf.length===0)r=o?r:I.any();else{let s=o?r:be(e.allOf[0],t),u=o?0:1;for(let l=u;l<e.allOf.length;l++)s=I.intersection(s,be(e.allOf[l],t));r=s}e.nullable===!0&&t.version==="openapi-3.0"&&(r=I.nullable(r)),e.readOnly===!0&&(r=I.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&&!Yr(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&&!Yr(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))Xw.has(s)||le(n,s,e[s]);return Object.keys(n).length>0&&t.registry.add(r,n),e.description&&(r=r.describe(e.description)),r}function Ov(e,t){if(typeof e=="boolean")return e?I.any():I.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=Yw(r,t?.defaultTarget),n=r.$defs||r.definitions||{},i={version:o,defs:n,refs:new Map,processing:new Set,rootSchema:r,registry:t?.registry??de};return be(r,i)}var Nv=Symbol("z.visit/resolving");function Qr(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===Nv)return new zr({type:"lazy",getter:()=>o.get(a)});if(s!==void 0)return s;o.set(a,Nv);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,f={};for(let v of d){let $=n(l[v]);$!==l[v]&&(p=!0),f[v]=$}let m=s.catchall;return s.catchall&&(m=n(s.catchall),m!==s.catchall&&(p=!0)),p?V(a,{...s,shape:f,catchall:m}):a}case"array":{let l=n(s.element);return l===s.element?a:V(a,{...s,element:l})}case"tuple":{let l=s.items,d=!1,p=[];for(let m of l){let v=n(m);v!==m&&(d=!0),p.push(v)}let f=s.rest;return s.rest&&(f=n(s.rest),f!==s.rest&&(d=!0)),d?V(a,{...s,items:p,rest:f}):a}case"record":case"map":{let l=n(s.keyType),d=n(s.valueType);return l===s.keyType&&d===s.valueType?a:V(a,{...s,keyType:l,valueType:d})}case"set":{let l=n(s.valueType);return l===s.valueType?a:V(a,{...s,valueType:l})}case"union":{let l=s.options,d=!1,p=[];for(let f of l){let m=n(f);m!==f&&(d=!0),p.push(m)}return d?V(a,{...s,options:p}):a}case"intersection":{let l=n(s.left),d=n(s.right);return l===s.left&&d===s.right?a:V(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:V(a,{...s,innerType:l})}case"pipe":{let l=n(s.in),d=n(s.out);return l===s.in&&d===s.out?a:V(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:V(a,{...s,input:l,output:d})}case"lazy":{let l=s.getter,{_cachedInner:d,...p}=s;return V(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 Dv(e){return Qr(e,{object:t=>t.partial(),union:t=>{let r=t._zod.def;return r.discriminator===void 0?t:Fn(r.options)}})}function aS(e,t){if(!t?.length)return e;let r=e._zod.def;return V(e,Re(r,{checks:[...r.checks??[],...t]}),{parent:!0})}function Uv(e){return aS(e.out,e.checks)}function sS(e){return e.in._zod.traits.has("$ZodTransform")?Uv(e):e.in}function Cv(e){return Qr(e,{pipe:t=>sS(t._zod.def),default:(t,r)=>r?Ft(t._zod.def.innerType):t,catch:(t,r)=>r?t._zod.def.innerType:t})}function Ev(e){return Qr(e,{pipe:t=>Uv(t._zod.def),prefault:(t,r)=>r?t._zod.def.innerType:t})}var Np={};et(Np,{bigint:()=>dS,boolean:()=>lS,date:()=>pS,number:()=>uS,string:()=>cS});function cS(e){return tl(Rn,e)}function uS(e){return sl(Mn,e)}function lS(e){return fl(Ln,e)}function dS(e){return hl(Zn,e)}function pS(e){return zl(Vr,e)}var Kn=c.string().min(1).max(512).refine(mS,"Invalid path: use segments like notes/plan.md, without .. or a leading /");function mS(e){return/[\u0000-\u001f\u007f\\]/.test(e)?!1:e.split("/").every(r=>r.length>0&&r.length<=255&&r!=="."&&r!=="..")}var ei=c.string().regex(me("message")),H=c.string().regex(me("thread")),ze=c.string().regex(me("project")),Pe=c.string().regex(me("task")),Dp=c.string().regex(me("artifact")),R=c.iso.datetime(),ti=c.enum(["user","agent","system"]),fS=c.object({path:Kn,name:c.string(),size:c.number().int().nonnegative(),contentType:c.string()}),gS=c.object({artifactId:Dp,version:c.number().int().positive(),title:c.string()}),Rv=c.enum(["cloud","local"]),X=c.number().int().nonnegative(),hS=c.object({title:c.string(),harness:c.string(),runtime:Rv,model:c.string().nullable(),durationMs:X,inputTokens:X,outputTokens:X,costMicros:X.nullable()}),vS=c.object({chars:X,limit:X,parts:c.object({instructions:X,skills:X,knowledge:X,brief:X,conversation:X,notes:X,other:X}),droppedMessages:X,droppedNotes:X,cut:c.boolean()}),yS=c.object({model:c.string(),durationMs:X,calls:X,inputTokens:X,cachedInputTokens:X,outputTokens:X,costMicros:X.nullable(),runtime:Rv,computer:c.string().optional(),harness:c.string().optional(),task:hS.optional(),prompt:vS.optional()}),bS=c.enum(["brief","follow_up","reply","relay","answer"]),$S=c.object({kind:bS,threadId:H,fromThreadId:H.optional(),note:c.string()}),xa=8,Bt=c.object({id:ei,projectId:ze,threadId:H.nullable(),authorKind:ti,authorId:c.string().min(1),body:c.string(),attachments:c.array(fS).optional(),artifacts:c.array(gS).optional(),stats:yS.optional(),relay:$S.optional(),clis:c.array(c.string().max(40)).max(xa).optional(),seq:c.number().int().positive(),createdAt:R,editedAt:R.optional()}),_S=c.enum(["working","blocked","review_ready","done","failed"]),xS=c.object({id:c.string().max(40),options:c.array(c.string().max(40)).max(xa),by:c.enum(["person","coordinator"]),reason:c.string().max(300).nullable()}),kS=c.object({cli:c.string().max(40),model:c.string().max(200).nullable(),effort:c.string().max(20).nullable()}),Mv="cloud",wS=c.object({id:c.string().max(60),by:c.enum(["person","auto","coordinator"]),reason:c.string().max(300).nullable().default(null)}),Up=c.enum(["duplicate","misrouted","cancelled"]),SS=c.object({replies:X,usage:c.object({tokens:X,durationMs:X,costMicros:X.nullable()}).nullable(),planMessageId:ei.nullable()}),Cp=c.object({id:H,projectId:ze,rootMessageId:ei,ackMessageId:ei.nullable().default(null),title:c.string(),status:_S,statusText:c.string().nullable(),resolved:c.boolean(),closeReason:Up.nullable().default(null),duplicateOf:H.nullable().default(null),label:c.string().nullable(),cli:xS.nullable().default(null),runner:wS.nullable().default(null),model:kS.nullable().default(null),seenSeq:c.number().int().nonnegative().nullable().default(null),summary:SS.nullable().default(null),createdAt:R,updatedAt:R}),IS=c.enum(["running","done","failed","cancelled"]),Lv=c.object({id:Pe,threadId:H,title:c.string(),harness:c.string(),backend:c.string(),status:IS,prUrl:c.string().nullable(),summary:c.string().nullable(),createdAt:R,finishedAt:R.nullable()}),lN=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()}),Ep=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()}),Zv=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:Ep.optional()}),Rp=c.object({messageId:ei,emoji:c.string().min(1).max(32),authorKind:ti,authorId:c.string().min(1)}),ka=c.enum(["owner","admin","member"]),zS=c.object({working:c.number().int().nonnegative(),waiting:c.number().int().nonnegative()}),PS=c.object({monthMicros:c.number().int().nonnegative(),totalMicros:c.number().int().nonnegative()}),wa=c.enum(["indigo","blue","teal","green","amber","orange","red","pink","purple","gray"]),Sa=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"]),dN=c.object({id:ze,name:c.string().min(1).max(120),role:ka,icon:Sa.nullable().optional(),color:wa.nullable().optional(),createdAt:R,activity:zS.optional(),cost:PS.optional(),pinned:c.boolean().optional()}),pN=c.object({pinned:c.boolean()}),mN=c.object({name:c.string().trim().min(1).max(120)}),fN=c.object({id:c.string(),name:c.string(),role:ka,email:c.string().optional()}),Mp=32e3,jS=c.object({id:c.number().int(),accountLogin:c.string(),accountType:c.enum(["User","Organization"]),accountAvatarUrl:c.string().nullable()}),gN=c.object({configured:c.boolean(),installUrl:c.string().nullable(),installations:c.array(jS)}),hN=c.object({id:c.number().int(),installationId:c.number().int(),fullName:c.string(),defaultBranch:c.string(),private:c.boolean(),description:c.string().nullable()}),vN=c.object({repoId:c.number().int(),installationId:c.number().int(),fullName:c.string(),defaultBranch:c.string(),private:c.boolean(),createdAt:R}),Fv=c.object({repo:c.string(),number:c.number().int(),url:c.string(),threadId:H,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}),AS=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()}),yN=c.object({files:c.array(AS),truncated:c.boolean()}),Vv=c.enum(["merge","squash","rebase"]),bN=c.object({permitted:c.boolean(),blocked:c.enum(["closed","draft","conflict","checks_failed","checks_pending","changes_requested","protected","checking"]).nullable(),methods:c.array(Vv),sha:c.string()}),$N=c.object({method:Vv,sha:c.string().min(1),deleteBranch:c.boolean().default(!1)}),_N=c.object({merged:c.literal(!0),branchDeleted:c.boolean(),branchKept:c.enum(["fork","default","protected","gone","in_use","reopened","failed"]).nullable()}),xN=c.object({installationId:c.number().int().positive(),repoId:c.number().int().positive()});var TS=16e3,OS=16e3,zN=25*1024*1024,Kv=10;var PN=c.object({path:Kn,size:c.number().int().nonnegative(),contentType:c.string(),updatedAt:R,updatedByKind:ti,updatedBy:c.string()}),NS=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"),DS=c.enum(["ok","stale"]),US=c.object({name:NS,description:c.string().max(300),content:c.string().max(OS),updatedAt:R,updatedByKind:ti,updatedBy:c.string(),status:DS.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)}),jN=US.pick({description:!0,content:!0}),AN=c.discriminatedUnion("status",[c.object({status:c.literal("ok")}),c.object({status:c.literal("stale"),reason:c.string().trim().min(1).max(300)})]),CS=c.object({text:c.string().max(TS),updatedAt:R.nullable(),updatedBy:c.string().nullable()}),TN=CS.pick({text:!0}),Jv=c.enum(["files","memory","instructions"]),Bv=c.enum(["auto","on","off"]),ON=c.object({mode:Bv,active:c.boolean(),lastRunAt:R.nullable(),threadsSince:c.number().int().nonnegative(),threadsNeeded:c.number().int().positive(),threadId:c.string().nullable()}),NN=c.object({mode:Bv});var Lp=c.object({id:Dp,projectId:ze,threadId:H.nullable(),title:c.string(),description:c.string().nullable(),version:c.number().int().positive(),createdAt:R,updatedAt:R}),EN=c.object({version:c.number().int().positive(),size:c.number().int().nonnegative(),threadId:H.nullable(),createdAt:R}),RN=c.object({version:c.number().int().positive(),url:c.string().nullable(),expiresAt:R.nullable()}),MN=2*1024*1024;var Zp=c.string().regex(me("routine")),ES=/^(\*|\d+(-\d+)?)(\/\d+)?(,(\*|\d+(-\d+)?)(\/\d+)?)*$/,RS=c.string().trim().refine(e=>{let t=e.split(/\s+/);return t.length===5&&t.every(r=>ES.test(r))},"Expected a five-field cron expression, e.g. 0 9 * * 1-5"),MS=c.string().min(1).max(64).refine(e=>{try{return new Intl.DateTimeFormat("en-US",{timeZone:e}),!0}catch{return!1}},"Unknown time zone"),Fp=c.discriminatedUnion("kind",[c.object({kind:c.literal("cron"),cron:RS,timezone:MS.default("UTC")}),c.object({kind:c.literal("once"),at:R})]),Vp=c.discriminatedUnion("kind",[c.object({kind:c.literal("coordinator")}),c.object({kind:c.literal("thread"),threadId:H})]),Kp=c.object({id:Zp,projectId:ze,name:c.string(),prompt:c.string(),target:Vp,schedule:Fp,paused:c.boolean(),nextRunAt:R.nullable(),lastRunAt:R.nullable(),runCount:c.number().int().nonnegative(),createdBy:c.string(),createdAt:R});var KN=c.object({name:c.string().trim().min(1).max(120),prompt:c.string().trim().min(1).max(8e3),target:Vp.default({kind:"coordinator"}),schedule:Fp}),JN=c.object({name:c.string().trim().min(1).max(120),prompt:c.string().trim().min(1).max(8e3),target:Vp,schedule:Fp,paused:c.boolean()}).partial();var Jp=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 LS=c.string().regex(me("sshHost")),Bp=c.string().regex(/^[a-z0-9][a-z0-9_-]{0,39}$/,"Use lowercase letters, digits, - and _ (up to 40)."),Ia=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."),Wv=c.string().trim().regex(/^[A-Za-z0-9_][A-Za-z0-9_.-]{0,63}$/,"Enter the user name on the server."),Gv=c.enum(["ask","off"]),YN=c.string().max(16e3).regex(/^(?:ssh|ecdsa|sk)-[\w@.-]+ [A-Za-z0-9+/=]+(?: .*)?$/),qv=c.string().max(200).regex(/^SHA256:[A-Za-z0-9+/=]+$/),ZS=c.object({id:LS,projectId:ze,alias:Bp,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:Gv,testedAt:R.nullable(),createdAt:R}),FS=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}),QN=c.object({hosts:c.array(ZS),history:c.array(FS)}),eD=c.object({runnerId:c.string(),alias:Bp,host:Ia,port:c.number().int().min(1).max(65535).default(22),user:Wv,existingKey:c.string().min(1).max(1024).optional()}),tD=c.object({rule:Gv}),nD=c.object({hostKey:c.string().min(1).max(16e3)}),Hv=c.object({type:c.string().max(60),key:c.string().max(16e3),fingerprint:qv}),Xv=c.object({path:c.string().max(1024),name:c.string().max(255),type:c.string().max(60),fingerprint:qv,comment:c.string().max(500)}),Yv=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()}),Qv=300*1e3,ey=200*1024,za=c.object({projectId:ze,alias:Bp}),Wp=za.extend({host:Ia,port:c.number().int().min(1).max(65535),user:Wv,hostKey:c.string().min(1).max(16e3)});var ry=2,at=c.string().regex(me("runner")),Be=c.enum(["claude","codex","antigravity","opencode","hermes","cursor","muse","kimi"]);var iy=c.object({path:c.string().min(1).max(1024),name:c.string().max(255)}),VS=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(VS).max(8),at:R});var JS=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 BS=c.object({id:Be,version:c.string().max(200).nullable(),limits:KS.optional().catch(void 0),models:c.array(JS).max(100).optional().catch(void 0)}),WS=c.enum(["folders","cancel","agent","agent-clis","connectors","skills","project-folders","files","settings","update","models","github-token","git-token","steer","steer-claude","ssh","stats"]),GS=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))})]),qS=c.enum(["read","edit","auto","full"]),qp=c.object({access:qS,worktrees:c.boolean(),autoUpdate:c.boolean(),remote:c.boolean()}),oy=qp.omit({remote:!0}).partial(),HS=c.enum(["service","app","manual"]),Gp=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}),ay=c.object({version:c.string().max(50),hostname:c.string().max(255),platform:c.string().max(50),folders:c.array(iy).max(200),clis:c.array(c.unknown()).max(10).transform(e=>e.flatMap(t=>{let r=BS.safeParse(t);return r.success?[r.data]:[]})),features:c.array(c.string().max(50)).max(20).default([]).transform(e=>e.filter(t=>WS.safeParse(t).success)),settings:qp.optional().catch(void 0),updates:HS.optional().catch(void 0),update:Gp.optional().catch(void 0)}),Wt=c.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),ja=c.object({at:R,cpu:c.object({percent:c.number().min(0).max(100).optional(),cores:c.number().int().min(1).max(1024)}),memory:c.object({total:Wt,available:Wt}),swap:c.object({total:Wt,used:Wt}).optional(),disk:c.object({total:Wt,free:Wt}).optional(),tasks:c.number().int().nonnegative().max(1e3),runnerMemory:Wt.optional()}),Pa=1e5,Q=c.string().min(1).max(64),XS=c.object({name:c.string().max(255),path:c.string().max(1024)}),YS=c.object({path:c.string().max(1024),parent:c.string().max(1024).nullable(),home:c.string().max(1024),dirs:c.array(XS).max(1e3)}),ty=c.object({inputTokens:c.number().int().nonnegative(),outputTokens:c.number().int().nonnegative(),model:c.string().max(200).optional()}),Hp=512*1024,QS=c.object({path:c.string().max(4096),size:c.number().int().nonnegative(),data:c.string().max(Math.ceil(Hp/3)*4+4),truncated:c.boolean()}),eI=c.object({model:c.string().min(1).max(200).optional(),effort:c.string().min(1).max(20).optional()}),ny=c.object({token:c.string().min(20).max(4096),expiresAt:R,repos:c.array(c.string().regex(/^[\w.-]+\/[\w.-]+$/).max(200)).max(100)}),cD=c.discriminatedUnion("type",[ay.extend({type:c.literal("hello"),protocol:c.number().int().positive(),running:c.array(Pe).max(100).default([]),interrupted:c.array(Pe).max(100).default([]),stats:ja.optional().catch(void 0)}),c.object({type:c.literal("task.progress"),taskId:Pe,text:c.string().max(2e3),usage:ty.optional(),agent:Ep.optional(),ms:c.number().nonnegative().optional()}),c.object({type:c.literal("task.done"),taskId:Pe,ok:c.boolean(),usage:ty.optional(),result:c.string().max(Pa),cancelled:c.boolean().optional()}),c.object({type:c.literal("ping"),stats:ja.optional().catch(void 0)}),c.object({type:c.literal("task.folders"),taskId:Pe,folders:c.array(c.string().min(1).max(1024)).max(60)}),YS.extend({type:c.literal("dirs"),requestId:Q}),c.object({type:c.literal("folders"),requestId:Q,folders:c.array(iy).max(200)}),c.object({type:c.literal("request.failed"),requestId:Q,message:c.string().max(500)}),QS.extend({type:c.literal("file"),requestId:Q}),c.object({type:c.literal("settings"),requestId:Q,settings:qp}),c.object({type:c.literal("update.accepted"),requestId:Q,update:Gp}),c.object({type:c.literal("update.status"),update:Gp.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(Xv).max(100)}),c.object({type:c.literal("ssh.hostkeylist"),requestId:Q,keys:c.array(Hv).max(10)}),Yv.extend({type:c.literal("ssh.result"),requestId:Q})]),sy=c.discriminatedUnion("type",[c.object({type:c.literal("welcome"),runnerId:at,name:c.string()}),c.object({type:c.literal("task.start"),taskId:Pe,threadId:H,folder:c.string().min(1).max(1024),cli:Be,prompt:c.string().min(1).max(Pa),model:eI.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(GS).max(30).optional(),skills:c.object({path:c.string().regex(/^\/api\/[\w/-]+$/).max(300)}).optional(),resume:c.object({after:Pe,prompt:c.string().min(1).max(Pa)}).optional()}).optional(),github:ny.optional()}),c.object({type:c.literal("task.github"),taskId:Pe,github:ny}),c.object({type:c.literal("task.steer"),requestId:Q,taskId:Pe,text:c.string().min(1).max(Pa)}),c.object({type:c.literal("task.cancel"),taskId:Pe}),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:H.optional()}),c.object({type:c.literal("settings.set"),requestId:Q,settings:oy}),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)}),za.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:Ia,port:c.number().int().min(1).max(65535)}),c.object({type:c.literal("ssh.test"),requestId:Q,target:Wp}),c.object({type:c.literal("ssh.run"),requestId:Q,target:Wp,command:c.string().min(1).max(2e4)}),za.extend({type:c.literal("ssh.forget"),requestId:Q})]),tI=ay.extend({id:at,name:c.string(),version:c.string().nullable(),online:c.boolean(),lastSeenAt:R.nullable(),createdAt:R,stats:ja.optional()}),uD=c.object({name:c.string().trim().min(1).max(80).optional(),settings:oy.optional()}),lD=c.object({now:c.boolean().default(!1)}),dD=c.object({runners:c.array(tI),latestVersion:c.string().nullable()}),pD=c.object({code:c.string(),expiresAt:R}),mD=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("")}),cy=c.object({runner:c.object({id:at,name:c.string()}),token:c.string()}),fD=c.object({projectId:ze,runnerId:at,runnerName:c.string(),path:c.string(),folders:c.array(c.string()).default([]),cli:Be,online:c.boolean(),isDefault:c.boolean().default(!0),stats:ja.optional()}),gD=c.object({path:c.string().trim().min(1).max(1024)}),hD=c.object({runnerId:at,path:c.string().min(1).max(1024),cli:Be,add:c.boolean().optional()}),vD=c.object({path:c.string().min(1).max(1024),runnerId:at.optional()}),yD=c.object({runnerId:at});function uy(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 nI=200,rI=c.object({threadId:H.nullable(),hasEarlier:c.boolean()});var PD=c.discriminatedUnion("type",[c.object({type:c.literal("message.send"),clientId:c.string().max(64).optional(),threadId:H.nullable().default(null),body:c.string().trim().max(Mp),attachments:c.array(Kn).max(Kv).default([]),clis:c.array(Be).max(xa).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(Mp)}),c.object({type:c.literal("thread.resolve"),threadId:H,resolved:c.boolean(),reason:Up.optional()}),c.object({type:c.literal("thread.cli"),threadId:H,cli:Be.nullable()}),c.object({type:c.literal("thread.runner"),threadId:H,runnerId:c.union([at,c.literal(Mv)]).nullable()}),c.object({type:c.literal("thread.model"),threadId:H,cli:Be,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(nI).optional()})]),jD=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(Cp).default([]),reactions:c.array(Rp).default([]),artifacts:c.array(Lp).default([]),routines:c.array(Kp).default([]),goal:Jp.nullable().optional(),windows:c.array(rI).optional(),reset:c.boolean().optional(),lastSeq:c.number().int().nonnegative().optional()}),c.object({type:c.literal("thread.updated"),thread:Cp}),c.object({type:c.literal("reaction.added"),reaction:Rp}),c.object({type:c.literal("artifact.updated"),artifact:Lp}),c.object({type:c.literal("routine.updated"),routine:Kp}),c.object({type:c.literal("routine.deleted"),routineId:Zp}),c.object({type:c.literal("goal.updated"),goal:Jp.nullable()}),c.object({type:c.literal("agent.activity"),threadId:H.nullable(),active:c.boolean(),label:c.string().max(200).optional()}),c.object({type:c.literal("knowledge.changed"),kind:Jv}),c.object({type:c.literal("workspace.changed")}),c.object({type:c.literal("task.updated"),task:Lv}),c.object({type:c.literal("task.output"),taskId:Pe,threadId:H,lines:c.array(Zv)}),c.object({type:c.literal("pr.updated"),pullRequest:Fv}),c.object({type:c.literal("error"),code:c.string(),message:c.string()})]);var OD=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 UD=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 ni=c.enum(["fireworks","anthropic","openai"]),FD=c.object({id:ni,name:c.string(),defaultModel:c.string(),serverKey:c.boolean()}),VD=c.object({id:c.string(),provider:ni,label:c.string(),hint:c.string(),scope:c.enum(["user","instance"]),createdAt:c.iso.datetime()}),KD=c.object({provider:ni,label:c.string().trim().min(1).max(80),key:c.string().trim().min(8).max(500),scope:c.enum(["user","instance"]).default("user")}),ly=c.enum(["auto","local","cloud"]),dy=c.enum(["opencode","claude","codex"]),iI=c.object({model:c.string().trim().min(1).max(200).nullable(),effort:c.string().trim().min(1).max(20).nullable()}),py=c.partialRecord(Be,iI),JD=c.object({name:c.string(),provider:ni.nullable(),model:c.string().nullable(),keyId:c.string().nullable(),taskTarget:ly,icon:Sa.nullable().default(null),color:wa.nullable().default(null),cloudCli:dy.default("opencode"),cliModels:py.default({})}),BD=c.object({name:c.string().trim().min(1).max(120).optional(),provider:ni.nullable().optional(),model:c.string().trim().max(200).nullable().optional(),keyId:c.string().nullable().optional(),taskTarget:ly.optional(),icon:Sa.nullable().optional(),color:wa.nullable().optional(),cloudCli:dy.optional(),cliModels:py.optional()}),my=c.enum(["admin","member"]),WD=c.object({id:c.string(),projectId:c.string(),projectName:c.string(),email:c.string(),role:my,invitedBy:c.string(),createdAt:c.iso.datetime()}),GD=c.object({email:c.email().trim().toLowerCase(),role:my.default("member")}),qD=c.object({role:ka}),oI=c.enum(["admin","user"]),HD=c.enum(["computer","decision"]),XD=c.object({id:c.string(),name:c.string(),email:c.string(),role:oI,onboarded:c.boolean().optional(),tips:c.array(c.string()).optional()}),aI=c.object({signUpEnabled:c.boolean()}),sI=c.enum(["api","agent","cron","web","desktop","mobile"]),YD=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()}),QD=c.object({id:c.string(),source:sI,where:c.string(),name:c.string(),message:c.string(),stack:c.string().nullable(),count:c.number().int(),firstSeenAt:c.number(),lastSeenAt:c.number()}),e4=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()}),t4=aI.partial();var fy=c.string().regex(me("notification")),cI=c.enum(["done","ready","decision","blocked","failed"]),a4=c.object({id:fy,projectId:ze,threadId:H.nullable(),kind:cI,title:c.string(),body:c.string(),url:c.string(),readAt:R.nullable(),createdAt:R}),s4=c.object({email:c.boolean(),push:c.boolean()}),c4=c.object({webPushKey:c.string().nullable(),email:c.boolean()}),uI=[/^fcm\.googleapis\.com$/,/^updates\.push\.services\.mozilla\.com$/,/^web\.push\.apple\.com$/,/^[a-z0-9-]+\.notify\.windows\.com$/];function lI(e){try{let t=new URL(e);return t.protocol==="https:"&&uI.some(r=>r.test(t.hostname))}catch{return!1}}var u4=c.discriminatedUnion("kind",[c.object({kind:c.literal("webpush"),endpoint:c.url().max(2048).refine(lI,"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)})]),l4=c.union([c.object({ids:c.array(fy).min(1).max(200)}),c.object({all:c.literal(!0)})]);var dI=new RegExp(me("thread").source.slice(1,-1)),h4=new RegExp(`^#(${dI.source})$`);var pI=c.enum(["http","stdio"]),mI=c.enum(["user","project"]),Yp=c.enum(["cloud","local","both"]),fI=c.enum(["unknown","ok","error","needs_auth"]),gI=c.enum(["none","headers","oauth"]),gy=c.string().regex(/^[a-z][a-z0-9_-]{0,31}$/).refine(e=>e!=="myrel","That name is taken by Myrel's own tools."),hI=c.object({name:c.string(),description:c.string().optional()}),vI=/^[A-Za-z_][\w-]{0,99}$/,yI=/^[A-Za-z_][A-Za-z0-9_]{0,99}$/,hy=(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}),vy=hy(vI,"Header","letters, digits, - and _"),bI=hy(yI,"Variable","letters, digits and _"),b4=c.object({id:c.string(),name:c.string(),slug:c.string(),scope:mI,transport:pI,url:c.string().nullable(),auth:gI,command:c.string().nullable(),args:c.array(c.string()),runsOn:Yp,secretNames:c.array(c.string()),enabled:c.boolean(),status:fI,lastError:c.string().nullable(),tools:c.array(hI),canEdit:c.boolean(),createdAt:c.iso.datetime(),official:c.object({id:c.string(),title:c.string(),iconUrl:c.string().nullable()}).nullable().default(null)}),Xp=c.string().trim().min(1).max(60),$4=c.discriminatedUnion("transport",[c.object({transport:c.literal("http"),name:Xp,slug:gy.optional(),url:c.url({protocol:/^https$/}).max(2e3),auth:c.enum(["headers","oauth"]).default("headers"),headers:vy.default({})}),c.object({transport:c.literal("stdio"),name:Xp,slug:gy.optional(),command:c.string().trim().min(1).max(200),args:c.array(c.string().max(2e3)).max(50).default([]),env:bI.default({}),runsOn:Yp.default("both")})]),_4=c.object({name:Xp.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:Yp.optional(),secrets:vy.optional()});var x4=c.object({authorizeUrl:c.url()});var $I=["developer","productivity","communication","design","data","sales","finance","search","ai","other"],yy=c.enum($I);var _I=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:yy,official:c.boolean()}),k4=c.object({connectors:c.array(_I),nextOffset:c.number().nullable(),syncedAt:c.iso.datetime().nullable(),categories:c.array(c.object({id:yy,count:c.number()}))}),xI=[{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"}],w4=xI.map(e=>e.id);var kI=c.enum(["user","project"]),wI=c.string().max(64).regex(/^[a-z0-9]+(-[a-z0-9]+)*$/,"Use lowercase letters, digits and hyphens, like pdf-forms."),by=c.string().trim().min(1).max(1024),SI=c.string().min(1).max(300).regex(/^[\w@+=,.~ -]+(\/[\w@+=,.~ -]+)*$/,"Invalid file path.").refine(e=>!e.split("/").some(t=>t==="."||t===".."),"Invalid file path."),$y={files:200,bytes:5*1024*1024,fileBytes:1024*1024};var II=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()})]),zI=c.object({path:c.string(),size:c.number().int().nonnegative()}),PI=c.object({id:c.string(),name:c.string(),description:c.string(),scope:kI,source:II,enabled:c.boolean(),files:c.array(zI),size:c.number().int().nonnegative(),canEdit:c.boolean(),createdAt:c.iso.datetime(),updatedAt:c.iso.datetime()}),z4=PI.extend({skillMd:c.string()}),jI=c.object({path:SI,content:c.string().max(Math.ceil($y.fileBytes*4/3)+4)}),P4=c.discriminatedUnion("kind",[c.object({kind:c.literal("write"),name:wI,description:by,instructions:c.string().max(1e5)}),c.object({kind:c.literal("upload"),files:c.array(jI).min(1).max($y.files)}),c.object({kind:c.literal("github"),source:c.string().trim().min(3).max(500),skill:c.string().max(64).optional()})]),j4=c.object({error:c.literal("choose_skill"),skills:c.array(c.object({name:c.string(),description:c.string(),path:c.string()}))}),A4=c.object({enabled:c.boolean().optional(),description:by.optional(),instructions:c.string().max(1e5).optional()}),T4=c.object({skills:c.array(c.object({name:c.string(),files:c.array(c.object({path:c.string(),content:c.string()}))}))});var O4=c.object({on:c.boolean()});var AI=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)}),TI=c.enum(["open","connected","dismissed"]),U4=c.object({id:c.string(),reason:c.string().min(1).max(400),offers:c.array(AI).min(1).max(3),state:TI.default("open"),connected:c.string().optional(),signIn:c.boolean().optional()});var C4=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()}),E4=c.object({authorizeUrl:c.string().optional(),connected:c.boolean()});var OI=/^(?:\/(?:usr\/)?(?:local\/)?bin\/)?(?:ba|z|da|k)?sh\s+-l?c\s+(\S[\s\S]*)$/;function Jn(e){let t=OI.exec(e.trim());return t?NI(t[1])??e:e}function NI(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 DI,readFile as UI,rename as CI,writeFile as EI}from"node:fs/promises";import{homedir as ky}from"node:os";import{dirname as RI,join as _y}from"node:path";var wy="MYREL_MCP_BRIDGE";function MI(e=ky()){return{mcp:_y(e,".gemini","config","mcp_config.json"),settings:_y(e,".gemini","antigravity-cli","settings.json")}}function ri(){let e=process.argv[1],t=!e||/\$bunfs|~BUN/.test(e);return{command:process.execPath,args:t?[]:[e]}}async function Sy(e,t=ky()){let r=MI(t),o=ri(),n={command:o.command,args:[...o.args,"mcp-bridge"]};await xy(r.mcp,a=>{let s=Qp(a.mcpServers)?a.mcpServers:{};return JSON.stringify(s[e])===JSON.stringify(n)?!1:(a.mcpServers={...s,[e]:n},!0)});let i=`mcp(${e}/*)`;await xy(r.settings,a=>{let s=Qp(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 xy(e,t){let r=await UI(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(!Qp(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 DI(RI(e),{recursive:!0});let n=`${e}.myrel-${process.pid}`;await EI(n,`${JSON.stringify(o,null,2)}
63
63
  `,{mode:384}),await CI(n,e)}function Qp(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}import{mkdir as LI,readFile as ZI,rename as FI,writeFile as VI}from"node:fs/promises";import{homedir as KI}from"node:os";import{basename as JI,join as em,resolve as zy}from"node:path";function ee(){return process.env.MYREL_RUNNER_HOME||em(KI(),".myrel-runner")}var Bn=()=>em(ee(),"config.json");async function ii(){let e=await $e(Bn()),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 BI=["MYREL_RUNNER_TOKEN"],WI=["SSH_AUTH_SOCK"];function We(e){let t={...process.env,...e};for(let r of[...BI,...WI])delete t[r];return t}async function Ta(e){let t={...e};process.env.MYREL_RUNNER_TOKEN&&t.token===process.env.MYREL_RUNNER_TOKEN&&(t.token=(await $e(Bn()))?.token),await Ze(Bn(),t)}function Py(e,t){let r=zy(t);return e.folders.some(o=>o.path===r)?!1:(e.folders.push({path:r,name:JI(r)||r}),!0)}function jy(e,t){let r=zy(t),o=e.folders.length;return e.folders=e.folders.filter(n=>n.path!==r),e.folders.length!==o}var Aa=class{constructor(t=em(ee(),"sessions.json")){this.path=t}path;async get(t,r="claude"){let o=(await $e(this.path))?.[Iy(t,r)];return typeof o=="string"?{id:o}:o}async set(t,r,o){let n=await $e(this.path)??{};n[Iy(t,r)]=o,await Ze(this.path,n)}},Iy=(e,t)=>t==="claude"?e:`${t}:${e}`;async function $e(e){try{return JSON.parse(await ZI(e,"utf8"))}catch(t){if(t.code==="ENOENT")return;throw t}}async function Ze(e,t){await LI(ee(),{recursive:!0,mode:448});let r=`${e}.${process.pid}.tmp`;await VI(r,`${JSON.stringify(t,null,2)}
64
64
  `,{mode:384}),await FI(r,e)}import{open as GI,readdir as qI,stat as HI}from"node:fs/promises";import{homedir as XI}from"node:os";import{join as Gt}from"node:path";var YI={five_hour:"session",seven_day:"weekly",seven_day_opus:"weekly_opus",seven_day_sonnet:"weekly_sonnet"},Wn=e=>typeof e=="number"&&Number.isFinite(e)?e:null,Ay=e=>e!==null&&e>0?new Date(e*1e3).toISOString():null,Ty=e=>e===null?null:Math.min(1e3,Math.max(0,Math.round(e*10)/10));function Oy(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"?YI[a]:void 0;if(!l)return;let d=Wn(s),p=o.get(l);o.set(l,{kind:l,usedPercent:d===null?p?.usedPercent??null:Ty(d*100),resetsAt:Ay(Wn(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 QI(e){return e===300?"session":e===10080?"weekly":e?`${e}m`:"other"}function tm(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=Wn(i.resets_in_seconds),s=Ay(Wn(i.resets_at))??(a!==null?new Date(new Date(t).getTime()+a*1e3).toISOString():null);r.push({kind:QI(Wn(i.window_minutes)),usedPercent:Ty(Wn(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 ez(){return process.env.CODEX_HOME||Gt(XI(),".codex")}async function Oa(e){return(await qI(e).catch(()=>[])).sort().reverse()}var tz=256*1024;async function nz(e){let t=await GI(e,"r").catch(()=>null);if(t)try{let{size:r}=await t.stat(),o=Math.min(r,tz),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 HI(e)).mtime.toISOString(),l=tm(s.payload.rate_limits,u);if(l)return l}catch{}return}finally{await t.close()}}async function Na(e){let t=Gt(ez(),"sessions"),r=0;for(let o of await Oa(t))for(let n of await Oa(Gt(t,o)))for(let i of await Oa(Gt(t,o,n))){let a=Gt(t,o,n,i);for(let s of await Oa(a)){if(!s.endsWith(".jsonl")||e&&!s.includes(e))continue;let u=await nz(Gt(a,s));if(u||e)return u;if(++r>=20)return}if(e&&++r>=14)return}}var Ny=()=>Gt(ee(),"limits.json");async function Dy(){return await $e(Ny()).catch(()=>{})??{}}async function Uy(e){await Ze(Ny(),e)}import{execFile as rz}from"node:child_process";import{existsSync as iz}from"node:fs";import{homedir as oz}from"node:os";import{delimiter as Cy,dirname as az,join as st}from"node:path";async function Ey(){let e=[az(process.execPath),...process.platform==="win32"?[...await dz(),...pz()]:[]];process.env.PATH=sz(process.env.PATH??"",e,Cy,process.platform==="win32")}function sz(e,t,r=Cy,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 cz(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 uz(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 lz=["HKLM\\SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment","HKCU\\Environment"];async function dz(){return(await Promise.all(lz.map(t=>new Promise(r=>{rz("reg",["query",t,"/v","Path"],{timeout:5e3,windowsHide:!0},(o,n)=>r(o?void 0:uz(n)))})))).flatMap(t=>t?cz(t).split(";"):[])}function pz(){let e=oz(),t=process.env.APPDATA??st(e,"AppData","Roaming"),r=process.env.LOCALAPPDATA??st(e,"AppData","Local");return[st(t,"npm"),process.env.PNPM_HOME??st(r,"pnpm"),st(e,".bun","bin"),st(e,".local","bin"),st(e,"scoop","shims"),st(r,"Microsoft","WinGet","Links"),st(r,"Volta","bin")].filter(o=>iz(o))}function oi(e,t,r){e.progress=t;let o=r&&mz(e,r);o?e.progressAgent=o:delete e.progressAgent}function Gn(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:fz(o),agent:{id:t,label:a,state:"started"}})}function St(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 Da(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 mz(e,t){e.agents?.has(t)||Gn(e,t,"");let r=e.agents?.get(t);return r&&{id:t,label:r.label}}function fz(e){return(e.trim().split(`
66
- `)[0]??"").slice(0,200)}function Ge(e){return!!e&&e.length<=200&&/^[A-Za-z0-9][\w.:/@+-]*$/.test(e)}function Ma(e){let t={...Ge(e?.model)&&{model:e.model},...Ge(e?.effort)&&{effort:e.effort}};return t.model||t.effort?t:void 0}function qy(e,t){let r=Ma(t);return r&&e.modelArgs?e.modelArgs(r):[]}function zt(e,t,r=2e4){return new Promise(o=>{nm(e,t,{timeout:r,maxBuffer:4*1024*1024,shell:process.platform==="win32",env:We()},(n,i)=>{o(n?null:i)})})}function vz(e){let t=e.replace(/\s+/g," "),r=Ry(t,"--model <model>","(e.g. ")?.match(/'[a-z0-9-]+'/g)?.map(n=>n.slice(1,-1));if(!r?.length)return;let o=Ry(t,"--effort <level>","(")?.split(",").map(n=>n.trim()).filter(Ge)??[];return[...r,...r.includes("haiku")?[]:["haiku"]].map(n=>({id:n,name:n[0].toUpperCase()+n.slice(1),efforts:n==="haiku"?[]:o}))}function Ry(e,t,r){let o=e.indexOf(t);if(o<0)return;let n=e.slice(o+t.length,o+t.length+400),i=n.indexOf(r),a=i<0?-1:n.indexOf(")",i+r.length);return a<0?void 0:n.slice(i+r.length,a)}function yz(e){try{let{models:t}=JSON.parse(e);if(!Array.isArray(t))return;let r=t.flatMap(o=>{if(typeof o.slug!="string"||!Ge(o.slug)||o.visibility==="hide")return[];let i=(Array.isArray(o.supported_reasoning_levels)?o.supported_reasoning_levels:[]).map(a=>a?.effort).filter(a=>typeof a=="string"&&Ge(a));return[{id:o.slug,name:typeof o.display_name=="string"?o.display_name:o.slug,efforts:i}]});return r.length?r.slice(0,100):void 0}catch{return}}function rm(e){let t=e.split(/\r?\n/).flatMap(r=>{let o=r.trim(),n=o.indexOf(" "),i=n>=0?n:o.indexOf(" - "),a=i>=0?o.slice(0,i).trim():o,s=i>=0?o.slice(i+(n>=0?1:3)).trim():"";return!Ge(a)||/^(available|fetching|loading)$/i.test(a)||a.endsWith(":")?[]:[{id:a,name:s||a,efforts:[]}]});return t.length?t.slice(0,100):void 0}var Oe="myrel",bz="mcp__myrel__approve_access",$z=900*1e3,_z=1e4,Ea="MYREL_MCP_TOKEN";function ct(e){return process.platform==="win32"?`"${e}"`:e}async function Ra(e,t,r){let o=se(e,t);return await Ca(o,JSON.stringify(r),{mode:384}),process.platform==="win32"?`"${o}"`:o}var My=["ssh","scp","sftp","rsync"].map(e=>`Bash(${e}:*)`),xz=["~/.ssh/**","~/.myrel-runner/ssh/**"].flatMap(e=>[`Read(${e})`,`Edit(${e})`]),kz={id:"claude",bin:"claude",args:({access:e,resume:t,extra:r=[],dirs:o=[],asks:n,stream:i})=>["-p","--output-format","stream-json","--verbose",...i?["--input-format","stream-json","--replay-user-messages"]:[],"--permission-mode",{read:"plan",edit:"acceptEdits",auto:"auto",full:n?"acceptEdits":"bypassPermissions"}[e],...o.flatMap(a=>["--add-dir",ct(a)]),...n?["--permission-prompt-tool",bz]:[],...t?["--resume",t]:[],...r],async agent({url:e,token:t,dir:r,connectors:o=[],skills:n,asks:i,access:a}){let s={Authorization:`Bearer ${t}`},u={[Oe]:{type:"http",url:e,headers:s,alwaysLoad:!0}};for(let m of o)u[m.name]=m.transport==="http"?{type:"http",url:m.url,headers:s}:{type:"stdio",command:m.command,args:m.args,env:m.env};let l=await Ra(r,"mcp.json",{mcpServers:u}),d=[Oe,...o.map(m=>m.name)].map(m=>`mcp__${m}`);i&&a==="full"&&d.push("Bash","WebFetch","WebSearch");let p=await Ra(r,"settings.json",{permissions:{...i&&{ask:My},deny:xz}}),f=n?["--plugin-dir",ct(n.plugin),"--add-dir",ct(n.dir)]:[];return{args:["--mcp-config",l,"--strict-mcp-config","--allowedTools",d.join(","),"--disallowedTools",["Bash(gh pr create:*)",...i?[]:My].join(","),"--settings",p,...f],env:{ENABLE_CLAUDEAI_MCP_SERVERS:"false",...!process.env.MCP_TIMEOUT&&{MCP_TIMEOUT:String(_z)},...i&&{MCP_TOOL_TIMEOUT:String($z)}}}},streamInput:!0,line(e,t){let r=qn(e);if(!r)return;t.claudeStream?.receive(r),typeof r.session_id=="string"&&(t.sessionId=r.session_id),r.type==="system"&&typeof r.model=="string"&&(t.model=r.model),r.type==="rate_limit_event"&&(t.limits=Oy(r.rate_limit_info,t.limits));let o=typeof r.parent_tool_use_id=="string"&&r.parent_tool_use_id?r.parent_tool_use_id:void 0;if(r.type==="assistant"){let n=r.message??{};if(typeof n.model=="string"&&!o&&(t.model=n.model),typeof n.id=="string"&&n.usage&&!t.counted?.has(n.id)){(t.counted??=new Set).add(n.id);let a=By(n.usage);sm(t,a),o&&Da(t,o,a.inputTokens+a.outputTokens,typeof n.model=="string"?n.model:void 0)}let i=n.content??[];for(let a of i)if(a.type==="tool_use"){let s=a.input??{};if(Fz.has(String(a.name))&&typeof a.id=="string"){let u=typeof s.subagent_type=="string"?s.subagent_type:"Agent",l=typeof s.description=="string"?s.description:"";Gn(t,a.id,u,l,{background:s.run_in_background===!0})}else oi(t,It(String(a.name),a.input),o)}else a.type==="text"&&typeof a.text=="string"&&a.text.trim()&&oi(t,ut(a.text),o)}if(r.type==="user"){let n=(r.message??{}).content;for(let i of Array.isArray(n)?n:[]){let a=i.type==="tool_result"&&typeof i.tool_use_id=="string"?t.agents?.get(i.tool_use_id):void 0;a&&!a.background&&St(t,i.tool_use_id,i.is_error!==!0,Vz(i.content))}}if(r.type==="system"&&r.subtype==="task_notification"&&typeof r.tool_use_id=="string"){let n=typeof r.summary=="string"?r.summary:"";St(t,r.tool_use_id,r.status==="completed",n)}if(r.type==="result"){if(r.usage){let n=By(r.usage),i=t.usage??{inputTokens:0,outputTokens:0};t.usage={inputTokens:Math.max(i.inputTokens,n.inputTokens),outputTokens:Math.max(i.outputTokens,n.outputTokens)}}t.result=typeof r.result=="string"?r.result:"",t.failed=r.is_error===!0||typeof r.subtype=="string"&&r.subtype!=="success"}},models:async()=>vz(await zt("claude",["--help"])??""),modelArgs:({model:e,effort:t})=>[...e?["--model",e]:[],...t?["--effort",t]:[]]},Ly={read:"read-only",edit:"workspace-write",auto:"workspace-write",full:"danger-full-access"},wz={id:"codex",bin:"codex",args:({access:e,resume:t,extra:r=[],dirs:o=[]})=>["exec","--json","--skip-git-repo-check","--sandbox",Ly[e],...o.flatMap(n=>["--add-dir",ct(n)]),...r,...t?["resume",t]:[],"-"],agent:async({url:e,token:t,connectors:r=[],access:o})=>{let n=s=>["-c",`mcp_servers.${s}.default_tools_approval_mode="approve"`],i=(s,u)=>["-c",`mcp_servers.${s}.url=${JSON.stringify(u)}`,"-c",`mcp_servers.${s}.bearer_token_env_var=${JSON.stringify(Ea)}`,...n(s)],a=i(Oe,e);for(let s of r){if(s.transport==="http"){a.push(...i(s.name,s.url));continue}let u=Object.entries(s.env).map(([l,d])=>`${l} = ${JSON.stringify(d)}`);a.push("-c",`mcp_servers.${s.name}.command=${JSON.stringify(s.command)}`,"-c",`mcp_servers.${s.name}.args=${JSON.stringify(s.args)}`),u.length&&a.push("-c",`mcp_servers.${s.name}.env={ ${u.join(", ")} }`),a.push(...n(s.name))}return o&&o!=="read"&&a.push("-c",'apps._default.default_tools_approval_mode="approve"'),{args:a,env:{[Ea]:t}}},appServer:({access:e,dirs:t,asks:r})=>({...t.length&&{config:{"sandbox_workspace_write.writable_roots":t}},sandbox:Ly[e],approvalPolicy:r&&(e==="edit"||e==="auto")?"on-request":"never"}),line(e,t){if(t.appServer)return t.appServer.receive(e);let r=qn(e);if(!r)return;r.type==="thread.started"&&typeof r.thread_id=="string"&&(t.sessionId=r.thread_id);let o=r.item;if(o?.type==="command_execution"&&typeof o.command=="string"&&(t.progress=ut(`$ ${Jn(o.command)}`)),r.type==="item.completed"&&o?.type==="agent_message"&&typeof o.text=="string"&&(t.result=o.text,t.progress=ut(o.text)),r.type==="turn.completed"&&r.usage){let i=r.usage;sm(t,{inputTokens:re(i.input_tokens),outputTokens:re(i.output_tokens)})}let n=r.error?.message??r.message;r.type==="error"&&typeof n=="string"&&(t.error=n),r.type==="turn.failed"&&(t.failed=!0,t.result=typeof n=="string"?n:t.error),r.type==="turn.completed"&&(t.failed=!1)},limits:e=>Na(e.sessionId),models:async()=>yz(await zt("codex",["debug","models"])??""),modelArgs:({model:e,effort:t})=>[...e?["-m",e]:[],...t?["-c",`model_reasoning_effort=${JSON.stringify(t)}`]:[]]},Sz="(myrel-runner: in this run you cannot run shell commands, open web pages or use any tool that needs approval: asking for one ends your run at once, with no answer. Read and edit the files here and use Myrel's tools. If a command is essential, say so in a reply: it needs full access on this computer, which the person sets in Myrel > Devices.)",Iz={id:"antigravity",bin:"agy",args:({access:e,resume:t,extra:r=[],dirs:o=[]})=>["--output-format","stream-json","--input-format","stream-json",...{read:["--mode","plan"],edit:["--mode","accept-edits"],auto:["--mode","accept-edits"],full:["--dangerously-skip-permissions"]}[e],...o.flatMap(n=>["--add-dir",ct(n)]),...t?["--conversation",t]:[],...r],input:(e,t)=>{let r=t==="full"?e:`${e}
66
+ `)[0]??"").slice(0,200)}function Ge(e){return!!e&&e.length<=200&&/^[A-Za-z0-9][\w.:/@+-]*$/.test(e)}function Ma(e){let t={...Ge(e?.model)&&{model:e.model},...Ge(e?.effort)&&{effort:e.effort}};return t.model||t.effort?t:void 0}function qy(e,t){let r=Ma(t);return r&&e.modelArgs?e.modelArgs(r):[]}function zt(e,t,r=2e4){return new Promise(o=>{nm(e,t,{timeout:r,maxBuffer:4*1024*1024,shell:process.platform==="win32",env:We()},(n,i)=>{o(n?null:i)})})}function vz(e){let t=e.replace(/\s+/g," "),r=Ry(t,"--model <model>","(e.g. ")?.match(/'[a-z0-9-]+'/g)?.map(n=>n.slice(1,-1));if(!r?.length)return;let o=Ry(t,"--effort <level>","(")?.split(",").map(n=>n.trim()).filter(Ge)??[];return[...r,...r.includes("haiku")?[]:["haiku"]].map(n=>({id:n,name:n[0].toUpperCase()+n.slice(1),efforts:n==="haiku"?[]:o}))}function Ry(e,t,r){let o=e.indexOf(t);if(o<0)return;let n=e.slice(o+t.length,o+t.length+400),i=n.indexOf(r),a=i<0?-1:n.indexOf(")",i+r.length);return a<0?void 0:n.slice(i+r.length,a)}function yz(e){try{let{models:t}=JSON.parse(e);if(!Array.isArray(t))return;let r=t.flatMap(o=>{if(typeof o.slug!="string"||!Ge(o.slug)||o.visibility==="hide")return[];let i=(Array.isArray(o.supported_reasoning_levels)?o.supported_reasoning_levels:[]).map(a=>a?.effort).filter(a=>typeof a=="string"&&Ge(a));return[{id:o.slug,name:typeof o.display_name=="string"?o.display_name:o.slug,efforts:i}]});return r.length?r.slice(0,100):void 0}catch{return}}function rm(e){let t=e.split(/\r?\n/).flatMap(r=>{let o=r.trim(),n=o.indexOf(" "),i=n>=0?n:o.indexOf(" - "),a=i>=0?o.slice(0,i).trim():o,s=i>=0?o.slice(i+(n>=0?1:3)).trim():"";return!Ge(a)||/^(available|fetching|loading)$/i.test(a)||a.endsWith(":")?[]:[{id:a,name:s||a,efforts:[]}]});return t.length?t.slice(0,100):void 0}var Oe="myrel",bz="mcp__myrel__approve_access",$z=900*1e3,_z=1e4,Ea="MYREL_MCP_TOKEN";function ct(e){return process.platform==="win32"?`"${e}"`:e}async function Ra(e,t,r){let o=se(e,t);return await Ca(o,JSON.stringify(r),{mode:384}),process.platform==="win32"?`"${o}"`:o}var My=["ssh","scp","sftp","rsync"].map(e=>`Bash(${e}:*)`),xz=["~/.ssh/**","~/.myrel-runner/ssh/**"].flatMap(e=>[`Read(${e})`,`Edit(${e})`]),kz={id:"claude",bin:"claude",args:({access:e,resume:t,extra:r=[],dirs:o=[],asks:n,stream:i})=>["-p","--output-format","stream-json","--verbose",...i?["--input-format","stream-json","--replay-user-messages"]:[],"--permission-mode",{read:"plan",edit:"acceptEdits",auto:"auto",full:n?"acceptEdits":"bypassPermissions"}[e],...o.flatMap(a=>["--add-dir",ct(a)]),...n?["--permission-prompt-tool",bz]:[],...t?["--resume",t]:[],...r],async agent({url:e,token:t,dir:r,connectors:o=[],skills:n,asks:i,access:a}){let s={Authorization:`Bearer ${t}`},u={[Oe]:{type:"http",url:e,headers:s,alwaysLoad:!0}};for(let m of o)u[m.name]=m.transport==="http"?{type:"http",url:m.url,headers:s}:{type:"stdio",command:m.command,args:m.args,env:m.env};let l=await Ra(r,"mcp.json",{mcpServers:u}),d=[Oe,...o.map(m=>m.name)].map(m=>`mcp__${m}`);i&&a==="full"&&d.push("Bash","WebFetch","WebSearch");let p=await Ra(r,"settings.json",{permissions:{...i&&{ask:My},deny:xz}}),f=n?["--plugin-dir",ct(n.plugin),"--add-dir",ct(n.dir)]:[];return{args:["--mcp-config",l,"--strict-mcp-config","--allowedTools",d.join(","),"--disallowedTools",["Bash(gh pr create:*)",...i?[]:My].join(","),"--settings",p,...f],env:{ENABLE_CLAUDEAI_MCP_SERVERS:"false",...!process.env.MCP_TIMEOUT&&{MCP_TIMEOUT:String(_z)},...i&&{MCP_TOOL_TIMEOUT:String($z)}}}},streamInput:!0,line(e,t){let r=qn(e);if(!r)return;t.claudeStream?.receive(r),typeof r.session_id=="string"&&(t.sessionId=r.session_id),r.type==="system"&&typeof r.model=="string"&&(t.model=r.model),r.type==="rate_limit_event"&&(t.limits=Oy(r.rate_limit_info,t.limits));let o=typeof r.parent_tool_use_id=="string"&&r.parent_tool_use_id?r.parent_tool_use_id:void 0;if(r.type==="assistant"){let n=r.message??{};if(typeof n.model=="string"&&!o&&(t.model=n.model),typeof n.id=="string"&&n.usage&&!t.counted?.has(n.id)){(t.counted??=new Set).add(n.id);let a=By(n.usage);sm(t,a),o&&Da(t,o,a.inputTokens+a.outputTokens,typeof n.model=="string"?n.model:void 0)}let i=n.content??[];for(let a of i)if(a.type==="tool_use"){let s=a.input??{};if(Vz.has(String(a.name))&&typeof a.id=="string"){let u=typeof s.subagent_type=="string"?s.subagent_type:"Agent",l=typeof s.description=="string"?s.description:"";Gn(t,a.id,u,l,{background:s.run_in_background===!0})}else oi(t,It(String(a.name),a.input),o)}else a.type==="text"&&typeof a.text=="string"&&a.text.trim()&&oi(t,ut(a.text),o)}if(r.type==="user"){let n=(r.message??{}).content;for(let i of Array.isArray(n)?n:[]){let a=i.type==="tool_result"&&typeof i.tool_use_id=="string"?t.agents?.get(i.tool_use_id):void 0;a&&!a.background&&St(t,i.tool_use_id,i.is_error!==!0,Kz(i.content))}}if(r.type==="system"&&r.subtype==="task_notification"&&typeof r.tool_use_id=="string"){let n=typeof r.summary=="string"?r.summary:"";St(t,r.tool_use_id,r.status==="completed",n)}if(r.type==="result"){if(r.usage){let n=By(r.usage),i=t.usage??{inputTokens:0,outputTokens:0};t.usage={inputTokens:Math.max(i.inputTokens,n.inputTokens),outputTokens:Math.max(i.outputTokens,n.outputTokens)}}t.result=typeof r.result=="string"?r.result:"",t.failed=r.is_error===!0||typeof r.subtype=="string"&&r.subtype!=="success"}},models:async()=>vz(await zt("claude",["--help"])??""),modelArgs:({model:e,effort:t})=>[...e?["--model",e]:[],...t?["--effort",t]:[]]},Ly={read:"read-only",edit:"workspace-write",auto:"workspace-write",full:"danger-full-access"},wz={id:"codex",bin:"codex",args:({access:e,resume:t,extra:r=[],dirs:o=[]})=>["exec","--json","--skip-git-repo-check","--sandbox",Ly[e],...o.flatMap(n=>["--add-dir",ct(n)]),...r,...t?["resume",t]:[],"-"],agent:async({url:e,token:t,connectors:r=[],access:o})=>{let n=s=>["-c",`mcp_servers.${s}.default_tools_approval_mode="approve"`],i=(s,u)=>["-c",`mcp_servers.${s}.url=${JSON.stringify(u)}`,"-c",`mcp_servers.${s}.bearer_token_env_var=${JSON.stringify(Ea)}`,...n(s)],a=i(Oe,e);for(let s of r){if(s.transport==="http"){a.push(...i(s.name,s.url));continue}let u=Object.entries(s.env).map(([l,d])=>`${l} = ${JSON.stringify(d)}`);a.push("-c",`mcp_servers.${s.name}.command=${JSON.stringify(s.command)}`,"-c",`mcp_servers.${s.name}.args=${JSON.stringify(s.args)}`),u.length&&a.push("-c",`mcp_servers.${s.name}.env={ ${u.join(", ")} }`),a.push(...n(s.name))}return o&&o!=="read"&&a.push("-c",'apps._default.default_tools_approval_mode="approve"'),{args:a,env:{[Ea]:t}}},appServer:({access:e,dirs:t,asks:r})=>({...t.length&&{config:{"sandbox_workspace_write.writable_roots":t}},sandbox:Ly[e],approvalPolicy:r&&(e==="edit"||e==="auto")?"on-request":"never"}),line(e,t){if(t.appServer)return t.appServer.receive(e);let r=qn(e);if(!r)return;r.type==="thread.started"&&typeof r.thread_id=="string"&&(t.sessionId=r.thread_id);let o=r.item;if(o?.type==="command_execution"&&typeof o.command=="string"&&(t.progress=ut(`$ ${Jn(o.command)}`)),r.type==="item.completed"&&o?.type==="agent_message"&&typeof o.text=="string"&&(t.result=o.text,t.progress=ut(o.text)),r.type==="turn.completed"&&r.usage){let i=r.usage;sm(t,{inputTokens:re(i.input_tokens),outputTokens:re(i.output_tokens)})}let n=r.error?.message??r.message;r.type==="error"&&typeof n=="string"&&(t.error=n),r.type==="turn.failed"&&(t.failed=!0,t.result=typeof n=="string"?n:t.error),r.type==="turn.completed"&&(t.failed=!1)},limits:e=>Na(e.sessionId),models:async()=>yz(await zt("codex",["debug","models"])??""),modelArgs:({model:e,effort:t})=>[...e?["-m",e]:[],...t?["-c",`model_reasoning_effort=${JSON.stringify(t)}`]:[]]},Sz="(myrel-runner: in this run you cannot run shell commands, open web pages or use any tool that needs approval: asking for one ends your run at once, with no answer. Read and edit the files here and use Myrel's tools. If a command is essential, say so in a reply: it needs full access on this computer, which the person sets in Myrel > Devices.)",Iz={id:"antigravity",bin:"agy",args:({access:e,resume:t,extra:r=[],dirs:o=[]})=>["--output-format","stream-json","--input-format","stream-json",...{read:["--mode","plan"],edit:["--mode","accept-edits"],auto:["--mode","accept-edits"],full:["--dangerously-skip-permissions"]}[e],...o.flatMap(n=>["--add-dir",ct(n)]),...t?["--conversation",t]:[],...r],input:(e,t)=>{let r=t==="full"?e:`${e}
67
67
 
68
68
  ${Sz}`;return`${JSON.stringify({event:"user",message:{content:r}})}
69
69
  `},async agent({url:e,token:t,dir:r,connectors:o=[],skills:n}){await Sy(Oe);let i={token:t,servers:[{transport:"http",name:Oe,url:e},...o]},a=await Ra(r,"bridge.json",i);return{args:n?["--add-dir",ct(n.dir)]:[],env:{[wy]:a.replace(/^"|"$/g,"")}}},line(e,t){let r=qn(e);if(!r)return;typeof r.conversation_id=="string"&&r.conversation_id&&(t.sessionId=r.conversation_id);let o=r.init;if(r.event==="init"&&typeof o?.model=="string"&&(t.model=o.model),r.event==="step_update"){let n=r.step_update??{},i=n.tool_info;if(n.step_type==="tool"&&n.state==="ACTIVE"){let a=typeof i?.name=="string"?i.name:n.tool_name;typeof a=="string"&&(t.progress=It(a,i?.parameters))}n.step_type==="agent_response"&&typeof n.text_delta=="string"&&(t.draft=n.step_index===t.draftStep?(t.draft??"")+n.text_delta:n.text_delta,t.draftStep=n.step_index,t.draft.trim()&&(t.progress=ut(t.draft)))}if(r.event==="result"){let n=r.result??{};typeof n.conversation_id=="string"&&n.conversation_id&&(t.sessionId=n.conversation_id);let i=n.usage??{},a=re(i.output_tokens)+re(i.thinking_tokens),s=Math.max(re(i.input_tokens),re(i.total_tokens)-a);(s||a)&&(t.usage={inputTokens:s,outputTokens:a}),t.failed=n.status!=="SUCCESS",t.result=t.failed&&typeof n.error=="string"&&n.error?n.error:typeof n.response=="string"?n.response:"";let u=Array.isArray(n.denied_actions)?n.denied_actions:[];if(u.length&&!t.result.trim()){let l=[...new Set(u.map(d=>String(d.action??"a tool")))].join(", ");t.failed=!0,t.result=`Antigravity CLI stopped: a step needed the "${l}" permission, which it cannot ask for when Myrel runs it. Set this computer's access to full in Myrel > Devices, or allow it under permissions.allow in ~/.gemini/antigravity-cli/settings.json (for example command(git)).`}}},models:async()=>rm(await zt("agy",["models"],3e4)??""),modelArgs:({model:e})=>e?["--model",e]:[]},Hy={read:{edit:"deny",bash:"deny"},edit:{edit:"allow",bash:"deny"},auto:{edit:"allow",bash:"deny"},full:{edit:"allow",bash:"allow"}},zz={id:"opencode",bin:"opencode",args:({access:e,resume:t,extra:r=[]})=>["run","--format","json",...e==="full"?["--auto"]:[],...t?["--session",t]:[],...r],async agent({url:e,token:t,connectors:r=[],skills:o,access:n="edit",dirs:i=[]}){let a=await om("opencode"),s={Authorization:`Bearer {env:${Ea}}`},u={[Oe]:{type:"remote",url:e,headers:s,oauth:!1}};for(let p of r)u[p.name]=p.transport==="http"?{type:"remote",url:p.url,headers:s,oauth:!1}:{type:"local",command:[p.command,...p.args],environment:p.env};let l=[...i,...o?[o.dir]:[]],d;if(Xy(a)>=2)d=jz(u,n,l,o?.dir);else{let p={...Hy[n]};for(let f of Object.keys(u))p[`${f}_*`]="allow";l.length&&(p.external_directory=Object.fromEntries(l.flatMap(f=>[[f,"allow"],[se(f,"*"),"allow"]]))),d={mcp:u,permission:p,...o&&{skills:{paths:[o.dir]}},experimental:{continue_loop_on_deny:!0}}}return{args:Pz(a),env:{OPENCODE_CONFIG_CONTENT:JSON.stringify(d),[Ea]:t}}},line(e,t){let r=qn(e);if(!r)return;typeof r.sessionID=="string"&&r.sessionID&&(t.sessionId=r.sessionID);let o=r.part??{};if(r.type==="tool_use"&&typeof o.tool=="string"&&(t.progress=It(o.tool,o.state?.input)),r.type==="text"&&typeof o.text=="string"&&o.text.trim()&&(t.draft=o.messageID===t.draftStep&&t.draft?`${t.draft}
70
70
 
71
71
  ${o.text}`:o.text,t.draftStep=o.messageID,t.result=t.draft,t.progress=ut(o.text)),r.type==="step_finish"){let n=o.tokens??{},i=n.cache??{};sm(t,{inputTokens:re(n.input)+re(i.read)+re(i.write),outputTokens:re(n.output)+re(n.reasoning)})}if(r.type==="error"){let n=r.error??{},i=[n.data?.message,n.message,n.name].find(a=>typeof a=="string"&&a);t.failed=!0,t.result=typeof i=="string"?i:"opencode reported an error."}},models:async()=>rm(await zt("opencode",["models"])??""),modelArgs:({model:e})=>e?["--model",e]:[]};function Xy(e){return Number(/\d+/.exec(e??"")?.[0]??0)}function Pz(e){return Xy(e)>=2?["--standalone"]:[]}function jz(e,t,r,o){let n=[];t!=="full"&&n.push({action:"external_directory",resource:"*",effect:"deny"});for(let s of r)n.push({action:"external_directory",resource:s,effect:"allow"}),n.push({action:"external_directory",resource:se(s,"*"),effect:"allow"});let i=Hy[t];n.push({action:"edit",resource:"*",effect:i.edit}),n.push({action:"shell",resource:"*",effect:i.bash});for(let s of Object.keys(e))n.push({action:`${s}_*`,resource:"*",effect:"allow"});let a={};for(let[s,u]of Object.entries(e))a[s]={...u,codemode:!1};return{mcp:{servers:a},permissions:n,...o&&{skills:[o]}}}var Zy={read:"(myrel-runner: this run may only read. Do not change files or run commands that change anything: steps that need approval are declined.)",edit:"(myrel-runner: steps that need approval, such as dangerous commands or sensitive files, are declined in this run. Do not run commands that change anything outside this folder.)",auto:"(myrel-runner: steps that need approval, such as dangerous commands or sensitive files, are declined in this run. Do not run commands that change anything outside this folder.)",full:null};function Yy({url:e,token:t,connectors:r=[]}){let o=[{name:"Authorization",value:`Bearer ${t}`}],n=[{type:"http",name:Oe,url:e,headers:o}];for(let i of r)n.push(i.transport==="http"?{type:"http",name:i.name,url:i.url,headers:o}:{name:i.name,command:i.command,args:i.args,env:Object.entries(i.env).map(([a,s])=>({name:a,value:s}))});return n}var Az={id:"hermes",bin:"hermes",args:({extra:e=[]})=>["acp",...e],acp:e=>({mode:{read:"default",edit:"accept_edits",auto:"accept_edits",full:"dont_ask"}[e],allow:e==="full"}),input:(e,t)=>Zy[t]?`${e}
72
72
 
73
- ${Zy[t]}`:e,agent:async e=>({args:[],mcpServers:Yy(e)}),line:(e,t)=>t.acp?.receive(e),isMine:e=>e.startsWith("Hermes Agent")},Tz={read:["--mode","ask"],edit:["--sandbox","enabled"],auto:["--sandbox","enabled"],full:["--force","--sandbox","disabled"]},Oz={id:"cursor",bin:"cursor-agent",args:({access:e,resume:t,extra:r=[],dirs:o=[]})=>["-p","--output-format","stream-json","--trust",...Tz[e],...o.flatMap(n=>["--add-dir",ct(n)]),...t?["--resume",t]:[],...r],async agent({url:e,token:t,dir:r,connectors:o=[],skills:n}){let i=se(r,Oe);await Ua(se(i,".cursor-plugin"),{recursive:!0}),await Ca(se(i,".cursor-plugin","plugin.json"),JSON.stringify({name:Oe,description:"Myrel's tools for this run.",version:"1.0.0"}));let a={Authorization:`Bearer ${t}`},s={[Oe]:{url:e,headers:a}};for(let d of o)s[d.name]=d.transport==="http"?{url:d.url,headers:a}:{command:d.command,args:d.args,env:d.env};await Ra(i,"mcp.json",{mcpServers:s}),n&&(await Ua(se(n.plugin,".cursor-plugin"),{recursive:!0}),await Ca(se(n.plugin,".cursor-plugin","plugin.json"),JSON.stringify({name:`${Oe}-skills`,description:"Skills added in Myrel for this run.",version:"1.0.0"})));let u=await Dz(se(r,"cursor-config"),Object.keys(s).map(d=>`Mcp(plugin-${Oe}-${d}:*)`));return{args:["--approve-mcps",...[i,...n?[n.plugin]:[]].flatMap(d=>["--plugin-dir",ct(d)])],env:{CURSOR_CONFIG_DIR:u}}},line(e,t){let r=qn(e);if(r){if(typeof r.session_id=="string"&&r.session_id&&(t.sessionId=r.session_id),r.type==="system"&&typeof r.model=="string"&&(t.model=r.model),r.type==="tool_call"&&r.subtype==="started"){let o=r.tool_call??{},[n,i]=Object.entries(o).find(([s])=>s.endsWith("ToolCall")||s==="function")??[],a=i?.args;n==="mcpToolCall"&&typeof a?.toolName=="string"?t.progress=It(a.toolName,a.args):n==="function"&&typeof i?.name=="string"?t.progress=It(i.name,tb(i.arguments)):n&&(t.progress=It(n.replace(/ToolCall$/,""),a))}if(r.type==="assistant"){let n=(r.message?.content??[]).map(i=>i.type==="text"&&typeof i.text=="string"?i.text:"").join("");n.trim()&&(t.draft=n,t.progress=ut(n))}if(r.type==="result"){t.result=t.draft??(typeof r.result=="string"?r.result:""),t.failed=r.is_error===!0||r.subtype!=="success";let o=r.usage??{},n=re(o.inputTokens)+re(o.cacheReadTokens)+re(o.cacheWriteTokens);(n||re(o.outputTokens))&&(t.usage={inputTokens:n,outputTokens:re(o.outputTokens)})}}},models:async()=>rm(await zt("cursor-agent",["models"])??""),modelArgs:({model:e})=>e?["--model",e]:[]};function Nz(){return process.env.CURSOR_CONFIG_DIR?.trim()||(process.env.XDG_CONFIG_HOME?.trim()?se(process.env.XDG_CONFIG_HOME,"cursor"):se(Gy(),".cursor"))}async function Dz(e,t,r=Nz()){await Ua(e,{recursive:!0});let o=await Wy(se(r,"cli-config.json"),"utf8").then(JSON.parse,()=>null)??{version:1},n=o.permissions??{};return o.permissions={...n,allow:[...Array.isArray(n.allow)?n.allow:[],...t]},await Ca(se(e,"cli-config.json"),JSON.stringify(o),{mode:384}),await Ua(se(r,"chats"),{recursive:!0}).then(()=>hz(se(r,"chats"),se(e,"chats"),process.platform==="win32"?"junction":"dir")).catch(()=>{}),e}var Uz={read:["--approval-mode","never","--disable-write","--disable-shell"],edit:["--approval-mode","never","--trust-workspace"],auto:["--approval-mode","never","--trust-workspace"],full:["--yolo"]},Fy="MYREL_MCP_AUTH",Cz={id:"muse",bin:"muse",promptFile:!0,args:({access:e,resume:t,extra:r=[],promptFile:o})=>["exec","--json",...Uz[e],...t?["--session-id",t]:[],...r,...o?["--prompt-file",ct(o)]:[]],async agent({url:e,token:t,connectors:r=[]}){let o={[Fy]:`Bearer ${t}`},n={Authorization:`\${${Fy}}`},i=[[Oe,{url:e,headers:n}]];for(let[a,s]of r.entries()){if(s.transport==="http"){i.push([s.name,{url:s.url,headers:n}]);continue}let u=Object.entries(s.env).map(([l,d],p)=>{let f=`MYREL_MCP_${a}_${p}`;return o[f]=d,[l,`\${${f}}`]});i.push([s.name,{command:s.command,args:s.args,env:Object.fromEntries(u)}])}return{args:i.flatMap(([a,s])=>["-c",`mcpServers.${a}=${JSON.stringify(s)}`]),env:o}},line(e,t){let r=qn(e);if(!r)return;let o=r.stream;o?.kind==="session"&&typeof o.id=="string"&&o.id&&(t.sessionId=o.id);let n=r.payload??{};switch(r.payload_type){case"run.model.configured":typeof n.model_id=="string"&&(t.model=n.model_id);break;case"task.lifecycle.proposed":{let i=n.event?.task_kind;typeof i=="string"&&i.startsWith("tool.")&&(t.progress=It(i.slice(5),void 0),t.draft=void 0);break}case"tool.result":{let i=n.correlation_facts?.tool_name,a=n.edit_facts,s=typeof n.text=="string"&&n.text.startsWith("{")?tb(n.text)?.command:void 0;typeof s=="string"?t.progress=ut(`$ ${Jn(s)}`):typeof i=="string"&&(t.progress=It(i,a));break}case"run.output.delta":typeof n.text=="string"&&(t.draft=(t.draft??"")+n.text,t.draft.trim()&&(t.progress=ut(t.draft)));break;case"run.usage":{let i=Array.isArray(n.models)?n.models:[],a=i.reduce((u,l)=>u+re(l.input_tokens),0),s=i.reduce((u,l)=>u+re(l.output_tokens),0);(a||s)&&(t.usage={inputTokens:a,outputTokens:s});break}default:if(typeof r.payload_type=="string"&&r.payload_type.startsWith("run.terminal.")){t.failed=n.terminal!=="completed";let i=typeof n.text=="string"?n.text:"",a=typeof n.reason=="string"?n.reason:"";t.result=t.failed?i||a||`Muse Code stopped (${String(n.terminal??"failed")}).`:i||t.draft||""}}},isMine:e=>e.startsWith("Muse Code"),models:()=>Ez(),modelArgs:({model:e,effort:t})=>[...e?["--model",e]:[],...t?["--effort",t]:[]]};async function Ez(){let e=se(process.env.XDG_DATA_HOME?.trim()||se(Gy(),".local","share"),"muse","model-catalog"),t=await gz(e).catch(()=>[]),r=await Promise.all(t.filter(i=>i.endsWith(".json")).map(i=>Wy(se(e,i),"utf8").then(Rz,()=>{}))),o=new Set,n=r.flatMap(i=>i??[]).filter(i=>!o.has(i.id)&&o.add(i.id));return n.length?n:void 0}function Rz(e){try{let{rows:t}=JSON.parse(e);return Array.isArray(t)?t.flatMap(r=>{if(typeof r.model_id!="string"||!Ge(r.model_id)||r.visibility==="hidden")return[];let n=(Array.isArray(r.reasoning_effort_variants)?r.reasoning_effort_variants:[]).map(a=>a?.tier).filter(a=>typeof a=="string"&&Ge(a)),i=typeof r.display_label=="string"&&r.display_label?r.display_label:r.model_id;return[{id:r.model_id,name:i,efforts:n}]}):void 0}catch{return}}var Vy={read:"(myrel-runner: this run may only read. Do not change files, run commands that change anything, write a plan file or call ExitPlanMode: steps that need approval are declined. Answer with Myrel's tools.)",edit:"(myrel-runner: in this run shell commands and edits outside this folder's git repository are declined, as is anything else that needs approval. Read and edit the files here and use Myrel's tools. If a command is essential, say so in a reply: it needs full access on this computer, which the person sets in Myrel > Devices.)",auto:"(myrel-runner: in this run shell commands and edits outside this folder's git repository are declined, as is anything else that needs approval. Read and edit the files here and use Myrel's tools. If a command is essential, say so in a reply: it needs full access on this computer, which the person sets in Myrel > Devices.)",full:null},Mz={id:"kimi",bin:"kimi",args:({extra:e=[]})=>["acp",...e],acp:(e,t)=>({mode:{read:"plan",edit:"default",auto:"default",full:"auto"}[e],allow:e==="full",serverTools:r=>`mcp__${r}__`,config:[...t?.model?[{id:"model",value:t.model}]:[],...t?.effort?[{id:"thinking",value:t.effort}]:[]]}),input:(e,t)=>Vy[t]?`${e}
73
+ ${Zy[t]}`:e,agent:async e=>({args:[],mcpServers:Yy(e)}),line:(e,t)=>t.acp?.receive(e),isMine:e=>e.startsWith("Hermes Agent")},Tz={read:["--mode","ask"],edit:["--sandbox","enabled"],auto:["--sandbox","enabled"],full:["--force","--sandbox","disabled"]},Oz={id:"cursor",bin:"cursor-agent",args:({access:e,resume:t,extra:r=[],dirs:o=[]})=>["-p","--output-format","stream-json","--trust",...Tz[e],...o.flatMap(n=>["--add-dir",ct(n)]),...t?["--resume",t]:[],...r],async agent({url:e,token:t,dir:r,connectors:o=[],skills:n}){let i=se(r,Oe);await Ua(se(i,".cursor-plugin"),{recursive:!0}),await Ca(se(i,".cursor-plugin","plugin.json"),JSON.stringify({name:Oe,description:"Myrel's tools for this run.",version:"1.0.0"}));let a={Authorization:`Bearer ${t}`},s={[Oe]:{url:e,headers:a}};for(let d of o)s[d.name]=d.transport==="http"?{url:d.url,headers:a}:{command:d.command,args:d.args,env:d.env};await Ra(i,"mcp.json",{mcpServers:s}),n&&(await Ua(se(n.plugin,".cursor-plugin"),{recursive:!0}),await Ca(se(n.plugin,".cursor-plugin","plugin.json"),JSON.stringify({name:`${Oe}-skills`,description:"Skills added in Myrel for this run.",version:"1.0.0"})));let u=await Dz(se(r,"cursor-config"),Object.keys(s).map(d=>`Mcp(plugin-${Oe}-${d}:*)`));return{args:["--approve-mcps",...[i,...n?[n.plugin]:[]].flatMap(d=>["--plugin-dir",ct(d)])],env:{CURSOR_CONFIG_DIR:u}}},line(e,t){let r=qn(e);if(r){if(typeof r.session_id=="string"&&r.session_id&&(t.sessionId=r.session_id),r.type==="system"&&typeof r.model=="string"&&(t.model=r.model),r.type==="tool_call"&&r.subtype==="started"){let o=r.tool_call??{},[n,i]=Object.entries(o).find(([s])=>s.endsWith("ToolCall")||s==="function")??[],a=i?.args;n==="mcpToolCall"&&typeof a?.toolName=="string"?t.progress=It(a.toolName,a.args):n==="function"&&typeof i?.name=="string"?t.progress=It(i.name,tb(i.arguments)):n&&(t.progress=It(n.replace(/ToolCall$/,""),a))}if(r.type==="assistant"){let n=(r.message?.content??[]).map(i=>i.type==="text"&&typeof i.text=="string"?i.text:"").join("");n.trim()&&(t.draft=n,t.progress=ut(n))}if(r.type==="result"){t.result=t.draft??(typeof r.result=="string"?r.result:""),t.failed=r.is_error===!0||r.subtype!=="success";let o=r.usage??{},n=re(o.inputTokens)+re(o.cacheReadTokens)+re(o.cacheWriteTokens);(n||re(o.outputTokens))&&(t.usage={inputTokens:n,outputTokens:re(o.outputTokens)})}}},models:async()=>rm(await zt("cursor-agent",["models"])??""),modelArgs:({model:e})=>e?["--model",e]:[]};function Nz(){return process.env.CURSOR_CONFIG_DIR?.trim()||(process.env.XDG_CONFIG_HOME?.trim()?se(process.env.XDG_CONFIG_HOME,"cursor"):se(Gy(),".cursor"))}async function Dz(e,t,r=Nz()){await Ua(e,{recursive:!0});let o=await Wy(se(r,"cli-config.json"),"utf8").then(JSON.parse,()=>null)??{version:1},n=o.permissions??{};return o.permissions={...n,allow:[...Array.isArray(n.allow)?n.allow:[],...t]},await Ca(se(e,"cli-config.json"),JSON.stringify(o),{mode:384}),await Ua(se(r,"chats"),{recursive:!0}).then(()=>hz(se(r,"chats"),se(e,"chats"),process.platform==="win32"?"junction":"dir")).catch(()=>{}),e}var Uz={read:["--approval-mode","never","--disable-write","--disable-shell"],edit:["--approval-mode","never","--trust-workspace"],auto:["--approval-mode","never","--trust-workspace"],full:["--yolo"]},Cz=["--context-compaction-soft-threshold","0.15"],Fy="MYREL_MCP_AUTH",Ez={id:"muse",bin:"muse",promptFile:!0,args:({access:e,resume:t,extra:r=[],promptFile:o})=>["exec","--json",...Cz,...Uz[e],...t?["--session-id",t]:[],...r,...o?["--prompt-file",ct(o)]:[]],async agent({url:e,token:t,connectors:r=[]}){let o={[Fy]:`Bearer ${t}`},n={Authorization:`\${${Fy}}`},i=[[Oe,{url:e,headers:n}]];for(let[a,s]of r.entries()){if(s.transport==="http"){i.push([s.name,{url:s.url,headers:n}]);continue}let u=Object.entries(s.env).map(([l,d],p)=>{let f=`MYREL_MCP_${a}_${p}`;return o[f]=d,[l,`\${${f}}`]});i.push([s.name,{command:s.command,args:s.args,env:Object.fromEntries(u)}])}return{args:i.flatMap(([a,s])=>["-c",`mcpServers.${a}=${JSON.stringify(s)}`]),env:o}},line(e,t){let r=qn(e);if(!r)return;let o=r.stream;o?.kind==="session"&&typeof o.id=="string"&&o.id&&(t.sessionId=o.id);let n=r.payload??{};switch(r.payload_type){case"run.model.configured":typeof n.model_id=="string"&&(t.model=n.model_id);break;case"task.lifecycle.proposed":{let i=n.event?.task_kind;typeof i=="string"&&i.startsWith("tool.")&&(t.progress=It(i.slice(5),void 0),t.draft=void 0);break}case"tool.result":{let i=n.correlation_facts?.tool_name,a=n.edit_facts,s=typeof n.text=="string"&&n.text.startsWith("{")?tb(n.text)?.command:void 0;typeof s=="string"?t.progress=ut(`$ ${Jn(s)}`):typeof i=="string"&&(t.progress=It(i,a));break}case"run.output.delta":typeof n.text=="string"&&(t.draft=(t.draft??"")+n.text,t.draft.trim()&&(t.progress=ut(t.draft)));break;case"run.usage":{let i=Array.isArray(n.models)?n.models:[],a=i.reduce((u,l)=>u+re(l.input_tokens),0),s=i.reduce((u,l)=>u+re(l.output_tokens),0);(a||s)&&(t.usage={inputTokens:a,outputTokens:s});break}default:if(typeof r.payload_type=="string"&&r.payload_type.startsWith("run.terminal.")){t.failed=n.terminal!=="completed";let i=typeof n.text=="string"?n.text:"",a=typeof n.reason=="string"?n.reason:"";t.result=t.failed?i||a||`Muse Code stopped (${String(n.terminal??"failed")}).`:i||t.draft||""}}},isMine:e=>e.startsWith("Muse Code"),models:()=>Rz(),modelArgs:({model:e,effort:t})=>[...e?["--model",e]:[],...t?["--effort",t]:[]]};async function Rz(){let e=se(process.env.XDG_DATA_HOME?.trim()||se(Gy(),".local","share"),"muse","model-catalog"),t=await gz(e).catch(()=>[]),r=await Promise.all(t.filter(i=>i.endsWith(".json")).map(i=>Wy(se(e,i),"utf8").then(Mz,()=>{}))),o=new Set,n=r.flatMap(i=>i??[]).filter(i=>!o.has(i.id)&&o.add(i.id));return n.length?n:void 0}function Mz(e){try{let{rows:t}=JSON.parse(e);return Array.isArray(t)?t.flatMap(r=>{if(typeof r.model_id!="string"||!Ge(r.model_id)||r.visibility==="hidden")return[];let n=(Array.isArray(r.reasoning_effort_variants)?r.reasoning_effort_variants:[]).map(a=>a?.tier).filter(a=>typeof a=="string"&&Ge(a)),i=typeof r.display_label=="string"&&r.display_label?r.display_label:r.model_id;return[{id:r.model_id,name:i,efforts:n}]}):void 0}catch{return}}var Vy={read:"(myrel-runner: this run may only read. Do not change files, run commands that change anything, write a plan file or call ExitPlanMode: steps that need approval are declined. Answer with Myrel's tools.)",edit:"(myrel-runner: in this run shell commands and edits outside this folder's git repository are declined, as is anything else that needs approval. Read and edit the files here and use Myrel's tools. If a command is essential, say so in a reply: it needs full access on this computer, which the person sets in Myrel > Devices.)",auto:"(myrel-runner: in this run shell commands and edits outside this folder's git repository are declined, as is anything else that needs approval. Read and edit the files here and use Myrel's tools. If a command is essential, say so in a reply: it needs full access on this computer, which the person sets in Myrel > Devices.)",full:null},Lz={id:"kimi",bin:"kimi",args:({extra:e=[]})=>["acp",...e],acp:(e,t)=>({mode:{read:"plan",edit:"default",auto:"default",full:"auto"}[e],allow:e==="full",serverTools:r=>`mcp__${r}__`,config:[...t?.model?[{id:"model",value:t.model}]:[],...t?.effort?[{id:"thinking",value:t.effort}]:[]]}),input:(e,t)=>Vy[t]?`${e}
74
74
 
75
- ${Vy[t]}`:e,agent:async e=>({args:[],mcpServers:Yy(e)}),line:(e,t)=>t.acp?.receive(e),isMine:e=>/^v?\d+\.\d+/.test(e),models:async()=>Lz(await zt("kimi",["provider","list","--json"])??"")};function Lz(e){try{let{models:t}=JSON.parse(e);if(!t||typeof t!="object")return;let r=Object.entries(t).flatMap(([o,n])=>{if(!Ge(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"&&Ge(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 si={claude:kz,codex:wz,antigravity:Iz,opencode:zz,hermes:Az,cursor:Oz,muse:Cz,kimi:Mz},im=process.platform==="win32"?3e4:1e4;function om(e){return new Promise(t=>{nm(e,["--version"],{timeout:im,shell:process.platform==="win32",env:We()},(r,o)=>{t(r?null:ai(o)||null)})})}var Ky=new Map;async function Qy(e){if(process.env.MYREL_CODEX_EXEC==="1")return!1;let t=await om(e);if(!t)return!1;let r=Ky.get(t);return r||(r=zt(e,["app-server","--help"],1e4).then(o=>!!o?.includes("--listen")),Ky.set(t,r)),r}var Jy=new Map;async function eb(e){if(process.env.MYREL_CLAUDE_ONESHOT==="1")return!1;let t=await om(e);if(!t)return!1;let r=Jy.get(t);return r||(r=zt(e,["--help"],1e4).then(o=>!!o?.includes("--replay-user-messages")),Jy.set(t,r)),r}async function am(e){return await Ey().catch(()=>{}),(await Promise.all(Object.values(si).map(r=>new Promise(o=>{nm(r.bin,["--version"],{timeout:im,shell:process.platform==="win32",env:We(),windowsHide:!0},(n,i,a)=>{if(n||r.isMine&&!r.isMine(ai(i)))return e?.push({id:r.id,reason:n?Zz(n,a):`\`${r.bin} --version\` printed "${ai(i)}"`}),o(null);o({id:r.id,version:ai(i)||null})})})))).filter(r=>r!==null)}function Zz(e,t=""){return e.killed?`no answer in ${im/1e3}s`:e.code==="ENOENT"?"not on PATH":ai(t)||e.message.split(`
76
- `)[0]||"failed"}function re(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?Math.round(e):0}function By(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 sm(e,t){let r=e.usage??={inputTokens:0,outputTokens:0};r.inputTokens+=t.inputTokens,r.outputTokens+=t.outputTokens}function qn(e){if(!e.startsWith("{"))return null;try{return JSON.parse(e)}catch{return null}}function tb(e){if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return}}var Fz=new Set(["Agent","Task"]);function Vz(e){return typeof e=="string"?e:Array.isArray(e)?e.map(t=>t.type==="text"?String(t.text??""):"").filter(Boolean).join(`
75
+ ${Vy[t]}`:e,agent:async e=>({args:[],mcpServers:Yy(e)}),line:(e,t)=>t.acp?.receive(e),isMine:e=>/^v?\d+\.\d+/.test(e),models:async()=>Zz(await zt("kimi",["provider","list","--json"])??"")};function Zz(e){try{let{models:t}=JSON.parse(e);if(!t||typeof t!="object")return;let r=Object.entries(t).flatMap(([o,n])=>{if(!Ge(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"&&Ge(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 si={claude:kz,codex:wz,antigravity:Iz,opencode:zz,hermes:Az,cursor:Oz,muse:Ez,kimi:Lz},im=process.platform==="win32"?3e4:1e4;function om(e){return new Promise(t=>{nm(e,["--version"],{timeout:im,shell:process.platform==="win32",env:We()},(r,o)=>{t(r?null:ai(o)||null)})})}var Ky=new Map;async function Qy(e){if(process.env.MYREL_CODEX_EXEC==="1")return!1;let t=await om(e);if(!t)return!1;let r=Ky.get(t);return r||(r=zt(e,["app-server","--help"],1e4).then(o=>!!o?.includes("--listen")),Ky.set(t,r)),r}var Jy=new Map;async function eb(e){if(process.env.MYREL_CLAUDE_ONESHOT==="1")return!1;let t=await om(e);if(!t)return!1;let r=Jy.get(t);return r||(r=zt(e,["--help"],1e4).then(o=>!!o?.includes("--replay-user-messages")),Jy.set(t,r)),r}async function am(e){return await Ey().catch(()=>{}),(await Promise.all(Object.values(si).map(r=>new Promise(o=>{nm(r.bin,["--version"],{timeout:im,shell:process.platform==="win32",env:We(),windowsHide:!0},(n,i,a)=>{if(n||r.isMine&&!r.isMine(ai(i)))return e?.push({id:r.id,reason:n?Fz(n,a):`\`${r.bin} --version\` printed "${ai(i)}"`}),o(null);o({id:r.id,version:ai(i)||null})})})))).filter(r=>r!==null)}function Fz(e,t=""){return e.killed?`no answer in ${im/1e3}s`:e.code==="ENOENT"?"not on PATH":ai(t)||e.message.split(`
76
+ `)[0]||"failed"}function re(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?Math.round(e):0}function By(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 sm(e,t){let r=e.usage??={inputTokens:0,outputTokens:0};r.inputTokens+=t.inputTokens,r.outputTokens+=t.outputTokens}function qn(e){if(!e.startsWith("{"))return null;try{return JSON.parse(e)}catch{return null}}function tb(e){if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return}}var Vz=new Set(["Agent","Task"]);function Kz(e){return typeof e=="string"?e:Array.isArray(e)?e.map(t=>t.type==="text"?String(t.text??""):"").filter(Boolean).join(`
77
77
  `):""}function It(e,t){let r=t??{},o=r.command??r.file_path??r.filePath??r.path??r.pattern??r.description;return typeof o=="string"?ut(`${e}: ${o}`):e}function ut(e){return e.trim().slice(0,2e3)}function ai(e){return(e.trim().split(`
78
- `)[0]??"").slice(0,200)}import{readdir as Kz,realpath as cm,stat as nb}from"node:fs/promises";import{homedir as rb}from"node:os";import{dirname as Jz,isAbsolute as Bz,join as Wz,parse as Gz}from"node:path";var qz=1e3;async function ib(e){let t=rb(),r=await cm(e?ab(e):t),n=(await Kz(r,{withFileTypes:!0})).filter(u=>(u.isDirectory()||u.isSymbolicLink())&&!u.name.startsWith(".")).map(u=>({name:u.name,path:Wz(r,u.name)})),a=(await Promise.all(n.map(async u=>(await nb(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=Jz(r);return{path:r,parent:s===r?null:s,home:t,dirs:a.slice(0,qz)}}async function ob(e){let t=await cm(ab(e)).catch(()=>{throw new Error(`${e} does not exist on this computer.`)});if(!(await nb(t)).isDirectory())throw new Error(`${e} is not a folder.`);if(t===Gz(t).root||t===await cm(rb()))throw new Error("Pick a project folder, not your whole home folder or disk.");return t}function ab(e){if(!Bz(e))throw new Error(`${e} is not a full path.`);return e}import{watchFile as sj,unwatchFile as cj}from"node:fs";import{hostname as Um,platform as $$}from"node:os";import{access as Hz,constants as Xz,mkdtemp as tC,readdir as Yz,readFile as sb,realpath as Qz,rm as nC,stat as ub,writeFile as rC}from"node:fs/promises";import{tmpdir as oC,userInfo as e0}from"node:os";import{basename as um,delimiter as t0,dirname as La,join as Za}from"node:path";var n0="/proc/sys/kernel/apparmor_restrict_unprivileged_userns";function r0(e=lb(),t="/etc/apparmor.d"){return Za(t,`myrel-runner-${e}`)}function lb(){return e0().username.replace(/[^A-Za-z0-9_.-]/g,"_")||"user"}async function dm(e={}){let t=e.user??lb(),r=r0(t,e.profileDir),o={restricted:!1,applies:!1,binaries:[],blocked:[],file:r};if((e.platform??process.platform)!=="linux")return o;let n=await sb(e.restrict??n0,"utf8").catch(()=>null);if(n===null)return o;o.applies=!0,o.restricted=n.trim()==="1",o.binaries=await i0(e.env??process.env);let i=await sb(r,"utf8").catch(()=>"");return o.blocked=o.binaries.filter(a=>!i.includes(a0(a.attach))),o}async function i0(e=process.env){let t=[],r=await cb("muse",e);if(r){let n=La(r),i=(await Yz(n).catch(()=>[])).filter(a=>a.startsWith("muse-bin-")).sort();(um(r).startsWith("muse-bin-")||i.length)&&t.push({cli:"muse",path:um(r).startsWith("muse-bin-")?r:Za(n,i.at(-1)),attach:`${lm(n)}/muse-bin-*`})}let o=await cb("codex",e);if(o){let n=La(La(o)),i=Za(n,"codex-resources","bwrap");if(await o0(i)){let a=La(n);t.push({cli:"codex",path:i,attach:um(a)==="releases"?`${lm(a)}/*/codex-resources/bwrap`:lm(i)})}}return t}async function cb(e,t){for(let r of(t.PATH??"").split(t0)){if(!r)continue;let o=Za(r,e);try{if(await Hz(o,Xz.X_OK),!(await ub(o)).isFile())continue;return await Qz(o)}catch{}}}async function o0(e){return ub(e).then(t=>t.isFile(),()=>!1)}function lm(e){return e.replace(/[\\"*?[\]{}^]/g,t=>`\\${t}`)}function a0(e){return`"${e}" flags=(unconfined)`}function db(e,t){return e==="codex"?t!=="full":e==="muse"?t==="edit"||t==="auto":!1}async function pb(e,t){if(e!=="muse"&&e!=="codex")return null;let r=t??await dm();return!r.restricted||!r.blocked.some(o=>o.cli===e)?null:"(myrel-runner: on this computer Ubuntu's AppArmor blocks this CLI's sandbox, so every shell command fails with \"bwrap: loopback: Failed RTM_NEWADDR: Operation not permitted\". Do not retry commands or work around it. Read and edit files, use Myrel's tools, and tell the person to run `npx myrel-runner sandbox fix` once in a terminal on this computer (it asks for their sudo password), or to give this computer full access in Myrel > Devices.)"}function mb(e){return!e.restricted||!e.blocked.length?null:`Ubuntu's AppArmor blocks the sandbox of ${[...new Set(e.blocked.map(r=>r.cli==="muse"?"Muse Code":"Codex"))].join(" and ")}, so their commands fail below full access. Fix it once with \`myrel-runner sandbox fix\`.`}import{open as J0,realpath as Ob,stat as B0}from"node:fs/promises";import{isAbsolute as W0,join as G0,relative as q0,resolve as H0,sep as Tb}from"node:path";import{spawn as Z0}from"node:child_process";import{mkdtemp as Sb,realpath as Ib,rm as zb,writeFile as F0}from"node:fs/promises";import{tmpdir as Pb}from"node:os";import{join as fm}from"node:path";var Fa=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
- `)}};import{request as s0}from"node:http";import{request as c0}from"node:https";var W=e=>e&&typeof e=="object"?e:{},B=e=>typeof e=="string"&&e?e:void 0,Va=e=>typeof e=="number"&&Number.isFinite(e)&&e>0?Math.round(e):0,u0=e=>e.trim().slice(0,2e3),Ka=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,W(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=W(W(t).thread),o=B(r.id);if(!o)return this.fail("Codex started no session.");this.threadId=o,this.state.sessionId=o;let n=B(W(t).model)??B(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=B(W(W(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,W(r.item));case"thread/tokenUsage/updated":return this.addUsage(r);case"account/rateLimits/updated":{let o=l0(r.rateLimits);o&&(this.state.limits=o);return}case"model/rerouted":{let o=B(r.toModel)??B(r.model);o&&(this.state.model=o);return}case"error":{let o=B(W(r.error).message);o&&(this.state.error=o);return}case"turn/completed":return this.completed(W(r.turn))}}subagent(t,r,o){if(t==="item/started"||t==="item/completed")return this.item(t,W(r.item),o);if(t==="thread/tokenUsage/updated"){let n=W(W(r.tokenUsage).last);return Da(this.state,o,Va(n.inputTokens)+Va(n.outputTokens)),this.addUsage(r)}}addUsage(t){let r=W(W(t.tokenUsage).last),o=this.state.usage??={inputTokens:0,outputTokens:0};o.inputTokens+=Va(r.inputTokens),o.outputTokens+=Va(r.outputTokens)}item(t,r,o){let n=i=>oi(this.state,u0(i),o);switch(r.type){case"commandExecution":{if(t!=="item/started")return;let a=B(W(r.commandActions?.[0]).command)??Jn(B(r.command)??"");a&&n(`$ ${a}`);return}case"fileChange":{let i=Array.isArray(r.changes)?r.changes.map(a=>B(W(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(`${B(r.server)??"mcp"}.${B(r.tool)??"tool"}`);return;case"webSearch":t==="item/started"&&B(r.query)&&n(`Search ${B(r.query)}`);return;case"agentMessage":{let i=B(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=B(r.agentThreadId);if(!i)return;r.kind==="started"?Gn(this.state,i,m0(r.agentPath),"",{model:B(r.model)}):r.kind==="completed"?St(this.state,i,!0):r.kind==="interrupted"&&St(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)Gn(this.state,n,"",B(r.prompt)??"",{model:B(r.model)});if(t==="item/completed")for(let[n,i]of Object.entries(W(r.agentsStates))){let a=W(i),s=B(a.message)??"";a.status==="completed"||a.status==="shutdown"?St(this.state,n,!0,s):(a.status==="errored"||a.status==="interrupted")&&St(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=B(W(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=W(t.params),o=n=>this.send({jsonrpc:"2.0",id:t.id,result:n});switch(t.method){case"item/commandExecution/requestApproval":{let i=B(W(r.commandActions?.[0]).command)??Jn(B(r.command)??""),a=!!i&&await this.ask("Bash",{command:i,...B(r.reason)&&{description:B(r.reason)}});return o({decision:a?"accept":"decline"})}case"item/fileChange/requestApproval":{let n=[...B(r.grantRoot)?[B(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=W(r.permissions),i=W(n.fileSystem),a=[...i.write??[],...i.read??[]].filter(l=>typeof l=="string"),s=W(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:B(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
- `)}};function l0(e){let t=W(e),r=o=>{let n=W(o);return Object.keys(n).length?{used_percent:n.usedPercent,window_minutes:n.windowDurationMins,resets_at:n.resetsAt}:null};return tm({primary:r(t.primary),secondary:r(t.secondary)},new Date().toISOString())}var d0=900*1e3;function fb(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:")?c0:s0)(e,{method:"POST",headers:{"content-type":"application/json",accept:"application/json",authorization:`Bearer ${t}`,"content-length":Buffer.byteLength(i)},timeout:d0},u=>{let l="";u.setEncoding("utf8"),u.on("data",d=>{l.length<1e6&&(l+=d)}),u.on("end",()=>n(u.statusCode===200&&p0(l))),u.on("error",()=>n(!1))});s.on("timeout",()=>s.destroy()),s.on("error",()=>n(!1)),s.end(i)})}function p0(e){try{let t=W(W(JSON.parse(e)).result).content,r=Array.isArray(t)?B(W(t[0]).text):void 0;return!!r&&W(JSON.parse(r)).behavior==="allow"}catch{return!1}}function m0(e){return(B(e)??"").split("/").filter(Boolean).pop()??""}var Ja=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"}})}
78
+ `)[0]??"").slice(0,200)}import{readdir as Jz,realpath as cm,stat as nb}from"node:fs/promises";import{homedir as rb}from"node:os";import{dirname as Bz,isAbsolute as Wz,join as Gz,parse as qz}from"node:path";var Hz=1e3;async function ib(e){let t=rb(),r=await cm(e?ab(e):t),n=(await Jz(r,{withFileTypes:!0})).filter(u=>(u.isDirectory()||u.isSymbolicLink())&&!u.name.startsWith(".")).map(u=>({name:u.name,path:Gz(r,u.name)})),a=(await Promise.all(n.map(async u=>(await nb(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=Bz(r);return{path:r,parent:s===r?null:s,home:t,dirs:a.slice(0,Hz)}}async function ob(e){let t=await cm(ab(e)).catch(()=>{throw new Error(`${e} does not exist on this computer.`)});if(!(await nb(t)).isDirectory())throw new Error(`${e} is not a folder.`);if(t===qz(t).root||t===await cm(rb()))throw new Error("Pick a project folder, not your whole home folder or disk.");return t}function ab(e){if(!Wz(e))throw new Error(`${e} is not a full path.`);return e}import{watchFile as cj,unwatchFile as uj}from"node:fs";import{hostname as Um,platform as $$}from"node:os";import{access as Xz,constants as Yz,mkdtemp as nC,readdir as Qz,readFile as sb,realpath as e0,rm as rC,stat as ub,writeFile as iC}from"node:fs/promises";import{tmpdir as aC,userInfo as t0}from"node:os";import{basename as um,delimiter as n0,dirname as La,join as Za}from"node:path";var r0="/proc/sys/kernel/apparmor_restrict_unprivileged_userns";function i0(e=lb(),t="/etc/apparmor.d"){return Za(t,`myrel-runner-${e}`)}function lb(){return t0().username.replace(/[^A-Za-z0-9_.-]/g,"_")||"user"}async function dm(e={}){let t=e.user??lb(),r=i0(t,e.profileDir),o={restricted:!1,applies:!1,binaries:[],blocked:[],file:r};if((e.platform??process.platform)!=="linux")return o;let n=await sb(e.restrict??r0,"utf8").catch(()=>null);if(n===null)return o;o.applies=!0,o.restricted=n.trim()==="1",o.binaries=await o0(e.env??process.env);let i=await sb(r,"utf8").catch(()=>"");return o.blocked=o.binaries.filter(a=>!i.includes(s0(a.attach))),o}async function o0(e=process.env){let t=[],r=await cb("muse",e);if(r){let n=La(r),i=(await Qz(n).catch(()=>[])).filter(a=>a.startsWith("muse-bin-")).sort();(um(r).startsWith("muse-bin-")||i.length)&&t.push({cli:"muse",path:um(r).startsWith("muse-bin-")?r:Za(n,i.at(-1)),attach:`${lm(n)}/muse-bin-*`})}let o=await cb("codex",e);if(o){let n=La(La(o)),i=Za(n,"codex-resources","bwrap");if(await a0(i)){let a=La(n);t.push({cli:"codex",path:i,attach:um(a)==="releases"?`${lm(a)}/*/codex-resources/bwrap`:lm(i)})}}return t}async function cb(e,t){for(let r of(t.PATH??"").split(n0)){if(!r)continue;let o=Za(r,e);try{if(await Xz(o,Yz.X_OK),!(await ub(o)).isFile())continue;return await e0(o)}catch{}}}async function a0(e){return ub(e).then(t=>t.isFile(),()=>!1)}function lm(e){return e.replace(/[\\"*?[\]{}^]/g,t=>`\\${t}`)}function s0(e){return`"${e}" flags=(unconfined)`}function db(e,t){return e==="codex"?t!=="full":e==="muse"?t==="edit"||t==="auto":!1}async function pb(e,t){if(e!=="muse"&&e!=="codex")return null;let r=t??await dm();return!r.restricted||!r.blocked.some(o=>o.cli===e)?null:"(myrel-runner: on this computer Ubuntu's AppArmor blocks this CLI's sandbox, so every shell command fails with \"bwrap: loopback: Failed RTM_NEWADDR: Operation not permitted\". Do not retry commands or work around it. Read and edit files, use Myrel's tools, and tell the person to run `npx myrel-runner sandbox fix` once in a terminal on this computer (it asks for their sudo password), or to give this computer full access in Myrel > Devices.)"}function mb(e){return!e.restricted||!e.blocked.length?null:`Ubuntu's AppArmor blocks the sandbox of ${[...new Set(e.blocked.map(r=>r.cli==="muse"?"Muse Code":"Codex"))].join(" and ")}, so their commands fail below full access. Fix it once with \`myrel-runner sandbox fix\`.`}import{open as B0,realpath as Ob,stat as W0}from"node:fs/promises";import{isAbsolute as G0,join as q0,relative as H0,resolve as X0,sep as Tb}from"node:path";import{spawn as F0}from"node:child_process";import{mkdtemp as Sb,realpath as Ib,rm as zb,writeFile as V0}from"node:fs/promises";import{tmpdir as Pb}from"node:os";import{join as fm}from"node:path";var Fa=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
+ `)}};import{request as c0}from"node:http";import{request as u0}from"node:https";var W=e=>e&&typeof e=="object"?e:{},B=e=>typeof e=="string"&&e?e:void 0,Va=e=>typeof e=="number"&&Number.isFinite(e)&&e>0?Math.round(e):0,l0=e=>e.trim().slice(0,2e3),Ka=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,W(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=W(W(t).thread),o=B(r.id);if(!o)return this.fail("Codex started no session.");this.threadId=o,this.state.sessionId=o;let n=B(W(t).model)??B(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=B(W(W(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,W(r.item));case"thread/tokenUsage/updated":return this.addUsage(r);case"account/rateLimits/updated":{let o=d0(r.rateLimits);o&&(this.state.limits=o);return}case"model/rerouted":{let o=B(r.toModel)??B(r.model);o&&(this.state.model=o);return}case"error":{let o=B(W(r.error).message);o&&(this.state.error=o);return}case"turn/completed":return this.completed(W(r.turn))}}subagent(t,r,o){if(t==="item/started"||t==="item/completed")return this.item(t,W(r.item),o);if(t==="thread/tokenUsage/updated"){let n=W(W(r.tokenUsage).last);return Da(this.state,o,Va(n.inputTokens)+Va(n.outputTokens)),this.addUsage(r)}}addUsage(t){let r=W(W(t.tokenUsage).last),o=this.state.usage??={inputTokens:0,outputTokens:0};o.inputTokens+=Va(r.inputTokens),o.outputTokens+=Va(r.outputTokens)}item(t,r,o){let n=i=>oi(this.state,l0(i),o);switch(r.type){case"commandExecution":{if(t!=="item/started")return;let a=B(W(r.commandActions?.[0]).command)??Jn(B(r.command)??"");a&&n(`$ ${a}`);return}case"fileChange":{let i=Array.isArray(r.changes)?r.changes.map(a=>B(W(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(`${B(r.server)??"mcp"}.${B(r.tool)??"tool"}`);return;case"webSearch":t==="item/started"&&B(r.query)&&n(`Search ${B(r.query)}`);return;case"agentMessage":{let i=B(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=B(r.agentThreadId);if(!i)return;r.kind==="started"?Gn(this.state,i,f0(r.agentPath),"",{model:B(r.model)}):r.kind==="completed"?St(this.state,i,!0):r.kind==="interrupted"&&St(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)Gn(this.state,n,"",B(r.prompt)??"",{model:B(r.model)});if(t==="item/completed")for(let[n,i]of Object.entries(W(r.agentsStates))){let a=W(i),s=B(a.message)??"";a.status==="completed"||a.status==="shutdown"?St(this.state,n,!0,s):(a.status==="errored"||a.status==="interrupted")&&St(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=B(W(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=W(t.params),o=n=>this.send({jsonrpc:"2.0",id:t.id,result:n});switch(t.method){case"item/commandExecution/requestApproval":{let i=B(W(r.commandActions?.[0]).command)??Jn(B(r.command)??""),a=!!i&&await this.ask("Bash",{command:i,...B(r.reason)&&{description:B(r.reason)}});return o({decision:a?"accept":"decline"})}case"item/fileChange/requestApproval":{let n=[...B(r.grantRoot)?[B(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=W(r.permissions),i=W(n.fileSystem),a=[...i.write??[],...i.read??[]].filter(l=>typeof l=="string"),s=W(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:B(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
+ `)}};function d0(e){let t=W(e),r=o=>{let n=W(o);return Object.keys(n).length?{used_percent:n.usedPercent,window_minutes:n.windowDurationMins,resets_at:n.resetsAt}:null};return tm({primary:r(t.primary),secondary:r(t.secondary)},new Date().toISOString())}var p0=900*1e3;function fb(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:")?u0:c0)(e,{method:"POST",headers:{"content-type":"application/json",accept:"application/json",authorization:`Bearer ${t}`,"content-length":Buffer.byteLength(i)},timeout:p0},u=>{let l="";u.setEncoding("utf8"),u.on("data",d=>{l.length<1e6&&(l+=d)}),u.on("end",()=>n(u.statusCode===200&&m0(l))),u.on("error",()=>n(!1))});s.on("timeout",()=>s.destroy()),s.on("error",()=>n(!1)),s.end(i)})}function m0(e){try{let t=W(W(JSON.parse(e)).result).content,r=Array.isArray(t)?B(W(t[0]).text):void 0;return!!r&&W(JSON.parse(r)).behavior==="allow"}catch{return!1}}function f0(e){return(B(e)??"").split("/").filter(Boolean).pop()??""}var Ja=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
- `)}};import{randomBytes as f0}from"node:crypto";import{createServer as g0}from"node:http";var h0="MYREL_GIT_CREDENTIALS",v0=40,Ba=class{lent=new Map;keyOf=new Map;port=null;server=null;async lend(t,r){let o=f0(32).toString("hex");this.keyOf.set(t,o),this.lent.set(o,{token:r.token,expiresAt:Date.parse(r.expiresAt)});try{return y0(`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=g0((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
82
+ `)}};import{randomBytes as g0}from"node:crypto";import{createServer as h0}from"node:http";var v0="MYREL_GIT_CREDENTIALS",y0=40,Ba=class{lent=new Map;keyOf=new Map;port=null;server=null;async lend(t,r){let o=g0(32).toString("hex");this.keyOf.set(t,o),this.lent.set(o,{token:r.token,expiresAt:Date.parse(r.expiresAt)});try{return b0(`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=h0((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 y0(e,t,r=process.env.GIT_CONFIG_PARAMETERS,o=ri()){let n=`!${[o.command,...o.args].map($0).join(" ")} git-credential`,i=[],a=[...new Set(t.slice(0,v0).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])=>b0(`${u}=${l}`)).join(" ");return{[h0]:e,GIT_CONFIG_PARAMETERS:r?`${r} ${s}`:s}}var b0=e=>`'${e.replaceAll("'","'\\''")}'`;function $0(e){return`"${(process.platform==="win32"?e.replaceAll("\\","/"):e).replace(/["\\$`]/g,"\\$&")}"`}import{chmod as _0,mkdir as gb,writeFile as hb}from"node:fs/promises";import{dirname as x0,join as ci,resolve as k0,sep as w0}from"node:path";var S0="myrel",I0=/^[a-z0-9]+(-[a-z0-9]+)*$/;async function vb(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=ci(r,"plugin"),a=ci(i,"skills"),s=0;for(let u of n.skills??[]){if(!I0.test(u.name))continue;let l=ci(a,u.name);for(let d of u.files??[]){let p=k0(l,d.path);p.startsWith(l+w0)&&(await gb(x0(p),{recursive:!0}),await hb(p,Buffer.from(d.content,"base64")),(/\.(sh|py)$/.test(d.path)||d.path.startsWith("scripts/"))&&await _0(p,493).catch(()=>{}))}s++}return s?(await gb(ci(i,".claude-plugin"),{recursive:!0}),await hb(ci(i,".claude-plugin","plugin.json"),JSON.stringify({name:S0,description:"Skills added in Myrel for this run.",version:"1.0.0"})),{plugin:i,skills:a,count:s}):null}import{chmod as z0,mkdir as P0,writeFile as pm}from"node:fs/promises";import{delimiter as SC,join as Wa}from"node:path";var j0="MYREL_SSH_SHIM",A0=["ssh","scp","sftp"],PC=960*1e3;async function yb(e,t,r=process.platform){let o=Wa(e,"ssh-bin");await P0(o,{recursive:!0,mode:448});let n=ri();for(let s of A0)if(r==="win32"){let u=[n.command,...n.args].map(l=>`"${l}"`).join(" ");await pm(Wa(o,`${s}.cmd`),`@echo off\r
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 b0(e,t,r=process.env.GIT_CONFIG_PARAMETERS,o=ri()){let n=`!${[o.command,...o.args].map(_0).join(" ")} git-credential`,i=[],a=[...new Set(t.slice(0,y0).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])=>$0(`${u}=${l}`)).join(" ");return{[v0]:e,GIT_CONFIG_PARAMETERS:r?`${r} ${s}`:s}}var $0=e=>`'${e.replaceAll("'","'\\''")}'`;function _0(e){return`"${(process.platform==="win32"?e.replaceAll("\\","/"):e).replace(/["\\$`]/g,"\\$&")}"`}import{chmod as x0,mkdir as gb,writeFile as hb}from"node:fs/promises";import{dirname as k0,join as ci,resolve as w0,sep as S0}from"node:path";var I0="myrel",z0=/^[a-z0-9]+(-[a-z0-9]+)*$/;async function vb(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=ci(r,"plugin"),a=ci(i,"skills"),s=0;for(let u of n.skills??[]){if(!z0.test(u.name))continue;let l=ci(a,u.name);for(let d of u.files??[]){let p=w0(l,d.path);p.startsWith(l+S0)&&(await gb(k0(p),{recursive:!0}),await hb(p,Buffer.from(d.content,"base64")),(/\.(sh|py)$/.test(d.path)||d.path.startsWith("scripts/"))&&await x0(p,493).catch(()=>{}))}s++}return s?(await gb(ci(i,".claude-plugin"),{recursive:!0}),await hb(ci(i,".claude-plugin","plugin.json"),JSON.stringify({name:I0,description:"Skills added in Myrel for this run.",version:"1.0.0"})),{plugin:i,skills:a,count:s}):null}import{chmod as P0,mkdir as j0,writeFile as pm}from"node:fs/promises";import{delimiter as IC,join as Wa}from"node:path";var A0="MYREL_SSH_SHIM",T0=["ssh","scp","sftp"],jC=960*1e3;async function yb(e,t,r=process.platform){let o=Wa(e,"ssh-bin");await j0(o,{recursive:!0,mode:448});let n=ri();for(let s of T0)if(r==="win32"){let u=[n.command,...n.args].map(l=>`"${l}"`).join(" ");await pm(Wa(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=Wa(o,s);await pm(l,`#!/bin/sh
87
87
  exec ${u} ssh-shim ${s} "$@"
88
- `,{mode:448}),await z0(l,448)}let i=Wa(e,"ssh-shim.json");await pm(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"?";":":"),[j0]:i}}var jC=new Set("qTn46vxCa".split(""));import{execFile as T0}from"node:child_process";import{createHash as O0}from"node:crypto";import{mkdir as N0,realpath as mm,stat as bb}from"node:fs/promises";import{basename as D0,join as Ga,relative as U0}from"node:path";import{promisify as C0}from"node:util";var E0=C0(T0),R0=1440*60*1e3,$b=()=>Ga(ee(),"worktrees.json"),qe=(e,t)=>E0("git",["-C",e,...t],{maxBuffer:4*1024*1024,env:We()});async function ui(){return await $e($b())??[]}async function _b(e){await Ze($b(),e)}function M0(e){return`myrel/thr-${e.slice(-10).toLowerCase()}`}async function xb(e,t){let r=await qe(e,["rev-parse","--show-toplevel"]).then(a=>mm(a.stdout.trim())).catch(()=>null);if(!r||!await qe(r,["rev-parse","--verify","--quiet","HEAD"]).catch(()=>null))return null;let o=await ui(),n=o.find(a=>a.repo===r&&a.threadId===t),i=!1;if(!n||!await bb(n.path).catch(()=>null)){let a=O0("sha256").update(r).digest("hex").slice(0,8),s=Ga(ee(),"worktrees",`${D0(r)}-${a}`);await N0(s,{recursive:!0,mode:448});let u=Ga(await mm(s),t.slice(-10).toLowerCase()),l=M0(t);await qe(r,["worktree","prune"]).catch(()=>{});let d=await qe(r,["rev-parse","--verify","--quiet",`refs/heads/${l}`]).catch(()=>null);await qe(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 _b([...o.filter(a=>!(a.repo===r&&a.threadId===t)),n]),{cwd:Ga(n.path,U0(r,await mm(e))),worktree:n,created:i}}async function kb(e){if(!await bb(e.path).catch(()=>null))return{missing:!0,dirty:!1,merged:!0};let t=await qe(e.path,["status","--porcelain"]).catch(()=>null),r=await qe(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 L0(e,{force:t=!1}={}){let r=await kb(e);if(r.dirty&&!t)throw new Error(`${e.path} has uncommitted changes. Commit them, or remove it with --force.`);r.missing||await qe(e.repo,["worktree","remove",...t?["--force"]:[],e.path]),await qe(e.repo,["worktree","prune"]).catch(()=>{}),r.merged&&await qe(e.repo,["branch","-d",e.branch]).catch(()=>{}),await _b((await ui()).filter(o=>o.path!==e.path))}async function wb(e=()=>!1,t=Date.now()){let r=[];for(let o of await ui()){if(e(o)||t-o.lastUsed<R0)continue;let n=await kb(o).catch(()=>null);!n||n.dirty||!n.merged||await L0(o).then(()=>r.push(o)).catch(()=>{})}return r}var gm=new Set(["claude","codex","antigravity","opencode","hermes","cursor","muse","kimi"]),jb=9e4,V0=1e3,qa=class{constructor(t){this.opts=t}opts;running=new Map;turns=new Map;worktrees=new Map;cancelled=new Set;interrupted=new Set;git=new Ba;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=z=>this.send({type:"task.done",taskId:t.taskId,ok:!1,result:z}),o=this.opts.config(),n=await Ha(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 xb(n,t.threadId)}catch(z){return r(`Could not make a git worktree for this thread in ${n}: ${Ab(z)}
88
+ `,{mode:448}),await P0(l,448)}let i=Wa(e,"ssh-shim.json");await pm(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"?";":":"),[A0]:i}}var AC=new Set("qTn46vxCa".split(""));import{execFile as O0}from"node:child_process";import{createHash as N0}from"node:crypto";import{mkdir as D0,realpath as mm,stat as bb}from"node:fs/promises";import{basename as U0,join as Ga,relative as C0}from"node:path";import{promisify as E0}from"node:util";var R0=E0(O0),M0=1440*60*1e3,$b=()=>Ga(ee(),"worktrees.json"),qe=(e,t)=>R0("git",["-C",e,...t],{maxBuffer:4*1024*1024,env:We()});async function ui(){return await $e($b())??[]}async function _b(e){await Ze($b(),e)}function L0(e){return`myrel/thr-${e.slice(-10).toLowerCase()}`}async function xb(e,t){let r=await qe(e,["rev-parse","--show-toplevel"]).then(a=>mm(a.stdout.trim())).catch(()=>null);if(!r||!await qe(r,["rev-parse","--verify","--quiet","HEAD"]).catch(()=>null))return null;let o=await ui(),n=o.find(a=>a.repo===r&&a.threadId===t),i=!1;if(!n||!await bb(n.path).catch(()=>null)){let a=N0("sha256").update(r).digest("hex").slice(0,8),s=Ga(ee(),"worktrees",`${U0(r)}-${a}`);await D0(s,{recursive:!0,mode:448});let u=Ga(await mm(s),t.slice(-10).toLowerCase()),l=L0(t);await qe(r,["worktree","prune"]).catch(()=>{});let d=await qe(r,["rev-parse","--verify","--quiet",`refs/heads/${l}`]).catch(()=>null);await qe(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 _b([...o.filter(a=>!(a.repo===r&&a.threadId===t)),n]),{cwd:Ga(n.path,C0(r,await mm(e))),worktree:n,created:i}}async function kb(e){if(!await bb(e.path).catch(()=>null))return{missing:!0,dirty:!1,merged:!0};let t=await qe(e.path,["status","--porcelain"]).catch(()=>null),r=await qe(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 Z0(e,{force:t=!1}={}){let r=await kb(e);if(r.dirty&&!t)throw new Error(`${e.path} has uncommitted changes. Commit them, or remove it with --force.`);r.missing||await qe(e.repo,["worktree","remove",...t?["--force"]:[],e.path]),await qe(e.repo,["worktree","prune"]).catch(()=>{}),r.merged&&await qe(e.repo,["branch","-d",e.branch]).catch(()=>{}),await _b((await ui()).filter(o=>o.path!==e.path))}async function wb(e=()=>!1,t=Date.now()){let r=[];for(let o of await ui()){if(e(o)||t-o.lastUsed<M0)continue;let n=await kb(o).catch(()=>null);!n||n.dirty||!n.merged||await Z0(o).then(()=>r.push(o)).catch(()=>{})}return r}var gm=new Set(["claude","codex","antigravity","opencode","hermes","cursor","muse","kimi"]),jb=9e4,K0=1e3,qa=class{constructor(t){this.opts=t}opts;running=new Map;turns=new Map;worktrees=new Map;cancelled=new Set;interrupted=new Set;git=new Ba;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=z=>this.send({type:"task.done",taskId:t.taskId,ok:!1,result:z}),o=this.opts.config(),n=await Ha(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 xb(n,t.threadId)}catch(z){return r(`Could not make a git worktree for this thread in ${n}: ${Ab(z)}
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 z of t.folders??[]){let C=await Ha(o,z);C?C!==a&&!u.includes(C)&&u.push(C):s(` skipping ${z}: not shared on this computer`)}let l=si[t.cli],d=!!t.agent&&t.cli==="claude",p=gm.has(t.cli)&&!i?.created?await this.opts.sessions.get(t.threadId,t.cli):void 0,f=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 m,v={args:[]},$=null,k;if(t.agent&&o.server){m=await Sb(fm(Pb(),"myrel-agent-"));let z=o.server.replace(/\/$/,"");k=fb(`${z}${t.agent.mcpPath}`,t.agent.token);let C=(t.agent.connectors??[]).map(j=>j.transport==="http"?{transport:j.transport,name:j.name,url:`${z}${j.path}`}:j);$=t.agent.skills?await vb(`${z}${t.agent.skills.path}`,t.agent.token,m):null,v=await l.agent({url:`${z}${t.agent.mcpPath}`,token:t.agent.token,dir:m,connectors:C,asks:d,access:o.access,dirs:u,...$&&{skills:{plugin:$.plugin,dir:$.skills}}})}let P=()=>m?zb(m,{recursive:!0,force:!0}).catch(()=>{}):Promise.resolve(),S=i?`
91
91
 
@@ -93,20 +93,20 @@ To run tasks in the folder itself instead, run \`myrel-runner worktrees off\`.`)
93
93
 
94
94
  Skills folder for this run: ${p.skills}`:n,$=db(u.id,i.access)?await pb(u.id).catch(()=>null):null,k=$?`${v}
95
95
 
96
- ${$}`:v,P=u.input?u.input(k,i.access):k,S=u.promptFile?await Sb(fm(Pb(),"myrel-prompt-")):void 0,T=S?fm(S,"prompt.md"):void 0;T&&await F0(T,P,{mode:384});let z=[...r.appServer?[]:qy(u,t.model),...l.args],C=r.appServer?["app-server",...l.args]:u.args({access:i.access,resume:o,extra:z,dirs:d,asks:r.asks,promptFile:T,stream:r.stream}),j=(this.opts.spawn??Z0)(u.bin,C,{cwd:s,env:We(r.env),stdio:["pipe","pipe","pipe"],shell:process.platform==="win32"});if(S){let Z=()=>{zb(S,{recursive:!0,force:!0}).catch(()=>{})};j.once("close",Z),j.once("error",Z)}this.running.set(t.taskId,j),this.opts.onChange?.(this.runningIds());let A={},ue="",Ye="",Ee="",Qe=0,Qt,dt="",mi,Yn,Qn=Z=>{!Z||Z===mi||(mi=Z,this.opts.onLimits?.(t.cli,Z))},en=()=>A.usage?{...A.usage,...A.model&&{model:A.model.slice(0,200)}}:void 0,fi=()=>{for(let ie of A.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 Z=en(),te=Z?JSON.stringify(Z):"",pe=!!A.progress&&A.progress!==Qt;if(pe||te!==dt){Qt=A.progress,dt=te,Qe=Date.now();let ie=pe&&A.progressAgent;this.send({type:"task.progress",taskId:t.taskId,text:pe?A.progress:"",...Z&&{usage:Z},...ie&&{agent:ie}})}};if(j.stdout.setEncoding("utf8"),j.stdout.on("data",Z=>{ue.length<4*jb&&(ue+=Z),Ee+=Z;let te=Ee.split(`
97
- `);Ee=te.pop();for(let ie of te)u.line(ie.trim(),A);Qn(A.limits),A.sessionId&&A.sessionId!==Yn&&gm.has(t.cli)&&(Yn=A.sessionId,this.opts.sessions.set(t.threadId,t.cli,{id:A.sessionId,task:t.taskId}).catch(()=>{}));let pe=en();(Date.now()-Qe>=V0||pe&&JSON.stringify(pe)!==dt||A.agentNotes?.length)&&fi()}),j.stderr.setEncoding("utf8"),j.stderr.on("data",Z=>{Ye.length<2e4&&(Ye+=Z)}),j.stdin.on("error",()=>{}),u.acp){let Z={write:pe=>{j.stdin.write(pe)},end:()=>j.stdin.end()},te={cwd:s,prompt:P,mcpServers:l.mcpServers??[],resume:o,dirs:d,...u.acp(i.access,Ma(t.model))};A.acp=new Fa(Z,te,A),A.acp.start()}else if(r.appServer){let Z={write:pe=>{j.stdin.write(pe)},end:()=>j.stdin.end()},te={cwd:s,prompt:P,resume:o,model:Ma(t.model),clientVersion:this.opts.version??"0",...r.appServer};A.appServer=new Ka(Z,te,A),this.turns.set(t.taskId,A.appServer),A.appServer.start()}else if(r.stream){let Z={write:te=>{j.stdin.write(te)},end:()=>j.stdin.end()};A.claudeStream=new Ja(Z,P),this.turns.set(t.taskId,A.claudeStream),A.claudeStream.start()}else j.stdin.end(T?"":P);let er=setTimeout(()=>j.kill("SIGTERM"),this.opts.timeoutMs??3600*1e3);return await new Promise(Z=>{let te=!1,pe=(ie,x)=>{if(te)return;if(te=!0,clearTimeout(er),m(),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`),Z(!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."}),Z(!1);a(`${ie?"\u2713":"\u2717"} ${u.id} task finished`);let D=en();this.send({type:"task.done",taskId:t.taskId,ok:ie,result:x.slice(0,jb-f.length)+f,...D&&{usage:D}}),Z(!1)};j.on("error",ie=>{pe(!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}`)}),j.on("exit",()=>{(this.cancelled.has(t.taskId)||this.interrupted.has(t.taskId))&&pe(!1,"")}),j.on("close",async(ie,x)=>{Ee.trim()&&u.line(Ee.trim(),A),u.end?.(ue,A),Qn(A.limits??await u.limits?.(A).catch(()=>{}));let D=ie===0&&!A.failed;if(o&&!D&&!A.usage&&!A.progress&&!this.cancelled.has(t.taskId))return te=!0,clearTimeout(er),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()),m(),Z(!1)):Z(!0);A.sessionId&&gm.has(t.cli)&&await this.opts.sessions.set(t.threadId,t.cli,{id:A.sessionId,task:t.taskId}).catch(()=>{});let F=A.result??(D?ue.trim():K0(u.bin,ie,x,A.error??(Ye.trim()||ue.trim())));pe(D,F||"(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 Ha(e,t){let r=await Ib(t).catch(()=>null);if(!r)return null;for(let o of e.folders)if(await Ib(o.path).catch(()=>null)===r)return r;return null}var Ab=e=>(e.stderr||e.message||String(e)).trim().split(`
98
- `).at(-1);function K0(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}`}.
99
- ${o}`}async function Nb(e,t){let r=await X0(e,t.folders,t.threadId);if(!r.length)throw new Error("None of this project's folders is shared on this computer.");let o=Y0(t.path),n=W0(o)?[o]:r.map(i=>H0(i,o));for(let i of n){let a=await Ob(i).catch(()=>null);if(!a||!r.some(p=>Db(a,p)))continue;let s=await B0(a);if(!s.isFile())continue;let u=Math.min(s.size,Hp),l=Buffer.alloc(u),d=await J0(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 X0(e,t,r){let o=(await Promise.all(t.map(a=>Ha(e,a)))).filter(a=>a!==null),n=r?(await ui()).filter(a=>a.threadId===r):[],i=[];for(let a of o)for(let s of n){if(!Db(a,s.repo))continue;let u=await Ob(G0(s.path,q0(s.repo,a))).catch(()=>null);u&&i.push(u)}return[...i,...o]}function Y0(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 Db(e,t){return e===t||e.startsWith(t.endsWith(Tb)?t:t+Tb)}import{readFileSync as Q0,rmSync as eP,writeFileSync as tP,mkdirSync as nP}from"node:fs";import{join as Ub}from"node:path";var rP=3600*1e3,hm=()=>Ub(ee(),"interrupted.json"),iP=()=>Ub(ee(),"running.json");function Cb(e,t=Date.now()){if(!e.length)return;let r=[...Rb(t),...e.map(o=>({taskId:o,at:t}))];Mb(hm(),r)}function Eb(e=Date.now()){let t=[...new Set(Rb(e).map(r=>r.taskId))];return eP(hm(),{force:!0}),t}function Rb(e){let t=oP(hm());return Array.isArray(t)?t.filter(r=>typeof r?.taskId=="string"&&e-r.at<rP):[]}function vm(e){try{Mb(iP(),{pid:process.pid,running:e})}catch{}}function oP(e){try{return JSON.parse(Q0(e,"utf8"))}catch{return}}function Mb(e,t){nP(ee(),{recursive:!0,mode:448}),tP(e,`${JSON.stringify(t)}
100
- `,{mode:384})}import{spawn as aP}from"node:child_process";import{createHash as sP,randomBytes as cP}from"node:crypto";import{access as $m,chmod as uP,mkdir as Xa,readdir as lP,readFile as _m,rm as Lb,writeFile as Fb}from"node:fs/promises";import{homedir as Vb}from"node:os";import{dirname as dP,join as lt,relative as pP,resolve as Zb}from"node:path";var Ht=()=>lt(ee(),"ssh"),li=()=>lt(Ht(),"keys.json"),ym=()=>lt(Ht(),"known_hosts"),mP=()=>lt(Ht(),"askpass.sh"),Hn="myrel-runner-ssh",fP=3e4,xm=e=>lt(Ht(),e.projectId,e.alias),qt=e=>`${e.projectId}/${e.alias}`,Kb=e=>`myrel.${e.projectId}.${e.alias}`;function Ya(e){let t=e.trim().split(/\s+/)[1]??"";return`SHA256:${sP("sha256").update(Buffer.from(t,"base64")).digest("base64").replace(/=+$/,"")}`}function He(e,t,r={}){let o=r.max??ey;return new Promise((n,i)=>{let a=aP(e,t,{env:r.env??bm(),stdio:[r.input===void 0?"ignore":"pipe","pipe","pipe"],windowsHide:!0}),s="",u="",l=!1,d=!1,p=(m,v)=>m.length+v.length<=o?m+v:(l=!0,m+v.slice(0,Math.max(0,o-m.length)));a.stdout.setEncoding("utf8").on("data",m=>s=p(s,m)),a.stderr.setEncoding("utf8").on("data",m=>u=p(u,m));let f=r.timeoutMs?setTimeout(()=>{d=!0,a.kill("SIGKILL")},r.timeoutMs):void 0;a.once("error",m=>{clearTimeout(f),i(m)}),a.once("close",m=>{clearTimeout(f),n({code:m,stdout:s,stderr:u,truncated:l,timedOut:d})}),r.input!==void 0&&a.stdin.end(r.input)})}function bm(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 km(e=process.platform){return e==="darwin"?{async set(t,r){let o=await He("security",["-i"],{input:`add-generic-password -U -a "${t}" -s "${Hn}" -w "${r}"
101
- `,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 He("security",["find-generic-password","-a",t,"-s",Hn,"-w"],{timeoutMs:15e3});return r.code===0?r.stdout.replace(/\n$/,""):null},async remove(t){await He("security",["delete-generic-password","-a",t,"-s",Hn],{timeoutMs:15e3}).catch(()=>{})}}:e==="linux"?{async set(t,r){let o=await He("secret-tool",["store",`--label=Myrel SSH key ${t}`,"service",Hn,"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 He("secret-tool",["lookup","service",Hn,"account",t],{timeoutMs:15e3});return r.code===0&&r.stdout?r.stdout.replace(/\n$/,""):null},async remove(t){await He("secret-tool",["clear","service",Hn,"account",t],{timeoutMs:15e3}).catch(()=>{})}}:null}async function gP(e,t,r){if(!e)return!1;try{return await e.set(t,r),await e.get(t)===r}catch{return!1}}async function Jb(e,t,r,o=km()){if(await Xa(Ht(),{recursive:!0,mode:448}),await wm(e,o),r){let l=await hP(r),d=await He("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(li())??{};p[qt(e)]=l,await Ze(li(),p);let f=d.stdout.trim();return{publicKey:f,fingerprint:Ya(f),protected:!1}}let n=xm(e);await Xa(dP(n),{recursive:!0,mode:448});let i=cP(24).toString("base64url"),a=await gP(o,qt(e),i),s=await He("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 uP(n,384).catch(()=>{});let u=(await _m(`${n}.pub`,"utf8")).trim();return{publicKey:u,fingerprint:Ya(u),protected:a}}async function hP(e,t=Vb()){let r=lt(t,".ssh"),o=Zb(r,e),n=pP(r,o);if(!n||n.startsWith("..")||Zb(r,n)!==o)throw new Error("Only keys in ~/.ssh can be used.");return await $m(o),o}async function Bb(e=Vb()){let t=lt(e,".ssh"),r=await lP(t).catch(()=>[]),o=[];for(let n of r.filter(i=>i.endsWith(".pub")).sort()){let i=lt(t,n.slice(0,-4));if(!await $m(i).then(()=>!0,()=>!1))continue;let a=(await _m(lt(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:Ya(a),comment:l.join(" ").slice(0,500)})}return o.slice(0,100)}async function wm(e,t=km()){let r=xm(e);await Lb(r,{force:!0}),await Lb(`${r}.pub`,{force:!0}),await t?.remove(qt(e));let o=await $e(li());o&&qt(e)in o&&(delete o[qt(e)],await Ze(li(),o)),await Gb(e,null)}async function vP(e,t){let r=(await $e(li()))?.[qt(e)];if(r)return{path:r,passphrase:null};let o=xm(e);return await $m(o).then(()=>!0,()=>!1)?{path:o,passphrase:await t?.get(qt(e)).catch(()=>null)??null}:null}async function Wb(e,t){let r=await He("ssh-keyscan",["-T","10","-p",String(t),"-t","ed25519,ecdsa,rsa","--",e],{timeoutMs:3e4}),o=bP(r.stdout);if(!o.length)throw new Error(`${e}:${t} did not answer with a server key${r.stderr.trim()?` (${r.stderr.trim().split(`
102
- `).pop()})`:""}.`);return o}var yP=["ssh-ed25519","ecdsa-sha2-nistp256","ecdsa-sha2-nistp384","ecdsa-sha2-nistp521","rsa-sha2-512","ssh-rsa"];function bP(e){let t=[];for(let o of e.split(`
103
- `)){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:Ya(a)})}let r=o=>yP.indexOf(o)+1||99;return t.sort((o,n)=>r(o.type)-r(n.type)).slice(0,10)}async function Gb(e,t,r=!0){let o=Kb(e),n=(await _m(ym(),"utf8").catch(()=>"")).split(`
96
+ ${$}`:v,P=u.input?u.input(k,i.access):k,S=u.promptFile?await Sb(fm(Pb(),"myrel-prompt-")):void 0,T=S?fm(S,"prompt.md"):void 0;T&&await V0(T,P,{mode:384});let z=[...r.appServer?[]:qy(u,t.model),...l.args],C=r.appServer?["app-server",...l.args]:u.args({access:i.access,resume:o,extra:z,dirs:d,asks:r.asks,promptFile:T,stream:r.stream}),j=(this.opts.spawn??F0)(u.bin,C,{cwd:s,env:We(r.env),stdio:["pipe","pipe","pipe"],shell:process.platform==="win32"});if(S){let Z=()=>{zb(S,{recursive:!0,force:!0}).catch(()=>{})};j.once("close",Z),j.once("error",Z)}this.running.set(t.taskId,j),this.opts.onChange?.(this.runningIds());let A={},ue="",Ye="",Ee="",Qe=0,Qt,dt="",mi,Yn,Qn=Z=>{!Z||Z===mi||(mi=Z,this.opts.onLimits?.(t.cli,Z))},en=()=>A.usage?{...A.usage,...A.model&&{model:A.model.slice(0,200)}}:void 0,fi=()=>{for(let ie of A.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 Z=en(),te=Z?JSON.stringify(Z):"",pe=!!A.progress&&A.progress!==Qt;if(pe||te!==dt){Qt=A.progress,dt=te,Qe=Date.now();let ie=pe&&A.progressAgent;this.send({type:"task.progress",taskId:t.taskId,text:pe?A.progress:"",...Z&&{usage:Z},...ie&&{agent:ie}})}};if(j.stdout.setEncoding("utf8"),j.stdout.on("data",Z=>{ue.length<4*jb&&(ue+=Z),Ee+=Z;let te=Ee.split(`
97
+ `);Ee=te.pop();for(let ie of te)u.line(ie.trim(),A);Qn(A.limits),A.sessionId&&A.sessionId!==Yn&&gm.has(t.cli)&&(Yn=A.sessionId,this.opts.sessions.set(t.threadId,t.cli,{id:A.sessionId,task:t.taskId}).catch(()=>{}));let pe=en();(Date.now()-Qe>=K0||pe&&JSON.stringify(pe)!==dt||A.agentNotes?.length)&&fi()}),j.stderr.setEncoding("utf8"),j.stderr.on("data",Z=>{Ye.length<2e4&&(Ye+=Z)}),j.stdin.on("error",()=>{}),u.acp){let Z={write:pe=>{j.stdin.write(pe)},end:()=>j.stdin.end()},te={cwd:s,prompt:P,mcpServers:l.mcpServers??[],resume:o,dirs:d,...u.acp(i.access,Ma(t.model))};A.acp=new Fa(Z,te,A),A.acp.start()}else if(r.appServer){let Z={write:pe=>{j.stdin.write(pe)},end:()=>j.stdin.end()},te={cwd:s,prompt:P,resume:o,model:Ma(t.model),clientVersion:this.opts.version??"0",...r.appServer};A.appServer=new Ka(Z,te,A),this.turns.set(t.taskId,A.appServer),A.appServer.start()}else if(r.stream){let Z={write:te=>{j.stdin.write(te)},end:()=>j.stdin.end()};A.claudeStream=new Ja(Z,P),this.turns.set(t.taskId,A.claudeStream),A.claudeStream.start()}else j.stdin.end(T?"":P);let er=setTimeout(()=>j.kill("SIGTERM"),this.opts.timeoutMs??3600*1e3);return await new Promise(Z=>{let te=!1,pe=(ie,x)=>{if(te)return;if(te=!0,clearTimeout(er),m(),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`),Z(!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."}),Z(!1);a(`${ie?"\u2713":"\u2717"} ${u.id} task finished`);let D=en();this.send({type:"task.done",taskId:t.taskId,ok:ie,result:x.slice(0,jb-f.length)+f,...D&&{usage:D}}),Z(!1)};j.on("error",ie=>{pe(!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}`)}),j.on("exit",()=>{(this.cancelled.has(t.taskId)||this.interrupted.has(t.taskId))&&pe(!1,"")}),j.on("close",async(ie,x)=>{Ee.trim()&&u.line(Ee.trim(),A),u.end?.(ue,A),Qn(A.limits??await u.limits?.(A).catch(()=>{}));let D=ie===0&&!A.failed;if(o&&!D&&!A.usage&&!A.progress&&!this.cancelled.has(t.taskId))return te=!0,clearTimeout(er),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()),m(),Z(!1)):Z(!0);A.sessionId&&gm.has(t.cli)&&await this.opts.sessions.set(t.threadId,t.cli,{id:A.sessionId,task:t.taskId}).catch(()=>{});let F=A.result??(D?ue.trim():J0(u.bin,ie,x,A.error??(Ye.trim()||ue.trim())));pe(D,F||"(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 Ha(e,t){let r=await Ib(t).catch(()=>null);if(!r)return null;for(let o of e.folders)if(await Ib(o.path).catch(()=>null)===r)return r;return null}var Ab=e=>(e.stderr||e.message||String(e)).trim().split(`
98
+ `).at(-1);function J0(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}`}.
99
+ ${o}`}async function Nb(e,t){let r=await Y0(e,t.folders,t.threadId);if(!r.length)throw new Error("None of this project's folders is shared on this computer.");let o=Q0(t.path),n=G0(o)?[o]:r.map(i=>X0(i,o));for(let i of n){let a=await Ob(i).catch(()=>null);if(!a||!r.some(p=>Db(a,p)))continue;let s=await W0(a);if(!s.isFile())continue;let u=Math.min(s.size,Hp),l=Buffer.alloc(u),d=await B0(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 Y0(e,t,r){let o=(await Promise.all(t.map(a=>Ha(e,a)))).filter(a=>a!==null),n=r?(await ui()).filter(a=>a.threadId===r):[],i=[];for(let a of o)for(let s of n){if(!Db(a,s.repo))continue;let u=await Ob(q0(s.path,H0(s.repo,a))).catch(()=>null);u&&i.push(u)}return[...i,...o]}function Q0(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 Db(e,t){return e===t||e.startsWith(t.endsWith(Tb)?t:t+Tb)}import{readFileSync as eP,rmSync as tP,writeFileSync as nP,mkdirSync as rP}from"node:fs";import{join as Ub}from"node:path";var iP=3600*1e3,hm=()=>Ub(ee(),"interrupted.json"),oP=()=>Ub(ee(),"running.json");function Cb(e,t=Date.now()){if(!e.length)return;let r=[...Rb(t),...e.map(o=>({taskId:o,at:t}))];Mb(hm(),r)}function Eb(e=Date.now()){let t=[...new Set(Rb(e).map(r=>r.taskId))];return tP(hm(),{force:!0}),t}function Rb(e){let t=aP(hm());return Array.isArray(t)?t.filter(r=>typeof r?.taskId=="string"&&e-r.at<iP):[]}function vm(e){try{Mb(oP(),{pid:process.pid,running:e})}catch{}}function aP(e){try{return JSON.parse(eP(e,"utf8"))}catch{return}}function Mb(e,t){rP(ee(),{recursive:!0,mode:448}),nP(e,`${JSON.stringify(t)}
100
+ `,{mode:384})}import{spawn as sP}from"node:child_process";import{createHash as cP,randomBytes as uP}from"node:crypto";import{access as $m,chmod as lP,mkdir as Xa,readdir as dP,readFile as _m,rm as Lb,writeFile as Fb}from"node:fs/promises";import{homedir as Vb}from"node:os";import{dirname as pP,join as lt,relative as mP,resolve as Zb}from"node:path";var Ht=()=>lt(ee(),"ssh"),li=()=>lt(Ht(),"keys.json"),ym=()=>lt(Ht(),"known_hosts"),fP=()=>lt(Ht(),"askpass.sh"),Hn="myrel-runner-ssh",gP=3e4,xm=e=>lt(Ht(),e.projectId,e.alias),qt=e=>`${e.projectId}/${e.alias}`,Kb=e=>`myrel.${e.projectId}.${e.alias}`;function Ya(e){let t=e.trim().split(/\s+/)[1]??"";return`SHA256:${cP("sha256").update(Buffer.from(t,"base64")).digest("base64").replace(/=+$/,"")}`}function He(e,t,r={}){let o=r.max??ey;return new Promise((n,i)=>{let a=sP(e,t,{env:r.env??bm(),stdio:[r.input===void 0?"ignore":"pipe","pipe","pipe"],windowsHide:!0}),s="",u="",l=!1,d=!1,p=(m,v)=>m.length+v.length<=o?m+v:(l=!0,m+v.slice(0,Math.max(0,o-m.length)));a.stdout.setEncoding("utf8").on("data",m=>s=p(s,m)),a.stderr.setEncoding("utf8").on("data",m=>u=p(u,m));let f=r.timeoutMs?setTimeout(()=>{d=!0,a.kill("SIGKILL")},r.timeoutMs):void 0;a.once("error",m=>{clearTimeout(f),i(m)}),a.once("close",m=>{clearTimeout(f),n({code:m,stdout:s,stderr:u,truncated:l,timedOut:d})}),r.input!==void 0&&a.stdin.end(r.input)})}function bm(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 km(e=process.platform){return e==="darwin"?{async set(t,r){let o=await He("security",["-i"],{input:`add-generic-password -U -a "${t}" -s "${Hn}" -w "${r}"
101
+ `,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 He("security",["find-generic-password","-a",t,"-s",Hn,"-w"],{timeoutMs:15e3});return r.code===0?r.stdout.replace(/\n$/,""):null},async remove(t){await He("security",["delete-generic-password","-a",t,"-s",Hn],{timeoutMs:15e3}).catch(()=>{})}}:e==="linux"?{async set(t,r){let o=await He("secret-tool",["store",`--label=Myrel SSH key ${t}`,"service",Hn,"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 He("secret-tool",["lookup","service",Hn,"account",t],{timeoutMs:15e3});return r.code===0&&r.stdout?r.stdout.replace(/\n$/,""):null},async remove(t){await He("secret-tool",["clear","service",Hn,"account",t],{timeoutMs:15e3}).catch(()=>{})}}:null}async function hP(e,t,r){if(!e)return!1;try{return await e.set(t,r),await e.get(t)===r}catch{return!1}}async function Jb(e,t,r,o=km()){if(await Xa(Ht(),{recursive:!0,mode:448}),await wm(e,o),r){let l=await vP(r),d=await He("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(li())??{};p[qt(e)]=l,await Ze(li(),p);let f=d.stdout.trim();return{publicKey:f,fingerprint:Ya(f),protected:!1}}let n=xm(e);await Xa(pP(n),{recursive:!0,mode:448});let i=uP(24).toString("base64url"),a=await hP(o,qt(e),i),s=await He("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 lP(n,384).catch(()=>{});let u=(await _m(`${n}.pub`,"utf8")).trim();return{publicKey:u,fingerprint:Ya(u),protected:a}}async function vP(e,t=Vb()){let r=lt(t,".ssh"),o=Zb(r,e),n=mP(r,o);if(!n||n.startsWith("..")||Zb(r,n)!==o)throw new Error("Only keys in ~/.ssh can be used.");return await $m(o),o}async function Bb(e=Vb()){let t=lt(e,".ssh"),r=await dP(t).catch(()=>[]),o=[];for(let n of r.filter(i=>i.endsWith(".pub")).sort()){let i=lt(t,n.slice(0,-4));if(!await $m(i).then(()=>!0,()=>!1))continue;let a=(await _m(lt(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:Ya(a),comment:l.join(" ").slice(0,500)})}return o.slice(0,100)}async function wm(e,t=km()){let r=xm(e);await Lb(r,{force:!0}),await Lb(`${r}.pub`,{force:!0}),await t?.remove(qt(e));let o=await $e(li());o&&qt(e)in o&&(delete o[qt(e)],await Ze(li(),o)),await Gb(e,null)}async function yP(e,t){let r=(await $e(li()))?.[qt(e)];if(r)return{path:r,passphrase:null};let o=xm(e);return await $m(o).then(()=>!0,()=>!1)?{path:o,passphrase:await t?.get(qt(e)).catch(()=>null)??null}:null}async function Wb(e,t){let r=await He("ssh-keyscan",["-T","10","-p",String(t),"-t","ed25519,ecdsa,rsa","--",e],{timeoutMs:3e4}),o=$P(r.stdout);if(!o.length)throw new Error(`${e}:${t} did not answer with a server key${r.stderr.trim()?` (${r.stderr.trim().split(`
102
+ `).pop()})`:""}.`);return o}var bP=["ssh-ed25519","ecdsa-sha2-nistp256","ecdsa-sha2-nistp384","ecdsa-sha2-nistp521","rsa-sha2-512","ssh-rsa"];function $P(e){let t=[];for(let o of e.split(`
103
+ `)){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:Ya(a)})}let r=o=>bP.indexOf(o)+1||99;return t.sort((o,n)=>r(o.type)-r(n.type)).slice(0,10)}async function Gb(e,t,r=!0){let o=Kb(e),n=(await _m(ym(),"utf8").catch(()=>"")).split(`
104
104
  `).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 Qa}let s=[...n.filter(u=>!u.startsWith(`${o} `)),...a?[a]:[]];!a&&!i.length||(await Xa(Ht(),{recursive:!0,mode:448}),await Fb(ym(),s.length?`${s.join(`
105
105
  `)}
106
- `:"",{mode:384}))}var Qa=class extends Error{constructor(){super("The server's key is not the one confirmed in Myrel.")}};function $P(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=${ym()}`),...o(`GlobalKnownHostsFile=${process.platform==="win32"?"NUL":"/dev/null"}`),...o(`HostKeyAlias=${Kb(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 Sm(e,t,r={}){let o=Date.now(),n=(p,f)=>({exitCode:null,stdout:"",stderr:f,truncated:!1,ms:Date.now()-o,error:p}),i=r.keychain===void 0?km():r.keychain,a=await vP(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 Gb(e,e.hostKey,!!r.trust)}catch(p){if(p instanceof Qa)return n("hostkey",p.message);throw p}let s=r.timeoutMs??Qv,u=a.passphrase?bm({SSH_ASKPASS:await xP(),SSH_ASKPASS_REQUIRE:"force",DISPLAY:process.env.DISPLAY||":0",MYREL_SSH_PASSPHRASE:a.passphrase}):bm(),l=await He("ssh",[...$P(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:_P(l.stderr)}}}var qb=(e,t)=>Sm(e,"true",{trust:!0,keychain:t,timeoutMs:fP});function _P(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 xP(){let e=mP();return await Xa(Ht(),{recursive:!0,mode:448}),await Fb(e,`#!/bin/sh
106
+ `:"",{mode:384}))}var Qa=class extends Error{constructor(){super("The server's key is not the one confirmed in Myrel.")}};function _P(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=${ym()}`),...o(`GlobalKnownHostsFile=${process.platform==="win32"?"NUL":"/dev/null"}`),...o(`HostKeyAlias=${Kb(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 Sm(e,t,r={}){let o=Date.now(),n=(p,f)=>({exitCode:null,stdout:"",stderr:f,truncated:!1,ms:Date.now()-o,error:p}),i=r.keychain===void 0?km():r.keychain,a=await yP(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 Gb(e,e.hostKey,!!r.trust)}catch(p){if(p instanceof Qa)return n("hostkey",p.message);throw p}let s=r.timeoutMs??Qv,u=a.passphrase?bm({SSH_ASKPASS:await kP(),SSH_ASKPASS_REQUIRE:"force",DISPLAY:process.env.DISPLAY||":0",MYREL_SSH_PASSPHRASE:a.passphrase}):bm(),l=await He("ssh",[..._P(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:xP(l.stderr)}}}var qb=(e,t)=>Sm(e,"true",{trust:!0,keychain:t,timeoutMs:gP});function xP(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 kP(){let e=fP();return await Xa(Ht(),{recursive:!0,mode:448}),await Fb(e,`#!/bin/sh
107
107
  printf "%s\\n" "$MYREL_SSH_PASSPHRASE"
108
- `,{mode:448}),e}import{execFile as EP}from"node:child_process";import{createHash as RP}from"node:crypto";import{copyFile as a$,rename as MP,rm as s$,stat as c$,writeFile as LP}from"node:fs/promises";import{join as Tm,resolve as ZP}from"node:path";import{promisify as FP}from"node:util";import{gunzipSync as VP}from"node:zlib";import{execFile as kP,spawn as Yb}from"node:child_process";import{copyFile as wP,mkdir as Im,readFile as SP,rm as Qb,stat as IP,writeFile as es}from"node:fs/promises";import{homedir as Xn,platform as e$}from"node:os";import{delimiter as Hb,join as Xe}from"node:path";import{promisify as zP}from"node:util";var Ne=zP(kP),Xt="io.fibteq.myrel-runner",Yt="myrel-runner.service";async function kE(e){let t=ts(),r=pi();await Im(Xe(ee(),"bin"),{recursive:!0,mode:448}),e!==r&&await wP(e,r);let o=[process.execPath,r,"start"],n=jP(),i=await ns(t);if(t==="launchd")await Im(Xe(Xn(),"Library","LaunchAgents"),{recursive:!0}),await es(i.file,AP(o,n,i.log)),await PP(i.file);else if(t==="systemd"){await Im(Xe(Xn(),".config","systemd","user"),{recursive:!0}),await es(i.file,TP(o,n));try{await Ne("systemctl",["--user","daemon-reload"]),await Ne("systemctl",["--user","enable",Yt]),await Ne("systemctl",["--user","restart",Yt])}catch(a){throw await Qb(i.file,{force:!0}),new Error(`Could not register with systemd (${a.message.split(`
109
- `).filter(Boolean).at(-1)}). Use \`myrel-runner start\` instead.`)}}else await es(i.file,NP(o,i.log)),Yb("wscript.exe",[i.file],{detached:!0,stdio:"ignore"}).unref();return n$()}var pi=()=>Xe(ee(),"bin","myrel-runner.mjs");async function t$(){if(ts()!=="startup")return;let e=await ns("startup");e.installed&&Yb("wscript.exe",[e.file],{detached:!0,stdio:"ignore"}).unref()}async function PP(e){let t=`gui/${process.getuid?.()}`,r=()=>Ne("launchctl",["print",`${t}/${Xt}`]).then(()=>!0,()=>!1);await Ne("launchctl",["bootout",`${t}/${Xt}`]).catch(()=>{});for(let o=0;o<50&&await r();o++)await zm(100);for(let o=1;;o++)try{await Ne("launchctl",["bootstrap",t,e]);break}catch(n){if(o>=5)throw n;await zm(500*o)}for(let o=0;o<30;o++){if((await Ne("launchctl",["print",`${t}/${Xt}`]).catch(()=>null))?.stdout.includes("state = running"))return;await zm(100)}}var zm=e=>new Promise(t=>setTimeout(t,e));async function wE(){let e=ts(),t=await ns(e);return e==="launchd"?await Ne("launchctl",["bootout",`gui/${process.getuid?.()}/${Xt}`]).catch(()=>{}):e==="systemd"&&await Ne("systemctl",["--user","disable","--now",Yt]).catch(()=>{}),await Qb(t.file,{force:!0}),e==="systemd"&&await Ne("systemctl",["--user","daemon-reload"]).catch(()=>{}),n$()}async function n$(){let e=await ns(ts());if(!e.installed)return{...e,running:!1};if(e.manager==="launchd"){let t=await Ne("launchctl",["print",`gui/${process.getuid?.()}/${Xt}`]).catch(()=>null);return{...e,running:!!t?.stdout.includes("state = running")}}if(e.manager==="systemd"){let t=await Ne("systemctl",["--user","is-active",Yt]).catch(()=>null);return{...e,running:t?.stdout.trim()==="active"}}return{...e,running:null}}function ts(){let e=e$();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 ns(e){let t=e==="launchd"?Xe(Xn(),"Library","LaunchAgents",`${Xt}.plist`):e==="systemd"?Xe(Xn(),".config","systemd","user",Yt):Xe(process.env.APPDATA??Xe(Xn(),"AppData","Roaming"),"Microsoft","Windows","Start Menu","Programs","Startup","myrel-runner.vbs"),r=e==="systemd"?`journalctl --user -u ${Yt}`:Xe(ee(),"runner.log"),o=!!await IP(t).catch(()=>null);return{manager:e,file:t,installed:o,log:r}}function jP(){let t={PATH:(process.env.PATH??"").split(Hb).filter(r=>r&&!/[\\/]_npx[\\/]/.test(r)).join(Hb)};return process.env.MYREL_RUNNER_HOME&&(t.MYREL_RUNNER_HOME=process.env.MYREL_RUNNER_HOME),t}var di=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;");function AP(e,t,r){return`<?xml version="1.0" encoding="UTF-8"?>
108
+ `,{mode:448}),e}import{execFile as RP}from"node:child_process";import{createHash as MP}from"node:crypto";import{copyFile as a$,rename as LP,rm as s$,stat as c$,writeFile as ZP}from"node:fs/promises";import{join as Tm,resolve as FP}from"node:path";import{promisify as VP}from"node:util";import{gunzipSync as KP}from"node:zlib";import{execFile as wP,spawn as Yb}from"node:child_process";import{copyFile as SP,mkdir as Im,readFile as IP,rm as Qb,stat as zP,writeFile as es}from"node:fs/promises";import{homedir as Xn,platform as e$}from"node:os";import{delimiter as Hb,join as Xe}from"node:path";import{promisify as PP}from"node:util";var Ne=PP(wP),Xt="io.fibteq.myrel-runner",Yt="myrel-runner.service";async function wE(e){let t=ts(),r=pi();await Im(Xe(ee(),"bin"),{recursive:!0,mode:448}),e!==r&&await SP(e,r);let o=[process.execPath,r,"start"],n=AP(),i=await ns(t);if(t==="launchd")await Im(Xe(Xn(),"Library","LaunchAgents"),{recursive:!0}),await es(i.file,TP(o,n,i.log)),await jP(i.file);else if(t==="systemd"){await Im(Xe(Xn(),".config","systemd","user"),{recursive:!0}),await es(i.file,OP(o,n));try{await Ne("systemctl",["--user","daemon-reload"]),await Ne("systemctl",["--user","enable",Yt]),await Ne("systemctl",["--user","restart",Yt])}catch(a){throw await Qb(i.file,{force:!0}),new Error(`Could not register with systemd (${a.message.split(`
109
+ `).filter(Boolean).at(-1)}). Use \`myrel-runner start\` instead.`)}}else await es(i.file,DP(o,i.log)),Yb("wscript.exe",[i.file],{detached:!0,stdio:"ignore"}).unref();return n$()}var pi=()=>Xe(ee(),"bin","myrel-runner.mjs");async function t$(){if(ts()!=="startup")return;let e=await ns("startup");e.installed&&Yb("wscript.exe",[e.file],{detached:!0,stdio:"ignore"}).unref()}async function jP(e){let t=`gui/${process.getuid?.()}`,r=()=>Ne("launchctl",["print",`${t}/${Xt}`]).then(()=>!0,()=>!1);await Ne("launchctl",["bootout",`${t}/${Xt}`]).catch(()=>{});for(let o=0;o<50&&await r();o++)await zm(100);for(let o=1;;o++)try{await Ne("launchctl",["bootstrap",t,e]);break}catch(n){if(o>=5)throw n;await zm(500*o)}for(let o=0;o<30;o++){if((await Ne("launchctl",["print",`${t}/${Xt}`]).catch(()=>null))?.stdout.includes("state = running"))return;await zm(100)}}var zm=e=>new Promise(t=>setTimeout(t,e));async function SE(){let e=ts(),t=await ns(e);return e==="launchd"?await Ne("launchctl",["bootout",`gui/${process.getuid?.()}/${Xt}`]).catch(()=>{}):e==="systemd"&&await Ne("systemctl",["--user","disable","--now",Yt]).catch(()=>{}),await Qb(t.file,{force:!0}),e==="systemd"&&await Ne("systemctl",["--user","daemon-reload"]).catch(()=>{}),n$()}async function n$(){let e=await ns(ts());if(!e.installed)return{...e,running:!1};if(e.manager==="launchd"){let t=await Ne("launchctl",["print",`gui/${process.getuid?.()}/${Xt}`]).catch(()=>null);return{...e,running:!!t?.stdout.includes("state = running")}}if(e.manager==="systemd"){let t=await Ne("systemctl",["--user","is-active",Yt]).catch(()=>null);return{...e,running:t?.stdout.trim()==="active"}}return{...e,running:null}}function ts(){let e=e$();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 ns(e){let t=e==="launchd"?Xe(Xn(),"Library","LaunchAgents",`${Xt}.plist`):e==="systemd"?Xe(Xn(),".config","systemd","user",Yt):Xe(process.env.APPDATA??Xe(Xn(),"AppData","Roaming"),"Microsoft","Windows","Start Menu","Programs","Startup","myrel-runner.vbs"),r=e==="systemd"?`journalctl --user -u ${Yt}`:Xe(ee(),"runner.log"),o=!!await zP(t).catch(()=>null);return{manager:e,file:t,installed:o,log:r}}function AP(){let t={PATH:(process.env.PATH??"").split(Hb).filter(r=>r&&!/[\\/]_npx[\\/]/.test(r)).join(Hb)};return process.env.MYREL_RUNNER_HOME&&(t.MYREL_RUNNER_HOME=process.env.MYREL_RUNNER_HOME),t}var di=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;");function TP(e,t,r){return`<?xml version="1.0" encoding="UTF-8"?>
110
110
  <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
111
111
  <plist version="1.0">
112
112
  <dict>
@@ -129,7 +129,7 @@ ${Object.entries(t).map(([o,n])=>` <key>${di(o)}</key><string>${di(n)}</strin
129
129
  <key>StandardErrorPath</key><string>${di(r)}</string>
130
130
  </dict>
131
131
  </plist>
132
- `}var Xb=e=>`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/%/g,"%%")}"`;function TP(e,t){return`[Unit]
132
+ `}var Xb=e=>`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/%/g,"%%")}"`;function OP(e,t){return`[Unit]
133
133
  Description=Myrel runner (connects this computer to Myrel)
134
134
  After=network-online.target
135
135
 
@@ -143,9 +143,9 @@ ${r$}
143
143
 
144
144
  [Install]
145
145
  WantedBy=default.target
146
- `}var r$="OOMPolicy=continue";function OP(e){return/^OOMPolicy=/m.test(e)||!/^RestartSec=.*$/m.test(e)?null:e.replace(/^RestartSec=.*$/m,t=>`${t}
147
- ${r$}`)}async function i$(){if(e$()!=="linux")return;let e=Xe(Xn(),".config","systemd","user",Yt),t=OP(await SP(e,"utf8").catch(()=>""));t&&(await es(e,t),await Ne("systemctl",["--user","daemon-reload"]))}function NP(e,t){return`' Starts myrel-runner at login. Remove with: myrel-runner service uninstall\r
146
+ `}var r$="OOMPolicy=continue";function NP(e){return/^OOMPolicy=/m.test(e)||!/^RestartSec=.*$/m.test(e)?null:e.replace(/^RestartSec=.*$/m,t=>`${t}
147
+ ${r$}`)}async function i$(){if(e$()!=="linux")return;let e=Xe(Xn(),".config","systemd","user",Yt),t=NP(await IP(e,"utf8").catch(()=>""));t&&(await es(e,t),await Ne("systemctl",["--user","daemon-reload"]))}function DP(e,t){return`' Starts myrel-runner at login. Remove with: myrel-runner service uninstall\r
148
148
  CreateObject("WScript.Shell").Run "${`cmd.exe /c "${e.map(o=>`"${o}"`).join(" ")} >> "${t}" 2>&1"`.replace(/"/g,'""')}", 0, False\r
149
- `}import{spawn as DP}from"node:child_process";var UP="@fibteq/myrel-runner",Pm="@fibteq%2Fmyrel-runner",CP=/^\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?$/;async function o$(e="https://registry.npmjs.org"){try{let t=await fetch(`${e}/${Pm}/latest`,{signal:AbortSignal.timeout(1e4)});if(!t.ok)return null;let{version:r}=await t.json();return typeof r=="string"&&CP.test(r)?r:null}catch{return null}}var jm=uy;function PE(e,t){let r=process.platform==="win32"?"npx.cmd":"npx";return new Promise((o,n)=>{let i=DP(r,["--yes",`--package=${UP}@${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 KP=FP(EP);function Om(e){return{access:e.access,worktrees:e.worktrees!==!1,autoUpdate:e.autoUpdate===!0,remote:e.remoteSettings!==!1}}function u$(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 l$(e=process.argv[1]){return process.versions.bun?"app":e&&ZP(e)===pi()?"service":"manual"}var Am=()=>Tm(ee(),"bin","myrel-runner.prev.mjs"),Nm=()=>Tm(ee(),"update.json"),d$=()=>$e(Nm()).catch(()=>{}),rs=e=>Ze(Nm(),e),Dm=()=>s$(Nm(),{force:!0}),p$=1440*60*1e3;async function m$(e,t="https://registry.npmjs.org"){let r=await fetch(`${t}/${Pm}/${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(RP("sha512").update(a).digest("base64")!==n)throw new Error("The download does not match npm's checksum, so it was not installed.");let s=JP(VP(a),"package/dist/cli.js");if(!s)throw new Error("The download has no dist/cli.js.");return s}function JP(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,f)=>n.toString("utf8",p,p+f).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 f$(e,t){let r=pi(),o=Tm(ee(),"bin","myrel-runner.next.mjs");await LP(o,e,{mode:448});try{let{stdout:n}=await KP(process.execPath,[o,"--version"],{timeout:3e4});if(n.trim()!==t)throw new Error(`it says it is ${n.trim()||"nothing"}`)}catch(n){throw await s$(o,{force:!0}),new Error(`The new version does not start (${n.message.split(`
150
- `)[0]}), so it was not installed.`)}await c$(r).catch(()=>null)&&await a$(r,Am()),await MP(o,r)}async function g$(){return await c$(Am()).catch(()=>null)?(await a$(Am(),pi()),!0):!1}import{execFile as BP}from"node:child_process";import{readFile as WP,statfs as h$}from"node:fs/promises";import{cpus as v$,freemem as GP,homedir as qP,platform as HP,totalmem as XP}from"node:os";import{promisify as YP}from"node:util";var QP=YP(BP);function ej(e=v$()){let t=0,r=0;for(let{times:o}of e)t+=o.idle,r+=o.user+o.nice+o.sys+o.idle+o.irq;return{idle:t,total:r}}function tj(e,t){let r=t.total-e.total;if(r<=0)return;let o=r-(t.idle-e.idle);return Math.round(Math.min(100,Math.max(0,o/r*100))*10)/10}function nj(e){let t=a=>{let s=e.match(new RegExp(`^${a}:\\s+(\\d+)\\s*kB`,"m"));return s?Number(s[1])*1024:void 0},r=t("MemTotal"),o=t("MemAvailable")??t("MemFree");if(r===void 0||o===void 0)return;let n=t("SwapTotal"),i=t("SwapFree");return{total:r,available:Math.min(r,o),...n!==void 0&&i!==void 0&&{swap:{total:n,used:Math.max(0,n-i)}}}}function rj(e,t){let r=Number(e.match(/page size of (\d+) bytes/)?.[1]),o=i=>Number(e.match(new RegExp(`^${i}:\\s+(\\d+)\\.`,"m"))?.[1]),n=(o("Pages active")+o("Pages wired down")+o("Pages occupied by compressor"))*r;if(!(!Number.isFinite(n)||!Number.isFinite(r)))return{total:t,available:Math.min(t,Math.max(0,t-n))}}var ij=()=>({platform:HP(),cores:()=>v$().length,cpuTimes:ej,totalmem:XP,freemem:GP,meminfo:()=>WP("/proc/meminfo","utf8"),vmStat:async()=>(await QP("vm_stat",[],{timeout:5e3,env:We()})).stdout,disk:async()=>{let e=ee(),t=await h$(e).catch(()=>h$(qP()));return{total:t.blocks*t.bsize,free:t.bavail*t.bsize}},runnerMemory:()=>process.memoryUsage.rss(),now:()=>new Date}),is=class{constructor(t,r={}){this.tasks=t;this.sources={...ij(),...r}}tasks;sources;previous;latest;async sample(){let t=this.sources,r=t.cpuTimes(),o=this.previous?tj(this.previous,r):void 0;this.previous=r;let[n,i]=await Promise.all([this.memory(),t.disk().catch(()=>{})]),a={at:t.now().toISOString(),cpu:{...o!==void 0&&{percent:o},cores:Math.max(1,t.cores())},memory:{total:n.total,available:n.available},...n.swap&&{swap:n.swap},...i&&Number.isFinite(i.total)&&Number.isFinite(i.free)&&{disk:{total:Math.round(i.total),free:Math.round(i.free)}},tasks:this.tasks(),runnerMemory:t.runnerMemory()};return this.latest=a,a}async memory(){let t=this.sources,r=t.totalmem(),o={total:r,available:Math.min(r,t.freemem())};try{if(t.platform==="linux")return nj(await t.meminfo())??o;if(t.platform==="darwin")return rj(await t.vmStat(),r)??o}catch{}return o}};var oj=600*1e3,aj=360*60*1e3,y$=120*1e3,os=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 d$();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)<p$){let{from:r,...o}=t;return this.current=o,!1}return await Dm(),!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 Dm(),this.opts.report(null))}async rollback(t){let r=this.pending;if(r){if(this.pending=null,!await(this.opts.restore??g$)().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 rs({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(!jm(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??aj:this.opts.waitMs??oj);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??o$)();!t||!jm(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??m$)(t);await(this.opts.install??f$)(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 rs(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 rs({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 as="0.31.0",uj=360*60*1e3;async function pR(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||Um(),hostname:Um(),platform:$$()})}),o=await r.json().catch(()=>null);if(!r.ok)throw new Error(o?.message??`Pairing failed (${r.status})`);let n=cy.parse(o),i=await ii();return Object.assign(i,{server:t,runnerId:n.runner.id,token:n.token}),await Ta(i),i}async function b$(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 lj="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>`.",dj=900*1e3,mR=75,pj=300*1e3;function mj(e,t){return e.length===t.length&&e.every(r=>t.some(o=>o.id===r.id&&o.version===r.version))}async function fR(e={}){let t=e.log??(x=>console.log(x)),r=e.onStatus??(()=>{}),o=await ii();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 am(),i=await Dy(),a=(x,D)=>{let F=i[x];!D||F&&F.at>=D.at||(i[x]=D,Uy(i).catch(()=>{}),JSON.stringify({...F,at:""})!==JSON.stringify({...D,at:""})&&ue())},s=()=>{n.some(x=>x.id==="codex")&&Na().then(x=>a("codex",x),()=>{})},u=new qa({config:()=>o,sessions:new Aa,log:t,onLimits:a,onChange:vm,version:as}),l=Eb();l.length&&t(`${l.length} task(s) stopped when the runner restarted; Myrel continues them.`),vm([]);let d="stopped",p=null,f=!1,m=0,v,$=new Promise(x=>v=x),k=l$();k==="service"&&i$().catch(()=>{});let P=new os({version:as,running:()=>u.runningIds(),report:x=>z({type:"update.status",update:x}),log:t,restart:()=>{t$().catch(()=>{}).finally(()=>{d="restart",te()})}}),S;await P.init()&&(S=setTimeout(()=>{b$(o).then(x=>{x==="ok"&&P.confirming&&P.rollback("it did not connect within 2 minutes")})},y$),S.unref?.());let T=new Map,z=x=>{x.type==="task.done"&&(r({state:"task",taskId:x.taskId,event:"done",ok:x.ok}),T.set(x.taskId,{frame:x,at:Date.now()})),p?.readyState===WebSocket.OPEN&&p.send(JSON.stringify(x))},C=()=>{for(let[x,{frame:D,at:F}]of T)Date.now()-F>dj?T.delete(x):z(D)},j=new is(()=>u.runningIds().length),A=()=>o.stats!==!1;A()&&await j.sample().catch(()=>{});let ue=()=>z({type:"hello",protocol:ry,version:as,hostname:Um(),platform:$$(),folders:o.folders,clis:n.map(x=>i[x.id]?{...x,limits:i[x.id]}:x),features:["folders","cancel","agent","agent-clis","connectors","skills","project-folders","files","settings","models","git-token","steer","steer-claude","ssh",...k==="service"?["update"]:[],...A()?["stats"]:[]],settings:Om(o),updates:k,...P.state()&&{update:P.state()},running:u.runningIds(),interrupted:l,...A()&&j.latest&&{stats:j.latest}});u.setSender(z);let Ye=async()=>{o=await ii().catch(()=>o),ue()};sj(Bn(),{interval:2e3},Ye);let Ee=setInterval(()=>{if(p?.readyState===WebSocket.OPEN){if(!A())return z({type:"ping"});j.sample().then(x=>z({type:"ping",stats:x}),()=>z({type:"ping"}))}},25e3),Qe=()=>{Promise.all(n.map(async x=>{let D=await si[x.id].models?.().catch(()=>{}),F=JSON.stringify(D)!==JSON.stringify(x.models);return D&&(x.models=D),F&&!!D})).then(x=>x.some(Boolean)&&ue())};Qe(),s();let Qt=()=>{am().then(x=>{if(mj(n,x))return;let D=new Map(n.map(F=>[F.id,F]));n.splice(0,n.length,...x.map(F=>D.get(F.id)?.version===F.version?D.get(F.id):F)),t(`CLIs found: ${n.map(F=>F.id).join(", ")||"none"}`),ue(),Qe(),s()},()=>{})},dt=setInterval(s,600*1e3),mi=setInterval(Qe,360*60*1e3),Yn=setInterval(Qt,pj);dt.unref?.(),Yn.unref?.();let Qn=()=>{wb(x=>u.inUse(x)).then(x=>x.forEach(D=>t(`Removed the finished worktree ${D.path} (${D.branch})`))).catch(()=>{})};Qn();let en=setInterval(Qn,360*60*1e3);en.unref?.();let fi=()=>{k==="service"&&o.autoUpdate&&P.checkNewest().catch(()=>{})},er=setTimeout(fi,600*1e3);er.unref?.();let Z=setInterval(fi,uj);Z.unref?.();let te=()=>{f=!0,clearInterval(Ee),clearInterval(en),clearInterval(dt),clearInterval(mi),clearInterval(Yn),clearInterval(Z),clearTimeout(er),clearTimeout(S),cj(Bn(),Ye),Cb(u.stopAll()),p?.close(1e3),r({state:"stopped",reason:d}),v(d)},pe=async x=>{let{requestId:D}=x;if(x.type==="dirs.list")return z({type:"dirs",requestId:D,...await ib(x.path)});if(x.type==="task.steer")return z({type:"task.steered",requestId:D,taken:await u.steer(x.taskId,x.text)});if(x.type==="file.read")return z({type:"file",requestId:D,...await Nb(o,x)});if(x.type==="ssh.keygen"){let F=await Jb({projectId:x.projectId,alias:x.alias},x.comment,x.existing);return t(`${x.existing?"Using":"Made"} an SSH key for ${x.alias} (${F.fingerprint}, from Myrel)`),z({type:"ssh.key",requestId:D,...F})}if(x.type==="ssh.keys")return z({type:"ssh.keylist",requestId:D,keys:await Bb()});if(x.type==="ssh.hostkeys")return z({type:"ssh.hostkeylist",requestId:D,keys:await Wb(x.host,x.port)});if(x.type==="ssh.test")return z({type:"ssh.result",requestId:D,...await qb(x.target)});if(x.type==="ssh.run")return t(`SSH ${x.target.alias}: ${x.command.split(`
151
- `)[0].slice(0,80)}`),z({type:"ssh.result",requestId:D,...await Sm(x.target,x.command)});if(x.type==="ssh.forget")return await wm({projectId:x.projectId,alias:x.alias}),t(`Forgot the SSH key for ${x.alias} (from Myrel)`),z({type:"ssh.result",requestId:D,exitCode:0,stdout:"",stderr:"",truncated:!1,ms:0});if(x.type==="runner.update"){if(k!=="service")throw new Error(k==="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 ${x.version} (from Myrel)${x.now?"":" once the running tasks finish"}`),z({type:"update.accepted",requestId:D,update:P.request(x.version,x.now)})}if(o=await ii(),x.type==="settings.set")return u$(o,x.settings),await Ta(o),t(`Settings changed from Myrel: ${Object.entries(x.settings).map(([F,gi])=>`${F} ${gi}`).join(", ")}`),z({type:"settings",requestId:D,settings:Om(o)});if(x.type==="folder.share"){let F=await ob(x.path);Py(o,F)&&t(`Shared ${F} (from Myrel)`)}else jy(o,x.path)&&t(`Stopped sharing ${x.path} (from Myrel)`);await Ta(o),z({type:"folders",requestId:D,folders:o.folders})},ie=()=>{if(f)return;let x=`${o.server.replace(/^http/,"ws")}/api/runner/connect`;r({state:"connecting"});let D=new WebSocket(x,{headers:{authorization:`Bearer ${o.token}`}});p=D;let F=!1;D.onopen=()=>{F=!0,m=0,C(),ue()},D.onmessage=je=>{let tn=JSON.parse(String(je.data)),ss=sy.safeParse(tn);if(!ss.success){let nn=tn;if(nn?.type==="task.start"&&typeof nn.taskId=="string"){let Em=ss.error.issues[0],Rm=`${Em?.path.join(".")||"frame"}: ${Em?.message??"invalid"}`;t(`\u2717 could not read task ${nn.taskId} (${Rm})`),z({type:"task.done",taskId:nn.taskId,ok:!1,result:`myrel-runner ${as} could not read this task (${Rm}). Update myrel-runner.`})}return}let _e=ss.data;_e.type==="welcome"&&(t(`\u25CF Connected to ${o.server} as "${_e.name}"`),r({state:"online",name:_e.name}),P.confirmed()),_e.type==="task.start"&&(r({state:"task",taskId:_e.taskId,event:"started"}),u.start(_e)),_e.type==="task.cancel"&&u.cancel(_e.taskId),_e.type==="task.github"&&u.renewGithub(_e.taskId,_e.github),"requestId"in _e&&pe(_e).catch(nn=>z({type:"request.failed",requestId:_e.requestId,message:fj(nn)}))};let gi=!1,Cm=async je=>{if(gi||p!==D||f)return;if(gi=!0,!F&&await b$(o)==="invalid")return t(lj),e.onRevoked?.(),d="revoked",te();if(je.code===4401)return t("This computer was removed from Myrel. Pair it again with `myrel-runner pair`."),e.onRevoked?.(),d="revoked",te();if(je.code===4e3)return t("myrel-runner was started somewhere else with this computer's login, so this one stops."),d="replaced",te();if(je.code===4400)return t(`The server refused this runner: ${je.reason}`),P.confirming&&(await P.rollback(`the server refused it: ${je.reason}`),f)?void 0:(d="refused",te());let tn=Math.min(3e4,1e3*2**m++);t(`\u25CB Disconnected${je.reason?` (${je.reason})`:""}. Reconnecting in ${Math.round(tn/1e3)}s\u2026`),r({state:"offline",reason:je.reason||`code ${je.code}`,retryInMs:tn}),setTimeout(ie,tn)};D.onclose=je=>{Cm(je)},D.onerror=()=>{F||Cm({code:1006,reason:""})}};return ie(),t(`Sharing ${o.folders.length} folder(s); CLIs found: ${n.map(x=>x.id).join(", ")||"none"}`),dm().then(x=>{let D=mb(x);D&&t(D)}),{stop:te,done:$}}function fj(e){return(e instanceof Error?e.message:String(e)).slice(0,500)}export{si as ADAPTERS,bz as APPROVE_TOOL,Oe as MYREL_MCP_SERVER,UP as PACKAGE_NAME,Pm as PACKAGE_PATH,mR as RESTART_EXIT_CODE,as as RUNNER_VERSION,Xt as SERVICE_NAME,Aa as SessionStore,qa as TaskRunner,M0 as branchFor,b$ as checkPairing,We as childEnv,Bn as configPath,Dz as cursorConfig,am as detectClis,K0 as exitMessage,Qy as hasAppServer,eb as hasStreamInput,kE as installService,jm as isNewer,o$ as latestVersion,AP as launchdPlist,ib as listDirs,ui as listWorktrees,ii as loadConfig,Zz as missingReason,qy as modelFlags,Xy as opencodeMajor,Pz as opencodeServerArgs,pR as pair,vz as parseClaudeHelp,yz as parseCodexModels,Lz as parseKimiModels,rm as parseModelLines,Rz as parseMuseCatalog,wb as pruneWorktrees,$e as readJson,t$ as relaunchService,L0 as removeWorktree,PE as runVersion,ee as runnerHome,Ma as safeModel,Ge as safeModelArg,mj as sameClis,Ta as saveConfig,pi as serviceBin,n$ as serviceStatus,Py as shareFolder,ob as shareableFolder,Ha as sharedFolder,fR as startRunner,NP as startupScript,TP as systemdUnit,xb as threadWorktree,wE as uninstallService,jy as unshareFolder,i$ as upgradeService,OP as upgradeSystemdUnit,kb as worktreeState,Ze as writeJson};
149
+ `}import{spawn as UP}from"node:child_process";var CP="@fibteq/myrel-runner",Pm="@fibteq%2Fmyrel-runner",EP=/^\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?$/;async function o$(e="https://registry.npmjs.org"){try{let t=await fetch(`${e}/${Pm}/latest`,{signal:AbortSignal.timeout(1e4)});if(!t.ok)return null;let{version:r}=await t.json();return typeof r=="string"&&EP.test(r)?r:null}catch{return null}}var jm=uy;function jE(e,t){let r=process.platform==="win32"?"npx.cmd":"npx";return new Promise((o,n)=>{let i=UP(r,["--yes",`--package=${CP}@${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 JP=VP(RP);function Om(e){return{access:e.access,worktrees:e.worktrees!==!1,autoUpdate:e.autoUpdate===!0,remote:e.remoteSettings!==!1}}function u$(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 l$(e=process.argv[1]){return process.versions.bun?"app":e&&FP(e)===pi()?"service":"manual"}var Am=()=>Tm(ee(),"bin","myrel-runner.prev.mjs"),Nm=()=>Tm(ee(),"update.json"),d$=()=>$e(Nm()).catch(()=>{}),rs=e=>Ze(Nm(),e),Dm=()=>s$(Nm(),{force:!0}),p$=1440*60*1e3;async function m$(e,t="https://registry.npmjs.org"){let r=await fetch(`${t}/${Pm}/${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(MP("sha512").update(a).digest("base64")!==n)throw new Error("The download does not match npm's checksum, so it was not installed.");let s=BP(KP(a),"package/dist/cli.js");if(!s)throw new Error("The download has no dist/cli.js.");return s}function BP(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,f)=>n.toString("utf8",p,p+f).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 f$(e,t){let r=pi(),o=Tm(ee(),"bin","myrel-runner.next.mjs");await ZP(o,e,{mode:448});try{let{stdout:n}=await JP(process.execPath,[o,"--version"],{timeout:3e4});if(n.trim()!==t)throw new Error(`it says it is ${n.trim()||"nothing"}`)}catch(n){throw await s$(o,{force:!0}),new Error(`The new version does not start (${n.message.split(`
150
+ `)[0]}), so it was not installed.`)}await c$(r).catch(()=>null)&&await a$(r,Am()),await LP(o,r)}async function g$(){return await c$(Am()).catch(()=>null)?(await a$(Am(),pi()),!0):!1}import{execFile as WP}from"node:child_process";import{readFile as GP,statfs as h$}from"node:fs/promises";import{cpus as v$,freemem as qP,homedir as HP,platform as XP,totalmem as YP}from"node:os";import{promisify as QP}from"node:util";var ej=QP(WP);function tj(e=v$()){let t=0,r=0;for(let{times:o}of e)t+=o.idle,r+=o.user+o.nice+o.sys+o.idle+o.irq;return{idle:t,total:r}}function nj(e,t){let r=t.total-e.total;if(r<=0)return;let o=r-(t.idle-e.idle);return Math.round(Math.min(100,Math.max(0,o/r*100))*10)/10}function rj(e){let t=a=>{let s=e.match(new RegExp(`^${a}:\\s+(\\d+)\\s*kB`,"m"));return s?Number(s[1])*1024:void 0},r=t("MemTotal"),o=t("MemAvailable")??t("MemFree");if(r===void 0||o===void 0)return;let n=t("SwapTotal"),i=t("SwapFree");return{total:r,available:Math.min(r,o),...n!==void 0&&i!==void 0&&{swap:{total:n,used:Math.max(0,n-i)}}}}function ij(e,t){let r=Number(e.match(/page size of (\d+) bytes/)?.[1]),o=i=>Number(e.match(new RegExp(`^${i}:\\s+(\\d+)\\.`,"m"))?.[1]),n=(o("Pages active")+o("Pages wired down")+o("Pages occupied by compressor"))*r;if(!(!Number.isFinite(n)||!Number.isFinite(r)))return{total:t,available:Math.min(t,Math.max(0,t-n))}}var oj=()=>({platform:XP(),cores:()=>v$().length,cpuTimes:tj,totalmem:YP,freemem:qP,meminfo:()=>GP("/proc/meminfo","utf8"),vmStat:async()=>(await ej("vm_stat",[],{timeout:5e3,env:We()})).stdout,disk:async()=>{let e=ee(),t=await h$(e).catch(()=>h$(HP()));return{total:t.blocks*t.bsize,free:t.bavail*t.bsize}},runnerMemory:()=>process.memoryUsage.rss(),now:()=>new Date}),is=class{constructor(t,r={}){this.tasks=t;this.sources={...oj(),...r}}tasks;sources;previous;latest;async sample(){let t=this.sources,r=t.cpuTimes(),o=this.previous?nj(this.previous,r):void 0;this.previous=r;let[n,i]=await Promise.all([this.memory(),t.disk().catch(()=>{})]),a={at:t.now().toISOString(),cpu:{...o!==void 0&&{percent:o},cores:Math.max(1,t.cores())},memory:{total:n.total,available:n.available},...n.swap&&{swap:n.swap},...i&&Number.isFinite(i.total)&&Number.isFinite(i.free)&&{disk:{total:Math.round(i.total),free:Math.round(i.free)}},tasks:this.tasks(),runnerMemory:t.runnerMemory()};return this.latest=a,a}async memory(){let t=this.sources,r=t.totalmem(),o={total:r,available:Math.min(r,t.freemem())};try{if(t.platform==="linux")return rj(await t.meminfo())??o;if(t.platform==="darwin")return ij(await t.vmStat(),r)??o}catch{}return o}};var aj=600*1e3,sj=360*60*1e3,y$=120*1e3,os=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 d$();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)<p$){let{from:r,...o}=t;return this.current=o,!1}return await Dm(),!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 Dm(),this.opts.report(null))}async rollback(t){let r=this.pending;if(r){if(this.pending=null,!await(this.opts.restore??g$)().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 rs({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(!jm(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??sj:this.opts.waitMs??aj);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??o$)();!t||!jm(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??m$)(t);await(this.opts.install??f$)(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 rs(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 rs({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 as="0.32.0",lj=360*60*1e3;async function mR(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||Um(),hostname:Um(),platform:$$()})}),o=await r.json().catch(()=>null);if(!r.ok)throw new Error(o?.message??`Pairing failed (${r.status})`);let n=cy.parse(o),i=await ii();return Object.assign(i,{server:t,runnerId:n.runner.id,token:n.token}),await Ta(i),i}async function b$(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 dj="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>`.",pj=900*1e3,fR=75,mj=300*1e3;function fj(e,t){return e.length===t.length&&e.every(r=>t.some(o=>o.id===r.id&&o.version===r.version))}async function gR(e={}){let t=e.log??(x=>console.log(x)),r=e.onStatus??(()=>{}),o=await ii();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 am(),i=await Dy(),a=(x,D)=>{let F=i[x];!D||F&&F.at>=D.at||(i[x]=D,Uy(i).catch(()=>{}),JSON.stringify({...F,at:""})!==JSON.stringify({...D,at:""})&&ue())},s=()=>{n.some(x=>x.id==="codex")&&Na().then(x=>a("codex",x),()=>{})},u=new qa({config:()=>o,sessions:new Aa,log:t,onLimits:a,onChange:vm,version:as}),l=Eb();l.length&&t(`${l.length} task(s) stopped when the runner restarted; Myrel continues them.`),vm([]);let d="stopped",p=null,f=!1,m=0,v,$=new Promise(x=>v=x),k=l$();k==="service"&&i$().catch(()=>{});let P=new os({version:as,running:()=>u.runningIds(),report:x=>z({type:"update.status",update:x}),log:t,restart:()=>{t$().catch(()=>{}).finally(()=>{d="restart",te()})}}),S;await P.init()&&(S=setTimeout(()=>{b$(o).then(x=>{x==="ok"&&P.confirming&&P.rollback("it did not connect within 2 minutes")})},y$),S.unref?.());let T=new Map,z=x=>{x.type==="task.done"&&(r({state:"task",taskId:x.taskId,event:"done",ok:x.ok}),T.set(x.taskId,{frame:x,at:Date.now()})),p?.readyState===WebSocket.OPEN&&p.send(JSON.stringify(x))},C=()=>{for(let[x,{frame:D,at:F}]of T)Date.now()-F>pj?T.delete(x):z(D)},j=new is(()=>u.runningIds().length),A=()=>o.stats!==!1;A()&&await j.sample().catch(()=>{});let ue=()=>z({type:"hello",protocol:ry,version:as,hostname:Um(),platform:$$(),folders:o.folders,clis:n.map(x=>i[x.id]?{...x,limits:i[x.id]}:x),features:["folders","cancel","agent","agent-clis","connectors","skills","project-folders","files","settings","models","git-token","steer","steer-claude","ssh",...k==="service"?["update"]:[],...A()?["stats"]:[]],settings:Om(o),updates:k,...P.state()&&{update:P.state()},running:u.runningIds(),interrupted:l,...A()&&j.latest&&{stats:j.latest}});u.setSender(z);let Ye=async()=>{o=await ii().catch(()=>o),ue()};cj(Bn(),{interval:2e3},Ye);let Ee=setInterval(()=>{if(p?.readyState===WebSocket.OPEN){if(!A())return z({type:"ping"});j.sample().then(x=>z({type:"ping",stats:x}),()=>z({type:"ping"}))}},25e3),Qe=()=>{Promise.all(n.map(async x=>{let D=await si[x.id].models?.().catch(()=>{}),F=JSON.stringify(D)!==JSON.stringify(x.models);return D&&(x.models=D),F&&!!D})).then(x=>x.some(Boolean)&&ue())};Qe(),s();let Qt=()=>{am().then(x=>{if(fj(n,x))return;let D=new Map(n.map(F=>[F.id,F]));n.splice(0,n.length,...x.map(F=>D.get(F.id)?.version===F.version?D.get(F.id):F)),t(`CLIs found: ${n.map(F=>F.id).join(", ")||"none"}`),ue(),Qe(),s()},()=>{})},dt=setInterval(s,600*1e3),mi=setInterval(Qe,360*60*1e3),Yn=setInterval(Qt,mj);dt.unref?.(),Yn.unref?.();let Qn=()=>{wb(x=>u.inUse(x)).then(x=>x.forEach(D=>t(`Removed the finished worktree ${D.path} (${D.branch})`))).catch(()=>{})};Qn();let en=setInterval(Qn,360*60*1e3);en.unref?.();let fi=()=>{k==="service"&&o.autoUpdate&&P.checkNewest().catch(()=>{})},er=setTimeout(fi,600*1e3);er.unref?.();let Z=setInterval(fi,lj);Z.unref?.();let te=()=>{f=!0,clearInterval(Ee),clearInterval(en),clearInterval(dt),clearInterval(mi),clearInterval(Yn),clearInterval(Z),clearTimeout(er),clearTimeout(S),uj(Bn(),Ye),Cb(u.stopAll()),p?.close(1e3),r({state:"stopped",reason:d}),v(d)},pe=async x=>{let{requestId:D}=x;if(x.type==="dirs.list")return z({type:"dirs",requestId:D,...await ib(x.path)});if(x.type==="task.steer")return z({type:"task.steered",requestId:D,taken:await u.steer(x.taskId,x.text)});if(x.type==="file.read")return z({type:"file",requestId:D,...await Nb(o,x)});if(x.type==="ssh.keygen"){let F=await Jb({projectId:x.projectId,alias:x.alias},x.comment,x.existing);return t(`${x.existing?"Using":"Made"} an SSH key for ${x.alias} (${F.fingerprint}, from Myrel)`),z({type:"ssh.key",requestId:D,...F})}if(x.type==="ssh.keys")return z({type:"ssh.keylist",requestId:D,keys:await Bb()});if(x.type==="ssh.hostkeys")return z({type:"ssh.hostkeylist",requestId:D,keys:await Wb(x.host,x.port)});if(x.type==="ssh.test")return z({type:"ssh.result",requestId:D,...await qb(x.target)});if(x.type==="ssh.run")return t(`SSH ${x.target.alias}: ${x.command.split(`
151
+ `)[0].slice(0,80)}`),z({type:"ssh.result",requestId:D,...await Sm(x.target,x.command)});if(x.type==="ssh.forget")return await wm({projectId:x.projectId,alias:x.alias}),t(`Forgot the SSH key for ${x.alias} (from Myrel)`),z({type:"ssh.result",requestId:D,exitCode:0,stdout:"",stderr:"",truncated:!1,ms:0});if(x.type==="runner.update"){if(k!=="service")throw new Error(k==="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 ${x.version} (from Myrel)${x.now?"":" once the running tasks finish"}`),z({type:"update.accepted",requestId:D,update:P.request(x.version,x.now)})}if(o=await ii(),x.type==="settings.set")return u$(o,x.settings),await Ta(o),t(`Settings changed from Myrel: ${Object.entries(x.settings).map(([F,gi])=>`${F} ${gi}`).join(", ")}`),z({type:"settings",requestId:D,settings:Om(o)});if(x.type==="folder.share"){let F=await ob(x.path);Py(o,F)&&t(`Shared ${F} (from Myrel)`)}else jy(o,x.path)&&t(`Stopped sharing ${x.path} (from Myrel)`);await Ta(o),z({type:"folders",requestId:D,folders:o.folders})},ie=()=>{if(f)return;let x=`${o.server.replace(/^http/,"ws")}/api/runner/connect`;r({state:"connecting"});let D=new WebSocket(x,{headers:{authorization:`Bearer ${o.token}`}});p=D;let F=!1;D.onopen=()=>{F=!0,m=0,C(),ue()},D.onmessage=je=>{let tn=JSON.parse(String(je.data)),ss=sy.safeParse(tn);if(!ss.success){let nn=tn;if(nn?.type==="task.start"&&typeof nn.taskId=="string"){let Em=ss.error.issues[0],Rm=`${Em?.path.join(".")||"frame"}: ${Em?.message??"invalid"}`;t(`\u2717 could not read task ${nn.taskId} (${Rm})`),z({type:"task.done",taskId:nn.taskId,ok:!1,result:`myrel-runner ${as} could not read this task (${Rm}). Update myrel-runner.`})}return}let _e=ss.data;_e.type==="welcome"&&(t(`\u25CF Connected to ${o.server} as "${_e.name}"`),r({state:"online",name:_e.name}),P.confirmed()),_e.type==="task.start"&&(r({state:"task",taskId:_e.taskId,event:"started"}),u.start(_e)),_e.type==="task.cancel"&&u.cancel(_e.taskId),_e.type==="task.github"&&u.renewGithub(_e.taskId,_e.github),"requestId"in _e&&pe(_e).catch(nn=>z({type:"request.failed",requestId:_e.requestId,message:gj(nn)}))};let gi=!1,Cm=async je=>{if(gi||p!==D||f)return;if(gi=!0,!F&&await b$(o)==="invalid")return t(dj),e.onRevoked?.(),d="revoked",te();if(je.code===4401)return t("This computer was removed from Myrel. Pair it again with `myrel-runner pair`."),e.onRevoked?.(),d="revoked",te();if(je.code===4e3)return t("myrel-runner was started somewhere else with this computer's login, so this one stops."),d="replaced",te();if(je.code===4400)return t(`The server refused this runner: ${je.reason}`),P.confirming&&(await P.rollback(`the server refused it: ${je.reason}`),f)?void 0:(d="refused",te());let tn=Math.min(3e4,1e3*2**m++);t(`\u25CB Disconnected${je.reason?` (${je.reason})`:""}. Reconnecting in ${Math.round(tn/1e3)}s\u2026`),r({state:"offline",reason:je.reason||`code ${je.code}`,retryInMs:tn}),setTimeout(ie,tn)};D.onclose=je=>{Cm(je)},D.onerror=()=>{F||Cm({code:1006,reason:""})}};return ie(),t(`Sharing ${o.folders.length} folder(s); CLIs found: ${n.map(x=>x.id).join(", ")||"none"}`),dm().then(x=>{let D=mb(x);D&&t(D)}),{stop:te,done:$}}function gj(e){return(e instanceof Error?e.message:String(e)).slice(0,500)}export{si as ADAPTERS,bz as APPROVE_TOOL,Oe as MYREL_MCP_SERVER,CP as PACKAGE_NAME,Pm as PACKAGE_PATH,fR as RESTART_EXIT_CODE,as as RUNNER_VERSION,Xt as SERVICE_NAME,Aa as SessionStore,qa as TaskRunner,L0 as branchFor,b$ as checkPairing,We as childEnv,Bn as configPath,Dz as cursorConfig,am as detectClis,J0 as exitMessage,Qy as hasAppServer,eb as hasStreamInput,wE as installService,jm as isNewer,o$ as latestVersion,TP as launchdPlist,ib as listDirs,ui as listWorktrees,ii as loadConfig,Fz as missingReason,qy as modelFlags,Xy as opencodeMajor,Pz as opencodeServerArgs,mR as pair,vz as parseClaudeHelp,yz as parseCodexModels,Zz as parseKimiModels,rm as parseModelLines,Mz as parseMuseCatalog,wb as pruneWorktrees,$e as readJson,t$ as relaunchService,Z0 as removeWorktree,jE as runVersion,ee as runnerHome,Ma as safeModel,Ge as safeModelArg,fj as sameClis,Ta as saveConfig,pi as serviceBin,n$ as serviceStatus,Py as shareFolder,ob as shareableFolder,Ha as sharedFolder,gR as startRunner,DP as startupScript,OP as systemdUnit,xb as threadWorktree,SE as uninstallService,jy as unshareFolder,i$ as upgradeService,NP as upgradeSystemdUnit,kb as worktreeState,Ze as writeJson};