@juspay/neurolink 12.11.2 → 12.11.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +3 -2
- package/dist/browser/neurolink.min.js +3 -3
- package/dist/mcp/toolRegistry.js +7 -0
- package/dist/neurolink.d.ts +7 -0
- package/dist/neurolink.js +61 -11
- package/dist/types/tools.d.ts +23 -0
- package/dist/utils/errorHandling.d.ts +20 -3
- package/dist/utils/errorHandling.js +22 -5
- package/dist/utils/mcpDefaults.d.ts +1 -1
- package/dist/utils/mcpDefaults.js +4 -1
- package/package.json +1 -1
|
@@ -49,7 +49,7 @@ ${JSON.stringify(t,null,2)}
|
|
|
49
49
|
|
|
50
50
|
`)}h.write("payload.value = newResult;"),h.write("return payload;");const b=h.compile();return(T,k)=>b(m,T,k)};let s;const i=dv,a=!lT.jitless,c=a&&eU.value,u=t.catchall;let d;e._zod.parse=(m,h)=>{d??(d=n.value);const g=m.value;return i(g)?a&&c&&h?.async===!1&&h.jitless!==!0?(s||(s=o(t.shape)),m=s(m,h),u?Mhe([],g,m,h,d,e):m):r(m,h):(m.issues.push({expected:"object",code:"invalid_type",input:g,inst:e}),m)}}),fT=be("$ZodUnion",(e,t)=>{Kt.init(e,t),ir(e._zod,"optin",()=>t.options.some(o=>o._zod.optin==="optional")?"optional":void 0),ir(e._zod,"optout",()=>t.options.some(o=>o._zod.optout==="optional")?"optional":void 0),ir(e._zod,"values",()=>{if(t.options.every(o=>o._zod.values))return new Set(t.options.flatMap(o=>Array.from(o._zod.values)))}),ir(e._zod,"pattern",()=>{if(t.options.every(o=>o._zod.pattern)){const o=t.options.map(s=>s._zod.pattern);return new RegExp(`^(${o.map(s=>VI(s.source)).join("|")})$`)}});const r=t.options.length===1,n=t.options[0]._zod.run;e._zod.parse=(o,s)=>{if(r)return n(o,s);let i=!1;const a=[];for(const l of t.options){const c=l._zod.run({value:o.value,issues:[]},s);if(c instanceof Promise)a.push(c),i=!0;else{if(c.issues.length===0)return c;a.push(c)}}return i?Promise.all(a).then(l=>Phe(l,o,e,s)):Phe(a,o,e,s)}}),G6=be("$ZodXor",(e,t)=>{fT.init(e,t),t.inclusive=!1;const r=t.options.length===1,n=t.options[0]._zod.run;e._zod.parse=(o,s)=>{if(r)return n(o,s);let i=!1;const a=[];for(const l of t.options){const c=l._zod.run({value:o.value,issues:[]},s);c instanceof Promise?(a.push(c),i=!0):a.push(c)}return i?Promise.all(a).then(l=>Dhe(l,o,e,s)):Dhe(a,o,e,s)}}),H6=be("$ZodDiscriminatedUnion",(e,t)=>{t.inclusive=!1,fT.init(e,t);const r=e._zod.parse;ir(e._zod,"propValues",()=>{const o={};for(const s of t.options){const i=s._zod.propValues;if(!i||Object.keys(i).length===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(s)}"`);for(const[a,l]of Object.entries(i)){o[a]||(o[a]=new Set);for(const c of l)o[a].add(c)}}return o});const n=uT(()=>{const o=t.options,s=new Map;for(const i of o){const a=i._zod.propValues?.[t.discriminator];if(!a||a.size===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(i)}"`);for(const l of a){if(s.has(l))throw new Error(`Duplicate discriminator value "${String(l)}"`);s.set(l,i)}}return s});e._zod.parse=(o,s)=>{const i=o.value;if(!dv(i))return o.issues.push({code:"invalid_type",expected:"object",input:i,inst:e}),o;const a=n.value.get(i?.[t.discriminator]);return a?a._zod.run(o,s):t.unionFallback?r(o,s):(o.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:t.discriminator,input:i,path:[t.discriminator],inst:e}),o)}}),V6=be("$ZodIntersection",(e,t)=>{Kt.init(e,t),e._zod.parse=(r,n)=>{const o=r.value,s=t.left._zod.run({value:o,issues:[]},n),i=t.right._zod.run({value:o,issues:[]},n);return s instanceof Promise||i instanceof Promise?Promise.all([s,i]).then(([l,c])=>Ohe(r,l,c)):Ohe(r,s,i)}}),bR=be("$ZodTuple",(e,t)=>{Kt.init(e,t);const r=t.items;e._zod.parse=(n,o)=>{const s=n.value;if(!Array.isArray(s))return n.issues.push({input:s,inst:e,expected:"tuple",code:"invalid_type"}),n;n.value=[];const i=[],a=[...r].reverse().findIndex(u=>u._zod.optin!=="optional"),l=a===-1?0:r.length-a;if(!t.rest){const u=s.length>r.length,d=s.length<l-1;if(u||d)return n.issues.push({...u?{code:"too_big",maximum:r.length,inclusive:!0}:{code:"too_small",minimum:r.length},input:s,inst:e,origin:"array"}),n}let c=-1;for(const u of r){if(c++,c>=s.length&&c>=l)continue;const d=u._zod.run({value:s[c],issues:[]},o);d instanceof Promise?i.push(d.then(m=>hR(m,n,c))):hR(d,n,c)}if(t.rest){const u=s.slice(r.length);for(const d of u){c++;const m=t.rest._zod.run({value:d,issues:[]},o);m instanceof Promise?i.push(m.then(h=>hR(h,n,c))):hR(m,n,c)}}return i.length?Promise.all(i).then(()=>n):n}}),W6=be("$ZodRecord",(e,t)=>{Kt.init(e,t),e._zod.parse=(r,n)=>{const o=r.value;if(!nf(o))return r.issues.push({expected:"record",code:"invalid_type",input:o,inst:e}),r;const s=[],i=t.keyType._zod.values;if(i){r.value={};const a=new Set;for(const c of i)if(typeof c=="string"||typeof c=="number"||typeof c=="symbol"){a.add(typeof c=="number"?c.toString():c);const u=t.valueType._zod.run({value:o[c],issues:[]},n);u instanceof Promise?s.push(u.then(d=>{d.issues.length&&r.issues.push(...Hc(c,d.issues)),r.value[c]=d.value})):(u.issues.length&&r.issues.push(...Hc(c,u.issues)),r.value[c]=u.value)}let l;for(const c in o)a.has(c)||(l=l??[],l.push(c));l&&l.length>0&&r.issues.push({code:"unrecognized_keys",input:o,inst:e,keys:l})}else{r.value={};for(const a of Reflect.ownKeys(o)){if(a==="__proto__")continue;let l=t.keyType._zod.run({value:a,issues:[]},n);if(l instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(typeof a=="string"&&uR.test(a)&&l.issues.length){const d=t.keyType._zod.run({value:Number(a),issues:[]},n);if(d instanceof Promise)throw new Error("Async schemas not supported in object keys currently");d.issues.length===0&&(l=d)}if(l.issues.length){t.mode==="loose"?r.value[a]=o[a]:r.issues.push({code:"invalid_key",origin:"record",issues:l.issues.map(d=>oc(d,n,qi())),input:a,path:[a],inst:e});continue}const u=t.valueType._zod.run({value:o[a],issues:[]},n);u instanceof Promise?s.push(u.then(d=>{d.issues.length&&r.issues.push(...Hc(a,d.issues)),r.value[l.value]=d.value})):(u.issues.length&&r.issues.push(...Hc(a,u.issues)),r.value[l.value]=u.value)}}return s.length?Promise.all(s).then(()=>r):r}}),K6=be("$ZodMap",(e,t)=>{Kt.init(e,t),e._zod.parse=(r,n)=>{const o=r.value;if(!(o instanceof Map))return r.issues.push({expected:"map",code:"invalid_type",input:o,inst:e}),r;const s=[];r.value=new Map;for(const[i,a]of o){const l=t.keyType._zod.run({value:i,issues:[]},n),c=t.valueType._zod.run({value:a,issues:[]},n);l instanceof Promise||c instanceof Promise?s.push(Promise.all([l,c]).then(([u,d])=>{Nhe(u,d,r,i,o,e,n)})):Nhe(l,c,r,i,o,e,n)}return s.length?Promise.all(s).then(()=>r):r}}),J6=be("$ZodSet",(e,t)=>{Kt.init(e,t),e._zod.parse=(r,n)=>{const o=r.value;if(!(o instanceof Set))return r.issues.push({input:o,inst:e,expected:"set",code:"invalid_type"}),r;const s=[];r.value=new Set;for(const i of o){const a=t.valueType._zod.run({value:i,issues:[]},n);a instanceof Promise?s.push(a.then(l=>Lhe(l,r))):Lhe(a,r)}return s.length?Promise.all(s).then(()=>r):r}}),Y6=be("$ZodEnum",(e,t)=>{Kt.init(e,t);const r=Z3(t.entries),n=new Set(r);e._zod.values=n,e._zod.pattern=new RegExp(`^(${r.filter(o=>pT.has(typeof o)).map(o=>typeof o=="string"?$d(o):o.toString()).join("|")})$`),e._zod.parse=(o,s)=>{const i=o.value;return n.has(i)||o.issues.push({code:"invalid_value",values:r,input:i,inst:e}),o}}),Z6=be("$ZodLiteral",(e,t)=>{if(Kt.init(e,t),t.values.length===0)throw new Error("Cannot create literal schema with no valid values");const r=new Set(t.values);e._zod.values=r,e._zod.pattern=new RegExp(`^(${t.values.map(n=>typeof n=="string"?$d(n):n?$d(n.toString()):String(n)).join("|")})$`),e._zod.parse=(n,o)=>{const s=n.value;return r.has(s)||n.issues.push({code:"invalid_value",values:t.values,input:s,inst:e}),n}}),X6=be("$ZodFile",(e,t)=>{Kt.init(e,t),e._zod.parse=(r,n)=>{const o=r.value;return o instanceof File||r.issues.push({expected:"file",code:"invalid_type",input:o,inst:e}),r}}),Q6=be("$ZodTransform",(e,t)=>{Kt.init(e,t),e._zod.parse=(r,n)=>{if(n.direction==="backward")throw new aT(e.constructor.name);const o=t.transform(r.value,r);if(n.async)return(o instanceof Promise?o:Promise.resolve(o)).then(i=>(r.value=i,r));if(o instanceof Promise)throw new pm;return r.value=o,r}}),TR=be("$ZodOptional",(e,t)=>{Kt.init(e,t),e._zod.optin="optional",e._zod.optout="optional",ir(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),ir(e._zod,"pattern",()=>{const r=t.innerType._zod.pattern;return r?new RegExp(`^(${VI(r.source)})?$`):void 0}),e._zod.parse=(r,n)=>{if(t.innerType._zod.optin==="optional"){const o=t.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>$he(s,r.value)):$he(o,r.value)}return r.value===void 0?r:t.innerType._zod.run(r,n)}}),e5=be("$ZodExactOptional",(e,t)=>{TR.init(e,t),ir(e._zod,"values",()=>t.innerType._zod.values),ir(e._zod,"pattern",()=>t.innerType._zod.pattern),e._zod.parse=(r,n)=>t.innerType._zod.run(r,n)}),t5=be("$ZodNullable",(e,t)=>{Kt.init(e,t),ir(e._zod,"optin",()=>t.innerType._zod.optin),ir(e._zod,"optout",()=>t.innerType._zod.optout),ir(e._zod,"pattern",()=>{const r=t.innerType._zod.pattern;return r?new RegExp(`^(${VI(r.source)}|null)$`):void 0}),ir(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(r,n)=>r.value===null?r:t.innerType._zod.run(r,n)}),r5=be("$ZodDefault",(e,t)=>{Kt.init(e,t),e._zod.optin="optional",ir(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,n)=>{if(n.direction==="backward")return t.innerType._zod.run(r,n);if(r.value===void 0)return r.value=t.defaultValue,r;const o=t.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>Fhe(s,t)):Fhe(o,t)}}),n5=be("$ZodPrefault",(e,t)=>{Kt.init(e,t),e._zod.optin="optional",ir(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,n)=>(n.direction==="backward"||r.value===void 0&&(r.value=t.defaultValue),t.innerType._zod.run(r,n))}),o5=be("$ZodNonOptional",(e,t)=>{Kt.init(e,t),ir(e._zod,"values",()=>{const r=t.innerType._zod.values;return r?new Set([...r].filter(n=>n!==void 0)):void 0}),e._zod.parse=(r,n)=>{const o=t.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>Uhe(s,e)):Uhe(o,e)}}),s5=be("$ZodSuccess",(e,t)=>{Kt.init(e,t),e._zod.parse=(r,n)=>{if(n.direction==="backward")throw new aT("ZodSuccess");const o=t.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>(r.value=s.issues.length===0,r)):(r.value=o.issues.length===0,r)}}),i5=be("$ZodCatch",(e,t)=>{Kt.init(e,t),ir(e._zod,"optin",()=>t.innerType._zod.optin),ir(e._zod,"optout",()=>t.innerType._zod.optout),ir(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,n)=>{if(n.direction==="backward")return t.innerType._zod.run(r,n);const o=t.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>(r.value=s.value,s.issues.length&&(r.value=t.catchValue({...r,error:{issues:s.issues.map(i=>oc(i,n,qi()))},input:r.value}),r.issues=[]),r)):(r.value=o.value,o.issues.length&&(r.value=t.catchValue({...r,error:{issues:o.issues.map(s=>oc(s,n,qi()))},input:r.value}),r.issues=[]),r)}}),a5=be("$ZodNaN",(e,t)=>{Kt.init(e,t),e._zod.parse=(r,n)=>((typeof r.value!="number"||!Number.isNaN(r.value))&&r.issues.push({input:r.value,inst:e,expected:"nan",code:"invalid_type"}),r)}),l5=be("$ZodPipe",(e,t)=>{Kt.init(e,t),ir(e._zod,"values",()=>t.in._zod.values),ir(e._zod,"optin",()=>t.in._zod.optin),ir(e._zod,"optout",()=>t.out._zod.optout),ir(e._zod,"propValues",()=>t.in._zod.propValues),e._zod.parse=(r,n)=>{if(n.direction==="backward"){const s=t.out._zod.run(r,n);return s instanceof Promise?s.then(i=>fR(i,t.in,n)):fR(s,t.in,n)}const o=t.in._zod.run(r,n);return o instanceof Promise?o.then(s=>fR(s,t.out,n)):fR(o,t.out,n)}}),ER=be("$ZodCodec",(e,t)=>{Kt.init(e,t),ir(e._zod,"values",()=>t.in._zod.values),ir(e._zod,"optin",()=>t.in._zod.optin),ir(e._zod,"optout",()=>t.out._zod.optout),ir(e._zod,"propValues",()=>t.in._zod.propValues),e._zod.parse=(r,n)=>{if((n.direction||"forward")==="forward"){const s=t.in._zod.run(r,n);return s instanceof Promise?s.then(i=>gR(i,t,n)):gR(s,t,n)}else{const s=t.out._zod.run(r,n);return s instanceof Promise?s.then(i=>gR(i,t,n)):gR(s,t,n)}}}),c5=be("$ZodReadonly",(e,t)=>{Kt.init(e,t),ir(e._zod,"propValues",()=>t.innerType._zod.propValues),ir(e._zod,"values",()=>t.innerType._zod.values),ir(e._zod,"optin",()=>t.innerType?._zod?.optin),ir(e._zod,"optout",()=>t.innerType?._zod?.optout),e._zod.parse=(r,n)=>{if(n.direction==="backward")return t.innerType._zod.run(r,n);const o=t.innerType._zod.run(r,n);return o instanceof Promise?o.then(Bhe):Bhe(o)}}),u5=be("$ZodTemplateLiteral",(e,t)=>{Kt.init(e,t);const r=[];for(const n of t.parts)if(typeof n=="object"&&n!==null){if(!n._zod.pattern)throw new Error(`Invalid template literal part, no pattern found: ${[...n._zod.traits].shift()}`);const o=n._zod.pattern instanceof RegExp?n._zod.pattern.source:n._zod.pattern;if(!o)throw new Error(`Invalid template literal part: ${n._zod.traits}`);const s=o.startsWith("^")?1:0,i=o.endsWith("$")?o.length-1:o.length;r.push(o.slice(s,i))}else if(n===null||tU.has(typeof n))r.push($d(`${n}`));else throw new Error(`Invalid template literal part: ${n}`);e._zod.pattern=new RegExp(`^${r.join("")}$`),e._zod.parse=(n,o)=>typeof n.value!="string"?(n.issues.push({input:n.value,inst:e,expected:"string",code:"invalid_type"}),n):(e._zod.pattern.lastIndex=0,e._zod.pattern.test(n.value)||n.issues.push({input:n.value,inst:e,code:"invalid_format",format:t.format??"template_literal",pattern:e._zod.pattern.source}),n)}),d5=be("$ZodFunction",(e,t)=>(Kt.init(e,t),e._def=t,e._zod.def=t,e.implement=r=>{if(typeof r!="function")throw new Error("implement() must be called with a function");return function(...n){const o=e._def.input?XI(e._def.input,n):n,s=Reflect.apply(r,this,o);return e._def.output?XI(e._def.output,s):s}},e.implementAsync=r=>{if(typeof r!="function")throw new Error("implementAsync() must be called with a function");return async function(...n){const o=e._def.input?await QI(e._def.input,n):n,s=await Reflect.apply(r,this,o);return e._def.output?await QI(e._def.output,s):s}},e._zod.parse=(r,n)=>typeof r.value!="function"?(r.issues.push({code:"invalid_type",expected:"function",input:r.value,inst:e}),r):(e._def.output&&e._def.output._zod.def.type==="promise"?r.value=e.implementAsync(r.value):r.value=e.implement(r.value),r),e.input=(...r)=>{const n=e.constructor;return Array.isArray(r[0])?new n({type:"function",input:new bR({type:"tuple",items:r[0],rest:r[1]}),output:e._def.output}):new n({type:"function",input:r[0],output:e._def.output})},e.output=r=>{const n=e.constructor;return new n({type:"function",input:e._def.input,output:r})},e)),p5=be("$ZodPromise",(e,t)=>{Kt.init(e,t),e._zod.parse=(r,n)=>Promise.resolve(r.value).then(o=>t.innerType._zod.run({value:o,issues:[]},n))}),m5=be("$ZodLazy",(e,t)=>{Kt.init(e,t),ir(e._zod,"innerType",()=>t.getter()),ir(e._zod,"pattern",()=>e._zod.innerType?._zod?.pattern),ir(e._zod,"propValues",()=>e._zod.innerType?._zod?.propValues),ir(e._zod,"optin",()=>e._zod.innerType?._zod?.optin??void 0),ir(e._zod,"optout",()=>e._zod.innerType?._zod?.optout??void 0),e._zod.parse=(r,n)=>e._zod.innerType._zod.run(r,n)}),h5=be("$ZodCustom",(e,t)=>{Tn.init(e,t),Kt.init(e,t),e._zod.parse=(r,n)=>r,e._zod.check=r=>{const n=r.value,o=t.fn(n);if(o instanceof Promise)return o.then(s=>zhe(s,r,n,e));zhe(o,r,n,e)}})}});function mfr(){return{localeError:qhe()}}var qhe,hfr=S({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ar.js"(){kt(),qhe=()=>{const e={string:{unit:"\u062D\u0631\u0641",verb:"\u0623\u0646 \u064A\u062D\u0648\u064A"},file:{unit:"\u0628\u0627\u064A\u062A",verb:"\u0623\u0646 \u064A\u062D\u0648\u064A"},array:{unit:"\u0639\u0646\u0635\u0631",verb:"\u0623\u0646 \u064A\u062D\u0648\u064A"},set:{unit:"\u0639\u0646\u0635\u0631",verb:"\u0623\u0646 \u064A\u062D\u0648\u064A"}};function t(o){return e[o]??null}const r={regex:"\u0645\u062F\u062E\u0644",email:"\u0628\u0631\u064A\u062F \u0625\u0644\u0643\u062A\u0631\u0648\u0646\u064A",url:"\u0631\u0627\u0628\u0637",emoji:"\u0625\u064A\u0645\u0648\u062C\u064A",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"\u062A\u0627\u0631\u064A\u062E \u0648\u0648\u0642\u062A \u0628\u0645\u0639\u064A\u0627\u0631 ISO",date:"\u062A\u0627\u0631\u064A\u062E \u0628\u0645\u0639\u064A\u0627\u0631 ISO",time:"\u0648\u0642\u062A \u0628\u0645\u0639\u064A\u0627\u0631 ISO",duration:"\u0645\u062F\u0629 \u0628\u0645\u0639\u064A\u0627\u0631 ISO",ipv4:"\u0639\u0646\u0648\u0627\u0646 IPv4",ipv6:"\u0639\u0646\u0648\u0627\u0646 IPv6",cidrv4:"\u0645\u062F\u0649 \u0639\u0646\u0627\u0648\u064A\u0646 \u0628\u0635\u064A\u063A\u0629 IPv4",cidrv6:"\u0645\u062F\u0649 \u0639\u0646\u0627\u0648\u064A\u0646 \u0628\u0635\u064A\u063A\u0629 IPv6",base64:"\u0646\u064E\u0635 \u0628\u062A\u0631\u0645\u064A\u0632 base64-encoded",base64url:"\u0646\u064E\u0635 \u0628\u062A\u0631\u0645\u064A\u0632 base64url-encoded",json_string:"\u0646\u064E\u0635 \u0639\u0644\u0649 \u0647\u064A\u0626\u0629 JSON",e164:"\u0631\u0642\u0645 \u0647\u0627\u062A\u0641 \u0628\u0645\u0639\u064A\u0627\u0631 E.164",jwt:"JWT",template_literal:"\u0645\u062F\u062E\u0644"},n={nan:"NaN"};return o=>{switch(o.code){case"invalid_type":{const s=n[o.expected]??o.expected,i=Ut(o.input),a=n[i]??i;return/^[A-Z]/.test(o.expected)?`\u0645\u062F\u062E\u0644\u0627\u062A \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644\u0629: \u064A\u0641\u062A\u0631\u0636 \u0625\u062F\u062E\u0627\u0644 instanceof ${o.expected}\u060C \u0648\u0644\u0643\u0646 \u062A\u0645 \u0625\u062F\u062E\u0627\u0644 ${a}`:`\u0645\u062F\u062E\u0644\u0627\u062A \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644\u0629: \u064A\u0641\u062A\u0631\u0636 \u0625\u062F\u062E\u0627\u0644 ${s}\u060C \u0648\u0644\u0643\u0646 \u062A\u0645 \u0625\u062F\u062E\u0627\u0644 ${a}`}case"invalid_value":return o.values.length===1?`\u0645\u062F\u062E\u0644\u0627\u062A \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644\u0629: \u064A\u0641\u062A\u0631\u0636 \u0625\u062F\u062E\u0627\u0644 ${Ot(o.values[0])}`:`\u0627\u062E\u062A\u064A\u0627\u0631 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062A\u0648\u0642\u0639 \u0627\u0646\u062A\u0642\u0627\u0621 \u0623\u062D\u062F \u0647\u0630\u0647 \u0627\u0644\u062E\u064A\u0627\u0631\u0627\u062A: ${Ye(o.values,"|")}`;case"too_big":{const s=o.inclusive?"<=":"<",i=t(o.origin);return i?` \u0623\u0643\u0628\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0623\u0646 \u062A\u0643\u0648\u0646 ${o.origin??"\u0627\u0644\u0642\u064A\u0645\u0629"} ${s} ${o.maximum.toString()} ${i.unit??"\u0639\u0646\u0635\u0631"}`:`\u0623\u0643\u0628\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0623\u0646 \u062A\u0643\u0648\u0646 ${o.origin??"\u0627\u0644\u0642\u064A\u0645\u0629"} ${s} ${o.maximum.toString()}`}case"too_small":{const s=o.inclusive?">=":">",i=t(o.origin);return i?`\u0623\u0635\u063A\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0644\u0640 ${o.origin} \u0623\u0646 \u064A\u0643\u0648\u0646 ${s} ${o.minimum.toString()} ${i.unit}`:`\u0623\u0635\u063A\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0644\u0640 ${o.origin} \u0623\u0646 \u064A\u0643\u0648\u0646 ${s} ${o.minimum.toString()}`}case"invalid_format":{const s=o;return s.format==="starts_with"?`\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0628\u062F\u0623 \u0628\u0640 "${o.prefix}"`:s.format==="ends_with"?`\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0646\u062A\u0647\u064A \u0628\u0640 "${s.suffix}"`:s.format==="includes"?`\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u062A\u0636\u0645\u0651\u064E\u0646 "${s.includes}"`:s.format==="regex"?`\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0637\u0627\u0628\u0642 \u0627\u0644\u0646\u0645\u0637 ${s.pattern}`:`${r[s.format]??o.format} \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644`}case"not_multiple_of":return`\u0631\u0642\u0645 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0643\u0648\u0646 \u0645\u0646 \u0645\u0636\u0627\u0639\u0641\u0627\u062A ${o.divisor}`;case"unrecognized_keys":return`\u0645\u0639\u0631\u0641${o.keys.length>1?"\u0627\u062A":""} \u063A\u0631\u064A\u0628${o.keys.length>1?"\u0629":""}: ${Ye(o.keys,"\u060C ")}`;case"invalid_key":return`\u0645\u0639\u0631\u0641 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644 \u0641\u064A ${o.origin}`;case"invalid_union":return"\u0645\u062F\u062E\u0644 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644";case"invalid_element":return`\u0645\u062F\u062E\u0644 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644 \u0641\u064A ${o.origin}`;default:return"\u0645\u062F\u062E\u0644 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644"}}}}});function ffr(){return{localeError:Ghe()}}var Ghe,gfr=S({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/az.js"(){kt(),Ghe=()=>{const e={string:{unit:"simvol",verb:"olmal\u0131d\u0131r"},file:{unit:"bayt",verb:"olmal\u0131d\u0131r"},array:{unit:"element",verb:"olmal\u0131d\u0131r"},set:{unit:"element",verb:"olmal\u0131d\u0131r"}};function t(o){return e[o]??null}const r={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"},n={nan:"NaN"};return o=>{switch(o.code){case"invalid_type":{const s=n[o.expected]??o.expected,i=Ut(o.input),a=n[i]??i;return/^[A-Z]/.test(o.expected)?`Yanl\u0131\u015F d\u0259y\u0259r: g\xF6zl\u0259nil\u0259n instanceof ${o.expected}, daxil olan ${a}`:`Yanl\u0131\u015F d\u0259y\u0259r: g\xF6zl\u0259nil\u0259n ${s}, daxil olan ${a}`}case"invalid_value":return o.values.length===1?`Yanl\u0131\u015F d\u0259y\u0259r: g\xF6zl\u0259nil\u0259n ${Ot(o.values[0])}`:`Yanl\u0131\u015F se\xE7im: a\u015Fa\u011F\u0131dak\u0131lardan biri olmal\u0131d\u0131r: ${Ye(o.values,"|")}`;case"too_big":{const s=o.inclusive?"<=":"<",i=t(o.origin);return i?`\xC7ox b\xF6y\xFCk: g\xF6zl\u0259nil\u0259n ${o.origin??"d\u0259y\u0259r"} ${s}${o.maximum.toString()} ${i.unit??"element"}`:`\xC7ox b\xF6y\xFCk: g\xF6zl\u0259nil\u0259n ${o.origin??"d\u0259y\u0259r"} ${s}${o.maximum.toString()}`}case"too_small":{const s=o.inclusive?">=":">",i=t(o.origin);return i?`\xC7ox ki\xE7ik: g\xF6zl\u0259nil\u0259n ${o.origin} ${s}${o.minimum.toString()} ${i.unit}`:`\xC7ox ki\xE7ik: g\xF6zl\u0259nil\u0259n ${o.origin} ${s}${o.minimum.toString()}`}case"invalid_format":{const s=o;return s.format==="starts_with"?`Yanl\u0131\u015F m\u0259tn: "${s.prefix}" il\u0259 ba\u015Flamal\u0131d\u0131r`:s.format==="ends_with"?`Yanl\u0131\u015F m\u0259tn: "${s.suffix}" il\u0259 bitm\u0259lidir`:s.format==="includes"?`Yanl\u0131\u015F m\u0259tn: "${s.includes}" daxil olmal\u0131d\u0131r`:s.format==="regex"?`Yanl\u0131\u015F m\u0259tn: ${s.pattern} \u015Fablonuna uy\u011Fun olmal\u0131d\u0131r`:`Yanl\u0131\u015F ${r[s.format]??o.format}`}case"not_multiple_of":return`Yanl\u0131\u015F \u0259d\u0259d: ${o.divisor} il\u0259 b\xF6l\xFCn\u0259 bil\u0259n olmal\u0131d\u0131r`;case"unrecognized_keys":return`Tan\u0131nmayan a\xE7ar${o.keys.length>1?"lar":""}: ${Ye(o.keys,", ")}`;case"invalid_key":return`${o.origin} daxilind\u0259 yanl\u0131\u015F a\xE7ar`;case"invalid_union":return"Yanl\u0131\u015F d\u0259y\u0259r";case"invalid_element":return`${o.origin} daxilind\u0259 yanl\u0131\u015F d\u0259y\u0259r`;default:return"Yanl\u0131\u015F d\u0259y\u0259r"}}}}});function Hhe(e,t,r,n){const o=Math.abs(e),s=o%10,i=o%100;return i>=11&&i<=19?n:s===1?t:s>=2&&s<=4?r:n}function yfr(){return{localeError:Vhe()}}var Vhe,vfr=S({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/be.js"(){kt(),Vhe=()=>{const e={string:{unit:{one:"\u0441\u0456\u043C\u0432\u0430\u043B",few:"\u0441\u0456\u043C\u0432\u0430\u043B\u044B",many:"\u0441\u0456\u043C\u0432\u0430\u043B\u0430\u045E"},verb:"\u043C\u0435\u0446\u044C"},array:{unit:{one:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442",few:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u044B",many:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430\u045E"},verb:"\u043C\u0435\u0446\u044C"},set:{unit:{one:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442",few:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u044B",many:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430\u045E"},verb:"\u043C\u0435\u0446\u044C"},file:{unit:{one:"\u0431\u0430\u0439\u0442",few:"\u0431\u0430\u0439\u0442\u044B",many:"\u0431\u0430\u0439\u0442\u0430\u045E"},verb:"\u043C\u0435\u0446\u044C"}};function t(o){return e[o]??null}const r={regex:"\u0443\u0432\u043E\u0434",email:"email \u0430\u0434\u0440\u0430\u0441",url:"URL",emoji:"\u044D\u043C\u043E\u0434\u0437\u0456",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO \u0434\u0430\u0442\u0430 \u0456 \u0447\u0430\u0441",date:"ISO \u0434\u0430\u0442\u0430",time:"ISO \u0447\u0430\u0441",duration:"ISO \u043F\u0440\u0430\u0446\u044F\u0433\u043B\u0430\u0441\u0446\u044C",ipv4:"IPv4 \u0430\u0434\u0440\u0430\u0441",ipv6:"IPv6 \u0430\u0434\u0440\u0430\u0441",cidrv4:"IPv4 \u0434\u044B\u044F\u043F\u0430\u0437\u043E\u043D",cidrv6:"IPv6 \u0434\u044B\u044F\u043F\u0430\u0437\u043E\u043D",base64:"\u0440\u0430\u0434\u043E\u043A \u0443 \u0444\u0430\u0440\u043C\u0430\u0446\u0435 base64",base64url:"\u0440\u0430\u0434\u043E\u043A \u0443 \u0444\u0430\u0440\u043C\u0430\u0446\u0435 base64url",json_string:"JSON \u0440\u0430\u0434\u043E\u043A",e164:"\u043D\u0443\u043C\u0430\u0440 E.164",jwt:"JWT",template_literal:"\u0443\u0432\u043E\u0434"},n={nan:"NaN",number:"\u043B\u0456\u043A",array:"\u043C\u0430\u0441\u0456\u045E"};return o=>{switch(o.code){case"invalid_type":{const s=n[o.expected]??o.expected,i=Ut(o.input),a=n[i]??i;return/^[A-Z]/.test(o.expected)?`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434: \u0447\u0430\u043A\u0430\u045E\u0441\u044F instanceof ${o.expected}, \u0430\u0442\u0440\u044B\u043C\u0430\u043D\u0430 ${a}`:`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434: \u0447\u0430\u043A\u0430\u045E\u0441\u044F ${s}, \u0430\u0442\u0440\u044B\u043C\u0430\u043D\u0430 ${a}`}case"invalid_value":return o.values.length===1?`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F ${Ot(o.values[0])}`:`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0432\u0430\u0440\u044B\u044F\u043D\u0442: \u0447\u0430\u043A\u0430\u045E\u0441\u044F \u0430\u0434\u0437\u0456\u043D \u0437 ${Ye(o.values,"|")}`;case"too_big":{const s=o.inclusive?"<=":"<",i=t(o.origin);if(i){const a=Number(o.maximum),l=Hhe(a,i.unit.one,i.unit.few,i.unit.many);return`\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u0432\u044F\u043B\u0456\u043A\u0456: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${o.origin??"\u0437\u043D\u0430\u0447\u044D\u043D\u043D\u0435"} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 ${i.verb} ${s}${o.maximum.toString()} ${l}`}return`\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u0432\u044F\u043B\u0456\u043A\u0456: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${o.origin??"\u0437\u043D\u0430\u0447\u044D\u043D\u043D\u0435"} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 \u0431\u044B\u0446\u044C ${s}${o.maximum.toString()}`}case"too_small":{const s=o.inclusive?">=":">",i=t(o.origin);if(i){const a=Number(o.minimum),l=Hhe(a,i.unit.one,i.unit.few,i.unit.many);return`\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u043C\u0430\u043B\u044B: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${o.origin} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 ${i.verb} ${s}${o.minimum.toString()} ${l}`}return`\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u043C\u0430\u043B\u044B: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${o.origin} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 \u0431\u044B\u0446\u044C ${s}${o.minimum.toString()}`}case"invalid_format":{const s=o;return s.format==="starts_with"?`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u043F\u0430\u0447\u044B\u043D\u0430\u0446\u0446\u0430 \u0437 "${s.prefix}"`:s.format==="ends_with"?`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0437\u0430\u043A\u0430\u043D\u0447\u0432\u0430\u0446\u0446\u0430 \u043D\u0430 "${s.suffix}"`:s.format==="includes"?`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0437\u043C\u044F\u0448\u0447\u0430\u0446\u044C "${s.includes}"`:s.format==="regex"?`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0430\u0434\u043F\u0430\u0432\u044F\u0434\u0430\u0446\u044C \u0448\u0430\u0431\u043B\u043E\u043D\u0443 ${s.pattern}`:`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B ${r[s.format]??o.format}`}case"not_multiple_of":return`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u043B\u0456\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0431\u044B\u0446\u044C \u043A\u0440\u0430\u0442\u043D\u044B\u043C ${o.divisor}`;case"unrecognized_keys":return`\u041D\u0435\u0440\u0430\u0441\u043F\u0430\u0437\u043D\u0430\u043D\u044B ${o.keys.length>1?"\u043A\u043B\u044E\u0447\u044B":"\u043A\u043B\u044E\u0447"}: ${Ye(o.keys,", ")}`;case"invalid_key":return`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u043A\u043B\u044E\u0447 \u0443 ${o.origin}`;case"invalid_union":return"\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434";case"invalid_element":return`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u0430\u0435 \u0437\u043D\u0430\u0447\u044D\u043D\u043D\u0435 \u045E ${o.origin}`;default:return"\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434"}}}}});function _fr(){return{localeError:Whe()}}var Whe,wfr=S({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/bg.js"(){kt(),Whe=()=>{const e={string:{unit:"\u0441\u0438\u043C\u0432\u043E\u043B\u0430",verb:"\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430"},file:{unit:"\u0431\u0430\u0439\u0442\u0430",verb:"\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430"},array:{unit:"\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0430",verb:"\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430"},set:{unit:"\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0430",verb:"\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430"}};function t(o){return e[o]??null}const r={regex:"\u0432\u0445\u043E\u0434",email:"\u0438\u043C\u0435\u0439\u043B \u0430\u0434\u0440\u0435\u0441",url:"URL",emoji:"\u0435\u043C\u043E\u0434\u0436\u0438",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO \u0432\u0440\u0435\u043C\u0435",date:"ISO \u0434\u0430\u0442\u0430",time:"ISO \u0432\u0440\u0435\u043C\u0435",duration:"ISO \u043F\u0440\u043E\u0434\u044A\u043B\u0436\u0438\u0442\u0435\u043B\u043D\u043E\u0441\u0442",ipv4:"IPv4 \u0430\u0434\u0440\u0435\u0441",ipv6:"IPv6 \u0430\u0434\u0440\u0435\u0441",cidrv4:"IPv4 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D",cidrv6:"IPv6 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D",base64:"base64-\u043A\u043E\u0434\u0438\u0440\u0430\u043D \u043D\u0438\u0437",base64url:"base64url-\u043A\u043E\u0434\u0438\u0440\u0430\u043D \u043D\u0438\u0437",json_string:"JSON \u043D\u0438\u0437",e164:"E.164 \u043D\u043E\u043C\u0435\u0440",jwt:"JWT",template_literal:"\u0432\u0445\u043E\u0434"},n={nan:"NaN",number:"\u0447\u0438\u0441\u043B\u043E",array:"\u043C\u0430\u0441\u0438\u0432"};return o=>{switch(o.code){case"invalid_type":{const s=n[o.expected]??o.expected,i=Ut(o.input),a=n[i]??i;return/^[A-Z]/.test(o.expected)?`\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u0432\u0445\u043E\u0434: \u043E\u0447\u0430\u043A\u0432\u0430\u043D instanceof ${o.expected}, \u043F\u043E\u043B\u0443\u0447\u0435\u043D ${a}`:`\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u0432\u0445\u043E\u0434: \u043E\u0447\u0430\u043A\u0432\u0430\u043D ${s}, \u043F\u043E\u043B\u0443\u0447\u0435\u043D ${a}`}case"invalid_value":return o.values.length===1?`\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u0432\u0445\u043E\u0434: \u043E\u0447\u0430\u043A\u0432\u0430\u043D ${Ot(o.values[0])}`:`\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u0430 \u043E\u043F\u0446\u0438\u044F: \u043E\u0447\u0430\u043A\u0432\u0430\u043D\u043E \u0435\u0434\u043D\u043E \u043E\u0442 ${Ye(o.values,"|")}`;case"too_big":{const s=o.inclusive?"<=":"<",i=t(o.origin);return i?`\u0422\u0432\u044A\u0440\u0434\u0435 \u0433\u043E\u043B\u044F\u043C\u043E: \u043E\u0447\u0430\u043A\u0432\u0430 \u0441\u0435 ${o.origin??"\u0441\u0442\u043E\u0439\u043D\u043E\u0441\u0442"} \u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430 ${s}${o.maximum.toString()} ${i.unit??"\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0430"}`:`\u0422\u0432\u044A\u0440\u0434\u0435 \u0433\u043E\u043B\u044F\u043C\u043E: \u043E\u0447\u0430\u043A\u0432\u0430 \u0441\u0435 ${o.origin??"\u0441\u0442\u043E\u0439\u043D\u043E\u0441\u0442"} \u0434\u0430 \u0431\u044A\u0434\u0435 ${s}${o.maximum.toString()}`}case"too_small":{const s=o.inclusive?">=":">",i=t(o.origin);return i?`\u0422\u0432\u044A\u0440\u0434\u0435 \u043C\u0430\u043B\u043A\u043E: \u043E\u0447\u0430\u043A\u0432\u0430 \u0441\u0435 ${o.origin} \u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430 ${s}${o.minimum.toString()} ${i.unit}`:`\u0422\u0432\u044A\u0440\u0434\u0435 \u043C\u0430\u043B\u043A\u043E: \u043E\u0447\u0430\u043A\u0432\u0430 \u0441\u0435 ${o.origin} \u0434\u0430 \u0431\u044A\u0434\u0435 ${s}${o.minimum.toString()}`}case"invalid_format":{const s=o;if(s.format==="starts_with")return`\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u043D\u0438\u0437: \u0442\u0440\u044F\u0431\u0432\u0430 \u0434\u0430 \u0437\u0430\u043F\u043E\u0447\u0432\u0430 \u0441 "${s.prefix}"`;if(s.format==="ends_with")return`\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u043D\u0438\u0437: \u0442\u0440\u044F\u0431\u0432\u0430 \u0434\u0430 \u0437\u0430\u0432\u044A\u0440\u0448\u0432\u0430 \u0441 "${s.suffix}"`;if(s.format==="includes")return`\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u043D\u0438\u0437: \u0442\u0440\u044F\u0431\u0432\u0430 \u0434\u0430 \u0432\u043A\u043B\u044E\u0447\u0432\u0430 "${s.includes}"`;if(s.format==="regex")return`\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u043D\u0438\u0437: \u0442\u0440\u044F\u0431\u0432\u0430 \u0434\u0430 \u0441\u044A\u0432\u043F\u0430\u0434\u0430 \u0441 ${s.pattern}`;let i="\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D";return s.format==="emoji"&&(i="\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u043E"),s.format==="datetime"&&(i="\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u043E"),s.format==="date"&&(i="\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u0430"),s.format==="time"&&(i="\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u043E"),s.format==="duration"&&(i="\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u0430"),`${i} ${r[s.format]??o.format}`}case"not_multiple_of":return`\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u043E \u0447\u0438\u0441\u043B\u043E: \u0442\u0440\u044F\u0431\u0432\u0430 \u0434\u0430 \u0431\u044A\u0434\u0435 \u043A\u0440\u0430\u0442\u043D\u043E \u043D\u0430 ${o.divisor}`;case"unrecognized_keys":return`\u041D\u0435\u0440\u0430\u0437\u043F\u043E\u0437\u043D\u0430\u0442${o.keys.length>1?"\u0438":""} \u043A\u043B\u044E\u0447${o.keys.length>1?"\u043E\u0432\u0435":""}: ${Ye(o.keys,", ")}`;case"invalid_key":return`\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u043A\u043B\u044E\u0447 \u0432 ${o.origin}`;case"invalid_union":return"\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u0432\u0445\u043E\u0434";case"invalid_element":return`\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u0430 \u0441\u0442\u043E\u0439\u043D\u043E\u0441\u0442 \u0432 ${o.origin}`;default:return"\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u0432\u0445\u043E\u0434"}}}}});function bfr(){return{localeError:Khe()}}var Khe,Tfr=S({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ca.js"(){kt(),Khe=()=>{const e={string:{unit:"car\xE0cters",verb:"contenir"},file:{unit:"bytes",verb:"contenir"},array:{unit:"elements",verb:"contenir"},set:{unit:"elements",verb:"contenir"}};function t(o){return e[o]??null}const r={regex:"entrada",email:"adre\xE7a electr\xF2nica",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data i hora ISO",date:"data ISO",time:"hora ISO",duration:"durada ISO",ipv4:"adre\xE7a IPv4",ipv6:"adre\xE7a IPv6",cidrv4:"rang IPv4",cidrv6:"rang IPv6",base64:"cadena codificada en base64",base64url:"cadena codificada en base64url",json_string:"cadena JSON",e164:"n\xFAmero E.164",jwt:"JWT",template_literal:"entrada"},n={nan:"NaN"};return o=>{switch(o.code){case"invalid_type":{const s=n[o.expected]??o.expected,i=Ut(o.input),a=n[i]??i;return/^[A-Z]/.test(o.expected)?`Tipus inv\xE0lid: s'esperava instanceof ${o.expected}, s'ha rebut ${a}`:`Tipus inv\xE0lid: s'esperava ${s}, s'ha rebut ${a}`}case"invalid_value":return o.values.length===1?`Valor inv\xE0lid: s'esperava ${Ot(o.values[0])}`:`Opci\xF3 inv\xE0lida: s'esperava una de ${Ye(o.values," o ")}`;case"too_big":{const s=o.inclusive?"com a m\xE0xim":"menys de",i=t(o.origin);return i?`Massa gran: s'esperava que ${o.origin??"el valor"} contingu\xE9s ${s} ${o.maximum.toString()} ${i.unit??"elements"}`:`Massa gran: s'esperava que ${o.origin??"el valor"} fos ${s} ${o.maximum.toString()}`}case"too_small":{const s=o.inclusive?"com a m\xEDnim":"m\xE9s de",i=t(o.origin);return i?`Massa petit: s'esperava que ${o.origin} contingu\xE9s ${s} ${o.minimum.toString()} ${i.unit}`:`Massa petit: s'esperava que ${o.origin} fos ${s} ${o.minimum.toString()}`}case"invalid_format":{const s=o;return s.format==="starts_with"?`Format inv\xE0lid: ha de comen\xE7ar amb "${s.prefix}"`:s.format==="ends_with"?`Format inv\xE0lid: ha d'acabar amb "${s.suffix}"`:s.format==="includes"?`Format inv\xE0lid: ha d'incloure "${s.includes}"`:s.format==="regex"?`Format inv\xE0lid: ha de coincidir amb el patr\xF3 ${s.pattern}`:`Format inv\xE0lid per a ${r[s.format]??o.format}`}case"not_multiple_of":return`N\xFAmero inv\xE0lid: ha de ser m\xFAltiple de ${o.divisor}`;case"unrecognized_keys":return`Clau${o.keys.length>1?"s":""} no reconeguda${o.keys.length>1?"s":""}: ${Ye(o.keys,", ")}`;case"invalid_key":return`Clau inv\xE0lida a ${o.origin}`;case"invalid_union":return"Entrada inv\xE0lida";case"invalid_element":return`Element inv\xE0lid a ${o.origin}`;default:return"Entrada inv\xE0lida"}}}}});function Efr(){return{localeError:Jhe()}}var Jhe,Sfr=S({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/cs.js"(){kt(),Jhe=()=>{const e={string:{unit:"znak\u016F",verb:"m\xEDt"},file:{unit:"bajt\u016F",verb:"m\xEDt"},array:{unit:"prvk\u016F",verb:"m\xEDt"},set:{unit:"prvk\u016F",verb:"m\xEDt"}};function t(o){return e[o]??null}const r={regex:"regul\xE1rn\xED v\xFDraz",email:"e-mailov\xE1 adresa",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"datum a \u010Das ve form\xE1tu ISO",date:"datum ve form\xE1tu ISO",time:"\u010Das ve form\xE1tu ISO",duration:"doba trv\xE1n\xED ISO",ipv4:"IPv4 adresa",ipv6:"IPv6 adresa",cidrv4:"rozsah IPv4",cidrv6:"rozsah IPv6",base64:"\u0159et\u011Bzec zak\xF3dovan\xFD ve form\xE1tu base64",base64url:"\u0159et\u011Bzec zak\xF3dovan\xFD ve form\xE1tu base64url",json_string:"\u0159et\u011Bzec ve form\xE1tu JSON",e164:"\u010D\xEDslo E.164",jwt:"JWT",template_literal:"vstup"},n={nan:"NaN",number:"\u010D\xEDslo",string:"\u0159et\u011Bzec",function:"funkce",array:"pole"};return o=>{switch(o.code){case"invalid_type":{const s=n[o.expected]??o.expected,i=Ut(o.input),a=n[i]??i;return/^[A-Z]/.test(o.expected)?`Neplatn\xFD vstup: o\u010Dek\xE1v\xE1no instanceof ${o.expected}, obdr\u017Eeno ${a}`:`Neplatn\xFD vstup: o\u010Dek\xE1v\xE1no ${s}, obdr\u017Eeno ${a}`}case"invalid_value":return o.values.length===1?`Neplatn\xFD vstup: o\u010Dek\xE1v\xE1no ${Ot(o.values[0])}`:`Neplatn\xE1 mo\u017Enost: o\u010Dek\xE1v\xE1na jedna z hodnot ${Ye(o.values,"|")}`;case"too_big":{const s=o.inclusive?"<=":"<",i=t(o.origin);return i?`Hodnota je p\u0159\xEDli\u0161 velk\xE1: ${o.origin??"hodnota"} mus\xED m\xEDt ${s}${o.maximum.toString()} ${i.unit??"prvk\u016F"}`:`Hodnota je p\u0159\xEDli\u0161 velk\xE1: ${o.origin??"hodnota"} mus\xED b\xFDt ${s}${o.maximum.toString()}`}case"too_small":{const s=o.inclusive?">=":">",i=t(o.origin);return i?`Hodnota je p\u0159\xEDli\u0161 mal\xE1: ${o.origin??"hodnota"} mus\xED m\xEDt ${s}${o.minimum.toString()} ${i.unit??"prvk\u016F"}`:`Hodnota je p\u0159\xEDli\u0161 mal\xE1: ${o.origin??"hodnota"} mus\xED b\xFDt ${s}${o.minimum.toString()}`}case"invalid_format":{const s=o;return s.format==="starts_with"?`Neplatn\xFD \u0159et\u011Bzec: mus\xED za\u010D\xEDnat na "${s.prefix}"`:s.format==="ends_with"?`Neplatn\xFD \u0159et\u011Bzec: mus\xED kon\u010Dit na "${s.suffix}"`:s.format==="includes"?`Neplatn\xFD \u0159et\u011Bzec: mus\xED obsahovat "${s.includes}"`:s.format==="regex"?`Neplatn\xFD \u0159et\u011Bzec: mus\xED odpov\xEDdat vzoru ${s.pattern}`:`Neplatn\xFD form\xE1t ${r[s.format]??o.format}`}case"not_multiple_of":return`Neplatn\xE9 \u010D\xEDslo: mus\xED b\xFDt n\xE1sobkem ${o.divisor}`;case"unrecognized_keys":return`Nezn\xE1m\xE9 kl\xED\u010De: ${Ye(o.keys,", ")}`;case"invalid_key":return`Neplatn\xFD kl\xED\u010D v ${o.origin}`;case"invalid_union":return"Neplatn\xFD vstup";case"invalid_element":return`Neplatn\xE1 hodnota v ${o.origin}`;default:return"Neplatn\xFD vstup"}}}}});function Cfr(){return{localeError:Yhe()}}var Yhe,kfr=S({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/da.js"(){kt(),Yhe=()=>{const e={string:{unit:"tegn",verb:"havde"},file:{unit:"bytes",verb:"havde"},array:{unit:"elementer",verb:"indeholdt"},set:{unit:"elementer",verb:"indeholdt"}};function t(o){return e[o]??null}const r={regex:"input",email:"e-mailadresse",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO dato- og klokkesl\xE6t",date:"ISO-dato",time:"ISO-klokkesl\xE6t",duration:"ISO-varighed",ipv4:"IPv4-omr\xE5de",ipv6:"IPv6-omr\xE5de",cidrv4:"IPv4-spektrum",cidrv6:"IPv6-spektrum",base64:"base64-kodet streng",base64url:"base64url-kodet streng",json_string:"JSON-streng",e164:"E.164-nummer",jwt:"JWT",template_literal:"input"},n={nan:"NaN",string:"streng",number:"tal",boolean:"boolean",array:"liste",object:"objekt",set:"s\xE6t",file:"fil"};return o=>{switch(o.code){case"invalid_type":{const s=n[o.expected]??o.expected,i=Ut(o.input),a=n[i]??i;return/^[A-Z]/.test(o.expected)?`Ugyldigt input: forventede instanceof ${o.expected}, fik ${a}`:`Ugyldigt input: forventede ${s}, fik ${a}`}case"invalid_value":return o.values.length===1?`Ugyldig v\xE6rdi: forventede ${Ot(o.values[0])}`:`Ugyldigt valg: forventede en af f\xF8lgende ${Ye(o.values,"|")}`;case"too_big":{const s=o.inclusive?"<=":"<",i=t(o.origin),a=n[o.origin]??o.origin;return i?`For stor: forventede ${a??"value"} ${i.verb} ${s} ${o.maximum.toString()} ${i.unit??"elementer"}`:`For stor: forventede ${a??"value"} havde ${s} ${o.maximum.toString()}`}case"too_small":{const s=o.inclusive?">=":">",i=t(o.origin),a=n[o.origin]??o.origin;return i?`For lille: forventede ${a} ${i.verb} ${s} ${o.minimum.toString()} ${i.unit}`:`For lille: forventede ${a} havde ${s} ${o.minimum.toString()}`}case"invalid_format":{const s=o;return s.format==="starts_with"?`Ugyldig streng: skal starte med "${s.prefix}"`:s.format==="ends_with"?`Ugyldig streng: skal ende med "${s.suffix}"`:s.format==="includes"?`Ugyldig streng: skal indeholde "${s.includes}"`:s.format==="regex"?`Ugyldig streng: skal matche m\xF8nsteret ${s.pattern}`:`Ugyldig ${r[s.format]??o.format}`}case"not_multiple_of":return`Ugyldigt tal: skal v\xE6re deleligt med ${o.divisor}`;case"unrecognized_keys":return`${o.keys.length>1?"Ukendte n\xF8gler":"Ukendt n\xF8gle"}: ${Ye(o.keys,", ")}`;case"invalid_key":return`Ugyldig n\xF8gle i ${o.origin}`;case"invalid_union":return"Ugyldigt input: matcher ingen af de tilladte typer";case"invalid_element":return`Ugyldig v\xE6rdi i ${o.origin}`;default:return"Ugyldigt input"}}}}});function xfr(){return{localeError:Zhe()}}var Zhe,Afr=S({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/de.js"(){kt(),Zhe=()=>{const e={string:{unit:"Zeichen",verb:"zu haben"},file:{unit:"Bytes",verb:"zu haben"},array:{unit:"Elemente",verb:"zu haben"},set:{unit:"Elemente",verb:"zu haben"}};function t(o){return e[o]??null}const r={regex:"Eingabe",email:"E-Mail-Adresse",url:"URL",emoji:"Emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-Datum und -Uhrzeit",date:"ISO-Datum",time:"ISO-Uhrzeit",duration:"ISO-Dauer",ipv4:"IPv4-Adresse",ipv6:"IPv6-Adresse",cidrv4:"IPv4-Bereich",cidrv6:"IPv6-Bereich",base64:"Base64-codierter String",base64url:"Base64-URL-codierter String",json_string:"JSON-String",e164:"E.164-Nummer",jwt:"JWT",template_literal:"Eingabe"},n={nan:"NaN",number:"Zahl",array:"Array"};return o=>{switch(o.code){case"invalid_type":{const s=n[o.expected]??o.expected,i=Ut(o.input),a=n[i]??i;return/^[A-Z]/.test(o.expected)?`Ung\xFCltige Eingabe: erwartet instanceof ${o.expected}, erhalten ${a}`:`Ung\xFCltige Eingabe: erwartet ${s}, erhalten ${a}`}case"invalid_value":return o.values.length===1?`Ung\xFCltige Eingabe: erwartet ${Ot(o.values[0])}`:`Ung\xFCltige Option: erwartet eine von ${Ye(o.values,"|")}`;case"too_big":{const s=o.inclusive?"<=":"<",i=t(o.origin);return i?`Zu gro\xDF: erwartet, dass ${o.origin??"Wert"} ${s}${o.maximum.toString()} ${i.unit??"Elemente"} hat`:`Zu gro\xDF: erwartet, dass ${o.origin??"Wert"} ${s}${o.maximum.toString()} ist`}case"too_small":{const s=o.inclusive?">=":">",i=t(o.origin);return i?`Zu klein: erwartet, dass ${o.origin} ${s}${o.minimum.toString()} ${i.unit} hat`:`Zu klein: erwartet, dass ${o.origin} ${s}${o.minimum.toString()} ist`}case"invalid_format":{const s=o;return s.format==="starts_with"?`Ung\xFCltiger String: muss mit "${s.prefix}" beginnen`:s.format==="ends_with"?`Ung\xFCltiger String: muss mit "${s.suffix}" enden`:s.format==="includes"?`Ung\xFCltiger String: muss "${s.includes}" enthalten`:s.format==="regex"?`Ung\xFCltiger String: muss dem Muster ${s.pattern} entsprechen`:`Ung\xFCltig: ${r[s.format]??o.format}`}case"not_multiple_of":return`Ung\xFCltige Zahl: muss ein Vielfaches von ${o.divisor} sein`;case"unrecognized_keys":return`${o.keys.length>1?"Unbekannte Schl\xFCssel":"Unbekannter Schl\xFCssel"}: ${Ye(o.keys,", ")}`;case"invalid_key":return`Ung\xFCltiger Schl\xFCssel in ${o.origin}`;case"invalid_union":return"Ung\xFCltige Eingabe";case"invalid_element":return`Ung\xFCltiger Wert in ${o.origin}`;default:return"Ung\xFCltige Eingabe"}}}}});function Xhe(){return{localeError:Qhe()}}var Qhe,efe=S({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/en.js"(){kt(),Qhe=()=>{const e={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"},map:{unit:"entries",verb:"to have"}};function t(o){return e[o]??null}const r={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",mac:"MAC address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"},n={nan:"NaN"};return o=>{switch(o.code){case"invalid_type":{const s=n[o.expected]??o.expected,i=Ut(o.input),a=n[i]??i;return`Invalid input: expected ${s}, received ${a}`}case"invalid_value":return o.values.length===1?`Invalid input: expected ${Ot(o.values[0])}`:`Invalid option: expected one of ${Ye(o.values,"|")}`;case"too_big":{const s=o.inclusive?"<=":"<",i=t(o.origin);return i?`Too big: expected ${o.origin??"value"} to have ${s}${o.maximum.toString()} ${i.unit??"elements"}`:`Too big: expected ${o.origin??"value"} to be ${s}${o.maximum.toString()}`}case"too_small":{const s=o.inclusive?">=":">",i=t(o.origin);return i?`Too small: expected ${o.origin} to have ${s}${o.minimum.toString()} ${i.unit}`:`Too small: expected ${o.origin} to be ${s}${o.minimum.toString()}`}case"invalid_format":{const s=o;return s.format==="starts_with"?`Invalid string: must start with "${s.prefix}"`:s.format==="ends_with"?`Invalid string: must end with "${s.suffix}"`:s.format==="includes"?`Invalid string: must include "${s.includes}"`:s.format==="regex"?`Invalid string: must match pattern ${s.pattern}`:`Invalid ${r[s.format]??o.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${o.divisor}`;case"unrecognized_keys":return`Unrecognized key${o.keys.length>1?"s":""}: ${Ye(o.keys,", ")}`;case"invalid_key":return`Invalid key in ${o.origin}`;case"invalid_union":return"Invalid input";case"invalid_element":return`Invalid value in ${o.origin}`;default:return"Invalid input"}}}}});function Ifr(){return{localeError:tfe()}}var tfe,Rfr=S({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/eo.js"(){kt(),tfe=()=>{const e={string:{unit:"karaktrojn",verb:"havi"},file:{unit:"bajtojn",verb:"havi"},array:{unit:"elementojn",verb:"havi"},set:{unit:"elementojn",verb:"havi"}};function t(o){return e[o]??null}const r={regex:"enigo",email:"retadreso",url:"URL",emoji:"emo\u011Dio",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-datotempo",date:"ISO-dato",time:"ISO-tempo",duration:"ISO-da\u016Dro",ipv4:"IPv4-adreso",ipv6:"IPv6-adreso",cidrv4:"IPv4-rango",cidrv6:"IPv6-rango",base64:"64-ume kodita karaktraro",base64url:"URL-64-ume kodita karaktraro",json_string:"JSON-karaktraro",e164:"E.164-nombro",jwt:"JWT",template_literal:"enigo"},n={nan:"NaN",number:"nombro",array:"tabelo",null:"senvalora"};return o=>{switch(o.code){case"invalid_type":{const s=n[o.expected]??o.expected,i=Ut(o.input),a=n[i]??i;return/^[A-Z]/.test(o.expected)?`Nevalida enigo: atendi\u011Dis instanceof ${o.expected}, ricevi\u011Dis ${a}`:`Nevalida enigo: atendi\u011Dis ${s}, ricevi\u011Dis ${a}`}case"invalid_value":return o.values.length===1?`Nevalida enigo: atendi\u011Dis ${Ot(o.values[0])}`:`Nevalida opcio: atendi\u011Dis unu el ${Ye(o.values,"|")}`;case"too_big":{const s=o.inclusive?"<=":"<",i=t(o.origin);return i?`Tro granda: atendi\u011Dis ke ${o.origin??"valoro"} havu ${s}${o.maximum.toString()} ${i.unit??"elementojn"}`:`Tro granda: atendi\u011Dis ke ${o.origin??"valoro"} havu ${s}${o.maximum.toString()}`}case"too_small":{const s=o.inclusive?">=":">",i=t(o.origin);return i?`Tro malgranda: atendi\u011Dis ke ${o.origin} havu ${s}${o.minimum.toString()} ${i.unit}`:`Tro malgranda: atendi\u011Dis ke ${o.origin} estu ${s}${o.minimum.toString()}`}case"invalid_format":{const s=o;return s.format==="starts_with"?`Nevalida karaktraro: devas komenci\u011Di per "${s.prefix}"`:s.format==="ends_with"?`Nevalida karaktraro: devas fini\u011Di per "${s.suffix}"`:s.format==="includes"?`Nevalida karaktraro: devas inkluzivi "${s.includes}"`:s.format==="regex"?`Nevalida karaktraro: devas kongrui kun la modelo ${s.pattern}`:`Nevalida ${r[s.format]??o.format}`}case"not_multiple_of":return`Nevalida nombro: devas esti oblo de ${o.divisor}`;case"unrecognized_keys":return`Nekonata${o.keys.length>1?"j":""} \u015Dlosilo${o.keys.length>1?"j":""}: ${Ye(o.keys,", ")}`;case"invalid_key":return`Nevalida \u015Dlosilo en ${o.origin}`;case"invalid_union":return"Nevalida enigo";case"invalid_element":return`Nevalida valoro en ${o.origin}`;default:return"Nevalida enigo"}}}}});function Mfr(){return{localeError:rfe()}}var rfe,Pfr=S({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/es.js"(){kt(),rfe=()=>{const e={string:{unit:"caracteres",verb:"tener"},file:{unit:"bytes",verb:"tener"},array:{unit:"elementos",verb:"tener"},set:{unit:"elementos",verb:"tener"}};function t(o){return e[o]??null}const r={regex:"entrada",email:"direcci\xF3n de correo electr\xF3nico",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"fecha y hora ISO",date:"fecha ISO",time:"hora ISO",duration:"duraci\xF3n ISO",ipv4:"direcci\xF3n IPv4",ipv6:"direcci\xF3n IPv6",cidrv4:"rango IPv4",cidrv6:"rango IPv6",base64:"cadena codificada en base64",base64url:"URL codificada en base64",json_string:"cadena JSON",e164:"n\xFAmero E.164",jwt:"JWT",template_literal:"entrada"},n={nan:"NaN",string:"texto",number:"n\xFAmero",boolean:"booleano",array:"arreglo",object:"objeto",set:"conjunto",file:"archivo",date:"fecha",bigint:"n\xFAmero grande",symbol:"s\xEDmbolo",undefined:"indefinido",null:"nulo",function:"funci\xF3n",map:"mapa",record:"registro",tuple:"tupla",enum:"enumeraci\xF3n",union:"uni\xF3n",literal:"literal",promise:"promesa",void:"vac\xEDo",never:"nunca",unknown:"desconocido",any:"cualquiera"};return o=>{switch(o.code){case"invalid_type":{const s=n[o.expected]??o.expected,i=Ut(o.input),a=n[i]??i;return/^[A-Z]/.test(o.expected)?`Entrada inv\xE1lida: se esperaba instanceof ${o.expected}, recibido ${a}`:`Entrada inv\xE1lida: se esperaba ${s}, recibido ${a}`}case"invalid_value":return o.values.length===1?`Entrada inv\xE1lida: se esperaba ${Ot(o.values[0])}`:`Opci\xF3n inv\xE1lida: se esperaba una de ${Ye(o.values,"|")}`;case"too_big":{const s=o.inclusive?"<=":"<",i=t(o.origin),a=n[o.origin]??o.origin;return i?`Demasiado grande: se esperaba que ${a??"valor"} tuviera ${s}${o.maximum.toString()} ${i.unit??"elementos"}`:`Demasiado grande: se esperaba que ${a??"valor"} fuera ${s}${o.maximum.toString()}`}case"too_small":{const s=o.inclusive?">=":">",i=t(o.origin),a=n[o.origin]??o.origin;return i?`Demasiado peque\xF1o: se esperaba que ${a} tuviera ${s}${o.minimum.toString()} ${i.unit}`:`Demasiado peque\xF1o: se esperaba que ${a} fuera ${s}${o.minimum.toString()}`}case"invalid_format":{const s=o;return s.format==="starts_with"?`Cadena inv\xE1lida: debe comenzar con "${s.prefix}"`:s.format==="ends_with"?`Cadena inv\xE1lida: debe terminar en "${s.suffix}"`:s.format==="includes"?`Cadena inv\xE1lida: debe incluir "${s.includes}"`:s.format==="regex"?`Cadena inv\xE1lida: debe coincidir con el patr\xF3n ${s.pattern}`:`Inv\xE1lido ${r[s.format]??o.format}`}case"not_multiple_of":return`N\xFAmero inv\xE1lido: debe ser m\xFAltiplo de ${o.divisor}`;case"unrecognized_keys":return`Llave${o.keys.length>1?"s":""} desconocida${o.keys.length>1?"s":""}: ${Ye(o.keys,", ")}`;case"invalid_key":return`Llave inv\xE1lida en ${n[o.origin]??o.origin}`;case"invalid_union":return"Entrada inv\xE1lida";case"invalid_element":return`Valor inv\xE1lido en ${n[o.origin]??o.origin}`;default:return"Entrada inv\xE1lida"}}}}});function Dfr(){return{localeError:nfe()}}var nfe,Ofr=S({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/fa.js"(){kt(),nfe=()=>{const e={string:{unit:"\u06A9\u0627\u0631\u0627\u06A9\u062A\u0631",verb:"\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F"},file:{unit:"\u0628\u0627\u06CC\u062A",verb:"\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F"},array:{unit:"\u0622\u06CC\u062A\u0645",verb:"\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F"},set:{unit:"\u0622\u06CC\u062A\u0645",verb:"\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F"}};function t(o){return e[o]??null}const r={regex:"\u0648\u0631\u0648\u062F\u06CC",email:"\u0622\u062F\u0631\u0633 \u0627\u06CC\u0645\u06CC\u0644",url:"URL",emoji:"\u0627\u06CC\u0645\u0648\u062C\u06CC",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"\u062A\u0627\u0631\u06CC\u062E \u0648 \u0632\u0645\u0627\u0646 \u0627\u06CC\u0632\u0648",date:"\u062A\u0627\u0631\u06CC\u062E \u0627\u06CC\u0632\u0648",time:"\u0632\u0645\u0627\u0646 \u0627\u06CC\u0632\u0648",duration:"\u0645\u062F\u062A \u0632\u0645\u0627\u0646 \u0627\u06CC\u0632\u0648",ipv4:"IPv4 \u0622\u062F\u0631\u0633",ipv6:"IPv6 \u0622\u062F\u0631\u0633",cidrv4:"IPv4 \u062F\u0627\u0645\u0646\u0647",cidrv6:"IPv6 \u062F\u0627\u0645\u0646\u0647",base64:"base64-encoded \u0631\u0634\u062A\u0647",base64url:"base64url-encoded \u0631\u0634\u062A\u0647",json_string:"JSON \u0631\u0634\u062A\u0647",e164:"E.164 \u0639\u062F\u062F",jwt:"JWT",template_literal:"\u0648\u0631\u0648\u062F\u06CC"},n={nan:"NaN",number:"\u0639\u062F\u062F",array:"\u0622\u0631\u0627\u06CC\u0647"};return o=>{switch(o.code){case"invalid_type":{const s=n[o.expected]??o.expected,i=Ut(o.input),a=n[i]??i;return/^[A-Z]/.test(o.expected)?`\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A instanceof ${o.expected} \u0645\u06CC\u200C\u0628\u0648\u062F\u060C ${a} \u062F\u0631\u06CC\u0627\u0641\u062A \u0634\u062F`:`\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A ${s} \u0645\u06CC\u200C\u0628\u0648\u062F\u060C ${a} \u062F\u0631\u06CC\u0627\u0641\u062A \u0634\u062F`}case"invalid_value":return o.values.length===1?`\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A ${Ot(o.values[0])} \u0645\u06CC\u200C\u0628\u0648\u062F`:`\u06AF\u0632\u06CC\u0646\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A \u06CC\u06A9\u06CC \u0627\u0632 ${Ye(o.values,"|")} \u0645\u06CC\u200C\u0628\u0648\u062F`;case"too_big":{const s=o.inclusive?"<=":"<",i=t(o.origin);return i?`\u062E\u06CC\u0644\u06CC \u0628\u0632\u0631\u06AF: ${o.origin??"\u0645\u0642\u062F\u0627\u0631"} \u0628\u0627\u06CC\u062F ${s}${o.maximum.toString()} ${i.unit??"\u0639\u0646\u0635\u0631"} \u0628\u0627\u0634\u062F`:`\u062E\u06CC\u0644\u06CC \u0628\u0632\u0631\u06AF: ${o.origin??"\u0645\u0642\u062F\u0627\u0631"} \u0628\u0627\u06CC\u062F ${s}${o.maximum.toString()} \u0628\u0627\u0634\u062F`}case"too_small":{const s=o.inclusive?">=":">",i=t(o.origin);return i?`\u062E\u06CC\u0644\u06CC \u06A9\u0648\u0686\u06A9: ${o.origin} \u0628\u0627\u06CC\u062F ${s}${o.minimum.toString()} ${i.unit} \u0628\u0627\u0634\u062F`:`\u062E\u06CC\u0644\u06CC \u06A9\u0648\u0686\u06A9: ${o.origin} \u0628\u0627\u06CC\u062F ${s}${o.minimum.toString()} \u0628\u0627\u0634\u062F`}case"invalid_format":{const s=o;return s.format==="starts_with"?`\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0628\u0627 "${s.prefix}" \u0634\u0631\u0648\u0639 \u0634\u0648\u062F`:s.format==="ends_with"?`\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0628\u0627 "${s.suffix}" \u062A\u0645\u0627\u0645 \u0634\u0648\u062F`:s.format==="includes"?`\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0634\u0627\u0645\u0644 "${s.includes}" \u0628\u0627\u0634\u062F`:s.format==="regex"?`\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0628\u0627 \u0627\u0644\u06AF\u0648\u06CC ${s.pattern} \u0645\u0637\u0627\u0628\u0642\u062A \u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F`:`${r[s.format]??o.format} \u0646\u0627\u0645\u0639\u062A\u0628\u0631`}case"not_multiple_of":return`\u0639\u062F\u062F \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0645\u0636\u0631\u0628 ${o.divisor} \u0628\u0627\u0634\u062F`;case"unrecognized_keys":return`\u06A9\u0644\u06CC\u062F${o.keys.length>1?"\u0647\u0627\u06CC":""} \u0646\u0627\u0634\u0646\u0627\u0633: ${Ye(o.keys,", ")}`;case"invalid_key":return`\u06A9\u0644\u06CC\u062F \u0646\u0627\u0634\u0646\u0627\u0633 \u062F\u0631 ${o.origin}`;case"invalid_union":return"\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631";case"invalid_element":return`\u0645\u0642\u062F\u0627\u0631 \u0646\u0627\u0645\u0639\u062A\u0628\u0631 \u062F\u0631 ${o.origin}`;default:return"\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631"}}}}});function Nfr(){return{localeError:ofe()}}var ofe,Lfr=S({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/fi.js"(){kt(),ofe=()=>{const e={string:{unit:"merkki\xE4",subject:"merkkijonon"},file:{unit:"tavua",subject:"tiedoston"},array:{unit:"alkiota",subject:"listan"},set:{unit:"alkiota",subject:"joukon"},number:{unit:"",subject:"luvun"},bigint:{unit:"",subject:"suuren kokonaisluvun"},int:{unit:"",subject:"kokonaisluvun"},date:{unit:"",subject:"p\xE4iv\xE4m\xE4\xE4r\xE4n"}};function t(o){return e[o]??null}const r={regex:"s\xE4\xE4nn\xF6llinen lauseke",email:"s\xE4hk\xF6postiosoite",url:"URL-osoite",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-aikaleima",date:"ISO-p\xE4iv\xE4m\xE4\xE4r\xE4",time:"ISO-aika",duration:"ISO-kesto",ipv4:"IPv4-osoite",ipv6:"IPv6-osoite",cidrv4:"IPv4-alue",cidrv6:"IPv6-alue",base64:"base64-koodattu merkkijono",base64url:"base64url-koodattu merkkijono",json_string:"JSON-merkkijono",e164:"E.164-luku",jwt:"JWT",template_literal:"templaattimerkkijono"},n={nan:"NaN"};return o=>{switch(o.code){case"invalid_type":{const s=n[o.expected]??o.expected,i=Ut(o.input),a=n[i]??i;return/^[A-Z]/.test(o.expected)?`Virheellinen tyyppi: odotettiin instanceof ${o.expected}, oli ${a}`:`Virheellinen tyyppi: odotettiin ${s}, oli ${a}`}case"invalid_value":return o.values.length===1?`Virheellinen sy\xF6te: t\xE4ytyy olla ${Ot(o.values[0])}`:`Virheellinen valinta: t\xE4ytyy olla yksi seuraavista: ${Ye(o.values,"|")}`;case"too_big":{const s=o.inclusive?"<=":"<",i=t(o.origin);return i?`Liian suuri: ${i.subject} t\xE4ytyy olla ${s}${o.maximum.toString()} ${i.unit}`.trim():`Liian suuri: arvon t\xE4ytyy olla ${s}${o.maximum.toString()}`}case"too_small":{const s=o.inclusive?">=":">",i=t(o.origin);return i?`Liian pieni: ${i.subject} t\xE4ytyy olla ${s}${o.minimum.toString()} ${i.unit}`.trim():`Liian pieni: arvon t\xE4ytyy olla ${s}${o.minimum.toString()}`}case"invalid_format":{const s=o;return s.format==="starts_with"?`Virheellinen sy\xF6te: t\xE4ytyy alkaa "${s.prefix}"`:s.format==="ends_with"?`Virheellinen sy\xF6te: t\xE4ytyy loppua "${s.suffix}"`:s.format==="includes"?`Virheellinen sy\xF6te: t\xE4ytyy sis\xE4lt\xE4\xE4 "${s.includes}"`:s.format==="regex"?`Virheellinen sy\xF6te: t\xE4ytyy vastata s\xE4\xE4nn\xF6llist\xE4 lauseketta ${s.pattern}`:`Virheellinen ${r[s.format]??o.format}`}case"not_multiple_of":return`Virheellinen luku: t\xE4ytyy olla luvun ${o.divisor} monikerta`;case"unrecognized_keys":return`${o.keys.length>1?"Tuntemattomat avaimet":"Tuntematon avain"}: ${Ye(o.keys,", ")}`;case"invalid_key":return"Virheellinen avain tietueessa";case"invalid_union":return"Virheellinen unioni";case"invalid_element":return"Virheellinen arvo joukossa";default:return"Virheellinen sy\xF6te"}}}}});function $fr(){return{localeError:sfe()}}var sfe,Ffr=S({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/fr.js"(){kt(),sfe=()=>{const e={string:{unit:"caract\xE8res",verb:"avoir"},file:{unit:"octets",verb:"avoir"},array:{unit:"\xE9l\xE9ments",verb:"avoir"},set:{unit:"\xE9l\xE9ments",verb:"avoir"}};function t(o){return e[o]??null}const r={regex:"entr\xE9e",email:"adresse e-mail",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"date et heure ISO",date:"date ISO",time:"heure ISO",duration:"dur\xE9e ISO",ipv4:"adresse IPv4",ipv6:"adresse IPv6",cidrv4:"plage IPv4",cidrv6:"plage IPv6",base64:"cha\xEEne encod\xE9e en base64",base64url:"cha\xEEne encod\xE9e en base64url",json_string:"cha\xEEne JSON",e164:"num\xE9ro E.164",jwt:"JWT",template_literal:"entr\xE9e"},n={nan:"NaN",number:"nombre",array:"tableau"};return o=>{switch(o.code){case"invalid_type":{const s=n[o.expected]??o.expected,i=Ut(o.input),a=n[i]??i;return/^[A-Z]/.test(o.expected)?`Entr\xE9e invalide : instanceof ${o.expected} attendu, ${a} re\xE7u`:`Entr\xE9e invalide : ${s} attendu, ${a} re\xE7u`}case"invalid_value":return o.values.length===1?`Entr\xE9e invalide : ${Ot(o.values[0])} attendu`:`Option invalide : une valeur parmi ${Ye(o.values,"|")} attendue`;case"too_big":{const s=o.inclusive?"<=":"<",i=t(o.origin);return i?`Trop grand : ${o.origin??"valeur"} doit ${i.verb} ${s}${o.maximum.toString()} ${i.unit??"\xE9l\xE9ment(s)"}`:`Trop grand : ${o.origin??"valeur"} doit \xEAtre ${s}${o.maximum.toString()}`}case"too_small":{const s=o.inclusive?">=":">",i=t(o.origin);return i?`Trop petit : ${o.origin} doit ${i.verb} ${s}${o.minimum.toString()} ${i.unit}`:`Trop petit : ${o.origin} doit \xEAtre ${s}${o.minimum.toString()}`}case"invalid_format":{const s=o;return s.format==="starts_with"?`Cha\xEEne invalide : doit commencer par "${s.prefix}"`:s.format==="ends_with"?`Cha\xEEne invalide : doit se terminer par "${s.suffix}"`:s.format==="includes"?`Cha\xEEne invalide : doit inclure "${s.includes}"`:s.format==="regex"?`Cha\xEEne invalide : doit correspondre au mod\xE8le ${s.pattern}`:`${r[s.format]??o.format} invalide`}case"not_multiple_of":return`Nombre invalide : doit \xEAtre un multiple de ${o.divisor}`;case"unrecognized_keys":return`Cl\xE9${o.keys.length>1?"s":""} non reconnue${o.keys.length>1?"s":""} : ${Ye(o.keys,", ")}`;case"invalid_key":return`Cl\xE9 invalide dans ${o.origin}`;case"invalid_union":return"Entr\xE9e invalide";case"invalid_element":return`Valeur invalide dans ${o.origin}`;default:return"Entr\xE9e invalide"}}}}});function Ufr(){return{localeError:ife()}}var ife,Bfr=S({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/fr-CA.js"(){kt(),ife=()=>{const e={string:{unit:"caract\xE8res",verb:"avoir"},file:{unit:"octets",verb:"avoir"},array:{unit:"\xE9l\xE9ments",verb:"avoir"},set:{unit:"\xE9l\xE9ments",verb:"avoir"}};function t(o){return e[o]??null}const r={regex:"entr\xE9e",email:"adresse courriel",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"date-heure ISO",date:"date ISO",time:"heure ISO",duration:"dur\xE9e ISO",ipv4:"adresse IPv4",ipv6:"adresse IPv6",cidrv4:"plage IPv4",cidrv6:"plage IPv6",base64:"cha\xEEne encod\xE9e en base64",base64url:"cha\xEEne encod\xE9e en base64url",json_string:"cha\xEEne JSON",e164:"num\xE9ro E.164",jwt:"JWT",template_literal:"entr\xE9e"},n={nan:"NaN"};return o=>{switch(o.code){case"invalid_type":{const s=n[o.expected]??o.expected,i=Ut(o.input),a=n[i]??i;return/^[A-Z]/.test(o.expected)?`Entr\xE9e invalide : attendu instanceof ${o.expected}, re\xE7u ${a}`:`Entr\xE9e invalide : attendu ${s}, re\xE7u ${a}`}case"invalid_value":return o.values.length===1?`Entr\xE9e invalide : attendu ${Ot(o.values[0])}`:`Option invalide : attendu l'une des valeurs suivantes ${Ye(o.values,"|")}`;case"too_big":{const s=o.inclusive?"\u2264":"<",i=t(o.origin);return i?`Trop grand : attendu que ${o.origin??"la valeur"} ait ${s}${o.maximum.toString()} ${i.unit}`:`Trop grand : attendu que ${o.origin??"la valeur"} soit ${s}${o.maximum.toString()}`}case"too_small":{const s=o.inclusive?"\u2265":">",i=t(o.origin);return i?`Trop petit : attendu que ${o.origin} ait ${s}${o.minimum.toString()} ${i.unit}`:`Trop petit : attendu que ${o.origin} soit ${s}${o.minimum.toString()}`}case"invalid_format":{const s=o;return s.format==="starts_with"?`Cha\xEEne invalide : doit commencer par "${s.prefix}"`:s.format==="ends_with"?`Cha\xEEne invalide : doit se terminer par "${s.suffix}"`:s.format==="includes"?`Cha\xEEne invalide : doit inclure "${s.includes}"`:s.format==="regex"?`Cha\xEEne invalide : doit correspondre au motif ${s.pattern}`:`${r[s.format]??o.format} invalide`}case"not_multiple_of":return`Nombre invalide : doit \xEAtre un multiple de ${o.divisor}`;case"unrecognized_keys":return`Cl\xE9${o.keys.length>1?"s":""} non reconnue${o.keys.length>1?"s":""} : ${Ye(o.keys,", ")}`;case"invalid_key":return`Cl\xE9 invalide dans ${o.origin}`;case"invalid_union":return"Entr\xE9e invalide";case"invalid_element":return`Valeur invalide dans ${o.origin}`;default:return"Entr\xE9e invalide"}}}}});function zfr(){return{localeError:afe()}}var afe,jfr=S({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/he.js"(){kt(),afe=()=>{const e={string:{label:"\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA",gender:"f"},number:{label:"\u05DE\u05E1\u05E4\u05E8",gender:"m"},boolean:{label:"\u05E2\u05E8\u05DA \u05D1\u05D5\u05DC\u05D9\u05D0\u05E0\u05D9",gender:"m"},bigint:{label:"BigInt",gender:"m"},date:{label:"\u05EA\u05D0\u05E8\u05D9\u05DA",gender:"m"},array:{label:"\u05DE\u05E2\u05E8\u05DA",gender:"m"},object:{label:"\u05D0\u05D5\u05D1\u05D9\u05D9\u05E7\u05D8",gender:"m"},null:{label:"\u05E2\u05E8\u05DA \u05E8\u05D9\u05E7 (null)",gender:"m"},undefined:{label:"\u05E2\u05E8\u05DA \u05DC\u05D0 \u05DE\u05D5\u05D2\u05D3\u05E8 (undefined)",gender:"m"},symbol:{label:"\u05E1\u05D9\u05DE\u05D1\u05D5\u05DC (Symbol)",gender:"m"},function:{label:"\u05E4\u05D5\u05E0\u05E7\u05E6\u05D9\u05D4",gender:"f"},map:{label:"\u05DE\u05E4\u05D4 (Map)",gender:"f"},set:{label:"\u05E7\u05D1\u05D5\u05E6\u05D4 (Set)",gender:"f"},file:{label:"\u05E7\u05D5\u05D1\u05E5",gender:"m"},promise:{label:"Promise",gender:"m"},NaN:{label:"NaN",gender:"m"},unknown:{label:"\u05E2\u05E8\u05DA \u05DC\u05D0 \u05D9\u05D3\u05D5\u05E2",gender:"m"},value:{label:"\u05E2\u05E8\u05DA",gender:"m"}},t={string:{unit:"\u05EA\u05D5\u05D5\u05D9\u05DD",shortLabel:"\u05E7\u05E6\u05E8",longLabel:"\u05D0\u05E8\u05D5\u05DA"},file:{unit:"\u05D1\u05D9\u05D9\u05D8\u05D9\u05DD",shortLabel:"\u05E7\u05D8\u05DF",longLabel:"\u05D2\u05D3\u05D5\u05DC"},array:{unit:"\u05E4\u05E8\u05D9\u05D8\u05D9\u05DD",shortLabel:"\u05E7\u05D8\u05DF",longLabel:"\u05D2\u05D3\u05D5\u05DC"},set:{unit:"\u05E4\u05E8\u05D9\u05D8\u05D9\u05DD",shortLabel:"\u05E7\u05D8\u05DF",longLabel:"\u05D2\u05D3\u05D5\u05DC"},number:{unit:"",shortLabel:"\u05E7\u05D8\u05DF",longLabel:"\u05D2\u05D3\u05D5\u05DC"}},r=c=>c?e[c]:void 0,n=c=>{const u=r(c);return u?u.label:c??e.unknown.label},o=c=>`\u05D4${n(c)}`,s=c=>(r(c)?.gender??"m")==="f"?"\u05E6\u05E8\u05D9\u05DB\u05D4 \u05DC\u05D4\u05D9\u05D5\u05EA":"\u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA",i=c=>c?t[c]??null:null,a={regex:{label:"\u05E7\u05DC\u05D8",gender:"m"},email:{label:"\u05DB\u05EA\u05D5\u05D1\u05EA \u05D0\u05D9\u05DE\u05D9\u05D9\u05DC",gender:"f"},url:{label:"\u05DB\u05EA\u05D5\u05D1\u05EA \u05E8\u05E9\u05EA",gender:"f"},emoji:{label:"\u05D0\u05D9\u05DE\u05D5\u05D2'\u05D9",gender:"m"},uuid:{label:"UUID",gender:"m"},nanoid:{label:"nanoid",gender:"m"},guid:{label:"GUID",gender:"m"},cuid:{label:"cuid",gender:"m"},cuid2:{label:"cuid2",gender:"m"},ulid:{label:"ULID",gender:"m"},xid:{label:"XID",gender:"m"},ksuid:{label:"KSUID",gender:"m"},datetime:{label:"\u05EA\u05D0\u05E8\u05D9\u05DA \u05D5\u05D6\u05DE\u05DF ISO",gender:"m"},date:{label:"\u05EA\u05D0\u05E8\u05D9\u05DA ISO",gender:"m"},time:{label:"\u05D6\u05DE\u05DF ISO",gender:"m"},duration:{label:"\u05DE\u05E9\u05DA \u05D6\u05DE\u05DF ISO",gender:"m"},ipv4:{label:"\u05DB\u05EA\u05D5\u05D1\u05EA IPv4",gender:"f"},ipv6:{label:"\u05DB\u05EA\u05D5\u05D1\u05EA IPv6",gender:"f"},cidrv4:{label:"\u05D8\u05D5\u05D5\u05D7 IPv4",gender:"m"},cidrv6:{label:"\u05D8\u05D5\u05D5\u05D7 IPv6",gender:"m"},base64:{label:"\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D1\u05D1\u05E1\u05D9\u05E1 64",gender:"f"},base64url:{label:"\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D1\u05D1\u05E1\u05D9\u05E1 64 \u05DC\u05DB\u05EA\u05D5\u05D1\u05D5\u05EA \u05E8\u05E9\u05EA",gender:"f"},json_string:{label:"\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA JSON",gender:"f"},e164:{label:"\u05DE\u05E1\u05E4\u05E8 E.164",gender:"m"},jwt:{label:"JWT",gender:"m"},ends_with:{label:"\u05E7\u05DC\u05D8",gender:"m"},includes:{label:"\u05E7\u05DC\u05D8",gender:"m"},lowercase:{label:"\u05E7\u05DC\u05D8",gender:"m"},starts_with:{label:"\u05E7\u05DC\u05D8",gender:"m"},uppercase:{label:"\u05E7\u05DC\u05D8",gender:"m"}},l={nan:"NaN"};return c=>{switch(c.code){case"invalid_type":{const u=c.expected,d=l[u??""]??n(u),m=Ut(c.input),h=l[m]??e[m]?.label??m;return/^[A-Z]/.test(c.expected)?`\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA instanceof ${c.expected}, \u05D4\u05EA\u05E7\u05D1\u05DC ${h}`:`\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${d}, \u05D4\u05EA\u05E7\u05D1\u05DC ${h}`}case"invalid_value":{if(c.values.length===1)return`\u05E2\u05E8\u05DA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05D4\u05E2\u05E8\u05DA \u05D7\u05D9\u05D9\u05D1 \u05DC\u05D4\u05D9\u05D5\u05EA ${Ot(c.values[0])}`;const u=c.values.map(h=>Ot(h));if(c.values.length===2)return`\u05E2\u05E8\u05DA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05D4\u05D0\u05E4\u05E9\u05E8\u05D5\u05D9\u05D5\u05EA \u05D4\u05DE\u05EA\u05D0\u05D9\u05DE\u05D5\u05EA \u05D4\u05DF ${u[0]} \u05D0\u05D5 ${u[1]}`;const d=u[u.length-1];return`\u05E2\u05E8\u05DA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05D4\u05D0\u05E4\u05E9\u05E8\u05D5\u05D9\u05D5\u05EA \u05D4\u05DE\u05EA\u05D0\u05D9\u05DE\u05D5\u05EA \u05D4\u05DF ${u.slice(0,-1).join(", ")} \u05D0\u05D5 ${d}`}case"too_big":{const u=i(c.origin),d=o(c.origin??"value");if(c.origin==="string")return`${u?.longLabel??"\u05D0\u05E8\u05D5\u05DA"} \u05DE\u05D3\u05D9: ${d} \u05E6\u05E8\u05D9\u05DB\u05D4 \u05DC\u05D4\u05DB\u05D9\u05DC ${c.maximum.toString()} ${u?.unit??""} ${c.inclusive?"\u05D0\u05D5 \u05E4\u05D7\u05D5\u05EA":"\u05DC\u05DB\u05DC \u05D4\u05D9\u05D5\u05EA\u05E8"}`.trim();if(c.origin==="number"){const g=c.inclusive?`\u05E7\u05D8\u05DF \u05D0\u05D5 \u05E9\u05D5\u05D5\u05D4 \u05DC-${c.maximum}`:`\u05E7\u05D8\u05DF \u05DE-${c.maximum}`;return`\u05D2\u05D3\u05D5\u05DC \u05DE\u05D3\u05D9: ${d} \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${g}`}if(c.origin==="array"||c.origin==="set"){const g=c.origin==="set"?"\u05E6\u05E8\u05D9\u05DB\u05D4":"\u05E6\u05E8\u05D9\u05DA",y=c.inclusive?`${c.maximum} ${u?.unit??""} \u05D0\u05D5 \u05E4\u05D7\u05D5\u05EA`:`\u05E4\u05D7\u05D5\u05EA \u05DE-${c.maximum} ${u?.unit??""}`;return`\u05D2\u05D3\u05D5\u05DC \u05DE\u05D3\u05D9: ${d} ${g} \u05DC\u05D4\u05DB\u05D9\u05DC ${y}`.trim()}const m=c.inclusive?"<=":"<",h=s(c.origin??"value");return u?.unit?`${u.longLabel} \u05DE\u05D3\u05D9: ${d} ${h} ${m}${c.maximum.toString()} ${u.unit}`:`${u?.longLabel??"\u05D2\u05D3\u05D5\u05DC"} \u05DE\u05D3\u05D9: ${d} ${h} ${m}${c.maximum.toString()}`}case"too_small":{const u=i(c.origin),d=o(c.origin??"value");if(c.origin==="string")return`${u?.shortLabel??"\u05E7\u05E6\u05E8"} \u05DE\u05D3\u05D9: ${d} \u05E6\u05E8\u05D9\u05DB\u05D4 \u05DC\u05D4\u05DB\u05D9\u05DC ${c.minimum.toString()} ${u?.unit??""} ${c.inclusive?"\u05D0\u05D5 \u05D9\u05D5\u05EA\u05E8":"\u05DC\u05E4\u05D7\u05D5\u05EA"}`.trim();if(c.origin==="number"){const g=c.inclusive?`\u05D2\u05D3\u05D5\u05DC \u05D0\u05D5 \u05E9\u05D5\u05D5\u05D4 \u05DC-${c.minimum}`:`\u05D2\u05D3\u05D5\u05DC \u05DE-${c.minimum}`;return`\u05E7\u05D8\u05DF \u05DE\u05D3\u05D9: ${d} \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${g}`}if(c.origin==="array"||c.origin==="set"){const g=c.origin==="set"?"\u05E6\u05E8\u05D9\u05DB\u05D4":"\u05E6\u05E8\u05D9\u05DA";if(c.minimum===1&&c.inclusive){const v=(c.origin==="set","\u05DC\u05E4\u05D7\u05D5\u05EA \u05E4\u05E8\u05D9\u05D8 \u05D0\u05D7\u05D3");return`\u05E7\u05D8\u05DF \u05DE\u05D3\u05D9: ${d} ${g} \u05DC\u05D4\u05DB\u05D9\u05DC ${v}`}const y=c.inclusive?`${c.minimum} ${u?.unit??""} \u05D0\u05D5 \u05D9\u05D5\u05EA\u05E8`:`\u05D9\u05D5\u05EA\u05E8 \u05DE-${c.minimum} ${u?.unit??""}`;return`\u05E7\u05D8\u05DF \u05DE\u05D3\u05D9: ${d} ${g} \u05DC\u05D4\u05DB\u05D9\u05DC ${y}`.trim()}const m=c.inclusive?">=":">",h=s(c.origin??"value");return u?.unit?`${u.shortLabel} \u05DE\u05D3\u05D9: ${d} ${h} ${m}${c.minimum.toString()} ${u.unit}`:`${u?.shortLabel??"\u05E7\u05D8\u05DF"} \u05DE\u05D3\u05D9: ${d} ${h} ${m}${c.minimum.toString()}`}case"invalid_format":{const u=c;if(u.format==="starts_with")return`\u05D4\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05D4\u05EA\u05D7\u05D9\u05DC \u05D1 "${u.prefix}"`;if(u.format==="ends_with")return`\u05D4\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05D4\u05E1\u05EA\u05D9\u05D9\u05DD \u05D1 "${u.suffix}"`;if(u.format==="includes")return`\u05D4\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05DB\u05DC\u05D5\u05DC "${u.includes}"`;if(u.format==="regex")return`\u05D4\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05D4\u05EA\u05D0\u05D9\u05DD \u05DC\u05EA\u05D1\u05E0\u05D9\u05EA ${u.pattern}`;const d=a[u.format],m=d?.label??u.format,g=(d?.gender??"m")==="f"?"\u05EA\u05E7\u05D9\u05E0\u05D4":"\u05EA\u05E7\u05D9\u05DF";return`${m} \u05DC\u05D0 ${g}`}case"not_multiple_of":return`\u05DE\u05E1\u05E4\u05E8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05D7\u05D9\u05D9\u05D1 \u05DC\u05D4\u05D9\u05D5\u05EA \u05DE\u05DB\u05E4\u05DC\u05D4 \u05E9\u05DC ${c.divisor}`;case"unrecognized_keys":return`\u05DE\u05E4\u05EA\u05D7${c.keys.length>1?"\u05D5\u05EA":""} \u05DC\u05D0 \u05DE\u05D6\u05D5\u05D4${c.keys.length>1?"\u05D9\u05DD":"\u05D4"}: ${Ye(c.keys,", ")}`;case"invalid_key":return"\u05E9\u05D3\u05D4 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF \u05D1\u05D0\u05D5\u05D1\u05D9\u05D9\u05E7\u05D8";case"invalid_union":return"\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF";case"invalid_element":return`\u05E2\u05E8\u05DA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF \u05D1${o(c.origin??"array")}`;default:return"\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF"}}}}});function qfr(){return{localeError:lfe()}}var lfe,Gfr=S({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/hu.js"(){kt(),lfe=()=>{const e={string:{unit:"karakter",verb:"legyen"},file:{unit:"byte",verb:"legyen"},array:{unit:"elem",verb:"legyen"},set:{unit:"elem",verb:"legyen"}};function t(o){return e[o]??null}const r={regex:"bemenet",email:"email c\xEDm",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO id\u0151b\xE9lyeg",date:"ISO d\xE1tum",time:"ISO id\u0151",duration:"ISO id\u0151intervallum",ipv4:"IPv4 c\xEDm",ipv6:"IPv6 c\xEDm",cidrv4:"IPv4 tartom\xE1ny",cidrv6:"IPv6 tartom\xE1ny",base64:"base64-k\xF3dolt string",base64url:"base64url-k\xF3dolt string",json_string:"JSON string",e164:"E.164 sz\xE1m",jwt:"JWT",template_literal:"bemenet"},n={nan:"NaN",number:"sz\xE1m",array:"t\xF6mb"};return o=>{switch(o.code){case"invalid_type":{const s=n[o.expected]??o.expected,i=Ut(o.input),a=n[i]??i;return/^[A-Z]/.test(o.expected)?`\xC9rv\xE9nytelen bemenet: a v\xE1rt \xE9rt\xE9k instanceof ${o.expected}, a kapott \xE9rt\xE9k ${a}`:`\xC9rv\xE9nytelen bemenet: a v\xE1rt \xE9rt\xE9k ${s}, a kapott \xE9rt\xE9k ${a}`}case"invalid_value":return o.values.length===1?`\xC9rv\xE9nytelen bemenet: a v\xE1rt \xE9rt\xE9k ${Ot(o.values[0])}`:`\xC9rv\xE9nytelen opci\xF3: valamelyik \xE9rt\xE9k v\xE1rt ${Ye(o.values,"|")}`;case"too_big":{const s=o.inclusive?"<=":"<",i=t(o.origin);return i?`T\xFAl nagy: ${o.origin??"\xE9rt\xE9k"} m\xE9rete t\xFAl nagy ${s}${o.maximum.toString()} ${i.unit??"elem"}`:`T\xFAl nagy: a bemeneti \xE9rt\xE9k ${o.origin??"\xE9rt\xE9k"} t\xFAl nagy: ${s}${o.maximum.toString()}`}case"too_small":{const s=o.inclusive?">=":">",i=t(o.origin);return i?`T\xFAl kicsi: a bemeneti \xE9rt\xE9k ${o.origin} m\xE9rete t\xFAl kicsi ${s}${o.minimum.toString()} ${i.unit}`:`T\xFAl kicsi: a bemeneti \xE9rt\xE9k ${o.origin} t\xFAl kicsi ${s}${o.minimum.toString()}`}case"invalid_format":{const s=o;return s.format==="starts_with"?`\xC9rv\xE9nytelen string: "${s.prefix}" \xE9rt\xE9kkel kell kezd\u0151dnie`:s.format==="ends_with"?`\xC9rv\xE9nytelen string: "${s.suffix}" \xE9rt\xE9kkel kell v\xE9gz\u0151dnie`:s.format==="includes"?`\xC9rv\xE9nytelen string: "${s.includes}" \xE9rt\xE9ket kell tartalmaznia`:s.format==="regex"?`\xC9rv\xE9nytelen string: ${s.pattern} mint\xE1nak kell megfelelnie`:`\xC9rv\xE9nytelen ${r[s.format]??o.format}`}case"not_multiple_of":return`\xC9rv\xE9nytelen sz\xE1m: ${o.divisor} t\xF6bbsz\xF6r\xF6s\xE9nek kell lennie`;case"unrecognized_keys":return`Ismeretlen kulcs${o.keys.length>1?"s":""}: ${Ye(o.keys,", ")}`;case"invalid_key":return`\xC9rv\xE9nytelen kulcs ${o.origin}`;case"invalid_union":return"\xC9rv\xE9nytelen bemenet";case"invalid_element":return`\xC9rv\xE9nytelen \xE9rt\xE9k: ${o.origin}`;default:return"\xC9rv\xE9nytelen bemenet"}}}}});function cfe(e,t,r){return Math.abs(e)===1?t:r}function vv(e){if(!e)return"";const t=["\u0561","\u0565","\u0568","\u056B","\u0578","\u0578\u0582","\u0585"],r=e[e.length-1];return e+(t.includes(r)?"\u0576":"\u0568")}function Hfr(){return{localeError:ufe()}}var ufe,Vfr=S({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/hy.js"(){kt(),ufe=()=>{const e={string:{unit:{one:"\u0576\u0577\u0561\u0576",many:"\u0576\u0577\u0561\u0576\u0576\u0565\u0580"},verb:"\u0578\u0582\u0576\u0565\u0576\u0561\u056C"},file:{unit:{one:"\u0562\u0561\u0575\u0569",many:"\u0562\u0561\u0575\u0569\u0565\u0580"},verb:"\u0578\u0582\u0576\u0565\u0576\u0561\u056C"},array:{unit:{one:"\u057F\u0561\u0580\u0580",many:"\u057F\u0561\u0580\u0580\u0565\u0580"},verb:"\u0578\u0582\u0576\u0565\u0576\u0561\u056C"},set:{unit:{one:"\u057F\u0561\u0580\u0580",many:"\u057F\u0561\u0580\u0580\u0565\u0580"},verb:"\u0578\u0582\u0576\u0565\u0576\u0561\u056C"}};function t(o){return e[o]??null}const r={regex:"\u0574\u0578\u0582\u057F\u0584",email:"\u0567\u056C. \u0570\u0561\u057D\u0581\u0565",url:"URL",emoji:"\u0567\u0574\u0578\u057B\u056B",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO \u0561\u0574\u057D\u0561\u0569\u056B\u057E \u0587 \u056A\u0561\u0574",date:"ISO \u0561\u0574\u057D\u0561\u0569\u056B\u057E",time:"ISO \u056A\u0561\u0574",duration:"ISO \u057F\u0587\u0578\u0572\u0578\u0582\u0569\u0575\u0578\u0582\u0576",ipv4:"IPv4 \u0570\u0561\u057D\u0581\u0565",ipv6:"IPv6 \u0570\u0561\u057D\u0581\u0565",cidrv4:"IPv4 \u0574\u056B\u057B\u0561\u056F\u0561\u0575\u0584",cidrv6:"IPv6 \u0574\u056B\u057B\u0561\u056F\u0561\u0575\u0584",base64:"base64 \u0571\u0587\u0561\u0579\u0561\u0583\u0578\u057E \u057F\u0578\u0572",base64url:"base64url \u0571\u0587\u0561\u0579\u0561\u0583\u0578\u057E \u057F\u0578\u0572",json_string:"JSON \u057F\u0578\u0572",e164:"E.164 \u0570\u0561\u0574\u0561\u0580",jwt:"JWT",template_literal:"\u0574\u0578\u0582\u057F\u0584"},n={nan:"NaN",number:"\u0569\u056B\u057E",array:"\u0566\u0561\u0576\u0563\u057E\u0561\u056E"};return o=>{switch(o.code){case"invalid_type":{const s=n[o.expected]??o.expected,i=Ut(o.input),a=n[i]??i;return/^[A-Z]/.test(o.expected)?`\u054D\u056D\u0561\u056C \u0574\u0578\u0582\u057F\u0584\u0561\u0563\u0580\u0578\u0582\u0574\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567\u0580 instanceof ${o.expected}, \u057D\u057F\u0561\u0581\u057E\u0565\u056C \u0567 ${a}`:`\u054D\u056D\u0561\u056C \u0574\u0578\u0582\u057F\u0584\u0561\u0563\u0580\u0578\u0582\u0574\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567\u0580 ${s}, \u057D\u057F\u0561\u0581\u057E\u0565\u056C \u0567 ${a}`}case"invalid_value":return o.values.length===1?`\u054D\u056D\u0561\u056C \u0574\u0578\u0582\u057F\u0584\u0561\u0563\u0580\u0578\u0582\u0574\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567\u0580 ${Ot(o.values[1])}`:`\u054D\u056D\u0561\u056C \u057F\u0561\u0580\u0562\u0565\u0580\u0561\u056F\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567\u0580 \u0570\u0565\u057F\u0587\u0575\u0561\u056C\u0576\u0565\u0580\u056B\u0581 \u0574\u0565\u056F\u0568\u055D ${Ye(o.values,"|")}`;case"too_big":{const s=o.inclusive?"<=":"<",i=t(o.origin);if(i){const a=Number(o.maximum),l=cfe(a,i.unit.one,i.unit.many);return`\u0549\u0561\u0583\u0561\u0566\u0561\u0576\u0581 \u0574\u0565\u056E \u0561\u0580\u056A\u0565\u0584\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567, \u0578\u0580 ${vv(o.origin??"\u0561\u0580\u056A\u0565\u0584")} \u056F\u0578\u0582\u0576\u0565\u0576\u0561 ${s}${o.maximum.toString()} ${l}`}return`\u0549\u0561\u0583\u0561\u0566\u0561\u0576\u0581 \u0574\u0565\u056E \u0561\u0580\u056A\u0565\u0584\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567, \u0578\u0580 ${vv(o.origin??"\u0561\u0580\u056A\u0565\u0584")} \u056C\u056B\u0576\u056B ${s}${o.maximum.toString()}`}case"too_small":{const s=o.inclusive?">=":">",i=t(o.origin);if(i){const a=Number(o.minimum),l=cfe(a,i.unit.one,i.unit.many);return`\u0549\u0561\u0583\u0561\u0566\u0561\u0576\u0581 \u0583\u0578\u0584\u0580 \u0561\u0580\u056A\u0565\u0584\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567, \u0578\u0580 ${vv(o.origin)} \u056F\u0578\u0582\u0576\u0565\u0576\u0561 ${s}${o.minimum.toString()} ${l}`}return`\u0549\u0561\u0583\u0561\u0566\u0561\u0576\u0581 \u0583\u0578\u0584\u0580 \u0561\u0580\u056A\u0565\u0584\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567, \u0578\u0580 ${vv(o.origin)} \u056C\u056B\u0576\u056B ${s}${o.minimum.toString()}`}case"invalid_format":{const s=o;return s.format==="starts_with"?`\u054D\u056D\u0561\u056C \u057F\u0578\u0572\u2024 \u057A\u0565\u057F\u0584 \u0567 \u057D\u056F\u057D\u057E\u056B "${s.prefix}"-\u0578\u057E`:s.format==="ends_with"?`\u054D\u056D\u0561\u056C \u057F\u0578\u0572\u2024 \u057A\u0565\u057F\u0584 \u0567 \u0561\u057E\u0561\u0580\u057F\u057E\u056B "${s.suffix}"-\u0578\u057E`:s.format==="includes"?`\u054D\u056D\u0561\u056C \u057F\u0578\u0572\u2024 \u057A\u0565\u057F\u0584 \u0567 \u057A\u0561\u0580\u0578\u0582\u0576\u0561\u056F\u056B "${s.includes}"`:s.format==="regex"?`\u054D\u056D\u0561\u056C \u057F\u0578\u0572\u2024 \u057A\u0565\u057F\u0584 \u0567 \u0570\u0561\u0574\u0561\u057A\u0561\u057F\u0561\u057D\u056D\u0561\u0576\u056B ${s.pattern} \u0571\u0587\u0561\u0579\u0561\u0583\u056B\u0576`:`\u054D\u056D\u0561\u056C ${r[s.format]??o.format}`}case"not_multiple_of":return`\u054D\u056D\u0561\u056C \u0569\u056B\u057E\u2024 \u057A\u0565\u057F\u0584 \u0567 \u0562\u0561\u0566\u0574\u0561\u057A\u0561\u057F\u056B\u056F \u056C\u056B\u0576\u056B ${o.divisor}-\u056B`;case"unrecognized_keys":return`\u0549\u0573\u0561\u0576\u0561\u0579\u057E\u0561\u056E \u0562\u0561\u0576\u0561\u056C\u056B${o.keys.length>1?"\u0576\u0565\u0580":""}. ${Ye(o.keys,", ")}`;case"invalid_key":return`\u054D\u056D\u0561\u056C \u0562\u0561\u0576\u0561\u056C\u056B ${vv(o.origin)}-\u0578\u0582\u0574`;case"invalid_union":return"\u054D\u056D\u0561\u056C \u0574\u0578\u0582\u057F\u0584\u0561\u0563\u0580\u0578\u0582\u0574";case"invalid_element":return`\u054D\u056D\u0561\u056C \u0561\u0580\u056A\u0565\u0584 ${vv(o.origin)}-\u0578\u0582\u0574`;default:return"\u054D\u056D\u0561\u056C \u0574\u0578\u0582\u057F\u0584\u0561\u0563\u0580\u0578\u0582\u0574"}}}}});function Wfr(){return{localeError:dfe()}}var dfe,Kfr=S({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/id.js"(){kt(),dfe=()=>{const e={string:{unit:"karakter",verb:"memiliki"},file:{unit:"byte",verb:"memiliki"},array:{unit:"item",verb:"memiliki"},set:{unit:"item",verb:"memiliki"}};function t(o){return e[o]??null}const r={regex:"input",email:"alamat email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"tanggal dan waktu format ISO",date:"tanggal format ISO",time:"jam format ISO",duration:"durasi format ISO",ipv4:"alamat IPv4",ipv6:"alamat IPv6",cidrv4:"rentang alamat IPv4",cidrv6:"rentang alamat IPv6",base64:"string dengan enkode base64",base64url:"string dengan enkode base64url",json_string:"string JSON",e164:"angka E.164",jwt:"JWT",template_literal:"input"},n={nan:"NaN"};return o=>{switch(o.code){case"invalid_type":{const s=n[o.expected]??o.expected,i=Ut(o.input),a=n[i]??i;return/^[A-Z]/.test(o.expected)?`Input tidak valid: diharapkan instanceof ${o.expected}, diterima ${a}`:`Input tidak valid: diharapkan ${s}, diterima ${a}`}case"invalid_value":return o.values.length===1?`Input tidak valid: diharapkan ${Ot(o.values[0])}`:`Pilihan tidak valid: diharapkan salah satu dari ${Ye(o.values,"|")}`;case"too_big":{const s=o.inclusive?"<=":"<",i=t(o.origin);return i?`Terlalu besar: diharapkan ${o.origin??"value"} memiliki ${s}${o.maximum.toString()} ${i.unit??"elemen"}`:`Terlalu besar: diharapkan ${o.origin??"value"} menjadi ${s}${o.maximum.toString()}`}case"too_small":{const s=o.inclusive?">=":">",i=t(o.origin);return i?`Terlalu kecil: diharapkan ${o.origin} memiliki ${s}${o.minimum.toString()} ${i.unit}`:`Terlalu kecil: diharapkan ${o.origin} menjadi ${s}${o.minimum.toString()}`}case"invalid_format":{const s=o;return s.format==="starts_with"?`String tidak valid: harus dimulai dengan "${s.prefix}"`:s.format==="ends_with"?`String tidak valid: harus berakhir dengan "${s.suffix}"`:s.format==="includes"?`String tidak valid: harus menyertakan "${s.includes}"`:s.format==="regex"?`String tidak valid: harus sesuai pola ${s.pattern}`:`${r[s.format]??o.format} tidak valid`}case"not_multiple_of":return`Angka tidak valid: harus kelipatan dari ${o.divisor}`;case"unrecognized_keys":return`Kunci tidak dikenali ${o.keys.length>1?"s":""}: ${Ye(o.keys,", ")}`;case"invalid_key":return`Kunci tidak valid di ${o.origin}`;case"invalid_union":return"Input tidak valid";case"invalid_element":return`Nilai tidak valid di ${o.origin}`;default:return"Input tidak valid"}}}}});function Jfr(){return{localeError:pfe()}}var pfe,Yfr=S({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/is.js"(){kt(),pfe=()=>{const e={string:{unit:"stafi",verb:"a\xF0 hafa"},file:{unit:"b\xE6ti",verb:"a\xF0 hafa"},array:{unit:"hluti",verb:"a\xF0 hafa"},set:{unit:"hluti",verb:"a\xF0 hafa"}};function t(o){return e[o]??null}const r={regex:"gildi",email:"netfang",url:"vefsl\xF3\xF0",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO dagsetning og t\xEDmi",date:"ISO dagsetning",time:"ISO t\xEDmi",duration:"ISO t\xEDmalengd",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded strengur",base64url:"base64url-encoded strengur",json_string:"JSON strengur",e164:"E.164 t\xF6lugildi",jwt:"JWT",template_literal:"gildi"},n={nan:"NaN",number:"n\xFAmer",array:"fylki"};return o=>{switch(o.code){case"invalid_type":{const s=n[o.expected]??o.expected,i=Ut(o.input),a=n[i]??i;return/^[A-Z]/.test(o.expected)?`Rangt gildi: \xDE\xFA sl\xF3st inn ${a} \xFEar sem \xE1 a\xF0 vera instanceof ${o.expected}`:`Rangt gildi: \xDE\xFA sl\xF3st inn ${a} \xFEar sem \xE1 a\xF0 vera ${s}`}case"invalid_value":return o.values.length===1?`Rangt gildi: gert r\xE1\xF0 fyrir ${Ot(o.values[0])}`:`\xD3gilt val: m\xE1 vera eitt af eftirfarandi ${Ye(o.values,"|")}`;case"too_big":{const s=o.inclusive?"<=":"<",i=t(o.origin);return i?`Of st\xF3rt: gert er r\xE1\xF0 fyrir a\xF0 ${o.origin??"gildi"} hafi ${s}${o.maximum.toString()} ${i.unit??"hluti"}`:`Of st\xF3rt: gert er r\xE1\xF0 fyrir a\xF0 ${o.origin??"gildi"} s\xE9 ${s}${o.maximum.toString()}`}case"too_small":{const s=o.inclusive?">=":">",i=t(o.origin);return i?`Of l\xEDti\xF0: gert er r\xE1\xF0 fyrir a\xF0 ${o.origin} hafi ${s}${o.minimum.toString()} ${i.unit}`:`Of l\xEDti\xF0: gert er r\xE1\xF0 fyrir a\xF0 ${o.origin} s\xE9 ${s}${o.minimum.toString()}`}case"invalid_format":{const s=o;return s.format==="starts_with"?`\xD3gildur strengur: ver\xF0ur a\xF0 byrja \xE1 "${s.prefix}"`:s.format==="ends_with"?`\xD3gildur strengur: ver\xF0ur a\xF0 enda \xE1 "${s.suffix}"`:s.format==="includes"?`\xD3gildur strengur: ver\xF0ur a\xF0 innihalda "${s.includes}"`:s.format==="regex"?`\xD3gildur strengur: ver\xF0ur a\xF0 fylgja mynstri ${s.pattern}`:`Rangt ${r[s.format]??o.format}`}case"not_multiple_of":return`R\xF6ng tala: ver\xF0ur a\xF0 vera margfeldi af ${o.divisor}`;case"unrecognized_keys":return`\xD3\xFEekkt ${o.keys.length>1?"ir lyklar":"ur lykill"}: ${Ye(o.keys,", ")}`;case"invalid_key":return`Rangur lykill \xED ${o.origin}`;case"invalid_union":return"Rangt gildi";case"invalid_element":return`Rangt gildi \xED ${o.origin}`;default:return"Rangt gildi"}}}}});function Zfr(){return{localeError:mfe()}}var mfe,Xfr=S({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/it.js"(){kt(),mfe=()=>{const e={string:{unit:"caratteri",verb:"avere"},file:{unit:"byte",verb:"avere"},array:{unit:"elementi",verb:"avere"},set:{unit:"elementi",verb:"avere"}};function t(o){return e[o]??null}const r={regex:"input",email:"indirizzo email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data e ora ISO",date:"data ISO",time:"ora ISO",duration:"durata ISO",ipv4:"indirizzo IPv4",ipv6:"indirizzo IPv6",cidrv4:"intervallo IPv4",cidrv6:"intervallo IPv6",base64:"stringa codificata in base64",base64url:"URL codificata in base64",json_string:"stringa JSON",e164:"numero E.164",jwt:"JWT",template_literal:"input"},n={nan:"NaN",number:"numero",array:"vettore"};return o=>{switch(o.code){case"invalid_type":{const s=n[o.expected]??o.expected,i=Ut(o.input),a=n[i]??i;return/^[A-Z]/.test(o.expected)?`Input non valido: atteso instanceof ${o.expected}, ricevuto ${a}`:`Input non valido: atteso ${s}, ricevuto ${a}`}case"invalid_value":return o.values.length===1?`Input non valido: atteso ${Ot(o.values[0])}`:`Opzione non valida: atteso uno tra ${Ye(o.values,"|")}`;case"too_big":{const s=o.inclusive?"<=":"<",i=t(o.origin);return i?`Troppo grande: ${o.origin??"valore"} deve avere ${s}${o.maximum.toString()} ${i.unit??"elementi"}`:`Troppo grande: ${o.origin??"valore"} deve essere ${s}${o.maximum.toString()}`}case"too_small":{const s=o.inclusive?">=":">",i=t(o.origin);return i?`Troppo piccolo: ${o.origin} deve avere ${s}${o.minimum.toString()} ${i.unit}`:`Troppo piccolo: ${o.origin} deve essere ${s}${o.minimum.toString()}`}case"invalid_format":{const s=o;return s.format==="starts_with"?`Stringa non valida: deve iniziare con "${s.prefix}"`:s.format==="ends_with"?`Stringa non valida: deve terminare con "${s.suffix}"`:s.format==="includes"?`Stringa non valida: deve includere "${s.includes}"`:s.format==="regex"?`Stringa non valida: deve corrispondere al pattern ${s.pattern}`:`Invalid ${r[s.format]??o.format}`}case"not_multiple_of":return`Numero non valido: deve essere un multiplo di ${o.divisor}`;case"unrecognized_keys":return`Chiav${o.keys.length>1?"i":"e"} non riconosciut${o.keys.length>1?"e":"a"}: ${Ye(o.keys,", ")}`;case"invalid_key":return`Chiave non valida in ${o.origin}`;case"invalid_union":return"Input non valido";case"invalid_element":return`Valore non valido in ${o.origin}`;default:return"Input non valido"}}}}});function Qfr(){return{localeError:hfe()}}var hfe,egr=S({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ja.js"(){kt(),hfe=()=>{const e={string:{unit:"\u6587\u5B57",verb:"\u3067\u3042\u308B"},file:{unit:"\u30D0\u30A4\u30C8",verb:"\u3067\u3042\u308B"},array:{unit:"\u8981\u7D20",verb:"\u3067\u3042\u308B"},set:{unit:"\u8981\u7D20",verb:"\u3067\u3042\u308B"}};function t(o){return e[o]??null}const r={regex:"\u5165\u529B\u5024",email:"\u30E1\u30FC\u30EB\u30A2\u30C9\u30EC\u30B9",url:"URL",emoji:"\u7D75\u6587\u5B57",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO\u65E5\u6642",date:"ISO\u65E5\u4ED8",time:"ISO\u6642\u523B",duration:"ISO\u671F\u9593",ipv4:"IPv4\u30A2\u30C9\u30EC\u30B9",ipv6:"IPv6\u30A2\u30C9\u30EC\u30B9",cidrv4:"IPv4\u7BC4\u56F2",cidrv6:"IPv6\u7BC4\u56F2",base64:"base64\u30A8\u30F3\u30B3\u30FC\u30C9\u6587\u5B57\u5217",base64url:"base64url\u30A8\u30F3\u30B3\u30FC\u30C9\u6587\u5B57\u5217",json_string:"JSON\u6587\u5B57\u5217",e164:"E.164\u756A\u53F7",jwt:"JWT",template_literal:"\u5165\u529B\u5024"},n={nan:"NaN",number:"\u6570\u5024",array:"\u914D\u5217"};return o=>{switch(o.code){case"invalid_type":{const s=n[o.expected]??o.expected,i=Ut(o.input),a=n[i]??i;return/^[A-Z]/.test(o.expected)?`\u7121\u52B9\u306A\u5165\u529B: instanceof ${o.expected}\u304C\u671F\u5F85\u3055\u308C\u307E\u3057\u305F\u304C\u3001${a}\u304C\u5165\u529B\u3055\u308C\u307E\u3057\u305F`:`\u7121\u52B9\u306A\u5165\u529B: ${s}\u304C\u671F\u5F85\u3055\u308C\u307E\u3057\u305F\u304C\u3001${a}\u304C\u5165\u529B\u3055\u308C\u307E\u3057\u305F`}case"invalid_value":return o.values.length===1?`\u7121\u52B9\u306A\u5165\u529B: ${Ot(o.values[0])}\u304C\u671F\u5F85\u3055\u308C\u307E\u3057\u305F`:`\u7121\u52B9\u306A\u9078\u629E: ${Ye(o.values,"\u3001")}\u306E\u3044\u305A\u308C\u304B\u3067\u3042\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;case"too_big":{const s=o.inclusive?"\u4EE5\u4E0B\u3067\u3042\u308B":"\u3088\u308A\u5C0F\u3055\u3044",i=t(o.origin);return i?`\u5927\u304D\u3059\u304E\u308B\u5024: ${o.origin??"\u5024"}\u306F${o.maximum.toString()}${i.unit??"\u8981\u7D20"}${s}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`:`\u5927\u304D\u3059\u304E\u308B\u5024: ${o.origin??"\u5024"}\u306F${o.maximum.toString()}${s}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`}case"too_small":{const s=o.inclusive?"\u4EE5\u4E0A\u3067\u3042\u308B":"\u3088\u308A\u5927\u304D\u3044",i=t(o.origin);return i?`\u5C0F\u3055\u3059\u304E\u308B\u5024: ${o.origin}\u306F${o.minimum.toString()}${i.unit}${s}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`:`\u5C0F\u3055\u3059\u304E\u308B\u5024: ${o.origin}\u306F${o.minimum.toString()}${s}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`}case"invalid_format":{const s=o;return s.format==="starts_with"?`\u7121\u52B9\u306A\u6587\u5B57\u5217: "${s.prefix}"\u3067\u59CB\u307E\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`:s.format==="ends_with"?`\u7121\u52B9\u306A\u6587\u5B57\u5217: "${s.suffix}"\u3067\u7D42\u308F\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`:s.format==="includes"?`\u7121\u52B9\u306A\u6587\u5B57\u5217: "${s.includes}"\u3092\u542B\u3080\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`:s.format==="regex"?`\u7121\u52B9\u306A\u6587\u5B57\u5217: \u30D1\u30BF\u30FC\u30F3${s.pattern}\u306B\u4E00\u81F4\u3059\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`:`\u7121\u52B9\u306A${r[s.format]??o.format}`}case"not_multiple_of":return`\u7121\u52B9\u306A\u6570\u5024: ${o.divisor}\u306E\u500D\u6570\u3067\u3042\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;case"unrecognized_keys":return`\u8A8D\u8B58\u3055\u308C\u3066\u3044\u306A\u3044\u30AD\u30FC${o.keys.length>1?"\u7FA4":""}: ${Ye(o.keys,"\u3001")}`;case"invalid_key":return`${o.origin}\u5185\u306E\u7121\u52B9\u306A\u30AD\u30FC`;case"invalid_union":return"\u7121\u52B9\u306A\u5165\u529B";case"invalid_element":return`${o.origin}\u5185\u306E\u7121\u52B9\u306A\u5024`;default:return"\u7121\u52B9\u306A\u5165\u529B"}}}}});function tgr(){return{localeError:ffe()}}var ffe,rgr=S({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ka.js"(){kt(),ffe=()=>{const e={string:{unit:"\u10E1\u10D8\u10DB\u10D1\u10DD\u10DA\u10DD",verb:"\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1"},file:{unit:"\u10D1\u10D0\u10D8\u10E2\u10D8",verb:"\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1"},array:{unit:"\u10D4\u10DA\u10D4\u10DB\u10D4\u10DC\u10E2\u10D8",verb:"\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1"},set:{unit:"\u10D4\u10DA\u10D4\u10DB\u10D4\u10DC\u10E2\u10D8",verb:"\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1"}};function t(o){return e[o]??null}const r={regex:"\u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0",email:"\u10D4\u10DA-\u10E4\u10DD\u10E1\u10E2\u10D8\u10E1 \u10DB\u10D8\u10E1\u10D0\u10DB\u10D0\u10E0\u10D7\u10D8",url:"URL",emoji:"\u10D4\u10DB\u10DD\u10EF\u10D8",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"\u10D7\u10D0\u10E0\u10D8\u10E6\u10D8-\u10D3\u10E0\u10DD",date:"\u10D7\u10D0\u10E0\u10D8\u10E6\u10D8",time:"\u10D3\u10E0\u10DD",duration:"\u10EE\u10D0\u10DC\u10D2\u10E0\u10EB\u10DA\u10D8\u10D5\u10DD\u10D1\u10D0",ipv4:"IPv4 \u10DB\u10D8\u10E1\u10D0\u10DB\u10D0\u10E0\u10D7\u10D8",ipv6:"IPv6 \u10DB\u10D8\u10E1\u10D0\u10DB\u10D0\u10E0\u10D7\u10D8",cidrv4:"IPv4 \u10D3\u10D8\u10D0\u10DE\u10D0\u10D6\u10DD\u10DC\u10D8",cidrv6:"IPv6 \u10D3\u10D8\u10D0\u10DE\u10D0\u10D6\u10DD\u10DC\u10D8",base64:"base64-\u10D9\u10DD\u10D3\u10D8\u10E0\u10D4\u10D1\u10E3\u10DA\u10D8 \u10E1\u10E2\u10E0\u10D8\u10DC\u10D2\u10D8",base64url:"base64url-\u10D9\u10DD\u10D3\u10D8\u10E0\u10D4\u10D1\u10E3\u10DA\u10D8 \u10E1\u10E2\u10E0\u10D8\u10DC\u10D2\u10D8",json_string:"JSON \u10E1\u10E2\u10E0\u10D8\u10DC\u10D2\u10D8",e164:"E.164 \u10DC\u10DD\u10DB\u10D4\u10E0\u10D8",jwt:"JWT",template_literal:"\u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0"},n={nan:"NaN",number:"\u10E0\u10D8\u10EA\u10EE\u10D5\u10D8",string:"\u10E1\u10E2\u10E0\u10D8\u10DC\u10D2\u10D8",boolean:"\u10D1\u10E3\u10DA\u10D4\u10D0\u10DC\u10D8",function:"\u10E4\u10E3\u10DC\u10E5\u10EA\u10D8\u10D0",array:"\u10DB\u10D0\u10E1\u10D8\u10D5\u10D8"};return o=>{switch(o.code){case"invalid_type":{const s=n[o.expected]??o.expected,i=Ut(o.input),a=n[i]??i;return/^[A-Z]/.test(o.expected)?`\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 instanceof ${o.expected}, \u10DB\u10D8\u10E6\u10D4\u10D1\u10E3\u10DA\u10D8 ${a}`:`\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${s}, \u10DB\u10D8\u10E6\u10D4\u10D1\u10E3\u10DA\u10D8 ${a}`}case"invalid_value":return o.values.length===1?`\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${Ot(o.values[0])}`:`\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10D5\u10D0\u10E0\u10D8\u10D0\u10DC\u10E2\u10D8: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8\u10D0 \u10D4\u10E0\u10D7-\u10D4\u10E0\u10D7\u10D8 ${Ye(o.values,"|")}-\u10D3\u10D0\u10DC`;case"too_big":{const s=o.inclusive?"<=":"<",i=t(o.origin);return i?`\u10D6\u10D4\u10D3\u10DB\u10D4\u10E2\u10D0\u10D3 \u10D3\u10D8\u10D3\u10D8: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${o.origin??"\u10DB\u10DC\u10D8\u10E8\u10D5\u10DC\u10D4\u10DA\u10DD\u10D1\u10D0"} ${i.verb} ${s}${o.maximum.toString()} ${i.unit}`:`\u10D6\u10D4\u10D3\u10DB\u10D4\u10E2\u10D0\u10D3 \u10D3\u10D8\u10D3\u10D8: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${o.origin??"\u10DB\u10DC\u10D8\u10E8\u10D5\u10DC\u10D4\u10DA\u10DD\u10D1\u10D0"} \u10D8\u10E7\u10DD\u10E1 ${s}${o.maximum.toString()}`}case"too_small":{const s=o.inclusive?">=":">",i=t(o.origin);return i?`\u10D6\u10D4\u10D3\u10DB\u10D4\u10E2\u10D0\u10D3 \u10DE\u10D0\u10E2\u10D0\u10E0\u10D0: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${o.origin} ${i.verb} ${s}${o.minimum.toString()} ${i.unit}`:`\u10D6\u10D4\u10D3\u10DB\u10D4\u10E2\u10D0\u10D3 \u10DE\u10D0\u10E2\u10D0\u10E0\u10D0: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${o.origin} \u10D8\u10E7\u10DD\u10E1 ${s}${o.minimum.toString()}`}case"invalid_format":{const s=o;return s.format==="starts_with"?`\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E1\u10E2\u10E0\u10D8\u10DC\u10D2\u10D8: \u10E3\u10DC\u10D3\u10D0 \u10D8\u10EC\u10E7\u10D4\u10D1\u10DD\u10D3\u10D4\u10E1 "${s.prefix}"-\u10D8\u10D7`:s.format==="ends_with"?`\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E1\u10E2\u10E0\u10D8\u10DC\u10D2\u10D8: \u10E3\u10DC\u10D3\u10D0 \u10DB\u10D7\u10D0\u10D5\u10E0\u10D3\u10D4\u10D1\u10DD\u10D3\u10D4\u10E1 "${s.suffix}"-\u10D8\u10D7`:s.format==="includes"?`\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E1\u10E2\u10E0\u10D8\u10DC\u10D2\u10D8: \u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1 "${s.includes}"-\u10E1`:s.format==="regex"?`\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E1\u10E2\u10E0\u10D8\u10DC\u10D2\u10D8: \u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D4\u10E1\u10D0\u10D1\u10D0\u10DB\u10D4\u10D1\u10DD\u10D3\u10D4\u10E1 \u10E8\u10D0\u10D1\u10DA\u10DD\u10DC\u10E1 ${s.pattern}`:`\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 ${r[s.format]??o.format}`}case"not_multiple_of":return`\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E0\u10D8\u10EA\u10EE\u10D5\u10D8: \u10E3\u10DC\u10D3\u10D0 \u10D8\u10E7\u10DD\u10E1 ${o.divisor}-\u10D8\u10E1 \u10EF\u10D4\u10E0\u10D0\u10D3\u10D8`;case"unrecognized_keys":return`\u10E3\u10EA\u10DC\u10DD\u10D1\u10D8 \u10D2\u10D0\u10E1\u10D0\u10E6\u10D4\u10D1${o.keys.length>1?"\u10D4\u10D1\u10D8":"\u10D8"}: ${Ye(o.keys,", ")}`;case"invalid_key":return`\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10D2\u10D0\u10E1\u10D0\u10E6\u10D4\u10D1\u10D8 ${o.origin}-\u10E8\u10D8`;case"invalid_union":return"\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0";case"invalid_element":return`\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10DB\u10DC\u10D8\u10E8\u10D5\u10DC\u10D4\u10DA\u10DD\u10D1\u10D0 ${o.origin}-\u10E8\u10D8`;default:return"\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0"}}}}});function gfe(){return{localeError:yfe()}}var yfe,vfe=S({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/km.js"(){kt(),yfe=()=>{const e={string:{unit:"\u178F\u17BD\u17A2\u1780\u17D2\u179F\u179A",verb:"\u1782\u17BD\u179A\u1798\u17B6\u1793"},file:{unit:"\u1794\u17C3",verb:"\u1782\u17BD\u179A\u1798\u17B6\u1793"},array:{unit:"\u1792\u17B6\u178F\u17BB",verb:"\u1782\u17BD\u179A\u1798\u17B6\u1793"},set:{unit:"\u1792\u17B6\u178F\u17BB",verb:"\u1782\u17BD\u179A\u1798\u17B6\u1793"}};function t(o){return e[o]??null}const r={regex:"\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B",email:"\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793\u17A2\u17CA\u17B8\u1798\u17C2\u179B",url:"URL",emoji:"\u179F\u1789\u17D2\u1789\u17B6\u17A2\u17B6\u179A\u1798\u17D2\u1798\u178E\u17CD",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"\u1780\u17B6\u179B\u1794\u179A\u17B7\u1785\u17D2\u1786\u17C1\u1791 \u1793\u17B7\u1784\u1798\u17C9\u17C4\u1784 ISO",date:"\u1780\u17B6\u179B\u1794\u179A\u17B7\u1785\u17D2\u1786\u17C1\u1791 ISO",time:"\u1798\u17C9\u17C4\u1784 ISO",duration:"\u179A\u1799\u17C8\u1796\u17C1\u179B ISO",ipv4:"\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv4",ipv6:"\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv6",cidrv4:"\u178A\u17C2\u1793\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv4",cidrv6:"\u178A\u17C2\u1793\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv6",base64:"\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u17A2\u17CA\u17B7\u1780\u17BC\u178A base64",base64url:"\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u17A2\u17CA\u17B7\u1780\u17BC\u178A base64url",json_string:"\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A JSON",e164:"\u179B\u17C1\u1781 E.164",jwt:"JWT",template_literal:"\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B"},n={nan:"NaN",number:"\u179B\u17C1\u1781",array:"\u17A2\u17B6\u179A\u17C1 (Array)",null:"\u1782\u17D2\u1798\u17B6\u1793\u178F\u1798\u17D2\u179B\u17C3 (null)"};return o=>{switch(o.code){case"invalid_type":{const s=n[o.expected]??o.expected,i=Ut(o.input),a=n[i]??i;return/^[A-Z]/.test(o.expected)?`\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A instanceof ${o.expected} \u1794\u17C9\u17BB\u1793\u17D2\u178F\u17C2\u1791\u1791\u17BD\u179B\u1794\u17B6\u1793 ${a}`:`\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${s} \u1794\u17C9\u17BB\u1793\u17D2\u178F\u17C2\u1791\u1791\u17BD\u179B\u1794\u17B6\u1793 ${a}`}case"invalid_value":return o.values.length===1?`\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${Ot(o.values[0])}`:`\u1787\u1798\u17D2\u179A\u17BE\u179F\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1787\u17B6\u1798\u17BD\u1799\u1780\u17D2\u1793\u17BB\u1784\u1785\u17C6\u178E\u17C4\u1798 ${Ye(o.values,"|")}`;case"too_big":{const s=o.inclusive?"<=":"<",i=t(o.origin);return i?`\u1792\u17C6\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${o.origin??"\u178F\u1798\u17D2\u179B\u17C3"} ${s} ${o.maximum.toString()} ${i.unit??"\u1792\u17B6\u178F\u17BB"}`:`\u1792\u17C6\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${o.origin??"\u178F\u1798\u17D2\u179B\u17C3"} ${s} ${o.maximum.toString()}`}case"too_small":{const s=o.inclusive?">=":">",i=t(o.origin);return i?`\u178F\u17BC\u1785\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${o.origin} ${s} ${o.minimum.toString()} ${i.unit}`:`\u178F\u17BC\u1785\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${o.origin} ${s} ${o.minimum.toString()}`}case"invalid_format":{const s=o;return s.format==="starts_with"?`\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1785\u17B6\u1794\u17CB\u1795\u17D2\u178F\u17BE\u1798\u178A\u17C4\u1799 "${s.prefix}"`:s.format==="ends_with"?`\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1794\u1789\u17D2\u1785\u1794\u17CB\u178A\u17C4\u1799 "${s.suffix}"`:s.format==="includes"?`\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1798\u17B6\u1793 "${s.includes}"`:s.format==="regex"?`\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u178F\u17C2\u1795\u17D2\u1782\u17BC\u1795\u17D2\u1782\u1784\u1793\u17B9\u1784\u1791\u1798\u17D2\u179A\u1784\u17CB\u178A\u17C2\u179B\u1794\u17B6\u1793\u1780\u17C6\u178E\u178F\u17CB ${s.pattern}`:`\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 ${r[s.format]??o.format}`}case"not_multiple_of":return`\u179B\u17C1\u1781\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u178F\u17C2\u1787\u17B6\u1796\u17A0\u17BB\u1782\u17BB\u178E\u1793\u17C3 ${o.divisor}`;case"unrecognized_keys":return`\u179A\u1780\u1783\u17BE\u1789\u179F\u17C4\u1798\u17B7\u1793\u179F\u17D2\u1782\u17B6\u179B\u17CB\u17D6 ${Ye(o.keys,", ")}`;case"invalid_key":return`\u179F\u17C4\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u1793\u17C5\u1780\u17D2\u1793\u17BB\u1784 ${o.origin}`;case"invalid_union":return"\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C";case"invalid_element":return`\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u1793\u17C5\u1780\u17D2\u1793\u17BB\u1784 ${o.origin}`;default:return"\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C"}}}}});function ngr(){return gfe()}var ogr=S({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/kh.js"(){vfe()}});function sgr(){return{localeError:_fe()}}var _fe,igr=S({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ko.js"(){kt(),_fe=()=>{const e={string:{unit:"\uBB38\uC790",verb:"to have"},file:{unit:"\uBC14\uC774\uD2B8",verb:"to have"},array:{unit:"\uAC1C",verb:"to have"},set:{unit:"\uAC1C",verb:"to have"}};function t(o){return e[o]??null}const r={regex:"\uC785\uB825",email:"\uC774\uBA54\uC77C \uC8FC\uC18C",url:"URL",emoji:"\uC774\uBAA8\uC9C0",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO \uB0A0\uC9DC\uC2DC\uAC04",date:"ISO \uB0A0\uC9DC",time:"ISO \uC2DC\uAC04",duration:"ISO \uAE30\uAC04",ipv4:"IPv4 \uC8FC\uC18C",ipv6:"IPv6 \uC8FC\uC18C",cidrv4:"IPv4 \uBC94\uC704",cidrv6:"IPv6 \uBC94\uC704",base64:"base64 \uC778\uCF54\uB529 \uBB38\uC790\uC5F4",base64url:"base64url \uC778\uCF54\uB529 \uBB38\uC790\uC5F4",json_string:"JSON \uBB38\uC790\uC5F4",e164:"E.164 \uBC88\uD638",jwt:"JWT",template_literal:"\uC785\uB825"},n={nan:"NaN"};return o=>{switch(o.code){case"invalid_type":{const s=n[o.expected]??o.expected,i=Ut(o.input),a=n[i]??i;return/^[A-Z]/.test(o.expected)?`\uC798\uBABB\uB41C \uC785\uB825: \uC608\uC0C1 \uD0C0\uC785\uC740 instanceof ${o.expected}, \uBC1B\uC740 \uD0C0\uC785\uC740 ${a}\uC785\uB2C8\uB2E4`:`\uC798\uBABB\uB41C \uC785\uB825: \uC608\uC0C1 \uD0C0\uC785\uC740 ${s}, \uBC1B\uC740 \uD0C0\uC785\uC740 ${a}\uC785\uB2C8\uB2E4`}case"invalid_value":return o.values.length===1?`\uC798\uBABB\uB41C \uC785\uB825: \uAC12\uC740 ${Ot(o.values[0])} \uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4`:`\uC798\uBABB\uB41C \uC635\uC158: ${Ye(o.values,"\uB610\uB294 ")} \uC911 \uD558\uB098\uC5EC\uC57C \uD569\uB2C8\uB2E4`;case"too_big":{const s=o.inclusive?"\uC774\uD558":"\uBBF8\uB9CC",i=s==="\uBBF8\uB9CC"?"\uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4":"\uC5EC\uC57C \uD569\uB2C8\uB2E4",a=t(o.origin),l=a?.unit??"\uC694\uC18C";return a?`${o.origin??"\uAC12"}\uC774 \uB108\uBB34 \uD07D\uB2C8\uB2E4: ${o.maximum.toString()}${l} ${s}${i}`:`${o.origin??"\uAC12"}\uC774 \uB108\uBB34 \uD07D\uB2C8\uB2E4: ${o.maximum.toString()} ${s}${i}`}case"too_small":{const s=o.inclusive?"\uC774\uC0C1":"\uCD08\uACFC",i=s==="\uC774\uC0C1"?"\uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4":"\uC5EC\uC57C \uD569\uB2C8\uB2E4",a=t(o.origin),l=a?.unit??"\uC694\uC18C";return a?`${o.origin??"\uAC12"}\uC774 \uB108\uBB34 \uC791\uC2B5\uB2C8\uB2E4: ${o.minimum.toString()}${l} ${s}${i}`:`${o.origin??"\uAC12"}\uC774 \uB108\uBB34 \uC791\uC2B5\uB2C8\uB2E4: ${o.minimum.toString()} ${s}${i}`}case"invalid_format":{const s=o;return s.format==="starts_with"?`\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: "${s.prefix}"(\uC73C)\uB85C \uC2DC\uC791\uD574\uC57C \uD569\uB2C8\uB2E4`:s.format==="ends_with"?`\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: "${s.suffix}"(\uC73C)\uB85C \uB05D\uB098\uC57C \uD569\uB2C8\uB2E4`:s.format==="includes"?`\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: "${s.includes}"\uC744(\uB97C) \uD3EC\uD568\uD574\uC57C \uD569\uB2C8\uB2E4`:s.format==="regex"?`\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: \uC815\uADDC\uC2DD ${s.pattern} \uD328\uD134\uACFC \uC77C\uCE58\uD574\uC57C \uD569\uB2C8\uB2E4`:`\uC798\uBABB\uB41C ${r[s.format]??o.format}`}case"not_multiple_of":return`\uC798\uBABB\uB41C \uC22B\uC790: ${o.divisor}\uC758 \uBC30\uC218\uC5EC\uC57C \uD569\uB2C8\uB2E4`;case"unrecognized_keys":return`\uC778\uC2DD\uD560 \uC218 \uC5C6\uB294 \uD0A4: ${Ye(o.keys,", ")}`;case"invalid_key":return`\uC798\uBABB\uB41C \uD0A4: ${o.origin}`;case"invalid_union":return"\uC798\uBABB\uB41C \uC785\uB825";case"invalid_element":return`\uC798\uBABB\uB41C \uAC12: ${o.origin}`;default:return"\uC798\uBABB\uB41C \uC785\uB825"}}}}});function wfe(e){const t=Math.abs(e),r=t%10,n=t%100;return n>=11&&n<=19||r===0?"many":r===1?"one":"few"}function agr(){return{localeError:bfe()}}var _v,bfe,lgr=S({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/lt.js"(){kt(),_v=e=>e.charAt(0).toUpperCase()+e.slice(1),bfe=()=>{const e={string:{unit:{one:"simbolis",few:"simboliai",many:"simboli\u0173"},verb:{smaller:{inclusive:"turi b\u016Bti ne ilgesn\u0117 kaip",notInclusive:"turi b\u016Bti trumpesn\u0117 kaip"},bigger:{inclusive:"turi b\u016Bti ne trumpesn\u0117 kaip",notInclusive:"turi b\u016Bti ilgesn\u0117 kaip"}}},file:{unit:{one:"baitas",few:"baitai",many:"bait\u0173"},verb:{smaller:{inclusive:"turi b\u016Bti ne didesnis kaip",notInclusive:"turi b\u016Bti ma\u017Eesnis kaip"},bigger:{inclusive:"turi b\u016Bti ne ma\u017Eesnis kaip",notInclusive:"turi b\u016Bti didesnis kaip"}}},array:{unit:{one:"element\u0105",few:"elementus",many:"element\u0173"},verb:{smaller:{inclusive:"turi tur\u0117ti ne daugiau kaip",notInclusive:"turi tur\u0117ti ma\u017Eiau kaip"},bigger:{inclusive:"turi tur\u0117ti ne ma\u017Eiau kaip",notInclusive:"turi tur\u0117ti daugiau kaip"}}},set:{unit:{one:"element\u0105",few:"elementus",many:"element\u0173"},verb:{smaller:{inclusive:"turi tur\u0117ti ne daugiau kaip",notInclusive:"turi tur\u0117ti ma\u017Eiau kaip"},bigger:{inclusive:"turi tur\u0117ti ne ma\u017Eiau kaip",notInclusive:"turi tur\u0117ti daugiau kaip"}}}};function t(o,s,i,a){const l=e[o]??null;return l===null?l:{unit:l.unit[s],verb:l.verb[a][i?"inclusive":"notInclusive"]}}const r={regex:"\u012Fvestis",email:"el. pa\u0161to adresas",url:"URL",emoji:"jaustukas",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO data ir laikas",date:"ISO data",time:"ISO laikas",duration:"ISO trukm\u0117",ipv4:"IPv4 adresas",ipv6:"IPv6 adresas",cidrv4:"IPv4 tinklo prefiksas (CIDR)",cidrv6:"IPv6 tinklo prefiksas (CIDR)",base64:"base64 u\u017Ekoduota eilut\u0117",base64url:"base64url u\u017Ekoduota eilut\u0117",json_string:"JSON eilut\u0117",e164:"E.164 numeris",jwt:"JWT",template_literal:"\u012Fvestis"},n={nan:"NaN",number:"skai\u010Dius",bigint:"sveikasis skai\u010Dius",string:"eilut\u0117",boolean:"login\u0117 reik\u0161m\u0117",undefined:"neapibr\u0117\u017Eta reik\u0161m\u0117",function:"funkcija",symbol:"simbolis",array:"masyvas",object:"objektas",null:"nulin\u0117 reik\u0161m\u0117"};return o=>{switch(o.code){case"invalid_type":{const s=n[o.expected]??o.expected,i=Ut(o.input),a=n[i]??i;return/^[A-Z]/.test(o.expected)?`Gautas tipas ${a}, o tik\u0117tasi - instanceof ${o.expected}`:`Gautas tipas ${a}, o tik\u0117tasi - ${s}`}case"invalid_value":return o.values.length===1?`Privalo b\u016Bti ${Ot(o.values[0])}`:`Privalo b\u016Bti vienas i\u0161 ${Ye(o.values,"|")} pasirinkim\u0173`;case"too_big":{const s=n[o.origin]??o.origin,i=t(o.origin,wfe(Number(o.maximum)),o.inclusive??!1,"smaller");if(i?.verb)return`${_v(s??o.origin??"reik\u0161m\u0117")} ${i.verb} ${o.maximum.toString()} ${i.unit??"element\u0173"}`;const a=o.inclusive?"ne didesnis kaip":"ma\u017Eesnis kaip";return`${_v(s??o.origin??"reik\u0161m\u0117")} turi b\u016Bti ${a} ${o.maximum.toString()} ${i?.unit}`}case"too_small":{const s=n[o.origin]??o.origin,i=t(o.origin,wfe(Number(o.minimum)),o.inclusive??!1,"bigger");if(i?.verb)return`${_v(s??o.origin??"reik\u0161m\u0117")} ${i.verb} ${o.minimum.toString()} ${i.unit??"element\u0173"}`;const a=o.inclusive?"ne ma\u017Eesnis kaip":"didesnis kaip";return`${_v(s??o.origin??"reik\u0161m\u0117")} turi b\u016Bti ${a} ${o.minimum.toString()} ${i?.unit}`}case"invalid_format":{const s=o;return s.format==="starts_with"?`Eilut\u0117 privalo prasid\u0117ti "${s.prefix}"`:s.format==="ends_with"?`Eilut\u0117 privalo pasibaigti "${s.suffix}"`:s.format==="includes"?`Eilut\u0117 privalo \u012Ftraukti "${s.includes}"`:s.format==="regex"?`Eilut\u0117 privalo atitikti ${s.pattern}`:`Neteisingas ${r[s.format]??o.format}`}case"not_multiple_of":return`Skai\u010Dius privalo b\u016Bti ${o.divisor} kartotinis.`;case"unrecognized_keys":return`Neatpa\u017Eint${o.keys.length>1?"i":"as"} rakt${o.keys.length>1?"ai":"as"}: ${Ye(o.keys,", ")}`;case"invalid_key":return"Rastas klaidingas raktas";case"invalid_union":return"Klaidinga \u012Fvestis";case"invalid_element":{const s=n[o.origin]??o.origin;return`${_v(s??o.origin??"reik\u0161m\u0117")} turi klaiding\u0105 \u012Fvest\u012F`}default:return"Klaidinga \u012Fvestis"}}}}});function cgr(){return{localeError:Tfe()}}var Tfe,ugr=S({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/mk.js"(){kt(),Tfe=()=>{const e={string:{unit:"\u0437\u043D\u0430\u0446\u0438",verb:"\u0434\u0430 \u0438\u043C\u0430\u0430\u0442"},file:{unit:"\u0431\u0430\u0458\u0442\u0438",verb:"\u0434\u0430 \u0438\u043C\u0430\u0430\u0442"},array:{unit:"\u0441\u0442\u0430\u0432\u043A\u0438",verb:"\u0434\u0430 \u0438\u043C\u0430\u0430\u0442"},set:{unit:"\u0441\u0442\u0430\u0432\u043A\u0438",verb:"\u0434\u0430 \u0438\u043C\u0430\u0430\u0442"}};function t(o){return e[o]??null}const r={regex:"\u0432\u043D\u0435\u0441",email:"\u0430\u0434\u0440\u0435\u0441\u0430 \u043D\u0430 \u0435-\u043F\u043E\u0448\u0442\u0430",url:"URL",emoji:"\u0435\u043C\u043E\u045F\u0438",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO \u0434\u0430\u0442\u0443\u043C \u0438 \u0432\u0440\u0435\u043C\u0435",date:"ISO \u0434\u0430\u0442\u0443\u043C",time:"ISO \u0432\u0440\u0435\u043C\u0435",duration:"ISO \u0432\u0440\u0435\u043C\u0435\u0442\u0440\u0430\u0435\u045A\u0435",ipv4:"IPv4 \u0430\u0434\u0440\u0435\u0441\u0430",ipv6:"IPv6 \u0430\u0434\u0440\u0435\u0441\u0430",cidrv4:"IPv4 \u043E\u043F\u0441\u0435\u0433",cidrv6:"IPv6 \u043E\u043F\u0441\u0435\u0433",base64:"base64-\u0435\u043D\u043A\u043E\u0434\u0438\u0440\u0430\u043D\u0430 \u043D\u0438\u0437\u0430",base64url:"base64url-\u0435\u043D\u043A\u043E\u0434\u0438\u0440\u0430\u043D\u0430 \u043D\u0438\u0437\u0430",json_string:"JSON \u043D\u0438\u0437\u0430",e164:"E.164 \u0431\u0440\u043E\u0458",jwt:"JWT",template_literal:"\u0432\u043D\u0435\u0441"},n={nan:"NaN",number:"\u0431\u0440\u043E\u0458",array:"\u043D\u0438\u0437\u0430"};return o=>{switch(o.code){case"invalid_type":{const s=n[o.expected]??o.expected,i=Ut(o.input),a=n[i]??i;return/^[A-Z]/.test(o.expected)?`\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 instanceof ${o.expected}, \u043F\u0440\u0438\u043C\u0435\u043D\u043E ${a}`:`\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${s}, \u043F\u0440\u0438\u043C\u0435\u043D\u043E ${a}`}case"invalid_value":return o.values.length===1?`Invalid input: expected ${Ot(o.values[0])}`:`\u0413\u0440\u0435\u0448\u0430\u043D\u0430 \u043E\u043F\u0446\u0438\u0458\u0430: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 \u0435\u0434\u043D\u0430 ${Ye(o.values,"|")}`;case"too_big":{const s=o.inclusive?"<=":"<",i=t(o.origin);return i?`\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u0433\u043E\u043B\u0435\u043C: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${o.origin??"\u0432\u0440\u0435\u0434\u043D\u043E\u0441\u0442\u0430"} \u0434\u0430 \u0438\u043C\u0430 ${s}${o.maximum.toString()} ${i.unit??"\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0438"}`:`\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u0433\u043E\u043B\u0435\u043C: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${o.origin??"\u0432\u0440\u0435\u0434\u043D\u043E\u0441\u0442\u0430"} \u0434\u0430 \u0431\u0438\u0434\u0435 ${s}${o.maximum.toString()}`}case"too_small":{const s=o.inclusive?">=":">",i=t(o.origin);return i?`\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u043C\u0430\u043B: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${o.origin} \u0434\u0430 \u0438\u043C\u0430 ${s}${o.minimum.toString()} ${i.unit}`:`\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u043C\u0430\u043B: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${o.origin} \u0434\u0430 \u0431\u0438\u0434\u0435 ${s}${o.minimum.toString()}`}case"invalid_format":{const s=o;return s.format==="starts_with"?`\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0437\u0430\u043F\u043E\u0447\u043D\u0443\u0432\u0430 \u0441\u043E "${s.prefix}"`:s.format==="ends_with"?`\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0437\u0430\u0432\u0440\u0448\u0443\u0432\u0430 \u0441\u043E "${s.suffix}"`:s.format==="includes"?`\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0432\u043A\u043B\u0443\u0447\u0443\u0432\u0430 "${s.includes}"`:s.format==="regex"?`\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u043E\u0434\u0433\u043E\u0430\u0440\u0430 \u043D\u0430 \u043F\u0430\u0442\u0435\u0440\u043D\u043E\u0442 ${s.pattern}`:`Invalid ${r[s.format]??o.format}`}case"not_multiple_of":return`\u0413\u0440\u0435\u0448\u0435\u043D \u0431\u0440\u043E\u0458: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0431\u0438\u0434\u0435 \u0434\u0435\u043B\u0438\u0432 \u0441\u043E ${o.divisor}`;case"unrecognized_keys":return`${o.keys.length>1?"\u041D\u0435\u043F\u0440\u0435\u043F\u043E\u0437\u043D\u0430\u0435\u043D\u0438 \u043A\u043B\u0443\u0447\u0435\u0432\u0438":"\u041D\u0435\u043F\u0440\u0435\u043F\u043E\u0437\u043D\u0430\u0435\u043D \u043A\u043B\u0443\u0447"}: ${Ye(o.keys,", ")}`;case"invalid_key":return`\u0413\u0440\u0435\u0448\u0435\u043D \u043A\u043B\u0443\u0447 \u0432\u043E ${o.origin}`;case"invalid_union":return"\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441";case"invalid_element":return`\u0413\u0440\u0435\u0448\u043D\u0430 \u0432\u0440\u0435\u0434\u043D\u043E\u0441\u0442 \u0432\u043E ${o.origin}`;default:return"\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441"}}}}});function dgr(){return{localeError:Efe()}}var Efe,pgr=S({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ms.js"(){kt(),Efe=()=>{const e={string:{unit:"aksara",verb:"mempunyai"},file:{unit:"bait",verb:"mempunyai"},array:{unit:"elemen",verb:"mempunyai"},set:{unit:"elemen",verb:"mempunyai"}};function t(o){return e[o]??null}const r={regex:"input",email:"alamat e-mel",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"tarikh masa ISO",date:"tarikh ISO",time:"masa ISO",duration:"tempoh ISO",ipv4:"alamat IPv4",ipv6:"alamat IPv6",cidrv4:"julat IPv4",cidrv6:"julat IPv6",base64:"string dikodkan base64",base64url:"string dikodkan base64url",json_string:"string JSON",e164:"nombor E.164",jwt:"JWT",template_literal:"input"},n={nan:"NaN",number:"nombor"};return o=>{switch(o.code){case"invalid_type":{const s=n[o.expected]??o.expected,i=Ut(o.input),a=n[i]??i;return/^[A-Z]/.test(o.expected)?`Input tidak sah: dijangka instanceof ${o.expected}, diterima ${a}`:`Input tidak sah: dijangka ${s}, diterima ${a}`}case"invalid_value":return o.values.length===1?`Input tidak sah: dijangka ${Ot(o.values[0])}`:`Pilihan tidak sah: dijangka salah satu daripada ${Ye(o.values,"|")}`;case"too_big":{const s=o.inclusive?"<=":"<",i=t(o.origin);return i?`Terlalu besar: dijangka ${o.origin??"nilai"} ${i.verb} ${s}${o.maximum.toString()} ${i.unit??"elemen"}`:`Terlalu besar: dijangka ${o.origin??"nilai"} adalah ${s}${o.maximum.toString()}`}case"too_small":{const s=o.inclusive?">=":">",i=t(o.origin);return i?`Terlalu kecil: dijangka ${o.origin} ${i.verb} ${s}${o.minimum.toString()} ${i.unit}`:`Terlalu kecil: dijangka ${o.origin} adalah ${s}${o.minimum.toString()}`}case"invalid_format":{const s=o;return s.format==="starts_with"?`String tidak sah: mesti bermula dengan "${s.prefix}"`:s.format==="ends_with"?`String tidak sah: mesti berakhir dengan "${s.suffix}"`:s.format==="includes"?`String tidak sah: mesti mengandungi "${s.includes}"`:s.format==="regex"?`String tidak sah: mesti sepadan dengan corak ${s.pattern}`:`${r[s.format]??o.format} tidak sah`}case"not_multiple_of":return`Nombor tidak sah: perlu gandaan ${o.divisor}`;case"unrecognized_keys":return`Kunci tidak dikenali: ${Ye(o.keys,", ")}`;case"invalid_key":return`Kunci tidak sah dalam ${o.origin}`;case"invalid_union":return"Input tidak sah";case"invalid_element":return`Nilai tidak sah dalam ${o.origin}`;default:return"Input tidak sah"}}}}});function mgr(){return{localeError:Sfe()}}var Sfe,hgr=S({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/nl.js"(){kt(),Sfe=()=>{const e={string:{unit:"tekens",verb:"heeft"},file:{unit:"bytes",verb:"heeft"},array:{unit:"elementen",verb:"heeft"},set:{unit:"elementen",verb:"heeft"}};function t(o){return e[o]??null}const r={regex:"invoer",email:"emailadres",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datum en tijd",date:"ISO datum",time:"ISO tijd",duration:"ISO duur",ipv4:"IPv4-adres",ipv6:"IPv6-adres",cidrv4:"IPv4-bereik",cidrv6:"IPv6-bereik",base64:"base64-gecodeerde tekst",base64url:"base64 URL-gecodeerde tekst",json_string:"JSON string",e164:"E.164-nummer",jwt:"JWT",template_literal:"invoer"},n={nan:"NaN",number:"getal"};return o=>{switch(o.code){case"invalid_type":{const s=n[o.expected]??o.expected,i=Ut(o.input),a=n[i]??i;return/^[A-Z]/.test(o.expected)?`Ongeldige invoer: verwacht instanceof ${o.expected}, ontving ${a}`:`Ongeldige invoer: verwacht ${s}, ontving ${a}`}case"invalid_value":return o.values.length===1?`Ongeldige invoer: verwacht ${Ot(o.values[0])}`:`Ongeldige optie: verwacht \xE9\xE9n van ${Ye(o.values,"|")}`;case"too_big":{const s=o.inclusive?"<=":"<",i=t(o.origin),a=o.origin==="date"?"laat":o.origin==="string"?"lang":"groot";return i?`Te ${a}: verwacht dat ${o.origin??"waarde"} ${s}${o.maximum.toString()} ${i.unit??"elementen"} ${i.verb}`:`Te ${a}: verwacht dat ${o.origin??"waarde"} ${s}${o.maximum.toString()} is`}case"too_small":{const s=o.inclusive?">=":">",i=t(o.origin),a=o.origin==="date"?"vroeg":o.origin==="string"?"kort":"klein";return i?`Te ${a}: verwacht dat ${o.origin} ${s}${o.minimum.toString()} ${i.unit} ${i.verb}`:`Te ${a}: verwacht dat ${o.origin} ${s}${o.minimum.toString()} is`}case"invalid_format":{const s=o;return s.format==="starts_with"?`Ongeldige tekst: moet met "${s.prefix}" beginnen`:s.format==="ends_with"?`Ongeldige tekst: moet op "${s.suffix}" eindigen`:s.format==="includes"?`Ongeldige tekst: moet "${s.includes}" bevatten`:s.format==="regex"?`Ongeldige tekst: moet overeenkomen met patroon ${s.pattern}`:`Ongeldig: ${r[s.format]??o.format}`}case"not_multiple_of":return`Ongeldig getal: moet een veelvoud van ${o.divisor} zijn`;case"unrecognized_keys":return`Onbekende key${o.keys.length>1?"s":""}: ${Ye(o.keys,", ")}`;case"invalid_key":return`Ongeldige key in ${o.origin}`;case"invalid_union":return"Ongeldige invoer";case"invalid_element":return`Ongeldige waarde in ${o.origin}`;default:return"Ongeldige invoer"}}}}});function fgr(){return{localeError:Cfe()}}var Cfe,ggr=S({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/no.js"(){kt(),Cfe=()=>{const e={string:{unit:"tegn",verb:"\xE5 ha"},file:{unit:"bytes",verb:"\xE5 ha"},array:{unit:"elementer",verb:"\xE5 inneholde"},set:{unit:"elementer",verb:"\xE5 inneholde"}};function t(o){return e[o]??null}const r={regex:"input",email:"e-postadresse",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO dato- og klokkeslett",date:"ISO-dato",time:"ISO-klokkeslett",duration:"ISO-varighet",ipv4:"IPv4-omr\xE5de",ipv6:"IPv6-omr\xE5de",cidrv4:"IPv4-spekter",cidrv6:"IPv6-spekter",base64:"base64-enkodet streng",base64url:"base64url-enkodet streng",json_string:"JSON-streng",e164:"E.164-nummer",jwt:"JWT",template_literal:"input"},n={nan:"NaN",number:"tall",array:"liste"};return o=>{switch(o.code){case"invalid_type":{const s=n[o.expected]??o.expected,i=Ut(o.input),a=n[i]??i;return/^[A-Z]/.test(o.expected)?`Ugyldig input: forventet instanceof ${o.expected}, fikk ${a}`:`Ugyldig input: forventet ${s}, fikk ${a}`}case"invalid_value":return o.values.length===1?`Ugyldig verdi: forventet ${Ot(o.values[0])}`:`Ugyldig valg: forventet en av ${Ye(o.values,"|")}`;case"too_big":{const s=o.inclusive?"<=":"<",i=t(o.origin);return i?`For stor(t): forventet ${o.origin??"value"} til \xE5 ha ${s}${o.maximum.toString()} ${i.unit??"elementer"}`:`For stor(t): forventet ${o.origin??"value"} til \xE5 ha ${s}${o.maximum.toString()}`}case"too_small":{const s=o.inclusive?">=":">",i=t(o.origin);return i?`For lite(n): forventet ${o.origin} til \xE5 ha ${s}${o.minimum.toString()} ${i.unit}`:`For lite(n): forventet ${o.origin} til \xE5 ha ${s}${o.minimum.toString()}`}case"invalid_format":{const s=o;return s.format==="starts_with"?`Ugyldig streng: m\xE5 starte med "${s.prefix}"`:s.format==="ends_with"?`Ugyldig streng: m\xE5 ende med "${s.suffix}"`:s.format==="includes"?`Ugyldig streng: m\xE5 inneholde "${s.includes}"`:s.format==="regex"?`Ugyldig streng: m\xE5 matche m\xF8nsteret ${s.pattern}`:`Ugyldig ${r[s.format]??o.format}`}case"not_multiple_of":return`Ugyldig tall: m\xE5 v\xE6re et multiplum av ${o.divisor}`;case"unrecognized_keys":return`${o.keys.length>1?"Ukjente n\xF8kler":"Ukjent n\xF8kkel"}: ${Ye(o.keys,", ")}`;case"invalid_key":return`Ugyldig n\xF8kkel i ${o.origin}`;case"invalid_union":return"Ugyldig input";case"invalid_element":return`Ugyldig verdi i ${o.origin}`;default:return"Ugyldig input"}}}}});function ygr(){return{localeError:kfe()}}var kfe,vgr=S({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ota.js"(){kt(),kfe=()=>{const e={string:{unit:"harf",verb:"olmal\u0131d\u0131r"},file:{unit:"bayt",verb:"olmal\u0131d\u0131r"},array:{unit:"unsur",verb:"olmal\u0131d\u0131r"},set:{unit:"unsur",verb:"olmal\u0131d\u0131r"}};function t(o){return e[o]??null}const r={regex:"giren",email:"epostag\xE2h",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO heng\xE2m\u0131",date:"ISO tarihi",time:"ISO zaman\u0131",duration:"ISO m\xFCddeti",ipv4:"IPv4 ni\u015F\xE2n\u0131",ipv6:"IPv6 ni\u015F\xE2n\u0131",cidrv4:"IPv4 menzili",cidrv6:"IPv6 menzili",base64:"base64-\u015Fifreli metin",base64url:"base64url-\u015Fifreli metin",json_string:"JSON metin",e164:"E.164 say\u0131s\u0131",jwt:"JWT",template_literal:"giren"},n={nan:"NaN",number:"numara",array:"saf",null:"gayb"};return o=>{switch(o.code){case"invalid_type":{const s=n[o.expected]??o.expected,i=Ut(o.input),a=n[i]??i;return/^[A-Z]/.test(o.expected)?`F\xE2sit giren: umulan instanceof ${o.expected}, al\u0131nan ${a}`:`F\xE2sit giren: umulan ${s}, al\u0131nan ${a}`}case"invalid_value":return o.values.length===1?`F\xE2sit giren: umulan ${Ot(o.values[0])}`:`F\xE2sit tercih: m\xFBteberler ${Ye(o.values,"|")}`;case"too_big":{const s=o.inclusive?"<=":"<",i=t(o.origin);return i?`Fazla b\xFCy\xFCk: ${o.origin??"value"}, ${s}${o.maximum.toString()} ${i.unit??"elements"} sahip olmal\u0131yd\u0131.`:`Fazla b\xFCy\xFCk: ${o.origin??"value"}, ${s}${o.maximum.toString()} olmal\u0131yd\u0131.`}case"too_small":{const s=o.inclusive?">=":">",i=t(o.origin);return i?`Fazla k\xFC\xE7\xFCk: ${o.origin}, ${s}${o.minimum.toString()} ${i.unit} sahip olmal\u0131yd\u0131.`:`Fazla k\xFC\xE7\xFCk: ${o.origin}, ${s}${o.minimum.toString()} olmal\u0131yd\u0131.`}case"invalid_format":{const s=o;return s.format==="starts_with"?`F\xE2sit metin: "${s.prefix}" ile ba\u015Flamal\u0131.`:s.format==="ends_with"?`F\xE2sit metin: "${s.suffix}" ile bitmeli.`:s.format==="includes"?`F\xE2sit metin: "${s.includes}" ihtiv\xE2 etmeli.`:s.format==="regex"?`F\xE2sit metin: ${s.pattern} nak\u015F\u0131na uymal\u0131.`:`F\xE2sit ${r[s.format]??o.format}`}case"not_multiple_of":return`F\xE2sit say\u0131: ${o.divisor} kat\u0131 olmal\u0131yd\u0131.`;case"unrecognized_keys":return`Tan\u0131nmayan anahtar ${o.keys.length>1?"s":""}: ${Ye(o.keys,", ")}`;case"invalid_key":return`${o.origin} i\xE7in tan\u0131nmayan anahtar var.`;case"invalid_union":return"Giren tan\u0131namad\u0131.";case"invalid_element":return`${o.origin} i\xE7in tan\u0131nmayan k\u0131ymet var.`;default:return"K\u0131ymet tan\u0131namad\u0131."}}}}});function _gr(){return{localeError:xfe()}}var xfe,wgr=S({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ps.js"(){kt(),xfe=()=>{const e={string:{unit:"\u062A\u0648\u06A9\u064A",verb:"\u0648\u0644\u0631\u064A"},file:{unit:"\u0628\u0627\u06CC\u067C\u0633",verb:"\u0648\u0644\u0631\u064A"},array:{unit:"\u062A\u0648\u06A9\u064A",verb:"\u0648\u0644\u0631\u064A"},set:{unit:"\u062A\u0648\u06A9\u064A",verb:"\u0648\u0644\u0631\u064A"}};function t(o){return e[o]??null}const r={regex:"\u0648\u0631\u0648\u062F\u064A",email:"\u0628\u0631\u06CC\u069A\u0646\u0627\u0644\u06CC\u06A9",url:"\u06CC\u0648 \u0622\u0631 \u0627\u0644",emoji:"\u0627\u06CC\u0645\u0648\u062C\u064A",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"\u0646\u06CC\u067C\u0647 \u0627\u0648 \u0648\u062E\u062A",date:"\u0646\u06D0\u067C\u0647",time:"\u0648\u062E\u062A",duration:"\u0645\u0648\u062F\u0647",ipv4:"\u062F IPv4 \u067E\u062A\u0647",ipv6:"\u062F IPv6 \u067E\u062A\u0647",cidrv4:"\u062F IPv4 \u0633\u0627\u062D\u0647",cidrv6:"\u062F IPv6 \u0633\u0627\u062D\u0647",base64:"base64-encoded \u0645\u062A\u0646",base64url:"base64url-encoded \u0645\u062A\u0646",json_string:"JSON \u0645\u062A\u0646",e164:"\u062F E.164 \u0634\u0645\u06D0\u0631\u0647",jwt:"JWT",template_literal:"\u0648\u0631\u0648\u062F\u064A"},n={nan:"NaN",number:"\u0639\u062F\u062F",array:"\u0627\u0631\u06D0"};return o=>{switch(o.code){case"invalid_type":{const s=n[o.expected]??o.expected,i=Ut(o.input),a=n[i]??i;return/^[A-Z]/.test(o.expected)?`\u0646\u0627\u0633\u0645 \u0648\u0631\u0648\u062F\u064A: \u0628\u0627\u06CC\u062F instanceof ${o.expected} \u0648\u0627\u06CC, \u0645\u06AB\u0631 ${a} \u062A\u0631\u0644\u0627\u0633\u0647 \u0634\u0648`:`\u0646\u0627\u0633\u0645 \u0648\u0631\u0648\u062F\u064A: \u0628\u0627\u06CC\u062F ${s} \u0648\u0627\u06CC, \u0645\u06AB\u0631 ${a} \u062A\u0631\u0644\u0627\u0633\u0647 \u0634\u0648`}case"invalid_value":return o.values.length===1?`\u0646\u0627\u0633\u0645 \u0648\u0631\u0648\u062F\u064A: \u0628\u0627\u06CC\u062F ${Ot(o.values[0])} \u0648\u0627\u06CC`:`\u0646\u0627\u0633\u0645 \u0627\u0646\u062A\u062E\u0627\u0628: \u0628\u0627\u06CC\u062F \u06CC\u0648 \u0644\u0647 ${Ye(o.values,"|")} \u0685\u062E\u0647 \u0648\u0627\u06CC`;case"too_big":{const s=o.inclusive?"<=":"<",i=t(o.origin);return i?`\u0689\u06CC\u0631 \u0644\u0648\u06CC: ${o.origin??"\u0627\u0631\u0632\u069A\u062A"} \u0628\u0627\u06CC\u062F ${s}${o.maximum.toString()} ${i.unit??"\u0639\u0646\u0635\u0631\u0648\u0646\u0647"} \u0648\u0644\u0631\u064A`:`\u0689\u06CC\u0631 \u0644\u0648\u06CC: ${o.origin??"\u0627\u0631\u0632\u069A\u062A"} \u0628\u0627\u06CC\u062F ${s}${o.maximum.toString()} \u0648\u064A`}case"too_small":{const s=o.inclusive?">=":">",i=t(o.origin);return i?`\u0689\u06CC\u0631 \u06A9\u0648\u0686\u0646\u06CC: ${o.origin} \u0628\u0627\u06CC\u062F ${s}${o.minimum.toString()} ${i.unit} \u0648\u0644\u0631\u064A`:`\u0689\u06CC\u0631 \u06A9\u0648\u0686\u0646\u06CC: ${o.origin} \u0628\u0627\u06CC\u062F ${s}${o.minimum.toString()} \u0648\u064A`}case"invalid_format":{const s=o;return s.format==="starts_with"?`\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F \u062F "${s.prefix}" \u0633\u0631\u0647 \u067E\u06CC\u0644 \u0634\u064A`:s.format==="ends_with"?`\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F \u062F "${s.suffix}" \u0633\u0631\u0647 \u067E\u0627\u06CC \u062A\u0647 \u0648\u0631\u0633\u064A\u0696\u064A`:s.format==="includes"?`\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F "${s.includes}" \u0648\u0644\u0631\u064A`:s.format==="regex"?`\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F \u062F ${s.pattern} \u0633\u0631\u0647 \u0645\u0637\u0627\u0628\u0642\u062A \u0648\u0644\u0631\u064A`:`${r[s.format]??o.format} \u0646\u0627\u0633\u0645 \u062F\u06CC`}case"not_multiple_of":return`\u0646\u0627\u0633\u0645 \u0639\u062F\u062F: \u0628\u0627\u06CC\u062F \u062F ${o.divisor} \u0645\u0636\u0631\u0628 \u0648\u064A`;case"unrecognized_keys":return`\u0646\u0627\u0633\u0645 ${o.keys.length>1?"\u06A9\u0644\u06CC\u0689\u0648\u0646\u0647":"\u06A9\u0644\u06CC\u0689"}: ${Ye(o.keys,", ")}`;case"invalid_key":return`\u0646\u0627\u0633\u0645 \u06A9\u0644\u06CC\u0689 \u067E\u0647 ${o.origin} \u06A9\u06D0`;case"invalid_union":return"\u0646\u0627\u0633\u0645\u0647 \u0648\u0631\u0648\u062F\u064A";case"invalid_element":return`\u0646\u0627\u0633\u0645 \u0639\u0646\u0635\u0631 \u067E\u0647 ${o.origin} \u06A9\u06D0`;default:return"\u0646\u0627\u0633\u0645\u0647 \u0648\u0631\u0648\u062F\u064A"}}}}});function bgr(){return{localeError:Afe()}}var Afe,Tgr=S({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/pl.js"(){kt(),Afe=()=>{const e={string:{unit:"znak\xF3w",verb:"mie\u0107"},file:{unit:"bajt\xF3w",verb:"mie\u0107"},array:{unit:"element\xF3w",verb:"mie\u0107"},set:{unit:"element\xF3w",verb:"mie\u0107"}};function t(o){return e[o]??null}const r={regex:"wyra\u017Cenie",email:"adres email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data i godzina w formacie ISO",date:"data w formacie ISO",time:"godzina w formacie ISO",duration:"czas trwania ISO",ipv4:"adres IPv4",ipv6:"adres IPv6",cidrv4:"zakres IPv4",cidrv6:"zakres IPv6",base64:"ci\u0105g znak\xF3w zakodowany w formacie base64",base64url:"ci\u0105g znak\xF3w zakodowany w formacie base64url",json_string:"ci\u0105g znak\xF3w w formacie JSON",e164:"liczba E.164",jwt:"JWT",template_literal:"wej\u015Bcie"},n={nan:"NaN",number:"liczba",array:"tablica"};return o=>{switch(o.code){case"invalid_type":{const s=n[o.expected]??o.expected,i=Ut(o.input),a=n[i]??i;return/^[A-Z]/.test(o.expected)?`Nieprawid\u0142owe dane wej\u015Bciowe: oczekiwano instanceof ${o.expected}, otrzymano ${a}`:`Nieprawid\u0142owe dane wej\u015Bciowe: oczekiwano ${s}, otrzymano ${a}`}case"invalid_value":return o.values.length===1?`Nieprawid\u0142owe dane wej\u015Bciowe: oczekiwano ${Ot(o.values[0])}`:`Nieprawid\u0142owa opcja: oczekiwano jednej z warto\u015Bci ${Ye(o.values,"|")}`;case"too_big":{const s=o.inclusive?"<=":"<",i=t(o.origin);return i?`Za du\u017Ca warto\u015B\u0107: oczekiwano, \u017Ce ${o.origin??"warto\u015B\u0107"} b\u0119dzie mie\u0107 ${s}${o.maximum.toString()} ${i.unit??"element\xF3w"}`:`Zbyt du\u017C(y/a/e): oczekiwano, \u017Ce ${o.origin??"warto\u015B\u0107"} b\u0119dzie wynosi\u0107 ${s}${o.maximum.toString()}`}case"too_small":{const s=o.inclusive?">=":">",i=t(o.origin);return i?`Za ma\u0142a warto\u015B\u0107: oczekiwano, \u017Ce ${o.origin??"warto\u015B\u0107"} b\u0119dzie mie\u0107 ${s}${o.minimum.toString()} ${i.unit??"element\xF3w"}`:`Zbyt ma\u0142(y/a/e): oczekiwano, \u017Ce ${o.origin??"warto\u015B\u0107"} b\u0119dzie wynosi\u0107 ${s}${o.minimum.toString()}`}case"invalid_format":{const s=o;return s.format==="starts_with"?`Nieprawid\u0142owy ci\u0105g znak\xF3w: musi zaczyna\u0107 si\u0119 od "${s.prefix}"`:s.format==="ends_with"?`Nieprawid\u0142owy ci\u0105g znak\xF3w: musi ko\u0144czy\u0107 si\u0119 na "${s.suffix}"`:s.format==="includes"?`Nieprawid\u0142owy ci\u0105g znak\xF3w: musi zawiera\u0107 "${s.includes}"`:s.format==="regex"?`Nieprawid\u0142owy ci\u0105g znak\xF3w: musi odpowiada\u0107 wzorcowi ${s.pattern}`:`Nieprawid\u0142ow(y/a/e) ${r[s.format]??o.format}`}case"not_multiple_of":return`Nieprawid\u0142owa liczba: musi by\u0107 wielokrotno\u015Bci\u0105 ${o.divisor}`;case"unrecognized_keys":return`Nierozpoznane klucze${o.keys.length>1?"s":""}: ${Ye(o.keys,", ")}`;case"invalid_key":return`Nieprawid\u0142owy klucz w ${o.origin}`;case"invalid_union":return"Nieprawid\u0142owe dane wej\u015Bciowe";case"invalid_element":return`Nieprawid\u0142owa warto\u015B\u0107 w ${o.origin}`;default:return"Nieprawid\u0142owe dane wej\u015Bciowe"}}}}});function Egr(){return{localeError:Ife()}}var Ife,Sgr=S({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/pt.js"(){kt(),Ife=()=>{const e={string:{unit:"caracteres",verb:"ter"},file:{unit:"bytes",verb:"ter"},array:{unit:"itens",verb:"ter"},set:{unit:"itens",verb:"ter"}};function t(o){return e[o]??null}const r={regex:"padr\xE3o",email:"endere\xE7o de e-mail",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data e hora ISO",date:"data ISO",time:"hora ISO",duration:"dura\xE7\xE3o ISO",ipv4:"endere\xE7o IPv4",ipv6:"endere\xE7o IPv6",cidrv4:"faixa de IPv4",cidrv6:"faixa de IPv6",base64:"texto codificado em base64",base64url:"URL codificada em base64",json_string:"texto JSON",e164:"n\xFAmero E.164",jwt:"JWT",template_literal:"entrada"},n={nan:"NaN",number:"n\xFAmero",null:"nulo"};return o=>{switch(o.code){case"invalid_type":{const s=n[o.expected]??o.expected,i=Ut(o.input),a=n[i]??i;return/^[A-Z]/.test(o.expected)?`Tipo inv\xE1lido: esperado instanceof ${o.expected}, recebido ${a}`:`Tipo inv\xE1lido: esperado ${s}, recebido ${a}`}case"invalid_value":return o.values.length===1?`Entrada inv\xE1lida: esperado ${Ot(o.values[0])}`:`Op\xE7\xE3o inv\xE1lida: esperada uma das ${Ye(o.values,"|")}`;case"too_big":{const s=o.inclusive?"<=":"<",i=t(o.origin);return i?`Muito grande: esperado que ${o.origin??"valor"} tivesse ${s}${o.maximum.toString()} ${i.unit??"elementos"}`:`Muito grande: esperado que ${o.origin??"valor"} fosse ${s}${o.maximum.toString()}`}case"too_small":{const s=o.inclusive?">=":">",i=t(o.origin);return i?`Muito pequeno: esperado que ${o.origin} tivesse ${s}${o.minimum.toString()} ${i.unit}`:`Muito pequeno: esperado que ${o.origin} fosse ${s}${o.minimum.toString()}`}case"invalid_format":{const s=o;return s.format==="starts_with"?`Texto inv\xE1lido: deve come\xE7ar com "${s.prefix}"`:s.format==="ends_with"?`Texto inv\xE1lido: deve terminar com "${s.suffix}"`:s.format==="includes"?`Texto inv\xE1lido: deve incluir "${s.includes}"`:s.format==="regex"?`Texto inv\xE1lido: deve corresponder ao padr\xE3o ${s.pattern}`:`${r[s.format]??o.format} inv\xE1lido`}case"not_multiple_of":return`N\xFAmero inv\xE1lido: deve ser m\xFAltiplo de ${o.divisor}`;case"unrecognized_keys":return`Chave${o.keys.length>1?"s":""} desconhecida${o.keys.length>1?"s":""}: ${Ye(o.keys,", ")}`;case"invalid_key":return`Chave inv\xE1lida em ${o.origin}`;case"invalid_union":return"Entrada inv\xE1lida";case"invalid_element":return`Valor inv\xE1lido em ${o.origin}`;default:return"Campo inv\xE1lido"}}}}});function Rfe(e,t,r,n){const o=Math.abs(e),s=o%10,i=o%100;return i>=11&&i<=19?n:s===1?t:s>=2&&s<=4?r:n}function Cgr(){return{localeError:Mfe()}}var Mfe,kgr=S({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ru.js"(){kt(),Mfe=()=>{const e={string:{unit:{one:"\u0441\u0438\u043C\u0432\u043E\u043B",few:"\u0441\u0438\u043C\u0432\u043E\u043B\u0430",many:"\u0441\u0438\u043C\u0432\u043E\u043B\u043E\u0432"},verb:"\u0438\u043C\u0435\u0442\u044C"},file:{unit:{one:"\u0431\u0430\u0439\u0442",few:"\u0431\u0430\u0439\u0442\u0430",many:"\u0431\u0430\u0439\u0442"},verb:"\u0438\u043C\u0435\u0442\u044C"},array:{unit:{one:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442",few:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430",many:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u043E\u0432"},verb:"\u0438\u043C\u0435\u0442\u044C"},set:{unit:{one:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442",few:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430",many:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u043E\u0432"},verb:"\u0438\u043C\u0435\u0442\u044C"}};function t(o){return e[o]??null}const r={regex:"\u0432\u0432\u043E\u0434",email:"email \u0430\u0434\u0440\u0435\u0441",url:"URL",emoji:"\u044D\u043C\u043E\u0434\u0437\u0438",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO \u0434\u0430\u0442\u0430 \u0438 \u0432\u0440\u0435\u043C\u044F",date:"ISO \u0434\u0430\u0442\u0430",time:"ISO \u0432\u0440\u0435\u043C\u044F",duration:"ISO \u0434\u043B\u0438\u0442\u0435\u043B\u044C\u043D\u043E\u0441\u0442\u044C",ipv4:"IPv4 \u0430\u0434\u0440\u0435\u0441",ipv6:"IPv6 \u0430\u0434\u0440\u0435\u0441",cidrv4:"IPv4 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D",cidrv6:"IPv6 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D",base64:"\u0441\u0442\u0440\u043E\u043A\u0430 \u0432 \u0444\u043E\u0440\u043C\u0430\u0442\u0435 base64",base64url:"\u0441\u0442\u0440\u043E\u043A\u0430 \u0432 \u0444\u043E\u0440\u043C\u0430\u0442\u0435 base64url",json_string:"JSON \u0441\u0442\u0440\u043E\u043A\u0430",e164:"\u043D\u043E\u043C\u0435\u0440 E.164",jwt:"JWT",template_literal:"\u0432\u0432\u043E\u0434"},n={nan:"NaN",number:"\u0447\u0438\u0441\u043B\u043E",array:"\u043C\u0430\u0441\u0441\u0438\u0432"};return o=>{switch(o.code){case"invalid_type":{const s=n[o.expected]??o.expected,i=Ut(o.input),a=n[i]??i;return/^[A-Z]/.test(o.expected)?`\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0432\u043E\u0434: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C instanceof ${o.expected}, \u043F\u043E\u043B\u0443\u0447\u0435\u043D\u043E ${a}`:`\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0432\u043E\u0434: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C ${s}, \u043F\u043E\u043B\u0443\u0447\u0435\u043D\u043E ${a}`}case"invalid_value":return o.values.length===1?`\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0432\u043E\u0434: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C ${Ot(o.values[0])}`:`\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0430\u0440\u0438\u0430\u043D\u0442: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C \u043E\u0434\u043D\u043E \u0438\u0437 ${Ye(o.values,"|")}`;case"too_big":{const s=o.inclusive?"<=":"<",i=t(o.origin);if(i){const a=Number(o.maximum),l=Rfe(a,i.unit.one,i.unit.few,i.unit.many);return`\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u0431\u043E\u043B\u044C\u0448\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${o.origin??"\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435"} \u0431\u0443\u0434\u0435\u0442 \u0438\u043C\u0435\u0442\u044C ${s}${o.maximum.toString()} ${l}`}return`\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u0431\u043E\u043B\u044C\u0448\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${o.origin??"\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435"} \u0431\u0443\u0434\u0435\u0442 ${s}${o.maximum.toString()}`}case"too_small":{const s=o.inclusive?">=":">",i=t(o.origin);if(i){const a=Number(o.minimum),l=Rfe(a,i.unit.one,i.unit.few,i.unit.many);return`\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u043C\u0430\u043B\u0435\u043D\u044C\u043A\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${o.origin} \u0431\u0443\u0434\u0435\u0442 \u0438\u043C\u0435\u0442\u044C ${s}${o.minimum.toString()} ${l}`}return`\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u043C\u0430\u043B\u0435\u043D\u044C\u043A\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${o.origin} \u0431\u0443\u0434\u0435\u0442 ${s}${o.minimum.toString()}`}case"invalid_format":{const s=o;return s.format==="starts_with"?`\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u043D\u0430\u0447\u0438\u043D\u0430\u0442\u044C\u0441\u044F \u0441 "${s.prefix}"`:s.format==="ends_with"?`\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u0437\u0430\u043A\u0430\u043D\u0447\u0438\u0432\u0430\u0442\u044C\u0441\u044F \u043D\u0430 "${s.suffix}"`:s.format==="includes"?`\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u0441\u043E\u0434\u0435\u0440\u0436\u0430\u0442\u044C "${s.includes}"`:s.format==="regex"?`\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u0441\u043E\u043E\u0442\u0432\u0435\u0442\u0441\u0442\u0432\u043E\u0432\u0430\u0442\u044C \u0448\u0430\u0431\u043B\u043E\u043D\u0443 ${s.pattern}`:`\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 ${r[s.format]??o.format}`}case"not_multiple_of":return`\u041D\u0435\u0432\u0435\u0440\u043D\u043E\u0435 \u0447\u0438\u0441\u043B\u043E: \u0434\u043E\u043B\u0436\u043D\u043E \u0431\u044B\u0442\u044C \u043A\u0440\u0430\u0442\u043D\u044B\u043C ${o.divisor}`;case"unrecognized_keys":return`\u041D\u0435\u0440\u0430\u0441\u043F\u043E\u0437\u043D\u0430\u043D\u043D${o.keys.length>1?"\u044B\u0435":"\u044B\u0439"} \u043A\u043B\u044E\u0447${o.keys.length>1?"\u0438":""}: ${Ye(o.keys,", ")}`;case"invalid_key":return`\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u043A\u043B\u044E\u0447 \u0432 ${o.origin}`;case"invalid_union":return"\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0435 \u0432\u0445\u043E\u0434\u043D\u044B\u0435 \u0434\u0430\u043D\u043D\u044B\u0435";case"invalid_element":return`\u041D\u0435\u0432\u0435\u0440\u043D\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435 \u0432 ${o.origin}`;default:return"\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0435 \u0432\u0445\u043E\u0434\u043D\u044B\u0435 \u0434\u0430\u043D\u043D\u044B\u0435"}}}}});function xgr(){return{localeError:Pfe()}}var Pfe,Agr=S({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/sl.js"(){kt(),Pfe=()=>{const e={string:{unit:"znakov",verb:"imeti"},file:{unit:"bajtov",verb:"imeti"},array:{unit:"elementov",verb:"imeti"},set:{unit:"elementov",verb:"imeti"}};function t(o){return e[o]??null}const r={regex:"vnos",email:"e-po\u0161tni naslov",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datum in \u010Das",date:"ISO datum",time:"ISO \u010Das",duration:"ISO trajanje",ipv4:"IPv4 naslov",ipv6:"IPv6 naslov",cidrv4:"obseg IPv4",cidrv6:"obseg IPv6",base64:"base64 kodiran niz",base64url:"base64url kodiran niz",json_string:"JSON niz",e164:"E.164 \u0161tevilka",jwt:"JWT",template_literal:"vnos"},n={nan:"NaN",number:"\u0161tevilo",array:"tabela"};return o=>{switch(o.code){case"invalid_type":{const s=n[o.expected]??o.expected,i=Ut(o.input),a=n[i]??i;return/^[A-Z]/.test(o.expected)?`Neveljaven vnos: pri\u010Dakovano instanceof ${o.expected}, prejeto ${a}`:`Neveljaven vnos: pri\u010Dakovano ${s}, prejeto ${a}`}case"invalid_value":return o.values.length===1?`Neveljaven vnos: pri\u010Dakovano ${Ot(o.values[0])}`:`Neveljavna mo\u017Enost: pri\u010Dakovano eno izmed ${Ye(o.values,"|")}`;case"too_big":{const s=o.inclusive?"<=":"<",i=t(o.origin);return i?`Preveliko: pri\u010Dakovano, da bo ${o.origin??"vrednost"} imelo ${s}${o.maximum.toString()} ${i.unit??"elementov"}`:`Preveliko: pri\u010Dakovano, da bo ${o.origin??"vrednost"} ${s}${o.maximum.toString()}`}case"too_small":{const s=o.inclusive?">=":">",i=t(o.origin);return i?`Premajhno: pri\u010Dakovano, da bo ${o.origin} imelo ${s}${o.minimum.toString()} ${i.unit}`:`Premajhno: pri\u010Dakovano, da bo ${o.origin} ${s}${o.minimum.toString()}`}case"invalid_format":{const s=o;return s.format==="starts_with"?`Neveljaven niz: mora se za\u010Deti z "${s.prefix}"`:s.format==="ends_with"?`Neveljaven niz: mora se kon\u010Dati z "${s.suffix}"`:s.format==="includes"?`Neveljaven niz: mora vsebovati "${s.includes}"`:s.format==="regex"?`Neveljaven niz: mora ustrezati vzorcu ${s.pattern}`:`Neveljaven ${r[s.format]??o.format}`}case"not_multiple_of":return`Neveljavno \u0161tevilo: mora biti ve\u010Dkratnik ${o.divisor}`;case"unrecognized_keys":return`Neprepoznan${o.keys.length>1?"i klju\u010Di":" klju\u010D"}: ${Ye(o.keys,", ")}`;case"invalid_key":return`Neveljaven klju\u010D v ${o.origin}`;case"invalid_union":return"Neveljaven vnos";case"invalid_element":return`Neveljavna vrednost v ${o.origin}`;default:return"Neveljaven vnos"}}}}});function Igr(){return{localeError:Dfe()}}var Dfe,Rgr=S({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/sv.js"(){kt(),Dfe=()=>{const e={string:{unit:"tecken",verb:"att ha"},file:{unit:"bytes",verb:"att ha"},array:{unit:"objekt",verb:"att inneh\xE5lla"},set:{unit:"objekt",verb:"att inneh\xE5lla"}};function t(o){return e[o]??null}const r={regex:"regulj\xE4rt uttryck",email:"e-postadress",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-datum och tid",date:"ISO-datum",time:"ISO-tid",duration:"ISO-varaktighet",ipv4:"IPv4-intervall",ipv6:"IPv6-intervall",cidrv4:"IPv4-spektrum",cidrv6:"IPv6-spektrum",base64:"base64-kodad str\xE4ng",base64url:"base64url-kodad str\xE4ng",json_string:"JSON-str\xE4ng",e164:"E.164-nummer",jwt:"JWT",template_literal:"mall-literal"},n={nan:"NaN",number:"antal",array:"lista"};return o=>{switch(o.code){case"invalid_type":{const s=n[o.expected]??o.expected,i=Ut(o.input),a=n[i]??i;return/^[A-Z]/.test(o.expected)?`Ogiltig inmatning: f\xF6rv\xE4ntat instanceof ${o.expected}, fick ${a}`:`Ogiltig inmatning: f\xF6rv\xE4ntat ${s}, fick ${a}`}case"invalid_value":return o.values.length===1?`Ogiltig inmatning: f\xF6rv\xE4ntat ${Ot(o.values[0])}`:`Ogiltigt val: f\xF6rv\xE4ntade en av ${Ye(o.values,"|")}`;case"too_big":{const s=o.inclusive?"<=":"<",i=t(o.origin);return i?`F\xF6r stor(t): f\xF6rv\xE4ntade ${o.origin??"v\xE4rdet"} att ha ${s}${o.maximum.toString()} ${i.unit??"element"}`:`F\xF6r stor(t): f\xF6rv\xE4ntat ${o.origin??"v\xE4rdet"} att ha ${s}${o.maximum.toString()}`}case"too_small":{const s=o.inclusive?">=":">",i=t(o.origin);return i?`F\xF6r lite(t): f\xF6rv\xE4ntade ${o.origin??"v\xE4rdet"} att ha ${s}${o.minimum.toString()} ${i.unit}`:`F\xF6r lite(t): f\xF6rv\xE4ntade ${o.origin??"v\xE4rdet"} att ha ${s}${o.minimum.toString()}`}case"invalid_format":{const s=o;return s.format==="starts_with"?`Ogiltig str\xE4ng: m\xE5ste b\xF6rja med "${s.prefix}"`:s.format==="ends_with"?`Ogiltig str\xE4ng: m\xE5ste sluta med "${s.suffix}"`:s.format==="includes"?`Ogiltig str\xE4ng: m\xE5ste inneh\xE5lla "${s.includes}"`:s.format==="regex"?`Ogiltig str\xE4ng: m\xE5ste matcha m\xF6nstret "${s.pattern}"`:`Ogiltig(t) ${r[s.format]??o.format}`}case"not_multiple_of":return`Ogiltigt tal: m\xE5ste vara en multipel av ${o.divisor}`;case"unrecognized_keys":return`${o.keys.length>1?"Ok\xE4nda nycklar":"Ok\xE4nd nyckel"}: ${Ye(o.keys,", ")}`;case"invalid_key":return`Ogiltig nyckel i ${o.origin??"v\xE4rdet"}`;case"invalid_union":return"Ogiltig input";case"invalid_element":return`Ogiltigt v\xE4rde i ${o.origin??"v\xE4rdet"}`;default:return"Ogiltig input"}}}}});function Mgr(){return{localeError:Ofe()}}var Ofe,Pgr=S({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ta.js"(){kt(),Ofe=()=>{const e={string:{unit:"\u0B8E\u0BB4\u0BC1\u0BA4\u0BCD\u0BA4\u0BC1\u0B95\u0BCD\u0B95\u0BB3\u0BCD",verb:"\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD"},file:{unit:"\u0BAA\u0BC8\u0B9F\u0BCD\u0B9F\u0BC1\u0B95\u0BB3\u0BCD",verb:"\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD"},array:{unit:"\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD",verb:"\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD"},set:{unit:"\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD",verb:"\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD"}};function t(o){return e[o]??null}const r={regex:"\u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1",email:"\u0BAE\u0BBF\u0BA9\u0BCD\u0BA9\u0B9E\u0BCD\u0B9A\u0BB2\u0BCD \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO \u0BA4\u0BC7\u0BA4\u0BBF \u0BA8\u0BC7\u0BB0\u0BAE\u0BCD",date:"ISO \u0BA4\u0BC7\u0BA4\u0BBF",time:"ISO \u0BA8\u0BC7\u0BB0\u0BAE\u0BCD",duration:"ISO \u0B95\u0BBE\u0BB2 \u0B85\u0BB3\u0BB5\u0BC1",ipv4:"IPv4 \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF",ipv6:"IPv6 \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF",cidrv4:"IPv4 \u0BB5\u0BB0\u0BAE\u0BCD\u0BAA\u0BC1",cidrv6:"IPv6 \u0BB5\u0BB0\u0BAE\u0BCD\u0BAA\u0BC1",base64:"base64-encoded \u0B9A\u0BB0\u0BAE\u0BCD",base64url:"base64url-encoded \u0B9A\u0BB0\u0BAE\u0BCD",json_string:"JSON \u0B9A\u0BB0\u0BAE\u0BCD",e164:"E.164 \u0B8E\u0BA3\u0BCD",jwt:"JWT",template_literal:"input"},n={nan:"NaN",number:"\u0B8E\u0BA3\u0BCD",array:"\u0B85\u0BA3\u0BBF",null:"\u0BB5\u0BC6\u0BB1\u0BC1\u0BAE\u0BC8"};return o=>{switch(o.code){case"invalid_type":{const s=n[o.expected]??o.expected,i=Ut(o.input),a=n[i]??i;return/^[A-Z]/.test(o.expected)?`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 instanceof ${o.expected}, \u0BAA\u0BC6\u0BB1\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${a}`:`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${s}, \u0BAA\u0BC6\u0BB1\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${a}`}case"invalid_value":return o.values.length===1?`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${Ot(o.values[0])}`:`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0BB5\u0BBF\u0BB0\u0BC1\u0BAA\u0BCD\u0BAA\u0BAE\u0BCD: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${Ye(o.values,"|")} \u0B87\u0BB2\u0BCD \u0B92\u0BA9\u0BCD\u0BB1\u0BC1`;case"too_big":{const s=o.inclusive?"<=":"<",i=t(o.origin);return i?`\u0BAE\u0BBF\u0B95 \u0BAA\u0BC6\u0BB0\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${o.origin??"\u0BAE\u0BA4\u0BBF\u0BAA\u0BCD\u0BAA\u0BC1"} ${s}${o.maximum.toString()} ${i.unit??"\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD"} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`:`\u0BAE\u0BBF\u0B95 \u0BAA\u0BC6\u0BB0\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${o.origin??"\u0BAE\u0BA4\u0BBF\u0BAA\u0BCD\u0BAA\u0BC1"} ${s}${o.maximum.toString()} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`}case"too_small":{const s=o.inclusive?">=":">",i=t(o.origin);return i?`\u0BAE\u0BBF\u0B95\u0B9A\u0BCD \u0B9A\u0BBF\u0BB1\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${o.origin} ${s}${o.minimum.toString()} ${i.unit} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`:`\u0BAE\u0BBF\u0B95\u0B9A\u0BCD \u0B9A\u0BBF\u0BB1\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${o.origin} ${s}${o.minimum.toString()} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`}case"invalid_format":{const s=o;return s.format==="starts_with"?`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: "${s.prefix}" \u0B87\u0BB2\u0BCD \u0BA4\u0BCA\u0B9F\u0B99\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`:s.format==="ends_with"?`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: "${s.suffix}" \u0B87\u0BB2\u0BCD \u0BAE\u0BC1\u0B9F\u0BBF\u0BB5\u0B9F\u0BC8\u0BAF \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`:s.format==="includes"?`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: "${s.includes}" \u0B90 \u0B89\u0BB3\u0BCD\u0BB3\u0B9F\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`:s.format==="regex"?`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: ${s.pattern} \u0BAE\u0BC1\u0BB1\u0BC8\u0BAA\u0BBE\u0B9F\u0BCD\u0B9F\u0BC1\u0B9F\u0BA9\u0BCD \u0BAA\u0BCA\u0BB0\u0BC1\u0BA8\u0BCD\u0BA4 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`:`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 ${r[s.format]??o.format}`}case"not_multiple_of":return`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B8E\u0BA3\u0BCD: ${o.divisor} \u0B87\u0BA9\u0BCD \u0BAA\u0BB2\u0BAE\u0BBE\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;case"unrecognized_keys":return`\u0B85\u0B9F\u0BC8\u0BAF\u0BBE\u0BB3\u0BAE\u0BCD \u0BA4\u0BC6\u0BB0\u0BBF\u0BAF\u0BBE\u0BA4 \u0BB5\u0BBF\u0B9A\u0BC8${o.keys.length>1?"\u0B95\u0BB3\u0BCD":""}: ${Ye(o.keys,", ")}`;case"invalid_key":return`${o.origin} \u0B87\u0BB2\u0BCD \u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0BB5\u0BBF\u0B9A\u0BC8`;case"invalid_union":return"\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1";case"invalid_element":return`${o.origin} \u0B87\u0BB2\u0BCD \u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0BAE\u0BA4\u0BBF\u0BAA\u0BCD\u0BAA\u0BC1`;default:return"\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1"}}}}});function Dgr(){return{localeError:Nfe()}}var Nfe,Ogr=S({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/th.js"(){kt(),Nfe=()=>{const e={string:{unit:"\u0E15\u0E31\u0E27\u0E2D\u0E31\u0E01\u0E29\u0E23",verb:"\u0E04\u0E27\u0E23\u0E21\u0E35"},file:{unit:"\u0E44\u0E1A\u0E15\u0E4C",verb:"\u0E04\u0E27\u0E23\u0E21\u0E35"},array:{unit:"\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23",verb:"\u0E04\u0E27\u0E23\u0E21\u0E35"},set:{unit:"\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23",verb:"\u0E04\u0E27\u0E23\u0E21\u0E35"}};function t(o){return e[o]??null}const r={regex:"\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E17\u0E35\u0E48\u0E1B\u0E49\u0E2D\u0E19",email:"\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48\u0E2D\u0E35\u0E40\u0E21\u0E25",url:"URL",emoji:"\u0E2D\u0E34\u0E42\u0E21\u0E08\u0E34",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"\u0E27\u0E31\u0E19\u0E17\u0E35\u0E48\u0E40\u0E27\u0E25\u0E32\u0E41\u0E1A\u0E1A ISO",date:"\u0E27\u0E31\u0E19\u0E17\u0E35\u0E48\u0E41\u0E1A\u0E1A ISO",time:"\u0E40\u0E27\u0E25\u0E32\u0E41\u0E1A\u0E1A ISO",duration:"\u0E0A\u0E48\u0E27\u0E07\u0E40\u0E27\u0E25\u0E32\u0E41\u0E1A\u0E1A ISO",ipv4:"\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48 IPv4",ipv6:"\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48 IPv6",cidrv4:"\u0E0A\u0E48\u0E27\u0E07 IP \u0E41\u0E1A\u0E1A IPv4",cidrv6:"\u0E0A\u0E48\u0E27\u0E07 IP \u0E41\u0E1A\u0E1A IPv6",base64:"\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A Base64",base64url:"\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A Base64 \u0E2A\u0E33\u0E2B\u0E23\u0E31\u0E1A URL",json_string:"\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A JSON",e164:"\u0E40\u0E1A\u0E2D\u0E23\u0E4C\u0E42\u0E17\u0E23\u0E28\u0E31\u0E1E\u0E17\u0E4C\u0E23\u0E30\u0E2B\u0E27\u0E48\u0E32\u0E07\u0E1B\u0E23\u0E30\u0E40\u0E17\u0E28 (E.164)",jwt:"\u0E42\u0E17\u0E40\u0E04\u0E19 JWT",template_literal:"\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E17\u0E35\u0E48\u0E1B\u0E49\u0E2D\u0E19"},n={nan:"NaN",number:"\u0E15\u0E31\u0E27\u0E40\u0E25\u0E02",array:"\u0E2D\u0E32\u0E23\u0E4C\u0E40\u0E23\u0E22\u0E4C (Array)",null:"\u0E44\u0E21\u0E48\u0E21\u0E35\u0E04\u0E48\u0E32 (null)"};return o=>{switch(o.code){case"invalid_type":{const s=n[o.expected]??o.expected,i=Ut(o.input),a=n[i]??i;return/^[A-Z]/.test(o.expected)?`\u0E1B\u0E23\u0E30\u0E40\u0E20\u0E17\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19 instanceof ${o.expected} \u0E41\u0E15\u0E48\u0E44\u0E14\u0E49\u0E23\u0E31\u0E1A ${a}`:`\u0E1B\u0E23\u0E30\u0E40\u0E20\u0E17\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19 ${s} \u0E41\u0E15\u0E48\u0E44\u0E14\u0E49\u0E23\u0E31\u0E1A ${a}`}case"invalid_value":return o.values.length===1?`\u0E04\u0E48\u0E32\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19 ${Ot(o.values[0])}`:`\u0E15\u0E31\u0E27\u0E40\u0E25\u0E37\u0E2D\u0E01\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19\u0E2B\u0E19\u0E36\u0E48\u0E07\u0E43\u0E19 ${Ye(o.values,"|")}`;case"too_big":{const s=o.inclusive?"\u0E44\u0E21\u0E48\u0E40\u0E01\u0E34\u0E19":"\u0E19\u0E49\u0E2D\u0E22\u0E01\u0E27\u0E48\u0E32",i=t(o.origin);return i?`\u0E40\u0E01\u0E34\u0E19\u0E01\u0E33\u0E2B\u0E19\u0E14: ${o.origin??"\u0E04\u0E48\u0E32"} \u0E04\u0E27\u0E23\u0E21\u0E35${s} ${o.maximum.toString()} ${i.unit??"\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23"}`:`\u0E40\u0E01\u0E34\u0E19\u0E01\u0E33\u0E2B\u0E19\u0E14: ${o.origin??"\u0E04\u0E48\u0E32"} \u0E04\u0E27\u0E23\u0E21\u0E35${s} ${o.maximum.toString()}`}case"too_small":{const s=o.inclusive?"\u0E2D\u0E22\u0E48\u0E32\u0E07\u0E19\u0E49\u0E2D\u0E22":"\u0E21\u0E32\u0E01\u0E01\u0E27\u0E48\u0E32",i=t(o.origin);return i?`\u0E19\u0E49\u0E2D\u0E22\u0E01\u0E27\u0E48\u0E32\u0E01\u0E33\u0E2B\u0E19\u0E14: ${o.origin} \u0E04\u0E27\u0E23\u0E21\u0E35${s} ${o.minimum.toString()} ${i.unit}`:`\u0E19\u0E49\u0E2D\u0E22\u0E01\u0E27\u0E48\u0E32\u0E01\u0E33\u0E2B\u0E19\u0E14: ${o.origin} \u0E04\u0E27\u0E23\u0E21\u0E35${s} ${o.minimum.toString()}`}case"invalid_format":{const s=o;return s.format==="starts_with"?`\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E15\u0E49\u0E2D\u0E07\u0E02\u0E36\u0E49\u0E19\u0E15\u0E49\u0E19\u0E14\u0E49\u0E27\u0E22 "${s.prefix}"`:s.format==="ends_with"?`\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E15\u0E49\u0E2D\u0E07\u0E25\u0E07\u0E17\u0E49\u0E32\u0E22\u0E14\u0E49\u0E27\u0E22 "${s.suffix}"`:s.format==="includes"?`\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E15\u0E49\u0E2D\u0E07\u0E21\u0E35 "${s.includes}" \u0E2D\u0E22\u0E39\u0E48\u0E43\u0E19\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21`:s.format==="regex"?`\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E15\u0E49\u0E2D\u0E07\u0E15\u0E23\u0E07\u0E01\u0E31\u0E1A\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E17\u0E35\u0E48\u0E01\u0E33\u0E2B\u0E19\u0E14 ${s.pattern}`:`\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: ${r[s.format]??o.format}`}case"not_multiple_of":return`\u0E15\u0E31\u0E27\u0E40\u0E25\u0E02\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E15\u0E49\u0E2D\u0E07\u0E40\u0E1B\u0E47\u0E19\u0E08\u0E33\u0E19\u0E27\u0E19\u0E17\u0E35\u0E48\u0E2B\u0E32\u0E23\u0E14\u0E49\u0E27\u0E22 ${o.divisor} \u0E44\u0E14\u0E49\u0E25\u0E07\u0E15\u0E31\u0E27`;case"unrecognized_keys":return`\u0E1E\u0E1A\u0E04\u0E35\u0E22\u0E4C\u0E17\u0E35\u0E48\u0E44\u0E21\u0E48\u0E23\u0E39\u0E49\u0E08\u0E31\u0E01: ${Ye(o.keys,", ")}`;case"invalid_key":return`\u0E04\u0E35\u0E22\u0E4C\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07\u0E43\u0E19 ${o.origin}`;case"invalid_union":return"\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E44\u0E21\u0E48\u0E15\u0E23\u0E07\u0E01\u0E31\u0E1A\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E22\u0E39\u0E40\u0E19\u0E35\u0E22\u0E19\u0E17\u0E35\u0E48\u0E01\u0E33\u0E2B\u0E19\u0E14\u0E44\u0E27\u0E49";case"invalid_element":return`\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07\u0E43\u0E19 ${o.origin}`;default:return"\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07"}}}}});function Ngr(){return{localeError:Lfe()}}var Lfe,Lgr=S({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/tr.js"(){kt(),Lfe=()=>{const e={string:{unit:"karakter",verb:"olmal\u0131"},file:{unit:"bayt",verb:"olmal\u0131"},array:{unit:"\xF6\u011Fe",verb:"olmal\u0131"},set:{unit:"\xF6\u011Fe",verb:"olmal\u0131"}};function t(o){return e[o]??null}const r={regex:"girdi",email:"e-posta adresi",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO tarih ve saat",date:"ISO tarih",time:"ISO saat",duration:"ISO s\xFCre",ipv4:"IPv4 adresi",ipv6:"IPv6 adresi",cidrv4:"IPv4 aral\u0131\u011F\u0131",cidrv6:"IPv6 aral\u0131\u011F\u0131",base64:"base64 ile \u015Fifrelenmi\u015F metin",base64url:"base64url ile \u015Fifrelenmi\u015F metin",json_string:"JSON dizesi",e164:"E.164 say\u0131s\u0131",jwt:"JWT",template_literal:"\u015Eablon dizesi"},n={nan:"NaN"};return o=>{switch(o.code){case"invalid_type":{const s=n[o.expected]??o.expected,i=Ut(o.input),a=n[i]??i;return/^[A-Z]/.test(o.expected)?`Ge\xE7ersiz de\u011Fer: beklenen instanceof ${o.expected}, al\u0131nan ${a}`:`Ge\xE7ersiz de\u011Fer: beklenen ${s}, al\u0131nan ${a}`}case"invalid_value":return o.values.length===1?`Ge\xE7ersiz de\u011Fer: beklenen ${Ot(o.values[0])}`:`Ge\xE7ersiz se\xE7enek: a\u015Fa\u011F\u0131dakilerden biri olmal\u0131: ${Ye(o.values,"|")}`;case"too_big":{const s=o.inclusive?"<=":"<",i=t(o.origin);return i?`\xC7ok b\xFCy\xFCk: beklenen ${o.origin??"de\u011Fer"} ${s}${o.maximum.toString()} ${i.unit??"\xF6\u011Fe"}`:`\xC7ok b\xFCy\xFCk: beklenen ${o.origin??"de\u011Fer"} ${s}${o.maximum.toString()}`}case"too_small":{const s=o.inclusive?">=":">",i=t(o.origin);return i?`\xC7ok k\xFC\xE7\xFCk: beklenen ${o.origin} ${s}${o.minimum.toString()} ${i.unit}`:`\xC7ok k\xFC\xE7\xFCk: beklenen ${o.origin} ${s}${o.minimum.toString()}`}case"invalid_format":{const s=o;return s.format==="starts_with"?`Ge\xE7ersiz metin: "${s.prefix}" ile ba\u015Flamal\u0131`:s.format==="ends_with"?`Ge\xE7ersiz metin: "${s.suffix}" ile bitmeli`:s.format==="includes"?`Ge\xE7ersiz metin: "${s.includes}" i\xE7ermeli`:s.format==="regex"?`Ge\xE7ersiz metin: ${s.pattern} desenine uymal\u0131`:`Ge\xE7ersiz ${r[s.format]??o.format}`}case"not_multiple_of":return`Ge\xE7ersiz say\u0131: ${o.divisor} ile tam b\xF6l\xFCnebilmeli`;case"unrecognized_keys":return`Tan\u0131nmayan anahtar${o.keys.length>1?"lar":""}: ${Ye(o.keys,", ")}`;case"invalid_key":return`${o.origin} i\xE7inde ge\xE7ersiz anahtar`;case"invalid_union":return"Ge\xE7ersiz de\u011Fer";case"invalid_element":return`${o.origin} i\xE7inde ge\xE7ersiz de\u011Fer`;default:return"Ge\xE7ersiz de\u011Fer"}}}}});function $fe(){return{localeError:Ffe()}}var Ffe,Ufe=S({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/uk.js"(){kt(),Ffe=()=>{const e={string:{unit:"\u0441\u0438\u043C\u0432\u043E\u043B\u0456\u0432",verb:"\u043C\u0430\u0442\u0438\u043C\u0435"},file:{unit:"\u0431\u0430\u0439\u0442\u0456\u0432",verb:"\u043C\u0430\u0442\u0438\u043C\u0435"},array:{unit:"\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432",verb:"\u043C\u0430\u0442\u0438\u043C\u0435"},set:{unit:"\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432",verb:"\u043C\u0430\u0442\u0438\u043C\u0435"}};function t(o){return e[o]??null}const r={regex:"\u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456",email:"\u0430\u0434\u0440\u0435\u0441\u0430 \u0435\u043B\u0435\u043A\u0442\u0440\u043E\u043D\u043D\u043E\u0457 \u043F\u043E\u0448\u0442\u0438",url:"URL",emoji:"\u0435\u043C\u043E\u0434\u0437\u0456",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"\u0434\u0430\u0442\u0430 \u0442\u0430 \u0447\u0430\u0441 ISO",date:"\u0434\u0430\u0442\u0430 ISO",time:"\u0447\u0430\u0441 ISO",duration:"\u0442\u0440\u0438\u0432\u0430\u043B\u0456\u0441\u0442\u044C ISO",ipv4:"\u0430\u0434\u0440\u0435\u0441\u0430 IPv4",ipv6:"\u0430\u0434\u0440\u0435\u0441\u0430 IPv6",cidrv4:"\u0434\u0456\u0430\u043F\u0430\u0437\u043E\u043D IPv4",cidrv6:"\u0434\u0456\u0430\u043F\u0430\u0437\u043E\u043D IPv6",base64:"\u0440\u044F\u0434\u043E\u043A \u0443 \u043A\u043E\u0434\u0443\u0432\u0430\u043D\u043D\u0456 base64",base64url:"\u0440\u044F\u0434\u043E\u043A \u0443 \u043A\u043E\u0434\u0443\u0432\u0430\u043D\u043D\u0456 base64url",json_string:"\u0440\u044F\u0434\u043E\u043A JSON",e164:"\u043D\u043E\u043C\u0435\u0440 E.164",jwt:"JWT",template_literal:"\u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456"},n={nan:"NaN",number:"\u0447\u0438\u0441\u043B\u043E",array:"\u043C\u0430\u0441\u0438\u0432"};return o=>{switch(o.code){case"invalid_type":{const s=n[o.expected]??o.expected,i=Ut(o.input),a=n[i]??i;return/^[A-Z]/.test(o.expected)?`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F instanceof ${o.expected}, \u043E\u0442\u0440\u0438\u043C\u0430\u043D\u043E ${a}`:`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F ${s}, \u043E\u0442\u0440\u0438\u043C\u0430\u043D\u043E ${a}`}case"invalid_value":return o.values.length===1?`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F ${Ot(o.values[0])}`:`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0430 \u043E\u043F\u0446\u0456\u044F: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F \u043E\u0434\u043D\u0435 \u0437 ${Ye(o.values,"|")}`;case"too_big":{const s=o.inclusive?"<=":"<",i=t(o.origin);return i?`\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u0432\u0435\u043B\u0438\u043A\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${o.origin??"\u0437\u043D\u0430\u0447\u0435\u043D\u043D\u044F"} ${i.verb} ${s}${o.maximum.toString()} ${i.unit??"\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432"}`:`\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u0432\u0435\u043B\u0438\u043A\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${o.origin??"\u0437\u043D\u0430\u0447\u0435\u043D\u043D\u044F"} \u0431\u0443\u0434\u0435 ${s}${o.maximum.toString()}`}case"too_small":{const s=o.inclusive?">=":">",i=t(o.origin);return i?`\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u043C\u0430\u043B\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${o.origin} ${i.verb} ${s}${o.minimum.toString()} ${i.unit}`:`\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u043C\u0430\u043B\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${o.origin} \u0431\u0443\u0434\u0435 ${s}${o.minimum.toString()}`}case"invalid_format":{const s=o;return s.format==="starts_with"?`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u043F\u043E\u0447\u0438\u043D\u0430\u0442\u0438\u0441\u044F \u0437 "${s.prefix}"`:s.format==="ends_with"?`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u0437\u0430\u043A\u0456\u043D\u0447\u0443\u0432\u0430\u0442\u0438\u0441\u044F \u043D\u0430 "${s.suffix}"`:s.format==="includes"?`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u043C\u0456\u0441\u0442\u0438\u0442\u0438 "${s.includes}"`:s.format==="regex"?`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u0432\u0456\u0434\u043F\u043E\u0432\u0456\u0434\u0430\u0442\u0438 \u0448\u0430\u0431\u043B\u043E\u043D\u0443 ${s.pattern}`:`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 ${r[s.format]??o.format}`}case"not_multiple_of":return`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0435 \u0447\u0438\u0441\u043B\u043E: \u043F\u043E\u0432\u0438\u043D\u043D\u043E \u0431\u0443\u0442\u0438 \u043A\u0440\u0430\u0442\u043D\u0438\u043C ${o.divisor}`;case"unrecognized_keys":return`\u041D\u0435\u0440\u043E\u0437\u043F\u0456\u0437\u043D\u0430\u043D\u0438\u0439 \u043A\u043B\u044E\u0447${o.keys.length>1?"\u0456":""}: ${Ye(o.keys,", ")}`;case"invalid_key":return`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u043A\u043B\u044E\u0447 \u0443 ${o.origin}`;case"invalid_union":return"\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456";case"invalid_element":return`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u043D\u044F \u0443 ${o.origin}`;default:return"\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456"}}}}});function $gr(){return $fe()}var Fgr=S({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ua.js"(){Ufe()}});function Ugr(){return{localeError:Bfe()}}var Bfe,Bgr=S({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ur.js"(){kt(),Bfe=()=>{const e={string:{unit:"\u062D\u0631\u0648\u0641",verb:"\u06C1\u0648\u0646\u0627"},file:{unit:"\u0628\u0627\u0626\u0679\u0633",verb:"\u06C1\u0648\u0646\u0627"},array:{unit:"\u0622\u0626\u0679\u0645\u0632",verb:"\u06C1\u0648\u0646\u0627"},set:{unit:"\u0622\u0626\u0679\u0645\u0632",verb:"\u06C1\u0648\u0646\u0627"}};function t(o){return e[o]??null}const r={regex:"\u0627\u0646 \u067E\u0679",email:"\u0627\u06CC \u0645\u06CC\u0644 \u0627\u06CC\u0688\u0631\u06CC\u0633",url:"\u06CC\u0648 \u0622\u0631 \u0627\u06CC\u0644",emoji:"\u0627\u06CC\u0645\u0648\u062C\u06CC",uuid:"\u06CC\u0648 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC",uuidv4:"\u06CC\u0648 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC \u0648\u06CC 4",uuidv6:"\u06CC\u0648 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC \u0648\u06CC 6",nanoid:"\u0646\u06CC\u0646\u0648 \u0622\u0626\u06CC \u0688\u06CC",guid:"\u062C\u06CC \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC",cuid:"\u0633\u06CC \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC",cuid2:"\u0633\u06CC \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC 2",ulid:"\u06CC\u0648 \u0627\u06CC\u0644 \u0622\u0626\u06CC \u0688\u06CC",xid:"\u0627\u06CC\u06A9\u0633 \u0622\u0626\u06CC \u0688\u06CC",ksuid:"\u06A9\u06D2 \u0627\u06CC\u0633 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC",datetime:"\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u0688\u06CC\u0679 \u0679\u0627\u0626\u0645",date:"\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u062A\u0627\u0631\u06CC\u062E",time:"\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u0648\u0642\u062A",duration:"\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u0645\u062F\u062A",ipv4:"\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 4 \u0627\u06CC\u0688\u0631\u06CC\u0633",ipv6:"\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 6 \u0627\u06CC\u0688\u0631\u06CC\u0633",cidrv4:"\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 4 \u0631\u06CC\u0646\u062C",cidrv6:"\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 6 \u0631\u06CC\u0646\u062C",base64:"\u0628\u06CC\u0633 64 \u0627\u0646 \u06A9\u0648\u0688\u0688 \u0633\u0679\u0631\u0646\u06AF",base64url:"\u0628\u06CC\u0633 64 \u06CC\u0648 \u0622\u0631 \u0627\u06CC\u0644 \u0627\u0646 \u06A9\u0648\u0688\u0688 \u0633\u0679\u0631\u0646\u06AF",json_string:"\u062C\u06D2 \u0627\u06CC\u0633 \u0627\u0648 \u0627\u06CC\u0646 \u0633\u0679\u0631\u0646\u06AF",e164:"\u0627\u06CC 164 \u0646\u0645\u0628\u0631",jwt:"\u062C\u06D2 \u0688\u0628\u0644\u06CC\u0648 \u0679\u06CC",template_literal:"\u0627\u0646 \u067E\u0679"},n={nan:"NaN",number:"\u0646\u0645\u0628\u0631",array:"\u0622\u0631\u06D2",null:"\u0646\u0644"};return o=>{switch(o.code){case"invalid_type":{const s=n[o.expected]??o.expected,i=Ut(o.input),a=n[i]??i;return/^[A-Z]/.test(o.expected)?`\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679: instanceof ${o.expected} \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627\u060C ${a} \u0645\u0648\u0635\u0648\u0644 \u06C1\u0648\u0627`:`\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679: ${s} \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627\u060C ${a} \u0645\u0648\u0635\u0648\u0644 \u06C1\u0648\u0627`}case"invalid_value":return o.values.length===1?`\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679: ${Ot(o.values[0])} \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`:`\u063A\u0644\u0637 \u0622\u067E\u0634\u0646: ${Ye(o.values,"|")} \u0645\u06CC\u06BA \u0633\u06D2 \u0627\u06CC\u06A9 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`;case"too_big":{const s=o.inclusive?"<=":"<",i=t(o.origin);return i?`\u0628\u06C1\u062A \u0628\u0691\u0627: ${o.origin??"\u0648\u06CC\u0644\u06CC\u0648"} \u06A9\u06D2 ${s}${o.maximum.toString()} ${i.unit??"\u0639\u0646\u0627\u0635\u0631"} \u06C1\u0648\u0646\u06D2 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u06D2`:`\u0628\u06C1\u062A \u0628\u0691\u0627: ${o.origin??"\u0648\u06CC\u0644\u06CC\u0648"} \u06A9\u0627 ${s}${o.maximum.toString()} \u06C1\u0648\u0646\u0627 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`}case"too_small":{const s=o.inclusive?">=":">",i=t(o.origin);return i?`\u0628\u06C1\u062A \u0686\u06BE\u0648\u0679\u0627: ${o.origin} \u06A9\u06D2 ${s}${o.minimum.toString()} ${i.unit} \u06C1\u0648\u0646\u06D2 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u06D2`:`\u0628\u06C1\u062A \u0686\u06BE\u0648\u0679\u0627: ${o.origin} \u06A9\u0627 ${s}${o.minimum.toString()} \u06C1\u0648\u0646\u0627 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`}case"invalid_format":{const s=o;return s.format==="starts_with"?`\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: "${s.prefix}" \u0633\u06D2 \u0634\u0631\u0648\u0639 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`:s.format==="ends_with"?`\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: "${s.suffix}" \u067E\u0631 \u062E\u062A\u0645 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`:s.format==="includes"?`\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: "${s.includes}" \u0634\u0627\u0645\u0644 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`:s.format==="regex"?`\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: \u067E\u06CC\u0679\u0631\u0646 ${s.pattern} \u0633\u06D2 \u0645\u06CC\u0686 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`:`\u063A\u0644\u0637 ${r[s.format]??o.format}`}case"not_multiple_of":return`\u063A\u0644\u0637 \u0646\u0645\u0628\u0631: ${o.divisor} \u06A9\u0627 \u0645\u0636\u0627\u0639\u0641 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`;case"unrecognized_keys":return`\u063A\u06CC\u0631 \u062A\u0633\u0644\u06CC\u0645 \u0634\u062F\u06C1 \u06A9\u06CC${o.keys.length>1?"\u0632":""}: ${Ye(o.keys,"\u060C ")}`;case"invalid_key":return`${o.origin} \u0645\u06CC\u06BA \u063A\u0644\u0637 \u06A9\u06CC`;case"invalid_union":return"\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679";case"invalid_element":return`${o.origin} \u0645\u06CC\u06BA \u063A\u0644\u0637 \u0648\u06CC\u0644\u06CC\u0648`;default:return"\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679"}}}}});function zgr(){return{localeError:zfe()}}var zfe,jgr=S({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/uz.js"(){kt(),zfe=()=>{const e={string:{unit:"belgi",verb:"bo\u2018lishi kerak"},file:{unit:"bayt",verb:"bo\u2018lishi kerak"},array:{unit:"element",verb:"bo\u2018lishi kerak"},set:{unit:"element",verb:"bo\u2018lishi kerak"}};function t(o){return e[o]??null}const r={regex:"kirish",email:"elektron pochta manzili",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO sana va vaqti",date:"ISO sana",time:"ISO vaqt",duration:"ISO davomiylik",ipv4:"IPv4 manzil",ipv6:"IPv6 manzil",mac:"MAC manzil",cidrv4:"IPv4 diapazon",cidrv6:"IPv6 diapazon",base64:"base64 kodlangan satr",base64url:"base64url kodlangan satr",json_string:"JSON satr",e164:"E.164 raqam",jwt:"JWT",template_literal:"kirish"},n={nan:"NaN",number:"raqam",array:"massiv"};return o=>{switch(o.code){case"invalid_type":{const s=n[o.expected]??o.expected,i=Ut(o.input),a=n[i]??i;return/^[A-Z]/.test(o.expected)?`Noto\u2018g\u2018ri kirish: kutilgan instanceof ${o.expected}, qabul qilingan ${a}`:`Noto\u2018g\u2018ri kirish: kutilgan ${s}, qabul qilingan ${a}`}case"invalid_value":return o.values.length===1?`Noto\u2018g\u2018ri kirish: kutilgan ${Ot(o.values[0])}`:`Noto\u2018g\u2018ri variant: quyidagilardan biri kutilgan ${Ye(o.values,"|")}`;case"too_big":{const s=o.inclusive?"<=":"<",i=t(o.origin);return i?`Juda katta: kutilgan ${o.origin??"qiymat"} ${s}${o.maximum.toString()} ${i.unit} ${i.verb}`:`Juda katta: kutilgan ${o.origin??"qiymat"} ${s}${o.maximum.toString()}`}case"too_small":{const s=o.inclusive?">=":">",i=t(o.origin);return i?`Juda kichik: kutilgan ${o.origin} ${s}${o.minimum.toString()} ${i.unit} ${i.verb}`:`Juda kichik: kutilgan ${o.origin} ${s}${o.minimum.toString()}`}case"invalid_format":{const s=o;return s.format==="starts_with"?`Noto\u2018g\u2018ri satr: "${s.prefix}" bilan boshlanishi kerak`:s.format==="ends_with"?`Noto\u2018g\u2018ri satr: "${s.suffix}" bilan tugashi kerak`:s.format==="includes"?`Noto\u2018g\u2018ri satr: "${s.includes}" ni o\u2018z ichiga olishi kerak`:s.format==="regex"?`Noto\u2018g\u2018ri satr: ${s.pattern} shabloniga mos kelishi kerak`:`Noto\u2018g\u2018ri ${r[s.format]??o.format}`}case"not_multiple_of":return`Noto\u2018g\u2018ri raqam: ${o.divisor} ning karralisi bo\u2018lishi kerak`;case"unrecognized_keys":return`Noma\u2019lum kalit${o.keys.length>1?"lar":""}: ${Ye(o.keys,", ")}`;case"invalid_key":return`${o.origin} dagi kalit noto\u2018g\u2018ri`;case"invalid_union":return"Noto\u2018g\u2018ri kirish";case"invalid_element":return`${o.origin} da noto\u2018g\u2018ri qiymat`;default:return"Noto\u2018g\u2018ri kirish"}}}}});function qgr(){return{localeError:jfe()}}var jfe,Ggr=S({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/vi.js"(){kt(),jfe=()=>{const e={string:{unit:"k\xFD t\u1EF1",verb:"c\xF3"},file:{unit:"byte",verb:"c\xF3"},array:{unit:"ph\u1EA7n t\u1EED",verb:"c\xF3"},set:{unit:"ph\u1EA7n t\u1EED",verb:"c\xF3"}};function t(o){return e[o]??null}const r={regex:"\u0111\u1EA7u v\xE0o",email:"\u0111\u1ECBa ch\u1EC9 email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ng\xE0y gi\u1EDD ISO",date:"ng\xE0y ISO",time:"gi\u1EDD ISO",duration:"kho\u1EA3ng th\u1EDDi gian ISO",ipv4:"\u0111\u1ECBa ch\u1EC9 IPv4",ipv6:"\u0111\u1ECBa ch\u1EC9 IPv6",cidrv4:"d\u1EA3i IPv4",cidrv6:"d\u1EA3i IPv6",base64:"chu\u1ED7i m\xE3 h\xF3a base64",base64url:"chu\u1ED7i m\xE3 h\xF3a base64url",json_string:"chu\u1ED7i JSON",e164:"s\u1ED1 E.164",jwt:"JWT",template_literal:"\u0111\u1EA7u v\xE0o"},n={nan:"NaN",number:"s\u1ED1",array:"m\u1EA3ng"};return o=>{switch(o.code){case"invalid_type":{const s=n[o.expected]??o.expected,i=Ut(o.input),a=n[i]??i;return/^[A-Z]/.test(o.expected)?`\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i instanceof ${o.expected}, nh\u1EADn \u0111\u01B0\u1EE3c ${a}`:`\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i ${s}, nh\u1EADn \u0111\u01B0\u1EE3c ${a}`}case"invalid_value":return o.values.length===1?`\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i ${Ot(o.values[0])}`:`T\xF9y ch\u1ECDn kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i m\u1ED9t trong c\xE1c gi\xE1 tr\u1ECB ${Ye(o.values,"|")}`;case"too_big":{const s=o.inclusive?"<=":"<",i=t(o.origin);return i?`Qu\xE1 l\u1EDBn: mong \u0111\u1EE3i ${o.origin??"gi\xE1 tr\u1ECB"} ${i.verb} ${s}${o.maximum.toString()} ${i.unit??"ph\u1EA7n t\u1EED"}`:`Qu\xE1 l\u1EDBn: mong \u0111\u1EE3i ${o.origin??"gi\xE1 tr\u1ECB"} ${s}${o.maximum.toString()}`}case"too_small":{const s=o.inclusive?">=":">",i=t(o.origin);return i?`Qu\xE1 nh\u1ECF: mong \u0111\u1EE3i ${o.origin} ${i.verb} ${s}${o.minimum.toString()} ${i.unit}`:`Qu\xE1 nh\u1ECF: mong \u0111\u1EE3i ${o.origin} ${s}${o.minimum.toString()}`}case"invalid_format":{const s=o;return s.format==="starts_with"?`Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i b\u1EAFt \u0111\u1EA7u b\u1EB1ng "${s.prefix}"`:s.format==="ends_with"?`Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i k\u1EBFt th\xFAc b\u1EB1ng "${s.suffix}"`:s.format==="includes"?`Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i bao g\u1ED3m "${s.includes}"`:s.format==="regex"?`Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i kh\u1EDBp v\u1EDBi m\u1EABu ${s.pattern}`:`${r[s.format]??o.format} kh\xF4ng h\u1EE3p l\u1EC7`}case"not_multiple_of":return`S\u1ED1 kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i l\xE0 b\u1ED9i s\u1ED1 c\u1EE7a ${o.divisor}`;case"unrecognized_keys":return`Kh\xF3a kh\xF4ng \u0111\u01B0\u1EE3c nh\u1EADn d\u1EA1ng: ${Ye(o.keys,", ")}`;case"invalid_key":return`Kh\xF3a kh\xF4ng h\u1EE3p l\u1EC7 trong ${o.origin}`;case"invalid_union":return"\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7";case"invalid_element":return`Gi\xE1 tr\u1ECB kh\xF4ng h\u1EE3p l\u1EC7 trong ${o.origin}`;default:return"\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7"}}}}});function Hgr(){return{localeError:qfe()}}var qfe,Vgr=S({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/zh-CN.js"(){kt(),qfe=()=>{const e={string:{unit:"\u5B57\u7B26",verb:"\u5305\u542B"},file:{unit:"\u5B57\u8282",verb:"\u5305\u542B"},array:{unit:"\u9879",verb:"\u5305\u542B"},set:{unit:"\u9879",verb:"\u5305\u542B"}};function t(o){return e[o]??null}const r={regex:"\u8F93\u5165",email:"\u7535\u5B50\u90AE\u4EF6",url:"URL",emoji:"\u8868\u60C5\u7B26\u53F7",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO\u65E5\u671F\u65F6\u95F4",date:"ISO\u65E5\u671F",time:"ISO\u65F6\u95F4",duration:"ISO\u65F6\u957F",ipv4:"IPv4\u5730\u5740",ipv6:"IPv6\u5730\u5740",cidrv4:"IPv4\u7F51\u6BB5",cidrv6:"IPv6\u7F51\u6BB5",base64:"base64\u7F16\u7801\u5B57\u7B26\u4E32",base64url:"base64url\u7F16\u7801\u5B57\u7B26\u4E32",json_string:"JSON\u5B57\u7B26\u4E32",e164:"E.164\u53F7\u7801",jwt:"JWT",template_literal:"\u8F93\u5165"},n={nan:"NaN",number:"\u6570\u5B57",array:"\u6570\u7EC4",null:"\u7A7A\u503C(null)"};return o=>{switch(o.code){case"invalid_type":{const s=n[o.expected]??o.expected,i=Ut(o.input),a=n[i]??i;return/^[A-Z]/.test(o.expected)?`\u65E0\u6548\u8F93\u5165\uFF1A\u671F\u671B instanceof ${o.expected}\uFF0C\u5B9E\u9645\u63A5\u6536 ${a}`:`\u65E0\u6548\u8F93\u5165\uFF1A\u671F\u671B ${s}\uFF0C\u5B9E\u9645\u63A5\u6536 ${a}`}case"invalid_value":return o.values.length===1?`\u65E0\u6548\u8F93\u5165\uFF1A\u671F\u671B ${Ot(o.values[0])}`:`\u65E0\u6548\u9009\u9879\uFF1A\u671F\u671B\u4EE5\u4E0B\u4E4B\u4E00 ${Ye(o.values,"|")}`;case"too_big":{const s=o.inclusive?"<=":"<",i=t(o.origin);return i?`\u6570\u503C\u8FC7\u5927\uFF1A\u671F\u671B ${o.origin??"\u503C"} ${s}${o.maximum.toString()} ${i.unit??"\u4E2A\u5143\u7D20"}`:`\u6570\u503C\u8FC7\u5927\uFF1A\u671F\u671B ${o.origin??"\u503C"} ${s}${o.maximum.toString()}`}case"too_small":{const s=o.inclusive?">=":">",i=t(o.origin);return i?`\u6570\u503C\u8FC7\u5C0F\uFF1A\u671F\u671B ${o.origin} ${s}${o.minimum.toString()} ${i.unit}`:`\u6570\u503C\u8FC7\u5C0F\uFF1A\u671F\u671B ${o.origin} ${s}${o.minimum.toString()}`}case"invalid_format":{const s=o;return s.format==="starts_with"?`\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u4EE5 "${s.prefix}" \u5F00\u5934`:s.format==="ends_with"?`\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u4EE5 "${s.suffix}" \u7ED3\u5C3E`:s.format==="includes"?`\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u5305\u542B "${s.includes}"`:s.format==="regex"?`\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u6EE1\u8DB3\u6B63\u5219\u8868\u8FBE\u5F0F ${s.pattern}`:`\u65E0\u6548${r[s.format]??o.format}`}case"not_multiple_of":return`\u65E0\u6548\u6570\u5B57\uFF1A\u5FC5\u987B\u662F ${o.divisor} \u7684\u500D\u6570`;case"unrecognized_keys":return`\u51FA\u73B0\u672A\u77E5\u7684\u952E(key): ${Ye(o.keys,", ")}`;case"invalid_key":return`${o.origin} \u4E2D\u7684\u952E(key)\u65E0\u6548`;case"invalid_union":return"\u65E0\u6548\u8F93\u5165";case"invalid_element":return`${o.origin} \u4E2D\u5305\u542B\u65E0\u6548\u503C(value)`;default:return"\u65E0\u6548\u8F93\u5165"}}}}});function Wgr(){return{localeError:Gfe()}}var Gfe,Kgr=S({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/zh-TW.js"(){kt(),Gfe=()=>{const e={string:{unit:"\u5B57\u5143",verb:"\u64C1\u6709"},file:{unit:"\u4F4D\u5143\u7D44",verb:"\u64C1\u6709"},array:{unit:"\u9805\u76EE",verb:"\u64C1\u6709"},set:{unit:"\u9805\u76EE",verb:"\u64C1\u6709"}};function t(o){return e[o]??null}const r={regex:"\u8F38\u5165",email:"\u90F5\u4EF6\u5730\u5740",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO \u65E5\u671F\u6642\u9593",date:"ISO \u65E5\u671F",time:"ISO \u6642\u9593",duration:"ISO \u671F\u9593",ipv4:"IPv4 \u4F4D\u5740",ipv6:"IPv6 \u4F4D\u5740",cidrv4:"IPv4 \u7BC4\u570D",cidrv6:"IPv6 \u7BC4\u570D",base64:"base64 \u7DE8\u78BC\u5B57\u4E32",base64url:"base64url \u7DE8\u78BC\u5B57\u4E32",json_string:"JSON \u5B57\u4E32",e164:"E.164 \u6578\u503C",jwt:"JWT",template_literal:"\u8F38\u5165"},n={nan:"NaN"};return o=>{switch(o.code){case"invalid_type":{const s=n[o.expected]??o.expected,i=Ut(o.input),a=n[i]??i;return/^[A-Z]/.test(o.expected)?`\u7121\u6548\u7684\u8F38\u5165\u503C\uFF1A\u9810\u671F\u70BA instanceof ${o.expected}\uFF0C\u4F46\u6536\u5230 ${a}`:`\u7121\u6548\u7684\u8F38\u5165\u503C\uFF1A\u9810\u671F\u70BA ${s}\uFF0C\u4F46\u6536\u5230 ${a}`}case"invalid_value":return o.values.length===1?`\u7121\u6548\u7684\u8F38\u5165\u503C\uFF1A\u9810\u671F\u70BA ${Ot(o.values[0])}`:`\u7121\u6548\u7684\u9078\u9805\uFF1A\u9810\u671F\u70BA\u4EE5\u4E0B\u5176\u4E2D\u4E4B\u4E00 ${Ye(o.values,"|")}`;case"too_big":{const s=o.inclusive?"<=":"<",i=t(o.origin);return i?`\u6578\u503C\u904E\u5927\uFF1A\u9810\u671F ${o.origin??"\u503C"} \u61C9\u70BA ${s}${o.maximum.toString()} ${i.unit??"\u500B\u5143\u7D20"}`:`\u6578\u503C\u904E\u5927\uFF1A\u9810\u671F ${o.origin??"\u503C"} \u61C9\u70BA ${s}${o.maximum.toString()}`}case"too_small":{const s=o.inclusive?">=":">",i=t(o.origin);return i?`\u6578\u503C\u904E\u5C0F\uFF1A\u9810\u671F ${o.origin} \u61C9\u70BA ${s}${o.minimum.toString()} ${i.unit}`:`\u6578\u503C\u904E\u5C0F\uFF1A\u9810\u671F ${o.origin} \u61C9\u70BA ${s}${o.minimum.toString()}`}case"invalid_format":{const s=o;return s.format==="starts_with"?`\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u4EE5 "${s.prefix}" \u958B\u982D`:s.format==="ends_with"?`\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u4EE5 "${s.suffix}" \u7D50\u5C3E`:s.format==="includes"?`\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u5305\u542B "${s.includes}"`:s.format==="regex"?`\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u7B26\u5408\u683C\u5F0F ${s.pattern}`:`\u7121\u6548\u7684 ${r[s.format]??o.format}`}case"not_multiple_of":return`\u7121\u6548\u7684\u6578\u5B57\uFF1A\u5FC5\u9808\u70BA ${o.divisor} \u7684\u500D\u6578`;case"unrecognized_keys":return`\u7121\u6CD5\u8B58\u5225\u7684\u9375\u503C${o.keys.length>1?"\u5011":""}\uFF1A${Ye(o.keys,"\u3001")}`;case"invalid_key":return`${o.origin} \u4E2D\u6709\u7121\u6548\u7684\u9375\u503C`;case"invalid_union":return"\u7121\u6548\u7684\u8F38\u5165\u503C";case"invalid_element":return`${o.origin} \u4E2D\u6709\u7121\u6548\u7684\u503C`;default:return"\u7121\u6548\u7684\u8F38\u5165\u503C"}}}}});function Jgr(){return{localeError:Hfe()}}var Hfe,Ygr=S({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/yo.js"(){kt(),Hfe=()=>{const e={string:{unit:"\xE0mi",verb:"n\xED"},file:{unit:"bytes",verb:"n\xED"},array:{unit:"nkan",verb:"n\xED"},set:{unit:"nkan",verb:"n\xED"}};function t(o){return e[o]??null}const r={regex:"\u1EB9\u0300r\u1ECD \xECb\xE1w\u1ECDl\xE9",email:"\xE0d\xEDr\u1EB9\u0301s\xEC \xECm\u1EB9\u0301l\xEC",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"\xE0k\xF3k\xF2 ISO",date:"\u1ECDj\u1ECD\u0301 ISO",time:"\xE0k\xF3k\xF2 ISO",duration:"\xE0k\xF3k\xF2 t\xF3 p\xE9 ISO",ipv4:"\xE0d\xEDr\u1EB9\u0301s\xEC IPv4",ipv6:"\xE0d\xEDr\u1EB9\u0301s\xEC IPv6",cidrv4:"\xE0gb\xE8gb\xE8 IPv4",cidrv6:"\xE0gb\xE8gb\xE8 IPv6",base64:"\u1ECD\u0300r\u1ECD\u0300 t\xED a k\u1ECD\u0301 n\xED base64",base64url:"\u1ECD\u0300r\u1ECD\u0300 base64url",json_string:"\u1ECD\u0300r\u1ECD\u0300 JSON",e164:"n\u1ECD\u0301mb\xE0 E.164",jwt:"JWT",template_literal:"\u1EB9\u0300r\u1ECD \xECb\xE1w\u1ECDl\xE9"},n={nan:"NaN",number:"n\u1ECD\u0301mb\xE0",array:"akop\u1ECD"};return o=>{switch(o.code){case"invalid_type":{const s=n[o.expected]??o.expected,i=Ut(o.input),a=n[i]??i;return/^[A-Z]/.test(o.expected)?`\xCCb\xE1w\u1ECDl\xE9 a\u1E63\xEC\u1E63e: a n\xED l\xE1ti fi instanceof ${o.expected}, \xE0m\u1ECD\u0300 a r\xED ${a}`:`\xCCb\xE1w\u1ECDl\xE9 a\u1E63\xEC\u1E63e: a n\xED l\xE1ti fi ${s}, \xE0m\u1ECD\u0300 a r\xED ${a}`}case"invalid_value":return o.values.length===1?`\xCCb\xE1w\u1ECDl\xE9 a\u1E63\xEC\u1E63e: a n\xED l\xE1ti fi ${Ot(o.values[0])}`:`\xC0\u1E63\xE0y\xE0n a\u1E63\xEC\u1E63e: yan \u1ECD\u0300kan l\xE1ra ${Ye(o.values,"|")}`;case"too_big":{const s=o.inclusive?"<=":"<",i=t(o.origin);return i?`T\xF3 p\u1ECD\u0300 j\xF9: a n\xED l\xE1ti j\u1EB9\u0301 p\xE9 ${o.origin??"iye"} ${i.verb} ${s}${o.maximum} ${i.unit}`:`T\xF3 p\u1ECD\u0300 j\xF9: a n\xED l\xE1ti j\u1EB9\u0301 ${s}${o.maximum}`}case"too_small":{const s=o.inclusive?">=":">",i=t(o.origin);return i?`K\xE9r\xE9 ju: a n\xED l\xE1ti j\u1EB9\u0301 p\xE9 ${o.origin} ${i.verb} ${s}${o.minimum} ${i.unit}`:`K\xE9r\xE9 ju: a n\xED l\xE1ti j\u1EB9\u0301 ${s}${o.minimum}`}case"invalid_format":{const s=o;return s.format==="starts_with"?`\u1ECC\u0300r\u1ECD\u0300 a\u1E63\xEC\u1E63e: gb\u1ECD\u0301d\u1ECD\u0300 b\u1EB9\u0300r\u1EB9\u0300 p\u1EB9\u0300l\xFA "${s.prefix}"`:s.format==="ends_with"?`\u1ECC\u0300r\u1ECD\u0300 a\u1E63\xEC\u1E63e: gb\u1ECD\u0301d\u1ECD\u0300 par\xED p\u1EB9\u0300l\xFA "${s.suffix}"`:s.format==="includes"?`\u1ECC\u0300r\u1ECD\u0300 a\u1E63\xEC\u1E63e: gb\u1ECD\u0301d\u1ECD\u0300 n\xED "${s.includes}"`:s.format==="regex"?`\u1ECC\u0300r\u1ECD\u0300 a\u1E63\xEC\u1E63e: gb\u1ECD\u0301d\u1ECD\u0300 b\xE1 \xE0p\u1EB9\u1EB9r\u1EB9 mu ${s.pattern}`:`A\u1E63\xEC\u1E63e: ${r[s.format]??o.format}`}case"not_multiple_of":return`N\u1ECD\u0301mb\xE0 a\u1E63\xEC\u1E63e: gb\u1ECD\u0301d\u1ECD\u0300 j\u1EB9\u0301 \xE8y\xE0 p\xEDp\xEDn ti ${o.divisor}`;case"unrecognized_keys":return`B\u1ECDt\xECn\xEC \xE0\xECm\u1ECD\u0300: ${Ye(o.keys,", ")}`;case"invalid_key":return`B\u1ECDt\xECn\xEC a\u1E63\xEC\u1E63e n\xEDn\xFA ${o.origin}`;case"invalid_union":return"\xCCb\xE1w\u1ECDl\xE9 a\u1E63\xEC\u1E63e";case"invalid_element":return`Iye a\u1E63\xEC\u1E63e n\xEDn\xFA ${o.origin}`;default:return"\xCCb\xE1w\u1ECDl\xE9 a\u1E63\xEC\u1E63e"}}}}}),f5={};he(f5,{ar:()=>mfr,az:()=>ffr,be:()=>yfr,bg:()=>_fr,ca:()=>bfr,cs:()=>Efr,da:()=>Cfr,de:()=>xfr,en:()=>Xhe,eo:()=>Ifr,es:()=>Mfr,fa:()=>Dfr,fi:()=>Nfr,fr:()=>$fr,frCA:()=>Ufr,he:()=>zfr,hu:()=>qfr,hy:()=>Hfr,id:()=>Wfr,is:()=>Jfr,it:()=>Zfr,ja:()=>Qfr,ka:()=>tgr,kh:()=>ngr,km:()=>gfe,ko:()=>sgr,lt:()=>agr,mk:()=>cgr,ms:()=>dgr,nl:()=>mgr,no:()=>fgr,ota:()=>ygr,pl:()=>bgr,ps:()=>_gr,pt:()=>Egr,ru:()=>Cgr,sl:()=>xgr,sv:()=>Igr,ta:()=>Mgr,th:()=>Dgr,tr:()=>Ngr,ua:()=>$gr,uk:()=>$fe,ur:()=>Ugr,uz:()=>zgr,vi:()=>qgr,yo:()=>Jgr,zhCN:()=>Hgr,zhTW:()=>Wgr});var g5=S({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/index.js"(){hfr(),gfr(),vfr(),wfr(),Tfr(),Sfr(),kfr(),Afr(),efe(),Rfr(),Pfr(),Ofr(),Lfr(),Ffr(),Bfr(),jfr(),Gfr(),Vfr(),Kfr(),Yfr(),Xfr(),egr(),rgr(),ogr(),vfe(),igr(),lgr(),ugr(),pgr(),hgr(),ggr(),vgr(),wgr(),Tgr(),Sgr(),kgr(),Agr(),Rgr(),Pgr(),Ogr(),Lgr(),Fgr(),Ufe(),Bgr(),jgr(),Ggr(),Vgr(),Kgr(),Ygr()}});function y5(){return new w5}var Vfe,v5,_5,w5,vl,SR=S({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/registries.js"(){v5=Symbol("ZodOutput"),_5=Symbol("ZodInput"),w5=class{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...t){const r=t[0];return this._map.set(e,r),r&&typeof r=="object"&&"id"in r&&this._idmap.set(r.id,e),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){const t=this._map.get(e);return t&&typeof t=="object"&&"id"in t&&this._idmap.delete(t.id),this._map.delete(e),this}get(e){const t=e._zod.parent;if(t){const r={...this.get(t)??{}};delete r.id;const n={...r,...this._map.get(e)};return Object.keys(n).length?n:void 0}return this._map.get(e)}has(e){return this._map.has(e)}},(Vfe=globalThis).__zod_globalRegistry??(Vfe.__zod_globalRegistry=y5()),vl=globalThis.__zod_globalRegistry}});function Wfe(e,t){return new e({type:"string",...Qe(t)})}function Kfe(e,t){return new e({type:"string",coerce:!0,...Qe(t)})}function b5(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...Qe(t)})}function CR(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...Qe(t)})}function T5(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...Qe(t)})}function E5(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...Qe(t)})}function S5(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...Qe(t)})}function C5(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...Qe(t)})}function kR(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...Qe(t)})}function k5(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...Qe(t)})}function x5(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...Qe(t)})}function A5(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...Qe(t)})}function I5(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...Qe(t)})}function R5(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...Qe(t)})}function M5(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...Qe(t)})}function P5(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...Qe(t)})}function D5(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...Qe(t)})}function O5(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...Qe(t)})}function Jfe(e,t){return new e({type:"string",format:"mac",check:"string_format",abort:!1,...Qe(t)})}function N5(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...Qe(t)})}function L5(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...Qe(t)})}function $5(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...Qe(t)})}function F5(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...Qe(t)})}function U5(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...Qe(t)})}function B5(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...Qe(t)})}function Yfe(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...Qe(t)})}function Zfe(e,t){return new e({type:"string",format:"date",check:"string_format",...Qe(t)})}function Xfe(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...Qe(t)})}function Qfe(e,t){return new e({type:"string",format:"duration",check:"string_format",...Qe(t)})}function ege(e,t){return new e({type:"number",checks:[],...Qe(t)})}function tge(e,t){return new e({type:"number",coerce:!0,checks:[],...Qe(t)})}function rge(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...Qe(t)})}function nge(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"float32",...Qe(t)})}function oge(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"float64",...Qe(t)})}function sge(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"int32",...Qe(t)})}function ige(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"uint32",...Qe(t)})}function age(e,t){return new e({type:"boolean",...Qe(t)})}function lge(e,t){return new e({type:"boolean",coerce:!0,...Qe(t)})}function cge(e,t){return new e({type:"bigint",...Qe(t)})}function uge(e,t){return new e({type:"bigint",coerce:!0,...Qe(t)})}function dge(e,t){return new e({type:"bigint",check:"bigint_format",abort:!1,format:"int64",...Qe(t)})}function pge(e,t){return new e({type:"bigint",check:"bigint_format",abort:!1,format:"uint64",...Qe(t)})}function mge(e,t){return new e({type:"symbol",...Qe(t)})}function hge(e,t){return new e({type:"undefined",...Qe(t)})}function fge(e,t){return new e({type:"null",...Qe(t)})}function gge(e){return new e({type:"any"})}function yge(e){return new e({type:"unknown"})}function vge(e,t){return new e({type:"never",...Qe(t)})}function _ge(e,t){return new e({type:"void",...Qe(t)})}function wge(e,t){return new e({type:"date",...Qe(t)})}function bge(e,t){return new e({type:"date",coerce:!0,...Qe(t)})}function Tge(e,t){return new e({type:"nan",...Qe(t)})}function hm(e,t){return new dR({check:"less_than",...Qe(t),value:e,inclusive:!1})}function sc(e,t){return new dR({check:"less_than",...Qe(t),value:e,inclusive:!0})}function fm(e,t){return new pR({check:"greater_than",...Qe(t),value:e,inclusive:!1})}function Ua(e,t){return new pR({check:"greater_than",...Qe(t),value:e,inclusive:!0})}function z5(e){return fm(0,e)}function j5(e){return hm(0,e)}function q5(e){return sc(0,e)}function G5(e){return Ua(0,e)}function wv(e,t){return new $U({check:"multiple_of",...Qe(t),value:e})}function bv(e,t){return new BU({check:"max_size",...Qe(t),maximum:e})}function gm(e,t){return new zU({check:"min_size",...Qe(t),minimum:e})}function gT(e,t){return new jU({check:"size_equals",...Qe(t),size:e})}function yT(e,t){return new qU({check:"max_length",...Qe(t),maximum:e})}function lf(e,t){return new GU({check:"min_length",...Qe(t),minimum:e})}function vT(e,t){return new HU({check:"length_equals",...Qe(t),length:e})}function xR(e,t){return new VU({check:"string_format",format:"regex",...Qe(t),pattern:e})}function AR(e){return new WU({check:"string_format",format:"lowercase",...Qe(e)})}function IR(e){return new KU({check:"string_format",format:"uppercase",...Qe(e)})}function RR(e,t){return new JU({check:"string_format",format:"includes",...Qe(t),includes:e})}function MR(e,t){return new YU({check:"string_format",format:"starts_with",...Qe(t),prefix:e})}function PR(e,t){return new ZU({check:"string_format",format:"ends_with",...Qe(t),suffix:e})}function H5(e,t,r){return new XU({check:"property",property:e,schema:t,...Qe(r)})}function DR(e,t){return new QU({check:"mime_type",mime:e,...Qe(t)})}function Fd(e){return new e6({check:"overwrite",tx:e})}function OR(e){return Fd(t=>t.normalize(e))}function NR(){return Fd(e=>e.trim())}function LR(){return Fd(e=>e.toLowerCase())}function $R(){return Fd(e=>e.toUpperCase())}function FR(){return Fd(e=>xme(e))}function Ege(e,t,r){return new e({type:"array",element:t,...Qe(r)})}function Zgr(e,t,r){return new e({type:"union",options:t,...Qe(r)})}function Xgr(e,t,r){return new e({type:"union",options:t,inclusive:!1,...Qe(r)})}function Qgr(e,t,r,n){return new e({type:"union",options:r,discriminator:t,...Qe(n)})}function eyr(e,t,r){return new e({type:"intersection",left:t,right:r})}function tyr(e,t,r,n){const o=r instanceof Kt,s=o?n:r,i=o?r:null;return new e({type:"tuple",items:t,rest:i,...Qe(s)})}function ryr(e,t,r,n){return new e({type:"record",keyType:t,valueType:r,...Qe(n)})}function nyr(e,t,r,n){return new e({type:"map",keyType:t,valueType:r,...Qe(n)})}function oyr(e,t,r){return new e({type:"set",valueType:t,...Qe(r)})}function syr(e,t,r){const n=Array.isArray(t)?Object.fromEntries(t.map(o=>[o,o])):t;return new e({type:"enum",entries:n,...Qe(r)})}function iyr(e,t,r){return new e({type:"enum",entries:t,...Qe(r)})}function ayr(e,t,r){return new e({type:"literal",values:Array.isArray(t)?t:[t],...Qe(r)})}function Sge(e,t){return new e({type:"file",...Qe(t)})}function lyr(e,t){return new e({type:"transform",transform:t})}function cyr(e,t){return new e({type:"optional",innerType:t})}function uyr(e,t){return new e({type:"nullable",innerType:t})}function dyr(e,t,r){return new e({type:"default",innerType:t,get defaultValue(){return typeof r=="function"?r():Ame(r)}})}function pyr(e,t,r){return new e({type:"nonoptional",innerType:t,...Qe(r)})}function myr(e,t){return new e({type:"success",innerType:t})}function hyr(e,t,r){return new e({type:"catch",innerType:t,catchValue:typeof r=="function"?r:()=>r})}function fyr(e,t,r){return new e({type:"pipe",in:t,out:r})}function gyr(e,t){return new e({type:"readonly",innerType:t})}function yyr(e,t,r){return new e({type:"template_literal",parts:t,...Qe(r)})}function vyr(e,t){return new e({type:"lazy",getter:t})}function _yr(e,t){return new e({type:"promise",innerType:t})}function Cge(e,t,r){const n=Qe(r);return n.abort??(n.abort=!0),new e({type:"custom",check:"custom",fn:t,...n})}function kge(e,t,r){return new e({type:"custom",check:"custom",fn:t,...Qe(r)})}function xge(e){const t=Age(r=>(r.addIssue=n=>{if(typeof n=="string")r.issues.push(JI(n,r.value,t._zod.def));else{const o=n;o.fatal&&(o.continue=!1),o.code??(o.code="custom"),o.input??(o.input=r.value),o.inst??(o.inst=t),o.continue??(o.continue=!t._zod.def.abort),r.issues.push(JI(o))}},e(r.value,r)));return t}function Age(e,t){const r=new Tn({check:"custom",...Qe(t)});return r._zod.check=e,r}function Ige(e){const t=new Tn({check:"describe"});return t._zod.onattach=[r=>{const n=vl.get(r)??{};vl.add(r,{...n,description:e})}],t._zod.check=()=>{},t}function Rge(e){const t=new Tn({check:"meta"});return t._zod.onattach=[r=>{const n=vl.get(r)??{};vl.add(r,{...n,...e})}],t._zod.check=()=>{},t}function Mge(e,t){const r=Qe(t);let n=r.truthy??["true","1","yes","on","y","enabled"],o=r.falsy??["false","0","no","off","n","disabled"];r.case!=="sensitive"&&(n=n.map(h=>typeof h=="string"?h.toLowerCase():h),o=o.map(h=>typeof h=="string"?h.toLowerCase():h));const s=new Set(n),i=new Set(o),a=e.Codec??ER,l=e.Boolean??_R,c=e.String??yv,u=new c({type:"string",error:r.error}),d=new l({type:"boolean",error:r.error}),m=new a({type:"pipe",in:u,out:d,transform:((h,g)=>{let y=h;return r.case!=="sensitive"&&(y=y.toLowerCase()),s.has(y)?!0:i.has(y)?!1:(g.issues.push({code:"invalid_value",expected:"stringbool",values:[...s,...i],input:g.value,inst:m,continue:!1}),{})}),reverseTransform:((h,g)=>h===!0?n[0]||"true":o[0]||"false"),error:r.error});return m}function _T(e,t,r,n={}){const o=Qe(n),s={...Qe(n),check:"string_format",type:"string",format:t,fn:typeof r=="function"?r:a=>r.test(a),...o};return r instanceof RegExp&&(s.pattern=r),new e(s)}var V5,wyr=S({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/api.js"(){t6(),SR(),jhe(),kt(),V5={Any:null,Minute:-1,Second:0,Millisecond:3,Microsecond:6}}});function Tv(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??vl,target:t,unrepresentable:e?.unrepresentable??"throw",override:e?.override??(()=>{}),io:e?.io??"output",counter:0,seen:new Map,cycles:e?.cycles??"ref",reused:e?.reused??"inline",external:e?.external??void 0}}function en(e,t,r={path:[],schemaPath:[]}){var n;const o=e._zod.def,s=t.seen.get(e);if(s)return s.count++,r.schemaPath.includes(e)&&(s.cycle=r.path),s.schema;const i={schema:{},count:1,cycle:void 0,path:r.path};t.seen.set(e,i);const a=e._zod.toJSONSchema?.();if(a)i.schema=a;else{const u={...r,schemaPath:[...r.schemaPath,e],path:r.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,i.schema,u);else{const m=i.schema,h=t.processors[o.type];if(!h)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${o.type}`);h(e,t,m,u)}const d=e._zod.parent;d&&(i.ref||(i.ref=d),en(d,t,u),t.seen.get(d).isParent=!0)}const l=t.metadataRegistry.get(e);return l&&Object.assign(i.schema,l),t.io==="input"&&da(e)&&(delete i.schema.examples,delete i.schema.default),t.io==="input"&&i.schema._prefault&&((n=i.schema).default??(n.default=i.schema._prefault)),delete i.schema._prefault,t.seen.get(e).schema}function Ev(e,t){const r=e.seen.get(t);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");const n=new Map;for(const i of e.seen.entries()){const a=e.metadataRegistry.get(i[0])?.id;if(a){const l=n.get(a);if(l&&l!==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])}}const o=i=>{const a=e.target==="draft-2020-12"?"$defs":"definitions";if(e.external){const d=e.external.registry.get(i[0])?.id,m=e.external.uri??(g=>g);if(d)return{ref:m(d)};const h=i[1].defId??i[1].schema.id??`schema${e.counter++}`;return i[1].defId=h,{defId:h,ref:`${m("__shared")}#/${a}/${h}`}}if(i[1]===r)return{ref:"#"};const c=`#/${a}/`,u=i[1].schema.id??`__schema${e.counter++}`;return{defId:u,ref:c+u}},s=i=>{if(i[1].schema.$ref)return;const a=i[1],{ref:l,defId:c}=o(i);a.def={...a.schema},c&&(a.defId=c);const u=a.schema;for(const d in u)delete u[d];u.$ref=l};if(e.cycles==="throw")for(const i of e.seen.entries()){const a=i[1];if(a.cycle)throw new Error(`Cycle detected: #/${a.cycle?.join("/")}/<root>
|
|
51
51
|
|
|
52
|
-
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const i of e.seen.entries()){const a=i[1];if(t===i[0]){s(i);continue}if(e.external){const c=e.external.registry.get(i[0])?.id;if(t!==i[0]&&c){s(i);continue}}if(e.metadataRegistry.get(i[0])?.id){s(i);continue}if(a.cycle){s(i);continue}if(a.count>1&&e.reused==="ref"){s(i);continue}}}function Sv(e,t){const r=e.seen.get(t);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");const n=i=>{const a=e.seen.get(i);if(a.ref===null)return;const l=a.def??a.schema,c={...l},u=a.ref;if(a.ref=null,u){n(u);const m=e.seen.get(u),h=m.schema;if(h.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0")?(l.allOf=l.allOf??[],l.allOf.push(h)):Object.assign(l,h),Object.assign(l,c),i._zod.parent===u)for(const y in l)y==="$ref"||y==="allOf"||y in c||delete l[y];if(h.$ref&&m.def)for(const y in l)y==="$ref"||y==="allOf"||y in m.def&&JSON.stringify(l[y])===JSON.stringify(m.def[y])&&delete l[y]}const d=i._zod.parent;if(d&&d!==u){n(d);const m=e.seen.get(d);if(m?.schema.$ref&&(l.$ref=m.schema.$ref,m.def))for(const h in l)h==="$ref"||h==="allOf"||h in m.def&&JSON.stringify(l[h])===JSON.stringify(m.def[h])&&delete l[h]}e.override({zodSchema:i,jsonSchema:l,path:a.path??[]})};for(const i of[...e.seen.entries()].reverse())n(i[0]);const o={};if(e.target==="draft-2020-12"?o.$schema="https://json-schema.org/draft/2020-12/schema":e.target==="draft-07"?o.$schema="http://json-schema.org/draft-07/schema#":e.target==="draft-04"?o.$schema="http://json-schema.org/draft-04/schema#":e.target,e.external?.uri){const i=e.external.registry.get(t)?.id;if(!i)throw new Error("Schema is missing an `id` property");o.$id=e.external.uri(i)}Object.assign(o,r.def??r.schema);const s=e.external?.defs??{};for(const i of e.seen.entries()){const a=i[1];a.def&&a.defId&&(s[a.defId]=a.def)}e.external||Object.keys(s).length>0&&(e.target==="draft-2020-12"?o.$defs=s:o.definitions=s);try{const i=JSON.parse(JSON.stringify(o));return Object.defineProperty(i,"~standard",{value:{...t["~standard"],jsonSchema:{input:Cv(t,"input",e.processors),output:Cv(t,"output",e.processors)}},enumerable:!1,writable:!1}),i}catch{throw new Error("Error converting schema to JSON.")}}function da(e,t){const r=t??{seen:new Set};if(r.seen.has(e))return!1;r.seen.add(e);const n=e._zod.def;if(n.type==="transform")return!0;if(n.type==="array")return da(n.element,r);if(n.type==="set")return da(n.valueType,r);if(n.type==="lazy")return da(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")return da(n.innerType,r);if(n.type==="intersection")return da(n.left,r)||da(n.right,r);if(n.type==="record"||n.type==="map")return da(n.keyType,r)||da(n.valueType,r);if(n.type==="pipe")return da(n.in,r)||da(n.out,r);if(n.type==="object"){for(const o in n.shape)if(da(n.shape[o],r))return!0;return!1}if(n.type==="union"){for(const o of n.options)if(da(o,r))return!0;return!1}if(n.type==="tuple"){for(const o of n.items)if(da(o,r))return!0;return!!(n.rest&&da(n.rest,r))}return!1}var W5,Cv,UR=S({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/to-json-schema.js"(){SR(),W5=(e,t={})=>r=>{const n=Tv({...r,processors:t});return en(e,n),Ev(n,e),Sv(n,e)},Cv=(e,t,r={})=>n=>{const{libraryOptions:o,target:s}=n??{},i=Tv({...o??{},target:s,io:t,processors:r});return en(e,i),Ev(i,e),Sv(i,e)}}});function wT(e,t){if("_idmap"in e){const n=e,o=Tv({...t,processors:jR}),s={};for(const l of n._idmap.entries()){const[c,u]=l;en(u,o)}const i={},a={registry:n,uri:t?.uri,defs:s};o.external=a;for(const l of n._idmap.entries()){const[c,u]=l;Ev(o,u),i[c]=Sv(o,u)}if(Object.keys(s).length>0){const l=o.target==="draft-2020-12"?"$defs":"definitions";i.__shared={[l]:s}}return{schemas:i}}const r=Tv({...t,processors:jR});return en(e,r),Ev(r,e),Sv(r,e)}var Pge,K5,J5,Y5,Z5,X5,Q5,eB,tB,rB,nB,oB,sB,iB,aB,lB,cB,uB,dB,pB,mB,hB,fB,gB,yB,vB,BR,_B,wB,bB,TB,EB,SB,CB,kB,xB,AB,IB,zR,RB,jR,bT=S({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/json-schema-processors.js"(){UR(),kt(),Pge={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},K5=(e,t,r,n)=>{const o=r;o.type="string";const{minimum:s,maximum:i,format:a,patterns:l,contentEncoding:c}=e._zod.bag;if(typeof s=="number"&&(o.minLength=s),typeof i=="number"&&(o.maxLength=i),a&&(o.format=Pge[a]??a,o.format===""&&delete o.format,a==="time"&&delete o.format),c&&(o.contentEncoding=c),l&&l.size>0){const u=[...l];u.length===1?o.pattern=u[0].source:u.length>1&&(o.allOf=[...u.map(d=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:d.source}))])}},J5=(e,t,r,n)=>{const o=r,{minimum:s,maximum:i,format:a,multipleOf:l,exclusiveMaximum:c,exclusiveMinimum:u}=e._zod.bag;typeof a=="string"&&a.includes("int")?o.type="integer":o.type="number",typeof u=="number"&&(t.target==="draft-04"||t.target==="openapi-3.0"?(o.minimum=u,o.exclusiveMinimum=!0):o.exclusiveMinimum=u),typeof s=="number"&&(o.minimum=s,typeof u=="number"&&t.target!=="draft-04"&&(u>=s?delete o.minimum:delete o.exclusiveMinimum)),typeof c=="number"&&(t.target==="draft-04"||t.target==="openapi-3.0"?(o.maximum=c,o.exclusiveMaximum=!0):o.exclusiveMaximum=c),typeof i=="number"&&(o.maximum=i,typeof c=="number"&&t.target!=="draft-04"&&(c<=i?delete o.maximum:delete o.exclusiveMaximum)),typeof l=="number"&&(o.multipleOf=l)},Y5=(e,t,r,n)=>{r.type="boolean"},Z5=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema")},X5=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw new Error("Symbols cannot be represented in JSON Schema")},Q5=(e,t,r,n)=>{t.target==="openapi-3.0"?(r.type="string",r.nullable=!0,r.enum=[null]):r.type="null"},eB=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw new Error("Undefined cannot be represented in JSON Schema")},tB=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw new Error("Void cannot be represented in JSON Schema")},rB=(e,t,r,n)=>{r.not={}},nB=(e,t,r,n)=>{},oB=(e,t,r,n)=>{},sB=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema")},iB=(e,t,r,n)=>{const o=e._zod.def,s=Z3(o.entries);s.every(i=>typeof i=="number")&&(r.type="number"),s.every(i=>typeof i=="string")&&(r.type="string"),r.enum=s},aB=(e,t,r,n)=>{const o=e._zod.def,s=[];for(const i of o.values)if(i===void 0){if(t.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof i=="bigint"){if(t.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");s.push(Number(i))}else s.push(i);if(s.length!==0)if(s.length===1){const i=s[0];r.type=i===null?"null":typeof i,t.target==="draft-04"||t.target==="openapi-3.0"?r.enum=[i]:r.const=i}else s.every(i=>typeof i=="number")&&(r.type="number"),s.every(i=>typeof i=="string")&&(r.type="string"),s.every(i=>typeof i=="boolean")&&(r.type="boolean"),s.every(i=>i===null)&&(r.type="null"),r.enum=s},lB=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema")},cB=(e,t,r,n)=>{const o=r,s=e._zod.pattern;if(!s)throw new Error("Pattern not found in template literal");o.type="string",o.pattern=s.source},uB=(e,t,r,n)=>{const o=r,s={type:"string",format:"binary",contentEncoding:"binary"},{minimum:i,maximum:a,mime:l}=e._zod.bag;i!==void 0&&(s.minLength=i),a!==void 0&&(s.maxLength=a),l?l.length===1?(s.contentMediaType=l[0],Object.assign(o,s)):(Object.assign(o,s),o.anyOf=l.map(c=>({contentMediaType:c}))):Object.assign(o,s)},dB=(e,t,r,n)=>{r.type="boolean"},pB=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")},mB=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw new Error("Function types cannot be represented in JSON Schema")},hB=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")},fB=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw new Error("Map cannot be represented in JSON Schema")},gB=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw new Error("Set cannot be represented in JSON Schema")},yB=(e,t,r,n)=>{const o=r,s=e._zod.def,{minimum:i,maximum:a}=e._zod.bag;typeof i=="number"&&(o.minItems=i),typeof a=="number"&&(o.maxItems=a),o.type="array",o.items=en(s.element,t,{...n,path:[...n.path,"items"]})},vB=(e,t,r,n)=>{const o=r,s=e._zod.def;o.type="object",o.properties={};const i=s.shape;for(const c in i)o.properties[c]=en(i[c],t,{...n,path:[...n.path,"properties",c]});const a=new Set(Object.keys(i)),l=new Set([...a].filter(c=>{const u=s.shape[c]._zod;return t.io==="input"?u.optin===void 0:u.optout===void 0}));l.size>0&&(o.required=Array.from(l)),s.catchall?._zod.def.type==="never"?o.additionalProperties=!1:s.catchall?s.catchall&&(o.additionalProperties=en(s.catchall,t,{...n,path:[...n.path,"additionalProperties"]})):t.io==="output"&&(o.additionalProperties=!1)},BR=(e,t,r,n)=>{const o=e._zod.def,s=o.inclusive===!1,i=o.options.map((a,l)=>en(a,t,{...n,path:[...n.path,s?"oneOf":"anyOf",l]}));s?r.oneOf=i:r.anyOf=i},_B=(e,t,r,n)=>{const o=e._zod.def,s=en(o.left,t,{...n,path:[...n.path,"allOf",0]}),i=en(o.right,t,{...n,path:[...n.path,"allOf",1]}),a=c=>"allOf"in c&&Object.keys(c).length===1,l=[...a(s)?s.allOf:[s],...a(i)?i.allOf:[i]];r.allOf=l},wB=(e,t,r,n)=>{const o=r,s=e._zod.def;o.type="array";const i=t.target==="draft-2020-12"?"prefixItems":"items",a=t.target==="draft-2020-12"||t.target==="openapi-3.0"?"items":"additionalItems",l=s.items.map((m,h)=>en(m,t,{...n,path:[...n.path,i,h]})),c=s.rest?en(s.rest,t,{...n,path:[...n.path,a,...t.target==="openapi-3.0"?[s.items.length]:[]]}):null;t.target==="draft-2020-12"?(o.prefixItems=l,c&&(o.items=c)):t.target==="openapi-3.0"?(o.items={anyOf:l},c&&o.items.anyOf.push(c),o.minItems=l.length,c||(o.maxItems=l.length)):(o.items=l,c&&(o.additionalItems=c));const{minimum:u,maximum:d}=e._zod.bag;typeof u=="number"&&(o.minItems=u),typeof d=="number"&&(o.maxItems=d)},bB=(e,t,r,n)=>{const o=r,s=e._zod.def;o.type="object";const i=s.keyType,l=i._zod.bag?.patterns;if(s.mode==="loose"&&l&&l.size>0){const u=en(s.valueType,t,{...n,path:[...n.path,"patternProperties","*"]});o.patternProperties={};for(const d of l)o.patternProperties[d.source]=u}else(t.target==="draft-07"||t.target==="draft-2020-12")&&(o.propertyNames=en(s.keyType,t,{...n,path:[...n.path,"propertyNames"]})),o.additionalProperties=en(s.valueType,t,{...n,path:[...n.path,"additionalProperties"]});const c=i._zod.values;if(c){const u=[...c].filter(d=>typeof d=="string"||typeof d=="number");u.length>0&&(o.required=u)}},TB=(e,t,r,n)=>{const o=e._zod.def,s=en(o.innerType,t,n),i=t.seen.get(e);t.target==="openapi-3.0"?(i.ref=o.innerType,r.nullable=!0):r.anyOf=[s,{type:"null"}]},EB=(e,t,r,n)=>{const o=e._zod.def;en(o.innerType,t,n);const s=t.seen.get(e);s.ref=o.innerType},SB=(e,t,r,n)=>{const o=e._zod.def;en(o.innerType,t,n);const s=t.seen.get(e);s.ref=o.innerType,r.default=JSON.parse(JSON.stringify(o.defaultValue))},CB=(e,t,r,n)=>{const o=e._zod.def;en(o.innerType,t,n);const s=t.seen.get(e);s.ref=o.innerType,t.io==="input"&&(r._prefault=JSON.parse(JSON.stringify(o.defaultValue)))},kB=(e,t,r,n)=>{const o=e._zod.def;en(o.innerType,t,n);const s=t.seen.get(e);s.ref=o.innerType;let i;try{i=o.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}r.default=i},xB=(e,t,r,n)=>{const o=e._zod.def,s=t.io==="input"?o.in._zod.def.type==="transform"?o.out:o.in:o.out;en(s,t,n);const i=t.seen.get(e);i.ref=s},AB=(e,t,r,n)=>{const o=e._zod.def;en(o.innerType,t,n);const s=t.seen.get(e);s.ref=o.innerType,r.readOnly=!0},IB=(e,t,r,n)=>{const o=e._zod.def;en(o.innerType,t,n);const s=t.seen.get(e);s.ref=o.innerType},zR=(e,t,r,n)=>{const o=e._zod.def;en(o.innerType,t,n);const s=t.seen.get(e);s.ref=o.innerType},RB=(e,t,r,n)=>{const o=e._zod.innerType;en(o,t,n);const s=t.seen.get(e);s.ref=o},jR={string:K5,number:J5,boolean:Y5,bigint:Z5,symbol:X5,null:Q5,undefined:eB,void:tB,never:rB,any:nB,unknown:oB,date:sB,enum:iB,literal:aB,nan:lB,template_literal:cB,file:uB,success:dB,custom:pB,function:mB,transform:hB,map:fB,set:gB,array:yB,object:vB,union:BR,intersection:_B,tuple:wB,record:bB,nullable:TB,nonoptional:EB,default:SB,prefault:CB,catch:kB,pipe:xB,readonly:AB,promise:IB,optional:zR,lazy:RB}}}),Dge,byr=S({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/json-schema-generator.js"(){bT(),UR(),Dge=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(e){this.ctx.counter=e}get seen(){return this.ctx.seen}constructor(e){let t=e?.target??"draft-2020-12";t==="draft-4"&&(t="draft-04"),t==="draft-7"&&(t="draft-07"),this.ctx=Tv({processors:jR,target:t,...e?.metadata&&{metadata:e.metadata},...e?.unrepresentable&&{unrepresentable:e.unrepresentable},...e?.override&&{override:e.override},...e?.io&&{io:e.io}})}process(e,t={path:[],schemaPath:[]}){return en(e,this.ctx,t)}emit(e,t){t&&(t.cycles&&(this.ctx.cycles=t.cycles),t.reused&&(this.ctx.reused=t.reused),t.external&&(this.ctx.external=t.external)),Ev(this.ctx,e);const r=Sv(this.ctx,e),{"~standard":n,...o}=r;return o}}}}),Tyr={},Eyr=S({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/json-schema.js"(){}}),Oge={};he(Oge,{$ZodAny:()=>L6,$ZodArray:()=>z6,$ZodAsyncError:()=>pm,$ZodBase64:()=>k6,$ZodBase64URL:()=>x6,$ZodBigInt:()=>wR,$ZodBigIntFormat:()=>P6,$ZodBoolean:()=>_R,$ZodCIDRv4:()=>S6,$ZodCIDRv6:()=>C6,$ZodCUID:()=>p6,$ZodCUID2:()=>m6,$ZodCatch:()=>i5,$ZodCheck:()=>Tn,$ZodCheckBigIntFormat:()=>UU,$ZodCheckEndsWith:()=>ZU,$ZodCheckGreaterThan:()=>pR,$ZodCheckIncludes:()=>JU,$ZodCheckLengthEquals:()=>HU,$ZodCheckLessThan:()=>dR,$ZodCheckLowerCase:()=>WU,$ZodCheckMaxLength:()=>qU,$ZodCheckMaxSize:()=>BU,$ZodCheckMimeType:()=>QU,$ZodCheckMinLength:()=>GU,$ZodCheckMinSize:()=>zU,$ZodCheckMultipleOf:()=>$U,$ZodCheckNumberFormat:()=>FU,$ZodCheckOverwrite:()=>e6,$ZodCheckProperty:()=>XU,$ZodCheckRegex:()=>VU,$ZodCheckSizeEquals:()=>jU,$ZodCheckStartsWith:()=>YU,$ZodCheckStringFormat:()=>gv,$ZodCheckUpperCase:()=>KU,$ZodCodec:()=>ER,$ZodCustom:()=>h5,$ZodCustomStringFormat:()=>R6,$ZodDate:()=>B6,$ZodDefault:()=>r5,$ZodDiscriminatedUnion:()=>H6,$ZodE164:()=>A6,$ZodEmail:()=>l6,$ZodEmoji:()=>u6,$ZodEncodeError:()=>aT,$ZodEnum:()=>Y6,$ZodError:()=>ZI,$ZodExactOptional:()=>e5,$ZodFile:()=>X6,$ZodFunction:()=>d5,$ZodGUID:()=>i6,$ZodIPv4:()=>b6,$ZodIPv6:()=>T6,$ZodISODate:()=>v6,$ZodISODateTime:()=>y6,$ZodISODuration:()=>w6,$ZodISOTime:()=>_6,$ZodIntersection:()=>V6,$ZodJWT:()=>I6,$ZodKSUID:()=>g6,$ZodLazy:()=>m5,$ZodLiteral:()=>Z6,$ZodMAC:()=>E6,$ZodMap:()=>K6,$ZodNaN:()=>a5,$ZodNanoID:()=>d6,$ZodNever:()=>F6,$ZodNonOptional:()=>o5,$ZodNull:()=>N6,$ZodNullable:()=>t5,$ZodNumber:()=>vR,$ZodNumberFormat:()=>M6,$ZodObject:()=>j6,$ZodObjectJIT:()=>q6,$ZodOptional:()=>TR,$ZodPipe:()=>l5,$ZodPrefault:()=>n5,$ZodPromise:()=>p5,$ZodReadonly:()=>c5,$ZodRealError:()=>Fa,$ZodRecord:()=>W6,$ZodRegistry:()=>w5,$ZodSet:()=>J6,$ZodString:()=>yv,$ZodStringFormat:()=>Qr,$ZodSuccess:()=>s5,$ZodSymbol:()=>D6,$ZodTemplateLiteral:()=>u5,$ZodTransform:()=>Q6,$ZodTuple:()=>bR,$ZodType:()=>Kt,$ZodULID:()=>h6,$ZodURL:()=>c6,$ZodUUID:()=>a6,$ZodUndefined:()=>O6,$ZodUnion:()=>fT,$ZodUnknown:()=>$6,$ZodVoid:()=>U6,$ZodXID:()=>f6,$ZodXor:()=>G6,$brand:()=>Y3,$constructor:()=>be,$input:()=>_5,$output:()=>v5,Doc:()=>r6,JSONSchema:()=>Tyr,JSONSchemaGenerator:()=>Dge,NEVER:()=>GI,TimePrecision:()=>V5,_any:()=>gge,_array:()=>Ege,_base64:()=>$5,_base64url:()=>F5,_bigint:()=>cge,_boolean:()=>age,_catch:()=>hyr,_check:()=>Age,_cidrv4:()=>N5,_cidrv6:()=>L5,_coercedBigint:()=>uge,_coercedBoolean:()=>lge,_coercedDate:()=>bge,_coercedNumber:()=>tge,_coercedString:()=>Kfe,_cuid:()=>A5,_cuid2:()=>I5,_custom:()=>Cge,_date:()=>wge,_decode:()=>rR,_decodeAsync:()=>oR,_default:()=>dyr,_discriminatedUnion:()=>Qgr,_e164:()=>U5,_email:()=>b5,_emoji:()=>k5,_encode:()=>tR,_encodeAsync:()=>nR,_endsWith:()=>PR,_enum:()=>syr,_file:()=>Sge,_float32:()=>nge,_float64:()=>oge,_gt:()=>fm,_gte:()=>Ua,_guid:()=>CR,_includes:()=>RR,_int:()=>rge,_int32:()=>sge,_int64:()=>dge,_intersection:()=>eyr,_ipv4:()=>D5,_ipv6:()=>O5,_isoDate:()=>Zfe,_isoDateTime:()=>Yfe,_isoDuration:()=>Qfe,_isoTime:()=>Xfe,_jwt:()=>B5,_ksuid:()=>P5,_lazy:()=>vyr,_length:()=>vT,_literal:()=>ayr,_lowercase:()=>AR,_lt:()=>hm,_lte:()=>sc,_mac:()=>Jfe,_map:()=>nyr,_max:()=>sc,_maxLength:()=>yT,_maxSize:()=>bv,_mime:()=>DR,_min:()=>Ua,_minLength:()=>lf,_minSize:()=>gm,_multipleOf:()=>wv,_nan:()=>Tge,_nanoid:()=>x5,_nativeEnum:()=>iyr,_negative:()=>j5,_never:()=>vge,_nonnegative:()=>G5,_nonoptional:()=>pyr,_nonpositive:()=>q5,_normalize:()=>OR,_null:()=>fge,_nullable:()=>uyr,_number:()=>ege,_optional:()=>cyr,_overwrite:()=>Fd,_parse:()=>pv,_parseAsync:()=>mv,_pipe:()=>fyr,_positive:()=>z5,_promise:()=>_yr,_property:()=>H5,_readonly:()=>gyr,_record:()=>ryr,_refine:()=>kge,_regex:()=>xR,_safeDecode:()=>iR,_safeDecodeAsync:()=>lR,_safeEncode:()=>sR,_safeEncodeAsync:()=>aR,_safeParse:()=>hv,_safeParseAsync:()=>fv,_set:()=>oyr,_size:()=>gT,_slugify:()=>FR,_startsWith:()=>MR,_string:()=>Wfe,_stringFormat:()=>_T,_stringbool:()=>Mge,_success:()=>myr,_superRefine:()=>xge,_symbol:()=>mge,_templateLiteral:()=>yyr,_toLowerCase:()=>LR,_toUpperCase:()=>$R,_transform:()=>lyr,_trim:()=>NR,_tuple:()=>tyr,_uint32:()=>ige,_uint64:()=>pge,_ulid:()=>R5,_undefined:()=>hge,_union:()=>Zgr,_unknown:()=>yge,_uppercase:()=>IR,_url:()=>kR,_uuid:()=>T5,_uuidv4:()=>E5,_uuidv6:()=>S5,_uuidv7:()=>C5,_void:()=>_ge,_xid:()=>M5,_xor:()=>Xgr,clone:()=>nc,config:()=>qi,createStandardJSONSchemaMethod:()=>Cv,createToJSONSchemaMethod:()=>W5,decode:()=>Ume,decodeAsync:()=>zme,describe:()=>Ige,encode:()=>Fme,encodeAsync:()=>Bme,extractDefs:()=>Ev,finalize:()=>Sv,flattenError:()=>oU,formatError:()=>sU,globalConfig:()=>lT,globalRegistry:()=>vl,initializeContext:()=>Tv,isValidBase64:()=>o6,isValidBase64URL:()=>xhe,isValidJWT:()=>Ahe,locales:()=>f5,meta:()=>Rge,parse:()=>XI,parseAsync:()=>QI,prettifyError:()=>Lme,process:()=>en,regexes:()=>sf,registry:()=>y5,safeDecode:()=>qme,safeDecodeAsync:()=>Hme,safeEncode:()=>jme,safeEncodeAsync:()=>Gme,safeParse:()=>eR,safeParseAsync:()=>aU,toDotPath:()=>Nme,toJSONSchema:()=>wT,treeifyError:()=>Ome,util:()=>_r,version:()=>n6});var cs=S({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/index.js"(){cT(),Vme(),$me(),jhe(),t6(),khe(),kt(),NU(),g5(),SR(),Che(),wyr(),UR(),bT(),byr(),Eyr()}}),Nge={};he(Nge,{endsWith:()=>PR,gt:()=>fm,gte:()=>Ua,includes:()=>RR,length:()=>vT,lowercase:()=>AR,lt:()=>hm,lte:()=>sc,maxLength:()=>yT,maxSize:()=>bv,mime:()=>DR,minLength:()=>lf,minSize:()=>gm,multipleOf:()=>wv,negative:()=>j5,nonnegative:()=>G5,nonpositive:()=>q5,normalize:()=>OR,overwrite:()=>Fd,positive:()=>z5,property:()=>H5,regex:()=>xR,size:()=>gT,slugify:()=>FR,startsWith:()=>MR,toLowerCase:()=>LR,toUpperCase:()=>$R,trim:()=>NR,uppercase:()=>IR});var MB=S({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/checks.js"(){cs()}}),qR={};he(qR,{ZodISODate:()=>HR,ZodISODateTime:()=>GR,ZodISODuration:()=>WR,ZodISOTime:()=>VR,date:()=>$ge,datetime:()=>Lge,duration:()=>Uge,time:()=>Fge});function Lge(e){return Yfe(GR,e)}function $ge(e){return Zfe(HR,e)}function Fge(e){return Xfe(VR,e)}function Uge(e){return Qfe(WR,e)}var GR,HR,VR,WR,KR=S({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/iso.js"(){cs(),P1(),GR=be("ZodISODateTime",(e,t)=>{y6.init(e,t),nn.init(e,t)}),HR=be("ZodISODate",(e,t)=>{v6.init(e,t),nn.init(e,t)}),VR=be("ZodISOTime",(e,t)=>{_6.init(e,t),nn.init(e,t)}),WR=be("ZodISODuration",(e,t)=>{w6.init(e,t),nn.init(e,t)})}}),PB,Bge,Ba,zge=S({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/errors.js"(){cs(),cs(),kt(),PB=(e,t)=>{ZI.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:r=>sU(e,r)},flatten:{value:r=>oU(e,r)},addIssue:{value:r=>{e.issues.push(r),e.message=JSON.stringify(e.issues,HI,2)}},addIssues:{value:r=>{e.issues.push(...r),e.message=JSON.stringify(e.issues,HI,2)}},isEmpty:{get(){return e.issues.length===0}}})},Bge=be("ZodError",PB),Ba=be("ZodError",PB,{Parent:Error})}}),DB,OB,NB,JR,LB,$B,FB,UB,BB,zB,jB,qB,jge=S({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/parse.js"(){cs(),zge(),DB=pv(Ba),OB=mv(Ba),NB=hv(Ba),JR=fv(Ba),LB=tR(Ba),$B=rR(Ba),FB=nR(Ba),UB=oR(Ba),BB=sR(Ba),zB=iR(Ba),jB=aR(Ba),qB=lR(Ba)}}),qge={};he(qge,{ZodAny:()=>i1,ZodArray:()=>u1,ZodBase64:()=>UT,ZodBase64URL:()=>BT,ZodBigInt:()=>Mv,ZodBigIntFormat:()=>qT,ZodBoolean:()=>Rv,ZodCIDRv4:()=>$T,ZodCIDRv6:()=>FT,ZodCUID:()=>RT,ZodCUID2:()=>MT,ZodCatch:()=>C1,ZodCodec:()=>KT,ZodCustom:()=>Nv,ZodCustomStringFormat:()=>cf,ZodDate:()=>GT,ZodDefault:()=>T1,ZodDiscriminatedUnion:()=>p1,ZodE164:()=>zT,ZodEmail:()=>xT,ZodEmoji:()=>AT,ZodEnum:()=>uf,ZodExactOptional:()=>w1,ZodFile:()=>v1,ZodFunction:()=>M1,ZodGUID:()=>xv,ZodIPv4:()=>NT,ZodIPv6:()=>LT,ZodIntersection:()=>m1,ZodJWT:()=>jT,ZodKSUID:()=>OT,ZodLazy:()=>I1,ZodLiteral:()=>y1,ZodMAC:()=>r1,ZodMap:()=>f1,ZodNaN:()=>k1,ZodNanoID:()=>IT,ZodNever:()=>l1,ZodNonOptional:()=>VT,ZodNull:()=>s1,ZodNullable:()=>b1,ZodNumber:()=>Iv,ZodNumberFormat:()=>ym,ZodObject:()=>Pv,ZodOptional:()=>HT,ZodPipe:()=>WT,ZodPrefault:()=>E1,ZodPromise:()=>R1,ZodReadonly:()=>x1,ZodRecord:()=>Ov,ZodSet:()=>g1,ZodString:()=>kv,ZodStringFormat:()=>nn,ZodSuccess:()=>S1,ZodSymbol:()=>n1,ZodTemplateLiteral:()=>A1,ZodTransform:()=>_1,ZodTuple:()=>h1,ZodType:()=>Qt,ZodULID:()=>PT,ZodURL:()=>Av,ZodUUID:()=>Vc,ZodUndefined:()=>o1,ZodUnion:()=>Dv,ZodUnknown:()=>a1,ZodVoid:()=>c1,ZodXID:()=>DT,ZodXor:()=>d1,_ZodString:()=>kT,_default:()=>KB,_function:()=>e1,any:()=>HB,array:()=>rt,base64:()=>cye,base64url:()=>uye,bigint:()=>bye,boolean:()=>tn,catch:()=>ZB,check:()=>qye,cidrv4:()=>aye,cidrv6:()=>lye,codec:()=>Bye,cuid:()=>Qge,cuid2:()=>eye,custom:()=>ez,date:()=>xye,describe:()=>nz,discriminatedUnion:()=>XR,e164:()=>dye,email:()=>Gge,emoji:()=>Zge,enum:()=>Gi,exactOptional:()=>WB,file:()=>Lye,float32:()=>yye,float64:()=>vye,function:()=>e1,guid:()=>Hge,hash:()=>gye,hex:()=>fye,hostname:()=>hye,httpUrl:()=>Yge,instanceof:()=>Gye,int:()=>YR,int32:()=>_ye,int64:()=>Tye,intersection:()=>ET,ipv4:()=>oye,ipv6:()=>iye,json:()=>Hye,jwt:()=>pye,keyof:()=>Aye,ksuid:()=>nye,lazy:()=>QB,literal:()=>Tt,looseObject:()=>Ns,looseRecord:()=>Pye,mac:()=>sye,map:()=>Dye,meta:()=>oz,nan:()=>Uye,nanoid:()=>Xge,nativeEnum:()=>Nye,never:()=>ZR,nonoptional:()=>YB,null:()=>TT,nullable:()=>ST,nullish:()=>$ye,number:()=>Rr,object:()=>ot,optional:()=>En,partialRecord:()=>Mye,pipe:()=>CT,prefault:()=>JB,preprocess:()=>t1,promise:()=>jye,readonly:()=>XB,record:()=>gn,refine:()=>tz,set:()=>Oye,strictObject:()=>Iye,string:()=>ce,stringFormat:()=>mye,stringbool:()=>sz,success:()=>Fye,superRefine:()=>rz,symbol:()=>Sye,templateLiteral:()=>zye,transform:()=>QR,tuple:()=>VB,uint32:()=>wye,uint64:()=>Eye,ulid:()=>tye,undefined:()=>Cye,union:()=>rn,unknown:()=>un,url:()=>GB,uuid:()=>Vge,uuidv4:()=>Wge,uuidv6:()=>Kge,uuidv7:()=>Jge,void:()=>kye,xid:()=>rye,xor:()=>Rye});function ce(e){return Wfe(kv,e)}function Gge(e){return b5(xT,e)}function Hge(e){return CR(xv,e)}function Vge(e){return T5(Vc,e)}function Wge(e){return E5(Vc,e)}function Kge(e){return S5(Vc,e)}function Jge(e){return C5(Vc,e)}function GB(e){return kR(Av,e)}function Yge(e){return kR(Av,{protocol:/^https?$/,hostname:sf.domain,..._r.normalizeParams(e)})}function Zge(e){return k5(AT,e)}function Xge(e){return x5(IT,e)}function Qge(e){return A5(RT,e)}function eye(e){return I5(MT,e)}function tye(e){return R5(PT,e)}function rye(e){return M5(DT,e)}function nye(e){return P5(OT,e)}function oye(e){return D5(NT,e)}function sye(e){return Jfe(r1,e)}function iye(e){return O5(LT,e)}function aye(e){return N5($T,e)}function lye(e){return L5(FT,e)}function cye(e){return $5(UT,e)}function uye(e){return F5(BT,e)}function dye(e){return U5(zT,e)}function pye(e){return B5(jT,e)}function mye(e,t,r={}){return _T(cf,e,t,r)}function hye(e){return _T(cf,"hostname",sf.hostname,e)}function fye(e){return _T(cf,"hex",sf.hex,e)}function gye(e,t){const r=t?.enc??"hex",n=`${e}_${r}`,o=sf[n];if(!o)throw new Error(`Unrecognized hash format: ${n}`);return _T(cf,n,o,t)}function Rr(e){return ege(Iv,e)}function YR(e){return rge(ym,e)}function yye(e){return nge(ym,e)}function vye(e){return oge(ym,e)}function _ye(e){return sge(ym,e)}function wye(e){return ige(ym,e)}function tn(e){return age(Rv,e)}function bye(e){return cge(Mv,e)}function Tye(e){return dge(qT,e)}function Eye(e){return pge(qT,e)}function Sye(e){return mge(n1,e)}function Cye(e){return hge(o1,e)}function TT(e){return fge(s1,e)}function HB(){return gge(i1)}function un(){return yge(a1)}function ZR(e){return vge(l1,e)}function kye(e){return _ge(c1,e)}function xye(e){return wge(GT,e)}function rt(e,t){return Ege(u1,e,t)}function Aye(e){const t=e._zod.def.shape;return Gi(Object.keys(t))}function ot(e,t){const r={type:"object",shape:e??{},..._r.normalizeParams(t)};return new Pv(r)}function Iye(e,t){return new Pv({type:"object",shape:e,catchall:ZR(),..._r.normalizeParams(t)})}function Ns(e,t){return new Pv({type:"object",shape:e,catchall:un(),..._r.normalizeParams(t)})}function rn(e,t){return new Dv({type:"union",options:e,..._r.normalizeParams(t)})}function Rye(e,t){return new d1({type:"union",options:e,inclusive:!1,..._r.normalizeParams(t)})}function XR(e,t,r){return new p1({type:"union",options:t,discriminator:e,..._r.normalizeParams(r)})}function ET(e,t){return new m1({type:"intersection",left:e,right:t})}function VB(e,t,r){const n=t instanceof Kt,o=n?r:t,s=n?t:null;return new h1({type:"tuple",items:e,rest:s,..._r.normalizeParams(o)})}function gn(e,t,r){return new Ov({type:"record",keyType:e,valueType:t,..._r.normalizeParams(r)})}function Mye(e,t,r){const n=nc(e);return n._zod.values=void 0,new Ov({type:"record",keyType:n,valueType:t,..._r.normalizeParams(r)})}function Pye(e,t,r){return new Ov({type:"record",keyType:e,valueType:t,mode:"loose",..._r.normalizeParams(r)})}function Dye(e,t,r){return new f1({type:"map",keyType:e,valueType:t,..._r.normalizeParams(r)})}function Oye(e,t){return new g1({type:"set",valueType:e,..._r.normalizeParams(t)})}function Gi(e,t){const r=Array.isArray(e)?Object.fromEntries(e.map(n=>[n,n])):e;return new uf({type:"enum",entries:r,..._r.normalizeParams(t)})}function Nye(e,t){return new uf({type:"enum",entries:e,..._r.normalizeParams(t)})}function Tt(e,t){return new y1({type:"literal",values:Array.isArray(e)?e:[e],..._r.normalizeParams(t)})}function Lye(e){return Sge(v1,e)}function QR(e){return new _1({type:"transform",transform:e})}function En(e){return new HT({type:"optional",innerType:e})}function WB(e){return new w1({type:"optional",innerType:e})}function ST(e){return new b1({type:"nullable",innerType:e})}function $ye(e){return En(ST(e))}function KB(e,t){return new T1({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():_r.shallowClone(t)}})}function JB(e,t){return new E1({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():_r.shallowClone(t)}})}function YB(e,t){return new VT({type:"nonoptional",innerType:e,..._r.normalizeParams(t)})}function Fye(e){return new S1({type:"success",innerType:e})}function ZB(e,t){return new C1({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}function Uye(e){return Tge(k1,e)}function CT(e,t){return new WT({type:"pipe",in:e,out:t})}function Bye(e,t,r){return new KT({type:"pipe",in:e,out:t,transform:r.decode,reverseTransform:r.encode})}function XB(e){return new x1({type:"readonly",innerType:e})}function zye(e,t){return new A1({type:"template_literal",parts:e,..._r.normalizeParams(t)})}function QB(e){return new I1({type:"lazy",getter:e})}function jye(e){return new R1({type:"promise",innerType:e})}function e1(e){return new M1({type:"function",input:Array.isArray(e?.input)?VB(e?.input):e?.input??rt(un()),output:e?.output??un()})}function qye(e){const t=new Tn({check:"custom"});return t._zod.check=e,t}function ez(e,t){return Cge(Nv,e??(()=>!0),t)}function tz(e,t={}){return kge(Nv,e,t)}function rz(e){return xge(e)}function Gye(e,t={}){const r=new Nv({type:"custom",check:"custom",fn:n=>n instanceof e,abort:!0,..._r.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 Hye(e){const t=QB(()=>rn([ce(e),Rr(),tn(),TT(),rt(t),gn(ce(),t)]));return t}function t1(e,t){return CT(QR(e),t)}var Qt,kT,kv,nn,xT,xv,Vc,Av,AT,IT,RT,MT,PT,DT,OT,NT,r1,LT,$T,FT,UT,BT,zT,jT,cf,Iv,ym,Rv,Mv,qT,n1,o1,s1,i1,a1,l1,c1,GT,u1,Pv,Dv,d1,p1,m1,h1,Ov,f1,g1,uf,y1,v1,_1,HT,w1,b1,T1,E1,VT,S1,C1,k1,WT,KT,x1,A1,I1,R1,M1,Nv,nz,oz,sz,P1=S({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/schemas.js"(){cs(),cs(),bT(),UR(),MB(),KR(),jge(),Qt=be("ZodType",(e,t)=>(Kt.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:Cv(e,"input"),output:Cv(e,"output")}}),e.toJSONSchema=W5(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.check=(...r)=>e.clone(_r.mergeDefs(t,{checks:[...t.checks??[],...r.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),{parent:!0}),e.with=e.check,e.clone=(r,n)=>nc(e,r,n),e.brand=()=>e,e.register=((r,n)=>(r.add(e,n),e)),e.parse=(r,n)=>DB(e,r,n,{callee:e.parse}),e.safeParse=(r,n)=>NB(e,r,n),e.parseAsync=async(r,n)=>OB(e,r,n,{callee:e.parseAsync}),e.safeParseAsync=async(r,n)=>JR(e,r,n),e.spa=e.safeParseAsync,e.encode=(r,n)=>LB(e,r,n),e.decode=(r,n)=>$B(e,r,n),e.encodeAsync=async(r,n)=>FB(e,r,n),e.decodeAsync=async(r,n)=>UB(e,r,n),e.safeEncode=(r,n)=>BB(e,r,n),e.safeDecode=(r,n)=>zB(e,r,n),e.safeEncodeAsync=async(r,n)=>jB(e,r,n),e.safeDecodeAsync=async(r,n)=>qB(e,r,n),e.refine=(r,n)=>e.check(tz(r,n)),e.superRefine=r=>e.check(rz(r)),e.overwrite=r=>e.check(Fd(r)),e.optional=()=>En(e),e.exactOptional=()=>WB(e),e.nullable=()=>ST(e),e.nullish=()=>En(ST(e)),e.nonoptional=r=>YB(e,r),e.array=()=>rt(e),e.or=r=>rn([e,r]),e.and=r=>ET(e,r),e.transform=r=>CT(e,QR(r)),e.default=r=>KB(e,r),e.prefault=r=>JB(e,r),e.catch=r=>ZB(e,r),e.pipe=r=>CT(e,r),e.readonly=()=>XB(e),e.describe=r=>{const n=e.clone();return vl.add(n,{description:r}),n},Object.defineProperty(e,"description",{get(){return vl.get(e)?.description},configurable:!0}),e.meta=(...r)=>{if(r.length===0)return vl.get(e);const n=e.clone();return vl.add(n,r[0]),n},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e.apply=r=>r(e),e)),kT=be("_ZodString",(e,t)=>{yv.init(e,t),Qt.init(e,t),e._zod.processJSONSchema=(n,o,s)=>K5(e,n,o,s);const r=e._zod.bag;e.format=r.format??null,e.minLength=r.minimum??null,e.maxLength=r.maximum??null,e.regex=(...n)=>e.check(xR(...n)),e.includes=(...n)=>e.check(RR(...n)),e.startsWith=(...n)=>e.check(MR(...n)),e.endsWith=(...n)=>e.check(PR(...n)),e.min=(...n)=>e.check(lf(...n)),e.max=(...n)=>e.check(yT(...n)),e.length=(...n)=>e.check(vT(...n)),e.nonempty=(...n)=>e.check(lf(1,...n)),e.lowercase=n=>e.check(AR(n)),e.uppercase=n=>e.check(IR(n)),e.trim=()=>e.check(NR()),e.normalize=(...n)=>e.check(OR(...n)),e.toLowerCase=()=>e.check(LR()),e.toUpperCase=()=>e.check($R()),e.slugify=()=>e.check(FR())}),kv=be("ZodString",(e,t)=>{yv.init(e,t),kT.init(e,t),e.email=r=>e.check(b5(xT,r)),e.url=r=>e.check(kR(Av,r)),e.jwt=r=>e.check(B5(jT,r)),e.emoji=r=>e.check(k5(AT,r)),e.guid=r=>e.check(CR(xv,r)),e.uuid=r=>e.check(T5(Vc,r)),e.uuidv4=r=>e.check(E5(Vc,r)),e.uuidv6=r=>e.check(S5(Vc,r)),e.uuidv7=r=>e.check(C5(Vc,r)),e.nanoid=r=>e.check(x5(IT,r)),e.guid=r=>e.check(CR(xv,r)),e.cuid=r=>e.check(A5(RT,r)),e.cuid2=r=>e.check(I5(MT,r)),e.ulid=r=>e.check(R5(PT,r)),e.base64=r=>e.check($5(UT,r)),e.base64url=r=>e.check(F5(BT,r)),e.xid=r=>e.check(M5(DT,r)),e.ksuid=r=>e.check(P5(OT,r)),e.ipv4=r=>e.check(D5(NT,r)),e.ipv6=r=>e.check(O5(LT,r)),e.cidrv4=r=>e.check(N5($T,r)),e.cidrv6=r=>e.check(L5(FT,r)),e.e164=r=>e.check(U5(zT,r)),e.datetime=r=>e.check(Lge(r)),e.date=r=>e.check($ge(r)),e.time=r=>e.check(Fge(r)),e.duration=r=>e.check(Uge(r))}),nn=be("ZodStringFormat",(e,t)=>{Qr.init(e,t),kT.init(e,t)}),xT=be("ZodEmail",(e,t)=>{l6.init(e,t),nn.init(e,t)}),xv=be("ZodGUID",(e,t)=>{i6.init(e,t),nn.init(e,t)}),Vc=be("ZodUUID",(e,t)=>{a6.init(e,t),nn.init(e,t)}),Av=be("ZodURL",(e,t)=>{c6.init(e,t),nn.init(e,t)}),AT=be("ZodEmoji",(e,t)=>{u6.init(e,t),nn.init(e,t)}),IT=be("ZodNanoID",(e,t)=>{d6.init(e,t),nn.init(e,t)}),RT=be("ZodCUID",(e,t)=>{p6.init(e,t),nn.init(e,t)}),MT=be("ZodCUID2",(e,t)=>{m6.init(e,t),nn.init(e,t)}),PT=be("ZodULID",(e,t)=>{h6.init(e,t),nn.init(e,t)}),DT=be("ZodXID",(e,t)=>{f6.init(e,t),nn.init(e,t)}),OT=be("ZodKSUID",(e,t)=>{g6.init(e,t),nn.init(e,t)}),NT=be("ZodIPv4",(e,t)=>{b6.init(e,t),nn.init(e,t)}),r1=be("ZodMAC",(e,t)=>{E6.init(e,t),nn.init(e,t)}),LT=be("ZodIPv6",(e,t)=>{T6.init(e,t),nn.init(e,t)}),$T=be("ZodCIDRv4",(e,t)=>{S6.init(e,t),nn.init(e,t)}),FT=be("ZodCIDRv6",(e,t)=>{C6.init(e,t),nn.init(e,t)}),UT=be("ZodBase64",(e,t)=>{k6.init(e,t),nn.init(e,t)}),BT=be("ZodBase64URL",(e,t)=>{x6.init(e,t),nn.init(e,t)}),zT=be("ZodE164",(e,t)=>{A6.init(e,t),nn.init(e,t)}),jT=be("ZodJWT",(e,t)=>{I6.init(e,t),nn.init(e,t)}),cf=be("ZodCustomStringFormat",(e,t)=>{R6.init(e,t),nn.init(e,t)}),Iv=be("ZodNumber",(e,t)=>{vR.init(e,t),Qt.init(e,t),e._zod.processJSONSchema=(n,o,s)=>J5(e,n,o,s),e.gt=(n,o)=>e.check(fm(n,o)),e.gte=(n,o)=>e.check(Ua(n,o)),e.min=(n,o)=>e.check(Ua(n,o)),e.lt=(n,o)=>e.check(hm(n,o)),e.lte=(n,o)=>e.check(sc(n,o)),e.max=(n,o)=>e.check(sc(n,o)),e.int=n=>e.check(YR(n)),e.safe=n=>e.check(YR(n)),e.positive=n=>e.check(fm(0,n)),e.nonnegative=n=>e.check(Ua(0,n)),e.negative=n=>e.check(hm(0,n)),e.nonpositive=n=>e.check(sc(0,n)),e.multipleOf=(n,o)=>e.check(wv(n,o)),e.step=(n,o)=>e.check(wv(n,o)),e.finite=()=>e;const r=e._zod.bag;e.minValue=Math.max(r.minimum??Number.NEGATIVE_INFINITY,r.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(r.maximum??Number.POSITIVE_INFINITY,r.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(r.format??"").includes("int")||Number.isSafeInteger(r.multipleOf??.5),e.isFinite=!0,e.format=r.format??null}),ym=be("ZodNumberFormat",(e,t)=>{M6.init(e,t),Iv.init(e,t)}),Rv=be("ZodBoolean",(e,t)=>{_R.init(e,t),Qt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Y5(e,r,n,o)}),Mv=be("ZodBigInt",(e,t)=>{wR.init(e,t),Qt.init(e,t),e._zod.processJSONSchema=(n,o,s)=>Z5(e,n,o,s),e.gte=(n,o)=>e.check(Ua(n,o)),e.min=(n,o)=>e.check(Ua(n,o)),e.gt=(n,o)=>e.check(fm(n,o)),e.gte=(n,o)=>e.check(Ua(n,o)),e.min=(n,o)=>e.check(Ua(n,o)),e.lt=(n,o)=>e.check(hm(n,o)),e.lte=(n,o)=>e.check(sc(n,o)),e.max=(n,o)=>e.check(sc(n,o)),e.positive=n=>e.check(fm(BigInt(0),n)),e.negative=n=>e.check(hm(BigInt(0),n)),e.nonpositive=n=>e.check(sc(BigInt(0),n)),e.nonnegative=n=>e.check(Ua(BigInt(0),n)),e.multipleOf=(n,o)=>e.check(wv(n,o));const r=e._zod.bag;e.minValue=r.minimum??null,e.maxValue=r.maximum??null,e.format=r.format??null}),qT=be("ZodBigIntFormat",(e,t)=>{P6.init(e,t),Mv.init(e,t)}),n1=be("ZodSymbol",(e,t)=>{D6.init(e,t),Qt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>X5(e,r,n,o)}),o1=be("ZodUndefined",(e,t)=>{O6.init(e,t),Qt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>eB(e,r,n,o)}),s1=be("ZodNull",(e,t)=>{N6.init(e,t),Qt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Q5(e,r,n,o)}),i1=be("ZodAny",(e,t)=>{L6.init(e,t),Qt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>nB(e,r,n,o)}),a1=be("ZodUnknown",(e,t)=>{$6.init(e,t),Qt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>oB(e,r,n,o)}),l1=be("ZodNever",(e,t)=>{F6.init(e,t),Qt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>rB(e,r,n,o)}),c1=be("ZodVoid",(e,t)=>{U6.init(e,t),Qt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>tB(e,r,n,o)}),GT=be("ZodDate",(e,t)=>{B6.init(e,t),Qt.init(e,t),e._zod.processJSONSchema=(n,o,s)=>sB(e,n,o,s),e.min=(n,o)=>e.check(Ua(n,o)),e.max=(n,o)=>e.check(sc(n,o));const r=e._zod.bag;e.minDate=r.minimum?new Date(r.minimum):null,e.maxDate=r.maximum?new Date(r.maximum):null}),u1=be("ZodArray",(e,t)=>{z6.init(e,t),Qt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>yB(e,r,n,o),e.element=t.element,e.min=(r,n)=>e.check(lf(r,n)),e.nonempty=r=>e.check(lf(1,r)),e.max=(r,n)=>e.check(yT(r,n)),e.length=(r,n)=>e.check(vT(r,n)),e.unwrap=()=>e.element}),Pv=be("ZodObject",(e,t)=>{q6.init(e,t),Qt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>vB(e,r,n,o),_r.defineLazy(e,"shape",()=>t.shape),e.keyof=()=>Gi(Object.keys(e._zod.def.shape)),e.catchall=r=>e.clone({...e._zod.def,catchall:r}),e.passthrough=()=>e.clone({...e._zod.def,catchall:un()}),e.loose=()=>e.clone({...e._zod.def,catchall:un()}),e.strict=()=>e.clone({...e._zod.def,catchall:ZR()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=r=>_r.extend(e,r),e.safeExtend=r=>_r.safeExtend(e,r),e.merge=r=>_r.merge(e,r),e.pick=r=>_r.pick(e,r),e.omit=r=>_r.omit(e,r),e.partial=(...r)=>_r.partial(HT,e,r[0]),e.required=(...r)=>_r.required(VT,e,r[0])}),Dv=be("ZodUnion",(e,t)=>{fT.init(e,t),Qt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>BR(e,r,n,o),e.options=t.options}),d1=be("ZodXor",(e,t)=>{Dv.init(e,t),G6.init(e,t),e._zod.processJSONSchema=(r,n,o)=>BR(e,r,n,o),e.options=t.options}),p1=be("ZodDiscriminatedUnion",(e,t)=>{Dv.init(e,t),H6.init(e,t)}),m1=be("ZodIntersection",(e,t)=>{V6.init(e,t),Qt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>_B(e,r,n,o)}),h1=be("ZodTuple",(e,t)=>{bR.init(e,t),Qt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>wB(e,r,n,o),e.rest=r=>e.clone({...e._zod.def,rest:r})}),Ov=be("ZodRecord",(e,t)=>{W6.init(e,t),Qt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>bB(e,r,n,o),e.keyType=t.keyType,e.valueType=t.valueType}),f1=be("ZodMap",(e,t)=>{K6.init(e,t),Qt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>fB(e,r,n,o),e.keyType=t.keyType,e.valueType=t.valueType,e.min=(...r)=>e.check(gm(...r)),e.nonempty=r=>e.check(gm(1,r)),e.max=(...r)=>e.check(bv(...r)),e.size=(...r)=>e.check(gT(...r))}),g1=be("ZodSet",(e,t)=>{J6.init(e,t),Qt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>gB(e,r,n,o),e.min=(...r)=>e.check(gm(...r)),e.nonempty=r=>e.check(gm(1,r)),e.max=(...r)=>e.check(bv(...r)),e.size=(...r)=>e.check(gT(...r))}),uf=be("ZodEnum",(e,t)=>{Y6.init(e,t),Qt.init(e,t),e._zod.processJSONSchema=(n,o,s)=>iB(e,n,o,s),e.enum=t.entries,e.options=Object.values(t.entries);const r=new Set(Object.keys(t.entries));e.extract=(n,o)=>{const s={};for(const i of n)if(r.has(i))s[i]=t.entries[i];else throw new Error(`Key ${i} not found in enum`);return new uf({...t,checks:[],..._r.normalizeParams(o),entries:s})},e.exclude=(n,o)=>{const s={...t.entries};for(const i of n)if(r.has(i))delete s[i];else throw new Error(`Key ${i} not found in enum`);return new uf({...t,checks:[],..._r.normalizeParams(o),entries:s})}}),y1=be("ZodLiteral",(e,t)=>{Z6.init(e,t),Qt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>aB(e,r,n,o),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]}})}),v1=be("ZodFile",(e,t)=>{X6.init(e,t),Qt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>uB(e,r,n,o),e.min=(r,n)=>e.check(gm(r,n)),e.max=(r,n)=>e.check(bv(r,n)),e.mime=(r,n)=>e.check(DR(Array.isArray(r)?r:[r],n))}),_1=be("ZodTransform",(e,t)=>{Q6.init(e,t),Qt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>hB(e,r,n,o),e._zod.parse=(r,n)=>{if(n.direction==="backward")throw new aT(e.constructor.name);r.addIssue=s=>{if(typeof s=="string")r.issues.push(_r.issue(s,r.value,t));else{const i=s;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),i.input??(i.input=r.value),i.inst??(i.inst=e),r.issues.push(_r.issue(i))}};const o=t.transform(r.value,r);return o instanceof Promise?o.then(s=>(r.value=s,r)):(r.value=o,r)}}),HT=be("ZodOptional",(e,t)=>{TR.init(e,t),Qt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>zR(e,r,n,o),e.unwrap=()=>e._zod.def.innerType}),w1=be("ZodExactOptional",(e,t)=>{e5.init(e,t),Qt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>zR(e,r,n,o),e.unwrap=()=>e._zod.def.innerType}),b1=be("ZodNullable",(e,t)=>{t5.init(e,t),Qt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>TB(e,r,n,o),e.unwrap=()=>e._zod.def.innerType}),T1=be("ZodDefault",(e,t)=>{r5.init(e,t),Qt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>SB(e,r,n,o),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap}),E1=be("ZodPrefault",(e,t)=>{n5.init(e,t),Qt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>CB(e,r,n,o),e.unwrap=()=>e._zod.def.innerType}),VT=be("ZodNonOptional",(e,t)=>{o5.init(e,t),Qt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>EB(e,r,n,o),e.unwrap=()=>e._zod.def.innerType}),S1=be("ZodSuccess",(e,t)=>{s5.init(e,t),Qt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>dB(e,r,n,o),e.unwrap=()=>e._zod.def.innerType}),C1=be("ZodCatch",(e,t)=>{i5.init(e,t),Qt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>kB(e,r,n,o),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap}),k1=be("ZodNaN",(e,t)=>{a5.init(e,t),Qt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>lB(e,r,n,o)}),WT=be("ZodPipe",(e,t)=>{l5.init(e,t),Qt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>xB(e,r,n,o),e.in=t.in,e.out=t.out}),KT=be("ZodCodec",(e,t)=>{WT.init(e,t),ER.init(e,t)}),x1=be("ZodReadonly",(e,t)=>{c5.init(e,t),Qt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>AB(e,r,n,o),e.unwrap=()=>e._zod.def.innerType}),A1=be("ZodTemplateLiteral",(e,t)=>{u5.init(e,t),Qt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>cB(e,r,n,o)}),I1=be("ZodLazy",(e,t)=>{m5.init(e,t),Qt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>RB(e,r,n,o),e.unwrap=()=>e._zod.def.getter()}),R1=be("ZodPromise",(e,t)=>{p5.init(e,t),Qt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>IB(e,r,n,o),e.unwrap=()=>e._zod.def.innerType}),M1=be("ZodFunction",(e,t)=>{d5.init(e,t),Qt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>mB(e,r,n,o)}),Nv=be("ZodCustom",(e,t)=>{h5.init(e,t),Qt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>pB(e,r,n,o)}),nz=Ige,oz=Rge,sz=(...e)=>Mge({Codec:KT,Boolean:Rv,String:kv},...e)}});function Syr(e){qi({customError:e})}function Cyr(){return qi().customError}var iz,az,kyr=S({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/compat.js"(){cs(),cs(),iz={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"},az||(az={})}});function xyr(e,t){const 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 Ayr(e,t){if(!e.startsWith("#"))throw new Error("External $ref is not supported, only local refs (#/...) are allowed");const r=e.slice(1).split("/").filter(Boolean);if(r.length===0)return t.rootSchema;const n=t.version==="draft-2020-12"?"$defs":"definitions";if(r[0]===n){const o=r[1];if(!o||!t.defs[o])throw new Error(`Reference not found: ${e}`);return t.defs[o]}throw new Error(`Reference not found: ${e}`)}function Vye(e,t){if(e.not!==void 0){if(typeof e.not=="object"&&Object.keys(e.not).length===0)return it.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){const o=e.$ref;if(t.refs.has(o))return t.refs.get(o);if(t.processing.has(o))return it.lazy(()=>{if(!t.refs.has(o))throw new Error(`Circular reference not resolved: ${o}`);return t.refs.get(o)});t.processing.add(o);const s=Ayr(o,t),i=Hi(s,t);return t.refs.set(o,i),t.processing.delete(o),i}if(e.enum!==void 0){const o=e.enum;if(t.version==="openapi-3.0"&&e.nullable===!0&&o.length===1&&o[0]===null)return it.null();if(o.length===0)return it.never();if(o.length===1)return it.literal(o[0]);if(o.every(i=>typeof i=="string"))return it.enum(o);const s=o.map(i=>it.literal(i));return s.length<2?s[0]:it.union([s[0],s[1],...s.slice(2)])}if(e.const!==void 0)return it.literal(e.const);const r=e.type;if(Array.isArray(r)){const o=r.map(s=>{const i={...e,type:s};return Vye(i,t)});return o.length===0?it.never():o.length===1?o[0]:it.union(o)}if(!r)return it.any();let n;switch(r){case"string":{let o=it.string();if(e.format){const s=e.format;s==="email"?o=o.check(it.email()):s==="uri"||s==="uri-reference"?o=o.check(it.url()):s==="uuid"||s==="guid"?o=o.check(it.uuid()):s==="date-time"?o=o.check(it.iso.datetime()):s==="date"?o=o.check(it.iso.date()):s==="time"?o=o.check(it.iso.time()):s==="duration"?o=o.check(it.iso.duration()):s==="ipv4"?o=o.check(it.ipv4()):s==="ipv6"?o=o.check(it.ipv6()):s==="mac"?o=o.check(it.mac()):s==="cidr"?o=o.check(it.cidrv4()):s==="cidr-v6"?o=o.check(it.cidrv6()):s==="base64"?o=o.check(it.base64()):s==="base64url"?o=o.check(it.base64url()):s==="e164"?o=o.check(it.e164()):s==="jwt"?o=o.check(it.jwt()):s==="emoji"?o=o.check(it.emoji()):s==="nanoid"?o=o.check(it.nanoid()):s==="cuid"?o=o.check(it.cuid()):s==="cuid2"?o=o.check(it.cuid2()):s==="ulid"?o=o.check(it.ulid()):s==="xid"?o=o.check(it.xid()):s==="ksuid"&&(o=o.check(it.ksuid()))}typeof e.minLength=="number"&&(o=o.min(e.minLength)),typeof e.maxLength=="number"&&(o=o.max(e.maxLength)),e.pattern&&(o=o.regex(new RegExp(e.pattern))),n=o;break}case"number":case"integer":{let o=r==="integer"?it.number().int():it.number();typeof e.minimum=="number"&&(o=o.min(e.minimum)),typeof e.maximum=="number"&&(o=o.max(e.maximum)),typeof e.exclusiveMinimum=="number"?o=o.gt(e.exclusiveMinimum):e.exclusiveMinimum===!0&&typeof e.minimum=="number"&&(o=o.gt(e.minimum)),typeof e.exclusiveMaximum=="number"?o=o.lt(e.exclusiveMaximum):e.exclusiveMaximum===!0&&typeof e.maximum=="number"&&(o=o.lt(e.maximum)),typeof e.multipleOf=="number"&&(o=o.multipleOf(e.multipleOf)),n=o;break}case"boolean":{n=it.boolean();break}case"null":{n=it.null();break}case"object":{const o={},s=e.properties||{},i=new Set(e.required||[]);for(const[l,c]of Object.entries(s)){const u=Hi(c,t);o[l]=i.has(l)?u:u.optional()}if(e.propertyNames){const l=Hi(e.propertyNames,t),c=e.additionalProperties&&typeof e.additionalProperties=="object"?Hi(e.additionalProperties,t):it.any();if(Object.keys(o).length===0){n=it.record(l,c);break}const u=it.object(o).passthrough(),d=it.looseRecord(l,c);n=it.intersection(u,d);break}if(e.patternProperties){const l=e.patternProperties,c=Object.keys(l),u=[];for(const m of c){const h=Hi(l[m],t),g=it.string().regex(new RegExp(m));u.push(it.looseRecord(g,h))}const d=[];if(Object.keys(o).length>0&&d.push(it.object(o).passthrough()),d.push(...u),d.length===0)n=it.object({}).passthrough();else if(d.length===1)n=d[0];else{let m=it.intersection(d[0],d[1]);for(let h=2;h<d.length;h++)m=it.intersection(m,d[h]);n=m}break}const a=it.object(o);e.additionalProperties===!1?n=a.strict():typeof e.additionalProperties=="object"?n=a.catchall(Hi(e.additionalProperties,t)):n=a.passthrough();break}case"array":{const o=e.prefixItems,s=e.items;if(o&&Array.isArray(o)){const i=o.map(l=>Hi(l,t)),a=s&&typeof s=="object"&&!Array.isArray(s)?Hi(s,t):void 0;a?n=it.tuple(i).rest(a):n=it.tuple(i),typeof e.minItems=="number"&&(n=n.check(it.minLength(e.minItems))),typeof e.maxItems=="number"&&(n=n.check(it.maxLength(e.maxItems)))}else if(Array.isArray(s)){const i=s.map(l=>Hi(l,t)),a=e.additionalItems&&typeof e.additionalItems=="object"?Hi(e.additionalItems,t):void 0;a?n=it.tuple(i).rest(a):n=it.tuple(i),typeof e.minItems=="number"&&(n=n.check(it.minLength(e.minItems))),typeof e.maxItems=="number"&&(n=n.check(it.maxLength(e.maxItems)))}else if(s!==void 0){const i=Hi(s,t);let a=it.array(i);typeof e.minItems=="number"&&(a=a.min(e.minItems)),typeof e.maxItems=="number"&&(a=a.max(e.maxItems)),n=a}else n=it.array(it.any());break}default:throw new Error(`Unsupported type: ${r}`)}return e.description&&(n=n.describe(e.description)),e.default!==void 0&&(n=n.default(e.default)),n}function Hi(e,t){if(typeof e=="boolean")return e?it.any():it.never();let r=Vye(e,t);const n=e.type||e.enum!==void 0||e.const!==void 0;if(e.anyOf&&Array.isArray(e.anyOf)){const a=e.anyOf.map(c=>Hi(c,t)),l=it.union(a);r=n?it.intersection(r,l):l}if(e.oneOf&&Array.isArray(e.oneOf)){const a=e.oneOf.map(c=>Hi(c,t)),l=it.xor(a);r=n?it.intersection(r,l):l}if(e.allOf&&Array.isArray(e.allOf))if(e.allOf.length===0)r=n?r:it.any();else{let a=n?r:Hi(e.allOf[0],t);const l=n?0:1;for(let c=l;c<e.allOf.length;c++)a=it.intersection(a,Hi(e.allOf[c],t));r=a}e.nullable===!0&&t.version==="openapi-3.0"&&(r=it.nullable(r)),e.readOnly===!0&&(r=it.readonly(r));const o={},s=["$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor"];for(const a of s)a in e&&(o[a]=e[a]);const i=["contentEncoding","contentMediaType","contentSchema"];for(const a of i)a in e&&(o[a]=e[a]);for(const a of Object.keys(e))Wye.has(a)||(o[a]=e[a]);return Object.keys(o).length>0&&t.registry.add(r,o),r}function Iyr(e,t){if(typeof e=="boolean")return e?it.any():it.never();const r=xyr(e,t?.defaultTarget),n=e.$defs||e.definitions||{},o={version:r,defs:n,refs:new Map,processing:new Set,rootSchema:e,registry:t?.registry??vl};return Hi(e,o)}var it,Wye,Ryr=S({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/from-json-schema.js"(){SR(),MB(),KR(),P1(),it={...qge,...Nge,iso:qR},Wye=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"])}}),lz={};he(lz,{bigint:()=>Oyr,boolean:()=>Dyr,date:()=>Nyr,number:()=>Pyr,string:()=>Myr});function Myr(e){return Kfe(kv,e)}function Pyr(e){return tge(Iv,e)}function Dyr(e){return lge(Rv,e)}function Oyr(e){return uge(Mv,e)}function Nyr(e){return bge(GT,e)}var Lyr=S({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/coerce.js"(){cs(),P1()}}),p={};he(p,{$brand:()=>Y3,$input:()=>_5,$output:()=>v5,NEVER:()=>GI,TimePrecision:()=>V5,ZodAny:()=>i1,ZodArray:()=>u1,ZodBase64:()=>UT,ZodBase64URL:()=>BT,ZodBigInt:()=>Mv,ZodBigIntFormat:()=>qT,ZodBoolean:()=>Rv,ZodCIDRv4:()=>$T,ZodCIDRv6:()=>FT,ZodCUID:()=>RT,ZodCUID2:()=>MT,ZodCatch:()=>C1,ZodCodec:()=>KT,ZodCustom:()=>Nv,ZodCustomStringFormat:()=>cf,ZodDate:()=>GT,ZodDefault:()=>T1,ZodDiscriminatedUnion:()=>p1,ZodE164:()=>zT,ZodEmail:()=>xT,ZodEmoji:()=>AT,ZodEnum:()=>uf,ZodError:()=>Bge,ZodExactOptional:()=>w1,ZodFile:()=>v1,ZodFirstPartyTypeKind:()=>az,ZodFunction:()=>M1,ZodGUID:()=>xv,ZodIPv4:()=>NT,ZodIPv6:()=>LT,ZodISODate:()=>HR,ZodISODateTime:()=>GR,ZodISODuration:()=>WR,ZodISOTime:()=>VR,ZodIntersection:()=>m1,ZodIssueCode:()=>iz,ZodJWT:()=>jT,ZodKSUID:()=>OT,ZodLazy:()=>I1,ZodLiteral:()=>y1,ZodMAC:()=>r1,ZodMap:()=>f1,ZodNaN:()=>k1,ZodNanoID:()=>IT,ZodNever:()=>l1,ZodNonOptional:()=>VT,ZodNull:()=>s1,ZodNullable:()=>b1,ZodNumber:()=>Iv,ZodNumberFormat:()=>ym,ZodObject:()=>Pv,ZodOptional:()=>HT,ZodPipe:()=>WT,ZodPrefault:()=>E1,ZodPromise:()=>R1,ZodReadonly:()=>x1,ZodRealError:()=>Ba,ZodRecord:()=>Ov,ZodSet:()=>g1,ZodString:()=>kv,ZodStringFormat:()=>nn,ZodSuccess:()=>S1,ZodSymbol:()=>n1,ZodTemplateLiteral:()=>A1,ZodTransform:()=>_1,ZodTuple:()=>h1,ZodType:()=>Qt,ZodULID:()=>PT,ZodURL:()=>Av,ZodUUID:()=>Vc,ZodUndefined:()=>o1,ZodUnion:()=>Dv,ZodUnknown:()=>a1,ZodVoid:()=>c1,ZodXID:()=>DT,ZodXor:()=>d1,_ZodString:()=>kT,_default:()=>KB,_function:()=>e1,any:()=>HB,array:()=>rt,base64:()=>cye,base64url:()=>uye,bigint:()=>bye,boolean:()=>tn,catch:()=>ZB,check:()=>qye,cidrv4:()=>aye,cidrv6:()=>lye,clone:()=>nc,codec:()=>Bye,coerce:()=>lz,config:()=>qi,core:()=>Oge,cuid:()=>Qge,cuid2:()=>eye,custom:()=>ez,date:()=>xye,decode:()=>$B,decodeAsync:()=>UB,describe:()=>nz,discriminatedUnion:()=>XR,e164:()=>dye,email:()=>Gge,emoji:()=>Zge,encode:()=>LB,encodeAsync:()=>FB,endsWith:()=>PR,enum:()=>Gi,exactOptional:()=>WB,file:()=>Lye,flattenError:()=>oU,float32:()=>yye,float64:()=>vye,formatError:()=>sU,fromJSONSchema:()=>Iyr,function:()=>e1,getErrorMap:()=>Cyr,globalRegistry:()=>vl,gt:()=>fm,gte:()=>Ua,guid:()=>Hge,hash:()=>gye,hex:()=>fye,hostname:()=>hye,httpUrl:()=>Yge,includes:()=>RR,instanceof:()=>Gye,int:()=>YR,int32:()=>_ye,int64:()=>Tye,intersection:()=>ET,ipv4:()=>oye,ipv6:()=>iye,iso:()=>qR,json:()=>Hye,jwt:()=>pye,keyof:()=>Aye,ksuid:()=>nye,lazy:()=>QB,length:()=>vT,literal:()=>Tt,locales:()=>f5,looseObject:()=>Ns,looseRecord:()=>Pye,lowercase:()=>AR,lt:()=>hm,lte:()=>sc,mac:()=>sye,map:()=>Dye,maxLength:()=>yT,maxSize:()=>bv,meta:()=>oz,mime:()=>DR,minLength:()=>lf,minSize:()=>gm,multipleOf:()=>wv,nan:()=>Uye,nanoid:()=>Xge,nativeEnum:()=>Nye,negative:()=>j5,never:()=>ZR,nonnegative:()=>G5,nonoptional:()=>YB,nonpositive:()=>q5,normalize:()=>OR,null:()=>TT,nullable:()=>ST,nullish:()=>$ye,number:()=>Rr,object:()=>ot,optional:()=>En,overwrite:()=>Fd,parse:()=>DB,parseAsync:()=>OB,partialRecord:()=>Mye,pipe:()=>CT,positive:()=>z5,prefault:()=>JB,preprocess:()=>t1,prettifyError:()=>Lme,promise:()=>jye,property:()=>H5,readonly:()=>XB,record:()=>gn,refine:()=>tz,regex:()=>xR,regexes:()=>sf,registry:()=>y5,safeDecode:()=>zB,safeDecodeAsync:()=>qB,safeEncode:()=>BB,safeEncodeAsync:()=>jB,safeParse:()=>NB,safeParseAsync:()=>JR,set:()=>Oye,setErrorMap:()=>Syr,size:()=>gT,slugify:()=>FR,startsWith:()=>MR,strictObject:()=>Iye,string:()=>ce,stringFormat:()=>mye,stringbool:()=>sz,success:()=>Fye,superRefine:()=>rz,symbol:()=>Sye,templateLiteral:()=>zye,toJSONSchema:()=>wT,toLowerCase:()=>LR,toUpperCase:()=>$R,transform:()=>QR,treeifyError:()=>Ome,trim:()=>NR,tuple:()=>VB,uint32:()=>wye,uint64:()=>Eye,ulid:()=>tye,undefined:()=>Cye,union:()=>rn,unknown:()=>un,uppercase:()=>IR,url:()=>GB,util:()=>_r,uuid:()=>Vge,uuidv4:()=>Wge,uuidv6:()=>Kge,uuidv7:()=>Jge,void:()=>kye,xid:()=>rye,xor:()=>Rye});var D1=S({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/external.js"(){cs(),P1(),MB(),zge(),jge(),kyr(),cs(),efe(),cs(),bT(),Ryr(),g5(),KR(),KR(),Lyr(),qi(Xhe())}}),Gr=S({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/index.js"(){D1(),D1()}}),cz,uz,$yr=S({"src/lib/types/model.ts"(){"use strict";Gr(),cz=p.object({id:p.string(),displayName:p.string(),capabilities:p.array(p.string()),deprecated:p.boolean(),pricing:p.object({input:p.number(),output:p.number()}),contextWindow:p.number(),releaseDate:p.string()}),uz=p.object({version:p.string(),lastUpdated:p.string(),models:p.record(p.string(),p.record(p.string(),cz)),aliases:p.record(p.string(),p.string()).optional(),defaults:p.record(p.string(),p.string()).optional()})}});function Fyr(e){return e.type==="text"}function Uyr(e){return e.type==="image"}function dz(e){return e.type==="csv"}function Byr(e){return e.type==="pdf"}function zyr(e){return e.type==="audio"}function jyr(e){return e.type==="video"}function qyr(e){if(!e||typeof e!="object")return!1;const t=e;if(typeof t.prompt!="string"||!t.prompt)return!1;const{image:r}=t;if(!r)return!1;if(Buffer.isBuffer(r)||typeof r=="string")return!0;if(typeof r=="object"&&"data"in r){const n=r.data;return Buffer.isBuffer(n)||typeof n=="string"}return!1}function Gyr(e){if(typeof e!="object"||e===null)return!1;const t=e,r=n=>Array.isArray(n)&&n.length>0;return!!(r(t.images)||r(t.csvFiles)||r(t.pdfFiles)||r(t.files)||r(t.content)||r(t.audioFiles)||r(t.videoFiles)||Array.isArray(t.segments)&&t.segments.length>0&&t.segments.every(qyr))}function Hyr(e){return Array.isArray(e)}var Vyr=S({"src/lib/types/multimodal.ts"(){"use strict"}}),Wyr=S({"src/lib/types/nativeTools.ts"(){"use strict"}}),Kyr=S({"src/lib/types/observability.ts"(){"use strict"}}),Jyr=S({"src/lib/types/openaiCompatible.ts"(){"use strict"}});function Yyr(e){return/^[0-9A-Fa-f]{6}$/.test(e)}function Zyr(e){return e.startsWith("#")?e.slice(1):e}var Kye,Jye,O1,Xyr=S({"src/lib/types/ppt.ts"(){"use strict";Kye=5,Jye=50,O1={"16:9":{width:10,height:5.625},"4:3":{width:10,height:7.5}}}}),pz,Yye,Zye=S({"src/lib/processors/errors/FileErrorCode.ts"(){"use strict";pz=(e=>(e.DOWNLOAD_FAILED="DOWNLOAD_FAILED",e.DOWNLOAD_TIMEOUT="DOWNLOAD_TIMEOUT",e.DOWNLOAD_AUTH_FAILED="DOWNLOAD_AUTH_FAILED",e.NETWORK_ERROR="NETWORK_ERROR",e.FILE_NOT_FOUND="FILE_NOT_FOUND",e.RATE_LIMITED="RATE_LIMITED",e.FILE_TOO_LARGE="FILE_TOO_LARGE",e.UNSUPPORTED_TYPE="UNSUPPORTED_TYPE",e.INVALID_FORMAT="INVALID_FORMAT",e.INVALID_MIME_TYPE="INVALID_MIME_TYPE",e.INVALID_MAGIC_BYTES="INVALID_MAGIC_BYTES",e.CORRUPTED_FILE="CORRUPTED_FILE",e.INVALID_STRUCTURE="INVALID_STRUCTURE",e.PROCESSING_FAILED="PROCESSING_FAILED",e.PARSING_FAILED="PARSING_FAILED",e.ENCODING_ERROR="ENCODING_ERROR",e.EXTRACTION_FAILED="EXTRACTION_FAILED",e.DECOMPRESSION_FAILED="DECOMPRESSION_FAILED",e.SECURITY_VALIDATION_FAILED="SECURITY_VALIDATION_FAILED",e.XXE_DETECTED="XXE_DETECTED",e.XSS_DETECTED="XSS_DETECTED",e.CODE_EXECUTION_DETECTED="CODE_EXECUTION_DETECTED",e.ZIP_BOMB_DETECTED="ZIP_BOMB_DETECTED",e.UNKNOWN_ERROR="UNKNOWN_ERROR",e))(pz||{}),Yye={DOWNLOAD_FAILED:{message:"Failed to download the file from the source.",userMessage:"We couldn't download your file.",suggestedAction:"Please try uploading the file again. If the problem persists, the file may have been deleted or access revoked.",retryable:!0},DOWNLOAD_TIMEOUT:{message:"File download timed out.",userMessage:"The download took too long and was cancelled.",suggestedAction:"This usually happens with very large files or slow connections. Try re-uploading a smaller version or check your network connection.",retryable:!0},DOWNLOAD_AUTH_FAILED:{message:"Authentication failed when accessing the file.",userMessage:"We don't have permission to access this file.",suggestedAction:"Please check the file permissions and ensure it's accessible, then try again.",retryable:!1},NETWORK_ERROR:{message:"Network error while downloading the file.",userMessage:"A network error occurred while downloading.",suggestedAction:"This is usually temporary. Please try uploading the file again.",retryable:!0},FILE_NOT_FOUND:{message:"The file could not be found at the specified location.",userMessage:"The file could not be found.",suggestedAction:"The file may have been moved or deleted. Please re-upload the file.",retryable:!1},RATE_LIMITED:{message:"Request was rate limited by the server.",userMessage:"Too many requests in a short time.",suggestedAction:"Please wait a few seconds and try again.",retryable:!0},FILE_TOO_LARGE:{message:"File exceeds the maximum allowed size.",userMessage:"This file is too large to process.",suggestedAction:"Try compressing the file or splitting it into smaller parts. Consider reducing image quality or removing unnecessary content.",retryable:!1},UNSUPPORTED_TYPE:{message:"The file type is not supported for processing.",userMessage:"This file type is not supported.",suggestedAction:"Please convert your file to a supported format and try again.",retryable:!1},INVALID_FORMAT:{message:"The file format is invalid or malformed.",userMessage:"This file appears to be in an invalid format.",suggestedAction:"Please ensure the file is properly saved and not corrupted, then try again.",retryable:!1},INVALID_MIME_TYPE:{message:"File MIME type doesn't match the expected format.",userMessage:"The file type doesn't match its extension.",suggestedAction:"Please ensure the file extension matches its actual content type and try again.",retryable:!1},INVALID_MAGIC_BYTES:{message:"File magic bytes don't match the expected file type.",userMessage:"This file doesn't appear to be a valid file of the expected type.",suggestedAction:"The file may be corrupted or saved in the wrong format. Try re-saving the file in the correct format.",retryable:!0},CORRUPTED_FILE:{message:"File appears to be corrupted or damaged.",userMessage:"This file appears to be corrupted or invalid.",suggestedAction:"The file structure is invalid. Try re-downloading from the original source or re-creating the file.",retryable:!1},INVALID_STRUCTURE:{message:"File internal structure is invalid.",userMessage:"The file has an invalid internal structure.",suggestedAction:"The file format is correct but the content is malformed. Try validating the file with a format checker or re-exporting from the original application.",retryable:!1},PROCESSING_FAILED:{message:"Failed to process the file content.",userMessage:"We couldn't process this file.",suggestedAction:"Please try again. If the problem persists, the file may be in an unsupported variant.",retryable:!0},PARSING_FAILED:{message:"Failed to parse the file content.",userMessage:"We couldn't read the contents of this file.",suggestedAction:"The file structure may be invalid. Try validating the file with a format checker or re-creating the file.",retryable:!1},ENCODING_ERROR:{message:"Text encoding error detected.",userMessage:"We couldn't decode the text in this file.",suggestedAction:"Try re-saving the file with UTF-8 encoding. Most modern text editors have this option in 'Save As' settings.",retryable:!1},EXTRACTION_FAILED:{message:"Failed to extract content from the file.",userMessage:"We couldn't extract the content from this file.",suggestedAction:"The file may be password-protected, corrupted, or use an unsupported variant. Try re-saving without protection.",retryable:!1},DECOMPRESSION_FAILED:{message:"Failed to decompress the file content.",userMessage:"We couldn't decompress this file.",suggestedAction:"The file may be corrupted or use an unsupported compression method. Try re-uploading or using a different file format.",retryable:!0},SECURITY_VALIDATION_FAILED:{message:"File failed security validation.",userMessage:"This file contains content that is blocked for security reasons.",suggestedAction:"Please remove the problematic content and try again. If you believe this is a legitimate file, please contact support.",retryable:!1},XXE_DETECTED:{message:"XML External Entity (XXE) attack pattern detected.",userMessage:"This XML file contains DOCTYPE or ENTITY declarations that could pose security risks.",suggestedAction:"Please remove DOCTYPE and ENTITY declarations from the XML file. Most XML files don't need these for basic data storage.",retryable:!1},XSS_DETECTED:{message:"Cross-site scripting (XSS) attack pattern detected.",userMessage:"This file contains script tags or event handlers that could pose security risks.",suggestedAction:"Please remove <script> tags and event handlers (onclick, onerror, etc.) from the file.",retryable:!1},CODE_EXECUTION_DETECTED:{message:"Potentially malicious code execution pattern detected.",userMessage:"This file contains code execution tags that are not allowed.",suggestedAction:"Please remove custom object/function tags and use standard data structures only.",retryable:!1},ZIP_BOMB_DETECTED:{message:"Zip bomb or decompression bomb pattern detected.",userMessage:"This file has an unusually high compression ratio that could indicate a security threat.",suggestedAction:"If this is a legitimate file, try re-saving it without extreme compression. Otherwise, please verify the file source.",retryable:!1},UNKNOWN_ERROR:{message:"An unexpected error occurred.",userMessage:"An unexpected error occurred while processing your file.",suggestedAction:"Please try again. If the problem persists, contact support.",retryable:!0}}}}),mz,Xye,Qye,eve,tve,rve,Qyr=S({"src/lib/types/processor.ts"(){"use strict";Zye(),mz={maxRetries:3,baseDelayMs:1e3,maxDelayMs:1e4},Xye=3e4,Qye=10,eve=3e4,tve=10,rve={SVG:5,IMAGE:10,PDF:20,CSV:30,MARKDOWN:40,JSON:50,YAML:60,XML:70,HTML:80,EXCEL:90,DOC:95,WORD:100,TEXT:110,SOURCE_CODE:120,CONFIG:130,RTF:140,OPENDOCUMENT:150,VIDEO:160,AUDIO:170,ARCHIVE:180}}}),evr=S({"src/lib/types/providerCatalog.ts"(){"use strict"}}),tvr=S({"src/lib/types/providerCatalog.generated.ts"(){"use strict"}});function rvr(e){if(e==null||typeof e!="object")return!1;const t=e,r=["api_key","oauth"],n=["free","pro","max","max_5","max_20","api"];if(t.authMethod!==void 0&&typeof t.authMethod=="string"&&r.includes(t.authMethod)||t.subscriptionTier!==void 0&&typeof t.subscriptionTier=="string"&&n.includes(t.subscriptionTier)||t.oauthConfig!==void 0&&typeof t.oauthConfig=="object"&&t.oauthConfig!==null)return!0;if(t.authConfig!==void 0&&typeof t.authConfig=="object"&&t.authConfig!==null){const o=t.authConfig;if(o.method!==void 0&&typeof o.method=="string"&&r.includes(o.method))return!0}return!1}var N1,nve,ove,nvr=S({"src/lib/types/providers.ts"(){"use strict";N1={LATEST_OPENAI:"gpt-4o",FASTEST_OPENAI:"gpt-4o-mini",LATEST_ANTHROPIC:"claude-3-5-sonnet-20241022",FASTEST_ANTHROPIC:"claude-3-5-haiku-20241022",LATEST_GOOGLE:"gemini-2.5-pro",FASTEST_GOOGLE:"gemini-2.5-flash",BEST_CODING:"claude-3-5-sonnet-20241022",BEST_ANALYSIS:"gemini-2.5-pro",BEST_CREATIVE:"claude-3-5-sonnet-20241022",BEST_VALUE:"gemini-2.5-flash"},nve=N1,ove=[{provider:"bedrock",models:["anthropic.claude-3-7-sonnet-20250219-v1:0","anthropic.claude-3-5-sonnet-20241022-v1:0"]},{provider:"vertex",models:["claude-sonnet-4@20250514","gemini-2.5-flash"]},{provider:"openai",models:["gpt-4o","gpt-4o-mini"]}]}}),ovr=S({"src/lib/types/proxy.ts"(){"use strict"}}),svr=S({"src/lib/types/proxyClient.ts"(){"use strict"}}),ivr=S({"src/lib/types/rag.ts"(){"use strict"}}),avr=S({"src/lib/types/scorer.ts"(){"use strict"}}),lvr=S({"src/lib/types/sdk.ts"(){"use strict"}}),kr,Sn,Er,cvr=S({"src/lib/types/server.ts"(){"use strict";kr={CONFIG:"CONFIG",VALIDATION:"VALIDATION",EXECUTION:"EXECUTION",EXTERNAL:"EXTERNAL",RATE_LIMIT:"RATE_LIMIT",AUTHENTICATION:"AUTHENTICATION",AUTHORIZATION:"AUTHORIZATION",STREAMING:"STREAMING",WEBSOCKET:"WEBSOCKET"},Sn={LOW:"LOW",MEDIUM:"MEDIUM",HIGH:"HIGH",CRITICAL:"CRITICAL"},Er={INVALID_CONFIG:"SERVER_ADAPTER_INVALID_CONFIG",MISSING_DEPENDENCY:"SERVER_ADAPTER_MISSING_DEPENDENCY",FRAMEWORK_INIT_FAILED:"SERVER_ADAPTER_FRAMEWORK_INIT_FAILED",ROUTE_NOT_FOUND:"SERVER_ADAPTER_ROUTE_NOT_FOUND",ROUTE_CONFLICT:"SERVER_ADAPTER_ROUTE_CONFLICT",INVALID_ROUTE:"SERVER_ADAPTER_INVALID_ROUTE",HANDLER_ERROR:"SERVER_ADAPTER_HANDLER_ERROR",TIMEOUT:"SERVER_ADAPTER_TIMEOUT",MIDDLEWARE_ERROR:"SERVER_ADAPTER_MIDDLEWARE_ERROR",RATE_LIMIT_EXCEEDED:"SERVER_ADAPTER_RATE_LIMIT_EXCEEDED",AUTH_REQUIRED:"SERVER_ADAPTER_AUTH_REQUIRED",AUTH_INVALID:"SERVER_ADAPTER_AUTH_INVALID",FORBIDDEN:"SERVER_ADAPTER_FORBIDDEN",STREAM_ERROR:"SERVER_ADAPTER_STREAM_ERROR",STREAM_ABORTED:"SERVER_ADAPTER_STREAM_ABORTED",WEBSOCKET_ERROR:"SERVER_ADAPTER_WEBSOCKET_ERROR",WEBSOCKET_CONNECTION_FAILED:"SERVER_ADAPTER_WEBSOCKET_CONNECTION_FAILED",VALIDATION_ERROR:"SERVER_ADAPTER_VALIDATION_ERROR",SCHEMA_ERROR:"SERVER_ADAPTER_SCHEMA_ERROR",START_FAILED:"SERVER_ADAPTER_START_FAILED",STOP_FAILED:"SERVER_ADAPTER_STOP_FAILED",ALREADY_RUNNING:"SERVER_ADAPTER_ALREADY_RUNNING",NOT_RUNNING:"SERVER_ADAPTER_NOT_RUNNING"}}}),uvr=S({"src/lib/types/service.ts"(){"use strict"}}),dvr=S({"src/lib/types/skills.ts"(){"use strict"}}),pvr=S({"src/lib/types/stream.ts"(){"use strict"}}),mvr=S({"src/lib/types/streaming.ts"(){"use strict"}}),hvr=S({"src/lib/types/subscription.ts"(){"use strict"}}),hz,fz,Ho,fvr=S({"src/lib/types/task.ts"(){"use strict";hz=720*60*60*1e3,fz=10080*60*1e3,Ho={enabled:!0,maxTasks:100,backend:"bullmq",mode:"isolated",timeout:12e4,maxConcurrentRuns:5,maxRunLogs:2e3,maxHistoryEntries:200,tools:!0,retry:{maxAttempts:3,backoffMs:[3e4,6e4,3e5]},storePath:".neurolink/tasks/tasks.json",logsPath:".neurolink/tasks/runs/",redis:{host:"localhost",port:6379},retention:{completedTTL:hz,failedTTL:fz,cancelledTTL:fz,runLogTTL:hz}}}}),gvr=S({"src/lib/types/taskClassification.ts"(){"use strict"}}),yvr=S({"src/lib/types/tasks.ts"(){"use strict"}}),vvr=S({"src/lib/types/toolDedup.ts"(){"use strict"}}),_vr=S({"src/lib/types/toolResolution.ts"(){"use strict"}}),wvr=S({"src/lib/types/toolRouting.ts"(){"use strict"}});function bvr(e){return typeof e=="object"&&e!==null&&"success"in e&&typeof e.success=="boolean"}function Tvr(e){return typeof e=="object"&&e!==null&&"description"in e&&"execute"in e&&typeof e.description=="string"&&typeof e.execute=="function"}var Evr=S({"src/lib/types/tools.ts"(){"use strict"}}),Svr=S({"src/lib/types/vectorStoreChroma.ts"(){"use strict"}}),Cvr=S({"src/lib/types/vectorStorePinecone.ts"(){"use strict"}});function kvr(e){if(!e||typeof e!="object")return!1;const t=e;return Buffer.isBuffer(t.buffer)&&typeof t.format=="string"&&JT.includes(t.format)&&typeof t.size=="number"&&t.size>=0}function xvr(e){if(!e||typeof e!="object")return!1;const t=e;return!(t.speed!==void 0&&(typeof t.speed!="number"||t.speed<.25||t.speed>4)||t.format!==void 0&&!JT.includes(t.format)||t.quality!==void 0&&!gz.includes(t.quality)||t.streamingBufferSize!==void 0&&(!Number.isInteger(t.streamingBufferSize)||t.streamingBufferSize<1))}var JT,gz,Avr=S({"src/lib/types/tts.ts"(){"use strict";JT=["mp3","wav","ogg","opus","m4a","flac","webm","mp4","mpeg","mpga","pcm16"],gz=["standard","hd"]}});function sve(e){if(!e||typeof e!="object")return!1;const t=e;return typeof t.text=="string"&&typeof t.confidence=="number"&&t.confidence>=0&&t.confidence<=1}function ive(e){if(!e||typeof e!="object")return!1;const t=e;return!(t.sampleRate!==void 0&&(typeof t.sampleRate!="number"||t.sampleRate<=0)||t.speakerCount!==void 0&&(typeof t.speakerCount!="number"||t.speakerCount<1||t.speakerCount>10))}function ave(e){if(!e||typeof e!="object")return!1;const t=e;return(t.index===void 0||typeof t.index=="number")&&typeof t.text=="string"&&typeof t.isFinal=="boolean"}var Ai,yz,Ivr=S({"src/lib/types/stt.ts"(){"use strict";Ai={AUDIO_EMPTY:"STT_AUDIO_EMPTY",AUDIO_TOO_LONG:"STT_AUDIO_TOO_LONG",INVALID_AUDIO_FORMAT:"STT_INVALID_AUDIO_FORMAT",LANGUAGE_NOT_SUPPORTED:"STT_LANGUAGE_NOT_SUPPORTED",TRANSCRIPTION_FAILED:"STT_TRANSCRIPTION_FAILED",PROVIDER_NOT_CONFIGURED:"STT_PROVIDER_NOT_CONFIGURED",PROVIDER_NOT_SUPPORTED:"STT_PROVIDER_NOT_SUPPORTED",STREAM_ERROR:"STT_STREAM_ERROR",STREAMING_NOT_SUPPORTED:"STT_STREAMING_NOT_SUPPORTED"},yz={language:"en-US",punctuation:!0,profanityFilter:!1,sampleRate:16e3}}});function lve(e){if(!e||typeof e!="object")return!1;const t=e;return!(!t.provider||!["openai-realtime","gemini-live"].includes(t.provider)||t.timeout!==void 0&&(typeof t.timeout!="number"||t.timeout<=0)||t.vadThreshold!==void 0&&(typeof t.vadThreshold!="number"||t.vadThreshold<0||t.vadThreshold>1))}var ri,L1,Rvr=S({"src/lib/types/realtime.ts"(){"use strict";ri={CONNECTION_FAILED:"REALTIME_CONNECTION_FAILED",SESSION_TIMEOUT:"REALTIME_SESSION_TIMEOUT",PROTOCOL_ERROR:"REALTIME_PROTOCOL_ERROR",AUDIO_STREAM_ERROR:"REALTIME_AUDIO_STREAM_ERROR",PROVIDER_NOT_CONFIGURED:"REALTIME_PROVIDER_NOT_CONFIGURED",PROVIDER_NOT_SUPPORTED:"REALTIME_PROVIDER_NOT_SUPPORTED",SESSION_ALREADY_ACTIVE:"REALTIME_SESSION_ALREADY_ACTIVE",SESSION_NOT_ACTIVE:"REALTIME_SESSION_NOT_ACTIVE",INVALID_MESSAGE:"REALTIME_INVALID_MESSAGE"},L1={timeout:3e4,inputSampleRate:24e3,outputSampleRate:24e3,vadEnabled:!0,vadThreshold:.5,turnDetection:"server_vad"}}}),vz,YT,Mvr=S({"src/lib/types/voice.ts"(){"use strict";Avr(),Ivr(),Rvr(),vz={PROVIDER_NOT_FOUND:"VOICE_PROVIDER_NOT_FOUND",INVALID_CONFIGURATION:"VOICE_INVALID_CONFIGURATION",INITIALIZATION_FAILED:"VOICE_INITIALIZATION_FAILED",OPERATION_CANCELLED:"VOICE_OPERATION_CANCELLED",PROVIDER_NOT_CONFIGURED:"VOICE_PROVIDER_NOT_CONFIGURED",PROVIDER_NOT_SUPPORTED:"VOICE_PROVIDER_NOT_SUPPORTED",FEATURE_NOT_SUPPORTED:"VOICE_FEATURE_NOT_SUPPORTED",TTS_EMPTY_TEXT:"VOICE_TTS_EMPTY_TEXT",TTS_TEXT_TOO_LONG:"VOICE_TTS_TEXT_TOO_LONG",TTS_SYNTHESIS_FAILED:"VOICE_TTS_SYNTHESIS_FAILED",STT_EMPTY_AUDIO:"VOICE_STT_EMPTY_AUDIO",STT_INVALID_FORMAT:"VOICE_STT_INVALID_FORMAT",STT_TRANSCRIPTION_FAILED:"VOICE_STT_TRANSCRIPTION_FAILED",REALTIME_CONNECTION_FAILED:"VOICE_REALTIME_CONNECTION_FAILED",REALTIME_SESSION_ERROR:"VOICE_REALTIME_SESSION_ERROR",NETWORK_ERROR:"VOICE_NETWORK_ERROR",TIMEOUT:"VOICE_TIMEOUT"},YT={mp3:{format:"mp3",mimeType:"audio/mpeg",extension:".mp3",supportsStreaming:!0,sampleRates:[8e3,16e3,22050,24e3,44100,48e3],bitDepths:[16]},wav:{format:"wav",mimeType:"audio/wav",extension:".wav",supportsStreaming:!1,sampleRates:[8e3,16e3,22050,24e3,44100,48e3],bitDepths:[8,16,24,32]},ogg:{format:"ogg",mimeType:"audio/ogg",extension:".ogg",supportsStreaming:!0,sampleRates:[8e3,16e3,22050,24e3,44100,48e3],bitDepths:[16]},opus:{format:"opus",mimeType:"audio/opus",extension:".opus",supportsStreaming:!0,sampleRates:[8e3,12e3,16e3,24e3,48e3],bitDepths:[16]},m4a:{format:"m4a",mimeType:"audio/mp4",extension:".m4a",supportsStreaming:!1,sampleRates:[44100,48e3],bitDepths:[16]},flac:{format:"flac",mimeType:"audio/flac",extension:".flac",supportsStreaming:!1,sampleRates:[44100,48e3,96e3],bitDepths:[16,24]},webm:{format:"webm",mimeType:"audio/webm",extension:".webm",supportsStreaming:!0,sampleRates:[44100,48e3],bitDepths:[16]},mp4:{format:"mp4",mimeType:"audio/mp4",extension:".mp4",supportsStreaming:!1,sampleRates:[44100,48e3],bitDepths:[16]},mpeg:{format:"mpeg",mimeType:"audio/mpeg",extension:".mpeg",supportsStreaming:!0,sampleRates:[8e3,16e3,22050,24e3,44100,48e3],bitDepths:[16]},mpga:{format:"mpga",mimeType:"audio/mpeg",extension:".mpga",supportsStreaming:!0,sampleRates:[8e3,16e3,22050,24e3,44100,48e3],bitDepths:[16]}}}}),Pvr=S({"src/lib/types/utilities.ts"(){"use strict"}}),Ud,Dvr=S({"src/lib/types/workflow.ts"(){"use strict";Ud=class sdr extends Error{details;constructor(t,r){super(t),this.name="WorkflowError",this.details=r,"captureStackTrace"in Error&&typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,sdr)}}}}),Ovr=S({"src/lib/types/ioProcessor.ts"(){"use strict"}}),Nvr=S({"src/lib/types/exporter.ts"(){"use strict"}}),_z,wz,cve,uve,Lvr=S({"src/lib/types/span.ts"(){"use strict";_z=(e=>(e.AGENT_RUN="agent.run",e.WORKFLOW_STEP="workflow.step",e.TOOL_CALL="tool.call",e.MODEL_GENERATION="model.generation",e.EMBEDDING="embedding",e.RETRIEVAL="retrieval",e.MEMORY="memory",e.CONTEXT_COMPACTION="context.compaction",e.RAG="rag",e.EVALUATION="evaluation",e.MCP_TRANSPORT="mcp.transport",e.MEDIA_GENERATION="media.generation",e.PPT_GENERATION="ppt.generation",e.WORKFLOW="workflow",e.TTS="tts",e.STT="stt",e.SERVER_REQUEST="server.request",e.CUSTOM="custom",e))(_z||{}),wz=(e=>(e[e.UNSET=0]="UNSET",e[e.OK=1]="OK",e[e.ERROR=2]="ERROR",e[e.WARNING=3]="WARNING",e))(wz||{}),cve={GEN_AI_SYSTEM:"gen_ai.system",GEN_AI_REQUEST_MODEL:"gen_ai.request.model",GEN_AI_RESPONSE_MODEL:"gen_ai.response.model",GEN_AI_USAGE_INPUT_TOKENS:"gen_ai.usage.input_tokens",GEN_AI_USAGE_OUTPUT_TOKENS:"gen_ai.usage.output_tokens",GEN_AI_USAGE_TOTAL_TOKENS:"gen_ai.usage.total_tokens",GEN_AI_REQUEST_TEMPERATURE:"gen_ai.request.temperature",GEN_AI_REQUEST_TOP_P:"gen_ai.request.top_p",GEN_AI_REQUEST_MAX_TOKENS:"gen_ai.request.max_tokens",GEN_AI_REQUEST_STOP_SEQUENCES:"gen_ai.request.stop_sequences",GEN_AI_RESPONSE_FINISH_REASON:"gen_ai.response.finish_reasons",GEN_AI_RESPONSE_ID:"gen_ai.response.id",GEN_AI_TOOL_NAME:"gen_ai.tool.name",GEN_AI_TOOL_CALL_ID:"gen_ai.tool.call_id",GEN_AI_PROMPT:"gen_ai.prompt",GEN_AI_COMPLETION:"gen_ai.completion"},uve={AGENT_NAME:"gen_ai.agent.name",AGENT_STEP_TYPE:"gen_ai.agent.step_type",AGENT_TOOL_CALLS:"gen_ai.agent.tool_calls",AGENT_MEMORY_ACCESS:"gen_ai.agent.memory_access",AGENT_REASONING_TRACE:"gen_ai.agent.reasoning_trace"}}}),bz,$vr=S({"src/lib/types/imageGen.ts"(){"use strict";bz={enabled:!0,defaultModel:"imagen-3.0-generate-001",defaultProvider:"vertex",defaultRegion:"global",timeout:12e4,defaultTemperature:.75,maxImages:4,maxReferenceImages:5,maxReferencePdfs:1}}}),Fvr=S({"src/lib/types/elicitation.ts"(){"use strict"}}),Uvr=S({"src/lib/types/dynamic.ts"(){"use strict"}}),Bvr=S({"src/lib/types/streamDedup.ts"(){"use strict"}}),zvr=S({"src/lib/types/noOutputSentinel.ts"(){"use strict"}}),jvr=S({"src/lib/types/video.ts"(){"use strict"}}),dve,qvr=S({"src/lib/types/avatar.ts"(){"use strict";dve=["mp4","webm","mov"]}}),pve,Gvr=S({"src/lib/types/music.ts"(){"use strict";pve=["mp3","wav","flac","ogg"]}}),Hvr=S({"src/lib/types/replicate.ts"(){"use strict"}}),Vvr=S({"src/lib/types/mediaCatalog.ts"(){"use strict"}}),Wvr=S({"src/lib/types/safeFetch.ts"(){"use strict"}}),Kvr=S({"src/lib/types/modelPool.ts"(){"use strict"}}),Jvr=S({"src/lib/types/requestRouter.ts"(){"use strict"}}),Yvr=S({"src/lib/types/classifierRouter.ts"(){"use strict"}}),Zvr=S({"src/lib/types/agentNetwork.ts"(){"use strict"}}),Xvr=S({"src/lib/types/localUsage.ts"(){"use strict"}}),Qvr=S({"src/lib/types/dispatch.ts"(){"use strict"}}),yt=S({"src/lib/types/index.ts"(){"use strict";cpr(),upr(),Amr(),Imr(),Rmr(),Mmr(),Pmr(),Dmr(),Omr(),$mr(),Fmr(),Umr(),zmr(),ghr(),yhr(),vhr(),_hr(),whr(),bhr(),Thr(),Ehr(),Shr(),Chr(),khr(),xhr(),Ahr(),Ihr(),Rhr(),Mhr(),Phr(),Dhr(),Ohr(),Nhr(),Lhr(),$hr(),Fhr(),Uhr(),Bhr(),zhr(),jhr(),$yr(),Vyr(),Wyr(),Kyr(),Jyr(),Xyr(),Qyr(),evr(),tvr(),nvr(),ovr(),svr(),ivr(),avr(),lvr(),cvr(),uvr(),dvr(),pvr(),mvr(),hvr(),fvr(),gvr(),yvr(),vvr(),_vr(),wvr(),Evr(),Svr(),Cvr(),Mvr(),Pvr(),Dvr(),Ovr(),Nvr(),Lvr(),$vr(),Fvr(),Uvr(),Bvr(),zvr(),jvr(),qvr(),Gvr(),Hvr(),Vvr(),Wvr(),Kvr(),Jvr(),Yvr(),Zvr(),Xvr(),Qvr()}});function ic(e){if(e!==void 0){if(typeof e=="number"){if(e<=0)throw new Error(`Timeout must be positive, got: ${e}`);return e}if(typeof e=="string"){const t=e.match(/^(\d+(?:\.\d+)?)(ms|s|m|h)?$/);if(!t)throw new Error(`Invalid timeout format: ${e}. Use formats like '30s', '2m', '500ms', or '1.5h'`);const r=parseFloat(t[1]);if(r<=0)throw new Error(`Timeout must be positive, got: ${r}`);switch(t[2]||"ms"){case"ms":return r;case"s":return r*1e3;case"m":return r*60*1e3;case"h":return r*60*60*1e3;default:return r}}throw new Error(`Invalid timeout type: ${typeof e}`)}}function e0r(e,t="generate"){if(t==="stream")return F1.streaming;const r=e.toLowerCase().replace("_","-");return F1.providers[r]||F1.global}async function t0r(e,t,r,n){const o=ic(t);if(!o)return e;const s=new Promise((i,a)=>{setTimeout(()=>{a(new Wc(`${r} ${n} operation timed out after ${o}ms`,o,r,n))},o)});return Promise.race([e,s])}function ac(e,t,r){const n=ic(e);if(!n)return null;const o=new AbortController,s=()=>{o.abort(new Wc(`${t} ${r} operation timed out after ${e}`,n,t,r))};let i=setTimeout(s,n);return{controller:o,cleanup:()=>{clearTimeout(i)},reset:()=>{o.signal.aborted||(clearTimeout(i),i=setTimeout(s,n))},timeoutMs:n}}function $1(e,t){return e&&t?AbortSignal.any([e,t]):e??t}function r0r(e,t){if(!e||!t)return{signal:e??t,dispose:()=>{}};const r=new AbortController,n=[e,t],o=[],s=()=>{for(const{source:a,listener:l}of o)a.removeEventListener("abort",l);o.length=0},i=a=>{r.signal.aborted||r.abort(a.reason),s()};for(const a of n){const l=()=>i(a);a.addEventListener("abort",l,{once:!0}),o.push({source:a,listener:l})}for(const a of n)if(a.aborted){i(a);break}return{signal:r.signal,dispose:s}}function mve(e){const t=new AbortController,r=e.filter(s=>s!==void 0),n=r.find(s=>s.aborted);if(n)return t.abort(n.reason),t;if(r.length===0)return t;const o=AbortSignal.any(r);return o.addEventListener("abort",()=>{t.signal.aborted||t.abort(o.reason)},{once:!0}),t.__nlMergedSignal=o,t}var Wc,F1,za=S({"src/lib/utils/timeout.ts"(){"use strict";Wc=class idr extends Error{constructor(t,r,n,o){super(t),this.timeout=r,this.provider=n,this.operation=o,this.name="TimeoutError",typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,idr)}timeout;provider;operation},F1={global:"30s",streaming:"2m",providers:{openai:"30s",bedrock:"45s",vertex:"60s",anthropic:"60s",azure:"30s","google-ai":"30s",huggingface:"2m",ollama:"5m",mistral:"45s",litellm:"5m"},tools:{default:"10s",filesystem:"5s",network:"30s",computation:"2m"}}}}),U1,ZT,XT,QT,B1=S({"src/lib/hitl/hitlErrors.ts"(){"use strict";U1=class extends Error{constructor(e,t){super(e),this.confirmationId=t,this.name="HITLError"}confirmationId},ZT=class extends U1{constructor(e,t,r,n){super(e,n),this.toolName=t,this.reason=r,this.name="HITLUserRejectedError"}toolName;reason},XT=class extends U1{constructor(e,t,r){super(e,t),this.timeout=r,this.name="HITLTimeoutError"}timeout},QT=class extends U1{constructor(e){super(e),this.name="HITLConfigurationError"}}}}),eE={};he(eE,{CircuitBreaker:()=>j1,ERROR_CODES:()=>Xe,ErrorFactory:()=>ke,NeuroLinkError:()=>Ne,isAbortError:()=>mr,isRecoverableError:()=>z1,isRetriableError:()=>Tz,logStructuredError:()=>fve,withRetry:()=>hve,withTimeout:()=>Ze});async function Ze(e,t,r){let n;const o=new Promise((s,i)=>{n=setTimeout(()=>{i(r||new Error(`Operation timed out after ${t}ms`))},t)});try{return await Promise.race([e,o])}finally{clearTimeout(n)}}async function hve(e,t){const{maxAttempts:r,delayMs:n,isRetriable:o=()=>!0,onRetry:s}=t;let i;for(let a=1;a<=r;a++)try{return await e()}catch(l){if(i=l instanceof Error?l:new Error(String(l)),a===r||!o(i))throw i;s&&s(a,i),await new Promise(c=>setTimeout(c,n))}throw i||new Error("Retry operation failed with no error information")}function mr(e){return!!(e instanceof DOMException&&e.name==="AbortError"||e instanceof Error&&e.name==="AbortError"||e instanceof Ne&&e.category==="abort"||e instanceof Error&&(e.message?.includes("This operation was aborted")||e.message?.includes("The operation was aborted")||e.message?.includes("The user aborted a request")||e.message?.includes("Request was aborted")))}function Tz(e){return e instanceof Ne?e.retriable:e instanceof XT?!1:[/timeout/i,/network/i,/connection/i,/temporary/i,/rate limit/i,/quota/i,/503/i,/502/i,/504/i].some(r=>r.test(e.message))}function z1(e){const t=e;if("retriable"in e&&typeof t.retriable=="boolean")return t.retriable;const r=e.message?.toLowerCase()||"";return!!(r.includes("rate limit")||r.includes("too many requests")||/\b429\b/.test(r)||r.includes("timeout")||r.includes("etimedout")||r.includes("timed out")||r.includes("econnreset")||r.includes("econnrefused")||r.includes("network")||r.includes("socket")||/\b50[0234]\b/.test(r))}function fve(e,t){const r={...e.toJSON(),...t};switch(e.severity){case"critical":f.error(`[CRITICAL] ${e.message}`,r);break;case"high":f.error(`[HIGH] ${e.message}`,r);break;case"medium":f.warn(`[MEDIUM] ${e.message}`,r);break;case"low":f.info(`[LOW] ${e.message}`,r);break}}var Xe,Ne,ke,j1,at=S({"src/lib/utils/errorHandling.ts"(){"use strict";q(),yt(),B1(),Xe={TOOL_NOT_FOUND:"TOOL_NOT_FOUND",TOOL_EXECUTION_FAILED:"TOOL_EXECUTION_FAILED",TOOL_TIMEOUT:"TOOL_TIMEOUT",TOOL_VALIDATION_FAILED:"TOOL_VALIDATION_FAILED",INVALID_PARAMETERS:"INVALID_PARAMETERS",MISSING_REQUIRED_PARAM:"MISSING_REQUIRED_PARAM",MEMORY_EXHAUSTED:"MEMORY_EXHAUSTED",NETWORK_ERROR:"NETWORK_ERROR",PERMISSION_DENIED:"PERMISSION_DENIED",PROXY_WORKER_LIFECYCLE_FAILED:"PROXY_WORKER_LIFECYCLE_FAILED",PROVIDER_NOT_AVAILABLE:"PROVIDER_NOT_AVAILABLE",PROVIDER_AUTH_FAILED:"PROVIDER_AUTH_FAILED",PROVIDER_QUOTA_EXCEEDED:"PROVIDER_QUOTA_EXCEEDED",OPERATION_ABORTED:"OPERATION_ABORTED",INVALID_CONFIGURATION:"INVALID_CONFIGURATION",MISSING_CONFIGURATION:"MISSING_CONFIGURATION",INVALID_VIDEO_RESOLUTION:"INVALID_VIDEO_RESOLUTION",INVALID_VIDEO_LENGTH:"INVALID_VIDEO_LENGTH",INVALID_VIDEO_ASPECT_RATIO:"INVALID_VIDEO_ASPECT_RATIO",INVALID_VIDEO_AUDIO:"INVALID_VIDEO_AUDIO",INVALID_VIDEO_MODE:"INVALID_VIDEO_MODE",MISSING_VIDEO_IMAGE:"MISSING_VIDEO_IMAGE",EMPTY_VIDEO_PROMPT:"EMPTY_VIDEO_PROMPT",VIDEO_PROMPT_TOO_LONG:"VIDEO_PROMPT_TOO_LONG",EMPTY_IMAGE_PATH:"EMPTY_IMAGE_PATH",INVALID_IMAGE_TYPE:"INVALID_IMAGE_TYPE",IMAGE_TOO_LARGE:"IMAGE_TOO_LARGE",IMAGE_TOO_SMALL:"IMAGE_TOO_SMALL",INVALID_IMAGE_FORMAT:"INVALID_IMAGE_FORMAT",INVALID_IMAGE_SIZE:"INVALID_IMAGE_SIZE",IMAGE_BUFFER_INVALID:"IMAGE_BUFFER_INVALID",FILE_PROCESSING_FAILED:"FILE_PROCESSING_FAILED",CSV_PROCESSING_FAILED:"CSV_PROCESSING_FAILED",PDF_PAGE_LIMIT_EXCEEDED:"PDF_PAGE_LIMIT_EXCEEDED",PDF_AGGREGATE_PAGE_LIMIT_EXCEEDED:"PDF_AGGREGATE_PAGE_LIMIT_EXCEEDED",PDF_AGGREGATE_SIZE_LIMIT_EXCEEDED:"PDF_AGGREGATE_SIZE_LIMIT_EXCEEDED",PDF_PAGE_COUNT_UNVERIFIABLE:"PDF_PAGE_COUNT_UNVERIFIABLE",PDF_PASSWORD_REQUIRED:"PDF_PASSWORD_REQUIRED",PDF_INCORRECT_PASSWORD:"PDF_INCORRECT_PASSWORD",RATE_LIMITER_QUEUE_FULL:"RATE_LIMITER_QUEUE_FULL",RATE_LIMITER_QUEUE_TIMEOUT:"RATE_LIMITER_QUEUE_TIMEOUT",RATE_LIMITER_RESET:"RATE_LIMITER_RESET",SCORER_NOT_FOUND:"SCORER_NOT_FOUND",EVALUATION_VALIDATION_FAILED:"EVALUATION_VALIDATION_FAILED",EVALUATION_TIMEOUT:"EVALUATION_TIMEOUT",EVALUATION_EXECUTION_FAILED:"EVALUATION_EXECUTION_FAILED",MISSING_PPT_PROPERTIES:"MISSING_PPT_PROPERTIES",INVALID_PPT_PAGES:"INVALID_PPT_PAGES",INVALID_PPT_FORMAT:"INVALID_PPT_FORMAT",INVALID_PPT_PROVIDER:"INVALID_PPT_PROVIDER",INVALID_PPT_OUTPUT_OPTIONS:"INVALID_PPT_OUTPUT_OPTIONS",INVALID_PPT_OUTPUT_PATH:"INVALID_PPT_OUTPUT_PATH",INVALID_PPT_LOGO_PATH:"INVALID_PPT_LOGO_PATH",INVALID_PPT_MODE:"INVALID_PPT_MODE",INVALID_PPT_PROMPT:"INVALID_PPT_PROMPT",CSV_INVALID_INPUT:"CSV_INVALID_INPUT",CSV_ROW_INVALID:"CSV_ROW_INVALID",CSV_FILE_ACCESS_FAILED:"CSV_FILE_ACCESS_FAILED",CSV_PARSE_FAILED:"CSV_PARSE_FAILED"},Ne=class extends Error{code;category;severity;retriable;retryAfterMs;context;timestamp;toolName;serverId;constructor(e){super(e.message),this.name="NeuroLinkError",this.code=e.code,this.category=e.category,this.severity=e.severity,this.retriable=e.retriable,this.retryAfterMs=e.retryAfterMs,this.context=e.context||{},this.timestamp=new Date,this.toolName=e.toolName,this.serverId=e.serverId,e.originalError&&(this.stack=e.originalError.stack,this.context.originalMessage=e.originalError.message)}toJSON(){return{code:this.code,message:this.message,category:this.category,severity:this.severity,retriable:this.retriable,context:this.context,timestamp:this.timestamp,toolName:this.toolName,serverId:this.serverId}}},ke=class{static toolNotFound(e,t){return new Ne({code:Xe.TOOL_NOT_FOUND,message:`Tool '${e}' not found`,category:"validation",severity:"medium",retriable:!1,context:{toolName:e,availableTools:t},toolName:e})}static toolExecutionFailed(e,t,r){return new Ne({code:Xe.TOOL_EXECUTION_FAILED,message:`Tool '${e}' execution failed: ${t.message}`,category:"execution",severity:"high",retriable:!0,originalError:t,toolName:e,serverId:r})}static toolTimeout(e,t,r){return new Ne({code:Xe.TOOL_TIMEOUT,message:`Tool '${e}' timed out after ${t}ms`,category:"timeout",severity:"high",retriable:!0,context:{timeoutMs:t},toolName:e,serverId:r})}static invalidParameters(e,t,r){return new Ne({code:Xe.INVALID_PARAMETERS,message:`Invalid parameters for tool '${e}': ${t.message}`,category:"validation",severity:"medium",retriable:!1,context:{providedParams:r},originalError:t,toolName:e})}static networkError(e,t,r){return new Ne({code:Xe.NETWORK_ERROR,message:`Network error in tool '${e}': ${t.message}`,category:"network",severity:"high",retriable:!0,originalError:t,toolName:e,serverId:r})}static memoryExhausted(e,t){return new Ne({code:Xe.MEMORY_EXHAUSTED,message:`Memory exhausted during tool '${e}' execution (${t}MB used)`,category:"resource",severity:"critical",retriable:!1,context:{memoryUsageMB:t},toolName:e})}static aborted(e){const t=new Ne({code:Xe.OPERATION_ABORTED,message:e?.message||"The operation was aborted",category:"abort",severity:"low",retriable:!1,context:{},originalError:e});return t.name="AbortError",t}static missingConfiguration(e,t){return new Ne({code:Xe.MISSING_CONFIGURATION,message:`Missing required configuration: ${e}`,category:"validation",severity:"high",retriable:!1,context:t||{}})}static invalidConfiguration(e,t,r){return new Ne({code:Xe.INVALID_CONFIGURATION,message:`Invalid configuration for '${e}': ${t}`,category:"validation",severity:"high",retriable:!1,context:r||{}})}static csvInvalidInput(e){return new Ne({code:Xe.CSV_INVALID_INPUT,message:e,category:"validation",severity:"medium",retriable:!1,context:{}})}static csvRowInvalid(e,t){return new Ne({code:Xe.CSV_ROW_INVALID,message:e,category:"validation",severity:"medium",retriable:!1,context:{rowNumber:t}})}static csvFileAccessFailed(e,t,r){return new Ne({code:Xe.CSV_FILE_ACCESS_FAILED,message:e,category:"resource",severity:"high",retriable:!1,context:{filePath:t},originalError:r})}static csvParseFailed(e,t,r){return new Ne({code:Xe.CSV_PARSE_FAILED,message:e,category:"execution",severity:"medium",retriable:!1,context:t,originalError:r})}static invalidVideoResolution(e){return new Ne({code:Xe.INVALID_VIDEO_RESOLUTION,message:`Invalid resolution '${e}'. Use '720p' or '1080p'`,category:"validation",severity:"medium",retriable:!1,context:{field:"output.video.resolution",providedValue:e,suggestions:["Use '720p' for standard HD","Use '1080p' for full HD"]}})}static invalidVideoLength(e){return new Ne({code:Xe.INVALID_VIDEO_LENGTH,message:`Invalid length '${e}'. Use 4, 6, or 8 seconds`,category:"validation",severity:"medium",retriable:!1,context:{field:"output.video.length",providedValue:e,suggestions:["Use 4 for short clips","Use 6 for balanced duration (recommended)","Use 8 for longer videos"]}})}static invalidVideoAspectRatio(e){return new Ne({code:Xe.INVALID_VIDEO_ASPECT_RATIO,message:`Invalid aspect ratio '${e}'. Use '9:16' or '16:9'`,category:"validation",severity:"medium",retriable:!1,context:{field:"output.video.aspectRatio",providedValue:e,suggestions:["Use '9:16' for portrait/vertical video","Use '16:9' for landscape"]}})}static invalidVideoAudio(e){return new Ne({code:Xe.INVALID_VIDEO_AUDIO,message:`Invalid audio option '${e}'. Must be true or false`,category:"validation",severity:"medium",retriable:!1,context:{field:"output.video.audio",providedValue:e,suggestions:["Set audio: true to enable audio generation","Set audio: false to disable"]}})}static invalidVideoMode(){return new Ne({code:Xe.INVALID_VIDEO_MODE,message:"Video generation requires output.mode to be 'video'",category:"validation",severity:"medium",retriable:!1,context:{field:"output.mode",suggestions:["Set output: { mode: 'video' } for video generation"]}})}static missingVideoImage(){return new Ne({code:Xe.MISSING_VIDEO_IMAGE,message:"Video generation requires an input image",category:"validation",severity:"medium",retriable:!1,context:{field:"input.images",suggestions:["Provide an image via input.images array","Example: input: { text: 'prompt', images: [imageBuffer] }"]}})}static emptyVideoPrompt(){return new Ne({code:Xe.EMPTY_VIDEO_PROMPT,message:"Video prompt cannot be empty",category:"validation",severity:"medium",retriable:!1,context:{field:"input.text",suggestions:["Provide a text prompt describing the desired video motion/content","Example: 'Smooth camera pan with dramatic lighting'"]}})}static videoPromptTooLong(e,t){return new Ne({code:Xe.VIDEO_PROMPT_TOO_LONG,message:`Video prompt must be ${t} characters or less (got ${e})`,category:"validation",severity:"medium",retriable:!1,context:{field:"input.text",providedLength:e,maxLength:t,suggestions:[`Shorten your prompt to ${t} characters or less`,"Focus on key visual elements and camera motion"]}})}static emptyImagePath(){return new Ne({code:Xe.EMPTY_IMAGE_PATH,message:"Image path or URL cannot be empty",category:"validation",severity:"medium",retriable:!1,context:{field:"input.images",suggestions:["Provide a valid file path or URL"]}})}static invalidImageType(){return new Ne({code:Xe.INVALID_IMAGE_TYPE,message:"Image must be a Buffer, file path string, or URL",category:"validation",severity:"medium",retriable:!1,context:{field:"input.images",suggestions:["Provide image as Buffer: fs.readFileSync('image.jpg')","Or as file path string: './image.jpg'","Or as URL: 'https://example.com/image.jpg'"]}})}static pdfPageLimitExceeded(e,t,r){const n=[`Split the PDF into smaller files (max ${t} pages each)`,"Extract only the pages you need using a PDF editor","For large files, consider Google AI Studio which supports up to 2000MB file size (though page limits still apply)","Convert specific pages to images manually before processing","Bypass this limit with { enforceLimits: false } (not recommended - may cause API errors or unexpected costs)"];return new Ne({code:Xe.PDF_PAGE_LIMIT_EXCEEDED,message:`PDF page limit exceeded: ${e} pages detected, but ${r} supports maximum ${t} pages.
|
|
52
|
+
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const i of e.seen.entries()){const a=i[1];if(t===i[0]){s(i);continue}if(e.external){const c=e.external.registry.get(i[0])?.id;if(t!==i[0]&&c){s(i);continue}}if(e.metadataRegistry.get(i[0])?.id){s(i);continue}if(a.cycle){s(i);continue}if(a.count>1&&e.reused==="ref"){s(i);continue}}}function Sv(e,t){const r=e.seen.get(t);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");const n=i=>{const a=e.seen.get(i);if(a.ref===null)return;const l=a.def??a.schema,c={...l},u=a.ref;if(a.ref=null,u){n(u);const m=e.seen.get(u),h=m.schema;if(h.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0")?(l.allOf=l.allOf??[],l.allOf.push(h)):Object.assign(l,h),Object.assign(l,c),i._zod.parent===u)for(const y in l)y==="$ref"||y==="allOf"||y in c||delete l[y];if(h.$ref&&m.def)for(const y in l)y==="$ref"||y==="allOf"||y in m.def&&JSON.stringify(l[y])===JSON.stringify(m.def[y])&&delete l[y]}const d=i._zod.parent;if(d&&d!==u){n(d);const m=e.seen.get(d);if(m?.schema.$ref&&(l.$ref=m.schema.$ref,m.def))for(const h in l)h==="$ref"||h==="allOf"||h in m.def&&JSON.stringify(l[h])===JSON.stringify(m.def[h])&&delete l[h]}e.override({zodSchema:i,jsonSchema:l,path:a.path??[]})};for(const i of[...e.seen.entries()].reverse())n(i[0]);const o={};if(e.target==="draft-2020-12"?o.$schema="https://json-schema.org/draft/2020-12/schema":e.target==="draft-07"?o.$schema="http://json-schema.org/draft-07/schema#":e.target==="draft-04"?o.$schema="http://json-schema.org/draft-04/schema#":e.target,e.external?.uri){const i=e.external.registry.get(t)?.id;if(!i)throw new Error("Schema is missing an `id` property");o.$id=e.external.uri(i)}Object.assign(o,r.def??r.schema);const s=e.external?.defs??{};for(const i of e.seen.entries()){const a=i[1];a.def&&a.defId&&(s[a.defId]=a.def)}e.external||Object.keys(s).length>0&&(e.target==="draft-2020-12"?o.$defs=s:o.definitions=s);try{const i=JSON.parse(JSON.stringify(o));return Object.defineProperty(i,"~standard",{value:{...t["~standard"],jsonSchema:{input:Cv(t,"input",e.processors),output:Cv(t,"output",e.processors)}},enumerable:!1,writable:!1}),i}catch{throw new Error("Error converting schema to JSON.")}}function da(e,t){const r=t??{seen:new Set};if(r.seen.has(e))return!1;r.seen.add(e);const n=e._zod.def;if(n.type==="transform")return!0;if(n.type==="array")return da(n.element,r);if(n.type==="set")return da(n.valueType,r);if(n.type==="lazy")return da(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")return da(n.innerType,r);if(n.type==="intersection")return da(n.left,r)||da(n.right,r);if(n.type==="record"||n.type==="map")return da(n.keyType,r)||da(n.valueType,r);if(n.type==="pipe")return da(n.in,r)||da(n.out,r);if(n.type==="object"){for(const o in n.shape)if(da(n.shape[o],r))return!0;return!1}if(n.type==="union"){for(const o of n.options)if(da(o,r))return!0;return!1}if(n.type==="tuple"){for(const o of n.items)if(da(o,r))return!0;return!!(n.rest&&da(n.rest,r))}return!1}var W5,Cv,UR=S({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/to-json-schema.js"(){SR(),W5=(e,t={})=>r=>{const n=Tv({...r,processors:t});return en(e,n),Ev(n,e),Sv(n,e)},Cv=(e,t,r={})=>n=>{const{libraryOptions:o,target:s}=n??{},i=Tv({...o??{},target:s,io:t,processors:r});return en(e,i),Ev(i,e),Sv(i,e)}}});function wT(e,t){if("_idmap"in e){const n=e,o=Tv({...t,processors:jR}),s={};for(const l of n._idmap.entries()){const[c,u]=l;en(u,o)}const i={},a={registry:n,uri:t?.uri,defs:s};o.external=a;for(const l of n._idmap.entries()){const[c,u]=l;Ev(o,u),i[c]=Sv(o,u)}if(Object.keys(s).length>0){const l=o.target==="draft-2020-12"?"$defs":"definitions";i.__shared={[l]:s}}return{schemas:i}}const r=Tv({...t,processors:jR});return en(e,r),Ev(r,e),Sv(r,e)}var Pge,K5,J5,Y5,Z5,X5,Q5,eB,tB,rB,nB,oB,sB,iB,aB,lB,cB,uB,dB,pB,mB,hB,fB,gB,yB,vB,BR,_B,wB,bB,TB,EB,SB,CB,kB,xB,AB,IB,zR,RB,jR,bT=S({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/json-schema-processors.js"(){UR(),kt(),Pge={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},K5=(e,t,r,n)=>{const o=r;o.type="string";const{minimum:s,maximum:i,format:a,patterns:l,contentEncoding:c}=e._zod.bag;if(typeof s=="number"&&(o.minLength=s),typeof i=="number"&&(o.maxLength=i),a&&(o.format=Pge[a]??a,o.format===""&&delete o.format,a==="time"&&delete o.format),c&&(o.contentEncoding=c),l&&l.size>0){const u=[...l];u.length===1?o.pattern=u[0].source:u.length>1&&(o.allOf=[...u.map(d=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:d.source}))])}},J5=(e,t,r,n)=>{const o=r,{minimum:s,maximum:i,format:a,multipleOf:l,exclusiveMaximum:c,exclusiveMinimum:u}=e._zod.bag;typeof a=="string"&&a.includes("int")?o.type="integer":o.type="number",typeof u=="number"&&(t.target==="draft-04"||t.target==="openapi-3.0"?(o.minimum=u,o.exclusiveMinimum=!0):o.exclusiveMinimum=u),typeof s=="number"&&(o.minimum=s,typeof u=="number"&&t.target!=="draft-04"&&(u>=s?delete o.minimum:delete o.exclusiveMinimum)),typeof c=="number"&&(t.target==="draft-04"||t.target==="openapi-3.0"?(o.maximum=c,o.exclusiveMaximum=!0):o.exclusiveMaximum=c),typeof i=="number"&&(o.maximum=i,typeof c=="number"&&t.target!=="draft-04"&&(c<=i?delete o.maximum:delete o.exclusiveMaximum)),typeof l=="number"&&(o.multipleOf=l)},Y5=(e,t,r,n)=>{r.type="boolean"},Z5=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema")},X5=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw new Error("Symbols cannot be represented in JSON Schema")},Q5=(e,t,r,n)=>{t.target==="openapi-3.0"?(r.type="string",r.nullable=!0,r.enum=[null]):r.type="null"},eB=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw new Error("Undefined cannot be represented in JSON Schema")},tB=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw new Error("Void cannot be represented in JSON Schema")},rB=(e,t,r,n)=>{r.not={}},nB=(e,t,r,n)=>{},oB=(e,t,r,n)=>{},sB=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema")},iB=(e,t,r,n)=>{const o=e._zod.def,s=Z3(o.entries);s.every(i=>typeof i=="number")&&(r.type="number"),s.every(i=>typeof i=="string")&&(r.type="string"),r.enum=s},aB=(e,t,r,n)=>{const o=e._zod.def,s=[];for(const i of o.values)if(i===void 0){if(t.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof i=="bigint"){if(t.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");s.push(Number(i))}else s.push(i);if(s.length!==0)if(s.length===1){const i=s[0];r.type=i===null?"null":typeof i,t.target==="draft-04"||t.target==="openapi-3.0"?r.enum=[i]:r.const=i}else s.every(i=>typeof i=="number")&&(r.type="number"),s.every(i=>typeof i=="string")&&(r.type="string"),s.every(i=>typeof i=="boolean")&&(r.type="boolean"),s.every(i=>i===null)&&(r.type="null"),r.enum=s},lB=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema")},cB=(e,t,r,n)=>{const o=r,s=e._zod.pattern;if(!s)throw new Error("Pattern not found in template literal");o.type="string",o.pattern=s.source},uB=(e,t,r,n)=>{const o=r,s={type:"string",format:"binary",contentEncoding:"binary"},{minimum:i,maximum:a,mime:l}=e._zod.bag;i!==void 0&&(s.minLength=i),a!==void 0&&(s.maxLength=a),l?l.length===1?(s.contentMediaType=l[0],Object.assign(o,s)):(Object.assign(o,s),o.anyOf=l.map(c=>({contentMediaType:c}))):Object.assign(o,s)},dB=(e,t,r,n)=>{r.type="boolean"},pB=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")},mB=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw new Error("Function types cannot be represented in JSON Schema")},hB=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")},fB=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw new Error("Map cannot be represented in JSON Schema")},gB=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw new Error("Set cannot be represented in JSON Schema")},yB=(e,t,r,n)=>{const o=r,s=e._zod.def,{minimum:i,maximum:a}=e._zod.bag;typeof i=="number"&&(o.minItems=i),typeof a=="number"&&(o.maxItems=a),o.type="array",o.items=en(s.element,t,{...n,path:[...n.path,"items"]})},vB=(e,t,r,n)=>{const o=r,s=e._zod.def;o.type="object",o.properties={};const i=s.shape;for(const c in i)o.properties[c]=en(i[c],t,{...n,path:[...n.path,"properties",c]});const a=new Set(Object.keys(i)),l=new Set([...a].filter(c=>{const u=s.shape[c]._zod;return t.io==="input"?u.optin===void 0:u.optout===void 0}));l.size>0&&(o.required=Array.from(l)),s.catchall?._zod.def.type==="never"?o.additionalProperties=!1:s.catchall?s.catchall&&(o.additionalProperties=en(s.catchall,t,{...n,path:[...n.path,"additionalProperties"]})):t.io==="output"&&(o.additionalProperties=!1)},BR=(e,t,r,n)=>{const o=e._zod.def,s=o.inclusive===!1,i=o.options.map((a,l)=>en(a,t,{...n,path:[...n.path,s?"oneOf":"anyOf",l]}));s?r.oneOf=i:r.anyOf=i},_B=(e,t,r,n)=>{const o=e._zod.def,s=en(o.left,t,{...n,path:[...n.path,"allOf",0]}),i=en(o.right,t,{...n,path:[...n.path,"allOf",1]}),a=c=>"allOf"in c&&Object.keys(c).length===1,l=[...a(s)?s.allOf:[s],...a(i)?i.allOf:[i]];r.allOf=l},wB=(e,t,r,n)=>{const o=r,s=e._zod.def;o.type="array";const i=t.target==="draft-2020-12"?"prefixItems":"items",a=t.target==="draft-2020-12"||t.target==="openapi-3.0"?"items":"additionalItems",l=s.items.map((m,h)=>en(m,t,{...n,path:[...n.path,i,h]})),c=s.rest?en(s.rest,t,{...n,path:[...n.path,a,...t.target==="openapi-3.0"?[s.items.length]:[]]}):null;t.target==="draft-2020-12"?(o.prefixItems=l,c&&(o.items=c)):t.target==="openapi-3.0"?(o.items={anyOf:l},c&&o.items.anyOf.push(c),o.minItems=l.length,c||(o.maxItems=l.length)):(o.items=l,c&&(o.additionalItems=c));const{minimum:u,maximum:d}=e._zod.bag;typeof u=="number"&&(o.minItems=u),typeof d=="number"&&(o.maxItems=d)},bB=(e,t,r,n)=>{const o=r,s=e._zod.def;o.type="object";const i=s.keyType,l=i._zod.bag?.patterns;if(s.mode==="loose"&&l&&l.size>0){const u=en(s.valueType,t,{...n,path:[...n.path,"patternProperties","*"]});o.patternProperties={};for(const d of l)o.patternProperties[d.source]=u}else(t.target==="draft-07"||t.target==="draft-2020-12")&&(o.propertyNames=en(s.keyType,t,{...n,path:[...n.path,"propertyNames"]})),o.additionalProperties=en(s.valueType,t,{...n,path:[...n.path,"additionalProperties"]});const c=i._zod.values;if(c){const u=[...c].filter(d=>typeof d=="string"||typeof d=="number");u.length>0&&(o.required=u)}},TB=(e,t,r,n)=>{const o=e._zod.def,s=en(o.innerType,t,n),i=t.seen.get(e);t.target==="openapi-3.0"?(i.ref=o.innerType,r.nullable=!0):r.anyOf=[s,{type:"null"}]},EB=(e,t,r,n)=>{const o=e._zod.def;en(o.innerType,t,n);const s=t.seen.get(e);s.ref=o.innerType},SB=(e,t,r,n)=>{const o=e._zod.def;en(o.innerType,t,n);const s=t.seen.get(e);s.ref=o.innerType,r.default=JSON.parse(JSON.stringify(o.defaultValue))},CB=(e,t,r,n)=>{const o=e._zod.def;en(o.innerType,t,n);const s=t.seen.get(e);s.ref=o.innerType,t.io==="input"&&(r._prefault=JSON.parse(JSON.stringify(o.defaultValue)))},kB=(e,t,r,n)=>{const o=e._zod.def;en(o.innerType,t,n);const s=t.seen.get(e);s.ref=o.innerType;let i;try{i=o.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}r.default=i},xB=(e,t,r,n)=>{const o=e._zod.def,s=t.io==="input"?o.in._zod.def.type==="transform"?o.out:o.in:o.out;en(s,t,n);const i=t.seen.get(e);i.ref=s},AB=(e,t,r,n)=>{const o=e._zod.def;en(o.innerType,t,n);const s=t.seen.get(e);s.ref=o.innerType,r.readOnly=!0},IB=(e,t,r,n)=>{const o=e._zod.def;en(o.innerType,t,n);const s=t.seen.get(e);s.ref=o.innerType},zR=(e,t,r,n)=>{const o=e._zod.def;en(o.innerType,t,n);const s=t.seen.get(e);s.ref=o.innerType},RB=(e,t,r,n)=>{const o=e._zod.innerType;en(o,t,n);const s=t.seen.get(e);s.ref=o},jR={string:K5,number:J5,boolean:Y5,bigint:Z5,symbol:X5,null:Q5,undefined:eB,void:tB,never:rB,any:nB,unknown:oB,date:sB,enum:iB,literal:aB,nan:lB,template_literal:cB,file:uB,success:dB,custom:pB,function:mB,transform:hB,map:fB,set:gB,array:yB,object:vB,union:BR,intersection:_B,tuple:wB,record:bB,nullable:TB,nonoptional:EB,default:SB,prefault:CB,catch:kB,pipe:xB,readonly:AB,promise:IB,optional:zR,lazy:RB}}}),Dge,byr=S({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/json-schema-generator.js"(){bT(),UR(),Dge=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(e){this.ctx.counter=e}get seen(){return this.ctx.seen}constructor(e){let t=e?.target??"draft-2020-12";t==="draft-4"&&(t="draft-04"),t==="draft-7"&&(t="draft-07"),this.ctx=Tv({processors:jR,target:t,...e?.metadata&&{metadata:e.metadata},...e?.unrepresentable&&{unrepresentable:e.unrepresentable},...e?.override&&{override:e.override},...e?.io&&{io:e.io}})}process(e,t={path:[],schemaPath:[]}){return en(e,this.ctx,t)}emit(e,t){t&&(t.cycles&&(this.ctx.cycles=t.cycles),t.reused&&(this.ctx.reused=t.reused),t.external&&(this.ctx.external=t.external)),Ev(this.ctx,e);const r=Sv(this.ctx,e),{"~standard":n,...o}=r;return o}}}}),Tyr={},Eyr=S({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/json-schema.js"(){}}),Oge={};he(Oge,{$ZodAny:()=>L6,$ZodArray:()=>z6,$ZodAsyncError:()=>pm,$ZodBase64:()=>k6,$ZodBase64URL:()=>x6,$ZodBigInt:()=>wR,$ZodBigIntFormat:()=>P6,$ZodBoolean:()=>_R,$ZodCIDRv4:()=>S6,$ZodCIDRv6:()=>C6,$ZodCUID:()=>p6,$ZodCUID2:()=>m6,$ZodCatch:()=>i5,$ZodCheck:()=>Tn,$ZodCheckBigIntFormat:()=>UU,$ZodCheckEndsWith:()=>ZU,$ZodCheckGreaterThan:()=>pR,$ZodCheckIncludes:()=>JU,$ZodCheckLengthEquals:()=>HU,$ZodCheckLessThan:()=>dR,$ZodCheckLowerCase:()=>WU,$ZodCheckMaxLength:()=>qU,$ZodCheckMaxSize:()=>BU,$ZodCheckMimeType:()=>QU,$ZodCheckMinLength:()=>GU,$ZodCheckMinSize:()=>zU,$ZodCheckMultipleOf:()=>$U,$ZodCheckNumberFormat:()=>FU,$ZodCheckOverwrite:()=>e6,$ZodCheckProperty:()=>XU,$ZodCheckRegex:()=>VU,$ZodCheckSizeEquals:()=>jU,$ZodCheckStartsWith:()=>YU,$ZodCheckStringFormat:()=>gv,$ZodCheckUpperCase:()=>KU,$ZodCodec:()=>ER,$ZodCustom:()=>h5,$ZodCustomStringFormat:()=>R6,$ZodDate:()=>B6,$ZodDefault:()=>r5,$ZodDiscriminatedUnion:()=>H6,$ZodE164:()=>A6,$ZodEmail:()=>l6,$ZodEmoji:()=>u6,$ZodEncodeError:()=>aT,$ZodEnum:()=>Y6,$ZodError:()=>ZI,$ZodExactOptional:()=>e5,$ZodFile:()=>X6,$ZodFunction:()=>d5,$ZodGUID:()=>i6,$ZodIPv4:()=>b6,$ZodIPv6:()=>T6,$ZodISODate:()=>v6,$ZodISODateTime:()=>y6,$ZodISODuration:()=>w6,$ZodISOTime:()=>_6,$ZodIntersection:()=>V6,$ZodJWT:()=>I6,$ZodKSUID:()=>g6,$ZodLazy:()=>m5,$ZodLiteral:()=>Z6,$ZodMAC:()=>E6,$ZodMap:()=>K6,$ZodNaN:()=>a5,$ZodNanoID:()=>d6,$ZodNever:()=>F6,$ZodNonOptional:()=>o5,$ZodNull:()=>N6,$ZodNullable:()=>t5,$ZodNumber:()=>vR,$ZodNumberFormat:()=>M6,$ZodObject:()=>j6,$ZodObjectJIT:()=>q6,$ZodOptional:()=>TR,$ZodPipe:()=>l5,$ZodPrefault:()=>n5,$ZodPromise:()=>p5,$ZodReadonly:()=>c5,$ZodRealError:()=>Fa,$ZodRecord:()=>W6,$ZodRegistry:()=>w5,$ZodSet:()=>J6,$ZodString:()=>yv,$ZodStringFormat:()=>Qr,$ZodSuccess:()=>s5,$ZodSymbol:()=>D6,$ZodTemplateLiteral:()=>u5,$ZodTransform:()=>Q6,$ZodTuple:()=>bR,$ZodType:()=>Kt,$ZodULID:()=>h6,$ZodURL:()=>c6,$ZodUUID:()=>a6,$ZodUndefined:()=>O6,$ZodUnion:()=>fT,$ZodUnknown:()=>$6,$ZodVoid:()=>U6,$ZodXID:()=>f6,$ZodXor:()=>G6,$brand:()=>Y3,$constructor:()=>be,$input:()=>_5,$output:()=>v5,Doc:()=>r6,JSONSchema:()=>Tyr,JSONSchemaGenerator:()=>Dge,NEVER:()=>GI,TimePrecision:()=>V5,_any:()=>gge,_array:()=>Ege,_base64:()=>$5,_base64url:()=>F5,_bigint:()=>cge,_boolean:()=>age,_catch:()=>hyr,_check:()=>Age,_cidrv4:()=>N5,_cidrv6:()=>L5,_coercedBigint:()=>uge,_coercedBoolean:()=>lge,_coercedDate:()=>bge,_coercedNumber:()=>tge,_coercedString:()=>Kfe,_cuid:()=>A5,_cuid2:()=>I5,_custom:()=>Cge,_date:()=>wge,_decode:()=>rR,_decodeAsync:()=>oR,_default:()=>dyr,_discriminatedUnion:()=>Qgr,_e164:()=>U5,_email:()=>b5,_emoji:()=>k5,_encode:()=>tR,_encodeAsync:()=>nR,_endsWith:()=>PR,_enum:()=>syr,_file:()=>Sge,_float32:()=>nge,_float64:()=>oge,_gt:()=>fm,_gte:()=>Ua,_guid:()=>CR,_includes:()=>RR,_int:()=>rge,_int32:()=>sge,_int64:()=>dge,_intersection:()=>eyr,_ipv4:()=>D5,_ipv6:()=>O5,_isoDate:()=>Zfe,_isoDateTime:()=>Yfe,_isoDuration:()=>Qfe,_isoTime:()=>Xfe,_jwt:()=>B5,_ksuid:()=>P5,_lazy:()=>vyr,_length:()=>vT,_literal:()=>ayr,_lowercase:()=>AR,_lt:()=>hm,_lte:()=>sc,_mac:()=>Jfe,_map:()=>nyr,_max:()=>sc,_maxLength:()=>yT,_maxSize:()=>bv,_mime:()=>DR,_min:()=>Ua,_minLength:()=>lf,_minSize:()=>gm,_multipleOf:()=>wv,_nan:()=>Tge,_nanoid:()=>x5,_nativeEnum:()=>iyr,_negative:()=>j5,_never:()=>vge,_nonnegative:()=>G5,_nonoptional:()=>pyr,_nonpositive:()=>q5,_normalize:()=>OR,_null:()=>fge,_nullable:()=>uyr,_number:()=>ege,_optional:()=>cyr,_overwrite:()=>Fd,_parse:()=>pv,_parseAsync:()=>mv,_pipe:()=>fyr,_positive:()=>z5,_promise:()=>_yr,_property:()=>H5,_readonly:()=>gyr,_record:()=>ryr,_refine:()=>kge,_regex:()=>xR,_safeDecode:()=>iR,_safeDecodeAsync:()=>lR,_safeEncode:()=>sR,_safeEncodeAsync:()=>aR,_safeParse:()=>hv,_safeParseAsync:()=>fv,_set:()=>oyr,_size:()=>gT,_slugify:()=>FR,_startsWith:()=>MR,_string:()=>Wfe,_stringFormat:()=>_T,_stringbool:()=>Mge,_success:()=>myr,_superRefine:()=>xge,_symbol:()=>mge,_templateLiteral:()=>yyr,_toLowerCase:()=>LR,_toUpperCase:()=>$R,_transform:()=>lyr,_trim:()=>NR,_tuple:()=>tyr,_uint32:()=>ige,_uint64:()=>pge,_ulid:()=>R5,_undefined:()=>hge,_union:()=>Zgr,_unknown:()=>yge,_uppercase:()=>IR,_url:()=>kR,_uuid:()=>T5,_uuidv4:()=>E5,_uuidv6:()=>S5,_uuidv7:()=>C5,_void:()=>_ge,_xid:()=>M5,_xor:()=>Xgr,clone:()=>nc,config:()=>qi,createStandardJSONSchemaMethod:()=>Cv,createToJSONSchemaMethod:()=>W5,decode:()=>Ume,decodeAsync:()=>zme,describe:()=>Ige,encode:()=>Fme,encodeAsync:()=>Bme,extractDefs:()=>Ev,finalize:()=>Sv,flattenError:()=>oU,formatError:()=>sU,globalConfig:()=>lT,globalRegistry:()=>vl,initializeContext:()=>Tv,isValidBase64:()=>o6,isValidBase64URL:()=>xhe,isValidJWT:()=>Ahe,locales:()=>f5,meta:()=>Rge,parse:()=>XI,parseAsync:()=>QI,prettifyError:()=>Lme,process:()=>en,regexes:()=>sf,registry:()=>y5,safeDecode:()=>qme,safeDecodeAsync:()=>Hme,safeEncode:()=>jme,safeEncodeAsync:()=>Gme,safeParse:()=>eR,safeParseAsync:()=>aU,toDotPath:()=>Nme,toJSONSchema:()=>wT,treeifyError:()=>Ome,util:()=>_r,version:()=>n6});var cs=S({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/index.js"(){cT(),Vme(),$me(),jhe(),t6(),khe(),kt(),NU(),g5(),SR(),Che(),wyr(),UR(),bT(),byr(),Eyr()}}),Nge={};he(Nge,{endsWith:()=>PR,gt:()=>fm,gte:()=>Ua,includes:()=>RR,length:()=>vT,lowercase:()=>AR,lt:()=>hm,lte:()=>sc,maxLength:()=>yT,maxSize:()=>bv,mime:()=>DR,minLength:()=>lf,minSize:()=>gm,multipleOf:()=>wv,negative:()=>j5,nonnegative:()=>G5,nonpositive:()=>q5,normalize:()=>OR,overwrite:()=>Fd,positive:()=>z5,property:()=>H5,regex:()=>xR,size:()=>gT,slugify:()=>FR,startsWith:()=>MR,toLowerCase:()=>LR,toUpperCase:()=>$R,trim:()=>NR,uppercase:()=>IR});var MB=S({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/checks.js"(){cs()}}),qR={};he(qR,{ZodISODate:()=>HR,ZodISODateTime:()=>GR,ZodISODuration:()=>WR,ZodISOTime:()=>VR,date:()=>$ge,datetime:()=>Lge,duration:()=>Uge,time:()=>Fge});function Lge(e){return Yfe(GR,e)}function $ge(e){return Zfe(HR,e)}function Fge(e){return Xfe(VR,e)}function Uge(e){return Qfe(WR,e)}var GR,HR,VR,WR,KR=S({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/iso.js"(){cs(),P1(),GR=be("ZodISODateTime",(e,t)=>{y6.init(e,t),nn.init(e,t)}),HR=be("ZodISODate",(e,t)=>{v6.init(e,t),nn.init(e,t)}),VR=be("ZodISOTime",(e,t)=>{_6.init(e,t),nn.init(e,t)}),WR=be("ZodISODuration",(e,t)=>{w6.init(e,t),nn.init(e,t)})}}),PB,Bge,Ba,zge=S({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/errors.js"(){cs(),cs(),kt(),PB=(e,t)=>{ZI.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:r=>sU(e,r)},flatten:{value:r=>oU(e,r)},addIssue:{value:r=>{e.issues.push(r),e.message=JSON.stringify(e.issues,HI,2)}},addIssues:{value:r=>{e.issues.push(...r),e.message=JSON.stringify(e.issues,HI,2)}},isEmpty:{get(){return e.issues.length===0}}})},Bge=be("ZodError",PB),Ba=be("ZodError",PB,{Parent:Error})}}),DB,OB,NB,JR,LB,$B,FB,UB,BB,zB,jB,qB,jge=S({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/parse.js"(){cs(),zge(),DB=pv(Ba),OB=mv(Ba),NB=hv(Ba),JR=fv(Ba),LB=tR(Ba),$B=rR(Ba),FB=nR(Ba),UB=oR(Ba),BB=sR(Ba),zB=iR(Ba),jB=aR(Ba),qB=lR(Ba)}}),qge={};he(qge,{ZodAny:()=>i1,ZodArray:()=>u1,ZodBase64:()=>UT,ZodBase64URL:()=>BT,ZodBigInt:()=>Mv,ZodBigIntFormat:()=>qT,ZodBoolean:()=>Rv,ZodCIDRv4:()=>$T,ZodCIDRv6:()=>FT,ZodCUID:()=>RT,ZodCUID2:()=>MT,ZodCatch:()=>C1,ZodCodec:()=>KT,ZodCustom:()=>Nv,ZodCustomStringFormat:()=>cf,ZodDate:()=>GT,ZodDefault:()=>T1,ZodDiscriminatedUnion:()=>p1,ZodE164:()=>zT,ZodEmail:()=>xT,ZodEmoji:()=>AT,ZodEnum:()=>uf,ZodExactOptional:()=>w1,ZodFile:()=>v1,ZodFunction:()=>M1,ZodGUID:()=>xv,ZodIPv4:()=>NT,ZodIPv6:()=>LT,ZodIntersection:()=>m1,ZodJWT:()=>jT,ZodKSUID:()=>OT,ZodLazy:()=>I1,ZodLiteral:()=>y1,ZodMAC:()=>r1,ZodMap:()=>f1,ZodNaN:()=>k1,ZodNanoID:()=>IT,ZodNever:()=>l1,ZodNonOptional:()=>VT,ZodNull:()=>s1,ZodNullable:()=>b1,ZodNumber:()=>Iv,ZodNumberFormat:()=>ym,ZodObject:()=>Pv,ZodOptional:()=>HT,ZodPipe:()=>WT,ZodPrefault:()=>E1,ZodPromise:()=>R1,ZodReadonly:()=>x1,ZodRecord:()=>Ov,ZodSet:()=>g1,ZodString:()=>kv,ZodStringFormat:()=>nn,ZodSuccess:()=>S1,ZodSymbol:()=>n1,ZodTemplateLiteral:()=>A1,ZodTransform:()=>_1,ZodTuple:()=>h1,ZodType:()=>Qt,ZodULID:()=>PT,ZodURL:()=>Av,ZodUUID:()=>Vc,ZodUndefined:()=>o1,ZodUnion:()=>Dv,ZodUnknown:()=>a1,ZodVoid:()=>c1,ZodXID:()=>DT,ZodXor:()=>d1,_ZodString:()=>kT,_default:()=>KB,_function:()=>e1,any:()=>HB,array:()=>rt,base64:()=>cye,base64url:()=>uye,bigint:()=>bye,boolean:()=>tn,catch:()=>ZB,check:()=>qye,cidrv4:()=>aye,cidrv6:()=>lye,codec:()=>Bye,cuid:()=>Qge,cuid2:()=>eye,custom:()=>ez,date:()=>xye,describe:()=>nz,discriminatedUnion:()=>XR,e164:()=>dye,email:()=>Gge,emoji:()=>Zge,enum:()=>Gi,exactOptional:()=>WB,file:()=>Lye,float32:()=>yye,float64:()=>vye,function:()=>e1,guid:()=>Hge,hash:()=>gye,hex:()=>fye,hostname:()=>hye,httpUrl:()=>Yge,instanceof:()=>Gye,int:()=>YR,int32:()=>_ye,int64:()=>Tye,intersection:()=>ET,ipv4:()=>oye,ipv6:()=>iye,json:()=>Hye,jwt:()=>pye,keyof:()=>Aye,ksuid:()=>nye,lazy:()=>QB,literal:()=>Tt,looseObject:()=>Ns,looseRecord:()=>Pye,mac:()=>sye,map:()=>Dye,meta:()=>oz,nan:()=>Uye,nanoid:()=>Xge,nativeEnum:()=>Nye,never:()=>ZR,nonoptional:()=>YB,null:()=>TT,nullable:()=>ST,nullish:()=>$ye,number:()=>Rr,object:()=>ot,optional:()=>En,partialRecord:()=>Mye,pipe:()=>CT,prefault:()=>JB,preprocess:()=>t1,promise:()=>jye,readonly:()=>XB,record:()=>gn,refine:()=>tz,set:()=>Oye,strictObject:()=>Iye,string:()=>ce,stringFormat:()=>mye,stringbool:()=>sz,success:()=>Fye,superRefine:()=>rz,symbol:()=>Sye,templateLiteral:()=>zye,transform:()=>QR,tuple:()=>VB,uint32:()=>wye,uint64:()=>Eye,ulid:()=>tye,undefined:()=>Cye,union:()=>rn,unknown:()=>un,url:()=>GB,uuid:()=>Vge,uuidv4:()=>Wge,uuidv6:()=>Kge,uuidv7:()=>Jge,void:()=>kye,xid:()=>rye,xor:()=>Rye});function ce(e){return Wfe(kv,e)}function Gge(e){return b5(xT,e)}function Hge(e){return CR(xv,e)}function Vge(e){return T5(Vc,e)}function Wge(e){return E5(Vc,e)}function Kge(e){return S5(Vc,e)}function Jge(e){return C5(Vc,e)}function GB(e){return kR(Av,e)}function Yge(e){return kR(Av,{protocol:/^https?$/,hostname:sf.domain,..._r.normalizeParams(e)})}function Zge(e){return k5(AT,e)}function Xge(e){return x5(IT,e)}function Qge(e){return A5(RT,e)}function eye(e){return I5(MT,e)}function tye(e){return R5(PT,e)}function rye(e){return M5(DT,e)}function nye(e){return P5(OT,e)}function oye(e){return D5(NT,e)}function sye(e){return Jfe(r1,e)}function iye(e){return O5(LT,e)}function aye(e){return N5($T,e)}function lye(e){return L5(FT,e)}function cye(e){return $5(UT,e)}function uye(e){return F5(BT,e)}function dye(e){return U5(zT,e)}function pye(e){return B5(jT,e)}function mye(e,t,r={}){return _T(cf,e,t,r)}function hye(e){return _T(cf,"hostname",sf.hostname,e)}function fye(e){return _T(cf,"hex",sf.hex,e)}function gye(e,t){const r=t?.enc??"hex",n=`${e}_${r}`,o=sf[n];if(!o)throw new Error(`Unrecognized hash format: ${n}`);return _T(cf,n,o,t)}function Rr(e){return ege(Iv,e)}function YR(e){return rge(ym,e)}function yye(e){return nge(ym,e)}function vye(e){return oge(ym,e)}function _ye(e){return sge(ym,e)}function wye(e){return ige(ym,e)}function tn(e){return age(Rv,e)}function bye(e){return cge(Mv,e)}function Tye(e){return dge(qT,e)}function Eye(e){return pge(qT,e)}function Sye(e){return mge(n1,e)}function Cye(e){return hge(o1,e)}function TT(e){return fge(s1,e)}function HB(){return gge(i1)}function un(){return yge(a1)}function ZR(e){return vge(l1,e)}function kye(e){return _ge(c1,e)}function xye(e){return wge(GT,e)}function rt(e,t){return Ege(u1,e,t)}function Aye(e){const t=e._zod.def.shape;return Gi(Object.keys(t))}function ot(e,t){const r={type:"object",shape:e??{},..._r.normalizeParams(t)};return new Pv(r)}function Iye(e,t){return new Pv({type:"object",shape:e,catchall:ZR(),..._r.normalizeParams(t)})}function Ns(e,t){return new Pv({type:"object",shape:e,catchall:un(),..._r.normalizeParams(t)})}function rn(e,t){return new Dv({type:"union",options:e,..._r.normalizeParams(t)})}function Rye(e,t){return new d1({type:"union",options:e,inclusive:!1,..._r.normalizeParams(t)})}function XR(e,t,r){return new p1({type:"union",options:t,discriminator:e,..._r.normalizeParams(r)})}function ET(e,t){return new m1({type:"intersection",left:e,right:t})}function VB(e,t,r){const n=t instanceof Kt,o=n?r:t,s=n?t:null;return new h1({type:"tuple",items:e,rest:s,..._r.normalizeParams(o)})}function gn(e,t,r){return new Ov({type:"record",keyType:e,valueType:t,..._r.normalizeParams(r)})}function Mye(e,t,r){const n=nc(e);return n._zod.values=void 0,new Ov({type:"record",keyType:n,valueType:t,..._r.normalizeParams(r)})}function Pye(e,t,r){return new Ov({type:"record",keyType:e,valueType:t,mode:"loose",..._r.normalizeParams(r)})}function Dye(e,t,r){return new f1({type:"map",keyType:e,valueType:t,..._r.normalizeParams(r)})}function Oye(e,t){return new g1({type:"set",valueType:e,..._r.normalizeParams(t)})}function Gi(e,t){const r=Array.isArray(e)?Object.fromEntries(e.map(n=>[n,n])):e;return new uf({type:"enum",entries:r,..._r.normalizeParams(t)})}function Nye(e,t){return new uf({type:"enum",entries:e,..._r.normalizeParams(t)})}function Tt(e,t){return new y1({type:"literal",values:Array.isArray(e)?e:[e],..._r.normalizeParams(t)})}function Lye(e){return Sge(v1,e)}function QR(e){return new _1({type:"transform",transform:e})}function En(e){return new HT({type:"optional",innerType:e})}function WB(e){return new w1({type:"optional",innerType:e})}function ST(e){return new b1({type:"nullable",innerType:e})}function $ye(e){return En(ST(e))}function KB(e,t){return new T1({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():_r.shallowClone(t)}})}function JB(e,t){return new E1({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():_r.shallowClone(t)}})}function YB(e,t){return new VT({type:"nonoptional",innerType:e,..._r.normalizeParams(t)})}function Fye(e){return new S1({type:"success",innerType:e})}function ZB(e,t){return new C1({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}function Uye(e){return Tge(k1,e)}function CT(e,t){return new WT({type:"pipe",in:e,out:t})}function Bye(e,t,r){return new KT({type:"pipe",in:e,out:t,transform:r.decode,reverseTransform:r.encode})}function XB(e){return new x1({type:"readonly",innerType:e})}function zye(e,t){return new A1({type:"template_literal",parts:e,..._r.normalizeParams(t)})}function QB(e){return new I1({type:"lazy",getter:e})}function jye(e){return new R1({type:"promise",innerType:e})}function e1(e){return new M1({type:"function",input:Array.isArray(e?.input)?VB(e?.input):e?.input??rt(un()),output:e?.output??un()})}function qye(e){const t=new Tn({check:"custom"});return t._zod.check=e,t}function ez(e,t){return Cge(Nv,e??(()=>!0),t)}function tz(e,t={}){return kge(Nv,e,t)}function rz(e){return xge(e)}function Gye(e,t={}){const r=new Nv({type:"custom",check:"custom",fn:n=>n instanceof e,abort:!0,..._r.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 Hye(e){const t=QB(()=>rn([ce(e),Rr(),tn(),TT(),rt(t),gn(ce(),t)]));return t}function t1(e,t){return CT(QR(e),t)}var Qt,kT,kv,nn,xT,xv,Vc,Av,AT,IT,RT,MT,PT,DT,OT,NT,r1,LT,$T,FT,UT,BT,zT,jT,cf,Iv,ym,Rv,Mv,qT,n1,o1,s1,i1,a1,l1,c1,GT,u1,Pv,Dv,d1,p1,m1,h1,Ov,f1,g1,uf,y1,v1,_1,HT,w1,b1,T1,E1,VT,S1,C1,k1,WT,KT,x1,A1,I1,R1,M1,Nv,nz,oz,sz,P1=S({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/schemas.js"(){cs(),cs(),bT(),UR(),MB(),KR(),jge(),Qt=be("ZodType",(e,t)=>(Kt.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:Cv(e,"input"),output:Cv(e,"output")}}),e.toJSONSchema=W5(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.check=(...r)=>e.clone(_r.mergeDefs(t,{checks:[...t.checks??[],...r.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),{parent:!0}),e.with=e.check,e.clone=(r,n)=>nc(e,r,n),e.brand=()=>e,e.register=((r,n)=>(r.add(e,n),e)),e.parse=(r,n)=>DB(e,r,n,{callee:e.parse}),e.safeParse=(r,n)=>NB(e,r,n),e.parseAsync=async(r,n)=>OB(e,r,n,{callee:e.parseAsync}),e.safeParseAsync=async(r,n)=>JR(e,r,n),e.spa=e.safeParseAsync,e.encode=(r,n)=>LB(e,r,n),e.decode=(r,n)=>$B(e,r,n),e.encodeAsync=async(r,n)=>FB(e,r,n),e.decodeAsync=async(r,n)=>UB(e,r,n),e.safeEncode=(r,n)=>BB(e,r,n),e.safeDecode=(r,n)=>zB(e,r,n),e.safeEncodeAsync=async(r,n)=>jB(e,r,n),e.safeDecodeAsync=async(r,n)=>qB(e,r,n),e.refine=(r,n)=>e.check(tz(r,n)),e.superRefine=r=>e.check(rz(r)),e.overwrite=r=>e.check(Fd(r)),e.optional=()=>En(e),e.exactOptional=()=>WB(e),e.nullable=()=>ST(e),e.nullish=()=>En(ST(e)),e.nonoptional=r=>YB(e,r),e.array=()=>rt(e),e.or=r=>rn([e,r]),e.and=r=>ET(e,r),e.transform=r=>CT(e,QR(r)),e.default=r=>KB(e,r),e.prefault=r=>JB(e,r),e.catch=r=>ZB(e,r),e.pipe=r=>CT(e,r),e.readonly=()=>XB(e),e.describe=r=>{const n=e.clone();return vl.add(n,{description:r}),n},Object.defineProperty(e,"description",{get(){return vl.get(e)?.description},configurable:!0}),e.meta=(...r)=>{if(r.length===0)return vl.get(e);const n=e.clone();return vl.add(n,r[0]),n},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e.apply=r=>r(e),e)),kT=be("_ZodString",(e,t)=>{yv.init(e,t),Qt.init(e,t),e._zod.processJSONSchema=(n,o,s)=>K5(e,n,o,s);const r=e._zod.bag;e.format=r.format??null,e.minLength=r.minimum??null,e.maxLength=r.maximum??null,e.regex=(...n)=>e.check(xR(...n)),e.includes=(...n)=>e.check(RR(...n)),e.startsWith=(...n)=>e.check(MR(...n)),e.endsWith=(...n)=>e.check(PR(...n)),e.min=(...n)=>e.check(lf(...n)),e.max=(...n)=>e.check(yT(...n)),e.length=(...n)=>e.check(vT(...n)),e.nonempty=(...n)=>e.check(lf(1,...n)),e.lowercase=n=>e.check(AR(n)),e.uppercase=n=>e.check(IR(n)),e.trim=()=>e.check(NR()),e.normalize=(...n)=>e.check(OR(...n)),e.toLowerCase=()=>e.check(LR()),e.toUpperCase=()=>e.check($R()),e.slugify=()=>e.check(FR())}),kv=be("ZodString",(e,t)=>{yv.init(e,t),kT.init(e,t),e.email=r=>e.check(b5(xT,r)),e.url=r=>e.check(kR(Av,r)),e.jwt=r=>e.check(B5(jT,r)),e.emoji=r=>e.check(k5(AT,r)),e.guid=r=>e.check(CR(xv,r)),e.uuid=r=>e.check(T5(Vc,r)),e.uuidv4=r=>e.check(E5(Vc,r)),e.uuidv6=r=>e.check(S5(Vc,r)),e.uuidv7=r=>e.check(C5(Vc,r)),e.nanoid=r=>e.check(x5(IT,r)),e.guid=r=>e.check(CR(xv,r)),e.cuid=r=>e.check(A5(RT,r)),e.cuid2=r=>e.check(I5(MT,r)),e.ulid=r=>e.check(R5(PT,r)),e.base64=r=>e.check($5(UT,r)),e.base64url=r=>e.check(F5(BT,r)),e.xid=r=>e.check(M5(DT,r)),e.ksuid=r=>e.check(P5(OT,r)),e.ipv4=r=>e.check(D5(NT,r)),e.ipv6=r=>e.check(O5(LT,r)),e.cidrv4=r=>e.check(N5($T,r)),e.cidrv6=r=>e.check(L5(FT,r)),e.e164=r=>e.check(U5(zT,r)),e.datetime=r=>e.check(Lge(r)),e.date=r=>e.check($ge(r)),e.time=r=>e.check(Fge(r)),e.duration=r=>e.check(Uge(r))}),nn=be("ZodStringFormat",(e,t)=>{Qr.init(e,t),kT.init(e,t)}),xT=be("ZodEmail",(e,t)=>{l6.init(e,t),nn.init(e,t)}),xv=be("ZodGUID",(e,t)=>{i6.init(e,t),nn.init(e,t)}),Vc=be("ZodUUID",(e,t)=>{a6.init(e,t),nn.init(e,t)}),Av=be("ZodURL",(e,t)=>{c6.init(e,t),nn.init(e,t)}),AT=be("ZodEmoji",(e,t)=>{u6.init(e,t),nn.init(e,t)}),IT=be("ZodNanoID",(e,t)=>{d6.init(e,t),nn.init(e,t)}),RT=be("ZodCUID",(e,t)=>{p6.init(e,t),nn.init(e,t)}),MT=be("ZodCUID2",(e,t)=>{m6.init(e,t),nn.init(e,t)}),PT=be("ZodULID",(e,t)=>{h6.init(e,t),nn.init(e,t)}),DT=be("ZodXID",(e,t)=>{f6.init(e,t),nn.init(e,t)}),OT=be("ZodKSUID",(e,t)=>{g6.init(e,t),nn.init(e,t)}),NT=be("ZodIPv4",(e,t)=>{b6.init(e,t),nn.init(e,t)}),r1=be("ZodMAC",(e,t)=>{E6.init(e,t),nn.init(e,t)}),LT=be("ZodIPv6",(e,t)=>{T6.init(e,t),nn.init(e,t)}),$T=be("ZodCIDRv4",(e,t)=>{S6.init(e,t),nn.init(e,t)}),FT=be("ZodCIDRv6",(e,t)=>{C6.init(e,t),nn.init(e,t)}),UT=be("ZodBase64",(e,t)=>{k6.init(e,t),nn.init(e,t)}),BT=be("ZodBase64URL",(e,t)=>{x6.init(e,t),nn.init(e,t)}),zT=be("ZodE164",(e,t)=>{A6.init(e,t),nn.init(e,t)}),jT=be("ZodJWT",(e,t)=>{I6.init(e,t),nn.init(e,t)}),cf=be("ZodCustomStringFormat",(e,t)=>{R6.init(e,t),nn.init(e,t)}),Iv=be("ZodNumber",(e,t)=>{vR.init(e,t),Qt.init(e,t),e._zod.processJSONSchema=(n,o,s)=>J5(e,n,o,s),e.gt=(n,o)=>e.check(fm(n,o)),e.gte=(n,o)=>e.check(Ua(n,o)),e.min=(n,o)=>e.check(Ua(n,o)),e.lt=(n,o)=>e.check(hm(n,o)),e.lte=(n,o)=>e.check(sc(n,o)),e.max=(n,o)=>e.check(sc(n,o)),e.int=n=>e.check(YR(n)),e.safe=n=>e.check(YR(n)),e.positive=n=>e.check(fm(0,n)),e.nonnegative=n=>e.check(Ua(0,n)),e.negative=n=>e.check(hm(0,n)),e.nonpositive=n=>e.check(sc(0,n)),e.multipleOf=(n,o)=>e.check(wv(n,o)),e.step=(n,o)=>e.check(wv(n,o)),e.finite=()=>e;const r=e._zod.bag;e.minValue=Math.max(r.minimum??Number.NEGATIVE_INFINITY,r.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(r.maximum??Number.POSITIVE_INFINITY,r.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(r.format??"").includes("int")||Number.isSafeInteger(r.multipleOf??.5),e.isFinite=!0,e.format=r.format??null}),ym=be("ZodNumberFormat",(e,t)=>{M6.init(e,t),Iv.init(e,t)}),Rv=be("ZodBoolean",(e,t)=>{_R.init(e,t),Qt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Y5(e,r,n,o)}),Mv=be("ZodBigInt",(e,t)=>{wR.init(e,t),Qt.init(e,t),e._zod.processJSONSchema=(n,o,s)=>Z5(e,n,o,s),e.gte=(n,o)=>e.check(Ua(n,o)),e.min=(n,o)=>e.check(Ua(n,o)),e.gt=(n,o)=>e.check(fm(n,o)),e.gte=(n,o)=>e.check(Ua(n,o)),e.min=(n,o)=>e.check(Ua(n,o)),e.lt=(n,o)=>e.check(hm(n,o)),e.lte=(n,o)=>e.check(sc(n,o)),e.max=(n,o)=>e.check(sc(n,o)),e.positive=n=>e.check(fm(BigInt(0),n)),e.negative=n=>e.check(hm(BigInt(0),n)),e.nonpositive=n=>e.check(sc(BigInt(0),n)),e.nonnegative=n=>e.check(Ua(BigInt(0),n)),e.multipleOf=(n,o)=>e.check(wv(n,o));const r=e._zod.bag;e.minValue=r.minimum??null,e.maxValue=r.maximum??null,e.format=r.format??null}),qT=be("ZodBigIntFormat",(e,t)=>{P6.init(e,t),Mv.init(e,t)}),n1=be("ZodSymbol",(e,t)=>{D6.init(e,t),Qt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>X5(e,r,n,o)}),o1=be("ZodUndefined",(e,t)=>{O6.init(e,t),Qt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>eB(e,r,n,o)}),s1=be("ZodNull",(e,t)=>{N6.init(e,t),Qt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Q5(e,r,n,o)}),i1=be("ZodAny",(e,t)=>{L6.init(e,t),Qt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>nB(e,r,n,o)}),a1=be("ZodUnknown",(e,t)=>{$6.init(e,t),Qt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>oB(e,r,n,o)}),l1=be("ZodNever",(e,t)=>{F6.init(e,t),Qt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>rB(e,r,n,o)}),c1=be("ZodVoid",(e,t)=>{U6.init(e,t),Qt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>tB(e,r,n,o)}),GT=be("ZodDate",(e,t)=>{B6.init(e,t),Qt.init(e,t),e._zod.processJSONSchema=(n,o,s)=>sB(e,n,o,s),e.min=(n,o)=>e.check(Ua(n,o)),e.max=(n,o)=>e.check(sc(n,o));const r=e._zod.bag;e.minDate=r.minimum?new Date(r.minimum):null,e.maxDate=r.maximum?new Date(r.maximum):null}),u1=be("ZodArray",(e,t)=>{z6.init(e,t),Qt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>yB(e,r,n,o),e.element=t.element,e.min=(r,n)=>e.check(lf(r,n)),e.nonempty=r=>e.check(lf(1,r)),e.max=(r,n)=>e.check(yT(r,n)),e.length=(r,n)=>e.check(vT(r,n)),e.unwrap=()=>e.element}),Pv=be("ZodObject",(e,t)=>{q6.init(e,t),Qt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>vB(e,r,n,o),_r.defineLazy(e,"shape",()=>t.shape),e.keyof=()=>Gi(Object.keys(e._zod.def.shape)),e.catchall=r=>e.clone({...e._zod.def,catchall:r}),e.passthrough=()=>e.clone({...e._zod.def,catchall:un()}),e.loose=()=>e.clone({...e._zod.def,catchall:un()}),e.strict=()=>e.clone({...e._zod.def,catchall:ZR()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=r=>_r.extend(e,r),e.safeExtend=r=>_r.safeExtend(e,r),e.merge=r=>_r.merge(e,r),e.pick=r=>_r.pick(e,r),e.omit=r=>_r.omit(e,r),e.partial=(...r)=>_r.partial(HT,e,r[0]),e.required=(...r)=>_r.required(VT,e,r[0])}),Dv=be("ZodUnion",(e,t)=>{fT.init(e,t),Qt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>BR(e,r,n,o),e.options=t.options}),d1=be("ZodXor",(e,t)=>{Dv.init(e,t),G6.init(e,t),e._zod.processJSONSchema=(r,n,o)=>BR(e,r,n,o),e.options=t.options}),p1=be("ZodDiscriminatedUnion",(e,t)=>{Dv.init(e,t),H6.init(e,t)}),m1=be("ZodIntersection",(e,t)=>{V6.init(e,t),Qt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>_B(e,r,n,o)}),h1=be("ZodTuple",(e,t)=>{bR.init(e,t),Qt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>wB(e,r,n,o),e.rest=r=>e.clone({...e._zod.def,rest:r})}),Ov=be("ZodRecord",(e,t)=>{W6.init(e,t),Qt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>bB(e,r,n,o),e.keyType=t.keyType,e.valueType=t.valueType}),f1=be("ZodMap",(e,t)=>{K6.init(e,t),Qt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>fB(e,r,n,o),e.keyType=t.keyType,e.valueType=t.valueType,e.min=(...r)=>e.check(gm(...r)),e.nonempty=r=>e.check(gm(1,r)),e.max=(...r)=>e.check(bv(...r)),e.size=(...r)=>e.check(gT(...r))}),g1=be("ZodSet",(e,t)=>{J6.init(e,t),Qt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>gB(e,r,n,o),e.min=(...r)=>e.check(gm(...r)),e.nonempty=r=>e.check(gm(1,r)),e.max=(...r)=>e.check(bv(...r)),e.size=(...r)=>e.check(gT(...r))}),uf=be("ZodEnum",(e,t)=>{Y6.init(e,t),Qt.init(e,t),e._zod.processJSONSchema=(n,o,s)=>iB(e,n,o,s),e.enum=t.entries,e.options=Object.values(t.entries);const r=new Set(Object.keys(t.entries));e.extract=(n,o)=>{const s={};for(const i of n)if(r.has(i))s[i]=t.entries[i];else throw new Error(`Key ${i} not found in enum`);return new uf({...t,checks:[],..._r.normalizeParams(o),entries:s})},e.exclude=(n,o)=>{const s={...t.entries};for(const i of n)if(r.has(i))delete s[i];else throw new Error(`Key ${i} not found in enum`);return new uf({...t,checks:[],..._r.normalizeParams(o),entries:s})}}),y1=be("ZodLiteral",(e,t)=>{Z6.init(e,t),Qt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>aB(e,r,n,o),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]}})}),v1=be("ZodFile",(e,t)=>{X6.init(e,t),Qt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>uB(e,r,n,o),e.min=(r,n)=>e.check(gm(r,n)),e.max=(r,n)=>e.check(bv(r,n)),e.mime=(r,n)=>e.check(DR(Array.isArray(r)?r:[r],n))}),_1=be("ZodTransform",(e,t)=>{Q6.init(e,t),Qt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>hB(e,r,n,o),e._zod.parse=(r,n)=>{if(n.direction==="backward")throw new aT(e.constructor.name);r.addIssue=s=>{if(typeof s=="string")r.issues.push(_r.issue(s,r.value,t));else{const i=s;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),i.input??(i.input=r.value),i.inst??(i.inst=e),r.issues.push(_r.issue(i))}};const o=t.transform(r.value,r);return o instanceof Promise?o.then(s=>(r.value=s,r)):(r.value=o,r)}}),HT=be("ZodOptional",(e,t)=>{TR.init(e,t),Qt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>zR(e,r,n,o),e.unwrap=()=>e._zod.def.innerType}),w1=be("ZodExactOptional",(e,t)=>{e5.init(e,t),Qt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>zR(e,r,n,o),e.unwrap=()=>e._zod.def.innerType}),b1=be("ZodNullable",(e,t)=>{t5.init(e,t),Qt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>TB(e,r,n,o),e.unwrap=()=>e._zod.def.innerType}),T1=be("ZodDefault",(e,t)=>{r5.init(e,t),Qt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>SB(e,r,n,o),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap}),E1=be("ZodPrefault",(e,t)=>{n5.init(e,t),Qt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>CB(e,r,n,o),e.unwrap=()=>e._zod.def.innerType}),VT=be("ZodNonOptional",(e,t)=>{o5.init(e,t),Qt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>EB(e,r,n,o),e.unwrap=()=>e._zod.def.innerType}),S1=be("ZodSuccess",(e,t)=>{s5.init(e,t),Qt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>dB(e,r,n,o),e.unwrap=()=>e._zod.def.innerType}),C1=be("ZodCatch",(e,t)=>{i5.init(e,t),Qt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>kB(e,r,n,o),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap}),k1=be("ZodNaN",(e,t)=>{a5.init(e,t),Qt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>lB(e,r,n,o)}),WT=be("ZodPipe",(e,t)=>{l5.init(e,t),Qt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>xB(e,r,n,o),e.in=t.in,e.out=t.out}),KT=be("ZodCodec",(e,t)=>{WT.init(e,t),ER.init(e,t)}),x1=be("ZodReadonly",(e,t)=>{c5.init(e,t),Qt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>AB(e,r,n,o),e.unwrap=()=>e._zod.def.innerType}),A1=be("ZodTemplateLiteral",(e,t)=>{u5.init(e,t),Qt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>cB(e,r,n,o)}),I1=be("ZodLazy",(e,t)=>{m5.init(e,t),Qt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>RB(e,r,n,o),e.unwrap=()=>e._zod.def.getter()}),R1=be("ZodPromise",(e,t)=>{p5.init(e,t),Qt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>IB(e,r,n,o),e.unwrap=()=>e._zod.def.innerType}),M1=be("ZodFunction",(e,t)=>{d5.init(e,t),Qt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>mB(e,r,n,o)}),Nv=be("ZodCustom",(e,t)=>{h5.init(e,t),Qt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>pB(e,r,n,o)}),nz=Ige,oz=Rge,sz=(...e)=>Mge({Codec:KT,Boolean:Rv,String:kv},...e)}});function Syr(e){qi({customError:e})}function Cyr(){return qi().customError}var iz,az,kyr=S({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/compat.js"(){cs(),cs(),iz={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"},az||(az={})}});function xyr(e,t){const 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 Ayr(e,t){if(!e.startsWith("#"))throw new Error("External $ref is not supported, only local refs (#/...) are allowed");const r=e.slice(1).split("/").filter(Boolean);if(r.length===0)return t.rootSchema;const n=t.version==="draft-2020-12"?"$defs":"definitions";if(r[0]===n){const o=r[1];if(!o||!t.defs[o])throw new Error(`Reference not found: ${e}`);return t.defs[o]}throw new Error(`Reference not found: ${e}`)}function Vye(e,t){if(e.not!==void 0){if(typeof e.not=="object"&&Object.keys(e.not).length===0)return it.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){const o=e.$ref;if(t.refs.has(o))return t.refs.get(o);if(t.processing.has(o))return it.lazy(()=>{if(!t.refs.has(o))throw new Error(`Circular reference not resolved: ${o}`);return t.refs.get(o)});t.processing.add(o);const s=Ayr(o,t),i=Hi(s,t);return t.refs.set(o,i),t.processing.delete(o),i}if(e.enum!==void 0){const o=e.enum;if(t.version==="openapi-3.0"&&e.nullable===!0&&o.length===1&&o[0]===null)return it.null();if(o.length===0)return it.never();if(o.length===1)return it.literal(o[0]);if(o.every(i=>typeof i=="string"))return it.enum(o);const s=o.map(i=>it.literal(i));return s.length<2?s[0]:it.union([s[0],s[1],...s.slice(2)])}if(e.const!==void 0)return it.literal(e.const);const r=e.type;if(Array.isArray(r)){const o=r.map(s=>{const i={...e,type:s};return Vye(i,t)});return o.length===0?it.never():o.length===1?o[0]:it.union(o)}if(!r)return it.any();let n;switch(r){case"string":{let o=it.string();if(e.format){const s=e.format;s==="email"?o=o.check(it.email()):s==="uri"||s==="uri-reference"?o=o.check(it.url()):s==="uuid"||s==="guid"?o=o.check(it.uuid()):s==="date-time"?o=o.check(it.iso.datetime()):s==="date"?o=o.check(it.iso.date()):s==="time"?o=o.check(it.iso.time()):s==="duration"?o=o.check(it.iso.duration()):s==="ipv4"?o=o.check(it.ipv4()):s==="ipv6"?o=o.check(it.ipv6()):s==="mac"?o=o.check(it.mac()):s==="cidr"?o=o.check(it.cidrv4()):s==="cidr-v6"?o=o.check(it.cidrv6()):s==="base64"?o=o.check(it.base64()):s==="base64url"?o=o.check(it.base64url()):s==="e164"?o=o.check(it.e164()):s==="jwt"?o=o.check(it.jwt()):s==="emoji"?o=o.check(it.emoji()):s==="nanoid"?o=o.check(it.nanoid()):s==="cuid"?o=o.check(it.cuid()):s==="cuid2"?o=o.check(it.cuid2()):s==="ulid"?o=o.check(it.ulid()):s==="xid"?o=o.check(it.xid()):s==="ksuid"&&(o=o.check(it.ksuid()))}typeof e.minLength=="number"&&(o=o.min(e.minLength)),typeof e.maxLength=="number"&&(o=o.max(e.maxLength)),e.pattern&&(o=o.regex(new RegExp(e.pattern))),n=o;break}case"number":case"integer":{let o=r==="integer"?it.number().int():it.number();typeof e.minimum=="number"&&(o=o.min(e.minimum)),typeof e.maximum=="number"&&(o=o.max(e.maximum)),typeof e.exclusiveMinimum=="number"?o=o.gt(e.exclusiveMinimum):e.exclusiveMinimum===!0&&typeof e.minimum=="number"&&(o=o.gt(e.minimum)),typeof e.exclusiveMaximum=="number"?o=o.lt(e.exclusiveMaximum):e.exclusiveMaximum===!0&&typeof e.maximum=="number"&&(o=o.lt(e.maximum)),typeof e.multipleOf=="number"&&(o=o.multipleOf(e.multipleOf)),n=o;break}case"boolean":{n=it.boolean();break}case"null":{n=it.null();break}case"object":{const o={},s=e.properties||{},i=new Set(e.required||[]);for(const[l,c]of Object.entries(s)){const u=Hi(c,t);o[l]=i.has(l)?u:u.optional()}if(e.propertyNames){const l=Hi(e.propertyNames,t),c=e.additionalProperties&&typeof e.additionalProperties=="object"?Hi(e.additionalProperties,t):it.any();if(Object.keys(o).length===0){n=it.record(l,c);break}const u=it.object(o).passthrough(),d=it.looseRecord(l,c);n=it.intersection(u,d);break}if(e.patternProperties){const l=e.patternProperties,c=Object.keys(l),u=[];for(const m of c){const h=Hi(l[m],t),g=it.string().regex(new RegExp(m));u.push(it.looseRecord(g,h))}const d=[];if(Object.keys(o).length>0&&d.push(it.object(o).passthrough()),d.push(...u),d.length===0)n=it.object({}).passthrough();else if(d.length===1)n=d[0];else{let m=it.intersection(d[0],d[1]);for(let h=2;h<d.length;h++)m=it.intersection(m,d[h]);n=m}break}const a=it.object(o);e.additionalProperties===!1?n=a.strict():typeof e.additionalProperties=="object"?n=a.catchall(Hi(e.additionalProperties,t)):n=a.passthrough();break}case"array":{const o=e.prefixItems,s=e.items;if(o&&Array.isArray(o)){const i=o.map(l=>Hi(l,t)),a=s&&typeof s=="object"&&!Array.isArray(s)?Hi(s,t):void 0;a?n=it.tuple(i).rest(a):n=it.tuple(i),typeof e.minItems=="number"&&(n=n.check(it.minLength(e.minItems))),typeof e.maxItems=="number"&&(n=n.check(it.maxLength(e.maxItems)))}else if(Array.isArray(s)){const i=s.map(l=>Hi(l,t)),a=e.additionalItems&&typeof e.additionalItems=="object"?Hi(e.additionalItems,t):void 0;a?n=it.tuple(i).rest(a):n=it.tuple(i),typeof e.minItems=="number"&&(n=n.check(it.minLength(e.minItems))),typeof e.maxItems=="number"&&(n=n.check(it.maxLength(e.maxItems)))}else if(s!==void 0){const i=Hi(s,t);let a=it.array(i);typeof e.minItems=="number"&&(a=a.min(e.minItems)),typeof e.maxItems=="number"&&(a=a.max(e.maxItems)),n=a}else n=it.array(it.any());break}default:throw new Error(`Unsupported type: ${r}`)}return e.description&&(n=n.describe(e.description)),e.default!==void 0&&(n=n.default(e.default)),n}function Hi(e,t){if(typeof e=="boolean")return e?it.any():it.never();let r=Vye(e,t);const n=e.type||e.enum!==void 0||e.const!==void 0;if(e.anyOf&&Array.isArray(e.anyOf)){const a=e.anyOf.map(c=>Hi(c,t)),l=it.union(a);r=n?it.intersection(r,l):l}if(e.oneOf&&Array.isArray(e.oneOf)){const a=e.oneOf.map(c=>Hi(c,t)),l=it.xor(a);r=n?it.intersection(r,l):l}if(e.allOf&&Array.isArray(e.allOf))if(e.allOf.length===0)r=n?r:it.any();else{let a=n?r:Hi(e.allOf[0],t);const l=n?0:1;for(let c=l;c<e.allOf.length;c++)a=it.intersection(a,Hi(e.allOf[c],t));r=a}e.nullable===!0&&t.version==="openapi-3.0"&&(r=it.nullable(r)),e.readOnly===!0&&(r=it.readonly(r));const o={},s=["$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor"];for(const a of s)a in e&&(o[a]=e[a]);const i=["contentEncoding","contentMediaType","contentSchema"];for(const a of i)a in e&&(o[a]=e[a]);for(const a of Object.keys(e))Wye.has(a)||(o[a]=e[a]);return Object.keys(o).length>0&&t.registry.add(r,o),r}function Iyr(e,t){if(typeof e=="boolean")return e?it.any():it.never();const r=xyr(e,t?.defaultTarget),n=e.$defs||e.definitions||{},o={version:r,defs:n,refs:new Map,processing:new Set,rootSchema:e,registry:t?.registry??vl};return Hi(e,o)}var it,Wye,Ryr=S({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/from-json-schema.js"(){SR(),MB(),KR(),P1(),it={...qge,...Nge,iso:qR},Wye=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"])}}),lz={};he(lz,{bigint:()=>Oyr,boolean:()=>Dyr,date:()=>Nyr,number:()=>Pyr,string:()=>Myr});function Myr(e){return Kfe(kv,e)}function Pyr(e){return tge(Iv,e)}function Dyr(e){return lge(Rv,e)}function Oyr(e){return uge(Mv,e)}function Nyr(e){return bge(GT,e)}var Lyr=S({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/coerce.js"(){cs(),P1()}}),p={};he(p,{$brand:()=>Y3,$input:()=>_5,$output:()=>v5,NEVER:()=>GI,TimePrecision:()=>V5,ZodAny:()=>i1,ZodArray:()=>u1,ZodBase64:()=>UT,ZodBase64URL:()=>BT,ZodBigInt:()=>Mv,ZodBigIntFormat:()=>qT,ZodBoolean:()=>Rv,ZodCIDRv4:()=>$T,ZodCIDRv6:()=>FT,ZodCUID:()=>RT,ZodCUID2:()=>MT,ZodCatch:()=>C1,ZodCodec:()=>KT,ZodCustom:()=>Nv,ZodCustomStringFormat:()=>cf,ZodDate:()=>GT,ZodDefault:()=>T1,ZodDiscriminatedUnion:()=>p1,ZodE164:()=>zT,ZodEmail:()=>xT,ZodEmoji:()=>AT,ZodEnum:()=>uf,ZodError:()=>Bge,ZodExactOptional:()=>w1,ZodFile:()=>v1,ZodFirstPartyTypeKind:()=>az,ZodFunction:()=>M1,ZodGUID:()=>xv,ZodIPv4:()=>NT,ZodIPv6:()=>LT,ZodISODate:()=>HR,ZodISODateTime:()=>GR,ZodISODuration:()=>WR,ZodISOTime:()=>VR,ZodIntersection:()=>m1,ZodIssueCode:()=>iz,ZodJWT:()=>jT,ZodKSUID:()=>OT,ZodLazy:()=>I1,ZodLiteral:()=>y1,ZodMAC:()=>r1,ZodMap:()=>f1,ZodNaN:()=>k1,ZodNanoID:()=>IT,ZodNever:()=>l1,ZodNonOptional:()=>VT,ZodNull:()=>s1,ZodNullable:()=>b1,ZodNumber:()=>Iv,ZodNumberFormat:()=>ym,ZodObject:()=>Pv,ZodOptional:()=>HT,ZodPipe:()=>WT,ZodPrefault:()=>E1,ZodPromise:()=>R1,ZodReadonly:()=>x1,ZodRealError:()=>Ba,ZodRecord:()=>Ov,ZodSet:()=>g1,ZodString:()=>kv,ZodStringFormat:()=>nn,ZodSuccess:()=>S1,ZodSymbol:()=>n1,ZodTemplateLiteral:()=>A1,ZodTransform:()=>_1,ZodTuple:()=>h1,ZodType:()=>Qt,ZodULID:()=>PT,ZodURL:()=>Av,ZodUUID:()=>Vc,ZodUndefined:()=>o1,ZodUnion:()=>Dv,ZodUnknown:()=>a1,ZodVoid:()=>c1,ZodXID:()=>DT,ZodXor:()=>d1,_ZodString:()=>kT,_default:()=>KB,_function:()=>e1,any:()=>HB,array:()=>rt,base64:()=>cye,base64url:()=>uye,bigint:()=>bye,boolean:()=>tn,catch:()=>ZB,check:()=>qye,cidrv4:()=>aye,cidrv6:()=>lye,clone:()=>nc,codec:()=>Bye,coerce:()=>lz,config:()=>qi,core:()=>Oge,cuid:()=>Qge,cuid2:()=>eye,custom:()=>ez,date:()=>xye,decode:()=>$B,decodeAsync:()=>UB,describe:()=>nz,discriminatedUnion:()=>XR,e164:()=>dye,email:()=>Gge,emoji:()=>Zge,encode:()=>LB,encodeAsync:()=>FB,endsWith:()=>PR,enum:()=>Gi,exactOptional:()=>WB,file:()=>Lye,flattenError:()=>oU,float32:()=>yye,float64:()=>vye,formatError:()=>sU,fromJSONSchema:()=>Iyr,function:()=>e1,getErrorMap:()=>Cyr,globalRegistry:()=>vl,gt:()=>fm,gte:()=>Ua,guid:()=>Hge,hash:()=>gye,hex:()=>fye,hostname:()=>hye,httpUrl:()=>Yge,includes:()=>RR,instanceof:()=>Gye,int:()=>YR,int32:()=>_ye,int64:()=>Tye,intersection:()=>ET,ipv4:()=>oye,ipv6:()=>iye,iso:()=>qR,json:()=>Hye,jwt:()=>pye,keyof:()=>Aye,ksuid:()=>nye,lazy:()=>QB,length:()=>vT,literal:()=>Tt,locales:()=>f5,looseObject:()=>Ns,looseRecord:()=>Pye,lowercase:()=>AR,lt:()=>hm,lte:()=>sc,mac:()=>sye,map:()=>Dye,maxLength:()=>yT,maxSize:()=>bv,meta:()=>oz,mime:()=>DR,minLength:()=>lf,minSize:()=>gm,multipleOf:()=>wv,nan:()=>Uye,nanoid:()=>Xge,nativeEnum:()=>Nye,negative:()=>j5,never:()=>ZR,nonnegative:()=>G5,nonoptional:()=>YB,nonpositive:()=>q5,normalize:()=>OR,null:()=>TT,nullable:()=>ST,nullish:()=>$ye,number:()=>Rr,object:()=>ot,optional:()=>En,overwrite:()=>Fd,parse:()=>DB,parseAsync:()=>OB,partialRecord:()=>Mye,pipe:()=>CT,positive:()=>z5,prefault:()=>JB,preprocess:()=>t1,prettifyError:()=>Lme,promise:()=>jye,property:()=>H5,readonly:()=>XB,record:()=>gn,refine:()=>tz,regex:()=>xR,regexes:()=>sf,registry:()=>y5,safeDecode:()=>zB,safeDecodeAsync:()=>qB,safeEncode:()=>BB,safeEncodeAsync:()=>jB,safeParse:()=>NB,safeParseAsync:()=>JR,set:()=>Oye,setErrorMap:()=>Syr,size:()=>gT,slugify:()=>FR,startsWith:()=>MR,strictObject:()=>Iye,string:()=>ce,stringFormat:()=>mye,stringbool:()=>sz,success:()=>Fye,superRefine:()=>rz,symbol:()=>Sye,templateLiteral:()=>zye,toJSONSchema:()=>wT,toLowerCase:()=>LR,toUpperCase:()=>$R,transform:()=>QR,treeifyError:()=>Ome,trim:()=>NR,tuple:()=>VB,uint32:()=>wye,uint64:()=>Eye,ulid:()=>tye,undefined:()=>Cye,union:()=>rn,unknown:()=>un,uppercase:()=>IR,url:()=>GB,util:()=>_r,uuid:()=>Vge,uuidv4:()=>Wge,uuidv6:()=>Kge,uuidv7:()=>Jge,void:()=>kye,xid:()=>rye,xor:()=>Rye});var D1=S({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/external.js"(){cs(),P1(),MB(),zge(),jge(),kyr(),cs(),efe(),cs(),bT(),Ryr(),g5(),KR(),KR(),Lyr(),qi(Xhe())}}),Gr=S({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/index.js"(){D1(),D1()}}),cz,uz,$yr=S({"src/lib/types/model.ts"(){"use strict";Gr(),cz=p.object({id:p.string(),displayName:p.string(),capabilities:p.array(p.string()),deprecated:p.boolean(),pricing:p.object({input:p.number(),output:p.number()}),contextWindow:p.number(),releaseDate:p.string()}),uz=p.object({version:p.string(),lastUpdated:p.string(),models:p.record(p.string(),p.record(p.string(),cz)),aliases:p.record(p.string(),p.string()).optional(),defaults:p.record(p.string(),p.string()).optional()})}});function Fyr(e){return e.type==="text"}function Uyr(e){return e.type==="image"}function dz(e){return e.type==="csv"}function Byr(e){return e.type==="pdf"}function zyr(e){return e.type==="audio"}function jyr(e){return e.type==="video"}function qyr(e){if(!e||typeof e!="object")return!1;const t=e;if(typeof t.prompt!="string"||!t.prompt)return!1;const{image:r}=t;if(!r)return!1;if(Buffer.isBuffer(r)||typeof r=="string")return!0;if(typeof r=="object"&&"data"in r){const n=r.data;return Buffer.isBuffer(n)||typeof n=="string"}return!1}function Gyr(e){if(typeof e!="object"||e===null)return!1;const t=e,r=n=>Array.isArray(n)&&n.length>0;return!!(r(t.images)||r(t.csvFiles)||r(t.pdfFiles)||r(t.files)||r(t.content)||r(t.audioFiles)||r(t.videoFiles)||Array.isArray(t.segments)&&t.segments.length>0&&t.segments.every(qyr))}function Hyr(e){return Array.isArray(e)}var Vyr=S({"src/lib/types/multimodal.ts"(){"use strict"}}),Wyr=S({"src/lib/types/nativeTools.ts"(){"use strict"}}),Kyr=S({"src/lib/types/observability.ts"(){"use strict"}}),Jyr=S({"src/lib/types/openaiCompatible.ts"(){"use strict"}});function Yyr(e){return/^[0-9A-Fa-f]{6}$/.test(e)}function Zyr(e){return e.startsWith("#")?e.slice(1):e}var Kye,Jye,O1,Xyr=S({"src/lib/types/ppt.ts"(){"use strict";Kye=5,Jye=50,O1={"16:9":{width:10,height:5.625},"4:3":{width:10,height:7.5}}}}),pz,Yye,Zye=S({"src/lib/processors/errors/FileErrorCode.ts"(){"use strict";pz=(e=>(e.DOWNLOAD_FAILED="DOWNLOAD_FAILED",e.DOWNLOAD_TIMEOUT="DOWNLOAD_TIMEOUT",e.DOWNLOAD_AUTH_FAILED="DOWNLOAD_AUTH_FAILED",e.NETWORK_ERROR="NETWORK_ERROR",e.FILE_NOT_FOUND="FILE_NOT_FOUND",e.RATE_LIMITED="RATE_LIMITED",e.FILE_TOO_LARGE="FILE_TOO_LARGE",e.UNSUPPORTED_TYPE="UNSUPPORTED_TYPE",e.INVALID_FORMAT="INVALID_FORMAT",e.INVALID_MIME_TYPE="INVALID_MIME_TYPE",e.INVALID_MAGIC_BYTES="INVALID_MAGIC_BYTES",e.CORRUPTED_FILE="CORRUPTED_FILE",e.INVALID_STRUCTURE="INVALID_STRUCTURE",e.PROCESSING_FAILED="PROCESSING_FAILED",e.PARSING_FAILED="PARSING_FAILED",e.ENCODING_ERROR="ENCODING_ERROR",e.EXTRACTION_FAILED="EXTRACTION_FAILED",e.DECOMPRESSION_FAILED="DECOMPRESSION_FAILED",e.SECURITY_VALIDATION_FAILED="SECURITY_VALIDATION_FAILED",e.XXE_DETECTED="XXE_DETECTED",e.XSS_DETECTED="XSS_DETECTED",e.CODE_EXECUTION_DETECTED="CODE_EXECUTION_DETECTED",e.ZIP_BOMB_DETECTED="ZIP_BOMB_DETECTED",e.UNKNOWN_ERROR="UNKNOWN_ERROR",e))(pz||{}),Yye={DOWNLOAD_FAILED:{message:"Failed to download the file from the source.",userMessage:"We couldn't download your file.",suggestedAction:"Please try uploading the file again. If the problem persists, the file may have been deleted or access revoked.",retryable:!0},DOWNLOAD_TIMEOUT:{message:"File download timed out.",userMessage:"The download took too long and was cancelled.",suggestedAction:"This usually happens with very large files or slow connections. Try re-uploading a smaller version or check your network connection.",retryable:!0},DOWNLOAD_AUTH_FAILED:{message:"Authentication failed when accessing the file.",userMessage:"We don't have permission to access this file.",suggestedAction:"Please check the file permissions and ensure it's accessible, then try again.",retryable:!1},NETWORK_ERROR:{message:"Network error while downloading the file.",userMessage:"A network error occurred while downloading.",suggestedAction:"This is usually temporary. Please try uploading the file again.",retryable:!0},FILE_NOT_FOUND:{message:"The file could not be found at the specified location.",userMessage:"The file could not be found.",suggestedAction:"The file may have been moved or deleted. Please re-upload the file.",retryable:!1},RATE_LIMITED:{message:"Request was rate limited by the server.",userMessage:"Too many requests in a short time.",suggestedAction:"Please wait a few seconds and try again.",retryable:!0},FILE_TOO_LARGE:{message:"File exceeds the maximum allowed size.",userMessage:"This file is too large to process.",suggestedAction:"Try compressing the file or splitting it into smaller parts. Consider reducing image quality or removing unnecessary content.",retryable:!1},UNSUPPORTED_TYPE:{message:"The file type is not supported for processing.",userMessage:"This file type is not supported.",suggestedAction:"Please convert your file to a supported format and try again.",retryable:!1},INVALID_FORMAT:{message:"The file format is invalid or malformed.",userMessage:"This file appears to be in an invalid format.",suggestedAction:"Please ensure the file is properly saved and not corrupted, then try again.",retryable:!1},INVALID_MIME_TYPE:{message:"File MIME type doesn't match the expected format.",userMessage:"The file type doesn't match its extension.",suggestedAction:"Please ensure the file extension matches its actual content type and try again.",retryable:!1},INVALID_MAGIC_BYTES:{message:"File magic bytes don't match the expected file type.",userMessage:"This file doesn't appear to be a valid file of the expected type.",suggestedAction:"The file may be corrupted or saved in the wrong format. Try re-saving the file in the correct format.",retryable:!0},CORRUPTED_FILE:{message:"File appears to be corrupted or damaged.",userMessage:"This file appears to be corrupted or invalid.",suggestedAction:"The file structure is invalid. Try re-downloading from the original source or re-creating the file.",retryable:!1},INVALID_STRUCTURE:{message:"File internal structure is invalid.",userMessage:"The file has an invalid internal structure.",suggestedAction:"The file format is correct but the content is malformed. Try validating the file with a format checker or re-exporting from the original application.",retryable:!1},PROCESSING_FAILED:{message:"Failed to process the file content.",userMessage:"We couldn't process this file.",suggestedAction:"Please try again. If the problem persists, the file may be in an unsupported variant.",retryable:!0},PARSING_FAILED:{message:"Failed to parse the file content.",userMessage:"We couldn't read the contents of this file.",suggestedAction:"The file structure may be invalid. Try validating the file with a format checker or re-creating the file.",retryable:!1},ENCODING_ERROR:{message:"Text encoding error detected.",userMessage:"We couldn't decode the text in this file.",suggestedAction:"Try re-saving the file with UTF-8 encoding. Most modern text editors have this option in 'Save As' settings.",retryable:!1},EXTRACTION_FAILED:{message:"Failed to extract content from the file.",userMessage:"We couldn't extract the content from this file.",suggestedAction:"The file may be password-protected, corrupted, or use an unsupported variant. Try re-saving without protection.",retryable:!1},DECOMPRESSION_FAILED:{message:"Failed to decompress the file content.",userMessage:"We couldn't decompress this file.",suggestedAction:"The file may be corrupted or use an unsupported compression method. Try re-uploading or using a different file format.",retryable:!0},SECURITY_VALIDATION_FAILED:{message:"File failed security validation.",userMessage:"This file contains content that is blocked for security reasons.",suggestedAction:"Please remove the problematic content and try again. If you believe this is a legitimate file, please contact support.",retryable:!1},XXE_DETECTED:{message:"XML External Entity (XXE) attack pattern detected.",userMessage:"This XML file contains DOCTYPE or ENTITY declarations that could pose security risks.",suggestedAction:"Please remove DOCTYPE and ENTITY declarations from the XML file. Most XML files don't need these for basic data storage.",retryable:!1},XSS_DETECTED:{message:"Cross-site scripting (XSS) attack pattern detected.",userMessage:"This file contains script tags or event handlers that could pose security risks.",suggestedAction:"Please remove <script> tags and event handlers (onclick, onerror, etc.) from the file.",retryable:!1},CODE_EXECUTION_DETECTED:{message:"Potentially malicious code execution pattern detected.",userMessage:"This file contains code execution tags that are not allowed.",suggestedAction:"Please remove custom object/function tags and use standard data structures only.",retryable:!1},ZIP_BOMB_DETECTED:{message:"Zip bomb or decompression bomb pattern detected.",userMessage:"This file has an unusually high compression ratio that could indicate a security threat.",suggestedAction:"If this is a legitimate file, try re-saving it without extreme compression. Otherwise, please verify the file source.",retryable:!1},UNKNOWN_ERROR:{message:"An unexpected error occurred.",userMessage:"An unexpected error occurred while processing your file.",suggestedAction:"Please try again. If the problem persists, contact support.",retryable:!0}}}}),mz,Xye,Qye,eve,tve,rve,Qyr=S({"src/lib/types/processor.ts"(){"use strict";Zye(),mz={maxRetries:3,baseDelayMs:1e3,maxDelayMs:1e4},Xye=3e4,Qye=10,eve=3e4,tve=10,rve={SVG:5,IMAGE:10,PDF:20,CSV:30,MARKDOWN:40,JSON:50,YAML:60,XML:70,HTML:80,EXCEL:90,DOC:95,WORD:100,TEXT:110,SOURCE_CODE:120,CONFIG:130,RTF:140,OPENDOCUMENT:150,VIDEO:160,AUDIO:170,ARCHIVE:180}}}),evr=S({"src/lib/types/providerCatalog.ts"(){"use strict"}}),tvr=S({"src/lib/types/providerCatalog.generated.ts"(){"use strict"}});function rvr(e){if(e==null||typeof e!="object")return!1;const t=e,r=["api_key","oauth"],n=["free","pro","max","max_5","max_20","api"];if(t.authMethod!==void 0&&typeof t.authMethod=="string"&&r.includes(t.authMethod)||t.subscriptionTier!==void 0&&typeof t.subscriptionTier=="string"&&n.includes(t.subscriptionTier)||t.oauthConfig!==void 0&&typeof t.oauthConfig=="object"&&t.oauthConfig!==null)return!0;if(t.authConfig!==void 0&&typeof t.authConfig=="object"&&t.authConfig!==null){const o=t.authConfig;if(o.method!==void 0&&typeof o.method=="string"&&r.includes(o.method))return!0}return!1}var N1,nve,ove,nvr=S({"src/lib/types/providers.ts"(){"use strict";N1={LATEST_OPENAI:"gpt-4o",FASTEST_OPENAI:"gpt-4o-mini",LATEST_ANTHROPIC:"claude-3-5-sonnet-20241022",FASTEST_ANTHROPIC:"claude-3-5-haiku-20241022",LATEST_GOOGLE:"gemini-2.5-pro",FASTEST_GOOGLE:"gemini-2.5-flash",BEST_CODING:"claude-3-5-sonnet-20241022",BEST_ANALYSIS:"gemini-2.5-pro",BEST_CREATIVE:"claude-3-5-sonnet-20241022",BEST_VALUE:"gemini-2.5-flash"},nve=N1,ove=[{provider:"bedrock",models:["anthropic.claude-3-7-sonnet-20250219-v1:0","anthropic.claude-3-5-sonnet-20241022-v1:0"]},{provider:"vertex",models:["claude-sonnet-4@20250514","gemini-2.5-flash"]},{provider:"openai",models:["gpt-4o","gpt-4o-mini"]}]}}),ovr=S({"src/lib/types/proxy.ts"(){"use strict"}}),svr=S({"src/lib/types/proxyClient.ts"(){"use strict"}}),ivr=S({"src/lib/types/rag.ts"(){"use strict"}}),avr=S({"src/lib/types/scorer.ts"(){"use strict"}}),lvr=S({"src/lib/types/sdk.ts"(){"use strict"}}),kr,Sn,Er,cvr=S({"src/lib/types/server.ts"(){"use strict";kr={CONFIG:"CONFIG",VALIDATION:"VALIDATION",EXECUTION:"EXECUTION",EXTERNAL:"EXTERNAL",RATE_LIMIT:"RATE_LIMIT",AUTHENTICATION:"AUTHENTICATION",AUTHORIZATION:"AUTHORIZATION",STREAMING:"STREAMING",WEBSOCKET:"WEBSOCKET"},Sn={LOW:"LOW",MEDIUM:"MEDIUM",HIGH:"HIGH",CRITICAL:"CRITICAL"},Er={INVALID_CONFIG:"SERVER_ADAPTER_INVALID_CONFIG",MISSING_DEPENDENCY:"SERVER_ADAPTER_MISSING_DEPENDENCY",FRAMEWORK_INIT_FAILED:"SERVER_ADAPTER_FRAMEWORK_INIT_FAILED",ROUTE_NOT_FOUND:"SERVER_ADAPTER_ROUTE_NOT_FOUND",ROUTE_CONFLICT:"SERVER_ADAPTER_ROUTE_CONFLICT",INVALID_ROUTE:"SERVER_ADAPTER_INVALID_ROUTE",HANDLER_ERROR:"SERVER_ADAPTER_HANDLER_ERROR",TIMEOUT:"SERVER_ADAPTER_TIMEOUT",MIDDLEWARE_ERROR:"SERVER_ADAPTER_MIDDLEWARE_ERROR",RATE_LIMIT_EXCEEDED:"SERVER_ADAPTER_RATE_LIMIT_EXCEEDED",AUTH_REQUIRED:"SERVER_ADAPTER_AUTH_REQUIRED",AUTH_INVALID:"SERVER_ADAPTER_AUTH_INVALID",FORBIDDEN:"SERVER_ADAPTER_FORBIDDEN",STREAM_ERROR:"SERVER_ADAPTER_STREAM_ERROR",STREAM_ABORTED:"SERVER_ADAPTER_STREAM_ABORTED",WEBSOCKET_ERROR:"SERVER_ADAPTER_WEBSOCKET_ERROR",WEBSOCKET_CONNECTION_FAILED:"SERVER_ADAPTER_WEBSOCKET_CONNECTION_FAILED",VALIDATION_ERROR:"SERVER_ADAPTER_VALIDATION_ERROR",SCHEMA_ERROR:"SERVER_ADAPTER_SCHEMA_ERROR",START_FAILED:"SERVER_ADAPTER_START_FAILED",STOP_FAILED:"SERVER_ADAPTER_STOP_FAILED",ALREADY_RUNNING:"SERVER_ADAPTER_ALREADY_RUNNING",NOT_RUNNING:"SERVER_ADAPTER_NOT_RUNNING"}}}),uvr=S({"src/lib/types/service.ts"(){"use strict"}}),dvr=S({"src/lib/types/skills.ts"(){"use strict"}}),pvr=S({"src/lib/types/stream.ts"(){"use strict"}}),mvr=S({"src/lib/types/streaming.ts"(){"use strict"}}),hvr=S({"src/lib/types/subscription.ts"(){"use strict"}}),hz,fz,Ho,fvr=S({"src/lib/types/task.ts"(){"use strict";hz=720*60*60*1e3,fz=10080*60*1e3,Ho={enabled:!0,maxTasks:100,backend:"bullmq",mode:"isolated",timeout:12e4,maxConcurrentRuns:5,maxRunLogs:2e3,maxHistoryEntries:200,tools:!0,retry:{maxAttempts:3,backoffMs:[3e4,6e4,3e5]},storePath:".neurolink/tasks/tasks.json",logsPath:".neurolink/tasks/runs/",redis:{host:"localhost",port:6379},retention:{completedTTL:hz,failedTTL:fz,cancelledTTL:fz,runLogTTL:hz}}}}),gvr=S({"src/lib/types/taskClassification.ts"(){"use strict"}}),yvr=S({"src/lib/types/tasks.ts"(){"use strict"}}),vvr=S({"src/lib/types/toolDedup.ts"(){"use strict"}}),_vr=S({"src/lib/types/toolResolution.ts"(){"use strict"}}),wvr=S({"src/lib/types/toolRouting.ts"(){"use strict"}});function bvr(e){return typeof e=="object"&&e!==null&&"success"in e&&typeof e.success=="boolean"}function Tvr(e){return typeof e=="object"&&e!==null&&"description"in e&&"execute"in e&&typeof e.description=="string"&&typeof e.execute=="function"}var Evr=S({"src/lib/types/tools.ts"(){"use strict"}}),Svr=S({"src/lib/types/vectorStoreChroma.ts"(){"use strict"}}),Cvr=S({"src/lib/types/vectorStorePinecone.ts"(){"use strict"}});function kvr(e){if(!e||typeof e!="object")return!1;const t=e;return Buffer.isBuffer(t.buffer)&&typeof t.format=="string"&&JT.includes(t.format)&&typeof t.size=="number"&&t.size>=0}function xvr(e){if(!e||typeof e!="object")return!1;const t=e;return!(t.speed!==void 0&&(typeof t.speed!="number"||t.speed<.25||t.speed>4)||t.format!==void 0&&!JT.includes(t.format)||t.quality!==void 0&&!gz.includes(t.quality)||t.streamingBufferSize!==void 0&&(!Number.isInteger(t.streamingBufferSize)||t.streamingBufferSize<1))}var JT,gz,Avr=S({"src/lib/types/tts.ts"(){"use strict";JT=["mp3","wav","ogg","opus","m4a","flac","webm","mp4","mpeg","mpga","pcm16"],gz=["standard","hd"]}});function sve(e){if(!e||typeof e!="object")return!1;const t=e;return typeof t.text=="string"&&typeof t.confidence=="number"&&t.confidence>=0&&t.confidence<=1}function ive(e){if(!e||typeof e!="object")return!1;const t=e;return!(t.sampleRate!==void 0&&(typeof t.sampleRate!="number"||t.sampleRate<=0)||t.speakerCount!==void 0&&(typeof t.speakerCount!="number"||t.speakerCount<1||t.speakerCount>10))}function ave(e){if(!e||typeof e!="object")return!1;const t=e;return(t.index===void 0||typeof t.index=="number")&&typeof t.text=="string"&&typeof t.isFinal=="boolean"}var Ai,yz,Ivr=S({"src/lib/types/stt.ts"(){"use strict";Ai={AUDIO_EMPTY:"STT_AUDIO_EMPTY",AUDIO_TOO_LONG:"STT_AUDIO_TOO_LONG",INVALID_AUDIO_FORMAT:"STT_INVALID_AUDIO_FORMAT",LANGUAGE_NOT_SUPPORTED:"STT_LANGUAGE_NOT_SUPPORTED",TRANSCRIPTION_FAILED:"STT_TRANSCRIPTION_FAILED",PROVIDER_NOT_CONFIGURED:"STT_PROVIDER_NOT_CONFIGURED",PROVIDER_NOT_SUPPORTED:"STT_PROVIDER_NOT_SUPPORTED",STREAM_ERROR:"STT_STREAM_ERROR",STREAMING_NOT_SUPPORTED:"STT_STREAMING_NOT_SUPPORTED"},yz={language:"en-US",punctuation:!0,profanityFilter:!1,sampleRate:16e3}}});function lve(e){if(!e||typeof e!="object")return!1;const t=e;return!(!t.provider||!["openai-realtime","gemini-live"].includes(t.provider)||t.timeout!==void 0&&(typeof t.timeout!="number"||t.timeout<=0)||t.vadThreshold!==void 0&&(typeof t.vadThreshold!="number"||t.vadThreshold<0||t.vadThreshold>1))}var ri,L1,Rvr=S({"src/lib/types/realtime.ts"(){"use strict";ri={CONNECTION_FAILED:"REALTIME_CONNECTION_FAILED",SESSION_TIMEOUT:"REALTIME_SESSION_TIMEOUT",PROTOCOL_ERROR:"REALTIME_PROTOCOL_ERROR",AUDIO_STREAM_ERROR:"REALTIME_AUDIO_STREAM_ERROR",PROVIDER_NOT_CONFIGURED:"REALTIME_PROVIDER_NOT_CONFIGURED",PROVIDER_NOT_SUPPORTED:"REALTIME_PROVIDER_NOT_SUPPORTED",SESSION_ALREADY_ACTIVE:"REALTIME_SESSION_ALREADY_ACTIVE",SESSION_NOT_ACTIVE:"REALTIME_SESSION_NOT_ACTIVE",INVALID_MESSAGE:"REALTIME_INVALID_MESSAGE"},L1={timeout:3e4,inputSampleRate:24e3,outputSampleRate:24e3,vadEnabled:!0,vadThreshold:.5,turnDetection:"server_vad"}}}),vz,YT,Mvr=S({"src/lib/types/voice.ts"(){"use strict";Avr(),Ivr(),Rvr(),vz={PROVIDER_NOT_FOUND:"VOICE_PROVIDER_NOT_FOUND",INVALID_CONFIGURATION:"VOICE_INVALID_CONFIGURATION",INITIALIZATION_FAILED:"VOICE_INITIALIZATION_FAILED",OPERATION_CANCELLED:"VOICE_OPERATION_CANCELLED",PROVIDER_NOT_CONFIGURED:"VOICE_PROVIDER_NOT_CONFIGURED",PROVIDER_NOT_SUPPORTED:"VOICE_PROVIDER_NOT_SUPPORTED",FEATURE_NOT_SUPPORTED:"VOICE_FEATURE_NOT_SUPPORTED",TTS_EMPTY_TEXT:"VOICE_TTS_EMPTY_TEXT",TTS_TEXT_TOO_LONG:"VOICE_TTS_TEXT_TOO_LONG",TTS_SYNTHESIS_FAILED:"VOICE_TTS_SYNTHESIS_FAILED",STT_EMPTY_AUDIO:"VOICE_STT_EMPTY_AUDIO",STT_INVALID_FORMAT:"VOICE_STT_INVALID_FORMAT",STT_TRANSCRIPTION_FAILED:"VOICE_STT_TRANSCRIPTION_FAILED",REALTIME_CONNECTION_FAILED:"VOICE_REALTIME_CONNECTION_FAILED",REALTIME_SESSION_ERROR:"VOICE_REALTIME_SESSION_ERROR",NETWORK_ERROR:"VOICE_NETWORK_ERROR",TIMEOUT:"VOICE_TIMEOUT"},YT={mp3:{format:"mp3",mimeType:"audio/mpeg",extension:".mp3",supportsStreaming:!0,sampleRates:[8e3,16e3,22050,24e3,44100,48e3],bitDepths:[16]},wav:{format:"wav",mimeType:"audio/wav",extension:".wav",supportsStreaming:!1,sampleRates:[8e3,16e3,22050,24e3,44100,48e3],bitDepths:[8,16,24,32]},ogg:{format:"ogg",mimeType:"audio/ogg",extension:".ogg",supportsStreaming:!0,sampleRates:[8e3,16e3,22050,24e3,44100,48e3],bitDepths:[16]},opus:{format:"opus",mimeType:"audio/opus",extension:".opus",supportsStreaming:!0,sampleRates:[8e3,12e3,16e3,24e3,48e3],bitDepths:[16]},m4a:{format:"m4a",mimeType:"audio/mp4",extension:".m4a",supportsStreaming:!1,sampleRates:[44100,48e3],bitDepths:[16]},flac:{format:"flac",mimeType:"audio/flac",extension:".flac",supportsStreaming:!1,sampleRates:[44100,48e3,96e3],bitDepths:[16,24]},webm:{format:"webm",mimeType:"audio/webm",extension:".webm",supportsStreaming:!0,sampleRates:[44100,48e3],bitDepths:[16]},mp4:{format:"mp4",mimeType:"audio/mp4",extension:".mp4",supportsStreaming:!1,sampleRates:[44100,48e3],bitDepths:[16]},mpeg:{format:"mpeg",mimeType:"audio/mpeg",extension:".mpeg",supportsStreaming:!0,sampleRates:[8e3,16e3,22050,24e3,44100,48e3],bitDepths:[16]},mpga:{format:"mpga",mimeType:"audio/mpeg",extension:".mpga",supportsStreaming:!0,sampleRates:[8e3,16e3,22050,24e3,44100,48e3],bitDepths:[16]}}}}),Pvr=S({"src/lib/types/utilities.ts"(){"use strict"}}),Ud,Dvr=S({"src/lib/types/workflow.ts"(){"use strict";Ud=class sdr extends Error{details;constructor(t,r){super(t),this.name="WorkflowError",this.details=r,"captureStackTrace"in Error&&typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,sdr)}}}}),Ovr=S({"src/lib/types/ioProcessor.ts"(){"use strict"}}),Nvr=S({"src/lib/types/exporter.ts"(){"use strict"}}),_z,wz,cve,uve,Lvr=S({"src/lib/types/span.ts"(){"use strict";_z=(e=>(e.AGENT_RUN="agent.run",e.WORKFLOW_STEP="workflow.step",e.TOOL_CALL="tool.call",e.MODEL_GENERATION="model.generation",e.EMBEDDING="embedding",e.RETRIEVAL="retrieval",e.MEMORY="memory",e.CONTEXT_COMPACTION="context.compaction",e.RAG="rag",e.EVALUATION="evaluation",e.MCP_TRANSPORT="mcp.transport",e.MEDIA_GENERATION="media.generation",e.PPT_GENERATION="ppt.generation",e.WORKFLOW="workflow",e.TTS="tts",e.STT="stt",e.SERVER_REQUEST="server.request",e.CUSTOM="custom",e))(_z||{}),wz=(e=>(e[e.UNSET=0]="UNSET",e[e.OK=1]="OK",e[e.ERROR=2]="ERROR",e[e.WARNING=3]="WARNING",e))(wz||{}),cve={GEN_AI_SYSTEM:"gen_ai.system",GEN_AI_REQUEST_MODEL:"gen_ai.request.model",GEN_AI_RESPONSE_MODEL:"gen_ai.response.model",GEN_AI_USAGE_INPUT_TOKENS:"gen_ai.usage.input_tokens",GEN_AI_USAGE_OUTPUT_TOKENS:"gen_ai.usage.output_tokens",GEN_AI_USAGE_TOTAL_TOKENS:"gen_ai.usage.total_tokens",GEN_AI_REQUEST_TEMPERATURE:"gen_ai.request.temperature",GEN_AI_REQUEST_TOP_P:"gen_ai.request.top_p",GEN_AI_REQUEST_MAX_TOKENS:"gen_ai.request.max_tokens",GEN_AI_REQUEST_STOP_SEQUENCES:"gen_ai.request.stop_sequences",GEN_AI_RESPONSE_FINISH_REASON:"gen_ai.response.finish_reasons",GEN_AI_RESPONSE_ID:"gen_ai.response.id",GEN_AI_TOOL_NAME:"gen_ai.tool.name",GEN_AI_TOOL_CALL_ID:"gen_ai.tool.call_id",GEN_AI_PROMPT:"gen_ai.prompt",GEN_AI_COMPLETION:"gen_ai.completion"},uve={AGENT_NAME:"gen_ai.agent.name",AGENT_STEP_TYPE:"gen_ai.agent.step_type",AGENT_TOOL_CALLS:"gen_ai.agent.tool_calls",AGENT_MEMORY_ACCESS:"gen_ai.agent.memory_access",AGENT_REASONING_TRACE:"gen_ai.agent.reasoning_trace"}}}),bz,$vr=S({"src/lib/types/imageGen.ts"(){"use strict";bz={enabled:!0,defaultModel:"imagen-3.0-generate-001",defaultProvider:"vertex",defaultRegion:"global",timeout:12e4,defaultTemperature:.75,maxImages:4,maxReferenceImages:5,maxReferencePdfs:1}}}),Fvr=S({"src/lib/types/elicitation.ts"(){"use strict"}}),Uvr=S({"src/lib/types/dynamic.ts"(){"use strict"}}),Bvr=S({"src/lib/types/streamDedup.ts"(){"use strict"}}),zvr=S({"src/lib/types/noOutputSentinel.ts"(){"use strict"}}),jvr=S({"src/lib/types/video.ts"(){"use strict"}}),dve,qvr=S({"src/lib/types/avatar.ts"(){"use strict";dve=["mp4","webm","mov"]}}),pve,Gvr=S({"src/lib/types/music.ts"(){"use strict";pve=["mp3","wav","flac","ogg"]}}),Hvr=S({"src/lib/types/replicate.ts"(){"use strict"}}),Vvr=S({"src/lib/types/mediaCatalog.ts"(){"use strict"}}),Wvr=S({"src/lib/types/safeFetch.ts"(){"use strict"}}),Kvr=S({"src/lib/types/modelPool.ts"(){"use strict"}}),Jvr=S({"src/lib/types/requestRouter.ts"(){"use strict"}}),Yvr=S({"src/lib/types/classifierRouter.ts"(){"use strict"}}),Zvr=S({"src/lib/types/agentNetwork.ts"(){"use strict"}}),Xvr=S({"src/lib/types/localUsage.ts"(){"use strict"}}),Qvr=S({"src/lib/types/dispatch.ts"(){"use strict"}}),yt=S({"src/lib/types/index.ts"(){"use strict";cpr(),upr(),Amr(),Imr(),Rmr(),Mmr(),Pmr(),Dmr(),Omr(),$mr(),Fmr(),Umr(),zmr(),ghr(),yhr(),vhr(),_hr(),whr(),bhr(),Thr(),Ehr(),Shr(),Chr(),khr(),xhr(),Ahr(),Ihr(),Rhr(),Mhr(),Phr(),Dhr(),Ohr(),Nhr(),Lhr(),$hr(),Fhr(),Uhr(),Bhr(),zhr(),jhr(),$yr(),Vyr(),Wyr(),Kyr(),Jyr(),Xyr(),Qyr(),evr(),tvr(),nvr(),ovr(),svr(),ivr(),avr(),lvr(),cvr(),uvr(),dvr(),pvr(),mvr(),hvr(),fvr(),gvr(),yvr(),vvr(),_vr(),wvr(),Evr(),Svr(),Cvr(),Mvr(),Pvr(),Dvr(),Ovr(),Nvr(),Lvr(),$vr(),Fvr(),Uvr(),Bvr(),zvr(),jvr(),qvr(),Gvr(),Hvr(),Vvr(),Wvr(),Kvr(),Jvr(),Yvr(),Zvr(),Xvr(),Qvr()}});function ic(e){if(e!==void 0){if(typeof e=="number"){if(e<=0)throw new Error(`Timeout must be positive, got: ${e}`);return e}if(typeof e=="string"){const t=e.match(/^(\d+(?:\.\d+)?)(ms|s|m|h)?$/);if(!t)throw new Error(`Invalid timeout format: ${e}. Use formats like '30s', '2m', '500ms', or '1.5h'`);const r=parseFloat(t[1]);if(r<=0)throw new Error(`Timeout must be positive, got: ${r}`);switch(t[2]||"ms"){case"ms":return r;case"s":return r*1e3;case"m":return r*60*1e3;case"h":return r*60*60*1e3;default:return r}}throw new Error(`Invalid timeout type: ${typeof e}`)}}function e0r(e,t="generate"){if(t==="stream")return F1.streaming;const r=e.toLowerCase().replace("_","-");return F1.providers[r]||F1.global}async function t0r(e,t,r,n){const o=ic(t);if(!o)return e;const s=new Promise((i,a)=>{setTimeout(()=>{a(new Wc(`${r} ${n} operation timed out after ${o}ms`,o,r,n))},o)});return Promise.race([e,s])}function ac(e,t,r){const n=ic(e);if(!n)return null;const o=new AbortController,s=()=>{o.abort(new Wc(`${t} ${r} operation timed out after ${e}`,n,t,r))};let i=setTimeout(s,n);return{controller:o,cleanup:()=>{clearTimeout(i)},reset:()=>{o.signal.aborted||(clearTimeout(i),i=setTimeout(s,n))},timeoutMs:n}}function $1(e,t){return e&&t?AbortSignal.any([e,t]):e??t}function r0r(e,t){if(!e||!t)return{signal:e??t,dispose:()=>{}};const r=new AbortController,n=[e,t],o=[],s=()=>{for(const{source:a,listener:l}of o)a.removeEventListener("abort",l);o.length=0},i=a=>{r.signal.aborted||r.abort(a.reason),s()};for(const a of n){const l=()=>i(a);a.addEventListener("abort",l,{once:!0}),o.push({source:a,listener:l})}for(const a of n)if(a.aborted){i(a);break}return{signal:r.signal,dispose:s}}function mve(e){const t=new AbortController,r=e.filter(s=>s!==void 0),n=r.find(s=>s.aborted);if(n)return t.abort(n.reason),t;if(r.length===0)return t;const o=AbortSignal.any(r);return o.addEventListener("abort",()=>{t.signal.aborted||t.abort(o.reason)},{once:!0}),t.__nlMergedSignal=o,t}var Wc,F1,za=S({"src/lib/utils/timeout.ts"(){"use strict";Wc=class idr extends Error{constructor(t,r,n,o){super(t),this.timeout=r,this.provider=n,this.operation=o,this.name="TimeoutError",typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,idr)}timeout;provider;operation},F1={global:"30s",streaming:"2m",providers:{openai:"30s",bedrock:"45s",vertex:"60s",anthropic:"60s",azure:"30s","google-ai":"30s",huggingface:"2m",ollama:"5m",mistral:"45s",litellm:"5m"},tools:{default:"10s",filesystem:"5s",network:"30s",computation:"2m"}}}}),U1,ZT,XT,QT,B1=S({"src/lib/hitl/hitlErrors.ts"(){"use strict";U1=class extends Error{constructor(e,t){super(e),this.confirmationId=t,this.name="HITLError"}confirmationId},ZT=class extends U1{constructor(e,t,r,n){super(e,n),this.toolName=t,this.reason=r,this.name="HITLUserRejectedError"}toolName;reason},XT=class extends U1{constructor(e,t,r){super(e,t),this.timeout=r,this.name="HITLTimeoutError"}timeout},QT=class extends U1{constructor(e){super(e),this.name="HITLConfigurationError"}}}}),eE={};he(eE,{CircuitBreaker:()=>j1,ERROR_CODES:()=>Xe,ErrorFactory:()=>ke,NeuroLinkError:()=>Ne,isAbortError:()=>mr,isRecoverableError:()=>z1,isRetriableError:()=>Tz,logStructuredError:()=>fve,withRetry:()=>hve,withTimeout:()=>Ze});async function Ze(e,t,r){let n;const o=new Promise((s,i)=>{n=setTimeout(()=>{i(r||new Error(`Operation timed out after ${t}ms`))},t)});try{return await Promise.race([e,o])}finally{clearTimeout(n)}}async function hve(e,t){const{maxAttempts:r,delayMs:n,isRetriable:o=()=>!0,onRetry:s}=t;let i;for(let a=1;a<=r;a++)try{return await e()}catch(l){if(i=l instanceof Error?l:new Error(String(l)),a===r||!o(i))throw i;s&&s(a,i),await new Promise(c=>setTimeout(c,n))}throw i||new Error("Retry operation failed with no error information")}function mr(e){return!!(e instanceof DOMException&&e.name==="AbortError"||e instanceof Error&&e.name==="AbortError"||e instanceof Ne&&e.category==="abort"||e instanceof Error&&(e.message?.includes("This operation was aborted")||e.message?.includes("The operation was aborted")||e.message?.includes("The user aborted a request")||e.message?.includes("Request was aborted")))}function Tz(e){return e instanceof Ne?e.retriable:e instanceof XT?!1:[/timeout/i,/network/i,/connection/i,/temporary/i,/rate limit/i,/quota/i,/503/i,/502/i,/504/i].some(r=>r.test(e.message))}function z1(e){const t=e;if("retriable"in e&&typeof t.retriable=="boolean")return t.retriable;const r=e.message?.toLowerCase()||"";return!!(r.includes("rate limit")||r.includes("too many requests")||/\b429\b/.test(r)||r.includes("timeout")||r.includes("etimedout")||r.includes("timed out")||r.includes("econnreset")||r.includes("econnrefused")||r.includes("network")||r.includes("socket")||/\b50[0234]\b/.test(r))}function fve(e,t){const r={...e.toJSON(),...t};switch(e.severity){case"critical":f.error(`[CRITICAL] ${e.message}`,r);break;case"high":f.error(`[HIGH] ${e.message}`,r);break;case"medium":f.warn(`[MEDIUM] ${e.message}`,r);break;case"low":f.info(`[LOW] ${e.message}`,r);break}}var Xe,Ne,ke,j1,at=S({"src/lib/utils/errorHandling.ts"(){"use strict";q(),yt(),B1(),Xe={TOOL_NOT_FOUND:"TOOL_NOT_FOUND",TOOL_EXECUTION_FAILED:"TOOL_EXECUTION_FAILED",TOOL_TIMEOUT:"TOOL_TIMEOUT",TOOL_VALIDATION_FAILED:"TOOL_VALIDATION_FAILED",INVALID_PARAMETERS:"INVALID_PARAMETERS",MISSING_REQUIRED_PARAM:"MISSING_REQUIRED_PARAM",MEMORY_EXHAUSTED:"MEMORY_EXHAUSTED",NETWORK_ERROR:"NETWORK_ERROR",PERMISSION_DENIED:"PERMISSION_DENIED",PROXY_WORKER_LIFECYCLE_FAILED:"PROXY_WORKER_LIFECYCLE_FAILED",PROVIDER_NOT_AVAILABLE:"PROVIDER_NOT_AVAILABLE",PROVIDER_AUTH_FAILED:"PROVIDER_AUTH_FAILED",PROVIDER_QUOTA_EXCEEDED:"PROVIDER_QUOTA_EXCEEDED",OPERATION_ABORTED:"OPERATION_ABORTED",INVALID_CONFIGURATION:"INVALID_CONFIGURATION",MISSING_CONFIGURATION:"MISSING_CONFIGURATION",INVALID_VIDEO_RESOLUTION:"INVALID_VIDEO_RESOLUTION",INVALID_VIDEO_LENGTH:"INVALID_VIDEO_LENGTH",INVALID_VIDEO_ASPECT_RATIO:"INVALID_VIDEO_ASPECT_RATIO",INVALID_VIDEO_AUDIO:"INVALID_VIDEO_AUDIO",INVALID_VIDEO_MODE:"INVALID_VIDEO_MODE",MISSING_VIDEO_IMAGE:"MISSING_VIDEO_IMAGE",EMPTY_VIDEO_PROMPT:"EMPTY_VIDEO_PROMPT",VIDEO_PROMPT_TOO_LONG:"VIDEO_PROMPT_TOO_LONG",EMPTY_IMAGE_PATH:"EMPTY_IMAGE_PATH",INVALID_IMAGE_TYPE:"INVALID_IMAGE_TYPE",IMAGE_TOO_LARGE:"IMAGE_TOO_LARGE",IMAGE_TOO_SMALL:"IMAGE_TOO_SMALL",INVALID_IMAGE_FORMAT:"INVALID_IMAGE_FORMAT",INVALID_IMAGE_SIZE:"INVALID_IMAGE_SIZE",IMAGE_BUFFER_INVALID:"IMAGE_BUFFER_INVALID",FILE_PROCESSING_FAILED:"FILE_PROCESSING_FAILED",CSV_PROCESSING_FAILED:"CSV_PROCESSING_FAILED",PDF_PAGE_LIMIT_EXCEEDED:"PDF_PAGE_LIMIT_EXCEEDED",PDF_AGGREGATE_PAGE_LIMIT_EXCEEDED:"PDF_AGGREGATE_PAGE_LIMIT_EXCEEDED",PDF_AGGREGATE_SIZE_LIMIT_EXCEEDED:"PDF_AGGREGATE_SIZE_LIMIT_EXCEEDED",PDF_PAGE_COUNT_UNVERIFIABLE:"PDF_PAGE_COUNT_UNVERIFIABLE",PDF_PASSWORD_REQUIRED:"PDF_PASSWORD_REQUIRED",PDF_INCORRECT_PASSWORD:"PDF_INCORRECT_PASSWORD",RATE_LIMITER_QUEUE_FULL:"RATE_LIMITER_QUEUE_FULL",RATE_LIMITER_QUEUE_TIMEOUT:"RATE_LIMITER_QUEUE_TIMEOUT",RATE_LIMITER_RESET:"RATE_LIMITER_RESET",SCORER_NOT_FOUND:"SCORER_NOT_FOUND",EVALUATION_VALIDATION_FAILED:"EVALUATION_VALIDATION_FAILED",EVALUATION_TIMEOUT:"EVALUATION_TIMEOUT",EVALUATION_EXECUTION_FAILED:"EVALUATION_EXECUTION_FAILED",MISSING_PPT_PROPERTIES:"MISSING_PPT_PROPERTIES",INVALID_PPT_PAGES:"INVALID_PPT_PAGES",INVALID_PPT_FORMAT:"INVALID_PPT_FORMAT",INVALID_PPT_PROVIDER:"INVALID_PPT_PROVIDER",INVALID_PPT_OUTPUT_OPTIONS:"INVALID_PPT_OUTPUT_OPTIONS",INVALID_PPT_OUTPUT_PATH:"INVALID_PPT_OUTPUT_PATH",INVALID_PPT_LOGO_PATH:"INVALID_PPT_LOGO_PATH",INVALID_PPT_MODE:"INVALID_PPT_MODE",INVALID_PPT_PROMPT:"INVALID_PPT_PROMPT",CSV_INVALID_INPUT:"CSV_INVALID_INPUT",CSV_ROW_INVALID:"CSV_ROW_INVALID",CSV_FILE_ACCESS_FAILED:"CSV_FILE_ACCESS_FAILED",CSV_PARSE_FAILED:"CSV_PARSE_FAILED"},Ne=class extends Error{code;category;severity;retriable;retryAfterMs;context;timestamp;toolName;serverId;constructor(e){super(e.message),this.name="NeuroLinkError",this.code=e.code,this.category=e.category,this.severity=e.severity,this.retriable=e.retriable,this.retryAfterMs=e.retryAfterMs,this.context=e.context||{},this.timestamp=new Date,this.toolName=e.toolName,this.serverId=e.serverId,e.originalError&&(this.stack=e.originalError.stack,this.context.originalMessage=e.originalError.message)}toJSON(){return{code:this.code,message:this.message,category:this.category,severity:this.severity,retriable:this.retriable,context:this.context,timestamp:this.timestamp,toolName:this.toolName,serverId:this.serverId}}},ke=class{static toolNotFound(e,t){return new Ne({code:Xe.TOOL_NOT_FOUND,message:`Tool '${e}' not found`,category:"validation",severity:"medium",retriable:!1,context:{toolName:e,availableTools:t},toolName:e})}static toolExecutionFailed(e,t,r){return new Ne({code:Xe.TOOL_EXECUTION_FAILED,message:`Tool '${e}' execution failed: ${t.message}`,category:"execution",severity:"high",retriable:!0,originalError:t,toolName:e,serverId:r})}static toolTimeout(e,t,r,n){const o=n?.exhausted?`exhausted its ${n.totalTimeoutMs}ms total budget`:n?.maxAttempts&&n.maxAttempts>1?`timed out after ${t}ms on attempt ${n.attempt??1} of ${n.maxAttempts}`:`timed out after ${t}ms`;return new Ne({code:Xe.TOOL_TIMEOUT,message:`Tool '${e}' ${o}`,category:"timeout",severity:"high",retriable:n?.exhausted!==!0,context:{timeoutMs:t,...n??{}},toolName:e,serverId:r})}static invalidParameters(e,t,r){return new Ne({code:Xe.INVALID_PARAMETERS,message:`Invalid parameters for tool '${e}': ${t.message}`,category:"validation",severity:"medium",retriable:!1,context:{providedParams:r},originalError:t,toolName:e})}static networkError(e,t,r){return new Ne({code:Xe.NETWORK_ERROR,message:`Network error in tool '${e}': ${t.message}`,category:"network",severity:"high",retriable:!0,originalError:t,toolName:e,serverId:r})}static memoryExhausted(e,t){return new Ne({code:Xe.MEMORY_EXHAUSTED,message:`Memory exhausted during tool '${e}' execution (${t}MB used)`,category:"resource",severity:"critical",retriable:!1,context:{memoryUsageMB:t},toolName:e})}static aborted(e){const t=new Ne({code:Xe.OPERATION_ABORTED,message:e?.message||"The operation was aborted",category:"abort",severity:"low",retriable:!1,context:{},originalError:e});return t.name="AbortError",t}static missingConfiguration(e,t){return new Ne({code:Xe.MISSING_CONFIGURATION,message:`Missing required configuration: ${e}`,category:"validation",severity:"high",retriable:!1,context:t||{}})}static invalidConfiguration(e,t,r){return new Ne({code:Xe.INVALID_CONFIGURATION,message:`Invalid configuration for '${e}': ${t}`,category:"validation",severity:"high",retriable:!1,context:r||{}})}static csvInvalidInput(e){return new Ne({code:Xe.CSV_INVALID_INPUT,message:e,category:"validation",severity:"medium",retriable:!1,context:{}})}static csvRowInvalid(e,t){return new Ne({code:Xe.CSV_ROW_INVALID,message:e,category:"validation",severity:"medium",retriable:!1,context:{rowNumber:t}})}static csvFileAccessFailed(e,t,r){return new Ne({code:Xe.CSV_FILE_ACCESS_FAILED,message:e,category:"resource",severity:"high",retriable:!1,context:{filePath:t},originalError:r})}static csvParseFailed(e,t,r){return new Ne({code:Xe.CSV_PARSE_FAILED,message:e,category:"execution",severity:"medium",retriable:!1,context:t,originalError:r})}static invalidVideoResolution(e){return new Ne({code:Xe.INVALID_VIDEO_RESOLUTION,message:`Invalid resolution '${e}'. Use '720p' or '1080p'`,category:"validation",severity:"medium",retriable:!1,context:{field:"output.video.resolution",providedValue:e,suggestions:["Use '720p' for standard HD","Use '1080p' for full HD"]}})}static invalidVideoLength(e){return new Ne({code:Xe.INVALID_VIDEO_LENGTH,message:`Invalid length '${e}'. Use 4, 6, or 8 seconds`,category:"validation",severity:"medium",retriable:!1,context:{field:"output.video.length",providedValue:e,suggestions:["Use 4 for short clips","Use 6 for balanced duration (recommended)","Use 8 for longer videos"]}})}static invalidVideoAspectRatio(e){return new Ne({code:Xe.INVALID_VIDEO_ASPECT_RATIO,message:`Invalid aspect ratio '${e}'. Use '9:16' or '16:9'`,category:"validation",severity:"medium",retriable:!1,context:{field:"output.video.aspectRatio",providedValue:e,suggestions:["Use '9:16' for portrait/vertical video","Use '16:9' for landscape"]}})}static invalidVideoAudio(e){return new Ne({code:Xe.INVALID_VIDEO_AUDIO,message:`Invalid audio option '${e}'. Must be true or false`,category:"validation",severity:"medium",retriable:!1,context:{field:"output.video.audio",providedValue:e,suggestions:["Set audio: true to enable audio generation","Set audio: false to disable"]}})}static invalidVideoMode(){return new Ne({code:Xe.INVALID_VIDEO_MODE,message:"Video generation requires output.mode to be 'video'",category:"validation",severity:"medium",retriable:!1,context:{field:"output.mode",suggestions:["Set output: { mode: 'video' } for video generation"]}})}static missingVideoImage(){return new Ne({code:Xe.MISSING_VIDEO_IMAGE,message:"Video generation requires an input image",category:"validation",severity:"medium",retriable:!1,context:{field:"input.images",suggestions:["Provide an image via input.images array","Example: input: { text: 'prompt', images: [imageBuffer] }"]}})}static emptyVideoPrompt(){return new Ne({code:Xe.EMPTY_VIDEO_PROMPT,message:"Video prompt cannot be empty",category:"validation",severity:"medium",retriable:!1,context:{field:"input.text",suggestions:["Provide a text prompt describing the desired video motion/content","Example: 'Smooth camera pan with dramatic lighting'"]}})}static videoPromptTooLong(e,t){return new Ne({code:Xe.VIDEO_PROMPT_TOO_LONG,message:`Video prompt must be ${t} characters or less (got ${e})`,category:"validation",severity:"medium",retriable:!1,context:{field:"input.text",providedLength:e,maxLength:t,suggestions:[`Shorten your prompt to ${t} characters or less`,"Focus on key visual elements and camera motion"]}})}static emptyImagePath(){return new Ne({code:Xe.EMPTY_IMAGE_PATH,message:"Image path or URL cannot be empty",category:"validation",severity:"medium",retriable:!1,context:{field:"input.images",suggestions:["Provide a valid file path or URL"]}})}static invalidImageType(){return new Ne({code:Xe.INVALID_IMAGE_TYPE,message:"Image must be a Buffer, file path string, or URL",category:"validation",severity:"medium",retriable:!1,context:{field:"input.images",suggestions:["Provide image as Buffer: fs.readFileSync('image.jpg')","Or as file path string: './image.jpg'","Or as URL: 'https://example.com/image.jpg'"]}})}static pdfPageLimitExceeded(e,t,r){const n=[`Split the PDF into smaller files (max ${t} pages each)`,"Extract only the pages you need using a PDF editor","For large files, consider Google AI Studio which supports up to 2000MB file size (though page limits still apply)","Convert specific pages to images manually before processing","Bypass this limit with { enforceLimits: false } (not recommended - may cause API errors or unexpected costs)"];return new Ne({code:Xe.PDF_PAGE_LIMIT_EXCEEDED,message:`PDF page limit exceeded: ${e} pages detected, but ${r} supports maximum ${t} pages.
|
|
53
53
|
|
|
54
54
|
Alternatives:
|
|
55
55
|
`+n.map((o,s)=>`${s+1}. ${o}`).join(`
|
|
@@ -1483,7 +1483,7 @@ For video extraction, the result includes images (frames) that will be visible t
|
|
|
1483
1483
|
`);if(e===-1)return null;const t=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),aBr(t)}clear(){this._buffer=void 0}}}});function uBr(){const e={};for(const t of YOt){const r=Bk.env[t];r!==void 0&&(r.startsWith("()")||(e[t]=r))}return e}function dBr(){return"type"in Bk}var JOt,YOt,Pte,ZOt=S({"node_modules/.pnpm/@modelcontextprotocol+sdk@1.28.0_@cfworker+json-schema@4.1.1_zod@4.3.6/node_modules/@modelcontextprotocol/sdk/dist/esm/client/stdio.js"(){JOt=la(z5r(),1),Y5r(),ASt(),cBr(),YOt=Bk.platform==="win32"?["APPDATA","HOMEDRIVE","HOMEPATH","LOCALAPPDATA","PATH","PROCESSOR_ARCHITECTURE","SYSTEMDRIVE","SYSTEMROOT","TEMP","USERNAME","USERPROFILE","PROGRAMFILES"]:["HOME","LOGNAME","PATH","SHELL","TERM","USER"],Pte=class{constructor(e){this._readBuffer=new KOt,this._stderrStream=null,this._serverParams=e,(e.stderr==="pipe"||e.stderr==="overlapped")&&(this._stderrStream=new kSt)}async start(){if(this._process)throw new Error("StdioClientTransport already started! If using Client class, note that connect() calls start() automatically.");return new Promise((e,t)=>{this._process=(0,JOt.default)(this._serverParams.command,this._serverParams.args??[],{env:{...uBr(),...this._serverParams.env},stdio:["pipe","pipe",this._serverParams.stderr??"inherit"],shell:!1,windowsHide:Bk.platform==="win32"&&dBr(),cwd:this._serverParams.cwd}),this._process.on("error",r=>{t(r),this.onerror?.(r)}),this._process.on("spawn",()=>{e()}),this._process.on("close",r=>{this._process=void 0,this.onclose?.()}),this._process.stdin?.on("error",r=>{this.onerror?.(r)}),this._process.stdout?.on("data",r=>{this._readBuffer.append(r),this.processReadBuffer()}),this._process.stdout?.on("error",r=>{this.onerror?.(r)}),this._stderrStream&&this._process.stderr&&this._process.stderr.pipe(this._stderrStream)})}get stderr(){return this._stderrStream?this._stderrStream:this._process?.stderr??null}get pid(){return this._process?.pid??null}processReadBuffer(){for(;;)try{const e=this._readBuffer.readMessage();if(e===null)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}async close(){if(this._process){const e=this._process;this._process=void 0;const t=new Promise(r=>{e.once("close",()=>{r()})});try{e.stdin?.end()}catch{}if(await Promise.race([t,new Promise(r=>setTimeout(r,2e3).unref())]),e.exitCode===null){try{e.kill("SIGTERM")}catch{}await Promise.race([t,new Promise(r=>setTimeout(r,2e3).unref())])}if(e.exitCode===null)try{e.kill("SIGKILL")}catch{}}this._readBuffer.clear()}send(e){return new Promise(t=>{if(!this._process?.stdin)throw new Error("Not connected");const r=lBr(e);this._process.stdin.write(r)?t():this._process.stdin.once("drain",t)})}}}}),XOt=S({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/mini/parse.js"(){cs()}}),Dte=S({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/mini/schemas.js"(){cs(),kt(),XOt()}}),pBr=S({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/mini/checks.js"(){cs()}}),QOt=S({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/mini/iso.js"(){cs(),Dte()}}),mBr=S({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/mini/coerce.js"(){cs(),Dte()}}),eNt=S({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/mini/external.js"(){cs(),XOt(),Dte(),pBr(),cs(),bT(),g5(),QOt(),QOt(),mBr()}}),tNt=S({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4-mini/index.js"(){eNt(),eNt()}});function gL(e){return!!e._zod}function yh(e,t){return gL(e)?eR(e,t):e.safeParse(t)}function rNt(e){if(!e)return;let t;if(gL(e)?t=e._zod?.def?.shape:t=e.shape,!!t){if(typeof t=="function")try{return t()}catch{return}return t}}function hBr(e){if(gL(e)){const s=e._zod?.def;if(s){if(s.value!==void 0)return s.value;if(Array.isArray(s.values)&&s.values.length>0)return s.values[0]}}const r=e._def;if(r){if(r.value!==void 0)return r.value;if(Array.isArray(r.values)&&r.values.length>0)return r.values[0]}const n=e.value;if(n!==void 0)return n}var Ote=S({"node_modules/.pnpm/@modelcontextprotocol+sdk@1.28.0_@cfworker+json-schema@4.1.1_zod@4.3.6/node_modules/@modelcontextprotocol/sdk/dist/esm/server/zod-compat.js"(){Zh(),tNt()}});function Jg(e){return e==="completed"||e==="failed"||e==="cancelled"}var fBr=S({"node_modules/.pnpm/@modelcontextprotocol+sdk@1.28.0_@cfworker+json-schema@4.1.1_zod@4.3.6/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/interfaces.js"(){}});function nNt(e){const r=rNt(e)?.method;if(!r)throw new Error("Schema is missing a method literal");const n=hBr(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function oNt(e,t){const r=yh(e,t);if(!r.success)throw r.error;return r.data}var gBr=S({"node_modules/.pnpm/@modelcontextprotocol+sdk@1.28.0_@cfworker+json-schema@4.1.1_zod@4.3.6/node_modules/@modelcontextprotocol/sdk/dist/esm/server/zod-json-schema-compat.js"(){tNt(),Ote(),j3()}});function sNt(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function yBr(e,t){const r={...e};for(const n in t){const o=n,s=t[o];if(s===void 0)continue;const i=r[o];sNt(i)&&sNt(s)?r[o]={...i,...s}:r[o]=s}return r}var iNt,aNt,vBr=S({"node_modules/.pnpm/@modelcontextprotocol+sdk@1.28.0_@cfworker+json-schema@4.1.1_zod@4.3.6/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/protocol.js"(){Ote(),gh(),fBr(),gBr(),iNt=6e4,aNt=class{constructor(e){this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(tL,t=>{this._oncancel(t)}),this.setNotificationHandler(nL,t=>{this._onprogress(t)}),this.setRequestHandler(rL,t=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(oL,async(t,r)=>{const n=await this._taskStore.getTask(t.params.taskId,r.sessionId);if(!n)throw new Ft(Zt.InvalidParams,"Failed to retrieve task: Task not found");return{...n}}),this.setRequestHandler(iL,async(t,r)=>{const n=async()=>{const o=t.params.taskId;if(this._taskMessageQueue){let i;for(;i=await this._taskMessageQueue.dequeue(o,r.sessionId);){if(i.type==="response"||i.type==="error"){const a=i.message,l=a.id,c=this._requestResolvers.get(l);if(c)if(this._requestResolvers.delete(l),i.type==="response")c(a);else{const u=a,d=new Ft(u.error.code,u.error.message,u.error.data);c(d)}else{const u=i.type==="response"?"Response":"Error";this._onerror(new Error(`${u} handler missing for request ${l}`))}continue}await this._transport?.send(i.message,{relatedRequestId:r.requestId})}}const s=await this._taskStore.getTask(o,r.sessionId);if(!s)throw new Ft(Zt.InvalidParams,`Task not found: ${o}`);if(!Jg(s.status))return await this._waitForTaskUpdate(o,r.signal),await n();if(Jg(s.status)){const i=await this._taskStore.getTaskResult(o,r.sessionId);return this._clearTaskQueue(o),{...i,_meta:{...i._meta,[fh]:{taskId:o}}}}return await n()};return await n()}),this.setRequestHandler(aL,async(t,r)=>{try{const{tasks:n,nextCursor:o}=await this._taskStore.listTasks(t.params?.cursor,r.sessionId);return{tasks:n,nextCursor:o,_meta:{}}}catch(n){throw new Ft(Zt.InvalidParams,`Failed to list tasks: ${n instanceof Error?n.message:String(n)}`)}}),this.setRequestHandler(cL,async(t,r)=>{try{const n=await this._taskStore.getTask(t.params.taskId,r.sessionId);if(!n)throw new Ft(Zt.InvalidParams,`Task not found: ${t.params.taskId}`);if(Jg(n.status))throw new Ft(Zt.InvalidParams,`Cannot cancel task in terminal status: ${n.status}`);await this._taskStore.updateTaskStatus(t.params.taskId,"cancelled","Client cancelled task execution.",r.sessionId),this._clearTaskQueue(t.params.taskId);const o=await this._taskStore.getTask(t.params.taskId,r.sessionId);if(!o)throw new Ft(Zt.InvalidParams,`Task not found after cancellation: ${t.params.taskId}`);return{_meta:{},...o}}catch(n){throw n instanceof Ft?n:new Ft(Zt.InvalidRequest,`Failed to cancel task: ${n instanceof Error?n.message:String(n)}`)}}))}async _oncancel(e){if(!e.params.requestId)return;this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,t,r,n,o=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(n,t),startTime:Date.now(),timeout:t,maxTotalTimeout:r,resetTimeoutOnProgress:o,onTimeout:n})}_resetTimeout(e){const t=this._timeoutInfo.get(e);if(!t)return!1;const r=Date.now()-t.startTime;if(t.maxTotalTimeout&&r>=t.maxTotalTimeout)throw this._timeoutInfo.delete(e),Ft.fromError(Zt.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:t.maxTotalTimeout,totalElapsed:r});return clearTimeout(t.timeoutId),t.timeoutId=setTimeout(t.onTimeout,t.timeout),!0}_cleanupTimeout(e){const t=this._timeoutInfo.get(e);t&&(clearTimeout(t.timeoutId),this._timeoutInfo.delete(e))}async connect(e){if(this._transport)throw new Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");this._transport=e;const t=this.transport?.onclose;this._transport.onclose=()=>{t?.(),this._onclose()};const r=this.transport?.onerror;this._transport.onerror=o=>{r?.(o),this._onerror(o)};const n=this._transport?.onmessage;this._transport.onmessage=(o,s)=>{n?.(o,s),U_(o)||b4t(o)?this._onresponse(o):XN(o)?this._onrequest(o,s):w4t(o)?this._onnotification(o):this._onerror(new Error(`Unknown message type: ${JSON.stringify(o)}`))},await this._transport.start()}_onclose(){const e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(const r of this._timeoutInfo.values())clearTimeout(r.timeoutId);this._timeoutInfo.clear();for(const r of this._requestHandlerAbortControllers.values())r.abort();this._requestHandlerAbortControllers.clear();const t=Ft.fromError(Zt.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(const r of e.values())r(t)}_onerror(e){this.onerror?.(e)}_onnotification(e){const t=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;t!==void 0&&Promise.resolve().then(()=>t(e)).catch(r=>this._onerror(new Error(`Uncaught error in notification handler: ${r}`)))}_onrequest(e,t){const r=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,n=this._transport,o=e.params?._meta?.[fh]?.taskId;if(r===void 0){const c={jsonrpc:"2.0",id:e.id,error:{code:Zt.MethodNotFound,message:"Method not found"}};o&&this._taskMessageQueue?this._enqueueTaskMessage(o,{type:"error",message:c,timestamp:Date.now()},n?.sessionId).catch(u=>this._onerror(new Error(`Failed to enqueue error response: ${u}`))):n?.send(c).catch(u=>this._onerror(new Error(`Failed to send an error response: ${u}`)));return}const s=new AbortController;this._requestHandlerAbortControllers.set(e.id,s);const i=_4t(e.params)?e.params.task:void 0,a=this._taskStore?this.requestTaskStore(e,n?.sessionId):void 0,l={signal:s.signal,sessionId:n?.sessionId,_meta:e.params?._meta,sendNotification:async c=>{if(s.signal.aborted)return;const u={relatedRequestId:e.id};o&&(u.relatedTask={taskId:o}),await this.notification(c,u)},sendRequest:async(c,u,d)=>{if(s.signal.aborted)throw new Ft(Zt.ConnectionClosed,"Request was cancelled");const m={...d,relatedRequestId:e.id};o&&!m.relatedTask&&(m.relatedTask={taskId:o});const h=m.relatedTask?.taskId??o;return h&&a&&await a.updateTaskStatus(h,"input_required"),await this.request(c,u,m)},authInfo:t?.authInfo,requestId:e.id,requestInfo:t?.requestInfo,taskId:o,taskStore:a,taskRequestedTtl:i?.ttl,closeSSEStream:t?.closeSSEStream,closeStandaloneSSEStream:t?.closeStandaloneSSEStream};Promise.resolve().then(()=>{i&&this.assertTaskHandlerCapability(e.method)}).then(()=>r(e,l)).then(async c=>{if(s.signal.aborted)return;const u={result:c,jsonrpc:"2.0",id:e.id};o&&this._taskMessageQueue?await this._enqueueTaskMessage(o,{type:"response",message:u,timestamp:Date.now()},n?.sessionId):await n?.send(u)},async c=>{if(s.signal.aborted)return;const u={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(c.code)?c.code:Zt.InternalError,message:c.message??"Internal error",...c.data!==void 0&&{data:c.data}}};o&&this._taskMessageQueue?await this._enqueueTaskMessage(o,{type:"error",message:u,timestamp:Date.now()},n?.sessionId):await n?.send(u)}).catch(c=>this._onerror(new Error(`Failed to send response: ${c}`))).finally(()=>{this._requestHandlerAbortControllers.get(e.id)===s&&this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){const{progressToken:t,...r}=e.params,n=Number(t),o=this._progressHandlers.get(n);if(!o){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}const s=this._responseHandlers.get(n),i=this._timeoutInfo.get(n);if(i&&s&&i.resetTimeoutOnProgress)try{this._resetTimeout(n)}catch(a){this._responseHandlers.delete(n),this._progressHandlers.delete(n),this._cleanupTimeout(n),s(a);return}o(r)}_onresponse(e){const t=Number(e.id),r=this._requestResolvers.get(t);if(r){if(this._requestResolvers.delete(t),U_(e))r(e);else{const s=new Ft(e.error.code,e.error.message,e.error.data);r(s)}return}const n=this._responseHandlers.get(t);if(n===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(t),this._cleanupTimeout(t);let o=!1;if(U_(e)&&e.result&&typeof e.result=="object"){const s=e.result;if(s.task&&typeof s.task=="object"){const i=s.task;typeof i.taskId=="string"&&(o=!0,this._taskProgressTokens.set(i.taskId,t))}}if(o||this._progressHandlers.delete(t),U_(e))n(e);else{const s=Ft.fromError(e.error.code,e.error.message,e.error.data);n(s)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(e,t,r){const{task:n}=r??{};if(!n){try{yield{type:"result",result:await this.request(e,t,r)}}catch(s){yield{type:"error",error:s instanceof Ft?s:new Ft(Zt.InternalError,String(s))}}return}let o;try{const s=await this.request(e,G_,r);if(s.task)o=s.task.taskId,yield{type:"taskCreated",task:s.task};else throw new Ft(Zt.InternalError,"Task creation did not return a task");for(;;){const i=await this.getTask({taskId:o},r);if(yield{type:"taskStatus",task:i},Jg(i.status)){i.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:o},t,r)}:i.status==="failed"?yield{type:"error",error:new Ft(Zt.InternalError,`Task ${o} failed`)}:i.status==="cancelled"&&(yield{type:"error",error:new Ft(Zt.InternalError,`Task ${o} was cancelled`)});return}if(i.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:o},t,r)};return}const a=i.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(l=>setTimeout(l,a)),r?.signal?.throwIfAborted()}}catch(s){yield{type:"error",error:s instanceof Ft?s:new Ft(Zt.InternalError,String(s))}}}request(e,t,r){const{relatedRequestId:n,resumptionToken:o,onresumptiontoken:s,task:i,relatedTask:a}=r??{};return new Promise((l,c)=>{const u=_=>{c(_)};if(!this._transport){u(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),i&&this.assertTaskCapability(e.method)}catch(_){u(_);return}r?.signal?.throwIfAborted();const d=this._requestMessageId++,m={...e,jsonrpc:"2.0",id:d};r?.onprogress&&(this._progressHandlers.set(d,r.onprogress),m.params={...e.params,_meta:{...e.params?._meta||{},progressToken:d}}),i&&(m.params={...m.params,task:i}),a&&(m.params={...m.params,_meta:{...m.params?._meta||{},[fh]:a}});const h=_=>{this._responseHandlers.delete(d),this._progressHandlers.delete(d),this._cleanupTimeout(d),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:d,reason:String(_)}},{relatedRequestId:n,resumptionToken:o,onresumptiontoken:s}).catch(T=>this._onerror(new Error(`Failed to send cancellation: ${T}`)));const b=_ instanceof Ft?_:new Ft(Zt.RequestTimeout,String(_));c(b)};this._responseHandlers.set(d,_=>{if(!r?.signal?.aborted){if(_ instanceof Error)return c(_);try{const b=yh(t,_.result);b.success?l(b.data):c(b.error)}catch(b){c(b)}}}),r?.signal?.addEventListener("abort",()=>{h(r?.signal?.reason)});const g=r?.timeout??iNt,y=()=>h(Ft.fromError(Zt.RequestTimeout,"Request timed out",{timeout:g}));this._setupTimeout(d,g,r?.maxTotalTimeout,y,r?.resetTimeoutOnProgress??!1);const v=a?.taskId;if(v){const _=b=>{const T=this._responseHandlers.get(d);T?T(b):this._onerror(new Error(`Response handler missing for side-channeled request ${d}`))};this._requestResolvers.set(d,_),this._enqueueTaskMessage(v,{type:"request",message:m,timestamp:Date.now()}).catch(b=>{this._cleanupTimeout(d),c(b)})}else this._transport.send(m,{relatedRequestId:n,resumptionToken:o,onresumptiontoken:s}).catch(_=>{this._cleanupTimeout(d),c(_)})})}async getTask(e,t){return this.request({method:"tasks/get",params:e},sL,t)}async getTaskResult(e,t,r){return this.request({method:"tasks/result",params:e},t,r)}async listTasks(e,t){return this.request({method:"tasks/list",params:e},lL,t)}async cancelTask(e,t){return this.request({method:"tasks/cancel",params:e},F4t,t)}async notification(e,t){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(e.method);const r=t?.relatedTask?.taskId;if(r){const i={...e,jsonrpc:"2.0",params:{...e.params,_meta:{...e.params?._meta||{},[fh]:t.relatedTask}}};await this._enqueueTaskMessage(r,{type:"notification",message:i,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(e.method)&&!e.params&&!t?.relatedRequestId&&!t?.relatedTask){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let i={...e,jsonrpc:"2.0"};t?.relatedTask&&(i={...i,params:{...i.params,_meta:{...i.params?._meta||{},[fh]:t.relatedTask}}}),this._transport?.send(i,t).catch(a=>this._onerror(a))});return}let s={...e,jsonrpc:"2.0"};t?.relatedTask&&(s={...s,params:{...s.params,_meta:{...s.params?._meta||{},[fh]:t.relatedTask}}}),await this._transport.send(s,t)}setRequestHandler(e,t){const r=nNt(e);this.assertRequestHandlerCapability(r),this._requestHandlers.set(r,(n,o)=>{const s=oNt(e,n);return Promise.resolve(t(s,o))})}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,t){const r=nNt(e);this._notificationHandlers.set(r,n=>{const o=oNt(e,n);return Promise.resolve(t(o))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){const t=this._taskProgressTokens.get(e);t!==void 0&&(this._progressHandlers.delete(t),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,t,r){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");const n=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,t,r,n)}async _clearTaskQueue(e,t){if(this._taskMessageQueue){const r=await this._taskMessageQueue.dequeueAll(e,t);for(const n of r)if(n.type==="request"&&XN(n.message)){const o=n.message.id,s=this._requestResolvers.get(o);s?(s(new Ft(Zt.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(o)):this._onerror(new Error(`Resolver missing for request ${o} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,t){let r=this._options?.defaultTaskPollInterval??1e3;try{const n=await this._taskStore?.getTask(e);n?.pollInterval&&(r=n.pollInterval)}catch{}return new Promise((n,o)=>{if(t.aborted){o(new Ft(Zt.InvalidRequest,"Request cancelled"));return}const s=setTimeout(n,r);t.addEventListener("abort",()=>{clearTimeout(s),o(new Ft(Zt.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,t){const r=this._taskStore;if(!r)throw new Error("No task store configured");return{createTask:async n=>{if(!e)throw new Error("No request provided");return await r.createTask(n,e.id,{method:e.method,params:e.params},t)},getTask:async n=>{const o=await r.getTask(n,t);if(!o)throw new Ft(Zt.InvalidParams,"Failed to retrieve task: Task not found");return o},storeTaskResult:async(n,o,s)=>{await r.storeTaskResult(n,o,s,t);const i=await r.getTask(n,t);if(i){const a=Gk.parse({method:"notifications/tasks/status",params:i});await this.notification(a),Jg(i.status)&&this._cleanupTaskProgressHandler(n)}},getTaskResult:n=>r.getTaskResult(n,t),updateTaskStatus:async(n,o,s)=>{const i=await r.getTask(n,t);if(!i)throw new Ft(Zt.InvalidParams,`Task "${n}" not found - it may have been cleaned up`);if(Jg(i.status))throw new Ft(Zt.InvalidParams,`Cannot update task "${n}" from terminal status "${i.status}" to "${o}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await r.updateTaskStatus(n,o,s,t);const a=await r.getTask(n,t);if(a){const l=Gk.parse({method:"notifications/tasks/status",params:a});await this.notification(l),Jg(a.status)&&this._cleanupTaskProgressHandler(n)}},listTasks:n=>r.listTasks(n,t)}}}}}),Yg,Ys,lNt,_Br,wBr,bBr,TBr,EBr,SBr,CBr,kBr,xBr,ABr,IBr,RBr,MBr,PBr,DBr,OBr,NBr,LBr,$Br,FBr,UBr,BBr,zBr,jBr,qBr,GBr,HBr,VBr,WBr,KBr,JBr,YBr,ZBr,XBr,QBr,ezr,tzr,rzr,nzr,ozr,szr,izr,azr,lzr,czr,uzr,dzr=S({"npm-stub:ajv"(){Yg={get(e,t){return t==="__esModule"?!0:t==="default"?new Proxy({},{get:Yg.get}):new Proxy(function(...r){return new Proxy({},{get:Yg.get})},{get:Yg.get,apply(r,n,o){return new Proxy({},{get:Yg.get})},construct(r,n){return new Proxy({},{get:Yg.get})}})}},Ys=new Proxy({},Yg),lNt=Ys,{BedrockClient:_Br,ListFoundationModelsCommand:wBr,BedrockRuntimeClient:bBr,ConverseCommand:TBr,ConverseStreamCommand:EBr,ImageFormat:SBr,InvokeModelCommand:CBr}=Ys,{SageMakerRuntimeClient:kBr,InvokeEndpointCommand:xBr,InvokeEndpointWithResponseStreamCommand:ABr}=Ys,{GoogleAuth:IBr,VertexAI:RBr,TextToSpeechClient:MBr}=Ys,{Webhook:PBr}=Ys,{Hippocampus:DBr,HippocampusConfig:OBr}=Ys,{createClient:NBr}=Ys,{Queue:LBr,Worker:$Br,Job:FBr,QueueScheduler:UBr,FlowProducer:BBr}=Ys,{Cron:zBr}=Ys,{parseBuffer:jBr,selectCover:qBr}=Ys,{extractRawText:GBr,convertToHtml:HBr}=Ys,{Hono:VBr}=Ys,{cors:WBr,HTTPException:KBr,logger:JBr,secureHeaders:YBr,streamSSE:ZBr,timeout:XBr}=Ys,QBr=globalThis.fetch,ezr=globalThis.Request,tzr=globalThis.Response,rzr=globalThis.Headers,nzr=globalThis.FormData,ozr=globalThis.File,szr=globalThis.Blob,izr=Ys.Agent,azr=Ys.Pool,lzr=Ys.Client,czr=Ys.Dispatcher,uzr=Ys.MockAgent}}),Zg,Zs,cNt,pzr,mzr,hzr,fzr,gzr,yzr,vzr,_zr,wzr,bzr,Tzr,Ezr,Szr,Czr,kzr,xzr,Azr,Izr,Rzr,Mzr,Pzr,Dzr,Ozr,Nzr,Lzr,$zr,Fzr,Uzr,Bzr,zzr,jzr,qzr,Gzr,Hzr,Vzr,Wzr,Kzr,Jzr,Yzr,Zzr,Xzr,Qzr,ejr,tjr,rjr,njr,ojr=S({"npm-stub:ajv-formats"(){Zg={get(e,t){return t==="__esModule"?!0:t==="default"?new Proxy({},{get:Zg.get}):new Proxy(function(...r){return new Proxy({},{get:Zg.get})},{get:Zg.get,apply(r,n,o){return new Proxy({},{get:Zg.get})},construct(r,n){return new Proxy({},{get:Zg.get})}})}},Zs=new Proxy({},Zg),cNt=Zs,{BedrockClient:pzr,ListFoundationModelsCommand:mzr,BedrockRuntimeClient:hzr,ConverseCommand:fzr,ConverseStreamCommand:gzr,ImageFormat:yzr,InvokeModelCommand:vzr}=Zs,{SageMakerRuntimeClient:_zr,InvokeEndpointCommand:wzr,InvokeEndpointWithResponseStreamCommand:bzr}=Zs,{GoogleAuth:Tzr,VertexAI:Ezr,TextToSpeechClient:Szr}=Zs,{Webhook:Czr}=Zs,{Hippocampus:kzr,HippocampusConfig:xzr}=Zs,{createClient:Azr}=Zs,{Queue:Izr,Worker:Rzr,Job:Mzr,QueueScheduler:Pzr,FlowProducer:Dzr}=Zs,{Cron:Ozr}=Zs,{parseBuffer:Nzr,selectCover:Lzr}=Zs,{extractRawText:$zr,convertToHtml:Fzr}=Zs,{Hono:Uzr}=Zs,{cors:Bzr,HTTPException:zzr,logger:jzr,secureHeaders:qzr,streamSSE:Gzr,timeout:Hzr}=Zs,Vzr=globalThis.fetch,Wzr=globalThis.Request,Kzr=globalThis.Response,Jzr=globalThis.Headers,Yzr=globalThis.FormData,Zzr=globalThis.File,Xzr=globalThis.Blob,Qzr=Zs.Agent,ejr=Zs.Pool,tjr=Zs.Client,rjr=Zs.Dispatcher,njr=Zs.MockAgent}});function sjr(){const e=new lNt({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return cNt(e),e}var uNt,ijr=S({"node_modules/.pnpm/@modelcontextprotocol+sdk@1.28.0_@cfworker+json-schema@4.1.1_zod@4.3.6/node_modules/@modelcontextprotocol/sdk/dist/esm/validation/ajv-provider.js"(){dzr(),ojr(),uNt=class{constructor(e){this._ajv=e??sjr()}getValidator(e){const t="$id"in e&&typeof e.$id=="string"?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return r=>t(r)?{valid:!0,data:r,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(t.errors)}}}}}),dNt,ajr=S({"node_modules/.pnpm/@modelcontextprotocol+sdk@1.28.0_@cfworker+json-schema@4.1.1_zod@4.3.6/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/client.js"(){gh(),dNt=class{constructor(e){this._client=e}async*callToolStream(e,t=Hk,r){const n=this._client,o={...r,task:r?.task??(n.isToolTask(e.name)?{}:void 0)},s=n.requestStream({method:"tools/call",params:e},t,o),i=n.getToolOutputValidator(e.name);for await(const a of s){if(a.type==="result"&&i){const l=a.result;if(!l.structuredContent&&!l.isError){yield{type:"error",error:new Ft(Zt.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`)};return}if(l.structuredContent)try{const c=i(l.structuredContent);if(!c.valid){yield{type:"error",error:new Ft(Zt.InvalidParams,`Structured content does not match the tool's output schema: ${c.errorMessage}`)};return}}catch(c){if(c instanceof Ft){yield{type:"error",error:c};return}yield{type:"error",error:new Ft(Zt.InvalidParams,`Failed to validate structured content: ${c instanceof Error?c.message:String(c)}`)};return}}yield a}}async getTask(e,t){return this._client.getTask({taskId:e},t)}async getTaskResult(e,t,r){return this._client.getTaskResult({taskId:e},t,r)}async listTasks(e,t){return this._client.listTasks(e?{cursor:e}:void 0,t)}async cancelTask(e,t){return this._client.cancelTask({taskId:e},t)}requestStream(e,t,r){return this._client.requestStream(e,t,r)}}}});function ljr(e,t,r){if(!e)throw new Error(`${r} does not support task creation (required for ${t})`);switch(t){case"tools/call":if(!e.tools?.call)throw new Error(`${r} does not support task creation for tools/call (required for ${t})`);break;default:break}}function cjr(e,t,r){if(!e)throw new Error(`${r} does not support task creation (required for ${t})`);switch(t){case"sampling/createMessage":if(!e.sampling?.createMessage)throw new Error(`${r} does not support task creation for sampling/createMessage (required for ${t})`);break;case"elicitation/create":if(!e.elicitation?.create)throw new Error(`${r} does not support task creation for elicitation/create (required for ${t})`);break;default:break}}var ujr=S({"node_modules/.pnpm/@modelcontextprotocol+sdk@1.28.0_@cfworker+json-schema@4.1.1_zod@4.3.6/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/helpers.js"(){}});function yL(e,t){if(!(!e||t===null||typeof t!="object")){if(e.type==="object"&&e.properties&&typeof e.properties=="object"){const r=t,n=e.properties;for(const o of Object.keys(n)){const s=n[o];r[o]===void 0&&Object.prototype.hasOwnProperty.call(s,"default")&&(r[o]=s.default),r[o]!==void 0&&yL(s,r[o])}}if(Array.isArray(e.anyOf))for(const r of e.anyOf)typeof r!="boolean"&&yL(r,t);if(Array.isArray(e.oneOf))for(const r of e.oneOf)typeof r!="boolean"&&yL(r,t)}}function djr(e){if(!e)return{supportsFormMode:!1,supportsUrlMode:!1};const t=e.form!==void 0,r=e.url!==void 0;return{supportsFormMode:t||!t&&!r,supportsUrlMode:r}}var pNt,pjr=S({"node_modules/.pnpm/@modelcontextprotocol+sdk@1.28.0_@cfworker+json-schema@4.1.1_zod@4.3.6/node_modules/@modelcontextprotocol/sdk/dist/esm/client/index.js"(){vBr(),gh(),ijr(),Ote(),ajr(),ujr(),pNt=class extends aNt{constructor(e,t){super(t),this._clientInfo=e,this._cachedToolOutputValidators=new Map,this._cachedKnownTaskTools=new Set,this._cachedRequiredTaskTools=new Set,this._listChangedDebounceTimers=new Map,this._capabilities=t?.capabilities??{},this._jsonSchemaValidator=t?.jsonSchemaValidator??new uNt,t?.listChanged&&(this._pendingListChangedConfig=t.listChanged)}_setupListChangedHandlers(e){e.tools&&this._serverCapabilities?.tools?.listChanged&&this._setupListChangedHandler("tools",Ste,e.tools,async()=>(await this.listTools()).tools),e.prompts&&this._serverCapabilities?.prompts?.listChanged&&this._setupListChangedHandler("prompts",bte,e.prompts,async()=>(await this.listPrompts()).prompts),e.resources&&this._serverCapabilities?.resources?.listChanged&&this._setupListChangedHandler("resources",vte,e.resources,async()=>(await this.listResources()).resources)}get experimental(){return this._experimental||(this._experimental={tasks:new dNt(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=yBr(this._capabilities,e)}setRequestHandler(e,t){const n=rNt(e)?.method;if(!n)throw new Error("Schema is missing a method literal");let o;if(gL(n)){const i=n;o=i._zod?.def?.value??i.value}else{const i=n;o=i._def?.value??i.value}if(typeof o!="string")throw new Error("Schema method literal must be a string");const s=o;if(s==="elicitation/create"){const i=async(a,l)=>{const c=yh(Ite,a);if(!c.success){const _=c.error instanceof Error?c.error.message:String(c.error);throw new Ft(Zt.InvalidParams,`Invalid elicitation request: ${_}`)}const{params:u}=c.data;u.mode=u.mode??"form";const{supportsFormMode:d,supportsUrlMode:m}=djr(this._capabilities.elicitation);if(u.mode==="form"&&!d)throw new Ft(Zt.InvalidParams,"Client does not support form-mode elicitation requests");if(u.mode==="url"&&!m)throw new Ft(Zt.InvalidParams,"Client does not support URL-mode elicitation requests");const h=await Promise.resolve(t(a,l));if(u.task){const _=yh(G_,h);if(!_.success){const b=_.error instanceof Error?_.error.message:String(_.error);throw new Ft(Zt.InvalidParams,`Invalid task creation result: ${b}`)}return _.data}const g=yh(Rte,h);if(!g.success){const _=g.error instanceof Error?g.error.message:String(g.error);throw new Ft(Zt.InvalidParams,`Invalid elicitation result: ${_}`)}const y=g.data,v=u.mode==="form"?u.requestedSchema:void 0;if(u.mode==="form"&&y.action==="accept"&&y.content&&v&&this._capabilities.elicitation?.form?.applyDefaults)try{yL(v,y.content)}catch{}return y};return super.setRequestHandler(e,i)}if(s==="sampling/createMessage"){const i=async(a,l)=>{const c=yh(kte,a);if(!c.success){const y=c.error instanceof Error?c.error.message:String(c.error);throw new Ft(Zt.InvalidParams,`Invalid sampling request: ${y}`)}const{params:u}=c.data,d=await Promise.resolve(t(a,l));if(u.task){const y=yh(G_,d);if(!y.success){const v=y.error instanceof Error?y.error.message:String(y.error);throw new Ft(Zt.InvalidParams,`Invalid task creation result: ${v}`)}return y.data}const h=u.tools||u.toolChoice?Ate:xte,g=yh(h,d);if(!g.success){const y=g.error instanceof Error?g.error.message:String(g.error);throw new Ft(Zt.InvalidParams,`Invalid sampling result: ${y}`)}return g.data};return super.setRequestHandler(e,i)}return super.setRequestHandler(e,t)}assertCapability(e,t){if(!this._serverCapabilities?.[e])throw new Error(`Server does not support ${e} (required for ${t})`)}async connect(e,t){if(await super.connect(e),e.sessionId===void 0)try{const r=await this.request({method:"initialize",params:{protocolVersion:zk,capabilities:this._capabilities,clientInfo:this._clientInfo}},cte,t);if(r===void 0)throw new Error(`Server sent invalid initialize result: ${r}`);if(!g4t.includes(r.protocolVersion))throw new Error(`Server's protocol version is not supported: ${r.protocolVersion}`);this._serverCapabilities=r.capabilities,this._serverVersion=r.serverInfo,e.setProtocolVersion&&e.setProtocolVersion(r.protocolVersion),this._instructions=r.instructions,await this.notification({method:"notifications/initialized"}),this._pendingListChangedConfig&&(this._setupListChangedHandlers(this._pendingListChangedConfig),this._pendingListChangedConfig=void 0)}catch(r){throw this.close(),r}}getServerCapabilities(){return this._serverCapabilities}getServerVersion(){return this._serverVersion}getInstructions(){return this._instructions}assertCapabilityForMethod(e){switch(e){case"logging/setLevel":if(!this._serverCapabilities?.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._serverCapabilities?.prompts)throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":case"resources/subscribe":case"resources/unsubscribe":if(!this._serverCapabilities?.resources)throw new Error(`Server does not support resources (required for ${e})`);if(e==="resources/subscribe"&&!this._serverCapabilities.resources.subscribe)throw new Error(`Server does not support resource subscriptions (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._serverCapabilities?.tools)throw new Error(`Server does not support tools (required for ${e})`);break;case"completion/complete":if(!this._serverCapabilities?.completions)throw new Error(`Server does not support completions (required for ${e})`);break;case"initialize":break;case"ping":break}}assertNotificationCapability(e){switch(e){case"notifications/roots/list_changed":if(!this._capabilities.roots?.listChanged)throw new Error(`Client does not support roots list changed notifications (required for ${e})`);break;case"notifications/initialized":break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case"sampling/createMessage":if(!this._capabilities.sampling)throw new Error(`Client does not support sampling capability (required for ${e})`);break;case"elicitation/create":if(!this._capabilities.elicitation)throw new Error(`Client does not support elicitation capability (required for ${e})`);break;case"roots/list":if(!this._capabilities.roots)throw new Error(`Client does not support roots capability (required for ${e})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Client does not support tasks capability (required for ${e})`);break;case"ping":break}}assertTaskCapability(e){ljr(this._serverCapabilities?.tasks?.requests,e,"Server")}assertTaskHandlerCapability(e){this._capabilities&&cjr(this._capabilities.tasks?.requests,e,"Client")}async ping(e){return this.request({method:"ping"},Vg,e)}async complete(e,t){return this.request({method:"completion/complete",params:e},Mte,t)}async setLoggingLevel(e,t){return this.request({method:"logging/setLevel",params:{level:e}},Vg,t)}async getPrompt(e,t){return this.request({method:"prompts/get",params:e},wte,t)}async listPrompts(e,t){return this.request({method:"prompts/list",params:e},_te,t)}async listResources(e,t){return this.request({method:"resources/list",params:e},fte,t)}async listResourceTemplates(e,t){return this.request({method:"resources/templates/list",params:e},gte,t)}async readResource(e,t){return this.request({method:"resources/read",params:e},yte,t)}async subscribeResource(e,t){return this.request({method:"resources/subscribe",params:e},Vg,t)}async unsubscribeResource(e,t){return this.request({method:"resources/unsubscribe",params:e},Vg,t)}async callTool(e,t=Hk,r){if(this.isToolTaskRequired(e.name))throw new Ft(Zt.InvalidRequest,`Tool "${e.name}" requires task-based execution. Use client.experimental.tasks.callToolStream() instead.`);const n=await this.request({method:"tools/call",params:e},t,r),o=this.getToolOutputValidator(e.name);if(o){if(!n.structuredContent&&!n.isError)throw new Ft(Zt.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`);if(n.structuredContent)try{const s=o(n.structuredContent);if(!s.valid)throw new Ft(Zt.InvalidParams,`Structured content does not match the tool's output schema: ${s.errorMessage}`)}catch(s){throw s instanceof Ft?s:new Ft(Zt.InvalidParams,`Failed to validate structured content: ${s instanceof Error?s.message:String(s)}`)}}return n}isToolTask(e){return this._serverCapabilities?.tasks?.requests?.tools?.call?this._cachedKnownTaskTools.has(e):!1}isToolTaskRequired(e){return this._cachedRequiredTaskTools.has(e)}cacheToolMetadata(e){this._cachedToolOutputValidators.clear(),this._cachedKnownTaskTools.clear(),this._cachedRequiredTaskTools.clear();for(const t of e){if(t.outputSchema){const n=this._jsonSchemaValidator.getValidator(t.outputSchema);this._cachedToolOutputValidators.set(t.name,n)}const r=t.execution?.taskSupport;(r==="required"||r==="optional")&&this._cachedKnownTaskTools.add(t.name),r==="required"&&this._cachedRequiredTaskTools.add(t.name)}}getToolOutputValidator(e){return this._cachedToolOutputValidators.get(e)}async listTools(e,t){const r=await this.request({method:"tools/list",params:e},Ete,t);return this.cacheToolMetadata(r.tools),r}_setupListChangedHandler(e,t,r,n){const o=uOt.safeParse(r);if(!o.success)throw new Error(`Invalid ${e} listChanged options: ${o.error.message}`);if(typeof r.onChanged!="function")throw new Error(`Invalid ${e} listChanged options: onChanged must be a function`);const{autoRefresh:s,debounceMs:i}=o.data,{onChanged:a}=r,l=async()=>{if(!s){a(null,null);return}try{const u=await n();a(null,u)}catch(u){const d=u instanceof Error?u:new Error(String(u));a(d,null)}},c=()=>{if(i){const u=this._listChangedDebounceTimers.get(e);u&&clearTimeout(u);const d=setTimeout(l,i);this._listChangedDebounceTimers.set(e,d)}else l()};this.setNotificationHandler(t,c)}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}}}});function mjr(e){const t=globalThis.DOMException;return typeof t=="function"?new t(e,"SyntaxError"):new SyntaxError(e)}function Nte(e){return e instanceof Error?"errors"in e&&Array.isArray(e.errors)?e.errors.map(Nte).join(", "):"cause"in e&&e.cause instanceof Error?`${e}: ${Nte(e.cause)}`:e.message:`${e}`}function mNt(e){return{type:e.type,message:e.message,code:e.code,defaultPrevented:e.defaultPrevented,cancelable:e.cancelable,timeStamp:e.timeStamp}}function hjr(){const e="document"in globalThis?globalThis.document:void 0;return e&&typeof e=="object"&&"baseURI"in e&&typeof e.baseURI=="string"?e.baseURI:void 0}var Lte,$te,vL,gr,xs,Hn,ld,sl,Xg,V_,_L,wL,Wk,W_,Kk,vh,K_,J_,Y_,Jk,fu,Fte,Ute,Bte,hNt,zte,jte,Yk,qte,Gte,Zk,fjr=S({"node_modules/.pnpm/eventsource@3.0.7/node_modules/eventsource/dist/index.js"(){tj(),Lte=class extends Event{constructor(e,t){var r,n;super(e),this.code=(r=t?.code)!=null?r:void 0,this.message=(n=t?.message)!=null?n:void 0}[Symbol.for("nodejs.util.inspect.custom")](e,t,r){return r(mNt(this),t)}[Symbol.for("Deno.customInspect")](e,t){return e(mNt(this),t)}},$te=e=>{throw TypeError(e)},vL=(e,t,r)=>t.has(e)||$te("Cannot "+r),gr=(e,t,r)=>(vL(e,t,"read from private field"),r?r.call(e):t.get(e)),xs=(e,t,r)=>t.has(e)?$te("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,r),Hn=(e,t,r,n)=>(vL(e,t,"write to private field"),t.set(e,r),r),ld=(e,t,r)=>(vL(e,t,"access private method"),r),Zk=class extends EventTarget{constructor(e,t){var r,n;super(),xs(this,fu),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,xs(this,sl),xs(this,Xg),xs(this,V_),xs(this,_L),xs(this,wL),xs(this,Wk),xs(this,W_),xs(this,Kk,null),xs(this,vh),xs(this,K_),xs(this,J_,null),xs(this,Y_,null),xs(this,Jk,null),xs(this,Ute,async o=>{var s;gr(this,K_).reset();const{body:i,redirected:a,status:l,headers:c}=o;if(l===204){ld(this,fu,Yk).call(this,"Server sent HTTP 204, not reconnecting",204),this.close();return}if(a?Hn(this,V_,new URL(o.url)):Hn(this,V_,void 0),l!==200){ld(this,fu,Yk).call(this,`Non-200 status code (${l})`,l);return}if(!(c.get("content-type")||"").startsWith("text/event-stream")){ld(this,fu,Yk).call(this,'Invalid content type, expected "text/event-stream"',l);return}if(gr(this,sl)===this.CLOSED)return;Hn(this,sl,this.OPEN);const u=new Event("open");if((s=gr(this,Jk))==null||s.call(this,u),this.dispatchEvent(u),typeof i!="object"||!i||!("getReader"in i)){ld(this,fu,Yk).call(this,"Invalid response body, expected a web ReadableStream",l),this.close();return}const d=new TextDecoder,m=i.getReader();let h=!0;do{const{done:g,value:y}=await m.read();y&&gr(this,K_).feed(d.decode(y,{stream:!g})),g&&(h=!1,gr(this,K_).reset(),ld(this,fu,qte).call(this))}while(h)}),xs(this,Bte,o=>{Hn(this,vh,void 0),!(o.name==="AbortError"||o.type==="aborted")&&ld(this,fu,qte).call(this,Nte(o))}),xs(this,zte,o=>{typeof o.id=="string"&&Hn(this,Kk,o.id);const s=new MessageEvent(o.event||"message",{data:o.data,origin:gr(this,V_)?gr(this,V_).origin:gr(this,Xg).origin,lastEventId:o.id||""});gr(this,Y_)&&(!o.event||o.event==="message")&&gr(this,Y_).call(this,s),this.dispatchEvent(s)}),xs(this,jte,o=>{Hn(this,Wk,o)}),xs(this,Gte,()=>{Hn(this,W_,void 0),gr(this,sl)===this.CONNECTING&&ld(this,fu,Fte).call(this)});try{if(e instanceof URL)Hn(this,Xg,e);else if(typeof e=="string")Hn(this,Xg,new URL(e,hjr()));else throw new Error("Invalid URL")}catch{throw mjr("An invalid or illegal string was specified")}Hn(this,K_,Xz({onEvent:gr(this,zte),onRetry:gr(this,jte)})),Hn(this,sl,this.CONNECTING),Hn(this,Wk,3e3),Hn(this,wL,(r=t?.fetch)!=null?r:globalThis.fetch),Hn(this,_L,(n=t?.withCredentials)!=null?n:!1),ld(this,fu,Fte).call(this)}get readyState(){return gr(this,sl)}get url(){return gr(this,Xg).href}get withCredentials(){return gr(this,_L)}get onerror(){return gr(this,J_)}set onerror(e){Hn(this,J_,e)}get onmessage(){return gr(this,Y_)}set onmessage(e){Hn(this,Y_,e)}get onopen(){return gr(this,Jk)}set onopen(e){Hn(this,Jk,e)}addEventListener(e,t,r){const n=t;super.addEventListener(e,n,r)}removeEventListener(e,t,r){const n=t;super.removeEventListener(e,n,r)}close(){gr(this,W_)&&clearTimeout(gr(this,W_)),gr(this,sl)!==this.CLOSED&&(gr(this,vh)&&gr(this,vh).abort(),Hn(this,sl,this.CLOSED),Hn(this,vh,void 0))}},sl=new WeakMap,Xg=new WeakMap,V_=new WeakMap,_L=new WeakMap,wL=new WeakMap,Wk=new WeakMap,W_=new WeakMap,Kk=new WeakMap,vh=new WeakMap,K_=new WeakMap,J_=new WeakMap,Y_=new WeakMap,Jk=new WeakMap,fu=new WeakSet,Fte=function(){Hn(this,sl,this.CONNECTING),Hn(this,vh,new AbortController),gr(this,wL)(gr(this,Xg),ld(this,fu,hNt).call(this)).then(gr(this,Ute)).catch(gr(this,Bte))},Ute=new WeakMap,Bte=new WeakMap,hNt=function(){var e;const t={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...gr(this,Kk)?{"Last-Event-ID":gr(this,Kk)}:void 0},cache:"no-store",signal:(e=gr(this,vh))==null?void 0:e.signal};return"window"in globalThis&&(t.credentials=this.withCredentials?"include":"same-origin"),t},zte=new WeakMap,jte=new WeakMap,Yk=function(e,t){var r;gr(this,sl)!==this.CLOSED&&Hn(this,sl,this.CLOSED);const n=new Lte("error",{code:t,message:e});(r=gr(this,J_))==null||r.call(this,n),this.dispatchEvent(n)},qte=function(e,t){var r;if(gr(this,sl)===this.CLOSED)return;Hn(this,sl,this.CONNECTING);const n=new Lte("error",{code:t,message:e});(r=gr(this,J_))==null||r.call(this,n),this.dispatchEvent(n),Hn(this,W_,setTimeout(gr(this,Gte),gr(this,Wk)))},Gte=new WeakMap,Zk.CONNECTING=0,Zk.OPEN=1,Zk.CLOSED=2}});function bL(e){return e?e instanceof Headers?Object.fromEntries(e.entries()):Array.isArray(e)?Object.fromEntries(e):{...e}:{}}function fNt(e=fetch,t){return t?async(r,n)=>{const o={...t,...n,headers:n?.headers?{...bL(t.headers),...bL(n.headers)}:t.headers};return e(r,o)}:e}var gNt=S({"node_modules/.pnpm/@modelcontextprotocol+sdk@1.28.0_@cfworker+json-schema@4.1.1_zod@4.3.6/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/transport.js"(){}}),Qg,Xs,yNt,gjr,yjr,vjr,_jr,wjr,bjr,Tjr,Ejr,Sjr,Cjr,kjr,xjr,Ajr,Ijr,Rjr,Mjr,Pjr,Djr,Ojr,Njr,Ljr,$jr,Fjr,Ujr,Bjr,zjr,jjr,qjr,Gjr,Hjr,Vjr,Wjr,Kjr,Jjr,Yjr,Zjr,Xjr,Qjr,eqr,tqr,rqr,nqr,oqr,sqr,iqr,aqr,lqr=S({"npm-stub:pkce-challenge"(){Qg={get(e,t){return t==="__esModule"?!0:t==="default"?new Proxy({},{get:Qg.get}):new Proxy(function(...r){return new Proxy({},{get:Qg.get})},{get:Qg.get,apply(r,n,o){return new Proxy({},{get:Qg.get})},construct(r,n){return new Proxy({},{get:Qg.get})}})}},Xs=new Proxy({},Qg),yNt=Xs,{BedrockClient:gjr,ListFoundationModelsCommand:yjr,BedrockRuntimeClient:vjr,ConverseCommand:_jr,ConverseStreamCommand:wjr,ImageFormat:bjr,InvokeModelCommand:Tjr}=Xs,{SageMakerRuntimeClient:Ejr,InvokeEndpointCommand:Sjr,InvokeEndpointWithResponseStreamCommand:Cjr}=Xs,{GoogleAuth:kjr,VertexAI:xjr,TextToSpeechClient:Ajr}=Xs,{Webhook:Ijr}=Xs,{Hippocampus:Rjr,HippocampusConfig:Mjr}=Xs,{createClient:Pjr}=Xs,{Queue:Djr,Worker:Ojr,Job:Njr,QueueScheduler:Ljr,FlowProducer:$jr}=Xs,{Cron:Fjr}=Xs,{parseBuffer:Ujr,selectCover:Bjr}=Xs,{extractRawText:zjr,convertToHtml:jjr}=Xs,{Hono:qjr}=Xs,{cors:Gjr,HTTPException:Hjr,logger:Vjr,secureHeaders:Wjr,streamSSE:Kjr,timeout:Jjr}=Xs,Yjr=globalThis.fetch,Zjr=globalThis.Request,Xjr=globalThis.Response,Qjr=globalThis.Headers,eqr=globalThis.FormData,tqr=globalThis.File,rqr=globalThis.Blob,nqr=Xs.Agent,oqr=Xs.Pool,sqr=Xs.Client,iqr=Xs.Dispatcher,aqr=Xs.MockAgent}}),yi,vNt,Hte,_Nt,wNt,bNt,TNt,Vte,ENt,SNt,CNt,cqr,uqr,kNt=S({"node_modules/.pnpm/@modelcontextprotocol+sdk@1.28.0_@cfworker+json-schema@4.1.1_zod@4.3.6/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/auth.js"(){dt(),yi=GB().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:iz.custom,message:"URL must be parseable",fatal:!0}),GI}).refine(e=>{const t=new URL(e);return t.protocol!=="javascript:"&&t.protocol!=="data:"&&t.protocol!=="vbscript:"},{message:"URL cannot use javascript:, data:, or vbscript: scheme"}),vNt=Ns({resource:ce().url(),authorization_servers:rt(yi).optional(),jwks_uri:ce().url().optional(),scopes_supported:rt(ce()).optional(),bearer_methods_supported:rt(ce()).optional(),resource_signing_alg_values_supported:rt(ce()).optional(),resource_name:ce().optional(),resource_documentation:ce().optional(),resource_policy_uri:ce().url().optional(),resource_tos_uri:ce().url().optional(),tls_client_certificate_bound_access_tokens:tn().optional(),authorization_details_types_supported:rt(ce()).optional(),dpop_signing_alg_values_supported:rt(ce()).optional(),dpop_bound_access_tokens_required:tn().optional()}),Hte=Ns({issuer:ce(),authorization_endpoint:yi,token_endpoint:yi,registration_endpoint:yi.optional(),scopes_supported:rt(ce()).optional(),response_types_supported:rt(ce()),response_modes_supported:rt(ce()).optional(),grant_types_supported:rt(ce()).optional(),token_endpoint_auth_methods_supported:rt(ce()).optional(),token_endpoint_auth_signing_alg_values_supported:rt(ce()).optional(),service_documentation:yi.optional(),revocation_endpoint:yi.optional(),revocation_endpoint_auth_methods_supported:rt(ce()).optional(),revocation_endpoint_auth_signing_alg_values_supported:rt(ce()).optional(),introspection_endpoint:ce().optional(),introspection_endpoint_auth_methods_supported:rt(ce()).optional(),introspection_endpoint_auth_signing_alg_values_supported:rt(ce()).optional(),code_challenge_methods_supported:rt(ce()).optional(),client_id_metadata_document_supported:tn().optional()}),_Nt=Ns({issuer:ce(),authorization_endpoint:yi,token_endpoint:yi,userinfo_endpoint:yi.optional(),jwks_uri:yi,registration_endpoint:yi.optional(),scopes_supported:rt(ce()).optional(),response_types_supported:rt(ce()),response_modes_supported:rt(ce()).optional(),grant_types_supported:rt(ce()).optional(),acr_values_supported:rt(ce()).optional(),subject_types_supported:rt(ce()),id_token_signing_alg_values_supported:rt(ce()),id_token_encryption_alg_values_supported:rt(ce()).optional(),id_token_encryption_enc_values_supported:rt(ce()).optional(),userinfo_signing_alg_values_supported:rt(ce()).optional(),userinfo_encryption_alg_values_supported:rt(ce()).optional(),userinfo_encryption_enc_values_supported:rt(ce()).optional(),request_object_signing_alg_values_supported:rt(ce()).optional(),request_object_encryption_alg_values_supported:rt(ce()).optional(),request_object_encryption_enc_values_supported:rt(ce()).optional(),token_endpoint_auth_methods_supported:rt(ce()).optional(),token_endpoint_auth_signing_alg_values_supported:rt(ce()).optional(),display_values_supported:rt(ce()).optional(),claim_types_supported:rt(ce()).optional(),claims_supported:rt(ce()).optional(),service_documentation:ce().optional(),claims_locales_supported:rt(ce()).optional(),ui_locales_supported:rt(ce()).optional(),claims_parameter_supported:tn().optional(),request_parameter_supported:tn().optional(),request_uri_parameter_supported:tn().optional(),require_request_uri_registration:tn().optional(),op_policy_uri:yi.optional(),op_tos_uri:yi.optional(),client_id_metadata_document_supported:tn().optional()}),wNt=ot({..._Nt.shape,...Hte.pick({code_challenge_methods_supported:!0}).shape}),bNt=ot({access_token:ce(),id_token:ce().optional(),token_type:ce(),expires_in:lz.number().optional(),scope:ce().optional(),refresh_token:ce().optional()}).strip(),TNt=ot({error:ce(),error_description:ce().optional(),error_uri:ce().optional()}),Vte=yi.optional().or(Tt("").transform(()=>{})),ENt=ot({redirect_uris:rt(yi),token_endpoint_auth_method:ce().optional(),grant_types:rt(ce()).optional(),response_types:rt(ce()).optional(),client_name:ce().optional(),client_uri:yi.optional(),logo_uri:Vte,scope:ce().optional(),contacts:rt(ce()).optional(),tos_uri:Vte,policy_uri:ce().optional(),jwks_uri:yi.optional(),jwks:HB().optional(),software_id:ce().optional(),software_version:ce().optional(),software_statement:ce().optional()}).strip(),SNt=ot({client_id:ce(),client_secret:ce().optional(),client_id_issued_at:Rr().optional(),client_secret_expires_at:Rr().optional()}).strip(),CNt=ENt.merge(SNt),cqr=ot({error:ce(),error_description:ce().optional()}).strip(),uqr=ot({token:ce(),token_type_hint:ce().optional()}).strip()}});function dqr(e){const t=typeof e=="string"?new URL(e):new URL(e.href);return t.hash="",t}function pqr({requestedResource:e,configuredResource:t}){const r=typeof e=="string"?new URL(e):new URL(e.href),n=typeof t=="string"?new URL(t):new URL(t.href);if(r.origin!==n.origin||r.pathname.length<n.pathname.length)return!1;const o=r.pathname.endsWith("/")?r.pathname:r.pathname+"/",s=n.pathname.endsWith("/")?n.pathname:n.pathname+"/";return o.startsWith(s)}var mqr=S({"node_modules/.pnpm/@modelcontextprotocol+sdk@1.28.0_@cfworker+json-schema@4.1.1_zod@4.3.6/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/auth-utils.js"(){}}),Qs,TL,Xk,Qk,ex,EL,SL,CL,ey,kL,xL,AL,IL,RL,ML,tx,PL,DL,xNt,hqr=S({"node_modules/.pnpm/@modelcontextprotocol+sdk@1.28.0_@cfworker+json-schema@4.1.1_zod@4.3.6/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/errors.js"(){Qs=class extends Error{constructor(e,t){super(e),this.errorUri=t,this.name=this.constructor.name}toResponseObject(){const e={error:this.errorCode,error_description:this.message};return this.errorUri&&(e.error_uri=this.errorUri),e}get errorCode(){return this.constructor.errorCode}},TL=class extends Qs{},TL.errorCode="invalid_request",Xk=class extends Qs{},Xk.errorCode="invalid_client",Qk=class extends Qs{},Qk.errorCode="invalid_grant",ex=class extends Qs{},ex.errorCode="unauthorized_client",EL=class extends Qs{},EL.errorCode="unsupported_grant_type",SL=class extends Qs{},SL.errorCode="invalid_scope",CL=class extends Qs{},CL.errorCode="access_denied",ey=class extends Qs{},ey.errorCode="server_error",kL=class extends Qs{},kL.errorCode="temporarily_unavailable",xL=class extends Qs{},xL.errorCode="unsupported_response_type",AL=class extends Qs{},AL.errorCode="unsupported_token_type",IL=class extends Qs{},IL.errorCode="invalid_token",RL=class extends Qs{},RL.errorCode="method_not_allowed",ML=class extends Qs{},ML.errorCode="too_many_requests",tx=class extends Qs{},tx.errorCode="invalid_client_metadata",PL=class extends Qs{},PL.errorCode="insufficient_scope",DL=class extends Qs{},DL.errorCode="invalid_target",xNt={[TL.errorCode]:TL,[Xk.errorCode]:Xk,[Qk.errorCode]:Qk,[ex.errorCode]:ex,[EL.errorCode]:EL,[SL.errorCode]:SL,[CL.errorCode]:CL,[ey.errorCode]:ey,[kL.errorCode]:kL,[xL.errorCode]:xL,[AL.errorCode]:AL,[IL.errorCode]:IL,[RL.errorCode]:RL,[ML.errorCode]:ML,[tx.errorCode]:tx,[PL.errorCode]:PL,[DL.errorCode]:DL}}});function fqr(e){return["client_secret_basic","client_secret_post","none"].includes(e)}function gqr(e,t){const r=e.client_secret!==void 0;return"token_endpoint_auth_method"in e&&e.token_endpoint_auth_method&&fqr(e.token_endpoint_auth_method)&&(t.length===0||t.includes(e.token_endpoint_auth_method))?e.token_endpoint_auth_method:t.length===0?r?"client_secret_basic":"none":r&&t.includes("client_secret_basic")?"client_secret_basic":r&&t.includes("client_secret_post")?"client_secret_post":t.includes("none")?"none":r?"client_secret_post":"none"}function yqr(e,t,r,n){const{client_id:o,client_secret:s}=t;switch(e){case"client_secret_basic":vqr(o,s,r);return;case"client_secret_post":_qr(o,s,n);return;case"none":wqr(o,n);return;default:throw new Error(`Unsupported client authentication method: ${e}`)}}function vqr(e,t,r){if(!t)throw new Error("client_secret_basic authentication requires a client_secret");const n=btoa(`${e}:${t}`);r.set("Authorization",`Basic ${n}`)}function _qr(e,t,r){r.set("client_id",e),t&&r.set("client_secret",t)}function wqr(e,t){t.set("client_id",e)}async function ANt(e){const t=e instanceof Response?e.status:void 0,r=e instanceof Response?await e.text():e;try{const n=TNt.parse(JSON.parse(r)),{error:o,error_description:s,error_uri:i}=n,a=xNt[o]||ey;return new a(s||"",i)}catch(n){const o=`${t?`HTTP ${t}: `:""}Invalid OAuth error response: ${n}. Raw body: ${r}`;return new ey(o)}}async function ty(e,t){try{return await Wte(e,t)}catch(r){if(r instanceof Xk||r instanceof ex)return await e.invalidateCredentials?.("all"),await Wte(e,t);if(r instanceof Qk)return await e.invalidateCredentials?.("tokens"),await Wte(e,t);throw r}}async function Wte(e,{serverUrl:t,authorizationCode:r,scope:n,resourceMetadataUrl:o,fetchFn:s}){const i=await e.discoveryState?.();let a,l,c,u=o;if(!u&&i?.resourceMetadataUrl&&(u=new URL(i.resourceMetadataUrl)),i?.authorizationServerUrl){if(l=i.authorizationServerUrl,a=i.resourceMetadata,c=i.authorizationServerMetadata??await MNt(l,{fetchFn:s}),!a)try{a=await INt(t,{resourceMetadataUrl:u},s)}catch{}(c!==i.authorizationServerMetadata||a!==i.resourceMetadata)&&await e.saveDiscoveryState?.({authorizationServerUrl:String(l),resourceMetadataUrl:u?.toString(),resourceMetadata:a,authorizationServerMetadata:c})}else{const T=await xqr(t,{resourceMetadataUrl:u,fetchFn:s});l=T.authorizationServerUrl,c=T.authorizationServerMetadata,a=T.resourceMetadata,await e.saveDiscoveryState?.({authorizationServerUrl:String(l),resourceMetadataUrl:u?.toString(),resourceMetadata:a,authorizationServerMetadata:c})}const d=await Tqr(t,e,a),m=n||a?.scopes_supported?.join(" ")||e.clientMetadata.scope;let h=await Promise.resolve(e.clientInformation());if(!h){if(r!==void 0)throw new Error("Existing OAuth client information is required when exchanging an authorization code");const T=c?.client_id_metadata_document_supported===!0,k=e.clientMetadataUrl;if(k&&!bqr(k))throw new tx(`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${k}`);if(T&&k)h={client_id:k},await e.saveClientInformation?.(h);else{if(!e.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");const I=await Pqr(l,{metadata:c,clientMetadata:e.clientMetadata,scope:m,fetchFn:s});await e.saveClientInformation(I),h=I}}const g=!e.redirectUrl;if(r!==void 0||g){const T=await Mqr(e,l,{metadata:c,resource:d,authorizationCode:r,fetchFn:s});return await e.saveTokens(T),"AUTHORIZED"}const y=await e.tokens();if(y?.refresh_token)try{const T=await Rqr(l,{metadata:c,clientInformation:h,refreshToken:y.refresh_token,resource:d,addClientAuthentication:e.addClientAuthentication,fetchFn:s});return await e.saveTokens(T),"AUTHORIZED"}catch(T){if(!(!(T instanceof Qs)||T instanceof ey))throw T}const v=e.state?await e.state():void 0,{authorizationUrl:_,codeVerifier:b}=await Aqr(l,{metadata:c,clientInformation:h,state:v,redirectUrl:e.redirectUrl,scope:m,resource:d});return await e.saveCodeVerifier(b),await e.redirectToAuthorization(_),"REDIRECT"}function bqr(e){if(!e)return!1;try{const t=new URL(e);return t.protocol==="https:"&&t.pathname!=="/"}catch{return!1}}async function Tqr(e,t,r){const n=dqr(e);if(t.validateResourceURL)return await t.validateResourceURL(n,r?.resource);if(r){if(!pqr({requestedResource:n,configuredResource:r.resource}))throw new Error(`Protected resource ${r.resource} does not match expected ${n} (or origin)`);return new URL(r.resource)}}function OL(e){const t=e.headers.get("WWW-Authenticate");if(!t)return{};const[r,n]=t.split(" ");if(r.toLowerCase()!=="bearer"||!n)return{};const o=Kte(e,"resource_metadata")||void 0;let s;if(o)try{s=new URL(o)}catch{}const i=Kte(e,"scope")||void 0,a=Kte(e,"error")||void 0;return{resourceMetadataUrl:s,scope:i,error:a}}function Kte(e,t){const r=e.headers.get("WWW-Authenticate");if(!r)return null;const n=new RegExp(`${t}=(?:"([^"]+)"|([^\\s,]+))`),o=r.match(n);return o?o[1]||o[2]:null}async function INt(e,t,r=fetch){const n=await Cqr(e,"oauth-protected-resource",r,{protocolVersion:t?.protocolVersion,metadataUrl:t?.resourceMetadataUrl});if(!n||n.status===404)throw await n?.body?.cancel(),new Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");if(!n.ok)throw await n.body?.cancel(),new Error(`HTTP ${n.status} trying to load well-known OAuth protected resource metadata.`);return vNt.parse(await n.json())}async function Jte(e,t,r=fetch){try{return await r(e,{headers:t})}catch(n){if(n instanceof TypeError)return t?Jte(e,void 0,r):void 0;throw n}}function Eqr(e,t="",r={}){return t.endsWith("/")&&(t=t.slice(0,-1)),r.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}async function RNt(e,t,r=fetch){return await Jte(e,{"MCP-Protocol-Version":t},r)}function Sqr(e,t){return!e||e.status>=400&&e.status<500&&t!=="/"}async function Cqr(e,t,r,n){const o=new URL(e),s=n?.protocolVersion??zk;let i;if(n?.metadataUrl)i=new URL(n.metadataUrl);else{const l=Eqr(t,o.pathname);i=new URL(l,n?.metadataServerUrl??o),i.search=o.search}let a=await RNt(i,s,r);if(!n?.metadataUrl&&Sqr(a,o.pathname)){const l=new URL(`/.well-known/${t}`,o);a=await RNt(l,s,r)}return a}function kqr(e){const t=typeof e=="string"?new URL(e):e,r=t.pathname!=="/",n=[];if(!r)return n.push({url:new URL("/.well-known/oauth-authorization-server",t.origin),type:"oauth"}),n.push({url:new URL("/.well-known/openid-configuration",t.origin),type:"oidc"}),n;let o=t.pathname;return o.endsWith("/")&&(o=o.slice(0,-1)),n.push({url:new URL(`/.well-known/oauth-authorization-server${o}`,t.origin),type:"oauth"}),n.push({url:new URL(`/.well-known/openid-configuration${o}`,t.origin),type:"oidc"}),n.push({url:new URL(`${o}/.well-known/openid-configuration`,t.origin),type:"oidc"}),n}async function MNt(e,{fetchFn:t=fetch,protocolVersion:r=zk}={}){const n={"MCP-Protocol-Version":r,Accept:"application/json"},o=kqr(e);for(const{url:s,type:i}of o){const a=await Jte(s,n,t);if(a){if(!a.ok){if(await a.body?.cancel(),a.status>=400&&a.status<500)continue;throw new Error(`HTTP ${a.status} trying to load ${i==="oauth"?"OAuth":"OpenID provider"} metadata from ${s}`)}return i==="oauth"?Hte.parse(await a.json()):wNt.parse(await a.json())}}}async function xqr(e,t){let r,n;try{r=await INt(e,{resourceMetadataUrl:t?.resourceMetadataUrl},t?.fetchFn),r.authorization_servers&&r.authorization_servers.length>0&&(n=r.authorization_servers[0])}catch{}n||(n=String(new URL("/",e)));const o=await MNt(n,{fetchFn:t?.fetchFn});return{authorizationServerUrl:n,authorizationServerMetadata:o,resourceMetadata:r}}async function Aqr(e,{metadata:t,clientInformation:r,redirectUrl:n,scope:o,state:s,resource:i}){let a;if(t){if(a=new URL(t.authorization_endpoint),!t.response_types_supported.includes(NL))throw new Error(`Incompatible auth server: does not support response type ${NL}`);if(t.code_challenge_methods_supported&&!t.code_challenge_methods_supported.includes(LL))throw new Error(`Incompatible auth server: does not support code challenge method ${LL}`)}else a=new URL("/authorize",e);const l=await yNt(),c=l.code_verifier,u=l.code_challenge;return a.searchParams.set("response_type",NL),a.searchParams.set("client_id",r.client_id),a.searchParams.set("code_challenge",u),a.searchParams.set("code_challenge_method",LL),a.searchParams.set("redirect_uri",String(n)),s&&a.searchParams.set("state",s),o&&a.searchParams.set("scope",o),o?.includes("offline_access")&&a.searchParams.append("prompt","consent"),i&&a.searchParams.set("resource",i.href),{authorizationUrl:a,codeVerifier:c}}function Iqr(e,t,r){return new URLSearchParams({grant_type:"authorization_code",code:e,code_verifier:t,redirect_uri:String(r)})}async function PNt(e,{metadata:t,tokenRequestParams:r,clientInformation:n,addClientAuthentication:o,resource:s,fetchFn:i}){const a=t?.token_endpoint?new URL(t.token_endpoint):new URL("/token",e),l=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"});if(s&&r.set("resource",s.href),o)await o(l,r,a,t);else if(n){const u=t?.token_endpoint_auth_methods_supported??[],d=gqr(n,u);yqr(d,n,l,r)}const c=await(i??fetch)(a,{method:"POST",headers:l,body:r});if(!c.ok)throw await ANt(c);return bNt.parse(await c.json())}async function Rqr(e,{metadata:t,clientInformation:r,refreshToken:n,resource:o,addClientAuthentication:s,fetchFn:i}){const a=new URLSearchParams({grant_type:"refresh_token",refresh_token:n}),l=await PNt(e,{metadata:t,tokenRequestParams:a,clientInformation:r,addClientAuthentication:s,resource:o,fetchFn:i});return{refresh_token:n,...l}}async function Mqr(e,t,{metadata:r,resource:n,authorizationCode:o,fetchFn:s}={}){const i=e.clientMetadata.scope;let a;if(e.prepareTokenRequest&&(a=await e.prepareTokenRequest(i)),!a){if(!o)throw new Error("Either provider.prepareTokenRequest() or authorizationCode is required");if(!e.redirectUrl)throw new Error("redirectUrl is required for authorization_code flow");const c=await e.codeVerifier();a=Iqr(o,c,e.redirectUrl)}const l=await e.clientInformation();return PNt(t,{metadata:r,tokenRequestParams:a,clientInformation:l??void 0,addClientAuthentication:e.addClientAuthentication,resource:n,fetchFn:s})}async function Pqr(e,{metadata:t,clientMetadata:r,scope:n,fetchFn:o}){let s;if(t){if(!t.registration_endpoint)throw new Error("Incompatible auth server: does not support dynamic client registration");s=new URL(t.registration_endpoint)}else s=new URL("/register",e);const i=await(o??fetch)(s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...r,...n!==void 0?{scope:n}:{}})});if(!i.ok)throw await ANt(i);return CNt.parse(await i.json())}var Rc,NL,LL,DNt=S({"node_modules/.pnpm/@modelcontextprotocol+sdk@1.28.0_@cfworker+json-schema@4.1.1_zod@4.3.6/node_modules/@modelcontextprotocol/sdk/dist/esm/client/auth.js"(){lqr(),gh(),kNt(),kNt(),mqr(),hqr(),Rc=class extends Error{constructor(e){super(e??"Unauthorized")}},NL="code",LL="S256"}}),ONt,NNt,Dqr=S({"node_modules/.pnpm/@modelcontextprotocol+sdk@1.28.0_@cfworker+json-schema@4.1.1_zod@4.3.6/node_modules/@modelcontextprotocol/sdk/dist/esm/client/sse.js"(){fjr(),gNt(),gh(),DNt(),ONt=class extends Error{constructor(e,t,r){super(`SSE error: ${t}`),this.code=e,this.event=r}},NNt=class{constructor(e,t){this._url=e,this._resourceMetadataUrl=void 0,this._scope=void 0,this._eventSourceInit=t?.eventSourceInit,this._requestInit=t?.requestInit,this._authProvider=t?.authProvider,this._fetch=t?.fetch,this._fetchWithInit=fNt(t?.fetch,t?.requestInit)}async _authThenStart(){if(!this._authProvider)throw new Rc("No auth provider");let e;try{e=await ty(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(t){throw this.onerror?.(t),t}if(e!=="AUTHORIZED")throw new Rc;return await this._startOrAuth()}async _commonHeaders(){const e={};if(this._authProvider){const r=await this._authProvider.tokens();r&&(e.Authorization=`Bearer ${r.access_token}`)}this._protocolVersion&&(e["mcp-protocol-version"]=this._protocolVersion);const t=bL(this._requestInit?.headers);return new Headers({...e,...t})}_startOrAuth(){const e=this?._eventSourceInit?.fetch??this._fetch??fetch;return new Promise((t,r)=>{this._eventSource=new Zk(this._url.href,{...this._eventSourceInit,fetch:async(n,o)=>{const s=await this._commonHeaders();s.set("Accept","text/event-stream");const i=await e(n,{...o,headers:s});if(i.status===401&&i.headers.has("www-authenticate")){const{resourceMetadataUrl:a,scope:l}=OL(i);this._resourceMetadataUrl=a,this._scope=l}return i}}),this._abortController=new AbortController,this._eventSource.onerror=n=>{if(n.code===401&&this._authProvider){this._authThenStart().then(t,r);return}const o=new ONt(n.code,n.message,n);r(o),this.onerror?.(o)},this._eventSource.onopen=()=>{},this._eventSource.addEventListener("endpoint",n=>{const o=n;try{if(this._endpoint=new URL(o.data,this._url),this._endpoint.origin!==this._url.origin)throw new Error(`Endpoint origin does not match connection origin: ${this._endpoint.origin}`)}catch(s){r(s),this.onerror?.(s),this.close();return}t()}),this._eventSource.onmessage=n=>{const o=n;let s;try{s=Hg.parse(JSON.parse(o.data))}catch(i){this.onerror?.(i);return}this.onmessage?.(s)}})}async start(){if(this._eventSource)throw new Error("SSEClientTransport already started! If using Client class, note that connect() calls start() automatically.");return await this._startOrAuth()}async finishAuth(e){if(!this._authProvider)throw new Rc("No auth provider");if(await ty(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new Rc("Failed to authorize")}async close(){this._abortController?.abort(),this._eventSource?.close(),this.onclose?.()}async send(e){if(!this._endpoint)throw new Error("Not connected");try{const t=await this._commonHeaders();t.set("content-type","application/json");const r={...this._requestInit,method:"POST",headers:t,body:JSON.stringify(e),signal:this._abortController?.signal},n=await(this._fetch??fetch)(this._endpoint,r);if(!n.ok){const o=await n.text().catch(()=>null);if(n.status===401&&this._authProvider){const{resourceMetadataUrl:s,scope:i}=OL(n);if(this._resourceMetadataUrl=s,this._scope=i,await ty(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new Rc;return this.send(e)}throw new Error(`Error POSTing to endpoint (HTTP ${n.status}): ${o}`)}await n.body?.cancel()}catch(t){throw this.onerror?.(t),t}}setProtocolVersion(e){this._protocolVersion=e}}}}),LNt,$Nt,Oqr=S({"node_modules/.pnpm/@modelcontextprotocol+sdk@1.28.0_@cfworker+json-schema@4.1.1_zod@4.3.6/node_modules/@modelcontextprotocol/sdk/dist/esm/client/websocket.js"(){gh(),LNt="mcp",$Nt=class{constructor(e){this._url=e}start(){if(this._socket)throw new Error("WebSocketClientTransport already started! If using Client class, note that connect() calls start() automatically.");return new Promise((e,t)=>{this._socket=new WebSocket(this._url,LNt),this._socket.onerror=r=>{const n="error"in r?r.error:new Error(`WebSocket error: ${JSON.stringify(r)}`);t(n),this.onerror?.(n)},this._socket.onopen=()=>{e()},this._socket.onclose=()=>{this.onclose?.()},this._socket.onmessage=r=>{let n;try{n=Hg.parse(JSON.parse(r.data))}catch(o){this.onerror?.(o);return}this.onmessage?.(n)}})}async close(){this._socket?.close()}send(e){return new Promise((t,r)=>{if(!this._socket){r(new Error("Not connected"));return}this._socket?.send(JSON.stringify(e)),t()})}}}}),FNt,ry,UNt,Nqr=S({"node_modules/.pnpm/@modelcontextprotocol+sdk@1.28.0_@cfworker+json-schema@4.1.1_zod@4.3.6/node_modules/@modelcontextprotocol/sdk/dist/esm/client/streamableHttp.js"(){gNt(),gh(),DNt(),u0e(),FNt={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},ry=class extends Error{constructor(e,t){super(`Streamable HTTP error: ${t}`),this.code=e}},UNt=class{constructor(e,t){this._hasCompletedAuthFlow=!1,this._url=e,this._resourceMetadataUrl=void 0,this._scope=void 0,this._requestInit=t?.requestInit,this._authProvider=t?.authProvider,this._fetch=t?.fetch,this._fetchWithInit=fNt(t?.fetch,t?.requestInit),this._sessionId=t?.sessionId,this._reconnectionOptions=t?.reconnectionOptions??FNt}async _authThenStart(){if(!this._authProvider)throw new Rc("No auth provider");let e;try{e=await ty(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(t){throw this.onerror?.(t),t}if(e!=="AUTHORIZED")throw new Rc;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){const e={};if(this._authProvider){const r=await this._authProvider.tokens();r&&(e.Authorization=`Bearer ${r.access_token}`)}this._sessionId&&(e["mcp-session-id"]=this._sessionId),this._protocolVersion&&(e["mcp-protocol-version"]=this._protocolVersion);const t=bL(this._requestInit?.headers);return new Headers({...e,...t})}async _startOrAuthSse(e){const{resumptionToken:t}=e;try{const r=await this._commonHeaders();r.set("Accept","text/event-stream"),t&&r.set("last-event-id",t);const n=await(this._fetch??fetch)(this._url,{method:"GET",headers:r,signal:this._abortController?.signal});if(!n.ok){if(await n.body?.cancel(),n.status===401&&this._authProvider)return await this._authThenStart();if(n.status===405)return;throw new ry(n.status,`Failed to open SSE stream: ${n.statusText}`)}this._handleSseStream(n.body,e,!0)}catch(r){throw this.onerror?.(r),r}}_getNextReconnectionDelay(e){if(this._serverRetryMs!==void 0)return this._serverRetryMs;const t=this._reconnectionOptions.initialReconnectionDelay,r=this._reconnectionOptions.reconnectionDelayGrowFactor,n=this._reconnectionOptions.maxReconnectionDelay;return Math.min(t*Math.pow(r,e),n)}_scheduleReconnection(e,t=0){const r=this._reconnectionOptions.maxRetries;if(t>=r){this.onerror?.(new Error(`Maximum reconnection attempts (${r}) exceeded.`));return}const n=this._getNextReconnectionDelay(t);this._reconnectionTimeout=setTimeout(()=>{this._startOrAuthSse(e).catch(o=>{this.onerror?.(new Error(`Failed to reconnect SSE stream: ${o instanceof Error?o.message:String(o)}`)),this._scheduleReconnection(e,t+1)})},n)}_handleSseStream(e,t,r){if(!e)return;const{onresumptiontoken:n,replayMessageId:o}=t;let s,i=!1,a=!1;(async()=>{try{const c=e.pipeThrough(new TextDecoderStream).pipeThrough(new rj({onRetry:m=>{this._serverRetryMs=m}})).getReader();for(;;){const{value:m,done:h}=await c.read();if(h)break;if(m.id&&(s=m.id,i=!0,n?.(m.id)),!!m.data&&(!m.event||m.event==="message"))try{const g=Hg.parse(JSON.parse(m.data));U_(g)&&(a=!0,o!==void 0&&(g.id=o)),this.onmessage?.(g)}catch(g){this.onerror?.(g)}}(r||i)&&!a&&this._abortController&&!this._abortController.signal.aborted&&this._scheduleReconnection({resumptionToken:s,onresumptiontoken:n,replayMessageId:o},0)}catch(c){if(this.onerror?.(new Error(`SSE stream disconnected: ${c}`)),(r||i)&&!a&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:s,onresumptiontoken:n,replayMessageId:o},0)}catch(m){this.onerror?.(new Error(`Failed to reconnect: ${m instanceof Error?m.message:String(m)}`))}}})()}async start(){if(this._abortController)throw new Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");this._abortController=new AbortController}async finishAuth(e){if(!this._authProvider)throw new Rc("No auth provider");if(await ty(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new Rc("Failed to authorize")}async close(){this._reconnectionTimeout&&(clearTimeout(this._reconnectionTimeout),this._reconnectionTimeout=void 0),this._abortController?.abort(),this.onclose?.()}async send(e,t){try{const{resumptionToken:r,onresumptiontoken:n}=t||{};if(r){this._startOrAuthSse({resumptionToken:r,replayMessageId:XN(e)?e.id:void 0}).catch(d=>this.onerror?.(d));return}const o=await this._commonHeaders();o.set("content-type","application/json"),o.set("accept","application/json, text/event-stream");const s={...this._requestInit,method:"POST",headers:o,body:JSON.stringify(e),signal:this._abortController?.signal},i=await(this._fetch??fetch)(this._url,s),a=i.headers.get("mcp-session-id");if(a&&(this._sessionId=a),!i.ok){const d=await i.text().catch(()=>null);if(i.status===401&&this._authProvider){if(this._hasCompletedAuthFlow)throw new ry(401,"Server returned 401 after successful authentication");const{resourceMetadataUrl:m,scope:h}=OL(i);if(this._resourceMetadataUrl=m,this._scope=h,await ty(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new Rc;return this._hasCompletedAuthFlow=!0,this.send(e)}if(i.status===403&&this._authProvider){const{resourceMetadataUrl:m,scope:h,error:g}=OL(i);if(g==="insufficient_scope"){const y=i.headers.get("WWW-Authenticate");if(this._lastUpscopingHeader===y)throw new ry(403,"Server returned 403 after trying upscoping");if(h&&(this._scope=h),m&&(this._resourceMetadataUrl=m),this._lastUpscopingHeader=y??void 0,await ty(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!=="AUTHORIZED")throw new Rc;return this.send(e)}}throw new ry(i.status,`Error POSTing to endpoint: ${d}`)}if(this._hasCompletedAuthFlow=!1,this._lastUpscopingHeader=void 0,i.status===202){await i.body?.cancel(),P4t(e)&&this._startOrAuthSse({resumptionToken:void 0}).catch(d=>this.onerror?.(d));return}const c=(Array.isArray(e)?e:[e]).filter(d=>"method"in d&&"id"in d&&d.id!==void 0).length>0,u=i.headers.get("content-type");if(c)if(u?.includes("text/event-stream"))this._handleSseStream(i.body,{onresumptiontoken:n},!1);else if(u?.includes("application/json")){const d=await i.json(),m=Array.isArray(d)?d.map(h=>Hg.parse(h)):[Hg.parse(d)];for(const h of m)this.onmessage?.(h)}else throw await i.body?.cancel(),new ry(-1,`Unexpected content type: ${u}`);else await i.body?.cancel()}catch(r){throw this.onerror?.(r),r}}get sessionId(){return this._sessionId}async terminateSession(){if(this._sessionId)try{const e=await this._commonHeaders(),t={...this._requestInit,method:"DELETE",headers:e,signal:this._abortController?.signal},r=await(this._fetch??fetch)(this._url,t);if(await r.body?.cancel(),!r.ok&&r.status!==405)throw new ry(r.status,`Failed to terminate session: ${r.statusText}`);this._sessionId=void 0}catch(e){throw this.onerror?.(e),e}}setProtocolVersion(e){this._protocolVersion=e}get protocolVersion(){return this._protocolVersion}async resumeStream(e,t){await this._startOrAuthSse({resumptionToken:e,onresumptiontoken:t?.onresumptiontoken})}}}}),BNt,Yte,Zte,rx,Xte=S({"src/lib/mcp/mcpCircuitBreaker.ts"(){"use strict";vn(),tr(),q(),yt(),yt(),BNt=Math.max(1e4,Number(process.env.MCP_OPERATION_TIMEOUT)||6e4),Yte=class extends sn{constructor(e,t={}){super(),this.name=e,this.config={failureThreshold:t.failureThreshold??5,resetTimeout:t.resetTimeout??6e4,halfOpenMaxCalls:t.halfOpenMaxCalls??3,operationTimeout:t.operationTimeout??BNt,minimumCallsBeforeCalculation:t.minimumCallsBeforeCalculation??10,statisticsWindowSize:t.statisticsWindowSize??3e5},this.cleanupTimer=setInterval(()=>this.cleanupCallHistory(),6e4)}name;state="closed";config;callHistory=[];lastFailureTime=0;halfOpenCalls=0;lastStateChange=new Date;cleanupTimer;async execute(e){const t=Date.now();try{if(this.state==="open"){const n=this.config.resetTimeout-(Date.now()-this.lastFailureTime);if(n>0)throw new am({breakerName:this.name,retryAfter:new Date(this.lastFailureTime+this.config.resetTimeout),retryAfterMs:n,breakerState:"open",failureCount:this.getStats().failedCalls});this.changeState("half-open","Reset timeout reached")}if(this.state==="half-open"&&this.halfOpenCalls>=this.config.halfOpenMaxCalls)throw this.lastFailureTime=Date.now(),this.changeState("open","Half-open call limit reached, reverting to open"),new am({breakerName:this.name,retryAfter:new Date(this.lastFailureTime+this.config.resetTimeout),retryAfterMs:this.config.resetTimeout,breakerState:"open",failureCount:this.getStats().failedCalls});if(this.state==="half-open"){const n=vt.getActiveSpan();n&&n.addEvent("circuit.half_open_test",{"circuit.name":this.name,"circuit.half_open_call":this.halfOpenCalls+1,"circuit.half_open_max_calls":this.config.halfOpenMaxCalls})}const r=await Promise.race([e(),this.timeoutPromise(this.config.operationTimeout)]);return this.recordCall(!0,Date.now()-t),this.state==="half-open"&&(this.halfOpenCalls++,this.halfOpenCalls>=this.config.halfOpenMaxCalls&&this.changeState("closed","Half-open test successful")),r}catch(r){const n=Date.now()-t;this.recordCall(!1,n);const o=r instanceof Error?r.message:String(r);throw this.emit("callFailure",{error:o,duration:n,timestamp:new Date}),this.state==="half-open"?this.changeState("open",`Half-open test failed: ${o}`):this.state==="closed"&&this.checkFailureThreshold(),r}}recordCall(e,t){const r=Date.now();this.callHistory.push({timestamp:r,success:e,duration:t}),e&&this.emit("callSuccess",{duration:t,timestamp:new Date}),e||(this.lastFailureTime=r)}checkFailureThreshold(){const e=Date.now()-this.config.statisticsWindowSize,t=this.callHistory.filter(o=>o.timestamp>=e);if(t.length<this.config.minimumCallsBeforeCalculation)return;const r=t.filter(o=>!o.success).length,n=r/t.length;de.debug(`[CircuitBreaker:${this.name}] Failure rate: ${(n*100).toFixed(1)}% (${r}/${t.length})`),r>=this.config.failureThreshold&&(this.changeState("open",`Failure threshold exceeded: ${r} failures`),this.emit("circuitOpen",{failureRate:n,totalCalls:t.length,timestamp:new Date}))}changeState(e,t){const r=this.state;this.state=e,this.lastStateChange=new Date;const n=vt.getActiveSpan();n&&n.addEvent("circuit.state_change",{"circuit.name":this.name,"circuit.from_state":r,"circuit.to_state":e,"circuit.reason":t.slice(0,128),"circuit.failure_count":this.callHistory.filter(o=>!o.success).length}),e==="half-open"?(this.halfOpenCalls=0,this.emit("circuitHalfOpen",{timestamp:new Date})):e==="closed"&&(this.halfOpenCalls=0,this.emit("circuitClosed",{timestamp:new Date})),de.info(`[CircuitBreaker:${this.name}] State changed: ${r} -> ${e} (${t})`),this.emit("stateChange",{oldState:r,newState:e,reason:t,timestamp:new Date})}timeoutPromise(e){return new Promise((t,r)=>{setTimeout(()=>{r(new Error(`Operation timed out after ${e}ms`))},e)})}cleanupCallHistory(){const e=Date.now()-this.config.statisticsWindowSize,t=this.callHistory.length;this.callHistory=this.callHistory.filter(n=>n.timestamp>=e);const r=t-this.callHistory.length;r>0&&de.debug(`[CircuitBreaker:${this.name}] Cleaned up ${r} old call records`)}getStats(){const e=Date.now()-this.config.statisticsWindowSize,t=this.callHistory.filter(s=>s.timestamp>=e),r=t.filter(s=>s.success).length,n=t.length-r,o=t.length>0?n/t.length:0;return{state:this.state,totalCalls:this.callHistory.length,successfulCalls:this.callHistory.filter(s=>s.success).length,failedCalls:this.callHistory.filter(s=>!s.success).length,failureRate:o,windowCalls:t.length,lastStateChange:this.lastStateChange,nextRetryTime:this.state==="open"?new Date(this.lastFailureTime+this.config.resetTimeout):void 0,halfOpenCalls:this.halfOpenCalls}}reset(){this.changeState("closed","Manual reset"),this.callHistory=[],this.lastFailureTime=0,this.halfOpenCalls=0}forceOpen(e="Manual force open"){this.changeState("open",e),this.lastFailureTime=Date.now()}getName(){return this.name}isOpen(){return this.state==="open"}isClosed(){return this.state==="closed"}isHalfOpen(){return this.state==="half-open"}destroy(){this.cleanupTimer&&(clearInterval(this.cleanupTimer),this.cleanupTimer=void 0,de.debug(`[CircuitBreaker:${this.name}] Cleanup timer cleared`)),this.removeAllListeners(),this.callHistory=[],de.debug(`[CircuitBreaker:${this.name}] Destroyed and cleaned up`)}},Zte=class{breakers=new Map;getBreaker(e,t){if(!this.breakers.has(e)){const n=new Yte(e,t);this.breakers.set(e,n),de.debug(`[CircuitBreakerManager] Created circuit breaker: ${e}`)}const r=this.breakers.get(e);if(!r)throw new Error(`Circuit breaker ${e} not found after creation`);return r}removeBreaker(e){const t=this.breakers.get(e);return t?(t.destroy(),this.breakers.delete(e),de.debug(`[CircuitBreakerManager] Removed and cleaned up circuit breaker: ${e}`),!0):!1}getBreakerNames(){return Array.from(this.breakers.keys())}getAllStats(){const e={};for(const[t,r]of this.breakers)e[t]=r.getStats();return e}resetAll(){for(const e of this.breakers.values())e.reset();de.info("[CircuitBreakerManager] Reset all circuit breakers")}getHealthSummary(){let e=0,t=0,r=0;const n=[];for(const[o,s]of this.breakers)switch(s.getStats().state){case"closed":e++;break;case"open":t++,n.push(o);break;case"half-open":r++;break}return{totalBreakers:this.breakers.size,closedBreakers:e,openBreakers:t,halfOpenBreakers:r,unhealthyBreakers:n}}destroyAll(){for(const e of this.breakers.values())e.destroy();this.breakers.clear(),de.info("[CircuitBreakerManager] Destroyed all circuit breakers")}},rx=new Zte}});function Lqr(e){return new Promise(t=>setTimeout(t,e))}function $L(e,t=cd){return t.retryableStatusCodes.includes(e)}function zNt(e,t=cd){if(!e||typeof e!="object")return!1;const r=e;if(mr(e))return!1;if(r.name==="TimeoutError"||r.code==="TIMEOUT"||r.code==="ETIMEDOUT"||r.code==="ECONNRESET"||r.code==="ENOTFOUND"||r.code==="ECONNREFUSED"||r.code==="ECONNABORTED"||r.code==="EPIPE"||r.code==="ENETUNREACH"||r.code==="EHOSTUNREACH")return!0;if(r.name==="TypeError"&&typeof r.message=="string"){const n=r.message.toLowerCase();if(n.includes("fetch")||n.includes("network")||n.includes("connection"))return!0}return typeof r.status=="number"?$L(r.status,t):r.response&&typeof r.response=="object"&&typeof r.response.status=="number"?$L(r.response.status,t):typeof r.statusCode=="number"?$L(r.statusCode,t):!1}async function jNt(e,t={}){const r={...cd,...t},{traceId:n,parentSpanId:o}=p0(),s=Oe.createSpan("mcp.transport","mcp.retry",{"mcp.transport":"http","mcp.operation":"retry","mcp.maxAttempts":r.maxAttempts},o,n),i=Date.now();let a,l=0;for(let u=1;u<=r.maxAttempts;u++){l=u;try{const d=await e();s.durationMs=Date.now()-i,s.attributes["mcp.retryAttempt"]=u;const m=Oe.endSpan(s,1);return ut().recordSpan(m),d}catch(d){if(a=d,u===r.maxAttempts){f.debug(`HTTP retry: All ${r.maxAttempts} attempts exhausted`);break}if(!zNt(d,r)){f.debug("HTTP retry: Non-retryable error encountered",d instanceof Error?d.message:String(d));break}const m=git(u,r.initialDelay,r.backoffMultiplier,r.maxDelay,!0),h=d instanceof Error?d.message:String(d);f.warn(`HTTP retry: Attempt ${u}/${r.maxAttempts} failed: ${h}. Retrying in ${Math.round(m)}ms...`),await Lqr(m)}}s.durationMs=Date.now()-i,s.attributes["mcp.retryAttempt"]=l;const c=Oe.endSpan(s,2);throw c.statusMessage=a instanceof Error?a.message:String(a),ut().recordSpan(c),a}var cd,qNt=S({"src/lib/mcp/httpRetryHandler.ts"(){"use strict";at(),bit(),q(),ro(),m0(),cd={maxAttempts:3,initialDelay:1e3,maxDelay:3e4,backoffMultiplier:2,retryableStatusCodes:[408,429,500,502,503,504]}}}),Qte,ere,tre,rre,GNt=S({"src/lib/mcp/httpRateLimiter.ts"(){"use strict";q(),cG(),ro(),m0(),Qte={requestsPerWindow:60,windowMs:6e4,useTokenBucket:!0,refillRate:1,maxBurst:10},ere=class{tokens;lastRefill;config;waitQueue=[];processingQueue=!1;constructor(e={}){this.config={...Qte,...e},this.tokens=this.config.maxBurst,this.lastRefill=Date.now(),de.debug("[HTTPRateLimiter] Initialized with config:",{requestsPerWindow:this.config.requestsPerWindow,windowMs:this.config.windowMs,useTokenBucket:this.config.useTokenBucket,refillRate:this.config.refillRate,maxBurst:this.config.maxBurst})}refillTokens(){const e=Date.now(),n=(e-this.lastRefill)/1e3*this.config.refillRate;if(n>=1){const o=this.tokens;this.tokens=Math.min(this.config.maxBurst,this.tokens+n),this.lastRefill=e,this.tokens>o&&de.debug(`[HTTPRateLimiter] Refilled tokens: ${o.toFixed(2)} -> ${this.tokens.toFixed(2)} (+${n.toFixed(2)})`)}}async acquire(){const{traceId:e,parentSpanId:t}=p0(),r=Oe.createSpan("mcp.transport","mcp.rateLimit",{"mcp.transport":"http","mcp.operation":"rateLimit","mcp.rateLimit.tokensAvailable":this.tokens,"mcp.rateLimit.maxBurst":this.config.maxBurst},t,e),n=Date.now();try{if(this.tryAcquire()){r.durationMs=Date.now()-n,r.attributes["mcp.rateLimit.waited"]=!1;const s=Oe.endSpan(r,1);ut().recordSpan(s);return}await new Promise((s,i)=>{this.waitQueue.push({resolve:s,reject:i}),de.debug(`[HTTPRateLimiter] Request queued, queue length: ${this.waitQueue.length}`),this.processingQueue||this.processQueue()}),r.durationMs=Date.now()-n,r.attributes["mcp.rateLimit.waited"]=!0;const o=Oe.endSpan(r,1);ut().recordSpan(o)}catch(o){r.durationMs=Date.now()-n;const s=Oe.endSpan(r,2);throw s.statusMessage=o instanceof Error?o.message:String(o),ut().recordSpan(s),o}}async processQueue(){if(!this.processingQueue){for(this.processingQueue=!0;this.waitQueue.length>0;)if(this.refillTokens(),this.tokens>=1){const e=this.waitQueue.shift();e&&(this.tokens-=1,de.debug(`[HTTPRateLimiter] Token granted from queue, remaining: ${this.tokens.toFixed(2)}, queue: ${this.waitQueue.length}`),e.resolve())}else{const t=(1-this.tokens)/this.config.refillRate*1e3,r=Math.max(10,Math.ceil(t));de.debug(`[HTTPRateLimiter] Waiting ${r}ms for token refill`),await this.sleep(r)}this.processingQueue=!1}}sleep(e){return new Promise(t=>setTimeout(t,e))}tryAcquire(){return this.refillTokens(),this.tokens>=1?(this.tokens-=1,de.debug(`[HTTPRateLimiter] Token acquired, remaining: ${this.tokens.toFixed(2)}`),!0):(de.debug(`[HTTPRateLimiter] No tokens available, current: ${this.tokens.toFixed(2)}`),!1)}handleRateLimitResponse(e){const t=gE(e),r=e.get("Retry-After");if(r&&t!==void 0){const s=parseInt(r,10);if(isNaN(s)){const i=new Date(r);if(!isNaN(i.getTime()))return de.info(`[HTTPRateLimiter] Server requested retry at ${i.toISOString()} (${t}ms)`),t}else return de.info(`[HTTPRateLimiter] Server requested retry after ${s} seconds`),t}const n=e.get("X-RateLimit-Reset");if(n&&t!==void 0){const s=parseInt(n,10);if(!isNaN(s)){const i=s>1e12?s:s*1e3;return de.info(`[HTTPRateLimiter] Rate limit resets at ${new Date(i).toISOString()} (${t}ms)`),t}}return e.get("X-RateLimit-Remaining")==="0"&&t!==void 0?(de.info(`[HTTPRateLimiter] Rate limit exhausted, using default backoff: ${t}ms`),t):t??0}getRemainingTokens(){return this.refillTokens(),this.tokens}reset(){for(this.tokens=this.config.maxBurst,this.lastRefill=Date.now();this.waitQueue.length>0;){const e=this.waitQueue.shift();e&&e.reject(new Error("Rate limiter was reset"))}de.info(`[HTTPRateLimiter] Reset to initial state, tokens: ${this.tokens}`)}getStats(){return this.refillTokens(),{tokens:this.tokens,maxBurst:this.config.maxBurst,refillRate:this.config.refillRate,queueLength:this.waitQueue.length,lastRefill:new Date(this.lastRefill)}}updateConfig(e){Object.assign(this.config,e),de.info("[HTTPRateLimiter] Configuration updated:",e)}getConfig(){return{...this.config}}},tre=class{limiters=new Map;getLimiter(e,t){let r=this.limiters.get(e);return r?t&&r.updateConfig(t):(r=new ere(t),this.limiters.set(e,r),de.debug(`[RateLimiterManager] Created rate limiter for server: ${e}`)),r}hasLimiter(e){return this.limiters.has(e)}removeLimiter(e){const t=this.limiters.get(e);t&&(t.reset(),this.limiters.delete(e),de.debug(`[RateLimiterManager] Removed rate limiter for server: ${e}`))}getServerIds(){return Array.from(this.limiters.keys())}getAllStats(){const e={};for(const[t,r]of this.limiters)e[t]=r.getStats();return e}resetAll(){for(const e of this.limiters.values())e.reset();de.info("[RateLimiterManager] Reset all rate limiters")}destroyAll(){for(const e of this.limiters.values())e.reset();this.limiters.clear(),de.info("[RateLimiterManager] Destroyed all rate limiters")}getHealthSummary(){const e=[];let t=0,r=0;for(const[o,s]of this.limiters){const i=s.getStats();i.queueLength>0&&(e.push(o),t+=i.queueLength),r+=i.tokens}const n=this.limiters.size>0?r/this.limiters.size:0;return{totalLimiters:this.limiters.size,serversWithQueuedRequests:e,totalQueuedRequests:t,averageTokensAvailable:n}}},rre=new tre}});function HNt(e,t=60){if(!e.expiresAt)return!1;const r=t*1e3,n=Date.now();return e.expiresAt-r<=n}function nre(e){return Date.now()+e*1e3}var FL,VNt,WNt=S({"src/lib/mcp/auth/tokenStorage.ts"(){"use strict";q(),FL=class{tokens=new Map;async getTokens(e){return this.tokens.get(e)??null}async saveTokens(e,t){this.tokens.set(e,t)}async deleteTokens(e){this.tokens.delete(e)}async hasTokens(e){return this.tokens.has(e)}async clearAll(){this.tokens.clear()}get size(){return this.tokens.size}getServerIds(){return Array.from(this.tokens.keys())}},VNt=class{filePath;tokens=new Map;loaded=!1;constructor(e){this.filePath=e}async loadTokens(){if(!this.loaded)try{const t=await(await Promise.resolve().then(()=>(rs(),Zf))).readFile(this.filePath,"utf-8"),r=JSON.parse(t);this.tokens=new Map(Object.entries(r)),this.loaded=!0}catch(e){e instanceof Error&&"code"in e&&e.code!=="ENOENT"&&f.warn(`[FileTokenStorage] Error loading tokens: ${e.message}`),this.tokens=new Map,this.loaded=!0}}async saveToFile(){try{const e=await Promise.resolve().then(()=>(rs(),Zf)),r=(await Promise.resolve().then(()=>(wr(),Yc))).dirname(this.filePath);await e.mkdir(r,{recursive:!0});const n=Object.fromEntries(this.tokens.entries());await e.writeFile(this.filePath,JSON.stringify(n,null,2),"utf-8")}catch(e){throw f.error(`[FileTokenStorage] Error saving tokens: ${e instanceof Error?e.message:String(e)}`),e}}async getTokens(e){return await this.loadTokens(),this.tokens.get(e)??null}async saveTokens(e,t){await this.loadTokens(),this.tokens.set(e,t),await this.saveToFile()}async deleteTokens(e){await this.loadTokens(),this.tokens.delete(e),await this.saveToFile()}async hasTokens(e){return await this.loadTokens(),this.tokens.has(e)}async clearAll(){this.tokens.clear(),await this.saveToFile()}}}});function $qr(e,t){return new UL({clientId:e.clientId,clientSecret:e.clientSecret,authorizationUrl:e.authorizationUrl,tokenUrl:e.tokenUrl,redirectUrl:e.redirectUrl,scope:e.scope,usePKCE:e.usePKCE??!0},t)}var ny,UL,Fqr=S({"src/lib/mcp/auth/oauthClientProvider.ts"(){"use strict";Bt(),WNt(),q(),at(),ny=3e4,UL=class{config;storage;pendingChallenges=new Map;pendingStates=new Set;constructor(e,t){this.config={...e,usePKCE:e.usePKCE??!0},this.storage=t??new FL}async tokens(e){const t=await this.storage.getTokens(e);if(!t)return null;if(HNt(t)){if(t.refreshToken)try{return await this.refreshTokens(e,t.refreshToken)}catch(r){return f.warn(`[NeuroLinkOAuthProvider] Token refresh failed: ${r instanceof Error?r.message:String(r)}`),await this.storage.deleteTokens(e),null}return await this.storage.deleteTokens(e),null}return t}async saveTokens(e,t){await this.storage.saveTokens(e,t)}async deleteTokens(e){await this.storage.deleteTokens(e)}clientInformation(){return{clientId:this.config.clientId,clientSecret:this.config.clientSecret,redirectUri:this.config.redirectUrl}}redirectToAuthorization(e){const t=this.generateState();this.pendingStates.add(t);const r=new URL(this.config.authorizationUrl);r.searchParams.set("response_type","code"),r.searchParams.set("client_id",this.config.clientId),r.searchParams.set("redirect_uri",this.config.redirectUrl),r.searchParams.set("state",t),this.config.scope&&r.searchParams.set("scope",this.config.scope);let n;if(this.config.usePKCE){const o=this.generatePKCE();n=o.codeVerifier,this.pendingChallenges.set(t,o),r.searchParams.set("code_challenge",o.codeChallenge),r.searchParams.set("code_challenge_method",o.codeChallengeMethod)}if(this.config.additionalParams)for(const[o,s]of Object.entries(this.config.additionalParams))r.searchParams.set(o,s);return{url:r.toString(),state:t,codeVerifier:n}}async exchangeCode(e,t){if(!this.pendingStates.has(t.state))throw new Error("Invalid or expired state parameter");this.pendingStates.delete(t.state);let r=t.codeVerifier;if(this.config.usePKCE&&!r){const a=this.pendingChallenges.get(t.state);a&&(r=a.codeVerifier,this.pendingChallenges.delete(t.state))}const n=new URLSearchParams;n.set("grant_type","authorization_code"),n.set("code",t.code),n.set("redirect_uri",this.config.redirectUrl),n.set("client_id",this.config.clientId),this.config.clientSecret&&n.set("client_secret",this.config.clientSecret),r&&n.set("code_verifier",r);const o=await Ze(fetch(this.config.tokenUrl,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:n.toString()}),ny,new Error(`OAuth token exchange timed out after ${ny}ms`));if(!o.ok){const a=await o.text();throw new Error(`Token exchange failed: ${o.status} ${o.statusText} - ${a}`)}const s=await o.json(),i={accessToken:s.access_token,refreshToken:s.refresh_token,expiresAt:s.expires_in?nre(s.expires_in):void 0,tokenType:s.token_type??"Bearer",scope:s.scope};return await this.saveTokens(e,i),i}async refreshTokens(e,t){const r=new URLSearchParams;r.set("grant_type","refresh_token"),r.set("refresh_token",t),r.set("client_id",this.config.clientId),this.config.clientSecret&&r.set("client_secret",this.config.clientSecret);const n=await Ze(fetch(this.config.tokenUrl,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:r.toString()}),ny,new Error(`OAuth token refresh timed out after ${ny}ms`));if(!n.ok){const i=await n.text();throw new Error(`Token refresh failed: ${n.status} ${n.statusText} - ${i}`)}const o=await n.json(),s={accessToken:o.access_token,refreshToken:o.refresh_token??t,expiresAt:o.expires_in?nre(o.expires_in):void 0,tokenType:o.token_type??"Bearer",scope:o.scope};return await this.saveTokens(e,s),s}async revokeTokens(e,t){const r=await this.storage.getTokens(e);if(!r)return;const n=new URLSearchParams;n.set("token",r.accessToken),n.set("client_id",this.config.clientId),this.config.clientSecret&&n.set("client_secret",this.config.clientSecret);try{await Ze(fetch(t,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:n.toString()}),ny,new Error(`OAuth token revocation timed out after ${ny}ms`))}catch(o){f.warn(`[NeuroLinkOAuthProvider] Token revocation failed: ${o instanceof Error?o.message:String(o)}`)}await this.storage.deleteTokens(e)}async getAuthorizationHeader(e){const t=await this.tokens(e);return t?`${t.tokenType} ${t.accessToken}`:null}async hasValidTokens(e){return await this.tokens(e)!==null}generateState(){return Tf(32).toString("base64url")}generatePKCE(){const e=Tf(32).toString("base64url"),t=Qc("sha256").update(e).digest("base64url");return{codeVerifier:e,codeChallenge:t,codeChallengeMethod:"S256"}}getConfig(){return{...this.config}}getStorage(){return this.storage}cleanupPendingRequests(){this.pendingStates.size>100&&this.pendingStates.clear(),this.pendingChallenges.size>100&&this.pendingChallenges.clear()}}}}),KNt=S({"src/lib/mcp/auth/index.ts"(){"use strict";WNt(),Fqr()}}),JNt={};he(JNt,{MCPClientFactory:()=>Z_});var YNt,ore,ZNt,sre,Z_,ire=S({"src/lib/mcp/mcpClientFactory.ts"(){"use strict";pjr(),ZOt(),Dqr(),Oqr(),Nqr(),q(),Xte(),yt(),qNt(),GNt(),KNt(),ro(),m0(),YNt=Math.max(5e3,Number(process.env.MCP_CLIENT_TIMEOUT)||6e4),ore=20,ZNt=class{lines=[];partial="";append(e){this.partial+=e.toString();const t=this.partial.split(/\r?\n/);this.partial=t.pop()??"";for(const r of t)r.trim().length!==0&&(this.lines.push(r),this.lines.length>ore&&this.lines.shift())}snapshot(){const e=[...this.lines];return this.partial.trim().length>0&&e.push(this.partial),e.slice(-ore)}},sre=new WeakMap,Z_=class{static NEUROLINK_IMPLEMENTATION={name:"neurolink-sdk",version:"1.0.0"};static DEFAULT_CAPABILITIES={sampling:{},roots:{listChanged:!1}};static async createClient(e,t=YNt){const r=Date.now(),{traceId:n,parentSpanId:o}=p0(),s=Oe.createSpan("mcp.transport","mcp.connect",{"mcp.transport":e.transport,"mcp.operation":"connect","mcp.server_id":e.id},o,n);try{de.info(`[MCPClientFactory] Creating client for ${e.id}`,{transport:e.transport,command:e.command,hasRetryConfig:!!e.retryConfig,hasRateLimiting:!!e.rateLimiting,hasAuth:!!e.auth}),(e.transport==="http"||e.transport==="sse")&&e.rateLimiting&&(await rre.getLimiter(e.id,{requestsPerWindow:e.rateLimiting.requestsPerMinute??60,windowMs:6e4,maxBurst:e.rateLimiting.maxBurst??10,useTokenBucket:e.rateLimiting.useTokenBucket??!0,refillRate:(e.rateLimiting.requestsPerMinute??60)/60}).acquire(),de.debug(`[MCPClientFactory] Rate limit token acquired for ${e.id}`));const i=rx.getBreaker(`mcp-client-${e.id}`,{failureThreshold:3,resetTimeout:3e4,operationTimeout:t}),a=async()=>await i.execute(async()=>await this.createClientInternal(e,t));let l;(e.transport==="http"||e.transport==="sse")&&e.retryConfig?(de.debug(`[MCPClientFactory] Using retry logic for ${e.id}`,{maxAttempts:e.retryConfig.maxAttempts??cd.maxAttempts}),l=await jNt(a,{maxAttempts:e.retryConfig.maxAttempts??cd.maxAttempts,initialDelay:e.retryConfig.initialDelay??cd.initialDelay,maxDelay:e.retryConfig.maxDelay??cd.maxDelay,backoffMultiplier:e.retryConfig.backoffMultiplier??cd.backoffMultiplier})):l=await a(),de.info(`[MCPClientFactory] Client created successfully for ${e.id}`,{duration:Date.now()-r,capabilities:l.capabilities}),s.durationMs=Date.now()-r;const c=Oe.endSpan(s,1);return ut().recordSpan(c),{...l,success:!0,duration:Date.now()-r}}catch(i){const a=i instanceof Error?i.message:String(i);if(i instanceof am){de.warn(`[MCPClientFactory] Client creation blocked by circuit breaker for ${e.id}`,{serverId:e.id,breakerState:i.breakerState,retryAfter:i.retryAfter,retryAfterMs:i.retryAfterMs,failureCount:i.failureCount}),s.durationMs=Date.now()-r;const c=Oe.endSpan(s,2);return c.statusMessage=`Circuit breaker open: ${a}`,ut().recordSpan(c),{success:!1,error:a,duration:Date.now()-r}}de.debug(`[MCPClientFactory] Failed to create client for ${e.id}:`,i),s.durationMs=Date.now()-r;const l=Oe.endSpan(s,2);return l.statusMessage=a,ut().recordSpan(l),{success:!1,error:a,duration:Date.now()-r}}}static async createClientInternal(e,t){const n=(await this.createTransport(e)).transport;try{const o=new pNt(this.NEUROLINK_IMPLEMENTATION,{capabilities:this.DEFAULT_CAPABILITIES});await Promise.race([o.connect(n),this.createTimeoutPromise(t,`Client connection timeout for ${e.id}`)]);const s=await this.performHandshake(o,t);return de.debug(`[MCPClientFactory] Handshake completed for ${e.id}`,{capabilities:s}),{client:o,transport:n,capabilities:s}}catch(o){try{await n.close()}catch(i){de.debug("[MCPClientFactory] Error closing transport during cleanup:",i)}const s=this.getStderrTail(n);throw o instanceof Error&&s.length>0?new Error(`${o.message}
|
|
1484
1484
|
Server stderr (last ${s.length} lines):
|
|
1485
1485
|
${s.join(`
|
|
1486
|
-
`)}`,{cause:o}):o}}static getStderrTail(e){return sre.get(e)?.snapshot()??[]}static async createTransport(e){switch(e.transport){case"stdio":return this.createStdioTransport(e);case"sse":return this.createSSETransport(e);case"websocket":return this.createWebSocketTransport(e);case"http":return this.createHTTPTransport(e);default:throw new Error(`Unsupported transport type: ${e.transport}`)}}static async createStdioTransport(e){if(de.debug(`[MCPClientFactory] Creating stdio transport for ${e.id}`,{command:e.command,args:e.args}),!e.command)throw new Error("Command is required for stdio transport");const t=new Pte({command:e.command,args:e.args||[],env:Object.fromEntries(Object.entries({...process.env,...e.env}).filter(([,n])=>n!==void 0).map(([n,o])=>[n,String(o)])),cwd:e.cwd,stderr:"pipe"}),r=new ZNt;return sre.set(t,r),t.stderr?.on("data",n=>{if(r.append(n),de.shouldLog("debug")){const o=n.toString().trim();o.length>0&&de.debug(`[MCPClientFactory] ${e.id} stderr:`,o)}}),{transport:t}}static async createSSETransport(e){if(!e.url)throw new Error("URL is required for SSE transport");de.debug(`[MCPClientFactory] Creating SSE transport for ${e.id}`,{url:e.url});try{const t=new URL(e.url);return{transport:new NNt(t)}}catch(t){throw new Error(`Invalid SSE URL: ${t instanceof Error?t.message:String(t)}`,{cause:t})}}static async createWebSocketTransport(e){if(!e.url)throw new Error("URL is required for WebSocket transport");de.debug(`[MCPClientFactory] Creating WebSocket transport for ${e.id}`,{url:e.url});try{const t=new URL(e.url);return{transport:new $Nt(t)}}catch(t){throw new Error(`Invalid WebSocket URL: ${t instanceof Error?t.message:String(t)}`,{cause:t})}}static async createHTTPTransport(e){if(!e.url)throw new Error("URL is required for HTTP transport");const t={connectionTimeout:e.httpOptions?.connectionTimeout??3e4,requestTimeout:e.httpOptions?.requestTimeout??6e4,idleTimeout:e.httpOptions?.idleTimeout??12e4,keepAliveTimeout:e.httpOptions?.keepAliveTimeout??3e4};de.debug(`[MCPClientFactory] Creating HTTP transport for ${e.id}`,{url:e.url,hasHeaders:!!e.headers,hasAuth:!!e.auth,authType:e.auth?.type,httpOptions:t});try{const r=new URL(e.url),n=await this.setupAuthProvider(e),o={...e.headers??{}};if(e.auth){const l=await this.getAuthorizationHeader(e,n);l&&(o.Authorization=l)}const s=this.createEnhancedFetch(e,t.requestTimeout,n),i={headers:Object.keys(o).length>0?o:void 0};return{transport:new UNt(r,{requestInit:i,fetch:s})}}catch(r){throw new Error(`Invalid HTTP URL: ${r instanceof Error?r.message:String(r)}`,{cause:r})}}static createFetchWithTimeout(e){return async(t,r)=>{const n=new AbortController,o=setTimeout(()=>n.abort(),e);try{return await fetch(t,{...r,signal:n.signal})}finally{clearTimeout(o)}}}static createEnhancedFetch(e,t,r){const n=this.createFetchWithTimeout(t);return async(o,s)=>{if(r&&e.auth?.type==="oauth2")try{const i=await r.getAuthorizationHeader(e.id);if(i){const a=s?.headers??{},l=new Headers(a);l.set("Authorization",i),s={...s,headers:l}}}catch(i){de.warn(`[MCPClientFactory] OAuth token refresh failed for ${e.id}:`,i instanceof Error?i.message:String(i))}return n(o,s)}}static async setupAuthProvider(e){if(e.auth?.type==="oauth2"&&e.auth.oauth){const t=new FL,r={clientId:e.auth.oauth.clientId,clientSecret:e.auth.oauth.clientSecret,authorizationUrl:e.auth.oauth.authorizationUrl,tokenUrl:e.auth.oauth.tokenUrl,redirectUrl:e.auth.oauth.redirectUrl,scope:e.auth.oauth.scope,usePKCE:e.auth.oauth.usePKCE??!0},n=new UL(r,t);return de.debug(`[MCPClientFactory] OAuth provider created for ${e.id}`,{clientId:r.clientId,usePKCE:r.usePKCE}),n}}static async getAuthorizationHeader(e,t){if(e.auth)switch(e.auth.type){case"oauth2":return t?await t.getAuthorizationHeader(e.id)??void 0:void 0;case"bearer":return e.auth.token?`Bearer ${e.auth.token}`:void 0;case"api-key":return;default:return}}static async performHandshake(e,t){try{const r=await Promise.race([this.getServerInfo(e),this.createTimeoutPromise(t,"Handshake timeout")]);return this.extractCapabilities(r)}catch(r){return de.warn("[MCPClientFactory] Handshake failed, but connection may still be valid:",r),this.DEFAULT_CAPABILITIES}}static async getServerInfo(e){try{return{tools:(await e.listTools()).tools||[],capabilities:this.DEFAULT_CAPABILITIES}}catch{return de.debug("[MCPClientFactory] Tool listing failed, server may not support tools yet"),{tools:[],capabilities:this.DEFAULT_CAPABILITIES}}}static extractCapabilities(e){return{...this.DEFAULT_CAPABILITIES,...e.tools?{tools:{}}:{}}}static createTimeoutPromise(e,t,r){return new Promise((n,o)=>{const s=setTimeout(()=>{o(new Error(t))},e);r&&r.addEventListener("abort",()=>{clearTimeout(s),o(new Error(`Operation aborted: ${t}`))})})}static async closeClient(e,t,r){const n=[];try{await e.close()}catch(o){n.push(`Client close error: ${o instanceof Error?o.message:String(o)}`)}try{await t.close()}catch(o){n.push(`Transport close error: ${o instanceof Error?o.message:String(o)}`)}if(r&&!r.killed)try{r.kill("SIGTERM"),await new Promise(o=>{const s=setTimeout(()=>{if(!r.killed){de.warn("[MCPClientFactory] Force killing process");try{r.kill("SIGKILL")}catch(i){de.debug("[MCPClientFactory] Error in force kill:",i)}}o()},5e3);r.on("exit",()=>{clearTimeout(s),o()})})}catch(o){n.push(`Process kill error: ${o instanceof Error?o.message:String(o)}`)}n.length>0&&de.warn("[MCPClientFactory] Errors during client cleanup:",n)}static async testConnection(e,t=5e3){let r,n,o;try{const s=await this.createClient(e,t);if(!s.success)return{success:!1,error:s.error};if(r=s.client,n=s.transport,o=s.process,r)try{await r.listTools()}catch{de.debug("[MCPClientFactory] Tool listing failed during test, but connection may be valid")}return{success:!0,capabilities:s.capabilities}}catch(s){return{success:!1,error:s instanceof Error?s.message:String(s)}}finally{if(r&&n)try{await this.closeClient(r,n,o)}catch(s){de.debug("[MCPClientFactory] Error cleaning up test connection:",s)}}}static validateClientConfig(e){const t=[];if(e.command||t.push("Command is required"),e.transport||t.push("Transport is required"),["stdio","sse","websocket","http"].includes(e.transport)||t.push("Transport must be stdio, sse, websocket, or http"),e.transport==="sse"||e.transport==="websocket"||e.transport==="http")if(!e.url)t.push(`URL is required for ${e.transport} transport`);else try{new URL(e.url)}catch{t.push(`Invalid URL for ${e.transport} transport`)}return e.transport==="stdio"&&(Array.isArray(e.args)||t.push("Args array is required for stdio transport")),{isValid:t.length===0,errors:t}}static getSupportedTransports(){return["stdio","sse","websocket","http"]}static getDefaultCapabilities(){return{...this.DEFAULT_CAPABILITIES}}}}});function XNt(e,t){if(t<=0)return"";try{const r=JSON.stringify(e);return typeof r!="string"?"":r.length<=t?r:r.slice(0,Math.max(0,t-1))+"\u2026"}catch{return""}}function BL(e,t=0){if(t>10)return"[...]";if(e==null||typeof e!="object")return e;if(Array.isArray(e))return e.map(n=>BL(n,t+1));const r={};for(const[n,o]of Object.entries(e))eLt.test(n)?r[n]="[REDACTED]":r[n]=BL(o,t+1);return r}var QNt,eLt,are,tLt,Uqr=S({"src/lib/mcp/toolDiscoveryService.ts"(){"use strict";vn(),q(),Xte(),Af(),gg(),at(),dD(),EC(),tr(),vr(),Kr(),QNt=He.mcp,eLt=/^(password|passwd|secret|token|api[_-]?key|apikey|access[_-]?key|authorization|auth|bearer|credential|cookie|session[_-]?id|private[_-]?key|client[_-]?secret|refresh[_-]?token|x-api-key)$/i,are=Math.max(5e3,Number(process.env.MCP_TOOL_TIMEOUT)||6e4),tLt=class extends sn{serverToolStorage=new Map;toolRegistry=new Map;serverTools=new Map;discoveryInProgress=new Set;outputNormalizer;constructor(){super()}setOutputNormalizer(e){this.outputNormalizer=e}async discoverTools(e,t,r=are){return gt({name:"neurolink.mcp.discoverTools",tracer:He.mcp,attributes:{"mcp.server_id":e}},async n=>{const o=Date.now();try{if(this.discoveryInProgress.has(e))return{success:!1,error:`Discovery already in progress for server: ${e}`,toolCount:0,tools:[],duration:Date.now()-o,serverId:e};this.discoveryInProgress.add(e),de.info(`[ToolDiscoveryService] Starting tool discovery for server: ${e}`);const i=await rx.getBreaker(`tool-discovery-${e}`,{failureThreshold:2,resetTimeout:6e4,operationTimeout:r}).execute(async()=>await this.performToolDiscovery(e,t,r)),a=await this.registerDiscoveredTools(e,i);n.setAttribute("mcp.tools_discovered",a.length);const l={success:!0,toolCount:a.length,tools:a,duration:Date.now()-o,serverId:e};return this.emit("discoveryCompleted",{serverId:e,toolCount:a.length,duration:l.duration,timestamp:new Date}),de.info(`[ToolDiscoveryService] Discovery completed for ${e}: ${a.length} tools`),l}catch(s){const i=s instanceof Error?s.message:String(s);return n.setStatus({code:ze.ERROR,message:i}),n.recordException(s instanceof Error?s:new Error(i)),de.error(`[ToolDiscoveryService] Discovery failed for ${e}:`,s),this.emit("discoveryFailed",{serverId:e,error:i,timestamp:new Date}),{success:!1,error:i,toolCount:0,tools:[],duration:Date.now()-o,serverId:e}}finally{this.discoveryInProgress.delete(e)}})}async performToolDiscovery(e,t,r){const n=t.listTools(),o=this.createTimeoutPromise(r,"Tool discovery timeout"),s=await Promise.race([n,o]);if(!s||!s.tools)throw new Error("No tools returned from server");return de.debug(`[ToolDiscoveryService] Discovered ${s.tools.length} tools from ${e}`),s.tools}async registerDiscoveredTools(e,t){const r=[];this.clearServerTools(e);for(const n of t)try{const o=await this.createToolInfo(e,n),s=this.validateTool(o);if(!s.isValid){de.warn(`[ToolDiscoveryService] Skipping invalid tool ${n.name} from ${e}:`,s.errors);continue}s.metadata&&(o.metadata={...o.metadata,...s.metadata});const i=this.createToolKey(e,n.name);this.toolRegistry.set(i,o),this.serverToolStorage.has(e)||this.serverToolStorage.set(e,[]);const a=this.serverToolStorage.get(e);if(!a)throw new Error(`Server tools storage not found for ${e}`);a.find(c=>c.name===n.name)||a.push({name:n.name,description:n.description||"",inputSchema:n.inputSchema}),this.serverTools.has(e)||this.serverTools.set(e,new Set);const l=this.serverTools.get(e);l&&l.add(n.name),r.push(o),this.emit("toolRegistered",{serverId:e,toolName:n.name,toolInfo:o,timestamp:new Date}),de.debug(`[ToolDiscoveryService] Registered tool: ${n.name} from ${e}`)}catch(o){de.error(`[ToolDiscoveryService] Failed to register tool ${n.name} from ${e}:`,o)}return r}async createToolInfo(e,t){return{name:t.name,description:t.description||"No description provided",serverId:e,inputSchema:t.inputSchema,isAvailable:!0,stats:{totalCalls:0,successfulCalls:0,failedCalls:0,averageExecutionTime:0,lastExecutionTime:0},metadata:{category:this.inferToolCategory(t),version:"1.0.0",deprecated:!1}}}inferToolCategory(e){const t=e.name.toLowerCase(),r=(e.description||"").toLowerCase();return t.includes("git")||r.includes("git")?"version-control":t.includes("file")||t.includes("read")||t.includes("write")?"file-system":t.includes("api")||t.includes("http")||t.includes("request")?"api":t.includes("data")||t.includes("query")||t.includes("search")?"data":t.includes("auth")||t.includes("login")||t.includes("token")?"authentication":t.includes("deploy")||t.includes("build")||t.includes("ci")?"deployment":"general"}validateTool(e){const t=[],r=[],n=wC(e.name);n&&t.push(n.message);const o=h4(e.description);if(o&&r.push(o.message),e.serverId||t.push("Server ID is required"),e.inputSchema)try{JSON.stringify(e.inputSchema)}catch{t.push("Input schema is not valid JSON")}const s={category:typeof e.metadata?.category=="string"?e.metadata.category:"general",complexity:this.inferComplexity(e),requiresAuth:this.inferAuthRequirement(e),isDeprecated:typeof e.metadata?.deprecated=="boolean"?e.metadata.deprecated:!1};return{isValid:t.length===0,errors:t,warnings:r,metadata:s}}inferComplexity(e){const t=e.inputSchema;if(!t||!t.properties)return"simple";const r=Object.keys(t.properties).length;return r<=2?"simple":r<=5?"moderate":"complex"}inferAuthRequirement(e){const t=e.name.toLowerCase(),r=e.description.toLowerCase();return t.includes("auth")||t.includes("login")||t.includes("token")||r.includes("authentication")||r.includes("credentials")||r.includes("permission")}async executeTool(e,t,r,n,o={}){const s=Date.now();try{const i=this.createToolKey(t,e),a=this.toolRegistry.get(i);if(!a)throw new Error(`Tool '${e}' not found for server '${t}'`);if(!a.isAvailable)throw new Error(`Tool '${e}' is not available`);let l=n;o.validateInput!==!1&&(l=this.validateToolParameters(a,n)),de.debug(`[ToolDiscoveryService] Executing tool: ${e} on ${t}`,{parameters:l});const c=o.timeout||are,d=await rx.getBreaker(`tool-execution-${t}-${e}`,{failureThreshold:3,resetTimeout:3e4,operationTimeout:c}).execute(async()=>QNt.startActiveSpan("neurolink.mcp.callTool",{kind:jr.CLIENT,attributes:{"mcp.server_id":t,"mcp.tool_name":e,"mcp.timeout_ms":c,"ai.tool.name":e,"gen_ai.tool.name":e,"gen_ai.request":XNt({name:e,arguments:BL(l)},2048)}},async h=>{try{const g=c,y=await Ze(r.callTool({name:e,arguments:l},void 0,{timeout:c}),g,new Error(`Tool execution timeout: ${e}`)),v=y;if(v&&v.isError===!0){const T=E4(v);h.setStatus({code:ze.ERROR,message:T||`Tool ${e} returned isError`})}else h.setStatus({code:ze.OK});let _=y,b=y;if(this.outputNormalizer)try{const T=await this.outputNormalizer.normalize(y,{toolName:e,serverId:t});h.setAttribute("mcp.output.strategy",T.isExternalized?"externalize":"inline"),T.isExternalized&&h.setAttribute("mcp.output.original_bytes",T.originalBytes),_=T.result,b=T.result}catch(T){de.warn(`[ToolDiscoveryService] McpOutputNormalizer failed for ${e}: ${T instanceof Error?T.message:String(T)} \u2014 returning raw result`)}return h.setAttribute("gen_ai.response",XNt(BL(_),2048)),b}catch(g){throw h.setStatus({code:ze.ERROR,message:g.message}),h.recordException(g),g}finally{h.end()}})),m=Date.now()-s;return this.updateToolStats(i,!0,m),o.validateOutput!==!1&&this.validateToolOutput(d),de.debug(`[ToolDiscoveryService] Tool execution completed: ${e}`,{duration:m,hasContent:!!d?.content}),{success:!0,data:d,duration:m,metadata:{toolName:e,serverId:t,timestamp:Date.now()}}}catch(i){const a=Date.now()-s,l=i instanceof Error?i.message:String(i),c=this.createToolKey(t,e);return this.updateToolStats(c,!1,a),i instanceof am?(de.warn(`[ToolDiscoveryService] Tool blocked by circuit breaker: ${e} on ${t}`,{breakerState:i.breakerState,retryAfter:i.retryAfter,retryAfterMs:i.retryAfterMs,failureCount:i.failureCount}),{success:!1,error:i.message,data:{isError:!0,content:[{type:"text",text:`TOOL TEMPORARILY UNAVAILABLE: "${e}" has been disabled after ${i.failureCount} failures. This is a circuit breaker protection \u2014 do NOT retry this tool. It will become available again after ${Math.ceil(i.retryAfterMs/1e3)} seconds (at ${i.retryAfter}). Instead, inform the user that the operation failed and suggest trying again later.`}]},duration:a,metadata:{toolName:e,serverId:t,timestamp:Date.now(),circuitBreaker:{state:i.breakerState,retryAfter:i.retryAfter,retryAfterMs:i.retryAfterMs,failureCount:i.failureCount}}}):(de.error(`[ToolDiscoveryService] Tool execution failed: ${e}`,i),{success:!1,error:l,duration:a,metadata:{toolName:e,serverId:t,timestamp:Date.now()}})}}validateToolParameters(e,t){if(!e.inputSchema)return t;const r=e.inputSchema,n=r.properties&&typeof r.properties=="object"?r.properties:{},o=Array.isArray(r.required)?r.required.filter(l=>typeof l=="string"):[],s=()=>Object.entries(n).map(([l,c])=>`${l}${o.includes(l)?"":"?"}: ${c.type??"any"}`).join(", "),i=o.filter(l=>!(l in t));if(i.length>0)throw new Error(`Missing required parameter${i.length>1?"s":""}: ${i.join(", ")}. Expected arguments: { ${s()} }; received keys: [${Object.keys(t).join(", ")}]`);let a;for(const[l,c]of Object.entries(n))if(l in t){const u=t[l],d=Q9(u,c);d!==u&&(de.debug(`[ToolDiscoveryService] Coerced parameter '${l}' for tool '${e.name}': ${typeof u} \u2192 ${typeof d}`),a=a??{...t},a[l]=d),this.validateParameterType(l,a?a[l]:u,c)}return a??t}validateParameterType(e,t,r){if(!r.type)return;const n=r.type,o=typeof t;switch(n){case"string":if(o!=="string")throw new Error(`Parameter '${e}' must be a string, got ${o}`);break;case"number":if(o!=="number")throw new Error(`Parameter '${e}' must be a number, got ${o}`);break;case"integer":if(o!=="number"||!Number.isInteger(t))throw new Error(`Parameter '${e}' must be an integer, got ${o==="number"?String(t):o}`);break;case"boolean":if(o!=="boolean")throw new Error(`Parameter '${e}' must be a boolean, got ${o}`);break;case"array":if(!Array.isArray(t))throw new Error(`Parameter '${e}' must be an array, got ${o}`);break;case"object":if(o!=="object"||t===null||Array.isArray(t))throw new Error(`Parameter '${e}' must be an object, got ${o}`);break}}validateToolOutput(e){if(dTr(e)){de.debug("[ToolDiscoveryService] Tool returned null/undefined, treating as empty response");return}de.debug("[ToolDiscoveryService] Tool response received",{type:typeof e,isArray:Array.isArray(e),isObject:EM(e),hasKeys:EM(e)?Object.keys(e).length:0,fullResponse:e})}updateToolStats(e,t,r){const n=this.toolRegistry.get(e);if(!n)return;n.stats.totalCalls++,n.lastCalled=new Date,n.stats.lastExecutionTime=r,t?n.stats.successfulCalls++:n.stats.failedCalls++;const o=n.stats.averageExecutionTime*(n.stats.totalCalls-1)+r;n.stats.averageExecutionTime=o/n.stats.totalCalls}getTool(e,t){const r=this.createToolKey(t,e);return this.toolRegistry.get(r)}getServerTools(e){const t=this.serverToolStorage.get(e);if(t)return t.map(o=>({name:o.name,description:o.description,serverId:e,inputSchema:o.inputSchema,isAvailable:!0,stats:{totalCalls:0,successfulCalls:0,failedCalls:0,averageExecutionTime:0,lastExecutionTime:0}}));const r=[],n=this.serverTools.get(e);if(n)for(const o of n){const s=this.createToolKey(e,o),i=this.toolRegistry.get(s);i&&r.push(i)}return r}getAllTools(){const e=[];for(const[r,n]of this.serverToolStorage.entries())for(const o of n)e.push({name:o.name,description:o.description,serverId:r,inputSchema:o.inputSchema,isAvailable:!0,stats:{totalCalls:0,successfulCalls:0,failedCalls:0,averageExecutionTime:0,lastExecutionTime:0}});const t=Array.from(this.toolRegistry.values()).filter(r=>!e.some(n=>n.name===r.name&&n.serverId===r.serverId));return[...e,...t]}clearServerTools(e){const t=this.serverToolStorage.get(e);if(t){for(const n of t)this.emit("toolUnregistered",{serverId:e,toolName:n.name,timestamp:new Date});this.serverToolStorage.delete(e)}const r=this.serverTools.get(e);if(r){for(const n of r){const o=this.createToolKey(e,n);this.toolRegistry.delete(o),(!t||!t.find(s=>s.name===n))&&this.emit("toolUnregistered",{serverId:e,toolName:n,timestamp:new Date})}this.serverTools.delete(e)}de.debug(`[ToolDiscoveryService] Cleared tools for server: ${e}`)}updateToolAvailability(e,t,r){const n=this.createToolKey(t,e),o=this.toolRegistry.get(n);o&&(o.isAvailable=r,de.debug(`[ToolDiscoveryService] Updated availability for ${e}: ${r}`))}createToolKey(e,t){return`${e}:${t}`}createTimeoutPromise(e,t){return new Promise((r,n)=>{setTimeout(()=>{n(new Error(t))},e)})}destroy(){de.debug("[ToolDiscoveryService] Starting cleanup..."),this.removeAllListeners(),this.serverToolStorage.clear(),this.toolRegistry.clear(),this.serverTools.clear(),this.discoveryInProgress.clear(),de.debug("[ToolDiscoveryService] Destroyed and cleaned up")}resetStatistics(){for(const e of this.toolRegistry.values())e.stats={totalCalls:0,successfulCalls:0,failedCalls:0,averageExecutionTime:0,lastExecutionTime:0},e.lastCalled=void 0;de.debug("[ToolDiscoveryService] Statistics reset for all tools")}getListenerCount(){const e=["discoveryCompleted","discoveryFailed","toolRegistered","toolUnregistered"];let t=0;for(const r of e)t+=this.listenerCount(r);return t}getStatistics(){const e={},t={};let r=0,n=0;for(const o of this.toolRegistry.values()){e[o.serverId]=(e[o.serverId]||0)+1;const s=typeof o.metadata?.category=="string"?o.metadata.category:"unknown";t[s]=(t[s]||0)+1,o.isAvailable?r++:n++}return{totalTools:this.toolRegistry.size,availableTools:r,unavailableTools:n,totalServers:this.serverTools.size,toolsByServer:e,toolsByCategory:t}}}}}),rLt,Bqr=S({"src/lib/mcp/registry.ts"(){"use strict";q(),rLt=class{plugins=new Map;register(e){this.plugins.set(e.metadata.name,e),dr.debug(`Registered plugin: ${e.metadata.name}`)}unregister(e){const t=this.plugins.delete(e);return t&&dr.debug(`Unregistered plugin: ${e}`),t}get(e){return this.plugins.get(e)}list(){return Array.from(this.plugins.values())}has(e){return this.plugins.has(e)}clear(){this.plugins.clear(),dr.info("Registry cleared")}async registerServer(e,t,r){const n={metadata:{name:e,description:typeof t=="object"&&t&&t.description||"No description"},tools:typeof t=="object"&&t?t.tools:{},configuration:typeof t=="object"&&t?t:{}};this.register(n)}async executeTool(e,t,r){return dr.info(`Executing tool: ${e}`),{result:`Mock execution of ${e}`,args:t}}async listTools(e){return this.list().map(r=>({name:r.metadata.name,description:r.metadata.description||"No description",serverId:r.metadata.name,category:"general"}))}registerServerSync(e){this.register(e)}executeToolSync(e,t){return dr.info(`Executing tool (sync): ${e}`),{result:`Mock execution of ${e}`,args:t}}listToolsSync(){return this.list().map(t=>({name:t.metadata.name,description:t.metadata.description||"No description"}))}listServers(){return Array.from(this.plugins.keys())}}}});function Ia(e){return e.existingCategory&&["external","in-memory","built-in","user-defined"].includes(e.existingCategory)?e.existingCategory:e.isCustomTool?"user-defined":e.isBuiltIn?"built-in":e.isExternal?"external":e.serverId?.startsWith("custom-tool-")?"user-defined":e.serverId?.includes("external")?"external":e.serverId==="direct"?"built-in":"in-memory"}function zqr(e,t){switch(t){case"external":return`External MCP server: ${e}`;case"built-in":return`Built-in tool server: ${e}`;case"custom":case"user-defined":return`Custom tool server: ${e}`;case"in-memory":return`In-memory MCP server: ${e}`;default:return e}}function nLt(e){const t=e.id||`server-${e.name}`,r=e.category||Ia({isCustomTool:e.isCustomTool,isExternal:e.isExternal,isBuiltIn:e.isBuiltIn,serverId:t}),n=e.tools||(e.tool?[e.tool]:[]);return{id:t,name:e.name,transport:e.transport||"stdio",status:e.status||"connected",tools:n,description:e.description||zqr(e.name,r),...e.command&&{command:e.command},...e.args&&{args:e.args},...e.env&&{env:e.env},metadata:{category:r,toolCount:n.length}}}function jqr(e,t,r,n){const o=nLt({id:`custom-tool-${e}`,name:e,tool:{name:e,description:t.description||e,inputSchema:t.inputSchema||{},execute:t.execute},isCustomTool:!0});return o.metadata&&(r!==void 0&&(o.metadata.toolTimeoutMs=r),n!==void 0&&(o.metadata.toolMaxRetries=n)),o}var lre=S({"src/lib/utils/mcpDefaults.ts"(){"use strict"}}),oLt,qqr=S({"src/lib/mcp/flexibleToolValidator.ts"(){"use strict";q(),oLt=class{static MAX_TOOL_NAME_LENGTH=1e3;static MIN_TOOL_NAME_LENGTH=1;static validateToolName(e){const t=[];if(!e||typeof e!="string")return{isValid:!1,error:"Tool name is required and must be a string"};if(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/.test(e))return{isValid:!1,error:"Tool name contains control characters that could break systems"};const n=e.trim();return n.length===0?{isValid:!1,error:"Tool name cannot be empty or whitespace-only"}:n.length<this.MIN_TOOL_NAME_LENGTH?{isValid:!1,error:`Tool name must be at least ${this.MIN_TOOL_NAME_LENGTH} character long`}:n.length>this.MAX_TOOL_NAME_LENGTH?{isValid:!1,error:`Tool name exceeds maximum length of ${this.MAX_TOOL_NAME_LENGTH} characters`}:(n!==e&&t.push("Tool name has leading/trailing whitespace (will be trimmed)"),n.length>200&&t.push("Tool name is unusually long but allowed"),dr.debug(`\u2705 FlexibleToolValidator: Tool '${e}' passed universal safety checks`),{isValid:!0,warnings:t.length>0?t:void 0})}static validateToolInfo(e,t){const r=this.validateToolName(e);if(!r.isValid)return r;const n=[...r.warnings||[]];return t.description&&typeof t.description!="string"?{isValid:!1,error:"Tool description must be a string if provided"}:t.serverId&&typeof t.serverId!="string"?{isValid:!1,error:"Tool serverId must be a string if provided"}:(dr.debug(`\u2705 FlexibleToolValidator: Tool info for '${e}' passed validation`),{isValid:!0,warnings:n.length>0?n:void 0})}static getValidationInfo(){return{philosophy:"Maximum flexibility with universal safety only - following Anthropic's MCP specification",checks:["Empty or whitespace-only names","Excessive length (over 1000 characters)","Control characters that could break systems"],whatIsAllowed:["Dots (github.create_repo, filesystem.read_file)","Hyphens and underscores (my-tool, user_helper)","Numbers (tool1, my_tool_v2)","Unicode characters (\u{1F680}_tool, caf\xE9_manager)","Mixed case (createRepo, ReadFile)","Long descriptive names (enterprise_database_connection_manager)","Any legitimate MCP tool naming pattern"],examples:{valid:["github.create_repo","filesystem.read_file","my-custom-tool","user_helper","tool1","\u{1F680}_rocket_tool","enterprise.database.connection.manager","UPPERCASE_TOOL","mixed_Case.Tool-Name_123"],invalid:[""," ","tool\0","a".repeat(1001)]}}}}}}),sLt={};he(sLt,{AuthError:()=>At,AuthErrorCodes:()=>zL});var zL,At,oa=S({"src/lib/auth/errors.ts"(){"use strict";KE(),zL={INVALID_TOKEN:"AUTH-001",EXPIRED_TOKEN:"AUTH-002",MISSING_TOKEN:"AUTH-003",TOKEN_DECODE_FAILED:"AUTH-004",INVALID_SIGNATURE:"AUTH-005",SESSION_NOT_FOUND:"AUTH-010",SESSION_EXPIRED:"AUTH-011",SESSION_REVOKED:"AUTH-012",INSUFFICIENT_PERMISSIONS:"AUTH-020",INSUFFICIENT_ROLES:"AUTH-021",ACCESS_DENIED:"AUTH-022",USER_NOT_FOUND:"AUTH-030",USER_DISABLED:"AUTH-031",EMAIL_NOT_VERIFIED:"AUTH-032",MFA_REQUIRED:"AUTH-033",PROVIDER_ERROR:"AUTH-040",PROVIDER_NOT_FOUND:"AUTH-041",PROVIDER_INIT_FAILED:"AUTH-042",CONFIGURATION_ERROR:"AUTH-043",CREATION_FAILED:"AUTH-050",REGISTRATION_FAILED:"AUTH-051",DUPLICATE_REGISTRATION:"AUTH-052",MIDDLEWARE_ERROR:"AUTH-060",RATE_LIMITED:"AUTH-061",JWKS_FETCH_FAILED:"AUTH-070",JWKS_KEY_NOT_FOUND:"AUTH-071"},At=Nf("Auth",zL)}}),jL={};he(jL,{AuthContextHolder:()=>HL,createAuthenticatedContext:()=>hLt,getAuthContext:()=>qL,getCurrentSession:()=>aLt,getCurrentUser:()=>nx,globalAuthContext:()=>oy,hasAllPermissions:()=>dLt,hasAnyRole:()=>uLt,hasPermission:()=>GL,hasRole:()=>ure,isAuthenticated:()=>lLt,requireAuth:()=>cre,requirePermission:()=>pLt,requireRole:()=>mLt,requireUser:()=>cLt,runWithAuthContext:()=>iLt});function iLt(e,t){return X_.run(e,t)}function qL(){return X_.getStore()??oy.get()}function nx(){return(X_.getStore()??oy.get())?.user}function aLt(){return(X_.getStore()??oy.get())?.session}function lLt(){return X_.getStore()!==void 0||oy.isAuthenticated()}function cre(){const e=qL();if(!e)throw At.create("MISSING_TOKEN","Authentication required");return e}function cLt(e){const t=cre();if(t.user.id!==e)throw At.create("ACCESS_DENIED","User mismatch");return t}function GL(e){const t=nx();if(!t)return!1;if(t.permissions.includes(e)||t.permissions.includes("*"))return!0;const r=e.split(":");for(let n=r.length-1;n>0;n--){const o=[...r.slice(0,n),"*"].join(":");if(t.permissions.includes(o))return!0}return!1}function ure(e){return nx()?.roles.includes(e)??!1}function uLt(e){const t=nx();return t?e.some(r=>t.roles.includes(r)):!1}function dLt(e){return e.every(t=>GL(t))}function pLt(e){if(!GL(e))throw At.create("INSUFFICIENT_PERMISSIONS",`Permission denied: ${e}`)}function mLt(e){if(!ure(e))throw At.create("INSUFFICIENT_ROLES",`Role required: ${e}`)}function hLt(e,t,r,n){return{...r,user:e,session:t,request:r,authenticatedAt:new Date,provider:n}}var X_,HL,oy,ox=S({"src/lib/auth/authContext.ts"(){"use strict";TC(),oa(),X_=new H0,HL=class{context;set(e){this.context=e}get(){return this.context}clear(){this.context=void 0}getUser(){return this.context?.user}getSession(){return this.context?.session}isAuthenticated(){return this.context!==void 0}hasPermission(e){const t=this.context?.user;if(!t)return!1;if(t.permissions.includes(e)||t.permissions.includes("*"))return!0;const r=e.split(":");for(let n=r.length-1;n>0;n--){const o=[...r.slice(0,n),"*"].join(":");if(t.permissions.includes(o))return!0}return!1}hasRole(e){return this.context?.user.roles.includes(e)??!1}},oy=new HL}}),VL,dre,pre=S({"src/lib/mcp/toolRegistry.ts"(){"use strict";Bqr(),q(),Bt(),kM(),sP(),Qi(),lre(),qqr(),at(),B1(),Il(),tr(),ox(),VL=class extends rLt{tools=new Map;toolImplementations=new Map;toolExecutionStats=new Map;builtInServerInfos=[];hitlManager;constructor(){super(),qG()||this.registerDirectTools()}setHITLManager(e){this.hitlManager=e,e&&e.isEnabled()?dr.info("HITL safety mechanisms enabled for tool execution"):dr.debug("HITL safety mechanisms disabled or not configured")}getHITLManager(){return this.hitlManager}registerDirectTools(){dr.debug("Auto-registering direct tools...");for(const[e,t]of Object.entries(Pf)){if(!t){dr.warn(`Skipping undefined tool during registration: ${e}`);continue}const r=`direct.${e}`,n=ms(t.inputSchema),o={name:e,description:t.description||`Direct tool: ${e}`,inputSchema:n,serverId:"direct",category:Ia({isBuiltIn:!0,serverId:"direct"})};this.tools.set(r,o),this.toolImplementations.set(r,{execute:async(s,i)=>{try{return{success:!0,data:await t.execute(s,{toolCallId:i?.sessionId||"unknown",messages:[]}),metadata:{toolName:e,serverId:"direct",executionTime:0}}}catch(a){return{success:!1,error:a instanceof Error?a.message:String(a),metadata:{toolName:e,serverId:"direct",executionTime:0}}}},description:t.description,inputSchema:n}),dr.debug(`Registered direct tool: ${e} as ${r}`)}dr.debug(`Auto-registered ${Object.keys(Pf).length} direct tools`)}async registerServer(e,t,r){let n;if(typeof e=="string"){const l=e;n=nLt({id:l,name:l,tools:[],isExternal:!0})}else n=e;const o=n.id,s={};for(const l of n.tools)s[l.name]={execute:l.execute||(async()=>{throw new Error(`Tool ${l.name} has no execute function`)}),description:l.description,inputSchema:l.inputSchema,category:Ia({existingCategory:n.metadata?.category,serverId:n.id})};const i={metadata:{name:n.name,description:n.description,category:Ia({existingCategory:n.metadata?.category,serverId:n.id})},tools:s,configuration:{}};this.register(i);const a=n.tools;for(const l of a){const u=o.startsWith("custom-tool-")?l.name:`${o}.${l.name}`,d=n.metadata?.toolTimeoutMs,m=n.metadata?.toolMaxRetries,h={name:l.name,description:l.description,inputSchema:l.inputSchema,outputSchema:void 0,serverId:o,category:Ia({existingCategory:n.metadata?.category,serverId:n.id}),permissions:[],...d!==void 0&&{timeoutMs:d},...m!==void 0&&{maxRetries:m}};this.tools.set(u,h),this.toolImplementations.set(u,{execute:l.execute||(async()=>{throw new Error(`Tool ${l.name} has no execute function`)}),description:l.description,inputSchema:l.inputSchema,category:Ia({existingCategory:n.metadata?.category,serverId:n.id}),...d!==void 0&&{timeoutMs:d},...m!==void 0&&{maxRetries:m}})}if(a.length>0){const l=Ia({existingCategory:n.metadata?.category,serverId:n.id});l==="in-memory"&&(this.builtInServerInfos.push(n),dr.debug(`Added ${l} server to builtInServerInfos: ${o} with ${a.length} tools`))}}async executeTool(e,t,r){const n=Date.now();let o;const s=this.tools.get(e);if(s)o=s.serverId;else for(const i of this.tools.values())if(i.name===e){o=i.serverId;break}return gt({name:"neurolink.tool.registry.execute",tracer:He.mcp,attributes:{[Pe.GEN_AI_TOOL_NAME]:e,[Pe.MCP_SERVER_ID]:o||"builtin","langfuse.internal":!0}},async i=>{try{dr.info(`\u{1F527} [TOOL_EXECUTION] Starting execution: ${e}`,{hasArgs:t!==void 0,hasContext:r!==void 0,sessionId:r?.sessionId});const{tool:a,toolId:l}=this.resolveToolExecutionTarget(e);if(!a)throw new Error(`Tool '${e}' not found in registry`);const c=a.serverId||"unknown",u=c==="direct"?"builtin":c.startsWith("custom-tool-")?"custom":"mcp";i.setAttribute("tool.type",u),i.setAttribute(Pe.MCP_SERVER_ID,c);const d=this.createExecutionContext(r),m=this.toolImplementations.get(l);if(dr.debug(`Looking for tool '${e}' (toolId: '${l}'), found: ${!!m}, type: ${typeof m?.execute}`),dr.debug("Available tools:",Array.from(this.toolImplementations.keys())),!m||typeof m?.execute!="function")throw new Error(`Tool '${e}' implementation not found or not executable`);let h;try{h=JSON.stringify(t).slice(0,4096)}catch{h="[unserializable]"}i.setAttribute("tool.arguments_present",t!==void 0),i.setAttribute("tool.arguments_size",h.length);let g=t;const y=r?.hitlState;if(!y?.triggered&&this.hitlManager&&this.hitlManager.isEnabled())if(this.hitlManager.requiresConfirmation(e,t)){dr.info(`Tool '${e}' requires HITL confirmation`),i.addEvent("tool.hitl_requested");try{y&&(y.triggered=!0);const x=await this.hitlManager.requestConfirmation(e,t,{serverId:a.serverId,sessionId:d.sessionId,userId:d.userId});if(!x.approved)throw i.addEvent("tool.hitl_rejected"),new ZT(`Tool execution rejected by user: ${x.reason||"No reason provided"}`,e,x.reason);i.addEvent("tool.hitl_approved"),x.modifiedArguments!==void 0&&(g=x.modifiedArguments,dr.info(`Tool '${e}' arguments modified by user`)),dr.info(`Tool '${e}' approved for execution (response time: ${x.responseTime}ms)`)}catch(x){throw x instanceof XT?(dr.warn(`Tool '${e}' execution timed out waiting for user confirmation`),x):x instanceof ZT?(dr.info(`Tool '${e}' execution rejected by user`),x):(dr.error(`HITL confirmation failed for tool '${e}':`,x),new Error(`HITL confirmation failed: ${x instanceof Error?x.message:String(x)}`,{cause:x}))}}else dr.debug(`Tool '${e}' does not require HITL confirmation`);dr.debug(`Executing tool '${e}' with args:`,g);const v=await m.execute(g,d);let _;if(v&&typeof v=="object"&&"success"in v&&typeof v.success=="boolean"){const k=v;_={...k,usage:{...k.usage||{},executionTime:Date.now()-n},metadata:{...k.metadata||{},toolName:e,serverId:a.serverId,sessionId:d.sessionId,executionTime:Date.now()-n}}}else _={success:!0,data:v,usage:{executionTime:Date.now()-n},metadata:{toolName:e,serverId:a.serverId,sessionId:d.sessionId,executionTime:Date.now()-n}};const b=Date.now()-n;this.updateStats(e,b);let T;try{T=JSON.stringify(_.data)??"undefined"}catch{T="[unserializable]"}return i.setAttribute("tool.result_length",T.length),i.setAttribute("tool.success",!0),dr.debug(`Tool '${e}' executed successfully in ${b}ms`),_}catch(a){dr.error(`Tool execution failed: ${e}`,a),i.setAttribute("tool.success",!1);const l=a instanceof Error?a.message:String(a);if(l.includes("not found in registry")||l.includes("not executable"))throw a;return i.setStatus({code:ze.ERROR,message:l}),a instanceof Error&&i.recordException(a),{success:!1,data:null,error:a instanceof Error?a.message:String(a),usage:{executionTime:Date.now()-n},metadata:{toolName:e,sessionId:r?.sessionId}}}})}async listTools(e){const t=new Map;for(const o of this.tools.values()){const s=`${o.serverId||"unknown"}.${o.name}`;t.has(s)||t.set(s,o)}let r=Array.from(t.values()),n;return e&&("sessionId"in e||"userId"in e?n=void 0:n=e),n&&(n.category&&(r=r.filter(o=>o.category===n.category)),n.serverId&&(r=r.filter(o=>o.serverId===n.serverId)),n.serverCategory&&(r=r.filter(o=>this.get(o.serverId||"")?.metadata?.category===n.serverCategory)),n.permissions&&n.permissions.length>0&&(r=r.filter(o=>{const s=o.permissions||[];return n.permissions?.some(i=>s.includes(i))??!1}))),dr.debug(`Listed ${r.length} unique tools (${n?"filtered":"unfiltered"})`),r}resolveToolExecutionTarget(e){let t=this.tools.get(e);dr.info(`\u{1F50D} [TOOL_LOOKUP] Direct lookup result for '${e}':`,!!t);let r=e;if(!t){const n=Array.from(this.tools.entries()).filter(([,o])=>o.name===e);if(n.length>1)throw ke.toolExecutionFailed(e,new Error(`Ambiguous tool name '${e}'. Use fully-qualified name 'serverId.${e}'.`));n.length===1&&([r,t]=n[0])}return{tool:t,toolId:r}}createExecutionContext(e){let t;try{t=qL()?.user?.id}catch{}return{...e,sessionId:e?.sessionId??st(),userId:e?.userId??t}}getToolInfo(e){let t=this.tools.get(e);if(!t){for(const r of this.tools.values())if(r.name===e){t=r;break}}if(t)return{tool:t,server:{id:t.serverId||"unknown-server"}}}updateStats(e,t){const r=this.toolExecutionStats.get(e)||{count:0,totalTime:0};r.count+=1,r.totalTime+=t,this.toolExecutionStats.set(e,r)}getExecutionStats(){const e={};for(const[t,r]of this.toolExecutionStats.entries())e[t]={count:r.count,totalTime:r.totalTime,averageTime:r.totalTime/r.count};return e}clearStats(){this.toolExecutionStats.clear()}getBuiltInServerInfos(){return this.builtInServerInfos}getToolsByCategory(e){const t=new Map;for(const[r,n]of this.tools.entries())n.category===e&&!t.has(r)&&t.set(r,n);return Array.from(t.values())}getAvailableTools(e){const t=Array.from(this.tools.values()),r=[],n=[];for(const o of t){const s=`${o.serverId||"unknown"}.${o.name}`,i=e.get(s);i&&i.getState()==="open"?r.push(o.name):n.push(o)}return{tools:n,unavailableTools:r}}hasTool(e){if(this.tools.has(e))return!0;for(const t of this.tools.values())if(t.name===e)return!0;return!1}async registerTool(e,t,r){dr.debug(`Registering tool: ${e}`);const n=oLt.validateToolInfo(e,{description:t.description,serverId:t.serverId});if(!n.isValid)throw dr.error(`Tool registration failed for ${e}: ${n.error}`),new Error(`Tool validation failed: ${n.error}`);n.warnings&&n.warnings.length>0&&dr.warn(`Tool registration warnings for ${e}:`,n.warnings),dr.debug(`\u2705 Tool '${e}' passed flexible validation - registration proceeding`),this.tools.set(e,t),this.toolImplementations.set(e,r),dr.debug(`Successfully registered tool: ${e}`)}removeTool(e){let t=!1;if(this.tools.has(e))this.tools.delete(e),this.toolImplementations.delete(e),this.toolExecutionStats.delete(e),dr.info(`Removed tool: ${e}`),t=!0;else for(const[r,n]of Array.from(this.tools.entries()))n.name===e&&(this.tools.delete(r),this.toolImplementations.delete(r),this.toolExecutionStats.delete(r),dr.info(`Removed tool: ${r}`),t=!0);return t}getToolCount(){return this.tools.size}getStats(){const e=this.list(),t=Array.from(this.tools.values()),r={};for(const o of e){const s=o.metadata?.category||"uncategorized";r[s]=(r[s]||0)+1}const n={};for(const o of t){const s=o.category||"uncategorized";n[s]=(n[s]||0)+1}return{totalServers:e.length,totalTools:t.length,serversByCategory:r,toolsByCategory:n,executionStats:this.getExecutionStats()}}unregisterServer(e){const t=[];for(const[s,i]of this.tools.entries())i.serverId===e&&(this.tools.delete(s),this.toolImplementations.delete(s),this.toolExecutionStats.delete(s),t.push(s));const r=this.builtInServerInfos.length;this.builtInServerInfos=this.builtInServerInfos.filter(s=>s.id!==e);const n=r>this.builtInServerInfos.length,o=this.unregister(e);return dr.info(`Unregistered server ${e}, removed ${t.length} tools${n?" and server from builtInServerInfos":""}`),o}},dre=new VL}});function Q_(e){if(typeof e=="string")return e.replace(/\$\{([^}]+)\}/g,(t,r)=>{const n=process.env[r.trim()];return n===void 0?(de.warn(`[ExternalServerManager] Environment variable ${r} is not defined, using empty string`),""):n});if(Array.isArray(e))return e.map(t=>Q_(t));if(ar(e)){const t={};for(const[r,n]of Object.entries(e))t[r]=Q_(n);return t}return e}function fLt(e){const t=e instanceof Error?e.message:String(e);return yLt.test(t)}function Gqr(e){if(!e||e.length===0)return e;const t=[...e];for(let r=0;r<t.length;r++){const n=t[r].indexOf("=");if(n!==-1){const o=t[r].substring(0,n);fre.test(o)&&(t[r]=`${o}=[REDACTED]`);continue}fre.test(t[r])&&r+1<t.length&&!t[r+1].startsWith("--")&&(t[r+1]="[REDACTED]",r++)}return t}function mre(e){return EM(e)?Object.values(e).every(r=>r===null||typeof r=="string"||typeof r=="number"||typeof r=="boolean"?!0:Array.isArray(r)?r.every(n=>mre(n)||typeof n=="string"||typeof n=="number"||typeof n=="boolean"||n===null):ar(r)?mre(r):!1):!1}function sx(e){return mre(e)?e:void 0}function gLt(e){if(!ar(e))return!1;const t=e;if(t.blockedTools!==void 0&&(!Array.isArray(t.blockedTools)||!t.blockedTools.every(o=>typeof o=="string")))return!1;const r=typeof t.command=="string",n=typeof t.url=="string";return!r&&!n?!1:(t.command===void 0||typeof t.command=="string")&&(t.args===void 0||Array.isArray(t.args))&&(t.env===void 0||ar(t.env))&&(t.transport===void 0||typeof t.transport=="string")&&(t.timeout===void 0||typeof t.timeout=="number")&&(t.retries===void 0||typeof t.retries=="number")&&(t.healthCheckInterval===void 0||typeof t.healthCheckInterval=="number")&&(t.autoRestart===void 0||typeof t.autoRestart=="boolean")&&(t.cwd===void 0||typeof t.cwd=="string")&&(t.url===void 0||typeof t.url=="string")&&(t.headers===void 0||ar(t.headers))&&(t.httpOptions===void 0||ar(t.httpOptions))&&(t.retryConfig===void 0||ar(t.retryConfig))&&(t.rateLimiting===void 0||ar(t.rateLimiting))&&(t.metadata===void 0||ar(t.metadata))}var yLt,hre,fre,WL,gre,KL,vLt,yre,_Lt=S({"src/lib/mcp/externalServerManager.ts"(){"use strict";vn(),ZOt(),q(),ire(),Uqr(),pre(),B1(),lre(),Af(),SS(),vr(),tr(),yLt=/^Not connected$|MCP error -32000: Connection closed/,hre=2,fre=/^--(api-key|token|secret|password|key|figma-api-key|access-token|auth|credential)$/i,WL=new Set,gre=!1,KL=()=>{for(const e of WL)e.shutdown()},vLt=e=>{WL.add(e),gre||(gre=!0,process.on("SIGINT",KL),process.on("SIGTERM",KL),process.on("beforeExit",KL))},yre=class extends sn{servers=new Map;config;isShuttingDown=!1;healthChecksInFlight=new Set;inFlightToolCalls=new Map;unresponsiveChecks=new Map;toolDiscovery;enableMainRegistryIntegration;hitlManager;constructor(e={},t={}){super();const r=Math.max(5e3,Number(process.env.MCP_CLIENT_TIMEOUT)||6e4);this.config={maxServers:e.maxServers??10,defaultTimeout:e.defaultTimeout??r,defaultHealthCheckInterval:e.defaultHealthCheckInterval??3e4,enableAutoRestart:e.enableAutoRestart??!0,maxRestartAttempts:e.maxRestartAttempts??3,restartBackoffMultiplier:e.restartBackoffMultiplier??2,enablePerformanceMonitoring:e.enablePerformanceMonitoring??!0,logLevel:e.logLevel??"info"},this.enableMainRegistryIntegration=t.enableMainRegistryIntegration??!1,this.toolDiscovery=new tLt,this.toolDiscovery.on("toolRegistered",n=>{this.emit("toolDiscovered",{...n,serverName:this.getServerName(n.serverId)})}),this.toolDiscovery.on("toolUnregistered",n=>{this.emit("toolRemoved",{...n,serverName:this.getServerName(n.serverId)})}),vLt(this)}setOutputNormalizer(e){this.toolDiscovery.setOutputNormalizer(e),de.debug("[ExternalServerManager] MCP output normalizer attached to ToolDiscoveryService")}setHITLManager(e){this.hitlManager=e,e&&e.isEnabled()?de.info("[ExternalServerManager] HITL safety mechanisms enabled for external tool execution"):de.debug("[ExternalServerManager] HITL safety mechanisms disabled or not configured")}getHITLManager(){return this.hitlManager}getServerName(e){return this.servers.get(e)?.config?.name||e}async loadMCPConfiguration(e,t={}){return t.parallel?this.loadMCPConfigurationParallel(e):this.loadMCPConfigurationSequential(e)}async loadMCPConfigurationParallel(e){const t=await Promise.resolve().then(()=>(Wr(),El)),r=await Promise.resolve().then(()=>(wr(),Yc)),n=e||r.join(process.cwd(),".mcp-config.json");if(!t.existsSync(n))return de.debug(`[ExternalServerManager] No MCP config found at ${n}`),{serversLoaded:0,errors:[]};de.debug(`[ExternalServerManager] Loading MCP configuration in PARALLEL mode from ${n}`);try{const o=t.readFileSync(n,"utf8"),s=JSON.parse(o);if(!s.mcpServers||typeof s.mcpServers!="object")return de.debug("[ExternalServerManager] No mcpServers found in configuration"),{serversLoaded:0,errors:[]};const i=Object.entries(s.mcpServers).map(async([u,d])=>{try{if(!gLt(d))throw new Error(`Invalid server config for ${u}: missing required properties or wrong types`);const m={id:u,name:u,description:typeof d.description=="string"?d.description:`External MCP server: ${u}`,transport:typeof d.transport=="string"?d.transport:"stdio",status:"initializing",tools:[],command:typeof d.command=="string"?d.command:void 0,args:Array.isArray(d.args)?d.args:[],env:ar(d.env)?Q_(d.env):{},timeout:typeof d.timeout=="number"?d.timeout:void 0,retries:typeof d.retries=="number"?d.retries:void 0,healthCheckInterval:typeof d.healthCheckInterval=="number"?d.healthCheckInterval:void 0,autoRestart:typeof d.autoRestart=="boolean"?d.autoRestart:void 0,cwd:typeof d.cwd=="string"?d.cwd:void 0,url:typeof d.url=="string"?d.url:void 0,headers:ar(d.headers)?Q_(d.headers):void 0,httpOptions:ar(d.httpOptions)?d.httpOptions:void 0,retryConfig:ar(d.retryConfig)?d.retryConfig:void 0,rateLimiting:ar(d.rateLimiting)?d.rateLimiting:void 0,blockedTools:Array.isArray(d.blockedTools)?d.blockedTools:void 0,metadata:sx(d.metadata)},h=await this.addServer(u,m);return{serverId:u,result:h}}catch(m){const h=`Failed to load MCP server ${u}: ${m instanceof Error?m.message:String(m)}`;return{serverId:u,error:h}}}),a=await Promise.allSettled(i);let l=0;const c=[];for(const u of a)if(u.status==="fulfilled"){const{serverId:d,result:m,error:h}=u.value;if(m&&m.success)l++,de.debug(`[ExternalServerManager] Successfully loaded MCP server in parallel: ${d}`);else if(h)c.push(h),de.error(`[ExternalServerManager] Failed to load server ${d}: ${h}`);else if(m&&!m.success){const g=`Failed to load server ${d}: ${m.error}`;c.push(g),de.error(`[ExternalServerManager] ${g}`)}}else{const d=`Unexpected error during parallel loading: ${u.reason}`;c.push(d),de.error(`[ExternalServerManager] ${d}`)}return de.info(`[ExternalServerManager] PARALLEL MCP configuration loading complete: ${l} servers loaded, ${c.length} errors`),{serversLoaded:l,errors:c}}catch(o){const s=`Failed to load MCP configuration in parallel mode: ${o instanceof Error?o.message:String(o)}`;return de.error(`[ExternalServerManager] ${s}`),{serversLoaded:0,errors:[s]}}}async loadMCPConfigurationSequential(e){const t=await Promise.resolve().then(()=>(Wr(),El)),r=await Promise.resolve().then(()=>(wr(),Yc)),n=e||r.join(process.cwd(),".mcp-config.json");if(!t.existsSync(n))return de.debug(`[ExternalServerManager] No MCP config found at ${n}`),{serversLoaded:0,errors:[]};de.debug(`[ExternalServerManager] Loading MCP configuration from ${n}`);try{const o=t.readFileSync(n,"utf8"),s=JSON.parse(o);if(!s.mcpServers||typeof s.mcpServers!="object")return de.debug("[ExternalServerManager] No mcpServers found in configuration"),{serversLoaded:0,errors:[]};let i=0;const a=[];for(const[l,c]of Object.entries(s.mcpServers))try{if(!gLt(c))throw new Error(`Invalid server config for ${l}: missing required properties or wrong types`);const u={id:l,name:l,description:typeof c.description=="string"?c.description:`External MCP server: ${l}`,transport:typeof c.transport=="string"?c.transport:"stdio",status:"initializing",tools:[],command:typeof c.command=="string"?c.command:void 0,args:Array.isArray(c.args)?c.args:[],env:ar(c.env)?Q_(c.env):{},timeout:typeof c.timeout=="number"?c.timeout:void 0,retries:typeof c.retries=="number"?c.retries:void 0,healthCheckInterval:typeof c.healthCheckInterval=="number"?c.healthCheckInterval:void 0,autoRestart:typeof c.autoRestart=="boolean"?c.autoRestart:void 0,cwd:typeof c.cwd=="string"?c.cwd:void 0,url:typeof c.url=="string"?c.url:void 0,headers:ar(c.headers)?Q_(c.headers):void 0,httpOptions:ar(c.httpOptions)?c.httpOptions:void 0,retryConfig:ar(c.retryConfig)?c.retryConfig:void 0,rateLimiting:ar(c.rateLimiting)?c.rateLimiting:void 0,blockedTools:Array.isArray(c.blockedTools)?c.blockedTools:void 0,metadata:sx(c.metadata)},d=await this.addServer(l,u);if(d.success)i++,de.debug(`[ExternalServerManager] Successfully loaded MCP server: ${l}`);else{const m=`Failed to load server ${l}: ${d.error}`;a.push(m),de.error(`[ExternalServerManager] ${m}`)}}catch(u){const d=`Failed to load MCP server ${l}: ${u instanceof Error?u.message:String(u)}`;a.push(d),de.error(`[ExternalServerManager] ${d}`)}return de.info(`[ExternalServerManager] MCP configuration loading complete: ${i} servers loaded, ${a.length} errors`),{serversLoaded:i,errors:a}}catch(o){const s=`Failed to load MCP configuration: ${o instanceof Error?o.message:String(o)}`;return de.error(`[ExternalServerManager] ${s}`),{serversLoaded:0,errors:[s]}}}validateConfig(e){const t=[],r=[],n=[];return(!e.id||typeof e.id!="string")&&t.push("Server ID is required and must be a string"),["stdio","sse","websocket","http"].includes(e.transport)||t.push("Transport must be one of: stdio, sse, websocket, http"),e.transport==="stdio"?((!e.command||typeof e.command!="string")&&t.push("Command is required and must be a string for stdio transport"),Array.isArray(e.args)||t.push("Args must be an array")):(e.transport==="sse"||e.transport==="websocket"||e.transport==="http")&&(!e.url||typeof e.url!="string")&&t.push(`URL is required for ${e.transport} transport`),e.timeout&&e.timeout<5e3&&r.push("Timeout less than 5 seconds may cause connection issues"),e.retries&&e.retries>5&&r.push("High retry count may slow down error recovery"),e.healthCheckInterval||n.push("Consider setting a health check interval for better reliability"),e.autoRestart===void 0&&n.push("Consider enabling auto-restart for production use"),{isValid:t.length===0,errors:t,warnings:r,suggestions:n}}convertConfigToMCPServerInfo(e,t){return{id:e,name:String(t.metadata?.title||e),description:`External MCP server (${t.transport})`,status:"initializing",transport:t.transport,command:t.command,args:t.args,env:t.env,tools:[],blockedTools:t.blockedTools,timeout:t.timeout,retries:t.retries,healthCheckInterval:t.healthCheckInterval,autoRestart:t.autoRestart,cwd:t.cwd,url:t.url,metadata:{category:"external",...sx(t.metadata)||{}}}}async addServer(e,t){const r=Date.now();try{const n="transport"in t&&"command"in t&&!("tools"in t)?this.convertConfigToMCPServerInfo(e,t):t;if(this.servers.size>=this.config.maxServers)return{success:!1,error:`Maximum number of servers (${this.config.maxServers}) reached`,serverId:e,duration:Date.now()-r};const o={id:e,name:n.name,description:n.description,transport:n.transport,status:n.status,tools:n.tools,command:n.command||"",args:n.args||[],env:n.env||{},timeout:n.timeout,retries:n.retries,healthCheckInterval:n.healthCheckInterval,autoRestart:n.autoRestart,cwd:n.cwd,url:n.url,blockedTools:n.blockedTools,metadata:sx(n.metadata),headers:n.headers,httpOptions:n.httpOptions,retryConfig:n.retryConfig,rateLimiting:n.rateLimiting},s=this.validateConfig(o);if(!s.isValid)return{success:!1,error:`Configuration validation failed: ${s.errors.join(", ")}`,serverId:e,duration:Date.now()-r};if(this.servers.has(e))return{success:!1,error:`Server with ID '${e}' already exists`,serverId:e,duration:Date.now()-r};de.info(`[ExternalServerManager] Adding server: ${e}`,{command:n.command,transport:n.transport});const i={...n,process:null,client:null,transportInstance:null,status:"initializing",reconnectAttempts:0,maxReconnectAttempts:this.config.maxRestartAttempts,toolsMap:new Map,metrics:{totalConnections:0,totalDisconnections:0,totalErrors:0,totalToolCalls:0,averageResponseTime:0,lastResponseTime:0},config:o};this.servers.set(e,i),await this.startServer(e);const a=this.servers.get(e);if(!a)throw new Error(`Server ${e} not found after registration`);return{success:!0,data:{config:a.config,process:a.process,pid:a.pid,client:a.client,transport:a.transportInstance,status:a.status,lastError:a.lastError,startTime:a.startTime,lastHealthCheck:a.lastHealthCheck,reconnectAttempts:a.reconnectAttempts,maxReconnectAttempts:a.maxReconnectAttempts,tools:a.toolsMap,toolsArray:a.toolsArray,capabilities:a.capabilities,healthTimer:a.healthTimer,restartTimer:a.restartTimer,metrics:a.metrics},serverId:e,duration:Date.now()-r,metadata:{timestamp:Date.now(),operation:"addServer",toolsDiscovered:a.tools.length}}}catch(n){return de.debug(`[ExternalServerManager] Failed to add server ${e}:`,n),this.servers.delete(e),{success:!1,error:n instanceof Error?n.message:String(n),serverId:e,duration:Date.now()-r}}}async removeServer(e){const t=Date.now();try{if(!this.servers.get(e))return{success:!1,error:`Server '${e}' not found`,serverId:e,duration:Date.now()-t};de.info(`[ExternalServerManager] Removing server: ${e}`);const n=this.getServerName(e);return await this.stopServer(e),this.servers.delete(e),this.emit("disconnected",{serverId:e,serverName:n,reason:"Manually removed",timestamp:new Date}),{success:!0,serverId:e,duration:Date.now()-t,metadata:{timestamp:Date.now(),operation:"removeServer"}}}catch(r){return de.error(`[ExternalServerManager] Failed to remove server ${e}:`,r),{success:!1,error:r instanceof Error?r.message:String(r),serverId:e,duration:Date.now()-t}}}async startServer(e){const t=this.servers.get(e);if(!t)throw new Error(`Server '${e}' not found`);const r=t.config,n=He.mcp.startSpan("neurolink.mcp.server.start",{attributes:{"mcp.server_id":e,"mcp.transport":r.transport,"mcp.command_name":r.command&&r.command.split(/[\\/]/).pop()||"","mcp.command_present":!!r.command}});try{this.updateServerStatus(e,"connecting"),de.debug(`[ExternalServerManager] Starting server: ${e}`,{command:r.command,args:Gqr(r.args),transport:r.transport});const o=await Z_.createClient(r,r.timeout||this.config.defaultTimeout);if(!o.success||!o.client||!o.transport)throw new Error(`Failed to create MCP client: ${o.error}`);t.client=o.client,t.transportInstance=o.transport,t.process=o.process||null,t.pid=o.transport instanceof Pte?o.transport.pid??void 0:void 0,t.capabilities=sx(o.capabilities),t.startTime=new Date,t.lastHealthCheck=new Date,t.metrics.totalConnections++,this.unresponsiveChecks.delete(e),this.attachClientLifecycle(e,o.client,o.transport),this.updateServerStatus(e,"connected"),await this.discoverServerTools(e),this.enableMainRegistryIntegration&&await this.registerServerToolsWithMainRegistry(e),this.startHealthMonitoring(e),this.emit("connected",{serverId:e,serverName:this.getServerName(e),toolCount:t.toolsMap.size,timestamp:new Date}),n.setAttribute("mcp.tool_count",t.toolsMap.size),n.setStatus({code:ze.OK}),de.info(`[ExternalServerManager] Server started successfully: ${e}`)}catch(o){throw de.debug(`[ExternalServerManager] Failed to start server ${e}:`,o),this.updateServerStatus(e,"failed"),t.lastError=o instanceof Error?o.message:String(o),n.recordException(o instanceof Error?o:new Error(String(o))),n.setStatus({code:ze.ERROR,message:o instanceof Error?o.message:String(o)}),o}finally{n.end()}}async stopServer(e){const t=this.servers.get(e);if(!t)return;const r=He.mcp.startSpan("neurolink.mcp.server.stop",{attributes:{"mcp.server_id":e}});try{if(this.updateServerStatus(e,"stopping"),t.healthTimer&&(clearInterval(t.healthTimer),t.healthTimer=void 0),t.restartTimer&&(clearTimeout(t.restartTimer),t.restartTimer=void 0),this.enableMainRegistryIntegration&&this.unregisterServerToolsFromMainRegistry(e),this.toolDiscovery.clearServerTools(e),t.client&&t.transportInstance){t.client.onclose=void 0,t.client.onerror=void 0;try{await Z_.closeClient(t.client,t.transportInstance)}catch(n){de.debug(`[ExternalServerManager] Error closing client for ${e}:`,n)}t.client=null,t.transportInstance=null,t.process=null,t.pid=void 0}this.updateServerStatus(e,"stopped"),r.setStatus({code:ze.OK}),de.info(`[ExternalServerManager] Server stopped: ${e}`)}catch(n){de.error(`[ExternalServerManager] Error stopping server ${e}:`,n),this.updateServerStatus(e,"failed"),r.recordException(n instanceof Error?n:new Error(String(n))),r.setStatus({code:ze.ERROR,message:n instanceof Error?n.message:String(n)})}finally{r.end()}}updateServerStatus(e,t){const r=this.servers.get(e);if(!r)return;const n=r.status,o=t==="connecting"||t==="restarting"?"initializing":t==="stopping"||t==="stopped"?"stopping":t==="connected"?"connected":t==="disconnected"?"disconnected":"failed";r.status=o,this.emit("statusChanged",{serverId:e,serverName:this.getServerName(e),oldStatus:n,newStatus:t,timestamp:new Date}),de.debug(`[ExternalServerManager] Status changed for ${e}: ${n} -> ${t}`)}attachClientLifecycle(e,t,r){t.onclose=()=>{const n=this.servers.get(e),o=n?.pid?` (pid ${n.pid})`:"",s=Z_.getStderrTail(r),i=s.length>0?`Server process closed${o}; last stderr: ${s.slice(-5).join(" | ")}`:`Server process closed${o}`;this.handleConnectionLost(e,t,i,s)},t.onerror=n=>{de.warn(`[ExternalServerManager] Transport error for ${e}: ${n.message}`)}}handleConnectionLost(e,t,r,n=[]){const o=this.servers.get(e);!o||o.client!==t||o.status!=="connected"||(de.warn(`[ExternalServerManager] Connection lost for ${e}: ${r}`,n.length>0?{stderrTail:n}:void 0),o.lastError=r,this.handleServerDisconnection(e,r))}trackToolCall(e,t){const r=(this.inFlightToolCalls.get(e)??0)+t;r<=0?this.inFlightToolCalls.delete(e):this.inFlightToolCalls.set(e,r)}handleServerError(e,t){const r=this.servers.get(e);r&&(r.lastError=t.message,r.metrics.totalErrors++,de.error(`[ExternalServerManager] Server error for ${e}:`,t),this.emit("failed",{serverId:e,serverName:this.getServerName(e),error:t.message,timestamp:new Date}),this.config.enableAutoRestart&&!this.isShuttingDown?this.scheduleRestart(e):this.updateServerStatus(e,"failed"))}handleServerDisconnection(e,t){const r=this.servers.get(e);r&&(r.metrics.totalDisconnections++,de.warn(`[ExternalServerManager] Server disconnected ${e}: ${t}`),this.emit("disconnected",{serverId:e,serverName:this.getServerName(e),reason:t,timestamp:new Date}),(r.config.autoRestart??this.config.enableAutoRestart)&&!this.isShuttingDown?this.scheduleRestart(e):this.updateServerStatus(e,"disconnected"))}scheduleRestart(e){const t=this.servers.get(e);if(!t)return;if(t.reconnectAttempts>=t.maxReconnectAttempts){de.error(`[ExternalServerManager] Max restart attempts reached for ${e}`),this.updateServerStatus(e,"failed");return}t.reconnectAttempts++,this.updateServerStatus(e,"restarting");const r=Math.min(1e3*Math.pow(this.config.restartBackoffMultiplier,t.reconnectAttempts-1),3e4);de.info(`[ExternalServerManager] Scheduling restart for ${e} in ${r}ms (attempt ${t.reconnectAttempts})`),!t.restartTimer&&(t.restartTimer=setTimeout(async()=>{const n=He.mcp.startSpan("neurolink.mcp.server.restart",{attributes:{"mcp.server_id":e,"mcp.restart_attempt":t.reconnectAttempts,"mcp.restart_delay_ms":r}});try{await this.stopServer(e),await this.startServer(e),t.reconnectAttempts=0,n.setStatus({code:ze.OK})}catch(o){de.error(`[ExternalServerManager] Restart failed for ${e}:`,o),n.recordException(o instanceof Error?o:new Error(String(o))),n.setStatus({code:ze.ERROR,message:o instanceof Error?o.message:String(o)}),this.scheduleRestart(e)}finally{n.end()}},r))}startHealthMonitoring(e){const t=this.servers.get(e);if(!t||!this.config.enablePerformanceMonitoring)return;const r=t.config.healthCheckInterval??this.config.defaultHealthCheckInterval;t.healthTimer=setInterval(async()=>{await this.performHealthCheck(e)},r)}async performHealthCheck(e){const t=this.servers.get(e);if(!t||t.status!=="connected"||!t.client||this.healthChecksInFlight.has(e))return;this.healthChecksInFlight.add(e);const r=t.client,n=t.config.healthCheckInterval??this.config.defaultHealthCheckInterval,o=Math.max(1,Math.min(t.config.timeout||this.config.defaultTimeout,n)),s=Date.now(),i=[];let a=!0,l=!1,c=!1;try{try{await r.ping({timeout:o}),this.unresponsiveChecks.delete(e)}catch(m){if(a=!1,fLt(m))l=!0,i.push("connection closed");else{const h=this.inFlightToolCalls.get(e)??0;if(h>0)i.push(`ping timed out after ${o}ms while ${h} tool call(s) in flight`);else{const g=(this.unresponsiveChecks.get(e)??0)+1;this.unresponsiveChecks.set(e,g),i.push(`ping timed out after ${o}ms while idle (${g}/${hre})`),c=g>=hre}}}const u=Date.now()-s;t.lastHealthCheck=new Date;const d={serverId:e,isHealthy:a,status:t.status,checkedAt:new Date,responseTime:u,toolCount:t.toolsMap.size,issues:i,performance:{uptime:t.startTime?Date.now()-t.startTime.getTime():0,averageResponseTime:t.metrics.averageResponseTime}};this.emit("healthCheck",{serverId:e,serverName:this.getServerName(e),health:d,timestamp:new Date}),l||c?this.handleConnectionLost(e,r,`Health check failed: ${i.join(", ")}`):a||de.warn(`[ExternalServerManager] Health check failed for ${e}:`,i)}catch(u){de.error(`[ExternalServerManager] Health check error for ${e}:`,u)}finally{this.healthChecksInFlight.delete(e)}}getServer(e){const t=this.servers.get(e);if(t)return{config:t.config,process:t.process,pid:t.pid,client:t.client,transport:t.transportInstance,status:t.status,lastError:t.lastError,startTime:t.startTime,lastHealthCheck:t.lastHealthCheck,reconnectAttempts:t.reconnectAttempts,maxReconnectAttempts:t.maxReconnectAttempts,tools:t.toolsMap,toolsArray:t.toolsArray,capabilities:t.capabilities,healthTimer:t.healthTimer,restartTimer:t.restartTimer,metrics:t.metrics}}getAllServers(){const e=new Map;for(const[t,r]of this.servers.entries())e.set(t,{config:r.config,process:r.process,pid:r.pid,client:r.client,transport:r.transportInstance,status:r.status,lastError:r.lastError,startTime:r.startTime,lastHealthCheck:r.lastHealthCheck,reconnectAttempts:r.reconnectAttempts,maxReconnectAttempts:r.maxReconnectAttempts,tools:r.toolsMap,toolsArray:r.toolsArray,capabilities:r.capabilities,healthTimer:r.healthTimer,restartTimer:r.restartTimer,metrics:r.metrics});return e}listServers(){return Array.from(this.servers.values())}getServerStatuses(){const e=[];for(const[t,r]of Array.from(this.servers.entries())){const n=r.startTime?Date.now()-r.startTime.getTime():0;e.push({serverId:t,isHealthy:r.status==="connected",status:r.status,checkedAt:r.lastHealthCheck||new Date,toolCount:r.toolsMap.size,issues:r.lastError?[r.lastError]:[],performance:{uptime:n,averageResponseTime:r.metrics.averageResponseTime}})}return e}async shutdown(){if(this.isShuttingDown)return;this.isShuttingDown=!0,WL.delete(this),de.info("[ExternalServerManager] Shutting down all servers...");const e=Array.from(this.servers.keys()).map(t=>this.stopServer(t).catch(r=>{de.error(`[ExternalServerManager] Error shutting down ${t}:`,r)}));await Promise.all(e),this.servers.clear(),this.toolDiscovery.destroy(),this.removeAllListeners(),de.info("[ExternalServerManager] All servers shut down and resources cleaned up")}async destroy(){return this.shutdown()}getStatistics(){let e=0,t=0,r=0,n=0,o=0;for(const s of Array.from(this.servers.values()))s.status==="connected"?e++:s.status==="failed"&&t++,r+=s.toolsMap.size,n+=s.metrics.totalConnections,o+=s.metrics.totalErrors;return{totalServers:this.servers.size,connectedServers:e,failedServers:t,totalTools:r,totalConnections:n,totalErrors:o}}async discoverServerTools(e){const t=this.servers.get(e);if(!t||!t.client)throw new Error(`Server '${e}' not found or not connected`);try{de.debug(`[ExternalServerManager] Discovering tools for server: ${e}`);const r=await this.toolDiscovery.discoverTools(e,t.client,t.config.timeout||this.config.defaultTimeout);if(r.success){t.toolsMap.clear(),t.toolsArray=void 0,t.tools=[];const n=t.blockedTools||[];let o=0;for(const s of r.tools){if(n.includes(s.name)){de.info(`[ExternalServerManager] Blocking tool '${s.name}' from server '${e}' (configured in blockedTools)`),o++;continue}t.toolsMap.set(s.name,s),t.tools.push({name:s.name,description:s.description,inputSchema:s.inputSchema})}de.info(`[ExternalServerManager] Discovered ${r.toolCount} tools for ${e} (${o} blocked, ${t.toolsMap.size} available)`)}else de.warn(`[ExternalServerManager] Tool discovery failed for ${e}: ${r.error}`)}catch(r){de.error(`[ExternalServerManager] Tool discovery error for ${e}:`,r)}}async registerServerToolsWithMainRegistry(e){const t=this.servers.get(e);if(!t)throw new Error(`Server '${e}' not found`);try{de.debug(`[ExternalServerManager] Registering ${t.toolsMap.size} tools with main registry for server: ${e}`);const r=[];for(const[i,a]of t.toolsMap.entries()){const l=`${e}.${i}`,c={name:i,description:a.description||i,inputSchema:a.inputSchema||{},serverId:e,category:Ia({isExternal:!0,serverId:e})};try{r.push(dre.registerTool(l,c,{execute:async(u,d)=>await this.executeTool(e,i,u,{timeout:t.config.timeout||this.config.defaultTimeout})})),de.debug(`[ExternalServerManager] Registered tool with main registry: ${l}`)}catch(u){de.warn(`[ExternalServerManager] Failed to register tool ${l} with main registry:`,u)}}const n=await Promise.allSettled(r),o=n.filter(i=>i.status==="fulfilled").length,s=n.length-o;de.info(`[ExternalServerManager] Registered ${o}/${n.length} tools with main registry for ${e}${s?` (${s} failed)`:""}`)}catch(r){de.error(`[ExternalServerManager] Failed to register tools with main registry for ${e}:`,r)}}unregisterServerToolsFromMainRegistry(e){const t=this.servers.get(e);if(!(!t||!this.enableMainRegistryIntegration))try{de.debug(`[ExternalServerManager] Unregistering tools from main registry for server: ${e}`);for(const[r]of t.toolsMap.entries()){const n=`${e}.${r}`;try{dre.removeTool(n),de.debug(`[ExternalServerManager] Unregistered tool from main registry: ${n}`)}catch(o){de.debug(`[ExternalServerManager] Failed to unregister tool ${n}:`,o)}}de.debug(`[ExternalServerManager] Completed unregistering tools from main registry for ${e}`)}catch(r){de.error(`[ExternalServerManager] Error unregistering tools from main registry for ${e}:`,r)}}async executeTool(e,t,r,n){const o=this.servers.get(e);if(!o)throw new Error(`Server '${e}' not found`);const s=o.client;if(!s)throw new Error(`Server '${e}' is not connected`);if(o.status!=="connected")throw new Error(`Server '${e}' is not in connected state: ${o.status}`);if((o.blockedTools||[]).includes(t))throw new Error(`Tool '${t}' is blocked on server '${e}' by configuration`);const a=Date.now();try{let l=r;if(this.hitlManager&&this.hitlManager.isEnabled())if(this.hitlManager.requiresConfirmation(t,r)){de.info(`[ExternalServerManager] External tool '${t}' on server '${e}' requires HITL confirmation`);try{const h=await this.hitlManager.requestConfirmation(t,r,{serverId:e,sessionId:`external-${e}-${Date.now()}`,userId:void 0});if(!h.approved)throw new ZT(`External tool execution rejected by user: ${h.reason||"No reason provided"}`,t,h.reason);h.modifiedArguments!==void 0&&(l=h.modifiedArguments,de.info(`[ExternalServerManager] External tool '${t}' arguments modified by user`)),de.info(`[ExternalServerManager] External tool '${t}' approved for execution (response time: ${h.responseTime}ms)`)}catch(h){throw h instanceof XT?(de.warn(`[ExternalServerManager] External tool '${t}' execution timed out waiting for user confirmation`),h):h instanceof ZT?(de.info(`[ExternalServerManager] External tool '${t}' execution rejected by user`),h):(de.error(`[ExternalServerManager] HITL confirmation failed for external tool '${t}':`,h),new Error(`HITL confirmation failed: ${h instanceof Error?h.message:String(h)}`,{cause:h}))}}else de.debug(`[ExternalServerManager] External tool '${t}' does not require HITL confirmation`);this.trackToolCall(e,1);let c;try{c=await this.toolDiscovery.executeTool(t,e,s,l,{timeout:n?.timeout||o.config.timeout||this.config.defaultTimeout})}finally{this.trackToolCall(e,-1)}const u=Date.now()-a;o.metrics.totalToolCalls++,o.metrics.lastResponseTime=u;const d=o.metrics.averageResponseTime*(o.metrics.totalToolCalls-1)+u;if(o.metrics.averageResponseTime=d/o.metrics.totalToolCalls,c.success){de.debug(`[ExternalServerManager] Tool executed successfully: ${t} on ${e}`,{duration:u});try{jf.getInstance()?.recordMCPToolCall(t,u,!0)}catch{}return c.data}else throw new Error(c.error||"Tool execution failed")}catch(l){o.metrics.totalErrors++;try{const c=Date.now()-a;jf.getInstance()?.recordMCPToolCall(t,c,!1)}catch{}throw de.error(`[ExternalServerManager] Tool execution failed: ${t} on ${e}`,l),fLt(l)&&this.handleConnectionLost(e,s,`Connection lost during tool call '${t}': ${l instanceof Error?l.message:String(l)}`),l}}getAllTools(){return this.toolDiscovery.getAllTools()}getServerTools(e){return this.toolDiscovery.getServerTools(e)}getToolDiscovery(){return this.toolDiscovery}}}});function Hqr(e,t,r,n){return{content:[{type:"text",text:`[MCP Tool Output \u2014 ${r.toolName} | ${r.serverId}]
|
|
1486
|
+
`)}`,{cause:o}):o}}static getStderrTail(e){return sre.get(e)?.snapshot()??[]}static async createTransport(e){switch(e.transport){case"stdio":return this.createStdioTransport(e);case"sse":return this.createSSETransport(e);case"websocket":return this.createWebSocketTransport(e);case"http":return this.createHTTPTransport(e);default:throw new Error(`Unsupported transport type: ${e.transport}`)}}static async createStdioTransport(e){if(de.debug(`[MCPClientFactory] Creating stdio transport for ${e.id}`,{command:e.command,args:e.args}),!e.command)throw new Error("Command is required for stdio transport");const t=new Pte({command:e.command,args:e.args||[],env:Object.fromEntries(Object.entries({...process.env,...e.env}).filter(([,n])=>n!==void 0).map(([n,o])=>[n,String(o)])),cwd:e.cwd,stderr:"pipe"}),r=new ZNt;return sre.set(t,r),t.stderr?.on("data",n=>{if(r.append(n),de.shouldLog("debug")){const o=n.toString().trim();o.length>0&&de.debug(`[MCPClientFactory] ${e.id} stderr:`,o)}}),{transport:t}}static async createSSETransport(e){if(!e.url)throw new Error("URL is required for SSE transport");de.debug(`[MCPClientFactory] Creating SSE transport for ${e.id}`,{url:e.url});try{const t=new URL(e.url);return{transport:new NNt(t)}}catch(t){throw new Error(`Invalid SSE URL: ${t instanceof Error?t.message:String(t)}`,{cause:t})}}static async createWebSocketTransport(e){if(!e.url)throw new Error("URL is required for WebSocket transport");de.debug(`[MCPClientFactory] Creating WebSocket transport for ${e.id}`,{url:e.url});try{const t=new URL(e.url);return{transport:new $Nt(t)}}catch(t){throw new Error(`Invalid WebSocket URL: ${t instanceof Error?t.message:String(t)}`,{cause:t})}}static async createHTTPTransport(e){if(!e.url)throw new Error("URL is required for HTTP transport");const t={connectionTimeout:e.httpOptions?.connectionTimeout??3e4,requestTimeout:e.httpOptions?.requestTimeout??6e4,idleTimeout:e.httpOptions?.idleTimeout??12e4,keepAliveTimeout:e.httpOptions?.keepAliveTimeout??3e4};de.debug(`[MCPClientFactory] Creating HTTP transport for ${e.id}`,{url:e.url,hasHeaders:!!e.headers,hasAuth:!!e.auth,authType:e.auth?.type,httpOptions:t});try{const r=new URL(e.url),n=await this.setupAuthProvider(e),o={...e.headers??{}};if(e.auth){const l=await this.getAuthorizationHeader(e,n);l&&(o.Authorization=l)}const s=this.createEnhancedFetch(e,t.requestTimeout,n),i={headers:Object.keys(o).length>0?o:void 0};return{transport:new UNt(r,{requestInit:i,fetch:s})}}catch(r){throw new Error(`Invalid HTTP URL: ${r instanceof Error?r.message:String(r)}`,{cause:r})}}static createFetchWithTimeout(e){return async(t,r)=>{const n=new AbortController,o=setTimeout(()=>n.abort(),e);try{return await fetch(t,{...r,signal:n.signal})}finally{clearTimeout(o)}}}static createEnhancedFetch(e,t,r){const n=this.createFetchWithTimeout(t);return async(o,s)=>{if(r&&e.auth?.type==="oauth2")try{const i=await r.getAuthorizationHeader(e.id);if(i){const a=s?.headers??{},l=new Headers(a);l.set("Authorization",i),s={...s,headers:l}}}catch(i){de.warn(`[MCPClientFactory] OAuth token refresh failed for ${e.id}:`,i instanceof Error?i.message:String(i))}return n(o,s)}}static async setupAuthProvider(e){if(e.auth?.type==="oauth2"&&e.auth.oauth){const t=new FL,r={clientId:e.auth.oauth.clientId,clientSecret:e.auth.oauth.clientSecret,authorizationUrl:e.auth.oauth.authorizationUrl,tokenUrl:e.auth.oauth.tokenUrl,redirectUrl:e.auth.oauth.redirectUrl,scope:e.auth.oauth.scope,usePKCE:e.auth.oauth.usePKCE??!0},n=new UL(r,t);return de.debug(`[MCPClientFactory] OAuth provider created for ${e.id}`,{clientId:r.clientId,usePKCE:r.usePKCE}),n}}static async getAuthorizationHeader(e,t){if(e.auth)switch(e.auth.type){case"oauth2":return t?await t.getAuthorizationHeader(e.id)??void 0:void 0;case"bearer":return e.auth.token?`Bearer ${e.auth.token}`:void 0;case"api-key":return;default:return}}static async performHandshake(e,t){try{const r=await Promise.race([this.getServerInfo(e),this.createTimeoutPromise(t,"Handshake timeout")]);return this.extractCapabilities(r)}catch(r){return de.warn("[MCPClientFactory] Handshake failed, but connection may still be valid:",r),this.DEFAULT_CAPABILITIES}}static async getServerInfo(e){try{return{tools:(await e.listTools()).tools||[],capabilities:this.DEFAULT_CAPABILITIES}}catch{return de.debug("[MCPClientFactory] Tool listing failed, server may not support tools yet"),{tools:[],capabilities:this.DEFAULT_CAPABILITIES}}}static extractCapabilities(e){return{...this.DEFAULT_CAPABILITIES,...e.tools?{tools:{}}:{}}}static createTimeoutPromise(e,t,r){return new Promise((n,o)=>{const s=setTimeout(()=>{o(new Error(t))},e);r&&r.addEventListener("abort",()=>{clearTimeout(s),o(new Error(`Operation aborted: ${t}`))})})}static async closeClient(e,t,r){const n=[];try{await e.close()}catch(o){n.push(`Client close error: ${o instanceof Error?o.message:String(o)}`)}try{await t.close()}catch(o){n.push(`Transport close error: ${o instanceof Error?o.message:String(o)}`)}if(r&&!r.killed)try{r.kill("SIGTERM"),await new Promise(o=>{const s=setTimeout(()=>{if(!r.killed){de.warn("[MCPClientFactory] Force killing process");try{r.kill("SIGKILL")}catch(i){de.debug("[MCPClientFactory] Error in force kill:",i)}}o()},5e3);r.on("exit",()=>{clearTimeout(s),o()})})}catch(o){n.push(`Process kill error: ${o instanceof Error?o.message:String(o)}`)}n.length>0&&de.warn("[MCPClientFactory] Errors during client cleanup:",n)}static async testConnection(e,t=5e3){let r,n,o;try{const s=await this.createClient(e,t);if(!s.success)return{success:!1,error:s.error};if(r=s.client,n=s.transport,o=s.process,r)try{await r.listTools()}catch{de.debug("[MCPClientFactory] Tool listing failed during test, but connection may be valid")}return{success:!0,capabilities:s.capabilities}}catch(s){return{success:!1,error:s instanceof Error?s.message:String(s)}}finally{if(r&&n)try{await this.closeClient(r,n,o)}catch(s){de.debug("[MCPClientFactory] Error cleaning up test connection:",s)}}}static validateClientConfig(e){const t=[];if(e.command||t.push("Command is required"),e.transport||t.push("Transport is required"),["stdio","sse","websocket","http"].includes(e.transport)||t.push("Transport must be stdio, sse, websocket, or http"),e.transport==="sse"||e.transport==="websocket"||e.transport==="http")if(!e.url)t.push(`URL is required for ${e.transport} transport`);else try{new URL(e.url)}catch{t.push(`Invalid URL for ${e.transport} transport`)}return e.transport==="stdio"&&(Array.isArray(e.args)||t.push("Args array is required for stdio transport")),{isValid:t.length===0,errors:t}}static getSupportedTransports(){return["stdio","sse","websocket","http"]}static getDefaultCapabilities(){return{...this.DEFAULT_CAPABILITIES}}}}});function XNt(e,t){if(t<=0)return"";try{const r=JSON.stringify(e);return typeof r!="string"?"":r.length<=t?r:r.slice(0,Math.max(0,t-1))+"\u2026"}catch{return""}}function BL(e,t=0){if(t>10)return"[...]";if(e==null||typeof e!="object")return e;if(Array.isArray(e))return e.map(n=>BL(n,t+1));const r={};for(const[n,o]of Object.entries(e))eLt.test(n)?r[n]="[REDACTED]":r[n]=BL(o,t+1);return r}var QNt,eLt,are,tLt,Uqr=S({"src/lib/mcp/toolDiscoveryService.ts"(){"use strict";vn(),q(),Xte(),Af(),gg(),at(),dD(),EC(),tr(),vr(),Kr(),QNt=He.mcp,eLt=/^(password|passwd|secret|token|api[_-]?key|apikey|access[_-]?key|authorization|auth|bearer|credential|cookie|session[_-]?id|private[_-]?key|client[_-]?secret|refresh[_-]?token|x-api-key)$/i,are=Math.max(5e3,Number(process.env.MCP_TOOL_TIMEOUT)||6e4),tLt=class extends sn{serverToolStorage=new Map;toolRegistry=new Map;serverTools=new Map;discoveryInProgress=new Set;outputNormalizer;constructor(){super()}setOutputNormalizer(e){this.outputNormalizer=e}async discoverTools(e,t,r=are){return gt({name:"neurolink.mcp.discoverTools",tracer:He.mcp,attributes:{"mcp.server_id":e}},async n=>{const o=Date.now();try{if(this.discoveryInProgress.has(e))return{success:!1,error:`Discovery already in progress for server: ${e}`,toolCount:0,tools:[],duration:Date.now()-o,serverId:e};this.discoveryInProgress.add(e),de.info(`[ToolDiscoveryService] Starting tool discovery for server: ${e}`);const i=await rx.getBreaker(`tool-discovery-${e}`,{failureThreshold:2,resetTimeout:6e4,operationTimeout:r}).execute(async()=>await this.performToolDiscovery(e,t,r)),a=await this.registerDiscoveredTools(e,i);n.setAttribute("mcp.tools_discovered",a.length);const l={success:!0,toolCount:a.length,tools:a,duration:Date.now()-o,serverId:e};return this.emit("discoveryCompleted",{serverId:e,toolCount:a.length,duration:l.duration,timestamp:new Date}),de.info(`[ToolDiscoveryService] Discovery completed for ${e}: ${a.length} tools`),l}catch(s){const i=s instanceof Error?s.message:String(s);return n.setStatus({code:ze.ERROR,message:i}),n.recordException(s instanceof Error?s:new Error(i)),de.error(`[ToolDiscoveryService] Discovery failed for ${e}:`,s),this.emit("discoveryFailed",{serverId:e,error:i,timestamp:new Date}),{success:!1,error:i,toolCount:0,tools:[],duration:Date.now()-o,serverId:e}}finally{this.discoveryInProgress.delete(e)}})}async performToolDiscovery(e,t,r){const n=t.listTools(),o=this.createTimeoutPromise(r,"Tool discovery timeout"),s=await Promise.race([n,o]);if(!s||!s.tools)throw new Error("No tools returned from server");return de.debug(`[ToolDiscoveryService] Discovered ${s.tools.length} tools from ${e}`),s.tools}async registerDiscoveredTools(e,t){const r=[];this.clearServerTools(e);for(const n of t)try{const o=await this.createToolInfo(e,n),s=this.validateTool(o);if(!s.isValid){de.warn(`[ToolDiscoveryService] Skipping invalid tool ${n.name} from ${e}:`,s.errors);continue}s.metadata&&(o.metadata={...o.metadata,...s.metadata});const i=this.createToolKey(e,n.name);this.toolRegistry.set(i,o),this.serverToolStorage.has(e)||this.serverToolStorage.set(e,[]);const a=this.serverToolStorage.get(e);if(!a)throw new Error(`Server tools storage not found for ${e}`);a.find(c=>c.name===n.name)||a.push({name:n.name,description:n.description||"",inputSchema:n.inputSchema}),this.serverTools.has(e)||this.serverTools.set(e,new Set);const l=this.serverTools.get(e);l&&l.add(n.name),r.push(o),this.emit("toolRegistered",{serverId:e,toolName:n.name,toolInfo:o,timestamp:new Date}),de.debug(`[ToolDiscoveryService] Registered tool: ${n.name} from ${e}`)}catch(o){de.error(`[ToolDiscoveryService] Failed to register tool ${n.name} from ${e}:`,o)}return r}async createToolInfo(e,t){return{name:t.name,description:t.description||"No description provided",serverId:e,inputSchema:t.inputSchema,isAvailable:!0,stats:{totalCalls:0,successfulCalls:0,failedCalls:0,averageExecutionTime:0,lastExecutionTime:0},metadata:{category:this.inferToolCategory(t),version:"1.0.0",deprecated:!1}}}inferToolCategory(e){const t=e.name.toLowerCase(),r=(e.description||"").toLowerCase();return t.includes("git")||r.includes("git")?"version-control":t.includes("file")||t.includes("read")||t.includes("write")?"file-system":t.includes("api")||t.includes("http")||t.includes("request")?"api":t.includes("data")||t.includes("query")||t.includes("search")?"data":t.includes("auth")||t.includes("login")||t.includes("token")?"authentication":t.includes("deploy")||t.includes("build")||t.includes("ci")?"deployment":"general"}validateTool(e){const t=[],r=[],n=wC(e.name);n&&t.push(n.message);const o=h4(e.description);if(o&&r.push(o.message),e.serverId||t.push("Server ID is required"),e.inputSchema)try{JSON.stringify(e.inputSchema)}catch{t.push("Input schema is not valid JSON")}const s={category:typeof e.metadata?.category=="string"?e.metadata.category:"general",complexity:this.inferComplexity(e),requiresAuth:this.inferAuthRequirement(e),isDeprecated:typeof e.metadata?.deprecated=="boolean"?e.metadata.deprecated:!1};return{isValid:t.length===0,errors:t,warnings:r,metadata:s}}inferComplexity(e){const t=e.inputSchema;if(!t||!t.properties)return"simple";const r=Object.keys(t.properties).length;return r<=2?"simple":r<=5?"moderate":"complex"}inferAuthRequirement(e){const t=e.name.toLowerCase(),r=e.description.toLowerCase();return t.includes("auth")||t.includes("login")||t.includes("token")||r.includes("authentication")||r.includes("credentials")||r.includes("permission")}async executeTool(e,t,r,n,o={}){const s=Date.now();try{const i=this.createToolKey(t,e),a=this.toolRegistry.get(i);if(!a)throw new Error(`Tool '${e}' not found for server '${t}'`);if(!a.isAvailable)throw new Error(`Tool '${e}' is not available`);let l=n;o.validateInput!==!1&&(l=this.validateToolParameters(a,n)),de.debug(`[ToolDiscoveryService] Executing tool: ${e} on ${t}`,{parameters:l});const c=o.timeout||are,d=await rx.getBreaker(`tool-execution-${t}-${e}`,{failureThreshold:3,resetTimeout:3e4,operationTimeout:c}).execute(async()=>QNt.startActiveSpan("neurolink.mcp.callTool",{kind:jr.CLIENT,attributes:{"mcp.server_id":t,"mcp.tool_name":e,"mcp.timeout_ms":c,"ai.tool.name":e,"gen_ai.tool.name":e,"gen_ai.request":XNt({name:e,arguments:BL(l)},2048)}},async h=>{try{const g=c,y=await Ze(r.callTool({name:e,arguments:l},void 0,{timeout:c}),g,new Error(`Tool execution timeout: ${e}`)),v=y;if(v&&v.isError===!0){const T=E4(v);h.setStatus({code:ze.ERROR,message:T||`Tool ${e} returned isError`})}else h.setStatus({code:ze.OK});let _=y,b=y;if(this.outputNormalizer)try{const T=await this.outputNormalizer.normalize(y,{toolName:e,serverId:t});h.setAttribute("mcp.output.strategy",T.isExternalized?"externalize":"inline"),T.isExternalized&&h.setAttribute("mcp.output.original_bytes",T.originalBytes),_=T.result,b=T.result}catch(T){de.warn(`[ToolDiscoveryService] McpOutputNormalizer failed for ${e}: ${T instanceof Error?T.message:String(T)} \u2014 returning raw result`)}return h.setAttribute("gen_ai.response",XNt(BL(_),2048)),b}catch(g){throw h.setStatus({code:ze.ERROR,message:g.message}),h.recordException(g),g}finally{h.end()}})),m=Date.now()-s;return this.updateToolStats(i,!0,m),o.validateOutput!==!1&&this.validateToolOutput(d),de.debug(`[ToolDiscoveryService] Tool execution completed: ${e}`,{duration:m,hasContent:!!d?.content}),{success:!0,data:d,duration:m,metadata:{toolName:e,serverId:t,timestamp:Date.now()}}}catch(i){const a=Date.now()-s,l=i instanceof Error?i.message:String(i),c=this.createToolKey(t,e);return this.updateToolStats(c,!1,a),i instanceof am?(de.warn(`[ToolDiscoveryService] Tool blocked by circuit breaker: ${e} on ${t}`,{breakerState:i.breakerState,retryAfter:i.retryAfter,retryAfterMs:i.retryAfterMs,failureCount:i.failureCount}),{success:!1,error:i.message,data:{isError:!0,content:[{type:"text",text:`TOOL TEMPORARILY UNAVAILABLE: "${e}" has been disabled after ${i.failureCount} failures. This is a circuit breaker protection \u2014 do NOT retry this tool. It will become available again after ${Math.ceil(i.retryAfterMs/1e3)} seconds (at ${i.retryAfter}). Instead, inform the user that the operation failed and suggest trying again later.`}]},duration:a,metadata:{toolName:e,serverId:t,timestamp:Date.now(),circuitBreaker:{state:i.breakerState,retryAfter:i.retryAfter,retryAfterMs:i.retryAfterMs,failureCount:i.failureCount}}}):(de.error(`[ToolDiscoveryService] Tool execution failed: ${e}`,i),{success:!1,error:l,duration:a,metadata:{toolName:e,serverId:t,timestamp:Date.now()}})}}validateToolParameters(e,t){if(!e.inputSchema)return t;const r=e.inputSchema,n=r.properties&&typeof r.properties=="object"?r.properties:{},o=Array.isArray(r.required)?r.required.filter(l=>typeof l=="string"):[],s=()=>Object.entries(n).map(([l,c])=>`${l}${o.includes(l)?"":"?"}: ${c.type??"any"}`).join(", "),i=o.filter(l=>!(l in t));if(i.length>0)throw new Error(`Missing required parameter${i.length>1?"s":""}: ${i.join(", ")}. Expected arguments: { ${s()} }; received keys: [${Object.keys(t).join(", ")}]`);let a;for(const[l,c]of Object.entries(n))if(l in t){const u=t[l],d=Q9(u,c);d!==u&&(de.debug(`[ToolDiscoveryService] Coerced parameter '${l}' for tool '${e.name}': ${typeof u} \u2192 ${typeof d}`),a=a??{...t},a[l]=d),this.validateParameterType(l,a?a[l]:u,c)}return a??t}validateParameterType(e,t,r){if(!r.type)return;const n=r.type,o=typeof t;switch(n){case"string":if(o!=="string")throw new Error(`Parameter '${e}' must be a string, got ${o}`);break;case"number":if(o!=="number")throw new Error(`Parameter '${e}' must be a number, got ${o}`);break;case"integer":if(o!=="number"||!Number.isInteger(t))throw new Error(`Parameter '${e}' must be an integer, got ${o==="number"?String(t):o}`);break;case"boolean":if(o!=="boolean")throw new Error(`Parameter '${e}' must be a boolean, got ${o}`);break;case"array":if(!Array.isArray(t))throw new Error(`Parameter '${e}' must be an array, got ${o}`);break;case"object":if(o!=="object"||t===null||Array.isArray(t))throw new Error(`Parameter '${e}' must be an object, got ${o}`);break}}validateToolOutput(e){if(dTr(e)){de.debug("[ToolDiscoveryService] Tool returned null/undefined, treating as empty response");return}de.debug("[ToolDiscoveryService] Tool response received",{type:typeof e,isArray:Array.isArray(e),isObject:EM(e),hasKeys:EM(e)?Object.keys(e).length:0,fullResponse:e})}updateToolStats(e,t,r){const n=this.toolRegistry.get(e);if(!n)return;n.stats.totalCalls++,n.lastCalled=new Date,n.stats.lastExecutionTime=r,t?n.stats.successfulCalls++:n.stats.failedCalls++;const o=n.stats.averageExecutionTime*(n.stats.totalCalls-1)+r;n.stats.averageExecutionTime=o/n.stats.totalCalls}getTool(e,t){const r=this.createToolKey(t,e);return this.toolRegistry.get(r)}getServerTools(e){const t=this.serverToolStorage.get(e);if(t)return t.map(o=>({name:o.name,description:o.description,serverId:e,inputSchema:o.inputSchema,isAvailable:!0,stats:{totalCalls:0,successfulCalls:0,failedCalls:0,averageExecutionTime:0,lastExecutionTime:0}}));const r=[],n=this.serverTools.get(e);if(n)for(const o of n){const s=this.createToolKey(e,o),i=this.toolRegistry.get(s);i&&r.push(i)}return r}getAllTools(){const e=[];for(const[r,n]of this.serverToolStorage.entries())for(const o of n)e.push({name:o.name,description:o.description,serverId:r,inputSchema:o.inputSchema,isAvailable:!0,stats:{totalCalls:0,successfulCalls:0,failedCalls:0,averageExecutionTime:0,lastExecutionTime:0}});const t=Array.from(this.toolRegistry.values()).filter(r=>!e.some(n=>n.name===r.name&&n.serverId===r.serverId));return[...e,...t]}clearServerTools(e){const t=this.serverToolStorage.get(e);if(t){for(const n of t)this.emit("toolUnregistered",{serverId:e,toolName:n.name,timestamp:new Date});this.serverToolStorage.delete(e)}const r=this.serverTools.get(e);if(r){for(const n of r){const o=this.createToolKey(e,n);this.toolRegistry.delete(o),(!t||!t.find(s=>s.name===n))&&this.emit("toolUnregistered",{serverId:e,toolName:n,timestamp:new Date})}this.serverTools.delete(e)}de.debug(`[ToolDiscoveryService] Cleared tools for server: ${e}`)}updateToolAvailability(e,t,r){const n=this.createToolKey(t,e),o=this.toolRegistry.get(n);o&&(o.isAvailable=r,de.debug(`[ToolDiscoveryService] Updated availability for ${e}: ${r}`))}createToolKey(e,t){return`${e}:${t}`}createTimeoutPromise(e,t){return new Promise((r,n)=>{setTimeout(()=>{n(new Error(t))},e)})}destroy(){de.debug("[ToolDiscoveryService] Starting cleanup..."),this.removeAllListeners(),this.serverToolStorage.clear(),this.toolRegistry.clear(),this.serverTools.clear(),this.discoveryInProgress.clear(),de.debug("[ToolDiscoveryService] Destroyed and cleaned up")}resetStatistics(){for(const e of this.toolRegistry.values())e.stats={totalCalls:0,successfulCalls:0,failedCalls:0,averageExecutionTime:0,lastExecutionTime:0},e.lastCalled=void 0;de.debug("[ToolDiscoveryService] Statistics reset for all tools")}getListenerCount(){const e=["discoveryCompleted","discoveryFailed","toolRegistered","toolUnregistered"];let t=0;for(const r of e)t+=this.listenerCount(r);return t}getStatistics(){const e={},t={};let r=0,n=0;for(const o of this.toolRegistry.values()){e[o.serverId]=(e[o.serverId]||0)+1;const s=typeof o.metadata?.category=="string"?o.metadata.category:"unknown";t[s]=(t[s]||0)+1,o.isAvailable?r++:n++}return{totalTools:this.toolRegistry.size,availableTools:r,unavailableTools:n,totalServers:this.serverTools.size,toolsByServer:e,toolsByCategory:t}}}}}),rLt,Bqr=S({"src/lib/mcp/registry.ts"(){"use strict";q(),rLt=class{plugins=new Map;register(e){this.plugins.set(e.metadata.name,e),dr.debug(`Registered plugin: ${e.metadata.name}`)}unregister(e){const t=this.plugins.delete(e);return t&&dr.debug(`Unregistered plugin: ${e}`),t}get(e){return this.plugins.get(e)}list(){return Array.from(this.plugins.values())}has(e){return this.plugins.has(e)}clear(){this.plugins.clear(),dr.info("Registry cleared")}async registerServer(e,t,r){const n={metadata:{name:e,description:typeof t=="object"&&t&&t.description||"No description"},tools:typeof t=="object"&&t?t.tools:{},configuration:typeof t=="object"&&t?t:{}};this.register(n)}async executeTool(e,t,r){return dr.info(`Executing tool: ${e}`),{result:`Mock execution of ${e}`,args:t}}async listTools(e){return this.list().map(r=>({name:r.metadata.name,description:r.metadata.description||"No description",serverId:r.metadata.name,category:"general"}))}registerServerSync(e){this.register(e)}executeToolSync(e,t){return dr.info(`Executing tool (sync): ${e}`),{result:`Mock execution of ${e}`,args:t}}listToolsSync(){return this.list().map(t=>({name:t.metadata.name,description:t.metadata.description||"No description"}))}listServers(){return Array.from(this.plugins.keys())}}}});function Ia(e){return e.existingCategory&&["external","in-memory","built-in","user-defined"].includes(e.existingCategory)?e.existingCategory:e.isCustomTool?"user-defined":e.isBuiltIn?"built-in":e.isExternal?"external":e.serverId?.startsWith("custom-tool-")?"user-defined":e.serverId?.includes("external")?"external":e.serverId==="direct"?"built-in":"in-memory"}function zqr(e,t){switch(t){case"external":return`External MCP server: ${e}`;case"built-in":return`Built-in tool server: ${e}`;case"custom":case"user-defined":return`Custom tool server: ${e}`;case"in-memory":return`In-memory MCP server: ${e}`;default:return e}}function nLt(e){const t=e.id||`server-${e.name}`,r=e.category||Ia({isCustomTool:e.isCustomTool,isExternal:e.isExternal,isBuiltIn:e.isBuiltIn,serverId:t}),n=e.tools||(e.tool?[e.tool]:[]);return{id:t,name:e.name,transport:e.transport||"stdio",status:e.status||"connected",tools:n,description:e.description||zqr(e.name,r),...e.command&&{command:e.command},...e.args&&{args:e.args},...e.env&&{env:e.env},metadata:{category:r,toolCount:n.length}}}function jqr(e,t,r,n,o){const s=nLt({id:`custom-tool-${e}`,name:e,tool:{name:e,description:t.description||e,inputSchema:t.inputSchema||{},execute:t.execute},isCustomTool:!0});return s.metadata&&(r!==void 0&&(s.metadata.toolTimeoutMs=r),n!==void 0&&(s.metadata.toolMaxRetries=n),o!==void 0&&(s.metadata.toolTotalTimeoutMs=o)),s}var lre=S({"src/lib/utils/mcpDefaults.ts"(){"use strict"}}),oLt,qqr=S({"src/lib/mcp/flexibleToolValidator.ts"(){"use strict";q(),oLt=class{static MAX_TOOL_NAME_LENGTH=1e3;static MIN_TOOL_NAME_LENGTH=1;static validateToolName(e){const t=[];if(!e||typeof e!="string")return{isValid:!1,error:"Tool name is required and must be a string"};if(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/.test(e))return{isValid:!1,error:"Tool name contains control characters that could break systems"};const n=e.trim();return n.length===0?{isValid:!1,error:"Tool name cannot be empty or whitespace-only"}:n.length<this.MIN_TOOL_NAME_LENGTH?{isValid:!1,error:`Tool name must be at least ${this.MIN_TOOL_NAME_LENGTH} character long`}:n.length>this.MAX_TOOL_NAME_LENGTH?{isValid:!1,error:`Tool name exceeds maximum length of ${this.MAX_TOOL_NAME_LENGTH} characters`}:(n!==e&&t.push("Tool name has leading/trailing whitespace (will be trimmed)"),n.length>200&&t.push("Tool name is unusually long but allowed"),dr.debug(`\u2705 FlexibleToolValidator: Tool '${e}' passed universal safety checks`),{isValid:!0,warnings:t.length>0?t:void 0})}static validateToolInfo(e,t){const r=this.validateToolName(e);if(!r.isValid)return r;const n=[...r.warnings||[]];return t.description&&typeof t.description!="string"?{isValid:!1,error:"Tool description must be a string if provided"}:t.serverId&&typeof t.serverId!="string"?{isValid:!1,error:"Tool serverId must be a string if provided"}:(dr.debug(`\u2705 FlexibleToolValidator: Tool info for '${e}' passed validation`),{isValid:!0,warnings:n.length>0?n:void 0})}static getValidationInfo(){return{philosophy:"Maximum flexibility with universal safety only - following Anthropic's MCP specification",checks:["Empty or whitespace-only names","Excessive length (over 1000 characters)","Control characters that could break systems"],whatIsAllowed:["Dots (github.create_repo, filesystem.read_file)","Hyphens and underscores (my-tool, user_helper)","Numbers (tool1, my_tool_v2)","Unicode characters (\u{1F680}_tool, caf\xE9_manager)","Mixed case (createRepo, ReadFile)","Long descriptive names (enterprise_database_connection_manager)","Any legitimate MCP tool naming pattern"],examples:{valid:["github.create_repo","filesystem.read_file","my-custom-tool","user_helper","tool1","\u{1F680}_rocket_tool","enterprise.database.connection.manager","UPPERCASE_TOOL","mixed_Case.Tool-Name_123"],invalid:[""," ","tool\0","a".repeat(1001)]}}}}}}),sLt={};he(sLt,{AuthError:()=>At,AuthErrorCodes:()=>zL});var zL,At,oa=S({"src/lib/auth/errors.ts"(){"use strict";KE(),zL={INVALID_TOKEN:"AUTH-001",EXPIRED_TOKEN:"AUTH-002",MISSING_TOKEN:"AUTH-003",TOKEN_DECODE_FAILED:"AUTH-004",INVALID_SIGNATURE:"AUTH-005",SESSION_NOT_FOUND:"AUTH-010",SESSION_EXPIRED:"AUTH-011",SESSION_REVOKED:"AUTH-012",INSUFFICIENT_PERMISSIONS:"AUTH-020",INSUFFICIENT_ROLES:"AUTH-021",ACCESS_DENIED:"AUTH-022",USER_NOT_FOUND:"AUTH-030",USER_DISABLED:"AUTH-031",EMAIL_NOT_VERIFIED:"AUTH-032",MFA_REQUIRED:"AUTH-033",PROVIDER_ERROR:"AUTH-040",PROVIDER_NOT_FOUND:"AUTH-041",PROVIDER_INIT_FAILED:"AUTH-042",CONFIGURATION_ERROR:"AUTH-043",CREATION_FAILED:"AUTH-050",REGISTRATION_FAILED:"AUTH-051",DUPLICATE_REGISTRATION:"AUTH-052",MIDDLEWARE_ERROR:"AUTH-060",RATE_LIMITED:"AUTH-061",JWKS_FETCH_FAILED:"AUTH-070",JWKS_KEY_NOT_FOUND:"AUTH-071"},At=Nf("Auth",zL)}}),jL={};he(jL,{AuthContextHolder:()=>HL,createAuthenticatedContext:()=>hLt,getAuthContext:()=>qL,getCurrentSession:()=>aLt,getCurrentUser:()=>nx,globalAuthContext:()=>oy,hasAllPermissions:()=>dLt,hasAnyRole:()=>uLt,hasPermission:()=>GL,hasRole:()=>ure,isAuthenticated:()=>lLt,requireAuth:()=>cre,requirePermission:()=>pLt,requireRole:()=>mLt,requireUser:()=>cLt,runWithAuthContext:()=>iLt});function iLt(e,t){return X_.run(e,t)}function qL(){return X_.getStore()??oy.get()}function nx(){return(X_.getStore()??oy.get())?.user}function aLt(){return(X_.getStore()??oy.get())?.session}function lLt(){return X_.getStore()!==void 0||oy.isAuthenticated()}function cre(){const e=qL();if(!e)throw At.create("MISSING_TOKEN","Authentication required");return e}function cLt(e){const t=cre();if(t.user.id!==e)throw At.create("ACCESS_DENIED","User mismatch");return t}function GL(e){const t=nx();if(!t)return!1;if(t.permissions.includes(e)||t.permissions.includes("*"))return!0;const r=e.split(":");for(let n=r.length-1;n>0;n--){const o=[...r.slice(0,n),"*"].join(":");if(t.permissions.includes(o))return!0}return!1}function ure(e){return nx()?.roles.includes(e)??!1}function uLt(e){const t=nx();return t?e.some(r=>t.roles.includes(r)):!1}function dLt(e){return e.every(t=>GL(t))}function pLt(e){if(!GL(e))throw At.create("INSUFFICIENT_PERMISSIONS",`Permission denied: ${e}`)}function mLt(e){if(!ure(e))throw At.create("INSUFFICIENT_ROLES",`Role required: ${e}`)}function hLt(e,t,r,n){return{...r,user:e,session:t,request:r,authenticatedAt:new Date,provider:n}}var X_,HL,oy,ox=S({"src/lib/auth/authContext.ts"(){"use strict";TC(),oa(),X_=new H0,HL=class{context;set(e){this.context=e}get(){return this.context}clear(){this.context=void 0}getUser(){return this.context?.user}getSession(){return this.context?.session}isAuthenticated(){return this.context!==void 0}hasPermission(e){const t=this.context?.user;if(!t)return!1;if(t.permissions.includes(e)||t.permissions.includes("*"))return!0;const r=e.split(":");for(let n=r.length-1;n>0;n--){const o=[...r.slice(0,n),"*"].join(":");if(t.permissions.includes(o))return!0}return!1}hasRole(e){return this.context?.user.roles.includes(e)??!1}},oy=new HL}}),VL,dre,pre=S({"src/lib/mcp/toolRegistry.ts"(){"use strict";Bqr(),q(),Bt(),kM(),sP(),Qi(),lre(),qqr(),at(),B1(),Il(),tr(),ox(),VL=class extends rLt{tools=new Map;toolImplementations=new Map;toolExecutionStats=new Map;builtInServerInfos=[];hitlManager;constructor(){super(),qG()||this.registerDirectTools()}setHITLManager(e){this.hitlManager=e,e&&e.isEnabled()?dr.info("HITL safety mechanisms enabled for tool execution"):dr.debug("HITL safety mechanisms disabled or not configured")}getHITLManager(){return this.hitlManager}registerDirectTools(){dr.debug("Auto-registering direct tools...");for(const[e,t]of Object.entries(Pf)){if(!t){dr.warn(`Skipping undefined tool during registration: ${e}`);continue}const r=`direct.${e}`,n=ms(t.inputSchema),o={name:e,description:t.description||`Direct tool: ${e}`,inputSchema:n,serverId:"direct",category:Ia({isBuiltIn:!0,serverId:"direct"})};this.tools.set(r,o),this.toolImplementations.set(r,{execute:async(s,i)=>{try{return{success:!0,data:await t.execute(s,{toolCallId:i?.sessionId||"unknown",messages:[]}),metadata:{toolName:e,serverId:"direct",executionTime:0}}}catch(a){return{success:!1,error:a instanceof Error?a.message:String(a),metadata:{toolName:e,serverId:"direct",executionTime:0}}}},description:t.description,inputSchema:n}),dr.debug(`Registered direct tool: ${e} as ${r}`)}dr.debug(`Auto-registered ${Object.keys(Pf).length} direct tools`)}async registerServer(e,t,r){let n;if(typeof e=="string"){const l=e;n=nLt({id:l,name:l,tools:[],isExternal:!0})}else n=e;const o=n.id,s={};for(const l of n.tools)s[l.name]={execute:l.execute||(async()=>{throw new Error(`Tool ${l.name} has no execute function`)}),description:l.description,inputSchema:l.inputSchema,category:Ia({existingCategory:n.metadata?.category,serverId:n.id})};const i={metadata:{name:n.name,description:n.description,category:Ia({existingCategory:n.metadata?.category,serverId:n.id})},tools:s,configuration:{}};this.register(i);const a=n.tools;for(const l of a){const u=o.startsWith("custom-tool-")?l.name:`${o}.${l.name}`,d=n.metadata?.toolTimeoutMs,m=n.metadata?.toolMaxRetries,h=n.metadata?.toolTotalTimeoutMs,g={name:l.name,description:l.description,inputSchema:l.inputSchema,outputSchema:void 0,serverId:o,category:Ia({existingCategory:n.metadata?.category,serverId:n.id}),permissions:[],...d!==void 0&&{timeoutMs:d},...m!==void 0&&{maxRetries:m},...h!==void 0&&{totalTimeoutMs:h}};this.tools.set(u,g),this.toolImplementations.set(u,{execute:l.execute||(async()=>{throw new Error(`Tool ${l.name} has no execute function`)}),description:l.description,inputSchema:l.inputSchema,category:Ia({existingCategory:n.metadata?.category,serverId:n.id}),...d!==void 0&&{timeoutMs:d},...m!==void 0&&{maxRetries:m},...h!==void 0&&{totalTimeoutMs:h}})}if(a.length>0){const l=Ia({existingCategory:n.metadata?.category,serverId:n.id});l==="in-memory"&&(this.builtInServerInfos.push(n),dr.debug(`Added ${l} server to builtInServerInfos: ${o} with ${a.length} tools`))}}async executeTool(e,t,r){const n=Date.now();let o;const s=this.tools.get(e);if(s)o=s.serverId;else for(const i of this.tools.values())if(i.name===e){o=i.serverId;break}return gt({name:"neurolink.tool.registry.execute",tracer:He.mcp,attributes:{[Pe.GEN_AI_TOOL_NAME]:e,[Pe.MCP_SERVER_ID]:o||"builtin","langfuse.internal":!0}},async i=>{try{dr.info(`\u{1F527} [TOOL_EXECUTION] Starting execution: ${e}`,{hasArgs:t!==void 0,hasContext:r!==void 0,sessionId:r?.sessionId});const{tool:a,toolId:l}=this.resolveToolExecutionTarget(e);if(!a)throw new Error(`Tool '${e}' not found in registry`);const c=a.serverId||"unknown",u=c==="direct"?"builtin":c.startsWith("custom-tool-")?"custom":"mcp";i.setAttribute("tool.type",u),i.setAttribute(Pe.MCP_SERVER_ID,c);const d=this.createExecutionContext(r),m=this.toolImplementations.get(l);if(dr.debug(`Looking for tool '${e}' (toolId: '${l}'), found: ${!!m}, type: ${typeof m?.execute}`),dr.debug("Available tools:",Array.from(this.toolImplementations.keys())),!m||typeof m?.execute!="function")throw new Error(`Tool '${e}' implementation not found or not executable`);let h;try{h=JSON.stringify(t).slice(0,4096)}catch{h="[unserializable]"}i.setAttribute("tool.arguments_present",t!==void 0),i.setAttribute("tool.arguments_size",h.length);let g=t;const y=r?.hitlState;if(!y?.triggered&&this.hitlManager&&this.hitlManager.isEnabled())if(this.hitlManager.requiresConfirmation(e,t)){dr.info(`Tool '${e}' requires HITL confirmation`),i.addEvent("tool.hitl_requested");try{y&&(y.triggered=!0);const x=await this.hitlManager.requestConfirmation(e,t,{serverId:a.serverId,sessionId:d.sessionId,userId:d.userId});if(!x.approved)throw i.addEvent("tool.hitl_rejected"),new ZT(`Tool execution rejected by user: ${x.reason||"No reason provided"}`,e,x.reason);i.addEvent("tool.hitl_approved"),x.modifiedArguments!==void 0&&(g=x.modifiedArguments,dr.info(`Tool '${e}' arguments modified by user`)),dr.info(`Tool '${e}' approved for execution (response time: ${x.responseTime}ms)`)}catch(x){throw x instanceof XT?(dr.warn(`Tool '${e}' execution timed out waiting for user confirmation`),x):x instanceof ZT?(dr.info(`Tool '${e}' execution rejected by user`),x):(dr.error(`HITL confirmation failed for tool '${e}':`,x),new Error(`HITL confirmation failed: ${x instanceof Error?x.message:String(x)}`,{cause:x}))}}else dr.debug(`Tool '${e}' does not require HITL confirmation`);dr.debug(`Executing tool '${e}' with args:`,g);const v=await m.execute(g,d);let _;if(v&&typeof v=="object"&&"success"in v&&typeof v.success=="boolean"){const k=v;_={...k,usage:{...k.usage||{},executionTime:Date.now()-n},metadata:{...k.metadata||{},toolName:e,serverId:a.serverId,sessionId:d.sessionId,executionTime:Date.now()-n}}}else _={success:!0,data:v,usage:{executionTime:Date.now()-n},metadata:{toolName:e,serverId:a.serverId,sessionId:d.sessionId,executionTime:Date.now()-n}};const b=Date.now()-n;this.updateStats(e,b);let T;try{T=JSON.stringify(_.data)??"undefined"}catch{T="[unserializable]"}return i.setAttribute("tool.result_length",T.length),i.setAttribute("tool.success",!0),dr.debug(`Tool '${e}' executed successfully in ${b}ms`),_}catch(a){dr.error(`Tool execution failed: ${e}`,a),i.setAttribute("tool.success",!1);const l=a instanceof Error?a.message:String(a);if(l.includes("not found in registry")||l.includes("not executable"))throw a;return i.setStatus({code:ze.ERROR,message:l}),a instanceof Error&&i.recordException(a),{success:!1,data:null,error:a instanceof Error?a.message:String(a),usage:{executionTime:Date.now()-n},metadata:{toolName:e,sessionId:r?.sessionId}}}})}async listTools(e){const t=new Map;for(const o of this.tools.values()){const s=`${o.serverId||"unknown"}.${o.name}`;t.has(s)||t.set(s,o)}let r=Array.from(t.values()),n;return e&&("sessionId"in e||"userId"in e?n=void 0:n=e),n&&(n.category&&(r=r.filter(o=>o.category===n.category)),n.serverId&&(r=r.filter(o=>o.serverId===n.serverId)),n.serverCategory&&(r=r.filter(o=>this.get(o.serverId||"")?.metadata?.category===n.serverCategory)),n.permissions&&n.permissions.length>0&&(r=r.filter(o=>{const s=o.permissions||[];return n.permissions?.some(i=>s.includes(i))??!1}))),dr.debug(`Listed ${r.length} unique tools (${n?"filtered":"unfiltered"})`),r}resolveToolExecutionTarget(e){let t=this.tools.get(e);dr.info(`\u{1F50D} [TOOL_LOOKUP] Direct lookup result for '${e}':`,!!t);let r=e;if(!t){const n=Array.from(this.tools.entries()).filter(([,o])=>o.name===e);if(n.length>1)throw ke.toolExecutionFailed(e,new Error(`Ambiguous tool name '${e}'. Use fully-qualified name 'serverId.${e}'.`));n.length===1&&([r,t]=n[0])}return{tool:t,toolId:r}}createExecutionContext(e){let t;try{t=qL()?.user?.id}catch{}return{...e,sessionId:e?.sessionId??st(),userId:e?.userId??t}}getToolInfo(e){let t=this.tools.get(e);if(!t){for(const r of this.tools.values())if(r.name===e){t=r;break}}if(t)return{tool:t,server:{id:t.serverId||"unknown-server"}}}updateStats(e,t){const r=this.toolExecutionStats.get(e)||{count:0,totalTime:0};r.count+=1,r.totalTime+=t,this.toolExecutionStats.set(e,r)}getExecutionStats(){const e={};for(const[t,r]of this.toolExecutionStats.entries())e[t]={count:r.count,totalTime:r.totalTime,averageTime:r.totalTime/r.count};return e}clearStats(){this.toolExecutionStats.clear()}getBuiltInServerInfos(){return this.builtInServerInfos}getToolsByCategory(e){const t=new Map;for(const[r,n]of this.tools.entries())n.category===e&&!t.has(r)&&t.set(r,n);return Array.from(t.values())}getAvailableTools(e){const t=Array.from(this.tools.values()),r=[],n=[];for(const o of t){const s=`${o.serverId||"unknown"}.${o.name}`,i=e.get(s);i&&i.getState()==="open"?r.push(o.name):n.push(o)}return{tools:n,unavailableTools:r}}hasTool(e){if(this.tools.has(e))return!0;for(const t of this.tools.values())if(t.name===e)return!0;return!1}async registerTool(e,t,r){dr.debug(`Registering tool: ${e}`);const n=oLt.validateToolInfo(e,{description:t.description,serverId:t.serverId});if(!n.isValid)throw dr.error(`Tool registration failed for ${e}: ${n.error}`),new Error(`Tool validation failed: ${n.error}`);n.warnings&&n.warnings.length>0&&dr.warn(`Tool registration warnings for ${e}:`,n.warnings),dr.debug(`\u2705 Tool '${e}' passed flexible validation - registration proceeding`),this.tools.set(e,t),this.toolImplementations.set(e,r),dr.debug(`Successfully registered tool: ${e}`)}removeTool(e){let t=!1;if(this.tools.has(e))this.tools.delete(e),this.toolImplementations.delete(e),this.toolExecutionStats.delete(e),dr.info(`Removed tool: ${e}`),t=!0;else for(const[r,n]of Array.from(this.tools.entries()))n.name===e&&(this.tools.delete(r),this.toolImplementations.delete(r),this.toolExecutionStats.delete(r),dr.info(`Removed tool: ${r}`),t=!0);return t}getToolCount(){return this.tools.size}getStats(){const e=this.list(),t=Array.from(this.tools.values()),r={};for(const o of e){const s=o.metadata?.category||"uncategorized";r[s]=(r[s]||0)+1}const n={};for(const o of t){const s=o.category||"uncategorized";n[s]=(n[s]||0)+1}return{totalServers:e.length,totalTools:t.length,serversByCategory:r,toolsByCategory:n,executionStats:this.getExecutionStats()}}unregisterServer(e){const t=[];for(const[s,i]of this.tools.entries())i.serverId===e&&(this.tools.delete(s),this.toolImplementations.delete(s),this.toolExecutionStats.delete(s),t.push(s));const r=this.builtInServerInfos.length;this.builtInServerInfos=this.builtInServerInfos.filter(s=>s.id!==e);const n=r>this.builtInServerInfos.length,o=this.unregister(e);return dr.info(`Unregistered server ${e}, removed ${t.length} tools${n?" and server from builtInServerInfos":""}`),o}},dre=new VL}});function Q_(e){if(typeof e=="string")return e.replace(/\$\{([^}]+)\}/g,(t,r)=>{const n=process.env[r.trim()];return n===void 0?(de.warn(`[ExternalServerManager] Environment variable ${r} is not defined, using empty string`),""):n});if(Array.isArray(e))return e.map(t=>Q_(t));if(ar(e)){const t={};for(const[r,n]of Object.entries(e))t[r]=Q_(n);return t}return e}function fLt(e){const t=e instanceof Error?e.message:String(e);return yLt.test(t)}function Gqr(e){if(!e||e.length===0)return e;const t=[...e];for(let r=0;r<t.length;r++){const n=t[r].indexOf("=");if(n!==-1){const o=t[r].substring(0,n);fre.test(o)&&(t[r]=`${o}=[REDACTED]`);continue}fre.test(t[r])&&r+1<t.length&&!t[r+1].startsWith("--")&&(t[r+1]="[REDACTED]",r++)}return t}function mre(e){return EM(e)?Object.values(e).every(r=>r===null||typeof r=="string"||typeof r=="number"||typeof r=="boolean"?!0:Array.isArray(r)?r.every(n=>mre(n)||typeof n=="string"||typeof n=="number"||typeof n=="boolean"||n===null):ar(r)?mre(r):!1):!1}function sx(e){return mre(e)?e:void 0}function gLt(e){if(!ar(e))return!1;const t=e;if(t.blockedTools!==void 0&&(!Array.isArray(t.blockedTools)||!t.blockedTools.every(o=>typeof o=="string")))return!1;const r=typeof t.command=="string",n=typeof t.url=="string";return!r&&!n?!1:(t.command===void 0||typeof t.command=="string")&&(t.args===void 0||Array.isArray(t.args))&&(t.env===void 0||ar(t.env))&&(t.transport===void 0||typeof t.transport=="string")&&(t.timeout===void 0||typeof t.timeout=="number")&&(t.retries===void 0||typeof t.retries=="number")&&(t.healthCheckInterval===void 0||typeof t.healthCheckInterval=="number")&&(t.autoRestart===void 0||typeof t.autoRestart=="boolean")&&(t.cwd===void 0||typeof t.cwd=="string")&&(t.url===void 0||typeof t.url=="string")&&(t.headers===void 0||ar(t.headers))&&(t.httpOptions===void 0||ar(t.httpOptions))&&(t.retryConfig===void 0||ar(t.retryConfig))&&(t.rateLimiting===void 0||ar(t.rateLimiting))&&(t.metadata===void 0||ar(t.metadata))}var yLt,hre,fre,WL,gre,KL,vLt,yre,_Lt=S({"src/lib/mcp/externalServerManager.ts"(){"use strict";vn(),ZOt(),q(),ire(),Uqr(),pre(),B1(),lre(),Af(),SS(),vr(),tr(),yLt=/^Not connected$|MCP error -32000: Connection closed/,hre=2,fre=/^--(api-key|token|secret|password|key|figma-api-key|access-token|auth|credential)$/i,WL=new Set,gre=!1,KL=()=>{for(const e of WL)e.shutdown()},vLt=e=>{WL.add(e),gre||(gre=!0,process.on("SIGINT",KL),process.on("SIGTERM",KL),process.on("beforeExit",KL))},yre=class extends sn{servers=new Map;config;isShuttingDown=!1;healthChecksInFlight=new Set;inFlightToolCalls=new Map;unresponsiveChecks=new Map;toolDiscovery;enableMainRegistryIntegration;hitlManager;constructor(e={},t={}){super();const r=Math.max(5e3,Number(process.env.MCP_CLIENT_TIMEOUT)||6e4);this.config={maxServers:e.maxServers??10,defaultTimeout:e.defaultTimeout??r,defaultHealthCheckInterval:e.defaultHealthCheckInterval??3e4,enableAutoRestart:e.enableAutoRestart??!0,maxRestartAttempts:e.maxRestartAttempts??3,restartBackoffMultiplier:e.restartBackoffMultiplier??2,enablePerformanceMonitoring:e.enablePerformanceMonitoring??!0,logLevel:e.logLevel??"info"},this.enableMainRegistryIntegration=t.enableMainRegistryIntegration??!1,this.toolDiscovery=new tLt,this.toolDiscovery.on("toolRegistered",n=>{this.emit("toolDiscovered",{...n,serverName:this.getServerName(n.serverId)})}),this.toolDiscovery.on("toolUnregistered",n=>{this.emit("toolRemoved",{...n,serverName:this.getServerName(n.serverId)})}),vLt(this)}setOutputNormalizer(e){this.toolDiscovery.setOutputNormalizer(e),de.debug("[ExternalServerManager] MCP output normalizer attached to ToolDiscoveryService")}setHITLManager(e){this.hitlManager=e,e&&e.isEnabled()?de.info("[ExternalServerManager] HITL safety mechanisms enabled for external tool execution"):de.debug("[ExternalServerManager] HITL safety mechanisms disabled or not configured")}getHITLManager(){return this.hitlManager}getServerName(e){return this.servers.get(e)?.config?.name||e}async loadMCPConfiguration(e,t={}){return t.parallel?this.loadMCPConfigurationParallel(e):this.loadMCPConfigurationSequential(e)}async loadMCPConfigurationParallel(e){const t=await Promise.resolve().then(()=>(Wr(),El)),r=await Promise.resolve().then(()=>(wr(),Yc)),n=e||r.join(process.cwd(),".mcp-config.json");if(!t.existsSync(n))return de.debug(`[ExternalServerManager] No MCP config found at ${n}`),{serversLoaded:0,errors:[]};de.debug(`[ExternalServerManager] Loading MCP configuration in PARALLEL mode from ${n}`);try{const o=t.readFileSync(n,"utf8"),s=JSON.parse(o);if(!s.mcpServers||typeof s.mcpServers!="object")return de.debug("[ExternalServerManager] No mcpServers found in configuration"),{serversLoaded:0,errors:[]};const i=Object.entries(s.mcpServers).map(async([u,d])=>{try{if(!gLt(d))throw new Error(`Invalid server config for ${u}: missing required properties or wrong types`);const m={id:u,name:u,description:typeof d.description=="string"?d.description:`External MCP server: ${u}`,transport:typeof d.transport=="string"?d.transport:"stdio",status:"initializing",tools:[],command:typeof d.command=="string"?d.command:void 0,args:Array.isArray(d.args)?d.args:[],env:ar(d.env)?Q_(d.env):{},timeout:typeof d.timeout=="number"?d.timeout:void 0,retries:typeof d.retries=="number"?d.retries:void 0,healthCheckInterval:typeof d.healthCheckInterval=="number"?d.healthCheckInterval:void 0,autoRestart:typeof d.autoRestart=="boolean"?d.autoRestart:void 0,cwd:typeof d.cwd=="string"?d.cwd:void 0,url:typeof d.url=="string"?d.url:void 0,headers:ar(d.headers)?Q_(d.headers):void 0,httpOptions:ar(d.httpOptions)?d.httpOptions:void 0,retryConfig:ar(d.retryConfig)?d.retryConfig:void 0,rateLimiting:ar(d.rateLimiting)?d.rateLimiting:void 0,blockedTools:Array.isArray(d.blockedTools)?d.blockedTools:void 0,metadata:sx(d.metadata)},h=await this.addServer(u,m);return{serverId:u,result:h}}catch(m){const h=`Failed to load MCP server ${u}: ${m instanceof Error?m.message:String(m)}`;return{serverId:u,error:h}}}),a=await Promise.allSettled(i);let l=0;const c=[];for(const u of a)if(u.status==="fulfilled"){const{serverId:d,result:m,error:h}=u.value;if(m&&m.success)l++,de.debug(`[ExternalServerManager] Successfully loaded MCP server in parallel: ${d}`);else if(h)c.push(h),de.error(`[ExternalServerManager] Failed to load server ${d}: ${h}`);else if(m&&!m.success){const g=`Failed to load server ${d}: ${m.error}`;c.push(g),de.error(`[ExternalServerManager] ${g}`)}}else{const d=`Unexpected error during parallel loading: ${u.reason}`;c.push(d),de.error(`[ExternalServerManager] ${d}`)}return de.info(`[ExternalServerManager] PARALLEL MCP configuration loading complete: ${l} servers loaded, ${c.length} errors`),{serversLoaded:l,errors:c}}catch(o){const s=`Failed to load MCP configuration in parallel mode: ${o instanceof Error?o.message:String(o)}`;return de.error(`[ExternalServerManager] ${s}`),{serversLoaded:0,errors:[s]}}}async loadMCPConfigurationSequential(e){const t=await Promise.resolve().then(()=>(Wr(),El)),r=await Promise.resolve().then(()=>(wr(),Yc)),n=e||r.join(process.cwd(),".mcp-config.json");if(!t.existsSync(n))return de.debug(`[ExternalServerManager] No MCP config found at ${n}`),{serversLoaded:0,errors:[]};de.debug(`[ExternalServerManager] Loading MCP configuration from ${n}`);try{const o=t.readFileSync(n,"utf8"),s=JSON.parse(o);if(!s.mcpServers||typeof s.mcpServers!="object")return de.debug("[ExternalServerManager] No mcpServers found in configuration"),{serversLoaded:0,errors:[]};let i=0;const a=[];for(const[l,c]of Object.entries(s.mcpServers))try{if(!gLt(c))throw new Error(`Invalid server config for ${l}: missing required properties or wrong types`);const u={id:l,name:l,description:typeof c.description=="string"?c.description:`External MCP server: ${l}`,transport:typeof c.transport=="string"?c.transport:"stdio",status:"initializing",tools:[],command:typeof c.command=="string"?c.command:void 0,args:Array.isArray(c.args)?c.args:[],env:ar(c.env)?Q_(c.env):{},timeout:typeof c.timeout=="number"?c.timeout:void 0,retries:typeof c.retries=="number"?c.retries:void 0,healthCheckInterval:typeof c.healthCheckInterval=="number"?c.healthCheckInterval:void 0,autoRestart:typeof c.autoRestart=="boolean"?c.autoRestart:void 0,cwd:typeof c.cwd=="string"?c.cwd:void 0,url:typeof c.url=="string"?c.url:void 0,headers:ar(c.headers)?Q_(c.headers):void 0,httpOptions:ar(c.httpOptions)?c.httpOptions:void 0,retryConfig:ar(c.retryConfig)?c.retryConfig:void 0,rateLimiting:ar(c.rateLimiting)?c.rateLimiting:void 0,blockedTools:Array.isArray(c.blockedTools)?c.blockedTools:void 0,metadata:sx(c.metadata)},d=await this.addServer(l,u);if(d.success)i++,de.debug(`[ExternalServerManager] Successfully loaded MCP server: ${l}`);else{const m=`Failed to load server ${l}: ${d.error}`;a.push(m),de.error(`[ExternalServerManager] ${m}`)}}catch(u){const d=`Failed to load MCP server ${l}: ${u instanceof Error?u.message:String(u)}`;a.push(d),de.error(`[ExternalServerManager] ${d}`)}return de.info(`[ExternalServerManager] MCP configuration loading complete: ${i} servers loaded, ${a.length} errors`),{serversLoaded:i,errors:a}}catch(o){const s=`Failed to load MCP configuration: ${o instanceof Error?o.message:String(o)}`;return de.error(`[ExternalServerManager] ${s}`),{serversLoaded:0,errors:[s]}}}validateConfig(e){const t=[],r=[],n=[];return(!e.id||typeof e.id!="string")&&t.push("Server ID is required and must be a string"),["stdio","sse","websocket","http"].includes(e.transport)||t.push("Transport must be one of: stdio, sse, websocket, http"),e.transport==="stdio"?((!e.command||typeof e.command!="string")&&t.push("Command is required and must be a string for stdio transport"),Array.isArray(e.args)||t.push("Args must be an array")):(e.transport==="sse"||e.transport==="websocket"||e.transport==="http")&&(!e.url||typeof e.url!="string")&&t.push(`URL is required for ${e.transport} transport`),e.timeout&&e.timeout<5e3&&r.push("Timeout less than 5 seconds may cause connection issues"),e.retries&&e.retries>5&&r.push("High retry count may slow down error recovery"),e.healthCheckInterval||n.push("Consider setting a health check interval for better reliability"),e.autoRestart===void 0&&n.push("Consider enabling auto-restart for production use"),{isValid:t.length===0,errors:t,warnings:r,suggestions:n}}convertConfigToMCPServerInfo(e,t){return{id:e,name:String(t.metadata?.title||e),description:`External MCP server (${t.transport})`,status:"initializing",transport:t.transport,command:t.command,args:t.args,env:t.env,tools:[],blockedTools:t.blockedTools,timeout:t.timeout,retries:t.retries,healthCheckInterval:t.healthCheckInterval,autoRestart:t.autoRestart,cwd:t.cwd,url:t.url,metadata:{category:"external",...sx(t.metadata)||{}}}}async addServer(e,t){const r=Date.now();try{const n="transport"in t&&"command"in t&&!("tools"in t)?this.convertConfigToMCPServerInfo(e,t):t;if(this.servers.size>=this.config.maxServers)return{success:!1,error:`Maximum number of servers (${this.config.maxServers}) reached`,serverId:e,duration:Date.now()-r};const o={id:e,name:n.name,description:n.description,transport:n.transport,status:n.status,tools:n.tools,command:n.command||"",args:n.args||[],env:n.env||{},timeout:n.timeout,retries:n.retries,healthCheckInterval:n.healthCheckInterval,autoRestart:n.autoRestart,cwd:n.cwd,url:n.url,blockedTools:n.blockedTools,metadata:sx(n.metadata),headers:n.headers,httpOptions:n.httpOptions,retryConfig:n.retryConfig,rateLimiting:n.rateLimiting},s=this.validateConfig(o);if(!s.isValid)return{success:!1,error:`Configuration validation failed: ${s.errors.join(", ")}`,serverId:e,duration:Date.now()-r};if(this.servers.has(e))return{success:!1,error:`Server with ID '${e}' already exists`,serverId:e,duration:Date.now()-r};de.info(`[ExternalServerManager] Adding server: ${e}`,{command:n.command,transport:n.transport});const i={...n,process:null,client:null,transportInstance:null,status:"initializing",reconnectAttempts:0,maxReconnectAttempts:this.config.maxRestartAttempts,toolsMap:new Map,metrics:{totalConnections:0,totalDisconnections:0,totalErrors:0,totalToolCalls:0,averageResponseTime:0,lastResponseTime:0},config:o};this.servers.set(e,i),await this.startServer(e);const a=this.servers.get(e);if(!a)throw new Error(`Server ${e} not found after registration`);return{success:!0,data:{config:a.config,process:a.process,pid:a.pid,client:a.client,transport:a.transportInstance,status:a.status,lastError:a.lastError,startTime:a.startTime,lastHealthCheck:a.lastHealthCheck,reconnectAttempts:a.reconnectAttempts,maxReconnectAttempts:a.maxReconnectAttempts,tools:a.toolsMap,toolsArray:a.toolsArray,capabilities:a.capabilities,healthTimer:a.healthTimer,restartTimer:a.restartTimer,metrics:a.metrics},serverId:e,duration:Date.now()-r,metadata:{timestamp:Date.now(),operation:"addServer",toolsDiscovered:a.tools.length}}}catch(n){return de.debug(`[ExternalServerManager] Failed to add server ${e}:`,n),this.servers.delete(e),{success:!1,error:n instanceof Error?n.message:String(n),serverId:e,duration:Date.now()-r}}}async removeServer(e){const t=Date.now();try{if(!this.servers.get(e))return{success:!1,error:`Server '${e}' not found`,serverId:e,duration:Date.now()-t};de.info(`[ExternalServerManager] Removing server: ${e}`);const n=this.getServerName(e);return await this.stopServer(e),this.servers.delete(e),this.emit("disconnected",{serverId:e,serverName:n,reason:"Manually removed",timestamp:new Date}),{success:!0,serverId:e,duration:Date.now()-t,metadata:{timestamp:Date.now(),operation:"removeServer"}}}catch(r){return de.error(`[ExternalServerManager] Failed to remove server ${e}:`,r),{success:!1,error:r instanceof Error?r.message:String(r),serverId:e,duration:Date.now()-t}}}async startServer(e){const t=this.servers.get(e);if(!t)throw new Error(`Server '${e}' not found`);const r=t.config,n=He.mcp.startSpan("neurolink.mcp.server.start",{attributes:{"mcp.server_id":e,"mcp.transport":r.transport,"mcp.command_name":r.command&&r.command.split(/[\\/]/).pop()||"","mcp.command_present":!!r.command}});try{this.updateServerStatus(e,"connecting"),de.debug(`[ExternalServerManager] Starting server: ${e}`,{command:r.command,args:Gqr(r.args),transport:r.transport});const o=await Z_.createClient(r,r.timeout||this.config.defaultTimeout);if(!o.success||!o.client||!o.transport)throw new Error(`Failed to create MCP client: ${o.error}`);t.client=o.client,t.transportInstance=o.transport,t.process=o.process||null,t.pid=o.transport instanceof Pte?o.transport.pid??void 0:void 0,t.capabilities=sx(o.capabilities),t.startTime=new Date,t.lastHealthCheck=new Date,t.metrics.totalConnections++,this.unresponsiveChecks.delete(e),this.attachClientLifecycle(e,o.client,o.transport),this.updateServerStatus(e,"connected"),await this.discoverServerTools(e),this.enableMainRegistryIntegration&&await this.registerServerToolsWithMainRegistry(e),this.startHealthMonitoring(e),this.emit("connected",{serverId:e,serverName:this.getServerName(e),toolCount:t.toolsMap.size,timestamp:new Date}),n.setAttribute("mcp.tool_count",t.toolsMap.size),n.setStatus({code:ze.OK}),de.info(`[ExternalServerManager] Server started successfully: ${e}`)}catch(o){throw de.debug(`[ExternalServerManager] Failed to start server ${e}:`,o),this.updateServerStatus(e,"failed"),t.lastError=o instanceof Error?o.message:String(o),n.recordException(o instanceof Error?o:new Error(String(o))),n.setStatus({code:ze.ERROR,message:o instanceof Error?o.message:String(o)}),o}finally{n.end()}}async stopServer(e){const t=this.servers.get(e);if(!t)return;const r=He.mcp.startSpan("neurolink.mcp.server.stop",{attributes:{"mcp.server_id":e}});try{if(this.updateServerStatus(e,"stopping"),t.healthTimer&&(clearInterval(t.healthTimer),t.healthTimer=void 0),t.restartTimer&&(clearTimeout(t.restartTimer),t.restartTimer=void 0),this.enableMainRegistryIntegration&&this.unregisterServerToolsFromMainRegistry(e),this.toolDiscovery.clearServerTools(e),t.client&&t.transportInstance){t.client.onclose=void 0,t.client.onerror=void 0;try{await Z_.closeClient(t.client,t.transportInstance)}catch(n){de.debug(`[ExternalServerManager] Error closing client for ${e}:`,n)}t.client=null,t.transportInstance=null,t.process=null,t.pid=void 0}this.updateServerStatus(e,"stopped"),r.setStatus({code:ze.OK}),de.info(`[ExternalServerManager] Server stopped: ${e}`)}catch(n){de.error(`[ExternalServerManager] Error stopping server ${e}:`,n),this.updateServerStatus(e,"failed"),r.recordException(n instanceof Error?n:new Error(String(n))),r.setStatus({code:ze.ERROR,message:n instanceof Error?n.message:String(n)})}finally{r.end()}}updateServerStatus(e,t){const r=this.servers.get(e);if(!r)return;const n=r.status,o=t==="connecting"||t==="restarting"?"initializing":t==="stopping"||t==="stopped"?"stopping":t==="connected"?"connected":t==="disconnected"?"disconnected":"failed";r.status=o,this.emit("statusChanged",{serverId:e,serverName:this.getServerName(e),oldStatus:n,newStatus:t,timestamp:new Date}),de.debug(`[ExternalServerManager] Status changed for ${e}: ${n} -> ${t}`)}attachClientLifecycle(e,t,r){t.onclose=()=>{const n=this.servers.get(e),o=n?.pid?` (pid ${n.pid})`:"",s=Z_.getStderrTail(r),i=s.length>0?`Server process closed${o}; last stderr: ${s.slice(-5).join(" | ")}`:`Server process closed${o}`;this.handleConnectionLost(e,t,i,s)},t.onerror=n=>{de.warn(`[ExternalServerManager] Transport error for ${e}: ${n.message}`)}}handleConnectionLost(e,t,r,n=[]){const o=this.servers.get(e);!o||o.client!==t||o.status!=="connected"||(de.warn(`[ExternalServerManager] Connection lost for ${e}: ${r}`,n.length>0?{stderrTail:n}:void 0),o.lastError=r,this.handleServerDisconnection(e,r))}trackToolCall(e,t){const r=(this.inFlightToolCalls.get(e)??0)+t;r<=0?this.inFlightToolCalls.delete(e):this.inFlightToolCalls.set(e,r)}handleServerError(e,t){const r=this.servers.get(e);r&&(r.lastError=t.message,r.metrics.totalErrors++,de.error(`[ExternalServerManager] Server error for ${e}:`,t),this.emit("failed",{serverId:e,serverName:this.getServerName(e),error:t.message,timestamp:new Date}),this.config.enableAutoRestart&&!this.isShuttingDown?this.scheduleRestart(e):this.updateServerStatus(e,"failed"))}handleServerDisconnection(e,t){const r=this.servers.get(e);r&&(r.metrics.totalDisconnections++,de.warn(`[ExternalServerManager] Server disconnected ${e}: ${t}`),this.emit("disconnected",{serverId:e,serverName:this.getServerName(e),reason:t,timestamp:new Date}),(r.config.autoRestart??this.config.enableAutoRestart)&&!this.isShuttingDown?this.scheduleRestart(e):this.updateServerStatus(e,"disconnected"))}scheduleRestart(e){const t=this.servers.get(e);if(!t)return;if(t.reconnectAttempts>=t.maxReconnectAttempts){de.error(`[ExternalServerManager] Max restart attempts reached for ${e}`),this.updateServerStatus(e,"failed");return}t.reconnectAttempts++,this.updateServerStatus(e,"restarting");const r=Math.min(1e3*Math.pow(this.config.restartBackoffMultiplier,t.reconnectAttempts-1),3e4);de.info(`[ExternalServerManager] Scheduling restart for ${e} in ${r}ms (attempt ${t.reconnectAttempts})`),!t.restartTimer&&(t.restartTimer=setTimeout(async()=>{const n=He.mcp.startSpan("neurolink.mcp.server.restart",{attributes:{"mcp.server_id":e,"mcp.restart_attempt":t.reconnectAttempts,"mcp.restart_delay_ms":r}});try{await this.stopServer(e),await this.startServer(e),t.reconnectAttempts=0,n.setStatus({code:ze.OK})}catch(o){de.error(`[ExternalServerManager] Restart failed for ${e}:`,o),n.recordException(o instanceof Error?o:new Error(String(o))),n.setStatus({code:ze.ERROR,message:o instanceof Error?o.message:String(o)}),this.scheduleRestart(e)}finally{n.end()}},r))}startHealthMonitoring(e){const t=this.servers.get(e);if(!t||!this.config.enablePerformanceMonitoring)return;const r=t.config.healthCheckInterval??this.config.defaultHealthCheckInterval;t.healthTimer=setInterval(async()=>{await this.performHealthCheck(e)},r)}async performHealthCheck(e){const t=this.servers.get(e);if(!t||t.status!=="connected"||!t.client||this.healthChecksInFlight.has(e))return;this.healthChecksInFlight.add(e);const r=t.client,n=t.config.healthCheckInterval??this.config.defaultHealthCheckInterval,o=Math.max(1,Math.min(t.config.timeout||this.config.defaultTimeout,n)),s=Date.now(),i=[];let a=!0,l=!1,c=!1;try{try{await r.ping({timeout:o}),this.unresponsiveChecks.delete(e)}catch(m){if(a=!1,fLt(m))l=!0,i.push("connection closed");else{const h=this.inFlightToolCalls.get(e)??0;if(h>0)i.push(`ping timed out after ${o}ms while ${h} tool call(s) in flight`);else{const g=(this.unresponsiveChecks.get(e)??0)+1;this.unresponsiveChecks.set(e,g),i.push(`ping timed out after ${o}ms while idle (${g}/${hre})`),c=g>=hre}}}const u=Date.now()-s;t.lastHealthCheck=new Date;const d={serverId:e,isHealthy:a,status:t.status,checkedAt:new Date,responseTime:u,toolCount:t.toolsMap.size,issues:i,performance:{uptime:t.startTime?Date.now()-t.startTime.getTime():0,averageResponseTime:t.metrics.averageResponseTime}};this.emit("healthCheck",{serverId:e,serverName:this.getServerName(e),health:d,timestamp:new Date}),l||c?this.handleConnectionLost(e,r,`Health check failed: ${i.join(", ")}`):a||de.warn(`[ExternalServerManager] Health check failed for ${e}:`,i)}catch(u){de.error(`[ExternalServerManager] Health check error for ${e}:`,u)}finally{this.healthChecksInFlight.delete(e)}}getServer(e){const t=this.servers.get(e);if(t)return{config:t.config,process:t.process,pid:t.pid,client:t.client,transport:t.transportInstance,status:t.status,lastError:t.lastError,startTime:t.startTime,lastHealthCheck:t.lastHealthCheck,reconnectAttempts:t.reconnectAttempts,maxReconnectAttempts:t.maxReconnectAttempts,tools:t.toolsMap,toolsArray:t.toolsArray,capabilities:t.capabilities,healthTimer:t.healthTimer,restartTimer:t.restartTimer,metrics:t.metrics}}getAllServers(){const e=new Map;for(const[t,r]of this.servers.entries())e.set(t,{config:r.config,process:r.process,pid:r.pid,client:r.client,transport:r.transportInstance,status:r.status,lastError:r.lastError,startTime:r.startTime,lastHealthCheck:r.lastHealthCheck,reconnectAttempts:r.reconnectAttempts,maxReconnectAttempts:r.maxReconnectAttempts,tools:r.toolsMap,toolsArray:r.toolsArray,capabilities:r.capabilities,healthTimer:r.healthTimer,restartTimer:r.restartTimer,metrics:r.metrics});return e}listServers(){return Array.from(this.servers.values())}getServerStatuses(){const e=[];for(const[t,r]of Array.from(this.servers.entries())){const n=r.startTime?Date.now()-r.startTime.getTime():0;e.push({serverId:t,isHealthy:r.status==="connected",status:r.status,checkedAt:r.lastHealthCheck||new Date,toolCount:r.toolsMap.size,issues:r.lastError?[r.lastError]:[],performance:{uptime:n,averageResponseTime:r.metrics.averageResponseTime}})}return e}async shutdown(){if(this.isShuttingDown)return;this.isShuttingDown=!0,WL.delete(this),de.info("[ExternalServerManager] Shutting down all servers...");const e=Array.from(this.servers.keys()).map(t=>this.stopServer(t).catch(r=>{de.error(`[ExternalServerManager] Error shutting down ${t}:`,r)}));await Promise.all(e),this.servers.clear(),this.toolDiscovery.destroy(),this.removeAllListeners(),de.info("[ExternalServerManager] All servers shut down and resources cleaned up")}async destroy(){return this.shutdown()}getStatistics(){let e=0,t=0,r=0,n=0,o=0;for(const s of Array.from(this.servers.values()))s.status==="connected"?e++:s.status==="failed"&&t++,r+=s.toolsMap.size,n+=s.metrics.totalConnections,o+=s.metrics.totalErrors;return{totalServers:this.servers.size,connectedServers:e,failedServers:t,totalTools:r,totalConnections:n,totalErrors:o}}async discoverServerTools(e){const t=this.servers.get(e);if(!t||!t.client)throw new Error(`Server '${e}' not found or not connected`);try{de.debug(`[ExternalServerManager] Discovering tools for server: ${e}`);const r=await this.toolDiscovery.discoverTools(e,t.client,t.config.timeout||this.config.defaultTimeout);if(r.success){t.toolsMap.clear(),t.toolsArray=void 0,t.tools=[];const n=t.blockedTools||[];let o=0;for(const s of r.tools){if(n.includes(s.name)){de.info(`[ExternalServerManager] Blocking tool '${s.name}' from server '${e}' (configured in blockedTools)`),o++;continue}t.toolsMap.set(s.name,s),t.tools.push({name:s.name,description:s.description,inputSchema:s.inputSchema})}de.info(`[ExternalServerManager] Discovered ${r.toolCount} tools for ${e} (${o} blocked, ${t.toolsMap.size} available)`)}else de.warn(`[ExternalServerManager] Tool discovery failed for ${e}: ${r.error}`)}catch(r){de.error(`[ExternalServerManager] Tool discovery error for ${e}:`,r)}}async registerServerToolsWithMainRegistry(e){const t=this.servers.get(e);if(!t)throw new Error(`Server '${e}' not found`);try{de.debug(`[ExternalServerManager] Registering ${t.toolsMap.size} tools with main registry for server: ${e}`);const r=[];for(const[i,a]of t.toolsMap.entries()){const l=`${e}.${i}`,c={name:i,description:a.description||i,inputSchema:a.inputSchema||{},serverId:e,category:Ia({isExternal:!0,serverId:e})};try{r.push(dre.registerTool(l,c,{execute:async(u,d)=>await this.executeTool(e,i,u,{timeout:t.config.timeout||this.config.defaultTimeout})})),de.debug(`[ExternalServerManager] Registered tool with main registry: ${l}`)}catch(u){de.warn(`[ExternalServerManager] Failed to register tool ${l} with main registry:`,u)}}const n=await Promise.allSettled(r),o=n.filter(i=>i.status==="fulfilled").length,s=n.length-o;de.info(`[ExternalServerManager] Registered ${o}/${n.length} tools with main registry for ${e}${s?` (${s} failed)`:""}`)}catch(r){de.error(`[ExternalServerManager] Failed to register tools with main registry for ${e}:`,r)}}unregisterServerToolsFromMainRegistry(e){const t=this.servers.get(e);if(!(!t||!this.enableMainRegistryIntegration))try{de.debug(`[ExternalServerManager] Unregistering tools from main registry for server: ${e}`);for(const[r]of t.toolsMap.entries()){const n=`${e}.${r}`;try{dre.removeTool(n),de.debug(`[ExternalServerManager] Unregistered tool from main registry: ${n}`)}catch(o){de.debug(`[ExternalServerManager] Failed to unregister tool ${n}:`,o)}}de.debug(`[ExternalServerManager] Completed unregistering tools from main registry for ${e}`)}catch(r){de.error(`[ExternalServerManager] Error unregistering tools from main registry for ${e}:`,r)}}async executeTool(e,t,r,n){const o=this.servers.get(e);if(!o)throw new Error(`Server '${e}' not found`);const s=o.client;if(!s)throw new Error(`Server '${e}' is not connected`);if(o.status!=="connected")throw new Error(`Server '${e}' is not in connected state: ${o.status}`);if((o.blockedTools||[]).includes(t))throw new Error(`Tool '${t}' is blocked on server '${e}' by configuration`);const a=Date.now();try{let l=r;if(this.hitlManager&&this.hitlManager.isEnabled())if(this.hitlManager.requiresConfirmation(t,r)){de.info(`[ExternalServerManager] External tool '${t}' on server '${e}' requires HITL confirmation`);try{const h=await this.hitlManager.requestConfirmation(t,r,{serverId:e,sessionId:`external-${e}-${Date.now()}`,userId:void 0});if(!h.approved)throw new ZT(`External tool execution rejected by user: ${h.reason||"No reason provided"}`,t,h.reason);h.modifiedArguments!==void 0&&(l=h.modifiedArguments,de.info(`[ExternalServerManager] External tool '${t}' arguments modified by user`)),de.info(`[ExternalServerManager] External tool '${t}' approved for execution (response time: ${h.responseTime}ms)`)}catch(h){throw h instanceof XT?(de.warn(`[ExternalServerManager] External tool '${t}' execution timed out waiting for user confirmation`),h):h instanceof ZT?(de.info(`[ExternalServerManager] External tool '${t}' execution rejected by user`),h):(de.error(`[ExternalServerManager] HITL confirmation failed for external tool '${t}':`,h),new Error(`HITL confirmation failed: ${h instanceof Error?h.message:String(h)}`,{cause:h}))}}else de.debug(`[ExternalServerManager] External tool '${t}' does not require HITL confirmation`);this.trackToolCall(e,1);let c;try{c=await this.toolDiscovery.executeTool(t,e,s,l,{timeout:n?.timeout||o.config.timeout||this.config.defaultTimeout})}finally{this.trackToolCall(e,-1)}const u=Date.now()-a;o.metrics.totalToolCalls++,o.metrics.lastResponseTime=u;const d=o.metrics.averageResponseTime*(o.metrics.totalToolCalls-1)+u;if(o.metrics.averageResponseTime=d/o.metrics.totalToolCalls,c.success){de.debug(`[ExternalServerManager] Tool executed successfully: ${t} on ${e}`,{duration:u});try{jf.getInstance()?.recordMCPToolCall(t,u,!0)}catch{}return c.data}else throw new Error(c.error||"Tool execution failed")}catch(l){o.metrics.totalErrors++;try{const c=Date.now()-a;jf.getInstance()?.recordMCPToolCall(t,c,!1)}catch{}throw de.error(`[ExternalServerManager] Tool execution failed: ${t} on ${e}`,l),fLt(l)&&this.handleConnectionLost(e,s,`Connection lost during tool call '${t}': ${l instanceof Error?l.message:String(l)}`),l}}getAllTools(){return this.toolDiscovery.getAllTools()}getServerTools(e){return this.toolDiscovery.getServerTools(e)}getToolDiscovery(){return this.toolDiscovery}}}});function Hqr(e,t,r,n){return{content:[{type:"text",text:`[MCP Tool Output \u2014 ${r.toolName} | ${r.serverId}]
|
|
1487
1487
|
Original size: ${ix(n)} | Externalized \u2014 use retrieve_context with artifactId="${t}" to read the full output (supports offset + limit pagination)
|
|
1488
1488
|
|
|
1489
1489
|
--- Preview (head + tail) ---
|
|
@@ -2159,7 +2159,7 @@ ${r}`:r}}return t?`${t}
|
|
|
2159
2159
|
|
|
2160
2160
|
${r}`:r}async retrieveKnowledgeGrounding(t){const r=this.knowledgeGroundingEngine;if(!r||!r.isEnabled()||t.useKnowledgeGrounding!==!0)return;const n=t.input?.text;if(n)try{const s=(t.conversationMessages!==void 0?t.conversationMessages:await this.fetchRecentRoutingHistory(t)).filter(i=>i.role==="user"||i.role==="assistant").slice(-zN).map(i=>({role:i.role==="assistant"?"assistant":"user",text:typeof i.content=="string"?i.content:""}));return await r.ground({query:n,recentTurns:s,scope:t.knowledgeContext})}catch(o){f.warn("[KnowledgeGrounding] grounding hook failed open",{error:String(o)});return}}async validateStreamRequestOptions(t,r){if(await this.validateStreamInput(t),t.inputValidation&&t.input?.text){const n=t.inputValidation;if(n.trimWhitespace&&(t.input.text=t.input.text.trim()),n.requireContent&&!t.input.text.trim())throw new Error("Input content is required but was empty or whitespace");if(n.minLength&&t.input.text.length<n.minLength)throw new Error(`Input text is too short (${t.input.text.length} < ${n.minLength})`);if(n.maxLength&&t.input.text.length>n.maxLength)throw new Error(`Input text is too long (${t.input.text.length} > ${n.maxLength})`)}if(t.piiDetection?.enabled&&t.input?.text){const n=await Xoe(t.input.text,{enabled:!0,action:t.piiDetection.action??"warn",detectTypes:t.piiDetection.detectTypes,customPatterns:t.piiDetection.customPatterns,allowList:t.piiDetection.allowList,redactionText:t.piiDetection.redactionText});if(n.action==="abort")throw new Error(n.feedback??"Request blocked: PII detected in input");t.input.text=n.text}this.enforceSessionBudget(t.maxBudgetUsd),await this.applyAuthenticatedRequestContext(t),this.emitStreamStartEvents(t,r),this.applyStreamLifecycleMiddleware(t)}async maybeHandleWorkflowStreamRequest(t){if(!t.options.workflow&&!t.options.workflowConfig)return null;const r=await this.streamWithWorkflow(t.options,t.startTime),n=r.stream,o=this;return r.stream=(async function*(){try{for await(const s of n)yield s;t.streamSpan.setStatus({code:ze.OK})}catch(s){throw t.streamSpan.setStatus({code:ze.ERROR,message:s instanceof Error?s.message:String(s)}),s}finally{o._disableToolCacheForCurrentRequest=!1,o._toolCacheKeysServedThisRequest=new Set,o._generationTurnActive=!1,t.streamSpan.setAttribute("neurolink.response_time_ms",Date.now()-t.spanStartTime),t.streamSpan.end()}})(),r}async runStandardStreamRequest(t){const{options:r,streamSpan:n,spanStartTime:o,startTime:s,hrTimeStart:i,streamId:a,originalPrompt:l,ttsResolver:c,ttsMetadataSink:u}=t;f.debug("[NeuroLink] Running standard stream request",{streamId:a,provider:r.provider,model:r.model,inputLength:r.input?.text?.length||0,disableTools:r.disableTools,enableAnalytics:r.enableAnalytics,enableEvaluation:r.enableEvaluation,contextKeys:r.context?Object.keys(r.context):[],optionKeys:Object.keys(r),sessionId:r.context?.sessionId});try{const{enhancedOptions:d,factoryResult:m}=await this.prepareStreamOptions(r,a,s,i);f.debug("[NeuroLink] Stream options prepared",{streamId:a,options:d,factoryResult:m,sessionId:d.context?.sessionId});const{stream:h,provider:g,usage:y,model:v,finishReason:_,toolCalls:b,toolResults:T,analytics:k,metadata:x}=await this.createMCPStream(d);let I;const{stream:M,ttsMetadata:R}=await this.createIncrementalTTSStream({stream:h,ttsOptions:d.tts,providerName:g,fallbackProvider:d.provider,onComplete:G=>{I=G}});u?.(R);const A={finishReason:_??"stop",toolCalls:b,toolResults:T};n.setAttribute(Pe.NL_PROVIDER,g||"unknown");let O="",N=0;const{eventSequence:L,cleanup:P}=this.setupStreamEventListeners(),D={fallbackAttempted:!1,guardrailsBlocked:!1,error:void 0,fallbackProvider:void 0,fallbackModel:void 0},F=this,$=Date.now(),B=d.context?.sessionId,z={providerEmitted:!1};d._streamDedupContext=z;const j=(async function*(){let G,Q,ve=0;try{for await(const H of M){N++;const Z=H!==null&&typeof H=="object"&&"metadata"in H&&H.metadata?.noOutput===!0,Ee=H&&"content"in H&&typeof H.content=="string"&&H.content.length>0,Se=H!==null&&typeof H=="object"&&"type"in H&&(H.type==="audio"||H.type==="tts_audio"||H.type==="image");!Z&&(Ee||Se)&&ve++,H&&"content"in H&&typeof H.content=="string"&&(O+=H.content,F.emitter.emit("response:chunk",H.content),F.emitter.emit("stream:chunk",{type:"stream:chunk",content:H.content,metadata:{chunkIndex:N,totalLength:O.length,...Z&&{noOutput:!0}},timestamp:Date.now()})),yield H}const te=d.fallbackOnMaxSteps===!1&&x?.stopReason==="step-cap";if(ve===0&&!te&&!D.fallbackAttempted&&!d.disableInternalFallback&&A.toolCalls.length===0&&A.toolResults.length===0){const H=F.handleStreamFallback(D,A,l,d,g,Ee=>{O+=Ee}),{stream:Z}=await F.createIncrementalTTSStream({stream:H,ttsOptions:d.tts,providerName:g,fallbackProvider:d.provider,ttsMetadata:R,onComplete:Ee=>{I=Ee}});yield*Z}if(c?.(I),Q=y,!Q&&k)try{const H=await Promise.resolve(k);H?.tokenUsage&&(Q=H.tokenUsage)}catch{}F.emitter.emit("stream:complete",{type:"stream:complete",content:O,provider:D.fallbackProvider??g,model:D.fallbackModel??v??d.model,finishReason:A.finishReason??"stop",prompt:d.input?.text||d.prompt,metadata:{chunkCount:N,totalLength:O.length,durationMs:Date.now()-$,sessionId:B,usage:Q,finishReason:A.finishReason??"stop",...D.fallbackAttempted&&{primaryProvider:g,primaryModel:d.model,fallback:!0}},timestamp:Date.now()})}catch(te){throw f.debug("[NeuroLink.stream] Stream error occurred",{error:te instanceof Error?te.message:String(te),name:te instanceof Error?te.name:"UnknownError",provider:g,model:d.model,chunkCount:N,totalLength:O.length,durationMs:Date.now()-$,sessionId:B}),G=te,F.emitter.emit("stream:error",{type:"stream:error",content:te instanceof Error?te.message:String(te),provider:g,model:d.model,metadata:{chunkCount:N,totalLength:O.length,durationMs:Date.now()-$,errorName:te instanceof Error?te.name:"UnknownError",sessionId:B},timestamp:Date.now()}),te}finally{if(c?.(void 0),f.debug("[NeuroLink.stream] Stream finished, performing cleanup",{provider:g,model:d.model,totalChunks:N,totalLength:O.length,durationMs:Date.now()-$,fallbackAttempted:D.fallbackAttempted,guardrailsBlocked:D.guardrailsBlocked,error:D.error}),!z.providerEmitted)try{const H=D.fallbackProvider??g??"unknown",Z=D.fallbackModel??v??d.model??"unknown",Ee=G?"error":A.finishReason??"stop";F.emitter.emit("generation:end",{provider:H,model:Z,responseTime:Date.now()-$,toolsUsed:A.toolCalls?.map(Se=>Se.toolName),timestamp:Date.now(),result:{content:O,usage:Q,model:Z,provider:H,finishReason:Ee},prompt:d.input?.text||d.prompt,temperature:d.temperature,maxTokens:d.maxTokens,success:!G,error:G?G instanceof Error?G.message:String(G):void 0,pipelineAHandled:!0})}catch(H){f.debug("[NeuroLink.stream] generation:end listener threw \u2014 ignored",{error:H instanceof Error?H.message:String(H)})}F._disableToolCacheForCurrentRequest=!1,F._toolCacheKeysServedThisRequest=new Set,F._generationTurnActive=!1,P(),n.setAttribute("neurolink.response_time_ms",Date.now()-o),n.setAttribute(Pe.NL_OUTPUT_LENGTH,O.length);const te=!!(D.error||G);n.setAttribute(Pe.GEN_AI_FINISH_REASON,te?"error":"stop"),D.fallbackAttempted&&(n.setAttribute("neurolink.fallback_triggered",!0),D.fallbackProvider&&n.setAttribute("neurolink.fallback_provider",D.fallbackProvider)),te?n.setStatus({code:ze.ERROR,message:D.error||(G instanceof Error?G.message:String(G))}):n.setStatus({code:ze.OK}),n.end(),O.trim()&&f.info("[NeuroLink.stream] stream() - COMPLETE SUCCESS",{provider:g,model:d.model,responseTimeMs:Date.now()-s,contentLength:O.length,fallback:D.fallbackAttempted}),await F.storeStreamConversationMemory({enhancedOptions:d,providerName:g,originalPrompt:l,accumulatedContent:O,startTime:s,eventSequence:L})}})(),K=await this.processStreamResult(j,d,m);return K.finishReason=A.finishReason||K.finishReason,K.toolCalls=A.toolCalls,K.toolResults=A.toolResults,K.usage||(K.usage=y),K.analytics||(K.analytics=k),Promise.resolve(K.analytics).then(G=>{G?.cost&&G.cost>0&&(this._sessionCostUsd+=G.cost)}).catch(()=>{}),this.emitStreamEndEvents(K),this.createStreamResponse(K,j,{providerName:g,options:r,startTime:s,responseTime:Date.now()-s,streamId:a,fallback:D.fallbackAttempted,guardrailsBlocked:D.guardrailsBlocked,error:D.error,events:L,providerMetadata:x})}catch(d){if(c?.(void 0),r.disableInternalFallback)throw d;return this.handleStreamError(d,r,s,a,void 0,void 0)}}async createIncrementalTTSStream(t){const{stream:r,ttsOptions:n,providerName:o,fallbackProvider:s,onComplete:i}=t;if(!n?.enabled)return i(void 0),{stream:r};const{TTSProcessor:a}=await Promise.resolve().then(()=>(fc(),jGe)),l=s==="auto"?void 0:s,c=n.provider??l??o,u=c&&a.supports(c)?c:void 0,d=t.ttsMetadata??{attempted:u!==void 0,success:!1};d.attempted=u!==void 0,d.success=!1,delete d.error,delete d.latency;const m=Date.now();let h=!1;const g=(y,v)=>{h||(h=!0,d.success=v===void 0&&y!==void 0,v?d.error=v:delete d.error,d.latency=Date.now()-m,i(y))};return u?{stream:QGe({stream:r,provider:u,options:n,onComplete:g}),ttsMetadata:d}:(f.warn(`[NeuroLink.stream] No TTS provider resolved for incremental streaming (set tts.provider explicitly \u2014 chat provider "${c??"<unset>"}" is not a registered TTS handler)`),g(void 0),{stream:r,ttsMetadata:d})}deferProviderStreamTTS(t){return t.tts?.enabled?{...t,tts:void 0}:t}async prepareStreamOptions(t,r,n,o){if(await this.initializeConversationMemoryForGeneration(r,n,o),await this.initializeMCP(),this.shouldReadMemory(t.memory,t.context?.userId)&&t.context?.userId)try{t.input.text=await this.retrieveMemory(t.input.text??"",t.context.userId,t.memory?.additionalUsers),f.debug("Memory retrieval successful")}catch(a){f.warn("Memory retrieval failed:",a)}if(await this.applySkillsAugmentation(t),this.enableOrchestration&&!t.provider&&!t.model)try{const a=await this.applyStreamOrchestration(t);f.debug("Stream orchestration applied",{originalProvider:t.provider||"auto",orchestratedProvider:a.provider,orchestratedModel:a.model,prompt:t.input.text?.substring(0,100)}),t={...t,...a},a.model&&(t.model=Mx(t.model,this.modelAliasConfig))}catch(a){f.warn("Stream orchestration failed, continuing with original options",{error:a instanceof Error?a.message:String(a),originalProvider:t.provider||"auto"})}if(await this.autoDisableOllamaStreamTools(t),t.rag?.files?.length)try{const{prepareRAGTool:a}=await Promise.resolve().then(()=>(use(),cse)),l=await a(t.rag,t.provider);t.tools||(t.tools={}),t.tools[l.toolName]=l.tool;const c=[`
|
|
2161
2161
|
|
|
2162
|
-
IMPORTANT: You have a tool called "${l.toolName}" that searches through`,`${l.filesLoaded} loaded document(s) containing ${l.chunksIndexed} indexed chunks.`,`ALWAYS use the "${l.toolName}" tool FIRST to answer the user's question before using any other tools.`,"This tool searches your local knowledge base of pre-loaded documents and is the primary source of truth.","Do NOT use websearchGrounding or any web search tools when the answer can be found in the loaded documents."].join(" ");t.systemPrompt=(t.systemPrompt||"")+c,f.info("[RAG] Tool injected into stream()",{toolName:l.toolName,filesLoaded:l.filesLoaded,chunksIndexed:l.chunksIndexed})}catch(a){f.warn("[RAG] Failed to prepare RAG tool, continuing without RAG",{error:a instanceof Error?a.message:String(a)})}const s=U7r(t),i=B7r(t);if(t.input?.text){const{toolResults:a,enhancedPrompt:l}=await this.detectAndExecuteTools(t.input.text,void 0);l!==t.input.text&&(i.input.text=l)}return{enhancedOptions:i,factoryResult:s}}async autoDisableOllamaStreamTools(t){if((t.provider==="ollama"||t.provider?.toLowerCase().includes("ollama"))&&!t.disableTools){const{ModelConfigurationManager:r}=await Promise.resolve().then(()=>(Gf(),IGe)),s=r.getInstance().getProviderConfiguration("ollama")?.modelBehavior?.toolCapableModels||[],i=t.model;s.length>0&&i&&(s.some(l=>i.toLowerCase().includes(l.toLowerCase()))||(t.disableTools=!0,f.debug("Auto-disabled tools for Ollama model that doesn't support them (stream)",{model:t.model,toolCapableModels:s.slice(0,3)})))}}setupStreamEventListeners(){const t=[];let r=0;const n=(d,m)=>{t.push({type:d,seq:r++,timestamp:Date.now(),...m&&typeof m=="object"?m:{data:m}})},o=(...d)=>{const m=d[0];n("response:chunk",{content:m})},s=(...d)=>{const m=d[0];n("tool:start",{...m,toolName:m.toolName??m.tool})},i=(...d)=>{const m=d[0],h=m.toolName??m.tool,g=m.responseTime??m.duration,y=m.success??(m.error!==void 0?!1:void 0),v={...m,toolName:h,...g!==void 0?{responseTime:g}:{},...y!==void 0?{success:y}:{},...m.error!==void 0?{error:m.error}:{}};n("tool:end",v),v.result&&v.result.uiComponent===!0&&n("ui-component",{toolName:h,componentData:v.result,timestamp:Date.now(),...y!==void 0?{success:y}:{},...g!==void 0?{responseTime:g}:{}})},a=(...d)=>{n("ui-component",d[0])},l=(...d)=>{n("hitl:confirmation-request",d[0])},c=(...d)=>{n("hitl:confirmation-response",d[0])};return this.emitter.on("response:chunk",o),this.emitter.on("tool:start",s),this.emitter.on("tool:end",i),this.emitter.on("ui-component",a),this.emitter.on("hitl:confirmation-request",l),this.emitter.on("hitl:confirmation-response",c),{eventSequence:t,cleanup:()=>{this.emitter.off("response:chunk",o),this.emitter.off("tool:start",s),this.emitter.off("tool:end",i),this.emitter.off("ui-component",a),this.emitter.off("hitl:confirmation-request",l),this.emitter.off("hitl:confirmation-response",c)}}}async*handleStreamFallback(t,r,n,o,s,i){t.fallbackAttempted=!0;const a="Stream completed with 0 chunks (possible guardrails block)";t.error=a;try{const g=this._metricsTraceContext;let y=Oe.createGenerationSpan({provider:s,model:o.model||"unknown",name:`gen_ai.${s}.stream.failed`,traceId:g?.traceId,parentSpanId:g?.parentSpanId});y=Oe.endSpan(y,2),y.statusMessage=a,y.durationMs=0,this.metricsAggregator.recordSpan(y),ut().recordSpan(y)}catch{}const l=o.fallbackProvider?.trim()||void 0,c=o.fallbackModel?.trim()||void 0,u=process.env.FALLBACK_PROVIDER?.trim()||void 0,d=process.env.FALLBACK_MODEL?.trim()||void 0,m=M2.getFallbackRoute(n||o.input.text||"",{provider:s,model:o.model||"gpt-4o",reasoning:"primary failed",confidence:.5},{fallbackStrategy:"auto"}),h={...m,provider:l??u??m.provider,model:c??d??m.model};f.warn("Retrying with fallback provider",{originalProvider:s,fallbackProvider:h.provider,fallbackModel:h.model,fallbackSource:l||c?"options":u||d?"env":"model_config",reason:a});try{const g=await po.createProvider(h.provider,h.model,!0,void 0,void 0,this.resolveCredentials(o.credentials));g.setupToolExecutor({customTools:this.getCustomTools(),executeTool:(x,I)=>this.executeTool(x,I,{disableToolCache:o.disableToolCache})},"NeuroLink.fallbackStream");const y=o.conversationMessages!==void 0?o.conversationMessages:await mh(this.conversationMemory,{prompt:o.input.text,context:o.context}),v=await g.stream({...this.deferProviderStreamTTS(o),model:h.model,conversationMessages:y}),_=v.toolCalls??[],b=v.toolResults??[];(_.length>0||b.length>0)&&(r.toolCalls=_,r.toolResults=b,r.finishReason=v.finishReason??r.finishReason);let T=0,k=0;for await(const x of v.stream){T++;const I=x!==null&&typeof x=="object"&&"metadata"in x&&x.metadata?.noOutput===!0,M=x&&"content"in x&&typeof x.content=="string"&&x.content.length>0,R=x!==null&&typeof x=="object"&&"type"in x&&(x.type==="audio"||x.type==="tts_audio"||x.type==="image");!I&&(M||R)&&k++,x&&"content"in x&&typeof x.content=="string"&&(i(x.content),this.emitter.emit("response:chunk",x.content)),yield x}if(k===0&&_.length===0&&b.length===0)throw new Error(`Fallback provider ${h.provider} also returned 0 real output chunks (chunkCount=${T}, sentinel-only or empty)`);t.fallbackProvider=h.provider,t.fallbackModel=h.model,t.guardrailsBlocked=!0}catch(g){const y=g instanceof Error?g.message:String(g);throw t.error=`${a}; Fallback failed: ${y}`,f.error("Fallback provider failed",{fallbackProvider:h.provider,error:y}),g}}async storeStreamConversationMemory(t){const{enhancedOptions:r,providerName:n,originalPrompt:o,accumulatedContent:s,startTime:i,eventSequence:a}=t;f.shouldLog("debug")&&f.debug("[NeuroLink.stream] Preparing to store conversation turn in memory",{options:vM(wM(r)),sessionId:r.context?.sessionId});const l=a.some(c=>c.type==="tool:start"||c.type==="tool:end");if(!s.trim()&&!l){f.warn("[NeuroLink.stream] Skipping conversation turn storage \u2014 no text content or tool activity",{sessionId:r.context?.sessionId});return}if(f.shouldLog("debug")&&f.debug("[NeuroLink.stream] Storing conversation turn in memory",{options:vM(wM(r)),sessionId:r.context?.sessionId,conversationMemoryExists:!!this.conversationMemory}),this.conversationMemory&&r.context?.sessionId){const c=r.context?.sessionId,u=r.context?.userId;let d;r.model&&(d={provider:n,model:r.model});const m=Date.now();try{const h=this.drainPendingSkillMessages(c);await this.conversationMemory.storeConversationTurn({sessionId:c,userId:u,userMessage:o??"",aiResponse:s,startTimeStamp:new Date(i),providerDetails:d,enableSummarization:r.enableSummarization,events:a.length>0?a:void 0,requestId:r.context?.requestId,...h.length>0?{skillMessages:h}:{}}),this.recordMemorySpan("memory.store",{"memory.operation":"store","memory.path":"stream"},Date.now()-m,1),f.debug("[NeuroLink.stream] Stored conversation turn with events",{sessionId:c,eventCount:a.length,eventTypes:[...new Set(a.map(g=>g.type))]})}catch(h){this.recordMemorySpan("memory.store",{"memory.operation":"store","memory.path":"stream"},Date.now()-m,2,h instanceof Error?h.message:String(h)),f.warn("Failed to store stream conversation turn",{error:h instanceof Error?h.message:String(h)})}}this.shouldWriteMemory(r.memory,r.context?.userId,s)&&this.storeMemoryInBackground(o??"",s.trim(),r.context?.userId,r.memory?.additionalUsers,r.context)}async validateStreamInput(t){const r=process.hrtime.bigint();f.debug("[NeuroLink] \u{1F3AF} LOG_POINT_003_VALIDATION_START",{logPoint:"003_VALIDATION_START",validationStartTimeNs:r.toString(),message:"Starting comprehensive input validation process"});const n=typeof t?.input?.text=="string"&&t.input.text.trim().length>0,o=!!(t?.input?.audio&&t.input.audio.frames&&typeof t.input.audio.frames[Symbol.asyncIterator]=="function"),s=!!(t?.stt?.enabled&&t?.stt?.audio);if(!n&&!o&&!s)throw new Error("Stream options must include either input.text, input.audio, or stt.audio")}emitStreamStartEvents(t,r){this.emitter.emit("stream:start",{provider:t.provider||"auto",timestamp:r}),this.emitter.emit("response:start"),this.emitter.emit("message",`Starting ${t.provider||"auto"} stream...`)}async createMCPStream(t){const r=await lw(t.provider),n=await po.createProvider(r,t.model,!t.disableTools,this,t.region,this.resolveCredentials(t.credentials));await n.ensureModelLimits?.(),n.setTraceContext(this._metricsTraceContext),n.setupToolExecutor({customTools:this.getCustomTools(),executeTool:(g,y)=>this.executeTool(g,y,{disableToolCache:t.disableToolCache})},"NeuroLink.createMCPStream");let o=await this.getAllAvailableTools();o=this.applyToolInfoFiltering(o,t);const s=t.skipToolPromptInjection?t.systemPrompt||"":this.createToolAwareSystemPrompt(t.systemPrompt,o,n.supportsTools?.()??!0),i=t.conversationMessages!==void 0,a=i?t.conversationMessages:await mh(this.conversationMemory,{...t,prompt:t.input.text,context:t.context});t.conversationMessages=a;let l=a;const c=Aa({provider:r,model:t.model,maxTokens:t.maxTokens,systemPrompt:s,conversationMessages:l,currentPrompt:t.input.text,toolDefinitions:o}),u=l?.length||0,d=this.getCompactionSessionId(t),m=u>0;if(!c.withinBudget&&!m){try{this.emitter.emit("compaction.insufficient",{stagesAttempted:["pre-dispatch hard cap"],finalTokens:c.estimatedInputTokens,budget:c.availableInputTokens,provider:r,model:t.model,phase:"pre-dispatch-no-recovery",timestamp:Date.now()})}catch{}throw new Qa(`Stream context exceeds model budget and no compaction is possible (no conversationMemory, no inline conversationMessages \u2014 only prompt + tools). Estimated: ${c.estimatedInputTokens} tokens, budget: ${c.availableInputTokens} tokens. Reduce prompt or tool-definition size, or trim the request.`,{estimatedTokens:c.estimatedInputTokens,availableTokens:c.availableInputTokens,stagesUsed:[],breakdown:c.breakdown})}if(c.shouldCompact&&(i||this.conversationMemory)&&u>(this.lastCompactionMessageCount.get(d)??0)){const y=await new D_({provider:r,summarizationProvider:this.conversationMemoryConfig?.conversationMemory?.summarizationProvider,summarizationModel:this.conversationMemoryConfig?.conversationMemory?.summarizationModel}).compact(l,lee(c),this.conversationMemoryConfig?.conversationMemory,t.context?.requestId);y.compacted&&(l=M_(y.messages).messages,t.conversationMessages=l,this.lastCompactionMessageCount.set(d,l.length));const v=Aa({provider:r,model:t.model,maxTokens:t.maxTokens,systemPrompt:s,conversationMessages:l,currentPrompt:t.input.text,toolDefinitions:o});if(!v.withinBudget){f.warn("[NeuroLink] Stream: post-compaction still over budget, emergency truncation",{estimatedTokens:v.estimatedInputTokens,availableTokens:v.availableInputTokens,overagePercent:Math.round((v.usageRatio-1)*100)});try{this.emitter.emit("compaction.insufficient",{stagesAttempted:y.stagesUsed,finalTokens:v.estimatedInputTokens,budget:v.availableInputTokens,provider:r,model:t.model,phase:"mid-compaction",willEmergencyTruncate:!0,timestamp:Date.now()})}catch{}l=hee(l,v.availableInputTokens,v.breakdown,r),t.conversationMessages=l;const _=Aa({provider:r,model:t.model,maxTokens:t.maxTokens,systemPrompt:s,conversationMessages:l,currentPrompt:t.input.text,toolDefinitions:o});if(!_.withinBudget){this.lastCompactionMessageCount.delete(d);try{this.emitter.emit("compaction.insufficient",{stagesAttempted:y.stagesUsed,finalTokens:_.estimatedInputTokens,budget:_.availableInputTokens,provider:r,model:t.model,phase:"post-emergency-truncation",timestamp:Date.now()})}catch{}throw new Qa(`Stream context exceeds model budget after all compaction stages. Estimated: ${_.estimatedInputTokens} tokens, Budget: ${_.availableInputTokens} tokens.`,{estimatedTokens:_.estimatedInputTokens,availableTokens:_.availableInputTokens,stagesUsed:y.stagesUsed,breakdown:_.breakdown})}}}if(this.modelPool){const g=this.modelPool,y=g.maxAttempts,v=new Set;let _=null;for(let b=0;b<y;b++){if(t.abortSignal?.aborted)throw new DOMException("The operation was aborted","AbortError");const T=g.selectNext(v);if(!T)break;v.add(g.memberKey(T));const k=T.provider,x=T.model??void 0,I=T.region??void 0;f.debug(`[createMCPStream] ModelPool: attempting member ${k}`,{model:x,attempt:b});try{const M=await po.createProvider(k,x,!t.disableTools,this,I,this.resolveCredentials(t.credentials));M.setTraceContext(this._metricsTraceContext),M.setupToolExecutor({customTools:this.getCustomTools(),executeTool:(N,L)=>this.executeTool(N,L,{disableToolCache:t.disableToolCache})},"NeuroLink.createMCPStream");const R=await M.stream({...this.deferProviderStreamTTS(t),provider:k,model:x,region:I,systemPrompt:s,conversationMessages:l});f.debug("[createMCPStream] ModelPool stream handle obtained",{provider:k});const A=T;return{stream:(async function*(){try{yield*R.stream,g.recordSuccess(A)}catch(N){throw g.recordFailure(A,cw(N)),N}})(),provider:k,usage:R.usage,model:R.model||x,finishReason:R.finishReason,toolCalls:R.toolCalls??[],toolResults:R.toolResults??[],analytics:R.analytics,metadata:R.metadata}}catch(M){if(mr(M))throw M;if(Zse(M)){const R=M instanceof Error?M.message:String(M);throw g.recordFailure(T,cw(M)),new Error(`[ModelPool] non-retryable: ${R}`,{cause:M})}g.recordFailure(T,cw(M)),_=M instanceof Error?M:new Error(String(M)),f.warn(`[createMCPStream] ModelPool: member ${k} failed`,{error:_.message})}}throw new Error(`[ModelPool] all stream members failed: ${_?.message??"no stream members available"}`)}const h=await n.stream({...this.deferProviderStreamTTS(t),systemPrompt:s,conversationMessages:l});return f.debug("[createMCPStream] Stream created successfully",{provider:r,systemPromptPassedLength:s.length}),{stream:h.stream,provider:r,usage:h.usage,model:h.model||t.model,finishReason:h.finishReason,toolCalls:h.toolCalls??[],toolResults:h.toolResults??[],analytics:h.analytics,metadata:h.metadata}}async processStreamResult(t,r,n){return{content:"",usage:void 0,finishReason:"stop",toolCalls:[],toolResults:[],analytics:void 0,evaluation:void 0}}emitStreamEndEvents(t){this.emitter.emit("stream:end",{responseTime:Date.now(),timestamp:Date.now()}),this.emitter.emit("response:end",t.content||"")}createStreamResponse(t,r,n){return{stream:r,provider:n.providerName,model:n.options.model,usage:t.usage,finishReason:t.finishReason,toolCalls:t.toolCalls,toolResults:t.toolResults,analytics:t.analytics,evaluation:t.evaluation,events:n.events&&n.events.length>0?n.events:void 0,metadata:Object.assign(n.providerMetadata??{},{streamId:n.streamId,startTime:n.startTime,responseTime:n.responseTime,fallback:n.fallback||!1,guardrailsBlocked:n.guardrailsBlocked,error:n.error})}}async handleStreamError(t,r,n,o,s,i){if(t instanceof Qa)throw t;f.error("Stream generation failed, attempting fallback",{error:t instanceof Error?t.message:String(t)});try{this.emitter.emit("stream:error",{content:t instanceof Error?t.message:String(t),metadata:{errorName:t instanceof Error?t.name:"UnknownError",durationMs:Date.now()-n,chunkCount:0},provider:r.provider||"unknown",model:r.model||"unknown"})}catch{}const a=r.input.text,l=Date.now()-n,c=await lw(r.provider),d=await(await po.createProvider(c,r.model,!0,void 0,void 0,this.resolveCredentials(r.credentials))).stream({input:{text:r.input.text},model:r.model,temperature:r.temperature,maxTokens:r.maxTokens,conversationMessages:r.conversationMessages});let m="";return{stream:(async function*(g){try{for await(const y of d.stream)y&&"content"in y&&typeof y.content=="string"&&(m+=y.content,g.emitter.emit("response:chunk",y.content)),yield y}finally{if(m.trim()){f.info("[NeuroLink.handleStreamError] stream() - COMPLETE SUCCESS (fallback)",{provider:c,model:r.model,responseTimeMs:Date.now()-n,contentLength:m.length});try{const y=r.model||"unknown",v=Date.now()-n;g.emitter.emit("stream:complete",{content:m,provider:c,model:y,finishReason:"stop",metadata:{durationMs:v,chunkCount:0,totalLength:m.length,isFallback:!0,finishReason:"stop"}}),g.emitter.emit("generation:end",{provider:c,model:y,responseTime:v,timestamp:Date.now(),result:{content:m,usage:{input:0,output:0,total:0},model:y,provider:c,finishReason:"stop"},success:!0,pipelineAHandled:!0})}catch{}}if(g.conversationMemory&&s?.context?.sessionId&&m.trim()){const y=s?.context?.sessionId,v=s?.context?.userId;let _;r.model&&(_={provider:c,model:r.model});const b=Date.now();try{const T=y||r.context?.sessionId,k=g.drainPendingSkillMessages(T);await g.conversationMemory.storeConversationTurn({sessionId:T,userId:v||r.context?.userId,userMessage:a??"",aiResponse:m,startTimeStamp:new Date(n),providerDetails:_,enableSummarization:s?.enableSummarization,requestId:s?.context?.requestId||r.context?.requestId,...k.length>0?{skillMessages:k}:{}}),g.recordMemorySpan("memory.store",{"memory.operation":"store","memory.path":"fallback-stream"},Date.now()-b,1)}catch(T){g.recordMemorySpan("memory.store",{"memory.operation":"store","memory.path":"fallback-stream"},Date.now()-b,2,T instanceof Error?T.message:String(T)),f.warn("Failed to store fallback stream conversation turn",{error:T instanceof Error?T.message:String(T)})}}}})(this),provider:c,model:r.model,usage:d.usage,finishReason:d.finishReason||"stop",toolCalls:d.toolCalls||[],toolResults:d.toolResults||[],analytics:d.analytics,evaluation:d.evaluation,metadata:{streamId:o,startTime:n,responseTime:l,fallback:!0}}}getEventEmitter(){return this.emitter}hasPendingHITLConfirmation(t){return this.hitlManager?.hasPendingConfirmation(t)??!1}getToolDedupConfig(){return this.toolDedupConfig}getToolsConfig(){return this.toolsConfig}getDiscoveryPins(t){const r=this.discoveryPins.get(t);return r?(this.discoveryPins.delete(t),this.discoveryPins.set(t,r),r):new Set}pinDiscoveredTools(t,r){let n=this.discoveryPins.get(t);n?this.discoveryPins.delete(t):n=new Set,this.discoveryPins.set(t,n);for(const o of r)n.add(o);if(this.discoveryPins.size>1e3){const o=this.discoveryPins.keys().next().value;o!==void 0&&this.discoveryPins.delete(o)}}async checkCredentials(t){const{provider:r,model:n}=t,o="ping";try{return await this.generate({provider:r,...n&&{model:n},input:{text:o},maxTokens:16,disableTools:!0}),{provider:r,status:"ok",detail:"credentials valid"}}catch(s){const i=s instanceof Error?s.message:String(s),a=i.toLowerCase();return s instanceof uv?{provider:r,status:"denied",detail:i}:a.includes("authentication")||a.includes("401")||a.includes("invalid api key")||a.includes("incorrect api key")||a.includes("api_key_invalid")||a.includes("token has expired")||a.includes("expired credentials")?{provider:r,status:"expired",detail:i}:a.includes("not configured")||a.includes("missing api")||a.includes("api key is required")||a.includes("no api key")||a.includes("application default credentials")||a.includes("google_application_credentials")||a.includes("project_id")||a.includes("default credentials")||a.includes("service account")?{provider:r,status:"missing",detail:i}:a.includes("econnrefused")||a.includes("enotfound")||a.includes("could not resolve")||a.includes("timeout")||a.includes("network")||a.includes("cannot connect")?{provider:r,status:"network",detail:i}:{provider:r,status:"unknown",detail:i}}}emitToolStart(t,r,n=Date.now()){const o=`${t}-${n}-${Math.random().toString(36).substr(2,9)}`,s={executionId:o,tool:t,startTime:n,metadata:{inputType:typeof r,hasInput:r!=null}};return this.activeToolExecutions.set(o,s),this.currentStreamToolExecutions.push(s),this.emitter.emit("tool:start",x0(t,{input:r,timestamp:n,executionId:o})),f.debug(`tool:start emitted for ${t}`,{toolName:t,executionId:o,timestamp:n,inputProvided:r!==void 0}),o}emitToolEnd(t,r,n,o,s=Date.now(),i){const a=o||s-1e3,l=s-a,c=!n;let u;i?u=this.activeToolExecutions.get(i):u=Array.from(this.activeToolExecutions.values()).find(h=>h.tool===t&&!h.endTime);const d=i||u?.executionId||`${t}-${a}-fallback-${Math.random().toString(36).substr(2,9)}`;u&&(u.endTime=s,u.result=r,u.error=n,this.activeToolExecutions.delete(u.executionId));const m={tool:t,startTime:a,endTime:s,duration:l,success:c,result:r,error:n,executionId:d,metadata:{toolCategory:"custom"}};this.toolExecutionHistory.push(m),this.emitter.emit("tool:end",x0(t,{result:r,error:n,success:c,responseTime:l,timestamp:s,duration:l,executionId:d})),f.debug(`tool:end emitted for ${t}`,{toolName:t,executionId:d,duration:l,success:c,hasResult:r!==void 0,hasError:!!n})}getCurrentToolExecutions(){return[...this.currentStreamToolExecutions]}getToolExecutionHistory(){return[...this.toolExecutionHistory]}clearCurrentStreamExecutions(){this.currentStreamToolExecutions=[]}registerTool(t,r,n){this.invalidateToolCache(),this.emitter.emit("tools-register:start",{toolName:t,timestamp:Date.now()});try{if(!t||typeof t!="string")throw new Error("Invalid tool name");if(!r||typeof r!="object")throw new Error(`Invalid tool object provided for tool: ${t}`);if(typeof r.execute!="function")throw new Error(`Tool '${t}' must have an execute method.`);if(t.trim()==="")throw new Error("Tool name cannot be empty");if(t.length>100)throw new Error("Tool name is too long (maximum 100 characters)");if(/[\x00-\x1F\x7F]/.test(t))throw new Error("Tool name contains invalid control characters");const o={name:r.name||t,description:r.description||t,execute:r.execute,inputSchema:"parameters"in r&&r.parameters&&(e9(r.parameters)||typeof r.parameters=="object")?r.parameters:r.inputSchema||{}};if(n?.timeout!==void 0&&n.timeout>0&&Number.isFinite(n.timeout)&&typeof o.execute=="function"){const i=o.execute,a=n.timeout,l=t;o.execute=async(...c)=>{const u=AbortSignal.timeout(a),d=c[1],m=d?.abortSignal,h=m?AbortSignal.any([m,u]):u,g={...d,abortSignal:h};return Promise.race([i(c[0],g),new Promise((y,v)=>{h.addEventListener("abort",()=>{u.aborted?v(ke.toolTimeout(l,a)):v(new DOMException("The operation was aborted","AbortError"))},{once:!0})})])}}const s=jqr(t,o,n?.timeout,n?.maxRetries);this.toolRegistry.registerServer(s),n?.cacheable===!1?this.uncacheableTools.add(t):this.uncacheableTools.delete(t),this.emitter.emit("tools-register:end",{toolName:t,success:!0,timestamp:Date.now(),timeoutMs:n?.timeout})}catch(o){throw f.error(`Failed to register tool ${t}:`,o),o}}setToolContext(t){this.toolExecutionContext={...t},f.debug("Tool execution context updated",{sessionId:t.sessionId,contextKeys:Object.keys(t),hasJuspayToken:!!t.juspayToken,hasShopId:!!t.shopId})}getToolContext(){return this.toolExecutionContext?{...this.toolExecutionContext}:void 0}clearToolContext(){this.toolExecutionContext=void 0,f.debug("Tool execution context cleared")}registerTools(t){if(Array.isArray(t))for(const{name:r,tool:n}of t)this.registerTool(r,n);else for(const[r,n]of Object.entries(t))this.registerTool(r,n)}unregisterTool(t){this.invalidateToolCache();const r=`custom-tool-${t}`,n=this.toolRegistry.unregisterServer(r);return n&&(this.uncacheableTools.delete(t),f.info(`Unregistered custom tool: ${t}`)),n}useToolMiddleware(t){return this.mcpToolMiddlewares.push(t),f.debug(`[NeuroLink] Registered tool middleware (total: ${this.mcpToolMiddlewares.length})`),this}getToolMiddlewares(){return[...this.mcpToolMiddlewares]}async flushToolBatch(){this.mcpToolBatcher&&await this.mcpToolBatcher.flush()}getMCPEnhancementsConfig(){return this.mcpEnhancementsConfig}async updateAgenticLoopReport(t,r,n){if(!this.conversationMemory)throw new yl("Conversation memory is not initialized. Enable conversationMemory in NeuroLink options.","CONFIG_ERROR");if(!("updateAgenticLoopReport"in this.conversationMemory)||typeof this.conversationMemory.updateAgenticLoopReport!="function")throw new yl("updateAgenticLoopReport is only supported with Redis conversation memory.","CONFIG_ERROR");await Ze(this.conversationMemory.updateAgenticLoopReport(t,n,r),5e3)}getCustomTools(){const t=this.toolRegistry.getToolsByCategory(Ia({isCustomTool:!0})),r=new Map;for(const o of t){const s=o.inputSchema||o.parameters;f.debug("Processing tool schema for Claude",{toolName:o.name,hasDescription:!!o.description,description:o.description,hasParameters:!!o.parameters,parametersType:typeof o.parameters,parametersKeys:o.parameters&&typeof o.parameters=="object"?Object.keys(o.parameters):"NOT_OBJECT",hasInputSchema:!!o.inputSchema,inputSchemaType:typeof o.inputSchema,inputSchemaKeys:o.inputSchema&&typeof o.inputSchema=="object"?Object.keys(o.inputSchema):"NOT_OBJECT",hasEffectiveSchema:!!s,effectiveSchemaType:typeof s,effectiveSchemaHasProperties:!!s?.properties,effectiveSchemaHasRequired:!!s?.required,originalInputSchema:o.inputSchema,phase:"AFTER_SCHEMA_FIX",timestamp:Date.now()}),r.set(o.name,{name:o.name,description:o.description||"",inputSchema:typeof o.inputSchema=="object"&&o.inputSchema!==null?o.inputSchema:typeof o.parameters=="object"&&o.parameters!==null?o.parameters:{},execute:async(i,a)=>{const l=this.toolExecutionContext||{},c=a&&ar(a)?a:{},u={...l,...c,sessionId:c.sessionId||l.sessionId||`fallback-${Date.now()}`};return f.debug("Tool execution context merged",{toolName:o.name,storedContextKeys:Object.keys(l),runtimeContextKeys:Object.keys(c),finalContextKeys:Object.keys(u),hasJuspayToken:!!u.juspayToken,hasShopId:!!u.shopId,sessionId:u.sessionId}),await this.toolRegistry.executeTool(o.name,i,u)}})}this.cachedFileTools||(this.cachedFileTools=iDt(this.fileRegistry));const n=this.cachedFileTools;for(const[o,s]of Object.entries(n))if(!r.has(o)){const i=s,a=i.inputSchema??i.parameters;r.set(o,{name:o,description:s.description||`File tool: ${o}`,inputSchema:typeof a=="object"&&a!==null?a:{type:"object",properties:{}},execute:async l=>await s.execute(l,{toolCallId:`file-tool-${Date.now()}`,messages:[]})})}return r}async addInMemoryMCPServer(t,r){this.invalidateToolCache();try{de.debug(`[NeuroLink] Registering in-memory MCP server: ${t}`),r.tools||(r.tools=[]),await this.toolRegistry.registerServer(r),de.info(`[NeuroLink] Successfully registered in-memory server: ${t}`,{category:r.metadata?.category,provider:r.metadata?.provider,version:r.metadata?.version})}catch(n){throw de.error(`[NeuroLink] Failed to register in-memory server ${t}:`,n),n}}getInMemoryServers(){const t=this.getInMemoryServerInfos(),r=new Map;for(const n of t)r.set(n.id,n);return r}getInMemoryServerInfos(){return this.toolRegistry.getBuiltInServerInfos().filter(r=>Ia({existingCategory:r.metadata?.category,serverId:r.id})==="in-memory")}getAutoDiscoveredServerInfos(){return this.autoDiscoveredServerInfos}async executeTool(t,r={},n){if(this.mcpToolBatcher&&!n?.bypassBatcher)return this.mcpToolBatcher.execute(t,r);const o=this.createToolExecutionContext(t,r,n);return He.mcp.startActiveSpan("neurolink.tool.execute",{attributes:{"tool.name":t,"tool.type":o.toolType,"tool.input_size":o.inputSize,"tool.input_preview":o.truncatedInput}},s=>this.executeToolWithSpan(t,r,n,o,s))}createToolExecutionContext(t,r,n){const o=this.externalServerManager.getAllTools().find(c=>c.name===t),s=o?"mcp":this.getCustomTools().has(t)?"custom":"external",i=r?Kv(r):"",a=Date.now(),l=`${t}-${a}-${Math.random().toString(36).slice(2,11)}`;return{functionTag:"NeuroLink.executeTool",executionStartTime:a,executionId:l,externalTool:o,toolType:s,inputSize:i.length,truncatedInput:i.length>2048?i.substring(0,2048):i,options:n,hitlState:{triggered:!1}}}async executeToolWithSpan(t,r,n,o,s){try{const i=await this.prepareToolExecutionState(t,r,n,o);return await this.runPreparedToolExecution(t,r,i,o,s)}catch(i){if(!(i instanceof Ne)){const a=i instanceof Error?i.message:String(i);s.recordException(i instanceof Error?i:new Error(a)),s.setStatus({code:ze.ERROR,message:a})}throw i}finally{s.end()}}async prepareToolExecutionState(t,r,n,o){f.debug(`[${o.functionTag}] Tool execution requested:`,{toolName:t,params:ar(r)?W8e(r):r,hasExternalManager:!!this.externalServerManager}),f.debug("Tool execution detailed analysis",{toolName:t,executionStartTime:o.executionStartTime,paramsAnalysis:{type:typeof r,isNull:r===null,isUndefined:r===void 0,isEmpty:r&&typeof r=="object"&&Object.keys(r).length===0,keys:r&&typeof r=="object"?Object.keys(r):"NOT_OBJECT",keysLength:r&&typeof r=="object"?Object.keys(r).length:0},isTargetTool:t==="juspay-analytics_SuccessRateSRByTime",options:n,hasExternalManager:!!this.externalServerManager}),this.emitter.emit("tool:start",x0(t,{timestamp:o.executionStartTime,input:r,executionId:o.executionId}));const s=this.toolRegistry.getToolInfo(t),i={timeout:n?.timeout??s?.tool?.timeoutMs??tc.EXECUTION_BATCH_MS,maxRetries:n?.maxRetries??s?.tool?.maxRetries??ls.DEFAULT,retryDelayMs:n?.retryDelayMs||bn.BASE_MS,authContext:n?.authContext,disableToolCache:n?.disableToolCache},{MemoryManager:a}=await Promise.resolve().then(()=>(Dx(),dw)),l=a.getMemoryUsageMB(),u=`${o.externalTool?.serverId||s?.tool?.serverId||"unknown"}.${t}`;let d=this.toolCircuitBreakers.get(u);d||(d=new j1(jI.FAILURE_THRESHOLD,V3),this.toolCircuitBreakers.set(u,d));let m=this.toolExecutionMetrics.get(t);return m||(m={totalExecutions:0,successfulExecutions:0,failedExecutions:0,averageExecutionTime:0,lastExecutionTime:0,errorCategories:{}},this.toolExecutionMetrics.set(t,m)),m.totalExecutions++,{finalOptions:i,startMemory:l,circuitBreaker:d,breakerKey:u,metrics:m}}async runPreparedToolExecution(t,r,n,o,s){let i=0;try{de.debug(`[${o.functionTag}] Executing tool: ${t}`,{toolName:t,params:r,options:n.finalOptions,circuitBreakerState:n.circuitBreaker.getState()});const a=await n.circuitBreaker.execute(async()=>hve(async()=>Ze(this.executeToolInternal(t,r,n.finalOptions,o.hitlState),n.finalOptions.timeout,ke.toolTimeout(t,n.finalOptions.timeout)),{maxAttempts:n.finalOptions.maxRetries+1,delayMs:n.finalOptions.retryDelayMs,isRetriable:Tz,onRetry:(l,c)=>{i=l,de.warn(`[${o.functionTag}] Retrying tool execution (attempt ${l})`,{toolName:t,error:c.message,attempt:l})}}));return s.setAttribute("tool.retry_count",i),await this.handleSuccessfulToolExecution(t,a,n,o,s)}catch(a){return s.setAttribute("tool.retry_count",i),this.handleFailedToolExecution(t,r,a,n,o,s)}}async handleSuccessfulToolExecution(t,r,n,o,s){const i=Date.now()-o.executionStartTime;n.metrics.successfulExecutions++,n.metrics.lastExecutionTime=i,n.metrics.averageExecutionTime=(n.metrics.averageExecutionTime*(n.metrics.successfulExecutions-1)+i)/n.metrics.successfulExecutions;const{MemoryManager:a}=await Promise.resolve().then(()=>(Dx(),dw)),c=a.getMemoryUsageMB().heapUsed-n.startMemory.heapUsed;c>20&&de.warn(`Tool '${t}' used excessive memory: ${c}MB`,{toolName:t,memoryDelta:c,executionTime:i}),de.debug(`[${o.functionTag}] Tool executed successfully`,{toolName:t,executionTime:i,memoryDelta:c,circuitBreakerState:n.circuitBreaker.getState()});const u=r&&typeof r=="object"?r:void 0,d=u&&"isError"in u&&u.isError===!0||u&&"success"in u&&u.success===!1,m=d?u?.content:void 0,h=d?m?.filter(g=>g.type==="text"&&g.text).map(g=>g.text).join(" ")||(typeof u?.error=="string"?u.error:"Unknown error"):void 0;if(d){try{await n.circuitBreaker.execute(async()=>{throw new Error(`Tool ${t} returned isError:true`)})}catch{}de.debug(`[${o.functionTag}] Circuit breaker failure recorded for isError result`,{toolName:t,circuitBreakerState:n.circuitBreaker.getState(),circuitBreakerFailures:n.circuitBreaker.getFailureCount()});const g=BWr(h??"Unknown error"),y=`[TOOL_ERROR: ${t} failed (${g})] `;if(u&&Array.isArray(m)){const b=m.map(T=>({...T}));for(const T of b)if(T.type==="text"&&T.text){T.text=y+T.text;break}u.content=b}s.setAttribute("tool.error.message",(h??"Unknown error").substring(0,500)),s.setAttribute("tool.error.category",g),s.setStatus({code:ze.ERROR,message:`MCP tool returned isError: ${(h??"Unknown error").substring(0,200)}`}),n.metrics.failedExecutions++;const v=n.metrics.successfulExecutions;n.metrics.successfulExecutions=Math.max(0,n.metrics.successfulExecutions-1),n.metrics.averageExecutionTime=v>1?(n.metrics.averageExecutionTime*v-i)/(v-1):0;const _=zWr(g);n.metrics.errorCategories[_]=(n.metrics.errorCategories[_]||0)+1}return this.emitToolEndEvent(t,o.executionStartTime,!d,r,d&&h?new Error(h):void 0,o.executionId),s.setAttribute("tool.result.status",d?"error":"success"),s.setAttribute("tool.duration_ms",i),r}async handleFailedToolExecution(t,r,n,o,s,i){o.metrics.failedExecutions++;const a=Date.now()-s.executionStartTime;if(n instanceof am)return de.warn(`[${s.functionTag}] Tool blocked by circuit breaker: ${t}`,{toolName:t,breakerState:n.breakerState,retryAfter:n.retryAfter,retryAfterMs:n.retryAfterMs,failureCount:n.failureCount,executionTime:a}),o.metrics.errorCategories.execution=(o.metrics.errorCategories.execution||0)+1,this.emitToolEndEvent(t,s.executionStartTime,!1,void 0,new Error(`Circuit breaker open for ${t} (state=${n.breakerState}, failures=${n.failureCount})`),s.executionId),i.setAttribute("tool.result.status","circuit_breaker_open"),i.setAttribute("tool.duration_ms",a),i.setAttribute("tool.circuit_breaker.state",n.breakerState),i.setAttribute("tool.circuit_breaker.retry_after_ms",n.retryAfterMs),i.setAttribute("tool.circuit_breaker.failure_count",n.failureCount),i.setStatus({code:ze.ERROR,message:`Circuit breaker open for ${t}: ${n.message}`}),{isError:!0,content:[{type:"text",text:`TOOL TEMPORARILY UNAVAILABLE: "${t}" has been disabled after ${n.failureCount} failures. This is a circuit breaker protection \u2014 do NOT retry this tool. It will become available again after ${Math.ceil(n.retryAfterMs/1e3)} seconds (at ${n.retryAfter}). Instead, inform the user that the operation failed and suggest trying again later.`}]};let l;if(n instanceof Ne)l=n;else if(n instanceof Error)if(n.message.includes("timeout"))l=ke.toolTimeout(t,o.finalOptions.timeout);else if(n.message.includes("not found")){const u=await this.getAllAvailableTools();l=ke.toolNotFound(t,dMr(u.map(d=>({name:d.name}))))}else n.message.includes("validation")||n.message.includes("parameter")?l=ke.invalidParameters(t,n,r):n.message.includes("network")||n.message.includes("connection")?l=ke.networkError(t,n):l=ke.toolExecutionFailed(t,n);else l=ke.toolExecutionFailed(t,new Error(String(n)));const c=l.category||"execution";throw o.metrics.errorCategories[c]=(o.metrics.errorCategories[c]||0)+1,this.emitToolEndEvent(t,s.executionStartTime,!1,void 0,l,s.executionId),this.emitter.listenerCount("error")>0&&this.emitter.emit("error",l),l=new Ne({...l,context:{...l.context,executionTime:a,params:r,options:o.finalOptions,circuitBreakerState:o.circuitBreaker.getState(),circuitBreakerFailures:o.circuitBreaker.getFailureCount(),metrics:{...o.metrics}}}),fve(l),i.setAttribute("tool.result.status","error"),i.setAttribute("tool.duration_ms",a),i.recordException(l),i.setStatus({code:ze.ERROR,message:l.message}),l}toolCacheRepeatKey(t,r){try{return`${t}:${JSON.stringify(r)??""}`}catch{return}}async executeToolInternal(t,r,n,o){const s="NeuroLink.executeToolInternal",i=this.getToolAnnotationsForExecution(t),a=this.mcpToolResultCache&&!n.disableToolCache&&!this._disableToolCacheForCurrentRequest&&!this.uncacheableTools.has(t)&&!i?.destructiveHint,l=this.mcpToolResultCache,c=n.authContext||this.toolExecutionContext?{__args:r,__ctx:n.authContext??this.toolExecutionContext}:r,u=this._generationTurnActive?this.toolCacheRepeatKey(t,c):void 0,d=u!==void 0&&this._toolCacheKeysServedThisRequest.has(u);if(u!==void 0&&this._toolCacheKeysServedThisRequest.add(u),a&&l&&!d){const g=l.getCachedResult(t,c);if(g!==void 0)return f.debug(`[${s}] Cache HIT for tool: ${t}`),g}else d&&f.debug(`[${s}] Repeat call within this request \u2014 bypassing tool cache for: ${t}`);const m=async g=>{if(this.mcpToolMiddlewares.length===0)return g();let y=0;const v=async()=>{if(y<this.mcpToolMiddlewares.length){const _=this.mcpToolMiddlewares[y++];return _({name:t,description:"",inputSchema:{},annotations:i,execute:async()=>({})},r,{toolMeta:{name:t,annotations:i}},v)}return g()};return await v()},h=async()=>{const g=this.externalServerManager.getAllTools(),y=g.filter(_=>_.name===t&&_.isAvailable);let v;if(y.length>1&&this.mcpToolRouter)try{const _={name:t,description:y[0].description??"",serverId:y[0].serverId,inputSchema:{}},b=this.mcpToolRouter.route(_);v=y.find(T=>T.serverId===b.serverId)||y[0],f.debug(`[${s}] Router selected server: ${b.serverId}`,{strategy:b.strategy,confidence:b.confidence})}catch(_){f.warn(`[${s}] Router failed, falling back to first match`,{error:_}),v=y[0]}else v=y[0];if(f.debug(`[${s}] External MCP tool search:`,{toolName:t,externalToolsCount:g.length,foundTool:!!v,isAvailable:v?.isAvailable,serverId:v?.serverId}),v&&v.isAvailable)try{de.debug(`[${s}] Executing external MCP tool: ${t} from ${v.serverId}`);const _=await this.externalServerManager.executeTool(v.serverId,t,r,{timeout:n.timeout});return f.debug(`[${s}] External MCP tool execution successful:`,{toolName:t,serverId:v.serverId,resultType:typeof _}),_}catch(_){throw f.error(`[${s}] External MCP tool execution failed:`,{toolName:t,serverId:v.serverId,error:_ instanceof Error?_.message:String(_)}),ke.toolExecutionFailed(t,_ instanceof Error?_:new Error(String(_)),v.serverId)}try{const _=this.toolExecutionContext||{},b=n.authContext||{},T={..._,...b,hitlState:o};f.debug("[Using merged context for unified registry tool:",{toolName:t,storedContextKeys:Object.keys(_),finalContextKeys:Object.keys(T)});const k=await this.toolRegistry.executeTool(t,r,T);if(k&&typeof k=="object"&&"success"in k&&k.success===!1){const x=k.error||"Tool execution failed",I=new Error(x);this.emitter.listenerCount("error")>0&&this.emitter.emit("error",I)}return k}catch(_){const b=_ instanceof Error?_:new Error(String(_));if(this.emitter.listenerCount("error")>0&&this.emitter.emit("error",b),_ instanceof Error&&_.message.includes("not found")){const T=await this.getAllAvailableTools();throw ke.toolNotFound(t,T.map(k=>k.name))}throw ke.toolExecutionFailed(t,_ instanceof Error?_:new Error(String(_)))}};try{const g=await m(h);return a&&l&&g!==void 0&&(l.cacheResult(t,c,g),f.debug(`[${s}] Cached result for tool: ${t}`)),g}catch(g){const y=i?{name:t,description:"",annotations:i,execute:async()=>({})}:void 0;if(y&&FY(y)&&g instanceof Error&&Tz(g)){f.debug(`[${s}] Tool ${t} is safe to retry, attempting once more`);try{const v=await m(h);return a&&l&&v!==void 0&&l.cacheResult(t,c,v),v}catch{}}throw g}}getToolAnnotationsForExecution(t){if(this.toolCache?.tools){const r=this.toolCache.tools.find(n=>n.name===t);if(r?.annotations)return r.annotations}if(this.mcpEnhancementsConfig?.annotations?.autoInfer!==!1)return mp({name:t,description:""})}invalidateToolCache(){this.toolCache=null,f.debug("Tool cache invalidated")}async getAllAvailableTools(){if(this.toolCache&&Date.now()-this.toolCache.timestamp<this.toolCacheDuration)return f.debug("Returning available tools from cache"),this.toolCache.tools;const t=`get-all-tools-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,r=Date.now(),n=process.hrtime.bigint();f.debug("[NeuroLink] \u{1F6E0}\uFE0F LOG_POINT_A001_GET_ALL_TOOLS_START",{logPoint:"A001_GET_ALL_TOOLS_START",getAllToolsId:t,timestamp:new Date().toISOString(),getAllToolsStartTime:r,getAllToolsHrTimeStart:n.toString(),toolRegistryState:{hasToolRegistry:!!this.toolRegistry,toolRegistrySize:0,toolRegistryType:this.toolRegistry?.constructor?.name||"NOT_SET",hasExternalServerManager:!!this.externalServerManager,externalServerManagerType:this.externalServerManager?.constructor?.name||"NOT_SET"},mcpState:{mcpInitialized:this.mcpInitialized,hasProviderRegistry:!!po,providerRegistrySize:0},message:"Starting comprehensive tool discovery across all sources"});const{MemoryManager:o}=await Promise.resolve().then(()=>(Dx(),dw)),s=o.getMemoryUsageMB();try{const i=new Map,a=await this.toolRegistry.listTools();for(const y of a)if(!i.has(y.name)){const v=ZP(y,{serverId:y.serverId==="direct"?"neurolink-direct":y.serverId});i.set(y.name,v)}const l=this.toolRegistry.getToolsByCategory(Ia({isCustomTool:!0}));for(const y of l)if(!i.has(y.name)){const v=ZP(y,{description:"Custom tool",serverId:`custom-tool-${y.name}`,category:Ia({isCustomTool:!0,serverId:y.serverId}),inputSchema:{}});i.set(y.name,v)}const c=this.toolRegistry.getToolsByCategory("in-memory");for(const y of c)if(!i.has(y.name)){const v=ZP(y,{description:"In-memory MCP tool",serverId:"unknown",category:"in-memory",inputSchema:{}});i.set(y.name,v)}const u=this.externalServerManager.getAllTools();for(const y of u)if(!i.has(y.name)){const v=ZP(y,{category:Ia({existingCategory:typeof y.metadata?.category=="string"?y.metadata.category:void 0,isExternal:!0,serverId:y.serverId}),inputSchema:{}});i.set(y.name,v)}const d=Array.from(i.values());de.debug("Tool discovery results",{mcpTools:a.length,customTools:l.length,inMemoryTools:c.length,externalMCPTools:u.length,total:d.length});const h=o.getMemoryUsageMB().heapUsed-s.heapUsed;if(h>cm.LOW_USAGE_MB&&(de.debug(`\u{1F50D} Tool listing used ${h}MB memory (large tool registry detected)`),d.length>mme.LARGE_TOOL_COLLECTION&&de.debug("\u{1F4A1} Tool collection optimized for large sets. Memory usage reduced through efficient object reuse.")),this.mcpEnhancementsConfig?.annotations?.autoInfer!==!1)for(const y of d)y.annotations||(y.annotations=mp({name:y.name,description:y.description||""}));const g=d.sort((y,v)=>y.name<v.name?-1:y.name>v.name?1:0);return this.toolCache={tools:g,timestamp:Date.now()},g}catch(i){return de.error("Failed to list available tools",{error:i}),[]}}async getProviderStatus(t){const{MemoryManager:r}=await Promise.resolve().then(()=>(Dx(),dw)),n=r.getMemoryUsageMB();t?.quiet||de.debug("\u{1F50D} DEBUG: Initializing MCP for provider status..."),await this.initializeMCP(),t?.quiet||de.debug("\u{1F50D} DEBUG: MCP initialized:",this.mcpInitialized);const{AIProviderFactory:o}=await Promise.resolve().then(()=>(Gl(),iA)),{hasProviderEnvVars:s}=await Promise.resolve().then(()=>(Th(),Px)),i=zr.getAllDescriptors().map(m=>m.name),a=IC(Va.DEFAULT_CONCURRENCY_LIMIT),l=i.map(m=>a(async()=>{const h=Date.now();try{if(!await this.hasProviderEnvVars(m)&&m!=="ollama")return{provider:m,status:"not-configured",configured:!1,authenticated:!1,error:"Missing required environment variables",responseTime:Date.now()-h};if(m==="ollama")try{const b=await fetch("http://localhost:11434/api/tags",{method:"GET",signal:AbortSignal.timeout(rc.AUTH_MS)});if(!b.ok)throw new Error("Ollama service not responding");const T=await b.json(),k=T?.models;if(!Array.isArray(k))throw f.warn("Ollama API returned invalid models format in testProvider",{responseData:T,modelsType:typeof k}),new Error("Invalid models format from Ollama API");const x=k.filter(I=>I&&typeof I=="object"&&typeof I.name=="string");return x.length>0?{provider:m,status:"working",configured:!0,authenticated:!0,responseTime:Date.now()-h,model:x[0].name}:{provider:m,status:"failed",configured:!0,authenticated:!1,error:"Ollama service running but no models installed",responseTime:Date.now()-h}}catch(b){return{provider:m,status:"failed",configured:!1,authenticated:!1,error:b instanceof Error?b.message:"Ollama service not running",responseTime:Date.now()-h}}const y=5e3,v=this.testProviderConnection(m),_=new Promise((b,T)=>{setTimeout(()=>T(new Error("Provider test timeout (5s)")),y)});return await Promise.race([v,_]),{provider:m,status:"working",configured:!0,authenticated:!0,responseTime:Date.now()-h}}catch(g){const y=g instanceof Error?g.message:String(g);return{provider:m,status:"failed",configured:!0,authenticated:!1,error:y,responseTime:Date.now()-h}}})),c=await Promise.all(l),d=r.getMemoryUsageMB().heapUsed-n.heapUsed;return!t?.quiet&&d>20&&de.debug(`\u{1F50D} Memory usage: +${d}MB (consider cleanup for large operations)`),d>50&&r.forceGC(),c}async testProvider(t){try{return await this.testProviderConnection(t),!0}catch{return!1}}async testProviderConnection(t){const{AIProviderFactory:r}=await Promise.resolve().then(()=>(Gl(),iA));await(await r.createProvider(t,null)).generate({prompt:"test",maxTokens:1,disableTools:!0})}async getBestProvider(t){const{getBestProvider:r}=await Promise.resolve().then(()=>(Th(),Px));return r(t)}async getAvailableProviders(){const{getAvailableProviders:t}=await Promise.resolve().then(()=>(Th(),Px));return t()}async isValidProvider(t){const{isValidProvider:r}=await Promise.resolve().then(()=>(Th(),Px));return r(t)}async getMCPStatus(){try{await this.initializeMCP();const t=await this.toolRegistry.listTools(),r=this.externalServerManager.getStatistics(),n=this.externalServerManager.listServers(),o=this.getInMemoryServerInfos(),s=this.toolRegistry.getBuiltInServerInfos(),i=this.getAutoDiscoveredServerInfos(),a=n.length+o.length+s.length+i.length,l=r.connectedServers+o.length+s.length,c=t.length+r.totalTools;return{mcpInitialized:this.mcpInitialized,totalServers:a,availableServers:l,autoDiscoveredCount:i.length,totalTools:c,autoDiscoveredServers:i,customToolsCount:this.toolRegistry.getToolsByCategory(Ia({isCustomTool:!0})).length,inMemoryServersCount:o.length,externalMCPServersCount:n.length,externalMCPConnectedCount:r.connectedServers,externalMCPFailedCount:r.failedServers,externalMCPServers:n}}catch(t){return{mcpInitialized:!1,totalServers:0,availableServers:0,autoDiscoveredCount:0,totalTools:0,autoDiscoveredServers:[],customToolsCount:this.toolRegistry.getToolsByCategory(Ia({isCustomTool:!0})).length,inMemoryServersCount:0,externalMCPServersCount:0,externalMCPConnectedCount:0,externalMCPFailedCount:0,externalMCPServers:[],error:t instanceof Error?t.message:String(t)}}}async listMCPServers(){return[...this.externalServerManager.listServers(),...this.getInMemoryServerInfos(),...this.toolRegistry.getBuiltInServerInfos(),...this.getAutoDiscoveredServerInfos()]}async testMCPServer(t){try{if(t==="neurolink-direct")return(await this.toolRegistry.listTools()).length>0;const r=this.getInMemoryServers();if(r.has(t)){const o=r.get(t);return!!(o?.tools&&o.tools.length>0)}const n=this.externalServerManager.getServer(t);return n?n.status==="connected"&&n.client!==null:!1}catch(r){return de.error(`[NeuroLink] Error testing MCP server ${t}:`,r),!1}}async hasProviderEnvVars(t){const{ProviderHealthChecker:r}=await Promise.resolve().then(()=>(gy(),iw));try{const n=await r.checkProviderHealth(t,{includeConnectivityTest:!1,cacheResults:!1});return n.isConfigured&&n.hasApiKey}catch(n){return f.warn(`Provider env var check failed for ${t}`,{error:n instanceof Error?n.message:String(n)}),!1}}async checkProviderHealth(t,r={}){const{ProviderHealthChecker:n}=await Promise.resolve().then(()=>(gy(),iw)),o=await n.checkProviderHealth(t,r);return{provider:o.provider,isHealthy:o.isHealthy,isConfigured:o.isConfigured,hasApiKey:o.hasApiKey,lastChecked:o.lastChecked,error:o.error,warning:o.warning,responseTime:o.responseTime,configurationIssues:o.configurationIssues,recommendations:o.recommendations}}async checkAllProvidersHealth(t={}){const{ProviderHealthChecker:r}=await Promise.resolve().then(()=>(gy(),iw));return(await r.checkAllProvidersHealth(t)).map(o=>({provider:o.provider,isHealthy:o.isHealthy,isConfigured:o.isConfigured,hasApiKey:o.hasApiKey,lastChecked:o.lastChecked,error:o.error,warning:o.warning,responseTime:o.responseTime,configurationIssues:o.configurationIssues,recommendations:o.recommendations}))}async getProviderHealthSummary(){const{ProviderHealthChecker:t}=await Promise.resolve().then(()=>(gy(),iw)),r=await t.checkAllProvidersHealth({cacheResults:!0,includeConnectivityTest:!1}),n=t.getHealthSummary(r),o=[];return n.healthy===0?o.push("No providers are healthy. Check your environment configuration."):n.healthy<2&&o.push("Consider configuring additional providers for better reliability."),n.hasIssues>0&&o.push("Some providers have configuration issues. Run checkAllProvidersHealth() for details."),{...n,recommendations:o}}async clearProviderHealthCache(t){const{ProviderHealthChecker:r}=await Promise.resolve().then(()=>(gy(),iw));r.clearHealthCache(t)}getToolExecutionMetrics(){const t={};for(const[r,n]of this.toolExecutionMetrics.entries())t[r]={...n,errorCategories:{...n.errorCategories},successRate:n.totalExecutions>0?n.successfulExecutions/n.totalExecutions:0};return t}setModelAliasConfig(t){this.modelAliasConfig=t,f.info(`[ModelAlias] Configured ${Object.keys(t.aliases).length} model aliases`)}getToolCircuitBreakerStatus(){const t={};for(const[r,n]of this.toolCircuitBreakers.entries())t[r]={state:n.getState(),failureCount:n.getFailureCount(),isHealthy:n.getState()==="closed"};return t}resetToolCircuitBreaker(t){this.toolCircuitBreakers.has(t)&&(this.toolCircuitBreakers.set(t,new j1(jI.FAILURE_THRESHOLD,V3)),de.info(`Circuit breaker reset for tool: ${t}`))}clearToolExecutionMetrics(){this.toolExecutionMetrics.clear(),de.info("All tool execution metrics cleared")}async getToolHealthReport(){const t={};let r=0;const n=await this.toolRegistry.listTools(),o=new Set(n.map(i=>i.name)),s=new Map;for(const i of n)s.has(i.name)||s.set(i.name,i.serverId||"unknown");for(const i of o){const a=this.toolExecutionMetrics.get(i),l=`${s.get(i)||"unknown"}.${i}`,c=this.toolCircuitBreakers.get(l),u=a&&a.totalExecutions>0?a.successfulExecutions/a.totalExecutions:0,d=(!c||c.getState()==="closed")&&u>=.8;d&&r++;const m=[],h=[];if(c&&c.getState()==="open"&&(m.push("Circuit breaker is open due to repeated failures"),h.push("Check tool implementation and fix underlying issues")),u<.8&&a&&a.totalExecutions>0&&(m.push(`Low success rate: ${(u*100).toFixed(1)}%`),h.push("Review error logs and improve tool reliability")),a&&a.averageExecutionTime>1e4&&(m.push("High average execution time"),h.push("Optimize tool performance or increase timeout")),a&&a.errorCategories){const g=a.errorCategories;g.timeout>0&&(m.push(`Timeout errors: ${g.timeout}`),h.push("Consider increasing the tool timeout configuration")),g.validation>0&&(m.push(`Validation errors: ${g.validation}`),h.push("Review input schemas and parameter validation")),g.network>0&&(m.push(`Network errors: ${g.network}`),h.push("Check network connectivity and endpoint availability"))}t[i]={name:i,isHealthy:d,metrics:{totalExecutions:a?.totalExecutions||0,successRate:u,averageExecutionTime:a?.averageExecutionTime||0,lastExecutionTime:a?.lastExecutionTime||0,errorCategories:a?.errorCategories?{...a.errorCategories}:{}},circuitBreaker:{state:c?.getState()||"closed",failureCount:c?.getFailureCount()||0},issues:m,recommendations:h}}return{totalTools:o.size,healthyTools:r,unhealthyTools:o.size-r,tools:t}}async ensureConversationMemoryInitialized(){try{const t=`manual-init-${Date.now()}`;return await this.initializeConversationMemoryForGeneration(t,Date.now(),process.hrtime.bigint()),!!this.conversationMemory}catch(t){return f.error("Failed to initialize conversation memory",{error:t instanceof Error?t.message:String(t)}),!1}}async getConversationStats(){const t=`stats-init-${Date.now()}`;if(await this.initializeConversationMemoryForGeneration(t,Date.now(),process.hrtime.bigint()),!this.conversationMemory)throw new Ne({code:Xe.MISSING_CONFIGURATION,message:"Conversation memory is not enabled",category:"validation",severity:"high",retriable:!1});return await this.conversationMemory.getStats()}async getConversationHistory(t){const r=`history-init-${Date.now()}`;if(await this.initializeConversationMemoryForGeneration(r,Date.now(),process.hrtime.bigint()),!this.conversationMemory)throw new Ne({code:Xe.MISSING_CONFIGURATION,message:"Conversation memory is not enabled",category:"validation",severity:"high",retriable:!1});if(!t||typeof t!="string")throw new Ne({code:Xe.INVALID_PARAMETERS,message:"Session ID must be a non-empty string",category:"validation",severity:"medium",retriable:!1,context:{sessionId:t}});try{const n=await this.conversationMemory.buildContextMessages(t);return f.debug("Retrieved conversation history",{sessionId:t,messageCount:n.length,turnCount:n.length/2}),n}catch(n){return f.error("Failed to retrieve conversation history",{sessionId:t,error:n instanceof Error?n.message:String(n)}),[]}}async clearConversationSession(t){const r=`clear-session-init-${Date.now()}`;if(await this.initializeConversationMemoryForGeneration(r,Date.now(),process.hrtime.bigint()),!this.conversationMemory)throw new Ne({code:Xe.MISSING_CONFIGURATION,message:"Conversation memory is not enabled",category:"validation",severity:"high",retriable:!1});return this.lastCompactionMessageCount.delete(t),await this.conversationMemory.clearSession(t)}async clearAllConversations(){const t=`clear-all-init-${Date.now()}`;if(await this.initializeConversationMemoryForGeneration(t,Date.now(),process.hrtime.bigint()),!this.conversationMemory)throw new Ne({code:Xe.MISSING_CONFIGURATION,message:"Conversation memory is not enabled",category:"validation",severity:"high",retriable:!1});this.lastCompactionMessageCount.clear(),await this.conversationMemory.clearAllSessions()}async listSessions(t){const r=`list-sessions-init-${Date.now()}`;if(await this.initializeConversationMemoryForGeneration(r,Date.now(),process.hrtime.bigint()),!this.conversationMemory)throw new Error("Conversation memory is not enabled");if(!this.conversationMemory.listSessions)return f.warn("listSessions not available on current memory manager"),[];const n=3e4;try{const o=await Ze(this.conversationMemory.listSessions(t),n,new Error("listSessions operation timed out after 30s"));return f.debug("Listed conversation sessions",{userId:t,sessionCount:o.length}),o}catch(o){return f.error("Failed to list conversation sessions",{userId:t,error:o instanceof Error?o.message:String(o)}),[]}}async exportSession(t,r={}){const n=`export-session-init-${Date.now()}`;if(await this.initializeConversationMemoryForGeneration(n,Date.now(),process.hrtime.bigint()),!this.conversationMemory)throw new Error("Conversation memory is not enabled");if(!t||typeof t!="string")throw new Error("Session ID must be a non-empty string");const o=3e4;try{const s=await Ze(this.conversationMemory.buildContextMessages(t),o,new Error("buildContextMessages operation timed out after 30s"));if(s.length===0)return f.debug("No messages found for session export",{sessionId:t}),null;const i=this.conversationMemory.getSession(t),a=await Ze(i instanceof Promise?i:Promise.resolve(i),o,new Error("getSession operation timed out after 30s")),l=new Date().toISOString(),c={sessionId:t,title:t,userId:a?.userId,createdAt:a?.createdAt?new Date(a.createdAt).toISOString():l,updatedAt:a?.lastActivity?new Date(a.lastActivity).toISOString():l,messages:s};return r.includeMetadata&&(c.exportMetadata={exportedAt:l,exportFormat:r.format||"json"}),f.debug("Exported conversation session",{sessionId:t,messageCount:s.length}),c}catch(s){return f.error("Failed to export conversation session",{sessionId:t,error:s instanceof Error?s.message:String(s)}),null}}async exportAllSessions(t,r={}){const n=`export-all-init-${Date.now()}`;if(await this.initializeConversationMemoryForGeneration(n,Date.now(),process.hrtime.bigint()),!this.conversationMemory)throw new Error("Conversation memory is not enabled");const o=3e4,s=6e4;try{const i=await Ze(this.listSessions(t),o,new Error("listSessions operation timed out after 30s")),a=[];for(const l of i){const c=await Ze(this.exportSession(l.id,r),s,new Error(`exportSession operation timed out after 60s for session ${l.id}`));c&&a.push(c)}return f.debug("Exported all conversation sessions",{userId:t,sessionCount:a.length}),a}catch(i){return f.error("Failed to export all conversation sessions",{userId:t,error:i instanceof Error?i.message:String(i)}),[]}}async storeToolExecutions(t,r,n,o,s){const i=n&&n.length>0||o&&o.length>0;if(!i){f.debug("Tool execution storage skipped",{hasToolData:i,toolCallsCount:n?.length||0,toolResultsCount:o?.length||0});return}const a=this.conversationMemory;if(!a?.storeToolExecution){f.debug("Tool execution storage not supported by this memory backend");return}try{await a.storeToolExecution(t,r,n,o,s)}catch(l){f.warn("Failed to store tool executions",{sessionId:t,userId:r,error:l instanceof Error?l.message:String(l)})}}isToolExecutionStorageAvailable(){return typeof this.conversationMemory?.storeToolExecution=="function"}async getSessionMessages(t,r){const n=`get-msgs-init-${Date.now()}`;if(await this.initializeConversationMemoryForGeneration(n,Date.now(),process.hrtime.bigint()),!this.conversationMemory)throw new Ne({code:Xe.MISSING_CONFIGURATION,message:"Conversation memory is not enabled",category:"validation",severity:"high",retriable:!1});if(!t||typeof t!="string")throw new Ne({code:Xe.INVALID_PARAMETERS,message:"Session ID must be a non-empty string",category:"validation",severity:"medium",retriable:!1,context:{sessionId:t}});return await this.conversationMemory.getSessionMessages(t,r)}async setSessionMessages(t,r,n){const o=`set-msgs-init-${Date.now()}`;if(await this.initializeConversationMemoryForGeneration(o,Date.now(),process.hrtime.bigint()),!this.conversationMemory)throw new Ne({code:Xe.MISSING_CONFIGURATION,message:"Conversation memory is not enabled",category:"validation",severity:"high",retriable:!1});if(!t||typeof t!="string")throw new Ne({code:Xe.INVALID_PARAMETERS,message:"Session ID must be a non-empty string",category:"validation",severity:"medium",retriable:!1,context:{sessionId:t}});await this.conversationMemory.setSessionMessages(t,r,n)}async modifyLastAssistantMessage(t,r,n){const o=await this.getSessionMessages(t,n);for(let s=o.length-1;s>=0;s--)if(o[s].role==="assistant")return o[s]={...o[s],content:r(o[s].content)},await this.setSessionMessages(t,o,n),!0;return!1}async addExternalMCPServer(t,r){this.invalidateToolCache();try{de.info(`[NeuroLink] Adding external MCP server: ${t}`,{command:r.command,transport:r.transport});const n=await this.externalServerManager.addServer(t,r);if(n.success){if(de.info(`[NeuroLink] External MCP server added successfully: ${t}`,{toolsDiscovered:n.metadata?.toolsDiscovered||0,duration:n.duration}),this.mcpEnhancementsConfig?.router?.enabled!==!1){const o=this.externalServerManager.listServers();if(o.length>=2&&!this.mcpToolRouter){this.mcpToolRouter=new o2({strategy:this.mcpEnhancementsConfig?.router?.strategy??"least-loaded",enableAffinity:this.mcpEnhancementsConfig?.router?.enableAffinity??!1});for(const s of o)this.mcpToolRouter.registerServer(s.id||t);f.debug("[NeuroLink] ToolRouter auto-initialized (2+ external servers)")}else this.mcpToolRouter&&this.mcpToolRouter.registerServer(t)}this.emitter.emit("externalMCP:serverAdded",{serverId:t,serverName:r.name||t,config:r,toolCount:n.metadata?.toolsDiscovered||0,timestamp:Date.now()})}else de.error(`[NeuroLink] Failed to add external MCP server: ${t}`,{error:n.error,transport:r.transport,command:r.command,url:r.url?to(r.url):void 0});return n}catch(n){throw de.error(`[NeuroLink] Error adding external MCP server: ${t}`,n),n}}async removeExternalMCPServer(t){this.invalidateToolCache();try{de.info(`[NeuroLink] Removing external MCP server: ${t}`);const r=this.externalServerManager.getServerName(t),n=await this.externalServerManager.removeServer(t);return n.success?(de.info(`[NeuroLink] External MCP server removed successfully: ${t}`),this.emitter.emit("externalMCP:serverRemoved",{serverId:t,serverName:r,timestamp:Date.now()})):n.error?.includes("not found")?de.debug(`[NeuroLink] Remove skipped \u2014 external MCP server not registered: ${t}`):de.error(`[NeuroLink] Failed to remove external MCP server: ${t}`,{error:n.error}),n}catch(r){throw de.error(`[NeuroLink] Error removing external MCP server: ${t}`,r),r}}listExternalMCPServers(){const t=this.externalServerManager.getServerStatuses(),r=this.externalServerManager.listServers();return t.map(n=>{const o=r.find(s=>s.id===n.serverId);return{serverId:n.serverId,status:n.status,toolCount:n.toolCount,uptime:n.performance.uptime,isHealthy:n.isHealthy,config:o||{}}})}getExternalMCPServer(t){return this.externalServerManager.getServer(t)}async executeExternalMCPTool(t,r,n,o){let s=r;try{s=this.resolveDirectMcpToolName(t,r),de.debug(`[NeuroLink] Executing external MCP tool: ${s} on ${t}`);const i=this.getToolAnnotationsForExecution(s),a=!!this.mcpToolResultCache&&!this._disableToolCacheForCurrentRequest&&!i?.destructiveHint,l={__serverId:t,__args:n,...this.toolExecutionContext?{__ctx:this.toolExecutionContext}:{}},c=this._generationTurnActive?this.toolCacheRepeatKey(s,l):void 0,u=c!==void 0&&this._toolCacheKeysServedThisRequest.has(c);if(c!==void 0&&this._toolCacheKeysServedThisRequest.add(c),a&&this.mcpToolResultCache&&!u){const g=this.mcpToolResultCache.getCachedResult(s,l);if(g!==void 0)return de.debug(`[NeuroLink] Tool result cache HIT: ${s} on ${t}`),g}const d=await this.externalServerManager.executeTool(t,s,n,o),m=d&&typeof d=="object"?d:void 0,h=!!(m&&"isError"in m&&m.isError===!0||m&&"success"in m&&m.success===!1);return a&&this.mcpToolResultCache&&!h&&d!==void 0&&this.mcpToolResultCache.cacheResult(s,l,d),de.debug(`[NeuroLink] External MCP tool ${h?"returned error":"executed successfully"}: ${s}`),d}catch(i){throw de.error(`[NeuroLink] External MCP tool execution failed: ${s}`,i),i}}resolveDirectMcpToolName(t,r){const n=this.getExternalMCPServer(t);if(!n||n.status!=="connected"||!n.client)return r;const o=this.getExternalMCPServerTools(t).map(i=>i.name);if(o.includes(r))return r;const s=X9(r,o);if(!s)throw new eW(r,t,E9e(r,o));return He.mcp.startActiveSpan("neurolink.mcp.toolNameRepair",{attributes:{"mcp.server_id":t,"mcp.tool_name.requested":r,"mcp.tool_name.resolved":s.name,"mcp.tool_name.repair_strategy":s.strategy,...s.score!==void 0?{"mcp.tool_name.repair_score":s.score}:{}}},i=>i.end()),de.info(`[NeuroLink] Repaired external MCP tool name at direct execution boundary: "${r}" \u2192 "${s.name}" (${s.strategy}) on server '${t}'`),s.name}getExternalMCPTools(){return this.externalServerManager.getAllTools()}getExternalMCPServerTools(t){return this.externalServerManager.getServerTools(t)}async testExternalMCPConnection(t){try{const{MCPClientFactory:r}=await Ze(Promise.resolve().then(()=>(ire(),JNt)),1e4),n=await r.testConnection(t,1e4);return{success:n.success,error:n.error,toolCount:n.capabilities?1:0}}catch(r){return{success:!1,error:r instanceof Error?r.message:String(r)}}}getExternalMCPStatistics(){return this.externalServerManager.getStatistics()}async shutdownExternalMCPServers(){try{de.info("[NeuroLink] Shutting down all external MCP servers..."),this.unregisterAllExternalMCPToolsFromRegistry(),await this.externalServerManager.shutdown(),de.info("[NeuroLink] All external MCP servers shut down successfully")}catch(t){throw de.error("[NeuroLink] Error shutting down external MCP servers:",t),t}}async getElicitationManager(){return(await Ze(Promise.resolve().then(()=>(FBt(),$Bt)),1e4)).globalElicitationManager}async registerElicitationHandler(t){(await this.getElicitationManager()).registerHandler(t)}async getMultiServerManager(){return(await Ze(Promise.resolve().then(()=>(tte(),fDt)),1e4)).globalMultiServerManager}async getEnhancedToolDiscovery(){const t=await Ze(Promise.resolve().then(()=>(rte(),gDt)),1e4);return new t.EnhancedToolDiscovery(this.toolRegistry)}async getMCPRegistryClient(){return(await Ze(Promise.resolve().then(()=>(jBt(),UBt)),1e4)).globalMCPRegistryClient}async exposeAgentAsTool(t,r){return(await Ze(Promise.resolve().then(()=>(Lse(),Ose)),1e4)).exposeAgentAsTool(t,r)}async exposeWorkflowAsTool(t,r){return(await Ze(Promise.resolve().then(()=>(Lse(),Ose)),1e4)).exposeWorkflowAsTool(t,r)}async getToolIntegrationManager(){return(await Ze(Promise.resolve().then(()=>(JBt(),HBt)),1e4)).globalToolIntegrationManager}async convertToolsToMCPFormat(t,r={}){const n=await Ze(Promise.resolve().then(()=>(eO(),UY)),1e4),o=t.map(s=>({...s,execute:s.execute??(async()=>({success:!1,error:"No execute function provided"}))}));return n.batchConvertToMCP(o,r)}async convertToolsFromMCPFormat(t,r={}){return(await Ze(Promise.resolve().then(()=>(eO(),UY)),1e4)).batchConvertToNeuroLink(t,r)}async getToolAnnotations(t){const{inferAnnotations:r,mergeAnnotations:n,getAnnotationSummary:o}=await Ze(Promise.resolve().then(()=>(PC(),aTt)),1e4),s=this.toolRegistry.getToolInfo(t);if(!s)return null;const i=s.tool.annotations,a=r({name:s.tool.name,description:s.tool.description??""}),l=n(a,i);return{annotations:l,summary:o(l)}}convertExternalMCPToolsToAISDKFormat(){const t=this.externalServerManager.getAllTools(),r={};for(const n of t)if(n.isAvailable){const o={description:n.description,execute:async s=>{try{de.debug(`[NeuroLink] Executing external MCP tool via AI SDK: ${n.name}`,{params:s});const i=await this.externalServerManager.executeTool(n.serverId,n.name,s,{timeout:3e4});return de.debug(`[NeuroLink] External MCP tool execution result: ${n.name}`,{success:!!i,hasData:!!(i&&typeof i=="object"&&"content"in i)}),i}catch(i){throw de.error(`[NeuroLink] External MCP tool execution failed: ${n.name}`,i),i}}};r[n.name]=o,de.debug(`[NeuroLink] Converted external MCP tool to AI SDK format: ${n.name} from server ${n.serverId}`)}return de.info(`[NeuroLink] Converted ${Object.keys(r).length} external MCP tools to AI SDK format`),r}convertJSONSchemaToAISDKFormat(t){}unregisterExternalMCPToolsFromRegistry(t){try{const r=this.externalServerManager.getServerTools(t);for(const n of r)this.toolRegistry.removeTool(n.name),de.debug(`[NeuroLink] Unregistered external MCP tool from main registry: ${n.name}`)}catch(r){de.error(`[NeuroLink] Failed to unregister external MCP tools from registry for server ${t}:`,r)}}unregisterExternalMCPToolFromRegistry(t){try{this.toolRegistry.removeTool(t),de.debug(`[NeuroLink] Unregistered external MCP tool from main registry: ${t}`)}catch(r){de.error(`[NeuroLink] Failed to unregister external MCP tool ${t} from registry:`,r)}}async lazyInitializeConversationMemory(t,r,n){try{const{initializeConversationMemory:o}=await LWr().then(()=>XBt),s=await o(this.conversationMemoryConfig);this.conversationMemory=s,this.conversationMemoryNeedsInit=!1}catch(o){throw f.error("[NeuroLink] \u274C LOG_POINT_G005_MEMORY_LAZY_INIT_ERROR",{logPoint:"G005_MEMORY_LAZY_INIT_ERROR",generateInternalId:t,timestamp:new Date().toISOString(),elapsedMs:Date.now()-r,elapsedNs:(process.hrtime.bigint()-n).toString(),error:o instanceof Error?o.message:String(o),errorName:o instanceof Error?o.name:"UnknownError",errorStack:o instanceof Error?o.stack:void 0,message:"Lazy conversation memory initialization failed"}),o}}unregisterAllExternalMCPToolsFromRegistry(){try{const t=this.externalServerManager.getAllTools();for(const r of t)this.toolRegistry.removeTool(r.name);de.debug(`[NeuroLink] Unregistered ${t.length} external MCP tools from main registry`)}catch(t){de.error("[NeuroLink] Failed to unregister all external MCP tools from registry:",t)}}async createEvaluationPipeline(t){const{EvaluationPipeline:r,getPreset:n}=await Ze(Promise.resolve().then(()=>(mS(),pS)),1e4,ke.evaluationTimeout("evaluation module load",1e4));let o;typeof t=="string"?o=n(t):o=t;const s=new r(o);return await Ze(s.initialize(),3e4,ke.evaluationTimeout("pipeline initialization",3e4)),f.debug(`[NeuroLink] Created evaluation pipeline: ${o.name??"custom"}`),s}async evaluate(t,r){const{EvaluationPipeline:n,getPreset:o}=await Ze(Promise.resolve().then(()=>(mS(),pS)),1e4,ke.evaluationTimeout("evaluation module load",1e4));let s;if(r?.pipeline&&r?.scorers)throw new Error("Cannot specify both 'pipeline' and 'scorers' options. Use one or the other.");if(r?.scorers&&r.scorers.length===0)throw new Error("The 'scorers' array must not be empty. Provide at least one scorer ID or omit the option to use the default 'quality' preset.");r?.pipeline?s={...o(r.pipeline)}:r?.scorers&&r.scorers.length>0?s={name:"SDK Evaluation",description:"Evaluation from NeuroLink SDK",scorers:r.scorers.map(c=>({id:c})),executionMode:r.executionMode??"parallel",passThreshold:r.passThreshold??.7}:s=o("quality"),r?.passThreshold!==void 0&&(s.passThreshold=r.passThreshold),r?.executionMode!==void 0&&(s.executionMode=r.executionMode);const i=new n(s);await Ze(i.initialize(),3e4,ke.evaluationTimeout("pipeline initialization",3e4));const a=r?.timeoutMs??6e4,l=await Ze(i.execute(t,{correlationId:r?.correlationId}),a,ke.evaluationTimeout("pipeline execution",a));return f.debug("[NeuroLink] Evaluation completed",{pipeline:s.name,overallScore:l.overallScore,passed:l.passed,scorerCount:l.scores.length}),l}async score(t,r,n){const{ScorerRegistry:o}=await Ze(Promise.resolve().then(()=>(aV(),iV)),1e4,ke.evaluationTimeout("scorer module load",1e4));await Ze(o.registerBuiltInScorers(),3e4,ke.evaluationTimeout("scorer bootstrap",3e4));const s=await Ze(o.getScorer(t,n),3e4,ke.evaluationTimeout(`scorer load: ${t}`,3e4));if(!s)throw ke.scorerNotFound(t);const i=s.validateInput(r);if(!i.valid)throw ke.evaluationValidationFailed(t,i.errors);const a=await Ze(s.score(r),6e4,ke.evaluationTimeout("scorer execution",6e4));return f.debug("[NeuroLink] Scoring completed",{scorerId:t,score:a.score,passed:a.passed,computeTime:a.computeTime}),a}async getAvailableScorers(t){const{ScorerRegistry:r}=await Ze(Promise.resolve().then(()=>(aV(),iV)),1e4,ke.evaluationTimeout("scorer module load",1e4));await Ze(r.registerBuiltInScorers(),3e4,ke.evaluationTimeout("scorer bootstrap",3e4));let n=r.list();return t?.category&&(n=n.filter(o=>o.category===t.category)),t?.type&&(n=n.filter(o=>o.type===t.type)),n}async getEvaluationPresets(){const{getPresetNames:t}=await Ze(Promise.resolve().then(()=>(mS(),pS)),1e4,ke.evaluationTimeout("evaluation module load",1e4));return t()}async getEvaluationPreset(t){const{getPreset:r}=await Ze(Promise.resolve().then(()=>(mS(),pS)),1e4,ke.evaluationTimeout("evaluation module load",1e4));return r(t)}async createAgent(t){const{Agent:r}=await Promise.resolve().then(()=>(jse(),QBt));return f.debug("[NeuroLink] Creating agent",{id:t.id,name:t.name,tools:t.tools?.length||0}),new r(t,this)}async createNetwork(t){const{AgentNetwork:r}=await Promise.resolve().then(()=>(tzt(),ezt));return f.debug("[NeuroLink] Creating agent network",{name:t.name,agentCount:t.agents.length,workflowCount:t.workflows?.length||0,toolCount:t.tools?.length||0}),new r(t,this)}createWorkerInstance(t){const r=t?.logTag??"worker",n=this.emitter,o=t?.config??{},s={...this.credentials?{credentials:this.credentials}:{},...o,conversationMemory:{enabled:!1},enableOrchestration:!1,observability:{...this.observabilityConfig??{},langfuse:{...this.observabilityConfig?.langfuse??{},autoDetectExternalProvider:!0,skipLangfuseSpanProcessor:!0}},...t?.shareToolRegistry!==!1&&{toolRegistry:this.toolRegistry}},i=new a3(s);if(t?.shareToolRegistry!==!1)for(const a of this.uncacheableTools)i.uncacheableTools.add(a);if(f.setEventEmitter(n),t?.onLog){const a=t.onLog,l=u=>{try{const d=u??{};a({tag:r,level:String(d.level??"info"),message:String(d.message??""),timestamp:typeof d.timestamp=="number"?d.timestamp:Date.now(),data:d.data})}catch{}};n.on("log-event",l);const c=i.dispose.bind(i);i.dispose=async()=>{n.off("log-event",l),await c()}}return f.debug("[NeuroLink] Created worker instance",{tag:r,sharedToolRegistry:t?.shareToolRegistry!==!1}),i}async runIsolatedAgent(t,r,n){const{runIsolatedAgent:o}=await Promise.resolve().then(()=>(bx(),c2));return o(this,t,r,n)}async continueAgent(t,r){const{continueIsolatedAgent:n}=await Promise.resolve().then(()=>(bx(),c2));return n(this,t,r)}async stopAgent(t){const{stopIsolatedAgent:r}=await Promise.resolve().then(()=>(bx(),c2));return r(this,t)}async registerAgentTool(t,r){const{registerAgentTool:n}=await Promise.resolve().then(()=>(Ex(),m2)),o=n(this,t,r);return this.hasAgentTools=!0,o}registerTaskTools(){if(this.hasTaskChecklistTools)return;const t=_8r(this);for(const[r,n]of Object.entries(t))this.registerTool(r,n,{cacheable:!1});this.hasTaskChecklistTools=!0,f.info(`[NeuroLink] Registered ${Object.keys(t).length} task checklist tools`)}getTaskState(t){return f8r(t??ns(this))}clearTaskState(t){return g8r(t??ns(this))}registerDelegationTools(t){if(F8r(this,t),this.hasBackgroundDelegationTools)return;const r=K8r(this);for(const[n,o]of Object.entries(r))this.registerTool(n,o,{cacheable:!1});this.hasBackgroundDelegationTools=!0,f.info(`[NeuroLink] Registered ${Object.keys(r).length} background delegation tools`)}async spawnDelegate(t){return GFt(this,t)}async collectDelegates(t){return VFt(this,t)}async cancelDelegates(t){return Vne(this,t)}getArtifactStore(){return this.mcpArtifactStore||(this.mcpArtifactStore=this.createConfiguredArtifactStore()),this.registerMemoryRetrievalTools(),this.mcpArtifactStore}setArtifactStore(t){const r=this.mcpArtifactStore;r!==t&&(r&&(f.warn("[NeuroLink] Artifact store replaced \u2014 artifacts already written to the previous store will not resolve through this instance"),this.ownsArtifactStore&&r.close&&r.close().catch(n=>{f.warn("[NeuroLink] Previous artifact store close failed",{error:n instanceof Error?n.message:String(n)})})),this.mcpArtifactStore=t,this.ownsArtifactStore=!1,this.installOutputNormalizer(t),this.registerMemoryRetrievalTools())}createConfiguredArtifactStore(){const t=this.artifactsConfig?.store!==void 0,r=F2t(this.artifactsConfig,this.conversationMemoryConfig?.conversationMemory?.redisConfig);return this.ownsArtifactStore=!t,f.debug("[NeuroLink] Artifact store initialized",{backend:t?"custom":Ore(this.artifactsConfig)}),r}installOutputNormalizer(t){this.mcpOutputNormalizerConfig&&(this.externalServerManager.setOutputNormalizer(new bLt(this.mcpOutputNormalizerConfig,t)),f.debug("[NeuroLink] MCP output normalizer initialized",{...this.mcpOutputNormalizerConfig,hasArtifactStore:t!==void 0}))}async bankArtifact(t,r){return cGr(this,t,r)}async readArtifact(t,r){return uGr(this,t,r)}registerBackgroundCommandTools(t){if(e3t(this,t),this.hasBackgroundCommandTools)return;const r=sHr(this);for(const[n,o]of Object.entries(r))this.registerTool(n,o,{cacheable:!1});this.hasBackgroundCommandTools=!0,f.info(`[NeuroLink] Registered ${Object.keys(r).length} background command tools`)}setBackgroundCommandPolicy(t){e3t(this,t)}async startBackgroundCommand(t,r){return l3t(this,t,r)}getBackgroundCommandStatus(t){return c3t(this,t)}async awaitBackgroundCommand(t,r){return ioe(this,t,r)}async killBackgroundCommand(t,r){return u3t(this,t,r)}async readBackgroundCommandOutput(t,r){return E2(this,t,r)}registerGitTools(t){if(iHr(this,t),this.hasGitTools)return;const r=mHr(this);for(const[n,o]of Object.entries(r))this.registerTool(n,o,{cacheable:!1});this.hasGitTools=!0,f.info(`[NeuroLink] Registered ${Object.keys(r).length} read-only git tools`)}async runGitCommand(t,r){return E3t(this,t,r)}async executeNetwork(t,r,n){return f.debug("[NeuroLink] Executing agent network",{networkId:t.id,networkName:t.name,hasContext:!!r.context}),t.execute(r,n)}async*streamNetwork(t,r,n){f.debug("[NeuroLink] Streaming agent network",{networkId:t.id,networkName:t.name,hasContext:!!r.context}),yield*t.stream(r,n)}async createOrchestrator(t){const{NetworkOrchestrator:r}=await Promise.resolve().then(()=>(szt(),ozt));return f.debug("[NeuroLink] Creating network orchestrator",{maxConcurrentExecutions:t?.maxConcurrentExecutions,defaultMode:t?.defaultMode}),new r(this,t)}async createCoordinator(t){const{AgentCoordinator:r}=await Promise.resolve().then(()=>(azt(),izt));return f.debug("[NeuroLink] Creating agent coordinator",{strategy:t?.strategy,maxConcurrency:t?.maxConcurrency}),new r(t)}async createMessageBus(t){const{MessageBus:r}=await Promise.resolve().then(()=>(czt(),lzt));return f.debug("[NeuroLink] Creating message bus",{maxHistorySize:t?.maxHistorySize}),new r(t)}async dispose(){f.debug("[NeuroLink] Starting disposal of resources..."),this.lastCompactionMessageCount.clear();const t=[];try{try{await d3t(this),await Vne(this)}catch(r){const n=r instanceof Error?r:new Error(`Background work cleanup error: ${String(r)}`);t.push(n),f.warn("[NeuroLink] Error stopping background work:",r)}try{f.debug("[NeuroLink] Flushing and shutting down OpenTelemetry..."),await k4(),await x4(),f.debug("[NeuroLink] OpenTelemetry shutdown successfully")}catch(r){const n=r instanceof Error?r:new Error(`OpenTelemetry shutdown error: ${String(r)}`);t.push(n),f.warn("[NeuroLink] Error shutting down OpenTelemetry:",r)}if(this.externalServerManager)try{f.debug("[NeuroLink] Shutting down external MCP servers..."),await this.externalServerManager.shutdown(),f.debug("[NeuroLink] External MCP servers shutdown successfully")}catch(r){const n=r instanceof Error?r:new Error(`External server shutdown error: ${String(r)}`);t.push(n),f.warn("[NeuroLink] Error shutting down external MCP servers:",r)}if(this.ownsArtifactStore&&this.mcpArtifactStore?.close)try{await this.mcpArtifactStore.close(),f.debug("[NeuroLink] Artifact store closed")}catch(r){const n=r instanceof Error?r:new Error(`Artifact store close error: ${String(r)}`);t.push(n),f.warn("[NeuroLink] Error closing artifact store:",r)}if(this.emitter)try{f.debug("[NeuroLink] Removing all event listeners..."),this.emitter.removeAllListeners(),f.clearEventEmitter(this.emitter),f.debug("[NeuroLink] Event listeners removed successfully")}catch(r){const n=r instanceof Error?r:new Error(`Event emitter cleanup error: ${String(r)}`);t.push(n),f.warn("[NeuroLink] Error removing event listeners:",r)}if(this.toolCircuitBreakers&&this.toolCircuitBreakers.size>0)try{f.debug(`[NeuroLink] Clearing ${this.toolCircuitBreakers.size} circuit breakers...`),this.toolCircuitBreakers.clear(),f.debug("[NeuroLink] Circuit breakers cleared successfully")}catch(r){const n=r instanceof Error?r:new Error(`Circuit breaker cleanup error: ${String(r)}`);t.push(n),f.warn("[NeuroLink] Error clearing circuit breakers:",r)}try{f.debug("[NeuroLink] Clearing maps and caches..."),this.toolExecutionMetrics&&this.toolExecutionMetrics.clear(),this.activeToolExecutions&&this.activeToolExecutions.clear(),this.currentStreamToolExecutions&&(this.currentStreamToolExecutions.length=0),this.toolExecutionHistory&&(this.toolExecutionHistory.length=0),this.toolCache&&(this.toolCache.tools=[],this.toolCache.timestamp=0),this.mcpToolResultCache?.destroy(),this.mcpToolRouter?.destroy(),this.mcpToolBatcher?.destroy(),this.mcpToolResultCache=void 0,this.mcpToolRouter=void 0,this.mcpToolBatcher=void 0,this.mcpEnhancedDiscovery=void 0,this.mcpToolMiddlewares=[],f.debug("[NeuroLink] Maps and caches cleared successfully")}catch(r){const n=r instanceof Error?r:new Error(`Cache cleanup error: ${String(r)}`);t.push(n),f.warn("[NeuroLink] Error clearing caches:",r)}if(this._taskManager)try{f.debug("[NeuroLink] Shutting down TaskManager..."),await Ze(this._taskManager.shutdown(),5e3,new Error("TaskManager shutdown timed out"))}catch(r){f.warn("[NeuroLink] TaskManager shutdown error:",r)}finally{this._taskManager=void 0}try{f.debug("[NeuroLink] Resetting initialization state..."),this.mcpInitialized=!1,this.mcpInitPromise=null,this.conversationMemoryNeedsInit=!1,this.credentials=void 0,f.debug("[NeuroLink] Initialization state reset successfully")}catch(r){const n=r instanceof Error?r:new Error(`State reset error: ${String(r)}`);t.push(n),f.warn("[NeuroLink] Error resetting state:",r)}t.length===0?f.debug("[NeuroLink] \u2705 Resource disposal completed successfully"):f.warn(`[NeuroLink] \u26A0\uFE0F Resource disposal completed with ${t.length} errors`,{errors:t.map(r=>r.message)})}catch(r){throw f.error("[NeuroLink] Critical error during disposal:",r),r}}getToolRegistry(){return this.toolRegistry}async compactSession(t,r){if(!this.conversationMemory)return null;const n=await this.conversationMemory.buildContextMessages(t);if(!n||n.length===0)return null;const o=new D_({...r,summarizationProvider:r?.summarizationProvider??this.conversationMemoryConfig?.conversationMemory?.summarizationProvider,summarizationModel:r?.summarizationModel??this.conversationMemoryConfig?.conversationMemory?.summarizationModel}),s=Aa({provider:r?.provider||"openai",conversationMessages:n}),i=Math.floor(s.availableInputTokens*.6),a=await o.compact(n,i,this.conversationMemoryConfig?.conversationMemory);return a.compacted&&M_(a.messages),a}async getContextStats(t,r,n){if(!this.conversationMemory)return null;const o=await this.conversationMemory.buildContextMessages(t);if(!o||o.length===0)return null;const s=Aa({provider:r||"openai",model:n,conversationMessages:o});return{estimatedInputTokens:s.estimatedInputTokens,availableInputTokens:s.availableInputTokens,usageRatio:s.usageRatio,shouldCompact:s.shouldCompact,messageCount:o.length}}needsCompaction(t,r,n){if(!this.conversationMemory)return!1;const o=this.conversationMemory.getSession?.(t);return o?Aa({provider:r||"openai",model:n,conversationMessages:o.messages}).shouldCompact:!1}async setAuthProvider(t){this.authInitPromise=void 0,await this.initializeAuthProviderFromConfig(t)}async initializeAuthProviderFromConfig(t){let r,n;if("authenticateToken"in t&&typeof t.authenticateToken=="function")r=t,n=r.type;else if("provider"in t)r=t.provider,n=r.type;else{const o=t,{AuthProviderFactory:s}=await Promise.resolve().then(()=>(d$(),uzt));r=await s.createProvider(o.type,o.config),n=o.type}this.authProvider=r,f.info(`Auth provider set: ${n}`),this.emitter.emit("auth:provider:set",{type:r.type,timestamp:Date.now()})}getAuthProvider(){return this.authProvider}async ensureAuthProvider(){if(this.authProvider||!this.pendingAuthConfig)return;const t=this.pendingAuthConfig;this.authInitPromise??=(async()=>{try{await this.initializeAuthProviderFromConfig(t),this.pendingAuthConfig=void 0}finally{this.authInitPromise&&(this.pendingAuthConfig===void 0||this.pendingAuthConfig===t)&&(this.authInitPromise=void 0)}})(),await this.authInitPromise}async setAuthContext(t){const{globalAuthContext:r}=await Promise.resolve().then(()=>(ox(),jL));r.set(t),f.debug("Auth context set",{userId:t.user.id,provider:t.provider,sessionId:t.session?.id})}async getAuthContext(){const{getAuthContext:t}=await Promise.resolve().then(()=>(ox(),jL));return t()}async clearAuthContext(){const{globalAuthContext:t}=await Promise.resolve().then(()=>(ox(),jL)),r=t.get()?.user.id;t.clear(),r&&f.debug(`Auth context cleared for user: ${r}`)}getExternalServerManager(){return this.externalServerManager}buildResolutionContext(t,r){return{requestContext:r||{},signal:t}}async resolveDynamicOptions(t){const r=["model","provider","temperature","maxTokens","systemPrompt","timeout","thinkingLevel","disableTools","enableAnalytics","enableEvaluation"];if(!(r.some(s=>typeof t[s]=="function")||typeof t.tools=="function"))return;const o=t.dynamicContext;await this.resolveDynamicFields(t,r,o)}async resolveDynamicFields(t,r,n){const o=this.buildResolutionContext(t.abortSignal,n);if(f.debug("[NeuroLink] Resolving dynamic arguments"),await Promise.all(r.map(async s=>{if(typeof t[s]=="function"){const i=await Ure(t[s],o);t[s]=i.value,f.debug(`[NeuroLink] Resolved dynamic ${s}: ${i.resolutionType}`)}})),typeof t.tools=="function"){const s=await Ure(t.tools,o);if(!Array.isArray(s.value))throw new TypeError(`Dynamic tools resolver must return string[] (tool names), got ${typeof s.value=="object"?"object":typeof s.value}`);t.enabledToolNames=s.value,delete t.tools}}},Xse=new Gx,mzt=Xse}}),hzt={};he(hzt,{VoyageProvider:()=>yzt});var fzt,Qse,gzt,m$,yzt,HWr=S({async"src/lib/providers/voyage.ts"(){"use strict";Tc(),await fd(),io(),yt(),at(),q(),ps(),fzt="https://api.voyageai.com/v1",Qse=6e4,gzt=()=>Yi(dwr()),m$=()=>Zi("VOYAGE_MODEL","voyage-3.5"),yzt=class extends Ol{apiKey;baseURL;proxyFetch;constructor(e,t,r,n){const o=by(t)?t:void 0;super(e,"voyage",o);const s=n?.apiKey?.trim();this.apiKey=s&&s.length>0?s:gzt(),this.baseURL=n?.baseURL??process.env.VOYAGE_BASE_URL??fzt,this.proxyFetch=zt(),f.debug("Voyage Provider initialized (embeddings only)",{modelName:this.modelName,baseURL:this.baseURL})}getProviderName(){return this.providerName}getDefaultModel(){return m$()}supportsTools(){return!1}getDefaultEmbeddingModel(){return m$()}getAISDKModel(){throw new _t("Voyage AI is an embedding-only provider; chat completions are not available. Use `embed()` or `embedMany()` instead, or pick a different provider for `generate()` / `stream()`.","voyage")}async executeStream(e,t){throw new _t("Voyage AI is an embedding-only provider; streaming chat is not available. Use `embed()` / `embedMany()`, or pick another provider for `stream()`.","voyage")}formatProviderError(e){const t=e instanceof Error?e.message:typeof e=="string"?e:"Unknown error";return t.includes("401")||t.toLowerCase().includes("unauthorized")||t.includes("invalid_api_key")?new Nr("Invalid Voyage AI API key. Get one at https://dash.voyageai.com/api-keys","voyage"):t.includes("429")||t.toLowerCase().includes("rate limit")?new Os("Voyage AI rate limit exceeded. Back off and retry.","voyage"):t.includes("404")||t.toLowerCase().includes("model_not_found")?new Qn(`Voyage AI model '${this.modelName}' not found. Browse https://docs.voyageai.com/docs/embeddings`,"voyage"):new _t(`Voyage AI error: ${t}`,"voyage")}async embed(e,t){const r=await this.callEmbeddings([e],t);if(!r[0])throw new _t("Voyage AI returned no embedding for the provided text","voyage");return r[0]}async embedMany(e,t){if(e.length===0)return[];const r=128,n=[];for(let o=0;o<e.length;o+=r){const s=e.slice(o,o+r),i=await this.callEmbeddings(s,t);n.push(...i)}return n}async callEmbeddings(e,t){const r=t??this.modelName;let n;try{n=await Ze(this.proxyFetch(`${this.baseURL}/embeddings`,{method:"POST",headers:{Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify({input:e,model:r})}),Qse,new _t(`Voyage embeddings request timed out after ${Qse/1e3}s`,"voyage"))}catch(i){throw i instanceof _t?i:this.formatProviderError(i)}if(!n.ok){const i=await n.text();throw this.formatProviderError(new Error(`Voyage embeddings failed: ${n.status} \u2014 ${i}`))}const o=await n.json();if(!o.data||o.data.length===0)throw new _t("Voyage embeddings response missing data","voyage");if(o.data.length!==e.length)throw new _t(`Voyage embeddings response count mismatch: expected ${e.length}, got ${o.data.length}`,"voyage");const s=o.data.slice().sort((i,a)=>i.index-a.index);for(let i=0;i<s.length;i++)if(s[i].index!==i)throw new _t(`Voyage embeddings response has unexpected index ordering: position ${i} has index ${s[i].index}`,"voyage");return s.map(i=>i.embedding)}async validateConfiguration(){return typeof this.apiKey=="string"&&this.apiKey.trim().length>0}getConfiguration(){return{provider:this.providerName,model:this.modelName,defaultModel:m$(),baseURL:this.baseURL}}}}}),vzt={};he(vzt,{JinaProvider:()=>bzt});var _zt,Hx,wzt,h$,bzt,VWr=S({async"src/lib/providers/jina.ts"(){"use strict";Tc(),await fd(),io(),yt(),q(),ps(),_zt="https://api.jina.ai/v1",Hx=6e4,wzt=()=>Yi(pwr()),h$=()=>Zi("JINA_MODEL","jina-embeddings-v3"),bzt=class extends Ol{apiKey;baseURL;proxyFetch;constructor(e,t,r,n){const o=by(t)?t:void 0;super(e,"jina",o);const s=n?.apiKey?.trim();this.apiKey=s&&s.length>0?s:wzt(),this.baseURL=n?.baseURL??process.env.JINA_BASE_URL??_zt,this.proxyFetch=zt(),f.debug("Jina Provider initialized (embeddings + reranking)",{modelName:this.modelName,baseURL:this.baseURL})}getProviderName(){return this.providerName}getDefaultModel(){return h$()}supportsTools(){return!1}getDefaultEmbeddingModel(){return h$()}getAISDKModel(){throw new Error("Jina AI is an embeddings + reranking provider; chat completions are not available. Use `embed()` / `embedMany()` / `rerank()`.")}async executeStream(e,t){throw new Error("Jina AI is an embeddings + reranking provider; streaming chat is not available.")}formatProviderError(e){const t=e instanceof Error?e.message:typeof e=="string"?e:"Unknown error";return t.includes("401")||t.toLowerCase().includes("unauthorized")?new Nr("Invalid Jina AI API key. Get one at https://jina.ai/?sui=apikey","jina"):t.includes("429")||t.toLowerCase().includes("rate limit")?new Os("Jina AI rate limit exceeded. Back off and retry.","jina"):t.includes("404")||t.toLowerCase().includes("model_not_found")?new Qn(`Jina AI model '${this.modelName}' not found. See https://jina.ai/embeddings/`,"jina"):new _t(`Jina AI error: ${t}`,"jina")}async embed(e,t){const r=await this.callEmbeddings([e],t);if(!r[0])throw new Error("Jina AI returned no embedding for the provided text");return r[0]}async embedMany(e,t){return e.length===0?[]:this.callEmbeddings(e,t)}async rerank(e,t,r={}){if(t.length===0)return[];const n=r.model??"jina-reranker-v2-base-multilingual",o=r.credentials,s=o?.apiKey?.trim()||this.apiKey,i=o?.baseURL||this.baseURL,a=new AbortController,l=setTimeout(()=>a.abort(),Hx);let c;try{c=await this.proxyFetch(`${i}/rerank`,{method:"POST",headers:{Authorization:`Bearer ${s}`,"Content-Type":"application/json"},body:JSON.stringify({model:n,query:e,documents:t,top_n:r.topN??t.length}),signal:a.signal})}catch(d){throw d instanceof Error&&d.name==="AbortError"?this.formatProviderError(new Error(`Jina rerank request timed out after ${Hx/1e3}s`)):this.formatProviderError(d)}finally{clearTimeout(l)}if(!c.ok){const d=await c.text();throw this.formatProviderError(new Error(`Jina rerank failed: ${c.status} \u2014 ${d}`))}return((await c.json()).results??[]).map(d=>({index:d.index,score:d.relevance_score,document:t[d.index]??d.document?.text??""}))}async callEmbeddings(e,t,r){const n=t??this.modelName,o=r?.apiKey?.trim()||this.apiKey,s=r?.baseURL||this.baseURL,i=new AbortController,a=setTimeout(()=>i.abort(),Hx);let l;try{l=await this.proxyFetch(`${s}/embeddings`,{method:"POST",headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json"},body:JSON.stringify({input:e,model:n}),signal:i.signal})}catch(d){throw d instanceof Error&&d.name==="AbortError"?this.formatProviderError(new Error(`Jina embeddings request timed out after ${Hx/1e3}s`)):this.formatProviderError(d)}finally{clearTimeout(a)}if(!l.ok){const d=await l.text();throw this.formatProviderError(new Error(`Jina embeddings failed: ${l.status} \u2014 ${d}`))}const c=await l.json();if(!c.data||c.data.length===0)throw new Error("Jina embeddings response missing data");if(c.data.length!==e.length)throw new Error(`Jina embeddings response count mismatch: expected ${e.length}, got ${c.data.length}`);const u=c.data.slice().sort((d,m)=>d.index-m.index);for(let d=0;d<u.length;d++)if(u[d].index!==d)throw new Error(`Jina embeddings response has unexpected index ordering: position ${d} has index ${u[d].index}`);return u.map(d=>d.embedding)}async validateConfiguration(){return typeof this.apiKey=="string"&&this.apiKey.trim().length>0}getConfiguration(){return{provider:this.providerName,model:this.modelName,defaultModel:h$(),baseURL:this.baseURL}}}}}),Tzt={};he(Tzt,{StabilityProvider:()=>rie,default:()=>Czt});var Ezt,eie,Szt,tie,rie,Czt,WWr=S({async"src/lib/providers/stability.ts"(){"use strict";Tc(),await fd(),io(),yt(),q(),ps(),Ezt="https://api.stability.ai",eie=12e4,Szt=()=>(process.env.STABILITY_API_KEY??process.env.STABILITY_AI_API_KEY??"").trim()||void 0,tie=()=>Zi("STABILITY_MODEL","stable-image-ultra"),rie=class extends Ol{apiKey;baseURL;proxyFetch;constructor(e,t,r,n){const o=by(t)?t:void 0;super(e,"stability",o);const s=n?.apiKey?.trim();this.apiKey=s&&s.length>0?s:Szt(),this.baseURL=n?.baseURL??process.env.STABILITY_BASE_URL??Ezt,this.proxyFetch=zt(),f.debug("Stability AI Provider initialized (image-gen only)",{modelName:this.modelName,baseURL:this.baseURL})}getProviderName(){return this.providerName}getDefaultModel(){return tie()}supportsTools(){return!1}getAISDKModel(){throw new Error("Stability AI is an image-generation-only provider; chat completions are not available.")}async executeStream(e,t){throw new Error("Stability AI is an image-generation-only provider; streaming chat is not available. Use generate({output:{format:'binary'}}) with a Stable Image / SD 3.5 model.")}formatProviderError(e){const t=e instanceof Error?e.message:typeof e=="string"?e:"Unknown error";return t.includes("401")||t.toLowerCase().includes("unauthorized")?new Nr("Invalid Stability AI API key. Get one at https://platform.stability.ai/account/keys","stability"):t.includes("429")||t.toLowerCase().includes("rate limit")?new Os("Stability AI rate limit exceeded. Back off and retry.","stability"):t.includes("content_filtered")||t.includes("CONTENT_FILTERED")?new _t("Stability AI declined the request due to content policy. Adjust the prompt and retry.","stability"):t.includes("404")?new Qn(`Stability AI model '${this.modelName}' not found. Use stable-image-ultra, stable-image-core, sd3.5-large, sd3.5-large-turbo, or sd3.5-medium.`,"stability"):new _t(`Stability AI error: ${t}`,"stability")}async executeImageGeneration(e){const t=Date.now(),r=e.credentials?.stability,n=r?.apiKey?.trim()||this.apiKey;if(!n)throw new Error("Stability AI API key is required. Set STABILITY_API_KEY or pass credentials.stability.apiKey per-call.");const o=n,s=r?.baseURL||this.baseURL,i=e.prompt??e.input?.text??"";if(!i.trim())throw new Error("Stability AI image generation requires a prompt (input.text or prompt)");const a=this.modelName.startsWith("sd3.5-")?"sd3":this.modelName==="stable-image-ultra"?"ultra":this.modelName==="stable-image-core"?"core":this.modelName,l=e,c=new FormData;c.append("prompt",i),c.append("output_format","png"),l.aspectRatio&&c.append("aspect_ratio",String(l.aspectRatio)),l.negativePrompt&&c.append("negative_prompt",l.negativePrompt),this.modelName.startsWith("sd3.5-")&&c.append("model",this.modelName),l.seed!==void 0&&c.append("seed",String(l.seed));const u=new AbortController,d=setTimeout(()=>u.abort(),eie);let m;try{m=await this.proxyFetch(`${s}/v2beta/stable-image/generate/${a}`,{method:"POST",headers:{Authorization:`Bearer ${o}`,Accept:"application/json"},body:c,signal:u.signal})}catch(y){throw y instanceof Error&&y.name==="AbortError"?this.formatProviderError(new Error(`Stability image-gen request timed out after ${eie/1e3}s`)):this.formatProviderError(y)}finally{clearTimeout(d)}if(!m.ok){const y=await m.text();throw this.formatProviderError(new Error(`Stability image-gen failed: ${m.status} \u2014 ${y}`))}const h=await m.json();if(!h.image)throw new Error(`Stability AI returned no image (finish_reason: ${h.finish_reason??"unknown"})`);const g=Date.now()-t;return f.info(`[StabilityProvider] Generated image (${h.image.length} base64 chars) in ${g}ms \u2014 model ${this.modelName}`),{content:i,provider:this.providerName,model:this.modelName,usage:{input:0,output:1e3,total:1e3},imageOutput:{base64:h.image}}}async validateConfiguration(){return this.apiKey!==void 0&&this.apiKey.trim().length>0}getConfiguration(){return{provider:this.providerName,model:this.modelName,defaultModel:tie(),baseURL:this.baseURL}}},Czt=rie}}),kzt={};he(kzt,{IdeogramProvider:()=>sie,default:()=>Izt});var xzt,nie,Azt,oie,sie,Izt,KWr=S({async"src/lib/providers/ideogram.ts"(){"use strict";Tc(),await fd(),io(),yt(),q(),ps(),xzt="https://api.ideogram.ai",nie=12e4,Azt=()=>Yi(mwr()),oie=()=>Zi("IDEOGRAM_MODEL","V_3"),sie=class extends Ol{apiKey;baseURL;proxyFetch;constructor(e,t,r,n){const o=by(t)?t:void 0;super(e,"ideogram",o);const s=n?.apiKey?.trim();this.apiKey=s&&s.length>0?s:Azt(),this.baseURL=n?.baseURL??process.env.IDEOGRAM_BASE_URL??xzt,this.proxyFetch=zt(),f.debug("Ideogram Provider initialized (image-gen only)",{modelName:this.modelName,baseURL:this.baseURL})}getProviderName(){return this.providerName}getDefaultModel(){return oie()}supportsTools(){return!1}getAISDKModel(){throw new Error("Ideogram is an image-generation-only provider; chat completions are not available.")}async executeStream(e,t){throw new Error("Ideogram is an image-generation-only provider; streaming chat is not available.")}formatProviderError(e){const t=e instanceof Error?e.message:typeof e=="string"?e:"Unknown error";return t.includes("401")||t.toLowerCase().includes("unauthorized")?new Nr("Invalid Ideogram API key. Get one at https://developer.ideogram.ai/","ideogram"):t.includes("429")||t.toLowerCase().includes("rate limit")?new Os("Ideogram rate limit exceeded. Back off and retry.","ideogram"):t.includes("safety")||t.includes("is_image_safe")?new _t("Ideogram declined the request due to safety filters. Adjust the prompt and retry.","ideogram"):new _t(`Ideogram error: ${t}`,"ideogram")}async executeImageGeneration(e){const t=Date.now(),r=e.credentials?.ideogram,n=r?.apiKey?.trim()||this.apiKey,o=r?.baseURL||this.baseURL,s=e.prompt??e.input?.text??"";if(!s.trim())throw new Error("Ideogram image generation requires a prompt (input.text or prompt)");const i=e,a={prompt:s,model:this.modelName,magic_prompt:i.magicPrompt??"AUTO"};i.aspectRatio&&(a.aspect_ratio=i.aspectRatio),i.negativePrompt&&(a.negative_prompt=i.negativePrompt),i.seed!==void 0&&(a.seed=i.seed),i.style&&(a.style_type=i.style);const l=new AbortController,c=setTimeout(()=>l.abort(),nie);let u;try{u=await this.proxyFetch(`${o}/v1/ideogram-v3/generate`,{method:"POST",headers:{"Api-Key":n,"Content-Type":"application/json"},body:JSON.stringify(a),signal:l.signal})}catch(T){throw T instanceof Error&&T.name==="AbortError"?this.formatProviderError(new Error(`Ideogram image-gen request timed out after ${nie/1e3}s`)):this.formatProviderError(T)}finally{clearTimeout(c)}if(!u.ok){const T=await u.text();throw this.formatProviderError(new Error(`Ideogram image-gen failed: ${u.status} \u2014 ${T}`))}const m=(await u.json()).data?.[0]?.url;if(!m)throw new Error("Ideogram returned no image URL");const h=new AbortController,g=setTimeout(()=>h.abort(),6e4);let y;try{y=await this.proxyFetch(m,{signal:h.signal})}catch(T){throw T instanceof Error&&T.name==="AbortError"?new Error("Ideogram image download timed out after 60s",{cause:T}):T}finally{clearTimeout(g)}if(!y.ok)throw new Error(`Failed to download Ideogram image: ${y.status}`);const v=Buffer.from(await y.arrayBuffer()),_=v.toString("base64"),b=Date.now()-t;return f.info(`[IdeogramProvider] Generated image (${v.length} bytes) in ${b}ms \u2014 model ${this.modelName}`),{content:s,provider:this.providerName,model:this.modelName,usage:{input:0,output:1e3,total:1e3},imageOutput:{base64:_}}}async validateConfiguration(){return typeof this.apiKey=="string"&&this.apiKey.trim().length>0}getConfiguration(){return{provider:this.providerName,model:this.modelName,defaultModel:oie(),baseURL:this.baseURL}}},Izt=sie}}),Rzt={};he(Rzt,{ReplicateProvider:()=>Mzt});function JWr(e){const t=e,r=t.prompt??t.input?.text??"",n=t.systemPrompt;return n?`${n}
|
|
2162
|
+
IMPORTANT: You have a tool called "${l.toolName}" that searches through`,`${l.filesLoaded} loaded document(s) containing ${l.chunksIndexed} indexed chunks.`,`ALWAYS use the "${l.toolName}" tool FIRST to answer the user's question before using any other tools.`,"This tool searches your local knowledge base of pre-loaded documents and is the primary source of truth.","Do NOT use websearchGrounding or any web search tools when the answer can be found in the loaded documents."].join(" ");t.systemPrompt=(t.systemPrompt||"")+c,f.info("[RAG] Tool injected into stream()",{toolName:l.toolName,filesLoaded:l.filesLoaded,chunksIndexed:l.chunksIndexed})}catch(a){f.warn("[RAG] Failed to prepare RAG tool, continuing without RAG",{error:a instanceof Error?a.message:String(a)})}const s=U7r(t),i=B7r(t);if(t.input?.text){const{toolResults:a,enhancedPrompt:l}=await this.detectAndExecuteTools(t.input.text,void 0);l!==t.input.text&&(i.input.text=l)}return{enhancedOptions:i,factoryResult:s}}async autoDisableOllamaStreamTools(t){if((t.provider==="ollama"||t.provider?.toLowerCase().includes("ollama"))&&!t.disableTools){const{ModelConfigurationManager:r}=await Promise.resolve().then(()=>(Gf(),IGe)),s=r.getInstance().getProviderConfiguration("ollama")?.modelBehavior?.toolCapableModels||[],i=t.model;s.length>0&&i&&(s.some(l=>i.toLowerCase().includes(l.toLowerCase()))||(t.disableTools=!0,f.debug("Auto-disabled tools for Ollama model that doesn't support them (stream)",{model:t.model,toolCapableModels:s.slice(0,3)})))}}setupStreamEventListeners(){const t=[];let r=0;const n=(d,m)=>{t.push({type:d,seq:r++,timestamp:Date.now(),...m&&typeof m=="object"?m:{data:m}})},o=(...d)=>{const m=d[0];n("response:chunk",{content:m})},s=(...d)=>{const m=d[0];n("tool:start",{...m,toolName:m.toolName??m.tool})},i=(...d)=>{const m=d[0],h=m.toolName??m.tool,g=m.responseTime??m.duration,y=m.success??(m.error!==void 0?!1:void 0),v={...m,toolName:h,...g!==void 0?{responseTime:g}:{},...y!==void 0?{success:y}:{},...m.error!==void 0?{error:m.error}:{}};n("tool:end",v),v.result&&v.result.uiComponent===!0&&n("ui-component",{toolName:h,componentData:v.result,timestamp:Date.now(),...y!==void 0?{success:y}:{},...g!==void 0?{responseTime:g}:{}})},a=(...d)=>{n("ui-component",d[0])},l=(...d)=>{n("hitl:confirmation-request",d[0])},c=(...d)=>{n("hitl:confirmation-response",d[0])};return this.emitter.on("response:chunk",o),this.emitter.on("tool:start",s),this.emitter.on("tool:end",i),this.emitter.on("ui-component",a),this.emitter.on("hitl:confirmation-request",l),this.emitter.on("hitl:confirmation-response",c),{eventSequence:t,cleanup:()=>{this.emitter.off("response:chunk",o),this.emitter.off("tool:start",s),this.emitter.off("tool:end",i),this.emitter.off("ui-component",a),this.emitter.off("hitl:confirmation-request",l),this.emitter.off("hitl:confirmation-response",c)}}}async*handleStreamFallback(t,r,n,o,s,i){t.fallbackAttempted=!0;const a="Stream completed with 0 chunks (possible guardrails block)";t.error=a;try{const g=this._metricsTraceContext;let y=Oe.createGenerationSpan({provider:s,model:o.model||"unknown",name:`gen_ai.${s}.stream.failed`,traceId:g?.traceId,parentSpanId:g?.parentSpanId});y=Oe.endSpan(y,2),y.statusMessage=a,y.durationMs=0,this.metricsAggregator.recordSpan(y),ut().recordSpan(y)}catch{}const l=o.fallbackProvider?.trim()||void 0,c=o.fallbackModel?.trim()||void 0,u=process.env.FALLBACK_PROVIDER?.trim()||void 0,d=process.env.FALLBACK_MODEL?.trim()||void 0,m=M2.getFallbackRoute(n||o.input.text||"",{provider:s,model:o.model||"gpt-4o",reasoning:"primary failed",confidence:.5},{fallbackStrategy:"auto"}),h={...m,provider:l??u??m.provider,model:c??d??m.model};f.warn("Retrying with fallback provider",{originalProvider:s,fallbackProvider:h.provider,fallbackModel:h.model,fallbackSource:l||c?"options":u||d?"env":"model_config",reason:a});try{const g=await po.createProvider(h.provider,h.model,!0,void 0,void 0,this.resolveCredentials(o.credentials));g.setupToolExecutor({customTools:this.getCustomTools(),executeTool:(x,I)=>this.executeTool(x,I,{disableToolCache:o.disableToolCache})},"NeuroLink.fallbackStream");const y=o.conversationMessages!==void 0?o.conversationMessages:await mh(this.conversationMemory,{prompt:o.input.text,context:o.context}),v=await g.stream({...this.deferProviderStreamTTS(o),model:h.model,conversationMessages:y}),_=v.toolCalls??[],b=v.toolResults??[];(_.length>0||b.length>0)&&(r.toolCalls=_,r.toolResults=b,r.finishReason=v.finishReason??r.finishReason);let T=0,k=0;for await(const x of v.stream){T++;const I=x!==null&&typeof x=="object"&&"metadata"in x&&x.metadata?.noOutput===!0,M=x&&"content"in x&&typeof x.content=="string"&&x.content.length>0,R=x!==null&&typeof x=="object"&&"type"in x&&(x.type==="audio"||x.type==="tts_audio"||x.type==="image");!I&&(M||R)&&k++,x&&"content"in x&&typeof x.content=="string"&&(i(x.content),this.emitter.emit("response:chunk",x.content)),yield x}if(k===0&&_.length===0&&b.length===0)throw new Error(`Fallback provider ${h.provider} also returned 0 real output chunks (chunkCount=${T}, sentinel-only or empty)`);t.fallbackProvider=h.provider,t.fallbackModel=h.model,t.guardrailsBlocked=!0}catch(g){const y=g instanceof Error?g.message:String(g);throw t.error=`${a}; Fallback failed: ${y}`,f.error("Fallback provider failed",{fallbackProvider:h.provider,error:y}),g}}async storeStreamConversationMemory(t){const{enhancedOptions:r,providerName:n,originalPrompt:o,accumulatedContent:s,startTime:i,eventSequence:a}=t;f.shouldLog("debug")&&f.debug("[NeuroLink.stream] Preparing to store conversation turn in memory",{options:vM(wM(r)),sessionId:r.context?.sessionId});const l=a.some(c=>c.type==="tool:start"||c.type==="tool:end");if(!s.trim()&&!l){f.warn("[NeuroLink.stream] Skipping conversation turn storage \u2014 no text content or tool activity",{sessionId:r.context?.sessionId});return}if(f.shouldLog("debug")&&f.debug("[NeuroLink.stream] Storing conversation turn in memory",{options:vM(wM(r)),sessionId:r.context?.sessionId,conversationMemoryExists:!!this.conversationMemory}),this.conversationMemory&&r.context?.sessionId){const c=r.context?.sessionId,u=r.context?.userId;let d;r.model&&(d={provider:n,model:r.model});const m=Date.now();try{const h=this.drainPendingSkillMessages(c);await this.conversationMemory.storeConversationTurn({sessionId:c,userId:u,userMessage:o??"",aiResponse:s,startTimeStamp:new Date(i),providerDetails:d,enableSummarization:r.enableSummarization,events:a.length>0?a:void 0,requestId:r.context?.requestId,...h.length>0?{skillMessages:h}:{}}),this.recordMemorySpan("memory.store",{"memory.operation":"store","memory.path":"stream"},Date.now()-m,1),f.debug("[NeuroLink.stream] Stored conversation turn with events",{sessionId:c,eventCount:a.length,eventTypes:[...new Set(a.map(g=>g.type))]})}catch(h){this.recordMemorySpan("memory.store",{"memory.operation":"store","memory.path":"stream"},Date.now()-m,2,h instanceof Error?h.message:String(h)),f.warn("Failed to store stream conversation turn",{error:h instanceof Error?h.message:String(h)})}}this.shouldWriteMemory(r.memory,r.context?.userId,s)&&this.storeMemoryInBackground(o??"",s.trim(),r.context?.userId,r.memory?.additionalUsers,r.context)}async validateStreamInput(t){const r=process.hrtime.bigint();f.debug("[NeuroLink] \u{1F3AF} LOG_POINT_003_VALIDATION_START",{logPoint:"003_VALIDATION_START",validationStartTimeNs:r.toString(),message:"Starting comprehensive input validation process"});const n=typeof t?.input?.text=="string"&&t.input.text.trim().length>0,o=!!(t?.input?.audio&&t.input.audio.frames&&typeof t.input.audio.frames[Symbol.asyncIterator]=="function"),s=!!(t?.stt?.enabled&&t?.stt?.audio);if(!n&&!o&&!s)throw new Error("Stream options must include either input.text, input.audio, or stt.audio")}emitStreamStartEvents(t,r){this.emitter.emit("stream:start",{provider:t.provider||"auto",timestamp:r}),this.emitter.emit("response:start"),this.emitter.emit("message",`Starting ${t.provider||"auto"} stream...`)}async createMCPStream(t){const r=await lw(t.provider),n=await po.createProvider(r,t.model,!t.disableTools,this,t.region,this.resolveCredentials(t.credentials));await n.ensureModelLimits?.(),n.setTraceContext(this._metricsTraceContext),n.setupToolExecutor({customTools:this.getCustomTools(),executeTool:(g,y)=>this.executeTool(g,y,{disableToolCache:t.disableToolCache})},"NeuroLink.createMCPStream");let o=await this.getAllAvailableTools();o=this.applyToolInfoFiltering(o,t);const s=t.skipToolPromptInjection?t.systemPrompt||"":this.createToolAwareSystemPrompt(t.systemPrompt,o,n.supportsTools?.()??!0),i=t.conversationMessages!==void 0,a=i?t.conversationMessages:await mh(this.conversationMemory,{...t,prompt:t.input.text,context:t.context});t.conversationMessages=a;let l=a;const c=Aa({provider:r,model:t.model,maxTokens:t.maxTokens,systemPrompt:s,conversationMessages:l,currentPrompt:t.input.text,toolDefinitions:o}),u=l?.length||0,d=this.getCompactionSessionId(t),m=u>0;if(!c.withinBudget&&!m){try{this.emitter.emit("compaction.insufficient",{stagesAttempted:["pre-dispatch hard cap"],finalTokens:c.estimatedInputTokens,budget:c.availableInputTokens,provider:r,model:t.model,phase:"pre-dispatch-no-recovery",timestamp:Date.now()})}catch{}throw new Qa(`Stream context exceeds model budget and no compaction is possible (no conversationMemory, no inline conversationMessages \u2014 only prompt + tools). Estimated: ${c.estimatedInputTokens} tokens, budget: ${c.availableInputTokens} tokens. Reduce prompt or tool-definition size, or trim the request.`,{estimatedTokens:c.estimatedInputTokens,availableTokens:c.availableInputTokens,stagesUsed:[],breakdown:c.breakdown})}if(c.shouldCompact&&(i||this.conversationMemory)&&u>(this.lastCompactionMessageCount.get(d)??0)){const y=await new D_({provider:r,summarizationProvider:this.conversationMemoryConfig?.conversationMemory?.summarizationProvider,summarizationModel:this.conversationMemoryConfig?.conversationMemory?.summarizationModel}).compact(l,lee(c),this.conversationMemoryConfig?.conversationMemory,t.context?.requestId);y.compacted&&(l=M_(y.messages).messages,t.conversationMessages=l,this.lastCompactionMessageCount.set(d,l.length));const v=Aa({provider:r,model:t.model,maxTokens:t.maxTokens,systemPrompt:s,conversationMessages:l,currentPrompt:t.input.text,toolDefinitions:o});if(!v.withinBudget){f.warn("[NeuroLink] Stream: post-compaction still over budget, emergency truncation",{estimatedTokens:v.estimatedInputTokens,availableTokens:v.availableInputTokens,overagePercent:Math.round((v.usageRatio-1)*100)});try{this.emitter.emit("compaction.insufficient",{stagesAttempted:y.stagesUsed,finalTokens:v.estimatedInputTokens,budget:v.availableInputTokens,provider:r,model:t.model,phase:"mid-compaction",willEmergencyTruncate:!0,timestamp:Date.now()})}catch{}l=hee(l,v.availableInputTokens,v.breakdown,r),t.conversationMessages=l;const _=Aa({provider:r,model:t.model,maxTokens:t.maxTokens,systemPrompt:s,conversationMessages:l,currentPrompt:t.input.text,toolDefinitions:o});if(!_.withinBudget){this.lastCompactionMessageCount.delete(d);try{this.emitter.emit("compaction.insufficient",{stagesAttempted:y.stagesUsed,finalTokens:_.estimatedInputTokens,budget:_.availableInputTokens,provider:r,model:t.model,phase:"post-emergency-truncation",timestamp:Date.now()})}catch{}throw new Qa(`Stream context exceeds model budget after all compaction stages. Estimated: ${_.estimatedInputTokens} tokens, Budget: ${_.availableInputTokens} tokens.`,{estimatedTokens:_.estimatedInputTokens,availableTokens:_.availableInputTokens,stagesUsed:y.stagesUsed,breakdown:_.breakdown})}}}if(this.modelPool){const g=this.modelPool,y=g.maxAttempts,v=new Set;let _=null;for(let b=0;b<y;b++){if(t.abortSignal?.aborted)throw new DOMException("The operation was aborted","AbortError");const T=g.selectNext(v);if(!T)break;v.add(g.memberKey(T));const k=T.provider,x=T.model??void 0,I=T.region??void 0;f.debug(`[createMCPStream] ModelPool: attempting member ${k}`,{model:x,attempt:b});try{const M=await po.createProvider(k,x,!t.disableTools,this,I,this.resolveCredentials(t.credentials));M.setTraceContext(this._metricsTraceContext),M.setupToolExecutor({customTools:this.getCustomTools(),executeTool:(N,L)=>this.executeTool(N,L,{disableToolCache:t.disableToolCache})},"NeuroLink.createMCPStream");const R=await M.stream({...this.deferProviderStreamTTS(t),provider:k,model:x,region:I,systemPrompt:s,conversationMessages:l});f.debug("[createMCPStream] ModelPool stream handle obtained",{provider:k});const A=T;return{stream:(async function*(){try{yield*R.stream,g.recordSuccess(A)}catch(N){throw g.recordFailure(A,cw(N)),N}})(),provider:k,usage:R.usage,model:R.model||x,finishReason:R.finishReason,toolCalls:R.toolCalls??[],toolResults:R.toolResults??[],analytics:R.analytics,metadata:R.metadata}}catch(M){if(mr(M))throw M;if(Zse(M)){const R=M instanceof Error?M.message:String(M);throw g.recordFailure(T,cw(M)),new Error(`[ModelPool] non-retryable: ${R}`,{cause:M})}g.recordFailure(T,cw(M)),_=M instanceof Error?M:new Error(String(M)),f.warn(`[createMCPStream] ModelPool: member ${k} failed`,{error:_.message})}}throw new Error(`[ModelPool] all stream members failed: ${_?.message??"no stream members available"}`)}const h=await n.stream({...this.deferProviderStreamTTS(t),systemPrompt:s,conversationMessages:l});return f.debug("[createMCPStream] Stream created successfully",{provider:r,systemPromptPassedLength:s.length}),{stream:h.stream,provider:r,usage:h.usage,model:h.model||t.model,finishReason:h.finishReason,toolCalls:h.toolCalls??[],toolResults:h.toolResults??[],analytics:h.analytics,metadata:h.metadata}}async processStreamResult(t,r,n){return{content:"",usage:void 0,finishReason:"stop",toolCalls:[],toolResults:[],analytics:void 0,evaluation:void 0}}emitStreamEndEvents(t){this.emitter.emit("stream:end",{responseTime:Date.now(),timestamp:Date.now()}),this.emitter.emit("response:end",t.content||"")}createStreamResponse(t,r,n){return{stream:r,provider:n.providerName,model:n.options.model,usage:t.usage,finishReason:t.finishReason,toolCalls:t.toolCalls,toolResults:t.toolResults,analytics:t.analytics,evaluation:t.evaluation,events:n.events&&n.events.length>0?n.events:void 0,metadata:Object.assign(n.providerMetadata??{},{streamId:n.streamId,startTime:n.startTime,responseTime:n.responseTime,fallback:n.fallback||!1,guardrailsBlocked:n.guardrailsBlocked,error:n.error})}}async handleStreamError(t,r,n,o,s,i){if(t instanceof Qa)throw t;f.error("Stream generation failed, attempting fallback",{error:t instanceof Error?t.message:String(t)});try{this.emitter.emit("stream:error",{content:t instanceof Error?t.message:String(t),metadata:{errorName:t instanceof Error?t.name:"UnknownError",durationMs:Date.now()-n,chunkCount:0},provider:r.provider||"unknown",model:r.model||"unknown"})}catch{}const a=r.input.text,l=Date.now()-n,c=await lw(r.provider),d=await(await po.createProvider(c,r.model,!0,void 0,void 0,this.resolveCredentials(r.credentials))).stream({input:{text:r.input.text},model:r.model,temperature:r.temperature,maxTokens:r.maxTokens,conversationMessages:r.conversationMessages});let m="";return{stream:(async function*(g){try{for await(const y of d.stream)y&&"content"in y&&typeof y.content=="string"&&(m+=y.content,g.emitter.emit("response:chunk",y.content)),yield y}finally{if(m.trim()){f.info("[NeuroLink.handleStreamError] stream() - COMPLETE SUCCESS (fallback)",{provider:c,model:r.model,responseTimeMs:Date.now()-n,contentLength:m.length});try{const y=r.model||"unknown",v=Date.now()-n;g.emitter.emit("stream:complete",{content:m,provider:c,model:y,finishReason:"stop",metadata:{durationMs:v,chunkCount:0,totalLength:m.length,isFallback:!0,finishReason:"stop"}}),g.emitter.emit("generation:end",{provider:c,model:y,responseTime:v,timestamp:Date.now(),result:{content:m,usage:{input:0,output:0,total:0},model:y,provider:c,finishReason:"stop"},success:!0,pipelineAHandled:!0})}catch{}}if(g.conversationMemory&&s?.context?.sessionId&&m.trim()){const y=s?.context?.sessionId,v=s?.context?.userId;let _;r.model&&(_={provider:c,model:r.model});const b=Date.now();try{const T=y||r.context?.sessionId,k=g.drainPendingSkillMessages(T);await g.conversationMemory.storeConversationTurn({sessionId:T,userId:v||r.context?.userId,userMessage:a??"",aiResponse:m,startTimeStamp:new Date(n),providerDetails:_,enableSummarization:s?.enableSummarization,requestId:s?.context?.requestId||r.context?.requestId,...k.length>0?{skillMessages:k}:{}}),g.recordMemorySpan("memory.store",{"memory.operation":"store","memory.path":"fallback-stream"},Date.now()-b,1)}catch(T){g.recordMemorySpan("memory.store",{"memory.operation":"store","memory.path":"fallback-stream"},Date.now()-b,2,T instanceof Error?T.message:String(T)),f.warn("Failed to store fallback stream conversation turn",{error:T instanceof Error?T.message:String(T)})}}}})(this),provider:c,model:r.model,usage:d.usage,finishReason:d.finishReason||"stop",toolCalls:d.toolCalls||[],toolResults:d.toolResults||[],analytics:d.analytics,evaluation:d.evaluation,metadata:{streamId:o,startTime:n,responseTime:l,fallback:!0}}}getEventEmitter(){return this.emitter}hasPendingHITLConfirmation(t){return this.hitlManager?.hasPendingConfirmation(t)??!1}getToolDedupConfig(){return this.toolDedupConfig}getToolsConfig(){return this.toolsConfig}getDiscoveryPins(t){const r=this.discoveryPins.get(t);return r?(this.discoveryPins.delete(t),this.discoveryPins.set(t,r),r):new Set}pinDiscoveredTools(t,r){let n=this.discoveryPins.get(t);n?this.discoveryPins.delete(t):n=new Set,this.discoveryPins.set(t,n);for(const o of r)n.add(o);if(this.discoveryPins.size>1e3){const o=this.discoveryPins.keys().next().value;o!==void 0&&this.discoveryPins.delete(o)}}async checkCredentials(t){const{provider:r,model:n}=t,o="ping";try{return await this.generate({provider:r,...n&&{model:n},input:{text:o},maxTokens:16,disableTools:!0}),{provider:r,status:"ok",detail:"credentials valid"}}catch(s){const i=s instanceof Error?s.message:String(s),a=i.toLowerCase();return s instanceof uv?{provider:r,status:"denied",detail:i}:a.includes("authentication")||a.includes("401")||a.includes("invalid api key")||a.includes("incorrect api key")||a.includes("api_key_invalid")||a.includes("token has expired")||a.includes("expired credentials")?{provider:r,status:"expired",detail:i}:a.includes("not configured")||a.includes("missing api")||a.includes("api key is required")||a.includes("no api key")||a.includes("application default credentials")||a.includes("google_application_credentials")||a.includes("project_id")||a.includes("default credentials")||a.includes("service account")?{provider:r,status:"missing",detail:i}:a.includes("econnrefused")||a.includes("enotfound")||a.includes("could not resolve")||a.includes("timeout")||a.includes("network")||a.includes("cannot connect")?{provider:r,status:"network",detail:i}:{provider:r,status:"unknown",detail:i}}}emitToolStart(t,r,n=Date.now()){const o=`${t}-${n}-${Math.random().toString(36).substr(2,9)}`,s={executionId:o,tool:t,startTime:n,metadata:{inputType:typeof r,hasInput:r!=null}};return this.activeToolExecutions.set(o,s),this.currentStreamToolExecutions.push(s),this.emitter.emit("tool:start",x0(t,{input:r,timestamp:n,executionId:o})),f.debug(`tool:start emitted for ${t}`,{toolName:t,executionId:o,timestamp:n,inputProvided:r!==void 0}),o}emitToolEnd(t,r,n,o,s=Date.now(),i){const a=o||s-1e3,l=s-a,c=!n;let u;i?u=this.activeToolExecutions.get(i):u=Array.from(this.activeToolExecutions.values()).find(h=>h.tool===t&&!h.endTime);const d=i||u?.executionId||`${t}-${a}-fallback-${Math.random().toString(36).substr(2,9)}`;u&&(u.endTime=s,u.result=r,u.error=n,this.activeToolExecutions.delete(u.executionId));const m={tool:t,startTime:a,endTime:s,duration:l,success:c,result:r,error:n,executionId:d,metadata:{toolCategory:"custom"}};this.toolExecutionHistory.push(m),this.emitter.emit("tool:end",x0(t,{result:r,error:n,success:c,responseTime:l,timestamp:s,duration:l,executionId:d})),f.debug(`tool:end emitted for ${t}`,{toolName:t,executionId:d,duration:l,success:c,hasResult:r!==void 0,hasError:!!n})}getCurrentToolExecutions(){return[...this.currentStreamToolExecutions]}getToolExecutionHistory(){return[...this.toolExecutionHistory]}clearCurrentStreamExecutions(){this.currentStreamToolExecutions=[]}registerTool(t,r,n){this.invalidateToolCache(),this.emitter.emit("tools-register:start",{toolName:t,timestamp:Date.now()});try{if(!t||typeof t!="string")throw new Error("Invalid tool name");if(!r||typeof r!="object")throw new Error(`Invalid tool object provided for tool: ${t}`);if(typeof r.execute!="function")throw new Error(`Tool '${t}' must have an execute method.`);if(t.trim()==="")throw new Error("Tool name cannot be empty");if(t.length>100)throw new Error("Tool name is too long (maximum 100 characters)");if(/[\x00-\x1F\x7F]/.test(t))throw new Error("Tool name contains invalid control characters");const o={name:r.name||t,description:r.description||t,execute:r.execute,inputSchema:"parameters"in r&&r.parameters&&(e9(r.parameters)||typeof r.parameters=="object")?r.parameters:r.inputSchema||{}};if(n?.timeout!==void 0&&n.timeout>0&&Number.isFinite(n.timeout)&&typeof o.execute=="function"){const i=o.execute,a=n.timeout,l=t;o.execute=async(...c)=>{const u=AbortSignal.timeout(a),d=c[1],m=d?.abortSignal,h=m?AbortSignal.any([m,u]):u,g={...d,abortSignal:h};return Promise.race([i(c[0],g),new Promise((y,v)=>{h.addEventListener("abort",()=>{u.aborted?v(ke.toolTimeout(l,a)):v(new DOMException("The operation was aborted","AbortError"))},{once:!0})})])}}const s=jqr(t,o,n?.timeout,n?.maxRetries,n?.totalTimeoutMs);this.toolRegistry.registerServer(s),n?.cacheable===!1?this.uncacheableTools.add(t):this.uncacheableTools.delete(t),this.emitter.emit("tools-register:end",{toolName:t,success:!0,timestamp:Date.now(),timeoutMs:n?.timeout})}catch(o){throw f.error(`Failed to register tool ${t}:`,o),o}}setToolContext(t){this.toolExecutionContext={...t},f.debug("Tool execution context updated",{sessionId:t.sessionId,contextKeys:Object.keys(t),hasJuspayToken:!!t.juspayToken,hasShopId:!!t.shopId})}getToolContext(){return this.toolExecutionContext?{...this.toolExecutionContext}:void 0}clearToolContext(){this.toolExecutionContext=void 0,f.debug("Tool execution context cleared")}registerTools(t){if(Array.isArray(t))for(const{name:r,tool:n}of t)this.registerTool(r,n);else for(const[r,n]of Object.entries(t))this.registerTool(r,n)}unregisterTool(t){this.invalidateToolCache();const r=`custom-tool-${t}`,n=this.toolRegistry.unregisterServer(r);return n&&(this.uncacheableTools.delete(t),f.info(`Unregistered custom tool: ${t}`)),n}useToolMiddleware(t){return this.mcpToolMiddlewares.push(t),f.debug(`[NeuroLink] Registered tool middleware (total: ${this.mcpToolMiddlewares.length})`),this}getToolMiddlewares(){return[...this.mcpToolMiddlewares]}async flushToolBatch(){this.mcpToolBatcher&&await this.mcpToolBatcher.flush()}getMCPEnhancementsConfig(){return this.mcpEnhancementsConfig}async updateAgenticLoopReport(t,r,n){if(!this.conversationMemory)throw new yl("Conversation memory is not initialized. Enable conversationMemory in NeuroLink options.","CONFIG_ERROR");if(!("updateAgenticLoopReport"in this.conversationMemory)||typeof this.conversationMemory.updateAgenticLoopReport!="function")throw new yl("updateAgenticLoopReport is only supported with Redis conversation memory.","CONFIG_ERROR");await Ze(this.conversationMemory.updateAgenticLoopReport(t,n,r),5e3)}getCustomTools(){const t=this.toolRegistry.getToolsByCategory(Ia({isCustomTool:!0})),r=new Map;for(const o of t){const s=o.inputSchema||o.parameters;f.debug("Processing tool schema for Claude",{toolName:o.name,hasDescription:!!o.description,description:o.description,hasParameters:!!o.parameters,parametersType:typeof o.parameters,parametersKeys:o.parameters&&typeof o.parameters=="object"?Object.keys(o.parameters):"NOT_OBJECT",hasInputSchema:!!o.inputSchema,inputSchemaType:typeof o.inputSchema,inputSchemaKeys:o.inputSchema&&typeof o.inputSchema=="object"?Object.keys(o.inputSchema):"NOT_OBJECT",hasEffectiveSchema:!!s,effectiveSchemaType:typeof s,effectiveSchemaHasProperties:!!s?.properties,effectiveSchemaHasRequired:!!s?.required,originalInputSchema:o.inputSchema,phase:"AFTER_SCHEMA_FIX",timestamp:Date.now()}),r.set(o.name,{name:o.name,description:o.description||"",inputSchema:typeof o.inputSchema=="object"&&o.inputSchema!==null?o.inputSchema:typeof o.parameters=="object"&&o.parameters!==null?o.parameters:{},execute:async(i,a)=>{const l=this.toolExecutionContext||{},c=a&&ar(a)?a:{},u={...l,...c,sessionId:c.sessionId||l.sessionId||`fallback-${Date.now()}`};return f.debug("Tool execution context merged",{toolName:o.name,storedContextKeys:Object.keys(l),runtimeContextKeys:Object.keys(c),finalContextKeys:Object.keys(u),hasJuspayToken:!!u.juspayToken,hasShopId:!!u.shopId,sessionId:u.sessionId}),await this.toolRegistry.executeTool(o.name,i,u)}})}this.cachedFileTools||(this.cachedFileTools=iDt(this.fileRegistry));const n=this.cachedFileTools;for(const[o,s]of Object.entries(n))if(!r.has(o)){const i=s,a=i.inputSchema??i.parameters;r.set(o,{name:o,description:s.description||`File tool: ${o}`,inputSchema:typeof a=="object"&&a!==null?a:{type:"object",properties:{}},execute:async l=>await s.execute(l,{toolCallId:`file-tool-${Date.now()}`,messages:[]})})}return r}async addInMemoryMCPServer(t,r){this.invalidateToolCache();try{de.debug(`[NeuroLink] Registering in-memory MCP server: ${t}`),r.tools||(r.tools=[]),await this.toolRegistry.registerServer(r),de.info(`[NeuroLink] Successfully registered in-memory server: ${t}`,{category:r.metadata?.category,provider:r.metadata?.provider,version:r.metadata?.version})}catch(n){throw de.error(`[NeuroLink] Failed to register in-memory server ${t}:`,n),n}}getInMemoryServers(){const t=this.getInMemoryServerInfos(),r=new Map;for(const n of t)r.set(n.id,n);return r}getInMemoryServerInfos(){return this.toolRegistry.getBuiltInServerInfos().filter(r=>Ia({existingCategory:r.metadata?.category,serverId:r.id})==="in-memory")}getAutoDiscoveredServerInfos(){return this.autoDiscoveredServerInfos}async executeTool(t,r={},n){if(this.mcpToolBatcher&&!n?.bypassBatcher)return this.mcpToolBatcher.execute(t,r);const o=this.createToolExecutionContext(t,r,n);return He.mcp.startActiveSpan("neurolink.tool.execute",{attributes:{"tool.name":t,"tool.type":o.toolType,"tool.input_size":o.inputSize,"tool.input_preview":o.truncatedInput}},s=>this.executeToolWithSpan(t,r,n,o,s))}createToolExecutionContext(t,r,n){const o=this.externalServerManager.getAllTools().find(c=>c.name===t),s=o?"mcp":this.getCustomTools().has(t)?"custom":"external",i=r?Kv(r):"",a=Date.now(),l=`${t}-${a}-${Math.random().toString(36).slice(2,11)}`;return{functionTag:"NeuroLink.executeTool",executionStartTime:a,executionId:l,externalTool:o,toolType:s,inputSize:i.length,truncatedInput:i.length>2048?i.substring(0,2048):i,options:n,hitlState:{triggered:!1}}}async executeToolWithSpan(t,r,n,o,s){try{const i=await this.prepareToolExecutionState(t,r,n,o);return await this.runPreparedToolExecution(t,r,i,o,s)}catch(i){if(!(i instanceof Ne)){const a=i instanceof Error?i.message:String(i);s.recordException(i instanceof Error?i:new Error(a)),s.setStatus({code:ze.ERROR,message:a})}throw i}finally{s.end()}}async prepareToolExecutionState(t,r,n,o){f.debug(`[${o.functionTag}] Tool execution requested:`,{toolName:t,params:ar(r)?W8e(r):r,hasExternalManager:!!this.externalServerManager}),f.debug("Tool execution detailed analysis",{toolName:t,executionStartTime:o.executionStartTime,paramsAnalysis:{type:typeof r,isNull:r===null,isUndefined:r===void 0,isEmpty:r&&typeof r=="object"&&Object.keys(r).length===0,keys:r&&typeof r=="object"?Object.keys(r):"NOT_OBJECT",keysLength:r&&typeof r=="object"?Object.keys(r).length:0},isTargetTool:t==="juspay-analytics_SuccessRateSRByTime",options:n,hasExternalManager:!!this.externalServerManager}),this.emitter.emit("tool:start",x0(t,{timestamp:o.executionStartTime,input:r,executionId:o.executionId}));const s=this.toolRegistry.getToolInfo(t),i=n?.timeout??s?.tool?.timeoutMs??tc.EXECUTION_BATCH_MS,a=n?.maxRetries??s?.tool?.maxRetries??ls.DEFAULT,l=n?.retryDelayMs||bn.BASE_MS,c={timeout:i,maxRetries:a,totalTimeout:n?.totalTimeoutMs??s?.tool?.totalTimeoutMs??i*(a+1)+l*a,retryDelayMs:l,authContext:n?.authContext,disableToolCache:n?.disableToolCache},{MemoryManager:u}=await Promise.resolve().then(()=>(Dx(),dw)),d=u.getMemoryUsageMB(),h=`${o.externalTool?.serverId||s?.tool?.serverId||"unknown"}.${t}`;let g=this.toolCircuitBreakers.get(h);g||(g=new j1(jI.FAILURE_THRESHOLD,V3),this.toolCircuitBreakers.set(h,g));let y=this.toolExecutionMetrics.get(t);return y||(y={totalExecutions:0,successfulExecutions:0,failedExecutions:0,averageExecutionTime:0,lastExecutionTime:0,errorCategories:{}},this.toolExecutionMetrics.set(t,y)),y.totalExecutions++,{finalOptions:c,startMemory:d,circuitBreaker:g,breakerKey:h,metrics:y}}async runPreparedToolExecution(t,r,n,o,s){let i=0;try{de.debug(`[${o.functionTag}] Executing tool: ${t}`,{toolName:t,params:r,options:n.finalOptions,circuitBreakerState:n.circuitBreaker.getState()});const a=n.finalOptions.maxRetries+1,l=n.finalOptions.totalTimeout,c=Date.now(),u=c+l;let d=0;const m=await n.circuitBreaker.execute(async()=>hve(async()=>{d++;const h=u-Date.now();if(h<=0)throw ke.toolTimeout(t,l,void 0,{attempt:d,maxAttempts:a,attemptTimeoutMs:n.finalOptions.timeout,totalTimeoutMs:l,elapsedMs:Date.now()-c,exhausted:!0});const g=Math.min(n.finalOptions.timeout,h);return Ze(this.executeToolInternal(t,r,n.finalOptions,o.hitlState),g,ke.toolTimeout(t,g,void 0,{attempt:d,maxAttempts:a,attemptTimeoutMs:n.finalOptions.timeout,totalTimeoutMs:l,elapsedMs:Date.now()-c}))},{maxAttempts:a,delayMs:n.finalOptions.retryDelayMs,isRetriable:h=>Date.now()+n.finalOptions.retryDelayMs<u&&Tz(h),onRetry:(h,g)=>{i=h,de.warn(`[${o.functionTag}] Retrying tool execution (attempt ${h})`,{toolName:t,error:g.message,attempt:h})}}));return s.setAttribute("tool.retry_count",i),await this.handleSuccessfulToolExecution(t,m,n,o,s)}catch(a){return s.setAttribute("tool.retry_count",i),this.handleFailedToolExecution(t,r,a,n,o,s)}}async handleSuccessfulToolExecution(t,r,n,o,s){const i=Date.now()-o.executionStartTime;n.metrics.successfulExecutions++,n.metrics.lastExecutionTime=i,n.metrics.averageExecutionTime=(n.metrics.averageExecutionTime*(n.metrics.successfulExecutions-1)+i)/n.metrics.successfulExecutions;const{MemoryManager:a}=await Promise.resolve().then(()=>(Dx(),dw)),c=a.getMemoryUsageMB().heapUsed-n.startMemory.heapUsed;c>20&&de.warn(`Tool '${t}' used excessive memory: ${c}MB`,{toolName:t,memoryDelta:c,executionTime:i}),de.debug(`[${o.functionTag}] Tool executed successfully`,{toolName:t,executionTime:i,memoryDelta:c,circuitBreakerState:n.circuitBreaker.getState()});const u=r&&typeof r=="object"?r:void 0,d=u&&"isError"in u&&u.isError===!0||u&&"success"in u&&u.success===!1,m=d?u?.content:void 0,h=d?m?.filter(g=>g.type==="text"&&g.text).map(g=>g.text).join(" ")||(typeof u?.error=="string"?u.error:"Unknown error"):void 0;if(d){try{await n.circuitBreaker.execute(async()=>{throw new Error(`Tool ${t} returned isError:true`)})}catch{}de.debug(`[${o.functionTag}] Circuit breaker failure recorded for isError result`,{toolName:t,circuitBreakerState:n.circuitBreaker.getState(),circuitBreakerFailures:n.circuitBreaker.getFailureCount()});const g=BWr(h??"Unknown error"),y=`[TOOL_ERROR: ${t} failed (${g})] `;if(u&&Array.isArray(m)){const b=m.map(T=>({...T}));for(const T of b)if(T.type==="text"&&T.text){T.text=y+T.text;break}u.content=b}s.setAttribute("tool.error.message",(h??"Unknown error").substring(0,500)),s.setAttribute("tool.error.category",g),s.setStatus({code:ze.ERROR,message:`MCP tool returned isError: ${(h??"Unknown error").substring(0,200)}`}),n.metrics.failedExecutions++;const v=n.metrics.successfulExecutions;n.metrics.successfulExecutions=Math.max(0,n.metrics.successfulExecutions-1),n.metrics.averageExecutionTime=v>1?(n.metrics.averageExecutionTime*v-i)/(v-1):0;const _=zWr(g);n.metrics.errorCategories[_]=(n.metrics.errorCategories[_]||0)+1}return this.emitToolEndEvent(t,o.executionStartTime,!d,r,d&&h?new Error(h):void 0,o.executionId),s.setAttribute("tool.result.status",d?"error":"success"),s.setAttribute("tool.duration_ms",i),r}async handleFailedToolExecution(t,r,n,o,s,i){o.metrics.failedExecutions++;const a=Date.now()-s.executionStartTime;if(n instanceof am)return de.warn(`[${s.functionTag}] Tool blocked by circuit breaker: ${t}`,{toolName:t,breakerState:n.breakerState,retryAfter:n.retryAfter,retryAfterMs:n.retryAfterMs,failureCount:n.failureCount,executionTime:a}),o.metrics.errorCategories.execution=(o.metrics.errorCategories.execution||0)+1,this.emitToolEndEvent(t,s.executionStartTime,!1,void 0,new Error(`Circuit breaker open for ${t} (state=${n.breakerState}, failures=${n.failureCount})`),s.executionId),i.setAttribute("tool.result.status","circuit_breaker_open"),i.setAttribute("tool.duration_ms",a),i.setAttribute("tool.circuit_breaker.state",n.breakerState),i.setAttribute("tool.circuit_breaker.retry_after_ms",n.retryAfterMs),i.setAttribute("tool.circuit_breaker.failure_count",n.failureCount),i.setStatus({code:ze.ERROR,message:`Circuit breaker open for ${t}: ${n.message}`}),{isError:!0,content:[{type:"text",text:`TOOL TEMPORARILY UNAVAILABLE: "${t}" has been disabled after ${n.failureCount} failures. This is a circuit breaker protection \u2014 do NOT retry this tool. It will become available again after ${Math.ceil(n.retryAfterMs/1e3)} seconds (at ${n.retryAfter}). Instead, inform the user that the operation failed and suggest trying again later.`}]};let l;if(n instanceof Ne)l=n;else if(n instanceof Error)if(n.message.includes("timeout"))l=ke.toolTimeout(t,o.finalOptions.timeout);else if(n.message.includes("not found")){const u=await this.getAllAvailableTools();l=ke.toolNotFound(t,dMr(u.map(d=>({name:d.name}))))}else n.message.includes("validation")||n.message.includes("parameter")?l=ke.invalidParameters(t,n,r):n.message.includes("network")||n.message.includes("connection")?l=ke.networkError(t,n):l=ke.toolExecutionFailed(t,n);else l=ke.toolExecutionFailed(t,new Error(String(n)));const c=l.category||"execution";throw o.metrics.errorCategories[c]=(o.metrics.errorCategories[c]||0)+1,this.emitToolEndEvent(t,s.executionStartTime,!1,void 0,l,s.executionId),this.emitter.listenerCount("error")>0&&this.emitter.emit("error",l),l=new Ne({...l,context:{...l.context,executionTime:a,params:r,options:o.finalOptions,circuitBreakerState:o.circuitBreaker.getState(),circuitBreakerFailures:o.circuitBreaker.getFailureCount(),metrics:{...o.metrics}}}),fve(l),i.setAttribute("tool.result.status","error"),i.setAttribute("tool.duration_ms",a),i.recordException(l),i.setStatus({code:ze.ERROR,message:l.message}),l}toolCacheRepeatKey(t,r){try{return`${t}:${JSON.stringify(r)??""}`}catch{return}}async executeToolInternal(t,r,n,o){const s="NeuroLink.executeToolInternal",i=this.getToolAnnotationsForExecution(t),a=this.mcpToolResultCache&&!n.disableToolCache&&!this._disableToolCacheForCurrentRequest&&!this.uncacheableTools.has(t)&&!i?.destructiveHint,l=this.mcpToolResultCache,c=n.authContext||this.toolExecutionContext?{__args:r,__ctx:n.authContext??this.toolExecutionContext}:r,u=this._generationTurnActive?this.toolCacheRepeatKey(t,c):void 0,d=u!==void 0&&this._toolCacheKeysServedThisRequest.has(u);if(u!==void 0&&this._toolCacheKeysServedThisRequest.add(u),a&&l&&!d){const g=l.getCachedResult(t,c);if(g!==void 0)return f.debug(`[${s}] Cache HIT for tool: ${t}`),g}else d&&f.debug(`[${s}] Repeat call within this request \u2014 bypassing tool cache for: ${t}`);const m=async g=>{if(this.mcpToolMiddlewares.length===0)return g();let y=0;const v=async()=>{if(y<this.mcpToolMiddlewares.length){const _=this.mcpToolMiddlewares[y++];return _({name:t,description:"",inputSchema:{},annotations:i,execute:async()=>({})},r,{toolMeta:{name:t,annotations:i}},v)}return g()};return await v()},h=async()=>{const g=this.externalServerManager.getAllTools(),y=g.filter(_=>_.name===t&&_.isAvailable);let v;if(y.length>1&&this.mcpToolRouter)try{const _={name:t,description:y[0].description??"",serverId:y[0].serverId,inputSchema:{}},b=this.mcpToolRouter.route(_);v=y.find(T=>T.serverId===b.serverId)||y[0],f.debug(`[${s}] Router selected server: ${b.serverId}`,{strategy:b.strategy,confidence:b.confidence})}catch(_){f.warn(`[${s}] Router failed, falling back to first match`,{error:_}),v=y[0]}else v=y[0];if(f.debug(`[${s}] External MCP tool search:`,{toolName:t,externalToolsCount:g.length,foundTool:!!v,isAvailable:v?.isAvailable,serverId:v?.serverId}),v&&v.isAvailable)try{de.debug(`[${s}] Executing external MCP tool: ${t} from ${v.serverId}`);const _=await this.externalServerManager.executeTool(v.serverId,t,r,{timeout:n.timeout});return f.debug(`[${s}] External MCP tool execution successful:`,{toolName:t,serverId:v.serverId,resultType:typeof _}),_}catch(_){throw f.error(`[${s}] External MCP tool execution failed:`,{toolName:t,serverId:v.serverId,error:_ instanceof Error?_.message:String(_)}),ke.toolExecutionFailed(t,_ instanceof Error?_:new Error(String(_)),v.serverId)}try{const _=this.toolExecutionContext||{},b=n.authContext||{},T={..._,...b,hitlState:o};f.debug("[Using merged context for unified registry tool:",{toolName:t,storedContextKeys:Object.keys(_),finalContextKeys:Object.keys(T)});const k=await this.toolRegistry.executeTool(t,r,T);if(k&&typeof k=="object"&&"success"in k&&k.success===!1){const x=k.error||"Tool execution failed",I=new Error(x);this.emitter.listenerCount("error")>0&&this.emitter.emit("error",I)}return k}catch(_){const b=_ instanceof Error?_:new Error(String(_));if(this.emitter.listenerCount("error")>0&&this.emitter.emit("error",b),_ instanceof Error&&_.message.includes("not found")){const T=await this.getAllAvailableTools();throw ke.toolNotFound(t,T.map(k=>k.name))}throw ke.toolExecutionFailed(t,_ instanceof Error?_:new Error(String(_)))}};try{const g=await m(h);return a&&l&&g!==void 0&&(l.cacheResult(t,c,g),f.debug(`[${s}] Cached result for tool: ${t}`)),g}catch(g){const y=i?{name:t,description:"",annotations:i,execute:async()=>({})}:void 0;if(y&&FY(y)&&g instanceof Error&&Tz(g)){f.debug(`[${s}] Tool ${t} is safe to retry, attempting once more`);try{const v=await m(h);return a&&l&&v!==void 0&&l.cacheResult(t,c,v),v}catch{}}throw g}}getToolAnnotationsForExecution(t){if(this.toolCache?.tools){const r=this.toolCache.tools.find(n=>n.name===t);if(r?.annotations)return r.annotations}if(this.mcpEnhancementsConfig?.annotations?.autoInfer!==!1)return mp({name:t,description:""})}invalidateToolCache(){this.toolCache=null,f.debug("Tool cache invalidated")}async getAllAvailableTools(){if(this.toolCache&&Date.now()-this.toolCache.timestamp<this.toolCacheDuration)return f.debug("Returning available tools from cache"),this.toolCache.tools;const t=`get-all-tools-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,r=Date.now(),n=process.hrtime.bigint();f.debug("[NeuroLink] \u{1F6E0}\uFE0F LOG_POINT_A001_GET_ALL_TOOLS_START",{logPoint:"A001_GET_ALL_TOOLS_START",getAllToolsId:t,timestamp:new Date().toISOString(),getAllToolsStartTime:r,getAllToolsHrTimeStart:n.toString(),toolRegistryState:{hasToolRegistry:!!this.toolRegistry,toolRegistrySize:0,toolRegistryType:this.toolRegistry?.constructor?.name||"NOT_SET",hasExternalServerManager:!!this.externalServerManager,externalServerManagerType:this.externalServerManager?.constructor?.name||"NOT_SET"},mcpState:{mcpInitialized:this.mcpInitialized,hasProviderRegistry:!!po,providerRegistrySize:0},message:"Starting comprehensive tool discovery across all sources"});const{MemoryManager:o}=await Promise.resolve().then(()=>(Dx(),dw)),s=o.getMemoryUsageMB();try{const i=new Map,a=await this.toolRegistry.listTools();for(const y of a)if(!i.has(y.name)){const v=ZP(y,{serverId:y.serverId==="direct"?"neurolink-direct":y.serverId});i.set(y.name,v)}const l=this.toolRegistry.getToolsByCategory(Ia({isCustomTool:!0}));for(const y of l)if(!i.has(y.name)){const v=ZP(y,{description:"Custom tool",serverId:`custom-tool-${y.name}`,category:Ia({isCustomTool:!0,serverId:y.serverId}),inputSchema:{}});i.set(y.name,v)}const c=this.toolRegistry.getToolsByCategory("in-memory");for(const y of c)if(!i.has(y.name)){const v=ZP(y,{description:"In-memory MCP tool",serverId:"unknown",category:"in-memory",inputSchema:{}});i.set(y.name,v)}const u=this.externalServerManager.getAllTools();for(const y of u)if(!i.has(y.name)){const v=ZP(y,{category:Ia({existingCategory:typeof y.metadata?.category=="string"?y.metadata.category:void 0,isExternal:!0,serverId:y.serverId}),inputSchema:{}});i.set(y.name,v)}const d=Array.from(i.values());de.debug("Tool discovery results",{mcpTools:a.length,customTools:l.length,inMemoryTools:c.length,externalMCPTools:u.length,total:d.length});const h=o.getMemoryUsageMB().heapUsed-s.heapUsed;if(h>cm.LOW_USAGE_MB&&(de.debug(`\u{1F50D} Tool listing used ${h}MB memory (large tool registry detected)`),d.length>mme.LARGE_TOOL_COLLECTION&&de.debug("\u{1F4A1} Tool collection optimized for large sets. Memory usage reduced through efficient object reuse.")),this.mcpEnhancementsConfig?.annotations?.autoInfer!==!1)for(const y of d)y.annotations||(y.annotations=mp({name:y.name,description:y.description||""}));const g=d.sort((y,v)=>y.name<v.name?-1:y.name>v.name?1:0);return this.toolCache={tools:g,timestamp:Date.now()},g}catch(i){return de.error("Failed to list available tools",{error:i}),[]}}async getProviderStatus(t){const{MemoryManager:r}=await Promise.resolve().then(()=>(Dx(),dw)),n=r.getMemoryUsageMB();t?.quiet||de.debug("\u{1F50D} DEBUG: Initializing MCP for provider status..."),await this.initializeMCP(),t?.quiet||de.debug("\u{1F50D} DEBUG: MCP initialized:",this.mcpInitialized);const{AIProviderFactory:o}=await Promise.resolve().then(()=>(Gl(),iA)),{hasProviderEnvVars:s}=await Promise.resolve().then(()=>(Th(),Px)),i=zr.getAllDescriptors().map(m=>m.name),a=IC(Va.DEFAULT_CONCURRENCY_LIMIT),l=i.map(m=>a(async()=>{const h=Date.now();try{if(!await this.hasProviderEnvVars(m)&&m!=="ollama")return{provider:m,status:"not-configured",configured:!1,authenticated:!1,error:"Missing required environment variables",responseTime:Date.now()-h};if(m==="ollama")try{const b=await fetch("http://localhost:11434/api/tags",{method:"GET",signal:AbortSignal.timeout(rc.AUTH_MS)});if(!b.ok)throw new Error("Ollama service not responding");const T=await b.json(),k=T?.models;if(!Array.isArray(k))throw f.warn("Ollama API returned invalid models format in testProvider",{responseData:T,modelsType:typeof k}),new Error("Invalid models format from Ollama API");const x=k.filter(I=>I&&typeof I=="object"&&typeof I.name=="string");return x.length>0?{provider:m,status:"working",configured:!0,authenticated:!0,responseTime:Date.now()-h,model:x[0].name}:{provider:m,status:"failed",configured:!0,authenticated:!1,error:"Ollama service running but no models installed",responseTime:Date.now()-h}}catch(b){return{provider:m,status:"failed",configured:!1,authenticated:!1,error:b instanceof Error?b.message:"Ollama service not running",responseTime:Date.now()-h}}const y=5e3,v=this.testProviderConnection(m),_=new Promise((b,T)=>{setTimeout(()=>T(new Error("Provider test timeout (5s)")),y)});return await Promise.race([v,_]),{provider:m,status:"working",configured:!0,authenticated:!0,responseTime:Date.now()-h}}catch(g){const y=g instanceof Error?g.message:String(g);return{provider:m,status:"failed",configured:!0,authenticated:!1,error:y,responseTime:Date.now()-h}}})),c=await Promise.all(l),d=r.getMemoryUsageMB().heapUsed-n.heapUsed;return!t?.quiet&&d>20&&de.debug(`\u{1F50D} Memory usage: +${d}MB (consider cleanup for large operations)`),d>50&&r.forceGC(),c}async testProvider(t){try{return await this.testProviderConnection(t),!0}catch{return!1}}async testProviderConnection(t){const{AIProviderFactory:r}=await Promise.resolve().then(()=>(Gl(),iA));await(await r.createProvider(t,null)).generate({prompt:"test",maxTokens:1,disableTools:!0})}async getBestProvider(t){const{getBestProvider:r}=await Promise.resolve().then(()=>(Th(),Px));return r(t)}async getAvailableProviders(){const{getAvailableProviders:t}=await Promise.resolve().then(()=>(Th(),Px));return t()}async isValidProvider(t){const{isValidProvider:r}=await Promise.resolve().then(()=>(Th(),Px));return r(t)}async getMCPStatus(){try{await this.initializeMCP();const t=await this.toolRegistry.listTools(),r=this.externalServerManager.getStatistics(),n=this.externalServerManager.listServers(),o=this.getInMemoryServerInfos(),s=this.toolRegistry.getBuiltInServerInfos(),i=this.getAutoDiscoveredServerInfos(),a=n.length+o.length+s.length+i.length,l=r.connectedServers+o.length+s.length,c=t.length+r.totalTools;return{mcpInitialized:this.mcpInitialized,totalServers:a,availableServers:l,autoDiscoveredCount:i.length,totalTools:c,autoDiscoveredServers:i,customToolsCount:this.toolRegistry.getToolsByCategory(Ia({isCustomTool:!0})).length,inMemoryServersCount:o.length,externalMCPServersCount:n.length,externalMCPConnectedCount:r.connectedServers,externalMCPFailedCount:r.failedServers,externalMCPServers:n}}catch(t){return{mcpInitialized:!1,totalServers:0,availableServers:0,autoDiscoveredCount:0,totalTools:0,autoDiscoveredServers:[],customToolsCount:this.toolRegistry.getToolsByCategory(Ia({isCustomTool:!0})).length,inMemoryServersCount:0,externalMCPServersCount:0,externalMCPConnectedCount:0,externalMCPFailedCount:0,externalMCPServers:[],error:t instanceof Error?t.message:String(t)}}}async listMCPServers(){return[...this.externalServerManager.listServers(),...this.getInMemoryServerInfos(),...this.toolRegistry.getBuiltInServerInfos(),...this.getAutoDiscoveredServerInfos()]}async testMCPServer(t){try{if(t==="neurolink-direct")return(await this.toolRegistry.listTools()).length>0;const r=this.getInMemoryServers();if(r.has(t)){const o=r.get(t);return!!(o?.tools&&o.tools.length>0)}const n=this.externalServerManager.getServer(t);return n?n.status==="connected"&&n.client!==null:!1}catch(r){return de.error(`[NeuroLink] Error testing MCP server ${t}:`,r),!1}}async hasProviderEnvVars(t){const{ProviderHealthChecker:r}=await Promise.resolve().then(()=>(gy(),iw));try{const n=await r.checkProviderHealth(t,{includeConnectivityTest:!1,cacheResults:!1});return n.isConfigured&&n.hasApiKey}catch(n){return f.warn(`Provider env var check failed for ${t}`,{error:n instanceof Error?n.message:String(n)}),!1}}async checkProviderHealth(t,r={}){const{ProviderHealthChecker:n}=await Promise.resolve().then(()=>(gy(),iw)),o=await n.checkProviderHealth(t,r);return{provider:o.provider,isHealthy:o.isHealthy,isConfigured:o.isConfigured,hasApiKey:o.hasApiKey,lastChecked:o.lastChecked,error:o.error,warning:o.warning,responseTime:o.responseTime,configurationIssues:o.configurationIssues,recommendations:o.recommendations}}async checkAllProvidersHealth(t={}){const{ProviderHealthChecker:r}=await Promise.resolve().then(()=>(gy(),iw));return(await r.checkAllProvidersHealth(t)).map(o=>({provider:o.provider,isHealthy:o.isHealthy,isConfigured:o.isConfigured,hasApiKey:o.hasApiKey,lastChecked:o.lastChecked,error:o.error,warning:o.warning,responseTime:o.responseTime,configurationIssues:o.configurationIssues,recommendations:o.recommendations}))}async getProviderHealthSummary(){const{ProviderHealthChecker:t}=await Promise.resolve().then(()=>(gy(),iw)),r=await t.checkAllProvidersHealth({cacheResults:!0,includeConnectivityTest:!1}),n=t.getHealthSummary(r),o=[];return n.healthy===0?o.push("No providers are healthy. Check your environment configuration."):n.healthy<2&&o.push("Consider configuring additional providers for better reliability."),n.hasIssues>0&&o.push("Some providers have configuration issues. Run checkAllProvidersHealth() for details."),{...n,recommendations:o}}async clearProviderHealthCache(t){const{ProviderHealthChecker:r}=await Promise.resolve().then(()=>(gy(),iw));r.clearHealthCache(t)}getToolExecutionMetrics(){const t={};for(const[r,n]of this.toolExecutionMetrics.entries())t[r]={...n,errorCategories:{...n.errorCategories},successRate:n.totalExecutions>0?n.successfulExecutions/n.totalExecutions:0};return t}setModelAliasConfig(t){this.modelAliasConfig=t,f.info(`[ModelAlias] Configured ${Object.keys(t.aliases).length} model aliases`)}getToolCircuitBreakerStatus(){const t={};for(const[r,n]of this.toolCircuitBreakers.entries())t[r]={state:n.getState(),failureCount:n.getFailureCount(),isHealthy:n.getState()==="closed"};return t}resetToolCircuitBreaker(t){this.toolCircuitBreakers.has(t)&&(this.toolCircuitBreakers.set(t,new j1(jI.FAILURE_THRESHOLD,V3)),de.info(`Circuit breaker reset for tool: ${t}`))}clearToolExecutionMetrics(){this.toolExecutionMetrics.clear(),de.info("All tool execution metrics cleared")}async getToolHealthReport(){const t={};let r=0;const n=await this.toolRegistry.listTools(),o=new Set(n.map(i=>i.name)),s=new Map;for(const i of n)s.has(i.name)||s.set(i.name,i.serverId||"unknown");for(const i of o){const a=this.toolExecutionMetrics.get(i),l=`${s.get(i)||"unknown"}.${i}`,c=this.toolCircuitBreakers.get(l),u=a&&a.totalExecutions>0?a.successfulExecutions/a.totalExecutions:0,d=(!c||c.getState()==="closed")&&u>=.8;d&&r++;const m=[],h=[];if(c&&c.getState()==="open"&&(m.push("Circuit breaker is open due to repeated failures"),h.push("Check tool implementation and fix underlying issues")),u<.8&&a&&a.totalExecutions>0&&(m.push(`Low success rate: ${(u*100).toFixed(1)}%`),h.push("Review error logs and improve tool reliability")),a&&a.averageExecutionTime>1e4&&(m.push("High average execution time"),h.push("Optimize tool performance or increase timeout")),a&&a.errorCategories){const g=a.errorCategories;g.timeout>0&&(m.push(`Timeout errors: ${g.timeout}`),h.push("Consider increasing the tool timeout configuration")),g.validation>0&&(m.push(`Validation errors: ${g.validation}`),h.push("Review input schemas and parameter validation")),g.network>0&&(m.push(`Network errors: ${g.network}`),h.push("Check network connectivity and endpoint availability"))}t[i]={name:i,isHealthy:d,metrics:{totalExecutions:a?.totalExecutions||0,successRate:u,averageExecutionTime:a?.averageExecutionTime||0,lastExecutionTime:a?.lastExecutionTime||0,errorCategories:a?.errorCategories?{...a.errorCategories}:{}},circuitBreaker:{state:c?.getState()||"closed",failureCount:c?.getFailureCount()||0},issues:m,recommendations:h}}return{totalTools:o.size,healthyTools:r,unhealthyTools:o.size-r,tools:t}}async ensureConversationMemoryInitialized(){try{const t=`manual-init-${Date.now()}`;return await this.initializeConversationMemoryForGeneration(t,Date.now(),process.hrtime.bigint()),!!this.conversationMemory}catch(t){return f.error("Failed to initialize conversation memory",{error:t instanceof Error?t.message:String(t)}),!1}}async getConversationStats(){const t=`stats-init-${Date.now()}`;if(await this.initializeConversationMemoryForGeneration(t,Date.now(),process.hrtime.bigint()),!this.conversationMemory)throw new Ne({code:Xe.MISSING_CONFIGURATION,message:"Conversation memory is not enabled",category:"validation",severity:"high",retriable:!1});return await this.conversationMemory.getStats()}async getConversationHistory(t){const r=`history-init-${Date.now()}`;if(await this.initializeConversationMemoryForGeneration(r,Date.now(),process.hrtime.bigint()),!this.conversationMemory)throw new Ne({code:Xe.MISSING_CONFIGURATION,message:"Conversation memory is not enabled",category:"validation",severity:"high",retriable:!1});if(!t||typeof t!="string")throw new Ne({code:Xe.INVALID_PARAMETERS,message:"Session ID must be a non-empty string",category:"validation",severity:"medium",retriable:!1,context:{sessionId:t}});try{const n=await this.conversationMemory.buildContextMessages(t);return f.debug("Retrieved conversation history",{sessionId:t,messageCount:n.length,turnCount:n.length/2}),n}catch(n){return f.error("Failed to retrieve conversation history",{sessionId:t,error:n instanceof Error?n.message:String(n)}),[]}}async clearConversationSession(t){const r=`clear-session-init-${Date.now()}`;if(await this.initializeConversationMemoryForGeneration(r,Date.now(),process.hrtime.bigint()),!this.conversationMemory)throw new Ne({code:Xe.MISSING_CONFIGURATION,message:"Conversation memory is not enabled",category:"validation",severity:"high",retriable:!1});return this.lastCompactionMessageCount.delete(t),await this.conversationMemory.clearSession(t)}async clearAllConversations(){const t=`clear-all-init-${Date.now()}`;if(await this.initializeConversationMemoryForGeneration(t,Date.now(),process.hrtime.bigint()),!this.conversationMemory)throw new Ne({code:Xe.MISSING_CONFIGURATION,message:"Conversation memory is not enabled",category:"validation",severity:"high",retriable:!1});this.lastCompactionMessageCount.clear(),await this.conversationMemory.clearAllSessions()}async listSessions(t){const r=`list-sessions-init-${Date.now()}`;if(await this.initializeConversationMemoryForGeneration(r,Date.now(),process.hrtime.bigint()),!this.conversationMemory)throw new Error("Conversation memory is not enabled");if(!this.conversationMemory.listSessions)return f.warn("listSessions not available on current memory manager"),[];const n=3e4;try{const o=await Ze(this.conversationMemory.listSessions(t),n,new Error("listSessions operation timed out after 30s"));return f.debug("Listed conversation sessions",{userId:t,sessionCount:o.length}),o}catch(o){return f.error("Failed to list conversation sessions",{userId:t,error:o instanceof Error?o.message:String(o)}),[]}}async exportSession(t,r={}){const n=`export-session-init-${Date.now()}`;if(await this.initializeConversationMemoryForGeneration(n,Date.now(),process.hrtime.bigint()),!this.conversationMemory)throw new Error("Conversation memory is not enabled");if(!t||typeof t!="string")throw new Error("Session ID must be a non-empty string");const o=3e4;try{const s=await Ze(this.conversationMemory.buildContextMessages(t),o,new Error("buildContextMessages operation timed out after 30s"));if(s.length===0)return f.debug("No messages found for session export",{sessionId:t}),null;const i=this.conversationMemory.getSession(t),a=await Ze(i instanceof Promise?i:Promise.resolve(i),o,new Error("getSession operation timed out after 30s")),l=new Date().toISOString(),c={sessionId:t,title:t,userId:a?.userId,createdAt:a?.createdAt?new Date(a.createdAt).toISOString():l,updatedAt:a?.lastActivity?new Date(a.lastActivity).toISOString():l,messages:s};return r.includeMetadata&&(c.exportMetadata={exportedAt:l,exportFormat:r.format||"json"}),f.debug("Exported conversation session",{sessionId:t,messageCount:s.length}),c}catch(s){return f.error("Failed to export conversation session",{sessionId:t,error:s instanceof Error?s.message:String(s)}),null}}async exportAllSessions(t,r={}){const n=`export-all-init-${Date.now()}`;if(await this.initializeConversationMemoryForGeneration(n,Date.now(),process.hrtime.bigint()),!this.conversationMemory)throw new Error("Conversation memory is not enabled");const o=3e4,s=6e4;try{const i=await Ze(this.listSessions(t),o,new Error("listSessions operation timed out after 30s")),a=[];for(const l of i){const c=await Ze(this.exportSession(l.id,r),s,new Error(`exportSession operation timed out after 60s for session ${l.id}`));c&&a.push(c)}return f.debug("Exported all conversation sessions",{userId:t,sessionCount:a.length}),a}catch(i){return f.error("Failed to export all conversation sessions",{userId:t,error:i instanceof Error?i.message:String(i)}),[]}}async storeToolExecutions(t,r,n,o,s){const i=n&&n.length>0||o&&o.length>0;if(!i){f.debug("Tool execution storage skipped",{hasToolData:i,toolCallsCount:n?.length||0,toolResultsCount:o?.length||0});return}const a=this.conversationMemory;if(!a?.storeToolExecution){f.debug("Tool execution storage not supported by this memory backend");return}try{await a.storeToolExecution(t,r,n,o,s)}catch(l){f.warn("Failed to store tool executions",{sessionId:t,userId:r,error:l instanceof Error?l.message:String(l)})}}isToolExecutionStorageAvailable(){return typeof this.conversationMemory?.storeToolExecution=="function"}async getSessionMessages(t,r){const n=`get-msgs-init-${Date.now()}`;if(await this.initializeConversationMemoryForGeneration(n,Date.now(),process.hrtime.bigint()),!this.conversationMemory)throw new Ne({code:Xe.MISSING_CONFIGURATION,message:"Conversation memory is not enabled",category:"validation",severity:"high",retriable:!1});if(!t||typeof t!="string")throw new Ne({code:Xe.INVALID_PARAMETERS,message:"Session ID must be a non-empty string",category:"validation",severity:"medium",retriable:!1,context:{sessionId:t}});return await this.conversationMemory.getSessionMessages(t,r)}async setSessionMessages(t,r,n){const o=`set-msgs-init-${Date.now()}`;if(await this.initializeConversationMemoryForGeneration(o,Date.now(),process.hrtime.bigint()),!this.conversationMemory)throw new Ne({code:Xe.MISSING_CONFIGURATION,message:"Conversation memory is not enabled",category:"validation",severity:"high",retriable:!1});if(!t||typeof t!="string")throw new Ne({code:Xe.INVALID_PARAMETERS,message:"Session ID must be a non-empty string",category:"validation",severity:"medium",retriable:!1,context:{sessionId:t}});await this.conversationMemory.setSessionMessages(t,r,n)}async modifyLastAssistantMessage(t,r,n){const o=await this.getSessionMessages(t,n);for(let s=o.length-1;s>=0;s--)if(o[s].role==="assistant")return o[s]={...o[s],content:r(o[s].content)},await this.setSessionMessages(t,o,n),!0;return!1}async addExternalMCPServer(t,r){this.invalidateToolCache();try{de.info(`[NeuroLink] Adding external MCP server: ${t}`,{command:r.command,transport:r.transport});const n=await this.externalServerManager.addServer(t,r);if(n.success){if(de.info(`[NeuroLink] External MCP server added successfully: ${t}`,{toolsDiscovered:n.metadata?.toolsDiscovered||0,duration:n.duration}),this.mcpEnhancementsConfig?.router?.enabled!==!1){const o=this.externalServerManager.listServers();if(o.length>=2&&!this.mcpToolRouter){this.mcpToolRouter=new o2({strategy:this.mcpEnhancementsConfig?.router?.strategy??"least-loaded",enableAffinity:this.mcpEnhancementsConfig?.router?.enableAffinity??!1});for(const s of o)this.mcpToolRouter.registerServer(s.id||t);f.debug("[NeuroLink] ToolRouter auto-initialized (2+ external servers)")}else this.mcpToolRouter&&this.mcpToolRouter.registerServer(t)}this.emitter.emit("externalMCP:serverAdded",{serverId:t,serverName:r.name||t,config:r,toolCount:n.metadata?.toolsDiscovered||0,timestamp:Date.now()})}else de.error(`[NeuroLink] Failed to add external MCP server: ${t}`,{error:n.error,transport:r.transport,command:r.command,url:r.url?to(r.url):void 0});return n}catch(n){throw de.error(`[NeuroLink] Error adding external MCP server: ${t}`,n),n}}async removeExternalMCPServer(t){this.invalidateToolCache();try{de.info(`[NeuroLink] Removing external MCP server: ${t}`);const r=this.externalServerManager.getServerName(t),n=await this.externalServerManager.removeServer(t);return n.success?(de.info(`[NeuroLink] External MCP server removed successfully: ${t}`),this.emitter.emit("externalMCP:serverRemoved",{serverId:t,serverName:r,timestamp:Date.now()})):n.error?.includes("not found")?de.debug(`[NeuroLink] Remove skipped \u2014 external MCP server not registered: ${t}`):de.error(`[NeuroLink] Failed to remove external MCP server: ${t}`,{error:n.error}),n}catch(r){throw de.error(`[NeuroLink] Error removing external MCP server: ${t}`,r),r}}listExternalMCPServers(){const t=this.externalServerManager.getServerStatuses(),r=this.externalServerManager.listServers();return t.map(n=>{const o=r.find(s=>s.id===n.serverId);return{serverId:n.serverId,status:n.status,toolCount:n.toolCount,uptime:n.performance.uptime,isHealthy:n.isHealthy,config:o||{}}})}getExternalMCPServer(t){return this.externalServerManager.getServer(t)}async executeExternalMCPTool(t,r,n,o){let s=r;try{s=this.resolveDirectMcpToolName(t,r),de.debug(`[NeuroLink] Executing external MCP tool: ${s} on ${t}`);const i=this.getToolAnnotationsForExecution(s),a=!!this.mcpToolResultCache&&!this._disableToolCacheForCurrentRequest&&!i?.destructiveHint,l={__serverId:t,__args:n,...this.toolExecutionContext?{__ctx:this.toolExecutionContext}:{}},c=this._generationTurnActive?this.toolCacheRepeatKey(s,l):void 0,u=c!==void 0&&this._toolCacheKeysServedThisRequest.has(c);if(c!==void 0&&this._toolCacheKeysServedThisRequest.add(c),a&&this.mcpToolResultCache&&!u){const g=this.mcpToolResultCache.getCachedResult(s,l);if(g!==void 0)return de.debug(`[NeuroLink] Tool result cache HIT: ${s} on ${t}`),g}const d=await this.externalServerManager.executeTool(t,s,n,o),m=d&&typeof d=="object"?d:void 0,h=!!(m&&"isError"in m&&m.isError===!0||m&&"success"in m&&m.success===!1);return a&&this.mcpToolResultCache&&!h&&d!==void 0&&this.mcpToolResultCache.cacheResult(s,l,d),de.debug(`[NeuroLink] External MCP tool ${h?"returned error":"executed successfully"}: ${s}`),d}catch(i){throw de.error(`[NeuroLink] External MCP tool execution failed: ${s}`,i),i}}resolveDirectMcpToolName(t,r){const n=this.getExternalMCPServer(t);if(!n||n.status!=="connected"||!n.client)return r;const o=this.getExternalMCPServerTools(t).map(i=>i.name);if(o.includes(r))return r;const s=X9(r,o);if(!s)throw new eW(r,t,E9e(r,o));return He.mcp.startActiveSpan("neurolink.mcp.toolNameRepair",{attributes:{"mcp.server_id":t,"mcp.tool_name.requested":r,"mcp.tool_name.resolved":s.name,"mcp.tool_name.repair_strategy":s.strategy,...s.score!==void 0?{"mcp.tool_name.repair_score":s.score}:{}}},i=>i.end()),de.info(`[NeuroLink] Repaired external MCP tool name at direct execution boundary: "${r}" \u2192 "${s.name}" (${s.strategy}) on server '${t}'`),s.name}getExternalMCPTools(){return this.externalServerManager.getAllTools()}getExternalMCPServerTools(t){return this.externalServerManager.getServerTools(t)}async testExternalMCPConnection(t){try{const{MCPClientFactory:r}=await Ze(Promise.resolve().then(()=>(ire(),JNt)),1e4),n=await r.testConnection(t,1e4);return{success:n.success,error:n.error,toolCount:n.capabilities?1:0}}catch(r){return{success:!1,error:r instanceof Error?r.message:String(r)}}}getExternalMCPStatistics(){return this.externalServerManager.getStatistics()}async shutdownExternalMCPServers(){try{de.info("[NeuroLink] Shutting down all external MCP servers..."),this.unregisterAllExternalMCPToolsFromRegistry(),await this.externalServerManager.shutdown(),de.info("[NeuroLink] All external MCP servers shut down successfully")}catch(t){throw de.error("[NeuroLink] Error shutting down external MCP servers:",t),t}}async getElicitationManager(){return(await Ze(Promise.resolve().then(()=>(FBt(),$Bt)),1e4)).globalElicitationManager}async registerElicitationHandler(t){(await this.getElicitationManager()).registerHandler(t)}async getMultiServerManager(){return(await Ze(Promise.resolve().then(()=>(tte(),fDt)),1e4)).globalMultiServerManager}async getEnhancedToolDiscovery(){const t=await Ze(Promise.resolve().then(()=>(rte(),gDt)),1e4);return new t.EnhancedToolDiscovery(this.toolRegistry)}async getMCPRegistryClient(){return(await Ze(Promise.resolve().then(()=>(jBt(),UBt)),1e4)).globalMCPRegistryClient}async exposeAgentAsTool(t,r){return(await Ze(Promise.resolve().then(()=>(Lse(),Ose)),1e4)).exposeAgentAsTool(t,r)}async exposeWorkflowAsTool(t,r){return(await Ze(Promise.resolve().then(()=>(Lse(),Ose)),1e4)).exposeWorkflowAsTool(t,r)}async getToolIntegrationManager(){return(await Ze(Promise.resolve().then(()=>(JBt(),HBt)),1e4)).globalToolIntegrationManager}async convertToolsToMCPFormat(t,r={}){const n=await Ze(Promise.resolve().then(()=>(eO(),UY)),1e4),o=t.map(s=>({...s,execute:s.execute??(async()=>({success:!1,error:"No execute function provided"}))}));return n.batchConvertToMCP(o,r)}async convertToolsFromMCPFormat(t,r={}){return(await Ze(Promise.resolve().then(()=>(eO(),UY)),1e4)).batchConvertToNeuroLink(t,r)}async getToolAnnotations(t){const{inferAnnotations:r,mergeAnnotations:n,getAnnotationSummary:o}=await Ze(Promise.resolve().then(()=>(PC(),aTt)),1e4),s=this.toolRegistry.getToolInfo(t);if(!s)return null;const i=s.tool.annotations,a=r({name:s.tool.name,description:s.tool.description??""}),l=n(a,i);return{annotations:l,summary:o(l)}}convertExternalMCPToolsToAISDKFormat(){const t=this.externalServerManager.getAllTools(),r={};for(const n of t)if(n.isAvailable){const o={description:n.description,execute:async s=>{try{de.debug(`[NeuroLink] Executing external MCP tool via AI SDK: ${n.name}`,{params:s});const i=await this.externalServerManager.executeTool(n.serverId,n.name,s,{timeout:3e4});return de.debug(`[NeuroLink] External MCP tool execution result: ${n.name}`,{success:!!i,hasData:!!(i&&typeof i=="object"&&"content"in i)}),i}catch(i){throw de.error(`[NeuroLink] External MCP tool execution failed: ${n.name}`,i),i}}};r[n.name]=o,de.debug(`[NeuroLink] Converted external MCP tool to AI SDK format: ${n.name} from server ${n.serverId}`)}return de.info(`[NeuroLink] Converted ${Object.keys(r).length} external MCP tools to AI SDK format`),r}convertJSONSchemaToAISDKFormat(t){}unregisterExternalMCPToolsFromRegistry(t){try{const r=this.externalServerManager.getServerTools(t);for(const n of r)this.toolRegistry.removeTool(n.name),de.debug(`[NeuroLink] Unregistered external MCP tool from main registry: ${n.name}`)}catch(r){de.error(`[NeuroLink] Failed to unregister external MCP tools from registry for server ${t}:`,r)}}unregisterExternalMCPToolFromRegistry(t){try{this.toolRegistry.removeTool(t),de.debug(`[NeuroLink] Unregistered external MCP tool from main registry: ${t}`)}catch(r){de.error(`[NeuroLink] Failed to unregister external MCP tool ${t} from registry:`,r)}}async lazyInitializeConversationMemory(t,r,n){try{const{initializeConversationMemory:o}=await LWr().then(()=>XBt),s=await o(this.conversationMemoryConfig);this.conversationMemory=s,this.conversationMemoryNeedsInit=!1}catch(o){throw f.error("[NeuroLink] \u274C LOG_POINT_G005_MEMORY_LAZY_INIT_ERROR",{logPoint:"G005_MEMORY_LAZY_INIT_ERROR",generateInternalId:t,timestamp:new Date().toISOString(),elapsedMs:Date.now()-r,elapsedNs:(process.hrtime.bigint()-n).toString(),error:o instanceof Error?o.message:String(o),errorName:o instanceof Error?o.name:"UnknownError",errorStack:o instanceof Error?o.stack:void 0,message:"Lazy conversation memory initialization failed"}),o}}unregisterAllExternalMCPToolsFromRegistry(){try{const t=this.externalServerManager.getAllTools();for(const r of t)this.toolRegistry.removeTool(r.name);de.debug(`[NeuroLink] Unregistered ${t.length} external MCP tools from main registry`)}catch(t){de.error("[NeuroLink] Failed to unregister all external MCP tools from registry:",t)}}async createEvaluationPipeline(t){const{EvaluationPipeline:r,getPreset:n}=await Ze(Promise.resolve().then(()=>(mS(),pS)),1e4,ke.evaluationTimeout("evaluation module load",1e4));let o;typeof t=="string"?o=n(t):o=t;const s=new r(o);return await Ze(s.initialize(),3e4,ke.evaluationTimeout("pipeline initialization",3e4)),f.debug(`[NeuroLink] Created evaluation pipeline: ${o.name??"custom"}`),s}async evaluate(t,r){const{EvaluationPipeline:n,getPreset:o}=await Ze(Promise.resolve().then(()=>(mS(),pS)),1e4,ke.evaluationTimeout("evaluation module load",1e4));let s;if(r?.pipeline&&r?.scorers)throw new Error("Cannot specify both 'pipeline' and 'scorers' options. Use one or the other.");if(r?.scorers&&r.scorers.length===0)throw new Error("The 'scorers' array must not be empty. Provide at least one scorer ID or omit the option to use the default 'quality' preset.");r?.pipeline?s={...o(r.pipeline)}:r?.scorers&&r.scorers.length>0?s={name:"SDK Evaluation",description:"Evaluation from NeuroLink SDK",scorers:r.scorers.map(c=>({id:c})),executionMode:r.executionMode??"parallel",passThreshold:r.passThreshold??.7}:s=o("quality"),r?.passThreshold!==void 0&&(s.passThreshold=r.passThreshold),r?.executionMode!==void 0&&(s.executionMode=r.executionMode);const i=new n(s);await Ze(i.initialize(),3e4,ke.evaluationTimeout("pipeline initialization",3e4));const a=r?.timeoutMs??6e4,l=await Ze(i.execute(t,{correlationId:r?.correlationId}),a,ke.evaluationTimeout("pipeline execution",a));return f.debug("[NeuroLink] Evaluation completed",{pipeline:s.name,overallScore:l.overallScore,passed:l.passed,scorerCount:l.scores.length}),l}async score(t,r,n){const{ScorerRegistry:o}=await Ze(Promise.resolve().then(()=>(aV(),iV)),1e4,ke.evaluationTimeout("scorer module load",1e4));await Ze(o.registerBuiltInScorers(),3e4,ke.evaluationTimeout("scorer bootstrap",3e4));const s=await Ze(o.getScorer(t,n),3e4,ke.evaluationTimeout(`scorer load: ${t}`,3e4));if(!s)throw ke.scorerNotFound(t);const i=s.validateInput(r);if(!i.valid)throw ke.evaluationValidationFailed(t,i.errors);const a=await Ze(s.score(r),6e4,ke.evaluationTimeout("scorer execution",6e4));return f.debug("[NeuroLink] Scoring completed",{scorerId:t,score:a.score,passed:a.passed,computeTime:a.computeTime}),a}async getAvailableScorers(t){const{ScorerRegistry:r}=await Ze(Promise.resolve().then(()=>(aV(),iV)),1e4,ke.evaluationTimeout("scorer module load",1e4));await Ze(r.registerBuiltInScorers(),3e4,ke.evaluationTimeout("scorer bootstrap",3e4));let n=r.list();return t?.category&&(n=n.filter(o=>o.category===t.category)),t?.type&&(n=n.filter(o=>o.type===t.type)),n}async getEvaluationPresets(){const{getPresetNames:t}=await Ze(Promise.resolve().then(()=>(mS(),pS)),1e4,ke.evaluationTimeout("evaluation module load",1e4));return t()}async getEvaluationPreset(t){const{getPreset:r}=await Ze(Promise.resolve().then(()=>(mS(),pS)),1e4,ke.evaluationTimeout("evaluation module load",1e4));return r(t)}async createAgent(t){const{Agent:r}=await Promise.resolve().then(()=>(jse(),QBt));return f.debug("[NeuroLink] Creating agent",{id:t.id,name:t.name,tools:t.tools?.length||0}),new r(t,this)}async createNetwork(t){const{AgentNetwork:r}=await Promise.resolve().then(()=>(tzt(),ezt));return f.debug("[NeuroLink] Creating agent network",{name:t.name,agentCount:t.agents.length,workflowCount:t.workflows?.length||0,toolCount:t.tools?.length||0}),new r(t,this)}createWorkerInstance(t){const r=t?.logTag??"worker",n=this.emitter,o=t?.config??{},s={...this.credentials?{credentials:this.credentials}:{},...o,conversationMemory:{enabled:!1},enableOrchestration:!1,observability:{...this.observabilityConfig??{},langfuse:{...this.observabilityConfig?.langfuse??{},autoDetectExternalProvider:!0,skipLangfuseSpanProcessor:!0}},...t?.shareToolRegistry!==!1&&{toolRegistry:this.toolRegistry}},i=new a3(s);if(t?.shareToolRegistry!==!1)for(const a of this.uncacheableTools)i.uncacheableTools.add(a);if(f.setEventEmitter(n),t?.onLog){const a=t.onLog,l=u=>{try{const d=u??{};a({tag:r,level:String(d.level??"info"),message:String(d.message??""),timestamp:typeof d.timestamp=="number"?d.timestamp:Date.now(),data:d.data})}catch{}};n.on("log-event",l);const c=i.dispose.bind(i);i.dispose=async()=>{n.off("log-event",l),await c()}}return f.debug("[NeuroLink] Created worker instance",{tag:r,sharedToolRegistry:t?.shareToolRegistry!==!1}),i}async runIsolatedAgent(t,r,n){const{runIsolatedAgent:o}=await Promise.resolve().then(()=>(bx(),c2));return o(this,t,r,n)}async continueAgent(t,r){const{continueIsolatedAgent:n}=await Promise.resolve().then(()=>(bx(),c2));return n(this,t,r)}async stopAgent(t){const{stopIsolatedAgent:r}=await Promise.resolve().then(()=>(bx(),c2));return r(this,t)}async registerAgentTool(t,r){const{registerAgentTool:n}=await Promise.resolve().then(()=>(Ex(),m2)),o=n(this,t,r);return this.hasAgentTools=!0,o}registerTaskTools(){if(this.hasTaskChecklistTools)return;const t=_8r(this);for(const[r,n]of Object.entries(t))this.registerTool(r,n,{cacheable:!1});this.hasTaskChecklistTools=!0,f.info(`[NeuroLink] Registered ${Object.keys(t).length} task checklist tools`)}getTaskState(t){return f8r(t??ns(this))}clearTaskState(t){return g8r(t??ns(this))}registerDelegationTools(t){if(F8r(this,t),this.hasBackgroundDelegationTools)return;const r=K8r(this);for(const[n,o]of Object.entries(r))this.registerTool(n,o,{cacheable:!1});this.hasBackgroundDelegationTools=!0,f.info(`[NeuroLink] Registered ${Object.keys(r).length} background delegation tools`)}async spawnDelegate(t){return GFt(this,t)}async collectDelegates(t){return VFt(this,t)}async cancelDelegates(t){return Vne(this,t)}getArtifactStore(){return this.mcpArtifactStore||(this.mcpArtifactStore=this.createConfiguredArtifactStore()),this.registerMemoryRetrievalTools(),this.mcpArtifactStore}setArtifactStore(t){const r=this.mcpArtifactStore;r!==t&&(r&&(f.warn("[NeuroLink] Artifact store replaced \u2014 artifacts already written to the previous store will not resolve through this instance"),this.ownsArtifactStore&&r.close&&r.close().catch(n=>{f.warn("[NeuroLink] Previous artifact store close failed",{error:n instanceof Error?n.message:String(n)})})),this.mcpArtifactStore=t,this.ownsArtifactStore=!1,this.installOutputNormalizer(t),this.registerMemoryRetrievalTools())}createConfiguredArtifactStore(){const t=this.artifactsConfig?.store!==void 0,r=F2t(this.artifactsConfig,this.conversationMemoryConfig?.conversationMemory?.redisConfig);return this.ownsArtifactStore=!t,f.debug("[NeuroLink] Artifact store initialized",{backend:t?"custom":Ore(this.artifactsConfig)}),r}installOutputNormalizer(t){this.mcpOutputNormalizerConfig&&(this.externalServerManager.setOutputNormalizer(new bLt(this.mcpOutputNormalizerConfig,t)),f.debug("[NeuroLink] MCP output normalizer initialized",{...this.mcpOutputNormalizerConfig,hasArtifactStore:t!==void 0}))}async bankArtifact(t,r){return cGr(this,t,r)}async readArtifact(t,r){return uGr(this,t,r)}registerBackgroundCommandTools(t){if(e3t(this,t),this.hasBackgroundCommandTools)return;const r=sHr(this);for(const[n,o]of Object.entries(r))this.registerTool(n,o,{cacheable:!1});this.hasBackgroundCommandTools=!0,f.info(`[NeuroLink] Registered ${Object.keys(r).length} background command tools`)}setBackgroundCommandPolicy(t){e3t(this,t)}async startBackgroundCommand(t,r){return l3t(this,t,r)}getBackgroundCommandStatus(t){return c3t(this,t)}async awaitBackgroundCommand(t,r){return ioe(this,t,r)}async killBackgroundCommand(t,r){return u3t(this,t,r)}async readBackgroundCommandOutput(t,r){return E2(this,t,r)}registerGitTools(t){if(iHr(this,t),this.hasGitTools)return;const r=mHr(this);for(const[n,o]of Object.entries(r))this.registerTool(n,o,{cacheable:!1});this.hasGitTools=!0,f.info(`[NeuroLink] Registered ${Object.keys(r).length} read-only git tools`)}async runGitCommand(t,r){return E3t(this,t,r)}async executeNetwork(t,r,n){return f.debug("[NeuroLink] Executing agent network",{networkId:t.id,networkName:t.name,hasContext:!!r.context}),t.execute(r,n)}async*streamNetwork(t,r,n){f.debug("[NeuroLink] Streaming agent network",{networkId:t.id,networkName:t.name,hasContext:!!r.context}),yield*t.stream(r,n)}async createOrchestrator(t){const{NetworkOrchestrator:r}=await Promise.resolve().then(()=>(szt(),ozt));return f.debug("[NeuroLink] Creating network orchestrator",{maxConcurrentExecutions:t?.maxConcurrentExecutions,defaultMode:t?.defaultMode}),new r(this,t)}async createCoordinator(t){const{AgentCoordinator:r}=await Promise.resolve().then(()=>(azt(),izt));return f.debug("[NeuroLink] Creating agent coordinator",{strategy:t?.strategy,maxConcurrency:t?.maxConcurrency}),new r(t)}async createMessageBus(t){const{MessageBus:r}=await Promise.resolve().then(()=>(czt(),lzt));return f.debug("[NeuroLink] Creating message bus",{maxHistorySize:t?.maxHistorySize}),new r(t)}async dispose(){f.debug("[NeuroLink] Starting disposal of resources..."),this.lastCompactionMessageCount.clear();const t=[];try{try{await d3t(this),await Vne(this)}catch(r){const n=r instanceof Error?r:new Error(`Background work cleanup error: ${String(r)}`);t.push(n),f.warn("[NeuroLink] Error stopping background work:",r)}try{f.debug("[NeuroLink] Flushing and shutting down OpenTelemetry..."),await k4(),await x4(),f.debug("[NeuroLink] OpenTelemetry shutdown successfully")}catch(r){const n=r instanceof Error?r:new Error(`OpenTelemetry shutdown error: ${String(r)}`);t.push(n),f.warn("[NeuroLink] Error shutting down OpenTelemetry:",r)}if(this.externalServerManager)try{f.debug("[NeuroLink] Shutting down external MCP servers..."),await this.externalServerManager.shutdown(),f.debug("[NeuroLink] External MCP servers shutdown successfully")}catch(r){const n=r instanceof Error?r:new Error(`External server shutdown error: ${String(r)}`);t.push(n),f.warn("[NeuroLink] Error shutting down external MCP servers:",r)}if(this.ownsArtifactStore&&this.mcpArtifactStore?.close)try{await this.mcpArtifactStore.close(),f.debug("[NeuroLink] Artifact store closed")}catch(r){const n=r instanceof Error?r:new Error(`Artifact store close error: ${String(r)}`);t.push(n),f.warn("[NeuroLink] Error closing artifact store:",r)}if(this.emitter)try{f.debug("[NeuroLink] Removing all event listeners..."),this.emitter.removeAllListeners(),f.clearEventEmitter(this.emitter),f.debug("[NeuroLink] Event listeners removed successfully")}catch(r){const n=r instanceof Error?r:new Error(`Event emitter cleanup error: ${String(r)}`);t.push(n),f.warn("[NeuroLink] Error removing event listeners:",r)}if(this.toolCircuitBreakers&&this.toolCircuitBreakers.size>0)try{f.debug(`[NeuroLink] Clearing ${this.toolCircuitBreakers.size} circuit breakers...`),this.toolCircuitBreakers.clear(),f.debug("[NeuroLink] Circuit breakers cleared successfully")}catch(r){const n=r instanceof Error?r:new Error(`Circuit breaker cleanup error: ${String(r)}`);t.push(n),f.warn("[NeuroLink] Error clearing circuit breakers:",r)}try{f.debug("[NeuroLink] Clearing maps and caches..."),this.toolExecutionMetrics&&this.toolExecutionMetrics.clear(),this.activeToolExecutions&&this.activeToolExecutions.clear(),this.currentStreamToolExecutions&&(this.currentStreamToolExecutions.length=0),this.toolExecutionHistory&&(this.toolExecutionHistory.length=0),this.toolCache&&(this.toolCache.tools=[],this.toolCache.timestamp=0),this.mcpToolResultCache?.destroy(),this.mcpToolRouter?.destroy(),this.mcpToolBatcher?.destroy(),this.mcpToolResultCache=void 0,this.mcpToolRouter=void 0,this.mcpToolBatcher=void 0,this.mcpEnhancedDiscovery=void 0,this.mcpToolMiddlewares=[],f.debug("[NeuroLink] Maps and caches cleared successfully")}catch(r){const n=r instanceof Error?r:new Error(`Cache cleanup error: ${String(r)}`);t.push(n),f.warn("[NeuroLink] Error clearing caches:",r)}if(this._taskManager)try{f.debug("[NeuroLink] Shutting down TaskManager..."),await Ze(this._taskManager.shutdown(),5e3,new Error("TaskManager shutdown timed out"))}catch(r){f.warn("[NeuroLink] TaskManager shutdown error:",r)}finally{this._taskManager=void 0}try{f.debug("[NeuroLink] Resetting initialization state..."),this.mcpInitialized=!1,this.mcpInitPromise=null,this.conversationMemoryNeedsInit=!1,this.credentials=void 0,f.debug("[NeuroLink] Initialization state reset successfully")}catch(r){const n=r instanceof Error?r:new Error(`State reset error: ${String(r)}`);t.push(n),f.warn("[NeuroLink] Error resetting state:",r)}t.length===0?f.debug("[NeuroLink] \u2705 Resource disposal completed successfully"):f.warn(`[NeuroLink] \u26A0\uFE0F Resource disposal completed with ${t.length} errors`,{errors:t.map(r=>r.message)})}catch(r){throw f.error("[NeuroLink] Critical error during disposal:",r),r}}getToolRegistry(){return this.toolRegistry}async compactSession(t,r){if(!this.conversationMemory)return null;const n=await this.conversationMemory.buildContextMessages(t);if(!n||n.length===0)return null;const o=new D_({...r,summarizationProvider:r?.summarizationProvider??this.conversationMemoryConfig?.conversationMemory?.summarizationProvider,summarizationModel:r?.summarizationModel??this.conversationMemoryConfig?.conversationMemory?.summarizationModel}),s=Aa({provider:r?.provider||"openai",conversationMessages:n}),i=Math.floor(s.availableInputTokens*.6),a=await o.compact(n,i,this.conversationMemoryConfig?.conversationMemory);return a.compacted&&M_(a.messages),a}async getContextStats(t,r,n){if(!this.conversationMemory)return null;const o=await this.conversationMemory.buildContextMessages(t);if(!o||o.length===0)return null;const s=Aa({provider:r||"openai",model:n,conversationMessages:o});return{estimatedInputTokens:s.estimatedInputTokens,availableInputTokens:s.availableInputTokens,usageRatio:s.usageRatio,shouldCompact:s.shouldCompact,messageCount:o.length}}needsCompaction(t,r,n){if(!this.conversationMemory)return!1;const o=this.conversationMemory.getSession?.(t);return o?Aa({provider:r||"openai",model:n,conversationMessages:o.messages}).shouldCompact:!1}async setAuthProvider(t){this.authInitPromise=void 0,await this.initializeAuthProviderFromConfig(t)}async initializeAuthProviderFromConfig(t){let r,n;if("authenticateToken"in t&&typeof t.authenticateToken=="function")r=t,n=r.type;else if("provider"in t)r=t.provider,n=r.type;else{const o=t,{AuthProviderFactory:s}=await Promise.resolve().then(()=>(d$(),uzt));r=await s.createProvider(o.type,o.config),n=o.type}this.authProvider=r,f.info(`Auth provider set: ${n}`),this.emitter.emit("auth:provider:set",{type:r.type,timestamp:Date.now()})}getAuthProvider(){return this.authProvider}async ensureAuthProvider(){if(this.authProvider||!this.pendingAuthConfig)return;const t=this.pendingAuthConfig;this.authInitPromise??=(async()=>{try{await this.initializeAuthProviderFromConfig(t),this.pendingAuthConfig=void 0}finally{this.authInitPromise&&(this.pendingAuthConfig===void 0||this.pendingAuthConfig===t)&&(this.authInitPromise=void 0)}})(),await this.authInitPromise}async setAuthContext(t){const{globalAuthContext:r}=await Promise.resolve().then(()=>(ox(),jL));r.set(t),f.debug("Auth context set",{userId:t.user.id,provider:t.provider,sessionId:t.session?.id})}async getAuthContext(){const{getAuthContext:t}=await Promise.resolve().then(()=>(ox(),jL));return t()}async clearAuthContext(){const{globalAuthContext:t}=await Promise.resolve().then(()=>(ox(),jL)),r=t.get()?.user.id;t.clear(),r&&f.debug(`Auth context cleared for user: ${r}`)}getExternalServerManager(){return this.externalServerManager}buildResolutionContext(t,r){return{requestContext:r||{},signal:t}}async resolveDynamicOptions(t){const r=["model","provider","temperature","maxTokens","systemPrompt","timeout","thinkingLevel","disableTools","enableAnalytics","enableEvaluation"];if(!(r.some(s=>typeof t[s]=="function")||typeof t.tools=="function"))return;const o=t.dynamicContext;await this.resolveDynamicFields(t,r,o)}async resolveDynamicFields(t,r,n){const o=this.buildResolutionContext(t.abortSignal,n);if(f.debug("[NeuroLink] Resolving dynamic arguments"),await Promise.all(r.map(async s=>{if(typeof t[s]=="function"){const i=await Ure(t[s],o);t[s]=i.value,f.debug(`[NeuroLink] Resolved dynamic ${s}: ${i.resolutionType}`)}})),typeof t.tools=="function"){const s=await Ure(t.tools,o);if(!Array.isArray(s.value))throw new TypeError(`Dynamic tools resolver must return string[] (tool names), got ${typeof s.value=="object"?"object":typeof s.value}`);t.enabledToolNames=s.value,delete t.tools}}},Xse=new Gx,mzt=Xse}}),hzt={};he(hzt,{VoyageProvider:()=>yzt});var fzt,Qse,gzt,m$,yzt,HWr=S({async"src/lib/providers/voyage.ts"(){"use strict";Tc(),await fd(),io(),yt(),at(),q(),ps(),fzt="https://api.voyageai.com/v1",Qse=6e4,gzt=()=>Yi(dwr()),m$=()=>Zi("VOYAGE_MODEL","voyage-3.5"),yzt=class extends Ol{apiKey;baseURL;proxyFetch;constructor(e,t,r,n){const o=by(t)?t:void 0;super(e,"voyage",o);const s=n?.apiKey?.trim();this.apiKey=s&&s.length>0?s:gzt(),this.baseURL=n?.baseURL??process.env.VOYAGE_BASE_URL??fzt,this.proxyFetch=zt(),f.debug("Voyage Provider initialized (embeddings only)",{modelName:this.modelName,baseURL:this.baseURL})}getProviderName(){return this.providerName}getDefaultModel(){return m$()}supportsTools(){return!1}getDefaultEmbeddingModel(){return m$()}getAISDKModel(){throw new _t("Voyage AI is an embedding-only provider; chat completions are not available. Use `embed()` or `embedMany()` instead, or pick a different provider for `generate()` / `stream()`.","voyage")}async executeStream(e,t){throw new _t("Voyage AI is an embedding-only provider; streaming chat is not available. Use `embed()` / `embedMany()`, or pick another provider for `stream()`.","voyage")}formatProviderError(e){const t=e instanceof Error?e.message:typeof e=="string"?e:"Unknown error";return t.includes("401")||t.toLowerCase().includes("unauthorized")||t.includes("invalid_api_key")?new Nr("Invalid Voyage AI API key. Get one at https://dash.voyageai.com/api-keys","voyage"):t.includes("429")||t.toLowerCase().includes("rate limit")?new Os("Voyage AI rate limit exceeded. Back off and retry.","voyage"):t.includes("404")||t.toLowerCase().includes("model_not_found")?new Qn(`Voyage AI model '${this.modelName}' not found. Browse https://docs.voyageai.com/docs/embeddings`,"voyage"):new _t(`Voyage AI error: ${t}`,"voyage")}async embed(e,t){const r=await this.callEmbeddings([e],t);if(!r[0])throw new _t("Voyage AI returned no embedding for the provided text","voyage");return r[0]}async embedMany(e,t){if(e.length===0)return[];const r=128,n=[];for(let o=0;o<e.length;o+=r){const s=e.slice(o,o+r),i=await this.callEmbeddings(s,t);n.push(...i)}return n}async callEmbeddings(e,t){const r=t??this.modelName;let n;try{n=await Ze(this.proxyFetch(`${this.baseURL}/embeddings`,{method:"POST",headers:{Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify({input:e,model:r})}),Qse,new _t(`Voyage embeddings request timed out after ${Qse/1e3}s`,"voyage"))}catch(i){throw i instanceof _t?i:this.formatProviderError(i)}if(!n.ok){const i=await n.text();throw this.formatProviderError(new Error(`Voyage embeddings failed: ${n.status} \u2014 ${i}`))}const o=await n.json();if(!o.data||o.data.length===0)throw new _t("Voyage embeddings response missing data","voyage");if(o.data.length!==e.length)throw new _t(`Voyage embeddings response count mismatch: expected ${e.length}, got ${o.data.length}`,"voyage");const s=o.data.slice().sort((i,a)=>i.index-a.index);for(let i=0;i<s.length;i++)if(s[i].index!==i)throw new _t(`Voyage embeddings response has unexpected index ordering: position ${i} has index ${s[i].index}`,"voyage");return s.map(i=>i.embedding)}async validateConfiguration(){return typeof this.apiKey=="string"&&this.apiKey.trim().length>0}getConfiguration(){return{provider:this.providerName,model:this.modelName,defaultModel:m$(),baseURL:this.baseURL}}}}}),vzt={};he(vzt,{JinaProvider:()=>bzt});var _zt,Hx,wzt,h$,bzt,VWr=S({async"src/lib/providers/jina.ts"(){"use strict";Tc(),await fd(),io(),yt(),q(),ps(),_zt="https://api.jina.ai/v1",Hx=6e4,wzt=()=>Yi(pwr()),h$=()=>Zi("JINA_MODEL","jina-embeddings-v3"),bzt=class extends Ol{apiKey;baseURL;proxyFetch;constructor(e,t,r,n){const o=by(t)?t:void 0;super(e,"jina",o);const s=n?.apiKey?.trim();this.apiKey=s&&s.length>0?s:wzt(),this.baseURL=n?.baseURL??process.env.JINA_BASE_URL??_zt,this.proxyFetch=zt(),f.debug("Jina Provider initialized (embeddings + reranking)",{modelName:this.modelName,baseURL:this.baseURL})}getProviderName(){return this.providerName}getDefaultModel(){return h$()}supportsTools(){return!1}getDefaultEmbeddingModel(){return h$()}getAISDKModel(){throw new Error("Jina AI is an embeddings + reranking provider; chat completions are not available. Use `embed()` / `embedMany()` / `rerank()`.")}async executeStream(e,t){throw new Error("Jina AI is an embeddings + reranking provider; streaming chat is not available.")}formatProviderError(e){const t=e instanceof Error?e.message:typeof e=="string"?e:"Unknown error";return t.includes("401")||t.toLowerCase().includes("unauthorized")?new Nr("Invalid Jina AI API key. Get one at https://jina.ai/?sui=apikey","jina"):t.includes("429")||t.toLowerCase().includes("rate limit")?new Os("Jina AI rate limit exceeded. Back off and retry.","jina"):t.includes("404")||t.toLowerCase().includes("model_not_found")?new Qn(`Jina AI model '${this.modelName}' not found. See https://jina.ai/embeddings/`,"jina"):new _t(`Jina AI error: ${t}`,"jina")}async embed(e,t){const r=await this.callEmbeddings([e],t);if(!r[0])throw new Error("Jina AI returned no embedding for the provided text");return r[0]}async embedMany(e,t){return e.length===0?[]:this.callEmbeddings(e,t)}async rerank(e,t,r={}){if(t.length===0)return[];const n=r.model??"jina-reranker-v2-base-multilingual",o=r.credentials,s=o?.apiKey?.trim()||this.apiKey,i=o?.baseURL||this.baseURL,a=new AbortController,l=setTimeout(()=>a.abort(),Hx);let c;try{c=await this.proxyFetch(`${i}/rerank`,{method:"POST",headers:{Authorization:`Bearer ${s}`,"Content-Type":"application/json"},body:JSON.stringify({model:n,query:e,documents:t,top_n:r.topN??t.length}),signal:a.signal})}catch(d){throw d instanceof Error&&d.name==="AbortError"?this.formatProviderError(new Error(`Jina rerank request timed out after ${Hx/1e3}s`)):this.formatProviderError(d)}finally{clearTimeout(l)}if(!c.ok){const d=await c.text();throw this.formatProviderError(new Error(`Jina rerank failed: ${c.status} \u2014 ${d}`))}return((await c.json()).results??[]).map(d=>({index:d.index,score:d.relevance_score,document:t[d.index]??d.document?.text??""}))}async callEmbeddings(e,t,r){const n=t??this.modelName,o=r?.apiKey?.trim()||this.apiKey,s=r?.baseURL||this.baseURL,i=new AbortController,a=setTimeout(()=>i.abort(),Hx);let l;try{l=await this.proxyFetch(`${s}/embeddings`,{method:"POST",headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json"},body:JSON.stringify({input:e,model:n}),signal:i.signal})}catch(d){throw d instanceof Error&&d.name==="AbortError"?this.formatProviderError(new Error(`Jina embeddings request timed out after ${Hx/1e3}s`)):this.formatProviderError(d)}finally{clearTimeout(a)}if(!l.ok){const d=await l.text();throw this.formatProviderError(new Error(`Jina embeddings failed: ${l.status} \u2014 ${d}`))}const c=await l.json();if(!c.data||c.data.length===0)throw new Error("Jina embeddings response missing data");if(c.data.length!==e.length)throw new Error(`Jina embeddings response count mismatch: expected ${e.length}, got ${c.data.length}`);const u=c.data.slice().sort((d,m)=>d.index-m.index);for(let d=0;d<u.length;d++)if(u[d].index!==d)throw new Error(`Jina embeddings response has unexpected index ordering: position ${d} has index ${u[d].index}`);return u.map(d=>d.embedding)}async validateConfiguration(){return typeof this.apiKey=="string"&&this.apiKey.trim().length>0}getConfiguration(){return{provider:this.providerName,model:this.modelName,defaultModel:h$(),baseURL:this.baseURL}}}}}),Tzt={};he(Tzt,{StabilityProvider:()=>rie,default:()=>Czt});var Ezt,eie,Szt,tie,rie,Czt,WWr=S({async"src/lib/providers/stability.ts"(){"use strict";Tc(),await fd(),io(),yt(),q(),ps(),Ezt="https://api.stability.ai",eie=12e4,Szt=()=>(process.env.STABILITY_API_KEY??process.env.STABILITY_AI_API_KEY??"").trim()||void 0,tie=()=>Zi("STABILITY_MODEL","stable-image-ultra"),rie=class extends Ol{apiKey;baseURL;proxyFetch;constructor(e,t,r,n){const o=by(t)?t:void 0;super(e,"stability",o);const s=n?.apiKey?.trim();this.apiKey=s&&s.length>0?s:Szt(),this.baseURL=n?.baseURL??process.env.STABILITY_BASE_URL??Ezt,this.proxyFetch=zt(),f.debug("Stability AI Provider initialized (image-gen only)",{modelName:this.modelName,baseURL:this.baseURL})}getProviderName(){return this.providerName}getDefaultModel(){return tie()}supportsTools(){return!1}getAISDKModel(){throw new Error("Stability AI is an image-generation-only provider; chat completions are not available.")}async executeStream(e,t){throw new Error("Stability AI is an image-generation-only provider; streaming chat is not available. Use generate({output:{format:'binary'}}) with a Stable Image / SD 3.5 model.")}formatProviderError(e){const t=e instanceof Error?e.message:typeof e=="string"?e:"Unknown error";return t.includes("401")||t.toLowerCase().includes("unauthorized")?new Nr("Invalid Stability AI API key. Get one at https://platform.stability.ai/account/keys","stability"):t.includes("429")||t.toLowerCase().includes("rate limit")?new Os("Stability AI rate limit exceeded. Back off and retry.","stability"):t.includes("content_filtered")||t.includes("CONTENT_FILTERED")?new _t("Stability AI declined the request due to content policy. Adjust the prompt and retry.","stability"):t.includes("404")?new Qn(`Stability AI model '${this.modelName}' not found. Use stable-image-ultra, stable-image-core, sd3.5-large, sd3.5-large-turbo, or sd3.5-medium.`,"stability"):new _t(`Stability AI error: ${t}`,"stability")}async executeImageGeneration(e){const t=Date.now(),r=e.credentials?.stability,n=r?.apiKey?.trim()||this.apiKey;if(!n)throw new Error("Stability AI API key is required. Set STABILITY_API_KEY or pass credentials.stability.apiKey per-call.");const o=n,s=r?.baseURL||this.baseURL,i=e.prompt??e.input?.text??"";if(!i.trim())throw new Error("Stability AI image generation requires a prompt (input.text or prompt)");const a=this.modelName.startsWith("sd3.5-")?"sd3":this.modelName==="stable-image-ultra"?"ultra":this.modelName==="stable-image-core"?"core":this.modelName,l=e,c=new FormData;c.append("prompt",i),c.append("output_format","png"),l.aspectRatio&&c.append("aspect_ratio",String(l.aspectRatio)),l.negativePrompt&&c.append("negative_prompt",l.negativePrompt),this.modelName.startsWith("sd3.5-")&&c.append("model",this.modelName),l.seed!==void 0&&c.append("seed",String(l.seed));const u=new AbortController,d=setTimeout(()=>u.abort(),eie);let m;try{m=await this.proxyFetch(`${s}/v2beta/stable-image/generate/${a}`,{method:"POST",headers:{Authorization:`Bearer ${o}`,Accept:"application/json"},body:c,signal:u.signal})}catch(y){throw y instanceof Error&&y.name==="AbortError"?this.formatProviderError(new Error(`Stability image-gen request timed out after ${eie/1e3}s`)):this.formatProviderError(y)}finally{clearTimeout(d)}if(!m.ok){const y=await m.text();throw this.formatProviderError(new Error(`Stability image-gen failed: ${m.status} \u2014 ${y}`))}const h=await m.json();if(!h.image)throw new Error(`Stability AI returned no image (finish_reason: ${h.finish_reason??"unknown"})`);const g=Date.now()-t;return f.info(`[StabilityProvider] Generated image (${h.image.length} base64 chars) in ${g}ms \u2014 model ${this.modelName}`),{content:i,provider:this.providerName,model:this.modelName,usage:{input:0,output:1e3,total:1e3},imageOutput:{base64:h.image}}}async validateConfiguration(){return this.apiKey!==void 0&&this.apiKey.trim().length>0}getConfiguration(){return{provider:this.providerName,model:this.modelName,defaultModel:tie(),baseURL:this.baseURL}}},Czt=rie}}),kzt={};he(kzt,{IdeogramProvider:()=>sie,default:()=>Izt});var xzt,nie,Azt,oie,sie,Izt,KWr=S({async"src/lib/providers/ideogram.ts"(){"use strict";Tc(),await fd(),io(),yt(),q(),ps(),xzt="https://api.ideogram.ai",nie=12e4,Azt=()=>Yi(mwr()),oie=()=>Zi("IDEOGRAM_MODEL","V_3"),sie=class extends Ol{apiKey;baseURL;proxyFetch;constructor(e,t,r,n){const o=by(t)?t:void 0;super(e,"ideogram",o);const s=n?.apiKey?.trim();this.apiKey=s&&s.length>0?s:Azt(),this.baseURL=n?.baseURL??process.env.IDEOGRAM_BASE_URL??xzt,this.proxyFetch=zt(),f.debug("Ideogram Provider initialized (image-gen only)",{modelName:this.modelName,baseURL:this.baseURL})}getProviderName(){return this.providerName}getDefaultModel(){return oie()}supportsTools(){return!1}getAISDKModel(){throw new Error("Ideogram is an image-generation-only provider; chat completions are not available.")}async executeStream(e,t){throw new Error("Ideogram is an image-generation-only provider; streaming chat is not available.")}formatProviderError(e){const t=e instanceof Error?e.message:typeof e=="string"?e:"Unknown error";return t.includes("401")||t.toLowerCase().includes("unauthorized")?new Nr("Invalid Ideogram API key. Get one at https://developer.ideogram.ai/","ideogram"):t.includes("429")||t.toLowerCase().includes("rate limit")?new Os("Ideogram rate limit exceeded. Back off and retry.","ideogram"):t.includes("safety")||t.includes("is_image_safe")?new _t("Ideogram declined the request due to safety filters. Adjust the prompt and retry.","ideogram"):new _t(`Ideogram error: ${t}`,"ideogram")}async executeImageGeneration(e){const t=Date.now(),r=e.credentials?.ideogram,n=r?.apiKey?.trim()||this.apiKey,o=r?.baseURL||this.baseURL,s=e.prompt??e.input?.text??"";if(!s.trim())throw new Error("Ideogram image generation requires a prompt (input.text or prompt)");const i=e,a={prompt:s,model:this.modelName,magic_prompt:i.magicPrompt??"AUTO"};i.aspectRatio&&(a.aspect_ratio=i.aspectRatio),i.negativePrompt&&(a.negative_prompt=i.negativePrompt),i.seed!==void 0&&(a.seed=i.seed),i.style&&(a.style_type=i.style);const l=new AbortController,c=setTimeout(()=>l.abort(),nie);let u;try{u=await this.proxyFetch(`${o}/v1/ideogram-v3/generate`,{method:"POST",headers:{"Api-Key":n,"Content-Type":"application/json"},body:JSON.stringify(a),signal:l.signal})}catch(T){throw T instanceof Error&&T.name==="AbortError"?this.formatProviderError(new Error(`Ideogram image-gen request timed out after ${nie/1e3}s`)):this.formatProviderError(T)}finally{clearTimeout(c)}if(!u.ok){const T=await u.text();throw this.formatProviderError(new Error(`Ideogram image-gen failed: ${u.status} \u2014 ${T}`))}const m=(await u.json()).data?.[0]?.url;if(!m)throw new Error("Ideogram returned no image URL");const h=new AbortController,g=setTimeout(()=>h.abort(),6e4);let y;try{y=await this.proxyFetch(m,{signal:h.signal})}catch(T){throw T instanceof Error&&T.name==="AbortError"?new Error("Ideogram image download timed out after 60s",{cause:T}):T}finally{clearTimeout(g)}if(!y.ok)throw new Error(`Failed to download Ideogram image: ${y.status}`);const v=Buffer.from(await y.arrayBuffer()),_=v.toString("base64"),b=Date.now()-t;return f.info(`[IdeogramProvider] Generated image (${v.length} bytes) in ${b}ms \u2014 model ${this.modelName}`),{content:s,provider:this.providerName,model:this.modelName,usage:{input:0,output:1e3,total:1e3},imageOutput:{base64:_}}}async validateConfiguration(){return typeof this.apiKey=="string"&&this.apiKey.trim().length>0}getConfiguration(){return{provider:this.providerName,model:this.modelName,defaultModel:oie(),baseURL:this.baseURL}}},Izt=sie}}),Rzt={};he(Rzt,{ReplicateProvider:()=>Mzt});function JWr(e){const t=e,r=t.prompt??t.input?.text??"",n=t.systemPrompt;return n?`${n}
|
|
2163
2163
|
|
|
2164
2164
|
${r}`:r}function YWr(e){return typeof e=="string"?e:Array.isArray(e)?e.map(t=>typeof t=="string"?t:"").join(""):""}function iie(e){const t=e?.apiKey?.trim()||e?.apiToken?.trim(),r=e?.baseURL||e?.baseUrl;return{apiToken:t,baseUrl:r}}var aie,Mzt,ZWr=S({async"src/lib/providers/replicate.ts"(){"use strict";Tc(),NP(),W2(),Z2(),Nl(),await fd(),q(),at(),ps(),aie=()=>Zi("REPLICATE_MODEL","meta/meta-llama-3-70b-instruct"),Mzt=class extends Ol{apiToken;baseURL;constructor(e,t,r,n){const o=by(t)?t:void 0;super(e,"replicate",o);const{apiToken:s,baseUrl:i}=iie(n);this.apiToken=s&&s.length>0?s:Yi(uwr()),this.baseURL=i,f.debug("Replicate Provider initialized",{modelName:this.modelName,baseURL:this.baseURL})}getProviderName(){return this.providerName}getDefaultModel(){return aie()}supportsTools(){return!1}getAISDKModel(){throw new Error("Replicate routes through the predictions API, not the AI SDK chat models. Streaming uses the predict-then-stream path inside executeStream.")}async generate(e,t){const r=typeof e=="string"?{prompt:e}:e,n=v0(r,this.modelName);if(n==="video"||n==="avatar"||n==="music"||n==="image")return super.generate(r,t);if(r.output?.format==="json"||r.output?.format==="structured"||t!=null)throw new Ne({code:Xe.PROVIDER_NOT_AVAILABLE,message:"Replicate models do not support structured-output / JSON schema. Remove output.format or _analysisSchema, or use a provider that implements the OpenAI chat-completions contract (e.g. openai, anthropic).",category:"validation",severity:"medium",retriable:!1});const o=r.prompt??r.input?.text??"",s=Date.now(),i=await this.executeStream({input:{text:o},systemPrompt:r.systemPrompt,maxTokens:r.maxTokens,temperature:r.temperature,abortSignal:r.abortSignal,timeout:r.timeout});let a="";for await(const c of i.stream)"content"in c&&typeof c.content=="string"&&(a+=c.content);const l={content:a,provider:this.providerName,model:this.modelName,usage:{input:0,output:0,total:0}};return f.info(`[ReplicateProvider] generate() complete in ${Date.now()-s}ms \u2014 ${a.length} chars`),l}async executeStream(e,t){const r=Date.now(),n=e.credentials?.replicate,o=iie(n),s=o.apiToken||this.apiToken,i=o.baseUrl||this.baseURL,a=Ch({apiToken:s,baseUrl:i});if(!a)throw new Ne({code:Xe.MISSING_CONFIGURATION,message:"Replicate auth could not be resolved (REPLICATE_API_TOKEN missing).",category:"configuration",severity:"high",retriable:!1});const l=JWr(e);if(!l.trim())throw new Ne({code:Xe.INVALID_PARAMETERS,message:"Replicate predictions require a prompt (input.text or prompt)",category:"validation",severity:"medium",retriable:!1});const c={prompt:l,...e.maxTokens!==void 0&&{max_new_tokens:e.maxTokens},temperature:e.temperature,top_p:1};let u;try{u=await zx(a,{model:this.modelName,input:c},{abortSignal:e.abortSignal})}catch(h){throw this.handleProviderError(h)}const d=YWr(u.output);if(!d)throw new Error(`Replicate prediction ${u.id} returned empty output`);const m={async*[Symbol.asyncIterator](){yield{content:d}}};return f.info(`[ReplicateProvider] Generated ${d.length} chars in ${Date.now()-r}ms \u2014 model ${this.modelName} (prediction ${u.id})`),{stream:m,provider:this.providerName,model:this.modelName,finishReason:"stop",metadata:{startTime:r,streamId:`replicate-${u.id}`}}}async executeImageGeneration(e){const t=Date.now(),r=e.credentials?.replicate,n=iie(r),o=n.apiToken||this.apiToken,s=n.baseUrl||this.baseURL,i=Ch({apiToken:o,baseUrl:s});if(!i)throw new Ne({code:Xe.MISSING_CONFIGURATION,message:"Replicate auth could not be resolved (REPLICATE_API_TOKEN missing).",category:"configuration",severity:"high",retriable:!1});const a=e.prompt??e.input?.text??"";if(!a.trim())throw new Ne({code:Xe.INVALID_PARAMETERS,message:"Replicate image-gen requires a prompt",category:"validation",severity:"medium",retriable:!1});const l=e,c={prompt:a,output_format:"png"};l.aspectRatio&&(c.aspect_ratio=l.aspectRatio),l.negativePrompt&&(c.negative_prompt=l.negativePrompt),l.seed!==void 0&&(c.seed=l.seed);let u;try{u=await zx(i,{model:this.modelName,input:c},{abortSignal:e.abortSignal})}catch(h){throw this.handleProviderError(h)}let d;try{d=await Y2(u,Cg)}catch(h){throw this.handleProviderError(h)}const m=d.toString("base64");return f.info(`[ReplicateProvider] Generated image (${d.length} bytes) in ${Date.now()-t}ms \u2014 model ${this.modelName}`),{content:a,provider:this.providerName,model:this.modelName,usage:{input:0,output:0,total:0},imageOutput:{base64:m}}}formatProviderError(e){const t=e instanceof Error?e.message:typeof e=="string"?e:"Unknown error",r=e instanceof Error?e:void 0;return t.includes("401")||t.toLowerCase().includes("unauthorized")||t.toLowerCase().includes("invalid token")?new Ne({code:Xe.PROVIDER_AUTH_FAILED,message:"Invalid Replicate API token. Get one at https://replicate.com/account/api-tokens",category:"configuration",severity:"high",retriable:!1,context:{provider:"replicate"},originalError:r}):t.includes("402")||t.toLowerCase().includes("insufficient credit")?new Ne({code:Xe.PROVIDER_QUOTA_EXCEEDED,message:"Replicate insufficient credit. Top up at https://replicate.com/account/billing \u2014 most image/music models require a paid balance.",category:"resource",severity:"high",retriable:!1,context:{provider:"replicate"},originalError:r}):t.includes("429")||t.toLowerCase().includes("rate limit")?new Ne({code:Xe.PROVIDER_QUOTA_EXCEEDED,message:"Replicate rate limit exceeded. Back off and retry.",category:"resource",severity:"high",retriable:!0,context:{provider:"replicate"},originalError:r}):t.toLowerCase().includes("not found")||t.includes("404")?new Ne({code:Xe.PROVIDER_NOT_AVAILABLE,message:`Replicate model '${this.modelName}' not found. Use owner/name or owner/name:version format. Browse https://replicate.com/explore`,category:"validation",severity:"medium",retriable:!1,context:{provider:"replicate",model:this.modelName},originalError:r}):new Ne({code:Xe.PROVIDER_NOT_AVAILABLE,message:`Replicate error: ${t}`,category:"execution",severity:"high",retriable:!1,context:{provider:"replicate"},originalError:r})}async validateConfiguration(){return typeof this.apiToken=="string"&&this.apiToken.trim().length>0}getConfiguration(){return{provider:this.providerName,model:this.modelName,defaultModel:aie(),baseURL:this.baseURL}}}}}),Pzt={};he(Pzt,{RecraftProvider:()=>uie,default:()=>Nzt});var Dzt,lie,Ozt,cie,uie,Nzt,XWr=S({async"src/lib/providers/recraft.ts"(){"use strict";Tc(),await fd(),io(),yt(),q(),ps(),Nl(),xg(),Dzt="https://external.api.recraft.ai/v1",lie=12e4,Ozt=()=>Yi(hwr()),cie=()=>Zi("RECRAFT_MODEL","recraftv3"),uie=class extends Ol{apiKey;baseURL;proxyFetch;constructor(e,t,r,n){const o=by(t)?t:void 0;super(e,"recraft",o);const s=n?.apiKey?.trim();this.apiKey=s&&s.length>0?s:Ozt(),this.baseURL=n?.baseURL??process.env.RECRAFT_BASE_URL??Dzt,this.proxyFetch=zt(),f.debug("Recraft Provider initialized (image-gen only)",{modelName:this.modelName,baseURL:this.baseURL})}getProviderName(){return this.providerName}getDefaultModel(){return cie()}supportsTools(){return!1}getAISDKModel(){throw new Error("Recraft is an image-generation-only provider; chat completions are not available.")}async executeStream(e,t){throw new Error("Recraft is an image-generation-only provider; streaming chat is not available.")}formatProviderError(e){const t=e instanceof Error?e.message:typeof e=="string"?e:"Unknown error";return t.includes("401")||t.toLowerCase().includes("unauthorized")?new Nr("Invalid Recraft API key. Get one at https://www.recraft.ai/api","recraft"):t.includes("429")||t.toLowerCase().includes("rate limit")?new Os("Recraft rate limit exceeded. Back off and retry.","recraft"):t.includes("404")||t.includes("model_not_found")?new Qn(`Recraft model '${this.modelName}' not found. Use recraftv3, recraftv3-svg, or recraftv2.`,"recraft"):new _t(`Recraft error: ${t}`,"recraft")}async executeImageGeneration(e){const t=Date.now(),r=e.credentials?.recraft,n=r?.apiKey?.trim()||this.apiKey,o=r?.baseURL||this.baseURL,s=e.prompt??e.input?.text??"";if(!s.trim())throw new Error("Recraft image generation requires a prompt (input.text or prompt)");const i=e,a={model:e.model??this.modelName,prompt:s,n:1,response_format:"b64_json"};i.negativePrompt&&(a.negative_prompt=i.negativePrompt),i.style&&(a.style=i.style),i.styleId&&(a.style_id=i.styleId),i.size&&(a.size=i.size);const l=new AbortController,c=setTimeout(()=>l.abort(),lie);let u;try{u=await this.proxyFetch(`${o}/images/generations`,{method:"POST",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"},body:JSON.stringify(a),signal:l.signal})}catch(y){throw y instanceof Error&&y.name==="AbortError"?this.formatProviderError(new Error(`Recraft image-gen request timed out after ${lie/1e3}s`)):this.formatProviderError(y)}finally{clearTimeout(c)}if(!u.ok){const y=await u.text();throw this.formatProviderError(new Error(`Recraft image-gen failed: ${u.status} \u2014 ${y}`))}const m=(await u.json()).data?.[0];if(!m)throw new Error("Recraft returned no image data");let h;if(m.b64_json)h=m.b64_json;else if(m.url){await kg(m.url);const y=new AbortController,v=setTimeout(()=>y.abort(),6e4);let _;try{_=await this.proxyFetch(m.url,{signal:y.signal})}catch(T){throw T instanceof Error&&T.name==="AbortError"?new Error("Recraft image download timed out after 60s",{cause:T}):T}finally{clearTimeout(v)}if(!_.ok)throw new Error(`Failed to download Recraft image: ${_.status}`);h=(await pp(_,Cg,"Recraft image")).toString("base64")}else throw new Error("Recraft response missing both b64_json and url");const g=Date.now()-t;return f.info(`[RecraftProvider] Generated image (${h.length} base64 chars) in ${g}ms \u2014 model ${this.modelName}`),{content:s,provider:this.providerName,model:this.modelName,usage:{input:0,output:1e3,total:1e3},imageOutput:{base64:h}}}async validateConfiguration(){return typeof this.apiKey=="string"&&this.apiKey.trim().length>0}getConfiguration(){return{provider:this.providerName,model:this.modelName,defaultModel:cie(),baseURL:this.baseURL}}},Nzt=uie}}),Lzt={};he(Lzt,{Agent:()=>Cjt,BedrockClient:()=>Fzt,BedrockRuntimeClient:()=>Bzt,Blob:()=>Sjt,Client:()=>xjt,ConverseCommand:()=>zzt,ConverseStreamCommand:()=>jzt,Cron:()=>ijt,Dispatcher:()=>Ajt,File:()=>Ejt,FlowProducer:()=>sjt,FormData:()=>Tjt,GoogleAuth:()=>Kzt,HTTPException:()=>mjt,Headers:()=>bjt,Hippocampus:()=>Xzt,HippocampusConfig:()=>Qzt,Hono:()=>djt,ImageFormat:()=>qzt,InvokeEndpointCommand:()=>Vzt,InvokeEndpointWithResponseStreamCommand:()=>Wzt,InvokeModelCommand:()=>Gzt,Job:()=>njt,ListFoundationModelsCommand:()=>Uzt,MockAgent:()=>Mjt,Pool:()=>kjt,Queue:()=>tjt,QueueScheduler:()=>ojt,Request:()=>_jt,Response:()=>wjt,SageMakerRuntimeClient:()=>Hzt,TextToSpeechClient:()=>Yzt,VertexAI:()=>Jzt,Webhook:()=>Zzt,Worker:()=>rjt,convertToHtml:()=>ujt,cors:()=>pjt,createClient:()=>ejt,default:()=>$zt,extractRawText:()=>cjt,fetch:()=>vjt,getGlobalDispatcher:()=>Rjt,interceptors:()=>Pjt,logger:()=>hjt,parseBuffer:()=>ajt,request:()=>Djt,secureHeaders:()=>fjt,selectCover:()=>ljt,setGlobalDispatcher:()=>Ijt,streamSSE:()=>gjt,timeout:()=>yjt});var Ty,Is,$zt,Fzt,Uzt,Bzt,zzt,jzt,qzt,Gzt,Hzt,Vzt,Wzt,Kzt,Jzt,Yzt,Zzt,Xzt,Qzt,ejt,tjt,rjt,njt,ojt,sjt,ijt,ajt,ljt,cjt,ujt,djt,pjt,mjt,hjt,fjt,gjt,yjt,vjt,_jt,wjt,bjt,Tjt,Ejt,Sjt,Cjt,kjt,xjt,Ajt,Ijt,Rjt,Mjt,Pjt,Djt,QWr=S({"npm-stub:@google-cloud/text-to-speech"(){Ty={get(e,t){return t==="__esModule"?!0:t==="default"?new Proxy({},{get:Ty.get}):new Proxy(function(...r){return new Proxy({},{get:Ty.get})},{get:Ty.get,apply(r,n,o){return new Proxy({},{get:Ty.get})},construct(r,n){return new Proxy({},{get:Ty.get})}})}},Is=new Proxy({},Ty),$zt=Is,{BedrockClient:Fzt,ListFoundationModelsCommand:Uzt,BedrockRuntimeClient:Bzt,ConverseCommand:zzt,ConverseStreamCommand:jzt,ImageFormat:qzt,InvokeModelCommand:Gzt}=Is,{SageMakerRuntimeClient:Hzt,InvokeEndpointCommand:Vzt,InvokeEndpointWithResponseStreamCommand:Wzt}=Is,{GoogleAuth:Kzt,VertexAI:Jzt,TextToSpeechClient:Yzt}=Is,{Webhook:Zzt}=Is,{Hippocampus:Xzt,HippocampusConfig:Qzt}=Is,{createClient:ejt}=Is,{Queue:tjt,Worker:rjt,Job:njt,QueueScheduler:ojt,FlowProducer:sjt}=Is,{Cron:ijt}=Is,{parseBuffer:ajt,selectCover:ljt}=Is,{extractRawText:cjt,convertToHtml:ujt}=Is,{Hono:djt}=Is,{cors:pjt,HTTPException:mjt,logger:hjt,secureHeaders:fjt,streamSSE:gjt,timeout:yjt}=Is,vjt=globalThis.fetch,_jt=globalThis.Request,wjt=globalThis.Response,bjt=globalThis.Headers,Tjt=globalThis.FormData,Ejt=globalThis.File,Sjt=globalThis.Blob,Cjt=Is.Agent,kjt=Is.Pool,xjt=Is.Client,Ajt=Is.Dispatcher,Ijt=()=>{},Rjt=()=>Is,Mjt=Is.MockAgent,Pjt={redirect:()=>e=>e,retry:()=>e=>e},Djt=async(e,t)=>{const r=await globalThis.fetch(e,t);return{statusCode:r.status,headers:Object.fromEntries(r.headers.entries()),body:{text:()=>r.text(),json:()=>r.json(),arrayBuffer:()=>r.arrayBuffer()}}}}}),f$,Ojt=S({"src/lib/adapters/tts/googleTTSHandler.ts"(){"use strict";fc(),q(),ro(),f$=class l3{client=null;voicesCache=null;static CACHE_TTL_MS=300*1e3;static DEFAULT_MAX_TEXT_LENGTH=5e3;static DEFAULT_API_TIMEOUT_MS=30*1e3;maxTextLength=l3.DEFAULT_MAX_TEXT_LENGTH;credentialsPath;constructor(t){this.credentialsPath=t??process.env.GOOGLE_APPLICATION_CREDENTIALS}isConfigured(){return this.credentialsPath!==void 0}async getClient(){if(!this.client){const{TextToSpeechClient:t}=await Promise.resolve().then(()=>(QWr(),Lzt));this.client=new t({keyFilename:this.credentialsPath})}return this.client}async getVoices(t){if(!this.isConfigured())throw new Nt({code:qt.PROVIDER_NOT_CONFIGURED,message:"Google Cloud TTS client not initialized. Set GOOGLE_APPLICATION_CREDENTIALS or pass credentials path.",category:"configuration",severity:"high",retriable:!1});const r=await this.getClient(),n=Oe.createSpan("tts","tts.google.listVoices",{"tts.operation":"listVoices","tts.provider":"google"});try{if(this.voicesCache&&Date.now()-this.voicesCache.timestamp<l3.CACHE_TTL_MS&&!t){const a=Oe.endSpan(n,1);return ut().recordSpan(a),this.voicesCache.voices}const[o]=await r.listVoices(t?{languageCode:t}:{});if(!o.voices||o.voices.length===0){f.warn("Google Cloud TTS returned no voices");const a=Oe.endSpan(n,1);return ut().recordSpan(a),[]}const s=[];for(const a of o.voices??[]){if(!a.name||!Array.isArray(a.languageCodes)||a.languageCodes.length===0){f.warn("Skipping voice with missing required fields",{name:a.name,languageCodesCount:a.languageCodes?.length});continue}const l=a.name,c=a.languageCodes,u=c[0],d=this.detectVoiceType(l),m=a.ssmlGender==="MALE"?"male":a.ssmlGender==="FEMALE"?"female":"neutral";s.push({id:l,name:l,languageCode:u,languageCodes:c,gender:m,type:d,naturalSampleRateHertz:a.naturalSampleRateHertz??void 0})}t||(this.voicesCache={voices:s,timestamp:Date.now()});const i=Oe.endSpan(n,1);return ut().recordSpan(i),s}catch(o){const s=Oe.endSpan(n,2,o instanceof Error?o.message:"Unknown error");ut().recordSpan(s);const i=o instanceof Error?o.message:"Unknown error";return f.error(`Failed to fetch Google TTS voices: ${i}`),[]}}async synthesize(t,r){if(!this.isConfigured())throw new Nt({code:qt.PROVIDER_NOT_CONFIGURED,message:"Google Cloud TTS client not initialized. Set GOOGLE_APPLICATION_CREDENTIALS or pass credentials path.",category:"configuration",severity:"high",retriable:!1});const n=await this.getClient(),o=r.voice??"en-US-Neural2-C",s=Oe.createSpan("tts","tts.google.synthesize",{"tts.operation":"synthesize","tts.provider":"google","tts.voice":o,"tts.format":r.format??"mp3"}),i=Date.now();try{const a=t.startsWith("<speak>")&&t.endsWith("</speak>");if(t.startsWith("<speak>")&&!t.endsWith("</speak>")||!t.startsWith("<speak>")&&t.endsWith("</speak>"))throw new Nt({code:qt.INVALID_INPUT,message:"Malformed SSML: missing opening <speak> or closing </speak> tag.",category:"validation",severity:"medium",retriable:!1});const l=this.extractLanguageCode(o),c=this.mapFormat(r.format??"mp3"),u={input:a?{ssml:t}:{text:t},voice:{name:o,languageCode:l},audioConfig:{audioEncoding:c,speakingRate:r.speed??1,pitch:r.pitch??0,volumeGainDb:r.volumeGainDb??0}},[d]=await n.synthesizeSpeech(u,{timeout:l3.DEFAULT_API_TIMEOUT_MS}),m=d.audioContent;if(!m)throw new Nt({code:qt.SYNTHESIS_FAILED,message:"Google TTS returned empty audio content",category:"execution",severity:"high",retriable:!0});const h=m instanceof Uint8Array?Buffer.from(m):typeof m=="string"?Buffer.from(m,"base64"):(()=>{throw new Nt({code:qt.SYNTHESIS_FAILED,message:"Unsupported audioContent type returned by Google TTS",category:"execution",severity:"high",retriable:!0,context:{type:typeof m}})})(),g=Date.now()-i,y=Oe.endSpan(s,1);return ut().recordSpan(y),{buffer:h,format:r.format??"mp3",size:h.length,voice:o,metadata:{latency:g,provider:"google-ai"}}}catch(a){const l=Oe.endSpan(s,2,a instanceof Error?a.message:String(a));if(ut().recordSpan(l),a instanceof Nt)throw a;const c=Date.now()-i,u=a instanceof Error?a.message:"Unknown error";throw new Nt({code:qt.SYNTHESIS_FAILED,message:`Google TTS failed after ${c}ms: ${u}`,category:"execution",severity:"high",retriable:!0,context:{latency:c},originalError:a instanceof Error?a:void 0})}}extractLanguageCode(t){const r=t.split("-");if(r.length>=2)return`${r[0]}-${r[1]}`;throw new Nt({code:qt.INVALID_INPUT,message:`Invalid Google TTS voiceId format: "${t}". Expected format like "en-US-Neural2-C".`,category:"validation",severity:"medium",retriable:!1,context:{voiceId:t}})}mapFormat(t){switch(t.toLowerCase()){case"mp3":return"MP3";case"wav":return"LINEAR16";case"ogg":case"opus":return"OGG_OPUS";default:throw new Nt({code:qt.INVALID_INPUT,message:`Unsupported audio format: ${t}`,category:"validation",severity:"medium",retriable:!1,context:{format:t}})}}detectVoiceType(t){const r=t.toLowerCase().split("-");return r.some(n=>n.startsWith("chirp"))?"chirp":r.includes("neural2")?"neural":r.includes("wavenet")?"wavenet":r.includes("standard")?"standard":"unknown"}}}}),Rw,Vx,g$=S({"src/lib/voice/RealtimeVoiceAPI.ts"(){"use strict";q(),Rp(),yt(),b0(),Rw=class{static registry=new Hf("RealtimeProcessor");static sessions=new Map;static registerHandler(e,t){const r=e&&e.toLowerCase();this.registry.register(e,t),f.debug(`[RealtimeProcessor] Registered Realtime handler for provider: ${r}`)}static getHandler(e){return this.registry.get(e)}static supports(e){return this.registry.supports(e)}static getProviders(){return this.registry.list()}static async connect(e,t,r){const n=this.getHandler(e);if(!n)throw sr.providerNotSupported(e,this.registry.list());if(!n.isConfigured())throw sr.providerNotConfigured(e);if(n.isConnected())throw sr.sessionAlreadyActive(e);const o={...L1,...t};r&&n.on(r);try{f.debug(`[RealtimeProcessor] Connecting to provider: ${e}`);const s=await n.connect(o);return this.sessions.set(e.toLowerCase(),s),f.info(`[RealtimeProcessor] Connected to ${e} session: ${s.id}`),s}catch(s){if(r&&n.off(),s instanceof sr)throw s;const i=s instanceof Error?s.message:String(s||"Unknown error");throw sr.connectionFailed(i,e,s instanceof Error?s:void 0)}}static async disconnect(e){const t=this.getHandler(e);if(!t)throw sr.providerNotSupported(e,this.registry.list());if(!t.isConnected()){f.warn(`[RealtimeProcessor] No active session for provider: ${e}`);return}try{await t.disconnect(),this.sessions.delete(e.toLowerCase()),t.off(),f.info(`[RealtimeProcessor] Disconnected from ${e}`)}catch(r){if(r instanceof sr)throw r;const n=r instanceof Error?r.message:String(r||"Unknown error");throw sr.protocolError(`Disconnect failed: ${n}`,e,r instanceof Error?r:void 0)}}static async sendAudio(e,t){const r=this.getHandler(e);if(!r)throw sr.providerNotSupported(e,this.registry.list());if(!r.isConnected())throw sr.sessionNotActive(e);try{await r.sendAudio(t)}catch(n){if(n instanceof sr)throw n;const o=n instanceof Error?n.message:String(n||"Unknown error");throw sr.audioStreamError(o,e)}}static async sendText(e,t){const r=this.getHandler(e);if(!r)throw sr.providerNotSupported(e,this.registry.list());if(!r.isConnected())throw sr.sessionNotActive(e);if(!r.sendText)throw new sr({code:ri.PROTOCOL_ERROR,message:`Provider "${e}" does not support text input`,category:"validation",severity:"medium",context:{provider:e}});try{await r.sendText(t)}catch(n){throw n instanceof sr?n:new sr({code:ri.PROTOCOL_ERROR,message:`sendText failed: ${n instanceof Error?n.message:String(n)}`,category:"network",severity:"medium",retriable:!0,context:{provider:e},originalError:n instanceof Error?n:void 0})}}static async triggerResponse(e){const t=this.getHandler(e);if(!t)throw sr.providerNotSupported(e,this.registry.list());if(!t.isConnected())throw sr.sessionNotActive(e);if(t.triggerResponse)try{await t.triggerResponse()}catch(r){throw r instanceof sr?r:new sr({code:ri.PROTOCOL_ERROR,message:`triggerResponse failed: ${r instanceof Error?r.message:String(r)}`,category:"network",severity:"medium",retriable:!0,context:{provider:e},originalError:r instanceof Error?r:void 0})}}static async cancelResponse(e){const t=this.getHandler(e);if(!t)throw sr.providerNotSupported(e,this.registry.list());if(t.isConnected()&&t.cancelResponse)try{await t.cancelResponse()}catch(r){throw r instanceof sr?r:new sr({code:ri.PROTOCOL_ERROR,message:`cancelResponse failed: ${r instanceof Error?r.message:String(r)}`,category:"network",severity:"medium",retriable:!0,context:{provider:e},originalError:r instanceof Error?r:void 0})}}static getSession(e){return this.getHandler(e)?.getSession()??null}static isConnected(e){return this.getHandler(e)?.isConnected()??!1}static getSupportedFormats(e){return this.getHandler(e)?.getSupportedFormats()??[]}static clearHandlers(){for(const[e]of this.sessions){const t=this.registry.get(e);t?.isConnected()&&t.disconnect().catch(()=>{})}this.sessions.clear(),this.registry.clear(),f.debug("[RealtimeProcessor] Cleared all handlers and sessions")}},Vx=class{session=null;eventHandlers=null;state="disconnected";isConnected(){return this.state==="connected"}getSession(){return this.session}on(e){this.eventHandlers=e}off(){this.eventHandlers=null}emitStateChange(e){this.state=e,this.session&&(this.session.state=e,this.session.lastActivityAt=new Date),this.eventHandlers?.onStateChange?.(e)}emitAudio(e){this.eventHandlers?.onAudio?.(e)}emitTranscript(e,t){this.eventHandlers?.onTranscript?.(e,t)}emitText(e,t){this.eventHandlers?.onText?.(e,t)}async emitFunctionCall(e,t){if(this.eventHandlers?.onFunctionCall)return this.eventHandlers.onFunctionCall(e,t)}emitError(e){this.eventHandlers?.onError?.(e)}emitTurnStart(){this.eventHandlers?.onTurnStart?.()}emitTurnEnd(){this.eventHandlers?.onTurnEnd?.()}createSession(e,t){return{id:e,state:"connected",provider:this.name,model:t.model,createdAt:new Date,lastActivityAt:new Date,config:t}}}}});function Njt(e){if(e.length<12)return null;if(e[0]===82&&e[1]===73&&e[2]===70&&e[3]===70&&e[8]===87&&e[9]===65&&e[10]===86&&e[11]===69)return"wav";if(e[0]===73&&e[1]===68&&e[2]===51||e[0]===255&&(e[1]&224)===224)return"mp3";if(e[0]===79&&e[1]===103&&e[2]===103&&e[3]===83){const t=e.indexOf("OpusHead");return t!==-1&&t<200?"opus":"ogg"}return null}function eKr(e){return YT[e]?.mimeType??"application/octet-stream"}function tKr(e){return YT[e]?.extension??".bin"}function rKr(e,t,r){const n=t??Njt(e);if(n)try{switch(n){case"wav":return nKr(e);case"mp3":return oKr(e);case"ogg":case"opus":return sKr(e);default:return r?e.length/(r*2):void 0}}catch(o){f.debug(`[audio-utils] Failed to calculate duration: ${o instanceof Error?o.message:String(o)}`);return}}function nKr(e){if(e.length<44)return;let t=12;for(;t<e.length-8;){const r=e.toString("ascii",t,t+4),n=e.readUInt32LE(t+4);if(r==="fmt "){const o=e.readUInt16LE(t+10),s=e.readUInt32LE(t+12),i=e.readUInt16LE(t+22);let a=t+8+n+n%2;for(;a<e.length-8;){const l=e.toString("ascii",a,a+4),c=e.readUInt32LE(a+4);if(l==="data"){const u=i/8*o;return c/u/s}a+=8+c+c%2}}t+=8+n+n%2}}function oKr(e){let t=0;for(e[0]===73&&e[1]===68&&e[2]===51&&(t=10+((e[6]&127)<<21|(e[7]&127)<<14|(e[8]&127)<<7|e[9]&127));t<e.length-4;){if(e[t]===255&&(e[t+1]&224)===224){const r=e[t+1]>>3&3,n=e[t+1]>>1&3,o=e[t+2]>>4&15,s=e[t+2]>>2&3,a={3:[44100,48e3,32e3],2:[22050,24e3,16e3],0:[11025,12e3,8e3]}[r]?.[s],c=[0,32,40,48,56,64,80,96,112,128,160,192,224,256,320,0][o];if(a&&c)return(e.length-t)*8/(c*1e3);break}t++}return e.length*8/128e3}function sKr(e){return e.length*8/64e3}async function iKr(e,t,r,n={}){if(t===r)return e;throw f.warn(`[audio-utils] Audio format conversion from ${t} to ${r} is not implemented.`),new Error(`Audio format conversion from ${t} to ${r} is not implemented. Convert with ffmpeg before passing to NeuroLink.`)}function aKr(e,t=16e3,r=16){const n=r/8,o=Buffer.alloc(e.length*n);for(let s=0;s<e.length;s++){const i=Math.max(-1,Math.min(1,e[s])),a=s*n;switch(r){case 8:o.writeUInt8(Math.round((i+1)*127.5),a);break;case 16:o.writeInt16LE(Math.round(i*32767),a);break;case 24:{const l=Math.round(i*8388607);o.writeUInt8(l&255,a),o.writeUInt8(l>>8&255,a+1),o.writeUInt8(l>>16&255,a+2);break}case 32:o.writeInt32LE(Math.round(i*2147483647),a);break}}return o}function lKr(e,t=16){const r=t/8,n=Math.floor(e.length/r),o=[];for(let s=0;s<n;s++){const i=s*r;switch(t){case 8:o.push(e.readUInt8(i)/127.5-1);break;case 16:o.push(e.readInt16LE(i)/32767);break;case 24:{const a=e.readUInt8(i)|e.readUInt8(i+1)<<8|e.readUInt8(i+2)<<16;o.push((a>8388607?a-16777216:a)/8388607);break}case 32:o.push(e.readInt32LE(i)/2147483647);break}}return o}function cKr(e,t,r){if(t<=0||r<=0||t===r)return e;const n=t/r,o=Math.round(e.length/n),s=[];for(let i=0;i<o;i++){const a=i*n,l=Math.floor(a),c=Math.min(l+1,e.length-1),u=a-l,d=e[l]*(1-u)+e[c]*u;s.push(d)}return s}function uKr(e,t=.95){if(e.length===0)return e;let r=0;for(const o of e)r=Math.max(r,Math.abs(o));if(r===0)return e;const n=t/r;return e.map(o=>o*n)}function Ljt(e,t=16e3,r=1,n=16){const o=Buffer.alloc(44),s=t*r*(n/8),i=r*(n/8);return o.write("RIFF",0),o.writeUInt32LE(36+e,4),o.write("WAVE",8),o.write("fmt ",12),o.writeUInt32LE(16,16),o.writeUInt16LE(1,20),o.writeUInt16LE(r,22),o.writeUInt32LE(t,24),o.writeUInt32LE(s,28),o.writeUInt16LE(i,32),o.writeUInt16LE(n,34),o.write("data",36),o.writeUInt32LE(e,40),o}function dKr(e,t=16e3,r=1,n=16){const o=Ljt(e.length,t,r,n);return Buffer.concat([o,e])}function pKr(e,t,r=16e3,n=2){if(t<=0||r<=0||n<=0)return[e];const o=r*n/1e3,s=Math.round(t*o);if(s<=0)return[e];const i=[];for(let a=0;a<e.length;a+=s){const l=Math.min(a+s,e.length);i.push(e.subarray(a,l))}return i}var $jt,Fjt,mKr=S({"src/lib/voice/audio-utils.ts"(){"use strict";yt(),q(),$jt={wav:Buffer.from([82,73,70,70]),mp3:{id3:Buffer.from([73,68,51]),frameSync:Buffer.from([255,224])},ogg:Buffer.from([79,103,103,83])},Fjt={wav:"audio/wav",mp3:"audio/mpeg",ogg:"audio/ogg",opus:"audio/opus"}}});function hKr(e){return{[Symbol.asyncIterator](){const t=[];let r=null,n=null,o=!1,s=null;const i=u=>{r?(r({value:u,done:!1}),r=null,n=null):t.push(u)},a=()=>{o=!0,r&&(r({value:void 0,done:!0}),r=null,n=null)},l=u=>{s=u,n&&(n(u),r=null,n=null)};e.on("chunk",i),e.on("end",a),e.on("error",l);const c=()=>{e.off("chunk",i),e.off("end",a),e.off("error",l)};return{async next(){if(s)throw s;if(t.length>0){const u=t.shift();if(u!==void 0)return{value:u,done:!1}}return o?{value:void 0,done:!0}:new Promise((u,d)=>{r=u,n=d})},async return(){return c(),o=!0,{value:void 0,done:!0}}}}}}async function fKr(e,t={}){const r=new Mw(t);return(async()=>{try{for await(const n of e)r.write(n)||await new Promise(s=>r.once("drain",s));r.end()}catch(n){r.emit("error",n instanceof Error?n:new Error(String(n)))}})(),r}var die,Mw,Ujt,Bjt,gKr=S({"src/lib/voice/stream-handler.ts"(){"use strict";vn(),q(),die={chunkDurationMs:100,sampleRate:16e3,bytesPerSample:2,format:"wav",highWaterMark:64*1024,bufferTimeoutMs:5e3},Mw=class extends sn{config;chunkSize;buffer;chunkIndex;timestampMs;isPaused;isEnded;pendingData;bufferTimeout;constructor(e={}){if(super(),this.config={...die,...e},this.config.sampleRate<=0)throw new Error("Invalid stream configuration: sampleRate must be positive");if(this.config.bytesPerSample<=0)throw new Error("Invalid stream configuration: bytesPerSample must be positive");const t=this.config.sampleRate*this.config.bytesPerSample/1e3;if(this.chunkSize=Math.round(this.config.chunkDurationMs*t),this.chunkSize<=0)throw new Error("Invalid stream configuration: chunkSize must be positive (check chunkDurationMs, sampleRate, bytesPerSample)");this.buffer=Buffer.alloc(0),this.chunkIndex=0,this.timestampMs=0,this.isPaused=!1,this.isEnded=!1,this.pendingData=[],this.bufferTimeout=null}write(e){if(this.isEnded)throw new Error("Cannot write to ended stream");return this.buffer.length+e.length>this.config.highWaterMark?(this.isPaused||(this.isPaused=!0,this.emit("pause")),this.pendingData.push(e),!1):(this.processData(e),!0)}processData(e){for(this.buffer=Buffer.concat([this.buffer,e]),this.resetBufferTimeout();this.buffer.length>=this.chunkSize;){const t=this.buffer.subarray(0,this.chunkSize);this.buffer=this.buffer.subarray(this.chunkSize);const r={data:t,index:this.chunkIndex++,isFinal:!1,format:this.config.format,sampleRate:this.config.sampleRate,timestampMs:this.timestampMs,durationMs:this.config.chunkDurationMs};this.timestampMs+=this.config.chunkDurationMs,this.emit("chunk",r)}if(this.isPaused&&this.buffer.length<this.config.highWaterMark/2)for(this.isPaused=!1,this.emit("resume"),this.emit("drain");this.pendingData.length>0&&!this.isPaused;){const t=this.pendingData.shift();if(t===void 0||!this.write(t))break}}end(){if(!this.isEnded){this.isEnded=!0,this.clearBufferTimeout();for(const e of this.pendingData)this.buffer=Buffer.concat([this.buffer,e]);if(this.pendingData=[],this.buffer.length>0){const e=this.buffer.length/this.config.bytesPerSample/this.config.sampleRate*1e3,t={data:this.buffer,index:this.chunkIndex++,isFinal:!0,format:this.config.format,sampleRate:this.config.sampleRate,timestampMs:this.timestampMs,durationMs:e};this.emit("chunk",t)}else{const e={data:Buffer.alloc(0),index:this.chunkIndex,isFinal:!0,format:this.config.format,sampleRate:this.config.sampleRate,timestampMs:this.timestampMs,durationMs:0};this.emit("chunk",e)}this.emit("end"),this.cleanup()}}resetBufferTimeout(){this.clearBufferTimeout(),this.bufferTimeout=setTimeout(()=>{this.buffer.length>0&&!this.isEnded&&(f.warn(`[ChunkedAudioStream] Buffer timeout, forcing flush of ${this.buffer.length} bytes`),this.end())},this.config.bufferTimeoutMs)}clearBufferTimeout(){this.bufferTimeout&&(clearTimeout(this.bufferTimeout),this.bufferTimeout=null)}cleanup(){this.clearBufferTimeout(),this.buffer=Buffer.alloc(0),this.pendingData=[]}getStats(){return{chunksEmitted:this.chunkIndex,bufferedBytes:this.buffer.length,pendingChunks:this.pendingData.length,totalDurationMs:this.timestampMs,isPaused:this.isPaused,isEnded:this.isEnded}}},Ujt=class extends sn{streams;config;constructor(e={}){super(),this.streams=new Map,this.config={...die,...e}}addStream(e){if(this.streams.has(e))throw new Error(`Stream ${e} already exists`);const t=new Mw(this.config);return t.on("chunk",r=>{this.emit("chunk",{id:e,chunk:r})}),t.on("end",()=>{this.emit("streamEnd",e),this.streams.delete(e),this.streams.size===0&&this.emit("end")}),t.on("error",r=>{this.emit("error",{id:e,error:r})}),this.streams.set(e,t),t}removeStream(e){const t=this.streams.get(e);t&&(t.end(),this.streams.delete(e))}write(e,t){const r=this.streams.get(e);if(!r)throw new Error(`Stream ${e} not found`);return r.write(t)}endAll(){for(const e of this.streams.values())e.end()}get activeStreams(){return this.streams.size}},Bjt=class extends sn{consumers;input;constructor(e={}){super(),this.consumers=new Map,this.input=new Mw(e),this.input.on("chunk",t=>{for(const[r,n]of this.consumers)try{n(t)}catch(o){this.emit("error",{consumerId:r,error:o instanceof Error?o:new Error(String(o))})}}),this.input.on("end",()=>{this.emit("end")}),this.input.on("error",t=>{this.emit("error",{error:t})})}write(e){return this.input.write(e)}end(){this.input.end()}addConsumer(e,t){if(this.consumers.has(e))throw new Error(`Consumer ${e} already exists`);this.consumers.set(e,t)}removeConsumer(e){this.consumers.delete(e)}get consumerCount(){return this.consumers.size}}}}),Pw,zjt=S({"src/lib/voice/providers/AzureTTS.ts"(){"use strict";q(),fc(),Pw=class Ndr{apiKey;region;voicesCache=null;static CACHE_TTL_MS=1800*1e3;maxTextLength=1e4;constructor(t,r){const n=(t??process.env.AZURE_SPEECH_KEY??"").trim();this.apiKey=n.length>0?n:null;const o=(r??process.env.AZURE_SPEECH_REGION??"").trim();this.region=o.length>0?o:"eastus"}isConfigured(){return this.apiKey!==null&&this.region.length>0}async getVoices(t){if(!this.apiKey)throw new Nt({code:qt.PROVIDER_NOT_CONFIGURED,message:"Azure Speech key not configured",category:"configuration",severity:"high",retriable:!1});if(this.voicesCache&&Date.now()-this.voicesCache.timestamp<Ndr.CACHE_TTL_MS&&!t)return this.voicesCache.voices;try{const r=new AbortController,n=setTimeout(()=>r.abort(),3e4);let o;try{o=await fetch(`https://${this.region}.tts.speech.microsoft.com/cognitiveservices/voices/list`,{method:"GET",headers:{"Ocp-Apim-Subscription-Key":this.apiKey},signal:r.signal})}catch(a){throw a instanceof Error&&a.name==="AbortError"?new Nt({code:qt.SYNTHESIS_FAILED,message:"Azure TTS voices request timed out after 30 seconds",category:"network",severity:"medium",retriable:!0,originalError:a}):a}finally{clearTimeout(n)}if(!o.ok)throw new Error(`HTTP ${o.status}`);let i=(await o.json()).map(a=>({id:a.ShortName,name:a.DisplayName,languageCode:a.Locale,languageCodes:[a.Locale],gender:this.mapGender(a.Gender),type:a.VoiceType.toLowerCase().includes("neural")?"neural":"standard",description:a.LocaleName}));return t&&(i=i.filter(a=>a.languageCode.toLowerCase().startsWith(t.toLowerCase())||a.languageCode.toLowerCase()===t.toLowerCase())),t||(this.voicesCache={voices:i,timestamp:Date.now()}),i}catch(r){if(r instanceof Nt)throw r;const n=r instanceof Error?r.message:String(r||"Unknown error");throw f.error(`[AzureTTSHandler] Failed to get voices: ${n}`),new Nt({code:qt.SYNTHESIS_FAILED,message:`Failed to get voices: ${n}`,category:"network",severity:"medium",retriable:!0,originalError:r instanceof Error?r:void 0})}}async synthesize(t,r={}){if(!this.apiKey)throw new Nt({code:qt.PROVIDER_NOT_CONFIGURED,message:"Azure Speech key not configured",category:"configuration",severity:"high",retriable:!1});const n=Date.now(),o=r;try{const s=r.voice??"en-US-JennyNeural",i=o.outputFormat??this.mapFormat(r.format??"mp3"),a=this.buildSSML(t,s,r),l=new AbortController,c=setTimeout(()=>l.abort(),3e4);let u;try{u=await fetch(`https://${this.region}.tts.speech.microsoft.com/cognitiveservices/v1`,{method:"POST",headers:{"Ocp-Apim-Subscription-Key":this.apiKey,"Content-Type":"application/ssml+xml","X-Microsoft-OutputFormat":i},body:a,signal:l.signal})}catch(y){throw y instanceof Error&&y.name==="AbortError"?new Nt({code:qt.SYNTHESIS_FAILED,message:"Azure TTS request timed out after 30 seconds",category:"network",severity:"high",retriable:!0,originalError:y}):y}finally{clearTimeout(c)}if(!u.ok){const y=await u.text();throw new Error(`HTTP ${u.status}: ${y}`)}const d=Date.now()-n,m=await u.arrayBuffer(),h=Buffer.from(m),g={buffer:h,format:this.effectiveFormat(i),size:h.length,voice:s,sampleRate:this.getSampleRate(i),metadata:{latency:d,provider:"azure-tts",requestedFormat:r.format,outputFormat:i,region:this.region}};return f.info(`[AzureTTSHandler] Synthesized ${h.length} bytes in ${d}ms`),g}catch(s){if(s instanceof Nt)throw s;const i=s instanceof Error?s.message:String(s||"Unknown error");throw f.error(`[AzureTTSHandler] Synthesis failed: ${i}`),new Nt({code:qt.SYNTHESIS_FAILED,message:`Synthesis failed: ${i}`,category:"execution",severity:"high",retriable:!0,context:{textLength:t.length},originalError:s instanceof Error?s:void 0})}}buildSSML(t,r,n){const o=n;if(o.ssmlTemplate)return o.ssmlTemplate.replace("{text}",this.escapeXml(t)).replace("{voice}",this.escapeXml(r));if(o.allowRawSSML&&t.trim().startsWith("<speak"))return t;const s=n.speed?`${Math.round((n.speed-1)*100)}%`:"0%",i=n.pitch??0,a=i>=0?`+${Math.round(i)}st`:`${Math.round(i)}st`;return`<speak version="1.0" xmlns="http://www.w3.org/2001/10/synthesis" xml:lang="${this.escapeXml(this.extractLanguage(r))}">
|
|
2165
2165
|
<voice name="${this.escapeXml(r)}">
|