@oss-autopilot/core 3.42.2 → 3.42.4

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.
@@ -60,7 +60,7 @@ ${c}`:c:"",d=Function,p=`return (input) => {
60
60
  ${c}
61
61
  }`,m;try{m=new d(...i,p)(...a)}catch(f){throw new _e(`this schema (generated code failed to evaluate: ${f.message})`)}return t?.debug&&(m.code=u),m.definite=n.definite,m}function ce(e,t){for(let[n,s]of e.constants)if(s===t)return n;let r=`c${e.constantCounter++}`;return e.constants.set(r,t),r}function zs(e,t){return e.definite=!1,ce(e,t)}function te(e){return`v${e.varCounter++}`}function LG(e,t){let r=e._zod.run({value:t,issues:[]},{});if(r&&typeof r.then=="function")return Mt;let n=r;return n.issues.length===0?n.value:Mt}function Ot(e,t,r,n,s=!0){let o=e.content.length,i=t.constants.size,a=t.constantCounter,c=t.varCounter;try{return Ze(e,t,r,n,s)}catch(u){if(!(u instanceof _e)||!u.islandable)throw u;if(e.content.length=o,t.constants.size>i){let d=Array.from(t.constants.keys()).slice(i);for(let p of d)t.constants.delete(p)}return t.constantCounter=a,t.varCounter=c,MG(e,t,r,n)}}function MG(e,t,r,n){t.definite=!1;let s=ce(t,r),o=ce(t,LG),i=te(t);return e.write(`const ${i} = ${o}(${s}, ${n});`),e.write(`if (${i} === INVALID) return INVALID;`),i}function NG(e,t,r,n){let s=r._zod.def.checks;if(!s||s.length===0)return n;let o=n;for(let i of s){let a=i._zod.def;if(a.when&&!FG.has(a.check))throw new _e('check with a custom "when" condition');switch(a.check){case"greater_than":GG(e,t,a,o);break;case"less_than":UG(e,t,a,o);break;case"multiple_of":jG(e,t,a,o);break;case"number_format":CP(e,a,o);break;case"min_length":{let c=Zn(a.minimum,"min_length"),u=Ub(e,t,o,`${o}.length >= ${c} && ${o}.length < ${a.minimum*2}`);e.write(`if (${u} < ${c}) return INVALID;`);break}case"max_length":{let c=Zn(a.maximum,"max_length"),u=Ub(e,t,o,`${o}.length > ${c}`);e.write(`if (${u} > ${c}) return INVALID;`);break}case"length_equals":{let c=Zn(a.length,"length_equals"),u=Ub(e,t,o,`${o}.length >= ${c} && ${o}.length <= ${a.length*2}`);e.write(`if (${u} !== ${c}) return INVALID;`);break}case"min_size":e.write(`if (${o}.size < ${Zn(a.minimum,"min_size")}) return INVALID;`);break;case"max_size":e.write(`if (${o}.size > ${Zn(a.maximum,"max_size")}) return INVALID;`);break;case"size_equals":e.write(`if (${o}.size !== ${Zn(a.size,"size_equals")}) return INVALID;`);break;case"string_format":o=PP(e,t,a,o);break;case"custom":o=qG(e,t,i,o);break;case"bigint_format":zG(e,a,o);break;case"mime_type":BG(e,t,a,o);break;case"property":WG(e,t,a,o);break;case"properties":HG(e,t,a,o);break;case"overwrite":{let c=te(t);VG(e,t,i,o,c),o=c;break}default:throw new _e(`check type ${a.check}`)}}return o}function Ub(e,t,r,n){let s=ce(t,Ms),o=te(t);return e.write(`const ${o} = typeof ${r} === "string" && ${n} ? ${s}(${r}) : ${r}.length;`),o}function Zn(e,t){if(typeof e!="number"||!Number.isFinite(e))throw new _e(`${t} bound of type ${typeof e}`);return`${e}`}function kP(e,t){if(typeof t=="bigint")return`${t}n`;if(typeof t=="number"){if(Number.isNaN(t))throw new _e("comparison check with NaN bound");return`${t}`}if(t instanceof Date){if(Number.isNaN(t.getTime()))throw new _e("comparison check with Invalid Date bound");return ce(e,t)}throw new _e(`comparison check bound of type ${typeof t}`)}function GG(e,t,r,n){let s=r.inclusive?"<":"<=";e.write(`if (${n} ${s} ${kP(t,r.value)}) return INVALID;`)}function UG(e,t,r,n){let s=r.inclusive?">":">=";e.write(`if (${n} ${s} ${kP(t,r.value)}) return INVALID;`)}function jG(e,t,r,n){if(typeof r.value=="bigint"){if(r.value===BigInt(0))throw new _e("multiple_of check with a zero divisor");e.write(`if (${n} % ${r.value}n !== 0n) return INVALID;`)}else{let s=ce(t,lc);e.write(`if (${s}(${n}, ${Zn(r.value,"multiple_of")}) !== 0) return INVALID;`)}}function CP(e,t,r){let n=t.format;switch(n){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 _e(`number format ${n}`)}}function zG(e,t,r){let n=t.format;if(n)switch(n){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 _e(`bigint format ${n}`)}}function BG(e,t,r,n){let s=r.mime;if(s&&s.length>0){let o=ce(t,new Set(s));e.write(`if (!${o}.has(${n}.type)) return INVALID;`)}}function HG(e,t,r,n){if(r.when)throw new _e('check with a custom "when" condition');e.write(`if (${n} == null) return INVALID;`);let s=r.shape;for(let o of Reflect.ownKeys(s)){let i=typeof o=="symbol"?ce(t,o):Dt(o),a=te(t);e.write(`const ${a} = ${n}[${i}];`),Ot(e,t,s[o],a,!1)}}function WG(e,t,r,n){let s=`${n}[${JSON.stringify(r.property)}]`;Ze(e,t,r.schema,s)}function VG(e,t,r,n,s){let o=r._zod.def.tx;if(!o)throw new _e("overwrite check without a transform function");if(Bs(o))throw new Or("z.compile: async overwrite transforms are not supported");let i=ce(t,o);e.write(`const ${s} = ${i}(${n});`)}function jb(){throw new Kt}function Hb(e){this.issues.push(e)}function qG(e,t,r,n){let s=r._zod.def;if(s.fn){if(Bs(s.fn))throw new Or("z.compile: async .refine() predicates are not supported");let o=zs(t,s.fn),i=ce(t,jb),a=te(t);return e.write(`const ${a} = ${o}(${n});`),e.write(`if (${a} instanceof Promise) ${i}();`),e.write(`if (!${a}) return INVALID;`),n}if(r._zod.check){if(Bs(r._zod.check))throw new Or("z.compile: async .superRefine() / check functions are not supported");let o=r._zod.check,a=zs(t,u=>{let d={value:u,issues:[],addIssue:Hb};return o(d)instanceof Promise&&jb(),d.issues.length===0?d.value:Mt}),c=te(t);return e.write(`const ${c} = ${a}(${n});`),e.write(`if (${c} === INVALID) return INVALID;`),c}throw new _e("custom check without a predicate or check function")}function PP(e,t,r,n,s=!0){let o=r.format;if(o==="base64"){let u=ce(t,$c);return e.write(`if (!${u}(${n})) return INVALID;`),n}if(o==="base64url"){let u=ce(t,Sd);return e.write(`if (!${u}(${n})) return INVALID;`),n}if(o==="jwt"){let u=ce(t,kd),d=ce(t,r.alg??null);return e.write(`if (!${u}(${n}, ${d})) return INVALID;`),n}if(o==="ipv6"){let u=ce(t,Tc);return e.write(`if (!${u}(${n})) return INVALID;`),n}if(o==="cidrv6"){let u=ce(t,wd);return e.write(`if (!${u}(${n})) return INVALID;`),n}if(o==="credit_card"){let u=ce(t,_d);return e.write(`if (!${u}(${n})) return INVALID;`),n}if(o==="iban"){let u=ce(t,vd);return e.write(`if (!${u}(${n})) return INVALID;`),n}let i=r;if(o==="url"||o==="httpurl"||i.normalize||i.hostname!==void 0||i.protocol!==void 0){let u=ce(t,hd),d=ce(t,r),p=te(t),m=te(t);if(e.write(`const ${p} = ${n}.trim();`),e.write(`const ${m} = ${u}(${p}, ${d});`),e.write(`if (typeof ${m} === "number") return INVALID;`),i.hostname!==void 0){let y=ce(t,yd);e.write(`if (!${y}(${m}, ${d}.hostname)) return INVALID;`)}if(i.protocol!==void 0){let y=ce(t,bd);e.write(`if (!${y}(${m}, ${d}.protocol)) return INVALID;`)}if(!s)return null;let f=te(t),g=i.normalize?`${m}.href`:`${ce(t,Ac)}(${p})`;return e.write(`const ${f} = ${g};`),f}let a=r.fn;if(a){if(Bs(a))throw new _e(`async string format ${o}`);let u=ce(t,a);return e.write(`if (!${u}(${n})) return INVALID;`),n}if(ZG.has(o)&&r.pattern){let u=ce(t,r.pattern);return e.write(`${u}.lastIndex = 0;`),e.write(`if (!${u}.test(${n})) return INVALID;`),n}let c=r.format;switch(c){case"regex":throw new _e("regex format without a pattern");case"lowercase":e.write(`if (${n} !== ${n}.toLowerCase()) return INVALID;`);break;case"uppercase":e.write(`if (${n} !== ${n}.toUpperCase()) return INVALID;`);break;case"includes":e.write(`if (!${n}.includes(${Dt(r.includes)})) return INVALID;`);break;case"starts_with":{let u=r.prefix;e.write(`if (${n}.slice(0, ${u.length}) !== ${Dt(u)}) return INVALID;`);break}case"ends_with":{let u=r.suffix;e.write(`if (${n}.slice(-${u.length}) !== ${Dt(u)}) return INVALID;`);break}default:throw new _e(`string format ${c}`)}return n}function Ze(e,t,r,n,s=!0){let o=r._zod.def,i=o.type;if(o.coerce)throw new _e(`coercion (z.coerce.${i}())`);let a=s||!!o.checks?.length,c;switch(i){case"string":c=KG(e,t,r,n,a);break;case"number":c=JG(e,r,n);break;case"boolean":c=YG(e,n);break;case"bigint":c=QG(e,r,n);break;case"symbol":c=XG(e,n);break;case"undefined":c=eU(e,n);break;case"null":c=tU(e,n);break;case"any":case"unknown":c=n;break;case"never":e.write("return INVALID;"),c=n;break;case"void":c=rU(e,n);break;case"nan":c=nU(e,n);break;case"date":c=sU(e,n);break;case"object":c=oU(e,t,r,n,a);break;case"optional":c=iU(e,t,r,n,a);break;case"nullable":c=uU(e,t,r,n,a);break;case"array":c=lU(e,t,r,n,a);break;case"literal":c=dU(e,t,r,n);break;case"enum":c=pU(e,t,r,n);break;case"readonly":{let u=SP(e,t,r,n),d=te(t);e.write(`const ${d} = Object.freeze(${u});`),c=d;break}case"success":SP(e,t,r,n),c="true";break;case"default":case"prefault":c=mU(e,t,r,n);break;case"nonoptional":c=fU(e,t,r,n);break;case"tuple":c=gU(e,t,r,n);break;case"union":c=hU(e,t,r,n);break;case"intersection":c=wU(e,t,r,n);break;case"record":c=RU(e,t,r,n);break;case"map":c=_U(e,t,r,n);break;case"set":c=vU(e,t,r,n);break;case"file":c=kU(e,n);break;case"template_literal":c=CU(e,t,r,n);break;case"lazy":c=PU(e,t,r,n);break;case"pipe":c=EU(e,t,r,n);break;case"custom":c=AU(e,t,r,n);break;case"transform":c=OU(e,t,r,n);break;case"catch":c=$U(e,t,r,n);break;default:throw new _e(`schema type ${i}`)}return c===null?null:NG(e,t,r,c)}function KG(e,t,r,n,s=!0){e.write(`if (typeof ${n} !== "string") return INVALID;`);let o=r._zod.def;return o.format===void 0?n:PP(e,t,o,n,s)}function JG(e,t,r){e.write(`if (typeof ${r} !== "number" || !Number.isFinite(${r})) return INVALID;`);let n=t._zod.def;return n.check==="number_format"&&n.format&&CP(e,{format:n.format},r),r}function YG(e,t){return e.write(`if (typeof ${t} !== "boolean") return INVALID;`),t}function QG(e,t,r){e.write(`if (typeof ${r} !== "bigint") return INVALID;`);let n=t._zod.def;if(n.format)switch(n.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 XG(e,t){return e.write(`if (typeof ${t} !== "symbol") return INVALID;`),t}function eU(e,t){return e.write(`if (${t} !== undefined) return INVALID;`),t}function tU(e,t){return e.write(`if (${t} !== null) return INVALID;`),t}function rU(e,t){return e.write(`if (${t} !== undefined) return INVALID;`),t}function nU(e,t){return e.write(`if (typeof ${t} !== "number" || !Number.isNaN(${t})) return INVALID;`),t}function sU(e,t){return e.write(`if (!(${t} instanceof Date) || Number.isNaN(${t}.getTime())) return INVALID;`),t}function oU(e,t,r,n,s=!0){let o=r._zod.def;e.write(`if (typeof ${n} !== "object" || ${n} === null || Array.isArray(${n})) return INVALID;`);let i=o.shape,a=Object.keys(i),c=Object.getOwnPropertySymbols(i),u=c.length?[...a,...c]:a,d=h=>typeof h=="symbol"?ce(t,h):Dt(h),p=h=>typeof h=="symbol"?`[${d(h)}]`:Dt(h),m=i;if(a.includes("__proto__"))throw new _e('object shape key "__proto__"');let f=new Map;for(let h of u){let _=m[h],S=d(h),w=te(t);if(e.write(`const ${w} = ${n}[${S}];`),_._zod.optin!==void 0){let P=te(t);e.write(`let ${P} = (() => {`),e.indented(C=>{let E=Ot(C,t,_,w);C.write(`return ${E};`)}),e.write("})();"),_._zod.optout==="optional"?(e.write(`if (${P} === INVALID) {`),e.indented(C=>{C.write(`if (${S} in ${n}) return INVALID;`),C.write(`${P} = undefined;`)}),e.write("}")):e.write(`if (${P} === INVALID) return INVALID;`),f.set(h,P)}else{cU(_)&&e.write(`if (!(${S} in ${n})) return INVALID;`);let P=Ot(e,t,_,w,s);P!==null&&f.set(h,P)}}let g=o.catchall,y="none";if(g){let h=g._zod.def.type;if(h==="never"){let _=a.map(S=>`k !== ${Dt(S)}`).join(" && ")||"true";e.write(`for (const k in ${n}) {`),e.indented(S=>{S.write(`if (${_}) return INVALID;`)}),e.write("}")}else(h==="unknown"||h==="any")&&!g._zod.def.checks?.length?y="passthrough":y="schema"}let b=te(t),R=u.some(h=>RP(m[h])||zb(m[h]));if(!s){if(y==="schema"){let h=a.length>0?ce(t,new Set(a)):null;e.write(`for (const k in ${n}) {`),e.indented(_=>{_.write('if (k === "__proto__") continue;'),h&&_.write(`if (${h}.has(k)) continue;`);let S=te(t);_.write(`const ${S} = ${n}[k];`),Ot(_,t,g,S,!1)}),e.write("}")}return null}if(R){e.write(`const ${b} = {};`);for(let h of u){let _=d(h),S=f.get(h);zb(m[h])?e.write(`if (${_} in ${n}) ${b}[${_}] = ${S};`):RP(m[h])?e.write(`if (${S} !== undefined || ${_} in ${n}) ${b}[${_}] = ${S};`):e.write(`${b}[${_}] = ${S};`)}}else{let h=u.map(_=>`${p(_)}: ${f.get(_)}`).join(", ");e.write(`const ${b} = { ${h} };`)}if(y!=="none"){let h=a.length>0?ce(t,new Set(a)):null;e.write(`for (const k in ${n}) {`),e.indented(_=>{if(_.write('if (k === "__proto__") continue;'),h&&_.write(`if (${h}.has(k)) continue;`),y==="passthrough")_.write(`${b}[k] = ${n}[k];`);else{let S=te(t);_.write(`const ${S} = ${n}[k];`);let w=Ot(_,t,g,S);_.write(`${b}[k] = ${w};`)}}),e.write("}")}return b}function iU(e,t,r,n,s=!0){let o=r._zod.def;if(aU(r))return Ze(e,t,o.innerType,n,s);if(o.innerType._zod.optin==="defaulted"){let a=te(t),c=te(t);return e.write(`let ${a};`),e.write(`if (${n} === undefined) {`),e.indented(u=>{u.write(`const ${c} = (() => {`),u.indented(d=>{let p=Ze(d,t,o.innerType,n);d.write(`return ${p};`)}),u.write("})();"),u.write(`if (${c} !== INVALID) ${a} = ${c};`)}),e.write("} else {"),e.indented(u=>{let d=Ze(u,t,o.innerType,n);u.write(`${a} = ${d};`)}),e.write("}"),a}let i=s?te(t):null;return i&&e.write(`let ${i};`),e.write(`if (${n} !== undefined) {`),e.indented(a=>{let c=Ze(a,t,o.innerType,n,s);i&&c!==null&&a.write(`${i} = ${c};`)}),e.write("}"),i}function aU(e){return e._zod.traits?.has("$ZodExactOptional")===!0}function cU(e){return e._zod.optin===void 0&&js(e)}function js(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?js(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?js(t.innerType):!0;case"catch":return!0;case"union":return t.options?t.options.some(js):!0;case"intersection":return!t.left||!t.right?!0:js(t.left)&&js(t.right);case"pipe":return t.in?js(t.in):!0;default:return!0}}function zb(e){return e._zod.optin==="optional"&&e._zod.optout==="optional"}function RP(e){return(e._zod.optin!=="defaulted"||e._zod.optout==="optional")&&yi(e)}function yi(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?yi(t.innerType):!0;case"union":return t.options?t.options.some(yi):!0;case"intersection":return!t.left||!t.right||yi(t.left)||yi(t.right);case"pipe":return t.out?yi(t.out):!0;default:return!0}}function uU(e,t,r,n,s=!0){let o=r._zod.def,i=s?te(t):null;return i&&e.write(`let ${i} = null;`),e.write(`if (${n} !== null) {`),e.indented(a=>{let c=Ze(a,t,o.innerType,n,s);i&&c!==null&&a.write(`${i} = ${c};`)}),e.write("}"),i}function Wb(e,t,r){for(let[n,s]of ai(t._zod.def.checks))e.write(`if (${r} > ${Zn(n,s._zod.def.check)}) return INVALID;`)}function lU(e,t,r,n,s=!0){let o=r._zod.def;e.write(`if (!Array.isArray(${n})) return INVALID;`),Wb(e,r,`${n}.length`);let i=s?te(t):null,a=te(t),c=te(t);return i&&e.write(`const ${i} = new Array(${n}.length);`),e.write(`for (let ${a} = 0; ${a} < ${n}.length; ${a}++) {`),e.indented(u=>{u.write(`const ${c} = ${n}[${a}];`);let d=Ot(u,t,o.element,c,s);i&&d!==null&&u.write(`${i}[${a}] = ${d};`)}),e.write("}"),i}function dU(e,t,r,n){let o=r._zod.def.values;if(o.length!==1){let a=ce(t,new Set(o));return e.write(`if (!${a}.has(${n})) return INVALID;`),n}let i=o[0];if(typeof i=="number"&&Number.isNaN(i)){let a=ce(t,new Set(o));return e.write(`if (!${a}.has(${n})) return INVALID;`),n}if(typeof i=="string")e.write(`if (${n} !== ${Dt(i)}) return INVALID;`);else if(typeof i=="number"||typeof i=="boolean")e.write(`if (${n} !== ${i}) return INVALID;`);else if(i===null)e.write(`if (${n} !== null) return INVALID;`);else if(i===void 0)e.write(`if (${n} !== undefined) return INVALID;`);else if(typeof i=="bigint")e.write(`if (${n} !== ${i}n) return INVALID;`);else throw new _e(`literal type ${typeof i}`);return n}function pU(e,t,r,n){let s=r._zod.values;if(!s)throw new _e("enum schema without enumerated values");let o=ce(t,s);return e.write(`if (!${o}.has(${n})) return INVALID;`),n}function SP(e,t,r,n){let s=r._zod.def;return Ze(e,t,s.innerType,n)}function mU(e,t,r,n){let s=r._zod.def,i=Object.getOwnPropertyDescriptor(r._zod.def,"defaultValue")?()=>r._zod.def.defaultValue:void 0;if(r._zod.def.type==="prefault"){if(!i)return Ze(e,t,s.innerType,n);let c=ce(t,i),u=te(t);return e.write(`let ${u} = ${n};`),e.write(`if (${n} === undefined) ${u} = ${c}();`),Ze(e,t,s.innerType,u)}let a=te(t);if(i){let c=ce(t,i),u=ce(t,dc);e.write(`let ${a};`),e.write(`if (${n} === undefined) {`),e.indented(d=>{d.write(`${a} = ${u}(${c}());`)}),e.write("} else {"),e.indented(d=>{let p=Ze(d,t,s.innerType,n);d.write(`${a} = ${p} === undefined ? ${u}(${c}()) : ${p};`)}),e.write("}")}else e.write(`let ${a};`),e.write(`if (${n} !== undefined) {`),e.indented(c=>{let u=Ze(c,t,s.innerType,n);c.write(`${a} = ${u};`)}),e.write("}");return a}function fU(e,t,r,n){let s=r._zod.def,o=Ze(e,t,s.innerType,n),i=te(t);return e.write(`const ${i} = ${o};`),e.write(`if (${i} === undefined) return INVALID;`),i}function gU(e,t,r,n){let s=r._zod.def,o=s.items,i=s.rest;e.write(`if (!Array.isArray(${n})) return INVALID;`);let a=_P(o,"optin"),c=_P(o,"optout");i?e.write(`if (${n}.length < ${a}) return INVALID;`):e.write(`if (${n}.length < ${a} || ${n}.length > ${o.length}) return INVALID;`);let u=te(t);e.write(`const ${u} = [];`);for(let d=0;d<o.length;d++){let p=o[d];if(d>=c)e.write(`if (${u}.length === ${d}) {`),e.indented(m=>{m.write(`if (${d} < ${n}.length) {`),m.indented(f=>{let g=te(t);f.write(`const ${g} = ${n}[${d}];`);let y=Ot(f,t,p,g);f.write(`${u}[${d}] = ${y};`)}),m.write("} else {"),m.indented(f=>{if(zb(p)){f.write(`${u}.length = ${d};`);return}let g=te(t),y=te(t);f.write(`const ${g} = undefined;`),f.write(`const ${y} = (() => {`),f.indented(b=>{let R=Ot(b,t,p,g);b.write(`return ${R};`)}),f.write("})();"),f.write(`if (${y} === INVALID || ${y} === undefined) ${u}.length = ${d};`),f.write(`else ${u}[${d}] = ${y};`)}),m.write("}")}),e.write("}");else{let m=te(t);e.write(`const ${m} = ${n}[${d}];`);let f=Ot(e,t,p,m);e.write(`${u}[${d}] = ${f};`)}}if(i){let d=te(t),p=te(t);e.write(`for (let ${d} = ${o.length}; ${d} < ${n}.length; ${d}++) {`),e.indented(m=>{m.write(`const ${p} = ${n}[${d}];`);let f=Ot(m,t,i,p);m.write(`${u}[${d}] = ${f};`)}),e.write("}")}return u}function _P(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 hU(e,t,r,n){let s=r._zod.def,o=s.options;if(s.discriminator)return yU(e,t,s,n);if(s.inclusive===!1)throw new _e("exclusive unions (z.xor)");if(o.length===0)return e.write("return INVALID;"),n;if(o.length===1)return Ze(e,t,o[0],n);if(o.every(c=>c._zod.def.type==="literal"&&!c._zod.def.checks?.length)){let c=new Set(o.flatMap(d=>d._zod.def.values)),u=ce(t,c);return e.write(`if (!${u}.has(${n})) return INVALID;`),n}let a=te(t);e.write(`let ${a};`);for(let c=0;c<o.length;c++){let u=o[c];c===0?e.write(`${a} = (() => {`):e.write(`if (${a} === INVALID) ${a} = (() => {`),e.indented(d=>{let p=Ze(d,t,u,n);d.write(`return ${p};`)}),e.write("})();")}return e.write(`if (${a} === INVALID) return INVALID;`),a}function yU(e,t,r,n){if(r.unionFallback)throw new _e("discriminated union with unionFallback");if(r.options.length===0)return e.write("return INVALID;"),n;let s=te(t),o=te(t);e.write(`const ${s} = ${n}?.[${Dt(r.discriminator)}];`),e.write(`let ${o};`);let i=!0,a=new Set;for(let c of r.options){let u=c._zod.propValues?.[r.discriminator];if(!u||u.size===0)throw new _e("discriminated union option without static discriminator values");for(let m of u){if(a.has(m))throw new _e(`duplicate discriminator value ${String(m)}`);a.add(m)}let d=Array.from(u,m=>bU(t,s,m)),p=i?"if":"else if";e.write(`${p} (${d.join(" || ")}) {`),e.indented(m=>{let f=Ze(m,t,c,n);m.write(`${o} = ${f};`)}),e.write("}"),i=!1}return e.write("else { return INVALID; }"),o}function bU(e,t,r){if(typeof r=="string")return`${t} === ${Dt(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 n=ce(e,r);return`${t} === ${n}`}throw new _e(`literal discriminator value ${String(r)}`)}function wU(e,t,r,n){let s=r._zod.def;t.definite=!1;let o=Ot(e,t,s.left,n),i=Ot(e,t,s.right,n),a=ce(t,fi),c=te(t);return e.write(`const ${c} = ${a}(${o}, ${i});`),e.write(`if (!${c}.valid) return INVALID;`),`${c}.data`}function RU(e,t,r,n){let s=r._zod.def,o=ce(t,Sr);e.write(`if (!${o}(${n})) return INVALID;`);let i=te(t),a=te(t),c=te(t);e.write(`const ${i} = {};`);let u=s,d=u.partial?void 0:s.keyType._zod.values;if(d){let f=[];for(let y of d){if(!(typeof y=="string"||typeof y=="number"||typeof y=="symbol"))throw new _e(`record key value ${String(y)}`);let b=typeof y=="number"?y.toString():y;if(b==="__proto__")throw new _e('record key "__proto__"');f.push(b);let R=ce(t,y),h=Ze(e,t,s.keyType,R),_=te(t);e.write(`const ${_} = ${n}[${SU(t,b)}];`);let S=Ot(e,t,s.valueType,_);e.write(`${i}[${h}] = ${S};`)}let g=ce(t,new Set(f));return e.write(`for (const ${a} in ${n}) {`),e.indented(y=>{y.write(`if (${g}.has(${a})) continue;`),u.mode==="loose"?y.write(`if (${a} !== "__proto__") ${i}[${a}] = ${n}[${a}];`):y.write("return INVALID;")}),e.write("}"),i}let p=s.keyType._zod.def;if(!(p.type==="string"&&p.format===void 0&&!p.coerce&&(p.checks?.length??0)===0)){let f=s.mode==="loose",g=Ud(s.keyType);g.definite===!1&&(t.definite=!1);let y=ce(t,g),b=ce(t,hn),R=te(t);return vP(e,t,n,a,h=>{h.write(`let ${R} = ${y}(${a});`),h.write(`if (${R} === INVALID && typeof ${a} === "string" && ${b}.test(${a})) ${R} = ${y}(Number(${a}));`),f?h.write(`if (${R} === INVALID) { ${i}[${a}] = ${n}[${a}]; continue; }`):h.write(`if (${R} === INVALID) return INVALID;`),h.write(`if (${R} === "__proto__") continue;`);let _=te(t);h.write(`const ${_} = ${n}[${a}];`);let S=Ot(h,t,s.valueType,_);h.write(`${i}[${R}] = ${S};`)}),i}return vP(e,t,n,a,f=>{f.write(`const ${c} = ${n}[${a}];`);let g=Ot(f,t,s.valueType,c);f.write(`${i}[${a}] = ${g};`)},"return INVALID;"),i}function vP(e,t,r,n,s,o){let i=ce(t,Object.prototype.propertyIsEnumerable),a=te(t),c=te(t),u=te(t);e.write(`const ${a} = Object.getOwnPropertySymbols(${r});`),e.write(`const ${c} = Object.getOwnPropertyNames(${r});`),e.write(`for (let ${u} = 0; ${u} < ${c}.length; ${u}++) {`),e.indented(d=>{d.write(`const ${n} = ${c}[${u}];`),d.write(`if (${n} === "__proto__" || !${i}.call(${r}, ${n})) continue;`),s(d)}),e.write("}"),e.write(`for (let ${u} = 0; ${u} < ${a}.length; ${u}++) {`),e.indented(d=>{d.write(`const ${n} = ${a}[${u}];`),d.write(`if (!${i}.call(${r}, ${n})) continue;`),o?d.write(o):s(d)}),e.write("}")}function SU(e,t){return typeof t=="string"?Dt(t):ce(e,t)}function _U(e,t,r,n){let s=r._zod.def;e.write(`if (!(${n} instanceof Map)) return INVALID;`),Wb(e,r,`${n}.size`);let o=te(t),i=te(t),a=te(t);return e.write(`const ${o} = new Map();`),e.write(`for (const [${i}, ${a}] of ${n}) {`),e.indented(c=>{let u=Ze(c,t,s.keyType,i),d=Ze(c,t,s.valueType,a);c.write(`${o}.set(${u}, ${d});`)}),e.write("}"),o}function vU(e,t,r,n){let s=r._zod.def;e.write(`if (!(${n} instanceof Set)) return INVALID;`),Wb(e,r,`${n}.size`);let o=te(t),i=te(t);return e.write(`const ${o} = new Set();`),e.write(`for (const ${i} of ${n}) {`),e.indented(a=>{let c=Ze(a,t,s.valueType,i);a.write(`${o}.add(${c});`)}),e.write("}"),o}function kU(e,t){return e.write(`if (!(${t} instanceof File)) return INVALID;`),t}function CU(e,t,r,n){e.write(`if (typeof ${n} !== "string") return INVALID;`);let s=r._zod.pattern;if(s){let o=ce(t,s);e.write(`${o}.lastIndex = 0;`),e.write(`if (!${o}.test(${n})) return INVALID;`)}return n}function PU(e,t,r,n){let s=r._zod.def,o=zs(t,s.getter),i=ce(t,{parser:null});e.write(`if (!${i}.parser) {`),e.indented(c=>{c.write(`const inner = ${o}();`),c.write(`${i}.parser = function(input) {`),c.indented(u=>{u.write("const result = inner._zod.run({ value: input, issues: [] }, {});"),u.write("return result.issues.length === 0 ? result.value : INVALID;")}),c.write("};")}),e.write("}");let a=te(t);return e.write(`const ${a} = ${i}.parser(${n});`),e.write(`if (${a} === INVALID) return INVALID;`),a}function EU(e,t,r,n){let s=r._zod.def,o=Ze(e,t,s.in,n);if(s.transform){if(Bs(s.transform))throw new Or("z.compile: async transforms in pipes are not supported");let i=s.transform,c=zs(t,d=>{let p={value:d,issues:[],addIssue:Hb},m=i(d,p);return m instanceof Promise?Mt:p.issues.length===0?m:Mt}),u=te(t);return e.write(`const ${u} = ${c}(${o});`),e.write(`if (${u} === INVALID) return INVALID;`),Ze(e,t,s.out,u)}else return Ze(e,t,s.out,o)}function Bs(e){return typeof e=="function"&&(e.constructor.name==="AsyncFunction"||e[Symbol.toStringTag]==="AsyncFunction")}function AU(e,t,r,n){let s=r._zod.def;if(s.fn){if(Bs(s.fn))throw new Or("z.compile: async custom predicates are not supported");let o=zs(t,s.fn),i=ce(t,jb),a=te(t);e.write(`const ${a} = ${o}(${n});`),e.write(`if (${a} instanceof Promise) ${i}();`),e.write(`if (!${a}) return INVALID;`)}else throw new _e("custom schema without a predicate function");return n}function TU(e,t,r){let n=e._zod.run({value:r,issues:[]},{});if(n&&typeof n.then=="function")return Mt;let s=n;return s.issues.length===0?s.value:t()}function $U(e,t,r,n){let s=r._zod.def;if(!s.catchValue[Wl])throw new _e("catch with a callback (only a constant catch value compiles)",!1);let o=te(t);e.write(`let ${o} = (() => {`),e.indented(u=>{let d=Ot(u,t,s.innerType,n);u.write(`return ${d};`)}),e.write("})();");let i=ce(t,s.innerType),a=zs(t,s.catchValue),c=ce(t,TU);return e.write(`if (${o} === INVALID) {`),e.indented(u=>{u.write(`${o} = ${c}(${i}, ${a}, ${n});`),u.write(`if (${o} === INVALID) return INVALID;`)}),e.write("}"),o}function OU(e,t,r,n){let s=r._zod.def;if(s.transform){if(Bs(s.transform))throw new Or("z.compile: async transforms are not supported");let o=s.transform,a=zs(t,u=>{let d={value:u,issues:[],addIssue:Hb},p=o(u,d);return p instanceof Promise?Mt:d.issues.length===0?p:Mt}),c=te(t);return e.write(`const ${c} = ${a}(${n});`),e.write(`if (${c} === INVALID) return INVALID;`),c}return n}var Mt,wP,Or,_e,FG,ZG,EP=A(()=>{Vn();ld();Lb();Ns();gi();nt();Mt=Symbol.for("zod.compile.invalid"),wP=Symbol.for("zod.compile.fallback"),Or=class extends Error{constructor(t="z.compile does not support async refinements, transforms, or checks"){super(t),this.name="ZodCompileAsyncError"}},_e=class extends Error{constructor(t,r=!0){super(`z.compile does not support ${t}; this schema must use the runtime parser`),this.name="ZodCompileUnsupportedError",this.islandable=r}};FG=new Set(["max_size","min_size","size_equals","max_length","min_length","length_equals"]);ZG=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 jd(e){return e.checks&&(e.checks=[...e.checks]),e}function Vb(e,t){return new e(jd({type:"string",...U(t)}))}function qb(e,t){return new e(jd({type:"string",coerce:!0,...U(t)}))}function zd(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...U(t)})}function Bd(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...U(t)})}function Hd(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...U(t)})}function Wd(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...U(t)})}function Vd(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...U(t)})}function qd(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...U(t)})}function jc(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...U(t)})}function Zd(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...U(t)})}function Kd(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...U(t)})}function Jd(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...U(t)})}function Yd(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...U(t)})}function Qd(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...U(t)})}function Xd(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...U(t)})}function ep(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...U(t)})}function tp(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...U(t)})}function rp(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...U(t)})}function Zb(e,t){return new e({type:"string",format:"mac",check:"string_format",abort:!1,...U(t)})}function np(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...U(t)})}function sp(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...U(t)})}function op(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...U(t)})}function ip(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...U(t)})}function ap(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...U(t)})}function Kb(e,t){return new e({type:"string",format:"credit_card",check:"string_format",abort:!1,...U(t)})}function Jb(e,t){return new e({type:"string",format:"iban",check:"string_format",abort:!1,...U(t)})}function cp(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...U(t)})}function zc(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...U(t)})}function Bc(e,t){return new e({type:"string",format:"date",check:"string_format",...U(t)})}function Hc(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...U(t)})}function Wc(e,t){return new e({type:"string",format:"duration",check:"string_format",...U(t)})}function Qb(e,t){return new e(jd({type:"number",checks:[],...U(t)}))}function Xb(e,t){return new e(jd({type:"number",coerce:!0,checks:[],...U(t)}))}function ew(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...U(t)})}function tw(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"float32",...U(t)})}function rw(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"float64",...U(t)})}function nw(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"int32",...U(t)})}function sw(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"uint32",...U(t)})}function ow(e,t){return new e({type:"boolean",...U(t)})}function iw(e,t){return new e({type:"boolean",coerce:!0,...U(t)})}function aw(e,t){return new e({type:"bigint",...U(t)})}function cw(e,t){return new e({type:"bigint",coerce:!0,...U(t)})}function uw(e,t){return new e({type:"bigint",check:"bigint_format",abort:!1,format:"int64",...U(t)})}function lw(e,t){return new e({type:"bigint",check:"bigint_format",abort:!1,format:"uint64",...U(t)})}function dw(e,t){return new e({type:"symbol",...U(t)})}function pw(e,t){return new e({type:"undefined",...U(t)})}function mw(e,t){return new e({type:"null",...U(t)})}function fw(e){return new e({type:"any"})}function gw(e){return new e({type:"unknown"})}function hw(e,t){return new e({type:"never",...U(t)})}function yw(e,t){return new e({type:"void",...U(t)})}function bw(e,t){return new e({type:"date",...U(t)})}function ww(e,t){return new e({type:"date",coerce:!0,...U(t)})}function Rw(e,t){return new e({type:"nan",...U(t)})}function Br(e,t){return new ad({check:"less_than",...U(t),value:e,inclusive:!1})}function ar(e,t){return new ad({check:"less_than",...U(t),value:e,inclusive:!0})}function Hr(e,t){return new cd({check:"greater_than",...U(t),value:e,inclusive:!1})}function cr(e,t){return new cd({check:"greater_than",...U(t),value:e,inclusive:!0})}function up(e){return Hr(0,e)}function lp(e){return Br(0,e)}function dp(e){return ar(0,e)}function pp(e){return cr(0,e)}function Kn(e,t){return new Qh({check:"multiple_of",...U(t),value:e})}function Jn(e,t){return new ty({check:"max_size",...U(t),maximum:e})}function Wr(e,t){return new ry({check:"min_size",...U(t),minimum:e})}function Hs(e,t){return new ny({check:"size_equals",...U(t),size:e})}function Ws(e,t){return new sy({check:"max_length",...U(t),maximum:e})}function yn(e,t){return new oy({check:"min_length",...U(t),minimum:e})}function Vs(e,t){return new iy({check:"length_equals",...U(t),length:e})}function bi(e,t){return new ay({check:"string_format",format:"regex",...U(t),pattern:e})}function wi(e){return new cy({check:"string_format",format:"lowercase",...U(e)})}function Ri(e){return new uy({check:"string_format",format:"uppercase",...U(e)})}function Si(e,t){return new ly({check:"string_format",format:"includes",...U(t),includes:e})}function _i(e,t){return new dy({check:"string_format",format:"starts_with",...U(t),prefix:e})}function vi(e,t){return new py({check:"string_format",format:"ends_with",...U(t),suffix:e})}function mp(e,t,r){return new my({check:"property",property:e,schema:t,...U(r)})}function ki(e,t){return new fy({check:"properties",shape:e,...U(t)})}function Ci(e,t){return new gy({check:"mime_type",mime:e,...U(t)})}function Ir(e){return new hy({check:"overwrite",tx:e})}function Pi(e){return Ir(t=>t.normalize(e))}function Ei(){return Ir(e=>e.trim())}function Ai(){return Ir(e=>e.toLowerCase())}function Ti(){return Ir(e=>e.toUpperCase())}function $i(){return Ir(e=>Yg(e))}function Sw(e,t,r){return new e({type:"array",element:t,...U(r)})}function IU(e,t,r){return new e({type:"union",options:t,...U(r)})}function xU(e,t,r){return new e({type:"union",options:t,inclusive:!1,...U(r)})}function DU(e,t,r,n){return new e({type:"union",options:r,discriminator:t,...U(n)})}function LU(e,t,r){return new e({type:"intersection",left:t,right:r})}function MU(e,t,r,n){let s=r instanceof de,o=s?n:r,i=s?r:null;return new e({type:"tuple",items:t,rest:i,...U(o)})}function FU(e,t,r,n){return new e({type:"record",keyType:t,valueType:r,...U(n)})}function NU(e,t,r,n){return new e({type:"map",keyType:t,valueType:r,...U(n)})}function GU(e,t,r){return new e({type:"set",valueType:t,...U(r)})}function UU(e,t,r){let n=Array.isArray(t)?Object.fromEntries(t.map(s=>[s,s])):t;return new e({type:"enum",entries:n,...U(r)})}function jU(e,t,r){return new e({type:"enum",entries:t,...U(r)})}function zU(e,t,r){return new e({type:"literal",values:Array.isArray(t)?t:[t],...U(r)})}function _w(e,t){return new e({type:"file",...U(t)})}function BU(e,t){return new e({type:"transform",transform:t})}function HU(e,t){return new e({type:"optional",innerType:t})}function WU(e,t){return new e({type:"nullable",innerType:t})}function VU(e,t,r){return new e({type:"default",innerType:t,get defaultValue(){return typeof r=="function"?r():dc(r)}})}function qU(e,t,r){return new e({type:"nonoptional",innerType:t,...U(r)})}function ZU(e,t){return new e({type:"success",innerType:t})}function KU(e,t,r){return new e({type:"catch",innerType:t,catchValue:typeof r=="function"?r:sh(r)})}function JU(e,t,r){return new e({type:"pipe",in:t,out:r})}function YU(e,t){return new e({type:"readonly",innerType:t})}function QU(e,t,r){return new e({type:"template_literal",parts:t,...U(r)})}function XU(e,t){return new e({type:"lazy",getter:t})}function ej(e,t){return new e({type:"promise",innerType:t})}function vw(e,t,r){let n=U(r);return n.abort??(n.abort=!0),new e({type:"custom",check:"custom",fn:t,...n})}function kw(e,t,r){return new e({type:"custom",check:"custom",fn:t,...U(r)})}function Cw(e,t){let r=AP(n=>(n.addIssue=s=>{if(typeof s=="string")n.issues.push(ci(s,n.value,r._zod.def));else{let o=s;o.fatal&&(o.continue=!1),o.code??(o.code="custom"),"input"in o||(o.input=n.value),o.inst??(o.inst=r),o.continue??(o.continue=!r._zod.def.abort),n.issues.push(ci(o))}},e(n.value,n)),t);return r}function AP(e,t){let r=new Ge({check:"custom",...U(t)});return r._zod.check=e,r}function Pw(e){let t=new Ge({check:"describe"});return t._zod.onattach=[r=>{let n=kt.get(r)??{};kt.add(r,{...n,description:e})}],t._zod.check=()=>{},t}function Ew(e){let t=new Ge({check:"meta"});return t._zod.onattach=[r=>{let n=kt.get(r)??{};kt.add(r,{...n,...e})}],t._zod.check=()=>{},t}function Aw(e,t){let r=U(t),n=r.truthy??["true","1","yes","on","y","enabled"],s=r.falsy??["false","0","no","off","n","disabled"];r.case!=="sensitive"&&(n=n.map(f=>typeof f=="string"?f.toLowerCase():f),s=s.map(f=>typeof f=="string"?f.toLowerCase():f));let o=new Set(n),i=new Set(s),a=e.Codec??Dc,c=e.Boolean??Ic,u=e.String??Us,d=new u({type:"string",error:r.error}),p=new c({type:"boolean",error:r.error}),m=new a({type:"pipe",in:d,out:p,transform:((f,g)=>{let y=f;return r.case!=="sensitive"&&(y=y.toLowerCase()),o.has(y)?!0:i.has(y)?!1:(g.issues.push({code:"invalid_value",expected:"stringbool",values:[...o,...i],input:g.value,inst:m,continue:!1}),{})}),reverseTransform:((f,g)=>f===!0?n[0]||"true":s[0]||"false"),error:r.error});return m._zod.bag.truthy=n,m._zod.bag.falsy=s,m._zod.bag.case=r.case??"insensitive",m}function qs(e,t,r,n={}){let s=U(n),o={check:"string_format",type:"string",format:t,fn:typeof r=="function"?r:a=>r.test(a),...s};return r instanceof RegExp&&(o.pattern=r),new e(o)}var Yb,TP=A(()=>{ud();Uc();gi();nt();Yb={Any:null,Minute:-1,Second:0,Millisecond:3,Microsecond:6}});function Vc(e,...t){for(let r of t)for(let n of Reflect.ownKeys(r))Object.prototype.propertyIsEnumerable.call(r,n)&&vt(e,n,r[n]);return e}function Yn(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??kt,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 pt(e,t,r,n,s){let o=typeof t.unrepresentable=="function"?t.unrepresentable({zodSchema:e,path:n.path,message:s}):t.unrepresentable;if(o==="any")return!1;if(o===void 0||o==="throw")throw new Error(s);return Object.assign(r,o),!0}function De(e,t,r={path:[],schemaPath:[]}){var n;let s=e._zod.def,o=t.seen.get(e);if(o)return o.count++,r.schemaPath.includes(e)&&(o.cycle=r.path),o.schema;let i={schema:{},count:1,cycle:void 0,path:r.path};t.seen.set(e,i),t.sharedDefsExtractedFor=void 0,t.sharedEmitDoneFor=void 0;let a=e._zod.toJSONSchema?.();if(a)i.schema=a;else{let d={...r,schemaPath:[...r.schemaPath,e],path:r.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,i.schema,d);else{let m=i.schema,f=t.processors[s.type];if(!f)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${s.type}`);f(e,t,m,d)}let p=e._zod.parent;p&&(i.ref||(i.ref=p),De(p,t,d),t.seen.get(p).isParent=!0)}let c=t.metadataRegistry.get(e);return c&&Vc(i.schema,c),t.io==="input"&&Ft(e)&&(delete i.schema.examples,delete i.schema.default),t.io==="input"&&"_prefault"in i.schema&&((n=i.schema).default??(n.default=i.schema._prefault)),delete i.schema._prefault,t.seen.get(e).schema}function $P(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}function Qn(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 n=new Map;for(let i of e.seen.entries()){let a=e.metadataRegistry.get(i[0])?.id;if(a){let c=n.get(a);if(c&&c!==i[0])throw new Error(`Duplicate schema id "${a}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);n.set(a,i[0])}}let s=i=>{let a=e.target==="draft-2020-12"?"$defs":"definitions";if(e.external){let p=e.external.registry.get(i[0])?.id,m=e.external.uri??(g=>g);if(p)return{ref:m(p)};let f=i[1].defId??i[1].schema.id??`schema${e.counter++}`;return i[1].defId=f,{defId:f,ref:`${m("__shared")}#/${a}/${$P(f)}`}}let c="#",u=`${c}/${a}/`;if(i[1]===r&&!i[1].schema.id)return{ref:c};let d=i[1].schema.id??`__schema${e.counter++}`;return{defId:d,ref:u+$P(d)}},o=i=>{if(i[1].schema.$ref)return;let a=i[1],{ref:c,defId:u}=s(i);a.def={...a.schema},u&&(a.defId=u);let d=a.schema;for(let p in d)delete d[p];d.$ref=c};if(e.cycles==="throw")for(let i of e.seen.entries()){let a=i[1];if(a.cycle)throw new Error(`Cycle detected: #/${a.cycle?.join("/")}/<root>
62
62
 
63
- Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let i of e.seen.entries()){let a=i[1];if(t===i[0]){o(i);continue}if(e.external){let u=e.external.registry.get(i[0])?.id;if(t!==i[0]&&u){o(i);continue}}if(e.metadataRegistry.get(i[0])?.id){o(i);continue}if(a.cycle){o(i);continue}a.count>1&&e.reused==="ref"&&o(i)}e.external&&(e.sharedDefsExtractedFor=e.external)}function xP(e){let t=e.anyOf;if(!Array.isArray(t)||t.length===0||e.type!==void 0)return;let r=[];for(let n of t){if(!n||typeof n!="object")return;xP(n);let s=Object.keys(n);if(s.length!==1||s[0]!=="type")return;let o=n.type;for(let i of Array.isArray(o)?o:[o]){if(typeof i!="string")return;r.includes(i)||r.push(i)}}delete e.anyOf,e.type=r.length===1?r[0]:r}function IP(e){let t=e.additionalProperties;return t===void 0||t===!1||typeof t!="object"||t===null?null:Object.keys(t).length?t:null}function Tw(e){let t=[];for(let o of e){if(typeof o!="object"||o.type!=="object")return null;for(let i in o)if(!DP.has(i))return null;t.push(o)}let r={},n=new Set;for(let o of t){for(let i in o.properties){if(Object.prototype.hasOwnProperty.call(r,i))continue;let a=[];for(let u of t){let d=u.properties?.[i]??IP(u);d!=null&&(a.some(p=>JSON.stringify(p)===JSON.stringify(d))||a.push(d))}let c=a.length===1?a[0]:Tw(a)??{allOf:a};vt(r,i,c)}for(let i of o.required??[])n.add(i)}let s={type:"object",properties:r};if(n.size&&(s.required=[...n]),t.every(o=>o.additionalProperties===!1))s.additionalProperties=!1;else{let o=[];for(let i of t){let a=IP(i);a&&!o.some(c=>JSON.stringify(c)===JSON.stringify(a))&&o.push(a)}o.length===1?s.additionalProperties=o[0]:o.length>1&&(s.additionalProperties={allOf:o})}return s}function tj(e){let t=e.allOf;if(!Array.isArray(t)||t.length<2)return;for(let s of DP)if(s in e)return;let r=t.filter(s=>OP.some(o=>Array.isArray(s[o]))),n=null;if(!r.length)n=Tw(t);else{let s=r[0],o=OP.find(c=>Array.isArray(s[c]));if(Object.keys(s).length!==1)return;let i=t.filter(c=>c!==s),a=s[o].map(c=>Tw([...i,c]));if(a.some(c=>!c))return;n={[o]:a}}n&&(delete e.allOf,Vc(e,n))}function Xn(e,t){let r=e.seen.get(t);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");let n=a=>{let c=e.seen.get(a);if(c.ref===null)return;let u=c.def??c.schema,d={...u},p=c.ref;if(c.ref=null,p){n(p);let f=e.seen.get(p),g=f.schema;if(g.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0")?(u.allOf=u.allOf??[],u.allOf.push(g)):Vc(u,g),Vc(u,d),a._zod.parent===p)for(let b in u)b==="$ref"||b==="allOf"||b in d||delete u[b];if(g.$ref&&f.def)for(let b in u)b==="$ref"||b==="allOf"||b in f.def&&JSON.stringify(u[b])===JSON.stringify(f.def[b])&&delete u[b]}let m=a._zod.parent;if(m&&m!==p){n(m);let f=e.seen.get(m);if(f?.schema.$ref&&(u.$ref=f.schema.$ref,f.def))for(let g in u)g==="$ref"||g==="allOf"||g in f.def&&JSON.stringify(u[g])===JSON.stringify(f.def[g])&&delete u[g]}e.override({zodSchema:a,jsonSchema:u,path:c.path??[]})};if(!e.external||e.sharedEmitDoneFor!==e.external){for(let a of[...e.seen.entries()].reverse())n(a[0]);if(e.target!=="openapi-3.0")for(let a of e.seen.entries())xP(a[1].def??a[1].schema);for(let a of e.deferred)a();if(e.intersections.length){let a=new Map;for(let c of e.seen.values())for(let u of[c.schema,c.def]){let d=u?.allOf;if(!Array.isArray(d))continue;let p=a.get(d);p?p.push(u):a.set(d,[u])}for(let c of e.intersections)for(let u of a.get(c)??[])tj(u)}}let s={};if(e.target==="draft-2020-12"?s.$schema="https://json-schema.org/draft/2020-12/schema":e.target==="draft-07"?s.$schema="http://json-schema.org/draft-07/schema#":e.target==="draft-04"?s.$schema="http://json-schema.org/draft-04/schema#":e.target,e.external?.uri){let a=e.external.registry.get(t)?.id;if(!a)throw new Error("Schema is missing an `id` property");s.$id=e.external.uri(a)}Vc(s,r.defId?r.schema:r.def??r.schema);let o=e.metadataRegistry.get(t)?.id;o!==void 0&&s.id===o&&delete s.id;let i=e.external?.defs??{};if(!e.external||e.sharedEmitDoneFor!==e.external)for(let a of e.seen.entries()){let c=a[1];c.def&&c.defId&&(c.def.id===c.defId&&delete c.def.id,vt(i,c.defId,c.def))}e.external&&(e.sharedEmitDoneFor=e.external),e.external||Object.keys(i).length>0&&(e.target==="draft-2020-12"?s.$defs=i:s.definitions=i);try{let a=JSON.parse(JSON.stringify(s));return Object.defineProperty(a,"~standard",{value:{...t["~standard"],jsonSchema:{input:Oi(t,"input",e.processors),output:Oi(t,"output",e.processors)}},enumerable:!1,writable:!1}),a}catch{throw new Error("Error converting schema to JSON.")}}function Ft(e,t){let r=t??{seen:new Set};if(r.seen.has(e))return!1;r.seen.add(e);let n=e._zod.def;if(n.type==="transform")return!0;if(n.type==="array")return Ft(n.element,r);if(n.type==="set")return Ft(n.valueType,r);if(n.type==="lazy")return Ft(n.getter(),r);if(n.type==="promise"||n.type==="optional"||n.type==="nonoptional"||n.type==="nullable"||n.type==="readonly"||n.type==="default"||n.type==="prefault"||n.type==="catch")return Ft(n.innerType,r);if(n.type==="intersection")return Ft(n.left,r)||Ft(n.right,r);if(n.type==="record"||n.type==="map")return Ft(n.keyType,r)||Ft(n.valueType,r);if(n.type==="pipe")return e._zod.traits.has("$ZodCodec")?!0:Ft(n.in,r)||Ft(n.out,r);if(n.type==="object"){for(let s in n.shape)if(Ft(n.shape[s],r))return!0;return!1}if(n.type==="union"){for(let s of n.options)if(Ft(s,r))return!0;return!1}if(n.type==="tuple"){for(let s of n.items)if(Ft(s,r))return!0;return!!(n.rest&&Ft(n.rest,r))}return!1}var DP,OP,$w,Oi,qc=A(()=>{Uc();nt();DP=new Set(["type","properties","required","additionalProperties"]),OP=["oneOf","anyOf"];$w=(e,t={})=>r=>{let n=Yn({...r,processors:t});return De(e,n),Qn(n,e),Xn(n,e)},Oi=(e,t,r={})=>n=>{let{libraryOptions:s,target:o}=n??{},i=Yn({...s??{},target:o,io:t,processors:r});return De(e,i),Qn(i,e),Xn(i,e)}});function mt(e){let t={},r=e._zod.def,n=e._zod.traits.has("$ZodCheck")?[e,...r.checks??[]]:r.checks??[];for(let o of n)rj[o._zod.def.check]?.(t,o._zod.def);let s=e._zod.bag;s.minimum!==void 0&&Ii(t,"minimum",s.minimum),s.exclusiveMinimum!==void 0&&Ii(t,"exclusiveMinimum",s.exclusiveMinimum),s.maximum!==void 0&&xi(t,"maximum",s.maximum),s.exclusiveMaximum!==void 0&&xi(t,"exclusiveMaximum",s.exclusiveMaximum),s.multipleOf!==void 0&&GP(t,s.multipleOf),s.format!==void 0&&(t.format??(t.format=s.format),s.format.includes("int")&&(t.isInt=!0)),s.mime&&jP(t,s.mime);for(let o of s.patterns??[])UP(t,o);return t}function Zc(e){let t=e._zod.def;return t.type==="pipe"&&t.in._zod.traits.has("$ZodTransform")?Zc(t.out):t.type==="catch"?Zc(t.innerType):e._zod.optin}function Ow(e,t,r){if(t.$ref){if(r.has(t))return t;r.add(t);let g=e.get(t)?.def;if(!g)return t;let y=Ow(e,g,r);return y===g?t:y}for(let g of["anyOf","oneOf"]){let y=t[g];if(!Array.isArray(y))continue;let b=y.map(R=>Ow(e,R,r));b.some((R,h)=>R!==y[h])&&(t={...t,[g]:b})}let n=Array.isArray(t.type)?t.type:[t.type],s=!n.includes("string")&&n.some(g=>g==="number"||g==="integer"),o=t.enum??(t.const!==void 0?[t.const]:void 0);if(!s&&!o?.some(g=>typeof g=="number"))return t;let{minimum:i,maximum:a,exclusiveMinimum:c,exclusiveMaximum:u,multipleOf:d,format:p,id:m,...f}=t;return f.enum?f.enum=f.enum.map(g=>typeof g=="number"?String(g):g):typeof f.const=="number"&&(f.const=String(f.const)),s&&(f.type="string",o||(f.pattern=(n.includes("number")?hn:kc).source)),f}function oj(e){let t=new Map;for(let n of e.seen.values())n.def&&!t.has(n.schema)&&t.set(n.schema,n);let r=new Map;for(let n of Iw.get(e)??[]){let s=e.seen.get(n),o=(s?.def??s?.schema)?.propertyNames;if(!o||o===!0||r.has(o))continue;let i=Ow(t,o,new Set);i!==o&&r.set(o,i)}if(r.size)for(let n of e.seen.values())for(let s of[n.schema,n.def]){let o=s&&r.get(s.propertyNames);o&&(s.propertyNames=o)}}function HP(e,t,r,n,s){let o=!1,i=JSON.stringify(e,(a,c)=>typeof c!="bigint"?c:(o=!0,null));return o?(pt(t,r,n,s,"BigInt defaults cannot be represented in JSON Schema"),uR):JSON.parse(i)}function yp(e,t){if("_idmap"in e){let n=e,s=Yn({...t,processors:fp}),o={};for(let c of n._idmap.entries()){let[u,d]=c;De(d,s)}let i={},a={registry:n,uri:t?.uri,defs:o};s.external=a;for(let c of n._idmap.entries()){let[u,d]=c;Qn(s,d),vt(i,u,Xn(s,d))}if(Object.keys(o).length>0){let c=s.target==="draft-2020-12"?"$defs":"definitions";i.__shared={[c]:o}}return{schemas:i}}let r=Yn({...t,processors:fp});return De(e,r),Qn(r,e),Xn(r,e)}var Ii,xi,LP,GP,UP,jP,zP,MP,FP,NP,rj,nj,sj,BP,xw,Dw,Lw,Mw,Fw,Nw,Gw,Uw,jw,zw,Bw,Hw,Ww,Vw,qw,Zw,Kw,Jw,Yw,Qw,Xw,eR,tR,rR,nR,gp,sR,oR,Iw,iR,aR,cR,uR,lR,dR,pR,mR,fR,gR,hp,hR,fp,Kc=A(()=>{Ns();gi();qc();nt();Ii=(e,t,r)=>{(e[t]===void 0||r>e[t])&&(e[t]=r)},xi=(e,t,r)=>{(e[t]===void 0||r<e[t])&&(e[t]=r)},LP=(e,t)=>{Ii(e,"minimum",t),xi(e,"maximum",t)},GP=(e,t)=>{e.multipleOf??(e.multipleOf=[]),e.multipleOf.includes(t)||e.multipleOf.push(t)},UP=(e,t)=>{e.patterns??(e.patterns=new Set),e.patterns.add(t)},jP=(e,t)=>{e.mime=e.mime?e.mime.filter(r=>t.includes(r)):[...t]},zP=(e,t)=>{e.format=t,t.includes("int")&&(e.isInt=!0)},MP=(e,t)=>Ii(e,"minimum",t.minimum),FP=(e,t)=>xi(e,"maximum",t.maximum),NP=e=>(t,r)=>{zP(t,r.format);let[n,s]=e[r.format];Ii(t,"minimum",n),xi(t,"maximum",s)},rj={greater_than:(e,t)=>Ii(e,t.inclusive?"minimum":"exclusiveMinimum",t.value),less_than:(e,t)=>xi(e,t.inclusive?"maximum":"exclusiveMaximum",t.value),multiple_of:(e,t)=>GP(e,t.value),number_format:NP(mc),bigint_format:NP(fc),min_length:MP,max_length:FP,length_equals:(e,t)=>LP(e,t.length),min_size:MP,max_size:FP,size_equals:(e,t)=>LP(e,t.size),string_format:(e,t)=>{zP(e,t.format),t.pattern&&UP(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)=>jP(e,t.mime)};nj={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},sj=new Map([[Rd,Ih],[Oc,xh]]),BP=e=>sj.get(e)??e,xw=(e,t,r,n)=>{let s=r;s.type="string";let{minimum:o,maximum:i,format:a,patterns:c,contentEncoding:u,laxFormat:d}=mt(e);if(typeof o=="number"&&(s.minLength=o),typeof i=="number"&&(s.maxLength=i),a&&(s.format=nj[a]??a,s.format===""&&delete s.format,(a==="time"||d)&&delete s.format),u&&(s.contentEncoding=u),c&&c.size>0){let p=[...c].map(BP);p.length===1?s.pattern=p[0].source:p.length>1&&(s.allOf=[...p.map(m=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:m.source}))])}},Dw=(e,t,r,n)=>{let s=r,{minimum:o,maximum:i,multipleOf:a,exclusiveMaximum:c,exclusiveMinimum:u,isInt:d}=mt(e);s.type=d?"integer":"number";let p=typeof u=="number"&&u>=(o??Number.NEGATIVE_INFINITY),m=typeof c=="number"&&c<=(i??Number.POSITIVE_INFINITY),f=t.target==="draft-04"||t.target==="openapi-3.0";if(p?f?(s.minimum=u,s.exclusiveMinimum=!0):s.exclusiveMinimum=u:typeof o=="number"&&(s.minimum=o),m?f?(s.maximum=c,s.exclusiveMaximum=!0):s.exclusiveMaximum=c:typeof i=="number"&&(s.maximum=i),a){let g=new Set;for(let R of a)Number.isFinite(R)&&R!==0?g.add(Math.abs(R)):pt(e,t,s,n,`A multipleOf divisor of ${R} cannot be represented in JSON Schema`);let[y,...b]=g;y!==void 0&&(s.multipleOf=y),b.length&&(s.allOf=[...s.allOf??[],...b.map(R=>({multipleOf:R}))])}},Lw=(e,t,r,n)=>{r.type="boolean"},Mw=(e,t,r,n)=>{pt(e,t,r,n,"BigInt cannot be represented in JSON Schema")},Fw=(e,t,r,n)=>{pt(e,t,r,n,"Symbols cannot be represented in JSON Schema")},Nw=(e,t,r,n)=>{t.target==="openapi-3.0"?(r.type="string",r.nullable=!0,r.enum=[null]):r.type="null"},Gw=(e,t,r,n)=>{pt(e,t,r,n,"Undefined cannot be represented in JSON Schema")},Uw=(e,t,r,n)=>{pt(e,t,r,n,"Void cannot be represented in JSON Schema")},jw=(e,t,r,n)=>{r.not={}},zw=(e,t,r,n)=>{},Bw=(e,t,r,n)=>{},Hw=(e,t,r,n)=>{pt(e,t,r,n,"Date cannot be represented in JSON Schema")},Ww=(e,t,r,n)=>{let s=e._zod.def,o=ni(s.entries);if(o.length===0){r.not={};return}o.every(i=>typeof i=="number")&&(r.type="number"),o.every(i=>typeof i=="string")&&(r.type="string"),r.enum=o},Vw=(e,t,r,n)=>{let s=e._zod.def;if(s.values.length===0){r.not={};return}let o=[];for(let i of s.values)if(i===void 0){if(pt(e,t,r,n,"Literal `undefined` cannot be represented in JSON Schema"))return}else if(typeof i=="bigint"){if(pt(e,t,r,n,"BigInt literals cannot be represented in JSON Schema"))return;o.push(Number(i))}else o.push(i);if(o.length!==0)if(o.length===1){let i=o[0];r.type=i===null?"null":typeof i,t.target==="draft-04"||t.target==="openapi-3.0"?r.enum=[i]:r.const=i}else o.every(i=>typeof i=="number")&&(r.type="number"),o.every(i=>typeof i=="string")&&(r.type="string"),o.every(i=>typeof i=="boolean")&&(r.type="boolean"),o.every(i=>i===null)&&(r.type="null"),r.enum=o},qw=(e,t,r,n)=>{pt(e,t,r,n,"NaN cannot be represented in JSON Schema")},Zw=(e,t,r,n)=>{let s=r,o=e._zod.pattern;if(!o)throw new Error("Pattern not found in template literal");s.type="string",s.pattern=o.source},Kw=(e,t,r,n)=>{let s=r;s.type="string",s.format="binary",s.contentEncoding="binary";let{minimum:o,maximum:i,mime:a}=mt(e);o!==void 0&&(s.minLength=o),i!==void 0&&(s.maxLength=i),a&&(a.length===0?s.not={}:a.length===1?s.contentMediaType=a[0]:s.anyOf=a.map(c=>({contentMediaType:c})))},Jw=(e,t,r,n)=>{r.type="boolean"},Yw=(e,t,r,n)=>{pt(e,t,r,n,"Custom types cannot be represented in JSON Schema")},Qw=(e,t,r,n)=>{pt(e,t,r,n,"Function types cannot be represented in JSON Schema")},Xw=(e,t,r,n)=>{pt(e,t,r,n,"Transforms cannot be represented in JSON Schema")},eR=(e,t,r,n)=>{pt(e,t,r,n,"Map cannot be represented in JSON Schema")},tR=(e,t,r,n)=>{pt(e,t,r,n,"Set cannot be represented in JSON Schema")},rR=(e,t,r,n)=>{let s=r,o=e._zod.def,{minimum:i,maximum:a}=mt(e);typeof i=="number"&&(s.minItems=i),typeof a=="number"&&(s.maxItems=a),s.type="array",s.items=De(o.element,t,{...n,path:[...n.path,"items"]})};nR=(e,t,r,n)=>{let s=r,o=e._zod.def,i=o.shape;if(Object.getOwnPropertySymbols(i).length&&pt(e,t,s,n,"Symbol keys cannot be represented in JSON Schema"))return;s.type="object",s.properties={};for(let u in i)vt(s.properties,u,De(i[u],t,{...n,path:[...n.path,"properties",u]}));let c=[];for(let u of Object.keys(i)){let d=o.shape[u];(t.io==="input"?Zc(d)===void 0:d._zod.optout===void 0)&&c.push(u)}c.length>0&&(s.required=c),o.catchall?._zod.def.type==="never"?s.additionalProperties=!1:o.catchall?o.catchall&&(s.additionalProperties=De(o.catchall,t,{...n,path:[...n.path,"additionalProperties"]})):t.io==="output"&&(s.additionalProperties=!1)},gp=(e,t,r,n)=>{let s=e._zod.def,o=s.inclusive===!1,i=s.options.map((a,c)=>De(a,t,{...n,path:[...n.path,o?"oneOf":"anyOf",c]}));o?r.oneOf=i:r.anyOf=i},sR=(e,t,r,n)=>{let s=e._zod.def,o=De(s.left,t,{...n,path:[...n.path,"allOf",0]}),i=De(s.right,t,{...n,path:[...n.path,"allOf",1]}),a=u=>"allOf"in u&&Object.keys(u).length===1,c=[...a(o)?o.allOf:[o],...a(i)?i.allOf:[i]];r.allOf=c,t.intersections.push(c)},oR=(e,t,r,n)=>{let s=r,o=e._zod.def;s.type="array";let i=t.target==="draft-2020-12"?"prefixItems":"items",a=t.target==="draft-2020-12"||t.target==="openapi-3.0"?"items":"additionalItems",c=o.items.map((y,b)=>De(y,t,{...n,path:[...n.path,i,b]})),u=o.rest?De(o.rest,t,{...n,path:[...n.path,a,...t.target==="openapi-3.0"?[o.items.length]:[]]}):null,d=o.items.length;for(;d>0;){let y=o.items[d-1];if(!(t.io==="input"?Zc(y)!==void 0:y._zod.optout==="optional"))break;d--}let p=o.items.length,m=!o.rest;t.target==="draft-2020-12"?(s.prefixItems=c,m?s.items=!1:u&&(s.items=u),d>0&&(s.minItems=d),m&&(s.maxItems=p)):t.target==="openapi-3.0"?(s.items={anyOf:c},u&&s.items.anyOf.push(u),d>0&&(s.minItems=d),m&&(s.maxItems=p)):(s.items=c,m?s.additionalItems=!1:u&&(s.additionalItems=u),d>0&&(s.minItems=d),m&&(s.maxItems=p));let{minimum:f,maximum:g}=mt(e);typeof f=="number"&&(s.minItems=f),typeof g=="number"&&(s.maxItems=g)};Iw=new WeakMap;iR=(e,t,r,n)=>{let s=r,o=e._zod.def;s.type="object";let i=o.keyType,a=mt(i).patterns;if(o.mode==="loose"&&a&&a.size>0){let d=De(o.valueType,t,{...n,path:[...n.path,"patternProperties","*"]});s.patternProperties={};for(let p of a)vt(s.patternProperties,BP(p).source,d)}else{if(t.target==="draft-07"||t.target==="draft-2020-12"){s.propertyNames=De(o.keyType,t,{...n,path:[...n.path,"propertyNames"]});let d=Iw.get(t);d||(d=[],Iw.set(t,d),t.deferred.push(()=>oj(t))),d.push(e)}s.additionalProperties=De(o.valueType,t,{...n,path:[...n.path,"additionalProperties"]})}let c=i._zod.values,u=t.io==="input"&&Zc(o.valueType)!==void 0;if(c&&!o.partial&&!u){let d=[...c].filter(p=>typeof p=="string"||typeof p=="number");d.length>0&&(s.required=d.map(String))}},aR=(e,t,r,n)=>{let s=e._zod.def,o=De(s.innerType,t,n),i=t.seen.get(e);t.target==="openapi-3.0"?(i.ref=s.innerType,r.nullable=!0):r.anyOf=[o,{type:"null"}]},cR=(e,t,r,n)=>{let s=e._zod.def;De(s.innerType,t,n);let o=t.seen.get(e);o.ref=s.innerType},uR=Symbol();lR=(e,t,r,n)=>{let s=e._zod.def;De(s.innerType,t,n);let o=t.seen.get(e);o.ref=s.innerType;let i=HP(s.defaultValue,e,t,r,n);i!==uR&&(r.default=i)},dR=(e,t,r,n)=>{let s=e._zod.def;De(s.innerType,t,n);let o=t.seen.get(e);if(o.ref=s.innerType,t.io!=="input")return;let i=HP(s.defaultValue,e,t,r,n);i!==uR&&(r._prefault=i)},pR=(e,t,r,n)=>{let s=e._zod.def;De(s.innerType,t,n);let o=t.seen.get(e);o.ref=s.innerType;let i;try{i=s.catchValue(void 0)}catch{pt(e,t,r,n,"Dynamic catch values are not supported in JSON Schema");return}r.default=i},mR=(e,t,r,n)=>{let s=e._zod.def,o=s.in._zod.traits.has("$ZodTransform"),i=t.io==="input"?o?s.out:s.in:s.out;De(i,t,n);let a=t.seen.get(e);a.ref=i},fR=(e,t,r,n)=>{let s=e._zod.def;De(s.innerType,t,n);let o=t.seen.get(e);o.ref=s.innerType,r.readOnly=!0},gR=(e,t,r,n)=>{let s=e._zod.def;De(s.innerType,t,n);let o=t.seen.get(e);o.ref=s.innerType},hp=(e,t,r,n)=>{let s=e._zod.def;De(s.innerType,t,n);let o=t.seen.get(e);o.ref=s.innerType},hR=(e,t,r,n)=>{let s=e._zod.innerType;De(s,t,n);let o=t.seen.get(e);o.ref=s},fp={string:xw,number:Dw,boolean:Lw,bigint:Mw,symbol:Fw,null:Nw,undefined:Gw,void:Uw,never:jw,any:zw,unknown:Bw,date:Hw,enum:Ww,literal:Vw,nan:qw,template_literal:Zw,file:Kw,success:Jw,custom:Yw,function:Qw,transform:Xw,map:eR,set:tR,array:rR,object:nR,union:gp,intersection:sR,tuple:oR,record:iR,nullable:aR,nonoptional:cR,default:lR,prefault:dR,catch:pR,pipe:mR,readonly:fR,promise:gR,optional:hp,lazy:hR}});var bp,WP=A(()=>{Kc();qc();bp=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=Yn({processors:fp,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 De(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,Qn(this.ctx,t);let n=Xn(this.ctx,t),{"~standard":s,...o}=n;return o}}});var VP={};var qP=A(()=>{});var bn={};re(bn,{$ZodAny:()=>eb,$ZodArray:()=>ib,$ZodAsyncError:()=>Kt,$ZodBase64:()=>zy,$ZodBase64URL:()=>By,$ZodBigInt:()=>Pd,$ZodBigIntFormat:()=>Jy,$ZodBoolean:()=>Ic,$ZodCIDRv4:()=>Uy,$ZodCIDRv6:()=>jy,$ZodCUID:()=>Ay,$ZodCUID2:()=>Ty,$ZodCatch:()=>Cb,$ZodCheck:()=>Ge,$ZodCheckBigIntFormat:()=>ey,$ZodCheckEndsWith:()=>py,$ZodCheckGreaterThan:()=>cd,$ZodCheckIncludes:()=>ly,$ZodCheckLengthEquals:()=>iy,$ZodCheckLessThan:()=>ad,$ZodCheckLowerCase:()=>cy,$ZodCheckMaxLength:()=>sy,$ZodCheckMaxSize:()=>ty,$ZodCheckMimeType:()=>gy,$ZodCheckMinLength:()=>oy,$ZodCheckMinSize:()=>ry,$ZodCheckMultipleOf:()=>Qh,$ZodCheckNumberFormat:()=>Xh,$ZodCheckOverwrite:()=>hy,$ZodCheckProperties:()=>fy,$ZodCheckProperty:()=>my,$ZodCheckRegex:()=>ay,$ZodCheckSizeEquals:()=>ny,$ZodCheckStartsWith:()=>dy,$ZodCheckStringFormat:()=>mi,$ZodCheckUpperCase:()=>uy,$ZodCodec:()=>Dc,$ZodCreditCard:()=>Wy,$ZodCustom:()=>Ib,$ZodCustomStringFormat:()=>Zy,$ZodCyclicError:()=>xd,$ZodDate:()=>sb,$ZodDefault:()=>Sb,$ZodDiscriminatedUnion:()=>lb,$ZodE164:()=>Hy,$ZodEmail:()=>_y,$ZodEmoji:()=>Py,$ZodEncodeError:()=>qn,$ZodEnum:()=>gb,$ZodError:()=>lh,$ZodExactOptional:()=>wb,$ZodFile:()=>yb,$ZodFunction:()=>$b,$ZodGUID:()=>Ry,$ZodIBAN:()=>Vy,$ZodIPv4:()=>Fy,$ZodIPv6:()=>Ny,$ZodISODate:()=>Dy,$ZodISODateTime:()=>xy,$ZodISODuration:()=>My,$ZodISOTime:()=>Ly,$ZodIntersection:()=>db,$ZodJWT:()=>qy,$ZodKSUID:()=>Iy,$ZodLazy:()=>Lc,$ZodLiteral:()=>hb,$ZodMAC:()=>Gy,$ZodMap:()=>mb,$ZodNaN:()=>Pb,$ZodNanoID:()=>Ey,$ZodNever:()=>rb,$ZodNonOptional:()=>vb,$ZodNull:()=>Xy,$ZodNullable:()=>Rb,$ZodNumber:()=>Cd,$ZodNumberFormat:()=>Ky,$ZodObject:()=>pP,$ZodObjectJIT:()=>ab,$ZodOptional:()=>Ad,$ZodPipe:()=>Td,$ZodPrefault:()=>_b,$ZodPreprocess:()=>Eb,$ZodPromise:()=>Ob,$ZodReadonly:()=>Ab,$ZodRealError:()=>Jt,$ZodRecord:()=>pb,$ZodRegistry:()=>Fd,$ZodSet:()=>fb,$ZodString:()=>Us,$ZodStringFormat:()=>xe,$ZodSuccess:()=>kb,$ZodSymbol:()=>Yy,$ZodTemplateLiteral:()=>Tb,$ZodTransform:()=>bb,$ZodTuple:()=>Ed,$ZodType:()=>de,$ZodULID:()=>$y,$ZodURL:()=>Cy,$ZodUUID:()=>Sy,$ZodUndefined:()=>Qy,$ZodUnion:()=>xc,$ZodUnknown:()=>tb,$ZodVoid:()=>nb,$ZodXID:()=>Oy,$ZodXor:()=>cb,$brand:()=>ah,$constructor:()=>$,$input:()=>Gb,$output:()=>Nb,Doc:()=>Gs,INVALID:()=>Mt,JSONSchema:()=>VP,JSONSchemaGenerator:()=>bp,NEVER:()=>ih,TimePrecision:()=>Yb,URL_BAD_FORMAT:()=>vy,URL_UNPARSEABLE:()=>Ec,ZodCompileAsyncError:()=>Or,ZodCompileUnsupportedError:()=>_e,_any:()=>fw,_array:()=>Sw,_base64:()=>op,_base64url:()=>ip,_bigint:()=>aw,_boolean:()=>ow,_catch:()=>KU,_check:()=>AP,_cidrv4:()=>np,_cidrv6:()=>sp,_coercedBigint:()=>cw,_coercedBoolean:()=>iw,_coercedDate:()=>ww,_coercedNumber:()=>Xb,_coercedString:()=>qb,_creditCard:()=>Kb,_cuid:()=>Jd,_cuid2:()=>Yd,_custom:()=>vw,_date:()=>bw,_decode:()=>Jl,_decodeAsync:()=>Ql,_default:()=>VU,_discriminatedUnion:()=>DU,_e164:()=>ap,_email:()=>zd,_emoji:()=>Zd,_encode:()=>Kl,_encodeAsync:()=>Yl,_endsWith:()=>vi,_enum:()=>UU,_file:()=>_w,_float32:()=>tw,_float64:()=>rw,_gt:()=>Hr,_gte:()=>cr,_guid:()=>Bd,_iban:()=>Jb,_includes:()=>Si,_int:()=>ew,_int32:()=>nw,_int64:()=>uw,_intersection:()=>LU,_ipv4:()=>tp,_ipv6:()=>rp,_isoDate:()=>Bc,_isoDateTime:()=>zc,_isoDuration:()=>Wc,_isoTime:()=>Hc,_jwt:()=>cp,_ksuid:()=>ep,_lazy:()=>XU,_length:()=>Vs,_literal:()=>zU,_lowercase:()=>wi,_lt:()=>Br,_lte:()=>ar,_mac:()=>Zb,_map:()=>NU,_max:()=>ar,_maxLength:()=>Ws,_maxSize:()=>Jn,_mime:()=>Ci,_min:()=>cr,_minLength:()=>yn,_minSize:()=>Wr,_multipleOf:()=>Kn,_nan:()=>Rw,_nanoid:()=>Kd,_nativeEnum:()=>jU,_negative:()=>lp,_never:()=>hw,_nonnegative:()=>pp,_nonoptional:()=>qU,_nonpositive:()=>dp,_normalize:()=>Pi,_null:()=>mw,_nullable:()=>WU,_number:()=>Qb,_optional:()=>HU,_overwrite:()=>Ir,_parse:()=>ui,_parseAsync:()=>li,_pipe:()=>JU,_positive:()=>up,_promise:()=>ej,_properties:()=>ki,_property:()=>mp,_readonly:()=>YU,_record:()=>FU,_refine:()=>kw,_regex:()=>bi,_safeDecode:()=>ed,_safeDecodeAsync:()=>rd,_safeEncode:()=>Xl,_safeEncodeAsync:()=>td,_safeParse:()=>di,_safeParseAsync:()=>pi,_set:()=>GU,_size:()=>Hs,_slugify:()=>$i,_startsWith:()=>_i,_string:()=>Vb,_stringFormat:()=>qs,_stringbool:()=>Aw,_success:()=>ZU,_superRefine:()=>Cw,_symbol:()=>dw,_templateLiteral:()=>QU,_toLowerCase:()=>Ai,_toUpperCase:()=>Ti,_transform:()=>BU,_trim:()=>Ei,_tuple:()=>MU,_uint32:()=>sw,_uint64:()=>lw,_ulid:()=>Qd,_undefined:()=>pw,_union:()=>IU,_unknown:()=>gw,_uppercase:()=>Ri,_url:()=>jc,_uuid:()=>Hd,_uuidv4:()=>Wd,_uuidv6:()=>Vd,_uuidv7:()=>qd,_void:()=>yw,_xid:()=>Xd,_xor:()=>xU,base64Charset:()=>Rd,base64urlCharset:()=>Oc,canParseURL:()=>ky,clone:()=>Ie,compile:()=>Bb,compileFn:()=>Ud,config:()=>Ye,createStandardJSONSchemaMethod:()=>Oi,createToJSONSchemaMethod:()=>$w,decode:()=>GN,decodeAsync:()=>jN,describe:()=>Pw,encode:()=>NN,encodeAsync:()=>UN,extractDefs:()=>Qn,finalize:()=>Xn,flattenError:()=>wc,formatError:()=>Rc,getDiscriminatedOption:()=>ub,globalConfig:()=>yt,globalRegistry:()=>kt,handleUnrepresentable:()=>pt,initializeContext:()=>Yn,isBackEdge:()=>Ld,isRecursiveSchema:()=>Dd,isValidBase64:()=>$c,isValidBase64URL:()=>Sd,isValidCIDRv6:()=>wd,isValidCreditCard:()=>_d,isValidIBAN:()=>vd,isValidIPv6:()=>Tc,isValidJWT:()=>kd,locales:()=>Gc,memoizer:()=>Nc,mergeValues:()=>fi,meta:()=>Ew,parse:()=>ql,parseAsync:()=>Zl,parseURLObject:()=>uP,prettifyError:()=>ph,process:()=>De,processSchema:()=>De,regexes:()=>vr,registry:()=>Nd,safeDecode:()=>BN,safeDecodeAsync:()=>WN,safeEncode:()=>zN,safeEncodeAsync:()=>HN,safeParse:()=>xN,safeParseAsync:()=>DN,standardProps:()=>gd,stripTabAndNewline:()=>Ac,toDotPath:()=>zC,toJSONSchema:()=>yp,toZod:()=>uc,treeifyError:()=>dh,urlHostnameOk:()=>yd,urlProtocolOk:()=>bd,util:()=>V,validate:()=>Sc,validateAsync:()=>_c,validateURL:()=>hd,version:()=>yy,withParser:()=>Gd});var ur=A(()=>{Vn();fh();mh();gi();Lb();ud();by();nt();nt();Ns();Fb();Uc();ld();EP();TP();qc();Kc();WP();qP()});var wp={};re(wp,{endsWith:()=>vi,gt:()=>Hr,gte:()=>cr,includes:()=>Si,length:()=>Vs,lowercase:()=>wi,lt:()=>Br,lte:()=>ar,maxLength:()=>Ws,maxSize:()=>Jn,mime:()=>Ci,minLength:()=>yn,minSize:()=>Wr,multipleOf:()=>Kn,negative:()=>lp,nonnegative:()=>pp,nonpositive:()=>dp,normalize:()=>Pi,overwrite:()=>Ir,positive:()=>up,properties:()=>ki,property:()=>mp,regex:()=>bi,size:()=>Hs,slugify:()=>$i,startsWith:()=>_i,toLowerCase:()=>Ai,toUpperCase:()=>Ti,trim:()=>Ei,uppercase:()=>Ri});var Rp=A(()=>{ur()});function Sp(e,t,r){Object.defineProperty(e,t,{configurable:!0,enumerable:!1,get(){let n=r(this);return Object.defineProperty(this,t,{value:n,configurable:!0,writable:!0}),n},set(n){Object.defineProperty(this,t,{value:n,configurable:!0,writable:!0})}})}var ZP,KP,aj,Yt,yR=A(()=>{ur();ur();nt();ZP=new WeakSet([Object.prototype,Error.prototype]);KP=(e,t)=>{lh.init(e,t),e.name="ZodError";let r=Object.getPrototypeOf(e);ZP.has(r)||(ZP.add(r),Sp(r,"format",n=>s=>Rc(n,s)),Sp(r,"flatten",n=>s=>wc(n,s)),Sp(r,"addIssue",n=>s=>{n.issues.push(s),n.message=JSON.stringify(n.issues,si,2)}),Sp(r,"addIssues",n=>s=>{n.issues.push(...s),n.message=JSON.stringify(n.issues,si,2)}),Object.defineProperty(r,"isEmpty",{configurable:!0,enumerable:!1,get(){return this.issues.length===0}}))},aj=$("ZodError",KP),Yt=$("ZodError",KP,void 0,{Parent:Error})});var bR,wR,RR,SR,_R,vR,kR,CR,PR,ER,AR,TR,$R=A(()=>{ur();yR();ur();bR=ui(Yt),wR=li(Yt),RR=di(Yt),SR=pi(Yt),_R=Kl(Yt),vR=Jl(Yt),kR=Yl(Yt),CR=Ql(Yt),PR=Xl(Yt),ER=ed(Yt),AR=td(Yt),TR=rd(Yt)});var ji={};re(ji,{ZodAny:()=>UR,ZodArray:()=>HR,ZodBase64:()=>Np,ZodBase64URL:()=>Gp,ZodBigInt:()=>Gi,ZodBigIntFormat:()=>zp,ZodBoolean:()=>Ni,ZodCIDRv4:()=>Mp,ZodCIDRv6:()=>Fp,ZodCUID:()=>Tp,ZodCUID2:()=>$p,ZodCatch:()=>dS,ZodCodec:()=>ou,ZodCreditCard:()=>IR,ZodCustom:()=>iu,ZodCustomStringFormat:()=>Ys,ZodDate:()=>Xc,ZodDefault:()=>oS,ZodDiscriminatedUnion:()=>VR,ZodE164:()=>Up,ZodEmail:()=>Cp,ZodEmoji:()=>Ep,ZodEnum:()=>Li,ZodExactOptional:()=>Vp,ZodFile:()=>tS,ZodFunction:()=>SS,ZodGUID:()=>Pp,ZodIBAN:()=>xR,ZodIPv4:()=>Dp,ZodIPv6:()=>Lp,ZodISODate:()=>ts,ZodISODateTime:()=>es,ZodISODuration:()=>ns,ZodISOTime:()=>rs,ZodInstanceOf:()=>kS,ZodIntersection:()=>qR,ZodJWT:()=>jp,ZodKSUID:()=>xp,ZodLazy:()=>bS,ZodLiteral:()=>eS,ZodMAC:()=>OR,ZodMap:()=>QR,ZodNaN:()=>mS,ZodNanoID:()=>Ap,ZodNever:()=>zR,ZodNonOptional:()=>qp,ZodNull:()=>NR,ZodNullable:()=>sS,ZodNumber:()=>Fi,ZodNumberFormat:()=>Qs,ZodObject:()=>tu,ZodOptional:()=>nu,ZodPipe:()=>su,ZodPrefault:()=>aS,ZodPreprocess:()=>fS,ZodPromise:()=>RS,ZodReadonly:()=>gS,ZodRecord:()=>Di,ZodSet:()=>XR,ZodString:()=>Mi,ZodStringFormat:()=>Me,ZodSuccess:()=>lS,ZodSymbol:()=>MR,ZodTemplateLiteral:()=>yS,ZodTransform:()=>rS,ZodTuple:()=>KR,ZodType:()=>ye,ZodULID:()=>Op,ZodURL:()=>Qc,ZodUUID:()=>Vr,ZodUndefined:()=>FR,ZodUnion:()=>ru,ZodUnknown:()=>jR,ZodVoid:()=>BR,ZodXID:()=>Ip,ZodXor:()=>WR,_ZodString:()=>kp,_default:()=>iS,_function:()=>oA,any:()=>ME,array:()=>eu,base64:()=>hE,base64url:()=>yE,bigint:()=>OE,boolean:()=>LR,catch:()=>pS,check:()=>iA,cidrv4:()=>fE,cidrv6:()=>gE,codec:()=>tA,creditCard:()=>wE,cuid:()=>iE,cuid2:()=>aE,currencyCode:()=>CE,custom:()=>aA,date:()=>NE,describe:()=>cA,discriminatedUnion:()=>HE,e164:()=>bE,email:()=>JP,emoji:()=>sE,enum:()=>Hp,exactOptional:()=>nS,file:()=>YE,float32:()=>EE,float64:()=>AE,function:()=>oA,guid:()=>YP,hash:()=>PE,hex:()=>kE,hostname:()=>vE,httpUrl:()=>nE,iban:()=>RE,instanceof:()=>lA,int:()=>_p,int32:()=>TE,int64:()=>IE,intersection:()=>ZR,invertCodec:()=>rA,ipv4:()=>dE,ipv6:()=>mE,json:()=>pA,jwt:()=>SE,keyof:()=>GE,ksuid:()=>lE,lazy:()=>wS,literal:()=>JE,looseObject:()=>zE,looseRecord:()=>VE,mac:()=>pE,map:()=>qE,meta:()=>uA,nan:()=>eA,nanoid:()=>oE,nativeEnum:()=>KE,never:()=>Bp,nonoptional:()=>uS,null:()=>GR,nullable:()=>Yc,nullish:()=>QE,number:()=>DR,object:()=>UE,optional:()=>Ks,partialRecord:()=>WE,pipe:()=>vp,prefault:()=>cS,preprocess:()=>mA,promise:()=>sA,readonly:()=>hS,record:()=>YR,refine:()=>_S,set:()=>ZE,strictObject:()=>jE,string:()=>Jc,stringFormat:()=>_E,stringbool:()=>dA,success:()=>XE,superRefine:()=>vS,symbol:()=>DE,templateLiteral:()=>nA,transform:()=>Wp,tuple:()=>JR,uint32:()=>$E,uint64:()=>xE,ulid:()=>cE,undefined:()=>LE,union:()=>Ui,unknown:()=>Zs,url:()=>rE,uuid:()=>QP,uuidv4:()=>XP,uuidv6:()=>eE,uuidv7:()=>tE,void:()=>FE,xid:()=>uE,xor:()=>BE});function uj(){yt.localeError||Ye(Md())}function Js(){yt.memoizer||Ye({memoizer:Nc()})}function Jc(e){return Vb(Mi,e)}function JP(e){return zd(Cp,e)}function YP(e){return Bd(Pp,e)}function QP(e){return Hd(Vr,e)}function XP(e){return Wd(Vr,e)}function eE(e){return Vd(Vr,e)}function tE(e){return qd(Vr,e)}function rE(e){return jc(Qc,e)}function nE(e){return jc(Qc,{protocol:vc,hostname:Lh,...V.normalizeParams(e)})}function sE(e){return Zd(Ep,e)}function oE(e){return Kd(Ap,e)}function iE(e){return Jd(Tp,e)}function aE(e){return Yd($p,e)}function cE(e){return Qd(Op,e)}function uE(e){return Xd(Ip,e)}function lE(e){return ep(xp,e)}function dE(e){return tp(Dp,e)}function pE(e){return Zb(OR,e)}function mE(e){return rp(Lp,e)}function fE(e){return np(Mp,e)}function gE(e){return sp(Fp,e)}function hE(e){return op(Np,e)}function yE(e){return ip(Gp,e)}function bE(e){return ap(Up,e)}function wE(e){return Kb(IR,e)}function RE(e){return Jb(xR,e)}function SE(e){return cp(jp,e)}function _E(e,t,r={}){return qs(Ys,e,t,r)}function vE(e){return qs(Ys,"hostname",Dh,e)}function kE(e){return qs(Ys,"hex",Kh,e)}function CE(e){return qs(Ys,"currency_code",Fh,e)}function PE(e,t){let r=t?.enc??"hex",n=`${e}_${r}`,s=vr[n];if(!s)throw new Error(`Unrecognized hash format: ${n}`);return qs(Ys,n,s,t)}function DR(e){return Qb(Fi,e)}function _p(e){return ew(Qs,e)}function EE(e){return tw(Qs,e)}function AE(e){return rw(Qs,e)}function TE(e){return nw(Qs,e)}function $E(e){return sw(Qs,e)}function LR(e){return ow(Ni,e)}function OE(e){return aw(Gi,e)}function IE(e){return uw(zp,e)}function xE(e){return lw(zp,e)}function DE(e){return dw(MR,e)}function LE(e){return pw(FR,e)}function GR(e){return mw(NR,e)}function ME(){return fw(UR)}function Zs(){return gw(jR)}function Bp(e){return hw(zR,e)}function FE(e){return yw(BR,e)}function NE(e){return bw(Xc,e)}function eu(e,t){return Sw(HR,e,t)}function GE(e){let t=e._zod.def.shape;return Hp(Object.keys(t))}function UE(e,t){let r={type:"object",shape:e??{},...V.normalizeParams(t)};return new tu(r)}function jE(e,t){return new tu({type:"object",shape:e,catchall:Bp(),...V.normalizeParams(t)})}function zE(e,t){return new tu({type:"object",shape:e,catchall:Zs(),...V.normalizeParams(t)})}function Ui(e,t){return new ru({type:"union",options:e,...V.normalizeParams(t)})}function BE(e,t){return new WR({type:"union",options:e,inclusive:!1,...V.normalizeParams(t)})}function HE(e,t,r){return new VR({type:"union",options:t,discriminator:e,...V.normalizeParams(r)})}function ZR(e,t){return new qR({type:"intersection",left:e,right:t})}function JR(e,t,r){let n=t instanceof de,s=n?r:t,o=n?t:null;return new KR({type:"tuple",items:e,rest:o,...V.normalizeParams(s)})}function YR(e,t,r){return!t||!t._zod?new Di({type:"record",keyType:Jc(),valueType:e,...V.normalizeParams(t)}):new Di({type:"record",keyType:e,valueType:t,...V.normalizeParams(r)})}function WE(e,t,r){return new Di({type:"record",keyType:e,valueType:t,...V.normalizeParams(r),partial:!0})}function VE(e,t,r){return new Di({type:"record",keyType:e,valueType:t,mode:"loose",...V.normalizeParams(r)})}function qE(e,t,r){return new QR({type:"map",keyType:e,valueType:t,...V.normalizeParams(r)})}function ZE(e,t){return new XR({type:"set",valueType:e,...V.normalizeParams(t)})}function Hp(e,t){let r=Array.isArray(e)?Object.fromEntries(e.map(n=>[n,n])):e;return new Li({type:"enum",entries:r,...V.normalizeParams(t)})}function KE(e,t){return new Li({type:"enum",entries:e,...V.normalizeParams(t)})}function JE(e,t){return new eS({type:"literal",values:Array.isArray(e)?e:[e],...V.normalizeParams(t)})}function YE(e){return _w(tS,e)}function Wp(e){return new rS({type:"transform",transform:e})}function Ks(e){return new nu({type:"optional",innerType:e})}function nS(e){return new Vp({type:"optional",innerType:e})}function Yc(e){return new sS({type:"nullable",innerType:e})}function QE(e){return Ks(Yc(e))}function iS(e,t){return new oS({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():V.shallowClone(t)}})}function cS(e,t){return new aS({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():V.shallowClone(t)}})}function uS(e,t){return new qp({type:"nonoptional",innerType:e,...V.normalizeParams(t)})}function XE(e){return new lS({type:"success",innerType:e})}function pS(e,t){return new dS({type:"catch",innerType:e,catchValue:typeof t=="function"?t:V.constantCatch(t)})}function eA(e){return Rw(mS,e)}function vp(e,t){return new su({type:"pipe",in:e,out:t})}function tA(e,t,r){return new ou({type:"pipe",in:e,out:t,transform:r.decode,reverseTransform:r.encode})}function rA(e){let t=e._zod.def;return new ou({type:"pipe",in:t.out,out:t.in,transform:t.reverseTransform,reverseTransform:t.transform})}function hS(e){return new gS({type:"readonly",innerType:e})}function nA(e,t){return new yS({type:"template_literal",parts:e,...V.normalizeParams(t)})}function wS(e){return new bS({type:"lazy",getter:e})}function sA(e){return new RS({type:"promise",innerType:e})}function oA(e){return new SS({type:"function",input:Array.isArray(e?.input)?JR(e?.input):e?.input??eu(Zs()),output:e?.output??Zs()})}function iA(e){let t=new Ge({check:"custom"});return t._zod.check=e,t}function aA(e,t){return vw(iu,e??(()=>!0),t)}function _S(e,t={}){return kw(iu,e,t)}function vS(e,t){return Cw(e,t)}function lA(e,t={}){let r=new kS({type:"custom",check:"custom",fn:n=>n instanceof e,abort:!0,...V.normalizeParams(t)});return r._zod.bag.Class=e,r._zod.check=n=>{n.value instanceof e||n.issues.push({code:"invalid_type",expected:e.name,input:n.value,inst:r,path:[...r._zod.def.path??[]]})},r}function pA(e){let t=wS(()=>Ui([Jc(e),DR(),LR(),GR(),eu(t),YR(Jc(),t)]));return t}function mA(e,t){return new fS({type:"pipe",in:Wp(e),out:t})}var ye,kp,Mi,Me,es,ts,rs,ns,Cp,Pp,Vr,Qc,Ep,Ap,Tp,$p,Op,Ip,xp,Dp,OR,Lp,Mp,Fp,Np,Gp,Up,IR,xR,jp,Ys,Fi,Qs,Ni,Gi,zp,MR,FR,NR,UR,jR,zR,BR,Xc,HR,tu,ru,WR,VR,qR,KR,Di,QR,XR,Li,eS,tS,rS,nu,Vp,sS,oS,aS,qp,lS,dS,mS,su,ou,fS,gS,yS,bS,RS,SS,iu,cA,uA,kS,dA,ss=A(()=>{ur();ur();Kc();Ns();qc();Mb();Rp();$R();ye=$("ZodType",(e,t)=>(uj(),de.init(e,t),e.def=t,e.type=t.type,e),{check(...e){let t=this.def;return this.clone(V.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 Ie(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},refine(e,t){return this.check(_S(e,t))},superRefine(e,t){return this.check(vS(e,t))},overwrite(e){return this.check(Ir(e))},optional(){return Ks(this)},exactOptional(){return nS(this)},nullable(){return Yc(this)},nullish(){return Ks(Yc(this))},nonoptional(e){return uS(this,e)},array(){return eu(this)},or(e){return Ui([this,e])},and(e){return ZR(this,e)},transform(e){return vp(this,Wp(e))},default(e){return iS(this,e)},prefault(e){return cS(this,e)},catch(e){return pS(this,e)},pipe(e){return vp(this,e)},readonly(){return hS(this)},describe(e){let t=this.clone();return kt.add(t,{description:e}),t},meta(...e){if(e.length===0)return kt.get(this);let t=this.clone();return kt.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 V.hide(this,"~standard",{...gd(this),jsonSchema:{input:Oi(this,"input"),output:Oi(this,"output")}})},set"~standard"(e){V.own(this,"~standard",e)},parse:function e(t,r){return bR(this,t,r,{callee:e})},parseAsync:async function e(t,r){return await wR(this,t,r,{callee:e})},safeParse(e,t){return RR(this,e,t)},async safeParseAsync(e,t){return SR(this,e,t)},get spa(){return this?.safeParseAsync},set spa(e){V.own(this,"spa",e)},validate(e,t){return Sc(this,e,t)},validateAsync(e,t){return _c(this,e,t)},encode:function e(t,r){return _R(this,t,r,{callee:e})},decode:function e(t,r){return vR(this,t,r,{callee:e})},encodeAsync:async function e(t,r){return await kR(this,t,r,{callee:e})},decodeAsync:async function e(t,r){return await CR(this,t,r,{callee:e})},safeEncode(e,t){return PR(this,e,t)},safeDecode(e,t){return ER(this,e,t)},async safeEncodeAsync(e,t){return AR(this,e,t)},async safeDecodeAsync(e,t){return TR(this,e,t)},toJSONSchema(e){return $w(this,{})(e)},get description(){return kt.get(this)?.description},get _def(){return this._zod.def}}),kp=$("_ZodString",(e,t)=>{Us.init(e,t),ye.init(e,t),e._zod.processJSONSchema=(r,n,s)=>xw(e,r,n,s)},V.derived({format:e=>mt(e).format??null,minLength:e=>mt(e).minimum??null,maxLength:e=>mt(e).maximum??null},{regex(...e){return this.check(bi(...e))},includes(...e){return this.check(Si(...e))},startsWith(...e){return this.check(_i(...e))},endsWith(...e){return this.check(vi(...e))},min(...e){return this.check(yn(...e))},max(...e){return this.check(Ws(...e))},length(...e){return this.check(Vs(...e))},nonempty(...e){return this.check(yn(1,...e))},lowercase(e){return this.check(wi(e))},uppercase(e){return this.check(Ri(e))},trim(){return this.check(Ei())},normalize(...e){return this.check(Pi(...e))},toLowerCase(){return this.check(Ai())},toUpperCase(){return this.check(Ti())},slugify(){return this.check($i())}})),Mi=$("ZodString",(e,t)=>{Us.init(e,t),kp.init(e,t)},{email(e){return this.check(zd(Cp,e))},url(e){return this.check(jc(Qc,e))},jwt(e){return this.check(cp(jp,e))},emoji(e){return this.check(Zd(Ep,e))},guid(e){return this.check(Bd(Pp,e))},uuid(e){return this.check(Hd(Vr,e))},uuidv4(e){return this.check(Wd(Vr,e))},uuidv6(e){return this.check(Vd(Vr,e))},uuidv7(e){return this.check(qd(Vr,e))},nanoid(e){return this.check(Kd(Ap,e))},cuid(e){return this.check(Jd(Tp,e))},cuid2(e){return this.check(Yd($p,e))},ulid(e){return this.check(Qd(Op,e))},base64(e){return this.check(op(Np,e))},base64url(e){return this.check(ip(Gp,e))},xid(e){return this.check(Xd(Ip,e))},ksuid(e){return this.check(ep(xp,e))},ipv4(e){return this.check(tp(Dp,e))},ipv6(e){return this.check(rp(Lp,e))},cidrv4(e){return this.check(np(Mp,e))},cidrv6(e){return this.check(sp(Fp,e))},e164(e){return this.check(ap(Up,e))},datetime(e){return this.check(zc(es,e))},date(e){return this.check(Bc(ts,e))},time(e){return this.check(Hc(rs,e))},duration(e){return this.check(Wc(ns,e))}});Me=$("ZodStringFormat",(e,t)=>{xe.init(e,t),kp.init(e,t)}),es=$("ZodISODateTime",(e,t)=>{xy.init(e,t),Me.init(e,t)}),ts=$("ZodISODate",(e,t)=>{Dy.init(e,t),Me.init(e,t)}),rs=$("ZodISOTime",(e,t)=>{Ly.init(e,t),Me.init(e,t)}),ns=$("ZodISODuration",(e,t)=>{My.init(e,t),Me.init(e,t)}),Cp=$("ZodEmail",(e,t)=>{_y.init(e,t),Me.init(e,t)});Pp=$("ZodGUID",(e,t)=>{Ry.init(e,t),Me.init(e,t)});Vr=$("ZodUUID",(e,t)=>{Sy.init(e,t),Me.init(e,t)});Qc=$("ZodURL",(e,t)=>{Cy.init(e,t),Me.init(e,t)});Ep=$("ZodEmoji",(e,t)=>{Py.init(e,t),Me.init(e,t)});Ap=$("ZodNanoID",(e,t)=>{Ey.init(e,t),Me.init(e,t)});Tp=$("ZodCUID",(e,t)=>{Ay.init(e,t),Me.init(e,t)});$p=$("ZodCUID2",(e,t)=>{Ty.init(e,t),Me.init(e,t)});Op=$("ZodULID",(e,t)=>{$y.init(e,t),Me.init(e,t)});Ip=$("ZodXID",(e,t)=>{Oy.init(e,t),Me.init(e,t)});xp=$("ZodKSUID",(e,t)=>{Iy.init(e,t),Me.init(e,t)});Dp=$("ZodIPv4",(e,t)=>{Fy.init(e,t),Me.init(e,t)});OR=$("ZodMAC",(e,t)=>{Gy.init(e,t),Me.init(e,t)});Lp=$("ZodIPv6",(e,t)=>{Ny.init(e,t),Me.init(e,t)});Mp=$("ZodCIDRv4",(e,t)=>{Uy.init(e,t),Me.init(e,t)});Fp=$("ZodCIDRv6",(e,t)=>{jy.init(e,t),Me.init(e,t)});Np=$("ZodBase64",(e,t)=>{zy.init(e,t),Me.init(e,t)});Gp=$("ZodBase64URL",(e,t)=>{By.init(e,t),Me.init(e,t)});Up=$("ZodE164",(e,t)=>{Hy.init(e,t),Me.init(e,t)});IR=$("ZodCreditCard",(e,t)=>{Wy.init(e,t),Me.init(e,t)});xR=$("ZodIBAN",(e,t)=>{Vy.init(e,t),Me.init(e,t)});jp=$("ZodJWT",(e,t)=>{qy.init(e,t),Me.init(e,t)});Ys=$("ZodCustomStringFormat",(e,t)=>{Zy.init(e,t),Me.init(e,t)});Fi=$("ZodNumber",(e,t)=>{Cd.init(e,t),ye.init(e,t),e._zod.processJSONSchema=(r,n,s)=>Dw(e,r,n,s),e.isFinite=!0},V.derived({minValue:e=>{let{minimum:t,exclusiveMinimum:r}=mt(e);return Math.max(t??Number.NEGATIVE_INFINITY,r??Number.NEGATIVE_INFINITY)},maxValue:e=>{let{maximum:t,exclusiveMaximum:r}=mt(e);return Math.min(t??Number.POSITIVE_INFINITY,r??Number.POSITIVE_INFINITY)},isInt:e=>{let{isInt:t,multipleOf:r}=mt(e);return!!t||!!r?.some(Number.isSafeInteger)},format:e=>mt(e).format??null},{gt(e,t){return this.check(Hr(e,t))},gte(e,t){return this.check(cr(e,t))},min(e,t){return this.check(cr(e,t))},lt(e,t){return this.check(Br(e,t))},lte(e,t){return this.check(ar(e,t))},max(e,t){return this.check(ar(e,t))},int(e){return this.check(_p(e))},safe(e){return this.check(_p(e))},positive(e){return this.check(Hr(0,e))},nonnegative(e){return this.check(cr(0,e))},negative(e){return this.check(Br(0,e))},nonpositive(e){return this.check(ar(0,e))},multipleOf(e,t){return this.check(Kn(e,t))},step(e,t){return this.check(Kn(e,t))},finite(){return this}}));Qs=$("ZodNumberFormat",(e,t)=>{Ky.init(e,t),Fi.init(e,t)});Ni=$("ZodBoolean",(e,t)=>{Ic.init(e,t),ye.init(e,t),e._zod.processJSONSchema=(r,n,s)=>Lw(e,r,n,s)});Gi=$("ZodBigInt",(e,t)=>{Pd.init(e,t),ye.init(e,t),e._zod.processJSONSchema=(r,n,s)=>Mw(e,r,n,s)},V.derived({minValue:e=>mt(e).minimum??null,maxValue:e=>mt(e).maximum??null,format:e=>mt(e).format??null},{gte(e,t){return this.check(cr(e,t))},min(e,t){return this.check(cr(e,t))},gt(e,t){return this.check(Hr(e,t))},lt(e,t){return this.check(Br(e,t))},lte(e,t){return this.check(ar(e,t))},max(e,t){return this.check(ar(e,t))},positive(e){return this.check(Hr(BigInt(0),e))},negative(e){return this.check(Br(BigInt(0),e))},nonpositive(e){return this.check(ar(BigInt(0),e))},nonnegative(e){return this.check(cr(BigInt(0),e))},multipleOf(e,t){return this.check(Kn(e,t))}}));zp=$("ZodBigIntFormat",(e,t)=>{Jy.init(e,t),Gi.init(e,t)});MR=$("ZodSymbol",(e,t)=>{Yy.init(e,t),ye.init(e,t),e._zod.processJSONSchema=(r,n,s)=>Fw(e,r,n,s)});FR=$("ZodUndefined",(e,t)=>{Qy.init(e,t),ye.init(e,t),e._zod.processJSONSchema=(r,n,s)=>Gw(e,r,n,s)});NR=$("ZodNull",(e,t)=>{Xy.init(e,t),ye.init(e,t),e._zod.processJSONSchema=(r,n,s)=>Nw(e,r,n,s)});UR=$("ZodAny",(e,t)=>{eb.init(e,t),ye.init(e,t),e._zod.processJSONSchema=(r,n,s)=>zw(e,r,n,s)});jR=$("ZodUnknown",(e,t)=>{tb.init(e,t),ye.init(e,t),e._zod.processJSONSchema=(r,n,s)=>Bw(e,r,n,s)});zR=$("ZodNever",(e,t)=>{rb.init(e,t),ye.init(e,t),e._zod.processJSONSchema=(r,n,s)=>jw(e,r,n,s)});BR=$("ZodVoid",(e,t)=>{nb.init(e,t),ye.init(e,t),e._zod.processJSONSchema=(r,n,s)=>Uw(e,r,n,s)});Xc=$("ZodDate",(e,t)=>{sb.init(e,t),ye.init(e,t),e._zod.processJSONSchema=(r,n,s)=>Hw(e,r,n,s),e.min=(r,n)=>e.check(cr(r,n)),e.max=(r,n)=>e.check(ar(r,n))},V.derived({minDate:e=>{let{minimum:t}=mt(e);return t?new Date(t):null},maxDate:e=>{let{maximum:t}=mt(e);return t?new Date(t):null}},{}));HR=$("ZodArray",(e,t)=>{Js(),ib.init(e,t),ye.init(e,t),e._zod.processJSONSchema=(r,n,s)=>rR(e,r,n,s),e.element=t.element},{min(e,t){return this.check(yn(e,t))},nonempty(e){return this.check(yn(1,e))},max(e,t){return this.check(Ws(e,t))},length(e,t){return this.check(Vs(e,t))},unwrap(){return this.element}});tu=$("ZodObject",(e,t)=>{Js(),ab.init(e,t),ye.init(e,t),e._zod.processJSONSchema=(r,n,s)=>nR(e,r,n,s),V.installLazyProp(e,"shape",r=>r._zod.def.shape,!1)},{keyof(){return Hp(Object.keys(this._zod.def.shape))},catchall(e){return this.clone(V.mergeDefs(this._zod.def,{catchall:e}))},passthrough(){return this.clone(V.mergeDefs(this._zod.def,{catchall:Zs()}))},loose(){return this.clone(V.mergeDefs(this._zod.def,{catchall:Zs()}))},strict(){return this.clone(V.mergeDefs(this._zod.def,{catchall:Bp()}))},strip(){return this.clone(V.mergeDefs(this._zod.def,{catchall:void 0}))},extend(e){return V.extend(this,e)},safeExtend(e){return V.safeExtend(this,e)},merge(e){return V.merge(this,e)},pick(e){return V.pick(this,e)},omit(e){return V.omit(this,e)},partial(...e){return V.partial(nu,this,e[0])},exactPartial(...e){return V.partial(Vp,this,e[0],"exactPartial")},required(...e){return V.required(qp,this,e[0])}});ru=$("ZodUnion",(e,t)=>{xc.init(e,t),ye.init(e,t),e._zod.processJSONSchema=(r,n,s)=>gp(e,r,n,s),e.options=t.options});WR=$("ZodXor",(e,t)=>{ru.init(e,t),cb.init(e,t),e._zod.processJSONSchema=(r,n,s)=>gp(e,r,n,s),e.options=t.options});VR=$("ZodDiscriminatedUnion",(e,t)=>{ru.init(e,t),lb.init(e,t)});qR=$("ZodIntersection",(e,t)=>{db.init(e,t),ye.init(e,t),e._zod.processJSONSchema=(r,n,s)=>sR(e,r,n,s)});KR=$("ZodTuple",(e,t)=>{Js(),Ed.init(e,t),ye.init(e,t),e._zod.processJSONSchema=(r,n,s)=>oR(e,r,n,s)},{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 nu({type:"optional",innerType:t}))})}});Di=$("ZodRecord",(e,t)=>{Js(),pb.init(e,t),ye.init(e,t),e._zod.processJSONSchema=(r,n,s)=>iR(e,r,n,s),e.keyType=t.keyType,e.valueType=t.valueType});QR=$("ZodMap",(e,t)=>{Js(),mb.init(e,t),ye.init(e,t),e._zod.processJSONSchema=(r,n,s)=>eR(e,r,n,s),e.keyType=t.keyType,e.valueType=t.valueType,e.min=(...r)=>e.check(Wr(...r)),e.nonempty=r=>e.check(Wr(1,r)),e.max=(...r)=>e.check(Jn(...r)),e.size=(...r)=>e.check(Hs(...r))});XR=$("ZodSet",(e,t)=>{Js(),fb.init(e,t),ye.init(e,t),e._zod.processJSONSchema=(r,n,s)=>tR(e,r,n,s),e.min=(...r)=>e.check(Wr(...r)),e.nonempty=r=>e.check(Wr(1,r)),e.max=(...r)=>e.check(Jn(...r)),e.size=(...r)=>e.check(Hs(...r))});Li=$("ZodEnum",(e,t)=>{gb.init(e,t),ye.init(e,t),e._zod.processJSONSchema=(n,s,o)=>Ww(e,n,s,o),e.enum=t.entries,e.options=[...e._zod.values];let r=new Set(Object.keys(t.entries));e.extract=(n,s)=>{let o={};for(let i of n)if(r.has(i))o[i]=t.entries[i];else throw new Error(`Key ${i} not found in enum`);return new Li({...t,checks:[],...V.normalizeParams(s),entries:o})},e.exclude=(n,s)=>{let o={...t.entries};for(let i of n)if(r.has(i))delete o[i];else throw new Error(`Key ${i} not found in enum`);return new Li({...t,checks:[],...V.normalizeParams(s),entries:o})}});eS=$("ZodLiteral",(e,t)=>{hb.init(e,t),ye.init(e,t),e._zod.processJSONSchema=(r,n,s)=>Vw(e,r,n,s),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]}})});tS=$("ZodFile",(e,t)=>{yb.init(e,t),ye.init(e,t),e._zod.processJSONSchema=(r,n,s)=>Kw(e,r,n,s),e.min=(r,n)=>e.check(Wr(r,n)),e.max=(r,n)=>e.check(Jn(r,n)),e.mime=(r,n)=>e.check(Ci(Array.isArray(r)?r:[r],n))});rS=$("ZodTransform",(e,t)=>{Js(),bb.init(e,t),ye.init(e,t),e._zod.processJSONSchema=(r,n,s)=>Xw(e,r,n,s),e._zod.parse=(r,n)=>{if(n.direction==="backward")throw new qn(e.constructor.name);r.addIssue=o=>{if(typeof o=="string")r.issues.push(V.issue(o,r.value,t));else{let i=o;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),"input"in i||(i.input=r.value),i.inst??(i.inst=e),r.issues.push(V.issue(i))}};let s=t.transform(r.value,r);return s instanceof Promise?s.then(o=>(r.value=o,r)):(r.value=s,r)}});nu=$("ZodOptional",(e,t)=>{Ad.init(e,t),ye.init(e,t),e._zod.processJSONSchema=(r,n,s)=>hp(e,r,n,s),e.unwrap=()=>e._zod.def.innerType});Vp=$("ZodExactOptional",(e,t)=>{wb.init(e,t),ye.init(e,t),e._zod.processJSONSchema=(r,n,s)=>hp(e,r,n,s),e.unwrap=()=>e._zod.def.innerType});sS=$("ZodNullable",(e,t)=>{Rb.init(e,t),ye.init(e,t),e._zod.processJSONSchema=(r,n,s)=>aR(e,r,n,s),e.unwrap=()=>e._zod.def.innerType});oS=$("ZodDefault",(e,t)=>{Sb.init(e,t),ye.init(e,t),e._zod.processJSONSchema=(r,n,s)=>lR(e,r,n,s),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});aS=$("ZodPrefault",(e,t)=>{_b.init(e,t),ye.init(e,t),e._zod.processJSONSchema=(r,n,s)=>dR(e,r,n,s),e.unwrap=()=>e._zod.def.innerType});qp=$("ZodNonOptional",(e,t)=>{vb.init(e,t),ye.init(e,t),e._zod.processJSONSchema=(r,n,s)=>cR(e,r,n,s),e.unwrap=()=>e._zod.def.innerType});lS=$("ZodSuccess",(e,t)=>{kb.init(e,t),ye.init(e,t),e._zod.processJSONSchema=(r,n,s)=>Jw(e,r,n,s),e.unwrap=()=>e._zod.def.innerType});dS=$("ZodCatch",(e,t)=>{Cb.init(e,t),ye.init(e,t),e._zod.processJSONSchema=(r,n,s)=>pR(e,r,n,s),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});mS=$("ZodNaN",(e,t)=>{Pb.init(e,t),ye.init(e,t),e._zod.processJSONSchema=(r,n,s)=>qw(e,r,n,s)});su=$("ZodPipe",(e,t)=>{Td.init(e,t),ye.init(e,t),e._zod.processJSONSchema=(r,n,s)=>mR(e,r,n,s),e.in=t.in,e.out=t.out});ou=$("ZodCodec",(e,t)=>{su.init(e,t),Dc.init(e,t)});fS=$("ZodPreprocess",(e,t)=>{su.init(e,t),Eb.init(e,t)}),gS=$("ZodReadonly",(e,t)=>{Ab.init(e,t),ye.init(e,t),e._zod.processJSONSchema=(r,n,s)=>fR(e,r,n,s),e.unwrap=()=>e._zod.def.innerType});yS=$("ZodTemplateLiteral",(e,t)=>{Tb.init(e,t),ye.init(e,t),e._zod.processJSONSchema=(r,n,s)=>Zw(e,r,n,s)});bS=$("ZodLazy",(e,t)=>{Lc.init(e,t),ye.init(e,t),e._zod.processJSONSchema=(r,n,s)=>hR(e,r,n,s),e.unwrap=()=>e._zod.def.getter()});RS=$("ZodPromise",(e,t)=>{Ob.init(e,t),ye.init(e,t),e._zod.processJSONSchema=(r,n,s)=>gR(e,r,n,s),e.unwrap=()=>e._zod.def.innerType});SS=$("ZodFunction",(e,t)=>{$b.init(e,t),ye.init(e,t),e._zod.processJSONSchema=(r,n,s)=>Qw(e,r,n,s)});iu=$("ZodCustom",(e,t)=>{Ib.init(e,t),ye.init(e,t),e._zod.processJSONSchema=(r,n,s)=>Yw(e,r,n,s)});cA=Pw,uA=Ew,kS=$("ZodInstanceOf",(e,t)=>{iu.init(e,t)},{properties(e,t){return this.check(ki(e,t))}});dA=(...e)=>Aw({Codec:ou,Boolean:Ni,String:Mi},...e)});function dj(e){Ye({customError:e})}function pj(){return Ye().customError}var lj,CS,fA=A(()=>{ur();lj={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"};CS||(CS={})});var au={};re(au,{ZodISODate:()=>ts,ZodISODateTime:()=>es,ZodISODuration:()=>ns,ZodISOTime:()=>rs,date:()=>fj,datetime:()=>mj,duration:()=>hj,time:()=>gj});function mj(e){return zc(es,e)}function fj(e){return Bc(ts,e)}function gj(e){return Hc(rs,e)}function hj(e){return Wc(ns,e)}var Zp=A(()=>{ur();ss();ss()});function bj(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 gA(e,t){return e.map((r,n)=>n<t?r:r.optional())}function wj(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}function Rj(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 n=t.version==="draft-2020-12"?"$defs":"definitions";if(r[0]===n){let s=r[1]===void 0?void 0:wj(r[1]);if(!s||!t.defs[s])throw new Error(`Reference not found: ${e}`);return t.defs[s]}throw new Error(`Reference not found: ${e}`)}function Sj(e,t){return W.transform(n=>n).check(n=>{let s=n.value;if(typeof s!="object"||s===null||Array.isArray(s))return;let o=Object.getOwnPropertyNames(s);if(t.minProperties!==void 0&&o.length<t.minProperties&&n.issues.push({origin:"object",code:"too_small",minimum:t.minProperties,inclusive:!0,message:`Too small: expected object to have >=${t.minProperties} properties`,input:s,inst:e,continue:!0}),t.maxProperties!==void 0&&o.length>t.maxProperties&&n.issues.push({origin:"object",code:"too_big",maximum:t.maxProperties,inclusive:!0,message:`Too big: expected object to have <=${t.maxProperties} properties`,input:s,inst:e,continue:!0}),t.keySchema)for(let i of o){let a=t.keySchema.safeParse(i);a.success||n.issues.push({code:"invalid_key",origin:"record",issues:a.error.issues,input:i,path:[i],continue:!0})}}).pipe(e)}function PS(e,t){if(e===null)return"z";let r=typeof e;if(r!=="object"){if(r==="number"&&Number.isNaN(e))return null;let n=String(e);return`${r[0]}${n.length}:${n}`}if(t.has(e))return null;t.add(e);try{if(Array.isArray(e)){let o=[];for(let i of e){let a=PS(i,t);if(a===null)return null;o.push(a)}return`a${o.length}:[${o.join(",")}]`}let n=Object.keys(e).sort(),s=[];for(let o of n){let i=PS(e[o],t);if(i===null)return null;s.push(`${o.length}:${o}=${i}`)}return`o${s.length}:{${s.join(",")}}`}finally{t.delete(e)}}function cu(e){return typeof e!="object"||e===null?!1:Array.isArray(e)?e.some(cu):typeof e.$ref=="string"?!0:Object.entries(e).some(([t,r])=>_j.has(t)?cu(r):!vj.has(t)||typeof r!="object"||r===null?!1:Object.values(r).some(cu))}function hA(e){return e===1?"element":"elements"}function kj(e,t){return W.transform(n=>n).check(n=>{let s=n.value;if(Array.isArray(s)){if(t.uniqueItems===!0){let o=new Map;for(let i=0;i<s.length;i++){let a=PS(s[i],new Set);if(a===null)continue;let c=o.get(a);if(c===void 0){o.set(a,i);continue}n.issues.push({code:"custom",message:`Array items must be unique: element at index ${i} duplicates the one at index ${c}`,input:s,path:[i],continue:!0})}}if(t.containsSchema){let o=t.minContains??1,i=t.maxContains!==void 0?t.maxContains+1:Number.POSITIVE_INFINITY,a=0;for(let c of s)if(t.containsSchema.safeParse(c).success&&++a>=i)break;a<o&&n.issues.push({code:"custom",message:`Array must contain at least ${o} matching ${hA(o)}; found ${a}`,input:s,continue:!0}),t.maxContains!==void 0&&a>t.maxContains&&n.issues.push({code:"custom",message:`Array must contain at most ${t.maxContains} matching ${hA(t.maxContains)}`,input:s,continue:!0})}}}).pipe(e)}function yA(e,t){if(e!==!1)return e===void 0||e===!0?W.any():Nt(e,t)}function bA(e,t){if(e.not!==void 0){if(typeof e.not=="object"&&Object.keys(e.not).length===0)return W.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 s=e.$ref;if(t.refs.has(s))return t.refs.get(s);if(t.processing.has(s))return W.lazy(()=>{if(!t.refs.has(s))throw new Error(`Circular reference not resolved: ${s}`);return t.refs.get(s)});t.processing.add(s);let o=Rj(s,t),i=Nt(o,t);return t.refs.set(s,i),t.processing.delete(s),i}if(e.enum!==void 0){let s=e.enum;if(t.version==="openapi-3.0"&&e.nullable===!0&&s.length===1&&s[0]===null)return W.null();if(s.length===0)return W.never();if(s.length===1)return W.literal(s[0]);if(s.every(i=>typeof i=="string"))return W.enum(s);let o=s.map(i=>W.literal(i));return o.length<2?o[0]:W.union([o[0],o[1],...o.slice(2)])}if(e.const!==void 0)return W.literal(e.const);let r=e.type;if(Array.isArray(r)){let s=r.map(o=>{let i={...e,type:o};return bA(i,t)});return s.length===0?W.never():s.length===1?s[0]:W.union(s)}if(!r)return W.any();let n;switch(r){case"string":{let s=W.string();if(e.format){let o=e.format;o==="email"?s=s.check(W.email()):o==="uri"||o==="uri-reference"?s=s.check(W.url()):o==="uuid"||o==="guid"?s=s.check(W.uuid()):o==="date-time"?s=s.check(W.iso.datetime({offset:!0})):o==="date"?s=s.check(W.iso.date()):o==="time"?s=s.check(W.regex(Cj)):o==="duration"?s=s.check(W.iso.duration()):o==="hostname"?s=s.check(W.hostname()):o==="ipv4"?s=s.check(W.ipv4()):o==="ipv6"?s=s.check(W.ipv6()):o==="mac"?s=s.check(W.mac()):o==="cidr"?s=s.check(W.cidrv4()):o==="cidr-v6"?s=s.check(W.cidrv6()):o==="base64"?s=s.check(W.base64()):o==="base64url"?s=s.check(W.base64url()):o==="e164"?s=s.check(W.e164()):o==="credit_card"?s=s.check(W.creditCard()):o==="iban"?s=s.check(W.iban()):o==="jwt"?s=s.check(W.jwt()):o==="emoji"?s=s.check(W.emoji()):o==="nanoid"?s=s.check(W.nanoid()):o==="cuid"?s=s.check(W.cuid()):o==="cuid2"?s=s.check(W.cuid2()):o==="ulid"?s=s.check(W.ulid()):o==="xid"?s=s.check(W.xid()):o==="ksuid"&&(s=s.check(W.ksuid()))}typeof e.minLength=="number"&&(s=s.min(e.minLength)),typeof e.maxLength=="number"&&(s=s.max(e.maxLength)),e.pattern&&(s=s.regex(new RegExp(e.pattern))),n=s;break}case"number":case"integer":{let s=r==="integer"?W.number().int():W.number();typeof e.minimum=="number"&&e.exclusiveMinimum!==!0&&(s=s.min(e.minimum)),typeof e.maximum=="number"&&e.exclusiveMaximum!==!0&&(s=s.max(e.maximum)),typeof e.exclusiveMinimum=="number"?s=s.gt(e.exclusiveMinimum):e.exclusiveMinimum===!0&&typeof e.minimum=="number"&&(s=s.gt(e.minimum)),typeof e.exclusiveMaximum=="number"?s=s.lt(e.exclusiveMaximum):e.exclusiveMaximum===!0&&typeof e.maximum=="number"&&(s=s.lt(e.maximum)),typeof e.multipleOf=="number"&&(s=s.multipleOf(e.multipleOf)),n=s;break}case"boolean":{n=W.boolean();break}case"null":{n=W.null();break}case"object":{let s={},o=e.properties||{},i=new Set(e.required||[]),a=typeof e.additionalProperties=="object"?Nt(e.additionalProperties,t):void 0;for(let[p,m]of Object.entries(o)){let f=Nt(m,t);vt(s,p,i.has(p)?f:f.optional())}if(e.patternProperties){let p=e.patternProperties,m=Object.keys(p),f=[];for(let y of m){let b=Nt(p[y],t),R=W.string().regex(new RegExp(y));f.push(W.looseRecord(R,b))}let g=[];if(Object.keys(s).length>0&&g.push(W.object(s).passthrough()),g.push(...f),g.length===0)n=W.object({}).passthrough();else if(g.length===1)n=g[0];else{let y=W.intersection(g[0],g[1]);for(let b=2;b<g.length;b++)y=W.intersection(y,g[b]);n=y}if(e.additionalProperties===!1){let y=Object.keys(s),b=m.map(h=>new RegExp(h)),R=n;n=n.check(h=>{if(!Sr(h.value))return;let _=[];for(let S of Object.keys(h.value))y.includes(S)||b.some(w=>w.test(S))||_.push(S);_.length&&h.issues.push({code:"unrecognized_keys",keys:_,input:h.value,inst:R})})}}else{let p=W.object(s);e.additionalProperties===!1?n=p.strict():a?n=p.catchall(a):n=p.passthrough()}let c=e.propertyNames!==void 0&&e.propertyNames!==!0,u=typeof e.minProperties=="number"?e.minProperties:void 0,d=typeof e.maxProperties=="number"?e.maxProperties:void 0;if(c||u!==void 0||d!==void 0){let p;if(c){let m=typeof e.propertyNames=="object"&&e.propertyNames.type===void 0?{type:"string",...e.propertyNames}:e.propertyNames;p=Nt(m,t)}n=Sj(n,{keySchema:p,minProperties:u,maxProperties:d})}break}case"array":{let s=e.prefixItems,o=e.items;if(s&&Array.isArray(s)){let i=typeof e.minItems=="number"?e.minItems:0,a=s.map(p=>Nt(p,t)),c=gA(a,i),u=Array.isArray(o)?void 0:yA(o,t),d=W.tuple(c);n=u?d.rest(u):d,typeof e.minItems=="number"&&(n=n.check(W.minLength(e.minItems))),typeof e.maxItems=="number"&&(n=n.check(W.maxLength(e.maxItems)))}else if(Array.isArray(o)){let i=typeof e.minItems=="number"?e.minItems:0,a=o.map(p=>Nt(p,t)),c=gA(a,i),u=yA(e.additionalItems,t),d=W.tuple(c);n=u?d.rest(u):d,typeof e.minItems=="number"&&(n=n.check(W.minLength(e.minItems))),typeof e.maxItems=="number"&&(n=n.check(W.maxLength(e.maxItems)))}else if(o!==void 0){let i=Nt(o,t),a=W.array(i);typeof e.minItems=="number"&&(a=a.min(e.minItems)),typeof e.maxItems=="number"&&(a=a.max(e.maxItems)),n=a}else n=W.array(W.any());(e.uniqueItems===!0||e.contains!==void 0)&&(n=kj(n,{uniqueItems:e.uniqueItems===!0,containsSchema:e.contains!==void 0?Nt(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 n}function Nt(e,t){if(typeof e=="boolean")return e?W.any():W.never();let r=bA(e,t),n=e.type||e.enum!==void 0||e.const!==void 0;if(e.anyOf&&Array.isArray(e.anyOf)){let a=e.anyOf.map(u=>Nt(u,t)),c=W.union(a);r=n?W.intersection(r,c):c}if(e.oneOf&&Array.isArray(e.oneOf)){let a=e.oneOf.map(u=>Nt(u,t)),c=W.xor(a);r=n?W.intersection(r,c):c}if(e.allOf&&Array.isArray(e.allOf))if(e.allOf.length===0)r=n?r:W.any();else{let a=n?r:Nt(e.allOf[0],t),c=n?0:1;for(let u=c;u<e.allOf.length;u++)a=W.intersection(a,Nt(e.allOf[u],t));r=a}e.nullable===!0&&t.version==="openapi-3.0"&&(r=W.nullable(r)),e.readOnly===!0&&(r=W.readonly(r)),e.default!==void 0&&(r=r.default(e.default));let s={},o=["$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor"];for(let a of o)a in e&&(s[a]=e[a]);let i=["contentEncoding","contentMediaType","contentSchema"];for(let a of i)a in e&&(s[a]=e[a]);if(e.type==="object"&&e.$ref===void 0){e.propertyNames!==void 0&&!cu(e.propertyNames)&&(s.propertyNames=e.propertyNames);for(let a of["minProperties","maxProperties"])e[a]!==void 0&&(s[a]=e[a])}if(e.type==="array"&&e.$ref===void 0){e.contains!==void 0&&!cu(e.contains)&&(s.contains=e.contains);for(let a of["uniqueItems","minContains","maxContains"])e[a]!==void 0&&(s[a]=e[a])}for(let a of Object.keys(e))yj.has(a)||vt(s,a,e[a]);return Object.keys(s).length>0&&t.registry.add(r,s),e.description&&(r=r.describe(e.description)),r}function wA(e,t){if(typeof e=="boolean")return e?W.any():W.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 n=bj(r,t?.defaultTarget),s=r.$defs||r.definitions||{},o={version:n,defs:s,refs:new Map,processing:new Set,rootSchema:r,registry:t?.registry??kt};return Nt(r,o)}var W,yj,_j,vj,Cj,RA=A(()=>{Uc();nt();Rp();Zp();ss();W={...ji,...wp,iso:au},yj=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"]);_j=new Set(["items","prefixItems","additionalItems","additionalProperties","contains","propertyNames","not","if","then","else","allOf","anyOf","oneOf","unevaluatedItems","unevaluatedProperties","contentSchema"]),vj=new Set(["properties","patternProperties","dependentSchemas","dependencies","$defs","definitions"]);Cj=/^(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:\.\d+)?(?:Z|[+-](?:[01]\d|2[0-3]):[0-5]\d)$/});function uu(e,t){let r=typeof t=="function"?t:(i,a)=>{let c=t[i._zod.def.type];return c?c(i,a):i},n=new Map;function s(i){let a=n.get(i);if(a===SA)return new Lc({type:"lazy",getter:()=>n.get(i)});if(a!==void 0)return a;n.set(i,SA);let c=o(i),u=r(c,c!==i);return n.set(i,u),u}function o(i){let a=i._zod.def,c=a.type;switch(c){case"object":{let u=a.shape,d=Object.keys(u),p=!1,m={};for(let g of d){let y=s(u[g]);y!==u[g]&&(p=!0),m[g]=y}let f=a.catchall;return a.catchall&&(f=s(a.catchall),f!==a.catchall&&(p=!0)),p?Ie(i,{...a,shape:m,catchall:f}):i}case"array":{let u=s(a.element);return u===a.element?i:Ie(i,{...a,element:u})}case"tuple":{let u=a.items,d=!1,p=[];for(let f of u){let g=s(f);g!==f&&(d=!0),p.push(g)}let m=a.rest;return a.rest&&(m=s(a.rest),m!==a.rest&&(d=!0)),d?Ie(i,{...a,items:p,rest:m}):i}case"record":case"map":{let u=s(a.keyType),d=s(a.valueType);return u===a.keyType&&d===a.valueType?i:Ie(i,{...a,keyType:u,valueType:d})}case"set":{let u=s(a.valueType);return u===a.valueType?i:Ie(i,{...a,valueType:u})}case"union":{let u=a.options,d=!1,p=[];for(let m of u){let f=s(m);f!==m&&(d=!0),p.push(f)}return d?Ie(i,{...a,options:p}):i}case"intersection":{let u=s(a.left),d=s(a.right);return u===a.left&&d===a.right?i:Ie(i,{...a,left:u,right:d})}case"optional":case"nullable":case"default":case"prefault":case"catch":case"readonly":case"nonoptional":case"promise":case"success":{let u=s(a.innerType);return u===a.innerType?i:Ie(i,{...a,innerType:u})}case"pipe":{let u=s(a.in),d=s(a.out);return u===a.in&&d===a.out?i:Ie(i,{...a,in:u,out:d})}case"function":{let u=s(a.input),d=s(a.output);return u===a.input&&d===a.output?i:Ie(i,{...a,input:u,output:d})}case"lazy":{let u=a.getter,{_cachedInner:d,...p}=a;return Ie(i,{...p,getter:()=>s(u())})}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 i;default:return i}}return s(e)}var SA,ES=A(()=>{gi();nt();SA=Symbol("z.visit/resolving")});function _A(e){return uu(e,{object:t=>t.partial(),union:t=>{let r=t._zod.def;return r.discriminator===void 0?t:Ui(r.options)}})}var vA=A(()=>{ES();ss()});function Pj(e,t){if(!t?.length)return e;let r=e._zod.def;return Ie(e,$r(r,{checks:[...r.checks??[],...t]}),{parent:!0})}function kA(e){return Pj(e.out,e.checks)}function Ej(e){return e.in._zod.traits.has("$ZodTransform")?kA(e):e.in}function CA(e){return uu(e,{pipe:t=>Ej(t._zod.def),default:(t,r)=>r?Ks(t._zod.def.innerType):t,catch:(t,r)=>r?t._zod.def.innerType:t})}function PA(e){return uu(e,{pipe:t=>kA(t._zod.def),prefault:(t,r)=>r?t._zod.def.innerType:t})}var EA=A(()=>{nt();ES();ss()});var AS={};re(AS,{bigint:()=>Oj,boolean:()=>$j,date:()=>Ij,number:()=>Tj,string:()=>Aj});function Aj(e){return qb(Mi,e)}function Tj(e){return Xb(Fi,e)}function $j(e){return iw(Ni,e)}function Oj(e){return cw(Gi,e)}function Ij(e){return ww(Xc,e)}var AA=A(()=>{ur();ss()});var l={};re(l,{$brand:()=>ah,$input:()=>Gb,$output:()=>Nb,INVALID:()=>Mt,NEVER:()=>ih,TimePrecision:()=>Yb,ZodAny:()=>UR,ZodArray:()=>HR,ZodBase64:()=>Np,ZodBase64URL:()=>Gp,ZodBigInt:()=>Gi,ZodBigIntFormat:()=>zp,ZodBoolean:()=>Ni,ZodCIDRv4:()=>Mp,ZodCIDRv6:()=>Fp,ZodCUID:()=>Tp,ZodCUID2:()=>$p,ZodCatch:()=>dS,ZodCodec:()=>ou,ZodCompileAsyncError:()=>Or,ZodCompileUnsupportedError:()=>_e,ZodCreditCard:()=>IR,ZodCustom:()=>iu,ZodCustomStringFormat:()=>Ys,ZodDate:()=>Xc,ZodDefault:()=>oS,ZodDiscriminatedUnion:()=>VR,ZodE164:()=>Up,ZodEmail:()=>Cp,ZodEmoji:()=>Ep,ZodEnum:()=>Li,ZodError:()=>aj,ZodExactOptional:()=>Vp,ZodFile:()=>tS,ZodFirstPartyTypeKind:()=>CS,ZodFunction:()=>SS,ZodGUID:()=>Pp,ZodIBAN:()=>xR,ZodIPv4:()=>Dp,ZodIPv6:()=>Lp,ZodISODate:()=>ts,ZodISODateTime:()=>es,ZodISODuration:()=>ns,ZodISOTime:()=>rs,ZodInstanceOf:()=>kS,ZodIntersection:()=>qR,ZodIssueCode:()=>lj,ZodJWT:()=>jp,ZodKSUID:()=>xp,ZodLazy:()=>bS,ZodLiteral:()=>eS,ZodMAC:()=>OR,ZodMap:()=>QR,ZodNaN:()=>mS,ZodNanoID:()=>Ap,ZodNever:()=>zR,ZodNonOptional:()=>qp,ZodNull:()=>NR,ZodNullable:()=>sS,ZodNumber:()=>Fi,ZodNumberFormat:()=>Qs,ZodObject:()=>tu,ZodOptional:()=>nu,ZodPipe:()=>su,ZodPrefault:()=>aS,ZodPreprocess:()=>fS,ZodPromise:()=>RS,ZodReadonly:()=>gS,ZodRealError:()=>Yt,ZodRecord:()=>Di,ZodSet:()=>XR,ZodString:()=>Mi,ZodStringFormat:()=>Me,ZodSuccess:()=>lS,ZodSymbol:()=>MR,ZodTemplateLiteral:()=>yS,ZodTransform:()=>rS,ZodTuple:()=>KR,ZodType:()=>ye,ZodULID:()=>Op,ZodURL:()=>Qc,ZodUUID:()=>Vr,ZodUndefined:()=>FR,ZodUnion:()=>ru,ZodUnknown:()=>jR,ZodVoid:()=>BR,ZodXID:()=>Ip,ZodXor:()=>WR,_ZodString:()=>kp,_default:()=>iS,_function:()=>oA,any:()=>ME,array:()=>eu,base64:()=>hE,base64url:()=>yE,bigint:()=>OE,boolean:()=>LR,catch:()=>pS,check:()=>iA,cidrv4:()=>fE,cidrv6:()=>gE,clone:()=>Ie,codec:()=>tA,coerce:()=>AS,compile:()=>Bb,config:()=>Ye,core:()=>bn,creditCard:()=>wE,cuid:()=>iE,cuid2:()=>aE,currencyCode:()=>CE,custom:()=>aA,date:()=>NE,decode:()=>vR,decodeAsync:()=>CR,deepPartial:()=>_A,describe:()=>cA,discriminatedUnion:()=>HE,e164:()=>bE,email:()=>JP,emoji:()=>sE,encode:()=>_R,encodeAsync:()=>kR,endsWith:()=>vi,enum:()=>Hp,exactOptional:()=>nS,file:()=>YE,flattenError:()=>wc,float32:()=>EE,float64:()=>AE,formatError:()=>Rc,fromJSONSchema:()=>wA,function:()=>oA,getDiscriminatedOption:()=>ub,getErrorMap:()=>pj,globalRegistry:()=>kt,gt:()=>Hr,gte:()=>cr,guid:()=>YP,hash:()=>PE,hex:()=>kE,hostname:()=>vE,httpUrl:()=>nE,iban:()=>RE,includes:()=>Si,input:()=>CA,instanceof:()=>lA,int:()=>_p,int32:()=>TE,int64:()=>IE,intersection:()=>ZR,invertCodec:()=>rA,ipv4:()=>dE,ipv6:()=>mE,iso:()=>au,json:()=>pA,jwt:()=>SE,keyof:()=>GE,ksuid:()=>lE,lazy:()=>wS,length:()=>Vs,literal:()=>JE,locales:()=>Gc,looseObject:()=>zE,looseRecord:()=>VE,lowercase:()=>wi,lt:()=>Br,lte:()=>ar,mac:()=>pE,map:()=>qE,maxLength:()=>Ws,maxSize:()=>Jn,memoizer:()=>Nc,meta:()=>uA,mime:()=>Ci,minLength:()=>yn,minSize:()=>Wr,multipleOf:()=>Kn,nan:()=>eA,nanoid:()=>oE,nativeEnum:()=>KE,negative:()=>lp,never:()=>Bp,nonnegative:()=>pp,nonoptional:()=>uS,nonpositive:()=>dp,normalize:()=>Pi,null:()=>GR,nullable:()=>Yc,nullish:()=>QE,number:()=>DR,object:()=>UE,optional:()=>Ks,output:()=>PA,overwrite:()=>Ir,parse:()=>bR,parseAsync:()=>wR,partialRecord:()=>WE,pipe:()=>vp,positive:()=>up,prefault:()=>cS,preprocess:()=>mA,prettifyError:()=>ph,promise:()=>sA,properties:()=>ki,property:()=>mp,readonly:()=>hS,record:()=>YR,refine:()=>_S,regex:()=>bi,regexes:()=>vr,registry:()=>Nd,safeDecode:()=>ER,safeDecodeAsync:()=>TR,safeEncode:()=>PR,safeEncodeAsync:()=>AR,safeParse:()=>RR,safeParseAsync:()=>SR,set:()=>ZE,setErrorMap:()=>dj,size:()=>Hs,slugify:()=>$i,startsWith:()=>_i,strictObject:()=>jE,string:()=>Jc,stringFormat:()=>_E,stringbool:()=>dA,success:()=>XE,superRefine:()=>vS,symbol:()=>DE,templateLiteral:()=>nA,toJSONSchema:()=>yp,toLowerCase:()=>Ai,toUpperCase:()=>Ti,toZod:()=>uc,transform:()=>Wp,treeifyError:()=>dh,trim:()=>Ei,tuple:()=>JR,uint32:()=>$E,uint64:()=>xE,ulid:()=>cE,undefined:()=>LE,union:()=>Ui,unknown:()=>Zs,uppercase:()=>Ri,url:()=>rE,util:()=>V,uuid:()=>QP,uuidv4:()=>XP,uuidv6:()=>eE,uuidv7:()=>tE,validate:()=>Sc,validateAsync:()=>_c,void:()=>FE,withParser:()=>Gd,xid:()=>uE,xor:()=>BE});var TS=A(()=>{ur();ss();Rp();yR();$R();fA();ur();Kc();RA();vA();EA();Fb();Zp();Zp();AA()});var lu=A(()=>{TS();TS()});function OA({author:e,comments:t}){let r=t.filter(n=>!n.isBot&&n.author===e).map(n=>n.body);return r.some(n=>Mj.some(s=>s.test(n)))?"superseded":r.some(n=>Fj.test(n))?"no-traction":t.some(n=>!n.isBot&&n.author!==e)?"after-feedback":"no-response"}function IA({author:e,closer:t,closerIsBot:r,comments:n}){let s=n.filter(o=>!o.isBot&&o.author!==e).map(o=>o.body);return s.some(o=>xj.test(o))?"ai-policy":s.some(o=>Dj.test(o))?"superseded":r||s.some(o=>Lj.test(o))?"stale":t?t===e?"self-closed":"rejected":"unknown"}var TA,$A,xj,Dj,Lj,Mj,Fj,$S=A(()=>{"use strict";TA=["ai-policy","superseded","stale","self-closed","rejected","unknown"],$A=["superseded","no-traction","after-feedback","no-response"],xj=/\b(?:AI|LLM)[- ](?:generated|written|authored|slop|polic(?:y|ies))|(?:generated|written) (?:by|with) (?:an? )?(?:AI|LLM|ChatGPT|Copilot)\b|vibe[- ]?cod|machine[- ]generated/i,Dj=/clos(?:e|ing) (?:this )?as (?:a )?duplicate|duplicate of #\d+|superseded by|already (?:been )?(?:fixed|merged|addressed|resolved|implemented)|fixed (?:in|by|via) #\d+|in favou?r of #\d+/i,Lj=/marked as stale|clos(?:e|ing) (?:this )?(?:as|due to) (?:stale|inactiv)|no activity (?:for|in)/i,Mj=[/already (?:been )?(?:fixed|merged|addressed|resolved|implemented|landed|applied|several)/i,/cover(?:s|ed) (?:this|everything|the same)|same (?:one-line )?fix|(?:landed|fixed|ships?) the same/i,/has (?:landed|shipped)|is in and|(?:fixed|addressed|resolved|landed|applied) (?:upstream|elsewhere)/i,/upstream (?:upgrade|commit|fix)|supersed|in favou?r of|replaced by|duplicate/i,/no longer (?:needed|relevant|reproduc|applies)/i],Fj=/traction|(?:been )?quiet|unmaintained|actively (?:reviewing|maintained)|not maintained|no (?:response|activity)|keep the queue tidy|sitting in (?:your|the) queue|stale/i});function Xs(e){return l.custom(t=>typeof t=="string")}function tz(e){let t=e?.openPRs;return!Array.isArray(t)||t.length===0?e:{...e,needsAddressingPRs:t.filter(r=>r?.status==="needs_addressing"),waitingOnMaintainerPRs:t.filter(r=>r?.status==="waiting_on_maintainer")}}function MA(e,t){let r=e!==null&&typeof e=="object"?e.workClaims:void 0;return Array.isArray(r)?Math.max(0,r.length-t.workClaims.length):0}function Jp(e){if(!e||typeof e!="object")return[];let t=new Set(Object.keys(Gt.shape));return Object.keys(e).filter(r=>!t.has(r))}var Nj,IS,xS,DS,LS,Gj,Uj,DA,LA,jj,zj,Bj,Hj,Wj,Vj,qj,Zj,xA,Kj,Kp,Jj,Yj,Qj,Xj,ez,OS,rz,nz,sz,oz,iz,MS,FS,eo,az,Gt,Yp,wn=A(()=>{"use strict";lu();$S();Nj=l.enum(["candidate","claimed","in_progress","pr_submitted"]),IS=l.enum(["needs_addressing","waiting_on_maintainer"]),xS=l.enum(["nonprofit","devtools","infrastructure","web-frameworks","data-ml","education"]),DS=l.enum(["beginner","intermediate","advanced"]),LS=l.enum(["inline","sourcetree","vscode","custom"]),Gj=l.object({hasActiveMaintainers:l.boolean(),isResponsive:l.boolean(),hasHostileComments:l.boolean()}),Uj=l.object({repo:l.string(),score:l.number(),mergedPRCount:l.number(),closedWithoutMergeCount:l.number(),avgResponseDays:l.number().nullable(),lastMergedAt:l.string().optional(),lastEvaluatedAt:l.string(),signals:Gj,stargazersCount:l.number().optional(),language:l.string().nullable().optional()}).passthrough(),DA=l.object({issueUrl:l.string(),grade:l.number(),recommendation:l.string(),stargazersCount:l.number().optional(),source:Xs(["vet","vet-list","list"]),capturedAt:l.string().optional(),labels:l.array(l.string()).optional(),issueAuthorAssociation:Xs(["OWNER","MEMBER","COLLABORATOR","CONTRIBUTOR","FIRST_TIMER","FIRST_TIME_CONTRIBUTOR","MANNEQUIN","NONE"]).optional(),issueAuthorIsBot:l.boolean().optional(),competingPRs:l.number().optional(),mentioningPRs:l.number().optional(),firstInRepo:l.boolean().optional(),commentCount:l.number().optional()}).passthrough(),LA={issueUrl:l.string().optional(),pick:DA.optional(),lastReviewDecision:l.string().optional(),lastCiStatus:l.string().optional(),backfilledAt:l.string().optional(),responseRule:l.number().int().optional()},jj=l.object({url:l.string(),title:l.string(),mergedAt:l.string(),openedAt:l.string().optional(),firstMaintainerResponseAt:l.string().optional(),commentsFetchedAt:l.string().datetime().optional(),learningsExtractedAt:l.string().datetime().optional(),...LA}).passthrough(),zj=l.object({url:l.string(),title:l.string(),closedAt:l.string(),openedAt:l.string().optional(),firstMaintainerResponseAt:l.string().optional(),commentsFetchedAt:l.string().datetime().optional(),learningsExtractedAt:l.string().datetime().optional(),...LA,closeReason:Xs(TA).optional(),selfCloseReason:Xs($A).optional()}).passthrough(),Bj=l.object({url:l.string(),repo:l.string(),analyzedAt:l.string()}),Hj=l.object({tier:l.enum(["light_check_in","direct_check_in","final_check_in"]),timestamp:l.string().datetime(),draftPath:l.string().optional()}),Wj=l.object({workflowName:l.enum(["draft-first","work-through-issues","pre-commit-review"]),currentStep:l.string(),branchName:l.string().optional(),issueContext:l.object({title:l.string(),url:l.string()}).optional(),completedSteps:l.array(l.string()).default([]),stepData:l.record(l.string(),l.unknown()).default({}),lastUpdatedAt:l.string().datetime()}),Vj=l.object({branchNamingConvention:l.string().optional(),commitMessageFormat:l.string().optional(),prTitleFormat:l.string().optional(),requiredChecks:l.array(l.string()).optional(),testFramework:l.string().optional(),testCoverageRequired:l.boolean().optional(),testFileNaming:l.string().optional(),linter:l.string().optional(),formatter:l.string().optional(),styleGuideUrl:l.string().optional(),issueClaimProcess:l.string().optional(),reviewProcess:l.string().optional(),claRequired:l.boolean().optional(),rawContent:l.string().optional()}),qj=l.object({passedAllChecks:l.boolean(),checks:l.object({noExistingPR:l.boolean(),notClaimed:l.boolean(),projectActive:l.boolean(),clearRequirements:l.boolean(),contributionGuidelinesFound:l.boolean()}),contributionGuidelines:Vj.optional(),notes:l.array(l.string())}),Zj=l.object({id:l.number(),url:l.string(),repo:l.string(),number:l.number(),title:l.string(),status:Nj,labels:l.array(l.string()),createdAt:l.string(),updatedAt:l.string(),vetted:l.boolean(),vettingResult:qj.optional()}),xA=l.object({number:l.number(),url:l.string(),title:l.string(),repo:l.string(),daysSinceActivity:l.number(),status:IS}),Kj=l.object({status:IS,setAt:l.string(),lastActivityAt:l.string()}),Kp=l.object({setupComplete:l.boolean().default(!1),setupCompletedAt:l.string().optional(),persistence:l.enum(["local","gist"]).default("local"),maxActivePRs:l.number().default(10),maxOpenPRsPerRepo:l.number().int().min(0).default(0),maxOpenPRsColdRepo:l.number().int().min(0).default(1),maxConcurrentImplementations:l.number().int().min(0).default(2),dormantThresholdDays:l.number().default(30),approachingDormantDays:l.number().default(25),maxIssueAgeDays:l.number().default(90),skipBroadWhenSufficientResults:l.number().min(0).default(8),complexIssues:Xs(["off","warm"]).default("off"),languages:l.array(l.string()).default(["typescript","javascript"]),labels:l.array(l.string()).default(["good first issue","help wanted"]),scope:l.array(DS).optional(),excludeRepos:l.array(l.string()).default([]),excludeOrgs:l.array(l.string()).optional(),untrackedOrgs:l.array(l.string()).default([]),avoidRepos:l.array(l.string()).default([]),boostIssueTypes:l.array(l.string()).default([]),trustedProjects:l.array(l.string()).default([]),githubUsername:l.string().default(""),minRepoScoreThreshold:l.number().default(4),starredRepos:l.array(l.string()).default([]),starredReposLastFetched:l.string().optional(),squashByDefault:l.union([l.boolean(),l.literal("ask")]).default(!0),localRepoScanPaths:l.array(l.string()).optional(),minStars:l.number().default(50),includeDocIssues:l.boolean().default(!0),aiPolicyBlocklist:l.array(l.string()).default(["matplotlib/matplotlib"]),shelvedPRUrls:l.array(l.string()).default([]),dismissedIssues:l.record(l.string(),l.string()).default({}),dismissedPRHeads:l.record(l.string(),l.string()).default({}),statusOverrides:l.record(l.string(),Kj).optional(),issueListPath:l.string().optional(),skippedIssuesPath:l.string().optional(),projectCategories:l.array(xS).default([]),preferredOrgs:l.array(l.string()).default([]),diffTool:LS.default("inline"),diffToolCustomCommand:l.string().optional(),autoExtractLearnings:l.boolean().default(!0),autoFormatBeforePush:l.boolean().default(!1),trustOwnRepoWrites:l.boolean().default(!1),healthCheckFreshnessMinutes:l.number().int().positive().default(30),reviewMaxPasses:l.number().int().positive().optional(),slmTriageModel:l.string().default(""),slmTriageHost:l.string().default("")}).passthrough().transform(({snoozedPRs:e,...t})=>t),Jj=l.object({repos:l.record(l.string(),l.object({path:l.string(),exists:l.boolean(),currentBranch:l.string().nullable()})),scanPaths:l.array(l.string()),cachedAt:l.string()}),Yj=l.object({url:l.string(),repo:l.string(),number:l.number(),title:l.string(),closedAt:l.string(),closedBy:l.string().optional(),openedAt:l.string().optional(),issueUrl:l.string().optional()}),Qj=l.object({url:l.string(),repo:l.string(),number:l.number(),title:l.string(),mergedAt:l.string(),openedAt:l.string().optional(),issueUrl:l.string().optional()}),Xj=l.object({totalActivePRs:l.number(),totalNeedingAttention:l.number(),totalMergedAllTime:l.number(),mergeRate:l.number()}),ez=l.object({url:l.string(),repo:l.string(),number:l.number(),status:IS}).passthrough(),OS=l.array(ez);rz=l.object({generatedAt:l.string(),openPRs:OS,needsAddressingPRs:OS,waitingOnMaintainerPRs:OS,recentlyClosedPRs:l.array(Yj),recentlyMergedPRs:l.array(Qj),shelvedPRs:l.array(xA),autoUnshelvedPRs:l.array(xA),summary:Xj}),nz=l.preprocess(tz,rz),sz=l.object({url:l.string(),lastSeenAt:l.string()}),oz=l.object({url:l.string(),branch:l.string(),worktree:l.string().optional(),note:l.string().optional(),recordedAt:l.string(),pushedRef:l.string().optional(),pushedAt:l.string().optional(),compareUrl:l.string().optional(),pushProblem:l.string().optional()}).passthrough(),iz=l.object({url:l.string(),attemptedAt:l.string(),outcome:l.enum(["prepared","blocked"]),note:l.string().optional()}).passthrough(),MS=l.object({runAt:l.string(),reportPath:l.string(),prepareCount:l.number().int().nonnegative(),judgmentCount:l.number().int().nonnegative(),prepared:l.array(oz).default([]),implementUrl:l.string().optional(),implementAttempts:l.array(iz).optional()}).passthrough(),FS=l.object({languageOffset:l.number().int().nonnegative().default(0),phase0Offset:l.number().int().nonnegative().default(0),starredOffset:l.number().int().nonnegative().default(0),maintainedOffset:l.number().int().nonnegative().default(0),strategyOffset:l.number().int().nonnegative().default(0),lastRotatedAt:l.string().optional()}).passthrough(),eo=l.object({kind:Xs(["implementation","pr"]),url:l.string(),session:l.string(),startedAt:l.string(),expiresAt:l.string(),status:Xs(["running","finished"]),branch:l.string().optional(),worktree:l.string().optional(),host:l.string().optional(),machineId:l.string().optional(),runId:l.string().optional(),finishedAt:l.string().optional()}).loose(),az=l.array(l.unknown()).default([]).transform(e=>e.flatMap(t=>{let r=eo.safeParse(t);return r.success?[r.data]:[]}));Gt=l.object({version:l.literal(4),gistId:l.string().optional(),repoScores:l.record(l.string(),Uj).default({}),config:Kp.default(()=>Kp.parse({})),lastRunAt:l.string().default(()=>new Date().toISOString()),lastDigestAt:l.string().optional(),lastStrategyAt:l.string().optional(),lastDigest:nz.optional(),monthlyMergedCounts:l.record(l.string(),l.number()).optional(),monthlyClosedCounts:l.record(l.string(),l.number()).optional(),monthlyOpenedCounts:l.record(l.string(),l.number()).optional(),localRepoCache:Jj.optional(),mergedPRs:l.array(jj).optional(),closedPRs:l.array(zj).optional(),analyzedIssueConversations:l.array(Bj).optional(),activeIssues:l.array(Zj).default([]),prFollowUpHistory:l.record(l.string(),l.array(Hj)).optional(),workflowState:Wj.optional(),searchSeen:l.array(sz).default([]),pickSnapshots:l.array(DA).default([]),lastOvernight:MS.optional(),searchRotation:FS.optional(),workClaims:az}).passthrough();Yp="was written by a different oss-autopilot release (usually a newer one); this version keeps those fields but cannot use them. If you are not on the latest release, update with `claude plugin update oss-autopilot@oss-autopilot` and restart Claude Code."});function NS(e,t){return cz.test(e)&&uz.test(t)}function q(e){if(!e.startsWith("https://github.com/"))return null;let t=e.match(/github\.com\/([^/]+)\/([^/]+)\/pull\/(\d+)/);if(t){let n=t[1],s=t[2];return NS(n,s)?{owner:n,repo:s,number:parseInt(t[3],10),type:"pull"}:null}let r=e.match(/github\.com\/([^/]+)\/([^/]+)\/issues\/(\d+)/);if(r){let n=r[1],s=r[2];return NS(n,s)?{owner:n,repo:s,number:parseInt(r[3],10),type:"issues"}:null}return null}function qe(e){let t=q(e);return t?`${t.owner.toLowerCase()}/${t.repo.toLowerCase()}#${t.number}`:null}function qr(e){if(!e.startsWith("https://github.com/"))return null;let t=e.match(/github\.com\/([^/]+)\/([^/]+)/);if(!t)return null;let r=t[1],n=t[2];return NS(r,n)?{owner:r,repo:n}:null}function to(e){let[t,r]=e.split("/",2);if(!t||!r)throw new Error(`Invalid repo format: expected "owner/repo", got "${e}"`);return{owner:t,repo:r}}function kr(e,t){return e.toLowerCase()===t.toLowerCase()}function zi(e,t=[]){let r=e.toLowerCase();return t.some(n=>n.toLowerCase()===r)}var cz,uz,st=A(()=>{"use strict";cz=/^[\w-]+$/,uz=/^[\w.-]+$/});function Qt(e){return qe(e)??e.trim().toLowerCase()}function GS(e,t=Date.now()){let r=Date.parse(e.expiresAt);return Number.isFinite(r)&&r>t}function lr(e,t=Date.now()){return e.filter(r=>GS(r,t))}function ro(e,t,r=Date.now()){let n=Qt(t);return lr(e,r).find(s=>Qt(s.url)===n)}function Xp(e,t,r,n=Date.now()){let s=ro(e,t,n);if(!(s===void 0||s.session===r))return s}function em(e,t){let r=new Date(Date.parse(t)+pu*36e5),n=Date.parse(e.expiresAt),s=Number.isFinite(n)&&n>r.getTime()?e.expiresAt:r.toISOString();return{...e,status:"finished",finishedAt:t,expiresAt:s}}function tm(e,t=Date.now()){return lr(e,t).filter(r=>r.kind==="implementation"&&r.status==="finished")}function UA(e,t=Date.now()){return lr(e,t).filter(r=>r.kind==="implementation"&&r.status==="running")}function Bi(e){return GA.default.resolve(e.trim())}function lz(e,t){return e===void 0||t===void 0||e===t}function FA(e){try{return NA.realpathSync(e)}catch{return e}}function dz(e,t,r){if(!e.worktree)return!1;let n=Bi(e.worktree);return e.machineId!==void 0&&r.machineId!==void 0?e.machineId!==r.machineId?!1:FA(n)===FA(t):lz(e.host,r.host)&&n===t}function rm(e,t,r,n=Date.now()){let s=Qt(t.url),o=lr(e,n).filter(a=>a.kind==="implementation"&&Qt(a.url)!==s);if(t.worktree!==void 0){let a=Bi(t.worktree),c=o.filter(u=>dz(u,a,t));if(c.length>0){let u=c[0];return{reason:"worktree",blocking:c,message:`Checkout ${a} already hosts an implementation of ${u.url} (session ${u.session}, ${u.status}). Use a separate worktree, or finish or release that claim first.`}}}let i=o.filter(a=>a.status==="running");if(r>0&&i.length>=r){let a=i.map(c=>`${c.url} (session ${c.session})`).join(", ");return{reason:"cap",blocking:i,message:`Implementation cap reached: ${i.length} of ${r} running (${a}). Collect or release one, or raise it with \`setup --set maxConcurrentImplementations=N\`.`}}return null}function US(e,t=Date.now()){let r=Date.parse(e.startedAt),n=Number.isFinite(r)?Math.max(0,Math.floor((t-r)/6e4)):0;return n<60?`${n} min`:n<1440?`${Math.floor(n/60)} h`:`${Math.floor(n/1440)} d`}function mu(e,t=Date.now()){return`${e.kind} claimed in session ${e.session} (${US(e,t)}, ${e.status})`}function Hi(e,t,r=Date.now()){let n=ro(e,t,r);return!n||n.kind!=="implementation"?null:{recommendation:"skip",reasonsToSkip:[`Already being implemented: ${mu(n,r)}`],workClaim:n}}var NA,GA,Qp,du,pu,jS=A(()=>{"use strict";NA=B(require("node:fs"),1),GA=B(require("node:path"),1);st();Qp={implementation:24,pr:12},du=168,pu=168});function mz(e){let t=e.lastDigest,r=[...t?.openPRs??[],...t?.shelvedPRs??[],...e.activeIssues].map(i=>i.repo),s=[...(e.mergedPRs??[]).map(i=>i.url),...(e.closedPRs??[]).map(i=>i.url),...e.config.shelvedPRUrls??[]].flatMap(i=>{let a=q(i);return a?[`${a.owner}/${a.repo}`]:[]}),o=new Set(r);for(let i of s)o.add(i);return o}function fz(e,t=Date.now()){let r=t-fu*jA,n=e.searchSeen.filter(c=>Date.parse(c.lastSeenAt)>=r),s=t-pz*jA,o=mz(e),i=Object.fromEntries(Object.entries(e.repoScores).filter(([c,u])=>{let d=u.mergedPRCount>0||u.closedWithoutMergeCount>0,p=Date.parse(u.lastEvaluatedAt),m=Number.isNaN(p)||p>=s;return d||o.has(c)||m})),a=e.lastDigest&&{...e.lastDigest,needsAddressingPRs:[],waitingOnMaintainerPRs:[]};return{...e,searchSeen:n,repoScores:i,lastDigest:a}}function xr(e){return JSON.stringify(fz(e))}var jA,zS,fu,pz,Wi=A(()=>{"use strict";st();jA=1440*60*1e3,zS=7,fu=zS+1,pz=14});function gz(){try{return nm.userInfo().homedir}catch{return null}}function sm(){let e=nm.homedir(),t=process.env.VITEST?gz():null;if(t!==null&&bt.resolve(e)===bt.resolve(t))throw new Error(`Refusing to use the real home directory (${e}) under vitest`);return bt.join(e,".oss-autopilot")}function dr(){let e=sm();return Ut.existsSync(e)||Ut.mkdirSync(e,{recursive:!0,mode:448}),e}function jt(){return bt.join(dr(),"state.json")}function zA(){return bt.join(process.cwd(),"data","state.json")}function BA(){return bt.join(process.cwd(),"data","backups")}function no(){let e=bt.join(dr(),"backups");return Ut.existsSync(e)||Ut.mkdirSync(e,{recursive:!0,mode:448}),e}function om(){let e=bt.join(dr(),"cache");return Ut.existsSync(e)||Ut.mkdirSync(e,{recursive:!0,mode:448}),e}function Vi(){let e=bt.join(dr(),"reports");return Ut.existsSync(e)||Ut.mkdirSync(e,{recursive:!0,mode:448}),e}function so(){return bt.join(dr(),"gist-id")}function HA(){return bt.join(dr(),"machine-id")}function os(){return bt.join(dr(),"state-cache.json")}function im(){return Ut.existsSync(bt.join(sm(),"state.json"))}function Zr(){return"3.42.2"}var Ut,bt,nm,Kr=A(()=>{"use strict";Ut=B(require("node:fs"),1),bt=B(require("node:path"),1),nm=B(require("node:os"),1)});function cm(){am=!0}function WA(){return am}function O(e,t,...r){if(!am)return;let n=new Date().toISOString();console.error(`[${n}] [DEBUG] [${e}] ${t}`,...r)}function VA(e,t,...r){let n=new Date().toISOString();console.error(`[${n}] [INFO] [${e}] ${t}`,...r)}function k(e,t,...r){let n=new Date().toISOString();console.error(`[${n}] [WARN] [${e}] ${t}`,...r)}async function um(e,t,r){if(!am)return r();let n=performance.now();try{let s=await r(),o=(performance.now()-n).toFixed(0);return O(e,`${t} completed in ${o}ms`),s}catch(s){let o=(performance.now()-n).toFixed(0);throw O(e,`${t} failed after ${o}ms`),s}}var am,ae=A(()=>{"use strict";am=!1});function hu(e){if(process.env[lm]!==void 0)throw new Oe(`Refusing to ${e} during an unattended run (${lm} is set). Run it yourself in an interactive session.`)}function I(e){return e instanceof Error?e.message:String(e)}function je(e){if(e&&typeof e=="object"&&"status"in e){let t=e.status;return typeof t=="number"&&Number.isFinite(t)?t:void 0}}function Rn(e){let t=je(e);return t===void 0?void 0:`HTTP ${t}`}function er(e){let t=Rn(e);return t?`${t}: ${I(e)}`:I(e)}function zt(e){let t=je(e);return t===429?!0:t===403?I(e).toLowerCase().includes("rate limit"):!1}function qA(e){if(je(e)!==422)return!1;let t=e?.response?.data,r=t&&typeof t=="object"?t.errors:void 0;return Array.isArray(r)?r.some(n=>{if(!n||typeof n!="object")return!1;let s=n;return s.resource!=="Search"||s.code!=="invalid"?!1:typeof s.message=="string"?BS.test(s.message):BS.test(I(e))}):BS.test(I(e))}function le(e){let t=je(e);if(t===401||t===429)return!0;if(t===403){let r=I(e).toLowerCase();return r.includes("rate limit")||r.includes("abuse detection")}return!1}function pm(e){if(!e||typeof e!="object")return!1;let t=je(e);if(typeof t=="number"&&t>=500&&t<600)return!0;let r=e.code;if(typeof r=="string"&&(r==="ECONNRESET"||r==="ETIMEDOUT"||r==="ENETUNREACH"||r==="ENOTFOUND"||r==="ECONNREFUSED"||r==="EAI_AGAIN"))return!0;let n=e.name;return typeof n=="string"&&(n==="AbortError"||n==="TimeoutError")}function ZA(e){return t=>{if(le(t))throw t;return k(e.module,`Failed to ${e.label}: ${I(t)}`),e.fallback}}function mm(e){if(e instanceof Oe)return"CONFIGURATION";if(e instanceof j)return"VALIDATION";if(e instanceof Dr||e instanceof Xt)return"CONCURRENCY";let t=je(e);if(t===401)return"AUTH_REQUIRED";if(t===403){let n=I(e).toLowerCase();return n.includes("rate limit")||n.includes("abuse detection")?"RATE_LIMITED":"AUTH_REQUIRED"}if(t===404)return"NOT_FOUND";if(t===429)return"RATE_LIMITED";let r=I(e).toLowerCase();return r.includes("enotfound")||r.includes("econnrefused")||r.includes("econnreset")||r.includes("etimedout")||r.includes("fetch failed")?"NETWORK":r.includes("state")&&(r.includes("corrupt")||r.includes("invalid"))?"STATE_CORRUPTED":"UNKNOWN"}var Cr,Oe,lm,j,qi,gu,Dr,Xt,dm,Lr,BS,ee=A(()=>{"use strict";ae();Cr=class extends Error{constructor(r,n){super(r);this.code=n;this.name="OssAutopilotError"}code},Oe=class extends Cr{constructor(t){super(t,"CONFIGURATION_ERROR"),this.name="ConfigurationError"}},lm="OSS_AUTOPILOT_UNATTENDED";j=class extends Cr{constructor(t){super(t,"VALIDATION_ERROR"),this.name="ValidationError"}},qi=class extends Oe{constructor(t){super(t??'Your GitHub token does not have Gist permissions. Run `gh auth refresh -s gist` to add the required scope, or create a token with the "gist" scope.'),this.name="GistPermissionError"}},gu=class extends Oe{constructor(r,n,s){let o=s instanceof Error?s.message:String(s),i=n?`
63
+ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let i of e.seen.entries()){let a=i[1];if(t===i[0]){o(i);continue}if(e.external){let u=e.external.registry.get(i[0])?.id;if(t!==i[0]&&u){o(i);continue}}if(e.metadataRegistry.get(i[0])?.id){o(i);continue}if(a.cycle){o(i);continue}a.count>1&&e.reused==="ref"&&o(i)}e.external&&(e.sharedDefsExtractedFor=e.external)}function xP(e){let t=e.anyOf;if(!Array.isArray(t)||t.length===0||e.type!==void 0)return;let r=[];for(let n of t){if(!n||typeof n!="object")return;xP(n);let s=Object.keys(n);if(s.length!==1||s[0]!=="type")return;let o=n.type;for(let i of Array.isArray(o)?o:[o]){if(typeof i!="string")return;r.includes(i)||r.push(i)}}delete e.anyOf,e.type=r.length===1?r[0]:r}function IP(e){let t=e.additionalProperties;return t===void 0||t===!1||typeof t!="object"||t===null?null:Object.keys(t).length?t:null}function Tw(e){let t=[];for(let o of e){if(typeof o!="object"||o.type!=="object")return null;for(let i in o)if(!DP.has(i))return null;t.push(o)}let r={},n=new Set;for(let o of t){for(let i in o.properties){if(Object.prototype.hasOwnProperty.call(r,i))continue;let a=[];for(let u of t){let d=u.properties?.[i]??IP(u);d!=null&&(a.some(p=>JSON.stringify(p)===JSON.stringify(d))||a.push(d))}let c=a.length===1?a[0]:Tw(a)??{allOf:a};vt(r,i,c)}for(let i of o.required??[])n.add(i)}let s={type:"object",properties:r};if(n.size&&(s.required=[...n]),t.every(o=>o.additionalProperties===!1))s.additionalProperties=!1;else{let o=[];for(let i of t){let a=IP(i);a&&!o.some(c=>JSON.stringify(c)===JSON.stringify(a))&&o.push(a)}o.length===1?s.additionalProperties=o[0]:o.length>1&&(s.additionalProperties={allOf:o})}return s}function tj(e){let t=e.allOf;if(!Array.isArray(t)||t.length<2)return;for(let s of DP)if(s in e)return;let r=t.filter(s=>OP.some(o=>Array.isArray(s[o]))),n=null;if(!r.length)n=Tw(t);else{let s=r[0],o=OP.find(c=>Array.isArray(s[c]));if(Object.keys(s).length!==1)return;let i=t.filter(c=>c!==s),a=s[o].map(c=>Tw([...i,c]));if(a.some(c=>!c))return;n={[o]:a}}n&&(delete e.allOf,Vc(e,n))}function Xn(e,t){let r=e.seen.get(t);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");let n=a=>{let c=e.seen.get(a);if(c.ref===null)return;let u=c.def??c.schema,d={...u},p=c.ref;if(c.ref=null,p){n(p);let f=e.seen.get(p),g=f.schema;if(g.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0")?(u.allOf=u.allOf??[],u.allOf.push(g)):Vc(u,g),Vc(u,d),a._zod.parent===p)for(let b in u)b==="$ref"||b==="allOf"||b in d||delete u[b];if(g.$ref&&f.def)for(let b in u)b==="$ref"||b==="allOf"||b in f.def&&JSON.stringify(u[b])===JSON.stringify(f.def[b])&&delete u[b]}let m=a._zod.parent;if(m&&m!==p){n(m);let f=e.seen.get(m);if(f?.schema.$ref&&(u.$ref=f.schema.$ref,f.def))for(let g in u)g==="$ref"||g==="allOf"||g in f.def&&JSON.stringify(u[g])===JSON.stringify(f.def[g])&&delete u[g]}e.override({zodSchema:a,jsonSchema:u,path:c.path??[]})};if(!e.external||e.sharedEmitDoneFor!==e.external){for(let a of[...e.seen.entries()].reverse())n(a[0]);if(e.target!=="openapi-3.0")for(let a of e.seen.entries())xP(a[1].def??a[1].schema);for(let a of e.deferred)a();if(e.intersections.length){let a=new Map;for(let c of e.seen.values())for(let u of[c.schema,c.def]){let d=u?.allOf;if(!Array.isArray(d))continue;let p=a.get(d);p?p.push(u):a.set(d,[u])}for(let c of e.intersections)for(let u of a.get(c)??[])tj(u)}}let s={};if(e.target==="draft-2020-12"?s.$schema="https://json-schema.org/draft/2020-12/schema":e.target==="draft-07"?s.$schema="http://json-schema.org/draft-07/schema#":e.target==="draft-04"?s.$schema="http://json-schema.org/draft-04/schema#":e.target,e.external?.uri){let a=e.external.registry.get(t)?.id;if(!a)throw new Error("Schema is missing an `id` property");s.$id=e.external.uri(a)}Vc(s,r.defId?r.schema:r.def??r.schema);let o=e.metadataRegistry.get(t)?.id;o!==void 0&&s.id===o&&delete s.id;let i=e.external?.defs??{};if(!e.external||e.sharedEmitDoneFor!==e.external)for(let a of e.seen.entries()){let c=a[1];c.def&&c.defId&&(c.def.id===c.defId&&delete c.def.id,vt(i,c.defId,c.def))}e.external&&(e.sharedEmitDoneFor=e.external),e.external||Object.keys(i).length>0&&(e.target==="draft-2020-12"?s.$defs=i:s.definitions=i);try{let a=JSON.parse(JSON.stringify(s));return Object.defineProperty(a,"~standard",{value:{...t["~standard"],jsonSchema:{input:Oi(t,"input",e.processors),output:Oi(t,"output",e.processors)}},enumerable:!1,writable:!1}),a}catch{throw new Error("Error converting schema to JSON.")}}function Ft(e,t){let r=t??{seen:new Set};if(r.seen.has(e))return!1;r.seen.add(e);let n=e._zod.def;if(n.type==="transform")return!0;if(n.type==="array")return Ft(n.element,r);if(n.type==="set")return Ft(n.valueType,r);if(n.type==="lazy")return Ft(n.getter(),r);if(n.type==="promise"||n.type==="optional"||n.type==="nonoptional"||n.type==="nullable"||n.type==="readonly"||n.type==="default"||n.type==="prefault"||n.type==="catch")return Ft(n.innerType,r);if(n.type==="intersection")return Ft(n.left,r)||Ft(n.right,r);if(n.type==="record"||n.type==="map")return Ft(n.keyType,r)||Ft(n.valueType,r);if(n.type==="pipe")return e._zod.traits.has("$ZodCodec")?!0:Ft(n.in,r)||Ft(n.out,r);if(n.type==="object"){for(let s in n.shape)if(Ft(n.shape[s],r))return!0;return!1}if(n.type==="union"){for(let s of n.options)if(Ft(s,r))return!0;return!1}if(n.type==="tuple"){for(let s of n.items)if(Ft(s,r))return!0;return!!(n.rest&&Ft(n.rest,r))}return!1}var DP,OP,$w,Oi,qc=A(()=>{Uc();nt();DP=new Set(["type","properties","required","additionalProperties"]),OP=["oneOf","anyOf"];$w=(e,t={})=>r=>{let n=Yn({...r,processors:t});return De(e,n),Qn(n,e),Xn(n,e)},Oi=(e,t,r={})=>n=>{let{libraryOptions:s,target:o}=n??{},i=Yn({...s??{},target:o,io:t,processors:r});return De(e,i),Qn(i,e),Xn(i,e)}});function mt(e){let t={},r=e._zod.def,n=e._zod.traits.has("$ZodCheck")?[e,...r.checks??[]]:r.checks??[];for(let o of n)rj[o._zod.def.check]?.(t,o._zod.def);let s=e._zod.bag;s.minimum!==void 0&&Ii(t,"minimum",s.minimum),s.exclusiveMinimum!==void 0&&Ii(t,"exclusiveMinimum",s.exclusiveMinimum),s.maximum!==void 0&&xi(t,"maximum",s.maximum),s.exclusiveMaximum!==void 0&&xi(t,"exclusiveMaximum",s.exclusiveMaximum),s.multipleOf!==void 0&&GP(t,s.multipleOf),s.format!==void 0&&(t.format??(t.format=s.format),s.format.includes("int")&&(t.isInt=!0)),s.mime&&jP(t,s.mime);for(let o of s.patterns??[])UP(t,o);return t}function Zc(e){let t=e._zod.def;return t.type==="pipe"&&t.in._zod.traits.has("$ZodTransform")?Zc(t.out):t.type==="catch"?Zc(t.innerType):e._zod.optin}function Ow(e,t,r){if(t.$ref){if(r.has(t))return t;r.add(t);let g=e.get(t)?.def;if(!g)return t;let y=Ow(e,g,r);return y===g?t:y}for(let g of["anyOf","oneOf"]){let y=t[g];if(!Array.isArray(y))continue;let b=y.map(R=>Ow(e,R,r));b.some((R,h)=>R!==y[h])&&(t={...t,[g]:b})}let n=Array.isArray(t.type)?t.type:[t.type],s=!n.includes("string")&&n.some(g=>g==="number"||g==="integer"),o=t.enum??(t.const!==void 0?[t.const]:void 0);if(!s&&!o?.some(g=>typeof g=="number"))return t;let{minimum:i,maximum:a,exclusiveMinimum:c,exclusiveMaximum:u,multipleOf:d,format:p,id:m,...f}=t;return f.enum?f.enum=f.enum.map(g=>typeof g=="number"?String(g):g):typeof f.const=="number"&&(f.const=String(f.const)),s&&(f.type="string",o||(f.pattern=(n.includes("number")?hn:kc).source)),f}function oj(e){let t=new Map;for(let n of e.seen.values())n.def&&!t.has(n.schema)&&t.set(n.schema,n);let r=new Map;for(let n of Iw.get(e)??[]){let s=e.seen.get(n),o=(s?.def??s?.schema)?.propertyNames;if(!o||o===!0||r.has(o))continue;let i=Ow(t,o,new Set);i!==o&&r.set(o,i)}if(r.size)for(let n of e.seen.values())for(let s of[n.schema,n.def]){let o=s&&r.get(s.propertyNames);o&&(s.propertyNames=o)}}function HP(e,t,r,n,s){let o=!1,i=JSON.stringify(e,(a,c)=>typeof c!="bigint"?c:(o=!0,null));return o?(pt(t,r,n,s,"BigInt defaults cannot be represented in JSON Schema"),uR):JSON.parse(i)}function yp(e,t){if("_idmap"in e){let n=e,s=Yn({...t,processors:fp}),o={};for(let c of n._idmap.entries()){let[u,d]=c;De(d,s)}let i={},a={registry:n,uri:t?.uri,defs:o};s.external=a;for(let c of n._idmap.entries()){let[u,d]=c;Qn(s,d),vt(i,u,Xn(s,d))}if(Object.keys(o).length>0){let c=s.target==="draft-2020-12"?"$defs":"definitions";i.__shared={[c]:o}}return{schemas:i}}let r=Yn({...t,processors:fp});return De(e,r),Qn(r,e),Xn(r,e)}var Ii,xi,LP,GP,UP,jP,zP,MP,FP,NP,rj,nj,sj,BP,xw,Dw,Lw,Mw,Fw,Nw,Gw,Uw,jw,zw,Bw,Hw,Ww,Vw,qw,Zw,Kw,Jw,Yw,Qw,Xw,eR,tR,rR,nR,gp,sR,oR,Iw,iR,aR,cR,uR,lR,dR,pR,mR,fR,gR,hp,hR,fp,Kc=A(()=>{Ns();gi();qc();nt();Ii=(e,t,r)=>{(e[t]===void 0||r>e[t])&&(e[t]=r)},xi=(e,t,r)=>{(e[t]===void 0||r<e[t])&&(e[t]=r)},LP=(e,t)=>{Ii(e,"minimum",t),xi(e,"maximum",t)},GP=(e,t)=>{e.multipleOf??(e.multipleOf=[]),e.multipleOf.includes(t)||e.multipleOf.push(t)},UP=(e,t)=>{e.patterns??(e.patterns=new Set),e.patterns.add(t)},jP=(e,t)=>{e.mime=e.mime?e.mime.filter(r=>t.includes(r)):[...t]},zP=(e,t)=>{e.format=t,t.includes("int")&&(e.isInt=!0)},MP=(e,t)=>Ii(e,"minimum",t.minimum),FP=(e,t)=>xi(e,"maximum",t.maximum),NP=e=>(t,r)=>{zP(t,r.format);let[n,s]=e[r.format];Ii(t,"minimum",n),xi(t,"maximum",s)},rj={greater_than:(e,t)=>Ii(e,t.inclusive?"minimum":"exclusiveMinimum",t.value),less_than:(e,t)=>xi(e,t.inclusive?"maximum":"exclusiveMaximum",t.value),multiple_of:(e,t)=>GP(e,t.value),number_format:NP(mc),bigint_format:NP(fc),min_length:MP,max_length:FP,length_equals:(e,t)=>LP(e,t.length),min_size:MP,max_size:FP,size_equals:(e,t)=>LP(e,t.size),string_format:(e,t)=>{zP(e,t.format),t.pattern&&UP(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)=>jP(e,t.mime)};nj={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},sj=new Map([[Rd,Ih],[Oc,xh]]),BP=e=>sj.get(e)??e,xw=(e,t,r,n)=>{let s=r;s.type="string";let{minimum:o,maximum:i,format:a,patterns:c,contentEncoding:u,laxFormat:d}=mt(e);if(typeof o=="number"&&(s.minLength=o),typeof i=="number"&&(s.maxLength=i),a&&(s.format=nj[a]??a,s.format===""&&delete s.format,(a==="time"||d)&&delete s.format),u&&(s.contentEncoding=u),c&&c.size>0){let p=[...c].map(BP);p.length===1?s.pattern=p[0].source:p.length>1&&(s.allOf=[...p.map(m=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:m.source}))])}},Dw=(e,t,r,n)=>{let s=r,{minimum:o,maximum:i,multipleOf:a,exclusiveMaximum:c,exclusiveMinimum:u,isInt:d}=mt(e);s.type=d?"integer":"number";let p=typeof u=="number"&&u>=(o??Number.NEGATIVE_INFINITY),m=typeof c=="number"&&c<=(i??Number.POSITIVE_INFINITY),f=t.target==="draft-04"||t.target==="openapi-3.0";if(p?f?(s.minimum=u,s.exclusiveMinimum=!0):s.exclusiveMinimum=u:typeof o=="number"&&(s.minimum=o),m?f?(s.maximum=c,s.exclusiveMaximum=!0):s.exclusiveMaximum=c:typeof i=="number"&&(s.maximum=i),a){let g=new Set;for(let R of a)Number.isFinite(R)&&R!==0?g.add(Math.abs(R)):pt(e,t,s,n,`A multipleOf divisor of ${R} cannot be represented in JSON Schema`);let[y,...b]=g;y!==void 0&&(s.multipleOf=y),b.length&&(s.allOf=[...s.allOf??[],...b.map(R=>({multipleOf:R}))])}},Lw=(e,t,r,n)=>{r.type="boolean"},Mw=(e,t,r,n)=>{pt(e,t,r,n,"BigInt cannot be represented in JSON Schema")},Fw=(e,t,r,n)=>{pt(e,t,r,n,"Symbols cannot be represented in JSON Schema")},Nw=(e,t,r,n)=>{t.target==="openapi-3.0"?(r.type="string",r.nullable=!0,r.enum=[null]):r.type="null"},Gw=(e,t,r,n)=>{pt(e,t,r,n,"Undefined cannot be represented in JSON Schema")},Uw=(e,t,r,n)=>{pt(e,t,r,n,"Void cannot be represented in JSON Schema")},jw=(e,t,r,n)=>{r.not={}},zw=(e,t,r,n)=>{},Bw=(e,t,r,n)=>{},Hw=(e,t,r,n)=>{pt(e,t,r,n,"Date cannot be represented in JSON Schema")},Ww=(e,t,r,n)=>{let s=e._zod.def,o=ni(s.entries);if(o.length===0){r.not={};return}o.every(i=>typeof i=="number")&&(r.type="number"),o.every(i=>typeof i=="string")&&(r.type="string"),r.enum=o},Vw=(e,t,r,n)=>{let s=e._zod.def;if(s.values.length===0){r.not={};return}let o=[];for(let i of s.values)if(i===void 0){if(pt(e,t,r,n,"Literal `undefined` cannot be represented in JSON Schema"))return}else if(typeof i=="bigint"){if(pt(e,t,r,n,"BigInt literals cannot be represented in JSON Schema"))return;o.push(Number(i))}else o.push(i);if(o.length!==0)if(o.length===1){let i=o[0];r.type=i===null?"null":typeof i,t.target==="draft-04"||t.target==="openapi-3.0"?r.enum=[i]:r.const=i}else o.every(i=>typeof i=="number")&&(r.type="number"),o.every(i=>typeof i=="string")&&(r.type="string"),o.every(i=>typeof i=="boolean")&&(r.type="boolean"),o.every(i=>i===null)&&(r.type="null"),r.enum=o},qw=(e,t,r,n)=>{pt(e,t,r,n,"NaN cannot be represented in JSON Schema")},Zw=(e,t,r,n)=>{let s=r,o=e._zod.pattern;if(!o)throw new Error("Pattern not found in template literal");s.type="string",s.pattern=o.source},Kw=(e,t,r,n)=>{let s=r;s.type="string",s.format="binary",s.contentEncoding="binary";let{minimum:o,maximum:i,mime:a}=mt(e);o!==void 0&&(s.minLength=o),i!==void 0&&(s.maxLength=i),a&&(a.length===0?s.not={}:a.length===1?s.contentMediaType=a[0]:s.anyOf=a.map(c=>({contentMediaType:c})))},Jw=(e,t,r,n)=>{r.type="boolean"},Yw=(e,t,r,n)=>{pt(e,t,r,n,"Custom types cannot be represented in JSON Schema")},Qw=(e,t,r,n)=>{pt(e,t,r,n,"Function types cannot be represented in JSON Schema")},Xw=(e,t,r,n)=>{pt(e,t,r,n,"Transforms cannot be represented in JSON Schema")},eR=(e,t,r,n)=>{pt(e,t,r,n,"Map cannot be represented in JSON Schema")},tR=(e,t,r,n)=>{pt(e,t,r,n,"Set cannot be represented in JSON Schema")},rR=(e,t,r,n)=>{let s=r,o=e._zod.def,{minimum:i,maximum:a}=mt(e);typeof i=="number"&&(s.minItems=i),typeof a=="number"&&(s.maxItems=a),s.type="array",s.items=De(o.element,t,{...n,path:[...n.path,"items"]})};nR=(e,t,r,n)=>{let s=r,o=e._zod.def,i=o.shape;if(Object.getOwnPropertySymbols(i).length&&pt(e,t,s,n,"Symbol keys cannot be represented in JSON Schema"))return;s.type="object",s.properties={};for(let u in i)vt(s.properties,u,De(i[u],t,{...n,path:[...n.path,"properties",u]}));let c=[];for(let u of Object.keys(i)){let d=o.shape[u];(t.io==="input"?Zc(d)===void 0:d._zod.optout===void 0)&&c.push(u)}c.length>0&&(s.required=c),o.catchall?._zod.def.type==="never"?s.additionalProperties=!1:o.catchall?o.catchall&&(s.additionalProperties=De(o.catchall,t,{...n,path:[...n.path,"additionalProperties"]})):t.io==="output"&&(s.additionalProperties=!1)},gp=(e,t,r,n)=>{let s=e._zod.def,o=s.inclusive===!1,i=s.options.map((a,c)=>De(a,t,{...n,path:[...n.path,o?"oneOf":"anyOf",c]}));o?r.oneOf=i:r.anyOf=i},sR=(e,t,r,n)=>{let s=e._zod.def,o=De(s.left,t,{...n,path:[...n.path,"allOf",0]}),i=De(s.right,t,{...n,path:[...n.path,"allOf",1]}),a=u=>"allOf"in u&&Object.keys(u).length===1,c=[...a(o)?o.allOf:[o],...a(i)?i.allOf:[i]];r.allOf=c,t.intersections.push(c)},oR=(e,t,r,n)=>{let s=r,o=e._zod.def;s.type="array";let i=t.target==="draft-2020-12"?"prefixItems":"items",a=t.target==="draft-2020-12"||t.target==="openapi-3.0"?"items":"additionalItems",c=o.items.map((y,b)=>De(y,t,{...n,path:[...n.path,i,b]})),u=o.rest?De(o.rest,t,{...n,path:[...n.path,a,...t.target==="openapi-3.0"?[o.items.length]:[]]}):null,d=o.items.length;for(;d>0;){let y=o.items[d-1];if(!(t.io==="input"?Zc(y)!==void 0:y._zod.optout==="optional"))break;d--}let p=o.items.length,m=!o.rest;t.target==="draft-2020-12"?(s.prefixItems=c,m?s.items=!1:u&&(s.items=u),d>0&&(s.minItems=d),m&&(s.maxItems=p)):t.target==="openapi-3.0"?(s.items={anyOf:c},u&&s.items.anyOf.push(u),d>0&&(s.minItems=d),m&&(s.maxItems=p)):(s.items=c,m?s.additionalItems=!1:u&&(s.additionalItems=u),d>0&&(s.minItems=d),m&&(s.maxItems=p));let{minimum:f,maximum:g}=mt(e);typeof f=="number"&&(s.minItems=f),typeof g=="number"&&(s.maxItems=g)};Iw=new WeakMap;iR=(e,t,r,n)=>{let s=r,o=e._zod.def;s.type="object";let i=o.keyType,a=mt(i).patterns;if(o.mode==="loose"&&a&&a.size>0){let d=De(o.valueType,t,{...n,path:[...n.path,"patternProperties","*"]});s.patternProperties={};for(let p of a)vt(s.patternProperties,BP(p).source,d)}else{if(t.target==="draft-07"||t.target==="draft-2020-12"){s.propertyNames=De(o.keyType,t,{...n,path:[...n.path,"propertyNames"]});let d=Iw.get(t);d||(d=[],Iw.set(t,d),t.deferred.push(()=>oj(t))),d.push(e)}s.additionalProperties=De(o.valueType,t,{...n,path:[...n.path,"additionalProperties"]})}let c=i._zod.values,u=t.io==="input"&&Zc(o.valueType)!==void 0;if(c&&!o.partial&&!u){let d=[...c].filter(p=>typeof p=="string"||typeof p=="number");d.length>0&&(s.required=d.map(String))}},aR=(e,t,r,n)=>{let s=e._zod.def,o=De(s.innerType,t,n),i=t.seen.get(e);t.target==="openapi-3.0"?(i.ref=s.innerType,r.nullable=!0):r.anyOf=[o,{type:"null"}]},cR=(e,t,r,n)=>{let s=e._zod.def;De(s.innerType,t,n);let o=t.seen.get(e);o.ref=s.innerType},uR=Symbol();lR=(e,t,r,n)=>{let s=e._zod.def;De(s.innerType,t,n);let o=t.seen.get(e);o.ref=s.innerType;let i=HP(s.defaultValue,e,t,r,n);i!==uR&&(r.default=i)},dR=(e,t,r,n)=>{let s=e._zod.def;De(s.innerType,t,n);let o=t.seen.get(e);if(o.ref=s.innerType,t.io!=="input")return;let i=HP(s.defaultValue,e,t,r,n);i!==uR&&(r._prefault=i)},pR=(e,t,r,n)=>{let s=e._zod.def;De(s.innerType,t,n);let o=t.seen.get(e);o.ref=s.innerType;let i;try{i=s.catchValue(void 0)}catch{pt(e,t,r,n,"Dynamic catch values are not supported in JSON Schema");return}r.default=i},mR=(e,t,r,n)=>{let s=e._zod.def,o=s.in._zod.traits.has("$ZodTransform"),i=t.io==="input"?o?s.out:s.in:s.out;De(i,t,n);let a=t.seen.get(e);a.ref=i},fR=(e,t,r,n)=>{let s=e._zod.def;De(s.innerType,t,n);let o=t.seen.get(e);o.ref=s.innerType,r.readOnly=!0},gR=(e,t,r,n)=>{let s=e._zod.def;De(s.innerType,t,n);let o=t.seen.get(e);o.ref=s.innerType},hp=(e,t,r,n)=>{let s=e._zod.def;De(s.innerType,t,n);let o=t.seen.get(e);o.ref=s.innerType},hR=(e,t,r,n)=>{let s=e._zod.innerType;De(s,t,n);let o=t.seen.get(e);o.ref=s},fp={string:xw,number:Dw,boolean:Lw,bigint:Mw,symbol:Fw,null:Nw,undefined:Gw,void:Uw,never:jw,any:zw,unknown:Bw,date:Hw,enum:Ww,literal:Vw,nan:qw,template_literal:Zw,file:Kw,success:Jw,custom:Yw,function:Qw,transform:Xw,map:eR,set:tR,array:rR,object:nR,union:gp,intersection:sR,tuple:oR,record:iR,nullable:aR,nonoptional:cR,default:lR,prefault:dR,catch:pR,pipe:mR,readonly:fR,promise:gR,optional:hp,lazy:hR}});var bp,WP=A(()=>{Kc();qc();bp=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=Yn({processors:fp,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 De(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,Qn(this.ctx,t);let n=Xn(this.ctx,t),{"~standard":s,...o}=n;return o}}});var VP={};var qP=A(()=>{});var bn={};re(bn,{$ZodAny:()=>eb,$ZodArray:()=>ib,$ZodAsyncError:()=>Kt,$ZodBase64:()=>zy,$ZodBase64URL:()=>By,$ZodBigInt:()=>Pd,$ZodBigIntFormat:()=>Jy,$ZodBoolean:()=>Ic,$ZodCIDRv4:()=>Uy,$ZodCIDRv6:()=>jy,$ZodCUID:()=>Ay,$ZodCUID2:()=>Ty,$ZodCatch:()=>Cb,$ZodCheck:()=>Ge,$ZodCheckBigIntFormat:()=>ey,$ZodCheckEndsWith:()=>py,$ZodCheckGreaterThan:()=>cd,$ZodCheckIncludes:()=>ly,$ZodCheckLengthEquals:()=>iy,$ZodCheckLessThan:()=>ad,$ZodCheckLowerCase:()=>cy,$ZodCheckMaxLength:()=>sy,$ZodCheckMaxSize:()=>ty,$ZodCheckMimeType:()=>gy,$ZodCheckMinLength:()=>oy,$ZodCheckMinSize:()=>ry,$ZodCheckMultipleOf:()=>Qh,$ZodCheckNumberFormat:()=>Xh,$ZodCheckOverwrite:()=>hy,$ZodCheckProperties:()=>fy,$ZodCheckProperty:()=>my,$ZodCheckRegex:()=>ay,$ZodCheckSizeEquals:()=>ny,$ZodCheckStartsWith:()=>dy,$ZodCheckStringFormat:()=>mi,$ZodCheckUpperCase:()=>uy,$ZodCodec:()=>Dc,$ZodCreditCard:()=>Wy,$ZodCustom:()=>Ib,$ZodCustomStringFormat:()=>Zy,$ZodCyclicError:()=>xd,$ZodDate:()=>sb,$ZodDefault:()=>Sb,$ZodDiscriminatedUnion:()=>lb,$ZodE164:()=>Hy,$ZodEmail:()=>_y,$ZodEmoji:()=>Py,$ZodEncodeError:()=>qn,$ZodEnum:()=>gb,$ZodError:()=>lh,$ZodExactOptional:()=>wb,$ZodFile:()=>yb,$ZodFunction:()=>$b,$ZodGUID:()=>Ry,$ZodIBAN:()=>Vy,$ZodIPv4:()=>Fy,$ZodIPv6:()=>Ny,$ZodISODate:()=>Dy,$ZodISODateTime:()=>xy,$ZodISODuration:()=>My,$ZodISOTime:()=>Ly,$ZodIntersection:()=>db,$ZodJWT:()=>qy,$ZodKSUID:()=>Iy,$ZodLazy:()=>Lc,$ZodLiteral:()=>hb,$ZodMAC:()=>Gy,$ZodMap:()=>mb,$ZodNaN:()=>Pb,$ZodNanoID:()=>Ey,$ZodNever:()=>rb,$ZodNonOptional:()=>vb,$ZodNull:()=>Xy,$ZodNullable:()=>Rb,$ZodNumber:()=>Cd,$ZodNumberFormat:()=>Ky,$ZodObject:()=>pP,$ZodObjectJIT:()=>ab,$ZodOptional:()=>Ad,$ZodPipe:()=>Td,$ZodPrefault:()=>_b,$ZodPreprocess:()=>Eb,$ZodPromise:()=>Ob,$ZodReadonly:()=>Ab,$ZodRealError:()=>Jt,$ZodRecord:()=>pb,$ZodRegistry:()=>Fd,$ZodSet:()=>fb,$ZodString:()=>Us,$ZodStringFormat:()=>xe,$ZodSuccess:()=>kb,$ZodSymbol:()=>Yy,$ZodTemplateLiteral:()=>Tb,$ZodTransform:()=>bb,$ZodTuple:()=>Ed,$ZodType:()=>de,$ZodULID:()=>$y,$ZodURL:()=>Cy,$ZodUUID:()=>Sy,$ZodUndefined:()=>Qy,$ZodUnion:()=>xc,$ZodUnknown:()=>tb,$ZodVoid:()=>nb,$ZodXID:()=>Oy,$ZodXor:()=>cb,$brand:()=>ah,$constructor:()=>$,$input:()=>Gb,$output:()=>Nb,Doc:()=>Gs,INVALID:()=>Mt,JSONSchema:()=>VP,JSONSchemaGenerator:()=>bp,NEVER:()=>ih,TimePrecision:()=>Yb,URL_BAD_FORMAT:()=>vy,URL_UNPARSEABLE:()=>Ec,ZodCompileAsyncError:()=>Or,ZodCompileUnsupportedError:()=>_e,_any:()=>fw,_array:()=>Sw,_base64:()=>op,_base64url:()=>ip,_bigint:()=>aw,_boolean:()=>ow,_catch:()=>KU,_check:()=>AP,_cidrv4:()=>np,_cidrv6:()=>sp,_coercedBigint:()=>cw,_coercedBoolean:()=>iw,_coercedDate:()=>ww,_coercedNumber:()=>Xb,_coercedString:()=>qb,_creditCard:()=>Kb,_cuid:()=>Jd,_cuid2:()=>Yd,_custom:()=>vw,_date:()=>bw,_decode:()=>Jl,_decodeAsync:()=>Ql,_default:()=>VU,_discriminatedUnion:()=>DU,_e164:()=>ap,_email:()=>zd,_emoji:()=>Zd,_encode:()=>Kl,_encodeAsync:()=>Yl,_endsWith:()=>vi,_enum:()=>UU,_file:()=>_w,_float32:()=>tw,_float64:()=>rw,_gt:()=>Hr,_gte:()=>cr,_guid:()=>Bd,_iban:()=>Jb,_includes:()=>Si,_int:()=>ew,_int32:()=>nw,_int64:()=>uw,_intersection:()=>LU,_ipv4:()=>tp,_ipv6:()=>rp,_isoDate:()=>Bc,_isoDateTime:()=>zc,_isoDuration:()=>Wc,_isoTime:()=>Hc,_jwt:()=>cp,_ksuid:()=>ep,_lazy:()=>XU,_length:()=>Vs,_literal:()=>zU,_lowercase:()=>wi,_lt:()=>Br,_lte:()=>ar,_mac:()=>Zb,_map:()=>NU,_max:()=>ar,_maxLength:()=>Ws,_maxSize:()=>Jn,_mime:()=>Ci,_min:()=>cr,_minLength:()=>yn,_minSize:()=>Wr,_multipleOf:()=>Kn,_nan:()=>Rw,_nanoid:()=>Kd,_nativeEnum:()=>jU,_negative:()=>lp,_never:()=>hw,_nonnegative:()=>pp,_nonoptional:()=>qU,_nonpositive:()=>dp,_normalize:()=>Pi,_null:()=>mw,_nullable:()=>WU,_number:()=>Qb,_optional:()=>HU,_overwrite:()=>Ir,_parse:()=>ui,_parseAsync:()=>li,_pipe:()=>JU,_positive:()=>up,_promise:()=>ej,_properties:()=>ki,_property:()=>mp,_readonly:()=>YU,_record:()=>FU,_refine:()=>kw,_regex:()=>bi,_safeDecode:()=>ed,_safeDecodeAsync:()=>rd,_safeEncode:()=>Xl,_safeEncodeAsync:()=>td,_safeParse:()=>di,_safeParseAsync:()=>pi,_set:()=>GU,_size:()=>Hs,_slugify:()=>$i,_startsWith:()=>_i,_string:()=>Vb,_stringFormat:()=>qs,_stringbool:()=>Aw,_success:()=>ZU,_superRefine:()=>Cw,_symbol:()=>dw,_templateLiteral:()=>QU,_toLowerCase:()=>Ai,_toUpperCase:()=>Ti,_transform:()=>BU,_trim:()=>Ei,_tuple:()=>MU,_uint32:()=>sw,_uint64:()=>lw,_ulid:()=>Qd,_undefined:()=>pw,_union:()=>IU,_unknown:()=>gw,_uppercase:()=>Ri,_url:()=>jc,_uuid:()=>Hd,_uuidv4:()=>Wd,_uuidv6:()=>Vd,_uuidv7:()=>qd,_void:()=>yw,_xid:()=>Xd,_xor:()=>xU,base64Charset:()=>Rd,base64urlCharset:()=>Oc,canParseURL:()=>ky,clone:()=>Ie,compile:()=>Bb,compileFn:()=>Ud,config:()=>Ye,createStandardJSONSchemaMethod:()=>Oi,createToJSONSchemaMethod:()=>$w,decode:()=>GN,decodeAsync:()=>jN,describe:()=>Pw,encode:()=>NN,encodeAsync:()=>UN,extractDefs:()=>Qn,finalize:()=>Xn,flattenError:()=>wc,formatError:()=>Rc,getDiscriminatedOption:()=>ub,globalConfig:()=>yt,globalRegistry:()=>kt,handleUnrepresentable:()=>pt,initializeContext:()=>Yn,isBackEdge:()=>Ld,isRecursiveSchema:()=>Dd,isValidBase64:()=>$c,isValidBase64URL:()=>Sd,isValidCIDRv6:()=>wd,isValidCreditCard:()=>_d,isValidIBAN:()=>vd,isValidIPv6:()=>Tc,isValidJWT:()=>kd,locales:()=>Gc,memoizer:()=>Nc,mergeValues:()=>fi,meta:()=>Ew,parse:()=>ql,parseAsync:()=>Zl,parseURLObject:()=>uP,prettifyError:()=>ph,process:()=>De,processSchema:()=>De,regexes:()=>vr,registry:()=>Nd,safeDecode:()=>BN,safeDecodeAsync:()=>WN,safeEncode:()=>zN,safeEncodeAsync:()=>HN,safeParse:()=>xN,safeParseAsync:()=>DN,standardProps:()=>gd,stripTabAndNewline:()=>Ac,toDotPath:()=>zC,toJSONSchema:()=>yp,toZod:()=>uc,treeifyError:()=>dh,urlHostnameOk:()=>yd,urlProtocolOk:()=>bd,util:()=>V,validate:()=>Sc,validateAsync:()=>_c,validateURL:()=>hd,version:()=>yy,withParser:()=>Gd});var ur=A(()=>{Vn();fh();mh();gi();Lb();ud();by();nt();nt();Ns();Fb();Uc();ld();EP();TP();qc();Kc();WP();qP()});var wp={};re(wp,{endsWith:()=>vi,gt:()=>Hr,gte:()=>cr,includes:()=>Si,length:()=>Vs,lowercase:()=>wi,lt:()=>Br,lte:()=>ar,maxLength:()=>Ws,maxSize:()=>Jn,mime:()=>Ci,minLength:()=>yn,minSize:()=>Wr,multipleOf:()=>Kn,negative:()=>lp,nonnegative:()=>pp,nonpositive:()=>dp,normalize:()=>Pi,overwrite:()=>Ir,positive:()=>up,properties:()=>ki,property:()=>mp,regex:()=>bi,size:()=>Hs,slugify:()=>$i,startsWith:()=>_i,toLowerCase:()=>Ai,toUpperCase:()=>Ti,trim:()=>Ei,uppercase:()=>Ri});var Rp=A(()=>{ur()});function Sp(e,t,r){Object.defineProperty(e,t,{configurable:!0,enumerable:!1,get(){let n=r(this);return Object.defineProperty(this,t,{value:n,configurable:!0,writable:!0}),n},set(n){Object.defineProperty(this,t,{value:n,configurable:!0,writable:!0})}})}var ZP,KP,aj,Yt,yR=A(()=>{ur();ur();nt();ZP=new WeakSet([Object.prototype,Error.prototype]);KP=(e,t)=>{lh.init(e,t),e.name="ZodError";let r=Object.getPrototypeOf(e);ZP.has(r)||(ZP.add(r),Sp(r,"format",n=>s=>Rc(n,s)),Sp(r,"flatten",n=>s=>wc(n,s)),Sp(r,"addIssue",n=>s=>{n.issues.push(s),n.message=JSON.stringify(n.issues,si,2)}),Sp(r,"addIssues",n=>s=>{n.issues.push(...s),n.message=JSON.stringify(n.issues,si,2)}),Object.defineProperty(r,"isEmpty",{configurable:!0,enumerable:!1,get(){return this.issues.length===0}}))},aj=$("ZodError",KP),Yt=$("ZodError",KP,void 0,{Parent:Error})});var bR,wR,RR,SR,_R,vR,kR,CR,PR,ER,AR,TR,$R=A(()=>{ur();yR();ur();bR=ui(Yt),wR=li(Yt),RR=di(Yt),SR=pi(Yt),_R=Kl(Yt),vR=Jl(Yt),kR=Yl(Yt),CR=Ql(Yt),PR=Xl(Yt),ER=ed(Yt),AR=td(Yt),TR=rd(Yt)});var ji={};re(ji,{ZodAny:()=>UR,ZodArray:()=>HR,ZodBase64:()=>Np,ZodBase64URL:()=>Gp,ZodBigInt:()=>Gi,ZodBigIntFormat:()=>zp,ZodBoolean:()=>Ni,ZodCIDRv4:()=>Mp,ZodCIDRv6:()=>Fp,ZodCUID:()=>Tp,ZodCUID2:()=>$p,ZodCatch:()=>dS,ZodCodec:()=>ou,ZodCreditCard:()=>IR,ZodCustom:()=>iu,ZodCustomStringFormat:()=>Ys,ZodDate:()=>Xc,ZodDefault:()=>oS,ZodDiscriminatedUnion:()=>VR,ZodE164:()=>Up,ZodEmail:()=>Cp,ZodEmoji:()=>Ep,ZodEnum:()=>Li,ZodExactOptional:()=>Vp,ZodFile:()=>tS,ZodFunction:()=>SS,ZodGUID:()=>Pp,ZodIBAN:()=>xR,ZodIPv4:()=>Dp,ZodIPv6:()=>Lp,ZodISODate:()=>ts,ZodISODateTime:()=>es,ZodISODuration:()=>ns,ZodISOTime:()=>rs,ZodInstanceOf:()=>kS,ZodIntersection:()=>qR,ZodJWT:()=>jp,ZodKSUID:()=>xp,ZodLazy:()=>bS,ZodLiteral:()=>eS,ZodMAC:()=>OR,ZodMap:()=>QR,ZodNaN:()=>mS,ZodNanoID:()=>Ap,ZodNever:()=>zR,ZodNonOptional:()=>qp,ZodNull:()=>NR,ZodNullable:()=>sS,ZodNumber:()=>Fi,ZodNumberFormat:()=>Qs,ZodObject:()=>tu,ZodOptional:()=>nu,ZodPipe:()=>su,ZodPrefault:()=>aS,ZodPreprocess:()=>fS,ZodPromise:()=>RS,ZodReadonly:()=>gS,ZodRecord:()=>Di,ZodSet:()=>XR,ZodString:()=>Mi,ZodStringFormat:()=>Me,ZodSuccess:()=>lS,ZodSymbol:()=>MR,ZodTemplateLiteral:()=>yS,ZodTransform:()=>rS,ZodTuple:()=>KR,ZodType:()=>ye,ZodULID:()=>Op,ZodURL:()=>Qc,ZodUUID:()=>Vr,ZodUndefined:()=>FR,ZodUnion:()=>ru,ZodUnknown:()=>jR,ZodVoid:()=>BR,ZodXID:()=>Ip,ZodXor:()=>WR,_ZodString:()=>kp,_default:()=>iS,_function:()=>oA,any:()=>ME,array:()=>eu,base64:()=>hE,base64url:()=>yE,bigint:()=>OE,boolean:()=>LR,catch:()=>pS,check:()=>iA,cidrv4:()=>fE,cidrv6:()=>gE,codec:()=>tA,creditCard:()=>wE,cuid:()=>iE,cuid2:()=>aE,currencyCode:()=>CE,custom:()=>aA,date:()=>NE,describe:()=>cA,discriminatedUnion:()=>HE,e164:()=>bE,email:()=>JP,emoji:()=>sE,enum:()=>Hp,exactOptional:()=>nS,file:()=>YE,float32:()=>EE,float64:()=>AE,function:()=>oA,guid:()=>YP,hash:()=>PE,hex:()=>kE,hostname:()=>vE,httpUrl:()=>nE,iban:()=>RE,instanceof:()=>lA,int:()=>_p,int32:()=>TE,int64:()=>IE,intersection:()=>ZR,invertCodec:()=>rA,ipv4:()=>dE,ipv6:()=>mE,json:()=>pA,jwt:()=>SE,keyof:()=>GE,ksuid:()=>lE,lazy:()=>wS,literal:()=>JE,looseObject:()=>zE,looseRecord:()=>VE,mac:()=>pE,map:()=>qE,meta:()=>uA,nan:()=>eA,nanoid:()=>oE,nativeEnum:()=>KE,never:()=>Bp,nonoptional:()=>uS,null:()=>GR,nullable:()=>Yc,nullish:()=>QE,number:()=>DR,object:()=>UE,optional:()=>Ks,partialRecord:()=>WE,pipe:()=>vp,prefault:()=>cS,preprocess:()=>mA,promise:()=>sA,readonly:()=>hS,record:()=>YR,refine:()=>_S,set:()=>ZE,strictObject:()=>jE,string:()=>Jc,stringFormat:()=>_E,stringbool:()=>dA,success:()=>XE,superRefine:()=>vS,symbol:()=>DE,templateLiteral:()=>nA,transform:()=>Wp,tuple:()=>JR,uint32:()=>$E,uint64:()=>xE,ulid:()=>cE,undefined:()=>LE,union:()=>Ui,unknown:()=>Zs,url:()=>rE,uuid:()=>QP,uuidv4:()=>XP,uuidv6:()=>eE,uuidv7:()=>tE,void:()=>FE,xid:()=>uE,xor:()=>BE});function uj(){yt.localeError||Ye(Md())}function Js(){yt.memoizer||Ye({memoizer:Nc()})}function Jc(e){return Vb(Mi,e)}function JP(e){return zd(Cp,e)}function YP(e){return Bd(Pp,e)}function QP(e){return Hd(Vr,e)}function XP(e){return Wd(Vr,e)}function eE(e){return Vd(Vr,e)}function tE(e){return qd(Vr,e)}function rE(e){return jc(Qc,e)}function nE(e){return jc(Qc,{protocol:vc,hostname:Lh,...V.normalizeParams(e)})}function sE(e){return Zd(Ep,e)}function oE(e){return Kd(Ap,e)}function iE(e){return Jd(Tp,e)}function aE(e){return Yd($p,e)}function cE(e){return Qd(Op,e)}function uE(e){return Xd(Ip,e)}function lE(e){return ep(xp,e)}function dE(e){return tp(Dp,e)}function pE(e){return Zb(OR,e)}function mE(e){return rp(Lp,e)}function fE(e){return np(Mp,e)}function gE(e){return sp(Fp,e)}function hE(e){return op(Np,e)}function yE(e){return ip(Gp,e)}function bE(e){return ap(Up,e)}function wE(e){return Kb(IR,e)}function RE(e){return Jb(xR,e)}function SE(e){return cp(jp,e)}function _E(e,t,r={}){return qs(Ys,e,t,r)}function vE(e){return qs(Ys,"hostname",Dh,e)}function kE(e){return qs(Ys,"hex",Kh,e)}function CE(e){return qs(Ys,"currency_code",Fh,e)}function PE(e,t){let r=t?.enc??"hex",n=`${e}_${r}`,s=vr[n];if(!s)throw new Error(`Unrecognized hash format: ${n}`);return qs(Ys,n,s,t)}function DR(e){return Qb(Fi,e)}function _p(e){return ew(Qs,e)}function EE(e){return tw(Qs,e)}function AE(e){return rw(Qs,e)}function TE(e){return nw(Qs,e)}function $E(e){return sw(Qs,e)}function LR(e){return ow(Ni,e)}function OE(e){return aw(Gi,e)}function IE(e){return uw(zp,e)}function xE(e){return lw(zp,e)}function DE(e){return dw(MR,e)}function LE(e){return pw(FR,e)}function GR(e){return mw(NR,e)}function ME(){return fw(UR)}function Zs(){return gw(jR)}function Bp(e){return hw(zR,e)}function FE(e){return yw(BR,e)}function NE(e){return bw(Xc,e)}function eu(e,t){return Sw(HR,e,t)}function GE(e){let t=e._zod.def.shape;return Hp(Object.keys(t))}function UE(e,t){let r={type:"object",shape:e??{},...V.normalizeParams(t)};return new tu(r)}function jE(e,t){return new tu({type:"object",shape:e,catchall:Bp(),...V.normalizeParams(t)})}function zE(e,t){return new tu({type:"object",shape:e,catchall:Zs(),...V.normalizeParams(t)})}function Ui(e,t){return new ru({type:"union",options:e,...V.normalizeParams(t)})}function BE(e,t){return new WR({type:"union",options:e,inclusive:!1,...V.normalizeParams(t)})}function HE(e,t,r){return new VR({type:"union",options:t,discriminator:e,...V.normalizeParams(r)})}function ZR(e,t){return new qR({type:"intersection",left:e,right:t})}function JR(e,t,r){let n=t instanceof de,s=n?r:t,o=n?t:null;return new KR({type:"tuple",items:e,rest:o,...V.normalizeParams(s)})}function YR(e,t,r){return!t||!t._zod?new Di({type:"record",keyType:Jc(),valueType:e,...V.normalizeParams(t)}):new Di({type:"record",keyType:e,valueType:t,...V.normalizeParams(r)})}function WE(e,t,r){return new Di({type:"record",keyType:e,valueType:t,...V.normalizeParams(r),partial:!0})}function VE(e,t,r){return new Di({type:"record",keyType:e,valueType:t,mode:"loose",...V.normalizeParams(r)})}function qE(e,t,r){return new QR({type:"map",keyType:e,valueType:t,...V.normalizeParams(r)})}function ZE(e,t){return new XR({type:"set",valueType:e,...V.normalizeParams(t)})}function Hp(e,t){let r=Array.isArray(e)?Object.fromEntries(e.map(n=>[n,n])):e;return new Li({type:"enum",entries:r,...V.normalizeParams(t)})}function KE(e,t){return new Li({type:"enum",entries:e,...V.normalizeParams(t)})}function JE(e,t){return new eS({type:"literal",values:Array.isArray(e)?e:[e],...V.normalizeParams(t)})}function YE(e){return _w(tS,e)}function Wp(e){return new rS({type:"transform",transform:e})}function Ks(e){return new nu({type:"optional",innerType:e})}function nS(e){return new Vp({type:"optional",innerType:e})}function Yc(e){return new sS({type:"nullable",innerType:e})}function QE(e){return Ks(Yc(e))}function iS(e,t){return new oS({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():V.shallowClone(t)}})}function cS(e,t){return new aS({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():V.shallowClone(t)}})}function uS(e,t){return new qp({type:"nonoptional",innerType:e,...V.normalizeParams(t)})}function XE(e){return new lS({type:"success",innerType:e})}function pS(e,t){return new dS({type:"catch",innerType:e,catchValue:typeof t=="function"?t:V.constantCatch(t)})}function eA(e){return Rw(mS,e)}function vp(e,t){return new su({type:"pipe",in:e,out:t})}function tA(e,t,r){return new ou({type:"pipe",in:e,out:t,transform:r.decode,reverseTransform:r.encode})}function rA(e){let t=e._zod.def;return new ou({type:"pipe",in:t.out,out:t.in,transform:t.reverseTransform,reverseTransform:t.transform})}function hS(e){return new gS({type:"readonly",innerType:e})}function nA(e,t){return new yS({type:"template_literal",parts:e,...V.normalizeParams(t)})}function wS(e){return new bS({type:"lazy",getter:e})}function sA(e){return new RS({type:"promise",innerType:e})}function oA(e){return new SS({type:"function",input:Array.isArray(e?.input)?JR(e?.input):e?.input??eu(Zs()),output:e?.output??Zs()})}function iA(e){let t=new Ge({check:"custom"});return t._zod.check=e,t}function aA(e,t){return vw(iu,e??(()=>!0),t)}function _S(e,t={}){return kw(iu,e,t)}function vS(e,t){return Cw(e,t)}function lA(e,t={}){let r=new kS({type:"custom",check:"custom",fn:n=>n instanceof e,abort:!0,...V.normalizeParams(t)});return r._zod.bag.Class=e,r._zod.check=n=>{n.value instanceof e||n.issues.push({code:"invalid_type",expected:e.name,input:n.value,inst:r,path:[...r._zod.def.path??[]]})},r}function pA(e){let t=wS(()=>Ui([Jc(e),DR(),LR(),GR(),eu(t),YR(Jc(),t)]));return t}function mA(e,t){return new fS({type:"pipe",in:Wp(e),out:t})}var ye,kp,Mi,Me,es,ts,rs,ns,Cp,Pp,Vr,Qc,Ep,Ap,Tp,$p,Op,Ip,xp,Dp,OR,Lp,Mp,Fp,Np,Gp,Up,IR,xR,jp,Ys,Fi,Qs,Ni,Gi,zp,MR,FR,NR,UR,jR,zR,BR,Xc,HR,tu,ru,WR,VR,qR,KR,Di,QR,XR,Li,eS,tS,rS,nu,Vp,sS,oS,aS,qp,lS,dS,mS,su,ou,fS,gS,yS,bS,RS,SS,iu,cA,uA,kS,dA,ss=A(()=>{ur();ur();Kc();Ns();qc();Mb();Rp();$R();ye=$("ZodType",(e,t)=>(uj(),de.init(e,t),e.def=t,e.type=t.type,e),{check(...e){let t=this.def;return this.clone(V.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 Ie(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},refine(e,t){return this.check(_S(e,t))},superRefine(e,t){return this.check(vS(e,t))},overwrite(e){return this.check(Ir(e))},optional(){return Ks(this)},exactOptional(){return nS(this)},nullable(){return Yc(this)},nullish(){return Ks(Yc(this))},nonoptional(e){return uS(this,e)},array(){return eu(this)},or(e){return Ui([this,e])},and(e){return ZR(this,e)},transform(e){return vp(this,Wp(e))},default(e){return iS(this,e)},prefault(e){return cS(this,e)},catch(e){return pS(this,e)},pipe(e){return vp(this,e)},readonly(){return hS(this)},describe(e){let t=this.clone();return kt.add(t,{description:e}),t},meta(...e){if(e.length===0)return kt.get(this);let t=this.clone();return kt.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 V.hide(this,"~standard",{...gd(this),jsonSchema:{input:Oi(this,"input"),output:Oi(this,"output")}})},set"~standard"(e){V.own(this,"~standard",e)},parse:function e(t,r){return bR(this,t,r,{callee:e})},parseAsync:async function e(t,r){return await wR(this,t,r,{callee:e})},safeParse(e,t){return RR(this,e,t)},async safeParseAsync(e,t){return SR(this,e,t)},get spa(){return this?.safeParseAsync},set spa(e){V.own(this,"spa",e)},validate(e,t){return Sc(this,e,t)},validateAsync(e,t){return _c(this,e,t)},encode:function e(t,r){return _R(this,t,r,{callee:e})},decode:function e(t,r){return vR(this,t,r,{callee:e})},encodeAsync:async function e(t,r){return await kR(this,t,r,{callee:e})},decodeAsync:async function e(t,r){return await CR(this,t,r,{callee:e})},safeEncode(e,t){return PR(this,e,t)},safeDecode(e,t){return ER(this,e,t)},async safeEncodeAsync(e,t){return AR(this,e,t)},async safeDecodeAsync(e,t){return TR(this,e,t)},toJSONSchema(e){return $w(this,{})(e)},get description(){return kt.get(this)?.description},get _def(){return this._zod.def}}),kp=$("_ZodString",(e,t)=>{Us.init(e,t),ye.init(e,t),e._zod.processJSONSchema=(r,n,s)=>xw(e,r,n,s)},V.derived({format:e=>mt(e).format??null,minLength:e=>mt(e).minimum??null,maxLength:e=>mt(e).maximum??null},{regex(...e){return this.check(bi(...e))},includes(...e){return this.check(Si(...e))},startsWith(...e){return this.check(_i(...e))},endsWith(...e){return this.check(vi(...e))},min(...e){return this.check(yn(...e))},max(...e){return this.check(Ws(...e))},length(...e){return this.check(Vs(...e))},nonempty(...e){return this.check(yn(1,...e))},lowercase(e){return this.check(wi(e))},uppercase(e){return this.check(Ri(e))},trim(){return this.check(Ei())},normalize(...e){return this.check(Pi(...e))},toLowerCase(){return this.check(Ai())},toUpperCase(){return this.check(Ti())},slugify(){return this.check($i())}})),Mi=$("ZodString",(e,t)=>{Us.init(e,t),kp.init(e,t)},{email(e){return this.check(zd(Cp,e))},url(e){return this.check(jc(Qc,e))},jwt(e){return this.check(cp(jp,e))},emoji(e){return this.check(Zd(Ep,e))},guid(e){return this.check(Bd(Pp,e))},uuid(e){return this.check(Hd(Vr,e))},uuidv4(e){return this.check(Wd(Vr,e))},uuidv6(e){return this.check(Vd(Vr,e))},uuidv7(e){return this.check(qd(Vr,e))},nanoid(e){return this.check(Kd(Ap,e))},cuid(e){return this.check(Jd(Tp,e))},cuid2(e){return this.check(Yd($p,e))},ulid(e){return this.check(Qd(Op,e))},base64(e){return this.check(op(Np,e))},base64url(e){return this.check(ip(Gp,e))},xid(e){return this.check(Xd(Ip,e))},ksuid(e){return this.check(ep(xp,e))},ipv4(e){return this.check(tp(Dp,e))},ipv6(e){return this.check(rp(Lp,e))},cidrv4(e){return this.check(np(Mp,e))},cidrv6(e){return this.check(sp(Fp,e))},e164(e){return this.check(ap(Up,e))},datetime(e){return this.check(zc(es,e))},date(e){return this.check(Bc(ts,e))},time(e){return this.check(Hc(rs,e))},duration(e){return this.check(Wc(ns,e))}});Me=$("ZodStringFormat",(e,t)=>{xe.init(e,t),kp.init(e,t)}),es=$("ZodISODateTime",(e,t)=>{xy.init(e,t),Me.init(e,t)}),ts=$("ZodISODate",(e,t)=>{Dy.init(e,t),Me.init(e,t)}),rs=$("ZodISOTime",(e,t)=>{Ly.init(e,t),Me.init(e,t)}),ns=$("ZodISODuration",(e,t)=>{My.init(e,t),Me.init(e,t)}),Cp=$("ZodEmail",(e,t)=>{_y.init(e,t),Me.init(e,t)});Pp=$("ZodGUID",(e,t)=>{Ry.init(e,t),Me.init(e,t)});Vr=$("ZodUUID",(e,t)=>{Sy.init(e,t),Me.init(e,t)});Qc=$("ZodURL",(e,t)=>{Cy.init(e,t),Me.init(e,t)});Ep=$("ZodEmoji",(e,t)=>{Py.init(e,t),Me.init(e,t)});Ap=$("ZodNanoID",(e,t)=>{Ey.init(e,t),Me.init(e,t)});Tp=$("ZodCUID",(e,t)=>{Ay.init(e,t),Me.init(e,t)});$p=$("ZodCUID2",(e,t)=>{Ty.init(e,t),Me.init(e,t)});Op=$("ZodULID",(e,t)=>{$y.init(e,t),Me.init(e,t)});Ip=$("ZodXID",(e,t)=>{Oy.init(e,t),Me.init(e,t)});xp=$("ZodKSUID",(e,t)=>{Iy.init(e,t),Me.init(e,t)});Dp=$("ZodIPv4",(e,t)=>{Fy.init(e,t),Me.init(e,t)});OR=$("ZodMAC",(e,t)=>{Gy.init(e,t),Me.init(e,t)});Lp=$("ZodIPv6",(e,t)=>{Ny.init(e,t),Me.init(e,t)});Mp=$("ZodCIDRv4",(e,t)=>{Uy.init(e,t),Me.init(e,t)});Fp=$("ZodCIDRv6",(e,t)=>{jy.init(e,t),Me.init(e,t)});Np=$("ZodBase64",(e,t)=>{zy.init(e,t),Me.init(e,t)});Gp=$("ZodBase64URL",(e,t)=>{By.init(e,t),Me.init(e,t)});Up=$("ZodE164",(e,t)=>{Hy.init(e,t),Me.init(e,t)});IR=$("ZodCreditCard",(e,t)=>{Wy.init(e,t),Me.init(e,t)});xR=$("ZodIBAN",(e,t)=>{Vy.init(e,t),Me.init(e,t)});jp=$("ZodJWT",(e,t)=>{qy.init(e,t),Me.init(e,t)});Ys=$("ZodCustomStringFormat",(e,t)=>{Zy.init(e,t),Me.init(e,t)});Fi=$("ZodNumber",(e,t)=>{Cd.init(e,t),ye.init(e,t),e._zod.processJSONSchema=(r,n,s)=>Dw(e,r,n,s),e.isFinite=!0},V.derived({minValue:e=>{let{minimum:t,exclusiveMinimum:r}=mt(e);return Math.max(t??Number.NEGATIVE_INFINITY,r??Number.NEGATIVE_INFINITY)},maxValue:e=>{let{maximum:t,exclusiveMaximum:r}=mt(e);return Math.min(t??Number.POSITIVE_INFINITY,r??Number.POSITIVE_INFINITY)},isInt:e=>{let{isInt:t,multipleOf:r}=mt(e);return!!t||!!r?.some(Number.isSafeInteger)},format:e=>mt(e).format??null},{gt(e,t){return this.check(Hr(e,t))},gte(e,t){return this.check(cr(e,t))},min(e,t){return this.check(cr(e,t))},lt(e,t){return this.check(Br(e,t))},lte(e,t){return this.check(ar(e,t))},max(e,t){return this.check(ar(e,t))},int(e){return this.check(_p(e))},safe(e){return this.check(_p(e))},positive(e){return this.check(Hr(0,e))},nonnegative(e){return this.check(cr(0,e))},negative(e){return this.check(Br(0,e))},nonpositive(e){return this.check(ar(0,e))},multipleOf(e,t){return this.check(Kn(e,t))},step(e,t){return this.check(Kn(e,t))},finite(){return this}}));Qs=$("ZodNumberFormat",(e,t)=>{Ky.init(e,t),Fi.init(e,t)});Ni=$("ZodBoolean",(e,t)=>{Ic.init(e,t),ye.init(e,t),e._zod.processJSONSchema=(r,n,s)=>Lw(e,r,n,s)});Gi=$("ZodBigInt",(e,t)=>{Pd.init(e,t),ye.init(e,t),e._zod.processJSONSchema=(r,n,s)=>Mw(e,r,n,s)},V.derived({minValue:e=>mt(e).minimum??null,maxValue:e=>mt(e).maximum??null,format:e=>mt(e).format??null},{gte(e,t){return this.check(cr(e,t))},min(e,t){return this.check(cr(e,t))},gt(e,t){return this.check(Hr(e,t))},lt(e,t){return this.check(Br(e,t))},lte(e,t){return this.check(ar(e,t))},max(e,t){return this.check(ar(e,t))},positive(e){return this.check(Hr(BigInt(0),e))},negative(e){return this.check(Br(BigInt(0),e))},nonpositive(e){return this.check(ar(BigInt(0),e))},nonnegative(e){return this.check(cr(BigInt(0),e))},multipleOf(e,t){return this.check(Kn(e,t))}}));zp=$("ZodBigIntFormat",(e,t)=>{Jy.init(e,t),Gi.init(e,t)});MR=$("ZodSymbol",(e,t)=>{Yy.init(e,t),ye.init(e,t),e._zod.processJSONSchema=(r,n,s)=>Fw(e,r,n,s)});FR=$("ZodUndefined",(e,t)=>{Qy.init(e,t),ye.init(e,t),e._zod.processJSONSchema=(r,n,s)=>Gw(e,r,n,s)});NR=$("ZodNull",(e,t)=>{Xy.init(e,t),ye.init(e,t),e._zod.processJSONSchema=(r,n,s)=>Nw(e,r,n,s)});UR=$("ZodAny",(e,t)=>{eb.init(e,t),ye.init(e,t),e._zod.processJSONSchema=(r,n,s)=>zw(e,r,n,s)});jR=$("ZodUnknown",(e,t)=>{tb.init(e,t),ye.init(e,t),e._zod.processJSONSchema=(r,n,s)=>Bw(e,r,n,s)});zR=$("ZodNever",(e,t)=>{rb.init(e,t),ye.init(e,t),e._zod.processJSONSchema=(r,n,s)=>jw(e,r,n,s)});BR=$("ZodVoid",(e,t)=>{nb.init(e,t),ye.init(e,t),e._zod.processJSONSchema=(r,n,s)=>Uw(e,r,n,s)});Xc=$("ZodDate",(e,t)=>{sb.init(e,t),ye.init(e,t),e._zod.processJSONSchema=(r,n,s)=>Hw(e,r,n,s),e.min=(r,n)=>e.check(cr(r,n)),e.max=(r,n)=>e.check(ar(r,n))},V.derived({minDate:e=>{let{minimum:t}=mt(e);return t?new Date(t):null},maxDate:e=>{let{maximum:t}=mt(e);return t?new Date(t):null}},{}));HR=$("ZodArray",(e,t)=>{Js(),ib.init(e,t),ye.init(e,t),e._zod.processJSONSchema=(r,n,s)=>rR(e,r,n,s),e.element=t.element},{min(e,t){return this.check(yn(e,t))},nonempty(e){return this.check(yn(1,e))},max(e,t){return this.check(Ws(e,t))},length(e,t){return this.check(Vs(e,t))},unwrap(){return this.element}});tu=$("ZodObject",(e,t)=>{Js(),ab.init(e,t),ye.init(e,t),e._zod.processJSONSchema=(r,n,s)=>nR(e,r,n,s),V.installLazyProp(e,"shape",r=>r._zod.def.shape,!1)},{keyof(){return Hp(Object.keys(this._zod.def.shape))},catchall(e){return this.clone(V.mergeDefs(this._zod.def,{catchall:e}))},passthrough(){return this.clone(V.mergeDefs(this._zod.def,{catchall:Zs()}))},loose(){return this.clone(V.mergeDefs(this._zod.def,{catchall:Zs()}))},strict(){return this.clone(V.mergeDefs(this._zod.def,{catchall:Bp()}))},strip(){return this.clone(V.mergeDefs(this._zod.def,{catchall:void 0}))},extend(e){return V.extend(this,e)},safeExtend(e){return V.safeExtend(this,e)},merge(e){return V.merge(this,e)},pick(e){return V.pick(this,e)},omit(e){return V.omit(this,e)},partial(...e){return V.partial(nu,this,e[0])},exactPartial(...e){return V.partial(Vp,this,e[0],"exactPartial")},required(...e){return V.required(qp,this,e[0])}});ru=$("ZodUnion",(e,t)=>{xc.init(e,t),ye.init(e,t),e._zod.processJSONSchema=(r,n,s)=>gp(e,r,n,s),e.options=t.options});WR=$("ZodXor",(e,t)=>{ru.init(e,t),cb.init(e,t),e._zod.processJSONSchema=(r,n,s)=>gp(e,r,n,s),e.options=t.options});VR=$("ZodDiscriminatedUnion",(e,t)=>{ru.init(e,t),lb.init(e,t)});qR=$("ZodIntersection",(e,t)=>{db.init(e,t),ye.init(e,t),e._zod.processJSONSchema=(r,n,s)=>sR(e,r,n,s)});KR=$("ZodTuple",(e,t)=>{Js(),Ed.init(e,t),ye.init(e,t),e._zod.processJSONSchema=(r,n,s)=>oR(e,r,n,s)},{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 nu({type:"optional",innerType:t}))})}});Di=$("ZodRecord",(e,t)=>{Js(),pb.init(e,t),ye.init(e,t),e._zod.processJSONSchema=(r,n,s)=>iR(e,r,n,s),e.keyType=t.keyType,e.valueType=t.valueType});QR=$("ZodMap",(e,t)=>{Js(),mb.init(e,t),ye.init(e,t),e._zod.processJSONSchema=(r,n,s)=>eR(e,r,n,s),e.keyType=t.keyType,e.valueType=t.valueType,e.min=(...r)=>e.check(Wr(...r)),e.nonempty=r=>e.check(Wr(1,r)),e.max=(...r)=>e.check(Jn(...r)),e.size=(...r)=>e.check(Hs(...r))});XR=$("ZodSet",(e,t)=>{Js(),fb.init(e,t),ye.init(e,t),e._zod.processJSONSchema=(r,n,s)=>tR(e,r,n,s),e.min=(...r)=>e.check(Wr(...r)),e.nonempty=r=>e.check(Wr(1,r)),e.max=(...r)=>e.check(Jn(...r)),e.size=(...r)=>e.check(Hs(...r))});Li=$("ZodEnum",(e,t)=>{gb.init(e,t),ye.init(e,t),e._zod.processJSONSchema=(n,s,o)=>Ww(e,n,s,o),e.enum=t.entries,e.options=[...e._zod.values];let r=new Set(Object.keys(t.entries));e.extract=(n,s)=>{let o={};for(let i of n)if(r.has(i))o[i]=t.entries[i];else throw new Error(`Key ${i} not found in enum`);return new Li({...t,checks:[],...V.normalizeParams(s),entries:o})},e.exclude=(n,s)=>{let o={...t.entries};for(let i of n)if(r.has(i))delete o[i];else throw new Error(`Key ${i} not found in enum`);return new Li({...t,checks:[],...V.normalizeParams(s),entries:o})}});eS=$("ZodLiteral",(e,t)=>{hb.init(e,t),ye.init(e,t),e._zod.processJSONSchema=(r,n,s)=>Vw(e,r,n,s),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]}})});tS=$("ZodFile",(e,t)=>{yb.init(e,t),ye.init(e,t),e._zod.processJSONSchema=(r,n,s)=>Kw(e,r,n,s),e.min=(r,n)=>e.check(Wr(r,n)),e.max=(r,n)=>e.check(Jn(r,n)),e.mime=(r,n)=>e.check(Ci(Array.isArray(r)?r:[r],n))});rS=$("ZodTransform",(e,t)=>{Js(),bb.init(e,t),ye.init(e,t),e._zod.processJSONSchema=(r,n,s)=>Xw(e,r,n,s),e._zod.parse=(r,n)=>{if(n.direction==="backward")throw new qn(e.constructor.name);r.addIssue=o=>{if(typeof o=="string")r.issues.push(V.issue(o,r.value,t));else{let i=o;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),"input"in i||(i.input=r.value),i.inst??(i.inst=e),r.issues.push(V.issue(i))}};let s=t.transform(r.value,r);return s instanceof Promise?s.then(o=>(r.value=o,r)):(r.value=s,r)}});nu=$("ZodOptional",(e,t)=>{Ad.init(e,t),ye.init(e,t),e._zod.processJSONSchema=(r,n,s)=>hp(e,r,n,s),e.unwrap=()=>e._zod.def.innerType});Vp=$("ZodExactOptional",(e,t)=>{wb.init(e,t),ye.init(e,t),e._zod.processJSONSchema=(r,n,s)=>hp(e,r,n,s),e.unwrap=()=>e._zod.def.innerType});sS=$("ZodNullable",(e,t)=>{Rb.init(e,t),ye.init(e,t),e._zod.processJSONSchema=(r,n,s)=>aR(e,r,n,s),e.unwrap=()=>e._zod.def.innerType});oS=$("ZodDefault",(e,t)=>{Sb.init(e,t),ye.init(e,t),e._zod.processJSONSchema=(r,n,s)=>lR(e,r,n,s),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});aS=$("ZodPrefault",(e,t)=>{_b.init(e,t),ye.init(e,t),e._zod.processJSONSchema=(r,n,s)=>dR(e,r,n,s),e.unwrap=()=>e._zod.def.innerType});qp=$("ZodNonOptional",(e,t)=>{vb.init(e,t),ye.init(e,t),e._zod.processJSONSchema=(r,n,s)=>cR(e,r,n,s),e.unwrap=()=>e._zod.def.innerType});lS=$("ZodSuccess",(e,t)=>{kb.init(e,t),ye.init(e,t),e._zod.processJSONSchema=(r,n,s)=>Jw(e,r,n,s),e.unwrap=()=>e._zod.def.innerType});dS=$("ZodCatch",(e,t)=>{Cb.init(e,t),ye.init(e,t),e._zod.processJSONSchema=(r,n,s)=>pR(e,r,n,s),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});mS=$("ZodNaN",(e,t)=>{Pb.init(e,t),ye.init(e,t),e._zod.processJSONSchema=(r,n,s)=>qw(e,r,n,s)});su=$("ZodPipe",(e,t)=>{Td.init(e,t),ye.init(e,t),e._zod.processJSONSchema=(r,n,s)=>mR(e,r,n,s),e.in=t.in,e.out=t.out});ou=$("ZodCodec",(e,t)=>{su.init(e,t),Dc.init(e,t)});fS=$("ZodPreprocess",(e,t)=>{su.init(e,t),Eb.init(e,t)}),gS=$("ZodReadonly",(e,t)=>{Ab.init(e,t),ye.init(e,t),e._zod.processJSONSchema=(r,n,s)=>fR(e,r,n,s),e.unwrap=()=>e._zod.def.innerType});yS=$("ZodTemplateLiteral",(e,t)=>{Tb.init(e,t),ye.init(e,t),e._zod.processJSONSchema=(r,n,s)=>Zw(e,r,n,s)});bS=$("ZodLazy",(e,t)=>{Lc.init(e,t),ye.init(e,t),e._zod.processJSONSchema=(r,n,s)=>hR(e,r,n,s),e.unwrap=()=>e._zod.def.getter()});RS=$("ZodPromise",(e,t)=>{Ob.init(e,t),ye.init(e,t),e._zod.processJSONSchema=(r,n,s)=>gR(e,r,n,s),e.unwrap=()=>e._zod.def.innerType});SS=$("ZodFunction",(e,t)=>{$b.init(e,t),ye.init(e,t),e._zod.processJSONSchema=(r,n,s)=>Qw(e,r,n,s)});iu=$("ZodCustom",(e,t)=>{Ib.init(e,t),ye.init(e,t),e._zod.processJSONSchema=(r,n,s)=>Yw(e,r,n,s)});cA=Pw,uA=Ew,kS=$("ZodInstanceOf",(e,t)=>{iu.init(e,t)},{properties(e,t){return this.check(ki(e,t))}});dA=(...e)=>Aw({Codec:ou,Boolean:Ni,String:Mi},...e)});function dj(e){Ye({customError:e})}function pj(){return Ye().customError}var lj,CS,fA=A(()=>{ur();lj={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"};CS||(CS={})});var au={};re(au,{ZodISODate:()=>ts,ZodISODateTime:()=>es,ZodISODuration:()=>ns,ZodISOTime:()=>rs,date:()=>fj,datetime:()=>mj,duration:()=>hj,time:()=>gj});function mj(e){return zc(es,e)}function fj(e){return Bc(ts,e)}function gj(e){return Hc(rs,e)}function hj(e){return Wc(ns,e)}var Zp=A(()=>{ur();ss();ss()});function bj(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 gA(e,t){return e.map((r,n)=>n<t?r:r.optional())}function wj(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}function Rj(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 n=t.version==="draft-2020-12"?"$defs":"definitions";if(r[0]===n){let s=r[1]===void 0?void 0:wj(r[1]);if(!s||!t.defs[s])throw new Error(`Reference not found: ${e}`);return t.defs[s]}throw new Error(`Reference not found: ${e}`)}function Sj(e,t){return W.transform(n=>n).check(n=>{let s=n.value;if(typeof s!="object"||s===null||Array.isArray(s))return;let o=Object.getOwnPropertyNames(s);if(t.minProperties!==void 0&&o.length<t.minProperties&&n.issues.push({origin:"object",code:"too_small",minimum:t.minProperties,inclusive:!0,message:`Too small: expected object to have >=${t.minProperties} properties`,input:s,inst:e,continue:!0}),t.maxProperties!==void 0&&o.length>t.maxProperties&&n.issues.push({origin:"object",code:"too_big",maximum:t.maxProperties,inclusive:!0,message:`Too big: expected object to have <=${t.maxProperties} properties`,input:s,inst:e,continue:!0}),t.keySchema)for(let i of o){let a=t.keySchema.safeParse(i);a.success||n.issues.push({code:"invalid_key",origin:"record",issues:a.error.issues,input:i,path:[i],continue:!0})}}).pipe(e)}function PS(e,t){if(e===null)return"z";let r=typeof e;if(r!=="object"){if(r==="number"&&Number.isNaN(e))return null;let n=String(e);return`${r[0]}${n.length}:${n}`}if(t.has(e))return null;t.add(e);try{if(Array.isArray(e)){let o=[];for(let i of e){let a=PS(i,t);if(a===null)return null;o.push(a)}return`a${o.length}:[${o.join(",")}]`}let n=Object.keys(e).sort(),s=[];for(let o of n){let i=PS(e[o],t);if(i===null)return null;s.push(`${o.length}:${o}=${i}`)}return`o${s.length}:{${s.join(",")}}`}finally{t.delete(e)}}function cu(e){return typeof e!="object"||e===null?!1:Array.isArray(e)?e.some(cu):typeof e.$ref=="string"?!0:Object.entries(e).some(([t,r])=>_j.has(t)?cu(r):!vj.has(t)||typeof r!="object"||r===null?!1:Object.values(r).some(cu))}function hA(e){return e===1?"element":"elements"}function kj(e,t){return W.transform(n=>n).check(n=>{let s=n.value;if(Array.isArray(s)){if(t.uniqueItems===!0){let o=new Map;for(let i=0;i<s.length;i++){let a=PS(s[i],new Set);if(a===null)continue;let c=o.get(a);if(c===void 0){o.set(a,i);continue}n.issues.push({code:"custom",message:`Array items must be unique: element at index ${i} duplicates the one at index ${c}`,input:s,path:[i],continue:!0})}}if(t.containsSchema){let o=t.minContains??1,i=t.maxContains!==void 0?t.maxContains+1:Number.POSITIVE_INFINITY,a=0;for(let c of s)if(t.containsSchema.safeParse(c).success&&++a>=i)break;a<o&&n.issues.push({code:"custom",message:`Array must contain at least ${o} matching ${hA(o)}; found ${a}`,input:s,continue:!0}),t.maxContains!==void 0&&a>t.maxContains&&n.issues.push({code:"custom",message:`Array must contain at most ${t.maxContains} matching ${hA(t.maxContains)}`,input:s,continue:!0})}}}).pipe(e)}function yA(e,t){if(e!==!1)return e===void 0||e===!0?W.any():Nt(e,t)}function bA(e,t){if(e.not!==void 0){if(typeof e.not=="object"&&Object.keys(e.not).length===0)return W.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 s=e.$ref;if(t.refs.has(s))return t.refs.get(s);if(t.processing.has(s))return W.lazy(()=>{if(!t.refs.has(s))throw new Error(`Circular reference not resolved: ${s}`);return t.refs.get(s)});t.processing.add(s);let o=Rj(s,t),i=Nt(o,t);return t.refs.set(s,i),t.processing.delete(s),i}if(e.enum!==void 0){let s=e.enum;if(t.version==="openapi-3.0"&&e.nullable===!0&&s.length===1&&s[0]===null)return W.null();if(s.length===0)return W.never();if(s.length===1)return W.literal(s[0]);if(s.every(i=>typeof i=="string"))return W.enum(s);let o=s.map(i=>W.literal(i));return o.length<2?o[0]:W.union([o[0],o[1],...o.slice(2)])}if(e.const!==void 0)return W.literal(e.const);let r=e.type;if(Array.isArray(r)){let s=r.map(o=>{let i={...e,type:o};return bA(i,t)});return s.length===0?W.never():s.length===1?s[0]:W.union(s)}if(!r)return W.any();let n;switch(r){case"string":{let s=W.string();if(e.format){let o=e.format;o==="email"?s=s.check(W.email()):o==="uri"||o==="uri-reference"?s=s.check(W.url()):o==="uuid"||o==="guid"?s=s.check(W.uuid()):o==="date-time"?s=s.check(W.iso.datetime({offset:!0})):o==="date"?s=s.check(W.iso.date()):o==="time"?s=s.check(W.regex(Cj)):o==="duration"?s=s.check(W.iso.duration()):o==="hostname"?s=s.check(W.hostname()):o==="ipv4"?s=s.check(W.ipv4()):o==="ipv6"?s=s.check(W.ipv6()):o==="mac"?s=s.check(W.mac()):o==="cidr"?s=s.check(W.cidrv4()):o==="cidr-v6"?s=s.check(W.cidrv6()):o==="base64"?s=s.check(W.base64()):o==="base64url"?s=s.check(W.base64url()):o==="e164"?s=s.check(W.e164()):o==="credit_card"?s=s.check(W.creditCard()):o==="iban"?s=s.check(W.iban()):o==="jwt"?s=s.check(W.jwt()):o==="emoji"?s=s.check(W.emoji()):o==="nanoid"?s=s.check(W.nanoid()):o==="cuid"?s=s.check(W.cuid()):o==="cuid2"?s=s.check(W.cuid2()):o==="ulid"?s=s.check(W.ulid()):o==="xid"?s=s.check(W.xid()):o==="ksuid"&&(s=s.check(W.ksuid()))}typeof e.minLength=="number"&&(s=s.min(e.minLength)),typeof e.maxLength=="number"&&(s=s.max(e.maxLength)),e.pattern&&(s=s.regex(new RegExp(e.pattern))),n=s;break}case"number":case"integer":{let s=r==="integer"?W.number().int():W.number();typeof e.minimum=="number"&&e.exclusiveMinimum!==!0&&(s=s.min(e.minimum)),typeof e.maximum=="number"&&e.exclusiveMaximum!==!0&&(s=s.max(e.maximum)),typeof e.exclusiveMinimum=="number"?s=s.gt(e.exclusiveMinimum):e.exclusiveMinimum===!0&&typeof e.minimum=="number"&&(s=s.gt(e.minimum)),typeof e.exclusiveMaximum=="number"?s=s.lt(e.exclusiveMaximum):e.exclusiveMaximum===!0&&typeof e.maximum=="number"&&(s=s.lt(e.maximum)),typeof e.multipleOf=="number"&&(s=s.multipleOf(e.multipleOf)),n=s;break}case"boolean":{n=W.boolean();break}case"null":{n=W.null();break}case"object":{let s={},o=e.properties||{},i=new Set(e.required||[]),a=typeof e.additionalProperties=="object"?Nt(e.additionalProperties,t):void 0;for(let[p,m]of Object.entries(o)){let f=Nt(m,t);vt(s,p,i.has(p)?f:f.optional())}if(e.patternProperties){let p=e.patternProperties,m=Object.keys(p),f=[];for(let y of m){let b=Nt(p[y],t),R=W.string().regex(new RegExp(y));f.push(W.looseRecord(R,b))}let g=[];if(Object.keys(s).length>0&&g.push(W.object(s).passthrough()),g.push(...f),g.length===0)n=W.object({}).passthrough();else if(g.length===1)n=g[0];else{let y=W.intersection(g[0],g[1]);for(let b=2;b<g.length;b++)y=W.intersection(y,g[b]);n=y}if(e.additionalProperties===!1){let y=Object.keys(s),b=m.map(h=>new RegExp(h)),R=n;n=n.check(h=>{if(!Sr(h.value))return;let _=[];for(let S of Object.keys(h.value))y.includes(S)||b.some(w=>w.test(S))||_.push(S);_.length&&h.issues.push({code:"unrecognized_keys",keys:_,input:h.value,inst:R})})}}else{let p=W.object(s);e.additionalProperties===!1?n=p.strict():a?n=p.catchall(a):n=p.passthrough()}let c=e.propertyNames!==void 0&&e.propertyNames!==!0,u=typeof e.minProperties=="number"?e.minProperties:void 0,d=typeof e.maxProperties=="number"?e.maxProperties:void 0;if(c||u!==void 0||d!==void 0){let p;if(c){let m=typeof e.propertyNames=="object"&&e.propertyNames.type===void 0?{type:"string",...e.propertyNames}:e.propertyNames;p=Nt(m,t)}n=Sj(n,{keySchema:p,minProperties:u,maxProperties:d})}break}case"array":{let s=e.prefixItems,o=e.items;if(s&&Array.isArray(s)){let i=typeof e.minItems=="number"?e.minItems:0,a=s.map(p=>Nt(p,t)),c=gA(a,i),u=Array.isArray(o)?void 0:yA(o,t),d=W.tuple(c);n=u?d.rest(u):d,typeof e.minItems=="number"&&(n=n.check(W.minLength(e.minItems))),typeof e.maxItems=="number"&&(n=n.check(W.maxLength(e.maxItems)))}else if(Array.isArray(o)){let i=typeof e.minItems=="number"?e.minItems:0,a=o.map(p=>Nt(p,t)),c=gA(a,i),u=yA(e.additionalItems,t),d=W.tuple(c);n=u?d.rest(u):d,typeof e.minItems=="number"&&(n=n.check(W.minLength(e.minItems))),typeof e.maxItems=="number"&&(n=n.check(W.maxLength(e.maxItems)))}else if(o!==void 0){let i=Nt(o,t),a=W.array(i);typeof e.minItems=="number"&&(a=a.min(e.minItems)),typeof e.maxItems=="number"&&(a=a.max(e.maxItems)),n=a}else n=W.array(W.any());(e.uniqueItems===!0||e.contains!==void 0)&&(n=kj(n,{uniqueItems:e.uniqueItems===!0,containsSchema:e.contains!==void 0?Nt(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 n}function Nt(e,t){if(typeof e=="boolean")return e?W.any():W.never();let r=bA(e,t),n=e.type||e.enum!==void 0||e.const!==void 0;if(e.anyOf&&Array.isArray(e.anyOf)){let a=e.anyOf.map(u=>Nt(u,t)),c=W.union(a);r=n?W.intersection(r,c):c}if(e.oneOf&&Array.isArray(e.oneOf)){let a=e.oneOf.map(u=>Nt(u,t)),c=W.xor(a);r=n?W.intersection(r,c):c}if(e.allOf&&Array.isArray(e.allOf))if(e.allOf.length===0)r=n?r:W.any();else{let a=n?r:Nt(e.allOf[0],t),c=n?0:1;for(let u=c;u<e.allOf.length;u++)a=W.intersection(a,Nt(e.allOf[u],t));r=a}e.nullable===!0&&t.version==="openapi-3.0"&&(r=W.nullable(r)),e.readOnly===!0&&(r=W.readonly(r)),e.default!==void 0&&(r=r.default(e.default));let s={},o=["$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor"];for(let a of o)a in e&&(s[a]=e[a]);let i=["contentEncoding","contentMediaType","contentSchema"];for(let a of i)a in e&&(s[a]=e[a]);if(e.type==="object"&&e.$ref===void 0){e.propertyNames!==void 0&&!cu(e.propertyNames)&&(s.propertyNames=e.propertyNames);for(let a of["minProperties","maxProperties"])e[a]!==void 0&&(s[a]=e[a])}if(e.type==="array"&&e.$ref===void 0){e.contains!==void 0&&!cu(e.contains)&&(s.contains=e.contains);for(let a of["uniqueItems","minContains","maxContains"])e[a]!==void 0&&(s[a]=e[a])}for(let a of Object.keys(e))yj.has(a)||vt(s,a,e[a]);return Object.keys(s).length>0&&t.registry.add(r,s),e.description&&(r=r.describe(e.description)),r}function wA(e,t){if(typeof e=="boolean")return e?W.any():W.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 n=bj(r,t?.defaultTarget),s=r.$defs||r.definitions||{},o={version:n,defs:s,refs:new Map,processing:new Set,rootSchema:r,registry:t?.registry??kt};return Nt(r,o)}var W,yj,_j,vj,Cj,RA=A(()=>{Uc();nt();Rp();Zp();ss();W={...ji,...wp,iso:au},yj=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"]);_j=new Set(["items","prefixItems","additionalItems","additionalProperties","contains","propertyNames","not","if","then","else","allOf","anyOf","oneOf","unevaluatedItems","unevaluatedProperties","contentSchema"]),vj=new Set(["properties","patternProperties","dependentSchemas","dependencies","$defs","definitions"]);Cj=/^(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:\.\d+)?(?:Z|[+-](?:[01]\d|2[0-3]):[0-5]\d)$/});function uu(e,t){let r=typeof t=="function"?t:(i,a)=>{let c=t[i._zod.def.type];return c?c(i,a):i},n=new Map;function s(i){let a=n.get(i);if(a===SA)return new Lc({type:"lazy",getter:()=>n.get(i)});if(a!==void 0)return a;n.set(i,SA);let c=o(i),u=r(c,c!==i);return n.set(i,u),u}function o(i){let a=i._zod.def,c=a.type;switch(c){case"object":{let u=a.shape,d=Object.keys(u),p=!1,m={};for(let g of d){let y=s(u[g]);y!==u[g]&&(p=!0),m[g]=y}let f=a.catchall;return a.catchall&&(f=s(a.catchall),f!==a.catchall&&(p=!0)),p?Ie(i,{...a,shape:m,catchall:f}):i}case"array":{let u=s(a.element);return u===a.element?i:Ie(i,{...a,element:u})}case"tuple":{let u=a.items,d=!1,p=[];for(let f of u){let g=s(f);g!==f&&(d=!0),p.push(g)}let m=a.rest;return a.rest&&(m=s(a.rest),m!==a.rest&&(d=!0)),d?Ie(i,{...a,items:p,rest:m}):i}case"record":case"map":{let u=s(a.keyType),d=s(a.valueType);return u===a.keyType&&d===a.valueType?i:Ie(i,{...a,keyType:u,valueType:d})}case"set":{let u=s(a.valueType);return u===a.valueType?i:Ie(i,{...a,valueType:u})}case"union":{let u=a.options,d=!1,p=[];for(let m of u){let f=s(m);f!==m&&(d=!0),p.push(f)}return d?Ie(i,{...a,options:p}):i}case"intersection":{let u=s(a.left),d=s(a.right);return u===a.left&&d===a.right?i:Ie(i,{...a,left:u,right:d})}case"optional":case"nullable":case"default":case"prefault":case"catch":case"readonly":case"nonoptional":case"promise":case"success":{let u=s(a.innerType);return u===a.innerType?i:Ie(i,{...a,innerType:u})}case"pipe":{let u=s(a.in),d=s(a.out);return u===a.in&&d===a.out?i:Ie(i,{...a,in:u,out:d})}case"function":{let u=s(a.input),d=s(a.output);return u===a.input&&d===a.output?i:Ie(i,{...a,input:u,output:d})}case"lazy":{let u=a.getter,{_cachedInner:d,...p}=a;return Ie(i,{...p,getter:()=>s(u())})}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 i;default:return i}}return s(e)}var SA,ES=A(()=>{gi();nt();SA=Symbol("z.visit/resolving")});function _A(e){return uu(e,{object:t=>t.partial(),union:t=>{let r=t._zod.def;return r.discriminator===void 0?t:Ui(r.options)}})}var vA=A(()=>{ES();ss()});function Pj(e,t){if(!t?.length)return e;let r=e._zod.def;return Ie(e,$r(r,{checks:[...r.checks??[],...t]}),{parent:!0})}function kA(e){return Pj(e.out,e.checks)}function Ej(e){return e.in._zod.traits.has("$ZodTransform")?kA(e):e.in}function CA(e){return uu(e,{pipe:t=>Ej(t._zod.def),default:(t,r)=>r?Ks(t._zod.def.innerType):t,catch:(t,r)=>r?t._zod.def.innerType:t})}function PA(e){return uu(e,{pipe:t=>kA(t._zod.def),prefault:(t,r)=>r?t._zod.def.innerType:t})}var EA=A(()=>{nt();ES();ss()});var AS={};re(AS,{bigint:()=>Oj,boolean:()=>$j,date:()=>Ij,number:()=>Tj,string:()=>Aj});function Aj(e){return qb(Mi,e)}function Tj(e){return Xb(Fi,e)}function $j(e){return iw(Ni,e)}function Oj(e){return cw(Gi,e)}function Ij(e){return ww(Xc,e)}var AA=A(()=>{ur();ss()});var l={};re(l,{$brand:()=>ah,$input:()=>Gb,$output:()=>Nb,INVALID:()=>Mt,NEVER:()=>ih,TimePrecision:()=>Yb,ZodAny:()=>UR,ZodArray:()=>HR,ZodBase64:()=>Np,ZodBase64URL:()=>Gp,ZodBigInt:()=>Gi,ZodBigIntFormat:()=>zp,ZodBoolean:()=>Ni,ZodCIDRv4:()=>Mp,ZodCIDRv6:()=>Fp,ZodCUID:()=>Tp,ZodCUID2:()=>$p,ZodCatch:()=>dS,ZodCodec:()=>ou,ZodCompileAsyncError:()=>Or,ZodCompileUnsupportedError:()=>_e,ZodCreditCard:()=>IR,ZodCustom:()=>iu,ZodCustomStringFormat:()=>Ys,ZodDate:()=>Xc,ZodDefault:()=>oS,ZodDiscriminatedUnion:()=>VR,ZodE164:()=>Up,ZodEmail:()=>Cp,ZodEmoji:()=>Ep,ZodEnum:()=>Li,ZodError:()=>aj,ZodExactOptional:()=>Vp,ZodFile:()=>tS,ZodFirstPartyTypeKind:()=>CS,ZodFunction:()=>SS,ZodGUID:()=>Pp,ZodIBAN:()=>xR,ZodIPv4:()=>Dp,ZodIPv6:()=>Lp,ZodISODate:()=>ts,ZodISODateTime:()=>es,ZodISODuration:()=>ns,ZodISOTime:()=>rs,ZodInstanceOf:()=>kS,ZodIntersection:()=>qR,ZodIssueCode:()=>lj,ZodJWT:()=>jp,ZodKSUID:()=>xp,ZodLazy:()=>bS,ZodLiteral:()=>eS,ZodMAC:()=>OR,ZodMap:()=>QR,ZodNaN:()=>mS,ZodNanoID:()=>Ap,ZodNever:()=>zR,ZodNonOptional:()=>qp,ZodNull:()=>NR,ZodNullable:()=>sS,ZodNumber:()=>Fi,ZodNumberFormat:()=>Qs,ZodObject:()=>tu,ZodOptional:()=>nu,ZodPipe:()=>su,ZodPrefault:()=>aS,ZodPreprocess:()=>fS,ZodPromise:()=>RS,ZodReadonly:()=>gS,ZodRealError:()=>Yt,ZodRecord:()=>Di,ZodSet:()=>XR,ZodString:()=>Mi,ZodStringFormat:()=>Me,ZodSuccess:()=>lS,ZodSymbol:()=>MR,ZodTemplateLiteral:()=>yS,ZodTransform:()=>rS,ZodTuple:()=>KR,ZodType:()=>ye,ZodULID:()=>Op,ZodURL:()=>Qc,ZodUUID:()=>Vr,ZodUndefined:()=>FR,ZodUnion:()=>ru,ZodUnknown:()=>jR,ZodVoid:()=>BR,ZodXID:()=>Ip,ZodXor:()=>WR,_ZodString:()=>kp,_default:()=>iS,_function:()=>oA,any:()=>ME,array:()=>eu,base64:()=>hE,base64url:()=>yE,bigint:()=>OE,boolean:()=>LR,catch:()=>pS,check:()=>iA,cidrv4:()=>fE,cidrv6:()=>gE,clone:()=>Ie,codec:()=>tA,coerce:()=>AS,compile:()=>Bb,config:()=>Ye,core:()=>bn,creditCard:()=>wE,cuid:()=>iE,cuid2:()=>aE,currencyCode:()=>CE,custom:()=>aA,date:()=>NE,decode:()=>vR,decodeAsync:()=>CR,deepPartial:()=>_A,describe:()=>cA,discriminatedUnion:()=>HE,e164:()=>bE,email:()=>JP,emoji:()=>sE,encode:()=>_R,encodeAsync:()=>kR,endsWith:()=>vi,enum:()=>Hp,exactOptional:()=>nS,file:()=>YE,flattenError:()=>wc,float32:()=>EE,float64:()=>AE,formatError:()=>Rc,fromJSONSchema:()=>wA,function:()=>oA,getDiscriminatedOption:()=>ub,getErrorMap:()=>pj,globalRegistry:()=>kt,gt:()=>Hr,gte:()=>cr,guid:()=>YP,hash:()=>PE,hex:()=>kE,hostname:()=>vE,httpUrl:()=>nE,iban:()=>RE,includes:()=>Si,input:()=>CA,instanceof:()=>lA,int:()=>_p,int32:()=>TE,int64:()=>IE,intersection:()=>ZR,invertCodec:()=>rA,ipv4:()=>dE,ipv6:()=>mE,iso:()=>au,json:()=>pA,jwt:()=>SE,keyof:()=>GE,ksuid:()=>lE,lazy:()=>wS,length:()=>Vs,literal:()=>JE,locales:()=>Gc,looseObject:()=>zE,looseRecord:()=>VE,lowercase:()=>wi,lt:()=>Br,lte:()=>ar,mac:()=>pE,map:()=>qE,maxLength:()=>Ws,maxSize:()=>Jn,memoizer:()=>Nc,meta:()=>uA,mime:()=>Ci,minLength:()=>yn,minSize:()=>Wr,multipleOf:()=>Kn,nan:()=>eA,nanoid:()=>oE,nativeEnum:()=>KE,negative:()=>lp,never:()=>Bp,nonnegative:()=>pp,nonoptional:()=>uS,nonpositive:()=>dp,normalize:()=>Pi,null:()=>GR,nullable:()=>Yc,nullish:()=>QE,number:()=>DR,object:()=>UE,optional:()=>Ks,output:()=>PA,overwrite:()=>Ir,parse:()=>bR,parseAsync:()=>wR,partialRecord:()=>WE,pipe:()=>vp,positive:()=>up,prefault:()=>cS,preprocess:()=>mA,prettifyError:()=>ph,promise:()=>sA,properties:()=>ki,property:()=>mp,readonly:()=>hS,record:()=>YR,refine:()=>_S,regex:()=>bi,regexes:()=>vr,registry:()=>Nd,safeDecode:()=>ER,safeDecodeAsync:()=>TR,safeEncode:()=>PR,safeEncodeAsync:()=>AR,safeParse:()=>RR,safeParseAsync:()=>SR,set:()=>ZE,setErrorMap:()=>dj,size:()=>Hs,slugify:()=>$i,startsWith:()=>_i,strictObject:()=>jE,string:()=>Jc,stringFormat:()=>_E,stringbool:()=>dA,success:()=>XE,superRefine:()=>vS,symbol:()=>DE,templateLiteral:()=>nA,toJSONSchema:()=>yp,toLowerCase:()=>Ai,toUpperCase:()=>Ti,toZod:()=>uc,transform:()=>Wp,treeifyError:()=>dh,trim:()=>Ei,tuple:()=>JR,uint32:()=>$E,uint64:()=>xE,ulid:()=>cE,undefined:()=>LE,union:()=>Ui,unknown:()=>Zs,uppercase:()=>Ri,url:()=>rE,util:()=>V,uuid:()=>QP,uuidv4:()=>XP,uuidv6:()=>eE,uuidv7:()=>tE,validate:()=>Sc,validateAsync:()=>_c,void:()=>FE,withParser:()=>Gd,xid:()=>uE,xor:()=>BE});var TS=A(()=>{ur();ss();Rp();yR();$R();fA();ur();Kc();RA();vA();EA();Fb();Zp();Zp();AA()});var lu=A(()=>{TS();TS()});function OA({author:e,comments:t}){let r=t.filter(n=>!n.isBot&&n.author===e).map(n=>n.body);return r.some(n=>Mj.some(s=>s.test(n)))?"superseded":r.some(n=>Fj.test(n))?"no-traction":t.some(n=>!n.isBot&&n.author!==e)?"after-feedback":"no-response"}function IA({author:e,closer:t,closerIsBot:r,comments:n}){let s=n.filter(o=>!o.isBot&&o.author!==e).map(o=>o.body);return s.some(o=>xj.test(o))?"ai-policy":s.some(o=>Dj.test(o))?"superseded":r||s.some(o=>Lj.test(o))?"stale":t?t===e?"self-closed":"rejected":"unknown"}var TA,$A,xj,Dj,Lj,Mj,Fj,$S=A(()=>{"use strict";TA=["ai-policy","superseded","stale","self-closed","rejected","unknown"],$A=["superseded","no-traction","after-feedback","no-response"],xj=/\b(?:AI|LLM)[- ](?:generated|written|authored|slop|polic(?:y|ies))|(?:generated|written) (?:by|with) (?:an? )?(?:AI|LLM|ChatGPT|Copilot)\b|vibe[- ]?cod|machine[- ]generated/i,Dj=/clos(?:e|ing) (?:this )?as (?:a )?duplicate|duplicate of #\d+|superseded by|already (?:been )?(?:fixed|merged|addressed|resolved|implemented)|fixed (?:in|by|via) #\d+|in favou?r of #\d+/i,Lj=/marked as stale|clos(?:e|ing) (?:this )?(?:as|due to) (?:stale|inactiv)|no activity (?:for|in)/i,Mj=[/already (?:been )?(?:fixed|merged|addressed|resolved|implemented|landed|applied|several)/i,/cover(?:s|ed) (?:this|everything|the same)|same (?:one-line )?fix|(?:landed|fixed|ships?) the same/i,/has (?:landed|shipped)|is in and|(?:fixed|addressed|resolved|landed|applied) (?:upstream|elsewhere)/i,/upstream (?:upgrade|commit|fix)|supersed|in favou?r of|replaced by|duplicate/i,/no longer (?:needed|relevant|reproduc|applies)/i],Fj=/traction|(?:been )?quiet|unmaintained|actively (?:reviewing|maintained)|not maintained|no (?:response|activity)|keep the queue tidy|sitting in (?:your|the) queue|stale/i});function Xs(e){return l.custom(t=>typeof t=="string")}function tz(e){let t=e?.openPRs;return!Array.isArray(t)||t.length===0?e:{...e,needsAddressingPRs:t.filter(r=>r?.status==="needs_addressing"),waitingOnMaintainerPRs:t.filter(r=>r?.status==="waiting_on_maintainer")}}function MA(e,t){let r=e!==null&&typeof e=="object"?e.workClaims:void 0;return Array.isArray(r)?Math.max(0,r.length-t.workClaims.length):0}function Jp(e){if(!e||typeof e!="object")return[];let t=new Set(Object.keys(Gt.shape));return Object.keys(e).filter(r=>!t.has(r))}var Nj,IS,xS,DS,LS,Gj,Uj,DA,LA,jj,zj,Bj,Hj,Wj,Vj,qj,Zj,xA,Kj,Kp,Jj,Yj,Qj,Xj,ez,OS,rz,nz,sz,oz,iz,MS,FS,eo,az,Gt,Yp,wn=A(()=>{"use strict";lu();$S();Nj=l.enum(["candidate","claimed","in_progress","pr_submitted"]),IS=l.enum(["needs_addressing","waiting_on_maintainer"]),xS=l.enum(["nonprofit","devtools","infrastructure","web-frameworks","data-ml","education"]),DS=l.enum(["beginner","intermediate","advanced"]),LS=l.enum(["inline","sourcetree","vscode","custom"]),Gj=l.object({hasActiveMaintainers:l.boolean(),isResponsive:l.boolean(),hasHostileComments:l.boolean()}),Uj=l.object({repo:l.string(),score:l.number(),mergedPRCount:l.number(),closedWithoutMergeCount:l.number(),avgResponseDays:l.number().nullable(),lastMergedAt:l.string().optional(),lastEvaluatedAt:l.string(),signals:Gj,stargazersCount:l.number().optional(),language:l.string().nullable().optional()}).passthrough(),DA=l.object({issueUrl:l.string(),grade:l.number(),recommendation:l.string(),stargazersCount:l.number().optional(),source:Xs(["vet","vet-list","list"]),capturedAt:l.string().optional(),labels:l.array(l.string()).optional(),issueAuthorAssociation:Xs(["OWNER","MEMBER","COLLABORATOR","CONTRIBUTOR","FIRST_TIMER","FIRST_TIME_CONTRIBUTOR","MANNEQUIN","NONE"]).optional(),issueAuthorIsBot:l.boolean().optional(),competingPRs:l.number().optional(),mentioningPRs:l.number().optional(),firstInRepo:l.boolean().optional(),commentCount:l.number().optional()}).passthrough(),LA={issueUrl:l.string().optional(),pick:DA.optional(),lastReviewDecision:l.string().optional(),lastCiStatus:l.string().optional(),backfilledAt:l.string().optional(),responseRule:l.number().int().optional()},jj=l.object({url:l.string(),title:l.string(),mergedAt:l.string(),openedAt:l.string().optional(),firstMaintainerResponseAt:l.string().optional(),commentsFetchedAt:l.string().datetime().optional(),learningsExtractedAt:l.string().datetime().optional(),...LA}).passthrough(),zj=l.object({url:l.string(),title:l.string(),closedAt:l.string(),openedAt:l.string().optional(),firstMaintainerResponseAt:l.string().optional(),commentsFetchedAt:l.string().datetime().optional(),learningsExtractedAt:l.string().datetime().optional(),...LA,closeReason:Xs(TA).optional(),selfCloseReason:Xs($A).optional()}).passthrough(),Bj=l.object({url:l.string(),repo:l.string(),analyzedAt:l.string()}),Hj=l.object({tier:l.enum(["light_check_in","direct_check_in","final_check_in"]),timestamp:l.string().datetime(),draftPath:l.string().optional()}),Wj=l.object({workflowName:l.enum(["draft-first","work-through-issues","pre-commit-review"]),currentStep:l.string(),branchName:l.string().optional(),issueContext:l.object({title:l.string(),url:l.string()}).optional(),completedSteps:l.array(l.string()).default([]),stepData:l.record(l.string(),l.unknown()).default({}),lastUpdatedAt:l.string().datetime()}),Vj=l.object({branchNamingConvention:l.string().optional(),commitMessageFormat:l.string().optional(),prTitleFormat:l.string().optional(),requiredChecks:l.array(l.string()).optional(),testFramework:l.string().optional(),testCoverageRequired:l.boolean().optional(),testFileNaming:l.string().optional(),linter:l.string().optional(),formatter:l.string().optional(),styleGuideUrl:l.string().optional(),issueClaimProcess:l.string().optional(),reviewProcess:l.string().optional(),claRequired:l.boolean().optional(),rawContent:l.string().optional()}),qj=l.object({passedAllChecks:l.boolean(),checks:l.object({noExistingPR:l.boolean(),notClaimed:l.boolean(),projectActive:l.boolean(),clearRequirements:l.boolean(),contributionGuidelinesFound:l.boolean()}),contributionGuidelines:Vj.optional(),notes:l.array(l.string())}),Zj=l.object({id:l.number(),url:l.string(),repo:l.string(),number:l.number(),title:l.string(),status:Nj,labels:l.array(l.string()),createdAt:l.string(),updatedAt:l.string(),vetted:l.boolean(),vettingResult:qj.optional()}),xA=l.object({number:l.number(),url:l.string(),title:l.string(),repo:l.string(),daysSinceActivity:l.number(),status:IS}),Kj=l.object({status:IS,setAt:l.string(),lastActivityAt:l.string()}),Kp=l.object({setupComplete:l.boolean().default(!1),setupCompletedAt:l.string().optional(),persistence:l.enum(["local","gist"]).default("local"),maxActivePRs:l.number().default(10),maxOpenPRsPerRepo:l.number().int().min(0).default(0),maxOpenPRsColdRepo:l.number().int().min(0).default(1),maxConcurrentImplementations:l.number().int().min(0).default(2),dormantThresholdDays:l.number().default(30),approachingDormantDays:l.number().default(25),maxIssueAgeDays:l.number().default(90),skipBroadWhenSufficientResults:l.number().min(0).default(8),complexIssues:Xs(["off","warm"]).default("off"),languages:l.array(l.string()).default(["typescript","javascript"]),labels:l.array(l.string()).default(["good first issue","help wanted"]),scope:l.array(DS).optional(),excludeRepos:l.array(l.string()).default([]),excludeOrgs:l.array(l.string()).optional(),untrackedOrgs:l.array(l.string()).default([]),avoidRepos:l.array(l.string()).default([]),boostIssueTypes:l.array(l.string()).default([]),trustedProjects:l.array(l.string()).default([]),githubUsername:l.string().default(""),minRepoScoreThreshold:l.number().default(4),starredRepos:l.array(l.string()).default([]),starredReposLastFetched:l.string().optional(),squashByDefault:l.union([l.boolean(),l.literal("ask")]).default(!0),localRepoScanPaths:l.array(l.string()).optional(),minStars:l.number().default(50),includeDocIssues:l.boolean().default(!0),aiPolicyBlocklist:l.array(l.string()).default(["matplotlib/matplotlib"]),shelvedPRUrls:l.array(l.string()).default([]),dismissedIssues:l.record(l.string(),l.string()).default({}),dismissedPRHeads:l.record(l.string(),l.string()).default({}),statusOverrides:l.record(l.string(),Kj).optional(),issueListPath:l.string().optional(),skippedIssuesPath:l.string().optional(),projectCategories:l.array(xS).default([]),preferredOrgs:l.array(l.string()).default([]),diffTool:LS.default("inline"),diffToolCustomCommand:l.string().optional(),autoExtractLearnings:l.boolean().default(!0),autoFormatBeforePush:l.boolean().default(!1),trustOwnRepoWrites:l.boolean().default(!1),healthCheckFreshnessMinutes:l.number().int().positive().default(30),reviewMaxPasses:l.number().int().positive().optional(),slmTriageModel:l.string().default(""),slmTriageHost:l.string().default("")}).passthrough().transform(({snoozedPRs:e,...t})=>t),Jj=l.object({repos:l.record(l.string(),l.object({path:l.string(),exists:l.boolean(),currentBranch:l.string().nullable()})),scanPaths:l.array(l.string()),cachedAt:l.string()}),Yj=l.object({url:l.string(),repo:l.string(),number:l.number(),title:l.string(),closedAt:l.string(),closedBy:l.string().optional(),openedAt:l.string().optional(),issueUrl:l.string().optional()}),Qj=l.object({url:l.string(),repo:l.string(),number:l.number(),title:l.string(),mergedAt:l.string(),openedAt:l.string().optional(),issueUrl:l.string().optional()}),Xj=l.object({totalActivePRs:l.number(),totalNeedingAttention:l.number(),totalMergedAllTime:l.number(),mergeRate:l.number()}),ez=l.object({url:l.string(),repo:l.string(),number:l.number(),status:IS}).passthrough(),OS=l.array(ez);rz=l.object({generatedAt:l.string(),openPRs:OS,needsAddressingPRs:OS,waitingOnMaintainerPRs:OS,recentlyClosedPRs:l.array(Yj),recentlyMergedPRs:l.array(Qj),shelvedPRs:l.array(xA),autoUnshelvedPRs:l.array(xA),summary:Xj}),nz=l.preprocess(tz,rz),sz=l.object({url:l.string(),lastSeenAt:l.string()}),oz=l.object({url:l.string(),branch:l.string(),worktree:l.string().optional(),note:l.string().optional(),recordedAt:l.string(),pushedRef:l.string().optional(),pushedAt:l.string().optional(),compareUrl:l.string().optional(),pushProblem:l.string().optional()}).passthrough(),iz=l.object({url:l.string(),attemptedAt:l.string(),outcome:l.enum(["prepared","blocked"]),note:l.string().optional()}).passthrough(),MS=l.object({runAt:l.string(),reportPath:l.string(),prepareCount:l.number().int().nonnegative(),judgmentCount:l.number().int().nonnegative(),prepared:l.array(oz).default([]),implementUrl:l.string().optional(),implementAttempts:l.array(iz).optional()}).passthrough(),FS=l.object({languageOffset:l.number().int().nonnegative().default(0),phase0Offset:l.number().int().nonnegative().default(0),starredOffset:l.number().int().nonnegative().default(0),maintainedOffset:l.number().int().nonnegative().default(0),strategyOffset:l.number().int().nonnegative().default(0),lastRotatedAt:l.string().optional()}).passthrough(),eo=l.object({kind:Xs(["implementation","pr"]),url:l.string(),session:l.string(),startedAt:l.string(),expiresAt:l.string(),status:Xs(["running","finished"]),branch:l.string().optional(),worktree:l.string().optional(),host:l.string().optional(),machineId:l.string().optional(),runId:l.string().optional(),finishedAt:l.string().optional()}).loose(),az=l.array(l.unknown()).default([]).transform(e=>e.flatMap(t=>{let r=eo.safeParse(t);return r.success?[r.data]:[]}));Gt=l.object({version:l.literal(4),gistId:l.string().optional(),repoScores:l.record(l.string(),Uj).default({}),config:Kp.default(()=>Kp.parse({})),lastRunAt:l.string().default(()=>new Date().toISOString()),lastDigestAt:l.string().optional(),lastStrategyAt:l.string().optional(),lastDigest:nz.optional(),monthlyMergedCounts:l.record(l.string(),l.number()).optional(),monthlyClosedCounts:l.record(l.string(),l.number()).optional(),monthlyOpenedCounts:l.record(l.string(),l.number()).optional(),localRepoCache:Jj.optional(),mergedPRs:l.array(jj).optional(),closedPRs:l.array(zj).optional(),analyzedIssueConversations:l.array(Bj).optional(),activeIssues:l.array(Zj).default([]),prFollowUpHistory:l.record(l.string(),l.array(Hj)).optional(),workflowState:Wj.optional(),searchSeen:l.array(sz).default([]),pickSnapshots:l.array(DA).default([]),lastOvernight:MS.optional(),searchRotation:FS.optional(),workClaims:az}).passthrough();Yp="was written by a different oss-autopilot release (usually a newer one); this version keeps those fields but cannot use them. If you are not on the latest release, update with `claude plugin update oss-autopilot@oss-autopilot` and restart Claude Code."});function NS(e,t){return cz.test(e)&&uz.test(t)}function q(e){if(!e.startsWith("https://github.com/"))return null;let t=e.match(/github\.com\/([^/]+)\/([^/]+)\/pull\/(\d+)/);if(t){let n=t[1],s=t[2];return NS(n,s)?{owner:n,repo:s,number:parseInt(t[3],10),type:"pull"}:null}let r=e.match(/github\.com\/([^/]+)\/([^/]+)\/issues\/(\d+)/);if(r){let n=r[1],s=r[2];return NS(n,s)?{owner:n,repo:s,number:parseInt(r[3],10),type:"issues"}:null}return null}function qe(e){let t=q(e);return t?`${t.owner.toLowerCase()}/${t.repo.toLowerCase()}#${t.number}`:null}function qr(e){if(!e.startsWith("https://github.com/"))return null;let t=e.match(/github\.com\/([^/]+)\/([^/]+)/);if(!t)return null;let r=t[1],n=t[2];return NS(r,n)?{owner:r,repo:n}:null}function to(e){let[t,r]=e.split("/",2);if(!t||!r)throw new Error(`Invalid repo format: expected "owner/repo", got "${e}"`);return{owner:t,repo:r}}function kr(e,t){return e.toLowerCase()===t.toLowerCase()}function zi(e,t=[]){let r=e.toLowerCase();return t.some(n=>n.toLowerCase()===r)}var cz,uz,st=A(()=>{"use strict";cz=/^[\w-]+$/,uz=/^[\w.-]+$/});function Qt(e){return qe(e)??e.trim().toLowerCase()}function GS(e,t=Date.now()){let r=Date.parse(e.expiresAt);return Number.isFinite(r)&&r>t}function lr(e,t=Date.now()){return e.filter(r=>GS(r,t))}function ro(e,t,r=Date.now()){let n=Qt(t);return lr(e,r).find(s=>Qt(s.url)===n)}function Xp(e,t,r,n=Date.now()){let s=ro(e,t,n);if(!(s===void 0||s.session===r))return s}function em(e,t){let r=new Date(Date.parse(t)+pu*36e5),n=Date.parse(e.expiresAt),s=Number.isFinite(n)&&n>r.getTime()?e.expiresAt:r.toISOString();return{...e,status:"finished",finishedAt:t,expiresAt:s}}function tm(e,t=Date.now()){return lr(e,t).filter(r=>r.kind==="implementation"&&r.status==="finished")}function UA(e,t=Date.now()){return lr(e,t).filter(r=>r.kind==="implementation"&&r.status==="running")}function Bi(e){return GA.default.resolve(e.trim())}function lz(e,t){return e===void 0||t===void 0||e===t}function FA(e){try{return NA.realpathSync(e)}catch{return e}}function dz(e,t,r){if(!e.worktree)return!1;let n=Bi(e.worktree);return e.machineId!==void 0&&r.machineId!==void 0?e.machineId!==r.machineId?!1:FA(n)===FA(t):lz(e.host,r.host)&&n===t}function rm(e,t,r,n=Date.now()){let s=Qt(t.url),o=lr(e,n).filter(a=>a.kind==="implementation"&&Qt(a.url)!==s);if(t.worktree!==void 0){let a=Bi(t.worktree),c=o.filter(u=>dz(u,a,t));if(c.length>0){let u=c[0];return{reason:"worktree",blocking:c,message:`Checkout ${a} already hosts an implementation of ${u.url} (session ${u.session}, ${u.status}). Use a separate worktree, or finish or release that claim first.`}}}let i=o.filter(a=>a.status==="running");if(r>0&&i.length>=r){let a=i.map(c=>`${c.url} (session ${c.session})`).join(", ");return{reason:"cap",blocking:i,message:`Implementation cap reached: ${i.length} of ${r} running (${a}). Collect or release one, or raise it with \`setup --set maxConcurrentImplementations=N\`.`}}return null}function US(e,t=Date.now()){let r=Date.parse(e.startedAt),n=Number.isFinite(r)?Math.max(0,Math.floor((t-r)/6e4)):0;return n<60?`${n} min`:n<1440?`${Math.floor(n/60)} h`:`${Math.floor(n/1440)} d`}function mu(e,t=Date.now()){return`${e.kind} claimed in session ${e.session} (${US(e,t)}, ${e.status})`}function Hi(e,t,r=Date.now()){let n=ro(e,t,r);return!n||n.kind!=="implementation"?null:{recommendation:"skip",reasonsToSkip:[`Already being implemented: ${mu(n,r)}`],workClaim:n}}var NA,GA,Qp,du,pu,jS=A(()=>{"use strict";NA=B(require("node:fs"),1),GA=B(require("node:path"),1);st();Qp={implementation:24,pr:12},du=168,pu=168});function mz(e){let t=e.lastDigest,r=[...t?.openPRs??[],...t?.shelvedPRs??[],...e.activeIssues].map(i=>i.repo),s=[...(e.mergedPRs??[]).map(i=>i.url),...(e.closedPRs??[]).map(i=>i.url),...e.config.shelvedPRUrls??[]].flatMap(i=>{let a=q(i);return a?[`${a.owner}/${a.repo}`]:[]}),o=new Set(r);for(let i of s)o.add(i);return o}function fz(e,t=Date.now()){let r=t-fu*jA,n=e.searchSeen.filter(c=>Date.parse(c.lastSeenAt)>=r),s=t-pz*jA,o=mz(e),i=Object.fromEntries(Object.entries(e.repoScores).filter(([c,u])=>{let d=u.mergedPRCount>0||u.closedWithoutMergeCount>0,p=Date.parse(u.lastEvaluatedAt),m=Number.isNaN(p)||p>=s;return d||o.has(c)||m})),a=e.lastDigest&&{...e.lastDigest,needsAddressingPRs:[],waitingOnMaintainerPRs:[]};return{...e,searchSeen:n,repoScores:i,lastDigest:a}}function xr(e){return JSON.stringify(fz(e))}var jA,zS,fu,pz,Wi=A(()=>{"use strict";st();jA=1440*60*1e3,zS=7,fu=zS+1,pz=14});function gz(){try{return nm.userInfo().homedir}catch{return null}}function sm(){let e=nm.homedir(),t=process.env.VITEST?gz():null;if(t!==null&&bt.resolve(e)===bt.resolve(t))throw new Error(`Refusing to use the real home directory (${e}) under vitest`);return bt.join(e,".oss-autopilot")}function dr(){let e=sm();return Ut.existsSync(e)||Ut.mkdirSync(e,{recursive:!0,mode:448}),e}function jt(){return bt.join(dr(),"state.json")}function zA(){return bt.join(process.cwd(),"data","state.json")}function BA(){return bt.join(process.cwd(),"data","backups")}function no(){let e=bt.join(dr(),"backups");return Ut.existsSync(e)||Ut.mkdirSync(e,{recursive:!0,mode:448}),e}function om(){let e=bt.join(dr(),"cache");return Ut.existsSync(e)||Ut.mkdirSync(e,{recursive:!0,mode:448}),e}function Vi(){let e=bt.join(dr(),"reports");return Ut.existsSync(e)||Ut.mkdirSync(e,{recursive:!0,mode:448}),e}function so(){return bt.join(dr(),"gist-id")}function HA(){return bt.join(dr(),"machine-id")}function os(){return bt.join(dr(),"state-cache.json")}function im(){return Ut.existsSync(bt.join(sm(),"state.json"))}function Zr(){return"3.42.4"}var Ut,bt,nm,Kr=A(()=>{"use strict";Ut=B(require("node:fs"),1),bt=B(require("node:path"),1),nm=B(require("node:os"),1)});function cm(){am=!0}function WA(){return am}function O(e,t,...r){if(!am)return;let n=new Date().toISOString();console.error(`[${n}] [DEBUG] [${e}] ${t}`,...r)}function VA(e,t,...r){let n=new Date().toISOString();console.error(`[${n}] [INFO] [${e}] ${t}`,...r)}function k(e,t,...r){let n=new Date().toISOString();console.error(`[${n}] [WARN] [${e}] ${t}`,...r)}async function um(e,t,r){if(!am)return r();let n=performance.now();try{let s=await r(),o=(performance.now()-n).toFixed(0);return O(e,`${t} completed in ${o}ms`),s}catch(s){let o=(performance.now()-n).toFixed(0);throw O(e,`${t} failed after ${o}ms`),s}}var am,ae=A(()=>{"use strict";am=!1});function hu(e){if(process.env[lm]!==void 0)throw new Oe(`Refusing to ${e} during an unattended run (${lm} is set). Run it yourself in an interactive session.`)}function I(e){return e instanceof Error?e.message:String(e)}function je(e){if(e&&typeof e=="object"&&"status"in e){let t=e.status;return typeof t=="number"&&Number.isFinite(t)?t:void 0}}function Rn(e){let t=je(e);return t===void 0?void 0:`HTTP ${t}`}function er(e){let t=Rn(e);return t?`${t}: ${I(e)}`:I(e)}function zt(e){let t=je(e);return t===429?!0:t===403?I(e).toLowerCase().includes("rate limit"):!1}function qA(e){if(je(e)!==422)return!1;let t=e?.response?.data,r=t&&typeof t=="object"?t.errors:void 0;return Array.isArray(r)?r.some(n=>{if(!n||typeof n!="object")return!1;let s=n;return s.resource!=="Search"||s.code!=="invalid"?!1:typeof s.message=="string"?BS.test(s.message):BS.test(I(e))}):BS.test(I(e))}function le(e){let t=je(e);if(t===401||t===429)return!0;if(t===403){let r=I(e).toLowerCase();return r.includes("rate limit")||r.includes("abuse detection")}return!1}function pm(e){if(!e||typeof e!="object")return!1;let t=je(e);if(typeof t=="number"&&t>=500&&t<600)return!0;let r=e.code;if(typeof r=="string"&&(r==="ECONNRESET"||r==="ETIMEDOUT"||r==="ENETUNREACH"||r==="ENOTFOUND"||r==="ECONNREFUSED"||r==="EAI_AGAIN"))return!0;let n=e.name;return typeof n=="string"&&(n==="AbortError"||n==="TimeoutError")}function ZA(e){return t=>{if(le(t))throw t;return k(e.module,`Failed to ${e.label}: ${I(t)}`),e.fallback}}function mm(e){if(e instanceof Oe)return"CONFIGURATION";if(e instanceof j)return"VALIDATION";if(e instanceof Dr||e instanceof Xt)return"CONCURRENCY";let t=je(e);if(t===401)return"AUTH_REQUIRED";if(t===403){let n=I(e).toLowerCase();return n.includes("rate limit")||n.includes("abuse detection")?"RATE_LIMITED":"AUTH_REQUIRED"}if(t===404)return"NOT_FOUND";if(t===429)return"RATE_LIMITED";let r=I(e).toLowerCase();return r.includes("enotfound")||r.includes("econnrefused")||r.includes("econnreset")||r.includes("etimedout")||r.includes("fetch failed")?"NETWORK":r.includes("state")&&(r.includes("corrupt")||r.includes("invalid"))?"STATE_CORRUPTED":"UNKNOWN"}var Cr,Oe,lm,j,qi,gu,Dr,Xt,dm,Lr,BS,ee=A(()=>{"use strict";ae();Cr=class extends Error{constructor(r,n){super(r);this.code=n;this.name="OssAutopilotError"}code},Oe=class extends Cr{constructor(t){super(t,"CONFIGURATION_ERROR"),this.name="ConfigurationError"}},lm="OSS_AUTOPILOT_UNATTENDED";j=class extends Cr{constructor(t){super(t,"VALIDATION_ERROR"),this.name="ValidationError"}},qi=class extends Oe{constructor(t){super(t??'Your GitHub token does not have Gist permissions. Run `gh auth refresh -s gist` to add the required scope, or create a token with the "gist" scope.'),this.name="GistPermissionError"}},gu=class extends Oe{constructor(r,n,s){let o=s instanceof Error?s.message:String(s),i=n?`
64
64
  Corrupt content preserved at: ${n}
65
65
  Inspect or restore manually, then re-run. Falling back to a fresh state would overwrite your Gist.`:`
66
66
  Could not preserve the rejected content; do not push without inspecting the Gist manually.`;super(`Gist ${r} state.json is corrupt or fails schema validation: ${o}${i}`);this.gistId=r;this.rejectedPath=n;this.cause=s;this.name="GistCorruptError"}gistId;rejectedPath;cause},Dr=class extends Cr{constructor(r,n){super("Another oss-autopilot process wrote state.json concurrently. Re-run the command to retry \u2014 the last write wins and no data was lost from the other process.","CONCURRENCY_ERROR");this.expectedMtimeMs=r;this.actualMtimeMs=n;this.name="ConcurrencyError"}expectedMtimeMs;actualMtimeMs},Xt=class extends Cr{constructor(r,n){super("Another machine pushed to the state Gist while this push was in flight, and the merge attempt also collided. Your local mutations are still in memory, but `state --sync` cannot merge them: re-run the command that made the change.","CONCURRENCY_ERROR");this.expectedEtag=r;this.remoteEtag=n;this.name="GistConcurrencyError"}expectedEtag;remoteEtag},dm="trim the large state fields in the Gist (repoScores and searchSeen are usually the biggest), or run state-unlink to fall back to local state",Lr=class extends Oe{constructor(t){super(t),this.name="GistFileSizeError"}};BS=/users.*do not exist|cannot be searched/i});function yz(e){try{let t=JSON.parse(oe.readFileSync(e,"utf8"));return Date.now()-t.timestamp>hz}catch(t){return O(ne,"Lock file unreadable or invalid JSON, treating as stale",t),!0}}function YA(e){let t=JSON.stringify({pid:process.pid,timestamp:Date.now()});try{oe.writeFileSync(e,t,{flag:"wx"});return}catch(r){O(ne,"Lock file already exists, checking staleness",r)}if(!yz(e))throw new Error("State file is locked by another process");try{oe.unlinkSync(e)}catch(r){O(ne,"Stale lock already removed by another process",r)}try{oe.writeFileSync(e,t,{flag:"wx"})}catch(r){throw O(ne,"Lock re-acquire failed (race condition)",r),new Error("State file is locked by another process",{cause:r})}}function QA(e){try{JSON.parse(oe.readFileSync(e,"utf8")).pid===process.pid&&oe.unlinkSync(e)}catch(t){O(ne,"Lock file already removed or unreadable during release",t)}}function Mr(e,t,r){let n=`${e}.${process.pid}.tmp`;oe.writeFileSync(n,t,{mode:r??384}),oe.renameSync(n,e),r!==void 0&&oe.chmodSync(e,r)}function Ki(e){O(ne,"Migrating state from v1 to v2 (fresh GitHub fetching)...");let t=e.mergedPRs||[],r=e.closedPRs||[],n={...e.repoScores||{}};for(let o of[...t,...r])n[o.repo]||(n[o.repo]={repo:o.repo,score:5,mergedPRCount:0,closedWithoutMergeCount:0,avgResponseDays:null,lastEvaluatedAt:new Date().toISOString(),signals:{hasActiveMaintainers:!0,isResponsive:!1,hasHostileComments:!1}});let s={version:2,activeIssues:e.activeIssues||[],repoScores:n,config:e.config,lastRunAt:new Date().toISOString()};return O(ne,`Migration complete. Preserved ${Object.keys(n).length} repo scores.`),s}function Ji(e){O(ne,"Migrating state from v2 to v3 (drop dead fields, add learnings tracking)..."),delete e.events,delete e.dailyActivityCounts;let t=e.config;return t&&(delete t.showHealthCheck,delete t.scoreThreshold),e.version=3,O(ne,"v2 to v3 migration complete."),e}function Yi(e){return O(ne,"Migrating state from v3 to v4 (add commentsFetchedAt to stored PR records)..."),e.version=4,O(ne,"v3 to v4 migration complete (no data transformation required)."),e}function _n(){return Gt.parse({version:4})}function bz(){let e=jt(),t=zA(),r=BA();if(oe.existsSync(e)||!oe.existsSync(t))return!1;O(ne,"Migrating state from ./data/ to ~/.oss-autopilot/...");try{if(dr(),oe.copyFileSync(t,e),O(ne,`Migrated state file to ${e}`),oe.existsSync(r)){let s=no(),o=oe.readdirSync(r).filter(i=>i.startsWith("state-")&&i.endsWith(".json"));for(let i of o){let a=Sn.join(r,i),c=Sn.join(s,i);oe.copyFileSync(a,c)}O(ne,`Migrated ${o.length} backup files`)}if(oe.unlinkSync(t),O(ne,"Removed legacy state file"),oe.existsSync(r)){let s=oe.readdirSync(r);for(let o of s)oe.unlinkSync(Sn.join(r,o));oe.rmdirSync(r)}let n=Sn.dirname(t);return oe.existsSync(n)&&oe.readdirSync(n).length===0&&(oe.rmdirSync(n),O(ne,"Removed empty legacy data directory")),O(ne,"Migration complete!"),!0}catch(n){if(k(ne,`Failed to migrate state: ${I(n)}`),oe.existsSync(e)&&oe.existsSync(t))try{oe.unlinkSync(e),O(ne,"Cleaned up partial migration - removed incomplete new state file")}catch(s){k(ne,"Could not clean up partial migration file"),O(ne,"Partial migration cleanup failed",s)}return k(ne,"To resolve this issue:"),k(ne," 1. Ensure you have write permissions to ~/.oss-autopilot/"),k(ne," 2. Check available disk space"),k(ne," 3. Manually copy ./data/state.json to ~/.oss-autopilot/state.json"),k(ne," 4. Or delete ./data/state.json to start fresh"),!1}}function KA(){let e=no();if(!oe.existsSync(e))return null;let t=oe.readdirSync(e).filter(r=>r.startsWith("state-")&&r.endsWith(".json")).sort().reverse();for(let r of t){let n=Sn.join(e,r);try{let s=oe.readFileSync(n,"utf8"),o=JSON.parse(s);if(typeof o=="object"&&o!==null){let c=o;c.version===1&&(o=Ki(c)),o.version===2&&(o=Ji(o)),o.version===3&&(o=Yi(o))}let i=Gt.safeParse(o);if(i.success){let c=i.data;O(ne,`Successfully restored state from backup: ${r}`);let u=Object.keys(c.repoScores).length;O(ne,`Restored state v${c.version}: ${u} repo scores`);let d=jt();return Mr(d,xr(c),384),O(ne,"Restored backup written to main state file"),c}let a=i.error.issues.map(c=>`${c.path.join(".")}: ${c.message}`).join("; ");k(ne,`Backup ${r} failed schema validation: ${a}`),O(ne,`Backup ${r} full validation errors:`,i.error.issues)}catch(s){let o=s instanceof Error?s.message:String(s);k(ne,`Backup ${r} is corrupted (${o}), trying next...`),O(ne,`Backup ${r} parse failed`,s)}}return null}function JA(e){try{let t=e+".rejected-"+Date.now();return oe.copyFileSync(e,t),k(ne,`Previous state preserved at: ${t}`),t}catch(t){return k(ne,`Could not preserve rejected state file: ${I(t)}`),null}}function oo(e,t,r){let n=MA(e,t);n>0&&k(ne,`${r} has ${n} unreadable work claim(s); they were dropped`)}function fm(){bz();let e=jt();try{if(oe.existsSync(e)){let t=Zi(e),r=oe.readFileSync(e,"utf8"),n=JSON.parse(r),s=!1;if(typeof n=="object"&&n!==null){let u=n;u.version===1&&(n=Ki(u),s=!0),n.version===2&&(n=Ji(n),s=!0),n.version===3&&(n=Yi(n),s=!0)}let o=Jp(n);o.length>0&&k(ne,`State file (fields: ${o.join(", ")}) ${Yp}`);let i=Gt.safeParse(n);if(!i.success){let u=i.error.issues.map(f=>`${f.path.join(".")}: ${f.message}`).join("; ");k(ne,`Invalid state file structure: ${u}`),k(ne,"Attempting to restore from backup..."),O(ne,"Full validation errors:",i.error.issues);let d=JA(e),p=`Invalid state file structure: ${u}`,m=KA();if(m){let f=Zi(e);return{state:m,mtimeMs:f,recovery:{source:"backup",rejectedPath:d,reason:p}}}return k(ne,"No valid backup found, starting fresh"),{state:_n(),mtimeMs:0,recovery:{source:"fresh",rejectedPath:d,reason:p}}}s&&(Mr(e,xr(i.data),384),t=Zi(e),O(ne,"Migrated and validated state saved"));let a=i.data;oo(n,a,"State file");let c=Object.keys(a.repoScores).length;return O(ne,`Loaded state v${a.version}: ${c} repo scores tracked`),{state:a,mtimeMs:t}}}catch(t){let r=t?.code;if(r==="EACCES"||r==="EPERM")throw new Error(`Permission denied reading state file (${r}): ${I(t)}. This is an environment problem, not state corruption. Check the ownership and permissions of ~/.oss-autopilot/state.json (e.g. run \`ls -l ~/.oss-autopilot/state.json\` and fix with chown/chmod), then retry.`,{cause:t});k(ne,"Error loading state:",t),k(ne,"Attempting to restore from backup...");let n=oe.existsSync(e)?JA(e):null,s=`Error loading state: ${I(t)}`,o=KA();if(o){let i=Zi(e);return{state:o,mtimeMs:i,recovery:{source:"backup",rejectedPath:n,reason:s}}}return k(ne,"No valid backup found, starting fresh"),{state:_n(),mtimeMs:0,recovery:{source:"fresh",rejectedPath:n,reason:s}}}return O(ne,"No existing state found, initializing..."),{state:_n(),mtimeMs:0}}function Zi(e){try{return oe.statSync(e).mtimeMs}catch(t){return O(ne,`Could not read state file mtime (reload detection will always trigger): ${I(t)}`),0}}function wz(){let e=no();try{let t=oe.readdirSync(e).filter(r=>r.startsWith("state-")).sort().reverse();for(let r of t.slice(10))try{oe.unlinkSync(Sn.join(e,r))}catch(n){k(ne,`Could not delete old backup ${r}:`,I(n))}}catch(t){k(ne,"Could not clean up backups:",I(t))}}function XA(e,t=null){let r=jt(),n=r+".lock",s=no();YA(n);try{if(t!==null&&t>0&&oe.existsSync(r)){let i=Zi(r);if(i!==t)throw new Dr(t,i)}try{if(oe.existsSync(r)){let i=new Date().toISOString().replaceAll(/[.:]/g,"-"),a=Math.random().toString(36).slice(2,8).padEnd(6,"0"),c=Sn.join(s,`state-${i}-${a}.json`);oe.copyFileSync(r,c),oe.chmodSync(c,384),wz()}}catch(i){k(ne,`Could not create backup before save: ${I(i)}`)}Mr(r,xr(e),384);let o=Zi(r);return O(ne,"State saved successfully"),o}finally{QA(n)}}function eT(e){try{let t=jt();if(oe.statSync(t).mtimeMs===e)return null;let n=fm();if(n.recovery)try{n.mtimeMs=oe.statSync(t).mtimeMs}catch(s){O(ne,"Could not re-read mtime after reload (will retry next cycle)",s)}return n}catch(t){return k(ne,`Failed to reload state from disk: ${I(t)}`),null}}var oe,Sn,ne,hz,yu=A(()=>{"use strict";oe=B(require("node:fs"),1),Sn=B(require("node:path"),1);wn();Wi();Kr();ee();ae();ne="state",hz=3e4});function Jr(e,t){return e===void 0||e<t}var HS,Rz,gm,io,ao,Sz,is=A(()=>{"use strict";wn();HS=Kp.parse({}),Rz=Gt.parse({version:4}),gm=xS.options,io=DS.options,ao=LS.options,Sz={beginner:["good first issue","help wanted","easy","up-for-grabs","first-timers-only","beginner"],intermediate:["enhancement","feature","feature-request","contributions welcome"],advanced:["proposal","RFC","accepted","design"]}});function Iz(e){return{repo:e,score:sT,mergedPRCount:0,closedWithoutMergeCount:0,avgResponseDays:null,lastEvaluatedAt:new Date().toISOString(),signals:{hasActiveMaintainers:!0,isResponsive:!1,hasHostileComments:!1}}}function xz(e){let t=sT;if(e.mergedPRCount>0){let r=Math.min(Math.round(Math.log2(e.mergedPRCount+1)*_z),vz);t+=r}if(t-=Math.min(e.closedWithoutMergeCount,kz),e.lastMergedAt){let r=new Date(e.lastMergedAt);isNaN(r.getTime())?k(Qi,`Invalid lastMergedAt date for ${e.repo}: "${e.lastMergedAt}". Skipping recency bonus.`):Math.floor((Date.now()-r.getTime())/864e5)<=Cz&&(t+=Pz)}return e.signals.isResponsive&&(t+=Ez),e.signals.hasHostileComments&&(t-=Az),Math.max(Tz,Math.min($z,t))}function oT(e,t){return e.repoScores[t]}function tT(e){return JSON.stringify([e.mergedPRCount,e.closedWithoutMergeCount,e.avgResponseDays??null,e.lastMergedAt??null,e.signals.hasActiveMaintainers,e.signals.isResponsive,e.signals.hasHostileComments])}function WS(e,t,r){let n=!e.repoScores[t];n&&(e.repoScores[t]=Iz(t));let s=e.repoScores[t],o=tT(s);r.mergedPRCount!==void 0&&(s.mergedPRCount=r.mergedPRCount),r.closedWithoutMergeCount!==void 0&&(s.closedWithoutMergeCount=r.closedWithoutMergeCount),r.avgResponseDays!==void 0&&(s.avgResponseDays=r.avgResponseDays),r.lastMergedAt!==void 0&&(s.lastMergedAt=r.lastMergedAt),r.stargazersCount!==void 0&&(s.stargazersCount=r.stargazersCount),r.language!==void 0&&(s.language=r.language),r.signals&&(s.signals={...s.signals,...r.signals}),s.score=xz(s),(n||tT(s)!==o)&&(s.lastEvaluatedAt=new Date().toISOString()),O(Qi,`Updated repo score for ${t}: ${s.score}/10`)}function iT(e){return Object.values(e.repoScores).filter(t=>t.mergedPRCount>0).sort((t,r)=>r.mergedPRCount-t.mergedPRCount).map(t=>t.repo)}function aT(e){return Object.values(e.repoScores).filter(t=>t.mergedPRCount===0&&t.closedWithoutMergeCount===0).sort((t,r)=>r.score-t.score).map(t=>t.repo)}function cT(e,t){let r=t??e.config.minRepoScoreThreshold;return Object.values(e.repoScores).filter(n=>n.score>=r).sort((n,s)=>s.score-n.score).map(n=>n.repo)}function uT(e,t){let r=t??e.config.minRepoScoreThreshold,n=Date.now();return Object.values(e.repoScores).filter(s=>{if(s.score>r)return!1;let o=n-new Date(s.lastEvaluatedAt).getTime();return Number.isFinite(o)?o<=Oz:(k(Qi,`Invalid lastEvaluatedAt for repo ${s.repo}: "${s.lastEvaluatedAt}", treating as stale`),!1)}).sort((s,o)=>s.score-o.score).map(s=>s.repo)}function rT(e){let t=new Map;for(let r of e){let n=q(r.url);if(!n){k(Qi,`Skipping PR with unparseable URL during reconciliation: "${r.url}"`);continue}let s=`${n.owner}/${n.repo}`;t.set(s,(t.get(s)??0)+1)}return t}function lT(e,t,r){let n=nT(e,rT(t),"mergedPRCount"),s=nT(e,rT(r),"closedWithoutMergeCount");return n||s}function nT(e,t,r){let n=!1;for(let[s,o]of t){let i=e.repoScores[s]?.[r]??0;o>i&&(O(Qi,`Reconciling ${s} ${r}: ${i} \u2192 ${o}`),WS(e,s,{[r]:o}),n=!0)}return n}function dT(e,t){let r=new Set(t.map(o=>o.url)),n=new Map;for(let o of t){let i=q(o.url);!i||!o.title||n.set(`${i.number}\0${o.title}`,`${i.owner}/${i.repo}`)}let s=new Map;for(let o of e){let i=r.has(o.url)||!o.title?null:q(o.url);if(!i)continue;let a=`${i.owner}/${i.repo}`,c=n.get(`${i.number}\0${o.title}`);c&&c!==a&&s.set(a,c)}return s}function pT(e,t,r){let n=`https://github.com/${t}/`,s=`https://github.com/${r}/`,o=a=>{if(!a?.some(d=>d.url.startsWith(n)))return a;let c=new Set;return a.map(d=>{if(!d.url.startsWith(n))return d;let p=s+d.url.slice(n.length);return c.add(p),{...d,url:p}}).filter((d,p)=>!c.has(d.url)||a[p].url.startsWith(n))};e.mergedPRs=o(e.mergedPRs),e.closedPRs=o(e.closedPRs);let i=e.repoScores[t];i&&(Object.hasOwn(e.repoScores,r)||(e.repoScores[r]={...i,repo:r}),delete e.repoScores[t]),O(Qi,`Renamed transferred repo ${t} \u2192 ${r}`)}function mT(e){let t=0,r=0,n=0;for(let i of Object.values(e.repoScores))Jr(i.stargazersCount,e.config.minStars??50)||(n++,t+=i.mergedPRCount,r+=i.closedWithoutMergeCount);let s=t+r,o=s>0?t/s*100:0;return{mergedPRs:t,closedPRs:r,activeIssues:0,trustedProjects:e.config.trustedProjects.length,mergeRate:o.toFixed(1)+"%",totalTracked:n,needsResponse:0}}var Qi,sT,_z,vz,kz,Cz,Pz,Ez,Az,Tz,$z,Oz,VS=A(()=>{"use strict";is();ae();st();Qi="scoring",sT=5,_z=2,vz=5,kz=3,Cz=90,Pz=1,Ez=1,Az=2,Tz=1,$z=10,Oz=720*60*60*1e3});function fT(e){return e?e.etag??e.ETag??null:null}function qS(e,t){try{let r=`${os()}.rejected-${Date.now()}`;return Yr.writeFileSync(r,e,{encoding:"utf8",mode:384}),r}catch(r){return k(Ee,`Could not preserve rejected Gist content for ${t}: ${r instanceof Error?r.message:String(r)}`),null}}var Yr,Ee,ZS,vn,Lz,gT,Mz,Fz,hT,Xi,KS=A(()=>{"use strict";Yr=B(require("node:fs"),1);wn();Wi();yu();Kr();ae();ee();Ee="gist-store";ZS="oss-autopilot-state",vn="state.json",Lz=900*1024,gT=10*1024*1024,Mz="gist.githubusercontent.com",Fz=100*1024,hT=new Map,Xi=class e{gistId=null;cachedFiles=new Map;dirtyFiles=new Set;baselineFiles=new Map;lastFetchedEtag=null;octokit;lastRefreshAt=0;static REFRESH_THROTTLE_MS=3e4;lastRefreshError=null;constructor(t){this.octokit=t}async bootstrap(){try{await this.checkGistScope();let t=this.readLocalGistId();if(t){O(Ee,`Found local Gist ID: ${t}`);try{this.gistId=t;let o=await this.fetchAndCache(t);return{gistId:t,state:o,created:!1}}catch(o){if(o instanceof Oe||zt(o))throw o;k(Ee,`Failed to fetch Gist ${t}, will search/create`,o)}}let r=await this.searchForGist();if(r){O(Ee,`Found Gist via search: ${r}`),this.gistId=r,this.writeLocalGistId(r);let o=await this.fetchAndCache(r);return{gistId:r,state:o,created:!1}}O(Ee,"No existing Gist found, creating new one");let{id:n,state:s}=await this.createGist();return this.writeLocalGistId(n),{gistId:n,state:s,created:!0}}catch(t){if(t instanceof Oe||zt(t))throw t;this.gistId=null,this.lastFetchedEtag=null,k(Ee,"All Gist API paths failed, entering degraded mode",t);let r=os(),n=null;try{if(Yr.existsSync(r)){n=Yr.readFileSync(r,"utf8");let s=JSON.parse(n);if(typeof s=="object"&&s!==null){let i=s;i.version===1&&(s=Ki(i)),s.version===2&&(s=Ji(s)),s.version===3&&(s=Yi(s))}let o=Gt.parse(s);return oo(s,o,"Local state cache"),O(Ee,"Loaded state from local cache in degraded mode"),{gistId:"",state:o,created:!1,degraded:!0}}}catch(s){if(n){let o=qS(n,"local-cache");k(Ee,`Local state cache failed to parse in degraded mode: ${s instanceof Error?s.message:String(s)}. Corrupt cache preserved at: ${o??"(could not preserve)"}`)}else k(Ee,`Failed to read local cache in degraded mode: ${s instanceof Error?s.message:String(s)}`)}return O(Ee,"No local cache found, returning fresh state in degraded mode"),{gistId:"",state:_n(),created:!1,degraded:!0}}}async bootstrapWithMigration(t){try{await this.checkGistScope();let r=this.readLocalGistId();if(r){O(Ee,`bootstrapWithMigration: found local Gist ID: ${r}`);try{this.gistId=r;let i=await this.fetchAndCache(r);return{gistId:r,state:i,created:!1,migrated:!1}}catch(i){if(i instanceof Oe||zt(i))throw i;k(Ee,`bootstrapWithMigration: failed to fetch Gist ${r}, will search/create`,i)}}let n=await this.searchForGist();if(n){O(Ee,`bootstrapWithMigration: found Gist via search: ${n}`),this.gistId=n,this.writeLocalGistId(n);let i=await this.fetchAndCache(n);return{gistId:n,state:i,created:!1,migrated:!1}}O(Ee,"bootstrapWithMigration: no existing Gist found, creating one seeded with local state");let{id:s,state:o}=await this.createGistFromState(t);return this.writeLocalGistId(s),{gistId:s,state:o,created:!0,migrated:!0}}catch(r){if(r instanceof Oe||zt(r))throw r;this.gistId=null,this.lastFetchedEtag=null,k(Ee,"bootstrapWithMigration: all Gist API paths failed, entering degraded mode",r);let n=os(),s=null;try{if(Yr.existsSync(n)){s=Yr.readFileSync(n,"utf8");let o=JSON.parse(s);if(typeof o=="object"&&o!==null){let a=o;a.version===1&&(o=Ki(a)),o.version===2&&(o=Ji(o)),o.version===3&&(o=Yi(o))}let i=Gt.parse(o);return oo(o,i,"Local state cache"),O(Ee,"bootstrapWithMigration: loaded state from local cache in degraded mode"),{gistId:"",state:i,created:!1,degraded:!0,migrated:!1}}}catch(o){if(s){let i=qS(s,"local-cache");k(Ee,`bootstrapWithMigration: local cache failed to parse: ${o instanceof Error?o.message:String(o)}. Corrupt cache preserved at: ${i??"(could not preserve)"}`)}else k(Ee,`bootstrapWithMigration: failed to read local cache: ${o instanceof Error?o.message:String(o)}`)}return O(Ee,"bootstrapWithMigration: no local cache found, returning existing state in degraded mode"),{gistId:"",state:t,created:!1,degraded:!0,migrated:!1}}}getGistId(){return this.gistId}markDirty(t){this.dirtyFiles.add(t)}getDocument(t){return this.cachedFiles.get(t)??null}setDocument(t,r){this.cachedFiles.set(t,r),this.markDirty(t)}listDocuments(t){let r=[];for(let n of this.cachedFiles.keys())n.startsWith(t)&&r.push(n);return r}setState(t){this.cachedFiles.set(vn,t),this.markDirty(vn)}async push(){if(this.dirtyFiles.size===0)return!0;if(this.gistId===null)throw new Error("GistStateStore: cannot push before bootstrap \u2014 gistId is null");this.checkPushSize();let t=()=>{let o={};for(let i of this.dirtyFiles){let a=this.cachedFiles.get(i);a!==void 0&&(o[i]={content:a})}return o},r=async()=>{try{let o={gist_id:this.gistId,files:t()},i=await this.octokit.gists.update(o),a=fT(i.headers);return a&&(this.lastFetchedEtag=a),{ok:!0}}catch(o){return{ok:!1,status:o.status,err:o}}};if(this.dirtyFiles.has(vn)){let o={};for(let f of this.dirtyFiles){let g=this.cachedFiles.get(f);g!==void 0&&(o[f]=g)}let i=new Map(this.cachedFiles),a=new Map(this.baselineFiles),c=this.lastFetchedEtag,u=a.get(vn),d=()=>{for(let[f,g]of Object.entries(o))this.cachedFiles.set(f,g)},p=()=>{this.cachedFiles.clear();for(let[f,g]of i)this.cachedFiles.set(f,g);this.baselineFiles=a,this.lastFetchedEtag=c,d()};try{await this.fetchAndCache(this.gistId)}catch(f){throw k(Ee,`Pre-write re-read failed: ${I(f)}`),p(),f instanceof gu||f instanceof Lr||zt(f)?f:new Xt(c,null)}let m=this.cachedFiles.get(vn);if(u!==m){k(Ee,"state.json changed remotely since our last fetch; surfacing GistConcurrencyError instead of clobbering (#1235, #1510)");let f=this.lastFetchedEtag;throw p(),new Xt(c,f)}d()}let n=await r();if(!n.ok&&(O(Ee,`push failed on first attempt, retrying: ${n.err}`),n=await r(),!n.ok))return k(Ee,`push failed after retry, giving up: ${n.err}`),!1;if(this.dirtyFiles.clear(),this.baselineFiles=new Map(this.cachedFiles),this.cachedFiles.get(vn))try{let o=this.parseStateFromCache();this.writeLocalStateCache(o)}catch(o){O(Ee,`push succeeded but local cache write failed: ${o}`)}return!0}async refreshFromGist(t={}){if(!this.gistId)return{status:"no-gist"};let r=Date.now(),n=r-this.lastRefreshAt;if(n<e.REFRESH_THROTTLE_MS&&!t.force)return{status:"throttled",sinceLastMs:n};this.lastRefreshAt=r;try{return await this.fetchAndCache(this.gistId),this.lastRefreshError=null,{status:"refreshed"}}catch(s){let o=s instanceof Error?s:new Error(String(s));return k(Ee,`refreshFromGist failed: ${o.message}`),this.lastRefreshError=o,{status:"error",error:o}}}checkPushSize(){for(let t of this.dirtyFiles){let r=this.cachedFiles.get(t);if(r===void 0)continue;let n=Buffer.byteLength(r,"utf8");if(n>gT)throw new Lr(`Refusing to push Gist file ${t}: ${n} bytes exceeds the ${gT}-byte limit the Gist API can serve back. The local change is kept in memory but was not synced.`);if(n>Lz){let s=Math.floor(n/Fz);(hT.get(t)??-1)<s&&(hT.set(t,s),k(Ee,`Gist file ${t} is ${n} bytes, near or past the 1 MB the Gist API returns inline. Reads fall back to raw_url, which works up to 10 MB; to stay well under that, trim large state fields (repoScores and searchSeen are usually the biggest).`))}}}async checkGistScope(){try{await this.octokit.gists.list({per_page:1,page:1})}catch(t){if(zt(t))throw t;let r=t.status;throw r===401||r===403?new qi:t}}async fetchAndCache(t){let r=await this.octokit.gists.get({gist_id:t});this.gistId=t;let n=new Map;for(let[o,i]of Object.entries(r.data.files)){if(!i)continue;let a=i.truncated?await this.fetchRawContent(o,i.raw_url):i.content;a!=null&&n.set(o,a)}this.lastFetchedEtag=fT(r.headers),this.cachedFiles.clear();for(let[o,i]of n)this.cachedFiles.set(o,i);this.baselineFiles=new Map(this.cachedFiles);let s=this.parseStateFromCache();return this.writeLocalStateCache(s),s}async fetchRawContent(t,r){let n=a=>new Lr(`Gist file ${t} is larger than the 1 MB the Gist API returns inline and its full content could not be read from raw_url (${a}). Local state was left unchanged.`);if(!this.octokit.request)throw n("no HTTP client available");if(!r)throw n("the API returned no raw_url");let s=URL.canParse(r)?new URL(r):void 0;if((s?.protocol==="https:"?s.hostname:"")!==Mz)throw n("unexpected raw_url host");let i;try{({data:i}=await this.octokit.request({method:"GET",url:r}))}catch(a){throw zt(a)||pm(a)?a:n(I(a))}if(typeof i!="string")throw n("response body was not text");return i}parseStateFromCache(){let t=this.cachedFiles.get(vn);if(!t)return O(Ee,"No state.json found in Gist, using fresh state"),_n();try{let r=JSON.parse(t);if(typeof r=="object"&&r!==null){let o=r;o.version===1&&(r=Ki(o)),r.version===2&&(r=Ji(r)),r.version===3&&(r=Yi(r))}let n=Jp(r);n.length>0&&k(Ee,`Gist state (fields: ${n.join(", ")}) ${Yp}`);let s=Gt.parse(r);return oo(r,s,"Gist state"),s}catch(r){let n=qS(t,this.gistId??"unknown");throw k(Ee,`Gist state.json failed to parse \u2014 refusing to overwrite with fresh state. Corrupt content preserved at: ${n??"(could not preserve)"}`),new gu(this.gistId??"unknown",n,r)}}async searchForGist(){try{for(let r=1;r<=10;r++){let{data:n}=await this.octokit.gists.list({per_page:100,page:r});if(n.length===0)break;let s=n.find(o=>o.description===ZS);if(s)return s.id}}catch(t){if(zt(t))throw t;k(Ee,"Failed to search Gists by description",t)}return null}async createGist(){let t=_n(),r=xr(t),{data:n}=await this.octokit.gists.create({description:ZS,public:!1,files:{[vn]:{content:r}}});this.gistId=n.id,this.cachedFiles.clear();for(let[s,o]of Object.entries(n.files))o&&o.content!=null&&this.cachedFiles.set(s,o.content);return this.baselineFiles=new Map(this.cachedFiles),this.writeLocalStateCache(t),{id:n.id,state:t}}async createGistFromState(t){let r=xr(t),{data:n}=await this.octokit.gists.create({description:ZS,public:!1,files:{[vn]:{content:r}}});this.gistId=n.id,this.cachedFiles.clear();for(let[s,o]of Object.entries(n.files))o&&o.content!=null&&this.cachedFiles.set(s,o.content);return this.baselineFiles=new Map(this.cachedFiles),this.writeLocalStateCache(t),{id:n.id,state:t}}readLocalGistId(){try{let t=so();if(Yr.existsSync(t))return Yr.readFileSync(t,"utf8").trim()||null}catch(t){O(Ee,"Could not read local Gist ID file",t)}return null}writeLocalGistId(t){try{let r=so();Mr(r,t,384),O(Ee,`Wrote Gist ID to ${r}`)}catch(r){k(Ee,`Failed to write local Gist ID file: ${r}`)}}writeLocalStateCache(t){try{let r=os();Mr(r,xr(t),384),O(Ee,`Wrote state cache to ${r}`)}catch(r){k(Ee,`Failed to write local state cache: ${r}`)}}}});function wu(e){if(!e.includes("/"))throw new Cr(`Invalid repo identifier "${e}". Expected "owner/repo" format.`,"INVALID_REPO_ID");let[t,r]=e.split("/",2);return`${ea}${t}--${r}${JS}`}function YS(e){if(!e.startsWith(ea)||!e.endsWith(JS))return null;let t=e.slice(ea.length,e.length-JS.length),r=t.indexOf("--");if(r===-1)return null;let n=t.slice(0,r),s=t.slice(r+2);return!n||!s?null:`${n}/${s}`}function yT(e,t){if(!e)return null;let r=e.getDocument(wu(t));return r===null||r===""?null:r}function bT(e,t,r){if(!e)throw new as;let n=Buffer.byteLength(r,"utf8");if(n>hm)throw new bu(n);e.setDocument(wu(t),r)}function wT(e,t){if(!e)throw new as;e.setDocument(wu(t),"")}function RT(e){if(!e)return[];let t=e.listDocuments(ea),r=[];for(let n of t){let s=YS(n);if(!s)continue;let o=e.getDocument(n);o===null||o===""||r.push(s)}return r.sort()}var ea,hm,JS,as,bu,QS=A(()=>{"use strict";ee();ea="guidelines--",hm=8192,JS=".md";as=class extends Cr{constructor(t){super(t??"Per-repo guidelines require Gist persistence. Run `oss-autopilot setup` to enable Gist sync, then retry.","GUIDELINES_NOT_AVAILABLE"),this.name="GuidelinesNotAvailableError"}},bu=class extends Cr{constructor(t,r=hm){super(`Guidelines content is ${t} bytes, exceeding the ${r}-byte cap. Trim or split across categories.`,"GUIDELINES_TOO_LARGE"),this.name="GuidelinesTooLargeError"}}});function ta(e,t={}){return`Gist persistence is configured but ${typeof e=="string"?Gz[e]:e.reason}; writes are LOCAL-ONLY and may be overwritten by the next successful Gist sync.${t.retryHint?` ${t.retryHint}`:""}`}var Gz,XS=A(()=>{"use strict";Gz={"no-token":"no GitHub token was available","state-unreadable":"the state file could not be read","init-fallback":"initialization hit a transient network failure","configured-but-local":"this process is running local-only (Gist init has not succeeded)","bootstrap-degraded":"the Gist bootstrap fell back to the local cache (reads may be stale and pushes are failing)"}});function cs(){return typeof navigator=="object"&&"userAgent"in navigator?navigator.userAgent:typeof process=="object"&&process.version!==void 0?`Node.js/${process.version.substr(1)} (${process.platform}; ${process.arch})`:"<environment undetectable>"}var Ru=A(()=>{});function ym(e,t,r,n){if(typeof r!="function")throw new Error("method for before hook must be a function");return n||(n={}),Array.isArray(t)?t.reverse().reduce((s,o)=>ym.bind(null,e,o,s,n),r)():Promise.resolve().then(()=>e.registry[t]?e.registry[t].reduce((s,o)=>o.hook.bind(null,s,n),r)():r(n))}var ST=A(()=>{});function _T(e,t,r,n){let s=n;e.registry[r]||(e.registry[r]=[]),t==="before"&&(n=(o,i)=>Promise.resolve().then(s.bind(null,i)).then(o.bind(null,i))),t==="after"&&(n=(o,i)=>{let a;return Promise.resolve().then(o.bind(null,i)).then(c=>(a=c,s(a,i))).then(()=>a)}),t==="error"&&(n=(o,i)=>Promise.resolve().then(o.bind(null,i)).catch(a=>s(a,i))),e.registry[r].push({hook:n,orig:s})}var vT=A(()=>{});function kT(e,t,r){if(!e.registry[t])return;let n=e.registry[t].map(s=>s.orig).indexOf(r);n!==-1&&e.registry[t].splice(n,1)}var CT=A(()=>{});function AT(e,t,r){let n=ET(kT,null).apply(null,r?[t,r]:[t]);e.api={remove:n},e.remove=n,["before","error","after","wrap"].forEach(s=>{let o=r?[t,s,r]:[t,s];e[s]=e.api[s]=ET(_T,null).apply(null,o)})}function Uz(){let e=Symbol("Singular"),t={registry:{}},r=ym.bind(null,t,e);return AT(r,t,e),r}function jz(){let e={registry:{}},t=ym.bind(null,e);return AT(t,e),t}var PT,ET,TT,$T=A(()=>{ST();vT();CT();PT=Function.bind,ET=PT.bind(PT);TT={Singular:Uz,Collection:jz}});function Wz(e){return e?Object.keys(e).reduce((t,r)=>(t[r.toLowerCase()]=e[r],t),{}):{}}function Vz(e){if(typeof e!="object"||e===null||Object.prototype.toString.call(e)!=="[object Object]")return!1;let t=Object.getPrototypeOf(e);if(t===null)return!0;let r=Object.prototype.hasOwnProperty.call(t,"constructor")&&t.constructor;return typeof r=="function"&&r instanceof r&&Function.prototype.call(r)===Function.prototype.call(e)}function xT(e,t){let r=Object.assign({},e);return Object.keys(t).forEach(n=>{Vz(t[n])?n in e?r[n]=xT(e[n],t[n]):Object.assign(r,{[n]:t[n]}):Object.assign(r,{[n]:t[n]})}),r}function OT(e){for(let t in e)e[t]===void 0&&delete e[t];return e}function t_(e,t,r){if(typeof t=="string"){let[s,o]=t.split(" ");r=Object.assign(o?{method:s,url:o}:{url:s},r)}else r=Object.assign({},t);r.headers=Wz(r.headers),OT(r),OT(r.headers);let n=xT(e||{},r);return r.url==="/graphql"&&(e&&e.mediaType.previews?.length&&(n.mediaType.previews=e.mediaType.previews.filter(s=>!n.mediaType.previews.includes(s)).concat(n.mediaType.previews)),n.mediaType.previews=(n.mediaType.previews||[]).map(s=>s.replace(/-preview/,""))),n}function qz(e,t){let r=/\?/.test(e)?"&":"?",n=Object.keys(t);return n.length===0?e:e+r+n.map(s=>s==="q"?"q="+t.q.split("+").map(encodeURIComponent).join("+"):`${s}=${encodeURIComponent(t[s])}`).join("&")}function Kz(e){return e.replace(/(?:^\W+)|(?:(?<!\W)\W+$)/g,"").split(/,/)}function Jz(e){let t=e.match(Zz);return t?t.map(Kz).reduce((r,n)=>r.concat(n),[]):[]}function IT(e,t){let r={__proto__:null};for(let n of Object.keys(e))t.indexOf(n)===-1&&(r[n]=e[n]);return r}function DT(e){return e.split(/(%[0-9A-Fa-f]{2})/g).map(function(t){return/%[0-9A-Fa-f]/.test(t)||(t=encodeURI(t).replace(/%5B/g,"[").replace(/%5D/g,"]")),t}).join("")}function na(e){return encodeURIComponent(e).replace(/[!'()*]/g,function(t){return"%"+t.charCodeAt(0).toString(16).toUpperCase()})}function Su(e,t,r){return t=e==="+"||e==="#"?DT(t):na(t),r?na(r)+"="+t:t}function ra(e){return e!=null}function e_(e){return e===";"||e==="&"||e==="?"}function Yz(e,t,r,n){var s=e[r],o=[];if(ra(s)&&s!=="")if(typeof s=="string"||typeof s=="number"||typeof s=="bigint"||typeof s=="boolean")s=s.toString(),n&&n!=="*"&&(s=s.substring(0,parseInt(n,10))),o.push(Su(t,s,e_(t)?r:""));else if(n==="*")Array.isArray(s)?s.filter(ra).forEach(function(i){o.push(Su(t,i,e_(t)?r:""))}):Object.keys(s).forEach(function(i){ra(s[i])&&o.push(Su(t,s[i],i))});else{let i=[];Array.isArray(s)?s.filter(ra).forEach(function(a){i.push(Su(t,a))}):Object.keys(s).forEach(function(a){ra(s[a])&&(i.push(na(a)),i.push(Su(t,s[a].toString())))}),e_(t)?o.push(na(r)+"="+i.join(",")):i.length!==0&&o.push(i.join(","))}else t===";"?ra(s)&&o.push(na(r)):s===""&&(t==="&"||t==="?")?o.push(na(r)+"="):s===""&&o.push("");return o}function Qz(e){return{expand:Xz.bind(null,e)}}function Xz(e,t){var r=["+","#",".","/",";","?","&"];return e=e.replace(/\{([^\{\}]+)\}|([^\{\}]+)/g,function(n,s,o){if(s){let a="",c=[];if(r.indexOf(s.charAt(0))!==-1&&(a=s.charAt(0),s=s.substr(1)),s.split(/,/g).forEach(function(u){var d=/([^:\*]*)(?::(\d+)|(\*))?/.exec(u);c.push(Yz(t,a,d[1],d[2]||d[3]))}),a&&a!=="+"){var i=",";return a==="?"?i="&":a!=="#"&&(i=a),(c.length!==0?a:"")+c.join(i)}else return c.join(",")}else return DT(o)}),e==="/"?e:e.replace(/\/$/,"")}function LT(e){let t=e.method.toUpperCase(),r=(e.url||"/").replace(/:([a-z]\w+)/g,"{$1}"),n=Object.assign({},e.headers),s,o=IT(e,["method","baseUrl","url","headers","request","mediaType"]),i=Jz(r);r=Qz(r).expand(o),/^http/.test(r)||(r=e.baseUrl+r);let a=Object.keys(e).filter(d=>i.includes(d)).concat("baseUrl"),c=IT(o,a);if(!/application\/octet-stream/i.test(n.accept)&&(e.mediaType.format&&(n.accept=n.accept.split(/,/).map(d=>d.replace(/application\/vnd(\.\w+)(\.v3)?(\.\w+)?(\+json)?$/,`application/vnd$1$2.${e.mediaType.format}`)).join(",")),r.endsWith("/graphql")&&e.mediaType.previews?.length)){let d=n.accept.match(/(?<![\w-])[\w-]+(?=-preview)/g)||[];n.accept=d.concat(e.mediaType.previews).map(p=>{let m=e.mediaType.format?`.${e.mediaType.format}`:"+json";return`application/vnd.github.${p}-preview${m}`}).join(",")}return["GET","HEAD"].includes(t)?r=qz(r,c):"data"in c?s=c.data:Object.keys(c).length&&(s=c),!n["content-type"]&&typeof s<"u"&&(n["content-type"]="application/json; charset=utf-8"),["PATCH","PUT"].includes(t)&&typeof s>"u"&&(s=""),Object.assign({method:t,url:r,headers:n},typeof s<"u"?{body:s}:null,e.request?{request:e.request}:null)}function e1(e,t,r){return LT(t_(e,t,r))}function MT(e,t){let r=t_(e,t),n=e1.bind(null,r);return Object.assign(n,{DEFAULTS:r,defaults:MT.bind(null,r),merge:t_.bind(null,r),parse:LT})}var zz,Bz,Hz,Zz,FT,NT=A(()=>{Ru();zz="0.0.0-development",Bz=`octokit-endpoint.js/${zz} ${cs()}`,Hz={method:"GET",baseUrl:"https://api.github.com",headers:{accept:"application/vnd.github.v3+json","user-agent":Bz},mediaType:{format:""}};Zz=/\{[^{}}]+\}/g;FT=MT(null,Hz)});var zT=CC((bY,_u)=>{"use strict";var Rm=function(){};Rm.prototype=Object.create(null);var bm=/; *([!#$%&'*+.^\w`|~-]+)=("(?:[\v\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\v\u0020-\u00ff])*"|[!#$%&'*+.^\w`|~-]+) */gu,wm=/\\([\v\u0020-\u00ff])/gu,GT=/^[!#$%&'*+.^\w|~-]+\/[!#$%&'*+.^\w|~-]+$/u,co={type:"",parameters:new Rm};Object.freeze(co.parameters);Object.freeze(co);function UT(e){if(typeof e!="string")throw new TypeError("argument header is required and must be a string");let t=e.indexOf(";"),r=t!==-1?e.slice(0,t).trim():e.trim();if(GT.test(r)===!1)throw new TypeError("invalid media type");let n={type:r.toLowerCase(),parameters:new Rm};if(t===-1)return n;let s,o,i;for(bm.lastIndex=t;o=bm.exec(e);){if(o.index!==t)throw new TypeError("invalid parameter format");t+=o[0].length,s=o[1].toLowerCase(),i=o[2],i[0]==='"'&&(i=i.slice(1,i.length-1),wm.test(i)&&(i=i.replace(wm,"$1"))),n.parameters[s]=i}if(t!==e.length)throw new TypeError("invalid parameter format");return n}function jT(e){if(typeof e!="string")return co;let t=e.indexOf(";"),r=t!==-1?e.slice(0,t).trim():e.trim();if(GT.test(r)===!1)return co;let n={type:r.toLowerCase(),parameters:new Rm};if(t===-1)return n;let s,o,i;for(bm.lastIndex=t;o=bm.exec(e);){if(o.index!==t)return co;t+=o[0].length,s=o[1].toLowerCase(),i=o[2],i[0]==='"'&&(i=i.slice(1,i.length-1),wm.test(i)&&(i=i.replace(wm,"$1"))),n.parameters[s]=i}return t!==e.length?co:n}_u.exports.default={parse:UT,safeParse:jT};_u.exports.parse=UT;_u.exports.safeParse=jT;_u.exports.defaultContentType=co});var t1,WT,r_,BT,r1,n1,s1,VT,o1,i1,a1,qT,HT,c1,u1,ZT,KT=A(()=>{t1=/^-?\d+$/,WT=/^-?\d+n+$/,r_=JSON.stringify,BT=JSON.parse,r1=/^-?\d+n$/,n1=/([\[:])?"(-?\d+)n"($|([\\n]|\s)*(\s|[\\n])*[,\}\]])/g,s1=/([\[:])?("-?\d+n+)n("$|"([\\n]|\s)*(\s|[\\n])*[,\}\]])/g,VT=(e,t,r)=>"rawJSON"in JSON?r_(e,(i,a)=>typeof a=="bigint"?JSON.rawJSON(a.toString()):typeof t=="function"?t(i,a):(Array.isArray(t)&&t.includes(i),a),r):e?r_(e,(i,a)=>typeof a=="string"&&!!a.match(WT)||typeof a=="bigint"?a.toString()+"n":typeof t=="function"?t(i,a):(Array.isArray(t)&&t.includes(i),a),r).replace(n1,"$1$2$3").replace(s1,"$1$2$3"):r_(e,t,r),o1=()=>JSON.parse("1",(e,t,r)=>!!r&&r.source==="1"),i1=(e,t,r,n)=>typeof t=="string"&&t.match(r1)?BigInt(t.slice(0,-1)):typeof t=="string"&&t.match(WT)?t.slice(0,-1):typeof n!="function"?t:n(e,t,r),a1=(e,t)=>JSON.parse(e,(r,n,s)=>{let o=typeof n=="number"&&(n>Number.MAX_SAFE_INTEGER||n<Number.MIN_SAFE_INTEGER),i=s&&t1.test(s.source);return o&&i?BigInt(s.source):typeof t!="function"?n:t(r,n,s)}),qT=Number.MAX_SAFE_INTEGER.toString(),HT=qT.length,c1=/"(?:\\.|[^"])*"|-?(0|[1-9][0-9]*)(\.[0-9]+)?([eE][+-]?[0-9]+)?/g,u1=/^"-?\d+n+"$/,ZT=(e,t)=>{if(!e)return BT(e,t);if(o1())return a1(e,t);let r=e.replace(c1,(n,s,o,i)=>{let a=n[0]==='"';if(a&&!!n.match(u1))return n.substring(0,n.length-1)+'n"';let u=o||i,d=s&&(s.length<HT||s.length===HT&&s<=qT);return a||u||d?n:'"'+n+'n"'});return BT(r,(n,s,o)=>i1(n,s,o,t))}});var kn,n_=A(()=>{kn=class extends Error{name;status;request;response;constructor(t,r,n){super(t,{cause:n.cause}),this.name="HttpError",this.status=Number.parseInt(r),Number.isNaN(this.status)&&(this.status=0);"response"in n&&(this.response=n.response);let s=Object.assign({},n.request);n.request.headers.authorization&&(s.headers=Object.assign({},n.request.headers,{authorization:n.request.headers.authorization.replace(/(?<! ) .*$/," [REDACTED]")})),s.url=s.url.replace(/\bclient_secret=\w+/g,"client_secret=[REDACTED]").replace(/\baccess_token=\w+/g,"access_token=[REDACTED]"),this.request=s}}});function p1(e){if(typeof e!="object"||e===null||Object.prototype.toString.call(e)!=="[object Object]")return!1;let t=Object.getPrototypeOf(e);if(t===null)return!0;let r=Object.prototype.hasOwnProperty.call(t,"constructor")&&t.constructor;return typeof r=="function"&&r instanceof r&&Function.prototype.call(r)===Function.prototype.call(e)}async function YT(e){let t=e.request?.fetch||globalThis.fetch;if(!t)throw new Error("fetch is not set. Please pass a fetch implementation as new Octokit({ request: { fetch }}). Learn more at https://github.com/octokit/octokit.js/#fetch-missing");let r=e.request?.log||console,n=e.request?.parseSuccessResponseBody!==!1,s=p1(e.body)||Array.isArray(e.body)?VT(e.body):e.body,o=Object.fromEntries(Object.entries(e.headers).map(([p,m])=>[p,String(m)])),i;try{i=await t(e.url,{method:e.method,body:s,redirect:e.request?.redirect,headers:o,signal:e.request?.signal,...e.body&&{duplex:"half"}})}catch(p){let m="Unknown Error";if(p instanceof Error){if(p.name==="AbortError")throw p.status=500,p;m=p.message,p.name==="TypeError"&&"cause"in p&&(p.cause instanceof Error?m=p.cause.message:typeof p.cause=="string"&&(m=p.cause))}let f=new kn(m,500,{request:e});throw f.cause=p,f}let a=i.status,c=i.url,u={};for(let[p,m]of i.headers)u[p]=m;let d={url:c,status:a,headers:u,data:""};if("deprecation"in u){let p=u.link&&u.link.match(/<([^<>]+)>; rel="deprecation"/),m=p&&p.pop();r.warn(`[@octokit/request] "${e.method} ${e.url}" is deprecated. It is scheduled to be removed on ${u.sunset}${m?`. See ${m}`:""}`)}if(a===204||a===205)return d;if(e.method==="HEAD"){if(a<400)return d;throw new kn(i.statusText,a,{response:d,request:e})}if(a===304)throw d.data=await s_(i),new kn("Not modified",a,{response:d,request:e});if(a>=400)throw d.data=await s_(i),new kn(f1(d.data),a,{response:d,request:e});return d.data=n?await s_(i):i.body,d}async function s_(e){let t=e.headers.get("content-type");if(!t)return e.text().catch(JT);let r=(0,QT.safeParse)(t);if(m1(r)){let n="";try{return n=await e.text(),ZT(n)}catch{return n}}else return r.type.startsWith("text/")||r.parameters.charset?.toLowerCase()==="utf-8"?e.text().catch(JT):e.arrayBuffer().catch(()=>new ArrayBuffer(0))}function m1(e){return e.type==="application/json"||e.type==="application/scim+json"}function f1(e){if(typeof e=="string")return e;if(e instanceof ArrayBuffer)return"Unknown error";if("message"in e){let t="documentation_url"in e?` - ${e.documentation_url}`:"";return Array.isArray(e.errors)?`${e.message}: ${e.errors.map(r=>JSON.stringify(r)).join(", ")}${t}`:`${e.message}${t}`}return`Unknown error: ${JSON.stringify(e)}`}function o_(e,t){let r=e.defaults(t);return Object.assign(function(s,o){let i=r.merge(s,o);if(!i.request||!i.request.hook)return YT(r.parse(i));let a=(c,u)=>YT(r.parse(r.merge(c,u)));return Object.assign(a,{endpoint:r,defaults:o_.bind(null,r)}),i.request.hook(a,i)},{endpoint:r,defaults:o_.bind(null,r)})}var QT,l1,d1,JT,vu,i_=A(()=>{NT();Ru();QT=B(zT(),1);KT();n_();l1="10.0.8",d1={headers:{"user-agent":`octokit-request.js/${l1} ${cs()}`}};JT=()=>"";vu=o_(FT,d1);});function h1(e){return`Request failed due to following response errors:
@@ -75,7 +75,7 @@ Could not preserve the rejected content; do not push without inspecting the Gist
75
75
  onRateLimit: (retryAfter, options) => {/* ... */}
76
76
  }
77
77
  })
78
- `);let u=!1,d=()=>{if(u)return;u=!0,Fr.global==null&&U1(n,a),c.global=c.global??Fr.global,c.auth=c.auth??Fr.auth,c.search=c.search??Fr.search,c.write=c.write??Fr.write,c.notifications=c.notifications??Fr.notifications,c.retryLimiter=c.retryLimiter??new n;let p={},m=new n.Events(p);p.on("secondary-limit",c.onSecondaryRateLimit),p.on("rate-limit",c.onRateLimit),p.on("error",f=>e.log.warn("Error in throttling-plugin limit handler",f)),c.retryLimiter.on("failed",async function(f,g){let[y,b,R]=g.args,{pathname:h}=new URL(R.url,"http://github.test");if(!(h.startsWith("/graphql")&&f.status!==401||f.status===403||f.status===429))return;let S=~~b.retryCount;b.retryCount=S,R.request.retryCount=S;let{wantRetry:w,retryAfter:P=0}=await(async function(){if(/\bsecondary rate\b/i.test(f.message)){let C=Number(f.response.headers["retry-after"])||y.fallbackSecondaryRateRetryAfter;return{wantRetry:await m.trigger("secondary-limit",C,R,e,S),retryAfter:C}}if(f.response.headers!=null&&f.response.headers["x-ratelimit-remaining"]==="0"||(f.response.data?.errors??[]).some(C=>C.type==="RATE_LIMITED")){let C=new Date(~~f.response.headers["x-ratelimit-reset"]*1e3).getTime(),E=Math.max(Math.ceil((C-Date.now())/1e3)+1,0);return{wantRetry:await m.trigger("rate-limit",E,R,e,S),retryAfter:E}}return{}})();if(w)return b.retryCount++,P*y.retryAfterBaseValue})};return e.hook.wrap("request",(p,m)=>(d(),L1(c,p,m))),{}}var k$,D1,R_,N1,v$,C$,Fr,U1,S_=A(()=>{k$=B(w_(),1),D1="0.0.0-development",R_=()=>Promise.resolve();N1=["/orgs/{org}/invitations","/orgs/{org}/invitations/{invitation_id}","/orgs/{org}/teams/{team_slug}/discussions","/orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments","/repos/{owner}/{repo}/collaborators/{username}","/repos/{owner}/{repo}/commits/{commit_sha}/comments","/repos/{owner}/{repo}/issues","/repos/{owner}/{repo}/issues/{issue_number}/comments","/repos/{owner}/{repo}/issues/{issue_number}/sub_issue","/repos/{owner}/{repo}/issues/{issue_number}/sub_issues/priority","/repos/{owner}/{repo}/pulls","/repos/{owner}/{repo}/pulls/{pull_number}/comments","/repos/{owner}/{repo}/pulls/{pull_number}/comments/{comment_id}/replies","/repos/{owner}/{repo}/pulls/{pull_number}/merge","/repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers","/repos/{owner}/{repo}/pulls/{pull_number}/reviews","/repos/{owner}/{repo}/releases","/teams/{team_id}/discussions","/teams/{team_id}/discussions/{discussion_number}/comments"];v$=G1(N1),C$=v$.test.bind(v$),Fr={},U1=function(e,t){Fr.global=new e.Group({id:"octokit-global",maxConcurrent:10,...t}),Fr.auth=new e.Group({id:"octokit-auth",maxConcurrent:1,...t}),Fr.search=new e.Group({id:"octokit-search",maxConcurrent:1,minTime:2e3,...t}),Fr.write=new e.Group({id:"octokit-write",maxConcurrent:1,minTime:1e3,...t}),Fr.notifications=new e.Group({id:"octokit-notifications",maxConcurrent:1,minTime:3e3,...t})};sa.VERSION=D1;sa.triggersNotification=C$});function z1(e){return e.request!==void 0}async function P$(e,t,r,n){if(!z1(r)||!r?.request.request)throw r;if(r.status>=400&&!e.doNotRetry.includes(r.status)){let s=n.request.retries!=null?n.request.retries:e.retries,o=Math.pow((n.request.retryCount||0)+1,2);throw t.retry.retryRequest(r,s,o)}throw r}async function B1(e,t,r,n){let s=new E$.default;return s.on("failed",function(o,i){let a=~~o.request.request?.retries,c=~~o.request.request?.retryAfter;if(n.request.retryCount=i.retryCount+1,a>i.retryCount)return c*e.retryAfterBaseValue}),s.schedule(H1.bind(null,e,t,r),n)}async function H1(e,t,r,n){let s=await r(n);if(s.data&&s.data.errors&&s.data.errors.length>0&&/Something went wrong while executing your query/.test(s.data.errors[0].message)){let o=new kn(s.data.errors[0].message,500,{request:n,response:s});return P$(e,t,o,n)}return s}function ku(e,t){let r=Object.assign({enabled:!0,retryAfterBaseValue:1e3,doNotRetry:[400,401,403,404,410,422,451],retries:3},t.retry),n={retry:{retryRequest:(s,o,i)=>(s.request.request=Object.assign({},s.request.request,{retries:o,retryAfter:i}),s)}};return r.enabled&&(e.hook.error("request",P$.bind(null,r,n)),e.hook.wrap("request",B1.bind(null,r,n))),n}var E$,j1,__=A(()=>{E$=B(w_(),1);n_();j1="0.0.0-development";ku.VERSION=j1});var $$={};re($$,{checkRateLimit:()=>v_,getOctokit:()=>we,getRateLimitCallbacks:()=>T$});function Cm(e){return e.toLocaleTimeString("en-US",{hour12:!1})}function T$(){return{onRateLimit:(e,t,r,n)=>{let s=t,o=new Date(Date.now()+e*1e3);return n<2?(k(vm,`Rate limit hit (retry ${n+1}/2, waiting ${e}s, resets at ${Cm(o)}) \u2014 ${s.method} ${s.url}`),!0):(k(vm,`Rate limit exceeded, not retrying \u2014 ${s.method} ${s.url} (resets at ${Cm(o)})`),!1)},onSecondaryRateLimit:(e,t,r,n)=>{let s=t,o=new Date(Date.now()+e*1e3);return n<3?(k(vm,`Secondary rate limit hit (retry ${n+1}/3, waiting ${e}s, resets at ${Cm(o)}) \u2014 ${s.method} ${s.url}`),!0):(k(vm,`Secondary rate limit exceeded, not retrying \u2014 ${s.method} ${s.url} (resets at ${Cm(o)})`),!1)}}}function we(e){if(km&&A$===e)return km;let t=T$();return km=new W1({auth:e,throttle:t,retry:{doNotRetry:[400,401,403,404,410,422,429,451]}}),A$=e,km}async function v_(e){let t=we(e),{data:r}=await t.rateLimit.get(),n=r.resources.search;return{remaining:n.remaining,limit:n.limit,resetAt:new Date(n.reset*1e3).toISOString()}}var vm,W1,km,A$,lo=A(()=>{"use strict";h_();S_();__();ae();vm="github",W1=_m.plugin(ku,sa),km=null,A$=null});function I$(e,t){let r=[],n=0;for(let s of e){if(q(s.url)===null){k(Fe,`Dropping ${t} PR with invalid URL: ${s.url}`),n++;continue}r.push(s)}return{valid:r,dropped:n}}function x$(e,t){let r=!1;for(let n of V1)t[n]!==void 0&&e[n]===void 0&&(e[n]=t[n],r=!0);return r}async function Re(e,t,r){if(!e.isGistMode())return null;r?.();try{return await D$(e,t)}catch(n){return n instanceof Xt&&r?Z1(e,t,r,n):Pm(t,n)}}async function D$(e,t){if(await e.checkpoint())return null;let r="Gist checkpoint push failed after retry; the local mutation is saved but NOT synced yet. A running MCP server or dashboard retries the push before its next Gist refresh; a new CLI run starts from the Gist without it, so re-run the command there";return k(t,r),r}async function Z1(e,t,r,n){let s;try{s=await e.runMutation(()=>e.refreshFromGist({force:!0}))}catch(o){return Pm(t,o)}if(!s)return Pm(t,n);try{r()}catch(o){let i=`Gist conflict recovery failed; state was refreshed from the Gist and re-applying the mutation threw, so the mutation was LOST, re-run the command: ${I(o)}`;return k(t,i),i}try{return await D$(e,t)}catch(o){return Pm(t,o)}}function Pm(e,t){let r=`Gist checkpoint failed; the local mutation is saved but NOT synced to the Gist, re-run the command to retry: ${I(t)}`;return k(e,r),r}function M(){return Cn||(Cn=new oa),Cn}async function k_(e){return Cn&&(!e||Cn.isGistMode()&&!Cn.isGistDegraded())?Cn:po||(e?(po=oa.createWithGist(e).then(t=>(Cn=t,po=null,t)).catch(t=>{if(po=null,t instanceof Oe||!pm(t))throw t;return k(Fe,`Gist initialization failed (transient network error), falling back to local-only mode: ${t}`),M()}),po):M())}async function ia(e){let t;try{let n=us.readFileSync(jt(),"utf8");t=JSON.parse(n)?.config?.persistence}catch(n){if(n.code!=="ENOENT")return k(Fe,`State file unreadable during gist-persistence check (will retry): ${I(n)}`),"state-unreadable";let s=K1();if(s==="local")return"local-mode";if(s==="unreadable")return"state-unreadable";t="gist"}if(t!=="gist")return"local-mode";if(!e)return"no-token";let r=await k_(e);return r.isGistMode()&&!r.isGistDegraded()?"gist":"degraded"}function K1(){try{let e=us.readFileSync(os(),"utf8");return JSON.parse(e)?.config?.persistence==="gist"?"gist":"local"}catch(e){if(e.code!=="ENOENT")return k(Fe,`State cache unreadable during gist-persistence check (will retry): ${I(e)}`),"unreadable"}try{return us.existsSync(so())?"gist":"local"}catch(e){return k(Fe,`Gist ID check failed during gist-persistence check (will retry): ${I(e)}`),"unreadable"}}async function L$(e){let t=null;try{let r=await ia(null);r==="no-token"&&(r=await ia(await e())),r==="no-token"?t="no-token":r==="state-unreadable"?t="state-unreadable":r==="degraded"&&(t="init-fallback")}catch(r){let n=`Gist initialization failed: ${I(r)}`;r instanceof Lr?n=`Gist initialization failed (${I(r)}). To fix it, ${dm}.`:r instanceof Oe&&(n=`Gist initialization failed (${I(r)}) \u2014 fix the Gist setup (check the token's gist scope, or run state-show / setup) before relying on sync`),t={reason:n}}return t===null?null:ta(t)}function Em(){Cn=null,po=null}var us,O$,Fe,V1,q1,oa,Cn,po,ls=A(()=>{"use strict";us=B(require("node:fs"),1);wn();jS();Wi();yu();VS();ae();ee();KS();QS();XS();Kr();st();yu();O$="overnight-report.md",Fe="state";V1=["openedAt","firstMaintainerResponseAt","issueUrl","pick","lastReviewDecision","lastCiStatus","backfilledAt","responseRule","closeReason","selfCloseReason"];q1=300;oa=class e{state;inMemoryOnly;lastLoadedMtimeMs=0;_batching=!1;_batchDirty=!1;gistStore=null;gistDegraded=!1;staleness=null;lastSuccessfulRefreshAt=null;mutationDepth=0;unpushed=!1;refreshCount=0;loadRecovery=null;constructor(t=!1){if(this.inMemoryOnly=t,t)this.state=_n();else{let r=fm();this.state=r.state,this.lastLoadedMtimeMs=r.mtimeMs,this.loadRecovery=r.recovery??null,this.tryReconcilePRCounts()}}static async createWithGist(t){let{getOctokit:r}=await Promise.resolve().then(()=>(lo(),$$)),n=r(t),s=new Xi(n),o=jt(),i,a=null;if(us.existsSync(o)){let u=fm();a=u.recovery??null;let d=await s.bootstrapWithMigration(u.state);if(i=d,d.migrated)try{let p=o+".pre-gist-migration";us.renameSync(o,p),O(Fe,`Renamed ${o} to ${p} after Gist migration`)}catch(p){k(Fe,`Failed to rename state.json after Gist migration: ${p}`)}}else i=await s.bootstrap();let c=new e(!0);return c.state=i.state,i.gistId&&(c.state.gistId=i.gistId),c.gistStore=s,c.gistDegraded=i.degraded??!1,c.inMemoryOnly=!1,c.loadRecovery=a,i.degraded&&(c.staleness={source:"cache",reason:"initial Gist bootstrap fell back to local cache",lastSuccessfulRefresh:null,detectedAt:new Date().toISOString()}),c}tryReconcilePRCounts(){try{this.reconcilePRCounts()}catch(t){k(Fe,`PR count reconciliation failed (will retry on next load): ${I(t)}`),O(Fe,`Reconciliation error details: ${t instanceof Error?t.stack:String(t)}`)}}batch(t){if(this._batching){t();return}this._batching=!0,this._batchDirty=!1;try{t(),this._batchDirty&&this.save()}finally{this._batching=!1,this._batchDirty=!1}}autoSave(){if(this._batching){this._batchDirty=!0;return}this.save()}isSetupComplete(){return this.state.config.setupComplete===!0}markSetupComplete(){this.state.config.setupComplete=!0,this.state.config.setupCompletedAt=new Date().toISOString(),this.autoSave()}initializeWithDefaults(t){if(this.state.config.setupComplete){O(Fe,`Setup already complete, skipping initializeWithDefaults for "${t}"`);return}this.batch(()=>{this.updateConfig({githubUsername:t}),this.markSetupComplete(),O(Fe,`Initialized with defaults for user "${t}"`)})}save(t={}){if(this.state.lastRunAt=new Date().toISOString(),this.gistStore&&(this.unpushed=!0),!this.inMemoryOnly){if(this.gistStore){try{Mr(os(),xr(this.state),384)}catch(r){k(Fe,`Failed to write Gist local cache: ${I(r)}`)}return}try{this.lastLoadedMtimeMs=XA(this.state,this.lastLoadedMtimeMs)}catch(r){if(r instanceof Dr&&t.allowReloadAndLoseMutation){k(Fe,`Concurrent external write detected; reloading and discarding in-memory mutation. ${r.message}`),this.reloadIfChanged();return}throw r}}}async checkpoint(){if(!this.gistStore)return!0;this.gistStore.setState(xr(this.state));let t;try{t=await this.gistStore.push()}catch(r){throw r instanceof Lr&&(this.gistDegraded=!0),r}return this.gistDegraded=!t,t&&(this.unpushed=!1),t}isGistMode(){return this.gistStore!==null}isGistDegraded(){return this.gistDegraded}getGistHealth(){return this.gistStore===null?{mode:"local",degraded:this.state.config.persistence==="gist"?{cause:"configured-but-local",recoverable:!0}:null}:this.gistDegraded?{mode:"gist",degraded:{cause:"bootstrap-degraded",...this.staleness&&{since:this.staleness.detectedAt},recoverable:!0}}:{mode:"gist",degraded:null}}isGuidelinesAvailable(){return this.gistStore!==null}getGuidelines(t){return yT(this.gistStore,t)}setGuidelines(t,r){bT(this.gistStore,t,r),this.autoSave()}deleteGuidelines(t){wT(this.gistStore,t),this.autoSave()}listGuidelinesRepos(){return RT(this.gistStore)}getState(){return this.state}reloadIfChanged(){if(this.inMemoryOnly||this.gistStore)return!1;let t=eT(this.lastLoadedMtimeMs);return t?(this.state=t.state,this.lastLoadedMtimeMs=t.mtimeMs,this.loadRecovery=t.recovery??null,this.tryReconcilePRCounts(),!0):!1}getLoadRecovery(){return this.loadRecovery}async runMutation(t){this.mutationDepth++;try{return await t()}finally{this.mutationDepth--}}get refreshGeneration(){return this.refreshCount}hasUnpushedChanges(){return this.unpushed}forgetUnpushedChanges(){this.unpushed=!1}async refreshFromGist(t={}){if(!this.gistStore||this.mutationDepth>0&&!t.force)return!1;if(t.force&&this.mutationDepth===0&&this.unpushed)return k(Fe,"Forced Gist refresh refused: local changes are not pushed yet and nothing would re-apply them"),!1;if(!t.force&&this.unpushed){if(await this.checkpoint().catch(o=>(k(Fe,`Push before Gist refresh failed: ${I(o)}`),null))===!1)return this.staleness={source:"cache",reason:"Gist refresh skipped: local changes are not pushed yet (push failed); serving local state",lastSuccessfulRefresh:this.lastSuccessfulRefreshAt,detectedAt:new Date().toISOString()},!1;if(this.mutationDepth>0)return!1}let n=(await this.gistStore.refreshFromGist(t)).status==="refreshed";if(n){let s=this.gistStore.cachedFiles.get("state.json");if(!s)return k(Fe,"Gist refreshed but state.json missing from cache"),this.staleness={source:"cache",reason:"Gist refresh returned no state.json file",lastSuccessfulRefresh:this.lastSuccessfulRefreshAt,detectedAt:new Date().toISOString()},!1;let o=this.unpushed,i;try{i=JSON.parse(s),this.state=Gt.parse(i)}catch(c){return k(Fe,`Failed to parse refreshed Gist state: ${I(c)}`),this.staleness={source:"cache",reason:`Gist refresh succeeded but payload was invalid: ${I(c)}`,lastSuccessfulRefresh:this.lastSuccessfulRefreshAt,detectedAt:new Date().toISOString()},!1}oo(i,this.state,"Gist state"),this.tryReconcilePRCounts(),this.unpushed=!1;let a=new Date;if(this.lastSuccessfulRefreshAt=a.toISOString(),this.staleness=null,this.refreshCount++,o&&!t.force){let c="A Gist refresh replaced local state that still had un-pushed changes; they were NOT synced. Re-run the command that made the change.";k(Fe,c),this.staleness={reason:c,source:"cache",lastSuccessfulRefresh:this.lastSuccessfulRefreshAt,detectedAt:a.toISOString()}}}else this.gistStore.lastRefreshError&&(this.staleness={source:"cache",reason:I(this.gistStore.lastRefreshError),lastSuccessfulRefresh:this.lastSuccessfulRefreshAt,detectedAt:new Date().toISOString()});return n}getStateStaleness(){return this.staleness}setLastDigest(t){this.state.lastDigest=t,this.state.lastDigestAt=t.generatedAt,this.autoSave()}setLastStrategyAt(t){this.state.lastStrategyAt=t,this.autoSave()}setMonthlyMergedCounts(t){this.state.monthlyMergedCounts=t,this.autoSave()}setMonthlyClosedCounts(t){this.state.monthlyClosedCounts=t,this.autoSave()}setMonthlyOpenedCounts(t){this.state.monthlyOpenedCounts=t,this.autoSave()}setLocalRepoCache(t){this.state.localRepoCache=t,this.autoSave()}getMergedPRs(){return this.state.mergedPRs??[]}addMergedPRs(t){if(t.length===0)return{added:0,dropped:0};let{valid:r,dropped:n}=I$(t,"merged"),s=r.map(c=>this.withPick(c));if(s.length===0)return{added:0,dropped:n};this.state.mergedPRs||(this.state.mergedPRs=[]);let o=new Map(this.state.mergedPRs.map(c=>[c.url,c])),i=[],a=!1;for(let c of s){let u=o.get(c.url);u?a=x$(u,c)||a:(i.push(c),o.set(c.url,c))}return i.length===0&&!a?{added:0,dropped:n}:(this.state.mergedPRs.push(...i),this.state.mergedPRs.sort((c,u)=>u.mergedAt.localeCompare(c.mergedAt)),O(Fe,`Added ${i.length} merged PRs (total: ${this.state.mergedPRs.length})`),this.tryReconcilePRCounts(),this.autoSave(),{added:i.length,dropped:n})}withPick(t){if(!t.issueUrl||t.pick)return t;let r=t.issueUrl.toLowerCase(),n=this.getPickSnapshots().find(s=>s.issueUrl.toLowerCase()===r);return n?{...t,pick:n}:t}getMergedPRWatermark(){return this.state.mergedPRs?.[0]?.mergedAt||void 0}getClosedPRs(){return this.state.closedPRs??[]}addClosedPRs(t){if(t.length===0)return{added:0,dropped:0};let{valid:r,dropped:n}=I$(t,"closed"),s=r.map(c=>this.withPick(c));if(s.length===0)return{added:0,dropped:n};this.state.closedPRs||(this.state.closedPRs=[]);let o=new Map(this.state.closedPRs.map(c=>[c.url,c])),i=[],a=!1;for(let c of s){let u=o.get(c.url);u?a=x$(u,c)||a:(i.push(c),o.set(c.url,c))}return i.length===0&&!a?{added:0,dropped:n}:(this.state.closedPRs.push(...i),this.state.closedPRs.sort((c,u)=>u.closedAt.localeCompare(c.closedAt)),O(Fe,`Added ${i.length} closed PRs (total: ${this.state.closedPRs.length})`),this.tryReconcilePRCounts(),this.autoSave(),{added:i.length,dropped:n})}getClosedPRWatermark(){return this.state.closedPRs?.[0]?.closedAt||void 0}markPRCommentsFetched(t,r){let n=this.state.mergedPRs?.find(o=>o.url===t);if(n){n.commentsFetchedAt=r,this.autoSave();return}let s=this.state.closedPRs?.find(o=>o.url===t);s&&(s.commentsFetchedAt=r,this.autoSave())}setLedgerResponse(t,r,n){let s=this.state.mergedPRs?.find(o=>o.url===t)??this.state.closedPRs?.find(o=>o.url===t);s&&(r===void 0?delete s.firstMaintainerResponseAt:s.firstMaintainerResponseAt=r,s.responseRule=n,this.autoSave())}markPRLearningsExtracted(t,r){let n=this.state.mergedPRs?.find(o=>o.url===t);if(n){n.learningsExtractedAt=r,this.autoSave();return}let s=this.state.closedPRs?.find(o=>o.url===t);s&&(s.learningsExtractedAt=r,this.autoSave())}updateConfig(t){this.state.config={...this.state.config,...t},this.autoSave()}addIssue(t){let r=qe(t.url),n=this.state.activeIssues.find(s=>r?qe(s.url)===r:s.url===t.url);if(n){n.status=t.status,n.updatedAt=t.updatedAt,O(Fe,`Issue ${t.url} already tracked; refreshed claim stamp to ${t.updatedAt}`),this.autoSave();return}this.state.activeIssues.push(t),O(Fe,`Added issue: ${t.repo}#${t.number}`),this.autoSave()}releaseIssue(t,r){let n=qe(t),s=this.state.activeIssues.findIndex(i=>n?qe(i.url)===n:i.url===t);if(s===-1)return O(Fe,`releaseIssue: ${t} is not tracked; nothing to release`),"not_tracked";let o=this.state.activeIssues[s];if(r!==void 0){let i=Date.parse(o.updatedAt),a=Date.parse(r);if(Number.isNaN(i)||Number.isNaN(a)||i>=a)return O(Fe,`releaseIssue: keeping ${o.repo}#${o.number}; claim stamp ${o.updatedAt} is not before ${r}`),"newer_claim"}return this.state.activeIssues.splice(s,1),O(Fe,`Released issue claim: ${o.repo}#${o.number}`),this.autoSave(),"released"}addTrustedProject(t){this.state.config.trustedProjects.includes(t)||(this.state.config.trustedProjects.push(t),O(Fe,`Added trusted project: ${t}`),this.autoSave())}static matchesExclusion(t,r,n){let s=t.toLowerCase();return!!(r.some(o=>o.toLowerCase()===s)||n?.some(o=>o.toLowerCase()===s.split("/",1)[0]))}cleanupExcludedData(t,r){let n=i=>e.matchesExclusion(i,t,r),s=this.state.config.trustedProjects.length;this.state.config.trustedProjects=this.state.config.trustedProjects.filter(i=>!n(i));let o=s-this.state.config.trustedProjects.length;o>0&&(O(Fe,`Removed ${o} trusted project(s) for excluded repos/orgs`),this.autoSave())}getStarredRepos(){return this.state.config.starredRepos||[]}setStarredRepos(t){this.state.config.starredRepos=t,this.state.config.starredReposLastFetched=new Date().toISOString(),O(Fe,`Updated starred repos: ${t.length} repositories`),this.autoSave()}isStarredReposStale(){let t=this.state.config.starredReposLastFetched;if(!t)return!0;let r=1440*60*1e3,n=new Date(t);return new Date().getTime()-n.getTime()>r}shelvePR(t){return this.state.config.shelvedPRUrls||(this.state.config.shelvedPRUrls=[]),this.state.config.shelvedPRUrls.includes(t)?!1:(this.state.config.shelvedPRUrls.push(t),this.autoSave(),!0)}unshelvePR(t){if(!this.state.config.shelvedPRUrls)return!1;let r=this.state.config.shelvedPRUrls.indexOf(t);return r===-1?!1:(this.state.config.shelvedPRUrls.splice(r,1),this.autoSave(),!0)}isPRShelved(t){return this.state.config.shelvedPRUrls?.includes(t)??!1}dismissIssue(t,r,n={}){return this.state.config.dismissedIssues||(this.state.config.dismissedIssues={}),t in this.state.config.dismissedIssues&&!n.refresh?!1:(this.state.config.dismissedIssues[t]=r,this.setDismissedPRHead(t,n.headSha),this.autoSave(),!0)}undismissIssue(t){return!this.state.config.dismissedIssues||!(t in this.state.config.dismissedIssues)?!1:(delete this.state.config.dismissedIssues[t],this.setDismissedPRHead(t,void 0),this.autoSave(),!0)}getIssueDismissedAt(t){return this.state.config.dismissedIssues?.[t]}getDismissedPRHead(t){return this.state.config.dismissedPRHeads?.[t]}setDismissedPRHead(t,r){this.state.config.dismissedPRHeads||(this.state.config.dismissedPRHeads={}),r===void 0?delete this.state.config.dismissedPRHeads[t]:this.state.config.dismissedPRHeads[t]=r}getPickSnapshots(){return this.state.pickSnapshots??[]}recordPickSnapshots(t){let r=new Set(this.getPickSnapshots().map(s=>s.issueUrl.toLowerCase())),n=t.filter(s=>{let o=s.issueUrl.toLowerCase();return r.has(o)?!1:(r.add(o),!0)});n.length!==0&&(this.state.pickSnapshots=[...this.getPickSnapshots(),...n].slice(-q1),this.autoSave())}getSearchSeen(){return this.state.searchSeen??[]}setSearchSeen(t){this.state.searchSeen=t,this.autoSave()}getOvernightReportDocument(){let t=this.gistStore?.getDocument(O$)??null;return t===""?null:t}setOvernightReportDocument(t){this.gistStore?.setDocument(O$,t)}getLastOvernight(){return this.state.lastOvernight}setLastOvernight(t){this.state.lastOvernight=t,this.autoSave()}getSearchRotation(){return this.state.searchRotation}setSearchRotation(t){this.state.searchRotation=t,this.autoSave()}getWorkClaims(){return this.state.workClaims??[]}getActiveWorkClaims(t=Date.now()){return lr(this.getWorkClaims(),t)}pruneWorkClaims(t){let r=this.getWorkClaims();for(let n of r)Number.isFinite(Date.parse(n.expiresAt))||k(Fe,`Pruning work claim on ${n.url} (session ${n.session}): expiresAt "${n.expiresAt}" is not a date`);return lr(r,t)}upsertWorkClaim(t,r=Date.now()){let n=Qt(t.url),s=this.pruneWorkClaims(r),o=s.some(i=>Qt(i.url)===n);return this.state.workClaims=[...s.filter(i=>Qt(i.url)!==n),t],this.autoSave(),o}finishWorkClaim(t,r,n=Date.now()){let s=Qt(t),o=this.pruneWorkClaims(n),i=o.find(c=>Qt(c.url)===s);if(!i)return;let a=em(i,r);return this.state.workClaims=o.map(c=>c===i?a:c),this.autoSave(),a}releaseWorkClaims(t,r=Date.now()){let n=t.url===void 0?void 0:Qt(t.url),s=a=>n!==void 0&&Qt(a.url)!==n||t.session!==void 0&&a.session!==t.session?!1:t.kind===void 0||a.kind===t.kind,o=this.pruneWorkClaims(r),i=o.filter(a=>s(a)).map(a=>a.url);return i.length>0&&(this.state.workClaims=o.filter(a=>!s(a)),this.autoSave()),i}setStatusOverride(t,r,n){this.state.config.statusOverrides||(this.state.config.statusOverrides={}),this.state.config.statusOverrides[t]={status:r,setAt:new Date().toISOString(),lastActivityAt:n},this.autoSave()}clearStatusOverride(t){return!this.state.config.statusOverrides||!(t in this.state.config.statusOverrides)?!1:(delete this.state.config.statusOverrides[t],this.autoSave(),!0)}getStatusOverride(t,r){let n=this.state.config.statusOverrides?.[t];if(n){if(r&&r>n.lastActivityAt){this.clearStatusOverride(t);return}return n}}getRepoScore(t){return oT(this.state,t)}updateRepoScore(t,r){WS(this.state,t,r),this.autoSave()}getReposWithMergedPRs(){return iT(this.state)}getReposWithOpenPRs(){return aT(this.state)}getHighScoringRepos(t){return cT(this.state,t)}getLowScoringRepos(t){return uT(this.state,t)}getStats(){return mT(this.state)}renameRepo(t,r){pT(this.state,t,r),this.autoSave()}reconcilePRCounts(){let t=this.state.mergedPRs??[],r=this.state.closedPRs??[];if(t.length===0&&r.length===0)return;lT(this.state,t,r)&&this.autoSave()}},Cn=null,po=null});async function Qr(e,t,r){let n=0,s=!1,o=async()=>{for(;n<e.length&&!s;){let a=e[n++];try{await t(a)}catch(c){throw s=!0,c}}},i=Math.min(r,e.length);await Promise.all(Array.from({length:i},()=>o()))}function Am(e){let t=e.filter(n=>n.status==="rejected");if(t.length===0)return;throw(t.find(n=>le(n.reason))??t[0]).reason}var Pr,ds=A(()=>{"use strict";ee();Pr=5});async function ze(e,t=100,r=10){let n=[];for(let s=1;s<=r;s++){let{data:o}=await e(s);if(n.push(...o),o.length<t)return{items:n,truncated:!1}}return{items:n,truncated:!0}}async function Tm(e,t=100,r=10){let{items:n}=await ze(e,t,r);return n}var mo=A(()=>{"use strict"});function ps(){return C_||(C_=new Pu),C_}async function aa(e,t,r){let n=e.getInflight(t);if(n)return O(Pn,`Dedup hit for ${t}`),await n;let o=(async()=>{let a={},c=e.get(t);c&&(a["if-none-match"]=c.etag);try{let u=await r(a),d=u.headers?.etag;return d&&e.set(t,d,u.data),u.data}catch(u){if(Q1(u)){let d=e.get(t);if(d)return O(Pn,`304 cache hit for ${t}`),d.body}throw u}})(),i=e.setInflight(t,o);try{return await o}finally{i()}}function Q1(e){return je(e)===304}var Ct,Cu,M$,Pn,J1,Y1,Pu,C_,Eu=A(()=>{"use strict";Ct=B(require("node:fs"),1),Cu=B(require("node:path"),1),M$=B(require("node:crypto"),1);Kr();ae();ee();Pn="http-cache",J1=1440*60*1e3,Y1=2e3,Pu=class{cacheDir;maxEntries;inflightRequests=new Map;constructor(t,r=Y1){this.cacheDir=t??om(),this.maxEntries=r}keyFor(t){return M$.createHash("sha256").update(t).digest("hex")}pathFor(t){return Cu.join(this.cacheDir,`${this.keyFor(t)}.json`)}getIfFresh(t,r){let n=this.get(t);if(!n)return null;let s=Date.now()-new Date(n.cachedAt).getTime();return!Number.isFinite(s)||s<0||s>r?null:n.body}get(t){let r=this.pathFor(t);try{let n=Ct.readFileSync(r,"utf8"),s=JSON.parse(n);return s.url!==t?(O(Pn,`Cache collision detected for ${t}, ignoring`),null):s}catch(n){if(n&&typeof n=="object"&&n.code!=="ENOENT"){let s=n instanceof Error?n.message:"unknown error";O(Pn,`Cache read failed for ${t} (treating as miss): ${s}`)}return null}}set(t,r,n){let s={etag:r,url:t,body:n,cachedAt:new Date().toISOString()};try{Ct.writeFileSync(this.pathFor(t),JSON.stringify(s),{encoding:"utf8",mode:384}),O(Pn,`Cached response for ${t}`),this.evictIfExceeds(this.maxEntries)}catch(o){O(Pn,`Failed to write cache for ${t}`,o)}}evictIfExceeds(t){if(!(t<=0))try{let r=Ct.readdirSync(this.cacheDir).filter(i=>i.endsWith(".json"));if(r.length<=t)return;let n=r.map(i=>{let a=Cu.join(this.cacheDir,i);try{return{fullPath:a,mtimeMs:Ct.statSync(a).mtimeMs}}catch{return null}}).filter(i=>i!==null).sort((i,a)=>i.mtimeMs-a.mtimeMs),s=n.length-t,o=0;for(let i=0;i<s;i++)try{Ct.unlinkSync(n[i].fullPath),o++}catch{}o>0&&O(Pn,`Capped cache at ${t} entries: evicted ${o} oldest`)}catch{}}hasInflight(t){return this.inflightRequests.has(t)}getInflight(t){return this.inflightRequests.get(t)}setInflight(t,r){return this.inflightRequests.set(t,r),()=>{this.inflightRequests.delete(t)}}evictStale(t=J1){let r=0;try{let n=Ct.readdirSync(this.cacheDir),s=Date.now();for(let o of n){if(!o.endsWith(".json"))continue;let i=Cu.join(this.cacheDir,o);try{let a=Ct.readFileSync(i,"utf8"),c=JSON.parse(a);s-new Date(c.cachedAt).getTime()>t&&(Ct.unlinkSync(i),r++)}catch{try{Ct.unlinkSync(i),r++}catch{}}}}catch{}return r>0&&O(Pn,`Evicted ${r} stale cache entries`),r}clear(){try{let t=Ct.readdirSync(this.cacheDir);for(let r of t)r.endsWith(".json")&&Ct.unlinkSync(Cu.join(this.cacheDir,r));O(Pn,"Cache cleared")}catch{}}size(){try{return Ct.readdirSync(this.cacheDir).filter(t=>t.endsWith(".json")).length}catch{return 0}}},C_=null});function $m(){return{status:"unknown",failingCheckNames:[],failingCheckConclusions:new Map}}function Om(e,t,r){if(r==="cancelled"||r==="timed_out")return"infrastructure";if(r==="action_required")return"auth_gate";let n=e.toLowerCase();if(N$.some(s=>s.test(n)))return"auth_gate";if(F$.some(s=>s.test(n)))return"fork_limitation";if(G$.some(s=>s.test(n)))return"infrastructure";if(t){let s=t.toLowerCase();if(N$.some(o=>o.test(s)))return"auth_gate";if(F$.some(o=>o.test(s)))return"fork_limitation";if(G$.some(o=>o.test(s)))return"infrastructure"}return"actionable"}function Au(e,t){return e.map(r=>{let n=t?.get(r);return{name:r,category:Om(r,void 0,n),conclusion:n}})}function P_(e){let{ciStatus:t,failingCheckNames:r,classifiedChecks:n}=e;if(t==="passing")return{category:"all_passing",summary:"All checks passing",action:"none"};if(t==="pending"){let s=r.length;return{category:"blocked",summary:s>0?`${s} pending check(s); CI run incomplete`:"CI checks pending",action:"request_rerun"}}if(t==="failing"){let s=n.filter(a=>a.category==="actionable");if(s.length>0){let a=s.slice(0,3).map(u=>u.name).join(", "),c=s.length>3?` (+${s.length-3} more)`:"";return{category:"failing",summary:`${s.length} actionable failure(s): ${a}${c}`,action:"investigate"}}return n.length===0?{category:"failing",summary:"CI reported failure but no check details available",action:"investigate"}:n.some(a=>a.category==="infrastructure")?{category:"blocked",summary:`${n.length} non-actionable failure(s) including infrastructure issues; rerun may resolve`,action:"request_rerun"}:{category:"fork_limitation",summary:`${n.length} non-actionable failure(s) (fork limits / auth gates)`,action:"informational"}}return{category:"not_running",summary:"No CI checks reported",action:"check_workflows"}}function X1(e){let t=!1,r=!1,n=!1,s=[],o=new Map;for(let i of e)i.conclusion==="failure"||i.conclusion==="cancelled"||i.conclusion==="timed_out"||i.conclusion==="action_required"?(t=!0,s.push(i.name),o.set(i.name,i.conclusion)):i.conclusion===null&&i.status==="waiting"?(t=!0,s.push(i.name),o.set(i.name,"action_required")):i.conclusion===null&&i.status!=="completed"?r=!0:i.conclusion==="success"&&(n=!0);return{hasFailingChecks:t,hasPendingChecks:r,hasSuccessfulChecks:n,failingCheckNames:s,failingCheckConclusions:o}}function eB(e){let t=e.statuses.filter(c=>{let u=(c.description||"").toLowerCase();return!(c.state==="failure"&&(u.includes("authorization required")||u.includes("authorize")))}),r=t.some(c=>c.state==="failure"||c.state==="error"),n=t.some(c=>c.state==="pending"),s=t.some(c=>c.state==="success"),o;r?o="failure":n?o="pending":s||t.length===0?o="success":o=e.state;let i=e.statuses.length>0,a=[];for(let c of t)(c.state==="failure"||c.state==="error")&&a.push(c.context);return{effectiveCombinedState:o,hasStatuses:i,failingStatusNames:a}}function tB(e,t,r){let{hasFailingChecks:n,hasPendingChecks:s,hasSuccessfulChecks:o,failingCheckNames:i,failingCheckConclusions:a}=e,{effectiveCombinedState:c,hasStatuses:u,failingStatusNames:d}=t,p=[...i,...d];return n||c==="failure"||c==="error"?{status:"failing",failingCheckNames:p,failingCheckConclusions:a}:s||c==="pending"?{status:"pending",failingCheckNames:[],failingCheckConclusions:new Map}:o||c==="success"?{status:"passing",failingCheckNames:[],failingCheckConclusions:new Map}:$m()}function E_(e,t){let r=new Map;for(let i of e){let a=r.get(i.name);(!a||new Date(i.started_at??0)>new Date(a.started_at??0))&&r.set(i.name,i)}let n=[...r.values()],s=X1(n),o=eB(t);return tB(s,o,n.length)}async function A_(e,t,r,n){if(!n)return $m();try{let[s,o]=await Promise.all([e.repos.getCombinedStatusForRef({owner:t,repo:r,ref:n,per_page:100}),Tm(c=>e.checks.listForRef({owner:t,repo:r,ref:n,per_page:100,page:c}).then(u=>({data:u.data.check_runs}))).catch(c=>{let u=je(c);if(u===429)throw c;if(u===403){let d=I(c).toLowerCase();if(d.includes("rate limit")||d.includes("abuse detection"))throw c}return u===404?O("pr-monitor",`Check runs 404 for ${t}/${r}@${n.slice(0,7)} (no checks configured)`):k("pr-monitor",`Non-404 error fetching check runs for ${t}/${r}@${n.slice(0,7)}: ${u??c}`),null})]),i=s.data;return E_(o??[],i)}catch(s){let o=je(s);if(o===401||o===403||o===429)throw s;return o===404?O("pr-monitor",`CI check 404 for ${t}/${r} (no CI configured)`):k("pr-monitor",`Failed to check CI for ${t}/${r}@${n.slice(0,7)}: ${I(s)}`),$m()}}var F$,N$,G$,Tu=A(()=>{"use strict";ee();ae();mo();F$=[/vercel/i,/netlify/i,/\bpreview\s*deploy/i,/\bdeploy\s*preview/i,/storybook/i,/chromatic/i,/percy/i,/cloudflare pages/i,/\binternal\b(?!\s+(?:api|test|integration|smoke|unit|e2e|regression|functional))/i],N$=[/authoriz/i,/approval/i,/\bcla\b/i,/license\/cla/i,/\b(?:pr|type|require[sd]?|check|missing)[\s-]+(?:\w+[\s-]+)?labels?\b/i,/\blabeler\b/i,/\btriage\b/i],G$=[/\binstall\s*(os\s*)?dep(endenc|s\b)/i,/\bsetup\s+fail(ed|ure)?\b/i,/\bservice\s*unavailable/i,/\binfrastructure/i,/\bblacksmith\b/i,/\breadthedocs\b/i]});function $u(e){if(e.status==="rejected")throw e.reason;return e.value}function U$(e){let t=q(e);if(!t||t.type!=="pull")throw new j(`Invalid PR URL format: ${e}`);return t}async function sB(e,t){let r={items:[],totalCount:0,pagesRead:0,incomplete:!1};for(let n=1;n<=I_;n++){let s;try{({data:s}=await e.search.issuesAndPullRequests({q:t,page:n,sort:"updated",order:"desc",per_page:$_}))}catch(o){if(le(o))throw o;return r.failure={page:n,error:o},r}if(r.pagesRead=n,r.totalCount=s.total_count,s.incomplete_results&&(r.incomplete=!0),r.items.push(...s.items),s.items.length<$_||r.items.length>=r.totalCount)break}return r}function oB(e,t){if(t.failure)return`GitHub search for ${e} failed on page ${t.failure.page} (${er(t.failure.error)}); only the ${t.items.length} result(s) from the ${t.pagesRead} page(s) before it were read this run.`;if(t.items.length<t.totalCount)return`GitHub Search API reports ${t.totalCount} ${e}, but only the ${t.items.length} most recently updated were read (${t.pagesRead} page(s) of ${$_}). Older reviewed PRs are not checked this run.`}function iB(e,t){let r=`open PRs you ${e} (not authored)`,n=[],s=oB(r,t);return s!==void 0&&n.push(s),t.incomplete&&n.push(`GitHub Search API returned incomplete results for ${r} (the search timed out server-side); some reviewed PRs may be missing this run.`),n}function aB(e,t){return(Date.parse(t.updatedAt)||0)-(Date.parse(e.updatedAt)||0)}async function j$(e,t){let r=t.githubUsername;if(!r)throw new Oe("No GitHub username configured. Run setup first.");let n=new O_(t),s=[],o=new Set,i=[];for(let{qualifier:a,label:c}of nB){let u=await sB(e,`is:pr is:open is:public ${a}:${r} -author:${r}`);for(let d of u.items){if(o.has(d.html_url))continue;o.add(d.html_url);let p=n.toRef(d);p&&s.push(p)}for(let d of iB(c,u))i.push(d),k(T_,d)}return s.sort(aB),O(T_,`Found ${s.length} open PRs reviewed by @${r}`),{prs:s,warnings:i}}async function z$(e,t){let{owner:r,repo:n,number:s}=U$(t),o=await Promise.allSettled([e.pulls.get({owner:r,repo:n,pull_number:s}),ze(f=>e.issues.listComments({owner:r,repo:n,page:f,issue_number:s,per_page:100})),ze(f=>e.pulls.listReviews({owner:r,repo:n,page:f,pull_number:s,per_page:100})),ze(f=>e.pulls.listReviewComments({owner:r,repo:n,page:f,pull_number:s,per_page:100})),ze(f=>e.pulls.listCommits({owner:r,repo:n,page:f,pull_number:s,per_page:100}))]);Am(o);let i=$u(o[0]).data,a=$u(o[1]),c=$u(o[2]),u=$u(o[3]),d=$u(o[4]),p=[];return a.truncated&&p.push("comments"),c.truncated&&p.push("reviews"),u.truncated&&p.push("review comments"),(d.items.length>=rB||d.items.at(-1)?.sha!==i.head.sha||d.truncated)&&p.push("commits"),{truncatedLists:p,pr:{headSha:i.head.sha,state:i.state,author:i.user?.login,title:i.title},comments:a.items,reviews:c.items,reviewComments:u.items,commits:d.items}}async function B$(e,t,r,n){let{owner:s,repo:o}=U$(t);try{let{data:i}=await e.repos.compareCommitsWithBasehead({owner:s,repo:o,basehead:`${r}...${n}`,per_page:1});return i.status}catch(i){if(je(i)===404)return"missing";throw i}}var T_,I_,$_,rB,nB,O_,x_=A(()=>{"use strict";ds();ee();ae();mo();st();T_="reviewed-prs",I_=3,$_=100,rB=250,nB=[{qualifier:"reviewed-by",label:"reviewed"},{qualifier:"commenter",label:"commented on"}];O_=class{constructor(t){this.config=t;this.usernameLower=t.githubUsername.toLowerCase(),this.excludedRepos=new Set((t.excludeRepos??[]).map(r=>r.toLowerCase())),this.excludedOrgs=new Set((t.excludeOrgs??[]).map(r=>r.toLowerCase()))}config;usernameLower;excludedRepos;excludedOrgs;isRepoExcluded(t,r){let n=t.toLowerCase();return kr(t,this.config.githubUsername)||zi(t,this.config.untrackedOrgs)?!0:this.excludedRepos.has(r.toLowerCase())||this.excludedOrgs.has(n)}toRef(t){if(!t.pull_request)return;let r=q(t.html_url);if(!r||r.type!=="pull"){k(T_,`Skipping reviewed PR with unparseable URL: ${t.html_url}`);return}let n=t.user?.login??"",s=`${r.owner}/${r.repo}`;if(!(n.toLowerCase()===this.usernameLower||this.isRepoExcluded(r.owner,s)))return{repo:s,author:n,url:t.html_url,number:r.number,title:t.title,updatedAt:t.updated_at}}}});var H$={};re(H$,{byDateDescending:()=>D_,daysBetween:()=>ms,formatRelativeTime:()=>Ou});function ms(e,t=new Date){return Math.max(0,Math.floor((t.getTime()-e.getTime())/(1e3*60*60*24)))}function Ou(e){let t=new Date(e),r=Date.now()-t.getTime();if(r<0)return"just now";let n=Math.floor(r/6e4),s=Math.floor(r/36e5),o=Math.floor(r/864e5);return n<60?`${n}m ago`:s<24?`${s}h ago`:o<30?`${o}d ago`:t.toLocaleDateString()}function D_(e){return(t,r)=>{let n=new Date(e(t)||0).getTime();return new Date(e(r)||0).getTime()-n}}var ca=A(()=>{"use strict"});function lB(e,t){if(!e||!t)return!0;let r=e.toLowerCase();return cB.has(r)?!0:r===t.toLowerCase()}function ua(e){return e?new Date(e).getTime():Number.NaN}function dB(e,t){let r=ua(e),n=ua(t);return!Number.isFinite(r)||!Number.isFinite(n)?!1:r-n>=uB}function W$(e){let{latestCommitDate:t,latestCommitAuthor:r,contributorUsername:n}=e;if(t)return lB(r,n)?t:void 0}function V$(e,t,r){if(!e||!t||!dB(e,t))return!1;if(r){let n=ua(e),s=ua(r);if(!Number.isFinite(n)||!Number.isFinite(s)||n<s)return!1}return!0}function q$(e,t){if(!e||!t)return!1;let r=ua(e),n=ua(t);return!Number.isFinite(r)||!Number.isFinite(n)?!1:r>=n}function pB(e){let{ciStatus:t,hasMergeConflict:r,hasUnrespondedComment:n,reviewDecision:s,lastMaintainerCommentDate:o,latestChangesRequestedDate:i,hasActionableCIFailure:a=!0}=e,c=W$(e),u=[];return n&&!(s==="approved"&&(t==="passing"||t==="unknown"))&&!V$(c,o,i)&&u.push("needs_response"),s==="changes_requested"&&i&&!q$(c,i)&&u.push("needs_changes"),t==="failing"&&a&&u.push("failing_ci"),r&&u.push("merge_conflict"),u.length>0?u:void 0}function L_(e){let t=mB(e);t.status==="waiting_on_maintainer"&&e.hasMergeConflict&&(t={status:"needs_addressing",actionReason:"merge_conflict",stalenessTier:t.stalenessTier});let r=pB(e);return r?{...t,actionReasons:r}:t}function mB(e){let{ciStatus:t,hasMergeConflict:r,hasUnrespondedComment:n,reviewDecision:s,daysSinceActivity:o,daysSinceMaintainerActivity:i=o,dormantThreshold:a,approachingThreshold:c,lastMaintainerCommentDate:u,latestChangesRequestedDate:d,hasActionableCIFailure:p=!0}=e,m="active";i>=a?m="dormant":i>=c&&(m="approaching_dormant");let f=W$(e);return n?V$(f,u,d)?t==="failing"&&p?{status:"needs_addressing",actionReason:"failing_ci",stalenessTier:m}:{status:"waiting_on_maintainer",waitReason:"changes_addressed",stalenessTier:m}:s==="approved"&&(t==="passing"||t==="unknown")?{status:"waiting_on_maintainer",waitReason:"pending_merge",stalenessTier:m}:{status:"needs_addressing",actionReason:"needs_response",stalenessTier:m}:s==="changes_requested"&&d?q$(f,d)?t==="failing"&&p?{status:"needs_addressing",actionReason:"failing_ci",stalenessTier:m}:{status:"waiting_on_maintainer",waitReason:"changes_addressed",stalenessTier:m}:{status:"needs_addressing",actionReason:"needs_changes",stalenessTier:m}:t==="failing"?p?o>=5?{status:"waiting_on_maintainer",waitReason:"stale_ci_failure",stalenessTier:m}:{status:"needs_addressing",actionReason:"failing_ci",stalenessTier:m}:{status:"waiting_on_maintainer",waitReason:"ci_blocked",stalenessTier:m}:r?{status:"needs_addressing",actionReason:"merge_conflict",stalenessTier:m}:s==="approved"&&(t==="passing"||t==="unknown")?{status:"waiting_on_maintainer",waitReason:"pending_merge",stalenessTier:m}:{status:"waiting_on_maintainer",waitReason:"pending_review",stalenessTier:m}}var cB,uB,M_=A(()=>{"use strict";cB=new Set(["autofix-ci[bot]","prettier-ci[bot]","pre-commit-ci[bot]"]),uB=120*1e3});function Pt(e,t){if(t==="Bot")return!0;let r=e.toLowerCase();return r.includes("[bot]")||r.endsWith("-bot")||r.endsWith("-robot")||fB.has(r)}function la(e){if(!e||e.length>100||e.includes("?"))return!1;let t=e.toLowerCase();return["thanks","thank you","lgtm","looks good","will review","we'll review","we'll get to this","noted","got it","will look","will check"].some(n=>t.includes(n))}function J$(e){return e.replaceAll(/:[\w+-]+:/g," ").replaceAll(/[^\p{L}\p{N}+]+/gu," ").trim().toLowerCase()}function fo(e){let t=J$(e);return t===""||gB.has(t)}function Im(e){return hB.has(J$(e))}function K$(e){return e.replaceAll(/\s+/g," ").trim()}function Y$(e){let t=[],r=!1;for(let n of e.split(`
78
+ `);let u=!1,d=()=>{if(u)return;u=!0,Fr.global==null&&U1(n,a),c.global=c.global??Fr.global,c.auth=c.auth??Fr.auth,c.search=c.search??Fr.search,c.write=c.write??Fr.write,c.notifications=c.notifications??Fr.notifications,c.retryLimiter=c.retryLimiter??new n;let p={},m=new n.Events(p);p.on("secondary-limit",c.onSecondaryRateLimit),p.on("rate-limit",c.onRateLimit),p.on("error",f=>e.log.warn("Error in throttling-plugin limit handler",f)),c.retryLimiter.on("failed",async function(f,g){let[y,b,R]=g.args,{pathname:h}=new URL(R.url,"http://github.test");if(!(h.startsWith("/graphql")&&f.status!==401||f.status===403||f.status===429))return;let S=~~b.retryCount;b.retryCount=S,R.request.retryCount=S;let{wantRetry:w,retryAfter:P=0}=await(async function(){if(/\bsecondary rate\b/i.test(f.message)){let C=Number(f.response.headers["retry-after"])||y.fallbackSecondaryRateRetryAfter;return{wantRetry:await m.trigger("secondary-limit",C,R,e,S),retryAfter:C}}if(f.response.headers!=null&&f.response.headers["x-ratelimit-remaining"]==="0"||(f.response.data?.errors??[]).some(C=>C.type==="RATE_LIMITED")){let C=new Date(~~f.response.headers["x-ratelimit-reset"]*1e3).getTime(),E=Math.max(Math.ceil((C-Date.now())/1e3)+1,0);return{wantRetry:await m.trigger("rate-limit",E,R,e,S),retryAfter:E}}return{}})();if(w)return b.retryCount++,P*y.retryAfterBaseValue})};return e.hook.wrap("request",(p,m)=>(d(),L1(c,p,m))),{}}var k$,D1,R_,N1,v$,C$,Fr,U1,S_=A(()=>{k$=B(w_(),1),D1="0.0.0-development",R_=()=>Promise.resolve();N1=["/orgs/{org}/invitations","/orgs/{org}/invitations/{invitation_id}","/orgs/{org}/teams/{team_slug}/discussions","/orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments","/repos/{owner}/{repo}/collaborators/{username}","/repos/{owner}/{repo}/commits/{commit_sha}/comments","/repos/{owner}/{repo}/issues","/repos/{owner}/{repo}/issues/{issue_number}/comments","/repos/{owner}/{repo}/issues/{issue_number}/sub_issue","/repos/{owner}/{repo}/issues/{issue_number}/sub_issues/priority","/repos/{owner}/{repo}/pulls","/repos/{owner}/{repo}/pulls/{pull_number}/comments","/repos/{owner}/{repo}/pulls/{pull_number}/comments/{comment_id}/replies","/repos/{owner}/{repo}/pulls/{pull_number}/merge","/repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers","/repos/{owner}/{repo}/pulls/{pull_number}/reviews","/repos/{owner}/{repo}/releases","/teams/{team_id}/discussions","/teams/{team_id}/discussions/{discussion_number}/comments"];v$=G1(N1),C$=v$.test.bind(v$),Fr={},U1=function(e,t){Fr.global=new e.Group({id:"octokit-global",maxConcurrent:10,...t}),Fr.auth=new e.Group({id:"octokit-auth",maxConcurrent:1,...t}),Fr.search=new e.Group({id:"octokit-search",maxConcurrent:1,minTime:2e3,...t}),Fr.write=new e.Group({id:"octokit-write",maxConcurrent:1,minTime:1e3,...t}),Fr.notifications=new e.Group({id:"octokit-notifications",maxConcurrent:1,minTime:3e3,...t})};sa.VERSION=D1;sa.triggersNotification=C$});function z1(e){return e.request!==void 0}async function P$(e,t,r,n){if(!z1(r)||!r?.request.request)throw r;if(r.status>=400&&!e.doNotRetry.includes(r.status)){let s=n.request.retries!=null?n.request.retries:e.retries,o=Math.pow((n.request.retryCount||0)+1,2);throw t.retry.retryRequest(r,s,o)}throw r}async function B1(e,t,r,n){let s=new E$.default;return s.on("failed",function(o,i){let a=~~o.request.request?.retries,c=~~o.request.request?.retryAfter;if(n.request.retryCount=i.retryCount+1,a>i.retryCount)return c*e.retryAfterBaseValue}),s.schedule(H1.bind(null,e,t,r),n)}async function H1(e,t,r,n){let s=await r(n);if(s.data&&s.data.errors&&s.data.errors.length>0&&/Something went wrong while executing your query/.test(s.data.errors[0].message)){let o=new kn(s.data.errors[0].message,500,{request:n,response:s});return P$(e,t,o,n)}return s}function ku(e,t){let r=Object.assign({enabled:!0,retryAfterBaseValue:1e3,doNotRetry:[400,401,403,404,410,422,451],retries:3},t.retry),n={retry:{retryRequest:(s,o,i)=>(s.request.request=Object.assign({},s.request.request,{retries:o,retryAfter:i}),s)}};return r.enabled&&(e.hook.error("request",P$.bind(null,r,n)),e.hook.wrap("request",B1.bind(null,r,n))),n}var E$,j1,__=A(()=>{E$=B(w_(),1);n_();j1="0.0.0-development";ku.VERSION=j1});var $$={};re($$,{checkRateLimit:()=>v_,getOctokit:()=>we,getRateLimitCallbacks:()=>T$});function Cm(e){return e.toLocaleTimeString("en-US",{hour12:!1})}function T$(){return{onRateLimit:(e,t,r,n)=>{let s=t,o=new Date(Date.now()+e*1e3);return n<2?(k(vm,`Rate limit hit (retry ${n+1}/2, waiting ${e}s, resets at ${Cm(o)}) \u2014 ${s.method} ${s.url}`),!0):(k(vm,`Rate limit exceeded, not retrying \u2014 ${s.method} ${s.url} (resets at ${Cm(o)})`),!1)},onSecondaryRateLimit:(e,t,r,n)=>{let s=t,o=new Date(Date.now()+e*1e3);return n<3?(k(vm,`Secondary rate limit hit (retry ${n+1}/3, waiting ${e}s, resets at ${Cm(o)}) \u2014 ${s.method} ${s.url}`),!0):(k(vm,`Secondary rate limit exceeded, not retrying \u2014 ${s.method} ${s.url} (resets at ${Cm(o)})`),!1)}}}function we(e){if(km&&A$===e)return km;let t=T$();return km=new W1({auth:e,throttle:t,retry:{doNotRetry:[400,401,403,404,410,422,429,451]}}),A$=e,km}async function v_(e){let t=we(e),{data:r}=await t.rateLimit.get(),n=r.resources.search;return{remaining:n.remaining,limit:n.limit,resetAt:new Date(n.reset*1e3).toISOString()}}var vm,W1,km,A$,lo=A(()=>{"use strict";h_();S_();__();ae();vm="github",W1=_m.plugin(ku,sa),km=null,A$=null});function I$(e,t){let r=[],n=0;for(let s of e){if(q(s.url)===null){k(Fe,`Dropping ${t} PR with invalid URL: ${s.url}`),n++;continue}r.push(s)}return{valid:r,dropped:n}}function x$(e,t){let r=!1;for(let n of V1)t[n]!==void 0&&e[n]===void 0&&(e[n]=t[n],r=!0);return r}async function Re(e,t,r){if(!e.isGistMode())return null;r?.();try{return await D$(e,t)}catch(n){return n instanceof Xt&&r?Z1(e,t,r,n):Pm(t,n)}}async function D$(e,t){if(await e.checkpoint())return null;let r="Gist checkpoint push failed after retry; the local mutation is saved but NOT synced yet. A running MCP server or dashboard retries the push before its next Gist refresh; a new CLI run starts from the Gist without it, so re-run the command there";return k(t,r),r}async function Z1(e,t,r,n){let s;try{s=await e.runMutation(()=>e.refreshFromGist({force:!0}))}catch(o){return Pm(t,o)}if(!s)return Pm(t,n);try{r()}catch(o){let i=`Gist conflict recovery failed; state was refreshed from the Gist and re-applying the mutation threw, so the mutation was LOST, re-run the command: ${I(o)}`;return k(t,i),i}try{return await D$(e,t)}catch(o){return Pm(t,o)}}function Pm(e,t){let r=`Gist checkpoint failed; the local mutation is saved but NOT synced to the Gist, re-run the command to retry: ${I(t)}`;return k(e,r),r}function M(){return Cn||(Cn=new oa),Cn}async function k_(e){return Cn&&(!e||Cn.isGistMode()&&!Cn.isGistDegraded())?Cn:po||(e?(po=oa.createWithGist(e).then(t=>(Cn=t,po=null,t)).catch(t=>{if(po=null,t instanceof Oe||!pm(t))throw t;return k(Fe,`Gist initialization failed (transient network error), falling back to local-only mode: ${t}`),M()}),po):M())}async function ia(e){let t;try{let n=us.readFileSync(jt(),"utf8");t=JSON.parse(n)?.config?.persistence}catch(n){if(n.code!=="ENOENT")return k(Fe,`State file unreadable during gist-persistence check (will retry): ${I(n)}`),"state-unreadable";let s=K1();if(s==="local")return"local-mode";if(s==="unreadable")return"state-unreadable";t="gist"}if(t!=="gist")return"local-mode";if(!e)return"no-token";let r=await k_(e);return r.isGistMode()&&!r.isGistDegraded()?"gist":"degraded"}function K1(){try{let e=us.readFileSync(os(),"utf8");return JSON.parse(e)?.config?.persistence==="gist"?"gist":"local"}catch(e){if(e.code!=="ENOENT")return k(Fe,`State cache unreadable during gist-persistence check (will retry): ${I(e)}`),"unreadable"}try{return us.existsSync(so())?"gist":"local"}catch(e){return k(Fe,`Gist ID check failed during gist-persistence check (will retry): ${I(e)}`),"unreadable"}}async function L$(e){let t=null;try{let r=await ia(null);r==="no-token"&&(r=await ia(await e())),r==="no-token"?t="no-token":r==="state-unreadable"?t="state-unreadable":r==="degraded"&&(t="init-fallback")}catch(r){let n=`Gist initialization failed: ${I(r)}`;r instanceof Lr?n=`Gist initialization failed (${I(r)}). To fix it, ${dm}.`:r instanceof Oe&&(n=`Gist initialization failed (${I(r)}) \u2014 fix the Gist setup (check the token's gist scope, or run state-show / setup) before relying on sync`),t={reason:n}}return t===null?null:ta(t)}function Em(){Cn=null,po=null}var us,O$,Fe,V1,q1,oa,Cn,po,ls=A(()=>{"use strict";us=B(require("node:fs"),1);wn();jS();Wi();yu();VS();ae();ee();KS();QS();XS();Kr();st();yu();O$="overnight-report.md",Fe="state";V1=["openedAt","firstMaintainerResponseAt","issueUrl","pick","lastReviewDecision","lastCiStatus","backfilledAt","responseRule","closeReason","selfCloseReason"];q1=300;oa=class e{state;inMemoryOnly;lastLoadedMtimeMs=0;_batching=!1;_batchDirty=!1;gistStore=null;gistDegraded=!1;staleness=null;lastSuccessfulRefreshAt=null;mutationDepth=0;unpushed=!1;refreshCount=0;loadRecovery=null;constructor(t=!1){if(this.inMemoryOnly=t,t)this.state=_n();else{let r=fm();this.state=r.state,this.lastLoadedMtimeMs=r.mtimeMs,this.loadRecovery=r.recovery??null,this.tryReconcilePRCounts()}}static async createWithGist(t){let{getOctokit:r}=await Promise.resolve().then(()=>(lo(),$$)),n=r(t),s=new Xi(n),o=jt(),i,a=null;if(us.existsSync(o)){let u=fm();a=u.recovery??null;let d=await s.bootstrapWithMigration(u.state);if(i=d,d.migrated)try{let p=o+".pre-gist-migration";us.renameSync(o,p),O(Fe,`Renamed ${o} to ${p} after Gist migration`)}catch(p){k(Fe,`Failed to rename state.json after Gist migration: ${p}`)}}else i=await s.bootstrap();let c=new e(!0);return c.state=i.state,i.gistId&&(c.state.gistId=i.gistId),c.gistStore=s,c.gistDegraded=i.degraded??!1,c.inMemoryOnly=!1,c.loadRecovery=a,c.tryReconcilePRCounts(),c.unpushed=!1,i.degraded&&(c.staleness={source:"cache",reason:"initial Gist bootstrap fell back to local cache",lastSuccessfulRefresh:null,detectedAt:new Date().toISOString()}),c}tryReconcilePRCounts(){try{this.reconcilePRCounts()}catch(t){k(Fe,`PR count reconciliation failed (will retry on next load): ${I(t)}`),O(Fe,`Reconciliation error details: ${t instanceof Error?t.stack:String(t)}`)}}batch(t){if(this._batching){t();return}this._batching=!0,this._batchDirty=!1;try{t(),this._batchDirty&&this.save()}finally{this._batching=!1,this._batchDirty=!1}}autoSave(){if(this._batching){this._batchDirty=!0;return}this.save()}isSetupComplete(){return this.state.config.setupComplete===!0}markSetupComplete(){this.state.config.setupComplete=!0,this.state.config.setupCompletedAt=new Date().toISOString(),this.autoSave()}initializeWithDefaults(t){if(this.state.config.setupComplete){O(Fe,`Setup already complete, skipping initializeWithDefaults for "${t}"`);return}this.batch(()=>{this.updateConfig({githubUsername:t}),this.markSetupComplete(),O(Fe,`Initialized with defaults for user "${t}"`)})}save(t={}){if(this.state.lastRunAt=new Date().toISOString(),this.gistStore&&(this.unpushed=!0),!this.inMemoryOnly){if(this.gistStore){try{Mr(os(),xr(this.state),384)}catch(r){k(Fe,`Failed to write Gist local cache: ${I(r)}`)}return}try{this.lastLoadedMtimeMs=XA(this.state,this.lastLoadedMtimeMs)}catch(r){if(r instanceof Dr&&t.allowReloadAndLoseMutation){k(Fe,`Concurrent external write detected; reloading and discarding in-memory mutation. ${r.message}`),this.reloadIfChanged();return}throw r}}}async checkpoint(){if(!this.gistStore)return!0;this.gistStore.setState(xr(this.state));let t;try{t=await this.gistStore.push()}catch(r){throw r instanceof Lr&&(this.gistDegraded=!0),r}return this.gistDegraded=!t,t&&(this.unpushed=!1),t}isGistMode(){return this.gistStore!==null}isGistDegraded(){return this.gistDegraded}getGistHealth(){return this.gistStore===null?{mode:"local",degraded:this.state.config.persistence==="gist"?{cause:"configured-but-local",recoverable:!0}:null}:this.gistDegraded?{mode:"gist",degraded:{cause:"bootstrap-degraded",...this.staleness&&{since:this.staleness.detectedAt},recoverable:!0}}:{mode:"gist",degraded:null}}isGuidelinesAvailable(){return this.gistStore!==null}getGuidelines(t){return yT(this.gistStore,t)}setGuidelines(t,r){bT(this.gistStore,t,r),this.autoSave()}deleteGuidelines(t){wT(this.gistStore,t),this.autoSave()}listGuidelinesRepos(){return RT(this.gistStore)}getState(){return this.state}reloadIfChanged(){if(this.inMemoryOnly||this.gistStore)return!1;let t=eT(this.lastLoadedMtimeMs);return t?(this.state=t.state,this.lastLoadedMtimeMs=t.mtimeMs,this.loadRecovery=t.recovery??null,this.tryReconcilePRCounts(),!0):!1}getLoadRecovery(){return this.loadRecovery}async runMutation(t){this.mutationDepth++;try{return await t()}finally{this.mutationDepth--}}get refreshGeneration(){return this.refreshCount}hasUnpushedChanges(){return this.unpushed}forgetUnpushedChanges(){this.unpushed=!1}async refreshFromGist(t={}){if(!this.gistStore||this.mutationDepth>0&&!t.force)return!1;if(t.force&&this.mutationDepth===0&&this.unpushed)return k(Fe,"Forced Gist refresh refused: local changes are not pushed yet and nothing would re-apply them"),!1;if(!t.force&&this.unpushed){if(await this.checkpoint().catch(o=>(k(Fe,`Push before Gist refresh failed: ${I(o)}`),null))===!1)return this.staleness={source:"cache",reason:"Gist refresh skipped: local changes are not pushed yet (push failed); serving local state",lastSuccessfulRefresh:this.lastSuccessfulRefreshAt,detectedAt:new Date().toISOString()},!1;if(this.mutationDepth>0)return!1}let n=(await this.gistStore.refreshFromGist(t)).status==="refreshed";if(n){let s=this.gistStore.cachedFiles.get("state.json");if(!s)return k(Fe,"Gist refreshed but state.json missing from cache"),this.staleness={source:"cache",reason:"Gist refresh returned no state.json file",lastSuccessfulRefresh:this.lastSuccessfulRefreshAt,detectedAt:new Date().toISOString()},!1;let o=this.unpushed,i;try{i=JSON.parse(s),this.state=Gt.parse(i)}catch(c){return k(Fe,`Failed to parse refreshed Gist state: ${I(c)}`),this.staleness={source:"cache",reason:`Gist refresh succeeded but payload was invalid: ${I(c)}`,lastSuccessfulRefresh:this.lastSuccessfulRefreshAt,detectedAt:new Date().toISOString()},!1}oo(i,this.state,"Gist state"),this.tryReconcilePRCounts(),this.unpushed=!1;let a=new Date;if(this.lastSuccessfulRefreshAt=a.toISOString(),this.staleness=null,this.refreshCount++,o&&!t.force){let c="A Gist refresh replaced local state that still had un-pushed changes; they were NOT synced. Re-run the command that made the change.";k(Fe,c),this.staleness={reason:c,source:"cache",lastSuccessfulRefresh:this.lastSuccessfulRefreshAt,detectedAt:a.toISOString()}}}else this.gistStore.lastRefreshError&&(this.staleness={source:"cache",reason:I(this.gistStore.lastRefreshError),lastSuccessfulRefresh:this.lastSuccessfulRefreshAt,detectedAt:new Date().toISOString()});return n}getStateStaleness(){return this.staleness}setLastDigest(t){this.state.lastDigest=t,this.state.lastDigestAt=t.generatedAt,this.autoSave()}setLastStrategyAt(t){this.state.lastStrategyAt=t,this.autoSave()}setMonthlyMergedCounts(t){this.state.monthlyMergedCounts=t,this.autoSave()}setMonthlyClosedCounts(t){this.state.monthlyClosedCounts=t,this.autoSave()}setMonthlyOpenedCounts(t){this.state.monthlyOpenedCounts=t,this.autoSave()}setLocalRepoCache(t){this.state.localRepoCache=t,this.autoSave()}getMergedPRs(){return this.state.mergedPRs??[]}addMergedPRs(t){if(t.length===0)return{added:0,dropped:0};let{valid:r,dropped:n}=I$(t,"merged"),s=r.map(c=>this.withPick(c));if(s.length===0)return{added:0,dropped:n};this.state.mergedPRs||(this.state.mergedPRs=[]);let o=new Map(this.state.mergedPRs.map(c=>[c.url,c])),i=[],a=!1;for(let c of s){let u=o.get(c.url);u?a=x$(u,c)||a:(i.push(c),o.set(c.url,c))}return i.length===0&&!a?{added:0,dropped:n}:(this.state.mergedPRs.push(...i),this.state.mergedPRs.sort((c,u)=>u.mergedAt.localeCompare(c.mergedAt)),O(Fe,`Added ${i.length} merged PRs (total: ${this.state.mergedPRs.length})`),this.tryReconcilePRCounts(),this.autoSave(),{added:i.length,dropped:n})}withPick(t){if(!t.issueUrl||t.pick)return t;let r=t.issueUrl.toLowerCase(),n=this.getPickSnapshots().find(s=>s.issueUrl.toLowerCase()===r);return n?{...t,pick:n}:t}getMergedPRWatermark(){return this.state.mergedPRs?.[0]?.mergedAt||void 0}getClosedPRs(){return this.state.closedPRs??[]}addClosedPRs(t){if(t.length===0)return{added:0,dropped:0};let{valid:r,dropped:n}=I$(t,"closed"),s=r.map(c=>this.withPick(c));if(s.length===0)return{added:0,dropped:n};this.state.closedPRs||(this.state.closedPRs=[]);let o=new Map(this.state.closedPRs.map(c=>[c.url,c])),i=[],a=!1;for(let c of s){let u=o.get(c.url);u?a=x$(u,c)||a:(i.push(c),o.set(c.url,c))}return i.length===0&&!a?{added:0,dropped:n}:(this.state.closedPRs.push(...i),this.state.closedPRs.sort((c,u)=>u.closedAt.localeCompare(c.closedAt)),O(Fe,`Added ${i.length} closed PRs (total: ${this.state.closedPRs.length})`),this.tryReconcilePRCounts(),this.autoSave(),{added:i.length,dropped:n})}getClosedPRWatermark(){return this.state.closedPRs?.[0]?.closedAt||void 0}markPRCommentsFetched(t,r){let n=this.state.mergedPRs?.find(o=>o.url===t);if(n){n.commentsFetchedAt=r,this.autoSave();return}let s=this.state.closedPRs?.find(o=>o.url===t);s&&(s.commentsFetchedAt=r,this.autoSave())}setLedgerResponse(t,r,n){let s=this.state.mergedPRs?.find(o=>o.url===t)??this.state.closedPRs?.find(o=>o.url===t);s&&(r===void 0?delete s.firstMaintainerResponseAt:s.firstMaintainerResponseAt=r,s.responseRule=n,this.autoSave())}markPRLearningsExtracted(t,r){let n=this.state.mergedPRs?.find(o=>o.url===t);if(n){n.learningsExtractedAt=r,this.autoSave();return}let s=this.state.closedPRs?.find(o=>o.url===t);s&&(s.learningsExtractedAt=r,this.autoSave())}updateConfig(t){this.state.config={...this.state.config,...t},this.autoSave()}addIssue(t){let r=qe(t.url),n=this.state.activeIssues.find(s=>r?qe(s.url)===r:s.url===t.url);if(n){n.status=t.status,n.updatedAt=t.updatedAt,O(Fe,`Issue ${t.url} already tracked; refreshed claim stamp to ${t.updatedAt}`),this.autoSave();return}this.state.activeIssues.push(t),O(Fe,`Added issue: ${t.repo}#${t.number}`),this.autoSave()}releaseIssue(t,r){let n=qe(t),s=this.state.activeIssues.findIndex(i=>n?qe(i.url)===n:i.url===t);if(s===-1)return O(Fe,`releaseIssue: ${t} is not tracked; nothing to release`),"not_tracked";let o=this.state.activeIssues[s];if(r!==void 0){let i=Date.parse(o.updatedAt),a=Date.parse(r);if(Number.isNaN(i)||Number.isNaN(a)||i>=a)return O(Fe,`releaseIssue: keeping ${o.repo}#${o.number}; claim stamp ${o.updatedAt} is not before ${r}`),"newer_claim"}return this.state.activeIssues.splice(s,1),O(Fe,`Released issue claim: ${o.repo}#${o.number}`),this.autoSave(),"released"}addTrustedProject(t){this.state.config.trustedProjects.includes(t)||(this.state.config.trustedProjects.push(t),O(Fe,`Added trusted project: ${t}`),this.autoSave())}static matchesExclusion(t,r,n){let s=t.toLowerCase();return!!(r.some(o=>o.toLowerCase()===s)||n?.some(o=>o.toLowerCase()===s.split("/",1)[0]))}cleanupExcludedData(t,r){let n=i=>e.matchesExclusion(i,t,r),s=this.state.config.trustedProjects.length;this.state.config.trustedProjects=this.state.config.trustedProjects.filter(i=>!n(i));let o=s-this.state.config.trustedProjects.length;o>0&&(O(Fe,`Removed ${o} trusted project(s) for excluded repos/orgs`),this.autoSave())}getStarredRepos(){return this.state.config.starredRepos||[]}setStarredRepos(t){this.state.config.starredRepos=t,this.state.config.starredReposLastFetched=new Date().toISOString(),O(Fe,`Updated starred repos: ${t.length} repositories`),this.autoSave()}isStarredReposStale(){let t=this.state.config.starredReposLastFetched;if(!t)return!0;let r=1440*60*1e3,n=new Date(t);return new Date().getTime()-n.getTime()>r}shelvePR(t){return this.state.config.shelvedPRUrls||(this.state.config.shelvedPRUrls=[]),this.state.config.shelvedPRUrls.includes(t)?!1:(this.state.config.shelvedPRUrls.push(t),this.autoSave(),!0)}unshelvePR(t){if(!this.state.config.shelvedPRUrls)return!1;let r=this.state.config.shelvedPRUrls.indexOf(t);return r===-1?!1:(this.state.config.shelvedPRUrls.splice(r,1),this.autoSave(),!0)}isPRShelved(t){return this.state.config.shelvedPRUrls?.includes(t)??!1}dismissIssue(t,r,n={}){return this.state.config.dismissedIssues||(this.state.config.dismissedIssues={}),t in this.state.config.dismissedIssues&&!n.refresh?!1:(this.state.config.dismissedIssues[t]=r,this.setDismissedPRHead(t,n.headSha),this.autoSave(),!0)}undismissIssue(t){return!this.state.config.dismissedIssues||!(t in this.state.config.dismissedIssues)?!1:(delete this.state.config.dismissedIssues[t],this.setDismissedPRHead(t,void 0),this.autoSave(),!0)}getIssueDismissedAt(t){return this.state.config.dismissedIssues?.[t]}getDismissedPRHead(t){return this.state.config.dismissedPRHeads?.[t]}setDismissedPRHead(t,r){this.state.config.dismissedPRHeads||(this.state.config.dismissedPRHeads={}),r===void 0?delete this.state.config.dismissedPRHeads[t]:this.state.config.dismissedPRHeads[t]=r}getPickSnapshots(){return this.state.pickSnapshots??[]}recordPickSnapshots(t){let r=new Set(this.getPickSnapshots().map(s=>s.issueUrl.toLowerCase())),n=t.filter(s=>{let o=s.issueUrl.toLowerCase();return r.has(o)?!1:(r.add(o),!0)});n.length!==0&&(this.state.pickSnapshots=[...this.getPickSnapshots(),...n].slice(-q1),this.autoSave())}getSearchSeen(){return this.state.searchSeen??[]}setSearchSeen(t){this.state.searchSeen=t,this.autoSave()}getOvernightReportDocument(){let t=this.gistStore?.getDocument(O$)??null;return t===""?null:t}setOvernightReportDocument(t){this.gistStore?.setDocument(O$,t)}getLastOvernight(){return this.state.lastOvernight}setLastOvernight(t){this.state.lastOvernight=t,this.autoSave()}getSearchRotation(){return this.state.searchRotation}setSearchRotation(t){this.state.searchRotation=t,this.autoSave()}getWorkClaims(){return this.state.workClaims??[]}getActiveWorkClaims(t=Date.now()){return lr(this.getWorkClaims(),t)}pruneWorkClaims(t){let r=this.getWorkClaims();for(let n of r)Number.isFinite(Date.parse(n.expiresAt))||k(Fe,`Pruning work claim on ${n.url} (session ${n.session}): expiresAt "${n.expiresAt}" is not a date`);return lr(r,t)}upsertWorkClaim(t,r=Date.now()){let n=Qt(t.url),s=this.pruneWorkClaims(r),o=s.some(i=>Qt(i.url)===n);return this.state.workClaims=[...s.filter(i=>Qt(i.url)!==n),t],this.autoSave(),o}finishWorkClaim(t,r,n=Date.now()){let s=Qt(t),o=this.pruneWorkClaims(n),i=o.find(c=>Qt(c.url)===s);if(!i)return;let a=em(i,r);return this.state.workClaims=o.map(c=>c===i?a:c),this.autoSave(),a}releaseWorkClaims(t,r=Date.now()){let n=t.url===void 0?void 0:Qt(t.url),s=a=>n!==void 0&&Qt(a.url)!==n||t.session!==void 0&&a.session!==t.session?!1:t.kind===void 0||a.kind===t.kind,o=this.pruneWorkClaims(r),i=o.filter(a=>s(a)).map(a=>a.url);return i.length>0&&(this.state.workClaims=o.filter(a=>!s(a)),this.autoSave()),i}setStatusOverride(t,r,n){this.state.config.statusOverrides||(this.state.config.statusOverrides={}),this.state.config.statusOverrides[t]={status:r,setAt:new Date().toISOString(),lastActivityAt:n},this.autoSave()}clearStatusOverride(t){return!this.state.config.statusOverrides||!(t in this.state.config.statusOverrides)?!1:(delete this.state.config.statusOverrides[t],this.autoSave(),!0)}getStatusOverride(t,r){let n=this.state.config.statusOverrides?.[t];if(n){if(r&&r>n.lastActivityAt){this.clearStatusOverride(t);return}return n}}getRepoScore(t){return oT(this.state,t)}updateRepoScore(t,r){WS(this.state,t,r),this.autoSave()}getReposWithMergedPRs(){return iT(this.state)}getReposWithOpenPRs(){return aT(this.state)}getHighScoringRepos(t){return cT(this.state,t)}getLowScoringRepos(t){return uT(this.state,t)}getStats(){return mT(this.state)}renameRepo(t,r){pT(this.state,t,r),this.autoSave()}reconcilePRCounts(){let t=this.state.mergedPRs??[],r=this.state.closedPRs??[];if(t.length===0&&r.length===0)return;lT(this.state,t,r)&&this.autoSave()}},Cn=null,po=null});async function Qr(e,t,r){let n=0,s=!1,o=async()=>{for(;n<e.length&&!s;){let a=e[n++];try{await t(a)}catch(c){throw s=!0,c}}},i=Math.min(r,e.length);await Promise.all(Array.from({length:i},()=>o()))}function Am(e){let t=e.filter(n=>n.status==="rejected");if(t.length===0)return;throw(t.find(n=>le(n.reason))??t[0]).reason}var Pr,ds=A(()=>{"use strict";ee();Pr=5});async function ze(e,t=100,r=10){let n=[];for(let s=1;s<=r;s++){let{data:o}=await e(s);if(n.push(...o),o.length<t)return{items:n,truncated:!1}}return{items:n,truncated:!0}}async function Tm(e,t=100,r=10){let{items:n}=await ze(e,t,r);return n}var mo=A(()=>{"use strict"});function ps(){return C_||(C_=new Pu),C_}async function aa(e,t,r){let n=e.getInflight(t);if(n)return O(Pn,`Dedup hit for ${t}`),await n;let o=(async()=>{let a={},c=e.get(t);c&&(a["if-none-match"]=c.etag);try{let u=await r(a),d=u.headers?.etag;return d&&e.set(t,d,u.data),u.data}catch(u){if(Q1(u)){let d=e.get(t);if(d)return O(Pn,`304 cache hit for ${t}`),d.body}throw u}})(),i=e.setInflight(t,o);try{return await o}finally{i()}}function Q1(e){return je(e)===304}var Ct,Cu,M$,Pn,J1,Y1,Pu,C_,Eu=A(()=>{"use strict";Ct=B(require("node:fs"),1),Cu=B(require("node:path"),1),M$=B(require("node:crypto"),1);Kr();ae();ee();Pn="http-cache",J1=1440*60*1e3,Y1=2e3,Pu=class{cacheDir;maxEntries;inflightRequests=new Map;constructor(t,r=Y1){this.cacheDir=t??om(),this.maxEntries=r}keyFor(t){return M$.createHash("sha256").update(t).digest("hex")}pathFor(t){return Cu.join(this.cacheDir,`${this.keyFor(t)}.json`)}getIfFresh(t,r){let n=this.get(t);if(!n)return null;let s=Date.now()-new Date(n.cachedAt).getTime();return!Number.isFinite(s)||s<0||s>r?null:n.body}get(t){let r=this.pathFor(t);try{let n=Ct.readFileSync(r,"utf8"),s=JSON.parse(n);return s.url!==t?(O(Pn,`Cache collision detected for ${t}, ignoring`),null):s}catch(n){if(n&&typeof n=="object"&&n.code!=="ENOENT"){let s=n instanceof Error?n.message:"unknown error";O(Pn,`Cache read failed for ${t} (treating as miss): ${s}`)}return null}}set(t,r,n){let s={etag:r,url:t,body:n,cachedAt:new Date().toISOString()};try{Ct.writeFileSync(this.pathFor(t),JSON.stringify(s),{encoding:"utf8",mode:384}),O(Pn,`Cached response for ${t}`),this.evictIfExceeds(this.maxEntries)}catch(o){O(Pn,`Failed to write cache for ${t}`,o)}}evictIfExceeds(t){if(!(t<=0))try{let r=Ct.readdirSync(this.cacheDir).filter(i=>i.endsWith(".json"));if(r.length<=t)return;let n=r.map(i=>{let a=Cu.join(this.cacheDir,i);try{return{fullPath:a,mtimeMs:Ct.statSync(a).mtimeMs}}catch{return null}}).filter(i=>i!==null).sort((i,a)=>i.mtimeMs-a.mtimeMs),s=n.length-t,o=0;for(let i=0;i<s;i++)try{Ct.unlinkSync(n[i].fullPath),o++}catch{}o>0&&O(Pn,`Capped cache at ${t} entries: evicted ${o} oldest`)}catch{}}hasInflight(t){return this.inflightRequests.has(t)}getInflight(t){return this.inflightRequests.get(t)}setInflight(t,r){return this.inflightRequests.set(t,r),()=>{this.inflightRequests.delete(t)}}evictStale(t=J1){let r=0;try{let n=Ct.readdirSync(this.cacheDir),s=Date.now();for(let o of n){if(!o.endsWith(".json"))continue;let i=Cu.join(this.cacheDir,o);try{let a=Ct.readFileSync(i,"utf8"),c=JSON.parse(a);s-new Date(c.cachedAt).getTime()>t&&(Ct.unlinkSync(i),r++)}catch{try{Ct.unlinkSync(i),r++}catch{}}}}catch{}return r>0&&O(Pn,`Evicted ${r} stale cache entries`),r}clear(){try{let t=Ct.readdirSync(this.cacheDir);for(let r of t)r.endsWith(".json")&&Ct.unlinkSync(Cu.join(this.cacheDir,r));O(Pn,"Cache cleared")}catch{}}size(){try{return Ct.readdirSync(this.cacheDir).filter(t=>t.endsWith(".json")).length}catch{return 0}}},C_=null});function $m(){return{status:"unknown",failingCheckNames:[],failingCheckConclusions:new Map}}function Om(e,t,r){if(r==="cancelled"||r==="timed_out")return"infrastructure";if(r==="action_required")return"auth_gate";let n=e.toLowerCase();if(N$.some(s=>s.test(n)))return"auth_gate";if(F$.some(s=>s.test(n)))return"fork_limitation";if(G$.some(s=>s.test(n)))return"infrastructure";if(t){let s=t.toLowerCase();if(N$.some(o=>o.test(s)))return"auth_gate";if(F$.some(o=>o.test(s)))return"fork_limitation";if(G$.some(o=>o.test(s)))return"infrastructure"}return"actionable"}function Au(e,t){return e.map(r=>{let n=t?.get(r);return{name:r,category:Om(r,void 0,n),conclusion:n}})}function P_(e){let{ciStatus:t,failingCheckNames:r,classifiedChecks:n}=e;if(t==="passing")return{category:"all_passing",summary:"All checks passing",action:"none"};if(t==="pending"){let s=r.length;return{category:"blocked",summary:s>0?`${s} pending check(s); CI run incomplete`:"CI checks pending",action:"request_rerun"}}if(t==="failing"){let s=n.filter(a=>a.category==="actionable");if(s.length>0){let a=s.slice(0,3).map(u=>u.name).join(", "),c=s.length>3?` (+${s.length-3} more)`:"";return{category:"failing",summary:`${s.length} actionable failure(s): ${a}${c}`,action:"investigate"}}return n.length===0?{category:"failing",summary:"CI reported failure but no check details available",action:"investigate"}:n.some(a=>a.category==="infrastructure")?{category:"blocked",summary:`${n.length} non-actionable failure(s) including infrastructure issues; rerun may resolve`,action:"request_rerun"}:{category:"fork_limitation",summary:`${n.length} non-actionable failure(s) (fork limits / auth gates)`,action:"informational"}}return{category:"not_running",summary:"No CI checks reported",action:"check_workflows"}}function X1(e){let t=!1,r=!1,n=!1,s=[],o=new Map;for(let i of e)i.conclusion==="failure"||i.conclusion==="cancelled"||i.conclusion==="timed_out"||i.conclusion==="action_required"?(t=!0,s.push(i.name),o.set(i.name,i.conclusion)):i.conclusion===null&&i.status==="waiting"?(t=!0,s.push(i.name),o.set(i.name,"action_required")):i.conclusion===null&&i.status!=="completed"?r=!0:i.conclusion==="success"&&(n=!0);return{hasFailingChecks:t,hasPendingChecks:r,hasSuccessfulChecks:n,failingCheckNames:s,failingCheckConclusions:o}}function eB(e){let t=e.statuses.filter(c=>{let u=(c.description||"").toLowerCase();return!(c.state==="failure"&&(u.includes("authorization required")||u.includes("authorize")))}),r=t.some(c=>c.state==="failure"||c.state==="error"),n=t.some(c=>c.state==="pending"),s=t.some(c=>c.state==="success"),o;r?o="failure":n?o="pending":s||t.length===0?o="success":o=e.state;let i=e.statuses.length>0,a=[];for(let c of t)(c.state==="failure"||c.state==="error")&&a.push(c.context);return{effectiveCombinedState:o,hasStatuses:i,failingStatusNames:a}}function tB(e,t,r){let{hasFailingChecks:n,hasPendingChecks:s,hasSuccessfulChecks:o,failingCheckNames:i,failingCheckConclusions:a}=e,{effectiveCombinedState:c,hasStatuses:u,failingStatusNames:d}=t,p=[...i,...d];return n||c==="failure"||c==="error"?{status:"failing",failingCheckNames:p,failingCheckConclusions:a}:s||c==="pending"?{status:"pending",failingCheckNames:[],failingCheckConclusions:new Map}:o||c==="success"?{status:"passing",failingCheckNames:[],failingCheckConclusions:new Map}:$m()}function E_(e,t){let r=new Map;for(let i of e){let a=r.get(i.name);(!a||new Date(i.started_at??0)>new Date(a.started_at??0))&&r.set(i.name,i)}let n=[...r.values()],s=X1(n),o=eB(t);return tB(s,o,n.length)}async function A_(e,t,r,n){if(!n)return $m();try{let[s,o]=await Promise.all([e.repos.getCombinedStatusForRef({owner:t,repo:r,ref:n,per_page:100}),Tm(c=>e.checks.listForRef({owner:t,repo:r,ref:n,per_page:100,page:c}).then(u=>({data:u.data.check_runs}))).catch(c=>{let u=je(c);if(u===429)throw c;if(u===403){let d=I(c).toLowerCase();if(d.includes("rate limit")||d.includes("abuse detection"))throw c}return u===404?O("pr-monitor",`Check runs 404 for ${t}/${r}@${n.slice(0,7)} (no checks configured)`):k("pr-monitor",`Non-404 error fetching check runs for ${t}/${r}@${n.slice(0,7)}: ${u??c}`),null})]),i=s.data;return E_(o??[],i)}catch(s){let o=je(s);if(o===401||o===403||o===429)throw s;return o===404?O("pr-monitor",`CI check 404 for ${t}/${r} (no CI configured)`):k("pr-monitor",`Failed to check CI for ${t}/${r}@${n.slice(0,7)}: ${I(s)}`),$m()}}var F$,N$,G$,Tu=A(()=>{"use strict";ee();ae();mo();F$=[/vercel/i,/netlify/i,/\bpreview\s*deploy/i,/\bdeploy\s*preview/i,/storybook/i,/chromatic/i,/percy/i,/cloudflare pages/i,/\binternal\b(?!\s+(?:api|test|integration|smoke|unit|e2e|regression|functional))/i],N$=[/authoriz/i,/approval/i,/\bcla\b/i,/license\/cla/i,/\b(?:pr|type|require[sd]?|check|missing)[\s-]+(?:\w+[\s-]+)?labels?\b/i,/\blabeler\b/i,/\btriage\b/i],G$=[/\binstall\s*(os\s*)?dep(endenc|s\b)/i,/\bsetup\s+fail(ed|ure)?\b/i,/\bservice\s*unavailable/i,/\binfrastructure/i,/\bblacksmith\b/i,/\breadthedocs\b/i]});function $u(e){if(e.status==="rejected")throw e.reason;return e.value}function U$(e){let t=q(e);if(!t||t.type!=="pull")throw new j(`Invalid PR URL format: ${e}`);return t}async function sB(e,t){let r={items:[],totalCount:0,pagesRead:0,incomplete:!1};for(let n=1;n<=I_;n++){let s;try{({data:s}=await e.search.issuesAndPullRequests({q:t,page:n,sort:"updated",order:"desc",per_page:$_}))}catch(o){if(le(o))throw o;return r.failure={page:n,error:o},r}if(r.pagesRead=n,r.totalCount=s.total_count,s.incomplete_results&&(r.incomplete=!0),r.items.push(...s.items),s.items.length<$_||r.items.length>=r.totalCount)break}return r}function oB(e,t){if(t.failure)return`GitHub search for ${e} failed on page ${t.failure.page} (${er(t.failure.error)}); only the ${t.items.length} result(s) from the ${t.pagesRead} page(s) before it were read this run.`;if(t.items.length<t.totalCount)return`GitHub Search API reports ${t.totalCount} ${e}, but only the ${t.items.length} most recently updated were read (${t.pagesRead} page(s) of ${$_}). Older reviewed PRs are not checked this run.`}function iB(e,t){let r=`open PRs you ${e} (not authored)`,n=[],s=oB(r,t);return s!==void 0&&n.push(s),t.incomplete&&n.push(`GitHub Search API returned incomplete results for ${r} (the search timed out server-side); some reviewed PRs may be missing this run.`),n}function aB(e,t){return(Date.parse(t.updatedAt)||0)-(Date.parse(e.updatedAt)||0)}async function j$(e,t){let r=t.githubUsername;if(!r)throw new Oe("No GitHub username configured. Run setup first.");let n=new O_(t),s=[],o=new Set,i=[];for(let{qualifier:a,label:c}of nB){let u=await sB(e,`is:pr is:open is:public ${a}:${r} -author:${r}`);for(let d of u.items){if(o.has(d.html_url))continue;o.add(d.html_url);let p=n.toRef(d);p&&s.push(p)}for(let d of iB(c,u))i.push(d),k(T_,d)}return s.sort(aB),O(T_,`Found ${s.length} open PRs reviewed by @${r}`),{prs:s,warnings:i}}async function z$(e,t){let{owner:r,repo:n,number:s}=U$(t),o=await Promise.allSettled([e.pulls.get({owner:r,repo:n,pull_number:s}),ze(f=>e.issues.listComments({owner:r,repo:n,page:f,issue_number:s,per_page:100})),ze(f=>e.pulls.listReviews({owner:r,repo:n,page:f,pull_number:s,per_page:100})),ze(f=>e.pulls.listReviewComments({owner:r,repo:n,page:f,pull_number:s,per_page:100})),ze(f=>e.pulls.listCommits({owner:r,repo:n,page:f,pull_number:s,per_page:100}))]);Am(o);let i=$u(o[0]).data,a=$u(o[1]),c=$u(o[2]),u=$u(o[3]),d=$u(o[4]),p=[];return a.truncated&&p.push("comments"),c.truncated&&p.push("reviews"),u.truncated&&p.push("review comments"),(d.items.length>=rB||d.items.at(-1)?.sha!==i.head.sha||d.truncated)&&p.push("commits"),{truncatedLists:p,pr:{headSha:i.head.sha,state:i.state,author:i.user?.login,title:i.title},comments:a.items,reviews:c.items,reviewComments:u.items,commits:d.items}}async function B$(e,t,r,n){let{owner:s,repo:o}=U$(t);try{let{data:i}=await e.repos.compareCommitsWithBasehead({owner:s,repo:o,basehead:`${r}...${n}`,per_page:1});return i.status}catch(i){if(je(i)===404)return"missing";throw i}}var T_,I_,$_,rB,nB,O_,x_=A(()=>{"use strict";ds();ee();ae();mo();st();T_="reviewed-prs",I_=3,$_=100,rB=250,nB=[{qualifier:"reviewed-by",label:"reviewed"},{qualifier:"commenter",label:"commented on"}];O_=class{constructor(t){this.config=t;this.usernameLower=t.githubUsername.toLowerCase(),this.excludedRepos=new Set((t.excludeRepos??[]).map(r=>r.toLowerCase())),this.excludedOrgs=new Set((t.excludeOrgs??[]).map(r=>r.toLowerCase()))}config;usernameLower;excludedRepos;excludedOrgs;isRepoExcluded(t,r){let n=t.toLowerCase();return kr(t,this.config.githubUsername)||zi(t,this.config.untrackedOrgs)?!0:this.excludedRepos.has(r.toLowerCase())||this.excludedOrgs.has(n)}toRef(t){if(!t.pull_request)return;let r=q(t.html_url);if(!r||r.type!=="pull"){k(T_,`Skipping reviewed PR with unparseable URL: ${t.html_url}`);return}let n=t.user?.login??"",s=`${r.owner}/${r.repo}`;if(!(n.toLowerCase()===this.usernameLower||this.isRepoExcluded(r.owner,s)))return{repo:s,author:n,url:t.html_url,number:r.number,title:t.title,updatedAt:t.updated_at}}}});var H$={};re(H$,{byDateDescending:()=>D_,daysBetween:()=>ms,formatRelativeTime:()=>Ou});function ms(e,t=new Date){return Math.max(0,Math.floor((t.getTime()-e.getTime())/(1e3*60*60*24)))}function Ou(e){let t=new Date(e),r=Date.now()-t.getTime();if(r<0)return"just now";let n=Math.floor(r/6e4),s=Math.floor(r/36e5),o=Math.floor(r/864e5);return n<60?`${n}m ago`:s<24?`${s}h ago`:o<30?`${o}d ago`:t.toLocaleDateString()}function D_(e){return(t,r)=>{let n=new Date(e(t)||0).getTime();return new Date(e(r)||0).getTime()-n}}var ca=A(()=>{"use strict"});function lB(e,t){if(!e||!t)return!0;let r=e.toLowerCase();return cB.has(r)?!0:r===t.toLowerCase()}function ua(e){return e?new Date(e).getTime():Number.NaN}function dB(e,t){let r=ua(e),n=ua(t);return!Number.isFinite(r)||!Number.isFinite(n)?!1:r-n>=uB}function W$(e){let{latestCommitDate:t,latestCommitAuthor:r,contributorUsername:n}=e;if(t)return lB(r,n)?t:void 0}function V$(e,t,r){if(!e||!t||!dB(e,t))return!1;if(r){let n=ua(e),s=ua(r);if(!Number.isFinite(n)||!Number.isFinite(s)||n<s)return!1}return!0}function q$(e,t){if(!e||!t)return!1;let r=ua(e),n=ua(t);return!Number.isFinite(r)||!Number.isFinite(n)?!1:r>=n}function pB(e){let{ciStatus:t,hasMergeConflict:r,hasUnrespondedComment:n,reviewDecision:s,lastMaintainerCommentDate:o,latestChangesRequestedDate:i,hasActionableCIFailure:a=!0}=e,c=W$(e),u=[];return n&&!(s==="approved"&&(t==="passing"||t==="unknown"))&&!V$(c,o,i)&&u.push("needs_response"),s==="changes_requested"&&i&&!q$(c,i)&&u.push("needs_changes"),t==="failing"&&a&&u.push("failing_ci"),r&&u.push("merge_conflict"),u.length>0?u:void 0}function L_(e){let t=mB(e);t.status==="waiting_on_maintainer"&&e.hasMergeConflict&&(t={status:"needs_addressing",actionReason:"merge_conflict",stalenessTier:t.stalenessTier});let r=pB(e);return r?{...t,actionReasons:r}:t}function mB(e){let{ciStatus:t,hasMergeConflict:r,hasUnrespondedComment:n,reviewDecision:s,daysSinceActivity:o,daysSinceMaintainerActivity:i=o,dormantThreshold:a,approachingThreshold:c,lastMaintainerCommentDate:u,latestChangesRequestedDate:d,hasActionableCIFailure:p=!0}=e,m="active";i>=a?m="dormant":i>=c&&(m="approaching_dormant");let f=W$(e);return n?V$(f,u,d)?t==="failing"&&p?{status:"needs_addressing",actionReason:"failing_ci",stalenessTier:m}:{status:"waiting_on_maintainer",waitReason:"changes_addressed",stalenessTier:m}:s==="approved"&&(t==="passing"||t==="unknown")?{status:"waiting_on_maintainer",waitReason:"pending_merge",stalenessTier:m}:{status:"needs_addressing",actionReason:"needs_response",stalenessTier:m}:s==="changes_requested"&&d?q$(f,d)?t==="failing"&&p?{status:"needs_addressing",actionReason:"failing_ci",stalenessTier:m}:{status:"waiting_on_maintainer",waitReason:"changes_addressed",stalenessTier:m}:{status:"needs_addressing",actionReason:"needs_changes",stalenessTier:m}:t==="failing"?p?o>=5?{status:"waiting_on_maintainer",waitReason:"stale_ci_failure",stalenessTier:m}:{status:"needs_addressing",actionReason:"failing_ci",stalenessTier:m}:{status:"waiting_on_maintainer",waitReason:"ci_blocked",stalenessTier:m}:r?{status:"needs_addressing",actionReason:"merge_conflict",stalenessTier:m}:s==="approved"&&(t==="passing"||t==="unknown")?{status:"waiting_on_maintainer",waitReason:"pending_merge",stalenessTier:m}:{status:"waiting_on_maintainer",waitReason:"pending_review",stalenessTier:m}}var cB,uB,M_=A(()=>{"use strict";cB=new Set(["autofix-ci[bot]","prettier-ci[bot]","pre-commit-ci[bot]"]),uB=120*1e3});function Pt(e,t){if(t==="Bot")return!0;let r=e.toLowerCase();return r.includes("[bot]")||r.endsWith("-bot")||r.endsWith("-robot")||fB.has(r)}function la(e){if(!e||e.length>100||e.includes("?"))return!1;let t=e.toLowerCase();return["thanks","thank you","lgtm","looks good","will review","we'll review","we'll get to this","noted","got it","will look","will check"].some(n=>t.includes(n))}function J$(e){return e.replaceAll(/:[\w+-]+:/g," ").replaceAll(/[^\p{L}\p{N}+]+/gu," ").trim().toLowerCase()}function fo(e){let t=J$(e);return t===""||gB.has(t)}function Im(e){return hB.has(J$(e))}function K$(e){return e.replaceAll(/\s+/g," ").trim()}function Y$(e){let t=[],r=!1;for(let n of e.split(`
79
79
  `)){if(/^\s{0,3}(?:```|~~~)/.test(n)){r=!r;continue}let s=/^\s*>/.test(n)||/^(?: {4}|\t)/.test(n);!r&&!s&&t.push(n)}return t}function Q$(e){return Y$(e).join(`
80
80
  `).replaceAll(/`[^`\n]*`/g," ")}function da(e,t){let r=K$(Y$(t).join(`
81
81
  `)).toLowerCase();if(r.length<Z$)return!1;for(let n of e.split(`
@@ -341,10 +341,10 @@ ${o.join(`
341
341
  ${s.join(`
342
342
  `)}
343
343
  }`;try{return{data:await e.graphql(i,{...o,...r?{request:{retries:0}}:{}}),permanent:new Set}}catch(a){let c=a.data;if(!c||Je(a))throw a;let u=a.errors??[];return{data:c,permanent:new Set(u.filter(d=>E4.has(d.type??"")).map(d=>String(d.path?.[0])))}}}function T4(e,t,r){let n=t?.issues?.nodes;if(!t||!n)return null;if(t.isArchived)return[];if((t.stargazerCount??0)<r)return[];let s=t.nameWithOwner;return n.flatMap(o=>o?o.assignees.totalCount>0?[]:(o.closedByPullRequestsReferences?.totalCount??0)>0?[]:[{html_url:o.url,repository_url:`https://api.github.com/repos/${s}`,updated_at:o.updatedAt,title:o.title,labels:(o.labels?.nodes??[]).map(i=>({name:i.name})),repo:s,listedAs:e,createdAt:o.createdAt,maintainerFiled:Ba.has(o.authorAssociation)&&!o.viewerDidAuthor,commentCount:o.comments.totalCount}]:[])}async function $4(e,t,r=0){let n=t.filter(u=>{let d=u.split("/");return d.length===2&&d.every(p=>v4.test(p))}),s=new Map,o=t.length-n.length,i=!1,a=async(u,d=!1)=>{try{let{data:p,permanent:m}=await A4(e,u,d),f=[];return u.forEach((g,y)=>{let b=T4(g,p[`r${y}`],r);if(b)for(let R of b)s.set(R.html_url,R);else u.length>1&&!m.has(`r${y}`)?f.push(g):o++}),f}catch(p){if($e(p)===401)throw p;return Je(p)?(z(pg,`Rate limit hit listing warm repos: ${K(p)}`),i=!0,[]):(z(pg,`Failed to list issues for ${u.join(", ")}: ${K(p)}`),null)}},c=0;for(let u=0;u<n.length&&!i;u+=jD){u>0&&await Wt(S4);let d=n.slice(u,u+jD),p=await a(d),m=p!==null;p===null&&d.length===1&&o++;for(let f of p??(d.length>1?d:[])){if(i)break;await a([f],p===null)===null?o++:m=!0}if(c=m?0:c+1,c>=_4){z(pg,`${c} batches in a row returned nothing; stopping the warm-repo walk`),o+=Math.max(0,n.length-(u+d.length));break}}return{items:[...s.values()],failedRepos:o,rateLimitHit:i}}function I4(e,t,r=new Date){let n=s=>{let o=(r.getTime()-Date.parse(s.createdAt))/O4;return(o<=2?3:o<=14?2:o<=30?1:0)+(s.maintainerFiled?3:0)+(s.commentCount===0?2:0)+(t(s.repo)??t(s.listedAs)??5)/2};return e.map(s=>({issue:s,score:n(s)})).sort((s,o)=>o.score-s.score||Date.parse(o.issue.createdAt)-Date.parse(s.issue.createdAt)).map(s=>s.issue)}async function BD(e,t,r,n,s,o,i=0){let a=et(),c=await $4(e,r,i),u=R=>new Set(s(R).map(h=>h.html_url)),d=u(c.items),p=u(c.items.map(R=>({...R,repository_url:`https://api.github.com/repos/${R.listedAs}`}))),m=I4(c.items.filter(R=>d.has(R.html_url)&&p.has(R.html_url)&&a.getEntryIfFresh(zD(R.html_url),P4)===null),o),f=yl(m.map(R=>({url:R.html_url,issue:{repo:R.repo}})),k4).slice(0,Math.min(n*2,C4)).map(R=>R.url),g=[],y=c.rateLimitHit,b=null;if(f.length>0&&!c.rateLimitHit)try{let R=await t.vetIssuesParallel(f,f.length,"merged_pr");y||=R.rateLimitHit;for(let S of R.candidates)S.recommendation==="skip"&&a.set(zD(S.issue.url),"",!0);let h=new Map(f.map((S,w)=>[S,w])),_=[...R.candidates].sort((S,w)=>(h.get(S.issue.url)??0)-(h.get(w.issue.url)??0));g=yl([..._.filter(S=>S.recommendation!=="skip"),..._.filter(S=>S.recommendation==="skip")],lg).slice(0,n)}catch(R){if($e(R)===401)throw R;y||=Je(R),b=K(R),z(pg,`Vetting warm-repo issues failed: ${b}`)}return{candidates:g,allReposFailed:r.length>0&&c.failedRepos>=r.length,rateLimitHit:y,vetError:b}}var pg,jD,R4,S4,_4,v4,k4,C4,P4,E4,O4,zD,HD=A(()=>{ct();an();it();Ha();dg();At();pg="warm-repos",jD=8,R4=30,S4=500,_4=2,v4=/^[A-Za-z0-9_.-]+$/,k4=lg+1,C4=60,P4=1440*60*1e3,E4=new Set(["NOT_FOUND","FORBIDDEN"]);O4=1440*60*1e3;zD=e=>gr(`warm-skip:${e}`)});function fg(e){return e.personalization?.kind==="boosted"?e.personalization.score:0}function mg(e){return new Set((e??[]).map(t=>t.trim().toLowerCase()).filter(Boolean))}function WD(e,t={}){let r=mg(t.preferLanguages),n=mg(t.preferRepos),s=mg(t.avoidRepos),o=mg(t.boostIssueTypes);return r.size===0&&n.size===0&&s.size===0&&o.size===0?e:e.map(i=>{let a=0,c=[],u=i.issue.repo.toLowerCase();n.size>0&&n.has(u)&&(a+=20,c.push(`repo affinity: ${i.issue.repo}`));let d=i.projectHealth.checkFailed?null:i.projectHealth.language;if(r.size>0&&d&&r.has(d.toLowerCase())&&(a+=10,c.push(`language match: ${d}`)),o.size>0){let p=i.issue.labels.find(m=>o.has(m.toLowerCase()));p&&(a+=10,c.push(`issue type: ${p}`))}return s.size>0&&s.has(u)&&(a-=15,c.push(`avoided repo: ${i.issue.repo}`)),c.length===0?i:{...i,personalization:{kind:"boosted",score:a,reasons:c}}})}function VD(e,t,r){if(t<=0)return[];let n=Math.max(0,Math.min(1,r));if(n===0)return e.slice(0,t);let s=Math.min(Math.floor(t*n),t);if(s===0)return e.slice(0,t);let o=t-s,i=[],a=new Set;for(let c of e){if(i.length>=o)break;i.push(c),a.add(c.issue.url)}for(let c of e){if(i.length>=t)break;a.has(c.issue.url)||fg(c)===0&&(i.push({...c,personalization:{kind:"diversity"}}),a.add(c.issue.url))}for(let c of e){if(i.length>=t)break;a.has(c.issue.url)||(i.push(c),a.add(c.issue.url))}return i}var qD=A(()=>{});function JD(e,t,r){if(e.length<=t)return[...e];let n=r*t%e.length;return Array.from({length:t},(s,o)=>e[(n+o)%e.length])}function ZD(e){return t=>t.filter(r=>{let n=ut(r.repository_url);if(!n)return!1;let s=n.toLowerCase();if(e.excludedRepos.has(s))return!1;if(e.excludeOrgs.size>0){let c=s.split("/")[0];if(c&&e.excludeOrgs.has(c))return!1}if(e.aiBlocklisted.has(s)||e.lowScoringRepos.has(s)||e.skippedUrls.has(r.html_url))return!1;let o=new Date(r.updated_at);if(Number.isNaN(o.getTime())||ja(o,e.now)>e.maxAgeDays||!e.includeDocIssues&&Q0(r))return!1;let a=r.maintainerFiled===!0&&e.complexRepos.has(s);return!X0(r,{labelsOnly:a})})}async function N4(e,t,r,n,s,o,i){Be(Ce,`Phase 0: Listing open issues in ${r.length} merged-PR repos (no label filter)...`);let{candidates:a,allReposFailed:c,rateLimitHit:u,vetError:d}=await BD(e,t,r,n,s,o,i);return Be(Ce,`Found ${a.length} candidates from merged-PR repos`),{candidates:a,error:c?"All merged-PR repo fetches failed":d,rateLimitHit:u}}async function G4(e,t,r,n,s,o,i,a,c,u,d,p){Be(Ce,`Orgs phase: searching ${r.length} preferred org(s)...`);let m=r.slice(0,gg);r.length>gg&&z(Ce,`Orgs phase: capping query at ${gg} org(s); dropping ${r.slice(gg).join(", ")}`);let f=m.map(g=>`org:${g}`).join(" ");try{let g=await Gk(e,n,s,o,h=>`is:issue is:open ${h} no:assignee ${f}`.replace(/ +/g," ").trim(),i*3,p,0,m.length),{candidates:y,allVetFailed:b,rateLimitHit:R}=await wl(t,g,d,[c,u],i,a,"Orgs phase");return Be(Ce,`Found ${y.length} candidates from preferred orgs`),{candidates:y,error:b?"all vetting failed":null,rateLimitHit:R}}catch(g){if($e(g)===401)throw g;let y=K(g);return z(Ce,`Error in preferred-orgs search: ${y}`),{candidates:[],error:y,rateLimitHit:Je(g)}}}async function U4(e,t,r,n,s,o){Be(Ce,`Phase 1: Searching issues in ${r.length} starred repos...`);let i=n.slice(0,3),a=r.slice(0,KD),{candidates:c,allReposFailed:u,rateLimitHit:d}=await UD(e,t,a,i,s,"starred",o);return Be(Ce,`Found ${c.length} candidates from starred repos`),{candidates:c,error:u?"All starred repo fetches failed":null,rateLimitHit:d}}async function j4(e,t,r,n,s,o,i,a,c,u,d,p,m,f,g=0){Be(Ce,"Phase 2: General issue search...");let y=new Set(p.map(P=>P.issue.repo)),b=[];if(r&&r.length>1){for(let E of r){let T=ml[E]??[];if(T.length===0){z(Ce,`Scope "${E}" has no labels, skipping tier`);continue}b.push({tier:E,tierLabels:T})}let P=new Set(r.flatMap(E=>ml[E]??[])),C=s.filter(E=>!P.has(E));C.length>0&&b.push({tier:"custom",tierLabels:C})}else b.push({tier:"general",tierLabels:n});let R=Math.ceil(a/b.length),h=[],_=null,S=!1;for(let{tier:P,tierLabels:C}of b)try{let E=await Gk(e,o,i,C,Y=>`is:issue is:open ${Y} no:assignee`.replace(/ +/g," ").trim(),R*3,f,g);Be(Ce,`Phase 2 [${P}]: processing ${E.length} items...`);let{candidates:T,allVetFailed:L,rateLimitHit:G}=await wl(t,E,m,[u,d,y],R,c,`Phase 2 [${P}]`);h.push(T);for(let Y of T)y.add(Y.issue.repo);L&&(_=(_?_+"; ":"")+`${P}: all vetting failed`),G&&(S=!0),Be(Ce,`Found ${T.length} candidates from ${P} tier`)}catch(E){if($e(E)===401)throw E;let T=K(E);_=(_?_+"; ":"")+`${P}: ${T}`,Je(E)&&(S=!0),z(Ce,`Error in ${P} tier search: ${T}`),h.push([])}let w=FD(h);return w.length===0&&_&&z(Ce,`All ${b.length} scope tiers failed in Phase 2: ${_}`),{candidates:w.slice(0,a),error:_,rateLimitHit:S}}async function z4(e,t,r,n,s,o,i,a,c,u,d,p,m=0){Be(Ce,"Phase 3: Searching actively maintained repos...");let f=new Set(u.map(S=>S.issue.repo)),g=JD(c,F4,m).filter(S=>!i.has(S)&&!f.has(S));if(g.length>0){Be(Ce,`Phase 3: Checking ${g.length} starred repos via REST API...`);let S=await GD(e,g,n,o);if(S.length>0)try{let{candidates:w,allVetFailed:P,rateLimitHit:C}=await wl(t,S,d,[i,f],o,n,"Phase 3 (REST)");if(w.length>0)return Be(Ce,`Found ${w.length} candidates from maintained-repo REST search`),{candidates:w,error:P?"all vetting failed":null,rateLimitHit:C}}catch(w){if($e(w)===401)throw w;z(Ce,"Phase 3 REST vetting failed, falling back to Search API:",K(w))}}Be(Ce,"Phase 3: Falling back to Search API...");let y=new Date;y.setDate(y.getDate()-30);let b=y.toISOString().split("T")[0],R=oD(s),h=R.length>0?`topic:${R[0]}`:"",_=`is:issue is:open no:assignee ${r} ${h} pushed:>=${b} archived:false`.replace(/ +/g," ").trim();try{let S=await Nk(e,{q:_,sort:"updated",order:"desc",per_page:o*3},p);Be(Ce,`Found ${S.total_count} issues in maintained-repo search, processing top ${S.items.length}...`);let{candidates:w,allVetFailed:P,rateLimitHit:C}=await wl(t,S.items,d,[i,a,f],o,n,"Phase 3");return Be(Ce,`Found ${w.length} candidates from maintained-repo search`),{candidates:w,error:P?"all vetting failed":null,rateLimitHit:C}}catch(S){if($e(S)===401)throw S;let w=K(S);return z(Ce,`Error in maintained-repo search: ${w}`),{candidates:[],error:w,rateLimitHit:Je(S)}}}var Ce,x4,Ka,D4,L4,M4,KD,F4,gg,Go,Uk=A(()=>{eg();za();At();fk();No();ct();it();Ha();ug();Sk();dg();HD();qD();Ce="issue-discovery",x4=20,Ka=10,D4=365,L4=.8,M4=200,KD=10,F4=15;gg=8;Go=class{preferences;stateReader;octokit;githubToken;vetter;budgetTracker;rateLimitWarning=null;constructor(t,r,n,s=fr()){this.preferences=r,this.stateReader=n,this.githubToken=t,this.octokit=Mn(t),this.budgetTracker=s,this.vetter=new Ps(this.octokit,this.stateReader,this.budgetTracker)}getStarredRepos(){return this.stateReader.getStarredRepos()}async searchIssues(t={}){let r=this.preferences,n=t.languages||r.languages,s=r.scope,o=t.labels||(s?MD(s,r.labels):r.labels),i=t.maxResults||10,a=r.minStars??50,c=t.interPhaseDelayMs??r.interPhaseDelayMs??0,u=Fo,p=((...Z)=>Z.find(Ne=>Ne&&Ne.length>0)??["all"])(t.strategies,r.defaultStrategy),m=new Set(p.includes("all")?u:p),f=[],g=[],y={},b=!1,R=async()=>{c>0&&(Be(Ce,`Waiting ${(c/1e3).toFixed(0)}s between phases for rate limit management...`),await Wt(c))},h=(Z,Ne)=>{g.push(...Ne.candidates),y[Z]=Ne.error,Ne.rateLimitHit&&(b=!0)},_=()=>g.filter(Z=>Z.recommendation!=="skip").length;this.rateLimitWarning=null,LD();let S=this.budgetTracker,w=Ka-1,P=!1;try{let Z=await Xf(this.githubToken);if(w=Z.remaining,S.init(Z.remaining,Z.resetAt),Z.remaining<5){let Ne=new Date(Z.resetAt).toLocaleTimeString("en-US",{hour12:!1});this.rateLimitWarning=`GitHub search API quota low (${Z.remaining}/${Z.limit} remaining, resets at ${Ne}). Search may be slow.`,z(Ce,this.rateLimitWarning)}w<Ka?Be(Ce,`Search budget critical (${w} remaining) \u2014 skipping the starred phase; broad/maintained still run on GraphQL (points bucket)`):w<x4&&Be(Ce,`Search budget low (${w} remaining) \u2014 broad/maintained run on GraphQL (points bucket), unaffected by REST search quota`)}catch(Z){if($e(Z)===401)throw Z;P=!0,S.init(Ka,new Date(Date.now()+6e4).toISOString()),z(Ce,"Could not check rate limit \u2014 using conservative budget, skipping the starred phase:",K(Z))}w<=0&&(this.rateLimitWarning="GitHub search API quota exhausted \u2014 skipping the starred phase; other phases don't use it.",z(Ce,this.rateLimitWarning));let C=this.stateReader.getReposWithMergedPRs(),E=this.stateReader.getReposWithOpenPRs(),T=this.getStarredRepos(),L=new Set(T),G=new Set(this.deriveLowScoringRepos(r.minRepoScoreThreshold).map(Z=>Z.toLowerCase())),Y=n.some(Z=>Z.toLowerCase()==="any"),Se=Y?"":n.map(Z=>`language:${Z}`).join(" "),me=new Set(r.aiPolicyBlocklist.map(Z=>Z.toLowerCase()));me.size>0&&se(Ce,`[AI_POLICY_FILTER] Filtering issues from ${me.size} blocklisted repo(s): ${[...me].join(", ")}`);let pe={excludedRepos:new Set(r.excludeRepos.map(Z=>Z.toLowerCase())),excludeOrgs:new Set((r.excludeOrgs??[]).map(Z=>Z.toLowerCase())),aiBlocklisted:me,lowScoringRepos:G,skippedUrls:t.skippedUrls??new Set,now:new Date,includeDocIssues:r.includeDocIssues??!0,complexRepos:new Set(r.complexIssues==="warm"?C.map(Z=>Z.toLowerCase()):[])},X=ZD({...pe,maxAgeDays:r.maxIssueAgeDays||90}),he=ZD({...pe,maxAgeDays:D4}),tt=t.repoRotationOffsets??{},Pe=m.has("merged")?[...new Set([...C,...E])].slice(0,M4):[],dt=new Set(Pe),We=r.preferredOrgs??[],ht=JD(T.filter(Z=>!dt.has(Z)),KD,tt.starred??0),Rt={all:!1,merged:Pe.length>0,orgs:We.length>0,starred:ht.length>0&&w>=Ka,broad:!0,maintained:!0},Xe=t.broadPhaseDelayMs??r.broadPhaseDelayMs??0,Ve={merged:async Z=>{h("0",await N4(this.octokit,this.vetter,Pe,Z,he,Ne=>this.stateReader.getRepoScore(Ne),a)),f.push("merged")},orgs:async Z=>{h("orgs",await G4(this.octokit,this.vetter,We,n,Y,o,Z,a,dt,L,X,S)),f.push("orgs")},starred:async Z=>{h("1",await U4(this.octokit,this.vetter,ht,o,Z,X)),f.push("starred")},broad:async Z=>{h("2",await j4(this.octokit,this.vetter,s,o,r.labels,n,Y,Z,a,dt,L,g,X,S,t.languageRotationOffset??0)),f.push("broad")},maintained:async Z=>{h("3",await z4(this.octokit,this.vetter,Se,a,r.projectCategories??[],Z,dt,L,T,g,X,S,tt.maintained??0)),f.push("maintained")}},Ar=w<Ka;if(t.strategyRotationOffset!==void 0){let Z=t.strategyRotationOffset,Ne=Fo.length,br=Fo.map((rt,Vt)=>Fo[(Z+Vt)%Ne]).filter(rt=>m.has(rt));Ar=!1;for(let rt of br){if(!Rt[rt]){rt==="starred"&&ht.length>0&&(Ar=!0);continue}if(f.length>0&&await R(),Be(Ce,`Round-robin: running the ${rt} strategy`),await Ve[rt](i-_()),_()>0)break}}else{let Z=Rt.orgs&&m.has("orgs"),Ne=Z||Rt.starred&&m.has("starred")||m.has("broad")||m.has("maintained");if(Rt.merged&&m.has("merged")){let Rr=Ne?Math.max(1,Math.min(Math.ceil(i*L4),i-1)):i;await Ve.merged(Math.min(i-g.length,Rr))}g.length<i&&Z&&(await R(),await Ve.orgs(i-g.length)),g.length<i&&T.length>0&&w>=Ka&&m.has("starred")&&(await R(),ht.length>0&&await Ve.starred(i-g.length));let br=r.skipBroadWhenSufficientResults??8,rt=br>0?Math.min(br,i-1):0,Vt=_();if(Vt>=i&&m.has("broad"))Be(Ce,`Skipping broad search: ${Vt} viable candidate(s) already meet maxResults (${i})`);else if(m.has("broad")){let Rr=new Set(We.map(Tr=>Tr.toLowerCase())),Is=g.filter(Tr=>Tr.recommendation!=="skip"&&!dt.has(Tr.issue.repo)&&!L.has(Tr.issue.repo)&&!Rr.has(Tr.issue.repo.split("/")[0]?.toLowerCase()??"")).length;rt>0&&Is>=rt?Be(Ce,`Skipping broad search: already found ${Is} viable candidate(s) from new repos (threshold: ${rt})`):(await R(),g.length>0&&Xe>0?(Be(Ce,`Waiting ${(Xe/1e3).toFixed(0)}s for rate limit cooldown before broad search...`),await Wt(Xe)):g.length===0&&Be(Ce,"Skipping broad phase delay: no results from previous phases, proceeding immediately"),await Ve.broad(i-Vt))}let wr=_();wr>=i&&m.has("maintained")?Be(Ce,`Skipping maintained search: ${wr} viable candidate(s) already meet maxResults (${i})`):m.has("maintained")&&(await R(),await Ve.maintained(i-wr))}let Un=Ar,mn=Un?P?" The starred-repo phase was skipped as a precaution because the rate-limit check failed (quota unknown); the other strategies don't use that quota.":` The starred-repo phase was skipped due to critically low API quota (${w} remaining); the other strategies don't use that quota.`:"";if(g.length===0){let Z=[y[0]?`Phase 0 (merged-PR repos): ${y[0]}`:null,y.orgs?`Orgs phase (preferred orgs): ${y.orgs}`:null,y[1]?`Phase 1 (starred repos): ${y[1]}`:null,y[2]?`Phase 2 (general): ${y[2]}`:null,y[3]?`Phase 3 (maintained repos): ${y[3]}`:null].filter(Boolean),Ne=Z.length>0?` ${Z.join(". ")}.`:"";if(b||Un)return this.rateLimitWarning=`Search returned no results due to GitHub API rate limits.${Ne}${mn} Try again after the rate limit resets.`,{candidates:[],strategiesUsed:f};throw new at(`No issue candidates found across all search phases.${Ne} Try adjusting your search criteria (languages, labels) or check your network connection.`,f)}(b||Un)&&(this.rateLimitWarning=`Search results may be incomplete: GitHub API rate limits were hit during search.${mn} Found ${g.length} candidate${g.length===1?"":"s"} but some search phases were limited. Try again after the rate limit resets for complete results.`);let jr=WD(g,{preferLanguages:t.preferLanguages,preferRepos:t.preferRepos,avoidRepos:t.avoidRepos,boostIssueTypes:t.boostIssueTypes});jr.sort((Z,Ne)=>{let br={merged_pr:0,starred:1,normal:2},rt=br[Z.searchPriority]-br[Ne.searchPriority];if(rt!==0)return rt;let Vt={approve:0,needs_review:1,skip:2},wr=Vt[Z.recommendation]-Vt[Ne.recommendation];if(wr!==0)return wr;let Rr=fg(Ne)-fg(Z);return Rr!==0?Rr:Ne.viabilityScore-Z.viabilityScore});let jn=[...jr.filter(Z=>Z.recommendation!=="skip"),...jr.filter(Z=>Z.recommendation==="skip")],Qo=yl(jn,2),Os=VD(Qo,i,t.diversityRatio??0);return Be(Ce,`Search complete: ${S.getTotalCalls()} REST Search API call(s) + ${DD()} GraphQL broad-search query/queries used, ${Os.length} candidates returned`),{candidates:Os,strategiesUsed:f}}async vetIssue(t){return this.vetter.vetIssue(t)}deriveLowScoringRepos(t){let r=[],n=new Set([...this.stateReader.getReposWithMergedPRs(),...this.stateReader.getStarredRepos()]);for(let s of n){let o=this.stateReader.getRepoScore(s);o!==null&&o<=t&&r.push(s)}return r}}});function YD(){let e=Date.now()-QD;for(let[t,r]of Rl.entries())r.fetchedAt<e&&Rl.delete(t)}function zk(e,t,r){let n=new Set,s=`${t}/${r}`.toLowerCase(),o=d=>d.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),i=new RegExp(`\\b${o(t)}/${o(r)}#(\\d+)\\b`,"gi");for(let d of e.matchAll(i)){let p=Number.parseInt(d[1],10);p>0&&n.add(p)}let a=/\b[\w.-]+\/[\w.-]+#\d+\b/gi,c=!1;for(let d of e.split(`
344
- `)){if(/^\s*(```|~~~)/.test(d)){c=!c;continue}if(c||/^\s*#+\s/.test(d))continue;let p=d.replace(a,"").replace(/`[^`]*`/g,"");for(let m of p.matchAll(/(?:^|[^&\w])#(\d+)\b/g)){let f=Number.parseInt(m[1],10);f>0&&n.add(f)}}let u=/https?:\/\/github\.com\/([\w.-]+\/[\w.-]+)\/issues\/(\d+)/gi;for(let d of e.matchAll(u))if(d[1].toLowerCase()===s){let p=Number.parseInt(d[2],10);p>0&&n.add(p)}return n}async function hg(e,t,r){let n=`${t}/${r}`.toLowerCase(),s=Rl.get(n);if(s&&Date.now()-s.fetchedAt<QD)return s.refs;let o=jk.get(n);if(o)return o;let i=H4(e,t,r,n);jk.set(n,i);try{return await i}finally{jk.delete(n)}}async function H4(e,t,r,n){for(let o of B4){let{text:i}=await Va(e,t,r,o);if(!i)continue;let a=zk(i,t,r);return Rl.set(n,{refs:a,fetchedAt:Date.now()}),YD(),a}let s=new Set;return Rl.set(n,{refs:s,fetchedAt:Date.now()}),YD(),s}var QD,B4,Rl,jk,Bk=A(()=>{ag();QD=3600*1e3,B4=["ROADMAP.md","docs/ROADMAP.md",".github/ROADMAP.md","Roadmap.md","roadmap.md"],Rl=new Map;jk=new Map});function Vk(e,t=Wk){return Object.values(e).filter(r=>r.mergedPRCount>=t).sort((r,n)=>n.mergedPRCount-r.mergedPRCount).map(r=>r.repo)}function qk(e){if(e.hasMilestone||e.isOnRoadmap)return"bigger-bet";for(let t of e.labels)if(q4.has(t.toLowerCase()))return"bigger-bet";return"quick-win"}function yg(e,t,r=V4){let n=e.filter(g=>g.horizon==="quick-win").sort((g,y)=>y.viabilityScore-g.viabilityScore),s=e.filter(g=>g.horizon==="bigger-bet").sort((g,y)=>y.viabilityScore-g.viabilityScore),o=Math.max(0,Math.min(1,r)),i=Math.round(t*o),a=t-i,c=Math.min(n.length,i),u=Math.min(s.length,a),d=c,p=u,m=i-c,f=a-u;return m>0&&(p=Math.min(s.length,p+m)),f>0&&(d=Math.min(n.length,d+f)),{quickWins:n.slice(0,d),biggerBets:s.slice(0,p)}}function J4(e){if(!e.labels.some(o=>Z4.has(o.toLowerCase())))return!1;let r=new Date(e.createdAt);return Number.isNaN(r.getTime())?!1:((e.now??new Date).getTime()-r.getTime())/(1e3*60*60*24)>=(e.minAgeDays??K4)}function nL(e){let t=new Set([...e.excludeRepos??[],...e.aiPolicyBlocklist??[]].map(n=>n.toLowerCase())),r=new Set((e.excludeOrgs??[]).map(n=>n.toLowerCase()));return n=>{let s=n.toLowerCase();if(t.has(s))return!1;let o=s.split("/")[0];return!(o&&r.has(o))}}function sL(e){return Array.isArray(e.labels)?e.labels.map(t=>typeof t=="string"?t:t?.name).filter(t=>typeof t=="string"):[]}function oL(e){let t=sL(e).map(r=>r.toLowerCase());return t.length===0||t.some(r=>rL.has(r))?!1:t.some(r=>bg.includes(r))}async function iL(e,t,r){let n=sL(e),s=!!e.milestone,o=e.reactions?.total_count??0,i=e.comments??0,a=e.created_at?J4({labels:n,createdAt:e.created_at}):!1,c=r!==void 0,u=c&&typeof e.number=="number"&&r.has(e.number),d;try{d=await t.vetIssue(e.html_url,{featureSignals:{reactions:o,comments:i,hasMilestone:s,wontfixNoContributor:a,...c?{onRoadmap:u}:{}}})}catch(m){return He(m),z(Hk,`vet failed for ${e.html_url}: ${K(m)}`),null}let p=qk({hasMilestone:s,labels:n,...c?{isOnRoadmap:u}:{}});return{...d,horizon:p}}async function wg(e){let t=nL(e),r=Vk(e.repoScores,e.anchorThreshold).filter(t);if(r.length===0)return{quickWins:[],biggerBets:[],anchorRepos:[],message:Zk};let n=[];for(let a=0;a<r.length;a++){a>0&&await Wt(W4);let[c,u]=r[a].split("/"),d,p;try{let[f,g]=await Promise.all([e.octokit.issues.listForRepo({owner:c,repo:u,state:"open",sort:"updated",direction:"desc",per_page:20}),hg(e.octokit,c,u)]);d=f,p=g}catch(f){He(f),z(Hk,`failed to list issues for ${r[a]}: ${K(f)}`);continue}let m=d.data.filter(f=>!f.pull_request&&!f.assignee&&oL(f));for(let f of m){let g=await iL(f,e.vetter,p);g&&n.push(g)}}let s=n.filter(a=>a.viabilityScore>=tL),o=yg(s,e.count,e.splitRatio),i=o.quickWins.length+o.biggerBets.length;return{...o,anchorRepos:r,message:i===0?Kk:null}}function eL(e){let t=["is:issue","is:open","no:assignee"],r=`label:${bg.map(n=>JSON.stringify(n)).join(",")}`;t.push(r);for(let n of rL)t.push(`-label:"${n}"`);e.language&&t.push(`language:${e.language}`);for(let n of e.excludeRepos??[])t.push(`-repo:${n}`);for(let n of e.excludeOrgs??[])t.push(`-user:${n}`);return t.join(" ")}function Q4(e){let t={excludeRepos:e.excludeRepos,excludeOrgs:e.excludeOrgs},r=(e.languages??[]).filter(n=>n&&n.toLowerCase()!=="any");return r.length===0?[eL(t)]:r.map(n=>eL({...t,language:n}))}async function aL(e){let t=Q4({languages:e.languages,excludeRepos:e.excludeRepos,excludeOrgs:e.excludeOrgs}),r=e.maxToVet??Y4,n;try{let c=[],u=new Set;for(let p of t){let m=await Fk(e.octokit,{q:p,sort:"interactions",order:"desc",per_page:r});for(let f of m.items)u.has(f.html_url)||(u.add(f.html_url),c.push(f))}let d=nL(e);n=c.filter(p=>!p.pull_request&&!p.assignee&&oL(p)).filter(p=>{let m=ut(p.html_url);return m===null||d(m)}).slice(0,r)}catch(c){return He(c),z(Hk,`broad feature search failed: ${K(c)}`),{quickWins:[],biggerBets:[],anchorRepos:[],message:XD}}let s=[];for(let c of n){let u=await iL(c,e.vetter);u&&s.push(u)}let o=s.filter(c=>c.viabilityScore>=tL),i=yg(o,e.count,e.splitRatio),a=i.quickWins.length+i.biggerBets.length;return{...i,anchorRepos:[],message:a===0?XD:null}}var Hk,W4,tL,Wk,V4,q4,bg,rL,Z4,K4,Zk,Kk,XD,Y4,Jk=A(()=>{ct();it();At();Bk();dg();Hk="feature-discovery",W4=2e3,tL=40,Wk=3,V4=.6;q4=new Set(["roadmap","accepted-rfc","proposal"]);bg=["enhancement","feature","feature-request","proposal","roadmap","accepted-rfc"],rL=new Set(["good first issue","bug","documentation"]),Z4=new Set(["help wanted","contributions welcome","up-for-grabs","bounty","pinned","unmaintained"]),K4=60;Zk="No anchor repos yet (need 3+ merged PRs in a repo). Try `scout search` to build relationships first.",Kk="No open feature opportunities in your anchor repos right now. Check back next week, or try `scout search` for fix-mode work.";XD="No open feature opportunities matched your filters. Try widening your language preferences in `scout config`.",Y4=30});function uL(){return cL.join(Cs(),"state.json")}function Sg(){let e=uL();try{let t=Ur.readFileSync(e,"utf-8");return hl(JSON.parse(t))}catch(t){if(t?.code==="ENOENT")return Fn.parse({version:1});z(Rg,`Failed to load state from ${e}: ${K(t)}. Using defaults.`);try{let n=`${e}.corrupt.${Date.now()}`;Ur.copyFileSync(e,n),z(Rg,`Corrupt state backed up to ${n}`)}catch(n){z(Rg,`Failed to back up corrupt state: ${K(n)}`)}return Fn.parse({version:1})}}function lL(e){_g(uL(),JSON.stringify(e,null,2)+`
344
+ `)){if(/^\s*(```|~~~)/.test(d)){c=!c;continue}if(c||/^\s*#+\s/.test(d))continue;let p=d.replace(a,"").replace(/`[^`]*`/g,"");for(let m of p.matchAll(/(?:^|[^&\w])#(\d+)\b/g)){let f=Number.parseInt(m[1],10);f>0&&n.add(f)}}let u=/https?:\/\/github\.com\/([\w.-]+\/[\w.-]+)\/issues\/(\d+)/gi;for(let d of e.matchAll(u))if(d[1].toLowerCase()===s){let p=Number.parseInt(d[2],10);p>0&&n.add(p)}return n}async function hg(e,t,r){let n=`${t}/${r}`.toLowerCase(),s=Rl.get(n);if(s&&Date.now()-s.fetchedAt<QD)return s.refs;let o=jk.get(n);if(o)return o;let i=H4(e,t,r,n);jk.set(n,i);try{return await i}finally{jk.delete(n)}}async function H4(e,t,r,n){for(let o of B4){let{text:i}=await Va(e,t,r,o);if(!i)continue;let a=zk(i,t,r);return Rl.set(n,{refs:a,fetchedAt:Date.now()}),YD(),a}let s=new Set;return Rl.set(n,{refs:s,fetchedAt:Date.now()}),YD(),s}var QD,B4,Rl,jk,Bk=A(()=>{ag();QD=3600*1e3,B4=["ROADMAP.md","docs/ROADMAP.md",".github/ROADMAP.md","Roadmap.md","roadmap.md"],Rl=new Map;jk=new Map});function Vk(e,t=Wk){return Object.values(e).filter(r=>r.mergedPRCount>=t).sort((r,n)=>n.mergedPRCount-r.mergedPRCount).map(r=>r.repo)}function qk(e){if(e.hasMilestone||e.isOnRoadmap)return"bigger-bet";for(let t of e.labels)if(q4.has(t.toLowerCase()))return"bigger-bet";return"quick-win"}function yg(e,t,r=V4){let n=e.filter(g=>g.horizon==="quick-win").sort((g,y)=>y.viabilityScore-g.viabilityScore),s=e.filter(g=>g.horizon==="bigger-bet").sort((g,y)=>y.viabilityScore-g.viabilityScore),o=Math.max(0,Math.min(1,r)),i=Math.round(t*o),a=t-i,c=Math.min(n.length,i),u=Math.min(s.length,a),d=c,p=u,m=i-c,f=a-u;return m>0&&(p=Math.min(s.length,p+m)),f>0&&(d=Math.min(n.length,d+f)),{quickWins:n.slice(0,d),biggerBets:s.slice(0,p)}}function J4(e){if(!e.labels.some(o=>Z4.has(o.toLowerCase())))return!1;let r=new Date(e.createdAt);return Number.isNaN(r.getTime())?!1:((e.now??new Date).getTime()-r.getTime())/(1e3*60*60*24)>=(e.minAgeDays??K4)}function nL(e){let t=new Set([...e.excludeRepos??[],...e.aiPolicyBlocklist??[]].map(n=>n.toLowerCase())),r=new Set((e.excludeOrgs??[]).map(n=>n.toLowerCase()));return n=>{let s=n.toLowerCase();if(t.has(s))return!1;let o=s.split("/")[0];return!(o&&r.has(o))}}function sL(e){return Array.isArray(e.labels)?e.labels.map(t=>typeof t=="string"?t:t?.name).filter(t=>typeof t=="string"):[]}function oL(e){let t=sL(e).map(r=>r.toLowerCase());return t.length===0||t.some(r=>rL.has(r))?!1:t.some(r=>bg.includes(r))}async function iL(e,t,r,n){let s=sL(e),o=!!e.milestone,i=e.reactions?.total_count??0,a=e.comments??0,c=e.created_at?J4({labels:s,createdAt:e.created_at}):!1,u=n!==void 0,d=u&&typeof e.number=="number"&&n.has(e.number),p;try{p=await t.vetIssue(e.html_url,{featureSignals:{reactions:i,comments:a,hasMilestone:o,wontfixNoContributor:c,...u?{onRoadmap:d}:{}}})}catch(f){return He(f),z(Hk,`vet failed for ${e.html_url}: ${K(f)}`),null}if(!p.projectHealth.checkFailed&&(p.projectHealth.stargazersCount??0)<r)return null;let m=qk({hasMilestone:o,labels:s,...u?{isOnRoadmap:d}:{}});return{...p,horizon:m}}async function wg(e){let t=nL(e),r=Vk(e.repoScores,e.anchorThreshold).filter(t);if(r.length===0)return{quickWins:[],biggerBets:[],anchorRepos:[],message:Zk};let n=[];for(let a=0;a<r.length;a++){a>0&&await Wt(W4);let[c,u]=r[a].split("/"),d,p;try{let[f,g]=await Promise.all([e.octokit.issues.listForRepo({owner:c,repo:u,state:"open",sort:"updated",direction:"desc",per_page:20}),hg(e.octokit,c,u)]);d=f,p=g}catch(f){He(f),z(Hk,`failed to list issues for ${r[a]}: ${K(f)}`);continue}let m=d.data.filter(f=>!f.pull_request&&!f.assignee&&oL(f));for(let f of m){let g=await iL(f,e.vetter,e.minStars??0,p);g&&n.push(g)}}let s=n.filter(a=>a.viabilityScore>=tL),o=yg(s,e.count,e.splitRatio),i=o.quickWins.length+o.biggerBets.length;return{...o,anchorRepos:r,message:i===0?Kk:null}}function eL(e){let t=["is:issue","is:open","no:assignee"],r=`label:${bg.map(n=>JSON.stringify(n)).join(",")}`;t.push(r);for(let n of rL)t.push(`-label:"${n}"`);e.language&&t.push(`language:${e.language}`);for(let n of e.excludeRepos??[])t.push(`-repo:${n}`);for(let n of e.excludeOrgs??[])t.push(`-user:${n}`);return t.join(" ")}function Q4(e){let t={excludeRepos:e.excludeRepos,excludeOrgs:e.excludeOrgs},r=(e.languages??[]).filter(n=>n&&n.toLowerCase()!=="any");return r.length===0?[eL(t)]:r.map(n=>eL({...t,language:n}))}async function aL(e){let t=Q4({languages:e.languages,excludeRepos:e.excludeRepos,excludeOrgs:e.excludeOrgs}),r=e.maxToVet??Y4,n;try{let c=[],u=new Set;for(let p of t){let m=await Fk(e.octokit,{q:p,sort:"interactions",order:"desc",per_page:r});for(let f of m.items)u.has(f.html_url)||(u.add(f.html_url),c.push(f))}let d=nL(e);n=c.filter(p=>!p.pull_request&&!p.assignee&&oL(p)).filter(p=>{let m=ut(p.html_url);return m===null||d(m)}).slice(0,r)}catch(c){return He(c),z(Hk,`broad feature search failed: ${K(c)}`),{quickWins:[],biggerBets:[],anchorRepos:[],message:XD}}let s=[];for(let c of n){let u=await iL(c,e.vetter,e.minStars??0);u&&s.push(u)}let o=s.filter(c=>c.viabilityScore>=tL),i=yg(o,e.count,e.splitRatio),a=i.quickWins.length+i.biggerBets.length;return{...i,anchorRepos:[],message:a===0?XD:null}}var Hk,W4,tL,Wk,V4,q4,bg,rL,Z4,K4,Zk,Kk,XD,Y4,Jk=A(()=>{ct();it();At();Bk();dg();Hk="feature-discovery",W4=2e3,tL=40,Wk=3,V4=.6;q4=new Set(["roadmap","accepted-rfc","proposal"]);bg=["enhancement","feature","feature-request","proposal","roadmap","accepted-rfc"],rL=new Set(["good first issue","bug","documentation"]),Z4=new Set(["help wanted","contributions welcome","up-for-grabs","bounty","pinned","unmaintained"]),K4=60;Zk="No anchor repos yet (need 3+ merged PRs in a repo). Try `scout search` to build relationships first.",Kk="No open feature opportunities in your anchor repos right now. Check back next week, or try `scout search` for fix-mode work.";XD="No open feature opportunities matched your filters. Try widening your language preferences in `scout config`.",Y4=30});function uL(){return cL.join(Cs(),"state.json")}function Sg(){let e=uL();try{let t=Ur.readFileSync(e,"utf-8");return hl(JSON.parse(t))}catch(t){if(t?.code==="ENOENT")return Fn.parse({version:1});z(Rg,`Failed to load state from ${e}: ${K(t)}. Using defaults.`);try{let n=`${e}.corrupt.${Date.now()}`;Ur.copyFileSync(e,n),z(Rg,`Corrupt state backed up to ${n}`)}catch(n){z(Rg,`Failed to back up corrupt state: ${K(n)}`)}return Fn.parse({version:1})}}function lL(e){_g(uL(),JSON.stringify(e,null,2)+`
345
345
  `),se(Rg,"State saved")}function _g(e,t){let r=`${e}.tmp.${process.pid}.${X4++}`;Ur.writeFileSync(r,t,{mode:384});try{Ur.renameSync(r,e)}catch(n){try{Ur.unlinkSync(r)}catch{}throw n}}var Ur,cL,Rg,X4,Yk=A(()=>{Ur=B(require("fs"),1),cL=B(require("path"),1);No();At();it();ct();Rg="local-state";X4=0});function rK(e){if(Je(e))return"rate_limit";let t=$e(e);if(t!==void 0&&t>=500&&t<600)return"server";if(e&&typeof e=="object"&&"code"in e){let r=e.code;if(r==="ECONNREFUSED"||r==="ENOTFOUND"||r==="ETIMEDOUT"||r==="ECONNRESET"||r==="EAI_AGAIN")return"network"}return e instanceof Error&&e.message.toLowerCase().includes("fetch failed")?"network":"unknown"}function mL(){return tC.join(Cs(),eK)}function fL(){return tC.join(Cs(),tK)}function sK(e,t){let r=Date.now()-nK,n=new Map;for(let s of[...e,...t]){let o=n.get(s.url);(!o||s.removedAt>o.removedAt)&&n.set(s.url,s)}return[...n.values()].filter(s=>{let o=new Date(s.removedAt).getTime();return Number.isFinite(o)&&o>=r})}function gL(e,t,r,n){if(t.length===0)return e;let s=new Map(t.map(o=>[o.url,o.removedAt]));return e.filter(o=>{let i=s.get(r(o));return i===void 0?!0:n(o)>i})}function Sl(e,t){let r=sK(e.tombstones??[],t.tombstones??[]),n=gL(cK(e.savedResults??[],t.savedResults??[]),r,b=>b.issueUrl,b=>b.lastSeenAt),s=gL(uK(e.skippedIssues??[],t.skippedIssues??[]),r,b=>b.url,b=>b.skippedAt),o=new Set(s.map(b=>b.url)),i=n.filter(b=>!o.has(b.issueUrl)),a=e.preferencesUpdatedAt,c=t.preferencesUpdatedAt,d=a!==void 0&&(c===void 0||a>c)?e.preferences:t.preferences,p=vg(a,c),m=Xk(e.mergedPRs,t.mergedPRs),f=Xk(e.closedPRs,t.closedPRs),g=new Set([...m.map(b=>b.url),...f.map(b=>b.url)]),y=Xk(e.openPRs??[],t.openPRs??[]).filter(b=>!g.has(b.url));return{...e,...t,version:1,stateRevision:Math.max(e.stateRevision,t.stateRevision),preferences:d,preferencesUpdatedAt:p,tombstones:r,repoScores:iK(e.repoScores,t.repoScores),starredRepos:aK(e,t),starredReposLastFetched:vg(e.starredReposLastFetched,t.starredReposLastFetched),mergedPRs:m,closedPRs:f,openPRs:y,savedResults:i,skippedIssues:s,lastSearchAt:vg(e.lastSearchAt,t.lastSearchAt),lastRunAt:vg(e.lastRunAt,t.lastRunAt)??new Date().toISOString(),gistId:t.gistId??e.gistId,searchRotation:oK(e.searchRotation,t.searchRotation)}}function oK(e,t){let r=e??{languageOffset:0},n=t??{languageOffset:0},s=r.lastRotatedAt,o=n.lastRotatedAt;return s&&o?s>=o?r:n:s?r:o||n.languageOffset>=r.languageOffset?n:r}function iK(e,t){let r=Object.assign(Object.create(null),e);for(let[n,s]of Object.entries(t)){let o=r[n];if(!o)r[n]=s;else{let i=o.mergedPRCount+o.closedWithoutMergeCount,a=s.mergedPRCount+s.closedWithoutMergeCount;r[n]=a>=i?s:o}}return r}function aK(e,t){let r=e.starredReposLastFetched,n=t.starredReposLastFetched;return!r&&!n?t.starredRepos.length>=e.starredRepos.length?t.starredRepos:e.starredRepos:r?n&&n>=r?t.starredRepos:e.starredRepos:t.starredRepos}function Xk(e,t){let r=new Map;for(let n of e)r.set(n.url,n);for(let n of t)r.set(n.url,n);return[...r.values()]}function cK(e,t){let r=new Map;for(let n of e)r.set(n.issueUrl,n);for(let n of t){let s=r.get(n.issueUrl);(!s||n.lastSeenAt>s.lastSeenAt)&&r.set(n.issueUrl,n)}return[...r.values()]}function uK(e,t){let r=new Map;for(let n of e)r.set(n.url,n);for(let n of t){let s=r.get(n.url);(!s||n.skippedAt>s.skippedAt)&&r.set(n.url,n)}return[...r.values()]}function vg(e,t){return e?t?e>=t?e:t:e:t}var eC,tC,lt,dL,Qk,eK,tK,pL,kg,nK,hL=A(()=>{eC=B(require("fs"),1),tC=B(require("path"),1);No();At();Yk();it();ct();lt="gist-state",dL="oss-scout-state",Qk="state.json",eK="gist-id",tK="state-cache.json",pL=10;kg=class{octokit;gistId=null;constructor(t){this.octokit=t}async bootstrap(){try{return await this.bootstrapFromApi()}catch(t){if($e(t)===401)throw t;return z(lt,`API bootstrap failed: ${K(t)}`),this.bootstrapFromCache(rK(t))}}async push(t){if(!this.gistId)return z(lt,"No gist ID \u2014 cannot push"),this.writeCache(t),!1;let r=t;try{let s=await this.fetchGistState(this.gistId);if(s.kind==="ok")r=Sl(t,s.state);else if(s.kind==="invalid")return this.writeCache(t),z(lt,"Remote gist content failed validation \u2014 not overwriting it. Changes saved locally; gist sync skipped."),!1}catch(s){He(s),z(lt,`Could not fetch gist before push, writing local snapshot: ${K(s)}`)}this.writeCache(r);let n=JSON.stringify(r,null,2);if(n.length>9e5)return z(lt,`State too large for gist (${Math.round(n.length/1024)}KB). Consider clearing old results with 'oss-scout results clear'.`),!1;try{return await this.octokit.gists.update({gist_id:this.gistId,files:{[Qk]:{content:n}}}),se(lt,"State pushed to gist"),!0}catch(s){return He(s),z(lt,`Failed to push: ${K(s)}`),!1}}getGistId(){return this.gistId}async bootstrapFromApi(){let t=this.readCachedGistId();if(t){se(lt,`Trying cached gist ID: ${t}`);try{let o=await this.fetchGistState(t);if(o.kind==="ok"){this.gistId=t;let i=this.mergeCacheInto(o.state);return this.writeCache(i),{gistId:t,state:i,created:!1}}}catch(o){if($e(o)!==404)throw o;se(lt,`Cached gist gone (404): ${K(o)}`)}se(lt,"Cached gist ID invalid, searching...")}let r=await this.searchForGist();if(r.id){se(lt,`Found gist via search: ${r.id}`),this.saveGistId(r.id),this.gistId=r.id;let o=await this.fetchGistState(r.id);if(o.kind==="ok"){let i=this.mergeCacheInto(o.state);return this.writeCache(i),{gistId:r.id,state:i,created:!1}}return z(lt,`Found existing gist ${r.id} but content failed validation. Using local cache to avoid data loss.`),this.bootstrapFromCache("unknown")}r.exhaustive||z(lt,`Scanned the first ${pL*100} gists without finding an oss-scout state gist, but the account has more. Creating a new state gist; if one already exists, copy its id into the gist-id file in the oss-scout data directory to avoid a duplicate.`),se(lt,"No existing gist found, creating new one");let n=Fn.parse({version:1}),s=await this.createGist(n);return this.saveGistId(s),this.gistId=s,this.writeCache(n),{gistId:s,state:n,created:!0}}bootstrapFromCache(t){let r=this.readCache();if(r){se(lt,"Bootstrapped from local cache (degraded mode)");let s=this.readCachedGistId();return s&&(this.gistId=s),{gistId:s??"",state:r,created:!1,degraded:!0,degradedReason:t}}return se(lt,"No cache available, using fresh state (degraded mode)"),{gistId:"",state:Fn.parse({version:1}),created:!1,degraded:!0,degradedReason:t}}async fetchGistState(t){let{data:r}=await this.octokit.gists.get({gist_id:t}),n=r.files?.[Qk];if(!n?.content)return{kind:"missing"};try{let s=JSON.parse(n.content);return{kind:"ok",state:hl(s)}}catch(s){return z(lt,`Gist content failed validation: ${K(s)}`),{kind:"invalid"}}}async searchForGist(){for(let t=1;t<=pL;t++){let{data:r}=await this.octokit.gists.list({per_page:100,page:t});if(r.length===0)return{id:null,exhaustive:!0};let n=r.find(s=>s.description===dL);if(n)return{id:n.id,exhaustive:!0};if(r.length<100)return{id:null,exhaustive:!0}}return{id:null,exhaustive:!1}}async createGist(t){let{data:r}=await this.octokit.gists.create({description:dL,public:!1,files:{[Qk]:{content:JSON.stringify(t,null,2)}}});return r.id}readCachedGistId(){try{return eC.readFileSync(mL(),"utf-8").trim()||null}catch(t){return t?.code!=="ENOENT"&&z(lt,`Failed to read cached gist ID: ${K(t)}`),null}}saveGistId(t){_g(mL(),t+`
346
346
  `)}mergeCacheInto(t){let r=this.readCache();return r?Sl(r,t):t}readCache(){try{let t=eC.readFileSync(fL(),"utf-8");return hl(JSON.parse(t))}catch(t){return t?.code!=="ENOENT"&&z(lt,`Failed to read state cache: ${K(t)}`),null}}writeCache(t){try{_g(fL(),JSON.stringify(t,null,2)+`
347
- `)}catch(r){z(lt,`Failed to write cache: ${K(r)}`)}}},nK=2160*60*60*1e3});function dK(e){let t="Changes will only be saved locally.";switch(e){case"rate_limit":return`Gist sync unavailable \u2014 GitHub API rate limit exceeded. ${t} Try again after the rate limit resets.`;case"network":return`Gist sync unavailable \u2014 could not reach GitHub. ${t} Check your network connection.`;case"server":return`Gist sync unavailable \u2014 GitHub returned a server error. ${t} Try again later.`;case"unknown":case void 0:return`Gist sync unavailable \u2014 running in offline mode. ${t}`}}function pK(e){return{gists:{async get(t){let{data:r}=await e.gists.get(t);if(!r.id)throw new Error("Gist get returned no id");let n=r.files?Object.fromEntries(Object.entries(r.files).map(([s,o])=>[s,o?{content:o.content}:void 0])):null;return{data:{id:r.id,files:n}}},async create(t){let{data:r}=await e.gists.create(t);if(!r.id)throw new Error("Gist create returned no id");return{data:{id:r.id}}},async update(t){let{data:r}=await e.gists.update(t);if(!r.id)throw new Error("Gist update returned no id");return{data:{id:r.id}}},async list(t){let{data:r}=await e.gists.list(t);return{data:r.filter(n=>n.id).map(n=>({id:n.id,description:n.description??null}))}}}}}async function Cg(e){e.logLevel!==void 0&&qf(e.logLevel);let t,r=null,n=!1;if(e.persistence==="provided")t=e.initialState;else if(e.persistence==="gist"){r=new kg(pK(Mn(e.githubToken)));let s=await r.bootstrap();s.degraded&&z("scout",dK(s.degradedReason));let o=Sg();t=Sl(o,s.state),e.gistId?t.gistId=e.gistId:s.gistId&&(t.gistId=s.gistId)}else t=Sg(),n=!0;return new _l(e.githubToken,t,r,{persistLocal:n})}var lK,_l,yL=A(()=>{Uk();ug();Jk();No();hL();eg();Yk();it();At();ct();an();lK=/Linked PR already merged|Linked PR closed without merge|Has existing PR/;_l=class{githubToken;gistStore;state;dirty=!1;persistLocal;constructor(t,r,n=null,s={}){this.githubToken=t,this.gistStore=n,this.state=r,this.persistLocal=s.persistLocal??!1}evictStaleCacheEntries(){et().evictStale()}async search(t){this.evictStaleCacheEntries(),this.cullExpiredSkips();let r=new Set(this.getComplexIssuesMode()==="warm"?this.getReposWithMergedPRs().map(h=>h.toLowerCase()):[]),n=new Set((this.state.skippedIssues??[]).filter(h=>!(r.has(h.repo.toLowerCase())&&lK.test(h.reason??""))).map(h=>h.url));if(t?.excludeRecentlySurfaced??!0){let h=t?.recentlySurfacedTtlDays??7,_=Date.now()-h*24*60*60*1e3;for(let S of this.state.savedResults??[]){let w=Date.parse(S.lastSeenAt);!Number.isNaN(w)&&w>=_&&n.add(S.issueUrl)}}let s=new Go(this.githubToken,this.state.preferences,this),o=this.state.preferences,i=o.preferLanguages??[],a=o.preferRepos??[],c=t?.preferLanguages??(i.length>0?i:void 0),u=t?.preferRepos??(a.length>0?a:void 0),d=o.avoidRepos??[],p=o.boostIssueTypes??[],m=t?.avoidRepos??(d.length>0?d:void 0),f=t?.boostIssueTypes??(p.length>0?p:void 0),g=t?.diversityRatio??o.diversityRatio??0,y=this.state.searchRotation??{languageOffset:0},b,R;try{({candidates:b,strategiesUsed:R}=await s.searchIssues({maxResults:t?.maxResults,strategies:t?.strategies,skippedUrls:n,preferLanguages:c,preferRepos:u,avoidRepos:m,boostIssueTypes:f,diversityRatio:g,interPhaseDelayMs:t?.interPhaseDelayMs,broadPhaseDelayMs:t?.broadPhaseDelayMs,languageRotationOffset:y.languageOffset,repoRotationOffsets:{merged:y.phase0Offset??0,starred:y.starredOffset??0,maintained:y.maintainedOffset??0},strategyRotationOffset:t?.full?void 0:y.strategyOffset??0}))}catch(h){throw h instanceof at&&this.advanceRotation(y,h.strategiesUsed??[],t?.full),h}this.advanceRotation(y,R,t?.full);for(let h of b)this.updateRepoSignalsFromHealth(h.projectHealth);return this.state.lastSearchAt=new Date().toISOString(),this.dirty=!0,{candidates:b,excludedRepos:this.state.preferences.excludeRepos,aiPolicyBlocklist:this.state.preferences.aiPolicyBlocklist,rateLimitWarning:s.rateLimitWarning??void 0,strategiesUsed:R}}advanceRotation(t,r,n=!1){let s=o=>r.includes(o)?1:0;r.length!==0&&(this.state.searchRotation={...t,languageOffset:t.languageOffset+s("broad"),phase0Offset:(t.phase0Offset??0)+s("merged"),starredOffset:(t.starredOffset??0)+s("starred"),maintainedOffset:(t.maintainedOffset??0)+s("maintained"),strategyOffset:n?t.strategyOffset:Fo.indexOf(r[0])+1,lastRotatedAt:new Date().toISOString()},this.dirty=!0)}updateRepoSignalsFromHealth(t){t.checkFailed||this.updateRepoScore(t.repo,{signals:{hasActiveMaintainers:t.isActive}})}async vetIssue(t){return new Go(this.githubToken,this.state.preferences,this).vetIssue(t)}async features(t){this.evictStaleCacheEntries();let r=t?.count??10,n=Mn(this.githubToken),s=new Ps(n,this),o=t?.broad?await aL({octokit:n,vetter:s,count:r,languages:this.state.preferences.languages,excludeRepos:this.state.preferences.excludeRepos,excludeOrgs:this.state.preferences.excludeOrgs,aiPolicyBlocklist:this.state.preferences.aiPolicyBlocklist,splitRatio:t?.splitRatio??this.state.preferences.featuresSplitRatio}):await wg({octokit:n,vetter:s,repoScores:this.state.repoScores??{},count:r,excludeRepos:this.state.preferences.excludeRepos,excludeOrgs:this.state.preferences.excludeOrgs,aiPolicyBlocklist:this.state.preferences.aiPolicyBlocklist,anchorThreshold:t?.anchorThreshold??this.state.preferences.featuresAnchorThreshold,splitRatio:t?.splitRatio??this.state.preferences.featuresSplitRatio});return this.saveResults([...o.quickWins,...o.biggerBets]),this.state.lastSearchAt=new Date().toISOString(),this.dirty=!0,o}async vetList(t){this.evictStaleCacheEntries();let r=this.getSavedResults(),n=t?.concurrency??5,s=[],o=new Map,i=null;for(let m of r){if(i)break;let f=this.vetIssue(m.issueUrl).then(g=>{s.push({issueUrl:m.issueUrl,repo:m.repo,number:m.number,title:m.title,status:this.classifyVetResult(g),ok:!0,recommendation:g.recommendation,viabilityScore:g.viabilityScore})}).catch(g=>{if($e(g)===401||Je(g)){i??=g;return}let y=$e(g),b=y===404||y===410;s.push({issueUrl:m.issueUrl,repo:m.repo,number:m.number,title:m.title,status:b?"closed":"error",ok:!1,errorMessage:K(g)})}).finally(()=>{o.delete(m.issueUrl)});o.set(m.issueUrl,f),o.size>=n&&await Promise.race(o.values())}if(await Promise.allSettled(o.values()),i)throw s.length>0&&z("scout",`vetList aborted mid-batch after ${s.length} result(s) \u2014 discarding partial results due to auth/rate-limit failure`),i;let a={total:s.length,stillAvailable:s.filter(m=>m.status==="still_available").length,claimed:s.filter(m=>m.status==="claimed").length,closed:s.filter(m=>m.status==="closed").length,hasPR:s.filter(m=>m.status==="has_pr").length,errors:s.filter(m=>m.status==="error").length},c=new Map((this.state.savedResults??[]).map(m=>[m.issueUrl,m.lastStatus])),u=s.filter(m=>m.status!=="error").filter(m=>{let f=c.get(m.issueUrl);return f!==void 0&&f!==m.status}).map(m=>({issueUrl:m.issueUrl,repo:m.repo,number:m.number,from:c.get(m.issueUrl),to:m.status})),d=new Map(s.map(m=>[m.issueUrl,m.status]));for(let m of this.state.savedResults??[]){let f=d.get(m.issueUrl);f!==void 0&&f!=="error"&&(m.lastStatus=f)}s.length>0&&(this.dirty=!0);let p;if(t?.prune){let m=new Set(s.filter(g=>g.status!=="still_available").map(g=>g.issueUrl)),f=(this.state.savedResults??[]).length;this.state.savedResults=(this.state.savedResults??[]).filter(g=>!m.has(g.issueUrl)),p=f-(this.state.savedResults?.length??0),p>0&&this.addTombstones([...m]),this.dirty=!0}return{results:s,summary:a,prunedCount:p,transitions:u}}classifyVetResult(t){if(t.issueState==="closed")return"closed";let r=t.vettingResult.checks;return r.noExistingPR?r.notClaimed?"still_available":"claimed":"has_pr"}getReposWithMergedPRs(){let t=new Map;for(let r of this.state.mergedPRs??[]){let n=ut(r.url);n&&t.set(n,(t.get(n)??0)+1)}return[...t.entries()].sort((r,n)=>n[1]-r[1]).map(([r])=>r)}getReposWithOpenPRs(){let t=new Map;for(let r of this.state.openPRs??[]){let n=ut(r.url);n&&t.set(n,(t.get(n)??0)+1)}return[...t.entries()].sort((r,n)=>n[1]-r[1]).map(([r])=>r)}getStarredRepos(){return this.state.starredRepos}getProjectCategories(){return this.state.preferences.projectCategories}getGitHubUsername(){return this.state.preferences.githubUsername}getRepoScore(t){let r=this.state.repoScores[t];return r?r.score:null}getClosedWithoutMergeCount(t){let r=this.state.repoScores[t];return r?r.closedWithoutMergeCount:(this.state.closedPRs??[]).filter(n=>ut(n.url)===t).length}getSLMTriageConfig(){let t=this.state.preferences.slmTriageModel??"";return t?{model:t,host:this.state.preferences.slmTriageHost??""}:null}getComplexIssuesMode(){return this.state.preferences.complexIssues??"off"}getPreferences(){return this.state.preferences}getRepoScoreRecord(t){return this.state.repoScores[t]}recordMergedPR(t){let r=this.state.mergedPRs??[];r.some(n=>n.url===t.url)||(this.state.mergedPRs=[...r,{url:t.url,title:t.title,mergedAt:t.mergedAt}],this.updateRepoScoreFromPRs(t.repo),this.dirty=!0)}recordClosedPR(t){let r=this.state.closedPRs??[];r.some(n=>n.url===t.url)||(this.state.closedPRs=[...r,{url:t.url,title:t.title,closedAt:t.closedAt}],this.updateRepoScoreFromPRs(t.repo),this.dirty=!0)}recordOpenPR(t){let r=this.state.openPRs??[];r.some(n=>n.url===t.url)||(this.state.openPRs=[...r,{url:t.url,title:t.title,openedAt:t.openedAt}],this.dirty=!0)}async syncOpenPRs(){let t=Mn(this.githubToken),r=this.state.openPRs??[],n={checked:r.length,merged:0,closed:0,stillOpen:0,errors:0},s=[];for(let o of r){let i=Do(o.url);if(!i||i.type!=="pull"){s.push(o),n.errors++;continue}let a=`${i.owner}/${i.repo}`;try{let{data:c}=await t.pulls.get({owner:i.owner,repo:i.repo,pull_number:i.number});c.merged?(this.recordMergedPR({url:o.url,title:o.title,mergedAt:c.merged_at??new Date().toISOString(),repo:a}),n.merged++):c.state==="closed"?(this.recordClosedPR({url:o.url,title:o.title,closedAt:c.closed_at??new Date().toISOString(),repo:a}),n.closed++):(s.push(o),n.stillOpen++)}catch(c){He(c),z("scout",`sync: could not check ${o.url}: ${K(c)}`),s.push(o),n.errors++}}return this.state.openPRs=s,this.dirty=!0,await this.checkpoint(),n}updateRepoScore(t,r){let s=this.state.repoScores[t]??{repo:t,score:5,mergedPRCount:0,closedWithoutMergeCount:0,avgResponseDays:null,lastEvaluatedAt:new Date().toISOString(),signals:{hasActiveMaintainers:!1,isResponsive:!1,hasHostileComments:!1}},o={...s,...r,repo:t,lastEvaluatedAt:new Date().toISOString(),signals:{...s.signals,...r.signals??{}}};o.score=this.calculateScore(o),this.state.repoScores[t]=o,this.dirty=!0}updatePreferences(t){this.state.preferences={...this.state.preferences,...t},this.state.preferencesUpdatedAt=new Date().toISOString(),this.dirty=!0}setStarredRepos(t){this.state.starredRepos=t,this.state.starredReposLastFetched=new Date().toISOString(),this.dirty=!0}saveResults(t){let r=new Date().toISOString(),n=new Map((this.state.savedResults??[]).map(s=>[s.issueUrl,s]));for(let s of t){if(s.recommendation==="skip"){n.delete(s.issue.url);let i=new Set(["Issue is closed","Linked PR already merged"]),a=s.reasonsToSkip.some(c=>i.has(c));this.skipIssue(s.issue.url,{repo:s.issue.repo,number:s.issue.number,title:s.issue.title,reason:s.reasonsToSkip.join("; ")||"vetter: skip",permanent:a});continue}let o=n.get(s.issue.url);n.set(s.issue.url,{issueUrl:s.issue.url,repo:s.issue.repo,number:s.issue.number,title:s.issue.title,labels:s.issue.labels,recommendation:s.recommendation,viabilityScore:s.viabilityScore,searchPriority:s.searchPriority,firstSeenAt:o?.firstSeenAt??r,lastSeenAt:r,lastScore:s.viabilityScore,horizon:"horizon"in s?s.horizon:void 0})}this.state.savedResults=[...n.values()],this.dirty=!0}getSavedResults(){return this.state.savedResults??[]}clearResults(){this.addTombstones((this.state.savedResults??[]).map(t=>t.issueUrl)),this.state.savedResults=[],this.dirty=!0}addTombstones(t){if(t.length===0)return;let r=new Date().toISOString(),n=this.state.tombstones??[],s=new Map(n.map(o=>[o.url,o]));for(let o of t)s.set(o,{url:o,removedAt:r});this.state.tombstones=[...s.values()]}skipIssue(t,r){let n=this.state.skippedIssues??[],s=n.find(i=>i.url===t);if(s){r?.permanent===!0&&s.permanent!==!0&&(s.permanent=!0,s.skippedAt=new Date().toISOString(),this.dirty=!0);return}let o=r?.permanent??!0;this.state.skippedIssues=[...n,{url:t,repo:r?.repo??"",number:r?.number??0,title:r?.title??"",skippedAt:new Date().toISOString(),permanent:o,...r?.reason?{reason:r.reason}:{}}],this.state.savedResults&&(this.state.savedResults=this.state.savedResults.filter(i=>i.issueUrl!==t)),this.dirty=!0}getSkippedIssues(){return this.state.skippedIssues??[]}unskipIssue(t){let r=(this.state.skippedIssues??[]).length;this.state.skippedIssues=(this.state.skippedIssues??[]).filter(n=>n.url!==t),this.state.skippedIssues.length<r&&this.addTombstones([t]),this.dirty=!0}clearSkippedIssues(){this.addTombstones((this.state.skippedIssues??[]).map(t=>t.url)),this.state.skippedIssues=[],this.dirty=!0}cullExpiredSkips(t=90){let r=new Date;r.setDate(r.getDate()-t);let n=[];return this.state.skippedIssues=(this.state.skippedIssues??[]).filter(s=>{if(s.permanent!==!1)return!0;let o=new Date(s.skippedAt);return isNaN(o.getTime())||o>=r?!0:(n.push(s.url),!1)}),n.length>0&&(this.addTombstones(n),this.dirty=!0),n.length}isDirty(){return this.dirty}async checkpoint(){if(!this.dirty)return!0;if(this.state.lastRunAt=new Date().toISOString(),this.gistStore&&!await this.gistStore.push(this.state))return!1;if(this.persistLocal)try{this.state=Sl(this.state,Sg()),lL(this.state)}catch{return!1}return this.dirty=!1,!0}getState(){return this.state}updateRepoScoreFromPRs(t){let r=(this.state.mergedPRs??[]).filter(s=>ut(s.url)===t).length,n=(this.state.closedPRs??[]).filter(s=>ut(s.url)===t).length;this.updateRepoScore(t,{mergedPRCount:r,closedWithoutMergeCount:n,lastMergedAt:r>0?(this.state.mergedPRs??[]).filter(s=>ut(s.url)===t).sort((s,o)=>o.mergedAt.localeCompare(s.mergedAt))[0]?.mergedAt:void 0})}calculateScore(t){let r=5;return r+=Math.min(t.mergedPRCount,3),r-=Math.min(t.closedWithoutMergeCount,3),t.signals.hasActiveMaintainers&&(r+=1),t.signals.hasHostileComments&&(r-=2),Math.max(1,Math.min(10,r))}}});function bL(){let e=kl.filter(r=>!(r in vl));if(e.length>0)throw new Error(`FIELD_CONFIGS is missing entries for preference keys: ${e.join(", ")}`);let t=Object.keys(vl).filter(r=>!kl.includes(r));if(t.length>0)throw new Error(`FIELD_CONFIGS has entries for unknown preference keys: ${t.join(", ")}`)}function mK(e){let t=e.toLowerCase();if(t==="true"||t==="yes")return!0;if(t==="false"||t==="no")return!1;throw new at(`Invalid boolean value: "${e}". Use true/false or yes/no.`)}function fK(e,t){let r=parseInt(e,10);if(isNaN(r))throw new at(`Invalid number for "${t}": "${e}"`);return r}function gK(e,t){let r=Number.parseFloat(e);if(isNaN(r))throw new at(`Invalid number for "${t}": "${e}"`);return r}function rC(e){return e.split(",").map(t=>t.trim()).filter(t=>t.length>0)}function Pg(e,t){if(t.startsWith("+")){let r=rC(t.slice(1)),n=[...e];for(let s of r)n.includes(s)||n.push(s);return n}if(t.startsWith("-")){let r=new Set(rC(t.slice(1)));return e.filter(n=>!r.has(n))}return rC(t)}function wL(e,t,r){let n=vl[t];if(!n)throw new at(`Unknown config key: "${t}". Valid keys: ${nC.join(", ")}`);let s={...e};switch(n.type){case"string":t==="slmTriageHost"&&$D(r),s[t]=r;break;case"boolean":s[t]=mK(r);break;case"number":s[t]=fK(r,t);break;case"float":s[t]=gK(r,t);break;case"array":{let o=s[t]??[];s[t]=Pg(o,r);break}case"enum":{let o=n.validValues;if(!o.includes(r))throw new at(`Invalid value for "${t}": "${r}". Valid: ${o.join(", ")}`);s[t]=r;break}case"enum-array":{let o=s[t]??[],i=Pg(o,r),a=n.validValues,c=i.filter(u=>!a.includes(u));if(c.length>0)throw new at(`Invalid value(s) for "${t}": ${c.join(", ")}. Valid: ${a.join(", ")}`);t==="scope"?s[t]=i.length>0?i:void 0:s[t]=i;break}}return Lo.parse(s)}var vl,kl,nC,RL=A(()=>{No();ct();Lk();vl={githubUsername:{type:"string"},languages:{type:"array"},labels:{type:"array"},scope:{type:"enum-array",validValues:gl.options},excludeRepos:{type:"array"},excludeOrgs:{type:"array"},preferredOrgs:{type:"array"},aiPolicyBlocklist:{type:"array"},projectCategories:{type:"enum-array",validValues:fl.options},minStars:{type:"number"},maxIssueAgeDays:{type:"number"},includeDocIssues:{type:"boolean"},minRepoScoreThreshold:{type:"number"},interPhaseDelayMs:{type:"number"},persistence:{type:"enum",validValues:wk.options},defaultStrategy:{type:"enum-array",validValues:Mo.options},broadPhaseDelayMs:{type:"number"},skipBroadWhenSufficientResults:{type:"number"},preferLanguages:{type:"array"},preferRepos:{type:"array"},diversityRatio:{type:"float"},avoidRepos:{type:"array"},boostIssueTypes:{type:"array"},slmTriageModel:{type:"string"},slmTriageHost:{type:"string"},complexIssues:{type:"enum",validValues:Rk.options},featuresAnchorThreshold:{type:"number"},featuresSplitRatio:{type:"float"}},kl=Object.keys(Lo.shape),nC=[...kl].sort()});async function SL(e,t,r=fr()){let n=e.getPreferences().githubUsername;if(!n)throw new Ga("GitHub username not configured. Run `oss-scout setup` first.");let s=await Xf(t);if(se(cn,`Rate limit: ${s.remaining}/${s.limit}, resets at ${s.resetAt}`),s.remaining<15)return se(cn,"Insufficient rate limit, skipping bootstrap"),{starredRepoCount:0,mergedPRCount:0,closedPRCount:0,openPRCount:0,reposScoredCount:0,skippedDueToRateLimit:!0,errors:[]};r.init(s.remaining,s.resetAt);let o=Mn(t),i=[],a=[],c=0,u=new Set;try{let f=0;for await(let g of o.paginate.iterator(o.activity.listReposStarredByAuthenticatedUser,{per_page:Uo,headers:{accept:"application/vnd.github.v3+json"}})){for(let y of g.data){let b=y;a.push(b.full_name)}if(f++,f>=hK)break}se(cn,`Fetched ${a.length} starred repos`),e.setStarredRepos(a),c=a.length}catch(f){He(f),z(cn,`Failed to fetch starred repos: ${K(f)}`),i.push("starred repos fetch failed")}let d=0;try{for(let f=1;f<=sC;f++){await r.waitForBudget();let g;try{g=(await o.search.issuesAndPullRequests({q:`is:pr is:merged author:${n}`,per_page:Uo,page:f})).data}finally{r.recordCall()}for(let y of g.items){let b=ut(y.html_url);b&&(e.recordMergedPR({url:y.html_url,title:y.title,mergedAt:y.closed_at??new Date().toISOString(),repo:b}),u.add(b),d++)}if(g.items.length<Uo)break}se(cn,`Imported ${d} merged PRs`)}catch(f){He(f),z(cn,`Failed to fetch merged PRs: ${K(f)}`),i.push("merged PR fetch failed")}let p=0;try{for(let f=1;f<=sC;f++){await r.waitForBudget();let g;try{g=(await o.search.issuesAndPullRequests({q:`is:pr is:closed is:unmerged author:${n}`,per_page:Uo,page:f})).data}finally{r.recordCall()}for(let y of g.items){let b=ut(y.html_url);b&&(e.recordClosedPR({url:y.html_url,title:y.title,closedAt:y.closed_at??new Date().toISOString(),repo:b}),u.add(b),p++)}if(g.items.length<Uo)break}se(cn,`Imported ${p} closed PRs`)}catch(f){He(f),z(cn,`Failed to fetch closed PRs: ${K(f)}`),i.push("closed PR fetch failed")}let m=0;try{for(let f=1;f<=sC;f++){await r.waitForBudget();let g;try{g=(await o.search.issuesAndPullRequests({q:`is:pr is:open author:${n}`,per_page:Uo,page:f})).data}finally{r.recordCall()}for(let y of g.items){let b=ut(y.html_url);b&&(e.recordOpenPR({url:y.html_url,title:y.title,openedAt:y.created_at??new Date().toISOString(),repo:b}),m++)}if(g.items.length<Uo)break}se(cn,`Imported ${m} open PRs`)}catch(f){He(f),z(cn,`Failed to fetch open PRs: ${K(f)}`),i.push("open PR fetch failed")}return{starredRepoCount:c,mergedPRCount:d,closedPRCount:p,openPRCount:m,reposScoredCount:u.size,skippedDueToRateLimit:!1,errors:i}}var cn,hK,sC,Uo,_L=A(()=>{eg();it();ct();At();za();cn="bootstrap",hK=5,sC=3,Uo=100});function CL(e,t,r){if(!t.test(e))throw new at(`Invalid ${r} URL: ${e}. Expected format: https://github.com/owner/repo/issues/123`)}function PL(e){if(e.length>vL)throw new at(`URL exceeds maximum length of ${vL} characters`);return e}var kL,vL,EL=A(()=>{ct();kL=/^https:\/\/github\.com\/[^/]+\/[^/]+\/issues\/\d+$/,vL=2048});var AL={};re(AL,{ANCHOR_THRESHOLD:()=>Wk,ANTI_LLM_KEYWORDS:()=>Tk,FEATURE_LABELS:()=>bg,FIELD_CONFIGS:()=>vl,HorizonSchema:()=>bk,ISSUE_URL_PATTERN:()=>kL,IssueDiscovery:()=>Go,IssueScopeSchema:()=>gl,IssueVetter:()=>Ps,NO_ANCHORS_MESSAGE:()=>Zk,NO_RESULTS_MESSAGE:()=>Kk,OssScout:()=>_l,PREFERENCE_KEYS:()=>kl,ProjectCategorySchema:()=>fl,RepoScoreSchema:()=>hk,SORTED_PREFERENCE_KEYS:()=>nC,STALLED_PR_THRESHOLD_DAYS:()=>lD,ScoutPreferencesSchema:()=>Lo,ScoutStateSchema:()=>Fn,SearchStrategySchema:()=>Mo,SkippedIssueSchema:()=>yk,applyPreferenceField:()=>wL,assertFieldConfigsCover:()=>bL,bootstrapScout:()=>SL,classifyHorizon:()=>qk,createScout:()=>Cg,discoverFeatures:()=>wg,enableDebug:()=>j0,fetchRoadmapIssueRefs:()=>hg,getGitHubToken:()=>uk,getLogLevel:()=>U0,isLinkedPRStalled:()=>og,parseRoadmapIssueRefs:()=>zk,requireGitHubToken:()=>Z0,resolveAnchorRepos:()=>Vk,scanForAntiLLMPolicy:()=>$k,setLogLevel:()=>qf,splitByHorizon:()=>yg,updateArray:()=>Pg,validateGitHubUrl:()=>CL,validateUrl:()=>PL});var Eg=A(()=>{yL();No();RL();At();Uk();ug();Ok();_L();it();Jk();kk();Bk();EL()});function wK(e){let t=[],r=e.split(/\r?\n/);for(let n=0;n<r.length;n++){let s=n+1,o=r[n].trim();if(o===""||o.startsWith("#"))continue;let i=o.match(/^(\S+)\s+(\S+)(?:\s+#.*)?$/);if(!i){k("skip-file-parser",`Line ${s}: malformed (expected "<date> <url>"): ${o}`);continue}let[,a,c]=i;if(!yK.test(a)){k("skip-file-parser",`Line ${s}: invalid date format (expected YYYY-MM-DD): ${o}`);continue}let u=Date.parse(`${a}T00:00:00.000Z`);if(Number.isNaN(u)){k("skip-file-parser",`Line ${s}: unparseable date: ${o}`);continue}let d=new Date(u).toISOString().slice(0,10);if(d!==a){k("skip-file-parser",`Line ${s}: invalid calendar date ${a} (would be normalized to ${d}): ${o}`);continue}let p=c.match(bK);if(!p){k("skip-file-parser",`Line ${s}: non-GitHub-issue URL: ${o}`);continue}let[,m,f]=p,g=Number.parseInt(f,10);t.push({url:c,repo:m,number:g,title:"",skippedAt:new Date(u).toISOString(),permanent:!0})}return t}function oC(e){if(!e)return{issues:[]};let t=TL.resolve(e);if(!Ag.existsSync(t))return k("skip-file-parser",`Configured skipped-issues file not found at ${t} (cwd ${process.cwd()}); proceeding with an EMPTY skip list \u2014 previously skipped issues may resurface. Use an absolute skippedIssuesPath, or run from the directory that contains "${e}".`),{issues:[],notFound:!0,resolvedPath:t};let r;try{r=Ag.readFileSync(t,"utf8")}catch(n){return k("skip-file-parser",`Failed to read skipped-issues file at ${t}: ${I(n)}`),{issues:[],readError:I(n),resolvedPath:t}}return{issues:wK(r),resolvedPath:t}}function $L(e){return oC(e).issues}var Ag,TL,yK,bK,iC=A(()=>{"use strict";Ag=B(require("node:fs"),1),TL=B(require("node:path"),1);ae();ee();yK=/^\d{4}-\d{2}-\d{2}$/,bK=/^https:\/\/github\.com\/([^/]+\/[^/]+)\/(?:issues|pull)\/(\d+)(?:[#/?].*)?$/});function jo(e){if(!e)return null;let t={author:{login:e.author},state:e.merged?"merged":e.state};return e.updatedAt!==void 0&&(t.updatedAt=e.updatedAt),t}function Es(e){if(!e)return;let t=jo(e);if(!t)return;let r={number:e.number,state:t.state,url:e.url,isStalled:sf(t)};return e.updatedAt!==void 0&&(r.updatedAt=e.updatedAt),r}function RK(e,t=[]){let r=M().getState(),{config:n}=r,s=oC(n.skippedIssuesPath);(s.readError!==void 0||s.notFound)&&e&&(e.skipListUnavailable=!0);let o=[...s.issues],i=new Set(o.map(m=>m.url));for(let[m,f]of Object.entries(n.dismissedIssues??{})){if(i.has(m)||!nr.test(m))continue;let g=q(m);i.add(m),o.push({url:m,repo:g?`${g.owner}/${g.repo}`:"",number:g?.number??0,title:"",skippedAt:f,reason:"dismissed",permanent:!0})}let a=lr(r.workClaims??[]);for(let m of a){if(m.kind!=="implementation"||i.has(m.url)||!nr.test(m.url))continue;let f=q(m.url);i.add(m.url),o.push({url:m.url,repo:f?`${f.owner}/${f.repo}`:"",number:f?.number??0,title:"",skippedAt:m.startedAt,reason:`implementation in progress (session ${m.session})`,permanent:!0})}let c=new Date().toISOString();for(let m of t){if(i.has(m)||!nr.test(m))continue;let f=q(m);i.add(m),o.push({url:m,repo:f?`${f.owner}/${f.repo}`:"",number:f?.number??0,title:"",skippedAt:c,reason:"excluded by caller",permanent:!0})}let u=Rs(r),d=Hf(r),p=new Set(d.map(m=>m.toLowerCase()));return{version:1,stateRevision:1,preferences:{githubUsername:n.githubUsername,languages:n.languages,labels:n.labels,scope:n.scope,excludeRepos:[...n.excludeRepos,...d],excludeOrgs:n.excludeOrgs??[],preferredOrgs:n.preferredOrgs??[],aiPolicyBlocklist:n.aiPolicyBlocklist,projectCategories:n.projectCategories??[],minStars:n.minStars,maxIssueAgeDays:n.maxIssueAgeDays,includeDocIssues:n.includeDocIssues,minRepoScoreThreshold:n.minRepoScoreThreshold,interPhaseDelayMs:0,broadPhaseDelayMs:0,skipBroadWhenSufficientResults:n.skipBroadWhenSufficientResults,complexIssues:n.complexIssues==="warm"?"warm":"off",persistence:n.persistence,slmTriageModel:n.slmTriageModel,slmTriageHost:n.slmTriageHost,featuresAnchorThreshold:3,featuresSplitRatio:.6,preferLanguages:u?.recommendations.languages??[],preferRepos:(u?.recommendations.repos??[]).filter(m=>!p.has(m.toLowerCase())),diversityRatio:Cl,avoidRepos:n.avoidRepos??[],boostIssueTypes:n.boostIssueTypes??[]},repoScores:r.repoScores,tombstones:[],starredRepos:n.starredRepos,starredReposLastFetched:n.starredReposLastFetched,mergedPRs:(r.mergedPRs??[]).map(m=>({url:m.url,title:m.title,mergedAt:m.mergedAt})),closedPRs:(r.closedPRs??[]).map(m=>({url:m.url,title:m.title,closedAt:m.closedAt})),openPRs:(r.lastDigest?.openPRs??[]).map(m=>({url:m.url,title:m.title,openedAt:m.createdAt})),savedResults:(r.searchSeen??[]).map(m=>({issueUrl:m.url,repo:"",number:0,title:"",labels:[],recommendation:"skip",viabilityScore:0,searchPriority:"normal",firstSeenAt:m.lastSeenAt,lastSeenAt:m.lastSeenAt,lastScore:0})),skippedIssues:o,lastRunAt:r.lastRunAt,searchRotation:r.searchRotation??FS.parse({})}}async function As(e,t){let r=ke();return Cg({githubToken:r,persistence:"provided",initialState:RK(e,t)})}var Cl,Ja=A(()=>{"use strict";Na();Eg();ue();wn();tl();iC();xt();Cl=.2});function Ts(e,t){return e==="approve"&&t.score<4?"needs_review":e}function SK(e){return e.reduce((t,r)=>r.score<t.score?r:t)}function _K(e){let t=zo.indexOf(e);return t===-1?zo[zo.length-1]:zo[Math.min(t+1,zo.length-1)]}function Gn(e,t,r){return typeof e!="number"||!Number.isFinite(e)||e<t||e>r?null:e}function vK(e){return e<3?{score:10,detail:`~${Math.round(e)}-day avg response`}:e<14?{score:7,detail:`${Math.round(e)}-day avg response`}:e<=60?{score:4,detail:`${Math.round(e)}-day avg response`}:{score:1,detail:"unresponsive maintainers"}}function kK(e){let t=Math.round(e*100);return e>.7?{score:10,detail:`merges ${t}% of PRs`}:e>=.4?{score:7,detail:`merges ${t}% of PRs`}:e>=.1?{score:4,detail:`merges ${t}% of PRs`}:{score:1,detail:`merges ${t}% of PRs`}}function CK(e){return e<7?{score:10,detail:"commits in last week"}:e<30?{score:7,detail:"commits in last month"}:e<90?{score:4,detail:"commits in last 90 days"}:{score:1,detail:`no commits in ${e}+ days`}}function PK(e){let{projectHealth:t,repoScore:r}=e,n=!t.checkFailed,s=Gn(r?.avgResponseDays,0,Number.MAX_SAFE_INTEGER)??(n?Gn(t.avgIssueResponseDays,.001,Number.MAX_SAFE_INTEGER):null),o=n?Gn(t.daysSinceLastCommit,0,Number.MAX_SAFE_INTEGER):null,i=n?Gn(t.recentMergeRate,0,1):null;if(i===null&&r){let a=Gn(r.mergedPRCount,0,Number.MAX_SAFE_INTEGER),c=Gn(r.closedWithoutMergeCount,0,Number.MAX_SAFE_INTEGER);if(a!==null&&c!==null){let u=a+c;i=u===0?null:a/u}}return{avgResponseDays:s,mergeRate:i,daysSinceLastCommit:o}}function $s(e){let t=e.getRepoScore(e.repo),r=e.projectHealth,n=r.checkFailed?{avgIssueResponseDays:null,daysSinceLastCommit:null,checkFailed:!0}:{avgIssueResponseDays:r.avgIssueResponseDays,daysSinceLastCommit:r.daysSinceLastCommit,recentMergeRate:r.recentMergeRate??null,checkFailed:!1};return aC(PK({projectHealth:n,repoScore:t?{mergedPRCount:t.mergedPRCount,closedWithoutMergeCount:t.closedWithoutMergeCount,avgResponseDays:t.avgResponseDays}:null}))}function aC(e){let t=[],r=[],n=Gn(e.avgResponseDays,0,Number.MAX_SAFE_INTEGER);n===null?r.push("maintainer responsiveness"):t.push(vK(n));let s=Gn(e.mergeRate,0,1);s===null?r.push("merge rate"):t.push(kK(s));let o=Gn(e.daysSinceLastCommit,0,Number.MAX_SAFE_INTEGER);if(o===null?r.push("activity"):t.push(CK(o)),t.length===0)return{score:zo[zo.length-1],reason:`unknown ${r.join(", ")}`};let i=SK(t),a=r.length>0?_K(i.score):i.score,c=[i.detail];return r.length>0&&c.push(`unknown ${r.join(", ")}`),{score:a,reason:c.join(", ")}}var zo,Pl=A(()=>{"use strict";zo=[10,7,4,1]});async function TK(e){let t=[],r=0;for await(let n of e.paginate.iterator(e.activity.listReposStarredByAuthenticatedUser,{per_page:EK,headers:{accept:"application/vnd.github.v3+json"}})){for(let s of n.data)s.full_name&&t.push(s.full_name);if(r+=1,r>=AK)break}return t}async function OL(e){if(!e.isStarredReposStale())return e.getStarredRepos().length;let t=ke(),r;try{r=await TK(we(t))}catch(n){return k(cC,`Failed to refresh starred repos; continuing with cached list (${e.getStarredRepos().length}): ${n instanceof Error?n.message:String(n)}`),e.getStarredRepos().length}return r.length===0?(O(cC,"Starred-repo fetch returned 0; keeping existing cache"),e.getStarredRepos().length):(e.setStarredRepos(r),O(cC,`Refreshed starred repos from GitHub: ${r.length} cached`),r.length)}var cC,EK,AK,IL=A(()=>{"use strict";lo();jm();ae();cC="starred-repos",EK=100,AK=5});var ML={};re(ML,{DEFAULT_SEARCH_RESULTS:()=>OK,MAX_SEARCH_RESULTS:()=>$K,SEARCH_DIVERSITY_RATIO:()=>Cl,SEARCH_SEEN_RETENTION_DAYS:()=>fu,parseSearchStrategies:()=>xK,readExcludeFile:()=>IK,recordSearchSeen:()=>LL,runSearch:()=>LK});function IK(e){let t;try{t=DL.readFileSync(e,"utf8")}catch(n){throw new Error(`Cannot read --exclude-file "${e}": ${n instanceof Error?n.message:String(n)}`,{cause:n})}let r=[...new Set(t.match(/https:\/\/github\.com\/[^/\s]+\/[^/\s]+\/issues\/\d+/g)??[])];return r.length===0&&t.trim()!==""&&k(Bo,`--exclude-file "${e}" has content but no GitHub issue URLs; nothing is excluded`),r}function xK(e){if(e===void 0)return;let t=e.split(",").map(n=>n.trim()).filter(Boolean);if(t.length===0)return;let r=[];for(let n of t){let s=Mo.safeParse(n);if(!s.success)throw new Error(`Unknown search strategy "${n}". Valid strategies: merged, orgs, starred, broad, maintained, all`);r.push(s.data)}return r}function DK(e){return typeof e!="number"||!Number.isFinite(e)||e<0||e>100?(k(Bo,`Ignoring out-of-contract viabilityScore from scout: ${JSON.stringify(e)}`),0):e}function xL(e){let t=process.env[e];if(t===void 0||t==="")return;let r=Number(t);if(!Number.isInteger(r)||r<0){k(Bo,`Ignoring invalid ${e}="${t}" (expected a non-negative integer); using scout's default delay`);return}return r}function LL(e,t){let r=Date.now(),n=new Date(r).toISOString(),s=r-fu*24*60*60*1e3,o=new Map(e.getSearchSeen().map(a=>[a.url,a]));for(let a of t)o.set(a,{url:a,lastSeenAt:n});let i=[...o.values()].filter(a=>{let c=Date.parse(a.lastSeenAt);return Number.isNaN(c)?!1:c>=s});e.setSearchSeen(i)}async function LK(e){let t={},r=M();await OL(r);let n=await As(t,e.excludeUrls),s=Rs(r.getState()),o=s?.recommendations.languages??void 0,i=Hf(r.getState()),a=new Set(i.map(R=>R.toLowerCase())),c=s?.recommendations.repos?.filter(R=>!a.has(R.toLowerCase()));(o?.length||c?.length)&&O(Bo,`Applying strategy bias to search: preferLanguages=${JSON.stringify(o??[])}, preferRepos=${JSON.stringify(c??[])}`);let u=xL("OSS_AUTOPILOT_SCOUT_INTER_PHASE_DELAY_MS"),d=xL("OSS_AUTOPILOT_SCOUT_BROAD_PHASE_DELAY_MS"),p=await n.search({maxResults:e.maxResults,...e.strategies&&{strategies:e.strategies},...e.full&&{full:!0},preferLanguages:o,preferRepos:c,diversityRatio:Cl,recentlySurfacedTtlDays:zS,...u!==void 0&&{interPhaseDelayMs:u},...d!==void 0&&{broadPhaseDelayMs:d}}),m=null;if(e.record!==!1){let R=()=>{LL(r,p.candidates.map(h=>h.issue.url)),r.setSearchRotation(n.getState().searchRotation)};R(),m=await Re(r,Bo,R)}let f=r.getState().config?.githubUsername??"";f===""&&k(Bo,"githubUsername not configured \u2014 the own-PR filter (#1354) cannot run; hiddenOwnPRCount will be 0");let g=p.candidates.filter(R=>bs({linkedPR:jo(R.vettingResult?.linkedPR),userLogin:f})!=="user_open"),y=p.candidates.length-g.length;y>0&&O(Bo,`Hid ${y} candidate(s) with the user's own open PR (#1354)`);let b={candidates:g.map(R=>{let h=r.getRepoScore(R.issue.repo),_=$s({repo:R.issue.repo,projectHealth:R.projectHealth??{repo:R.issue.repo,checkFailed:!0,failureReason:"health not supplied by the caller"},getRepoScore:w=>{let P=r.getRepoScore(w);return P?{mergedPRCount:P.mergedPRCount,closedWithoutMergeCount:P.closedWithoutMergeCount,avgResponseDays:P.avgResponseDays??null}:void 0}}),S=Es(R.vettingResult?.linkedPR);return{issue:{repo:R.issue.repo,repoUrl:`https://github.com/${R.issue.repo}`,number:R.issue.number,title:R.issue.title,url:R.issue.url,labels:R.issue.labels},recommendation:Ts(R.recommendation,_),reasonsToApprove:R.reasonsToApprove,reasonsToSkip:R.reasonsToSkip,searchPriority:R.searchPriority,...R.complexityUnlocked&&{complexityUnlocked:!0},viabilityScore:DK(R.viabilityScore),grade:_,repoScore:h?{score:h.score,mergedPRCount:h.mergedPRCount,closedWithoutMergeCount:h.closedWithoutMergeCount,isResponsive:h.signals?.isResponsive??!1,lastMergedAt:h.lastMergedAt}:void 0,...S&&{linkedPR:S},...R.personalization?.kind==="boosted"&&{boostScore:R.personalization.score},...R.personalization?.kind==="boosted"&&R.personalization.reasons.length>0&&{boostReasons:R.personalization.reasons},...R.personalization?.kind==="diversity"&&{diversitySlot:!0}}}),excludedRepos:p.excludedRepos,aiPolicyBlocklist:p.aiPolicyBlocklist,hiddenOwnPRCount:y,reposAtCap:i};return m&&(b.gistSyncWarning=m),p.rateLimitWarning&&(b.rateLimitWarning=p.rateLimitWarning),t.skipListUnavailable&&(b.skipListUnavailable=!0),b}var DL,Bo,$K,OK,FL=A(()=>{"use strict";DL=B(require("node:fs"),1);Ja();Eg();ue();Pl();tl();IL();ae();Na();Wi();Ja();Wi();Bo="search",$K=100,OK=15});var GL={};re(GL,{MAX_FEATURES_RESULTS:()=>FK,runFeatures:()=>GK});function NK(e){return typeof e!="number"||!Number.isFinite(e)||e<0||e>100?(k(MK,`Ignoring out-of-contract viabilityScore from scout: ${JSON.stringify(e)}`),0):e}function NL(e,t){let r=t.getRepoScore(e.issue.repo),n=$s({repo:e.issue.repo,projectHealth:e.projectHealth??{repo:e.issue.repo,checkFailed:!0,failureReason:"health not supplied by the caller"},getRepoScore:o=>{let i=t.getRepoScore(o);return i?{mergedPRCount:i.mergedPRCount,closedWithoutMergeCount:i.closedWithoutMergeCount,avgResponseDays:i.avgResponseDays??null}:void 0}}),s=Es(e.vettingResult?.linkedPR);return{issue:{repo:e.issue.repo,repoUrl:`https://github.com/${e.issue.repo}`,number:e.issue.number,title:e.issue.title,url:e.issue.url,labels:e.issue.labels},recommendation:Ts(e.recommendation,n),reasonsToApprove:e.reasonsToApprove,reasonsToSkip:e.reasonsToSkip,searchPriority:e.searchPriority,...e.complexityUnlocked&&{complexityUnlocked:!0},viabilityScore:NK(e.viabilityScore),grade:n,repoScore:r?{score:r.score,mergedPRCount:r.mergedPRCount,closedWithoutMergeCount:r.closedWithoutMergeCount,isResponsive:r.signals?.isResponsive??!1,lastMergedAt:r.lastMergedAt}:void 0,...s&&{linkedPR:s},horizon:e.horizon}}async function GK(e){let r=await(await As()).features({count:e.maxResults,anchorThreshold:e.anchorThreshold,splitRatio:e.splitRatio}),n=M();return{quickWins:r.quickWins.map(o=>NL(o,n)),biggerBets:r.biggerBets.map(o=>NL(o,n)),anchorRepos:r.anchorRepos,message:r.message}}var MK,FK,UL=A(()=>{"use strict";Ja();ue();Pl();ae();MK="features",FK=100});var jL={};re(jL,{runVet:()=>UK});async function UK(e){Ke(e.issueUrl),Qe(e.issueUrl,nr,"issue");let r=await(await As()).vetIssue(e.issueUrl),n=$s({repo:r.issue.repo,projectHealth:r.projectHealth,getRepoScore:d=>M().getRepoScore(d)}),s=M().getState().config.githubUsername,o=bs({linkedPR:jo(r.vettingResult.linkedPR),userLogin:s}),i=Es(r.vettingResult.linkedPR),a={issue:{repo:r.issue.repo,number:r.issue.number,title:r.issue.title,url:r.issue.url,labels:r.issue.labels},recommendation:Ts(r.recommendation,n),reasonsToApprove:r.reasonsToApprove,reasonsToSkip:r.reasonsToSkip,...r.complexityUnlocked&&{complexityUnlocked:!0},projectHealth:r.projectHealth,vettingResult:r.vettingResult,antiLLMPolicy:r.antiLLMPolicy,linkedPRClassification:o,...i&&{linkedPR:i},slmTriage:r.slmTriage??null,grade:n,...Wf(M().getState(),r.issue.repo)},c=Hi(M().getState().workClaims??[],e.issueUrl);if(c)return{...a,...c,reasonsToSkip:[...a.reasonsToSkip,...c.reasonsToSkip]};let u=await jK(a);return{...a,...await Ea(M(),u?[u]:[])}}async function jK(e){if(e.linkedPRClassification?.startsWith("user_"))return;let{repo:t,number:r,url:n}=e.issue,[s,o]=t.split("/",2),i;try{i=await vo(we(ke()),{repo:o,owner:s,number:r})}catch(a){k("vet",`Could not verify ${n} for pick traits: ${I(a)}`)}if(!(i&&va.has(i.verdict)))return ka(e,"vet",{...i&&Ca(i),firstInRepo:Pa(t,M().getRepoScore(t),M().getState().mergedPRs)})}var zL=A(()=>{"use strict";Ja();xt();Pl();Na();ue()});var BL={};re(BL,{runVerifyIssue:()=>zK});async function zK(e){Ke(e.issueUrl),Qe(e.issueUrl,nr,"issue");let t=q(e.issueUrl);if(!t||t.type!=="issues")throw new j(`Not a parseable GitHub issue URL: ${e.issueUrl}`);let r=we(ke());return vo(r,{owner:t.owner,repo:t.repo,number:t.number})}var HL=A(()=>{"use strict";ue();ee();xt()});var ZL={};re(ZL,{classifyListStatus:()=>VL,extractSkipReason:()=>WL,listStatusFromVerdict:()=>qL,runVetList:()=>qK});function HK(e,t){switch(e){case"issue_closed":return"closed";case"claimed":return"claimed";case"has_linked_pr":return t.linkedPR?.state==="open"&&t.linkedPR.isStalled?"has_stalled_pr":"has_pr";case"score_too_low":case"anti_llm_policy":case"other":return null}}function WL(e){if(typeof e!="object"||e===null)return;let t=e.skipReason;if(typeof t=="string")return BK.has(t)?t:void 0}function VL(e,t){if(t){let r=HK(t,e);if(r)return r}else{let r=e.reasonsToSkip.map(n=>n.toLowerCase());if(r.some(n=>n.includes("closed")))return"closed";if(r.some(n=>n.includes("claimed")||n.includes("assigned")))return"claimed";if(r.some(n=>n.includes("existing pr")||n.includes("linked pr")||n.includes("pull request")))return e.linkedPR?.state==="open"&&e.linkedPR.isStalled?"has_stalled_pr":"has_pr"}return e.recommendation==="approve"||e.recommendation==="needs_review","still_available"}function qL(e){switch(e){case"closed":return"closed";case"own-open-pr":return"own_open_pr";case"taken":return"claimed";case"at-risk":return"at_risk";case"available":return"still_available"}}function WK(e){return{verdict:e.verdict,verdictReason:e.verdictReason,state:e.state,stateReason:e.stateReason,assignees:e.assignees,linkedPRs:e.linkedPRs}}function VK(e){return{issue:{repo:`${e.owner}/${e.repo}`,number:e.number,title:e.title,url:e.url,labels:[]},recommendation:"skip",reasonsToApprove:[],reasonsToSkip:[e.verdictReason],projectHealth:{},vettingResult:{},grade:lC}}function uC(e){return e instanceof Error?e.message:String(e)}async function qK(e={}){let t=e.concurrency??5,r=e.issueListPath;if(!r){let w=xo();if(!w)throw new Error("No issue list found. Provide a path with --path or configure issueListPath in settings.");r=w.path}let n=await Nv({filePath:r}),s=[...n.available,...n.blocked];if(s.length===0)return{results:[],summary:{total:0,stillAvailable:0,claimed:0,closed:0,hasPR:0,hasStalledPR:0,atRisk:0,ownOpenPr:0,errors:0}};let o=we(ke()),i=[];s.forEach((w,P)=>{let C=q(w.url);C&&C.type==="issues"&&i.push({index:P,params:{owner:C.owner,repo:C.repo,number:C.number}})});let a=await of(o,i.map(w=>w.params),{concurrency:t}),c=new Map;i.forEach((w,P)=>c.set(w.index,a[P]));let u=await As(),d=[];async function p(w,P){let C=await u.vetIssue(w.url),E=$s({repo:C.issue.repo,projectHealth:C.projectHealth,getRepoScore:Se=>M().getRepoScore(Se)}),T=M().getState().config.githubUsername,L=bs({linkedPR:jo(C.vettingResult.linkedPR),userLogin:T}),G=Es(C.vettingResult.linkedPR),Y={issue:{repo:C.issue.repo,number:C.issue.number,title:C.issue.title,url:C.issue.url,labels:C.issue.labels},recommendation:Ts(C.recommendation,E),reasonsToApprove:C.reasonsToApprove,reasonsToSkip:C.reasonsToSkip,...C.complexityUnlocked&&{complexityUnlocked:!0},projectHealth:C.projectHealth,vettingResult:C.vettingResult,antiLLMPolicy:C.antiLLMPolicy,linkedPRClassification:L,...G&&{linkedPR:G},slmTriage:C.slmTriage??null,grade:E,...Wf(M().getState(),C.issue.repo)};if(P){let Se=ka(Y,"vet-list",{...Ca(P),firstInRepo:Pa(C.issue.repo,M().getRepoScore(C.issue.repo),M().getState().mergedPRs)});Se&&d.push(Se)}return{vetResult:Y,skipReason:WL(C)}}function m(w,P){let C=uC(P);return{issue:{repo:w.repo,number:w.number,title:w.title,url:w.url,labels:[]},recommendation:"skip",reasonsToApprove:[],reasonsToSkip:[`Error: ${C}`],projectHealth:{},vettingResult:{},grade:lC,listStatus:"error",errorMessage:C}}async function f(w,P){let C=Hi(M().getState().workClaims??[],w.url);if(C)return{issue:{repo:w.repo,number:w.number,title:w.title,url:w.url,labels:[]},recommendation:"skip",reasonsToApprove:[],reasonsToSkip:C.reasonsToSkip,projectHealth:{},vettingResult:{},grade:lC,listStatus:"claimed",workClaim:C.workClaim};if(!P||P.verification===void 0){let G=P?.error;if(G instanceof j)return{...m(w,G),verifyError:uC(G)};let Y={verifyError:G===void 0?`not verified: ${w.url} is not a verifiable issue URL`:uC(G)};try{let{vetResult:Se,skipReason:me}=await p(w);return{...Se,listStatus:VL(Se,me),...Y}}catch(Se){return{...m(w,Se),...Y}}}let E=P.verification,T=WK(E),L=qL(E.verdict);if(va.has(E.verdict))return{...VK(E),listStatus:L,verification:T};try{let{vetResult:G}=await p(w,E);return{...G,listStatus:L,verification:T}}catch(G){return{...m(w,G),verification:T}}}let g=new Array(s.length),y=0;async function b(){for(;y<s.length;){let w=y++;g[w]=await f(s[w],c.get(w))}}let R=Array.from({length:Math.min(t,s.length)},()=>b());await Promise.all(R);let h=await Ea(M(),d),_={total:g.length,stillAvailable:g.filter(w=>w.listStatus==="still_available").length,claimed:g.filter(w=>w.listStatus==="claimed").length,closed:g.filter(w=>w.listStatus==="closed").length,hasPR:g.filter(w=>w.listStatus==="has_pr").length,hasStalledPR:g.filter(w=>w.listStatus==="has_stalled_pr").length,atRisk:g.filter(w=>w.listStatus==="at_risk").length,ownOpenPr:g.filter(w=>w.listStatus==="own_open_pr").length,errors:g.filter(w=>w.listStatus==="error").length},S;if(e.prune&&r)try{let w=Tg.readFileSync(r,"utf8"),{pruned:P,removedCount:C}=Fv(w);P!==w&&Tg.writeFileSync(r,P,"utf8"),S={removedCount:C}}catch(w){let P=w instanceof Error?w.message:String(w);console.error(`Warning: Failed to prune ${r}: ${P}`),S={removedCount:0,error:P}}return{results:g,summary:_,pruneResult:S,...h}}var Tg,lC,BK,KL=A(()=>{"use strict";Tg=B(require("node:fs"),1);Ja();Io();ul();Pl();Na();ee();ue();lC=aC({avgResponseDays:null,mergeRate:null,daysSinceLastCommit:null}),BK=new Set(["issue_closed","has_linked_pr","claimed","score_too_low","anti_llm_policy","other"])});var rM={};re(rM,{runLedgerBackfill:()=>i6});function QL(e){let t=(e.firstComments?.nodes??[]).filter(n=>n!==null).map(n=>({user:YL(n.author),author_association:n.authorAssociation,created_at:n.createdAt})),r=(e.reviews?.nodes??[]).filter(n=>n!==null).map(n=>({user:YL(n.author),submitted_at:n.submittedAt}));return e.author?.login?xm(t,r,e.author.login):void 0}async function XK(e,t,r){return(await e.graphql(YK,{o:t.owner,r:t.repo,n:t.number,c:r.firstComments?.pageInfo?.endCursor??null,rc:r.reviews?.pageInfo?.endCursor??null})).repository?.pullRequest}async function e6(e,t,r,n){let s=q(t),o=QL(r);for(let i=1;!o&&s&&i<KK&&QK(r);i++){let a;try{a=await XK(e,s,r)}catch(c){if(le(c)||fa(c))throw c;return n.push(`response lookup for ${t} failed: ${I(c)}`),{isPending:!0}}if(!a)return{isPending:!0};r.firstComments=a.firstComments,r.reviews=a.reviews,o=QL(r)}return{at:o,isPending:!1}}async function t6(e,t,r,n){if(t)for(let[s,o]of t){let{at:i,isPending:a}=await e6(e,s,o,n);a||r.set(s,i)}}function r6(e){let t=0;for(let r of e.values())r&&t++;return t}async function n6(e,t,r){let n=[],s=[],o={};if(t.forEach((u,d)=>{let p=q(u);p&&(n.push(`$o${d}: String!, $r${d}: String!, $n${d}: Int!`),Object.assign(o,{[`o${d}`]:p.owner,[`r${d}`]:p.repo,[`n${d}`]:p.number}),s.push(`p${d}: repository(owner: $o${d}, name: $r${d}) { pullRequest(number: $n${d}) {${JK}} }`))}),s.length===0)return new Map;let i=`query ledgerBackfill(${n.join(", ")}) {
347
+ `)}catch(r){z(lt,`Failed to write cache: ${K(r)}`)}}},nK=2160*60*60*1e3});function dK(e){let t="Changes will only be saved locally.";switch(e){case"rate_limit":return`Gist sync unavailable \u2014 GitHub API rate limit exceeded. ${t} Try again after the rate limit resets.`;case"network":return`Gist sync unavailable \u2014 could not reach GitHub. ${t} Check your network connection.`;case"server":return`Gist sync unavailable \u2014 GitHub returned a server error. ${t} Try again later.`;case"unknown":case void 0:return`Gist sync unavailable \u2014 running in offline mode. ${t}`}}function pK(e){return{gists:{async get(t){let{data:r}=await e.gists.get(t);if(!r.id)throw new Error("Gist get returned no id");let n=r.files?Object.fromEntries(Object.entries(r.files).map(([s,o])=>[s,o?{content:o.content}:void 0])):null;return{data:{id:r.id,files:n}}},async create(t){let{data:r}=await e.gists.create(t);if(!r.id)throw new Error("Gist create returned no id");return{data:{id:r.id}}},async update(t){let{data:r}=await e.gists.update(t);if(!r.id)throw new Error("Gist update returned no id");return{data:{id:r.id}}},async list(t){let{data:r}=await e.gists.list(t);return{data:r.filter(n=>n.id).map(n=>({id:n.id,description:n.description??null}))}}}}}async function Cg(e){e.logLevel!==void 0&&qf(e.logLevel);let t,r=null,n=!1;if(e.persistence==="provided")t=e.initialState;else if(e.persistence==="gist"){r=new kg(pK(Mn(e.githubToken)));let s=await r.bootstrap();s.degraded&&z("scout",dK(s.degradedReason));let o=Sg();t=Sl(o,s.state),e.gistId?t.gistId=e.gistId:s.gistId&&(t.gistId=s.gistId)}else t=Sg(),n=!0;return new _l(e.githubToken,t,r,{persistLocal:n})}var lK,_l,yL=A(()=>{Uk();ug();Jk();No();hL();eg();Yk();it();At();ct();an();lK=/Linked PR already merged|Linked PR closed without merge|Has existing PR/;_l=class{githubToken;gistStore;state;dirty=!1;persistLocal;constructor(t,r,n=null,s={}){this.githubToken=t,this.gistStore=n,this.state=r,this.persistLocal=s.persistLocal??!1}evictStaleCacheEntries(){et().evictStale()}async search(t){this.evictStaleCacheEntries(),this.cullExpiredSkips();let r=new Set(this.getComplexIssuesMode()==="warm"?this.getReposWithMergedPRs().map(h=>h.toLowerCase()):[]),n=new Set((this.state.skippedIssues??[]).filter(h=>!(r.has(h.repo.toLowerCase())&&lK.test(h.reason??""))).map(h=>h.url));if(t?.excludeRecentlySurfaced??!0){let h=t?.recentlySurfacedTtlDays??7,_=Date.now()-h*24*60*60*1e3;for(let S of this.state.savedResults??[]){let w=Date.parse(S.lastSeenAt);!Number.isNaN(w)&&w>=_&&n.add(S.issueUrl)}}let s=new Go(this.githubToken,this.state.preferences,this),o=this.state.preferences,i=o.preferLanguages??[],a=o.preferRepos??[],c=t?.preferLanguages??(i.length>0?i:void 0),u=t?.preferRepos??(a.length>0?a:void 0),d=o.avoidRepos??[],p=o.boostIssueTypes??[],m=t?.avoidRepos??(d.length>0?d:void 0),f=t?.boostIssueTypes??(p.length>0?p:void 0),g=t?.diversityRatio??o.diversityRatio??0,y=this.state.searchRotation??{languageOffset:0},b,R;try{({candidates:b,strategiesUsed:R}=await s.searchIssues({maxResults:t?.maxResults,strategies:t?.strategies,skippedUrls:n,preferLanguages:c,preferRepos:u,avoidRepos:m,boostIssueTypes:f,diversityRatio:g,interPhaseDelayMs:t?.interPhaseDelayMs,broadPhaseDelayMs:t?.broadPhaseDelayMs,languageRotationOffset:y.languageOffset,repoRotationOffsets:{merged:y.phase0Offset??0,starred:y.starredOffset??0,maintained:y.maintainedOffset??0},strategyRotationOffset:t?.full?void 0:y.strategyOffset??0}))}catch(h){throw h instanceof at&&this.advanceRotation(y,h.strategiesUsed??[],t?.full),h}this.advanceRotation(y,R,t?.full);for(let h of b)this.updateRepoSignalsFromHealth(h.projectHealth);return this.state.lastSearchAt=new Date().toISOString(),this.dirty=!0,{candidates:b,excludedRepos:this.state.preferences.excludeRepos,aiPolicyBlocklist:this.state.preferences.aiPolicyBlocklist,rateLimitWarning:s.rateLimitWarning??void 0,strategiesUsed:R}}advanceRotation(t,r,n=!1){let s=o=>r.includes(o)?1:0;r.length!==0&&(this.state.searchRotation={...t,languageOffset:t.languageOffset+s("broad"),phase0Offset:(t.phase0Offset??0)+s("merged"),starredOffset:(t.starredOffset??0)+s("starred"),maintainedOffset:(t.maintainedOffset??0)+s("maintained"),strategyOffset:n?t.strategyOffset:Fo.indexOf(r[0])+1,lastRotatedAt:new Date().toISOString()},this.dirty=!0)}updateRepoSignalsFromHealth(t){t.checkFailed||this.updateRepoScore(t.repo,{signals:{hasActiveMaintainers:t.isActive}})}async vetIssue(t){return new Go(this.githubToken,this.state.preferences,this).vetIssue(t)}async features(t){this.evictStaleCacheEntries();let r=t?.count??10,n=Mn(this.githubToken),s=new Ps(n,this),o=t?.broad?await aL({octokit:n,vetter:s,count:r,languages:this.state.preferences.languages,excludeRepos:this.state.preferences.excludeRepos,excludeOrgs:this.state.preferences.excludeOrgs,aiPolicyBlocklist:this.state.preferences.aiPolicyBlocklist,minStars:this.state.preferences.minStars,splitRatio:t?.splitRatio??this.state.preferences.featuresSplitRatio}):await wg({octokit:n,vetter:s,repoScores:this.state.repoScores??{},count:r,excludeRepos:this.state.preferences.excludeRepos,excludeOrgs:this.state.preferences.excludeOrgs,aiPolicyBlocklist:this.state.preferences.aiPolicyBlocklist,minStars:this.state.preferences.minStars,anchorThreshold:t?.anchorThreshold??this.state.preferences.featuresAnchorThreshold,splitRatio:t?.splitRatio??this.state.preferences.featuresSplitRatio});return this.saveResults([...o.quickWins,...o.biggerBets]),this.state.lastSearchAt=new Date().toISOString(),this.dirty=!0,o}async vetList(t){this.evictStaleCacheEntries();let r=this.getSavedResults(),n=t?.concurrency??5,s=[],o=new Map,i=null;for(let m of r){if(i)break;let f=this.vetIssue(m.issueUrl).then(g=>{s.push({issueUrl:m.issueUrl,repo:m.repo,number:m.number,title:m.title,status:this.classifyVetResult(g),ok:!0,recommendation:g.recommendation,viabilityScore:g.viabilityScore})}).catch(g=>{if($e(g)===401||Je(g)){i??=g;return}let y=$e(g),b=y===404||y===410;s.push({issueUrl:m.issueUrl,repo:m.repo,number:m.number,title:m.title,status:b?"closed":"error",ok:!1,errorMessage:K(g)})}).finally(()=>{o.delete(m.issueUrl)});o.set(m.issueUrl,f),o.size>=n&&await Promise.race(o.values())}if(await Promise.allSettled(o.values()),i)throw s.length>0&&z("scout",`vetList aborted mid-batch after ${s.length} result(s) \u2014 discarding partial results due to auth/rate-limit failure`),i;let a={total:s.length,stillAvailable:s.filter(m=>m.status==="still_available").length,claimed:s.filter(m=>m.status==="claimed").length,closed:s.filter(m=>m.status==="closed").length,hasPR:s.filter(m=>m.status==="has_pr").length,errors:s.filter(m=>m.status==="error").length},c=new Map((this.state.savedResults??[]).map(m=>[m.issueUrl,m.lastStatus])),u=s.filter(m=>m.status!=="error").filter(m=>{let f=c.get(m.issueUrl);return f!==void 0&&f!==m.status}).map(m=>({issueUrl:m.issueUrl,repo:m.repo,number:m.number,from:c.get(m.issueUrl),to:m.status})),d=new Map(s.map(m=>[m.issueUrl,m.status]));for(let m of this.state.savedResults??[]){let f=d.get(m.issueUrl);f!==void 0&&f!=="error"&&(m.lastStatus=f)}s.length>0&&(this.dirty=!0);let p;if(t?.prune){let m=new Set(s.filter(g=>g.status!=="still_available").map(g=>g.issueUrl)),f=(this.state.savedResults??[]).length;this.state.savedResults=(this.state.savedResults??[]).filter(g=>!m.has(g.issueUrl)),p=f-(this.state.savedResults?.length??0),p>0&&this.addTombstones([...m]),this.dirty=!0}return{results:s,summary:a,prunedCount:p,transitions:u}}classifyVetResult(t){if(t.issueState==="closed")return"closed";let r=t.vettingResult.checks;return r.noExistingPR?r.notClaimed?"still_available":"claimed":"has_pr"}getReposWithMergedPRs(){let t=new Map;for(let r of this.state.mergedPRs??[]){let n=ut(r.url);n&&t.set(n,(t.get(n)??0)+1)}return[...t.entries()].sort((r,n)=>n[1]-r[1]).map(([r])=>r)}getReposWithOpenPRs(){let t=new Map;for(let r of this.state.openPRs??[]){let n=ut(r.url);n&&t.set(n,(t.get(n)??0)+1)}return[...t.entries()].sort((r,n)=>n[1]-r[1]).map(([r])=>r)}getStarredRepos(){return this.state.starredRepos}getProjectCategories(){return this.state.preferences.projectCategories}getGitHubUsername(){return this.state.preferences.githubUsername}getRepoScore(t){let r=this.state.repoScores[t];return r?r.score:null}getClosedWithoutMergeCount(t){let r=this.state.repoScores[t];return r?r.closedWithoutMergeCount:(this.state.closedPRs??[]).filter(n=>ut(n.url)===t).length}getSLMTriageConfig(){let t=this.state.preferences.slmTriageModel??"";return t?{model:t,host:this.state.preferences.slmTriageHost??""}:null}getComplexIssuesMode(){return this.state.preferences.complexIssues??"off"}getPreferences(){return this.state.preferences}getRepoScoreRecord(t){return this.state.repoScores[t]}recordMergedPR(t){let r=this.state.mergedPRs??[];r.some(n=>n.url===t.url)||(this.state.mergedPRs=[...r,{url:t.url,title:t.title,mergedAt:t.mergedAt}],this.updateRepoScoreFromPRs(t.repo),this.dirty=!0)}recordClosedPR(t){let r=this.state.closedPRs??[];r.some(n=>n.url===t.url)||(this.state.closedPRs=[...r,{url:t.url,title:t.title,closedAt:t.closedAt}],this.updateRepoScoreFromPRs(t.repo),this.dirty=!0)}recordOpenPR(t){let r=this.state.openPRs??[];r.some(n=>n.url===t.url)||(this.state.openPRs=[...r,{url:t.url,title:t.title,openedAt:t.openedAt}],this.dirty=!0)}async syncOpenPRs(){let t=Mn(this.githubToken),r=this.state.openPRs??[],n={checked:r.length,merged:0,closed:0,stillOpen:0,errors:0},s=[];for(let o of r){let i=Do(o.url);if(!i||i.type!=="pull"){s.push(o),n.errors++;continue}let a=`${i.owner}/${i.repo}`;try{let{data:c}=await t.pulls.get({owner:i.owner,repo:i.repo,pull_number:i.number});c.merged?(this.recordMergedPR({url:o.url,title:o.title,mergedAt:c.merged_at??new Date().toISOString(),repo:a}),n.merged++):c.state==="closed"?(this.recordClosedPR({url:o.url,title:o.title,closedAt:c.closed_at??new Date().toISOString(),repo:a}),n.closed++):(s.push(o),n.stillOpen++)}catch(c){He(c),z("scout",`sync: could not check ${o.url}: ${K(c)}`),s.push(o),n.errors++}}return this.state.openPRs=s,this.dirty=!0,await this.checkpoint(),n}updateRepoScore(t,r){let s=this.state.repoScores[t]??{repo:t,score:5,mergedPRCount:0,closedWithoutMergeCount:0,avgResponseDays:null,lastEvaluatedAt:new Date().toISOString(),signals:{hasActiveMaintainers:!1,isResponsive:!1,hasHostileComments:!1}},o={...s,...r,repo:t,lastEvaluatedAt:new Date().toISOString(),signals:{...s.signals,...r.signals??{}}};o.score=this.calculateScore(o),this.state.repoScores[t]=o,this.dirty=!0}updatePreferences(t){this.state.preferences={...this.state.preferences,...t},this.state.preferencesUpdatedAt=new Date().toISOString(),this.dirty=!0}setStarredRepos(t){this.state.starredRepos=t,this.state.starredReposLastFetched=new Date().toISOString(),this.dirty=!0}saveResults(t){let r=new Date().toISOString(),n=new Map((this.state.savedResults??[]).map(s=>[s.issueUrl,s]));for(let s of t){if(s.recommendation==="skip"){n.delete(s.issue.url);let i=new Set(["Issue is closed","Linked PR already merged"]),a=s.reasonsToSkip.some(c=>i.has(c));this.skipIssue(s.issue.url,{repo:s.issue.repo,number:s.issue.number,title:s.issue.title,reason:s.reasonsToSkip.join("; ")||"vetter: skip",permanent:a});continue}let o=n.get(s.issue.url);n.set(s.issue.url,{issueUrl:s.issue.url,repo:s.issue.repo,number:s.issue.number,title:s.issue.title,labels:s.issue.labels,recommendation:s.recommendation,viabilityScore:s.viabilityScore,searchPriority:s.searchPriority,firstSeenAt:o?.firstSeenAt??r,lastSeenAt:r,lastScore:s.viabilityScore,horizon:"horizon"in s?s.horizon:void 0})}this.state.savedResults=[...n.values()],this.dirty=!0}getSavedResults(){return this.state.savedResults??[]}clearResults(){this.addTombstones((this.state.savedResults??[]).map(t=>t.issueUrl)),this.state.savedResults=[],this.dirty=!0}addTombstones(t){if(t.length===0)return;let r=new Date().toISOString(),n=this.state.tombstones??[],s=new Map(n.map(o=>[o.url,o]));for(let o of t)s.set(o,{url:o,removedAt:r});this.state.tombstones=[...s.values()]}skipIssue(t,r){let n=this.state.skippedIssues??[],s=n.find(i=>i.url===t);if(s){r?.permanent===!0&&s.permanent!==!0&&(s.permanent=!0,s.skippedAt=new Date().toISOString(),this.dirty=!0);return}let o=r?.permanent??!0;this.state.skippedIssues=[...n,{url:t,repo:r?.repo??"",number:r?.number??0,title:r?.title??"",skippedAt:new Date().toISOString(),permanent:o,...r?.reason?{reason:r.reason}:{}}],this.state.savedResults&&(this.state.savedResults=this.state.savedResults.filter(i=>i.issueUrl!==t)),this.dirty=!0}getSkippedIssues(){return this.state.skippedIssues??[]}unskipIssue(t){let r=(this.state.skippedIssues??[]).length;this.state.skippedIssues=(this.state.skippedIssues??[]).filter(n=>n.url!==t),this.state.skippedIssues.length<r&&this.addTombstones([t]),this.dirty=!0}clearSkippedIssues(){this.addTombstones((this.state.skippedIssues??[]).map(t=>t.url)),this.state.skippedIssues=[],this.dirty=!0}cullExpiredSkips(t=90){let r=new Date;r.setDate(r.getDate()-t);let n=[];return this.state.skippedIssues=(this.state.skippedIssues??[]).filter(s=>{if(s.permanent!==!1)return!0;let o=new Date(s.skippedAt);return isNaN(o.getTime())||o>=r?!0:(n.push(s.url),!1)}),n.length>0&&(this.addTombstones(n),this.dirty=!0),n.length}isDirty(){return this.dirty}async checkpoint(){if(!this.dirty)return!0;if(this.state.lastRunAt=new Date().toISOString(),this.gistStore&&!await this.gistStore.push(this.state))return!1;if(this.persistLocal)try{this.state=Sl(this.state,Sg()),lL(this.state)}catch{return!1}return this.dirty=!1,!0}getState(){return this.state}updateRepoScoreFromPRs(t){let r=(this.state.mergedPRs??[]).filter(s=>ut(s.url)===t).length,n=(this.state.closedPRs??[]).filter(s=>ut(s.url)===t).length;this.updateRepoScore(t,{mergedPRCount:r,closedWithoutMergeCount:n,lastMergedAt:r>0?(this.state.mergedPRs??[]).filter(s=>ut(s.url)===t).sort((s,o)=>o.mergedAt.localeCompare(s.mergedAt))[0]?.mergedAt:void 0})}calculateScore(t){let r=5;return r+=Math.min(t.mergedPRCount,3),r-=Math.min(t.closedWithoutMergeCount,3),t.signals.hasActiveMaintainers&&(r+=1),t.signals.hasHostileComments&&(r-=2),Math.max(1,Math.min(10,r))}}});function bL(){let e=kl.filter(r=>!(r in vl));if(e.length>0)throw new Error(`FIELD_CONFIGS is missing entries for preference keys: ${e.join(", ")}`);let t=Object.keys(vl).filter(r=>!kl.includes(r));if(t.length>0)throw new Error(`FIELD_CONFIGS has entries for unknown preference keys: ${t.join(", ")}`)}function mK(e){let t=e.toLowerCase();if(t==="true"||t==="yes")return!0;if(t==="false"||t==="no")return!1;throw new at(`Invalid boolean value: "${e}". Use true/false or yes/no.`)}function fK(e,t){let r=parseInt(e,10);if(isNaN(r))throw new at(`Invalid number for "${t}": "${e}"`);return r}function gK(e,t){let r=Number.parseFloat(e);if(isNaN(r))throw new at(`Invalid number for "${t}": "${e}"`);return r}function rC(e){return e.split(",").map(t=>t.trim()).filter(t=>t.length>0)}function Pg(e,t){if(t.startsWith("+")){let r=rC(t.slice(1)),n=[...e];for(let s of r)n.includes(s)||n.push(s);return n}if(t.startsWith("-")){let r=new Set(rC(t.slice(1)));return e.filter(n=>!r.has(n))}return rC(t)}function wL(e,t,r){let n=vl[t];if(!n)throw new at(`Unknown config key: "${t}". Valid keys: ${nC.join(", ")}`);let s={...e};switch(n.type){case"string":t==="slmTriageHost"&&$D(r),s[t]=r;break;case"boolean":s[t]=mK(r);break;case"number":s[t]=fK(r,t);break;case"float":s[t]=gK(r,t);break;case"array":{let o=s[t]??[];s[t]=Pg(o,r);break}case"enum":{let o=n.validValues;if(!o.includes(r))throw new at(`Invalid value for "${t}": "${r}". Valid: ${o.join(", ")}`);s[t]=r;break}case"enum-array":{let o=s[t]??[],i=Pg(o,r),a=n.validValues,c=i.filter(u=>!a.includes(u));if(c.length>0)throw new at(`Invalid value(s) for "${t}": ${c.join(", ")}. Valid: ${a.join(", ")}`);t==="scope"?s[t]=i.length>0?i:void 0:s[t]=i;break}}return Lo.parse(s)}var vl,kl,nC,RL=A(()=>{No();ct();Lk();vl={githubUsername:{type:"string"},languages:{type:"array"},labels:{type:"array"},scope:{type:"enum-array",validValues:gl.options},excludeRepos:{type:"array"},excludeOrgs:{type:"array"},preferredOrgs:{type:"array"},aiPolicyBlocklist:{type:"array"},projectCategories:{type:"enum-array",validValues:fl.options},minStars:{type:"number"},maxIssueAgeDays:{type:"number"},includeDocIssues:{type:"boolean"},minRepoScoreThreshold:{type:"number"},interPhaseDelayMs:{type:"number"},persistence:{type:"enum",validValues:wk.options},defaultStrategy:{type:"enum-array",validValues:Mo.options},broadPhaseDelayMs:{type:"number"},skipBroadWhenSufficientResults:{type:"number"},preferLanguages:{type:"array"},preferRepos:{type:"array"},diversityRatio:{type:"float"},avoidRepos:{type:"array"},boostIssueTypes:{type:"array"},slmTriageModel:{type:"string"},slmTriageHost:{type:"string"},complexIssues:{type:"enum",validValues:Rk.options},featuresAnchorThreshold:{type:"number"},featuresSplitRatio:{type:"float"}},kl=Object.keys(Lo.shape),nC=[...kl].sort()});async function SL(e,t,r=fr()){let n=e.getPreferences().githubUsername;if(!n)throw new Ga("GitHub username not configured. Run `oss-scout setup` first.");let s=await Xf(t);if(se(cn,`Rate limit: ${s.remaining}/${s.limit}, resets at ${s.resetAt}`),s.remaining<15)return se(cn,"Insufficient rate limit, skipping bootstrap"),{starredRepoCount:0,mergedPRCount:0,closedPRCount:0,openPRCount:0,reposScoredCount:0,skippedDueToRateLimit:!0,errors:[]};r.init(s.remaining,s.resetAt);let o=Mn(t),i=[],a=[],c=0,u=new Set;try{let f=0;for await(let g of o.paginate.iterator(o.activity.listReposStarredByAuthenticatedUser,{per_page:Uo,headers:{accept:"application/vnd.github.v3+json"}})){for(let y of g.data){let b=y;a.push(b.full_name)}if(f++,f>=hK)break}se(cn,`Fetched ${a.length} starred repos`),e.setStarredRepos(a),c=a.length}catch(f){He(f),z(cn,`Failed to fetch starred repos: ${K(f)}`),i.push("starred repos fetch failed")}let d=0;try{for(let f=1;f<=sC;f++){await r.waitForBudget();let g;try{g=(await o.search.issuesAndPullRequests({q:`is:pr is:merged author:${n}`,per_page:Uo,page:f})).data}finally{r.recordCall()}for(let y of g.items){let b=ut(y.html_url);b&&(e.recordMergedPR({url:y.html_url,title:y.title,mergedAt:y.closed_at??new Date().toISOString(),repo:b}),u.add(b),d++)}if(g.items.length<Uo)break}se(cn,`Imported ${d} merged PRs`)}catch(f){He(f),z(cn,`Failed to fetch merged PRs: ${K(f)}`),i.push("merged PR fetch failed")}let p=0;try{for(let f=1;f<=sC;f++){await r.waitForBudget();let g;try{g=(await o.search.issuesAndPullRequests({q:`is:pr is:closed is:unmerged author:${n}`,per_page:Uo,page:f})).data}finally{r.recordCall()}for(let y of g.items){let b=ut(y.html_url);b&&(e.recordClosedPR({url:y.html_url,title:y.title,closedAt:y.closed_at??new Date().toISOString(),repo:b}),u.add(b),p++)}if(g.items.length<Uo)break}se(cn,`Imported ${p} closed PRs`)}catch(f){He(f),z(cn,`Failed to fetch closed PRs: ${K(f)}`),i.push("closed PR fetch failed")}let m=0;try{for(let f=1;f<=sC;f++){await r.waitForBudget();let g;try{g=(await o.search.issuesAndPullRequests({q:`is:pr is:open author:${n}`,per_page:Uo,page:f})).data}finally{r.recordCall()}for(let y of g.items){let b=ut(y.html_url);b&&(e.recordOpenPR({url:y.html_url,title:y.title,openedAt:y.created_at??new Date().toISOString(),repo:b}),m++)}if(g.items.length<Uo)break}se(cn,`Imported ${m} open PRs`)}catch(f){He(f),z(cn,`Failed to fetch open PRs: ${K(f)}`),i.push("open PR fetch failed")}return{starredRepoCount:c,mergedPRCount:d,closedPRCount:p,openPRCount:m,reposScoredCount:u.size,skippedDueToRateLimit:!1,errors:i}}var cn,hK,sC,Uo,_L=A(()=>{eg();it();ct();At();za();cn="bootstrap",hK=5,sC=3,Uo=100});function CL(e,t,r){if(!t.test(e))throw new at(`Invalid ${r} URL: ${e}. Expected format: https://github.com/owner/repo/issues/123`)}function PL(e){if(e.length>vL)throw new at(`URL exceeds maximum length of ${vL} characters`);return e}var kL,vL,EL=A(()=>{ct();kL=/^https:\/\/github\.com\/[^/]+\/[^/]+\/issues\/\d+$/,vL=2048});var AL={};re(AL,{ANCHOR_THRESHOLD:()=>Wk,ANTI_LLM_KEYWORDS:()=>Tk,FEATURE_LABELS:()=>bg,FIELD_CONFIGS:()=>vl,HorizonSchema:()=>bk,ISSUE_URL_PATTERN:()=>kL,IssueDiscovery:()=>Go,IssueScopeSchema:()=>gl,IssueVetter:()=>Ps,NO_ANCHORS_MESSAGE:()=>Zk,NO_RESULTS_MESSAGE:()=>Kk,OssScout:()=>_l,PREFERENCE_KEYS:()=>kl,ProjectCategorySchema:()=>fl,RepoScoreSchema:()=>hk,SORTED_PREFERENCE_KEYS:()=>nC,STALLED_PR_THRESHOLD_DAYS:()=>lD,ScoutPreferencesSchema:()=>Lo,ScoutStateSchema:()=>Fn,SearchStrategySchema:()=>Mo,SkippedIssueSchema:()=>yk,applyPreferenceField:()=>wL,assertFieldConfigsCover:()=>bL,bootstrapScout:()=>SL,classifyHorizon:()=>qk,createScout:()=>Cg,discoverFeatures:()=>wg,enableDebug:()=>j0,fetchRoadmapIssueRefs:()=>hg,getGitHubToken:()=>uk,getLogLevel:()=>U0,isLinkedPRStalled:()=>og,parseRoadmapIssueRefs:()=>zk,requireGitHubToken:()=>Z0,resolveAnchorRepos:()=>Vk,scanForAntiLLMPolicy:()=>$k,setLogLevel:()=>qf,splitByHorizon:()=>yg,updateArray:()=>Pg,validateGitHubUrl:()=>CL,validateUrl:()=>PL});var Eg=A(()=>{yL();No();RL();At();Uk();ug();Ok();_L();it();Jk();kk();Bk();EL()});function wK(e){let t=[],r=e.split(/\r?\n/);for(let n=0;n<r.length;n++){let s=n+1,o=r[n].trim();if(o===""||o.startsWith("#"))continue;let i=o.match(/^(\S+)\s+(\S+)(?:\s+#.*)?$/);if(!i){k("skip-file-parser",`Line ${s}: malformed (expected "<date> <url>"): ${o}`);continue}let[,a,c]=i;if(!yK.test(a)){k("skip-file-parser",`Line ${s}: invalid date format (expected YYYY-MM-DD): ${o}`);continue}let u=Date.parse(`${a}T00:00:00.000Z`);if(Number.isNaN(u)){k("skip-file-parser",`Line ${s}: unparseable date: ${o}`);continue}let d=new Date(u).toISOString().slice(0,10);if(d!==a){k("skip-file-parser",`Line ${s}: invalid calendar date ${a} (would be normalized to ${d}): ${o}`);continue}let p=c.match(bK);if(!p){k("skip-file-parser",`Line ${s}: non-GitHub-issue URL: ${o}`);continue}let[,m,f]=p,g=Number.parseInt(f,10);t.push({url:c,repo:m,number:g,title:"",skippedAt:new Date(u).toISOString(),permanent:!0})}return t}function oC(e){if(!e)return{issues:[]};let t=TL.resolve(e);if(!Ag.existsSync(t))return k("skip-file-parser",`Configured skipped-issues file not found at ${t} (cwd ${process.cwd()}); proceeding with an EMPTY skip list \u2014 previously skipped issues may resurface. Use an absolute skippedIssuesPath, or run from the directory that contains "${e}".`),{issues:[],notFound:!0,resolvedPath:t};let r;try{r=Ag.readFileSync(t,"utf8")}catch(n){return k("skip-file-parser",`Failed to read skipped-issues file at ${t}: ${I(n)}`),{issues:[],readError:I(n),resolvedPath:t}}return{issues:wK(r),resolvedPath:t}}function $L(e){return oC(e).issues}var Ag,TL,yK,bK,iC=A(()=>{"use strict";Ag=B(require("node:fs"),1),TL=B(require("node:path"),1);ae();ee();yK=/^\d{4}-\d{2}-\d{2}$/,bK=/^https:\/\/github\.com\/([^/]+\/[^/]+)\/(?:issues|pull)\/(\d+)(?:[#/?].*)?$/});function jo(e){if(!e)return null;let t={author:{login:e.author},state:e.merged?"merged":e.state};return e.updatedAt!==void 0&&(t.updatedAt=e.updatedAt),t}function Es(e){if(!e)return;let t=jo(e);if(!t)return;let r={number:e.number,state:t.state,url:e.url,isStalled:sf(t)};return e.updatedAt!==void 0&&(r.updatedAt=e.updatedAt),r}function RK(e,t=[]){let r=M().getState(),{config:n}=r,s=oC(n.skippedIssuesPath);(s.readError!==void 0||s.notFound)&&e&&(e.skipListUnavailable=!0);let o=[...s.issues],i=new Set(o.map(m=>m.url));for(let[m,f]of Object.entries(n.dismissedIssues??{})){if(i.has(m)||!nr.test(m))continue;let g=q(m);i.add(m),o.push({url:m,repo:g?`${g.owner}/${g.repo}`:"",number:g?.number??0,title:"",skippedAt:f,reason:"dismissed",permanent:!0})}let a=lr(r.workClaims??[]);for(let m of a){if(m.kind!=="implementation"||i.has(m.url)||!nr.test(m.url))continue;let f=q(m.url);i.add(m.url),o.push({url:m.url,repo:f?`${f.owner}/${f.repo}`:"",number:f?.number??0,title:"",skippedAt:m.startedAt,reason:`implementation in progress (session ${m.session})`,permanent:!0})}let c=new Date().toISOString();for(let m of t){if(i.has(m)||!nr.test(m))continue;let f=q(m);i.add(m),o.push({url:m,repo:f?`${f.owner}/${f.repo}`:"",number:f?.number??0,title:"",skippedAt:c,reason:"excluded by caller",permanent:!0})}let u=Rs(r),d=Hf(r),p=new Set(d.map(m=>m.toLowerCase()));return{version:1,stateRevision:1,preferences:{githubUsername:n.githubUsername,languages:n.languages,labels:n.labels,scope:n.scope,excludeRepos:[...n.excludeRepos,...d],excludeOrgs:n.excludeOrgs??[],preferredOrgs:n.preferredOrgs??[],aiPolicyBlocklist:n.aiPolicyBlocklist,projectCategories:n.projectCategories??[],minStars:n.minStars,maxIssueAgeDays:n.maxIssueAgeDays,includeDocIssues:n.includeDocIssues,minRepoScoreThreshold:n.minRepoScoreThreshold,interPhaseDelayMs:0,broadPhaseDelayMs:0,skipBroadWhenSufficientResults:n.skipBroadWhenSufficientResults,complexIssues:n.complexIssues==="warm"?"warm":"off",persistence:n.persistence,slmTriageModel:n.slmTriageModel,slmTriageHost:n.slmTriageHost,featuresAnchorThreshold:3,featuresSplitRatio:.6,preferLanguages:u?.recommendations.languages??[],preferRepos:(u?.recommendations.repos??[]).filter(m=>!p.has(m.toLowerCase())),diversityRatio:Cl,avoidRepos:n.avoidRepos??[],boostIssueTypes:n.boostIssueTypes??[]},repoScores:r.repoScores,tombstones:[],starredRepos:n.starredRepos,starredReposLastFetched:n.starredReposLastFetched,mergedPRs:(r.mergedPRs??[]).map(m=>({url:m.url,title:m.title,mergedAt:m.mergedAt})),closedPRs:(r.closedPRs??[]).map(m=>({url:m.url,title:m.title,closedAt:m.closedAt})),openPRs:(r.lastDigest?.openPRs??[]).map(m=>({url:m.url,title:m.title,openedAt:m.createdAt})),savedResults:(r.searchSeen??[]).map(m=>({issueUrl:m.url,repo:"",number:0,title:"",labels:[],recommendation:"skip",viabilityScore:0,searchPriority:"normal",firstSeenAt:m.lastSeenAt,lastSeenAt:m.lastSeenAt,lastScore:0})),skippedIssues:o,lastRunAt:r.lastRunAt,searchRotation:r.searchRotation??FS.parse({})}}async function As(e,t){let r=ke();return Cg({githubToken:r,persistence:"provided",initialState:RK(e,t)})}var Cl,Ja=A(()=>{"use strict";Na();Eg();ue();wn();tl();iC();xt();Cl=.2});function Ts(e,t){return e==="approve"&&t.score<4?"needs_review":e}function SK(e){return e.reduce((t,r)=>r.score<t.score?r:t)}function _K(e){let t=zo.indexOf(e);return t===-1?zo[zo.length-1]:zo[Math.min(t+1,zo.length-1)]}function Gn(e,t,r){return typeof e!="number"||!Number.isFinite(e)||e<t||e>r?null:e}function vK(e){return e<3?{score:10,detail:`~${Math.round(e)}-day avg response`}:e<14?{score:7,detail:`${Math.round(e)}-day avg response`}:e<=60?{score:4,detail:`${Math.round(e)}-day avg response`}:{score:1,detail:"unresponsive maintainers"}}function kK(e){let t=Math.round(e*100);return e>.7?{score:10,detail:`merges ${t}% of PRs`}:e>=.4?{score:7,detail:`merges ${t}% of PRs`}:e>=.1?{score:4,detail:`merges ${t}% of PRs`}:{score:1,detail:`merges ${t}% of PRs`}}function CK(e){return e<7?{score:10,detail:"commits in last week"}:e<30?{score:7,detail:"commits in last month"}:e<90?{score:4,detail:"commits in last 90 days"}:{score:1,detail:`no commits in ${e}+ days`}}function PK(e){let{projectHealth:t,repoScore:r}=e,n=!t.checkFailed,s=Gn(r?.avgResponseDays,0,Number.MAX_SAFE_INTEGER)??(n?Gn(t.avgIssueResponseDays,.001,Number.MAX_SAFE_INTEGER):null),o=n?Gn(t.daysSinceLastCommit,0,Number.MAX_SAFE_INTEGER):null,i=n?Gn(t.recentMergeRate,0,1):null;if(i===null&&r){let a=Gn(r.mergedPRCount,0,Number.MAX_SAFE_INTEGER),c=Gn(r.closedWithoutMergeCount,0,Number.MAX_SAFE_INTEGER);if(a!==null&&c!==null){let u=a+c;i=u===0?null:a/u}}return{avgResponseDays:s,mergeRate:i,daysSinceLastCommit:o}}function $s(e){let t=e.getRepoScore(e.repo),r=e.projectHealth,n=r.checkFailed?{avgIssueResponseDays:null,daysSinceLastCommit:null,checkFailed:!0}:{avgIssueResponseDays:r.avgIssueResponseDays,daysSinceLastCommit:r.daysSinceLastCommit,recentMergeRate:r.recentMergeRate??null,checkFailed:!1};return aC(PK({projectHealth:n,repoScore:t?{mergedPRCount:t.mergedPRCount,closedWithoutMergeCount:t.closedWithoutMergeCount,avgResponseDays:t.avgResponseDays}:null}))}function aC(e){let t=[],r=[],n=Gn(e.avgResponseDays,0,Number.MAX_SAFE_INTEGER);n===null?r.push("maintainer responsiveness"):t.push(vK(n));let s=Gn(e.mergeRate,0,1);s===null?r.push("merge rate"):t.push(kK(s));let o=Gn(e.daysSinceLastCommit,0,Number.MAX_SAFE_INTEGER);if(o===null?r.push("activity"):t.push(CK(o)),t.length===0)return{score:zo[zo.length-1],reason:`unknown ${r.join(", ")}`};let i=SK(t),a=r.length>0?_K(i.score):i.score,c=[i.detail];return r.length>0&&c.push(`unknown ${r.join(", ")}`),{score:a,reason:c.join(", ")}}var zo,Pl=A(()=>{"use strict";zo=[10,7,4,1]});async function TK(e){let t=[],r=0;for await(let n of e.paginate.iterator(e.activity.listReposStarredByAuthenticatedUser,{per_page:EK,headers:{accept:"application/vnd.github.v3+json"}})){for(let s of n.data)s.full_name&&t.push(s.full_name);if(r+=1,r>=AK)break}return t}async function OL(e){if(!e.isStarredReposStale())return e.getStarredRepos().length;let t=ke(),r;try{r=await TK(we(t))}catch(n){return k(cC,`Failed to refresh starred repos; continuing with cached list (${e.getStarredRepos().length}): ${n instanceof Error?n.message:String(n)}`),e.getStarredRepos().length}return r.length===0?(O(cC,"Starred-repo fetch returned 0; keeping existing cache"),e.getStarredRepos().length):(e.setStarredRepos(r),O(cC,`Refreshed starred repos from GitHub: ${r.length} cached`),r.length)}var cC,EK,AK,IL=A(()=>{"use strict";lo();jm();ae();cC="starred-repos",EK=100,AK=5});var ML={};re(ML,{DEFAULT_SEARCH_RESULTS:()=>OK,MAX_SEARCH_RESULTS:()=>$K,SEARCH_DIVERSITY_RATIO:()=>Cl,SEARCH_SEEN_RETENTION_DAYS:()=>fu,parseSearchStrategies:()=>xK,readExcludeFile:()=>IK,recordSearchSeen:()=>LL,runSearch:()=>LK});function IK(e){let t;try{t=DL.readFileSync(e,"utf8")}catch(n){throw new Error(`Cannot read --exclude-file "${e}": ${n instanceof Error?n.message:String(n)}`,{cause:n})}let r=[...new Set(t.match(/https:\/\/github\.com\/[^/\s]+\/[^/\s]+\/issues\/\d+/g)??[])];return r.length===0&&t.trim()!==""&&k(Bo,`--exclude-file "${e}" has content but no GitHub issue URLs; nothing is excluded`),r}function xK(e){if(e===void 0)return;let t=e.split(",").map(n=>n.trim()).filter(Boolean);if(t.length===0)return;let r=[];for(let n of t){let s=Mo.safeParse(n);if(!s.success)throw new Error(`Unknown search strategy "${n}". Valid strategies: merged, orgs, starred, broad, maintained, all`);r.push(s.data)}return r}function DK(e){return typeof e!="number"||!Number.isFinite(e)||e<0||e>100?(k(Bo,`Ignoring out-of-contract viabilityScore from scout: ${JSON.stringify(e)}`),0):e}function xL(e){let t=process.env[e];if(t===void 0||t==="")return;let r=Number(t);if(!Number.isInteger(r)||r<0){k(Bo,`Ignoring invalid ${e}="${t}" (expected a non-negative integer); using scout's default delay`);return}return r}function LL(e,t){let r=Date.now(),n=new Date(r).toISOString(),s=r-fu*24*60*60*1e3,o=new Map(e.getSearchSeen().map(a=>[a.url,a]));for(let a of t)o.set(a,{url:a,lastSeenAt:n});let i=[...o.values()].filter(a=>{let c=Date.parse(a.lastSeenAt);return Number.isNaN(c)?!1:c>=s});e.setSearchSeen(i)}async function LK(e){let t={},r=M();await OL(r);let n=await As(t,e.excludeUrls),s=Rs(r.getState()),o=s?.recommendations.languages??void 0,i=Hf(r.getState()),a=new Set(i.map(R=>R.toLowerCase())),c=s?.recommendations.repos?.filter(R=>!a.has(R.toLowerCase()));(o?.length||c?.length)&&O(Bo,`Applying strategy bias to search: preferLanguages=${JSON.stringify(o??[])}, preferRepos=${JSON.stringify(c??[])}`);let u=xL("OSS_AUTOPILOT_SCOUT_INTER_PHASE_DELAY_MS"),d=xL("OSS_AUTOPILOT_SCOUT_BROAD_PHASE_DELAY_MS"),p=await n.search({maxResults:e.maxResults,...e.strategies&&{strategies:e.strategies},...e.full&&{full:!0},preferLanguages:o,preferRepos:c,diversityRatio:Cl,recentlySurfacedTtlDays:zS,...u!==void 0&&{interPhaseDelayMs:u},...d!==void 0&&{broadPhaseDelayMs:d}}),m=null;if(e.record!==!1){let R=()=>{LL(r,p.candidates.map(h=>h.issue.url)),r.setSearchRotation(n.getState().searchRotation)};R(),m=await Re(r,Bo,R)}let f=r.getState().config?.githubUsername??"";f===""&&k(Bo,"githubUsername not configured \u2014 the own-PR filter (#1354) cannot run; hiddenOwnPRCount will be 0");let g=p.candidates.filter(R=>bs({linkedPR:jo(R.vettingResult?.linkedPR),userLogin:f})!=="user_open"),y=p.candidates.length-g.length;y>0&&O(Bo,`Hid ${y} candidate(s) with the user's own open PR (#1354)`);let b={candidates:g.map(R=>{let h=r.getRepoScore(R.issue.repo),_=$s({repo:R.issue.repo,projectHealth:R.projectHealth??{repo:R.issue.repo,checkFailed:!0,failureReason:"health not supplied by the caller"},getRepoScore:w=>{let P=r.getRepoScore(w);return P?{mergedPRCount:P.mergedPRCount,closedWithoutMergeCount:P.closedWithoutMergeCount,avgResponseDays:P.avgResponseDays??null}:void 0}}),S=Es(R.vettingResult?.linkedPR);return{issue:{repo:R.issue.repo,repoUrl:`https://github.com/${R.issue.repo}`,number:R.issue.number,title:R.issue.title,url:R.issue.url,labels:R.issue.labels},recommendation:Ts(R.recommendation,_),reasonsToApprove:R.reasonsToApprove,reasonsToSkip:R.reasonsToSkip,searchPriority:R.searchPriority,...R.complexityUnlocked&&{complexityUnlocked:!0},viabilityScore:DK(R.viabilityScore),grade:_,repoScore:h?{score:h.score,mergedPRCount:h.mergedPRCount,closedWithoutMergeCount:h.closedWithoutMergeCount,isResponsive:h.signals?.isResponsive??!1,lastMergedAt:h.lastMergedAt}:void 0,...S&&{linkedPR:S},...R.personalization?.kind==="boosted"&&{boostScore:R.personalization.score},...R.personalization?.kind==="boosted"&&R.personalization.reasons.length>0&&{boostReasons:R.personalization.reasons},...R.personalization?.kind==="diversity"&&{diversitySlot:!0}}}),excludedRepos:p.excludedRepos,aiPolicyBlocklist:p.aiPolicyBlocklist,hiddenOwnPRCount:y,reposAtCap:i};return m&&(b.gistSyncWarning=m),p.rateLimitWarning&&(b.rateLimitWarning=p.rateLimitWarning),t.skipListUnavailable&&(b.skipListUnavailable=!0),b}var DL,Bo,$K,OK,FL=A(()=>{"use strict";DL=B(require("node:fs"),1);Ja();Eg();ue();Pl();tl();IL();ae();Na();Wi();Ja();Wi();Bo="search",$K=100,OK=15});var GL={};re(GL,{MAX_FEATURES_RESULTS:()=>FK,runFeatures:()=>GK});function NK(e){return typeof e!="number"||!Number.isFinite(e)||e<0||e>100?(k(MK,`Ignoring out-of-contract viabilityScore from scout: ${JSON.stringify(e)}`),0):e}function NL(e,t){let r=t.getRepoScore(e.issue.repo),n=$s({repo:e.issue.repo,projectHealth:e.projectHealth??{repo:e.issue.repo,checkFailed:!0,failureReason:"health not supplied by the caller"},getRepoScore:o=>{let i=t.getRepoScore(o);return i?{mergedPRCount:i.mergedPRCount,closedWithoutMergeCount:i.closedWithoutMergeCount,avgResponseDays:i.avgResponseDays??null}:void 0}}),s=Es(e.vettingResult?.linkedPR);return{issue:{repo:e.issue.repo,repoUrl:`https://github.com/${e.issue.repo}`,number:e.issue.number,title:e.issue.title,url:e.issue.url,labels:e.issue.labels},recommendation:Ts(e.recommendation,n),reasonsToApprove:e.reasonsToApprove,reasonsToSkip:e.reasonsToSkip,searchPriority:e.searchPriority,...e.complexityUnlocked&&{complexityUnlocked:!0},viabilityScore:NK(e.viabilityScore),grade:n,repoScore:r?{score:r.score,mergedPRCount:r.mergedPRCount,closedWithoutMergeCount:r.closedWithoutMergeCount,isResponsive:r.signals?.isResponsive??!1,lastMergedAt:r.lastMergedAt}:void 0,...s&&{linkedPR:s},horizon:e.horizon}}async function GK(e){let r=await(await As()).features({count:e.maxResults,anchorThreshold:e.anchorThreshold,splitRatio:e.splitRatio}),n=M();return{quickWins:r.quickWins.map(o=>NL(o,n)),biggerBets:r.biggerBets.map(o=>NL(o,n)),anchorRepos:r.anchorRepos,message:r.message}}var MK,FK,UL=A(()=>{"use strict";Ja();ue();Pl();ae();MK="features",FK=100});var jL={};re(jL,{runVet:()=>UK});async function UK(e){Ke(e.issueUrl),Qe(e.issueUrl,nr,"issue");let r=await(await As()).vetIssue(e.issueUrl),n=$s({repo:r.issue.repo,projectHealth:r.projectHealth,getRepoScore:d=>M().getRepoScore(d)}),s=M().getState().config.githubUsername,o=bs({linkedPR:jo(r.vettingResult.linkedPR),userLogin:s}),i=Es(r.vettingResult.linkedPR),a={issue:{repo:r.issue.repo,number:r.issue.number,title:r.issue.title,url:r.issue.url,labels:r.issue.labels},recommendation:Ts(r.recommendation,n),reasonsToApprove:r.reasonsToApprove,reasonsToSkip:r.reasonsToSkip,...r.complexityUnlocked&&{complexityUnlocked:!0},projectHealth:r.projectHealth,vettingResult:r.vettingResult,antiLLMPolicy:r.antiLLMPolicy,linkedPRClassification:o,...i&&{linkedPR:i},slmTriage:r.slmTriage??null,grade:n,...Wf(M().getState(),r.issue.repo)},c=Hi(M().getState().workClaims??[],e.issueUrl);if(c)return{...a,...c,reasonsToSkip:[...a.reasonsToSkip,...c.reasonsToSkip]};let u=await jK(a);return{...a,...await Ea(M(),u?[u]:[])}}async function jK(e){if(e.linkedPRClassification?.startsWith("user_"))return;let{repo:t,number:r,url:n}=e.issue,[s,o]=t.split("/",2),i;try{i=await vo(we(ke()),{repo:o,owner:s,number:r})}catch(a){k("vet",`Could not verify ${n} for pick traits: ${I(a)}`)}if(!(i&&va.has(i.verdict)))return ka(e,"vet",{...i&&Ca(i),firstInRepo:Pa(t,M().getRepoScore(t),M().getState().mergedPRs)})}var zL=A(()=>{"use strict";Ja();xt();Pl();Na();ue()});var BL={};re(BL,{runVerifyIssue:()=>zK});async function zK(e){Ke(e.issueUrl),Qe(e.issueUrl,nr,"issue");let t=q(e.issueUrl);if(!t||t.type!=="issues")throw new j(`Not a parseable GitHub issue URL: ${e.issueUrl}`);let r=we(ke());return vo(r,{owner:t.owner,repo:t.repo,number:t.number})}var HL=A(()=>{"use strict";ue();ee();xt()});var ZL={};re(ZL,{classifyListStatus:()=>VL,extractSkipReason:()=>WL,listStatusFromVerdict:()=>qL,runVetList:()=>qK});function HK(e,t){switch(e){case"issue_closed":return"closed";case"claimed":return"claimed";case"has_linked_pr":return t.linkedPR?.state==="open"&&t.linkedPR.isStalled?"has_stalled_pr":"has_pr";case"score_too_low":case"anti_llm_policy":case"other":return null}}function WL(e){if(typeof e!="object"||e===null)return;let t=e.skipReason;if(typeof t=="string")return BK.has(t)?t:void 0}function VL(e,t){if(t){let r=HK(t,e);if(r)return r}else{let r=e.reasonsToSkip.map(n=>n.toLowerCase());if(r.some(n=>n.includes("closed")))return"closed";if(r.some(n=>n.includes("claimed")||n.includes("assigned")))return"claimed";if(r.some(n=>n.includes("existing pr")||n.includes("linked pr")||n.includes("pull request")))return e.linkedPR?.state==="open"&&e.linkedPR.isStalled?"has_stalled_pr":"has_pr"}return e.recommendation==="approve"||e.recommendation==="needs_review","still_available"}function qL(e){switch(e){case"closed":return"closed";case"own-open-pr":return"own_open_pr";case"taken":return"claimed";case"at-risk":return"at_risk";case"available":return"still_available"}}function WK(e){return{verdict:e.verdict,verdictReason:e.verdictReason,state:e.state,stateReason:e.stateReason,assignees:e.assignees,linkedPRs:e.linkedPRs}}function VK(e){return{issue:{repo:`${e.owner}/${e.repo}`,number:e.number,title:e.title,url:e.url,labels:[]},recommendation:"skip",reasonsToApprove:[],reasonsToSkip:[e.verdictReason],projectHealth:{},vettingResult:{},grade:lC}}function uC(e){return e instanceof Error?e.message:String(e)}async function qK(e={}){let t=e.concurrency??5,r=e.issueListPath;if(!r){let w=xo();if(!w)throw new Error("No issue list found. Provide a path with --path or configure issueListPath in settings.");r=w.path}let n=await Nv({filePath:r}),s=[...n.available,...n.blocked];if(s.length===0)return{results:[],summary:{total:0,stillAvailable:0,claimed:0,closed:0,hasPR:0,hasStalledPR:0,atRisk:0,ownOpenPr:0,errors:0}};let o=we(ke()),i=[];s.forEach((w,P)=>{let C=q(w.url);C&&C.type==="issues"&&i.push({index:P,params:{owner:C.owner,repo:C.repo,number:C.number}})});let a=await of(o,i.map(w=>w.params),{concurrency:t}),c=new Map;i.forEach((w,P)=>c.set(w.index,a[P]));let u=await As(),d=[];async function p(w,P){let C=await u.vetIssue(w.url),E=$s({repo:C.issue.repo,projectHealth:C.projectHealth,getRepoScore:Se=>M().getRepoScore(Se)}),T=M().getState().config.githubUsername,L=bs({linkedPR:jo(C.vettingResult.linkedPR),userLogin:T}),G=Es(C.vettingResult.linkedPR),Y={issue:{repo:C.issue.repo,number:C.issue.number,title:C.issue.title,url:C.issue.url,labels:C.issue.labels},recommendation:Ts(C.recommendation,E),reasonsToApprove:C.reasonsToApprove,reasonsToSkip:C.reasonsToSkip,...C.complexityUnlocked&&{complexityUnlocked:!0},projectHealth:C.projectHealth,vettingResult:C.vettingResult,antiLLMPolicy:C.antiLLMPolicy,linkedPRClassification:L,...G&&{linkedPR:G},slmTriage:C.slmTriage??null,grade:E,...Wf(M().getState(),C.issue.repo)};if(P){let Se=ka(Y,"vet-list",{...Ca(P),firstInRepo:Pa(C.issue.repo,M().getRepoScore(C.issue.repo),M().getState().mergedPRs)});Se&&d.push(Se)}return{vetResult:Y,skipReason:WL(C)}}function m(w,P){let C=uC(P);return{issue:{repo:w.repo,number:w.number,title:w.title,url:w.url,labels:[]},recommendation:"skip",reasonsToApprove:[],reasonsToSkip:[`Error: ${C}`],projectHealth:{},vettingResult:{},grade:lC,listStatus:"error",errorMessage:C}}async function f(w,P){let C=Hi(M().getState().workClaims??[],w.url);if(C)return{issue:{repo:w.repo,number:w.number,title:w.title,url:w.url,labels:[]},recommendation:"skip",reasonsToApprove:[],reasonsToSkip:C.reasonsToSkip,projectHealth:{},vettingResult:{},grade:lC,listStatus:"claimed",workClaim:C.workClaim};if(!P||P.verification===void 0){let G=P?.error;if(G instanceof j)return{...m(w,G),verifyError:uC(G)};let Y={verifyError:G===void 0?`not verified: ${w.url} is not a verifiable issue URL`:uC(G)};try{let{vetResult:Se,skipReason:me}=await p(w);return{...Se,listStatus:VL(Se,me),...Y}}catch(Se){return{...m(w,Se),...Y}}}let E=P.verification,T=WK(E),L=qL(E.verdict);if(va.has(E.verdict))return{...VK(E),listStatus:L,verification:T};try{let{vetResult:G}=await p(w,E);return{...G,listStatus:L,verification:T}}catch(G){return{...m(w,G),verification:T}}}let g=new Array(s.length),y=0;async function b(){for(;y<s.length;){let w=y++;g[w]=await f(s[w],c.get(w))}}let R=Array.from({length:Math.min(t,s.length)},()=>b());await Promise.all(R);let h=await Ea(M(),d),_={total:g.length,stillAvailable:g.filter(w=>w.listStatus==="still_available").length,claimed:g.filter(w=>w.listStatus==="claimed").length,closed:g.filter(w=>w.listStatus==="closed").length,hasPR:g.filter(w=>w.listStatus==="has_pr").length,hasStalledPR:g.filter(w=>w.listStatus==="has_stalled_pr").length,atRisk:g.filter(w=>w.listStatus==="at_risk").length,ownOpenPr:g.filter(w=>w.listStatus==="own_open_pr").length,errors:g.filter(w=>w.listStatus==="error").length},S;if(e.prune&&r)try{let w=Tg.readFileSync(r,"utf8"),{pruned:P,removedCount:C}=Fv(w);P!==w&&Tg.writeFileSync(r,P,"utf8"),S={removedCount:C}}catch(w){let P=w instanceof Error?w.message:String(w);console.error(`Warning: Failed to prune ${r}: ${P}`),S={removedCount:0,error:P}}return{results:g,summary:_,pruneResult:S,...h}}var Tg,lC,BK,KL=A(()=>{"use strict";Tg=B(require("node:fs"),1);Ja();Io();ul();Pl();Na();ee();ue();lC=aC({avgResponseDays:null,mergeRate:null,daysSinceLastCommit:null}),BK=new Set(["issue_closed","has_linked_pr","claimed","score_too_low","anti_llm_policy","other"])});var rM={};re(rM,{runLedgerBackfill:()=>i6});function QL(e){let t=(e.firstComments?.nodes??[]).filter(n=>n!==null).map(n=>({user:YL(n.author),author_association:n.authorAssociation,created_at:n.createdAt})),r=(e.reviews?.nodes??[]).filter(n=>n!==null).map(n=>({user:YL(n.author),submitted_at:n.submittedAt}));return e.author?.login?xm(t,r,e.author.login):void 0}async function XK(e,t,r){return(await e.graphql(YK,{o:t.owner,r:t.repo,n:t.number,c:r.firstComments?.pageInfo?.endCursor??null,rc:r.reviews?.pageInfo?.endCursor??null})).repository?.pullRequest}async function e6(e,t,r,n){let s=q(t),o=QL(r);for(let i=1;!o&&s&&i<KK&&QK(r);i++){let a;try{a=await XK(e,s,r)}catch(c){if(le(c)||fa(c))throw c;return n.push(`response lookup for ${t} failed: ${I(c)}`),{isPending:!0}}if(!a)return{isPending:!0};r.firstComments=a.firstComments,r.reviews=a.reviews,o=QL(r)}return{at:o,isPending:!1}}async function t6(e,t,r,n){if(t)for(let[s,o]of t){let{at:i,isPending:a}=await e6(e,s,o,n);a||r.set(s,i)}}function r6(e){let t=0;for(let r of e.values())r&&t++;return t}async function n6(e,t,r){let n=[],s=[],o={};if(t.forEach((u,d)=>{let p=q(u);p&&(n.push(`$o${d}: String!, $r${d}: String!, $n${d}: Int!`),Object.assign(o,{[`o${d}`]:p.owner,[`r${d}`]:p.repo,[`n${d}`]:p.number}),s.push(`p${d}: repository(owner: $o${d}, name: $r${d}) { pullRequest(number: $n${d}) {${JK}} }`))}),s.length===0)return new Map;let i=`query ledgerBackfill(${n.join(", ")}) {
348
348
  ${s.join(`
349
349
  `)}
350
350
  }`,a;try{a=await e.graphql(i,o)}catch(u){if(le(u)||fa(u))throw u;let d=u.data;if(!d)return r.push(`batch of ${t.length} PRs failed: ${I(u)}`),null;let p=new Map;for(let m of u.errors??[]){let f=m.type??"ERROR";p.set(f,(p.get(f)??0)+1)}r.push(`PRs GitHub did not return: ${[...p].map(([m,f])=>`${m} x${f}`).join(", ")||"unknown"}`),a=d}let c=new Map;return t.forEach((u,d)=>{let p=a[`p${d}`]?.pullRequest;p&&c.set(u,p)}),c}function s6(e,t){let r=Qa.dirname(e),n=Qa.basename(e,".md");return Ya.readdirSync(r).filter(s=>s.startsWith(n)&&s.endsWith(".md")).sort().flatMap(s=>{let o=Qa.join(r,s);try{return[{file:o,content:Ya.readFileSync(o,"utf8")}]}catch(i){return t.push(`skipped list file ${o}: ${I(i)}`),[]}})}function o6(e,t){for(let{content:r}of e){let n=$v(r,t);if(!n?.includes("/issues/"))continue;let s=sn(r),o=[...s.available,...s.completed,...s.blocked].find(i=>i.url===n&&i.score!==void 0);if(o?.score!==void 0){let i=o.score>=ZK?"approve":"skip";return{issueUrl:n,grade:o.score,recommendation:i,source:"list"}}}}function eM(e){return{openedAt:e.filter(t=>t.openedAt).length,issueUrl:e.filter(t=>t.issueUrl).length,closeReason:e.filter(t=>"closeReason"in t&&t.closeReason).length,pick:e.filter(t=>t.pick).length}}async function i6(e={}){let t=M(),r=[];if(e.issueListPath&&!Ya.existsSync(e.issueListPath))throw new Error(`Issue list not found: ${e.issueListPath}`);let n=e.issueListPath??Ss()?.path;n||r.push("no curated issue list found; list vet scores were not imported");let s=n?s6(n,r):[],o=[...t.getMergedPRs().filter(h=>!h.backfilledAt||XL(h)),...t.getClosedPRs().filter(h=>!h.backfilledAt||XL(h)||h.closeReason==="self-closed"&&!h.selfCloseReason)].map(h=>h.url),i=new Map,a=new Map,c;if(o.length>0){let h=we(ke()),_=0;for(let S=0;S<o.length;S+=dC)try{let w=await n6(h,o.slice(S,S+dC),r);w||_++;for(let[P,C]of w??[])i.set(P,C);await t6(h,w,a,r)}catch(w){c=w;break}if(!c&&_===Math.ceil(o.length/dC))throw new Error(`Every GitHub batch failed: ${r.join("; ")}`)}t.reloadIfChanged();let u=t.getMergedPRs(),d=t.getClosedPRs(),p=eM([...u,...d]),m=h=>h&&t.getPickSnapshots().some(_=>_.issueUrl.toLowerCase()===h.toLowerCase()),f=new Date().toISOString(),g=h=>{let _=i.get(h.url),S=h.pick?void 0:o6(s,h.url),w=_?.closingIssuesReferences?.nodes[0]?.url??h.pick?.issueUrl??S?.issueUrl,P=S&&S.issueUrl===w&&!m(w)?S:void 0;return{openedAt:_?.createdAt,issueUrl:w,pick:P,..._&&{backfilledAt:f}}},y=()=>{t.addMergedPRs(u.map(h=>({url:h.url,title:h.title,mergedAt:h.mergedAt,...g(h)}))),t.addClosedPRs(d.map(h=>{let _=i.get(h.url),S=_?.timelineItems?.nodes.at(-1),w=S?{author:_?.author?.login,closer:S.actor?.login,closerIsBot:S.actor?.__typename==="Bot",comments:(_?.comments?.nodes??[]).flatMap(E=>E?[{author:E.author?.login,isBot:E.author?.__typename==="Bot",body:E.body}]:[])}:void 0,P=w&&IA(w),C=w&&(h.closeReason??P)==="self-closed"?OA(w):void 0;return{url:h.url,title:h.title,closedAt:h.closedAt,...g(h),closeReason:P,selfCloseReason:C}}));for(let[h,_]of a)t.setLedgerResponse(h,_,Iu)};t.batch(y);let b=eM([...t.getMergedPRs(),...t.getClosedPRs()]),R=await Re(t,"ledger-backfill",()=>t.batch(y));if(c)throw c;return{queried:o.length,filled:{openedAt:b.openedAt-p.openedAt,issueUrl:b.issueUrl-p.issueUrl,closeReason:b.closeReason-p.closeReason,pick:b.pick-p.pick,firstMaintainerResponseAt:r6(a)},listFiles:s.map(h=>h.file),unresolved:o.length-i.size,warnings:r,...R&&{gistSyncWarning:R}}}var Ya,Qa,dC,ZK,JL,KK,tM,JK,YK,YL,QK,XL,nM=A(()=>{"use strict";Ya=B(require("node:fs"),1),Qa=B(require("node:path"),1);$S();ee();ue();Dm();xu();ls();Ia();Ov();Io();dC=40,ZK=6,JL=10,KK=5,tM=e=>`