@juspay/neurolink 12.47.13 → 12.47.14
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 +2 -2
- package/dist/browser/neurolink.min.js +14 -14
- package/dist/providers/googleAiStudio/client.js +27 -13
- package/package.json +1 -1
|
@@ -20,7 +20,7 @@ Additional Context: ${JSON.stringify(n,null,2)}`}static formatForSystemPrompt(t)
|
|
|
20
20
|
${JSON.stringify(t,null,2)}
|
|
21
21
|
[/CONTEXT]
|
|
22
22
|
|
|
23
|
-
`}static extractAnalyticsContext(t){return{hasUserId:!!t.userId,hasSessionId:!!t.sessionId,hasUserRole:!!t.userRole,hasOrgContext:!!t.organizationId,contextKeys:Object.keys(t),contextSize:JSON.stringify(t).length}}static extractEvaluationContext(t){return{userRole:t.userRole||"unknown",applicationContext:t.applicationContext?.name||"unknown",organizationContext:t.organizationId||"unknown",hasPreferences:!!t.userPreferences}}},O0e=class yme{static convertBusinessContext(t,r,n={}){const{preserveLegacyFields:o=!1,validateDomainData:i=!0,includeMetadata:s=!0}=n;return{sessionId:t.sessionId,userId:t.userId,config:{domainType:r,providerConfig:{token:t.apiToken||t.authToken||t.accessToken,endpoint:t.apiEndpoint||t.serviceUrl,provider:yme.inferProvider(t)},platformConfig:{type:t.platformType||"generic",url:t.platformUrl||t.serviceUrl,id:t.platformId||t.serviceId,integrations:t.platformIntegrations||[]},operationalConfig:{demoMode:t.enableDemoMode||!1,environment:t.environment||"production",region:t.region,features:t.enabledFeatures||[]},customData:{...o?{entityId:t.entityId||t.organizationId,departmentId:t.departmentId,projectId:t.projectId}:{},...yme.extractCustomData(t)}},metadata:s?{convertedFrom:"legacy-business-context",conversionTime:Date.now(),originalKeys:Object.keys(t),domainType:r}:void 0}}static createDomainContext(t,r,n={}){return{sessionId:n.sessionId||`session_${Date.now()}`,userId:n.userId,config:{domainType:t,customData:r},metadata:{source:"domain-context-factory",createdAt:Date.now(),domainType:t}}}static inferProvider(t){return t.apiToken||t.authToken?"api-provider":t.serviceUrl||t.endpoint?"service-provider":"generic-provider"}static extractCustomData(t){const r=b5.getFrameworkFieldsConfig();let n;r.overrideFields?n=new Set(r.overrideFields):n=new Set([...r.defaultFields,...r.additionalFields||[]]),r.includeFields&&r.includeFields.forEach(i=>n.delete(i));const o={};return Object.entries(t).forEach(([i,s])=>{n.has(i)||(o[i]=s)}),o}}}}),Ya,$Ar=E({"src/lib/types/conversation.ts"(){"use strict";Ya=class extends Error{constructor(e,t,r){super(e),this.code=t,this.details=r,this.name="ConversationMemoryError"}code;details}}}),UAr=E({"src/lib/types/conversationMemoryInterface.ts"(){"use strict"}}),BAr=E({"src/lib/types/delegation.ts"(){"use strict"}}),zAr=E({"src/lib/types/backgroundCommand.ts"(){"use strict"}}),GAr=E({"src/lib/types/gitTools.ts"(){"use strict"}}),qAr=E({"src/lib/types/pathSandbox.ts"(){"use strict"}}),VAr=E({"src/lib/types/fileToolRoots.ts"(){"use strict"}}),jAr=E({"src/lib/types/domain.ts"(){"use strict"}});function D0e(e){if(typeof e!="string"||e.length===0||e.length>G0e)return;const t=e.toLowerCase();let r=t.indexOf("models",0);for(;r!==-1;){let n=r+6;for(;n<e.length&&/\s/.test(e[n]);)n++;if(e[n]!=="="){r=t.indexOf("models",r+1);continue}for(n++;n<e.length&&/\s/.test(e[n]);)n++;if(e[n]!=="["){r=t.indexOf("models",r+1);continue}const o=n,i=e.indexOf("]",o+1);if(i===-1)return;const a=e.slice(o+1,i).split(",").map(l=>l.trim().replace(/^['"]|['"]$/g,"")).filter(l=>l.length>0);return a.length>0?a:void 0}}function N0e(e){const t=e.toLowerCase();return t.includes("team")&&t.includes("not allowed")||t.includes("team can only access")||/not\s+allowed\s+to\s+access\s+(this\s+)?model/i.test(e)}var ty,ot,Wr,kI,ai,Qi,Jo,Kp,L0e,F0e,$0e,U0e,B0e,z0e,hn,_5,ry,G0e,HAr=E({"src/lib/types/errors.ts"(){"use strict";ty=class extends Error{constructor(e){super(e),this.name=this.constructor.name}},ot=class extends ty{constructor(e,t){super(t?`[${t}] ${e}`:e),this.provider=t}provider},Wr=class extends ot{constructor(e,t){super(e,t)}},kI=class extends ot{constructor(e,t){super(e,t)}},ai=class extends ot{constructor(e,t){super(e,t)}},Qi=class extends ot{constructor(e,t){super(e,t)}},Jo=class extends ot{constructor(e,t){super(e,t)}},Kp=class extends ty{constructor(e,t){super(e),this.code=t,this.name="OAuthError"}code},L0e=class extends Kp{constructor(e){super(e,"CONFIGURATION_ERROR"),this.name="OAuthConfigurationError"}},F0e=class extends Kp{constructor(e,t){super(e,"TOKEN_EXCHANGE_ERROR"),this.statusCode=t,this.name="OAuthTokenExchangeError"}statusCode},$0e=class extends Kp{constructor(e,t){super(e,"TOKEN_REFRESH_ERROR"),this.statusCode=t,this.name="OAuthTokenRefreshError"}statusCode},U0e=class extends Kp{constructor(e){super(e,"TOKEN_VALIDATION_ERROR"),this.name="OAuthTokenValidationError"}},B0e=class extends Kp{constructor(e,t){super(e,"TOKEN_REVOCATION_ERROR"),this.statusCode=t,this.name="OAuthTokenRevocationError"}statusCode},z0e=class extends Kp{constructor(e){super(e,"CALLBACK_SERVER_ERROR"),this.name="OAuthCallbackServerError"}},hn=class extends ty{constructor(e,t="STORAGE_ERROR"){super(e),this.code=t,this.name="TokenStoreError"}code},_5=class extends ty{model;tier;requiredTier;constructor(e,t,r){super(`Model "${e}" is not available for tier "${t}". Required tier: "${r}" or higher.`),this.name="ModelAccessError",this.model=e,this.tier=t,this.requiredTier=r}},ry=class extends ot{requestedModel;allowedModels;code="MODEL_ACCESS_DENIED";constructor(e,t={}){super(e,t.provider),this.name="ModelAccessDeniedError",this.requestedModel=t.requestedModel,this.allowedModels=t.allowedModels}},G0e=1e4}}),WAr=E({"src/lib/types/evaluation.ts"(){"use strict"}}),KAr=E({"src/lib/types/evaluationProviders.ts"(){"use strict"}}),JAr=E({"src/lib/types/externalMcp.ts"(){"use strict"}}),XAr=E({"src/lib/types/file.ts"(){"use strict"}}),Jp,YAr=E({"src/lib/types/fileReference.ts"(){"use strict";Jp={TINY_MAX:10*1024,SMALL_MAX:100*1024,MEDIUM_MAX:5*1024*1024,LARGE_MAX:100*1024*1024,HUGE_MAX:2*1024*1024*1024}}}),ZAr=E({"src/lib/types/generate.ts"(){"use strict"}}),QAr=E({"src/lib/types/grounding.ts"(){"use strict"}}),eCr=E({"src/lib/types/guardrails.ts"(){"use strict"}}),tCr=E({"src/lib/types/hitl.ts"(){"use strict"}}),rCr=E({"src/lib/types/isolatedAgent.ts"(){"use strict"}}),nCr=E({"src/lib/types/knowledge.ts"(){"use strict"}}),oCr=E({"src/lib/types/livekit.ts"(){"use strict"}}),iCr=E({"src/lib/types/loopEngine.ts"(){"use strict"}}),sCr=E({"src/lib/types/mcp.ts"(){"use strict"}}),aCr=E({"src/lib/types/mcpOutput.ts"(){"use strict"}}),lCr=E({"src/lib/types/memory.ts"(){"use strict"}}),cCr=E({"src/lib/types/middleware.ts"(){"use strict"}});function fe(e,t,r){function n(a,l){if(a._zod||Object.defineProperty(a,"_zod",{value:{def:l,constr:s,traits:new Set},enumerable:!1}),a._zod.traits.has(e))return;a._zod.traits.add(e),t(a,l);const c=s.prototype,u=Object.keys(c);for(let d=0;d<u.length;d++){const p=u[d];p in a||(a[p]=c[p].bind(a))}}const o=r?.Parent??Object;class i extends o{}Object.defineProperty(i,"name",{value:e});function s(a){var l;const c=r?.Parent?new i:this;n(c,a),(l=c._zod).deferred??(l.deferred=[]);for(const u of c._zod.deferred)u();return c}return Object.defineProperty(s,"init",{value:n}),Object.defineProperty(s,Symbol.hasInstance,{value:a=>r?.Parent&&a instanceof r.Parent?!0:a?._zod?.traits?.has(e)}),Object.defineProperty(s,"name",{value:e}),s}function Is(e){return e&&Object.assign(u_,e),u_}var xI,E5,Xp,c_,u_,d_=E({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/core.js"(){xI=Object.freeze({status:"aborted"}),E5=Symbol("zod_brand"),Xp=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},c_=class extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name="ZodEncodeError"}},u_={}}}),vr={};Z(vr,{BIGINT_FORMAT_RANGES:()=>R5,Class:()=>X0e,NUMBER_FORMAT_RANGES:()=>I5,aborted:()=>zh,allowsEval:()=>A5,assert:()=>hCr,assertEqual:()=>uCr,assertIs:()=>pCr,assertNever:()=>mCr,assertNotEqual:()=>dCr,assignProp:()=>Yp,base64ToUint8Array:()=>W0e,base64urlToUint8Array:()=>RCr,cached:()=>p_,captureStackTrace:()=>MI,cleanEnum:()=>ICr,cleanRegex:()=>CI,clone:()=>Ol,cloneDef:()=>gCr,createTransparentProxy:()=>bCr,defineLazy:()=>nr,esc:()=>k5,escapeRegex:()=>_d,extend:()=>SCr,finalizeIssue:()=>Dl,floatSafeRemainder:()=>q0e,getElementAtPath:()=>yCr,getEnumValues:()=>S5,getLengthableOrigin:()=>RI,getParsedType:()=>J0e,getSizableOrigin:()=>II,hexToUint8Array:()=>MCr,isObject:()=>ny,isPlainObject:()=>Bh,issue:()=>PI,joinValues:()=>Ve,jsonStringifyReplacer:()=>AI,merge:()=>xCr,mergeDefs:()=>bd,normalizeParams:()=>Ke,nullish:()=>Uh,numKeys:()=>TCr,objectClone:()=>fCr,omit:()=>ECr,optionalKeys:()=>H0e,parsedType:()=>Ft,partial:()=>ACr,pick:()=>_Cr,prefixIssues:()=>Ec,primitiveTypes:()=>C5,promiseAllObject:()=>vCr,propertyKeyTypes:()=>h_,randomString:()=>wCr,required:()=>CCr,safeExtend:()=>kCr,shallowClone:()=>j0e,slugify:()=>V0e,stringifyPrimitive:()=>Mt,uint8ArrayToBase64:()=>K0e,uint8ArrayToBase64url:()=>PCr,uint8ArrayToHex:()=>OCr,unwrapMessage:()=>m_});function uCr(e){return e}function dCr(e){return e}function pCr(e){}function mCr(e){throw new Error("Unexpected value in exhaustive check")}function hCr(e){}function S5(e){const t=Object.values(e).filter(n=>typeof n=="number");return Object.entries(e).filter(([n,o])=>t.indexOf(+n)===-1).map(([n,o])=>o)}function Ve(e,t="|"){return e.map(r=>Mt(r)).join(t)}function AI(e,t){return typeof t=="bigint"?t.toString():t}function p_(e){return{get value(){{const r=e();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function Uh(e){return e==null}function CI(e){const t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}function q0e(e,t){const r=(e.toString().split(".")[1]||"").length,n=t.toString();let o=(n.split(".")[1]||"").length;if(o===0&&/\d?e-\d?/.test(n)){const l=n.match(/\d?e-(\d?)/);l?.[1]&&(o=Number.parseInt(l[1]))}const i=r>o?r:o,s=Number.parseInt(e.toFixed(i).replace(".","")),a=Number.parseInt(t.toFixed(i).replace(".",""));return s%a/10**i}function nr(e,t,r){let n;Object.defineProperty(e,t,{get(){if(n!==x5)return n===void 0&&(n=x5,n=r()),n},set(o){Object.defineProperty(e,t,{value:o})},configurable:!0})}function fCr(e){return Object.create(Object.getPrototypeOf(e),Object.getOwnPropertyDescriptors(e))}function Yp(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function bd(...e){const t={};for(const r of e){const n=Object.getOwnPropertyDescriptors(r);Object.assign(t,n)}return Object.defineProperties({},t)}function gCr(e){return bd(e._zod.def)}function yCr(e,t){return t?t.reduce((r,n)=>r?.[n],e):e}function vCr(e){const t=Object.keys(e),r=t.map(n=>e[n]);return Promise.all(r).then(n=>{const o={};for(let i=0;i<t.length;i++)o[t[i]]=n[i];return o})}function wCr(e=10){const t="abcdefghijklmnopqrstuvwxyz";let r="";for(let n=0;n<e;n++)r+=t[Math.floor(Math.random()*t.length)];return r}function k5(e){return JSON.stringify(e)}function V0e(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}function ny(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Bh(e){if(ny(e)===!1)return!1;const t=e.constructor;if(t===void 0||typeof t!="function")return!0;const r=t.prototype;return!(ny(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function j0e(e){return Bh(e)?{...e}:Array.isArray(e)?[...e]:e}function TCr(e){let t=0;for(const r in e)Object.prototype.hasOwnProperty.call(e,r)&&t++;return t}function _d(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Ol(e,t,r){const n=new e._zod.constr(t??e._zod.def);return(!t||r?.parent)&&(n._zod.parent=e),n}function Ke(e){const t=e;if(!t)return{};if(typeof t=="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error=="string"?{...t,error:()=>t.error}:t}function bCr(e){let t;return new Proxy({},{get(r,n,o){return t??(t=e()),Reflect.get(t,n,o)},set(r,n,o,i){return t??(t=e()),Reflect.set(t,n,o,i)},has(r,n){return t??(t=e()),Reflect.has(t,n)},deleteProperty(r,n){return t??(t=e()),Reflect.deleteProperty(t,n)},ownKeys(r){return t??(t=e()),Reflect.ownKeys(t)},getOwnPropertyDescriptor(r,n){return t??(t=e()),Reflect.getOwnPropertyDescriptor(t,n)},defineProperty(r,n,o){return t??(t=e()),Reflect.defineProperty(t,n,o)}})}function Mt(e){return typeof e=="bigint"?e.toString()+"n":typeof e=="string"?`"${e}"`:`${e}`}function H0e(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}function _Cr(e,t){const r=e._zod.def,n=r.checks;if(n&&n.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");const i=bd(e._zod.def,{get shape(){const s={};for(const a in t){if(!(a in r.shape))throw new Error(`Unrecognized key: "${a}"`);t[a]&&(s[a]=r.shape[a])}return Yp(this,"shape",s),s},checks:[]});return Ol(e,i)}function ECr(e,t){const r=e._zod.def,n=r.checks;if(n&&n.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");const i=bd(e._zod.def,{get shape(){const s={...e._zod.def.shape};for(const a in t){if(!(a in r.shape))throw new Error(`Unrecognized key: "${a}"`);t[a]&&delete s[a]}return Yp(this,"shape",s),s},checks:[]});return Ol(e,i)}function SCr(e,t){if(!Bh(t))throw new Error("Invalid input to extend: expected a plain object");const r=e._zod.def.checks;if(r&&r.length>0){const i=e._zod.def.shape;for(const s in t)if(Object.getOwnPropertyDescriptor(i,s)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}const o=bd(e._zod.def,{get shape(){const i={...e._zod.def.shape,...t};return Yp(this,"shape",i),i}});return Ol(e,o)}function kCr(e,t){if(!Bh(t))throw new Error("Invalid input to safeExtend: expected a plain object");const r=bd(e._zod.def,{get shape(){const n={...e._zod.def.shape,...t};return Yp(this,"shape",n),n}});return Ol(e,r)}function xCr(e,t){const r=bd(e._zod.def,{get shape(){const n={...e._zod.def.shape,...t._zod.def.shape};return Yp(this,"shape",n),n},get catchall(){return t._zod.def.catchall},checks:[]});return Ol(e,r)}function ACr(e,t,r){const o=t._zod.def.checks;if(o&&o.length>0)throw new Error(".partial() cannot be used on object schemas containing refinements");const s=bd(t._zod.def,{get shape(){const a=t._zod.def.shape,l={...a};if(r)for(const c in r){if(!(c in a))throw new Error(`Unrecognized key: "${c}"`);r[c]&&(l[c]=e?new e({type:"optional",innerType:a[c]}):a[c])}else for(const c in a)l[c]=e?new e({type:"optional",innerType:a[c]}):a[c];return Yp(this,"shape",l),l},checks:[]});return Ol(t,s)}function CCr(e,t,r){const n=bd(t._zod.def,{get shape(){const o=t._zod.def.shape,i={...o};if(r)for(const s in r){if(!(s in i))throw new Error(`Unrecognized key: "${s}"`);r[s]&&(i[s]=new e({type:"nonoptional",innerType:o[s]}))}else for(const s in o)i[s]=new e({type:"nonoptional",innerType:o[s]});return Yp(this,"shape",i),i}});return Ol(t,n)}function zh(e,t=0){if(e.aborted===!0)return!0;for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue!==!0)return!0;return!1}function Ec(e,t){return t.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(e),r})}function m_(e){return typeof e=="string"?e:e?.message}function Dl(e,t,r){const n={...e,path:e.path??[]};if(!e.message){const o=m_(e.inst?._zod.def?.error?.(e))??m_(t?.error?.(e))??m_(r.customError?.(e))??m_(r.localeError?.(e))??"Invalid input";n.message=o}return delete n.inst,delete n.continue,t?.reportInput||delete n.input,n}function II(e){return e instanceof Set?"set":e instanceof Map?"map":e instanceof File?"file":"unknown"}function RI(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function Ft(e){const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"nan":"number";case"object":{if(e===null)return"null";if(Array.isArray(e))return"array";const r=e;if(r&&Object.getPrototypeOf(r)!==Object.prototype&&"constructor"in r&&r.constructor)return r.constructor.name}}return t}function PI(...e){const[t,r,n]=e;return typeof t=="string"?{message:t,code:"custom",input:r,inst:n}:{...t}}function ICr(e){return Object.entries(e).filter(([t,r])=>Number.isNaN(Number.parseInt(t,10))).map(t=>t[1])}function W0e(e){const t=atob(e),r=new Uint8Array(t.length);for(let n=0;n<t.length;n++)r[n]=t.charCodeAt(n);return r}function K0e(e){let t="";for(let r=0;r<e.length;r++)t+=String.fromCharCode(e[r]);return btoa(t)}function RCr(e){const t=e.replace(/-/g,"+").replace(/_/g,"/"),r="=".repeat((4-t.length%4)%4);return W0e(t+r)}function PCr(e){return K0e(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function MCr(e){const t=e.replace(/^0x/,"");if(t.length%2!==0)throw new Error("Invalid hex string length");const r=new Uint8Array(t.length/2);for(let n=0;n<t.length;n+=2)r[n/2]=Number.parseInt(t.slice(n,n+2),16);return r}function OCr(e){return Array.from(e).map(t=>t.toString(16).padStart(2,"0")).join("")}var x5,MI,A5,J0e,h_,C5,I5,R5,X0e,Et=E({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/util.js"(){x5=Symbol("evaluating"),MI="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{},A5=p_(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{const e=Function;return new e(""),!0}catch{return!1}}),J0e=e=>{const t=typeof e;switch(t){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(e)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(e)?"array":e===null?"null":e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?"promise":typeof Map<"u"&&e instanceof Map?"map":typeof Set<"u"&&e instanceof Set?"set":typeof Date<"u"&&e instanceof Date?"date":typeof File<"u"&&e instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${t}`)}},h_=new Set(["string","number","symbol"]),C5=new Set(["string","number","bigint","boolean","symbol","undefined"]),I5={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},R5={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]},X0e=class{constructor(...e){}}}});function P5(e,t=r=>r.message){const r={},n=[];for(const o of e.issues)o.path.length>0?(r[o.path[0]]=r[o.path[0]]||[],r[o.path[0]].push(t(o))):n.push(t(o));return{formErrors:n,fieldErrors:r}}function M5(e,t=r=>r.message){const r={_errors:[]},n=o=>{for(const i of o.issues)if(i.code==="invalid_union"&&i.errors.length)i.errors.map(s=>n({issues:s}));else if(i.code==="invalid_key")n({issues:i.issues});else if(i.code==="invalid_element")n({issues:i.issues});else if(i.path.length===0)r._errors.push(t(i));else{let s=r,a=0;for(;a<i.path.length;){const l=i.path[a];a===i.path.length-1?(s[l]=s[l]||{_errors:[]},s[l]._errors.push(t(i))):s[l]=s[l]||{_errors:[]},s=s[l],a++}}};return n(e),r}function Y0e(e,t=r=>r.message){const r={errors:[]},n=(o,i=[])=>{var s,a;for(const l of o.issues)if(l.code==="invalid_union"&&l.errors.length)l.errors.map(c=>n({issues:c},l.path));else if(l.code==="invalid_key")n({issues:l.issues},l.path);else if(l.code==="invalid_element")n({issues:l.issues},l.path);else{const c=[...i,...l.path];if(c.length===0){r.errors.push(t(l));continue}let u=r,d=0;for(;d<c.length;){const p=c[d],m=d===c.length-1;typeof p=="string"?(u.properties??(u.properties={}),(s=u.properties)[p]??(s[p]={errors:[]}),u=u.properties[p]):(u.items??(u.items=[]),(a=u.items)[p]??(a[p]={errors:[]}),u=u.items[p]),m&&u.errors.push(t(l)),d++}}};return n(e),r}function Z0e(e){const t=[],r=e.map(n=>typeof n=="object"?n.key:n);for(const n of r)typeof n=="number"?t.push(`[${n}]`):typeof n=="symbol"?t.push(`[${JSON.stringify(String(n))}]`):/[^\w$]/.test(n)?t.push(`[${JSON.stringify(n)}]`):(t.length&&t.push("."),t.push(n));return t.join("")}function Q0e(e){const t=[],r=[...e.issues].sort((n,o)=>(n.path??[]).length-(o.path??[]).length);for(const n of r)t.push(`\u2716 ${n.message}`),n.path?.length&&t.push(` \u2192 at ${Z0e(n.path)}`);return t.join(`
|
|
23
|
+
`}static extractAnalyticsContext(t){return{hasUserId:!!t.userId,hasSessionId:!!t.sessionId,hasUserRole:!!t.userRole,hasOrgContext:!!t.organizationId,contextKeys:Object.keys(t),contextSize:JSON.stringify(t).length}}static extractEvaluationContext(t){return{userRole:t.userRole||"unknown",applicationContext:t.applicationContext?.name||"unknown",organizationContext:t.organizationId||"unknown",hasPreferences:!!t.userPreferences}}},O0e=class yme{static convertBusinessContext(t,r,n={}){const{preserveLegacyFields:o=!1,validateDomainData:i=!0,includeMetadata:s=!0}=n;return{sessionId:t.sessionId,userId:t.userId,config:{domainType:r,providerConfig:{token:t.apiToken||t.authToken||t.accessToken,endpoint:t.apiEndpoint||t.serviceUrl,provider:yme.inferProvider(t)},platformConfig:{type:t.platformType||"generic",url:t.platformUrl||t.serviceUrl,id:t.platformId||t.serviceId,integrations:t.platformIntegrations||[]},operationalConfig:{demoMode:t.enableDemoMode||!1,environment:t.environment||"production",region:t.region,features:t.enabledFeatures||[]},customData:{...o?{entityId:t.entityId||t.organizationId,departmentId:t.departmentId,projectId:t.projectId}:{},...yme.extractCustomData(t)}},metadata:s?{convertedFrom:"legacy-business-context",conversionTime:Date.now(),originalKeys:Object.keys(t),domainType:r}:void 0}}static createDomainContext(t,r,n={}){return{sessionId:n.sessionId||`session_${Date.now()}`,userId:n.userId,config:{domainType:t,customData:r},metadata:{source:"domain-context-factory",createdAt:Date.now(),domainType:t}}}static inferProvider(t){return t.apiToken||t.authToken?"api-provider":t.serviceUrl||t.endpoint?"service-provider":"generic-provider"}static extractCustomData(t){const r=b5.getFrameworkFieldsConfig();let n;r.overrideFields?n=new Set(r.overrideFields):n=new Set([...r.defaultFields,...r.additionalFields||[]]),r.includeFields&&r.includeFields.forEach(i=>n.delete(i));const o={};return Object.entries(t).forEach(([i,s])=>{n.has(i)||(o[i]=s)}),o}}}}),Ya,$Ar=E({"src/lib/types/conversation.ts"(){"use strict";Ya=class extends Error{constructor(e,t,r){super(e),this.code=t,this.details=r,this.name="ConversationMemoryError"}code;details}}}),UAr=E({"src/lib/types/conversationMemoryInterface.ts"(){"use strict"}}),BAr=E({"src/lib/types/delegation.ts"(){"use strict"}}),zAr=E({"src/lib/types/backgroundCommand.ts"(){"use strict"}}),GAr=E({"src/lib/types/gitTools.ts"(){"use strict"}}),qAr=E({"src/lib/types/pathSandbox.ts"(){"use strict"}}),VAr=E({"src/lib/types/fileToolRoots.ts"(){"use strict"}}),jAr=E({"src/lib/types/domain.ts"(){"use strict"}});function D0e(e){if(typeof e!="string"||e.length===0||e.length>G0e)return;const t=e.toLowerCase();let r=t.indexOf("models",0);for(;r!==-1;){let n=r+6;for(;n<e.length&&/\s/.test(e[n]);)n++;if(e[n]!=="="){r=t.indexOf("models",r+1);continue}for(n++;n<e.length&&/\s/.test(e[n]);)n++;if(e[n]!=="["){r=t.indexOf("models",r+1);continue}const o=n,i=e.indexOf("]",o+1);if(i===-1)return;const a=e.slice(o+1,i).split(",").map(l=>l.trim().replace(/^['"]|['"]$/g,"")).filter(l=>l.length>0);return a.length>0?a:void 0}}function N0e(e){const t=e.toLowerCase();return t.includes("team")&&t.includes("not allowed")||t.includes("team can only access")||/not\s+allowed\s+to\s+access\s+(this\s+)?model/i.test(e)}var ty,nt,Wr,kI,ai,Qi,Jo,Kp,L0e,F0e,$0e,U0e,B0e,z0e,hn,_5,ry,G0e,HAr=E({"src/lib/types/errors.ts"(){"use strict";ty=class extends Error{constructor(e){super(e),this.name=this.constructor.name}},nt=class extends ty{constructor(e,t){super(t?`[${t}] ${e}`:e),this.provider=t}provider},Wr=class extends nt{constructor(e,t){super(e,t)}},kI=class extends nt{constructor(e,t){super(e,t)}},ai=class extends nt{constructor(e,t){super(e,t)}},Qi=class extends nt{constructor(e,t){super(e,t)}},Jo=class extends nt{constructor(e,t){super(e,t)}},Kp=class extends ty{constructor(e,t){super(e),this.code=t,this.name="OAuthError"}code},L0e=class extends Kp{constructor(e){super(e,"CONFIGURATION_ERROR"),this.name="OAuthConfigurationError"}},F0e=class extends Kp{constructor(e,t){super(e,"TOKEN_EXCHANGE_ERROR"),this.statusCode=t,this.name="OAuthTokenExchangeError"}statusCode},$0e=class extends Kp{constructor(e,t){super(e,"TOKEN_REFRESH_ERROR"),this.statusCode=t,this.name="OAuthTokenRefreshError"}statusCode},U0e=class extends Kp{constructor(e){super(e,"TOKEN_VALIDATION_ERROR"),this.name="OAuthTokenValidationError"}},B0e=class extends Kp{constructor(e,t){super(e,"TOKEN_REVOCATION_ERROR"),this.statusCode=t,this.name="OAuthTokenRevocationError"}statusCode},z0e=class extends Kp{constructor(e){super(e,"CALLBACK_SERVER_ERROR"),this.name="OAuthCallbackServerError"}},hn=class extends ty{constructor(e,t="STORAGE_ERROR"){super(e),this.code=t,this.name="TokenStoreError"}code},_5=class extends ty{model;tier;requiredTier;constructor(e,t,r){super(`Model "${e}" is not available for tier "${t}". Required tier: "${r}" or higher.`),this.name="ModelAccessError",this.model=e,this.tier=t,this.requiredTier=r}},ry=class extends nt{requestedModel;allowedModels;code="MODEL_ACCESS_DENIED";constructor(e,t={}){super(e,t.provider),this.name="ModelAccessDeniedError",this.requestedModel=t.requestedModel,this.allowedModels=t.allowedModels}},G0e=1e4}}),WAr=E({"src/lib/types/evaluation.ts"(){"use strict"}}),KAr=E({"src/lib/types/evaluationProviders.ts"(){"use strict"}}),JAr=E({"src/lib/types/externalMcp.ts"(){"use strict"}}),XAr=E({"src/lib/types/file.ts"(){"use strict"}}),Jp,YAr=E({"src/lib/types/fileReference.ts"(){"use strict";Jp={TINY_MAX:10*1024,SMALL_MAX:100*1024,MEDIUM_MAX:5*1024*1024,LARGE_MAX:100*1024*1024,HUGE_MAX:2*1024*1024*1024}}}),ZAr=E({"src/lib/types/generate.ts"(){"use strict"}}),QAr=E({"src/lib/types/grounding.ts"(){"use strict"}}),eCr=E({"src/lib/types/guardrails.ts"(){"use strict"}}),tCr=E({"src/lib/types/hitl.ts"(){"use strict"}}),rCr=E({"src/lib/types/isolatedAgent.ts"(){"use strict"}}),nCr=E({"src/lib/types/knowledge.ts"(){"use strict"}}),oCr=E({"src/lib/types/livekit.ts"(){"use strict"}}),iCr=E({"src/lib/types/loopEngine.ts"(){"use strict"}}),sCr=E({"src/lib/types/mcp.ts"(){"use strict"}}),aCr=E({"src/lib/types/mcpOutput.ts"(){"use strict"}}),lCr=E({"src/lib/types/memory.ts"(){"use strict"}}),cCr=E({"src/lib/types/middleware.ts"(){"use strict"}});function fe(e,t,r){function n(a,l){if(a._zod||Object.defineProperty(a,"_zod",{value:{def:l,constr:s,traits:new Set},enumerable:!1}),a._zod.traits.has(e))return;a._zod.traits.add(e),t(a,l);const c=s.prototype,u=Object.keys(c);for(let d=0;d<u.length;d++){const p=u[d];p in a||(a[p]=c[p].bind(a))}}const o=r?.Parent??Object;class i extends o{}Object.defineProperty(i,"name",{value:e});function s(a){var l;const c=r?.Parent?new i:this;n(c,a),(l=c._zod).deferred??(l.deferred=[]);for(const u of c._zod.deferred)u();return c}return Object.defineProperty(s,"init",{value:n}),Object.defineProperty(s,Symbol.hasInstance,{value:a=>r?.Parent&&a instanceof r.Parent?!0:a?._zod?.traits?.has(e)}),Object.defineProperty(s,"name",{value:e}),s}function Is(e){return e&&Object.assign(u_,e),u_}var xI,E5,Xp,c_,u_,d_=E({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/core.js"(){xI=Object.freeze({status:"aborted"}),E5=Symbol("zod_brand"),Xp=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},c_=class extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name="ZodEncodeError"}},u_={}}}),vr={};Z(vr,{BIGINT_FORMAT_RANGES:()=>R5,Class:()=>X0e,NUMBER_FORMAT_RANGES:()=>I5,aborted:()=>zh,allowsEval:()=>A5,assert:()=>hCr,assertEqual:()=>uCr,assertIs:()=>pCr,assertNever:()=>mCr,assertNotEqual:()=>dCr,assignProp:()=>Yp,base64ToUint8Array:()=>W0e,base64urlToUint8Array:()=>RCr,cached:()=>p_,captureStackTrace:()=>MI,cleanEnum:()=>ICr,cleanRegex:()=>CI,clone:()=>Ol,cloneDef:()=>gCr,createTransparentProxy:()=>bCr,defineLazy:()=>nr,esc:()=>k5,escapeRegex:()=>_d,extend:()=>SCr,finalizeIssue:()=>Dl,floatSafeRemainder:()=>q0e,getElementAtPath:()=>yCr,getEnumValues:()=>S5,getLengthableOrigin:()=>RI,getParsedType:()=>J0e,getSizableOrigin:()=>II,hexToUint8Array:()=>MCr,isObject:()=>ny,isPlainObject:()=>Bh,issue:()=>PI,joinValues:()=>Ve,jsonStringifyReplacer:()=>AI,merge:()=>xCr,mergeDefs:()=>bd,normalizeParams:()=>Ke,nullish:()=>Uh,numKeys:()=>TCr,objectClone:()=>fCr,omit:()=>ECr,optionalKeys:()=>H0e,parsedType:()=>Ft,partial:()=>ACr,pick:()=>_Cr,prefixIssues:()=>Ec,primitiveTypes:()=>C5,promiseAllObject:()=>vCr,propertyKeyTypes:()=>h_,randomString:()=>wCr,required:()=>CCr,safeExtend:()=>kCr,shallowClone:()=>j0e,slugify:()=>V0e,stringifyPrimitive:()=>Mt,uint8ArrayToBase64:()=>K0e,uint8ArrayToBase64url:()=>PCr,uint8ArrayToHex:()=>OCr,unwrapMessage:()=>m_});function uCr(e){return e}function dCr(e){return e}function pCr(e){}function mCr(e){throw new Error("Unexpected value in exhaustive check")}function hCr(e){}function S5(e){const t=Object.values(e).filter(n=>typeof n=="number");return Object.entries(e).filter(([n,o])=>t.indexOf(+n)===-1).map(([n,o])=>o)}function Ve(e,t="|"){return e.map(r=>Mt(r)).join(t)}function AI(e,t){return typeof t=="bigint"?t.toString():t}function p_(e){return{get value(){{const r=e();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function Uh(e){return e==null}function CI(e){const t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}function q0e(e,t){const r=(e.toString().split(".")[1]||"").length,n=t.toString();let o=(n.split(".")[1]||"").length;if(o===0&&/\d?e-\d?/.test(n)){const l=n.match(/\d?e-(\d?)/);l?.[1]&&(o=Number.parseInt(l[1]))}const i=r>o?r:o,s=Number.parseInt(e.toFixed(i).replace(".","")),a=Number.parseInt(t.toFixed(i).replace(".",""));return s%a/10**i}function nr(e,t,r){let n;Object.defineProperty(e,t,{get(){if(n!==x5)return n===void 0&&(n=x5,n=r()),n},set(o){Object.defineProperty(e,t,{value:o})},configurable:!0})}function fCr(e){return Object.create(Object.getPrototypeOf(e),Object.getOwnPropertyDescriptors(e))}function Yp(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function bd(...e){const t={};for(const r of e){const n=Object.getOwnPropertyDescriptors(r);Object.assign(t,n)}return Object.defineProperties({},t)}function gCr(e){return bd(e._zod.def)}function yCr(e,t){return t?t.reduce((r,n)=>r?.[n],e):e}function vCr(e){const t=Object.keys(e),r=t.map(n=>e[n]);return Promise.all(r).then(n=>{const o={};for(let i=0;i<t.length;i++)o[t[i]]=n[i];return o})}function wCr(e=10){const t="abcdefghijklmnopqrstuvwxyz";let r="";for(let n=0;n<e;n++)r+=t[Math.floor(Math.random()*t.length)];return r}function k5(e){return JSON.stringify(e)}function V0e(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}function ny(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Bh(e){if(ny(e)===!1)return!1;const t=e.constructor;if(t===void 0||typeof t!="function")return!0;const r=t.prototype;return!(ny(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function j0e(e){return Bh(e)?{...e}:Array.isArray(e)?[...e]:e}function TCr(e){let t=0;for(const r in e)Object.prototype.hasOwnProperty.call(e,r)&&t++;return t}function _d(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Ol(e,t,r){const n=new e._zod.constr(t??e._zod.def);return(!t||r?.parent)&&(n._zod.parent=e),n}function Ke(e){const t=e;if(!t)return{};if(typeof t=="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error=="string"?{...t,error:()=>t.error}:t}function bCr(e){let t;return new Proxy({},{get(r,n,o){return t??(t=e()),Reflect.get(t,n,o)},set(r,n,o,i){return t??(t=e()),Reflect.set(t,n,o,i)},has(r,n){return t??(t=e()),Reflect.has(t,n)},deleteProperty(r,n){return t??(t=e()),Reflect.deleteProperty(t,n)},ownKeys(r){return t??(t=e()),Reflect.ownKeys(t)},getOwnPropertyDescriptor(r,n){return t??(t=e()),Reflect.getOwnPropertyDescriptor(t,n)},defineProperty(r,n,o){return t??(t=e()),Reflect.defineProperty(t,n,o)}})}function Mt(e){return typeof e=="bigint"?e.toString()+"n":typeof e=="string"?`"${e}"`:`${e}`}function H0e(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}function _Cr(e,t){const r=e._zod.def,n=r.checks;if(n&&n.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");const i=bd(e._zod.def,{get shape(){const s={};for(const a in t){if(!(a in r.shape))throw new Error(`Unrecognized key: "${a}"`);t[a]&&(s[a]=r.shape[a])}return Yp(this,"shape",s),s},checks:[]});return Ol(e,i)}function ECr(e,t){const r=e._zod.def,n=r.checks;if(n&&n.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");const i=bd(e._zod.def,{get shape(){const s={...e._zod.def.shape};for(const a in t){if(!(a in r.shape))throw new Error(`Unrecognized key: "${a}"`);t[a]&&delete s[a]}return Yp(this,"shape",s),s},checks:[]});return Ol(e,i)}function SCr(e,t){if(!Bh(t))throw new Error("Invalid input to extend: expected a plain object");const r=e._zod.def.checks;if(r&&r.length>0){const i=e._zod.def.shape;for(const s in t)if(Object.getOwnPropertyDescriptor(i,s)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}const o=bd(e._zod.def,{get shape(){const i={...e._zod.def.shape,...t};return Yp(this,"shape",i),i}});return Ol(e,o)}function kCr(e,t){if(!Bh(t))throw new Error("Invalid input to safeExtend: expected a plain object");const r=bd(e._zod.def,{get shape(){const n={...e._zod.def.shape,...t};return Yp(this,"shape",n),n}});return Ol(e,r)}function xCr(e,t){const r=bd(e._zod.def,{get shape(){const n={...e._zod.def.shape,...t._zod.def.shape};return Yp(this,"shape",n),n},get catchall(){return t._zod.def.catchall},checks:[]});return Ol(e,r)}function ACr(e,t,r){const o=t._zod.def.checks;if(o&&o.length>0)throw new Error(".partial() cannot be used on object schemas containing refinements");const s=bd(t._zod.def,{get shape(){const a=t._zod.def.shape,l={...a};if(r)for(const c in r){if(!(c in a))throw new Error(`Unrecognized key: "${c}"`);r[c]&&(l[c]=e?new e({type:"optional",innerType:a[c]}):a[c])}else for(const c in a)l[c]=e?new e({type:"optional",innerType:a[c]}):a[c];return Yp(this,"shape",l),l},checks:[]});return Ol(t,s)}function CCr(e,t,r){const n=bd(t._zod.def,{get shape(){const o=t._zod.def.shape,i={...o};if(r)for(const s in r){if(!(s in i))throw new Error(`Unrecognized key: "${s}"`);r[s]&&(i[s]=new e({type:"nonoptional",innerType:o[s]}))}else for(const s in o)i[s]=new e({type:"nonoptional",innerType:o[s]});return Yp(this,"shape",i),i}});return Ol(t,n)}function zh(e,t=0){if(e.aborted===!0)return!0;for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue!==!0)return!0;return!1}function Ec(e,t){return t.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(e),r})}function m_(e){return typeof e=="string"?e:e?.message}function Dl(e,t,r){const n={...e,path:e.path??[]};if(!e.message){const o=m_(e.inst?._zod.def?.error?.(e))??m_(t?.error?.(e))??m_(r.customError?.(e))??m_(r.localeError?.(e))??"Invalid input";n.message=o}return delete n.inst,delete n.continue,t?.reportInput||delete n.input,n}function II(e){return e instanceof Set?"set":e instanceof Map?"map":e instanceof File?"file":"unknown"}function RI(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function Ft(e){const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"nan":"number";case"object":{if(e===null)return"null";if(Array.isArray(e))return"array";const r=e;if(r&&Object.getPrototypeOf(r)!==Object.prototype&&"constructor"in r&&r.constructor)return r.constructor.name}}return t}function PI(...e){const[t,r,n]=e;return typeof t=="string"?{message:t,code:"custom",input:r,inst:n}:{...t}}function ICr(e){return Object.entries(e).filter(([t,r])=>Number.isNaN(Number.parseInt(t,10))).map(t=>t[1])}function W0e(e){const t=atob(e),r=new Uint8Array(t.length);for(let n=0;n<t.length;n++)r[n]=t.charCodeAt(n);return r}function K0e(e){let t="";for(let r=0;r<e.length;r++)t+=String.fromCharCode(e[r]);return btoa(t)}function RCr(e){const t=e.replace(/-/g,"+").replace(/_/g,"/"),r="=".repeat((4-t.length%4)%4);return W0e(t+r)}function PCr(e){return K0e(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function MCr(e){const t=e.replace(/^0x/,"");if(t.length%2!==0)throw new Error("Invalid hex string length");const r=new Uint8Array(t.length/2);for(let n=0;n<t.length;n+=2)r[n/2]=Number.parseInt(t.slice(n,n+2),16);return r}function OCr(e){return Array.from(e).map(t=>t.toString(16).padStart(2,"0")).join("")}var x5,MI,A5,J0e,h_,C5,I5,R5,X0e,Et=E({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/util.js"(){x5=Symbol("evaluating"),MI="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{},A5=p_(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{const e=Function;return new e(""),!0}catch{return!1}}),J0e=e=>{const t=typeof e;switch(t){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(e)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(e)?"array":e===null?"null":e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?"promise":typeof Map<"u"&&e instanceof Map?"map":typeof Set<"u"&&e instanceof Set?"set":typeof Date<"u"&&e instanceof Date?"date":typeof File<"u"&&e instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${t}`)}},h_=new Set(["string","number","symbol"]),C5=new Set(["string","number","bigint","boolean","symbol","undefined"]),I5={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},R5={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]},X0e=class{constructor(...e){}}}});function P5(e,t=r=>r.message){const r={},n=[];for(const o of e.issues)o.path.length>0?(r[o.path[0]]=r[o.path[0]]||[],r[o.path[0]].push(t(o))):n.push(t(o));return{formErrors:n,fieldErrors:r}}function M5(e,t=r=>r.message){const r={_errors:[]},n=o=>{for(const i of o.issues)if(i.code==="invalid_union"&&i.errors.length)i.errors.map(s=>n({issues:s}));else if(i.code==="invalid_key")n({issues:i.issues});else if(i.code==="invalid_element")n({issues:i.issues});else if(i.path.length===0)r._errors.push(t(i));else{let s=r,a=0;for(;a<i.path.length;){const l=i.path[a];a===i.path.length-1?(s[l]=s[l]||{_errors:[]},s[l]._errors.push(t(i))):s[l]=s[l]||{_errors:[]},s=s[l],a++}}};return n(e),r}function Y0e(e,t=r=>r.message){const r={errors:[]},n=(o,i=[])=>{var s,a;for(const l of o.issues)if(l.code==="invalid_union"&&l.errors.length)l.errors.map(c=>n({issues:c},l.path));else if(l.code==="invalid_key")n({issues:l.issues},l.path);else if(l.code==="invalid_element")n({issues:l.issues},l.path);else{const c=[...i,...l.path];if(c.length===0){r.errors.push(t(l));continue}let u=r,d=0;for(;d<c.length;){const p=c[d],m=d===c.length-1;typeof p=="string"?(u.properties??(u.properties={}),(s=u.properties)[p]??(s[p]={errors:[]}),u=u.properties[p]):(u.items??(u.items=[]),(a=u.items)[p]??(a[p]={errors:[]}),u=u.items[p]),m&&u.errors.push(t(l)),d++}}};return n(e),r}function Z0e(e){const t=[],r=e.map(n=>typeof n=="object"?n.key:n);for(const n of r)typeof n=="number"?t.push(`[${n}]`):typeof n=="symbol"?t.push(`[${JSON.stringify(String(n))}]`):/[^\w$]/.test(n)?t.push(`[${JSON.stringify(n)}]`):(t.length&&t.push("."),t.push(n));return t.join("")}function Q0e(e){const t=[],r=[...e.issues].sort((n,o)=>(n.path??[]).length-(o.path??[]).length);for(const n of r)t.push(`\u2716 ${n.message}`),n.path?.length&&t.push(` \u2192 at ${Z0e(n.path)}`);return t.join(`
|
|
24
24
|
`)}var O5,OI,ga,eye=E({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/errors.js"(){d_(),Et(),O5=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,AI,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},OI=fe("$ZodError",O5),ga=fe("$ZodError",O5,{Parent:Error})}}),oy,DI,iy,NI,sy,LI,ay,D5,FI,tye,$I,rye,UI,nye,BI,oye,zI,iye,GI,sye,qI,aye,VI,lye,cye=E({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/parse.js"(){d_(),eye(),Et(),oy=e=>(t,r,n,o)=>{const i=n?Object.assign(n,{async:!1}):{async:!1},s=t._zod.run({value:r,issues:[]},i);if(s instanceof Promise)throw new Xp;if(s.issues.length){const a=new(o?.Err??e)(s.issues.map(l=>Dl(l,i,Is())));throw MI(a,o?.callee),a}return s.value},DI=oy(ga),iy=e=>async(t,r,n,o)=>{const i=n?Object.assign(n,{async:!0}):{async:!0};let s=t._zod.run({value:r,issues:[]},i);if(s instanceof Promise&&(s=await s),s.issues.length){const a=new(o?.Err??e)(s.issues.map(l=>Dl(l,i,Is())));throw MI(a,o?.callee),a}return s.value},NI=iy(ga),sy=e=>(t,r,n)=>{const o=n?{...n,async:!1}:{async:!1},i=t._zod.run({value:r,issues:[]},o);if(i instanceof Promise)throw new Xp;return i.issues.length?{success:!1,error:new(e??OI)(i.issues.map(s=>Dl(s,o,Is())))}:{success:!0,data:i.value}},LI=sy(ga),ay=e=>async(t,r,n)=>{const o=n?Object.assign(n,{async:!0}):{async:!0};let i=t._zod.run({value:r,issues:[]},o);return i instanceof Promise&&(i=await i),i.issues.length?{success:!1,error:new e(i.issues.map(s=>Dl(s,o,Is())))}:{success:!0,data:i.value}},D5=ay(ga),FI=e=>(t,r,n)=>{const o=n?Object.assign(n,{direction:"backward"}):{direction:"backward"};return oy(e)(t,r,o)},tye=FI(ga),$I=e=>(t,r,n)=>oy(e)(t,r,n),rye=$I(ga),UI=e=>async(t,r,n)=>{const o=n?Object.assign(n,{direction:"backward"}):{direction:"backward"};return iy(e)(t,r,o)},nye=UI(ga),BI=e=>async(t,r,n)=>iy(e)(t,r,n),oye=BI(ga),zI=e=>(t,r,n)=>{const o=n?Object.assign(n,{direction:"backward"}):{direction:"backward"};return sy(e)(t,r,o)},iye=zI(ga),GI=e=>(t,r,n)=>sy(e)(t,r,n),sye=GI(ga),qI=e=>async(t,r,n)=>{const o=n?Object.assign(n,{direction:"backward"}):{direction:"backward"};return ay(e)(t,r,o)},aye=qI(ga),VI=e=>async(t,r,n)=>ay(e)(t,r,n),lye=VI(ga)}}),Gh={};Z(Gh,{base64:()=>X5,base64url:()=>jI,bigint:()=>tU,boolean:()=>nU,browserEmail:()=>bye,cidrv4:()=>K5,cidrv6:()=>J5,cuid:()=>N5,cuid2:()=>L5,date:()=>Q5,datetime:()=>mye,domain:()=>Sye,duration:()=>z5,e164:()=>Y5,email:()=>q5,emoji:()=>uye,extendedDuration:()=>hye,guid:()=>G5,hex:()=>kye,hostname:()=>Eye,html5Email:()=>vye,idnEmail:()=>Tye,integer:()=>rU,ipv4:()=>j5,ipv6:()=>H5,ksuid:()=>U5,lowercase:()=>sU,mac:()=>W5,md5_base64:()=>Aye,md5_base64url:()=>Cye,md5_hex:()=>xye,nanoid:()=>B5,null:()=>oU,number:()=>HI,rfc5322Email:()=>wye,sha1_base64:()=>Rye,sha1_base64url:()=>Pye,sha1_hex:()=>Iye,sha256_base64:()=>Oye,sha256_base64url:()=>Dye,sha256_hex:()=>Mye,sha384_base64:()=>Lye,sha384_base64url:()=>Fye,sha384_hex:()=>Nye,sha512_base64:()=>Uye,sha512_base64url:()=>Bye,sha512_hex:()=>$ye,string:()=>eU,time:()=>pye,ulid:()=>F5,undefined:()=>iU,unicodeEmail:()=>V5,uppercase:()=>aU,uuid:()=>qh,uuid4:()=>fye,uuid6:()=>gye,uuid7:()=>yye,xid:()=>$5});function uye(){return new RegExp(_ye,"u")}function dye(e){const t="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof e.precision=="number"?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function pye(e){return new RegExp(`^${dye(e)}$`)}function mye(e){const t=dye({precision:e.precision}),r=["Z"];e.local&&r.push(""),e.offset&&r.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");const n=`${t}(?:${r.join("|")})`;return new RegExp(`^${Z5}T(?:${n})$`)}function f_(e,t){return new RegExp(`^[A-Za-z0-9+/]{${e}}${t}$`)}function g_(e){return new RegExp(`^[A-Za-z0-9_-]{${e}}$`)}var N5,L5,F5,$5,U5,B5,z5,hye,G5,qh,fye,gye,yye,q5,vye,wye,V5,Tye,bye,_ye,j5,H5,W5,K5,J5,X5,jI,Eye,Sye,Y5,Z5,Q5,eU,tU,rU,HI,nU,oU,iU,sU,aU,kye,xye,Aye,Cye,Iye,Rye,Pye,Mye,Oye,Dye,Nye,Lye,Fye,$ye,Uye,Bye,lU=E({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/regexes.js"(){Et(),N5=/^[cC][^\s-]{8,}$/,L5=/^[0-9a-z]+$/,F5=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,$5=/^[0-9a-vA-V]{20}$/,U5=/^[A-Za-z0-9]{27}$/,B5=/^[a-zA-Z0-9_-]{21}$/,z5=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,hye=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,G5=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,qh=e=>e?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,fye=qh(4),gye=qh(6),yye=qh(7),q5=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,vye=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,wye=/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,V5=/^[^\s@"]{1,64}@[^\s@]{1,255}$/u,Tye=V5,bye=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,_ye="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",j5=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,H5=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,W5=e=>{const t=_d(e??":");return new RegExp(`^(?:[0-9A-F]{2}${t}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${t}){5}[0-9a-f]{2}$`)},K5=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,J5=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,X5=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,jI=/^[A-Za-z0-9_-]*$/,Eye=/^(?=.{1,253}\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\.?$/,Sye=/^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/,Y5=/^\+[1-9]\d{6,14}$/,Z5="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",Q5=new RegExp(`^${Z5}$`),eU=e=>{const t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},tU=/^-?\d+n?$/,rU=/^-?\d+$/,HI=/^-?\d+(?:\.\d+)?$/,nU=/^(?:true|false)$/i,oU=/^null$/i,iU=/^undefined$/i,sU=/^[^A-Z]*$/,aU=/^[^a-z]*$/,kye=/^[0-9a-fA-F]*$/,xye=/^[0-9a-fA-F]{32}$/,Aye=f_(22,"=="),Cye=g_(22),Iye=/^[0-9a-fA-F]{40}$/,Rye=f_(27,"="),Pye=g_(27),Mye=/^[0-9a-fA-F]{64}$/,Oye=f_(43,"="),Dye=g_(43),Nye=/^[0-9a-fA-F]{96}$/,Lye=f_(64,""),Fye=g_(64),$ye=/^[0-9a-fA-F]{128}$/,Uye=f_(86,"=="),Bye=g_(86)}});function zye(e,t,r){e.issues.length&&t.issues.push(...Ec(r,e.issues))}var to,cU,WI,KI,uU,dU,pU,mU,hU,fU,gU,yU,vU,ly,wU,TU,bU,_U,EU,SU,kU,xU,AU,CU=E({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/checks.js"(){d_(),lU(),Et(),to=fe("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])}),cU={number:"number",bigint:"bigint",object:"date"},WI=fe("$ZodCheckLessThan",(e,t)=>{to.init(e,t);const r=cU[typeof t.value];e._zod.onattach.push(n=>{const o=n._zod.bag,i=(t.inclusive?o.maximum:o.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value<i&&(t.inclusive?o.maximum=t.value:o.exclusiveMaximum=t.value)}),e._zod.check=n=>{(t.inclusive?n.value<=t.value:n.value<t.value)||n.issues.push({origin:r,code:"too_big",maximum:typeof t.value=="object"?t.value.getTime():t.value,input:n.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),KI=fe("$ZodCheckGreaterThan",(e,t)=>{to.init(e,t);const r=cU[typeof t.value];e._zod.onattach.push(n=>{const o=n._zod.bag,i=(t.inclusive?o.minimum:o.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>i&&(t.inclusive?o.minimum=t.value:o.exclusiveMinimum=t.value)}),e._zod.check=n=>{(t.inclusive?n.value>=t.value:n.value>t.value)||n.issues.push({origin:r,code:"too_small",minimum:typeof t.value=="object"?t.value.getTime():t.value,input:n.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),uU=fe("$ZodCheckMultipleOf",(e,t)=>{to.init(e,t),e._zod.onattach.push(r=>{var n;(n=r._zod.bag).multipleOf??(n.multipleOf=t.value)}),e._zod.check=r=>{if(typeof r.value!=typeof t.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof r.value=="bigint"?r.value%t.value===BigInt(0):q0e(r.value,t.value)===0)||r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:t.value,input:r.value,inst:e,continue:!t.abort})}}),dU=fe("$ZodCheckNumberFormat",(e,t)=>{to.init(e,t),t.format=t.format||"float64";const r=t.format?.includes("int"),n=r?"int":"number",[o,i]=I5[t.format];e._zod.onattach.push(s=>{const a=s._zod.bag;a.format=t.format,a.minimum=o,a.maximum=i,r&&(a.pattern=rU)}),e._zod.check=s=>{const a=s.value;if(r){if(!Number.isInteger(a)){s.issues.push({expected:n,format:t.format,code:"invalid_type",continue:!1,input:a,inst:e});return}if(!Number.isSafeInteger(a)){a>0?s.issues.push({input:a,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:n,inclusive:!0,continue:!t.abort}):s.issues.push({input:a,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:n,inclusive:!0,continue:!t.abort});return}}a<o&&s.issues.push({origin:"number",input:a,code:"too_small",minimum:o,inclusive:!0,inst:e,continue:!t.abort}),a>i&&s.issues.push({origin:"number",input:a,code:"too_big",maximum:i,inclusive:!0,inst:e,continue:!t.abort})}}),pU=fe("$ZodCheckBigIntFormat",(e,t)=>{to.init(e,t);const[r,n]=R5[t.format];e._zod.onattach.push(o=>{const i=o._zod.bag;i.format=t.format,i.minimum=r,i.maximum=n}),e._zod.check=o=>{const i=o.value;i<r&&o.issues.push({origin:"bigint",input:i,code:"too_small",minimum:r,inclusive:!0,inst:e,continue:!t.abort}),i>n&&o.issues.push({origin:"bigint",input:i,code:"too_big",maximum:n,inclusive:!0,inst:e,continue:!t.abort})}}),mU=fe("$ZodCheckMaxSize",(e,t)=>{var r;to.init(e,t),(r=e._zod.def).when??(r.when=n=>{const o=n.value;return!Uh(o)&&o.size!==void 0}),e._zod.onattach.push(n=>{const o=n._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<o&&(n._zod.bag.maximum=t.maximum)}),e._zod.check=n=>{const o=n.value;o.size<=t.maximum||n.issues.push({origin:II(o),code:"too_big",maximum:t.maximum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),hU=fe("$ZodCheckMinSize",(e,t)=>{var r;to.init(e,t),(r=e._zod.def).when??(r.when=n=>{const o=n.value;return!Uh(o)&&o.size!==void 0}),e._zod.onattach.push(n=>{const o=n._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>o&&(n._zod.bag.minimum=t.minimum)}),e._zod.check=n=>{const o=n.value;o.size>=t.minimum||n.issues.push({origin:II(o),code:"too_small",minimum:t.minimum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),fU=fe("$ZodCheckSizeEquals",(e,t)=>{var r;to.init(e,t),(r=e._zod.def).when??(r.when=n=>{const o=n.value;return!Uh(o)&&o.size!==void 0}),e._zod.onattach.push(n=>{const o=n._zod.bag;o.minimum=t.size,o.maximum=t.size,o.size=t.size}),e._zod.check=n=>{const o=n.value,i=o.size;if(i===t.size)return;const s=i>t.size;n.issues.push({origin:II(o),...s?{code:"too_big",maximum:t.size}:{code:"too_small",minimum:t.size},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),gU=fe("$ZodCheckMaxLength",(e,t)=>{var r;to.init(e,t),(r=e._zod.def).when??(r.when=n=>{const o=n.value;return!Uh(o)&&o.length!==void 0}),e._zod.onattach.push(n=>{const o=n._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<o&&(n._zod.bag.maximum=t.maximum)}),e._zod.check=n=>{const o=n.value;if(o.length<=t.maximum)return;const s=RI(o);n.issues.push({origin:s,code:"too_big",maximum:t.maximum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),yU=fe("$ZodCheckMinLength",(e,t)=>{var r;to.init(e,t),(r=e._zod.def).when??(r.when=n=>{const o=n.value;return!Uh(o)&&o.length!==void 0}),e._zod.onattach.push(n=>{const o=n._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>o&&(n._zod.bag.minimum=t.minimum)}),e._zod.check=n=>{const o=n.value;if(o.length>=t.minimum)return;const s=RI(o);n.issues.push({origin:s,code:"too_small",minimum:t.minimum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),vU=fe("$ZodCheckLengthEquals",(e,t)=>{var r;to.init(e,t),(r=e._zod.def).when??(r.when=n=>{const o=n.value;return!Uh(o)&&o.length!==void 0}),e._zod.onattach.push(n=>{const o=n._zod.bag;o.minimum=t.length,o.maximum=t.length,o.length=t.length}),e._zod.check=n=>{const o=n.value,i=o.length;if(i===t.length)return;const s=RI(o),a=i>t.length;n.issues.push({origin:s,...a?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),ly=fe("$ZodCheckStringFormat",(e,t)=>{var r,n;to.init(e,t),e._zod.onattach.push(o=>{const i=o._zod.bag;i.format=t.format,t.pattern&&(i.patterns??(i.patterns=new Set),i.patterns.add(t.pattern))}),t.pattern?(r=e._zod).check??(r.check=o=>{t.pattern.lastIndex=0,!t.pattern.test(o.value)&&o.issues.push({origin:"string",code:"invalid_format",format:t.format,input:o.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(n=e._zod).check??(n.check=()=>{})}),wU=fe("$ZodCheckRegex",(e,t)=>{ly.init(e,t),e._zod.check=r=>{t.pattern.lastIndex=0,!t.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),TU=fe("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=sU),ly.init(e,t)}),bU=fe("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=aU),ly.init(e,t)}),_U=fe("$ZodCheckIncludes",(e,t)=>{to.init(e,t);const r=_d(t.includes),n=new RegExp(typeof t.position=="number"?`^.{${t.position}}${r}`:r);t.pattern=n,e._zod.onattach.push(o=>{const i=o._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(n)}),e._zod.check=o=>{o.value.includes(t.includes,t.position)||o.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:o.value,inst:e,continue:!t.abort})}}),EU=fe("$ZodCheckStartsWith",(e,t)=>{to.init(e,t);const r=new RegExp(`^${_d(t.prefix)}.*`);t.pattern??(t.pattern=r),e._zod.onattach.push(n=>{const o=n._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),e._zod.check=n=>{n.value.startsWith(t.prefix)||n.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:n.value,inst:e,continue:!t.abort})}}),SU=fe("$ZodCheckEndsWith",(e,t)=>{to.init(e,t);const r=new RegExp(`.*${_d(t.suffix)}$`);t.pattern??(t.pattern=r),e._zod.onattach.push(n=>{const o=n._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),e._zod.check=n=>{n.value.endsWith(t.suffix)||n.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:n.value,inst:e,continue:!t.abort})}}),kU=fe("$ZodCheckProperty",(e,t)=>{to.init(e,t),e._zod.check=r=>{const n=t.schema._zod.run({value:r.value[t.property],issues:[]},{});if(n instanceof Promise)return n.then(o=>zye(o,r,t.property));zye(n,r,t.property)}}),xU=fe("$ZodCheckMimeType",(e,t)=>{to.init(e,t);const r=new Set(t.mime);e._zod.onattach.push(n=>{n._zod.bag.mime=t.mime}),e._zod.check=n=>{r.has(n.value.type)||n.issues.push({code:"invalid_value",values:t.mime,input:n.value.type,inst:e,continue:!t.abort})}}),AU=fe("$ZodCheckOverwrite",(e,t)=>{to.init(e,t),e._zod.check=r=>{r.value=t.tx(r.value)}})}}),IU,Gye=E({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/doc.js"(){IU=class{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if(typeof e=="function"){e(this,{execution:"sync"}),e(this,{execution:"async"});return}const r=e.split(`
|
|
25
25
|
`).filter(i=>i),n=Math.min(...r.map(i=>i.length-i.trimStart().length)),o=r.map(i=>i.slice(n)).map(i=>" ".repeat(this.indent*2)+i);for(const i of o)this.content.push(i)}compile(){const e=Function,t=this?.args,n=[...(this?.content??[""]).map(o=>` ${o}`)];return new e(...t,n.join(`
|
|
26
26
|
`))}}}}),RU,qye=E({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/versions.js"(){RU={major:4,minor:3,patch:6}}});function PU(e){if(e==="")return!0;if(e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}function Vye(e){if(!jI.test(e))return!1;const t=e.replace(/[-_]/g,n=>n==="-"?"+":"/"),r=t.padEnd(Math.ceil(t.length/4)*4,"=");return PU(r)}function jye(e,t=null){try{const r=e.split(".");if(r.length!==3)return!1;const[n]=r;if(!n)return!1;const o=JSON.parse(atob(n));return!("typ"in o&&o?.typ!=="JWT"||!o.alg||t&&(!("alg"in o)||o.alg!==t))}catch{return!1}}function Hye(e,t,r){e.issues.length&&t.issues.push(...Ec(r,e.issues)),t.value[r]=e.value}function JI(e,t,r,n,o){if(e.issues.length){if(o&&!(r in n))return;t.issues.push(...Ec(r,e.issues))}e.value===void 0?r in n&&(t.value[r]=void 0):t.value[r]=e.value}function Wye(e){const t=Object.keys(e.shape);for(const n of t)if(!e.shape?.[n]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${n}": expected a Zod schema`);const r=H0e(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(r)}}function Kye(e,t,r,n,o,i){const s=[],a=o.keySet,l=o.catchall._zod,c=l.def.type,u=l.optout==="optional";for(const d in t){if(a.has(d))continue;if(c==="never"){s.push(d);continue}const p=l.run({value:t[d],issues:[]},n);p instanceof Promise?e.push(p.then(m=>JI(m,r,d,t,u))):JI(p,r,d,t,u)}return s.length&&r.issues.push({code:"unrecognized_keys",keys:s,input:t,inst:i}),e.length?Promise.all(e).then(()=>r):r}function Jye(e,t,r,n){for(const i of e)if(i.issues.length===0)return t.value=i.value,t;const o=e.filter(i=>!zh(i));return o.length===1?(t.value=o[0].value,o[0]):(t.issues.push({code:"invalid_union",input:t.value,inst:r,errors:e.map(i=>i.issues.map(s=>Dl(s,n,Is())))}),t)}function Xye(e,t,r,n){const o=e.filter(i=>i.issues.length===0);return o.length===1?(t.value=o[0].value,t):(o.length===0?t.issues.push({code:"invalid_union",input:t.value,inst:r,errors:e.map(i=>i.issues.map(s=>Dl(s,n,Is())))}):t.issues.push({code:"invalid_union",input:t.value,inst:r,errors:[],inclusive:!1}),t)}function MU(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(Bh(e)&&Bh(t)){const r=Object.keys(t),n=Object.keys(e).filter(i=>r.indexOf(i)!==-1),o={...e,...t};for(const i of n){const s=MU(e[i],t[i]);if(!s.valid)return{valid:!1,mergeErrorPath:[i,...s.mergeErrorPath]};o[i]=s.data}return{valid:!0,data:o}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};const r=[];for(let n=0;n<e.length;n++){const o=e[n],i=t[n],s=MU(o,i);if(!s.valid)return{valid:!1,mergeErrorPath:[n,...s.mergeErrorPath]};r.push(s.data)}return{valid:!0,data:r}}return{valid:!1,mergeErrorPath:[]}}function Yye(e,t,r){const n=new Map;let o;for(const a of t.issues)if(a.code==="unrecognized_keys"){o??(o=a);for(const l of a.keys)n.has(l)||n.set(l,{}),n.get(l).l=!0}else e.issues.push(a);for(const a of r.issues)if(a.code==="unrecognized_keys")for(const l of a.keys)n.has(l)||n.set(l,{}),n.get(l).r=!0;else e.issues.push(a);const i=[...n].filter(([,a])=>a.l&&a.r).map(([a])=>a);if(i.length&&o&&e.issues.push({...o,keys:i}),zh(e))return e;const s=MU(t.value,r.value);if(!s.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(s.mergeErrorPath)}`);return e.value=s.data,e}function XI(e,t,r){e.issues.length&&t.issues.push(...Ec(r,e.issues)),t.value[r]=e.value}function Zye(e,t,r,n,o,i,s){e.issues.length&&(h_.has(typeof n)?r.issues.push(...Ec(n,e.issues)):r.issues.push({code:"invalid_key",origin:"map",input:o,inst:i,issues:e.issues.map(a=>Dl(a,s,Is()))})),t.issues.length&&(h_.has(typeof n)?r.issues.push(...Ec(n,t.issues)):r.issues.push({origin:"map",code:"invalid_element",input:o,inst:i,key:n,issues:t.issues.map(a=>Dl(a,s,Is()))})),r.value.set(e.value,t.value)}function Qye(e,t){e.issues.length&&t.issues.push(...e.issues),t.value.add(e.value)}function eve(e,t){return e.issues.length&&t===void 0?{issues:[],value:void 0}:e}function tve(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}function rve(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}function YI(e,t,r){return e.issues.length?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues},r)}function ZI(e,t,r){if(e.issues.length)return e.aborted=!0,e;if((r.direction||"forward")==="forward"){const o=t.transform(e.value,e);return o instanceof Promise?o.then(i=>QI(e,i,t.out,r)):QI(e,o,t.out,r)}else{const o=t.reverseTransform(e.value,e);return o instanceof Promise?o.then(i=>QI(e,i,t.in,r)):QI(e,o,t.in,r)}}function QI(e,t,r,n){return e.issues.length?(e.aborted=!0,e):r._zod.run({value:t,issues:e.issues},n)}function nve(e){return e.value=Object.freeze(e.value),e}function ove(e,t,r,n){if(!e){const o={code:"custom",input:r,inst:n,path:[...n._zod.def.path??[]],continue:!n._zod.def.abort};n._zod.def.params&&(o.params=n._zod.def.params),t.issues.push(PI(o))}}var zt,cy,on,OU,DU,NU,LU,FU,$U,UU,BU,zU,GU,qU,VU,jU,HU,WU,KU,JU,XU,YU,ZU,QU,eB,tB,rB,nB,eR,oB,tR,rR,iB,sB,aB,lB,cB,uB,dB,pB,mB,hB,fB,gB,y_,yB,vB,wB,nR,TB,bB,_B,EB,SB,kB,xB,oR,AB,CB,IB,RB,PB,MB,OB,DB,NB,iR,LB,FB,$B,UB,BB,zB,ive=E({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/schemas.js"(){CU(),d_(),Gye(),cye(),lU(),Et(),qye(),Et(),zt=fe("$ZodType",(e,t)=>{var r;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=RU;const n=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&n.unshift(e);for(const o of n)for(const i of o._zod.onattach)i(e);if(n.length===0)(r=e._zod).deferred??(r.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{const o=(s,a,l)=>{let c=zh(s),u;for(const d of a){if(d._zod.def.when){if(!d._zod.def.when(s))continue}else if(c)continue;const p=s.issues.length,m=d._zod.check(s);if(m instanceof Promise&&l?.async===!1)throw new Xp;if(u||m instanceof Promise)u=(u??Promise.resolve()).then(async()=>{await m,s.issues.length!==p&&(c||(c=zh(s,p)))});else{if(s.issues.length===p)continue;c||(c=zh(s,p))}}return u?u.then(()=>s):s},i=(s,a,l)=>{if(zh(s))return s.aborted=!0,s;const c=o(a,n,l);if(c instanceof Promise){if(l.async===!1)throw new Xp;return c.then(u=>e._zod.parse(u,l))}return e._zod.parse(c,l)};e._zod.run=(s,a)=>{if(a.skipChecks)return e._zod.parse(s,a);if(a.direction==="backward"){const c=e._zod.parse({value:s.value,issues:[]},{...a,skipChecks:!0});return c instanceof Promise?c.then(u=>i(u,s,a)):i(c,s,a)}const l=e._zod.parse(s,a);if(l instanceof Promise){if(a.async===!1)throw new Xp;return l.then(c=>o(c,n,a))}return o(l,n,a)}}nr(e,"~standard",()=>({validate:o=>{try{const i=LI(e,o);return i.success?{value:i.data}:{issues:i.error?.issues}}catch{return D5(e,o).then(s=>s.success?{value:s.data}:{issues:s.error?.issues})}},vendor:"zod",version:1}))}),cy=fe("$ZodString",(e,t)=>{zt.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??eU(e._zod.bag),e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=String(r.value)}catch{}return typeof r.value=="string"||r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:e}),r}}),on=fe("$ZodStringFormat",(e,t)=>{ly.init(e,t),cy.init(e,t)}),OU=fe("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=G5),on.init(e,t)}),DU=fe("$ZodUUID",(e,t)=>{if(t.version){const n={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(n===void 0)throw new Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=qh(n))}else t.pattern??(t.pattern=qh());on.init(e,t)}),NU=fe("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=q5),on.init(e,t)}),LU=fe("$ZodURL",(e,t)=>{on.init(e,t),e._zod.check=r=>{try{const n=r.value.trim(),o=new URL(n);t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(o.hostname)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:t.hostname.source,input:r.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(o.protocol.endsWith(":")?o.protocol.slice(0,-1):o.protocol)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:r.value,inst:e,continue:!t.abort})),t.normalize?r.value=o.href:r.value=n;return}catch{r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:e,continue:!t.abort})}}}),FU=fe("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=uye()),on.init(e,t)}),$U=fe("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=B5),on.init(e,t)}),UU=fe("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=N5),on.init(e,t)}),BU=fe("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=L5),on.init(e,t)}),zU=fe("$ZodULID",(e,t)=>{t.pattern??(t.pattern=F5),on.init(e,t)}),GU=fe("$ZodXID",(e,t)=>{t.pattern??(t.pattern=$5),on.init(e,t)}),qU=fe("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=U5),on.init(e,t)}),VU=fe("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=mye(t)),on.init(e,t)}),jU=fe("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=Q5),on.init(e,t)}),HU=fe("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=pye(t)),on.init(e,t)}),WU=fe("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=z5),on.init(e,t)}),KU=fe("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=j5),on.init(e,t),e._zod.bag.format="ipv4"}),JU=fe("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=H5),on.init(e,t),e._zod.bag.format="ipv6",e._zod.check=r=>{try{new URL(`http://[${r.value}]`)}catch{r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:e,continue:!t.abort})}}}),XU=fe("$ZodMAC",(e,t)=>{t.pattern??(t.pattern=W5(t.delimiter)),on.init(e,t),e._zod.bag.format="mac"}),YU=fe("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=K5),on.init(e,t)}),ZU=fe("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=J5),on.init(e,t),e._zod.check=r=>{const n=r.value.split("/");try{if(n.length!==2)throw new Error;const[o,i]=n;if(!i)throw new Error;const s=Number(i);if(`${s}`!==i)throw new Error;if(s<0||s>128)throw new Error;new URL(`http://[${o}]`)}catch{r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:e,continue:!t.abort})}}}),QU=fe("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=X5),on.init(e,t),e._zod.bag.contentEncoding="base64",e._zod.check=r=>{PU(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:e,continue:!t.abort})}}),eB=fe("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=jI),on.init(e,t),e._zod.bag.contentEncoding="base64url",e._zod.check=r=>{Vye(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:e,continue:!t.abort})}}),tB=fe("$ZodE164",(e,t)=>{t.pattern??(t.pattern=Y5),on.init(e,t)}),rB=fe("$ZodJWT",(e,t)=>{on.init(e,t),e._zod.check=r=>{jye(r.value,t.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:e,continue:!t.abort})}}),nB=fe("$ZodCustomStringFormat",(e,t)=>{on.init(e,t),e._zod.check=r=>{t.fn(r.value)||r.issues.push({code:"invalid_format",format:t.format,input:r.value,inst:e,continue:!t.abort})}}),eR=fe("$ZodNumber",(e,t)=>{zt.init(e,t),e._zod.pattern=e._zod.bag.pattern??HI,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=Number(r.value)}catch{}const o=r.value;if(typeof o=="number"&&!Number.isNaN(o)&&Number.isFinite(o))return r;const i=typeof o=="number"?Number.isNaN(o)?"NaN":Number.isFinite(o)?void 0:"Infinity":void 0;return r.issues.push({expected:"number",code:"invalid_type",input:o,inst:e,...i?{received:i}:{}}),r}}),oB=fe("$ZodNumberFormat",(e,t)=>{dU.init(e,t),eR.init(e,t)}),tR=fe("$ZodBoolean",(e,t)=>{zt.init(e,t),e._zod.pattern=nU,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=!!r.value}catch{}const o=r.value;return typeof o=="boolean"||r.issues.push({expected:"boolean",code:"invalid_type",input:o,inst:e}),r}}),rR=fe("$ZodBigInt",(e,t)=>{zt.init(e,t),e._zod.pattern=tU,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=BigInt(r.value)}catch{}return typeof r.value=="bigint"||r.issues.push({expected:"bigint",code:"invalid_type",input:r.value,inst:e}),r}}),iB=fe("$ZodBigIntFormat",(e,t)=>{pU.init(e,t),rR.init(e,t)}),sB=fe("$ZodSymbol",(e,t)=>{zt.init(e,t),e._zod.parse=(r,n)=>{const o=r.value;return typeof o=="symbol"||r.issues.push({expected:"symbol",code:"invalid_type",input:o,inst:e}),r}}),aB=fe("$ZodUndefined",(e,t)=>{zt.init(e,t),e._zod.pattern=iU,e._zod.values=new Set([void 0]),e._zod.optin="optional",e._zod.optout="optional",e._zod.parse=(r,n)=>{const o=r.value;return typeof o>"u"||r.issues.push({expected:"undefined",code:"invalid_type",input:o,inst:e}),r}}),lB=fe("$ZodNull",(e,t)=>{zt.init(e,t),e._zod.pattern=oU,e._zod.values=new Set([null]),e._zod.parse=(r,n)=>{const o=r.value;return o===null||r.issues.push({expected:"null",code:"invalid_type",input:o,inst:e}),r}}),cB=fe("$ZodAny",(e,t)=>{zt.init(e,t),e._zod.parse=r=>r}),uB=fe("$ZodUnknown",(e,t)=>{zt.init(e,t),e._zod.parse=r=>r}),dB=fe("$ZodNever",(e,t)=>{zt.init(e,t),e._zod.parse=(r,n)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:e}),r)}),pB=fe("$ZodVoid",(e,t)=>{zt.init(e,t),e._zod.parse=(r,n)=>{const o=r.value;return typeof o>"u"||r.issues.push({expected:"void",code:"invalid_type",input:o,inst:e}),r}}),mB=fe("$ZodDate",(e,t)=>{zt.init(e,t),e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=new Date(r.value)}catch{}const o=r.value,i=o instanceof Date;return i&&!Number.isNaN(o.getTime())||r.issues.push({expected:"date",code:"invalid_type",input:o,...i?{received:"Invalid Date"}:{},inst:e}),r}}),hB=fe("$ZodArray",(e,t)=>{zt.init(e,t),e._zod.parse=(r,n)=>{const o=r.value;if(!Array.isArray(o))return r.issues.push({expected:"array",code:"invalid_type",input:o,inst:e}),r;r.value=Array(o.length);const i=[];for(let s=0;s<o.length;s++){const a=o[s],l=t.element._zod.run({value:a,issues:[]},n);l instanceof Promise?i.push(l.then(c=>Hye(c,r,s))):Hye(l,r,s)}return i.length?Promise.all(i).then(()=>r):r}}),fB=fe("$ZodObject",(e,t)=>{if(zt.init(e,t),!Object.getOwnPropertyDescriptor(t,"shape")?.get){const a=t.shape;Object.defineProperty(t,"shape",{get:()=>{const l={...a};return Object.defineProperty(t,"shape",{value:l}),l}})}const n=p_(()=>Wye(t));nr(e._zod,"propValues",()=>{const a=t.shape,l={};for(const c in a){const u=a[c]._zod;if(u.values){l[c]??(l[c]=new Set);for(const d of u.values)l[c].add(d)}}return l});const o=ny,i=t.catchall;let s;e._zod.parse=(a,l)=>{s??(s=n.value);const c=a.value;if(!o(c))return a.issues.push({expected:"object",code:"invalid_type",input:c,inst:e}),a;a.value={};const u=[],d=s.shape;for(const p of s.keys){const m=d[p],f=m._zod.optout==="optional",g=m._zod.run({value:c[p],issues:[]},l);g instanceof Promise?u.push(g.then(y=>JI(y,a,p,c,f))):JI(g,a,p,c,f)}return i?Kye(u,c,a,l,n.value,e):u.length?Promise.all(u).then(()=>a):a}}),gB=fe("$ZodObjectJIT",(e,t)=>{fB.init(e,t);const r=e._zod.parse,n=p_(()=>Wye(t)),o=p=>{const m=new IU(["shape","payload","ctx"]),f=n.value,g=b=>{const S=k5(b);return`shape[${S}]._zod.run({ value: input[${S}], issues: [] }, ctx)`};m.write("const input = payload.value;");const y=Object.create(null);let v=0;for(const b of f.keys)y[b]=`key_${v++}`;m.write("const newResult = {};");for(const b of f.keys){const S=y[b],k=k5(b),x=p[b]?._zod?.optout==="optional";m.write(`const ${S} = ${g(b)};`),x?m.write(`
|
|
@@ -59,11 +59,11 @@ ${JSON.stringify(t,null,2)}
|
|
|
59
59
|
|
|
60
60
|
`)}m.write("payload.value = newResult;"),m.write("return payload;");const T=m.compile();return(b,S)=>T(p,b,S)};let i;const s=ny,a=!u_.jitless,c=a&&A5.value,u=t.catchall;let d;e._zod.parse=(p,m)=>{d??(d=n.value);const f=p.value;return s(f)?a&&c&&m?.async===!1&&m.jitless!==!0?(i||(i=o(t.shape)),p=i(p,m),u?Kye([],f,p,m,d,e):p):r(p,m):(p.issues.push({expected:"object",code:"invalid_type",input:f,inst:e}),p)}}),y_=fe("$ZodUnion",(e,t)=>{zt.init(e,t),nr(e._zod,"optin",()=>t.options.some(o=>o._zod.optin==="optional")?"optional":void 0),nr(e._zod,"optout",()=>t.options.some(o=>o._zod.optout==="optional")?"optional":void 0),nr(e._zod,"values",()=>{if(t.options.every(o=>o._zod.values))return new Set(t.options.flatMap(o=>Array.from(o._zod.values)))}),nr(e._zod,"pattern",()=>{if(t.options.every(o=>o._zod.pattern)){const o=t.options.map(i=>i._zod.pattern);return new RegExp(`^(${o.map(i=>CI(i.source)).join("|")})$`)}});const r=t.options.length===1,n=t.options[0]._zod.run;e._zod.parse=(o,i)=>{if(r)return n(o,i);let s=!1;const a=[];for(const l of t.options){const c=l._zod.run({value:o.value,issues:[]},i);if(c instanceof Promise)a.push(c),s=!0;else{if(c.issues.length===0)return c;a.push(c)}}return s?Promise.all(a).then(l=>Jye(l,o,e,i)):Jye(a,o,e,i)}}),yB=fe("$ZodXor",(e,t)=>{y_.init(e,t),t.inclusive=!1;const r=t.options.length===1,n=t.options[0]._zod.run;e._zod.parse=(o,i)=>{if(r)return n(o,i);let s=!1;const a=[];for(const l of t.options){const c=l._zod.run({value:o.value,issues:[]},i);c instanceof Promise?(a.push(c),s=!0):a.push(c)}return s?Promise.all(a).then(l=>Xye(l,o,e,i)):Xye(a,o,e,i)}}),vB=fe("$ZodDiscriminatedUnion",(e,t)=>{t.inclusive=!1,y_.init(e,t);const r=e._zod.parse;nr(e._zod,"propValues",()=>{const o={};for(const i of t.options){const s=i._zod.propValues;if(!s||Object.keys(s).length===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(i)}"`);for(const[a,l]of Object.entries(s)){o[a]||(o[a]=new Set);for(const c of l)o[a].add(c)}}return o});const n=p_(()=>{const o=t.options,i=new Map;for(const s of o){const a=s._zod.propValues?.[t.discriminator];if(!a||a.size===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(s)}"`);for(const l of a){if(i.has(l))throw new Error(`Duplicate discriminator value "${String(l)}"`);i.set(l,s)}}return i});e._zod.parse=(o,i)=>{const s=o.value;if(!ny(s))return o.issues.push({code:"invalid_type",expected:"object",input:s,inst:e}),o;const a=n.value.get(s?.[t.discriminator]);return a?a._zod.run(o,i):t.unionFallback?r(o,i):(o.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:t.discriminator,input:s,path:[t.discriminator],inst:e}),o)}}),wB=fe("$ZodIntersection",(e,t)=>{zt.init(e,t),e._zod.parse=(r,n)=>{const o=r.value,i=t.left._zod.run({value:o,issues:[]},n),s=t.right._zod.run({value:o,issues:[]},n);return i instanceof Promise||s instanceof Promise?Promise.all([i,s]).then(([l,c])=>Yye(r,l,c)):Yye(r,i,s)}}),nR=fe("$ZodTuple",(e,t)=>{zt.init(e,t);const r=t.items;e._zod.parse=(n,o)=>{const i=n.value;if(!Array.isArray(i))return n.issues.push({input:i,inst:e,expected:"tuple",code:"invalid_type"}),n;n.value=[];const s=[],a=[...r].reverse().findIndex(u=>u._zod.optin!=="optional"),l=a===-1?0:r.length-a;if(!t.rest){const u=i.length>r.length,d=i.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:i,inst:e,origin:"array"}),n}let c=-1;for(const u of r){if(c++,c>=i.length&&c>=l)continue;const d=u._zod.run({value:i[c],issues:[]},o);d instanceof Promise?s.push(d.then(p=>XI(p,n,c))):XI(d,n,c)}if(t.rest){const u=i.slice(r.length);for(const d of u){c++;const p=t.rest._zod.run({value:d,issues:[]},o);p instanceof Promise?s.push(p.then(m=>XI(m,n,c))):XI(p,n,c)}}return s.length?Promise.all(s).then(()=>n):n}}),TB=fe("$ZodRecord",(e,t)=>{zt.init(e,t),e._zod.parse=(r,n)=>{const o=r.value;if(!Bh(o))return r.issues.push({expected:"record",code:"invalid_type",input:o,inst:e}),r;const i=[],s=t.keyType._zod.values;if(s){r.value={};const a=new Set;for(const c of s)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?i.push(u.then(d=>{d.issues.length&&r.issues.push(...Ec(c,d.issues)),r.value[c]=d.value})):(u.issues.length&&r.issues.push(...Ec(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"&&HI.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=>Dl(d,n,Is())),input:a,path:[a],inst:e});continue}const u=t.valueType._zod.run({value:o[a],issues:[]},n);u instanceof Promise?i.push(u.then(d=>{d.issues.length&&r.issues.push(...Ec(a,d.issues)),r.value[l.value]=d.value})):(u.issues.length&&r.issues.push(...Ec(a,u.issues)),r.value[l.value]=u.value)}}return i.length?Promise.all(i).then(()=>r):r}}),bB=fe("$ZodMap",(e,t)=>{zt.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 i=[];r.value=new Map;for(const[s,a]of o){const l=t.keyType._zod.run({value:s,issues:[]},n),c=t.valueType._zod.run({value:a,issues:[]},n);l instanceof Promise||c instanceof Promise?i.push(Promise.all([l,c]).then(([u,d])=>{Zye(u,d,r,s,o,e,n)})):Zye(l,c,r,s,o,e,n)}return i.length?Promise.all(i).then(()=>r):r}}),_B=fe("$ZodSet",(e,t)=>{zt.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 i=[];r.value=new Set;for(const s of o){const a=t.valueType._zod.run({value:s,issues:[]},n);a instanceof Promise?i.push(a.then(l=>Qye(l,r))):Qye(a,r)}return i.length?Promise.all(i).then(()=>r):r}}),EB=fe("$ZodEnum",(e,t)=>{zt.init(e,t);const r=S5(t.entries),n=new Set(r);e._zod.values=n,e._zod.pattern=new RegExp(`^(${r.filter(o=>h_.has(typeof o)).map(o=>typeof o=="string"?_d(o):o.toString()).join("|")})$`),e._zod.parse=(o,i)=>{const s=o.value;return n.has(s)||o.issues.push({code:"invalid_value",values:r,input:s,inst:e}),o}}),SB=fe("$ZodLiteral",(e,t)=>{if(zt.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 i=n.value;return r.has(i)||n.issues.push({code:"invalid_value",values:t.values,input:i,inst:e}),n}}),kB=fe("$ZodFile",(e,t)=>{zt.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}}),xB=fe("$ZodTransform",(e,t)=>{zt.init(e,t),e._zod.parse=(r,n)=>{if(n.direction==="backward")throw new c_(e.constructor.name);const o=t.transform(r.value,r);if(n.async)return(o instanceof Promise?o:Promise.resolve(o)).then(s=>(r.value=s,r));if(o instanceof Promise)throw new Xp;return r.value=o,r}}),oR=fe("$ZodOptional",(e,t)=>{zt.init(e,t),e._zod.optin="optional",e._zod.optout="optional",nr(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),nr(e._zod,"pattern",()=>{const r=t.innerType._zod.pattern;return r?new RegExp(`^(${CI(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(i=>eve(i,r.value)):eve(o,r.value)}return r.value===void 0?r:t.innerType._zod.run(r,n)}}),AB=fe("$ZodExactOptional",(e,t)=>{oR.init(e,t),nr(e._zod,"values",()=>t.innerType._zod.values),nr(e._zod,"pattern",()=>t.innerType._zod.pattern),e._zod.parse=(r,n)=>t.innerType._zod.run(r,n)}),CB=fe("$ZodNullable",(e,t)=>{zt.init(e,t),nr(e._zod,"optin",()=>t.innerType._zod.optin),nr(e._zod,"optout",()=>t.innerType._zod.optout),nr(e._zod,"pattern",()=>{const r=t.innerType._zod.pattern;return r?new RegExp(`^(${CI(r.source)}|null)$`):void 0}),nr(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)}),IB=fe("$ZodDefault",(e,t)=>{zt.init(e,t),e._zod.optin="optional",nr(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(i=>tve(i,t)):tve(o,t)}}),RB=fe("$ZodPrefault",(e,t)=>{zt.init(e,t),e._zod.optin="optional",nr(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))}),PB=fe("$ZodNonOptional",(e,t)=>{zt.init(e,t),nr(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(i=>rve(i,e)):rve(o,e)}}),MB=fe("$ZodSuccess",(e,t)=>{zt.init(e,t),e._zod.parse=(r,n)=>{if(n.direction==="backward")throw new c_("ZodSuccess");const o=t.innerType._zod.run(r,n);return o instanceof Promise?o.then(i=>(r.value=i.issues.length===0,r)):(r.value=o.issues.length===0,r)}}),OB=fe("$ZodCatch",(e,t)=>{zt.init(e,t),nr(e._zod,"optin",()=>t.innerType._zod.optin),nr(e._zod,"optout",()=>t.innerType._zod.optout),nr(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(i=>(r.value=i.value,i.issues.length&&(r.value=t.catchValue({...r,error:{issues:i.issues.map(s=>Dl(s,n,Is()))},input:r.value}),r.issues=[]),r)):(r.value=o.value,o.issues.length&&(r.value=t.catchValue({...r,error:{issues:o.issues.map(i=>Dl(i,n,Is()))},input:r.value}),r.issues=[]),r)}}),DB=fe("$ZodNaN",(e,t)=>{zt.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)}),NB=fe("$ZodPipe",(e,t)=>{zt.init(e,t),nr(e._zod,"values",()=>t.in._zod.values),nr(e._zod,"optin",()=>t.in._zod.optin),nr(e._zod,"optout",()=>t.out._zod.optout),nr(e._zod,"propValues",()=>t.in._zod.propValues),e._zod.parse=(r,n)=>{if(n.direction==="backward"){const i=t.out._zod.run(r,n);return i instanceof Promise?i.then(s=>YI(s,t.in,n)):YI(i,t.in,n)}const o=t.in._zod.run(r,n);return o instanceof Promise?o.then(i=>YI(i,t.out,n)):YI(o,t.out,n)}}),iR=fe("$ZodCodec",(e,t)=>{zt.init(e,t),nr(e._zod,"values",()=>t.in._zod.values),nr(e._zod,"optin",()=>t.in._zod.optin),nr(e._zod,"optout",()=>t.out._zod.optout),nr(e._zod,"propValues",()=>t.in._zod.propValues),e._zod.parse=(r,n)=>{if((n.direction||"forward")==="forward"){const i=t.in._zod.run(r,n);return i instanceof Promise?i.then(s=>ZI(s,t,n)):ZI(i,t,n)}else{const i=t.out._zod.run(r,n);return i instanceof Promise?i.then(s=>ZI(s,t,n)):ZI(i,t,n)}}}),LB=fe("$ZodReadonly",(e,t)=>{zt.init(e,t),nr(e._zod,"propValues",()=>t.innerType._zod.propValues),nr(e._zod,"values",()=>t.innerType._zod.values),nr(e._zod,"optin",()=>t.innerType?._zod?.optin),nr(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(nve):nve(o)}}),FB=fe("$ZodTemplateLiteral",(e,t)=>{zt.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 i=o.startsWith("^")?1:0,s=o.endsWith("$")?o.length-1:o.length;r.push(o.slice(i,s))}else if(n===null||C5.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)}),$B=fe("$ZodFunction",(e,t)=>(zt.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?DI(e._def.input,n):n,i=Reflect.apply(r,this,o);return e._def.output?DI(e._def.output,i):i}},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 NI(e._def.input,n):n,i=await Reflect.apply(r,this,o);return e._def.output?await NI(e._def.output,i):i}},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 nR({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)),UB=fe("$ZodPromise",(e,t)=>{zt.init(e,t),e._zod.parse=(r,n)=>Promise.resolve(r.value).then(o=>t.innerType._zod.run({value:o,issues:[]},n))}),BB=fe("$ZodLazy",(e,t)=>{zt.init(e,t),nr(e._zod,"innerType",()=>t.getter()),nr(e._zod,"pattern",()=>e._zod.innerType?._zod?.pattern),nr(e._zod,"propValues",()=>e._zod.innerType?._zod?.propValues),nr(e._zod,"optin",()=>e._zod.innerType?._zod?.optin??void 0),nr(e._zod,"optout",()=>e._zod.innerType?._zod?.optout??void 0),e._zod.parse=(r,n)=>e._zod.innerType._zod.run(r,n)}),zB=fe("$ZodCustom",(e,t)=>{to.init(e,t),zt.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(i=>ove(i,r,n,e));ove(o,r,n,e)}})}});function DCr(){return{localeError:sve()}}var sve,NCr=E({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ar.js"(){Et(),sve=()=>{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 i=n[o.expected]??o.expected,s=Ft(o.input),a=n[s]??s;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 ${i}\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 ${Mt(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: ${Ve(o.values,"|")}`;case"too_big":{const i=o.inclusive?"<=":"<",s=t(o.origin);return s?` \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"} ${i} ${o.maximum.toString()} ${s.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"} ${i} ${o.maximum.toString()}`}case"too_small":{const i=o.inclusive?">=":">",s=t(o.origin);return s?`\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 ${i} ${o.minimum.toString()} ${s.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 ${i} ${o.minimum.toString()}`}case"invalid_format":{const i=o;return i.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}"`:i.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 "${i.suffix}"`:i.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 "${i.includes}"`:i.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 ${i.pattern}`:`${r[i.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":""}: ${Ve(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 LCr(){return{localeError:ave()}}var ave,FCr=E({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/az.js"(){Et(),ave=()=>{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 i=n[o.expected]??o.expected,s=Ft(o.input),a=n[s]??s;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 ${i}, daxil olan ${a}`}case"invalid_value":return o.values.length===1?`Yanl\u0131\u015F d\u0259y\u0259r: g\xF6zl\u0259nil\u0259n ${Mt(o.values[0])}`:`Yanl\u0131\u015F se\xE7im: a\u015Fa\u011F\u0131dak\u0131lardan biri olmal\u0131d\u0131r: ${Ve(o.values,"|")}`;case"too_big":{const i=o.inclusive?"<=":"<",s=t(o.origin);return s?`\xC7ox b\xF6y\xFCk: g\xF6zl\u0259nil\u0259n ${o.origin??"d\u0259y\u0259r"} ${i}${o.maximum.toString()} ${s.unit??"element"}`:`\xC7ox b\xF6y\xFCk: g\xF6zl\u0259nil\u0259n ${o.origin??"d\u0259y\u0259r"} ${i}${o.maximum.toString()}`}case"too_small":{const i=o.inclusive?">=":">",s=t(o.origin);return s?`\xC7ox ki\xE7ik: g\xF6zl\u0259nil\u0259n ${o.origin} ${i}${o.minimum.toString()} ${s.unit}`:`\xC7ox ki\xE7ik: g\xF6zl\u0259nil\u0259n ${o.origin} ${i}${o.minimum.toString()}`}case"invalid_format":{const i=o;return i.format==="starts_with"?`Yanl\u0131\u015F m\u0259tn: "${i.prefix}" il\u0259 ba\u015Flamal\u0131d\u0131r`:i.format==="ends_with"?`Yanl\u0131\u015F m\u0259tn: "${i.suffix}" il\u0259 bitm\u0259lidir`:i.format==="includes"?`Yanl\u0131\u015F m\u0259tn: "${i.includes}" daxil olmal\u0131d\u0131r`:i.format==="regex"?`Yanl\u0131\u015F m\u0259tn: ${i.pattern} \u015Fablonuna uy\u011Fun olmal\u0131d\u0131r`:`Yanl\u0131\u015F ${r[i.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":""}: ${Ve(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 lve(e,t,r,n){const o=Math.abs(e),i=o%10,s=o%100;return s>=11&&s<=19?n:i===1?t:i>=2&&i<=4?r:n}function $Cr(){return{localeError:cve()}}var cve,UCr=E({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/be.js"(){Et(),cve=()=>{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 i=n[o.expected]??o.expected,s=Ft(o.input),a=n[s]??s;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 ${i}, \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 ${Mt(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 ${Ve(o.values,"|")}`;case"too_big":{const i=o.inclusive?"<=":"<",s=t(o.origin);if(s){const a=Number(o.maximum),l=lve(a,s.unit.one,s.unit.few,s.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 ${s.verb} ${i}${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 ${i}${o.maximum.toString()}`}case"too_small":{const i=o.inclusive?">=":">",s=t(o.origin);if(s){const a=Number(o.minimum),l=lve(a,s.unit.one,s.unit.few,s.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 ${s.verb} ${i}${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 ${i}${o.minimum.toString()}`}case"invalid_format":{const i=o;return i.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 "${i.prefix}"`:i.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 "${i.suffix}"`:i.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 "${i.includes}"`:i.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 ${i.pattern}`:`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B ${r[i.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"}: ${Ve(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 BCr(){return{localeError:uve()}}var uve,zCr=E({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/bg.js"(){Et(),uve=()=>{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 i=n[o.expected]??o.expected,s=Ft(o.input),a=n[s]??s;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 ${i}, \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 ${Mt(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 ${Ve(o.values,"|")}`;case"too_big":{const i=o.inclusive?"<=":"<",s=t(o.origin);return s?`\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 ${i}${o.maximum.toString()} ${s.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 ${i}${o.maximum.toString()}`}case"too_small":{const i=o.inclusive?">=":">",s=t(o.origin);return s?`\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 ${i}${o.minimum.toString()} ${s.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 ${i}${o.minimum.toString()}`}case"invalid_format":{const i=o;if(i.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 "${i.prefix}"`;if(i.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 "${i.suffix}"`;if(i.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 "${i.includes}"`;if(i.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 ${i.pattern}`;let s="\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D";return i.format==="emoji"&&(s="\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u043E"),i.format==="datetime"&&(s="\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u043E"),i.format==="date"&&(s="\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u0430"),i.format==="time"&&(s="\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u043E"),i.format==="duration"&&(s="\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u0430"),`${s} ${r[i.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":""}: ${Ve(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 GCr(){return{localeError:dve()}}var dve,qCr=E({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ca.js"(){Et(),dve=()=>{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 i=n[o.expected]??o.expected,s=Ft(o.input),a=n[s]??s;return/^[A-Z]/.test(o.expected)?`Tipus inv\xE0lid: s'esperava instanceof ${o.expected}, s'ha rebut ${a}`:`Tipus inv\xE0lid: s'esperava ${i}, s'ha rebut ${a}`}case"invalid_value":return o.values.length===1?`Valor inv\xE0lid: s'esperava ${Mt(o.values[0])}`:`Opci\xF3 inv\xE0lida: s'esperava una de ${Ve(o.values," o ")}`;case"too_big":{const i=o.inclusive?"com a m\xE0xim":"menys de",s=t(o.origin);return s?`Massa gran: s'esperava que ${o.origin??"el valor"} contingu\xE9s ${i} ${o.maximum.toString()} ${s.unit??"elements"}`:`Massa gran: s'esperava que ${o.origin??"el valor"} fos ${i} ${o.maximum.toString()}`}case"too_small":{const i=o.inclusive?"com a m\xEDnim":"m\xE9s de",s=t(o.origin);return s?`Massa petit: s'esperava que ${o.origin} contingu\xE9s ${i} ${o.minimum.toString()} ${s.unit}`:`Massa petit: s'esperava que ${o.origin} fos ${i} ${o.minimum.toString()}`}case"invalid_format":{const i=o;return i.format==="starts_with"?`Format inv\xE0lid: ha de comen\xE7ar amb "${i.prefix}"`:i.format==="ends_with"?`Format inv\xE0lid: ha d'acabar amb "${i.suffix}"`:i.format==="includes"?`Format inv\xE0lid: ha d'incloure "${i.includes}"`:i.format==="regex"?`Format inv\xE0lid: ha de coincidir amb el patr\xF3 ${i.pattern}`:`Format inv\xE0lid per a ${r[i.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":""}: ${Ve(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 VCr(){return{localeError:pve()}}var pve,jCr=E({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/cs.js"(){Et(),pve=()=>{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 i=n[o.expected]??o.expected,s=Ft(o.input),a=n[s]??s;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 ${i}, obdr\u017Eeno ${a}`}case"invalid_value":return o.values.length===1?`Neplatn\xFD vstup: o\u010Dek\xE1v\xE1no ${Mt(o.values[0])}`:`Neplatn\xE1 mo\u017Enost: o\u010Dek\xE1v\xE1na jedna z hodnot ${Ve(o.values,"|")}`;case"too_big":{const i=o.inclusive?"<=":"<",s=t(o.origin);return s?`Hodnota je p\u0159\xEDli\u0161 velk\xE1: ${o.origin??"hodnota"} mus\xED m\xEDt ${i}${o.maximum.toString()} ${s.unit??"prvk\u016F"}`:`Hodnota je p\u0159\xEDli\u0161 velk\xE1: ${o.origin??"hodnota"} mus\xED b\xFDt ${i}${o.maximum.toString()}`}case"too_small":{const i=o.inclusive?">=":">",s=t(o.origin);return s?`Hodnota je p\u0159\xEDli\u0161 mal\xE1: ${o.origin??"hodnota"} mus\xED m\xEDt ${i}${o.minimum.toString()} ${s.unit??"prvk\u016F"}`:`Hodnota je p\u0159\xEDli\u0161 mal\xE1: ${o.origin??"hodnota"} mus\xED b\xFDt ${i}${o.minimum.toString()}`}case"invalid_format":{const i=o;return i.format==="starts_with"?`Neplatn\xFD \u0159et\u011Bzec: mus\xED za\u010D\xEDnat na "${i.prefix}"`:i.format==="ends_with"?`Neplatn\xFD \u0159et\u011Bzec: mus\xED kon\u010Dit na "${i.suffix}"`:i.format==="includes"?`Neplatn\xFD \u0159et\u011Bzec: mus\xED obsahovat "${i.includes}"`:i.format==="regex"?`Neplatn\xFD \u0159et\u011Bzec: mus\xED odpov\xEDdat vzoru ${i.pattern}`:`Neplatn\xFD form\xE1t ${r[i.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: ${Ve(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 HCr(){return{localeError:mve()}}var mve,WCr=E({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/da.js"(){Et(),mve=()=>{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 i=n[o.expected]??o.expected,s=Ft(o.input),a=n[s]??s;return/^[A-Z]/.test(o.expected)?`Ugyldigt input: forventede instanceof ${o.expected}, fik ${a}`:`Ugyldigt input: forventede ${i}, fik ${a}`}case"invalid_value":return o.values.length===1?`Ugyldig v\xE6rdi: forventede ${Mt(o.values[0])}`:`Ugyldigt valg: forventede en af f\xF8lgende ${Ve(o.values,"|")}`;case"too_big":{const i=o.inclusive?"<=":"<",s=t(o.origin),a=n[o.origin]??o.origin;return s?`For stor: forventede ${a??"value"} ${s.verb} ${i} ${o.maximum.toString()} ${s.unit??"elementer"}`:`For stor: forventede ${a??"value"} havde ${i} ${o.maximum.toString()}`}case"too_small":{const i=o.inclusive?">=":">",s=t(o.origin),a=n[o.origin]??o.origin;return s?`For lille: forventede ${a} ${s.verb} ${i} ${o.minimum.toString()} ${s.unit}`:`For lille: forventede ${a} havde ${i} ${o.minimum.toString()}`}case"invalid_format":{const i=o;return i.format==="starts_with"?`Ugyldig streng: skal starte med "${i.prefix}"`:i.format==="ends_with"?`Ugyldig streng: skal ende med "${i.suffix}"`:i.format==="includes"?`Ugyldig streng: skal indeholde "${i.includes}"`:i.format==="regex"?`Ugyldig streng: skal matche m\xF8nsteret ${i.pattern}`:`Ugyldig ${r[i.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"}: ${Ve(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 KCr(){return{localeError:hve()}}var hve,JCr=E({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/de.js"(){Et(),hve=()=>{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 i=n[o.expected]??o.expected,s=Ft(o.input),a=n[s]??s;return/^[A-Z]/.test(o.expected)?`Ung\xFCltige Eingabe: erwartet instanceof ${o.expected}, erhalten ${a}`:`Ung\xFCltige Eingabe: erwartet ${i}, erhalten ${a}`}case"invalid_value":return o.values.length===1?`Ung\xFCltige Eingabe: erwartet ${Mt(o.values[0])}`:`Ung\xFCltige Option: erwartet eine von ${Ve(o.values,"|")}`;case"too_big":{const i=o.inclusive?"<=":"<",s=t(o.origin);return s?`Zu gro\xDF: erwartet, dass ${o.origin??"Wert"} ${i}${o.maximum.toString()} ${s.unit??"Elemente"} hat`:`Zu gro\xDF: erwartet, dass ${o.origin??"Wert"} ${i}${o.maximum.toString()} ist`}case"too_small":{const i=o.inclusive?">=":">",s=t(o.origin);return s?`Zu klein: erwartet, dass ${o.origin} ${i}${o.minimum.toString()} ${s.unit} hat`:`Zu klein: erwartet, dass ${o.origin} ${i}${o.minimum.toString()} ist`}case"invalid_format":{const i=o;return i.format==="starts_with"?`Ung\xFCltiger String: muss mit "${i.prefix}" beginnen`:i.format==="ends_with"?`Ung\xFCltiger String: muss mit "${i.suffix}" enden`:i.format==="includes"?`Ung\xFCltiger String: muss "${i.includes}" enthalten`:i.format==="regex"?`Ung\xFCltiger String: muss dem Muster ${i.pattern} entsprechen`:`Ung\xFCltig: ${r[i.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"}: ${Ve(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 fve(){return{localeError:gve()}}var gve,yve=E({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/en.js"(){Et(),gve=()=>{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 i=n[o.expected]??o.expected,s=Ft(o.input),a=n[s]??s;return`Invalid input: expected ${i}, received ${a}`}case"invalid_value":return o.values.length===1?`Invalid input: expected ${Mt(o.values[0])}`:`Invalid option: expected one of ${Ve(o.values,"|")}`;case"too_big":{const i=o.inclusive?"<=":"<",s=t(o.origin);return s?`Too big: expected ${o.origin??"value"} to have ${i}${o.maximum.toString()} ${s.unit??"elements"}`:`Too big: expected ${o.origin??"value"} to be ${i}${o.maximum.toString()}`}case"too_small":{const i=o.inclusive?">=":">",s=t(o.origin);return s?`Too small: expected ${o.origin} to have ${i}${o.minimum.toString()} ${s.unit}`:`Too small: expected ${o.origin} to be ${i}${o.minimum.toString()}`}case"invalid_format":{const i=o;return i.format==="starts_with"?`Invalid string: must start with "${i.prefix}"`:i.format==="ends_with"?`Invalid string: must end with "${i.suffix}"`:i.format==="includes"?`Invalid string: must include "${i.includes}"`:i.format==="regex"?`Invalid string: must match pattern ${i.pattern}`:`Invalid ${r[i.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":""}: ${Ve(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 XCr(){return{localeError:vve()}}var vve,YCr=E({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/eo.js"(){Et(),vve=()=>{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 i=n[o.expected]??o.expected,s=Ft(o.input),a=n[s]??s;return/^[A-Z]/.test(o.expected)?`Nevalida enigo: atendi\u011Dis instanceof ${o.expected}, ricevi\u011Dis ${a}`:`Nevalida enigo: atendi\u011Dis ${i}, ricevi\u011Dis ${a}`}case"invalid_value":return o.values.length===1?`Nevalida enigo: atendi\u011Dis ${Mt(o.values[0])}`:`Nevalida opcio: atendi\u011Dis unu el ${Ve(o.values,"|")}`;case"too_big":{const i=o.inclusive?"<=":"<",s=t(o.origin);return s?`Tro granda: atendi\u011Dis ke ${o.origin??"valoro"} havu ${i}${o.maximum.toString()} ${s.unit??"elementojn"}`:`Tro granda: atendi\u011Dis ke ${o.origin??"valoro"} havu ${i}${o.maximum.toString()}`}case"too_small":{const i=o.inclusive?">=":">",s=t(o.origin);return s?`Tro malgranda: atendi\u011Dis ke ${o.origin} havu ${i}${o.minimum.toString()} ${s.unit}`:`Tro malgranda: atendi\u011Dis ke ${o.origin} estu ${i}${o.minimum.toString()}`}case"invalid_format":{const i=o;return i.format==="starts_with"?`Nevalida karaktraro: devas komenci\u011Di per "${i.prefix}"`:i.format==="ends_with"?`Nevalida karaktraro: devas fini\u011Di per "${i.suffix}"`:i.format==="includes"?`Nevalida karaktraro: devas inkluzivi "${i.includes}"`:i.format==="regex"?`Nevalida karaktraro: devas kongrui kun la modelo ${i.pattern}`:`Nevalida ${r[i.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":""}: ${Ve(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 ZCr(){return{localeError:wve()}}var wve,QCr=E({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/es.js"(){Et(),wve=()=>{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 i=n[o.expected]??o.expected,s=Ft(o.input),a=n[s]??s;return/^[A-Z]/.test(o.expected)?`Entrada inv\xE1lida: se esperaba instanceof ${o.expected}, recibido ${a}`:`Entrada inv\xE1lida: se esperaba ${i}, recibido ${a}`}case"invalid_value":return o.values.length===1?`Entrada inv\xE1lida: se esperaba ${Mt(o.values[0])}`:`Opci\xF3n inv\xE1lida: se esperaba una de ${Ve(o.values,"|")}`;case"too_big":{const i=o.inclusive?"<=":"<",s=t(o.origin),a=n[o.origin]??o.origin;return s?`Demasiado grande: se esperaba que ${a??"valor"} tuviera ${i}${o.maximum.toString()} ${s.unit??"elementos"}`:`Demasiado grande: se esperaba que ${a??"valor"} fuera ${i}${o.maximum.toString()}`}case"too_small":{const i=o.inclusive?">=":">",s=t(o.origin),a=n[o.origin]??o.origin;return s?`Demasiado peque\xF1o: se esperaba que ${a} tuviera ${i}${o.minimum.toString()} ${s.unit}`:`Demasiado peque\xF1o: se esperaba que ${a} fuera ${i}${o.minimum.toString()}`}case"invalid_format":{const i=o;return i.format==="starts_with"?`Cadena inv\xE1lida: debe comenzar con "${i.prefix}"`:i.format==="ends_with"?`Cadena inv\xE1lida: debe terminar en "${i.suffix}"`:i.format==="includes"?`Cadena inv\xE1lida: debe incluir "${i.includes}"`:i.format==="regex"?`Cadena inv\xE1lida: debe coincidir con el patr\xF3n ${i.pattern}`:`Inv\xE1lido ${r[i.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":""}: ${Ve(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 e1r(){return{localeError:Tve()}}var Tve,t1r=E({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/fa.js"(){Et(),Tve=()=>{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 i=n[o.expected]??o.expected,s=Ft(o.input),a=n[s]??s;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 ${i} \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 ${Mt(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 ${Ve(o.values,"|")} \u0645\u06CC\u200C\u0628\u0648\u062F`;case"too_big":{const i=o.inclusive?"<=":"<",s=t(o.origin);return s?`\u062E\u06CC\u0644\u06CC \u0628\u0632\u0631\u06AF: ${o.origin??"\u0645\u0642\u062F\u0627\u0631"} \u0628\u0627\u06CC\u062F ${i}${o.maximum.toString()} ${s.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 ${i}${o.maximum.toString()} \u0628\u0627\u0634\u062F`}case"too_small":{const i=o.inclusive?">=":">",s=t(o.origin);return s?`\u062E\u06CC\u0644\u06CC \u06A9\u0648\u0686\u06A9: ${o.origin} \u0628\u0627\u06CC\u062F ${i}${o.minimum.toString()} ${s.unit} \u0628\u0627\u0634\u062F`:`\u062E\u06CC\u0644\u06CC \u06A9\u0648\u0686\u06A9: ${o.origin} \u0628\u0627\u06CC\u062F ${i}${o.minimum.toString()} \u0628\u0627\u0634\u062F`}case"invalid_format":{const i=o;return i.format==="starts_with"?`\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0628\u0627 "${i.prefix}" \u0634\u0631\u0648\u0639 \u0634\u0648\u062F`:i.format==="ends_with"?`\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0628\u0627 "${i.suffix}" \u062A\u0645\u0627\u0645 \u0634\u0648\u062F`:i.format==="includes"?`\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0634\u0627\u0645\u0644 "${i.includes}" \u0628\u0627\u0634\u062F`:i.format==="regex"?`\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0628\u0627 \u0627\u0644\u06AF\u0648\u06CC ${i.pattern} \u0645\u0637\u0627\u0628\u0642\u062A \u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F`:`${r[i.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: ${Ve(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 r1r(){return{localeError:bve()}}var bve,n1r=E({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/fi.js"(){Et(),bve=()=>{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 i=n[o.expected]??o.expected,s=Ft(o.input),a=n[s]??s;return/^[A-Z]/.test(o.expected)?`Virheellinen tyyppi: odotettiin instanceof ${o.expected}, oli ${a}`:`Virheellinen tyyppi: odotettiin ${i}, oli ${a}`}case"invalid_value":return o.values.length===1?`Virheellinen sy\xF6te: t\xE4ytyy olla ${Mt(o.values[0])}`:`Virheellinen valinta: t\xE4ytyy olla yksi seuraavista: ${Ve(o.values,"|")}`;case"too_big":{const i=o.inclusive?"<=":"<",s=t(o.origin);return s?`Liian suuri: ${s.subject} t\xE4ytyy olla ${i}${o.maximum.toString()} ${s.unit}`.trim():`Liian suuri: arvon t\xE4ytyy olla ${i}${o.maximum.toString()}`}case"too_small":{const i=o.inclusive?">=":">",s=t(o.origin);return s?`Liian pieni: ${s.subject} t\xE4ytyy olla ${i}${o.minimum.toString()} ${s.unit}`.trim():`Liian pieni: arvon t\xE4ytyy olla ${i}${o.minimum.toString()}`}case"invalid_format":{const i=o;return i.format==="starts_with"?`Virheellinen sy\xF6te: t\xE4ytyy alkaa "${i.prefix}"`:i.format==="ends_with"?`Virheellinen sy\xF6te: t\xE4ytyy loppua "${i.suffix}"`:i.format==="includes"?`Virheellinen sy\xF6te: t\xE4ytyy sis\xE4lt\xE4\xE4 "${i.includes}"`:i.format==="regex"?`Virheellinen sy\xF6te: t\xE4ytyy vastata s\xE4\xE4nn\xF6llist\xE4 lauseketta ${i.pattern}`:`Virheellinen ${r[i.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"}: ${Ve(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 o1r(){return{localeError:_ve()}}var _ve,i1r=E({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/fr.js"(){Et(),_ve=()=>{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 i=n[o.expected]??o.expected,s=Ft(o.input),a=n[s]??s;return/^[A-Z]/.test(o.expected)?`Entr\xE9e invalide : instanceof ${o.expected} attendu, ${a} re\xE7u`:`Entr\xE9e invalide : ${i} attendu, ${a} re\xE7u`}case"invalid_value":return o.values.length===1?`Entr\xE9e invalide : ${Mt(o.values[0])} attendu`:`Option invalide : une valeur parmi ${Ve(o.values,"|")} attendue`;case"too_big":{const i=o.inclusive?"<=":"<",s=t(o.origin);return s?`Trop grand : ${o.origin??"valeur"} doit ${s.verb} ${i}${o.maximum.toString()} ${s.unit??"\xE9l\xE9ment(s)"}`:`Trop grand : ${o.origin??"valeur"} doit \xEAtre ${i}${o.maximum.toString()}`}case"too_small":{const i=o.inclusive?">=":">",s=t(o.origin);return s?`Trop petit : ${o.origin} doit ${s.verb} ${i}${o.minimum.toString()} ${s.unit}`:`Trop petit : ${o.origin} doit \xEAtre ${i}${o.minimum.toString()}`}case"invalid_format":{const i=o;return i.format==="starts_with"?`Cha\xEEne invalide : doit commencer par "${i.prefix}"`:i.format==="ends_with"?`Cha\xEEne invalide : doit se terminer par "${i.suffix}"`:i.format==="includes"?`Cha\xEEne invalide : doit inclure "${i.includes}"`:i.format==="regex"?`Cha\xEEne invalide : doit correspondre au mod\xE8le ${i.pattern}`:`${r[i.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":""} : ${Ve(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 s1r(){return{localeError:Eve()}}var Eve,a1r=E({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/fr-CA.js"(){Et(),Eve=()=>{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 i=n[o.expected]??o.expected,s=Ft(o.input),a=n[s]??s;return/^[A-Z]/.test(o.expected)?`Entr\xE9e invalide : attendu instanceof ${o.expected}, re\xE7u ${a}`:`Entr\xE9e invalide : attendu ${i}, re\xE7u ${a}`}case"invalid_value":return o.values.length===1?`Entr\xE9e invalide : attendu ${Mt(o.values[0])}`:`Option invalide : attendu l'une des valeurs suivantes ${Ve(o.values,"|")}`;case"too_big":{const i=o.inclusive?"\u2264":"<",s=t(o.origin);return s?`Trop grand : attendu que ${o.origin??"la valeur"} ait ${i}${o.maximum.toString()} ${s.unit}`:`Trop grand : attendu que ${o.origin??"la valeur"} soit ${i}${o.maximum.toString()}`}case"too_small":{const i=o.inclusive?"\u2265":">",s=t(o.origin);return s?`Trop petit : attendu que ${o.origin} ait ${i}${o.minimum.toString()} ${s.unit}`:`Trop petit : attendu que ${o.origin} soit ${i}${o.minimum.toString()}`}case"invalid_format":{const i=o;return i.format==="starts_with"?`Cha\xEEne invalide : doit commencer par "${i.prefix}"`:i.format==="ends_with"?`Cha\xEEne invalide : doit se terminer par "${i.suffix}"`:i.format==="includes"?`Cha\xEEne invalide : doit inclure "${i.includes}"`:i.format==="regex"?`Cha\xEEne invalide : doit correspondre au motif ${i.pattern}`:`${r[i.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":""} : ${Ve(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 l1r(){return{localeError:Sve()}}var Sve,c1r=E({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/he.js"(){Et(),Sve=()=>{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)}`,i=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",s=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),p=Ft(c.input),m=l[p]??e[p]?.label??p;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 ${m}`:`\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${d}, \u05D4\u05EA\u05E7\u05D1\u05DC ${m}`}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 ${Mt(c.values[0])}`;const u=c.values.map(m=>Mt(m));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=s(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 f=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 ${f}`}if(c.origin==="array"||c.origin==="set"){const f=c.origin==="set"?"\u05E6\u05E8\u05D9\u05DB\u05D4":"\u05E6\u05E8\u05D9\u05DA",g=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} ${f} \u05DC\u05D4\u05DB\u05D9\u05DC ${g}`.trim()}const p=c.inclusive?"<=":"<",m=i(c.origin??"value");return u?.unit?`${u.longLabel} \u05DE\u05D3\u05D9: ${d} ${m} ${p}${c.maximum.toString()} ${u.unit}`:`${u?.longLabel??"\u05D2\u05D3\u05D5\u05DC"} \u05DE\u05D3\u05D9: ${d} ${m} ${p}${c.maximum.toString()}`}case"too_small":{const u=s(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 f=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 ${f}`}if(c.origin==="array"||c.origin==="set"){const f=c.origin==="set"?"\u05E6\u05E8\u05D9\u05DB\u05D4":"\u05E6\u05E8\u05D9\u05DA";if(c.minimum===1&&c.inclusive){const y=(c.origin==="set","\u05DC\u05E4\u05D7\u05D5\u05EA \u05E4\u05E8\u05D9\u05D8 \u05D0\u05D7\u05D3");return`\u05E7\u05D8\u05DF \u05DE\u05D3\u05D9: ${d} ${f} \u05DC\u05D4\u05DB\u05D9\u05DC ${y}`}const g=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} ${f} \u05DC\u05D4\u05DB\u05D9\u05DC ${g}`.trim()}const p=c.inclusive?">=":">",m=i(c.origin??"value");return u?.unit?`${u.shortLabel} \u05DE\u05D3\u05D9: ${d} ${m} ${p}${c.minimum.toString()} ${u.unit}`:`${u?.shortLabel??"\u05E7\u05D8\u05DF"} \u05DE\u05D3\u05D9: ${d} ${m} ${p}${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],p=d?.label??u.format,f=(d?.gender??"m")==="f"?"\u05EA\u05E7\u05D9\u05E0\u05D4":"\u05EA\u05E7\u05D9\u05DF";return`${p} \u05DC\u05D0 ${f}`}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"}: ${Ve(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 u1r(){return{localeError:kve()}}var kve,d1r=E({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/hu.js"(){Et(),kve=()=>{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 i=n[o.expected]??o.expected,s=Ft(o.input),a=n[s]??s;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 ${i}, a kapott \xE9rt\xE9k ${a}`}case"invalid_value":return o.values.length===1?`\xC9rv\xE9nytelen bemenet: a v\xE1rt \xE9rt\xE9k ${Mt(o.values[0])}`:`\xC9rv\xE9nytelen opci\xF3: valamelyik \xE9rt\xE9k v\xE1rt ${Ve(o.values,"|")}`;case"too_big":{const i=o.inclusive?"<=":"<",s=t(o.origin);return s?`T\xFAl nagy: ${o.origin??"\xE9rt\xE9k"} m\xE9rete t\xFAl nagy ${i}${o.maximum.toString()} ${s.unit??"elem"}`:`T\xFAl nagy: a bemeneti \xE9rt\xE9k ${o.origin??"\xE9rt\xE9k"} t\xFAl nagy: ${i}${o.maximum.toString()}`}case"too_small":{const i=o.inclusive?">=":">",s=t(o.origin);return s?`T\xFAl kicsi: a bemeneti \xE9rt\xE9k ${o.origin} m\xE9rete t\xFAl kicsi ${i}${o.minimum.toString()} ${s.unit}`:`T\xFAl kicsi: a bemeneti \xE9rt\xE9k ${o.origin} t\xFAl kicsi ${i}${o.minimum.toString()}`}case"invalid_format":{const i=o;return i.format==="starts_with"?`\xC9rv\xE9nytelen string: "${i.prefix}" \xE9rt\xE9kkel kell kezd\u0151dnie`:i.format==="ends_with"?`\xC9rv\xE9nytelen string: "${i.suffix}" \xE9rt\xE9kkel kell v\xE9gz\u0151dnie`:i.format==="includes"?`\xC9rv\xE9nytelen string: "${i.includes}" \xE9rt\xE9ket kell tartalmaznia`:i.format==="regex"?`\xC9rv\xE9nytelen string: ${i.pattern} mint\xE1nak kell megfelelnie`:`\xC9rv\xE9nytelen ${r[i.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":""}: ${Ve(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 xve(e,t,r){return Math.abs(e)===1?t:r}function uy(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 p1r(){return{localeError:Ave()}}var Ave,m1r=E({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/hy.js"(){Et(),Ave=()=>{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 i=n[o.expected]??o.expected,s=Ft(o.input),a=n[s]??s;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 ${i}, \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 ${Mt(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 ${Ve(o.values,"|")}`;case"too_big":{const i=o.inclusive?"<=":"<",s=t(o.origin);if(s){const a=Number(o.maximum),l=xve(a,s.unit.one,s.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 ${uy(o.origin??"\u0561\u0580\u056A\u0565\u0584")} \u056F\u0578\u0582\u0576\u0565\u0576\u0561 ${i}${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 ${uy(o.origin??"\u0561\u0580\u056A\u0565\u0584")} \u056C\u056B\u0576\u056B ${i}${o.maximum.toString()}`}case"too_small":{const i=o.inclusive?">=":">",s=t(o.origin);if(s){const a=Number(o.minimum),l=xve(a,s.unit.one,s.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 ${uy(o.origin)} \u056F\u0578\u0582\u0576\u0565\u0576\u0561 ${i}${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 ${uy(o.origin)} \u056C\u056B\u0576\u056B ${i}${o.minimum.toString()}`}case"invalid_format":{const i=o;return i.format==="starts_with"?`\u054D\u056D\u0561\u056C \u057F\u0578\u0572\u2024 \u057A\u0565\u057F\u0584 \u0567 \u057D\u056F\u057D\u057E\u056B "${i.prefix}"-\u0578\u057E`:i.format==="ends_with"?`\u054D\u056D\u0561\u056C \u057F\u0578\u0572\u2024 \u057A\u0565\u057F\u0584 \u0567 \u0561\u057E\u0561\u0580\u057F\u057E\u056B "${i.suffix}"-\u0578\u057E`:i.format==="includes"?`\u054D\u056D\u0561\u056C \u057F\u0578\u0572\u2024 \u057A\u0565\u057F\u0584 \u0567 \u057A\u0561\u0580\u0578\u0582\u0576\u0561\u056F\u056B "${i.includes}"`:i.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 ${i.pattern} \u0571\u0587\u0561\u0579\u0561\u0583\u056B\u0576`:`\u054D\u056D\u0561\u056C ${r[i.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":""}. ${Ve(o.keys,", ")}`;case"invalid_key":return`\u054D\u056D\u0561\u056C \u0562\u0561\u0576\u0561\u056C\u056B ${uy(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 ${uy(o.origin)}-\u0578\u0582\u0574`;default:return"\u054D\u056D\u0561\u056C \u0574\u0578\u0582\u057F\u0584\u0561\u0563\u0580\u0578\u0582\u0574"}}}}});function h1r(){return{localeError:Cve()}}var Cve,f1r=E({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/id.js"(){Et(),Cve=()=>{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 i=n[o.expected]??o.expected,s=Ft(o.input),a=n[s]??s;return/^[A-Z]/.test(o.expected)?`Input tidak valid: diharapkan instanceof ${o.expected}, diterima ${a}`:`Input tidak valid: diharapkan ${i}, diterima ${a}`}case"invalid_value":return o.values.length===1?`Input tidak valid: diharapkan ${Mt(o.values[0])}`:`Pilihan tidak valid: diharapkan salah satu dari ${Ve(o.values,"|")}`;case"too_big":{const i=o.inclusive?"<=":"<",s=t(o.origin);return s?`Terlalu besar: diharapkan ${o.origin??"value"} memiliki ${i}${o.maximum.toString()} ${s.unit??"elemen"}`:`Terlalu besar: diharapkan ${o.origin??"value"} menjadi ${i}${o.maximum.toString()}`}case"too_small":{const i=o.inclusive?">=":">",s=t(o.origin);return s?`Terlalu kecil: diharapkan ${o.origin} memiliki ${i}${o.minimum.toString()} ${s.unit}`:`Terlalu kecil: diharapkan ${o.origin} menjadi ${i}${o.minimum.toString()}`}case"invalid_format":{const i=o;return i.format==="starts_with"?`String tidak valid: harus dimulai dengan "${i.prefix}"`:i.format==="ends_with"?`String tidak valid: harus berakhir dengan "${i.suffix}"`:i.format==="includes"?`String tidak valid: harus menyertakan "${i.includes}"`:i.format==="regex"?`String tidak valid: harus sesuai pola ${i.pattern}`:`${r[i.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":""}: ${Ve(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 g1r(){return{localeError:Ive()}}var Ive,y1r=E({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/is.js"(){Et(),Ive=()=>{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 i=n[o.expected]??o.expected,s=Ft(o.input),a=n[s]??s;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 ${i}`}case"invalid_value":return o.values.length===1?`Rangt gildi: gert r\xE1\xF0 fyrir ${Mt(o.values[0])}`:`\xD3gilt val: m\xE1 vera eitt af eftirfarandi ${Ve(o.values,"|")}`;case"too_big":{const i=o.inclusive?"<=":"<",s=t(o.origin);return s?`Of st\xF3rt: gert er r\xE1\xF0 fyrir a\xF0 ${o.origin??"gildi"} hafi ${i}${o.maximum.toString()} ${s.unit??"hluti"}`:`Of st\xF3rt: gert er r\xE1\xF0 fyrir a\xF0 ${o.origin??"gildi"} s\xE9 ${i}${o.maximum.toString()}`}case"too_small":{const i=o.inclusive?">=":">",s=t(o.origin);return s?`Of l\xEDti\xF0: gert er r\xE1\xF0 fyrir a\xF0 ${o.origin} hafi ${i}${o.minimum.toString()} ${s.unit}`:`Of l\xEDti\xF0: gert er r\xE1\xF0 fyrir a\xF0 ${o.origin} s\xE9 ${i}${o.minimum.toString()}`}case"invalid_format":{const i=o;return i.format==="starts_with"?`\xD3gildur strengur: ver\xF0ur a\xF0 byrja \xE1 "${i.prefix}"`:i.format==="ends_with"?`\xD3gildur strengur: ver\xF0ur a\xF0 enda \xE1 "${i.suffix}"`:i.format==="includes"?`\xD3gildur strengur: ver\xF0ur a\xF0 innihalda "${i.includes}"`:i.format==="regex"?`\xD3gildur strengur: ver\xF0ur a\xF0 fylgja mynstri ${i.pattern}`:`Rangt ${r[i.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"}: ${Ve(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 v1r(){return{localeError:Rve()}}var Rve,w1r=E({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/it.js"(){Et(),Rve=()=>{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 i=n[o.expected]??o.expected,s=Ft(o.input),a=n[s]??s;return/^[A-Z]/.test(o.expected)?`Input non valido: atteso instanceof ${o.expected}, ricevuto ${a}`:`Input non valido: atteso ${i}, ricevuto ${a}`}case"invalid_value":return o.values.length===1?`Input non valido: atteso ${Mt(o.values[0])}`:`Opzione non valida: atteso uno tra ${Ve(o.values,"|")}`;case"too_big":{const i=o.inclusive?"<=":"<",s=t(o.origin);return s?`Troppo grande: ${o.origin??"valore"} deve avere ${i}${o.maximum.toString()} ${s.unit??"elementi"}`:`Troppo grande: ${o.origin??"valore"} deve essere ${i}${o.maximum.toString()}`}case"too_small":{const i=o.inclusive?">=":">",s=t(o.origin);return s?`Troppo piccolo: ${o.origin} deve avere ${i}${o.minimum.toString()} ${s.unit}`:`Troppo piccolo: ${o.origin} deve essere ${i}${o.minimum.toString()}`}case"invalid_format":{const i=o;return i.format==="starts_with"?`Stringa non valida: deve iniziare con "${i.prefix}"`:i.format==="ends_with"?`Stringa non valida: deve terminare con "${i.suffix}"`:i.format==="includes"?`Stringa non valida: deve includere "${i.includes}"`:i.format==="regex"?`Stringa non valida: deve corrispondere al pattern ${i.pattern}`:`Invalid ${r[i.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"}: ${Ve(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 T1r(){return{localeError:Pve()}}var Pve,b1r=E({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ja.js"(){Et(),Pve=()=>{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 i=n[o.expected]??o.expected,s=Ft(o.input),a=n[s]??s;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: ${i}\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: ${Mt(o.values[0])}\u304C\u671F\u5F85\u3055\u308C\u307E\u3057\u305F`:`\u7121\u52B9\u306A\u9078\u629E: ${Ve(o.values,"\u3001")}\u306E\u3044\u305A\u308C\u304B\u3067\u3042\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;case"too_big":{const i=o.inclusive?"\u4EE5\u4E0B\u3067\u3042\u308B":"\u3088\u308A\u5C0F\u3055\u3044",s=t(o.origin);return s?`\u5927\u304D\u3059\u304E\u308B\u5024: ${o.origin??"\u5024"}\u306F${o.maximum.toString()}${s.unit??"\u8981\u7D20"}${i}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`:`\u5927\u304D\u3059\u304E\u308B\u5024: ${o.origin??"\u5024"}\u306F${o.maximum.toString()}${i}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`}case"too_small":{const i=o.inclusive?"\u4EE5\u4E0A\u3067\u3042\u308B":"\u3088\u308A\u5927\u304D\u3044",s=t(o.origin);return s?`\u5C0F\u3055\u3059\u304E\u308B\u5024: ${o.origin}\u306F${o.minimum.toString()}${s.unit}${i}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`:`\u5C0F\u3055\u3059\u304E\u308B\u5024: ${o.origin}\u306F${o.minimum.toString()}${i}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`}case"invalid_format":{const i=o;return i.format==="starts_with"?`\u7121\u52B9\u306A\u6587\u5B57\u5217: "${i.prefix}"\u3067\u59CB\u307E\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`:i.format==="ends_with"?`\u7121\u52B9\u306A\u6587\u5B57\u5217: "${i.suffix}"\u3067\u7D42\u308F\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`:i.format==="includes"?`\u7121\u52B9\u306A\u6587\u5B57\u5217: "${i.includes}"\u3092\u542B\u3080\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`:i.format==="regex"?`\u7121\u52B9\u306A\u6587\u5B57\u5217: \u30D1\u30BF\u30FC\u30F3${i.pattern}\u306B\u4E00\u81F4\u3059\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`:`\u7121\u52B9\u306A${r[i.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":""}: ${Ve(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 _1r(){return{localeError:Mve()}}var Mve,E1r=E({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ka.js"(){Et(),Mve=()=>{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 i=n[o.expected]??o.expected,s=Ft(o.input),a=n[s]??s;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 ${i}, \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 ${Mt(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 ${Ve(o.values,"|")}-\u10D3\u10D0\u10DC`;case"too_big":{const i=o.inclusive?"<=":"<",s=t(o.origin);return s?`\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"} ${s.verb} ${i}${o.maximum.toString()} ${s.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 ${i}${o.maximum.toString()}`}case"too_small":{const i=o.inclusive?">=":">",s=t(o.origin);return s?`\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} ${s.verb} ${i}${o.minimum.toString()} ${s.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 ${i}${o.minimum.toString()}`}case"invalid_format":{const i=o;return i.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 "${i.prefix}"-\u10D8\u10D7`:i.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 "${i.suffix}"-\u10D8\u10D7`:i.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 "${i.includes}"-\u10E1`:i.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 ${i.pattern}`:`\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 ${r[i.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"}: ${Ve(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 Ove(){return{localeError:Dve()}}var Dve,Nve=E({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/km.js"(){Et(),Dve=()=>{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 i=n[o.expected]??o.expected,s=Ft(o.input),a=n[s]??s;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 ${i} \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 ${Mt(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 ${Ve(o.values,"|")}`;case"too_big":{const i=o.inclusive?"<=":"<",s=t(o.origin);return s?`\u1792\u17C6\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${o.origin??"\u178F\u1798\u17D2\u179B\u17C3"} ${i} ${o.maximum.toString()} ${s.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"} ${i} ${o.maximum.toString()}`}case"too_small":{const i=o.inclusive?">=":">",s=t(o.origin);return s?`\u178F\u17BC\u1785\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${o.origin} ${i} ${o.minimum.toString()} ${s.unit}`:`\u178F\u17BC\u1785\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${o.origin} ${i} ${o.minimum.toString()}`}case"invalid_format":{const i=o;return i.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 "${i.prefix}"`:i.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 "${i.suffix}"`:i.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 "${i.includes}"`:i.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 ${i.pattern}`:`\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 ${r[i.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 ${Ve(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 S1r(){return Ove()}var k1r=E({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/kh.js"(){Nve()}});function x1r(){return{localeError:Lve()}}var Lve,A1r=E({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ko.js"(){Et(),Lve=()=>{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 i=n[o.expected]??o.expected,s=Ft(o.input),a=n[s]??s;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 ${i}, \uBC1B\uC740 \uD0C0\uC785\uC740 ${a}\uC785\uB2C8\uB2E4`}case"invalid_value":return o.values.length===1?`\uC798\uBABB\uB41C \uC785\uB825: \uAC12\uC740 ${Mt(o.values[0])} \uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4`:`\uC798\uBABB\uB41C \uC635\uC158: ${Ve(o.values,"\uB610\uB294 ")} \uC911 \uD558\uB098\uC5EC\uC57C \uD569\uB2C8\uB2E4`;case"too_big":{const i=o.inclusive?"\uC774\uD558":"\uBBF8\uB9CC",s=i==="\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} ${i}${s}`:`${o.origin??"\uAC12"}\uC774 \uB108\uBB34 \uD07D\uB2C8\uB2E4: ${o.maximum.toString()} ${i}${s}`}case"too_small":{const i=o.inclusive?"\uC774\uC0C1":"\uCD08\uACFC",s=i==="\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} ${i}${s}`:`${o.origin??"\uAC12"}\uC774 \uB108\uBB34 \uC791\uC2B5\uB2C8\uB2E4: ${o.minimum.toString()} ${i}${s}`}case"invalid_format":{const i=o;return i.format==="starts_with"?`\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: "${i.prefix}"(\uC73C)\uB85C \uC2DC\uC791\uD574\uC57C \uD569\uB2C8\uB2E4`:i.format==="ends_with"?`\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: "${i.suffix}"(\uC73C)\uB85C \uB05D\uB098\uC57C \uD569\uB2C8\uB2E4`:i.format==="includes"?`\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: "${i.includes}"\uC744(\uB97C) \uD3EC\uD568\uD574\uC57C \uD569\uB2C8\uB2E4`:i.format==="regex"?`\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: \uC815\uADDC\uC2DD ${i.pattern} \uD328\uD134\uACFC \uC77C\uCE58\uD574\uC57C \uD569\uB2C8\uB2E4`:`\uC798\uBABB\uB41C ${r[i.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: ${Ve(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 Fve(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 C1r(){return{localeError:$ve()}}var dy,$ve,I1r=E({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/lt.js"(){Et(),dy=e=>e.charAt(0).toUpperCase()+e.slice(1),$ve=()=>{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,i,s,a){const l=e[o]??null;return l===null?l:{unit:l.unit[i],verb:l.verb[a][s?"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 i=n[o.expected]??o.expected,s=Ft(o.input),a=n[s]??s;return/^[A-Z]/.test(o.expected)?`Gautas tipas ${a}, o tik\u0117tasi - instanceof ${o.expected}`:`Gautas tipas ${a}, o tik\u0117tasi - ${i}`}case"invalid_value":return o.values.length===1?`Privalo b\u016Bti ${Mt(o.values[0])}`:`Privalo b\u016Bti vienas i\u0161 ${Ve(o.values,"|")} pasirinkim\u0173`;case"too_big":{const i=n[o.origin]??o.origin,s=t(o.origin,Fve(Number(o.maximum)),o.inclusive??!1,"smaller");if(s?.verb)return`${dy(i??o.origin??"reik\u0161m\u0117")} ${s.verb} ${o.maximum.toString()} ${s.unit??"element\u0173"}`;const a=o.inclusive?"ne didesnis kaip":"ma\u017Eesnis kaip";return`${dy(i??o.origin??"reik\u0161m\u0117")} turi b\u016Bti ${a} ${o.maximum.toString()} ${s?.unit}`}case"too_small":{const i=n[o.origin]??o.origin,s=t(o.origin,Fve(Number(o.minimum)),o.inclusive??!1,"bigger");if(s?.verb)return`${dy(i??o.origin??"reik\u0161m\u0117")} ${s.verb} ${o.minimum.toString()} ${s.unit??"element\u0173"}`;const a=o.inclusive?"ne ma\u017Eesnis kaip":"didesnis kaip";return`${dy(i??o.origin??"reik\u0161m\u0117")} turi b\u016Bti ${a} ${o.minimum.toString()} ${s?.unit}`}case"invalid_format":{const i=o;return i.format==="starts_with"?`Eilut\u0117 privalo prasid\u0117ti "${i.prefix}"`:i.format==="ends_with"?`Eilut\u0117 privalo pasibaigti "${i.suffix}"`:i.format==="includes"?`Eilut\u0117 privalo \u012Ftraukti "${i.includes}"`:i.format==="regex"?`Eilut\u0117 privalo atitikti ${i.pattern}`:`Neteisingas ${r[i.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"}: ${Ve(o.keys,", ")}`;case"invalid_key":return"Rastas klaidingas raktas";case"invalid_union":return"Klaidinga \u012Fvestis";case"invalid_element":{const i=n[o.origin]??o.origin;return`${dy(i??o.origin??"reik\u0161m\u0117")} turi klaiding\u0105 \u012Fvest\u012F`}default:return"Klaidinga \u012Fvestis"}}}}});function R1r(){return{localeError:Uve()}}var Uve,P1r=E({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/mk.js"(){Et(),Uve=()=>{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 i=n[o.expected]??o.expected,s=Ft(o.input),a=n[s]??s;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 ${i}, \u043F\u0440\u0438\u043C\u0435\u043D\u043E ${a}`}case"invalid_value":return o.values.length===1?`Invalid input: expected ${Mt(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 ${Ve(o.values,"|")}`;case"too_big":{const i=o.inclusive?"<=":"<",s=t(o.origin);return s?`\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 ${i}${o.maximum.toString()} ${s.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 ${i}${o.maximum.toString()}`}case"too_small":{const i=o.inclusive?">=":">",s=t(o.origin);return s?`\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 ${i}${o.minimum.toString()} ${s.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 ${i}${o.minimum.toString()}`}case"invalid_format":{const i=o;return i.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 "${i.prefix}"`:i.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 "${i.suffix}"`:i.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 "${i.includes}"`:i.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 ${i.pattern}`:`Invalid ${r[i.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"}: ${Ve(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 M1r(){return{localeError:Bve()}}var Bve,O1r=E({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ms.js"(){Et(),Bve=()=>{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 i=n[o.expected]??o.expected,s=Ft(o.input),a=n[s]??s;return/^[A-Z]/.test(o.expected)?`Input tidak sah: dijangka instanceof ${o.expected}, diterima ${a}`:`Input tidak sah: dijangka ${i}, diterima ${a}`}case"invalid_value":return o.values.length===1?`Input tidak sah: dijangka ${Mt(o.values[0])}`:`Pilihan tidak sah: dijangka salah satu daripada ${Ve(o.values,"|")}`;case"too_big":{const i=o.inclusive?"<=":"<",s=t(o.origin);return s?`Terlalu besar: dijangka ${o.origin??"nilai"} ${s.verb} ${i}${o.maximum.toString()} ${s.unit??"elemen"}`:`Terlalu besar: dijangka ${o.origin??"nilai"} adalah ${i}${o.maximum.toString()}`}case"too_small":{const i=o.inclusive?">=":">",s=t(o.origin);return s?`Terlalu kecil: dijangka ${o.origin} ${s.verb} ${i}${o.minimum.toString()} ${s.unit}`:`Terlalu kecil: dijangka ${o.origin} adalah ${i}${o.minimum.toString()}`}case"invalid_format":{const i=o;return i.format==="starts_with"?`String tidak sah: mesti bermula dengan "${i.prefix}"`:i.format==="ends_with"?`String tidak sah: mesti berakhir dengan "${i.suffix}"`:i.format==="includes"?`String tidak sah: mesti mengandungi "${i.includes}"`:i.format==="regex"?`String tidak sah: mesti sepadan dengan corak ${i.pattern}`:`${r[i.format]??o.format} tidak sah`}case"not_multiple_of":return`Nombor tidak sah: perlu gandaan ${o.divisor}`;case"unrecognized_keys":return`Kunci tidak dikenali: ${Ve(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 D1r(){return{localeError:zve()}}var zve,N1r=E({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/nl.js"(){Et(),zve=()=>{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 i=n[o.expected]??o.expected,s=Ft(o.input),a=n[s]??s;return/^[A-Z]/.test(o.expected)?`Ongeldige invoer: verwacht instanceof ${o.expected}, ontving ${a}`:`Ongeldige invoer: verwacht ${i}, ontving ${a}`}case"invalid_value":return o.values.length===1?`Ongeldige invoer: verwacht ${Mt(o.values[0])}`:`Ongeldige optie: verwacht \xE9\xE9n van ${Ve(o.values,"|")}`;case"too_big":{const i=o.inclusive?"<=":"<",s=t(o.origin),a=o.origin==="date"?"laat":o.origin==="string"?"lang":"groot";return s?`Te ${a}: verwacht dat ${o.origin??"waarde"} ${i}${o.maximum.toString()} ${s.unit??"elementen"} ${s.verb}`:`Te ${a}: verwacht dat ${o.origin??"waarde"} ${i}${o.maximum.toString()} is`}case"too_small":{const i=o.inclusive?">=":">",s=t(o.origin),a=o.origin==="date"?"vroeg":o.origin==="string"?"kort":"klein";return s?`Te ${a}: verwacht dat ${o.origin} ${i}${o.minimum.toString()} ${s.unit} ${s.verb}`:`Te ${a}: verwacht dat ${o.origin} ${i}${o.minimum.toString()} is`}case"invalid_format":{const i=o;return i.format==="starts_with"?`Ongeldige tekst: moet met "${i.prefix}" beginnen`:i.format==="ends_with"?`Ongeldige tekst: moet op "${i.suffix}" eindigen`:i.format==="includes"?`Ongeldige tekst: moet "${i.includes}" bevatten`:i.format==="regex"?`Ongeldige tekst: moet overeenkomen met patroon ${i.pattern}`:`Ongeldig: ${r[i.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":""}: ${Ve(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 L1r(){return{localeError:Gve()}}var Gve,F1r=E({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/no.js"(){Et(),Gve=()=>{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 i=n[o.expected]??o.expected,s=Ft(o.input),a=n[s]??s;return/^[A-Z]/.test(o.expected)?`Ugyldig input: forventet instanceof ${o.expected}, fikk ${a}`:`Ugyldig input: forventet ${i}, fikk ${a}`}case"invalid_value":return o.values.length===1?`Ugyldig verdi: forventet ${Mt(o.values[0])}`:`Ugyldig valg: forventet en av ${Ve(o.values,"|")}`;case"too_big":{const i=o.inclusive?"<=":"<",s=t(o.origin);return s?`For stor(t): forventet ${o.origin??"value"} til \xE5 ha ${i}${o.maximum.toString()} ${s.unit??"elementer"}`:`For stor(t): forventet ${o.origin??"value"} til \xE5 ha ${i}${o.maximum.toString()}`}case"too_small":{const i=o.inclusive?">=":">",s=t(o.origin);return s?`For lite(n): forventet ${o.origin} til \xE5 ha ${i}${o.minimum.toString()} ${s.unit}`:`For lite(n): forventet ${o.origin} til \xE5 ha ${i}${o.minimum.toString()}`}case"invalid_format":{const i=o;return i.format==="starts_with"?`Ugyldig streng: m\xE5 starte med "${i.prefix}"`:i.format==="ends_with"?`Ugyldig streng: m\xE5 ende med "${i.suffix}"`:i.format==="includes"?`Ugyldig streng: m\xE5 inneholde "${i.includes}"`:i.format==="regex"?`Ugyldig streng: m\xE5 matche m\xF8nsteret ${i.pattern}`:`Ugyldig ${r[i.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"}: ${Ve(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 $1r(){return{localeError:qve()}}var qve,U1r=E({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ota.js"(){Et(),qve=()=>{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 i=n[o.expected]??o.expected,s=Ft(o.input),a=n[s]??s;return/^[A-Z]/.test(o.expected)?`F\xE2sit giren: umulan instanceof ${o.expected}, al\u0131nan ${a}`:`F\xE2sit giren: umulan ${i}, al\u0131nan ${a}`}case"invalid_value":return o.values.length===1?`F\xE2sit giren: umulan ${Mt(o.values[0])}`:`F\xE2sit tercih: m\xFBteberler ${Ve(o.values,"|")}`;case"too_big":{const i=o.inclusive?"<=":"<",s=t(o.origin);return s?`Fazla b\xFCy\xFCk: ${o.origin??"value"}, ${i}${o.maximum.toString()} ${s.unit??"elements"} sahip olmal\u0131yd\u0131.`:`Fazla b\xFCy\xFCk: ${o.origin??"value"}, ${i}${o.maximum.toString()} olmal\u0131yd\u0131.`}case"too_small":{const i=o.inclusive?">=":">",s=t(o.origin);return s?`Fazla k\xFC\xE7\xFCk: ${o.origin}, ${i}${o.minimum.toString()} ${s.unit} sahip olmal\u0131yd\u0131.`:`Fazla k\xFC\xE7\xFCk: ${o.origin}, ${i}${o.minimum.toString()} olmal\u0131yd\u0131.`}case"invalid_format":{const i=o;return i.format==="starts_with"?`F\xE2sit metin: "${i.prefix}" ile ba\u015Flamal\u0131.`:i.format==="ends_with"?`F\xE2sit metin: "${i.suffix}" ile bitmeli.`:i.format==="includes"?`F\xE2sit metin: "${i.includes}" ihtiv\xE2 etmeli.`:i.format==="regex"?`F\xE2sit metin: ${i.pattern} nak\u015F\u0131na uymal\u0131.`:`F\xE2sit ${r[i.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":""}: ${Ve(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 B1r(){return{localeError:Vve()}}var Vve,z1r=E({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ps.js"(){Et(),Vve=()=>{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 i=n[o.expected]??o.expected,s=Ft(o.input),a=n[s]??s;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 ${i} \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 ${Mt(o.values[0])} \u0648\u0627\u06CC`:`\u0646\u0627\u0633\u0645 \u0627\u0646\u062A\u062E\u0627\u0628: \u0628\u0627\u06CC\u062F \u06CC\u0648 \u0644\u0647 ${Ve(o.values,"|")} \u0685\u062E\u0647 \u0648\u0627\u06CC`;case"too_big":{const i=o.inclusive?"<=":"<",s=t(o.origin);return s?`\u0689\u06CC\u0631 \u0644\u0648\u06CC: ${o.origin??"\u0627\u0631\u0632\u069A\u062A"} \u0628\u0627\u06CC\u062F ${i}${o.maximum.toString()} ${s.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 ${i}${o.maximum.toString()} \u0648\u064A`}case"too_small":{const i=o.inclusive?">=":">",s=t(o.origin);return s?`\u0689\u06CC\u0631 \u06A9\u0648\u0686\u0646\u06CC: ${o.origin} \u0628\u0627\u06CC\u062F ${i}${o.minimum.toString()} ${s.unit} \u0648\u0644\u0631\u064A`:`\u0689\u06CC\u0631 \u06A9\u0648\u0686\u0646\u06CC: ${o.origin} \u0628\u0627\u06CC\u062F ${i}${o.minimum.toString()} \u0648\u064A`}case"invalid_format":{const i=o;return i.format==="starts_with"?`\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F \u062F "${i.prefix}" \u0633\u0631\u0647 \u067E\u06CC\u0644 \u0634\u064A`:i.format==="ends_with"?`\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F \u062F "${i.suffix}" \u0633\u0631\u0647 \u067E\u0627\u06CC \u062A\u0647 \u0648\u0631\u0633\u064A\u0696\u064A`:i.format==="includes"?`\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F "${i.includes}" \u0648\u0644\u0631\u064A`:i.format==="regex"?`\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F \u062F ${i.pattern} \u0633\u0631\u0647 \u0645\u0637\u0627\u0628\u0642\u062A \u0648\u0644\u0631\u064A`:`${r[i.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"}: ${Ve(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 G1r(){return{localeError:jve()}}var jve,q1r=E({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/pl.js"(){Et(),jve=()=>{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 i=n[o.expected]??o.expected,s=Ft(o.input),a=n[s]??s;return/^[A-Z]/.test(o.expected)?`Nieprawid\u0142owe dane wej\u015Bciowe: oczekiwano instanceof ${o.expected}, otrzymano ${a}`:`Nieprawid\u0142owe dane wej\u015Bciowe: oczekiwano ${i}, otrzymano ${a}`}case"invalid_value":return o.values.length===1?`Nieprawid\u0142owe dane wej\u015Bciowe: oczekiwano ${Mt(o.values[0])}`:`Nieprawid\u0142owa opcja: oczekiwano jednej z warto\u015Bci ${Ve(o.values,"|")}`;case"too_big":{const i=o.inclusive?"<=":"<",s=t(o.origin);return s?`Za du\u017Ca warto\u015B\u0107: oczekiwano, \u017Ce ${o.origin??"warto\u015B\u0107"} b\u0119dzie mie\u0107 ${i}${o.maximum.toString()} ${s.unit??"element\xF3w"}`:`Zbyt du\u017C(y/a/e): oczekiwano, \u017Ce ${o.origin??"warto\u015B\u0107"} b\u0119dzie wynosi\u0107 ${i}${o.maximum.toString()}`}case"too_small":{const i=o.inclusive?">=":">",s=t(o.origin);return s?`Za ma\u0142a warto\u015B\u0107: oczekiwano, \u017Ce ${o.origin??"warto\u015B\u0107"} b\u0119dzie mie\u0107 ${i}${o.minimum.toString()} ${s.unit??"element\xF3w"}`:`Zbyt ma\u0142(y/a/e): oczekiwano, \u017Ce ${o.origin??"warto\u015B\u0107"} b\u0119dzie wynosi\u0107 ${i}${o.minimum.toString()}`}case"invalid_format":{const i=o;return i.format==="starts_with"?`Nieprawid\u0142owy ci\u0105g znak\xF3w: musi zaczyna\u0107 si\u0119 od "${i.prefix}"`:i.format==="ends_with"?`Nieprawid\u0142owy ci\u0105g znak\xF3w: musi ko\u0144czy\u0107 si\u0119 na "${i.suffix}"`:i.format==="includes"?`Nieprawid\u0142owy ci\u0105g znak\xF3w: musi zawiera\u0107 "${i.includes}"`:i.format==="regex"?`Nieprawid\u0142owy ci\u0105g znak\xF3w: musi odpowiada\u0107 wzorcowi ${i.pattern}`:`Nieprawid\u0142ow(y/a/e) ${r[i.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":""}: ${Ve(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 V1r(){return{localeError:Hve()}}var Hve,j1r=E({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/pt.js"(){Et(),Hve=()=>{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 i=n[o.expected]??o.expected,s=Ft(o.input),a=n[s]??s;return/^[A-Z]/.test(o.expected)?`Tipo inv\xE1lido: esperado instanceof ${o.expected}, recebido ${a}`:`Tipo inv\xE1lido: esperado ${i}, recebido ${a}`}case"invalid_value":return o.values.length===1?`Entrada inv\xE1lida: esperado ${Mt(o.values[0])}`:`Op\xE7\xE3o inv\xE1lida: esperada uma das ${Ve(o.values,"|")}`;case"too_big":{const i=o.inclusive?"<=":"<",s=t(o.origin);return s?`Muito grande: esperado que ${o.origin??"valor"} tivesse ${i}${o.maximum.toString()} ${s.unit??"elementos"}`:`Muito grande: esperado que ${o.origin??"valor"} fosse ${i}${o.maximum.toString()}`}case"too_small":{const i=o.inclusive?">=":">",s=t(o.origin);return s?`Muito pequeno: esperado que ${o.origin} tivesse ${i}${o.minimum.toString()} ${s.unit}`:`Muito pequeno: esperado que ${o.origin} fosse ${i}${o.minimum.toString()}`}case"invalid_format":{const i=o;return i.format==="starts_with"?`Texto inv\xE1lido: deve come\xE7ar com "${i.prefix}"`:i.format==="ends_with"?`Texto inv\xE1lido: deve terminar com "${i.suffix}"`:i.format==="includes"?`Texto inv\xE1lido: deve incluir "${i.includes}"`:i.format==="regex"?`Texto inv\xE1lido: deve corresponder ao padr\xE3o ${i.pattern}`:`${r[i.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":""}: ${Ve(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 Wve(e,t,r,n){const o=Math.abs(e),i=o%10,s=o%100;return s>=11&&s<=19?n:i===1?t:i>=2&&i<=4?r:n}function H1r(){return{localeError:Kve()}}var Kve,W1r=E({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ru.js"(){Et(),Kve=()=>{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 i=n[o.expected]??o.expected,s=Ft(o.input),a=n[s]??s;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 ${i}, \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 ${Mt(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 ${Ve(o.values,"|")}`;case"too_big":{const i=o.inclusive?"<=":"<",s=t(o.origin);if(s){const a=Number(o.maximum),l=Wve(a,s.unit.one,s.unit.few,s.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 ${i}${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 ${i}${o.maximum.toString()}`}case"too_small":{const i=o.inclusive?">=":">",s=t(o.origin);if(s){const a=Number(o.minimum),l=Wve(a,s.unit.one,s.unit.few,s.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 ${i}${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 ${i}${o.minimum.toString()}`}case"invalid_format":{const i=o;return i.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 "${i.prefix}"`:i.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 "${i.suffix}"`:i.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 "${i.includes}"`:i.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 ${i.pattern}`:`\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 ${r[i.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":""}: ${Ve(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 K1r(){return{localeError:Jve()}}var Jve,J1r=E({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/sl.js"(){Et(),Jve=()=>{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 i=n[o.expected]??o.expected,s=Ft(o.input),a=n[s]??s;return/^[A-Z]/.test(o.expected)?`Neveljaven vnos: pri\u010Dakovano instanceof ${o.expected}, prejeto ${a}`:`Neveljaven vnos: pri\u010Dakovano ${i}, prejeto ${a}`}case"invalid_value":return o.values.length===1?`Neveljaven vnos: pri\u010Dakovano ${Mt(o.values[0])}`:`Neveljavna mo\u017Enost: pri\u010Dakovano eno izmed ${Ve(o.values,"|")}`;case"too_big":{const i=o.inclusive?"<=":"<",s=t(o.origin);return s?`Preveliko: pri\u010Dakovano, da bo ${o.origin??"vrednost"} imelo ${i}${o.maximum.toString()} ${s.unit??"elementov"}`:`Preveliko: pri\u010Dakovano, da bo ${o.origin??"vrednost"} ${i}${o.maximum.toString()}`}case"too_small":{const i=o.inclusive?">=":">",s=t(o.origin);return s?`Premajhno: pri\u010Dakovano, da bo ${o.origin} imelo ${i}${o.minimum.toString()} ${s.unit}`:`Premajhno: pri\u010Dakovano, da bo ${o.origin} ${i}${o.minimum.toString()}`}case"invalid_format":{const i=o;return i.format==="starts_with"?`Neveljaven niz: mora se za\u010Deti z "${i.prefix}"`:i.format==="ends_with"?`Neveljaven niz: mora se kon\u010Dati z "${i.suffix}"`:i.format==="includes"?`Neveljaven niz: mora vsebovati "${i.includes}"`:i.format==="regex"?`Neveljaven niz: mora ustrezati vzorcu ${i.pattern}`:`Neveljaven ${r[i.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"}: ${Ve(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 X1r(){return{localeError:Xve()}}var Xve,Y1r=E({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/sv.js"(){Et(),Xve=()=>{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 i=n[o.expected]??o.expected,s=Ft(o.input),a=n[s]??s;return/^[A-Z]/.test(o.expected)?`Ogiltig inmatning: f\xF6rv\xE4ntat instanceof ${o.expected}, fick ${a}`:`Ogiltig inmatning: f\xF6rv\xE4ntat ${i}, fick ${a}`}case"invalid_value":return o.values.length===1?`Ogiltig inmatning: f\xF6rv\xE4ntat ${Mt(o.values[0])}`:`Ogiltigt val: f\xF6rv\xE4ntade en av ${Ve(o.values,"|")}`;case"too_big":{const i=o.inclusive?"<=":"<",s=t(o.origin);return s?`F\xF6r stor(t): f\xF6rv\xE4ntade ${o.origin??"v\xE4rdet"} att ha ${i}${o.maximum.toString()} ${s.unit??"element"}`:`F\xF6r stor(t): f\xF6rv\xE4ntat ${o.origin??"v\xE4rdet"} att ha ${i}${o.maximum.toString()}`}case"too_small":{const i=o.inclusive?">=":">",s=t(o.origin);return s?`F\xF6r lite(t): f\xF6rv\xE4ntade ${o.origin??"v\xE4rdet"} att ha ${i}${o.minimum.toString()} ${s.unit}`:`F\xF6r lite(t): f\xF6rv\xE4ntade ${o.origin??"v\xE4rdet"} att ha ${i}${o.minimum.toString()}`}case"invalid_format":{const i=o;return i.format==="starts_with"?`Ogiltig str\xE4ng: m\xE5ste b\xF6rja med "${i.prefix}"`:i.format==="ends_with"?`Ogiltig str\xE4ng: m\xE5ste sluta med "${i.suffix}"`:i.format==="includes"?`Ogiltig str\xE4ng: m\xE5ste inneh\xE5lla "${i.includes}"`:i.format==="regex"?`Ogiltig str\xE4ng: m\xE5ste matcha m\xF6nstret "${i.pattern}"`:`Ogiltig(t) ${r[i.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"}: ${Ve(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 Z1r(){return{localeError:Yve()}}var Yve,Q1r=E({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ta.js"(){Et(),Yve=()=>{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 i=n[o.expected]??o.expected,s=Ft(o.input),a=n[s]??s;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 ${i}, \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 ${Mt(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 ${Ve(o.values,"|")} \u0B87\u0BB2\u0BCD \u0B92\u0BA9\u0BCD\u0BB1\u0BC1`;case"too_big":{const i=o.inclusive?"<=":"<",s=t(o.origin);return s?`\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"} ${i}${o.maximum.toString()} ${s.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"} ${i}${o.maximum.toString()} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`}case"too_small":{const i=o.inclusive?">=":">",s=t(o.origin);return s?`\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} ${i}${o.minimum.toString()} ${s.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} ${i}${o.minimum.toString()} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`}case"invalid_format":{const i=o;return i.format==="starts_with"?`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: "${i.prefix}" \u0B87\u0BB2\u0BCD \u0BA4\u0BCA\u0B9F\u0B99\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`:i.format==="ends_with"?`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: "${i.suffix}" \u0B87\u0BB2\u0BCD \u0BAE\u0BC1\u0B9F\u0BBF\u0BB5\u0B9F\u0BC8\u0BAF \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`:i.format==="includes"?`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: "${i.includes}" \u0B90 \u0B89\u0BB3\u0BCD\u0BB3\u0B9F\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`:i.format==="regex"?`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: ${i.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[i.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":""}: ${Ve(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 eIr(){return{localeError:Zve()}}var Zve,tIr=E({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/th.js"(){Et(),Zve=()=>{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 i=n[o.expected]??o.expected,s=Ft(o.input),a=n[s]??s;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 ${i} \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 ${Mt(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 ${Ve(o.values,"|")}`;case"too_big":{const i=o.inclusive?"\u0E44\u0E21\u0E48\u0E40\u0E01\u0E34\u0E19":"\u0E19\u0E49\u0E2D\u0E22\u0E01\u0E27\u0E48\u0E32",s=t(o.origin);return s?`\u0E40\u0E01\u0E34\u0E19\u0E01\u0E33\u0E2B\u0E19\u0E14: ${o.origin??"\u0E04\u0E48\u0E32"} \u0E04\u0E27\u0E23\u0E21\u0E35${i} ${o.maximum.toString()} ${s.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${i} ${o.maximum.toString()}`}case"too_small":{const i=o.inclusive?"\u0E2D\u0E22\u0E48\u0E32\u0E07\u0E19\u0E49\u0E2D\u0E22":"\u0E21\u0E32\u0E01\u0E01\u0E27\u0E48\u0E32",s=t(o.origin);return s?`\u0E19\u0E49\u0E2D\u0E22\u0E01\u0E27\u0E48\u0E32\u0E01\u0E33\u0E2B\u0E19\u0E14: ${o.origin} \u0E04\u0E27\u0E23\u0E21\u0E35${i} ${o.minimum.toString()} ${s.unit}`:`\u0E19\u0E49\u0E2D\u0E22\u0E01\u0E27\u0E48\u0E32\u0E01\u0E33\u0E2B\u0E19\u0E14: ${o.origin} \u0E04\u0E27\u0E23\u0E21\u0E35${i} ${o.minimum.toString()}`}case"invalid_format":{const i=o;return i.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 "${i.prefix}"`:i.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 "${i.suffix}"`:i.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 "${i.includes}" \u0E2D\u0E22\u0E39\u0E48\u0E43\u0E19\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21`:i.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 ${i.pattern}`:`\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: ${r[i.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: ${Ve(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 rIr(){return{localeError:Qve()}}var Qve,nIr=E({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/tr.js"(){Et(),Qve=()=>{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 i=n[o.expected]??o.expected,s=Ft(o.input),a=n[s]??s;return/^[A-Z]/.test(o.expected)?`Ge\xE7ersiz de\u011Fer: beklenen instanceof ${o.expected}, al\u0131nan ${a}`:`Ge\xE7ersiz de\u011Fer: beklenen ${i}, al\u0131nan ${a}`}case"invalid_value":return o.values.length===1?`Ge\xE7ersiz de\u011Fer: beklenen ${Mt(o.values[0])}`:`Ge\xE7ersiz se\xE7enek: a\u015Fa\u011F\u0131dakilerden biri olmal\u0131: ${Ve(o.values,"|")}`;case"too_big":{const i=o.inclusive?"<=":"<",s=t(o.origin);return s?`\xC7ok b\xFCy\xFCk: beklenen ${o.origin??"de\u011Fer"} ${i}${o.maximum.toString()} ${s.unit??"\xF6\u011Fe"}`:`\xC7ok b\xFCy\xFCk: beklenen ${o.origin??"de\u011Fer"} ${i}${o.maximum.toString()}`}case"too_small":{const i=o.inclusive?">=":">",s=t(o.origin);return s?`\xC7ok k\xFC\xE7\xFCk: beklenen ${o.origin} ${i}${o.minimum.toString()} ${s.unit}`:`\xC7ok k\xFC\xE7\xFCk: beklenen ${o.origin} ${i}${o.minimum.toString()}`}case"invalid_format":{const i=o;return i.format==="starts_with"?`Ge\xE7ersiz metin: "${i.prefix}" ile ba\u015Flamal\u0131`:i.format==="ends_with"?`Ge\xE7ersiz metin: "${i.suffix}" ile bitmeli`:i.format==="includes"?`Ge\xE7ersiz metin: "${i.includes}" i\xE7ermeli`:i.format==="regex"?`Ge\xE7ersiz metin: ${i.pattern} desenine uymal\u0131`:`Ge\xE7ersiz ${r[i.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":""}: ${Ve(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 ewe(){return{localeError:twe()}}var twe,rwe=E({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/uk.js"(){Et(),twe=()=>{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 i=n[o.expected]??o.expected,s=Ft(o.input),a=n[s]??s;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 ${i}, \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 ${Mt(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 ${Ve(o.values,"|")}`;case"too_big":{const i=o.inclusive?"<=":"<",s=t(o.origin);return s?`\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"} ${s.verb} ${i}${o.maximum.toString()} ${s.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 ${i}${o.maximum.toString()}`}case"too_small":{const i=o.inclusive?">=":">",s=t(o.origin);return s?`\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} ${s.verb} ${i}${o.minimum.toString()} ${s.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 ${i}${o.minimum.toString()}`}case"invalid_format":{const i=o;return i.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 "${i.prefix}"`:i.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 "${i.suffix}"`:i.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 "${i.includes}"`:i.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 ${i.pattern}`:`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 ${r[i.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":""}: ${Ve(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 oIr(){return ewe()}var iIr=E({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ua.js"(){rwe()}});function sIr(){return{localeError:nwe()}}var nwe,aIr=E({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ur.js"(){Et(),nwe=()=>{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 i=n[o.expected]??o.expected,s=Ft(o.input),a=n[s]??s;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: ${i} \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: ${Mt(o.values[0])} \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`:`\u063A\u0644\u0637 \u0622\u067E\u0634\u0646: ${Ve(o.values,"|")} \u0645\u06CC\u06BA \u0633\u06D2 \u0627\u06CC\u06A9 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`;case"too_big":{const i=o.inclusive?"<=":"<",s=t(o.origin);return s?`\u0628\u06C1\u062A \u0628\u0691\u0627: ${o.origin??"\u0648\u06CC\u0644\u06CC\u0648"} \u06A9\u06D2 ${i}${o.maximum.toString()} ${s.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 ${i}${o.maximum.toString()} \u06C1\u0648\u0646\u0627 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`}case"too_small":{const i=o.inclusive?">=":">",s=t(o.origin);return s?`\u0628\u06C1\u062A \u0686\u06BE\u0648\u0679\u0627: ${o.origin} \u06A9\u06D2 ${i}${o.minimum.toString()} ${s.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 ${i}${o.minimum.toString()} \u06C1\u0648\u0646\u0627 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`}case"invalid_format":{const i=o;return i.format==="starts_with"?`\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: "${i.prefix}" \u0633\u06D2 \u0634\u0631\u0648\u0639 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`:i.format==="ends_with"?`\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: "${i.suffix}" \u067E\u0631 \u062E\u062A\u0645 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`:i.format==="includes"?`\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: "${i.includes}" \u0634\u0627\u0645\u0644 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`:i.format==="regex"?`\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: \u067E\u06CC\u0679\u0631\u0646 ${i.pattern} \u0633\u06D2 \u0645\u06CC\u0686 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`:`\u063A\u0644\u0637 ${r[i.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":""}: ${Ve(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 lIr(){return{localeError:owe()}}var owe,cIr=E({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/uz.js"(){Et(),owe=()=>{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 i=n[o.expected]??o.expected,s=Ft(o.input),a=n[s]??s;return/^[A-Z]/.test(o.expected)?`Noto\u2018g\u2018ri kirish: kutilgan instanceof ${o.expected}, qabul qilingan ${a}`:`Noto\u2018g\u2018ri kirish: kutilgan ${i}, qabul qilingan ${a}`}case"invalid_value":return o.values.length===1?`Noto\u2018g\u2018ri kirish: kutilgan ${Mt(o.values[0])}`:`Noto\u2018g\u2018ri variant: quyidagilardan biri kutilgan ${Ve(o.values,"|")}`;case"too_big":{const i=o.inclusive?"<=":"<",s=t(o.origin);return s?`Juda katta: kutilgan ${o.origin??"qiymat"} ${i}${o.maximum.toString()} ${s.unit} ${s.verb}`:`Juda katta: kutilgan ${o.origin??"qiymat"} ${i}${o.maximum.toString()}`}case"too_small":{const i=o.inclusive?">=":">",s=t(o.origin);return s?`Juda kichik: kutilgan ${o.origin} ${i}${o.minimum.toString()} ${s.unit} ${s.verb}`:`Juda kichik: kutilgan ${o.origin} ${i}${o.minimum.toString()}`}case"invalid_format":{const i=o;return i.format==="starts_with"?`Noto\u2018g\u2018ri satr: "${i.prefix}" bilan boshlanishi kerak`:i.format==="ends_with"?`Noto\u2018g\u2018ri satr: "${i.suffix}" bilan tugashi kerak`:i.format==="includes"?`Noto\u2018g\u2018ri satr: "${i.includes}" ni o\u2018z ichiga olishi kerak`:i.format==="regex"?`Noto\u2018g\u2018ri satr: ${i.pattern} shabloniga mos kelishi kerak`:`Noto\u2018g\u2018ri ${r[i.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":""}: ${Ve(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 uIr(){return{localeError:iwe()}}var iwe,dIr=E({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/vi.js"(){Et(),iwe=()=>{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 i=n[o.expected]??o.expected,s=Ft(o.input),a=n[s]??s;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 ${i}, 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 ${Mt(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 ${Ve(o.values,"|")}`;case"too_big":{const i=o.inclusive?"<=":"<",s=t(o.origin);return s?`Qu\xE1 l\u1EDBn: mong \u0111\u1EE3i ${o.origin??"gi\xE1 tr\u1ECB"} ${s.verb} ${i}${o.maximum.toString()} ${s.unit??"ph\u1EA7n t\u1EED"}`:`Qu\xE1 l\u1EDBn: mong \u0111\u1EE3i ${o.origin??"gi\xE1 tr\u1ECB"} ${i}${o.maximum.toString()}`}case"too_small":{const i=o.inclusive?">=":">",s=t(o.origin);return s?`Qu\xE1 nh\u1ECF: mong \u0111\u1EE3i ${o.origin} ${s.verb} ${i}${o.minimum.toString()} ${s.unit}`:`Qu\xE1 nh\u1ECF: mong \u0111\u1EE3i ${o.origin} ${i}${o.minimum.toString()}`}case"invalid_format":{const i=o;return i.format==="starts_with"?`Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i b\u1EAFt \u0111\u1EA7u b\u1EB1ng "${i.prefix}"`:i.format==="ends_with"?`Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i k\u1EBFt th\xFAc b\u1EB1ng "${i.suffix}"`:i.format==="includes"?`Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i bao g\u1ED3m "${i.includes}"`:i.format==="regex"?`Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i kh\u1EDBp v\u1EDBi m\u1EABu ${i.pattern}`:`${r[i.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: ${Ve(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 pIr(){return{localeError:swe()}}var swe,mIr=E({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/zh-CN.js"(){Et(),swe=()=>{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 i=n[o.expected]??o.expected,s=Ft(o.input),a=n[s]??s;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 ${i}\uFF0C\u5B9E\u9645\u63A5\u6536 ${a}`}case"invalid_value":return o.values.length===1?`\u65E0\u6548\u8F93\u5165\uFF1A\u671F\u671B ${Mt(o.values[0])}`:`\u65E0\u6548\u9009\u9879\uFF1A\u671F\u671B\u4EE5\u4E0B\u4E4B\u4E00 ${Ve(o.values,"|")}`;case"too_big":{const i=o.inclusive?"<=":"<",s=t(o.origin);return s?`\u6570\u503C\u8FC7\u5927\uFF1A\u671F\u671B ${o.origin??"\u503C"} ${i}${o.maximum.toString()} ${s.unit??"\u4E2A\u5143\u7D20"}`:`\u6570\u503C\u8FC7\u5927\uFF1A\u671F\u671B ${o.origin??"\u503C"} ${i}${o.maximum.toString()}`}case"too_small":{const i=o.inclusive?">=":">",s=t(o.origin);return s?`\u6570\u503C\u8FC7\u5C0F\uFF1A\u671F\u671B ${o.origin} ${i}${o.minimum.toString()} ${s.unit}`:`\u6570\u503C\u8FC7\u5C0F\uFF1A\u671F\u671B ${o.origin} ${i}${o.minimum.toString()}`}case"invalid_format":{const i=o;return i.format==="starts_with"?`\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u4EE5 "${i.prefix}" \u5F00\u5934`:i.format==="ends_with"?`\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u4EE5 "${i.suffix}" \u7ED3\u5C3E`:i.format==="includes"?`\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u5305\u542B "${i.includes}"`:i.format==="regex"?`\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u6EE1\u8DB3\u6B63\u5219\u8868\u8FBE\u5F0F ${i.pattern}`:`\u65E0\u6548${r[i.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): ${Ve(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 hIr(){return{localeError:awe()}}var awe,fIr=E({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/zh-TW.js"(){Et(),awe=()=>{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 i=n[o.expected]??o.expected,s=Ft(o.input),a=n[s]??s;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 ${i}\uFF0C\u4F46\u6536\u5230 ${a}`}case"invalid_value":return o.values.length===1?`\u7121\u6548\u7684\u8F38\u5165\u503C\uFF1A\u9810\u671F\u70BA ${Mt(o.values[0])}`:`\u7121\u6548\u7684\u9078\u9805\uFF1A\u9810\u671F\u70BA\u4EE5\u4E0B\u5176\u4E2D\u4E4B\u4E00 ${Ve(o.values,"|")}`;case"too_big":{const i=o.inclusive?"<=":"<",s=t(o.origin);return s?`\u6578\u503C\u904E\u5927\uFF1A\u9810\u671F ${o.origin??"\u503C"} \u61C9\u70BA ${i}${o.maximum.toString()} ${s.unit??"\u500B\u5143\u7D20"}`:`\u6578\u503C\u904E\u5927\uFF1A\u9810\u671F ${o.origin??"\u503C"} \u61C9\u70BA ${i}${o.maximum.toString()}`}case"too_small":{const i=o.inclusive?">=":">",s=t(o.origin);return s?`\u6578\u503C\u904E\u5C0F\uFF1A\u9810\u671F ${o.origin} \u61C9\u70BA ${i}${o.minimum.toString()} ${s.unit}`:`\u6578\u503C\u904E\u5C0F\uFF1A\u9810\u671F ${o.origin} \u61C9\u70BA ${i}${o.minimum.toString()}`}case"invalid_format":{const i=o;return i.format==="starts_with"?`\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u4EE5 "${i.prefix}" \u958B\u982D`:i.format==="ends_with"?`\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u4EE5 "${i.suffix}" \u7D50\u5C3E`:i.format==="includes"?`\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u5305\u542B "${i.includes}"`:i.format==="regex"?`\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u7B26\u5408\u683C\u5F0F ${i.pattern}`:`\u7121\u6548\u7684 ${r[i.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${Ve(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 gIr(){return{localeError:lwe()}}var lwe,yIr=E({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/yo.js"(){Et(),lwe=()=>{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 i=n[o.expected]??o.expected,s=Ft(o.input),a=n[s]??s;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 ${i}, \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 ${Mt(o.values[0])}`:`\xC0\u1E63\xE0y\xE0n a\u1E63\xEC\u1E63e: yan \u1ECD\u0300kan l\xE1ra ${Ve(o.values,"|")}`;case"too_big":{const i=o.inclusive?"<=":"<",s=t(o.origin);return s?`T\xF3 p\u1ECD\u0300 j\xF9: a n\xED l\xE1ti j\u1EB9\u0301 p\xE9 ${o.origin??"iye"} ${s.verb} ${i}${o.maximum} ${s.unit}`:`T\xF3 p\u1ECD\u0300 j\xF9: a n\xED l\xE1ti j\u1EB9\u0301 ${i}${o.maximum}`}case"too_small":{const i=o.inclusive?">=":">",s=t(o.origin);return s?`K\xE9r\xE9 ju: a n\xED l\xE1ti j\u1EB9\u0301 p\xE9 ${o.origin} ${s.verb} ${i}${o.minimum} ${s.unit}`:`K\xE9r\xE9 ju: a n\xED l\xE1ti j\u1EB9\u0301 ${i}${o.minimum}`}case"invalid_format":{const i=o;return i.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 "${i.prefix}"`:i.format==="ends_with"?`\u1ECC\u0300r\u1ECD\u0300 a\u1E63\xEC\u1E63e: gb\u1ECD\u0301d\u1ECD\u0300 par\xED p\u1EB9\u0300l\xFA "${i.suffix}"`:i.format==="includes"?`\u1ECC\u0300r\u1ECD\u0300 a\u1E63\xEC\u1E63e: gb\u1ECD\u0301d\u1ECD\u0300 n\xED "${i.includes}"`:i.format==="regex"?`\u1ECC\u0300r\u1ECD\u0300 a\u1E63\xEC\u1E63e: gb\u1ECD\u0301d\u1ECD\u0300 b\xE1 \xE0p\u1EB9\u1EB9r\u1EB9 mu ${i.pattern}`:`A\u1E63\xEC\u1E63e: ${r[i.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: ${Ve(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"}}}}}),GB={};Z(GB,{ar:()=>DCr,az:()=>LCr,be:()=>$Cr,bg:()=>BCr,ca:()=>GCr,cs:()=>VCr,da:()=>HCr,de:()=>KCr,en:()=>fve,eo:()=>XCr,es:()=>ZCr,fa:()=>e1r,fi:()=>r1r,fr:()=>o1r,frCA:()=>s1r,he:()=>l1r,hu:()=>u1r,hy:()=>p1r,id:()=>h1r,is:()=>g1r,it:()=>v1r,ja:()=>T1r,ka:()=>_1r,kh:()=>S1r,km:()=>Ove,ko:()=>x1r,lt:()=>C1r,mk:()=>R1r,ms:()=>M1r,nl:()=>D1r,no:()=>L1r,ota:()=>$1r,pl:()=>G1r,ps:()=>B1r,pt:()=>V1r,ru:()=>H1r,sl:()=>K1r,sv:()=>X1r,ta:()=>Z1r,th:()=>eIr,tr:()=>rIr,ua:()=>oIr,uk:()=>ewe,ur:()=>sIr,uz:()=>lIr,vi:()=>uIr,yo:()=>gIr,zhCN:()=>pIr,zhTW:()=>hIr});var qB=E({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/index.js"(){NCr(),FCr(),UCr(),zCr(),qCr(),jCr(),WCr(),JCr(),yve(),YCr(),QCr(),t1r(),n1r(),i1r(),a1r(),c1r(),d1r(),m1r(),f1r(),y1r(),w1r(),b1r(),E1r(),k1r(),Nve(),A1r(),I1r(),P1r(),O1r(),N1r(),F1r(),U1r(),z1r(),q1r(),j1r(),W1r(),J1r(),Y1r(),Q1r(),tIr(),nIr(),iIr(),rwe(),aIr(),cIr(),dIr(),mIr(),fIr(),yIr()}});function VB(){return new WB}var cwe,jB,HB,WB,Za,sR=E({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/registries.js"(){jB=Symbol("ZodOutput"),HB=Symbol("ZodInput"),WB=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)}},(cwe=globalThis).__zod_globalRegistry??(cwe.__zod_globalRegistry=VB()),Za=globalThis.__zod_globalRegistry}});function uwe(e,t){return new e({type:"string",...Ke(t)})}function dwe(e,t){return new e({type:"string",coerce:!0,...Ke(t)})}function KB(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...Ke(t)})}function aR(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...Ke(t)})}function JB(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...Ke(t)})}function XB(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...Ke(t)})}function YB(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...Ke(t)})}function ZB(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...Ke(t)})}function lR(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...Ke(t)})}function QB(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...Ke(t)})}function ez(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...Ke(t)})}function tz(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...Ke(t)})}function rz(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...Ke(t)})}function nz(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...Ke(t)})}function oz(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...Ke(t)})}function iz(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...Ke(t)})}function sz(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...Ke(t)})}function az(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...Ke(t)})}function pwe(e,t){return new e({type:"string",format:"mac",check:"string_format",abort:!1,...Ke(t)})}function lz(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...Ke(t)})}function cz(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...Ke(t)})}function uz(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...Ke(t)})}function dz(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...Ke(t)})}function pz(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...Ke(t)})}function mz(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...Ke(t)})}function mwe(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...Ke(t)})}function hwe(e,t){return new e({type:"string",format:"date",check:"string_format",...Ke(t)})}function fwe(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...Ke(t)})}function gwe(e,t){return new e({type:"string",format:"duration",check:"string_format",...Ke(t)})}function ywe(e,t){return new e({type:"number",checks:[],...Ke(t)})}function vwe(e,t){return new e({type:"number",coerce:!0,checks:[],...Ke(t)})}function wwe(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...Ke(t)})}function Twe(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"float32",...Ke(t)})}function bwe(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"float64",...Ke(t)})}function _we(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"int32",...Ke(t)})}function Ewe(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"uint32",...Ke(t)})}function Swe(e,t){return new e({type:"boolean",...Ke(t)})}function kwe(e,t){return new e({type:"boolean",coerce:!0,...Ke(t)})}function xwe(e,t){return new e({type:"bigint",...Ke(t)})}function Awe(e,t){return new e({type:"bigint",coerce:!0,...Ke(t)})}function Cwe(e,t){return new e({type:"bigint",check:"bigint_format",abort:!1,format:"int64",...Ke(t)})}function Iwe(e,t){return new e({type:"bigint",check:"bigint_format",abort:!1,format:"uint64",...Ke(t)})}function Rwe(e,t){return new e({type:"symbol",...Ke(t)})}function Pwe(e,t){return new e({type:"undefined",...Ke(t)})}function Mwe(e,t){return new e({type:"null",...Ke(t)})}function Owe(e){return new e({type:"any"})}function Dwe(e){return new e({type:"unknown"})}function Nwe(e,t){return new e({type:"never",...Ke(t)})}function Lwe(e,t){return new e({type:"void",...Ke(t)})}function Fwe(e,t){return new e({type:"date",...Ke(t)})}function $we(e,t){return new e({type:"date",coerce:!0,...Ke(t)})}function Uwe(e,t){return new e({type:"nan",...Ke(t)})}function Zp(e,t){return new WI({check:"less_than",...Ke(t),value:e,inclusive:!1})}function Nl(e,t){return new WI({check:"less_than",...Ke(t),value:e,inclusive:!0})}function Qp(e,t){return new KI({check:"greater_than",...Ke(t),value:e,inclusive:!1})}function ya(e,t){return new KI({check:"greater_than",...Ke(t),value:e,inclusive:!0})}function hz(e){return Qp(0,e)}function fz(e){return Zp(0,e)}function gz(e){return Nl(0,e)}function yz(e){return ya(0,e)}function py(e,t){return new uU({check:"multiple_of",...Ke(t),value:e})}function my(e,t){return new mU({check:"max_size",...Ke(t),maximum:e})}function em(e,t){return new hU({check:"min_size",...Ke(t),minimum:e})}function v_(e,t){return new fU({check:"size_equals",...Ke(t),size:e})}function w_(e,t){return new gU({check:"max_length",...Ke(t),maximum:e})}function Vh(e,t){return new yU({check:"min_length",...Ke(t),minimum:e})}function T_(e,t){return new vU({check:"length_equals",...Ke(t),length:e})}function cR(e,t){return new wU({check:"string_format",format:"regex",...Ke(t),pattern:e})}function uR(e){return new TU({check:"string_format",format:"lowercase",...Ke(e)})}function dR(e){return new bU({check:"string_format",format:"uppercase",...Ke(e)})}function pR(e,t){return new _U({check:"string_format",format:"includes",...Ke(t),includes:e})}function mR(e,t){return new EU({check:"string_format",format:"starts_with",...Ke(t),prefix:e})}function hR(e,t){return new SU({check:"string_format",format:"ends_with",...Ke(t),suffix:e})}function vz(e,t,r){return new kU({check:"property",property:e,schema:t,...Ke(r)})}function fR(e,t){return new xU({check:"mime_type",mime:e,...Ke(t)})}function Ed(e){return new AU({check:"overwrite",tx:e})}function gR(e){return Ed(t=>t.normalize(e))}function yR(){return Ed(e=>e.trim())}function vR(){return Ed(e=>e.toLowerCase())}function wR(){return Ed(e=>e.toUpperCase())}function TR(){return Ed(e=>V0e(e))}function Bwe(e,t,r){return new e({type:"array",element:t,...Ke(r)})}function vIr(e,t,r){return new e({type:"union",options:t,...Ke(r)})}function wIr(e,t,r){return new e({type:"union",options:t,inclusive:!1,...Ke(r)})}function TIr(e,t,r,n){return new e({type:"union",options:r,discriminator:t,...Ke(n)})}function bIr(e,t,r){return new e({type:"intersection",left:t,right:r})}function _Ir(e,t,r,n){const o=r instanceof zt,i=o?n:r,s=o?r:null;return new e({type:"tuple",items:t,rest:s,...Ke(i)})}function EIr(e,t,r,n){return new e({type:"record",keyType:t,valueType:r,...Ke(n)})}function SIr(e,t,r,n){return new e({type:"map",keyType:t,valueType:r,...Ke(n)})}function kIr(e,t,r){return new e({type:"set",valueType:t,...Ke(r)})}function xIr(e,t,r){const n=Array.isArray(t)?Object.fromEntries(t.map(o=>[o,o])):t;return new e({type:"enum",entries:n,...Ke(r)})}function AIr(e,t,r){return new e({type:"enum",entries:t,...Ke(r)})}function CIr(e,t,r){return new e({type:"literal",values:Array.isArray(t)?t:[t],...Ke(r)})}function zwe(e,t){return new e({type:"file",...Ke(t)})}function IIr(e,t){return new e({type:"transform",transform:t})}function RIr(e,t){return new e({type:"optional",innerType:t})}function PIr(e,t){return new e({type:"nullable",innerType:t})}function MIr(e,t,r){return new e({type:"default",innerType:t,get defaultValue(){return typeof r=="function"?r():j0e(r)}})}function OIr(e,t,r){return new e({type:"nonoptional",innerType:t,...Ke(r)})}function DIr(e,t){return new e({type:"success",innerType:t})}function NIr(e,t,r){return new e({type:"catch",innerType:t,catchValue:typeof r=="function"?r:()=>r})}function LIr(e,t,r){return new e({type:"pipe",in:t,out:r})}function FIr(e,t){return new e({type:"readonly",innerType:t})}function $Ir(e,t,r){return new e({type:"template_literal",parts:t,...Ke(r)})}function UIr(e,t){return new e({type:"lazy",getter:t})}function BIr(e,t){return new e({type:"promise",innerType:t})}function Gwe(e,t,r){const n=Ke(r);return n.abort??(n.abort=!0),new e({type:"custom",check:"custom",fn:t,...n})}function qwe(e,t,r){return new e({type:"custom",check:"custom",fn:t,...Ke(r)})}function Vwe(e){const t=jwe(r=>(r.addIssue=n=>{if(typeof n=="string")r.issues.push(PI(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(PI(o))}},e(r.value,r)));return t}function jwe(e,t){const r=new to({check:"custom",...Ke(t)});return r._zod.check=e,r}function Hwe(e){const t=new to({check:"describe"});return t._zod.onattach=[r=>{const n=Za.get(r)??{};Za.add(r,{...n,description:e})}],t._zod.check=()=>{},t}function Wwe(e){const t=new to({check:"meta"});return t._zod.onattach=[r=>{const n=Za.get(r)??{};Za.add(r,{...n,...e})}],t._zod.check=()=>{},t}function Kwe(e,t){const r=Ke(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(m=>typeof m=="string"?m.toLowerCase():m),o=o.map(m=>typeof m=="string"?m.toLowerCase():m));const i=new Set(n),s=new Set(o),a=e.Codec??iR,l=e.Boolean??tR,c=e.String??cy,u=new c({type:"string",error:r.error}),d=new l({type:"boolean",error:r.error}),p=new a({type:"pipe",in:u,out:d,transform:((m,f)=>{let g=m;return r.case!=="sensitive"&&(g=g.toLowerCase()),i.has(g)?!0:s.has(g)?!1:(f.issues.push({code:"invalid_value",expected:"stringbool",values:[...i,...s],input:f.value,inst:p,continue:!1}),{})}),reverseTransform:((m,f)=>m===!0?n[0]||"true":o[0]||"false"),error:r.error});return p}function b_(e,t,r,n={}){const o=Ke(n),i={...Ke(n),check:"string_format",type:"string",format:t,fn:typeof r=="function"?r:a=>r.test(a),...o};return r instanceof RegExp&&(i.pattern=r),new e(i)}var wz,zIr=E({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/api.js"(){CU(),sR(),ive(),Et(),wz={Any:null,Minute:-1,Second:0,Millisecond:3,Microsecond:6}}});function hy(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??Za,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 sn(e,t,r={path:[],schemaPath:[]}){var n;const o=e._zod.def,i=t.seen.get(e);if(i)return i.count++,r.schemaPath.includes(e)&&(i.cycle=r.path),i.schema;const s={schema:{},count:1,cycle:void 0,path:r.path};t.seen.set(e,s);const a=e._zod.toJSONSchema?.();if(a)s.schema=a;else{const u={...r,schemaPath:[...r.schemaPath,e],path:r.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,s.schema,u);else{const p=s.schema,m=t.processors[o.type];if(!m)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${o.type}`);m(e,t,p,u)}const d=e._zod.parent;d&&(s.ref||(s.ref=d),sn(d,t,u),t.seen.get(d).isParent=!0)}const l=t.metadataRegistry.get(e);return l&&Object.assign(s.schema,l),t.io==="input"&&Xs(e)&&(delete s.schema.examples,delete s.schema.default),t.io==="input"&&s.schema._prefault&&((n=s.schema).default??(n.default=s.schema._prefault)),delete s.schema._prefault,t.seen.get(e).schema}function fy(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 s of e.seen.entries()){const a=e.metadataRegistry.get(s[0])?.id;if(a){const l=n.get(a);if(l&&l!==s[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,s[0])}}const o=s=>{const a=e.target==="draft-2020-12"?"$defs":"definitions";if(e.external){const d=e.external.registry.get(s[0])?.id,p=e.external.uri??(f=>f);if(d)return{ref:p(d)};const m=s[1].defId??s[1].schema.id??`schema${e.counter++}`;return s[1].defId=m,{defId:m,ref:`${p("__shared")}#/${a}/${m}`}}if(s[1]===r)return{ref:"#"};const c=`#/${a}/`,u=s[1].schema.id??`__schema${e.counter++}`;return{defId:u,ref:c+u}},i=s=>{if(s[1].schema.$ref)return;const a=s[1],{ref:l,defId:c}=o(s);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 s of e.seen.entries()){const a=s[1];if(a.cycle)throw new Error(`Cycle detected: #/${a.cycle?.join("/")}/<root>
|
|
61
61
|
|
|
62
|
-
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const s of e.seen.entries()){const a=s[1];if(t===s[0]){i(s);continue}if(e.external){const c=e.external.registry.get(s[0])?.id;if(t!==s[0]&&c){i(s);continue}}if(e.metadataRegistry.get(s[0])?.id){i(s);continue}if(a.cycle){i(s);continue}if(a.count>1&&e.reused==="ref"){i(s);continue}}}function gy(e,t){const r=e.seen.get(t);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");const n=s=>{const a=e.seen.get(s);if(a.ref===null)return;const l=a.def??a.schema,c={...l},u=a.ref;if(a.ref=null,u){n(u);const p=e.seen.get(u),m=p.schema;if(m.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0")?(l.allOf=l.allOf??[],l.allOf.push(m)):Object.assign(l,m),Object.assign(l,c),s._zod.parent===u)for(const g in l)g==="$ref"||g==="allOf"||g in c||delete l[g];if(m.$ref&&p.def)for(const g in l)g==="$ref"||g==="allOf"||g in p.def&&JSON.stringify(l[g])===JSON.stringify(p.def[g])&&delete l[g]}const d=s._zod.parent;if(d&&d!==u){n(d);const p=e.seen.get(d);if(p?.schema.$ref&&(l.$ref=p.schema.$ref,p.def))for(const m in l)m==="$ref"||m==="allOf"||m in p.def&&JSON.stringify(l[m])===JSON.stringify(p.def[m])&&delete l[m]}e.override({zodSchema:s,jsonSchema:l,path:a.path??[]})};for(const s of[...e.seen.entries()].reverse())n(s[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 s=e.external.registry.get(t)?.id;if(!s)throw new Error("Schema is missing an `id` property");o.$id=e.external.uri(s)}Object.assign(o,r.def??r.schema);const i=e.external?.defs??{};for(const s of e.seen.entries()){const a=s[1];a.def&&a.defId&&(i[a.defId]=a.def)}e.external||Object.keys(i).length>0&&(e.target==="draft-2020-12"?o.$defs=i:o.definitions=i);try{const s=JSON.parse(JSON.stringify(o));return Object.defineProperty(s,"~standard",{value:{...t["~standard"],jsonSchema:{input:yy(t,"input",e.processors),output:yy(t,"output",e.processors)}},enumerable:!1,writable:!1}),s}catch{throw new Error("Error converting schema to JSON.")}}function Xs(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 Xs(n.element,r);if(n.type==="set")return Xs(n.valueType,r);if(n.type==="lazy")return Xs(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 Xs(n.innerType,r);if(n.type==="intersection")return Xs(n.left,r)||Xs(n.right,r);if(n.type==="record"||n.type==="map")return Xs(n.keyType,r)||Xs(n.valueType,r);if(n.type==="pipe")return Xs(n.in,r)||Xs(n.out,r);if(n.type==="object"){for(const o in n.shape)if(Xs(n.shape[o],r))return!0;return!1}if(n.type==="union"){for(const o of n.options)if(Xs(o,r))return!0;return!1}if(n.type==="tuple"){for(const o of n.items)if(Xs(o,r))return!0;return!!(n.rest&&Xs(n.rest,r))}return!1}var Tz,yy,bR=E({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/to-json-schema.js"(){sR(),Tz=(e,t={})=>r=>{const n=hy({...r,processors:t});return sn(e,n),fy(n,e),gy(n,e)},yy=(e,t,r={})=>n=>{const{libraryOptions:o,target:i}=n??{},s=hy({...o??{},target:i,io:t,processors:r});return sn(e,s),fy(s,e),gy(s,e)}}});function _R(e,t){if("_idmap"in e){const n=e,o=hy({...t,processors:kR}),i={};for(const l of n._idmap.entries()){const[c,u]=l;sn(u,o)}const s={},a={registry:n,uri:t?.uri,defs:i};o.external=a;for(const l of n._idmap.entries()){const[c,u]=l;fy(o,u),s[c]=gy(o,u)}if(Object.keys(i).length>0){const l=o.target==="draft-2020-12"?"$defs":"definitions";s.__shared={[l]:i}}return{schemas:s}}const r=hy({...t,processors:kR});return sn(e,r),fy(r,e),gy(r,e)}var Jwe,bz,_z,Ez,Sz,kz,xz,Az,Cz,Iz,Rz,Pz,Mz,Oz,Dz,Nz,Lz,Fz,$z,Uz,Bz,zz,Gz,qz,Vz,jz,ER,Hz,Wz,Kz,Jz,Xz,Yz,Zz,Qz,eG,tG,rG,SR,nG,kR,__=E({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/json-schema-processors.js"(){bR(),Et(),Jwe={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},bz=(e,t,r,n)=>{const o=r;o.type="string";const{minimum:i,maximum:s,format:a,patterns:l,contentEncoding:c}=e._zod.bag;if(typeof i=="number"&&(o.minLength=i),typeof s=="number"&&(o.maxLength=s),a&&(o.format=Jwe[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}))])}},_z=(e,t,r,n)=>{const o=r,{minimum:i,maximum:s,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 i=="number"&&(o.minimum=i,typeof u=="number"&&t.target!=="draft-04"&&(u>=i?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 s=="number"&&(o.maximum=s,typeof c=="number"&&t.target!=="draft-04"&&(c<=s?delete o.maximum:delete o.exclusiveMaximum)),typeof l=="number"&&(o.multipleOf=l)},Ez=(e,t,r,n)=>{r.type="boolean"},Sz=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema")},kz=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw new Error("Symbols cannot be represented in JSON Schema")},xz=(e,t,r,n)=>{t.target==="openapi-3.0"?(r.type="string",r.nullable=!0,r.enum=[null]):r.type="null"},Az=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw new Error("Undefined cannot be represented in JSON Schema")},Cz=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw new Error("Void cannot be represented in JSON Schema")},Iz=(e,t,r,n)=>{r.not={}},Rz=(e,t,r,n)=>{},Pz=(e,t,r,n)=>{},Mz=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema")},Oz=(e,t,r,n)=>{const o=e._zod.def,i=S5(o.entries);i.every(s=>typeof s=="number")&&(r.type="number"),i.every(s=>typeof s=="string")&&(r.type="string"),r.enum=i},Dz=(e,t,r,n)=>{const o=e._zod.def,i=[];for(const s of o.values)if(s===void 0){if(t.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof s=="bigint"){if(t.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");i.push(Number(s))}else i.push(s);if(i.length!==0)if(i.length===1){const s=i[0];r.type=s===null?"null":typeof s,t.target==="draft-04"||t.target==="openapi-3.0"?r.enum=[s]:r.const=s}else i.every(s=>typeof s=="number")&&(r.type="number"),i.every(s=>typeof s=="string")&&(r.type="string"),i.every(s=>typeof s=="boolean")&&(r.type="boolean"),i.every(s=>s===null)&&(r.type="null"),r.enum=i},Nz=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema")},Lz=(e,t,r,n)=>{const o=r,i=e._zod.pattern;if(!i)throw new Error("Pattern not found in template literal");o.type="string",o.pattern=i.source},Fz=(e,t,r,n)=>{const o=r,i={type:"string",format:"binary",contentEncoding:"binary"},{minimum:s,maximum:a,mime:l}=e._zod.bag;s!==void 0&&(i.minLength=s),a!==void 0&&(i.maxLength=a),l?l.length===1?(i.contentMediaType=l[0],Object.assign(o,i)):(Object.assign(o,i),o.anyOf=l.map(c=>({contentMediaType:c}))):Object.assign(o,i)},$z=(e,t,r,n)=>{r.type="boolean"},Uz=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")},Bz=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw new Error("Function types cannot be represented in JSON Schema")},zz=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")},Gz=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw new Error("Map cannot be represented in JSON Schema")},qz=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw new Error("Set cannot be represented in JSON Schema")},Vz=(e,t,r,n)=>{const o=r,i=e._zod.def,{minimum:s,maximum:a}=e._zod.bag;typeof s=="number"&&(o.minItems=s),typeof a=="number"&&(o.maxItems=a),o.type="array",o.items=sn(i.element,t,{...n,path:[...n.path,"items"]})},jz=(e,t,r,n)=>{const o=r,i=e._zod.def;o.type="object",o.properties={};const s=i.shape;for(const c in s)o.properties[c]=sn(s[c],t,{...n,path:[...n.path,"properties",c]});const a=new Set(Object.keys(s)),l=new Set([...a].filter(c=>{const u=i.shape[c]._zod;return t.io==="input"?u.optin===void 0:u.optout===void 0}));l.size>0&&(o.required=Array.from(l)),i.catchall?._zod.def.type==="never"?o.additionalProperties=!1:i.catchall?i.catchall&&(o.additionalProperties=sn(i.catchall,t,{...n,path:[...n.path,"additionalProperties"]})):t.io==="output"&&(o.additionalProperties=!1)},ER=(e,t,r,n)=>{const o=e._zod.def,i=o.inclusive===!1,s=o.options.map((a,l)=>sn(a,t,{...n,path:[...n.path,i?"oneOf":"anyOf",l]}));i?r.oneOf=s:r.anyOf=s},Hz=(e,t,r,n)=>{const o=e._zod.def,i=sn(o.left,t,{...n,path:[...n.path,"allOf",0]}),s=sn(o.right,t,{...n,path:[...n.path,"allOf",1]}),a=c=>"allOf"in c&&Object.keys(c).length===1,l=[...a(i)?i.allOf:[i],...a(s)?s.allOf:[s]];r.allOf=l},Wz=(e,t,r,n)=>{const o=r,i=e._zod.def;o.type="array";const s=t.target==="draft-2020-12"?"prefixItems":"items",a=t.target==="draft-2020-12"||t.target==="openapi-3.0"?"items":"additionalItems",l=i.items.map((p,m)=>sn(p,t,{...n,path:[...n.path,s,m]})),c=i.rest?sn(i.rest,t,{...n,path:[...n.path,a,...t.target==="openapi-3.0"?[i.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)},Kz=(e,t,r,n)=>{const o=r,i=e._zod.def;o.type="object";const s=i.keyType,l=s._zod.bag?.patterns;if(i.mode==="loose"&&l&&l.size>0){const u=sn(i.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=sn(i.keyType,t,{...n,path:[...n.path,"propertyNames"]})),o.additionalProperties=sn(i.valueType,t,{...n,path:[...n.path,"additionalProperties"]});const c=s._zod.values;if(c){const u=[...c].filter(d=>typeof d=="string"||typeof d=="number");u.length>0&&(o.required=u)}},Jz=(e,t,r,n)=>{const o=e._zod.def,i=sn(o.innerType,t,n),s=t.seen.get(e);t.target==="openapi-3.0"?(s.ref=o.innerType,r.nullable=!0):r.anyOf=[i,{type:"null"}]},Xz=(e,t,r,n)=>{const o=e._zod.def;sn(o.innerType,t,n);const i=t.seen.get(e);i.ref=o.innerType},Yz=(e,t,r,n)=>{const o=e._zod.def;sn(o.innerType,t,n);const i=t.seen.get(e);i.ref=o.innerType,r.default=JSON.parse(JSON.stringify(o.defaultValue))},Zz=(e,t,r,n)=>{const o=e._zod.def;sn(o.innerType,t,n);const i=t.seen.get(e);i.ref=o.innerType,t.io==="input"&&(r._prefault=JSON.parse(JSON.stringify(o.defaultValue)))},Qz=(e,t,r,n)=>{const o=e._zod.def;sn(o.innerType,t,n);const i=t.seen.get(e);i.ref=o.innerType;let s;try{s=o.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}r.default=s},eG=(e,t,r,n)=>{const o=e._zod.def,i=t.io==="input"?o.in._zod.def.type==="transform"?o.out:o.in:o.out;sn(i,t,n);const s=t.seen.get(e);s.ref=i},tG=(e,t,r,n)=>{const o=e._zod.def;sn(o.innerType,t,n);const i=t.seen.get(e);i.ref=o.innerType,r.readOnly=!0},rG=(e,t,r,n)=>{const o=e._zod.def;sn(o.innerType,t,n);const i=t.seen.get(e);i.ref=o.innerType},SR=(e,t,r,n)=>{const o=e._zod.def;sn(o.innerType,t,n);const i=t.seen.get(e);i.ref=o.innerType},nG=(e,t,r,n)=>{const o=e._zod.innerType;sn(o,t,n);const i=t.seen.get(e);i.ref=o},kR={string:bz,number:_z,boolean:Ez,bigint:Sz,symbol:kz,null:xz,undefined:Az,void:Cz,never:Iz,any:Rz,unknown:Pz,date:Mz,enum:Oz,literal:Dz,nan:Nz,template_literal:Lz,file:Fz,success:$z,custom:Uz,function:Bz,transform:zz,map:Gz,set:qz,array:Vz,object:jz,union:ER,intersection:Hz,tuple:Wz,record:Kz,nullable:Jz,nonoptional:Xz,default:Yz,prefault:Zz,catch:Qz,pipe:eG,readonly:tG,promise:rG,optional:SR,lazy:nG}}}),Xwe,GIr=E({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/json-schema-generator.js"(){__(),bR(),Xwe=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=hy({processors:kR,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 sn(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)),fy(this.ctx,e);const r=gy(this.ctx,e),{"~standard":n,...o}=r;return o}}}}),qIr={},VIr=E({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/json-schema.js"(){}}),Ywe={};Z(Ywe,{$ZodAny:()=>cB,$ZodArray:()=>hB,$ZodAsyncError:()=>Xp,$ZodBase64:()=>QU,$ZodBase64URL:()=>eB,$ZodBigInt:()=>rR,$ZodBigIntFormat:()=>iB,$ZodBoolean:()=>tR,$ZodCIDRv4:()=>YU,$ZodCIDRv6:()=>ZU,$ZodCUID:()=>UU,$ZodCUID2:()=>BU,$ZodCatch:()=>OB,$ZodCheck:()=>to,$ZodCheckBigIntFormat:()=>pU,$ZodCheckEndsWith:()=>SU,$ZodCheckGreaterThan:()=>KI,$ZodCheckIncludes:()=>_U,$ZodCheckLengthEquals:()=>vU,$ZodCheckLessThan:()=>WI,$ZodCheckLowerCase:()=>TU,$ZodCheckMaxLength:()=>gU,$ZodCheckMaxSize:()=>mU,$ZodCheckMimeType:()=>xU,$ZodCheckMinLength:()=>yU,$ZodCheckMinSize:()=>hU,$ZodCheckMultipleOf:()=>uU,$ZodCheckNumberFormat:()=>dU,$ZodCheckOverwrite:()=>AU,$ZodCheckProperty:()=>kU,$ZodCheckRegex:()=>wU,$ZodCheckSizeEquals:()=>fU,$ZodCheckStartsWith:()=>EU,$ZodCheckStringFormat:()=>ly,$ZodCheckUpperCase:()=>bU,$ZodCodec:()=>iR,$ZodCustom:()=>zB,$ZodCustomStringFormat:()=>nB,$ZodDate:()=>mB,$ZodDefault:()=>IB,$ZodDiscriminatedUnion:()=>vB,$ZodE164:()=>tB,$ZodEmail:()=>NU,$ZodEmoji:()=>FU,$ZodEncodeError:()=>c_,$ZodEnum:()=>EB,$ZodError:()=>OI,$ZodExactOptional:()=>AB,$ZodFile:()=>kB,$ZodFunction:()=>$B,$ZodGUID:()=>OU,$ZodIPv4:()=>KU,$ZodIPv6:()=>JU,$ZodISODate:()=>jU,$ZodISODateTime:()=>VU,$ZodISODuration:()=>WU,$ZodISOTime:()=>HU,$ZodIntersection:()=>wB,$ZodJWT:()=>rB,$ZodKSUID:()=>qU,$ZodLazy:()=>BB,$ZodLiteral:()=>SB,$ZodMAC:()=>XU,$ZodMap:()=>bB,$ZodNaN:()=>DB,$ZodNanoID:()=>$U,$ZodNever:()=>dB,$ZodNonOptional:()=>PB,$ZodNull:()=>lB,$ZodNullable:()=>CB,$ZodNumber:()=>eR,$ZodNumberFormat:()=>oB,$ZodObject:()=>fB,$ZodObjectJIT:()=>gB,$ZodOptional:()=>oR,$ZodPipe:()=>NB,$ZodPrefault:()=>RB,$ZodPromise:()=>UB,$ZodReadonly:()=>LB,$ZodRealError:()=>ga,$ZodRecord:()=>TB,$ZodRegistry:()=>WB,$ZodSet:()=>_B,$ZodString:()=>cy,$ZodStringFormat:()=>on,$ZodSuccess:()=>MB,$ZodSymbol:()=>sB,$ZodTemplateLiteral:()=>FB,$ZodTransform:()=>xB,$ZodTuple:()=>nR,$ZodType:()=>zt,$ZodULID:()=>zU,$ZodURL:()=>LU,$ZodUUID:()=>DU,$ZodUndefined:()=>aB,$ZodUnion:()=>y_,$ZodUnknown:()=>uB,$ZodVoid:()=>pB,$ZodXID:()=>GU,$ZodXor:()=>yB,$brand:()=>E5,$constructor:()=>fe,$input:()=>HB,$output:()=>jB,Doc:()=>IU,JSONSchema:()=>qIr,JSONSchemaGenerator:()=>Xwe,NEVER:()=>xI,TimePrecision:()=>wz,_any:()=>Owe,_array:()=>Bwe,_base64:()=>uz,_base64url:()=>dz,_bigint:()=>xwe,_boolean:()=>Swe,_catch:()=>NIr,_check:()=>jwe,_cidrv4:()=>lz,_cidrv6:()=>cz,_coercedBigint:()=>Awe,_coercedBoolean:()=>kwe,_coercedDate:()=>$we,_coercedNumber:()=>vwe,_coercedString:()=>dwe,_cuid:()=>tz,_cuid2:()=>rz,_custom:()=>Gwe,_date:()=>Fwe,_decode:()=>$I,_decodeAsync:()=>BI,_default:()=>MIr,_discriminatedUnion:()=>TIr,_e164:()=>pz,_email:()=>KB,_emoji:()=>QB,_encode:()=>FI,_encodeAsync:()=>UI,_endsWith:()=>hR,_enum:()=>xIr,_file:()=>zwe,_float32:()=>Twe,_float64:()=>bwe,_gt:()=>Qp,_gte:()=>ya,_guid:()=>aR,_includes:()=>pR,_int:()=>wwe,_int32:()=>_we,_int64:()=>Cwe,_intersection:()=>bIr,_ipv4:()=>sz,_ipv6:()=>az,_isoDate:()=>hwe,_isoDateTime:()=>mwe,_isoDuration:()=>gwe,_isoTime:()=>fwe,_jwt:()=>mz,_ksuid:()=>iz,_lazy:()=>UIr,_length:()=>T_,_literal:()=>CIr,_lowercase:()=>uR,_lt:()=>Zp,_lte:()=>Nl,_mac:()=>pwe,_map:()=>SIr,_max:()=>Nl,_maxLength:()=>w_,_maxSize:()=>my,_mime:()=>fR,_min:()=>ya,_minLength:()=>Vh,_minSize:()=>em,_multipleOf:()=>py,_nan:()=>Uwe,_nanoid:()=>ez,_nativeEnum:()=>AIr,_negative:()=>fz,_never:()=>Nwe,_nonnegative:()=>yz,_nonoptional:()=>OIr,_nonpositive:()=>gz,_normalize:()=>gR,_null:()=>Mwe,_nullable:()=>PIr,_number:()=>ywe,_optional:()=>RIr,_overwrite:()=>Ed,_parse:()=>oy,_parseAsync:()=>iy,_pipe:()=>LIr,_positive:()=>hz,_promise:()=>BIr,_property:()=>vz,_readonly:()=>FIr,_record:()=>EIr,_refine:()=>qwe,_regex:()=>cR,_safeDecode:()=>GI,_safeDecodeAsync:()=>VI,_safeEncode:()=>zI,_safeEncodeAsync:()=>qI,_safeParse:()=>sy,_safeParseAsync:()=>ay,_set:()=>kIr,_size:()=>v_,_slugify:()=>TR,_startsWith:()=>mR,_string:()=>uwe,_stringFormat:()=>b_,_stringbool:()=>Kwe,_success:()=>DIr,_superRefine:()=>Vwe,_symbol:()=>Rwe,_templateLiteral:()=>$Ir,_toLowerCase:()=>vR,_toUpperCase:()=>wR,_transform:()=>IIr,_trim:()=>yR,_tuple:()=>_Ir,_uint32:()=>Ewe,_uint64:()=>Iwe,_ulid:()=>nz,_undefined:()=>Pwe,_union:()=>vIr,_unknown:()=>Dwe,_uppercase:()=>dR,_url:()=>lR,_uuid:()=>JB,_uuidv4:()=>XB,_uuidv6:()=>YB,_uuidv7:()=>ZB,_void:()=>Lwe,_xid:()=>oz,_xor:()=>wIr,clone:()=>Ol,config:()=>Is,createStandardJSONSchemaMethod:()=>yy,createToJSONSchemaMethod:()=>Tz,decode:()=>rye,decodeAsync:()=>oye,describe:()=>Hwe,encode:()=>tye,encodeAsync:()=>nye,extractDefs:()=>fy,finalize:()=>gy,flattenError:()=>P5,formatError:()=>M5,globalConfig:()=>u_,globalRegistry:()=>Za,initializeContext:()=>hy,isValidBase64:()=>PU,isValidBase64URL:()=>Vye,isValidJWT:()=>jye,locales:()=>GB,meta:()=>Wwe,parse:()=>DI,parseAsync:()=>NI,prettifyError:()=>Q0e,process:()=>sn,regexes:()=>Gh,registry:()=>VB,safeDecode:()=>sye,safeDecodeAsync:()=>lye,safeEncode:()=>iye,safeEncodeAsync:()=>aye,safeParse:()=>LI,safeParseAsync:()=>D5,toDotPath:()=>Z0e,toJSONSchema:()=>_R,treeifyError:()=>Y0e,util:()=>vr,version:()=>RU});var gi=E({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/index.js"(){d_(),cye(),eye(),ive(),CU(),qye(),Et(),lU(),qB(),sR(),Gye(),zIr(),bR(),__(),GIr(),VIr()}}),Zwe={};Z(Zwe,{endsWith:()=>hR,gt:()=>Qp,gte:()=>ya,includes:()=>pR,length:()=>T_,lowercase:()=>uR,lt:()=>Zp,lte:()=>Nl,maxLength:()=>w_,maxSize:()=>my,mime:()=>fR,minLength:()=>Vh,minSize:()=>em,multipleOf:()=>py,negative:()=>fz,nonnegative:()=>yz,nonpositive:()=>gz,normalize:()=>gR,overwrite:()=>Ed,positive:()=>hz,property:()=>vz,regex:()=>cR,size:()=>v_,slugify:()=>TR,startsWith:()=>mR,toLowerCase:()=>vR,toUpperCase:()=>wR,trim:()=>yR,uppercase:()=>dR});var oG=E({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/checks.js"(){gi()}}),xR={};Z(xR,{ZodISODate:()=>CR,ZodISODateTime:()=>AR,ZodISODuration:()=>RR,ZodISOTime:()=>IR,date:()=>eTe,datetime:()=>Qwe,duration:()=>rTe,time:()=>tTe});function Qwe(e){return mwe(AR,e)}function eTe(e){return hwe(CR,e)}function tTe(e){return fwe(IR,e)}function rTe(e){return gwe(RR,e)}var AR,CR,IR,RR,PR=E({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/iso.js"(){gi(),h4(),AR=fe("ZodISODateTime",(e,t)=>{VU.init(e,t),cn.init(e,t)}),CR=fe("ZodISODate",(e,t)=>{jU.init(e,t),cn.init(e,t)}),IR=fe("ZodISOTime",(e,t)=>{HU.init(e,t),cn.init(e,t)}),RR=fe("ZodISODuration",(e,t)=>{WU.init(e,t),cn.init(e,t)})}}),iG,nTe,va,oTe=E({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/errors.js"(){gi(),gi(),Et(),iG=(e,t)=>{OI.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:r=>M5(e,r)},flatten:{value:r=>P5(e,r)},addIssue:{value:r=>{e.issues.push(r),e.message=JSON.stringify(e.issues,AI,2)}},addIssues:{value:r=>{e.issues.push(...r),e.message=JSON.stringify(e.issues,AI,2)}},isEmpty:{get(){return e.issues.length===0}}})},nTe=fe("ZodError",iG),va=fe("ZodError",iG,{Parent:Error})}}),sG,aG,lG,cG,uG,dG,pG,mG,hG,fG,gG,yG,iTe=E({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/parse.js"(){gi(),oTe(),sG=oy(va),aG=iy(va),lG=sy(va),cG=ay(va),uG=FI(va),dG=$I(va),pG=UI(va),mG=BI(va),hG=zI(va),fG=GI(va),gG=qI(va),yG=VI(va)}}),sTe={};Z(sTe,{ZodAny:()=>GR,ZodArray:()=>HR,ZodBase64:()=>B_,ZodBase64URL:()=>z_,ZodBigInt:()=>Ey,ZodBigIntFormat:()=>V_,ZodBoolean:()=>_y,ZodCIDRv4:()=>$_,ZodCIDRv6:()=>U_,ZodCUID:()=>P_,ZodCUID2:()=>M_,ZodCatch:()=>a4,ZodCodec:()=>J_,ZodCustom:()=>Ay,ZodCustomStringFormat:()=>jh,ZodDate:()=>j_,ZodDefault:()=>o4,ZodDiscriminatedUnion:()=>KR,ZodE164:()=>G_,ZodEmail:()=>C_,ZodEmoji:()=>I_,ZodEnum:()=>Hh,ZodExactOptional:()=>r4,ZodFile:()=>e4,ZodFunction:()=>m4,ZodGUID:()=>wy,ZodIPv4:()=>L_,ZodIPv6:()=>F_,ZodIntersection:()=>JR,ZodJWT:()=>q_,ZodKSUID:()=>N_,ZodLazy:()=>d4,ZodLiteral:()=>QR,ZodMAC:()=>$R,ZodMap:()=>YR,ZodNaN:()=>l4,ZodNanoID:()=>R_,ZodNever:()=>VR,ZodNonOptional:()=>W_,ZodNull:()=>zR,ZodNullable:()=>n4,ZodNumber:()=>by,ZodNumberFormat:()=>tm,ZodObject:()=>Sy,ZodOptional:()=>H_,ZodPipe:()=>K_,ZodPrefault:()=>i4,ZodPromise:()=>p4,ZodReadonly:()=>c4,ZodRecord:()=>xy,ZodSet:()=>ZR,ZodString:()=>vy,ZodStringFormat:()=>cn,ZodSuccess:()=>s4,ZodSymbol:()=>UR,ZodTemplateLiteral:()=>u4,ZodTransform:()=>t4,ZodTuple:()=>XR,ZodType:()=>Wt,ZodULID:()=>O_,ZodURL:()=>Ty,ZodUUID:()=>Sc,ZodUndefined:()=>BR,ZodUnion:()=>ky,ZodUnknown:()=>qR,ZodVoid:()=>jR,ZodXID:()=>D_,ZodXor:()=>WR,_ZodString:()=>A_,_default:()=>_G,_function:()=>LR,any:()=>wG,array:()=>Ze,base64:()=>xTe,base64url:()=>ATe,bigint:()=>$Te,boolean:()=>an,catch:()=>kG,check:()=>sbe,cidrv4:()=>STe,cidrv6:()=>kTe,codec:()=>nbe,cuid:()=>gTe,cuid2:()=>yTe,custom:()=>CG,date:()=>VTe,describe:()=>PG,discriminatedUnion:()=>DR,e164:()=>CTe,email:()=>aTe,emoji:()=>hTe,enum:()=>Rs,exactOptional:()=>bG,file:()=>QTe,float32:()=>DTe,float64:()=>NTe,function:()=>LR,guid:()=>lTe,hash:()=>OTe,hex:()=>MTe,hostname:()=>PTe,httpUrl:()=>mTe,instanceof:()=>abe,int:()=>MR,int32:()=>LTe,int64:()=>UTe,intersection:()=>S_,ipv4:()=>bTe,ipv6:()=>ETe,json:()=>lbe,jwt:()=>ITe,keyof:()=>jTe,ksuid:()=>TTe,lazy:()=>AG,literal:()=>wt,looseObject:()=>Ni,looseRecord:()=>JTe,mac:()=>_Te,map:()=>XTe,meta:()=>MG,nan:()=>rbe,nanoid:()=>fTe,nativeEnum:()=>ZTe,never:()=>OR,nonoptional:()=>SG,null:()=>E_,nullable:()=>k_,nullish:()=>ebe,number:()=>Lr,object:()=>rt,optional:()=>ro,partialRecord:()=>KTe,pipe:()=>x_,prefault:()=>EG,preprocess:()=>FR,promise:()=>ibe,readonly:()=>xG,record:()=>Hn,refine:()=>IG,set:()=>YTe,strictObject:()=>HTe,string:()=>ee,stringFormat:()=>RTe,stringbool:()=>OG,success:()=>tbe,superRefine:()=>RG,symbol:()=>zTe,templateLiteral:()=>obe,transform:()=>NR,tuple:()=>TG,uint32:()=>FTe,uint64:()=>BTe,ulid:()=>vTe,undefined:()=>GTe,union:()=>ln,unknown:()=>fn,url:()=>vG,uuid:()=>cTe,uuidv4:()=>uTe,uuidv6:()=>dTe,uuidv7:()=>pTe,void:()=>qTe,xid:()=>wTe,xor:()=>WTe});function ee(e){return uwe(vy,e)}function aTe(e){return KB(C_,e)}function lTe(e){return aR(wy,e)}function cTe(e){return JB(Sc,e)}function uTe(e){return XB(Sc,e)}function dTe(e){return YB(Sc,e)}function pTe(e){return ZB(Sc,e)}function vG(e){return lR(Ty,e)}function mTe(e){return lR(Ty,{protocol:/^https?$/,hostname:Gh.domain,...vr.normalizeParams(e)})}function hTe(e){return QB(I_,e)}function fTe(e){return ez(R_,e)}function gTe(e){return tz(P_,e)}function yTe(e){return rz(M_,e)}function vTe(e){return nz(O_,e)}function wTe(e){return oz(D_,e)}function TTe(e){return iz(N_,e)}function bTe(e){return sz(L_,e)}function _Te(e){return pwe($R,e)}function ETe(e){return az(F_,e)}function STe(e){return lz($_,e)}function kTe(e){return cz(U_,e)}function xTe(e){return uz(B_,e)}function ATe(e){return dz(z_,e)}function CTe(e){return pz(G_,e)}function ITe(e){return mz(q_,e)}function RTe(e,t,r={}){return b_(jh,e,t,r)}function PTe(e){return b_(jh,"hostname",Gh.hostname,e)}function MTe(e){return b_(jh,"hex",Gh.hex,e)}function OTe(e,t){const r=t?.enc??"hex",n=`${e}_${r}`,o=Gh[n];if(!o)throw new Error(`Unrecognized hash format: ${n}`);return b_(jh,n,o,t)}function Lr(e){return ywe(by,e)}function MR(e){return wwe(tm,e)}function DTe(e){return Twe(tm,e)}function NTe(e){return bwe(tm,e)}function LTe(e){return _we(tm,e)}function FTe(e){return Ewe(tm,e)}function an(e){return Swe(_y,e)}function $Te(e){return xwe(Ey,e)}function UTe(e){return Cwe(V_,e)}function BTe(e){return Iwe(V_,e)}function zTe(e){return Rwe(UR,e)}function GTe(e){return Pwe(BR,e)}function E_(e){return Mwe(zR,e)}function wG(){return Owe(GR)}function fn(){return Dwe(qR)}function OR(e){return Nwe(VR,e)}function qTe(e){return Lwe(jR,e)}function VTe(e){return Fwe(j_,e)}function Ze(e,t){return Bwe(HR,e,t)}function jTe(e){const t=e._zod.def.shape;return Rs(Object.keys(t))}function rt(e,t){const r={type:"object",shape:e??{},...vr.normalizeParams(t)};return new Sy(r)}function HTe(e,t){return new Sy({type:"object",shape:e,catchall:OR(),...vr.normalizeParams(t)})}function Ni(e,t){return new Sy({type:"object",shape:e,catchall:fn(),...vr.normalizeParams(t)})}function ln(e,t){return new ky({type:"union",options:e,...vr.normalizeParams(t)})}function WTe(e,t){return new WR({type:"union",options:e,inclusive:!1,...vr.normalizeParams(t)})}function DR(e,t,r){return new KR({type:"union",options:t,discriminator:e,...vr.normalizeParams(r)})}function S_(e,t){return new JR({type:"intersection",left:e,right:t})}function TG(e,t,r){const n=t instanceof zt,o=n?r:t,i=n?t:null;return new XR({type:"tuple",items:e,rest:i,...vr.normalizeParams(o)})}function Hn(e,t,r){return new xy({type:"record",keyType:e,valueType:t,...vr.normalizeParams(r)})}function KTe(e,t,r){const n=Ol(e);return n._zod.values=void 0,new xy({type:"record",keyType:n,valueType:t,...vr.normalizeParams(r)})}function JTe(e,t,r){return new xy({type:"record",keyType:e,valueType:t,mode:"loose",...vr.normalizeParams(r)})}function XTe(e,t,r){return new YR({type:"map",keyType:e,valueType:t,...vr.normalizeParams(r)})}function YTe(e,t){return new ZR({type:"set",valueType:e,...vr.normalizeParams(t)})}function Rs(e,t){const r=Array.isArray(e)?Object.fromEntries(e.map(n=>[n,n])):e;return new Hh({type:"enum",entries:r,...vr.normalizeParams(t)})}function ZTe(e,t){return new Hh({type:"enum",entries:e,...vr.normalizeParams(t)})}function wt(e,t){return new QR({type:"literal",values:Array.isArray(e)?e:[e],...vr.normalizeParams(t)})}function QTe(e){return zwe(e4,e)}function NR(e){return new t4({type:"transform",transform:e})}function ro(e){return new H_({type:"optional",innerType:e})}function bG(e){return new r4({type:"optional",innerType:e})}function k_(e){return new n4({type:"nullable",innerType:e})}function ebe(e){return ro(k_(e))}function _G(e,t){return new o4({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():vr.shallowClone(t)}})}function EG(e,t){return new i4({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():vr.shallowClone(t)}})}function SG(e,t){return new W_({type:"nonoptional",innerType:e,...vr.normalizeParams(t)})}function tbe(e){return new s4({type:"success",innerType:e})}function kG(e,t){return new a4({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}function rbe(e){return Uwe(l4,e)}function x_(e,t){return new K_({type:"pipe",in:e,out:t})}function nbe(e,t,r){return new J_({type:"pipe",in:e,out:t,transform:r.decode,reverseTransform:r.encode})}function xG(e){return new c4({type:"readonly",innerType:e})}function obe(e,t){return new u4({type:"template_literal",parts:e,...vr.normalizeParams(t)})}function AG(e){return new d4({type:"lazy",getter:e})}function ibe(e){return new p4({type:"promise",innerType:e})}function LR(e){return new m4({type:"function",input:Array.isArray(e?.input)?TG(e?.input):e?.input??Ze(fn()),output:e?.output??fn()})}function sbe(e){const t=new to({check:"custom"});return t._zod.check=e,t}function CG(e,t){return Gwe(Ay,e??(()=>!0),t)}function IG(e,t={}){return qwe(Ay,e,t)}function RG(e){return Vwe(e)}function abe(e,t={}){const r=new Ay({type:"custom",check:"custom",fn:n=>n instanceof e,abort:!0,...vr.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 lbe(e){const t=AG(()=>ln([ee(e),Lr(),an(),E_(),Ze(t),Hn(ee(),t)]));return t}function FR(e,t){return x_(NR(e),t)}var Wt,A_,vy,cn,C_,wy,Sc,Ty,I_,R_,P_,M_,O_,D_,N_,L_,$R,F_,$_,U_,B_,z_,G_,q_,jh,by,tm,_y,Ey,V_,UR,BR,zR,GR,qR,VR,jR,j_,HR,Sy,ky,WR,KR,JR,XR,xy,YR,ZR,Hh,QR,e4,t4,H_,r4,n4,o4,i4,W_,s4,a4,l4,K_,J_,c4,u4,d4,p4,m4,Ay,PG,MG,OG,h4=E({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/schemas.js"(){gi(),gi(),__(),bR(),oG(),PR(),iTe(),Wt=fe("ZodType",(e,t)=>(zt.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:yy(e,"input"),output:yy(e,"output")}}),e.toJSONSchema=Tz(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.check=(...r)=>e.clone(vr.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)=>Ol(e,r,n),e.brand=()=>e,e.register=((r,n)=>(r.add(e,n),e)),e.parse=(r,n)=>sG(e,r,n,{callee:e.parse}),e.safeParse=(r,n)=>lG(e,r,n),e.parseAsync=async(r,n)=>aG(e,r,n,{callee:e.parseAsync}),e.safeParseAsync=async(r,n)=>cG(e,r,n),e.spa=e.safeParseAsync,e.encode=(r,n)=>uG(e,r,n),e.decode=(r,n)=>dG(e,r,n),e.encodeAsync=async(r,n)=>pG(e,r,n),e.decodeAsync=async(r,n)=>mG(e,r,n),e.safeEncode=(r,n)=>hG(e,r,n),e.safeDecode=(r,n)=>fG(e,r,n),e.safeEncodeAsync=async(r,n)=>gG(e,r,n),e.safeDecodeAsync=async(r,n)=>yG(e,r,n),e.refine=(r,n)=>e.check(IG(r,n)),e.superRefine=r=>e.check(RG(r)),e.overwrite=r=>e.check(Ed(r)),e.optional=()=>ro(e),e.exactOptional=()=>bG(e),e.nullable=()=>k_(e),e.nullish=()=>ro(k_(e)),e.nonoptional=r=>SG(e,r),e.array=()=>Ze(e),e.or=r=>ln([e,r]),e.and=r=>S_(e,r),e.transform=r=>x_(e,NR(r)),e.default=r=>_G(e,r),e.prefault=r=>EG(e,r),e.catch=r=>kG(e,r),e.pipe=r=>x_(e,r),e.readonly=()=>xG(e),e.describe=r=>{const n=e.clone();return Za.add(n,{description:r}),n},Object.defineProperty(e,"description",{get(){return Za.get(e)?.description},configurable:!0}),e.meta=(...r)=>{if(r.length===0)return Za.get(e);const n=e.clone();return Za.add(n,r[0]),n},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e.apply=r=>r(e),e)),A_=fe("_ZodString",(e,t)=>{cy.init(e,t),Wt.init(e,t),e._zod.processJSONSchema=(n,o,i)=>bz(e,n,o,i);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(cR(...n)),e.includes=(...n)=>e.check(pR(...n)),e.startsWith=(...n)=>e.check(mR(...n)),e.endsWith=(...n)=>e.check(hR(...n)),e.min=(...n)=>e.check(Vh(...n)),e.max=(...n)=>e.check(w_(...n)),e.length=(...n)=>e.check(T_(...n)),e.nonempty=(...n)=>e.check(Vh(1,...n)),e.lowercase=n=>e.check(uR(n)),e.uppercase=n=>e.check(dR(n)),e.trim=()=>e.check(yR()),e.normalize=(...n)=>e.check(gR(...n)),e.toLowerCase=()=>e.check(vR()),e.toUpperCase=()=>e.check(wR()),e.slugify=()=>e.check(TR())}),vy=fe("ZodString",(e,t)=>{cy.init(e,t),A_.init(e,t),e.email=r=>e.check(KB(C_,r)),e.url=r=>e.check(lR(Ty,r)),e.jwt=r=>e.check(mz(q_,r)),e.emoji=r=>e.check(QB(I_,r)),e.guid=r=>e.check(aR(wy,r)),e.uuid=r=>e.check(JB(Sc,r)),e.uuidv4=r=>e.check(XB(Sc,r)),e.uuidv6=r=>e.check(YB(Sc,r)),e.uuidv7=r=>e.check(ZB(Sc,r)),e.nanoid=r=>e.check(ez(R_,r)),e.guid=r=>e.check(aR(wy,r)),e.cuid=r=>e.check(tz(P_,r)),e.cuid2=r=>e.check(rz(M_,r)),e.ulid=r=>e.check(nz(O_,r)),e.base64=r=>e.check(uz(B_,r)),e.base64url=r=>e.check(dz(z_,r)),e.xid=r=>e.check(oz(D_,r)),e.ksuid=r=>e.check(iz(N_,r)),e.ipv4=r=>e.check(sz(L_,r)),e.ipv6=r=>e.check(az(F_,r)),e.cidrv4=r=>e.check(lz($_,r)),e.cidrv6=r=>e.check(cz(U_,r)),e.e164=r=>e.check(pz(G_,r)),e.datetime=r=>e.check(Qwe(r)),e.date=r=>e.check(eTe(r)),e.time=r=>e.check(tTe(r)),e.duration=r=>e.check(rTe(r))}),cn=fe("ZodStringFormat",(e,t)=>{on.init(e,t),A_.init(e,t)}),C_=fe("ZodEmail",(e,t)=>{NU.init(e,t),cn.init(e,t)}),wy=fe("ZodGUID",(e,t)=>{OU.init(e,t),cn.init(e,t)}),Sc=fe("ZodUUID",(e,t)=>{DU.init(e,t),cn.init(e,t)}),Ty=fe("ZodURL",(e,t)=>{LU.init(e,t),cn.init(e,t)}),I_=fe("ZodEmoji",(e,t)=>{FU.init(e,t),cn.init(e,t)}),R_=fe("ZodNanoID",(e,t)=>{$U.init(e,t),cn.init(e,t)}),P_=fe("ZodCUID",(e,t)=>{UU.init(e,t),cn.init(e,t)}),M_=fe("ZodCUID2",(e,t)=>{BU.init(e,t),cn.init(e,t)}),O_=fe("ZodULID",(e,t)=>{zU.init(e,t),cn.init(e,t)}),D_=fe("ZodXID",(e,t)=>{GU.init(e,t),cn.init(e,t)}),N_=fe("ZodKSUID",(e,t)=>{qU.init(e,t),cn.init(e,t)}),L_=fe("ZodIPv4",(e,t)=>{KU.init(e,t),cn.init(e,t)}),$R=fe("ZodMAC",(e,t)=>{XU.init(e,t),cn.init(e,t)}),F_=fe("ZodIPv6",(e,t)=>{JU.init(e,t),cn.init(e,t)}),$_=fe("ZodCIDRv4",(e,t)=>{YU.init(e,t),cn.init(e,t)}),U_=fe("ZodCIDRv6",(e,t)=>{ZU.init(e,t),cn.init(e,t)}),B_=fe("ZodBase64",(e,t)=>{QU.init(e,t),cn.init(e,t)}),z_=fe("ZodBase64URL",(e,t)=>{eB.init(e,t),cn.init(e,t)}),G_=fe("ZodE164",(e,t)=>{tB.init(e,t),cn.init(e,t)}),q_=fe("ZodJWT",(e,t)=>{rB.init(e,t),cn.init(e,t)}),jh=fe("ZodCustomStringFormat",(e,t)=>{nB.init(e,t),cn.init(e,t)}),by=fe("ZodNumber",(e,t)=>{eR.init(e,t),Wt.init(e,t),e._zod.processJSONSchema=(n,o,i)=>_z(e,n,o,i),e.gt=(n,o)=>e.check(Qp(n,o)),e.gte=(n,o)=>e.check(ya(n,o)),e.min=(n,o)=>e.check(ya(n,o)),e.lt=(n,o)=>e.check(Zp(n,o)),e.lte=(n,o)=>e.check(Nl(n,o)),e.max=(n,o)=>e.check(Nl(n,o)),e.int=n=>e.check(MR(n)),e.safe=n=>e.check(MR(n)),e.positive=n=>e.check(Qp(0,n)),e.nonnegative=n=>e.check(ya(0,n)),e.negative=n=>e.check(Zp(0,n)),e.nonpositive=n=>e.check(Nl(0,n)),e.multipleOf=(n,o)=>e.check(py(n,o)),e.step=(n,o)=>e.check(py(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}),tm=fe("ZodNumberFormat",(e,t)=>{oB.init(e,t),by.init(e,t)}),_y=fe("ZodBoolean",(e,t)=>{tR.init(e,t),Wt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Ez(e,r,n,o)}),Ey=fe("ZodBigInt",(e,t)=>{rR.init(e,t),Wt.init(e,t),e._zod.processJSONSchema=(n,o,i)=>Sz(e,n,o,i),e.gte=(n,o)=>e.check(ya(n,o)),e.min=(n,o)=>e.check(ya(n,o)),e.gt=(n,o)=>e.check(Qp(n,o)),e.gte=(n,o)=>e.check(ya(n,o)),e.min=(n,o)=>e.check(ya(n,o)),e.lt=(n,o)=>e.check(Zp(n,o)),e.lte=(n,o)=>e.check(Nl(n,o)),e.max=(n,o)=>e.check(Nl(n,o)),e.positive=n=>e.check(Qp(BigInt(0),n)),e.negative=n=>e.check(Zp(BigInt(0),n)),e.nonpositive=n=>e.check(Nl(BigInt(0),n)),e.nonnegative=n=>e.check(ya(BigInt(0),n)),e.multipleOf=(n,o)=>e.check(py(n,o));const r=e._zod.bag;e.minValue=r.minimum??null,e.maxValue=r.maximum??null,e.format=r.format??null}),V_=fe("ZodBigIntFormat",(e,t)=>{iB.init(e,t),Ey.init(e,t)}),UR=fe("ZodSymbol",(e,t)=>{sB.init(e,t),Wt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>kz(e,r,n,o)}),BR=fe("ZodUndefined",(e,t)=>{aB.init(e,t),Wt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Az(e,r,n,o)}),zR=fe("ZodNull",(e,t)=>{lB.init(e,t),Wt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>xz(e,r,n,o)}),GR=fe("ZodAny",(e,t)=>{cB.init(e,t),Wt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Rz(e,r,n,o)}),qR=fe("ZodUnknown",(e,t)=>{uB.init(e,t),Wt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Pz(e,r,n,o)}),VR=fe("ZodNever",(e,t)=>{dB.init(e,t),Wt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Iz(e,r,n,o)}),jR=fe("ZodVoid",(e,t)=>{pB.init(e,t),Wt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Cz(e,r,n,o)}),j_=fe("ZodDate",(e,t)=>{mB.init(e,t),Wt.init(e,t),e._zod.processJSONSchema=(n,o,i)=>Mz(e,n,o,i),e.min=(n,o)=>e.check(ya(n,o)),e.max=(n,o)=>e.check(Nl(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}),HR=fe("ZodArray",(e,t)=>{hB.init(e,t),Wt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Vz(e,r,n,o),e.element=t.element,e.min=(r,n)=>e.check(Vh(r,n)),e.nonempty=r=>e.check(Vh(1,r)),e.max=(r,n)=>e.check(w_(r,n)),e.length=(r,n)=>e.check(T_(r,n)),e.unwrap=()=>e.element}),Sy=fe("ZodObject",(e,t)=>{gB.init(e,t),Wt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>jz(e,r,n,o),vr.defineLazy(e,"shape",()=>t.shape),e.keyof=()=>Rs(Object.keys(e._zod.def.shape)),e.catchall=r=>e.clone({...e._zod.def,catchall:r}),e.passthrough=()=>e.clone({...e._zod.def,catchall:fn()}),e.loose=()=>e.clone({...e._zod.def,catchall:fn()}),e.strict=()=>e.clone({...e._zod.def,catchall:OR()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=r=>vr.extend(e,r),e.safeExtend=r=>vr.safeExtend(e,r),e.merge=r=>vr.merge(e,r),e.pick=r=>vr.pick(e,r),e.omit=r=>vr.omit(e,r),e.partial=(...r)=>vr.partial(H_,e,r[0]),e.required=(...r)=>vr.required(W_,e,r[0])}),ky=fe("ZodUnion",(e,t)=>{y_.init(e,t),Wt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>ER(e,r,n,o),e.options=t.options}),WR=fe("ZodXor",(e,t)=>{ky.init(e,t),yB.init(e,t),e._zod.processJSONSchema=(r,n,o)=>ER(e,r,n,o),e.options=t.options}),KR=fe("ZodDiscriminatedUnion",(e,t)=>{ky.init(e,t),vB.init(e,t)}),JR=fe("ZodIntersection",(e,t)=>{wB.init(e,t),Wt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Hz(e,r,n,o)}),XR=fe("ZodTuple",(e,t)=>{nR.init(e,t),Wt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Wz(e,r,n,o),e.rest=r=>e.clone({...e._zod.def,rest:r})}),xy=fe("ZodRecord",(e,t)=>{TB.init(e,t),Wt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Kz(e,r,n,o),e.keyType=t.keyType,e.valueType=t.valueType}),YR=fe("ZodMap",(e,t)=>{bB.init(e,t),Wt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Gz(e,r,n,o),e.keyType=t.keyType,e.valueType=t.valueType,e.min=(...r)=>e.check(em(...r)),e.nonempty=r=>e.check(em(1,r)),e.max=(...r)=>e.check(my(...r)),e.size=(...r)=>e.check(v_(...r))}),ZR=fe("ZodSet",(e,t)=>{_B.init(e,t),Wt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>qz(e,r,n,o),e.min=(...r)=>e.check(em(...r)),e.nonempty=r=>e.check(em(1,r)),e.max=(...r)=>e.check(my(...r)),e.size=(...r)=>e.check(v_(...r))}),Hh=fe("ZodEnum",(e,t)=>{EB.init(e,t),Wt.init(e,t),e._zod.processJSONSchema=(n,o,i)=>Oz(e,n,o,i),e.enum=t.entries,e.options=Object.values(t.entries);const r=new Set(Object.keys(t.entries));e.extract=(n,o)=>{const i={};for(const s of n)if(r.has(s))i[s]=t.entries[s];else throw new Error(`Key ${s} not found in enum`);return new Hh({...t,checks:[],...vr.normalizeParams(o),entries:i})},e.exclude=(n,o)=>{const i={...t.entries};for(const s of n)if(r.has(s))delete i[s];else throw new Error(`Key ${s} not found in enum`);return new Hh({...t,checks:[],...vr.normalizeParams(o),entries:i})}}),QR=fe("ZodLiteral",(e,t)=>{SB.init(e,t),Wt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Dz(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]}})}),e4=fe("ZodFile",(e,t)=>{kB.init(e,t),Wt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Fz(e,r,n,o),e.min=(r,n)=>e.check(em(r,n)),e.max=(r,n)=>e.check(my(r,n)),e.mime=(r,n)=>e.check(fR(Array.isArray(r)?r:[r],n))}),t4=fe("ZodTransform",(e,t)=>{xB.init(e,t),Wt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>zz(e,r,n,o),e._zod.parse=(r,n)=>{if(n.direction==="backward")throw new c_(e.constructor.name);r.addIssue=i=>{if(typeof i=="string")r.issues.push(vr.issue(i,r.value,t));else{const s=i;s.fatal&&(s.continue=!1),s.code??(s.code="custom"),s.input??(s.input=r.value),s.inst??(s.inst=e),r.issues.push(vr.issue(s))}};const o=t.transform(r.value,r);return o instanceof Promise?o.then(i=>(r.value=i,r)):(r.value=o,r)}}),H_=fe("ZodOptional",(e,t)=>{oR.init(e,t),Wt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>SR(e,r,n,o),e.unwrap=()=>e._zod.def.innerType}),r4=fe("ZodExactOptional",(e,t)=>{AB.init(e,t),Wt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>SR(e,r,n,o),e.unwrap=()=>e._zod.def.innerType}),n4=fe("ZodNullable",(e,t)=>{CB.init(e,t),Wt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Jz(e,r,n,o),e.unwrap=()=>e._zod.def.innerType}),o4=fe("ZodDefault",(e,t)=>{IB.init(e,t),Wt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Yz(e,r,n,o),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap}),i4=fe("ZodPrefault",(e,t)=>{RB.init(e,t),Wt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Zz(e,r,n,o),e.unwrap=()=>e._zod.def.innerType}),W_=fe("ZodNonOptional",(e,t)=>{PB.init(e,t),Wt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Xz(e,r,n,o),e.unwrap=()=>e._zod.def.innerType}),s4=fe("ZodSuccess",(e,t)=>{MB.init(e,t),Wt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>$z(e,r,n,o),e.unwrap=()=>e._zod.def.innerType}),a4=fe("ZodCatch",(e,t)=>{OB.init(e,t),Wt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Qz(e,r,n,o),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap}),l4=fe("ZodNaN",(e,t)=>{DB.init(e,t),Wt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Nz(e,r,n,o)}),K_=fe("ZodPipe",(e,t)=>{NB.init(e,t),Wt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>eG(e,r,n,o),e.in=t.in,e.out=t.out}),J_=fe("ZodCodec",(e,t)=>{K_.init(e,t),iR.init(e,t)}),c4=fe("ZodReadonly",(e,t)=>{LB.init(e,t),Wt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>tG(e,r,n,o),e.unwrap=()=>e._zod.def.innerType}),u4=fe("ZodTemplateLiteral",(e,t)=>{FB.init(e,t),Wt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Lz(e,r,n,o)}),d4=fe("ZodLazy",(e,t)=>{BB.init(e,t),Wt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>nG(e,r,n,o),e.unwrap=()=>e._zod.def.getter()}),p4=fe("ZodPromise",(e,t)=>{UB.init(e,t),Wt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>rG(e,r,n,o),e.unwrap=()=>e._zod.def.innerType}),m4=fe("ZodFunction",(e,t)=>{$B.init(e,t),Wt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Bz(e,r,n,o)}),Ay=fe("ZodCustom",(e,t)=>{zB.init(e,t),Wt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Uz(e,r,n,o)}),PG=Hwe,MG=Wwe,OG=(...e)=>Kwe({Codec:J_,Boolean:_y,String:vy},...e)}});function jIr(e){Is({customError:e})}function HIr(){return Is().customError}var DG,NG,WIr=E({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/compat.js"(){gi(),gi(),DG={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"},NG||(NG={})}});function KIr(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 JIr(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 cbe(e,t){if(e.not!==void 0){if(typeof e.not=="object"&&Object.keys(e.not).length===0)return nt.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 nt.lazy(()=>{if(!t.refs.has(o))throw new Error(`Circular reference not resolved: ${o}`);return t.refs.get(o)});t.processing.add(o);const i=JIr(o,t),s=Ps(i,t);return t.refs.set(o,s),t.processing.delete(o),s}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 nt.null();if(o.length===0)return nt.never();if(o.length===1)return nt.literal(o[0]);if(o.every(s=>typeof s=="string"))return nt.enum(o);const i=o.map(s=>nt.literal(s));return i.length<2?i[0]:nt.union([i[0],i[1],...i.slice(2)])}if(e.const!==void 0)return nt.literal(e.const);const r=e.type;if(Array.isArray(r)){const o=r.map(i=>{const s={...e,type:i};return cbe(s,t)});return o.length===0?nt.never():o.length===1?o[0]:nt.union(o)}if(!r)return nt.any();let n;switch(r){case"string":{let o=nt.string();if(e.format){const i=e.format;i==="email"?o=o.check(nt.email()):i==="uri"||i==="uri-reference"?o=o.check(nt.url()):i==="uuid"||i==="guid"?o=o.check(nt.uuid()):i==="date-time"?o=o.check(nt.iso.datetime()):i==="date"?o=o.check(nt.iso.date()):i==="time"?o=o.check(nt.iso.time()):i==="duration"?o=o.check(nt.iso.duration()):i==="ipv4"?o=o.check(nt.ipv4()):i==="ipv6"?o=o.check(nt.ipv6()):i==="mac"?o=o.check(nt.mac()):i==="cidr"?o=o.check(nt.cidrv4()):i==="cidr-v6"?o=o.check(nt.cidrv6()):i==="base64"?o=o.check(nt.base64()):i==="base64url"?o=o.check(nt.base64url()):i==="e164"?o=o.check(nt.e164()):i==="jwt"?o=o.check(nt.jwt()):i==="emoji"?o=o.check(nt.emoji()):i==="nanoid"?o=o.check(nt.nanoid()):i==="cuid"?o=o.check(nt.cuid()):i==="cuid2"?o=o.check(nt.cuid2()):i==="ulid"?o=o.check(nt.ulid()):i==="xid"?o=o.check(nt.xid()):i==="ksuid"&&(o=o.check(nt.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"?nt.number().int():nt.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=nt.boolean();break}case"null":{n=nt.null();break}case"object":{const o={},i=e.properties||{},s=new Set(e.required||[]);for(const[l,c]of Object.entries(i)){const u=Ps(c,t);o[l]=s.has(l)?u:u.optional()}if(e.propertyNames){const l=Ps(e.propertyNames,t),c=e.additionalProperties&&typeof e.additionalProperties=="object"?Ps(e.additionalProperties,t):nt.any();if(Object.keys(o).length===0){n=nt.record(l,c);break}const u=nt.object(o).passthrough(),d=nt.looseRecord(l,c);n=nt.intersection(u,d);break}if(e.patternProperties){const l=e.patternProperties,c=Object.keys(l),u=[];for(const p of c){const m=Ps(l[p],t),f=nt.string().regex(new RegExp(p));u.push(nt.looseRecord(f,m))}const d=[];if(Object.keys(o).length>0&&d.push(nt.object(o).passthrough()),d.push(...u),d.length===0)n=nt.object({}).passthrough();else if(d.length===1)n=d[0];else{let p=nt.intersection(d[0],d[1]);for(let m=2;m<d.length;m++)p=nt.intersection(p,d[m]);n=p}break}const a=nt.object(o);e.additionalProperties===!1?n=a.strict():typeof e.additionalProperties=="object"?n=a.catchall(Ps(e.additionalProperties,t)):n=a.passthrough();break}case"array":{const o=e.prefixItems,i=e.items;if(o&&Array.isArray(o)){const s=o.map(l=>Ps(l,t)),a=i&&typeof i=="object"&&!Array.isArray(i)?Ps(i,t):void 0;a?n=nt.tuple(s).rest(a):n=nt.tuple(s),typeof e.minItems=="number"&&(n=n.check(nt.minLength(e.minItems))),typeof e.maxItems=="number"&&(n=n.check(nt.maxLength(e.maxItems)))}else if(Array.isArray(i)){const s=i.map(l=>Ps(l,t)),a=e.additionalItems&&typeof e.additionalItems=="object"?Ps(e.additionalItems,t):void 0;a?n=nt.tuple(s).rest(a):n=nt.tuple(s),typeof e.minItems=="number"&&(n=n.check(nt.minLength(e.minItems))),typeof e.maxItems=="number"&&(n=n.check(nt.maxLength(e.maxItems)))}else if(i!==void 0){const s=Ps(i,t);let a=nt.array(s);typeof e.minItems=="number"&&(a=a.min(e.minItems)),typeof e.maxItems=="number"&&(a=a.max(e.maxItems)),n=a}else n=nt.array(nt.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 Ps(e,t){if(typeof e=="boolean")return e?nt.any():nt.never();let r=cbe(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=>Ps(c,t)),l=nt.union(a);r=n?nt.intersection(r,l):l}if(e.oneOf&&Array.isArray(e.oneOf)){const a=e.oneOf.map(c=>Ps(c,t)),l=nt.xor(a);r=n?nt.intersection(r,l):l}if(e.allOf&&Array.isArray(e.allOf))if(e.allOf.length===0)r=n?r:nt.any();else{let a=n?r:Ps(e.allOf[0],t);const l=n?0:1;for(let c=l;c<e.allOf.length;c++)a=nt.intersection(a,Ps(e.allOf[c],t));r=a}e.nullable===!0&&t.version==="openapi-3.0"&&(r=nt.nullable(r)),e.readOnly===!0&&(r=nt.readonly(r));const o={},i=["$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor"];for(const a of i)a in e&&(o[a]=e[a]);const s=["contentEncoding","contentMediaType","contentSchema"];for(const a of s)a in e&&(o[a]=e[a]);for(const a of Object.keys(e))ube.has(a)||(o[a]=e[a]);return Object.keys(o).length>0&&t.registry.add(r,o),r}function XIr(e,t){if(typeof e=="boolean")return e?nt.any():nt.never();const r=KIr(e,t?.defaultTarget),n=e.$defs||e.definitions||{},o={version:r,defs:n,refs:new Map,processing:new Set,rootSchema:e,registry:t?.registry??Za};return Ps(e,o)}var nt,ube,YIr=E({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/from-json-schema.js"(){sR(),oG(),PR(),h4(),nt={...sTe,...Zwe,iso:xR},ube=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"])}}),LG={};Z(LG,{bigint:()=>tRr,boolean:()=>eRr,date:()=>rRr,number:()=>QIr,string:()=>ZIr});function ZIr(e){return dwe(vy,e)}function QIr(e){return vwe(by,e)}function eRr(e){return kwe(_y,e)}function tRr(e){return Awe(Ey,e)}function rRr(e){return $we(j_,e)}var nRr=E({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/coerce.js"(){gi(),h4()}}),N={};Z(N,{$brand:()=>E5,$input:()=>HB,$output:()=>jB,NEVER:()=>xI,TimePrecision:()=>wz,ZodAny:()=>GR,ZodArray:()=>HR,ZodBase64:()=>B_,ZodBase64URL:()=>z_,ZodBigInt:()=>Ey,ZodBigIntFormat:()=>V_,ZodBoolean:()=>_y,ZodCIDRv4:()=>$_,ZodCIDRv6:()=>U_,ZodCUID:()=>P_,ZodCUID2:()=>M_,ZodCatch:()=>a4,ZodCodec:()=>J_,ZodCustom:()=>Ay,ZodCustomStringFormat:()=>jh,ZodDate:()=>j_,ZodDefault:()=>o4,ZodDiscriminatedUnion:()=>KR,ZodE164:()=>G_,ZodEmail:()=>C_,ZodEmoji:()=>I_,ZodEnum:()=>Hh,ZodError:()=>nTe,ZodExactOptional:()=>r4,ZodFile:()=>e4,ZodFirstPartyTypeKind:()=>NG,ZodFunction:()=>m4,ZodGUID:()=>wy,ZodIPv4:()=>L_,ZodIPv6:()=>F_,ZodISODate:()=>CR,ZodISODateTime:()=>AR,ZodISODuration:()=>RR,ZodISOTime:()=>IR,ZodIntersection:()=>JR,ZodIssueCode:()=>DG,ZodJWT:()=>q_,ZodKSUID:()=>N_,ZodLazy:()=>d4,ZodLiteral:()=>QR,ZodMAC:()=>$R,ZodMap:()=>YR,ZodNaN:()=>l4,ZodNanoID:()=>R_,ZodNever:()=>VR,ZodNonOptional:()=>W_,ZodNull:()=>zR,ZodNullable:()=>n4,ZodNumber:()=>by,ZodNumberFormat:()=>tm,ZodObject:()=>Sy,ZodOptional:()=>H_,ZodPipe:()=>K_,ZodPrefault:()=>i4,ZodPromise:()=>p4,ZodReadonly:()=>c4,ZodRealError:()=>va,ZodRecord:()=>xy,ZodSet:()=>ZR,ZodString:()=>vy,ZodStringFormat:()=>cn,ZodSuccess:()=>s4,ZodSymbol:()=>UR,ZodTemplateLiteral:()=>u4,ZodTransform:()=>t4,ZodTuple:()=>XR,ZodType:()=>Wt,ZodULID:()=>O_,ZodURL:()=>Ty,ZodUUID:()=>Sc,ZodUndefined:()=>BR,ZodUnion:()=>ky,ZodUnknown:()=>qR,ZodVoid:()=>jR,ZodXID:()=>D_,ZodXor:()=>WR,_ZodString:()=>A_,_default:()=>_G,_function:()=>LR,any:()=>wG,array:()=>Ze,base64:()=>xTe,base64url:()=>ATe,bigint:()=>$Te,boolean:()=>an,catch:()=>kG,check:()=>sbe,cidrv4:()=>STe,cidrv6:()=>kTe,clone:()=>Ol,codec:()=>nbe,coerce:()=>LG,config:()=>Is,core:()=>Ywe,cuid:()=>gTe,cuid2:()=>yTe,custom:()=>CG,date:()=>VTe,decode:()=>dG,decodeAsync:()=>mG,describe:()=>PG,discriminatedUnion:()=>DR,e164:()=>CTe,email:()=>aTe,emoji:()=>hTe,encode:()=>uG,encodeAsync:()=>pG,endsWith:()=>hR,enum:()=>Rs,exactOptional:()=>bG,file:()=>QTe,flattenError:()=>P5,float32:()=>DTe,float64:()=>NTe,formatError:()=>M5,fromJSONSchema:()=>XIr,function:()=>LR,getErrorMap:()=>HIr,globalRegistry:()=>Za,gt:()=>Qp,gte:()=>ya,guid:()=>lTe,hash:()=>OTe,hex:()=>MTe,hostname:()=>PTe,httpUrl:()=>mTe,includes:()=>pR,instanceof:()=>abe,int:()=>MR,int32:()=>LTe,int64:()=>UTe,intersection:()=>S_,ipv4:()=>bTe,ipv6:()=>ETe,iso:()=>xR,json:()=>lbe,jwt:()=>ITe,keyof:()=>jTe,ksuid:()=>TTe,lazy:()=>AG,length:()=>T_,literal:()=>wt,locales:()=>GB,looseObject:()=>Ni,looseRecord:()=>JTe,lowercase:()=>uR,lt:()=>Zp,lte:()=>Nl,mac:()=>_Te,map:()=>XTe,maxLength:()=>w_,maxSize:()=>my,meta:()=>MG,mime:()=>fR,minLength:()=>Vh,minSize:()=>em,multipleOf:()=>py,nan:()=>rbe,nanoid:()=>fTe,nativeEnum:()=>ZTe,negative:()=>fz,never:()=>OR,nonnegative:()=>yz,nonoptional:()=>SG,nonpositive:()=>gz,normalize:()=>gR,null:()=>E_,nullable:()=>k_,nullish:()=>ebe,number:()=>Lr,object:()=>rt,optional:()=>ro,overwrite:()=>Ed,parse:()=>sG,parseAsync:()=>aG,partialRecord:()=>KTe,pipe:()=>x_,positive:()=>hz,prefault:()=>EG,preprocess:()=>FR,prettifyError:()=>Q0e,promise:()=>ibe,property:()=>vz,readonly:()=>xG,record:()=>Hn,refine:()=>IG,regex:()=>cR,regexes:()=>Gh,registry:()=>VB,safeDecode:()=>fG,safeDecodeAsync:()=>yG,safeEncode:()=>hG,safeEncodeAsync:()=>gG,safeParse:()=>lG,safeParseAsync:()=>cG,set:()=>YTe,setErrorMap:()=>jIr,size:()=>v_,slugify:()=>TR,startsWith:()=>mR,strictObject:()=>HTe,string:()=>ee,stringFormat:()=>RTe,stringbool:()=>OG,success:()=>tbe,superRefine:()=>RG,symbol:()=>zTe,templateLiteral:()=>obe,toJSONSchema:()=>_R,toLowerCase:()=>vR,toUpperCase:()=>wR,transform:()=>NR,treeifyError:()=>Y0e,trim:()=>yR,tuple:()=>TG,uint32:()=>FTe,uint64:()=>BTe,ulid:()=>vTe,undefined:()=>GTe,union:()=>ln,unknown:()=>fn,uppercase:()=>dR,url:()=>vG,util:()=>vr,uuid:()=>cTe,uuidv4:()=>uTe,uuidv6:()=>dTe,uuidv7:()=>pTe,void:()=>qTe,xid:()=>wTe,xor:()=>WTe});var f4=E({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/external.js"(){gi(),h4(),oG(),oTe(),iTe(),WIr(),gi(),yve(),gi(),__(),YIr(),qB(),PR(),PR(),nRr(),Is(fve())}}),gn=E({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/index.js"(){f4(),f4()}}),FG,$G,oRr=E({"src/lib/types/model.ts"(){"use strict";gn(),FG=N.object({id:N.string(),displayName:N.string(),capabilities:N.array(N.string()),deprecated:N.boolean(),pricing:N.object({input:N.number(),output:N.number()}),contextWindow:N.number(),releaseDate:N.string()}),$G=N.object({version:N.string(),lastUpdated:N.string(),models:N.record(N.string(),N.record(N.string(),FG)),aliases:N.record(N.string(),N.string()).optional(),defaults:N.record(N.string(),N.string()).optional()})}});function dbe(e){return e.type==="text"}function iRr(e){return e.type==="image"}function UG(e){return e.type==="csv"}function sRr(e){return e.type==="pdf"}function aRr(e){return e.type==="audio"}function lRr(e){return e.type==="video"}function cRr(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 uRr(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(cRr))}function dRr(e){return Array.isArray(e)}var pRr=E({"src/lib/types/multimodal.ts"(){"use strict"}}),mRr=E({"src/lib/types/nativeTools.ts"(){"use strict"}}),hRr=E({"src/lib/types/observability.ts"(){"use strict"}}),fRr=E({"src/lib/types/openaiCompatible.ts"(){"use strict"}});function gRr(e){return/^[0-9A-Fa-f]{6}$/.test(e)}function yRr(e){return e.startsWith("#")?e.slice(1):e}var pbe,mbe,g4,vRr=E({"src/lib/types/ppt.ts"(){"use strict";pbe=5,mbe=50,g4={"16:9":{width:10,height:5.625},"4:3":{width:10,height:7.5}}}}),BG,hbe,fbe=E({"src/lib/processors/errors/FileErrorCode.ts"(){"use strict";BG=(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))(BG||{}),hbe={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}}}}),zG,gbe,ybe,vbe,wbe,Tbe,wRr=E({"src/lib/types/processor.ts"(){"use strict";fbe(),zG={maxRetries:3,baseDelayMs:1e3,maxDelayMs:1e4},gbe=3e4,ybe=10,vbe=3e4,wbe=10,Tbe={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}}}),TRr=E({"src/lib/types/providerCatalog.ts"(){"use strict"}}),bRr=E({"src/lib/types/providerCatalog.generated.ts"(){"use strict"}});function _Rr(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 y4,bbe,_be,X_,ERr=E({"src/lib/types/providers.ts"(){"use strict";y4={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"},bbe=y4,_be=[{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"]}],X_=["generate","stream"]}}),SRr=E({"src/lib/types/proxy.ts"(){"use strict"}}),kRr=E({"src/lib/types/proxyIR.ts"(){"use strict"}}),xRr=E({"src/lib/types/proxyClient.ts"(){"use strict"}}),ARr=E({"src/lib/types/proxyContext.ts"(){"use strict"}}),Ebe,CRr=E({"src/lib/types/rag.ts"(){"use strict";Ebe=["image/jpeg","image/png","image/gif","image/webp","image/bmp","image/tiff","image/avif"]}}),IRr=E({"src/lib/types/scorer.ts"(){"use strict"}}),RRr=E({"src/lib/types/sdk.ts"(){"use strict"}}),Or,no,Ar,PRr=E({"src/lib/types/server.ts"(){"use strict";Or={CONFIG:"CONFIG",VALIDATION:"VALIDATION",EXECUTION:"EXECUTION",EXTERNAL:"EXTERNAL",RATE_LIMIT:"RATE_LIMIT",AUTHENTICATION:"AUTHENTICATION",AUTHORIZATION:"AUTHORIZATION",STREAMING:"STREAMING",WEBSOCKET:"WEBSOCKET"},no={LOW:"LOW",MEDIUM:"MEDIUM",HIGH:"HIGH",CRITICAL:"CRITICAL"},Ar={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"}}}),MRr=E({"src/lib/types/service.ts"(){"use strict"}}),ORr=E({"src/lib/types/skills.ts"(){"use strict"}}),DRr=E({"src/lib/types/stream.ts"(){"use strict"}}),NRr=E({"src/lib/types/streaming.ts"(){"use strict"}}),LRr=E({"src/lib/types/subscription.ts"(){"use strict"}}),GG,qG,Xo,FRr=E({"src/lib/types/task.ts"(){"use strict";GG=720*60*60*1e3,qG=10080*60*1e3,Xo={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:GG,failedTTL:qG,cancelledTTL:qG,runLogTTL:GG}}}}),$Rr=E({"src/lib/types/taskClassification.ts"(){"use strict"}}),URr=E({"src/lib/types/tasks.ts"(){"use strict"}}),BRr=E({"src/lib/types/toolDedup.ts"(){"use strict"}}),zRr=E({"src/lib/types/toolResolution.ts"(){"use strict"}}),GRr=E({"src/lib/types/toolRouting.ts"(){"use strict"}});function qRr(e){return typeof e=="object"&&e!==null&&"success"in e&&typeof e.success=="boolean"}function VRr(e){return typeof e=="object"&&e!==null&&"description"in e&&"execute"in e&&typeof e.description=="string"&&typeof e.execute=="function"}var jRr=E({"src/lib/types/tools.ts"(){"use strict"}}),HRr=E({"src/lib/types/vectorStoreChroma.ts"(){"use strict"}}),WRr=E({"src/lib/types/vectorStorePinecone.ts"(){"use strict"}});function KRr(e){if(!e||typeof e!="object")return!1;const t=e;return Buffer.isBuffer(t.buffer)&&typeof t.format=="string"&&Y_.includes(t.format)&&typeof t.size=="number"&&t.size>=0}function JRr(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&&!Y_.includes(t.format)||t.quality!==void 0&&!VG.includes(t.quality)||t.streamingBufferSize!==void 0&&(!Number.isInteger(t.streamingBufferSize)||t.streamingBufferSize<1))}var Y_,VG,XRr=E({"src/lib/types/tts.ts"(){"use strict";Y_=["mp3","wav","ogg","opus","m4a","flac","webm","mp4","mpeg","mpga","pcm16"],VG=["standard","hd"]}});function Sbe(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 kbe(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 xbe(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 vs,jG,YRr=E({"src/lib/types/stt.ts"(){"use strict";vs={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"},jG={language:"en-US",punctuation:!0,profanityFilter:!1,sampleRate:16e3}}});function Abe(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 es,v4,ZRr=E({"src/lib/types/realtime.ts"(){"use strict";es={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"},v4={timeout:3e4,inputSampleRate:24e3,outputSampleRate:24e3,vadEnabled:!0,vadThreshold:.5,turnDetection:"server_vad"}}}),HG,Z_,QRr=E({"src/lib/types/voice.ts"(){"use strict";XRr(),YRr(),ZRr(),HG={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"},Z_={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]}}}}),e4r=E({"src/lib/types/utilities.ts"(){"use strict"}}),Sd,t4r=E({"src/lib/types/workflow.ts"(){"use strict";Sd=class xEr extends Error{details;constructor(t,r){super(t),this.name="WorkflowError",this.details=r,"captureStackTrace"in Error&&typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,xEr)}}}}),r4r=E({"src/lib/types/ioProcessor.ts"(){"use strict"}}),n4r=E({"src/lib/types/exporter.ts"(){"use strict"}}),WG,KG,Cbe,Ibe,o4r=E({"src/lib/types/span.ts"(){"use strict";WG=(e=>(e.AGENT_RUN="agent.run",e.WORKFLOW_STEP="workflow.step",e.TOOL_CALL="tool.call",e.MODEL_GENERATION="model.generation",e.MODEL_DECISION="model.decision",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))(WG||{}),KG=(e=>(e[e.UNSET=0]="UNSET",e[e.OK=1]="OK",e[e.ERROR=2]="ERROR",e[e.WARNING=3]="WARNING",e))(KG||{}),Cbe={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"},Ibe={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"}}}),JG,i4r=E({"src/lib/types/imageGen.ts"(){"use strict";JG={enabled:!0,defaultModel:"imagen-3.0-generate-001",defaultProvider:"vertex",defaultRegion:"global",timeout:12e4,defaultTemperature:.75,maxImages:4,maxReferenceImages:5,maxReferencePdfs:1}}}),s4r=E({"src/lib/types/elicitation.ts"(){"use strict"}}),a4r=E({"src/lib/types/dynamic.ts"(){"use strict"}}),l4r=E({"src/lib/types/streamDedup.ts"(){"use strict"}}),c4r=E({"src/lib/types/noOutputSentinel.ts"(){"use strict"}}),u4r=E({"src/lib/types/video.ts"(){"use strict"}}),Rbe,d4r=E({"src/lib/types/avatar.ts"(){"use strict";Rbe=["mp4","webm","mov"]}}),Pbe,p4r=E({"src/lib/types/music.ts"(){"use strict";Pbe=["mp3","wav","flac","ogg"]}}),m4r=E({"src/lib/types/replicate.ts"(){"use strict"}}),h4r=E({"src/lib/types/mediaCatalog.ts"(){"use strict"}}),f4r=E({"src/lib/types/safeFetch.ts"(){"use strict"}}),g4r=E({"src/lib/types/modelPool.ts"(){"use strict"}}),y4r=E({"src/lib/types/requestRouter.ts"(){"use strict"}}),v4r=E({"src/lib/types/classifierRouter.ts"(){"use strict"}}),w4r=E({"src/lib/types/agentNetwork.ts"(){"use strict"}}),T4r=E({"src/lib/types/localUsage.ts"(){"use strict"}}),b4r=E({"src/lib/types/dispatch.ts"(){"use strict"}}),_4r=E({"src/lib/types/proxyRestart.ts"(){"use strict"}}),E4r=E({"src/lib/types/proxyBudget.ts"(){"use strict"}}),S4r=E({"src/lib/types/decision.ts"(){"use strict"}}),pt=E({"src/lib/types/index.ts"(){"use strict";Jkr(),Xkr(),Ykr(),Kxr(),Jxr(),Xxr(),Yxr(),Zxr(),Qxr(),eAr(),nAr(),oAr(),iAr(),aAr(),LAr(),FAr(),$Ar(),UAr(),BAr(),zAr(),GAr(),qAr(),VAr(),jAr(),HAr(),WAr(),KAr(),JAr(),XAr(),YAr(),ZAr(),QAr(),eCr(),tCr(),rCr(),nCr(),oCr(),iCr(),sCr(),aCr(),lCr(),cCr(),oRr(),pRr(),mRr(),hRr(),fRr(),vRr(),wRr(),TRr(),bRr(),ERr(),SRr(),kRr(),xRr(),ARr(),CRr(),IRr(),RRr(),PRr(),MRr(),ORr(),DRr(),NRr(),LRr(),FRr(),$Rr(),URr(),BRr(),zRr(),GRr(),jRr(),HRr(),WRr(),QRr(),e4r(),t4r(),r4r(),n4r(),o4r(),i4r(),s4r(),a4r(),l4r(),c4r(),u4r(),d4r(),p4r(),m4r(),h4r(),f4r(),g4r(),y4r(),v4r(),w4r(),T4r(),b4r(),_4r(),E4r(),S4r()}});async function It(e,t,r){let n;const o=new Promise((i,s)=>{n=setTimeout(()=>{s(new ku(r||`Operation timed out after ${t}ms`,t))},t)});try{return await Promise.race([e,o])}finally{n!==void 0&&clearTimeout(n)}}async function Su(e,t){if(!t||typeof t.addEventListener!="function")return e;const r=()=>{const n=new Error("Operation aborted");return n.name="AbortError",n};return t.aborted?(e.catch(()=>{}),Promise.reject(r())):new Promise((n,o)=>{const i=()=>{e.catch(()=>{}),o(r())};t.addEventListener("abort",i,{once:!0}),e.then(s=>{t.removeEventListener("abort",i),n(s)},s=>{t.removeEventListener("abort",i),o(s)})})}async function w4(e,t,r){return It(e(),t,r)}var ku,Kr=E({"src/lib/utils/async/withTimeout.ts"(){"use strict";ku=class AEr extends Error{constructor(t,r){super(t),this.timeoutMs=r,this.name="TimeoutError",Error.captureStackTrace&&Error.captureStackTrace(this,AEr)}timeoutMs}}});function kc(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 k4r(e,t="generate"){if(t==="stream")return b4.streaming;const r=e.toLowerCase().replace("_","-");return b4.providers[r]||b4.global}async function x4r(e,t,r,n){const o=kc(t);if(!o)return e;let i;const s=new Promise((a,l)=>{const c=setTimeout(()=>{l(new Ta(`${r} ${n} operation timed out after ${o}ms`,o,r,n))},o);i=c,typeof c=="object"&&c&&"unref"in c&&typeof c.unref=="function"&&c.unref()});try{return await Promise.race([e,s])}finally{i!==void 0&&clearTimeout(i)}}function wa(e,t,r){const n=kc(e);if(!n)return null;const o=new AbortController,i=()=>{o.abort(new Ta(`${t} ${r} operation timed out after ${e}`,n,t,r))};let s=setTimeout(i,n);return{controller:o,cleanup:()=>{clearTimeout(s)},reset:()=>{o.signal.aborted||(clearTimeout(s),s=setTimeout(i,n))},timeoutMs:n}}function Cy(e,t){return e&&t?AbortSignal.any([e,t]):e??t}function T4(e,t){if(!e||!t)return{signal:e??t,dispose:()=>{}};const r=new AbortController,n=[e,t],o=[],i=()=>{for(const{source:a,listener:l}of o)a.removeEventListener("abort",l);o.length=0},s=a=>{r.signal.aborted||r.abort(a.reason),i()};for(const a of n){const l=()=>s(a);a.addEventListener("abort",l,{once:!0}),o.push({source:a,listener:l})}for(const a of n)if(a.aborted){s(a);break}return{signal:r.signal,dispose:i}}function Mbe(e){const t=new AbortController,r=e.filter(i=>i!==void 0),n=r.find(i=>i.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 Ta,b4,Ys=E({"src/lib/utils/timeout.ts"(){"use strict";Kr(),Ta=class CEr extends ku{constructor(t,r,n,o){super(t,r),this.timeout=r,this.provider=n,this.operation=o,this.name="TimeoutError",typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,CEr)}timeout;provider;operation},b4={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"}}}}),_4,Q_,eE,tE,E4=E({"src/lib/hitl/hitlErrors.ts"(){"use strict";_4=class extends Error{constructor(e,t){super(e),this.confirmationId=t,this.name="HITLError"}confirmationId},Q_=class extends _4{constructor(e,t,r,n){super(e,n),this.toolName=t,this.reason=r,this.name="HITLUserRejectedError"}toolName;reason},eE=class extends _4{constructor(e,t,r){super(e,t),this.timeout=r,this.name="HITLTimeoutError"}timeout},tE=class extends _4{constructor(e){super(e),this.name="HITLConfigurationError"}}}}),rE={};Z(rE,{CircuitBreaker:()=>k4,ERROR_CODES:()=>He,ErrorFactory:()=>he,NeuroLinkError:()=>De,isAbortError:()=>pr,isRecoverableError:()=>S4,isRetriableError:()=>XG,logStructuredError:()=>Dbe,withRetry:()=>Obe,withTimeout:()=>ze});async function ze(e,t,r){let n;const o=new Promise((i,s)=>{n=setTimeout(()=>{s(r||new Error(`Operation timed out after ${t}ms`))},t)});try{return await Promise.race([e,o])}finally{clearTimeout(n)}}async function Obe(e,t){const{maxAttempts:r,delayMs:n,isRetriable:o=()=>!0,onRetry:i}=t;let s;for(let a=1;a<=r;a++)try{return await e()}catch(l){if(s=l instanceof Error?l:new Error(String(l)),a===r||!o(s))throw s;i&&i(a,s),await new Promise(c=>setTimeout(c,n))}throw s||new Error("Retry operation failed with no error information")}function pr(e){return!!(e instanceof DOMException&&e.name==="AbortError"||e instanceof Error&&e.name==="AbortError"||e instanceof De&&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 XG(e){return e instanceof De?e.retriable:e instanceof eE?!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 S4(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 Dbe(e,t){const r={...e.toJSON(),...t};switch(e.severity){case"critical":h.error(`[CRITICAL] ${e.message}`,r);break;case"high":h.error(`[HIGH] ${e.message}`,r);break;case"medium":h.warn(`[MEDIUM] ${e.message}`,r);break;case"low":h.info(`[LOW] ${e.message}`,r);break}}var He,De,he,k4,et=E({"src/lib/utils/errorHandling.ts"(){"use strict";z(),pt(),E4(),He={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"},De=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}}},he=class{static toolNotFound(e,t){return new De({code:He.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 De({code:He.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 De({code:He.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 De({code:He.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 De({code:He.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 De({code:He.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 De({code:He.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 De({code:He.MISSING_CONFIGURATION,message:`Missing required configuration: ${e}`,category:"validation",severity:"high",retriable:!1,context:t||{}})}static invalidConfiguration(e,t,r){return new De({code:He.INVALID_CONFIGURATION,message:`Invalid configuration for '${e}': ${t}`,category:"validation",severity:"high",retriable:!1,context:r||{}})}static csvInvalidInput(e){return new De({code:He.CSV_INVALID_INPUT,message:e,category:"validation",severity:"medium",retriable:!1,context:{}})}static csvRowInvalid(e,t){return new De({code:He.CSV_ROW_INVALID,message:e,category:"validation",severity:"medium",retriable:!1,context:{rowNumber:t}})}static csvFileAccessFailed(e,t,r){return new De({code:He.CSV_FILE_ACCESS_FAILED,message:e,category:"resource",severity:"high",retriable:!1,context:{filePath:t},originalError:r})}static csvParseFailed(e,t,r){return new De({code:He.CSV_PARSE_FAILED,message:e,category:"execution",severity:"medium",retriable:!1,context:t,originalError:r})}static invalidVideoResolution(e){return new De({code:He.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 De({code:He.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 De({code:He.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 De({code:He.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 De({code:He.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 De({code:He.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 De({code:He.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 De({code:He.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 De({code:He.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 De({code:He.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 De({code:He.PDF_PAGE_LIMIT_EXCEEDED,message:`PDF page limit exceeded: ${e} pages detected, but ${r} supports maximum ${t} pages.
|
|
62
|
+
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const s of e.seen.entries()){const a=s[1];if(t===s[0]){i(s);continue}if(e.external){const c=e.external.registry.get(s[0])?.id;if(t!==s[0]&&c){i(s);continue}}if(e.metadataRegistry.get(s[0])?.id){i(s);continue}if(a.cycle){i(s);continue}if(a.count>1&&e.reused==="ref"){i(s);continue}}}function gy(e,t){const r=e.seen.get(t);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");const n=s=>{const a=e.seen.get(s);if(a.ref===null)return;const l=a.def??a.schema,c={...l},u=a.ref;if(a.ref=null,u){n(u);const p=e.seen.get(u),m=p.schema;if(m.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0")?(l.allOf=l.allOf??[],l.allOf.push(m)):Object.assign(l,m),Object.assign(l,c),s._zod.parent===u)for(const g in l)g==="$ref"||g==="allOf"||g in c||delete l[g];if(m.$ref&&p.def)for(const g in l)g==="$ref"||g==="allOf"||g in p.def&&JSON.stringify(l[g])===JSON.stringify(p.def[g])&&delete l[g]}const d=s._zod.parent;if(d&&d!==u){n(d);const p=e.seen.get(d);if(p?.schema.$ref&&(l.$ref=p.schema.$ref,p.def))for(const m in l)m==="$ref"||m==="allOf"||m in p.def&&JSON.stringify(l[m])===JSON.stringify(p.def[m])&&delete l[m]}e.override({zodSchema:s,jsonSchema:l,path:a.path??[]})};for(const s of[...e.seen.entries()].reverse())n(s[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 s=e.external.registry.get(t)?.id;if(!s)throw new Error("Schema is missing an `id` property");o.$id=e.external.uri(s)}Object.assign(o,r.def??r.schema);const i=e.external?.defs??{};for(const s of e.seen.entries()){const a=s[1];a.def&&a.defId&&(i[a.defId]=a.def)}e.external||Object.keys(i).length>0&&(e.target==="draft-2020-12"?o.$defs=i:o.definitions=i);try{const s=JSON.parse(JSON.stringify(o));return Object.defineProperty(s,"~standard",{value:{...t["~standard"],jsonSchema:{input:yy(t,"input",e.processors),output:yy(t,"output",e.processors)}},enumerable:!1,writable:!1}),s}catch{throw new Error("Error converting schema to JSON.")}}function Xs(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 Xs(n.element,r);if(n.type==="set")return Xs(n.valueType,r);if(n.type==="lazy")return Xs(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 Xs(n.innerType,r);if(n.type==="intersection")return Xs(n.left,r)||Xs(n.right,r);if(n.type==="record"||n.type==="map")return Xs(n.keyType,r)||Xs(n.valueType,r);if(n.type==="pipe")return Xs(n.in,r)||Xs(n.out,r);if(n.type==="object"){for(const o in n.shape)if(Xs(n.shape[o],r))return!0;return!1}if(n.type==="union"){for(const o of n.options)if(Xs(o,r))return!0;return!1}if(n.type==="tuple"){for(const o of n.items)if(Xs(o,r))return!0;return!!(n.rest&&Xs(n.rest,r))}return!1}var Tz,yy,bR=E({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/to-json-schema.js"(){sR(),Tz=(e,t={})=>r=>{const n=hy({...r,processors:t});return sn(e,n),fy(n,e),gy(n,e)},yy=(e,t,r={})=>n=>{const{libraryOptions:o,target:i}=n??{},s=hy({...o??{},target:i,io:t,processors:r});return sn(e,s),fy(s,e),gy(s,e)}}});function _R(e,t){if("_idmap"in e){const n=e,o=hy({...t,processors:kR}),i={};for(const l of n._idmap.entries()){const[c,u]=l;sn(u,o)}const s={},a={registry:n,uri:t?.uri,defs:i};o.external=a;for(const l of n._idmap.entries()){const[c,u]=l;fy(o,u),s[c]=gy(o,u)}if(Object.keys(i).length>0){const l=o.target==="draft-2020-12"?"$defs":"definitions";s.__shared={[l]:i}}return{schemas:s}}const r=hy({...t,processors:kR});return sn(e,r),fy(r,e),gy(r,e)}var Jwe,bz,_z,Ez,Sz,kz,xz,Az,Cz,Iz,Rz,Pz,Mz,Oz,Dz,Nz,Lz,Fz,$z,Uz,Bz,zz,Gz,qz,Vz,jz,ER,Hz,Wz,Kz,Jz,Xz,Yz,Zz,Qz,eG,tG,rG,SR,nG,kR,__=E({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/json-schema-processors.js"(){bR(),Et(),Jwe={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},bz=(e,t,r,n)=>{const o=r;o.type="string";const{minimum:i,maximum:s,format:a,patterns:l,contentEncoding:c}=e._zod.bag;if(typeof i=="number"&&(o.minLength=i),typeof s=="number"&&(o.maxLength=s),a&&(o.format=Jwe[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}))])}},_z=(e,t,r,n)=>{const o=r,{minimum:i,maximum:s,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 i=="number"&&(o.minimum=i,typeof u=="number"&&t.target!=="draft-04"&&(u>=i?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 s=="number"&&(o.maximum=s,typeof c=="number"&&t.target!=="draft-04"&&(c<=s?delete o.maximum:delete o.exclusiveMaximum)),typeof l=="number"&&(o.multipleOf=l)},Ez=(e,t,r,n)=>{r.type="boolean"},Sz=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema")},kz=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw new Error("Symbols cannot be represented in JSON Schema")},xz=(e,t,r,n)=>{t.target==="openapi-3.0"?(r.type="string",r.nullable=!0,r.enum=[null]):r.type="null"},Az=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw new Error("Undefined cannot be represented in JSON Schema")},Cz=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw new Error("Void cannot be represented in JSON Schema")},Iz=(e,t,r,n)=>{r.not={}},Rz=(e,t,r,n)=>{},Pz=(e,t,r,n)=>{},Mz=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema")},Oz=(e,t,r,n)=>{const o=e._zod.def,i=S5(o.entries);i.every(s=>typeof s=="number")&&(r.type="number"),i.every(s=>typeof s=="string")&&(r.type="string"),r.enum=i},Dz=(e,t,r,n)=>{const o=e._zod.def,i=[];for(const s of o.values)if(s===void 0){if(t.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof s=="bigint"){if(t.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");i.push(Number(s))}else i.push(s);if(i.length!==0)if(i.length===1){const s=i[0];r.type=s===null?"null":typeof s,t.target==="draft-04"||t.target==="openapi-3.0"?r.enum=[s]:r.const=s}else i.every(s=>typeof s=="number")&&(r.type="number"),i.every(s=>typeof s=="string")&&(r.type="string"),i.every(s=>typeof s=="boolean")&&(r.type="boolean"),i.every(s=>s===null)&&(r.type="null"),r.enum=i},Nz=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema")},Lz=(e,t,r,n)=>{const o=r,i=e._zod.pattern;if(!i)throw new Error("Pattern not found in template literal");o.type="string",o.pattern=i.source},Fz=(e,t,r,n)=>{const o=r,i={type:"string",format:"binary",contentEncoding:"binary"},{minimum:s,maximum:a,mime:l}=e._zod.bag;s!==void 0&&(i.minLength=s),a!==void 0&&(i.maxLength=a),l?l.length===1?(i.contentMediaType=l[0],Object.assign(o,i)):(Object.assign(o,i),o.anyOf=l.map(c=>({contentMediaType:c}))):Object.assign(o,i)},$z=(e,t,r,n)=>{r.type="boolean"},Uz=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")},Bz=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw new Error("Function types cannot be represented in JSON Schema")},zz=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")},Gz=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw new Error("Map cannot be represented in JSON Schema")},qz=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw new Error("Set cannot be represented in JSON Schema")},Vz=(e,t,r,n)=>{const o=r,i=e._zod.def,{minimum:s,maximum:a}=e._zod.bag;typeof s=="number"&&(o.minItems=s),typeof a=="number"&&(o.maxItems=a),o.type="array",o.items=sn(i.element,t,{...n,path:[...n.path,"items"]})},jz=(e,t,r,n)=>{const o=r,i=e._zod.def;o.type="object",o.properties={};const s=i.shape;for(const c in s)o.properties[c]=sn(s[c],t,{...n,path:[...n.path,"properties",c]});const a=new Set(Object.keys(s)),l=new Set([...a].filter(c=>{const u=i.shape[c]._zod;return t.io==="input"?u.optin===void 0:u.optout===void 0}));l.size>0&&(o.required=Array.from(l)),i.catchall?._zod.def.type==="never"?o.additionalProperties=!1:i.catchall?i.catchall&&(o.additionalProperties=sn(i.catchall,t,{...n,path:[...n.path,"additionalProperties"]})):t.io==="output"&&(o.additionalProperties=!1)},ER=(e,t,r,n)=>{const o=e._zod.def,i=o.inclusive===!1,s=o.options.map((a,l)=>sn(a,t,{...n,path:[...n.path,i?"oneOf":"anyOf",l]}));i?r.oneOf=s:r.anyOf=s},Hz=(e,t,r,n)=>{const o=e._zod.def,i=sn(o.left,t,{...n,path:[...n.path,"allOf",0]}),s=sn(o.right,t,{...n,path:[...n.path,"allOf",1]}),a=c=>"allOf"in c&&Object.keys(c).length===1,l=[...a(i)?i.allOf:[i],...a(s)?s.allOf:[s]];r.allOf=l},Wz=(e,t,r,n)=>{const o=r,i=e._zod.def;o.type="array";const s=t.target==="draft-2020-12"?"prefixItems":"items",a=t.target==="draft-2020-12"||t.target==="openapi-3.0"?"items":"additionalItems",l=i.items.map((p,m)=>sn(p,t,{...n,path:[...n.path,s,m]})),c=i.rest?sn(i.rest,t,{...n,path:[...n.path,a,...t.target==="openapi-3.0"?[i.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)},Kz=(e,t,r,n)=>{const o=r,i=e._zod.def;o.type="object";const s=i.keyType,l=s._zod.bag?.patterns;if(i.mode==="loose"&&l&&l.size>0){const u=sn(i.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=sn(i.keyType,t,{...n,path:[...n.path,"propertyNames"]})),o.additionalProperties=sn(i.valueType,t,{...n,path:[...n.path,"additionalProperties"]});const c=s._zod.values;if(c){const u=[...c].filter(d=>typeof d=="string"||typeof d=="number");u.length>0&&(o.required=u)}},Jz=(e,t,r,n)=>{const o=e._zod.def,i=sn(o.innerType,t,n),s=t.seen.get(e);t.target==="openapi-3.0"?(s.ref=o.innerType,r.nullable=!0):r.anyOf=[i,{type:"null"}]},Xz=(e,t,r,n)=>{const o=e._zod.def;sn(o.innerType,t,n);const i=t.seen.get(e);i.ref=o.innerType},Yz=(e,t,r,n)=>{const o=e._zod.def;sn(o.innerType,t,n);const i=t.seen.get(e);i.ref=o.innerType,r.default=JSON.parse(JSON.stringify(o.defaultValue))},Zz=(e,t,r,n)=>{const o=e._zod.def;sn(o.innerType,t,n);const i=t.seen.get(e);i.ref=o.innerType,t.io==="input"&&(r._prefault=JSON.parse(JSON.stringify(o.defaultValue)))},Qz=(e,t,r,n)=>{const o=e._zod.def;sn(o.innerType,t,n);const i=t.seen.get(e);i.ref=o.innerType;let s;try{s=o.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}r.default=s},eG=(e,t,r,n)=>{const o=e._zod.def,i=t.io==="input"?o.in._zod.def.type==="transform"?o.out:o.in:o.out;sn(i,t,n);const s=t.seen.get(e);s.ref=i},tG=(e,t,r,n)=>{const o=e._zod.def;sn(o.innerType,t,n);const i=t.seen.get(e);i.ref=o.innerType,r.readOnly=!0},rG=(e,t,r,n)=>{const o=e._zod.def;sn(o.innerType,t,n);const i=t.seen.get(e);i.ref=o.innerType},SR=(e,t,r,n)=>{const o=e._zod.def;sn(o.innerType,t,n);const i=t.seen.get(e);i.ref=o.innerType},nG=(e,t,r,n)=>{const o=e._zod.innerType;sn(o,t,n);const i=t.seen.get(e);i.ref=o},kR={string:bz,number:_z,boolean:Ez,bigint:Sz,symbol:kz,null:xz,undefined:Az,void:Cz,never:Iz,any:Rz,unknown:Pz,date:Mz,enum:Oz,literal:Dz,nan:Nz,template_literal:Lz,file:Fz,success:$z,custom:Uz,function:Bz,transform:zz,map:Gz,set:qz,array:Vz,object:jz,union:ER,intersection:Hz,tuple:Wz,record:Kz,nullable:Jz,nonoptional:Xz,default:Yz,prefault:Zz,catch:Qz,pipe:eG,readonly:tG,promise:rG,optional:SR,lazy:nG}}}),Xwe,GIr=E({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/json-schema-generator.js"(){__(),bR(),Xwe=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=hy({processors:kR,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 sn(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)),fy(this.ctx,e);const r=gy(this.ctx,e),{"~standard":n,...o}=r;return o}}}}),qIr={},VIr=E({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/json-schema.js"(){}}),Ywe={};Z(Ywe,{$ZodAny:()=>cB,$ZodArray:()=>hB,$ZodAsyncError:()=>Xp,$ZodBase64:()=>QU,$ZodBase64URL:()=>eB,$ZodBigInt:()=>rR,$ZodBigIntFormat:()=>iB,$ZodBoolean:()=>tR,$ZodCIDRv4:()=>YU,$ZodCIDRv6:()=>ZU,$ZodCUID:()=>UU,$ZodCUID2:()=>BU,$ZodCatch:()=>OB,$ZodCheck:()=>to,$ZodCheckBigIntFormat:()=>pU,$ZodCheckEndsWith:()=>SU,$ZodCheckGreaterThan:()=>KI,$ZodCheckIncludes:()=>_U,$ZodCheckLengthEquals:()=>vU,$ZodCheckLessThan:()=>WI,$ZodCheckLowerCase:()=>TU,$ZodCheckMaxLength:()=>gU,$ZodCheckMaxSize:()=>mU,$ZodCheckMimeType:()=>xU,$ZodCheckMinLength:()=>yU,$ZodCheckMinSize:()=>hU,$ZodCheckMultipleOf:()=>uU,$ZodCheckNumberFormat:()=>dU,$ZodCheckOverwrite:()=>AU,$ZodCheckProperty:()=>kU,$ZodCheckRegex:()=>wU,$ZodCheckSizeEquals:()=>fU,$ZodCheckStartsWith:()=>EU,$ZodCheckStringFormat:()=>ly,$ZodCheckUpperCase:()=>bU,$ZodCodec:()=>iR,$ZodCustom:()=>zB,$ZodCustomStringFormat:()=>nB,$ZodDate:()=>mB,$ZodDefault:()=>IB,$ZodDiscriminatedUnion:()=>vB,$ZodE164:()=>tB,$ZodEmail:()=>NU,$ZodEmoji:()=>FU,$ZodEncodeError:()=>c_,$ZodEnum:()=>EB,$ZodError:()=>OI,$ZodExactOptional:()=>AB,$ZodFile:()=>kB,$ZodFunction:()=>$B,$ZodGUID:()=>OU,$ZodIPv4:()=>KU,$ZodIPv6:()=>JU,$ZodISODate:()=>jU,$ZodISODateTime:()=>VU,$ZodISODuration:()=>WU,$ZodISOTime:()=>HU,$ZodIntersection:()=>wB,$ZodJWT:()=>rB,$ZodKSUID:()=>qU,$ZodLazy:()=>BB,$ZodLiteral:()=>SB,$ZodMAC:()=>XU,$ZodMap:()=>bB,$ZodNaN:()=>DB,$ZodNanoID:()=>$U,$ZodNever:()=>dB,$ZodNonOptional:()=>PB,$ZodNull:()=>lB,$ZodNullable:()=>CB,$ZodNumber:()=>eR,$ZodNumberFormat:()=>oB,$ZodObject:()=>fB,$ZodObjectJIT:()=>gB,$ZodOptional:()=>oR,$ZodPipe:()=>NB,$ZodPrefault:()=>RB,$ZodPromise:()=>UB,$ZodReadonly:()=>LB,$ZodRealError:()=>ga,$ZodRecord:()=>TB,$ZodRegistry:()=>WB,$ZodSet:()=>_B,$ZodString:()=>cy,$ZodStringFormat:()=>on,$ZodSuccess:()=>MB,$ZodSymbol:()=>sB,$ZodTemplateLiteral:()=>FB,$ZodTransform:()=>xB,$ZodTuple:()=>nR,$ZodType:()=>zt,$ZodULID:()=>zU,$ZodURL:()=>LU,$ZodUUID:()=>DU,$ZodUndefined:()=>aB,$ZodUnion:()=>y_,$ZodUnknown:()=>uB,$ZodVoid:()=>pB,$ZodXID:()=>GU,$ZodXor:()=>yB,$brand:()=>E5,$constructor:()=>fe,$input:()=>HB,$output:()=>jB,Doc:()=>IU,JSONSchema:()=>qIr,JSONSchemaGenerator:()=>Xwe,NEVER:()=>xI,TimePrecision:()=>wz,_any:()=>Owe,_array:()=>Bwe,_base64:()=>uz,_base64url:()=>dz,_bigint:()=>xwe,_boolean:()=>Swe,_catch:()=>NIr,_check:()=>jwe,_cidrv4:()=>lz,_cidrv6:()=>cz,_coercedBigint:()=>Awe,_coercedBoolean:()=>kwe,_coercedDate:()=>$we,_coercedNumber:()=>vwe,_coercedString:()=>dwe,_cuid:()=>tz,_cuid2:()=>rz,_custom:()=>Gwe,_date:()=>Fwe,_decode:()=>$I,_decodeAsync:()=>BI,_default:()=>MIr,_discriminatedUnion:()=>TIr,_e164:()=>pz,_email:()=>KB,_emoji:()=>QB,_encode:()=>FI,_encodeAsync:()=>UI,_endsWith:()=>hR,_enum:()=>xIr,_file:()=>zwe,_float32:()=>Twe,_float64:()=>bwe,_gt:()=>Qp,_gte:()=>ya,_guid:()=>aR,_includes:()=>pR,_int:()=>wwe,_int32:()=>_we,_int64:()=>Cwe,_intersection:()=>bIr,_ipv4:()=>sz,_ipv6:()=>az,_isoDate:()=>hwe,_isoDateTime:()=>mwe,_isoDuration:()=>gwe,_isoTime:()=>fwe,_jwt:()=>mz,_ksuid:()=>iz,_lazy:()=>UIr,_length:()=>T_,_literal:()=>CIr,_lowercase:()=>uR,_lt:()=>Zp,_lte:()=>Nl,_mac:()=>pwe,_map:()=>SIr,_max:()=>Nl,_maxLength:()=>w_,_maxSize:()=>my,_mime:()=>fR,_min:()=>ya,_minLength:()=>Vh,_minSize:()=>em,_multipleOf:()=>py,_nan:()=>Uwe,_nanoid:()=>ez,_nativeEnum:()=>AIr,_negative:()=>fz,_never:()=>Nwe,_nonnegative:()=>yz,_nonoptional:()=>OIr,_nonpositive:()=>gz,_normalize:()=>gR,_null:()=>Mwe,_nullable:()=>PIr,_number:()=>ywe,_optional:()=>RIr,_overwrite:()=>Ed,_parse:()=>oy,_parseAsync:()=>iy,_pipe:()=>LIr,_positive:()=>hz,_promise:()=>BIr,_property:()=>vz,_readonly:()=>FIr,_record:()=>EIr,_refine:()=>qwe,_regex:()=>cR,_safeDecode:()=>GI,_safeDecodeAsync:()=>VI,_safeEncode:()=>zI,_safeEncodeAsync:()=>qI,_safeParse:()=>sy,_safeParseAsync:()=>ay,_set:()=>kIr,_size:()=>v_,_slugify:()=>TR,_startsWith:()=>mR,_string:()=>uwe,_stringFormat:()=>b_,_stringbool:()=>Kwe,_success:()=>DIr,_superRefine:()=>Vwe,_symbol:()=>Rwe,_templateLiteral:()=>$Ir,_toLowerCase:()=>vR,_toUpperCase:()=>wR,_transform:()=>IIr,_trim:()=>yR,_tuple:()=>_Ir,_uint32:()=>Ewe,_uint64:()=>Iwe,_ulid:()=>nz,_undefined:()=>Pwe,_union:()=>vIr,_unknown:()=>Dwe,_uppercase:()=>dR,_url:()=>lR,_uuid:()=>JB,_uuidv4:()=>XB,_uuidv6:()=>YB,_uuidv7:()=>ZB,_void:()=>Lwe,_xid:()=>oz,_xor:()=>wIr,clone:()=>Ol,config:()=>Is,createStandardJSONSchemaMethod:()=>yy,createToJSONSchemaMethod:()=>Tz,decode:()=>rye,decodeAsync:()=>oye,describe:()=>Hwe,encode:()=>tye,encodeAsync:()=>nye,extractDefs:()=>fy,finalize:()=>gy,flattenError:()=>P5,formatError:()=>M5,globalConfig:()=>u_,globalRegistry:()=>Za,initializeContext:()=>hy,isValidBase64:()=>PU,isValidBase64URL:()=>Vye,isValidJWT:()=>jye,locales:()=>GB,meta:()=>Wwe,parse:()=>DI,parseAsync:()=>NI,prettifyError:()=>Q0e,process:()=>sn,regexes:()=>Gh,registry:()=>VB,safeDecode:()=>sye,safeDecodeAsync:()=>lye,safeEncode:()=>iye,safeEncodeAsync:()=>aye,safeParse:()=>LI,safeParseAsync:()=>D5,toDotPath:()=>Z0e,toJSONSchema:()=>_R,treeifyError:()=>Y0e,util:()=>vr,version:()=>RU});var gi=E({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/index.js"(){d_(),cye(),eye(),ive(),CU(),qye(),Et(),lU(),qB(),sR(),Gye(),zIr(),bR(),__(),GIr(),VIr()}}),Zwe={};Z(Zwe,{endsWith:()=>hR,gt:()=>Qp,gte:()=>ya,includes:()=>pR,length:()=>T_,lowercase:()=>uR,lt:()=>Zp,lte:()=>Nl,maxLength:()=>w_,maxSize:()=>my,mime:()=>fR,minLength:()=>Vh,minSize:()=>em,multipleOf:()=>py,negative:()=>fz,nonnegative:()=>yz,nonpositive:()=>gz,normalize:()=>gR,overwrite:()=>Ed,positive:()=>hz,property:()=>vz,regex:()=>cR,size:()=>v_,slugify:()=>TR,startsWith:()=>mR,toLowerCase:()=>vR,toUpperCase:()=>wR,trim:()=>yR,uppercase:()=>dR});var oG=E({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/checks.js"(){gi()}}),xR={};Z(xR,{ZodISODate:()=>CR,ZodISODateTime:()=>AR,ZodISODuration:()=>RR,ZodISOTime:()=>IR,date:()=>eTe,datetime:()=>Qwe,duration:()=>rTe,time:()=>tTe});function Qwe(e){return mwe(AR,e)}function eTe(e){return hwe(CR,e)}function tTe(e){return fwe(IR,e)}function rTe(e){return gwe(RR,e)}var AR,CR,IR,RR,PR=E({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/iso.js"(){gi(),h4(),AR=fe("ZodISODateTime",(e,t)=>{VU.init(e,t),cn.init(e,t)}),CR=fe("ZodISODate",(e,t)=>{jU.init(e,t),cn.init(e,t)}),IR=fe("ZodISOTime",(e,t)=>{HU.init(e,t),cn.init(e,t)}),RR=fe("ZodISODuration",(e,t)=>{WU.init(e,t),cn.init(e,t)})}}),iG,nTe,va,oTe=E({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/errors.js"(){gi(),gi(),Et(),iG=(e,t)=>{OI.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:r=>M5(e,r)},flatten:{value:r=>P5(e,r)},addIssue:{value:r=>{e.issues.push(r),e.message=JSON.stringify(e.issues,AI,2)}},addIssues:{value:r=>{e.issues.push(...r),e.message=JSON.stringify(e.issues,AI,2)}},isEmpty:{get(){return e.issues.length===0}}})},nTe=fe("ZodError",iG),va=fe("ZodError",iG,{Parent:Error})}}),sG,aG,lG,cG,uG,dG,pG,mG,hG,fG,gG,yG,iTe=E({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/parse.js"(){gi(),oTe(),sG=oy(va),aG=iy(va),lG=sy(va),cG=ay(va),uG=FI(va),dG=$I(va),pG=UI(va),mG=BI(va),hG=zI(va),fG=GI(va),gG=qI(va),yG=VI(va)}}),sTe={};Z(sTe,{ZodAny:()=>GR,ZodArray:()=>HR,ZodBase64:()=>B_,ZodBase64URL:()=>z_,ZodBigInt:()=>Ey,ZodBigIntFormat:()=>V_,ZodBoolean:()=>_y,ZodCIDRv4:()=>$_,ZodCIDRv6:()=>U_,ZodCUID:()=>P_,ZodCUID2:()=>M_,ZodCatch:()=>a4,ZodCodec:()=>J_,ZodCustom:()=>Ay,ZodCustomStringFormat:()=>jh,ZodDate:()=>j_,ZodDefault:()=>o4,ZodDiscriminatedUnion:()=>KR,ZodE164:()=>G_,ZodEmail:()=>C_,ZodEmoji:()=>I_,ZodEnum:()=>Hh,ZodExactOptional:()=>r4,ZodFile:()=>e4,ZodFunction:()=>m4,ZodGUID:()=>wy,ZodIPv4:()=>L_,ZodIPv6:()=>F_,ZodIntersection:()=>JR,ZodJWT:()=>q_,ZodKSUID:()=>N_,ZodLazy:()=>d4,ZodLiteral:()=>QR,ZodMAC:()=>$R,ZodMap:()=>YR,ZodNaN:()=>l4,ZodNanoID:()=>R_,ZodNever:()=>VR,ZodNonOptional:()=>W_,ZodNull:()=>zR,ZodNullable:()=>n4,ZodNumber:()=>by,ZodNumberFormat:()=>tm,ZodObject:()=>Sy,ZodOptional:()=>H_,ZodPipe:()=>K_,ZodPrefault:()=>i4,ZodPromise:()=>p4,ZodReadonly:()=>c4,ZodRecord:()=>xy,ZodSet:()=>ZR,ZodString:()=>vy,ZodStringFormat:()=>cn,ZodSuccess:()=>s4,ZodSymbol:()=>UR,ZodTemplateLiteral:()=>u4,ZodTransform:()=>t4,ZodTuple:()=>XR,ZodType:()=>Wt,ZodULID:()=>O_,ZodURL:()=>Ty,ZodUUID:()=>Sc,ZodUndefined:()=>BR,ZodUnion:()=>ky,ZodUnknown:()=>qR,ZodVoid:()=>jR,ZodXID:()=>D_,ZodXor:()=>WR,_ZodString:()=>A_,_default:()=>_G,_function:()=>LR,any:()=>wG,array:()=>Ze,base64:()=>xTe,base64url:()=>ATe,bigint:()=>$Te,boolean:()=>an,catch:()=>kG,check:()=>sbe,cidrv4:()=>STe,cidrv6:()=>kTe,codec:()=>nbe,cuid:()=>gTe,cuid2:()=>yTe,custom:()=>CG,date:()=>VTe,describe:()=>PG,discriminatedUnion:()=>DR,e164:()=>CTe,email:()=>aTe,emoji:()=>hTe,enum:()=>Rs,exactOptional:()=>bG,file:()=>QTe,float32:()=>DTe,float64:()=>NTe,function:()=>LR,guid:()=>lTe,hash:()=>OTe,hex:()=>MTe,hostname:()=>PTe,httpUrl:()=>mTe,instanceof:()=>abe,int:()=>MR,int32:()=>LTe,int64:()=>UTe,intersection:()=>S_,ipv4:()=>bTe,ipv6:()=>ETe,json:()=>lbe,jwt:()=>ITe,keyof:()=>jTe,ksuid:()=>TTe,lazy:()=>AG,literal:()=>wt,looseObject:()=>Ni,looseRecord:()=>JTe,mac:()=>_Te,map:()=>XTe,meta:()=>MG,nan:()=>rbe,nanoid:()=>fTe,nativeEnum:()=>ZTe,never:()=>OR,nonoptional:()=>SG,null:()=>E_,nullable:()=>k_,nullish:()=>ebe,number:()=>Lr,object:()=>rt,optional:()=>ro,partialRecord:()=>KTe,pipe:()=>x_,prefault:()=>EG,preprocess:()=>FR,promise:()=>ibe,readonly:()=>xG,record:()=>Hn,refine:()=>IG,set:()=>YTe,strictObject:()=>HTe,string:()=>ee,stringFormat:()=>RTe,stringbool:()=>OG,success:()=>tbe,superRefine:()=>RG,symbol:()=>zTe,templateLiteral:()=>obe,transform:()=>NR,tuple:()=>TG,uint32:()=>FTe,uint64:()=>BTe,ulid:()=>vTe,undefined:()=>GTe,union:()=>ln,unknown:()=>fn,url:()=>vG,uuid:()=>cTe,uuidv4:()=>uTe,uuidv6:()=>dTe,uuidv7:()=>pTe,void:()=>qTe,xid:()=>wTe,xor:()=>WTe});function ee(e){return uwe(vy,e)}function aTe(e){return KB(C_,e)}function lTe(e){return aR(wy,e)}function cTe(e){return JB(Sc,e)}function uTe(e){return XB(Sc,e)}function dTe(e){return YB(Sc,e)}function pTe(e){return ZB(Sc,e)}function vG(e){return lR(Ty,e)}function mTe(e){return lR(Ty,{protocol:/^https?$/,hostname:Gh.domain,...vr.normalizeParams(e)})}function hTe(e){return QB(I_,e)}function fTe(e){return ez(R_,e)}function gTe(e){return tz(P_,e)}function yTe(e){return rz(M_,e)}function vTe(e){return nz(O_,e)}function wTe(e){return oz(D_,e)}function TTe(e){return iz(N_,e)}function bTe(e){return sz(L_,e)}function _Te(e){return pwe($R,e)}function ETe(e){return az(F_,e)}function STe(e){return lz($_,e)}function kTe(e){return cz(U_,e)}function xTe(e){return uz(B_,e)}function ATe(e){return dz(z_,e)}function CTe(e){return pz(G_,e)}function ITe(e){return mz(q_,e)}function RTe(e,t,r={}){return b_(jh,e,t,r)}function PTe(e){return b_(jh,"hostname",Gh.hostname,e)}function MTe(e){return b_(jh,"hex",Gh.hex,e)}function OTe(e,t){const r=t?.enc??"hex",n=`${e}_${r}`,o=Gh[n];if(!o)throw new Error(`Unrecognized hash format: ${n}`);return b_(jh,n,o,t)}function Lr(e){return ywe(by,e)}function MR(e){return wwe(tm,e)}function DTe(e){return Twe(tm,e)}function NTe(e){return bwe(tm,e)}function LTe(e){return _we(tm,e)}function FTe(e){return Ewe(tm,e)}function an(e){return Swe(_y,e)}function $Te(e){return xwe(Ey,e)}function UTe(e){return Cwe(V_,e)}function BTe(e){return Iwe(V_,e)}function zTe(e){return Rwe(UR,e)}function GTe(e){return Pwe(BR,e)}function E_(e){return Mwe(zR,e)}function wG(){return Owe(GR)}function fn(){return Dwe(qR)}function OR(e){return Nwe(VR,e)}function qTe(e){return Lwe(jR,e)}function VTe(e){return Fwe(j_,e)}function Ze(e,t){return Bwe(HR,e,t)}function jTe(e){const t=e._zod.def.shape;return Rs(Object.keys(t))}function rt(e,t){const r={type:"object",shape:e??{},...vr.normalizeParams(t)};return new Sy(r)}function HTe(e,t){return new Sy({type:"object",shape:e,catchall:OR(),...vr.normalizeParams(t)})}function Ni(e,t){return new Sy({type:"object",shape:e,catchall:fn(),...vr.normalizeParams(t)})}function ln(e,t){return new ky({type:"union",options:e,...vr.normalizeParams(t)})}function WTe(e,t){return new WR({type:"union",options:e,inclusive:!1,...vr.normalizeParams(t)})}function DR(e,t,r){return new KR({type:"union",options:t,discriminator:e,...vr.normalizeParams(r)})}function S_(e,t){return new JR({type:"intersection",left:e,right:t})}function TG(e,t,r){const n=t instanceof zt,o=n?r:t,i=n?t:null;return new XR({type:"tuple",items:e,rest:i,...vr.normalizeParams(o)})}function Hn(e,t,r){return new xy({type:"record",keyType:e,valueType:t,...vr.normalizeParams(r)})}function KTe(e,t,r){const n=Ol(e);return n._zod.values=void 0,new xy({type:"record",keyType:n,valueType:t,...vr.normalizeParams(r)})}function JTe(e,t,r){return new xy({type:"record",keyType:e,valueType:t,mode:"loose",...vr.normalizeParams(r)})}function XTe(e,t,r){return new YR({type:"map",keyType:e,valueType:t,...vr.normalizeParams(r)})}function YTe(e,t){return new ZR({type:"set",valueType:e,...vr.normalizeParams(t)})}function Rs(e,t){const r=Array.isArray(e)?Object.fromEntries(e.map(n=>[n,n])):e;return new Hh({type:"enum",entries:r,...vr.normalizeParams(t)})}function ZTe(e,t){return new Hh({type:"enum",entries:e,...vr.normalizeParams(t)})}function wt(e,t){return new QR({type:"literal",values:Array.isArray(e)?e:[e],...vr.normalizeParams(t)})}function QTe(e){return zwe(e4,e)}function NR(e){return new t4({type:"transform",transform:e})}function ro(e){return new H_({type:"optional",innerType:e})}function bG(e){return new r4({type:"optional",innerType:e})}function k_(e){return new n4({type:"nullable",innerType:e})}function ebe(e){return ro(k_(e))}function _G(e,t){return new o4({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():vr.shallowClone(t)}})}function EG(e,t){return new i4({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():vr.shallowClone(t)}})}function SG(e,t){return new W_({type:"nonoptional",innerType:e,...vr.normalizeParams(t)})}function tbe(e){return new s4({type:"success",innerType:e})}function kG(e,t){return new a4({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}function rbe(e){return Uwe(l4,e)}function x_(e,t){return new K_({type:"pipe",in:e,out:t})}function nbe(e,t,r){return new J_({type:"pipe",in:e,out:t,transform:r.decode,reverseTransform:r.encode})}function xG(e){return new c4({type:"readonly",innerType:e})}function obe(e,t){return new u4({type:"template_literal",parts:e,...vr.normalizeParams(t)})}function AG(e){return new d4({type:"lazy",getter:e})}function ibe(e){return new p4({type:"promise",innerType:e})}function LR(e){return new m4({type:"function",input:Array.isArray(e?.input)?TG(e?.input):e?.input??Ze(fn()),output:e?.output??fn()})}function sbe(e){const t=new to({check:"custom"});return t._zod.check=e,t}function CG(e,t){return Gwe(Ay,e??(()=>!0),t)}function IG(e,t={}){return qwe(Ay,e,t)}function RG(e){return Vwe(e)}function abe(e,t={}){const r=new Ay({type:"custom",check:"custom",fn:n=>n instanceof e,abort:!0,...vr.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 lbe(e){const t=AG(()=>ln([ee(e),Lr(),an(),E_(),Ze(t),Hn(ee(),t)]));return t}function FR(e,t){return x_(NR(e),t)}var Wt,A_,vy,cn,C_,wy,Sc,Ty,I_,R_,P_,M_,O_,D_,N_,L_,$R,F_,$_,U_,B_,z_,G_,q_,jh,by,tm,_y,Ey,V_,UR,BR,zR,GR,qR,VR,jR,j_,HR,Sy,ky,WR,KR,JR,XR,xy,YR,ZR,Hh,QR,e4,t4,H_,r4,n4,o4,i4,W_,s4,a4,l4,K_,J_,c4,u4,d4,p4,m4,Ay,PG,MG,OG,h4=E({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/schemas.js"(){gi(),gi(),__(),bR(),oG(),PR(),iTe(),Wt=fe("ZodType",(e,t)=>(zt.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:yy(e,"input"),output:yy(e,"output")}}),e.toJSONSchema=Tz(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.check=(...r)=>e.clone(vr.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)=>Ol(e,r,n),e.brand=()=>e,e.register=((r,n)=>(r.add(e,n),e)),e.parse=(r,n)=>sG(e,r,n,{callee:e.parse}),e.safeParse=(r,n)=>lG(e,r,n),e.parseAsync=async(r,n)=>aG(e,r,n,{callee:e.parseAsync}),e.safeParseAsync=async(r,n)=>cG(e,r,n),e.spa=e.safeParseAsync,e.encode=(r,n)=>uG(e,r,n),e.decode=(r,n)=>dG(e,r,n),e.encodeAsync=async(r,n)=>pG(e,r,n),e.decodeAsync=async(r,n)=>mG(e,r,n),e.safeEncode=(r,n)=>hG(e,r,n),e.safeDecode=(r,n)=>fG(e,r,n),e.safeEncodeAsync=async(r,n)=>gG(e,r,n),e.safeDecodeAsync=async(r,n)=>yG(e,r,n),e.refine=(r,n)=>e.check(IG(r,n)),e.superRefine=r=>e.check(RG(r)),e.overwrite=r=>e.check(Ed(r)),e.optional=()=>ro(e),e.exactOptional=()=>bG(e),e.nullable=()=>k_(e),e.nullish=()=>ro(k_(e)),e.nonoptional=r=>SG(e,r),e.array=()=>Ze(e),e.or=r=>ln([e,r]),e.and=r=>S_(e,r),e.transform=r=>x_(e,NR(r)),e.default=r=>_G(e,r),e.prefault=r=>EG(e,r),e.catch=r=>kG(e,r),e.pipe=r=>x_(e,r),e.readonly=()=>xG(e),e.describe=r=>{const n=e.clone();return Za.add(n,{description:r}),n},Object.defineProperty(e,"description",{get(){return Za.get(e)?.description},configurable:!0}),e.meta=(...r)=>{if(r.length===0)return Za.get(e);const n=e.clone();return Za.add(n,r[0]),n},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e.apply=r=>r(e),e)),A_=fe("_ZodString",(e,t)=>{cy.init(e,t),Wt.init(e,t),e._zod.processJSONSchema=(n,o,i)=>bz(e,n,o,i);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(cR(...n)),e.includes=(...n)=>e.check(pR(...n)),e.startsWith=(...n)=>e.check(mR(...n)),e.endsWith=(...n)=>e.check(hR(...n)),e.min=(...n)=>e.check(Vh(...n)),e.max=(...n)=>e.check(w_(...n)),e.length=(...n)=>e.check(T_(...n)),e.nonempty=(...n)=>e.check(Vh(1,...n)),e.lowercase=n=>e.check(uR(n)),e.uppercase=n=>e.check(dR(n)),e.trim=()=>e.check(yR()),e.normalize=(...n)=>e.check(gR(...n)),e.toLowerCase=()=>e.check(vR()),e.toUpperCase=()=>e.check(wR()),e.slugify=()=>e.check(TR())}),vy=fe("ZodString",(e,t)=>{cy.init(e,t),A_.init(e,t),e.email=r=>e.check(KB(C_,r)),e.url=r=>e.check(lR(Ty,r)),e.jwt=r=>e.check(mz(q_,r)),e.emoji=r=>e.check(QB(I_,r)),e.guid=r=>e.check(aR(wy,r)),e.uuid=r=>e.check(JB(Sc,r)),e.uuidv4=r=>e.check(XB(Sc,r)),e.uuidv6=r=>e.check(YB(Sc,r)),e.uuidv7=r=>e.check(ZB(Sc,r)),e.nanoid=r=>e.check(ez(R_,r)),e.guid=r=>e.check(aR(wy,r)),e.cuid=r=>e.check(tz(P_,r)),e.cuid2=r=>e.check(rz(M_,r)),e.ulid=r=>e.check(nz(O_,r)),e.base64=r=>e.check(uz(B_,r)),e.base64url=r=>e.check(dz(z_,r)),e.xid=r=>e.check(oz(D_,r)),e.ksuid=r=>e.check(iz(N_,r)),e.ipv4=r=>e.check(sz(L_,r)),e.ipv6=r=>e.check(az(F_,r)),e.cidrv4=r=>e.check(lz($_,r)),e.cidrv6=r=>e.check(cz(U_,r)),e.e164=r=>e.check(pz(G_,r)),e.datetime=r=>e.check(Qwe(r)),e.date=r=>e.check(eTe(r)),e.time=r=>e.check(tTe(r)),e.duration=r=>e.check(rTe(r))}),cn=fe("ZodStringFormat",(e,t)=>{on.init(e,t),A_.init(e,t)}),C_=fe("ZodEmail",(e,t)=>{NU.init(e,t),cn.init(e,t)}),wy=fe("ZodGUID",(e,t)=>{OU.init(e,t),cn.init(e,t)}),Sc=fe("ZodUUID",(e,t)=>{DU.init(e,t),cn.init(e,t)}),Ty=fe("ZodURL",(e,t)=>{LU.init(e,t),cn.init(e,t)}),I_=fe("ZodEmoji",(e,t)=>{FU.init(e,t),cn.init(e,t)}),R_=fe("ZodNanoID",(e,t)=>{$U.init(e,t),cn.init(e,t)}),P_=fe("ZodCUID",(e,t)=>{UU.init(e,t),cn.init(e,t)}),M_=fe("ZodCUID2",(e,t)=>{BU.init(e,t),cn.init(e,t)}),O_=fe("ZodULID",(e,t)=>{zU.init(e,t),cn.init(e,t)}),D_=fe("ZodXID",(e,t)=>{GU.init(e,t),cn.init(e,t)}),N_=fe("ZodKSUID",(e,t)=>{qU.init(e,t),cn.init(e,t)}),L_=fe("ZodIPv4",(e,t)=>{KU.init(e,t),cn.init(e,t)}),$R=fe("ZodMAC",(e,t)=>{XU.init(e,t),cn.init(e,t)}),F_=fe("ZodIPv6",(e,t)=>{JU.init(e,t),cn.init(e,t)}),$_=fe("ZodCIDRv4",(e,t)=>{YU.init(e,t),cn.init(e,t)}),U_=fe("ZodCIDRv6",(e,t)=>{ZU.init(e,t),cn.init(e,t)}),B_=fe("ZodBase64",(e,t)=>{QU.init(e,t),cn.init(e,t)}),z_=fe("ZodBase64URL",(e,t)=>{eB.init(e,t),cn.init(e,t)}),G_=fe("ZodE164",(e,t)=>{tB.init(e,t),cn.init(e,t)}),q_=fe("ZodJWT",(e,t)=>{rB.init(e,t),cn.init(e,t)}),jh=fe("ZodCustomStringFormat",(e,t)=>{nB.init(e,t),cn.init(e,t)}),by=fe("ZodNumber",(e,t)=>{eR.init(e,t),Wt.init(e,t),e._zod.processJSONSchema=(n,o,i)=>_z(e,n,o,i),e.gt=(n,o)=>e.check(Qp(n,o)),e.gte=(n,o)=>e.check(ya(n,o)),e.min=(n,o)=>e.check(ya(n,o)),e.lt=(n,o)=>e.check(Zp(n,o)),e.lte=(n,o)=>e.check(Nl(n,o)),e.max=(n,o)=>e.check(Nl(n,o)),e.int=n=>e.check(MR(n)),e.safe=n=>e.check(MR(n)),e.positive=n=>e.check(Qp(0,n)),e.nonnegative=n=>e.check(ya(0,n)),e.negative=n=>e.check(Zp(0,n)),e.nonpositive=n=>e.check(Nl(0,n)),e.multipleOf=(n,o)=>e.check(py(n,o)),e.step=(n,o)=>e.check(py(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}),tm=fe("ZodNumberFormat",(e,t)=>{oB.init(e,t),by.init(e,t)}),_y=fe("ZodBoolean",(e,t)=>{tR.init(e,t),Wt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Ez(e,r,n,o)}),Ey=fe("ZodBigInt",(e,t)=>{rR.init(e,t),Wt.init(e,t),e._zod.processJSONSchema=(n,o,i)=>Sz(e,n,o,i),e.gte=(n,o)=>e.check(ya(n,o)),e.min=(n,o)=>e.check(ya(n,o)),e.gt=(n,o)=>e.check(Qp(n,o)),e.gte=(n,o)=>e.check(ya(n,o)),e.min=(n,o)=>e.check(ya(n,o)),e.lt=(n,o)=>e.check(Zp(n,o)),e.lte=(n,o)=>e.check(Nl(n,o)),e.max=(n,o)=>e.check(Nl(n,o)),e.positive=n=>e.check(Qp(BigInt(0),n)),e.negative=n=>e.check(Zp(BigInt(0),n)),e.nonpositive=n=>e.check(Nl(BigInt(0),n)),e.nonnegative=n=>e.check(ya(BigInt(0),n)),e.multipleOf=(n,o)=>e.check(py(n,o));const r=e._zod.bag;e.minValue=r.minimum??null,e.maxValue=r.maximum??null,e.format=r.format??null}),V_=fe("ZodBigIntFormat",(e,t)=>{iB.init(e,t),Ey.init(e,t)}),UR=fe("ZodSymbol",(e,t)=>{sB.init(e,t),Wt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>kz(e,r,n,o)}),BR=fe("ZodUndefined",(e,t)=>{aB.init(e,t),Wt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Az(e,r,n,o)}),zR=fe("ZodNull",(e,t)=>{lB.init(e,t),Wt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>xz(e,r,n,o)}),GR=fe("ZodAny",(e,t)=>{cB.init(e,t),Wt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Rz(e,r,n,o)}),qR=fe("ZodUnknown",(e,t)=>{uB.init(e,t),Wt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Pz(e,r,n,o)}),VR=fe("ZodNever",(e,t)=>{dB.init(e,t),Wt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Iz(e,r,n,o)}),jR=fe("ZodVoid",(e,t)=>{pB.init(e,t),Wt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Cz(e,r,n,o)}),j_=fe("ZodDate",(e,t)=>{mB.init(e,t),Wt.init(e,t),e._zod.processJSONSchema=(n,o,i)=>Mz(e,n,o,i),e.min=(n,o)=>e.check(ya(n,o)),e.max=(n,o)=>e.check(Nl(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}),HR=fe("ZodArray",(e,t)=>{hB.init(e,t),Wt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Vz(e,r,n,o),e.element=t.element,e.min=(r,n)=>e.check(Vh(r,n)),e.nonempty=r=>e.check(Vh(1,r)),e.max=(r,n)=>e.check(w_(r,n)),e.length=(r,n)=>e.check(T_(r,n)),e.unwrap=()=>e.element}),Sy=fe("ZodObject",(e,t)=>{gB.init(e,t),Wt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>jz(e,r,n,o),vr.defineLazy(e,"shape",()=>t.shape),e.keyof=()=>Rs(Object.keys(e._zod.def.shape)),e.catchall=r=>e.clone({...e._zod.def,catchall:r}),e.passthrough=()=>e.clone({...e._zod.def,catchall:fn()}),e.loose=()=>e.clone({...e._zod.def,catchall:fn()}),e.strict=()=>e.clone({...e._zod.def,catchall:OR()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=r=>vr.extend(e,r),e.safeExtend=r=>vr.safeExtend(e,r),e.merge=r=>vr.merge(e,r),e.pick=r=>vr.pick(e,r),e.omit=r=>vr.omit(e,r),e.partial=(...r)=>vr.partial(H_,e,r[0]),e.required=(...r)=>vr.required(W_,e,r[0])}),ky=fe("ZodUnion",(e,t)=>{y_.init(e,t),Wt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>ER(e,r,n,o),e.options=t.options}),WR=fe("ZodXor",(e,t)=>{ky.init(e,t),yB.init(e,t),e._zod.processJSONSchema=(r,n,o)=>ER(e,r,n,o),e.options=t.options}),KR=fe("ZodDiscriminatedUnion",(e,t)=>{ky.init(e,t),vB.init(e,t)}),JR=fe("ZodIntersection",(e,t)=>{wB.init(e,t),Wt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Hz(e,r,n,o)}),XR=fe("ZodTuple",(e,t)=>{nR.init(e,t),Wt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Wz(e,r,n,o),e.rest=r=>e.clone({...e._zod.def,rest:r})}),xy=fe("ZodRecord",(e,t)=>{TB.init(e,t),Wt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Kz(e,r,n,o),e.keyType=t.keyType,e.valueType=t.valueType}),YR=fe("ZodMap",(e,t)=>{bB.init(e,t),Wt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Gz(e,r,n,o),e.keyType=t.keyType,e.valueType=t.valueType,e.min=(...r)=>e.check(em(...r)),e.nonempty=r=>e.check(em(1,r)),e.max=(...r)=>e.check(my(...r)),e.size=(...r)=>e.check(v_(...r))}),ZR=fe("ZodSet",(e,t)=>{_B.init(e,t),Wt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>qz(e,r,n,o),e.min=(...r)=>e.check(em(...r)),e.nonempty=r=>e.check(em(1,r)),e.max=(...r)=>e.check(my(...r)),e.size=(...r)=>e.check(v_(...r))}),Hh=fe("ZodEnum",(e,t)=>{EB.init(e,t),Wt.init(e,t),e._zod.processJSONSchema=(n,o,i)=>Oz(e,n,o,i),e.enum=t.entries,e.options=Object.values(t.entries);const r=new Set(Object.keys(t.entries));e.extract=(n,o)=>{const i={};for(const s of n)if(r.has(s))i[s]=t.entries[s];else throw new Error(`Key ${s} not found in enum`);return new Hh({...t,checks:[],...vr.normalizeParams(o),entries:i})},e.exclude=(n,o)=>{const i={...t.entries};for(const s of n)if(r.has(s))delete i[s];else throw new Error(`Key ${s} not found in enum`);return new Hh({...t,checks:[],...vr.normalizeParams(o),entries:i})}}),QR=fe("ZodLiteral",(e,t)=>{SB.init(e,t),Wt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Dz(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]}})}),e4=fe("ZodFile",(e,t)=>{kB.init(e,t),Wt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Fz(e,r,n,o),e.min=(r,n)=>e.check(em(r,n)),e.max=(r,n)=>e.check(my(r,n)),e.mime=(r,n)=>e.check(fR(Array.isArray(r)?r:[r],n))}),t4=fe("ZodTransform",(e,t)=>{xB.init(e,t),Wt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>zz(e,r,n,o),e._zod.parse=(r,n)=>{if(n.direction==="backward")throw new c_(e.constructor.name);r.addIssue=i=>{if(typeof i=="string")r.issues.push(vr.issue(i,r.value,t));else{const s=i;s.fatal&&(s.continue=!1),s.code??(s.code="custom"),s.input??(s.input=r.value),s.inst??(s.inst=e),r.issues.push(vr.issue(s))}};const o=t.transform(r.value,r);return o instanceof Promise?o.then(i=>(r.value=i,r)):(r.value=o,r)}}),H_=fe("ZodOptional",(e,t)=>{oR.init(e,t),Wt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>SR(e,r,n,o),e.unwrap=()=>e._zod.def.innerType}),r4=fe("ZodExactOptional",(e,t)=>{AB.init(e,t),Wt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>SR(e,r,n,o),e.unwrap=()=>e._zod.def.innerType}),n4=fe("ZodNullable",(e,t)=>{CB.init(e,t),Wt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Jz(e,r,n,o),e.unwrap=()=>e._zod.def.innerType}),o4=fe("ZodDefault",(e,t)=>{IB.init(e,t),Wt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Yz(e,r,n,o),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap}),i4=fe("ZodPrefault",(e,t)=>{RB.init(e,t),Wt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Zz(e,r,n,o),e.unwrap=()=>e._zod.def.innerType}),W_=fe("ZodNonOptional",(e,t)=>{PB.init(e,t),Wt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Xz(e,r,n,o),e.unwrap=()=>e._zod.def.innerType}),s4=fe("ZodSuccess",(e,t)=>{MB.init(e,t),Wt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>$z(e,r,n,o),e.unwrap=()=>e._zod.def.innerType}),a4=fe("ZodCatch",(e,t)=>{OB.init(e,t),Wt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Qz(e,r,n,o),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap}),l4=fe("ZodNaN",(e,t)=>{DB.init(e,t),Wt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Nz(e,r,n,o)}),K_=fe("ZodPipe",(e,t)=>{NB.init(e,t),Wt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>eG(e,r,n,o),e.in=t.in,e.out=t.out}),J_=fe("ZodCodec",(e,t)=>{K_.init(e,t),iR.init(e,t)}),c4=fe("ZodReadonly",(e,t)=>{LB.init(e,t),Wt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>tG(e,r,n,o),e.unwrap=()=>e._zod.def.innerType}),u4=fe("ZodTemplateLiteral",(e,t)=>{FB.init(e,t),Wt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Lz(e,r,n,o)}),d4=fe("ZodLazy",(e,t)=>{BB.init(e,t),Wt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>nG(e,r,n,o),e.unwrap=()=>e._zod.def.getter()}),p4=fe("ZodPromise",(e,t)=>{UB.init(e,t),Wt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>rG(e,r,n,o),e.unwrap=()=>e._zod.def.innerType}),m4=fe("ZodFunction",(e,t)=>{$B.init(e,t),Wt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Bz(e,r,n,o)}),Ay=fe("ZodCustom",(e,t)=>{zB.init(e,t),Wt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Uz(e,r,n,o)}),PG=Hwe,MG=Wwe,OG=(...e)=>Kwe({Codec:J_,Boolean:_y,String:vy},...e)}});function jIr(e){Is({customError:e})}function HIr(){return Is().customError}var DG,NG,WIr=E({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/compat.js"(){gi(),gi(),DG={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"},NG||(NG={})}});function KIr(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 JIr(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 cbe(e,t){if(e.not!==void 0){if(typeof e.not=="object"&&Object.keys(e.not).length===0)return ot.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 ot.lazy(()=>{if(!t.refs.has(o))throw new Error(`Circular reference not resolved: ${o}`);return t.refs.get(o)});t.processing.add(o);const i=JIr(o,t),s=Ps(i,t);return t.refs.set(o,s),t.processing.delete(o),s}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 ot.null();if(o.length===0)return ot.never();if(o.length===1)return ot.literal(o[0]);if(o.every(s=>typeof s=="string"))return ot.enum(o);const i=o.map(s=>ot.literal(s));return i.length<2?i[0]:ot.union([i[0],i[1],...i.slice(2)])}if(e.const!==void 0)return ot.literal(e.const);const r=e.type;if(Array.isArray(r)){const o=r.map(i=>{const s={...e,type:i};return cbe(s,t)});return o.length===0?ot.never():o.length===1?o[0]:ot.union(o)}if(!r)return ot.any();let n;switch(r){case"string":{let o=ot.string();if(e.format){const i=e.format;i==="email"?o=o.check(ot.email()):i==="uri"||i==="uri-reference"?o=o.check(ot.url()):i==="uuid"||i==="guid"?o=o.check(ot.uuid()):i==="date-time"?o=o.check(ot.iso.datetime()):i==="date"?o=o.check(ot.iso.date()):i==="time"?o=o.check(ot.iso.time()):i==="duration"?o=o.check(ot.iso.duration()):i==="ipv4"?o=o.check(ot.ipv4()):i==="ipv6"?o=o.check(ot.ipv6()):i==="mac"?o=o.check(ot.mac()):i==="cidr"?o=o.check(ot.cidrv4()):i==="cidr-v6"?o=o.check(ot.cidrv6()):i==="base64"?o=o.check(ot.base64()):i==="base64url"?o=o.check(ot.base64url()):i==="e164"?o=o.check(ot.e164()):i==="jwt"?o=o.check(ot.jwt()):i==="emoji"?o=o.check(ot.emoji()):i==="nanoid"?o=o.check(ot.nanoid()):i==="cuid"?o=o.check(ot.cuid()):i==="cuid2"?o=o.check(ot.cuid2()):i==="ulid"?o=o.check(ot.ulid()):i==="xid"?o=o.check(ot.xid()):i==="ksuid"&&(o=o.check(ot.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"?ot.number().int():ot.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=ot.boolean();break}case"null":{n=ot.null();break}case"object":{const o={},i=e.properties||{},s=new Set(e.required||[]);for(const[l,c]of Object.entries(i)){const u=Ps(c,t);o[l]=s.has(l)?u:u.optional()}if(e.propertyNames){const l=Ps(e.propertyNames,t),c=e.additionalProperties&&typeof e.additionalProperties=="object"?Ps(e.additionalProperties,t):ot.any();if(Object.keys(o).length===0){n=ot.record(l,c);break}const u=ot.object(o).passthrough(),d=ot.looseRecord(l,c);n=ot.intersection(u,d);break}if(e.patternProperties){const l=e.patternProperties,c=Object.keys(l),u=[];for(const p of c){const m=Ps(l[p],t),f=ot.string().regex(new RegExp(p));u.push(ot.looseRecord(f,m))}const d=[];if(Object.keys(o).length>0&&d.push(ot.object(o).passthrough()),d.push(...u),d.length===0)n=ot.object({}).passthrough();else if(d.length===1)n=d[0];else{let p=ot.intersection(d[0],d[1]);for(let m=2;m<d.length;m++)p=ot.intersection(p,d[m]);n=p}break}const a=ot.object(o);e.additionalProperties===!1?n=a.strict():typeof e.additionalProperties=="object"?n=a.catchall(Ps(e.additionalProperties,t)):n=a.passthrough();break}case"array":{const o=e.prefixItems,i=e.items;if(o&&Array.isArray(o)){const s=o.map(l=>Ps(l,t)),a=i&&typeof i=="object"&&!Array.isArray(i)?Ps(i,t):void 0;a?n=ot.tuple(s).rest(a):n=ot.tuple(s),typeof e.minItems=="number"&&(n=n.check(ot.minLength(e.minItems))),typeof e.maxItems=="number"&&(n=n.check(ot.maxLength(e.maxItems)))}else if(Array.isArray(i)){const s=i.map(l=>Ps(l,t)),a=e.additionalItems&&typeof e.additionalItems=="object"?Ps(e.additionalItems,t):void 0;a?n=ot.tuple(s).rest(a):n=ot.tuple(s),typeof e.minItems=="number"&&(n=n.check(ot.minLength(e.minItems))),typeof e.maxItems=="number"&&(n=n.check(ot.maxLength(e.maxItems)))}else if(i!==void 0){const s=Ps(i,t);let a=ot.array(s);typeof e.minItems=="number"&&(a=a.min(e.minItems)),typeof e.maxItems=="number"&&(a=a.max(e.maxItems)),n=a}else n=ot.array(ot.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 Ps(e,t){if(typeof e=="boolean")return e?ot.any():ot.never();let r=cbe(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=>Ps(c,t)),l=ot.union(a);r=n?ot.intersection(r,l):l}if(e.oneOf&&Array.isArray(e.oneOf)){const a=e.oneOf.map(c=>Ps(c,t)),l=ot.xor(a);r=n?ot.intersection(r,l):l}if(e.allOf&&Array.isArray(e.allOf))if(e.allOf.length===0)r=n?r:ot.any();else{let a=n?r:Ps(e.allOf[0],t);const l=n?0:1;for(let c=l;c<e.allOf.length;c++)a=ot.intersection(a,Ps(e.allOf[c],t));r=a}e.nullable===!0&&t.version==="openapi-3.0"&&(r=ot.nullable(r)),e.readOnly===!0&&(r=ot.readonly(r));const o={},i=["$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor"];for(const a of i)a in e&&(o[a]=e[a]);const s=["contentEncoding","contentMediaType","contentSchema"];for(const a of s)a in e&&(o[a]=e[a]);for(const a of Object.keys(e))ube.has(a)||(o[a]=e[a]);return Object.keys(o).length>0&&t.registry.add(r,o),r}function XIr(e,t){if(typeof e=="boolean")return e?ot.any():ot.never();const r=KIr(e,t?.defaultTarget),n=e.$defs||e.definitions||{},o={version:r,defs:n,refs:new Map,processing:new Set,rootSchema:e,registry:t?.registry??Za};return Ps(e,o)}var ot,ube,YIr=E({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/from-json-schema.js"(){sR(),oG(),PR(),h4(),ot={...sTe,...Zwe,iso:xR},ube=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"])}}),LG={};Z(LG,{bigint:()=>tRr,boolean:()=>eRr,date:()=>rRr,number:()=>QIr,string:()=>ZIr});function ZIr(e){return dwe(vy,e)}function QIr(e){return vwe(by,e)}function eRr(e){return kwe(_y,e)}function tRr(e){return Awe(Ey,e)}function rRr(e){return $we(j_,e)}var nRr=E({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/coerce.js"(){gi(),h4()}}),N={};Z(N,{$brand:()=>E5,$input:()=>HB,$output:()=>jB,NEVER:()=>xI,TimePrecision:()=>wz,ZodAny:()=>GR,ZodArray:()=>HR,ZodBase64:()=>B_,ZodBase64URL:()=>z_,ZodBigInt:()=>Ey,ZodBigIntFormat:()=>V_,ZodBoolean:()=>_y,ZodCIDRv4:()=>$_,ZodCIDRv6:()=>U_,ZodCUID:()=>P_,ZodCUID2:()=>M_,ZodCatch:()=>a4,ZodCodec:()=>J_,ZodCustom:()=>Ay,ZodCustomStringFormat:()=>jh,ZodDate:()=>j_,ZodDefault:()=>o4,ZodDiscriminatedUnion:()=>KR,ZodE164:()=>G_,ZodEmail:()=>C_,ZodEmoji:()=>I_,ZodEnum:()=>Hh,ZodError:()=>nTe,ZodExactOptional:()=>r4,ZodFile:()=>e4,ZodFirstPartyTypeKind:()=>NG,ZodFunction:()=>m4,ZodGUID:()=>wy,ZodIPv4:()=>L_,ZodIPv6:()=>F_,ZodISODate:()=>CR,ZodISODateTime:()=>AR,ZodISODuration:()=>RR,ZodISOTime:()=>IR,ZodIntersection:()=>JR,ZodIssueCode:()=>DG,ZodJWT:()=>q_,ZodKSUID:()=>N_,ZodLazy:()=>d4,ZodLiteral:()=>QR,ZodMAC:()=>$R,ZodMap:()=>YR,ZodNaN:()=>l4,ZodNanoID:()=>R_,ZodNever:()=>VR,ZodNonOptional:()=>W_,ZodNull:()=>zR,ZodNullable:()=>n4,ZodNumber:()=>by,ZodNumberFormat:()=>tm,ZodObject:()=>Sy,ZodOptional:()=>H_,ZodPipe:()=>K_,ZodPrefault:()=>i4,ZodPromise:()=>p4,ZodReadonly:()=>c4,ZodRealError:()=>va,ZodRecord:()=>xy,ZodSet:()=>ZR,ZodString:()=>vy,ZodStringFormat:()=>cn,ZodSuccess:()=>s4,ZodSymbol:()=>UR,ZodTemplateLiteral:()=>u4,ZodTransform:()=>t4,ZodTuple:()=>XR,ZodType:()=>Wt,ZodULID:()=>O_,ZodURL:()=>Ty,ZodUUID:()=>Sc,ZodUndefined:()=>BR,ZodUnion:()=>ky,ZodUnknown:()=>qR,ZodVoid:()=>jR,ZodXID:()=>D_,ZodXor:()=>WR,_ZodString:()=>A_,_default:()=>_G,_function:()=>LR,any:()=>wG,array:()=>Ze,base64:()=>xTe,base64url:()=>ATe,bigint:()=>$Te,boolean:()=>an,catch:()=>kG,check:()=>sbe,cidrv4:()=>STe,cidrv6:()=>kTe,clone:()=>Ol,codec:()=>nbe,coerce:()=>LG,config:()=>Is,core:()=>Ywe,cuid:()=>gTe,cuid2:()=>yTe,custom:()=>CG,date:()=>VTe,decode:()=>dG,decodeAsync:()=>mG,describe:()=>PG,discriminatedUnion:()=>DR,e164:()=>CTe,email:()=>aTe,emoji:()=>hTe,encode:()=>uG,encodeAsync:()=>pG,endsWith:()=>hR,enum:()=>Rs,exactOptional:()=>bG,file:()=>QTe,flattenError:()=>P5,float32:()=>DTe,float64:()=>NTe,formatError:()=>M5,fromJSONSchema:()=>XIr,function:()=>LR,getErrorMap:()=>HIr,globalRegistry:()=>Za,gt:()=>Qp,gte:()=>ya,guid:()=>lTe,hash:()=>OTe,hex:()=>MTe,hostname:()=>PTe,httpUrl:()=>mTe,includes:()=>pR,instanceof:()=>abe,int:()=>MR,int32:()=>LTe,int64:()=>UTe,intersection:()=>S_,ipv4:()=>bTe,ipv6:()=>ETe,iso:()=>xR,json:()=>lbe,jwt:()=>ITe,keyof:()=>jTe,ksuid:()=>TTe,lazy:()=>AG,length:()=>T_,literal:()=>wt,locales:()=>GB,looseObject:()=>Ni,looseRecord:()=>JTe,lowercase:()=>uR,lt:()=>Zp,lte:()=>Nl,mac:()=>_Te,map:()=>XTe,maxLength:()=>w_,maxSize:()=>my,meta:()=>MG,mime:()=>fR,minLength:()=>Vh,minSize:()=>em,multipleOf:()=>py,nan:()=>rbe,nanoid:()=>fTe,nativeEnum:()=>ZTe,negative:()=>fz,never:()=>OR,nonnegative:()=>yz,nonoptional:()=>SG,nonpositive:()=>gz,normalize:()=>gR,null:()=>E_,nullable:()=>k_,nullish:()=>ebe,number:()=>Lr,object:()=>rt,optional:()=>ro,overwrite:()=>Ed,parse:()=>sG,parseAsync:()=>aG,partialRecord:()=>KTe,pipe:()=>x_,positive:()=>hz,prefault:()=>EG,preprocess:()=>FR,prettifyError:()=>Q0e,promise:()=>ibe,property:()=>vz,readonly:()=>xG,record:()=>Hn,refine:()=>IG,regex:()=>cR,regexes:()=>Gh,registry:()=>VB,safeDecode:()=>fG,safeDecodeAsync:()=>yG,safeEncode:()=>hG,safeEncodeAsync:()=>gG,safeParse:()=>lG,safeParseAsync:()=>cG,set:()=>YTe,setErrorMap:()=>jIr,size:()=>v_,slugify:()=>TR,startsWith:()=>mR,strictObject:()=>HTe,string:()=>ee,stringFormat:()=>RTe,stringbool:()=>OG,success:()=>tbe,superRefine:()=>RG,symbol:()=>zTe,templateLiteral:()=>obe,toJSONSchema:()=>_R,toLowerCase:()=>vR,toUpperCase:()=>wR,transform:()=>NR,treeifyError:()=>Y0e,trim:()=>yR,tuple:()=>TG,uint32:()=>FTe,uint64:()=>BTe,ulid:()=>vTe,undefined:()=>GTe,union:()=>ln,unknown:()=>fn,uppercase:()=>dR,url:()=>vG,util:()=>vr,uuid:()=>cTe,uuidv4:()=>uTe,uuidv6:()=>dTe,uuidv7:()=>pTe,void:()=>qTe,xid:()=>wTe,xor:()=>WTe});var f4=E({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/external.js"(){gi(),h4(),oG(),oTe(),iTe(),WIr(),gi(),yve(),gi(),__(),YIr(),qB(),PR(),PR(),nRr(),Is(fve())}}),gn=E({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/index.js"(){f4(),f4()}}),FG,$G,oRr=E({"src/lib/types/model.ts"(){"use strict";gn(),FG=N.object({id:N.string(),displayName:N.string(),capabilities:N.array(N.string()),deprecated:N.boolean(),pricing:N.object({input:N.number(),output:N.number()}),contextWindow:N.number(),releaseDate:N.string()}),$G=N.object({version:N.string(),lastUpdated:N.string(),models:N.record(N.string(),N.record(N.string(),FG)),aliases:N.record(N.string(),N.string()).optional(),defaults:N.record(N.string(),N.string()).optional()})}});function dbe(e){return e.type==="text"}function iRr(e){return e.type==="image"}function UG(e){return e.type==="csv"}function sRr(e){return e.type==="pdf"}function aRr(e){return e.type==="audio"}function lRr(e){return e.type==="video"}function cRr(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 uRr(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(cRr))}function dRr(e){return Array.isArray(e)}var pRr=E({"src/lib/types/multimodal.ts"(){"use strict"}}),mRr=E({"src/lib/types/nativeTools.ts"(){"use strict"}}),hRr=E({"src/lib/types/observability.ts"(){"use strict"}}),fRr=E({"src/lib/types/openaiCompatible.ts"(){"use strict"}});function gRr(e){return/^[0-9A-Fa-f]{6}$/.test(e)}function yRr(e){return e.startsWith("#")?e.slice(1):e}var pbe,mbe,g4,vRr=E({"src/lib/types/ppt.ts"(){"use strict";pbe=5,mbe=50,g4={"16:9":{width:10,height:5.625},"4:3":{width:10,height:7.5}}}}),BG,hbe,fbe=E({"src/lib/processors/errors/FileErrorCode.ts"(){"use strict";BG=(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))(BG||{}),hbe={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}}}}),zG,gbe,ybe,vbe,wbe,Tbe,wRr=E({"src/lib/types/processor.ts"(){"use strict";fbe(),zG={maxRetries:3,baseDelayMs:1e3,maxDelayMs:1e4},gbe=3e4,ybe=10,vbe=3e4,wbe=10,Tbe={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}}}),TRr=E({"src/lib/types/providerCatalog.ts"(){"use strict"}}),bRr=E({"src/lib/types/providerCatalog.generated.ts"(){"use strict"}});function _Rr(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 y4,bbe,_be,X_,ERr=E({"src/lib/types/providers.ts"(){"use strict";y4={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"},bbe=y4,_be=[{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"]}],X_=["generate","stream"]}}),SRr=E({"src/lib/types/proxy.ts"(){"use strict"}}),kRr=E({"src/lib/types/proxyIR.ts"(){"use strict"}}),xRr=E({"src/lib/types/proxyClient.ts"(){"use strict"}}),ARr=E({"src/lib/types/proxyContext.ts"(){"use strict"}}),Ebe,CRr=E({"src/lib/types/rag.ts"(){"use strict";Ebe=["image/jpeg","image/png","image/gif","image/webp","image/bmp","image/tiff","image/avif"]}}),IRr=E({"src/lib/types/scorer.ts"(){"use strict"}}),RRr=E({"src/lib/types/sdk.ts"(){"use strict"}}),Or,no,Ar,PRr=E({"src/lib/types/server.ts"(){"use strict";Or={CONFIG:"CONFIG",VALIDATION:"VALIDATION",EXECUTION:"EXECUTION",EXTERNAL:"EXTERNAL",RATE_LIMIT:"RATE_LIMIT",AUTHENTICATION:"AUTHENTICATION",AUTHORIZATION:"AUTHORIZATION",STREAMING:"STREAMING",WEBSOCKET:"WEBSOCKET"},no={LOW:"LOW",MEDIUM:"MEDIUM",HIGH:"HIGH",CRITICAL:"CRITICAL"},Ar={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"}}}),MRr=E({"src/lib/types/service.ts"(){"use strict"}}),ORr=E({"src/lib/types/skills.ts"(){"use strict"}}),DRr=E({"src/lib/types/stream.ts"(){"use strict"}}),NRr=E({"src/lib/types/streaming.ts"(){"use strict"}}),LRr=E({"src/lib/types/subscription.ts"(){"use strict"}}),GG,qG,Xo,FRr=E({"src/lib/types/task.ts"(){"use strict";GG=720*60*60*1e3,qG=10080*60*1e3,Xo={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:GG,failedTTL:qG,cancelledTTL:qG,runLogTTL:GG}}}}),$Rr=E({"src/lib/types/taskClassification.ts"(){"use strict"}}),URr=E({"src/lib/types/tasks.ts"(){"use strict"}}),BRr=E({"src/lib/types/toolDedup.ts"(){"use strict"}}),zRr=E({"src/lib/types/toolResolution.ts"(){"use strict"}}),GRr=E({"src/lib/types/toolRouting.ts"(){"use strict"}});function qRr(e){return typeof e=="object"&&e!==null&&"success"in e&&typeof e.success=="boolean"}function VRr(e){return typeof e=="object"&&e!==null&&"description"in e&&"execute"in e&&typeof e.description=="string"&&typeof e.execute=="function"}var jRr=E({"src/lib/types/tools.ts"(){"use strict"}}),HRr=E({"src/lib/types/vectorStoreChroma.ts"(){"use strict"}}),WRr=E({"src/lib/types/vectorStorePinecone.ts"(){"use strict"}});function KRr(e){if(!e||typeof e!="object")return!1;const t=e;return Buffer.isBuffer(t.buffer)&&typeof t.format=="string"&&Y_.includes(t.format)&&typeof t.size=="number"&&t.size>=0}function JRr(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&&!Y_.includes(t.format)||t.quality!==void 0&&!VG.includes(t.quality)||t.streamingBufferSize!==void 0&&(!Number.isInteger(t.streamingBufferSize)||t.streamingBufferSize<1))}var Y_,VG,XRr=E({"src/lib/types/tts.ts"(){"use strict";Y_=["mp3","wav","ogg","opus","m4a","flac","webm","mp4","mpeg","mpga","pcm16"],VG=["standard","hd"]}});function Sbe(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 kbe(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 xbe(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 vs,jG,YRr=E({"src/lib/types/stt.ts"(){"use strict";vs={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"},jG={language:"en-US",punctuation:!0,profanityFilter:!1,sampleRate:16e3}}});function Abe(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 es,v4,ZRr=E({"src/lib/types/realtime.ts"(){"use strict";es={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"},v4={timeout:3e4,inputSampleRate:24e3,outputSampleRate:24e3,vadEnabled:!0,vadThreshold:.5,turnDetection:"server_vad"}}}),HG,Z_,QRr=E({"src/lib/types/voice.ts"(){"use strict";XRr(),YRr(),ZRr(),HG={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"},Z_={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]}}}}),e4r=E({"src/lib/types/utilities.ts"(){"use strict"}}),Sd,t4r=E({"src/lib/types/workflow.ts"(){"use strict";Sd=class xEr extends Error{details;constructor(t,r){super(t),this.name="WorkflowError",this.details=r,"captureStackTrace"in Error&&typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,xEr)}}}}),r4r=E({"src/lib/types/ioProcessor.ts"(){"use strict"}}),n4r=E({"src/lib/types/exporter.ts"(){"use strict"}}),WG,KG,Cbe,Ibe,o4r=E({"src/lib/types/span.ts"(){"use strict";WG=(e=>(e.AGENT_RUN="agent.run",e.WORKFLOW_STEP="workflow.step",e.TOOL_CALL="tool.call",e.MODEL_GENERATION="model.generation",e.MODEL_DECISION="model.decision",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))(WG||{}),KG=(e=>(e[e.UNSET=0]="UNSET",e[e.OK=1]="OK",e[e.ERROR=2]="ERROR",e[e.WARNING=3]="WARNING",e))(KG||{}),Cbe={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"},Ibe={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"}}}),JG,i4r=E({"src/lib/types/imageGen.ts"(){"use strict";JG={enabled:!0,defaultModel:"imagen-3.0-generate-001",defaultProvider:"vertex",defaultRegion:"global",timeout:12e4,defaultTemperature:.75,maxImages:4,maxReferenceImages:5,maxReferencePdfs:1}}}),s4r=E({"src/lib/types/elicitation.ts"(){"use strict"}}),a4r=E({"src/lib/types/dynamic.ts"(){"use strict"}}),l4r=E({"src/lib/types/streamDedup.ts"(){"use strict"}}),c4r=E({"src/lib/types/noOutputSentinel.ts"(){"use strict"}}),u4r=E({"src/lib/types/video.ts"(){"use strict"}}),Rbe,d4r=E({"src/lib/types/avatar.ts"(){"use strict";Rbe=["mp4","webm","mov"]}}),Pbe,p4r=E({"src/lib/types/music.ts"(){"use strict";Pbe=["mp3","wav","flac","ogg"]}}),m4r=E({"src/lib/types/replicate.ts"(){"use strict"}}),h4r=E({"src/lib/types/mediaCatalog.ts"(){"use strict"}}),f4r=E({"src/lib/types/safeFetch.ts"(){"use strict"}}),g4r=E({"src/lib/types/modelPool.ts"(){"use strict"}}),y4r=E({"src/lib/types/requestRouter.ts"(){"use strict"}}),v4r=E({"src/lib/types/classifierRouter.ts"(){"use strict"}}),w4r=E({"src/lib/types/agentNetwork.ts"(){"use strict"}}),T4r=E({"src/lib/types/localUsage.ts"(){"use strict"}}),b4r=E({"src/lib/types/dispatch.ts"(){"use strict"}}),_4r=E({"src/lib/types/proxyRestart.ts"(){"use strict"}}),E4r=E({"src/lib/types/proxyBudget.ts"(){"use strict"}}),S4r=E({"src/lib/types/decision.ts"(){"use strict"}}),pt=E({"src/lib/types/index.ts"(){"use strict";Jkr(),Xkr(),Ykr(),Kxr(),Jxr(),Xxr(),Yxr(),Zxr(),Qxr(),eAr(),nAr(),oAr(),iAr(),aAr(),LAr(),FAr(),$Ar(),UAr(),BAr(),zAr(),GAr(),qAr(),VAr(),jAr(),HAr(),WAr(),KAr(),JAr(),XAr(),YAr(),ZAr(),QAr(),eCr(),tCr(),rCr(),nCr(),oCr(),iCr(),sCr(),aCr(),lCr(),cCr(),oRr(),pRr(),mRr(),hRr(),fRr(),vRr(),wRr(),TRr(),bRr(),ERr(),SRr(),kRr(),xRr(),ARr(),CRr(),IRr(),RRr(),PRr(),MRr(),ORr(),DRr(),NRr(),LRr(),FRr(),$Rr(),URr(),BRr(),zRr(),GRr(),jRr(),HRr(),WRr(),QRr(),e4r(),t4r(),r4r(),n4r(),o4r(),i4r(),s4r(),a4r(),l4r(),c4r(),u4r(),d4r(),p4r(),m4r(),h4r(),f4r(),g4r(),y4r(),v4r(),w4r(),T4r(),b4r(),_4r(),E4r(),S4r()}});async function It(e,t,r){let n;const o=new Promise((i,s)=>{n=setTimeout(()=>{s(new ku(r||`Operation timed out after ${t}ms`,t))},t)});try{return await Promise.race([e,o])}finally{n!==void 0&&clearTimeout(n)}}async function Su(e,t){if(!t||typeof t.addEventListener!="function")return e;const r=()=>{const n=new Error("Operation aborted");return n.name="AbortError",n};return t.aborted?(e.catch(()=>{}),Promise.reject(r())):new Promise((n,o)=>{const i=()=>{e.catch(()=>{}),o(r())};t.addEventListener("abort",i,{once:!0}),e.then(s=>{t.removeEventListener("abort",i),n(s)},s=>{t.removeEventListener("abort",i),o(s)})})}async function w4(e,t,r){return It(e(),t,r)}var ku,Kr=E({"src/lib/utils/async/withTimeout.ts"(){"use strict";ku=class AEr extends Error{constructor(t,r){super(t),this.timeoutMs=r,this.name="TimeoutError",Error.captureStackTrace&&Error.captureStackTrace(this,AEr)}timeoutMs}}});function kc(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 k4r(e,t="generate"){if(t==="stream")return b4.streaming;const r=e.toLowerCase().replace("_","-");return b4.providers[r]||b4.global}async function x4r(e,t,r,n){const o=kc(t);if(!o)return e;let i;const s=new Promise((a,l)=>{const c=setTimeout(()=>{l(new Ta(`${r} ${n} operation timed out after ${o}ms`,o,r,n))},o);i=c,typeof c=="object"&&c&&"unref"in c&&typeof c.unref=="function"&&c.unref()});try{return await Promise.race([e,s])}finally{i!==void 0&&clearTimeout(i)}}function wa(e,t,r){const n=kc(e);if(!n)return null;const o=new AbortController,i=()=>{o.abort(new Ta(`${t} ${r} operation timed out after ${e}`,n,t,r))};let s=setTimeout(i,n);return{controller:o,cleanup:()=>{clearTimeout(s)},reset:()=>{o.signal.aborted||(clearTimeout(s),s=setTimeout(i,n))},timeoutMs:n}}function Cy(e,t){return e&&t?AbortSignal.any([e,t]):e??t}function T4(e,t){if(!e||!t)return{signal:e??t,dispose:()=>{}};const r=new AbortController,n=[e,t],o=[],i=()=>{for(const{source:a,listener:l}of o)a.removeEventListener("abort",l);o.length=0},s=a=>{r.signal.aborted||r.abort(a.reason),i()};for(const a of n){const l=()=>s(a);a.addEventListener("abort",l,{once:!0}),o.push({source:a,listener:l})}for(const a of n)if(a.aborted){s(a);break}return{signal:r.signal,dispose:i}}function Mbe(e){const t=new AbortController,r=e.filter(i=>i!==void 0),n=r.find(i=>i.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 Ta,b4,Ys=E({"src/lib/utils/timeout.ts"(){"use strict";Kr(),Ta=class CEr extends ku{constructor(t,r,n,o){super(t,r),this.timeout=r,this.provider=n,this.operation=o,this.name="TimeoutError",typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,CEr)}timeout;provider;operation},b4={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"}}}}),_4,Q_,eE,tE,E4=E({"src/lib/hitl/hitlErrors.ts"(){"use strict";_4=class extends Error{constructor(e,t){super(e),this.confirmationId=t,this.name="HITLError"}confirmationId},Q_=class extends _4{constructor(e,t,r,n){super(e,n),this.toolName=t,this.reason=r,this.name="HITLUserRejectedError"}toolName;reason},eE=class extends _4{constructor(e,t,r){super(e,t),this.timeout=r,this.name="HITLTimeoutError"}timeout},tE=class extends _4{constructor(e){super(e),this.name="HITLConfigurationError"}}}}),rE={};Z(rE,{CircuitBreaker:()=>k4,ERROR_CODES:()=>He,ErrorFactory:()=>he,NeuroLinkError:()=>De,isAbortError:()=>pr,isRecoverableError:()=>S4,isRetriableError:()=>XG,logStructuredError:()=>Dbe,withRetry:()=>Obe,withTimeout:()=>ze});async function ze(e,t,r){let n;const o=new Promise((i,s)=>{n=setTimeout(()=>{s(r||new Error(`Operation timed out after ${t}ms`))},t)});try{return await Promise.race([e,o])}finally{clearTimeout(n)}}async function Obe(e,t){const{maxAttempts:r,delayMs:n,isRetriable:o=()=>!0,onRetry:i}=t;let s;for(let a=1;a<=r;a++)try{return await e()}catch(l){if(s=l instanceof Error?l:new Error(String(l)),a===r||!o(s))throw s;i&&i(a,s),await new Promise(c=>setTimeout(c,n))}throw s||new Error("Retry operation failed with no error information")}function pr(e){return!!(e instanceof DOMException&&e.name==="AbortError"||e instanceof Error&&e.name==="AbortError"||e instanceof De&&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 XG(e){return e instanceof De?e.retriable:e instanceof eE?!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 S4(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 Dbe(e,t){const r={...e.toJSON(),...t};switch(e.severity){case"critical":h.error(`[CRITICAL] ${e.message}`,r);break;case"high":h.error(`[HIGH] ${e.message}`,r);break;case"medium":h.warn(`[MEDIUM] ${e.message}`,r);break;case"low":h.info(`[LOW] ${e.message}`,r);break}}var He,De,he,k4,et=E({"src/lib/utils/errorHandling.ts"(){"use strict";z(),pt(),E4(),He={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"},De=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}}},he=class{static toolNotFound(e,t){return new De({code:He.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 De({code:He.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 De({code:He.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 De({code:He.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 De({code:He.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 De({code:He.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 De({code:He.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 De({code:He.MISSING_CONFIGURATION,message:`Missing required configuration: ${e}`,category:"validation",severity:"high",retriable:!1,context:t||{}})}static invalidConfiguration(e,t,r){return new De({code:He.INVALID_CONFIGURATION,message:`Invalid configuration for '${e}': ${t}`,category:"validation",severity:"high",retriable:!1,context:r||{}})}static csvInvalidInput(e){return new De({code:He.CSV_INVALID_INPUT,message:e,category:"validation",severity:"medium",retriable:!1,context:{}})}static csvRowInvalid(e,t){return new De({code:He.CSV_ROW_INVALID,message:e,category:"validation",severity:"medium",retriable:!1,context:{rowNumber:t}})}static csvFileAccessFailed(e,t,r){return new De({code:He.CSV_FILE_ACCESS_FAILED,message:e,category:"resource",severity:"high",retriable:!1,context:{filePath:t},originalError:r})}static csvParseFailed(e,t,r){return new De({code:He.CSV_PARSE_FAILED,message:e,category:"execution",severity:"medium",retriable:!1,context:t,originalError:r})}static invalidVideoResolution(e){return new De({code:He.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 De({code:He.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 De({code:He.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 De({code:He.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 De({code:He.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 De({code:He.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 De({code:He.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 De({code:He.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 De({code:He.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 De({code:He.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 De({code:He.PDF_PAGE_LIMIT_EXCEEDED,message:`PDF page limit exceeded: ${e} pages detected, but ${r} supports maximum ${t} pages.
|
|
63
63
|
|
|
64
64
|
Alternatives:
|
|
65
65
|
`+n.map((o,i)=>`${i+1}. ${o}`).join(`
|
|
66
|
-
`),category:"validation",severity:"medium",retriable:!1,context:{estimatedPages:e,maxPages:t,provider:r,alternatives:n}})}static pdfAggregatePageLimitExceeded(e,t,r,n){return new De({code:He.PDF_AGGREGATE_PAGE_LIMIT_EXCEEDED,message:`[PDF] Combined page count across ${e} PDF(s) (${t}) exceeds the ${r}-page limit for ${n}. Split the request or reduce the number of PDFs.`,category:"validation",severity:"medium",retriable:!1,context:{fileCount:e,totalPages:t,maxPages:r,provider:n}})}static pdfAggregateSizeLimitExceeded(e,t,r,n){return new De({code:He.PDF_AGGREGATE_SIZE_LIMIT_EXCEEDED,message:`[PDF] Combined size across ${e} PDF(s) (${t.toFixed(2)}MB) exceeds the ${r}MB limit for ${n}.`,category:"validation",severity:"medium",retriable:!1,context:{fileCount:e,totalMB:t,maxSizeMB:r,provider:n}})}static pdfPageCountUnverifiable(e,t){return new De({code:He.PDF_PAGE_COUNT_UNVERIFIABLE,message:`[PDF] Cannot verify the page count for ${e.length} PDF(s) supplied via input.content (${e.join(", ")}). Provide readable PDFs, or submit them via input.pdfFiles where page counts are derived during detection.`,category:"validation",severity:"medium",retriable:!1,context:{filenames:e,provider:t}})}static pdfPasswordRequired(){return new De({code:He.PDF_PASSWORD_REQUIRED,message:"This PDF is password-protected. Supply the password via `pdfOptions: { password: '\u2026' }` (SDK) or `--pdf-password` (CLI).",category:"validation",severity:"medium",retriable:!1})}static pdfIncorrectPassword(){return new De({code:He.PDF_INCORRECT_PASSWORD,message:"The password supplied for this PDF is incorrect. Check the `pdfOptions.password` / `--pdf-password` value and try again.",category:"validation",severity:"medium",retriable:!1})}static imageTooLarge(e,t){return new De({code:He.IMAGE_TOO_LARGE,message:`Image size (${e}MB) exceeds maximum (${t}MB)`,category:"validation",severity:"medium",retriable:!1,context:{field:"input.images",sizeMB:e,maxMB:t,suggestions:[`Compress or resize the image to under ${t}MB`,"Use a lower quality JPEG compression","Reduce image dimensions"]}})}static invalidImageSize(e){return new De({code:He.INVALID_IMAGE_SIZE,message:`Invalid image size: ${e} (must be a finite, non-negative number)`,category:"validation",severity:"medium",retriable:!1,context:{field:"input.images",size:e}})}static imageTooSmall(){return new De({code:He.IMAGE_TOO_SMALL,message:"Image data is too small to be a valid image file",category:"validation",severity:"medium",retriable:!1,context:{field:"input.images",suggestions:["Provide a valid JPEG, PNG, or WebP image file"]}})}static invalidImageFormat(){return new De({code:He.INVALID_IMAGE_FORMAT,message:"Unsupported image format. Use JPEG, PNG, or WebP",category:"validation",severity:"medium",retriable:!1,context:{field:"input.images",suggestions:["Convert your image to JPEG, PNG, or WebP format","Ensure the file is not corrupted","Check that the file extension matches the actual format"]}})}static imageBufferInvalid(e){return new De({code:He.IMAGE_BUFFER_INVALID,message:e,category:"validation",severity:"medium",retriable:!1,context:{field:"input.images"}})}static rateLimiterQueueFull(e){return new De({code:He.RATE_LIMITER_QUEUE_FULL,message:`Rate limiter queue full: too many pending requests (${e} max)`,category:"resource",severity:"high",retriable:!0,context:{maxQueueSize:e}})}static rateLimiterQueueTimeout(e){return new De({code:He.RATE_LIMITER_QUEUE_TIMEOUT,message:`Rate limiter queue timeout: request exceeded ${e}ms wait time`,category:"timeout",severity:"high",retriable:!0,context:{timeoutMs:e}})}static rateLimiterReset(){return new De({code:He.RATE_LIMITER_RESET,message:"Rate limiter was reset while request was pending",category:"execution",severity:"medium",retriable:!0,context:{}})}static missingPPTProperty(e,t){const r=[`Provide the required '${e}' field`];return new De({code:He.MISSING_PPT_PROPERTIES,message:`PPT generation requires '${e}' field`,category:"validation",severity:"medium",retriable:!1,context:{field:e,suggestions:t||r}})}static invalidPPTPages(e,t){return new De({code:He.INVALID_PPT_PAGES,message:`Invalid pages value '${e}': ${t}`,category:"validation",severity:"medium",retriable:!1,context:{field:"output.ppt.pages",providedValue:e,suggestions:["Use a number between 5 and 50","For longer presentations, consider breaking into multiple decks"]}})}static invalidPPTFormat(e){return new De({code:He.INVALID_PPT_FORMAT,message:`Invalid format '${e}'. Only 'pptx' is supported`,category:"validation",severity:"medium",retriable:!1,context:{field:"output.ppt.format",providedValue:e,suggestions:["Use format: 'pptx' or omit (defaults to 'pptx')"]}})}static invalidPPTOutputOptions(e,t,r){const n=r?r.map(o=>`Use '${o}'`):["Check the documentation for valid options"];return new De({code:He.INVALID_PPT_OUTPUT_OPTIONS,message:`Invalid ${e} value '${t}'`,category:"validation",severity:"medium",retriable:!1,context:{field:`output.ppt.${e}`,providedValue:t,suggestions:n}})}static invalidPPTOutputPath(e,t){return new De({code:He.INVALID_PPT_OUTPUT_PATH,message:`Invalid outputPath '${e}': ${t}`,category:"validation",severity:"medium",retriable:!1,context:{field:"output.ppt.outputPath",providedValue:e,suggestions:["Provide a valid file path string","Example: './presentations/my-deck.pptx'","Omit to use auto-generated path"]}})}static invalidPPTMode(){return new De({code:He.INVALID_PPT_MODE,message:"Presentation generation requires output.mode to be 'ppt'",category:"validation",severity:"medium",retriable:!1,context:{field:"output.mode",suggestions:["Set output: { mode: 'ppt' } for presentation generation"]}})}static invalidPPTPrompt(e){return new De({code:He.INVALID_PPT_PROMPT,message:`Invalid PPT prompt: ${e}`,category:"validation",severity:"medium",retriable:!1,context:{field:"input.text",suggestions:["Provide a non-empty text prompt","Keep the prompt under 1000 characters","Focus on key topics and structure for the presentation"]}})}static invalidPPTLogoPath(e,t){return new De({code:He.INVALID_PPT_LOGO_PATH,message:`Invalid logoPath '${e}': ${t}`,category:"validation",severity:"medium",retriable:!1,context:{field:"output.ppt.logoPath",providedValue:e,suggestions:["Provide a valid file path string","Example: './assets/logo.png'","Omit to skip logo inclusion"]}})}static invalidPPTProvider(e){return new De({code:He.INVALID_PPT_PROVIDER,message:`Invalid provider '${e}' for PPT generation. Supported providers: vertex, openai, azure, anthropic, google-ai, bedrock`,category:"validation",severity:"medium",retriable:!1,context:{field:"provider",providedValue:e,suggestions:["Use 'vertex' for Google Vertex AI (Gemini)","Use 'openai' for OpenAI GPT models","Use 'azure' for Azure OpenAI","Use 'anthropic' for Anthropic Claude models","Use 'google-ai' for Google AI Studio (Gemini)","Use 'bedrock' for AWS Bedrock (Claude, Llama, Nova, etc.)"]}})}static scorerNotFound(e,t){return new De({code:He.SCORER_NOT_FOUND,message:`Scorer '${e}' not found. Use neurolink.getAvailableScorers() to see available scorers.`,category:"validation",severity:"medium",retriable:!1,context:{scorerId:e,availableScorers:t}})}static evaluationValidationFailed(e,t){return new De({code:He.EVALUATION_VALIDATION_FAILED,message:`Invalid input for scorer '${e}': ${t.join(", ")}`,category:"validation",severity:"medium",retriable:!1,context:{scorerId:e,validationErrors:t}})}static evaluationTimeout(e,t){return new De({code:He.EVALUATION_TIMEOUT,message:`Evaluation ${e} timed out after ${t}ms`,category:"timeout",severity:"high",retriable:!0,context:{operation:e,timeoutMs:t}})}static evaluationExecutionFailed(e,t){return new De({code:He.EVALUATION_EXECUTION_FAILED,message:`Evaluation ${e} failed: ${t.message}`,category:"execution",severity:"high",retriable:!1,originalError:t})}static proxyWorkerLifecycle(e,t){return new De({code:He.PROXY_WORKER_LIFECYCLE_FAILED,message:e,category:"system",severity:"high",retriable:!1,context:t||{}})}static fileProcessingFailed(e,t){return new De({code:He.FILE_PROCESSING_FAILED,message:`Failed to process file "${e}": ${t.message}`,category:"execution",severity:"high",retriable:!1,context:{filename:e},originalError:t})}static csvProcessingFailed(e,t){return new De({code:He.CSV_PROCESSING_FAILED,message:`Failed to process CSV file "${e}": ${t.message}`,category:"execution",severity:"high",retriable:!1,context:{filename:e},originalError:t})}},k4=class{constructor(e=5,t=6e4,r="tool-execution"){this.failureThreshold=e,this.resetTimeoutMs=t,this.name=r}failureThreshold;resetTimeoutMs;failures=0;lastFailureTime=0;state="closed";name;async execute(e){if(this.state==="open"){const t=this.resetTimeoutMs-(Date.now()-this.lastFailureTime);if(t>0)throw new jp({breakerName:this.name,retryAfter:new Date(this.lastFailureTime+this.resetTimeoutMs),retryAfterMs:t,breakerState:"open",failureCount:this.failures});this.state="half-open"}try{const t=await e();return this.onSuccess(),t}catch(t){throw this.onFailure(),t}}onSuccess(){this.failures=0,this.state="closed"}onFailure(){this.failures++,this.lastFailureTime=Date.now(),this.failures>=this.failureThreshold&&(this.state="open")}getState(){return this.state}getFailureCount(){return this.failures}}}}),Nbe={};Z(Nbe,{APICallError:()=>nE,InvalidToolInputError:()=>QG,NoObjectGeneratedError:()=>Lbe,NoOutputGeneratedError:()=>xu,NoSuchToolError:()=>ZG});var YG,Iy,Ry,xu,Lbe,ZG,QG,nE,rm=E({"src/lib/utils/generationErrors.ts"(){"use strict";YG=e=>Symbol.for(`vercel.ai.error.${e}`),Iy=(e,t)=>{const r=YG(t);return e!==null&&typeof e=="object"&&r in e&&e[r]===!0},Ry=class extends Error{cause;constructor(e,t,r){super(t),this.name=e,r!==void 0&&(this.cause=r),Object.defineProperty(this,YG(e),{value:!0,enumerable:!1,writable:!1})}},xu=class extends Ry{constructor(e={}){super("AI_NoOutputGeneratedError",e.message??"No output generated.",e.cause)}static isInstance(e){return Iy(e,"AI_NoOutputGeneratedError")}},Lbe=class extends Ry{text;finishReason;constructor(e={}){super("AI_NoObjectGeneratedError",e.message??"No object generated.",e.cause),this.text=e.text,this.finishReason=e.finishReason}static isInstance(e){return Iy(e,"AI_NoObjectGeneratedError")}},ZG=class extends Ry{toolName;constructor(e={}){super("AI_NoSuchToolError",e.message??`Model tried to call unavailable tool '${e.toolName??"unknown"}'.`),this.toolName=e.toolName}static isInstance(e){return Iy(e,"AI_NoSuchToolError")}},QG=class extends Ry{toolName;constructor(e={}){super("AI_InvalidToolInputError",e.message??`Invalid input for tool '${e.toolName??"unknown"}'.`,e.cause),this.toolName=e.toolName}static isInstance(e){return Iy(e,"AI_InvalidToolInputError")}},nE=class extends Ry{url;statusCode;responseBody;responseHeaders;isRetryable;requestBodyValues;constructor(e={}){super("AI_APICallError",e.message??"API call error.",e.cause),this.url=e.url,this.statusCode=e.statusCode,this.responseBody=e.responseBody,this.responseHeaders=e.responseHeaders,this.isRetryable=e.isRetryable??(e.statusCode!==null&&e.statusCode!==void 0&&(e.statusCode===408||e.statusCode===409||e.statusCode===429||e.statusCode>=500)),this.requestBodyValues=e.requestBodyValues}static isInstance(e){return Iy(e,"AI_APICallError")}}}});function e8(e,t){if("get"in e&&typeof e.get=="function")return e.get(t);const r=t.toLowerCase();for(const[n,o]of Object.entries(e))if(n.toLowerCase()===r)return o;return null}function oE(e){const t=e8(e,"Retry-After");if(t){const n=parseInt(t,10);if(!Number.isNaN(n))return Math.max(0,n*1e3);const o=new Date(t);if(!Number.isNaN(o.getTime()))return Math.max(0,o.getTime()-Date.now())}const r=e8(e,"X-RateLimit-Reset");if(r){const n=parseInt(r,10);if(!Number.isNaN(n)){const o=n>1e12?n:n*1e3;return Math.max(0,o-Date.now())}}if(e8(e,"X-RateLimit-Remaining")==="0")return 1e3}var t8=E({"src/lib/utils/retryAfter.ts"(){"use strict"}});function iE(e){if(!e||typeof e!="object")return;const t=e;if(typeof t.statusCode=="number")return t.statusCode;if(typeof t.status=="number")return t.status;const r=t.$metadata;if(typeof r=="object"&&r!==null){const n=r.httpStatusCode;if(typeof n=="number")return n}}function Fbe(e){if(!e||typeof e!="object")return;const t=e;if(typeof t.retryAfterMs=="number"&&Number.isFinite(t.retryAfterMs))return t.retryAfterMs;for(const r of[t.headers,t.responseHeaders])if(r&&typeof r=="object"){const n=oE(r);if(n!==void 0)return n}}function $be(e){if(typeof e=="string")try{const r=JSON.parse(e)?.error;return typeof r?.type=="string"?r.type:void 0}catch{return}}function Ube(e){if(typeof e!="object"||e===null)return!1;const t=e;return t.type==="insufficient_quota"?!0:$be(t.responseBody)==="insufficient_quota"}function Bbe(e,t=0){if(t>8||e===null||typeof e!="object")return pr(e);if(pr(e))return!0;const{cause:r}=e;return r===void 0||r===e?!1:Bbe(r,t+1)}function A4r(e){if(Bbe(e)||Ube(e))return!1;if(nE.isInstance(e))return e.isRetryable;if(e instanceof De)return e.retriable;const t=iE(e);return t!==void 0?t===429||t>=500:!1}function zbe(e){return nE.isInstance(e)?e.statusCode:iE(e)}function C4r(e){if(nE.isInstance(e)&&e.responseHeaders){const t=oE(e.responseHeaders);if(t!==void 0)return t}return e instanceof De&&e.retryAfterMs!==void 0&&Number.isFinite(e.retryAfterMs)?e.retryAfterMs:Fbe(e)}async function Py(e,t,r,n=Vbe,o){for(let i=0;i<=x4;i++){o?.throwIfAborted();try{const s=await e();return t?.setAttribute("gen_ai.provider.total_attempts",i+1),i>0&&h.info(`[providerRetry] ${r} succeeded after ${i+1} attempts`),s}catch(s){const a=A4r(s),l=zbe(s),c=s instanceof Error?s.message:String(s);if(!a||i===x4)throw t?.setAttribute("gen_ai.provider.total_attempts",i+1),i>0&&t?.setAttribute("gen_ai.provider.retries_exhausted",!0),h.warn(`[providerRetry] ${r} failed (non-retryable or retries exhausted)`,{attempt:i+1,retryable:a,statusCode:l,error:c}),s;const u=C4r(s);if(u!==void 0&&u>r8){t?.setAttribute("gen_ai.provider.total_attempts",i+1),t?.addEvent("gen_ai.provider.retry_suppressed",{"retry.after_ms":u,...l!==void 0&&{"retry.status_code":l}});try{Object.assign(s,{isRetryable:!1,retryAfterMs:u})}catch{}throw h.warn(`[providerRetry] ${r} not retrying \u2014 server requested a ${Math.round(u/1e3)}s wait (cap ${r8/1e3}s); surfacing for fallback`,{attempt:i+1,retryAfterMs:u,statusCode:l}),s}const d=(u===void 0?void 0:Math.max(0,u))??Math.max(Gbe*Math.pow(2,i),qbe);t?.addEvent("gen_ai.provider.retry",{"retry.attempt":i+1,"retry.delay_ms":d,...l!==void 0&&{"retry.status_code":l},"retry.error":c.slice(0,256)}),h.warn(`[providerRetry] ${r} retrying after ${l||"unknown"} error`,{attempt:i+1,maxRetries:x4,delayMs:d,statusCode:l,error:c}),await n(d,o),o?.throwIfAborted()}}throw new Error(`[providerRetry] ${r} exhausted all retries`)}var x4,Gbe,qbe,r8,Vbe,kd=E({"src/lib/utils/providerRetry.ts"(){"use strict";Qt(),et(),z(),rm(),t8(),x4=2,Gbe=1e3,qbe=1e4,r8=6e4,Vbe=(e,t)=>new Promise((r,n)=>{if(t?.aborted){n(t.reason);return}const o=()=>{clearTimeout(i),n(t?.reason)},i=setTimeout(()=>{t?.removeEventListener("abort",o),r()},e);t?.addEventListener("abort",o,{once:!0})})}}),n8,jbe=E({"src/lib/constants/networkErrorCodes.ts"(){"use strict";n8=new Set(["ECONNRESET","ETIMEDOUT","ECONNREFUSED","EPIPE","UND_ERR_SOCKET","UND_ERR_CONNECT_TIMEOUT"])}}),sE={};Z(sE,{Agent:()=>Zbe,AsyncLocalStorage:()=>p_e,Buffer:()=>uSe,Channel:()=>QEe,DatabaseSync:()=>cSe,Duplex:()=>h_e,EventEmitter:()=>d_e,Http2ServerRequest:()=>fSe,Http2ServerResponse:()=>gSe,Interface:()=>lSe,MIMEType:()=>_Se,PassThrough:()=>f_e,PerformanceObserver:()=>XEe,Readable:()=>i8,ReadableStream:()=>g_e,Resolver:()=>KEe,STATUS_CODES:()=>yEe,TextDecoder:()=>l8,TextEncoder:()=>lE,Transform:()=>m_e,URL:()=>NEe,URLSearchParams:()=>LEe,Worker:()=>nSe,Writable:()=>s8,access:()=>J_e,appendFile:()=>A_e,appendFileSync:()=>Jbe,arch:()=>mEe,arrayBuffer:()=>ySe,availableParallelism:()=>S_e,basename:()=>o_e,builtinModules:()=>PEe,callbackify:()=>qEe,channel:()=>ZEe,chmod:()=>E_e,chmodSync:()=>__e,clearInterval:()=>bSe,clearTimeout:()=>wSe,closeSync:()=>P_e,connect:()=>vEe,constants:()=>dSe,copyFileSync:()=>I_e,cpSync:()=>Xbe,cpus:()=>cEe,createConnection:()=>wEe,createGunzip:()=>xEe,createGzip:()=>AEe,createHash:()=>Au,createHmac:()=>o8,createInterface:()=>aSe,createReadStream:()=>G_e,createRequire:()=>REe,createServer:()=>Ybe,createWriteStream:()=>z_e,debug:()=>zEe,debuglog:()=>a8,default:()=>Hbe,deflateSync:()=>bEe,deprecate:()=>GEe,deserialize:()=>rSe,dirname:()=>n_e,exec:()=>tEe,execFile:()=>nEe,execFileSync:()=>oEe,execSync:()=>rEe,existsSync:()=>w_e,extname:()=>i_e,fileURLToPath:()=>FEe,finished:()=>v_e,format:()=>DEe,freemem:()=>uEe,fstatSync:()=>M_e,get:()=>gEe,gunzip:()=>kEe,gunzipSync:()=>_Ee,gzip:()=>SEe,gzipSync:()=>EEe,hasSubscribers:()=>eSe,homedir:()=>sEe,hostname:()=>lEe,inflateSync:()=>TEe,inherits:()=>UEe,inspect:()=>aE,isAbsolute:()=>a_e,isBuiltin:()=>MEe,isDeepStrictEqual:()=>VEe,isIP:()=>hSe,isIPv4:()=>mSe,isIPv6:()=>pSe,isMainThread:()=>oSe,join:()=>t_e,loadavg:()=>k_e,lookup:()=>WEe,lstatSync:()=>N_e,mkdir:()=>j_e,mkdirSync:()=>O_e,monitorEventLoopDelay:()=>YEe,normalize:()=>u_e,ok:()=>CEe,open:()=>Z_e,openSync:()=>R_e,parentPort:()=>iSe,parse:()=>OEe,pathToFileURL:()=>$Ee,performance:()=>JEe,pipeline:()=>y_e,platform:()=>iEe,posix:()=>c_e,promises:()=>Wbe,promisify:()=>BEe,randomBytes:()=>Wh,randomUUID:()=>Qe,readFile:()=>q_e,readFileSync:()=>T_e,readdir:()=>W_e,readdirSync:()=>L_e,realpath:()=>Q_e,realpathSync:()=>C_e,relative:()=>s_e,release:()=>hEe,rename:()=>X_e,renameSync:()=>$_e,request:()=>fEe,resolve:()=>r_e,rm:()=>Y_e,rmSync:()=>B_e,rmdirSync:()=>U_e,sep:()=>l_e,serialize:()=>tSe,setImmediate:()=>x_e,setInterval:()=>TSe,setTimeout:()=>vSe,spawn:()=>eEe,stat:()=>H_e,statSync:()=>D_e,strict:()=>IEe,tmpdir:()=>aEe,toUSVString:()=>jEe,totalmem:()=>dEe,type:()=>pEe,types:()=>HEe,unlink:()=>K_e,unlinkSync:()=>F_e,validateHeaderName:()=>Qbe,validateHeaderValue:()=>e_e,webcrypto:()=>Kbe,workerData:()=>sSe,writeFile:()=>V_e,writeFileSync:()=>b_e});var oo,yn,Hbe,Wbe,Au,o8,Wh,Qe,Kbe,Jbe,Xbe,Ybe,Zbe,Qbe,e_e,t_e,r_e,n_e,o_e,i_e,s_e,a_e,l_e,c_e,u_e,d_e,p_e,i8,s8,m_e,h_e,f_e,g_e,y_e,v_e,w_e,T_e,b_e,__e,E_e,S_e,k_e,x_e,A_e,C_e,I_e,R_e,P_e,M_e,O_e,D_e,N_e,L_e,F_e,$_e,U_e,B_e,z_e,G_e,q_e,V_e,j_e,H_e,W_e,K_e,J_e,X_e,Y_e,Z_e,Q_e,eEe,tEe,rEe,nEe,oEe,iEe,sEe,aEe,lEe,cEe,uEe,dEe,pEe,mEe,hEe,fEe,gEe,yEe,vEe,wEe,TEe,bEe,_Ee,EEe,SEe,kEe,xEe,AEe,CEe,IEe,REe,PEe,MEe,OEe,DEe,NEe,LEe,FEe,$Ee,UEe,BEe,a8,zEe,aE,GEe,qEe,VEe,jEe,HEe,l8,lE,WEe,KEe,JEe,XEe,YEe,ZEe,QEe,eSe,tSe,rSe,nSe,oSe,iSe,sSe,aSe,lSe,cSe,uSe,dSe,pSe,mSe,hSe,fSe,gSe,ySe,c8,vSe,wSe,TSe,bSe,_Se,$t=E({"node-stub:crypto"(){oo=()=>{},yn=async()=>{},Hbe={},Wbe={readFile:yn,writeFile:yn,mkdir:yn,stat:yn,readdir:yn,unlink:yn,access:yn,rm:yn,rename:yn},Au=e=>{const t=[];return{update(r){return t.push(typeof r=="string"?new lE().encode(r):r),this},digest(r){let n=0;for(const i of t)for(let s=0;s<i.length;s++)n=(n<<5)-n+i[s]|0;const o=(n>>>0).toString(16).padStart(8,"0");return r==="hex"?o:r==="base64"?btoa(o):o}}},o8=(e,t)=>Au(e),Wh=e=>new Uint8Array(e||32),Qe=()=>globalThis.crypto?.randomUUID?.()||Math.random().toString(36),Kbe=globalThis.crypto,Jbe=()=>{throw new Error("[NeuroLink:browser] fs.appendFileSync is not supported in browser runtime \u2014 use server-side execution")},Xbe=()=>{throw new Error("[NeuroLink:browser] fs.cpSync is not supported in browser runtime \u2014 use server-side execution")},Ybe=()=>({listen:oo,close:oo,on:oo}),Zbe=class{constructor(){throw new Error("[NeuroLink:browser] Node HTTP agents require a server runtime")}},Qbe=oo,e_e=oo,t_e=(...e)=>e.join("/"),r_e=(...e)=>e.join("/"),n_e=e=>e||"",o_e=e=>e?.split?.("/")?.pop?.()||"",i_e=e=>{const t=e?.match?.(/\.[^.]+$/);return t?t[0]:""},s_e=(e,t)=>t||"",a_e=()=>!1,l_e="/",c_e={normalize:e=>e,join:(...e)=>e.join("/"),resolve:(...e)=>e.join("/"),sep:"/"},u_e=e=>e,d_e=class{constructor(){this._ev=new Map}_list(t){let r=this._ev.get(t);return r||(r=[],this._ev.set(t,r)),r}on(t,r){return this._list(t).push(r),this}addListener(t,r){return this.on(t,r)}prependListener(t,r){return this._list(t).unshift(r),this}once(t,r){const n=(...o)=>{this.off(t,n),r(...o)};return n.listener=r,this.on(t,n)}prependOnceListener(t,r){const n=(...o)=>{this.off(t,n),r(...o)};return n.listener=r,this.prependListener(t,n)}off(t,r){const n=this._ev.get(t);if(n){const o=n.findIndex(i=>i===r||i.listener===r);o>=0&&n.splice(o,1)}return this}removeListener(t,r){return this.off(t,r)}removeAllListeners(t){return t===void 0?this._ev.clear():this._ev.delete(t),this}emit(t,...r){const n=this._ev.get(t);if(!n||n.length===0){if(t==="error")throw r[0]instanceof Error?r[0]:new Error("Unhandled error.");return!1}for(const o of[...n])o.apply(this,r);return!0}listenerCount(t){return(this._ev.get(t)||[]).length}listeners(t){return[...this._ev.get(t)||[]]}rawListeners(t){return this.listeners(t)}eventNames(){return[...this._ev.keys()]}setMaxListeners(){return this}getMaxListeners(){return 10}},p_e=class{getStore(){}run(e,t,...r){return t(...r)}enterWith(){}disable(){}},i8=class{pipe(){return this}on(){return this}read(){return null}push(){}destroy(){}},s8=class{write(){return!0}end(){}on(){return this}destroy(){}},m_e=class{push(){}on(){return this}},h_e=class{on(){return this}},f_e=class{pipe(){return this}on(){return this}},g_e=globalThis.ReadableStream||class{},y_e=oo,v_e=oo,w_e=()=>!1,T_e=()=>"",b_e=oo,__e=oo,E_e=yn,S_e=()=>1,k_e=()=>[0,0,0],x_e=yn,A_e=yn,C_e=e=>e,I_e=oo,R_e=()=>0,P_e=oo,M_e=()=>({}),O_e=oo,D_e=()=>({}),N_e=()=>({isSymbolicLink:()=>!1}),L_e=()=>[],F_e=oo,$_e=oo,U_e=oo,B_e=oo,z_e=()=>new s8,G_e=()=>new i8,q_e=yn,V_e=yn,j_e=yn,H_e=yn,W_e=yn,K_e=yn,J_e=yn,X_e=yn,Y_e=yn,Z_e=async()=>({stat:yn,readFile:yn,close:yn,read:yn,write:yn}),Q_e=async e=>e,eEe=()=>({on:oo,stdout:{on:oo},stderr:{on:oo},kill:oo}),tEe=(e,t)=>t?.(null,"",""),rEe=()=>"",nEe=(e,t,r)=>{typeof t=="function"?t(null,"",""):r?.(null,"","")},oEe=()=>"",iEe="browser",sEe=()=>"/",aEe=()=>"/tmp",lEe=()=>"browser",cEe=()=>[{}],uEe=()=>0,dEe=()=>0,pEe=()=>"Browser",mEe=()=>"wasm",hEe=()=>"0",fEe=()=>({}),gEe=()=>({}),yEe={100:"Continue",101:"Switching Protocols",200:"OK",201:"Created",202:"Accepted",204:"No Content",206:"Partial Content",301:"Moved Permanently",302:"Found",304:"Not Modified",307:"Temporary Redirect",308:"Permanent Redirect",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",408:"Request Timeout",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Failed",413:"Payload Too Large",414:"URI Too Long",415:"Unsupported Media Type",416:"Range Not Satisfiable",417:"Expectation Failed",422:"Unprocessable Entity",425:"Too Early",426:"Upgrade Required",428:"Precondition Required",429:"Too Many Requests",431:"Request Header Fields Too Large",451:"Unavailable For Legal Reasons",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout",505:"HTTP Version Not Supported"},vEe=()=>({}),wEe=()=>({}),TEe=()=>new Uint8Array,bEe=()=>new Uint8Array,_Ee=()=>new Uint8Array,EEe=()=>new Uint8Array,SEe=(e,t)=>t?.(null,e),kEe=(e,t)=>t?.(null,e),xEe=()=>({}),AEe=()=>({}),CEe=oo,IEe={},REe=()=>()=>({}),PEe=[],MEe=()=>!1,OEe=e=>({pathname:e||"",hostname:"",protocol:"",search:"",hash:""}),DEe=()=>"",NEe=globalThis.URL,LEe=globalThis.URLSearchParams,FEe=e=>typeof e=="string"?e.replace("file://",""):e,$Ee=e=>new globalThis.URL("file://"+e),UEe=(e,t)=>{t&&(e.super_=t,Object.setPrototypeOf(e.prototype,t.prototype))},BEe=e=>(...t)=>new Promise((r,n)=>e(...t,(o,i)=>o?n(o):r(i))),a8=e=>{const t=(...r)=>{};return t.enabled=!1,t},zEe=a8,aE=e=>{try{return JSON.stringify(e,null,2)}catch{return String(e)}},aE.custom=Symbol.for("nodejs.util.inspect.custom"),aE.colors={},aE.styles={},GEe=e=>e,qEe=e=>(...t)=>{const r=t.pop();e(...t).then(n=>r(null,n)).catch(r)},VEe=(e,t)=>JSON.stringify(e)===JSON.stringify(t),jEe=e=>String(e),HEe={isPromise:e=>e instanceof Promise,isDate:e=>e instanceof Date,isRegExp:e=>e instanceof RegExp,isNativeError:e=>e instanceof Error,isArrayBuffer:e=>e instanceof ArrayBuffer,isTypedArray:e=>ArrayBuffer.isView(e),isUint8Array:e=>e instanceof Uint8Array,isProxy:()=>!1},l8=globalThis.TextDecoder,lE=globalThis.TextEncoder,WEe=(e,t)=>t?.(null,"127.0.0.1",4),KEe=class{},JEe=globalThis.performance||{now:()=>Date.now()},XEe=class{observe(){}disconnect(){}},YEe=()=>({enable:oo,disable:oo,percentile:()=>0}),ZEe=()=>({}),QEe=class{},eSe=()=>!1,tSe=()=>new Uint8Array,rSe=oo,nSe=class{},oSe=!0,iSe=null,sSe=null,aSe=()=>({}),lSe=class{},cSe=class{},uSe=globalThis.Buffer||class extends Uint8Array{static from(t,r){if(typeof t=="string"){const n=(r||"utf8").toLowerCase();if(n==="base64"){const o=atob(t),i=new Uint8Array(o.length);for(let s=0;s<o.length;s++)i[s]=o.charCodeAt(s);return i}if(n==="hex"){const o=new Uint8Array(t.length/2);for(let i=0;i<t.length;i+=2)o[i/2]=parseInt(t.substr(i,2),16);return o}return new lE().encode(t)}return new Uint8Array(t)}static alloc(t){return new Uint8Array(t)}static isBuffer(t){return t instanceof Uint8Array}static concat(t){const r=t.reduce((i,s)=>i+s.length,0),n=new Uint8Array(r);let o=0;for(const i of t)n.set(i,o),o+=i.length;return n}static byteLength(t,r){return r==="base64"?Math.ceil(t.length*3/4):new lE().encode(t).length}toString(t){const r=(t||"utf8").toLowerCase();if(r==="hex")return Array.from(new Uint8Array(this.buffer,this.byteOffset,this.byteLength)).map(n=>n.toString(16).padStart(2,"0")).join("");if(r==="base64"){let n="";for(let o=0;o<this.length;o++)n+=String.fromCharCode(this[o]);return btoa(n)}return new l8().decode(this)}},dSe={F_OK:0,R_OK:4,W_OK:2,X_OK:1},pSe=()=>!1,mSe=()=>!1,hSe=()=>0,fSe=class{},gSe=class{},ySe=async()=>new ArrayBuffer(0),c8=e=>({[Symbol.toPrimitive](){return e},ref(){return this},unref(){return this},hasRef(){return!1},refresh(){return this},close(){}}),vSe=(...e)=>c8(globalThis.setTimeout(...e)),wSe=globalThis.clearTimeout,TSe=(...e)=>c8(globalThis.setInterval(...e)),bSe=globalThis.clearInterval,_Se=class{constructor(e){this.type=e}toString(){return this.type}}}}),nm={};Z(nm,{Agent:()=>PSe,AsyncLocalStorage:()=>LSe,Buffer:()=>Dxe,Channel:()=>Exe,DatabaseSync:()=>Oxe,Duplex:()=>$Se,EventEmitter:()=>NSe,Http2ServerRequest:()=>Uxe,Http2ServerResponse:()=>Bxe,Interface:()=>Mxe,MIMEType:()=>Hxe,PassThrough:()=>USe,PerformanceObserver:()=>Txe,Readable:()=>f8,ReadableStream:()=>BSe,Resolver:()=>vxe,STATUS_CODES:()=>zke,TextDecoder:()=>v8,TextEncoder:()=>uE,Transform:()=>FSe,URL:()=>ixe,URLSearchParams:()=>sxe,Worker:()=>Axe,Writable:()=>g8,access:()=>wke,appendFile:()=>YSe,appendFileSync:()=>CSe,arch:()=>Fke,arrayBuffer:()=>zxe,availableParallelism:()=>KSe,basename:()=>Ms,builtinModules:()=>txe,callbackify:()=>mxe,channel:()=>_xe,chmod:()=>WSe,chmodSync:()=>HSe,clearInterval:()=>jxe,clearTimeout:()=>qxe,closeSync:()=>tke,connect:()=>Gke,constants:()=>Nxe,copyFileSync:()=>QSe,cpSync:()=>ISe,cpus:()=>Oke,createConnection:()=>qke,createGunzip:()=>Xke,createGzip:()=>Yke,createHash:()=>u8,createHmac:()=>SSe,createInterface:()=>Pxe,createReadStream:()=>pke,createRequire:()=>exe,createServer:()=>RSe,createWriteStream:()=>dke,debug:()=>dxe,debuglog:()=>y8,default:()=>om,deflateSync:()=>jke,deprecate:()=>pxe,deserialize:()=>xxe,dirname:()=>d8,exec:()=>kke,execFile:()=>Ake,execFileSync:()=>Cke,execSync:()=>xke,existsSync:()=>qSe,extname:()=>Li,fileURLToPath:()=>axe,finished:()=>GSe,format:()=>oxe,freemem:()=>Dke,fstatSync:()=>rke,get:()=>Bke,gunzip:()=>Jke,gunzipSync:()=>Hke,gzip:()=>Kke,gzipSync:()=>Wke,hasSubscribers:()=>Sxe,homedir:()=>Rke,hostname:()=>Mke,inflateSync:()=>Vke,inherits:()=>cxe,inspect:()=>cE,isAbsolute:()=>A4,isBuiltin:()=>rxe,isDeepStrictEqual:()=>hxe,isIP:()=>$xe,isIPv4:()=>Fxe,isIPv6:()=>Lxe,isMainThread:()=>Cxe,join:()=>Rt,loadavg:()=>JSe,lookup:()=>yxe,lstatSync:()=>ike,mkdir:()=>fke,mkdirSync:()=>nke,monitorEventLoopDelay:()=>bxe,normalize:()=>DSe,ok:()=>Zke,open:()=>_ke,openSync:()=>eke,parentPort:()=>Ixe,parse:()=>nxe,pathToFileURL:()=>lxe,performance:()=>wxe,pipeline:()=>zSe,platform:()=>Ike,posix:()=>h8,promises:()=>ESe,promisify:()=>uxe,randomBytes:()=>kSe,randomUUID:()=>xSe,readFile:()=>mke,readFileSync:()=>VSe,readdir:()=>yke,readdirSync:()=>ske,realpath:()=>Eke,realpathSync:()=>ZSe,relative:()=>p8,release:()=>$ke,rename:()=>Tke,renameSync:()=>lke,request:()=>Uke,resolve:()=>Kh,rm:()=>bke,rmSync:()=>uke,rmdirSync:()=>cke,sep:()=>m8,serialize:()=>kxe,setImmediate:()=>XSe,setInterval:()=>Vxe,setTimeout:()=>Gxe,spawn:()=>Ske,stat:()=>gke,statSync:()=>oke,strict:()=>Qke,tmpdir:()=>Pke,toUSVString:()=>fxe,totalmem:()=>Nke,type:()=>Lke,types:()=>gxe,unlink:()=>vke,unlinkSync:()=>ake,validateHeaderName:()=>MSe,validateHeaderValue:()=>OSe,webcrypto:()=>ASe,workerData:()=>Rxe,writeFile:()=>hke,writeFileSync:()=>jSe});var io,vn,om,ESe,u8,SSe,kSe,xSe,ASe,CSe,ISe,RSe,PSe,MSe,OSe,Rt,Kh,d8,Ms,Li,p8,A4,m8,h8,DSe,NSe,LSe,f8,g8,FSe,$Se,USe,BSe,zSe,GSe,qSe,VSe,jSe,HSe,WSe,KSe,JSe,XSe,YSe,ZSe,QSe,eke,tke,rke,nke,oke,ike,ske,ake,lke,cke,uke,dke,pke,mke,hke,fke,gke,yke,vke,wke,Tke,bke,_ke,Eke,Ske,kke,xke,Ake,Cke,Ike,Rke,Pke,Mke,Oke,Dke,Nke,Lke,Fke,$ke,Uke,Bke,zke,Gke,qke,Vke,jke,Hke,Wke,Kke,Jke,Xke,Yke,Zke,Qke,exe,txe,rxe,nxe,oxe,ixe,sxe,axe,lxe,cxe,uxe,y8,dxe,cE,pxe,mxe,hxe,fxe,gxe,v8,uE,yxe,vxe,wxe,Txe,bxe,_xe,Exe,Sxe,kxe,xxe,Axe,Cxe,Ixe,Rxe,Pxe,Mxe,Oxe,Dxe,Nxe,Lxe,Fxe,$xe,Uxe,Bxe,zxe,w8,Gxe,qxe,Vxe,jxe,Hxe,kr=E({"node-stub:path"(){io=()=>{},vn=async()=>{},om={},ESe={readFile:vn,writeFile:vn,mkdir:vn,stat:vn,readdir:vn,unlink:vn,access:vn,rm:vn,rename:vn},u8=e=>{const t=[];return{update(r){return t.push(typeof r=="string"?new uE().encode(r):r),this},digest(r){let n=0;for(const i of t)for(let s=0;s<i.length;s++)n=(n<<5)-n+i[s]|0;const o=(n>>>0).toString(16).padStart(8,"0");return r==="hex"?o:r==="base64"?btoa(o):o}}},SSe=(e,t)=>u8(e),kSe=e=>new Uint8Array(e||32),xSe=()=>globalThis.crypto?.randomUUID?.()||Math.random().toString(36),ASe=globalThis.crypto,CSe=()=>{throw new Error("[NeuroLink:browser] fs.appendFileSync is not supported in browser runtime \u2014 use server-side execution")},ISe=()=>{throw new Error("[NeuroLink:browser] fs.cpSync is not supported in browser runtime \u2014 use server-side execution")},RSe=()=>({listen:io,close:io,on:io}),PSe=class{constructor(){throw new Error("[NeuroLink:browser] Node HTTP agents require a server runtime")}},MSe=io,OSe=io,Rt=(...e)=>e.join("/"),Kh=(...e)=>e.join("/"),d8=e=>e||"",Ms=e=>e?.split?.("/")?.pop?.()||"",Li=e=>{const t=e?.match?.(/\.[^.]+$/);return t?t[0]:""},p8=(e,t)=>t||"",A4=()=>!1,m8="/",h8={normalize:e=>e,join:(...e)=>e.join("/"),resolve:(...e)=>e.join("/"),sep:"/"},DSe=e=>e,NSe=class{constructor(){this._ev=new Map}_list(t){let r=this._ev.get(t);return r||(r=[],this._ev.set(t,r)),r}on(t,r){return this._list(t).push(r),this}addListener(t,r){return this.on(t,r)}prependListener(t,r){return this._list(t).unshift(r),this}once(t,r){const n=(...o)=>{this.off(t,n),r(...o)};return n.listener=r,this.on(t,n)}prependOnceListener(t,r){const n=(...o)=>{this.off(t,n),r(...o)};return n.listener=r,this.prependListener(t,n)}off(t,r){const n=this._ev.get(t);if(n){const o=n.findIndex(i=>i===r||i.listener===r);o>=0&&n.splice(o,1)}return this}removeListener(t,r){return this.off(t,r)}removeAllListeners(t){return t===void 0?this._ev.clear():this._ev.delete(t),this}emit(t,...r){const n=this._ev.get(t);if(!n||n.length===0){if(t==="error")throw r[0]instanceof Error?r[0]:new Error("Unhandled error.");return!1}for(const o of[...n])o.apply(this,r);return!0}listenerCount(t){return(this._ev.get(t)||[]).length}listeners(t){return[...this._ev.get(t)||[]]}rawListeners(t){return this.listeners(t)}eventNames(){return[...this._ev.keys()]}setMaxListeners(){return this}getMaxListeners(){return 10}},LSe=class{getStore(){}run(e,t,...r){return t(...r)}enterWith(){}disable(){}},f8=class{pipe(){return this}on(){return this}read(){return null}push(){}destroy(){}},g8=class{write(){return!0}end(){}on(){return this}destroy(){}},FSe=class{push(){}on(){return this}},$Se=class{on(){return this}},USe=class{pipe(){return this}on(){return this}},BSe=globalThis.ReadableStream||class{},zSe=io,GSe=io,qSe=()=>!1,VSe=()=>"",jSe=io,HSe=io,WSe=vn,KSe=()=>1,JSe=()=>[0,0,0],XSe=vn,YSe=vn,ZSe=e=>e,QSe=io,eke=()=>0,tke=io,rke=()=>({}),nke=io,oke=()=>({}),ike=()=>({isSymbolicLink:()=>!1}),ske=()=>[],ake=io,lke=io,cke=io,uke=io,dke=()=>new g8,pke=()=>new f8,mke=vn,hke=vn,fke=vn,gke=vn,yke=vn,vke=vn,wke=vn,Tke=vn,bke=vn,_ke=async()=>({stat:vn,readFile:vn,close:vn,read:vn,write:vn}),Eke=async e=>e,Ske=()=>({on:io,stdout:{on:io},stderr:{on:io},kill:io}),kke=(e,t)=>t?.(null,"",""),xke=()=>"",Ake=(e,t,r)=>{typeof t=="function"?t(null,"",""):r?.(null,"","")},Cke=()=>"",Ike="browser",Rke=()=>"/",Pke=()=>"/tmp",Mke=()=>"browser",Oke=()=>[{}],Dke=()=>0,Nke=()=>0,Lke=()=>"Browser",Fke=()=>"wasm",$ke=()=>"0",Uke=()=>({}),Bke=()=>({}),zke={100:"Continue",101:"Switching Protocols",200:"OK",201:"Created",202:"Accepted",204:"No Content",206:"Partial Content",301:"Moved Permanently",302:"Found",304:"Not Modified",307:"Temporary Redirect",308:"Permanent Redirect",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",408:"Request Timeout",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Failed",413:"Payload Too Large",414:"URI Too Long",415:"Unsupported Media Type",416:"Range Not Satisfiable",417:"Expectation Failed",422:"Unprocessable Entity",425:"Too Early",426:"Upgrade Required",428:"Precondition Required",429:"Too Many Requests",431:"Request Header Fields Too Large",451:"Unavailable For Legal Reasons",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout",505:"HTTP Version Not Supported"},Gke=()=>({}),qke=()=>({}),Vke=()=>new Uint8Array,jke=()=>new Uint8Array,Hke=()=>new Uint8Array,Wke=()=>new Uint8Array,Kke=(e,t)=>t?.(null,e),Jke=(e,t)=>t?.(null,e),Xke=()=>({}),Yke=()=>({}),Zke=io,Qke={},exe=()=>()=>({}),txe=[],rxe=()=>!1,nxe=e=>({pathname:e||"",hostname:"",protocol:"",search:"",hash:""}),oxe=()=>"",ixe=globalThis.URL,sxe=globalThis.URLSearchParams,axe=e=>typeof e=="string"?e.replace("file://",""):e,lxe=e=>new globalThis.URL("file://"+e),cxe=(e,t)=>{t&&(e.super_=t,Object.setPrototypeOf(e.prototype,t.prototype))},uxe=e=>(...t)=>new Promise((r,n)=>e(...t,(o,i)=>o?n(o):r(i))),y8=e=>{const t=(...r)=>{};return t.enabled=!1,t},dxe=y8,cE=e=>{try{return JSON.stringify(e,null,2)}catch{return String(e)}},cE.custom=Symbol.for("nodejs.util.inspect.custom"),cE.colors={},cE.styles={},pxe=e=>e,mxe=e=>(...t)=>{const r=t.pop();e(...t).then(n=>r(null,n)).catch(r)},hxe=(e,t)=>JSON.stringify(e)===JSON.stringify(t),fxe=e=>String(e),gxe={isPromise:e=>e instanceof Promise,isDate:e=>e instanceof Date,isRegExp:e=>e instanceof RegExp,isNativeError:e=>e instanceof Error,isArrayBuffer:e=>e instanceof ArrayBuffer,isTypedArray:e=>ArrayBuffer.isView(e),isUint8Array:e=>e instanceof Uint8Array,isProxy:()=>!1},v8=globalThis.TextDecoder,uE=globalThis.TextEncoder,yxe=(e,t)=>t?.(null,"127.0.0.1",4),vxe=class{},wxe=globalThis.performance||{now:()=>Date.now()},Txe=class{observe(){}disconnect(){}},bxe=()=>({enable:io,disable:io,percentile:()=>0}),_xe=()=>({}),Exe=class{},Sxe=()=>!1,kxe=()=>new Uint8Array,xxe=io,Axe=class{},Cxe=!0,Ixe=null,Rxe=null,Pxe=()=>({}),Mxe=class{},Oxe=class{},Dxe=globalThis.Buffer||class extends Uint8Array{static from(t,r){if(typeof t=="string"){const n=(r||"utf8").toLowerCase();if(n==="base64"){const o=atob(t),i=new Uint8Array(o.length);for(let s=0;s<o.length;s++)i[s]=o.charCodeAt(s);return i}if(n==="hex"){const o=new Uint8Array(t.length/2);for(let i=0;i<t.length;i+=2)o[i/2]=parseInt(t.substr(i,2),16);return o}return new uE().encode(t)}return new Uint8Array(t)}static alloc(t){return new Uint8Array(t)}static isBuffer(t){return t instanceof Uint8Array}static concat(t){const r=t.reduce((i,s)=>i+s.length,0),n=new Uint8Array(r);let o=0;for(const i of t)n.set(i,o),o+=i.length;return n}static byteLength(t,r){return r==="base64"?Math.ceil(t.length*3/4):new uE().encode(t).length}toString(t){const r=(t||"utf8").toLowerCase();if(r==="hex")return Array.from(new Uint8Array(this.buffer,this.byteOffset,this.byteLength)).map(n=>n.toString(16).padStart(2,"0")).join("");if(r==="base64"){let n="";for(let o=0;o<this.length;o++)n+=String.fromCharCode(this[o]);return btoa(n)}return new v8().decode(this)}},Nxe={F_OK:0,R_OK:4,W_OK:2,X_OK:1},Lxe=()=>!1,Fxe=()=>!1,$xe=()=>0,Uxe=class{},Bxe=class{},zxe=async()=>new ArrayBuffer(0),w8=e=>({[Symbol.toPrimitive](){return e},ref(){return this},unref(){return this},hasRef(){return!1},refresh(){return this},close(){}}),Gxe=(...e)=>w8(globalThis.setTimeout(...e)),qxe=globalThis.clearTimeout,Vxe=(...e)=>w8(globalThis.setInterval(...e)),jxe=globalThis.clearInterval,Hxe=class{constructor(e){this.type=e}toString(){return this.type}}}});function mr(e,t=500){return e&&e.slice(0,t).replace(Yxe,"***")}function My(e){if(typeof e=="string")return e;try{return JSON.stringify(e)??String(e)}catch{return"[content too large to serialize]"}}function C4(e,t=1e4){try{const r=JSON.stringify(e);return r===void 0?String(e):r.length>t?`${r.slice(0,t)}\u2026[truncated ${r.length-t} chars]`:r}catch(r){return`[unserializable: ${r instanceof Error?r.message:String(r)}]`}}function Yo(e){return e.replace(/\/\/[^/\s"'<>]*@/g,"//***@").replace(/\/\/(?:(?!\/\/)[^\s"'<>])*@/g,"//***@")}function Xt(e){const t=r=>r.length>200?`${r.slice(0,200)}\u2026`:r;try{const r=new URL(e);return r.host===""&&!r.pathname.startsWith("/")&&r.pathname.includes("@")&&!/^[a-z]:$/i.test(r.protocol)?t(`[redacted]@${r.pathname.slice(r.pathname.lastIndexOf("@")+1)}`):t(`${r.protocol}//${r.host}${r.pathname}`)}catch{const r=e.split(/[?#]/)[0];return t(Yo(r))}}function I4r(e){eAe.forEach(t=>e.searchParams.delete(t))}function R4r(e){const t=[],r=[];for(const[o,i]of e.searchParams.entries())Qxe.includes(o.toLowerCase())&&(t.push(`${o.toLowerCase()}=${i}`),r.push(o));return t.length===0?"":(r.forEach(o=>e.searchParams.delete(o)),t.sort(),`\0auth=${Au("sha256").update(t.join("&")).digest("hex").slice(0,16)}`)}function Wxe(e){try{const t=new URL(e);I4r(t);const r=R4r(t);return t.toString()+r}catch{return e}}function dE(e){return e.replace(/[a-zA-Z][a-zA-Z0-9+.-]*:\/\/[^\s"'<>)]+/g,t=>Xt(t))}function Kxe(e,t){const r=Ms(t);return e.split(Kh(t)).join(r).split(t).join(r)}function Jh(e,t){const r=i=>{const s=dE(i);return t?.filePath?Kxe(s,t.filePath):s};if(!(e instanceof Error))return new Error(r(String(e)));const n=new Error(r(e.message));n.name=e.name;const o=e.code;return o!==void 0&&(n.code=o),n}function I4(e,t=1e3){const r=new WeakSet,n=o=>{if(o==null)return o;if(typeof o=="string")return mr(o,t);if(typeof o!="object")return o;if(r.has(o))return"[Circular]";if(r.add(o),Array.isArray(o))return o.map(n);const i={};for(const[s,a]of Object.entries(o))Zxe.some(l=>l.toLowerCase()===s.toLowerCase())?i[s]="***":i[s]=n(a);return i};return n(e)}var Jxe,Xxe,Yxe,Zxe,Qxe,eAe,Nt=E({"src/lib/utils/logSanitize.ts"(){"use strict";$t(),kr(),Jxe=["sk","pk","r8","gsk","csk","xai","tgp","fw","pplx","pa","jina","fish"],Xxe=Jxe.join("|"),Yxe=new RegExp(`\\bBearer\\s+[A-Za-z0-9_\\-\\.]{8,}\\b|\\bToken\\s+[A-Za-z0-9_\\-\\.]{8,}\\b|\\bBasic\\s+[A-Za-z0-9+/=]{12,}\\b|\\b(?:${Xxe})[_\\-][A-Za-z0-9_\\-\\.]{8,}\\b|\\b(?:api[_-]?key|access[_-]?token|secret[_-]?key|refresh[_-]?token)['"]?\\s*[:=]\\s*['"]?[^\\s,;'"&]+`,"gi"),Zxe=["apikey","api_key","apiKey","access_token","accessToken","refresh_token","refreshToken","secret","secretkey","secret_key","secretKey","password","authorization","oauth","oauthToken","credentials","authContext","authToken","sessionToken","serviceAccountKey","secretAccessKey","userEmail"],Qxe=["token","signature","x-amz-signature","x-amz-credential","x-amz-security-token","awsaccesskeyid","expires","sig","se","sp","sr","sv","x-goog-signature","x-goog-credential","x-goog-algorithm","x-goog-date","x-goog-expires","x-goog-signedheaders"],eAe=["utm_source","utm_medium","utm_campaign","utm_term","utm_content","fbclid","gclid","_ga"]}});function P4r(e){const t=[],r=new Set;let n=e;for(;n&&typeof n=="object"&&!r.has(n)&&t.length<rAe;){r.add(n);const o=n;t.push(o),n=o.cause}return t}function tAe(e,t){for(const r of e)if(typeof r[t]=="string")return r[t]}function M4r(e,t,r){const n=P4r(e),o=n[0],i=typeof o?.message=="string"?o.message:e instanceof Error?e.message:"Unknown error",s=n[n.length-1],a=typeof s?.message=="string"?dE(s.message):void 0,l=a&&a!==i?`${i}: ${a}`:i;let c;for(const u of n)if(c=iE(u),c!==void 0)break;return{error:e,message:l,statusCode:c,errorName:tAe(n,"name"),errorCode:tAe(n,"code"),provider:t,modelName:r}}function ba(e,t,r,n){if(e instanceof Ta)return new ai(`Request timed out: ${e.message}`,r);const o=M4r(e,r,n),i=t.find(a=>a.match(o));if(!i)return new ot(`${r} error: ${o.message}`,r);const s=typeof i.message=="function"?i.message(o):i.message;return new i.errorClass(s,r)}function im(e,t){if(!Number.isInteger(t)||t<100||t>599)return!1;const r=String(t);return new RegExp(`^\\s*${r}\\b|\\b(?:error|status(?:\\s*code)?)\\b\\D{0,12}\\b${r}\\b|\\bhttp(?:/\\d(?:\\.\\d)?)?[\\s:-]{0,3}${r}\\b|\\b${r}\\b\\D{0,12}\\berror\\b`,"i").test(e)}var rAe,R4,nAe,T8,oAe,iAe,Ll,Zs=E({"src/lib/utils/errorClassifier.ts"(){"use strict";pt(),Ys(),kd(),jbe(),Nt(),rAe=5,R4="(?![\\s-]+(?:route|gateway|endpoint|url|path|proxy|server|service|api|host)s?(?![\\w-]))",nAe=`\\bmodel\\b${R4}`,T8=`\\b(?:model|deployment)\\b${R4}`,oAe=`(?:unknown|no such|invalid|unsupported) model${R4}`,iAe=new RegExp(`model[_ ]?not[_ ]?found|${oAe}|${T8}.{0,120}\\b(?:does not exist|not found|unavailable|not (?:available|supported))\\b|\\b(?:does not exist|not found)\\b.{0,120}${T8}|unable to access.{0,60}${nAe}`,"i"),Ll=[{match:e=>e.statusCode===401||/API_KEY_INVALID|Invalid API key|Unauthorized|invalid_api_key/i.test(e.message),errorClass:Wr,message:e=>`Invalid ${e.provider} API key. Please check your credentials.`},{match:e=>e.statusCode===429||/rate limit/i.test(e.message),errorClass:Qi,message:e=>`${e.provider} rate limit exceeded. Please try again later.`},{match:e=>/model_not_found|model not found/i.test(e.message)||e.statusCode===404&&iAe.test(e.message),errorClass:Jo,message:e=>e.modelName?`${e.provider} model '${e.modelName}' not found.`:`${e.provider} model not found.`},{match:e=>e.statusCode===404,errorClass:ot,message:e=>`${e.provider} returned HTTP 404: ${e.message}`},{match:e=>/ECONNRESET|ENOTFOUND|ECONNREFUSED|ETIMEDOUT|network|connection/i.test(e.message)||e.errorCode!==void 0&&n8.has(e.errorCode),errorClass:ai,message:e=>`Connection error: ${e.message}`},{match:e=>e.statusCode!==void 0&&e.statusCode>=500&&e.statusCode<=599||/server error|bad gateway|service unavailable|gateway timeout|\berror\b\D{0,12}\b5\d\d\b|\b5\d\d\b\D{0,12}\berror\b|\bstatus(?:\s*code)?\b\D{0,12}\b5\d\d\b/i.test(e.message),errorClass:ot,message:e=>`${e.provider} server error: ${e.message}`}]}});function O4r(e){return e.replace(/-([a-z])/g,(t,r)=>r.toUpperCase())}function D4r(e){return e.credentialsKey??O4r(e.id)}function Cu(e,t){const r=e.wire.envOverrides?.[t];if(r)return r;const n=e.id.toUpperCase().replace(/-/g,"_");return t==="apiKey"?`${n}_API_KEY`:t==="baseURL"?`${n}_BASE_URL`:`${n}_MODEL`}function b8(e,t,r,n){return e.replace(/\{apiKeyEnvVar\}/g,Cu(t,"apiKey")).replace(/\{setupUrl\}/g,t.setup.url).replace(/\{model\}/g,r??"").replace(/\{message\}/g,n??"")}function N4r(e){return{providerName:e.displayName,envVarName:Cu(e,"apiKey"),setupUrl:e.setup.url,description:e.setup.description??"API key",instructions:e.setup.instructions.map(t=>b8(t,e)),...e.wire.apiKeyFallbackEnvVars?{fallbackEnvVars:e.wire.apiKeyFallbackEnvVars}:{}}}function L4r(e){return[...e.errorRules.map(r=>{const n=r.pattern?new RegExp(r.pattern,"i"):void 0,o=r.message.includes("{model}")||r.message.includes("{message}");return{match:i=>r.status!==void 0&&i.statusCode===r.status||n!==void 0&&(r.patternStatuses===void 0||i.statusCode!==void 0&&r.patternStatuses.includes(i.statusCode))&&n.test(i.message),errorClass:sAe[r.class],message:o?i=>b8(r.message,e,i.modelName,i.message):b8(r.message,e)}}),...Ll]}function _8(e){if(Array.isArray(e)){for(const t of e)_8(t);return Object.freeze(e)}if(e!==null&&typeof e=="object"){for(const t of Object.keys(e))_8(e[t]);return Object.freeze(e)}return e}function Oy(){return _8(structuredClone(N6))}function F4r(){return N6.map(e=>{const t={providerName:e.id,aliases:[e.id,...e.aliases],apiKeyEnvVar:Cu(e,"apiKey"),configOptions:N4r(e),modelEnvVar:Cu(e,"model"),defaultModel:e.models.default,registryDefaultModel:e.models.registryDefaultModel??e.models.default,registryDefaultModelChecksEnvVar:e.quirks?.registryDefaultIgnoresModelEnvVar!==!0,fallbackModelName:e.models.fallbackModelName??e.models.fallbacks[1]??e.models.fallbacks[0],fallbackModels:[...e.models.fallbacks],errorRules:L4r(e),...typeof e.capabilities.tools=="boolean"?{supportsTools:e.capabilities.tools}:{},supportsStructuredOutputWithTools:e.capabilities.structuredOutputWithTools},{baseURLTemplate:r}=e.wire;if(r){const n=e.wire.extraCredentials?.[0]??"accountId";t.computedBaseURL={envVar:`${e.id.toUpperCase().replace(/-/g,"_")}_${n.replace(/([A-Z])/g,"_$1").toUpperCase()}`,missingValueMessage:e.wire.missingCredentialMessage??`Missing ${n} for ${e.displayName}`,build:o=>r.replaceAll(`{${n}}`,o)}}else t.baseURLEnvVar=Cu(e,"baseURL"),t.defaultBaseURL=e.wire.baseURL;return e.quirks?.messageContentFormat&&(t.messageContentFormat=e.quirks.messageContentFormat),e.quirks?.timeoutErrorClass==="provider"&&(t.timeoutErrorClass=ot),e.quirks?.responseFormatDowngrade&&(t.responseFormatDowngrade=e.quirks.responseFormatDowngrade),e.quirks?.replayReasoningContent&&(t.replayReasoningContent=!0),e.quirks?.authHeaderStyle&&(t.authHeaderStyle=e.quirks.authHeaderStyle),t})}var sAe,Dy=E({"src/lib/providers/catalog/loader.ts"(){"use strict";Kkr(),Zs(),pt(),sAe={authentication:Wr,"rate-limit":Qi,"invalid-model":Jo,network:ai,provider:ot}}});function _a(e){let t=process.env[e.envVarName];if(!t&&e.fallbackEnvVars){for(const r of e.fallbackEnvVars)if(t=process.env[r],t)break}if(!t){if(e.optional)return"";throw new Error($4r(e))}return t}function $4r(e){const t=e.fallbackEnvVars?[e.envVarName,...e.fallbackEnvVars].join(" or "):e.envVarName;return`\u274C ${e.providerName} Provider Configuration Error
|
|
66
|
+
`),category:"validation",severity:"medium",retriable:!1,context:{estimatedPages:e,maxPages:t,provider:r,alternatives:n}})}static pdfAggregatePageLimitExceeded(e,t,r,n){return new De({code:He.PDF_AGGREGATE_PAGE_LIMIT_EXCEEDED,message:`[PDF] Combined page count across ${e} PDF(s) (${t}) exceeds the ${r}-page limit for ${n}. Split the request or reduce the number of PDFs.`,category:"validation",severity:"medium",retriable:!1,context:{fileCount:e,totalPages:t,maxPages:r,provider:n}})}static pdfAggregateSizeLimitExceeded(e,t,r,n){return new De({code:He.PDF_AGGREGATE_SIZE_LIMIT_EXCEEDED,message:`[PDF] Combined size across ${e} PDF(s) (${t.toFixed(2)}MB) exceeds the ${r}MB limit for ${n}.`,category:"validation",severity:"medium",retriable:!1,context:{fileCount:e,totalMB:t,maxSizeMB:r,provider:n}})}static pdfPageCountUnverifiable(e,t){return new De({code:He.PDF_PAGE_COUNT_UNVERIFIABLE,message:`[PDF] Cannot verify the page count for ${e.length} PDF(s) supplied via input.content (${e.join(", ")}). Provide readable PDFs, or submit them via input.pdfFiles where page counts are derived during detection.`,category:"validation",severity:"medium",retriable:!1,context:{filenames:e,provider:t}})}static pdfPasswordRequired(){return new De({code:He.PDF_PASSWORD_REQUIRED,message:"This PDF is password-protected. Supply the password via `pdfOptions: { password: '\u2026' }` (SDK) or `--pdf-password` (CLI).",category:"validation",severity:"medium",retriable:!1})}static pdfIncorrectPassword(){return new De({code:He.PDF_INCORRECT_PASSWORD,message:"The password supplied for this PDF is incorrect. Check the `pdfOptions.password` / `--pdf-password` value and try again.",category:"validation",severity:"medium",retriable:!1})}static imageTooLarge(e,t){return new De({code:He.IMAGE_TOO_LARGE,message:`Image size (${e}MB) exceeds maximum (${t}MB)`,category:"validation",severity:"medium",retriable:!1,context:{field:"input.images",sizeMB:e,maxMB:t,suggestions:[`Compress or resize the image to under ${t}MB`,"Use a lower quality JPEG compression","Reduce image dimensions"]}})}static invalidImageSize(e){return new De({code:He.INVALID_IMAGE_SIZE,message:`Invalid image size: ${e} (must be a finite, non-negative number)`,category:"validation",severity:"medium",retriable:!1,context:{field:"input.images",size:e}})}static imageTooSmall(){return new De({code:He.IMAGE_TOO_SMALL,message:"Image data is too small to be a valid image file",category:"validation",severity:"medium",retriable:!1,context:{field:"input.images",suggestions:["Provide a valid JPEG, PNG, or WebP image file"]}})}static invalidImageFormat(){return new De({code:He.INVALID_IMAGE_FORMAT,message:"Unsupported image format. Use JPEG, PNG, or WebP",category:"validation",severity:"medium",retriable:!1,context:{field:"input.images",suggestions:["Convert your image to JPEG, PNG, or WebP format","Ensure the file is not corrupted","Check that the file extension matches the actual format"]}})}static imageBufferInvalid(e){return new De({code:He.IMAGE_BUFFER_INVALID,message:e,category:"validation",severity:"medium",retriable:!1,context:{field:"input.images"}})}static rateLimiterQueueFull(e){return new De({code:He.RATE_LIMITER_QUEUE_FULL,message:`Rate limiter queue full: too many pending requests (${e} max)`,category:"resource",severity:"high",retriable:!0,context:{maxQueueSize:e}})}static rateLimiterQueueTimeout(e){return new De({code:He.RATE_LIMITER_QUEUE_TIMEOUT,message:`Rate limiter queue timeout: request exceeded ${e}ms wait time`,category:"timeout",severity:"high",retriable:!0,context:{timeoutMs:e}})}static rateLimiterReset(){return new De({code:He.RATE_LIMITER_RESET,message:"Rate limiter was reset while request was pending",category:"execution",severity:"medium",retriable:!0,context:{}})}static missingPPTProperty(e,t){const r=[`Provide the required '${e}' field`];return new De({code:He.MISSING_PPT_PROPERTIES,message:`PPT generation requires '${e}' field`,category:"validation",severity:"medium",retriable:!1,context:{field:e,suggestions:t||r}})}static invalidPPTPages(e,t){return new De({code:He.INVALID_PPT_PAGES,message:`Invalid pages value '${e}': ${t}`,category:"validation",severity:"medium",retriable:!1,context:{field:"output.ppt.pages",providedValue:e,suggestions:["Use a number between 5 and 50","For longer presentations, consider breaking into multiple decks"]}})}static invalidPPTFormat(e){return new De({code:He.INVALID_PPT_FORMAT,message:`Invalid format '${e}'. Only 'pptx' is supported`,category:"validation",severity:"medium",retriable:!1,context:{field:"output.ppt.format",providedValue:e,suggestions:["Use format: 'pptx' or omit (defaults to 'pptx')"]}})}static invalidPPTOutputOptions(e,t,r){const n=r?r.map(o=>`Use '${o}'`):["Check the documentation for valid options"];return new De({code:He.INVALID_PPT_OUTPUT_OPTIONS,message:`Invalid ${e} value '${t}'`,category:"validation",severity:"medium",retriable:!1,context:{field:`output.ppt.${e}`,providedValue:t,suggestions:n}})}static invalidPPTOutputPath(e,t){return new De({code:He.INVALID_PPT_OUTPUT_PATH,message:`Invalid outputPath '${e}': ${t}`,category:"validation",severity:"medium",retriable:!1,context:{field:"output.ppt.outputPath",providedValue:e,suggestions:["Provide a valid file path string","Example: './presentations/my-deck.pptx'","Omit to use auto-generated path"]}})}static invalidPPTMode(){return new De({code:He.INVALID_PPT_MODE,message:"Presentation generation requires output.mode to be 'ppt'",category:"validation",severity:"medium",retriable:!1,context:{field:"output.mode",suggestions:["Set output: { mode: 'ppt' } for presentation generation"]}})}static invalidPPTPrompt(e){return new De({code:He.INVALID_PPT_PROMPT,message:`Invalid PPT prompt: ${e}`,category:"validation",severity:"medium",retriable:!1,context:{field:"input.text",suggestions:["Provide a non-empty text prompt","Keep the prompt under 1000 characters","Focus on key topics and structure for the presentation"]}})}static invalidPPTLogoPath(e,t){return new De({code:He.INVALID_PPT_LOGO_PATH,message:`Invalid logoPath '${e}': ${t}`,category:"validation",severity:"medium",retriable:!1,context:{field:"output.ppt.logoPath",providedValue:e,suggestions:["Provide a valid file path string","Example: './assets/logo.png'","Omit to skip logo inclusion"]}})}static invalidPPTProvider(e){return new De({code:He.INVALID_PPT_PROVIDER,message:`Invalid provider '${e}' for PPT generation. Supported providers: vertex, openai, azure, anthropic, google-ai, bedrock`,category:"validation",severity:"medium",retriable:!1,context:{field:"provider",providedValue:e,suggestions:["Use 'vertex' for Google Vertex AI (Gemini)","Use 'openai' for OpenAI GPT models","Use 'azure' for Azure OpenAI","Use 'anthropic' for Anthropic Claude models","Use 'google-ai' for Google AI Studio (Gemini)","Use 'bedrock' for AWS Bedrock (Claude, Llama, Nova, etc.)"]}})}static scorerNotFound(e,t){return new De({code:He.SCORER_NOT_FOUND,message:`Scorer '${e}' not found. Use neurolink.getAvailableScorers() to see available scorers.`,category:"validation",severity:"medium",retriable:!1,context:{scorerId:e,availableScorers:t}})}static evaluationValidationFailed(e,t){return new De({code:He.EVALUATION_VALIDATION_FAILED,message:`Invalid input for scorer '${e}': ${t.join(", ")}`,category:"validation",severity:"medium",retriable:!1,context:{scorerId:e,validationErrors:t}})}static evaluationTimeout(e,t){return new De({code:He.EVALUATION_TIMEOUT,message:`Evaluation ${e} timed out after ${t}ms`,category:"timeout",severity:"high",retriable:!0,context:{operation:e,timeoutMs:t}})}static evaluationExecutionFailed(e,t){return new De({code:He.EVALUATION_EXECUTION_FAILED,message:`Evaluation ${e} failed: ${t.message}`,category:"execution",severity:"high",retriable:!1,originalError:t})}static proxyWorkerLifecycle(e,t){return new De({code:He.PROXY_WORKER_LIFECYCLE_FAILED,message:e,category:"system",severity:"high",retriable:!1,context:t||{}})}static fileProcessingFailed(e,t){return new De({code:He.FILE_PROCESSING_FAILED,message:`Failed to process file "${e}": ${t.message}`,category:"execution",severity:"high",retriable:!1,context:{filename:e},originalError:t})}static csvProcessingFailed(e,t){return new De({code:He.CSV_PROCESSING_FAILED,message:`Failed to process CSV file "${e}": ${t.message}`,category:"execution",severity:"high",retriable:!1,context:{filename:e},originalError:t})}},k4=class{constructor(e=5,t=6e4,r="tool-execution"){this.failureThreshold=e,this.resetTimeoutMs=t,this.name=r}failureThreshold;resetTimeoutMs;failures=0;lastFailureTime=0;state="closed";name;async execute(e){if(this.state==="open"){const t=this.resetTimeoutMs-(Date.now()-this.lastFailureTime);if(t>0)throw new jp({breakerName:this.name,retryAfter:new Date(this.lastFailureTime+this.resetTimeoutMs),retryAfterMs:t,breakerState:"open",failureCount:this.failures});this.state="half-open"}try{const t=await e();return this.onSuccess(),t}catch(t){throw this.onFailure(),t}}onSuccess(){this.failures=0,this.state="closed"}onFailure(){this.failures++,this.lastFailureTime=Date.now(),this.failures>=this.failureThreshold&&(this.state="open")}getState(){return this.state}getFailureCount(){return this.failures}}}}),Nbe={};Z(Nbe,{APICallError:()=>nE,InvalidToolInputError:()=>QG,NoObjectGeneratedError:()=>Lbe,NoOutputGeneratedError:()=>xu,NoSuchToolError:()=>ZG});var YG,Iy,Ry,xu,Lbe,ZG,QG,nE,rm=E({"src/lib/utils/generationErrors.ts"(){"use strict";YG=e=>Symbol.for(`vercel.ai.error.${e}`),Iy=(e,t)=>{const r=YG(t);return e!==null&&typeof e=="object"&&r in e&&e[r]===!0},Ry=class extends Error{cause;constructor(e,t,r){super(t),this.name=e,r!==void 0&&(this.cause=r),Object.defineProperty(this,YG(e),{value:!0,enumerable:!1,writable:!1})}},xu=class extends Ry{constructor(e={}){super("AI_NoOutputGeneratedError",e.message??"No output generated.",e.cause)}static isInstance(e){return Iy(e,"AI_NoOutputGeneratedError")}},Lbe=class extends Ry{text;finishReason;constructor(e={}){super("AI_NoObjectGeneratedError",e.message??"No object generated.",e.cause),this.text=e.text,this.finishReason=e.finishReason}static isInstance(e){return Iy(e,"AI_NoObjectGeneratedError")}},ZG=class extends Ry{toolName;constructor(e={}){super("AI_NoSuchToolError",e.message??`Model tried to call unavailable tool '${e.toolName??"unknown"}'.`),this.toolName=e.toolName}static isInstance(e){return Iy(e,"AI_NoSuchToolError")}},QG=class extends Ry{toolName;constructor(e={}){super("AI_InvalidToolInputError",e.message??`Invalid input for tool '${e.toolName??"unknown"}'.`,e.cause),this.toolName=e.toolName}static isInstance(e){return Iy(e,"AI_InvalidToolInputError")}},nE=class extends Ry{url;statusCode;responseBody;responseHeaders;isRetryable;requestBodyValues;constructor(e={}){super("AI_APICallError",e.message??"API call error.",e.cause),this.url=e.url,this.statusCode=e.statusCode,this.responseBody=e.responseBody,this.responseHeaders=e.responseHeaders,this.isRetryable=e.isRetryable??(e.statusCode!==null&&e.statusCode!==void 0&&(e.statusCode===408||e.statusCode===409||e.statusCode===429||e.statusCode>=500)),this.requestBodyValues=e.requestBodyValues}static isInstance(e){return Iy(e,"AI_APICallError")}}}});function e8(e,t){if("get"in e&&typeof e.get=="function")return e.get(t);const r=t.toLowerCase();for(const[n,o]of Object.entries(e))if(n.toLowerCase()===r)return o;return null}function oE(e){const t=e8(e,"Retry-After");if(t){const n=parseInt(t,10);if(!Number.isNaN(n))return Math.max(0,n*1e3);const o=new Date(t);if(!Number.isNaN(o.getTime()))return Math.max(0,o.getTime()-Date.now())}const r=e8(e,"X-RateLimit-Reset");if(r){const n=parseInt(r,10);if(!Number.isNaN(n)){const o=n>1e12?n:n*1e3;return Math.max(0,o-Date.now())}}if(e8(e,"X-RateLimit-Remaining")==="0")return 1e3}var t8=E({"src/lib/utils/retryAfter.ts"(){"use strict"}});function iE(e){if(!e||typeof e!="object")return;const t=e;if(typeof t.statusCode=="number")return t.statusCode;if(typeof t.status=="number")return t.status;const r=t.$metadata;if(typeof r=="object"&&r!==null){const n=r.httpStatusCode;if(typeof n=="number")return n}}function Fbe(e){if(!e||typeof e!="object")return;const t=e;if(typeof t.retryAfterMs=="number"&&Number.isFinite(t.retryAfterMs))return t.retryAfterMs;for(const r of[t.headers,t.responseHeaders])if(r&&typeof r=="object"){const n=oE(r);if(n!==void 0)return n}}function $be(e){if(typeof e=="string")try{const r=JSON.parse(e)?.error;return typeof r?.type=="string"?r.type:void 0}catch{return}}function Ube(e){if(typeof e!="object"||e===null)return!1;const t=e;return t.type==="insufficient_quota"?!0:$be(t.responseBody)==="insufficient_quota"}function Bbe(e,t=0){if(t>8||e===null||typeof e!="object")return pr(e);if(pr(e))return!0;const{cause:r}=e;return r===void 0||r===e?!1:Bbe(r,t+1)}function A4r(e){if(Bbe(e)||Ube(e))return!1;if(nE.isInstance(e))return e.isRetryable;if(e instanceof De)return e.retriable;const t=iE(e);return t!==void 0?t===429||t>=500:!1}function zbe(e){return nE.isInstance(e)?e.statusCode:iE(e)}function C4r(e){if(nE.isInstance(e)&&e.responseHeaders){const t=oE(e.responseHeaders);if(t!==void 0)return t}return e instanceof De&&e.retryAfterMs!==void 0&&Number.isFinite(e.retryAfterMs)?e.retryAfterMs:Fbe(e)}async function Py(e,t,r,n=Vbe,o){for(let i=0;i<=x4;i++){o?.throwIfAborted();try{const s=await e();return t?.setAttribute("gen_ai.provider.total_attempts",i+1),i>0&&h.info(`[providerRetry] ${r} succeeded after ${i+1} attempts`),s}catch(s){const a=A4r(s),l=zbe(s),c=s instanceof Error?s.message:String(s);if(!a||i===x4)throw t?.setAttribute("gen_ai.provider.total_attempts",i+1),i>0&&t?.setAttribute("gen_ai.provider.retries_exhausted",!0),h.warn(`[providerRetry] ${r} failed (non-retryable or retries exhausted)`,{attempt:i+1,retryable:a,statusCode:l,error:c}),s;const u=C4r(s);if(u!==void 0&&u>r8){t?.setAttribute("gen_ai.provider.total_attempts",i+1),t?.addEvent("gen_ai.provider.retry_suppressed",{"retry.after_ms":u,...l!==void 0&&{"retry.status_code":l}});try{Object.assign(s,{isRetryable:!1,retryAfterMs:u})}catch{}throw h.warn(`[providerRetry] ${r} not retrying \u2014 server requested a ${Math.round(u/1e3)}s wait (cap ${r8/1e3}s); surfacing for fallback`,{attempt:i+1,retryAfterMs:u,statusCode:l}),s}const d=(u===void 0?void 0:Math.max(0,u))??Math.max(Gbe*Math.pow(2,i),qbe);t?.addEvent("gen_ai.provider.retry",{"retry.attempt":i+1,"retry.delay_ms":d,...l!==void 0&&{"retry.status_code":l},"retry.error":c.slice(0,256)}),h.warn(`[providerRetry] ${r} retrying after ${l||"unknown"} error`,{attempt:i+1,maxRetries:x4,delayMs:d,statusCode:l,error:c}),await n(d,o),o?.throwIfAborted()}}throw new Error(`[providerRetry] ${r} exhausted all retries`)}var x4,Gbe,qbe,r8,Vbe,kd=E({"src/lib/utils/providerRetry.ts"(){"use strict";Qt(),et(),z(),rm(),t8(),x4=2,Gbe=1e3,qbe=1e4,r8=6e4,Vbe=(e,t)=>new Promise((r,n)=>{if(t?.aborted){n(t.reason);return}const o=()=>{clearTimeout(i),n(t?.reason)},i=setTimeout(()=>{t?.removeEventListener("abort",o),r()},e);t?.addEventListener("abort",o,{once:!0})})}}),n8,jbe=E({"src/lib/constants/networkErrorCodes.ts"(){"use strict";n8=new Set(["ECONNRESET","ETIMEDOUT","ECONNREFUSED","EPIPE","UND_ERR_SOCKET","UND_ERR_CONNECT_TIMEOUT"])}}),sE={};Z(sE,{Agent:()=>Zbe,AsyncLocalStorage:()=>p_e,Buffer:()=>uSe,Channel:()=>QEe,DatabaseSync:()=>cSe,Duplex:()=>h_e,EventEmitter:()=>d_e,Http2ServerRequest:()=>fSe,Http2ServerResponse:()=>gSe,Interface:()=>lSe,MIMEType:()=>_Se,PassThrough:()=>f_e,PerformanceObserver:()=>XEe,Readable:()=>i8,ReadableStream:()=>g_e,Resolver:()=>KEe,STATUS_CODES:()=>yEe,TextDecoder:()=>l8,TextEncoder:()=>lE,Transform:()=>m_e,URL:()=>NEe,URLSearchParams:()=>LEe,Worker:()=>nSe,Writable:()=>s8,access:()=>J_e,appendFile:()=>A_e,appendFileSync:()=>Jbe,arch:()=>mEe,arrayBuffer:()=>ySe,availableParallelism:()=>S_e,basename:()=>o_e,builtinModules:()=>PEe,callbackify:()=>qEe,channel:()=>ZEe,chmod:()=>E_e,chmodSync:()=>__e,clearInterval:()=>bSe,clearTimeout:()=>wSe,closeSync:()=>P_e,connect:()=>vEe,constants:()=>dSe,copyFileSync:()=>I_e,cpSync:()=>Xbe,cpus:()=>cEe,createConnection:()=>wEe,createGunzip:()=>xEe,createGzip:()=>AEe,createHash:()=>Au,createHmac:()=>o8,createInterface:()=>aSe,createReadStream:()=>G_e,createRequire:()=>REe,createServer:()=>Ybe,createWriteStream:()=>z_e,debug:()=>zEe,debuglog:()=>a8,default:()=>Hbe,deflateSync:()=>bEe,deprecate:()=>GEe,deserialize:()=>rSe,dirname:()=>n_e,exec:()=>tEe,execFile:()=>nEe,execFileSync:()=>oEe,execSync:()=>rEe,existsSync:()=>w_e,extname:()=>i_e,fileURLToPath:()=>FEe,finished:()=>v_e,format:()=>DEe,freemem:()=>uEe,fstatSync:()=>M_e,get:()=>gEe,gunzip:()=>kEe,gunzipSync:()=>_Ee,gzip:()=>SEe,gzipSync:()=>EEe,hasSubscribers:()=>eSe,homedir:()=>sEe,hostname:()=>lEe,inflateSync:()=>TEe,inherits:()=>UEe,inspect:()=>aE,isAbsolute:()=>a_e,isBuiltin:()=>MEe,isDeepStrictEqual:()=>VEe,isIP:()=>hSe,isIPv4:()=>mSe,isIPv6:()=>pSe,isMainThread:()=>oSe,join:()=>t_e,loadavg:()=>k_e,lookup:()=>WEe,lstatSync:()=>N_e,mkdir:()=>j_e,mkdirSync:()=>O_e,monitorEventLoopDelay:()=>YEe,normalize:()=>u_e,ok:()=>CEe,open:()=>Z_e,openSync:()=>R_e,parentPort:()=>iSe,parse:()=>OEe,pathToFileURL:()=>$Ee,performance:()=>JEe,pipeline:()=>y_e,platform:()=>iEe,posix:()=>c_e,promises:()=>Wbe,promisify:()=>BEe,randomBytes:()=>Wh,randomUUID:()=>Qe,readFile:()=>q_e,readFileSync:()=>T_e,readdir:()=>W_e,readdirSync:()=>L_e,realpath:()=>Q_e,realpathSync:()=>C_e,relative:()=>s_e,release:()=>hEe,rename:()=>X_e,renameSync:()=>$_e,request:()=>fEe,resolve:()=>r_e,rm:()=>Y_e,rmSync:()=>B_e,rmdirSync:()=>U_e,sep:()=>l_e,serialize:()=>tSe,setImmediate:()=>x_e,setInterval:()=>TSe,setTimeout:()=>vSe,spawn:()=>eEe,stat:()=>H_e,statSync:()=>D_e,strict:()=>IEe,tmpdir:()=>aEe,toUSVString:()=>jEe,totalmem:()=>dEe,type:()=>pEe,types:()=>HEe,unlink:()=>K_e,unlinkSync:()=>F_e,validateHeaderName:()=>Qbe,validateHeaderValue:()=>e_e,webcrypto:()=>Kbe,workerData:()=>sSe,writeFile:()=>V_e,writeFileSync:()=>b_e});var oo,yn,Hbe,Wbe,Au,o8,Wh,Qe,Kbe,Jbe,Xbe,Ybe,Zbe,Qbe,e_e,t_e,r_e,n_e,o_e,i_e,s_e,a_e,l_e,c_e,u_e,d_e,p_e,i8,s8,m_e,h_e,f_e,g_e,y_e,v_e,w_e,T_e,b_e,__e,E_e,S_e,k_e,x_e,A_e,C_e,I_e,R_e,P_e,M_e,O_e,D_e,N_e,L_e,F_e,$_e,U_e,B_e,z_e,G_e,q_e,V_e,j_e,H_e,W_e,K_e,J_e,X_e,Y_e,Z_e,Q_e,eEe,tEe,rEe,nEe,oEe,iEe,sEe,aEe,lEe,cEe,uEe,dEe,pEe,mEe,hEe,fEe,gEe,yEe,vEe,wEe,TEe,bEe,_Ee,EEe,SEe,kEe,xEe,AEe,CEe,IEe,REe,PEe,MEe,OEe,DEe,NEe,LEe,FEe,$Ee,UEe,BEe,a8,zEe,aE,GEe,qEe,VEe,jEe,HEe,l8,lE,WEe,KEe,JEe,XEe,YEe,ZEe,QEe,eSe,tSe,rSe,nSe,oSe,iSe,sSe,aSe,lSe,cSe,uSe,dSe,pSe,mSe,hSe,fSe,gSe,ySe,c8,vSe,wSe,TSe,bSe,_Se,$t=E({"node-stub:crypto"(){oo=()=>{},yn=async()=>{},Hbe={},Wbe={readFile:yn,writeFile:yn,mkdir:yn,stat:yn,readdir:yn,unlink:yn,access:yn,rm:yn,rename:yn},Au=e=>{const t=[];return{update(r){return t.push(typeof r=="string"?new lE().encode(r):r),this},digest(r){let n=0;for(const i of t)for(let s=0;s<i.length;s++)n=(n<<5)-n+i[s]|0;const o=(n>>>0).toString(16).padStart(8,"0");return r==="hex"?o:r==="base64"?btoa(o):o}}},o8=(e,t)=>Au(e),Wh=e=>new Uint8Array(e||32),Qe=()=>globalThis.crypto?.randomUUID?.()||Math.random().toString(36),Kbe=globalThis.crypto,Jbe=()=>{throw new Error("[NeuroLink:browser] fs.appendFileSync is not supported in browser runtime \u2014 use server-side execution")},Xbe=()=>{throw new Error("[NeuroLink:browser] fs.cpSync is not supported in browser runtime \u2014 use server-side execution")},Ybe=()=>({listen:oo,close:oo,on:oo}),Zbe=class{constructor(){throw new Error("[NeuroLink:browser] Node HTTP agents require a server runtime")}},Qbe=oo,e_e=oo,t_e=(...e)=>e.join("/"),r_e=(...e)=>e.join("/"),n_e=e=>e||"",o_e=e=>e?.split?.("/")?.pop?.()||"",i_e=e=>{const t=e?.match?.(/\.[^.]+$/);return t?t[0]:""},s_e=(e,t)=>t||"",a_e=()=>!1,l_e="/",c_e={normalize:e=>e,join:(...e)=>e.join("/"),resolve:(...e)=>e.join("/"),sep:"/"},u_e=e=>e,d_e=class{constructor(){this._ev=new Map}_list(t){let r=this._ev.get(t);return r||(r=[],this._ev.set(t,r)),r}on(t,r){return this._list(t).push(r),this}addListener(t,r){return this.on(t,r)}prependListener(t,r){return this._list(t).unshift(r),this}once(t,r){const n=(...o)=>{this.off(t,n),r(...o)};return n.listener=r,this.on(t,n)}prependOnceListener(t,r){const n=(...o)=>{this.off(t,n),r(...o)};return n.listener=r,this.prependListener(t,n)}off(t,r){const n=this._ev.get(t);if(n){const o=n.findIndex(i=>i===r||i.listener===r);o>=0&&n.splice(o,1)}return this}removeListener(t,r){return this.off(t,r)}removeAllListeners(t){return t===void 0?this._ev.clear():this._ev.delete(t),this}emit(t,...r){const n=this._ev.get(t);if(!n||n.length===0){if(t==="error")throw r[0]instanceof Error?r[0]:new Error("Unhandled error.");return!1}for(const o of[...n])o.apply(this,r);return!0}listenerCount(t){return(this._ev.get(t)||[]).length}listeners(t){return[...this._ev.get(t)||[]]}rawListeners(t){return this.listeners(t)}eventNames(){return[...this._ev.keys()]}setMaxListeners(){return this}getMaxListeners(){return 10}},p_e=class{getStore(){}run(e,t,...r){return t(...r)}enterWith(){}disable(){}},i8=class{pipe(){return this}on(){return this}read(){return null}push(){}destroy(){}},s8=class{write(){return!0}end(){}on(){return this}destroy(){}},m_e=class{push(){}on(){return this}},h_e=class{on(){return this}},f_e=class{pipe(){return this}on(){return this}},g_e=globalThis.ReadableStream||class{},y_e=oo,v_e=oo,w_e=()=>!1,T_e=()=>"",b_e=oo,__e=oo,E_e=yn,S_e=()=>1,k_e=()=>[0,0,0],x_e=yn,A_e=yn,C_e=e=>e,I_e=oo,R_e=()=>0,P_e=oo,M_e=()=>({}),O_e=oo,D_e=()=>({}),N_e=()=>({isSymbolicLink:()=>!1}),L_e=()=>[],F_e=oo,$_e=oo,U_e=oo,B_e=oo,z_e=()=>new s8,G_e=()=>new i8,q_e=yn,V_e=yn,j_e=yn,H_e=yn,W_e=yn,K_e=yn,J_e=yn,X_e=yn,Y_e=yn,Z_e=async()=>({stat:yn,readFile:yn,close:yn,read:yn,write:yn}),Q_e=async e=>e,eEe=()=>({on:oo,stdout:{on:oo},stderr:{on:oo},kill:oo}),tEe=(e,t)=>t?.(null,"",""),rEe=()=>"",nEe=(e,t,r)=>{typeof t=="function"?t(null,"",""):r?.(null,"","")},oEe=()=>"",iEe="browser",sEe=()=>"/",aEe=()=>"/tmp",lEe=()=>"browser",cEe=()=>[{}],uEe=()=>0,dEe=()=>0,pEe=()=>"Browser",mEe=()=>"wasm",hEe=()=>"0",fEe=()=>({}),gEe=()=>({}),yEe={100:"Continue",101:"Switching Protocols",200:"OK",201:"Created",202:"Accepted",204:"No Content",206:"Partial Content",301:"Moved Permanently",302:"Found",304:"Not Modified",307:"Temporary Redirect",308:"Permanent Redirect",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",408:"Request Timeout",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Failed",413:"Payload Too Large",414:"URI Too Long",415:"Unsupported Media Type",416:"Range Not Satisfiable",417:"Expectation Failed",422:"Unprocessable Entity",425:"Too Early",426:"Upgrade Required",428:"Precondition Required",429:"Too Many Requests",431:"Request Header Fields Too Large",451:"Unavailable For Legal Reasons",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout",505:"HTTP Version Not Supported"},vEe=()=>({}),wEe=()=>({}),TEe=()=>new Uint8Array,bEe=()=>new Uint8Array,_Ee=()=>new Uint8Array,EEe=()=>new Uint8Array,SEe=(e,t)=>t?.(null,e),kEe=(e,t)=>t?.(null,e),xEe=()=>({}),AEe=()=>({}),CEe=oo,IEe={},REe=()=>()=>({}),PEe=[],MEe=()=>!1,OEe=e=>({pathname:e||"",hostname:"",protocol:"",search:"",hash:""}),DEe=()=>"",NEe=globalThis.URL,LEe=globalThis.URLSearchParams,FEe=e=>typeof e=="string"?e.replace("file://",""):e,$Ee=e=>new globalThis.URL("file://"+e),UEe=(e,t)=>{t&&(e.super_=t,Object.setPrototypeOf(e.prototype,t.prototype))},BEe=e=>(...t)=>new Promise((r,n)=>e(...t,(o,i)=>o?n(o):r(i))),a8=e=>{const t=(...r)=>{};return t.enabled=!1,t},zEe=a8,aE=e=>{try{return JSON.stringify(e,null,2)}catch{return String(e)}},aE.custom=Symbol.for("nodejs.util.inspect.custom"),aE.colors={},aE.styles={},GEe=e=>e,qEe=e=>(...t)=>{const r=t.pop();e(...t).then(n=>r(null,n)).catch(r)},VEe=(e,t)=>JSON.stringify(e)===JSON.stringify(t),jEe=e=>String(e),HEe={isPromise:e=>e instanceof Promise,isDate:e=>e instanceof Date,isRegExp:e=>e instanceof RegExp,isNativeError:e=>e instanceof Error,isArrayBuffer:e=>e instanceof ArrayBuffer,isTypedArray:e=>ArrayBuffer.isView(e),isUint8Array:e=>e instanceof Uint8Array,isProxy:()=>!1},l8=globalThis.TextDecoder,lE=globalThis.TextEncoder,WEe=(e,t)=>t?.(null,"127.0.0.1",4),KEe=class{},JEe=globalThis.performance||{now:()=>Date.now()},XEe=class{observe(){}disconnect(){}},YEe=()=>({enable:oo,disable:oo,percentile:()=>0}),ZEe=()=>({}),QEe=class{},eSe=()=>!1,tSe=()=>new Uint8Array,rSe=oo,nSe=class{},oSe=!0,iSe=null,sSe=null,aSe=()=>({}),lSe=class{},cSe=class{},uSe=globalThis.Buffer||class extends Uint8Array{static from(t,r){if(typeof t=="string"){const n=(r||"utf8").toLowerCase();if(n==="base64"){const o=atob(t),i=new Uint8Array(o.length);for(let s=0;s<o.length;s++)i[s]=o.charCodeAt(s);return i}if(n==="hex"){const o=new Uint8Array(t.length/2);for(let i=0;i<t.length;i+=2)o[i/2]=parseInt(t.substr(i,2),16);return o}return new lE().encode(t)}return new Uint8Array(t)}static alloc(t){return new Uint8Array(t)}static isBuffer(t){return t instanceof Uint8Array}static concat(t){const r=t.reduce((i,s)=>i+s.length,0),n=new Uint8Array(r);let o=0;for(const i of t)n.set(i,o),o+=i.length;return n}static byteLength(t,r){return r==="base64"?Math.ceil(t.length*3/4):new lE().encode(t).length}toString(t){const r=(t||"utf8").toLowerCase();if(r==="hex")return Array.from(new Uint8Array(this.buffer,this.byteOffset,this.byteLength)).map(n=>n.toString(16).padStart(2,"0")).join("");if(r==="base64"){let n="";for(let o=0;o<this.length;o++)n+=String.fromCharCode(this[o]);return btoa(n)}return new l8().decode(this)}},dSe={F_OK:0,R_OK:4,W_OK:2,X_OK:1},pSe=()=>!1,mSe=()=>!1,hSe=()=>0,fSe=class{},gSe=class{},ySe=async()=>new ArrayBuffer(0),c8=e=>({[Symbol.toPrimitive](){return e},ref(){return this},unref(){return this},hasRef(){return!1},refresh(){return this},close(){}}),vSe=(...e)=>c8(globalThis.setTimeout(...e)),wSe=globalThis.clearTimeout,TSe=(...e)=>c8(globalThis.setInterval(...e)),bSe=globalThis.clearInterval,_Se=class{constructor(e){this.type=e}toString(){return this.type}}}}),nm={};Z(nm,{Agent:()=>PSe,AsyncLocalStorage:()=>LSe,Buffer:()=>Dxe,Channel:()=>Exe,DatabaseSync:()=>Oxe,Duplex:()=>$Se,EventEmitter:()=>NSe,Http2ServerRequest:()=>Uxe,Http2ServerResponse:()=>Bxe,Interface:()=>Mxe,MIMEType:()=>Hxe,PassThrough:()=>USe,PerformanceObserver:()=>Txe,Readable:()=>f8,ReadableStream:()=>BSe,Resolver:()=>vxe,STATUS_CODES:()=>zke,TextDecoder:()=>v8,TextEncoder:()=>uE,Transform:()=>FSe,URL:()=>ixe,URLSearchParams:()=>sxe,Worker:()=>Axe,Writable:()=>g8,access:()=>wke,appendFile:()=>YSe,appendFileSync:()=>CSe,arch:()=>Fke,arrayBuffer:()=>zxe,availableParallelism:()=>KSe,basename:()=>Ms,builtinModules:()=>txe,callbackify:()=>mxe,channel:()=>_xe,chmod:()=>WSe,chmodSync:()=>HSe,clearInterval:()=>jxe,clearTimeout:()=>qxe,closeSync:()=>tke,connect:()=>Gke,constants:()=>Nxe,copyFileSync:()=>QSe,cpSync:()=>ISe,cpus:()=>Oke,createConnection:()=>qke,createGunzip:()=>Xke,createGzip:()=>Yke,createHash:()=>u8,createHmac:()=>SSe,createInterface:()=>Pxe,createReadStream:()=>pke,createRequire:()=>exe,createServer:()=>RSe,createWriteStream:()=>dke,debug:()=>dxe,debuglog:()=>y8,default:()=>om,deflateSync:()=>jke,deprecate:()=>pxe,deserialize:()=>xxe,dirname:()=>d8,exec:()=>kke,execFile:()=>Ake,execFileSync:()=>Cke,execSync:()=>xke,existsSync:()=>qSe,extname:()=>Li,fileURLToPath:()=>axe,finished:()=>GSe,format:()=>oxe,freemem:()=>Dke,fstatSync:()=>rke,get:()=>Bke,gunzip:()=>Jke,gunzipSync:()=>Hke,gzip:()=>Kke,gzipSync:()=>Wke,hasSubscribers:()=>Sxe,homedir:()=>Rke,hostname:()=>Mke,inflateSync:()=>Vke,inherits:()=>cxe,inspect:()=>cE,isAbsolute:()=>A4,isBuiltin:()=>rxe,isDeepStrictEqual:()=>hxe,isIP:()=>$xe,isIPv4:()=>Fxe,isIPv6:()=>Lxe,isMainThread:()=>Cxe,join:()=>Rt,loadavg:()=>JSe,lookup:()=>yxe,lstatSync:()=>ike,mkdir:()=>fke,mkdirSync:()=>nke,monitorEventLoopDelay:()=>bxe,normalize:()=>DSe,ok:()=>Zke,open:()=>_ke,openSync:()=>eke,parentPort:()=>Ixe,parse:()=>nxe,pathToFileURL:()=>lxe,performance:()=>wxe,pipeline:()=>zSe,platform:()=>Ike,posix:()=>h8,promises:()=>ESe,promisify:()=>uxe,randomBytes:()=>kSe,randomUUID:()=>xSe,readFile:()=>mke,readFileSync:()=>VSe,readdir:()=>yke,readdirSync:()=>ske,realpath:()=>Eke,realpathSync:()=>ZSe,relative:()=>p8,release:()=>$ke,rename:()=>Tke,renameSync:()=>lke,request:()=>Uke,resolve:()=>Kh,rm:()=>bke,rmSync:()=>uke,rmdirSync:()=>cke,sep:()=>m8,serialize:()=>kxe,setImmediate:()=>XSe,setInterval:()=>Vxe,setTimeout:()=>Gxe,spawn:()=>Ske,stat:()=>gke,statSync:()=>oke,strict:()=>Qke,tmpdir:()=>Pke,toUSVString:()=>fxe,totalmem:()=>Nke,type:()=>Lke,types:()=>gxe,unlink:()=>vke,unlinkSync:()=>ake,validateHeaderName:()=>MSe,validateHeaderValue:()=>OSe,webcrypto:()=>ASe,workerData:()=>Rxe,writeFile:()=>hke,writeFileSync:()=>jSe});var io,vn,om,ESe,u8,SSe,kSe,xSe,ASe,CSe,ISe,RSe,PSe,MSe,OSe,Rt,Kh,d8,Ms,Li,p8,A4,m8,h8,DSe,NSe,LSe,f8,g8,FSe,$Se,USe,BSe,zSe,GSe,qSe,VSe,jSe,HSe,WSe,KSe,JSe,XSe,YSe,ZSe,QSe,eke,tke,rke,nke,oke,ike,ske,ake,lke,cke,uke,dke,pke,mke,hke,fke,gke,yke,vke,wke,Tke,bke,_ke,Eke,Ske,kke,xke,Ake,Cke,Ike,Rke,Pke,Mke,Oke,Dke,Nke,Lke,Fke,$ke,Uke,Bke,zke,Gke,qke,Vke,jke,Hke,Wke,Kke,Jke,Xke,Yke,Zke,Qke,exe,txe,rxe,nxe,oxe,ixe,sxe,axe,lxe,cxe,uxe,y8,dxe,cE,pxe,mxe,hxe,fxe,gxe,v8,uE,yxe,vxe,wxe,Txe,bxe,_xe,Exe,Sxe,kxe,xxe,Axe,Cxe,Ixe,Rxe,Pxe,Mxe,Oxe,Dxe,Nxe,Lxe,Fxe,$xe,Uxe,Bxe,zxe,w8,Gxe,qxe,Vxe,jxe,Hxe,kr=E({"node-stub:path"(){io=()=>{},vn=async()=>{},om={},ESe={readFile:vn,writeFile:vn,mkdir:vn,stat:vn,readdir:vn,unlink:vn,access:vn,rm:vn,rename:vn},u8=e=>{const t=[];return{update(r){return t.push(typeof r=="string"?new uE().encode(r):r),this},digest(r){let n=0;for(const i of t)for(let s=0;s<i.length;s++)n=(n<<5)-n+i[s]|0;const o=(n>>>0).toString(16).padStart(8,"0");return r==="hex"?o:r==="base64"?btoa(o):o}}},SSe=(e,t)=>u8(e),kSe=e=>new Uint8Array(e||32),xSe=()=>globalThis.crypto?.randomUUID?.()||Math.random().toString(36),ASe=globalThis.crypto,CSe=()=>{throw new Error("[NeuroLink:browser] fs.appendFileSync is not supported in browser runtime \u2014 use server-side execution")},ISe=()=>{throw new Error("[NeuroLink:browser] fs.cpSync is not supported in browser runtime \u2014 use server-side execution")},RSe=()=>({listen:io,close:io,on:io}),PSe=class{constructor(){throw new Error("[NeuroLink:browser] Node HTTP agents require a server runtime")}},MSe=io,OSe=io,Rt=(...e)=>e.join("/"),Kh=(...e)=>e.join("/"),d8=e=>e||"",Ms=e=>e?.split?.("/")?.pop?.()||"",Li=e=>{const t=e?.match?.(/\.[^.]+$/);return t?t[0]:""},p8=(e,t)=>t||"",A4=()=>!1,m8="/",h8={normalize:e=>e,join:(...e)=>e.join("/"),resolve:(...e)=>e.join("/"),sep:"/"},DSe=e=>e,NSe=class{constructor(){this._ev=new Map}_list(t){let r=this._ev.get(t);return r||(r=[],this._ev.set(t,r)),r}on(t,r){return this._list(t).push(r),this}addListener(t,r){return this.on(t,r)}prependListener(t,r){return this._list(t).unshift(r),this}once(t,r){const n=(...o)=>{this.off(t,n),r(...o)};return n.listener=r,this.on(t,n)}prependOnceListener(t,r){const n=(...o)=>{this.off(t,n),r(...o)};return n.listener=r,this.prependListener(t,n)}off(t,r){const n=this._ev.get(t);if(n){const o=n.findIndex(i=>i===r||i.listener===r);o>=0&&n.splice(o,1)}return this}removeListener(t,r){return this.off(t,r)}removeAllListeners(t){return t===void 0?this._ev.clear():this._ev.delete(t),this}emit(t,...r){const n=this._ev.get(t);if(!n||n.length===0){if(t==="error")throw r[0]instanceof Error?r[0]:new Error("Unhandled error.");return!1}for(const o of[...n])o.apply(this,r);return!0}listenerCount(t){return(this._ev.get(t)||[]).length}listeners(t){return[...this._ev.get(t)||[]]}rawListeners(t){return this.listeners(t)}eventNames(){return[...this._ev.keys()]}setMaxListeners(){return this}getMaxListeners(){return 10}},LSe=class{getStore(){}run(e,t,...r){return t(...r)}enterWith(){}disable(){}},f8=class{pipe(){return this}on(){return this}read(){return null}push(){}destroy(){}},g8=class{write(){return!0}end(){}on(){return this}destroy(){}},FSe=class{push(){}on(){return this}},$Se=class{on(){return this}},USe=class{pipe(){return this}on(){return this}},BSe=globalThis.ReadableStream||class{},zSe=io,GSe=io,qSe=()=>!1,VSe=()=>"",jSe=io,HSe=io,WSe=vn,KSe=()=>1,JSe=()=>[0,0,0],XSe=vn,YSe=vn,ZSe=e=>e,QSe=io,eke=()=>0,tke=io,rke=()=>({}),nke=io,oke=()=>({}),ike=()=>({isSymbolicLink:()=>!1}),ske=()=>[],ake=io,lke=io,cke=io,uke=io,dke=()=>new g8,pke=()=>new f8,mke=vn,hke=vn,fke=vn,gke=vn,yke=vn,vke=vn,wke=vn,Tke=vn,bke=vn,_ke=async()=>({stat:vn,readFile:vn,close:vn,read:vn,write:vn}),Eke=async e=>e,Ske=()=>({on:io,stdout:{on:io},stderr:{on:io},kill:io}),kke=(e,t)=>t?.(null,"",""),xke=()=>"",Ake=(e,t,r)=>{typeof t=="function"?t(null,"",""):r?.(null,"","")},Cke=()=>"",Ike="browser",Rke=()=>"/",Pke=()=>"/tmp",Mke=()=>"browser",Oke=()=>[{}],Dke=()=>0,Nke=()=>0,Lke=()=>"Browser",Fke=()=>"wasm",$ke=()=>"0",Uke=()=>({}),Bke=()=>({}),zke={100:"Continue",101:"Switching Protocols",200:"OK",201:"Created",202:"Accepted",204:"No Content",206:"Partial Content",301:"Moved Permanently",302:"Found",304:"Not Modified",307:"Temporary Redirect",308:"Permanent Redirect",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",408:"Request Timeout",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Failed",413:"Payload Too Large",414:"URI Too Long",415:"Unsupported Media Type",416:"Range Not Satisfiable",417:"Expectation Failed",422:"Unprocessable Entity",425:"Too Early",426:"Upgrade Required",428:"Precondition Required",429:"Too Many Requests",431:"Request Header Fields Too Large",451:"Unavailable For Legal Reasons",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout",505:"HTTP Version Not Supported"},Gke=()=>({}),qke=()=>({}),Vke=()=>new Uint8Array,jke=()=>new Uint8Array,Hke=()=>new Uint8Array,Wke=()=>new Uint8Array,Kke=(e,t)=>t?.(null,e),Jke=(e,t)=>t?.(null,e),Xke=()=>({}),Yke=()=>({}),Zke=io,Qke={},exe=()=>()=>({}),txe=[],rxe=()=>!1,nxe=e=>({pathname:e||"",hostname:"",protocol:"",search:"",hash:""}),oxe=()=>"",ixe=globalThis.URL,sxe=globalThis.URLSearchParams,axe=e=>typeof e=="string"?e.replace("file://",""):e,lxe=e=>new globalThis.URL("file://"+e),cxe=(e,t)=>{t&&(e.super_=t,Object.setPrototypeOf(e.prototype,t.prototype))},uxe=e=>(...t)=>new Promise((r,n)=>e(...t,(o,i)=>o?n(o):r(i))),y8=e=>{const t=(...r)=>{};return t.enabled=!1,t},dxe=y8,cE=e=>{try{return JSON.stringify(e,null,2)}catch{return String(e)}},cE.custom=Symbol.for("nodejs.util.inspect.custom"),cE.colors={},cE.styles={},pxe=e=>e,mxe=e=>(...t)=>{const r=t.pop();e(...t).then(n=>r(null,n)).catch(r)},hxe=(e,t)=>JSON.stringify(e)===JSON.stringify(t),fxe=e=>String(e),gxe={isPromise:e=>e instanceof Promise,isDate:e=>e instanceof Date,isRegExp:e=>e instanceof RegExp,isNativeError:e=>e instanceof Error,isArrayBuffer:e=>e instanceof ArrayBuffer,isTypedArray:e=>ArrayBuffer.isView(e),isUint8Array:e=>e instanceof Uint8Array,isProxy:()=>!1},v8=globalThis.TextDecoder,uE=globalThis.TextEncoder,yxe=(e,t)=>t?.(null,"127.0.0.1",4),vxe=class{},wxe=globalThis.performance||{now:()=>Date.now()},Txe=class{observe(){}disconnect(){}},bxe=()=>({enable:io,disable:io,percentile:()=>0}),_xe=()=>({}),Exe=class{},Sxe=()=>!1,kxe=()=>new Uint8Array,xxe=io,Axe=class{},Cxe=!0,Ixe=null,Rxe=null,Pxe=()=>({}),Mxe=class{},Oxe=class{},Dxe=globalThis.Buffer||class extends Uint8Array{static from(t,r){if(typeof t=="string"){const n=(r||"utf8").toLowerCase();if(n==="base64"){const o=atob(t),i=new Uint8Array(o.length);for(let s=0;s<o.length;s++)i[s]=o.charCodeAt(s);return i}if(n==="hex"){const o=new Uint8Array(t.length/2);for(let i=0;i<t.length;i+=2)o[i/2]=parseInt(t.substr(i,2),16);return o}return new uE().encode(t)}return new Uint8Array(t)}static alloc(t){return new Uint8Array(t)}static isBuffer(t){return t instanceof Uint8Array}static concat(t){const r=t.reduce((i,s)=>i+s.length,0),n=new Uint8Array(r);let o=0;for(const i of t)n.set(i,o),o+=i.length;return n}static byteLength(t,r){return r==="base64"?Math.ceil(t.length*3/4):new uE().encode(t).length}toString(t){const r=(t||"utf8").toLowerCase();if(r==="hex")return Array.from(new Uint8Array(this.buffer,this.byteOffset,this.byteLength)).map(n=>n.toString(16).padStart(2,"0")).join("");if(r==="base64"){let n="";for(let o=0;o<this.length;o++)n+=String.fromCharCode(this[o]);return btoa(n)}return new v8().decode(this)}},Nxe={F_OK:0,R_OK:4,W_OK:2,X_OK:1},Lxe=()=>!1,Fxe=()=>!1,$xe=()=>0,Uxe=class{},Bxe=class{},zxe=async()=>new ArrayBuffer(0),w8=e=>({[Symbol.toPrimitive](){return e},ref(){return this},unref(){return this},hasRef(){return!1},refresh(){return this},close(){}}),Gxe=(...e)=>w8(globalThis.setTimeout(...e)),qxe=globalThis.clearTimeout,Vxe=(...e)=>w8(globalThis.setInterval(...e)),jxe=globalThis.clearInterval,Hxe=class{constructor(e){this.type=e}toString(){return this.type}}}});function mr(e,t=500){return e&&e.slice(0,t).replace(Yxe,"***")}function My(e){if(typeof e=="string")return e;try{return JSON.stringify(e)??String(e)}catch{return"[content too large to serialize]"}}function C4(e,t=1e4){try{const r=JSON.stringify(e);return r===void 0?String(e):r.length>t?`${r.slice(0,t)}\u2026[truncated ${r.length-t} chars]`:r}catch(r){return`[unserializable: ${r instanceof Error?r.message:String(r)}]`}}function Yo(e){return e.replace(/\/\/[^/\s"'<>]*@/g,"//***@").replace(/\/\/(?:(?!\/\/)[^\s"'<>])*@/g,"//***@")}function Xt(e){const t=r=>r.length>200?`${r.slice(0,200)}\u2026`:r;try{const r=new URL(e);return r.host===""&&!r.pathname.startsWith("/")&&r.pathname.includes("@")&&!/^[a-z]:$/i.test(r.protocol)?t(`[redacted]@${r.pathname.slice(r.pathname.lastIndexOf("@")+1)}`):t(`${r.protocol}//${r.host}${r.pathname}`)}catch{const r=e.split(/[?#]/)[0];return t(Yo(r))}}function I4r(e){eAe.forEach(t=>e.searchParams.delete(t))}function R4r(e){const t=[],r=[];for(const[o,i]of e.searchParams.entries())Qxe.includes(o.toLowerCase())&&(t.push(`${o.toLowerCase()}=${i}`),r.push(o));return t.length===0?"":(r.forEach(o=>e.searchParams.delete(o)),t.sort(),`\0auth=${Au("sha256").update(t.join("&")).digest("hex").slice(0,16)}`)}function Wxe(e){try{const t=new URL(e);I4r(t);const r=R4r(t);return t.toString()+r}catch{return e}}function dE(e){return e.replace(/[a-zA-Z][a-zA-Z0-9+.-]*:\/\/[^\s"'<>)]+/g,t=>Xt(t))}function Kxe(e,t){const r=Ms(t);return e.split(Kh(t)).join(r).split(t).join(r)}function Jh(e,t){const r=i=>{const s=dE(i);return t?.filePath?Kxe(s,t.filePath):s};if(!(e instanceof Error))return new Error(r(String(e)));const n=new Error(r(e.message));n.name=e.name;const o=e.code;return o!==void 0&&(n.code=o),n}function I4(e,t=1e3){const r=new WeakSet,n=o=>{if(o==null)return o;if(typeof o=="string")return mr(o,t);if(typeof o!="object")return o;if(r.has(o))return"[Circular]";if(r.add(o),Array.isArray(o))return o.map(n);const i={};for(const[s,a]of Object.entries(o))Zxe.some(l=>l.toLowerCase()===s.toLowerCase())?i[s]="***":i[s]=n(a);return i};return n(e)}var Jxe,Xxe,Yxe,Zxe,Qxe,eAe,Nt=E({"src/lib/utils/logSanitize.ts"(){"use strict";$t(),kr(),Jxe=["sk","pk","r8","gsk","csk","xai","tgp","fw","pplx","pa","jina","fish"],Xxe=Jxe.join("|"),Yxe=new RegExp(`\\bBearer\\s+[A-Za-z0-9_\\-\\.]{8,}\\b|\\bToken\\s+[A-Za-z0-9_\\-\\.]{8,}\\b|\\bBasic\\s+[A-Za-z0-9+/=]{12,}\\b|\\b(?:${Xxe})[_\\-][A-Za-z0-9_\\-\\.]{8,}\\b|\\b(?:api[_-]?key|access[_-]?token|secret[_-]?key|refresh[_-]?token)['"]?\\s*[:=]\\s*['"]?[^\\s,;'"&]+`,"gi"),Zxe=["apikey","api_key","apiKey","access_token","accessToken","refresh_token","refreshToken","secret","secretkey","secret_key","secretKey","password","authorization","oauth","oauthToken","credentials","authContext","authToken","sessionToken","serviceAccountKey","secretAccessKey","userEmail"],Qxe=["token","signature","x-amz-signature","x-amz-credential","x-amz-security-token","awsaccesskeyid","expires","sig","se","sp","sr","sv","x-goog-signature","x-goog-credential","x-goog-algorithm","x-goog-date","x-goog-expires","x-goog-signedheaders"],eAe=["utm_source","utm_medium","utm_campaign","utm_term","utm_content","fbclid","gclid","_ga"]}});function P4r(e){const t=[],r=new Set;let n=e;for(;n&&typeof n=="object"&&!r.has(n)&&t.length<rAe;){r.add(n);const o=n;t.push(o),n=o.cause}return t}function tAe(e,t){for(const r of e)if(typeof r[t]=="string")return r[t]}function M4r(e,t,r){const n=P4r(e),o=n[0],i=typeof o?.message=="string"?o.message:e instanceof Error?e.message:"Unknown error",s=n[n.length-1],a=typeof s?.message=="string"?dE(s.message):void 0,l=a&&a!==i?`${i}: ${a}`:i;let c;for(const u of n)if(c=iE(u),c!==void 0)break;return{error:e,message:l,statusCode:c,errorName:tAe(n,"name"),errorCode:tAe(n,"code"),provider:t,modelName:r}}function ba(e,t,r,n){if(e instanceof Ta)return new ai(`Request timed out: ${e.message}`,r);const o=M4r(e,r,n),i=t.find(a=>a.match(o));if(!i)return new nt(`${r} error: ${o.message}`,r);const s=typeof i.message=="function"?i.message(o):i.message;return new i.errorClass(s,r)}function im(e,t){if(!Number.isInteger(t)||t<100||t>599)return!1;const r=String(t);return new RegExp(`^\\s*${r}\\b|\\b(?:error|status(?:\\s*code)?)\\b\\D{0,12}\\b${r}\\b|\\bhttp(?:/\\d(?:\\.\\d)?)?[\\s:-]{0,3}${r}\\b|\\b${r}\\b\\D{0,12}\\berror\\b`,"i").test(e)}var rAe,R4,nAe,T8,oAe,iAe,Ll,Zs=E({"src/lib/utils/errorClassifier.ts"(){"use strict";pt(),Ys(),kd(),jbe(),Nt(),rAe=5,R4="(?![\\s-]+(?:route|gateway|endpoint|url|path|proxy|server|service|api|host)s?(?![\\w-]))",nAe=`\\bmodel\\b${R4}`,T8=`\\b(?:model|deployment)\\b${R4}`,oAe=`(?:unknown|no such|invalid|unsupported) model${R4}`,iAe=new RegExp(`model[_ ]?not[_ ]?found|${oAe}|${T8}.{0,120}\\b(?:does not exist|not found|unavailable|not (?:available|supported))\\b|\\b(?:does not exist|not found)\\b.{0,120}${T8}|unable to access.{0,60}${nAe}`,"i"),Ll=[{match:e=>e.statusCode===401||/API_KEY_INVALID|Invalid API key|Unauthorized|invalid_api_key/i.test(e.message),errorClass:Wr,message:e=>`Invalid ${e.provider} API key. Please check your credentials.`},{match:e=>e.statusCode===429||/rate limit/i.test(e.message),errorClass:Qi,message:e=>`${e.provider} rate limit exceeded. Please try again later.`},{match:e=>/model_not_found|model not found/i.test(e.message)||e.statusCode===404&&iAe.test(e.message),errorClass:Jo,message:e=>e.modelName?`${e.provider} model '${e.modelName}' not found.`:`${e.provider} model not found.`},{match:e=>e.statusCode===404,errorClass:nt,message:e=>`${e.provider} returned HTTP 404: ${e.message}`},{match:e=>/ECONNRESET|ENOTFOUND|ECONNREFUSED|ETIMEDOUT|network|connection/i.test(e.message)||e.errorCode!==void 0&&n8.has(e.errorCode),errorClass:ai,message:e=>`Connection error: ${e.message}`},{match:e=>e.statusCode!==void 0&&e.statusCode>=500&&e.statusCode<=599||/server error|bad gateway|service unavailable|gateway timeout|\berror\b\D{0,12}\b5\d\d\b|\b5\d\d\b\D{0,12}\berror\b|\bstatus(?:\s*code)?\b\D{0,12}\b5\d\d\b/i.test(e.message),errorClass:nt,message:e=>`${e.provider} server error: ${e.message}`}]}});function O4r(e){return e.replace(/-([a-z])/g,(t,r)=>r.toUpperCase())}function D4r(e){return e.credentialsKey??O4r(e.id)}function Cu(e,t){const r=e.wire.envOverrides?.[t];if(r)return r;const n=e.id.toUpperCase().replace(/-/g,"_");return t==="apiKey"?`${n}_API_KEY`:t==="baseURL"?`${n}_BASE_URL`:`${n}_MODEL`}function b8(e,t,r,n){return e.replace(/\{apiKeyEnvVar\}/g,Cu(t,"apiKey")).replace(/\{setupUrl\}/g,t.setup.url).replace(/\{model\}/g,r??"").replace(/\{message\}/g,n??"")}function N4r(e){return{providerName:e.displayName,envVarName:Cu(e,"apiKey"),setupUrl:e.setup.url,description:e.setup.description??"API key",instructions:e.setup.instructions.map(t=>b8(t,e)),...e.wire.apiKeyFallbackEnvVars?{fallbackEnvVars:e.wire.apiKeyFallbackEnvVars}:{}}}function L4r(e){return[...e.errorRules.map(r=>{const n=r.pattern?new RegExp(r.pattern,"i"):void 0,o=r.message.includes("{model}")||r.message.includes("{message}");return{match:i=>r.status!==void 0&&i.statusCode===r.status||n!==void 0&&(r.patternStatuses===void 0||i.statusCode!==void 0&&r.patternStatuses.includes(i.statusCode))&&n.test(i.message),errorClass:sAe[r.class],message:o?i=>b8(r.message,e,i.modelName,i.message):b8(r.message,e)}}),...Ll]}function _8(e){if(Array.isArray(e)){for(const t of e)_8(t);return Object.freeze(e)}if(e!==null&&typeof e=="object"){for(const t of Object.keys(e))_8(e[t]);return Object.freeze(e)}return e}function Oy(){return _8(structuredClone(N6))}function F4r(){return N6.map(e=>{const t={providerName:e.id,aliases:[e.id,...e.aliases],apiKeyEnvVar:Cu(e,"apiKey"),configOptions:N4r(e),modelEnvVar:Cu(e,"model"),defaultModel:e.models.default,registryDefaultModel:e.models.registryDefaultModel??e.models.default,registryDefaultModelChecksEnvVar:e.quirks?.registryDefaultIgnoresModelEnvVar!==!0,fallbackModelName:e.models.fallbackModelName??e.models.fallbacks[1]??e.models.fallbacks[0],fallbackModels:[...e.models.fallbacks],errorRules:L4r(e),...typeof e.capabilities.tools=="boolean"?{supportsTools:e.capabilities.tools}:{},supportsStructuredOutputWithTools:e.capabilities.structuredOutputWithTools},{baseURLTemplate:r}=e.wire;if(r){const n=e.wire.extraCredentials?.[0]??"accountId";t.computedBaseURL={envVar:`${e.id.toUpperCase().replace(/-/g,"_")}_${n.replace(/([A-Z])/g,"_$1").toUpperCase()}`,missingValueMessage:e.wire.missingCredentialMessage??`Missing ${n} for ${e.displayName}`,build:o=>r.replaceAll(`{${n}}`,o)}}else t.baseURLEnvVar=Cu(e,"baseURL"),t.defaultBaseURL=e.wire.baseURL;return e.quirks?.messageContentFormat&&(t.messageContentFormat=e.quirks.messageContentFormat),e.quirks?.timeoutErrorClass==="provider"&&(t.timeoutErrorClass=nt),e.quirks?.responseFormatDowngrade&&(t.responseFormatDowngrade=e.quirks.responseFormatDowngrade),e.quirks?.replayReasoningContent&&(t.replayReasoningContent=!0),e.quirks?.authHeaderStyle&&(t.authHeaderStyle=e.quirks.authHeaderStyle),t})}var sAe,Dy=E({"src/lib/providers/catalog/loader.ts"(){"use strict";Kkr(),Zs(),pt(),sAe={authentication:Wr,"rate-limit":Qi,"invalid-model":Jo,network:ai,provider:nt}}});function _a(e){let t=process.env[e.envVarName];if(!t&&e.fallbackEnvVars){for(const r of e.fallbackEnvVars)if(t=process.env[r],t)break}if(!t){if(e.optional)return"";throw new Error($4r(e))}return t}function $4r(e){const t=e.fallbackEnvVars?[e.envVarName,...e.fallbackEnvVars].join(" or "):e.envVarName;return`\u274C ${e.providerName} Provider Configuration Error
|
|
67
67
|
|
|
68
68
|
Missing required environment variable: ${t}
|
|
69
69
|
|
|
@@ -1027,10 +1027,10 @@ Based on this analysis, provide your response.`:`Here is a video/image analysis
|
|
|
1027
1027
|
|
|
1028
1028
|
${i}
|
|
1029
1029
|
|
|
1030
|
-
Based on this analysis, provide your response.`;h.debug("[VideoAnalysis] Formatting via Claude",{userTextLength:s.length,analysisLength:i.length});const u=await hUe(n,{...t.systemPrompt?{system:t.systemPrompt}:{},prompt:c,maxOutputTokens:t.maxTokens||8192,temperature:.3,...t.abortSignal?{abortSignal:t.abortSignal}:{}});a=u.text,l=mM(u.usage),h.debug("[VideoAnalysis] Claude formatting complete",{formattedLength:a.length,usage:l})}catch(c){h.warn("[VideoAnalysis] Claude formatting failed, using raw Gemini output",{error:c instanceof Error?c.message:String(c)})}return this.enhanceResult({content:a,provider:t.provider??this.providerName,model:this.modelName,usage:l},t,o)}async finalizeNativeGenerate(t,r,n){await this.recordPerformanceMetrics(t.usage,Date.now()-n);const o=await this.synthesizeAIResponseIfNeeded(t,r);return this.enhanceResult(o,r,n)}fireGenerateOnFinish(t,r,n){const o=t.onFinish;if(typeof o=="function")try{const i=r?.usage,s=o({text:r?.content||"",usage:i?{promptTokens:i.input??0,completionTokens:i.output??0}:void 0,duration:Date.now()-n,finishReason:r?.finishReason??"stop"});Promise.resolve(s).catch(a=>h.warn(`[${this.providerName}] onFinish callback rejected: ${a instanceof Error?a.message:String(a)}`))}catch(i){h.warn(`[${this.providerName}] onFinish callback threw: ${i instanceof Error?i.message:String(i)}`)}}async synthesizeAIResponseIfNeeded(t,r){if(!r.tts?.enabled||!r.tts?.useAiResponse)return t;const n=r.tts,o=t.content,i=n.provider??r.provider??this.providerName;if(!o||!i)return h.warn("TTS synthesis skipped despite being enabled",{provider:this.providerName,hasAiResponse:!!o,aiResponseLength:o?.length??0,hasProvider:!!i,ttsConfig:{enabled:r.tts?.enabled,useAiResponse:r.tts?.useAiResponse},reason:o?"Provider is missing":"AI response is empty or undefined"}),{...t,ttsMetadata:{attempted:!1,success:!1}};const s=Date.now(),a=this.getTimeout(r);try{const l=await w4(()=>Nc.synthesize(o,i,n),a,`TTS synthesis timed out after ${a}ms for provider "${i}"`);return{...t,audio:l,ttsMetadata:{attempted:!0,success:!0,latency:Date.now()-s}}}catch(l){const c=Date.now()-s,u=this.getTTSErrorDetails(l);return this.telemetryHandler.recordTTSFailure(i,u,c),h.error("TTS synthesis failed in Mode 2 (AI response synthesis):",l),{...t,ttsMetadata:{attempted:!0,success:!1,error:u,latency:c}}}}getTTSErrorDetails(t){const r=Jh(t).message;return t instanceof ku?{code:Tt.SYNTHESIS_FAILED,message:r,retriable:!0}:t instanceof De?{code:t.code,message:r,retriable:t.retriable}:{code:Tt.SYNTHESIS_FAILED,message:r}}async generateText(t){const r=t.prompt||t.input?.text;if(!r||typeof r!="string"||r.trim()==="")throw new Error("GenerateText options must include prompt or input.text as a non-empty string");const n=await this.generate(t);if(!n)throw new Error("Generation failed: No result returned");return{content:n.content||"",provider:n.provider||this.providerName,model:n.model||this.modelName,usage:n.usage||{input:0,output:0,total:0},responseTime:0,toolsUsed:n.toolsUsed||[],toolExecutions:n.toolExecutions?.map(o=>({toolName:o.toolName,executionTime:o.durationMs,success:!o.isError})),enhancedWithTools:!!(n.toolsUsed&&n.toolsUsed.length>0),analytics:n.analytics,evaluation:n.evaluation,audio:n.audio,reasoning:n.reasoning,reasoningTokens:n.reasoningTokens}}async embed(t,r){const n=typeof t=="string"?t.length:t.text?.length??0;throw h.warn(`embed() called on ${this.providerName} which does not have a native implementation`,{textLength:n}),new Error(`Embedding generation is not supported by the ${this.providerName} provider. Supported providers: openai, vertex/google, bedrock, cohere, voyage, jina. Use an embedding model like text-embedding-3-small (OpenAI), text-embedding-004 (Vertex), embed-english-v3.0 (Cohere), voyage-3 (Voyage), jina-embeddings-v3 (Jina), or amazon.titan-embed-text-v2:0 (Bedrock).`)}async embedMany(t,r){throw h.warn(`embedMany() called on ${this.providerName} which does not have a native implementation`,{count:t.length}),new Error(`Batch embedding generation is not supported by the ${this.providerName} provider. Supported providers: openai, googleAiStudio, vertex/google, bedrock, cohere, voyage, jina. Use an embedding model like text-embedding-3-small (OpenAI), gemini-embedding-001 (Google AI), text-embedding-004 (Vertex), embed-english-v3.0 (Cohere), voyage-3 (Voyage), jina-embeddings-v3 (Jina), or amazon.titan-embed-text-v2:0 (Bedrock).`)}getDefaultEmbeddingModel(){}async decide(t){throw h.warn(`decide() called on ${this.providerName}, which does not serve the decide inference type`),new Error(`The decide inference type is not supported by the ${this.providerName} provider. Supported providers: ${Ny.map(r=>r.name).join(", ")}. A provider declares this capability with "decide" in its descriptor's inferenceKinds.`)}getDefaultDecisionModel(){}getToolCallRepairFn(t){if(!t?.disableToolCallRepair)return(async(...r)=>{const{createToolCallRepair:n}=await Promise.resolve().then(()=>(aY(),R1t));return n()(...r)})}async executeStream(t,r){if(!this.doStream)throw new De({code:He.INVALID_CONFIGURATION,message:`${this.providerName} cannot stream: it neither implements doStream() nor overrides executeStream()`,category:"configuration",severity:"critical",retriable:!1,context:{provider:this.providerName,model:this.modelName}});const n=Date.now(),{stream:o,finishReason:i,usage:s,warnings:a}=await this.doStream(t);a?.length&&h.warn(`[${this.providerName}] doStream reported warnings`,{provider:this.providerName,count:a.length});const l={startTime:n,streamId:`${this.providerName}-${n}`},c=(async()=>{const[u,d]=await Promise.all([i,s]);return l.finishReason=u,l.rawFinishReason=u,cv(this.providerName,this.modelName||this.getDefaultModel(),{usage:{input:d.inputTokens,output:d.outputTokens,total:d.inputTokens+d.outputTokens},stopReason:u},Date.now()-n,{streamingMode:!0})})();return{stream:o,model:this.modelName||this.getDefaultModel(),provider:this.getProviderName(),analytics:c,metadata:l}}async withTurnTimeout(t,r,n){const i=typeof t.turnTimeoutMs=="number"&&Number.isFinite(t.turnTimeoutMs)&&t.turnTimeoutMs>0?t.turnTimeoutMs:t.timeout??Math.max(r??0,18e4),s=wa(i,this.providerName,"generate"),a=Cy(t.abortSignal,s?.controller.signal),l=a?{...t,abortSignal:a}:t;try{return await n(l)}catch(c){const u=s?.controller.signal.aborted?s.controller.signal.reason:void 0;throw u instanceof Ta&&pr(c)&&t.abortSignal?.aborted!==!0?u:c}finally{s?.cleanup()}}emitTurnEvent(t){try{this.neurolink?.getEventEmitter()?.emit("turn:lifecycle",{provider:this.providerName,timestamp:Date.now(),...t})}catch{}}getDescriptorGenerateMs(){return hr.get(this.providerName)?.timeouts?.generateMs}getDescriptorDecideMs(){return hr.get(this.providerName)?.timeouts?.decideMs}getModel(){return this.getAISDKModel()}async getAISDKModelWithMiddleware(t={}){return this.applyMiddlewareToModel(await this.getAISDKModel(),t)}async applyMiddlewareToModel(t,r={}){h.debug(`Retrieved base model for ${this.providerName}`,{provider:this.providerName,model:this.modelName,hasMiddlewareConfig:!!this.middlewareOptions,timestamp:Date.now()});const n=this.extractMiddlewareOptions(r);if(h.debug("Middleware extraction result",{provider:this.providerName,model:this.modelName,middlewareOptions:n}),!n)return t;try{h.debug(`Applying middleware to ${this.providerName} model`,{provider:this.providerName,model:this.modelName,middlewareOptions:n});const o=new Mj(n),i=o.createContext(this.providerName,this.modelName,r,{sessionId:this.sessionId,userId:this.userId}),s=o.applyMiddleware(t,i,n);return h.debug(`Applied middleware to ${this.providerName} model`,{provider:this.providerName,model:this.modelName,hasMiddleware:!0}),s}catch(o){return h.warn(`Failed to apply middleware to ${this.providerName}, using base model`,{error:o instanceof Error?o.message:String(o)}),t}}extractMiddlewareOptions(t){return this.utilities.extractMiddlewareOptions(t)}isZodSchema(t){return this.utilities.isZodSchema(t)}async convertToolResult(t){return this.utilities.convertToolResult(t)}fixSchemaForOpenAIStrictMode(t){return this.utilities.fixSchemaForOpenAIStrictMode(t)}setFileToolRootPolicy(t){t===void 0||Object.keys(this.directTools).length===0||(this.fileToolRootsBound=!0,this.toolsManager.setDirectTools(t.roots===null?this.directTools:hV(t)))}applyFileToolRoots(t){if(Object.keys(this.directTools).length===0)return;const r=wV(t);if(r!==void 0){this.setFileToolRootPolicy(r);return}this.fileToolRootsBound&&t.toolRoots===void 0||this.setFileToolRootPolicy(_P({perCall:t.toolRoots,instance:this.neurolink?.getToolsConfig()?.fileRoots}))}async getAllTools(){return this.fileToolRootsBound||this.applyFileToolRoots({}),this.toolsManager.getAllTools()}async calculateActualCost(t){return this.telemetryHandler.calculateActualCost(t)}createPermissiveZodSchema(){return this.utilities.createPermissiveZodSchema()}setSessionContext(t,r){this.sessionId=t,this.userId=r,this.toolsManager.setSessionContext(t,r)}classifyStreamError(t){const r=t instanceof Error?t:new Error(String(t));return X1t(r)||r instanceof ot||iE(r)===void 0?r:this.handleProviderError(r)}handleProviderError(t){if(pr(t))return t instanceof Error?t:new DOMException("The operation was aborted","AbortError");if(t instanceof Error&&X1t(t))return t;const r=this.formatProviderError(t);if(t&&typeof t=="object"&&r!==t){const n=t,o=r,i=iE(t);if(i!==void 0&&o.statusCode===void 0&&(o.statusCode=i),typeof n.isRetryable=="boolean"&&o.isRetryable===void 0&&(o.isRetryable=n.isRetryable),o.retryAfterMs===void 0){const s=Fbe(t);s!==void 0&&(o.retryAfterMs=s)}}kS(t)&&HP(r);try{const n=dt.getSpan(xr.active());if(n){let o="provider_error";const i=r?.constructor?.name??"";i==="RateLimitError"?o="rate_limit":i==="AuthenticationError"?o="auth_failure":i==="NetworkError"?o="network":i==="InvalidModelError"?o="invalid_model":i==="TimeoutError"&&(o="timeout"),n.setAttribute("error.type",o),r instanceof Error&&n.setAttribute("error.message",r.message.substring(0,500))}}catch{}return Dqr(r),r}async executeImageGeneration(t){throw new Error(`Image generation is not supported by the ${this.providerName} provider or the selected model.`)}async executeWithTimeout(t,r){const n=this.getTimeout(r),o=wa(n,this.providerName,r.operationType||"generate");try{return o?await Promise.race([t(),new Promise((i,s)=>{o.controller.signal.addEventListener("abort",()=>{s(new Ta(`${this.providerName} operation timed out`,o.timeoutMs,this.providerName,r.operationType||"generate"))})})]):await t()}finally{o?.cleanup()}}validateStreamOptions(t){this.streamHandler.validateStreamOptions(t)}createTextStream(t,r){return this.streamHandler.createTextStream(t,r)}createStreamResult(t,r={}){return this.streamHandler.createStreamResult(t,r)}async createStreamAnalytics(t,r,n){return this.streamHandler.createStreamAnalytics(t,r,n)}handleCommonErrors(t){return this.utilities.handleCommonErrors(t)}setupToolExecutor(t,r){this.toolsManager.setupToolExecutor(t,r)}normalizeTextOptions(t){return this.utilities.normalizeTextOptions(t)}normalizeStreamOptions(t){return this.utilities.normalizeStreamOptions(t)}async enhanceResult(t,r,n){const o=Date.now()-n,i=t.imageOutput;let s={...t};if(r.enableAnalytics)try{const a=await this.createAnalytics(t,o,r);s={...s,analytics:a,imageOutput:i}}catch(a){h.warn(`Analytics creation failed for ${this.providerName}:`,a)}if(r.enableEvaluation)try{const a=await this.createEvaluation(t,r);s={...s,evaluation:a,imageOutput:i}}catch(a){h.warn(`Evaluation creation failed for ${this.providerName}:`,a)}return i&&(s.imageOutput=i),s}async handleVideoGeneration(t,r){const{VideoProcessor:n,VideoError:o,VIDEO_ERROR_CODES:i}=await Promise.resolve().then(()=>(Pm(),U1t)),{validateVideoGenerationInput:s,validateImageForVideo:a,validateDirectorModeInput:l}=await Promise.resolve().then(()=>(Xd(),tSt)),{ErrorFactory:c}=await Promise.resolve().then(()=>(et(),rE)),u={input:t.input||{text:t.prompt||""},output:t.output,provider:t.provider,model:t.model};if(u.input?.segments&&Array.isArray(u.input.segments)&&u.input.segments.length>0){const C=u.input.segments,R=l(u);if(!R.isValid)throw c.invalidParameters("director-mode",new Error(R.errors.map(J=>J.message).join("; ")),{errors:R.errors});if(R.warnings.length>0)for(const J of R.warnings)h.warn(`Director Mode warning: ${J}`);const{executeDirectorPipeline:O,DIRECTOR_PIPELINE_TIMEOUT_MS:U}=await Promise.resolve().then(()=>(Oqr(),z1t)),M=t.timeout??U,D=await this.executeWithTimeout(()=>O(C,u.output?.video??{},u.output?.director??{},t.region),{timeout:M,operationType:"generate"}),$=u.input.segments.map(J=>J.prompt).join(" \u2192 "),B=D.metadata?.segmentCount??u.input.segments.length,q=D.metadata?.transitionCount??Math.max(0,B-1),L=D.metadata?.duration??0,G={content:`${$} \u2014 duration: ${L}s, segments: ${B}, transitions: ${q}`,provider:"vertex",model:t.model||"veo-3.1-generate-001",usage:{input:0,output:0,total:0},video:D};return await this.enhanceResult(G,t,r)}const d=s(u);if(!d.isValid)throw c.invalidParameters("video-generation",new Error(d.errors.map(C=>C.message).join("; ")),{errors:d.errors});if(d.warnings.length>0)for(const C of d.warnings)h.warn(`Video generation warning: ${C}`);const p=t.input?.images?.[0];if(!p)throw new o({code:i.INVALID_INPUT,message:"Video generation requires an input image. Provide via input.images array.",retriable:!1,context:{field:"input.images"}});const m=15e3;let f;if(typeof p=="string")if(p.startsWith("http://")||p.startsWith("https://")){h.debug("Fetching image from URL for video generation",{url:p.substring(0,100)});let C;try{C=await this.executeWithTimeout(()=>fetch(p),{timeout:m,operationType:"generate"})}catch(R){throw new o({code:i.INVALID_INPUT,message:`Failed to fetch image from URL: ${R instanceof Error?R.message:"Request timed out"}`,retriable:!0,context:{url:p,timeout:m},originalError:R instanceof Error?R:void 0})}if(!C.ok)throw new o({code:i.INVALID_INPUT,message:`Failed to fetch image from URL: ${C.status} ${C.statusText}`,retriable:C.status>=500,context:{url:p,status:C.status}});f=Buffer.from(await C.arrayBuffer())}else{h.debug("Reading image from path for video generation",{path:p});const C=await Promise.resolve().then(()=>(Yr(),gv));try{f=await this.executeWithTimeout(()=>C.readFile(p),{timeout:m,operationType:"generate"})}catch(R){throw new o({code:i.INVALID_INPUT,message:`Failed to read image file: ${R instanceof Error?R.message:String(R)}`,retriable:!1,context:{path:p,timeout:m},originalError:R instanceof Error?R:void 0})}}else if(Buffer.isBuffer(p))f=p;else if(typeof p=="object"&&"data"in p){const C=p.data;if(typeof C=="string")f=Buffer.from(C,"base64");else if(Buffer.isBuffer(C))f=C;else throw new o({code:i.INVALID_INPUT,message:"ImageWithAltText.data must be a base64 string or Buffer.",retriable:!1,context:{field:"input.images[0].data",type:typeof C}})}else throw new o({code:i.INVALID_INPUT,message:"Invalid image input type. Provide Buffer, path string, URL, or ImageWithAltText.",retriable:!1,context:{field:"input.images[0]",type:typeof p}});const g=a(f);if(g)throw c.invalidParameters("video-generation",new Error(g.message),{field:"input.images[0]",validation:g});const y=t.prompt||t.input?.text||"",v=t.output?.video?.provider??qPr("video");if(!n.supports(v))throw new o({code:i.PROVIDER_NOT_SUPPORTED,message:`Video provider "${v}" is not registered. Available: ${n.listProviders().join(", ")}`,retriable:!1,context:{provider:v,available:n.listProviders()}});const b=t.output?.video?.model??t.model??(v==="vertex"?"veo-3.1-generate-001":void 0);h.info("Starting video generation",{provider:v,...b?{model:b}:{},promptLength:y.length,imageSize:f.length,resolution:t.output?.video?.resolution||"720p",duration:t.output?.video?.length||6});const S=t.timeout??6e5,k=t.output?.video?.abortSignal??t.abortSignal,A=await this.executeWithTimeout(()=>n.generate(v,{...t.output?.video??{},image:f,prompt:y,region:t.region,abortSignal:k}),{timeout:S,operationType:"generate"}),x=A.metadata?.model??b??(v==="vertex"?"veo-3.1-generate-001":"unknown");h.info("Video generation complete",{provider:v,model:x,videoSize:A.data.length,duration:A.metadata?.duration,processingTime:A.metadata?.processingTime});const P={content:y,provider:v,model:x,usage:{input:0,output:0,total:0},video:A};return await this.enhanceResult(P,t,r)}async createAnalytics(t,r,n){return this.telemetryHandler.createAnalytics(t,r,n.context)}async createEvaluation(t,r){return this.telemetryHandler.createEvaluation(t,r)}validateOptions(t){this.utilities.validateOptions(t)}getProviderInfo(){return this.utilities.getProviderInfo()}getTimeout(t){return this.utilities.getTimeout(t)}async handleToolExecutionStorage(t,r,n,o){return this.telemetryHandler.handleToolExecutionStorage(t,r,n,o)}static chunkPrompt(t,r=9e5,n=100){if(t.length<=r)return[t];const o=[];let i=0;for(;i<t.length;){const s=Math.min(i+r,t.length);if(o.push(t.slice(i,s)),s>=t.length)break;const a=s-n;a<=i?i=s:i=Math.max(a,0)}return o}}}});async function ug(e,t){try{await e}catch(r){h.debug(`[${t}] detached stream pump rejected; reason absorbed because the turn's own error is authoritative`,r)}}var pY=E({"src/lib/utils/drainDetachedPump.ts"(){"use strict";z()}}),dg=E({"src/lib/utils/async/index.ts"(){"use strict";Kr()}});function pg(e,t,r){return async(n,o)=>{const i=()=>Promise.resolve(t(n,o)),s=r.withToolSpan,a=s?()=>s(e,i):i;r.onProgress?.();try{const l=r.abortSignal?Su(a(),r.abortSignal):a();return await(r.toolTimeoutMs===void 0||r.toolTimeoutMs===null?l:It(l,r.toolTimeoutMs,`Tool "${e}" execution timed out after ${r.toolTimeoutMs}ms`))}finally{r.onProgress?.()}}}var EO=E({"src/lib/core/toolExecutionGuards.ts"(){"use strict";dg()}});function Lqr(e,t){const r=Z1t[e];return Math.round(t.min+r*(t.max-t.min))}function mY(e,t){if(!e?.enabled&&!e?.thinkingLevel)return;const r=e.thinkingLevel??Y1t;if(t&&!sqr(t)){const n=aqr(t);if(n)return{includeThoughts:!0,thinkingBudget:Lqr(r,n)};hY.has(t)||(hY.add(t),h.warn(`[thinkingConfig] "${t}" has no verified Gemini thinkingBudget range; omitting thinkingConfig \u2014 requested thinkingLevel is silently disabled.`));return}return{includeThoughts:!0,thinkingLevel:r}}var Y1t,Z1t,hY,Q1t=E({"src/lib/utils/thinkingConfig.ts"(){"use strict";fO(),z(),Y1t="high",Z1t={minimal:0,low:.25,medium:.55,high:1},hY=new Set}});function Fqr(e){return JSON.stringify(e,(t,r)=>r&&typeof r=="object"&&!Array.isArray(r)?Object.keys(r).sort().reduce((n,o)=>(n[o]=r[o],n),{}):r)}function $qr(e){if(pIt.test(e))return e;let t=e.replace(/[^A-Za-z0-9_.:-]/g,"_");return/^[A-Za-z_]/.test(t)||(t=`_${t}`),t.length>AO&&(t=t.slice(0,AO)),t}function Uqr(e,t){if(!t(e))return e;let r=2;for(;;){const n=`_${r}`,i=`${e.slice(0,AO-n.length)}${n}`;if(!t(i))return i;r++}}function Mm(e){if(Array.isArray(e.anyOf)||Array.isArray(e.oneOf)){const n=e.anyOf?"anyOf":"oneOf",o=e[n],i=o.filter(c=>c.type!=="null"&&c.type!=="undefined");if(i.length===1){const c=Mm({...i[0]});return c.nullable=!0,e.description&&(c.description=e.description),c}const s=i.map(c=>c.type||"unknown").join(" | "),a={type:"string"},l=e.description?`${e.description} (accepts: ${s})`:`Value as string (accepts: ${s})`;return a.description=l,o.some(c=>c.type==="null")&&(a.nullable=!0),a}const t={};for(const[n,o]of Object.entries(e))if(!(n==="$schema"||n==="additionalProperties"||n==="default"))if(n==="properties"&&o&&typeof o=="object"){const i={};for(const[s,a]of Object.entries(o))a&&typeof a=="object"?i[s]=Mm(a):i[s]=a;t[n]=i}else n==="items"&&o&&typeof o=="object"?Array.isArray(o)?t[n]=o.map(i=>i&&typeof i=="object"?Mm(i):i):t[n]=Mm(o):t[n]=o;Array.isArray(t.allOf)&&(t.allOf=t.allOf.map(n=>Mm(n))),t.not&&typeof t.not=="object"&&(t.not=Mm(t.not));for(const n of["if","then","else"])t[n]&&typeof t[n]=="object"&&(t[n]=Mm(t[n]));typeof t.exclusiveMinimum=="boolean"&&(t.exclusiveMinimum===!0&&typeof t.minimum=="number"?(t.exclusiveMinimum=t.minimum,delete t.minimum):delete t.exclusiveMinimum),typeof t.exclusiveMaximum=="boolean"&&(t.exclusiveMaximum===!0&&typeof t.maximum=="number"?(t.exclusiveMaximum=t.maximum,delete t.maximum):delete t.exclusiveMaximum);const r=2147483647;return typeof t.maximum=="number"&&t.maximum>r&&delete t.maximum,typeof t.minimum=="number"&&t.minimum<-r&&delete t.minimum,t}function eIt(e,t){const r=[],n=new Wv,o=[],i=[],s=new Set(t??[]),a=new Map;for(const[l,c]of Object.entries(e))try{const u=$qr(l),d=Uqr(u,f=>s.has(f));a.set(d,l),d!==l&&i.push({from:l,to:d});const p={name:d,description:c.description||`Tool: ${d}`},m=c;if(m.parameters||c.inputSchema){let f;const g=m.parameters||c.inputSchema;BH(g)?f=qo(g,"openApi3"):typeof g=="object"?f=g:f={type:"object",properties:{}},f.jsonSchema&&typeof f.jsonSchema=="object"&&!f.type&&(f=f.jsonSchema),p.parametersJsonSchema=Mm(Kn(f))}r.push(p),s.add(d),c.execute&&n.set(p.name,c.execute)}catch(u){o.push(l),h.error(`[buildNativeToolDeclarations] Failed to convert tool "${l}":`,u)}return o.length>0&&h.warn(`[buildNativeToolDeclarations] ${o.length} tool(s) skipped due to schema errors: ${o.join(", ")}`),i.length>0&&h.warn(`[buildNativeToolDeclarations] ${i.length} tool name(s) sanitized for Google's function-name regex: ${i.map(l=>`"${l.from}" -> "${l.to}"`).join(", ")}`),{toolsConfig:[{functionDeclarations:r}],executeMap:n,originalNameMap:a}}function SO(e,t,r){const n={},o=(i,s)=>r?pg(i,s,r):async(a,l)=>s(a,l);if(e){for(const[i,s]of e.originalNameMap){const a=e.executeMap.get(i);a&&(n[s]={execute:o(s,a)})}return n}for(const[i,s]of Object.entries(t??{})){const a=s?.execute;a&&(n[i]={execute:o(i,a)})}return n}function Bqr(e,t){if(!e)return[];const r=new Set(t.originalNameMap.values()),n=Object.entries(e).filter(([i])=>!r.has(i));if(n.length===0)return[];const o=eIt(Object.fromEntries(n),new Set(t.originalNameMap.keys()));t.toolsConfig[0].functionDeclarations.push(...o.toolsConfig[0].functionDeclarations);for(const[i,s]of o.originalNameMap)t.originalNameMap.set(i,s);for(const[i,s]of o.executeMap)t.executeMap.set(i,s);return h.info(`[buildNativeToolDeclarations] ${n.length} tool(s) hydrated mid-turn via discovery: ${n.map(([i])=>i).join(", ")}`),n.map(([i])=>i)}function tIt(e,t){const r=Ac("google-ai",e.model,{temperature:e.temperature??1,topP:e.topP},"googleAiStudio.buildNativeConfig"),n={...r.temperature!==void 0&&{temperature:r.temperature},...r.topP!==void 0&&{topP:r.topP},maxOutputTokens:e.maxTokens};t&&(n.tools=t),e.systemPrompt&&(n.systemInstruction=e.systemPrompt);const o=mY(e.thinkingConfig,e.model);return o&&(n.thinkingConfig=o),t||((e.responseSchema||e.wantsJsonOutput)&&(n.responseMimeType="application/json"),e.responseSchema&&(n.responseSchema=e.responseSchema)),n}function rIt(e){const t=e||ts;return Number.isFinite(t)&&t>0?Math.min(Math.floor(t),TY):Math.min(ts,TY)}function mg(e){switch(e){case"MAX_TOKENS":return"length";case"MALFORMED_FUNCTION_CALL":case"UNEXPECTED_TOOL_CALL":return"error";case"SAFETY":case"RECITATION":case"BLOCKLIST":case"PROHIBITED_CONTENT":case"SPII":case"IMAGE_SAFETY":return"content-filter";default:return"stop"}}function zqr(e,t){return t?e?`${e}
|
|
1030
|
+
Based on this analysis, provide your response.`;h.debug("[VideoAnalysis] Formatting via Claude",{userTextLength:s.length,analysisLength:i.length});const u=await hUe(n,{...t.systemPrompt?{system:t.systemPrompt}:{},prompt:c,maxOutputTokens:t.maxTokens||8192,temperature:.3,...t.abortSignal?{abortSignal:t.abortSignal}:{}});a=u.text,l=mM(u.usage),h.debug("[VideoAnalysis] Claude formatting complete",{formattedLength:a.length,usage:l})}catch(c){h.warn("[VideoAnalysis] Claude formatting failed, using raw Gemini output",{error:c instanceof Error?c.message:String(c)})}return this.enhanceResult({content:a,provider:t.provider??this.providerName,model:this.modelName,usage:l},t,o)}async finalizeNativeGenerate(t,r,n){await this.recordPerformanceMetrics(t.usage,Date.now()-n);const o=await this.synthesizeAIResponseIfNeeded(t,r);return this.enhanceResult(o,r,n)}fireGenerateOnFinish(t,r,n){const o=t.onFinish;if(typeof o=="function")try{const i=r?.usage,s=o({text:r?.content||"",usage:i?{promptTokens:i.input??0,completionTokens:i.output??0}:void 0,duration:Date.now()-n,finishReason:r?.finishReason??"stop"});Promise.resolve(s).catch(a=>h.warn(`[${this.providerName}] onFinish callback rejected: ${a instanceof Error?a.message:String(a)}`))}catch(i){h.warn(`[${this.providerName}] onFinish callback threw: ${i instanceof Error?i.message:String(i)}`)}}async synthesizeAIResponseIfNeeded(t,r){if(!r.tts?.enabled||!r.tts?.useAiResponse)return t;const n=r.tts,o=t.content,i=n.provider??r.provider??this.providerName;if(!o||!i)return h.warn("TTS synthesis skipped despite being enabled",{provider:this.providerName,hasAiResponse:!!o,aiResponseLength:o?.length??0,hasProvider:!!i,ttsConfig:{enabled:r.tts?.enabled,useAiResponse:r.tts?.useAiResponse},reason:o?"Provider is missing":"AI response is empty or undefined"}),{...t,ttsMetadata:{attempted:!1,success:!1}};const s=Date.now(),a=this.getTimeout(r);try{const l=await w4(()=>Nc.synthesize(o,i,n),a,`TTS synthesis timed out after ${a}ms for provider "${i}"`);return{...t,audio:l,ttsMetadata:{attempted:!0,success:!0,latency:Date.now()-s}}}catch(l){const c=Date.now()-s,u=this.getTTSErrorDetails(l);return this.telemetryHandler.recordTTSFailure(i,u,c),h.error("TTS synthesis failed in Mode 2 (AI response synthesis):",l),{...t,ttsMetadata:{attempted:!0,success:!1,error:u,latency:c}}}}getTTSErrorDetails(t){const r=Jh(t).message;return t instanceof ku?{code:Tt.SYNTHESIS_FAILED,message:r,retriable:!0}:t instanceof De?{code:t.code,message:r,retriable:t.retriable}:{code:Tt.SYNTHESIS_FAILED,message:r}}async generateText(t){const r=t.prompt||t.input?.text;if(!r||typeof r!="string"||r.trim()==="")throw new Error("GenerateText options must include prompt or input.text as a non-empty string");const n=await this.generate(t);if(!n)throw new Error("Generation failed: No result returned");return{content:n.content||"",provider:n.provider||this.providerName,model:n.model||this.modelName,usage:n.usage||{input:0,output:0,total:0},responseTime:0,toolsUsed:n.toolsUsed||[],toolExecutions:n.toolExecutions?.map(o=>({toolName:o.toolName,executionTime:o.durationMs,success:!o.isError})),enhancedWithTools:!!(n.toolsUsed&&n.toolsUsed.length>0),analytics:n.analytics,evaluation:n.evaluation,audio:n.audio,reasoning:n.reasoning,reasoningTokens:n.reasoningTokens}}async embed(t,r){const n=typeof t=="string"?t.length:t.text?.length??0;throw h.warn(`embed() called on ${this.providerName} which does not have a native implementation`,{textLength:n}),new Error(`Embedding generation is not supported by the ${this.providerName} provider. Supported providers: openai, vertex/google, bedrock, cohere, voyage, jina. Use an embedding model like text-embedding-3-small (OpenAI), text-embedding-004 (Vertex), embed-english-v3.0 (Cohere), voyage-3 (Voyage), jina-embeddings-v3 (Jina), or amazon.titan-embed-text-v2:0 (Bedrock).`)}async embedMany(t,r){throw h.warn(`embedMany() called on ${this.providerName} which does not have a native implementation`,{count:t.length}),new Error(`Batch embedding generation is not supported by the ${this.providerName} provider. Supported providers: openai, googleAiStudio, vertex/google, bedrock, cohere, voyage, jina. Use an embedding model like text-embedding-3-small (OpenAI), gemini-embedding-001 (Google AI), text-embedding-004 (Vertex), embed-english-v3.0 (Cohere), voyage-3 (Voyage), jina-embeddings-v3 (Jina), or amazon.titan-embed-text-v2:0 (Bedrock).`)}getDefaultEmbeddingModel(){}async decide(t){throw h.warn(`decide() called on ${this.providerName}, which does not serve the decide inference type`),new Error(`The decide inference type is not supported by the ${this.providerName} provider. Supported providers: ${Ny.map(r=>r.name).join(", ")}. A provider declares this capability with "decide" in its descriptor's inferenceKinds.`)}getDefaultDecisionModel(){}getToolCallRepairFn(t){if(!t?.disableToolCallRepair)return(async(...r)=>{const{createToolCallRepair:n}=await Promise.resolve().then(()=>(aY(),R1t));return n()(...r)})}async executeStream(t,r){if(!this.doStream)throw new De({code:He.INVALID_CONFIGURATION,message:`${this.providerName} cannot stream: it neither implements doStream() nor overrides executeStream()`,category:"configuration",severity:"critical",retriable:!1,context:{provider:this.providerName,model:this.modelName}});const n=Date.now(),{stream:o,finishReason:i,usage:s,warnings:a}=await this.doStream(t);a?.length&&h.warn(`[${this.providerName}] doStream reported warnings`,{provider:this.providerName,count:a.length});const l={startTime:n,streamId:`${this.providerName}-${n}`},c=(async()=>{const[u,d]=await Promise.all([i,s]);return l.finishReason=u,l.rawFinishReason=u,cv(this.providerName,this.modelName||this.getDefaultModel(),{usage:{input:d.inputTokens,output:d.outputTokens,total:d.inputTokens+d.outputTokens},stopReason:u},Date.now()-n,{streamingMode:!0})})();return{stream:o,model:this.modelName||this.getDefaultModel(),provider:this.getProviderName(),analytics:c,metadata:l}}async withTurnTimeout(t,r,n){const i=typeof t.turnTimeoutMs=="number"&&Number.isFinite(t.turnTimeoutMs)&&t.turnTimeoutMs>0?t.turnTimeoutMs:t.timeout??Math.max(r??0,18e4),s=wa(i,this.providerName,"generate"),a=Cy(t.abortSignal,s?.controller.signal),l=a?{...t,abortSignal:a}:t;try{return await n(l)}catch(c){const u=s?.controller.signal.aborted?s.controller.signal.reason:void 0;throw u instanceof Ta&&pr(c)&&t.abortSignal?.aborted!==!0?u:c}finally{s?.cleanup()}}emitTurnEvent(t){try{this.neurolink?.getEventEmitter()?.emit("turn:lifecycle",{provider:this.providerName,timestamp:Date.now(),...t})}catch{}}getDescriptorGenerateMs(){return hr.get(this.providerName)?.timeouts?.generateMs}getDescriptorDecideMs(){return hr.get(this.providerName)?.timeouts?.decideMs}getModel(){return this.getAISDKModel()}async getAISDKModelWithMiddleware(t={}){return this.applyMiddlewareToModel(await this.getAISDKModel(),t)}async applyMiddlewareToModel(t,r={}){h.debug(`Retrieved base model for ${this.providerName}`,{provider:this.providerName,model:this.modelName,hasMiddlewareConfig:!!this.middlewareOptions,timestamp:Date.now()});const n=this.extractMiddlewareOptions(r);if(h.debug("Middleware extraction result",{provider:this.providerName,model:this.modelName,middlewareOptions:n}),!n)return t;try{h.debug(`Applying middleware to ${this.providerName} model`,{provider:this.providerName,model:this.modelName,middlewareOptions:n});const o=new Mj(n),i=o.createContext(this.providerName,this.modelName,r,{sessionId:this.sessionId,userId:this.userId}),s=o.applyMiddleware(t,i,n);return h.debug(`Applied middleware to ${this.providerName} model`,{provider:this.providerName,model:this.modelName,hasMiddleware:!0}),s}catch(o){return h.warn(`Failed to apply middleware to ${this.providerName}, using base model`,{error:o instanceof Error?o.message:String(o)}),t}}extractMiddlewareOptions(t){return this.utilities.extractMiddlewareOptions(t)}isZodSchema(t){return this.utilities.isZodSchema(t)}async convertToolResult(t){return this.utilities.convertToolResult(t)}fixSchemaForOpenAIStrictMode(t){return this.utilities.fixSchemaForOpenAIStrictMode(t)}setFileToolRootPolicy(t){t===void 0||Object.keys(this.directTools).length===0||(this.fileToolRootsBound=!0,this.toolsManager.setDirectTools(t.roots===null?this.directTools:hV(t)))}applyFileToolRoots(t){if(Object.keys(this.directTools).length===0)return;const r=wV(t);if(r!==void 0){this.setFileToolRootPolicy(r);return}this.fileToolRootsBound&&t.toolRoots===void 0||this.setFileToolRootPolicy(_P({perCall:t.toolRoots,instance:this.neurolink?.getToolsConfig()?.fileRoots}))}async getAllTools(){return this.fileToolRootsBound||this.applyFileToolRoots({}),this.toolsManager.getAllTools()}async calculateActualCost(t){return this.telemetryHandler.calculateActualCost(t)}createPermissiveZodSchema(){return this.utilities.createPermissiveZodSchema()}setSessionContext(t,r){this.sessionId=t,this.userId=r,this.toolsManager.setSessionContext(t,r)}classifyStreamError(t){const r=t instanceof Error?t:new Error(String(t));return X1t(r)||r instanceof nt||iE(r)===void 0?r:this.handleProviderError(r)}handleProviderError(t){if(pr(t))return t instanceof Error?t:new DOMException("The operation was aborted","AbortError");if(t instanceof Error&&X1t(t))return t;const r=this.formatProviderError(t);if(t&&typeof t=="object"&&r!==t){const n=t,o=r,i=iE(t);if(i!==void 0&&o.statusCode===void 0&&(o.statusCode=i),typeof n.isRetryable=="boolean"&&o.isRetryable===void 0&&(o.isRetryable=n.isRetryable),o.retryAfterMs===void 0){const s=Fbe(t);s!==void 0&&(o.retryAfterMs=s)}}kS(t)&&HP(r);try{const n=dt.getSpan(xr.active());if(n){let o="provider_error";const i=r?.constructor?.name??"";i==="RateLimitError"?o="rate_limit":i==="AuthenticationError"?o="auth_failure":i==="NetworkError"?o="network":i==="InvalidModelError"?o="invalid_model":i==="TimeoutError"&&(o="timeout"),n.setAttribute("error.type",o),r instanceof Error&&n.setAttribute("error.message",r.message.substring(0,500))}}catch{}return Dqr(r),r}async executeImageGeneration(t){throw new Error(`Image generation is not supported by the ${this.providerName} provider or the selected model.`)}async executeWithTimeout(t,r){const n=this.getTimeout(r),o=wa(n,this.providerName,r.operationType||"generate");try{return o?await Promise.race([t(),new Promise((i,s)=>{o.controller.signal.addEventListener("abort",()=>{s(new Ta(`${this.providerName} operation timed out`,o.timeoutMs,this.providerName,r.operationType||"generate"))})})]):await t()}finally{o?.cleanup()}}validateStreamOptions(t){this.streamHandler.validateStreamOptions(t)}createTextStream(t,r){return this.streamHandler.createTextStream(t,r)}createStreamResult(t,r={}){return this.streamHandler.createStreamResult(t,r)}async createStreamAnalytics(t,r,n){return this.streamHandler.createStreamAnalytics(t,r,n)}handleCommonErrors(t){return this.utilities.handleCommonErrors(t)}setupToolExecutor(t,r){this.toolsManager.setupToolExecutor(t,r)}normalizeTextOptions(t){return this.utilities.normalizeTextOptions(t)}normalizeStreamOptions(t){return this.utilities.normalizeStreamOptions(t)}async enhanceResult(t,r,n){const o=Date.now()-n,i=t.imageOutput;let s={...t};if(r.enableAnalytics)try{const a=await this.createAnalytics(t,o,r);s={...s,analytics:a,imageOutput:i}}catch(a){h.warn(`Analytics creation failed for ${this.providerName}:`,a)}if(r.enableEvaluation)try{const a=await this.createEvaluation(t,r);s={...s,evaluation:a,imageOutput:i}}catch(a){h.warn(`Evaluation creation failed for ${this.providerName}:`,a)}return i&&(s.imageOutput=i),s}async handleVideoGeneration(t,r){const{VideoProcessor:n,VideoError:o,VIDEO_ERROR_CODES:i}=await Promise.resolve().then(()=>(Pm(),U1t)),{validateVideoGenerationInput:s,validateImageForVideo:a,validateDirectorModeInput:l}=await Promise.resolve().then(()=>(Xd(),tSt)),{ErrorFactory:c}=await Promise.resolve().then(()=>(et(),rE)),u={input:t.input||{text:t.prompt||""},output:t.output,provider:t.provider,model:t.model};if(u.input?.segments&&Array.isArray(u.input.segments)&&u.input.segments.length>0){const C=u.input.segments,R=l(u);if(!R.isValid)throw c.invalidParameters("director-mode",new Error(R.errors.map(J=>J.message).join("; ")),{errors:R.errors});if(R.warnings.length>0)for(const J of R.warnings)h.warn(`Director Mode warning: ${J}`);const{executeDirectorPipeline:O,DIRECTOR_PIPELINE_TIMEOUT_MS:U}=await Promise.resolve().then(()=>(Oqr(),z1t)),M=t.timeout??U,D=await this.executeWithTimeout(()=>O(C,u.output?.video??{},u.output?.director??{},t.region),{timeout:M,operationType:"generate"}),$=u.input.segments.map(J=>J.prompt).join(" \u2192 "),B=D.metadata?.segmentCount??u.input.segments.length,q=D.metadata?.transitionCount??Math.max(0,B-1),L=D.metadata?.duration??0,G={content:`${$} \u2014 duration: ${L}s, segments: ${B}, transitions: ${q}`,provider:"vertex",model:t.model||"veo-3.1-generate-001",usage:{input:0,output:0,total:0},video:D};return await this.enhanceResult(G,t,r)}const d=s(u);if(!d.isValid)throw c.invalidParameters("video-generation",new Error(d.errors.map(C=>C.message).join("; ")),{errors:d.errors});if(d.warnings.length>0)for(const C of d.warnings)h.warn(`Video generation warning: ${C}`);const p=t.input?.images?.[0];if(!p)throw new o({code:i.INVALID_INPUT,message:"Video generation requires an input image. Provide via input.images array.",retriable:!1,context:{field:"input.images"}});const m=15e3;let f;if(typeof p=="string")if(p.startsWith("http://")||p.startsWith("https://")){h.debug("Fetching image from URL for video generation",{url:p.substring(0,100)});let C;try{C=await this.executeWithTimeout(()=>fetch(p),{timeout:m,operationType:"generate"})}catch(R){throw new o({code:i.INVALID_INPUT,message:`Failed to fetch image from URL: ${R instanceof Error?R.message:"Request timed out"}`,retriable:!0,context:{url:p,timeout:m},originalError:R instanceof Error?R:void 0})}if(!C.ok)throw new o({code:i.INVALID_INPUT,message:`Failed to fetch image from URL: ${C.status} ${C.statusText}`,retriable:C.status>=500,context:{url:p,status:C.status}});f=Buffer.from(await C.arrayBuffer())}else{h.debug("Reading image from path for video generation",{path:p});const C=await Promise.resolve().then(()=>(Yr(),gv));try{f=await this.executeWithTimeout(()=>C.readFile(p),{timeout:m,operationType:"generate"})}catch(R){throw new o({code:i.INVALID_INPUT,message:`Failed to read image file: ${R instanceof Error?R.message:String(R)}`,retriable:!1,context:{path:p,timeout:m},originalError:R instanceof Error?R:void 0})}}else if(Buffer.isBuffer(p))f=p;else if(typeof p=="object"&&"data"in p){const C=p.data;if(typeof C=="string")f=Buffer.from(C,"base64");else if(Buffer.isBuffer(C))f=C;else throw new o({code:i.INVALID_INPUT,message:"ImageWithAltText.data must be a base64 string or Buffer.",retriable:!1,context:{field:"input.images[0].data",type:typeof C}})}else throw new o({code:i.INVALID_INPUT,message:"Invalid image input type. Provide Buffer, path string, URL, or ImageWithAltText.",retriable:!1,context:{field:"input.images[0]",type:typeof p}});const g=a(f);if(g)throw c.invalidParameters("video-generation",new Error(g.message),{field:"input.images[0]",validation:g});const y=t.prompt||t.input?.text||"",v=t.output?.video?.provider??qPr("video");if(!n.supports(v))throw new o({code:i.PROVIDER_NOT_SUPPORTED,message:`Video provider "${v}" is not registered. Available: ${n.listProviders().join(", ")}`,retriable:!1,context:{provider:v,available:n.listProviders()}});const b=t.output?.video?.model??t.model??(v==="vertex"?"veo-3.1-generate-001":void 0);h.info("Starting video generation",{provider:v,...b?{model:b}:{},promptLength:y.length,imageSize:f.length,resolution:t.output?.video?.resolution||"720p",duration:t.output?.video?.length||6});const S=t.timeout??6e5,k=t.output?.video?.abortSignal??t.abortSignal,A=await this.executeWithTimeout(()=>n.generate(v,{...t.output?.video??{},image:f,prompt:y,region:t.region,abortSignal:k}),{timeout:S,operationType:"generate"}),x=A.metadata?.model??b??(v==="vertex"?"veo-3.1-generate-001":"unknown");h.info("Video generation complete",{provider:v,model:x,videoSize:A.data.length,duration:A.metadata?.duration,processingTime:A.metadata?.processingTime});const P={content:y,provider:v,model:x,usage:{input:0,output:0,total:0},video:A};return await this.enhanceResult(P,t,r)}async createAnalytics(t,r,n){return this.telemetryHandler.createAnalytics(t,r,n.context)}async createEvaluation(t,r){return this.telemetryHandler.createEvaluation(t,r)}validateOptions(t){this.utilities.validateOptions(t)}getProviderInfo(){return this.utilities.getProviderInfo()}getTimeout(t){return this.utilities.getTimeout(t)}async handleToolExecutionStorage(t,r,n,o){return this.telemetryHandler.handleToolExecutionStorage(t,r,n,o)}static chunkPrompt(t,r=9e5,n=100){if(t.length<=r)return[t];const o=[];let i=0;for(;i<t.length;){const s=Math.min(i+r,t.length);if(o.push(t.slice(i,s)),s>=t.length)break;const a=s-n;a<=i?i=s:i=Math.max(a,0)}return o}}}});async function ug(e,t){try{await e}catch(r){h.debug(`[${t}] detached stream pump rejected; reason absorbed because the turn's own error is authoritative`,r)}}var pY=E({"src/lib/utils/drainDetachedPump.ts"(){"use strict";z()}}),dg=E({"src/lib/utils/async/index.ts"(){"use strict";Kr()}});function pg(e,t,r){return async(n,o)=>{const i=()=>Promise.resolve(t(n,o)),s=r.withToolSpan,a=s?()=>s(e,i):i;r.onProgress?.();try{const l=r.abortSignal?Su(a(),r.abortSignal):a();return await(r.toolTimeoutMs===void 0||r.toolTimeoutMs===null?l:It(l,r.toolTimeoutMs,`Tool "${e}" execution timed out after ${r.toolTimeoutMs}ms`))}finally{r.onProgress?.()}}}var EO=E({"src/lib/core/toolExecutionGuards.ts"(){"use strict";dg()}});function Lqr(e,t){const r=Z1t[e];return Math.round(t.min+r*(t.max-t.min))}function mY(e,t){if(!e?.enabled&&!e?.thinkingLevel)return;const r=e.thinkingLevel??Y1t;if(t&&!sqr(t)){const n=aqr(t);if(n)return{includeThoughts:!0,thinkingBudget:Lqr(r,n)};hY.has(t)||(hY.add(t),h.warn(`[thinkingConfig] "${t}" has no verified Gemini thinkingBudget range; omitting thinkingConfig \u2014 requested thinkingLevel is silently disabled.`));return}return{includeThoughts:!0,thinkingLevel:r}}var Y1t,Z1t,hY,Q1t=E({"src/lib/utils/thinkingConfig.ts"(){"use strict";fO(),z(),Y1t="high",Z1t={minimal:0,low:.25,medium:.55,high:1},hY=new Set}});function Fqr(e){return JSON.stringify(e,(t,r)=>r&&typeof r=="object"&&!Array.isArray(r)?Object.keys(r).sort().reduce((n,o)=>(n[o]=r[o],n),{}):r)}function $qr(e){if(pIt.test(e))return e;let t=e.replace(/[^A-Za-z0-9_.:-]/g,"_");return/^[A-Za-z_]/.test(t)||(t=`_${t}`),t.length>AO&&(t=t.slice(0,AO)),t}function Uqr(e,t){if(!t(e))return e;let r=2;for(;;){const n=`_${r}`,i=`${e.slice(0,AO-n.length)}${n}`;if(!t(i))return i;r++}}function Mm(e){if(Array.isArray(e.anyOf)||Array.isArray(e.oneOf)){const n=e.anyOf?"anyOf":"oneOf",o=e[n],i=o.filter(c=>c.type!=="null"&&c.type!=="undefined");if(i.length===1){const c=Mm({...i[0]});return c.nullable=!0,e.description&&(c.description=e.description),c}const s=i.map(c=>c.type||"unknown").join(" | "),a={type:"string"},l=e.description?`${e.description} (accepts: ${s})`:`Value as string (accepts: ${s})`;return a.description=l,o.some(c=>c.type==="null")&&(a.nullable=!0),a}const t={};for(const[n,o]of Object.entries(e))if(!(n==="$schema"||n==="additionalProperties"||n==="default"))if(n==="properties"&&o&&typeof o=="object"){const i={};for(const[s,a]of Object.entries(o))a&&typeof a=="object"?i[s]=Mm(a):i[s]=a;t[n]=i}else n==="items"&&o&&typeof o=="object"?Array.isArray(o)?t[n]=o.map(i=>i&&typeof i=="object"?Mm(i):i):t[n]=Mm(o):t[n]=o;Array.isArray(t.allOf)&&(t.allOf=t.allOf.map(n=>Mm(n))),t.not&&typeof t.not=="object"&&(t.not=Mm(t.not));for(const n of["if","then","else"])t[n]&&typeof t[n]=="object"&&(t[n]=Mm(t[n]));typeof t.exclusiveMinimum=="boolean"&&(t.exclusiveMinimum===!0&&typeof t.minimum=="number"?(t.exclusiveMinimum=t.minimum,delete t.minimum):delete t.exclusiveMinimum),typeof t.exclusiveMaximum=="boolean"&&(t.exclusiveMaximum===!0&&typeof t.maximum=="number"?(t.exclusiveMaximum=t.maximum,delete t.maximum):delete t.exclusiveMaximum);const r=2147483647;return typeof t.maximum=="number"&&t.maximum>r&&delete t.maximum,typeof t.minimum=="number"&&t.minimum<-r&&delete t.minimum,t}function eIt(e,t){const r=[],n=new Wv,o=[],i=[],s=new Set(t??[]),a=new Map;for(const[l,c]of Object.entries(e))try{const u=$qr(l),d=Uqr(u,f=>s.has(f));a.set(d,l),d!==l&&i.push({from:l,to:d});const p={name:d,description:c.description||`Tool: ${d}`},m=c;if(m.parameters||c.inputSchema){let f;const g=m.parameters||c.inputSchema;BH(g)?f=qo(g,"openApi3"):typeof g=="object"?f=g:f={type:"object",properties:{}},f.jsonSchema&&typeof f.jsonSchema=="object"&&!f.type&&(f=f.jsonSchema),p.parametersJsonSchema=Mm(Kn(f))}r.push(p),s.add(d),c.execute&&n.set(p.name,c.execute)}catch(u){o.push(l),h.error(`[buildNativeToolDeclarations] Failed to convert tool "${l}":`,u)}return o.length>0&&h.warn(`[buildNativeToolDeclarations] ${o.length} tool(s) skipped due to schema errors: ${o.join(", ")}`),i.length>0&&h.warn(`[buildNativeToolDeclarations] ${i.length} tool name(s) sanitized for Google's function-name regex: ${i.map(l=>`"${l.from}" -> "${l.to}"`).join(", ")}`),{toolsConfig:[{functionDeclarations:r}],executeMap:n,originalNameMap:a}}function SO(e,t,r){const n={},o=(i,s)=>r?pg(i,s,r):async(a,l)=>s(a,l);if(e){for(const[i,s]of e.originalNameMap){const a=e.executeMap.get(i);a&&(n[s]={execute:o(s,a)})}return n}for(const[i,s]of Object.entries(t??{})){const a=s?.execute;a&&(n[i]={execute:o(i,a)})}return n}function Bqr(e,t){if(!e)return[];const r=new Set(t.originalNameMap.values()),n=Object.entries(e).filter(([i])=>!r.has(i));if(n.length===0)return[];const o=eIt(Object.fromEntries(n),new Set(t.originalNameMap.keys()));t.toolsConfig[0].functionDeclarations.push(...o.toolsConfig[0].functionDeclarations);for(const[i,s]of o.originalNameMap)t.originalNameMap.set(i,s);for(const[i,s]of o.executeMap)t.executeMap.set(i,s);return h.info(`[buildNativeToolDeclarations] ${n.length} tool(s) hydrated mid-turn via discovery: ${n.map(([i])=>i).join(", ")}`),n.map(([i])=>i)}function tIt(e,t){const r=Ac("google-ai",e.model,{temperature:e.temperature??1,topP:e.topP},"googleAiStudio.buildNativeConfig"),n={...r.temperature!==void 0&&{temperature:r.temperature},...r.topP!==void 0&&{topP:r.topP},maxOutputTokens:e.maxTokens};t&&(n.tools=t),e.systemPrompt&&(n.systemInstruction=e.systemPrompt);const o=mY(e.thinkingConfig,e.model);return o&&(n.thinkingConfig=o),t||((e.responseSchema||e.wantsJsonOutput)&&(n.responseMimeType="application/json"),e.responseSchema&&(n.responseSchema=e.responseSchema)),n}function rIt(e){const t=e||ts;return Number.isFinite(t)&&t>0?Math.min(Math.floor(t),TY):Math.min(ts,TY)}function mg(e){switch(e){case"MAX_TOKENS":return"length";case"MALFORMED_FUNCTION_CALL":case"UNEXPECTED_TOOL_CALL":return"error";case"SAFETY":case"RECITATION":case"BLOCKLIST":case"PROHIBITED_CONTENT":case"SPII":case"IMAGE_SAFETY":return"content-filter";default:return"stop"}}function zqr(e,t){return t?e?`${e}
|
|
1031
1031
|
${t}`:t:e}async function Gqr(e,t){const r=[],n=[];let o=0,i=0,s=0,a=0,l;for await(const c of e){const u=c,p=u.candidates?.[0],m=p?.finishReason;typeof m=="string"&&(l=m);const f=p?.content;if(f&&Array.isArray(f.parts))for(const y of f.parts)r.push(y),typeof y.text=="string"&&y.text.length>0&&t.push({content:y.text});c.functionCalls&&n.push(...c.functionCalls);const g=u.usageMetadata;g&&(o=Math.max(o,g.promptTokenCount||0),i=Math.max(i,g.candidatesTokenCount||0),s=Math.max(s,g.cachedContentTokenCount||0),a=Math.max(a,g.thoughtsTokenCount||0))}return{rawResponseParts:r,stepFunctionCalls:n,finishReason:l,inputTokens:o,outputTokens:i,cacheReadTokens:s,reasoningTokens:a}}function kO(e){for(let t=e.length-1;t>=0;t--){const r=e[t];if(r!=null&&typeof r=="object"&&"thoughtSignature"in r&&typeof r.thoughtSignature=="string")return r.thoughtSignature}}function qqr(e){return e.filter(t=>typeof t.text=="string").map(t=>t.text).join("")}function nIt(e,t,r,n,o){return t>=r&&!n?(h.warn(`${e} Tool call loop terminated after reaching maxSteps (${r}). Model was still calling tools. Using accumulated text from last step.`),o||Dm(r,0)):n}function Om(e){if(!e)return!1;const t=e;return t.name==="AbortError"||typeof t.message=="string"&&/abort/i.test(t.message)||typeof DOMException<"u"&&e instanceof DOMException&&t.code===20}function Dm(e,t){return`${t>0?`I gathered information across ${t} tool call${t===1?"":"s"} but `:"I "}reached the ${e}-step limit for a single turn before I could finish. Please narrow the request or break it into smaller asks and I'll continue.`}function Wl(e){return`${e>0?`I gathered information across ${e} tool call${e===1?"":"s"} but `:"I "}had to stop because the gathered material filled this turn's context window before I could finish. Please narrow the request or break it into smaller asks and I'll continue.`}function oIt(e){const t=Math.max(0,Math.round(e/1e3)),r=Math.floor(t/60),n=t%60;return r>0?`${r}m ${n}s`:`${n}s`}function Vqr(e,t){const r=t>0?` I completed ${t} tool call${t===1?"":"s"} before stopping;`:"";return`I had to stop after ${oIt(e)} \u2014 this turn hit its processing time limit.${r} ask me to continue and I'll pick up from there.`}function jqr(e,t){const r=t>0?` I completed ${t} tool call${t===1?"":"s"} before stopping;`:"";return`I had to stop because this turn made no progress for ${oIt(e)} \u2014 a tool or model call appears to be stuck.${r} ask me to continue and I'll pick up from there.`}function Hqr(e){return`This turn was stopped before I could finish.${e>0?` I completed ${e} tool call${e===1?"":"s"} before stopping.`:""}`}function fY(e){return e.timedOut?Vqr(e.elapsedMs,e.toolCallCount):e.stalled?jqr(e.stallTimeoutMs??0,e.toolCallCount):e.wasAborted?Hqr(e.toolCallCount):Dm(e.maxSteps,e.toolCallCount)}function Vv(e){return"NOTE: processing time for this turn is nearly up. Consolidate what you have and "+(e?"call final_result with your best answer now.":"provide your final answer now.")}function ep(e){return e.timedOut?"time-limit":e.stalled?"stalled":e.wasAborted?"aborted":e.contextCappedWithoutAnswer?"context-cap":e.cappedWithoutAnswer?"step-cap":e.finishReason==="error"?"provider-error":"completed"}function jv(e){const t=Date.now(),r=u=>u!==void 0&&Number.isFinite(u)&&u>0,n=r(e.turnTimeoutMs)?e.turnTimeoutMs:r(e.defaultTurnTimeoutMs)?e.defaultTurnTimeoutMs:void 0,o=r(e.turnTimeoutMs)?e.wrapupTimeLeadMs??yAe:void 0;let i=!1,s=!1,a=t,l,c;if(n!==void 0&&(l=setTimeout(()=>{i=!0,e.onDeadline("timeout")},n),l.unref?.()),r(e.stallTimeoutMs)){const u=e.stallTimeoutMs,d=Math.min(Math.max(1e3,Math.floor(u/4)),15e3);c=setInterval(()=>{!s&&!i&&Date.now()-a>=u&&(s=!0,e.onDeadline("stall"))},d),c.unref?.()}return{get timedOut(){return i},get stalled(){return s},get expired(){return i||s},get turnTimeoutMs(){return n},elapsedMs(){return Date.now()-t},noteProgress(){a=Date.now()},shouldNudgeWrapup(){if(n===void 0||o===void 0)return!1;const u=n-(Date.now()-t);return u>0&&u<=o},dispose(){l&&clearTimeout(l),c&&clearInterval(c)}}}function Hv(e,t=M4){const r=Math.floor(e*t);let n=0,o=0;return{get thresholdTokens(){return r},get projectedNextPromptTokens(){return n+o},noteUsage(i,s){i>0&&(n=i,o=Math.max(0,s))},noteAppendedChars(i){i>0&&(o+=Math.ceil(i/4))},resetAfterReclaim(){n=0,o=0},shouldStop(){return n>0&&n+o>=r}}}function Wqr(e,t,r){e.push({role:"model",parts:t.length>0?t:r.map(n=>({functionCall:n}))})}function iIt(e){const t=qo(e,"openApi3"),r=Kn(t);return r.$schema&&delete r.$schema,ea(r)}function xO(e,t){if(!t||t.length===0)return;const r=new Map,n=[];let o=0;const i=a=>`${o}:${a??"undefined"}`,s=a=>{const l=i(a),c=r.get(l);if(c)return c;const u={type:"tool_step",callParts:[],resultParts:[]};return r.set(l,u),n.push(u),u};for(const a of t){if(a.role==="tool_call"){const u=s(a.metadata?.stepIndex),d={functionCall:{name:a.tool||"unknown",args:a.args||{}}};a.metadata?.thoughtSignature&&(d.thoughtSignature=a.metadata.thoughtSignature),u.callParts.push(d);continue}if(a.role==="tool_result"){const u=s(a.metadata?.stepIndex);let d;try{d=a.content!==void 0&&a.content!==null?{result:JSON.parse(a.content)}:{result:"success"}}catch{d={result:a.content??"success"}}u.resultParts.push({functionResponse:{name:a.tool||"unknown",response:d}});continue}const l=a.role==="assistant"?"model":a.role;if(l!=="user"&&l!=="model"||!a.content||a.content.trim().length===0)continue;o++;const c={text:a.content};a.metadata?.thoughtSignature&&(c.thoughtSignature=a.metadata.thoughtSignature),n.push({type:"regular",role:l,parts:[c]})}for(const a of n){if(a.type==="regular"){e.push({role:a.role,parts:a.parts});continue}if(a.callParts.length===0){a.resultParts.length>0&&h.debug("[GoogleNativeGemini3] Dropping orphan tool_result segment with no matching tool_call rows",{resultCount:a.resultParts.length});continue}e.push({role:"model",parts:a.callParts}),a.resultParts.length>0&&e.push({role:"user",parts:a.resultParts})}}function sIt(e){return typeof e!="object"||e===null||!("text"in e)?!1:typeof e.text=="string"}function Kqr(e){if(typeof e!="object"||e===null||!("inlineData"in e))return!1;const t=e.inlineData;return typeof t=="object"&&t!==null&&"mimeType"in t&&"data"in t}function Jqr(e){return typeof e=="object"&&e!==null&&"functionCall"in e}function aIt(e){return typeof e=="object"&&e!==null&&"functionResponse"in e}function lIt(e){if(!(typeof e!="object"||e===null||!("thoughtSignature"in e)))return typeof e.thoughtSignature=="string"?e.thoughtSignature:void 0}function gY(e,t){return t?{...e,providerOptions:{...e.providerOptions,googleAiStudio:{...e.providerOptions?.googleAiStudio,thoughtSignature:t}}}:e}function yY(e){if(typeof e!="object"||e===null)return;const t=e.googleAiStudio;if(typeof t!="object"||t===null)return;const r=t.thoughtSignature;return typeof r=="string"?r:void 0}function Xqr(e){return e.length>0&&e.every(aIt)}function Yqr(e){if(aIt(e))return{type:"tool-result",toolCallId:`gemini-tool-${Zr()}`,toolName:e.functionResponse.name,output:e.functionResponse.response}}function Zqr(e){if(sIt(e))return gY({type:"text",text:e.text},lIt(e));if(Kqr(e))return{type:"file",data:e.inlineData.data,mediaType:e.inlineData.mimeType}}function Qqr(e){if(sIt(e))return gY({type:"text",text:e.text},lIt(e));if(Jqr(e))return gY({type:"tool-call",toolCallId:`gemini-tool-${Zr()}`,toolName:e.functionCall.name,input:e.functionCall.args??{}},e.thoughtSignature)}function e7r(e){const t=[];for(const r of e){const n=Array.isArray(r.parts)?r.parts:[];if(r.role==="user"&&Xqr(n)){const o=n.map(Yqr).filter(i=>i!==void 0);o.length>0&&t.push({role:"tool",content:o});continue}if(r.role==="user"){const o=n.map(Zqr).filter(i=>i!==void 0);o.length>0&&t.push({role:"user",content:o});continue}if(r.role==="model"){const o=n.map(Qqr).filter(i=>i!==void 0);o.length>0&&t.push({role:"assistant",content:o})}}return t}function cIt(e){return typeof e=="string"?e:Buffer.isBuffer(e)?e.toString("base64"):e instanceof ArrayBuffer?Buffer.from(e).toString("base64"):Buffer.from(e.buffer,e.byteOffset,e.byteLength).toString("base64")}function t7r(e){if(typeof e=="string")return e.length>0?[{text:e}]:[];const t=[];for(const r of e)if(r.type==="text"){if(r.text.length>0){const n=yY(r.providerOptions);t.push(n?{text:r.text,thoughtSignature:n}:{text:r.text})}}else r.type==="image"&&!(r.image instanceof URL)?t.push({inlineData:{mimeType:r.mediaType??"application/octet-stream",data:cIt(r.image)}}):r.type==="file"&&!(r.data instanceof URL)&&t.push({inlineData:{mimeType:r.mediaType,data:cIt(r.data)}});return t}function r7r(e){if(typeof e=="string")return e.length>0?[{text:e}]:[];const t=[];for(const r of e)if(r.type==="text"){if(r.text.length>0){const n=yY(r.providerOptions);t.push(n?{text:r.text,thoughtSignature:n}:{text:r.text})}}else if(r.type==="tool-call"){const n=yY(r.providerOptions),o={functionCall:{name:r.toolName,args:r.input??{}}};n&&(o.thoughtSignature=n),t.push(o)}return t}function n7r(e){const t=[];for(const r of e)r.type==="tool-result"&&t.push({functionResponse:{name:r.toolName,response:r.output&&typeof r.output=="object"?r.output:{result:r.output}}});return t}function uIt(e){const t=[],r=[];for(const n of e){if(n.role==="system"){n.content.length>0&&r.push(n.content);continue}if(n.role==="user"){const i=t7r(n.content);i.length>0&&t.push({role:"user",parts:i});continue}if(n.role==="assistant"){const i=r7r(n.content);i.length>0&&t.push({role:"model",parts:i});continue}const o=n7r(n.content);o.length>0&&t.push({role:"user",parts:o})}return r.length>0?{contents:t,systemText:r.join(`
|
|
1032
1032
|
|
|
1033
|
-
`)}:{contents:t}}async function vY(e,t,r="[GeminiNative]"){if(!(!t||t.length===0))for(const n of t){const o=n.filename.split(/[\\/]/).pop()??n.filename,i=o.lastIndexOf("."),s=i>0?o.slice(i):".bin",a=await uEt(n.buffer,n.mimeType,s);if(EJ(a.mimeType)){h.warn(`${r} Skipping native audio for ${o}: ${a.mimeType} is not accepted and could not be converted. The metadata summary was still included.`);continue}e.push({inlineData:{mimeType:a.mimeType,data:a.buffer.toString("base64")}}),h.debug(`${r} Added native audio part for ${o} (${a.mimeType})`)}}async function wY(e,t,r,n,o="[GeminiNative]"){if(!t||t.length===0)return;let i=e.reduce((s,a)=>"inlineData"in a?s+Math.floor(a.inlineData.data.length*3/4):s,0);for(const s of t){const a=s.filename.split(/[\\/]/).pop()??s.filename,l=vEt(r,s,i,n);if(!l.deliver){h.warn(`${o} Sending keyframes instead of the clip for ${a}: ${l.reason}.`);continue}i+=s.buffer.length,e.push({inlineData:{mimeType:s.mimeType,data:s.buffer.toString("base64")}}),h.debug(`${o} Added native video part for ${a} (${s.mimeType})`)}}async function dIt(e,t,r="[GeminiNative]",n){const i=[{text:typeof t=="string"?t:e?.text??""}];if(e?.pdfFiles&&e.pdfFiles.length>0){h.debug(`${r} Processing ${e.pdfFiles.length} PDF(s)`);for(const s of e.pdfFiles){let a;typeof s=="string"?Ds(s)?a=ws(s):a=Buffer.from(s,"base64"):a=s,i.push({inlineData:{mimeType:"application/pdf",data:a.toString("base64")}})}}if(e?.images&&e.images.length>0){h.debug(`${r} Processing ${e.images.length} image(s)`);for(const s of e.images){const a=s&&typeof s=="object"&&!Buffer.isBuffer(s)?s.data:s;let l,c="image/jpeg";if(typeof a=="string")if(Ds(a)){l=ws(a);const u=By(a).toLowerCase();u===".png"?c="image/png":u===".gif"?c="image/gif":u===".webp"&&(c="image/webp")}else if(a.startsWith("data:")){const u=a.match(/^data:([^;]+);base64,(.+)$/);if(u)c=u[1],l=Buffer.from(u[2],"base64");else continue}else if(a.startsWith("http://")||a.startsWith("https://"))try{const u=await fetch(a);if(!u.ok){h.warn(`${r} Image fetch failed: ${u.status} ${u.statusText}, skipping`,{url:a});continue}const d=await u.arrayBuffer();l=Buffer.from(d);const p=u.headers.get("content-type");p&&p.startsWith("image/")&&(c=p.split(";")[0])}catch(u){h.warn(`${r} Image URL fetch threw, skipping: ${u instanceof Error?u.message:String(u)}`,{url:a});continue}else l=Buffer.from(a,"base64");else l=a;l&&i.push({inlineData:{mimeType:c,data:l.toString("base64")}})}}return await vY(i,e?.nativeAudioFiles,r),await wY(i,e?.nativeVideoFiles,"google-ai-studio",n,r),i}var Wv,pIt,AO,TY,CO=E({"src/lib/providers/googleNativeGemini3/utils.ts"(){"use strict";Jr(),Sn(),qt(),Zo(),hEt(),kJ(),z(),EO(),Ic(),ss(),Q1t(),Wv=class extends Map{resultCache=new Map;get(e){const t=super.get(e);if(!t)return t;const r=this.resultCache;return async(o,i)=>{const s=`${e}::${Fqr(o)}`;if(r.has(s))return h.warn(`[DedupExecuteMap] Tool "${e}" re-requested with identical arguments in the same turn \u2014 reusing the previous result instead of re-executing.`),r.get(s);const a=await t(o,i);return r.set(s,a),a}}},pIt=/^[A-Za-z_][A-Za-z0-9_.:-]{0,127}$/,AO=128,TY=100}});function IO(e){const t=o=>e.declarations?.originalNameMap?.get(o)??o,r=o=>{const i=e.declarations?.originalNameMap;if(!i)return o;for(const[s,a]of i)if(a===o)return s;return o};let n=0;return{providerLabel:e.providerLabel,maxSteps:e.maxSteps,...e.toolFailureBreaker?{toolFailureBreaker:e.toolFailureBreaker}:{},buildStepRequest(o,i){const s=e.declarations?Bqr(e.liveTools,e.declarations):[];return{raw:e.buildRequest(o,i),...s.length>0?{hydratedToolNames:s}:{}}},...e.planReclaim?{planReclaim:(o,i)=>e.planReclaim?.(o,i)}:{},...e.enableMalformedRetry&&e.buildMalformedRetryNote?{isMalformedStep:o=>o.toolCalls.length===0&&!o.text&&o.rawStopReason==="MALFORMED_FUNCTION_CALL",buildMalformedRetryNote:e.buildMalformedRetryNote}:{},resolveToolOnMiss:o=>{const s=fQe(e.liveTools,o)?.execute;if(!s)return;const a=e.declarations?.executeMap;let l=s;return a&&(a.set(o,s),l=a.get(o)??s),{execute:e.toolGuards?pg(o,l,e.toolGuards):(async(u,d)=>l(u,d))}},async executeStep(o,i,s){const a=await e.sendStep(o.raw,s),l=e.collectStep?await e.collectStep(a,i):await Gqr(a,{push:f=>i.push(f)});e.noteUsage?.(l.inputTokens,l.outputTokens);const c=qqr(l.rawResponseParts),u=l.stepFunctionCalls.map(f=>({id:`${e.providerLabel}_${n++}_${f.name}`,name:t(f.name),args:f.args})),d=e.finalResultToolName?u.find(f=>f.name===e.finalResultToolName):void 0,p=d?[]:u,m=d?JSON.stringify(d.args):c;return d&&e.onTerminalResult?.(m),{text:m,toolCalls:p,usage:{inputTokens:l.inputTokens,outputTokens:l.outputTokens,...l.cacheReadTokens?{cacheReadTokens:l.cacheReadTokens}:{},...l.reasoningTokens?{reasoningTokens:l.reasoningTokens}:{}},rawStopReason:l.finishReason,raw:{rawResponseParts:l.rawResponseParts,stepFunctionCalls:l.stepFunctionCalls}}},buildToolResultMessages(o,i,s,a){const l=[...o];return Wqr(l,i.raw.rawResponseParts,i.raw.stepFunctionCalls),l.push({role:"user",parts:s.map(c=>({functionResponse:{name:r(c.name),response:c.error?c.output:{result:c.output}}}))}),l},mapFinishReason(o,i){const s=mg(o);return i&&s==="stop"?"tool-calls":s}}}var mIt=E({"src/lib/core/geminiLoopAdapter.ts"(){"use strict";EO(),qS(),CO()}});function Kv(){const e=[];let t=!1,r,n=!1,o=null;function i(){if(o){const d=o;o=null,d()}}function s(d){t||(e.push(d),i())}function a(){t=!0,i()}function l(d){t=!0,r=d,n=!0,i()}let c=0;async function*u(){try{for(;;)if(c<e.length)yield e[c++],c>1024&&c*2>=e.length&&(e.splice(0,c),c=0);else if(t){if(n)throw r instanceof Error?r:new Error(String(r));return}else await new Promise(d=>{o=d})}finally{t=!0,e.length=0,o?.()}}return{push:s,close:a,error:l,iterable:u()}}var Jv=E({"src/lib/core/streamChannel.ts"(){"use strict"}});function o7r(e,t){return{inputTokens:e.inputTokens+t.inputTokens,outputTokens:e.outputTokens+t.outputTokens,cacheReadTokens:(e.cacheReadTokens??0)+(t.cacheReadTokens??0)||void 0,cacheWriteTokens:(e.cacheWriteTokens??0)+(t.cacheWriteTokens??0)||void 0,reasoningTokens:(e.reasoningTokens??0)+(t.reasoningTokens??0)||void 0,cacheWrite5mTokens:(e.cacheWrite5mTokens??0)+(t.cacheWrite5mTokens??0)||void 0,cacheWrite1hTokens:(e.cacheWrite1hTokens??0)+(t.cacheWrite1hTokens??0)||void 0}}async function i7r(e){const{name:t,execute:r,args:n,toolCallId:o,turnSignal:i,toolTimeoutMs:s}=e;if(s===null)return r(n,{toolCallId:o,abortSignal:i});const a=new AbortController,l=()=>a.abort(i.reason);i.aborted?a.abort(i.reason):i.addEventListener("abort",l,{once:!0});let c;const u=new Promise((d,p)=>{c=setTimeout(()=>{const m=new Error(`Tool "${t}" execution timed out after ${s}ms`);a.abort(m),p(m)},s)});try{return await Promise.race([Promise.resolve(r(n,{toolCallId:o,abortSignal:a.signal})),u])}finally{clearTimeout(c),i.removeEventListener("abort",l)}}async function s7r(e){const{calls:t,adapter:r,tools:n,failedTools:o,abortSignal:i,toolTimeoutMs:s}=e,a=[],l=[],c=[];let u=!1;for(const d of t){if(i.aborted){u=!0;break}c.push(d);const p=r.toolFailureBreaker,m=p?o.get(d.name):void 0;if(p&&m&&m.count>=p.maxRetries){const y={error:`TOOL_PERMANENTLY_FAILED: "${d.name}" has failed ${m.count} times. Last error: ${m.lastError}.`,status:"permanently_failed",do_not_retry:!0};a.push({...d,output:y,error:y.error,permanentlyFailed:!0}),l.push({id:d.id,name:d.name,input:d.args,output:y,error:y.error});continue}const f=n?.[d.name];let g=f;if(!f?.execute){const y=r.resolveToolOnMiss?.(d.name);y&&(g=y,o.delete(d.name))}if(!g?.execute){const y=p?{error:`TOOL_NOT_FOUND: "${d.name}" does not exist.`,status:"permanently_failed",do_not_retry:!0}:{error:`Tool not found: ${d.name}`};a.push({...d,output:y,error:y.error,permanentlyFailed:!!p}),l.push({id:d.id,name:d.name,input:d.args,output:y,error:y.error});continue}try{const y=await i7r({name:d.name,execute:g.execute,args:d.args,toolCallId:d.id,turnSignal:i,toolTimeoutMs:s}),v=p?.classifyResultFailure?.(y);if(p)if(v){const T=o.get(d.name)??{count:0,lastError:""};T.count++,T.lastError=v,o.set(d.name,T)}else p.consecutive&&o.delete(d.name);a.push({...d,output:y}),l.push({id:d.id,name:d.name,input:d.args,output:y})}catch(y){const v=y instanceof Error?y.message:String(y);if(p){const b=o.get(d.name)??{count:0,lastError:""};b.count++,b.lastError=v,o.set(d.name,b)}const T={error:v,status:"failed"};a.push({...d,output:T,error:v}),l.push({id:d.id,name:d.name,input:d.args,output:T,error:v})}}return{toolResults:a,executions:l,dispatched:c,abortedMidBatch:u}}function tp(e,t,r){const n=Kv(),o=new AbortController,i=()=>o.abort();r.abortSignal?.addEventListener("abort",i),r.abortSignal?.aborted&&o.abort();const s=new Map;let a=!1;const l=(async()=>{let c=t,u={inputTokens:0,outputTokens:0},d="",p="",m;const f=[],g=[];let y=!1,v=e.maxSteps;const T=Date.now();try{for(let k=0;k<v&&!o.signal.aborted;k++){if(e.planReclaim){const M=e.planReclaim(c,k);if(M?.conversation!==void 0&&(c=M.conversation),M?.stop)break}const A=e.buildStepRequest(c,k);for(const M of A.hydratedToolNames??[])s.delete(M);let x=!1;const P={push:M=>{x=!0,n.push(M)}};let C;try{C=await Py(async()=>{x=!1;try{return await e.executeStep(A,P,o.signal)}catch(M){throw x?new bY(M):M}},r.span,`${e.providerLabel}.step`,void 0,o.signal)}catch(M){throw M instanceof bY?M.cause:M}if(u=o7r(u,C.usage),m=C.rawStopReason,p=C.text||p,e.isMalformedStep?.(C)&&!a&&!o.signal.aborted){a=!0,h.warn(`[${e.providerLabel}] Malformed function call at step ${k+1}/${v}; retrying once.`),c=e.buildMalformedRetryNote?.(c,k)??c;continue}if(C.toolCalls.length===0){d=C.text||d;break}k===v-1&&(y=!0);const R=await s7r({calls:C.toolCalls,adapter:e,tools:r.tools,failedTools:s,abortSignal:o.signal,toolTimeoutMs:Yh(r.toolTimeoutMs)}),O=R.toolResults;if(f.push(...R.dispatched),g.push(...R.executions),R.abortedMidBatch)break;if(c=e.buildToolResultMessages(c,C,O,k),r.beforeStep&&!o.signal.aborted){const M=await r.beforeStep({stepIndex:k,stepsCompleted:k+1,maxSteps:v,elapsedMs:Date.now()-T,toolNames:R.dispatched.map($=>$.name),signal:o.signal}),D=typeof M?.maxSteps=="number"&&Number.isFinite(M.maxSteps)?Math.floor(M.maxSteps):void 0;D!==void 0&&D>v&&(v=D,y=!1),M?.nudge&&e.appendPlanningNudge&&(c=e.appendPlanningNudge(c,M.nudge))}}const b=o.signal.aborted,S=e.mapFinishReason(m,y);return{text:d||(y?p:""),toolCalls:f,toolExecutions:g,usage:u,finishReason:b&&m===void 0?"other":S,rawStopReason:m,conversation:c,aborted:b}}catch(b){throw n.error(b),b}finally{n.close(),r.abortSignal?.removeEventListener("abort",i)}})();return{stream:n.iterable,resultPromise:l}}var bY,RO=E({"src/lib/core/loopEngine.ts"(){"use strict";Jv(),z(),kd(),Zo(),bY=class extends Error{constructor(e){super(e instanceof Error?e.message:String(e)),this.cause=e}cause}}});function a7r(e,t){return e==="google-ai"?!0:e==="vertex"?!(t?.startsWith("claude-")??!1):!1}function l7r(e){return e==="anthropic"||e==="bedrock"}function _Y(e,t,r,n){return(a7r(e,t)||l7r(e))&&r&&n>0}function c7r(e){const t=e instanceof Error?e.message:typeof e=="string"?e:"";return/cannot be combined with (a )?(tool|function)/i.test(t)||/json[\s_-]?(mode|schema|object|output)[^.]{0,60}(tool|function)/i.test(t)||/(tool|function)[\s-]?call[^.]{0,60}json[\s_-]?(mode|schema)/i.test(t)||/response_format[^.]{0,60}(tool|function)/i.test(t)}function hIt(e){const t=e instanceof Error?e.message:typeof e=="string"?e:"";return/too many states/i.test(t)}function u7r(e){const t=e instanceof Error?e.message:typeof e=="string"?e:"";return/does not support[^.]{0,80}response[\s_-]?format/i.test(t)||/response[\s_-]?format[^.]{0,60}(?:is )?not support/i.test(t)||/unsupported response[\s_-]?format/i.test(t)}var EY=E({"src/lib/core/modules/structuredOutputPolicy.ts"(){"use strict"}});function d7r(e){return e?.kind==="toolCall"||e?.kind==="toolResult"}function p7r(e,t,r){const n=[];let o=t;for(;o<r;){if(!d7r(e[o])){o++;continue}const i=o;for(;o<e.length&&e[o].kind==="toolCall";)o++;for(;o<e.length&&e[o].kind==="toolResult";)o++;if(o>r)break;n.push({start:i,end:o})}return n}function PO(e,t){const{availableInputTokens:r,fixedOverheadTokens:n,thresholdRatio:o=M4,lowWaterRatio:i=fIt,protectedTailCount:s=gIt,calibration:a=1}=t,l=a>0?a:1,c=Math.floor(r*o/l),u=Math.floor(r*i/l);let d=n;for(const v of e)d+=v.tokens;if(d<=c)return{fire:!1,truncate:[],drop:[],projectedTokens:d};const p=1,m=Math.max(p,e.length-s),f=[],g=new Set;for(let v=p;v<m&&d>u;v++){const T=e[v];if(T.kind!=="toolResult"||T.previewTokens===void 0)continue;const b=T.tokens-T.previewTokens;b<=0||(f.push(v),d-=b)}if(d>u){const v=p7r(e,p,m);for(const T of v){if(d<=u)break;for(let b=T.start;b<T.end;b++){const S=e[b],k=f.includes(b)?S.previewTokens??S.tokens:S.tokens;d-=k,g.add(b)}}}const y=f.filter(v=>!g.has(v));return{fire:y.length>0||g.size>0,truncate:y,drop:[...g].sort((v,T)=>v-T),projectedTokens:d}}var fIt,gIt,MO=E({"src/lib/context/loopGuardCore.ts"(){"use strict";Zo(),fIt=.6,gIt=4}});function yIt(e){if(typeof e=="string")return e;if(e==null)return"";try{return JSON.stringify(e)??""}catch{return"x".repeat(2e5)}}function vIt(e,t){return Array.isArray(e.parts)&&e.parts.some(r=>r&&typeof r=="object"&&t in r)}function m7r(e){return vIt(e,"functionResponse")}function SY(e){const{preview:t}=dl(e,{maxBytes:kY,maxLines:TIt});return t}function h7r(e,t){return Vt(yIt(e.parts),t)+jl}function f7r(e,t){return e.map(r=>{const n=h7r(r,t);if(m7r(r)){const o=yIt(r.parts),i=o.length>kY?Vt(SY(o),t)+jl:n;return{kind:"toolResult",tokens:n,...i<n?{previewTokens:i}:{}}}return vIt(r,"functionCall")?{kind:"toolCall",tokens:n}:{kind:"other",tokens:n}})}function wIt(e){const{contents:t,availableInputTokens:r,fixedOverheadTokens:n=0,provider:o,observedPromptTokens:i}=e,s=f7r(t,o);let a=1;if(i&&i>0){const c=n+s.reduce((u,d)=>u+d.tokens,0);c>0&&(a=Math.min(3,Math.max(1,i/c)))}const l=PO(s,{availableInputTokens:r,fixedOverheadTokens:n,calibration:a});if(l.fire)return h.info("[GeminiLoopGuard] Reclaiming agent-loop context",{provider:o,contents:t.length,toolResponsesTruncated:l.truncate.length,contentsDropped:l.drop.length,projectedTokens:l.projectedTokens,calibration:a}),l}var kY,TIt,xY,bIt=E({"src/lib/context/geminiLoopGuard.ts"(){"use strict";di(),cg(),MO(),z(),kY=2048,TIt=60,xY="[Earlier tool exchanges were removed to fit the context window.]"}}),_It=E({"src/lib/providers/googleNativeGemini3/index.ts"(){"use strict";CO()}}),AY,rp,EIt=E({"src/lib/providers/anthropic/cacheControl.ts"(){"use strict";AY=e=>{if(!e||e.length===0)return e;if(e.some(r=>r.cache_control!==void 0))return[...e];const t=e[e.length-1];return[...e.slice(0,-1),{...t,cache_control:{type:"ephemeral"}}]},rp=e=>e?.providerOptions?.anthropic?.cacheControl?.type==="ephemeral"?{type:"ephemeral"}:void 0}});function Xv(e,t){if(t==="functionDeclarations")return eIt(e);const r=Object.entries(e??{});if(r.length!==0)return r.map(([n,o])=>{const i=o,s=i.inputSchema??i.parameters,a=s?qo(s):{type:"object",properties:{}},l=rp(o);return{name:n,...i.description?{description:i.description}:{},input_schema:a,...l?{cache_control:l}:{}}})}var CY=E({"src/lib/core/nativeToolFormat.ts"(){"use strict";CO(),EIt(),ss()}});function g7r(e,t){try{const[r,n]=t.split("/"),o=parseInt(n,10);if(isNaN(o)||o<0||o>32)return!1;const i=c=>{const u=c.split(".").map(Number);return(u[0]<<24)+(u[1]<<16)+(u[2]<<8)+u[3]},s=i(e),a=i(r),l=-1<<32-o>>>0;return(s&l)===(a&l)}catch{return!1}}function y7r(e,t){const r=t||process.env.NO_PROXY||process.env.no_proxy;if(!r)return!1;try{const n=new URL(e),o=n.hostname.toLowerCase(),i=n.port||(n.protocol==="https:"?"443":"80"),s=r.split(",").map(a=>a.trim()).filter(Boolean);for(const a of s){const l=a.toLowerCase();if(l==="*")return!0;if(l.startsWith(".")){const c=l.slice(1);if(o.endsWith(c)||o===c)return!0}else if(l.includes(":")){const[c,u]=l.split(":");if(o===c&&i===u)return!0}else if(l.includes("/")){if(/^\d{1,3}(\.\d{1,3}){3}$/.test(o)&&g7r(o,l))return!0}else if(o===l)return!0}return!1}catch(n){return h.warn("[Proxy] Error in NO_PROXY bypass logic",{targetUrl:e,error:n}),!1}}var v7r=E({"src/lib/proxy/utils/noProxyUtils.ts"(){"use strict";z()}}),SIt={};Z(SIt,{createProxyFetch:()=>Ot,getProxyDispatcherForUrl:()=>S7r,getProxyStatus:()=>MIt,googleSdkProxyHttpOptions:()=>PY,isTransientNetworkError:()=>IY,maskProxyUrl:()=>hg});async function w7r(){try{return(await Promise.resolve().then(()=>(Im(),$X))).getLangfuseContext?.()}catch{return}}function T7r(e,t){const r=new Headers(e instanceof Request?e.headers:void 0);if(t?.headers){const n=new Headers(t.headers);for(const[o,i]of n.entries())r.set(o,i)}return r}async function kIt(e,t){const r={};W0.inject(xr.active(),r);const n=await w7r();if(n?.sessionId&&(r["x-neurolink-session-id"]=n.sessionId),n?.userId&&(r["x-neurolink-user-id"]=n.userId),n?.conversationId&&(r["x-neurolink-conversation-id"]=n.conversationId),Object.keys(r).length===0)return t??{};const o=T7r(e,t);for(const[i,s]of Object.entries(r))o.has(i)||o.set(i,s);return{...t,headers:o}}function b7r(e){try{const t=typeof e=="string"?e:e instanceof URL?e.href:e.url;return new URL(t).hostname}catch{return"[unknown]"}}function IY(e){let t=e;for(let r=0;r<5&&t;r++){const n=t;if(n.code&&n8.has(n.code)||n.message?.includes("socket hang up")||n.message?.includes("network socket disconnected")||n.message?.includes("other side closed"))return!0;t=n.cause}return!1}async function xIt(e,t,r=3,n=500){const o=b7r(e);return OIt.startActiveSpan("neurolink.http.fetchWithRetry",async i=>{i.setAttribute("http.request.max_retries",r),i.setAttribute("http.request.hostname",o),i.setAttribute("http.request.method",t?.method||"GET");let s=0;try{for(let a=0;a<=r;a++){s=a+1;try{const l=await fetch(e,t);return i.setAttribute("http.request.total_attempts",s),i.setAttribute("http.response.status_code",l.status),i.setStatus({code:Ue.OK}),l}catch(l){const c=IY(l),u=l;if(!c||a===r)throw i.setAttribute("http.request.total_attempts",s),i.setStatus({code:Ue.ERROR,message:u?.message||u?.code||"fetchWithRetry final failure"}),i.recordException(l instanceof Error?l:new Error(String(l))),l;const d=n*Math.pow(2,a);i.addEvent("http.request.retry",{"retry.attempt":a+1,"retry.delay_ms":d,"retry.error":(u?.code||u?.message||String(l)).slice(0,256)}),h.debug(`[fetchWithRetry] Transient error (${u?.code||u?.message}), retrying in ${d}ms (attempt ${a+1}/${r})`),await new Promise(p=>setTimeout(p,d))}}throw new Error("fetchWithRetry exhausted")}finally{i.end()}})}function AIt(e){if(!e)return{parsed:null,size:0,type:"empty"};if(typeof e=="string")try{return{parsed:JSON.parse(e),size:e.length,type:"json"}}catch{return{parsed:e,size:e.length,type:"text"}}return e instanceof ArrayBuffer?{parsed:"[ArrayBuffer]",size:e.byteLength,type:"arraybuffer"}:e instanceof Uint8Array?{parsed:"[Uint8Array]",size:e.length,type:"uint8array"}:{parsed:"[Stream]",size:-1,type:"stream"}}async function RY(e){const t={};e.headers.forEach((r,n)=>{t[n]=DIt.has(n.toLowerCase())?`${r.substring(0,4)}***`:r});try{const n=await e.clone().text();try{return{parsed:JSON.parse(n),size:n.length,type:"json",headers:t}}catch{return{parsed:n,size:n.length,type:"text",headers:t}}}catch{return{parsed:"[unable to read body]",size:-1,type:"error",headers:t}}}function _7r(e){try{const t=new URL(e),r={protocol:t.protocol,hostname:t.hostname,port:parseInt(t.port)||CIt(t.protocol),cleanUrl:`${t.protocol}//${t.hostname}:${t.port||CIt(t.protocol)}`};return t.username&&t.password&&(r.auth={username:decodeURIComponent(t.username),password:decodeURIComponent(t.password)}),r}catch(t){let r;try{const n=new URL(e);n.username="",n.password="",r=n.toString()}catch{r="[invalid-url]"}throw h.error("[Proxy] Failed to parse proxy URL",{proxyUrl:r,error:t}),new Error(`Invalid proxy URL: ${r}`,{cause:t})}}function CIt(e){switch(e){case"http:":return 8080;case"https:":return 8080;case"socks4:":return 1080;case"socks5:":return 1080;default:return 8080}}function IIt(e){if(y7r(e))return h.debug("[Proxy] Bypassing proxy due to NO_PROXY",{targetUrl:e}),null;try{const t=new URL(e),r=process.env.HTTPS_PROXY||process.env.https_proxy,n=process.env.HTTP_PROXY||process.env.http_proxy,o=process.env.ALL_PROXY||process.env.all_proxy,i=process.env.SOCKS_PROXY||process.env.socks_proxy;return t.protocol==="https:"&&r?r:t.protocol==="http:"&&n?n:o||i||null}catch(t){return h.warn("[Proxy] Error selecting proxy URL",{targetUrl:e,error:t}),null}}async function E7r(e){const t=_7r(e);switch(h.debug("[Proxy] Creating proxy agent",{protocol:t.protocol,hostname:t.hostname,port:t.port,hasAuth:!!t.auth}),t.protocol){case"http:":case"https:":{const{ProxyAgent:r}=await Promise.resolve().then(()=>(zd(),Uu));return new r(e)}case"socks4:":case"socks5:":throw new Error("SOCKS proxy support requires 'proxy-agent' package. Install it with: npm install proxy-agent");default:throw new Error(`Unsupported proxy protocol: ${t.protocol}`)}}async function RIt(e){const t=globalThis;t.__NL_PROXY_AGENT_CACHE__||(t.__NL_PROXY_AGENT_CACHE__=new Map);const r=t.__NL_PROXY_AGENT_CACHE__,n=Ld("sha256").update(hg(e)??e).digest("hex"),o=r.get(n)||await E7r(e);return r.set(n,o),o}async function S7r(e){const t=IIt(e);return t?RIt(t):null}function na(e){return hg(e)??"NOT_SET"}function PIt(e){return typeof e=="string"?e:e instanceof URL?e.href:e.url}function k7r(){return async(e,t)=>{const r=await kIt(e,t),n=`req-${Date.now()}-${Math.random().toString(36).substring(2,11)}`,o=Date.now(),i=PIt(e);if(h.shouldLog("debug")){const{size:s,type:a}=AIt(r?.body);h.debug("[Observability] HTTP request to LLM provider",{requestId:n,url:i,method:r?.method||"POST",bodySize:s,bodyType:a})}try{const s=await xIt(e,r);if(h.shouldLog("debug")){const{parsed:a,size:l,type:c,headers:u}=await RY(s);h.debug("[Observability] HTTP response from LLM provider",{requestId:n,url:i,status:s.status,statusText:s.statusText,durationMs:Date.now()-o,contentLength:l,hasContent:!!a,bodyType:c,responseHeaders:u})}return s}catch(s){throw h.debug("[Observability] HTTP request failed",{requestId:n,url:i,error:s instanceof Error?s.message:String(s),durationMs:Date.now()-o}),s}}}async function x7r(e,t,r){const{httpsProxy:n,httpProxy:o,allProxy:i,socksProxy:s,noProxy:a}=r;t=await kIt(e,t);const l=`req-${Date.now()}-${Math.random().toString(36).substring(2,11)}`,c=Date.now(),u=PIt(e);if(h.shouldLog("debug")){const{size:m,type:f}=AIt(t?.body);h.debug("[Observability] HTTP request to LLM provider",{requestId:l,url:u,method:t?.method||"POST",bodySize:m,bodyType:f})}h.debug("[Proxy Fetch] ENHANCED REQUEST START",{requestId:l,targetUrl:u,timestamp:new Date().toISOString(),httpProxy:na(o),httpsProxy:na(n),allProxy:na(i),socksProxy:na(s),noProxy:a||"NOT_SET",initMethod:t?.method||"GET"});const d=e instanceof Request?e.clone():null;try{const m=IIt(u);if(m){const f=new URL(u);h.debug("[Proxy Fetch] \u{1F517} ENHANCED URL ANALYSIS",{requestId:l,targetUrl:u,urlHostname:f.hostname,urlProtocol:f.protocol,urlPort:f.port,selectedProxyUrl:na(m),timestamp:new Date().toISOString()}),h.debug("[Proxy Fetch] \u{1F3AF} ENHANCED PROXY AGENT CREATION",{requestId:l,proxyUrl:na(m),targetHostname:f.hostname,targetProtocol:f.protocol,aboutToCreateProxyAgent:!0,timestamp:new Date().toISOString()});const g=await RIt(m);h.debug("[Proxy Fetch] \u2705 ENHANCED PROXY AGENT CREATED",{requestId:l,hasDispatcher:!!g,dispatcherType:typeof g,dispatcherConstructor:g?.constructor?.name||"unknown",timestamp:new Date().toISOString()});let y,v={...t};e instanceof Request?(y=e.url,v={method:e.method,headers:e.headers,body:e.body,...t}):y=e;const b=await(await Promise.resolve().then(()=>(zd(),Uu))).fetch(y,{...v,dispatcher:g});if(h.shouldLog("debug")){const{parsed:S,size:k,type:A,headers:x}=await RY(b);h.debug("[Observability] HTTP response from LLM provider",{requestId:l,url:u,status:b?.status,statusText:b?.statusText,durationMs:Date.now()-c,contentLength:k,hasContent:!!S,bodyType:A,proxied:!0,responseHeaders:x})}return h.debug("[Proxy Fetch] ENHANCED PROXY SUCCESS",{requestId:l,responseStatus:b?.status,responseOk:b?.ok,proxyUsed:!0,timestamp:new Date().toISOString()}),b}}catch(m){const f=m instanceof Error?m.message:String(m);h.debug("[Observability] HTTP request failed",{requestId:l,url:u,error:f,durationMs:Date.now()-c}),h.debug("[Proxy Fetch] ENHANCED ERROR ANALYSIS",{requestId:l,error:f,errorType:m instanceof Error?m.constructor.name:typeof m,willFallback:!0,timestamp:new Date().toISOString()}),h.warn(`[Proxy Fetch] Enhanced proxy failed (${f}), falling back to direct connection`)}h.debug("[Proxy Fetch] ENHANCED FALLBACK TO STANDARD FETCH",{requestId:l,fallbackReason:"No proxy configured or proxy failed",timestamp:new Date().toISOString()});const p=e instanceof Request?d??e:e;try{const m=await xIt(p,t);if(h.shouldLog("debug")){const{parsed:f,size:g,type:y,headers:v}=await RY(m);h.debug("[Observability] HTTP response from LLM provider",{requestId:l,url:u,status:m.status,statusText:m.statusText,durationMs:Date.now()-c,contentLength:g,hasContent:!!f,bodyType:y,proxied:!1,responseHeaders:v})}return m}catch(m){const f=m instanceof Error?m.message:String(m);throw h.debug("[Observability] HTTP request failed",{requestId:l,url:u,error:f,durationMs:Date.now()-c}),m}}function A7r(e){return async(t,r)=>x7r(t,r,e)}function Ot(){const e=process.env.HTTPS_PROXY||process.env.https_proxy,t=process.env.HTTP_PROXY||process.env.http_proxy,r=process.env.ALL_PROXY||process.env.all_proxy,n=process.env.SOCKS_PROXY||process.env.socks_proxy,o=process.env.NO_PROXY||process.env.no_proxy,i={httpsProxy:e,httpProxy:t,allProxy:r,socksProxy:n,noProxy:o};if(h.shouldLog("debug")){const s=Object.keys(process.env).filter(a=>a.toLowerCase().includes("proxy")).reduce((a,l)=>{const c=process.env[l]||"NOT_SET";return a[l]=l.toLowerCase()==="no_proxy"?c:na(c),a},{});h.debug("[Proxy Fetch] ENHANCED_PROXY_ENV_DETECTION",{httpProxy:na(t),httpsProxy:na(e),allProxy:na(r),socksProxy:na(n),noProxy:o||"NOT_SET",allProxyRelatedEnvVars:s,message:"Enhanced proxy environment detection \u2014 credentials redacted"})}return!e&&!t&&!r&&!n?(h.debug("[Proxy Fetch] No proxy environment variables found - using standard fetch"),k7r()):(h.debug("[Proxy Fetch] Configuring enhanced proxy with multiple protocol support"),h.debug(`[Proxy Fetch] HTTP_PROXY: ${na(t)}`),h.debug(`[Proxy Fetch] HTTPS_PROXY: ${na(e)}`),h.debug(`[Proxy Fetch] ALL_PROXY: ${na(r)}`),h.debug(`[Proxy Fetch] SOCKS_PROXY: ${na(n)}`),h.debug(`[Proxy Fetch] NO_PROXY: ${o||"not set"}`),A7r(i))}function hg(e){if(!e)return null;try{const t=new URL(e);return(t.username||t.password)&&(t.username="***",t.password="***"),t.toString()}catch{return"[invalid-url]"}}function MIt(){const e=process.env.HTTPS_PROXY||process.env.https_proxy,t=process.env.HTTP_PROXY||process.env.http_proxy,r=process.env.ALL_PROXY||process.env.all_proxy,n=process.env.SOCKS_PROXY||process.env.socks_proxy,o=process.env.NO_PROXY||process.env.no_proxy;return{enabled:!!(e||t||r||n),httpProxy:hg(t),httpsProxy:hg(e),allProxy:hg(r),socksProxy:hg(n),noProxy:o||null,method:"enhanced-proxy-agent",capabilities:["HTTP/HTTPS Proxy","SOCKS4/SOCKS5 Proxy","Proxy Authentication","NO_PROXY Bypass","CIDR Range Matching","Wildcard Domain Matching"]}}function PY(){return MIt().enabled?{fetch:Ot()}:{}}var OIt,DIt,Ln=E({"src/lib/proxy/proxyFetch.ts"(){"use strict";z(),Qt(),Sr(),v7r(),Jr(),jbe(),OIt=Be.http,DIt=new Set(["authorization","x-api-key","api-key","x-goog-api-key","proxy-authorization","cookie","set-cookie"])}});function C7r(e,t,r){const n=e[Symbol.asyncIterator]();return new ReadableStream({async pull(o){try{const i=await n.next();i.done?(o.enqueue(await t),o.close()):o.enqueue({type:"text-delta",delta:i.value.content})}catch(i){o.error(i)}},async cancel(){r(),await n.return?.()}})}async function*I7r(e,t,r){const n=e.getReader();let o=!1,i=!1;try{for(;;){const s=await n.read();if(s.done){o=!0;return}const a=s.value;if(a.type==="text-delta")yield{content:a.delta};else if(a.type==="finish")i=!0,t(a);else if(a.type==="error")throw a.error}}finally{try{o||await n.cancel()}finally{n.releaseLock(),i||r?.()}}}function NIt(e,t){const r=e.systemInstruction;return[...typeof r=="string"&&r.length>0?[{role:"system",content:r}]:[],...e7r(t)]}async function Yv(e,t){const n=(await Promise.resolve().then(()=>(KE(),zy))).GoogleGenAI;if(!n)throw new De({code:He.INVALID_CONFIGURATION,message:"@google/genai does not export GoogleGenAI",category:"configuration",severity:"critical",retriable:!1,context:{module:"@google/genai",expectedExport:"GoogleGenAI"}});const o=n;return new o({apiKey:e,httpOptions:{...t?{baseUrl:t}:{},...PY()}})}function LIt(e,t,r){const n=wIt({contents:e,availableInputTokens:ql("googleAiStudio",t),provider:"googleAiStudio",...r?{observedPromptTokens:r}:{}});if(!n)return!1;const o=new Set(n.drop),i=new Set(n.truncate),s=[];for(let a=0;a<e.length;a++){if(o.has(a))continue;const l=e[a];if(i.has(a)&&Array.isArray(l.parts)){s.push({...l,parts:l.parts.map(c=>{const u=c;if(!u.functionResponse)return c;const d=JSON.stringify(u.functionResponse.response)??"";return d.length<=2048?c:{functionResponse:{name:u.functionResponse.name,response:{result:SY(d)}}}})});continue}s.push(l)}if(o.size>0){let a=s.findIndex(l=>Array.isArray(l.parts)&&l.parts.some(c=>!!c.functionCall||!!c.functionResponse));a<0&&(a=Math.min(1,s.length)),s.splice(a,0,{role:"user",parts:[{text:xY}]})}return e.length=0,e.push(...s),!0}var FIt,R7r=E({"src/lib/providers/googleAiStudio/client.ts"(){"use strict";pl(),Zo(),R2(),il(),pt(),et(),z(),pY(),mIt(),RO(),Zo(),EY(),bIt(),$c(),Ys(),dg(),di(),zl(),vm(),_It(),Jv(),CY(),Ln(),FIt=class extends Ma{credentials;constructor(e,t,r){super(e,"google-ai",t),this.credentials=r,h.debug("GoogleAIStudioProvider initialized",{model:this.modelName,provider:this.providerName,sdkProvided:!!t})}getProviderName(){return"google-ai"}getDefaultModel(){return process.env.GOOGLE_AI_MODEL||"gemini-2.5-flash"}getAISDKModel(){throw new De({code:He.INVALID_CONFIGURATION,message:"GoogleAIStudioProvider no longer uses @ai-sdk/google. All models use native @google/genai SDK.",category:"configuration",severity:"critical",retriable:!1,context:{provider:this.providerName,model:this.modelName}})}formatProviderError(e){if(e instanceof Ta)return new ai(e.message,this.providerName);const t=e,r=typeof t?.message=="string"?t.message:"Unknown error",n=typeof t?.status=="number"?t.status:typeof t?.statusCode=="number"?t.statusCode:void 0;return r.includes("API_KEY_INVALID")||r.includes("Invalid API key")||n===401?new Wr("Invalid Google AI API key. Please check your GOOGLE_AI_API_KEY environment variable.",this.providerName):r.includes("RATE_LIMIT_EXCEEDED")||r.includes("rate limit")||r.includes("429")||n===429?new Qi("Google AI rate limit exceeded. Please try again later.",this.providerName):n===404||n===void 0&&(r.includes("model not found")||r.includes("Model not found"))?new Jo(`Model '${this.modelName}' not found. Please check the model name and ensure it is available.`,this.providerName):r.includes("ECONNRESET")||r.includes("ENOTFOUND")||r.includes("ETIMEDOUT")||r.includes("ECONNREFUSED")||r.includes("network")||r.includes("connection")?new ai(`Connection error: ${r}`,this.providerName):r.includes("500")||r.includes("502")||r.includes("503")||r.includes("504")||r.includes("server error")||r.includes("Internal Server Error")||n&&n>=500&&n<600?new ot(`Google AI server error: ${r}. Please try again later.`,this.providerName):new ot(`Google AI error: ${r}`,this.providerName)}async executeImageGeneration(e){await Ck(e.input);const t=e.prompt||e.input?.text||"",r=e.model||this.modelName,n=Date.now(),o=this.getApiKey();h.info("\u{1F3A8} Starting Google AI Studio image generation",{model:r,prompt:t.substring(0,100),provider:this.providerName});let i;try{i=await Yv(o,this.getBaseURL())}catch{throw new Wr("Missing '@google/genai'. Install with: npm install @google/genai",this.providerName)}try{const s=await Promise.all((e.input?.images||[]).map(async d=>{if(typeof d=="object"&&"url"in d){const f=d.url;if(f.startsWith("http")){const v=await fetch(f);if(!v.ok)throw new Error(`Failed to fetch image from ${f}: ${v.status} ${v.statusText}`);const T=await v.arrayBuffer(),b=Buffer.from(T),S=this.detectImageType(b);return h.debug(`Downloaded and detected image MIME type: ${S}`),{inlineData:{mimeType:S,data:b.toString("base64")}}}const g=Buffer.from(f,"base64");return{inlineData:{mimeType:this.detectImageType(g),data:g.toString("base64")}}}if(typeof d=="string"&&d.startsWith("http")){const f=await fetch(d);if(!f.ok)throw new Error(`Failed to fetch image from ${d}: ${f.status} ${f.statusText}`);const g=await f.arrayBuffer(),y=Buffer.from(g),v=this.detectImageType(y);return h.debug(`Downloaded and detected image MIME type: ${v}`),{inlineData:{mimeType:v,data:y.toString("base64")}}}const p=Buffer.isBuffer(d)?d:typeof d=="string"?Buffer.from(d,"base64"):Buffer.from(""),m=this.detectImageType(p);return h.debug(`Detected image MIME type: ${m}`),{inlineData:{mimeType:m,data:p.toString("base64")}}})),a=[{role:"user",parts:[{text:t},...s]}],l={responseModalities:["IMAGE","TEXT"]};h.debug("Starting image generation request",{model:r,contentParts:a[0].parts.length,responseModalities:l.responseModalities});let c=null,u="";try{const d=await i.models.generateContentStream({model:r,contents:a,config:l});for await(const p of d){h.debug("Received chunk",{hasCandidate:!!p.candidates?.[0],hasContent:!!p.candidates?.[0]?.content,hasParts:!!p.candidates?.[0]?.content?.parts});const m=p.candidates?.[0];if(m?.content?.parts)for(const f of m.content.parts){if("inlineData"in f&&f.inlineData?.data){const g=f.inlineData.data;c=g;const y=f.inlineData.mimeType,v=y||"image/png";h.info("Image generation successful",{model:r,mimeType:v,dataLength:g.length,responseTime:Date.now()-n});const T={content:`Generated image using ${r} (${v})`,imageOutput:{base64:g,...y?{mimeType:y}:{}},provider:this.providerName,model:r,usage:{input:this.estimateTokenCount(t),output:0,total:this.estimateTokenCount(t)}};return await this.enhanceResult(T,e,n)}"text"in f&&f.text&&(u+=f.text,h.debug("Received text content",{text:f.text.substring(0,100)}))}}}catch(d){h.debug("Streaming failed, trying non-streaming approach",{error:d instanceof Error?d.message:String(d)})}if(!c){h.debug("Trying non-streaming approach");const p=(await i.models.generateContent({model:r,contents:a,config:l})).candidates?.[0];if(p?.content?.parts)for(const m of p.content.parts){if("inlineData"in m&&m.inlineData?.data){const f=m.inlineData.data;c=f;const g=m.inlineData.mimeType,y=g||"image/png";h.info("Image generation successful (non-streaming)",{model:r,mimeType:y,dataLength:f.length,responseTime:Date.now()-n});const v={content:`Generated image using ${r} (${y})`,imageOutput:{base64:f,...g?{mimeType:g}:{}},provider:this.providerName,model:r,usage:{input:this.estimateTokenCount(t),output:0,total:this.estimateTokenCount(t)}};return await this.enhanceResult(v,e,n)}"text"in m&&m.text&&(u+=m.text)}}throw h.warn("No image data found in response",{model:r,prompt:t.substring(0,100),hasTextContent:!!u,textContent:u.substring(0,200)}),new ot(u||`Image generation completed but no image data was returned. This may indicate an issue with the model "${r}" or the prompt: "${t}". Please try again or use a different model.`,this.providerName)}catch(s){throw h.error("Image generation failed",{error:s instanceof Error?s.message:String(s),model:r,prompt:t.substring(0,100)}),this.handleProviderError(s)}}detectImageType(e){return e.length>=8&&e[0]===137&&e[1]===80&&e[2]===78&&e[3]===71?"image/png":e.length>=3&&e[0]===255&&e[1]===216&&e[2]===255?"image/jpeg":e.length>=12&&e[0]===82&&e[1]===73&&e[2]===70&&e[3]===70&&e[8]===87&&e[9]===69&&e[10]===66&&e[11]===80?"image/webp":e.length>=6&&e[0]===71&&e[1]===73&&e[2]===70?"image/gif":"image/png"}estimateTokenCount(e){return Vt(e,"google-ai")}async preprocessNativeFileInput(e){if(e.input&&RJ(e.input),e.input?.files&&e.input.files.length>0)try{await PJ(e,100*1024*1024,this.providerName)}catch(t){h.warn(`[GoogleAIStudio] processUnifiedFilesArray threw, continuing without file content: ${t instanceof Error?t.message:String(t)}`)}await Ck(e.input)}async executeStream(e,t){const r=e.model||this.modelName;if(e.input?.audio)return await this.executeAudioStreamViaGeminiLive(e);await this.preprocessNativeFileInput(e);const n=!!(t||e.output?.format==="json"||e.schema),o=!e.disableTools&&this.supportsTools()&&!n,i=e.tools||{};let s={...e,tools:i};const a=e.output?.format==="json"||e.schema,l=_Y(this.providerName,r,!s.disableTools,Object.keys(s.tools??{}).length);return a&&l&&(h.warn("[GoogleAIStudio] Gemini does not support tools and JSON schema output simultaneously. Disabling tools for this request."),s={...s,disableTools:!0,tools:{}}),o&&!s.disableTools&&s.tools&&Object.keys(s.tools).length>0&&h.info("[GoogleAIStudio] Routing to native @google/genai SDK for tool calling",{model:r,totalToolCount:Object.keys(s.tools??{}).length}),this.executeNativeGemini3Stream(s)}async executeNativeGemini3Stream(e){const t=e.model||this.modelName;return U9e({name:"neurolink.provider.stream",tracer:Be.provider,attributes:{[Re.GEN_AI_SYSTEM]:"google-ai",[Re.GEN_AI_MODEL]:t,[Re.GEN_AI_OPERATION]:"stream",[Re.NL_PROVIDER]:this.providerName}},async r=>{const n=Date.now(),o=this.getTimeout(e),i=wa(o,this.providerName,"stream");{const s=this.getApiKey(),a=await Yv(s,this.getBaseURL());h.debug("[GoogleAIStudio] Using native @google/genai for Gemini 3",{model:t,hasTools:!!e.tools&&Object.keys(e.tools).length>0});const l=[];xO(l,e.conversationMessages);const c=await dIt(e.input,e.input.text,"[GoogleAIStudio:stream]",t);l.push({role:"user",parts:c});let u,d;if(e.tools&&Object.keys(e.tools).length>0&&!e.disableTools){const de=Xv(e.tools,"functionDeclarations");d=de,u=de.toolsConfig,h.debug("[GoogleAIStudio] Converted tools for native SDK",{toolCount:u[0].functionDeclarations.length,toolNames:u[0].functionDeclarations.map(oe=>oe.name)})}const p=!u&&(e.output?.format==="json"||!!e.schema),m=p&&e.schema?iIt(e.schema):void 0,f=tIt({...e,model:t,wantsJsonOutput:p,responseSchema:m},u),g=rIt(e.maxSteps),y=Cy(e.abortSignal,i?.controller.signal),v=new AbortController,T=()=>v.abort();y?.addEventListener("abort",T),y?.aborted&&v.abort();const b=Yh(e.toolTimeoutMs),S=jv({...e.turnTimeoutMs!==void 0?{turnTimeoutMs:e.turnTimeoutMs}:{},...e.stallTimeoutMs!==void 0?{stallTimeoutMs:e.stallTimeoutMs}:{},...e.wrapupTimeLeadMs!==void 0?{wrapupTimeLeadMs:e.wrapupTimeLeadMs}:{},onDeadline:de=>{h.warn(de==="timeout"?`[GoogleAIStudio] Native Gemini turn exceeded its ${e.turnTimeoutMs}ms time budget \u2014 aborting`:`[GoogleAIStudio] Native Gemini turn made no progress for ${e.stallTimeoutMs}ms \u2014 aborting`),v.abort()}}),k=v.signal,A=()=>S.timedOut||i?.controller.signal.aborted===!0,x=Kv(),P=[],C=[];let R,O;const U=new Promise((de,oe)=>{R=de,O=oe}),M={streamId:`native-${Date.now()}`,startTime:n,responseTime:0,totalToolExecutions:0},D=async(de,oe)=>{let ae="",ge=0,be=0,Ce=0,ye=0,Ne=0,xe=0,le=!1,Oe;const Ie=Hv(jd("googleAiStudio",t));try{const Ge=IO({providerLabel:"GoogleAIStudio",maxSteps:g,toolFailureBreaker:{maxRetries:Zh},liveTools:e.tools??{},toolGuards:{toolTimeoutMs:b,abortSignal:k,onProgress:()=>S.noteProgress()},...d?{declarations:d}:{},buildRequest:ce=>({model:t,contents:ce,config:oe}),sendStep:async(ce,I)=>{S.noteProgress();const H=ce;return a.models.generateContentStream({...H,config:{...H.config??{},abortSignal:I}})},noteUsage:(ce,I)=>{Ie.noteUsage(ce,I)},planReclaim:(ce,I)=>{if(I!==0&&!Ie.shouldStop())return;const H=[...ce];if(LIt(H,t,Ie.projectedNextPromptTokens))return Ie.resetAfterReclaim(),{conversation:H}}}),je={...Ge,buildStepRequest:(ce,I)=>(xe=I+1,S.noteProgress(),Ge.buildStepRequest(ce,I)),buildToolResultMessages:(ce,I,H,ve)=>{Ne=ve+1;for(const ue of I.toolCalls)r.addEvent("gen_ai.tool_call",{"tool.name":ue.name,"tool.step":Ne});ae=I.text||ae;for(const ue of I.toolCalls)P.push({toolName:ue.name,args:ue.args});for(const ue of H)C.push({name:ue.name,input:ue.args,output:ue.output});if(H.length>0){const ue=kO(I.raw.rawResponseParts);It(this.handleToolExecutionStorage(I.toolCalls.map((F,ne)=>({toolName:F.name,args:F.args,...ne===0&&ue?{thoughtSignature:ue}:{},stepIndex:Ne})),H.map(F=>({toolName:F.name,output:F.output,stepIndex:Ne})),e,new Date),Qh,"tool storage write timed out").catch(F=>{h.warn("[GoogleAIStudio] Failed to store native tool executions",{error:F instanceof Error?F.message:String(F)})})}const se=Ge.buildToolResultMessages(ce,I,H,ve);if(S.shouldNudgeWrapup()){const ue=se[se.length-1];ue&&Array.isArray(ue.parts)&&ue.parts.push({text:Vv(!1)})}try{const ue=se[se.length-1];Ie.noteAppendedChars(JSON.stringify(ue?.parts??[]).length)}catch{}return se}},_e=SO(d,e.tools,{toolTimeoutMs:b,abortSignal:k,onProgress:()=>S.noteProgress()}),{stream:Fe,resultPromise:Y}=tp(je,de,{tools:_e,abortSignal:k,toolTimeoutMs:b}),X=(async()=>{for await(const ce of Fe)S.noteProgress(),x.push(ce)})();let ke,W;try{ke=await Y}catch(ce){W=ce}if(await ug(X,"GoogleAIStudio"),W!==void 0)if(S.expired||e.abortSignal?.aborted)le=!0;else throw h.error("[GoogleAIStudio] Native SDK error",W),this.handleProviderError(W);ke&&(ge+=ke.usage.inputTokens,be+=ke.usage.outputTokens,Ce+=ke.usage.cacheReadTokens??0,ye+=ke.usage.reasoningTokens??0,Oe=ke.rawStopReason??Oe,ke.aborted&&(le=!0)),k.aborted&&(le=!0);const te=ke!==void 0&&(ke.toolCalls.length===0||ke.finishReason!=="tool-calls"),me=!le&&Ne>=g&&!te;if(me){const ce=nIt("[GoogleAIStudio]",Ne,g,"",ae);ce&&x.push({content:ce})}else le&&!te&&(h.warn(`[GoogleAIStudio] Tool call loop ended mid-turn (${A()?"turn time limit":S.stalled?"stall watchdog":"caller abort"}); returning an honest terminal message.`),x.push({content:fY({timedOut:A(),stalled:S.stalled,elapsedMs:S.elapsedMs(),wasAborted:le,...e.stallTimeoutMs!==void 0?{stallTimeoutMs:e.stallTimeoutMs}:{},maxSteps:g,toolCallCount:P.length})}));const Te=Date.now()-n,pe=ep({timedOut:A(),stalled:S.stalled,wasAborted:le,cappedWithoutAnswer:me,finishReason:mg(Oe)});pe!=="completed"&&this.emitTurnEvent({phase:pe,step:xe,maxSteps:g,toolCallCount:P.length,elapsedMs:S.elapsedMs()}),M.responseTime=Te,M.totalToolExecutions=P.length,M.stopReason=pe,M.stepsUsed=xe,Oe!==void 0&&(M.rawFinishReason=Oe),r.setAttribute(Re.GEN_AI_INPUT_TOKENS,ge),r.setAttribute(Re.GEN_AI_OUTPUT_TOKENS,be),r.setAttribute(Re.GEN_AI_FINISH_REASON,me?"max_steps":"stop");const ie=Math.max(0,ge-Ce);R({provider:this.providerName,model:t,tokenUsage:{input:ie,output:be+ye,total:ie+Ce+be+ye,...Ce>0?{cacheReadTokens:Ce}:{},...ye>0?{reasoning:ye}:{}},requestDuration:Te,timestamp:new Date().toISOString(),stepsUsed:xe,toolCallCount:P.length,stopReason:pe,elapsedMs:S.elapsedMs(),...Oe!==void 0?{rawFinishReason:Oe}:{}}),x.close()}catch(Ge){x.error(Ge),O(Ge)}finally{S.dispose(),y?.removeEventListener("abort",T),i?.cleanup()}};let $;const B={prompt:NIt(f,l),...typeof f.maxOutputTokens=="number"?{maxOutputTokens:f.maxOutputTokens}:{},...typeof f.temperature=="number"?{temperature:f.temperature}:{},...typeof f.topP=="number"?{topP:f.topP}:{},abortSignal:k},q={specificationVersion:"v3",provider:this.providerName,modelId:t,supportedUrls:{},doGenerate:()=>{throw new Error("GoogleAIStudio: doGenerate is not implemented on the native stream model \u2014 NeuroLink streams through executeStream/doStream for this provider.")},doStream:async de=>{const{contents:oe,systemText:ae}=uIt(de.prompt),ge={...f,...typeof de.temperature=="number"?{temperature:de.temperature}:{},...typeof de.maxOutputTokens=="number"?{maxOutputTokens:de.maxOutputTokens}:{},...typeof de.topP=="number"?{topP:de.topP}:{}};ae?ge.systemInstruction=ae:delete ge.systemInstruction,$=D(oe,ge),$.catch(()=>{});const be=U.then(Ce=>({type:"finish",finishReason:{unified:mg(M.rawFinishReason)},usage:{inputTokens:{total:Ce.tokenUsage.input},outputTokens:{total:Ce.tokenUsage.output}}}));return be.catch(()=>{}),{stream:C7r(x.iterable,be,()=>v.abort())}}};let L;try{const de=await this.applyMiddlewareToModel(q,e);if(typeof de=="string")throw new Error("GoogleAIStudio: native stream middleware resolved to a bare model id string, expected a LanguageModelV3 handle.");({stream:L}=await de.doStream(B))}catch(de){throw v.abort(),x.close(),S.dispose(),y?.removeEventListener("abort",T),i?.cleanup(),this.handleProviderError(de)}let j=!1;const G=de=>{if($||j)return;j=!0;const oe=Date.now()-n,ae=ep({timedOut:!1,stalled:!1,wasAborted:!de,cappedWithoutAnswer:!1,...de?{finishReason:de.finishReason.unified}:{}});M.responseTime=oe,M.stopReason=ae,M.stepsUsed=0,R({provider:this.providerName,model:t,tokenUsage:{input:de?.usage.inputTokens.total??0,output:de?.usage.outputTokens.total??0,total:(de?.usage.inputTokens.total??0)+(de?.usage.outputTokens.total??0)},requestDuration:oe,timestamp:new Date().toISOString(),stepsUsed:0,toolCallCount:0,stopReason:ae,elapsedMs:oe}),S.dispose(),y?.removeEventListener("abort",T),i?.cleanup()},K={stream:I7r(L,de=>G(de),()=>G()),provider:this.providerName,model:t,toolCalls:P,analytics:U,metadata:M};return Object.defineProperty(K,"toolsUsed",{enumerable:!0,configurable:!0,get:()=>P.map(de=>de.toolName)}),Object.defineProperty(K,"toolExecutions",{enumerable:!0,configurable:!0,get:()=>Bd(C)}),K}},r=>r.stream,(r,n)=>({...r,stream:n}))}async executeNativeGemini3Generate(e){const t=e.model||this.modelName;return rS({name:"neurolink.provider.generate",tracer:Be.provider,attributes:{[Re.GEN_AI_SYSTEM]:"google-ai",[Re.GEN_AI_MODEL]:t,[Re.GEN_AI_OPERATION]:"generate",[Re.NL_PROVIDER]:this.providerName}},async r=>{const n=Date.now(),o=this.getTimeout(e),i=wa(o,this.providerName,"generate");let s=()=>{};try{const a=this.getApiKey(),l=await Yv(a,this.getBaseURL());h.debug("[GoogleAIStudio] Using native @google/genai for Gemini 3 generate",{model:t,hasTools:!!e.tools&&Object.keys(e.tools).length>0});const c=e.input?.text||e.prompt||"",u=[];xO(u,e.conversationMessages);const d=await dIt(e.input,c,"[GoogleAIStudio:generate]",t);u.push({role:"user",parts:d});let p,m;const f=!e.disableTools,g=!!(e.output?.format==="json"||e.schema),y=_Y(this.providerName,t,f,Object.keys(e.tools||{}).length);if(g&&y&&h.warn("[GoogleAIStudio] Gemini does not support tools and JSON schema output simultaneously. Disabling tools for this request (generate())."),f&&!(g&&y)){const K=e.tools||{};if(Object.keys(K).length>0){const de=Xv(K,"functionDeclarations");m=de,p=de.toolsConfig,h.debug("[GoogleAIStudio] Converted tools for native SDK generate",{toolCount:p[0].functionDeclarations.length,toolNames:p[0].functionDeclarations.map(oe=>oe.name)})}}const v=!p&&g,T=v&&e.schema?iIt(e.schema):void 0,b=tIt({...e,model:t,wantsJsonOutput:v,responseSchema:T},p),S=Cy(e.abortSignal,i?.controller.signal),k=new AbortController,A=()=>k.abort();S?.addEventListener("abort",A),S?.aborted&&k.abort();const x=Yh(e.toolTimeoutMs),P=jv({...e.turnTimeoutMs!==void 0?{turnTimeoutMs:e.turnTimeoutMs}:{},...e.stallTimeoutMs!==void 0?{stallTimeoutMs:e.stallTimeoutMs}:{},...e.wrapupTimeLeadMs!==void 0?{wrapupTimeLeadMs:e.wrapupTimeLeadMs}:{},onDeadline:K=>{h.warn(K==="timeout"?`[GoogleAIStudio] Native Gemini generate turn exceeded its ${e.turnTimeoutMs}ms time budget \u2014 aborting`:`[GoogleAIStudio] Native Gemini generate turn made no progress for ${e.stallTimeoutMs}ms \u2014 aborting`),k.abort()}}),C=k.signal;s=()=>{P.dispose(),S?.removeEventListener("abort",A)};const R=()=>P.timedOut||i?.controller.signal.aborted===!0,O=rIt(e.maxSteps),U=async(K,de)=>{let oe="",ae="",ge=0,be=0,Ce=0,ye=0;const Ne=[],xe=[];let le=0,Oe=0,Ie=!1,Ge;const je=Hv(jd("googleAiStudio",t)),_e=IO({providerLabel:"GoogleAIStudio",maxSteps:O,toolFailureBreaker:{maxRetries:Zh},liveTools:e.tools??{},toolGuards:{toolTimeoutMs:x,abortSignal:C,onProgress:()=>P.noteProgress()},...m?{declarations:m}:{},buildRequest:H=>({model:t,contents:H,config:de}),sendStep:async(H,ve)=>{P.noteProgress();const se=H;return l.models.generateContentStream({...se,config:{...se.config??{},abortSignal:ve}})},noteUsage:(H,ve)=>{je.noteUsage(H,ve)},planReclaim:(H,ve)=>{if(ve!==0&&!je.shouldStop())return;const se=[...H];if(LIt(se,t,je.projectedNextPromptTokens))return je.resetAfterReclaim(),{conversation:se}}}),Fe={..._e,buildStepRequest:(H,ve)=>(Oe=ve+1,P.noteProgress(),_e.buildStepRequest(H,ve)),buildToolResultMessages:(H,ve,se,ue)=>{le=ue+1;for(const ne of ve.toolCalls)r.addEvent("gen_ai.tool_call",{"tool.name":ne.name,"tool.step":le}),Ne.push({toolName:ne.name,args:ne.args});ae=ve.text||ae;for(const ne of se)xe.push({name:ne.name,input:ne.args,output:ne.output});if(se.length>0){const ne=kO(ve.raw.rawResponseParts);It(this.handleToolExecutionStorage(ve.toolCalls.map((Q,Se)=>({toolName:Q.name,args:Q.args,...Se===0&&ne?{thoughtSignature:ne}:{},stepIndex:le})),se.map(Q=>({toolName:Q.name,output:Q.output,stepIndex:le})),e,new Date),Qh,"tool storage write timed out").catch(Q=>{h.warn("[GoogleAIStudio] Failed to store native tool executions",{error:Q instanceof Error?Q.message:String(Q)})})}const F=_e.buildToolResultMessages(H,ve,se,ue);if(P.shouldNudgeWrapup()){const ne=F[F.length-1];ne&&Array.isArray(ne.parts)&&ne.parts.push({text:Vv(!1)})}try{const ne=F[F.length-1];je.noteAppendedChars(JSON.stringify(ne?.parts??[]).length)}catch{}return F}},Y=SO(m,e.tools,{toolTimeoutMs:x,abortSignal:C,onProgress:()=>P.noteProgress()}),{stream:X,resultPromise:ke}=tp(Fe,K,{tools:Y,abortSignal:C,toolTimeoutMs:x}),W=(async()=>{for await(const H of X)P.noteProgress()})();let te,me;try{te=await ke}catch(H){me=H}if(await ug(W,"GoogleAIStudio"),me!==void 0)if(P.expired||e.abortSignal?.aborted)Ie=!0;else throw h.error("[GoogleAIStudio] Native SDK generate error",me),this.handleProviderError(me);te&&(ge+=te.usage.inputTokens,be+=te.usage.outputTokens,Ce+=te.usage.cacheReadTokens??0,ye+=te.usage.reasoningTokens??0,Ge=te.rawStopReason??Ge,oe=te.text,te.aborted&&(Ie=!0)),C.aborted&&(Ie=!0);const Te=!Ie&&le>=O&&!oe;Ie&&!oe?(h.warn(`[GoogleAIStudio] Generate tool call loop ended mid-turn (${R()?"turn time limit":P.stalled?"stall watchdog":"caller abort"}); returning gathered text or an honest terminal message.`),oe=ae||fY({timedOut:R(),stalled:P.stalled,elapsedMs:P.elapsedMs(),wasAborted:Ie,...e.stallTimeoutMs!==void 0?{stallTimeoutMs:e.stallTimeoutMs}:{},maxSteps:O,toolCallCount:Ne.length})):oe=nIt("[GoogleAIStudio]",le,O,oe,ae);const pe=Date.now()-n,ie=ep({timedOut:R(),stalled:P.stalled,wasAborted:Ie,cappedWithoutAnswer:Te,finishReason:mg(Ge)});ie!=="completed"&&this.emitTurnEvent({phase:ie,step:Oe,maxSteps:O,toolCallCount:Ne.length,elapsedMs:P.elapsedMs()}),r.setAttribute(Re.GEN_AI_INPUT_TOKENS,ge),r.setAttribute(Re.GEN_AI_OUTPUT_TOKENS,be),r.setAttribute(Re.GEN_AI_FINISH_REASON,le>=O?"max_steps":"stop");const ce=Math.max(0,ge-Ce);return{content:oe,provider:this.providerName,model:t,stopReason:ie,stepsUsed:Oe,...Ge!==void 0?{rawFinishReason:Ge}:{},usage:{input:ce,output:be+ye,total:ce+Ce+be+ye,...Ce>0?{cacheReadTokens:Ce}:{},...ye>0?{reasoning:ye}:{}},...ye>0&&{reasoningTokens:ye},responseTime:pe,toolsUsed:Ne.map(H=>H.toolName),toolExecutions:Df(e,xe),enhancedWithTools:Ne.length>0}};let M;const D={prompt:NIt(b,u),...typeof b.maxOutputTokens=="number"?{maxOutputTokens:b.maxOutputTokens}:{},...typeof b.temperature=="number"?{temperature:b.temperature}:{},...typeof b.topP=="number"?{topP:b.topP}:{},abortSignal:C},$={specificationVersion:"v3",provider:this.providerName,modelId:t,supportedUrls:{},doStream:()=>{throw new Error("GoogleAIStudio: doStream is not implemented on the native generate model \u2014 NeuroLink runs this provider's turn synchronously through doGenerate.")},doGenerate:async K=>{const{contents:de,systemText:oe}=uIt(K.prompt),ae={...b,...typeof K.temperature=="number"?{temperature:K.temperature}:{},...typeof K.maxOutputTokens=="number"?{maxOutputTokens:K.maxOutputTokens}:{},...typeof K.topP=="number"?{topP:K.topP}:{}};oe?ae.systemInstruction=oe:delete ae.systemInstruction;const ge=await U(de,ae);return M=ge,{content:ge.content?[{type:"text",text:ge.content}]:[],finishReason:{unified:mg(ge.rawFinishReason)},usage:{inputTokens:{total:ge.usage?.input??0},outputTokens:{total:ge.usage?.output??0}}}}};let B;try{const K=await this.applyMiddlewareToModel($,e);if(typeof K=="string")throw new Error("GoogleAIStudio: native generate middleware resolved to a bare model id string, expected a LanguageModelV3 handle.");B=await K.doGenerate(D)}catch(K){throw this.handleProviderError(K)}let q="";for(const K of B.content)K.type==="text"&&(q+=K.text);const L=M?.usage,j=B.usage.inputTokens.total??0,G=B.usage.outputTokens.total??0,J={...M??{provider:this.providerName,model:t,stopReason:ep({timedOut:!1,stalled:!1,wasAborted:!1,cappedWithoutAnswer:!1,finishReason:B.finishReason.unified}),stepsUsed:0,responseTime:Date.now()-n,toolsUsed:[],toolExecutions:[],enhancedWithTools:!1},content:q,usage:{...L,input:j,output:G,total:j+G+(L?.cacheReadTokens??0)}};return this.enhanceResult(J,e,n)}finally{s(),i?.cleanup()}})}async generate(e){const t=typeof e=="string"?{prompt:e}:e,r=t.model||this.modelName;if(mE.some(d=>r.toLowerCase().startsWith(d.toLowerCase())))return h.info("[GoogleAIStudio] Routing image generation model to executeImageGeneration",{model:r}),this.executeImageGeneration(t);if(t.tts?.enabled&&!t.tts?.useAiResponse)return h.info("[GoogleAIStudio] Routing TTS direct-synthesis to handleDirectTTSSynthesis",{model:r}),this.handleDirectTTSSynthesis(t,Date.now());await this.preprocessNativeFileInput(t);const o=t.disableTools?{}:await this.getToolsForStream(t);let i={...t,tools:o};const s=t.output?.format==="json"||t.schema,a=_Y(this.providerName,r,!i.disableTools,Object.keys(i.tools??{}).length);s&&a&&(h.warn("[GoogleAIStudio] Gemini does not support tools and JSON schema output simultaneously. Disabling tools for this request."),i={...i,disableTools:!0,tools:{}}),!i.disableTools&&i.tools&&Object.keys(i.tools).length>0&&h.info("[GoogleAIStudio] Routing generate to native @google/genai SDK for tool calling",{model:r,totalToolCount:Object.keys(i.tools??{}).length});const c=Date.now(),u=i.input?.text||i.prompt||"";try{let d=await mt({name:"neurolink.executeGeneration",tracer:Be.provider,attributes:{[Re.GEN_AI_SYSTEM]:this.providerName,[Re.GEN_AI_MODEL]:r,"neurolink.path":"native.google-genai"}},async()=>this.executeNativeGemini3Generate(i));return d=await this.synthesizeAIResponseIfNeeded(d,t),this.emitPipelineBGenerationEvent(r,d,c,!0,void 0,u),d}catch(d){throw this.emitPipelineBGenerationEvent(r,null,c,!1,d,u),d}}emitPipelineBGenerationEvent(e,t,r,n,o,i){const s=this.neurolink?.getEventEmitter();if(!s)return;const a=t?.usage&&typeof t.usage=="object"?t.usage:{input:0,output:0,total:0};t&&typeof t=="object"&&(t._generationEndEmitted=!0),!n&&o&&typeof o=="object"&&(o._generationEndEmitted=!0),s.emit("generation:end",{provider:this.providerName,responseTime:Date.now()-r,timestamp:Date.now(),prompt:i||"",result:{content:t?.content||"",usage:a,model:e,provider:this.providerName,finishReason:n?"stop":"error"},success:n,...o?{error:o instanceof Error?o.message:String(o)}:{}})}async executeAudioStreamViaGeminiLive(e){const t=Date.now(),r=this.getApiKey();let n;try{n=await Yv(r,this.getBaseURL())}catch{throw new Wr("Missing '@google/genai'. Install with: pnpm add @google/genai",this.providerName)}const o=this.modelName||process.env.GOOGLE_VOICE_AI_MODEL||"gemini-2.5-flash-preview-native-audio-dialog",i=[];let s=null,a=!1;const l=g=>{if(!a){if(g.type==="audio"&&s){const y=s;s=null,y({value:{type:"audio",audio:g.audio},done:!1});return}i.push(g)}};let c=!1,u=()=>{};const d=new Promise((g,y)=>{u=y}),p=n.live.connect({model:o,callbacks:{onopen:()=>{},onmessage:async g=>{try{const y=g?.serverContent?.modelTurn?.parts?.[0]?.inlineData;if(y?.data){const T={data:Buffer.from(String(y.data),"base64"),sampleRateHz:24e3,channels:1,encoding:"PCM16LE"};l({type:"audio",audio:T})}g?.serverContent?.interrupted}catch(y){l({type:"error",error:y})}},onerror:g=>{c||u(new Error("Gemini Live connection failed before setup completed")),l({type:"error",error:g})},onclose:g=>{c||u(new Error("Gemini Live connection closed before setup completed")),l({type:"end"})}},config:{responseModalities:["AUDIO"],speechConfig:{voiceConfig:{prebuiltVoiceConfig:{voiceName:"Orus"}}}}}),m=await Promise.race([p,d]);return c=!0,(async()=>{try{const g=e.input?.audio;if(!g){h.debug("[GeminiLive] No audio spec found on input; skipping upstream send");return}for await(const y of g.frames){if(!y||y.byteLength===0){try{m.sendInput?await m.sendInput({event:"flush"}):m.sendRealtimeInput&&await m.sendRealtimeInput({event:"flush"})}catch(b){h.debug("[GeminiLive] flush control failed (non-fatal)",{error:b instanceof Error?b.message:String(b)})}continue}const v=y.toString("base64"),T=`audio/pcm;rate=${g.sampleRateHz||16e3}`;await m.sendRealtimeInput?.({media:{data:v,mimeType:T}})}try{m.sendInput?await m.sendInput({event:"flush"}):m.sendRealtimeInput&&await m.sendRealtimeInput({event:"flush"})}catch(y){h.debug("[GeminiLive] final flush failed (non-fatal)",{error:y instanceof Error?y.message:String(y)})}}catch(g){l({type:"error",error:g})}})().catch(()=>{}),{stream:{[Symbol.asyncIterator](){return{async next(){if(i.length>0){const g=i.shift();if(!g)return{value:void 0,done:!0};if(g.type==="audio")return{value:{type:"audio",audio:g.audio},done:!1};if(g.type==="end")return a=!0,{value:void 0,done:!0};if(g.type==="error")throw a=!0,g.error instanceof Error?g.error:new Error(String(g.error))}return a?{value:void 0,done:!0}:await new Promise(g=>{s=g})}}}},provider:this.providerName,model:o,metadata:{startTime:t,streamId:`google-ai-audio-${Date.now()}`}}}getDefaultEmbeddingModel(){return process.env.GOOGLE_AI_EMBEDDING_MODEL||process.env.GOOGLE_EMBEDDING_MODEL||"gemini-embedding-001"}async embed(e,t){if(typeof e!="string"&&e.image)throw new ot(`${this.providerName} does not support image embeddings; provide text input`,this.providerName);const r=typeof e=="string"?e:e.text??"",n=t||this.getDefaultEmbeddingModel()||"gemini-embedding-001";h.debug("Generating embedding",{provider:this.providerName,model:n,textLength:r.length});try{const o=this.getApiKey(),a=(await(await Yv(o,this.getBaseURL())).models.embedContent({model:n,contents:[r]})).embeddings?.[0]?.values;if(!a)throw new ot("No embedding returned from Google AI",this.providerName);return h.debug("Embedding generated successfully",{provider:this.providerName,model:n,embeddingDimension:a.length}),a}catch(o){throw h.error("Embedding generation failed",{error:o instanceof Error?o.message:String(o),model:n,textLength:r.length}),this.handleProviderError(o)}}async embedMany(e,t){const r=t||this.getDefaultEmbeddingModel()||"gemini-embedding-001";h.debug("Generating batch embeddings",{provider:this.providerName,model:r,count:e.length});try{const n=this.getApiKey(),o=await Yv(n,this.getBaseURL()),i=[];if(r.includes("gemini-embedding-2"))for(let a=0;a<e.length;a+=8){const l=e.slice(a,a+8),c=await Promise.all(l.map(u=>o.models.embedContent({model:r,contents:[u]})));for(const u of c)i.push(u.embeddings?.[0]?.values||[])}else{const s=await o.models.embedContent({model:r,contents:e});i.push(...(s.embeddings||[]).map(a=>a.values||[]))}if(i.length!==e.length)throw new Error(`Embedding response held ${i.length} vectors for ${e.length} texts`);return h.debug("Batch embeddings generated successfully",{provider:this.providerName,model:r,count:i.length,embeddingDimension:i[0]?.length}),i}catch(n){throw h.error("Batch embedding generation failed",{error:n instanceof Error?n.message:String(n),model:r,count:e.length}),this.handleProviderError(n)}}getApiKey(){const e=this.credentials?.apiKey||process.env.GOOGLE_AI_API_KEY||process.env.GOOGLE_GENERATIVE_AI_API_KEY;if(!e)throw new Wr("GOOGLE_AI_API_KEY or GOOGLE_GENERATIVE_AI_API_KEY environment variable is not set",this.providerName);return e}getBaseURL(){const e=this.credentials?.baseURL?.trim()||process.env.GOOGLE_AI_BASE_URL?.trim();return e&&e.length>0?e:void 0}}}}),$It={};Z($It,{GoogleAIStudioProvider:()=>FIt});var P7r=E({"src/lib/providers/googleAiStudio/index.ts"(){"use strict";R7r()}});async function fg(e,t,r){const n=parseInt(e.headers.get("content-length")??"0",10);if(n>0&&n>t)throw new Error(`${r} download too large: ${n} bytes (max ${t})`);const o=c=>new Error(`${r} download exceeded size cap after fetch: ${c} bytes (max ${t})`),i=e.body;if(!i||typeof i.getReader!="function"){const c=Buffer.from(await e.arrayBuffer());if(c.length>t)throw o(c.length);return c}const s=i.getReader(),a=[];let l=0;for(;;){const{done:c,value:u}=await s.read();if(c)break;if(l+=u.byteLength,l>t)throw await s.cancel().catch(()=>{}),o(l);a.push(u)}return Buffer.concat(a,l)}var gg,yg,Nm,Oa=E({"src/lib/utils/sizeGuard.ts"(){"use strict";gg=256*1024*1024,yg=50*1024*1024,Nm=25*1024*1024}}),M7r,O7r,D7r,N7r,OO,UIt,MY,OY,L7r,F7r,$7r,U7r,B7r=E({"node-stub:node:dns/promises"(){M7r=globalThis.crypto,O7r=globalThis.ReadableStream||class{},D7r=globalThis.URL,N7r=globalThis.URLSearchParams,OO=e=>{try{return JSON.stringify(e,null,2)}catch{return String(e)}},OO.custom=Symbol.for("nodejs.util.inspect.custom"),OO.colors={},OO.styles={},UIt=globalThis.TextDecoder,MY=globalThis.TextEncoder,OY=(e,t)=>t?.(null,"127.0.0.1",4),L7r=globalThis.performance||{now:()=>Date.now()},F7r=globalThis.Buffer||class extends Uint8Array{static from(t,r){if(typeof t=="string"){const n=(r||"utf8").toLowerCase();if(n==="base64"){const o=atob(t),i=new Uint8Array(o.length);for(let s=0;s<o.length;s++)i[s]=o.charCodeAt(s);return i}if(n==="hex"){const o=new Uint8Array(t.length/2);for(let i=0;i<t.length;i+=2)o[i/2]=parseInt(t.substr(i,2),16);return o}return new MY().encode(t)}return new Uint8Array(t)}static alloc(t){return new Uint8Array(t)}static isBuffer(t){return t instanceof Uint8Array}static concat(t){const r=t.reduce((i,s)=>i+s.length,0),n=new Uint8Array(r);let o=0;for(const i of t)n.set(i,o),o+=i.length;return n}static byteLength(t,r){return r==="base64"?Math.ceil(t.length*3/4):new MY().encode(t).length}toString(t){const r=(t||"utf8").toLowerCase();if(r==="hex")return Array.from(new Uint8Array(this.buffer,this.byteOffset,this.byteLength)).map(n=>n.toString(16).padStart(2,"0")).join("");if(r==="base64"){let n="";for(let o=0;o<this.length;o++)n+=String.fromCharCode(this[o]);return btoa(n)}return new UIt().decode(this)}},$7r=globalThis.clearTimeout,U7r=globalThis.clearInterval}}),z7r,G7r,q7r,V7r,DO,BIt,DY,j7r,H7r,zIt,W7r,K7r,J7r=E({"node-stub:node:net"(){z7r=globalThis.crypto,G7r=globalThis.ReadableStream||class{},q7r=globalThis.URL,V7r=globalThis.URLSearchParams,DO=e=>{try{return JSON.stringify(e,null,2)}catch{return String(e)}},DO.custom=Symbol.for("nodejs.util.inspect.custom"),DO.colors={},DO.styles={},BIt=globalThis.TextDecoder,DY=globalThis.TextEncoder,j7r=globalThis.performance||{now:()=>Date.now()},H7r=globalThis.Buffer||class extends Uint8Array{static from(t,r){if(typeof t=="string"){const n=(r||"utf8").toLowerCase();if(n==="base64"){const o=atob(t),i=new Uint8Array(o.length);for(let s=0;s<o.length;s++)i[s]=o.charCodeAt(s);return i}if(n==="hex"){const o=new Uint8Array(t.length/2);for(let i=0;i<t.length;i+=2)o[i/2]=parseInt(t.substr(i,2),16);return o}return new DY().encode(t)}return new Uint8Array(t)}static alloc(t){return new Uint8Array(t)}static isBuffer(t){return t instanceof Uint8Array}static concat(t){const r=t.reduce((i,s)=>i+s.length,0),n=new Uint8Array(r);let o=0;for(const i of t)n.set(i,o),o+=i.length;return n}static byteLength(t,r){return r==="base64"?Math.ceil(t.length*3/4):new DY().encode(t).length}toString(t){const r=(t||"utf8").toLowerCase();if(r==="hex")return Array.from(new Uint8Array(this.buffer,this.byteOffset,this.byteLength)).map(n=>n.toString(16).padStart(2,"0")).join("");if(r==="base64"){let n="";for(let o=0;o<this.length;o++)n+=String.fromCharCode(this[o]);return btoa(n)}return new BIt().decode(this)}},zIt=()=>0,W7r=globalThis.clearTimeout,K7r=globalThis.clearInterval}});function X7r(e){return e.length===0?null:/^0x[0-9a-f]+$/i.test(e)?parseInt(e.slice(2),16):e.length>1&&e.startsWith("0")&&/^0[0-7]+$/.test(e)?parseInt(e.slice(1),8):/^\d+$/.test(e)?parseInt(e,10):null}function NO(e){if(e.length===0)return null;const t=e.split(".");if(t.length===4){const r=t.map(X7r);return r.some(n=>n===null||n<0||n>255)?null:r.join(".")}if(t.length===1){let r;if(/^0x[0-9a-f]+$/i.test(e))r=parseInt(e.slice(2),16);else if(/^\d+$/.test(e))r=parseInt(e,10);else return null;return Number.isNaN(r)||r<0||r>4294967295?null:[r>>>24&255,r>>>16&255,r>>>8&255,r&255].join(".")}return null}function GIt(e){if(zIt(e)!==6)return null;const t=e.match(/^::ffff:(\d+\.\d+\.\d+\.\d+)$/i);let r;if(t){const n=NO(t[1]);if(!n)return null;const o=n.split(".").map(a=>parseInt(a,10)),i=(o[0]<<8|o[1]).toString(16),s=(o[2]<<8|o[3]).toString(16);r=["0","0","0","0","0","ffff",i,s]}else{const[n,o=""]=e.split("::"),i=n?n.split(":"):[],s=o?o.split(":"):[],a=8-i.length-s.length;if(a<0)return null;r=[...i,...Array(a).fill("0"),...s]}return r.length!==8?null:r.map(n=>n.toLowerCase().padStart(4,"0")).join(":")}function qIt(e){const t=e.match(/^::ffff:(\d+\.\d+\.\d+\.\d+)$/i);if(t)return NO(t[1]);const r=e.match(/^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/i);if(r){const n=parseInt(r[1],16),o=parseInt(r[2],16);return Number.isNaN(n)||Number.isNaN(o)||n>65535||o>65535?null:[n>>8&255,n&255,o>>8&255,o&255].join(".")}return null}function VIt(e){const[t,r,n,o]=e.split(".").map(i=>parseInt(i,10));return(t<<24|r<<16|n<<8|o)>>>0}function Hk(e){const t=VIt(e);for(const[r,n]of WIt){const o=VIt(r),i=n===0?0:4294967295<<32-n>>>0;if((t&i)===(o&i))return!0}return!1}function jIt(e){return KIt.some(t=>t.length===39?e===t:e.startsWith(t))}function NY(e){return e.startsWith("[")&&e.endsWith("]")?e.slice(1,-1):e}function LY(e){const t=NO(e);if(t)return Hk(t)?`IPv4 ${e} \u2192 ${t} is in a blocked range`:null;if(e.includes(":")){const r=qIt(e);if(r)return Hk(r)?`IPv4-mapped IPv6 ${e} \u2192 ${r} is in a blocked range`:null;const n=GIt(e);return n?jIt(n)?`IPv6 ${e} is in a blocked range`:null:`IPv6 ${e} could not be parsed`}return"not-an-ip"}async function Wk(e){let t;try{t=new URL(e)}catch{throw new Error(`Invalid URL: "${e}"`)}if(t.protocol!=="https:")throw new Error(`Only HTTPS URLs are permitted; got "${t.protocol}//" in "${e}"`);const r=NY(t.hostname).toLowerCase(),n=LY(r);if(n!==null){if(n!=="not-an-ip")throw new Error(`URL "${e}" rejected: ${n}`);await HIt(e,r)}}async function HIt(e,t){const[r,n]=await Promise.allSettled([OY(t,{family:4,all:!0}),OY(t,{family:6,all:!0})]),o=[],i=[];let s=!1;if(r.status==="fulfilled"){s=!0;for(const a of r.value)o.push(a.address)}if(n.status==="fulfilled"){s=!0;for(const a of n.value)i.push(a.address)}if(!s){const a=r.status==="rejected"?r.reason instanceof Error?r.reason.message:String(r.reason):"ok",l=n.status==="rejected"?n.reason instanceof Error?n.reason.message:String(n.reason):"ok";throw new Error(`URL "${e}" rejected: hostname ${t} could not be resolved (A: ${a}; AAAA: ${l})`)}for(const a of o)if(Hk(a))throw new Error(`URL "${e}" rejected: hostname ${t} resolves to ${a} (IPv4 in blocked range)`);for(const a of i){const l=LY(a.toLowerCase());if(l&&l!=="not-an-ip")throw new Error(`URL "${e}" rejected: hostname ${t} resolves to ${a} (IPv6 ${l})`)}return{v4:o,v6:i}}function Y7r(e){let t;try{t=new URL(e)}catch{throw new Error(`Invalid URL: "${e}"`)}if(t.protocol!=="https:")throw new Error(`Only HTTPS URLs are permitted; got "${t.protocol}//" in "${e}"`);const r=NY(t.hostname).toLowerCase(),n=LY(r);if(n===null)return;if(n!=="not-an-ip")throw new Error(`URL "${e}" rejected: ${n}`);const o=r.endsWith(".")?r.slice(0,-1):r;if(!o.includes("."))throw new Error(`URL "${e}" rejected: "${o}" is a single-label host name`);if(JIt.some(i=>o===i||o.endsWith(`.${i}`)))throw new Error(`URL "${e}" rejected: "${o}" is an internal host name`)}async function Z7r(e){let t;try{t=new URL(e)}catch{throw new Error(`Invalid URL: "${e}"`)}if(t.protocol!=="https:")throw new Error(`Only HTTPS URLs are permitted; got "${t.protocol}//" in "${e}"`);const r=NY(t.hostname).toLowerCase(),n=NO(r);if(n){if(Hk(n))throw new Error(`URL "${e}" rejected: IPv4 ${r} \u2192 ${n} is in a blocked range`);return{url:e,ip:n,family:4,addresses:[{ip:n,family:4}]}}if(r.includes(":")){const l=qIt(r);if(l){if(Hk(l))throw new Error(`URL "${e}" rejected: IPv4-mapped IPv6 ${r} \u2192 ${l} is in a blocked range`);return{url:e,ip:l,family:4,addresses:[{ip:l,family:4}]}}const c=GIt(r);if(!c)throw new Error(`URL "${e}" rejected: IPv6 ${r} could not be parsed`);if(jIt(c))throw new Error(`URL "${e}" rejected: IPv6 ${r} is in a blocked range`);return{url:e,ip:r,family:6,addresses:[{ip:r,family:6}]}}const{v4:o,v6:i}=await HIt(e,r),s=[...o.map(l=>({ip:l,family:4})),...i.map(l=>({ip:l,family:6}))],a=s[0];if(!a)throw new Error(`URL "${e}" rejected: hostname ${r} resolved to an empty address set`);return{url:e,ip:a.ip,family:a.family,addresses:s}}var WIt,KIt,JIt,Kk=E({"src/lib/utils/ssrfGuard.ts"(){"use strict";B7r(),J7r(),WIt=[["0.0.0.0",8],["10.0.0.0",8],["100.64.0.0",10],["127.0.0.0",8],["169.254.0.0",16],["172.16.0.0",12],["192.0.0.0",24],["192.168.0.0",16],["198.18.0.0",15],["100.100.100.200",32],["224.0.0.0",4],["240.0.0.0",4]],KIt=["0000:0000:0000:0000:0000:0000:0000:0000","0000:0000:0000:0000:0000:0000:0000:0001","fc","fd","fe8","fe9","fea","feb"],JIt=["localhost","local","localdomain","internal","home.arpa"]}});async function Q7r(e,t){const{Agent:r}=await Promise.resolve().then(()=>(zd(),Uu)),n=t[0];if(!n)throw new Error(`safeFetch: no validated addresses to pin for "${e}"`);return new r({connect:{lookup:(o,i,s)=>{if(o.toLowerCase()!==e.toLowerCase()){s(new Error(`safeFetch: refusing to resolve "${o}" \u2014 expected "${e}"`),"",0);return}if(i?.all){s(null,t.map(a=>({address:a.ip,family:a.family})));return}s(null,n.ip,n.family)}}})}function eVr(e){if(typeof e!="object"||e===null)return!1;const t=e;return typeof t.arrayBuffer=="function"&&typeof t.headers=="object"&&t.headers!==null&&typeof t.headers.get=="function"}async function tVr(e,t,r){if(e.status>=300&&e.status<400)throw new Error(`safeDownload(${r.label}): refused to follow redirect ${e.status} \u2192 ${e.headers.get("location")??"<no-location>"} (for ${t})`);if(!e.ok)throw new Error(`safeDownload(${r.label}) failed: HTTP ${e.status} for ${t}`);if(!eVr(e))throw new Error(`safeDownload(${r.label}): response is missing headers.get()/arrayBuffer()`);return fg(e,r.maxBytes,r.label)}async function Lm(e,t){const{getProxyDispatcherForUrl:r}=await Promise.resolve().then(()=>(Ln(),SIt)),n=await r(e),{fetch:o}=await Promise.resolve().then(()=>(zd(),Uu));let i,s,a=!1;if(n)Y7r(e),i=e,s=n;else{const p=await Z7r(e);i=p.url;const m=new URL(i).hostname.replace(/^\[|\]$/g,"");s=await Q7r(m,p.addresses),a=!0}const l=new AbortController,c=setTimeout(()=>l.abort(),t.timeoutMs??XIt),u=t.signal?AbortSignal.any([t.signal,l.signal]):l.signal;let d;try{d=await o(i,{method:"GET",signal:u,redirect:"manual",dispatcher:s})}finally{clearTimeout(c),a&&s.close().catch(()=>{})}return tVr(d,e,t)}var XIt,Fm=E({"src/lib/utils/safeFetch.ts"(){"use strict";Oa(),Kk(),XIt=6e4}});function FY(e){}function $Y(e){if(typeof e=="function")throw new TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");const{onEvent:t=FY,onError:r=FY,onRetry:n=FY,onComment:o}=e,i=[];let s=!0,a,l="",c=0,u;function d(v){if(s&&(s=!1,v.charCodeAt(0)===239&&v.charCodeAt(1)===187&&v.charCodeAt(2)===191&&(v=v.slice(3))),i.length===0){const S=p(v);S!==""&&i.push(S);return}if(v.indexOf(`
|
|
1033
|
+
`)}:{contents:t}}async function vY(e,t,r="[GeminiNative]"){if(!(!t||t.length===0))for(const n of t){const o=n.filename.split(/[\\/]/).pop()??n.filename,i=o.lastIndexOf("."),s=i>0?o.slice(i):".bin",a=await uEt(n.buffer,n.mimeType,s);if(EJ(a.mimeType)){h.warn(`${r} Skipping native audio for ${o}: ${a.mimeType} is not accepted and could not be converted. The metadata summary was still included.`);continue}e.push({inlineData:{mimeType:a.mimeType,data:a.buffer.toString("base64")}}),h.debug(`${r} Added native audio part for ${o} (${a.mimeType})`)}}async function wY(e,t,r,n,o="[GeminiNative]"){if(!t||t.length===0)return;let i=e.reduce((s,a)=>"inlineData"in a?s+Math.floor(a.inlineData.data.length*3/4):s,0);for(const s of t){const a=s.filename.split(/[\\/]/).pop()??s.filename,l=vEt(r,s,i,n);if(!l.deliver){h.warn(`${o} Sending keyframes instead of the clip for ${a}: ${l.reason}.`);continue}i+=s.buffer.length,e.push({inlineData:{mimeType:s.mimeType,data:s.buffer.toString("base64")}}),h.debug(`${o} Added native video part for ${a} (${s.mimeType})`)}}async function dIt(e,t,r="[GeminiNative]",n){const i=[{text:typeof t=="string"?t:e?.text??""}];if(e?.pdfFiles&&e.pdfFiles.length>0){h.debug(`${r} Processing ${e.pdfFiles.length} PDF(s)`);for(const s of e.pdfFiles){let a;typeof s=="string"?Ds(s)?a=ws(s):a=Buffer.from(s,"base64"):a=s,i.push({inlineData:{mimeType:"application/pdf",data:a.toString("base64")}})}}if(e?.images&&e.images.length>0){h.debug(`${r} Processing ${e.images.length} image(s)`);for(const s of e.images){const a=s&&typeof s=="object"&&!Buffer.isBuffer(s)?s.data:s;let l,c="image/jpeg";if(typeof a=="string")if(Ds(a)){l=ws(a);const u=By(a).toLowerCase();u===".png"?c="image/png":u===".gif"?c="image/gif":u===".webp"&&(c="image/webp")}else if(a.startsWith("data:")){const u=a.match(/^data:([^;]+);base64,(.+)$/);if(u)c=u[1],l=Buffer.from(u[2],"base64");else continue}else if(a.startsWith("http://")||a.startsWith("https://"))try{const u=await fetch(a);if(!u.ok){h.warn(`${r} Image fetch failed: ${u.status} ${u.statusText}, skipping`,{url:a});continue}const d=await u.arrayBuffer();l=Buffer.from(d);const p=u.headers.get("content-type");p&&p.startsWith("image/")&&(c=p.split(";")[0])}catch(u){h.warn(`${r} Image URL fetch threw, skipping: ${u instanceof Error?u.message:String(u)}`,{url:a});continue}else l=Buffer.from(a,"base64");else l=a;l&&i.push({inlineData:{mimeType:c,data:l.toString("base64")}})}}return await vY(i,e?.nativeAudioFiles,r),await wY(i,e?.nativeVideoFiles,"google-ai-studio",n,r),i}var Wv,pIt,AO,TY,CO=E({"src/lib/providers/googleNativeGemini3/utils.ts"(){"use strict";Jr(),Sn(),qt(),Zo(),hEt(),kJ(),z(),EO(),Ic(),ss(),Q1t(),Wv=class extends Map{resultCache=new Map;get(e){const t=super.get(e);if(!t)return t;const r=this.resultCache;return async(o,i)=>{const s=`${e}::${Fqr(o)}`;if(r.has(s))return h.warn(`[DedupExecuteMap] Tool "${e}" re-requested with identical arguments in the same turn \u2014 reusing the previous result instead of re-executing.`),r.get(s);const a=await t(o,i);return r.set(s,a),a}}},pIt=/^[A-Za-z_][A-Za-z0-9_.:-]{0,127}$/,AO=128,TY=100}});function IO(e){const t=o=>e.declarations?.originalNameMap?.get(o)??o,r=o=>{const i=e.declarations?.originalNameMap;if(!i)return o;for(const[s,a]of i)if(a===o)return s;return o};let n=0;return{providerLabel:e.providerLabel,maxSteps:e.maxSteps,...e.toolFailureBreaker?{toolFailureBreaker:e.toolFailureBreaker}:{},buildStepRequest(o,i){const s=e.declarations?Bqr(e.liveTools,e.declarations):[];return{raw:e.buildRequest(o,i),...s.length>0?{hydratedToolNames:s}:{}}},...e.planReclaim?{planReclaim:(o,i)=>e.planReclaim?.(o,i)}:{},...e.enableMalformedRetry&&e.buildMalformedRetryNote?{isMalformedStep:o=>o.toolCalls.length===0&&!o.text&&o.rawStopReason==="MALFORMED_FUNCTION_CALL",buildMalformedRetryNote:e.buildMalformedRetryNote}:{},resolveToolOnMiss:o=>{const s=fQe(e.liveTools,o)?.execute;if(!s)return;const a=e.declarations?.executeMap;let l=s;return a&&(a.set(o,s),l=a.get(o)??s),{execute:e.toolGuards?pg(o,l,e.toolGuards):(async(u,d)=>l(u,d))}},async executeStep(o,i,s){const a=await e.sendStep(o.raw,s),l=e.collectStep?await e.collectStep(a,i):await Gqr(a,{push:f=>i.push(f)});e.noteUsage?.(l.inputTokens,l.outputTokens);const c=qqr(l.rawResponseParts),u=l.stepFunctionCalls.map(f=>({id:`${e.providerLabel}_${n++}_${f.name}`,name:t(f.name),args:f.args})),d=e.finalResultToolName?u.find(f=>f.name===e.finalResultToolName):void 0,p=d?[]:u,m=d?JSON.stringify(d.args):c;return d&&e.onTerminalResult?.(m),{text:m,toolCalls:p,usage:{inputTokens:l.inputTokens,outputTokens:l.outputTokens,...l.cacheReadTokens?{cacheReadTokens:l.cacheReadTokens}:{},...l.reasoningTokens?{reasoningTokens:l.reasoningTokens}:{}},rawStopReason:l.finishReason,raw:{rawResponseParts:l.rawResponseParts,stepFunctionCalls:l.stepFunctionCalls}}},buildToolResultMessages(o,i,s,a){const l=[...o];return Wqr(l,i.raw.rawResponseParts,i.raw.stepFunctionCalls),l.push({role:"user",parts:s.map(c=>({functionResponse:{name:r(c.name),response:c.error?c.output:{result:c.output}}}))}),l},mapFinishReason(o,i){const s=mg(o);return i&&s==="stop"?"tool-calls":s}}}var mIt=E({"src/lib/core/geminiLoopAdapter.ts"(){"use strict";EO(),qS(),CO()}});function Kv(){const e=[];let t=!1,r,n=!1,o=null;function i(){if(o){const d=o;o=null,d()}}function s(d){t||(e.push(d),i())}function a(){t=!0,i()}function l(d){t=!0,r=d,n=!0,i()}let c=0;async function*u(){try{for(;;)if(c<e.length)yield e[c++],c>1024&&c*2>=e.length&&(e.splice(0,c),c=0);else if(t){if(n)throw r instanceof Error?r:new Error(String(r));return}else await new Promise(d=>{o=d})}finally{t=!0,e.length=0,o?.()}}return{push:s,close:a,error:l,iterable:u()}}var Jv=E({"src/lib/core/streamChannel.ts"(){"use strict"}});function o7r(e,t){return{inputTokens:e.inputTokens+t.inputTokens,outputTokens:e.outputTokens+t.outputTokens,cacheReadTokens:(e.cacheReadTokens??0)+(t.cacheReadTokens??0)||void 0,cacheWriteTokens:(e.cacheWriteTokens??0)+(t.cacheWriteTokens??0)||void 0,reasoningTokens:(e.reasoningTokens??0)+(t.reasoningTokens??0)||void 0,cacheWrite5mTokens:(e.cacheWrite5mTokens??0)+(t.cacheWrite5mTokens??0)||void 0,cacheWrite1hTokens:(e.cacheWrite1hTokens??0)+(t.cacheWrite1hTokens??0)||void 0}}async function i7r(e){const{name:t,execute:r,args:n,toolCallId:o,turnSignal:i,toolTimeoutMs:s}=e;if(s===null)return r(n,{toolCallId:o,abortSignal:i});const a=new AbortController,l=()=>a.abort(i.reason);i.aborted?a.abort(i.reason):i.addEventListener("abort",l,{once:!0});let c;const u=new Promise((d,p)=>{c=setTimeout(()=>{const m=new Error(`Tool "${t}" execution timed out after ${s}ms`);a.abort(m),p(m)},s)});try{return await Promise.race([Promise.resolve(r(n,{toolCallId:o,abortSignal:a.signal})),u])}finally{clearTimeout(c),i.removeEventListener("abort",l)}}async function s7r(e){const{calls:t,adapter:r,tools:n,failedTools:o,abortSignal:i,toolTimeoutMs:s}=e,a=[],l=[],c=[];let u=!1;for(const d of t){if(i.aborted){u=!0;break}c.push(d);const p=r.toolFailureBreaker,m=p?o.get(d.name):void 0;if(p&&m&&m.count>=p.maxRetries){const y={error:`TOOL_PERMANENTLY_FAILED: "${d.name}" has failed ${m.count} times. Last error: ${m.lastError}.`,status:"permanently_failed",do_not_retry:!0};a.push({...d,output:y,error:y.error,permanentlyFailed:!0}),l.push({id:d.id,name:d.name,input:d.args,output:y,error:y.error});continue}const f=n?.[d.name];let g=f;if(!f?.execute){const y=r.resolveToolOnMiss?.(d.name);y&&(g=y,o.delete(d.name))}if(!g?.execute){const y=p?{error:`TOOL_NOT_FOUND: "${d.name}" does not exist.`,status:"permanently_failed",do_not_retry:!0}:{error:`Tool not found: ${d.name}`};a.push({...d,output:y,error:y.error,permanentlyFailed:!!p}),l.push({id:d.id,name:d.name,input:d.args,output:y,error:y.error});continue}try{const y=await i7r({name:d.name,execute:g.execute,args:d.args,toolCallId:d.id,turnSignal:i,toolTimeoutMs:s}),v=p?.classifyResultFailure?.(y);if(p)if(v){const T=o.get(d.name)??{count:0,lastError:""};T.count++,T.lastError=v,o.set(d.name,T)}else p.consecutive&&o.delete(d.name);a.push({...d,output:y}),l.push({id:d.id,name:d.name,input:d.args,output:y})}catch(y){const v=y instanceof Error?y.message:String(y);if(p){const b=o.get(d.name)??{count:0,lastError:""};b.count++,b.lastError=v,o.set(d.name,b)}const T={error:v,status:"failed"};a.push({...d,output:T,error:v}),l.push({id:d.id,name:d.name,input:d.args,output:T,error:v})}}return{toolResults:a,executions:l,dispatched:c,abortedMidBatch:u}}function tp(e,t,r){const n=Kv(),o=new AbortController,i=()=>o.abort();r.abortSignal?.addEventListener("abort",i),r.abortSignal?.aborted&&o.abort();const s=new Map;let a=!1;const l=(async()=>{let c=t,u={inputTokens:0,outputTokens:0},d="",p="",m;const f=[],g=[];let y=!1,v=e.maxSteps;const T=Date.now();try{for(let k=0;k<v&&!o.signal.aborted;k++){if(e.planReclaim){const M=e.planReclaim(c,k);if(M?.conversation!==void 0&&(c=M.conversation),M?.stop)break}const A=e.buildStepRequest(c,k);for(const M of A.hydratedToolNames??[])s.delete(M);let x=!1;const P={push:M=>{x=!0,n.push(M)}};let C;try{C=await Py(async()=>{x=!1;try{return await e.executeStep(A,P,o.signal)}catch(M){throw x?new bY(M):M}},r.span,`${e.providerLabel}.step`,void 0,o.signal)}catch(M){throw M instanceof bY?M.cause:M}if(u=o7r(u,C.usage),m=C.rawStopReason,p=C.text||p,e.isMalformedStep?.(C)&&!a&&!o.signal.aborted){a=!0,h.warn(`[${e.providerLabel}] Malformed function call at step ${k+1}/${v}; retrying once.`),c=e.buildMalformedRetryNote?.(c,k)??c;continue}if(C.toolCalls.length===0){d=C.text||d;break}k===v-1&&(y=!0);const R=await s7r({calls:C.toolCalls,adapter:e,tools:r.tools,failedTools:s,abortSignal:o.signal,toolTimeoutMs:Yh(r.toolTimeoutMs)}),O=R.toolResults;if(f.push(...R.dispatched),g.push(...R.executions),R.abortedMidBatch)break;if(c=e.buildToolResultMessages(c,C,O,k),r.beforeStep&&!o.signal.aborted){const M=await r.beforeStep({stepIndex:k,stepsCompleted:k+1,maxSteps:v,elapsedMs:Date.now()-T,toolNames:R.dispatched.map($=>$.name),signal:o.signal}),D=typeof M?.maxSteps=="number"&&Number.isFinite(M.maxSteps)?Math.floor(M.maxSteps):void 0;D!==void 0&&D>v&&(v=D,y=!1),M?.nudge&&e.appendPlanningNudge&&(c=e.appendPlanningNudge(c,M.nudge))}}const b=o.signal.aborted,S=e.mapFinishReason(m,y);return{text:d||(y?p:""),toolCalls:f,toolExecutions:g,usage:u,finishReason:b&&m===void 0?"other":S,rawStopReason:m,conversation:c,aborted:b}}catch(b){throw n.error(b),b}finally{n.close(),r.abortSignal?.removeEventListener("abort",i)}})();return{stream:n.iterable,resultPromise:l}}var bY,RO=E({"src/lib/core/loopEngine.ts"(){"use strict";Jv(),z(),kd(),Zo(),bY=class extends Error{constructor(e){super(e instanceof Error?e.message:String(e)),this.cause=e}cause}}});function a7r(e,t){return e==="google-ai"?!0:e==="vertex"?!(t?.startsWith("claude-")??!1):!1}function l7r(e){return e==="anthropic"||e==="bedrock"}function _Y(e,t,r,n){return(a7r(e,t)||l7r(e))&&r&&n>0}function c7r(e){const t=e instanceof Error?e.message:typeof e=="string"?e:"";return/cannot be combined with (a )?(tool|function)/i.test(t)||/json[\s_-]?(mode|schema|object|output)[^.]{0,60}(tool|function)/i.test(t)||/(tool|function)[\s-]?call[^.]{0,60}json[\s_-]?(mode|schema)/i.test(t)||/response_format[^.]{0,60}(tool|function)/i.test(t)}function hIt(e){const t=e instanceof Error?e.message:typeof e=="string"?e:"";return/too many states/i.test(t)}function u7r(e){const t=e instanceof Error?e.message:typeof e=="string"?e:"";return/does not support[^.]{0,80}response[\s_-]?format/i.test(t)||/response[\s_-]?format[^.]{0,60}(?:is )?not support/i.test(t)||/unsupported response[\s_-]?format/i.test(t)}var EY=E({"src/lib/core/modules/structuredOutputPolicy.ts"(){"use strict"}});function d7r(e){return e?.kind==="toolCall"||e?.kind==="toolResult"}function p7r(e,t,r){const n=[];let o=t;for(;o<r;){if(!d7r(e[o])){o++;continue}const i=o;for(;o<e.length&&e[o].kind==="toolCall";)o++;for(;o<e.length&&e[o].kind==="toolResult";)o++;if(o>r)break;n.push({start:i,end:o})}return n}function PO(e,t){const{availableInputTokens:r,fixedOverheadTokens:n,thresholdRatio:o=M4,lowWaterRatio:i=fIt,protectedTailCount:s=gIt,calibration:a=1}=t,l=a>0?a:1,c=Math.floor(r*o/l),u=Math.floor(r*i/l);let d=n;for(const v of e)d+=v.tokens;if(d<=c)return{fire:!1,truncate:[],drop:[],projectedTokens:d};const p=1,m=Math.max(p,e.length-s),f=[],g=new Set;for(let v=p;v<m&&d>u;v++){const T=e[v];if(T.kind!=="toolResult"||T.previewTokens===void 0)continue;const b=T.tokens-T.previewTokens;b<=0||(f.push(v),d-=b)}if(d>u){const v=p7r(e,p,m);for(const T of v){if(d<=u)break;for(let b=T.start;b<T.end;b++){const S=e[b],k=f.includes(b)?S.previewTokens??S.tokens:S.tokens;d-=k,g.add(b)}}}const y=f.filter(v=>!g.has(v));return{fire:y.length>0||g.size>0,truncate:y,drop:[...g].sort((v,T)=>v-T),projectedTokens:d}}var fIt,gIt,MO=E({"src/lib/context/loopGuardCore.ts"(){"use strict";Zo(),fIt=.6,gIt=4}});function yIt(e){if(typeof e=="string")return e;if(e==null)return"";try{return JSON.stringify(e)??""}catch{return"x".repeat(2e5)}}function vIt(e,t){return Array.isArray(e.parts)&&e.parts.some(r=>r&&typeof r=="object"&&t in r)}function m7r(e){return vIt(e,"functionResponse")}function SY(e){const{preview:t}=dl(e,{maxBytes:kY,maxLines:TIt});return t}function h7r(e,t){return Vt(yIt(e.parts),t)+jl}function f7r(e,t){return e.map(r=>{const n=h7r(r,t);if(m7r(r)){const o=yIt(r.parts),i=o.length>kY?Vt(SY(o),t)+jl:n;return{kind:"toolResult",tokens:n,...i<n?{previewTokens:i}:{}}}return vIt(r,"functionCall")?{kind:"toolCall",tokens:n}:{kind:"other",tokens:n}})}function wIt(e){const{contents:t,availableInputTokens:r,fixedOverheadTokens:n=0,provider:o,observedPromptTokens:i}=e,s=f7r(t,o);let a=1;if(i&&i>0){const c=n+s.reduce((u,d)=>u+d.tokens,0);c>0&&(a=Math.min(3,Math.max(1,i/c)))}const l=PO(s,{availableInputTokens:r,fixedOverheadTokens:n,calibration:a});if(l.fire)return h.info("[GeminiLoopGuard] Reclaiming agent-loop context",{provider:o,contents:t.length,toolResponsesTruncated:l.truncate.length,contentsDropped:l.drop.length,projectedTokens:l.projectedTokens,calibration:a}),l}var kY,TIt,xY,bIt=E({"src/lib/context/geminiLoopGuard.ts"(){"use strict";di(),cg(),MO(),z(),kY=2048,TIt=60,xY="[Earlier tool exchanges were removed to fit the context window.]"}}),_It=E({"src/lib/providers/googleNativeGemini3/index.ts"(){"use strict";CO()}}),AY,rp,EIt=E({"src/lib/providers/anthropic/cacheControl.ts"(){"use strict";AY=e=>{if(!e||e.length===0)return e;if(e.some(r=>r.cache_control!==void 0))return[...e];const t=e[e.length-1];return[...e.slice(0,-1),{...t,cache_control:{type:"ephemeral"}}]},rp=e=>e?.providerOptions?.anthropic?.cacheControl?.type==="ephemeral"?{type:"ephemeral"}:void 0}});function Xv(e,t){if(t==="functionDeclarations")return eIt(e);const r=Object.entries(e??{});if(r.length!==0)return r.map(([n,o])=>{const i=o,s=i.inputSchema??i.parameters,a=s?qo(s):{type:"object",properties:{}},l=rp(o);return{name:n,...i.description?{description:i.description}:{},input_schema:a,...l?{cache_control:l}:{}}})}var CY=E({"src/lib/core/nativeToolFormat.ts"(){"use strict";CO(),EIt(),ss()}});function g7r(e,t){try{const[r,n]=t.split("/"),o=parseInt(n,10);if(isNaN(o)||o<0||o>32)return!1;const i=c=>{const u=c.split(".").map(Number);return(u[0]<<24)+(u[1]<<16)+(u[2]<<8)+u[3]},s=i(e),a=i(r),l=-1<<32-o>>>0;return(s&l)===(a&l)}catch{return!1}}function y7r(e,t){const r=t||process.env.NO_PROXY||process.env.no_proxy;if(!r)return!1;try{const n=new URL(e),o=n.hostname.toLowerCase(),i=n.port||(n.protocol==="https:"?"443":"80"),s=r.split(",").map(a=>a.trim()).filter(Boolean);for(const a of s){const l=a.toLowerCase();if(l==="*")return!0;if(l.startsWith(".")){const c=l.slice(1);if(o.endsWith(c)||o===c)return!0}else if(l.includes(":")){const[c,u]=l.split(":");if(o===c&&i===u)return!0}else if(l.includes("/")){if(/^\d{1,3}(\.\d{1,3}){3}$/.test(o)&&g7r(o,l))return!0}else if(o===l)return!0}return!1}catch(n){return h.warn("[Proxy] Error in NO_PROXY bypass logic",{targetUrl:e,error:n}),!1}}var v7r=E({"src/lib/proxy/utils/noProxyUtils.ts"(){"use strict";z()}}),SIt={};Z(SIt,{createProxyFetch:()=>Ot,getProxyDispatcherForUrl:()=>S7r,getProxyStatus:()=>MIt,googleSdkProxyHttpOptions:()=>PY,isTransientNetworkError:()=>IY,maskProxyUrl:()=>hg});async function w7r(){try{return(await Promise.resolve().then(()=>(Im(),$X))).getLangfuseContext?.()}catch{return}}function T7r(e,t){const r=new Headers(e instanceof Request?e.headers:void 0);if(t?.headers){const n=new Headers(t.headers);for(const[o,i]of n.entries())r.set(o,i)}return r}async function kIt(e,t){const r={};W0.inject(xr.active(),r);const n=await w7r();if(n?.sessionId&&(r["x-neurolink-session-id"]=n.sessionId),n?.userId&&(r["x-neurolink-user-id"]=n.userId),n?.conversationId&&(r["x-neurolink-conversation-id"]=n.conversationId),Object.keys(r).length===0)return t??{};const o=T7r(e,t);for(const[i,s]of Object.entries(r))o.has(i)||o.set(i,s);return{...t,headers:o}}function b7r(e){try{const t=typeof e=="string"?e:e instanceof URL?e.href:e.url;return new URL(t).hostname}catch{return"[unknown]"}}function IY(e){let t=e;for(let r=0;r<5&&t;r++){const n=t;if(n.code&&n8.has(n.code)||n.message?.includes("socket hang up")||n.message?.includes("network socket disconnected")||n.message?.includes("other side closed"))return!0;t=n.cause}return!1}async function xIt(e,t,r=3,n=500){const o=b7r(e);return OIt.startActiveSpan("neurolink.http.fetchWithRetry",async i=>{i.setAttribute("http.request.max_retries",r),i.setAttribute("http.request.hostname",o),i.setAttribute("http.request.method",t?.method||"GET");let s=0;try{for(let a=0;a<=r;a++){s=a+1;try{const l=await fetch(e,t);return i.setAttribute("http.request.total_attempts",s),i.setAttribute("http.response.status_code",l.status),i.setStatus({code:Ue.OK}),l}catch(l){const c=IY(l),u=l;if(!c||a===r)throw i.setAttribute("http.request.total_attempts",s),i.setStatus({code:Ue.ERROR,message:u?.message||u?.code||"fetchWithRetry final failure"}),i.recordException(l instanceof Error?l:new Error(String(l))),l;const d=n*Math.pow(2,a);i.addEvent("http.request.retry",{"retry.attempt":a+1,"retry.delay_ms":d,"retry.error":(u?.code||u?.message||String(l)).slice(0,256)}),h.debug(`[fetchWithRetry] Transient error (${u?.code||u?.message}), retrying in ${d}ms (attempt ${a+1}/${r})`),await new Promise(p=>setTimeout(p,d))}}throw new Error("fetchWithRetry exhausted")}finally{i.end()}})}function AIt(e){if(!e)return{parsed:null,size:0,type:"empty"};if(typeof e=="string")try{return{parsed:JSON.parse(e),size:e.length,type:"json"}}catch{return{parsed:e,size:e.length,type:"text"}}return e instanceof ArrayBuffer?{parsed:"[ArrayBuffer]",size:e.byteLength,type:"arraybuffer"}:e instanceof Uint8Array?{parsed:"[Uint8Array]",size:e.length,type:"uint8array"}:{parsed:"[Stream]",size:-1,type:"stream"}}async function RY(e){const t={};e.headers.forEach((r,n)=>{t[n]=DIt.has(n.toLowerCase())?`${r.substring(0,4)}***`:r});try{const n=await e.clone().text();try{return{parsed:JSON.parse(n),size:n.length,type:"json",headers:t}}catch{return{parsed:n,size:n.length,type:"text",headers:t}}}catch{return{parsed:"[unable to read body]",size:-1,type:"error",headers:t}}}function _7r(e){try{const t=new URL(e),r={protocol:t.protocol,hostname:t.hostname,port:parseInt(t.port)||CIt(t.protocol),cleanUrl:`${t.protocol}//${t.hostname}:${t.port||CIt(t.protocol)}`};return t.username&&t.password&&(r.auth={username:decodeURIComponent(t.username),password:decodeURIComponent(t.password)}),r}catch(t){let r;try{const n=new URL(e);n.username="",n.password="",r=n.toString()}catch{r="[invalid-url]"}throw h.error("[Proxy] Failed to parse proxy URL",{proxyUrl:r,error:t}),new Error(`Invalid proxy URL: ${r}`,{cause:t})}}function CIt(e){switch(e){case"http:":return 8080;case"https:":return 8080;case"socks4:":return 1080;case"socks5:":return 1080;default:return 8080}}function IIt(e){if(y7r(e))return h.debug("[Proxy] Bypassing proxy due to NO_PROXY",{targetUrl:e}),null;try{const t=new URL(e),r=process.env.HTTPS_PROXY||process.env.https_proxy,n=process.env.HTTP_PROXY||process.env.http_proxy,o=process.env.ALL_PROXY||process.env.all_proxy,i=process.env.SOCKS_PROXY||process.env.socks_proxy;return t.protocol==="https:"&&r?r:t.protocol==="http:"&&n?n:o||i||null}catch(t){return h.warn("[Proxy] Error selecting proxy URL",{targetUrl:e,error:t}),null}}async function E7r(e){const t=_7r(e);switch(h.debug("[Proxy] Creating proxy agent",{protocol:t.protocol,hostname:t.hostname,port:t.port,hasAuth:!!t.auth}),t.protocol){case"http:":case"https:":{const{ProxyAgent:r}=await Promise.resolve().then(()=>(zd(),Uu));return new r(e)}case"socks4:":case"socks5:":throw new Error("SOCKS proxy support requires 'proxy-agent' package. Install it with: npm install proxy-agent");default:throw new Error(`Unsupported proxy protocol: ${t.protocol}`)}}async function RIt(e){const t=globalThis;t.__NL_PROXY_AGENT_CACHE__||(t.__NL_PROXY_AGENT_CACHE__=new Map);const r=t.__NL_PROXY_AGENT_CACHE__,n=Ld("sha256").update(hg(e)??e).digest("hex"),o=r.get(n)||await E7r(e);return r.set(n,o),o}async function S7r(e){const t=IIt(e);return t?RIt(t):null}function na(e){return hg(e)??"NOT_SET"}function PIt(e){return typeof e=="string"?e:e instanceof URL?e.href:e.url}function k7r(){return async(e,t)=>{const r=await kIt(e,t),n=`req-${Date.now()}-${Math.random().toString(36).substring(2,11)}`,o=Date.now(),i=PIt(e);if(h.shouldLog("debug")){const{size:s,type:a}=AIt(r?.body);h.debug("[Observability] HTTP request to LLM provider",{requestId:n,url:i,method:r?.method||"POST",bodySize:s,bodyType:a})}try{const s=await xIt(e,r);if(h.shouldLog("debug")){const{parsed:a,size:l,type:c,headers:u}=await RY(s);h.debug("[Observability] HTTP response from LLM provider",{requestId:n,url:i,status:s.status,statusText:s.statusText,durationMs:Date.now()-o,contentLength:l,hasContent:!!a,bodyType:c,responseHeaders:u})}return s}catch(s){throw h.debug("[Observability] HTTP request failed",{requestId:n,url:i,error:s instanceof Error?s.message:String(s),durationMs:Date.now()-o}),s}}}async function x7r(e,t,r){const{httpsProxy:n,httpProxy:o,allProxy:i,socksProxy:s,noProxy:a}=r;t=await kIt(e,t);const l=`req-${Date.now()}-${Math.random().toString(36).substring(2,11)}`,c=Date.now(),u=PIt(e);if(h.shouldLog("debug")){const{size:m,type:f}=AIt(t?.body);h.debug("[Observability] HTTP request to LLM provider",{requestId:l,url:u,method:t?.method||"POST",bodySize:m,bodyType:f})}h.debug("[Proxy Fetch] ENHANCED REQUEST START",{requestId:l,targetUrl:u,timestamp:new Date().toISOString(),httpProxy:na(o),httpsProxy:na(n),allProxy:na(i),socksProxy:na(s),noProxy:a||"NOT_SET",initMethod:t?.method||"GET"});const d=e instanceof Request?e.clone():null;try{const m=IIt(u);if(m){const f=new URL(u);h.debug("[Proxy Fetch] \u{1F517} ENHANCED URL ANALYSIS",{requestId:l,targetUrl:u,urlHostname:f.hostname,urlProtocol:f.protocol,urlPort:f.port,selectedProxyUrl:na(m),timestamp:new Date().toISOString()}),h.debug("[Proxy Fetch] \u{1F3AF} ENHANCED PROXY AGENT CREATION",{requestId:l,proxyUrl:na(m),targetHostname:f.hostname,targetProtocol:f.protocol,aboutToCreateProxyAgent:!0,timestamp:new Date().toISOString()});const g=await RIt(m);h.debug("[Proxy Fetch] \u2705 ENHANCED PROXY AGENT CREATED",{requestId:l,hasDispatcher:!!g,dispatcherType:typeof g,dispatcherConstructor:g?.constructor?.name||"unknown",timestamp:new Date().toISOString()});let y,v={...t};e instanceof Request?(y=e.url,v={method:e.method,headers:e.headers,body:e.body,...t}):y=e;const b=await(await Promise.resolve().then(()=>(zd(),Uu))).fetch(y,{...v,dispatcher:g});if(h.shouldLog("debug")){const{parsed:S,size:k,type:A,headers:x}=await RY(b);h.debug("[Observability] HTTP response from LLM provider",{requestId:l,url:u,status:b?.status,statusText:b?.statusText,durationMs:Date.now()-c,contentLength:k,hasContent:!!S,bodyType:A,proxied:!0,responseHeaders:x})}return h.debug("[Proxy Fetch] ENHANCED PROXY SUCCESS",{requestId:l,responseStatus:b?.status,responseOk:b?.ok,proxyUsed:!0,timestamp:new Date().toISOString()}),b}}catch(m){const f=m instanceof Error?m.message:String(m);h.debug("[Observability] HTTP request failed",{requestId:l,url:u,error:f,durationMs:Date.now()-c}),h.debug("[Proxy Fetch] ENHANCED ERROR ANALYSIS",{requestId:l,error:f,errorType:m instanceof Error?m.constructor.name:typeof m,willFallback:!0,timestamp:new Date().toISOString()}),h.warn(`[Proxy Fetch] Enhanced proxy failed (${f}), falling back to direct connection`)}h.debug("[Proxy Fetch] ENHANCED FALLBACK TO STANDARD FETCH",{requestId:l,fallbackReason:"No proxy configured or proxy failed",timestamp:new Date().toISOString()});const p=e instanceof Request?d??e:e;try{const m=await xIt(p,t);if(h.shouldLog("debug")){const{parsed:f,size:g,type:y,headers:v}=await RY(m);h.debug("[Observability] HTTP response from LLM provider",{requestId:l,url:u,status:m.status,statusText:m.statusText,durationMs:Date.now()-c,contentLength:g,hasContent:!!f,bodyType:y,proxied:!1,responseHeaders:v})}return m}catch(m){const f=m instanceof Error?m.message:String(m);throw h.debug("[Observability] HTTP request failed",{requestId:l,url:u,error:f,durationMs:Date.now()-c}),m}}function A7r(e){return async(t,r)=>x7r(t,r,e)}function Ot(){const e=process.env.HTTPS_PROXY||process.env.https_proxy,t=process.env.HTTP_PROXY||process.env.http_proxy,r=process.env.ALL_PROXY||process.env.all_proxy,n=process.env.SOCKS_PROXY||process.env.socks_proxy,o=process.env.NO_PROXY||process.env.no_proxy,i={httpsProxy:e,httpProxy:t,allProxy:r,socksProxy:n,noProxy:o};if(h.shouldLog("debug")){const s=Object.keys(process.env).filter(a=>a.toLowerCase().includes("proxy")).reduce((a,l)=>{const c=process.env[l]||"NOT_SET";return a[l]=l.toLowerCase()==="no_proxy"?c:na(c),a},{});h.debug("[Proxy Fetch] ENHANCED_PROXY_ENV_DETECTION",{httpProxy:na(t),httpsProxy:na(e),allProxy:na(r),socksProxy:na(n),noProxy:o||"NOT_SET",allProxyRelatedEnvVars:s,message:"Enhanced proxy environment detection \u2014 credentials redacted"})}return!e&&!t&&!r&&!n?(h.debug("[Proxy Fetch] No proxy environment variables found - using standard fetch"),k7r()):(h.debug("[Proxy Fetch] Configuring enhanced proxy with multiple protocol support"),h.debug(`[Proxy Fetch] HTTP_PROXY: ${na(t)}`),h.debug(`[Proxy Fetch] HTTPS_PROXY: ${na(e)}`),h.debug(`[Proxy Fetch] ALL_PROXY: ${na(r)}`),h.debug(`[Proxy Fetch] SOCKS_PROXY: ${na(n)}`),h.debug(`[Proxy Fetch] NO_PROXY: ${o||"not set"}`),A7r(i))}function hg(e){if(!e)return null;try{const t=new URL(e);return(t.username||t.password)&&(t.username="***",t.password="***"),t.toString()}catch{return"[invalid-url]"}}function MIt(){const e=process.env.HTTPS_PROXY||process.env.https_proxy,t=process.env.HTTP_PROXY||process.env.http_proxy,r=process.env.ALL_PROXY||process.env.all_proxy,n=process.env.SOCKS_PROXY||process.env.socks_proxy,o=process.env.NO_PROXY||process.env.no_proxy;return{enabled:!!(e||t||r||n),httpProxy:hg(t),httpsProxy:hg(e),allProxy:hg(r),socksProxy:hg(n),noProxy:o||null,method:"enhanced-proxy-agent",capabilities:["HTTP/HTTPS Proxy","SOCKS4/SOCKS5 Proxy","Proxy Authentication","NO_PROXY Bypass","CIDR Range Matching","Wildcard Domain Matching"]}}function PY(){return MIt().enabled?{fetch:Ot()}:{}}var OIt,DIt,Ln=E({"src/lib/proxy/proxyFetch.ts"(){"use strict";z(),Qt(),Sr(),v7r(),Jr(),jbe(),OIt=Be.http,DIt=new Set(["authorization","x-api-key","api-key","x-goog-api-key","proxy-authorization","cookie","set-cookie"])}});function C7r(e,t,r){const n=e[Symbol.asyncIterator]();return new ReadableStream({async pull(o){try{const i=await n.next();i.done?(o.enqueue(await t),o.close()):o.enqueue({type:"text-delta",delta:i.value.content})}catch(i){o.error(i)}},async cancel(){r(),await n.return?.()}})}async function*I7r(e,t,r){const n=e.getReader();let o=!1,i=!1;try{for(;;){const s=await n.read();if(s.done){o=!0;return}const a=s.value;if(a.type==="text-delta")yield{content:a.delta};else if(a.type==="finish")i=!0,t(a);else if(a.type==="error")throw a.error}}finally{try{o||await n.cancel()}finally{n.releaseLock(),i||r?.()}}}function NIt(e,t){const r=e.systemInstruction;return[...typeof r=="string"&&r.length>0?[{role:"system",content:r}]:[],...e7r(t)]}async function Yv(e,t){const n=(await Promise.resolve().then(()=>(KE(),zy))).GoogleGenAI;if(!n)throw new De({code:He.INVALID_CONFIGURATION,message:"@google/genai does not export GoogleGenAI",category:"configuration",severity:"critical",retriable:!1,context:{module:"@google/genai",expectedExport:"GoogleGenAI"}});const o=n;return new o({apiKey:e,httpOptions:{...t?{baseUrl:t}:{},...PY()}})}function LIt(e,t,r){const n=wIt({contents:e,availableInputTokens:ql("googleAiStudio",t),provider:"googleAiStudio",...r?{observedPromptTokens:r}:{}});if(!n)return!1;const o=new Set(n.drop),i=new Set(n.truncate),s=[];for(let a=0;a<e.length;a++){if(o.has(a))continue;const l=e[a];if(i.has(a)&&Array.isArray(l.parts)){s.push({...l,parts:l.parts.map(c=>{const u=c;if(!u.functionResponse)return c;const d=JSON.stringify(u.functionResponse.response)??"";return d.length<=2048?c:{functionResponse:{name:u.functionResponse.name,response:{result:SY(d)}}}})});continue}s.push(l)}if(o.size>0){let a=s.findIndex(l=>Array.isArray(l.parts)&&l.parts.some(c=>!!c.functionCall||!!c.functionResponse));a<0&&(a=Math.min(1,s.length)),s.splice(a,0,{role:"user",parts:[{text:xY}]})}return e.length=0,e.push(...s),!0}var FIt,R7r=E({"src/lib/providers/googleAiStudio/client.ts"(){"use strict";pl(),Zo(),R2(),il(),pt(),et(),z(),pY(),mIt(),RO(),Zo(),EY(),bIt(),$c(),Ys(),dg(),di(),zl(),vm(),_It(),Jv(),CY(),Ln(),FIt=class extends Ma{credentials;constructor(e,t,r){super(e,"google-ai",t),this.credentials=r,h.debug("GoogleAIStudioProvider initialized",{model:this.modelName,provider:this.providerName,sdkProvided:!!t})}getProviderName(){return"google-ai"}getDefaultModel(){return process.env.GOOGLE_AI_MODEL||"gemini-2.5-flash"}getAISDKModel(){throw new De({code:He.INVALID_CONFIGURATION,message:"GoogleAIStudioProvider no longer uses @ai-sdk/google. All models use native @google/genai SDK.",category:"configuration",severity:"critical",retriable:!1,context:{provider:this.providerName,model:this.modelName}})}formatProviderError(e){if(e instanceof Ta)return new ai(e.message,this.providerName);const t=e,r=typeof t?.message=="string"?t.message:"Unknown error",n=typeof t?.status=="number"?t.status:typeof t?.statusCode=="number"?t.statusCode:void 0;return r.includes("API_KEY_INVALID")||r.includes("Invalid API key")||n===401?new Wr("Invalid Google AI API key. Please check your GOOGLE_AI_API_KEY environment variable.",this.providerName):r.includes("RATE_LIMIT_EXCEEDED")||r.includes("rate limit")||r.includes("429")||n===429?new Qi("Google AI rate limit exceeded. Please try again later.",this.providerName):n===404||n===void 0&&(r.includes("model not found")||r.includes("Model not found"))?new Jo(`Model '${this.modelName}' not found. Please check the model name and ensure it is available.`,this.providerName):r.includes("ECONNRESET")||r.includes("ENOTFOUND")||r.includes("ETIMEDOUT")||r.includes("ECONNREFUSED")||r.includes("network")||r.includes("connection")?new ai(`Connection error: ${r}`,this.providerName):r.includes("500")||r.includes("502")||r.includes("503")||r.includes("504")||r.includes("server error")||r.includes("Internal Server Error")||n&&n>=500&&n<600?new nt(`Google AI server error: ${r}. Please try again later.`,this.providerName):new nt(`Google AI error: ${r}`,this.providerName)}async executeImageGeneration(e){await Ck(e.input);const t=e.prompt||e.input?.text||"",r=e.model||this.modelName,n=Date.now(),o=this.getApiKey();h.info("\u{1F3A8} Starting Google AI Studio image generation",{model:r,prompt:t.substring(0,100),provider:this.providerName});let i;try{i=await Yv(o,this.getBaseURL())}catch{throw new Wr("Missing '@google/genai'. Install with: npm install @google/genai",this.providerName)}try{const s=await Promise.all((e.input?.images||[]).map(async d=>{if(typeof d=="object"&&"url"in d){const f=d.url;if(f.startsWith("http")){const v=await fetch(f);if(!v.ok)throw new Error(`Failed to fetch image from ${f}: ${v.status} ${v.statusText}`);const T=await v.arrayBuffer(),b=Buffer.from(T),S=this.detectImageType(b);return h.debug(`Downloaded and detected image MIME type: ${S}`),{inlineData:{mimeType:S,data:b.toString("base64")}}}const g=Buffer.from(f,"base64");return{inlineData:{mimeType:this.detectImageType(g),data:g.toString("base64")}}}if(typeof d=="string"&&d.startsWith("http")){const f=await fetch(d);if(!f.ok)throw new Error(`Failed to fetch image from ${d}: ${f.status} ${f.statusText}`);const g=await f.arrayBuffer(),y=Buffer.from(g),v=this.detectImageType(y);return h.debug(`Downloaded and detected image MIME type: ${v}`),{inlineData:{mimeType:v,data:y.toString("base64")}}}const p=Buffer.isBuffer(d)?d:typeof d=="string"?Buffer.from(d,"base64"):Buffer.from(""),m=this.detectImageType(p);return h.debug(`Detected image MIME type: ${m}`),{inlineData:{mimeType:m,data:p.toString("base64")}}})),a=[{role:"user",parts:[{text:t},...s]}],l={responseModalities:["IMAGE","TEXT"]};h.debug("Starting image generation request",{model:r,contentParts:a[0].parts.length,responseModalities:l.responseModalities});let c=null,u="";try{const d=await i.models.generateContentStream({model:r,contents:a,config:l});for await(const p of d){h.debug("Received chunk",{hasCandidate:!!p.candidates?.[0],hasContent:!!p.candidates?.[0]?.content,hasParts:!!p.candidates?.[0]?.content?.parts});const m=p.candidates?.[0];if(m?.content?.parts)for(const f of m.content.parts){if("inlineData"in f&&f.inlineData?.data){const g=f.inlineData.data;c=g;const y=f.inlineData.mimeType,v=y||"image/png";h.info("Image generation successful",{model:r,mimeType:v,dataLength:g.length,responseTime:Date.now()-n});const T={content:`Generated image using ${r} (${v})`,imageOutput:{base64:g,...y?{mimeType:y}:{}},provider:this.providerName,model:r,usage:{input:this.estimateTokenCount(t),output:0,total:this.estimateTokenCount(t)}};return await this.enhanceResult(T,e,n)}"text"in f&&f.text&&(u+=f.text,h.debug("Received text content",{text:f.text.substring(0,100)}))}}}catch(d){h.debug("Streaming failed, trying non-streaming approach",{error:d instanceof Error?d.message:String(d)})}if(!c){h.debug("Trying non-streaming approach");const p=(await i.models.generateContent({model:r,contents:a,config:l})).candidates?.[0];if(p?.content?.parts)for(const m of p.content.parts){if("inlineData"in m&&m.inlineData?.data){const f=m.inlineData.data;c=f;const g=m.inlineData.mimeType,y=g||"image/png";h.info("Image generation successful (non-streaming)",{model:r,mimeType:y,dataLength:f.length,responseTime:Date.now()-n});const v={content:`Generated image using ${r} (${y})`,imageOutput:{base64:f,...g?{mimeType:g}:{}},provider:this.providerName,model:r,usage:{input:this.estimateTokenCount(t),output:0,total:this.estimateTokenCount(t)}};return await this.enhanceResult(v,e,n)}"text"in m&&m.text&&(u+=m.text)}}throw h.warn("No image data found in response",{model:r,prompt:t.substring(0,100),hasTextContent:!!u,textContent:u.substring(0,200)}),new nt(u||`Image generation completed but no image data was returned. This may indicate an issue with the model "${r}" or the prompt: "${t}". Please try again or use a different model.`,this.providerName)}catch(s){throw h.error("Image generation failed",{error:s instanceof Error?s.message:String(s),model:r,prompt:t.substring(0,100)}),this.handleProviderError(s)}}detectImageType(e){return e.length>=8&&e[0]===137&&e[1]===80&&e[2]===78&&e[3]===71?"image/png":e.length>=3&&e[0]===255&&e[1]===216&&e[2]===255?"image/jpeg":e.length>=12&&e[0]===82&&e[1]===73&&e[2]===70&&e[3]===70&&e[8]===87&&e[9]===69&&e[10]===66&&e[11]===80?"image/webp":e.length>=6&&e[0]===71&&e[1]===73&&e[2]===70?"image/gif":"image/png"}estimateTokenCount(e){return Vt(e,"google-ai")}async preprocessNativeFileInput(e){if(e.input&&RJ(e.input),e.input?.files&&e.input.files.length>0)try{await PJ(e,100*1024*1024,this.providerName)}catch(t){h.warn(`[GoogleAIStudio] processUnifiedFilesArray threw, continuing without file content: ${t instanceof Error?t.message:String(t)}`)}await Ck(e.input)}async executeStream(e,t){const r=e.model||this.modelName;if(e.input?.audio)return await this.executeAudioStreamViaGeminiLive(e);await this.preprocessNativeFileInput(e);const n=!!(t||e.output?.format==="json"||e.schema),o=!e.disableTools&&this.supportsTools()&&!n,i=e.tools||{};let s={...e,tools:i};const a=e.output?.format==="json"||e.schema,l=_Y(this.providerName,r,!s.disableTools,Object.keys(s.tools??{}).length);return a&&l&&(h.warn("[GoogleAIStudio] Gemini does not support tools and JSON schema output simultaneously. Disabling tools for this request."),s={...s,disableTools:!0,tools:{}}),o&&!s.disableTools&&s.tools&&Object.keys(s.tools).length>0&&h.info("[GoogleAIStudio] Routing to native @google/genai SDK for tool calling",{model:r,totalToolCount:Object.keys(s.tools??{}).length}),this.executeNativeGemini3Stream(s)}async executeNativeGemini3Stream(e){const t=e.model||this.modelName;return U9e({name:"neurolink.provider.stream",tracer:Be.provider,attributes:{[Re.GEN_AI_SYSTEM]:"google-ai",[Re.GEN_AI_MODEL]:t,[Re.GEN_AI_OPERATION]:"stream",[Re.NL_PROVIDER]:this.providerName}},async r=>{const n=Date.now(),o=this.getTimeout(e),i=wa(o,this.providerName,"stream");{const s=this.getApiKey(),a=await Yv(s,this.getBaseURL());h.debug("[GoogleAIStudio] Using native @google/genai for Gemini 3",{model:t,hasTools:!!e.tools&&Object.keys(e.tools).length>0});const l=[];xO(l,e.conversationMessages);const c=await dIt(e.input,e.input.text,"[GoogleAIStudio:stream]",t);l.push({role:"user",parts:c});let u,d;if(e.tools&&Object.keys(e.tools).length>0&&!e.disableTools){const de=Xv(e.tools,"functionDeclarations");d=de,u=de.toolsConfig,h.debug("[GoogleAIStudio] Converted tools for native SDK",{toolCount:u[0].functionDeclarations.length,toolNames:u[0].functionDeclarations.map(oe=>oe.name)})}const p=!u&&(e.output?.format==="json"||!!e.schema),m=p&&e.schema?iIt(e.schema):void 0,f=tIt({...e,model:t,wantsJsonOutput:p,responseSchema:m},u),g=rIt(e.maxSteps),y=Cy(e.abortSignal,i?.controller.signal),v=new AbortController,T=()=>v.abort();y?.addEventListener("abort",T),y?.aborted&&v.abort();const b=Yh(e.toolTimeoutMs),S=jv({...e.turnTimeoutMs!==void 0?{turnTimeoutMs:e.turnTimeoutMs}:{},...e.stallTimeoutMs!==void 0?{stallTimeoutMs:e.stallTimeoutMs}:{},...e.wrapupTimeLeadMs!==void 0?{wrapupTimeLeadMs:e.wrapupTimeLeadMs}:{},onDeadline:de=>{h.warn(de==="timeout"?`[GoogleAIStudio] Native Gemini turn exceeded its ${e.turnTimeoutMs}ms time budget \u2014 aborting`:`[GoogleAIStudio] Native Gemini turn made no progress for ${e.stallTimeoutMs}ms \u2014 aborting`),v.abort()}}),k=v.signal,A=()=>S.timedOut||i?.controller.signal.aborted===!0,x=Kv(),P=[],C=[];let R,O;const U=new Promise((de,oe)=>{R=de,O=oe}),M={streamId:`native-${Date.now()}`,startTime:n,responseTime:0,totalToolExecutions:0},D=async(de,oe)=>{let ae="",ge=0,be=0,Ce=0,ye=0,Ne=0,xe=0,le=!1,Oe;const Ie=Hv(jd("googleAiStudio",t));try{const Ge=IO({providerLabel:"GoogleAIStudio",maxSteps:g,toolFailureBreaker:{maxRetries:Zh},liveTools:e.tools??{},toolGuards:{toolTimeoutMs:b,abortSignal:k,onProgress:()=>S.noteProgress()},...d?{declarations:d}:{},buildRequest:ce=>({model:t,contents:ce,config:oe}),sendStep:async(ce,I)=>{S.noteProgress();const H=ce;return a.models.generateContentStream({...H,config:{...H.config??{},abortSignal:I}})},noteUsage:(ce,I)=>{Ie.noteUsage(ce,I)},planReclaim:(ce,I)=>{if(I!==0&&!Ie.shouldStop())return;const H=[...ce];if(LIt(H,t,Ie.projectedNextPromptTokens))return Ie.resetAfterReclaim(),{conversation:H}}}),je={...Ge,buildStepRequest:(ce,I)=>(xe=I+1,S.noteProgress(),Ge.buildStepRequest(ce,I)),buildToolResultMessages:(ce,I,H,ve)=>{Ne=ve+1;for(const ue of I.toolCalls)r.addEvent("gen_ai.tool_call",{"tool.name":ue.name,"tool.step":Ne});ae=I.text||ae;for(const ue of I.toolCalls)P.push({toolName:ue.name,args:ue.args});for(const ue of H)C.push({name:ue.name,input:ue.args,output:ue.output});if(H.length>0){const ue=kO(I.raw.rawResponseParts);It(this.handleToolExecutionStorage(I.toolCalls.map((F,ne)=>({toolName:F.name,args:F.args,...ne===0&&ue?{thoughtSignature:ue}:{},stepIndex:Ne})),H.map(F=>({toolName:F.name,output:F.output,stepIndex:Ne})),e,new Date),Qh,"tool storage write timed out").catch(F=>{h.warn("[GoogleAIStudio] Failed to store native tool executions",{error:F instanceof Error?F.message:String(F)})})}const se=Ge.buildToolResultMessages(ce,I,H,ve);if(S.shouldNudgeWrapup()){const ue=se[se.length-1];ue&&Array.isArray(ue.parts)&&ue.parts.push({text:Vv(!1)})}try{const ue=se[se.length-1];Ie.noteAppendedChars(JSON.stringify(ue?.parts??[]).length)}catch{}return se}},_e=SO(d,e.tools,{toolTimeoutMs:b,abortSignal:k,onProgress:()=>S.noteProgress()}),{stream:Fe,resultPromise:Y}=tp(je,de,{tools:_e,abortSignal:k,toolTimeoutMs:b}),X=(async()=>{for await(const ce of Fe)S.noteProgress(),x.push(ce)})();let ke,W;try{ke=await Y}catch(ce){W=ce}if(await ug(X,"GoogleAIStudio"),W!==void 0)if(S.expired||e.abortSignal?.aborted)le=!0;else throw h.error("[GoogleAIStudio] Native SDK error",W),this.handleProviderError(W);ke&&(ge+=ke.usage.inputTokens,be+=ke.usage.outputTokens,Ce+=ke.usage.cacheReadTokens??0,ye+=ke.usage.reasoningTokens??0,Oe=ke.rawStopReason??Oe,ke.aborted&&(le=!0)),k.aborted&&(le=!0);const te=ke!==void 0&&(ke.toolCalls.length===0||ke.finishReason!=="tool-calls"),me=!le&&Ne>=g&&!te;if(me){const ce=nIt("[GoogleAIStudio]",Ne,g,"",ae);ce&&x.push({content:ce})}else le&&!te&&(h.warn(`[GoogleAIStudio] Tool call loop ended mid-turn (${A()?"turn time limit":S.stalled?"stall watchdog":"caller abort"}); returning an honest terminal message.`),x.push({content:fY({timedOut:A(),stalled:S.stalled,elapsedMs:S.elapsedMs(),wasAborted:le,...e.stallTimeoutMs!==void 0?{stallTimeoutMs:e.stallTimeoutMs}:{},maxSteps:g,toolCallCount:P.length})}));const Te=Date.now()-n,pe=ep({timedOut:A(),stalled:S.stalled,wasAborted:le,cappedWithoutAnswer:me,finishReason:mg(Oe)});pe!=="completed"&&this.emitTurnEvent({phase:pe,step:xe,maxSteps:g,toolCallCount:P.length,elapsedMs:S.elapsedMs()}),M.responseTime=Te,M.totalToolExecutions=P.length,M.stopReason=pe,M.stepsUsed=xe,Oe!==void 0&&(M.rawFinishReason=Oe),r.setAttribute(Re.GEN_AI_INPUT_TOKENS,ge),r.setAttribute(Re.GEN_AI_OUTPUT_TOKENS,be),r.setAttribute(Re.GEN_AI_FINISH_REASON,me?"max_steps":"stop");const ie=Math.max(0,ge-Ce);R({provider:this.providerName,model:t,tokenUsage:{input:ie,output:be+ye,total:ie+Ce+be+ye,...Ce>0?{cacheReadTokens:Ce}:{},...ye>0?{reasoning:ye}:{}},requestDuration:Te,timestamp:new Date().toISOString(),stepsUsed:xe,toolCallCount:P.length,stopReason:pe,elapsedMs:S.elapsedMs(),...Oe!==void 0?{rawFinishReason:Oe}:{}}),x.close()}catch(Ge){x.error(Ge),O(Ge)}finally{S.dispose(),y?.removeEventListener("abort",T),i?.cleanup()}};let $;const B={prompt:NIt(f,l),...typeof f.maxOutputTokens=="number"?{maxOutputTokens:f.maxOutputTokens}:{},...typeof f.temperature=="number"?{temperature:f.temperature}:{},...typeof f.topP=="number"?{topP:f.topP}:{},abortSignal:k},q={specificationVersion:"v3",provider:this.providerName,modelId:t,supportedUrls:{},doGenerate:()=>{throw new Error("GoogleAIStudio: doGenerate is not implemented on the native stream model \u2014 NeuroLink streams through executeStream/doStream for this provider.")},doStream:async de=>{const{contents:oe,systemText:ae}=uIt(de.prompt),ge={...f,...typeof de.temperature=="number"?{temperature:de.temperature}:{},...typeof de.maxOutputTokens=="number"?{maxOutputTokens:de.maxOutputTokens}:{},...typeof de.topP=="number"?{topP:de.topP}:{}};ae?ge.systemInstruction=ae:delete ge.systemInstruction,$=D(oe,ge),$.catch(()=>{});const be=U.then(Ce=>({type:"finish",finishReason:{unified:mg(M.rawFinishReason)},usage:{inputTokens:{total:Ce.tokenUsage.input},outputTokens:{total:Ce.tokenUsage.output}}}));return be.catch(()=>{}),{stream:C7r(x.iterable,be,()=>v.abort())}}};let L;try{const de=await this.applyMiddlewareToModel(q,e);if(typeof de=="string")throw new Error("GoogleAIStudio: native stream middleware resolved to a bare model id string, expected a LanguageModelV3 handle.");({stream:L}=await de.doStream(B))}catch(de){throw v.abort(),x.close(),S.dispose(),y?.removeEventListener("abort",T),i?.cleanup(),this.handleProviderError(de)}let j=!1;const G=de=>{if($||j)return;j=!0;const oe=Date.now()-n,ae=ep({timedOut:!1,stalled:!1,wasAborted:!de,cappedWithoutAnswer:!1,...de?{finishReason:de.finishReason.unified}:{}});M.responseTime=oe,M.stopReason=ae,M.stepsUsed=0,R({provider:this.providerName,model:t,tokenUsage:{input:de?.usage.inputTokens.total??0,output:de?.usage.outputTokens.total??0,total:(de?.usage.inputTokens.total??0)+(de?.usage.outputTokens.total??0)},requestDuration:oe,timestamp:new Date().toISOString(),stepsUsed:0,toolCallCount:0,stopReason:ae,elapsedMs:oe}),S.dispose(),y?.removeEventListener("abort",T),i?.cleanup()},K={stream:I7r(L,de=>G(de),()=>G()),provider:this.providerName,model:t,toolCalls:P,analytics:U,metadata:M};return Object.defineProperty(K,"toolsUsed",{enumerable:!0,configurable:!0,get:()=>P.map(de=>de.toolName)}),Object.defineProperty(K,"toolExecutions",{enumerable:!0,configurable:!0,get:()=>Bd(C)}),K}},r=>r.stream,(r,n)=>({...r,stream:n}))}async executeNativeGemini3Generate(e){const t=e.model||this.modelName;return rS({name:"neurolink.provider.generate",tracer:Be.provider,attributes:{[Re.GEN_AI_SYSTEM]:"google-ai",[Re.GEN_AI_MODEL]:t,[Re.GEN_AI_OPERATION]:"generate",[Re.NL_PROVIDER]:this.providerName}},async r=>{const n=Date.now(),o=this.getTimeout(e),i=wa(o,this.providerName,"generate");let s=()=>{};try{const a=this.getApiKey(),l=await Yv(a,this.getBaseURL());h.debug("[GoogleAIStudio] Using native @google/genai for Gemini 3 generate",{model:t,hasTools:!!e.tools&&Object.keys(e.tools).length>0});const c=e.input?.text||e.prompt||"",u=[];xO(u,e.conversationMessages);const d=await dIt(e.input,c,"[GoogleAIStudio:generate]",t);u.push({role:"user",parts:d});let p,m;const f=!e.disableTools,g=!!(e.output?.format==="json"||e.schema),y=_Y(this.providerName,t,f,Object.keys(e.tools||{}).length);if(g&&y&&h.warn("[GoogleAIStudio] Gemini does not support tools and JSON schema output simultaneously. Disabling tools for this request (generate())."),f&&!(g&&y)){const K=e.tools||{};if(Object.keys(K).length>0){const de=Xv(K,"functionDeclarations");m=de,p=de.toolsConfig,h.debug("[GoogleAIStudio] Converted tools for native SDK generate",{toolCount:p[0].functionDeclarations.length,toolNames:p[0].functionDeclarations.map(oe=>oe.name)})}}const v=!p&&g,T=v&&e.schema?iIt(e.schema):void 0,b=tIt({...e,model:t,wantsJsonOutput:v,responseSchema:T},p),S=Cy(e.abortSignal,i?.controller.signal),k=new AbortController,A=()=>k.abort();S?.addEventListener("abort",A),S?.aborted&&k.abort();const x=Yh(e.toolTimeoutMs),P=jv({...e.turnTimeoutMs!==void 0?{turnTimeoutMs:e.turnTimeoutMs}:{},...e.stallTimeoutMs!==void 0?{stallTimeoutMs:e.stallTimeoutMs}:{},...e.wrapupTimeLeadMs!==void 0?{wrapupTimeLeadMs:e.wrapupTimeLeadMs}:{},onDeadline:K=>{h.warn(K==="timeout"?`[GoogleAIStudio] Native Gemini generate turn exceeded its ${e.turnTimeoutMs}ms time budget \u2014 aborting`:`[GoogleAIStudio] Native Gemini generate turn made no progress for ${e.stallTimeoutMs}ms \u2014 aborting`),k.abort()}}),C=k.signal;s=()=>{P.dispose(),S?.removeEventListener("abort",A)};const R=()=>P.timedOut||i?.controller.signal.aborted===!0,O=rIt(e.maxSteps),U=async(K,de)=>{let oe="",ae="",ge=0,be=0,Ce=0,ye=0;const Ne=[],xe=[];let le=0,Oe=0,Ie=!1,Ge;const je=Hv(jd("googleAiStudio",t)),_e=IO({providerLabel:"GoogleAIStudio",maxSteps:O,toolFailureBreaker:{maxRetries:Zh},liveTools:e.tools??{},toolGuards:{toolTimeoutMs:x,abortSignal:C,onProgress:()=>P.noteProgress()},...m?{declarations:m}:{},buildRequest:H=>({model:t,contents:H,config:de}),sendStep:async(H,ve)=>{P.noteProgress();const se=H;return l.models.generateContentStream({...se,config:{...se.config??{},abortSignal:ve}})},noteUsage:(H,ve)=>{je.noteUsage(H,ve)},planReclaim:(H,ve)=>{if(ve!==0&&!je.shouldStop())return;const se=[...H];if(LIt(se,t,je.projectedNextPromptTokens))return je.resetAfterReclaim(),{conversation:se}}}),Fe={..._e,buildStepRequest:(H,ve)=>(Oe=ve+1,P.noteProgress(),_e.buildStepRequest(H,ve)),buildToolResultMessages:(H,ve,se,ue)=>{le=ue+1;for(const ne of ve.toolCalls)r.addEvent("gen_ai.tool_call",{"tool.name":ne.name,"tool.step":le}),Ne.push({toolName:ne.name,args:ne.args});ae=ve.text||ae;for(const ne of se)xe.push({name:ne.name,input:ne.args,output:ne.output});if(se.length>0){const ne=kO(ve.raw.rawResponseParts);It(this.handleToolExecutionStorage(ve.toolCalls.map((Q,Se)=>({toolName:Q.name,args:Q.args,...Se===0&&ne?{thoughtSignature:ne}:{},stepIndex:le})),se.map(Q=>({toolName:Q.name,output:Q.output,stepIndex:le})),e,new Date),Qh,"tool storage write timed out").catch(Q=>{h.warn("[GoogleAIStudio] Failed to store native tool executions",{error:Q instanceof Error?Q.message:String(Q)})})}const F=_e.buildToolResultMessages(H,ve,se,ue);if(P.shouldNudgeWrapup()){const ne=F[F.length-1];ne&&Array.isArray(ne.parts)&&ne.parts.push({text:Vv(!1)})}try{const ne=F[F.length-1];je.noteAppendedChars(JSON.stringify(ne?.parts??[]).length)}catch{}return F}},Y=SO(m,e.tools,{toolTimeoutMs:x,abortSignal:C,onProgress:()=>P.noteProgress()}),{stream:X,resultPromise:ke}=tp(Fe,K,{tools:Y,abortSignal:C,toolTimeoutMs:x}),W=(async()=>{for await(const H of X)P.noteProgress()})();let te,me;try{te=await ke}catch(H){me=H}if(await ug(W,"GoogleAIStudio"),me!==void 0)if(P.expired||e.abortSignal?.aborted)Ie=!0;else throw h.error("[GoogleAIStudio] Native SDK generate error",me),this.handleProviderError(me);te&&(ge+=te.usage.inputTokens,be+=te.usage.outputTokens,Ce+=te.usage.cacheReadTokens??0,ye+=te.usage.reasoningTokens??0,Ge=te.rawStopReason??Ge,oe=te.text,te.aborted&&(Ie=!0)),C.aborted&&(Ie=!0);const Te=!Ie&&le>=O&&!oe;Ie&&!oe?(h.warn(`[GoogleAIStudio] Generate tool call loop ended mid-turn (${R()?"turn time limit":P.stalled?"stall watchdog":"caller abort"}); returning gathered text or an honest terminal message.`),oe=ae||fY({timedOut:R(),stalled:P.stalled,elapsedMs:P.elapsedMs(),wasAborted:Ie,...e.stallTimeoutMs!==void 0?{stallTimeoutMs:e.stallTimeoutMs}:{},maxSteps:O,toolCallCount:Ne.length})):oe=nIt("[GoogleAIStudio]",le,O,oe,ae);const pe=Date.now()-n,ie=ep({timedOut:R(),stalled:P.stalled,wasAborted:Ie,cappedWithoutAnswer:Te,finishReason:mg(Ge)});ie!=="completed"&&this.emitTurnEvent({phase:ie,step:Oe,maxSteps:O,toolCallCount:Ne.length,elapsedMs:P.elapsedMs()}),r.setAttribute(Re.GEN_AI_INPUT_TOKENS,ge),r.setAttribute(Re.GEN_AI_OUTPUT_TOKENS,be),r.setAttribute(Re.GEN_AI_FINISH_REASON,le>=O?"max_steps":"stop");const ce=Math.max(0,ge-Ce);return{content:oe,provider:this.providerName,model:t,stopReason:ie,stepsUsed:Oe,...Ge!==void 0?{rawFinishReason:Ge}:{},usage:{input:ce,output:be+ye,total:ce+Ce+be+ye,...Ce>0?{cacheReadTokens:Ce}:{},...ye>0?{reasoning:ye}:{}},...ye>0&&{reasoningTokens:ye},responseTime:pe,toolsUsed:Ne.map(H=>H.toolName),toolExecutions:Df(e,xe),enhancedWithTools:Ne.length>0}};let M;const D={prompt:NIt(b,u),...typeof b.maxOutputTokens=="number"?{maxOutputTokens:b.maxOutputTokens}:{},...typeof b.temperature=="number"?{temperature:b.temperature}:{},...typeof b.topP=="number"?{topP:b.topP}:{},abortSignal:C},$={specificationVersion:"v3",provider:this.providerName,modelId:t,supportedUrls:{},doStream:()=>{throw new Error("GoogleAIStudio: doStream is not implemented on the native generate model \u2014 NeuroLink runs this provider's turn synchronously through doGenerate.")},doGenerate:async K=>{const{contents:de,systemText:oe}=uIt(K.prompt),ae={...b,...typeof K.temperature=="number"?{temperature:K.temperature}:{},...typeof K.maxOutputTokens=="number"?{maxOutputTokens:K.maxOutputTokens}:{},...typeof K.topP=="number"?{topP:K.topP}:{}};oe?ae.systemInstruction=oe:delete ae.systemInstruction;const ge=await U(de,ae);return M=ge,{content:ge.content?[{type:"text",text:ge.content}]:[],finishReason:{unified:mg(ge.rawFinishReason)},usage:{inputTokens:{total:ge.usage?.input??0},outputTokens:{total:ge.usage?.output??0}}}}};let B;try{const K=await this.applyMiddlewareToModel($,e);if(typeof K=="string")throw new Error("GoogleAIStudio: native generate middleware resolved to a bare model id string, expected a LanguageModelV3 handle.");B=await K.doGenerate(D)}catch(K){throw this.handleProviderError(K)}let q="";for(const K of B.content)K.type==="text"&&(q+=K.text);const L=M?.usage,j=B.usage.inputTokens.total??0,G=B.usage.outputTokens.total??0,J={...M??{provider:this.providerName,model:t,stopReason:ep({timedOut:!1,stalled:!1,wasAborted:!1,cappedWithoutAnswer:!1,finishReason:B.finishReason.unified}),stepsUsed:0,responseTime:Date.now()-n,toolsUsed:[],toolExecutions:[],enhancedWithTools:!1},content:q,usage:{...L,input:j,output:G,total:j+G+(L?.cacheReadTokens??0)}};return this.enhanceResult(J,e,n)}finally{s(),i?.cleanup()}})}async generate(e){const t=typeof e=="string"?{prompt:e}:e,r=t.model||this.modelName;if(mE.some(d=>r.toLowerCase().startsWith(d.toLowerCase())))return h.info("[GoogleAIStudio] Routing image generation model to executeImageGeneration",{model:r}),this.executeImageGeneration(t);if(t.tts?.enabled&&!t.tts?.useAiResponse)return h.info("[GoogleAIStudio] Routing TTS direct-synthesis to handleDirectTTSSynthesis",{model:r}),this.handleDirectTTSSynthesis(t,Date.now());await this.preprocessNativeFileInput(t);const o=t.disableTools?{}:await this.getToolsForStream(t);let i={...t,tools:o};const s=t.output?.format==="json"||t.schema,a=_Y(this.providerName,r,!i.disableTools,Object.keys(i.tools??{}).length);s&&a&&(h.warn("[GoogleAIStudio] Gemini does not support tools and JSON schema output simultaneously. Disabling tools for this request."),i={...i,disableTools:!0,tools:{}}),!i.disableTools&&i.tools&&Object.keys(i.tools).length>0&&h.info("[GoogleAIStudio] Routing generate to native @google/genai SDK for tool calling",{model:r,totalToolCount:Object.keys(i.tools??{}).length});const c=Date.now(),u=i.input?.text||i.prompt||"";try{let d=await mt({name:"neurolink.executeGeneration",tracer:Be.provider,attributes:{[Re.GEN_AI_SYSTEM]:this.providerName,[Re.GEN_AI_MODEL]:r,"neurolink.path":"native.google-genai"}},async()=>this.executeNativeGemini3Generate(i));return d=await this.synthesizeAIResponseIfNeeded(d,t),this.emitPipelineBGenerationEvent(r,d,c,!0,void 0,u),d}catch(d){throw this.emitPipelineBGenerationEvent(r,null,c,!1,d,u),d}}emitPipelineBGenerationEvent(e,t,r,n,o,i){const s=this.neurolink?.getEventEmitter();if(!s)return;const a=t?.usage&&typeof t.usage=="object"?t.usage:{input:0,output:0,total:0};t&&typeof t=="object"&&(t._generationEndEmitted=!0),!n&&o&&typeof o=="object"&&(o._generationEndEmitted=!0),s.emit("generation:end",{provider:this.providerName,responseTime:Date.now()-r,timestamp:Date.now(),prompt:i||"",result:{content:t?.content||"",usage:a,model:e,provider:this.providerName,finishReason:n?"stop":"error"},success:n,...o?{error:o instanceof Error?o.message:String(o)}:{}})}async executeAudioStreamViaGeminiLive(e){const t=Date.now(),r=this.getApiKey();let n;try{n=await Yv(r,this.getBaseURL())}catch{throw new Wr("Missing '@google/genai'. Install with: pnpm add @google/genai",this.providerName)}const o=this.modelName||process.env.GOOGLE_VOICE_AI_MODEL||"gemini-2.5-flash-preview-native-audio-dialog",i=[];let s=null,a=!1;const l=g=>{if(!a){if(g.type==="audio"&&s){const y=s;s=null,y({value:{type:"audio",audio:g.audio},done:!1});return}i.push(g)}};let c=!1,u=()=>{};const d=new Promise((g,y)=>{u=y}),p=n.live.connect({model:o,callbacks:{onopen:()=>{},onmessage:async g=>{try{const y=g?.serverContent?.modelTurn?.parts?.[0]?.inlineData;if(y?.data){const T={data:Buffer.from(String(y.data),"base64"),sampleRateHz:24e3,channels:1,encoding:"PCM16LE"};l({type:"audio",audio:T})}g?.serverContent?.interrupted}catch(y){l({type:"error",error:y})}},onerror:g=>{c||u(new Error("Gemini Live connection failed before setup completed")),l({type:"error",error:g})},onclose:g=>{c||u(new Error("Gemini Live connection closed before setup completed")),l({type:"end"})}},config:{responseModalities:["AUDIO"],speechConfig:{voiceConfig:{prebuiltVoiceConfig:{voiceName:"Orus"}}}}}),m=await Promise.race([p,d]);return c=!0,(async()=>{try{const g=e.input?.audio;if(!g){h.debug("[GeminiLive] No audio spec found on input; skipping upstream send");return}for await(const y of g.frames){if(!y||y.byteLength===0){try{m.sendInput?await m.sendInput({event:"flush"}):m.sendRealtimeInput&&await m.sendRealtimeInput({event:"flush"})}catch(b){h.debug("[GeminiLive] flush control failed (non-fatal)",{error:b instanceof Error?b.message:String(b)})}continue}const v=y.toString("base64"),T=`audio/pcm;rate=${g.sampleRateHz||16e3}`;await m.sendRealtimeInput?.({media:{data:v,mimeType:T}})}try{m.sendInput?await m.sendInput({event:"flush"}):m.sendRealtimeInput&&await m.sendRealtimeInput({event:"flush"})}catch(y){h.debug("[GeminiLive] final flush failed (non-fatal)",{error:y instanceof Error?y.message:String(y)})}}catch(g){l({type:"error",error:g})}})().catch(()=>{}),{stream:{[Symbol.asyncIterator](){return{async next(){if(i.length>0){const g=i.shift();if(!g)return{value:void 0,done:!0};if(g.type==="audio")return{value:{type:"audio",audio:g.audio},done:!1};if(g.type==="end")return a=!0,{value:void 0,done:!0};if(g.type==="error")throw a=!0,g.error instanceof Error?g.error:new Error(String(g.error))}return a?{value:void 0,done:!0}:await new Promise(g=>{s=g})}}}},provider:this.providerName,model:o,metadata:{startTime:t,streamId:`google-ai-audio-${Date.now()}`}}}getDefaultEmbeddingModel(){return process.env.GOOGLE_AI_EMBEDDING_MODEL||process.env.GOOGLE_EMBEDDING_MODEL||"gemini-embedding-001"}async embed(e,t){if(typeof e!="string"&&e.image)throw new nt(`${this.providerName} does not support image embeddings; provide text input`,this.providerName);const r=typeof e=="string"?e:e.text??"",n=t||this.getDefaultEmbeddingModel()||"gemini-embedding-001";h.debug("Generating embedding",{provider:this.providerName,model:n,textLength:r.length});try{const o=this.getApiKey(),a=(await(await Yv(o,this.getBaseURL())).models.embedContent({model:n,contents:[r]})).embeddings?.[0]?.values;if(!a||a.length===0)throw new nt("No embedding returned from Google AI",this.providerName);return h.debug("Embedding generated successfully",{provider:this.providerName,model:n,embeddingDimension:a.length}),a}catch(o){throw h.error("Embedding generation failed",{error:o instanceof Error?o.message:String(o),model:n,textLength:r.length}),this.handleProviderError(o)}}async embedMany(e,t){const r=t||this.getDefaultEmbeddingModel()||"gemini-embedding-001";h.debug("Generating batch embeddings",{provider:this.providerName,model:r,count:e.length});let n;try{const i=this.getApiKey(),s=await Yv(i,this.getBaseURL());if(n=[],r.includes("gemini-embedding-2"))for(let l=0;l<e.length;l+=8){const c=e.slice(l,l+8),u=await Promise.all(c.map(d=>s.models.embedContent({model:r,contents:[d]})));for(const d of u)n.push(d.embeddings?.[0]?.values)}else{const a=await s.models.embedContent({model:r,contents:e});n.push(...(a.embeddings||[]).map(l=>l.values))}if(n.length!==e.length)throw new Error(`Embedding response held ${n.length} vectors for ${e.length} texts`)}catch(i){throw h.error("Batch embedding generation failed",{error:i instanceof Error?i.message:String(i),model:r,count:e.length}),this.handleProviderError(i)}const o=n.map((i,s)=>{if(!i||i.length===0)throw h.error("Batch embedding returned no values",{model:r,index:s}),new nt(`Embedding for the text at index ${s} came back without values`,this.providerName);return i});return h.debug("Batch embeddings generated successfully",{provider:this.providerName,model:r,count:o.length,embeddingDimension:o[0]?.length}),o}getApiKey(){const e=this.credentials?.apiKey||process.env.GOOGLE_AI_API_KEY||process.env.GOOGLE_GENERATIVE_AI_API_KEY;if(!e)throw new Wr("GOOGLE_AI_API_KEY or GOOGLE_GENERATIVE_AI_API_KEY environment variable is not set",this.providerName);return e}getBaseURL(){const e=this.credentials?.baseURL?.trim()||process.env.GOOGLE_AI_BASE_URL?.trim();return e&&e.length>0?e:void 0}}}}),$It={};Z($It,{GoogleAIStudioProvider:()=>FIt});var P7r=E({"src/lib/providers/googleAiStudio/index.ts"(){"use strict";R7r()}});async function fg(e,t,r){const n=parseInt(e.headers.get("content-length")??"0",10);if(n>0&&n>t)throw new Error(`${r} download too large: ${n} bytes (max ${t})`);const o=c=>new Error(`${r} download exceeded size cap after fetch: ${c} bytes (max ${t})`),i=e.body;if(!i||typeof i.getReader!="function"){const c=Buffer.from(await e.arrayBuffer());if(c.length>t)throw o(c.length);return c}const s=i.getReader(),a=[];let l=0;for(;;){const{done:c,value:u}=await s.read();if(c)break;if(l+=u.byteLength,l>t)throw await s.cancel().catch(()=>{}),o(l);a.push(u)}return Buffer.concat(a,l)}var gg,yg,Nm,Oa=E({"src/lib/utils/sizeGuard.ts"(){"use strict";gg=256*1024*1024,yg=50*1024*1024,Nm=25*1024*1024}}),M7r,O7r,D7r,N7r,OO,UIt,MY,OY,L7r,F7r,$7r,U7r,B7r=E({"node-stub:node:dns/promises"(){M7r=globalThis.crypto,O7r=globalThis.ReadableStream||class{},D7r=globalThis.URL,N7r=globalThis.URLSearchParams,OO=e=>{try{return JSON.stringify(e,null,2)}catch{return String(e)}},OO.custom=Symbol.for("nodejs.util.inspect.custom"),OO.colors={},OO.styles={},UIt=globalThis.TextDecoder,MY=globalThis.TextEncoder,OY=(e,t)=>t?.(null,"127.0.0.1",4),L7r=globalThis.performance||{now:()=>Date.now()},F7r=globalThis.Buffer||class extends Uint8Array{static from(t,r){if(typeof t=="string"){const n=(r||"utf8").toLowerCase();if(n==="base64"){const o=atob(t),i=new Uint8Array(o.length);for(let s=0;s<o.length;s++)i[s]=o.charCodeAt(s);return i}if(n==="hex"){const o=new Uint8Array(t.length/2);for(let i=0;i<t.length;i+=2)o[i/2]=parseInt(t.substr(i,2),16);return o}return new MY().encode(t)}return new Uint8Array(t)}static alloc(t){return new Uint8Array(t)}static isBuffer(t){return t instanceof Uint8Array}static concat(t){const r=t.reduce((i,s)=>i+s.length,0),n=new Uint8Array(r);let o=0;for(const i of t)n.set(i,o),o+=i.length;return n}static byteLength(t,r){return r==="base64"?Math.ceil(t.length*3/4):new MY().encode(t).length}toString(t){const r=(t||"utf8").toLowerCase();if(r==="hex")return Array.from(new Uint8Array(this.buffer,this.byteOffset,this.byteLength)).map(n=>n.toString(16).padStart(2,"0")).join("");if(r==="base64"){let n="";for(let o=0;o<this.length;o++)n+=String.fromCharCode(this[o]);return btoa(n)}return new UIt().decode(this)}},$7r=globalThis.clearTimeout,U7r=globalThis.clearInterval}}),z7r,G7r,q7r,V7r,DO,BIt,DY,j7r,H7r,zIt,W7r,K7r,J7r=E({"node-stub:node:net"(){z7r=globalThis.crypto,G7r=globalThis.ReadableStream||class{},q7r=globalThis.URL,V7r=globalThis.URLSearchParams,DO=e=>{try{return JSON.stringify(e,null,2)}catch{return String(e)}},DO.custom=Symbol.for("nodejs.util.inspect.custom"),DO.colors={},DO.styles={},BIt=globalThis.TextDecoder,DY=globalThis.TextEncoder,j7r=globalThis.performance||{now:()=>Date.now()},H7r=globalThis.Buffer||class extends Uint8Array{static from(t,r){if(typeof t=="string"){const n=(r||"utf8").toLowerCase();if(n==="base64"){const o=atob(t),i=new Uint8Array(o.length);for(let s=0;s<o.length;s++)i[s]=o.charCodeAt(s);return i}if(n==="hex"){const o=new Uint8Array(t.length/2);for(let i=0;i<t.length;i+=2)o[i/2]=parseInt(t.substr(i,2),16);return o}return new DY().encode(t)}return new Uint8Array(t)}static alloc(t){return new Uint8Array(t)}static isBuffer(t){return t instanceof Uint8Array}static concat(t){const r=t.reduce((i,s)=>i+s.length,0),n=new Uint8Array(r);let o=0;for(const i of t)n.set(i,o),o+=i.length;return n}static byteLength(t,r){return r==="base64"?Math.ceil(t.length*3/4):new DY().encode(t).length}toString(t){const r=(t||"utf8").toLowerCase();if(r==="hex")return Array.from(new Uint8Array(this.buffer,this.byteOffset,this.byteLength)).map(n=>n.toString(16).padStart(2,"0")).join("");if(r==="base64"){let n="";for(let o=0;o<this.length;o++)n+=String.fromCharCode(this[o]);return btoa(n)}return new BIt().decode(this)}},zIt=()=>0,W7r=globalThis.clearTimeout,K7r=globalThis.clearInterval}});function X7r(e){return e.length===0?null:/^0x[0-9a-f]+$/i.test(e)?parseInt(e.slice(2),16):e.length>1&&e.startsWith("0")&&/^0[0-7]+$/.test(e)?parseInt(e.slice(1),8):/^\d+$/.test(e)?parseInt(e,10):null}function NO(e){if(e.length===0)return null;const t=e.split(".");if(t.length===4){const r=t.map(X7r);return r.some(n=>n===null||n<0||n>255)?null:r.join(".")}if(t.length===1){let r;if(/^0x[0-9a-f]+$/i.test(e))r=parseInt(e.slice(2),16);else if(/^\d+$/.test(e))r=parseInt(e,10);else return null;return Number.isNaN(r)||r<0||r>4294967295?null:[r>>>24&255,r>>>16&255,r>>>8&255,r&255].join(".")}return null}function GIt(e){if(zIt(e)!==6)return null;const t=e.match(/^::ffff:(\d+\.\d+\.\d+\.\d+)$/i);let r;if(t){const n=NO(t[1]);if(!n)return null;const o=n.split(".").map(a=>parseInt(a,10)),i=(o[0]<<8|o[1]).toString(16),s=(o[2]<<8|o[3]).toString(16);r=["0","0","0","0","0","ffff",i,s]}else{const[n,o=""]=e.split("::"),i=n?n.split(":"):[],s=o?o.split(":"):[],a=8-i.length-s.length;if(a<0)return null;r=[...i,...Array(a).fill("0"),...s]}return r.length!==8?null:r.map(n=>n.toLowerCase().padStart(4,"0")).join(":")}function qIt(e){const t=e.match(/^::ffff:(\d+\.\d+\.\d+\.\d+)$/i);if(t)return NO(t[1]);const r=e.match(/^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/i);if(r){const n=parseInt(r[1],16),o=parseInt(r[2],16);return Number.isNaN(n)||Number.isNaN(o)||n>65535||o>65535?null:[n>>8&255,n&255,o>>8&255,o&255].join(".")}return null}function VIt(e){const[t,r,n,o]=e.split(".").map(i=>parseInt(i,10));return(t<<24|r<<16|n<<8|o)>>>0}function Hk(e){const t=VIt(e);for(const[r,n]of WIt){const o=VIt(r),i=n===0?0:4294967295<<32-n>>>0;if((t&i)===(o&i))return!0}return!1}function jIt(e){return KIt.some(t=>t.length===39?e===t:e.startsWith(t))}function NY(e){return e.startsWith("[")&&e.endsWith("]")?e.slice(1,-1):e}function LY(e){const t=NO(e);if(t)return Hk(t)?`IPv4 ${e} \u2192 ${t} is in a blocked range`:null;if(e.includes(":")){const r=qIt(e);if(r)return Hk(r)?`IPv4-mapped IPv6 ${e} \u2192 ${r} is in a blocked range`:null;const n=GIt(e);return n?jIt(n)?`IPv6 ${e} is in a blocked range`:null:`IPv6 ${e} could not be parsed`}return"not-an-ip"}async function Wk(e){let t;try{t=new URL(e)}catch{throw new Error(`Invalid URL: "${e}"`)}if(t.protocol!=="https:")throw new Error(`Only HTTPS URLs are permitted; got "${t.protocol}//" in "${e}"`);const r=NY(t.hostname).toLowerCase(),n=LY(r);if(n!==null){if(n!=="not-an-ip")throw new Error(`URL "${e}" rejected: ${n}`);await HIt(e,r)}}async function HIt(e,t){const[r,n]=await Promise.allSettled([OY(t,{family:4,all:!0}),OY(t,{family:6,all:!0})]),o=[],i=[];let s=!1;if(r.status==="fulfilled"){s=!0;for(const a of r.value)o.push(a.address)}if(n.status==="fulfilled"){s=!0;for(const a of n.value)i.push(a.address)}if(!s){const a=r.status==="rejected"?r.reason instanceof Error?r.reason.message:String(r.reason):"ok",l=n.status==="rejected"?n.reason instanceof Error?n.reason.message:String(n.reason):"ok";throw new Error(`URL "${e}" rejected: hostname ${t} could not be resolved (A: ${a}; AAAA: ${l})`)}for(const a of o)if(Hk(a))throw new Error(`URL "${e}" rejected: hostname ${t} resolves to ${a} (IPv4 in blocked range)`);for(const a of i){const l=LY(a.toLowerCase());if(l&&l!=="not-an-ip")throw new Error(`URL "${e}" rejected: hostname ${t} resolves to ${a} (IPv6 ${l})`)}return{v4:o,v6:i}}function Y7r(e){let t;try{t=new URL(e)}catch{throw new Error(`Invalid URL: "${e}"`)}if(t.protocol!=="https:")throw new Error(`Only HTTPS URLs are permitted; got "${t.protocol}//" in "${e}"`);const r=NY(t.hostname).toLowerCase(),n=LY(r);if(n===null)return;if(n!=="not-an-ip")throw new Error(`URL "${e}" rejected: ${n}`);const o=r.endsWith(".")?r.slice(0,-1):r;if(!o.includes("."))throw new Error(`URL "${e}" rejected: "${o}" is a single-label host name`);if(JIt.some(i=>o===i||o.endsWith(`.${i}`)))throw new Error(`URL "${e}" rejected: "${o}" is an internal host name`)}async function Z7r(e){let t;try{t=new URL(e)}catch{throw new Error(`Invalid URL: "${e}"`)}if(t.protocol!=="https:")throw new Error(`Only HTTPS URLs are permitted; got "${t.protocol}//" in "${e}"`);const r=NY(t.hostname).toLowerCase(),n=NO(r);if(n){if(Hk(n))throw new Error(`URL "${e}" rejected: IPv4 ${r} \u2192 ${n} is in a blocked range`);return{url:e,ip:n,family:4,addresses:[{ip:n,family:4}]}}if(r.includes(":")){const l=qIt(r);if(l){if(Hk(l))throw new Error(`URL "${e}" rejected: IPv4-mapped IPv6 ${r} \u2192 ${l} is in a blocked range`);return{url:e,ip:l,family:4,addresses:[{ip:l,family:4}]}}const c=GIt(r);if(!c)throw new Error(`URL "${e}" rejected: IPv6 ${r} could not be parsed`);if(jIt(c))throw new Error(`URL "${e}" rejected: IPv6 ${r} is in a blocked range`);return{url:e,ip:r,family:6,addresses:[{ip:r,family:6}]}}const{v4:o,v6:i}=await HIt(e,r),s=[...o.map(l=>({ip:l,family:4})),...i.map(l=>({ip:l,family:6}))],a=s[0];if(!a)throw new Error(`URL "${e}" rejected: hostname ${r} resolved to an empty address set`);return{url:e,ip:a.ip,family:a.family,addresses:s}}var WIt,KIt,JIt,Kk=E({"src/lib/utils/ssrfGuard.ts"(){"use strict";B7r(),J7r(),WIt=[["0.0.0.0",8],["10.0.0.0",8],["100.64.0.0",10],["127.0.0.0",8],["169.254.0.0",16],["172.16.0.0",12],["192.0.0.0",24],["192.168.0.0",16],["198.18.0.0",15],["100.100.100.200",32],["224.0.0.0",4],["240.0.0.0",4]],KIt=["0000:0000:0000:0000:0000:0000:0000:0000","0000:0000:0000:0000:0000:0000:0000:0001","fc","fd","fe8","fe9","fea","feb"],JIt=["localhost","local","localdomain","internal","home.arpa"]}});async function Q7r(e,t){const{Agent:r}=await Promise.resolve().then(()=>(zd(),Uu)),n=t[0];if(!n)throw new Error(`safeFetch: no validated addresses to pin for "${e}"`);return new r({connect:{lookup:(o,i,s)=>{if(o.toLowerCase()!==e.toLowerCase()){s(new Error(`safeFetch: refusing to resolve "${o}" \u2014 expected "${e}"`),"",0);return}if(i?.all){s(null,t.map(a=>({address:a.ip,family:a.family})));return}s(null,n.ip,n.family)}}})}function eVr(e){if(typeof e!="object"||e===null)return!1;const t=e;return typeof t.arrayBuffer=="function"&&typeof t.headers=="object"&&t.headers!==null&&typeof t.headers.get=="function"}async function tVr(e,t,r){if(e.status>=300&&e.status<400)throw new Error(`safeDownload(${r.label}): refused to follow redirect ${e.status} \u2192 ${e.headers.get("location")??"<no-location>"} (for ${t})`);if(!e.ok)throw new Error(`safeDownload(${r.label}) failed: HTTP ${e.status} for ${t}`);if(!eVr(e))throw new Error(`safeDownload(${r.label}): response is missing headers.get()/arrayBuffer()`);return fg(e,r.maxBytes,r.label)}async function Lm(e,t){const{getProxyDispatcherForUrl:r}=await Promise.resolve().then(()=>(Ln(),SIt)),n=await r(e),{fetch:o}=await Promise.resolve().then(()=>(zd(),Uu));let i,s,a=!1;if(n)Y7r(e),i=e,s=n;else{const p=await Z7r(e);i=p.url;const m=new URL(i).hostname.replace(/^\[|\]$/g,"");s=await Q7r(m,p.addresses),a=!0}const l=new AbortController,c=setTimeout(()=>l.abort(),t.timeoutMs??XIt),u=t.signal?AbortSignal.any([t.signal,l.signal]):l.signal;let d;try{d=await o(i,{method:"GET",signal:u,redirect:"manual",dispatcher:s})}finally{clearTimeout(c),a&&s.close().catch(()=>{})}return tVr(d,e,t)}var XIt,Fm=E({"src/lib/utils/safeFetch.ts"(){"use strict";Oa(),Kk(),XIt=6e4}});function FY(e){}function $Y(e){if(typeof e=="function")throw new TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");const{onEvent:t=FY,onError:r=FY,onRetry:n=FY,onComment:o}=e,i=[];let s=!0,a,l="",c=0,u;function d(v){if(s&&(s=!1,v.charCodeAt(0)===239&&v.charCodeAt(1)===187&&v.charCodeAt(2)===191&&(v=v.slice(3))),i.length===0){const S=p(v);S!==""&&i.push(S);return}if(v.indexOf(`
|
|
1034
1034
|
`)===-1&&v.indexOf("\r")===-1){i.push(v);return}i.push(v);const T=i.join("");i.length=0;const b=p(T);b!==""&&i.push(b)}function p(v){let T=0;if(v.indexOf("\r")===-1){let b=v.indexOf(`
|
|
1035
1035
|
`,T);for(;b!==-1;){if(T===b){c>0&&t({id:a,event:u,data:l}),a=void 0,l="",c=0,u=void 0,T=b+1,b=v.indexOf(`
|
|
1036
1036
|
`,T);continue}const S=v.charCodeAt(T);if(YIt(v,T,S)){const k=v.charCodeAt(T+5)===$m?T+6:T+5,A=v.slice(k,b);if(c===0&&v.charCodeAt(b+1)===BY){t({id:a,event:u,data:A}),a=void 0,l="",u=void 0,T=b+2,b=v.indexOf(`
|
|
@@ -1050,7 +1050,7 @@ ${r}`:r;return e.map((s,a)=>a===n?{...s,content:i}:s)}}}),vg,cVr=E({"node_module
|
|
|
1050
1050
|
${r}
|
|
1051
1051
|
]`}function T(){let L=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1,j=arguments.length>1&&arguments[1]!==void 0?arguments[1]:-1,G=e[t]==="\\";if(G&&(t++,G=!0),GO(e[t])){const J=zRt(e[t])?zRt:GRt(e[t])?GRt:wZ(e[t])?wZ:BRt,K=t,de=r.length;let oe='"';for(t++;;){if(t>=e.length){const ae=C(t-1);return!L&&zO(e.charAt(ae))?(t=K,r=r.substring(0,de),T(!0)):(oe=Bc(oe,'"'),r+=oe,!0)}if(t===j)return oe=Bc(oe,'"'),r+=oe,!0;if(J(e[t])){const ae=t,ge=oe.length;if(oe+='"',t++,r+=oe,s(!1),L||t>=e.length||zO(e[t])||GO(e[t])||wg(e[t]))return b(),!0;const be=C(ae-1),Ce=e.charAt(be);if(Ce===",")return t=K,r=r.substring(0,de),T(!1,be);if(zO(Ce))return t=K,r=r.substring(0,de),T(!0);r=r.substring(0,de),t=ae+1,oe=`${oe.substring(0,ge)}\\${oe.substring(ge)}`}else if(L&&$Rt(e[t])){if(e[t-1]===":"&&EZ.test(e.substring(K+1,t+2)))for(;t<e.length&&SZ.test(e[t]);)oe+=e[t],t++;return oe=Bc(oe,'"'),r+=oe,b(),!0}else if(e[t]==="\\"){const ae=e.charAt(t+1);if(e4t[ae]!==void 0)oe+=e.slice(t,t+2),t+=2;else if(ae==="u"){let be=2;for(;be<6&&uVr(e[t+be]);)be++;be===6?(oe+=e.slice(t,t+6),t+=6):t+be>=e.length?t=e.length:q()}else ae===`
|
|
1052
1052
|
`?(oe+="\\n",t+=2):(oe+=ae,t+=2)}else{const ae=e.charAt(t);ae==='"'&&e[t-1]!=="\\"?(oe+=`\\${ae}`,t++):pVr(ae)?(oe+=QRt[ae],t++):(dVr(ae)||U(ae),oe+=ae,t++)}G&&m()}}return!1}function b(){let L=!1;for(s();e[t]==="+";){L=!0,t++,s(),r=tx(r,'"',!0);const j=r.length;T()?r=fVr(r,j,1):r=Bc(r,'"')}return L}function S(){const L=t;if(e[t]==="-"){if(t++,R())return O(L),!0;if(!wg(e[t]))return t=L,!1}for(;wg(e[t]);)t++;if(e[t]==="."){if(t++,R())return O(L),!0;if(!wg(e[t]))return t=L,!1;for(;wg(e[t]);)t++}if(e[t]==="e"||e[t]==="E"){if(t++,(e[t]==="-"||e[t]==="+")&&t++,R())return O(L),!0;if(!wg(e[t]))return t=L,!1;for(;wg(e[t]);)t++}if(!R())return t=L,!1;if(t>L){const j=e.slice(L,t),G=/^0\d/.test(j);return r+=G?`"${j}"`:j,!0}return!1}function k(){return A("true","true")||A("false","false")||A("null","null")||A("True","true")||A("False","false")||A("None","null")}function A(L,j){return e.slice(t,t+L.length)===L?(r+=j,t+=L.length,!0):!1}function x(L){const j=t;if(LRt(e[t])){for(;t<e.length&&FRt(e[t]);)t++;let G=t;for(;Tg(e,G);)G++;if(e[G]==="(")return t=G+1,i(),e[t]===")"&&(t++,e[t]===";"&&t++),!0}for(;t<e.length&&!$Rt(e[t])&&!GO(e[t])&&(!L||e[t]!==":");)t++;if(e[t-1]===":"&&EZ.test(e.substring(j,t+2)))for(;t<e.length&&SZ.test(e[t]);)t++;if(t>j){for(;Tg(e,t-1)&&t>0;)t--;const G=e.slice(j,t);return r+=G==="undefined"?"null":JSON.stringify(G),e[t]==='"'&&t++,!0}}function P(){if(e[t]==="/"){const L=t;for(t++;t<e.length&&(e[t]!=="/"||e[t-1]==="\\");)t++;return t++,r+=JSON.stringify(e.substring(L,t)),!0}}function C(L){let j=L;for(;j>0&&Tg(e,j);)j--;return j}function R(){return t>=e.length||zO(e[t])||Tg(e,t)}function O(L){r+=`${e.slice(L,t)}0`}function U(L){throw new vg(`Invalid character ${JSON.stringify(L)}`,t)}function M(){throw new vg(`Unexpected character ${JSON.stringify(e[t])}`,t)}function D(){throw new vg("Unexpected end of json string",e.length)}function $(){throw new vg("Object key expected",t)}function B(){throw new vg("Colon expected",t)}function q(){const L=e.slice(t,t+6);throw new vg(`Invalid unicode character "${L}"`,t)}}function wVr(e,t){return e[t]==="*"&&e[t+1]==="/"}var QRt,e4t,TVr=E({"node_modules/.pnpm/jsonrepair@3.14.0/node_modules/jsonrepair/lib/esm/regular/jsonrepair.js"(){cVr(),yVr(),QRt={"\b":"\\b","\f":"\\f","\n":"\\n","\r":"\\r"," ":"\\t"},e4t={'"':'"',"\\":"\\","/":"/",b:"\b",f:"\f",n:`
|
|
1053
|
-
`,r:"\r",t:" "}}}),bVr=E({"node_modules/.pnpm/jsonrepair@3.14.0/node_modules/jsonrepair/lib/esm/index.js"(){TVr()}});function t4t(e,t=0){for(let r=t;r<e.length;r++){const n=e[r];if(n!=="{"&&n!=="[")continue;const o=n==="{"?"}":"]";let i=0,s=!1,a=!1;for(let l=r;l<e.length;l++){const c=e[l];if(a){a=!1;continue}if(c==="\\"){a=!0;continue}if(c==='"'){s=!s;continue}if(!s){if(c===n)i++;else if(c===o&&(i--,i===0))return{span:e.substring(r,l+1),end:l+1}}}}return null}var _Vr=E({"src/lib/utils/json/extract.ts"(){"use strict"}});function r4t(e){return typeof e.safeParse=="function"}function qO(e,t){return!e||!r4t(e)?!0:e.safeParse(t).success}function n4t(e,t){try{const r=JSON.parse(e);return r===""?{kind:"empty"}:r==null?{kind:"nullish"}:qO(t,r)?{kind:"accepted",value:r}:{kind:"rejected",value:r}}catch{return{kind:"not-json"}}}function o4t(e){try{return{value:JSON.parse(e),repaired:!1}}catch{}try{const t=vVr(e),r=JSON.parse(t);return t!==e&&h.shouldLog("debug")&&h.debug("[coerceJsonToSchema] jsonrepair altered model output",{originalLength:e.length,repairedLength:t.length}),{value:r,repaired:t!==e}}catch{return}}function EVr(e){let t=e;for(let r=0;r<s4t&&t.length>1;r++){const n=Math.max(t.lastIndexOf(","),t.lastIndexOf("}"),t.lastIndexOf("]"));if(n<=0)break;t=t.slice(0,n);const o=o4t(t);if(o!==void 0&&o.value!==null&&typeof o.value=="object")return o.value}}function kZ(e,t=0){if(t>i4t)return{value:e,changed:!1};if(typeof e=="string"){const r=e.trim();if(r.startsWith("{")&&r.endsWith("}")||r.startsWith("[")&&r.endsWith("]"))try{const o=JSON.parse(r);if(o!==null&&typeof o=="object")return{value:o,changed:!0}}catch{}return{value:e,changed:!1}}if(Array.isArray(e)){let r=!1;const n=e.map(o=>{const i=kZ(o,t+1);return i.changed&&(r=!0),i.value});return{value:r?n:e,changed:r}}if(e!==null&&typeof e=="object"){let r=!1;const n={};for(const[o,i]of Object.entries(e)){const s=kZ(i,t+1);s.changed&&(r=!0),n[o]=s.value}return{value:r?n:e,changed:r}}return{value:e,changed:!1}}function xZ(e,t){if(typeof e!="string"||e.trim().length===0)return null;const r=[],n=[e.indexOf("{"),e.indexOf("[")].filter(v=>v>=0),o=n.length>0?Math.min(...n):-1;let i=!1,s=0;for(;;){const v=t4t(e,s);if(!v)break;const T=v.end-v.span.length;T===o&&(i=!0),r.push({text:v.span,truncated:!1,rootAligned:T===o}),s=v.end}const a=o>=0&&!i,l=Math.max(e.lastIndexOf("}"),e.lastIndexOf("]"));o>=0&&l>o&&r.push({text:e.slice(o,l+1),truncated:a,rootAligned:!0}),o>=0&&r.push({text:e.slice(o),truncated:!0,rootAligned:!0});const c=e.trim();if(c.length>1&&c.startsWith('"')&&c.endsWith('"'))try{const v=JSON.parse(c);if(typeof v=="string"){let T=0;for(;;){const b=t4t(v,T);if(!b)break;r.push({text:b.span,truncated:!1,rootAligned:!1}),T=b.end}}}catch{}const u=[...r.filter(v=>v.rootAligned),...r.filter(v=>!v.rootAligned)];let d;const p=[],m=!!(t&&r4t(t)),f=new Set;for(const v of u){if(f.has(v.text))continue;f.add(v.text);const T=o4t(v.text);if(T===void 0||T.value===null||typeof T.value!="object")continue;const b={value:T.value,repaired:T.repaired,truncated:v.truncated,rootAligned:v.rootAligned};if(d===void 0&&(d=b),!m)break;const S=t;if(S.safeParse(T.value).success)p.push(b);else{const k=kZ(T.value);k.changed&&k.value!==null&&typeof k.value=="object"&&S.safeParse(k.value).success?p.push({value:k.value,repaired:!0,truncated:v.truncated,rootAligned:v.rootAligned}):Array.isArray(T.value)&&T.value.length===1&&T.value[0]!==null&&typeof T.value[0]=="object"&&!Array.isArray(T.value[0])&&S.safeParse(T.value[0]).success&&p.push({value:T.value[0],repaired:!0,truncated:v.truncated,rootAligned:v.rootAligned})}}const g=p.length>0?p.reduce((v,T)=>JSON.stringify(T.value).length>JSON.stringify(v.value).length?T:v):void 0;let y=g??d;if(a&&g===void 0&&(y===void 0||!y.rootAligned)){const v=EVr(e.slice(o));v!==void 0?(h.debug("[coerceJsonToSchema] salvaged a partial truncated object",{textLength:e.length}),y={value:v,repaired:!0,truncated:!0,rootAligned:!0}):y!==void 0&&(y={...y,truncated:!0})}return y===void 0?null:{content:JSON.stringify(y.value),structuredData:y.value,repaired:y.repaired,truncated:y.truncated}}var i4t,s4t,a4t=E({"src/lib/utils/json/coerce.ts"(){"use strict";bVr(),z(),_Vr(),i4t=6,s4t=8}});function VO(e,t,r){return!r||!t||Object.keys(t).length===0?"none":e.toolChoice??"auto"}function SVr(e){if(typeof e=="string")return e;if(e&&typeof e=="object"){const t=e;if(t.type==="tool")return t.toolName?{type:"tool",toolName:t.toolName}:void 0;if(t.type)return t.type}}var l4t=E({"src/lib/utils/toolChoice.ts"(){"use strict"}});async function*kVr(e,t){const r=e.getReader();let n=!1;try{for(;;){const o=await r.read();if(o.done){n=!0;return}const i=o.value;if(i.type==="text-delta")yield{content:i.delta};else if(i.type==="reasoning-delta")yield{content:"",reasoning:i.delta};else if(i.type==="finish")t(i);else if(i.type==="error")throw i.error}}finally{try{n||await r.cancel()}finally{r.releaseLock()}}}var jO,AZ,rx,CZ,IZ,c4t,Kl,zc=E({"src/lib/providers/openaiChatCompletionsBase.ts"(){"use strict";Qt(),$c(),aVr(),di(),xRt(),ARt(),CRt(),pl(),Zo(),RRt(),Ln(),z(),Nt(),rm(),ZJ(),Ys(),MRt(),If(),vZ(),vm(),ss(),a4t(),l4t(),zl(),kd(),EY(),qS(),Um(),Jv(),jO=512,AZ=class extends Error{},rx=(e,t)=>{const r=xZ(e,t);return r!==null&&qO(t,r.structuredData)},CZ=(e,t)=>{const r=xZ(e,t);if(r!==null&&qO(t,r.structuredData))return r.structuredData;const n=n4t(e,t);return n.kind==="accepted"?n.value:void 0},IZ=e=>{switch(e){case"length":return"length";case"tool_calls":case"function_call":case"tool-calls":return"tool-calls";case"content_filter":case"content-filter":return"content-filter";default:return"stop"}},c4t=(e,t,r)=>{const n=e[Symbol.asyncIterator]();return new ReadableStream({async pull(o){try{const i=await n.next();i.done?(o.enqueue(await t),o.close()):i.value.reasoning?o.enqueue({type:"reasoning-delta",delta:i.value.reasoning}):o.enqueue({type:"text-delta",delta:i.value.content})}catch(i){o.error(i)}},async cancel(){r(),await n.return?.()}})},Kl=class extends Ma{config;resolvedModel;constructor(e,t,r,n){super(t,e,r),this.config=n}getFallbackModelName(){return"gpt-3.5-turbo"}getModelFallbacks(){return this.getFallbackModels()}refreshHandlersForModel(e){this.resolvedModel=e,super.refreshHandlersForModel(e)}getFallbackModels(){return[]}adjustBuildBodyOptions(e,t){return t}adjustResponseFormat(e,t){return e}suppressResponseFormatWithTools(){return!0}useStreamingWireForGenerate(){return!1}replayReasoningContent(){return!1}adjustRequestBody(e,t){return e}adjustBodyAfter400(e,t){}resolveWireMaxTokens(e,t,r,n){const o=hK(this.providerName,e);let i=t;o!==void 0&&(i===void 0||i>o)&&(i!==void 0&&h.debug(`${this.providerName}: clamping max_tokens ${i} to the advertised ${e} output ceiling ${o}`),i=o);const s=mK(this.providerName,e);if(s!==void 0){const a=XY(r,n,this.providerName),l=s-a-jO;if(l<=0)throw new Na(`Estimated input (${a} tokens) alone exceeds the ${this.providerName}/${e} context window advertised by the serving infrastructure (${s} tokens). Reduce the prompt/conversation size \u2014 no max_tokens value can make this request fit.`,{estimatedTokens:a,availableTokens:Math.max(0,s-jO),stagesUsed:[],breakdown:{}});i!==void 0&&i>l&&(h.warn(`${this.providerName}: max_tokens ${i} cannot fit the ${e} window (${s}) with ~${a} input tokens \u2014 re-fitting to ${l}`),i=l)}return i}correctBodyAfterContextOverflow(e,t){if(!pZ(t))return;const r=mZ(t)??mZ(t.responseBody);if(!r||r.budgetTokens<=0)return;pK(this.providerName,e.model,r.budgetTokens);const n=typeof e.max_tokens=="number"?e.max_tokens:r.requestedOutputTokens;if(n===void 0||r.actualTokens<=0)return;const o=r.budgetTokens-r.actualTokens-jO;if(!(o<=0||o>=n))return h.warn(`${this.providerName}: ${e.model} rejected the request as over-window \u2014 retrying once with max_tokens re-fit from the provider's own numbers`,{window:r.budgetTokens,inputTokens:r.actualTokens,previousMaxTokens:n,refitMaxTokens:o}),{...e,max_tokens:o}}onStreamStart(e){}shouldAutoDiscoverModel(){return!0}getChatCompletionsURL(e){return`${Da(this.config.baseURL)}/chat/completions`}getAuthHeaders(){return{Authorization:`Bearer ${this.config.apiKey}`}}async validateConfiguration(){return typeof this.config.apiKey=="string"&&this.config.apiKey.trim().length>0}async probeModelsEndpoint(e={}){try{const t=`${Da(this.config.baseURL)}/models`,n=await Ot()(t,{headers:{...e,"Content-Type":"application/json"},signal:AbortSignal.timeout(5e3)});return n.ok?!!(await n.json().catch(()=>null))?.data?.some(i=>typeof i?.id=="string"&&i.id.trim().length>0):!1}catch(t){return h.debug(`[${this.constructor.name}] probeModelsEndpoint failed`,{baseURL:Yo(this.config.baseURL),error:t instanceof Error?t.message:String(t)}),!1}}getConfiguration(){return{provider:this.providerName,model:this.modelName,defaultModel:this.getDefaultModel(),baseURL:this.config.baseURL}}async getAISDKModel(){const e=await this.resolveModelName();return this.buildDelegatingModel(e)}async resolveModelName(){if(this.resolvedModel)return this.resolvedModel;const e=this.modelName||this.getDefaultModel();if(e&&e.trim()!=="")return this.resolvedModel=e,this.modelName!==e&&this.refreshHandlersForModel(e),e;if(this.shouldAutoDiscoverModel()){try{const r=await this.getAvailableModels();if(r.length>0)return this.resolvedModel=r[0],this.refreshHandlersForModel(r[0]),h.info(`\u{1F50D} Auto-discovered model: ${r[0]} from ${r.length} available models`),r[0]}catch(r){h.warn("Model auto-discovery failed, using fallback:",r)}return this.getFallbackModelName()}const t=this.getFallbackModelName();return this.resolvedModel=t,this.refreshHandlersForModel(t),t}buildDelegatingModel(e){const t=this.getChatCompletionsURL(e),r=Ot(),n=this.getAuthHeaders.bind(this),o=this.providerName,i=this.adjustBuildBodyOptions.bind(this),s=this.adjustResponseFormat.bind(this),a=this.adjustRequestBody.bind(this),l=this.adjustBodyAfter400.bind(this),c=this.correctBodyAfterContextOverflow.bind(this),u=this.resolveWireMaxTokens.bind(this),d=this.suppressResponseFormatWithTools.bind(this),p=this.useStreamingWireForGenerate.bind(this),m=this.replayReasoningContent.bind(this),f=g=>this.getTimeout(g??{});return{specificationVersion:"v3",provider:o,modelId:e,supportedUrls:{},doGenerate:async g=>{const y=FO((g.tools??[]).filter(G=>G.type==="function").map(G=>G.name)),v=QY(g.prompt,y?.toWire,m()),T=Array.isArray(g.tools)&&g.tools.length>0,b=g.responseFormat&&!(T&&d())?s(nZ(g.responseFormat),e):void 0,S=hRt(g.tools,y?.toWire),k=u(e,g.maxOutputTokens,v,S),A=p(),x=oZ(a(iZ({modelId:e,messages:v,options:i(e,{maxTokens:k,temperature:g.temperature,topP:g.topP,presencePenalty:g.presencePenalty,frequencyPenalty:g.frequencyPenalty,seed:g.seed,stopSequences:g.stopSequences}),tools:S,...g.toolChoice?{toolChoice:fRt(g.toolChoice,y?.toWire)}:{},streaming:A,...b?{responseFormat:b}:{}}),e)),P=g.providerOptions?.neurolink?.timeoutMs,C=wa(typeof P=="number"?P:f(g),o,"generate"),{signal:R,dispose:O}=T4(g.abortSignal,C?.controller.signal);let U,M=A;try{let G=await r(t,{method:"POST",headers:{"Content-Type":"application/json",...n()},body:JSON.stringify(x),...R?{signal:R}:{}});if(!G.ok){const J=await Zk(t,x,G),K=J;let de=G.status===400?(()=>{const oe=c(x,K);return l(oe??x,K)??oe})():void 0;if(!de&&A&&G.status===400&&/stream/i.test(K.responseBody??"")){const{stream:oe,stream_options:ae,...ge}=x;de=ge,M=!1}if(!de)throw J;if(G=await r(t,{method:"POST",headers:{"Content-Type":"application/json",...n()},body:JSON.stringify(de),...R?{signal:R}:{}}),!G.ok)throw await Zk(t,de,G)}if(M){if(!G.body)throw new Error(`${o}: streaming generate response had no body`);const J=C?G.body.pipeThrough(new TransformStream({transform(de,oe){C.reset(),oe.enqueue(de)}})):G.body,K=await sZ(J,()=>{});U={...K.id?{id:K.id}:{},...K.model?{model:K.model}:{},choices:[{index:0,message:{role:"assistant",content:K.text.length>0?K.text:null,...K.reasoning?{reasoning:K.reasoning}:{},...K.toolCalls.size>0?{tool_calls:[...K.toolCalls.values()].map(de=>({id:de.id,type:"function",function:{name:de.name,arguments:de.argsBuffered}}))}:{}},finish_reason:K.finishReason??"stop"}],...K.usage?{usage:K.usage}:{}}}else U=await G.json()}finally{C?.cleanup(),O()}const D=U.choices?.[0],$=(typeof D?.message?.content=="string"?D.message.content:"")??"",B=[],q=D?.message?.reasoning_content||D?.message?.reasoning;typeof q=="string"&&q.length>0&&B.push({type:"reasoning",text:q}),$.length>0&&B.push({type:"text",text:$});for(const G of D?.message?.tool_calls??[])B.push({type:"tool-call",toolCallId:G.id,toolName:y?.fromWire.get(G.function.name)??G.function.name,input:G.function.arguments??""});const L=D?.finish_reason,j=IZ(L);return{content:B,finishReason:{unified:j,raw:L??"stop"},usage:{inputTokens:{total:U.usage?.prompt_tokens,noCache:U.usage?.prompt_tokens!==void 0&&U.usage?.prompt_tokens_details?.cached_tokens!==void 0?Math.max(0,U.usage.prompt_tokens-U.usage.prompt_tokens_details.cached_tokens):U.usage?.prompt_tokens,cacheRead:U.usage?.prompt_tokens!==void 0&&U.usage?.prompt_tokens_details?.cached_tokens!==void 0?Math.min(U.usage.prompt_tokens_details.cached_tokens,U.usage.prompt_tokens):U.usage?.prompt_tokens_details?.cached_tokens,cacheWrite:void 0},outputTokens:{total:U.usage?.completion_tokens,text:U.usage?.completion_tokens!==void 0&&U.usage?.completion_tokens_details?.reasoning_tokens!==void 0?Math.max(0,U.usage.completion_tokens-U.usage.completion_tokens_details.reasoning_tokens):U.usage?.completion_tokens,reasoning:U.usage?.completion_tokens_details?.reasoning_tokens}},warnings:[],request:{body:x},response:{...U.id?{id:U.id}:{},...U.model?{modelId:U.model}:{},headers:{},body:U}}},doStream:()=>{throw new Error(`${o}: doStream is not implemented on the delegating model. NeuroLink streams through executeStream, reached via NeuroLink.stream() \u2014 use that (the browser bundle exports the NeuroLink class) rather than calling doStream on a model handle.`)}}}async generate(e,t){await this.ensureModelLimits();const r=this.normalizeTextOptions(e);if($d(r,this.modelName)!=="text")return super.generate(r,t);this.validateOptions(r);const n=await this.getToolsForStream(r),o="disableInternalFallback"in r&&r.disableInternalFallback===!0;return this.runGenerateWithModelFallback(()=>this.withTurnTimeout({...r,tools:n},this.getDescriptorGenerateMs(),i=>this.executeNativeGenerate(i)),o,r)}async executeNativeGenerate(e){const t=Date.now(),r=await this.resolveModelName(),n=await this.getAISDKModelWithMiddleware(e);if(!ex(n))throw this.handleProviderError(new Error(`${this.providerName}: model handle exposes no doGenerate()`));const o=n.doGenerate.bind(n),i=!e.disableTools&&this.supportsTools(),s=i?e.tools||await this.getAllTools():{},a=i?Object.entries(s).map(([C,R])=>{const O=R;return{type:"function",name:C,description:O.description??"",inputSchema:O.inputSchema?qo(O.inputSchema):{type:"object",properties:{}}}}):void 0,l=!!a&&a.length>0,c=e.schema?qo(e.schema):void 0,u=c!==void 0&&l&&this.suppressResponseFormatWithTools(),d=c&&!u?{type:"json",schema:c}:void 0,p=await this.buildMessagesForStream(e),m=[],f=(C,R,O=!0)=>BO({doGenerate:o,...SRt({provider:this.providerName,availableInputTokens:ql(this.providerName,r,e.maxTokens??void 0),getFixedOverheadTokens:()=>Vt(xk({...O&&a?{tools:a}:{},responseFormat:R}),this.providerName)}),conversation:C,...O&&a?{tools:a}:{},toolsRecord:s,...O&&l&&e.toolChoice?{toolChoice:VO(e,s,!0)}:{},...typeof e.timeout=="number"?{providerOptions:{neurolink:{timeoutMs:e.timeout}}}:{},...R?{responseFormat:R}:{},maxSteps:e.maxSteps||ts,...e.maxTokens?{maxOutputTokens:e.maxTokens}:{},...e.temperature!==void 0?{temperature:e.temperature}:{},...e.abortSignal?{abortSignal:e.abortSignal}:{},...e.toolTimeoutMs!==void 0?{toolTimeoutMs:e.toolTimeoutMs}:{},runStep:U=>Py(U,dt.getActiveSpan()??void 0,`${this.providerName} generate`,void 0,e.abortSignal).catch(M=>{throw this.handleProviderError(M)})},m);let g=!1,y;try{y=await f(p,d)}catch(C){if(!(d!==void 0&&(c7r(C)||hIt(C)||u7r(C))))throw C;h.warn(`[${this.providerName}] provider rejected response_format \u2014 retrying with the schema in the system prompt`,{provider:this.providerName,model:r}),g=!0,y=await f(Qv(p,d.schema),void 0)}if(!g&&d!==void 0&&e.schema!==void 0&&!rx(y.text,e.schema)){h.warn(`[${this.providerName}] response_format did not yield a schema-valid object \u2014 retrying with the schema in the system prompt`,{provider:this.providerName,model:r});const C=y,R=await f(Qv(p,d.schema),void 0);y={...R,inputTokens:C.inputTokens+R.inputTokens,outputTokens:C.outputTokens+R.outputTokens,cacheReadTokens:(C.cacheReadTokens??0)+(R.cacheReadTokens??0),cacheWriteTokens:(C.cacheWriteTokens??0)+(R.cacheWriteTokens??0)}}u&&c&&e.schema&&(y=await this.reformatWithoutTools({toolPhase:y,conversation:p,schemaJson:c,schema:e.schema,runLoop:f,modelId:r,abortSignal:e.abortSignal}));const{text:v,finishReason:T,toolsUsed:b}=y,S=y.inputTokens,k=y.outputTokens,A=y.steps,x=A>=(e.maxSteps||ts)&&T==="tool-calls"?"step-cap":T==="error"?"provider-error":"completed",P={content:v,provider:this.providerName,model:r,finishReason:T,...y.rawFinishReason?{rawFinishReason:y.rawFinishReason}:{},stopReason:x,stepsUsed:A,usage:{input:S,output:k,total:S+k+y.cacheReadTokens+y.cacheWriteTokens,...y.cacheReadTokens?{cacheReadTokens:y.cacheReadTokens}:{},...y.cacheWriteTokens?{cacheCreationTokens:y.cacheWriteTokens}:{}},responseTime:Date.now()-t,...y.reasoning?{reasoning:y.reasoning}:{},toolsUsed:b,toolCalls:HH(m),toolExecutions:Df(e,Bd(m)),enhancedWithTools:b.length>0};return this.finalizeNativeGenerate(P,e,t)}async reformatWithoutTools(e){const{toolPhase:t,conversation:r,schemaJson:n,schema:o,runLoop:i,modelId:s,abortSignal:a}=e;let l=t;const c=()=>a?.aborted===!0;if(l.text.trim().length>0&&!c()&&!rx(l.text,o)){h.warn(`[${this.providerName}] tools suppressed response_format and the answer is not schema-valid \u2014 re-asking once without tools`,{provider:this.providerName,model:s});const u={inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0},d=p=>{u.inputTokens+=p.inputTokens,u.outputTokens+=p.outputTokens,u.cacheReadTokens+=p.cacheReadTokens??0,u.cacheWriteTokens+=p.cacheWriteTokens??0};try{const p=[...r,{role:"assistant",content:t.text},{role:"user",content:"Return that same answer as a single JSON value conforming to the required schema. No prose before or after it, and no markdown code fence."}];let m,f=!1;try{m=await i(p,{type:"json",schema:n},!1),d(m)}catch(g){if(c())throw g;h.warn(`[${this.providerName}] the re-ask's response_format was rejected \u2014 retrying with the schema in the prompt`,{provider:this.providerName,model:s,error:g instanceof Error?g.message:String(g)}),m=await i(Qv(p,n),void 0,!1),d(m),f=!0}if(!f&&!c()&&!rx(m.text,o)&&(h.warn(`[${this.providerName}] the re-ask's response_format carried no schema \u2014 retrying with the schema in the prompt`,{provider:this.providerName,model:s}),m=await i(Qv(p,n),void 0,!1),d(m)),!rx(m.text,o))throw h.warn(`[${this.providerName}] the tool-free re-ask did not yield a schema-valid object either; keeping the original answer`,{provider:this.providerName,model:s}),new AZ;l={...m,toolsUsed:[...new Set([...t.toolsUsed,...m.toolsUsed])],inputTokens:t.inputTokens+u.inputTokens,outputTokens:t.outputTokens+u.outputTokens,cacheReadTokens:(t.cacheReadTokens??0)+u.cacheReadTokens,cacheWriteTokens:(t.cacheWriteTokens??0)+u.cacheWriteTokens,steps:t.steps,...t.finishReason!=="stop"?{finishReason:t.finishReason,rawFinishReason:t.rawFinishReason}:{finishReason:m.finishReason}}}catch(p){if(c()&&!(a?.reason instanceof Ta))throw p;p instanceof AZ||h.warn(`[${this.providerName}] the tool-free structured-output re-ask failed; keeping the original answer`,{provider:this.providerName,model:s,error:p instanceof Error?p.message:String(p)}),l={...l,inputTokens:l.inputTokens+u.inputTokens,outputTokens:l.outputTokens+u.outputTokens,cacheReadTokens:(l.cacheReadTokens??0)+u.cacheReadTokens,cacheWriteTokens:(l.cacheWriteTokens??0)+u.cacheWriteTokens}}}return l}async resolveStreamStructuredData(e){const{schema:t,schemaJson:r,text:n,conversation:o,modelId:i,abortSignal:s,options:a}=e,l=()=>s?.aborted===!0;if(n.trim().length===0)return;const c=CZ(n,t);if(c!==void 0)return{data:c,usage:{inputTokens:0,outputTokens:0}};if(!(!o||l()))try{const u=await this.getAISDKModelWithMiddleware(a);if(!ex(u))return;h.warn(`[${this.providerName}] streamed answer is not schema-valid \u2014 re-asking once without tools`,{provider:this.providerName,model:i});const d=u.doGenerate.bind(u),p={inputTokens:0,outputTokens:0},m=(T,b)=>BO({doGenerate:d,conversation:T,toolsRecord:{},...b?{responseFormat:b}:{},maxSteps:1,...a.maxTokens?{maxOutputTokens:a.maxTokens}:{},...s?{abortSignal:s}:{},runStep:S=>S()},[]).then(S=>(p.inputTokens+=S.inputTokens,p.outputTokens+=S.outputTokens,S)),g=[...o.filter(T=>{if(T.role==="tool")return!1;const b=T.tool_calls;return!(T.role==="assistant"&&Array.isArray(b)&&b.length>0)}),{role:"assistant",content:n},{role:"user",content:"Return that same answer as a single JSON value conforming to the required schema. No prose before or after it, and no markdown code fence."}];let y;try{y=await m(g,{type:"json",schema:r})}catch(T){if(l())throw T;h.warn(`[${this.providerName}] the stream re-ask's response_format was rejected \u2014 retrying with the schema in the prompt`,{provider:this.providerName,model:i,error:T instanceof Error?T.message:String(T)}),y=await m(Qv(g,r),void 0)}const v=CZ(y.text,t);return v===void 0?(h.warn(`[${this.providerName}] the tool-free stream re-ask did not yield a schema-valid value either; leaving structuredData unset`,{provider:this.providerName,model:i}),{data:void 0,usage:p}):{data:v,usage:p}}catch(u){if(l()&&!(s?.reason instanceof Ta))throw u;h.warn(`[${this.providerName}] the tool-free structured-output re-ask failed for a stream; leaving structuredData unset`,{provider:this.providerName,model:i,error:u instanceof Error?u.message:String(u)});return}}async executeStream(e,t){this.validateStreamOptions(e);const r=Date.now(),n=this.getTimeout(e),o=wa(n,this.providerName,"stream"),i=new AbortController,s=Mbe([e.abortSignal,o?.controller.signal,i.signal]).signal;let a,l,c,u,d,p;try{a=await this.resolveModelName();const ye=!e.disableTools&&this.supportsTools();l=ye?e.tools||await this.getAllTools():{},c=ye?FO(Object.keys(l)):void 0,u=ye?eZ(l,c?.toWire):void 0,d=wRt(VO(e,l,ye),c?.toWire),p=await this.buildMessagesForStream(e)}catch(ye){throw o?.cleanup(),ye}const m=e.schema?qo(e.schema):void 0,f=!!u&&u.length>0,g=m!==void 0&&f&&this.suppressResponseFormatWithTools(),y=m&&!g?this.adjustResponseFormat(nZ({type:"json",schema:m}),a):void 0,v=this.getChatCompletionsURL(a),T=Ot(),b=e.maxSteps||ts,S=this.neurolink?.getEventEmitter(),k=[],A=[],{usagePromise:x,finishPromise:P,resolveUsage:C,resolveFinish:R}=aZ(),O=Kv(),U=this.onStreamStart(a),M=u?.map(ye=>({type:"function",name:ye.function.name,description:ye.function.description,inputSchema:ye.function.parameters})),D={prompt:p,...M?{tools:M}:{},...e.maxTokens!==void 0?{maxOutputTokens:e.maxTokens}:{},...e.temperature!==void 0?{temperature:e.temperature}:{},...e.topP!==void 0?{topP:e.topP}:{}};let $,B,q;const L=this.providerName,j={specificationVersion:"v3",provider:L,modelId:a,supportedUrls:{},doGenerate:async ye=>{const Ne=await this.getAISDKModel();if(typeof Ne=="string")throw new Error("Native model handle required");return Ne.doGenerate(ye)},doStream:async ye=>{ye?.tools!==void 0&&ye.tools!==M&&h.warn(`${L}: middleware rewrote 'tools' on the streaming path; tool rewrites are not applied to the wire request yet \u2014 the original tool list was sent.`);const Ne=Array.isArray(ye?.prompt)?ye.prompt:p,xe=QY(Ne,c?.toWire,this.replayReasoningContent());B=xe;const le={...e,...typeof ye?.maxOutputTokens=="number"?{maxTokens:ye.maxOutputTokens}:{},...typeof ye?.temperature=="number"?{temperature:ye.temperature}:{},...typeof ye?.topP=="number"?{topP:ye.topP}:{}};$=this.runStreamLoop({maxSteps:b,modelId:a,url:v,fetchImpl:T,abortSignal:s,options:le,conversation:xe,openAITools:u,openAIToolChoice:d,toolsRecord:l,toolNameFromWire:c?.fromWire,emitter:S,toolsUsed:k,toolExecutionSummaries:A,pushChunk:O.push,closeChannel:O.close,resolveUsage:C,resolveFinish:R,responseFormat:y,onModelObserved:Ie=>{q=Ie}});const Oe=$.then(()=>Promise.all([x,P]).then(([Ie,Ge])=>({type:"finish",finishReason:{unified:Ge},usage:{inputTokens:{total:Ie.promptTokens,cacheRead:Ie.cacheReadTokens},outputTokens:{total:Ie.completionTokens}}})));return Oe.catch(()=>{}),{stream:c4t(O.iterable,Oe,()=>i.abort())}}};let G;try{const ye=await this.applyMiddlewareToModel(j,e);if(typeof ye=="string")throw new Error("Native stream model handle required");const{stream:Ne}=await ye.doStream(D);G=kVr(Ne,xe=>{if(!$){const le=xe.usage.inputTokens.total??0,Oe=xe.usage.outputTokens.total??0,Ie=Math.min(xe.usage.inputTokens.cacheRead??0,le);C({promptTokens:le-Ie,completionTokens:Oe,totalTokens:le+Oe,...Ie>0?{cacheReadTokens:Ie}:{}}),R(xe.finishReason.unified)}})}catch(ye){throw i.abort(),O.close(),o?.cleanup(),ye}let J;const K=ye=>{J=ye};U?.onUsage&&x.then(U.onUsage).catch(()=>{}),U?.onFinish&&P.then(ye=>U.onFinish?.(ye,J)).catch(()=>{});const de=this.providerName,oe=this,ae={startTime:r,streamId:`${this.providerName}-${Date.now()}`},ge=async function*(){let ye=0,Ne="";try{for await(const le of G)"content"in le&&typeof le.content=="string"&&le.content.length>0&&(ye++,e.schema&&(Ne+=le.content)),yield le;await $,$||R("stop");const xe=await P;if(ae.rawFinishReason=xe,e.schema&&m){const le=await oe.resolveStreamStructuredData({schema:e.schema,schemaJson:m,text:Ne,conversation:B,modelId:a,abortSignal:s,options:e});le?.data!==void 0&&(ae.structuredData=le.data),le&&(le.usage.inputTokens>0||le.usage.outputTokens>0)&&(ae.structuredDataUsage=le.usage,h.info(`[${de}] structured-output re-ask billed separately from the streamed turn`,{provider:de,model:a,inputTokens:le.usage.inputTokens,outputTokens:le.usage.outputTokens}))}if(ae.finishReason=IZ(xe),ye===0&&k.length===0){h.warn(`${de}: Stream produced no output \u2014 emitting enriched sentinel`);const le=new xu({message:"Stream produced no output"}),Oe=await ig(le,void 0,J);sg(Oe),yield Oe}}catch(xe){if(xu.isInstance(xe)){const Oe=await ig(xe,void 0,J);sg(Oe),yield Oe;return}const le=await ig(xe,void 0,J);throw sg(le),yield le,xe}finally{$||(C({promptTokens:0,completionTokens:0,totalTokens:0}),R("stop")),o?.cleanup(),i.signal.aborted||i.abort()}},be=Date.now()-r,Ce={stream:ge(),provider:this.providerName,model:a,analytics:P.then(()=>gZ.createAnalytics(this.providerName,q??a,{textStream:(async function*(){})(),usage:x,finishReason:P},be,{requestId:e.requestId??`${this.providerName}-stream-${Date.now()}`,streamingMode:!0})),toolsUsed:k,metadata:ae};return Object.defineProperty(Ce,"model",{enumerable:!0,configurable:!0,get:()=>q??a}),Object.defineProperty(Ce,"toolExecutions",{enumerable:!0,configurable:!0,get:()=>Bd(A.map(ye=>({toolName:ye.toolName,input:ye.input,output:ye.output,duration:ye.endTime.getTime()-ye.startTime.getTime()})))}),$?.finally(()=>o?.cleanup()).catch(ye=>{K(ye)}),Ce}async runStreamLoop(e){const{maxSteps:t,modelId:r,url:n,fetchImpl:o,abortSignal:i,options:s,conversation:a,openAITools:l,openAIToolChoice:c,toolsRecord:u,toolNameFromWire:d,emitter:p,toolsUsed:m,toolExecutionSummaries:f,pushChunk:g,closeChannel:y,resolveUsage:v,resolveFinish:T,responseFormat:b,onModelObserved:S}=e;let k=null,A;const x=()=>{const P=A?.prompt_tokens??0,C=A?.completion_tokens??0,R=Math.min(A?.prompt_tokens_details?.cached_tokens??0,P),O=Math.min(Math.max(0,A?.completion_tokens_details?.reasoning_tokens??0),C);return{promptTokens:P-R,completionTokens:C,totalTokens:A?.total_tokens||P+C,...R>0?{cacheReadTokens:R}:{},...O>0?{reasoningTokens:O}:{}}};try{let P=d,C,R;for(let O=0;O<t;O++){if(l){const D=new Set(l.map(B=>P?.get(B.function.name)??B.function.name)),$=Object.fromEntries(Object.entries(u).filter(([B])=>!D.has(B)));if(Object.keys($).length>0){const B=FO(Object.keys($),new Set(l.map(q=>q.function.name)));if(B){P??=new Map;for(const[q,L]of B.fromWire)P.set(q,L)}l.push(...eZ($,B?.toWire)??[]),h.info(`${this.providerName}: ${Object.keys($).length} tool(s) hydrated mid-turn via discovery: ${Object.keys($).join(", ")}`)}}const U=sVr({conversation:a,availableInputTokens:ql(this.providerName,r,s.maxTokens??void 0),fixedOverheadTokens:XY([],l,this.providerName),provider:this.providerName,observedPromptTokens:C,previousSentEstimate:R,onSentEstimate:D=>{R=D}});U&&(a.length=0,a.push(...U));const M=await this.streamOneStep({modelId:r,url:n,fetchImpl:o,abortSignal:i,options:s,conversation:a,openAITools:l,openAIToolChoice:c,pushChunk:g,responseFormat:b});if(C=M.usage?.prompt_tokens,k=M.finishReason,M.usage&&(A=_Rt(A,M.usage)),M.model&&S?.(M.model),M.toolCalls.size===0)break;await this.executeToolBatch({stepResult:M,conversation:a,toolsRecord:u,toolNameFromWire:P,emitter:p,toolsUsed:m,toolExecutionSummaries:f,options:s})}return v(x()),T(k??"stop"),y(),{finishReason:k??"stop",usage:A}}catch(P){throw h.error(`${this.providerName}: Stream error`,{error:P instanceof Error?P.message:String(P)}),v(x()),T("error"),y(),P}}async streamOneStep(e){const t=this.resolveWireMaxTokens(e.modelId,e.options.maxTokens??void 0,e.conversation,e.openAITools),r=t!==e.options.maxTokens?{...e.options,maxTokens:t}:e.options,n=oZ(this.adjustRequestBody(iZ({modelId:e.modelId,messages:e.conversation,options:this.adjustBuildBodyOptions(e.modelId,r),tools:e.openAITools,...e.openAIToolChoice!==void 0?{toolChoice:e.openAIToolChoice}:{},streaming:!0,...e.responseFormat?{responseFormat:e.responseFormat}:{}}),e.modelId)),o=async()=>{const s=await e.fetchImpl(e.url,{method:"POST",headers:{"Content-Type":"application/json",...this.getAuthHeaders()},body:JSON.stringify(n),...e.abortSignal?{signal:e.abortSignal}:{}});if(!s.ok)throw await Zk(e.url,n,s);return s};let i;try{i=await Py(o,dt.getActiveSpan()??void 0,`${this.providerName} stream`,void 0,e.abortSignal)}catch(s){const a=s,l=a.statusCode===400?(()=>{const c=this.correctBodyAfterContextOverflow(n,a);return this.adjustBodyAfter400(c??n,a)??c})():void 0;if(!l)throw a;if(i=await e.fetchImpl(e.url,{method:"POST",headers:{"Content-Type":"application/json",...this.getAuthHeaders()},body:JSON.stringify(l),...e.abortSignal?{signal:e.abortSignal}:{}}),!i.ok)throw await Zk(e.url,l,i)}if(!i.body)throw new Error(`${this.providerName}: stream response had no body`);return sZ(i.body,s=>{e.pushChunk({content:s})},s=>{e.pushChunk({content:"",reasoning:s})})}async executeToolBatch(e){const{stepResult:t,conversation:r,toolsRecord:n,toolNameFromWire:o,emitter:i,toolsUsed:s,toolExecutionSummaries:a,options:l}=e,c=[];for(const[,d]of t.toolCalls)c.push({id:d.id,type:"function",function:{name:d.name,arguments:d.argsBuffered}});r.push({role:"assistant",content:t.text.length>0?t.text:null,tool_calls:c,...this.replayReasoningContent()&&t.reasoning?{reasoning_content:t.reasoning}:{}});for(const[,d]of t.toolCalls){const p=new Date;let m;try{m=JSON.parse(d.argsBuffered||"{}")}catch{m=d.argsBuffered}let f,g;const y=o?.get(d.name)??d.name,v=n[y]??lW(n,y);if(i?.emit("tool:start",{toolName:y,toolCallId:d.id,input:m}),!v||typeof v.execute!="function")g=`Tool '${y}' is not registered.`,f={error:g};else try{f=await v.execute(m,{})}catch(b){g=b instanceof Error?b.message:String(b),f={error:g}}const T=new Date;s.push(y),a.push({toolCallId:d.id,toolName:y,input:m,output:f,...g?{error:g}:{},startTime:p,endTime:T}),r.push({role:"tool",tool_call_id:d.id,content:YY(f)})}const u=a.slice(-t.toolCalls.size);PRt(i,u.map(d=>({toolName:d.toolName,output:d.output,...d.error?{error:d.error}:{}})));try{await this.handleToolExecutionStorage(u.map(d=>({toolCallId:d.toolCallId,toolName:d.toolName,input:d.input,output:d.output})),u.map(d=>({toolCallId:d.toolCallId,toolName:d.toolName,output:d.output})),l,new Date)}catch(d){h.warn(`[${this.constructor.name}] Failed to store tool executions`,{provider:this.providerName,error:d instanceof Error?d.message:String(d)})}}async getAvailableModels(){try{const e=`${Da(this.config.baseURL)}/models`;h.debug(`Fetching available models from: ${e}`);const t=Ot(),r=new AbortController,n=setTimeout(()=>r.abort(),5e3),o=await t(e,{headers:{...this.getAuthHeaders(),"Content-Type":"application/json"},signal:r.signal});if(clearTimeout(n),!o.ok)return h.warn(`Models endpoint returned ${o.status}: ${o.statusText}`),this.getFallbackModels();const i=await o.json();if(!i.data||!Array.isArray(i.data))return h.warn("Invalid models response format"),this.getFallbackModels();const s=i.data.map(a=>a.id).filter(Boolean);return h.shouldLog("debug")&&h.debug(`Discovered ${s.length} models:`,s),s.length>0?s:this.getFallbackModels()}catch(e){return h.warn(`[${this.constructor.name}] Failed to fetch models from endpoint:`,e),this.getFallbackModels()}}async getFirstAvailableModel(){return(await this.getAvailableModels())[0]||this.getFallbackModelName()}}}}),RZ,u4t,d4t,p4t,m4t,h4t,xVr=E({"src/lib/providers/openAI/client.ts"(){"use strict";Qt(),Ln(),pt(),z(),Nt(),sl(),Zs(),Go(),Fm(),Oa(),Ys(),Um(),zc(),kd(),RZ="https://api.openai.com/v1",u4t=(e,t)=>{const r=[e,t].map(n=>n?.trim()).find(n=>!!n&&n.length>0)??RZ;try{const n=new URL(r),o=n.pathname&&n.pathname!=="/";if(n.hostname==="api.openai.com"&&!o)return n.pathname="/v1",Da(n.toString())}catch{}return r},d4t=()=>_a(B4r()),p4t=()=>Fi("OPENAI_MODEL","gpt-5.4"),m4t=dt.getTracer("neurolink.provider.openai"),h4t=class extends Kl{constructor(e,t,r,n){const o=n?.apiKey?.trim(),i=o&&o.length>0?o:d4t(),s=u4t(n?.baseURL,process.env.OPENAI_BASE_URL);super("openai",e,t,{baseURL:s,apiKey:i}),h.debug("OpenAIProvider initialized",{model:this.modelName,providerName:this.providerName,baseURL:Yo(this.config.baseURL)})}suppressResponseFormatWithTools(){return!1}getProviderName(){return"openai"}getDefaultModel(){return p4t()}formatProviderError(e){const t=e,r=t?.type&&typeof t.type=="string"?t.type:$be(t?.responseBody),n=[{match:o=>o.statusCode===401||r==="invalid_api_key"||/API_KEY_INVALID|Invalid API key|Incorrect API key|invalid_api_key/i.test(o.message),errorClass:Wr,message:o=>/Incorrect API key|Invalid API key/i.test(o.message)?o.message:"Invalid OpenAI API key. Please check your OPENAI_API_KEY environment variable."},{match:o=>Ube(o.error),errorClass:ot,message:"OpenAI quota exhausted \u2014 this will not resolve by retrying. Check your plan and billing details at https://platform.openai.com/account/billing"},{match:o=>o.statusCode===429||r==="rate_limit_error"||/rate limit/i.test(o.message),errorClass:Qi,message:"OpenAI rate limit exceeded. Please try again later."},{match:o=>/model_not_found/i.test(o.message),errorClass:Jo,message:o=>`Model not found: ${o.modelName}`},...Ll];return ba(e,n,this.providerName,this.modelName)}onStreamStart(e){const t=m4t.startSpan("neurolink.provider.streamText",{kind:nn.CLIENT,attributes:{"gen_ai.system":"openai","gen_ai.request.model":e}});let r=!1;const n=()=>{r||(r=!0,t.end())};return{onUsage:o=>{t.setAttribute("gen_ai.usage.input_tokens",o.promptTokens+(o.cacheReadTokens??0)+(o.cacheCreationTokens??0)),t.setAttribute("gen_ai.usage.output_tokens",o.completionTokens);const i=Ls(this.providerName,e,{input:o.promptTokens,output:o.completionTokens,total:o.totalTokens,...o.cacheReadTokens?{cacheReadTokens:o.cacheReadTokens}:{},...o.cacheCreationTokens?{cacheCreationTokens:o.cacheCreationTokens}:{}});i&&i>0&&t.setAttribute("neurolink.cost",i)},onFinish:(o,i)=>{t.setAttribute("gen_ai.response.finish_reason",o||"unknown"),o==="error"&&t.setStatus({code:Ue.ERROR,message:i instanceof Error?i.message:String(i??"stream error")}),n()}}}getDefaultEmbeddingModel(){return process.env.OPENAI_EMBEDDING_MODEL||"text-embedding-3-small"}async embed(e,t){if(typeof e!="string"&&e.image)throw new ot(`${this.providerName} does not support image embeddings; provide text input`,this.providerName);const r=typeof e=="string"?e:e.text??"",n=t||this.getDefaultEmbeddingModel();h.debug("Generating embedding",{provider:this.providerName,model:n,textLength:r.length});try{const[o]=await this.callEmbeddings(n,[r],"embed");return h.debug("Embedding generated successfully",{provider:this.providerName,model:n,embeddingDimension:o.length}),o}catch(o){throw h.error("Embedding generation failed",{error:o instanceof Error?o.message:String(o),model:n,textLength:r.length}),this.handleProviderError(o)}}async embedMany(e,t){const r=t||this.getDefaultEmbeddingModel();h.debug("Generating batch embeddings",{provider:this.providerName,model:r,count:e.length});try{const n=await this.callEmbeddings(r,e,"embedMany");return h.debug("Batch embeddings generated successfully",{provider:this.providerName,model:r,count:n.length,embeddingDimension:n[0]?.length}),n}catch(n){throw h.error("Batch embedding generation failed",{error:n instanceof Error?n.message:String(n),model:r,count:e.length}),this.handleProviderError(n)}}async callEmbeddings(e,t,r){const n=`${Da(this.config.baseURL)}/embeddings`,o=Ot(),i=wa(3e4,this.providerName,"generate");try{const s=await o(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`},body:JSON.stringify({model:e,input:t.length===1?t[0]:t}),...i?.controller.signal?{signal:i.controller.signal}:{}});if(!s.ok){const c=await s.text().catch(()=>"");let u=`OpenAI ${r} failed with status ${s.status}`,d;if(c)try{const p=JSON.parse(c);p.error?.message&&(u=p.error.message),d=p.error?.type}catch{}throw Object.assign(new Error(u),{status:s.status,type:d})}const l=((await s.json()).data??[]).map(c=>c.embedding).filter(c=>Array.isArray(c));if(l.length===0)throw new ot(`OpenAI ${r} returned no embeddings`,this.providerName);return l}finally{i?.cleanup()}}async executeImageGeneration(e){const t=Date.now(),r=e.prompt??e.input?.text??"";if(!r.trim())throw new Error("OpenAI image generation requires a prompt (input.text or prompt)");const n=e.model??this.modelName,o=Da(this.config.baseURL??RZ),i=e,s=i.size??this.aspectRatioToOpenAISize(i.aspectRatio,n),a=i.numberOfImages??1;let l;n==="gpt-image-1"||n.startsWith("dall-e-3")?l=1:n.startsWith("dall-e-2")?l=Math.min(Math.max(a,1),10):l=1;const u={model:n,prompt:r,n:l,size:s};n==="gpt-image-1"?i.quality&&(u.quality=i.quality):n.startsWith("dall-e-3")?(u.response_format="b64_json",i.quality&&(u.quality=i.quality),i.style&&(u.style=i.style)):u.response_format="b64_json";const d=12e4,p=new AbortController,m=setTimeout(()=>p.abort(),d);let f;try{f=await Ot()(`${o}/images/generations`,{method:"POST",headers:{Authorization:`Bearer ${this.config.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify(u),signal:p.signal})}catch(b){throw b instanceof Error&&b.name==="AbortError"?new Error(`OpenAI image generation timed out after ${d/1e3}s`,{cause:b}):b}finally{clearTimeout(m)}if(!f.ok){const b=await f.text();throw new Error(`OpenAI image generation failed: ${f.status} \u2014 ${b}`)}const y=(await f.json()).data?.[0];if(!y)throw new Error("OpenAI image generation returned no images");let v=y.b64_json;if(!v&&y.url&&(v=(await Lm(y.url,{maxBytes:Nm,label:"OpenAI image fallback",timeoutMs:6e4})).toString("base64")),!v)throw new Error("OpenAI image generation returned neither b64_json nor a URL");const T=Date.now()-t;return h.info(`[OpenAIProvider] Generated image (${v.length} base64 chars) in ${T}ms \u2014 model ${n}`),{content:y.revised_prompt??r,provider:this.providerName,model:n,usage:{input:0,output:0,total:0},imageOutput:{base64:v}}}aspectRatioToOpenAISize(e,t){return t==="gpt-image-1"?e==="16:9"||e==="3:2"?"1536x1024":e==="9:16"||e==="2:3"?"1024x1536":"1024x1024":t.startsWith("dall-e-3")?e==="16:9"||e==="3:2"?"1792x1024":e==="9:16"||e==="2:3"?"1024x1792":"1024x1024":"1024x1024"}}}}),f4t={};Z(f4t,{OpenAIProvider:()=>h4t});var AVr=E({"src/lib/providers/openAI/index.ts"(){"use strict";xVr()}});function $e(e,t,r,n,o){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!o)throw new TypeError("Private accessor was defined without a setter");if(typeof t=="function"?e!==t||!o:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?o.call(e,r):o?o.value=r:t.set(e,r),r}function V(e,t,r,n){if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof t=="function"?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?n:r==="a"?n.call(e):n?n.value:t.get(e)}var ml=E({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/tslib.mjs"(){}}),nx,PZ=E({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/utils/uuid.mjs"(){nx=function(){const{crypto:e}=globalThis;if(e?.randomUUID)return nx=e.randomUUID.bind(e),e.randomUUID();const t=new Uint8Array(1),r=e?()=>e.getRandomValues(t)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,n=>(+n^r()&15>>+n/4).toString(16))}}});function ew(e){return typeof e=="object"&&e!==null&&("name"in e&&e.name==="AbortError"||"message"in e&&String(e.message).includes("FetchRequestCanceledException"))}var ox,tw=E({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/errors.mjs"(){ox=e=>{if(e instanceof Error)return e;if(typeof e=="object"&&e!==null){try{if(Object.prototype.toString.call(e)==="[object Error]"){const t=new Error(e.message,e.cause?{cause:e.cause}:{});return e.stack&&(t.stack=e.stack),e.cause&&!t.cause&&(t.cause=e.cause),e.name&&(t.name=e.name),t}}catch{}try{return new Error(JSON.stringify(e))}catch{}}return new Error(e)}}}),lt,Bs,Jl,rw,MZ,g4t,OZ,DZ,NZ,LZ,FZ,$Z,UZ,BZ,$o=E({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/core/error.mjs"(){tw(),lt=class extends Error{},Bs=class _me extends lt{constructor(t,r,n,o,i){super(`${_me.makeMessage(t,r,n)}`),this.status=t,this.headers=o,this.requestID=o?.get("request-id"),this.error=r,this.type=i??null}static makeMessage(t,r,n){const o=r?.message?typeof r.message=="string"?r.message:JSON.stringify(r.message):r?JSON.stringify(r):n;return t&&o?`${t} ${o}`:t?`${t} status code (no body)`:o||"(no status code or body)"}static generate(t,r,n,o){if(!t||!o)return new rw({message:n,cause:ox(r)});const i=r,s=i?.error?.type;return t===400?new OZ(t,i,n,o,s):t===401?new DZ(t,i,n,o,s):t===403?new NZ(t,i,n,o,s):t===404?new LZ(t,i,n,o,s):t===409?new FZ(t,i,n,o,s):t===422?new $Z(t,i,n,o,s):t===429?new UZ(t,i,n,o,s):t>=500?new BZ(t,i,n,o,s):new _me(t,i,n,o,s)}},Jl=class extends Bs{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},rw=class extends Bs{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}},MZ=class extends rw{constructor({message:e}={}){super({message:e??"Request timed out."})}},g4t=class extends lt{constructor(e,{cause:t}={}){super(e??"Retryable error."),t!==void 0&&(this.cause=t)}},OZ=class extends Bs{},DZ=class extends Bs{},NZ=class extends Bs{},LZ=class extends Bs{},FZ=class extends Bs{},$Z=class extends Bs{},UZ=class extends Bs{},BZ=class extends Bs{}}});function zZ(e){return typeof e!="object"?{}:e??{}}function y4t(e){if(!e)return!0;for(const t in e)return!1;return!0}function CVr(e,t){return Object.prototype.hasOwnProperty.call(e,t)}var v4t,w4t,oa,GZ,T4t,qZ,op=E({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/utils/values.mjs"(){$o(),v4t=/^[a-z][a-z0-9+.-]*:/i,w4t=e=>v4t.test(e),oa=e=>(oa=Array.isArray,oa(e)),GZ=oa,T4t=(e,t)=>{if(typeof t!="number"||!Number.isInteger(t))throw new lt(`${e} must be an integer`);if(t<0)throw new lt(`${e} must be a positive integer`);return t},qZ=e=>{try{return JSON.parse(e)}catch{return}}}}),Bm,ix=E({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/utils/sleep.mjs"(){Bm=(e,t)=>new Promise(r=>{if(t?.aborted)return r();const n=()=>{clearTimeout(o),r()},o=setTimeout(()=>{t?.removeEventListener("abort",n),r()},e);t?.addEventListener("abort",n,{once:!0})})}}),ip,HO=E({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/version.mjs"(){ip="0.102.0"}});function IVr(){return typeof Deno<"u"&&Deno.build!=null?"deno":typeof EdgeRuntime<"u"?"edge":Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]"?"node":"unknown"}function RVr(){if(typeof navigator>"u"||!navigator)return null;const e=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(const{key:t,pattern:r}of e){const n=r.exec(navigator.userAgent);if(n){const o=n[1]||0,i=n[2]||0,s=n[3]||0;return{browser:t,version:`${o}.${i}.${s}`}}}return null}var b4t,_4t,VZ,jZ,E4t,WO,HZ=E({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/detect-platform.mjs"(){HO(),b4t=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u",_4t=()=>{const e=IVr();if(e==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ip,"X-Stainless-OS":jZ(Deno.build.os),"X-Stainless-Arch":VZ(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version=="string"?Deno.version:Deno.version?.deno??"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ip,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(e==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ip,"X-Stainless-OS":jZ(globalThis.process.platform??"unknown"),"X-Stainless-Arch":VZ(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};const t=RVr();return t?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ip,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${t.browser}`,"X-Stainless-Runtime-Version":t.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ip,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}},VZ=e=>e==="x32"?"x32":e==="x86_64"||e==="x64"?"x64":e==="arm"?"arm":e==="aarch64"||e==="arm64"?"arm64":e?`other:${e}`:"unknown",jZ=e=>(e=e.toLowerCase(),e.includes("ios")?"iOS":e==="android"?"Android":e==="darwin"?"MacOS":e==="win32"?"Windows":e==="freebsd"?"FreeBSD":e==="openbsd"?"OpenBSD":e==="linux"?"Linux":e?`Other:${e}`:"Unknown"),WO=()=>E4t??(E4t=_4t())}});function PVr(){if(typeof fetch<"u")return fetch;throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new Anthropic({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function S4t(...e){const t=globalThis.ReadableStream;if(typeof t>"u")throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new t(...e)}function k4t(e){let t=Symbol.asyncIterator in e?e[Symbol.asyncIterator]():e[Symbol.iterator]();return S4t({start(){},async pull(r){const{done:n,value:o}=await t.next();n?r.close():r.enqueue(o)},async cancel(){await t.return?.()}})}function WZ(e){if(e[Symbol.asyncIterator])return e;const t=e.getReader();return{async next(){try{const r=await t.read();return r?.done&&t.releaseLock(),r}catch(r){throw t.releaseLock(),r}},async return(){const r=t.cancel();return t.releaseLock(),await r,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function MVr(e){if(e===null||typeof e!="object")return;if(e[Symbol.asyncIterator]){await e[Symbol.asyncIterator]().return?.();return}const t=e.getReader(),r=t.cancel();t.releaseLock(),await r}var sx=E({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/shims.mjs"(){}}),x4t,OVr=E({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/request-options.mjs"(){x4t=({headers:e,body:t})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(t)})}}),KZ,JZ,XZ,A4t,C4t=E({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/qs/formats.mjs"(){KZ="RFC3986",JZ=e=>String(e),XZ={RFC1738:e=>String(e).replace(/%20/g,"+"),RFC3986:JZ},A4t="RFC1738"}});function DVr(e){return!e||typeof e!="object"?!1:!!(e.constructor&&e.constructor.isBuffer&&e.constructor.isBuffer(e))}function I4t(e,t){if(oa(e)){const r=[];for(let n=0;n<e.length;n+=1)r.push(t(e[n]));return r}return t(e)}var KO,Gc,JO,R4t,NVr=E({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/qs/utils.mjs"(){C4t(),op(),KO=(e,t)=>(KO=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),KO(e,t)),Gc=(()=>{const e=[];for(let t=0;t<256;++t)e.push("%"+((t<16?"0":"")+t.toString(16)).toUpperCase());return e})(),JO=1024,R4t=(e,t,r,n,o)=>{if(e.length===0)return e;let i=e;if(typeof e=="symbol"?i=Symbol.prototype.toString.call(e):typeof e!="string"&&(i=String(e)),r==="iso-8859-1")return escape(i).replace(/%u[0-9a-f]{4}/gi,function(a){return"%26%23"+parseInt(a.slice(2),16)+"%3B"});let s="";for(let a=0;a<i.length;a+=JO){const l=i.length>=JO?i.slice(a,a+JO):i,c=[];for(let u=0;u<l.length;++u){let d=l.charCodeAt(u);if(d===45||d===46||d===95||d===126||d>=48&&d<=57||d>=65&&d<=90||d>=97&&d<=122||o===A4t&&(d===40||d===41)){c[c.length]=l.charAt(u);continue}if(d<128){c[c.length]=Gc[d];continue}if(d<2048){c[c.length]=Gc[192|d>>6]+Gc[128|d&63];continue}if(d<55296||d>=57344){c[c.length]=Gc[224|d>>12]+Gc[128|d>>6&63]+Gc[128|d&63];continue}u+=1,d=65536+((d&1023)<<10|l.charCodeAt(u)&1023),c[c.length]=Gc[240|d>>18]+Gc[128|d>>12&63]+Gc[128|d>>6&63]+Gc[128|d&63]}s+=c.join("")}return s}}});function LVr(e){return typeof e=="string"||typeof e=="number"||typeof e=="boolean"||typeof e=="symbol"||typeof e=="bigint"}function P4t(e,t,r,n,o,i,s,a,l,c,u,d,p,m,f,g,y,v){let T=e,b=v,S=0,k=!1;for(;(b=b.get(XO))!==void 0&&!k;){const R=b.get(e);if(S+=1,typeof R<"u"){if(R===S)throw new RangeError("Cyclic object value");k=!0}typeof b.get(XO)>"u"&&(S=0)}if(typeof c=="function"?T=c(t,T):T instanceof Date?T=p?.(T):r==="comma"&&oa(T)&&(T=I4t(T,function(R){return R instanceof Date?p?.(R):R})),T===null){if(i)return l&&!g?l(t,ki.encoder,y,"key",m):t;T=""}if(LVr(T)||DVr(T)){if(l){const R=g?t:l(t,ki.encoder,y,"key",m);return[f?.(R)+"="+f?.(l(T,ki.encoder,y,"value",m))]}return[f?.(t)+"="+f?.(String(T))]}const A=[];if(typeof T>"u")return A;let x;if(r==="comma"&&oa(T))g&&l&&(T=I4t(T,l)),x=[{value:T.length>0?T.join(",")||null:void 0}];else if(oa(c))x=c;else{const R=Object.keys(T);x=u?R.sort(u):R}const P=a?String(t).replace(/\./g,"%2E"):String(t),C=n&&oa(T)&&T.length===1?P+"[]":P;if(o&&oa(T)&&T.length===0)return C+"[]";for(let R=0;R<x.length;++R){const O=x[R],U=typeof O=="object"&&typeof O.value<"u"?O.value:T[O];if(s&&U===null)continue;const M=d&&a?O.replace(/\./g,"%2E"):O,D=oa(T)?typeof r=="function"?r(C,M):C:C+(d?"."+M:"["+M+"]");v.set(e,S);const $=new WeakMap;$.set(XO,v),ZZ(A,P4t(U,D,r,n,o,i,s,a,r==="comma"&&g&&oa(T)?null:l,c,u,d,p,m,f,g,y,$))}return A}function FVr(e=ki){if(typeof e.allowEmptyArrays<"u"&&typeof e.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof e.encodeDotInKeys<"u"&&typeof e.encodeDotInKeys!="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(e.encoder!==null&&typeof e.encoder<"u"&&typeof e.encoder!="function")throw new TypeError("Encoder has to be a function.");const t=e.charset||ki.charset;if(typeof e.charset<"u"&&e.charset!=="utf-8"&&e.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let r=KZ;if(typeof e.format<"u"){if(!KO(XZ,e.format))throw new TypeError("Unknown format option provided.");r=e.format}const n=XZ[r];let o=ki.filter;(typeof e.filter=="function"||oa(e.filter))&&(o=e.filter);let i;if(e.arrayFormat&&e.arrayFormat in YZ?i=e.arrayFormat:"indices"in e?i=e.indices?"indices":"repeat":i=ki.arrayFormat,"commaRoundTrip"in e&&typeof e.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");const s=typeof e.allowDots>"u"?e.encodeDotInKeys?!0:ki.allowDots:!!e.allowDots;return{addQueryPrefix:typeof e.addQueryPrefix=="boolean"?e.addQueryPrefix:ki.addQueryPrefix,allowDots:s,allowEmptyArrays:typeof e.allowEmptyArrays=="boolean"?!!e.allowEmptyArrays:ki.allowEmptyArrays,arrayFormat:i,charset:t,charsetSentinel:typeof e.charsetSentinel=="boolean"?e.charsetSentinel:ki.charsetSentinel,commaRoundTrip:!!e.commaRoundTrip,delimiter:typeof e.delimiter>"u"?ki.delimiter:e.delimiter,encode:typeof e.encode=="boolean"?e.encode:ki.encode,encodeDotInKeys:typeof e.encodeDotInKeys=="boolean"?e.encodeDotInKeys:ki.encodeDotInKeys,encoder:typeof e.encoder=="function"?e.encoder:ki.encoder,encodeValuesOnly:typeof e.encodeValuesOnly=="boolean"?e.encodeValuesOnly:ki.encodeValuesOnly,filter:o,format:r,formatter:n,serializeDate:typeof e.serializeDate=="function"?e.serializeDate:ki.serializeDate,skipNulls:typeof e.skipNulls=="boolean"?e.skipNulls:ki.skipNulls,sort:typeof e.sort=="function"?e.sort:null,strictNullHandling:typeof e.strictNullHandling=="boolean"?e.strictNullHandling:ki.strictNullHandling}}function $Vr(e,t={}){let r=e;const n=FVr(t);let o,i;typeof n.filter=="function"?(i=n.filter,r=i("",r)):oa(n.filter)&&(i=n.filter,o=i);const s=[];if(typeof r!="object"||r===null)return"";const a=YZ[n.arrayFormat],l=a==="comma"&&n.commaRoundTrip;o||(o=Object.keys(r)),n.sort&&o.sort(n.sort);const c=new WeakMap;for(let p=0;p<o.length;++p){const m=o[p];n.skipNulls&&r[m]===null||ZZ(s,P4t(r[m],m,a,l,n.allowEmptyArrays,n.strictNullHandling,n.skipNulls,n.encodeDotInKeys,n.encode?n.encoder:null,n.filter,n.sort,n.allowDots,n.serializeDate,n.format,n.formatter,n.encodeValuesOnly,n.charset,c))}const u=s.join(n.delimiter);let d=n.addQueryPrefix===!0?"?":"";return n.charsetSentinel&&(n.charset==="iso-8859-1"?d+="utf8=%26%2310003%3B&":d+="utf8=%E2%9C%93&"),u.length>0?d+u:""}var YZ,ZZ,M4t,ki,XO,UVr=E({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/qs/stringify.mjs"(){NVr(),C4t(),op(),YZ={brackets(e){return String(e)+"[]"},comma:"comma",indices(e,t){return String(e)+"["+t+"]"},repeat(e){return String(e)}},ZZ=function(e,t){Array.prototype.push.apply(e,oa(t)?t:[t])},ki={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:R4t,encodeValuesOnly:!1,format:KZ,formatter:JZ,indices:!1,serializeDate(e){return(M4t??(M4t=Function.prototype.call.bind(Date.prototype.toISOString)))(e)},skipNulls:!1,strictNullHandling:!1},XO={}}});function BVr(e){return $Vr(e,{arrayFormat:"brackets"})}var O4t=E({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/utils/query.mjs"(){UVr()}});function D4t(e){if(!e)return;let t;try{t=new URL(e)}catch(n){throw new Xn(`Invalid token endpoint base URL "${e}": ${n}`)}if(t.protocol==="https:")return;const r=t.hostname.toLowerCase().replace(/^\[|\]$/g,"");if(!(t.protocol==="http:"&&(r==="localhost"||r==="127.0.0.1"||r==="::1")))throw new Xn(`Refusing to send credential over non-https token endpoint "${e}"`)}async function N4t(e,t){const r=await zVr(e);let n;try{n=JSON.parse(r)}catch{throw new Xn(`Token endpoint returned non-JSON response (status ${e.status})`,e.status,Xl(r),t)}if(!n.access_token)throw new Xn(`Token endpoint response missing access_token: ${JSON.stringify(Xl(n))}`,e.status,Xl(n),t);if(n.token_type&&n.token_type.toLowerCase()!=="bearer")throw new Xn(`Token endpoint response: unsupported token_type "${n.token_type}" (want Bearer)`,e.status,Xl(n),t);return n}function Xl(e){if(e==null)return e;if(typeof e=="string"){let t;try{t=JSON.parse(e)}catch{return e.length<=ZO?e:e.slice(0,ZO)+`... <${e.length-ZO} more chars>`}return JSON.stringify(Xl(t))}if(typeof e=="object"&&!Array.isArray(e)){const t={};for(const[r,n]of Object.entries(e))q4t.has(r)&&(t[r]=n);return t}return null}async function L4t(e,t=r=>console.warn(`anthropic-sdk: ${r}`)){if(typeof process>"u"||process.platform==="win32")return;const r=await Promise.resolve().then(()=>(Sn(),Id));let n=e,o;try{n=await r.promises.realpath(e),o=await r.promises.stat(n)}catch{return}const i=o.mode&511;if(i&18)throw new Xn(`Credentials file at ${n} is group/world-writable (mode 0o${i.toString(8)}); this allows other local users to plant tokens. Run \`chmod 600 ${n}\`.`);if(i&36)throw new Xn(`Credentials file at ${n} is group/world-readable (mode 0o${i.toString(8)}); run \`chmod 600 ${n}\` before retrying.`);typeof process.getuid=="function"&&o.uid!==process.getuid()&&t(`credentials file at ${n} is owned by uid ${o.uid} (current process uid ${process.getuid()}); verify this is intentional.`)}async function F4t(e,t){const r=await Promise.resolve().then(()=>(Sn(),Id)),o=(await Promise.resolve().then(()=>(qt(),um))).dirname(e);await r.promises.mkdir(o,{recursive:!0,mode:448});const i=`${e}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;try{const s=await r.promises.open(i,"w",384);try{await s.writeFile(JSON.stringify(t,null,2)),await s.sync()}finally{await s.close()}await r.promises.rename(i,e)}catch(s){throw await r.promises.unlink(i).catch(()=>{}),s}try{const s=await r.promises.open(o,"r");try{await s.sync()}finally{await s.close()}}catch{}}async function zVr(e){if(!e.body)return"";const t=e.body.getReader(),r=[];let n=0;for(;;){const{done:i,value:s}=await t.read();if(i)break;if(n+s.length>eQ){const a=eQ-n;a>0&&r.push(s.subarray(0,a)),await t.cancel();break}r.push(s),n+=s.length}let o;if(r.length===1)o=r[0];else{o=new Uint8Array(r.reduce((s,a)=>s+a.length,0));let i=0;for(const s of r)o.set(s,i),i+=s.length}return new TextDecoder("utf-8").decode(o)}var $4t,U4t,QZ,ax,B4t,z4t,YO,G4t,eQ,ZO,q4t,Xn,lx=E({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/lib/credentials/types.mjs"(){$o(),$4t="urn:ietf:params:oauth:grant-type:jwt-bearer",U4t="refresh_token",QZ="/v1/oauth/token",ax="oauth-2025-04-20",B4t="oidc-federation-2026-04-01",z4t=120,YO=30,G4t=5,eQ=1<<20,ZO=2e3,q4t=new Set(["error","error_description","error_uri"]),Xn=class extends lt{constructor(e,t=null,r=null,n=null){super(e),this.statusCode=t,this.body=r,this.requestId=n}}}});function bg(){return Math.floor(Date.now()/1e3)}var QO=E({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/utils/time.mjs"(){}}),V4t,GVr=E({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/lib/credentials/token-cache.mjs"(){lx(),QO(),V4t=class{constructor(e,t){this.cached=null,this.pendingRefresh=null,this.nextForce=!1,this.lastAdvisoryError=0,this.provider=e,this.onAdvisoryRefreshError=t}async getToken(){const e=this.nextForce;this.nextForce=!1;const t=this.cached;if(e||t==null)return(await this.refresh(e)).token;if(t.expiresAt==null)return t.token;const r=t.expiresAt-bg();return r>z4t?t.token:r>YO?(this.backgroundRefresh(),t.token):(await this.refresh()).token}invalidate(){this.cached=null,this.nextForce=!0}refresh(e=!1){return this.pendingRefresh&&!e?this.pendingRefresh:this.doRefresh(e)}backgroundRefresh(){this.pendingRefresh||bg()-this.lastAdvisoryError<G4t||this.doRefresh().catch(e=>{this.lastAdvisoryError=bg(),this.onAdvisoryRefreshError?.(e)})}doRefresh(e=!1){return this.pendingRefresh=this.provider(e?{forceRefresh:!0}:void 0).then(t=>(this.cached=t,this.pendingRefresh=null,t),t=>{throw this.pendingRefresh=null,t}),this.pendingRefresh}}}}),Fr,eD=E({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/utils/env.mjs"(){Fr=e=>{if(typeof globalThis.process<"u")return globalThis.process.env?.[e]?.trim()||void 0;if(typeof globalThis.Deno<"u")return globalThis.Deno.env?.get?.(e)?.trim()||void 0}}});function qVr(e){let t=0;for(const o of e)t+=o.length;const r=new Uint8Array(t);let n=0;for(const o of e)r.set(o,n),n+=o.length;return r}function tQ(e){let t;return(H4t??(t=new globalThis.TextEncoder,H4t=t.encode.bind(t)))(e)}function j4t(e){let t;return(W4t??(t=new globalThis.TextDecoder,W4t=t.decode.bind(t)))(e)}var H4t,W4t,rQ=E({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/utils/bytes.mjs"(){}}),VVr=E({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/utils/base64.mjs"(){$o(),rQ()}});function cx(){}function tD(e,t,r){return!t||ux[e]>ux[r]?cx:t[e].bind(t)}function Uo(e){const t=e.logger,r=e.logLevel??"off";if(!t)return K4t;const n=oQ.get(t);if(n&&n[0]===r)return n[1];const o={error:tD("error",t,r),warn:tD("warn",t,r),info:tD("info",t,r),debug:tD("debug",t,r)};return oQ.set(t,[r,o]),o}var ux,nQ,K4t,oQ,sp,zm=E({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/utils/log.mjs"(){op(),ux={off:0,error:200,warn:300,info:400,debug:500},nQ=(e,t,r)=>{if(e){if(CVr(ux,e))return e;Uo(r).warn(`${t} was set to ${JSON.stringify(e)}, expected one of ${JSON.stringify(Object.keys(ux))}`)}},K4t={error:cx,warn:cx,info:cx,debug:cx},oQ=new WeakMap,sp=e=>(e.options&&(e.options={...e.options},delete e.options.headers),e.headers&&(e.headers=Object.fromEntries((e.headers instanceof Headers?[...e.headers]:Object.entries(e.headers)).map(([t,r])=>[t,t.toLowerCase()==="authorization"||t.toLowerCase()==="api-key"||t.toLowerCase()==="x-api-key"||t.toLowerCase()==="cookie"||t.toLowerCase()==="set-cookie"?"***":r]))),"retryOfRequestLogID"in e&&(e.retryOfRequestLogID&&(e.retryOf=e.retryOfRequestLogID),delete e.retryOfRequestLogID),e)}}),J4t=E({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/utils.mjs"(){op(),VVr(),eD(),zm(),PZ(),ix(),O4t()}});function X4t(e){if(!e)throw new Error("profile name is empty");if(e==="."||e==="..")throw new Error(`profile name "${e}" is not allowed`);if(e.includes("/")||e.includes("\\"))throw new Error(`profile name "${e}" must not contain path separators`);if(!Y4t.test(e))throw new Error(`profile name "${e}" contains disallowed characters (allowed: letters, digits, '_', '.', '-')`)}var iQ,Y4t,Z4t,Q4t,rD,ePt,sQ,tPt=E({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/core/credentials.mjs"(){HZ(),J4t(),iQ="1.0",Y4t=/^[A-Za-z0-9_.-]+$/,Z4t=async e=>{var t,r;const n=await rD();if(n===null)return null;const o=e??await sQ();if(o===null)return null;X4t(o);const i=await Promise.resolve().then(()=>(Sn(),Id)),a=(await Promise.resolve().then(()=>(qt(),um))).join(n,"configs",`${o}.json`);let l;try{l=await i.promises.readFile(a,"utf-8")}catch(d){if(d?.code!=="ENOENT")throw new Error(`failed to read config file ${a}: ${d}`);l=null}if(l===null){const d=Fr("ANTHROPIC_ORGANIZATION_ID"),p=Fr("ANTHROPIC_IDENTITY_TOKEN_FILE"),m=Fr("ANTHROPIC_FEDERATION_RULE_ID");return m&&d?{fromFile:!1,config:{organization_id:d,workspace_id:Fr("ANTHROPIC_WORKSPACE_ID"),base_url:Fr("ANTHROPIC_BASE_URL"),authentication:{type:"oidc_federation",federation_rule_id:m,service_account_id:Fr("ANTHROPIC_SERVICE_ACCOUNT_ID"),identity_token:p?{source:"file",path:p}:void 0,scope:Fr("ANTHROPIC_SCOPE")}}}:null}let c;try{c=JSON.parse(l)}catch(d){throw new Error(`failed to parse config file ${a}: ${d}`)}if(!c.authentication)throw new Error(`config file ${a} is missing "authentication"`);const u=c.authentication.type;if(u!=="oidc_federation"&&u!=="user_oauth")throw new Error(`authentication.type "${u}" is not a known authentication type`);if(c.organization_id??(c.organization_id=Fr("ANTHROPIC_ORGANIZATION_ID")),c.workspace_id??(c.workspace_id=Fr("ANTHROPIC_WORKSPACE_ID")),c.base_url??(c.base_url=Fr("ANTHROPIC_BASE_URL")),(t=c.authentication).scope??(t.scope=Fr("ANTHROPIC_SCOPE")),c.authentication.type==="oidc_federation"){if(!c.authentication.identity_token){const d=Fr("ANTHROPIC_IDENTITY_TOKEN_FILE");d&&(c.authentication.identity_token={source:"file",path:d})}c.authentication.federation_rule_id||(c.authentication.federation_rule_id=Fr("ANTHROPIC_FEDERATION_RULE_ID")??""),(r=c.authentication).service_account_id??(r.service_account_id=Fr("ANTHROPIC_SERVICE_ACCOUNT_ID"))}return{config:c,fromFile:!0}},Q4t=async(e,t)=>{if(e?.authentication.credentials_path)return e.authentication.credentials_path;const r=await rD();if(!r)return null;const n=t??await sQ();return n?(X4t(n),(await Promise.resolve().then(()=>(qt(),um))).join(r,"credentials",`${n}.json`)):null},rD=async()=>{if(!ePt())return null;const e=await Promise.resolve().then(()=>(qt(),um)),t=Fr("ANTHROPIC_CONFIG_DIR");if(t)return t;if(WO()["X-Stainless-OS"]==="Windows"){const i=Fr("APPDATA");if(i)return e.join(i,"Anthropic");const s=Fr("USERPROFILE");return s?e.join(s,"AppData","Roaming","Anthropic"):null}const n=Fr("XDG_CONFIG_HOME");if(n)return e.join(n,"anthropic");const o=Fr("HOME");return o?e.join(o,".config","anthropic"):null},ePt=()=>{const e=WO()["X-Stainless-Runtime"];return e==="node"||e==="deno"},sQ=async()=>{const e=await rD();if(!e)return null;const t=Fr("ANTHROPIC_PROFILE");if(t)return t;const r=await Promise.resolve().then(()=>(Sn(),Id)),o=(await Promise.resolve().then(()=>(qt(),um))).join(e,"active_config");try{return(await r.promises.readFile(o,"utf-8")).trim()||"default"}catch(i){if(i?.code!=="ENOENT")throw new Error(`failed to read ${o}: ${i}`);return"default"}}}});function rPt(e){if(!e)throw new lt("Identity token file path is empty");return async()=>{const t=await Promise.resolve().then(()=>(Sn(),Id));let r;try{r=await t.promises.readFile(e,"utf-8")}catch(o){throw new lt(`Failed to read identity token file at ${e}: ${o}`)}const n=r.trim();if(!n)throw new lt(`Identity token file at ${e} is empty`);return n}}function jVr(e){if(!e)throw new lt("Identity token value is empty");return()=>e}var HVr=E({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/lib/credentials/identity-token.mjs"(){$o()}});function WVr(e){return async()=>{D4t(e.baseURL);const t=await e.identityTokenProvider();if(t.length>16*1024)throw new Xn(`Identity token is ${Math.ceil(t.length/1024)} KiB, exceeds the 16 KiB assertion limit`);const r={grant_type:$4t,assertion:t,federation_rule_id:e.federationRuleId,organization_id:e.organizationId};e.serviceAccountId&&(r.service_account_id=e.serviceAccountId),e.workspaceId&&(r.workspace_id=e.workspaceId);const n=`${e.baseURL}${QZ}`;let o;try{o=await e.fetch(n,{method:"POST",headers:{"Content-Type":"application/json","anthropic-beta":`${ax},${B4t}`,"User-Agent":e.userAgent||`anthropic-sdk-typescript/${ip} oidcFederationProvider`},body:JSON.stringify(r)})}catch(l){throw new Xn(`Failed to reach token endpoint ${n}: ${l}`)}const i=o.headers.get("Request-Id");if(!o.ok){const l=await o.text().catch(()=>""),c=Xl(l);let u="";throw o.status===401&&(u=` Ensure your federation rule matches your identity token. ${e.workspaceId?"":"If your federation rule is scoped to multiple workspaces, set the ANTHROPIC_WORKSPACE_ID environment variable, the 'workspace_id' config key, or the `workspaceId` option. "}View your authentication events in the Workload identity page of Claude Console for more details.`),new Xn(`Token exchange failed with status ${o.status}${i?` (request-id ${i})`:""}: ${c}${u}`,o.status,c,i)}const s=await N4t(o,i),a=Number(s.expires_in);if(!Number.isFinite(a))throw new Xn(`Token endpoint response missing required fields: ${JSON.stringify(Xl(s))}`,o.status,Xl(s),i);return{token:s.access_token,expiresAt:bg()+a}}}var KVr=E({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/lib/credentials/oidc-federation.mjs"(){lx(),QO(),HO()}});function JVr(e){return async t=>{const r=await Promise.resolve().then(()=>(Sn(),Id));await L4t(e.credentialsPath,e.onSafetyWarning);let n;try{n=await r.promises.readFile(e.credentialsPath,"utf-8")}catch(y){throw new Xn(`Credentials file not found at ${e.credentialsPath}: ${y}`)}let o;try{o=JSON.parse(n)}catch(y){throw new Xn(`Credentials file at ${e.credentialsPath} is not valid JSON: ${y}`)}const i=o.access_token;if(!i)throw new Xn(`Credentials file at ${e.credentialsPath} must include 'access_token'`);const s=o.expires_at;if(!t?.forceRefresh&&(s==null||bg()<s-YO))return{token:i,expiresAt:s??null};const a=o.refresh_token;if(!e.clientId||!a)throw new Xn(`Access token at ${e.credentialsPath} has expired and no refresh is available (client_id ${e.clientId?"set":"empty"}, refresh_token ${a?"set":"empty"})`);D4t(e.baseURL);const l={grant_type:U4t,refresh_token:a,client_id:e.clientId},c=`${e.baseURL}${QZ}`;let u;try{u=await e.fetch(c,{method:"POST",headers:{"Content-Type":"application/json","anthropic-beta":ax,"User-Agent":e.userAgent||`anthropic-sdk-typescript/${ip} userOAuthProvider`},body:JSON.stringify(l)})}catch(y){throw new Xn(`User OAuth refresh failed to reach token endpoint: ${y}`)}const d=u.headers.get("Request-Id");if(!u.ok){const y=await u.text().catch(()=>"");throw new Xn(`User OAuth refresh failed (HTTP ${u.status}): ${Xl(y)}`,u.status,Xl(y),d)}const p=await N4t(u,d),m=Number(p.expires_in);if(!Number.isFinite(m))throw new Xn(`User OAuth refresh response missing or invalid expires_in: ${JSON.stringify(Xl(p))}`,u.status,Xl(p),d);const f=bg()+m,g=p.refresh_token||a;return await F4t(e.credentialsPath,{...o,version:iQ,type:"oauth_token",access_token:p.access_token,expires_at:f,refresh_token:g}),{token:p.access_token,expiresAt:f}}}var XVr=E({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/lib/credentials/user-oauth.mjs"(){tPt(),lx(),QO(),HO()}});function nPt(e,t){const r=e.authentication.credentials_path??null,n=(e.base_url||t.baseURL).replace(/\/+$/,""),o=ZVr(e,r,n,t),i={};return e.workspace_id&&e.authentication.type==="user_oauth"&&(i["anthropic-workspace-id"]=e.workspace_id),{provider:o,extraHeaders:i,baseURL:e.base_url||void 0}}async function YVr(e,t){const r=await Z4t(t);if(!r)return null;const{config:n,fromFile:o}=r,i=n.authentication.credentials_path||!o?n:{...n,authentication:{...n.authentication,credentials_path:await Q4t(n,t)??void 0}};return nPt(i,e)}function ZVr(e,t,r,n){switch(e.authentication.type){case"oidc_federation":{const o=e.authentication,i=QVr(o);if(!i)throw new Xn("oidc_federation config requires an identity token (set authentication.identity_token, ANTHROPIC_IDENTITY_TOKEN_FILE, or ANTHROPIC_IDENTITY_TOKEN)");if(!o.federation_rule_id)throw new Xn("oidc_federation config requires 'federation_rule_id'. Set it in authentication.federation_rule_id in your profile, or via ANTHROPIC_FEDERATION_RULE_ID (profile takes precedence).");if(!e.organization_id)throw new Xn("oidc_federation config requires organization_id (set ANTHROPIC_ORGANIZATION_ID or config.organization_id)");const s=WVr({identityTokenProvider:i,federationRuleId:o.federation_rule_id,organizationId:e.organization_id,serviceAccountId:o.service_account_id,workspaceId:e.workspace_id,baseURL:r,fetch:n.fetch,userAgent:n.userAgent});return t?ejr(s,t,n.onCacheWriteError,n.onSafetyWarning):s}case"user_oauth":{if(!t)throw new Xn("user_oauth config requires authentication.credentials_path (or load via a profile so it defaults to <config_dir>/credentials/<profile>.json)");return JVr({credentialsPath:t,clientId:e.authentication.client_id,baseURL:r,fetch:n.fetch,userAgent:n.userAgent,onSafetyWarning:n.onSafetyWarning})}default:{const o=e.authentication.type;throw new Xn(`authentication.type "${o}" is not a known authentication type`)}}}function QVr(e){if(e.identity_token){const n=e.identity_token.source;if(n!=="file")throw new Xn(`identity_token.source "${n}" is not supported by this SDK version (only "file")`);if(!e.identity_token.path)throw new Xn('identity_token.source "file" requires a non-empty path');return rPt(e.identity_token.path)}const t=Fr("ANTHROPIC_IDENTITY_TOKEN_FILE");if(t)return rPt(t);const r=Fr("ANTHROPIC_IDENTITY_TOKEN");return r?jVr(r):null}function ejr(e,t,r,n){return async o=>{const i=await Promise.resolve().then(()=>(Sn(),Id));await L4t(t,n);let s;try{const l=await i.promises.readFile(t,"utf-8");s=JSON.parse(l);const c=s?.access_token;if(c&&!o?.forceRefresh){const u=s?.expires_at;if(u==null||bg()<u-YO)return{token:c,expiresAt:u??null}}}catch(l){l?.code!=="ENOENT"&&!(l instanceof SyntaxError)&&r?.(l)}const a=await e(o);try{await F4t(t,{...s??{},version:iQ,type:"oauth_token",access_token:a.token,expires_at:a.expiresAt})}catch(l){r?.(l)}return a}}var tjr=E({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/lib/credentials/credential-chain.mjs"(){eD(),tPt(),lx(),QO(),HVr(),KVr(),XVr()}});function rjr(e,t){for(let o=t??0;o<e.length;o++){if(e[o]===10)return{preceding:o,index:o+1,carriage:!1};if(e[o]===13)return{preceding:o,index:o+1,carriage:!0}}return null}function njr(e){for(let n=0;n<e.length-1;n++){if(e[n]===10&&e[n+1]===10||e[n]===13&&e[n+1]===13)return n+2;if(e[n]===13&&e[n+1]===10&&n+3<e.length&&e[n+2]===13&&e[n+3]===10)return n+4}return-1}var hl,fl,nw,oPt=E({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/decoders/line.mjs"(){ml(),rQ(),nw=class{constructor(){hl.set(this,void 0),fl.set(this,void 0),$e(this,hl,new Uint8Array,"f"),$e(this,fl,null,"f")}decode(e){if(e==null)return[];const t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?tQ(e):e;$e(this,hl,qVr([V(this,hl,"f"),t]),"f");const r=[];let n;for(;(n=rjr(V(this,hl,"f"),V(this,fl,"f")))!=null;){if(n.carriage&&V(this,fl,"f")==null){$e(this,fl,n.index,"f");continue}if(V(this,fl,"f")!=null&&(n.index!==V(this,fl,"f")+1||n.carriage)){r.push(j4t(V(this,hl,"f").subarray(0,V(this,fl,"f")-1))),$e(this,hl,V(this,hl,"f").subarray(V(this,fl,"f")),"f"),$e(this,fl,null,"f");continue}const o=V(this,fl,"f")!==null?n.preceding-1:n.preceding,i=j4t(V(this,hl,"f").subarray(0,o));r.push(i),$e(this,hl,V(this,hl,"f").subarray(n.index),"f"),$e(this,fl,null,"f")}return r}flush(){return V(this,hl,"f").length?this.decode(`
|
|
1053
|
+
`,r:"\r",t:" "}}}),bVr=E({"node_modules/.pnpm/jsonrepair@3.14.0/node_modules/jsonrepair/lib/esm/index.js"(){TVr()}});function t4t(e,t=0){for(let r=t;r<e.length;r++){const n=e[r];if(n!=="{"&&n!=="[")continue;const o=n==="{"?"}":"]";let i=0,s=!1,a=!1;for(let l=r;l<e.length;l++){const c=e[l];if(a){a=!1;continue}if(c==="\\"){a=!0;continue}if(c==='"'){s=!s;continue}if(!s){if(c===n)i++;else if(c===o&&(i--,i===0))return{span:e.substring(r,l+1),end:l+1}}}}return null}var _Vr=E({"src/lib/utils/json/extract.ts"(){"use strict"}});function r4t(e){return typeof e.safeParse=="function"}function qO(e,t){return!e||!r4t(e)?!0:e.safeParse(t).success}function n4t(e,t){try{const r=JSON.parse(e);return r===""?{kind:"empty"}:r==null?{kind:"nullish"}:qO(t,r)?{kind:"accepted",value:r}:{kind:"rejected",value:r}}catch{return{kind:"not-json"}}}function o4t(e){try{return{value:JSON.parse(e),repaired:!1}}catch{}try{const t=vVr(e),r=JSON.parse(t);return t!==e&&h.shouldLog("debug")&&h.debug("[coerceJsonToSchema] jsonrepair altered model output",{originalLength:e.length,repairedLength:t.length}),{value:r,repaired:t!==e}}catch{return}}function EVr(e){let t=e;for(let r=0;r<s4t&&t.length>1;r++){const n=Math.max(t.lastIndexOf(","),t.lastIndexOf("}"),t.lastIndexOf("]"));if(n<=0)break;t=t.slice(0,n);const o=o4t(t);if(o!==void 0&&o.value!==null&&typeof o.value=="object")return o.value}}function kZ(e,t=0){if(t>i4t)return{value:e,changed:!1};if(typeof e=="string"){const r=e.trim();if(r.startsWith("{")&&r.endsWith("}")||r.startsWith("[")&&r.endsWith("]"))try{const o=JSON.parse(r);if(o!==null&&typeof o=="object")return{value:o,changed:!0}}catch{}return{value:e,changed:!1}}if(Array.isArray(e)){let r=!1;const n=e.map(o=>{const i=kZ(o,t+1);return i.changed&&(r=!0),i.value});return{value:r?n:e,changed:r}}if(e!==null&&typeof e=="object"){let r=!1;const n={};for(const[o,i]of Object.entries(e)){const s=kZ(i,t+1);s.changed&&(r=!0),n[o]=s.value}return{value:r?n:e,changed:r}}return{value:e,changed:!1}}function xZ(e,t){if(typeof e!="string"||e.trim().length===0)return null;const r=[],n=[e.indexOf("{"),e.indexOf("[")].filter(v=>v>=0),o=n.length>0?Math.min(...n):-1;let i=!1,s=0;for(;;){const v=t4t(e,s);if(!v)break;const T=v.end-v.span.length;T===o&&(i=!0),r.push({text:v.span,truncated:!1,rootAligned:T===o}),s=v.end}const a=o>=0&&!i,l=Math.max(e.lastIndexOf("}"),e.lastIndexOf("]"));o>=0&&l>o&&r.push({text:e.slice(o,l+1),truncated:a,rootAligned:!0}),o>=0&&r.push({text:e.slice(o),truncated:!0,rootAligned:!0});const c=e.trim();if(c.length>1&&c.startsWith('"')&&c.endsWith('"'))try{const v=JSON.parse(c);if(typeof v=="string"){let T=0;for(;;){const b=t4t(v,T);if(!b)break;r.push({text:b.span,truncated:!1,rootAligned:!1}),T=b.end}}}catch{}const u=[...r.filter(v=>v.rootAligned),...r.filter(v=>!v.rootAligned)];let d;const p=[],m=!!(t&&r4t(t)),f=new Set;for(const v of u){if(f.has(v.text))continue;f.add(v.text);const T=o4t(v.text);if(T===void 0||T.value===null||typeof T.value!="object")continue;const b={value:T.value,repaired:T.repaired,truncated:v.truncated,rootAligned:v.rootAligned};if(d===void 0&&(d=b),!m)break;const S=t;if(S.safeParse(T.value).success)p.push(b);else{const k=kZ(T.value);k.changed&&k.value!==null&&typeof k.value=="object"&&S.safeParse(k.value).success?p.push({value:k.value,repaired:!0,truncated:v.truncated,rootAligned:v.rootAligned}):Array.isArray(T.value)&&T.value.length===1&&T.value[0]!==null&&typeof T.value[0]=="object"&&!Array.isArray(T.value[0])&&S.safeParse(T.value[0]).success&&p.push({value:T.value[0],repaired:!0,truncated:v.truncated,rootAligned:v.rootAligned})}}const g=p.length>0?p.reduce((v,T)=>JSON.stringify(T.value).length>JSON.stringify(v.value).length?T:v):void 0;let y=g??d;if(a&&g===void 0&&(y===void 0||!y.rootAligned)){const v=EVr(e.slice(o));v!==void 0?(h.debug("[coerceJsonToSchema] salvaged a partial truncated object",{textLength:e.length}),y={value:v,repaired:!0,truncated:!0,rootAligned:!0}):y!==void 0&&(y={...y,truncated:!0})}return y===void 0?null:{content:JSON.stringify(y.value),structuredData:y.value,repaired:y.repaired,truncated:y.truncated}}var i4t,s4t,a4t=E({"src/lib/utils/json/coerce.ts"(){"use strict";bVr(),z(),_Vr(),i4t=6,s4t=8}});function VO(e,t,r){return!r||!t||Object.keys(t).length===0?"none":e.toolChoice??"auto"}function SVr(e){if(typeof e=="string")return e;if(e&&typeof e=="object"){const t=e;if(t.type==="tool")return t.toolName?{type:"tool",toolName:t.toolName}:void 0;if(t.type)return t.type}}var l4t=E({"src/lib/utils/toolChoice.ts"(){"use strict"}});async function*kVr(e,t){const r=e.getReader();let n=!1;try{for(;;){const o=await r.read();if(o.done){n=!0;return}const i=o.value;if(i.type==="text-delta")yield{content:i.delta};else if(i.type==="reasoning-delta")yield{content:"",reasoning:i.delta};else if(i.type==="finish")t(i);else if(i.type==="error")throw i.error}}finally{try{n||await r.cancel()}finally{r.releaseLock()}}}var jO,AZ,rx,CZ,IZ,c4t,Kl,zc=E({"src/lib/providers/openaiChatCompletionsBase.ts"(){"use strict";Qt(),$c(),aVr(),di(),xRt(),ARt(),CRt(),pl(),Zo(),RRt(),Ln(),z(),Nt(),rm(),ZJ(),Ys(),MRt(),If(),vZ(),vm(),ss(),a4t(),l4t(),zl(),kd(),EY(),qS(),Um(),Jv(),jO=512,AZ=class extends Error{},rx=(e,t)=>{const r=xZ(e,t);return r!==null&&qO(t,r.structuredData)},CZ=(e,t)=>{const r=xZ(e,t);if(r!==null&&qO(t,r.structuredData))return r.structuredData;const n=n4t(e,t);return n.kind==="accepted"?n.value:void 0},IZ=e=>{switch(e){case"length":return"length";case"tool_calls":case"function_call":case"tool-calls":return"tool-calls";case"content_filter":case"content-filter":return"content-filter";default:return"stop"}},c4t=(e,t,r)=>{const n=e[Symbol.asyncIterator]();return new ReadableStream({async pull(o){try{const i=await n.next();i.done?(o.enqueue(await t),o.close()):i.value.reasoning?o.enqueue({type:"reasoning-delta",delta:i.value.reasoning}):o.enqueue({type:"text-delta",delta:i.value.content})}catch(i){o.error(i)}},async cancel(){r(),await n.return?.()}})},Kl=class extends Ma{config;resolvedModel;constructor(e,t,r,n){super(t,e,r),this.config=n}getFallbackModelName(){return"gpt-3.5-turbo"}getModelFallbacks(){return this.getFallbackModels()}refreshHandlersForModel(e){this.resolvedModel=e,super.refreshHandlersForModel(e)}getFallbackModels(){return[]}adjustBuildBodyOptions(e,t){return t}adjustResponseFormat(e,t){return e}suppressResponseFormatWithTools(){return!0}useStreamingWireForGenerate(){return!1}replayReasoningContent(){return!1}adjustRequestBody(e,t){return e}adjustBodyAfter400(e,t){}resolveWireMaxTokens(e,t,r,n){const o=hK(this.providerName,e);let i=t;o!==void 0&&(i===void 0||i>o)&&(i!==void 0&&h.debug(`${this.providerName}: clamping max_tokens ${i} to the advertised ${e} output ceiling ${o}`),i=o);const s=mK(this.providerName,e);if(s!==void 0){const a=XY(r,n,this.providerName),l=s-a-jO;if(l<=0)throw new Na(`Estimated input (${a} tokens) alone exceeds the ${this.providerName}/${e} context window advertised by the serving infrastructure (${s} tokens). Reduce the prompt/conversation size \u2014 no max_tokens value can make this request fit.`,{estimatedTokens:a,availableTokens:Math.max(0,s-jO),stagesUsed:[],breakdown:{}});i!==void 0&&i>l&&(h.warn(`${this.providerName}: max_tokens ${i} cannot fit the ${e} window (${s}) with ~${a} input tokens \u2014 re-fitting to ${l}`),i=l)}return i}correctBodyAfterContextOverflow(e,t){if(!pZ(t))return;const r=mZ(t)??mZ(t.responseBody);if(!r||r.budgetTokens<=0)return;pK(this.providerName,e.model,r.budgetTokens);const n=typeof e.max_tokens=="number"?e.max_tokens:r.requestedOutputTokens;if(n===void 0||r.actualTokens<=0)return;const o=r.budgetTokens-r.actualTokens-jO;if(!(o<=0||o>=n))return h.warn(`${this.providerName}: ${e.model} rejected the request as over-window \u2014 retrying once with max_tokens re-fit from the provider's own numbers`,{window:r.budgetTokens,inputTokens:r.actualTokens,previousMaxTokens:n,refitMaxTokens:o}),{...e,max_tokens:o}}onStreamStart(e){}shouldAutoDiscoverModel(){return!0}getChatCompletionsURL(e){return`${Da(this.config.baseURL)}/chat/completions`}getAuthHeaders(){return{Authorization:`Bearer ${this.config.apiKey}`}}async validateConfiguration(){return typeof this.config.apiKey=="string"&&this.config.apiKey.trim().length>0}async probeModelsEndpoint(e={}){try{const t=`${Da(this.config.baseURL)}/models`,n=await Ot()(t,{headers:{...e,"Content-Type":"application/json"},signal:AbortSignal.timeout(5e3)});return n.ok?!!(await n.json().catch(()=>null))?.data?.some(i=>typeof i?.id=="string"&&i.id.trim().length>0):!1}catch(t){return h.debug(`[${this.constructor.name}] probeModelsEndpoint failed`,{baseURL:Yo(this.config.baseURL),error:t instanceof Error?t.message:String(t)}),!1}}getConfiguration(){return{provider:this.providerName,model:this.modelName,defaultModel:this.getDefaultModel(),baseURL:this.config.baseURL}}async getAISDKModel(){const e=await this.resolveModelName();return this.buildDelegatingModel(e)}async resolveModelName(){if(this.resolvedModel)return this.resolvedModel;const e=this.modelName||this.getDefaultModel();if(e&&e.trim()!=="")return this.resolvedModel=e,this.modelName!==e&&this.refreshHandlersForModel(e),e;if(this.shouldAutoDiscoverModel()){try{const r=await this.getAvailableModels();if(r.length>0)return this.resolvedModel=r[0],this.refreshHandlersForModel(r[0]),h.info(`\u{1F50D} Auto-discovered model: ${r[0]} from ${r.length} available models`),r[0]}catch(r){h.warn("Model auto-discovery failed, using fallback:",r)}return this.getFallbackModelName()}const t=this.getFallbackModelName();return this.resolvedModel=t,this.refreshHandlersForModel(t),t}buildDelegatingModel(e){const t=this.getChatCompletionsURL(e),r=Ot(),n=this.getAuthHeaders.bind(this),o=this.providerName,i=this.adjustBuildBodyOptions.bind(this),s=this.adjustResponseFormat.bind(this),a=this.adjustRequestBody.bind(this),l=this.adjustBodyAfter400.bind(this),c=this.correctBodyAfterContextOverflow.bind(this),u=this.resolveWireMaxTokens.bind(this),d=this.suppressResponseFormatWithTools.bind(this),p=this.useStreamingWireForGenerate.bind(this),m=this.replayReasoningContent.bind(this),f=g=>this.getTimeout(g??{});return{specificationVersion:"v3",provider:o,modelId:e,supportedUrls:{},doGenerate:async g=>{const y=FO((g.tools??[]).filter(G=>G.type==="function").map(G=>G.name)),v=QY(g.prompt,y?.toWire,m()),T=Array.isArray(g.tools)&&g.tools.length>0,b=g.responseFormat&&!(T&&d())?s(nZ(g.responseFormat),e):void 0,S=hRt(g.tools,y?.toWire),k=u(e,g.maxOutputTokens,v,S),A=p(),x=oZ(a(iZ({modelId:e,messages:v,options:i(e,{maxTokens:k,temperature:g.temperature,topP:g.topP,presencePenalty:g.presencePenalty,frequencyPenalty:g.frequencyPenalty,seed:g.seed,stopSequences:g.stopSequences}),tools:S,...g.toolChoice?{toolChoice:fRt(g.toolChoice,y?.toWire)}:{},streaming:A,...b?{responseFormat:b}:{}}),e)),P=g.providerOptions?.neurolink?.timeoutMs,C=wa(typeof P=="number"?P:f(g),o,"generate"),{signal:R,dispose:O}=T4(g.abortSignal,C?.controller.signal);let U,M=A;try{let G=await r(t,{method:"POST",headers:{"Content-Type":"application/json",...n()},body:JSON.stringify(x),...R?{signal:R}:{}});if(!G.ok){const J=await Zk(t,x,G),K=J;let de=G.status===400?(()=>{const oe=c(x,K);return l(oe??x,K)??oe})():void 0;if(!de&&A&&G.status===400&&/stream/i.test(K.responseBody??"")){const{stream:oe,stream_options:ae,...ge}=x;de=ge,M=!1}if(!de)throw J;if(G=await r(t,{method:"POST",headers:{"Content-Type":"application/json",...n()},body:JSON.stringify(de),...R?{signal:R}:{}}),!G.ok)throw await Zk(t,de,G)}if(M){if(!G.body)throw new Error(`${o}: streaming generate response had no body`);const J=C?G.body.pipeThrough(new TransformStream({transform(de,oe){C.reset(),oe.enqueue(de)}})):G.body,K=await sZ(J,()=>{});U={...K.id?{id:K.id}:{},...K.model?{model:K.model}:{},choices:[{index:0,message:{role:"assistant",content:K.text.length>0?K.text:null,...K.reasoning?{reasoning:K.reasoning}:{},...K.toolCalls.size>0?{tool_calls:[...K.toolCalls.values()].map(de=>({id:de.id,type:"function",function:{name:de.name,arguments:de.argsBuffered}}))}:{}},finish_reason:K.finishReason??"stop"}],...K.usage?{usage:K.usage}:{}}}else U=await G.json()}finally{C?.cleanup(),O()}const D=U.choices?.[0],$=(typeof D?.message?.content=="string"?D.message.content:"")??"",B=[],q=D?.message?.reasoning_content||D?.message?.reasoning;typeof q=="string"&&q.length>0&&B.push({type:"reasoning",text:q}),$.length>0&&B.push({type:"text",text:$});for(const G of D?.message?.tool_calls??[])B.push({type:"tool-call",toolCallId:G.id,toolName:y?.fromWire.get(G.function.name)??G.function.name,input:G.function.arguments??""});const L=D?.finish_reason,j=IZ(L);return{content:B,finishReason:{unified:j,raw:L??"stop"},usage:{inputTokens:{total:U.usage?.prompt_tokens,noCache:U.usage?.prompt_tokens!==void 0&&U.usage?.prompt_tokens_details?.cached_tokens!==void 0?Math.max(0,U.usage.prompt_tokens-U.usage.prompt_tokens_details.cached_tokens):U.usage?.prompt_tokens,cacheRead:U.usage?.prompt_tokens!==void 0&&U.usage?.prompt_tokens_details?.cached_tokens!==void 0?Math.min(U.usage.prompt_tokens_details.cached_tokens,U.usage.prompt_tokens):U.usage?.prompt_tokens_details?.cached_tokens,cacheWrite:void 0},outputTokens:{total:U.usage?.completion_tokens,text:U.usage?.completion_tokens!==void 0&&U.usage?.completion_tokens_details?.reasoning_tokens!==void 0?Math.max(0,U.usage.completion_tokens-U.usage.completion_tokens_details.reasoning_tokens):U.usage?.completion_tokens,reasoning:U.usage?.completion_tokens_details?.reasoning_tokens}},warnings:[],request:{body:x},response:{...U.id?{id:U.id}:{},...U.model?{modelId:U.model}:{},headers:{},body:U}}},doStream:()=>{throw new Error(`${o}: doStream is not implemented on the delegating model. NeuroLink streams through executeStream, reached via NeuroLink.stream() \u2014 use that (the browser bundle exports the NeuroLink class) rather than calling doStream on a model handle.`)}}}async generate(e,t){await this.ensureModelLimits();const r=this.normalizeTextOptions(e);if($d(r,this.modelName)!=="text")return super.generate(r,t);this.validateOptions(r);const n=await this.getToolsForStream(r),o="disableInternalFallback"in r&&r.disableInternalFallback===!0;return this.runGenerateWithModelFallback(()=>this.withTurnTimeout({...r,tools:n},this.getDescriptorGenerateMs(),i=>this.executeNativeGenerate(i)),o,r)}async executeNativeGenerate(e){const t=Date.now(),r=await this.resolveModelName(),n=await this.getAISDKModelWithMiddleware(e);if(!ex(n))throw this.handleProviderError(new Error(`${this.providerName}: model handle exposes no doGenerate()`));const o=n.doGenerate.bind(n),i=!e.disableTools&&this.supportsTools(),s=i?e.tools||await this.getAllTools():{},a=i?Object.entries(s).map(([C,R])=>{const O=R;return{type:"function",name:C,description:O.description??"",inputSchema:O.inputSchema?qo(O.inputSchema):{type:"object",properties:{}}}}):void 0,l=!!a&&a.length>0,c=e.schema?qo(e.schema):void 0,u=c!==void 0&&l&&this.suppressResponseFormatWithTools(),d=c&&!u?{type:"json",schema:c}:void 0,p=await this.buildMessagesForStream(e),m=[],f=(C,R,O=!0)=>BO({doGenerate:o,...SRt({provider:this.providerName,availableInputTokens:ql(this.providerName,r,e.maxTokens??void 0),getFixedOverheadTokens:()=>Vt(xk({...O&&a?{tools:a}:{},responseFormat:R}),this.providerName)}),conversation:C,...O&&a?{tools:a}:{},toolsRecord:s,...O&&l&&e.toolChoice?{toolChoice:VO(e,s,!0)}:{},...typeof e.timeout=="number"?{providerOptions:{neurolink:{timeoutMs:e.timeout}}}:{},...R?{responseFormat:R}:{},maxSteps:e.maxSteps||ts,...e.maxTokens?{maxOutputTokens:e.maxTokens}:{},...e.temperature!==void 0?{temperature:e.temperature}:{},...e.abortSignal?{abortSignal:e.abortSignal}:{},...e.toolTimeoutMs!==void 0?{toolTimeoutMs:e.toolTimeoutMs}:{},runStep:U=>Py(U,dt.getActiveSpan()??void 0,`${this.providerName} generate`,void 0,e.abortSignal).catch(M=>{throw this.handleProviderError(M)})},m);let g=!1,y;try{y=await f(p,d)}catch(C){if(!(d!==void 0&&(c7r(C)||hIt(C)||u7r(C))))throw C;h.warn(`[${this.providerName}] provider rejected response_format \u2014 retrying with the schema in the system prompt`,{provider:this.providerName,model:r}),g=!0,y=await f(Qv(p,d.schema),void 0)}if(!g&&d!==void 0&&e.schema!==void 0&&!rx(y.text,e.schema)){h.warn(`[${this.providerName}] response_format did not yield a schema-valid object \u2014 retrying with the schema in the system prompt`,{provider:this.providerName,model:r});const C=y,R=await f(Qv(p,d.schema),void 0);y={...R,inputTokens:C.inputTokens+R.inputTokens,outputTokens:C.outputTokens+R.outputTokens,cacheReadTokens:(C.cacheReadTokens??0)+(R.cacheReadTokens??0),cacheWriteTokens:(C.cacheWriteTokens??0)+(R.cacheWriteTokens??0)}}u&&c&&e.schema&&(y=await this.reformatWithoutTools({toolPhase:y,conversation:p,schemaJson:c,schema:e.schema,runLoop:f,modelId:r,abortSignal:e.abortSignal}));const{text:v,finishReason:T,toolsUsed:b}=y,S=y.inputTokens,k=y.outputTokens,A=y.steps,x=A>=(e.maxSteps||ts)&&T==="tool-calls"?"step-cap":T==="error"?"provider-error":"completed",P={content:v,provider:this.providerName,model:r,finishReason:T,...y.rawFinishReason?{rawFinishReason:y.rawFinishReason}:{},stopReason:x,stepsUsed:A,usage:{input:S,output:k,total:S+k+y.cacheReadTokens+y.cacheWriteTokens,...y.cacheReadTokens?{cacheReadTokens:y.cacheReadTokens}:{},...y.cacheWriteTokens?{cacheCreationTokens:y.cacheWriteTokens}:{}},responseTime:Date.now()-t,...y.reasoning?{reasoning:y.reasoning}:{},toolsUsed:b,toolCalls:HH(m),toolExecutions:Df(e,Bd(m)),enhancedWithTools:b.length>0};return this.finalizeNativeGenerate(P,e,t)}async reformatWithoutTools(e){const{toolPhase:t,conversation:r,schemaJson:n,schema:o,runLoop:i,modelId:s,abortSignal:a}=e;let l=t;const c=()=>a?.aborted===!0;if(l.text.trim().length>0&&!c()&&!rx(l.text,o)){h.warn(`[${this.providerName}] tools suppressed response_format and the answer is not schema-valid \u2014 re-asking once without tools`,{provider:this.providerName,model:s});const u={inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0},d=p=>{u.inputTokens+=p.inputTokens,u.outputTokens+=p.outputTokens,u.cacheReadTokens+=p.cacheReadTokens??0,u.cacheWriteTokens+=p.cacheWriteTokens??0};try{const p=[...r,{role:"assistant",content:t.text},{role:"user",content:"Return that same answer as a single JSON value conforming to the required schema. No prose before or after it, and no markdown code fence."}];let m,f=!1;try{m=await i(p,{type:"json",schema:n},!1),d(m)}catch(g){if(c())throw g;h.warn(`[${this.providerName}] the re-ask's response_format was rejected \u2014 retrying with the schema in the prompt`,{provider:this.providerName,model:s,error:g instanceof Error?g.message:String(g)}),m=await i(Qv(p,n),void 0,!1),d(m),f=!0}if(!f&&!c()&&!rx(m.text,o)&&(h.warn(`[${this.providerName}] the re-ask's response_format carried no schema \u2014 retrying with the schema in the prompt`,{provider:this.providerName,model:s}),m=await i(Qv(p,n),void 0,!1),d(m)),!rx(m.text,o))throw h.warn(`[${this.providerName}] the tool-free re-ask did not yield a schema-valid object either; keeping the original answer`,{provider:this.providerName,model:s}),new AZ;l={...m,toolsUsed:[...new Set([...t.toolsUsed,...m.toolsUsed])],inputTokens:t.inputTokens+u.inputTokens,outputTokens:t.outputTokens+u.outputTokens,cacheReadTokens:(t.cacheReadTokens??0)+u.cacheReadTokens,cacheWriteTokens:(t.cacheWriteTokens??0)+u.cacheWriteTokens,steps:t.steps,...t.finishReason!=="stop"?{finishReason:t.finishReason,rawFinishReason:t.rawFinishReason}:{finishReason:m.finishReason}}}catch(p){if(c()&&!(a?.reason instanceof Ta))throw p;p instanceof AZ||h.warn(`[${this.providerName}] the tool-free structured-output re-ask failed; keeping the original answer`,{provider:this.providerName,model:s,error:p instanceof Error?p.message:String(p)}),l={...l,inputTokens:l.inputTokens+u.inputTokens,outputTokens:l.outputTokens+u.outputTokens,cacheReadTokens:(l.cacheReadTokens??0)+u.cacheReadTokens,cacheWriteTokens:(l.cacheWriteTokens??0)+u.cacheWriteTokens}}}return l}async resolveStreamStructuredData(e){const{schema:t,schemaJson:r,text:n,conversation:o,modelId:i,abortSignal:s,options:a}=e,l=()=>s?.aborted===!0;if(n.trim().length===0)return;const c=CZ(n,t);if(c!==void 0)return{data:c,usage:{inputTokens:0,outputTokens:0}};if(!(!o||l()))try{const u=await this.getAISDKModelWithMiddleware(a);if(!ex(u))return;h.warn(`[${this.providerName}] streamed answer is not schema-valid \u2014 re-asking once without tools`,{provider:this.providerName,model:i});const d=u.doGenerate.bind(u),p={inputTokens:0,outputTokens:0},m=(T,b)=>BO({doGenerate:d,conversation:T,toolsRecord:{},...b?{responseFormat:b}:{},maxSteps:1,...a.maxTokens?{maxOutputTokens:a.maxTokens}:{},...s?{abortSignal:s}:{},runStep:S=>S()},[]).then(S=>(p.inputTokens+=S.inputTokens,p.outputTokens+=S.outputTokens,S)),g=[...o.filter(T=>{if(T.role==="tool")return!1;const b=T.tool_calls;return!(T.role==="assistant"&&Array.isArray(b)&&b.length>0)}),{role:"assistant",content:n},{role:"user",content:"Return that same answer as a single JSON value conforming to the required schema. No prose before or after it, and no markdown code fence."}];let y;try{y=await m(g,{type:"json",schema:r})}catch(T){if(l())throw T;h.warn(`[${this.providerName}] the stream re-ask's response_format was rejected \u2014 retrying with the schema in the prompt`,{provider:this.providerName,model:i,error:T instanceof Error?T.message:String(T)}),y=await m(Qv(g,r),void 0)}const v=CZ(y.text,t);return v===void 0?(h.warn(`[${this.providerName}] the tool-free stream re-ask did not yield a schema-valid value either; leaving structuredData unset`,{provider:this.providerName,model:i}),{data:void 0,usage:p}):{data:v,usage:p}}catch(u){if(l()&&!(s?.reason instanceof Ta))throw u;h.warn(`[${this.providerName}] the tool-free structured-output re-ask failed for a stream; leaving structuredData unset`,{provider:this.providerName,model:i,error:u instanceof Error?u.message:String(u)});return}}async executeStream(e,t){this.validateStreamOptions(e);const r=Date.now(),n=this.getTimeout(e),o=wa(n,this.providerName,"stream"),i=new AbortController,s=Mbe([e.abortSignal,o?.controller.signal,i.signal]).signal;let a,l,c,u,d,p;try{a=await this.resolveModelName();const ye=!e.disableTools&&this.supportsTools();l=ye?e.tools||await this.getAllTools():{},c=ye?FO(Object.keys(l)):void 0,u=ye?eZ(l,c?.toWire):void 0,d=wRt(VO(e,l,ye),c?.toWire),p=await this.buildMessagesForStream(e)}catch(ye){throw o?.cleanup(),ye}const m=e.schema?qo(e.schema):void 0,f=!!u&&u.length>0,g=m!==void 0&&f&&this.suppressResponseFormatWithTools(),y=m&&!g?this.adjustResponseFormat(nZ({type:"json",schema:m}),a):void 0,v=this.getChatCompletionsURL(a),T=Ot(),b=e.maxSteps||ts,S=this.neurolink?.getEventEmitter(),k=[],A=[],{usagePromise:x,finishPromise:P,resolveUsage:C,resolveFinish:R}=aZ(),O=Kv(),U=this.onStreamStart(a),M=u?.map(ye=>({type:"function",name:ye.function.name,description:ye.function.description,inputSchema:ye.function.parameters})),D={prompt:p,...M?{tools:M}:{},...e.maxTokens!==void 0?{maxOutputTokens:e.maxTokens}:{},...e.temperature!==void 0?{temperature:e.temperature}:{},...e.topP!==void 0?{topP:e.topP}:{}};let $,B,q;const L=this.providerName,j={specificationVersion:"v3",provider:L,modelId:a,supportedUrls:{},doGenerate:async ye=>{const Ne=await this.getAISDKModel();if(typeof Ne=="string")throw new Error("Native model handle required");return Ne.doGenerate(ye)},doStream:async ye=>{ye?.tools!==void 0&&ye.tools!==M&&h.warn(`${L}: middleware rewrote 'tools' on the streaming path; tool rewrites are not applied to the wire request yet \u2014 the original tool list was sent.`);const Ne=Array.isArray(ye?.prompt)?ye.prompt:p,xe=QY(Ne,c?.toWire,this.replayReasoningContent());B=xe;const le={...e,...typeof ye?.maxOutputTokens=="number"?{maxTokens:ye.maxOutputTokens}:{},...typeof ye?.temperature=="number"?{temperature:ye.temperature}:{},...typeof ye?.topP=="number"?{topP:ye.topP}:{}};$=this.runStreamLoop({maxSteps:b,modelId:a,url:v,fetchImpl:T,abortSignal:s,options:le,conversation:xe,openAITools:u,openAIToolChoice:d,toolsRecord:l,toolNameFromWire:c?.fromWire,emitter:S,toolsUsed:k,toolExecutionSummaries:A,pushChunk:O.push,closeChannel:O.close,resolveUsage:C,resolveFinish:R,responseFormat:y,onModelObserved:Ie=>{q=Ie}});const Oe=$.then(()=>Promise.all([x,P]).then(([Ie,Ge])=>({type:"finish",finishReason:{unified:Ge},usage:{inputTokens:{total:Ie.promptTokens,cacheRead:Ie.cacheReadTokens},outputTokens:{total:Ie.completionTokens}}})));return Oe.catch(()=>{}),{stream:c4t(O.iterable,Oe,()=>i.abort())}}};let G;try{const ye=await this.applyMiddlewareToModel(j,e);if(typeof ye=="string")throw new Error("Native stream model handle required");const{stream:Ne}=await ye.doStream(D);G=kVr(Ne,xe=>{if(!$){const le=xe.usage.inputTokens.total??0,Oe=xe.usage.outputTokens.total??0,Ie=Math.min(xe.usage.inputTokens.cacheRead??0,le);C({promptTokens:le-Ie,completionTokens:Oe,totalTokens:le+Oe,...Ie>0?{cacheReadTokens:Ie}:{}}),R(xe.finishReason.unified)}})}catch(ye){throw i.abort(),O.close(),o?.cleanup(),ye}let J;const K=ye=>{J=ye};U?.onUsage&&x.then(U.onUsage).catch(()=>{}),U?.onFinish&&P.then(ye=>U.onFinish?.(ye,J)).catch(()=>{});const de=this.providerName,oe=this,ae={startTime:r,streamId:`${this.providerName}-${Date.now()}`},ge=async function*(){let ye=0,Ne="";try{for await(const le of G)"content"in le&&typeof le.content=="string"&&le.content.length>0&&(ye++,e.schema&&(Ne+=le.content)),yield le;await $,$||R("stop");const xe=await P;if(ae.rawFinishReason=xe,e.schema&&m){const le=await oe.resolveStreamStructuredData({schema:e.schema,schemaJson:m,text:Ne,conversation:B,modelId:a,abortSignal:s,options:e});le?.data!==void 0&&(ae.structuredData=le.data),le&&(le.usage.inputTokens>0||le.usage.outputTokens>0)&&(ae.structuredDataUsage=le.usage,h.info(`[${de}] structured-output re-ask billed separately from the streamed turn`,{provider:de,model:a,inputTokens:le.usage.inputTokens,outputTokens:le.usage.outputTokens}))}if(ae.finishReason=IZ(xe),ye===0&&k.length===0){h.warn(`${de}: Stream produced no output \u2014 emitting enriched sentinel`);const le=new xu({message:"Stream produced no output"}),Oe=await ig(le,void 0,J);sg(Oe),yield Oe}}catch(xe){if(xu.isInstance(xe)){const Oe=await ig(xe,void 0,J);sg(Oe),yield Oe;return}const le=await ig(xe,void 0,J);throw sg(le),yield le,xe}finally{$||(C({promptTokens:0,completionTokens:0,totalTokens:0}),R("stop")),o?.cleanup(),i.signal.aborted||i.abort()}},be=Date.now()-r,Ce={stream:ge(),provider:this.providerName,model:a,analytics:P.then(()=>gZ.createAnalytics(this.providerName,q??a,{textStream:(async function*(){})(),usage:x,finishReason:P},be,{requestId:e.requestId??`${this.providerName}-stream-${Date.now()}`,streamingMode:!0})),toolsUsed:k,metadata:ae};return Object.defineProperty(Ce,"model",{enumerable:!0,configurable:!0,get:()=>q??a}),Object.defineProperty(Ce,"toolExecutions",{enumerable:!0,configurable:!0,get:()=>Bd(A.map(ye=>({toolName:ye.toolName,input:ye.input,output:ye.output,duration:ye.endTime.getTime()-ye.startTime.getTime()})))}),$?.finally(()=>o?.cleanup()).catch(ye=>{K(ye)}),Ce}async runStreamLoop(e){const{maxSteps:t,modelId:r,url:n,fetchImpl:o,abortSignal:i,options:s,conversation:a,openAITools:l,openAIToolChoice:c,toolsRecord:u,toolNameFromWire:d,emitter:p,toolsUsed:m,toolExecutionSummaries:f,pushChunk:g,closeChannel:y,resolveUsage:v,resolveFinish:T,responseFormat:b,onModelObserved:S}=e;let k=null,A;const x=()=>{const P=A?.prompt_tokens??0,C=A?.completion_tokens??0,R=Math.min(A?.prompt_tokens_details?.cached_tokens??0,P),O=Math.min(Math.max(0,A?.completion_tokens_details?.reasoning_tokens??0),C);return{promptTokens:P-R,completionTokens:C,totalTokens:A?.total_tokens||P+C,...R>0?{cacheReadTokens:R}:{},...O>0?{reasoningTokens:O}:{}}};try{let P=d,C,R;for(let O=0;O<t;O++){if(l){const D=new Set(l.map(B=>P?.get(B.function.name)??B.function.name)),$=Object.fromEntries(Object.entries(u).filter(([B])=>!D.has(B)));if(Object.keys($).length>0){const B=FO(Object.keys($),new Set(l.map(q=>q.function.name)));if(B){P??=new Map;for(const[q,L]of B.fromWire)P.set(q,L)}l.push(...eZ($,B?.toWire)??[]),h.info(`${this.providerName}: ${Object.keys($).length} tool(s) hydrated mid-turn via discovery: ${Object.keys($).join(", ")}`)}}const U=sVr({conversation:a,availableInputTokens:ql(this.providerName,r,s.maxTokens??void 0),fixedOverheadTokens:XY([],l,this.providerName),provider:this.providerName,observedPromptTokens:C,previousSentEstimate:R,onSentEstimate:D=>{R=D}});U&&(a.length=0,a.push(...U));const M=await this.streamOneStep({modelId:r,url:n,fetchImpl:o,abortSignal:i,options:s,conversation:a,openAITools:l,openAIToolChoice:c,pushChunk:g,responseFormat:b});if(C=M.usage?.prompt_tokens,k=M.finishReason,M.usage&&(A=_Rt(A,M.usage)),M.model&&S?.(M.model),M.toolCalls.size===0)break;await this.executeToolBatch({stepResult:M,conversation:a,toolsRecord:u,toolNameFromWire:P,emitter:p,toolsUsed:m,toolExecutionSummaries:f,options:s})}return v(x()),T(k??"stop"),y(),{finishReason:k??"stop",usage:A}}catch(P){throw h.error(`${this.providerName}: Stream error`,{error:P instanceof Error?P.message:String(P)}),v(x()),T("error"),y(),P}}async streamOneStep(e){const t=this.resolveWireMaxTokens(e.modelId,e.options.maxTokens??void 0,e.conversation,e.openAITools),r=t!==e.options.maxTokens?{...e.options,maxTokens:t}:e.options,n=oZ(this.adjustRequestBody(iZ({modelId:e.modelId,messages:e.conversation,options:this.adjustBuildBodyOptions(e.modelId,r),tools:e.openAITools,...e.openAIToolChoice!==void 0?{toolChoice:e.openAIToolChoice}:{},streaming:!0,...e.responseFormat?{responseFormat:e.responseFormat}:{}}),e.modelId)),o=async()=>{const s=await e.fetchImpl(e.url,{method:"POST",headers:{"Content-Type":"application/json",...this.getAuthHeaders()},body:JSON.stringify(n),...e.abortSignal?{signal:e.abortSignal}:{}});if(!s.ok)throw await Zk(e.url,n,s);return s};let i;try{i=await Py(o,dt.getActiveSpan()??void 0,`${this.providerName} stream`,void 0,e.abortSignal)}catch(s){const a=s,l=a.statusCode===400?(()=>{const c=this.correctBodyAfterContextOverflow(n,a);return this.adjustBodyAfter400(c??n,a)??c})():void 0;if(!l)throw a;if(i=await e.fetchImpl(e.url,{method:"POST",headers:{"Content-Type":"application/json",...this.getAuthHeaders()},body:JSON.stringify(l),...e.abortSignal?{signal:e.abortSignal}:{}}),!i.ok)throw await Zk(e.url,l,i)}if(!i.body)throw new Error(`${this.providerName}: stream response had no body`);return sZ(i.body,s=>{e.pushChunk({content:s})},s=>{e.pushChunk({content:"",reasoning:s})})}async executeToolBatch(e){const{stepResult:t,conversation:r,toolsRecord:n,toolNameFromWire:o,emitter:i,toolsUsed:s,toolExecutionSummaries:a,options:l}=e,c=[];for(const[,d]of t.toolCalls)c.push({id:d.id,type:"function",function:{name:d.name,arguments:d.argsBuffered}});r.push({role:"assistant",content:t.text.length>0?t.text:null,tool_calls:c,...this.replayReasoningContent()&&t.reasoning?{reasoning_content:t.reasoning}:{}});for(const[,d]of t.toolCalls){const p=new Date;let m;try{m=JSON.parse(d.argsBuffered||"{}")}catch{m=d.argsBuffered}let f,g;const y=o?.get(d.name)??d.name,v=n[y]??lW(n,y);if(i?.emit("tool:start",{toolName:y,toolCallId:d.id,input:m}),!v||typeof v.execute!="function")g=`Tool '${y}' is not registered.`,f={error:g};else try{f=await v.execute(m,{})}catch(b){g=b instanceof Error?b.message:String(b),f={error:g}}const T=new Date;s.push(y),a.push({toolCallId:d.id,toolName:y,input:m,output:f,...g?{error:g}:{},startTime:p,endTime:T}),r.push({role:"tool",tool_call_id:d.id,content:YY(f)})}const u=a.slice(-t.toolCalls.size);PRt(i,u.map(d=>({toolName:d.toolName,output:d.output,...d.error?{error:d.error}:{}})));try{await this.handleToolExecutionStorage(u.map(d=>({toolCallId:d.toolCallId,toolName:d.toolName,input:d.input,output:d.output})),u.map(d=>({toolCallId:d.toolCallId,toolName:d.toolName,output:d.output})),l,new Date)}catch(d){h.warn(`[${this.constructor.name}] Failed to store tool executions`,{provider:this.providerName,error:d instanceof Error?d.message:String(d)})}}async getAvailableModels(){try{const e=`${Da(this.config.baseURL)}/models`;h.debug(`Fetching available models from: ${e}`);const t=Ot(),r=new AbortController,n=setTimeout(()=>r.abort(),5e3),o=await t(e,{headers:{...this.getAuthHeaders(),"Content-Type":"application/json"},signal:r.signal});if(clearTimeout(n),!o.ok)return h.warn(`Models endpoint returned ${o.status}: ${o.statusText}`),this.getFallbackModels();const i=await o.json();if(!i.data||!Array.isArray(i.data))return h.warn("Invalid models response format"),this.getFallbackModels();const s=i.data.map(a=>a.id).filter(Boolean);return h.shouldLog("debug")&&h.debug(`Discovered ${s.length} models:`,s),s.length>0?s:this.getFallbackModels()}catch(e){return h.warn(`[${this.constructor.name}] Failed to fetch models from endpoint:`,e),this.getFallbackModels()}}async getFirstAvailableModel(){return(await this.getAvailableModels())[0]||this.getFallbackModelName()}}}}),RZ,u4t,d4t,p4t,m4t,h4t,xVr=E({"src/lib/providers/openAI/client.ts"(){"use strict";Qt(),Ln(),pt(),z(),Nt(),sl(),Zs(),Go(),Fm(),Oa(),Ys(),Um(),zc(),kd(),RZ="https://api.openai.com/v1",u4t=(e,t)=>{const r=[e,t].map(n=>n?.trim()).find(n=>!!n&&n.length>0)??RZ;try{const n=new URL(r),o=n.pathname&&n.pathname!=="/";if(n.hostname==="api.openai.com"&&!o)return n.pathname="/v1",Da(n.toString())}catch{}return r},d4t=()=>_a(B4r()),p4t=()=>Fi("OPENAI_MODEL","gpt-5.4"),m4t=dt.getTracer("neurolink.provider.openai"),h4t=class extends Kl{constructor(e,t,r,n){const o=n?.apiKey?.trim(),i=o&&o.length>0?o:d4t(),s=u4t(n?.baseURL,process.env.OPENAI_BASE_URL);super("openai",e,t,{baseURL:s,apiKey:i}),h.debug("OpenAIProvider initialized",{model:this.modelName,providerName:this.providerName,baseURL:Yo(this.config.baseURL)})}suppressResponseFormatWithTools(){return!1}getProviderName(){return"openai"}getDefaultModel(){return p4t()}formatProviderError(e){const t=e,r=t?.type&&typeof t.type=="string"?t.type:$be(t?.responseBody),n=[{match:o=>o.statusCode===401||r==="invalid_api_key"||/API_KEY_INVALID|Invalid API key|Incorrect API key|invalid_api_key/i.test(o.message),errorClass:Wr,message:o=>/Incorrect API key|Invalid API key/i.test(o.message)?o.message:"Invalid OpenAI API key. Please check your OPENAI_API_KEY environment variable."},{match:o=>Ube(o.error),errorClass:nt,message:"OpenAI quota exhausted \u2014 this will not resolve by retrying. Check your plan and billing details at https://platform.openai.com/account/billing"},{match:o=>o.statusCode===429||r==="rate_limit_error"||/rate limit/i.test(o.message),errorClass:Qi,message:"OpenAI rate limit exceeded. Please try again later."},{match:o=>/model_not_found/i.test(o.message),errorClass:Jo,message:o=>`Model not found: ${o.modelName}`},...Ll];return ba(e,n,this.providerName,this.modelName)}onStreamStart(e){const t=m4t.startSpan("neurolink.provider.streamText",{kind:nn.CLIENT,attributes:{"gen_ai.system":"openai","gen_ai.request.model":e}});let r=!1;const n=()=>{r||(r=!0,t.end())};return{onUsage:o=>{t.setAttribute("gen_ai.usage.input_tokens",o.promptTokens+(o.cacheReadTokens??0)+(o.cacheCreationTokens??0)),t.setAttribute("gen_ai.usage.output_tokens",o.completionTokens);const i=Ls(this.providerName,e,{input:o.promptTokens,output:o.completionTokens,total:o.totalTokens,...o.cacheReadTokens?{cacheReadTokens:o.cacheReadTokens}:{},...o.cacheCreationTokens?{cacheCreationTokens:o.cacheCreationTokens}:{}});i&&i>0&&t.setAttribute("neurolink.cost",i)},onFinish:(o,i)=>{t.setAttribute("gen_ai.response.finish_reason",o||"unknown"),o==="error"&&t.setStatus({code:Ue.ERROR,message:i instanceof Error?i.message:String(i??"stream error")}),n()}}}getDefaultEmbeddingModel(){return process.env.OPENAI_EMBEDDING_MODEL||"text-embedding-3-small"}async embed(e,t){if(typeof e!="string"&&e.image)throw new nt(`${this.providerName} does not support image embeddings; provide text input`,this.providerName);const r=typeof e=="string"?e:e.text??"",n=t||this.getDefaultEmbeddingModel();h.debug("Generating embedding",{provider:this.providerName,model:n,textLength:r.length});try{const[o]=await this.callEmbeddings(n,[r],"embed");return h.debug("Embedding generated successfully",{provider:this.providerName,model:n,embeddingDimension:o.length}),o}catch(o){throw h.error("Embedding generation failed",{error:o instanceof Error?o.message:String(o),model:n,textLength:r.length}),this.handleProviderError(o)}}async embedMany(e,t){const r=t||this.getDefaultEmbeddingModel();h.debug("Generating batch embeddings",{provider:this.providerName,model:r,count:e.length});try{const n=await this.callEmbeddings(r,e,"embedMany");return h.debug("Batch embeddings generated successfully",{provider:this.providerName,model:r,count:n.length,embeddingDimension:n[0]?.length}),n}catch(n){throw h.error("Batch embedding generation failed",{error:n instanceof Error?n.message:String(n),model:r,count:e.length}),this.handleProviderError(n)}}async callEmbeddings(e,t,r){const n=`${Da(this.config.baseURL)}/embeddings`,o=Ot(),i=wa(3e4,this.providerName,"generate");try{const s=await o(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`},body:JSON.stringify({model:e,input:t.length===1?t[0]:t}),...i?.controller.signal?{signal:i.controller.signal}:{}});if(!s.ok){const c=await s.text().catch(()=>"");let u=`OpenAI ${r} failed with status ${s.status}`,d;if(c)try{const p=JSON.parse(c);p.error?.message&&(u=p.error.message),d=p.error?.type}catch{}throw Object.assign(new Error(u),{status:s.status,type:d})}const l=((await s.json()).data??[]).map(c=>c.embedding).filter(c=>Array.isArray(c));if(l.length===0)throw new nt(`OpenAI ${r} returned no embeddings`,this.providerName);return l}finally{i?.cleanup()}}async executeImageGeneration(e){const t=Date.now(),r=e.prompt??e.input?.text??"";if(!r.trim())throw new Error("OpenAI image generation requires a prompt (input.text or prompt)");const n=e.model??this.modelName,o=Da(this.config.baseURL??RZ),i=e,s=i.size??this.aspectRatioToOpenAISize(i.aspectRatio,n),a=i.numberOfImages??1;let l;n==="gpt-image-1"||n.startsWith("dall-e-3")?l=1:n.startsWith("dall-e-2")?l=Math.min(Math.max(a,1),10):l=1;const u={model:n,prompt:r,n:l,size:s};n==="gpt-image-1"?i.quality&&(u.quality=i.quality):n.startsWith("dall-e-3")?(u.response_format="b64_json",i.quality&&(u.quality=i.quality),i.style&&(u.style=i.style)):u.response_format="b64_json";const d=12e4,p=new AbortController,m=setTimeout(()=>p.abort(),d);let f;try{f=await Ot()(`${o}/images/generations`,{method:"POST",headers:{Authorization:`Bearer ${this.config.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify(u),signal:p.signal})}catch(b){throw b instanceof Error&&b.name==="AbortError"?new Error(`OpenAI image generation timed out after ${d/1e3}s`,{cause:b}):b}finally{clearTimeout(m)}if(!f.ok){const b=await f.text();throw new Error(`OpenAI image generation failed: ${f.status} \u2014 ${b}`)}const y=(await f.json()).data?.[0];if(!y)throw new Error("OpenAI image generation returned no images");let v=y.b64_json;if(!v&&y.url&&(v=(await Lm(y.url,{maxBytes:Nm,label:"OpenAI image fallback",timeoutMs:6e4})).toString("base64")),!v)throw new Error("OpenAI image generation returned neither b64_json nor a URL");const T=Date.now()-t;return h.info(`[OpenAIProvider] Generated image (${v.length} base64 chars) in ${T}ms \u2014 model ${n}`),{content:y.revised_prompt??r,provider:this.providerName,model:n,usage:{input:0,output:0,total:0},imageOutput:{base64:v}}}aspectRatioToOpenAISize(e,t){return t==="gpt-image-1"?e==="16:9"||e==="3:2"?"1536x1024":e==="9:16"||e==="2:3"?"1024x1536":"1024x1024":t.startsWith("dall-e-3")?e==="16:9"||e==="3:2"?"1792x1024":e==="9:16"||e==="2:3"?"1024x1792":"1024x1024":"1024x1024"}}}}),f4t={};Z(f4t,{OpenAIProvider:()=>h4t});var AVr=E({"src/lib/providers/openAI/index.ts"(){"use strict";xVr()}});function $e(e,t,r,n,o){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!o)throw new TypeError("Private accessor was defined without a setter");if(typeof t=="function"?e!==t||!o:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?o.call(e,r):o?o.value=r:t.set(e,r),r}function V(e,t,r,n){if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof t=="function"?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?n:r==="a"?n.call(e):n?n.value:t.get(e)}var ml=E({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/tslib.mjs"(){}}),nx,PZ=E({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/utils/uuid.mjs"(){nx=function(){const{crypto:e}=globalThis;if(e?.randomUUID)return nx=e.randomUUID.bind(e),e.randomUUID();const t=new Uint8Array(1),r=e?()=>e.getRandomValues(t)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,n=>(+n^r()&15>>+n/4).toString(16))}}});function ew(e){return typeof e=="object"&&e!==null&&("name"in e&&e.name==="AbortError"||"message"in e&&String(e.message).includes("FetchRequestCanceledException"))}var ox,tw=E({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/errors.mjs"(){ox=e=>{if(e instanceof Error)return e;if(typeof e=="object"&&e!==null){try{if(Object.prototype.toString.call(e)==="[object Error]"){const t=new Error(e.message,e.cause?{cause:e.cause}:{});return e.stack&&(t.stack=e.stack),e.cause&&!t.cause&&(t.cause=e.cause),e.name&&(t.name=e.name),t}}catch{}try{return new Error(JSON.stringify(e))}catch{}}return new Error(e)}}}),lt,Bs,Jl,rw,MZ,g4t,OZ,DZ,NZ,LZ,FZ,$Z,UZ,BZ,$o=E({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/core/error.mjs"(){tw(),lt=class extends Error{},Bs=class _me extends lt{constructor(t,r,n,o,i){super(`${_me.makeMessage(t,r,n)}`),this.status=t,this.headers=o,this.requestID=o?.get("request-id"),this.error=r,this.type=i??null}static makeMessage(t,r,n){const o=r?.message?typeof r.message=="string"?r.message:JSON.stringify(r.message):r?JSON.stringify(r):n;return t&&o?`${t} ${o}`:t?`${t} status code (no body)`:o||"(no status code or body)"}static generate(t,r,n,o){if(!t||!o)return new rw({message:n,cause:ox(r)});const i=r,s=i?.error?.type;return t===400?new OZ(t,i,n,o,s):t===401?new DZ(t,i,n,o,s):t===403?new NZ(t,i,n,o,s):t===404?new LZ(t,i,n,o,s):t===409?new FZ(t,i,n,o,s):t===422?new $Z(t,i,n,o,s):t===429?new UZ(t,i,n,o,s):t>=500?new BZ(t,i,n,o,s):new _me(t,i,n,o,s)}},Jl=class extends Bs{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},rw=class extends Bs{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}},MZ=class extends rw{constructor({message:e}={}){super({message:e??"Request timed out."})}},g4t=class extends lt{constructor(e,{cause:t}={}){super(e??"Retryable error."),t!==void 0&&(this.cause=t)}},OZ=class extends Bs{},DZ=class extends Bs{},NZ=class extends Bs{},LZ=class extends Bs{},FZ=class extends Bs{},$Z=class extends Bs{},UZ=class extends Bs{},BZ=class extends Bs{}}});function zZ(e){return typeof e!="object"?{}:e??{}}function y4t(e){if(!e)return!0;for(const t in e)return!1;return!0}function CVr(e,t){return Object.prototype.hasOwnProperty.call(e,t)}var v4t,w4t,oa,GZ,T4t,qZ,op=E({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/utils/values.mjs"(){$o(),v4t=/^[a-z][a-z0-9+.-]*:/i,w4t=e=>v4t.test(e),oa=e=>(oa=Array.isArray,oa(e)),GZ=oa,T4t=(e,t)=>{if(typeof t!="number"||!Number.isInteger(t))throw new lt(`${e} must be an integer`);if(t<0)throw new lt(`${e} must be a positive integer`);return t},qZ=e=>{try{return JSON.parse(e)}catch{return}}}}),Bm,ix=E({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/utils/sleep.mjs"(){Bm=(e,t)=>new Promise(r=>{if(t?.aborted)return r();const n=()=>{clearTimeout(o),r()},o=setTimeout(()=>{t?.removeEventListener("abort",n),r()},e);t?.addEventListener("abort",n,{once:!0})})}}),ip,HO=E({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/version.mjs"(){ip="0.102.0"}});function IVr(){return typeof Deno<"u"&&Deno.build!=null?"deno":typeof EdgeRuntime<"u"?"edge":Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]"?"node":"unknown"}function RVr(){if(typeof navigator>"u"||!navigator)return null;const e=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(const{key:t,pattern:r}of e){const n=r.exec(navigator.userAgent);if(n){const o=n[1]||0,i=n[2]||0,s=n[3]||0;return{browser:t,version:`${o}.${i}.${s}`}}}return null}var b4t,_4t,VZ,jZ,E4t,WO,HZ=E({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/detect-platform.mjs"(){HO(),b4t=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u",_4t=()=>{const e=IVr();if(e==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ip,"X-Stainless-OS":jZ(Deno.build.os),"X-Stainless-Arch":VZ(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version=="string"?Deno.version:Deno.version?.deno??"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ip,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(e==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ip,"X-Stainless-OS":jZ(globalThis.process.platform??"unknown"),"X-Stainless-Arch":VZ(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};const t=RVr();return t?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ip,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${t.browser}`,"X-Stainless-Runtime-Version":t.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ip,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}},VZ=e=>e==="x32"?"x32":e==="x86_64"||e==="x64"?"x64":e==="arm"?"arm":e==="aarch64"||e==="arm64"?"arm64":e?`other:${e}`:"unknown",jZ=e=>(e=e.toLowerCase(),e.includes("ios")?"iOS":e==="android"?"Android":e==="darwin"?"MacOS":e==="win32"?"Windows":e==="freebsd"?"FreeBSD":e==="openbsd"?"OpenBSD":e==="linux"?"Linux":e?`Other:${e}`:"Unknown"),WO=()=>E4t??(E4t=_4t())}});function PVr(){if(typeof fetch<"u")return fetch;throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new Anthropic({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function S4t(...e){const t=globalThis.ReadableStream;if(typeof t>"u")throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new t(...e)}function k4t(e){let t=Symbol.asyncIterator in e?e[Symbol.asyncIterator]():e[Symbol.iterator]();return S4t({start(){},async pull(r){const{done:n,value:o}=await t.next();n?r.close():r.enqueue(o)},async cancel(){await t.return?.()}})}function WZ(e){if(e[Symbol.asyncIterator])return e;const t=e.getReader();return{async next(){try{const r=await t.read();return r?.done&&t.releaseLock(),r}catch(r){throw t.releaseLock(),r}},async return(){const r=t.cancel();return t.releaseLock(),await r,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function MVr(e){if(e===null||typeof e!="object")return;if(e[Symbol.asyncIterator]){await e[Symbol.asyncIterator]().return?.();return}const t=e.getReader(),r=t.cancel();t.releaseLock(),await r}var sx=E({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/shims.mjs"(){}}),x4t,OVr=E({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/request-options.mjs"(){x4t=({headers:e,body:t})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(t)})}}),KZ,JZ,XZ,A4t,C4t=E({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/qs/formats.mjs"(){KZ="RFC3986",JZ=e=>String(e),XZ={RFC1738:e=>String(e).replace(/%20/g,"+"),RFC3986:JZ},A4t="RFC1738"}});function DVr(e){return!e||typeof e!="object"?!1:!!(e.constructor&&e.constructor.isBuffer&&e.constructor.isBuffer(e))}function I4t(e,t){if(oa(e)){const r=[];for(let n=0;n<e.length;n+=1)r.push(t(e[n]));return r}return t(e)}var KO,Gc,JO,R4t,NVr=E({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/qs/utils.mjs"(){C4t(),op(),KO=(e,t)=>(KO=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),KO(e,t)),Gc=(()=>{const e=[];for(let t=0;t<256;++t)e.push("%"+((t<16?"0":"")+t.toString(16)).toUpperCase());return e})(),JO=1024,R4t=(e,t,r,n,o)=>{if(e.length===0)return e;let i=e;if(typeof e=="symbol"?i=Symbol.prototype.toString.call(e):typeof e!="string"&&(i=String(e)),r==="iso-8859-1")return escape(i).replace(/%u[0-9a-f]{4}/gi,function(a){return"%26%23"+parseInt(a.slice(2),16)+"%3B"});let s="";for(let a=0;a<i.length;a+=JO){const l=i.length>=JO?i.slice(a,a+JO):i,c=[];for(let u=0;u<l.length;++u){let d=l.charCodeAt(u);if(d===45||d===46||d===95||d===126||d>=48&&d<=57||d>=65&&d<=90||d>=97&&d<=122||o===A4t&&(d===40||d===41)){c[c.length]=l.charAt(u);continue}if(d<128){c[c.length]=Gc[d];continue}if(d<2048){c[c.length]=Gc[192|d>>6]+Gc[128|d&63];continue}if(d<55296||d>=57344){c[c.length]=Gc[224|d>>12]+Gc[128|d>>6&63]+Gc[128|d&63];continue}u+=1,d=65536+((d&1023)<<10|l.charCodeAt(u)&1023),c[c.length]=Gc[240|d>>18]+Gc[128|d>>12&63]+Gc[128|d>>6&63]+Gc[128|d&63]}s+=c.join("")}return s}}});function LVr(e){return typeof e=="string"||typeof e=="number"||typeof e=="boolean"||typeof e=="symbol"||typeof e=="bigint"}function P4t(e,t,r,n,o,i,s,a,l,c,u,d,p,m,f,g,y,v){let T=e,b=v,S=0,k=!1;for(;(b=b.get(XO))!==void 0&&!k;){const R=b.get(e);if(S+=1,typeof R<"u"){if(R===S)throw new RangeError("Cyclic object value");k=!0}typeof b.get(XO)>"u"&&(S=0)}if(typeof c=="function"?T=c(t,T):T instanceof Date?T=p?.(T):r==="comma"&&oa(T)&&(T=I4t(T,function(R){return R instanceof Date?p?.(R):R})),T===null){if(i)return l&&!g?l(t,ki.encoder,y,"key",m):t;T=""}if(LVr(T)||DVr(T)){if(l){const R=g?t:l(t,ki.encoder,y,"key",m);return[f?.(R)+"="+f?.(l(T,ki.encoder,y,"value",m))]}return[f?.(t)+"="+f?.(String(T))]}const A=[];if(typeof T>"u")return A;let x;if(r==="comma"&&oa(T))g&&l&&(T=I4t(T,l)),x=[{value:T.length>0?T.join(",")||null:void 0}];else if(oa(c))x=c;else{const R=Object.keys(T);x=u?R.sort(u):R}const P=a?String(t).replace(/\./g,"%2E"):String(t),C=n&&oa(T)&&T.length===1?P+"[]":P;if(o&&oa(T)&&T.length===0)return C+"[]";for(let R=0;R<x.length;++R){const O=x[R],U=typeof O=="object"&&typeof O.value<"u"?O.value:T[O];if(s&&U===null)continue;const M=d&&a?O.replace(/\./g,"%2E"):O,D=oa(T)?typeof r=="function"?r(C,M):C:C+(d?"."+M:"["+M+"]");v.set(e,S);const $=new WeakMap;$.set(XO,v),ZZ(A,P4t(U,D,r,n,o,i,s,a,r==="comma"&&g&&oa(T)?null:l,c,u,d,p,m,f,g,y,$))}return A}function FVr(e=ki){if(typeof e.allowEmptyArrays<"u"&&typeof e.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof e.encodeDotInKeys<"u"&&typeof e.encodeDotInKeys!="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(e.encoder!==null&&typeof e.encoder<"u"&&typeof e.encoder!="function")throw new TypeError("Encoder has to be a function.");const t=e.charset||ki.charset;if(typeof e.charset<"u"&&e.charset!=="utf-8"&&e.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let r=KZ;if(typeof e.format<"u"){if(!KO(XZ,e.format))throw new TypeError("Unknown format option provided.");r=e.format}const n=XZ[r];let o=ki.filter;(typeof e.filter=="function"||oa(e.filter))&&(o=e.filter);let i;if(e.arrayFormat&&e.arrayFormat in YZ?i=e.arrayFormat:"indices"in e?i=e.indices?"indices":"repeat":i=ki.arrayFormat,"commaRoundTrip"in e&&typeof e.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");const s=typeof e.allowDots>"u"?e.encodeDotInKeys?!0:ki.allowDots:!!e.allowDots;return{addQueryPrefix:typeof e.addQueryPrefix=="boolean"?e.addQueryPrefix:ki.addQueryPrefix,allowDots:s,allowEmptyArrays:typeof e.allowEmptyArrays=="boolean"?!!e.allowEmptyArrays:ki.allowEmptyArrays,arrayFormat:i,charset:t,charsetSentinel:typeof e.charsetSentinel=="boolean"?e.charsetSentinel:ki.charsetSentinel,commaRoundTrip:!!e.commaRoundTrip,delimiter:typeof e.delimiter>"u"?ki.delimiter:e.delimiter,encode:typeof e.encode=="boolean"?e.encode:ki.encode,encodeDotInKeys:typeof e.encodeDotInKeys=="boolean"?e.encodeDotInKeys:ki.encodeDotInKeys,encoder:typeof e.encoder=="function"?e.encoder:ki.encoder,encodeValuesOnly:typeof e.encodeValuesOnly=="boolean"?e.encodeValuesOnly:ki.encodeValuesOnly,filter:o,format:r,formatter:n,serializeDate:typeof e.serializeDate=="function"?e.serializeDate:ki.serializeDate,skipNulls:typeof e.skipNulls=="boolean"?e.skipNulls:ki.skipNulls,sort:typeof e.sort=="function"?e.sort:null,strictNullHandling:typeof e.strictNullHandling=="boolean"?e.strictNullHandling:ki.strictNullHandling}}function $Vr(e,t={}){let r=e;const n=FVr(t);let o,i;typeof n.filter=="function"?(i=n.filter,r=i("",r)):oa(n.filter)&&(i=n.filter,o=i);const s=[];if(typeof r!="object"||r===null)return"";const a=YZ[n.arrayFormat],l=a==="comma"&&n.commaRoundTrip;o||(o=Object.keys(r)),n.sort&&o.sort(n.sort);const c=new WeakMap;for(let p=0;p<o.length;++p){const m=o[p];n.skipNulls&&r[m]===null||ZZ(s,P4t(r[m],m,a,l,n.allowEmptyArrays,n.strictNullHandling,n.skipNulls,n.encodeDotInKeys,n.encode?n.encoder:null,n.filter,n.sort,n.allowDots,n.serializeDate,n.format,n.formatter,n.encodeValuesOnly,n.charset,c))}const u=s.join(n.delimiter);let d=n.addQueryPrefix===!0?"?":"";return n.charsetSentinel&&(n.charset==="iso-8859-1"?d+="utf8=%26%2310003%3B&":d+="utf8=%E2%9C%93&"),u.length>0?d+u:""}var YZ,ZZ,M4t,ki,XO,UVr=E({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/qs/stringify.mjs"(){NVr(),C4t(),op(),YZ={brackets(e){return String(e)+"[]"},comma:"comma",indices(e,t){return String(e)+"["+t+"]"},repeat(e){return String(e)}},ZZ=function(e,t){Array.prototype.push.apply(e,oa(t)?t:[t])},ki={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:R4t,encodeValuesOnly:!1,format:KZ,formatter:JZ,indices:!1,serializeDate(e){return(M4t??(M4t=Function.prototype.call.bind(Date.prototype.toISOString)))(e)},skipNulls:!1,strictNullHandling:!1},XO={}}});function BVr(e){return $Vr(e,{arrayFormat:"brackets"})}var O4t=E({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/utils/query.mjs"(){UVr()}});function D4t(e){if(!e)return;let t;try{t=new URL(e)}catch(n){throw new Xn(`Invalid token endpoint base URL "${e}": ${n}`)}if(t.protocol==="https:")return;const r=t.hostname.toLowerCase().replace(/^\[|\]$/g,"");if(!(t.protocol==="http:"&&(r==="localhost"||r==="127.0.0.1"||r==="::1")))throw new Xn(`Refusing to send credential over non-https token endpoint "${e}"`)}async function N4t(e,t){const r=await zVr(e);let n;try{n=JSON.parse(r)}catch{throw new Xn(`Token endpoint returned non-JSON response (status ${e.status})`,e.status,Xl(r),t)}if(!n.access_token)throw new Xn(`Token endpoint response missing access_token: ${JSON.stringify(Xl(n))}`,e.status,Xl(n),t);if(n.token_type&&n.token_type.toLowerCase()!=="bearer")throw new Xn(`Token endpoint response: unsupported token_type "${n.token_type}" (want Bearer)`,e.status,Xl(n),t);return n}function Xl(e){if(e==null)return e;if(typeof e=="string"){let t;try{t=JSON.parse(e)}catch{return e.length<=ZO?e:e.slice(0,ZO)+`... <${e.length-ZO} more chars>`}return JSON.stringify(Xl(t))}if(typeof e=="object"&&!Array.isArray(e)){const t={};for(const[r,n]of Object.entries(e))q4t.has(r)&&(t[r]=n);return t}return null}async function L4t(e,t=r=>console.warn(`anthropic-sdk: ${r}`)){if(typeof process>"u"||process.platform==="win32")return;const r=await Promise.resolve().then(()=>(Sn(),Id));let n=e,o;try{n=await r.promises.realpath(e),o=await r.promises.stat(n)}catch{return}const i=o.mode&511;if(i&18)throw new Xn(`Credentials file at ${n} is group/world-writable (mode 0o${i.toString(8)}); this allows other local users to plant tokens. Run \`chmod 600 ${n}\`.`);if(i&36)throw new Xn(`Credentials file at ${n} is group/world-readable (mode 0o${i.toString(8)}); run \`chmod 600 ${n}\` before retrying.`);typeof process.getuid=="function"&&o.uid!==process.getuid()&&t(`credentials file at ${n} is owned by uid ${o.uid} (current process uid ${process.getuid()}); verify this is intentional.`)}async function F4t(e,t){const r=await Promise.resolve().then(()=>(Sn(),Id)),o=(await Promise.resolve().then(()=>(qt(),um))).dirname(e);await r.promises.mkdir(o,{recursive:!0,mode:448});const i=`${e}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;try{const s=await r.promises.open(i,"w",384);try{await s.writeFile(JSON.stringify(t,null,2)),await s.sync()}finally{await s.close()}await r.promises.rename(i,e)}catch(s){throw await r.promises.unlink(i).catch(()=>{}),s}try{const s=await r.promises.open(o,"r");try{await s.sync()}finally{await s.close()}}catch{}}async function zVr(e){if(!e.body)return"";const t=e.body.getReader(),r=[];let n=0;for(;;){const{done:i,value:s}=await t.read();if(i)break;if(n+s.length>eQ){const a=eQ-n;a>0&&r.push(s.subarray(0,a)),await t.cancel();break}r.push(s),n+=s.length}let o;if(r.length===1)o=r[0];else{o=new Uint8Array(r.reduce((s,a)=>s+a.length,0));let i=0;for(const s of r)o.set(s,i),i+=s.length}return new TextDecoder("utf-8").decode(o)}var $4t,U4t,QZ,ax,B4t,z4t,YO,G4t,eQ,ZO,q4t,Xn,lx=E({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/lib/credentials/types.mjs"(){$o(),$4t="urn:ietf:params:oauth:grant-type:jwt-bearer",U4t="refresh_token",QZ="/v1/oauth/token",ax="oauth-2025-04-20",B4t="oidc-federation-2026-04-01",z4t=120,YO=30,G4t=5,eQ=1<<20,ZO=2e3,q4t=new Set(["error","error_description","error_uri"]),Xn=class extends lt{constructor(e,t=null,r=null,n=null){super(e),this.statusCode=t,this.body=r,this.requestId=n}}}});function bg(){return Math.floor(Date.now()/1e3)}var QO=E({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/utils/time.mjs"(){}}),V4t,GVr=E({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/lib/credentials/token-cache.mjs"(){lx(),QO(),V4t=class{constructor(e,t){this.cached=null,this.pendingRefresh=null,this.nextForce=!1,this.lastAdvisoryError=0,this.provider=e,this.onAdvisoryRefreshError=t}async getToken(){const e=this.nextForce;this.nextForce=!1;const t=this.cached;if(e||t==null)return(await this.refresh(e)).token;if(t.expiresAt==null)return t.token;const r=t.expiresAt-bg();return r>z4t?t.token:r>YO?(this.backgroundRefresh(),t.token):(await this.refresh()).token}invalidate(){this.cached=null,this.nextForce=!0}refresh(e=!1){return this.pendingRefresh&&!e?this.pendingRefresh:this.doRefresh(e)}backgroundRefresh(){this.pendingRefresh||bg()-this.lastAdvisoryError<G4t||this.doRefresh().catch(e=>{this.lastAdvisoryError=bg(),this.onAdvisoryRefreshError?.(e)})}doRefresh(e=!1){return this.pendingRefresh=this.provider(e?{forceRefresh:!0}:void 0).then(t=>(this.cached=t,this.pendingRefresh=null,t),t=>{throw this.pendingRefresh=null,t}),this.pendingRefresh}}}}),Fr,eD=E({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/utils/env.mjs"(){Fr=e=>{if(typeof globalThis.process<"u")return globalThis.process.env?.[e]?.trim()||void 0;if(typeof globalThis.Deno<"u")return globalThis.Deno.env?.get?.(e)?.trim()||void 0}}});function qVr(e){let t=0;for(const o of e)t+=o.length;const r=new Uint8Array(t);let n=0;for(const o of e)r.set(o,n),n+=o.length;return r}function tQ(e){let t;return(H4t??(t=new globalThis.TextEncoder,H4t=t.encode.bind(t)))(e)}function j4t(e){let t;return(W4t??(t=new globalThis.TextDecoder,W4t=t.decode.bind(t)))(e)}var H4t,W4t,rQ=E({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/utils/bytes.mjs"(){}}),VVr=E({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/utils/base64.mjs"(){$o(),rQ()}});function cx(){}function tD(e,t,r){return!t||ux[e]>ux[r]?cx:t[e].bind(t)}function Uo(e){const t=e.logger,r=e.logLevel??"off";if(!t)return K4t;const n=oQ.get(t);if(n&&n[0]===r)return n[1];const o={error:tD("error",t,r),warn:tD("warn",t,r),info:tD("info",t,r),debug:tD("debug",t,r)};return oQ.set(t,[r,o]),o}var ux,nQ,K4t,oQ,sp,zm=E({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/utils/log.mjs"(){op(),ux={off:0,error:200,warn:300,info:400,debug:500},nQ=(e,t,r)=>{if(e){if(CVr(ux,e))return e;Uo(r).warn(`${t} was set to ${JSON.stringify(e)}, expected one of ${JSON.stringify(Object.keys(ux))}`)}},K4t={error:cx,warn:cx,info:cx,debug:cx},oQ=new WeakMap,sp=e=>(e.options&&(e.options={...e.options},delete e.options.headers),e.headers&&(e.headers=Object.fromEntries((e.headers instanceof Headers?[...e.headers]:Object.entries(e.headers)).map(([t,r])=>[t,t.toLowerCase()==="authorization"||t.toLowerCase()==="api-key"||t.toLowerCase()==="x-api-key"||t.toLowerCase()==="cookie"||t.toLowerCase()==="set-cookie"?"***":r]))),"retryOfRequestLogID"in e&&(e.retryOfRequestLogID&&(e.retryOf=e.retryOfRequestLogID),delete e.retryOfRequestLogID),e)}}),J4t=E({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/utils.mjs"(){op(),VVr(),eD(),zm(),PZ(),ix(),O4t()}});function X4t(e){if(!e)throw new Error("profile name is empty");if(e==="."||e==="..")throw new Error(`profile name "${e}" is not allowed`);if(e.includes("/")||e.includes("\\"))throw new Error(`profile name "${e}" must not contain path separators`);if(!Y4t.test(e))throw new Error(`profile name "${e}" contains disallowed characters (allowed: letters, digits, '_', '.', '-')`)}var iQ,Y4t,Z4t,Q4t,rD,ePt,sQ,tPt=E({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/core/credentials.mjs"(){HZ(),J4t(),iQ="1.0",Y4t=/^[A-Za-z0-9_.-]+$/,Z4t=async e=>{var t,r;const n=await rD();if(n===null)return null;const o=e??await sQ();if(o===null)return null;X4t(o);const i=await Promise.resolve().then(()=>(Sn(),Id)),a=(await Promise.resolve().then(()=>(qt(),um))).join(n,"configs",`${o}.json`);let l;try{l=await i.promises.readFile(a,"utf-8")}catch(d){if(d?.code!=="ENOENT")throw new Error(`failed to read config file ${a}: ${d}`);l=null}if(l===null){const d=Fr("ANTHROPIC_ORGANIZATION_ID"),p=Fr("ANTHROPIC_IDENTITY_TOKEN_FILE"),m=Fr("ANTHROPIC_FEDERATION_RULE_ID");return m&&d?{fromFile:!1,config:{organization_id:d,workspace_id:Fr("ANTHROPIC_WORKSPACE_ID"),base_url:Fr("ANTHROPIC_BASE_URL"),authentication:{type:"oidc_federation",federation_rule_id:m,service_account_id:Fr("ANTHROPIC_SERVICE_ACCOUNT_ID"),identity_token:p?{source:"file",path:p}:void 0,scope:Fr("ANTHROPIC_SCOPE")}}}:null}let c;try{c=JSON.parse(l)}catch(d){throw new Error(`failed to parse config file ${a}: ${d}`)}if(!c.authentication)throw new Error(`config file ${a} is missing "authentication"`);const u=c.authentication.type;if(u!=="oidc_federation"&&u!=="user_oauth")throw new Error(`authentication.type "${u}" is not a known authentication type`);if(c.organization_id??(c.organization_id=Fr("ANTHROPIC_ORGANIZATION_ID")),c.workspace_id??(c.workspace_id=Fr("ANTHROPIC_WORKSPACE_ID")),c.base_url??(c.base_url=Fr("ANTHROPIC_BASE_URL")),(t=c.authentication).scope??(t.scope=Fr("ANTHROPIC_SCOPE")),c.authentication.type==="oidc_federation"){if(!c.authentication.identity_token){const d=Fr("ANTHROPIC_IDENTITY_TOKEN_FILE");d&&(c.authentication.identity_token={source:"file",path:d})}c.authentication.federation_rule_id||(c.authentication.federation_rule_id=Fr("ANTHROPIC_FEDERATION_RULE_ID")??""),(r=c.authentication).service_account_id??(r.service_account_id=Fr("ANTHROPIC_SERVICE_ACCOUNT_ID"))}return{config:c,fromFile:!0}},Q4t=async(e,t)=>{if(e?.authentication.credentials_path)return e.authentication.credentials_path;const r=await rD();if(!r)return null;const n=t??await sQ();return n?(X4t(n),(await Promise.resolve().then(()=>(qt(),um))).join(r,"credentials",`${n}.json`)):null},rD=async()=>{if(!ePt())return null;const e=await Promise.resolve().then(()=>(qt(),um)),t=Fr("ANTHROPIC_CONFIG_DIR");if(t)return t;if(WO()["X-Stainless-OS"]==="Windows"){const i=Fr("APPDATA");if(i)return e.join(i,"Anthropic");const s=Fr("USERPROFILE");return s?e.join(s,"AppData","Roaming","Anthropic"):null}const n=Fr("XDG_CONFIG_HOME");if(n)return e.join(n,"anthropic");const o=Fr("HOME");return o?e.join(o,".config","anthropic"):null},ePt=()=>{const e=WO()["X-Stainless-Runtime"];return e==="node"||e==="deno"},sQ=async()=>{const e=await rD();if(!e)return null;const t=Fr("ANTHROPIC_PROFILE");if(t)return t;const r=await Promise.resolve().then(()=>(Sn(),Id)),o=(await Promise.resolve().then(()=>(qt(),um))).join(e,"active_config");try{return(await r.promises.readFile(o,"utf-8")).trim()||"default"}catch(i){if(i?.code!=="ENOENT")throw new Error(`failed to read ${o}: ${i}`);return"default"}}}});function rPt(e){if(!e)throw new lt("Identity token file path is empty");return async()=>{const t=await Promise.resolve().then(()=>(Sn(),Id));let r;try{r=await t.promises.readFile(e,"utf-8")}catch(o){throw new lt(`Failed to read identity token file at ${e}: ${o}`)}const n=r.trim();if(!n)throw new lt(`Identity token file at ${e} is empty`);return n}}function jVr(e){if(!e)throw new lt("Identity token value is empty");return()=>e}var HVr=E({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/lib/credentials/identity-token.mjs"(){$o()}});function WVr(e){return async()=>{D4t(e.baseURL);const t=await e.identityTokenProvider();if(t.length>16*1024)throw new Xn(`Identity token is ${Math.ceil(t.length/1024)} KiB, exceeds the 16 KiB assertion limit`);const r={grant_type:$4t,assertion:t,federation_rule_id:e.federationRuleId,organization_id:e.organizationId};e.serviceAccountId&&(r.service_account_id=e.serviceAccountId),e.workspaceId&&(r.workspace_id=e.workspaceId);const n=`${e.baseURL}${QZ}`;let o;try{o=await e.fetch(n,{method:"POST",headers:{"Content-Type":"application/json","anthropic-beta":`${ax},${B4t}`,"User-Agent":e.userAgent||`anthropic-sdk-typescript/${ip} oidcFederationProvider`},body:JSON.stringify(r)})}catch(l){throw new Xn(`Failed to reach token endpoint ${n}: ${l}`)}const i=o.headers.get("Request-Id");if(!o.ok){const l=await o.text().catch(()=>""),c=Xl(l);let u="";throw o.status===401&&(u=` Ensure your federation rule matches your identity token. ${e.workspaceId?"":"If your federation rule is scoped to multiple workspaces, set the ANTHROPIC_WORKSPACE_ID environment variable, the 'workspace_id' config key, or the `workspaceId` option. "}View your authentication events in the Workload identity page of Claude Console for more details.`),new Xn(`Token exchange failed with status ${o.status}${i?` (request-id ${i})`:""}: ${c}${u}`,o.status,c,i)}const s=await N4t(o,i),a=Number(s.expires_in);if(!Number.isFinite(a))throw new Xn(`Token endpoint response missing required fields: ${JSON.stringify(Xl(s))}`,o.status,Xl(s),i);return{token:s.access_token,expiresAt:bg()+a}}}var KVr=E({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/lib/credentials/oidc-federation.mjs"(){lx(),QO(),HO()}});function JVr(e){return async t=>{const r=await Promise.resolve().then(()=>(Sn(),Id));await L4t(e.credentialsPath,e.onSafetyWarning);let n;try{n=await r.promises.readFile(e.credentialsPath,"utf-8")}catch(y){throw new Xn(`Credentials file not found at ${e.credentialsPath}: ${y}`)}let o;try{o=JSON.parse(n)}catch(y){throw new Xn(`Credentials file at ${e.credentialsPath} is not valid JSON: ${y}`)}const i=o.access_token;if(!i)throw new Xn(`Credentials file at ${e.credentialsPath} must include 'access_token'`);const s=o.expires_at;if(!t?.forceRefresh&&(s==null||bg()<s-YO))return{token:i,expiresAt:s??null};const a=o.refresh_token;if(!e.clientId||!a)throw new Xn(`Access token at ${e.credentialsPath} has expired and no refresh is available (client_id ${e.clientId?"set":"empty"}, refresh_token ${a?"set":"empty"})`);D4t(e.baseURL);const l={grant_type:U4t,refresh_token:a,client_id:e.clientId},c=`${e.baseURL}${QZ}`;let u;try{u=await e.fetch(c,{method:"POST",headers:{"Content-Type":"application/json","anthropic-beta":ax,"User-Agent":e.userAgent||`anthropic-sdk-typescript/${ip} userOAuthProvider`},body:JSON.stringify(l)})}catch(y){throw new Xn(`User OAuth refresh failed to reach token endpoint: ${y}`)}const d=u.headers.get("Request-Id");if(!u.ok){const y=await u.text().catch(()=>"");throw new Xn(`User OAuth refresh failed (HTTP ${u.status}): ${Xl(y)}`,u.status,Xl(y),d)}const p=await N4t(u,d),m=Number(p.expires_in);if(!Number.isFinite(m))throw new Xn(`User OAuth refresh response missing or invalid expires_in: ${JSON.stringify(Xl(p))}`,u.status,Xl(p),d);const f=bg()+m,g=p.refresh_token||a;return await F4t(e.credentialsPath,{...o,version:iQ,type:"oauth_token",access_token:p.access_token,expires_at:f,refresh_token:g}),{token:p.access_token,expiresAt:f}}}var XVr=E({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/lib/credentials/user-oauth.mjs"(){tPt(),lx(),QO(),HO()}});function nPt(e,t){const r=e.authentication.credentials_path??null,n=(e.base_url||t.baseURL).replace(/\/+$/,""),o=ZVr(e,r,n,t),i={};return e.workspace_id&&e.authentication.type==="user_oauth"&&(i["anthropic-workspace-id"]=e.workspace_id),{provider:o,extraHeaders:i,baseURL:e.base_url||void 0}}async function YVr(e,t){const r=await Z4t(t);if(!r)return null;const{config:n,fromFile:o}=r,i=n.authentication.credentials_path||!o?n:{...n,authentication:{...n.authentication,credentials_path:await Q4t(n,t)??void 0}};return nPt(i,e)}function ZVr(e,t,r,n){switch(e.authentication.type){case"oidc_federation":{const o=e.authentication,i=QVr(o);if(!i)throw new Xn("oidc_federation config requires an identity token (set authentication.identity_token, ANTHROPIC_IDENTITY_TOKEN_FILE, or ANTHROPIC_IDENTITY_TOKEN)");if(!o.federation_rule_id)throw new Xn("oidc_federation config requires 'federation_rule_id'. Set it in authentication.federation_rule_id in your profile, or via ANTHROPIC_FEDERATION_RULE_ID (profile takes precedence).");if(!e.organization_id)throw new Xn("oidc_federation config requires organization_id (set ANTHROPIC_ORGANIZATION_ID or config.organization_id)");const s=WVr({identityTokenProvider:i,federationRuleId:o.federation_rule_id,organizationId:e.organization_id,serviceAccountId:o.service_account_id,workspaceId:e.workspace_id,baseURL:r,fetch:n.fetch,userAgent:n.userAgent});return t?ejr(s,t,n.onCacheWriteError,n.onSafetyWarning):s}case"user_oauth":{if(!t)throw new Xn("user_oauth config requires authentication.credentials_path (or load via a profile so it defaults to <config_dir>/credentials/<profile>.json)");return JVr({credentialsPath:t,clientId:e.authentication.client_id,baseURL:r,fetch:n.fetch,userAgent:n.userAgent,onSafetyWarning:n.onSafetyWarning})}default:{const o=e.authentication.type;throw new Xn(`authentication.type "${o}" is not a known authentication type`)}}}function QVr(e){if(e.identity_token){const n=e.identity_token.source;if(n!=="file")throw new Xn(`identity_token.source "${n}" is not supported by this SDK version (only "file")`);if(!e.identity_token.path)throw new Xn('identity_token.source "file" requires a non-empty path');return rPt(e.identity_token.path)}const t=Fr("ANTHROPIC_IDENTITY_TOKEN_FILE");if(t)return rPt(t);const r=Fr("ANTHROPIC_IDENTITY_TOKEN");return r?jVr(r):null}function ejr(e,t,r,n){return async o=>{const i=await Promise.resolve().then(()=>(Sn(),Id));await L4t(t,n);let s;try{const l=await i.promises.readFile(t,"utf-8");s=JSON.parse(l);const c=s?.access_token;if(c&&!o?.forceRefresh){const u=s?.expires_at;if(u==null||bg()<u-YO)return{token:c,expiresAt:u??null}}}catch(l){l?.code!=="ENOENT"&&!(l instanceof SyntaxError)&&r?.(l)}const a=await e(o);try{await F4t(t,{...s??{},version:iQ,type:"oauth_token",access_token:a.token,expires_at:a.expiresAt})}catch(l){r?.(l)}return a}}var tjr=E({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/lib/credentials/credential-chain.mjs"(){eD(),tPt(),lx(),QO(),HVr(),KVr(),XVr()}});function rjr(e,t){for(let o=t??0;o<e.length;o++){if(e[o]===10)return{preceding:o,index:o+1,carriage:!1};if(e[o]===13)return{preceding:o,index:o+1,carriage:!0}}return null}function njr(e){for(let n=0;n<e.length-1;n++){if(e[n]===10&&e[n+1]===10||e[n]===13&&e[n+1]===13)return n+2;if(e[n]===13&&e[n+1]===10&&n+3<e.length&&e[n+2]===13&&e[n+3]===10)return n+4}return-1}var hl,fl,nw,oPt=E({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/decoders/line.mjs"(){ml(),rQ(),nw=class{constructor(){hl.set(this,void 0),fl.set(this,void 0),$e(this,hl,new Uint8Array,"f"),$e(this,fl,null,"f")}decode(e){if(e==null)return[];const t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?tQ(e):e;$e(this,hl,qVr([V(this,hl,"f"),t]),"f");const r=[];let n;for(;(n=rjr(V(this,hl,"f"),V(this,fl,"f")))!=null;){if(n.carriage&&V(this,fl,"f")==null){$e(this,fl,n.index,"f");continue}if(V(this,fl,"f")!=null&&(n.index!==V(this,fl,"f")+1||n.carriage)){r.push(j4t(V(this,hl,"f").subarray(0,V(this,fl,"f")-1))),$e(this,hl,V(this,hl,"f").subarray(V(this,fl,"f")),"f"),$e(this,fl,null,"f");continue}const o=V(this,fl,"f")!==null?n.preceding-1:n.preceding,i=j4t(V(this,hl,"f").subarray(0,o));r.push(i),$e(this,hl,V(this,hl,"f").subarray(n.index),"f"),$e(this,fl,null,"f")}return r}flush(){return V(this,hl,"f").length?this.decode(`
|
|
1054
1054
|
`):[]}},hl=new WeakMap,fl=new WeakMap,nw.NEWLINE_CHARS=new Set([`
|
|
1055
1055
|
`,"\r"]),nw.NEWLINE_REGEXP=/\r\n|[\n\r]/g}});async function*ojr(e,t){if(!e.body)throw t.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new lt("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api"):new lt("Attempted to iterate over a response with no body");const r=new iPt,n=new nw,o=WZ(e.body);for await(const i of ijr(o))for(const s of n.decode(i)){const a=r.decode(s);a&&(yield a)}for(const i of n.flush()){const s=r.decode(i);s&&(yield s)}}async function*ijr(e){let t=new Uint8Array;for await(const r of e){if(r==null)continue;const n=r instanceof ArrayBuffer?new Uint8Array(r):typeof r=="string"?tQ(r):r;let o=new Uint8Array(t.length+n.length);o.set(t),o.set(n,t.length),t=o;let i;for(;(i=njr(t))!==-1;)yield t.slice(0,i),t=t.slice(i)}t.length>0&&(yield t)}function sjr(e,t){const r=e.indexOf(t);return r!==-1?[e.substring(0,r),t,e.substring(r+t.length)]:[e,"",""]}var dx,_g,iPt,aQ=E({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/core/streaming.mjs"(){ml(),$o(),sx(),oPt(),sx(),tw(),op(),rQ(),zm(),$o(),_g=class K1{constructor(t,r,n){this.iterator=t,dx.set(this,void 0),this.controller=r,$e(this,dx,n,"f")}static fromSSEResponse(t,r,n){let o=!1;const i=n?Uo(n):console;async function*s(){if(o)throw new lt("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");o=!0;let a=!1;try{for await(const l of ojr(t,r)){if(l.event==="completion")try{yield JSON.parse(l.data)}catch(c){throw i.error("Could not parse message into JSON:",l.data),i.error("From chunk:",l.raw),c}if(l.event==="message_start"||l.event==="message_delta"||l.event==="message_stop"||l.event==="content_block_start"||l.event==="content_block_delta"||l.event==="content_block_stop"||l.event==="message"||l.event==="user.message"||l.event==="user.interrupt"||l.event==="user.tool_confirmation"||l.event==="user.custom_tool_result"||l.event==="user.tool_result"||l.event==="agent.message"||l.event==="agent.thinking"||l.event==="agent.tool_use"||l.event==="agent.tool_result"||l.event==="agent.mcp_tool_use"||l.event==="agent.mcp_tool_result"||l.event==="agent.custom_tool_use"||l.event==="agent.thread_context_compacted"||l.event==="session.status_running"||l.event==="session.status_idle"||l.event==="session.status_rescheduled"||l.event==="session.status_terminated"||l.event==="session.error"||l.event==="session.deleted"||l.event==="session.updated"||l.event==="span.model_request_start"||l.event==="span.model_request_end"||l.event==="span.outcome_evaluation_start"||l.event==="span.outcome_evaluation_ongoing"||l.event==="span.outcome_evaluation_end"||l.event==="user.define_outcome"||l.event==="agent.thread_message_received"||l.event==="agent.thread_message_sent"||l.event==="agent.session_thread_message_received"||l.event==="agent.session_thread_message_sent"||l.event==="session.thread_created"||l.event==="session.thread_status_created"||l.event==="session.thread_status_running"||l.event==="session.thread_status_idle"||l.event==="session.thread_status_rescheduled"||l.event==="session.thread_status_terminated")try{yield JSON.parse(l.data)}catch(c){throw i.error("Could not parse message into JSON:",l.data),i.error("From chunk:",l.raw),c}if(l.event!=="ping"&&l.event==="error"){const c=qZ(l.data)??l.data,u=c?.error?.type;throw new Bs(void 0,c,void 0,t.headers,u)}}a=!0}catch(l){if(ew(l))return;throw l}finally{a||r.abort()}}return new K1(s,r,n)}static fromReadableStream(t,r,n){let o=!1;async function*i(){const a=new nw,l=WZ(t);for await(const c of l)for(const u of a.decode(c))yield u;for(const c of a.flush())yield c}async function*s(){if(o)throw new lt("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");o=!0;let a=!1;try{for await(const l of i())a||l&&(yield JSON.parse(l));a=!0}catch(l){if(ew(l))return;throw l}finally{a||r.abort()}}return new K1(s,r,n)}[(dx=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){const t=[],r=[],n=this.iterator(),o=i=>({next:()=>{if(i.length===0){const s=n.next();t.push(s),r.push(s)}return i.shift()}});return[new K1(()=>o(t),this.controller,V(this,dx,"f")),new K1(()=>o(r),this.controller,V(this,dx,"f"))]}toReadableStream(){const t=this;let r;return S4t({async start(){r=t[Symbol.asyncIterator]()},async pull(n){try{const{value:o,done:i}=await r.next();if(i)return n.close();const s=tQ(JSON.stringify(o)+`
|
|
1056
1056
|
`);n.enqueue(s)}catch(o){n.error(o)}},async cancel(){await r.return?.()}})}},iPt=class{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith("\r")&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;const o={event:this.event,data:this.data.join(`
|
|
@@ -1108,9 +1108,9 @@ ${r[0].text}`;const n=r.length-1;r[n].text=`${r[n].text}
|
|
|
1108
1108
|
IMPORTANT: You MUST call the '${e}' tool to return your response in the required structured format. Do not respond with plain text - always use the ${e} tool.`}function aKr(e){const t=Kn({...e});delete t.$schema;const n={type:"object",properties:t.properties??t,required:Array.isArray(t.required)?t.required:[]};return{name:Mg,description:JNt,input_schema:n}}function HNt(e,t){return!e||e.length===0?{tools:e,applied:!1}:e.some(r=>r.name===Mg)?(h.warn("[Anthropic] A caller tool is already named 'final_result'; skipping the additive structured-output tool"),{tools:e,applied:!1}):{tools:[...e,aKr(t)],applied:!0}}function WNt(e,t){const r=jNt(t);return e===void 0?r.trim():typeof e=="string"?e+r:[...e,{type:"text",text:r.trim()}]}function KNt(e){return WNt(e,Mg)}function lKr(e){try{return JSON.stringify(JSON.parse(e||"{}"))}catch{return e}}var Mg,JNt,cKr,XNt=E({"src/lib/providers/anthropic/structuredOutput.ts"(){"use strict";z(),ss(),Mg="final_result",JNt="Return the final structured result. You MUST call this tool when you have gathered all information and are ready to provide the final answer. The arguments should contain the structured data matching the expected schema.",cKr=jNt(Mg)}});function uKr(e,t){switch(e){case"max_tokens":return"length";case"tool_use":return"tool-calls";case"refusal":return"content-filter";default:return t?"tool-calls":"stop"}}async function dKr({params:e,client:t,channel:r,stepSignal:n,requestTimeoutSignal:o,noteObservedPromptTokens:i,finalResultToolName:s,onTerminalResult:a,requireTerminalEvent:l}){const c=await t.messages.create({...e,stream:!0},{signal:n}),u=new Map,d=new Map,p=new Map,m=new Map;let f="",g="",y,v=0,T=0,b=0,S=0,k=0,A=0,x=0,P=0,C=0,R=!1;for await(const L of c){if(n.aborted)break;const j=L;if(j.type==="message_start"){const G=j.message?.usage;v+=G?.input_tokens??0;const J=G?.output_tokens??0;T+=J-x,x=J;const K=G?.output_tokens_details?.thinking_tokens??0;P+=K-C,C=K,b+=G?.cache_read_input_tokens??0,S+=G?.cache_creation_input_tokens??0,k+=G?.cache_creation?.ephemeral_5m_input_tokens??0,A+=G?.cache_creation?.ephemeral_1h_input_tokens??0,i?.((G?.input_tokens??0)+(G?.cache_read_input_tokens??0)+(G?.cache_creation_input_tokens??0));continue}if(j.type==="content_block_start"){const G=j.index??0;if(j.content_block?.type==="redacted_thinking"){const J=j.content_block.data;typeof J=="string"&&m.set(G,J)}j.content_block?.type==="tool_use"&&d.set(G,{id:j.content_block.id??"",name:j.content_block.name??"",inputJson:""});continue}if(j.type==="content_block_delta"){const G=j.index??0,J=j.delta;if(J?.type==="text_delta"&&J.text)f+=J.text,u.set(G,(u.get(G)??"")+J.text),r.push({content:J.text});else if(J?.type==="thinking_delta"&&J.thinking){const K=p.get(G)??{text:"",signature:""};K.text+=J.thinking,p.set(G,K),g+=J.thinking,r.push({content:"",reasoning:J.thinking})}else if(J?.type==="signature_delta"&&J.signature){const K=p.get(G)??{text:"",signature:""};K.signature+=J.signature,p.set(G,K)}else if(J?.type==="input_json_delta"&&J.partial_json){const K=d.get(G);K&&(K.inputJson+=J.partial_json)}continue}if(j.type==="message_delta"){y=j.delta?.stop_reason??y;const G=j.usage?.output_tokens??x;T+=G-x,x=G;const J=j.usage?.output_tokens_details?.thinking_tokens??C;P+=J-C,C=J;continue}j.type==="message_stop"&&(R=!0)}if(o?.aborted)throw o.reason;if(l&&!R&&!n.aborted)throw new De({code:"ANTHROPIC_STREAM_TRUNCATED",message:"Anthropic stream ended before its terminal message_stop event; the turn is incomplete and its content blocks were not dispatched.",category:"network",severity:"high",retriable:!1,context:{provider:"anthropic",rawStopReason:y}});const O=L=>{if(!L)return{};try{const j=JSON.parse(L);return typeof j=="object"&&j!==null&&!Array.isArray(j)?j:{}}catch{return{}}},U=[],M=new Set([...u.keys(),...d.keys(),...p.keys(),...m.keys()]);for(const L of[...M].sort((j,G)=>j-G)){const j=m.get(L);j&&U.push({type:"redacted_thinking",data:j});const G=p.get(L);G?.text&&G.signature&&U.push({type:"thinking",thinking:G.text,signature:G.signature});const J=u.get(L);J&&U.push({type:"text",text:J});const K=d.get(L);K&&U.push({type:"tool_use",id:K.id,name:K.name,input:O(K.inputJson)})}const D=[...d.values()].map(L=>({id:L.id,name:L.name,args:O(L.inputJson)})),$=s?[...d.values()].find(L=>L.name===s):void 0,B=$?[]:D,q=$?lKr($.inputJson):f;return $&&a?.(q),{text:q,...g?{reasoning:g}:{},toolCalls:B,usage:{inputTokens:v,outputTokens:T,cacheReadTokens:b,cacheWriteTokens:S,...k?{cacheWrite5mTokens:k}:{},...A?{cacheWrite1hTokens:A}:{},...P?{reasoningTokens:P}:{}},rawStopReason:y,raw:U}}function Uee(e){return{providerLabel:"anthropic",maxSteps:e.maxSteps,...e.toolFailureBreaker?{toolFailureBreaker:e.toolFailureBreaker}:{},...e.planReclaim?{planReclaim:(t,r)=>e.planReclaim?.(t,r)}:{},resolveToolOnMiss:t=>{const n=lW(e.toolsRecord,t)?.execute;if(n)return{execute:async(o,i)=>n(o,i)}},buildStepRequest(t,r){return{raw:e.buildParams(t,r)}},async executeStep(t,r,n){const o=t.raw,i=e.requestTimeoutMs?wa(e.requestTimeoutMs,"anthropic","stream"):null,s=T4(n,i?.controller.signal);try{return await dKr({params:o,client:e.client,channel:r,stepSignal:s.signal??n,requestTimeoutSignal:i?.controller.signal,...e.noteObservedPromptTokens?{noteObservedPromptTokens:e.noteObservedPromptTokens}:{},...e.finalResultToolName?{finalResultToolName:e.finalResultToolName}:{},...e.onTerminalResult?{onTerminalResult:e.onTerminalResult}:{},...e.requireTerminalEvent?{requireTerminalEvent:e.requireTerminalEvent}:{}})}finally{s.dispose(),i?.cleanup()}},appendPlanningNudge(t,r){const n={type:"text",text:r},o=t[t.length-1];if(o?.role==="user"&&Array.isArray(o.content)){const s={...o,content:[...o.content,n]};return[...t.slice(0,-1),s]}const i={role:"user",content:[n]};return[...t,i]},buildToolResultMessages(t,r,n){const o={role:"assistant",content:r.raw.filter(s=>s.type!=="server_tool_use")},i={role:"user",content:n.map(s=>({type:"tool_result",tool_use_id:s.id,content:s.error?`Error executing tool ${s.name}: ${s.error}`:$ee(s.output),...s.error?{is_error:!0}:{}}))};return[...t,o,i]},mapFinishReason:uKr}}var YNt=E({"src/lib/providers/anthropic/loopAdapter.ts"(){"use strict";qS(),VNt(),XNt(),Ys(),et()}});function Bee(e){if(e.length>=8&&e[0]===137&&e[1]===80&&e[2]===78&&e[3]===71)return"image/png";if(e.length>=3&&e[0]===255&&e[1]===216&&e[2]===255)return"image/jpeg";if(e.length>=6&&e[0]===71&&e[1]===73&&e[2]===70)return"image/gif";if(e.length>=12&&e[0]===82&&e[1]===73&&e[2]===70&&e[3]===70&&e[8]===87&&e[9]===69&&e[10]===66&&e[11]===80)return"image/webp"}function sN(e,t){if(e instanceof ArrayBuffer)return sN(new Uint8Array(e),t);if(e instanceof Uint8Array)return{type:"image",source:{type:"base64",media_type:aN(t)??Bee(e)??"image/png",data:Buffer.from(e).toString("base64")}};if(typeof e!="string"&&!(e instanceof URL))return;const r=e instanceof URL?e.toString():e,n=r.match(/^data:(image\/[a-z0-9+.-]+);base64,(.+)$/i);if(n){const i=aN(n[1])??Gee(n[2]);return i?{type:"image",source:{type:"base64",media_type:i,data:n[2]}}:void 0}return/^https?:\/\//i.test(r)?{type:"image",source:{type:"url",url:r}}:{type:"image",source:{type:"base64",media_type:aN(t)??Gee(r)??"image/png",data:r}}}function pKr(e){const t=e?.data;if(t==null)return;const r=typeof e.mediaType=="string"?e.mediaType.toLowerCase().split(";")[0].trim():"";if(zee.has(r)||r==="image/jpg")return sN(t,r);if(r==="application/pdf")return qee(t);const n=t instanceof ArrayBuffer?new Uint8Array(t):t instanceof Uint8Array?t:void 0;if(n&&Bee(n))return sN(n)}var zee,aN,ZNt,Gee,qee,mKr=E({"src/lib/providers/anthropicImageBlocks.ts"(){"use strict";zee=new Set(["image/jpeg","image/png","image/gif","image/webp"]),aN=e=>{if(!e)return;const t=e.toLowerCase().split(";")[0].trim();return t==="image/jpg"?"image/jpeg":zee.has(t)?t:void 0},ZNt=32,Gee=e=>{try{return Bee(Buffer.from(e.slice(0,ZNt),"base64"))}catch{return}},qee=e=>{if(e instanceof ArrayBuffer)return qee(new Uint8Array(e));if(e instanceof Uint8Array)return{type:"document",source:{type:"base64",media_type:"application/pdf",data:Buffer.from(e).toString("base64")}};if(e instanceof URL)return{type:"document",source:{type:"url",url:e.toString()}};if(typeof e=="string"){const t=e.match(/^data:application\/pdf;base64,(.+)$/i);return t?{type:"document",source:{type:"base64",media_type:"application/pdf",data:t[1]}}:/^https?:\/\//i.test(e)?{type:"document",source:{type:"url",url:e}}:{type:"document",source:{type:"base64",media_type:"application/pdf",data:e}}}}}}),lN,QNt=E({"src/lib/providers/anthropic/constants.ts"(){"use strict";lN={"anthropic-beta":["claude-code-20250219","fine-grained-tool-streaming-2025-05-14"].join(",")}}});function hKr(e){const t=e?.trim();if(!t)return;const r=t.replace(/\/+$/,""),n=r.replace(/\/v\d+$/,"");return n!==r&&h.debug("[AnthropicProvider] Stripping the version suffix from the base URL \u2014 the official Anthropic SDK appends /v1 to the base URL itself.",{baseURL:Yo(t),rewrittenTo:Yo(n)}),n}var Vee,kw,eLt,jee,tLt,rLt,Hee,Wee,Kee,Jee,Xee,nLt,fKr=E({"src/lib/providers/anthropic/client.ts"(){"use strict";C2t(),Qt(),Tn(),$s(),kr(),Hx(),D6(),pl(),Zo(),RRt(),ANt(),VWr(),Ln(),eKr(),pt(),Zs(),z(),pY(),BNt(),$c(),di(),Nt(),iN(),sl(),VNt(),YNt(),Xd(),RO(),vZ(),kd(),If(),vm(),zl(),Go(),Ys(),dg(),l4t(),MRt(),rm(),ZJ(),ss(),yO(),mKr(),Ic(),Um(),Jv(),CY(),QNt(),EIt(),xRt(),XNt(),ANt(),Vee=()=>_a(U4r()),kw=()=>Fi("ANTHROPIC_MODEL","claude-sonnet-4-6"),eLt=dt.getTracer("neurolink.provider.anthropic"),jee=()=>{try{const t=Rt(Fs(),".neurolink","anthropic-credentials.json");if(os(t)){const r=Cd(t,"utf-8"),n=JSON.parse(r);if(n.type==="oauth"&&n.oauth?.accessToken)return h.debug("[AnthropicProvider] Using OAuth token from stored credentials file"),n.oauth}}catch(t){h.debug("[AnthropicProvider] Failed to read stored credentials:",t)}const e=process.env.ANTHROPIC_OAUTH_TOKEN||process.env.CLAUDE_OAUTH_TOKEN;if(!e)return null;try{const t=JSON.parse(e);if(typeof t=="object"&&t.accessToken)return t;if(typeof t=="string")return{accessToken:t}}catch{}return{accessToken:e}},tLt=e=>{const t=process.env.ANTHROPIC_SUBSCRIPTION_TIER?.toLowerCase();if(t){const r=["free","pro","max","max_5","max_20","api"];if(r.includes(t))return h.debug("[detectSubscriptionTier] Using environment override",{tier:t}),t;h.warn("[detectSubscriptionTier] Invalid ANTHROPIC_SUBSCRIPTION_TIER",{value:t,validTiers:r})}if(e){const r=e.scopes??[];let n="pro";return r.includes("max_20")?n="max_20":r.includes("max_5")?n="max_5":r.includes("max")&&(n="max"),h.debug("[detectSubscriptionTier] Detected from OAuth token",{tier:n,scopes:r}),n}return h.debug("[detectSubscriptionTier] No OAuth token, defaulting to API tier"),"api"},rLt=e=>{const t=process.env.ANTHROPIC_AUTH_METHOD?.toLowerCase();if(t==="api_key"||t==="apikey")return h.debug("[detectAuthMethod] Forced to api_key by ANTHROPIC_AUTH_METHOD env var"),"api_key";if(t==="oauth"){if(e)return h.debug("[detectAuthMethod] Forced to oauth by ANTHROPIC_AUTH_METHOD env var"),"oauth";h.warn("[detectAuthMethod] ANTHROPIC_AUTH_METHOD=oauth but no OAuth token found; falling through to auto-detection")}else t&&h.warn("[detectAuthMethod] Unrecognized ANTHROPIC_AUTH_METHOD value; falling through to auto-detection",{value:t});const r=e?"oauth":"api_key";return h.debug("[detectAuthMethod] Auth method resolved",{method:r,hasOAuthToken:!!e}),r},Hee=e=>{const t=[],r=[],n=s=>Array.isArray(s)?s:[s],o=(s,a)=>{const l=rp(a);if(l&&s.length>0){const c=s[s.length-1];c.cache_control=l}};for(const s of e)switch(s.role){case"system":{const a=typeof s.content=="string"?s.content:n(s.content).map(c=>typeof c=="string"?c:String(c?.text??"")).join(`
|
|
1109
1109
|
`),l=rp(s);t.push({type:"text",text:a,...l?{cache_control:l}:{}});break}case"user":{const a=[];for(const l of n(s.content)){if(typeof l=="string"){l.length>0&&a.push({type:"text",text:l});continue}const c=l;if(c?.type==="text"&&typeof c.text=="string"){const u=rp(c);a.push({type:"text",text:c.text,...u?{cache_control:u}:{}})}else if(c?.type==="image"||c?.type==="image_url"){const u=sN(c.image??c.data??c.url);if(u){const d=rp(c);a.push(d?{...u,cache_control:d}:u)}}else if(c?.type==="file"){const d=typeof c=="object"&&c!==null&&("mediaType"in c?typeof c.mediaType=="string":!0)?pKr(c):void 0;if(d){const p=rp(c);p&&(d.cache_control=p),a.push(d)}}}a.length>0&&(o(a,s),r.push({role:"user",content:a}));break}case"assistant":{const a=[];for(const l of n(s.content)){if(typeof l=="string"){l.length>0&&a.push({type:"text",text:l});continue}const c=l;if(c?.type==="reasoning"){const u=c.providerOptions?.anthropic,d=u?.redactedData;if(typeof d=="string"&&d.length>0){a.push({type:"redacted_thinking",data:d});continue}const p=u?.signature;typeof p=="string"&&p.length>0&&typeof c.text=="string"&&c.text.length>0&&a.push({type:"thinking",thinking:c.text,signature:p});continue}if(c?.type==="text"&&typeof c.text=="string"){if(c.text.length>0){const u=rp(c);a.push({type:"text",text:c.text,...u?{cache_control:u}:{}})}}else if(c?.type==="tool-call"){let u=c.input;if(typeof u=="string")try{u=JSON.parse(u)}catch{u={}}a.push({type:"tool_use",id:c.toolCallId??"",name:c.toolName??"",input:u??{}})}}a.length>0&&(o(a,s),r.push({role:"assistant",content:a}));break}case"tool":{const a=[];if(Array.isArray(s.content))for(const l of s.content){const c=l;c?.type==="tool-result"&&a.push({type:"tool_result",tool_use_id:c.toolCallId??"",content:$ee(c.output)})}else typeof s.content=="string"&&a.push({type:"tool_result",tool_use_id:s.toolCallId??"",content:s.content});a.length>0&&r.push({role:"user",content:a});break}}const i=t.length===0?void 0:t.some(s=>s.cache_control)?t:t.map(s=>s.text).join(`
|
|
1110
1110
|
|
|
1111
|
-
`);return{...i!==void 0?{system:i}:{},messages:r}},Wee=e=>{if(!(!e||e==="auto")){if(e==="none")return{type:"none"};if(e==="required")return{type:"any"};if(typeof e=="object"){const t=e;if(t.type==="tool"&&t.toolName)return{type:"tool",name:t.toolName}}}},Kee=(e,t)=>t?.type!=="any"&&t?.type!=="tool"||ef(e)?t:(h.warn(`[anthropic] ${e} rejects tool_choice "${t.type}"; sending "auto" instead`),{type:"auto",...t.disable_parallel_tool_use!==void 0?{disable_parallel_tool_use:t.disable_parallel_tool_use}:{}}),Jee=e=>{switch(e){case"max_tokens":return"length";case"tool_use":return"tool-calls";case"refusal":return"content-filter";default:return"stop"}},Xee=6e5,nLt=class extends Ma{client;authMethod;subscriptionTier;enableBetaFeatures;baseURL;oauthToken;lastResponseMetadata=null;usageInfo=null;refreshPromise;constructor(e,t,r,n){const o=!!(n?.apiKey&&!n?.oauthToken),i=o?null:(n?.oauthToken?{accessToken:n.oauthToken}:null)??r?.oauthToken??jee(),s=o?"api_key":r?.authMethod??rLt(i),a=r?.subscriptionTier??(s==="oauth"?tLt(i):"api"),l=e||kw(),c=hKr(n?.baseURL??r?.baseURL??process.env.ANTHROPIC_BASE_URL);let u=l;!(c!==void 0)&&a!=="api"&&!Pee(l,a)&&(u=Mee(a),h.warn("Model not available for subscription tier, using recommended model",{requestedModel:l,subscriptionTier:a,recommendedModel:u})),super(u,"anthropic",t),this.enableBetaFeatures=r?.enableBetaFeatures??!0,this.oauthToken=i,this.subscriptionTier=a,this.baseURL=c,this.authMethod=s;const p=this.getAuthHeaders();let m;if(h.debug("[AnthropicProvider] Constructor - checking OAuth:",{authMethod:this.authMethod,hasOAuthToken:!!this.oauthToken,hasAccessToken:!!this.oauthToken?.accessToken}),this.authMethod==="oauth"&&this.oauthToken){h.debug("[AnthropicProvider] Creating OAuth fetch wrapper...");const f=this.oauthToken,g=qWr(()=>f.accessToken,this.enableBetaFeatures,!1,!0);m=new Rg({apiKey:"oauth-authenticated",...this.baseURL&&{baseURL:this.baseURL},fetch:MNt(g),timeout:Xee,maxRetries:0}),h.debug("[AnthropicProvider] Anthropic SDK client created with OAuth fetch wrapper"),h.debug("Anthropic Provider initialized with OAuth",{modelName:this.modelName,provider:this.providerName,authMethod:this.authMethod,subscriptionTier:this.subscriptionTier,enableBetaFeatures:this.enableBetaFeatures,hasRefreshToken:!!this.oauthToken.refreshToken,tokenExpiry:this.oauthToken.expiresAt?new Date(this.oauthToken.expiresAt).toISOString():"none"})}else{const f=n?.apiKey??r?.apiKey??Vee();m=new Rg({apiKey:f,defaultHeaders:p,...this.baseURL&&{baseURL:this.baseURL},fetch:MNt(Ot()),timeout:Xee,maxRetries:0}),h.debug("Anthropic Provider initialized with API key",{modelName:this.modelName,provider:this.providerName,authMethod:this.authMethod,subscriptionTier:this.subscriptionTier,enableBetaFeatures:this.enableBetaFeatures})}this.client=m,this.usageInfo={messagesUsed:0,messagesRemaining:-1,tokensUsed:0,tokensRemaining:-1,inputTokensUsed:0,outputTokensUsed:0,lastRequestTimestamp:0,isRateLimited:!1,requestCount:0,messageQuotaPercent:0,tokenQuotaPercent:0},h.debug("Anthropic Provider v2 initialized",{modelName:this.modelName,provider:this.providerName,authMethod:this.authMethod,subscriptionTier:this.subscriptionTier,enableBetaFeatures:this.enableBetaFeatures,betaFeatures:this.enableBetaFeatures?lN["anthropic-beta"]:"disabled"})}getAuthHeaders(){const e={},t=this.baseURL!==void 0;if(this.enableBetaFeatures)if(t){const r=process.env.ANTHROPIC_ENABLE_LONG_CONTEXT_BETA==="1"||process.env.ANTHROPIC_ENABLE_LONG_CONTEXT_BETA==="true",n=[...jx,"fine-grained-tool-streaming-2025-05-14","interleaved-thinking-2025-05-14","redact-thinking-2026-02-12"];r&&n.push("context-1m-2025-08-07"),e["anthropic-beta"]=n.join(",")}else e["anthropic-beta"]=lN["anthropic-beta"];return t&&(e["User-Agent"]=Pg),this.subscriptionTier!=="api"&&(e["x-subscription-tier"]=this.subscriptionTier),e}validateModelAccess(e){if(this.baseURL!==void 0)return h.debug("[validateModelAccess] Bypassing tier check (a base URL is set \u2014 the proxy enforces access)",{model:e}),!0;if(this.subscriptionTier==="api")return!0;const t=Pee(e,this.subscriptionTier);return t||h.debug("[validateModelAccess] Model not available for tier",{model:e,tier:this.subscriptionTier}),t}getUsageInfo(){return this.usageInfo}areBetaFeaturesEnabled(){return this.enableBetaFeatures}getModelCapabilities(){return Oee(this.modelName||this.getDefaultModel())}getSubscriptionTier(){return this.subscriptionTier}getAuthMethod(){return this.authMethod}async refreshAuthIfNeeded(){if(this.authMethod!=="oauth"||!this.oauthToken){h.debug("Token refresh not applicable for API key authentication");return}if(!this.oauthToken.expiresAt){h.debug("Token has no expiry information, assuming valid");return}const e=Date.now(),t=this.oauthToken.expiresAt<=e,r=this.oauthToken.expiresAt<=e+yhe;if(!t&&!r){h.debug("OAuth token is still valid",{expiresInMs:this.oauthToken.expiresAt-e});return}if(!this.oauthToken.refreshToken){if(t)throw new Wr("OAuth token expired and no refresh token available. Please re-authenticate.",this.providerName);h.warn("OAuth token expiring soon but no refresh token available",{expiresInMs:this.oauthToken.expiresAt-e});return}if(this.refreshPromise){await this.refreshPromise;return}h.info("Refreshing OAuth token",{isExpired:t,expiresInMs:this.oauthToken.expiresAt-e});const n=this.oauthToken,o=n.refreshToken;this.refreshPromise=(async()=>{const s=new AbortController,a=setTimeout(()=>s.abort(),3e4),l=await fetch(Vx,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded","User-Agent":Pg},body:new URLSearchParams({grant_type:"refresh_token",refresh_token:o,client_id:Iee}),signal:s.signal});if(clearTimeout(a),!l.ok){const d=await l.text();throw new Wr(`Failed to refresh OAuth token: ${l.status} ${d}`,this.providerName)}const c=await l.json();n.accessToken=c.access_token,n.refreshToken=c.refresh_token||n.refreshToken,n.expiresAt=c.expires_in?Date.now()+c.expires_in*1e3:void 0,n.tokenType=c.token_type||"Bearer";const u=n;try{const d=Rt(Fs(),".neurolink");os(d)||W8(d,{recursive:!0});const p=Rt(d,"anthropic-credentials.json"),m=`${p}.tmp`,g={...os(p)?JSON.parse(Cd(p,"utf-8")):{},type:"oauth",oauth:u,updatedAt:Date.now()};N4(m,JSON.stringify(g,null,2),{mode:384}),X8(m,p),h.debug("Refreshed OAuth credentials persisted to disk")}catch(d){h.warn("Failed to persist refreshed OAuth token to disk",{error:d instanceof Error?d.message:String(d)})}h.info("OAuth token refreshed successfully",{hasNewRefreshToken:!!c.refresh_token,expiresIn:c.expires_in})})();try{await this.refreshPromise}catch(i){throw i instanceof Wr?i:new Wr(`Failed to refresh OAuth token: ${i instanceof Error?i.message:String(i)}`,this.providerName)}finally{this.refreshPromise=void 0}}getLastResponseMetadata(){return this.lastResponseMetadata}updateResponseMetadata(e,t,r){this.lastResponseMetadata={rateLimit:e,...t?{requestId:t}:{}},this.usageInfo&&(this.usageInfo.requestCount++,this.usageInfo.messagesUsed++,this.usageInfo.lastRequestTimestamp=Date.now(),r&&(r.inputTokens!==void 0&&(this.usageInfo.inputTokensUsed+=r.inputTokens,this.usageInfo.tokensUsed+=r.inputTokens),r.outputTokens!==void 0&&(this.usageInfo.outputTokensUsed+=r.outputTokens,this.usageInfo.tokensUsed+=r.outputTokens)),e?.requestsRemaining!==void 0&&(this.usageInfo.messagesRemaining=e.requestsRemaining),e?.tokensRemaining!==void 0&&(this.usageInfo.tokensRemaining=e.tokensRemaining),e?.requestsLimit&&e.requestsLimit>0&&(this.usageInfo.messageQuotaPercent=Math.round((e.requestsLimit-(e.requestsRemaining??0))/e.requestsLimit*100)),e?.tokensLimit&&e.tokensLimit>0&&(this.usageInfo.tokenQuotaPercent=Math.round((e.tokensLimit-(e.tokensRemaining??0))/e.tokensLimit*100)),e?.retryAfter!==void 0?(this.usageInfo.isRateLimited=!0,this.usageInfo.rateLimitExpiresAt=Date.now()+e.retryAfter*1e3):(this.usageInfo.isRateLimited=!1,this.usageInfo.rateLimitExpiresAt=void 0)),e?.requestsRemaining!==void 0&&e.requestsRemaining<=5&&h.warn("Approaching Anthropic request rate limit",{remaining:e.requestsRemaining,limit:e.requestsLimit,reset:e.requestsReset}),e?.tokensRemaining!==void 0&&e.tokensLimit&&e.tokensRemaining<e.tokensLimit*.1&&h.warn("Approaching Anthropic token rate limit",{remaining:e.tokensRemaining,limit:e.tokensLimit,reset:e.tokensReset})}getProviderName(){return"anthropic"}getDefaultModel(){return kw()}getAISDKModel(){const e=this.client,t=this.providerName,r=this.modelName||kw(),n=s=>this.getTimeout(s??{}),o=()=>this.refreshAuthIfNeeded();return{specificationVersion:"v3",provider:t,modelId:r,supportedUrls:{},doGenerate:async s=>{await o();const a=Hee(s.prompt),l=a.messages;let c=a.system,u=(s.tools??[]).filter(L=>L.type==="function").map(L=>{const j=rp(L);return{name:L.name,...L.description?{description:L.description}:{},input_schema:L.inputSchema??{type:"object",properties:{}},...j?{cache_control:j}:{}}});u&&u.length===0&&(u=void 0);const d=SVr(s.toolChoice);let p=d?Wee(d):void 0,m;if(s.responseFormat?.type==="json"){m=s.responseFormat.name??"json";const L=s.responseFormat.schema??{type:"object"};u=[{name:m,description:s.responseFormat.description??"Respond by calling this tool with the answer as its input.",input_schema:L}],ef(r)?p={type:"tool",name:m}:(p=void 0,c=WNt(c,m))}p=Kee(r,p);const f=s.providerOptions?.anthropic?.finalResultSchema;let g=!1;if(!m&&f){const L=HNt(u,f);u=L.tools,g=L.applied,L.applied&&(c=KNt(c))}const y=s.providerOptions?.anthropic?.thinking,v=y?.type==="enabled";u=AY(u);const T=Fee({system:c,tools:u,messages:l}),b=zNt(l,nN-T),S=Ac("anthropic",r,{...s.temperature!==void 0&&s.temperature!==null?{temperature:s.temperature}:{},...s.topP!==void 0&&s.topP!==null?{topP:s.topP}:{}},"anthropic.doGenerate");v&&(S.temperature!==void 0||S.topP!==void 0)&&h.debug("[anthropic] extended thinking is enabled, so temperature/top_p are omitted \u2014 Anthropic rejects any temperature but 1 while thinking is set");const k={model:r,messages:b,max_tokens:Gk(r,s.maxOutputTokens),...c?{system:c}:{},...!v&&S.temperature!==void 0?{temperature:S.temperature}:{},...!v&&S.topP!==void 0?{top_p:S.topP}:{},...s.stopSequences&&s.stopSequences.length>0?{stop_sequences:s.stopSequences}:{},...u?{tools:u}:{},...p?{tool_choice:p}:{},...y?{thinking:y}:{}},A=s.providerOptions?.neurolink,x=typeof A?.timeoutMs=="number"&&Number.isFinite(A.timeoutMs)&&A.timeoutMs>0?A.timeoutMs:void 0,P=x!==void 0?x:k.max_tokens>8192?Math.max(n(s),3e5):n(s),C=wa(P,t,"generate"),R=Cy(s.abortSignal,C?.controller.signal);let O;try{O=await e.messages.create(k,{signal:R})}catch(L){const j=R?.aborted?R.reason:void 0;throw j instanceof Ta?j:L}finally{C?.cleanup()}const U=[];let M;const D=[];let $=!1;for(const L of O.content)L.type==="thinking"?U.push({type:"reasoning",text:L.thinking,providerOptions:{anthropic:{signature:L.signature}}}):L.type==="redacted_thinking"?U.push({type:"reasoning",text:"",providerOptions:{anthropic:{redactedData:L.data}}}):L.type==="text"?m?D.push(L.text):U.push({type:"text",text:L.text}):L.type==="tool_use"&&(m&&L.name===m?($=!0,U.push({type:"text",text:Xk(L.input)})):g&&L.name===Mg?M=Xk(L.input):U.push({type:"tool-call",toolCallId:L.id,toolName:L.name,input:Xk(L.input)}));if(m&&!$&&D.length>0&&U.push({type:"text",text:D.join("")}),M!==void 0){const L=U.filter(j=>j.type==="reasoning");U.length=0,U.push(...L,{type:"text",text:M}),h.debug("[Anthropic] Extracted structured output from final_result tool (generate)",{chars:M.length})}const B=O.usage.cache_read_input_tokens??0,q=O.usage.cache_creation_input_tokens??0;return{content:U,finishReason:{unified:M!==void 0&&Jee(O.stop_reason)==="tool-calls"?"stop":Jee(O.stop_reason),raw:O.stop_reason??"stop"},usage:{inputTokens:{total:O.usage.input_tokens+B+q,noCache:O.usage.input_tokens,cacheRead:B,cacheWrite:q},outputTokens:{total:O.usage.output_tokens,text:O.usage.output_tokens,reasoning:void 0}},warnings:[],request:{body:k},response:{id:O.id,modelId:O.model,headers:XWr()??{},body:O}}},doStream:()=>{throw new Error(`${t}: doStream is not implemented on the delegating model. NeuroLink streams through executeStream, reached via NeuroLink.stream() \u2014 use that (the browser bundle exports the NeuroLink class) rather than calling doStream on a model handle.`)}}}formatProviderError(e){return ba(e,[{match:r=>r.statusCode===401||/API_KEY_INVALID|Invalid API key/i.test(r.message),errorClass:Wr,message:"Invalid Anthropic API key. Please check your ANTHROPIC_API_KEY environment variable."},{match:r=>r.statusCode===429||/rate limit|too_many_requests/i.test(r.message)||im(r.message,429),errorClass:Qi,message:"Anthropic rate limit exceeded. Please try again later."},{match:r=>/ECONNRESET|ENOTFOUND|ECONNREFUSED|network|connection/i.test(r.message),errorClass:ai,message:r=>`Connection error: ${r.message}`},{match:r=>r.statusCode!==void 0&&r.statusCode>=500&&r.statusCode<=599||/server error|bad gateway|service unavailable|gateway timeout|\berror\b\D{0,12}\b5\d\d\b|\b5\d\d\b\D{0,12}\berror\b|\bstatus(?:\s*code)?\b\D{0,12}\b5\d\d\b/i.test(r.message),errorClass:ot,message:r=>`Server error: ${r.message}`},{match:()=>!0,errorClass:ot,message:r=>`Anthropic error: ${r.message}`}],this.providerName,this.modelName)}async generate(e,t){await this.refreshAuthIfNeeded();const{result:r,snapshot:n}=await KWr(()=>this.dispatchGenerate(e,t));return r&&n&&(this.recordLimitSnapshot(n),r.limits=n,r.analytics&&(r.analytics.limits=n)),r}async dispatchGenerate(e,t){await this.ensureModelLimits();const r=this.normalizeTextOptions(e);if($d(r,this.modelName)!=="text")return super.generate(r,t);this.validateOptions(r);const n=await this.getToolsForStream(r),o="disableInternalFallback"in r&&r.disableInternalFallback===!0;return this.runGenerateWithModelFallback(()=>this.withTurnTimeout({...r,tools:n},this.getDescriptorGenerateMs(),i=>this.executeNativeGenerate(i)),o,r)}async executeNativeGenerate(e){const t=Date.now(),r=this.modelName||kw(),n=await this.getAISDKModelWithMiddleware(e);if(!ex(n))throw this.handleProviderError(new Error("anthropic: model handle exposes no doGenerate()"));const o=n.doGenerate.bind(n),s=!e.disableTools&&this.supportsTools()?e.tools||{}:{},a=Object.entries(s).map(([T,b])=>{const S=b;return{type:"function",name:T,description:S.description??"",inputSchema:S.inputSchema?qo(S.inputSchema):{type:"object",properties:{}}}}),l=a.length>0,c=e.schema?qo(e.schema):void 0,u=c&&!l?{type:"json",schema:c}:void 0,d={};c&&l&&(d.finalResultSchema=c),e.thinkingConfig?.enabled&&e.thinkingConfig.budgetTokens?d.thinking={type:"enabled",budget_tokens:e.thinkingConfig.budgetTokens}:e.thinkingConfig?.type==="disabled"&&(d.thinking={type:"disabled"});const p={};Object.keys(d).length>0&&(p.anthropic=d),typeof e.timeout=="number"&&(p.neurolink={timeoutMs:e.timeout});const m=Object.keys(p).length>0?p:void 0,f=await this.buildMessagesForStream(e),g=[],y=await BO({doGenerate:o,...SRt({provider:"anthropic",availableInputTokens:ql("anthropic",r,e.maxTokens??void 0),getFixedOverheadTokens:()=>Vt(xk({tools:a,responseFormat:u,providerOptions:m}),"anthropic")}),conversation:f,...l?{tools:a}:{},toolsRecord:s,...l&&e.toolChoice?{toolChoice:VO(e,s,!0)}:{},...u?{responseFormat:u}:{},...m?{providerOptions:m}:{},maxSteps:e.maxSteps||ts,...e.maxTokens?{maxOutputTokens:e.maxTokens}:{},...e.temperature!==void 0?{temperature:e.temperature}:{},...e.abortSignal?{abortSignal:e.abortSignal}:{},...e.toolTimeoutMs!==void 0?{toolTimeoutMs:e.toolTimeoutMs}:{},runStep:T=>Py(T,dt.getActiveSpan()??void 0,"anthropic generate",void 0,e.abortSignal).catch(b=>{throw this.handleProviderError(b)})},g),v={content:y.text,provider:this.providerName,model:r,finishReason:y.finishReason,...y.rawFinishReason?{rawFinishReason:y.rawFinishReason}:{},...y.reasoning?{reasoning:y.reasoning}:{},usage:{input:y.inputTokens,output:y.outputTokens,total:y.inputTokens+y.outputTokens+y.cacheReadTokens+y.cacheWriteTokens,...y.cacheReadTokens?{cacheReadTokens:y.cacheReadTokens}:{},...y.cacheWriteTokens?{cacheCreationTokens:y.cacheWriteTokens}:{}},responseTime:Date.now()-t,toolsUsed:y.toolsUsed,toolCalls:HH(g),toolExecutions:Df(e,Bd(g)),enhancedWithTools:y.toolsUsed.length>0};return this.finalizeNativeGenerate(v,e,t)}recordLimitSnapshot(e){this.updateResponseMetadata(e.rateLimit,e.requestId),ZWr(e),QWr(e,this.modelName)}supportsExecutionControl(){return!0}async executeStream(e,t){return YWr(()=>this.executeStreamInCaptureScope(e,t))}async executeStreamInCaptureScope(e,t){await this.refreshAuthIfNeeded(),this.validateStreamOptions(e);const r=e.executionControl,n=typeof e.turnTimeoutMs=="number"&&Number.isFinite(e.turnTimeoutMs)&&e.turnTimeoutMs>0,o=r&&r.lifetimeTimeoutMs!==void 0?r.lifetimeTimeoutMs??void 0:n?e.turnTimeoutMs:this.getTimeout(e),i=wa(o,this.providerName,"stream"),s=new AbortController,a=Mbe([e.abortSignal,i?.controller.signal,s.signal]).signal;let l,c,u,d,p=!1;try{d=!e.disableTools&&this.supportsTools(),l=d?e.tools||await this.getAllTools():{},c=d?Xv(l,"input_schema"):void 0;const Ce=await this.buildMessagesForStream(e);if(u=Hee(Ce),e.schema&&c&&c.length>0){const ye=HNt(c,qo(e.schema));c=ye.tools,p=ye.applied,ye.applied&&(u.system=KNt(u.system))}}catch(Ce){throw i?.cleanup(),this.handleProviderError(Ce)}const m=this.modelName||kw(),f=d&&c&&c.length>0?Kee(m,Wee(VO(e,l,d))):void 0,g=e.thinkingConfig?.enabled&&e.thinkingConfig.budgetTokens?{type:"enabled",budget_tokens:e.thinkingConfig.budgetTokens}:e.thinkingConfig?.type==="disabled"?{type:"disabled"}:void 0,y=g?.type==="enabled",v=eLt.startSpan("neurolink.provider.streamText",{kind:nn.CLIENT,attributes:{"gen_ai.system":"anthropic","gen_ai.request.model":m}}),T=e.maxSteps||ts,b=this.neurolink?.getEventEmitter(),S=Kv(),{push:k}=S,{usagePromise:A,finishPromise:x,resolveUsage:P,resolveFinish:C}=aZ();A.then(Ce=>{v.setAttribute("gen_ai.usage.input_tokens",Ce.promptTokens||0),v.setAttribute("gen_ai.usage.output_tokens",Ce.completionTokens||0),Ce.cacheReadTokens&&v.setAttribute("gen_ai.usage.cached_input_tokens",Ce.cacheReadTokens);const ye=Ls(this.providerName,this.modelName,{input:Ce.promptTokens||0,output:Ce.completionTokens||0,total:Ce.totalTokens||0,...Ce.cacheReadTokens?{cacheReadTokens:Ce.cacheReadTokens}:{},...Ce.cacheCreationTokens?{cacheCreationTokens:Ce.cacheCreationTokens}:{}});ye&&ye>0&&v.setAttribute("neurolink.cost",ye)}).catch(()=>{}),x.then(Ce=>{v.setAttribute("gen_ai.response.finish_reason",Ce||"unknown"),v.end()}).catch(()=>{v.end()});let R;const O=this.client,U=[],M=Date.now(),D={};let $=0,B=0,q=0,L=0,j=null;const G=()=>({promptTokens:$,completionTokens:B,totalTokens:$+q+L+B,...q>0?{cacheReadTokens:q}:{},...L>0?{cacheCreationTokens:L}:{}});let J="",K;const de=(Ce,ye)=>{const Ne=xe=>{if(typeof xe=="string")return xe;try{return JSON.stringify(xe)??""}catch{return""}};return Vt(Ne(Ce),"anthropic")+Vt(Ne(ye),"anthropic")},ae=(async()=>{let Ce,ye;const le=Uee({client:O,maxSteps:T,toolsRecord:l,buildParams:W=>{if(c){const ie=new Set(c.map(I=>I.name)),ce=Object.fromEntries(Object.entries(l).filter(([I])=>!ie.has(I)));if(Object.keys(ce).length>0){const I=Xv(ce,"input_schema");I&&I.length>0&&(c=[...c,...I])}}const te=AY(c),me=Fee({system:u.system,tools:te,messages:W}),Te=zNt(W,nN-me),pe=Ac("anthropic",m,e.temperature!==void 0&&e.temperature!==null?{temperature:e.temperature}:{},"anthropic.executeStream");return y&&pe.temperature!==void 0&&h.debug("[anthropic] extended thinking is enabled, so temperature is omitted on the stream path \u2014 Anthropic rejects any temperature but 1 while thinking is set"),{model:m,messages:Te,max_tokens:Gk(m,e.maxTokens),...u.system?{system:u.system}:{},...!y&&pe.temperature!==void 0?{temperature:pe.temperature}:{},...te&&te.length>0?{tools:te}:{},...f?{tool_choice:f}:{},...g?{thinking:g}:{}}},planReclaim:W=>{const te=UNt({conversation:W,availableInputTokens:ql("anthropic",m,e.maxTokens??void 0),fixedOverheadTokens:de(u.system,c),provider:"anthropic",observedPromptTokens:Ce,previousSentEstimate:ye,onSentEstimate:ie=>{ye=ie}});if(!te)return;const me=new Set(te.drop),Te=new Set(te.truncate),pe=[];for(let ie=0;ie<W.length;ie++){if(me.has(ie))continue;const ce=W[ie];if(Te.has(ie)&&Array.isArray(ce.content)){pe.push({...ce,content:ce.content.map(I=>I.type==="tool_result"?{...I,content:$Nt(typeof I.content=="string"?I.content:JSON.stringify(I.content)??"")}:I)});continue}pe.push(ce)}if(me.size>0){let ie=pe.findIndex(ce=>Array.isArray(ce.content)&&ce.content.some(I=>I.type==="tool_use"||I.type==="tool_result"));ie<0&&(ie=Math.min(1,pe.length)),pe.splice(ie,0,{role:"user",content:[{type:"text",text:Lee}]})}return{conversation:pe}},...r?{requestTimeoutMs:r.requestTimeoutMs,requireTerminalEvent:!0}:{},noteObservedPromptTokens:W=>{Ce=W},...p?{finalResultToolName:Mg,onTerminalResult:W=>{K=W,h.debug("[Anthropic] Extracted structured output from final_result tool (stream)",{chars:W.length})}}:{}}),Oe={...le,buildToolResultMessages:(W,te,me,Te)=>{for(const ce of me)U.push(ce.name);const pe=me.map(ce=>({type:"tool-call",toolCallId:ce.id,toolName:ce.name,args:ce.args})),ie=me.map(ce=>ce.error?{type:"tool-result",toolCallId:ce.id,toolName:ce.name,error:ce.error}:{type:"tool-result",toolCallId:ce.id,toolName:ce.name,result:ce.output});return PRt(b,ie.map(ce=>({toolName:ce.toolName,result:"result"in ce?ce.result:void 0,error:"error"in ce?ce.error:void 0}))),this.handleToolExecutionStorage(pe,ie,e,new Date).catch(ce=>{h.warn("[AnthropicProvider] Failed to store tool executions",{provider:this.providerName,error:ce instanceof Error?ce.message:String(ce)})}),le.buildToolResultMessages(W,te,me,Te)}},Ie={};for(const[W,te]of Object.entries(l)){const me=te.execute;me&&(Ie[W]={execute:async(Te,pe)=>{const ie=pe;return me(Te,{toolCallId:ie.toolCallId??"",...ie.abortSignal?{abortSignal:ie.abortSignal}:{},messages:[]})}})}const Ge=dt.getActiveSpan(),je=r?.beforeStep,_e=je?async W=>{const te=r?.beforeStepTimeoutMs??YJ,me=wa(te,this.providerName,"stream"),Te=T4(W.signal,me?.controller.signal);try{return await Su(Promise.resolve(je({...W,signal:Te.signal??W.signal})),Te.signal??W.signal)}catch(pe){h.warn("[Anthropic] executionControl.beforeStep failed or timed out; the step cap stands",{error:pe instanceof Error?pe.message:String(pe),stepsCompleted:W.stepsCompleted});return}finally{Te.dispose(),me?.cleanup()}}:void 0,{stream:Fe,resultPromise:Y}=tp(Oe,u.messages.slice(),{tools:Ie,...a?{abortSignal:a}:{},...Ge?{span:Ge}:{},..._e?{beforeStep:_e}:{},...e.toolTimeoutMs!==void 0?{toolTimeoutMs:e.toolTimeoutMs}:{}}),X=(async()=>{for await(const W of Fe)W.reasoning&&k({content:"",reasoning:W.reasoning}),W.content&&(p?J+=W.content:k({content:W.content}))})();let ke;try{ke=await Y}catch(W){throw await ug(X,"Anthropic"),W}if(await X,$+=ke.usage.inputTokens,B+=ke.usage.outputTokens,q+=ke.usage.cacheReadTokens??0,L+=ke.usage.cacheWriteTokens??0,j=ke.rawStopReason??j,ke.aborted){const W=a?.aborted?a.reason:void 0;D.stopReason=W instanceof Ta?"time-limit":"aborted",D.finishReason="other",ke.rawStopReason&&(D.rawFinishReason=ke.rawStopReason),P(G()),C("other");return}D.finishReason=ke.finishReason,ke.rawStopReason&&(D.rawFinishReason=ke.rawStopReason),ke.finishReason==="tool-calls"&&K===void 0&&(D.stopReason="step-cap"),P(G()),C(j??"stop")})().catch(Ce=>{throw R=Ce,h.error("Anthropic: Stream error",{error:Ce instanceof Error?Ce.message:String(Ce)}),P(G()),C("error"),this.formatProviderError(Ce)}).finally(()=>{if(p){const Ce=K??J;Ce.length>0&&k({content:Ce})}i?.cleanup(),S.close()});ae.catch(()=>{});const ge=this.providerName;return{stream:async function*(){let Ce=0;try{for await(const ye of S.iterable)"content"in ye&&typeof ye.content=="string"&&ye.content.length>0&&Ce++,yield ye;if(await ae,Ce===0&&U.length===0){h.warn(`${ge}: Stream produced no output \u2014 emitting enriched sentinel`);const ye=new xu({message:"Stream produced no output"}),Ne=await ig(ye,void 0,R);sg(Ne),yield Ne}}catch(ye){const Ne=await ig(ye,void 0,R);if(sg(Ne),yield Ne,!xu.isInstance(ye))throw ye}finally{s.signal.aborted||s.abort()}}(),provider:this.providerName,model:m,toolCalls:[],toolResults:[],metadata:D,analytics:x.then(async()=>{const Ce=await gZ.createAnalytics(this.providerName,m,{textStream:(async function*(){})(),usage:A,finishReason:x},Date.now()-M,{requestId:e.requestId??`${this.providerName}-stream-${Date.now()}`,streamingMode:!0}),ye=JWr();return ye&&Ce&&(this.recordLimitSnapshot(ye),Ce.limits=ye),Ce})}}async isAvailable(){try{return jee()||Vee(),!0}catch{return!1}}getModel(){return this.getAISDKModel()}}}}),oLt={};Z(oLt,{ANTHROPIC_BETA_HEADERS:()=>lN,AnthropicProvider:()=>nLt,ModelAccessError:()=>_5,getModelCapabilities:()=>Oee,getRecommendedModelForTier:()=>Mee,isModelAvailableForTier:()=>Pee});var gKr=E({"src/lib/providers/anthropic/index.ts"(){"use strict";fKr(),QNt()}}),Og,us,yKr,vKr,iLt,sLt,aLt,Kx,lLt,wKr,TKr,bKr,_Kr,EKr,SKr,kKr,xKr,AKr,CKr,IKr,RKr,PKr,MKr,OKr,DKr,NKr,LKr,FKr,$Kr,UKr,BKr,zKr,GKr,qKr,VKr,jKr,HKr,WKr,KKr,JKr,XKr,YKr,ZKr,QKr,eJr,tJr,rJr,nJr,cLt=E({"npm-stub:@aws-sdk/client-bedrock-runtime"(){Og={get(e,t){return t==="__esModule"?!0:t==="default"?new Proxy({},{get:Og.get}):new Proxy(function(...r){return new Proxy({},{get:Og.get})},{get:Og.get,apply(r,n,o){return new Proxy({},{get:Og.get})},construct(r,n){return new Proxy({},{get:Og.get})}})}},us=new Proxy({},Og),{BedrockClient:yKr,ListFoundationModelsCommand:vKr,BedrockRuntimeClient:iLt,ConverseCommand:sLt,ConverseStreamCommand:aLt,ImageFormat:Kx,InvokeModelCommand:lLt}=us,{SageMakerRuntimeClient:wKr,InvokeEndpointCommand:TKr,InvokeEndpointWithResponseStreamCommand:bKr}=us,{GoogleAuth:_Kr,VertexAI:EKr,TextToSpeechClient:SKr}=us,{Webhook:kKr}=us,{Hippocampus:xKr,HippocampusConfig:AKr}=us,{createClient:CKr}=us,{Queue:IKr,Worker:RKr,Job:PKr,QueueScheduler:MKr,FlowProducer:OKr}=us,{Cron:DKr}=us,{parseBuffer:NKr,selectCover:LKr}=us,{extractRawText:FKr,convertToHtml:$Kr}=us,{Hono:UKr}=us,{cors:BKr,HTTPException:zKr,logger:GKr,secureHeaders:qKr,streamSSE:VKr,timeout:jKr}=us,HKr=globalThis.fetch,WKr=globalThis.Request,KKr=globalThis.Response,JKr=globalThis.Headers,XKr=globalThis.FormData,YKr=globalThis.File,ZKr=globalThis.Blob,QKr=us.Agent,eJr=us.Pool,tJr=us.Client,rJr=us.Dispatcher,nJr=us.MockAgent}});function oJr(e){if(/^(us|ca)-/.test(e))return"us";if(/^(eu|il|me|af)-/.test(e))return"eu";if(/^ap-northeast-[13]$/.test(e))return"jp";if(/^ap-southeast-[246]$/.test(e))return"au";if(/^ap-/.test(e))return"apac"}function iJr(e){return/^(us|eu|au|jp|apac|global)\./.test(e)}function uLt(e){if(typeof e!="object"||e===null)return!1;const t=e,r=typeof t.name=="string"?t.name:"",n=typeof t.message=="string"?t.message:"";return!/ValidationException/i.test(r)&&!/ValidationException/i.test(n)?!1:/inference profile/i.test(n)&&/on-demand throughput/i.test(n)}function sJr(e,t){if(e.startsWith("arn:")||iJr(e))return[];const r=[],n=oJr(t);return n&&r.push(`${n}.${e}`),r.push(`${mLt}.${e}`),r}function dLt(e,t){return`${e}::${t}`}function aJr(e,t){return Yee.get(dLt(t,e))}function lJr(e,t,r){Yee.set(dLt(t,e),r),h.debug("[Bedrock] Cached inference-profile resolution for subsequent calls",{region:t})}async function pLt(e,t,r){const n=aJr(e,t);if(n&&n!==e)return r(n);try{return await r(e)}catch(o){if(!uLt(o))throw o;const i=sJr(e,t);if(i.length===0)throw o;h.warn("[Bedrock] Model requires a cross-region inference profile in this region; retrying with a prefixed id",{region:t,candidates:i.length});for(const s of i)try{const a=await r(s);return lJr(e,t,s),a}catch(a){if(!uLt(a))throw a}throw o}}var mLt,Yee,cJr=E({"src/lib/providers/amazonBedrock/inferenceProfile.ts"(){"use strict";z(),mLt="global",Yee=new Map}});function cN(){return`tool_${Date.now()}_${Math.random().toString(36).substring(2,11)}`}function hLt(e,t){if(e){if(e.toolUse&&e._inputBuffer){try{e.toolUse.input=JSON.parse(e._inputBuffer)}catch{e.toolUse.input={}}delete e._inputBuffer}t&&!e.toolUse&&(e.text=t)}}function fLt(e){return e.filter(t=>t.toolUse).map(t=>({id:t.toolUse?.toolUseId??cN(),name:t.toolUse?.name??"",args:t.toolUse?.input??{}}))}async function uJr(e,t,r){const n=[],o=new Map,i=new Map,s=f=>{let g=o.get(f);return g||(g={},o.set(f,g),n.push(g)),g};let a="",l,c=0,u=0,d=0,p=0;if(e.stream)for await(const f of e.stream){if(r.aborted)break;const g=f;if(g.contentBlockStart&&s(g.contentBlockStart.contentBlockIndex??0),g.contentBlockDelta?.delta?.text){const y=g.contentBlockDelta.contentBlockIndex??0,v=g.contentBlockDelta.delta.text;s(y),a+=v,i.set(y,(i.get(y)??"")+v),t.push({content:v})}if(g.contentBlockStart?.start?.toolUse){const y=s(g.contentBlockStart.contentBlockIndex??0);y.toolUse={name:g.contentBlockStart.start.toolUse.name??"",input:{},toolUseId:g.contentBlockStart.start.toolUse.toolUseId??cN()}}if(g.contentBlockDelta?.delta?.toolUse){const y=s(g.contentBlockDelta.contentBlockIndex??0);y.toolUse??={name:"",input:{},toolUseId:cN()};const v=g.contentBlockDelta.delta.toolUse.input;typeof v=="string"?y._inputBuffer=(y._inputBuffer??"")+v:typeof v=="object"&&v!==null&&!Array.isArray(v)&&(y.toolUse.input={...y.toolUse.input??{},...v})}if(g.contentBlockStop){const y=g.contentBlockStop.contentBlockIndex??0;hLt(o.get(y),i.get(y)??"")}if(g.messageStop){l=g.messageStop.stopReason??"end_turn";continue}if(g.metadata?.usage){c+=g.metadata.usage.inputTokens??0,u+=g.metadata.usage.outputTokens??0,d+=g.metadata.usage.cacheReadInputTokens??0,p+=g.metadata.usage.cacheWriteInputTokens??0;break}}for(const[f,g]of o)hLt(g,i.get(f)??"");const m=n.filter(f=>f.text||f.toolUse||f.image||f.document);return{text:a,toolCalls:fLt(m),usage:{inputTokens:c,outputTokens:u,cacheReadTokens:d,cacheWriteTokens:p},rawStopReason:l,raw:m}}function dJr(e){const t=[];let r="";for(const n of e.output?.message?.content??[]){const o={};"text"in n&&n.text&&(o.text=n.text,r+=r?` ${n.text}`:n.text),"toolUse"in n&&n.toolUse&&(o.toolUse={toolUseId:n.toolUse.toolUseId??cN(),name:n.toolUse.name??"",input:n.toolUse.input??{}}),t.push(o)}return{text:r,toolCalls:fLt(t),usage:{inputTokens:e.usage?.inputTokens??0,outputTokens:e.usage?.outputTokens??0,cacheReadTokens:e.usage?.cacheReadInputTokens??0,cacheWriteTokens:e.usage?.cacheWriteInputTokens??0},rawStopReason:e.stopReason,raw:t}}function gLt(e){return{providerLabel:"bedrock",maxSteps:e.maxSteps,buildStepRequest(t,r){return{raw:e.buildCommandInput(t,r)}},async executeStep(t,r,n){const o=t.raw;if(!e.streaming){const s=await pLt(o.modelId??"",e.region,a=>ze(e.client.send(new sLt({...o,modelId:a}),{abortSignal:n}),Zee,new Error("Bedrock API call timed out")));if(!s.output?.message)throw new Error("Invalid response structure from Bedrock API");return dJr(s)}const i=await pLt(o.modelId??"",e.region,s=>ze(e.client.send(new aLt({...o,modelId:s}),{abortSignal:n}),Zee,new Error("Bedrock streaming API call timed out")));return uJr(i,r,n)},buildToolResultMessages(t,r,n){const o={role:"assistant",content:r.raw},i={role:"user",content:n.map(s=>({toolResult:{toolUseId:s.id,content:[{text:s.error?`Error executing tool ${s.name}: ${s.error}`:String(typeof s.output=="string"?s.output:JSON.stringify(s.output))}],status:s.error?"error":"success"}}))};return[...t,o,i]},mapFinishReason(t,r){switch(t){case"end_turn":case"stop_sequence":return"stop";case"max_tokens":return"length";case"tool_use":return"tool-calls";default:return r?"tool-calls":"stop"}}}}var Zee,pJr=E({"src/lib/providers/amazonBedrock/loopAdapter.ts"(){"use strict";cLt(),et(),cJr(),Zee=12e4}});function mJr(e){return bLt.filter(t=>{const r=e[t];return Array.isArray(r)?r.length>0:r!==void 0})}function yLt(e){return e&&"json"in e?e.json:void 0}function vLt(e){return e.every(t=>t.content.every(r=>r.text!==void 0&&r.image===void 0&&r.document===void 0&&r.toolUse===void 0&&r.toolResult===void 0))}function wLt(e,t){const r=[{role:"system",content:e}];for(const n of t){const o=n.content.map(i=>i.text??"").join("");n.role==="user"?r.push({role:"user",content:o}):r.push({role:"assistant",content:o})}return r}function hJr(e){return typeof e=="string"?e:e.filter(t=>typeof t=="object"&&t!==null&&t.type==="text").map(t=>t.text).join("")}function TLt(e){const t=[],r=[];for(const n of e){if(n.role==="system"){t.push(n.content);continue}if(n.role==="tool"){h.warn("[AmazonBedrockProvider] middleware transformParams introduced a 'tool' role message; it has no Bedrock wire shape at this boundary and was dropped");continue}r.push({role:n.role,content:[{text:hJr(n.content)}]})}return{system:t.join(`
|
|
1111
|
+
`);return{...i!==void 0?{system:i}:{},messages:r}},Wee=e=>{if(!(!e||e==="auto")){if(e==="none")return{type:"none"};if(e==="required")return{type:"any"};if(typeof e=="object"){const t=e;if(t.type==="tool"&&t.toolName)return{type:"tool",name:t.toolName}}}},Kee=(e,t)=>t?.type!=="any"&&t?.type!=="tool"||ef(e)?t:(h.warn(`[anthropic] ${e} rejects tool_choice "${t.type}"; sending "auto" instead`),{type:"auto",...t.disable_parallel_tool_use!==void 0?{disable_parallel_tool_use:t.disable_parallel_tool_use}:{}}),Jee=e=>{switch(e){case"max_tokens":return"length";case"tool_use":return"tool-calls";case"refusal":return"content-filter";default:return"stop"}},Xee=6e5,nLt=class extends Ma{client;authMethod;subscriptionTier;enableBetaFeatures;baseURL;oauthToken;lastResponseMetadata=null;usageInfo=null;refreshPromise;constructor(e,t,r,n){const o=!!(n?.apiKey&&!n?.oauthToken),i=o?null:(n?.oauthToken?{accessToken:n.oauthToken}:null)??r?.oauthToken??jee(),s=o?"api_key":r?.authMethod??rLt(i),a=r?.subscriptionTier??(s==="oauth"?tLt(i):"api"),l=e||kw(),c=hKr(n?.baseURL??r?.baseURL??process.env.ANTHROPIC_BASE_URL);let u=l;!(c!==void 0)&&a!=="api"&&!Pee(l,a)&&(u=Mee(a),h.warn("Model not available for subscription tier, using recommended model",{requestedModel:l,subscriptionTier:a,recommendedModel:u})),super(u,"anthropic",t),this.enableBetaFeatures=r?.enableBetaFeatures??!0,this.oauthToken=i,this.subscriptionTier=a,this.baseURL=c,this.authMethod=s;const p=this.getAuthHeaders();let m;if(h.debug("[AnthropicProvider] Constructor - checking OAuth:",{authMethod:this.authMethod,hasOAuthToken:!!this.oauthToken,hasAccessToken:!!this.oauthToken?.accessToken}),this.authMethod==="oauth"&&this.oauthToken){h.debug("[AnthropicProvider] Creating OAuth fetch wrapper...");const f=this.oauthToken,g=qWr(()=>f.accessToken,this.enableBetaFeatures,!1,!0);m=new Rg({apiKey:"oauth-authenticated",...this.baseURL&&{baseURL:this.baseURL},fetch:MNt(g),timeout:Xee,maxRetries:0}),h.debug("[AnthropicProvider] Anthropic SDK client created with OAuth fetch wrapper"),h.debug("Anthropic Provider initialized with OAuth",{modelName:this.modelName,provider:this.providerName,authMethod:this.authMethod,subscriptionTier:this.subscriptionTier,enableBetaFeatures:this.enableBetaFeatures,hasRefreshToken:!!this.oauthToken.refreshToken,tokenExpiry:this.oauthToken.expiresAt?new Date(this.oauthToken.expiresAt).toISOString():"none"})}else{const f=n?.apiKey??r?.apiKey??Vee();m=new Rg({apiKey:f,defaultHeaders:p,...this.baseURL&&{baseURL:this.baseURL},fetch:MNt(Ot()),timeout:Xee,maxRetries:0}),h.debug("Anthropic Provider initialized with API key",{modelName:this.modelName,provider:this.providerName,authMethod:this.authMethod,subscriptionTier:this.subscriptionTier,enableBetaFeatures:this.enableBetaFeatures})}this.client=m,this.usageInfo={messagesUsed:0,messagesRemaining:-1,tokensUsed:0,tokensRemaining:-1,inputTokensUsed:0,outputTokensUsed:0,lastRequestTimestamp:0,isRateLimited:!1,requestCount:0,messageQuotaPercent:0,tokenQuotaPercent:0},h.debug("Anthropic Provider v2 initialized",{modelName:this.modelName,provider:this.providerName,authMethod:this.authMethod,subscriptionTier:this.subscriptionTier,enableBetaFeatures:this.enableBetaFeatures,betaFeatures:this.enableBetaFeatures?lN["anthropic-beta"]:"disabled"})}getAuthHeaders(){const e={},t=this.baseURL!==void 0;if(this.enableBetaFeatures)if(t){const r=process.env.ANTHROPIC_ENABLE_LONG_CONTEXT_BETA==="1"||process.env.ANTHROPIC_ENABLE_LONG_CONTEXT_BETA==="true",n=[...jx,"fine-grained-tool-streaming-2025-05-14","interleaved-thinking-2025-05-14","redact-thinking-2026-02-12"];r&&n.push("context-1m-2025-08-07"),e["anthropic-beta"]=n.join(",")}else e["anthropic-beta"]=lN["anthropic-beta"];return t&&(e["User-Agent"]=Pg),this.subscriptionTier!=="api"&&(e["x-subscription-tier"]=this.subscriptionTier),e}validateModelAccess(e){if(this.baseURL!==void 0)return h.debug("[validateModelAccess] Bypassing tier check (a base URL is set \u2014 the proxy enforces access)",{model:e}),!0;if(this.subscriptionTier==="api")return!0;const t=Pee(e,this.subscriptionTier);return t||h.debug("[validateModelAccess] Model not available for tier",{model:e,tier:this.subscriptionTier}),t}getUsageInfo(){return this.usageInfo}areBetaFeaturesEnabled(){return this.enableBetaFeatures}getModelCapabilities(){return Oee(this.modelName||this.getDefaultModel())}getSubscriptionTier(){return this.subscriptionTier}getAuthMethod(){return this.authMethod}async refreshAuthIfNeeded(){if(this.authMethod!=="oauth"||!this.oauthToken){h.debug("Token refresh not applicable for API key authentication");return}if(!this.oauthToken.expiresAt){h.debug("Token has no expiry information, assuming valid");return}const e=Date.now(),t=this.oauthToken.expiresAt<=e,r=this.oauthToken.expiresAt<=e+yhe;if(!t&&!r){h.debug("OAuth token is still valid",{expiresInMs:this.oauthToken.expiresAt-e});return}if(!this.oauthToken.refreshToken){if(t)throw new Wr("OAuth token expired and no refresh token available. Please re-authenticate.",this.providerName);h.warn("OAuth token expiring soon but no refresh token available",{expiresInMs:this.oauthToken.expiresAt-e});return}if(this.refreshPromise){await this.refreshPromise;return}h.info("Refreshing OAuth token",{isExpired:t,expiresInMs:this.oauthToken.expiresAt-e});const n=this.oauthToken,o=n.refreshToken;this.refreshPromise=(async()=>{const s=new AbortController,a=setTimeout(()=>s.abort(),3e4),l=await fetch(Vx,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded","User-Agent":Pg},body:new URLSearchParams({grant_type:"refresh_token",refresh_token:o,client_id:Iee}),signal:s.signal});if(clearTimeout(a),!l.ok){const d=await l.text();throw new Wr(`Failed to refresh OAuth token: ${l.status} ${d}`,this.providerName)}const c=await l.json();n.accessToken=c.access_token,n.refreshToken=c.refresh_token||n.refreshToken,n.expiresAt=c.expires_in?Date.now()+c.expires_in*1e3:void 0,n.tokenType=c.token_type||"Bearer";const u=n;try{const d=Rt(Fs(),".neurolink");os(d)||W8(d,{recursive:!0});const p=Rt(d,"anthropic-credentials.json"),m=`${p}.tmp`,g={...os(p)?JSON.parse(Cd(p,"utf-8")):{},type:"oauth",oauth:u,updatedAt:Date.now()};N4(m,JSON.stringify(g,null,2),{mode:384}),X8(m,p),h.debug("Refreshed OAuth credentials persisted to disk")}catch(d){h.warn("Failed to persist refreshed OAuth token to disk",{error:d instanceof Error?d.message:String(d)})}h.info("OAuth token refreshed successfully",{hasNewRefreshToken:!!c.refresh_token,expiresIn:c.expires_in})})();try{await this.refreshPromise}catch(i){throw i instanceof Wr?i:new Wr(`Failed to refresh OAuth token: ${i instanceof Error?i.message:String(i)}`,this.providerName)}finally{this.refreshPromise=void 0}}getLastResponseMetadata(){return this.lastResponseMetadata}updateResponseMetadata(e,t,r){this.lastResponseMetadata={rateLimit:e,...t?{requestId:t}:{}},this.usageInfo&&(this.usageInfo.requestCount++,this.usageInfo.messagesUsed++,this.usageInfo.lastRequestTimestamp=Date.now(),r&&(r.inputTokens!==void 0&&(this.usageInfo.inputTokensUsed+=r.inputTokens,this.usageInfo.tokensUsed+=r.inputTokens),r.outputTokens!==void 0&&(this.usageInfo.outputTokensUsed+=r.outputTokens,this.usageInfo.tokensUsed+=r.outputTokens)),e?.requestsRemaining!==void 0&&(this.usageInfo.messagesRemaining=e.requestsRemaining),e?.tokensRemaining!==void 0&&(this.usageInfo.tokensRemaining=e.tokensRemaining),e?.requestsLimit&&e.requestsLimit>0&&(this.usageInfo.messageQuotaPercent=Math.round((e.requestsLimit-(e.requestsRemaining??0))/e.requestsLimit*100)),e?.tokensLimit&&e.tokensLimit>0&&(this.usageInfo.tokenQuotaPercent=Math.round((e.tokensLimit-(e.tokensRemaining??0))/e.tokensLimit*100)),e?.retryAfter!==void 0?(this.usageInfo.isRateLimited=!0,this.usageInfo.rateLimitExpiresAt=Date.now()+e.retryAfter*1e3):(this.usageInfo.isRateLimited=!1,this.usageInfo.rateLimitExpiresAt=void 0)),e?.requestsRemaining!==void 0&&e.requestsRemaining<=5&&h.warn("Approaching Anthropic request rate limit",{remaining:e.requestsRemaining,limit:e.requestsLimit,reset:e.requestsReset}),e?.tokensRemaining!==void 0&&e.tokensLimit&&e.tokensRemaining<e.tokensLimit*.1&&h.warn("Approaching Anthropic token rate limit",{remaining:e.tokensRemaining,limit:e.tokensLimit,reset:e.tokensReset})}getProviderName(){return"anthropic"}getDefaultModel(){return kw()}getAISDKModel(){const e=this.client,t=this.providerName,r=this.modelName||kw(),n=s=>this.getTimeout(s??{}),o=()=>this.refreshAuthIfNeeded();return{specificationVersion:"v3",provider:t,modelId:r,supportedUrls:{},doGenerate:async s=>{await o();const a=Hee(s.prompt),l=a.messages;let c=a.system,u=(s.tools??[]).filter(L=>L.type==="function").map(L=>{const j=rp(L);return{name:L.name,...L.description?{description:L.description}:{},input_schema:L.inputSchema??{type:"object",properties:{}},...j?{cache_control:j}:{}}});u&&u.length===0&&(u=void 0);const d=SVr(s.toolChoice);let p=d?Wee(d):void 0,m;if(s.responseFormat?.type==="json"){m=s.responseFormat.name??"json";const L=s.responseFormat.schema??{type:"object"};u=[{name:m,description:s.responseFormat.description??"Respond by calling this tool with the answer as its input.",input_schema:L}],ef(r)?p={type:"tool",name:m}:(p=void 0,c=WNt(c,m))}p=Kee(r,p);const f=s.providerOptions?.anthropic?.finalResultSchema;let g=!1;if(!m&&f){const L=HNt(u,f);u=L.tools,g=L.applied,L.applied&&(c=KNt(c))}const y=s.providerOptions?.anthropic?.thinking,v=y?.type==="enabled";u=AY(u);const T=Fee({system:c,tools:u,messages:l}),b=zNt(l,nN-T),S=Ac("anthropic",r,{...s.temperature!==void 0&&s.temperature!==null?{temperature:s.temperature}:{},...s.topP!==void 0&&s.topP!==null?{topP:s.topP}:{}},"anthropic.doGenerate");v&&(S.temperature!==void 0||S.topP!==void 0)&&h.debug("[anthropic] extended thinking is enabled, so temperature/top_p are omitted \u2014 Anthropic rejects any temperature but 1 while thinking is set");const k={model:r,messages:b,max_tokens:Gk(r,s.maxOutputTokens),...c?{system:c}:{},...!v&&S.temperature!==void 0?{temperature:S.temperature}:{},...!v&&S.topP!==void 0?{top_p:S.topP}:{},...s.stopSequences&&s.stopSequences.length>0?{stop_sequences:s.stopSequences}:{},...u?{tools:u}:{},...p?{tool_choice:p}:{},...y?{thinking:y}:{}},A=s.providerOptions?.neurolink,x=typeof A?.timeoutMs=="number"&&Number.isFinite(A.timeoutMs)&&A.timeoutMs>0?A.timeoutMs:void 0,P=x!==void 0?x:k.max_tokens>8192?Math.max(n(s),3e5):n(s),C=wa(P,t,"generate"),R=Cy(s.abortSignal,C?.controller.signal);let O;try{O=await e.messages.create(k,{signal:R})}catch(L){const j=R?.aborted?R.reason:void 0;throw j instanceof Ta?j:L}finally{C?.cleanup()}const U=[];let M;const D=[];let $=!1;for(const L of O.content)L.type==="thinking"?U.push({type:"reasoning",text:L.thinking,providerOptions:{anthropic:{signature:L.signature}}}):L.type==="redacted_thinking"?U.push({type:"reasoning",text:"",providerOptions:{anthropic:{redactedData:L.data}}}):L.type==="text"?m?D.push(L.text):U.push({type:"text",text:L.text}):L.type==="tool_use"&&(m&&L.name===m?($=!0,U.push({type:"text",text:Xk(L.input)})):g&&L.name===Mg?M=Xk(L.input):U.push({type:"tool-call",toolCallId:L.id,toolName:L.name,input:Xk(L.input)}));if(m&&!$&&D.length>0&&U.push({type:"text",text:D.join("")}),M!==void 0){const L=U.filter(j=>j.type==="reasoning");U.length=0,U.push(...L,{type:"text",text:M}),h.debug("[Anthropic] Extracted structured output from final_result tool (generate)",{chars:M.length})}const B=O.usage.cache_read_input_tokens??0,q=O.usage.cache_creation_input_tokens??0;return{content:U,finishReason:{unified:M!==void 0&&Jee(O.stop_reason)==="tool-calls"?"stop":Jee(O.stop_reason),raw:O.stop_reason??"stop"},usage:{inputTokens:{total:O.usage.input_tokens+B+q,noCache:O.usage.input_tokens,cacheRead:B,cacheWrite:q},outputTokens:{total:O.usage.output_tokens,text:O.usage.output_tokens,reasoning:void 0}},warnings:[],request:{body:k},response:{id:O.id,modelId:O.model,headers:XWr()??{},body:O}}},doStream:()=>{throw new Error(`${t}: doStream is not implemented on the delegating model. NeuroLink streams through executeStream, reached via NeuroLink.stream() \u2014 use that (the browser bundle exports the NeuroLink class) rather than calling doStream on a model handle.`)}}}formatProviderError(e){return ba(e,[{match:r=>r.statusCode===401||/API_KEY_INVALID|Invalid API key/i.test(r.message),errorClass:Wr,message:"Invalid Anthropic API key. Please check your ANTHROPIC_API_KEY environment variable."},{match:r=>r.statusCode===429||/rate limit|too_many_requests/i.test(r.message)||im(r.message,429),errorClass:Qi,message:"Anthropic rate limit exceeded. Please try again later."},{match:r=>/ECONNRESET|ENOTFOUND|ECONNREFUSED|network|connection/i.test(r.message),errorClass:ai,message:r=>`Connection error: ${r.message}`},{match:r=>r.statusCode!==void 0&&r.statusCode>=500&&r.statusCode<=599||/server error|bad gateway|service unavailable|gateway timeout|\berror\b\D{0,12}\b5\d\d\b|\b5\d\d\b\D{0,12}\berror\b|\bstatus(?:\s*code)?\b\D{0,12}\b5\d\d\b/i.test(r.message),errorClass:nt,message:r=>`Server error: ${r.message}`},{match:()=>!0,errorClass:nt,message:r=>`Anthropic error: ${r.message}`}],this.providerName,this.modelName)}async generate(e,t){await this.refreshAuthIfNeeded();const{result:r,snapshot:n}=await KWr(()=>this.dispatchGenerate(e,t));return r&&n&&(this.recordLimitSnapshot(n),r.limits=n,r.analytics&&(r.analytics.limits=n)),r}async dispatchGenerate(e,t){await this.ensureModelLimits();const r=this.normalizeTextOptions(e);if($d(r,this.modelName)!=="text")return super.generate(r,t);this.validateOptions(r);const n=await this.getToolsForStream(r),o="disableInternalFallback"in r&&r.disableInternalFallback===!0;return this.runGenerateWithModelFallback(()=>this.withTurnTimeout({...r,tools:n},this.getDescriptorGenerateMs(),i=>this.executeNativeGenerate(i)),o,r)}async executeNativeGenerate(e){const t=Date.now(),r=this.modelName||kw(),n=await this.getAISDKModelWithMiddleware(e);if(!ex(n))throw this.handleProviderError(new Error("anthropic: model handle exposes no doGenerate()"));const o=n.doGenerate.bind(n),s=!e.disableTools&&this.supportsTools()?e.tools||{}:{},a=Object.entries(s).map(([T,b])=>{const S=b;return{type:"function",name:T,description:S.description??"",inputSchema:S.inputSchema?qo(S.inputSchema):{type:"object",properties:{}}}}),l=a.length>0,c=e.schema?qo(e.schema):void 0,u=c&&!l?{type:"json",schema:c}:void 0,d={};c&&l&&(d.finalResultSchema=c),e.thinkingConfig?.enabled&&e.thinkingConfig.budgetTokens?d.thinking={type:"enabled",budget_tokens:e.thinkingConfig.budgetTokens}:e.thinkingConfig?.type==="disabled"&&(d.thinking={type:"disabled"});const p={};Object.keys(d).length>0&&(p.anthropic=d),typeof e.timeout=="number"&&(p.neurolink={timeoutMs:e.timeout});const m=Object.keys(p).length>0?p:void 0,f=await this.buildMessagesForStream(e),g=[],y=await BO({doGenerate:o,...SRt({provider:"anthropic",availableInputTokens:ql("anthropic",r,e.maxTokens??void 0),getFixedOverheadTokens:()=>Vt(xk({tools:a,responseFormat:u,providerOptions:m}),"anthropic")}),conversation:f,...l?{tools:a}:{},toolsRecord:s,...l&&e.toolChoice?{toolChoice:VO(e,s,!0)}:{},...u?{responseFormat:u}:{},...m?{providerOptions:m}:{},maxSteps:e.maxSteps||ts,...e.maxTokens?{maxOutputTokens:e.maxTokens}:{},...e.temperature!==void 0?{temperature:e.temperature}:{},...e.abortSignal?{abortSignal:e.abortSignal}:{},...e.toolTimeoutMs!==void 0?{toolTimeoutMs:e.toolTimeoutMs}:{},runStep:T=>Py(T,dt.getActiveSpan()??void 0,"anthropic generate",void 0,e.abortSignal).catch(b=>{throw this.handleProviderError(b)})},g),v={content:y.text,provider:this.providerName,model:r,finishReason:y.finishReason,...y.rawFinishReason?{rawFinishReason:y.rawFinishReason}:{},...y.reasoning?{reasoning:y.reasoning}:{},usage:{input:y.inputTokens,output:y.outputTokens,total:y.inputTokens+y.outputTokens+y.cacheReadTokens+y.cacheWriteTokens,...y.cacheReadTokens?{cacheReadTokens:y.cacheReadTokens}:{},...y.cacheWriteTokens?{cacheCreationTokens:y.cacheWriteTokens}:{}},responseTime:Date.now()-t,toolsUsed:y.toolsUsed,toolCalls:HH(g),toolExecutions:Df(e,Bd(g)),enhancedWithTools:y.toolsUsed.length>0};return this.finalizeNativeGenerate(v,e,t)}recordLimitSnapshot(e){this.updateResponseMetadata(e.rateLimit,e.requestId),ZWr(e),QWr(e,this.modelName)}supportsExecutionControl(){return!0}async executeStream(e,t){return YWr(()=>this.executeStreamInCaptureScope(e,t))}async executeStreamInCaptureScope(e,t){await this.refreshAuthIfNeeded(),this.validateStreamOptions(e);const r=e.executionControl,n=typeof e.turnTimeoutMs=="number"&&Number.isFinite(e.turnTimeoutMs)&&e.turnTimeoutMs>0,o=r&&r.lifetimeTimeoutMs!==void 0?r.lifetimeTimeoutMs??void 0:n?e.turnTimeoutMs:this.getTimeout(e),i=wa(o,this.providerName,"stream"),s=new AbortController,a=Mbe([e.abortSignal,i?.controller.signal,s.signal]).signal;let l,c,u,d,p=!1;try{d=!e.disableTools&&this.supportsTools(),l=d?e.tools||await this.getAllTools():{},c=d?Xv(l,"input_schema"):void 0;const Ce=await this.buildMessagesForStream(e);if(u=Hee(Ce),e.schema&&c&&c.length>0){const ye=HNt(c,qo(e.schema));c=ye.tools,p=ye.applied,ye.applied&&(u.system=KNt(u.system))}}catch(Ce){throw i?.cleanup(),this.handleProviderError(Ce)}const m=this.modelName||kw(),f=d&&c&&c.length>0?Kee(m,Wee(VO(e,l,d))):void 0,g=e.thinkingConfig?.enabled&&e.thinkingConfig.budgetTokens?{type:"enabled",budget_tokens:e.thinkingConfig.budgetTokens}:e.thinkingConfig?.type==="disabled"?{type:"disabled"}:void 0,y=g?.type==="enabled",v=eLt.startSpan("neurolink.provider.streamText",{kind:nn.CLIENT,attributes:{"gen_ai.system":"anthropic","gen_ai.request.model":m}}),T=e.maxSteps||ts,b=this.neurolink?.getEventEmitter(),S=Kv(),{push:k}=S,{usagePromise:A,finishPromise:x,resolveUsage:P,resolveFinish:C}=aZ();A.then(Ce=>{v.setAttribute("gen_ai.usage.input_tokens",Ce.promptTokens||0),v.setAttribute("gen_ai.usage.output_tokens",Ce.completionTokens||0),Ce.cacheReadTokens&&v.setAttribute("gen_ai.usage.cached_input_tokens",Ce.cacheReadTokens);const ye=Ls(this.providerName,this.modelName,{input:Ce.promptTokens||0,output:Ce.completionTokens||0,total:Ce.totalTokens||0,...Ce.cacheReadTokens?{cacheReadTokens:Ce.cacheReadTokens}:{},...Ce.cacheCreationTokens?{cacheCreationTokens:Ce.cacheCreationTokens}:{}});ye&&ye>0&&v.setAttribute("neurolink.cost",ye)}).catch(()=>{}),x.then(Ce=>{v.setAttribute("gen_ai.response.finish_reason",Ce||"unknown"),v.end()}).catch(()=>{v.end()});let R;const O=this.client,U=[],M=Date.now(),D={};let $=0,B=0,q=0,L=0,j=null;const G=()=>({promptTokens:$,completionTokens:B,totalTokens:$+q+L+B,...q>0?{cacheReadTokens:q}:{},...L>0?{cacheCreationTokens:L}:{}});let J="",K;const de=(Ce,ye)=>{const Ne=xe=>{if(typeof xe=="string")return xe;try{return JSON.stringify(xe)??""}catch{return""}};return Vt(Ne(Ce),"anthropic")+Vt(Ne(ye),"anthropic")},ae=(async()=>{let Ce,ye;const le=Uee({client:O,maxSteps:T,toolsRecord:l,buildParams:W=>{if(c){const ie=new Set(c.map(I=>I.name)),ce=Object.fromEntries(Object.entries(l).filter(([I])=>!ie.has(I)));if(Object.keys(ce).length>0){const I=Xv(ce,"input_schema");I&&I.length>0&&(c=[...c,...I])}}const te=AY(c),me=Fee({system:u.system,tools:te,messages:W}),Te=zNt(W,nN-me),pe=Ac("anthropic",m,e.temperature!==void 0&&e.temperature!==null?{temperature:e.temperature}:{},"anthropic.executeStream");return y&&pe.temperature!==void 0&&h.debug("[anthropic] extended thinking is enabled, so temperature is omitted on the stream path \u2014 Anthropic rejects any temperature but 1 while thinking is set"),{model:m,messages:Te,max_tokens:Gk(m,e.maxTokens),...u.system?{system:u.system}:{},...!y&&pe.temperature!==void 0?{temperature:pe.temperature}:{},...te&&te.length>0?{tools:te}:{},...f?{tool_choice:f}:{},...g?{thinking:g}:{}}},planReclaim:W=>{const te=UNt({conversation:W,availableInputTokens:ql("anthropic",m,e.maxTokens??void 0),fixedOverheadTokens:de(u.system,c),provider:"anthropic",observedPromptTokens:Ce,previousSentEstimate:ye,onSentEstimate:ie=>{ye=ie}});if(!te)return;const me=new Set(te.drop),Te=new Set(te.truncate),pe=[];for(let ie=0;ie<W.length;ie++){if(me.has(ie))continue;const ce=W[ie];if(Te.has(ie)&&Array.isArray(ce.content)){pe.push({...ce,content:ce.content.map(I=>I.type==="tool_result"?{...I,content:$Nt(typeof I.content=="string"?I.content:JSON.stringify(I.content)??"")}:I)});continue}pe.push(ce)}if(me.size>0){let ie=pe.findIndex(ce=>Array.isArray(ce.content)&&ce.content.some(I=>I.type==="tool_use"||I.type==="tool_result"));ie<0&&(ie=Math.min(1,pe.length)),pe.splice(ie,0,{role:"user",content:[{type:"text",text:Lee}]})}return{conversation:pe}},...r?{requestTimeoutMs:r.requestTimeoutMs,requireTerminalEvent:!0}:{},noteObservedPromptTokens:W=>{Ce=W},...p?{finalResultToolName:Mg,onTerminalResult:W=>{K=W,h.debug("[Anthropic] Extracted structured output from final_result tool (stream)",{chars:W.length})}}:{}}),Oe={...le,buildToolResultMessages:(W,te,me,Te)=>{for(const ce of me)U.push(ce.name);const pe=me.map(ce=>({type:"tool-call",toolCallId:ce.id,toolName:ce.name,args:ce.args})),ie=me.map(ce=>ce.error?{type:"tool-result",toolCallId:ce.id,toolName:ce.name,error:ce.error}:{type:"tool-result",toolCallId:ce.id,toolName:ce.name,result:ce.output});return PRt(b,ie.map(ce=>({toolName:ce.toolName,result:"result"in ce?ce.result:void 0,error:"error"in ce?ce.error:void 0}))),this.handleToolExecutionStorage(pe,ie,e,new Date).catch(ce=>{h.warn("[AnthropicProvider] Failed to store tool executions",{provider:this.providerName,error:ce instanceof Error?ce.message:String(ce)})}),le.buildToolResultMessages(W,te,me,Te)}},Ie={};for(const[W,te]of Object.entries(l)){const me=te.execute;me&&(Ie[W]={execute:async(Te,pe)=>{const ie=pe;return me(Te,{toolCallId:ie.toolCallId??"",...ie.abortSignal?{abortSignal:ie.abortSignal}:{},messages:[]})}})}const Ge=dt.getActiveSpan(),je=r?.beforeStep,_e=je?async W=>{const te=r?.beforeStepTimeoutMs??YJ,me=wa(te,this.providerName,"stream"),Te=T4(W.signal,me?.controller.signal);try{return await Su(Promise.resolve(je({...W,signal:Te.signal??W.signal})),Te.signal??W.signal)}catch(pe){h.warn("[Anthropic] executionControl.beforeStep failed or timed out; the step cap stands",{error:pe instanceof Error?pe.message:String(pe),stepsCompleted:W.stepsCompleted});return}finally{Te.dispose(),me?.cleanup()}}:void 0,{stream:Fe,resultPromise:Y}=tp(Oe,u.messages.slice(),{tools:Ie,...a?{abortSignal:a}:{},...Ge?{span:Ge}:{},..._e?{beforeStep:_e}:{},...e.toolTimeoutMs!==void 0?{toolTimeoutMs:e.toolTimeoutMs}:{}}),X=(async()=>{for await(const W of Fe)W.reasoning&&k({content:"",reasoning:W.reasoning}),W.content&&(p?J+=W.content:k({content:W.content}))})();let ke;try{ke=await Y}catch(W){throw await ug(X,"Anthropic"),W}if(await X,$+=ke.usage.inputTokens,B+=ke.usage.outputTokens,q+=ke.usage.cacheReadTokens??0,L+=ke.usage.cacheWriteTokens??0,j=ke.rawStopReason??j,ke.aborted){const W=a?.aborted?a.reason:void 0;D.stopReason=W instanceof Ta?"time-limit":"aborted",D.finishReason="other",ke.rawStopReason&&(D.rawFinishReason=ke.rawStopReason),P(G()),C("other");return}D.finishReason=ke.finishReason,ke.rawStopReason&&(D.rawFinishReason=ke.rawStopReason),ke.finishReason==="tool-calls"&&K===void 0&&(D.stopReason="step-cap"),P(G()),C(j??"stop")})().catch(Ce=>{throw R=Ce,h.error("Anthropic: Stream error",{error:Ce instanceof Error?Ce.message:String(Ce)}),P(G()),C("error"),this.formatProviderError(Ce)}).finally(()=>{if(p){const Ce=K??J;Ce.length>0&&k({content:Ce})}i?.cleanup(),S.close()});ae.catch(()=>{});const ge=this.providerName;return{stream:async function*(){let Ce=0;try{for await(const ye of S.iterable)"content"in ye&&typeof ye.content=="string"&&ye.content.length>0&&Ce++,yield ye;if(await ae,Ce===0&&U.length===0){h.warn(`${ge}: Stream produced no output \u2014 emitting enriched sentinel`);const ye=new xu({message:"Stream produced no output"}),Ne=await ig(ye,void 0,R);sg(Ne),yield Ne}}catch(ye){const Ne=await ig(ye,void 0,R);if(sg(Ne),yield Ne,!xu.isInstance(ye))throw ye}finally{s.signal.aborted||s.abort()}}(),provider:this.providerName,model:m,toolCalls:[],toolResults:[],metadata:D,analytics:x.then(async()=>{const Ce=await gZ.createAnalytics(this.providerName,m,{textStream:(async function*(){})(),usage:A,finishReason:x},Date.now()-M,{requestId:e.requestId??`${this.providerName}-stream-${Date.now()}`,streamingMode:!0}),ye=JWr();return ye&&Ce&&(this.recordLimitSnapshot(ye),Ce.limits=ye),Ce})}}async isAvailable(){try{return jee()||Vee(),!0}catch{return!1}}getModel(){return this.getAISDKModel()}}}}),oLt={};Z(oLt,{ANTHROPIC_BETA_HEADERS:()=>lN,AnthropicProvider:()=>nLt,ModelAccessError:()=>_5,getModelCapabilities:()=>Oee,getRecommendedModelForTier:()=>Mee,isModelAvailableForTier:()=>Pee});var gKr=E({"src/lib/providers/anthropic/index.ts"(){"use strict";fKr(),QNt()}}),Og,us,yKr,vKr,iLt,sLt,aLt,Kx,lLt,wKr,TKr,bKr,_Kr,EKr,SKr,kKr,xKr,AKr,CKr,IKr,RKr,PKr,MKr,OKr,DKr,NKr,LKr,FKr,$Kr,UKr,BKr,zKr,GKr,qKr,VKr,jKr,HKr,WKr,KKr,JKr,XKr,YKr,ZKr,QKr,eJr,tJr,rJr,nJr,cLt=E({"npm-stub:@aws-sdk/client-bedrock-runtime"(){Og={get(e,t){return t==="__esModule"?!0:t==="default"?new Proxy({},{get:Og.get}):new Proxy(function(...r){return new Proxy({},{get:Og.get})},{get:Og.get,apply(r,n,o){return new Proxy({},{get:Og.get})},construct(r,n){return new Proxy({},{get:Og.get})}})}},us=new Proxy({},Og),{BedrockClient:yKr,ListFoundationModelsCommand:vKr,BedrockRuntimeClient:iLt,ConverseCommand:sLt,ConverseStreamCommand:aLt,ImageFormat:Kx,InvokeModelCommand:lLt}=us,{SageMakerRuntimeClient:wKr,InvokeEndpointCommand:TKr,InvokeEndpointWithResponseStreamCommand:bKr}=us,{GoogleAuth:_Kr,VertexAI:EKr,TextToSpeechClient:SKr}=us,{Webhook:kKr}=us,{Hippocampus:xKr,HippocampusConfig:AKr}=us,{createClient:CKr}=us,{Queue:IKr,Worker:RKr,Job:PKr,QueueScheduler:MKr,FlowProducer:OKr}=us,{Cron:DKr}=us,{parseBuffer:NKr,selectCover:LKr}=us,{extractRawText:FKr,convertToHtml:$Kr}=us,{Hono:UKr}=us,{cors:BKr,HTTPException:zKr,logger:GKr,secureHeaders:qKr,streamSSE:VKr,timeout:jKr}=us,HKr=globalThis.fetch,WKr=globalThis.Request,KKr=globalThis.Response,JKr=globalThis.Headers,XKr=globalThis.FormData,YKr=globalThis.File,ZKr=globalThis.Blob,QKr=us.Agent,eJr=us.Pool,tJr=us.Client,rJr=us.Dispatcher,nJr=us.MockAgent}});function oJr(e){if(/^(us|ca)-/.test(e))return"us";if(/^(eu|il|me|af)-/.test(e))return"eu";if(/^ap-northeast-[13]$/.test(e))return"jp";if(/^ap-southeast-[246]$/.test(e))return"au";if(/^ap-/.test(e))return"apac"}function iJr(e){return/^(us|eu|au|jp|apac|global)\./.test(e)}function uLt(e){if(typeof e!="object"||e===null)return!1;const t=e,r=typeof t.name=="string"?t.name:"",n=typeof t.message=="string"?t.message:"";return!/ValidationException/i.test(r)&&!/ValidationException/i.test(n)?!1:/inference profile/i.test(n)&&/on-demand throughput/i.test(n)}function sJr(e,t){if(e.startsWith("arn:")||iJr(e))return[];const r=[],n=oJr(t);return n&&r.push(`${n}.${e}`),r.push(`${mLt}.${e}`),r}function dLt(e,t){return`${e}::${t}`}function aJr(e,t){return Yee.get(dLt(t,e))}function lJr(e,t,r){Yee.set(dLt(t,e),r),h.debug("[Bedrock] Cached inference-profile resolution for subsequent calls",{region:t})}async function pLt(e,t,r){const n=aJr(e,t);if(n&&n!==e)return r(n);try{return await r(e)}catch(o){if(!uLt(o))throw o;const i=sJr(e,t);if(i.length===0)throw o;h.warn("[Bedrock] Model requires a cross-region inference profile in this region; retrying with a prefixed id",{region:t,candidates:i.length});for(const s of i)try{const a=await r(s);return lJr(e,t,s),a}catch(a){if(!uLt(a))throw a}throw o}}var mLt,Yee,cJr=E({"src/lib/providers/amazonBedrock/inferenceProfile.ts"(){"use strict";z(),mLt="global",Yee=new Map}});function cN(){return`tool_${Date.now()}_${Math.random().toString(36).substring(2,11)}`}function hLt(e,t){if(e){if(e.toolUse&&e._inputBuffer){try{e.toolUse.input=JSON.parse(e._inputBuffer)}catch{e.toolUse.input={}}delete e._inputBuffer}t&&!e.toolUse&&(e.text=t)}}function fLt(e){return e.filter(t=>t.toolUse).map(t=>({id:t.toolUse?.toolUseId??cN(),name:t.toolUse?.name??"",args:t.toolUse?.input??{}}))}async function uJr(e,t,r){const n=[],o=new Map,i=new Map,s=f=>{let g=o.get(f);return g||(g={},o.set(f,g),n.push(g)),g};let a="",l,c=0,u=0,d=0,p=0;if(e.stream)for await(const f of e.stream){if(r.aborted)break;const g=f;if(g.contentBlockStart&&s(g.contentBlockStart.contentBlockIndex??0),g.contentBlockDelta?.delta?.text){const y=g.contentBlockDelta.contentBlockIndex??0,v=g.contentBlockDelta.delta.text;s(y),a+=v,i.set(y,(i.get(y)??"")+v),t.push({content:v})}if(g.contentBlockStart?.start?.toolUse){const y=s(g.contentBlockStart.contentBlockIndex??0);y.toolUse={name:g.contentBlockStart.start.toolUse.name??"",input:{},toolUseId:g.contentBlockStart.start.toolUse.toolUseId??cN()}}if(g.contentBlockDelta?.delta?.toolUse){const y=s(g.contentBlockDelta.contentBlockIndex??0);y.toolUse??={name:"",input:{},toolUseId:cN()};const v=g.contentBlockDelta.delta.toolUse.input;typeof v=="string"?y._inputBuffer=(y._inputBuffer??"")+v:typeof v=="object"&&v!==null&&!Array.isArray(v)&&(y.toolUse.input={...y.toolUse.input??{},...v})}if(g.contentBlockStop){const y=g.contentBlockStop.contentBlockIndex??0;hLt(o.get(y),i.get(y)??"")}if(g.messageStop){l=g.messageStop.stopReason??"end_turn";continue}if(g.metadata?.usage){c+=g.metadata.usage.inputTokens??0,u+=g.metadata.usage.outputTokens??0,d+=g.metadata.usage.cacheReadInputTokens??0,p+=g.metadata.usage.cacheWriteInputTokens??0;break}}for(const[f,g]of o)hLt(g,i.get(f)??"");const m=n.filter(f=>f.text||f.toolUse||f.image||f.document);return{text:a,toolCalls:fLt(m),usage:{inputTokens:c,outputTokens:u,cacheReadTokens:d,cacheWriteTokens:p},rawStopReason:l,raw:m}}function dJr(e){const t=[];let r="";for(const n of e.output?.message?.content??[]){const o={};"text"in n&&n.text&&(o.text=n.text,r+=r?` ${n.text}`:n.text),"toolUse"in n&&n.toolUse&&(o.toolUse={toolUseId:n.toolUse.toolUseId??cN(),name:n.toolUse.name??"",input:n.toolUse.input??{}}),t.push(o)}return{text:r,toolCalls:fLt(t),usage:{inputTokens:e.usage?.inputTokens??0,outputTokens:e.usage?.outputTokens??0,cacheReadTokens:e.usage?.cacheReadInputTokens??0,cacheWriteTokens:e.usage?.cacheWriteInputTokens??0},rawStopReason:e.stopReason,raw:t}}function gLt(e){return{providerLabel:"bedrock",maxSteps:e.maxSteps,buildStepRequest(t,r){return{raw:e.buildCommandInput(t,r)}},async executeStep(t,r,n){const o=t.raw;if(!e.streaming){const s=await pLt(o.modelId??"",e.region,a=>ze(e.client.send(new sLt({...o,modelId:a}),{abortSignal:n}),Zee,new Error("Bedrock API call timed out")));if(!s.output?.message)throw new Error("Invalid response structure from Bedrock API");return dJr(s)}const i=await pLt(o.modelId??"",e.region,s=>ze(e.client.send(new aLt({...o,modelId:s}),{abortSignal:n}),Zee,new Error("Bedrock streaming API call timed out")));return uJr(i,r,n)},buildToolResultMessages(t,r,n){const o={role:"assistant",content:r.raw},i={role:"user",content:n.map(s=>({toolResult:{toolUseId:s.id,content:[{text:s.error?`Error executing tool ${s.name}: ${s.error}`:String(typeof s.output=="string"?s.output:JSON.stringify(s.output))}],status:s.error?"error":"success"}}))};return[...t,o,i]},mapFinishReason(t,r){switch(t){case"end_turn":case"stop_sequence":return"stop";case"max_tokens":return"length";case"tool_use":return"tool-calls";default:return r?"tool-calls":"stop"}}}}var Zee,pJr=E({"src/lib/providers/amazonBedrock/loopAdapter.ts"(){"use strict";cLt(),et(),cJr(),Zee=12e4}});function mJr(e){return bLt.filter(t=>{const r=e[t];return Array.isArray(r)?r.length>0:r!==void 0})}function yLt(e){return e&&"json"in e?e.json:void 0}function vLt(e){return e.every(t=>t.content.every(r=>r.text!==void 0&&r.image===void 0&&r.document===void 0&&r.toolUse===void 0&&r.toolResult===void 0))}function wLt(e,t){const r=[{role:"system",content:e}];for(const n of t){const o=n.content.map(i=>i.text??"").join("");n.role==="user"?r.push({role:"user",content:o}):r.push({role:"assistant",content:o})}return r}function hJr(e){return typeof e=="string"?e:e.filter(t=>typeof t=="object"&&t!==null&&t.type==="text").map(t=>t.text).join("")}function TLt(e){const t=[],r=[];for(const n of e){if(n.role==="system"){t.push(n.content);continue}if(n.role==="tool"){h.warn("[AmazonBedrockProvider] middleware transformParams introduced a 'tool' role message; it has no Bedrock wire shape at this boundary and was dropped");continue}r.push({role:n.role,content:[{text:hJr(n.content)}]})}return{system:t.join(`
|
|
1112
1112
|
|
|
1113
|
-
`),conversation:r}}function fJr(e,t,r){const n=e[Symbol.asyncIterator]();return new ReadableStream({async pull(o){try{const i=await n.next();i.done?(o.enqueue(await t),o.close()):i.value.reasoning?o.enqueue({type:"reasoning-delta",delta:i.value.reasoning}):o.enqueue({type:"text-delta",delta:i.value.content})}catch(i){o.error(i)}},async cancel(){r(),await n.return?.()}})}async function*gJr(e){const t=e.getReader();let r=!1;try{for(;;){const n=await t.read();if(n.done){r=!0;return}const o=n.value;if(o.type==="text-delta")yield{content:o.delta};else if(o.type==="reasoning-delta")yield{content:"",reasoning:o.delta};else if(o.type==="error")throw o.error}}finally{try{r||await t.cancel()}finally{t.releaseLock()}}}var bLt,yJr=E({"src/lib/providers/amazonBedrock/modelBridge.ts"(){"use strict";z(),bLt=["topP","topK","presencePenalty","frequencyPenalty","stopSequences","seed","toolChoice","responseFormat"]}});function _Lt(e,t,r){return{input:{text:e.input?.text||"",images:e.input?.images,content:e.input?.content,files:e.input?.files,csvFiles:e.input?.csvFiles,pdfFiles:e.input?.pdfFiles,audioFiles:e.input?.audioFiles,videoFiles:e.input?.videoFiles},csvOptions:e.csvOptions,pdfOptions:e.pdfOptions,imageOptions:e.imageOptions,videoOptions:e.videoOptions,officeOptions:e.officeOptions,systemPrompt:e.systemPrompt,conversationHistory:e.conversationMessages,provider:t,model:r,temperature:e.temperature,maxTokens:e.maxTokens,enableAnalytics:e.enableAnalytics,enableEvaluation:e.enableEvaluation,context:e.context,fileRegistry:e.fileRegistry}}var vJr=E({"src/lib/utils/multimodalOptionsBuilder.ts"(){"use strict"}}),uN,ELt=E({"src/lib/providers/amazonBedrock/constants.ts"(){"use strict";il(),uN=Be.provider}}),SLt={};Z(SLt,{Agent:()=>m3t,BedrockClient:()=>xLt,BedrockRuntimeClient:()=>CLt,Blob:()=>p3t,Client:()=>f3t,ConverseCommand:()=>ILt,ConverseStreamCommand:()=>RLt,Cron:()=>KLt,Dispatcher:()=>g3t,File:()=>d3t,FlowProducer:()=>WLt,FormData:()=>u3t,GoogleAuth:()=>LLt,HTTPException:()=>t3t,Headers:()=>c3t,Hippocampus:()=>BLt,HippocampusConfig:()=>zLt,Hono:()=>QLt,ImageFormat:()=>PLt,InvokeEndpointCommand:()=>DLt,InvokeEndpointWithResponseStreamCommand:()=>NLt,InvokeModelCommand:()=>MLt,Job:()=>jLt,ListFoundationModelsCommand:()=>ALt,MockAgent:()=>w3t,Pool:()=>h3t,Queue:()=>qLt,QueueScheduler:()=>HLt,Request:()=>a3t,Response:()=>l3t,SageMakerRuntimeClient:()=>OLt,TextToSpeechClient:()=>$Lt,VertexAI:()=>FLt,Webhook:()=>ULt,Worker:()=>VLt,convertToHtml:()=>ZLt,cors:()=>e3t,createClient:()=>GLt,default:()=>kLt,extractRawText:()=>YLt,fetch:()=>s3t,getGlobalDispatcher:()=>v3t,interceptors:()=>T3t,logger:()=>r3t,parseBuffer:()=>JLt,request:()=>b3t,secureHeaders:()=>n3t,selectCover:()=>XLt,setGlobalDispatcher:()=>y3t,streamSSE:()=>o3t,timeout:()=>i3t});var Dg,xi,kLt,xLt,ALt,CLt,ILt,RLt,PLt,MLt,OLt,DLt,NLt,LLt,FLt,$Lt,ULt,BLt,zLt,GLt,qLt,VLt,jLt,HLt,WLt,KLt,JLt,XLt,YLt,ZLt,QLt,e3t,t3t,r3t,n3t,o3t,i3t,s3t,a3t,l3t,c3t,u3t,d3t,p3t,m3t,h3t,f3t,g3t,y3t,v3t,w3t,T3t,b3t,wJr=E({"npm-stub:@aws-sdk/client-bedrock"(){Dg={get(e,t){return t==="__esModule"?!0:t==="default"?new Proxy({},{get:Dg.get}):new Proxy(function(...r){return new Proxy({},{get:Dg.get})},{get:Dg.get,apply(r,n,o){return new Proxy({},{get:Dg.get})},construct(r,n){return new Proxy({},{get:Dg.get})}})}},xi=new Proxy({},Dg),kLt=xi,{BedrockClient:xLt,ListFoundationModelsCommand:ALt,BedrockRuntimeClient:CLt,ConverseCommand:ILt,ConverseStreamCommand:RLt,ImageFormat:PLt,InvokeModelCommand:MLt}=xi,{SageMakerRuntimeClient:OLt,InvokeEndpointCommand:DLt,InvokeEndpointWithResponseStreamCommand:NLt}=xi,{GoogleAuth:LLt,VertexAI:FLt,TextToSpeechClient:$Lt}=xi,{Webhook:ULt}=xi,{Hippocampus:BLt,HippocampusConfig:zLt}=xi,{createClient:GLt}=xi,{Queue:qLt,Worker:VLt,Job:jLt,QueueScheduler:HLt,FlowProducer:WLt}=xi,{Cron:KLt}=xi,{parseBuffer:JLt,selectCover:XLt}=xi,{extractRawText:YLt,convertToHtml:ZLt}=xi,{Hono:QLt}=xi,{cors:e3t,HTTPException:t3t,logger:r3t,secureHeaders:n3t,streamSSE:o3t,timeout:i3t}=xi,s3t=globalThis.fetch,a3t=globalThis.Request,l3t=globalThis.Response,c3t=globalThis.Headers,u3t=globalThis.FormData,d3t=globalThis.File,p3t=globalThis.Blob,m3t=xi.Agent,h3t=xi.Pool,f3t=xi.Client,g3t=xi.Dispatcher,y3t=()=>{},v3t=()=>xi,w3t=xi.MockAgent,T3t={redirect:()=>e=>e,retry:()=>e=>e},b3t=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()}}}}});async function Qee(){return await Promise.resolve().then(()=>(wJr(),SLt))}var _3t=E({"src/lib/providers/amazonBedrock/utils.ts"(){"use strict"}});function TJr(e){const t=(e??"").split(";").at(0)?.trim().toLowerCase();return ete[t??""]}var ete,E3t,bJr=E({"src/lib/providers/amazonBedrock/client.ts"(){"use strict";cLt(),kr(),OS(),pl(),Zo(),RO(),vm(),zl(),Ys(),pJr(),yJr(),pt(),Zs(),et(),jf(),z(),Ic(),R2(),vJr(),ss(),Qt(),ELt(),_3t(),ete={"image/png":"png","image/jpeg":"jpeg","image/jpg":"jpeg","image/gif":"gif","image/webp":"webp"},E3t=class XEr extends Ma{bedrockClient;conversationHistory=[];region;static extractRegionFromArn(t){return t?t.match(/^arn:aws[a-z0-9-]*:bedrock:([^:]+):/)?.[1]??null:null}constructor(t,r,n,o){super(t,"bedrock",r);const i=t||process.env.BEDROCK_MODEL||this.modelName,s=XEr.extractRegionFromArn(i);this.region=o?.region||n||s||process.env.AWS_REGION||"us-east-1",h.debug("[AmazonBedrockProvider] Starting constructor with extensive logging for debugging"),h.debug(`[AmazonBedrockProvider] Environment check: AWS_REGION=${process.env.AWS_REGION||"undefined"}, AWS_ACCESS_KEY_ID=${process.env.AWS_ACCESS_KEY_ID?"SET":"undefined"}, AWS_SECRET_ACCESS_KEY=${process.env.AWS_SECRET_ACCESS_KEY?"SET":"undefined"}`);try{h.debug("[AmazonBedrockProvider] Creating BedrockRuntimeClient with clean configuration"),this.bedrockClient=new iLt({region:this.region,...o?.accessKeyId&&o?.secretAccessKey?{credentials:{accessKeyId:o.accessKeyId,secretAccessKey:o.secretAccessKey,...o.sessionToken?{sessionToken:o.sessionToken}:{}}}:{}}),h.debug(`[AmazonBedrockProvider] Successfully created BedrockRuntimeClient with model: ${this.modelName}, region: ${this.region}`)}catch(a){throw h.error("[AmazonBedrockProvider] CRITICAL: Failed to initialize BedrockRuntimeClient:",a),a}}async performInitialHealthCheck(){const{BedrockClient:t,ListFoundationModelsCommand:r}=await Qee(),n=new t({region:this.region});try{h.debug("[AmazonBedrockProvider] Starting initial health check to validate credentials and connectivity");const o=new r({}),i=Date.now();await n.send(o);const s=Date.now()-i;h.debug(`[AmazonBedrockProvider] Health check PASSED - credentials valid, connectivity good, responseTime: ${s}ms`)}catch(o){const i=o instanceof Error?o.message:String(o);h.error("[AmazonBedrockProvider] Health check FAILED - this will cause production failures:",{error:i,errorType:o instanceof Error?o.constructor.name:"Unknown",region:process.env.AWS_REGION||"us-east-1",hasAccessKey:!!process.env.AWS_ACCESS_KEY_ID,hasSecretKey:!!process.env.AWS_SECRET_ACCESS_KEY})}finally{try{n.destroy()}catch{}}}getAISDKModel(){throw new Error("AmazonBedrockProvider does not use AI SDK models")}getProviderName(){return"bedrock"}getDefaultModel(){return process.env.BEDROCK_MODEL||"anthropic.claude-sonnet-4-6"}getDefaultEmbeddingModel(){return process.env.BEDROCK_EMBEDDING_MODEL||process.env.AWS_EMBEDDING_MODEL||"amazon.titan-embed-text-v2:0"}async generate(t){h.debug("[AmazonBedrockProvider] generate() called with conversation management");const r=Date.now(),n=typeof t=="string"?{prompt:t}:t;this.conversationHistory=[];const o=n.input;if(!!(o?.images?.length||o?.content?.length||o?.files?.length||o?.csvFiles?.length||o?.pdfFiles?.length)){h.debug("[AmazonBedrockProvider] Detected multimodal input in generate(), using multimodal message builder",{hasImages:!!o?.images?.length,imageCount:o?.images?.length||0,hasContent:!!o?.content?.length,contentCount:o?.content?.length||0,hasFiles:!!o?.files?.length,fileCount:o?.files?.length||0,hasCSVFiles:!!o?.csvFiles?.length,csvFileCount:o?.csvFiles?.length||0,hasPDFFiles:!!o?.pdfFiles?.length,pdfFileCount:o?.pdfFiles?.length||0});const f=_Lt(n,this.providerName,this.modelName),g=await A2(f,this.providerName,this.modelName);this.conversationHistory=this.convertToBedrockMessages(g)}else{h.debug("[AmazonBedrockProvider] Text-only input in generate(), using simple message builder");const m={role:"user",content:[{text:n.prompt||o?.text||""}]};this.conversationHistory.push(m)}h.debug(`[AmazonBedrockProvider] Starting conversation with ${this.conversationHistory.length} message(s)`);let s,a,l,c,u;try{({text:s,usage:a,finishReason:l,rawFinishReason:c,toolExecutions:u}=await this.conversationLoop(n))}catch(m){const f=this.neurolink?.getEventEmitter();throw f&&(f.emit("generation:end",{provider:this.providerName,responseTime:Date.now()-r,timestamp:Date.now(),result:{content:"",usage:{input:0,output:0,total:0},model:this.modelName||this.getDefaultModel(),provider:this.providerName,finishReason:"error"},success:!1,error:m instanceof Error?m.message:String(m)}),m&&typeof m=="object"&&(m._generationEndEmitted=!0)),m}const d=this.neurolink?.getEventEmitter();d&&d.emit("generation:end",{provider:this.providerName,responseTime:Date.now()-r,timestamp:Date.now(),result:{content:s,usage:a,model:this.modelName||this.getDefaultModel(),provider:this.providerName,finishReason:l},success:!0});const p={content:s,usage:a,model:this.modelName||this.getDefaultModel(),provider:this.getProviderName(),...l!==void 0&&{finishReason:l},...c!==void 0&&{rawFinishReason:c},toolsUsed:u.filter(m=>m.error===void 0).map(m=>m.name),toolCalls:u.map(m=>({toolCallId:m.id,toolName:m.name,args:m.input})),toolExecutions:Df(n,Bd(u)),enhancedWithTools:u.some(m=>m.error===void 0)};return p._generationEndEmitted=!0,p}async conversationLoop(t){const r=t.maxSteps||ts,n=await this.resolveTurnTools(t.tools,t.disableTools),o=this.formatToolsForBedrock(n),i=Ac(this.providerName,this.modelName||this.getDefaultModel(),{temperature:t.temperature??.7},"bedrock.converse"),s=t.systemPrompt||"You are a helpful assistant with access to external tools. Use tools when necessary to provide accurate information.",a=(l,c,u,d,p)=>{const m=gLt({client:this.bedrockClient,streaming:!1,region:this.region,maxSteps:r,buildCommandInput:g=>({modelId:this.modelName||this.getDefaultModel(),messages:this.convertToAWSMessages(g),...c?{system:[{text:c}]}:{},inferenceConfig:{maxTokens:u,...d!==void 0&&{temperature:d}},...o?{toolConfig:o}:{}})}),{resultPromise:f}=tp(m,l,{tools:this.toEngineTools(n),abortSignal:p,...t.toolTimeoutMs!==void 0?{toolTimeoutMs:t.toolTimeoutMs}:{}});return f};try{const l=this.conversationHistory;let c,u,d,p,m,f;if(vLt(l)){const b=o?.tools?.map(C=>C.toolSpec).filter(C=>!!C).map(C=>({type:"function",name:C.name??"",description:C.description,inputSchema:yLt(C.inputSchema)}));let S;const k={specificationVersion:"v3",provider:this.providerName,modelId:this.modelName||this.getDefaultModel(),supportedUrls:{},doGenerate:async C=>{C.tools!==void 0&&C.tools!==b&&h.warn("[AmazonBedrockProvider] middleware rewrote 'tools' on the generate path; the rewrite was ignored and the caller's original tool configuration was sent"),this.warnOnUnsentMiddlewareOptions("generate",C);const{system:R,conversation:O}=TLt(C.prompt),U=a(O,R,C.maxOutputTokens??t.maxTokens,C.temperature??i.temperature,Cy(t.abortSignal,C.abortSignal));S=U;const M=await U;return{content:M.text?[{type:"text",text:M.text}]:[],finishReason:{unified:M.finishReason,raw:M.rawStopReason},usage:{inputTokens:{total:M.usage.inputTokens+(M.usage.cacheReadTokens??0)+(M.usage.cacheWriteTokens??0),noCache:M.usage.inputTokens,cacheRead:M.usage.cacheReadTokens,cacheWrite:M.usage.cacheWriteTokens},outputTokens:{total:M.usage.outputTokens}}}},doStream:()=>{throw new Error("AmazonBedrockProvider's generate model does not implement doStream")}},A=await this.applyMiddlewareToModel(k,t);if(typeof A=="string")throw new Error("AmazonBedrockProvider: middleware returned a model id string, not a native model handle");const x=await A.doGenerate({prompt:wLt(s,l),maxOutputTokens:t.maxTokens,temperature:i.temperature,...b?{tools:b}:{},abortSignal:t.abortSignal}),P=await S?.catch(()=>{});c=x.content.filter(C=>C.type==="text").map(C=>C.text).join(""),u=P?.finishReason??x.finishReason.unified,d=P?.rawStopReason??x.finishReason.raw,p=P?.usage??{inputTokens:x.usage.inputTokens.noCache??x.usage.inputTokens.total??0,outputTokens:x.usage.outputTokens.total??0,...x.usage.inputTokens.cacheRead!==void 0&&{cacheReadTokens:x.usage.inputTokens.cacheRead},...x.usage.inputTokens.cacheWrite!==void 0&&{cacheWriteTokens:x.usage.inputTokens.cacheWrite}},m=P?.toolExecutions??[],f=P?.conversation??l}else{this.logMultimodalMiddlewareSkip(t);const b=await a(l,s,t.maxTokens,i.temperature,t.abortSignal);c=b.text||"",u=b.finishReason,d=b.rawStopReason,p=b.usage,m=b.toolExecutions,f=b.conversation}this.conversationHistory=f;const g=p.inputTokens,y=p.outputTokens,v=p.cacheReadTokens??0,T=p.cacheWriteTokens??0;return{text:c||"",usage:{input:g,output:y,total:g+v+T+y,...v>0&&{cacheReadTokens:v},...T>0&&{cacheCreationTokens:T}},finishReason:u,rawFinishReason:d,toolExecutions:m}}catch(l){throw h.error("[AmazonBedrockProvider] Error in conversation loop:",l),this.handleProviderError(l)}}convertToAWSMessages(t){return t.map(r=>({role:r.role,content:r.content.map(n=>n.text?{text:n.text}:n.image?{image:n.image}:n.document?{document:n.document}:n.toolUse?{toolUse:{toolUseId:n.toolUse.toolUseId,name:n.toolUse.name,input:n.toolUse.input}}:n.toolResult?{toolResult:{toolUseId:n.toolResult.toolUseId,content:n.toolResult.content,status:n.toolResult.status}}:{text:""})}))}async executeSingleTool(t,r,n,o){return uN.startActiveSpan("bedrock.tool.execute",{kind:nn.CLIENT,attributes:{"gen_ai.tool.name":r,"gen_ai.system":"aws.bedrock"}},async i=>{try{if(h.debug(`[AmazonBedrockProvider] Executing single tool: ${r}`,{args:n}),!t[r])throw new Error(`Tool not found: ${r}`);const s=t[r];if(!s||!s.execute)throw new Error(`Tool ${r} does not have execute method`);const a=n||{};r==="list_directory"&&!a.path&&(a.path=".",h.debug("[AmazonBedrockProvider] Added default path '.' for list_directory tool")),h.debug("[AmazonBedrockProvider] Tool input parameters:",a);const l={};for(const[d,p]of Object.entries(a))(p===null||typeof p=="string"||typeof p=="number"||typeof p=="boolean"||typeof p=="object"&&p!==null)&&(l[d]=p);const c=await s.execute(l);h.debug("[AmazonBedrockProvider] Tool execution result:",{toolName:r,result:c});let u;if(c&&typeof c=="object"&&"success"in c)if(c.success&&c.data!==void 0)typeof c.data=="string"?u=c.data:typeof c.data=="object"?u=JSON.stringify(c.data,null,2):u=String(c.data);else if(c.error){const d=typeof c.error=="string"?c.error:c.error.message||"Tool execution failed";throw new Error(d)}else u="";else typeof c=="string"?u=c:typeof c=="object"?u=JSON.stringify(c,null,2):u=String(c);return i.setStatus({code:Ue.OK}),u}catch(s){throw h.error("[AmazonBedrockProvider] Tool execution error:",{toolName:r,error:s}),i.setStatus({code:Ue.ERROR,message:s.message}),i.recordException(s),s}finally{i.end()}})}async resolveTurnTools(t,r){if(r)return{};const n=t??await this.getAllTools();return this.convertAISDKToolsToToolDefinitions(n)}toEngineTools(t){const r={};for(const n of Object.keys(t))r[n]={execute:o=>this.executeSingleTool(t,n,o)};return r}convertAISDKToolsToToolDefinitions(t){const r={};for(const[n,o]of Object.entries(t))if("description"in o&&o.description){const s=o.parameters??o.inputSchema;r[n]={description:o.description,parameters:s,execute:async a=>{if("execute"in o&&o.execute)return{success:!0,data:await o.execute(a,{toolCallId:`tool_${Date.now()}`,messages:[]})};throw new Error(`Tool ${n} has no execute method`)}}}return r}formatToolsForBedrock(t){if(!t||Object.keys(t).length===0)return null;const r=Object.entries(t).map(([n,o])=>{let i;return o.parameters&&typeof o.parameters=="object"?"_def"in o.parameters?i=qo(o.parameters):i=o.parameters:i={type:"object",properties:{},required:[]},(!i.type||i.type!=="object")&&(i={type:"object",properties:i.properties||{},required:i.required||[]}),{toolSpec:{name:n,description:o.description,inputSchema:{json:i}}}});return h.debug(`[AmazonBedrockProvider] Formatted ${r.length} tools for Bedrock`),{tools:r}}convertToBedrockMessages(t){return t.map(r=>{const n={role:r.role==="system"?"user":r.role,content:[]};return typeof r.content=="string"?n.content.push({text:r.content}):r.content.forEach(o=>{if(o.type==="text"&&o.text)n.content.push({text:o.text});else if(o.type==="image"&&o.image){const i=typeof o.image=="string"?Buffer.from(o.image.replace(/^data:image\/\w+;base64,/,""),"base64"):o.image;let s=o.mimeType?.split("/")[1]||"png";s==="jpg"&&(s="jpeg"),n.content.push({image:{format:s==="jpeg"?Kx.JPEG:s==="png"?Kx.PNG:s==="gif"?Kx.GIF:Kx.WEBP,source:{bytes:i}}})}else if(o.type==="document"||o.type==="pdf"||o.type==="file"&&o.mimeType?.toLowerCase().startsWith("application/pdf")){let i;if(typeof o.data=="string"){const a=o.data.replace(/^data:application\/pdf;base64,/i,"");i=Buffer.from(a,"base64")}else i=o.data;let s=typeof o.name=="string"&&o.name?om.basename(o.name):"document-pdf";s=s.replace(/\.[^.]+$/,""),s=s.replace(/[^a-zA-Z0-9\s\-()[\]]/g,"-"),s=s.replace(/-+/g,"-").trim().replace(/^-+|-+$/g,""),s=s||"document",n.content.push({document:{format:"pdf",name:s,source:{bytes:i}}})}}),n})}getBedrockClient(){return this.bedrockClient}async executeStream(t){return h.debug("[TRACE] executeStream ENTRY - starting streaming attempt"),h.info("[AmazonBedrockProvider] Attempting real streaming with ConverseStreamCommand"),uN.startActiveSpan("bedrock.stream",{kind:nn.CLIENT,attributes:{"gen_ai.system":"aws.bedrock","gen_ai.request.model":this.modelName||this.getDefaultModel(),"gen_ai.operation.name":"stream"}},async r=>{try{if(h.debug("[TRACE] executeStream TRY block - about to call streamingConversationLoop"),this.conversationHistory=[],!!(t.input?.images?.length||t.input?.content?.length||t.input?.files?.length||t.input?.csvFiles?.length||t.input?.pdfFiles?.length)){h.debug("[AmazonBedrockProvider] Detected multimodal input, using multimodal message builder",{hasImages:!!t.input?.images?.length,imageCount:t.input?.images?.length||0,hasContent:!!t.input?.content?.length,contentCount:t.input?.content?.length||0,hasFiles:!!t.input?.files?.length,fileCount:t.input?.files?.length||0,hasCSVFiles:!!t.input?.csvFiles?.length,csvFileCount:t.input?.csvFiles?.length||0,hasPDFFiles:!!t.input?.pdfFiles?.length,pdfFileCount:t.input?.pdfFiles?.length||0});const i=_Lt(t,this.providerName,this.modelName),s=await A2(i,this.providerName,this.modelName);this.conversationHistory=this.convertToBedrockMessages(s)}else{h.debug("[AmazonBedrockProvider] Text-only input, using simple message builder");const i={role:"user",content:[{text:t.input.text}]};this.conversationHistory.push(i)}h.debug(`[AmazonBedrockProvider] Starting streaming conversation with ${this.conversationHistory.length} message(s)`),h.debug("[TRACE] executeStream - calling streamingConversationLoop NOW");const o=await this.streamingConversationLoop(t,r);return h.debug("[TRACE] executeStream - streamingConversationLoop SUCCESS, returning result"),r.setStatus({code:Ue.OK}),r.end(),o}catch(n){h.debug("[TRACE] executeStream CATCH - error caught from streamingConversationLoop");const o=n,s=typeof o=="object"&&o!==null&&"$metadata"in o&&(o?.name==="AccessDeniedException"||o?.name==="UnauthorizedOperation"||o?.message?.includes("bedrock:InvokeModelWithResponseStream")||o?.message?.includes("streaming")||o?.message?.includes("ConverseStream"));if(h.debug("[TRACE] executeStream CATCH - checking if permission error"),h.debug(`[TRACE] executeStream CATCH - isPermissionError=${s}`),s){h.debug("[TRACE] executeStream CATCH - PERMISSION ERROR DETECTED, starting fallback"),h.warn(`[AmazonBedrockProvider] Streaming permissions not available, falling back to generate method: ${o.message}`),r.addEvent("stream.fallback_to_generate",{reason:o.message});const a=await this.generate({prompt:t.input.text,input:t.input,maxTokens:t.maxTokens,temperature:t.temperature,systemPrompt:t.systemPrompt});if(!a)throw r.setStatus({code:Ue.ERROR,message:"Generate method returned null result"}),r.end(),new Error("Generate method returned null result");r.setAttribute("gen_ai.response.stop_reason","fallback_end_turn"),r.setStatus({code:Ue.OK}),r.end();const l=new ReadableStream({start(u){const p=(a.content||"").split(/(\s+)/);let m="";for(let f=0;f<p.length;f++)m+=p[f],(f===p.length-1||m.length>50||/[.!?;,]\s*$/.test(m))&&m.length>0&&(u.enqueue({content:m}),m="");m.length>0&&u.enqueue({content:m}),u.close()}});return{stream:{async*[Symbol.asyncIterator](){const u=l.getReader();try{for(;;){const{done:d,value:p}=await u.read();if(d)break;yield p}}finally{u.releaseLock()}}},usage:a.usage,model:this.modelName||this.getDefaultModel(),provider:this.getProviderName(),metadata:{fallback:!0}}}throw r.setStatus({code:Ue.ERROR,message:o instanceof Error?o.message:String(o)}),r.recordException(o instanceof Error?o:new Error(String(o))),r.end(),n}})}logMultimodalMiddlewareSkip(t){if(t.middleware??this.middlewareOptions){h.warn("[AmazonBedrockProvider] multimodal turn \u2014 configured middleware was NOT applied (text-only turns only)");return}h.debug("[AmazonBedrockProvider] multimodal turn \u2014 skipping model middleware wrapping (text-only turns only)")}warnOnUnsentMiddlewareOptions(t,r){const n=mJr(r);n.length>0&&h.warn(`[AmazonBedrockProvider] middleware set options the native Bedrock path does not send on the ${t} path; ignored: ${n.map(o=>`'${o}'`).join(", ")}`)}async buildBedrockStreamTurn(t){const{initialConversation:r,systemPromptText:n,options:o,sampling:i,toolConfig:s,turnAbort:a,runTurn:l,raceFirstStep:c}=t;if(!vLt(r)){this.logMultimodalMiddlewareSkip(o);const g=l(r,n,o.maxTokens,i.temperature,a.signal);return await c(g.resultPromise),{stream:g.stream,capturedLoopResult:g.resultPromise}}const u=s?.tools?.map(g=>g.toolSpec).filter(g=>!!g).map(g=>({type:"function",name:g.name??"",description:g.description,inputSchema:yLt(g.inputSchema)}));let d;const p={specificationVersion:"v3",provider:this.providerName,modelId:this.modelName||this.getDefaultModel(),supportedUrls:{},doGenerate:()=>{throw new Error("AmazonBedrockProvider's stream model does not implement doGenerate")},doStream:async g=>{g.tools!==void 0&&g.tools!==u&&h.warn("[AmazonBedrockProvider] middleware rewrote 'tools' on the stream path; the rewrite was ignored and the caller's original tool configuration was sent"),this.warnOnUnsentMiddlewareOptions("stream",g);const{system:y,conversation:v}=TLt(g.prompt),T=l(v,y,g.maxOutputTokens??o.maxTokens,g.temperature??i.temperature,Cy(a.signal,g.abortSignal));d=T.resultPromise,await c(T.resultPromise);const b=T.resultPromise.then(S=>({type:"finish",finishReason:{unified:S.finishReason,raw:S.rawStopReason},usage:{inputTokens:{total:S.usage.inputTokens+(S.usage.cacheReadTokens??0)+(S.usage.cacheWriteTokens??0),noCache:S.usage.inputTokens,cacheRead:S.usage.cacheReadTokens,cacheWrite:S.usage.cacheWriteTokens},outputTokens:{total:S.usage.outputTokens}}}));return b.catch(()=>{}),{stream:fJr(T.stream,b,()=>a.abort())}}},m=await this.applyMiddlewareToModel(p,o);if(typeof m=="string")throw new Error("AmazonBedrockProvider: middleware returned a model id string, not a native model handle");const f=await m.doStream({prompt:wLt(n,r),maxOutputTokens:o.maxTokens,temperature:i.temperature,...u?{tools:u}:{},abortSignal:a.signal});return{stream:gJr(f.stream),capturedLoopResult:d}}summarizeBedrockStreamUsage(t){const r=t?.inputTokens??0,n=t?.outputTokens??0,o=t?.cacheReadTokens??0,i=t?.cacheWriteTokens??0;return{input:r,output:n,total:r+o+i+n,...o>0&&{cacheReadTokens:o},...i>0&&{cacheCreationTokens:i}}}async streamingConversationLoop(t,r){const n=Date.now(),o=t.maxSteps||ts,i=await this.resolveTurnTools(t.tools,t.disableTools),s=this.formatToolsForBedrock(i),a=Ac(this.providerName,this.modelName||this.getDefaultModel(),{temperature:t.temperature??.7},"bedrock.converseStream"),l=t.systemPrompt||"You are a helpful assistant with access to external tools. Use tools when necessary to provide accurate information.";let c=!1,u;const d=new Promise(C=>{u=()=>{c=!0,C()}}),p=async C=>{const R=C.then(O=>({result:O,error:void 0}),O=>({result:void 0,error:O}));if(await Promise.race([d,R]),!c){const O=await R;if(O.error)throw O.error}},m=(C,R,O,U,M)=>{const D=gLt({client:this.bedrockClient,streaming:!0,region:this.region,maxSteps:o,buildCommandInput:B=>({modelId:this.modelName||this.getDefaultModel(),messages:this.convertToAWSMessages(B),...R?{system:[{text:R}]}:{},inferenceConfig:{maxTokens:O,...U!==void 0&&{temperature:U}},...s?{toolConfig:s}:{}})}),$={...D,executeStep:async(B,q,L)=>{const j=await D.executeStep(B,q,L);return u(),j}};return r.addEvent("stream.api_call",{"bedrock.tool_count":s?.tools?.length??0}),tp($,C,{tools:this.toEngineTools(i),abortSignal:M,...t.toolTimeoutMs!==void 0?{toolTimeoutMs:t.toolTimeoutMs}:{}})},f=this.conversationHistory,g=new AbortController;t.abortSignal&&(t.abortSignal.aborted?g.abort():t.abortSignal.addEventListener("abort",()=>g.abort(),{once:!0}));const{stream:y,capturedLoopResult:v}=await this.buildBedrockStreamTurn({initialConversation:f,systemPromptText:l,options:t,sampling:a,toolConfig:s,turnAbort:g,runTurn:m,raceFirstStep:p}).catch(C=>{throw g.abort(),C}),T=(v??Promise.resolve(void 0)).then(C=>({result:C,error:void 0}),C=>({result:void 0,error:C})),b=this.neurolink?.getEventEmitter(),S=this,k={startTime:n,streamId:`bedrock-${Date.now()}`};let A;const x=new Promise(C=>{A=C});return T.then(C=>{A(cv(this.providerName,this.modelName||this.getDefaultModel(),{usage:this.summarizeBedrockStreamUsage(C.result?.usage),toolExecutions:C.result?.toolExecutions??[],toolsUsed:(C.result?.toolExecutions??[]).filter(R=>R.error===void 0).map(R=>R.name)},Date.now()-n,{requestId:`bedrock-stream-${Date.now()}`,streamingMode:!0}))}),{stream:{async*[Symbol.asyncIterator](){let C=!1;try{yield*y}catch(R){throw C=!0,R}finally{const R=await T;R.error&&(C=!0);const O=S.summarizeBedrockStreamUsage(R.result?.usage);if(R.result&&(S.conversationHistory=R.result.conversation,k.finishReason=R.result.finishReason,k.rawFinishReason=R.result.rawStopReason,r.setAttribute("gen_ai.response.stop_reason",R.result.rawStopReason??"unknown")),b){const U=t._streamDedupContext;U&&(U.providerEmitted=!0),b.emit("generation:end",{provider:S.providerName,responseTime:Date.now()-n,timestamp:Date.now(),result:{content:"",usage:O,model:S.modelName||S.getDefaultModel(),provider:S.providerName,finishReason:C?"error":R.result?.rawStopReason},success:!C})}}}},model:this.modelName||this.getDefaultModel(),provider:this.getProviderName(),analytics:x,metadata:k}}async checkBedrockHealth(){const t=new AbortController,r=setTimeout(()=>t.abort(),1e4),{BedrockClient:n,ListFoundationModelsCommand:o}=await Qee(),i=new n({region:process.env.AWS_REGION||"us-east-1"});try{h.debug("[AmazonBedrockProvider] Starting health check...");const s=new o({}),l=(await i.send(s,{abortSignal:t.signal})).modelSummaries||[],c=l.filter(u=>u.modelLifecycle?.status==="ACTIVE");if(h.debug(`[AmazonBedrockProvider] Health check passed - Found ${c.length} active models out of ${l.length} total models`),c.length===0)throw new Error("No active foundation models available in the region")}catch(s){clearTimeout(r);const a=s;if(pr(s))throw new Error("Bedrock health check timed out after 10 seconds",{cause:s});const l=typeof a.message=="string"?a.message:"";throw l.includes("UnauthorizedOperation")||l.includes("AccessDenied")?new Error("Bedrock access denied. Check your AWS credentials and IAM permissions for bedrock:ListFoundationModels",{cause:s}):a.code==="ECONNREFUSED"||a.code==="ENOTFOUND"?new Error("Unable to connect to Bedrock service. Check your network connectivity and AWS region configuration",{cause:s}):(h.error("[AmazonBedrockProvider] Health check failed:",s),new Error(`Bedrock health check failed: ${l||"Unknown error"}`,{cause:s}))}finally{clearTimeout(r);try{i.destroy()}catch{}}}formatProviderError(t){return ba(t,[{match:n=>/AccessDeniedException/i.test(n.message),errorClass:Wr,message:"AWS Bedrock access denied. Check your credentials and permissions."},{match:n=>n.errorName==="ThrottlingException"||n.errorCode==="ThrottlingException",errorClass:Qi,message:n=>`Bedrock rate limit (throttled): ${n.message}`},{match:n=>/ValidationException/i.test(n.message),errorClass:ot,message:n=>`Validation error: ${n.message}`},{match:()=>!0,errorClass:ot,message:n=>`AWS Bedrock error: ${n.message}`}],this.providerName,this.modelName)}async embed(t,r){const n=typeof t=="string"?{text:t}:t,o=r||this.getDefaultEmbeddingModel(),i=o.includes("nova")&&o.includes("multimodal"),s=o.includes("image")||o.includes("multimodal")||o==="amazon.titan-embed-image-v1"||i;h.debug("Generating embedding",{provider:this.providerName,model:o,hasText:typeof n.text=="string",hasImage:n.image!==void 0,isMultiModalModel:s});try{let a;if(n.image&&!s)throw new ot(`${this.providerName} model ${o} does not support image embeddings`,this.providerName);if(i){if(n.image&&n.text)throw new ot(`${this.providerName} model ${o} does not support combined image+text embeddings; provide exactly one of image or text`,this.providerName);const p={embeddingPurpose:"GENERIC_RETRIEVAL"};if(n.image){const m=Buffer.isBuffer(n.image)?n.image:Buffer.from(n.image,"base64"),f=TJr(n.mimeType);if(f===void 0)throw new ot(`${this.providerName} model ${o} does not support image format '${n.mimeType??"unknown"}'; supported formats are ${Object.keys(ete).join(", ")}`,this.providerName);p.image={detailLevel:"STANDARD_IMAGE",format:f,source:{bytes:bo.safeBase64Convert(m,"bedrock nova embed image")}}}n.text&&(p.text={value:n.text,truncationMode:"NONE"}),a=JSON.stringify({taskType:"SINGLE_EMBEDDING",singleEmbeddingParams:p})}else if(n.image){const p=Buffer.isBuffer(n.image)?n.image:Buffer.from(n.image,"base64");a=JSON.stringify({inputText:n.text??"",inputImage:bo.safeBase64Convert(p,"bedrock titan embed image")})}else a=JSON.stringify({inputText:n.text??""});const l=new lLt({modelId:o,contentType:"application/json",accept:"application/json",body:a}),c=await ze(this.bedrockClient.send(l),6e4,new Error("Bedrock embedding API call timed out")),u=JSON.parse(new TextDecoder().decode(c.body)),d=i?u.embeddings?.at(0)?.embedding:u.embedding;if(!Array.isArray(d))throw new Error("Invalid embedding response from Bedrock");return h.debug("Embedding generated successfully",{provider:this.providerName,model:o,embeddingDimension:d.length}),d}catch(a){throw h.error("Embedding generation failed",{error:a instanceof Error?a.message:String(a),model:o}),this.handleProviderError(a)}}async embedMany(t,r){const n=r||this.getDefaultEmbeddingModel();h.debug("Generating batch embeddings",{provider:this.providerName,model:n,count:t.length});try{const o=await Promise.all(t.map(i=>this.embed(i,n)));return h.debug("Batch embeddings generated successfully",{provider:this.providerName,model:n,count:o.length,embeddingDimension:o[0]?.length}),o}catch(o){throw h.error("Batch embedding generation failed",{error:o instanceof Error?o.message:String(o),model:n,count:t.length}),this.handleProviderError(o)}}}}}),S3t={};Z(S3t,{AmazonBedrockProvider:()=>E3t,bedrockTracer:()=>uN,loadBedrockControl:()=>Qee});var _Jr=E({"src/lib/providers/amazonBedrock/index.ts"(){"use strict";bJr(),ELt(),_3t()}}),k3t={};Z(k3t,{AzureOpenAIProvider:()=>x3t});var x3t,EJr=E({"src/lib/providers/azureOpenai.ts"(){"use strict";pt(),z(),Zs(),Go(),zl(),zc(),Um(),x3t=class extends Kl{azureDeployment;azureApiVersion;azureResourceOrigin;azureDeploymentPathPrefix;useMaxCompletionTokensOverride;constructor(e,t,r,n){const o=n?.apiKey||process.env.AZURE_OPENAI_API_KEY||"",i=process.env.AZURE_OPENAI_ENDPOINT||"";let s;if(i)try{s=new URL(i.includes("://")?i:`https://${i}`)}catch{s=void 0}const a=s?.hostname??"",l=s?.pathname&&s.pathname!=="/"?s.pathname.replace(/\/+$/,""):"",c=/\.(openai|cognitiveservices)\.azure\.com$/.test(a);let u;c?u="/openai":u=/\/openai(?:\/v\d+)?$/.test(l)?l:`${l}/openai`;const d=s?.origin??"",p=n?.deploymentName||e||process.env.AZURE_OPENAI_MODEL||process.env.AZURE_OPENAI_DEPLOYMENT||process.env.AZURE_OPENAI_DEPLOYMENT_ID||"gpt-4o",m=n?.apiVersion||process.env.AZURE_API_VERSION||"2025-04-01-preview",f=process.env.AZURE_OPENAI_USE_MAX_COMPLETION_TOKENS,g=n?.useMaxCompletionTokens??(f===void 0?void 0:/^(1|true|yes)$/i.test(f));o||_a(z4r()),d||_a(G4r()),super("azure",e,t,{baseURL:d,apiKey:o}),this.azureDeployment=p,this.azureApiVersion=m,this.azureResourceOrigin=d,this.azureDeploymentPathPrefix=u,this.useMaxCompletionTokensOverride=g,h.shouldLog("debug")&&h.debug("Azure OpenAI Provider initialized",CXe({deployment:this.azureDeployment,resourceOrigin:this.azureResourceOrigin,deploymentPathPrefix:this.azureDeploymentPathPrefix,apiVersion:this.azureApiVersion,provider:"azure"}))}suppressResponseFormatWithTools(){return!1}getProviderName(){return"azure"}getDefaultModel(){return this.azureDeployment}formatProviderError(e){const t=[{match:r=>im(r.message,401),errorClass:Wr,message:"Invalid Azure OpenAI API key or endpoint."},...Ll];return ba(e,t,this.providerName,this.modelName)}getChatCompletionsURL(e){const t=e||this.azureDeployment,r=this.azureDeploymentPathPrefix.replace(/\/+$/,"");return`${this.azureResourceOrigin}${r}/deployments/${t}/chat/completions?api-version=${this.azureApiVersion}`}getAuthHeaders(){return{"api-key":this.config.apiKey}}adjustRequestBody(e,t){const r=this.useMaxCompletionTokensOverride??bRt(t);return e.max_tokens!==void 0&&r?{...e,max_completion_tokens:e.max_tokens,max_tokens:void 0}:e}}}});function Jx(e){return e.length>=8&&e[0]===137&&e[1]===80&&e[2]===78&&e[3]===71&&e[4]===13&&e[5]===10&&e[6]===26&&e[7]===10?"image/png":e.length>=3&&e[0]===255&&e[1]===216&&e[2]===255?"image/jpeg":e.length>=12&&e[0]===82&&e[1]===73&&e[2]===70&&e[3]===70&&e[8]===87&&e[9]===69&&e[10]===66&&e[11]===80?"image/webp":e.length>=6&&e[0]===71&&e[1]===73&&e[2]===70&&e[3]===56&&(e[4]===55||e[4]===57)&&e[5]===97?"image/gif":null}function Xx(e){return Jx(e)??"image/png"}var xw=E({"src/lib/utils/imageDetection.ts"(){"use strict"}});function A3t(e){return e.map(t=>typeof t.content=="string"?{role:t.role,content:t.content}:{role:t.role,content:t.content.map(r=>r.type==="image"||r.type==="document"?{type:r.type,media_type:r.source.media_type,base64_chars:r.source.data.length}:r)})}var SJr=E({"src/lib/utils/anthropicTraceSanitizer.ts"(){"use strict"}}),dN,kJr=E({"node_modules/.pnpm/@anthropic-ai+vertex-sdk@0.16.0_zod@4.3.6/node_modules/@anthropic-ai/vertex-sdk/internal/utils/env.mjs"(){dN=e=>{if(typeof globalThis.process<"u")return globalThis.process.env?.[e]?.trim()||void 0;if(typeof globalThis.Deno<"u")return globalThis.Deno.env?.get?.(e)?.trim()||void 0}}}),xJr=E({"node_modules/.pnpm/@anthropic-ai+vertex-sdk@0.16.0_zod@4.3.6/node_modules/@anthropic-ai/vertex-sdk/core/error.mjs"(){$o()}});function tte(e){return e!=null&&typeof e=="object"&&!Array.isArray(e)}var pN,rte,C3t=E({"node_modules/.pnpm/@anthropic-ai+vertex-sdk@0.16.0_zod@4.3.6/node_modules/@anthropic-ai/vertex-sdk/internal/utils/values.mjs"(){xJr(),pN=e=>(pN=Array.isArray,pN(e)),rte=pN}});function*AJr(e){if(!e)return;if(nte in e){const{values:n,nulls:o}=e;yield*n.entries();for(const i of o)yield[i,null];return}let t=!1,r;e instanceof Headers?r=e.entries():rte(e)?r=e:(t=!0,r=Object.entries(e??{}));for(let n of r){const o=n[0];if(typeof o!="string")throw new TypeError("expected header name to be a string");const i=rte(n[1])?n[1]:[n[1]];let s=!1;for(const a of i)a!==void 0&&(t&&!s&&(s=!0,yield[o,null]),yield[o,a])}}var nte,I3t,CJr=E({"node_modules/.pnpm/@anthropic-ai+vertex-sdk@0.16.0_zod@4.3.6/node_modules/@anthropic-ai/vertex-sdk/internal/headers.mjs"(){C3t(),nte=Symbol.for("brand.privateNullableHeaders"),I3t=e=>{const t=new Headers,r=new Set;for(const n of e){const o=new Set;for(const[i,s]of AJr(n)){const a=i.toLowerCase();o.has(a)||(t.delete(i),o.add(a)),s===null?(t.delete(i),r.add(a)):(t.append(i,s),r.delete(a))}}return{[nte]:!0,values:t,nulls:r}}}});function IJr(e){const t=new Bx(e);return delete t.batches,t}function RJr(e){const t=new sa(e);return delete t.messages.batches,t}var R3t,P3t,ote,M3t=E({"node_modules/.pnpm/@anthropic-ai+vertex-sdk@0.16.0_zod@4.3.6/node_modules/@anthropic-ai/vertex-sdk/client.mjs"(){QD(),S2t(),yk(),kJr(),C3t(),CJr(),QD(),R3t="vertex-2023-10-16",P3t=new Set(["/v1/messages","/v1/messages?beta=true"]),ote=class extends jo{constructor({baseURL:e=dN("ANTHROPIC_VERTEX_BASE_URL"),region:t=dN("CLOUD_ML_REGION")??null,projectId:r=dN("ANTHROPIC_VERTEX_PROJECT_ID")??null,...n}={}){if(!t)throw new Error("No region was given. The client should be instantiated with the `region` option or the `CLOUD_ML_REGION` environment variable should be set.");if(!e)switch(t){case"global":e="https://aiplatform.googleapis.com/v1";break;case"us":e="https://aiplatform.us.rep.googleapis.com/v1";break;case"eu":e="https://aiplatform.eu.rep.googleapis.com/v1";break;default:e=`https://${t}-aiplatform.googleapis.com/v1`}if(super({baseURL:e,...n}),this.messages=IJr(this),this.beta=RJr(this),this.region=t,this.projectId=r,this.accessToken=n.accessToken??null,n.authClient&&n.googleAuth)throw new Error("You cannot provide both `authClient` and `googleAuth`. Please provide only one of them.");n.authClient?this._authClientPromise=Promise.resolve(n.authClient):(this._auth=n.googleAuth??new WK({scopes:"https://www.googleapis.com/auth/cloud-platform"}),this._authClientPromise=this._auth.getClient())}validateHeaders(){}async prepareOptions(e){const t=await this._authClientPromise,r=await t.getRequestHeaders(),n=t.projectId??r["x-goog-user-project"];!this.projectId&&n&&(this.projectId=n),e.headers=I3t([r,e.headers])}async buildRequest(e){if(tte(e.body)&&(e.body={...e.body}),tte(e.body)&&(e.body.anthropic_version||(e.body.anthropic_version=R3t)),P3t.has(e.path)&&e.method==="post"){if(!this.projectId)throw new Error("No projectId was given and it could not be resolved from credentials. The client should be instantiated with the `projectId` option or the `ANTHROPIC_VERTEX_PROJECT_ID` environment variable should be set.");if(!tte(e.body))throw new Error("Expected request body to be an object for post /v1/messages");const t=e.body.model;e.body.model=void 0;const n=e.body.stream??!1?"streamRawPredict":"rawPredict";e.path=`/projects/${this.projectId}/locations/${this.region}/publishers/anthropic/models/${t}:${n}`}if(e.path==="/v1/messages/count_tokens"||e.path=="/v1/messages/count_tokens?beta=true"&&e.method==="post"){if(!this.projectId)throw new Error("No projectId was given and it could not be resolved from credentials. The client should be instantiated with the `projectId` option or the `ANTHROPIC_VERTEX_PROJECT_ID` environment variable should be set.");e.path=`/projects/${this.projectId}/locations/${this.region}/publishers/anthropic/models/count-tokens:rawPredict`}return super.buildRequest(e)}}}}),ite={};Z(ite,{AnthropicVertex:()=>ote,BaseAnthropic:()=>jo,default:()=>ote});var O3t=E({"node_modules/.pnpm/@anthropic-ai+vertex-sdk@0.16.0_zod@4.3.6/node_modules/@anthropic-ai/vertex-sdk/index.mjs"(){M3t(),M3t()}});async function PJr(){return mN||(mN=await Promise.resolve().then(()=>(O3t(),ite))),mN}function MJr(e){const t=[],r=new Map;let n=0;const o=i=>{const s=`${n}:${i??"x"}`;let a=r.get(s);return a||(a={type:"tool_step",callParts:[],resultParts:[]},r.set(s,a),t.push(a)),a};for(const i of e){if(i.role==="tool_call"){o(i.metadata?.stepIndex).callParts.push({name:i.tool||"unknown",input:i.args||{}});continue}if(i.role==="tool_result"){o(i.metadata?.stepIndex).resultParts.push(i.content&&i.content.length>0?i.content:"(no output)");continue}const s=i.role==="assistant"?"assistant":i.role==="user"?"user":null;!s||!i.content||i.content.trim().length===0||(n++,t.push({type:"regular",role:s,parts:[i.content]}))}return t}function ste(e,t,r){const n=e[e.length-1];n&&n.role===t&&Array.isArray(n.content)?n.content.push(...r):e.push({role:t,content:[...r]})}function OJr(e,t){const r=e.callParts,n=e.resultParts,o=Math.min(r.length,n.length);(o!==r.length||o!==n.length)&&h.debug("[GoogleVertex] Unbalanced tool step in Claude history replay",{calls:r.length,results:n.length,paired:o});const i=[],s=[];for(let a=0;a<o;a++){const l=`hist_${t}_${a}`;i.push({type:"tool_use",id:l,name:r[a].name,input:r[a].input}),s.push({type:"tool_result",tool_use_id:l,content:n[a]})}return{uses:i,results:s}}function DJr(e){const t=r=>Array.isArray(r.content)&&r.content.length>0&&r.content.every(n=>n.type==="tool_result");for(;e.length>0&&(e[0].role!=="user"||t(e[0]));)e.shift()}function ate(e){const t=[];let r=0;for(const n of MJr(e)){if(n.type==="regular"){ste(t,n.role==="assistant"?"assistant":"user",[{type:"text",text:String(n.parts[0]??"")}]);continue}const{uses:o,results:i}=OJr(n,r);o.length!==0&&(r++,ste(t,"assistant",o),ste(t,"user",i))}if(DJr(t),h.shouldLog("debug")){const n=t.flatMap(o=>Array.isArray(o.content)?o.content:[]);h.debug("[GoogleVertex] Replayed Claude history with tool turns",{historyMessages:t.length,toolUseBlocks:n.filter(o=>o.type==="tool_use").length,toolResultBlocks:n.filter(o=>o.type==="tool_result").length})}return t}function lte(e,t){const r=e[e.length-1];if(r&&r.role==="user"){const n=Array.isArray(r.content)?r.content:[{type:"text",text:r.content}],o=Array.isArray(t)?t:[{type:"text",text:t}];r.content=[...n,...o];return}e.push({role:"user",content:t})}function Ng(e){if(!e||typeof e!="object")return;const t=["additionalProperties","default","$schema","$id","$ref","definitions","$defs","examples","errorMessage"];for(const n of t)n in e&&delete e[n];typeof e.exclusiveMinimum=="boolean"&&(e.exclusiveMinimum===!0&&typeof e.minimum=="number"?(e.exclusiveMinimum=e.minimum,delete e.minimum):delete e.exclusiveMinimum),typeof e.exclusiveMaximum=="boolean"&&(e.exclusiveMaximum===!0&&typeof e.maximum=="number"?(e.exclusiveMaximum=e.maximum,delete e.maximum):delete e.exclusiveMaximum);const r=2147483647;if(typeof e.maximum=="number"&&e.maximum>r&&delete e.maximum,typeof e.minimum=="number"&&e.minimum<-r&&delete e.minimum,e.properties&&typeof e.properties=="object")for(const n of Object.values(e.properties))n&&typeof n=="object"&&Ng(n);if(e.items&&typeof e.items=="object")if(Array.isArray(e.items))for(const n of e.items)n&&typeof n=="object"&&Ng(n);else Ng(e.items);for(const n of["allOf","anyOf","oneOf"])if(Array.isArray(e[n]))for(const o of e[n])o&&typeof o=="object"&&Ng(o)}async function*NJr(e,t){const r=e.getReader();let n=!1;try{for(;;){const o=await r.read();if(o.done){n=!0;return}const i=o.value;if(i.type==="text-delta")yield{content:i.delta};else if(i.type==="reasoning-delta")yield{content:"",reasoning:i.delta};else if(i.type==="finish")t(i);else if(i.type==="error")throw i.error}}finally{try{n||await r.cancel()}finally{r.releaseLock()}}}function D3t(e,t,r){const n=wIt({contents:e,availableInputTokens:ql("vertex",t),provider:"vertex",observedPromptTokens:r});if(!n)return!1;const o=new Set(n.drop),i=new Set(n.truncate),s=[];for(let a=0;a<e.length;a++){if(o.has(a))continue;const l=e[a];if(i.has(a)&&Array.isArray(l.parts)){s.push({...l,parts:l.parts.map(c=>{if(!("functionResponse"in c))return c;const u=c.functionResponse,d=JSON.stringify(u.response)??"";return d.length<=G3t?c:{functionResponse:{name:u.name,response:{result:SY(d)}}}})});continue}s.push(l)}if(o.size>0){let a=s.findIndex(l=>Array.isArray(l.parts)&&l.parts.some(c=>!!c.functionCall||!!c.functionResponse));a<0&&(a=Math.min(1,s.length)),s.splice(a,0,{role:"user",parts:[{text:xY}]})}return e.length=0,e.push(...s),!0}function N3t(e,t,r){const n=UNt({conversation:e,availableInputTokens:ql("vertex",t),fixedOverheadTokens:0,provider:"vertex",observedPromptTokens:r,observedDescribesCurrentPayload:!0});if(!n)return!1;const o=new Set(n.drop),i=new Set(n.truncate),s=[];for(let a=0;a<e.length;a++){if(o.has(a))continue;const l=e[a];if(i.has(a)&&Array.isArray(l.content)){s.push({...l,content:l.content.map(c=>{if(c.type!=="tool_result")return c;const u=typeof c.content=="string"?c.content:JSON.stringify(c.content)??"";return{...c,content:$Nt(u)}})});continue}s.push(l)}if(o.size>0){let a=s.findIndex(l=>Array.isArray(l.content)&&l.content.some(c=>c.type==="tool_use"||c.type==="tool_result"));a<0&&(a=Math.min(1,s.length)),s.splice(a,0,{role:"user",content:[{type:"text",text:Lee}]})}return e.length=0,e.push(...s),!0}async function L3t(e,t,r={}){const n=[],o=[];let i,s=0,a=0,l=0,c=0;for await(const u of e){r.onProgress?.();const d=u,m=d.candidates?.[0],f=m?.finishReason;typeof f=="string"&&f&&(i=f);const g=m?.content;if(g&&Array.isArray(g.parts))for(const v of g.parts)n.push(v),typeof v.text=="string"&&v.text.length>0&&t.push({content:v.text});u.functionCalls&&o.push(...u.functionCalls);const y=d.usageMetadata;if(y){if(y.promptTokenCount!==void 0&&y.promptTokenCount>0){r.onUsageDelta?.("input",y.promptTokenCount-s),s=y.promptTokenCount,r.onUsage?.(y.promptTokenCount,y.candidatesTokenCount??0);const v=Math.min(y.cachedContentTokenCount??0,y.promptTokenCount);r.onUsageDelta?.("cacheRead",v-l),l=v}y.candidatesTokenCount!==void 0&&y.candidatesTokenCount>0&&(r.onUsageDelta?.("output",y.candidatesTokenCount-a),a=y.candidatesTokenCount),y.thoughtsTokenCount!==void 0&&y.thoughtsTokenCount>0&&(r.onUsageDelta?.("reasoning",y.thoughtsTokenCount-c),c=y.thoughtsTokenCount)}}return{rawResponseParts:n,stepFunctionCalls:o,...i?{finishReason:i}:{},inputTokens:s,outputTokens:a,...l?{cacheReadTokens:l}:{},...c?{reasoningTokens:c}:{}}}function F3t(e){return e.some(t=>t.type==="tool_use")?"":e.filter(t=>t.type==="text").map(t=>t.text).join("")}var mN,$3t,cte,Yx,ute,Aw,Lg,U3t,B3t,hN,z3t,G3t,dte,LJr=E({"src/lib/providers/googleVertex/client.ts"(){"use strict";Tn(),EO(),kr(),pl(),KW(),CO(),EK(),Zo(),If(),Mf(),EY(),Nt(),Ln(),pt(),Zs(),et(),iN(),lEt(),R2(),z(),pY(),pv(),JP(),bIt(),BNt(),fO(),xw(),yO(),Go(),ss(),Q1t(),dg(),Ys(),_It(),mIt(),RO(),YNt(),Mk(),Jv(),CY(),$c(),qS(),il(),Qt(),sl(),zl(),vm(),Ic(),SJr(),Mk(),mN=null,$3t=()=>!0,cte=()=>_a(X4r()),Yx=()=>process.env.GOOGLE_CLOUD_LOCATION||process.env.VERTEX_LOCATION||process.env.GOOGLE_VERTEX_LOCATION||"us-central1",ute=(e,t)=>{const r=t||Yx();if(!e)return r;const n=e.toLowerCase();return n.startsWith("gemini-")||n.includes("/gemini-")||D8.some(i=>n===i.toLowerCase()||n.includes(i.toLowerCase())||i.toLowerCase().includes(n))?process.env.GOOGLE_VERTEX_GLOBAL_LOCATION||"global":r},Aw=ute,Lg=()=>process.env.VERTEX_MODEL||"gemini-2.5-flash",U3t=()=>!!(process.env.GOOGLE_APPLICATION_CREDENTIALS_NEUROLINK||process.env.GOOGLE_APPLICATION_CREDENTIALS||process.env.GOOGLE_SERVICE_ACCOUNT_KEY||process.env.GOOGLE_AUTH_CLIENT_EMAIL&&process.env.GOOGLE_AUTH_PRIVATE_KEY),B3t=async(e,t,r,n)=>{const o=e||Yx();return{projectId:r?r.projectId?.trim()||"express":cte(),region:o,...t!==void 0&&{timeout:t},maxRetries:0,...n?{baseURL:n}:{},...r?{authClient:{getRequestHeaders:async()=>({Authorization:`Bearer ${r.apiKey}`}),projectId:null}}:{}}},hN=e=>e.toLowerCase().includes("claude"),z3t=(e,t)=>{const r=e[Symbol.asyncIterator]();return new ReadableStream({async pull(n){try{const o=await r.next();if(o.done){n.enqueue(t()),n.close();return}const i=o.value;"content"in i&&typeof i.content=="string"&&("reasoning"in i&&typeof i.reasoning=="string"&&i.reasoning.length>0&&n.enqueue({type:"reasoning-delta",delta:i.reasoning}),i.content.length>0&&n.enqueue({type:"text-delta",delta:i.content}))}catch(o){n.error(o)}},cancel(){NS(r)}})},G3t=2048,dte=class mn extends Ma{projectId;location;expressApiKey;baseURL;registeredTools=new Map;toolContext={};static modelConfigCache=new Map;static modelConfigCacheTime=0;static CACHE_DURATION=300*1e3;static MAX_CACHE_SIZE=50;static maxTokensCache=new Map;static maxTokensCacheTime=0;constructor(t,r,n,o,i){super(t,"vertex",n),i&&(i.projectId&&(process.env.GOOGLE_CLOUD_PROJECT=String(i.projectId)),i.location&&(process.env.GOOGLE_CLOUD_LOCATION=String(i.location)),i.apiKey&&(process.env.GOOGLE_API_KEY=String(i.apiKey),!i.projectId&&!i.location&&(this.expressApiKey=String(i.apiKey))),i.baseURL&&(this.baseURL=String(i.baseURL)));const s=!!this.resolveExpressApiKey();s||U3t()||_a(Y4r()),this.projectId=i?.projectId||(s?"":cte()),this.location=o||i?.location||Yx(),h.debug("[GoogleVertexProvider] Constructor initialized",{regionParam:o,resolvedLocation:this.location,projectId:this.projectId}),h.debug("Google Vertex AI BaseProvider v2 initialized",{modelName:this.modelName,projectId:this.projectId,location:this.location,provider:this.providerName})}getProviderName(){return"vertex"}getDefaultModel(){return Lg()}async getAISDKModel(){throw new De({code:He.INVALID_CONFIGURATION,message:"GoogleVertexProvider no longer uses @ai-sdk/google-vertex. All models use native SDKs: @google/genai for Gemini, @anthropic-ai/vertex-sdk for Claude.",category:"configuration",severity:"critical",retriable:!1,context:{provider:this.providerName,model:this.modelName}})}validateStreamOptionsOnly(t){this.validateStreamOptions(t)}async preprocessNativeFileInput(t){if(t.input&&RJ(t.input),t.input?.files?.length)try{await PJ(t,100*1024*1024,this.providerName)}catch(r){h.warn(`[GoogleVertex] processUnifiedFilesArray threw, continuing without file content: ${r instanceof Error?r.message:String(r)}`)}await Ck(t.input)}async executeStream(t,r){const n=t.model||this.modelName||Lg();return U9e({name:"neurolink.provider.stream",tracer:Be.provider,attributes:{[Re.GEN_AI_SYSTEM]:this.providerName,[Re.GEN_AI_MODEL]:n,[Re.GEN_AI_OPERATION]:"stream",[Re.NL_PROVIDER]:this.providerName}},async o=>{const i=Date.now(),s=t.tools||{};await this.preprocessNativeFileInput(t);const l={...await mt({name:"neurolink.message.build",tracer:Be.provider,attributes:{[Re.NL_PROVIDER]:this.providerName,"message.count":1,"message.build.count":1,"message.build.path":"vertex.native.stream"}},async()=>this.processCSVFilesForNativeSDK(t)),tools:s},c=l.input?.text||l.prompt||"";try{let u;hN(n)?(h.info("[GoogleVertex] Routing Claude model to native @anthropic-ai/vertex-sdk",{model:n,totalToolCount:Object.keys(s).length}),u=await this.runNativeStreamWithMiddleware(l,n,p=>this.executeNativeAnthropicStream(p))):(h.info("[GoogleVertex] Routing Gemini model to native @google/genai",{model:n,totalToolCount:Object.keys(s).length}),u=await this.runNativeStreamWithMiddleware(l,n,p=>this.executeNativeGemini3Stream(p))),this.attachUsageAndCostAttributes(o,n,u?.usage);const d=this.wrapStreamResultWithLifecycle(t,u,i);return this.emitStreamEnd(n,i,!0,void 0,u.finishReason),d}catch(u){throw this.fireGenerateOnError(t,u,i),this.emitStreamEnd(n,i,!1,u),this.emitGenerationEnd(n,null,i,!1,u,c),u}},o=>o.stream,(o,i)=>this.preserveStreamResultAccessors(o,{...o,stream:i}))}emitStreamEnd(t,r,n,o,i){const s=this.neurolink?.getEventEmitter();s&&s.emit("stream:end",{provider:this.providerName,responseTime:Date.now()-r,timestamp:Date.now(),result:{content:"",usage:{input:0,output:0,total:0},model:t,provider:this.providerName,finishReason:n?i??"stop":"error"},success:n,...o?{error:o instanceof Error?o.message:String(o)}:{}})}async createVertexGenAIClient(t){const r=this.resolveExpressApiKey(),n=r?"":this.projectId,o=t||this.location||Yx(),s=(await Promise.resolve().then(()=>(KE(),zy))).GoogleGenAI;if(!s)throw new De({code:He.INVALID_CONFIGURATION,message:"@google/genai does not export GoogleGenAI",category:"configuration",severity:"critical",retriable:!1,context:{module:"@google/genai",expectedExport:"GoogleGenAI"}});const a=s,l=this.resolveBaseURL(),c={...l?{baseUrl:l}:{},...PY()};return r?new a({vertexai:!0,apiKey:r,httpOptions:c}):new a({vertexai:!0,project:n,location:o,httpOptions:c})}resolveBaseURL(){const t=this.baseURL?.trim()||process.env.GOOGLE_VERTEX_BASE_URL?.trim();return t&&t.length>0?t:void 0}resolveExpressApiKey(){const t=this.expressApiKey?.trim();if(t)return t;const r=process.env.GOOGLE_VERTEX_API_KEY?.trim();return r?["GOOGLE_CLOUD_PROJECT_ID","VERTEX_PROJECT_ID","GOOGLE_VERTEX_PROJECT","GOOGLE_CLOUD_PROJECT"].some(o=>(process.env[o]??"").trim().length>0)?void 0:r:void 0}buildAnthropicToolDeclaration(t,r){const n={name:t,description:r.description||`Tool: ${t}`,input_schema:{type:"object"}},i=r.parameters||r.inputSchema;if(i){const s=qo(i),a=Kn(s);n.input_schema={type:"object",properties:a.properties||{},required:a.required||[]}}return n}refreshAnthropicToolDeclarations(t,r,n,o){if(!t||!r)return;const i=new Set(r.map(s=>s.name));for(const[s,a]of Object.entries(t))i.has(s)||(r.push(this.buildAnthropicToolDeclaration(s,a)),a.execute&&n.set(s,a.execute),o.delete(s),h.info(`[GoogleVertex] Tool "${s}" hydrated mid-turn via discovery \u2014 added to Anthropic declarations.`))}resolveAnthropicToolOnMiss(t,r,n,o,i){if(!n)return;const s=fQe(r,t);if(s?.execute)return n.some(a=>a.name===t)||n.push(this.buildAnthropicToolDeclaration(t,s)),o.set(t,s.execute),i.delete(t),h.info(`[GoogleVertex] Tool "${t}" resolved mid-turn via discovery \u2014 executing.`),o.get(t)}buildFinalResultTool(t){const r=qo(t),n=Kn(r);n.$schema&&delete n.$schema;const o=ea(n);return{name:"final_result",description:"Return the final structured result. You MUST call this tool when you have gathered all information and are ready to provide the final answer. The arguments should contain the structured data matching the expected schema.",input_schema:{type:"object",properties:o.properties||o,required:o.required||[]}}}async executeNativeGemini3Stream(t){const r=t.model||this.modelName||Lg(),n=Aw(r,t.region),o=await this.createVertexGenAIClient(n);h.debug("[GoogleVertex] Using native @google/genai for Gemini 3",{model:r,hasTools:!!t.tools&&Object.keys(t.tools).length>0,project:this.projectId,location:n});const i=[],s=[{text:t.input.text??""}],a=t.input;if(a?.pdfFiles&&a.pdfFiles.length>0){h.debug(`[GoogleVertex] Processing ${a.pdfFiles.length} PDF file(s) for native stream`);for(const _e of a.pdfFiles){let Fe;typeof _e=="string"?Qo.existsSync(_e)?Fe=Qo.readFileSync(_e):Fe=Buffer.from(_e,"base64"):Fe=_e;const Y=Fe.toString("base64");s.push({inlineData:{mimeType:"application/pdf",data:Y}})}}if(await vY(s,a?.nativeAudioFiles,"[GoogleVertex]"),a?.images&&a.images.length>0){h.debug(`[GoogleVertex] Processing ${a.images.length} image(s) for native stream`);for(const _e of a.images){const Fe=rk(_e);let Y,X="image/jpeg";if(typeof Fe=="string")if(Qo.existsSync(Fe)){Y=Qo.readFileSync(Fe);const W=lk(Fe);X=W.startsWith("image/")?W:this.detectImageType(Y)}else if(Fe.startsWith("data:")){const W=Fe.match(/^data:([^;]+);base64,(.+)$/);if(W)X=W[1],Y=Buffer.from(W[2],"base64");else continue}else if(Fe.startsWith("http://")||Fe.startsWith("https://"))try{const W=await fetch(Fe);if(!W.ok){h.warn(`[GoogleVertex] Image fetch failed: ${W.status} ${W.statusText}, skipping`,{url:Xt(Fe)});continue}const te=await W.arrayBuffer();Y=Buffer.from(te);const me=W.headers.get("content-type");me&&me.startsWith("image/")&&(X=me.split(";")[0])}catch(W){h.warn(`[GoogleVertex] Image URL fetch threw, skipping: ${W instanceof Error?W.message:String(W)}`,{url:Xt(Fe)});continue}else Y=Buffer.from(Fe,"base64"),X=this.detectImageType(Y);else Y=Fe,X=this.detectImageType(Y);const ke=Y.toString("base64");s.push({inlineData:{mimeType:X,data:ke}})}}await wY(s,a?.nativeVideoFiles,"vertex",r,"[GoogleVertex]"),xO(i,t.conversationMessages),i.push({role:"user",parts:s});let l;const c=new Wv;let u;if(t.tools&&Object.keys(t.tools).length>0&&!t.disableTools){const _e=Xv(t.tools,"functionDeclarations");u=_e,l=_e.toolsConfig;for(const[Fe,Y]of _e.executeMap)c.set(Fe,Y);h.debug("[GoogleVertex] Converted tools for native SDK",{toolCount:_e.toolsConfig[0].functionDeclarations.length,toolNames:_e.toolsConfig[0].functionDeclarations.map(Fe=>Fe.name)})}const d=t;let p=!1;if(d.schema&&l){p=!0;const _e=qo(d.schema,"openApi3"),Fe=Kn(_e);Fe.$schema&&delete Fe.$schema;const Y=ea(Fe),X=l[0]?.functionDeclarations||[];X.push({name:"final_result",description:"Return the final structured result. You MUST call this tool when you have gathered all information and are ready to provide the final answer. The arguments should contain the structured data matching the expected schema.",parametersJsonSchema:Y}),l=[{functionDeclarations:X}],h.debug("[GoogleVertex] Added final_result tool for structured output with tools (stream)",{schemaKeys:Object.keys(Y),totalTools:X.length})}const m=Ac(this.providerName,r,{temperature:t.temperature??1,...t.topP!==void 0&&{topP:t.topP}},"vertex.gemini"),f={...m.temperature!==void 0&&{temperature:m.temperature},maxOutputTokens:t.maxTokens};rY(r)&&(f.maxOutputTokens&&f.maxOutputTokens>Pa&&(h.warn(`[GoogleVertex] Capping maxOutputTokens from ${f.maxOutputTokens} to ${Pa} for ${r}`),f.maxOutputTokens=Pa),f.maxOutputTokens||(f.maxOutputTokens=Pa)),m.topP!==void 0&&(f.topP=m.topP),t.topK!==void 0&&(f.topK=t.topK),t.stopSequences&&t.stopSequences.length>0&&(f.stopSequences=t.stopSequences),l&&(f.tools=l);let g=t.systemPrompt||"";p&&(g=g+`
|
|
1113
|
+
`),conversation:r}}function fJr(e,t,r){const n=e[Symbol.asyncIterator]();return new ReadableStream({async pull(o){try{const i=await n.next();i.done?(o.enqueue(await t),o.close()):i.value.reasoning?o.enqueue({type:"reasoning-delta",delta:i.value.reasoning}):o.enqueue({type:"text-delta",delta:i.value.content})}catch(i){o.error(i)}},async cancel(){r(),await n.return?.()}})}async function*gJr(e){const t=e.getReader();let r=!1;try{for(;;){const n=await t.read();if(n.done){r=!0;return}const o=n.value;if(o.type==="text-delta")yield{content:o.delta};else if(o.type==="reasoning-delta")yield{content:"",reasoning:o.delta};else if(o.type==="error")throw o.error}}finally{try{r||await t.cancel()}finally{t.releaseLock()}}}var bLt,yJr=E({"src/lib/providers/amazonBedrock/modelBridge.ts"(){"use strict";z(),bLt=["topP","topK","presencePenalty","frequencyPenalty","stopSequences","seed","toolChoice","responseFormat"]}});function _Lt(e,t,r){return{input:{text:e.input?.text||"",images:e.input?.images,content:e.input?.content,files:e.input?.files,csvFiles:e.input?.csvFiles,pdfFiles:e.input?.pdfFiles,audioFiles:e.input?.audioFiles,videoFiles:e.input?.videoFiles},csvOptions:e.csvOptions,pdfOptions:e.pdfOptions,imageOptions:e.imageOptions,videoOptions:e.videoOptions,officeOptions:e.officeOptions,systemPrompt:e.systemPrompt,conversationHistory:e.conversationMessages,provider:t,model:r,temperature:e.temperature,maxTokens:e.maxTokens,enableAnalytics:e.enableAnalytics,enableEvaluation:e.enableEvaluation,context:e.context,fileRegistry:e.fileRegistry}}var vJr=E({"src/lib/utils/multimodalOptionsBuilder.ts"(){"use strict"}}),uN,ELt=E({"src/lib/providers/amazonBedrock/constants.ts"(){"use strict";il(),uN=Be.provider}}),SLt={};Z(SLt,{Agent:()=>m3t,BedrockClient:()=>xLt,BedrockRuntimeClient:()=>CLt,Blob:()=>p3t,Client:()=>f3t,ConverseCommand:()=>ILt,ConverseStreamCommand:()=>RLt,Cron:()=>KLt,Dispatcher:()=>g3t,File:()=>d3t,FlowProducer:()=>WLt,FormData:()=>u3t,GoogleAuth:()=>LLt,HTTPException:()=>t3t,Headers:()=>c3t,Hippocampus:()=>BLt,HippocampusConfig:()=>zLt,Hono:()=>QLt,ImageFormat:()=>PLt,InvokeEndpointCommand:()=>DLt,InvokeEndpointWithResponseStreamCommand:()=>NLt,InvokeModelCommand:()=>MLt,Job:()=>jLt,ListFoundationModelsCommand:()=>ALt,MockAgent:()=>w3t,Pool:()=>h3t,Queue:()=>qLt,QueueScheduler:()=>HLt,Request:()=>a3t,Response:()=>l3t,SageMakerRuntimeClient:()=>OLt,TextToSpeechClient:()=>$Lt,VertexAI:()=>FLt,Webhook:()=>ULt,Worker:()=>VLt,convertToHtml:()=>ZLt,cors:()=>e3t,createClient:()=>GLt,default:()=>kLt,extractRawText:()=>YLt,fetch:()=>s3t,getGlobalDispatcher:()=>v3t,interceptors:()=>T3t,logger:()=>r3t,parseBuffer:()=>JLt,request:()=>b3t,secureHeaders:()=>n3t,selectCover:()=>XLt,setGlobalDispatcher:()=>y3t,streamSSE:()=>o3t,timeout:()=>i3t});var Dg,xi,kLt,xLt,ALt,CLt,ILt,RLt,PLt,MLt,OLt,DLt,NLt,LLt,FLt,$Lt,ULt,BLt,zLt,GLt,qLt,VLt,jLt,HLt,WLt,KLt,JLt,XLt,YLt,ZLt,QLt,e3t,t3t,r3t,n3t,o3t,i3t,s3t,a3t,l3t,c3t,u3t,d3t,p3t,m3t,h3t,f3t,g3t,y3t,v3t,w3t,T3t,b3t,wJr=E({"npm-stub:@aws-sdk/client-bedrock"(){Dg={get(e,t){return t==="__esModule"?!0:t==="default"?new Proxy({},{get:Dg.get}):new Proxy(function(...r){return new Proxy({},{get:Dg.get})},{get:Dg.get,apply(r,n,o){return new Proxy({},{get:Dg.get})},construct(r,n){return new Proxy({},{get:Dg.get})}})}},xi=new Proxy({},Dg),kLt=xi,{BedrockClient:xLt,ListFoundationModelsCommand:ALt,BedrockRuntimeClient:CLt,ConverseCommand:ILt,ConverseStreamCommand:RLt,ImageFormat:PLt,InvokeModelCommand:MLt}=xi,{SageMakerRuntimeClient:OLt,InvokeEndpointCommand:DLt,InvokeEndpointWithResponseStreamCommand:NLt}=xi,{GoogleAuth:LLt,VertexAI:FLt,TextToSpeechClient:$Lt}=xi,{Webhook:ULt}=xi,{Hippocampus:BLt,HippocampusConfig:zLt}=xi,{createClient:GLt}=xi,{Queue:qLt,Worker:VLt,Job:jLt,QueueScheduler:HLt,FlowProducer:WLt}=xi,{Cron:KLt}=xi,{parseBuffer:JLt,selectCover:XLt}=xi,{extractRawText:YLt,convertToHtml:ZLt}=xi,{Hono:QLt}=xi,{cors:e3t,HTTPException:t3t,logger:r3t,secureHeaders:n3t,streamSSE:o3t,timeout:i3t}=xi,s3t=globalThis.fetch,a3t=globalThis.Request,l3t=globalThis.Response,c3t=globalThis.Headers,u3t=globalThis.FormData,d3t=globalThis.File,p3t=globalThis.Blob,m3t=xi.Agent,h3t=xi.Pool,f3t=xi.Client,g3t=xi.Dispatcher,y3t=()=>{},v3t=()=>xi,w3t=xi.MockAgent,T3t={redirect:()=>e=>e,retry:()=>e=>e},b3t=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()}}}}});async function Qee(){return await Promise.resolve().then(()=>(wJr(),SLt))}var _3t=E({"src/lib/providers/amazonBedrock/utils.ts"(){"use strict"}});function TJr(e){const t=(e??"").split(";").at(0)?.trim().toLowerCase();return ete[t??""]}var ete,E3t,bJr=E({"src/lib/providers/amazonBedrock/client.ts"(){"use strict";cLt(),kr(),OS(),pl(),Zo(),RO(),vm(),zl(),Ys(),pJr(),yJr(),pt(),Zs(),et(),jf(),z(),Ic(),R2(),vJr(),ss(),Qt(),ELt(),_3t(),ete={"image/png":"png","image/jpeg":"jpeg","image/jpg":"jpeg","image/gif":"gif","image/webp":"webp"},E3t=class XEr extends Ma{bedrockClient;conversationHistory=[];region;static extractRegionFromArn(t){return t?t.match(/^arn:aws[a-z0-9-]*:bedrock:([^:]+):/)?.[1]??null:null}constructor(t,r,n,o){super(t,"bedrock",r);const i=t||process.env.BEDROCK_MODEL||this.modelName,s=XEr.extractRegionFromArn(i);this.region=o?.region||n||s||process.env.AWS_REGION||"us-east-1",h.debug("[AmazonBedrockProvider] Starting constructor with extensive logging for debugging"),h.debug(`[AmazonBedrockProvider] Environment check: AWS_REGION=${process.env.AWS_REGION||"undefined"}, AWS_ACCESS_KEY_ID=${process.env.AWS_ACCESS_KEY_ID?"SET":"undefined"}, AWS_SECRET_ACCESS_KEY=${process.env.AWS_SECRET_ACCESS_KEY?"SET":"undefined"}`);try{h.debug("[AmazonBedrockProvider] Creating BedrockRuntimeClient with clean configuration"),this.bedrockClient=new iLt({region:this.region,...o?.accessKeyId&&o?.secretAccessKey?{credentials:{accessKeyId:o.accessKeyId,secretAccessKey:o.secretAccessKey,...o.sessionToken?{sessionToken:o.sessionToken}:{}}}:{}}),h.debug(`[AmazonBedrockProvider] Successfully created BedrockRuntimeClient with model: ${this.modelName}, region: ${this.region}`)}catch(a){throw h.error("[AmazonBedrockProvider] CRITICAL: Failed to initialize BedrockRuntimeClient:",a),a}}async performInitialHealthCheck(){const{BedrockClient:t,ListFoundationModelsCommand:r}=await Qee(),n=new t({region:this.region});try{h.debug("[AmazonBedrockProvider] Starting initial health check to validate credentials and connectivity");const o=new r({}),i=Date.now();await n.send(o);const s=Date.now()-i;h.debug(`[AmazonBedrockProvider] Health check PASSED - credentials valid, connectivity good, responseTime: ${s}ms`)}catch(o){const i=o instanceof Error?o.message:String(o);h.error("[AmazonBedrockProvider] Health check FAILED - this will cause production failures:",{error:i,errorType:o instanceof Error?o.constructor.name:"Unknown",region:process.env.AWS_REGION||"us-east-1",hasAccessKey:!!process.env.AWS_ACCESS_KEY_ID,hasSecretKey:!!process.env.AWS_SECRET_ACCESS_KEY})}finally{try{n.destroy()}catch{}}}getAISDKModel(){throw new Error("AmazonBedrockProvider does not use AI SDK models")}getProviderName(){return"bedrock"}getDefaultModel(){return process.env.BEDROCK_MODEL||"anthropic.claude-sonnet-4-6"}getDefaultEmbeddingModel(){return process.env.BEDROCK_EMBEDDING_MODEL||process.env.AWS_EMBEDDING_MODEL||"amazon.titan-embed-text-v2:0"}async generate(t){h.debug("[AmazonBedrockProvider] generate() called with conversation management");const r=Date.now(),n=typeof t=="string"?{prompt:t}:t;this.conversationHistory=[];const o=n.input;if(!!(o?.images?.length||o?.content?.length||o?.files?.length||o?.csvFiles?.length||o?.pdfFiles?.length)){h.debug("[AmazonBedrockProvider] Detected multimodal input in generate(), using multimodal message builder",{hasImages:!!o?.images?.length,imageCount:o?.images?.length||0,hasContent:!!o?.content?.length,contentCount:o?.content?.length||0,hasFiles:!!o?.files?.length,fileCount:o?.files?.length||0,hasCSVFiles:!!o?.csvFiles?.length,csvFileCount:o?.csvFiles?.length||0,hasPDFFiles:!!o?.pdfFiles?.length,pdfFileCount:o?.pdfFiles?.length||0});const f=_Lt(n,this.providerName,this.modelName),g=await A2(f,this.providerName,this.modelName);this.conversationHistory=this.convertToBedrockMessages(g)}else{h.debug("[AmazonBedrockProvider] Text-only input in generate(), using simple message builder");const m={role:"user",content:[{text:n.prompt||o?.text||""}]};this.conversationHistory.push(m)}h.debug(`[AmazonBedrockProvider] Starting conversation with ${this.conversationHistory.length} message(s)`);let s,a,l,c,u;try{({text:s,usage:a,finishReason:l,rawFinishReason:c,toolExecutions:u}=await this.conversationLoop(n))}catch(m){const f=this.neurolink?.getEventEmitter();throw f&&(f.emit("generation:end",{provider:this.providerName,responseTime:Date.now()-r,timestamp:Date.now(),result:{content:"",usage:{input:0,output:0,total:0},model:this.modelName||this.getDefaultModel(),provider:this.providerName,finishReason:"error"},success:!1,error:m instanceof Error?m.message:String(m)}),m&&typeof m=="object"&&(m._generationEndEmitted=!0)),m}const d=this.neurolink?.getEventEmitter();d&&d.emit("generation:end",{provider:this.providerName,responseTime:Date.now()-r,timestamp:Date.now(),result:{content:s,usage:a,model:this.modelName||this.getDefaultModel(),provider:this.providerName,finishReason:l},success:!0});const p={content:s,usage:a,model:this.modelName||this.getDefaultModel(),provider:this.getProviderName(),...l!==void 0&&{finishReason:l},...c!==void 0&&{rawFinishReason:c},toolsUsed:u.filter(m=>m.error===void 0).map(m=>m.name),toolCalls:u.map(m=>({toolCallId:m.id,toolName:m.name,args:m.input})),toolExecutions:Df(n,Bd(u)),enhancedWithTools:u.some(m=>m.error===void 0)};return p._generationEndEmitted=!0,p}async conversationLoop(t){const r=t.maxSteps||ts,n=await this.resolveTurnTools(t.tools,t.disableTools),o=this.formatToolsForBedrock(n),i=Ac(this.providerName,this.modelName||this.getDefaultModel(),{temperature:t.temperature??.7},"bedrock.converse"),s=t.systemPrompt||"You are a helpful assistant with access to external tools. Use tools when necessary to provide accurate information.",a=(l,c,u,d,p)=>{const m=gLt({client:this.bedrockClient,streaming:!1,region:this.region,maxSteps:r,buildCommandInput:g=>({modelId:this.modelName||this.getDefaultModel(),messages:this.convertToAWSMessages(g),...c?{system:[{text:c}]}:{},inferenceConfig:{maxTokens:u,...d!==void 0&&{temperature:d}},...o?{toolConfig:o}:{}})}),{resultPromise:f}=tp(m,l,{tools:this.toEngineTools(n),abortSignal:p,...t.toolTimeoutMs!==void 0?{toolTimeoutMs:t.toolTimeoutMs}:{}});return f};try{const l=this.conversationHistory;let c,u,d,p,m,f;if(vLt(l)){const b=o?.tools?.map(C=>C.toolSpec).filter(C=>!!C).map(C=>({type:"function",name:C.name??"",description:C.description,inputSchema:yLt(C.inputSchema)}));let S;const k={specificationVersion:"v3",provider:this.providerName,modelId:this.modelName||this.getDefaultModel(),supportedUrls:{},doGenerate:async C=>{C.tools!==void 0&&C.tools!==b&&h.warn("[AmazonBedrockProvider] middleware rewrote 'tools' on the generate path; the rewrite was ignored and the caller's original tool configuration was sent"),this.warnOnUnsentMiddlewareOptions("generate",C);const{system:R,conversation:O}=TLt(C.prompt),U=a(O,R,C.maxOutputTokens??t.maxTokens,C.temperature??i.temperature,Cy(t.abortSignal,C.abortSignal));S=U;const M=await U;return{content:M.text?[{type:"text",text:M.text}]:[],finishReason:{unified:M.finishReason,raw:M.rawStopReason},usage:{inputTokens:{total:M.usage.inputTokens+(M.usage.cacheReadTokens??0)+(M.usage.cacheWriteTokens??0),noCache:M.usage.inputTokens,cacheRead:M.usage.cacheReadTokens,cacheWrite:M.usage.cacheWriteTokens},outputTokens:{total:M.usage.outputTokens}}}},doStream:()=>{throw new Error("AmazonBedrockProvider's generate model does not implement doStream")}},A=await this.applyMiddlewareToModel(k,t);if(typeof A=="string")throw new Error("AmazonBedrockProvider: middleware returned a model id string, not a native model handle");const x=await A.doGenerate({prompt:wLt(s,l),maxOutputTokens:t.maxTokens,temperature:i.temperature,...b?{tools:b}:{},abortSignal:t.abortSignal}),P=await S?.catch(()=>{});c=x.content.filter(C=>C.type==="text").map(C=>C.text).join(""),u=P?.finishReason??x.finishReason.unified,d=P?.rawStopReason??x.finishReason.raw,p=P?.usage??{inputTokens:x.usage.inputTokens.noCache??x.usage.inputTokens.total??0,outputTokens:x.usage.outputTokens.total??0,...x.usage.inputTokens.cacheRead!==void 0&&{cacheReadTokens:x.usage.inputTokens.cacheRead},...x.usage.inputTokens.cacheWrite!==void 0&&{cacheWriteTokens:x.usage.inputTokens.cacheWrite}},m=P?.toolExecutions??[],f=P?.conversation??l}else{this.logMultimodalMiddlewareSkip(t);const b=await a(l,s,t.maxTokens,i.temperature,t.abortSignal);c=b.text||"",u=b.finishReason,d=b.rawStopReason,p=b.usage,m=b.toolExecutions,f=b.conversation}this.conversationHistory=f;const g=p.inputTokens,y=p.outputTokens,v=p.cacheReadTokens??0,T=p.cacheWriteTokens??0;return{text:c||"",usage:{input:g,output:y,total:g+v+T+y,...v>0&&{cacheReadTokens:v},...T>0&&{cacheCreationTokens:T}},finishReason:u,rawFinishReason:d,toolExecutions:m}}catch(l){throw h.error("[AmazonBedrockProvider] Error in conversation loop:",l),this.handleProviderError(l)}}convertToAWSMessages(t){return t.map(r=>({role:r.role,content:r.content.map(n=>n.text?{text:n.text}:n.image?{image:n.image}:n.document?{document:n.document}:n.toolUse?{toolUse:{toolUseId:n.toolUse.toolUseId,name:n.toolUse.name,input:n.toolUse.input}}:n.toolResult?{toolResult:{toolUseId:n.toolResult.toolUseId,content:n.toolResult.content,status:n.toolResult.status}}:{text:""})}))}async executeSingleTool(t,r,n,o){return uN.startActiveSpan("bedrock.tool.execute",{kind:nn.CLIENT,attributes:{"gen_ai.tool.name":r,"gen_ai.system":"aws.bedrock"}},async i=>{try{if(h.debug(`[AmazonBedrockProvider] Executing single tool: ${r}`,{args:n}),!t[r])throw new Error(`Tool not found: ${r}`);const s=t[r];if(!s||!s.execute)throw new Error(`Tool ${r} does not have execute method`);const a=n||{};r==="list_directory"&&!a.path&&(a.path=".",h.debug("[AmazonBedrockProvider] Added default path '.' for list_directory tool")),h.debug("[AmazonBedrockProvider] Tool input parameters:",a);const l={};for(const[d,p]of Object.entries(a))(p===null||typeof p=="string"||typeof p=="number"||typeof p=="boolean"||typeof p=="object"&&p!==null)&&(l[d]=p);const c=await s.execute(l);h.debug("[AmazonBedrockProvider] Tool execution result:",{toolName:r,result:c});let u;if(c&&typeof c=="object"&&"success"in c)if(c.success&&c.data!==void 0)typeof c.data=="string"?u=c.data:typeof c.data=="object"?u=JSON.stringify(c.data,null,2):u=String(c.data);else if(c.error){const d=typeof c.error=="string"?c.error:c.error.message||"Tool execution failed";throw new Error(d)}else u="";else typeof c=="string"?u=c:typeof c=="object"?u=JSON.stringify(c,null,2):u=String(c);return i.setStatus({code:Ue.OK}),u}catch(s){throw h.error("[AmazonBedrockProvider] Tool execution error:",{toolName:r,error:s}),i.setStatus({code:Ue.ERROR,message:s.message}),i.recordException(s),s}finally{i.end()}})}async resolveTurnTools(t,r){if(r)return{};const n=t??await this.getAllTools();return this.convertAISDKToolsToToolDefinitions(n)}toEngineTools(t){const r={};for(const n of Object.keys(t))r[n]={execute:o=>this.executeSingleTool(t,n,o)};return r}convertAISDKToolsToToolDefinitions(t){const r={};for(const[n,o]of Object.entries(t))if("description"in o&&o.description){const s=o.parameters??o.inputSchema;r[n]={description:o.description,parameters:s,execute:async a=>{if("execute"in o&&o.execute)return{success:!0,data:await o.execute(a,{toolCallId:`tool_${Date.now()}`,messages:[]})};throw new Error(`Tool ${n} has no execute method`)}}}return r}formatToolsForBedrock(t){if(!t||Object.keys(t).length===0)return null;const r=Object.entries(t).map(([n,o])=>{let i;return o.parameters&&typeof o.parameters=="object"?"_def"in o.parameters?i=qo(o.parameters):i=o.parameters:i={type:"object",properties:{},required:[]},(!i.type||i.type!=="object")&&(i={type:"object",properties:i.properties||{},required:i.required||[]}),{toolSpec:{name:n,description:o.description,inputSchema:{json:i}}}});return h.debug(`[AmazonBedrockProvider] Formatted ${r.length} tools for Bedrock`),{tools:r}}convertToBedrockMessages(t){return t.map(r=>{const n={role:r.role==="system"?"user":r.role,content:[]};return typeof r.content=="string"?n.content.push({text:r.content}):r.content.forEach(o=>{if(o.type==="text"&&o.text)n.content.push({text:o.text});else if(o.type==="image"&&o.image){const i=typeof o.image=="string"?Buffer.from(o.image.replace(/^data:image\/\w+;base64,/,""),"base64"):o.image;let s=o.mimeType?.split("/")[1]||"png";s==="jpg"&&(s="jpeg"),n.content.push({image:{format:s==="jpeg"?Kx.JPEG:s==="png"?Kx.PNG:s==="gif"?Kx.GIF:Kx.WEBP,source:{bytes:i}}})}else if(o.type==="document"||o.type==="pdf"||o.type==="file"&&o.mimeType?.toLowerCase().startsWith("application/pdf")){let i;if(typeof o.data=="string"){const a=o.data.replace(/^data:application\/pdf;base64,/i,"");i=Buffer.from(a,"base64")}else i=o.data;let s=typeof o.name=="string"&&o.name?om.basename(o.name):"document-pdf";s=s.replace(/\.[^.]+$/,""),s=s.replace(/[^a-zA-Z0-9\s\-()[\]]/g,"-"),s=s.replace(/-+/g,"-").trim().replace(/^-+|-+$/g,""),s=s||"document",n.content.push({document:{format:"pdf",name:s,source:{bytes:i}}})}}),n})}getBedrockClient(){return this.bedrockClient}async executeStream(t){return h.debug("[TRACE] executeStream ENTRY - starting streaming attempt"),h.info("[AmazonBedrockProvider] Attempting real streaming with ConverseStreamCommand"),uN.startActiveSpan("bedrock.stream",{kind:nn.CLIENT,attributes:{"gen_ai.system":"aws.bedrock","gen_ai.request.model":this.modelName||this.getDefaultModel(),"gen_ai.operation.name":"stream"}},async r=>{try{if(h.debug("[TRACE] executeStream TRY block - about to call streamingConversationLoop"),this.conversationHistory=[],!!(t.input?.images?.length||t.input?.content?.length||t.input?.files?.length||t.input?.csvFiles?.length||t.input?.pdfFiles?.length)){h.debug("[AmazonBedrockProvider] Detected multimodal input, using multimodal message builder",{hasImages:!!t.input?.images?.length,imageCount:t.input?.images?.length||0,hasContent:!!t.input?.content?.length,contentCount:t.input?.content?.length||0,hasFiles:!!t.input?.files?.length,fileCount:t.input?.files?.length||0,hasCSVFiles:!!t.input?.csvFiles?.length,csvFileCount:t.input?.csvFiles?.length||0,hasPDFFiles:!!t.input?.pdfFiles?.length,pdfFileCount:t.input?.pdfFiles?.length||0});const i=_Lt(t,this.providerName,this.modelName),s=await A2(i,this.providerName,this.modelName);this.conversationHistory=this.convertToBedrockMessages(s)}else{h.debug("[AmazonBedrockProvider] Text-only input, using simple message builder");const i={role:"user",content:[{text:t.input.text}]};this.conversationHistory.push(i)}h.debug(`[AmazonBedrockProvider] Starting streaming conversation with ${this.conversationHistory.length} message(s)`),h.debug("[TRACE] executeStream - calling streamingConversationLoop NOW");const o=await this.streamingConversationLoop(t,r);return h.debug("[TRACE] executeStream - streamingConversationLoop SUCCESS, returning result"),r.setStatus({code:Ue.OK}),r.end(),o}catch(n){h.debug("[TRACE] executeStream CATCH - error caught from streamingConversationLoop");const o=n,s=typeof o=="object"&&o!==null&&"$metadata"in o&&(o?.name==="AccessDeniedException"||o?.name==="UnauthorizedOperation"||o?.message?.includes("bedrock:InvokeModelWithResponseStream")||o?.message?.includes("streaming")||o?.message?.includes("ConverseStream"));if(h.debug("[TRACE] executeStream CATCH - checking if permission error"),h.debug(`[TRACE] executeStream CATCH - isPermissionError=${s}`),s){h.debug("[TRACE] executeStream CATCH - PERMISSION ERROR DETECTED, starting fallback"),h.warn(`[AmazonBedrockProvider] Streaming permissions not available, falling back to generate method: ${o.message}`),r.addEvent("stream.fallback_to_generate",{reason:o.message});const a=await this.generate({prompt:t.input.text,input:t.input,maxTokens:t.maxTokens,temperature:t.temperature,systemPrompt:t.systemPrompt});if(!a)throw r.setStatus({code:Ue.ERROR,message:"Generate method returned null result"}),r.end(),new Error("Generate method returned null result");r.setAttribute("gen_ai.response.stop_reason","fallback_end_turn"),r.setStatus({code:Ue.OK}),r.end();const l=new ReadableStream({start(u){const p=(a.content||"").split(/(\s+)/);let m="";for(let f=0;f<p.length;f++)m+=p[f],(f===p.length-1||m.length>50||/[.!?;,]\s*$/.test(m))&&m.length>0&&(u.enqueue({content:m}),m="");m.length>0&&u.enqueue({content:m}),u.close()}});return{stream:{async*[Symbol.asyncIterator](){const u=l.getReader();try{for(;;){const{done:d,value:p}=await u.read();if(d)break;yield p}}finally{u.releaseLock()}}},usage:a.usage,model:this.modelName||this.getDefaultModel(),provider:this.getProviderName(),metadata:{fallback:!0}}}throw r.setStatus({code:Ue.ERROR,message:o instanceof Error?o.message:String(o)}),r.recordException(o instanceof Error?o:new Error(String(o))),r.end(),n}})}logMultimodalMiddlewareSkip(t){if(t.middleware??this.middlewareOptions){h.warn("[AmazonBedrockProvider] multimodal turn \u2014 configured middleware was NOT applied (text-only turns only)");return}h.debug("[AmazonBedrockProvider] multimodal turn \u2014 skipping model middleware wrapping (text-only turns only)")}warnOnUnsentMiddlewareOptions(t,r){const n=mJr(r);n.length>0&&h.warn(`[AmazonBedrockProvider] middleware set options the native Bedrock path does not send on the ${t} path; ignored: ${n.map(o=>`'${o}'`).join(", ")}`)}async buildBedrockStreamTurn(t){const{initialConversation:r,systemPromptText:n,options:o,sampling:i,toolConfig:s,turnAbort:a,runTurn:l,raceFirstStep:c}=t;if(!vLt(r)){this.logMultimodalMiddlewareSkip(o);const g=l(r,n,o.maxTokens,i.temperature,a.signal);return await c(g.resultPromise),{stream:g.stream,capturedLoopResult:g.resultPromise}}const u=s?.tools?.map(g=>g.toolSpec).filter(g=>!!g).map(g=>({type:"function",name:g.name??"",description:g.description,inputSchema:yLt(g.inputSchema)}));let d;const p={specificationVersion:"v3",provider:this.providerName,modelId:this.modelName||this.getDefaultModel(),supportedUrls:{},doGenerate:()=>{throw new Error("AmazonBedrockProvider's stream model does not implement doGenerate")},doStream:async g=>{g.tools!==void 0&&g.tools!==u&&h.warn("[AmazonBedrockProvider] middleware rewrote 'tools' on the stream path; the rewrite was ignored and the caller's original tool configuration was sent"),this.warnOnUnsentMiddlewareOptions("stream",g);const{system:y,conversation:v}=TLt(g.prompt),T=l(v,y,g.maxOutputTokens??o.maxTokens,g.temperature??i.temperature,Cy(a.signal,g.abortSignal));d=T.resultPromise,await c(T.resultPromise);const b=T.resultPromise.then(S=>({type:"finish",finishReason:{unified:S.finishReason,raw:S.rawStopReason},usage:{inputTokens:{total:S.usage.inputTokens+(S.usage.cacheReadTokens??0)+(S.usage.cacheWriteTokens??0),noCache:S.usage.inputTokens,cacheRead:S.usage.cacheReadTokens,cacheWrite:S.usage.cacheWriteTokens},outputTokens:{total:S.usage.outputTokens}}}));return b.catch(()=>{}),{stream:fJr(T.stream,b,()=>a.abort())}}},m=await this.applyMiddlewareToModel(p,o);if(typeof m=="string")throw new Error("AmazonBedrockProvider: middleware returned a model id string, not a native model handle");const f=await m.doStream({prompt:wLt(n,r),maxOutputTokens:o.maxTokens,temperature:i.temperature,...u?{tools:u}:{},abortSignal:a.signal});return{stream:gJr(f.stream),capturedLoopResult:d}}summarizeBedrockStreamUsage(t){const r=t?.inputTokens??0,n=t?.outputTokens??0,o=t?.cacheReadTokens??0,i=t?.cacheWriteTokens??0;return{input:r,output:n,total:r+o+i+n,...o>0&&{cacheReadTokens:o},...i>0&&{cacheCreationTokens:i}}}async streamingConversationLoop(t,r){const n=Date.now(),o=t.maxSteps||ts,i=await this.resolveTurnTools(t.tools,t.disableTools),s=this.formatToolsForBedrock(i),a=Ac(this.providerName,this.modelName||this.getDefaultModel(),{temperature:t.temperature??.7},"bedrock.converseStream"),l=t.systemPrompt||"You are a helpful assistant with access to external tools. Use tools when necessary to provide accurate information.";let c=!1,u;const d=new Promise(C=>{u=()=>{c=!0,C()}}),p=async C=>{const R=C.then(O=>({result:O,error:void 0}),O=>({result:void 0,error:O}));if(await Promise.race([d,R]),!c){const O=await R;if(O.error)throw O.error}},m=(C,R,O,U,M)=>{const D=gLt({client:this.bedrockClient,streaming:!0,region:this.region,maxSteps:o,buildCommandInput:B=>({modelId:this.modelName||this.getDefaultModel(),messages:this.convertToAWSMessages(B),...R?{system:[{text:R}]}:{},inferenceConfig:{maxTokens:O,...U!==void 0&&{temperature:U}},...s?{toolConfig:s}:{}})}),$={...D,executeStep:async(B,q,L)=>{const j=await D.executeStep(B,q,L);return u(),j}};return r.addEvent("stream.api_call",{"bedrock.tool_count":s?.tools?.length??0}),tp($,C,{tools:this.toEngineTools(i),abortSignal:M,...t.toolTimeoutMs!==void 0?{toolTimeoutMs:t.toolTimeoutMs}:{}})},f=this.conversationHistory,g=new AbortController;t.abortSignal&&(t.abortSignal.aborted?g.abort():t.abortSignal.addEventListener("abort",()=>g.abort(),{once:!0}));const{stream:y,capturedLoopResult:v}=await this.buildBedrockStreamTurn({initialConversation:f,systemPromptText:l,options:t,sampling:a,toolConfig:s,turnAbort:g,runTurn:m,raceFirstStep:p}).catch(C=>{throw g.abort(),C}),T=(v??Promise.resolve(void 0)).then(C=>({result:C,error:void 0}),C=>({result:void 0,error:C})),b=this.neurolink?.getEventEmitter(),S=this,k={startTime:n,streamId:`bedrock-${Date.now()}`};let A;const x=new Promise(C=>{A=C});return T.then(C=>{A(cv(this.providerName,this.modelName||this.getDefaultModel(),{usage:this.summarizeBedrockStreamUsage(C.result?.usage),toolExecutions:C.result?.toolExecutions??[],toolsUsed:(C.result?.toolExecutions??[]).filter(R=>R.error===void 0).map(R=>R.name)},Date.now()-n,{requestId:`bedrock-stream-${Date.now()}`,streamingMode:!0}))}),{stream:{async*[Symbol.asyncIterator](){let C=!1;try{yield*y}catch(R){throw C=!0,R}finally{const R=await T;R.error&&(C=!0);const O=S.summarizeBedrockStreamUsage(R.result?.usage);if(R.result&&(S.conversationHistory=R.result.conversation,k.finishReason=R.result.finishReason,k.rawFinishReason=R.result.rawStopReason,r.setAttribute("gen_ai.response.stop_reason",R.result.rawStopReason??"unknown")),b){const U=t._streamDedupContext;U&&(U.providerEmitted=!0),b.emit("generation:end",{provider:S.providerName,responseTime:Date.now()-n,timestamp:Date.now(),result:{content:"",usage:O,model:S.modelName||S.getDefaultModel(),provider:S.providerName,finishReason:C?"error":R.result?.rawStopReason},success:!C})}}}},model:this.modelName||this.getDefaultModel(),provider:this.getProviderName(),analytics:x,metadata:k}}async checkBedrockHealth(){const t=new AbortController,r=setTimeout(()=>t.abort(),1e4),{BedrockClient:n,ListFoundationModelsCommand:o}=await Qee(),i=new n({region:process.env.AWS_REGION||"us-east-1"});try{h.debug("[AmazonBedrockProvider] Starting health check...");const s=new o({}),l=(await i.send(s,{abortSignal:t.signal})).modelSummaries||[],c=l.filter(u=>u.modelLifecycle?.status==="ACTIVE");if(h.debug(`[AmazonBedrockProvider] Health check passed - Found ${c.length} active models out of ${l.length} total models`),c.length===0)throw new Error("No active foundation models available in the region")}catch(s){clearTimeout(r);const a=s;if(pr(s))throw new Error("Bedrock health check timed out after 10 seconds",{cause:s});const l=typeof a.message=="string"?a.message:"";throw l.includes("UnauthorizedOperation")||l.includes("AccessDenied")?new Error("Bedrock access denied. Check your AWS credentials and IAM permissions for bedrock:ListFoundationModels",{cause:s}):a.code==="ECONNREFUSED"||a.code==="ENOTFOUND"?new Error("Unable to connect to Bedrock service. Check your network connectivity and AWS region configuration",{cause:s}):(h.error("[AmazonBedrockProvider] Health check failed:",s),new Error(`Bedrock health check failed: ${l||"Unknown error"}`,{cause:s}))}finally{clearTimeout(r);try{i.destroy()}catch{}}}formatProviderError(t){return ba(t,[{match:n=>/AccessDeniedException/i.test(n.message),errorClass:Wr,message:"AWS Bedrock access denied. Check your credentials and permissions."},{match:n=>n.errorName==="ThrottlingException"||n.errorCode==="ThrottlingException",errorClass:Qi,message:n=>`Bedrock rate limit (throttled): ${n.message}`},{match:n=>/ValidationException/i.test(n.message),errorClass:nt,message:n=>`Validation error: ${n.message}`},{match:()=>!0,errorClass:nt,message:n=>`AWS Bedrock error: ${n.message}`}],this.providerName,this.modelName)}async embed(t,r){const n=typeof t=="string"?{text:t}:t,o=r||this.getDefaultEmbeddingModel(),i=o.includes("nova")&&o.includes("multimodal"),s=o.includes("image")||o.includes("multimodal")||o==="amazon.titan-embed-image-v1"||i;h.debug("Generating embedding",{provider:this.providerName,model:o,hasText:typeof n.text=="string",hasImage:n.image!==void 0,isMultiModalModel:s});try{let a;if(n.image&&!s)throw new nt(`${this.providerName} model ${o} does not support image embeddings`,this.providerName);if(i){if(n.image&&n.text)throw new nt(`${this.providerName} model ${o} does not support combined image+text embeddings; provide exactly one of image or text`,this.providerName);const p={embeddingPurpose:"GENERIC_RETRIEVAL"};if(n.image){const m=Buffer.isBuffer(n.image)?n.image:Buffer.from(n.image,"base64"),f=TJr(n.mimeType);if(f===void 0)throw new nt(`${this.providerName} model ${o} does not support image format '${n.mimeType??"unknown"}'; supported formats are ${Object.keys(ete).join(", ")}`,this.providerName);p.image={detailLevel:"STANDARD_IMAGE",format:f,source:{bytes:bo.safeBase64Convert(m,"bedrock nova embed image")}}}n.text&&(p.text={value:n.text,truncationMode:"NONE"}),a=JSON.stringify({taskType:"SINGLE_EMBEDDING",singleEmbeddingParams:p})}else if(n.image){const p=Buffer.isBuffer(n.image)?n.image:Buffer.from(n.image,"base64");a=JSON.stringify({inputText:n.text??"",inputImage:bo.safeBase64Convert(p,"bedrock titan embed image")})}else a=JSON.stringify({inputText:n.text??""});const l=new lLt({modelId:o,contentType:"application/json",accept:"application/json",body:a}),c=await ze(this.bedrockClient.send(l),6e4,new Error("Bedrock embedding API call timed out")),u=JSON.parse(new TextDecoder().decode(c.body)),d=i?u.embeddings?.at(0)?.embedding:u.embedding;if(!Array.isArray(d))throw new Error("Invalid embedding response from Bedrock");return h.debug("Embedding generated successfully",{provider:this.providerName,model:o,embeddingDimension:d.length}),d}catch(a){throw h.error("Embedding generation failed",{error:a instanceof Error?a.message:String(a),model:o}),this.handleProviderError(a)}}async embedMany(t,r){const n=r||this.getDefaultEmbeddingModel();h.debug("Generating batch embeddings",{provider:this.providerName,model:n,count:t.length});try{const o=await Promise.all(t.map(i=>this.embed(i,n)));return h.debug("Batch embeddings generated successfully",{provider:this.providerName,model:n,count:o.length,embeddingDimension:o[0]?.length}),o}catch(o){throw h.error("Batch embedding generation failed",{error:o instanceof Error?o.message:String(o),model:n,count:t.length}),this.handleProviderError(o)}}}}}),S3t={};Z(S3t,{AmazonBedrockProvider:()=>E3t,bedrockTracer:()=>uN,loadBedrockControl:()=>Qee});var _Jr=E({"src/lib/providers/amazonBedrock/index.ts"(){"use strict";bJr(),ELt(),_3t()}}),k3t={};Z(k3t,{AzureOpenAIProvider:()=>x3t});var x3t,EJr=E({"src/lib/providers/azureOpenai.ts"(){"use strict";pt(),z(),Zs(),Go(),zl(),zc(),Um(),x3t=class extends Kl{azureDeployment;azureApiVersion;azureResourceOrigin;azureDeploymentPathPrefix;useMaxCompletionTokensOverride;constructor(e,t,r,n){const o=n?.apiKey||process.env.AZURE_OPENAI_API_KEY||"",i=process.env.AZURE_OPENAI_ENDPOINT||"";let s;if(i)try{s=new URL(i.includes("://")?i:`https://${i}`)}catch{s=void 0}const a=s?.hostname??"",l=s?.pathname&&s.pathname!=="/"?s.pathname.replace(/\/+$/,""):"",c=/\.(openai|cognitiveservices)\.azure\.com$/.test(a);let u;c?u="/openai":u=/\/openai(?:\/v\d+)?$/.test(l)?l:`${l}/openai`;const d=s?.origin??"",p=n?.deploymentName||e||process.env.AZURE_OPENAI_MODEL||process.env.AZURE_OPENAI_DEPLOYMENT||process.env.AZURE_OPENAI_DEPLOYMENT_ID||"gpt-4o",m=n?.apiVersion||process.env.AZURE_API_VERSION||"2025-04-01-preview",f=process.env.AZURE_OPENAI_USE_MAX_COMPLETION_TOKENS,g=n?.useMaxCompletionTokens??(f===void 0?void 0:/^(1|true|yes)$/i.test(f));o||_a(z4r()),d||_a(G4r()),super("azure",e,t,{baseURL:d,apiKey:o}),this.azureDeployment=p,this.azureApiVersion=m,this.azureResourceOrigin=d,this.azureDeploymentPathPrefix=u,this.useMaxCompletionTokensOverride=g,h.shouldLog("debug")&&h.debug("Azure OpenAI Provider initialized",CXe({deployment:this.azureDeployment,resourceOrigin:this.azureResourceOrigin,deploymentPathPrefix:this.azureDeploymentPathPrefix,apiVersion:this.azureApiVersion,provider:"azure"}))}suppressResponseFormatWithTools(){return!1}getProviderName(){return"azure"}getDefaultModel(){return this.azureDeployment}formatProviderError(e){const t=[{match:r=>im(r.message,401),errorClass:Wr,message:"Invalid Azure OpenAI API key or endpoint."},...Ll];return ba(e,t,this.providerName,this.modelName)}getChatCompletionsURL(e){const t=e||this.azureDeployment,r=this.azureDeploymentPathPrefix.replace(/\/+$/,"");return`${this.azureResourceOrigin}${r}/deployments/${t}/chat/completions?api-version=${this.azureApiVersion}`}getAuthHeaders(){return{"api-key":this.config.apiKey}}adjustRequestBody(e,t){const r=this.useMaxCompletionTokensOverride??bRt(t);return e.max_tokens!==void 0&&r?{...e,max_completion_tokens:e.max_tokens,max_tokens:void 0}:e}}}});function Jx(e){return e.length>=8&&e[0]===137&&e[1]===80&&e[2]===78&&e[3]===71&&e[4]===13&&e[5]===10&&e[6]===26&&e[7]===10?"image/png":e.length>=3&&e[0]===255&&e[1]===216&&e[2]===255?"image/jpeg":e.length>=12&&e[0]===82&&e[1]===73&&e[2]===70&&e[3]===70&&e[8]===87&&e[9]===69&&e[10]===66&&e[11]===80?"image/webp":e.length>=6&&e[0]===71&&e[1]===73&&e[2]===70&&e[3]===56&&(e[4]===55||e[4]===57)&&e[5]===97?"image/gif":null}function Xx(e){return Jx(e)??"image/png"}var xw=E({"src/lib/utils/imageDetection.ts"(){"use strict"}});function A3t(e){return e.map(t=>typeof t.content=="string"?{role:t.role,content:t.content}:{role:t.role,content:t.content.map(r=>r.type==="image"||r.type==="document"?{type:r.type,media_type:r.source.media_type,base64_chars:r.source.data.length}:r)})}var SJr=E({"src/lib/utils/anthropicTraceSanitizer.ts"(){"use strict"}}),dN,kJr=E({"node_modules/.pnpm/@anthropic-ai+vertex-sdk@0.16.0_zod@4.3.6/node_modules/@anthropic-ai/vertex-sdk/internal/utils/env.mjs"(){dN=e=>{if(typeof globalThis.process<"u")return globalThis.process.env?.[e]?.trim()||void 0;if(typeof globalThis.Deno<"u")return globalThis.Deno.env?.get?.(e)?.trim()||void 0}}}),xJr=E({"node_modules/.pnpm/@anthropic-ai+vertex-sdk@0.16.0_zod@4.3.6/node_modules/@anthropic-ai/vertex-sdk/core/error.mjs"(){$o()}});function tte(e){return e!=null&&typeof e=="object"&&!Array.isArray(e)}var pN,rte,C3t=E({"node_modules/.pnpm/@anthropic-ai+vertex-sdk@0.16.0_zod@4.3.6/node_modules/@anthropic-ai/vertex-sdk/internal/utils/values.mjs"(){xJr(),pN=e=>(pN=Array.isArray,pN(e)),rte=pN}});function*AJr(e){if(!e)return;if(nte in e){const{values:n,nulls:o}=e;yield*n.entries();for(const i of o)yield[i,null];return}let t=!1,r;e instanceof Headers?r=e.entries():rte(e)?r=e:(t=!0,r=Object.entries(e??{}));for(let n of r){const o=n[0];if(typeof o!="string")throw new TypeError("expected header name to be a string");const i=rte(n[1])?n[1]:[n[1]];let s=!1;for(const a of i)a!==void 0&&(t&&!s&&(s=!0,yield[o,null]),yield[o,a])}}var nte,I3t,CJr=E({"node_modules/.pnpm/@anthropic-ai+vertex-sdk@0.16.0_zod@4.3.6/node_modules/@anthropic-ai/vertex-sdk/internal/headers.mjs"(){C3t(),nte=Symbol.for("brand.privateNullableHeaders"),I3t=e=>{const t=new Headers,r=new Set;for(const n of e){const o=new Set;for(const[i,s]of AJr(n)){const a=i.toLowerCase();o.has(a)||(t.delete(i),o.add(a)),s===null?(t.delete(i),r.add(a)):(t.append(i,s),r.delete(a))}}return{[nte]:!0,values:t,nulls:r}}}});function IJr(e){const t=new Bx(e);return delete t.batches,t}function RJr(e){const t=new sa(e);return delete t.messages.batches,t}var R3t,P3t,ote,M3t=E({"node_modules/.pnpm/@anthropic-ai+vertex-sdk@0.16.0_zod@4.3.6/node_modules/@anthropic-ai/vertex-sdk/client.mjs"(){QD(),S2t(),yk(),kJr(),C3t(),CJr(),QD(),R3t="vertex-2023-10-16",P3t=new Set(["/v1/messages","/v1/messages?beta=true"]),ote=class extends jo{constructor({baseURL:e=dN("ANTHROPIC_VERTEX_BASE_URL"),region:t=dN("CLOUD_ML_REGION")??null,projectId:r=dN("ANTHROPIC_VERTEX_PROJECT_ID")??null,...n}={}){if(!t)throw new Error("No region was given. The client should be instantiated with the `region` option or the `CLOUD_ML_REGION` environment variable should be set.");if(!e)switch(t){case"global":e="https://aiplatform.googleapis.com/v1";break;case"us":e="https://aiplatform.us.rep.googleapis.com/v1";break;case"eu":e="https://aiplatform.eu.rep.googleapis.com/v1";break;default:e=`https://${t}-aiplatform.googleapis.com/v1`}if(super({baseURL:e,...n}),this.messages=IJr(this),this.beta=RJr(this),this.region=t,this.projectId=r,this.accessToken=n.accessToken??null,n.authClient&&n.googleAuth)throw new Error("You cannot provide both `authClient` and `googleAuth`. Please provide only one of them.");n.authClient?this._authClientPromise=Promise.resolve(n.authClient):(this._auth=n.googleAuth??new WK({scopes:"https://www.googleapis.com/auth/cloud-platform"}),this._authClientPromise=this._auth.getClient())}validateHeaders(){}async prepareOptions(e){const t=await this._authClientPromise,r=await t.getRequestHeaders(),n=t.projectId??r["x-goog-user-project"];!this.projectId&&n&&(this.projectId=n),e.headers=I3t([r,e.headers])}async buildRequest(e){if(tte(e.body)&&(e.body={...e.body}),tte(e.body)&&(e.body.anthropic_version||(e.body.anthropic_version=R3t)),P3t.has(e.path)&&e.method==="post"){if(!this.projectId)throw new Error("No projectId was given and it could not be resolved from credentials. The client should be instantiated with the `projectId` option or the `ANTHROPIC_VERTEX_PROJECT_ID` environment variable should be set.");if(!tte(e.body))throw new Error("Expected request body to be an object for post /v1/messages");const t=e.body.model;e.body.model=void 0;const n=e.body.stream??!1?"streamRawPredict":"rawPredict";e.path=`/projects/${this.projectId}/locations/${this.region}/publishers/anthropic/models/${t}:${n}`}if(e.path==="/v1/messages/count_tokens"||e.path=="/v1/messages/count_tokens?beta=true"&&e.method==="post"){if(!this.projectId)throw new Error("No projectId was given and it could not be resolved from credentials. The client should be instantiated with the `projectId` option or the `ANTHROPIC_VERTEX_PROJECT_ID` environment variable should be set.");e.path=`/projects/${this.projectId}/locations/${this.region}/publishers/anthropic/models/count-tokens:rawPredict`}return super.buildRequest(e)}}}}),ite={};Z(ite,{AnthropicVertex:()=>ote,BaseAnthropic:()=>jo,default:()=>ote});var O3t=E({"node_modules/.pnpm/@anthropic-ai+vertex-sdk@0.16.0_zod@4.3.6/node_modules/@anthropic-ai/vertex-sdk/index.mjs"(){M3t(),M3t()}});async function PJr(){return mN||(mN=await Promise.resolve().then(()=>(O3t(),ite))),mN}function MJr(e){const t=[],r=new Map;let n=0;const o=i=>{const s=`${n}:${i??"x"}`;let a=r.get(s);return a||(a={type:"tool_step",callParts:[],resultParts:[]},r.set(s,a),t.push(a)),a};for(const i of e){if(i.role==="tool_call"){o(i.metadata?.stepIndex).callParts.push({name:i.tool||"unknown",input:i.args||{}});continue}if(i.role==="tool_result"){o(i.metadata?.stepIndex).resultParts.push(i.content&&i.content.length>0?i.content:"(no output)");continue}const s=i.role==="assistant"?"assistant":i.role==="user"?"user":null;!s||!i.content||i.content.trim().length===0||(n++,t.push({type:"regular",role:s,parts:[i.content]}))}return t}function ste(e,t,r){const n=e[e.length-1];n&&n.role===t&&Array.isArray(n.content)?n.content.push(...r):e.push({role:t,content:[...r]})}function OJr(e,t){const r=e.callParts,n=e.resultParts,o=Math.min(r.length,n.length);(o!==r.length||o!==n.length)&&h.debug("[GoogleVertex] Unbalanced tool step in Claude history replay",{calls:r.length,results:n.length,paired:o});const i=[],s=[];for(let a=0;a<o;a++){const l=`hist_${t}_${a}`;i.push({type:"tool_use",id:l,name:r[a].name,input:r[a].input}),s.push({type:"tool_result",tool_use_id:l,content:n[a]})}return{uses:i,results:s}}function DJr(e){const t=r=>Array.isArray(r.content)&&r.content.length>0&&r.content.every(n=>n.type==="tool_result");for(;e.length>0&&(e[0].role!=="user"||t(e[0]));)e.shift()}function ate(e){const t=[];let r=0;for(const n of MJr(e)){if(n.type==="regular"){ste(t,n.role==="assistant"?"assistant":"user",[{type:"text",text:String(n.parts[0]??"")}]);continue}const{uses:o,results:i}=OJr(n,r);o.length!==0&&(r++,ste(t,"assistant",o),ste(t,"user",i))}if(DJr(t),h.shouldLog("debug")){const n=t.flatMap(o=>Array.isArray(o.content)?o.content:[]);h.debug("[GoogleVertex] Replayed Claude history with tool turns",{historyMessages:t.length,toolUseBlocks:n.filter(o=>o.type==="tool_use").length,toolResultBlocks:n.filter(o=>o.type==="tool_result").length})}return t}function lte(e,t){const r=e[e.length-1];if(r&&r.role==="user"){const n=Array.isArray(r.content)?r.content:[{type:"text",text:r.content}],o=Array.isArray(t)?t:[{type:"text",text:t}];r.content=[...n,...o];return}e.push({role:"user",content:t})}function Ng(e){if(!e||typeof e!="object")return;const t=["additionalProperties","default","$schema","$id","$ref","definitions","$defs","examples","errorMessage"];for(const n of t)n in e&&delete e[n];typeof e.exclusiveMinimum=="boolean"&&(e.exclusiveMinimum===!0&&typeof e.minimum=="number"?(e.exclusiveMinimum=e.minimum,delete e.minimum):delete e.exclusiveMinimum),typeof e.exclusiveMaximum=="boolean"&&(e.exclusiveMaximum===!0&&typeof e.maximum=="number"?(e.exclusiveMaximum=e.maximum,delete e.maximum):delete e.exclusiveMaximum);const r=2147483647;if(typeof e.maximum=="number"&&e.maximum>r&&delete e.maximum,typeof e.minimum=="number"&&e.minimum<-r&&delete e.minimum,e.properties&&typeof e.properties=="object")for(const n of Object.values(e.properties))n&&typeof n=="object"&&Ng(n);if(e.items&&typeof e.items=="object")if(Array.isArray(e.items))for(const n of e.items)n&&typeof n=="object"&&Ng(n);else Ng(e.items);for(const n of["allOf","anyOf","oneOf"])if(Array.isArray(e[n]))for(const o of e[n])o&&typeof o=="object"&&Ng(o)}async function*NJr(e,t){const r=e.getReader();let n=!1;try{for(;;){const o=await r.read();if(o.done){n=!0;return}const i=o.value;if(i.type==="text-delta")yield{content:i.delta};else if(i.type==="reasoning-delta")yield{content:"",reasoning:i.delta};else if(i.type==="finish")t(i);else if(i.type==="error")throw i.error}}finally{try{n||await r.cancel()}finally{r.releaseLock()}}}function D3t(e,t,r){const n=wIt({contents:e,availableInputTokens:ql("vertex",t),provider:"vertex",observedPromptTokens:r});if(!n)return!1;const o=new Set(n.drop),i=new Set(n.truncate),s=[];for(let a=0;a<e.length;a++){if(o.has(a))continue;const l=e[a];if(i.has(a)&&Array.isArray(l.parts)){s.push({...l,parts:l.parts.map(c=>{if(!("functionResponse"in c))return c;const u=c.functionResponse,d=JSON.stringify(u.response)??"";return d.length<=G3t?c:{functionResponse:{name:u.name,response:{result:SY(d)}}}})});continue}s.push(l)}if(o.size>0){let a=s.findIndex(l=>Array.isArray(l.parts)&&l.parts.some(c=>!!c.functionCall||!!c.functionResponse));a<0&&(a=Math.min(1,s.length)),s.splice(a,0,{role:"user",parts:[{text:xY}]})}return e.length=0,e.push(...s),!0}function N3t(e,t,r){const n=UNt({conversation:e,availableInputTokens:ql("vertex",t),fixedOverheadTokens:0,provider:"vertex",observedPromptTokens:r,observedDescribesCurrentPayload:!0});if(!n)return!1;const o=new Set(n.drop),i=new Set(n.truncate),s=[];for(let a=0;a<e.length;a++){if(o.has(a))continue;const l=e[a];if(i.has(a)&&Array.isArray(l.content)){s.push({...l,content:l.content.map(c=>{if(c.type!=="tool_result")return c;const u=typeof c.content=="string"?c.content:JSON.stringify(c.content)??"";return{...c,content:$Nt(u)}})});continue}s.push(l)}if(o.size>0){let a=s.findIndex(l=>Array.isArray(l.content)&&l.content.some(c=>c.type==="tool_use"||c.type==="tool_result"));a<0&&(a=Math.min(1,s.length)),s.splice(a,0,{role:"user",content:[{type:"text",text:Lee}]})}return e.length=0,e.push(...s),!0}async function L3t(e,t,r={}){const n=[],o=[];let i,s=0,a=0,l=0,c=0;for await(const u of e){r.onProgress?.();const d=u,m=d.candidates?.[0],f=m?.finishReason;typeof f=="string"&&f&&(i=f);const g=m?.content;if(g&&Array.isArray(g.parts))for(const v of g.parts)n.push(v),typeof v.text=="string"&&v.text.length>0&&t.push({content:v.text});u.functionCalls&&o.push(...u.functionCalls);const y=d.usageMetadata;if(y){if(y.promptTokenCount!==void 0&&y.promptTokenCount>0){r.onUsageDelta?.("input",y.promptTokenCount-s),s=y.promptTokenCount,r.onUsage?.(y.promptTokenCount,y.candidatesTokenCount??0);const v=Math.min(y.cachedContentTokenCount??0,y.promptTokenCount);r.onUsageDelta?.("cacheRead",v-l),l=v}y.candidatesTokenCount!==void 0&&y.candidatesTokenCount>0&&(r.onUsageDelta?.("output",y.candidatesTokenCount-a),a=y.candidatesTokenCount),y.thoughtsTokenCount!==void 0&&y.thoughtsTokenCount>0&&(r.onUsageDelta?.("reasoning",y.thoughtsTokenCount-c),c=y.thoughtsTokenCount)}}return{rawResponseParts:n,stepFunctionCalls:o,...i?{finishReason:i}:{},inputTokens:s,outputTokens:a,...l?{cacheReadTokens:l}:{},...c?{reasoningTokens:c}:{}}}function F3t(e){return e.some(t=>t.type==="tool_use")?"":e.filter(t=>t.type==="text").map(t=>t.text).join("")}var mN,$3t,cte,Yx,ute,Aw,Lg,U3t,B3t,hN,z3t,G3t,dte,LJr=E({"src/lib/providers/googleVertex/client.ts"(){"use strict";Tn(),EO(),kr(),pl(),KW(),CO(),EK(),Zo(),If(),Mf(),EY(),Nt(),Ln(),pt(),Zs(),et(),iN(),lEt(),R2(),z(),pY(),pv(),JP(),bIt(),BNt(),fO(),xw(),yO(),Go(),ss(),Q1t(),dg(),Ys(),_It(),mIt(),RO(),YNt(),Mk(),Jv(),CY(),$c(),qS(),il(),Qt(),sl(),zl(),vm(),Ic(),SJr(),Mk(),mN=null,$3t=()=>!0,cte=()=>_a(X4r()),Yx=()=>process.env.GOOGLE_CLOUD_LOCATION||process.env.VERTEX_LOCATION||process.env.GOOGLE_VERTEX_LOCATION||"us-central1",ute=(e,t)=>{const r=t||Yx();if(!e)return r;const n=e.toLowerCase();return n.startsWith("gemini-")||n.includes("/gemini-")||D8.some(i=>n===i.toLowerCase()||n.includes(i.toLowerCase())||i.toLowerCase().includes(n))?process.env.GOOGLE_VERTEX_GLOBAL_LOCATION||"global":r},Aw=ute,Lg=()=>process.env.VERTEX_MODEL||"gemini-2.5-flash",U3t=()=>!!(process.env.GOOGLE_APPLICATION_CREDENTIALS_NEUROLINK||process.env.GOOGLE_APPLICATION_CREDENTIALS||process.env.GOOGLE_SERVICE_ACCOUNT_KEY||process.env.GOOGLE_AUTH_CLIENT_EMAIL&&process.env.GOOGLE_AUTH_PRIVATE_KEY),B3t=async(e,t,r,n)=>{const o=e||Yx();return{projectId:r?r.projectId?.trim()||"express":cte(),region:o,...t!==void 0&&{timeout:t},maxRetries:0,...n?{baseURL:n}:{},...r?{authClient:{getRequestHeaders:async()=>({Authorization:`Bearer ${r.apiKey}`}),projectId:null}}:{}}},hN=e=>e.toLowerCase().includes("claude"),z3t=(e,t)=>{const r=e[Symbol.asyncIterator]();return new ReadableStream({async pull(n){try{const o=await r.next();if(o.done){n.enqueue(t()),n.close();return}const i=o.value;"content"in i&&typeof i.content=="string"&&("reasoning"in i&&typeof i.reasoning=="string"&&i.reasoning.length>0&&n.enqueue({type:"reasoning-delta",delta:i.reasoning}),i.content.length>0&&n.enqueue({type:"text-delta",delta:i.content}))}catch(o){n.error(o)}},cancel(){NS(r)}})},G3t=2048,dte=class mn extends Ma{projectId;location;expressApiKey;baseURL;registeredTools=new Map;toolContext={};static modelConfigCache=new Map;static modelConfigCacheTime=0;static CACHE_DURATION=300*1e3;static MAX_CACHE_SIZE=50;static maxTokensCache=new Map;static maxTokensCacheTime=0;constructor(t,r,n,o,i){super(t,"vertex",n),i&&(i.projectId&&(process.env.GOOGLE_CLOUD_PROJECT=String(i.projectId)),i.location&&(process.env.GOOGLE_CLOUD_LOCATION=String(i.location)),i.apiKey&&(process.env.GOOGLE_API_KEY=String(i.apiKey),!i.projectId&&!i.location&&(this.expressApiKey=String(i.apiKey))),i.baseURL&&(this.baseURL=String(i.baseURL)));const s=!!this.resolveExpressApiKey();s||U3t()||_a(Y4r()),this.projectId=i?.projectId||(s?"":cte()),this.location=o||i?.location||Yx(),h.debug("[GoogleVertexProvider] Constructor initialized",{regionParam:o,resolvedLocation:this.location,projectId:this.projectId}),h.debug("Google Vertex AI BaseProvider v2 initialized",{modelName:this.modelName,projectId:this.projectId,location:this.location,provider:this.providerName})}getProviderName(){return"vertex"}getDefaultModel(){return Lg()}async getAISDKModel(){throw new De({code:He.INVALID_CONFIGURATION,message:"GoogleVertexProvider no longer uses @ai-sdk/google-vertex. All models use native SDKs: @google/genai for Gemini, @anthropic-ai/vertex-sdk for Claude.",category:"configuration",severity:"critical",retriable:!1,context:{provider:this.providerName,model:this.modelName}})}validateStreamOptionsOnly(t){this.validateStreamOptions(t)}async preprocessNativeFileInput(t){if(t.input&&RJ(t.input),t.input?.files?.length)try{await PJ(t,100*1024*1024,this.providerName)}catch(r){h.warn(`[GoogleVertex] processUnifiedFilesArray threw, continuing without file content: ${r instanceof Error?r.message:String(r)}`)}await Ck(t.input)}async executeStream(t,r){const n=t.model||this.modelName||Lg();return U9e({name:"neurolink.provider.stream",tracer:Be.provider,attributes:{[Re.GEN_AI_SYSTEM]:this.providerName,[Re.GEN_AI_MODEL]:n,[Re.GEN_AI_OPERATION]:"stream",[Re.NL_PROVIDER]:this.providerName}},async o=>{const i=Date.now(),s=t.tools||{};await this.preprocessNativeFileInput(t);const l={...await mt({name:"neurolink.message.build",tracer:Be.provider,attributes:{[Re.NL_PROVIDER]:this.providerName,"message.count":1,"message.build.count":1,"message.build.path":"vertex.native.stream"}},async()=>this.processCSVFilesForNativeSDK(t)),tools:s},c=l.input?.text||l.prompt||"";try{let u;hN(n)?(h.info("[GoogleVertex] Routing Claude model to native @anthropic-ai/vertex-sdk",{model:n,totalToolCount:Object.keys(s).length}),u=await this.runNativeStreamWithMiddleware(l,n,p=>this.executeNativeAnthropicStream(p))):(h.info("[GoogleVertex] Routing Gemini model to native @google/genai",{model:n,totalToolCount:Object.keys(s).length}),u=await this.runNativeStreamWithMiddleware(l,n,p=>this.executeNativeGemini3Stream(p))),this.attachUsageAndCostAttributes(o,n,u?.usage);const d=this.wrapStreamResultWithLifecycle(t,u,i);return this.emitStreamEnd(n,i,!0,void 0,u.finishReason),d}catch(u){throw this.fireGenerateOnError(t,u,i),this.emitStreamEnd(n,i,!1,u),this.emitGenerationEnd(n,null,i,!1,u,c),u}},o=>o.stream,(o,i)=>this.preserveStreamResultAccessors(o,{...o,stream:i}))}emitStreamEnd(t,r,n,o,i){const s=this.neurolink?.getEventEmitter();s&&s.emit("stream:end",{provider:this.providerName,responseTime:Date.now()-r,timestamp:Date.now(),result:{content:"",usage:{input:0,output:0,total:0},model:t,provider:this.providerName,finishReason:n?i??"stop":"error"},success:n,...o?{error:o instanceof Error?o.message:String(o)}:{}})}async createVertexGenAIClient(t){const r=this.resolveExpressApiKey(),n=r?"":this.projectId,o=t||this.location||Yx(),s=(await Promise.resolve().then(()=>(KE(),zy))).GoogleGenAI;if(!s)throw new De({code:He.INVALID_CONFIGURATION,message:"@google/genai does not export GoogleGenAI",category:"configuration",severity:"critical",retriable:!1,context:{module:"@google/genai",expectedExport:"GoogleGenAI"}});const a=s,l=this.resolveBaseURL(),c={...l?{baseUrl:l}:{},...PY()};return r?new a({vertexai:!0,apiKey:r,httpOptions:c}):new a({vertexai:!0,project:n,location:o,httpOptions:c})}resolveBaseURL(){const t=this.baseURL?.trim()||process.env.GOOGLE_VERTEX_BASE_URL?.trim();return t&&t.length>0?t:void 0}resolveExpressApiKey(){const t=this.expressApiKey?.trim();if(t)return t;const r=process.env.GOOGLE_VERTEX_API_KEY?.trim();return r?["GOOGLE_CLOUD_PROJECT_ID","VERTEX_PROJECT_ID","GOOGLE_VERTEX_PROJECT","GOOGLE_CLOUD_PROJECT"].some(o=>(process.env[o]??"").trim().length>0)?void 0:r:void 0}buildAnthropicToolDeclaration(t,r){const n={name:t,description:r.description||`Tool: ${t}`,input_schema:{type:"object"}},i=r.parameters||r.inputSchema;if(i){const s=qo(i),a=Kn(s);n.input_schema={type:"object",properties:a.properties||{},required:a.required||[]}}return n}refreshAnthropicToolDeclarations(t,r,n,o){if(!t||!r)return;const i=new Set(r.map(s=>s.name));for(const[s,a]of Object.entries(t))i.has(s)||(r.push(this.buildAnthropicToolDeclaration(s,a)),a.execute&&n.set(s,a.execute),o.delete(s),h.info(`[GoogleVertex] Tool "${s}" hydrated mid-turn via discovery \u2014 added to Anthropic declarations.`))}resolveAnthropicToolOnMiss(t,r,n,o,i){if(!n)return;const s=fQe(r,t);if(s?.execute)return n.some(a=>a.name===t)||n.push(this.buildAnthropicToolDeclaration(t,s)),o.set(t,s.execute),i.delete(t),h.info(`[GoogleVertex] Tool "${t}" resolved mid-turn via discovery \u2014 executing.`),o.get(t)}buildFinalResultTool(t){const r=qo(t),n=Kn(r);n.$schema&&delete n.$schema;const o=ea(n);return{name:"final_result",description:"Return the final structured result. You MUST call this tool when you have gathered all information and are ready to provide the final answer. The arguments should contain the structured data matching the expected schema.",input_schema:{type:"object",properties:o.properties||o,required:o.required||[]}}}async executeNativeGemini3Stream(t){const r=t.model||this.modelName||Lg(),n=Aw(r,t.region),o=await this.createVertexGenAIClient(n);h.debug("[GoogleVertex] Using native @google/genai for Gemini 3",{model:r,hasTools:!!t.tools&&Object.keys(t.tools).length>0,project:this.projectId,location:n});const i=[],s=[{text:t.input.text??""}],a=t.input;if(a?.pdfFiles&&a.pdfFiles.length>0){h.debug(`[GoogleVertex] Processing ${a.pdfFiles.length} PDF file(s) for native stream`);for(const _e of a.pdfFiles){let Fe;typeof _e=="string"?Qo.existsSync(_e)?Fe=Qo.readFileSync(_e):Fe=Buffer.from(_e,"base64"):Fe=_e;const Y=Fe.toString("base64");s.push({inlineData:{mimeType:"application/pdf",data:Y}})}}if(await vY(s,a?.nativeAudioFiles,"[GoogleVertex]"),a?.images&&a.images.length>0){h.debug(`[GoogleVertex] Processing ${a.images.length} image(s) for native stream`);for(const _e of a.images){const Fe=rk(_e);let Y,X="image/jpeg";if(typeof Fe=="string")if(Qo.existsSync(Fe)){Y=Qo.readFileSync(Fe);const W=lk(Fe);X=W.startsWith("image/")?W:this.detectImageType(Y)}else if(Fe.startsWith("data:")){const W=Fe.match(/^data:([^;]+);base64,(.+)$/);if(W)X=W[1],Y=Buffer.from(W[2],"base64");else continue}else if(Fe.startsWith("http://")||Fe.startsWith("https://"))try{const W=await fetch(Fe);if(!W.ok){h.warn(`[GoogleVertex] Image fetch failed: ${W.status} ${W.statusText}, skipping`,{url:Xt(Fe)});continue}const te=await W.arrayBuffer();Y=Buffer.from(te);const me=W.headers.get("content-type");me&&me.startsWith("image/")&&(X=me.split(";")[0])}catch(W){h.warn(`[GoogleVertex] Image URL fetch threw, skipping: ${W instanceof Error?W.message:String(W)}`,{url:Xt(Fe)});continue}else Y=Buffer.from(Fe,"base64"),X=this.detectImageType(Y);else Y=Fe,X=this.detectImageType(Y);const ke=Y.toString("base64");s.push({inlineData:{mimeType:X,data:ke}})}}await wY(s,a?.nativeVideoFiles,"vertex",r,"[GoogleVertex]"),xO(i,t.conversationMessages),i.push({role:"user",parts:s});let l;const c=new Wv;let u;if(t.tools&&Object.keys(t.tools).length>0&&!t.disableTools){const _e=Xv(t.tools,"functionDeclarations");u=_e,l=_e.toolsConfig;for(const[Fe,Y]of _e.executeMap)c.set(Fe,Y);h.debug("[GoogleVertex] Converted tools for native SDK",{toolCount:_e.toolsConfig[0].functionDeclarations.length,toolNames:_e.toolsConfig[0].functionDeclarations.map(Fe=>Fe.name)})}const d=t;let p=!1;if(d.schema&&l){p=!0;const _e=qo(d.schema,"openApi3"),Fe=Kn(_e);Fe.$schema&&delete Fe.$schema;const Y=ea(Fe),X=l[0]?.functionDeclarations||[];X.push({name:"final_result",description:"Return the final structured result. You MUST call this tool when you have gathered all information and are ready to provide the final answer. The arguments should contain the structured data matching the expected schema.",parametersJsonSchema:Y}),l=[{functionDeclarations:X}],h.debug("[GoogleVertex] Added final_result tool for structured output with tools (stream)",{schemaKeys:Object.keys(Y),totalTools:X.length})}const m=Ac(this.providerName,r,{temperature:t.temperature??1,...t.topP!==void 0&&{topP:t.topP}},"vertex.gemini"),f={...m.temperature!==void 0&&{temperature:m.temperature},maxOutputTokens:t.maxTokens};rY(r)&&(f.maxOutputTokens&&f.maxOutputTokens>Pa&&(h.warn(`[GoogleVertex] Capping maxOutputTokens from ${f.maxOutputTokens} to ${Pa} for ${r}`),f.maxOutputTokens=Pa),f.maxOutputTokens||(f.maxOutputTokens=Pa)),m.topP!==void 0&&(f.topP=m.topP),t.topK!==void 0&&(f.topK=t.topK),t.stopSequences&&t.stopSequences.length>0&&(f.stopSequences=t.stopSequences),l&&(f.tools=l);let g=t.systemPrompt||"";p&&(g=g+`
|
|
1114
1114
|
|
|
1115
1115
|
IMPORTANT: When you have gathered all necessary information and are ready to provide your final answer, you MUST call the 'final_result' tool with the structured data. Do not return the final answer as plain text - always use the final_result tool.`),g&&(f.systemInstruction=g);const y=mY(t.thinkingConfig,r);if(y&&(f.thinkingConfig=y),(d.output?.format==="json"||d.schema)&&!p&&!l&&(f.responseMimeType="application/json",d.schema)){const _e=qo(d.schema,"openApi3"),Fe=Kn(_e);Fe.$schema&&delete Fe.$schema;const Y=ea(Fe);Ng(Y),f.responseSchema=Y,h.debug("[GoogleVertex] Added responseSchema for JSON output (stream)",{schemaKeys:Object.keys(Y)})}const v=Date.now(),T=t.maxSteps||ts,b=Number.isFinite(T)&&T>0?Math.min(Math.floor(T),100):Math.min(ts,100),S=[...i];let k="",A;const x=[],P=[];let C;const R=Hv(jd("vertex",r));let O=!1,U=0,M=0,D=0,$=0;const B=[],q=kc(t.timeout)??hE,L=Yh(t.toolTimeoutMs),j=t.turnTimeoutMs??q,G=new AbortController,J=()=>G.abort();t.abortSignal?.addEventListener("abort",J);const K=jv({turnTimeoutMs:t.turnTimeoutMs,defaultTurnTimeoutMs:q,stallTimeoutMs:t.stallTimeoutMs,wrapupTimeLeadMs:t.wrapupTimeLeadMs,onDeadline:_e=>{h.warn(_e==="timeout"?`[GoogleVertex] Native Gemini turn exceeded its ${j}ms time budget \u2014 aborting`:`[GoogleVertex] Native Gemini turn made no progress for ${t.stallTimeoutMs}ms \u2014 aborting`),G.abort()}}),de=G.signal;t.abortSignal?.aborted&&G.abort();let oe=!1,ae=!1,ge=!1,be=0;try{const _e=IO({providerLabel:"GoogleVertex",maxSteps:b,toolFailureBreaker:{maxRetries:Zh,consecutive:!0,classifyResultFailure:me=>z2(me)??void 0},liveTools:t.tools??{},toolGuards:{toolTimeoutMs:L,abortSignal:de,onProgress:()=>K.noteProgress()},...u?{declarations:u}:{},...p?{finalResultToolName:"final_result",onTerminalResult:me=>{try{C=JSON.parse(me)}catch{}}}:{},enableMalformedRetry:!0,buildMalformedRetryNote:(me,Te)=>(this.emitTurnEvent({phase:"malformed-retry",step:Te+1,maxSteps:b}),[...me,{role:"user",parts:[{text:"Your previous function call was malformed and could not be parsed. Re-issue it as a single valid function call, or answer in plain text."}]}]),collectStep:(me,Te)=>L3t(me,Te,{onProgress:()=>K.noteProgress(),onUsage:(pe,ie)=>R.noteUsage(pe,ie),onUsageDelta:(pe,ie)=>{pe==="input"?U+=ie:pe==="output"?M+=ie:pe==="cacheRead"?D+=ie:$+=ie}}),planReclaim:me=>{if(!R.shouldStop())return;const Te=[...me];return D3t(Te,r,R.projectedNextPromptTokens)?(R.resetAfterReclaim(),{conversation:Te}):(O=!0,h.warn(`[GoogleVertex] Gemini turn stopped by the context guard: projected prompt ~${R.projectedNextPromptTokens} tokens >= threshold ${R.thresholdTokens} \u2014 synthesizing a final answer.`),{stop:!0})},buildRequest:me=>({model:r,contents:me,config:{...f,...l?{tools:l}:{}}}),sendStep:async(me,Te)=>{K.noteProgress();const pe=me;return o.models.generateContentStream({model:pe.model,contents:pe.contents,config:{...pe.config??{},abortSignal:Te}})}}),Fe={..._e,buildStepRequest:(me,Te)=>(be=Te+1,_e.buildStepRequest(me,Te)),buildToolResultMessages:(me,Te,pe,ie)=>{const ce=_e.buildToolResultMessages(me,Te,pe,ie);if(K.shouldNudgeWrapup()){const H=ce[ce.length-1];H&&Array.isArray(H.parts)&&H.parts.push({text:Vv(p)})}const I=kO(Te.raw.rawResponseParts);It(this.handleToolExecutionStorage(pe.map((H,ve)=>({toolName:H.name,args:H.args,...ve===0&&I?{thoughtSignature:I}:{},stepIndex:ie+1})),pe.map(H=>({toolName:H.name,output:H.output,stepIndex:ie+1})),t,new Date),Qh,"tool storage write timed out").catch(H=>{h.warn("[GoogleVertex] Failed to store native Gemini stream tool executions",{error:H instanceof Error?H.message:String(H)})});try{const H=ce[ce.length-1];R.noteAppendedChars(JSON.stringify(H?.parts??[]).length)}catch{}return ce}},{stream:Y,resultPromise:X}=tp(Fe,S,{tools:SO(u,t.tools,{toolTimeoutMs:L,abortSignal:de,onProgress:()=>K.noteProgress()}),abortSignal:de,toolTimeoutMs:L}),ke=(async()=>{for await(const me of Y)me.content&&B.push(me.content)})();let W,te;try{W=await X}catch(me){te=me}if(await ug(ke,"GoogleVertex"),te!==void 0)if(de.aborted||Om(te))oe=!0;else throw h.error("[GoogleVertex] Native SDK error",te),this.handleProviderError(te);if(W){k=W.text,A=W.rawStopReason??A;for(const me of W.toolCalls)x.push({toolName:me.name,args:me.args});for(const me of W.toolExecutions)P.push({name:me.name,input:me.input,output:me.output});S.length=0,S.push(...W.conversation)}if(de.aborted&&(oe=!0),!k&&(be>=b||oe||O)){ae=be>=b&&!oe;const me=x.filter(Te=>Te.toolName!=="final_result").length;if(B.length>0)h.warn(O?"[GoogleVertex] Tool call loop stopped by the context guard; returning text already gathered from prior steps.":`[GoogleVertex] Tool call loop terminated after reaching maxSteps (${b}); returning text already gathered from prior steps.`);else if(oe)h.warn(`[GoogleVertex] Tool call loop ended mid-turn (${K.timedOut?"turn time limit":K.stalled?"stall watchdog":"caller abort"}); returning an honest terminal message.`),k=this.buildLoopExitMessage({turnClock:K,wasAborted:oe,stallTimeoutMs:t.stallTimeoutMs,maxSteps:b,toolCallCount:me});else{h.warn(O?"[GoogleVertex] Tool call loop stopped by the context guard with no text; synthesizing a final answer with tools disabled.":`[GoogleVertex] Tool call loop terminated after reaching maxSteps (${b}) with no text; synthesizing a final answer with tools disabled.`);const Te=await this.synthesizeFinalAnswerWithoutTools(o,r,f,S,p,kc(t.timeout)??hE,de);Te.text?(ge=!0,k=Te.text,B.push(Te.text),U+=Te.inputTokens,M+=Te.outputTokens,$+=Te.reasoningTokens??0,Te.finishReason&&(A=Te.finishReason)):k=O?Wl(me):Dm(b,me)}}}finally{K.dispose(),t.abortSignal?.removeEventListener("abort",J)}const Ce=ae&&!ge?"tool-calls":mg(A),ye=ep({timedOut:K.timedOut,stalled:K.stalled,wasAborted:oe,cappedWithoutAnswer:ae&&!ge,contextCappedWithoutAnswer:O&&!ge,finishReason:Ce});ye!=="completed"&&this.emitTurnEvent({phase:ye,step:be,maxSteps:b,toolCallCount:x.filter(_e=>_e.toolName!=="final_result").length,elapsedMs:K.elapsedMs()});const Ne=Date.now()-v,xe=C?[k]:B.length>0?B:[k];async function*le(){for(const _e of xe)_e.length>0&&(yield{content:_e})}const Oe=x.filter(_e=>_e.toolName!=="final_result"),Ie=P.filter(_e=>_e.name!=="final_result"),Ge=Math.max(0,U-D),je={stream:le(),provider:this.providerName,model:r,finishReason:Ce,stopReason:ye,rawFinishReason:A,usage:{input:Ge,output:M+$,total:Ge+D+M+$,...D>0&&{cacheReadTokens:D},...$>0&&{reasoning:$}},toolCalls:Oe.map(_e=>({toolName:_e.toolName,args:_e.args})),toolsUsed:Oe.map(_e=>_e.toolName),toolExecutions:Bd(Ie),metadata:{streamId:`native-vertex-${Date.now()}`,startTime:v,responseTime:Ne,totalToolExecutions:Oe.length,stopReason:ye,rawFinishReason:A,stepsUsed:be}};return C&&(je.structuredOutput=C),je}resolveNativeGenerateText(t){return t.input?.text!==void 0&&t.input.text!==t.prompt?t.input.text:t.input?.text||t.prompt||"Please respond."}async executeNativeGemini3Generate(t){const r=t.model||this.modelName||Lg(),n=Aw(r,t.region),o=await this.createVertexGenAIClient(n);h.debug("[GoogleVertex] Using native @google/genai for Gemini 3 generate",{model:r,project:this.projectId,location:n});const i=this.resolveNativeGenerateText(t),s=[],a=[{text:i}],l=t.input;if(l?.pdfFiles&&l.pdfFiles.length>0){h.debug(`[GoogleVertex] Processing ${l.pdfFiles.length} PDF file(s) for native generate`);for(const je of l.pdfFiles){let _e;typeof je=="string"?Qo.existsSync(je)?_e=Qo.readFileSync(je):_e=Buffer.from(je,"base64"):_e=je;const Fe=_e.toString("base64");a.push({inlineData:{mimeType:"application/pdf",data:Fe}})}}if(await vY(a,l?.nativeAudioFiles,"[GoogleVertex]"),l?.images&&l.images.length>0){h.debug(`[GoogleVertex] Processing ${l.images.length} image(s) for native generate`);for(const je of l.images){const _e=rk(je);let Fe,Y="image/jpeg";if(typeof _e=="string")if(Qo.existsSync(_e)){Fe=Qo.readFileSync(_e);const ke=lk(_e);Y=ke.startsWith("image/")?ke:this.detectImageType(Fe)}else if(_e.startsWith("data:")){const ke=_e.match(/^data:([^;]+);base64,(.+)$/);if(ke)Y=ke[1],Fe=Buffer.from(ke[2],"base64");else continue}else if(_e.startsWith("http://")||_e.startsWith("https://"))try{const ke=await fetch(_e);if(!ke.ok){h.warn(`[GoogleVertex] Image fetch failed: ${ke.status} ${ke.statusText}, skipping`,{url:Xt(_e)});continue}const W=await ke.arrayBuffer();Fe=Buffer.from(W);const te=ke.headers.get("content-type");te&&te.startsWith("image/")&&(Y=te.split(";")[0])}catch(ke){h.warn(`[GoogleVertex] Image URL fetch threw, skipping: ${ke instanceof Error?ke.message:String(ke)}`,{url:Xt(_e)});continue}else Fe=Buffer.from(_e,"base64"),Y=this.detectImageType(Fe);else Fe=_e,Y=this.detectImageType(Fe);const X=Fe.toString("base64");a.push({inlineData:{mimeType:Y,data:X}})}}await wY(a,l?.nativeVideoFiles,"vertex",r,"[GoogleVertex]"),xO(s,t.conversationMessages),s.push({role:"user",parts:a});const c=t.disableTools?{}:t.tools||{};let u;const d=new Wv;let p;if(Object.keys(c).length>0){const je=Xv(c,"functionDeclarations");p=je,u=je.toolsConfig;for(const[_e,Fe]of je.executeMap)d.set(_e,Fe);h.debug("[GoogleVertex] Converted tools for native SDK generate",{toolCount:je.toolsConfig[0].functionDeclarations.length,toolNames:je.toolsConfig[0].functionDeclarations.map(_e=>_e.name)})}let m=!1;if(t.schema&&u){m=!0;const je=qo(t.schema,"openApi3"),_e=Kn(je);_e.$schema&&delete _e.$schema;const Fe=ea(_e),Y=u[0]?.functionDeclarations||[];Y.push({name:"final_result",description:"Return the final structured result. You MUST call this tool when you have gathered all information and are ready to provide the final answer. The arguments should contain the structured data matching the expected schema.",parametersJsonSchema:Fe}),u=[{functionDeclarations:Y}],h.debug("[GoogleVertex] Added final_result tool for structured output with tools (generate)",{schemaKeys:Object.keys(Fe),totalTools:Y.length})}const f=Ac(this.providerName,r,{temperature:t.temperature??1,...t.topP!==void 0&&{topP:t.topP}},"vertex.gemini"),g={...f.temperature!==void 0&&{temperature:f.temperature},maxOutputTokens:t.maxTokens};rY(r)&&(g.maxOutputTokens&&g.maxOutputTokens>Pa&&(h.warn(`[GoogleVertex] Capping maxOutputTokens from ${g.maxOutputTokens} to ${Pa} for ${r}`),g.maxOutputTokens=Pa),g.maxOutputTokens||(g.maxOutputTokens=Pa)),f.topP!==void 0&&(g.topP=f.topP),t.topK!==void 0&&(g.topK=t.topK),t.stopSequences&&t.stopSequences.length>0&&(g.stopSequences=t.stopSequences),u&&(g.tools=u);let y=t.systemPrompt||"";m&&(y=y+`
|
|
1116
1116
|
|
|
@@ -1149,7 +1149,7 @@ Reason: ${s instanceof Error?s.message:"Unknown error"}`}}return{...t,prompt:n,i
|
|
|
1149
1149
|
|
|
1150
1150
|
`):void 0,text:o.join(`
|
|
1151
1151
|
|
|
1152
|
-
`),unmapped:i+s}}applyTurnParamsRewrite(t,r){r.tools!==void 0&&h.warn("[GoogleVertex] middleware rewrote 'tools' on the native path; tool rewrites are not applied to the native request \u2014 the original tool list was sent.");const n=this.readTurnFromPrompt(r.prompt);n.unmapped>0&&h.warn(`[GoogleVertex] middleware added ${n.unmapped} prompt item(s) the native request cannot carry (non-text user parts, assistant or tool messages); only system and user text edits are applied \u2014 those items were not sent.`);const o=typeof r.maxOutputTokens=="number"?r.maxOutputTokens:void 0,i=typeof r.temperature=="number"?r.temperature:void 0,s=typeof r.topP=="number"?r.topP:void 0;return{...t,...n.systemPrompt!==(t.systemPrompt||void 0)?{systemPrompt:n.systemPrompt}:{},...n.text!==this.vertexTurnBaselineText(t)?{input:{...t.input??{},text:n.text}}:{},...o!==t.maxTokens?{maxTokens:o}:{},...i!==t.temperature?{temperature:i}:{},...s!==t.topP?{topP:s}:{}}}excludeAutoLifecycleMiddleware(t,r){const n=t;if(!(r==="stream"||!!(n.onFinish||n.onError||n.onChunk)))return t;const i=n.middleware?.middlewareConfig?.lifecycle;return i?{...t,middleware:{...n.middleware,middlewareConfig:{...n.middleware?.middlewareConfig,lifecycle:{...i,enabled:!1}}}}:t}async executeNativeGemini3GenerateWithSchemaFallback(t,r){try{return await this.executeNativeGemini3Generate(t)}catch(n){const o=t.schema!==void 0||t.output?.format==="json",i=!t.disableTools&&Object.keys(t.tools??{}).length>0;if(o&&!i&&hIt(n))return h.warn("[GoogleVertex] responseSchema too complex for constrained decoding \u2014 retrying native generate in schema-less JSON mode",{model:r,error:n instanceof Error?n.message:String(n)}),await this.executeNativeGemini3Generate({...t,schema:void 0,output:{format:"json"}});throw n}}async runNativeGenerateWithMiddleware(t,r,n){const o=Date.now(),i=this.buildTurnPromptForMiddleware(t),s=this.providerName;let a;const l={specificationVersion:"v3",provider:s,modelId:r,supportedUrls:{},doGenerate:async f=>{const g=this.applyTurnParamsRewrite(t,f),y=await n(g);return a=y,{content:[{type:"text",text:y.content}],finishReason:{unified:y.finishReason??"stop"},usage:{inputTokens:{total:y.usage?.input??0},outputTokens:{total:y.usage?.output??0}}}},doStream:()=>{throw new Error("[GoogleVertex] doStream is not implemented on the native generate middleware model \u2014 this path only drives doGenerate.")}},c=await this.applyMiddlewareToModel(l,this.excludeAutoLifecycleMiddleware(t,"generate"));if(typeof c=="string")throw new Error("[GoogleVertex] Native generate model handle required for middleware");const u=c,d=this.buildTurnV3Params(t,i),p=await u.doGenerate(d),m=p.content.map(f=>f.type==="text"?f.text:"").join("");return a?m===a.content?a:{...a,content:m}:this.enhanceResult({content:m,provider:s,model:r,finishReason:p.finishReason.unified,usage:{input:p.usage.inputTokens.total??0,output:p.usage.outputTokens.total??0,total:(p.usage.inputTokens.total??0)+(p.usage.outputTokens.total??0)},toolCalls:[],stopReason:ep({timedOut:!1,stalled:!1,wasAborted:!1,cappedWithoutAnswer:!1,finishReason:p.finishReason.unified}),stepsUsed:0,responseTime:Date.now()-o,toolsUsed:[],toolExecutions:[],enhancedWithTools:!1},t,o)}async runNativeStreamWithMiddleware(t,r,n){const o=this.buildTurnPromptForMiddleware(t),i=this.providerName;let s;const a={specificationVersion:"v3",provider:i,modelId:r,supportedUrls:{},doGenerate:()=>{throw new Error("[GoogleVertex] doGenerate is not implemented on the native stream middleware model \u2014 this path only drives doStream.")},doStream:async g=>{const y=this.applyTurnParamsRewrite(t,g),v=await n(y);return s=v,{stream:z3t(v.stream,()=>({type:"finish",finishReason:{unified:v.finishReason??"stop"},usage:{inputTokens:{total:v.usage?.input??0},outputTokens:{total:v.usage?.output??0}}}))}}},l=await this.applyMiddlewareToModel(a,this.excludeAutoLifecycleMiddleware(t,"stream"));if(typeof l=="string")throw new Error("[GoogleVertex] Native stream model handle required for middleware");const c=l,u=this.buildTurnV3Params(t,o),{stream:d}=await c.doStream(u);let p;const m=NJr(d,g=>{p=g});if(s){const g=s;return this.preserveStreamResultAccessors(g,{...g,stream:m})}const f={stream:m,provider:i,model:r};return Object.defineProperty(f,"usage",{enumerable:!0,configurable:!0,get:()=>p?{input:p.usage.inputTokens.total??0,output:p.usage.outputTokens.total??0,total:(p.usage.inputTokens.total??0)+(p.usage.outputTokens.total??0)}:void 0}),Object.defineProperty(f,"finishReason",{enumerable:!0,configurable:!0,get:()=>p?.finishReason.unified}),f}preserveStreamResultAccessors(t,r){for(const n of["finishReason","structuredOutput","toolCalls","toolsUsed","toolExecutions","usage"]){const o=Object.getOwnPropertyDescriptor(t,n),i=o?.get;if(!i)continue;let s=!1,a;Object.defineProperty(r,n,{configurable:!0,enumerable:o.enumerable??!0,get:()=>s?a:i.call(t),set:l=>{s=!0,a=l}})}return r}attachUsageAndCostAttributes(t,r,n){if(!t||!n)return;const o=n.input??n.inputTokens??0,i=n.output??n.outputTokens??0,s=n.total??n.totalTokens??o+i,a=n.cacheReadTokens??0,l=n.cacheCreationTokens??0;o>0&&t.setAttribute("gen_ai.usage.input_tokens",o),i>0&&t.setAttribute("gen_ai.usage.output_tokens",i),s>0&&t.setAttribute("gen_ai.usage.total_tokens",s),a>0&&t.setAttribute("gen_ai.usage.cache_read_input_tokens",a),l>0&&t.setAttribute("gen_ai.usage.cache_creation_input_tokens",l);try{const c=Ls(this.providerName,r,{input:o,output:i,total:s,cacheReadTokens:a,cacheCreationTokens:l});typeof c=="number"&&c>0&&t.setAttribute("neurolink.cost",c)}catch{}}emitGenerationEnd(t,r,n,o,i,s){const a=this.neurolink?.getEventEmitter();if(!a)return;const l=r?.usage&&typeof r.usage=="object"?r.usage:{input:0,output:0,total:0};r&&typeof r=="object"&&(r._generationEndEmitted=!0),!o&&i&&typeof i=="object"&&(i._generationEndEmitted=!0),a.emit("generation:end",{provider:this.providerName,responseTime:Date.now()-n,timestamp:Date.now(),prompt:s||"",result:{content:r?.content||"",usage:l,model:t,provider:this.providerName,finishReason:o?r?.finishReason??"stop":"error"},success:o,...i?{error:i instanceof Error?i.message:String(i)}:{}})}buildLoopExitMessage(t){return fY({timedOut:t.turnClock.timedOut,stalled:t.turnClock.stalled,elapsedMs:t.turnClock.elapsedMs(),wasAborted:t.wasAborted,...t.stallTimeoutMs!==void 0?{stallTimeoutMs:t.stallTimeoutMs}:{},maxSteps:t.maxSteps,toolCallCount:t.toolCallCount})}formatProviderError(t){const r=t,n=typeof r?.status=="number"?r.status:typeof r?.statusCode=="number"?r.statusCode:void 0;return ba(t,[{match:i=>i.errorName==="TimeoutError",errorClass:ai,message:"Google Vertex AI request timed out. Consider increasing timeout or using a lighter model."},{match:i=>/PERMISSION_DENIED|UNAUTHENTICATED|Invalid API key/i.test(i.message)||n===401||n===403,errorClass:Wr,message:()=>"Google Vertex AI Permission Denied. Your Google Cloud credentials don't have permission to access Vertex AI. Required Steps: 1. Ensure your service account has Vertex AI User role 2. Check if Vertex AI API is enabled in your project 3. Verify your project ID is correct 4. Confirm your location/region has Vertex AI available"},{match:i=>/NOT_FOUND|model not found|Model not found/i.test(i.message)||n===404,errorClass:Jo,message:()=>{const i=this.getModelSuggestions(this.modelName);return`Model '${this.modelName}' is not available in region ${this.location}. Suggested alternatives: ${i}. Troubleshooting: 1. Check model name spelling and format 2. Verify model is available in your region 3. Ensure your project has access to the model 4. For Claude models, enable Anthropic integration in Google Cloud Console`}},{match:i=>/QUOTA_EXCEEDED|RATE_LIMIT_EXCEEDED|rate limit/i.test(i.message)||im(i.message,429)||n===429||n===529||/overloaded/i.test(i.message),errorClass:Qi,message:i=>{const s=typeof r?.retryDelay=="string"?r.retryDelay:/["']?retryDelay["']?\s*[:=]\s*["']?(\d+(?:\.\d+)?s)/.exec(i.message)?.[1]??void 0,a=typeof r?.requestModel=="string"?r.requestModel:this.modelName,l=typeof r?.requestRegion=="string"?r.requestRegion:Aw(a,this.location);return`Google Vertex AI rate limit / shared-capacity exhausted (429 RESOURCE_EXHAUSTED / overloaded) for model '${a}' in region '${l}'.`+(s?` Upstream suggests retrying after ${s}.`:"")+" Solutions: 1. Retry with backoff 2. Check your Vertex AI quotas in Google Cloud Console (shared-capacity 429s can occur below quota) 3. Try a different region or model 4. Request provisioned throughput for sustained load"}},{match:i=>/ECONNRESET|ENOTFOUND|ETIMEDOUT|ECONNREFUSED|network|connection/i.test(i.message),errorClass:ai,message:i=>`Connection error: ${i.message}`},{match:i=>/server error|Internal Server Error|INTERNAL|UNAVAILABLE/i.test(i.message)||[500,502,503,504].some(s=>im(i.message,s))||n!==void 0&&n>=500&&n<600,errorClass:ot,message:i=>`Google Vertex AI server error: ${i.message}. Please try again later.`},{match:i=>/INVALID_ARGUMENT/i.test(i.message),errorClass:ot,message:i=>`Google Vertex AI Invalid Request: ${i.message}. Check: 1. Request parameters are within model limits 2. Input text is properly formatted 3. Temperature and other settings are valid 4. Model supports your request type`},{match:()=>!0,errorClass:ot,message:i=>`Google Vertex AI error: ${i.message}`}],this.providerName,this.modelName)}static evictLRUCacheEntries(t){if(t.size<=mn.MAX_CACHE_SIZE)return;const r=t.size-mn.MAX_CACHE_SIZE+5;let n=0;for(const o of t.keys()){if(n>=r)break;t.delete(o),n++}h.debug("GoogleVertexProvider: Evicted LRU cache entries",{entriesRemoved:n,currentCacheSize:t.size})}static accessCacheEntry(t,r){const n=t.get(r);return n!==void 0&&(t.delete(r),t.set(r,n)),n}shouldSetMaxTokensCached(t){const r=Date.now();r-mn.maxTokensCacheTime>mn.CACHE_DURATION&&(mn.maxTokensCache.clear(),mn.maxTokensCacheTime=r);const n=mn.accessCacheEntry(mn.maxTokensCache,t);if(n!==void 0)return n;const o=!this.modelHasMaxTokensIssues(t);return mn.maxTokensCache.set(t,o),mn.evictLRUCacheEntries(mn.maxTokensCache),o}modelHasMaxTokensIssues(t){const r=Date.now(),n="google-vertex-config";if(r-mn.modelConfigCacheTime>mn.CACHE_DURATION){mn.modelConfigCache.clear();const a=pM.getInstance().getProviderConfiguration("google-vertex");mn.modelConfigCache.set(n,a),mn.modelConfigCacheTime=r}return(mn.accessCacheEntry(mn.modelConfigCache,n)?.modelBehavior?.maxTokensIssues||["gemini-2.5-flash","gemini-2.5-pro"]).some(s=>t.includes(s))}async hasAnthropicSupport(){return $3t()}registerTool(t,r,n,o){const i="GoogleVertexProvider.registerTool";try{const s={description:n,parameters:r,execute:async a=>{try{const l={...a,__context:this.toolContext};return await o(l)}catch(l){throw h.error(`${i}: Tool execution error`,{toolName:t,error:l instanceof Error?l.message:String(l)}),l}}};this.registeredTools.set(t,s),h.debug(`${i}: Tool registered`,{toolName:t,modelName:this.modelName})}catch(s){throw h.error(`${i}: Tool registration error`,{toolName:t,error:s instanceof Error?s.message:String(s)}),s}}setToolContext(t){this.toolContext={...this.toolContext,...t},h.debug("GoogleVertexProvider.setToolContext: Tool context set",{contextKeys:Object.keys(t)})}getToolContext(){return{...this.toolContext}}setToolExecutor(t){this.toolExecutor=t,h.debug("GoogleVertexProvider.setToolExecutor: Tool executor set",{hasExecutor:typeof t=="function"})}static clearCaches(){mn.modelConfigCache.clear(),mn.maxTokensCache.clear(),mn.modelConfigCacheTime=0,mn.maxTokensCacheTime=0,h.debug("GoogleVertexProvider: All caches cleared",{clearedAt:Date.now()})}static getCacheStats(){const t=Date.now();return{modelConfigCacheSize:mn.modelConfigCache.size,maxTokensCacheSize:mn.maxTokensCache.size,maxCacheSize:mn.MAX_CACHE_SIZE,cacheAge:{modelConfig:t-mn.modelConfigCacheTime,maxTokens:t-mn.maxTokensCacheTime}}}detectImageType(t){return Xx(t)}estimateTokenCount(t){return Math.ceil(t.length/4)}async executeImageGeneration(t){await Ck(t.input);const r=t.prompt||t.input?.text||"",n=t.input?.pdfFiles||[],o=t.input?.images||[],i=n.length>0,s=o.length>0;if(!r.trim()&&!i&&!s)throw new ot("Image generation requires either a prompt, PDF file, or image as input",this.providerName);let a=t.model||this.modelName||"gemini-3-pro-image-preview";i&&!a.includes("gemini-3-pro-image")&&(a="gemini-3-pro-image-preview");const l=process.env.GOOGLE_VERTEX_IMAGE_LOCATION||"global",u=D8.some(p=>a.includes(p)||p.includes(a))?l:this.location,d=Date.now();h.info("\u{1F3A8} Starting Vertex AI image generation (REST API)",{model:a,prompt:r.substring(0,100),provider:this.providerName,projectId:this.projectId,location:u,hasPdfInput:i,pdfCount:n.length,hasImageInput:s,imageCount:o.length});try{const{GoogleAuth:p}=await Promise.resolve().then(()=>(yk(),gk)),m=process.env.GOOGLE_APPLICATION_CREDENTIALS_NEUROLINK||process.env.GOOGLE_APPLICATION_CREDENTIALS,y=await(await new p({...m&&{keyFilename:m},scopes:["https://www.googleapis.com/auth/cloud-platform"]}).getClient()).getAccessToken();if(!y.token)throw new Wr("Failed to obtain access token from Google Auth",this.providerName);const v=[];if(r&&v.push({text:r}),i)for(const $ of n){let B;if(Buffer.isBuffer($))B=$.toString("base64");else if(typeof $=="string")if($.startsWith("/")||/^[a-zA-Z]:\\/.test($)||$.startsWith("./")||$.startsWith("../")||$.startsWith("..\\")||$.startsWith(".\\")){const L=om.resolve($),j=process.cwd();if(!L.startsWith(j+om.sep)&&L!==j)throw new ot("PDF file path must be within current directory for security",this.providerName);if(!Qo.existsSync(L))throw new ot(`PDF file not found: ${L}`,this.providerName);B=Qo.readFileSync(L).toString("base64")}else B=$;else{h.warn("Invalid PDF file format, skipping",{type:typeof $});continue}v.push({inlineData:{mimeType:"application/pdf",data:B}}),h.debug("Added PDF file to request",{dataLength:B.length})}if(s)for(let $=0;$<o.length;$++){const B=rk(o[$]);let q,L;if(Buffer.isBuffer(B))q=B.toString("base64"),L=this.detectImageType(B);else if(typeof B=="string")if(B.startsWith("/")||/^[a-zA-Z]:\\/.test(B)||B.startsWith("./")||B.startsWith("../")||B.startsWith("..\\")||B.startsWith(".\\")){const G=om.resolve(B);if(!Qo.existsSync(G)){h.warn(`Image file not found: ${G}, skipping`);continue}const J=Qo.readFileSync(G);q=J.toString("base64"),L=this.detectImageType(J)}else if(B.startsWith("data:")){const G=B.match(/^data:([^;]+);base64,(.+)$/);if(G)L=G[1],q=G[2];else{h.warn("Invalid data URL format, skipping image",{index:$});continue}}else if(B.startsWith("http://")||B.startsWith("https://"))try{const G=await fetch(B);if(!G.ok){h.warn(`Image fetch failed: ${G.status} ${G.statusText}, skipping`,{url:Xt(B),index:$});continue}const J=await G.arrayBuffer(),K=Buffer.from(J);q=K.toString("base64");const de=G.headers.get("content-type");L=de&&de.startsWith("image/")?de.split(";")[0]:this.detectImageType(K)}catch(G){h.warn(`Image URL fetch threw, skipping: ${G instanceof Error?G.message:String(G)}`,{url:Xt(B),index:$});continue}else{q=B;const G=Buffer.from(q,"base64");L=this.detectImageType(G)}else{h.warn("Invalid image format, skipping",{type:typeof B,index:$});continue}v.push({inlineData:{mimeType:L,data:q}}),h.debug("Added image to request",{index:$,mimeType:L,dataLength:q.length})}const T={contents:[{role:"user",parts:v}],generation_config:{response_modalities:["TEXT","IMAGE"],temperature:t.temperature||.7,candidate_count:1}};let b;u==="global"?b=`https://aiplatform.googleapis.com/v1/projects/${this.projectId}/locations/global/publishers/google/models/${a}:generateContent`:b=`https://${u}-aiplatform.googleapis.com/v1/projects/${this.projectId}/locations/${u}/publishers/google/models/${a}:generateContent`,h.debug("Making REST API call to Vertex AI",{url:b,model:a,hasAccessToken:!!y.token});const S=12e4,k=fetch(b,{method:"POST",headers:{Authorization:`Bearer ${y.token}`,"Content-Type":"application/json"},body:JSON.stringify(T)}),A=new Promise(($,B)=>{setTimeout(()=>{B(new ku(`Vertex AI image generation timed out after ${S}ms`,S))},S)}),x=await Promise.race([k,A]);if(!x.ok){const $=await x.text();throw new ot(`Vertex AI API error (${x.status}): ${$}`,this.providerName)}const C=(await x.json()).candidates?.[0];if(!C?.content?.parts)throw new ot("No content parts in Vertex AI response",this.providerName);const R=C.content.parts.find($=>($.inlineData||$.inline_data)&&($.inlineData&&$.inlineData.mimeType||$.inline_data&&$.inline_data.mime_type)&&($.inlineData&&$.inlineData.mimeType?.startsWith("image/")||$.inline_data&&$.inline_data.mime_type?.startsWith("image/")));if(!R){const $=C.content.parts.map(B=>B.text).filter(B=>!!B).join("");if($){h.info("[GoogleVertex] Image-gen route returned text fallback",{model:a,length:$.length});const B={content:$,provider:this.providerName,model:a,usage:{input:this.estimateTokenCount(r),output:this.estimateTokenCount($),total:this.estimateTokenCount(r)+this.estimateTokenCount($)}};return await this.enhanceResult(B,t,d)}throw new ot(`Image generation completed but no image data was returned. Model: ${a}`,this.providerName)}const O=R.inlineData?.data||R.inline_data?.data,U=R.inlineData?.mimeType||R.inline_data?.mime_type,M=U||"image/png";if(!O)throw new ot("Image part found but no data available",this.providerName);h.info("Image generation successful",{model:a,mimeType:M,dataLength:O.length,responseTime:Date.now()-d});const D={content:`Generated image using ${a} (${M})`,imageOutput:{base64:O,...U?{mimeType:U}:{}},provider:this.providerName,model:a,usage:{input:this.estimateTokenCount(r),output:0,total:this.estimateTokenCount(r)}};return await this.enhanceResult(D,t,d)}catch(p){throw h.error("Image generation failed",{error:p instanceof Error?p.message:String(p),model:a,prompt:r.substring(0,100)}),this.handleProviderError(p)}}getModelSuggestions(t){const r={google:["gemini-3-pro-preview-11-2025","gemini-3-pro-latest","gemini-3-pro-preview","gemini-2.5-pro","gemini-2.5-flash","gemini-2.5-flash-lite","gemini-2.0-flash-001","gemini-2.0-flash-lite"],claude:["claude-sonnet-4-5@20250929","claude-sonnet-4@20250514","claude-opus-4@20250514","claude-3-5-sonnet-20241022","claude-3-5-haiku-20241022","claude-3-sonnet-20240229","claude-3-haiku-20240307","claude-3-opus-20240229"]},n=(t??"").split("@")[0].toLowerCase(),o=l=>l.split("@")[0].toLowerCase()!==n,i=r.google.filter(o),s=r.claude.filter(o);let a=`
|
|
1152
|
+
`),unmapped:i+s}}applyTurnParamsRewrite(t,r){r.tools!==void 0&&h.warn("[GoogleVertex] middleware rewrote 'tools' on the native path; tool rewrites are not applied to the native request \u2014 the original tool list was sent.");const n=this.readTurnFromPrompt(r.prompt);n.unmapped>0&&h.warn(`[GoogleVertex] middleware added ${n.unmapped} prompt item(s) the native request cannot carry (non-text user parts, assistant or tool messages); only system and user text edits are applied \u2014 those items were not sent.`);const o=typeof r.maxOutputTokens=="number"?r.maxOutputTokens:void 0,i=typeof r.temperature=="number"?r.temperature:void 0,s=typeof r.topP=="number"?r.topP:void 0;return{...t,...n.systemPrompt!==(t.systemPrompt||void 0)?{systemPrompt:n.systemPrompt}:{},...n.text!==this.vertexTurnBaselineText(t)?{input:{...t.input??{},text:n.text}}:{},...o!==t.maxTokens?{maxTokens:o}:{},...i!==t.temperature?{temperature:i}:{},...s!==t.topP?{topP:s}:{}}}excludeAutoLifecycleMiddleware(t,r){const n=t;if(!(r==="stream"||!!(n.onFinish||n.onError||n.onChunk)))return t;const i=n.middleware?.middlewareConfig?.lifecycle;return i?{...t,middleware:{...n.middleware,middlewareConfig:{...n.middleware?.middlewareConfig,lifecycle:{...i,enabled:!1}}}}:t}async executeNativeGemini3GenerateWithSchemaFallback(t,r){try{return await this.executeNativeGemini3Generate(t)}catch(n){const o=t.schema!==void 0||t.output?.format==="json",i=!t.disableTools&&Object.keys(t.tools??{}).length>0;if(o&&!i&&hIt(n))return h.warn("[GoogleVertex] responseSchema too complex for constrained decoding \u2014 retrying native generate in schema-less JSON mode",{model:r,error:n instanceof Error?n.message:String(n)}),await this.executeNativeGemini3Generate({...t,schema:void 0,output:{format:"json"}});throw n}}async runNativeGenerateWithMiddleware(t,r,n){const o=Date.now(),i=this.buildTurnPromptForMiddleware(t),s=this.providerName;let a;const l={specificationVersion:"v3",provider:s,modelId:r,supportedUrls:{},doGenerate:async f=>{const g=this.applyTurnParamsRewrite(t,f),y=await n(g);return a=y,{content:[{type:"text",text:y.content}],finishReason:{unified:y.finishReason??"stop"},usage:{inputTokens:{total:y.usage?.input??0},outputTokens:{total:y.usage?.output??0}}}},doStream:()=>{throw new Error("[GoogleVertex] doStream is not implemented on the native generate middleware model \u2014 this path only drives doGenerate.")}},c=await this.applyMiddlewareToModel(l,this.excludeAutoLifecycleMiddleware(t,"generate"));if(typeof c=="string")throw new Error("[GoogleVertex] Native generate model handle required for middleware");const u=c,d=this.buildTurnV3Params(t,i),p=await u.doGenerate(d),m=p.content.map(f=>f.type==="text"?f.text:"").join("");return a?m===a.content?a:{...a,content:m}:this.enhanceResult({content:m,provider:s,model:r,finishReason:p.finishReason.unified,usage:{input:p.usage.inputTokens.total??0,output:p.usage.outputTokens.total??0,total:(p.usage.inputTokens.total??0)+(p.usage.outputTokens.total??0)},toolCalls:[],stopReason:ep({timedOut:!1,stalled:!1,wasAborted:!1,cappedWithoutAnswer:!1,finishReason:p.finishReason.unified}),stepsUsed:0,responseTime:Date.now()-o,toolsUsed:[],toolExecutions:[],enhancedWithTools:!1},t,o)}async runNativeStreamWithMiddleware(t,r,n){const o=this.buildTurnPromptForMiddleware(t),i=this.providerName;let s;const a={specificationVersion:"v3",provider:i,modelId:r,supportedUrls:{},doGenerate:()=>{throw new Error("[GoogleVertex] doGenerate is not implemented on the native stream middleware model \u2014 this path only drives doStream.")},doStream:async g=>{const y=this.applyTurnParamsRewrite(t,g),v=await n(y);return s=v,{stream:z3t(v.stream,()=>({type:"finish",finishReason:{unified:v.finishReason??"stop"},usage:{inputTokens:{total:v.usage?.input??0},outputTokens:{total:v.usage?.output??0}}}))}}},l=await this.applyMiddlewareToModel(a,this.excludeAutoLifecycleMiddleware(t,"stream"));if(typeof l=="string")throw new Error("[GoogleVertex] Native stream model handle required for middleware");const c=l,u=this.buildTurnV3Params(t,o),{stream:d}=await c.doStream(u);let p;const m=NJr(d,g=>{p=g});if(s){const g=s;return this.preserveStreamResultAccessors(g,{...g,stream:m})}const f={stream:m,provider:i,model:r};return Object.defineProperty(f,"usage",{enumerable:!0,configurable:!0,get:()=>p?{input:p.usage.inputTokens.total??0,output:p.usage.outputTokens.total??0,total:(p.usage.inputTokens.total??0)+(p.usage.outputTokens.total??0)}:void 0}),Object.defineProperty(f,"finishReason",{enumerable:!0,configurable:!0,get:()=>p?.finishReason.unified}),f}preserveStreamResultAccessors(t,r){for(const n of["finishReason","structuredOutput","toolCalls","toolsUsed","toolExecutions","usage"]){const o=Object.getOwnPropertyDescriptor(t,n),i=o?.get;if(!i)continue;let s=!1,a;Object.defineProperty(r,n,{configurable:!0,enumerable:o.enumerable??!0,get:()=>s?a:i.call(t),set:l=>{s=!0,a=l}})}return r}attachUsageAndCostAttributes(t,r,n){if(!t||!n)return;const o=n.input??n.inputTokens??0,i=n.output??n.outputTokens??0,s=n.total??n.totalTokens??o+i,a=n.cacheReadTokens??0,l=n.cacheCreationTokens??0;o>0&&t.setAttribute("gen_ai.usage.input_tokens",o),i>0&&t.setAttribute("gen_ai.usage.output_tokens",i),s>0&&t.setAttribute("gen_ai.usage.total_tokens",s),a>0&&t.setAttribute("gen_ai.usage.cache_read_input_tokens",a),l>0&&t.setAttribute("gen_ai.usage.cache_creation_input_tokens",l);try{const c=Ls(this.providerName,r,{input:o,output:i,total:s,cacheReadTokens:a,cacheCreationTokens:l});typeof c=="number"&&c>0&&t.setAttribute("neurolink.cost",c)}catch{}}emitGenerationEnd(t,r,n,o,i,s){const a=this.neurolink?.getEventEmitter();if(!a)return;const l=r?.usage&&typeof r.usage=="object"?r.usage:{input:0,output:0,total:0};r&&typeof r=="object"&&(r._generationEndEmitted=!0),!o&&i&&typeof i=="object"&&(i._generationEndEmitted=!0),a.emit("generation:end",{provider:this.providerName,responseTime:Date.now()-n,timestamp:Date.now(),prompt:s||"",result:{content:r?.content||"",usage:l,model:t,provider:this.providerName,finishReason:o?r?.finishReason??"stop":"error"},success:o,...i?{error:i instanceof Error?i.message:String(i)}:{}})}buildLoopExitMessage(t){return fY({timedOut:t.turnClock.timedOut,stalled:t.turnClock.stalled,elapsedMs:t.turnClock.elapsedMs(),wasAborted:t.wasAborted,...t.stallTimeoutMs!==void 0?{stallTimeoutMs:t.stallTimeoutMs}:{},maxSteps:t.maxSteps,toolCallCount:t.toolCallCount})}formatProviderError(t){const r=t,n=typeof r?.status=="number"?r.status:typeof r?.statusCode=="number"?r.statusCode:void 0;return ba(t,[{match:i=>i.errorName==="TimeoutError",errorClass:ai,message:"Google Vertex AI request timed out. Consider increasing timeout or using a lighter model."},{match:i=>/PERMISSION_DENIED|UNAUTHENTICATED|Invalid API key/i.test(i.message)||n===401||n===403,errorClass:Wr,message:()=>"Google Vertex AI Permission Denied. Your Google Cloud credentials don't have permission to access Vertex AI. Required Steps: 1. Ensure your service account has Vertex AI User role 2. Check if Vertex AI API is enabled in your project 3. Verify your project ID is correct 4. Confirm your location/region has Vertex AI available"},{match:i=>/NOT_FOUND|model not found|Model not found/i.test(i.message)||n===404,errorClass:Jo,message:()=>{const i=this.getModelSuggestions(this.modelName);return`Model '${this.modelName}' is not available in region ${this.location}. Suggested alternatives: ${i}. Troubleshooting: 1. Check model name spelling and format 2. Verify model is available in your region 3. Ensure your project has access to the model 4. For Claude models, enable Anthropic integration in Google Cloud Console`}},{match:i=>/QUOTA_EXCEEDED|RATE_LIMIT_EXCEEDED|rate limit/i.test(i.message)||im(i.message,429)||n===429||n===529||/overloaded/i.test(i.message),errorClass:Qi,message:i=>{const s=typeof r?.retryDelay=="string"?r.retryDelay:/["']?retryDelay["']?\s*[:=]\s*["']?(\d+(?:\.\d+)?s)/.exec(i.message)?.[1]??void 0,a=typeof r?.requestModel=="string"?r.requestModel:this.modelName,l=typeof r?.requestRegion=="string"?r.requestRegion:Aw(a,this.location);return`Google Vertex AI rate limit / shared-capacity exhausted (429 RESOURCE_EXHAUSTED / overloaded) for model '${a}' in region '${l}'.`+(s?` Upstream suggests retrying after ${s}.`:"")+" Solutions: 1. Retry with backoff 2. Check your Vertex AI quotas in Google Cloud Console (shared-capacity 429s can occur below quota) 3. Try a different region or model 4. Request provisioned throughput for sustained load"}},{match:i=>/ECONNRESET|ENOTFOUND|ETIMEDOUT|ECONNREFUSED|network|connection/i.test(i.message),errorClass:ai,message:i=>`Connection error: ${i.message}`},{match:i=>/server error|Internal Server Error|INTERNAL|UNAVAILABLE/i.test(i.message)||[500,502,503,504].some(s=>im(i.message,s))||n!==void 0&&n>=500&&n<600,errorClass:nt,message:i=>`Google Vertex AI server error: ${i.message}. Please try again later.`},{match:i=>/INVALID_ARGUMENT/i.test(i.message),errorClass:nt,message:i=>`Google Vertex AI Invalid Request: ${i.message}. Check: 1. Request parameters are within model limits 2. Input text is properly formatted 3. Temperature and other settings are valid 4. Model supports your request type`},{match:()=>!0,errorClass:nt,message:i=>`Google Vertex AI error: ${i.message}`}],this.providerName,this.modelName)}static evictLRUCacheEntries(t){if(t.size<=mn.MAX_CACHE_SIZE)return;const r=t.size-mn.MAX_CACHE_SIZE+5;let n=0;for(const o of t.keys()){if(n>=r)break;t.delete(o),n++}h.debug("GoogleVertexProvider: Evicted LRU cache entries",{entriesRemoved:n,currentCacheSize:t.size})}static accessCacheEntry(t,r){const n=t.get(r);return n!==void 0&&(t.delete(r),t.set(r,n)),n}shouldSetMaxTokensCached(t){const r=Date.now();r-mn.maxTokensCacheTime>mn.CACHE_DURATION&&(mn.maxTokensCache.clear(),mn.maxTokensCacheTime=r);const n=mn.accessCacheEntry(mn.maxTokensCache,t);if(n!==void 0)return n;const o=!this.modelHasMaxTokensIssues(t);return mn.maxTokensCache.set(t,o),mn.evictLRUCacheEntries(mn.maxTokensCache),o}modelHasMaxTokensIssues(t){const r=Date.now(),n="google-vertex-config";if(r-mn.modelConfigCacheTime>mn.CACHE_DURATION){mn.modelConfigCache.clear();const a=pM.getInstance().getProviderConfiguration("google-vertex");mn.modelConfigCache.set(n,a),mn.modelConfigCacheTime=r}return(mn.accessCacheEntry(mn.modelConfigCache,n)?.modelBehavior?.maxTokensIssues||["gemini-2.5-flash","gemini-2.5-pro"]).some(s=>t.includes(s))}async hasAnthropicSupport(){return $3t()}registerTool(t,r,n,o){const i="GoogleVertexProvider.registerTool";try{const s={description:n,parameters:r,execute:async a=>{try{const l={...a,__context:this.toolContext};return await o(l)}catch(l){throw h.error(`${i}: Tool execution error`,{toolName:t,error:l instanceof Error?l.message:String(l)}),l}}};this.registeredTools.set(t,s),h.debug(`${i}: Tool registered`,{toolName:t,modelName:this.modelName})}catch(s){throw h.error(`${i}: Tool registration error`,{toolName:t,error:s instanceof Error?s.message:String(s)}),s}}setToolContext(t){this.toolContext={...this.toolContext,...t},h.debug("GoogleVertexProvider.setToolContext: Tool context set",{contextKeys:Object.keys(t)})}getToolContext(){return{...this.toolContext}}setToolExecutor(t){this.toolExecutor=t,h.debug("GoogleVertexProvider.setToolExecutor: Tool executor set",{hasExecutor:typeof t=="function"})}static clearCaches(){mn.modelConfigCache.clear(),mn.maxTokensCache.clear(),mn.modelConfigCacheTime=0,mn.maxTokensCacheTime=0,h.debug("GoogleVertexProvider: All caches cleared",{clearedAt:Date.now()})}static getCacheStats(){const t=Date.now();return{modelConfigCacheSize:mn.modelConfigCache.size,maxTokensCacheSize:mn.maxTokensCache.size,maxCacheSize:mn.MAX_CACHE_SIZE,cacheAge:{modelConfig:t-mn.modelConfigCacheTime,maxTokens:t-mn.maxTokensCacheTime}}}detectImageType(t){return Xx(t)}estimateTokenCount(t){return Math.ceil(t.length/4)}async executeImageGeneration(t){await Ck(t.input);const r=t.prompt||t.input?.text||"",n=t.input?.pdfFiles||[],o=t.input?.images||[],i=n.length>0,s=o.length>0;if(!r.trim()&&!i&&!s)throw new nt("Image generation requires either a prompt, PDF file, or image as input",this.providerName);let a=t.model||this.modelName||"gemini-3-pro-image-preview";i&&!a.includes("gemini-3-pro-image")&&(a="gemini-3-pro-image-preview");const l=process.env.GOOGLE_VERTEX_IMAGE_LOCATION||"global",u=D8.some(p=>a.includes(p)||p.includes(a))?l:this.location,d=Date.now();h.info("\u{1F3A8} Starting Vertex AI image generation (REST API)",{model:a,prompt:r.substring(0,100),provider:this.providerName,projectId:this.projectId,location:u,hasPdfInput:i,pdfCount:n.length,hasImageInput:s,imageCount:o.length});try{const{GoogleAuth:p}=await Promise.resolve().then(()=>(yk(),gk)),m=process.env.GOOGLE_APPLICATION_CREDENTIALS_NEUROLINK||process.env.GOOGLE_APPLICATION_CREDENTIALS,y=await(await new p({...m&&{keyFilename:m},scopes:["https://www.googleapis.com/auth/cloud-platform"]}).getClient()).getAccessToken();if(!y.token)throw new Wr("Failed to obtain access token from Google Auth",this.providerName);const v=[];if(r&&v.push({text:r}),i)for(const $ of n){let B;if(Buffer.isBuffer($))B=$.toString("base64");else if(typeof $=="string")if($.startsWith("/")||/^[a-zA-Z]:\\/.test($)||$.startsWith("./")||$.startsWith("../")||$.startsWith("..\\")||$.startsWith(".\\")){const L=om.resolve($),j=process.cwd();if(!L.startsWith(j+om.sep)&&L!==j)throw new nt("PDF file path must be within current directory for security",this.providerName);if(!Qo.existsSync(L))throw new nt(`PDF file not found: ${L}`,this.providerName);B=Qo.readFileSync(L).toString("base64")}else B=$;else{h.warn("Invalid PDF file format, skipping",{type:typeof $});continue}v.push({inlineData:{mimeType:"application/pdf",data:B}}),h.debug("Added PDF file to request",{dataLength:B.length})}if(s)for(let $=0;$<o.length;$++){const B=rk(o[$]);let q,L;if(Buffer.isBuffer(B))q=B.toString("base64"),L=this.detectImageType(B);else if(typeof B=="string")if(B.startsWith("/")||/^[a-zA-Z]:\\/.test(B)||B.startsWith("./")||B.startsWith("../")||B.startsWith("..\\")||B.startsWith(".\\")){const G=om.resolve(B);if(!Qo.existsSync(G)){h.warn(`Image file not found: ${G}, skipping`);continue}const J=Qo.readFileSync(G);q=J.toString("base64"),L=this.detectImageType(J)}else if(B.startsWith("data:")){const G=B.match(/^data:([^;]+);base64,(.+)$/);if(G)L=G[1],q=G[2];else{h.warn("Invalid data URL format, skipping image",{index:$});continue}}else if(B.startsWith("http://")||B.startsWith("https://"))try{const G=await fetch(B);if(!G.ok){h.warn(`Image fetch failed: ${G.status} ${G.statusText}, skipping`,{url:Xt(B),index:$});continue}const J=await G.arrayBuffer(),K=Buffer.from(J);q=K.toString("base64");const de=G.headers.get("content-type");L=de&&de.startsWith("image/")?de.split(";")[0]:this.detectImageType(K)}catch(G){h.warn(`Image URL fetch threw, skipping: ${G instanceof Error?G.message:String(G)}`,{url:Xt(B),index:$});continue}else{q=B;const G=Buffer.from(q,"base64");L=this.detectImageType(G)}else{h.warn("Invalid image format, skipping",{type:typeof B,index:$});continue}v.push({inlineData:{mimeType:L,data:q}}),h.debug("Added image to request",{index:$,mimeType:L,dataLength:q.length})}const T={contents:[{role:"user",parts:v}],generation_config:{response_modalities:["TEXT","IMAGE"],temperature:t.temperature||.7,candidate_count:1}};let b;u==="global"?b=`https://aiplatform.googleapis.com/v1/projects/${this.projectId}/locations/global/publishers/google/models/${a}:generateContent`:b=`https://${u}-aiplatform.googleapis.com/v1/projects/${this.projectId}/locations/${u}/publishers/google/models/${a}:generateContent`,h.debug("Making REST API call to Vertex AI",{url:b,model:a,hasAccessToken:!!y.token});const S=12e4,k=fetch(b,{method:"POST",headers:{Authorization:`Bearer ${y.token}`,"Content-Type":"application/json"},body:JSON.stringify(T)}),A=new Promise(($,B)=>{setTimeout(()=>{B(new ku(`Vertex AI image generation timed out after ${S}ms`,S))},S)}),x=await Promise.race([k,A]);if(!x.ok){const $=await x.text();throw new nt(`Vertex AI API error (${x.status}): ${$}`,this.providerName)}const C=(await x.json()).candidates?.[0];if(!C?.content?.parts)throw new nt("No content parts in Vertex AI response",this.providerName);const R=C.content.parts.find($=>($.inlineData||$.inline_data)&&($.inlineData&&$.inlineData.mimeType||$.inline_data&&$.inline_data.mime_type)&&($.inlineData&&$.inlineData.mimeType?.startsWith("image/")||$.inline_data&&$.inline_data.mime_type?.startsWith("image/")));if(!R){const $=C.content.parts.map(B=>B.text).filter(B=>!!B).join("");if($){h.info("[GoogleVertex] Image-gen route returned text fallback",{model:a,length:$.length});const B={content:$,provider:this.providerName,model:a,usage:{input:this.estimateTokenCount(r),output:this.estimateTokenCount($),total:this.estimateTokenCount(r)+this.estimateTokenCount($)}};return await this.enhanceResult(B,t,d)}throw new nt(`Image generation completed but no image data was returned. Model: ${a}`,this.providerName)}const O=R.inlineData?.data||R.inline_data?.data,U=R.inlineData?.mimeType||R.inline_data?.mime_type,M=U||"image/png";if(!O)throw new nt("Image part found but no data available",this.providerName);h.info("Image generation successful",{model:a,mimeType:M,dataLength:O.length,responseTime:Date.now()-d});const D={content:`Generated image using ${a} (${M})`,imageOutput:{base64:O,...U?{mimeType:U}:{}},provider:this.providerName,model:a,usage:{input:this.estimateTokenCount(r),output:0,total:this.estimateTokenCount(r)}};return await this.enhanceResult(D,t,d)}catch(p){throw h.error("Image generation failed",{error:p instanceof Error?p.message:String(p),model:a,prompt:r.substring(0,100)}),this.handleProviderError(p)}}getModelSuggestions(t){const r={google:["gemini-3-pro-preview-11-2025","gemini-3-pro-latest","gemini-3-pro-preview","gemini-2.5-pro","gemini-2.5-flash","gemini-2.5-flash-lite","gemini-2.0-flash-001","gemini-2.0-flash-lite"],claude:["claude-sonnet-4-5@20250929","claude-sonnet-4@20250514","claude-opus-4@20250514","claude-3-5-sonnet-20241022","claude-3-5-haiku-20241022","claude-3-sonnet-20240229","claude-3-haiku-20240307","claude-3-opus-20240229"]},n=(t??"").split("@")[0].toLowerCase(),o=l=>l.split("@")[0].toLowerCase()!==n,i=r.google.filter(o),s=r.claude.filter(o);let a=`
|
|
1153
1153
|
\u{1F916} Google Models (availability depends on your project and region):
|
|
1154
1154
|
`;return i.forEach(l=>{a+=` \u2022 ${l}
|
|
1155
1155
|
`}),a+=`
|
|
@@ -1158,7 +1158,7 @@ Reason: ${s instanceof Error?s.message:"Unknown error"}`}}return{...t,prompt:n,i
|
|
|
1158
1158
|
`}),t&&t.toLowerCase().includes("claude")&&(a+=`
|
|
1159
1159
|
\u{1F4A1} Tip: this model id appears to be a Claude model, which just failed.
|
|
1160
1160
|
`,a+=`Ensure Anthropic integration is enabled in your Google Cloud project.
|
|
1161
|
-
`,a+="Try another Claude model from the list above."),a}async embed(t,r){if(typeof t!="string"&&t.image)throw new ot(`${this.providerName} does not support image embeddings; provide text input`,this.providerName);const n=typeof t=="string"?t:t.text??"",o=r||this.getDefaultEmbeddingModel()||"text-embedding-004";h.debug("Generating embedding",{provider:this.providerName,model:o,textLength:n.length});try{const i=Aw(o,void 0),l=(await(await this.createVertexGenAIClient(i)).models.embedContent({model:o,contents:[n]})).embeddings?.[0]?.values;if(!l||l.length===0)throw new ot("No embedding returned from Vertex AI",this.providerName);return h.debug("Embedding generated successfully",{provider:this.providerName,model:o,embeddingDimension:l.length}),l}catch(i){throw h.error("Embedding generation failed",{error:i instanceof Error?i.message:String(i),model:o,textLength:n.length}),this.handleProviderError(i)}}async embedMany(t,r){const n=r||this.getDefaultEmbeddingModel()||"text-embedding-004";h.debug("Generating batch embeddings",{provider:this.providerName,model:n,count:t.length});try{const o=Aw(n,void 0),a=((await(await this.createVertexGenAIClient(o)).models.embedContent({model:n,contents:t})).embeddings||[]).map(l=>l.values||[]);return h.debug("Batch embeddings generated successfully",{provider:this.providerName,model:n,count:a.length,embeddingDimension:a[0]?.length}),a}catch(o){throw h.error("Batch embedding generation failed",{error:o instanceof Error?o.message:String(o),model:n,count:t.length}),this.handleProviderError(o)}}}}}),q3t,V3t,pte,j3t,H3t,FJr=E({"src/lib/providers/googleVertex/constants.ts"(){"use strict";Qt(),q3t=10*1024*1024,V3t=dt.getTracer("neurolink.provider.vertex"),pte=null,j3t={"claude-sonnet-4-5":"claude-sonnet-4-5@20250929","claude-opus-4-5":"claude-opus-4-5@20251101","claude-haiku-4-5":"claude-haiku-4-5@20251001","claude-sonnet-4":"claude-sonnet-4@20250514","claude-opus-4":"claude-opus-4@20250514","claude-opus-4-1":"claude-opus-4-1@20250805","claude-3-7-sonnet":"claude-3-7-sonnet@20250219","claude-3-5-sonnet":"claude-3-5-sonnet-20241022","claude-3-5-haiku":"claude-3-5-haiku-20241022","claude-3-opus":"claude-3-opus-20240229","claude-3-sonnet":"claude-3-sonnet-20240229","claude-3-haiku":"claude-3-haiku-20240307","gemini-3-pro":"gemini-3.1-pro-preview","gemini-3-flash":"gemini-3-flash-preview"},H3t=e=>{pte=e}}}),W3t={};Z(W3t,{GoogleVertexAI:()=>dte,GoogleVertexProvider:()=>dte,MAX_IMAGE_DOWNLOAD_BYTES:()=>q3t,VERTEX_MODEL_ALIASES:()=>j3t,appendUserMessage:()=>lte,buildAnthropicHistoryMessages:()=>ate,cachedCredentialsPath:()=>pte,resolveVertexLocation:()=>ute,setCachedCredentialsPath:()=>H3t,streamTracer:()=>V3t,stripAdditionalPropertiesDeep:()=>Ng});var $Jr=E({"src/lib/providers/googleVertex/index.ts"(){"use strict";LJr(),FJr()}}),K3t={};Z(K3t,{ConfiguredOpenAICompatProvider:()=>Z3t});var J3t,X3t,Y3t,Z3t,UJr=E({"src/lib/providers/configuredOpenAICompat.ts"(){"use strict";z(),Nt(),Go(),Zs(),Ys(),zc(),J3t="api.perplexity.ai",X3t="neurolink",Y3t=e=>typeof e=="string"?e:e==null?"":e.map(t=>t.type==="text"?t.text:"").join(""),Z3t=class extends Kl{entry;constructor(e,t,r,n){const{apiKey:o,baseURL:i}=ePr(e,n),s=t||Fi(e.modelEnvVar,e.defaultModel);super(e.providerName,s,r,{baseURL:i,apiKey:o}),this.entry=e,h.debug(`${e.configOptions.providerName} Provider initialized`,{modelName:this.modelName,providerName:this.providerName,baseURL:Yo(this.config.baseURL)})}getProviderName(){return this.entry.providerName}getDefaultModel(){return Fi(this.entry.modelEnvVar,this.entry.defaultModel)}getFallbackModelName(){return this.entry.fallbackModelName}getFallbackModels(){return this.entry.fallbackModels}getAuthHeaders(){const e=this.entry.authHeaderStyle==="x-api-key"?{"X-Api-Key":this.config.apiKey}:super.getAuthHeaders();return this.entry.providerName==="perplexity"&&new URL(this.config.baseURL).hostname===J3t&&(e["X-Pplx-Integration"]=X3t),e}supportsTools(){return this.entry.supportsTools===!1?!1:super.supportsTools()}suppressResponseFormatWithTools(){return this.entry.supportsStructuredOutputWithTools!==!0}adjustRequestBody(e,t){const r=super.adjustRequestBody(e,t);return this.entry.messageContentFormat!=="string"?r:{...r,messages:r.messages.map(n=>({...n,content:Y3t(n.content)}))}}adjustResponseFormat(e,t){return this.entry.responseFormatDowngrade==="json-schema-to-json-object"&&e?.type==="json_schema"?{type:"json_object"}:super.adjustResponseFormat(e,t)}replayReasoningContent(){return this.entry.replayReasoningContent===!0}formatProviderError(e){return e instanceof Ta&&this.entry.timeoutErrorClass?new this.entry.timeoutErrorClass(`${this.entry.configOptions.providerName} request timed out: ${e.message}`,this.entry.providerName):ba(e,this.entry.errorRules,this.entry.providerName,this.modelName)}}}});function mte(e,t){const r=e,n=r?.cause??{},o=r?.code??n?.code;return{match:i=>o==="ECONNREFUSED"||/ECONNREFUSED|Failed to fetch|fetch failed/.test(i.message),errorClass:ai,message:t}}var hte=E({"src/lib/providers/localRuntimeOpenAICompat.ts"(){"use strict";pt()}}),Zx,Q3t,eFt,fN=E({"src/lib/providers/ollama/constants.ts"(){"use strict";Ln(),Zx="llama3.2:latest",Q3t="llama3.2:latest",eFt=Ot()}}),tFt,rFt,fte,gte,nFt,Qx,oFt,iFt,BJr=E({"src/lib/providers/ollama/client.ts"(){"use strict";Mf(),Ln(),pt(),Zs(),z(),Nt(),Ys(),zc(),hte(),Um(),fN(),tFt="http://localhost:11434/v1",rFt="ollama",fte="llama3.1:8b",gte="nomic-embed-text",nFt=3e4,Qx=()=>process.env.OLLAMA_MODEL||Zx,oFt=e=>{const t=e?.trim()||process.env.OLLAMA_BASE_URL?.trim()||tFt,r=Da(t);return r.endsWith("/v1")?r:`${r}/v1`},iFt=class extends Kl{constructor(e,t,r,n){const o=oFt(n?.baseURL),i=n?.apiKey?.trim()||process.env.OLLAMA_API_KEY?.trim()||rFt;super("ollama",e,t,{baseURL:o,apiKey:i}),h.debug("Ollama Provider initialized",{modelName:this.modelName,providerName:this.providerName,baseURL:Yo(this.config.baseURL)})}getProviderName(){return"ollama"}getDefaultModel(){return Qx()}getFallbackModelName(){return fte}formatProviderError(e){if(e instanceof Ta)return new ai("Ollama request timed out. The model may be loading or the request is too large.","ollama");const t=e,r=typeof t?.responseBody=="string"?t.responseBody:"",n=[mte(e,()=>`Cannot connect to Ollama at ${Yo(this.config.baseURL)}. Install Ollama (https://ollama.com), start it with 'ollama serve', then try again.`),{match:o=>{const i=`${o.message} ${r}`.toLowerCase();return i.includes("model_not_found")||i.includes("model")&&i.includes("not found")},errorClass:Jo,message:()=>`Ollama model '${this.modelName}' is not available locally. Pull it first with 'ollama pull ${this.modelName}' (or try '${fte}'); list installed models with 'ollama list'.`},{match:o=>{const i=`${o.message} ${r}`.toLowerCase();return o.statusCode===404||i.includes("status 404")},errorClass:ot,message:()=>`Ollama returned HTTP 404 from ${Yo(this.config.baseURL)}. Verify the base URL serves the OpenAI-compatible /v1 API and that the model is installed ('ollama list').`},...Ll];return ba(e,n,this.providerName,this.modelName)}supportsTools(){const e=(this.modelName??Qx()).toLowerCase(),r=Pf.getProviderConfiguration("ollama")?.modelBehavior?.toolCapableModels||[];if(r.length===0)return!0;const n=r.some(o=>e.includes(o.toLowerCase()));return n||h.debug("Ollama tool calling disabled",{model:this.modelName,reason:"Model not in OLLAMA_TOOL_CAPABLE_MODELS list"}),n}getTimeout(e){if(e.timeout===void 0||e.timeout===null){const t=process.env.OLLAMA_TIMEOUT?.trim();if(t)try{const r=kc(t);if(r!==void 0&&r>0)return r}catch{h.debug(`Ignoring invalid OLLAMA_TIMEOUT='${t}'; using the default. Use a millisecond number (240000) or a duration like '4m' / '30s'.`)}}return super.getTimeout(e)}async validateConfiguration(){return this.probeModelsEndpoint(this.getAuthHeaders())}getConfiguration(){return{provider:this.providerName,model:this.modelName||this.resolvedModel||Qx(),defaultModel:Qx(),baseURL:this.config.baseURL}}async embed(e,t){if(typeof e!="string"&&e.image)throw new ot(`${this.providerName} does not support image embeddings; provide text input`,this.providerName);const r=typeof e=="string"?e:e.text??"",n=t||process.env.OLLAMA_EMBEDDING_MODEL||gte,[o]=await this.callEmbeddings(n,[r],"embed");return o}async embedMany(e,t){const r=t||process.env.OLLAMA_EMBEDDING_MODEL||gte;return this.callEmbeddings(r,e,"embedMany")}async callEmbeddings(e,t,r){const n=`${Da(this.config.baseURL)}/embeddings`,o=Ot(),i=wa(nFt,this.providerName,"generate");try{const s=await o(n,{method:"POST",headers:{"Content-Type":"application/json",...this.getAuthHeaders()},body:JSON.stringify({model:e,input:t.length===1?t[0]:t}),...i?.controller.signal?{signal:i.controller.signal}:{}});if(!s.ok){const c=await s.text().catch(()=>"");let u;if(c)try{u=JSON.parse(c)}catch{u=void 0}throw this.formatProviderError(new Error(u?.error?.message||`Ollama ${r} failed with status ${s.status}`))}const l=((await s.json()).data??[]).map(c=>c.embedding).filter(c=>Array.isArray(c));if(l.length===0)throw new ot(`Ollama ${r} returned no embeddings`,"ollama");return l}finally{i?.cleanup()}}}}}),sFt={};Z(sFt,{DEFAULT_OLLAMA_MODEL:()=>Zx,FALLBACK_OLLAMA_MODEL:()=>Q3t,OllamaProvider:()=>iFt,proxyFetch:()=>eFt});var zJr=E({"src/lib/providers/ollama/index.ts"(){"use strict";BJr(),fN()}});function GJr(){eA.clear(),gN.clear(),yN.clear()}async function qJr(e,t){const r=`${e}/model/info`,n=Ot(),o=new AbortController,i=setTimeout(()=>o.abort(),5e3);try{const s=await n(r,{method:"GET",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},signal:o.signal});if(!s.ok)throw new Error(`HTTP ${s.status}: ${s.statusText}`);const a=await s.json(),l=u=>typeof u=="number"&&Number.isFinite(u)&&u>0,c=new Map;for(const u of a.data??[]){const d=u?.model_name;if(typeof d!="string"||d.length===0)continue;const p=u?.model_info?.max_input_tokens,m=u?.model_info?.max_output_tokens;if(!l(p)&&!l(m))continue;const f=c.get(d)??{};l(p)&&(f.maxInputTokens=f.maxInputTokens===void 0?p:Math.min(f.maxInputTokens,p)),l(m)&&(f.maxOutputTokens=f.maxOutputTokens===void 0?m:Math.min(f.maxOutputTokens,m)),c.set(d,f)}return c}catch(s){throw pr(s)?new ai("Request timed out after 5 seconds","litellm"):s}finally{clearTimeout(i)}}function yte(e,t){const r=Da(e),n=gN.get(r)??0;if(Date.now()-n<uFt)return Promise.resolve();const o=eA.get(r);if(o)return o;const i=qJr(r,t).then(s=>{yN.set(r,s);const a=new Map;for(const l of yN.values())for(const[c,u]of l){const d=a.get(c)??{};u.maxInputTokens!==void 0&&(d.maxInputTokens=d.maxInputTokens===void 0?u.maxInputTokens:Math.min(d.maxInputTokens,u.maxInputTokens)),u.maxOutputTokens!==void 0&&(d.maxOutputTokens=d.maxOutputTokens===void 0?u.maxOutputTokens:Math.min(d.maxOutputTokens,u.maxOutputTokens)),a.set(c,d)}for(const[l,c]of a)c.maxInputTokens!==void 0&&pK("litellm",l,c.maxInputTokens),c.maxOutputTokens!==void 0&&Hct("litellm",l,c.maxOutputTokens);gN.set(r,Date.now()),s.size>0&&h.debug("[LiteLLM] Registered runtime model limits from /model/info",{baseURL:Yo(r),models:s.size})}).catch(s=>{h.debug("[LiteLLM] /model/info discovery failed; static context-window defaults remain in force",{error:s instanceof Error?s.message:String(s)})}).finally(()=>{eA.delete(r)});return eA.set(r,i),i}var aFt,vte,lFt,cFt,uFt,eA,gN,yN,dFt,pFt,VJr=E({"src/lib/providers/litellm/client.ts"(){"use strict";Qt(),$c(),Ln(),pt(),Zs(),et(),z(),Nt(),fO(),sl(),Go(),Ys(),Um(),zc(),aFt=dt.getTracer("neurolink.provider.litellm"),vte="openai/gpt-5.4-mini",lFt=()=>({baseURL:process.env.LITELLM_BASE_URL||"http://localhost:4000",apiKey:process.env.LITELLM_API_KEY||"sk-anything"}),cFt=()=>Fi("LITELLM_MODEL",vte),uFt=600*1e3,eA=new Map,gN=new Map,yN=new Map,dFt=e=>{const t=e.includes("/")?e.slice(e.lastIndexOf("/")+1):e;return S1t(t)},pFt=class Bp extends Kl{static modelsCache=[];static modelsCacheTime=0;static MODELS_CACHE_DURATION=600*1e3;constructor(t,r,n,o){const i=lFt();super("litellm",t,r,{baseURL:o?.baseURL??i.baseURL,apiKey:o?.apiKey??i.apiKey}),yte(this.config.baseURL,this.config.apiKey),h.debug("LiteLLM Provider initialized",{modelName:this.modelName,provider:this.providerName,baseURL:Yo(this.config.baseURL)})}async ensureModelLimits(){await yte(this.config.baseURL,this.config.apiKey)}getProviderName(){return"litellm"}getDefaultModel(){return cFt()}getFallbackModelName(){return vte}getFallbackModels(){return process.env.LITELLM_FALLBACK_MODELS?.split(",").map(t=>t.trim()).filter(t=>t.length>0)||["openai/gpt-5.4","anthropic/claude-haiku-4-5-20251001","meta-llama/llama-3.1-8b-instruct","google/gemini-2.5-flash"]}useStreamingWireForGenerate(){return process.env.NEUROLINK_LITELLM_SSE_GENERATE!=="false"}adjustBuildBodyOptions(t,r){return dFt(t)&&r.maxTokens!==void 0?(h.shouldLog("debug")&&h.debug("LiteLLM: Skipping maxTokens for Gemini 2.5 model (known compatibility issue)",{modelId:t,requestedMaxTokens:r.maxTokens}),{...r,maxTokens:void 0}):r}onStreamStart(t){const r=aFt.startSpan("neurolink.provider.streamText",{kind:nn.CLIENT,attributes:{"gen_ai.system":"litellm","gen_ai.request.model":t}});let n=!1;const o=()=>{n||(n=!0,r.end())};return{onUsage:i=>{r.setAttribute("gen_ai.usage.input_tokens",i.promptTokens+(i.cacheReadTokens??0)+(i.cacheCreationTokens??0)),r.setAttribute("gen_ai.usage.output_tokens",i.completionTokens);const s=Ls(this.providerName,t,{input:i.promptTokens,output:i.completionTokens,total:i.totalTokens,...i.cacheReadTokens?{cacheReadTokens:i.cacheReadTokens}:{},...i.cacheCreationTokens?{cacheCreationTokens:i.cacheCreationTokens}:{}});s&&s>0&&r.setAttribute("neurolink.cost",s)},onFinish:(i,s)=>{r.setAttribute("gen_ai.response.finish_reason",i||"unknown"),i==="error"&&r.setStatus({code:Ue.ERROR,message:s instanceof Error?s.message:String(s??"stream error")}),o()}}}formatProviderError(t){const r=t;if(typeof r?.message=="string"&&N0e(r.message))return new ry(r.message,{provider:this.providerName,requestedModel:this.modelName,allowedModels:D0e(r.message)});const n=[{match:o=>o.errorName==="TimeoutError"||/timeout/i.test(o.message),errorClass:ai,message:o=>`Request timed out: ${o.message}`},{match:o=>/ECONNREFUSED|Failed to fetch/.test(o.message),errorClass:ai,message:()=>"LiteLLM proxy server not available. Please start the LiteLLM proxy server at "+Yo(this.config.baseURL)},{match:o=>/API_KEY_INVALID|Invalid API key/.test(o.message),errorClass:Wr,message:"Invalid LiteLLM configuration. Please check your LITELLM_API_KEY environment variable."},{match:o=>/rate limit/i.test(o.message),errorClass:Qi,message:"LiteLLM rate limit exceeded. Please try again later."},{match:o=>/model/i.test(o.message)&&/not found/i.test(o.message),errorClass:Jo,message:()=>`Model '${this.modelName}' not available in LiteLLM proxy. Please check your LiteLLM configuration and ensure the model is configured.`},...Ll];return ba(t,n,this.providerName,this.modelName)}async getAvailableModels(){const t=Date.now();if(Bp.modelsCache.length>0&&t-Bp.modelsCacheTime<Bp.MODELS_CACHE_DURATION)return h.debug("[LiteLLMProvider.getAvailableModels] Using cached models",{cacheAge:Math.round((t-Bp.modelsCacheTime)/1e3),modelCount:Bp.modelsCache.length}),Bp.modelsCache;try{const r=await this.fetchModelsFromAPI();if(r.length>0)return Bp.modelsCache=r,Bp.modelsCacheTime=t,r}catch(r){h.warn("[LiteLLMProvider.getAvailableModels] Failed to fetch models from API, using fallback",{error:r instanceof Error?r.message:String(r)})}return this.getFallbackModels()}async fetchModelsFromAPI(){const r=`${Da(this.config.baseURL).replace(/\/v1$/,"")}/v1/models`,n=Ot(),o=new AbortController,i=setTimeout(()=>o.abort(),5e3);try{const s=await n(r,{method:"GET",headers:{Authorization:`Bearer ${this.config.apiKey}`,"Content-Type":"application/json"},signal:o.signal});if(!s.ok)throw new Error(`HTTP ${s.status}: ${s.statusText}`);const a=await s.json();if(!Array.isArray(a.data))throw new Error("Invalid response format: expected data.data array");return a.data.map(l=>l.id).filter(l=>typeof l=="string"&&l.length>0).sort()}catch(s){throw pr(s)?new ai("Request timed out after 5 seconds",this.providerName):s}finally{clearTimeout(i)}}async embed(t,r){if(typeof t!="string"&&t.image)throw new ot(`${this.providerName} does not support image embeddings; provide text input`,this.providerName);const n=typeof t=="string"?t:t.text??"",o=r||process.env.LITELLM_EMBEDDING_MODEL||"gemini-embedding-001",[i]=await this.callEmbeddings(o,[n],"embed");return i}async embedMany(t,r){const n=r||process.env.LITELLM_EMBEDDING_MODEL||"gemini-embedding-001";return this.callEmbeddings(n,t,"embedMany")}async callEmbeddings(t,r,n){const o=`${Da(this.config.baseURL)}/embeddings`,i=Ot(),s=wa(3e4,this.providerName,"generate");try{const a=await i(o,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`},body:JSON.stringify({model:t,input:r.length===1?r[0]:r}),...s?.controller.signal?{signal:s.controller.signal}:{}});if(!a.ok){const u=await a.text().catch(()=>""),d=u?JSON.parse(u):void 0;throw this.formatProviderError(new Error(d?.error?.message||`LiteLLM ${n} failed with status ${a.status}`))}const c=((await a.json()).data??[]).map(u=>u.embedding).filter(u=>Array.isArray(u));if(c.length===0)throw new ot(`LiteLLM ${n} returned no embeddings`,this.providerName);return c}finally{s?.cleanup()}}}}}),mFt={};Z(mFt,{LiteLLMProvider:()=>pFt,clearLiteLLMModelLimitsCache:()=>GJr,ensureLiteLLMModelLimits:()=>yte});var jJr=E({"src/lib/providers/litellm/index.ts"(){"use strict";VJr()}}),vN,hFt=E({"src/lib/providers/openaiCompatible/constants.ts"(){"use strict";vN="gpt-3.5-turbo"}}),wte,Tte,fFt=E({"src/lib/providers/openaiCompatible/utils.ts"(){"use strict";wte=()=>{const e=process.env.OPENAI_COMPATIBLE_BASE_URL,t=process.env.OPENAI_COMPATIBLE_API_KEY;if(!e)throw new Error("OPENAI_COMPATIBLE_BASE_URL environment variable is required. Please set it to your OpenAI-compatible endpoint (e.g., https://api.openrouter.ai/api/v1)");if(!t)throw new Error("OPENAI_COMPATIBLE_API_KEY environment variable is required. Please set it to your API key for the OpenAI-compatible service.");return{baseURL:e,apiKey:t}},Tte=()=>process.env.OPENAI_COMPATIBLE_MODEL||void 0}}),gFt,HJr=E({"src/lib/providers/openaiCompatible/client.ts"(){"use strict";pt(),z(),Nt(),Zs(),zc(),hFt(),fFt(),gFt=class extends Kl{constructor(e,t,r,n){const o=n?.apiKey&&n?.baseURL?{apiKey:n.apiKey,baseURL:n.baseURL}:(()=>{const i=wte();return{apiKey:n?.apiKey??i.apiKey,baseURL:n?.baseURL??i.baseURL}})();super("openai-compatible",e,t,o),h.debug("OpenAI Compatible Provider initialized",{modelName:this.modelName,provider:this.providerName,baseURL:Yo(this.config.baseURL)})}getProviderName(){return"openai-compatible"}getDefaultModel(){return Tte()||""}getFallbackModelName(){return vN}getFallbackModels(){return["gpt-4o","gpt-4o-mini","gpt-4-turbo",vN,"claude-3-5-sonnet","claude-3-haiku","gemini-pro"]}formatProviderError(e){const t=[{match:r=>r.errorName==="TimeoutError"||/Timeout/.test(r.message),errorClass:ai,message:r=>`Request timed out: ${r.message}`},{match:r=>/ECONNREFUSED|Failed to fetch/i.test(r.message),errorClass:ai,message:()=>`OpenAI Compatible endpoint not available. Please check your OPENAI_COMPATIBLE_BASE_URL: ${Yo(this.config.baseURL)}`},{match:r=>r.statusCode===401||/API_KEY_INVALID|Invalid API key|Unauthorized/i.test(r.message),errorClass:Wr,message:"Invalid OpenAI Compatible API key. Please check your OPENAI_COMPATIBLE_API_KEY environment variable."},{match:r=>/model/i.test(r.message)&&(/not found/i.test(r.message)||/does not exist/i.test(r.message)),errorClass:Jo,message:r=>`Model '${r.modelName}' not available on OpenAI Compatible endpoint. Please check available models or use getAvailableModels() to see supported models.`},...Ll];return ba(e,t,this.providerName,this.modelName)}}}}),yFt={};Z(yFt,{FALLBACK_OPENAI_COMPATIBLE_MODEL:()=>vN,OpenAICompatibleProvider:()=>gFt,getDefaultOpenAICompatibleModel:()=>Tte,getOpenAICompatibleConfig:()=>wte});var WJr=E({"src/lib/providers/openaiCompatible/index.ts"(){"use strict";HJr(),hFt(),fFt()}}),tA,vFt=E({"src/lib/providers/openRouter/utils.ts"(){"use strict";Go(),tA=()=>Fi("OPENROUTER_MODEL","anthropic/claude-sonnet-4.5")}}),wFt,wN,TFt,bFt,KJr=E({"src/lib/providers/openRouter/client.ts"(){"use strict";pt(),Ln(),Zs(),et(),z(),Nt(),zc(),Um(),vFt(),wFt="https://openrouter.ai/api/v1",wN=5e3,TFt=()=>{const e=process.env.OPENROUTER_API_KEY;if(!e)throw new Error("OPENROUTER_API_KEY environment variable is required. Get your API key at https://openrouter.ai/keys");return e},bFt=class Ka extends Kl{referer;appName;static modelsCache=[];static modelsCacheTime=0;static MODELS_CACHE_DURATION=600*1e3;static toolCapableModels=new Set;static capabilitiesCached=!1;constructor(t,r,n,o){const i=o?.apiKey?.trim(),s=i&&i.length>0?i:TFt(),a=o?.baseURL?.trim()||process.env.OPENROUTER_BASE_URL?.trim()||wFt;super("openrouter",t,r,{baseURL:a,apiKey:s}),this.referer=process.env.OPENROUTER_REFERER?.trim()||void 0,this.appName=process.env.OPENROUTER_APP_NAME?.trim()||void 0,h.debug("OpenRouter Provider initialized",{modelName:this.modelName,providerName:this.providerName,baseURL:Yo(this.config.baseURL)})}getProviderName(){return"openrouter"}getDefaultModel(){return tA()}formatProviderError(t){const r=[{match:n=>n.errorName==="TimeoutError"||/Timeout/.test(n.message),errorClass:ai,message:n=>`Request timed out: ${n.message}`},{match:n=>/ECONNREFUSED|Failed to fetch/.test(n.message),errorClass:ai,message:"OpenRouter API not available. Please check your network connection and try again."},{match:n=>/API_KEY_INVALID|Invalid API key|invalid_api_key|Unauthorized/.test(n.message),errorClass:Wr,message:"Invalid OpenRouter API key. Please check your OPENROUTER_API_KEY environment variable. Get your key at https://openrouter.ai/keys"},{match:n=>/rate limit/.test(n.message),errorClass:Qi,message:"OpenRouter rate limit exceeded. Please try again later or upgrade your account at https://openrouter.ai/credits"},{match:n=>/model/.test(n.message)&&/not found/.test(n.message),errorClass:Jo,message:()=>`Model '${this.modelName}' not available on OpenRouter. Browse available models at https://openrouter.ai/models`},{match:n=>/insufficient_credits/.test(n.message),errorClass:ot,message:"Insufficient OpenRouter credits. Add credits at https://openrouter.ai/credits"},{match:n=>/No endpoints found/.test(n.message),errorClass:Jo,message:()=>`No endpoints found for model '${this.modelName}' on OpenRouter. The model may be temporarily unavailable or does not support the requested parameters. Try a different model or check availability at https://openrouter.ai/models`},{match:n=>/tool use|tool_use|function_call|tools are not supported/.test(n.message),errorClass:ot,message:()=>`Model '${this.modelName}' does not support tool calling. Use a tool-capable model like:
|
|
1161
|
+
`,a+="Try another Claude model from the list above."),a}async embed(t,r){if(typeof t!="string"&&t.image)throw new nt(`${this.providerName} does not support image embeddings; provide text input`,this.providerName);const n=typeof t=="string"?t:t.text??"",o=r||this.getDefaultEmbeddingModel()||"text-embedding-004";h.debug("Generating embedding",{provider:this.providerName,model:o,textLength:n.length});try{const i=Aw(o,void 0),l=(await(await this.createVertexGenAIClient(i)).models.embedContent({model:o,contents:[n]})).embeddings?.[0]?.values;if(!l||l.length===0)throw new nt("No embedding returned from Vertex AI",this.providerName);return h.debug("Embedding generated successfully",{provider:this.providerName,model:o,embeddingDimension:l.length}),l}catch(i){throw h.error("Embedding generation failed",{error:i instanceof Error?i.message:String(i),model:o,textLength:n.length}),this.handleProviderError(i)}}async embedMany(t,r){const n=r||this.getDefaultEmbeddingModel()||"text-embedding-004";h.debug("Generating batch embeddings",{provider:this.providerName,model:n,count:t.length});try{const o=Aw(n,void 0),a=((await(await this.createVertexGenAIClient(o)).models.embedContent({model:n,contents:t})).embeddings||[]).map(l=>l.values||[]);return h.debug("Batch embeddings generated successfully",{provider:this.providerName,model:n,count:a.length,embeddingDimension:a[0]?.length}),a}catch(o){throw h.error("Batch embedding generation failed",{error:o instanceof Error?o.message:String(o),model:n,count:t.length}),this.handleProviderError(o)}}}}}),q3t,V3t,pte,j3t,H3t,FJr=E({"src/lib/providers/googleVertex/constants.ts"(){"use strict";Qt(),q3t=10*1024*1024,V3t=dt.getTracer("neurolink.provider.vertex"),pte=null,j3t={"claude-sonnet-4-5":"claude-sonnet-4-5@20250929","claude-opus-4-5":"claude-opus-4-5@20251101","claude-haiku-4-5":"claude-haiku-4-5@20251001","claude-sonnet-4":"claude-sonnet-4@20250514","claude-opus-4":"claude-opus-4@20250514","claude-opus-4-1":"claude-opus-4-1@20250805","claude-3-7-sonnet":"claude-3-7-sonnet@20250219","claude-3-5-sonnet":"claude-3-5-sonnet-20241022","claude-3-5-haiku":"claude-3-5-haiku-20241022","claude-3-opus":"claude-3-opus-20240229","claude-3-sonnet":"claude-3-sonnet-20240229","claude-3-haiku":"claude-3-haiku-20240307","gemini-3-pro":"gemini-3.1-pro-preview","gemini-3-flash":"gemini-3-flash-preview"},H3t=e=>{pte=e}}}),W3t={};Z(W3t,{GoogleVertexAI:()=>dte,GoogleVertexProvider:()=>dte,MAX_IMAGE_DOWNLOAD_BYTES:()=>q3t,VERTEX_MODEL_ALIASES:()=>j3t,appendUserMessage:()=>lte,buildAnthropicHistoryMessages:()=>ate,cachedCredentialsPath:()=>pte,resolveVertexLocation:()=>ute,setCachedCredentialsPath:()=>H3t,streamTracer:()=>V3t,stripAdditionalPropertiesDeep:()=>Ng});var $Jr=E({"src/lib/providers/googleVertex/index.ts"(){"use strict";LJr(),FJr()}}),K3t={};Z(K3t,{ConfiguredOpenAICompatProvider:()=>Z3t});var J3t,X3t,Y3t,Z3t,UJr=E({"src/lib/providers/configuredOpenAICompat.ts"(){"use strict";z(),Nt(),Go(),Zs(),Ys(),zc(),J3t="api.perplexity.ai",X3t="neurolink",Y3t=e=>typeof e=="string"?e:e==null?"":e.map(t=>t.type==="text"?t.text:"").join(""),Z3t=class extends Kl{entry;constructor(e,t,r,n){const{apiKey:o,baseURL:i}=ePr(e,n),s=t||Fi(e.modelEnvVar,e.defaultModel);super(e.providerName,s,r,{baseURL:i,apiKey:o}),this.entry=e,h.debug(`${e.configOptions.providerName} Provider initialized`,{modelName:this.modelName,providerName:this.providerName,baseURL:Yo(this.config.baseURL)})}getProviderName(){return this.entry.providerName}getDefaultModel(){return Fi(this.entry.modelEnvVar,this.entry.defaultModel)}getFallbackModelName(){return this.entry.fallbackModelName}getFallbackModels(){return this.entry.fallbackModels}getAuthHeaders(){const e=this.entry.authHeaderStyle==="x-api-key"?{"X-Api-Key":this.config.apiKey}:super.getAuthHeaders();return this.entry.providerName==="perplexity"&&new URL(this.config.baseURL).hostname===J3t&&(e["X-Pplx-Integration"]=X3t),e}supportsTools(){return this.entry.supportsTools===!1?!1:super.supportsTools()}suppressResponseFormatWithTools(){return this.entry.supportsStructuredOutputWithTools!==!0}adjustRequestBody(e,t){const r=super.adjustRequestBody(e,t);return this.entry.messageContentFormat!=="string"?r:{...r,messages:r.messages.map(n=>({...n,content:Y3t(n.content)}))}}adjustResponseFormat(e,t){return this.entry.responseFormatDowngrade==="json-schema-to-json-object"&&e?.type==="json_schema"?{type:"json_object"}:super.adjustResponseFormat(e,t)}replayReasoningContent(){return this.entry.replayReasoningContent===!0}formatProviderError(e){return e instanceof Ta&&this.entry.timeoutErrorClass?new this.entry.timeoutErrorClass(`${this.entry.configOptions.providerName} request timed out: ${e.message}`,this.entry.providerName):ba(e,this.entry.errorRules,this.entry.providerName,this.modelName)}}}});function mte(e,t){const r=e,n=r?.cause??{},o=r?.code??n?.code;return{match:i=>o==="ECONNREFUSED"||/ECONNREFUSED|Failed to fetch|fetch failed/.test(i.message),errorClass:ai,message:t}}var hte=E({"src/lib/providers/localRuntimeOpenAICompat.ts"(){"use strict";pt()}}),Zx,Q3t,eFt,fN=E({"src/lib/providers/ollama/constants.ts"(){"use strict";Ln(),Zx="llama3.2:latest",Q3t="llama3.2:latest",eFt=Ot()}}),tFt,rFt,fte,gte,nFt,Qx,oFt,iFt,BJr=E({"src/lib/providers/ollama/client.ts"(){"use strict";Mf(),Ln(),pt(),Zs(),z(),Nt(),Ys(),zc(),hte(),Um(),fN(),tFt="http://localhost:11434/v1",rFt="ollama",fte="llama3.1:8b",gte="nomic-embed-text",nFt=3e4,Qx=()=>process.env.OLLAMA_MODEL||Zx,oFt=e=>{const t=e?.trim()||process.env.OLLAMA_BASE_URL?.trim()||tFt,r=Da(t);return r.endsWith("/v1")?r:`${r}/v1`},iFt=class extends Kl{constructor(e,t,r,n){const o=oFt(n?.baseURL),i=n?.apiKey?.trim()||process.env.OLLAMA_API_KEY?.trim()||rFt;super("ollama",e,t,{baseURL:o,apiKey:i}),h.debug("Ollama Provider initialized",{modelName:this.modelName,providerName:this.providerName,baseURL:Yo(this.config.baseURL)})}getProviderName(){return"ollama"}getDefaultModel(){return Qx()}getFallbackModelName(){return fte}formatProviderError(e){if(e instanceof Ta)return new ai("Ollama request timed out. The model may be loading or the request is too large.","ollama");const t=e,r=typeof t?.responseBody=="string"?t.responseBody:"",n=[mte(e,()=>`Cannot connect to Ollama at ${Yo(this.config.baseURL)}. Install Ollama (https://ollama.com), start it with 'ollama serve', then try again.`),{match:o=>{const i=`${o.message} ${r}`.toLowerCase();return i.includes("model_not_found")||i.includes("model")&&i.includes("not found")},errorClass:Jo,message:()=>`Ollama model '${this.modelName}' is not available locally. Pull it first with 'ollama pull ${this.modelName}' (or try '${fte}'); list installed models with 'ollama list'.`},{match:o=>{const i=`${o.message} ${r}`.toLowerCase();return o.statusCode===404||i.includes("status 404")},errorClass:nt,message:()=>`Ollama returned HTTP 404 from ${Yo(this.config.baseURL)}. Verify the base URL serves the OpenAI-compatible /v1 API and that the model is installed ('ollama list').`},...Ll];return ba(e,n,this.providerName,this.modelName)}supportsTools(){const e=(this.modelName??Qx()).toLowerCase(),r=Pf.getProviderConfiguration("ollama")?.modelBehavior?.toolCapableModels||[];if(r.length===0)return!0;const n=r.some(o=>e.includes(o.toLowerCase()));return n||h.debug("Ollama tool calling disabled",{model:this.modelName,reason:"Model not in OLLAMA_TOOL_CAPABLE_MODELS list"}),n}getTimeout(e){if(e.timeout===void 0||e.timeout===null){const t=process.env.OLLAMA_TIMEOUT?.trim();if(t)try{const r=kc(t);if(r!==void 0&&r>0)return r}catch{h.debug(`Ignoring invalid OLLAMA_TIMEOUT='${t}'; using the default. Use a millisecond number (240000) or a duration like '4m' / '30s'.`)}}return super.getTimeout(e)}async validateConfiguration(){return this.probeModelsEndpoint(this.getAuthHeaders())}getConfiguration(){return{provider:this.providerName,model:this.modelName||this.resolvedModel||Qx(),defaultModel:Qx(),baseURL:this.config.baseURL}}async embed(e,t){if(typeof e!="string"&&e.image)throw new nt(`${this.providerName} does not support image embeddings; provide text input`,this.providerName);const r=typeof e=="string"?e:e.text??"",n=t||process.env.OLLAMA_EMBEDDING_MODEL||gte,[o]=await this.callEmbeddings(n,[r],"embed");return o}async embedMany(e,t){const r=t||process.env.OLLAMA_EMBEDDING_MODEL||gte;return this.callEmbeddings(r,e,"embedMany")}async callEmbeddings(e,t,r){const n=`${Da(this.config.baseURL)}/embeddings`,o=Ot(),i=wa(nFt,this.providerName,"generate");try{const s=await o(n,{method:"POST",headers:{"Content-Type":"application/json",...this.getAuthHeaders()},body:JSON.stringify({model:e,input:t.length===1?t[0]:t}),...i?.controller.signal?{signal:i.controller.signal}:{}});if(!s.ok){const c=await s.text().catch(()=>"");let u;if(c)try{u=JSON.parse(c)}catch{u=void 0}throw this.formatProviderError(new Error(u?.error?.message||`Ollama ${r} failed with status ${s.status}`))}const l=((await s.json()).data??[]).map(c=>c.embedding).filter(c=>Array.isArray(c));if(l.length===0)throw new nt(`Ollama ${r} returned no embeddings`,"ollama");return l}finally{i?.cleanup()}}}}}),sFt={};Z(sFt,{DEFAULT_OLLAMA_MODEL:()=>Zx,FALLBACK_OLLAMA_MODEL:()=>Q3t,OllamaProvider:()=>iFt,proxyFetch:()=>eFt});var zJr=E({"src/lib/providers/ollama/index.ts"(){"use strict";BJr(),fN()}});function GJr(){eA.clear(),gN.clear(),yN.clear()}async function qJr(e,t){const r=`${e}/model/info`,n=Ot(),o=new AbortController,i=setTimeout(()=>o.abort(),5e3);try{const s=await n(r,{method:"GET",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},signal:o.signal});if(!s.ok)throw new Error(`HTTP ${s.status}: ${s.statusText}`);const a=await s.json(),l=u=>typeof u=="number"&&Number.isFinite(u)&&u>0,c=new Map;for(const u of a.data??[]){const d=u?.model_name;if(typeof d!="string"||d.length===0)continue;const p=u?.model_info?.max_input_tokens,m=u?.model_info?.max_output_tokens;if(!l(p)&&!l(m))continue;const f=c.get(d)??{};l(p)&&(f.maxInputTokens=f.maxInputTokens===void 0?p:Math.min(f.maxInputTokens,p)),l(m)&&(f.maxOutputTokens=f.maxOutputTokens===void 0?m:Math.min(f.maxOutputTokens,m)),c.set(d,f)}return c}catch(s){throw pr(s)?new ai("Request timed out after 5 seconds","litellm"):s}finally{clearTimeout(i)}}function yte(e,t){const r=Da(e),n=gN.get(r)??0;if(Date.now()-n<uFt)return Promise.resolve();const o=eA.get(r);if(o)return o;const i=qJr(r,t).then(s=>{yN.set(r,s);const a=new Map;for(const l of yN.values())for(const[c,u]of l){const d=a.get(c)??{};u.maxInputTokens!==void 0&&(d.maxInputTokens=d.maxInputTokens===void 0?u.maxInputTokens:Math.min(d.maxInputTokens,u.maxInputTokens)),u.maxOutputTokens!==void 0&&(d.maxOutputTokens=d.maxOutputTokens===void 0?u.maxOutputTokens:Math.min(d.maxOutputTokens,u.maxOutputTokens)),a.set(c,d)}for(const[l,c]of a)c.maxInputTokens!==void 0&&pK("litellm",l,c.maxInputTokens),c.maxOutputTokens!==void 0&&Hct("litellm",l,c.maxOutputTokens);gN.set(r,Date.now()),s.size>0&&h.debug("[LiteLLM] Registered runtime model limits from /model/info",{baseURL:Yo(r),models:s.size})}).catch(s=>{h.debug("[LiteLLM] /model/info discovery failed; static context-window defaults remain in force",{error:s instanceof Error?s.message:String(s)})}).finally(()=>{eA.delete(r)});return eA.set(r,i),i}var aFt,vte,lFt,cFt,uFt,eA,gN,yN,dFt,pFt,VJr=E({"src/lib/providers/litellm/client.ts"(){"use strict";Qt(),$c(),Ln(),pt(),Zs(),et(),z(),Nt(),fO(),sl(),Go(),Ys(),Um(),zc(),aFt=dt.getTracer("neurolink.provider.litellm"),vte="openai/gpt-5.4-mini",lFt=()=>({baseURL:process.env.LITELLM_BASE_URL||"http://localhost:4000",apiKey:process.env.LITELLM_API_KEY||"sk-anything"}),cFt=()=>Fi("LITELLM_MODEL",vte),uFt=600*1e3,eA=new Map,gN=new Map,yN=new Map,dFt=e=>{const t=e.includes("/")?e.slice(e.lastIndexOf("/")+1):e;return S1t(t)},pFt=class Bp extends Kl{static modelsCache=[];static modelsCacheTime=0;static MODELS_CACHE_DURATION=600*1e3;constructor(t,r,n,o){const i=lFt();super("litellm",t,r,{baseURL:o?.baseURL??i.baseURL,apiKey:o?.apiKey??i.apiKey}),yte(this.config.baseURL,this.config.apiKey),h.debug("LiteLLM Provider initialized",{modelName:this.modelName,provider:this.providerName,baseURL:Yo(this.config.baseURL)})}async ensureModelLimits(){await yte(this.config.baseURL,this.config.apiKey)}getProviderName(){return"litellm"}getDefaultModel(){return cFt()}getFallbackModelName(){return vte}getFallbackModels(){return process.env.LITELLM_FALLBACK_MODELS?.split(",").map(t=>t.trim()).filter(t=>t.length>0)||["openai/gpt-5.4","anthropic/claude-haiku-4-5-20251001","meta-llama/llama-3.1-8b-instruct","google/gemini-2.5-flash"]}useStreamingWireForGenerate(){return process.env.NEUROLINK_LITELLM_SSE_GENERATE!=="false"}adjustBuildBodyOptions(t,r){return dFt(t)&&r.maxTokens!==void 0?(h.shouldLog("debug")&&h.debug("LiteLLM: Skipping maxTokens for Gemini 2.5 model (known compatibility issue)",{modelId:t,requestedMaxTokens:r.maxTokens}),{...r,maxTokens:void 0}):r}onStreamStart(t){const r=aFt.startSpan("neurolink.provider.streamText",{kind:nn.CLIENT,attributes:{"gen_ai.system":"litellm","gen_ai.request.model":t}});let n=!1;const o=()=>{n||(n=!0,r.end())};return{onUsage:i=>{r.setAttribute("gen_ai.usage.input_tokens",i.promptTokens+(i.cacheReadTokens??0)+(i.cacheCreationTokens??0)),r.setAttribute("gen_ai.usage.output_tokens",i.completionTokens);const s=Ls(this.providerName,t,{input:i.promptTokens,output:i.completionTokens,total:i.totalTokens,...i.cacheReadTokens?{cacheReadTokens:i.cacheReadTokens}:{},...i.cacheCreationTokens?{cacheCreationTokens:i.cacheCreationTokens}:{}});s&&s>0&&r.setAttribute("neurolink.cost",s)},onFinish:(i,s)=>{r.setAttribute("gen_ai.response.finish_reason",i||"unknown"),i==="error"&&r.setStatus({code:Ue.ERROR,message:s instanceof Error?s.message:String(s??"stream error")}),o()}}}formatProviderError(t){const r=t;if(typeof r?.message=="string"&&N0e(r.message))return new ry(r.message,{provider:this.providerName,requestedModel:this.modelName,allowedModels:D0e(r.message)});const n=[{match:o=>o.errorName==="TimeoutError"||/timeout/i.test(o.message),errorClass:ai,message:o=>`Request timed out: ${o.message}`},{match:o=>/ECONNREFUSED|Failed to fetch/.test(o.message),errorClass:ai,message:()=>"LiteLLM proxy server not available. Please start the LiteLLM proxy server at "+Yo(this.config.baseURL)},{match:o=>/API_KEY_INVALID|Invalid API key/.test(o.message),errorClass:Wr,message:"Invalid LiteLLM configuration. Please check your LITELLM_API_KEY environment variable."},{match:o=>/rate limit/i.test(o.message),errorClass:Qi,message:"LiteLLM rate limit exceeded. Please try again later."},{match:o=>/model/i.test(o.message)&&/not found/i.test(o.message),errorClass:Jo,message:()=>`Model '${this.modelName}' not available in LiteLLM proxy. Please check your LiteLLM configuration and ensure the model is configured.`},...Ll];return ba(t,n,this.providerName,this.modelName)}async getAvailableModels(){const t=Date.now();if(Bp.modelsCache.length>0&&t-Bp.modelsCacheTime<Bp.MODELS_CACHE_DURATION)return h.debug("[LiteLLMProvider.getAvailableModels] Using cached models",{cacheAge:Math.round((t-Bp.modelsCacheTime)/1e3),modelCount:Bp.modelsCache.length}),Bp.modelsCache;try{const r=await this.fetchModelsFromAPI();if(r.length>0)return Bp.modelsCache=r,Bp.modelsCacheTime=t,r}catch(r){h.warn("[LiteLLMProvider.getAvailableModels] Failed to fetch models from API, using fallback",{error:r instanceof Error?r.message:String(r)})}return this.getFallbackModels()}async fetchModelsFromAPI(){const r=`${Da(this.config.baseURL).replace(/\/v1$/,"")}/v1/models`,n=Ot(),o=new AbortController,i=setTimeout(()=>o.abort(),5e3);try{const s=await n(r,{method:"GET",headers:{Authorization:`Bearer ${this.config.apiKey}`,"Content-Type":"application/json"},signal:o.signal});if(!s.ok)throw new Error(`HTTP ${s.status}: ${s.statusText}`);const a=await s.json();if(!Array.isArray(a.data))throw new Error("Invalid response format: expected data.data array");return a.data.map(l=>l.id).filter(l=>typeof l=="string"&&l.length>0).sort()}catch(s){throw pr(s)?new ai("Request timed out after 5 seconds",this.providerName):s}finally{clearTimeout(i)}}async embed(t,r){if(typeof t!="string"&&t.image)throw new nt(`${this.providerName} does not support image embeddings; provide text input`,this.providerName);const n=typeof t=="string"?t:t.text??"",o=r||process.env.LITELLM_EMBEDDING_MODEL||"gemini-embedding-001",[i]=await this.callEmbeddings(o,[n],"embed");return i}async embedMany(t,r){const n=r||process.env.LITELLM_EMBEDDING_MODEL||"gemini-embedding-001";return this.callEmbeddings(n,t,"embedMany")}async callEmbeddings(t,r,n){const o=`${Da(this.config.baseURL)}/embeddings`,i=Ot(),s=wa(3e4,this.providerName,"generate");try{const a=await i(o,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`},body:JSON.stringify({model:t,input:r.length===1?r[0]:r}),...s?.controller.signal?{signal:s.controller.signal}:{}});if(!a.ok){const u=await a.text().catch(()=>""),d=u?JSON.parse(u):void 0;throw this.formatProviderError(new Error(d?.error?.message||`LiteLLM ${n} failed with status ${a.status}`))}const c=((await a.json()).data??[]).map(u=>u.embedding).filter(u=>Array.isArray(u));if(c.length===0)throw new nt(`LiteLLM ${n} returned no embeddings`,this.providerName);return c}finally{s?.cleanup()}}}}}),mFt={};Z(mFt,{LiteLLMProvider:()=>pFt,clearLiteLLMModelLimitsCache:()=>GJr,ensureLiteLLMModelLimits:()=>yte});var jJr=E({"src/lib/providers/litellm/index.ts"(){"use strict";VJr()}}),vN,hFt=E({"src/lib/providers/openaiCompatible/constants.ts"(){"use strict";vN="gpt-3.5-turbo"}}),wte,Tte,fFt=E({"src/lib/providers/openaiCompatible/utils.ts"(){"use strict";wte=()=>{const e=process.env.OPENAI_COMPATIBLE_BASE_URL,t=process.env.OPENAI_COMPATIBLE_API_KEY;if(!e)throw new Error("OPENAI_COMPATIBLE_BASE_URL environment variable is required. Please set it to your OpenAI-compatible endpoint (e.g., https://api.openrouter.ai/api/v1)");if(!t)throw new Error("OPENAI_COMPATIBLE_API_KEY environment variable is required. Please set it to your API key for the OpenAI-compatible service.");return{baseURL:e,apiKey:t}},Tte=()=>process.env.OPENAI_COMPATIBLE_MODEL||void 0}}),gFt,HJr=E({"src/lib/providers/openaiCompatible/client.ts"(){"use strict";pt(),z(),Nt(),Zs(),zc(),hFt(),fFt(),gFt=class extends Kl{constructor(e,t,r,n){const o=n?.apiKey&&n?.baseURL?{apiKey:n.apiKey,baseURL:n.baseURL}:(()=>{const i=wte();return{apiKey:n?.apiKey??i.apiKey,baseURL:n?.baseURL??i.baseURL}})();super("openai-compatible",e,t,o),h.debug("OpenAI Compatible Provider initialized",{modelName:this.modelName,provider:this.providerName,baseURL:Yo(this.config.baseURL)})}getProviderName(){return"openai-compatible"}getDefaultModel(){return Tte()||""}getFallbackModelName(){return vN}getFallbackModels(){return["gpt-4o","gpt-4o-mini","gpt-4-turbo",vN,"claude-3-5-sonnet","claude-3-haiku","gemini-pro"]}formatProviderError(e){const t=[{match:r=>r.errorName==="TimeoutError"||/Timeout/.test(r.message),errorClass:ai,message:r=>`Request timed out: ${r.message}`},{match:r=>/ECONNREFUSED|Failed to fetch/i.test(r.message),errorClass:ai,message:()=>`OpenAI Compatible endpoint not available. Please check your OPENAI_COMPATIBLE_BASE_URL: ${Yo(this.config.baseURL)}`},{match:r=>r.statusCode===401||/API_KEY_INVALID|Invalid API key|Unauthorized/i.test(r.message),errorClass:Wr,message:"Invalid OpenAI Compatible API key. Please check your OPENAI_COMPATIBLE_API_KEY environment variable."},{match:r=>/model/i.test(r.message)&&(/not found/i.test(r.message)||/does not exist/i.test(r.message)),errorClass:Jo,message:r=>`Model '${r.modelName}' not available on OpenAI Compatible endpoint. Please check available models or use getAvailableModels() to see supported models.`},...Ll];return ba(e,t,this.providerName,this.modelName)}}}}),yFt={};Z(yFt,{FALLBACK_OPENAI_COMPATIBLE_MODEL:()=>vN,OpenAICompatibleProvider:()=>gFt,getDefaultOpenAICompatibleModel:()=>Tte,getOpenAICompatibleConfig:()=>wte});var WJr=E({"src/lib/providers/openaiCompatible/index.ts"(){"use strict";HJr(),hFt(),fFt()}}),tA,vFt=E({"src/lib/providers/openRouter/utils.ts"(){"use strict";Go(),tA=()=>Fi("OPENROUTER_MODEL","anthropic/claude-sonnet-4.5")}}),wFt,wN,TFt,bFt,KJr=E({"src/lib/providers/openRouter/client.ts"(){"use strict";pt(),Ln(),Zs(),et(),z(),Nt(),zc(),Um(),vFt(),wFt="https://openrouter.ai/api/v1",wN=5e3,TFt=()=>{const e=process.env.OPENROUTER_API_KEY;if(!e)throw new Error("OPENROUTER_API_KEY environment variable is required. Get your API key at https://openrouter.ai/keys");return e},bFt=class Ka extends Kl{referer;appName;static modelsCache=[];static modelsCacheTime=0;static MODELS_CACHE_DURATION=600*1e3;static toolCapableModels=new Set;static capabilitiesCached=!1;constructor(t,r,n,o){const i=o?.apiKey?.trim(),s=i&&i.length>0?i:TFt(),a=o?.baseURL?.trim()||process.env.OPENROUTER_BASE_URL?.trim()||wFt;super("openrouter",t,r,{baseURL:a,apiKey:s}),this.referer=process.env.OPENROUTER_REFERER?.trim()||void 0,this.appName=process.env.OPENROUTER_APP_NAME?.trim()||void 0,h.debug("OpenRouter Provider initialized",{modelName:this.modelName,providerName:this.providerName,baseURL:Yo(this.config.baseURL)})}getProviderName(){return"openrouter"}getDefaultModel(){return tA()}formatProviderError(t){const r=[{match:n=>n.errorName==="TimeoutError"||/Timeout/.test(n.message),errorClass:ai,message:n=>`Request timed out: ${n.message}`},{match:n=>/ECONNREFUSED|Failed to fetch/.test(n.message),errorClass:ai,message:"OpenRouter API not available. Please check your network connection and try again."},{match:n=>/API_KEY_INVALID|Invalid API key|invalid_api_key|Unauthorized/.test(n.message),errorClass:Wr,message:"Invalid OpenRouter API key. Please check your OPENROUTER_API_KEY environment variable. Get your key at https://openrouter.ai/keys"},{match:n=>/rate limit/.test(n.message),errorClass:Qi,message:"OpenRouter rate limit exceeded. Please try again later or upgrade your account at https://openrouter.ai/credits"},{match:n=>/model/.test(n.message)&&/not found/.test(n.message),errorClass:Jo,message:()=>`Model '${this.modelName}' not available on OpenRouter. Browse available models at https://openrouter.ai/models`},{match:n=>/insufficient_credits/.test(n.message),errorClass:nt,message:"Insufficient OpenRouter credits. Add credits at https://openrouter.ai/credits"},{match:n=>/No endpoints found/.test(n.message),errorClass:Jo,message:()=>`No endpoints found for model '${this.modelName}' on OpenRouter. The model may be temporarily unavailable or does not support the requested parameters. Try a different model or check availability at https://openrouter.ai/models`},{match:n=>/tool use|tool_use|function_call|tools are not supported/.test(n.message),errorClass:nt,message:()=>`Model '${this.modelName}' does not support tool calling. Use a tool-capable model like:
|
|
1162
1162
|
\u2022 google/gemini-2.0-flash-exp:free (free)
|
|
1163
1163
|
\u2022 meta-llama/llama-3.3-70b-instruct:free (free)
|
|
1164
1164
|
\u2022 anthropic/claude-3.7-sonnet (paid)
|
|
@@ -1320,7 +1320,7 @@ ${o.join(`
|
|
|
1320
1320
|
`);this.buffer=n.pop()||"";for(const o of n){const i=o.trim();if(!i)continue;const s=this.parseJSON(i);if(s&&er(s)){const a=this.parseLlamaChunk(s);a&&r.push(a)}}return r}parseLlamaChunk(e){if(Array.isArray(e.choices)&&e.choices[0]){const t=e.choices[0];if(t.delta){const r=t.delta,n=String(r.content||""),o=t.finish_reason,i={content:n,done:o!=null,finishReason:this.mapFinishReason(o||null),usage:e.usage?this.parseLlamaUsage(e.usage):void 0};if(n&&this.structuredParser&&(i.structuredOutput=this.parseStructuredContent(n)),Array.isArray(r.tool_calls)&&r.tool_calls[0]){const s=r.tool_calls[0];i.toolCall=this.parseStreamingToolCall(s),o==="function_call"&&i.toolCall.arguments&&(i.toolCall.complete=!0)}return i}if(t.text!==void 0)return{content:String(t.text),done:t.finish_reason!==null,finishReason:this.mapFinishReason(t.finish_reason),usage:e.usage?this.parseLlamaUsage(e.usage):void 0}}if(e.content!==void 0)return{content:String(e.content),done:!!e.done,finishReason:this.mapFinishReason(e.finish_reason),usage:e.usage?this.parseLlamaUsage(e.usage):void 0};if(e.error){const t=e.error,r=NFt(t);throw new zo(`LLaMA streaming error: ${r}`,{code:"MODEL_ERROR",statusCode:500,retryable:!1})}return null}parseToolCallArguments(e,t){if(typeof e.arguments=="string"){const r=TXr(e.arguments);r.complete?(t.arguments=r.arguments,t.complete=!0):r.argumentsDelta!==void 0&&(t.argumentsDelta=r.argumentsDelta)}else if(e.arguments!==void 0)try{t.arguments=JSON.stringify(e.arguments),t.complete=!0}catch(r){h.warn("Failed to stringify tool arguments",{args:e.arguments,error:DFt(r)}),t.arguments="{}",t.complete=!0}else t.arguments="{}",t.complete=!0}parseStreamingToolCall(e){const t={id:String(e.id||`call_${Qe()}`),type:"function"},r=e.function;return r?.name&&(t.name=String(r.name)),r?.arguments&&this.parseToolCallArguments(r,t),t}parseLlamaUsage(e){const t=Number(e.prompt_tokens)||0,r=Number(e.completion_tokens)||0;return{promptTokens:t,completionTokens:r,total:Number(e.total_tokens)||t+r}}mapFinishReason(e){switch(e){case"stop":return"stop";case"length":return"length";case"function_call":return"tool-calls";case"content_filter":return"content-filter";default:return e?"unknown":void 0}}},Ate=class extends EN{expectedFormat="json";constructor(e="json"){super(),this.expectedFormat=e}getName(){return`Custom ${this.expectedFormat.toUpperCase()} Parser`}parse(e){const t=this.decodeChunk(e);return this.buffer+=t,this.expectedFormat==="json"?this.parseJSONFormat():this.parseTextFormat()}parseJSONFormat(){const e=[];let t=0;for(;t<this.buffer.length;)try{const r=this.buffer.substring(t),n=JSON.parse(r),o={content:n.text||n.generated_text||n.output||String(n),done:!0,finishReason:"stop"};e.push(o),this.buffer="",this.isCompleted=!0;break}catch{const r=this.buffer.indexOf(`
|
|
1321
1321
|
`,t);if(r===-1)break;const n=this.buffer.substring(t,r);if(n.trim()){const o=this.parseJSON(n.trim());if(o&&er(o)){const i=this.parseCustomChunk(o);i&&e.push(i)}}t=r+1}return t>0&&(this.buffer=this.buffer.substring(t)),e}parseTextFormat(){if(this.buffer){const e=this.buffer;return this.buffer="",[{content:e,done:!1}]}return[]}parseCustomChunk(e){const t=e.text||e.generated_text||e.output||e.response||e.content||(typeof e=="string"?e:JSON.stringify(e));return{content:String(t),done:!!(e.done||e.finished||e.complete),finishReason:e.finish_reason||e.status==="complete"?"stop":void 0,usage:e.usage||e.tokens?this.parseCustomUsage(e):void 0}}parseCustomUsage(e){const t=e.usage||e.tokens||{},r=Number(t.prompt_tokens||t.input_tokens)||0,n=Number(t.completion_tokens||t.output_tokens)||0;return{promptTokens:r,completionTokens:n,total:Number(t.total_tokens)||r+n}}},UFt=class{static createParser(e,t){switch(e){case"sse":return new FFt;case"jsonl":return new $Ft;case"chunked":{const r=t?.format;return new Ate(r||"json")}default:return new Ate("text")}}static getSupportedProtocols(){return["sse","jsonl","chunked","text"]}}}});async function bXr(e,t,r,n={}){const o=hXr(r);try{h.debug("Detecting streaming capabilities",{endpointName:t});const i=await o.detectStreamingCapability(t);if(!i.supported)return h.info("Streaming not supported, falling back to synthetic stream",{endpointName:t,modelType:i.modelType}),zFt(e,n);h.info("Creating streaming response",{endpointName:t,protocol:i.protocol,modelType:i.modelType,confidence:i.confidence});const s=UFt.createParser(i.protocol);return _Xr(e,s,i,n)}catch(i){return h.error("Failed to create streaming response",{endpointName:t,error:i instanceof Error?i.message:String(i)}),zFt(e,n)}}async function _Xr(e,t,r,n){return new kte({async start(o){const i=e[Symbol.asyncIterator]();let s="",a;try{for(t.reset();;){if(n.abortSignal?.aborted){try{await i.return?.()}catch{}throw new zo("Stream aborted by user",{code:"NETWORK_ERROR",statusCode:499,retryable:!1})}const{done:l,value:c}=await i.next();if(l){!a&&s&&(a=SN(n.prompt??"",s));const d={type:"finish",finishReason:"stop",usage:Cte(a)};o.enqueue(d),n.onComplete?.(a||{promptTokens:0,completionTokens:0,total:0}),o.close();break}const u=t.parse(c);for(const d of u){if(d.content&&(s+=d.content),d.toolCall){const p={type:"tool-call-delta",toolCallType:"function",toolCallId:d.toolCall.id,toolName:d.toolCall.name||"",argsTextDelta:d.toolCall.argumentsDelta||""};if(o.enqueue(p),n.onChunk?.(d),d.toolCall.complete&&d.toolCall.arguments){const m={type:"tool-call",toolCallType:"function",toolCallId:d.toolCall.id,toolName:d.toolCall.name||"",args:JSON.parse(d.toolCall.arguments)};o.enqueue(m)}continue}if(d.toolResult){const p={type:"tool-result",toolCallId:d.toolResult.toolCallId,toolName:d.toolResult.toolName,result:d.toolResult.result,args:{}};o.enqueue(p),n.onChunk?.(d);continue}if(d.structuredOutput){const p={type:"object-delta",objectDelta:d.structuredOutput.partialObject||{},objectPath:d.structuredOutput.currentPath||"",isComplete:d.structuredOutput.complete||!1,validationErrors:d.structuredOutput.validationErrors||[]};if(o.enqueue(p),n.onChunk?.(d),d.structuredOutput.complete&&d.structuredOutput.partialObject){const m={type:"object",object:d.structuredOutput.partialObject};o.enqueue(m)}continue}if(d.content){const p={type:"text-delta",textDelta:d.content};o.enqueue(p),n.onChunk?.(d)}if(t.isComplete(d)){a=t.extractUsage(d)||SN(n.prompt??"",s);const p={type:"finish",finishReason:d.finishReason||"stop",usage:Cte(a)};o.enqueue(p),n.onComplete?.(a),o.close();return}}}}catch(l){const c=mp(l);h.error("Streaming error",{error:c.message,modelType:r.modelType,protocol:r.protocol}),n.onError?.(c),o.error(c)}}})}async function zFt(e,t){return new kte({async start(r){try{const n=[],o=e[Symbol.asyncIterator]();for(;;){const{done:g,value:y}=await o.next();if(g)break;n.push(y)}let i=0;for(const g of n)i+=g.length;const s=new Uint8Array(i);let a=0;for(const g of n)s.set(g,a),a+=g.length;const l=new TextDecoder().decode(s),c=JSON.parse(l),u=c.generated_text||c.text||c.output||c[0]?.generated_text||String(c),d=u.split(/\s+/),p=Math.max(1,Math.floor(d.length/10));for(let g=0;g<d.length;g+=p){const y=d.slice(g,g+p).join(" "),v=g===0?y:" "+y,T={type:"text-delta",textDelta:v};r.enqueue(T),t.onChunk?.({content:v,done:!1}),await new Promise(b=>setTimeout(b,GFt))}const m=SN(t.prompt||"",u),f={type:"finish",finishReason:"stop",usage:Cte(m)};r.enqueue(f),t.onComplete?.(m),r.close()}catch(n){const o=mp(n);t.onError?.(o),r.error(o)}}})}function Cte(e){const t=e?.promptTokens??0,r=e?.completionTokens??0;return{inputTokens:t,outputTokens:r,totalTokens:e?.total||t+r}}function EXr(e){const t=Array.isArray(e)?e[0]:e;if(!t||typeof t!="object")return;const r=t.usage??t.tokens;if(r&&typeof r=="object"){const i=Number(r.prompt_tokens??r.input_tokens)||0,s=Number(r.completion_tokens??r.output_tokens)||0;if(i>0||s>0)return{promptTokens:i,completionTokens:s,total:Number(r.total_tokens)||i+s}}const o=t.details?.tokens;if(o&&typeof o=="object"){const i=Number(o.input)||0,s=Number(o.generated)||0;if(i>0||s>0)return{promptTokens:i,completionTokens:s,total:Number(o.total)||i+s}}}function SN(e,t){const r=Vt(e,"sagemaker"),n=Vt(t,"sagemaker");return{promptTokens:r,completionTokens:n,total:r+n}}var GFt,SXr=E({"src/lib/providers/sagemaker/streaming.ts"(){"use strict";mXr(),rA(),z(),di(),fXr(),BFt(),GFt=50}});function kXr(e,t=10,r=1){return new qFt({initialConcurrency:e,maxConcurrency:t,minConcurrency:r})}var qFt,xXr=E({"src/lib/providers/sagemaker/adaptive-semaphore.ts"(){"use strict";z(),qFt=class{count;waiters=[];currentConcurrency;activeRequests=0;completedCount=0;errorCount=0;responseTimes=[];maxConcurrency;minConcurrency;constructor(e){this.currentConcurrency=e.initialConcurrency,this.count=e.initialConcurrency,this.maxConcurrency=e.maxConcurrency,this.minConcurrency=e.minConcurrency,h.debug("AdaptiveSemaphore initialized",{initialConcurrency:e.initialConcurrency,maxConcurrency:e.maxConcurrency,minConcurrency:e.minConcurrency})}async acquire(){return new Promise(e=>{this.count>0?(this.count--,this.activeRequests++,e()):this.waiters.push(()=>{this.count--,this.activeRequests++,e()})})}release(){if(this.activeRequests--,this.waiters.length>0){const e=this.waiters.shift();e&&(this.count++,e())}else this.count++}recordSuccess(e){this.completedCount++,this.responseTimes.push(e),this.responseTimes.length>10&&this.responseTimes.shift(),this.adjustConcurrencyBasedOnPerformance(e,!1)}recordError(e){this.errorCount++,e&&(this.responseTimes.push(e),this.responseTimes.length>10&&this.responseTimes.shift()),this.adjustConcurrencyBasedOnPerformance(e||0,!0)}adjustConcurrency(e){const t=Math.max(this.minConcurrency,Math.min(this.maxConcurrency,e)),r=t-(this.currentConcurrency-this.count);for(this.count+=r,this.currentConcurrency=t,h.debug("Concurrency adjusted",{newConcurrency:t,previousConcurrency:this.currentConcurrency-r,availableCount:this.count,activeRequests:this.activeRequests});this.count>0&&this.waiters.length>0;){const n=this.waiters.shift();n&&n()}}getMetrics(){const e=this.responseTimes.length>0?this.responseTimes.reduce((t,r)=>t+r,0)/this.responseTimes.length:0;return{activeRequests:this.activeRequests,currentConcurrency:this.currentConcurrency,completedCount:this.completedCount,errorCount:this.errorCount,averageResponseTime:e,waitingCount:this.waiters.length}}resetMetrics(){this.completedCount=0,this.errorCount=0,this.responseTimes=[]}adjustConcurrencyBasedOnPerformance(e,t){const r=this.getMetrics();if(t){this.currentConcurrency>this.minConcurrency&&(this.adjustConcurrency(Math.max(this.minConcurrency,this.currentConcurrency-1)),h.warn("Reduced concurrency due to error",{newConcurrency:this.currentConcurrency,errorCount:this.errorCount}));return}if(this.completedCount<3)return;const n=2e3;e<n&&r.averageResponseTime<n&&this.currentConcurrency<this.maxConcurrency?(this.adjustConcurrency(Math.min(this.maxConcurrency,this.currentConcurrency+1)),h.debug("Increased concurrency due to fast responses",{newConcurrency:this.currentConcurrency,averageResponseTime:r.averageResponseTime})):e>5e3&&this.currentConcurrency>this.minConcurrency&&(this.adjustConcurrency(Math.max(this.minConcurrency,this.currentConcurrency-1)),h.debug("Decreased concurrency due to slow responses",{newConcurrency:this.currentConcurrency,responseTime:e}))}isIdle(){return this.activeRequests===0&&this.waiters.length===0}getCurrentConcurrency(){return this.currentConcurrency}getActiveRequestCount(){return this.activeRequests}getWaitingRequestCount(){return this.waiters.length}}}});function AXr(e,t){const r=Math.max(10,Math.min(jFt,VFt*(1e3/Math.max(e,100))));return t>20?Math.max(10,r*.5):t>10?Math.max(15,r*.7):r}async function*CXr(e){if(!e)return;const t=e.split(/\s+/),r=Math.max(1,Math.floor(t.length/10)),n=Math.ceil(t.length/r),o=AXr(e.length,n);for(let i=0;i<t.length;i+=r){const s=t.slice(i,i+r).join(" "),a=i===0?s:" "+s;i>0&&await new Promise(l=>setTimeout(l,o)),yield a}}var VFt,jFt,HFt,WFt,KFt,JFt,IXr=E({"src/lib/providers/sagemaker/language-model.ts"(){"use strict";$t(),AFt(),rA(),SXr(),xXr(),z(),et(),VFt=process.env.SAGEMAKER_BASE_STREAMING_DELAY_MS?parseInt(process.env.SAGEMAKER_BASE_STREAMING_DELAY_MS,10):50,jFt=process.env.SAGEMAKER_MAX_STREAMING_DELAY_MS?parseInt(process.env.SAGEMAKER_MAX_STREAMING_DELAY_MS,10):200,HFt=5,WFt=10,KFt=1,JFt=class{specificationVersion="v2";provider="sagemaker";modelId;supportsStreaming=!0;defaultObjectGenerationMode="json";supportedUrls={};client;config;modelConfig;constructor(e,t,r){this.modelId=e,this.config=t,this.modelConfig=r,this.client=new Ste(t),h.debug("SageMaker Language Model initialized",{modelId:this.modelId,endpointName:this.modelConfig.endpointName,provider:this.provider,specificationVersion:this.specificationVersion})}readAbortSignal(e){const t=e.abortSignal;return t instanceof AbortSignal?t:void 0}async doGenerate(e){const t=Date.now();try{const r=this.extractPromptText(e);h.debug("SageMaker doGenerate called",{endpointName:this.modelConfig.endpointName,promptLength:r.length,maxTokens:e.maxTokens,temperature:e.temperature});const n=this.convertToSageMakerRequest(e),o=await this.client.invokeEndpoint({EndpointName:this.modelConfig.endpointName,Body:JSON.stringify(n),ContentType:"application/json",Accept:"application/json",abortSignal:this.readAbortSignal(e)}),i=JSON.parse(new TextDecoder().decode(o.Body)),s=this.extractTextFromResponse(i),a=this.extractToolCallsFromResponse(i),l=EXr(i)??SN(r,s);let c="stop";a&&a.length>0?c="tool-calls":i.finish_reason&&(c=this.mapSageMakerFinishReason(i.finish_reason));const u=Date.now()-t;h.debug("SageMaker doGenerate completed",{duration:u,outputLength:s.length,usage:l,toolCallsCount:a?.length||0,finishReason:c});const d={text:s,usage:{inputTokens:l.promptTokens,outputTokens:l.completionTokens,totalTokens:l.total},finishReason:c,rawCall:{rawPrompt:e.prompt,rawSettings:{maxTokens:e.maxTokens,temperature:e.temperature,topP:e.topP,endpointName:this.modelConfig.endpointName}},rawResponse:{headers:{"content-type":o.ContentType||"application/json","invoked-variant":o.InvokedProductionVariant||""}},request:{body:JSON.stringify(n)}};a&&a.length>0&&(d.toolCalls=a);const p=n.response_format;if(p&&(p.type==="json_object"||p.type==="json_schema"))try{const m=JSON.parse(s);d.object=m,h.debug("Extracted structured data from response",{responseFormat:p.type,hasObject:!!d.object})}catch(m){h.warn("Failed to parse structured response as JSON",{error:m instanceof Error?m.message:String(m),responseText:s.substring(0,200)})}return d}catch(r){const n=Date.now()-t;throw h.error("SageMaker doGenerate failed",{duration:n,error:r instanceof Error?r.message:String(r)}),pr(r)?r:mp(r,this.modelConfig.endpointName)}}async doStream(e){try{const t=this.extractPromptText(e);h.debug("SageMaker doStream called",{endpointName:this.modelConfig.endpointName,promptLength:t.length});const r=this.convertToSageMakerRequest(e),n={...r,parameters:{...typeof r.parameters=="object"&&r.parameters!==null?r.parameters:{},stream:!0}};h.debug("Attempting streaming generation",{endpointName:this.modelConfig.endpointName,hasStreamingFlag:!0});try{const o=await this.client.invokeEndpointWithStreaming({EndpointName:this.modelConfig.endpointName,Body:JSON.stringify(n),ContentType:this.modelConfig.contentType||"application/json",Accept:this.modelConfig.accept||"application/json",abortSignal:this.readAbortSignal(e)});return{stream:await bXr(o.Body,this.modelConfig.endpointName,this.config,{prompt:t,onChunk:s=>{h.debug("Streaming chunk received",{contentLength:s.content?.length||0,done:s.done})},onComplete:s=>{h.debug("Streaming completed",{usage:s,endpointName:this.modelConfig.endpointName})},onError:s=>{h.error("Streaming error",{error:s.message,endpointName:this.modelConfig.endpointName})}}),rawCall:{rawPrompt:r,rawSettings:this.modelConfig},rawResponse:{headers:{"Content-Type":o.ContentType||"application/json","X-Invoked-Production-Variant":o.InvokedProductionVariant||"unknown"}}}}catch(o){if(pr(o))throw o;h.warn("Streaming failed, falling back to non-streaming",{endpointName:this.modelConfig.endpointName,error:o instanceof Error?o.message:String(o)});const i=await this.doGenerate(e);return{stream:new ReadableStream({async start(a){try{const l=CXr(i.text);for await(const c of l)a.enqueue({type:"text-delta",textDelta:c});a.enqueue({type:"finish",finishReason:i.finishReason,usage:i.usage}),a.close()}catch(l){a.error(l)}}}),rawCall:i.rawCall,rawResponse:i.rawResponse,request:i.request,warnings:[...i.warnings||[],{type:"other",message:"Streaming not supported, using synthetic stream"}]}}}catch(t){throw h.error("SageMaker doStream failed",{error:t instanceof Error?t.message:String(t)}),pr(t)?t:mp(t,this.modelConfig.endpointName)}}convertToSageMakerRequest(e){const t=this.extractPromptText(e),r={inputs:t,parameters:{...e.maxTokens!==void 0?{max_new_tokens:e.maxTokens}:{},temperature:e.temperature??.7,top_p:e.topP??.9,stop:e.stopSequences||[]}},n=e.tools;if(n&&Array.isArray(n)&&n.length>0){r.tools=this.convertToolsToSageMakerFormat(n);const i=e.toolChoice;i&&(r.tool_choice=this.convertToolChoiceToSageMakerFormat(i)),h.debug("Added tool support to SageMaker request",{toolCount:n.length,toolChoice:i})}const o=e.responseFormat;return o&&(r.response_format=this.convertResponseFormatToSageMakerFormat(o),h.debug("Added structured output support to SageMaker request",{responseFormat:o.type})),h.debug("Converted to SageMaker request format",{inputLength:t.length,parameters:r.parameters,hasTools:!!r.tools}),r}convertToolsToSageMakerFormat(e){const t=[];for(const r of e){if(r.type!=="function"){h.debug("SageMaker: dropping tool with no SageMaker equivalent",{toolType:r.type,toolName:r.name});continue}t.push({type:"function",function:{name:r.name,description:r.description||"",parameters:r.inputSchema||{}}})}return t}convertToolChoiceToSageMakerFormat(e){if(typeof e=="string")return e;switch(e.type){case"auto":case"none":case"required":return e.type;case"tool":return{type:"function",function:{name:e.toolName}};default:return"auto"}}convertResponseFormatToSageMakerFormat(e){return e.type==="json_object"?{type:"json_object",schema:e.schema||void 0}:e.type==="json_schema"?{type:"json_schema",json_schema:{name:e.json_schema?.name||"response",description:e.json_schema?.description||"Generated response",schema:e.json_schema?.schema||{}}}:{type:"text"}}extractPromptText(e){const t=e.messages;if(t&&Array.isArray(t))return t.filter(n=>n.role&&n.content).map(n=>typeof n.content=="string"?`${n.role}: ${n.content}`:`${n.role}: ${JSON.stringify(n.content)}`).join(`
|
|
1322
1322
|
`);const r=e.prompt;return typeof r=="string"?r:Array.isArray(r)?r.filter(n=>n.role&&n.content).map(n=>typeof n.content=="string"?`${n.role}: ${n.content}`:`${n.role}: ${JSON.stringify(n.content)}`).join(`
|
|
1323
|
-
`):String(r)}extractTextFromResponse(e){if(typeof e=="string")return e;if(e.generated_text)return e.generated_text;if(e.outputs)return e.outputs;if(e.text)return e.text;if(Array.isArray(e)&&e[0]?.generated_text)return e[0].generated_text;if(e.choices&&Array.isArray(e.choices)){const t=e.choices[0];if(typeof t?.message?.content=="string")return t.message.content;if(t?.message?.tool_calls?.length)return""}return JSON.stringify(e)}extractToolCallsFromResponse(e){if(e.choices&&Array.isArray(e.choices)){const t=e.choices[0];if(t?.message?.tool_calls)return t.message.tool_calls.map(r=>({type:"function",id:String(r.id||`call_${Qe()}`),function:{name:String(r.function.name),arguments:String(r.function.arguments)}}))}if(e.tool_calls&&Array.isArray(e.tool_calls))return e.tool_calls;if(e.content&&Array.isArray(e.content)){const t=e.content.filter(r=>r.type==="tool_use");if(t.length>0)return t.map(r=>({type:"function",id:String(r.id||`call_${Qe()}`),function:{name:String(r.name),arguments:JSON.stringify(r.input||{})}}))}}mapSageMakerFinishReason(e){switch(e?.toLowerCase()){case"stop":case"end_turn":case"stop_sequence":return"stop";case"length":case"max_tokens":case"max_length":return"length";case"content_filter":case"content_filtered":return"content-filter";case"tool_calls":case"function_call":return"tool-calls";case"error":return"error";default:return"unknown"}}getModelInfo(){return{modelId:this.modelId,provider:this.provider,specificationVersion:this.specificationVersion,endpointName:this.modelConfig.endpointName,modelType:this.modelConfig.modelType,region:this.config.region}}async testConnectivity(){try{return{success:!!(await this.doGenerate({inputFormat:"messages",mode:{type:"regular"},prompt:[{role:"user",content:[{type:"text",text:"Hello"}]}],maxTokens:10})).text}}catch(e){return{success:!1,error:e instanceof Error?e.message:String(e)}}}async doBatchGenerate(e,t){try{h.debug("SageMaker batch generate called",{batchSize:e.length,endpointName:this.modelConfig.endpointName});const r=await this.processPromptsInParallel(e,t);return h.debug("SageMaker batch generate completed",{batchSize:e.length,successCount:r.length}),r}catch(r){throw h.error("SageMaker batch generate failed",{error:r instanceof Error?r.message:String(r),batchSize:e.length}),pr(r)?r:mp(r,this.modelConfig.endpointName)}}async processPromptsInParallel(e,t){const r=Math.min(this.modelConfig.initialConcurrency??HFt,e.length),n=this.modelConfig.maxConcurrency??WFt,o=this.modelConfig.minConcurrency??KFt,i=new Array(e.length),s=[],a=kXr(r,n,o),l=async(d,p)=>{await a.acquire();const m=Date.now();try{const f=await this.doGenerate({inputFormat:"messages",mode:{type:"regular"},prompt:[{role:"user",content:[{type:"text",text:d}]}],maxTokens:t?.maxTokens,temperature:t?.temperature,topP:t?.topP}),g=Date.now()-m;i[p]={text:f.text||"",usage:{promptTokens:f.usage.inputTokens??0,completionTokens:f.usage.outputTokens??0,total:f.usage.totalTokens??(f.usage.inputTokens??0)+(f.usage.outputTokens??0)},finishReason:f.finishReason,index:p},a.recordSuccess(g)}catch(f){s.push({index:p,error:f instanceof Error?f:new Error(String(f))});const g=Date.now()-m;a.recordError(g),i[p]={text:"",usage:{promptTokens:0,completionTokens:0,total:0},finishReason:"error",index:p}}finally{a.release()}},c=e.map((d,p)=>l(d,p));await Promise.all(c);const u=a.getMetrics();return h.debug("Parallel batch processing completed",{totalPrompts:e.length,successCount:u.completedCount,errorCount:u.errorCount,finalConcurrency:u.currentConcurrency,errorRate:u.errorCount/e.length,averageResponseTime:u.averageResponseTime}),s.length>0&&h.warn("Batch processing encountered errors",{errorCount:s.length,sampleErrors:s.slice(0,3).map(d=>({index:d.index,message:d.error.message}))}),i.map(({text:d,usage:p,finishReason:m})=>({text:d,usage:p,finishReason:m}))}getModelCapabilities(){return{...this.getModelInfo(),capabilities:{streaming:!0,toolCalling:!0,structuredOutput:!0,batchInference:!0,supportedResponseFormats:["text","json_object","json_schema"],supportedToolTypes:["function"],maxBatchSize:100,adaptiveConcurrency:!0,errorRecovery:!0}}}}}}),XFt={};Z(XFt,{AmazonSageMakerProvider:()=>Ite,default:()=>YFt});var Ite,YFt,RXr=E({"src/lib/providers/amazonSagemaker.ts"(){"use strict";pl(),Jv(),z(),If(),vm(),zl(),ss(),kd(),Zo(),vZ(),Xr(),Sr(),eXr(),rA(),IXr(),Ite=class extends Ma{sagemakerModel;sagemakerConfig;modelConfig;constructor(e,t,r,n,o){super(e,"sagemaker",n);try{const i=YJr(o?.region??r,{...o?.region!==void 0&&{region:o.region},...o?.accessKeyId!==void 0&&{accessKeyId:o.accessKeyId},...o?.secretAccessKey!==void 0&&{secretAccessKey:o.secretAccessKey},...o?.sessionToken!==void 0&&{sessionToken:o.sessionToken},...o?.endpoint!==void 0&&{endpoint:o.endpoint}});this.sagemakerConfig={...i,...o?.region!==void 0&&{region:o.region},...o?.accessKeyId!==void 0&&{accessKeyId:o.accessKeyId},...o?.secretAccessKey!==void 0&&{secretAccessKey:o.secretAccessKey},...o?.sessionToken!==void 0&&{sessionToken:o.sessionToken},...o?.endpoint!==void 0&&{endpoint:o.endpoint}},this.modelConfig=ZJr(t||SFt()),this.sagemakerModel=new JFt(this.modelName,this.sagemakerConfig,this.modelConfig),h.debug("Amazon SageMaker Provider initialized",{modelName:this.modelName,endpointName:this.modelConfig.endpointName,region:this.sagemakerConfig.region,provider:this.providerName})}catch(i){throw h.error("Failed to initialize SageMaker provider",{error:i instanceof Error?i.message:String(i),modelName:e,endpointName:t}),mp(i)}}getProviderName(){return"sagemaker"}getDefaultModel(){return QJr()}getAISDKModel(){return this.sagemakerModel}async generate(e,t){await this.ensureModelLimits();const r=this.normalizeTextOptions(e);if($d(r,this.modelName)!=="text")return super.generate(r,t);this.validateOptions(r);const n=await this.getToolsForStream(r),o="disableInternalFallback"in r&&r.disableInternalFallback===!0;return this.runGenerateWithModelFallback(()=>this.withTurnTimeout({...r,tools:n},this.getDescriptorGenerateMs(),i=>this.executeNativeGenerate(i)),o,r)}async executeNativeGenerate(e){const t=Date.now(),r=await this.getAISDKModelWithMiddleware(e);if(!ex(r))throw this.handleProviderError(new Error("sagemaker: model handle exposes no doGenerate()"));const n=async p=>{const m=p.responseFormat,f=await r.doGenerate({...p,...p.maxOutputTokens!==void 0?{maxTokens:p.maxOutputTokens}:{},...m?.type==="json"?{responseFormat:m.schema?{type:"json_schema",json_schema:{name:"response",schema:m.schema}}:{type:"json_object"}}:{}});if(Array.isArray(f.content))return f;const g=[];typeof f.text=="string"&&f.text&&g.push({type:"text",text:f.text}),typeof f.reasoning=="string"&&f.reasoning&&g.push({type:"reasoning",text:f.reasoning});for(const v of Array.isArray(f.toolCalls)?f.toolCalls:[]){if(typeof v!="object"||v===null)continue;const T=v,b=T.function;typeof T.id=="string"&&typeof b?.name=="string"&&g.push({type:"tool-call",toolCallId:T.id,toolName:b.name,input:b.arguments??"{}"})}const y=f.usage;return{...f,content:g,usage:{inputTokens:{total:typeof y?.inputTokens=="number"?y.inputTokens:0},outputTokens:{total:typeof y?.outputTokens=="number"?y.outputTokens:0}}}},i=!e.disableTools&&this.supportsTools()?e.tools||{}:{},s=Object.entries(i).map(([p,m])=>{const f=m;return{type:"function",name:p,description:f.description??"",inputSchema:f.inputSchema?qo(f.inputSchema):{type:"object",properties:{}}}}),a=e.schema?{type:"json",schema:qo(e.schema)}:void 0,l=await this.buildMessagesForStream(e),c=[],u=await BO({doGenerate:n,conversation:l,...a?{responseFormat:a}:{},...s.length>0?{tools:s}:{},toolsRecord:i,maxSteps:e.maxSteps||ts,...e.maxTokens?{maxOutputTokens:e.maxTokens}:{},...e.temperature!==void 0?{temperature:e.temperature}:{},...e.abortSignal?{abortSignal:e.abortSignal}:{},...e.toolTimeoutMs!==void 0?{toolTimeoutMs:e.toolTimeoutMs}:{},runStep:p=>Py(p,void 0,"sagemaker generate",void 0,e.abortSignal).catch(m=>{throw this.handleProviderError(m)})},c),d={content:u.text,provider:this.providerName,model:this.modelName,finishReason:u.finishReason,usage:{input:u.inputTokens,output:u.outputTokens,total:u.inputTokens+u.outputTokens},responseTime:Date.now()-t,...u.reasoning?{reasoning:u.reasoning}:{},toolsUsed:u.toolsUsed,toolCalls:HH(c),toolExecutions:Df(e,Bd(c)),enhancedWithTools:u.toolsUsed.length>0};return this.finalizeNativeGenerate(d,e,t)}async doStream(e){return mt({name:"neurolink.provider.sagemaker.stream",tracer:Be.stream,attributes:{"provider.name":"sagemaker","model.name":this.modelName,"sagemaker.endpoint":this.modelConfig.endpointName,"sagemaker.region":this.sagemakerConfig.region}},async()=>{try{const t=await this.buildMessagesForStream(e),r=await this.sagemakerModel.doStream({prompt:t,maxTokens:e.maxTokens,temperature:e.temperature});let n,o;const i=new Promise(l=>{n=l}),s=new Promise(l=>{o=l}),a=Kv();return(async()=>{const l=r.stream.getReader();let c=!1;try{for(;;){const{done:u,value:d}=await l.read();if(u)break;const p=d;if(p.type==="text-delta"&&p.textDelta){a.push({content:p.textDelta});continue}p.type==="finish"&&(c=!0,n(p.finishReason??"stop"),o({inputTokens:p.usage?.inputTokens??p.usage?.promptTokens??0,outputTokens:p.usage?.outputTokens??p.usage?.completionTokens??0}))}a.close()}catch(u){a.error(u)}finally{l.releaseLock(),c||(n("unknown"),o({inputTokens:0,outputTokens:0}))}})(),{stream:a.iterable,finishReason:i,usage:s,warnings:(r.warnings??[]).map(l=>l.message??String(l))}}catch(t){throw this.handleProviderError(t)}})}formatProviderError(e){return e instanceof zo?e:e instanceof Error&&e.name==="TimeoutError"?new zo("SageMaker request timed out. Consider increasing timeout.",{code:"NETWORK_ERROR",statusCode:408,cause:e,endpoint:this.modelConfig.endpointName}):mp(e,this.modelConfig.endpointName)}getSageMakerInfo(){return{endpointName:this.modelConfig.endpointName,modelType:this.modelConfig.modelType||"custom",region:this.sagemakerConfig.region,configured:!!(this.sagemakerConfig.accessKeyId&&this.sagemakerConfig.secretAccessKey)}}async testConnection(){try{return!this.sagemakerConfig.accessKeyId||!this.sagemakerConfig.secretAccessKey?{connected:!1,error:"AWS credentials not configured"}:!this.modelConfig.endpointName||this.modelConfig.endpointName==="default-endpoint"?{connected:!1,error:"SageMaker endpoint not configured"}:{connected:!0}}catch(e){return{connected:!1,error:e instanceof Error?e.message:String(e)}}}async getModel(){return this.getAISDKModel()}async testConnectivity(){const e=this.sagemakerModel;return e.testConnectivity?await e.testConnectivity():{success:!1,error:"Test method not available"}}getModelCapabilities(){const e=this.sagemakerModel;return e.getModelCapabilities?e.getModelCapabilities():{capabilities:{streaming:!0,toolCalling:!0,structuredOutput:!0,batchInference:!0,supportedResponseFormats:["text","json_object"],supportedToolTypes:["function"],maxBatchSize:10}}}},YFt=Ite}}),ZFt,Rte,Pte,QFt,Mte,Ote,e$t,t$t,Dte,r$t,PXr=E({"src/lib/providers/nvidiaNim/client.ts"(){"use strict";pt(),Zs(),z(),Nt(),Go(),zc(),Fl(),ZFt=["unsupported","not supported","does not support","unrecognized","unknown field","unknown parameter","unknown argument","invalid field","invalid parameter","invalid argument"],Rte=(e,t)=>{if(!e)return!1;const r=e.toLowerCase(),n=t.toLowerCase();let o=r.indexOf(n);for(;o!==-1;){const i=Math.max(0,o-80),s=Math.min(r.length,o+n.length+80),a=r.slice(i,s);if(ZFt.some(l=>a.includes(l)))return!0;o=r.indexOf(n,o+n.length)}return!1},Pte=(e,t)=>{try{const r=JSON.parse(e);let n=!1;if(t==="chat_template"&&"chat_template"in r&&(delete r.chat_template,n=!0),t==="reasoning_budget"){const o=r.chat_template_kwargs;o&&"reasoning_budget"in o&&(delete o.reasoning_budget,n=!0,Object.keys(o).length===0&&delete r.chat_template_kwargs)}return n?JSON.stringify(r):null}catch{return null}},QFt="https://integrate.api.nvidia.com/v1",Mte=e=>{const t=process.env[e];if(!t)return;const r=Number.parseInt(t,10);return Number.isFinite(r)?r:void 0},Ote=e=>{const t=process.env[e];if(!t)return;const r=Number.parseFloat(t);return Number.isFinite(r)?r:void 0},e$t=(e,t)=>{const r={},n=Mte("NVIDIA_NIM_TOP_K");n!==void 0&&n!==-1&&(r.top_k=n);const o=Ote("NVIDIA_NIM_MIN_P");o!==void 0&&o!==0&&(r.min_p=o);const i=Ote("NVIDIA_NIM_REPETITION_PENALTY");i!==void 0&&i!==1&&(r.repetition_penalty=i);const s=Mte("NVIDIA_NIM_MIN_TOKENS");s!==void 0&&s!==0&&(r.min_tokens=s);const a=process.env.NVIDIA_NIM_CHAT_TEMPLATE;return a&&(r.chat_template=a),e&&(r.chat_template_kwargs={thinking:!0,enable_thinking:!0,...t?{reasoning_budget:t}:{}}),r},t$t=()=>_a(q4r()),Dte=()=>Fi("NVIDIA_NIM_MODEL",hr.get("nvidia-nim")?.defaultModel??"openai/gpt-oss-20b"),r$t=class extends Kl{constructor(e,t,r,n){const o=n?.apiKey?.trim(),i=o&&o.length>0?o:t$t(),s=n?.baseURL??process.env.NVIDIA_NIM_BASE_URL??QFt;super("nvidia-nim",e,t,{baseURL:s,apiKey:i}),h.debug("NVIDIA NIM Provider initialized",{modelName:this.modelName,providerName:this.providerName,baseURL:Yo(this.config.baseURL)})}getProviderName(){return"nvidia-nim"}getDefaultModel(){return Dte()}adjustBuildBodyOptions(e,t){const r=t,n=r.thinkingConfig,o=r.thinkingLevel??n?.thinkingLevel,i=o!==void 0&&o!=="minimal",s=typeof r.maxTokens=="number"?r.maxTokens:void 0,a=e$t(i,s);return Object.keys(a).length>0?{...t,extraBody:a}:t}adjustBodyAfter400(e,t){const r=t.responseBody??"";let n=JSON.stringify(e);const o=[];for(const i of["chat_template","reasoning_budget"])if(Rte(r,i)){const s=Pte(n,i);s!==null&&(n=s,o.push(i))}if(o.length!==0)return h.debug("NVIDIA NIM: 400 rejected request field(s) \u2014 retrying once without them",{strippedFields:o,model:e.model,rejection:r.slice(0,200)}),JSON.parse(n)}formatProviderError(e){const t=[{match:r=>/Invalid API key|Unauthorized/.test(r.message)||im(r.message,401),errorClass:Wr,message:"Invalid NVIDIA NIM API key. Get one at https://build.nvidia.com/settings/api-keys"},{match:r=>/rate limit/.test(r.message)||im(r.message,429),errorClass:Qi,message:"NVIDIA NIM rate limit exceeded"},{match:r=>r.statusCode===404||/model_not_found/.test(r.message)||im(r.message,404),errorClass:Jo,message:()=>`NVIDIA NIM model '${this.modelName}' not available. Browse the catalog at https://build.nvidia.com/models`},{match:r=>/quota/.test(r.message)||im(r.message,403),errorClass:ot,message:"NVIDIA NIM quota exceeded for your account"},...Ll];return ba(e,t,this.providerName,this.modelName)}async validateConfiguration(){return typeof this.config.apiKey=="string"&&this.config.apiKey.trim().length>0}getConfiguration(){return{provider:this.providerName,model:this.modelName,defaultModel:Dte(),baseURL:this.config.baseURL}}}}}),n$t,MXr=E({"src/lib/providers/nvidiaNim/constants.ts"(){"use strict";n$t="https://integrate.api.nvidia.com/v1"}}),o$t={};Z(o$t,{NVIDIA_NIM_DEFAULT_BASE_URL:()=>n$t,NvidiaNimProvider:()=>r$t,isNimFieldRejection:()=>Rte,stripFieldFromJsonBody:()=>Pte});var OXr=E({"src/lib/providers/nvidiaNim/index.ts"(){"use strict";PXr(),MXr()}}),i$t={};Z(i$t,{LMStudioProvider:()=>l$t});var s$t,Nte,Lte,a$t,l$t,DXr=E({"src/lib/providers/lmStudio.ts"(){"use strict";pt(),Zs(),z(),Nt(),zc(),hte(),s$t="http://localhost:1234/v1",Nte="lm-studio",Lte="local-model",a$t=()=>process.env.LM_STUDIO_BASE_URL||s$t,l$t=class extends Kl{constructor(e,t,r,n){const o=n?.apiKey??process.env.LM_STUDIO_API_KEY??Nte,i=n?.baseURL??a$t();super("lm-studio",e,t,{baseURL:i,apiKey:o}),h.debug("LM Studio Provider initialized",{modelName:this.modelName,providerName:this.providerName,baseURL:Yo(this.config.baseURL)})}getProviderName(){return"lm-studio"}getDefaultModel(){return process.env.LM_STUDIO_MODEL||""}getFallbackModelName(){return Lte}formatProviderError(e){const t=[mte(e,()=>`LM Studio server not reachable at ${Yo(this.config.baseURL)}. Open the LM Studio app, load a model, and click "Start Server".`),{match:r=>/model_not_found|404/.test(r.message),errorClass:Jo,message:()=>`LM Studio model '${this.modelName}' is not loaded. Load it in the LM Studio app first.`},...Ll];return ba(e,t,this.providerName,this.modelName)}async validateConfiguration(){return this.probeModelsEndpoint(this.config.apiKey&&this.config.apiKey!==Nte?{Authorization:`Bearer ${this.config.apiKey}`}:{})}getConfiguration(){return{provider:this.providerName,model:this.modelName||this.resolvedModel||Lte,defaultModel:this.getDefaultModel(),baseURL:this.config.baseURL}}}}}),c$t={};Z(c$t,{LlamaCppProvider:()=>m$t});var u$t,d$t,p$t,m$t,NXr=E({"src/lib/providers/llamaCpp.ts"(){"use strict";pt(),Zs(),z(),Nt(),zc(),hte(),u$t="http://localhost:8080/v1",d$t="llamacpp",p$t=()=>process.env.LLAMACPP_BASE_URL||u$t,m$t=class extends Kl{constructor(e,t,r,n){const o=n?.baseURL?.trim()||p$t(),i=n?.apiKey?.trim()||process.env.LLAMACPP_API_KEY||d$t;super("llamacpp",e,t,{baseURL:o,apiKey:i}),h.debug("llama.cpp Provider initialized",{modelName:this.modelName,providerName:this.providerName,baseURL:Yo(this.config.baseURL)})}async validateConfiguration(){return this.probeModelsEndpoint(this.getAuthHeaders())}getProviderName(){return"llamacpp"}getDefaultModel(){return process.env.LLAMACPP_MODEL||""}getFallbackModelName(){return"loaded-model"}getFallbackModels(){return["loaded-model"]}formatProviderError(e){const t=[mte(e,()=>`llama.cpp server not reachable at ${Yo(this.config.baseURL)}. Start it with: ./llama-server -m model.gguf --port 8080`),{match:r=>r.statusCode===400||r.statusCode===void 0&&/\b400\b/.test(r.message),errorClass:ot,message:"llama.cpp rejected the request. Common cause: model doesn't support tools (start llama-server with --jinja for tool support)."},...Ll];return ba(e,t,this.providerName,this.modelName)}}}}),h$t={};Z(h$t,{CohereProvider:()=>y$t});var f$t,g$t,Fte,y$t,LXr=E({"src/lib/providers/cohere.ts"(){"use strict";pt(),Zs(),z(),Nt(),Ln(),Go(),Ys(),Um(),zc(),f$t="https://api.cohere.com/compatibility/v1",g$t=()=>_a(V4r()),Fte=()=>Fi("COHERE_MODEL","command-r-plus-08-2024"),y$t=class extends Kl{constructor(e,t,r,n){const o=n?.apiKey?.trim(),i=o&&o.length>0?o:g$t(),s=n?.baseURL?.trim()||process.env.COHERE_BASE_URL?.trim()||f$t;super("cohere",e,t,{baseURL:s,apiKey:i}),h.debug("Cohere Provider initialized",{modelName:this.modelName,providerName:this.providerName,baseURL:Yo(this.config.baseURL)})}getProviderName(){return"cohere"}getDefaultModel(){return Fte()}getFallbackModelName(){return"command-r-08-2024"}getFallbackModels(){return["command-a-03-2025","command-a-reasoning-08-2025","command-r-plus-08-2024","command-r-08-2024","command-r7b-12-2024"]}formatProviderError(e){const t=[{match:r=>/invalid api token|Authentication|401|invalid_api_token/.test(r.message),errorClass:Wr,message:"Invalid Cohere API key. Check COHERE_API_KEY. Get one at https://dashboard.cohere.com/api-keys"},{match:r=>/rate limit|429/.test(r.message),errorClass:Qi,message:"Cohere rate limit exceeded. Back off and retry."},{match:r=>/model_not_found|404/.test(r.message),errorClass:Jo,message:()=>`Cohere model '${this.modelName}' not found. Use command-r, command-r-plus, or command-r7b-12-2024.`},{match:r=>/trial limit|trial_limit/.test(r.message),errorClass:ot,message:"Cohere trial usage limit exceeded. Upgrade at https://dashboard.cohere.com/billing."},...Ll];return ba(e,t,this.providerName,this.modelName)}async validateConfiguration(){return typeof this.config.apiKey=="string"&&this.config.apiKey.trim().length>0}getConfiguration(){return{provider:this.providerName,model:this.modelName,defaultModel:Fte(),baseURL:this.config.baseURL}}getDefaultEmbeddingModel(){return"embed-english-v3.0"}async embed(e,t){if(typeof e!="string"&&e.image)throw new ot(`${this.providerName} does not support image embeddings; provide text input`,this.providerName);const r=typeof e=="string"?e:e.text??"",n=await this.embedMany([r],t);if(!n[0])throw new ot("Cohere /v2/embed returned no embeddings.","cohere");return n[0]}async embedMany(e,t){if(e.length===0)return[];const r=t??this.getDefaultEmbeddingModel(),o=`${Da(this.config.baseURL.replace(/\/compatibility\/v\d+\/?$/,""))}/v2/embed`,i=96,s=[],a=Ot();for(let l=0;l<e.length;l+=i){const c=e.slice(l,l+i),u=wa(3e4,this.providerName,"generate");try{const d=await a(o,{method:"POST",headers:{Authorization:`Bearer ${this.config.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify({model:r,texts:c,input_type:"search_document",embedding_types:["float"]}),...u?.controller.signal?{signal:u.controller.signal}:{}});if(!d.ok){const f=await d.text().catch(()=>"");throw this.formatProviderError(new Error(`Cohere /v2/embed failed: ${d.status} \u2014 ${f.slice(0,500)}`))}const p=await d.json(),m=p.embeddings?.float??(Array.isArray(p.embeddings)?p.embeddings:void 0);if(!m||m.length!==c.length)throw new ot(`Cohere /v2/embed returned ${m?.length??0} embeddings for ${c.length} inputs.`,"cohere");s.push(...m)}finally{u?.cleanup()}}return s}}}}),FXr=tn({"node_modules/.pnpm/dotenv@17.3.1/node_modules/dotenv/package.json"(e,t){t.exports={name:"dotenv",version:"17.3.1",description:"Loads environment variables from .env file",main:"lib/main.js",types:"lib/main.d.ts",exports:{".":{types:"./lib/main.d.ts",require:"./lib/main.js",default:"./lib/main.js"},"./config":"./config.js","./config.js":"./config.js","./lib/env-options":"./lib/env-options.js","./lib/env-options.js":"./lib/env-options.js","./lib/cli-options":"./lib/cli-options.js","./lib/cli-options.js":"./lib/cli-options.js","./package.json":"./package.json"},scripts:{"dts-check":"tsc --project tests/types/tsconfig.json",lint:"standard",pretest:"npm run lint && npm run dts-check",test:"tap run tests/**/*.js --allow-empty-coverage --disable-coverage --timeout=60000","test:coverage":"tap run tests/**/*.js --show-full-coverage --timeout=60000 --coverage-report=text --coverage-report=lcov",prerelease:"npm test",release:"standard-version"},repository:{type:"git",url:"git://github.com/motdotla/dotenv.git"},homepage:"https://github.com/motdotla/dotenv#readme",funding:"https://dotenvx.com",keywords:["dotenv","env",".env","environment","variables","config","settings"],readmeFilename:"README.md",license:"BSD-2-Clause",devDependencies:{"@types/node":"^18.11.3",decache:"^4.6.2",sinon:"^14.0.1",standard:"^17.0.0","standard-version":"^9.5.0",tap:"^19.2.0",typescript:"^4.8.4"},engines:{node:">=12"},browser:{fs:!1}}}}),$Xr=tn({"node_modules/.pnpm/dotenv@17.3.1/node_modules/dotenv/lib/main.js"(e,t){var r=(Tn(),rn(Iu)),n=(kr(),rn(nm)),o=($s(),rn(xK)),i=($t(),rn(sE)),s=FXr(),a=s.version,l=["\u{1F510} encrypt with Dotenvx: https://dotenvx.com","\u{1F510} prevent committing .env to code: https://dotenvx.com/precommit","\u{1F510} prevent building .env in docker: https://dotenvx.com/prebuild","\u{1F916} agentic secret storage: https://dotenvx.com/as2","\u26A1\uFE0F secrets for agents: https://dotenvx.com/as2","\u{1F6E1}\uFE0F auth for agents: https://vestauth.com","\u{1F6E0}\uFE0F run anywhere with `dotenvx run -- yourcommand`","\u2699\uFE0F specify custom .env file path with { path: '/custom/path/.env' }","\u2699\uFE0F enable debug logging with { debug: true }","\u2699\uFE0F override existing env vars with { override: true }","\u2699\uFE0F suppress all logs with { quiet: true }","\u2699\uFE0F write to custom object with { processEnv: myObject }","\u2699\uFE0F load multiple .env files with { path: ['.env.local', '.env'] }"];function c(){return l[Math.floor(Math.random()*l.length)]}function u(M){return typeof M=="string"?!["false","0","no","off",""].includes(M.toLowerCase()):!!M}function d(){return process.stdout.isTTY}function p(M){return d()?`\x1B[2m${M}\x1B[0m`:M}var m=/(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/mg;function f(M){const D={};let $=M.toString();$=$.replace(/\r\n?/mg,`
|
|
1323
|
+
`):String(r)}extractTextFromResponse(e){if(typeof e=="string")return e;if(e.generated_text)return e.generated_text;if(e.outputs)return e.outputs;if(e.text)return e.text;if(Array.isArray(e)&&e[0]?.generated_text)return e[0].generated_text;if(e.choices&&Array.isArray(e.choices)){const t=e.choices[0];if(typeof t?.message?.content=="string")return t.message.content;if(t?.message?.tool_calls?.length)return""}return JSON.stringify(e)}extractToolCallsFromResponse(e){if(e.choices&&Array.isArray(e.choices)){const t=e.choices[0];if(t?.message?.tool_calls)return t.message.tool_calls.map(r=>({type:"function",id:String(r.id||`call_${Qe()}`),function:{name:String(r.function.name),arguments:String(r.function.arguments)}}))}if(e.tool_calls&&Array.isArray(e.tool_calls))return e.tool_calls;if(e.content&&Array.isArray(e.content)){const t=e.content.filter(r=>r.type==="tool_use");if(t.length>0)return t.map(r=>({type:"function",id:String(r.id||`call_${Qe()}`),function:{name:String(r.name),arguments:JSON.stringify(r.input||{})}}))}}mapSageMakerFinishReason(e){switch(e?.toLowerCase()){case"stop":case"end_turn":case"stop_sequence":return"stop";case"length":case"max_tokens":case"max_length":return"length";case"content_filter":case"content_filtered":return"content-filter";case"tool_calls":case"function_call":return"tool-calls";case"error":return"error";default:return"unknown"}}getModelInfo(){return{modelId:this.modelId,provider:this.provider,specificationVersion:this.specificationVersion,endpointName:this.modelConfig.endpointName,modelType:this.modelConfig.modelType,region:this.config.region}}async testConnectivity(){try{return{success:!!(await this.doGenerate({inputFormat:"messages",mode:{type:"regular"},prompt:[{role:"user",content:[{type:"text",text:"Hello"}]}],maxTokens:10})).text}}catch(e){return{success:!1,error:e instanceof Error?e.message:String(e)}}}async doBatchGenerate(e,t){try{h.debug("SageMaker batch generate called",{batchSize:e.length,endpointName:this.modelConfig.endpointName});const r=await this.processPromptsInParallel(e,t);return h.debug("SageMaker batch generate completed",{batchSize:e.length,successCount:r.length}),r}catch(r){throw h.error("SageMaker batch generate failed",{error:r instanceof Error?r.message:String(r),batchSize:e.length}),pr(r)?r:mp(r,this.modelConfig.endpointName)}}async processPromptsInParallel(e,t){const r=Math.min(this.modelConfig.initialConcurrency??HFt,e.length),n=this.modelConfig.maxConcurrency??WFt,o=this.modelConfig.minConcurrency??KFt,i=new Array(e.length),s=[],a=kXr(r,n,o),l=async(d,p)=>{await a.acquire();const m=Date.now();try{const f=await this.doGenerate({inputFormat:"messages",mode:{type:"regular"},prompt:[{role:"user",content:[{type:"text",text:d}]}],maxTokens:t?.maxTokens,temperature:t?.temperature,topP:t?.topP}),g=Date.now()-m;i[p]={text:f.text||"",usage:{promptTokens:f.usage.inputTokens??0,completionTokens:f.usage.outputTokens??0,total:f.usage.totalTokens??(f.usage.inputTokens??0)+(f.usage.outputTokens??0)},finishReason:f.finishReason,index:p},a.recordSuccess(g)}catch(f){s.push({index:p,error:f instanceof Error?f:new Error(String(f))});const g=Date.now()-m;a.recordError(g),i[p]={text:"",usage:{promptTokens:0,completionTokens:0,total:0},finishReason:"error",index:p}}finally{a.release()}},c=e.map((d,p)=>l(d,p));await Promise.all(c);const u=a.getMetrics();return h.debug("Parallel batch processing completed",{totalPrompts:e.length,successCount:u.completedCount,errorCount:u.errorCount,finalConcurrency:u.currentConcurrency,errorRate:u.errorCount/e.length,averageResponseTime:u.averageResponseTime}),s.length>0&&h.warn("Batch processing encountered errors",{errorCount:s.length,sampleErrors:s.slice(0,3).map(d=>({index:d.index,message:d.error.message}))}),i.map(({text:d,usage:p,finishReason:m})=>({text:d,usage:p,finishReason:m}))}getModelCapabilities(){return{...this.getModelInfo(),capabilities:{streaming:!0,toolCalling:!0,structuredOutput:!0,batchInference:!0,supportedResponseFormats:["text","json_object","json_schema"],supportedToolTypes:["function"],maxBatchSize:100,adaptiveConcurrency:!0,errorRecovery:!0}}}}}}),XFt={};Z(XFt,{AmazonSageMakerProvider:()=>Ite,default:()=>YFt});var Ite,YFt,RXr=E({"src/lib/providers/amazonSagemaker.ts"(){"use strict";pl(),Jv(),z(),If(),vm(),zl(),ss(),kd(),Zo(),vZ(),Xr(),Sr(),eXr(),rA(),IXr(),Ite=class extends Ma{sagemakerModel;sagemakerConfig;modelConfig;constructor(e,t,r,n,o){super(e,"sagemaker",n);try{const i=YJr(o?.region??r,{...o?.region!==void 0&&{region:o.region},...o?.accessKeyId!==void 0&&{accessKeyId:o.accessKeyId},...o?.secretAccessKey!==void 0&&{secretAccessKey:o.secretAccessKey},...o?.sessionToken!==void 0&&{sessionToken:o.sessionToken},...o?.endpoint!==void 0&&{endpoint:o.endpoint}});this.sagemakerConfig={...i,...o?.region!==void 0&&{region:o.region},...o?.accessKeyId!==void 0&&{accessKeyId:o.accessKeyId},...o?.secretAccessKey!==void 0&&{secretAccessKey:o.secretAccessKey},...o?.sessionToken!==void 0&&{sessionToken:o.sessionToken},...o?.endpoint!==void 0&&{endpoint:o.endpoint}},this.modelConfig=ZJr(t||SFt()),this.sagemakerModel=new JFt(this.modelName,this.sagemakerConfig,this.modelConfig),h.debug("Amazon SageMaker Provider initialized",{modelName:this.modelName,endpointName:this.modelConfig.endpointName,region:this.sagemakerConfig.region,provider:this.providerName})}catch(i){throw h.error("Failed to initialize SageMaker provider",{error:i instanceof Error?i.message:String(i),modelName:e,endpointName:t}),mp(i)}}getProviderName(){return"sagemaker"}getDefaultModel(){return QJr()}getAISDKModel(){return this.sagemakerModel}async generate(e,t){await this.ensureModelLimits();const r=this.normalizeTextOptions(e);if($d(r,this.modelName)!=="text")return super.generate(r,t);this.validateOptions(r);const n=await this.getToolsForStream(r),o="disableInternalFallback"in r&&r.disableInternalFallback===!0;return this.runGenerateWithModelFallback(()=>this.withTurnTimeout({...r,tools:n},this.getDescriptorGenerateMs(),i=>this.executeNativeGenerate(i)),o,r)}async executeNativeGenerate(e){const t=Date.now(),r=await this.getAISDKModelWithMiddleware(e);if(!ex(r))throw this.handleProviderError(new Error("sagemaker: model handle exposes no doGenerate()"));const n=async p=>{const m=p.responseFormat,f=await r.doGenerate({...p,...p.maxOutputTokens!==void 0?{maxTokens:p.maxOutputTokens}:{},...m?.type==="json"?{responseFormat:m.schema?{type:"json_schema",json_schema:{name:"response",schema:m.schema}}:{type:"json_object"}}:{}});if(Array.isArray(f.content))return f;const g=[];typeof f.text=="string"&&f.text&&g.push({type:"text",text:f.text}),typeof f.reasoning=="string"&&f.reasoning&&g.push({type:"reasoning",text:f.reasoning});for(const v of Array.isArray(f.toolCalls)?f.toolCalls:[]){if(typeof v!="object"||v===null)continue;const T=v,b=T.function;typeof T.id=="string"&&typeof b?.name=="string"&&g.push({type:"tool-call",toolCallId:T.id,toolName:b.name,input:b.arguments??"{}"})}const y=f.usage;return{...f,content:g,usage:{inputTokens:{total:typeof y?.inputTokens=="number"?y.inputTokens:0},outputTokens:{total:typeof y?.outputTokens=="number"?y.outputTokens:0}}}},i=!e.disableTools&&this.supportsTools()?e.tools||{}:{},s=Object.entries(i).map(([p,m])=>{const f=m;return{type:"function",name:p,description:f.description??"",inputSchema:f.inputSchema?qo(f.inputSchema):{type:"object",properties:{}}}}),a=e.schema?{type:"json",schema:qo(e.schema)}:void 0,l=await this.buildMessagesForStream(e),c=[],u=await BO({doGenerate:n,conversation:l,...a?{responseFormat:a}:{},...s.length>0?{tools:s}:{},toolsRecord:i,maxSteps:e.maxSteps||ts,...e.maxTokens?{maxOutputTokens:e.maxTokens}:{},...e.temperature!==void 0?{temperature:e.temperature}:{},...e.abortSignal?{abortSignal:e.abortSignal}:{},...e.toolTimeoutMs!==void 0?{toolTimeoutMs:e.toolTimeoutMs}:{},runStep:p=>Py(p,void 0,"sagemaker generate",void 0,e.abortSignal).catch(m=>{throw this.handleProviderError(m)})},c),d={content:u.text,provider:this.providerName,model:this.modelName,finishReason:u.finishReason,usage:{input:u.inputTokens,output:u.outputTokens,total:u.inputTokens+u.outputTokens},responseTime:Date.now()-t,...u.reasoning?{reasoning:u.reasoning}:{},toolsUsed:u.toolsUsed,toolCalls:HH(c),toolExecutions:Df(e,Bd(c)),enhancedWithTools:u.toolsUsed.length>0};return this.finalizeNativeGenerate(d,e,t)}async doStream(e){return mt({name:"neurolink.provider.sagemaker.stream",tracer:Be.stream,attributes:{"provider.name":"sagemaker","model.name":this.modelName,"sagemaker.endpoint":this.modelConfig.endpointName,"sagemaker.region":this.sagemakerConfig.region}},async()=>{try{const t=await this.buildMessagesForStream(e),r=await this.sagemakerModel.doStream({prompt:t,maxTokens:e.maxTokens,temperature:e.temperature});let n,o;const i=new Promise(l=>{n=l}),s=new Promise(l=>{o=l}),a=Kv();return(async()=>{const l=r.stream.getReader();let c=!1;try{for(;;){const{done:u,value:d}=await l.read();if(u)break;const p=d;if(p.type==="text-delta"&&p.textDelta){a.push({content:p.textDelta});continue}p.type==="finish"&&(c=!0,n(p.finishReason??"stop"),o({inputTokens:p.usage?.inputTokens??p.usage?.promptTokens??0,outputTokens:p.usage?.outputTokens??p.usage?.completionTokens??0}))}a.close()}catch(u){a.error(u)}finally{l.releaseLock(),c||(n("unknown"),o({inputTokens:0,outputTokens:0}))}})(),{stream:a.iterable,finishReason:i,usage:s,warnings:(r.warnings??[]).map(l=>l.message??String(l))}}catch(t){throw this.handleProviderError(t)}})}formatProviderError(e){return e instanceof zo?e:e instanceof Error&&e.name==="TimeoutError"?new zo("SageMaker request timed out. Consider increasing timeout.",{code:"NETWORK_ERROR",statusCode:408,cause:e,endpoint:this.modelConfig.endpointName}):mp(e,this.modelConfig.endpointName)}getSageMakerInfo(){return{endpointName:this.modelConfig.endpointName,modelType:this.modelConfig.modelType||"custom",region:this.sagemakerConfig.region,configured:!!(this.sagemakerConfig.accessKeyId&&this.sagemakerConfig.secretAccessKey)}}async testConnection(){try{return!this.sagemakerConfig.accessKeyId||!this.sagemakerConfig.secretAccessKey?{connected:!1,error:"AWS credentials not configured"}:!this.modelConfig.endpointName||this.modelConfig.endpointName==="default-endpoint"?{connected:!1,error:"SageMaker endpoint not configured"}:{connected:!0}}catch(e){return{connected:!1,error:e instanceof Error?e.message:String(e)}}}async getModel(){return this.getAISDKModel()}async testConnectivity(){const e=this.sagemakerModel;return e.testConnectivity?await e.testConnectivity():{success:!1,error:"Test method not available"}}getModelCapabilities(){const e=this.sagemakerModel;return e.getModelCapabilities?e.getModelCapabilities():{capabilities:{streaming:!0,toolCalling:!0,structuredOutput:!0,batchInference:!0,supportedResponseFormats:["text","json_object"],supportedToolTypes:["function"],maxBatchSize:10}}}},YFt=Ite}}),ZFt,Rte,Pte,QFt,Mte,Ote,e$t,t$t,Dte,r$t,PXr=E({"src/lib/providers/nvidiaNim/client.ts"(){"use strict";pt(),Zs(),z(),Nt(),Go(),zc(),Fl(),ZFt=["unsupported","not supported","does not support","unrecognized","unknown field","unknown parameter","unknown argument","invalid field","invalid parameter","invalid argument"],Rte=(e,t)=>{if(!e)return!1;const r=e.toLowerCase(),n=t.toLowerCase();let o=r.indexOf(n);for(;o!==-1;){const i=Math.max(0,o-80),s=Math.min(r.length,o+n.length+80),a=r.slice(i,s);if(ZFt.some(l=>a.includes(l)))return!0;o=r.indexOf(n,o+n.length)}return!1},Pte=(e,t)=>{try{const r=JSON.parse(e);let n=!1;if(t==="chat_template"&&"chat_template"in r&&(delete r.chat_template,n=!0),t==="reasoning_budget"){const o=r.chat_template_kwargs;o&&"reasoning_budget"in o&&(delete o.reasoning_budget,n=!0,Object.keys(o).length===0&&delete r.chat_template_kwargs)}return n?JSON.stringify(r):null}catch{return null}},QFt="https://integrate.api.nvidia.com/v1",Mte=e=>{const t=process.env[e];if(!t)return;const r=Number.parseInt(t,10);return Number.isFinite(r)?r:void 0},Ote=e=>{const t=process.env[e];if(!t)return;const r=Number.parseFloat(t);return Number.isFinite(r)?r:void 0},e$t=(e,t)=>{const r={},n=Mte("NVIDIA_NIM_TOP_K");n!==void 0&&n!==-1&&(r.top_k=n);const o=Ote("NVIDIA_NIM_MIN_P");o!==void 0&&o!==0&&(r.min_p=o);const i=Ote("NVIDIA_NIM_REPETITION_PENALTY");i!==void 0&&i!==1&&(r.repetition_penalty=i);const s=Mte("NVIDIA_NIM_MIN_TOKENS");s!==void 0&&s!==0&&(r.min_tokens=s);const a=process.env.NVIDIA_NIM_CHAT_TEMPLATE;return a&&(r.chat_template=a),e&&(r.chat_template_kwargs={thinking:!0,enable_thinking:!0,...t?{reasoning_budget:t}:{}}),r},t$t=()=>_a(q4r()),Dte=()=>Fi("NVIDIA_NIM_MODEL",hr.get("nvidia-nim")?.defaultModel??"openai/gpt-oss-20b"),r$t=class extends Kl{constructor(e,t,r,n){const o=n?.apiKey?.trim(),i=o&&o.length>0?o:t$t(),s=n?.baseURL??process.env.NVIDIA_NIM_BASE_URL??QFt;super("nvidia-nim",e,t,{baseURL:s,apiKey:i}),h.debug("NVIDIA NIM Provider initialized",{modelName:this.modelName,providerName:this.providerName,baseURL:Yo(this.config.baseURL)})}getProviderName(){return"nvidia-nim"}getDefaultModel(){return Dte()}adjustBuildBodyOptions(e,t){const r=t,n=r.thinkingConfig,o=r.thinkingLevel??n?.thinkingLevel,i=o!==void 0&&o!=="minimal",s=typeof r.maxTokens=="number"?r.maxTokens:void 0,a=e$t(i,s);return Object.keys(a).length>0?{...t,extraBody:a}:t}adjustBodyAfter400(e,t){const r=t.responseBody??"";let n=JSON.stringify(e);const o=[];for(const i of["chat_template","reasoning_budget"])if(Rte(r,i)){const s=Pte(n,i);s!==null&&(n=s,o.push(i))}if(o.length!==0)return h.debug("NVIDIA NIM: 400 rejected request field(s) \u2014 retrying once without them",{strippedFields:o,model:e.model,rejection:r.slice(0,200)}),JSON.parse(n)}formatProviderError(e){const t=[{match:r=>/Invalid API key|Unauthorized/.test(r.message)||im(r.message,401),errorClass:Wr,message:"Invalid NVIDIA NIM API key. Get one at https://build.nvidia.com/settings/api-keys"},{match:r=>/rate limit/.test(r.message)||im(r.message,429),errorClass:Qi,message:"NVIDIA NIM rate limit exceeded"},{match:r=>r.statusCode===404||/model_not_found/.test(r.message)||im(r.message,404),errorClass:Jo,message:()=>`NVIDIA NIM model '${this.modelName}' not available. Browse the catalog at https://build.nvidia.com/models`},{match:r=>/quota/.test(r.message)||im(r.message,403),errorClass:nt,message:"NVIDIA NIM quota exceeded for your account"},...Ll];return ba(e,t,this.providerName,this.modelName)}async validateConfiguration(){return typeof this.config.apiKey=="string"&&this.config.apiKey.trim().length>0}getConfiguration(){return{provider:this.providerName,model:this.modelName,defaultModel:Dte(),baseURL:this.config.baseURL}}}}}),n$t,MXr=E({"src/lib/providers/nvidiaNim/constants.ts"(){"use strict";n$t="https://integrate.api.nvidia.com/v1"}}),o$t={};Z(o$t,{NVIDIA_NIM_DEFAULT_BASE_URL:()=>n$t,NvidiaNimProvider:()=>r$t,isNimFieldRejection:()=>Rte,stripFieldFromJsonBody:()=>Pte});var OXr=E({"src/lib/providers/nvidiaNim/index.ts"(){"use strict";PXr(),MXr()}}),i$t={};Z(i$t,{LMStudioProvider:()=>l$t});var s$t,Nte,Lte,a$t,l$t,DXr=E({"src/lib/providers/lmStudio.ts"(){"use strict";pt(),Zs(),z(),Nt(),zc(),hte(),s$t="http://localhost:1234/v1",Nte="lm-studio",Lte="local-model",a$t=()=>process.env.LM_STUDIO_BASE_URL||s$t,l$t=class extends Kl{constructor(e,t,r,n){const o=n?.apiKey??process.env.LM_STUDIO_API_KEY??Nte,i=n?.baseURL??a$t();super("lm-studio",e,t,{baseURL:i,apiKey:o}),h.debug("LM Studio Provider initialized",{modelName:this.modelName,providerName:this.providerName,baseURL:Yo(this.config.baseURL)})}getProviderName(){return"lm-studio"}getDefaultModel(){return process.env.LM_STUDIO_MODEL||""}getFallbackModelName(){return Lte}formatProviderError(e){const t=[mte(e,()=>`LM Studio server not reachable at ${Yo(this.config.baseURL)}. Open the LM Studio app, load a model, and click "Start Server".`),{match:r=>/model_not_found|404/.test(r.message),errorClass:Jo,message:()=>`LM Studio model '${this.modelName}' is not loaded. Load it in the LM Studio app first.`},...Ll];return ba(e,t,this.providerName,this.modelName)}async validateConfiguration(){return this.probeModelsEndpoint(this.config.apiKey&&this.config.apiKey!==Nte?{Authorization:`Bearer ${this.config.apiKey}`}:{})}getConfiguration(){return{provider:this.providerName,model:this.modelName||this.resolvedModel||Lte,defaultModel:this.getDefaultModel(),baseURL:this.config.baseURL}}}}}),c$t={};Z(c$t,{LlamaCppProvider:()=>m$t});var u$t,d$t,p$t,m$t,NXr=E({"src/lib/providers/llamaCpp.ts"(){"use strict";pt(),Zs(),z(),Nt(),zc(),hte(),u$t="http://localhost:8080/v1",d$t="llamacpp",p$t=()=>process.env.LLAMACPP_BASE_URL||u$t,m$t=class extends Kl{constructor(e,t,r,n){const o=n?.baseURL?.trim()||p$t(),i=n?.apiKey?.trim()||process.env.LLAMACPP_API_KEY||d$t;super("llamacpp",e,t,{baseURL:o,apiKey:i}),h.debug("llama.cpp Provider initialized",{modelName:this.modelName,providerName:this.providerName,baseURL:Yo(this.config.baseURL)})}async validateConfiguration(){return this.probeModelsEndpoint(this.getAuthHeaders())}getProviderName(){return"llamacpp"}getDefaultModel(){return process.env.LLAMACPP_MODEL||""}getFallbackModelName(){return"loaded-model"}getFallbackModels(){return["loaded-model"]}formatProviderError(e){const t=[mte(e,()=>`llama.cpp server not reachable at ${Yo(this.config.baseURL)}. Start it with: ./llama-server -m model.gguf --port 8080`),{match:r=>r.statusCode===400||r.statusCode===void 0&&/\b400\b/.test(r.message),errorClass:nt,message:"llama.cpp rejected the request. Common cause: model doesn't support tools (start llama-server with --jinja for tool support)."},...Ll];return ba(e,t,this.providerName,this.modelName)}}}}),h$t={};Z(h$t,{CohereProvider:()=>y$t});var f$t,g$t,Fte,y$t,LXr=E({"src/lib/providers/cohere.ts"(){"use strict";pt(),Zs(),z(),Nt(),Ln(),Go(),Ys(),Um(),zc(),f$t="https://api.cohere.com/compatibility/v1",g$t=()=>_a(V4r()),Fte=()=>Fi("COHERE_MODEL","command-r-plus-08-2024"),y$t=class extends Kl{constructor(e,t,r,n){const o=n?.apiKey?.trim(),i=o&&o.length>0?o:g$t(),s=n?.baseURL?.trim()||process.env.COHERE_BASE_URL?.trim()||f$t;super("cohere",e,t,{baseURL:s,apiKey:i}),h.debug("Cohere Provider initialized",{modelName:this.modelName,providerName:this.providerName,baseURL:Yo(this.config.baseURL)})}getProviderName(){return"cohere"}getDefaultModel(){return Fte()}getFallbackModelName(){return"command-r-08-2024"}getFallbackModels(){return["command-a-03-2025","command-a-reasoning-08-2025","command-r-plus-08-2024","command-r-08-2024","command-r7b-12-2024"]}formatProviderError(e){const t=[{match:r=>/invalid api token|Authentication|401|invalid_api_token/.test(r.message),errorClass:Wr,message:"Invalid Cohere API key. Check COHERE_API_KEY. Get one at https://dashboard.cohere.com/api-keys"},{match:r=>/rate limit|429/.test(r.message),errorClass:Qi,message:"Cohere rate limit exceeded. Back off and retry."},{match:r=>/model_not_found|404/.test(r.message),errorClass:Jo,message:()=>`Cohere model '${this.modelName}' not found. Use command-r, command-r-plus, or command-r7b-12-2024.`},{match:r=>/trial limit|trial_limit/.test(r.message),errorClass:nt,message:"Cohere trial usage limit exceeded. Upgrade at https://dashboard.cohere.com/billing."},...Ll];return ba(e,t,this.providerName,this.modelName)}async validateConfiguration(){return typeof this.config.apiKey=="string"&&this.config.apiKey.trim().length>0}getConfiguration(){return{provider:this.providerName,model:this.modelName,defaultModel:Fte(),baseURL:this.config.baseURL}}getDefaultEmbeddingModel(){return"embed-english-v3.0"}async embed(e,t){if(typeof e!="string"&&e.image)throw new nt(`${this.providerName} does not support image embeddings; provide text input`,this.providerName);const r=typeof e=="string"?e:e.text??"",n=await this.embedMany([r],t);if(!n[0])throw new nt("Cohere /v2/embed returned no embeddings.","cohere");return n[0]}async embedMany(e,t){if(e.length===0)return[];const r=t??this.getDefaultEmbeddingModel(),o=`${Da(this.config.baseURL.replace(/\/compatibility\/v\d+\/?$/,""))}/v2/embed`,i=96,s=[],a=Ot();for(let l=0;l<e.length;l+=i){const c=e.slice(l,l+i),u=wa(3e4,this.providerName,"generate");try{const d=await a(o,{method:"POST",headers:{Authorization:`Bearer ${this.config.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify({model:r,texts:c,input_type:"search_document",embedding_types:["float"]}),...u?.controller.signal?{signal:u.controller.signal}:{}});if(!d.ok){const f=await d.text().catch(()=>"");throw this.formatProviderError(new Error(`Cohere /v2/embed failed: ${d.status} \u2014 ${f.slice(0,500)}`))}const p=await d.json(),m=p.embeddings?.float??(Array.isArray(p.embeddings)?p.embeddings:void 0);if(!m||m.length!==c.length)throw new nt(`Cohere /v2/embed returned ${m?.length??0} embeddings for ${c.length} inputs.`,"cohere");s.push(...m)}finally{u?.cleanup()}}return s}}}}),FXr=tn({"node_modules/.pnpm/dotenv@17.3.1/node_modules/dotenv/package.json"(e,t){t.exports={name:"dotenv",version:"17.3.1",description:"Loads environment variables from .env file",main:"lib/main.js",types:"lib/main.d.ts",exports:{".":{types:"./lib/main.d.ts",require:"./lib/main.js",default:"./lib/main.js"},"./config":"./config.js","./config.js":"./config.js","./lib/env-options":"./lib/env-options.js","./lib/env-options.js":"./lib/env-options.js","./lib/cli-options":"./lib/cli-options.js","./lib/cli-options.js":"./lib/cli-options.js","./package.json":"./package.json"},scripts:{"dts-check":"tsc --project tests/types/tsconfig.json",lint:"standard",pretest:"npm run lint && npm run dts-check",test:"tap run tests/**/*.js --allow-empty-coverage --disable-coverage --timeout=60000","test:coverage":"tap run tests/**/*.js --show-full-coverage --timeout=60000 --coverage-report=text --coverage-report=lcov",prerelease:"npm test",release:"standard-version"},repository:{type:"git",url:"git://github.com/motdotla/dotenv.git"},homepage:"https://github.com/motdotla/dotenv#readme",funding:"https://dotenvx.com",keywords:["dotenv","env",".env","environment","variables","config","settings"],readmeFilename:"README.md",license:"BSD-2-Clause",devDependencies:{"@types/node":"^18.11.3",decache:"^4.6.2",sinon:"^14.0.1",standard:"^17.0.0","standard-version":"^9.5.0",tap:"^19.2.0",typescript:"^4.8.4"},engines:{node:">=12"},browser:{fs:!1}}}}),$Xr=tn({"node_modules/.pnpm/dotenv@17.3.1/node_modules/dotenv/lib/main.js"(e,t){var r=(Tn(),rn(Iu)),n=(kr(),rn(nm)),o=($s(),rn(xK)),i=($t(),rn(sE)),s=FXr(),a=s.version,l=["\u{1F510} encrypt with Dotenvx: https://dotenvx.com","\u{1F510} prevent committing .env to code: https://dotenvx.com/precommit","\u{1F510} prevent building .env in docker: https://dotenvx.com/prebuild","\u{1F916} agentic secret storage: https://dotenvx.com/as2","\u26A1\uFE0F secrets for agents: https://dotenvx.com/as2","\u{1F6E1}\uFE0F auth for agents: https://vestauth.com","\u{1F6E0}\uFE0F run anywhere with `dotenvx run -- yourcommand`","\u2699\uFE0F specify custom .env file path with { path: '/custom/path/.env' }","\u2699\uFE0F enable debug logging with { debug: true }","\u2699\uFE0F override existing env vars with { override: true }","\u2699\uFE0F suppress all logs with { quiet: true }","\u2699\uFE0F write to custom object with { processEnv: myObject }","\u2699\uFE0F load multiple .env files with { path: ['.env.local', '.env'] }"];function c(){return l[Math.floor(Math.random()*l.length)]}function u(M){return typeof M=="string"?!["false","0","no","off",""].includes(M.toLowerCase()):!!M}function d(){return process.stdout.isTTY}function p(M){return d()?`\x1B[2m${M}\x1B[0m`:M}var m=/(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/mg;function f(M){const D={};let $=M.toString();$=$.replace(/\r\n?/mg,`
|
|
1324
1324
|
`);let B;for(;(B=m.exec($))!=null;){const q=B[1];let L=B[2]||"";L=L.trim();const j=L[0];L=L.replace(/^(['"`])([\s\S]*)\1$/mg,"$2"),j==='"'&&(L=L.replace(/\\n/g,`
|
|
1325
1325
|
`),L=L.replace(/\\r/g,"\r")),D[q]=L}return D}function g(M){M=M||{};const D=k(M);M.path=D;const $=U.configDotenv(M);if(!$.parsed){const j=new Error(`MISSING_DATA: Cannot parse ${D} for an unknown reason`);throw j.code="MISSING_DATA",j}const B=b(M).split(","),q=B.length;let L;for(let j=0;j<q;j++)try{const G=B[j].trim(),J=S($,G);L=U.decrypt(J.ciphertext,J.key);break}catch(G){if(j+1>=q)throw G}return U.parse(L)}function y(M){console.error(`[dotenv@${a}][WARN] ${M}`)}function v(M){console.log(`[dotenv@${a}][DEBUG] ${M}`)}function T(M){console.log(`[dotenv@${a}] ${M}`)}function b(M){return M&&M.DOTENV_KEY&&M.DOTENV_KEY.length>0?M.DOTENV_KEY:process.env.DOTENV_KEY&&process.env.DOTENV_KEY.length>0?process.env.DOTENV_KEY:""}function S(M,D){let $;try{$=new URL(D)}catch(G){if(G.code==="ERR_INVALID_URL"){const J=new Error("INVALID_DOTENV_KEY: Wrong format. Must be in valid uri format like dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=development");throw J.code="INVALID_DOTENV_KEY",J}throw G}const B=$.password;if(!B){const G=new Error("INVALID_DOTENV_KEY: Missing key part");throw G.code="INVALID_DOTENV_KEY",G}const q=$.searchParams.get("environment");if(!q){const G=new Error("INVALID_DOTENV_KEY: Missing environment part");throw G.code="INVALID_DOTENV_KEY",G}const L=`DOTENV_VAULT_${q.toUpperCase()}`,j=M.parsed[L];if(!j){const G=new Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${L} in your .env.vault file.`);throw G.code="NOT_FOUND_DOTENV_ENVIRONMENT",G}return{ciphertext:j,key:B}}function k(M){let D=null;if(M&&M.path&&M.path.length>0)if(Array.isArray(M.path))for(const $ of M.path)r.existsSync($)&&(D=$.endsWith(".vault")?$:`${$}.vault`);else D=M.path.endsWith(".vault")?M.path:`${M.path}.vault`;else D=n.resolve(process.cwd(),".env.vault");return r.existsSync(D)?D:null}function A(M){return M[0]==="~"?n.join(o.homedir(),M.slice(1)):M}function x(M){const D=u(process.env.DOTENV_CONFIG_DEBUG||M&&M.debug),$=u(process.env.DOTENV_CONFIG_QUIET||M&&M.quiet);(D||!$)&&T("Loading env from encrypted .env.vault");const B=U._parseVault(M);let q=process.env;return M&&M.processEnv!=null&&(q=M.processEnv),U.populate(q,B,M),{parsed:B}}function P(M){const D=n.resolve(process.cwd(),".env");let $="utf8",B=process.env;M&&M.processEnv!=null&&(B=M.processEnv);let q=u(B.DOTENV_CONFIG_DEBUG||M&&M.debug),L=u(B.DOTENV_CONFIG_QUIET||M&&M.quiet);M&&M.encoding?$=M.encoding:q&&v("No encoding is specified. UTF-8 is used by default");let j=[D];if(M&&M.path)if(!Array.isArray(M.path))j=[A(M.path)];else{j=[];for(const de of M.path)j.push(A(de))}let G;const J={};for(const de of j)try{const oe=U.parse(r.readFileSync(de,{encoding:$}));U.populate(J,oe,M)}catch(oe){q&&v(`Failed to load ${de} ${oe.message}`),G=oe}const K=U.populate(B,J,M);if(q=u(B.DOTENV_CONFIG_DEBUG||q),L=u(B.DOTENV_CONFIG_QUIET||L),q||!L){const de=Object.keys(K).length,oe=[];for(const ae of j)try{const ge=n.relative(process.cwd(),ae);oe.push(ge)}catch(ge){q&&v(`Failed to load ${ae} ${ge.message}`),G=ge}T(`injecting env (${de}) from ${oe.join(",")} ${p(`-- tip: ${c()}`)}`)}return G?{parsed:J,error:G}:{parsed:J}}function C(M){if(b(M).length===0)return U.configDotenv(M);const D=k(M);return D?U._configVault(M):(y(`You set DOTENV_KEY but you are missing a .env.vault file at ${D}. Did you forget to build it?`),U.configDotenv(M))}function R(M,D){const $=Buffer.from(D.slice(-64),"hex");let B=Buffer.from(M,"base64");const q=B.subarray(0,12),L=B.subarray(-16);B=B.subarray(12,-16);try{const j=i.createDecipheriv("aes-256-gcm",$,q);return j.setAuthTag(L),`${j.update(B)}${j.final()}`}catch(j){const G=j instanceof RangeError,J=j.message==="Invalid key length",K=j.message==="Unsupported state or unable to authenticate data";if(G||J){const de=new Error("INVALID_DOTENV_KEY: It must be 64 characters long (or more)");throw de.code="INVALID_DOTENV_KEY",de}else if(K){const de=new Error("DECRYPTION_FAILED: Please check your DOTENV_KEY");throw de.code="DECRYPTION_FAILED",de}else throw j}}function O(M,D,$={}){const B=!!($&&$.debug),q=!!($&&$.override),L={};if(typeof D!="object"){const j=new Error("OBJECT_REQUIRED: Please check the processEnv argument being passed to populate");throw j.code="OBJECT_REQUIRED",j}for(const j of Object.keys(D))Object.prototype.hasOwnProperty.call(M,j)?(q===!0&&(M[j]=D[j],L[j]=D[j]),B&&v(q===!0?`"${j}" is already defined and WAS overwritten`:`"${j}" is already defined and was NOT overwritten`)):(M[j]=D[j],L[j]=D[j]);return L}var U={configDotenv:P,_configVault:x,_parseVault:g,config:C,decrypt:R,parse:f,populate:O};t.exports.configDotenv=U.configDotenv,t.exports._configVault=U._configVault,t.exports._parseVault=U._parseVault,t.exports.config=U.config,t.exports.decrypt=U.decrypt,t.exports.parse=U.parse,t.exports.populate=U.populate,t.exports=U}});async function UXr(){try{process.env.DOTENV_CONFIG_QUIET=process.env.DOTENV_CONFIG_QUIET??"true";const{config:e}=await Promise.resolve().then(()=>vc($Xr(),1)),t=process.env.DOTENV_CONFIG_PATH;e(t?{quiet:!0,path:t}:{quiet:!0})}catch{}}var BXr=E({"src/lib/utils/dotenvBootstrap.ts"(){"use strict"}});function kN(e,t){const{availableInputTokens:r,breakdown:n}=e,o=t===void 0?1:Math.max(0,Math.min(1,t/xN)),i=v$t*o;if(!n)return Math.max(0,Math.floor(r*i));const s=n.systemPrompt+n.currentPrompt+n.toolDefinitions+n.fileAttachments;return Math.max(0,Math.floor((r-s)*i))}function aa(e){const{traceId:t,parentSpanId:r}=wf(),n=Me.createSpan("context.compaction","context.budgetCheck",{"context.operation":"budgetCheck"},r,t),o=Date.now();try{const{provider:i,model:s,maxTokens:a,systemPrompt:l,conversationMessages:c,currentPrompt:u,toolDefinitions:d,fileAttachments:p,compactionThreshold:m=xN}=e,f=ql(i,s,a),g=l?Vt(l,i)+jl:0,y=c?.length?ri(c,i):0,v=u?Vt(u,i)+jl:0,T=d?.length?d.reduce((R,O)=>{try{const U=JSON.stringify(O);return R+Vt(U,i)}catch{return R+w$t}},0):0,b=p?.length?p.reduce((R,O)=>R+Vt(O.content,i),0):0,S=g+y+v+T+b,k=f>0?S/f:1,A=S<=f,x=k>=m,P={withinBudget:A,estimatedInputTokens:S,availableInputTokens:f,usageRatio:k,shouldCompact:x,breakdown:{systemPrompt:g,conversationHistory:y,currentPrompt:v,toolDefinitions:T,fileAttachments:b}};n.durationMs=Date.now()-o;const C=Me.endSpan(Me.updateAttributes(n,{"context.budgetUsage":k,"context.triggered":x,"context.estimatedTokens":S,"context.availableTokens":f,"context.compactionThreshold":m}),1);return it().recordSpan(C),P}catch(i){n.durationMs=Date.now()-o;const s=Me.endSpan(n,2);throw s.statusMessage=i instanceof Error?i.message:String(i),it().recordSpan(s),i}}var xN,v$t,w$t,T$t=E({"src/lib/context/budgetChecker.ts"(){"use strict";$c(),di(),No(),Tf(),xN=.8,v$t=.95,w$t=200}});function zXr(e,t){const r=t?.protectTokens??b$t,n=t?.minimumSavings??_$t,o=new Set(t?.protectedTools??["skill"]),i=t?.provider,s=[...e];let a=0,l=0;for(let u=s.length-1;u>=0;u--){const d=s[u];if(d.role!=="tool_result"||d.tool&&o.has(d.tool))continue;const p=Vt(d.content,i);if(a<r){a+=p;continue}d.content!==AN&&(l+=p-Vt(AN,i),s[u]={...d,content:AN,metadata:{...d.metadata,truncated:!0}})}const c=l>=n;return{pruned:c,messages:c?s:e,tokensSaved:c?l:0}}var AN,b$t,_$t,GXr=E({"src/lib/context/stages/toolOutputPruner.ts"(){"use strict";di(),AN="[Tool result cleared]",b$t=4e4,_$t=2e4}});function qXr(e){const t=new Map;for(let l=0;l<e.length;l++){const c=e[l];if(c.role!=="tool_result"&&c.role!=="assistant")continue;const u=c.content.match(E$t);if(u){const d=u[1],p=t.get(d)||[];p.push(l),t.set(d,p)}}const r=new Map;for(const[l,c]of t)c.length>1&&r.set(l,c);if(r.size===0)return{deduplicated:!1,messages:e,filesDeduped:0};const n=[...e];let o=0,i=0;for(const[l,c]of r){const u=c[c.length-1];for(const d of c){if(d===u)continue;const p=n[d];o+=p.content.length;const m=S$t(l);i+=m.length,n[d]={...p,content:m,metadata:{...p.metadata,truncated:!0}}}}const a=(o>0?(o-i)/o:0)>=k$t;return{deduplicated:a,messages:a?n:e,filesDeduped:a?r.size:0}}var E$t,S$t,k$t,VXr=E({"src/lib/context/stages/fileReadDeduplicator.ts"(){"use strict";E$t=/(?:read|reading|read_file|readFile|Read file|cat)\s+['"`]?([^\s'"`\n]+)/i,S$t=e=>`[File ${e} - refer to latest read below]`,k$t=.3}});function x$t(e){for(let t=1;t<e.length;t++)e[t].role===e[t-1].role&&e[t].role!=="system"&&h.warn(`[SlidingWindowTruncator] Role alternation broken at index ${t}: consecutive "${e[t].role}" messages`)}function jXr(e,t){if(!t?.targetTokens)return{truncated:!1,messages:e,messagesRemoved:0};const r=t.provider,n=t.targetTokens;if(ri(e,r)<=n)return{truncated:!1,messages:e,messagesRemoved:0};const i=200,s=24+e.length*4,a=n-s;if(a<=0)return{truncated:!1,messages:e,messagesRemoved:0};const l=e.map(p=>Vt(p.content,r)),c=l.reduce((p,m)=>p+m,0),u=[...e];let d=0;for(let p=0;p<u.length;p++){const m=u[p];if(m.role==="system"||m.metadata?.isSummary||m.metadata?.isSkill)continue;const f=Math.floor(l[p]/c*a),g=Math.max(i,f);if(l[p]>g){const y=IEt(m.content,g,r);y.truncated&&(d+=l[p]-Vt(y.text,r),u[p]={...m,content:y.text,metadata:{...m.metadata,truncated:!0}})}}if(d>0){const p=ri(u,r);return h.info("[Truncation] Small conversation content truncated",{messageCount:e.length,tokensSaved:d,targetTokens:n,finalTokens:p}),{truncated:p<=n,messages:u,messagesRemoved:0}}return{truncated:!1,messages:e,messagesRemoved:0}}function HXr(e,t){const r=new Map,n=[],o=[];for(let f=0;f<e.length;f++){const g=e[f];if(!g.metadata?.isSkill){o.push(g);continue}const y=e.slice(f+1).find(v=>!v.metadata?.isSkill);if(y){const v=r.get(y.id);v?v.push(g):r.set(y.id,[g])}else n.push(g)}if(o.length<=4)return jXr(e,t);let i;if(t?.currentTokens&&t?.targetTokens&&t.currentTokens>t.targetTokens){const f=(t.currentTokens-t.targetTokens)/t.currentTokens,g=t?.adaptiveBuffer??.15;i=Math.min(.9,Math.max(.1,f+g)),h.info("[Truncation] Adaptive fraction calculated",{currentTokens:t.currentTokens,targetTokens:t.targetTokens,overageRatio:Math.round(f*100),fraction:Math.round(i*100)})}else i=t?.fraction??.5;const s=o.slice(0,2),a=o.slice(2),l=(f,g)=>{const y=new Set([...s,...f].map(b=>b.id)),v=[];for(const[b,S]of r)y.has(b)||v.push(...S);const T=b=>{const S=r.get(b.id);return S?[...S,b]:[b]};return[...s.flatMap(T),g,...v,...f.flatMap(T),...n]},c=()=>{const f=Qe();return{id:`truncation-marker-${f}`,role:"user",content:A$t,isTruncationMarker:!0,truncationId:f}},u=t?.maxIterations??3;let d=i;for(let f=0;f<u;f++){const g=Math.floor(a.length*d),y=g-g%2;if(y<=0)break;const v=l(a.slice(y),c());if(x$t(v),t?.targetTokens){if(ri(v,t.provider)<=t.targetTokens)return{truncated:!0,messages:v,messagesRemoved:y};d=Math.min(.95,d+.1);continue}return{truncated:!0,messages:v,messagesRemoved:y}}const p=Math.floor(a.length*.95),m=p-p%2;if(m>0){const f=l(a.slice(m),c());return x$t(f),{truncated:!0,messages:f,messagesRemoved:m}}return{truncated:!1,messages:e,messagesRemoved:0}}var A$t,WXr=E({"src/lib/context/stages/slidingWindowTruncator.ts"(){"use strict";di(),z(),$t(),A$t="[Earlier conversation history was truncated to fit within context limits]"}});function C$t(e,t){if(!(e&&e.length>0||t&&t.length>0))return"";let n=`
|
|
1326
1326
|
|
|
@@ -2147,9 +2147,9 @@ ${r}`:r}}return t?`${t}
|
|
|
2147
2147
|
|
|
2148
2148
|
${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 i=(t.conversationMessages!==void 0?t.conversationMessages:await this.fetchRecentRoutingHistory(t)).filter(s=>s.role==="user"||s.role==="assistant").slice(-ON).map(s=>({role:s.role==="assistant"?"assistant":"user",text:typeof s.content=="string"?s.content:""}));return await r.ground({query:n,recentTurns:i,scope:t.knowledgeContext})}catch(o){h.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 Wse(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 i of n)yield i;t.streamSpan.setStatus({code:Ue.OK})}catch(i){throw t.streamSpan.setStatus({code:Ue.ERROR,message:i instanceof Error?i.message:String(i)}),i}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:i,hrTimeStart:s,streamId:a,originalPrompt:l,ttsResolver:c,ttsMetadataSink:u}=t;h.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:p}=await this.prepareStreamOptions(r,a,i,s);h.debug("[NeuroLink] Stream options prepared",{streamId:a,options:d,factoryResult:p,sessionId:d.context?.sessionId});const m={providerEmitted:!1};d._streamDedupContext=m;const f=await this.createMCPStream(d),{stream:g}=f,y=f.provider??"unknown";let v;const{stream:T,ttsMetadata:b}=await this.createIncrementalTTSStream({stream:g,ttsOptions:d.tts,providerName:y,fallbackProvider:d.provider,onComplete:q=>{v=q}});u?.(b);const S={finishReason:f.finishReason??"stop",toolCalls:void 0,toolResults:void 0},k=()=>S.toolCalls??f.toolCalls??[],A=()=>S.toolResults??f.toolResults??[];n.setAttribute(Re.NL_PROVIDER,y||"unknown");let x="",P=0;const{eventSequence:C,cleanup:R}=this.setupStreamEventListeners(),O={fallbackAttempted:!1,guardrailsBlocked:!1,error:void 0,fallbackProvider:void 0,fallbackModel:void 0},U=this,M=Date.now(),D=d.context?.sessionId,$=(async function*(){let q,L,j=0;try{for await(const K of T){P++;const de=K!==null&&typeof K=="object"&&"metadata"in K&&K.metadata?.noOutput===!0,oe=K&&"content"in K&&typeof K.content=="string"&&K.content.length>0,ae=K!==null&&typeof K=="object"&&"type"in K&&(K.type==="audio"||K.type==="tts_audio"||K.type==="image");!de&&(oe||ae)&&j++,K&&"content"in K&&typeof K.content=="string"&&(x+=K.content,U.emitter.emit("response:chunk",K.content),U.emitter.emit("stream:chunk",{type:"stream:chunk",content:K.content,metadata:{chunkIndex:P,totalLength:x.length,...de&&{noOutput:!0}},timestamp:Date.now()})),yield K}const G=d.fallbackOnMaxSteps===!1&&f.metadata?.stopReason==="step-cap";if(j===0&&!G&&!O.fallbackAttempted&&!d.disableInternalFallback&&k().length===0&&A().length===0){const K=U.handleStreamFallback(O,S,l,d,y,oe=>{x+=oe}),{stream:de}=await U.createIncrementalTTSStream({stream:K,ttsOptions:d.tts,providerName:y,fallbackProvider:d.provider,ttsMetadata:b,onComplete:oe=>{v=oe}});yield*de}c?.(v);const J=f.metadata?.finishReason;if(!O.fallbackAttempted&&(J==="length"||J==="tool-calls"||J==="content-filter")&&(S.finishReason=J),L=f.usage,!L&&f.analytics)try{const K=await Promise.resolve(f.analytics);K?.tokenUsage&&(L=K.tokenUsage)}catch{}L&&(f.usage=L),U.emitter.emit("stream:complete",{type:"stream:complete",content:x,provider:O.fallbackProvider??y,model:O.fallbackModel??f.model??d.model,finishReason:S.finishReason??"stop",prompt:d.input?.text||d.prompt,metadata:{chunkCount:P,totalLength:x.length,durationMs:Date.now()-M,sessionId:D,usage:L,finishReason:S.finishReason??"stop",...O.fallbackAttempted&&{primaryProvider:y,primaryModel:d.model,fallback:!0}},timestamp:Date.now()})}catch(G){throw h.debug("[NeuroLink.stream] Stream error occurred",{error:G instanceof Error?G.message:String(G),name:G instanceof Error?G.name:"UnknownError",provider:y,model:d.model,chunkCount:P,totalLength:x.length,durationMs:Date.now()-M,sessionId:D}),q=G,U.emitter.emit("stream:error",{type:"stream:error",content:G instanceof Error?G.message:String(G),provider:y,model:d.model,metadata:{chunkCount:P,totalLength:x.length,durationMs:Date.now()-M,errorName:G instanceof Error?G.name:"UnknownError",sessionId:D},timestamp:Date.now()}),G}finally{if(c?.(void 0),h.debug("[NeuroLink.stream] Stream finished, performing cleanup",{provider:y,model:d.model,totalChunks:P,totalLength:x.length,durationMs:Date.now()-M,fallbackAttempted:O.fallbackAttempted,guardrailsBlocked:O.guardrailsBlocked,error:O.error}),!m.providerEmitted)try{const J=O.fallbackProvider??y??"unknown",K=O.fallbackModel??f.model??d.model??"unknown",de=q?"error":S.finishReason??"stop";U.emitter.emit("generation:end",{provider:J,model:K,responseTime:Date.now()-M,toolsUsed:k().map(oe=>oe.toolName),timestamp:Date.now(),result:{content:x,usage:L,model:K,provider:J,finishReason:de},prompt:d.input?.text||d.prompt,temperature:d.temperature,maxTokens:d.maxTokens,success:!q,error:q?q instanceof Error?q.message:String(q):void 0,pipelineAHandled:!0})}catch(J){h.debug("[NeuroLink.stream] generation:end listener threw \u2014 ignored",{error:J instanceof Error?J.message:String(J)})}U._disableToolCacheForCurrentRequest=!1,U._toolCacheKeysServedThisRequest=new Set,U._generationTurnActive=!1,R(),n.setAttribute("neurolink.response_time_ms",Date.now()-o),n.setAttribute(Re.NL_OUTPUT_LENGTH,x.length);const G=!!(O.error||q);n.setAttribute(Re.GEN_AI_FINISH_REASON,G?"error":"stop"),O.fallbackAttempted&&(n.setAttribute("neurolink.fallback_triggered",!0),O.fallbackProvider&&n.setAttribute("neurolink.fallback_provider",O.fallbackProvider)),G?n.setStatus({code:Ue.ERROR,message:O.error||(q instanceof Error?q.message:String(q))}):n.setStatus({code:Ue.OK}),n.end(),x.trim()&&h.info("[NeuroLink.stream] stream() - COMPLETE SUCCESS",{provider:y,model:d.model,responseTimeMs:Date.now()-i,contentLength:x.length,fallback:O.fallbackAttempted}),await U.storeStreamConversationMemory({enhancedOptions:d,providerName:y,originalPrompt:l,accumulatedContent:x,startTime:i,eventSequence:C})}})(),B=await this.processStreamResult($,d,p);return S.finishReason=S.finishReason||B.finishReason,Object.defineProperty(B,"finishReason",{enumerable:!0,configurable:!0,get:()=>S.finishReason,set:q=>{S.finishReason=q}}),Object.defineProperty(B,"toolCalls",{enumerable:!0,configurable:!0,get:()=>k()}),Object.defineProperty(B,"toolResults",{enumerable:!0,configurable:!0,get:()=>A()}),B.usage||(B.usage=f.usage),B.analytics||(B.analytics=f.analytics),Promise.resolve(B.analytics).then(q=>{q?.cost&&q.cost>0&&(this._sessionCostUsd+=q.cost)}).catch(()=>{}),this.emitStreamEndEvents(B),this.createStreamResponse(B,$,{providerName:y,options:r,startTime:i,responseTime:Date.now()-i,streamId:a,fallback:O.fallbackAttempted,guardrailsBlocked:O.guardrailsBlocked,error:O.error,events:C,sourceResult:f})}catch(d){if(c?.(void 0),r.disableInternalFallback)throw d;return this.handleStreamError(d,r,i,a,void 0,void 0)}}async createIncrementalTTSStream(t){const{stream:r,ttsOptions:n,providerName:o,fallbackProvider:i,onComplete:s}=t;if(!n?.enabled)return s(void 0),{stream:r};const{TTSProcessor:a}=await Promise.resolve().then(()=>(al(),PJe)),l=i==="auto"?void 0:i,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 p=Date.now();let m=!1;const f=(g,y)=>{m||(m=!0,d.success=y===void 0&&g!==void 0,y?d.error=y:delete d.error,d.latency=Date.now()-p,s(g))};return u?{stream:GJe({stream:r,provider:u,options:n,onComplete:f}),ttsMetadata:d}:(h.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)`),f(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),h.debug("Memory retrieval successful")}catch(a){h.warn("Memory retrieval failed:",a)}if(await this.applySkillsAugmentation(t),this.enableOrchestration&&!t.provider&&!t.model)try{const a=await this.applyStreamOrchestration(t);h.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=tC(t.model,this.modelAliasConfig))}catch(a){h.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(()=>(aae(),sae)),l=await a(t.rag,t.provider);t.tools||(t.tools={}),t.tools[l.toolName]=l.tool;const c=[`
|
|
2149
2149
|
|
|
2150
|
-
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,h.info("[RAG] Tool injected into stream()",{toolName:l.toolName,filesLoaded:l.filesLoaded,chunksIndexed:l.chunksIndexed})}catch(a){h.warn("[RAG] Failed to prepare RAG tool, continuing without RAG",{error:a instanceof Error?a.message:String(a)})}const i=$in(t),s=Uin(t);if(t.input?.text){const{toolResults:a,enhancedPrompt:l}=await this.detectAndExecuteTools(t.input.text,void 0);l!==t.input.text&&(s.input.text=l)}return{enhancedOptions:s,factoryResult:i}}async autoDisableOllamaStreamTools(t){if((t.provider==="ollama"||t.provider?.toLowerCase().includes("ollama"))&&!t.disableTools){const{ModelConfigurationManager:r}=await Promise.resolve().then(()=>(Mf(),_Je)),i=r.getInstance().getProviderConfiguration("ollama")?.modelBehavior?.toolCapableModels||[],s=t.model;i.length>0&&s&&(i.some(l=>s.toLowerCase().includes(l.toLowerCase()))||(t.disableTools=!0,h.debug("Auto-disabled tools for Ollama model that doesn't support them (stream)",{model:t.model,toolCapableModels:i.slice(0,3)})))}}setupStreamEventListeners(){const t=[];let r=0;const n=(d,p)=>{t.push({type:d,seq:r++,timestamp:Date.now(),...p&&typeof p=="object"?p:{data:p}})},o=(...d)=>{const p=d[0];n("response:chunk",{content:p})},i=(...d)=>{const p=d[0];n("tool:start",{...p,toolName:p.toolName??p.tool})},s=(...d)=>{const p=d[0],m=p.toolName??p.tool,f=p.responseTime??p.duration,g=p.success??(p.error!==void 0?!1:void 0),y={...p,toolName:m,...f!==void 0?{responseTime:f}:{},...g!==void 0?{success:g}:{},...p.error!==void 0?{error:p.error}:{}};n("tool:end",y),y.result&&y.result.uiComponent===!0&&n("ui-component",{toolName:m,componentData:y.result,timestamp:Date.now(),...g!==void 0?{success:g}:{},...f!==void 0?{responseTime:f}:{}})},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",i),this.emitter.on("tool:end",s),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",i),this.emitter.off("tool:end",s),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,i,s){t.fallbackAttempted=!0;const a="Stream completed with 0 chunks (possible guardrails block)";t.error=a;try{const f=this._metricsTraceContext;let g=Me.createGenerationSpan({provider:i,model:o.model||"unknown",name:`gen_ai.${i}.stream.failed`,traceId:f?.traceId,parentSpanId:f?.parentSpanId});g=Me.endSpan(g,2),g.statusMessage=a,g.durationMs=0,this.metricsAggregator.recordSpan(g),it().recordSpan(g)}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,p=E3.getFallbackRoute(n||o.input.text||"",{provider:i,model:o.model||"gpt-4o",reasoning:"primary failed",confidence:.5},{fallbackStrategy:"auto"}),m={...p,provider:l??u??p.provider,model:c??d??p.model};h.warn("Retrying with fallback provider",{originalProvider:i,fallbackProvider:m.provider,fallbackModel:m.model,fallbackSource:l||c?"options":u||d?"env":"model_config",reason:a});try{const f=await Yn.createProvider(m.provider,m.model,!0,void 0,void 0,this.resolveCredentials(o.credentials));f.setupToolExecutor({customTools:this.getCustomTools(),executeTool:(x,P)=>this.executeTool(x,P,{disableToolCache:o.disableToolCache})},"NeuroLink.fallbackStream");const g=o.conversationMessages!==void 0?o.conversationMessages:await Wm(this.conversationMemory,{prompt:o.input.text,context:o.context});f.setFileToolRootPolicy?.(this.fileToolRootsFor(o));const y=await f.stream({...this.deferProviderStreamTTS(o),model:m.model,conversationMessages:g}),v=y.toolCalls??[],T=y.toolResults??[];(v.length>0||T.length>0)&&(r.toolCalls=v,r.toolResults=T,r.finishReason=y.finishReason??r.finishReason);let b=0,S=0;for await(const x of y.stream){b++;const P=x!==null&&typeof x=="object"&&"metadata"in x&&x.metadata?.noOutput===!0,C=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");!P&&(C||R)&&S++,x&&"content"in x&&typeof x.content=="string"&&(s(x.content),this.emitter.emit("response:chunk",x.content)),yield x}const k=y.toolCalls??[],A=y.toolResults??[];if(S===0&&k.length===0&&A.length===0)throw new Error(`Fallback provider ${m.provider} also returned 0 real output chunks (chunkCount=${b}, sentinel-only or empty)`);r.toolCalls=k,r.toolResults=A,r.finishReason=y.finishReason??r.finishReason,t.fallbackProvider=m.provider,t.fallbackModel=m.model,t.guardrailsBlocked=!0}catch(f){const g=f instanceof Error?f.message:String(f);throw t.error=`${a}; Fallback failed: ${g}`,h.error("Fallback provider failed",{fallbackProvider:m.provider,error:g}),f}}async storeStreamConversationMemory(t){const{enhancedOptions:r,providerName:n,originalPrompt:o,accumulatedContent:i,startTime:s,eventSequence:a}=t;h.shouldLog("debug")&&h.debug("[NeuroLink.stream] Preparing to store conversation turn in memory",{options:C4(I4(r)),sessionId:r.context?.sessionId});const l=a.some(c=>c.type==="tool:start"||c.type==="tool:end");if(!i.trim()&&!l){h.warn("[NeuroLink.stream] Skipping conversation turn storage \u2014 no text content or tool activity",{sessionId:r.context?.sessionId});return}if(h.shouldLog("debug")&&h.debug("[NeuroLink.stream] Storing conversation turn in memory",{options:C4(I4(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 p=Date.now();try{const m=this.drainPendingSkillMessages(c);await this.conversationMemory.storeConversationTurn({sessionId:c,userId:u,userMessage:o??"",aiResponse:i,startTimeStamp:new Date(s),providerDetails:d,enableSummarization:r.enableSummarization,events:a.length>0?a:void 0,requestId:r.context?.requestId,...m.length>0?{skillMessages:m}:{}}),this.recordMemorySpan("memory.store",{"memory.operation":"store","memory.path":"stream"},Date.now()-p,1),h.debug("[NeuroLink.stream] Stored conversation turn with events",{sessionId:c,eventCount:a.length,eventTypes:[...new Set(a.map(f=>f.type))]})}catch(m){this.recordMemorySpan("memory.store",{"memory.operation":"store","memory.path":"stream"},Date.now()-p,2,m instanceof Error?m.message:String(m)),h.warn("Failed to store stream conversation turn",{error:m instanceof Error?m.message:String(m)})}}this.shouldWriteMemory(r.memory,r.context?.userId,i)&&this.storeMemoryInBackground(o??"",i.trim(),r.context?.userId,r.memory?.additionalUsers,r.context)}async validateStreamInput(t){const r=process.hrtime.bigint();h.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"),i=!!(t?.stt?.enabled&&t?.stt?.audio);if(!n&&!o&&!i)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 oT(t.provider),n=await Yn.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:(f,g)=>this.executeTool(f,g,{disableToolCache:t.disableToolCache})},"NeuroLink.createMCPStream");let o=await this.getAllAvailableTools();o=this.applyToolInfoFiltering(o,t),Cr.getDescriptor(r)?.toolSupport==="none"&&(o=[]);const i=t.skipToolPromptInjection?t.systemPrompt||"":this.createToolAwareSystemPrompt(t.systemPrompt,o,n.supportsTools?.()??!0),s=t.conversationMessages!==void 0,a=s?t.conversationMessages:await Wm(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:i,conversationMessages:l,currentPrompt:t.input.text,toolDefinitions:o,compactionThreshold:t.compactionThreshold}),u=l?.length||0,d=this.getCompactionSessionId(t),p=u>0;if(!c.withinBudget&&!p){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 Na(`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&&(s||this.conversationMemory)&&u>(this.lastCompactionMessageCount.get(d)??0)){const g=await new Rw({provider:r,summarizationProvider:this.conversationMemoryConfig?.conversationMemory?.summarizationProvider,summarizationModel:this.conversationMemoryConfig?.conversationMemory?.summarizationModel},this.contextCompactorDeps()).compact(l,kN(c,t.compactionThreshold),this.conversationMemoryConfig?.conversationMemory,t.context?.requestId,{currentRequest:t.input.text});g.compacted&&(l=Cw(g.messages).messages,t.conversationMessages=l,this.lastCompactionMessageCount.set(d,l.length));const y=aa({provider:r,model:t.model,maxTokens:t.maxTokens,systemPrompt:i,conversationMessages:l,currentPrompt:t.input.text,toolDefinitions:o});if(!y.withinBudget){h.warn("[NeuroLink] Stream: post-compaction still over budget, emergency truncation",{estimatedTokens:y.estimatedInputTokens,availableTokens:y.availableInputTokens,overagePercent:Math.round((y.usageRatio-1)*100)});try{this.emitter.emit("compaction.insufficient",{stagesAttempted:g.stagesUsed,finalTokens:y.estimatedInputTokens,budget:y.availableInputTokens,provider:r,model:t.model,phase:"mid-compaction",willEmergencyTruncate:!0,timestamp:Date.now()})}catch{}l=Wte(l,y.availableInputTokens,y.breakdown,r),t.conversationMessages=l;const v=aa({provider:r,model:t.model,maxTokens:t.maxTokens,systemPrompt:i,conversationMessages:l,currentPrompt:t.input.text,toolDefinitions:o});if(!v.withinBudget){this.lastCompactionMessageCount.delete(d);try{this.emitter.emit("compaction.insufficient",{stagesAttempted:g.stagesUsed,finalTokens:v.estimatedInputTokens,budget:v.availableInputTokens,provider:r,model:t.model,phase:"post-emergency-truncation",timestamp:Date.now()})}catch{}throw new Na(`Stream context exceeds model budget after all compaction stages. Estimated: ${v.estimatedInputTokens} tokens, Budget: ${v.availableInputTokens} tokens.`,{estimatedTokens:v.estimatedInputTokens,availableTokens:v.availableInputTokens,stagesUsed:g.stagesUsed,breakdown:v.breakdown})}}}if(this.modelPool){const f=this.modelPool,g=f.maxAttempts,y=new Set;let v=null;for(let T=0;T<g;T++){if(t.abortSignal?.aborted)throw new DOMException("The operation was aborted","AbortError");const b=f.selectNext(y);if(!b)break;y.add(f.memberKey(b));const S=b.provider,k=b.model??void 0,A=b.region??void 0;h.debug(`[createMCPStream] ModelPool: attempting member ${S}`,{model:k,attempt:T});try{const x=await Yn.createProvider(S,k,!t.disableTools,this,A,this.resolveCredentials(t.credentials));x.setTraceContext(this._metricsTraceContext),x.setupToolExecutor({customTools:this.getCustomTools(),executeTool:(O,U)=>this.executeTool(O,U,{disableToolCache:t.disableToolCache})},"NeuroLink.createMCPStream"),x.setFileToolRootPolicy?.(this.fileToolRootsFor(t));const P=await x.stream({...this.deferProviderStreamTTS(t),provider:S,model:k,region:A,systemPrompt:i,conversationMessages:l});h.debug("[createMCPStream] ModelPool stream handle obtained",{provider:S});const C=b,R=(async function*(){try{yield*P.stream,f.recordSuccess(C)}catch(O){throw f.recordFailure(C,iT(O)),O}})();return vO(P,{...P,stream:R,provider:S,model:P.model||k,toolCalls:P.toolCalls??[],toolResults:P.toolResults??[]})}catch(x){if(pr(x))throw x;if(Kae(x)){const P=x instanceof Error?x.message:String(x);throw f.recordFailure(b,iT(x)),new Error(`[ModelPool] non-retryable: ${P}`,{cause:x})}f.recordFailure(b,iT(x)),v=x instanceof Error?x:new Error(String(x)),h.warn(`[createMCPStream] ModelPool: member ${S} failed`,{error:v.message})}}throw new Error(`[ModelPool] all stream members failed: ${v?.message??"no stream members available"}`)}n.setFileToolRootPolicy?.(this.fileToolRootsFor(t));const m=await n.stream({...this.deferProviderStreamTTS(t),systemPrompt:i,conversationMessages:l});return h.debug("[createMCPStream] Stream created successfully",{provider:r,systemPromptPassedLength:i.length}),vO(m,{...m,provider:r,model:m.model||t.model,toolCalls:m.toolCalls??[],toolResults:m.toolResults??[]})}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){const o=n.sourceResult,i={streamId:n.streamId,startTime:n.startTime,responseTime:n.responseTime,fallback:n.fallback||!1,guardrailsBlocked:n.guardrailsBlocked,error:n.error},s={...o??{},stream:r,provider:o?.provider??n.providerName,model:o?.model??n.options.model,usage:t.usage,finishReason:t.finishReason,analytics:t.analytics,evaluation:t.evaluation,events:n.events&&n.events.length>0?n.events:void 0,metadata:o?void 0:Object.assign({},i)},a=Object.getOwnPropertyDescriptor(t,"toolCalls");a&&Object.defineProperty(s,"toolCalls",a);const l=Object.getOwnPropertyDescriptor(t,"toolResults");l&&Object.defineProperty(s,"toolResults",l);const c=Object.getOwnPropertyDescriptor(t,"finishReason");if(c&&Object.defineProperty(s,"finishReason",c),!o)return s;const u=new Set(["finishReason","stopReason","rawFinishReason","toolCalls","toolResults"]);for(const d of Object.getOwnPropertyNames(o)){const p=Object.getOwnPropertyDescriptor(o,d);!u.has(d)&&p&&typeof p.get=="function"&&Object.defineProperty(s,d,p)}return Object.defineProperty(s,"metadata",{enumerable:!0,configurable:!0,get:()=>(o.metadata===void 0&&(o.metadata={}),Object.assign(o.metadata,i)),set:d=>{o.metadata=d}}),s}async handleStreamError(t,r,n,o,i,s){if(t instanceof Na)throw t;h.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 oT(r.provider),u=await Yn.createProvider(c,r.model,!0,void 0,void 0,this.resolveCredentials(r.credentials));u.setFileToolRootPolicy?.(this.fileToolRootsFor(r));const d=await u.stream({input:{text:r.input.text},model:r.model,temperature:r.temperature,maxTokens:r.maxTokens,conversationMessages:r.conversationMessages});let p="";return{stream:(async function*(f){try{for await(const g of d.stream)g&&"content"in g&&typeof g.content=="string"&&(p+=g.content,f.emitter.emit("response:chunk",g.content)),yield g}finally{if(p.trim()){h.info("[NeuroLink.handleStreamError] stream() - COMPLETE SUCCESS (fallback)",{provider:c,model:r.model,responseTimeMs:Date.now()-n,contentLength:p.length});try{const g=r.model||"unknown",y=Date.now()-n;f.emitter.emit("stream:complete",{content:p,provider:c,model:g,finishReason:"stop",metadata:{durationMs:y,chunkCount:0,totalLength:p.length,isFallback:!0,finishReason:"stop"}}),f.emitter.emit("generation:end",{provider:c,model:g,responseTime:y,timestamp:Date.now(),result:{content:p,usage:{input:0,output:0,total:0},model:g,provider:c,finishReason:"stop"},success:!0,pipelineAHandled:!0})}catch{}}if(f.conversationMemory&&i?.context?.sessionId&&p.trim()){const g=i?.context?.sessionId,y=i?.context?.userId;let v;r.model&&(v={provider:c,model:r.model});const T=Date.now();try{const b=g||r.context?.sessionId,S=f.drainPendingSkillMessages(b);await f.conversationMemory.storeConversationTurn({sessionId:b,userId:y||r.context?.userId,userMessage:a??"",aiResponse:p,startTimeStamp:new Date(n),providerDetails:v,enableSummarization:i?.enableSummarization,requestId:i?.context?.requestId||r.context?.requestId,...S.length>0?{skillMessages:S}:{}}),f.recordMemorySpan("memory.store",{"memory.operation":"store","memory.path":"fallback-stream"},Date.now()-T,1)}catch(b){f.recordMemorySpan("memory.store",{"memory.operation":"store","memory.path":"fallback-stream"},Date.now()-T,2,b instanceof Error?b.message:String(b)),h.warn("Failed to store fallback stream conversation turn",{error:b instanceof Error?b.message:String(b)})}}}})(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}fileToolRootsFor(t){return wV(t)??this.resolveFileToolRoots(t.toolRoots)}workerToolsConfig(t){const r=this.toolsConfig?.fileRoots;if(t?.fileRoots===void 0)return r===void 0?t:{...t,fileRoots:r};const n=_P({perCall:t.fileRoots,instance:r}).roots;return{...t,fileRoots:n?[...n]:[]}}resolveFileToolRoots(t){return _P({perCall:t,instance:this.toolsConfig?.fileRoots})}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(i){const s=i instanceof Error?i.message:String(i),a=s.toLowerCase();return i instanceof ry?{provider:r,status:"denied",detail:s}: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:s}: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:s}: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:s}:{provider:r,status:"unknown",detail:s}}}emitToolStart(t,r,n=Date.now()){const o=`${t}-${n}-${Math.random().toString(36).substr(2,9)}`,i={executionId:o,tool:t,startTime:n,metadata:{inputType:typeof r,hasInput:r!=null}};return this.activeToolExecutions.set(o,i),this.currentStreamToolExecutions.push(i),this.emitter.emit("tool:start",Bv(t,{input:r,timestamp:n,executionId:o})),h.debug(`tool:start emitted for ${t}`,{toolName:t,executionId:o,timestamp:n,inputProvided:r!==void 0}),o}emitToolEnd(t,r,n,o,i=Date.now(),s){const a=o||i-1e3,l=i-a,c=!n;let u;s?u=this.activeToolExecutions.get(s):u=Array.from(this.activeToolExecutions.values()).find(m=>m.tool===t&&!m.endTime);const d=s||u?.executionId||`${t}-${a}-fallback-${Math.random().toString(36).substr(2,9)}`;u&&(u.endTime=i,u.result=r,u.error=n,this.activeToolExecutions.delete(u.executionId));const p={tool:t,startTime:a,endTime:i,duration:l,success:c,result:r,error:n,executionId:d,metadata:{toolCategory:"custom"}};this.toolExecutionHistory.push(p),this.emitter.emit("tool:end",Bv(t,{result:r,error:n,success:c,responseTime:l,timestamp:i,duration:l,executionId:d})),h.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&&(BH(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 s=o.execute,a=n.timeout,l=t;o.execute=async(...c)=>{const u=AbortSignal.timeout(a),d=c[1],p=d?.abortSignal,m=p?AbortSignal.any([p,u]):u,f={...d,abortSignal:m};return Promise.race([s(c[0],f),new Promise((g,y)=>{m.addEventListener("abort",()=>{u.aborted?y(he.toolTimeout(l,a)):y(new DOMException("The operation was aborted","AbortError"))},{once:!0})})])}}const i=qtn(t,o,n?.timeout,n?.maxRetries,n?.totalTimeoutMs);this.toolRegistry.registerServer(i),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 h.error(`Failed to register tool ${t}:`,o),o}}setToolContext(t){this.toolExecutionContext={...t},h.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,h.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),h.info(`Unregistered custom tool: ${t}`)),n}useToolMiddleware(t){return this.mcpToolMiddlewares.push(t),h.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 Ya("Conversation memory is not initialized. Enable conversationMemory in NeuroLink options.","CONFIG_ERROR");if(!("updateAgenticLoopReport"in this.conversationMemory)||typeof this.conversationMemory.updateAgenticLoopReport!="function")throw new Ya("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(la({isCustomTool:!0})),r=new Map;for(const o of t){const i=o.inputSchema||o.parameters;h.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:!!i,effectiveSchemaType:typeof i,effectiveSchemaHasProperties:!!i?.properties,effectiveSchemaHasRequired:!!i?.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(s,a)=>{const l=this.toolExecutionContext||{},c=a&&er(a)?a:{},u={...l,...c,sessionId:c.sessionId||l.sessionId||`fallback-${Date.now()}`};return h.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,s,u)}})}this.cachedFileTools||(this.cachedFileTools=i5t(this.fileRegistry));const n=this.cachedFileTools;for(const[o,i]of Object.entries(n))if(!r.has(o)){const s=i,a=s.inputSchema??s.parameters;r.set(o,{name:o,description:i.description||`File tool: ${o}`,inputSchema:typeof a=="object"&&a!==null?a:{type:"object",properties:{}},execute:async l=>await i.execute(l,{toolCallId:`file-tool-${Date.now()}`,messages:[]})})}return r}async addInMemoryMCPServer(t,r){this.invalidateToolCache();try{re.debug(`[NeuroLink] Registering in-memory MCP server: ${t}`),r.tools||(r.tools=[]),await this.toolRegistry.registerServer(r),re.info(`[NeuroLink] Successfully registered in-memory server: ${t}`,{category:r.metadata?.category,provider:r.metadata?.provider,version:r.metadata?.version})}catch(n){throw re.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=>la({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 Be.mcp.startActiveSpan("neurolink.tool.execute",{attributes:{"tool.name":t,"tool.type":o.toolType,"tool.input_size":o.inputSize,"tool.input_preview":o.truncatedInput}},i=>this.executeToolWithSpan(t,r,n,o,i))}createToolExecutionContext(t,r,n){const o=this.externalServerManager.getAllTools().find(c=>c.name===t),i=o?"mcp":this.getCustomTools().has(t)?"custom":"external",s=r?My(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:i,inputSize:s.length,truncatedInput:s.length>2048?s.substring(0,2048):s,options:n,hitlState:{triggered:!1}}}async executeToolWithSpan(t,r,n,o,i){try{const s=await this.prepareToolExecutionState(t,r,n,o);return await this.runPreparedToolExecution(t,r,s,o,i)}catch(s){if(!(s instanceof De)){const a=s instanceof Error?s.message:String(s);i.recordException(s instanceof Error?s:new Error(a)),i.setStatus({code:Ue.ERROR,message:a})}throw s}finally{i.end()}}async prepareToolExecutionState(t,r,n,o){h.debug(`[${o.functionTag}] Tool execution requested:`,{toolName:t,params:er(r)?CXe(r):r,hasExternalManager:!!this.externalServerManager}),h.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",Bv(t,{timestamp:o.executionStartTime,input:r,executionId:o.executionId}));const i=this.toolRegistry.getToolInfo(t),s=n?.timeout??i?.tool?.timeoutMs??Pl.EXECUTION_BATCH_MS,a=n?.maxRetries??i?.tool?.maxRetries??fi.DEFAULT,l=n?.retryDelayMs||eo.BASE_MS,c={timeout:s,maxRetries:a,totalTimeout:n?.totalTimeoutMs??i?.tool?.totalTimeoutMs??s*(a+1)+l*a,retryDelayMs:l,authContext:n?.authContext,disableToolCache:n?.disableToolCache},{MemoryManager:u}=await Promise.resolve().then(()=>(iC(),lT)),d=u.getMemoryUsageMB(),m=`${o.externalTool?.serverId||i?.tool?.serverId||"unknown"}.${t}`;let f=this.toolCircuitBreakers.get(m);f||(f=new k4(SI.FAILURE_THRESHOLD,w5),this.toolCircuitBreakers.set(m,f));let g=this.toolExecutionMetrics.get(t);return g||(g={totalExecutions:0,successfulExecutions:0,failedExecutions:0,averageExecutionTime:0,lastExecutionTime:0,errorCategories:{}},this.toolExecutionMetrics.set(t,g)),g.totalExecutions++,{finalOptions:c,startMemory:d,circuitBreaker:f,breakerKey:m,metrics:g}}async runPreparedToolExecution(t,r,n,o,i){let s=0;try{re.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 p=await n.circuitBreaker.execute(async()=>Obe(async()=>{d++;const m=u-Date.now();if(m<=0)throw he.toolTimeout(t,l,void 0,{attempt:d,maxAttempts:a,attemptTimeoutMs:n.finalOptions.timeout,totalTimeoutMs:l,elapsedMs:Date.now()-c,exhausted:!0});const f=Math.min(n.finalOptions.timeout,m);return ze(this.executeToolInternal(t,r,n.finalOptions,o.hitlState),f,he.toolTimeout(t,f,void 0,{attempt:d,maxAttempts:a,attemptTimeoutMs:n.finalOptions.timeout,totalTimeoutMs:l,elapsedMs:Date.now()-c}))},{maxAttempts:a,delayMs:n.finalOptions.retryDelayMs,isRetriable:m=>Date.now()+n.finalOptions.retryDelayMs<u&&XG(m),onRetry:(m,f)=>{s=m,re.warn(`[${o.functionTag}] Retrying tool execution (attempt ${m})`,{toolName:t,error:f.message,attempt:m})}}));return i.setAttribute("tool.retry_count",s),await this.handleSuccessfulToolExecution(t,p,n,o,i)}catch(a){return i.setAttribute("tool.retry_count",s),this.handleFailedToolExecution(t,r,a,n,o,i)}}async handleSuccessfulToolExecution(t,r,n,o,i){const s=Date.now()-o.executionStartTime;n.metrics.successfulExecutions++,n.metrics.lastExecutionTime=s,n.metrics.averageExecutionTime=(n.metrics.averageExecutionTime*(n.metrics.successfulExecutions-1)+s)/n.metrics.successfulExecutions;const{MemoryManager:a}=await Promise.resolve().then(()=>(iC(),lT)),c=a.getMemoryUsageMB().heapUsed-n.startMemory.heapUsed;c>20&&re.warn(`Tool '${t}' used excessive memory: ${c}MB`,{toolName:t,memoryDelta:c,executionTime:s}),re.debug(`[${o.functionTag}] Tool executed successfully`,{toolName:t,executionTime:s,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,p=d?u?.content:void 0,m=d?p?.filter(f=>f.type==="text"&&f.text).map(f=>f.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{}re.debug(`[${o.functionTag}] Circuit breaker failure recorded for isError result`,{toolName:t,circuitBreakerState:n.circuitBreaker.getState(),circuitBreakerFailures:n.circuitBreaker.getFailureCount()});const f=$ln(m??"Unknown error"),g=`[TOOL_ERROR: ${t} failed (${f})] `;if(u&&Array.isArray(p)){const T=p.map(b=>({...b}));for(const b of T)if(b.type==="text"&&b.text){b.text=g+b.text;break}u.content=T}i.setAttribute("tool.error.message",(m??"Unknown error").substring(0,500)),i.setAttribute("tool.error.category",f),i.setStatus({code:Ue.ERROR,message:`MCP tool returned isError: ${(m??"Unknown error").substring(0,200)}`}),n.metrics.failedExecutions++;const y=n.metrics.successfulExecutions;n.metrics.successfulExecutions=Math.max(0,n.metrics.successfulExecutions-1),n.metrics.averageExecutionTime=y>1?(n.metrics.averageExecutionTime*y-s)/(y-1):0;const v=Uln(f);n.metrics.errorCategories[v]=(n.metrics.errorCategories[v]||0)+1}return this.emitToolEndEvent(t,o.executionStartTime,!d,r,d&&m?new Error(m):void 0,o.executionId),i.setAttribute("tool.result.status",d?"error":"success"),i.setAttribute("tool.duration_ms",s),r}async handleFailedToolExecution(t,r,n,o,i,s){o.metrics.failedExecutions++;const a=Date.now()-i.executionStartTime;if(n instanceof jp)return re.warn(`[${i.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,i.executionStartTime,!1,void 0,new Error(`Circuit breaker open for ${t} (state=${n.breakerState}, failures=${n.failureCount})`),i.executionId),s.setAttribute("tool.result.status","circuit_breaker_open"),s.setAttribute("tool.duration_ms",a),s.setAttribute("tool.circuit_breaker.state",n.breakerState),s.setAttribute("tool.circuit_breaker.retry_after_ms",n.retryAfterMs),s.setAttribute("tool.circuit_breaker.failure_count",n.failureCount),s.setStatus({code:Ue.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 De)l=n;else if(n instanceof Error)if(n.message.includes("timeout"))l=he.toolTimeout(t,o.finalOptions.timeout);else if(n.message.includes("not found")){const u=await this.getAllAvailableTools();l=he.toolNotFound(t,QBr(u.map(d=>({name:d.name}))))}else n.message.includes("validation")||n.message.includes("parameter")?l=he.invalidParameters(t,n,r):n.message.includes("network")||n.message.includes("connection")?l=he.networkError(t,n):l=he.toolExecutionFailed(t,n);else l=he.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,i.executionStartTime,!1,void 0,l,i.executionId),this.emitter.listenerCount("error")>0&&this.emitter.emit("error",l),l=new De({...l,context:{...l.context,executionTime:a,params:r,options:o.finalOptions,circuitBreakerState:o.circuitBreaker.getState(),circuitBreakerFailures:o.circuitBreaker.getFailureCount(),metrics:{...o.metrics}}}),Dbe(l),s.setAttribute("tool.result.status","error"),s.setAttribute("tool.duration_ms",a),s.recordException(l),s.setStatus({code:Ue.ERROR,message:l.message}),l}toolCacheRepeatKey(t,r){try{return`${t}:${JSON.stringify(r)??""}`}catch{return}}async executeToolInternal(t,r,n,o){const i="NeuroLink.executeToolInternal",s=this.getToolAnnotationsForExecution(t),a=this.mcpToolResultCache&&!n.disableToolCache&&!this._disableToolCacheForCurrentRequest&&!this.uncacheableTools.has(t)&&!s?.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 f=l.getCachedResult(t,c);if(f!==void 0)return h.debug(`[${i}] Cache HIT for tool: ${t}`),f}else d&&h.debug(`[${i}] Repeat call within this request \u2014 bypassing tool cache for: ${t}`);const p=async f=>{if(this.mcpToolMiddlewares.length===0)return f();let g=0;const y=async()=>{if(g<this.mcpToolMiddlewares.length){const v=this.mcpToolMiddlewares[g++];return v({name:t,description:"",inputSchema:{},annotations:s,execute:async()=>({})},r,{toolMeta:{name:t,annotations:s}},y)}return f()};return await y()},m=async()=>{const f=this.externalServerManager.getAllTools(),g=f.filter(v=>v.name===t&&v.isAvailable);let y;if(g.length>1&&this.mcpToolRouter)try{const v={name:t,description:g[0].description??"",serverId:g[0].serverId,inputSchema:{}},T=this.mcpToolRouter.route(v);y=g.find(b=>b.serverId===T.serverId)||g[0],h.debug(`[${i}] Router selected server: ${T.serverId}`,{strategy:T.strategy,confidence:T.confidence})}catch(v){h.warn(`[${i}] Router failed, falling back to first match`,{error:v}),y=g[0]}else y=g[0];if(h.debug(`[${i}] External MCP tool search:`,{toolName:t,externalToolsCount:f.length,foundTool:!!y,isAvailable:y?.isAvailable,serverId:y?.serverId}),y&&y.isAvailable)try{re.debug(`[${i}] Executing external MCP tool: ${t} from ${y.serverId}`);const v=await this.externalServerManager.executeTool(y.serverId,t,r,{timeout:n.timeout});return h.debug(`[${i}] External MCP tool execution successful:`,{toolName:t,serverId:y.serverId,resultType:typeof v}),v}catch(v){throw h.error(`[${i}] External MCP tool execution failed:`,{toolName:t,serverId:y.serverId,error:v instanceof Error?v.message:String(v)}),he.toolExecutionFailed(t,v instanceof Error?v:new Error(String(v)),y.serverId)}try{const v=this.toolExecutionContext||{},T=n.authContext||{},b=XE({...v,...T,hitlState:o},this.resolveFileToolRoots(void 0));h.debug("[Using merged context for unified registry tool:",{toolName:t,storedContextKeys:Object.keys(v),finalContextKeys:Object.keys(b)});const S=await this.toolRegistry.executeTool(t,r,b);if(S&&typeof S=="object"&&"success"in S&&S.success===!1){const k=S.error||"Tool execution failed",A=new Error(k);this.emitter.listenerCount("error")>0&&this.emitter.emit("error",A)}return S}catch(v){const T=v instanceof Error?v:new Error(String(v));if(this.emitter.listenerCount("error")>0&&this.emitter.emit("error",T),v instanceof Error&&v.message.includes("not found")){const b=await this.getAllAvailableTools();throw he.toolNotFound(t,b.map(S=>S.name))}throw he.toolExecutionFailed(t,v instanceof Error?v:new Error(String(v)))}};try{const f=await p(m);return a&&l&&f!==void 0&&(l.cacheResult(t,c,f),h.debug(`[${i}] Cached result for tool: ${t}`)),f}catch(f){const g=s?{name:t,description:"",annotations:s,execute:async()=>({})}:void 0;if(g&&qY(g)&&f instanceof Error&&XG(f)){h.debug(`[${i}] Tool ${t} is safe to retry, attempting once more`);try{const y=await p(m);return a&&l&&y!==void 0&&l.cacheResult(t,c,y),y}catch{}}throw f}}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 np({name:t,description:""})}invalidateToolCache(){this.toolCache=null,h.debug("Tool cache invalidated")}async getAllAvailableTools(){if(this.toolCache&&Date.now()-this.toolCache.timestamp<this.toolCacheDuration)return h.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();h.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:!!Yn,providerRegistrySize:0},message:"Starting comprehensive tool discovery across all sources"});const{MemoryManager:o}=await Promise.resolve().then(()=>(iC(),lT)),i=o.getMemoryUsageMB();try{const s=new Map,a=await this.toolRegistry.listTools();for(const g of a)if(!s.has(g.name)){const y=kM(g,{serverId:g.serverId==="direct"?"neurolink-direct":g.serverId});s.set(g.name,y)}const l=this.toolRegistry.getToolsByCategory(la({isCustomTool:!0}));for(const g of l)if(!s.has(g.name)){const y=kM(g,{description:"Custom tool",serverId:`custom-tool-${g.name}`,category:la({isCustomTool:!0,serverId:g.serverId}),inputSchema:{}});s.set(g.name,y)}const c=this.toolRegistry.getToolsByCategory("in-memory");for(const g of c)if(!s.has(g.name)){const y=kM(g,{description:"In-memory MCP tool",serverId:"unknown",category:"in-memory",inputSchema:{}});s.set(g.name,y)}const u=this.externalServerManager.getAllTools();for(const g of u)if(!s.has(g.name)){const y=kM(g,{category:la({existingCategory:typeof g.metadata?.category=="string"?g.metadata.category:void 0,isExternal:!0,serverId:g.serverId}),inputSchema:{}});s.set(g.name,y)}const d=Array.from(s.values());re.debug("Tool discovery results",{mcpTools:a.length,customTools:l.length,inMemoryTools:c.length,externalMCPTools:u.length,total:d.length});const m=o.getMemoryUsageMB().heapUsed-i.heapUsed;if(m>Wp.LOW_USAGE_MB&&(re.debug(`\u{1F50D} Tool listing used ${m}MB memory (large tool registry detected)`),d.length>R0e.LARGE_TOOL_COLLECTION&&re.debug("\u{1F4A1} Tool collection optimized for large sets. Memory usage reduced through efficient object reuse.")),this.mcpEnhancementsConfig?.annotations?.autoInfer!==!1)for(const g of d)g.annotations||(g.annotations=np({name:g.name,description:g.description||""}));const f=d.sort((g,y)=>g.name<y.name?-1:g.name>y.name?1:0);return this.toolCache={tools:f,timestamp:Date.now()},f}catch(s){return re.error("Failed to list available tools",{error:s}),[]}}async getProviderStatus(t){const{MemoryManager:r}=await Promise.resolve().then(()=>(iC(),lT)),n=r.getMemoryUsageMB();t?.quiet||re.debug("\u{1F50D} DEBUG: Initializing MCP for provider status..."),await this.initializeMCP(),t?.quiet||re.debug("\u{1F50D} DEBUG: MCP initialized:",this.mcpInitialized);const{AIProviderFactory:o}=await Promise.resolve().then(()=>(Ga(),DC)),{hasProviderEnvVars:i}=await Promise.resolve().then(()=>(oh(),rC)),s=Cr.getAllDescriptors().map(p=>p.name),a=$f(Ea.DEFAULT_CONCURRENCY_LIMIT),l=s.map(p=>a(async()=>{const m=Date.now();try{if(!await this.hasProviderEnvVars(p)&&p!=="ollama")return{provider:p,status:"not-configured",configured:!1,authenticated:!1,error:"Missing required environment variables",responseTime:Date.now()-m};if(p==="ollama")try{const S=await fetch("http://localhost:11434/api/tags",{method:"GET",signal:AbortSignal.timeout(Ml.AUTH_MS)});if(!S.ok)throw new Error("Ollama service not responding");const k=await S.json(),A=k?.models;if(!Array.isArray(A))throw h.warn("Ollama API returned invalid models format in testProvider",{responseData:k,modelsType:typeof A}),new Error("Invalid models format from Ollama API");const x=A.filter(P=>P&&typeof P=="object"&&typeof P.name=="string");return x.length>0?{provider:p,status:"working",configured:!0,authenticated:!0,responseTime:Date.now()-m,model:x[0].name}:{provider:p,status:"failed",configured:!0,authenticated:!1,error:"Ollama service running but no models installed",responseTime:Date.now()-m}}catch(S){return{provider:p,status:"failed",configured:!1,authenticated:!1,error:S instanceof Error?S.message:"Ollama service not running",responseTime:Date.now()-m}}const g=5e3,y=new AbortController,v=this.testProviderConnection(p,y.signal);let T;const b=new Promise((S,k)=>{T=setTimeout(()=>{k(new Error("Provider test timeout (5s)"))},g)});try{await Promise.race([v,b])}finally{clearTimeout(T),v.catch(()=>{}),y.abort()}return{provider:p,status:"working",configured:!0,authenticated:!0,responseTime:Date.now()-m}}catch(f){const g=f instanceof Error?f.message:String(f);return{provider:p,status:"failed",configured:!0,authenticated:!1,error:g,responseTime:Date.now()-m}}})),c=await Promise.all(l),d=r.getMemoryUsageMB().heapUsed-n.heapUsed;return!t?.quiet&&d>20&&re.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,r){const{AIProviderFactory:n}=await Promise.resolve().then(()=>(Ga(),DC));await(await n.createProvider(t,null)).generate({prompt:"test",maxTokens:1,disableTools:!0,abortSignal:r})}async getBestProvider(t){const{getBestProvider:r}=await Promise.resolve().then(()=>(oh(),rC));return r(t)}async getAvailableProviders(){const{getAvailableProviders:t}=await Promise.resolve().then(()=>(oh(),rC));return t()}async isValidProvider(t){const{isValidProvider:r}=await Promise.resolve().then(()=>(oh(),rC));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(),i=this.toolRegistry.getBuiltInServerInfos(),s=this.getAutoDiscoveredServerInfos(),a=n.length+o.length+i.length+s.length,l=r.connectedServers+o.length+i.length,c=t.length+r.totalTools;return{mcpInitialized:this.mcpInitialized,totalServers:a,availableServers:l,autoDiscoveredCount:s.length,totalTools:c,autoDiscoveredServers:s,customToolsCount:this.toolRegistry.getToolsByCategory(la({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(la({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 re.error(`[NeuroLink] Error testing MCP server ${t}:`,r),!1}}async hasProviderEnvVars(t){const{ProviderHealthChecker:r}=await Promise.resolve().then(()=>(d0(),rT));try{const n=await r.checkProviderHealth(t,{includeConnectivityTest:!1,cacheResults:!1});return n.isConfigured&&n.hasApiKey}catch(n){return h.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(()=>(d0(),rT)),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(()=>(d0(),rT));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(()=>(d0(),rT)),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(()=>(d0(),rT));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,h.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 k4(SI.FAILURE_THRESHOLD,w5)),re.info(`Circuit breaker reset for tool: ${t}`))}clearToolExecutionMetrics(){this.toolExecutionMetrics.clear(),re.info("All tool execution metrics cleared")}async getToolHealthReport(){const t={};let r=0;const n=await this.toolRegistry.listTools(),o=new Set(n.map(s=>s.name)),i=new Map;for(const s of n)i.has(s.name)||i.set(s.name,s.serverId||"unknown");for(const s of o){const a=this.toolExecutionMetrics.get(s),l=`${i.get(s)||"unknown"}.${s}`,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 p=[],m=[];if(c&&c.getState()==="open"&&(p.push("Circuit breaker is open due to repeated failures"),m.push("Check tool implementation and fix underlying issues")),u<.8&&a&&a.totalExecutions>0&&(p.push(`Low success rate: ${(u*100).toFixed(1)}%`),m.push("Review error logs and improve tool reliability")),a&&a.averageExecutionTime>1e4&&(p.push("High average execution time"),m.push("Optimize tool performance or increase timeout")),a&&a.errorCategories){const f=a.errorCategories;f.timeout>0&&(p.push(`Timeout errors: ${f.timeout}`),m.push("Consider increasing the tool timeout configuration")),f.validation>0&&(p.push(`Validation errors: ${f.validation}`),m.push("Review input schemas and parameter validation")),f.network>0&&(p.push(`Network errors: ${f.network}`),m.push("Check network connectivity and endpoint availability"))}t[s]={name:s,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:p,recommendations:m}}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 h.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 De({code:He.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 De({code:He.MISSING_CONFIGURATION,message:"Conversation memory is not enabled",category:"validation",severity:"high",retriable:!1});if(!t||typeof t!="string")throw new De({code:He.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 h.debug("Retrieved conversation history",{sessionId:t,messageCount:n.length,turnCount:n.length/2}),n}catch(n){return h.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 De({code:He.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 De({code:He.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 h.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 h.debug("Listed conversation sessions",{userId:t,sessionCount:o.length}),o}catch(o){return h.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 i=await ze(this.conversationMemory.buildContextMessages(t),o,new Error("buildContextMessages operation timed out after 30s"));if(i.length===0)return h.debug("No messages found for session export",{sessionId:t}),null;const s=this.conversationMemory.getSession(t),a=await ze(s instanceof Promise?s:Promise.resolve(s),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:i};return r.includeMetadata&&(c.exportMetadata={exportedAt:l,exportFormat:r.format||"json"}),h.debug("Exported conversation session",{sessionId:t,messageCount:i.length}),c}catch(i){return h.error("Failed to export conversation session",{sessionId:t,error:i instanceof Error?i.message:String(i)}),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,i=6e4;try{const s=await ze(this.listSessions(t),o,new Error("listSessions operation timed out after 30s")),a=[];for(const l of s){const c=await ze(this.exportSession(l.id,r),i,new Error(`exportSession operation timed out after 60s for session ${l.id}`));c&&a.push(c)}return h.debug("Exported all conversation sessions",{userId:t,sessionCount:a.length}),a}catch(s){return h.error("Failed to export all conversation sessions",{userId:t,error:s instanceof Error?s.message:String(s)}),[]}}async storeToolExecutions(t,r,n,o,i){const s=n&&n.length>0||o&&o.length>0;if(!s){h.debug("Tool execution storage skipped",{hasToolData:s,toolCallsCount:n?.length||0,toolResultsCount:o?.length||0});return}const a=this.conversationMemory;if(!a?.storeToolExecution){h.debug("Tool execution storage not supported by this memory backend");return}try{await a.storeToolExecution(t,r,n,o,i)}catch(l){h.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 De({code:He.MISSING_CONFIGURATION,message:"Conversation memory is not enabled",category:"validation",severity:"high",retriable:!1});if(!t||typeof t!="string")throw new De({code:He.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 De({code:He.MISSING_CONFIGURATION,message:"Conversation memory is not enabled",category:"validation",severity:"high",retriable:!1});if(!t||typeof t!="string")throw new De({code:He.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 i=o.length-1;i>=0;i--)if(o[i].role==="assistant")return o[i]={...o[i],content:r(o[i].content)},await this.setSessionMessages(t,o,n),!0;return!1}async addExternalMCPServer(t,r){this.invalidateToolCache();try{re.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(re.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 JL({strategy:this.mcpEnhancementsConfig?.router?.strategy??"least-loaded",enableAffinity:this.mcpEnhancementsConfig?.router?.enableAffinity??!1});for(const i of o)this.mcpToolRouter.registerServer(i.id||t);h.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 re.error(`[NeuroLink] Failed to add external MCP server: ${t}`,{error:n.error,transport:r.transport,command:r.command,url:r.url?Yo(r.url):void 0});return n}catch(n){throw re.error(`[NeuroLink] Error adding external MCP server: ${t}`,n),n}}async removeExternalMCPServer(t){this.invalidateToolCache();try{re.info(`[NeuroLink] Removing external MCP server: ${t}`);const r=this.externalServerManager.getServerName(t),n=await this.externalServerManager.removeServer(t);return n.success?(re.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")?re.debug(`[NeuroLink] Remove skipped \u2014 external MCP server not registered: ${t}`):re.error(`[NeuroLink] Failed to remove external MCP server: ${t}`,{error:n.error}),n}catch(r){throw re.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(i=>i.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 i=r;try{i=this.resolveDirectMcpToolName(t,r),re.debug(`[NeuroLink] Executing external MCP tool: ${i} on ${t}`);const s=this.getToolAnnotationsForExecution(i),a=!!this.mcpToolResultCache&&!this._disableToolCacheForCurrentRequest&&!s?.destructiveHint,l={__serverId:t,__args:n,...this.toolExecutionContext?{__ctx:this.toolExecutionContext}:{}},c=this._generationTurnActive?this.toolCacheRepeatKey(i,l):void 0,u=c!==void 0&&this._toolCacheKeysServedThisRequest.has(c);if(c!==void 0&&this._toolCacheKeysServedThisRequest.add(c),a&&this.mcpToolResultCache&&!u){const f=this.mcpToolResultCache.getCachedResult(i,l);if(f!==void 0)return re.debug(`[NeuroLink] Tool result cache HIT: ${i} on ${t}`),f}const d=await this.externalServerManager.executeTool(t,i,n,o),p=d&&typeof d=="object"?d:void 0,m=!!(p&&"isError"in p&&p.isError===!0||p&&"success"in p&&p.success===!1);return a&&this.mcpToolResultCache&&!m&&d!==void 0&&this.mcpToolResultCache.cacheResult(i,l,d),re.debug(`[NeuroLink] External MCP tool ${m?"returned error":"executed successfully"}: ${i}`),d}catch(s){throw re.error(`[NeuroLink] External MCP tool execution failed: ${i}`,s),s}}resolveDirectMcpToolName(t,r){const n=this.getExternalMCPServer(t);if(!n||n.status!=="connected"||!n.client)return r;const o=this.getExternalMCPServerTools(t).map(s=>s.name);if(o.includes(r))return r;const i=oY(r,o);if(!i)throw new sY(r,t,P1t(r,o));return Be.mcp.startActiveSpan("neurolink.mcp.toolNameRepair",{attributes:{"mcp.server_id":t,"mcp.tool_name.requested":r,"mcp.tool_name.resolved":i.name,"mcp.tool_name.repair_strategy":i.strategy,...i.score!==void 0?{"mcp.tool_name.repair_score":i.score}:{}}},s=>s.end()),re.info(`[NeuroLink] Repaired external MCP tool name at direct execution boundary: "${r}" \u2192 "${i.name}" (${i.strategy}) on server '${t}'`),i.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(()=>(Vne(),rGt)),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{re.info("[NeuroLink] Shutting down all external MCP servers..."),this.unregisterAllExternalMCPToolsFromRegistry(),await this.externalServerManager.shutdown(),re.info("[NeuroLink] All external MCP servers shut down successfully")}catch(t){throw re.error("[NeuroLink] Error shutting down external MCP servers:",t),t}}async getElicitationManager(){return(await ze(Promise.resolve().then(()=>(cKt(),lKt)),1e4)).globalElicitationManager}async registerElicitationHandler(t){(await this.getElicitationManager()).registerHandler(t)}async getMultiServerManager(){return(await ze(Promise.resolve().then(()=>(Fre(),h5t)),1e4)).globalMultiServerManager}async getEnhancedToolDiscovery(){const t=await ze(Promise.resolve().then(()=>($re(),f5t)),1e4);return new t.EnhancedToolDiscovery(this.toolRegistry)}async getMCPRegistryClient(){return(await ze(Promise.resolve().then(()=>(mKt(),uKt)),1e4)).globalMCPRegistryClient}async exposeAgentAsTool(t,r){return(await ze(Promise.resolve().then(()=>(Oae(),Pae)),1e4)).exposeAgentAsTool(t,r)}async exposeWorkflowAsTool(t,r){return(await ze(Promise.resolve().then(()=>(Oae(),Pae)),1e4)).exposeWorkflowAsTool(t,r)}async getToolIntegrationManager(){return(await ze(Promise.resolve().then(()=>(TKt(),gKt)),1e4)).globalToolIntegrationManager}async convertToolsToMCPFormat(t,r={}){const n=await ze(Promise.resolve().then(()=>(LO(),VY)),1e4),o=t.map(i=>({...i,execute:i.execute??(async()=>({success:!1,error:"No execute function provided"}))}));return n.batchConvertToMCP(o,r)}async convertToolsFromMCPFormat(t,r={}){return(await ze(Promise.resolve().then(()=>(LO(),VY)),1e4)).batchConvertToNeuroLink(t,r)}async getToolAnnotations(t){const{inferAnnotations:r,mergeAnnotations:n,getAnnotationSummary:o}=await ze(Promise.resolve().then(()=>(Jk(),eRt)),1e4),i=this.toolRegistry.getToolInfo(t);if(!i)return null;const s=i.tool.annotations,a=r({name:i.tool.name,description:i.tool.description??""}),l=n(a,s);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 i=>{try{re.debug(`[NeuroLink] Executing external MCP tool via AI SDK: ${n.name}`,{params:i});const s=await this.externalServerManager.executeTool(n.serverId,n.name,i,{timeout:3e4});return re.debug(`[NeuroLink] External MCP tool execution result: ${n.name}`,{success:!!s,hasData:!!(s&&typeof s=="object"&&"content"in s)}),s}catch(s){throw re.error(`[NeuroLink] External MCP tool execution failed: ${n.name}`,s),s}}};r[n.name]=o,re.debug(`[NeuroLink] Converted external MCP tool to AI SDK format: ${n.name} from server ${n.serverId}`)}return re.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),re.debug(`[NeuroLink] Unregistered external MCP tool from main registry: ${n.name}`)}catch(r){re.error(`[NeuroLink] Failed to unregister external MCP tools from registry for server ${t}:`,r)}}unregisterExternalMCPToolFromRegistry(t){try{this.toolRegistry.removeTool(t),re.debug(`[NeuroLink] Unregistered external MCP tool from main registry: ${t}`)}catch(r){re.error(`[NeuroLink] Failed to unregister external MCP tool ${t} from registry:`,r)}}async lazyInitializeConversationMemory(t,r,n){try{const{initializeConversationMemory:o}=await Dln().then(()=>EKt),i=await o(this.conversationMemoryConfig);this.conversationMemory=i,this.conversationMemoryNeedsInit=!1}catch(o){throw h.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);re.debug(`[NeuroLink] Unregistered ${t.length} external MCP tools from main registry`)}catch(t){re.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(()=>(ES(),_S)),1e4,he.evaluationTimeout("evaluation module load",1e4));let o;typeof t=="string"?o=n(t):o=t;const i=new r(o);return await ze(i.initialize(),3e4,he.evaluationTimeout("pipeline initialization",3e4)),h.debug(`[NeuroLink] Created evaluation pipeline: ${o.name??"custom"}`),i}async decide(t){const r=t.provider??pE(this.resolveCredentials(t.credentials));if(!r)throw new Error(`No decision provider is configured. Set ${iPr()} (in the environment or in \`credentials\`), or pass \`provider\` explicitly.`);const n=Object.keys(t.questions).length;return mt({name:`gen_ai.${r}.decide`,tracer:Be.decision,attributes:{"gen_ai.system":r,"gen_ai.operation.name":"decide","ai.provider":r,"decision.question_count":n,"decision.images.count":t.images?.length??0}},async o=>{const{traceId:i,parentSpanId:s}=wf(),a=Date.now();let l=Me.createSpan("model.decision",`decision.${r}`,{"ai.provider":r,"ai.model":t.model??"","decision.question_count":n,"decision.images.count":t.images?.length??0},s,i);try{const c=await Yn.createProvider(r,t.model,!1,this,void 0,this.resolveCredentials(t.credentials));if(typeof c.decide!="function")throw new Error(`Provider "${r}" does not serve the decide inference type.`);const u=await c.decide({state:t.state,questions:t.questions,images:t.images,video:t.video,model:t.model,signal:t.signal,timeoutMs:t.timeoutMs}),d=Object.keys(u.answers).length,p=Ls(r,u.model,{input:u.usage.inputTokens,output:u.usage.outputTokens,total:u.usage.inputTokens+u.usage.outputTokens});o.setAttribute("gen_ai.response.model",u.model),o.setAttribute("gen_ai.usage.input_tokens",u.usage.inputTokens),o.setAttribute("gen_ai.usage.output_tokens",u.usage.outputTokens),o.setAttribute("decision.answer_count",d),o.setAttribute("decision.media.bytes",u.mediaBytes??0),o.setAttribute("ai.cost.total",p),u.upstreamMs!==void 0&&o.setAttribute("decision.upstream_ms",u.upstreamMs),u.requestId&&o.setAttribute("gen_ai.response.id",u.requestId),l.durationMs=Date.now()-a,l=Me.updateAttributes(l,{"ai.model":u.model,"ai.tokens.input":u.usage.inputTokens,"ai.tokens.output":u.usage.outputTokens,"ai.cost.input":p,"ai.cost.output":0,"ai.cost.total":p,"decision.answer_count":d,"decision.media.bytes":u.mediaBytes??0,"decision.latency_ms":u.latencyMs,...u.upstreamMs!==void 0?{"decision.upstream_ms":u.upstreamMs}:{}});const m=Me.endSpan(l,1);return this.metricsAggregator.recordSpan(m),it().recordSpan(m),u}catch(c){l.durationMs=Date.now()-a;const u=Me.endSpan(l,2,c instanceof Error?c.message:String(c));throw this.metricsAggregator.recordSpan(u),it().recordSpan(u),c}})}async tryDecide(t){try{const r=await this.decideInBatches(t);return h.shouldLog("debug")&&h.debug(`decide: ${Object.keys(r.answers).length} answers in ${r.latencyMs}ms`+(r.upstreamMs?` (upstream ${r.upstreamMs}ms)`:""),{provider:r.provider,model:r.model,requestId:r.requestId,usage:r.usage}),r}catch(r){return h.debug(`decide unavailable: ${r instanceof Error?r.message:String(r)} \u2014 falling back`),null}}async decideInBatches(t){const r=t.provider??pE(this.resolveCredentials(t.credentials)),n=r?sm.get(r.toLowerCase()):void 0,o=n?hr.get(n)?.decisionLimits?.maxQuestions:void 0,i=bYr(t,o);if(i.length===1)return this.decide(t);const s=[];let a;for(let u=0;u<i.length;u+=Ire){const d=await Promise.allSettled(i.slice(u,u+Ire).map(p=>this.decide(p)));for(const p of d)p.status==="fulfilled"?s.push(p.value):a??=p.reason}const[l,...c]=s;if(l===void 0)throw a instanceof Error?a:new Error(String(a));return c.length+1<i.length&&h.debug(`decide: ${i.length-s.length} of ${i.length} batches failed; using the answers of the rest`),_Yr([l,...c])}async evaluate(t,r){const{EvaluationPipeline:n,getPreset:o}=await ze(Promise.resolve().then(()=>(ES(),_S)),1e4,he.evaluationTimeout("evaluation module load",1e4));let i;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?i={...o(r.pipeline)}:r?.scorers&&r.scorers.length>0?i={name:"SDK Evaluation",description:"Evaluation from NeuroLink SDK",scorers:r.scorers.map(c=>({id:c})),executionMode:r.executionMode??"parallel",passThreshold:r.passThreshold??.7}:i=o("quality"),r?.passThreshold!==void 0&&(i.passThreshold=r.passThreshold),r?.executionMode!==void 0&&(i.executionMode=r.executionMode);const s=new n(i);await ze(s.initialize(),3e4,he.evaluationTimeout("pipeline initialization",3e4));const a=r?.timeoutMs??6e4,l=await ze(s.execute(t,{correlationId:r?.correlationId}),a,he.evaluationTimeout("pipeline execution",a));return h.debug("[NeuroLink] Evaluation completed",{pipeline:i.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(()=>(Sj(),Ej)),1e4,he.evaluationTimeout("scorer module load",1e4));await ze(o.registerBuiltInScorers(),3e4,he.evaluationTimeout("scorer bootstrap",3e4));const i=await ze(o.getScorer(t,n),3e4,he.evaluationTimeout(`scorer load: ${t}`,3e4));if(!i)throw he.scorerNotFound(t);const s=i.validateInput(r);if(!s.valid)throw he.evaluationValidationFailed(t,s.errors);const a=await ze(i.score(r),6e4,he.evaluationTimeout("scorer execution",6e4));return h.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(()=>(Sj(),Ej)),1e4,he.evaluationTimeout("scorer module load",1e4));await ze(r.registerBuiltInScorers(),3e4,he.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(()=>(ES(),_S)),1e4,he.evaluationTimeout("evaluation module load",1e4));return t()}async getEvaluationPreset(t){const{getPreset:r}=await ze(Promise.resolve().then(()=>(ES(),_S)),1e4,he.evaluationTimeout("evaluation module load",1e4));return r(t)}async createAgent(t){const{Agent:r}=await Promise.resolve().then(()=>(Uae(),SKt));return h.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(()=>(xKt(),kKt));return h.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??{},i={...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}},s=this.workerToolsConfig(o.tools),a=new _6(s?{...i,tools:s}:i);if(t?.shareToolRegistry!==!1)for(const l of this.uncacheableTools)a.uncacheableTools.add(l);if(h.setEventEmitter(n),t?.onLog){const l=t.onLog,c=f=>{try{const g=f??{};l({tag:r,level:String(g.level??"info"),message:String(g.message??""),timestamp:typeof g.timestamp=="number"?g.timestamp:Date.now(),data:g.data})}catch{}},u={emit:(f,...g)=>(f==="log-event"&&c(g[0]),!0)},d=a.logInstanceId;h.addScopedEventEmitter(d,u);const p=()=>{h.removeScopedEventEmitter(d,u),this.ownedWorkerLogBridgeDetachers.delete(p)};this.ownedWorkerLogBridgeDetachers.add(p);const m=a.dispose.bind(a);a.dispose=async()=>{p(),await m()}}return h.debug("[NeuroLink] Created worker instance",{tag:r,sharedToolRegistry:t?.shareToolRegistry!==!1}),a}async runIsolatedAgent(t,r,n){const{runIsolatedAgent:o}=await Promise.resolve().then(()=>(jA(),t3));return o(this,t,r,n)}async continueAgent(t,r){const{continueIsolatedAgent:n}=await Promise.resolve().then(()=>(jA(),t3));return n(this,t,r)}async stopAgent(t){const{stopIsolatedAgent:r}=await Promise.resolve().then(()=>(jA(),t3));return r(this,t)}async registerAgentTool(t,r){const{registerAgentTool:n}=await Promise.resolve().then(()=>(WA(),i3)),o=n(this,t,r);return this.hasAgentTools=!0,o}registerTaskTools(){if(this.hasTaskChecklistTools)return;const t=Tnn(this);for(const[r,n]of Object.entries(t))this.registerTool(r,n,{cacheable:!1});this.hasTaskChecklistTools=!0,h.info(`[NeuroLink] Registered ${Object.keys(t).length} task checklist tools`)}getTaskState(t){return gnn(t??pi(this))}clearTaskState(t){return ynn(t??pi(this))}registerDelegationTools(t){if(Unn(this,t),this.hasBackgroundDelegationTools)return;const r=Jnn(this);for(const[n,o]of Object.entries(r))this.registerTool(n,o,{cacheable:!1});this.hasBackgroundDelegationTools=!0,h.info(`[NeuroLink] Registered ${Object.keys(r).length} background delegation tools`)}async spawnDelegate(t){return t7t(this,t)}async collectDelegates(t){return n7t(this,t)}async cancelDelegates(t){return Fie(this,t)}getArtifactStore(){return this.mcpArtifactStore||(this.mcpArtifactStore=this.createConfiguredArtifactStore()),this.registerMemoryRetrievalTools(),this.mcpArtifactStore}setArtifactStore(t){const r=this.mcpArtifactStore;r!==t&&(r&&(h.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=>{h.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=W8t(this.artifactsConfig,this.conversationMemoryConfig?.conversationMemory?.redisConfig);return this.ownsArtifactStore=!t,h.debug("[NeuroLink] Artifact store initialized",{backend:t?"custom":_oe(this.artifactsConfig)}),r}installOutputNormalizer(t){this.mcpOutputNormalizerConfig&&(this.externalServerManager.setOutputNormalizer(new PGt(this.mcpOutputNormalizerConfig,t)),h.debug("[NeuroLink] MCP output normalizer initialized",{...this.mcpOutputNormalizerConfig,hasArtifactStore:t!==void 0}))}async bankArtifact(t,r){return urn(this,t,r)}async readArtifact(t,r){return drn(this,t,r)}registerBackgroundCommandTools(t){if(c7t(this,t),this.hasBackgroundCommandTools)return;const r=oon(this);for(const[n,o]of Object.entries(r))this.registerTool(n,o,{cacheable:!1});this.hasBackgroundCommandTools=!0,h.info(`[NeuroLink] Registered ${Object.keys(r).length} background command tools`)}setBackgroundCommandPolicy(t){c7t(this,t)}async startBackgroundCommand(t,r){return y7t(this,t,r)}getBackgroundCommandStatus(t){return v7t(this,t)}async awaitBackgroundCommand(t,r){return Xie(this,t,r)}async killBackgroundCommand(t,r){return w7t(this,t,r)}async readBackgroundCommandOutput(t,r){return h3(this,t,r)}registerGitTools(t){if(ion(this,t),this.hasGitTools)return;const r=pon(this);for(const[n,o]of Object.entries(r))this.registerTool(n,o,{cacheable:!1});this.hasGitTools=!0,h.info(`[NeuroLink] Registered ${Object.keys(r).length} read-only git tools`)}async runGitCommand(t,r){return M7t(this,t,r)}async executeNetwork(t,r,n){return h.debug("[NeuroLink] Executing agent network",{networkId:t.id,networkName:t.name,hasContext:!!r.context}),t.execute(r,n)}async*streamNetwork(t,r,n){h.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(()=>(RKt(),IKt));return h.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(()=>(MKt(),PKt));return h.debug("[NeuroLink] Creating agent coordinator",{strategy:t?.strategy,maxConcurrency:t?.maxConcurrency}),new r(t)}async createMessageBus(t){const{MessageBus:r}=await Promise.resolve().then(()=>(DKt(),OKt));return h.debug("[NeuroLink] Creating message bus",{maxHistorySize:t?.maxHistorySize}),new r(t)}async dispose(){h.debug("[NeuroLink] Starting disposal of resources..."),this.lastCompactionMessageCount.clear();const t=[];try{try{await T7t(this),await Fie(this)}catch(r){const n=r instanceof Error?r:new Error(`Background work cleanup error: ${String(r)}`);t.push(n),h.warn("[NeuroLink] Error stopping background work:",r)}try{h.debug("[NeuroLink] Flushing and shutting down OpenTelemetry..."),await aO(),await lO(),h.debug("[NeuroLink] OpenTelemetry shutdown successfully")}catch(r){const n=r instanceof Error?r:new Error(`OpenTelemetry shutdown error: ${String(r)}`);t.push(n),h.warn("[NeuroLink] Error shutting down OpenTelemetry:",r)}if(this.externalServerManager)try{h.debug("[NeuroLink] Shutting down external MCP servers..."),await this.externalServerManager.shutdown(),h.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),h.warn("[NeuroLink] Error shutting down external MCP servers:",r)}if(this.ownsArtifactStore&&this.mcpArtifactStore?.close)try{await this.mcpArtifactStore.close(),h.debug("[NeuroLink] Artifact store closed")}catch(r){const n=r instanceof Error?r:new Error(`Artifact store close error: ${String(r)}`);t.push(n),h.warn("[NeuroLink] Error closing artifact store:",r)}if(this.emitter)try{h.debug("[NeuroLink] Removing all event listeners..."),this.emitter.removeAllListeners(),h.clearEventEmitter(this.emitter),h.clearScopedEventEmitters(this.logInstanceId),h.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),h.warn("[NeuroLink] Error removing event listeners:",r)}if(this.ownedWorkerLogBridgeDetachers.size>0)try{const r=this.ownedWorkerLogBridgeDetachers.size;for(const n of[...this.ownedWorkerLogBridgeDetachers])n();h.debug(`[NeuroLink] Detached ${r} undisposed worker log bridge(s)`)}catch(r){const n=r instanceof Error?r:new Error(`Worker log bridge cleanup error: ${String(r)}`);t.push(n),h.warn("[NeuroLink] Error detaching worker log bridges:",r)}if(this.toolCircuitBreakers&&this.toolCircuitBreakers.size>0)try{h.debug(`[NeuroLink] Clearing ${this.toolCircuitBreakers.size} circuit breakers...`),this.toolCircuitBreakers.clear(),h.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),h.warn("[NeuroLink] Error clearing circuit breakers:",r)}try{h.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=[],h.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),h.warn("[NeuroLink] Error clearing caches:",r)}if(this._taskManager)try{h.debug("[NeuroLink] Shutting down TaskManager..."),await ze(this._taskManager.shutdown(),5e3,new Error("TaskManager shutdown timed out"))}catch(r){h.warn("[NeuroLink] TaskManager shutdown error:",r)}finally{this._taskManager=void 0}try{h.debug("[NeuroLink] Resetting initialization state..."),this.mcpInitialized=!1,this.mcpInitPromise=null,this.conversationMemoryNeedsInit=!1,this.credentials=void 0,h.debug("[NeuroLink] Initialization state reset successfully")}catch(r){const n=r instanceof Error?r:new Error(`State reset error: ${String(r)}`);t.push(n),h.warn("[NeuroLink] Error resetting state:",r)}t.length===0?h.debug("[NeuroLink] \u2705 Resource disposal completed successfully"):h.warn(`[NeuroLink] \u26A0\uFE0F Resource disposal completed with ${t.length} errors`,{errors:t.map(r=>r.message)})}catch(r){throw h.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 Rw({...r,summarizationProvider:r?.summarizationProvider??this.conversationMemoryConfig?.conversationMemory?.summarizationProvider,summarizationModel:r?.summarizationModel??this.conversationMemoryConfig?.conversationMemory?.summarizationModel},this.contextCompactorDeps()),i=aa({provider:r?.provider||"openai",conversationMessages:n}),s=Math.floor(i.availableInputTokens*.6),a=await o.compact(n,s,this.conversationMemoryConfig?.conversationMemory);return a.compacted&&Cw(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 i=aa({provider:r||"openai",model:n,conversationMessages:o});return{estimatedInputTokens:i.estimatedInputTokens,availableInputTokens:i.availableInputTokens,usageRatio:i.usageRatio,shouldCompact:i.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:i}=await Promise.resolve().then(()=>(rF(),NKt));r=await i.createProvider(o.type,o.config),n=o.type}this.authProvider=r,h.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(()=>(CA(),DL));r.set(t),h.debug("Auth context set",{userId:t.user.id,provider:t.provider,sessionId:t.session?.id})}async getAuthContext(){const{getAuthContext:t}=await Promise.resolve().then(()=>(CA(),DL));return t()}async clearAuthContext(){const{globalAuthContext:t}=await Promise.resolve().then(()=>(CA(),DL)),r=t.get()?.user.id;t.clear(),r&&h.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(i=>typeof t[i]=="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(h.debug("[NeuroLink] Resolving dynamic arguments"),await Promise.all(r.map(async i=>{if(typeof t[i]=="function"){const s=await Aoe(t[i],o);t[i]=s.value,h.debug(`[NeuroLink] Resolved dynamic ${i}: ${s.resolutionType}`)}})),typeof t.tools=="function"){const i=await Aoe(t.tools,o);if(!Array.isArray(i.value))throw new TypeError(`Dynamic tools resolver must return string[] (tool names), got ${typeof i.value=="object"?"object":typeof i.value}`);t.enabledToolNames=i.value,delete t.tools}}},Jae=new AT,UKt=Jae}});function BKt(e,t,r,n){const o=typeof e=="object"&&e!==null?e.data:void 0;if(!Array.isArray(o)||o.length===0)throw n(`${r} embeddings response missing data`);if(o.length!==t)throw n(`${r} embeddings response count mismatch: expected ${t}, got ${o.length}`);const i=o.findIndex(a=>!zKt(a));if(i!==-1)throw n(`${r} embeddings response entry ${i} is not an {index, embedding: number[]} object`);const s=o.slice().sort((a,l)=>a.index-l.index);for(let a=0;a<s.length;a++)if(s[a].index!==a)throw n(`${r} embeddings response has unexpected index ordering: position ${a} has index ${s[a].index}`);return s.map(a=>a.embedding)}var zKt,GKt=E({"src/lib/providers/embeddingResponseParsing.ts"(){"use strict";zKt=e=>{if(typeof e!="object"||e===null)return!1;const{embedding:t,index:r}=e;return Number.isInteger(r)&&Array.isArray(t)&&t.every(n=>typeof n=="number"&&Number.isFinite(n))}}}),qKt={};Z(qKt,{VoyageProvider:()=>HKt});var VKt,Xae,jKt,oF,HKt,qln=E({async"src/lib/providers/voyage.ts"(){"use strict";pl(),await tu(),GKt(),Ln(),pt(),et(),z(),Go(),VKt="https://api.voyageai.com/v1",Xae=6e4,jKt=()=>_a(H4r()),oF=()=>Fi("VOYAGE_MODEL","voyage-3.5"),HKt=class extends Ma{apiKey;baseURL;proxyFetch;constructor(e,t,r,n){const o=ch(t)?t:void 0;super(e,"voyage",o);const i=n?.apiKey?.trim();this.apiKey=i&&i.length>0?i:jKt(),this.baseURL=n?.baseURL??process.env.VOYAGE_BASE_URL??VKt,this.proxyFetch=Ot(),h.debug("Voyage Provider initialized (embeddings only)",{modelName:this.modelName,baseURL:this.baseURL})}getProviderName(){return this.providerName}getDefaultModel(){return oF()}supportsTools(){return!1}getDefaultEmbeddingModel(){return oF()}getAISDKModel(){throw new ot("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 ot("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 Wr("Invalid Voyage AI API key. Get one at https://dash.voyageai.com/api-keys","voyage"):t.includes("429")||t.toLowerCase().includes("rate limit")?new Qi("Voyage AI rate limit exceeded. Back off and retry.","voyage"):t.includes("404")||t.toLowerCase().includes("model_not_found")?new Jo(`Voyage AI model '${this.modelName}' not found. Browse https://docs.voyageai.com/docs/embeddings`,"voyage"):new ot(`Voyage AI error: ${t}`,"voyage")}async embed(e,t){if(typeof e!="string"&&e.image)throw new ot(`${this.providerName} does not support image embeddings; provide text input`,this.providerName);const r=typeof e=="string"?e:e.text??"",n=await this.callEmbeddings([r],t);if(!n[0])throw new ot("Voyage AI returned no embedding for the provided text","voyage");return n[0]}async embedMany(e,t){if(e.length===0)return[];const r=128,n=[];for(let o=0;o<e.length;o+=r){const i=e.slice(o,o+r),s=await this.callEmbeddings(i,t);n.push(...s)}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})}),Xae,new ot(`Voyage embeddings request timed out after ${Xae/1e3}s`,"voyage"))}catch(i){throw i instanceof ot?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();return BKt(o,e.length,"Voyage",i=>new ot(i,"voyage"))}async validateConfiguration(){return typeof this.apiKey=="string"&&this.apiKey.trim().length>0}getConfiguration(){return{provider:this.providerName,model:this.modelName,defaultModel:oF(),baseURL:this.baseURL}}}}}),WKt={};Z(WKt,{JinaProvider:()=>XKt});var KKt,gC,JKt,iF,XKt,Vln=E({async"src/lib/providers/jina.ts"(){"use strict";pl(),await tu(),GKt(),Ln(),pt(),z(),Go(),KKt="https://api.jina.ai/v1",gC=6e4,JKt=()=>_a(W4r()),iF=()=>Fi("JINA_MODEL","jina-embeddings-v3"),XKt=class extends Ma{apiKey;baseURL;proxyFetch;constructor(e,t,r,n){const o=ch(t)?t:void 0;super(e,"jina",o);const i=n?.apiKey?.trim();this.apiKey=i&&i.length>0?i:JKt(),this.baseURL=n?.baseURL??process.env.JINA_BASE_URL??KKt,this.proxyFetch=Ot(),h.debug("Jina Provider initialized (embeddings + reranking)",{modelName:this.modelName,baseURL:this.baseURL})}getProviderName(){return this.providerName}getDefaultModel(){return iF()}supportsTools(){return!1}getDefaultEmbeddingModel(){return iF()}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 Wr("Invalid Jina AI API key. Get one at https://jina.ai/?sui=apikey","jina"):t.includes("429")||t.toLowerCase().includes("rate limit")?new Qi("Jina AI rate limit exceeded. Back off and retry.","jina"):t.includes("404")||t.toLowerCase().includes("model_not_found")?new Jo(`Jina AI model '${this.modelName}' not found. See https://jina.ai/embeddings/`,"jina"):new ot(`Jina AI error: ${t}`,"jina")}async embed(e,t){if(typeof e!="string"&&e.image)throw new ot(`${this.providerName} does not support image embeddings; provide text input`,this.providerName);const r=typeof e=="string"?e:e.text??"",n=await this.callEmbeddings([r],t);if(!n[0])throw new Error("Jina AI returned no embedding for the provided text");return n[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,i=o?.apiKey?.trim()||this.apiKey,s=o?.baseURL||this.baseURL,a=new AbortController,l=setTimeout(()=>a.abort(),gC);let c;try{c=await this.proxyFetch(`${s}/rerank`,{method:"POST",headers:{Authorization:`Bearer ${i}`,"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 ${gC/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,i=r?.baseURL||this.baseURL,s=new AbortController,a=setTimeout(()=>s.abort(),gC);let l;try{l=await this.proxyFetch(`${i}/embeddings`,{method:"POST",headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json"},body:JSON.stringify({input:e,model:n}),signal:s.signal})}catch(u){throw u instanceof Error&&u.name==="AbortError"?this.formatProviderError(new Error(`Jina embeddings request timed out after ${gC/1e3}s`)):this.formatProviderError(u)}finally{clearTimeout(a)}if(!l.ok){const u=await l.text();throw this.formatProviderError(new Error(`Jina embeddings failed: ${l.status} \u2014 ${u}`))}const c=await l.json();return BKt(c,e.length,"Jina",u=>new Error(u))}async validateConfiguration(){return typeof this.apiKey=="string"&&this.apiKey.trim().length>0}getConfiguration(){return{provider:this.providerName,model:this.modelName,defaultModel:iF(),baseURL:this.baseURL}}}}}),YKt={};Z(YKt,{StabilityProvider:()=>Qae,default:()=>eJt});var ZKt,Yae,QKt,Zae,Qae,eJt,jln=E({async"src/lib/providers/stability.ts"(){"use strict";pl(),await tu(),Ln(),pt(),z(),Go(),ZKt="https://api.stability.ai",Yae=12e4,QKt=()=>(process.env.STABILITY_API_KEY??process.env.STABILITY_AI_API_KEY??"").trim()||void 0,Zae=()=>Fi("STABILITY_MODEL","stable-image-ultra"),Qae=class extends Ma{apiKey;baseURL;proxyFetch;constructor(e,t,r,n){const o=ch(t)?t:void 0;super(e,"stability",o);const i=n?.apiKey?.trim();this.apiKey=i&&i.length>0?i:QKt(),this.baseURL=n?.baseURL??process.env.STABILITY_BASE_URL??ZKt,this.proxyFetch=Ot(),h.debug("Stability AI Provider initialized (image-gen only)",{modelName:this.modelName,baseURL:this.baseURL})}getProviderName(){return this.providerName}getDefaultModel(){return Zae()}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 Wr("Invalid Stability AI API key. Get one at https://platform.stability.ai/account/keys","stability"):t.includes("429")||t.toLowerCase().includes("rate limit")?new Qi("Stability AI rate limit exceeded. Back off and retry.","stability"):t.includes("content_filtered")||t.includes("CONTENT_FILTERED")?new ot("Stability AI declined the request due to content policy. Adjust the prompt and retry.","stability"):t.includes("404")?new Jo(`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 ot(`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,i=r?.baseURL||this.baseURL,s=e.prompt??e.input?.text??"";if(!s.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",s),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(),Yae);let p;try{p=await this.proxyFetch(`${i}/v2beta/stable-image/generate/${a}`,{method:"POST",headers:{Authorization:`Bearer ${o}`,Accept:"application/json"},body:c,signal:u.signal})}catch(g){throw g instanceof Error&&g.name==="AbortError"?this.formatProviderError(new Error(`Stability image-gen request timed out after ${Yae/1e3}s`)):this.formatProviderError(g)}finally{clearTimeout(d)}if(!p.ok){const g=await p.text();throw this.formatProviderError(new Error(`Stability image-gen failed: ${p.status} \u2014 ${g}`))}const m=await p.json();if(!m.image)throw new Error(`Stability AI returned no image (finish_reason: ${m.finish_reason??"unknown"})`);const f=Date.now()-t;return h.info(`[StabilityProvider] Generated image (${m.image.length} base64 chars) in ${f}ms \u2014 model ${this.modelName}`),{content:s,provider:this.providerName,model:this.modelName,usage:{input:0,output:1e3,total:1e3},imageOutput:{base64:m.image}}}async validateConfiguration(){return this.apiKey!==void 0&&this.apiKey.trim().length>0}getConfiguration(){return{provider:this.providerName,model:this.modelName,defaultModel:Zae(),baseURL:this.baseURL}}},eJt=Qae}}),tJt={};Z(tJt,{IdeogramProvider:()=>rle,default:()=>oJt});var rJt,ele,nJt,tle,rle,oJt,Hln=E({async"src/lib/providers/ideogram.ts"(){"use strict";pl(),await tu(),Ln(),pt(),z(),Go(),Oa(),Fm(),rJt="https://api.ideogram.ai",ele=12e4,nJt=()=>_a(K4r()),tle=()=>Fi("IDEOGRAM_MODEL","V_3"),rle=class extends Ma{apiKey;baseURL;proxyFetch;constructor(e,t,r,n){const o=ch(t)?t:void 0;super(e,"ideogram",o);const i=n?.apiKey?.trim();this.apiKey=i&&i.length>0?i:nJt(),this.baseURL=n?.baseURL??process.env.IDEOGRAM_BASE_URL??rJt,this.proxyFetch=Ot(),h.debug("Ideogram Provider initialized (image-gen only)",{modelName:this.modelName,baseURL:this.baseURL})}getProviderName(){return this.providerName}getDefaultModel(){return tle()}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 Wr("Invalid Ideogram API key. Get one at https://developer.ideogram.ai/","ideogram"):t.includes("429")||t.toLowerCase().includes("rate limit")?new Qi("Ideogram rate limit exceeded. Back off and retry.","ideogram"):t.includes("safety")||t.includes("is_image_safe")?new ot("Ideogram declined the request due to safety filters. Adjust the prompt and retry.","ideogram"):new ot(`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,i=e.prompt??e.input?.text??"";if(!i.trim())throw new Error("Ideogram image generation requires a prompt (input.text or prompt)");const s=e,a={prompt:i,model:this.modelName,magic_prompt:s.magicPrompt??"AUTO"};s.aspectRatio&&(a.aspect_ratio=s.aspectRatio),s.negativePrompt&&(a.negative_prompt=s.negativePrompt),s.seed!==void 0&&(a.seed=s.seed),s.style&&(a.style_type=s.style);const l=new AbortController,c=setTimeout(()=>l.abort(),ele);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(y){throw y instanceof Error&&y.name==="AbortError"?this.formatProviderError(new Error(`Ideogram image-gen request timed out after ${ele/1e3}s`)):this.formatProviderError(y)}finally{clearTimeout(c)}if(!u.ok){const y=await u.text();throw this.formatProviderError(new Error(`Ideogram image-gen failed: ${u.status} \u2014 ${y}`))}const p=(await u.json()).data?.[0]?.url;if(!p)throw new Error("Ideogram returned no image URL");const m=await Lm(p,{label:"Ideogram image",maxBytes:Nm,timeoutMs:6e4}),f=m.toString("base64"),g=Date.now()-t;return h.info(`[IdeogramProvider] Generated image (${m.length} bytes) in ${g}ms \u2014 model ${this.modelName}`),{content:i,provider:this.providerName,model:this.modelName,usage:{input:0,output:1e3,total:1e3},imageOutput:{base64:f}}}async validateConfiguration(){return typeof this.apiKey=="string"&&this.apiKey.trim().length>0}getConfiguration(){return{provider:this.providerName,model:this.modelName,defaultModel:tle(),baseURL:this.baseURL}}},oJt=rle}}),iJt={};Z(iJt,{ReplicateProvider:()=>sJt});function Wln(e){const t=e,r=t.prompt??t.input?.text??"",n=t.systemPrompt;return n?`${n}
|
|
2150
|
+
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,h.info("[RAG] Tool injected into stream()",{toolName:l.toolName,filesLoaded:l.filesLoaded,chunksIndexed:l.chunksIndexed})}catch(a){h.warn("[RAG] Failed to prepare RAG tool, continuing without RAG",{error:a instanceof Error?a.message:String(a)})}const i=$in(t),s=Uin(t);if(t.input?.text){const{toolResults:a,enhancedPrompt:l}=await this.detectAndExecuteTools(t.input.text,void 0);l!==t.input.text&&(s.input.text=l)}return{enhancedOptions:s,factoryResult:i}}async autoDisableOllamaStreamTools(t){if((t.provider==="ollama"||t.provider?.toLowerCase().includes("ollama"))&&!t.disableTools){const{ModelConfigurationManager:r}=await Promise.resolve().then(()=>(Mf(),_Je)),i=r.getInstance().getProviderConfiguration("ollama")?.modelBehavior?.toolCapableModels||[],s=t.model;i.length>0&&s&&(i.some(l=>s.toLowerCase().includes(l.toLowerCase()))||(t.disableTools=!0,h.debug("Auto-disabled tools for Ollama model that doesn't support them (stream)",{model:t.model,toolCapableModels:i.slice(0,3)})))}}setupStreamEventListeners(){const t=[];let r=0;const n=(d,p)=>{t.push({type:d,seq:r++,timestamp:Date.now(),...p&&typeof p=="object"?p:{data:p}})},o=(...d)=>{const p=d[0];n("response:chunk",{content:p})},i=(...d)=>{const p=d[0];n("tool:start",{...p,toolName:p.toolName??p.tool})},s=(...d)=>{const p=d[0],m=p.toolName??p.tool,f=p.responseTime??p.duration,g=p.success??(p.error!==void 0?!1:void 0),y={...p,toolName:m,...f!==void 0?{responseTime:f}:{},...g!==void 0?{success:g}:{},...p.error!==void 0?{error:p.error}:{}};n("tool:end",y),y.result&&y.result.uiComponent===!0&&n("ui-component",{toolName:m,componentData:y.result,timestamp:Date.now(),...g!==void 0?{success:g}:{},...f!==void 0?{responseTime:f}:{}})},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",i),this.emitter.on("tool:end",s),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",i),this.emitter.off("tool:end",s),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,i,s){t.fallbackAttempted=!0;const a="Stream completed with 0 chunks (possible guardrails block)";t.error=a;try{const f=this._metricsTraceContext;let g=Me.createGenerationSpan({provider:i,model:o.model||"unknown",name:`gen_ai.${i}.stream.failed`,traceId:f?.traceId,parentSpanId:f?.parentSpanId});g=Me.endSpan(g,2),g.statusMessage=a,g.durationMs=0,this.metricsAggregator.recordSpan(g),it().recordSpan(g)}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,p=E3.getFallbackRoute(n||o.input.text||"",{provider:i,model:o.model||"gpt-4o",reasoning:"primary failed",confidence:.5},{fallbackStrategy:"auto"}),m={...p,provider:l??u??p.provider,model:c??d??p.model};h.warn("Retrying with fallback provider",{originalProvider:i,fallbackProvider:m.provider,fallbackModel:m.model,fallbackSource:l||c?"options":u||d?"env":"model_config",reason:a});try{const f=await Yn.createProvider(m.provider,m.model,!0,void 0,void 0,this.resolveCredentials(o.credentials));f.setupToolExecutor({customTools:this.getCustomTools(),executeTool:(x,P)=>this.executeTool(x,P,{disableToolCache:o.disableToolCache})},"NeuroLink.fallbackStream");const g=o.conversationMessages!==void 0?o.conversationMessages:await Wm(this.conversationMemory,{prompt:o.input.text,context:o.context});f.setFileToolRootPolicy?.(this.fileToolRootsFor(o));const y=await f.stream({...this.deferProviderStreamTTS(o),model:m.model,conversationMessages:g}),v=y.toolCalls??[],T=y.toolResults??[];(v.length>0||T.length>0)&&(r.toolCalls=v,r.toolResults=T,r.finishReason=y.finishReason??r.finishReason);let b=0,S=0;for await(const x of y.stream){b++;const P=x!==null&&typeof x=="object"&&"metadata"in x&&x.metadata?.noOutput===!0,C=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");!P&&(C||R)&&S++,x&&"content"in x&&typeof x.content=="string"&&(s(x.content),this.emitter.emit("response:chunk",x.content)),yield x}const k=y.toolCalls??[],A=y.toolResults??[];if(S===0&&k.length===0&&A.length===0)throw new Error(`Fallback provider ${m.provider} also returned 0 real output chunks (chunkCount=${b}, sentinel-only or empty)`);r.toolCalls=k,r.toolResults=A,r.finishReason=y.finishReason??r.finishReason,t.fallbackProvider=m.provider,t.fallbackModel=m.model,t.guardrailsBlocked=!0}catch(f){const g=f instanceof Error?f.message:String(f);throw t.error=`${a}; Fallback failed: ${g}`,h.error("Fallback provider failed",{fallbackProvider:m.provider,error:g}),f}}async storeStreamConversationMemory(t){const{enhancedOptions:r,providerName:n,originalPrompt:o,accumulatedContent:i,startTime:s,eventSequence:a}=t;h.shouldLog("debug")&&h.debug("[NeuroLink.stream] Preparing to store conversation turn in memory",{options:C4(I4(r)),sessionId:r.context?.sessionId});const l=a.some(c=>c.type==="tool:start"||c.type==="tool:end");if(!i.trim()&&!l){h.warn("[NeuroLink.stream] Skipping conversation turn storage \u2014 no text content or tool activity",{sessionId:r.context?.sessionId});return}if(h.shouldLog("debug")&&h.debug("[NeuroLink.stream] Storing conversation turn in memory",{options:C4(I4(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 p=Date.now();try{const m=this.drainPendingSkillMessages(c);await this.conversationMemory.storeConversationTurn({sessionId:c,userId:u,userMessage:o??"",aiResponse:i,startTimeStamp:new Date(s),providerDetails:d,enableSummarization:r.enableSummarization,events:a.length>0?a:void 0,requestId:r.context?.requestId,...m.length>0?{skillMessages:m}:{}}),this.recordMemorySpan("memory.store",{"memory.operation":"store","memory.path":"stream"},Date.now()-p,1),h.debug("[NeuroLink.stream] Stored conversation turn with events",{sessionId:c,eventCount:a.length,eventTypes:[...new Set(a.map(f=>f.type))]})}catch(m){this.recordMemorySpan("memory.store",{"memory.operation":"store","memory.path":"stream"},Date.now()-p,2,m instanceof Error?m.message:String(m)),h.warn("Failed to store stream conversation turn",{error:m instanceof Error?m.message:String(m)})}}this.shouldWriteMemory(r.memory,r.context?.userId,i)&&this.storeMemoryInBackground(o??"",i.trim(),r.context?.userId,r.memory?.additionalUsers,r.context)}async validateStreamInput(t){const r=process.hrtime.bigint();h.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"),i=!!(t?.stt?.enabled&&t?.stt?.audio);if(!n&&!o&&!i)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 oT(t.provider),n=await Yn.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:(f,g)=>this.executeTool(f,g,{disableToolCache:t.disableToolCache})},"NeuroLink.createMCPStream");let o=await this.getAllAvailableTools();o=this.applyToolInfoFiltering(o,t),Cr.getDescriptor(r)?.toolSupport==="none"&&(o=[]);const i=t.skipToolPromptInjection?t.systemPrompt||"":this.createToolAwareSystemPrompt(t.systemPrompt,o,n.supportsTools?.()??!0),s=t.conversationMessages!==void 0,a=s?t.conversationMessages:await Wm(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:i,conversationMessages:l,currentPrompt:t.input.text,toolDefinitions:o,compactionThreshold:t.compactionThreshold}),u=l?.length||0,d=this.getCompactionSessionId(t),p=u>0;if(!c.withinBudget&&!p){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 Na(`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&&(s||this.conversationMemory)&&u>(this.lastCompactionMessageCount.get(d)??0)){const g=await new Rw({provider:r,summarizationProvider:this.conversationMemoryConfig?.conversationMemory?.summarizationProvider,summarizationModel:this.conversationMemoryConfig?.conversationMemory?.summarizationModel},this.contextCompactorDeps()).compact(l,kN(c,t.compactionThreshold),this.conversationMemoryConfig?.conversationMemory,t.context?.requestId,{currentRequest:t.input.text});g.compacted&&(l=Cw(g.messages).messages,t.conversationMessages=l,this.lastCompactionMessageCount.set(d,l.length));const y=aa({provider:r,model:t.model,maxTokens:t.maxTokens,systemPrompt:i,conversationMessages:l,currentPrompt:t.input.text,toolDefinitions:o});if(!y.withinBudget){h.warn("[NeuroLink] Stream: post-compaction still over budget, emergency truncation",{estimatedTokens:y.estimatedInputTokens,availableTokens:y.availableInputTokens,overagePercent:Math.round((y.usageRatio-1)*100)});try{this.emitter.emit("compaction.insufficient",{stagesAttempted:g.stagesUsed,finalTokens:y.estimatedInputTokens,budget:y.availableInputTokens,provider:r,model:t.model,phase:"mid-compaction",willEmergencyTruncate:!0,timestamp:Date.now()})}catch{}l=Wte(l,y.availableInputTokens,y.breakdown,r),t.conversationMessages=l;const v=aa({provider:r,model:t.model,maxTokens:t.maxTokens,systemPrompt:i,conversationMessages:l,currentPrompt:t.input.text,toolDefinitions:o});if(!v.withinBudget){this.lastCompactionMessageCount.delete(d);try{this.emitter.emit("compaction.insufficient",{stagesAttempted:g.stagesUsed,finalTokens:v.estimatedInputTokens,budget:v.availableInputTokens,provider:r,model:t.model,phase:"post-emergency-truncation",timestamp:Date.now()})}catch{}throw new Na(`Stream context exceeds model budget after all compaction stages. Estimated: ${v.estimatedInputTokens} tokens, Budget: ${v.availableInputTokens} tokens.`,{estimatedTokens:v.estimatedInputTokens,availableTokens:v.availableInputTokens,stagesUsed:g.stagesUsed,breakdown:v.breakdown})}}}if(this.modelPool){const f=this.modelPool,g=f.maxAttempts,y=new Set;let v=null;for(let T=0;T<g;T++){if(t.abortSignal?.aborted)throw new DOMException("The operation was aborted","AbortError");const b=f.selectNext(y);if(!b)break;y.add(f.memberKey(b));const S=b.provider,k=b.model??void 0,A=b.region??void 0;h.debug(`[createMCPStream] ModelPool: attempting member ${S}`,{model:k,attempt:T});try{const x=await Yn.createProvider(S,k,!t.disableTools,this,A,this.resolveCredentials(t.credentials));x.setTraceContext(this._metricsTraceContext),x.setupToolExecutor({customTools:this.getCustomTools(),executeTool:(O,U)=>this.executeTool(O,U,{disableToolCache:t.disableToolCache})},"NeuroLink.createMCPStream"),x.setFileToolRootPolicy?.(this.fileToolRootsFor(t));const P=await x.stream({...this.deferProviderStreamTTS(t),provider:S,model:k,region:A,systemPrompt:i,conversationMessages:l});h.debug("[createMCPStream] ModelPool stream handle obtained",{provider:S});const C=b,R=(async function*(){try{yield*P.stream,f.recordSuccess(C)}catch(O){throw f.recordFailure(C,iT(O)),O}})();return vO(P,{...P,stream:R,provider:S,model:P.model||k,toolCalls:P.toolCalls??[],toolResults:P.toolResults??[]})}catch(x){if(pr(x))throw x;if(Kae(x)){const P=x instanceof Error?x.message:String(x);throw f.recordFailure(b,iT(x)),new Error(`[ModelPool] non-retryable: ${P}`,{cause:x})}f.recordFailure(b,iT(x)),v=x instanceof Error?x:new Error(String(x)),h.warn(`[createMCPStream] ModelPool: member ${S} failed`,{error:v.message})}}throw new Error(`[ModelPool] all stream members failed: ${v?.message??"no stream members available"}`)}n.setFileToolRootPolicy?.(this.fileToolRootsFor(t));const m=await n.stream({...this.deferProviderStreamTTS(t),systemPrompt:i,conversationMessages:l});return h.debug("[createMCPStream] Stream created successfully",{provider:r,systemPromptPassedLength:i.length}),vO(m,{...m,provider:r,model:m.model||t.model,toolCalls:m.toolCalls??[],toolResults:m.toolResults??[]})}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){const o=n.sourceResult,i={streamId:n.streamId,startTime:n.startTime,responseTime:n.responseTime,fallback:n.fallback||!1,guardrailsBlocked:n.guardrailsBlocked,error:n.error},s={...o??{},stream:r,provider:o?.provider??n.providerName,model:o?.model??n.options.model,usage:t.usage,finishReason:t.finishReason,analytics:t.analytics,evaluation:t.evaluation,events:n.events&&n.events.length>0?n.events:void 0,metadata:o?void 0:Object.assign({},i)},a=Object.getOwnPropertyDescriptor(t,"toolCalls");a&&Object.defineProperty(s,"toolCalls",a);const l=Object.getOwnPropertyDescriptor(t,"toolResults");l&&Object.defineProperty(s,"toolResults",l);const c=Object.getOwnPropertyDescriptor(t,"finishReason");if(c&&Object.defineProperty(s,"finishReason",c),!o)return s;const u=new Set(["finishReason","stopReason","rawFinishReason","toolCalls","toolResults"]);for(const d of Object.getOwnPropertyNames(o)){const p=Object.getOwnPropertyDescriptor(o,d);!u.has(d)&&p&&typeof p.get=="function"&&Object.defineProperty(s,d,p)}return Object.defineProperty(s,"metadata",{enumerable:!0,configurable:!0,get:()=>(o.metadata===void 0&&(o.metadata={}),Object.assign(o.metadata,i)),set:d=>{o.metadata=d}}),s}async handleStreamError(t,r,n,o,i,s){if(t instanceof Na)throw t;h.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 oT(r.provider),u=await Yn.createProvider(c,r.model,!0,void 0,void 0,this.resolveCredentials(r.credentials));u.setFileToolRootPolicy?.(this.fileToolRootsFor(r));const d=await u.stream({input:{text:r.input.text},model:r.model,temperature:r.temperature,maxTokens:r.maxTokens,conversationMessages:r.conversationMessages});let p="";return{stream:(async function*(f){try{for await(const g of d.stream)g&&"content"in g&&typeof g.content=="string"&&(p+=g.content,f.emitter.emit("response:chunk",g.content)),yield g}finally{if(p.trim()){h.info("[NeuroLink.handleStreamError] stream() - COMPLETE SUCCESS (fallback)",{provider:c,model:r.model,responseTimeMs:Date.now()-n,contentLength:p.length});try{const g=r.model||"unknown",y=Date.now()-n;f.emitter.emit("stream:complete",{content:p,provider:c,model:g,finishReason:"stop",metadata:{durationMs:y,chunkCount:0,totalLength:p.length,isFallback:!0,finishReason:"stop"}}),f.emitter.emit("generation:end",{provider:c,model:g,responseTime:y,timestamp:Date.now(),result:{content:p,usage:{input:0,output:0,total:0},model:g,provider:c,finishReason:"stop"},success:!0,pipelineAHandled:!0})}catch{}}if(f.conversationMemory&&i?.context?.sessionId&&p.trim()){const g=i?.context?.sessionId,y=i?.context?.userId;let v;r.model&&(v={provider:c,model:r.model});const T=Date.now();try{const b=g||r.context?.sessionId,S=f.drainPendingSkillMessages(b);await f.conversationMemory.storeConversationTurn({sessionId:b,userId:y||r.context?.userId,userMessage:a??"",aiResponse:p,startTimeStamp:new Date(n),providerDetails:v,enableSummarization:i?.enableSummarization,requestId:i?.context?.requestId||r.context?.requestId,...S.length>0?{skillMessages:S}:{}}),f.recordMemorySpan("memory.store",{"memory.operation":"store","memory.path":"fallback-stream"},Date.now()-T,1)}catch(b){f.recordMemorySpan("memory.store",{"memory.operation":"store","memory.path":"fallback-stream"},Date.now()-T,2,b instanceof Error?b.message:String(b)),h.warn("Failed to store fallback stream conversation turn",{error:b instanceof Error?b.message:String(b)})}}}})(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}fileToolRootsFor(t){return wV(t)??this.resolveFileToolRoots(t.toolRoots)}workerToolsConfig(t){const r=this.toolsConfig?.fileRoots;if(t?.fileRoots===void 0)return r===void 0?t:{...t,fileRoots:r};const n=_P({perCall:t.fileRoots,instance:r}).roots;return{...t,fileRoots:n?[...n]:[]}}resolveFileToolRoots(t){return _P({perCall:t,instance:this.toolsConfig?.fileRoots})}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(i){const s=i instanceof Error?i.message:String(i),a=s.toLowerCase();return i instanceof ry?{provider:r,status:"denied",detail:s}: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:s}: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:s}: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:s}:{provider:r,status:"unknown",detail:s}}}emitToolStart(t,r,n=Date.now()){const o=`${t}-${n}-${Math.random().toString(36).substr(2,9)}`,i={executionId:o,tool:t,startTime:n,metadata:{inputType:typeof r,hasInput:r!=null}};return this.activeToolExecutions.set(o,i),this.currentStreamToolExecutions.push(i),this.emitter.emit("tool:start",Bv(t,{input:r,timestamp:n,executionId:o})),h.debug(`tool:start emitted for ${t}`,{toolName:t,executionId:o,timestamp:n,inputProvided:r!==void 0}),o}emitToolEnd(t,r,n,o,i=Date.now(),s){const a=o||i-1e3,l=i-a,c=!n;let u;s?u=this.activeToolExecutions.get(s):u=Array.from(this.activeToolExecutions.values()).find(m=>m.tool===t&&!m.endTime);const d=s||u?.executionId||`${t}-${a}-fallback-${Math.random().toString(36).substr(2,9)}`;u&&(u.endTime=i,u.result=r,u.error=n,this.activeToolExecutions.delete(u.executionId));const p={tool:t,startTime:a,endTime:i,duration:l,success:c,result:r,error:n,executionId:d,metadata:{toolCategory:"custom"}};this.toolExecutionHistory.push(p),this.emitter.emit("tool:end",Bv(t,{result:r,error:n,success:c,responseTime:l,timestamp:i,duration:l,executionId:d})),h.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&&(BH(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 s=o.execute,a=n.timeout,l=t;o.execute=async(...c)=>{const u=AbortSignal.timeout(a),d=c[1],p=d?.abortSignal,m=p?AbortSignal.any([p,u]):u,f={...d,abortSignal:m};return Promise.race([s(c[0],f),new Promise((g,y)=>{m.addEventListener("abort",()=>{u.aborted?y(he.toolTimeout(l,a)):y(new DOMException("The operation was aborted","AbortError"))},{once:!0})})])}}const i=qtn(t,o,n?.timeout,n?.maxRetries,n?.totalTimeoutMs);this.toolRegistry.registerServer(i),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 h.error(`Failed to register tool ${t}:`,o),o}}setToolContext(t){this.toolExecutionContext={...t},h.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,h.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),h.info(`Unregistered custom tool: ${t}`)),n}useToolMiddleware(t){return this.mcpToolMiddlewares.push(t),h.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 Ya("Conversation memory is not initialized. Enable conversationMemory in NeuroLink options.","CONFIG_ERROR");if(!("updateAgenticLoopReport"in this.conversationMemory)||typeof this.conversationMemory.updateAgenticLoopReport!="function")throw new Ya("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(la({isCustomTool:!0})),r=new Map;for(const o of t){const i=o.inputSchema||o.parameters;h.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:!!i,effectiveSchemaType:typeof i,effectiveSchemaHasProperties:!!i?.properties,effectiveSchemaHasRequired:!!i?.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(s,a)=>{const l=this.toolExecutionContext||{},c=a&&er(a)?a:{},u={...l,...c,sessionId:c.sessionId||l.sessionId||`fallback-${Date.now()}`};return h.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,s,u)}})}this.cachedFileTools||(this.cachedFileTools=i5t(this.fileRegistry));const n=this.cachedFileTools;for(const[o,i]of Object.entries(n))if(!r.has(o)){const s=i,a=s.inputSchema??s.parameters;r.set(o,{name:o,description:i.description||`File tool: ${o}`,inputSchema:typeof a=="object"&&a!==null?a:{type:"object",properties:{}},execute:async l=>await i.execute(l,{toolCallId:`file-tool-${Date.now()}`,messages:[]})})}return r}async addInMemoryMCPServer(t,r){this.invalidateToolCache();try{re.debug(`[NeuroLink] Registering in-memory MCP server: ${t}`),r.tools||(r.tools=[]),await this.toolRegistry.registerServer(r),re.info(`[NeuroLink] Successfully registered in-memory server: ${t}`,{category:r.metadata?.category,provider:r.metadata?.provider,version:r.metadata?.version})}catch(n){throw re.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=>la({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 Be.mcp.startActiveSpan("neurolink.tool.execute",{attributes:{"tool.name":t,"tool.type":o.toolType,"tool.input_size":o.inputSize,"tool.input_preview":o.truncatedInput}},i=>this.executeToolWithSpan(t,r,n,o,i))}createToolExecutionContext(t,r,n){const o=this.externalServerManager.getAllTools().find(c=>c.name===t),i=o?"mcp":this.getCustomTools().has(t)?"custom":"external",s=r?My(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:i,inputSize:s.length,truncatedInput:s.length>2048?s.substring(0,2048):s,options:n,hitlState:{triggered:!1}}}async executeToolWithSpan(t,r,n,o,i){try{const s=await this.prepareToolExecutionState(t,r,n,o);return await this.runPreparedToolExecution(t,r,s,o,i)}catch(s){if(!(s instanceof De)){const a=s instanceof Error?s.message:String(s);i.recordException(s instanceof Error?s:new Error(a)),i.setStatus({code:Ue.ERROR,message:a})}throw s}finally{i.end()}}async prepareToolExecutionState(t,r,n,o){h.debug(`[${o.functionTag}] Tool execution requested:`,{toolName:t,params:er(r)?CXe(r):r,hasExternalManager:!!this.externalServerManager}),h.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",Bv(t,{timestamp:o.executionStartTime,input:r,executionId:o.executionId}));const i=this.toolRegistry.getToolInfo(t),s=n?.timeout??i?.tool?.timeoutMs??Pl.EXECUTION_BATCH_MS,a=n?.maxRetries??i?.tool?.maxRetries??fi.DEFAULT,l=n?.retryDelayMs||eo.BASE_MS,c={timeout:s,maxRetries:a,totalTimeout:n?.totalTimeoutMs??i?.tool?.totalTimeoutMs??s*(a+1)+l*a,retryDelayMs:l,authContext:n?.authContext,disableToolCache:n?.disableToolCache},{MemoryManager:u}=await Promise.resolve().then(()=>(iC(),lT)),d=u.getMemoryUsageMB(),m=`${o.externalTool?.serverId||i?.tool?.serverId||"unknown"}.${t}`;let f=this.toolCircuitBreakers.get(m);f||(f=new k4(SI.FAILURE_THRESHOLD,w5),this.toolCircuitBreakers.set(m,f));let g=this.toolExecutionMetrics.get(t);return g||(g={totalExecutions:0,successfulExecutions:0,failedExecutions:0,averageExecutionTime:0,lastExecutionTime:0,errorCategories:{}},this.toolExecutionMetrics.set(t,g)),g.totalExecutions++,{finalOptions:c,startMemory:d,circuitBreaker:f,breakerKey:m,metrics:g}}async runPreparedToolExecution(t,r,n,o,i){let s=0;try{re.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 p=await n.circuitBreaker.execute(async()=>Obe(async()=>{d++;const m=u-Date.now();if(m<=0)throw he.toolTimeout(t,l,void 0,{attempt:d,maxAttempts:a,attemptTimeoutMs:n.finalOptions.timeout,totalTimeoutMs:l,elapsedMs:Date.now()-c,exhausted:!0});const f=Math.min(n.finalOptions.timeout,m);return ze(this.executeToolInternal(t,r,n.finalOptions,o.hitlState),f,he.toolTimeout(t,f,void 0,{attempt:d,maxAttempts:a,attemptTimeoutMs:n.finalOptions.timeout,totalTimeoutMs:l,elapsedMs:Date.now()-c}))},{maxAttempts:a,delayMs:n.finalOptions.retryDelayMs,isRetriable:m=>Date.now()+n.finalOptions.retryDelayMs<u&&XG(m),onRetry:(m,f)=>{s=m,re.warn(`[${o.functionTag}] Retrying tool execution (attempt ${m})`,{toolName:t,error:f.message,attempt:m})}}));return i.setAttribute("tool.retry_count",s),await this.handleSuccessfulToolExecution(t,p,n,o,i)}catch(a){return i.setAttribute("tool.retry_count",s),this.handleFailedToolExecution(t,r,a,n,o,i)}}async handleSuccessfulToolExecution(t,r,n,o,i){const s=Date.now()-o.executionStartTime;n.metrics.successfulExecutions++,n.metrics.lastExecutionTime=s,n.metrics.averageExecutionTime=(n.metrics.averageExecutionTime*(n.metrics.successfulExecutions-1)+s)/n.metrics.successfulExecutions;const{MemoryManager:a}=await Promise.resolve().then(()=>(iC(),lT)),c=a.getMemoryUsageMB().heapUsed-n.startMemory.heapUsed;c>20&&re.warn(`Tool '${t}' used excessive memory: ${c}MB`,{toolName:t,memoryDelta:c,executionTime:s}),re.debug(`[${o.functionTag}] Tool executed successfully`,{toolName:t,executionTime:s,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,p=d?u?.content:void 0,m=d?p?.filter(f=>f.type==="text"&&f.text).map(f=>f.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{}re.debug(`[${o.functionTag}] Circuit breaker failure recorded for isError result`,{toolName:t,circuitBreakerState:n.circuitBreaker.getState(),circuitBreakerFailures:n.circuitBreaker.getFailureCount()});const f=$ln(m??"Unknown error"),g=`[TOOL_ERROR: ${t} failed (${f})] `;if(u&&Array.isArray(p)){const T=p.map(b=>({...b}));for(const b of T)if(b.type==="text"&&b.text){b.text=g+b.text;break}u.content=T}i.setAttribute("tool.error.message",(m??"Unknown error").substring(0,500)),i.setAttribute("tool.error.category",f),i.setStatus({code:Ue.ERROR,message:`MCP tool returned isError: ${(m??"Unknown error").substring(0,200)}`}),n.metrics.failedExecutions++;const y=n.metrics.successfulExecutions;n.metrics.successfulExecutions=Math.max(0,n.metrics.successfulExecutions-1),n.metrics.averageExecutionTime=y>1?(n.metrics.averageExecutionTime*y-s)/(y-1):0;const v=Uln(f);n.metrics.errorCategories[v]=(n.metrics.errorCategories[v]||0)+1}return this.emitToolEndEvent(t,o.executionStartTime,!d,r,d&&m?new Error(m):void 0,o.executionId),i.setAttribute("tool.result.status",d?"error":"success"),i.setAttribute("tool.duration_ms",s),r}async handleFailedToolExecution(t,r,n,o,i,s){o.metrics.failedExecutions++;const a=Date.now()-i.executionStartTime;if(n instanceof jp)return re.warn(`[${i.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,i.executionStartTime,!1,void 0,new Error(`Circuit breaker open for ${t} (state=${n.breakerState}, failures=${n.failureCount})`),i.executionId),s.setAttribute("tool.result.status","circuit_breaker_open"),s.setAttribute("tool.duration_ms",a),s.setAttribute("tool.circuit_breaker.state",n.breakerState),s.setAttribute("tool.circuit_breaker.retry_after_ms",n.retryAfterMs),s.setAttribute("tool.circuit_breaker.failure_count",n.failureCount),s.setStatus({code:Ue.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 De)l=n;else if(n instanceof Error)if(n.message.includes("timeout"))l=he.toolTimeout(t,o.finalOptions.timeout);else if(n.message.includes("not found")){const u=await this.getAllAvailableTools();l=he.toolNotFound(t,QBr(u.map(d=>({name:d.name}))))}else n.message.includes("validation")||n.message.includes("parameter")?l=he.invalidParameters(t,n,r):n.message.includes("network")||n.message.includes("connection")?l=he.networkError(t,n):l=he.toolExecutionFailed(t,n);else l=he.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,i.executionStartTime,!1,void 0,l,i.executionId),this.emitter.listenerCount("error")>0&&this.emitter.emit("error",l),l=new De({...l,context:{...l.context,executionTime:a,params:r,options:o.finalOptions,circuitBreakerState:o.circuitBreaker.getState(),circuitBreakerFailures:o.circuitBreaker.getFailureCount(),metrics:{...o.metrics}}}),Dbe(l),s.setAttribute("tool.result.status","error"),s.setAttribute("tool.duration_ms",a),s.recordException(l),s.setStatus({code:Ue.ERROR,message:l.message}),l}toolCacheRepeatKey(t,r){try{return`${t}:${JSON.stringify(r)??""}`}catch{return}}async executeToolInternal(t,r,n,o){const i="NeuroLink.executeToolInternal",s=this.getToolAnnotationsForExecution(t),a=this.mcpToolResultCache&&!n.disableToolCache&&!this._disableToolCacheForCurrentRequest&&!this.uncacheableTools.has(t)&&!s?.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 f=l.getCachedResult(t,c);if(f!==void 0)return h.debug(`[${i}] Cache HIT for tool: ${t}`),f}else d&&h.debug(`[${i}] Repeat call within this request \u2014 bypassing tool cache for: ${t}`);const p=async f=>{if(this.mcpToolMiddlewares.length===0)return f();let g=0;const y=async()=>{if(g<this.mcpToolMiddlewares.length){const v=this.mcpToolMiddlewares[g++];return v({name:t,description:"",inputSchema:{},annotations:s,execute:async()=>({})},r,{toolMeta:{name:t,annotations:s}},y)}return f()};return await y()},m=async()=>{const f=this.externalServerManager.getAllTools(),g=f.filter(v=>v.name===t&&v.isAvailable);let y;if(g.length>1&&this.mcpToolRouter)try{const v={name:t,description:g[0].description??"",serverId:g[0].serverId,inputSchema:{}},T=this.mcpToolRouter.route(v);y=g.find(b=>b.serverId===T.serverId)||g[0],h.debug(`[${i}] Router selected server: ${T.serverId}`,{strategy:T.strategy,confidence:T.confidence})}catch(v){h.warn(`[${i}] Router failed, falling back to first match`,{error:v}),y=g[0]}else y=g[0];if(h.debug(`[${i}] External MCP tool search:`,{toolName:t,externalToolsCount:f.length,foundTool:!!y,isAvailable:y?.isAvailable,serverId:y?.serverId}),y&&y.isAvailable)try{re.debug(`[${i}] Executing external MCP tool: ${t} from ${y.serverId}`);const v=await this.externalServerManager.executeTool(y.serverId,t,r,{timeout:n.timeout});return h.debug(`[${i}] External MCP tool execution successful:`,{toolName:t,serverId:y.serverId,resultType:typeof v}),v}catch(v){throw h.error(`[${i}] External MCP tool execution failed:`,{toolName:t,serverId:y.serverId,error:v instanceof Error?v.message:String(v)}),he.toolExecutionFailed(t,v instanceof Error?v:new Error(String(v)),y.serverId)}try{const v=this.toolExecutionContext||{},T=n.authContext||{},b=XE({...v,...T,hitlState:o},this.resolveFileToolRoots(void 0));h.debug("[Using merged context for unified registry tool:",{toolName:t,storedContextKeys:Object.keys(v),finalContextKeys:Object.keys(b)});const S=await this.toolRegistry.executeTool(t,r,b);if(S&&typeof S=="object"&&"success"in S&&S.success===!1){const k=S.error||"Tool execution failed",A=new Error(k);this.emitter.listenerCount("error")>0&&this.emitter.emit("error",A)}return S}catch(v){const T=v instanceof Error?v:new Error(String(v));if(this.emitter.listenerCount("error")>0&&this.emitter.emit("error",T),v instanceof Error&&v.message.includes("not found")){const b=await this.getAllAvailableTools();throw he.toolNotFound(t,b.map(S=>S.name))}throw he.toolExecutionFailed(t,v instanceof Error?v:new Error(String(v)))}};try{const f=await p(m);return a&&l&&f!==void 0&&(l.cacheResult(t,c,f),h.debug(`[${i}] Cached result for tool: ${t}`)),f}catch(f){const g=s?{name:t,description:"",annotations:s,execute:async()=>({})}:void 0;if(g&&qY(g)&&f instanceof Error&&XG(f)){h.debug(`[${i}] Tool ${t} is safe to retry, attempting once more`);try{const y=await p(m);return a&&l&&y!==void 0&&l.cacheResult(t,c,y),y}catch{}}throw f}}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 np({name:t,description:""})}invalidateToolCache(){this.toolCache=null,h.debug("Tool cache invalidated")}async getAllAvailableTools(){if(this.toolCache&&Date.now()-this.toolCache.timestamp<this.toolCacheDuration)return h.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();h.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:!!Yn,providerRegistrySize:0},message:"Starting comprehensive tool discovery across all sources"});const{MemoryManager:o}=await Promise.resolve().then(()=>(iC(),lT)),i=o.getMemoryUsageMB();try{const s=new Map,a=await this.toolRegistry.listTools();for(const g of a)if(!s.has(g.name)){const y=kM(g,{serverId:g.serverId==="direct"?"neurolink-direct":g.serverId});s.set(g.name,y)}const l=this.toolRegistry.getToolsByCategory(la({isCustomTool:!0}));for(const g of l)if(!s.has(g.name)){const y=kM(g,{description:"Custom tool",serverId:`custom-tool-${g.name}`,category:la({isCustomTool:!0,serverId:g.serverId}),inputSchema:{}});s.set(g.name,y)}const c=this.toolRegistry.getToolsByCategory("in-memory");for(const g of c)if(!s.has(g.name)){const y=kM(g,{description:"In-memory MCP tool",serverId:"unknown",category:"in-memory",inputSchema:{}});s.set(g.name,y)}const u=this.externalServerManager.getAllTools();for(const g of u)if(!s.has(g.name)){const y=kM(g,{category:la({existingCategory:typeof g.metadata?.category=="string"?g.metadata.category:void 0,isExternal:!0,serverId:g.serverId}),inputSchema:{}});s.set(g.name,y)}const d=Array.from(s.values());re.debug("Tool discovery results",{mcpTools:a.length,customTools:l.length,inMemoryTools:c.length,externalMCPTools:u.length,total:d.length});const m=o.getMemoryUsageMB().heapUsed-i.heapUsed;if(m>Wp.LOW_USAGE_MB&&(re.debug(`\u{1F50D} Tool listing used ${m}MB memory (large tool registry detected)`),d.length>R0e.LARGE_TOOL_COLLECTION&&re.debug("\u{1F4A1} Tool collection optimized for large sets. Memory usage reduced through efficient object reuse.")),this.mcpEnhancementsConfig?.annotations?.autoInfer!==!1)for(const g of d)g.annotations||(g.annotations=np({name:g.name,description:g.description||""}));const f=d.sort((g,y)=>g.name<y.name?-1:g.name>y.name?1:0);return this.toolCache={tools:f,timestamp:Date.now()},f}catch(s){return re.error("Failed to list available tools",{error:s}),[]}}async getProviderStatus(t){const{MemoryManager:r}=await Promise.resolve().then(()=>(iC(),lT)),n=r.getMemoryUsageMB();t?.quiet||re.debug("\u{1F50D} DEBUG: Initializing MCP for provider status..."),await this.initializeMCP(),t?.quiet||re.debug("\u{1F50D} DEBUG: MCP initialized:",this.mcpInitialized);const{AIProviderFactory:o}=await Promise.resolve().then(()=>(Ga(),DC)),{hasProviderEnvVars:i}=await Promise.resolve().then(()=>(oh(),rC)),s=Cr.getAllDescriptors().map(p=>p.name),a=$f(Ea.DEFAULT_CONCURRENCY_LIMIT),l=s.map(p=>a(async()=>{const m=Date.now();try{if(!await this.hasProviderEnvVars(p)&&p!=="ollama")return{provider:p,status:"not-configured",configured:!1,authenticated:!1,error:"Missing required environment variables",responseTime:Date.now()-m};if(p==="ollama")try{const S=await fetch("http://localhost:11434/api/tags",{method:"GET",signal:AbortSignal.timeout(Ml.AUTH_MS)});if(!S.ok)throw new Error("Ollama service not responding");const k=await S.json(),A=k?.models;if(!Array.isArray(A))throw h.warn("Ollama API returned invalid models format in testProvider",{responseData:k,modelsType:typeof A}),new Error("Invalid models format from Ollama API");const x=A.filter(P=>P&&typeof P=="object"&&typeof P.name=="string");return x.length>0?{provider:p,status:"working",configured:!0,authenticated:!0,responseTime:Date.now()-m,model:x[0].name}:{provider:p,status:"failed",configured:!0,authenticated:!1,error:"Ollama service running but no models installed",responseTime:Date.now()-m}}catch(S){return{provider:p,status:"failed",configured:!1,authenticated:!1,error:S instanceof Error?S.message:"Ollama service not running",responseTime:Date.now()-m}}const g=5e3,y=new AbortController,v=this.testProviderConnection(p,y.signal);let T;const b=new Promise((S,k)=>{T=setTimeout(()=>{k(new Error("Provider test timeout (5s)"))},g)});try{await Promise.race([v,b])}finally{clearTimeout(T),v.catch(()=>{}),y.abort()}return{provider:p,status:"working",configured:!0,authenticated:!0,responseTime:Date.now()-m}}catch(f){const g=f instanceof Error?f.message:String(f);return{provider:p,status:"failed",configured:!0,authenticated:!1,error:g,responseTime:Date.now()-m}}})),c=await Promise.all(l),d=r.getMemoryUsageMB().heapUsed-n.heapUsed;return!t?.quiet&&d>20&&re.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,r){const{AIProviderFactory:n}=await Promise.resolve().then(()=>(Ga(),DC));await(await n.createProvider(t,null)).generate({prompt:"test",maxTokens:1,disableTools:!0,abortSignal:r})}async getBestProvider(t){const{getBestProvider:r}=await Promise.resolve().then(()=>(oh(),rC));return r(t)}async getAvailableProviders(){const{getAvailableProviders:t}=await Promise.resolve().then(()=>(oh(),rC));return t()}async isValidProvider(t){const{isValidProvider:r}=await Promise.resolve().then(()=>(oh(),rC));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(),i=this.toolRegistry.getBuiltInServerInfos(),s=this.getAutoDiscoveredServerInfos(),a=n.length+o.length+i.length+s.length,l=r.connectedServers+o.length+i.length,c=t.length+r.totalTools;return{mcpInitialized:this.mcpInitialized,totalServers:a,availableServers:l,autoDiscoveredCount:s.length,totalTools:c,autoDiscoveredServers:s,customToolsCount:this.toolRegistry.getToolsByCategory(la({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(la({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 re.error(`[NeuroLink] Error testing MCP server ${t}:`,r),!1}}async hasProviderEnvVars(t){const{ProviderHealthChecker:r}=await Promise.resolve().then(()=>(d0(),rT));try{const n=await r.checkProviderHealth(t,{includeConnectivityTest:!1,cacheResults:!1});return n.isConfigured&&n.hasApiKey}catch(n){return h.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(()=>(d0(),rT)),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(()=>(d0(),rT));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(()=>(d0(),rT)),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(()=>(d0(),rT));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,h.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 k4(SI.FAILURE_THRESHOLD,w5)),re.info(`Circuit breaker reset for tool: ${t}`))}clearToolExecutionMetrics(){this.toolExecutionMetrics.clear(),re.info("All tool execution metrics cleared")}async getToolHealthReport(){const t={};let r=0;const n=await this.toolRegistry.listTools(),o=new Set(n.map(s=>s.name)),i=new Map;for(const s of n)i.has(s.name)||i.set(s.name,s.serverId||"unknown");for(const s of o){const a=this.toolExecutionMetrics.get(s),l=`${i.get(s)||"unknown"}.${s}`,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 p=[],m=[];if(c&&c.getState()==="open"&&(p.push("Circuit breaker is open due to repeated failures"),m.push("Check tool implementation and fix underlying issues")),u<.8&&a&&a.totalExecutions>0&&(p.push(`Low success rate: ${(u*100).toFixed(1)}%`),m.push("Review error logs and improve tool reliability")),a&&a.averageExecutionTime>1e4&&(p.push("High average execution time"),m.push("Optimize tool performance or increase timeout")),a&&a.errorCategories){const f=a.errorCategories;f.timeout>0&&(p.push(`Timeout errors: ${f.timeout}`),m.push("Consider increasing the tool timeout configuration")),f.validation>0&&(p.push(`Validation errors: ${f.validation}`),m.push("Review input schemas and parameter validation")),f.network>0&&(p.push(`Network errors: ${f.network}`),m.push("Check network connectivity and endpoint availability"))}t[s]={name:s,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:p,recommendations:m}}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 h.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 De({code:He.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 De({code:He.MISSING_CONFIGURATION,message:"Conversation memory is not enabled",category:"validation",severity:"high",retriable:!1});if(!t||typeof t!="string")throw new De({code:He.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 h.debug("Retrieved conversation history",{sessionId:t,messageCount:n.length,turnCount:n.length/2}),n}catch(n){return h.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 De({code:He.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 De({code:He.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 h.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 h.debug("Listed conversation sessions",{userId:t,sessionCount:o.length}),o}catch(o){return h.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 i=await ze(this.conversationMemory.buildContextMessages(t),o,new Error("buildContextMessages operation timed out after 30s"));if(i.length===0)return h.debug("No messages found for session export",{sessionId:t}),null;const s=this.conversationMemory.getSession(t),a=await ze(s instanceof Promise?s:Promise.resolve(s),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:i};return r.includeMetadata&&(c.exportMetadata={exportedAt:l,exportFormat:r.format||"json"}),h.debug("Exported conversation session",{sessionId:t,messageCount:i.length}),c}catch(i){return h.error("Failed to export conversation session",{sessionId:t,error:i instanceof Error?i.message:String(i)}),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,i=6e4;try{const s=await ze(this.listSessions(t),o,new Error("listSessions operation timed out after 30s")),a=[];for(const l of s){const c=await ze(this.exportSession(l.id,r),i,new Error(`exportSession operation timed out after 60s for session ${l.id}`));c&&a.push(c)}return h.debug("Exported all conversation sessions",{userId:t,sessionCount:a.length}),a}catch(s){return h.error("Failed to export all conversation sessions",{userId:t,error:s instanceof Error?s.message:String(s)}),[]}}async storeToolExecutions(t,r,n,o,i){const s=n&&n.length>0||o&&o.length>0;if(!s){h.debug("Tool execution storage skipped",{hasToolData:s,toolCallsCount:n?.length||0,toolResultsCount:o?.length||0});return}const a=this.conversationMemory;if(!a?.storeToolExecution){h.debug("Tool execution storage not supported by this memory backend");return}try{await a.storeToolExecution(t,r,n,o,i)}catch(l){h.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 De({code:He.MISSING_CONFIGURATION,message:"Conversation memory is not enabled",category:"validation",severity:"high",retriable:!1});if(!t||typeof t!="string")throw new De({code:He.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 De({code:He.MISSING_CONFIGURATION,message:"Conversation memory is not enabled",category:"validation",severity:"high",retriable:!1});if(!t||typeof t!="string")throw new De({code:He.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 i=o.length-1;i>=0;i--)if(o[i].role==="assistant")return o[i]={...o[i],content:r(o[i].content)},await this.setSessionMessages(t,o,n),!0;return!1}async addExternalMCPServer(t,r){this.invalidateToolCache();try{re.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(re.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 JL({strategy:this.mcpEnhancementsConfig?.router?.strategy??"least-loaded",enableAffinity:this.mcpEnhancementsConfig?.router?.enableAffinity??!1});for(const i of o)this.mcpToolRouter.registerServer(i.id||t);h.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 re.error(`[NeuroLink] Failed to add external MCP server: ${t}`,{error:n.error,transport:r.transport,command:r.command,url:r.url?Yo(r.url):void 0});return n}catch(n){throw re.error(`[NeuroLink] Error adding external MCP server: ${t}`,n),n}}async removeExternalMCPServer(t){this.invalidateToolCache();try{re.info(`[NeuroLink] Removing external MCP server: ${t}`);const r=this.externalServerManager.getServerName(t),n=await this.externalServerManager.removeServer(t);return n.success?(re.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")?re.debug(`[NeuroLink] Remove skipped \u2014 external MCP server not registered: ${t}`):re.error(`[NeuroLink] Failed to remove external MCP server: ${t}`,{error:n.error}),n}catch(r){throw re.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(i=>i.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 i=r;try{i=this.resolveDirectMcpToolName(t,r),re.debug(`[NeuroLink] Executing external MCP tool: ${i} on ${t}`);const s=this.getToolAnnotationsForExecution(i),a=!!this.mcpToolResultCache&&!this._disableToolCacheForCurrentRequest&&!s?.destructiveHint,l={__serverId:t,__args:n,...this.toolExecutionContext?{__ctx:this.toolExecutionContext}:{}},c=this._generationTurnActive?this.toolCacheRepeatKey(i,l):void 0,u=c!==void 0&&this._toolCacheKeysServedThisRequest.has(c);if(c!==void 0&&this._toolCacheKeysServedThisRequest.add(c),a&&this.mcpToolResultCache&&!u){const f=this.mcpToolResultCache.getCachedResult(i,l);if(f!==void 0)return re.debug(`[NeuroLink] Tool result cache HIT: ${i} on ${t}`),f}const d=await this.externalServerManager.executeTool(t,i,n,o),p=d&&typeof d=="object"?d:void 0,m=!!(p&&"isError"in p&&p.isError===!0||p&&"success"in p&&p.success===!1);return a&&this.mcpToolResultCache&&!m&&d!==void 0&&this.mcpToolResultCache.cacheResult(i,l,d),re.debug(`[NeuroLink] External MCP tool ${m?"returned error":"executed successfully"}: ${i}`),d}catch(s){throw re.error(`[NeuroLink] External MCP tool execution failed: ${i}`,s),s}}resolveDirectMcpToolName(t,r){const n=this.getExternalMCPServer(t);if(!n||n.status!=="connected"||!n.client)return r;const o=this.getExternalMCPServerTools(t).map(s=>s.name);if(o.includes(r))return r;const i=oY(r,o);if(!i)throw new sY(r,t,P1t(r,o));return Be.mcp.startActiveSpan("neurolink.mcp.toolNameRepair",{attributes:{"mcp.server_id":t,"mcp.tool_name.requested":r,"mcp.tool_name.resolved":i.name,"mcp.tool_name.repair_strategy":i.strategy,...i.score!==void 0?{"mcp.tool_name.repair_score":i.score}:{}}},s=>s.end()),re.info(`[NeuroLink] Repaired external MCP tool name at direct execution boundary: "${r}" \u2192 "${i.name}" (${i.strategy}) on server '${t}'`),i.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(()=>(Vne(),rGt)),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{re.info("[NeuroLink] Shutting down all external MCP servers..."),this.unregisterAllExternalMCPToolsFromRegistry(),await this.externalServerManager.shutdown(),re.info("[NeuroLink] All external MCP servers shut down successfully")}catch(t){throw re.error("[NeuroLink] Error shutting down external MCP servers:",t),t}}async getElicitationManager(){return(await ze(Promise.resolve().then(()=>(cKt(),lKt)),1e4)).globalElicitationManager}async registerElicitationHandler(t){(await this.getElicitationManager()).registerHandler(t)}async getMultiServerManager(){return(await ze(Promise.resolve().then(()=>(Fre(),h5t)),1e4)).globalMultiServerManager}async getEnhancedToolDiscovery(){const t=await ze(Promise.resolve().then(()=>($re(),f5t)),1e4);return new t.EnhancedToolDiscovery(this.toolRegistry)}async getMCPRegistryClient(){return(await ze(Promise.resolve().then(()=>(mKt(),uKt)),1e4)).globalMCPRegistryClient}async exposeAgentAsTool(t,r){return(await ze(Promise.resolve().then(()=>(Oae(),Pae)),1e4)).exposeAgentAsTool(t,r)}async exposeWorkflowAsTool(t,r){return(await ze(Promise.resolve().then(()=>(Oae(),Pae)),1e4)).exposeWorkflowAsTool(t,r)}async getToolIntegrationManager(){return(await ze(Promise.resolve().then(()=>(TKt(),gKt)),1e4)).globalToolIntegrationManager}async convertToolsToMCPFormat(t,r={}){const n=await ze(Promise.resolve().then(()=>(LO(),VY)),1e4),o=t.map(i=>({...i,execute:i.execute??(async()=>({success:!1,error:"No execute function provided"}))}));return n.batchConvertToMCP(o,r)}async convertToolsFromMCPFormat(t,r={}){return(await ze(Promise.resolve().then(()=>(LO(),VY)),1e4)).batchConvertToNeuroLink(t,r)}async getToolAnnotations(t){const{inferAnnotations:r,mergeAnnotations:n,getAnnotationSummary:o}=await ze(Promise.resolve().then(()=>(Jk(),eRt)),1e4),i=this.toolRegistry.getToolInfo(t);if(!i)return null;const s=i.tool.annotations,a=r({name:i.tool.name,description:i.tool.description??""}),l=n(a,s);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 i=>{try{re.debug(`[NeuroLink] Executing external MCP tool via AI SDK: ${n.name}`,{params:i});const s=await this.externalServerManager.executeTool(n.serverId,n.name,i,{timeout:3e4});return re.debug(`[NeuroLink] External MCP tool execution result: ${n.name}`,{success:!!s,hasData:!!(s&&typeof s=="object"&&"content"in s)}),s}catch(s){throw re.error(`[NeuroLink] External MCP tool execution failed: ${n.name}`,s),s}}};r[n.name]=o,re.debug(`[NeuroLink] Converted external MCP tool to AI SDK format: ${n.name} from server ${n.serverId}`)}return re.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),re.debug(`[NeuroLink] Unregistered external MCP tool from main registry: ${n.name}`)}catch(r){re.error(`[NeuroLink] Failed to unregister external MCP tools from registry for server ${t}:`,r)}}unregisterExternalMCPToolFromRegistry(t){try{this.toolRegistry.removeTool(t),re.debug(`[NeuroLink] Unregistered external MCP tool from main registry: ${t}`)}catch(r){re.error(`[NeuroLink] Failed to unregister external MCP tool ${t} from registry:`,r)}}async lazyInitializeConversationMemory(t,r,n){try{const{initializeConversationMemory:o}=await Dln().then(()=>EKt),i=await o(this.conversationMemoryConfig);this.conversationMemory=i,this.conversationMemoryNeedsInit=!1}catch(o){throw h.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);re.debug(`[NeuroLink] Unregistered ${t.length} external MCP tools from main registry`)}catch(t){re.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(()=>(ES(),_S)),1e4,he.evaluationTimeout("evaluation module load",1e4));let o;typeof t=="string"?o=n(t):o=t;const i=new r(o);return await ze(i.initialize(),3e4,he.evaluationTimeout("pipeline initialization",3e4)),h.debug(`[NeuroLink] Created evaluation pipeline: ${o.name??"custom"}`),i}async decide(t){const r=t.provider??pE(this.resolveCredentials(t.credentials));if(!r)throw new Error(`No decision provider is configured. Set ${iPr()} (in the environment or in \`credentials\`), or pass \`provider\` explicitly.`);const n=Object.keys(t.questions).length;return mt({name:`gen_ai.${r}.decide`,tracer:Be.decision,attributes:{"gen_ai.system":r,"gen_ai.operation.name":"decide","ai.provider":r,"decision.question_count":n,"decision.images.count":t.images?.length??0}},async o=>{const{traceId:i,parentSpanId:s}=wf(),a=Date.now();let l=Me.createSpan("model.decision",`decision.${r}`,{"ai.provider":r,"ai.model":t.model??"","decision.question_count":n,"decision.images.count":t.images?.length??0},s,i);try{const c=await Yn.createProvider(r,t.model,!1,this,void 0,this.resolveCredentials(t.credentials));if(typeof c.decide!="function")throw new Error(`Provider "${r}" does not serve the decide inference type.`);const u=await c.decide({state:t.state,questions:t.questions,images:t.images,video:t.video,model:t.model,signal:t.signal,timeoutMs:t.timeoutMs}),d=Object.keys(u.answers).length,p=Ls(r,u.model,{input:u.usage.inputTokens,output:u.usage.outputTokens,total:u.usage.inputTokens+u.usage.outputTokens});o.setAttribute("gen_ai.response.model",u.model),o.setAttribute("gen_ai.usage.input_tokens",u.usage.inputTokens),o.setAttribute("gen_ai.usage.output_tokens",u.usage.outputTokens),o.setAttribute("decision.answer_count",d),o.setAttribute("decision.media.bytes",u.mediaBytes??0),o.setAttribute("ai.cost.total",p),u.upstreamMs!==void 0&&o.setAttribute("decision.upstream_ms",u.upstreamMs),u.requestId&&o.setAttribute("gen_ai.response.id",u.requestId),l.durationMs=Date.now()-a,l=Me.updateAttributes(l,{"ai.model":u.model,"ai.tokens.input":u.usage.inputTokens,"ai.tokens.output":u.usage.outputTokens,"ai.cost.input":p,"ai.cost.output":0,"ai.cost.total":p,"decision.answer_count":d,"decision.media.bytes":u.mediaBytes??0,"decision.latency_ms":u.latencyMs,...u.upstreamMs!==void 0?{"decision.upstream_ms":u.upstreamMs}:{}});const m=Me.endSpan(l,1);return this.metricsAggregator.recordSpan(m),it().recordSpan(m),u}catch(c){l.durationMs=Date.now()-a;const u=Me.endSpan(l,2,c instanceof Error?c.message:String(c));throw this.metricsAggregator.recordSpan(u),it().recordSpan(u),c}})}async tryDecide(t){try{const r=await this.decideInBatches(t);return h.shouldLog("debug")&&h.debug(`decide: ${Object.keys(r.answers).length} answers in ${r.latencyMs}ms`+(r.upstreamMs?` (upstream ${r.upstreamMs}ms)`:""),{provider:r.provider,model:r.model,requestId:r.requestId,usage:r.usage}),r}catch(r){return h.debug(`decide unavailable: ${r instanceof Error?r.message:String(r)} \u2014 falling back`),null}}async decideInBatches(t){const r=t.provider??pE(this.resolveCredentials(t.credentials)),n=r?sm.get(r.toLowerCase()):void 0,o=n?hr.get(n)?.decisionLimits?.maxQuestions:void 0,i=bYr(t,o);if(i.length===1)return this.decide(t);const s=[];let a;for(let u=0;u<i.length;u+=Ire){const d=await Promise.allSettled(i.slice(u,u+Ire).map(p=>this.decide(p)));for(const p of d)p.status==="fulfilled"?s.push(p.value):a??=p.reason}const[l,...c]=s;if(l===void 0)throw a instanceof Error?a:new Error(String(a));return c.length+1<i.length&&h.debug(`decide: ${i.length-s.length} of ${i.length} batches failed; using the answers of the rest`),_Yr([l,...c])}async evaluate(t,r){const{EvaluationPipeline:n,getPreset:o}=await ze(Promise.resolve().then(()=>(ES(),_S)),1e4,he.evaluationTimeout("evaluation module load",1e4));let i;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?i={...o(r.pipeline)}:r?.scorers&&r.scorers.length>0?i={name:"SDK Evaluation",description:"Evaluation from NeuroLink SDK",scorers:r.scorers.map(c=>({id:c})),executionMode:r.executionMode??"parallel",passThreshold:r.passThreshold??.7}:i=o("quality"),r?.passThreshold!==void 0&&(i.passThreshold=r.passThreshold),r?.executionMode!==void 0&&(i.executionMode=r.executionMode);const s=new n(i);await ze(s.initialize(),3e4,he.evaluationTimeout("pipeline initialization",3e4));const a=r?.timeoutMs??6e4,l=await ze(s.execute(t,{correlationId:r?.correlationId}),a,he.evaluationTimeout("pipeline execution",a));return h.debug("[NeuroLink] Evaluation completed",{pipeline:i.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(()=>(Sj(),Ej)),1e4,he.evaluationTimeout("scorer module load",1e4));await ze(o.registerBuiltInScorers(),3e4,he.evaluationTimeout("scorer bootstrap",3e4));const i=await ze(o.getScorer(t,n),3e4,he.evaluationTimeout(`scorer load: ${t}`,3e4));if(!i)throw he.scorerNotFound(t);const s=i.validateInput(r);if(!s.valid)throw he.evaluationValidationFailed(t,s.errors);const a=await ze(i.score(r),6e4,he.evaluationTimeout("scorer execution",6e4));return h.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(()=>(Sj(),Ej)),1e4,he.evaluationTimeout("scorer module load",1e4));await ze(r.registerBuiltInScorers(),3e4,he.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(()=>(ES(),_S)),1e4,he.evaluationTimeout("evaluation module load",1e4));return t()}async getEvaluationPreset(t){const{getPreset:r}=await ze(Promise.resolve().then(()=>(ES(),_S)),1e4,he.evaluationTimeout("evaluation module load",1e4));return r(t)}async createAgent(t){const{Agent:r}=await Promise.resolve().then(()=>(Uae(),SKt));return h.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(()=>(xKt(),kKt));return h.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??{},i={...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}},s=this.workerToolsConfig(o.tools),a=new _6(s?{...i,tools:s}:i);if(t?.shareToolRegistry!==!1)for(const l of this.uncacheableTools)a.uncacheableTools.add(l);if(h.setEventEmitter(n),t?.onLog){const l=t.onLog,c=f=>{try{const g=f??{};l({tag:r,level:String(g.level??"info"),message:String(g.message??""),timestamp:typeof g.timestamp=="number"?g.timestamp:Date.now(),data:g.data})}catch{}},u={emit:(f,...g)=>(f==="log-event"&&c(g[0]),!0)},d=a.logInstanceId;h.addScopedEventEmitter(d,u);const p=()=>{h.removeScopedEventEmitter(d,u),this.ownedWorkerLogBridgeDetachers.delete(p)};this.ownedWorkerLogBridgeDetachers.add(p);const m=a.dispose.bind(a);a.dispose=async()=>{p(),await m()}}return h.debug("[NeuroLink] Created worker instance",{tag:r,sharedToolRegistry:t?.shareToolRegistry!==!1}),a}async runIsolatedAgent(t,r,n){const{runIsolatedAgent:o}=await Promise.resolve().then(()=>(jA(),t3));return o(this,t,r,n)}async continueAgent(t,r){const{continueIsolatedAgent:n}=await Promise.resolve().then(()=>(jA(),t3));return n(this,t,r)}async stopAgent(t){const{stopIsolatedAgent:r}=await Promise.resolve().then(()=>(jA(),t3));return r(this,t)}async registerAgentTool(t,r){const{registerAgentTool:n}=await Promise.resolve().then(()=>(WA(),i3)),o=n(this,t,r);return this.hasAgentTools=!0,o}registerTaskTools(){if(this.hasTaskChecklistTools)return;const t=Tnn(this);for(const[r,n]of Object.entries(t))this.registerTool(r,n,{cacheable:!1});this.hasTaskChecklistTools=!0,h.info(`[NeuroLink] Registered ${Object.keys(t).length} task checklist tools`)}getTaskState(t){return gnn(t??pi(this))}clearTaskState(t){return ynn(t??pi(this))}registerDelegationTools(t){if(Unn(this,t),this.hasBackgroundDelegationTools)return;const r=Jnn(this);for(const[n,o]of Object.entries(r))this.registerTool(n,o,{cacheable:!1});this.hasBackgroundDelegationTools=!0,h.info(`[NeuroLink] Registered ${Object.keys(r).length} background delegation tools`)}async spawnDelegate(t){return t7t(this,t)}async collectDelegates(t){return n7t(this,t)}async cancelDelegates(t){return Fie(this,t)}getArtifactStore(){return this.mcpArtifactStore||(this.mcpArtifactStore=this.createConfiguredArtifactStore()),this.registerMemoryRetrievalTools(),this.mcpArtifactStore}setArtifactStore(t){const r=this.mcpArtifactStore;r!==t&&(r&&(h.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=>{h.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=W8t(this.artifactsConfig,this.conversationMemoryConfig?.conversationMemory?.redisConfig);return this.ownsArtifactStore=!t,h.debug("[NeuroLink] Artifact store initialized",{backend:t?"custom":_oe(this.artifactsConfig)}),r}installOutputNormalizer(t){this.mcpOutputNormalizerConfig&&(this.externalServerManager.setOutputNormalizer(new PGt(this.mcpOutputNormalizerConfig,t)),h.debug("[NeuroLink] MCP output normalizer initialized",{...this.mcpOutputNormalizerConfig,hasArtifactStore:t!==void 0}))}async bankArtifact(t,r){return urn(this,t,r)}async readArtifact(t,r){return drn(this,t,r)}registerBackgroundCommandTools(t){if(c7t(this,t),this.hasBackgroundCommandTools)return;const r=oon(this);for(const[n,o]of Object.entries(r))this.registerTool(n,o,{cacheable:!1});this.hasBackgroundCommandTools=!0,h.info(`[NeuroLink] Registered ${Object.keys(r).length} background command tools`)}setBackgroundCommandPolicy(t){c7t(this,t)}async startBackgroundCommand(t,r){return y7t(this,t,r)}getBackgroundCommandStatus(t){return v7t(this,t)}async awaitBackgroundCommand(t,r){return Xie(this,t,r)}async killBackgroundCommand(t,r){return w7t(this,t,r)}async readBackgroundCommandOutput(t,r){return h3(this,t,r)}registerGitTools(t){if(ion(this,t),this.hasGitTools)return;const r=pon(this);for(const[n,o]of Object.entries(r))this.registerTool(n,o,{cacheable:!1});this.hasGitTools=!0,h.info(`[NeuroLink] Registered ${Object.keys(r).length} read-only git tools`)}async runGitCommand(t,r){return M7t(this,t,r)}async executeNetwork(t,r,n){return h.debug("[NeuroLink] Executing agent network",{networkId:t.id,networkName:t.name,hasContext:!!r.context}),t.execute(r,n)}async*streamNetwork(t,r,n){h.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(()=>(RKt(),IKt));return h.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(()=>(MKt(),PKt));return h.debug("[NeuroLink] Creating agent coordinator",{strategy:t?.strategy,maxConcurrency:t?.maxConcurrency}),new r(t)}async createMessageBus(t){const{MessageBus:r}=await Promise.resolve().then(()=>(DKt(),OKt));return h.debug("[NeuroLink] Creating message bus",{maxHistorySize:t?.maxHistorySize}),new r(t)}async dispose(){h.debug("[NeuroLink] Starting disposal of resources..."),this.lastCompactionMessageCount.clear();const t=[];try{try{await T7t(this),await Fie(this)}catch(r){const n=r instanceof Error?r:new Error(`Background work cleanup error: ${String(r)}`);t.push(n),h.warn("[NeuroLink] Error stopping background work:",r)}try{h.debug("[NeuroLink] Flushing and shutting down OpenTelemetry..."),await aO(),await lO(),h.debug("[NeuroLink] OpenTelemetry shutdown successfully")}catch(r){const n=r instanceof Error?r:new Error(`OpenTelemetry shutdown error: ${String(r)}`);t.push(n),h.warn("[NeuroLink] Error shutting down OpenTelemetry:",r)}if(this.externalServerManager)try{h.debug("[NeuroLink] Shutting down external MCP servers..."),await this.externalServerManager.shutdown(),h.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),h.warn("[NeuroLink] Error shutting down external MCP servers:",r)}if(this.ownsArtifactStore&&this.mcpArtifactStore?.close)try{await this.mcpArtifactStore.close(),h.debug("[NeuroLink] Artifact store closed")}catch(r){const n=r instanceof Error?r:new Error(`Artifact store close error: ${String(r)}`);t.push(n),h.warn("[NeuroLink] Error closing artifact store:",r)}if(this.emitter)try{h.debug("[NeuroLink] Removing all event listeners..."),this.emitter.removeAllListeners(),h.clearEventEmitter(this.emitter),h.clearScopedEventEmitters(this.logInstanceId),h.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),h.warn("[NeuroLink] Error removing event listeners:",r)}if(this.ownedWorkerLogBridgeDetachers.size>0)try{const r=this.ownedWorkerLogBridgeDetachers.size;for(const n of[...this.ownedWorkerLogBridgeDetachers])n();h.debug(`[NeuroLink] Detached ${r} undisposed worker log bridge(s)`)}catch(r){const n=r instanceof Error?r:new Error(`Worker log bridge cleanup error: ${String(r)}`);t.push(n),h.warn("[NeuroLink] Error detaching worker log bridges:",r)}if(this.toolCircuitBreakers&&this.toolCircuitBreakers.size>0)try{h.debug(`[NeuroLink] Clearing ${this.toolCircuitBreakers.size} circuit breakers...`),this.toolCircuitBreakers.clear(),h.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),h.warn("[NeuroLink] Error clearing circuit breakers:",r)}try{h.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=[],h.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),h.warn("[NeuroLink] Error clearing caches:",r)}if(this._taskManager)try{h.debug("[NeuroLink] Shutting down TaskManager..."),await ze(this._taskManager.shutdown(),5e3,new Error("TaskManager shutdown timed out"))}catch(r){h.warn("[NeuroLink] TaskManager shutdown error:",r)}finally{this._taskManager=void 0}try{h.debug("[NeuroLink] Resetting initialization state..."),this.mcpInitialized=!1,this.mcpInitPromise=null,this.conversationMemoryNeedsInit=!1,this.credentials=void 0,h.debug("[NeuroLink] Initialization state reset successfully")}catch(r){const n=r instanceof Error?r:new Error(`State reset error: ${String(r)}`);t.push(n),h.warn("[NeuroLink] Error resetting state:",r)}t.length===0?h.debug("[NeuroLink] \u2705 Resource disposal completed successfully"):h.warn(`[NeuroLink] \u26A0\uFE0F Resource disposal completed with ${t.length} errors`,{errors:t.map(r=>r.message)})}catch(r){throw h.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 Rw({...r,summarizationProvider:r?.summarizationProvider??this.conversationMemoryConfig?.conversationMemory?.summarizationProvider,summarizationModel:r?.summarizationModel??this.conversationMemoryConfig?.conversationMemory?.summarizationModel},this.contextCompactorDeps()),i=aa({provider:r?.provider||"openai",conversationMessages:n}),s=Math.floor(i.availableInputTokens*.6),a=await o.compact(n,s,this.conversationMemoryConfig?.conversationMemory);return a.compacted&&Cw(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 i=aa({provider:r||"openai",model:n,conversationMessages:o});return{estimatedInputTokens:i.estimatedInputTokens,availableInputTokens:i.availableInputTokens,usageRatio:i.usageRatio,shouldCompact:i.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:i}=await Promise.resolve().then(()=>(rF(),NKt));r=await i.createProvider(o.type,o.config),n=o.type}this.authProvider=r,h.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(()=>(CA(),DL));r.set(t),h.debug("Auth context set",{userId:t.user.id,provider:t.provider,sessionId:t.session?.id})}async getAuthContext(){const{getAuthContext:t}=await Promise.resolve().then(()=>(CA(),DL));return t()}async clearAuthContext(){const{globalAuthContext:t}=await Promise.resolve().then(()=>(CA(),DL)),r=t.get()?.user.id;t.clear(),r&&h.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(i=>typeof t[i]=="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(h.debug("[NeuroLink] Resolving dynamic arguments"),await Promise.all(r.map(async i=>{if(typeof t[i]=="function"){const s=await Aoe(t[i],o);t[i]=s.value,h.debug(`[NeuroLink] Resolved dynamic ${i}: ${s.resolutionType}`)}})),typeof t.tools=="function"){const i=await Aoe(t.tools,o);if(!Array.isArray(i.value))throw new TypeError(`Dynamic tools resolver must return string[] (tool names), got ${typeof i.value=="object"?"object":typeof i.value}`);t.enabledToolNames=i.value,delete t.tools}}},Jae=new AT,UKt=Jae}});function BKt(e,t,r,n){const o=typeof e=="object"&&e!==null?e.data:void 0;if(!Array.isArray(o)||o.length===0)throw n(`${r} embeddings response missing data`);if(o.length!==t)throw n(`${r} embeddings response count mismatch: expected ${t}, got ${o.length}`);const i=o.findIndex(a=>!zKt(a));if(i!==-1)throw n(`${r} embeddings response entry ${i} is not an {index, embedding: number[]} object`);const s=o.slice().sort((a,l)=>a.index-l.index);for(let a=0;a<s.length;a++)if(s[a].index!==a)throw n(`${r} embeddings response has unexpected index ordering: position ${a} has index ${s[a].index}`);return s.map(a=>a.embedding)}var zKt,GKt=E({"src/lib/providers/embeddingResponseParsing.ts"(){"use strict";zKt=e=>{if(typeof e!="object"||e===null)return!1;const{embedding:t,index:r}=e;return Number.isInteger(r)&&Array.isArray(t)&&t.every(n=>typeof n=="number"&&Number.isFinite(n))}}}),qKt={};Z(qKt,{VoyageProvider:()=>HKt});var VKt,Xae,jKt,oF,HKt,qln=E({async"src/lib/providers/voyage.ts"(){"use strict";pl(),await tu(),GKt(),Ln(),pt(),et(),z(),Go(),VKt="https://api.voyageai.com/v1",Xae=6e4,jKt=()=>_a(H4r()),oF=()=>Fi("VOYAGE_MODEL","voyage-3.5"),HKt=class extends Ma{apiKey;baseURL;proxyFetch;constructor(e,t,r,n){const o=ch(t)?t:void 0;super(e,"voyage",o);const i=n?.apiKey?.trim();this.apiKey=i&&i.length>0?i:jKt(),this.baseURL=n?.baseURL??process.env.VOYAGE_BASE_URL??VKt,this.proxyFetch=Ot(),h.debug("Voyage Provider initialized (embeddings only)",{modelName:this.modelName,baseURL:this.baseURL})}getProviderName(){return this.providerName}getDefaultModel(){return oF()}supportsTools(){return!1}getDefaultEmbeddingModel(){return oF()}getAISDKModel(){throw new nt("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 nt("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 Wr("Invalid Voyage AI API key. Get one at https://dash.voyageai.com/api-keys","voyage"):t.includes("429")||t.toLowerCase().includes("rate limit")?new Qi("Voyage AI rate limit exceeded. Back off and retry.","voyage"):t.includes("404")||t.toLowerCase().includes("model_not_found")?new Jo(`Voyage AI model '${this.modelName}' not found. Browse https://docs.voyageai.com/docs/embeddings`,"voyage"):new nt(`Voyage AI error: ${t}`,"voyage")}async embed(e,t){if(typeof e!="string"&&e.image)throw new nt(`${this.providerName} does not support image embeddings; provide text input`,this.providerName);const r=typeof e=="string"?e:e.text??"",n=await this.callEmbeddings([r],t);if(!n[0])throw new nt("Voyage AI returned no embedding for the provided text","voyage");return n[0]}async embedMany(e,t){if(e.length===0)return[];const r=128,n=[];for(let o=0;o<e.length;o+=r){const i=e.slice(o,o+r),s=await this.callEmbeddings(i,t);n.push(...s)}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})}),Xae,new nt(`Voyage embeddings request timed out after ${Xae/1e3}s`,"voyage"))}catch(i){throw i instanceof nt?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();return BKt(o,e.length,"Voyage",i=>new nt(i,"voyage"))}async validateConfiguration(){return typeof this.apiKey=="string"&&this.apiKey.trim().length>0}getConfiguration(){return{provider:this.providerName,model:this.modelName,defaultModel:oF(),baseURL:this.baseURL}}}}}),WKt={};Z(WKt,{JinaProvider:()=>XKt});var KKt,gC,JKt,iF,XKt,Vln=E({async"src/lib/providers/jina.ts"(){"use strict";pl(),await tu(),GKt(),Ln(),pt(),z(),Go(),KKt="https://api.jina.ai/v1",gC=6e4,JKt=()=>_a(W4r()),iF=()=>Fi("JINA_MODEL","jina-embeddings-v3"),XKt=class extends Ma{apiKey;baseURL;proxyFetch;constructor(e,t,r,n){const o=ch(t)?t:void 0;super(e,"jina",o);const i=n?.apiKey?.trim();this.apiKey=i&&i.length>0?i:JKt(),this.baseURL=n?.baseURL??process.env.JINA_BASE_URL??KKt,this.proxyFetch=Ot(),h.debug("Jina Provider initialized (embeddings + reranking)",{modelName:this.modelName,baseURL:this.baseURL})}getProviderName(){return this.providerName}getDefaultModel(){return iF()}supportsTools(){return!1}getDefaultEmbeddingModel(){return iF()}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 Wr("Invalid Jina AI API key. Get one at https://jina.ai/?sui=apikey","jina"):t.includes("429")||t.toLowerCase().includes("rate limit")?new Qi("Jina AI rate limit exceeded. Back off and retry.","jina"):t.includes("404")||t.toLowerCase().includes("model_not_found")?new Jo(`Jina AI model '${this.modelName}' not found. See https://jina.ai/embeddings/`,"jina"):new nt(`Jina AI error: ${t}`,"jina")}async embed(e,t){if(typeof e!="string"&&e.image)throw new nt(`${this.providerName} does not support image embeddings; provide text input`,this.providerName);const r=typeof e=="string"?e:e.text??"",n=await this.callEmbeddings([r],t);if(!n[0])throw new Error("Jina AI returned no embedding for the provided text");return n[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,i=o?.apiKey?.trim()||this.apiKey,s=o?.baseURL||this.baseURL,a=new AbortController,l=setTimeout(()=>a.abort(),gC);let c;try{c=await this.proxyFetch(`${s}/rerank`,{method:"POST",headers:{Authorization:`Bearer ${i}`,"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 ${gC/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,i=r?.baseURL||this.baseURL,s=new AbortController,a=setTimeout(()=>s.abort(),gC);let l;try{l=await this.proxyFetch(`${i}/embeddings`,{method:"POST",headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json"},body:JSON.stringify({input:e,model:n}),signal:s.signal})}catch(u){throw u instanceof Error&&u.name==="AbortError"?this.formatProviderError(new Error(`Jina embeddings request timed out after ${gC/1e3}s`)):this.formatProviderError(u)}finally{clearTimeout(a)}if(!l.ok){const u=await l.text();throw this.formatProviderError(new Error(`Jina embeddings failed: ${l.status} \u2014 ${u}`))}const c=await l.json();return BKt(c,e.length,"Jina",u=>new Error(u))}async validateConfiguration(){return typeof this.apiKey=="string"&&this.apiKey.trim().length>0}getConfiguration(){return{provider:this.providerName,model:this.modelName,defaultModel:iF(),baseURL:this.baseURL}}}}}),YKt={};Z(YKt,{StabilityProvider:()=>Qae,default:()=>eJt});var ZKt,Yae,QKt,Zae,Qae,eJt,jln=E({async"src/lib/providers/stability.ts"(){"use strict";pl(),await tu(),Ln(),pt(),z(),Go(),ZKt="https://api.stability.ai",Yae=12e4,QKt=()=>(process.env.STABILITY_API_KEY??process.env.STABILITY_AI_API_KEY??"").trim()||void 0,Zae=()=>Fi("STABILITY_MODEL","stable-image-ultra"),Qae=class extends Ma{apiKey;baseURL;proxyFetch;constructor(e,t,r,n){const o=ch(t)?t:void 0;super(e,"stability",o);const i=n?.apiKey?.trim();this.apiKey=i&&i.length>0?i:QKt(),this.baseURL=n?.baseURL??process.env.STABILITY_BASE_URL??ZKt,this.proxyFetch=Ot(),h.debug("Stability AI Provider initialized (image-gen only)",{modelName:this.modelName,baseURL:this.baseURL})}getProviderName(){return this.providerName}getDefaultModel(){return Zae()}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 Wr("Invalid Stability AI API key. Get one at https://platform.stability.ai/account/keys","stability"):t.includes("429")||t.toLowerCase().includes("rate limit")?new Qi("Stability AI rate limit exceeded. Back off and retry.","stability"):t.includes("content_filtered")||t.includes("CONTENT_FILTERED")?new nt("Stability AI declined the request due to content policy. Adjust the prompt and retry.","stability"):t.includes("404")?new Jo(`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 nt(`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,i=r?.baseURL||this.baseURL,s=e.prompt??e.input?.text??"";if(!s.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",s),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(),Yae);let p;try{p=await this.proxyFetch(`${i}/v2beta/stable-image/generate/${a}`,{method:"POST",headers:{Authorization:`Bearer ${o}`,Accept:"application/json"},body:c,signal:u.signal})}catch(g){throw g instanceof Error&&g.name==="AbortError"?this.formatProviderError(new Error(`Stability image-gen request timed out after ${Yae/1e3}s`)):this.formatProviderError(g)}finally{clearTimeout(d)}if(!p.ok){const g=await p.text();throw this.formatProviderError(new Error(`Stability image-gen failed: ${p.status} \u2014 ${g}`))}const m=await p.json();if(!m.image)throw new Error(`Stability AI returned no image (finish_reason: ${m.finish_reason??"unknown"})`);const f=Date.now()-t;return h.info(`[StabilityProvider] Generated image (${m.image.length} base64 chars) in ${f}ms \u2014 model ${this.modelName}`),{content:s,provider:this.providerName,model:this.modelName,usage:{input:0,output:1e3,total:1e3},imageOutput:{base64:m.image}}}async validateConfiguration(){return this.apiKey!==void 0&&this.apiKey.trim().length>0}getConfiguration(){return{provider:this.providerName,model:this.modelName,defaultModel:Zae(),baseURL:this.baseURL}}},eJt=Qae}}),tJt={};Z(tJt,{IdeogramProvider:()=>rle,default:()=>oJt});var rJt,ele,nJt,tle,rle,oJt,Hln=E({async"src/lib/providers/ideogram.ts"(){"use strict";pl(),await tu(),Ln(),pt(),z(),Go(),Oa(),Fm(),rJt="https://api.ideogram.ai",ele=12e4,nJt=()=>_a(K4r()),tle=()=>Fi("IDEOGRAM_MODEL","V_3"),rle=class extends Ma{apiKey;baseURL;proxyFetch;constructor(e,t,r,n){const o=ch(t)?t:void 0;super(e,"ideogram",o);const i=n?.apiKey?.trim();this.apiKey=i&&i.length>0?i:nJt(),this.baseURL=n?.baseURL??process.env.IDEOGRAM_BASE_URL??rJt,this.proxyFetch=Ot(),h.debug("Ideogram Provider initialized (image-gen only)",{modelName:this.modelName,baseURL:this.baseURL})}getProviderName(){return this.providerName}getDefaultModel(){return tle()}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 Wr("Invalid Ideogram API key. Get one at https://developer.ideogram.ai/","ideogram"):t.includes("429")||t.toLowerCase().includes("rate limit")?new Qi("Ideogram rate limit exceeded. Back off and retry.","ideogram"):t.includes("safety")||t.includes("is_image_safe")?new nt("Ideogram declined the request due to safety filters. Adjust the prompt and retry.","ideogram"):new nt(`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,i=e.prompt??e.input?.text??"";if(!i.trim())throw new Error("Ideogram image generation requires a prompt (input.text or prompt)");const s=e,a={prompt:i,model:this.modelName,magic_prompt:s.magicPrompt??"AUTO"};s.aspectRatio&&(a.aspect_ratio=s.aspectRatio),s.negativePrompt&&(a.negative_prompt=s.negativePrompt),s.seed!==void 0&&(a.seed=s.seed),s.style&&(a.style_type=s.style);const l=new AbortController,c=setTimeout(()=>l.abort(),ele);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(y){throw y instanceof Error&&y.name==="AbortError"?this.formatProviderError(new Error(`Ideogram image-gen request timed out after ${ele/1e3}s`)):this.formatProviderError(y)}finally{clearTimeout(c)}if(!u.ok){const y=await u.text();throw this.formatProviderError(new Error(`Ideogram image-gen failed: ${u.status} \u2014 ${y}`))}const p=(await u.json()).data?.[0]?.url;if(!p)throw new Error("Ideogram returned no image URL");const m=await Lm(p,{label:"Ideogram image",maxBytes:Nm,timeoutMs:6e4}),f=m.toString("base64"),g=Date.now()-t;return h.info(`[IdeogramProvider] Generated image (${m.length} bytes) in ${g}ms \u2014 model ${this.modelName}`),{content:i,provider:this.providerName,model:this.modelName,usage:{input:0,output:1e3,total:1e3},imageOutput:{base64:f}}}async validateConfiguration(){return typeof this.apiKey=="string"&&this.apiKey.trim().length>0}getConfiguration(){return{provider:this.providerName,model:this.modelName,defaultModel:tle(),baseURL:this.baseURL}}},oJt=rle}}),iJt={};Z(iJt,{ReplicateProvider:()=>sJt});function Wln(e){const t=e,r=t.prompt??t.input?.text??"",n=t.systemPrompt;return n?`${n}
|
|
2151
2151
|
|
|
2152
|
-
${r}`:r}function Kln(e){return typeof e=="string"?e:Array.isArray(e)?e.map(t=>typeof t=="string"?t:"").join(""):""}function nle(e){const t=e?.apiKey?.trim()||e?.apiToken?.trim(),r=e?.baseURL||e?.baseUrl;return{apiToken:t,baseUrl:r}}var ole,sJt,Jln=E({async"src/lib/providers/replicate.ts"(){"use strict";pl(),If(),B3(),G3(),Oa(),await tu(),z(),et(),Go(),ole=()=>Fi("REPLICATE_MODEL","meta/meta-llama-3-70b-instruct"),sJt=class extends Ma{apiToken;baseURL;constructor(e,t,r,n){const o=ch(t)?t:void 0;super(e,"replicate",o);const{apiToken:i,baseUrl:s}=nle(n);this.apiToken=i&&i.length>0?i:_a(j4r()),this.baseURL=s,h.debug("Replicate Provider initialized",{modelName:this.modelName,baseURL:this.baseURL})}getProviderName(){return this.providerName}getDefaultModel(){return ole()}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=$d(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 De({code:He.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??"",i=Date.now(),s=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 s.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 h.info(`[ReplicateProvider] generate() complete in ${Date.now()-i}ms \u2014 ${a.length} chars`),l}async executeStream(e,t){const r=Date.now(),n=e.credentials?.replicate,o=nle(n),i=o.apiToken||this.apiToken,s=o.baseUrl||this.baseURL,a=ah({apiToken:i,baseUrl:s});if(!a)throw new De({code:He.MISSING_CONFIGURATION,message:"Replicate auth could not be resolved (REPLICATE_API_TOKEN missing).",category:"configuration",severity:"high",retriable:!1});const l=Wln(e);if(!l.trim())throw new De({code:He.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 mC(a,{model:this.modelName,input:c},{abortSignal:e.abortSignal})}catch(m){throw this.handleProviderError(m)}const d=Kln(u.output);if(!d)throw new Error(`Replicate prediction ${u.id} returned empty output`);const p={async*[Symbol.asyncIterator](){yield{content:d}}};return h.info(`[ReplicateProvider] Generated ${d.length} chars in ${Date.now()-r}ms \u2014 model ${this.modelName} (prediction ${u.id})`),{stream:p,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=nle(r),o=n.apiToken||this.apiToken,i=n.baseUrl||this.baseURL,s=ah({apiToken:o,baseUrl:i});if(!s)throw new De({code:He.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 De({code:He.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 mC(s,{model:this.modelName,input:c},{abortSignal:e.abortSignal})}catch(m){throw this.handleProviderError(m)}let d;try{d=await z3(u,Nm)}catch(m){throw this.handleProviderError(m)}const p=d.toString("base64");return h.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:p}}}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 De({code:He.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 De({code:He.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 De({code:He.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 De({code:He.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 De({code:He.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:ole(),baseURL:this.baseURL}}}}}),aJt={};Z(aJt,{RecraftProvider:()=>ale,default:()=>uJt});var lJt,ile,cJt,sle,ale,uJt,Xln=E({async"src/lib/providers/recraft.ts"(){"use strict";pl(),await tu(),Ln(),pt(),z(),Go(),Oa(),Fm(),xw(),lJt="https://external.api.recraft.ai/v1",ile=12e4,cJt=()=>_a(J4r()),sle=()=>Fi("RECRAFT_MODEL","recraftv3"),ale=class extends Ma{apiKey;baseURL;proxyFetch;constructor(e,t,r,n){const o=ch(t)?t:void 0;super(e,"recraft",o);const i=n?.apiKey?.trim();this.apiKey=i&&i.length>0?i:cJt(),this.baseURL=n?.baseURL??process.env.RECRAFT_BASE_URL??lJt,this.proxyFetch=Ot(),h.debug("Recraft Provider initialized (image-gen only)",{modelName:this.modelName,baseURL:this.baseURL})}getProviderName(){return this.providerName}getDefaultModel(){return sle()}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 Wr("Invalid Recraft API key. Get one at https://www.recraft.ai/api","recraft"):t.includes("429")||t.toLowerCase().includes("rate limit")?new Qi("Recraft rate limit exceeded. Back off and retry.","recraft"):t.includes("404")||t.includes("model_not_found")?new Jo(`Recraft model '${this.modelName}' not found. Use recraftv3, recraftv3-svg, or recraftv2.`,"recraft"):new ot(`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,i=e.prompt??e.input?.text??"";if(!i.trim())throw new Error("Recraft image generation requires a prompt (input.text or prompt)");const s=e,a={model:e.model??this.modelName,prompt:i,n:1,response_format:"b64_json"};s.negativePrompt&&(a.negative_prompt=s.negativePrompt),s.style&&(a.style=s.style),s.styleId&&(a.style_id=s.styleId),s.size&&(a.size=s.size);const l=new AbortController,c=setTimeout(()=>l.abort(),ile);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(g){throw g instanceof Error&&g.name==="AbortError"?this.formatProviderError(new Error(`Recraft image-gen request timed out after ${ile/1e3}s`)):this.formatProviderError(g)}finally{clearTimeout(c)}if(!u.ok){const g=await u.text();throw this.formatProviderError(new Error(`Recraft image-gen failed: ${u.status} \u2014 ${g}`))}const p=(await u.json()).data?.[0];if(!p)throw new Error("Recraft returned no image data");let m;if(p.b64_json)m=p.b64_json;else if(p.url)m=(await Lm(p.url,{label:"Recraft image",maxBytes:Nm,timeoutMs:6e4})).toString("base64");else throw new Error("Recraft response missing both b64_json and url");const f=Date.now()-t;return h.info(`[RecraftProvider] Generated image (${m.length} base64 chars) in ${f}ms \u2014 model ${this.modelName}`),{content:i,provider:this.providerName,model:this.modelName,usage:{input:0,output:1e3,total:1e3},imageOutput:{base64:m,mimeType:Xx(Buffer.from(m.slice(0,64),"base64"))}}}async validateConfiguration(){return typeof this.apiKey=="string"&&this.apiKey.trim().length>0}getConfiguration(){return{provider:this.providerName,model:this.modelName,defaultModel:sle(),baseURL:this.baseURL}}},uJt=ale}});function Yln(e){return ok(e)&&$M(e)===null?"video/mp4":yJt.every((t,r)=>e[r]===t)?"video/webm":null}function dJt(e,t,r){const n=t==="image"?Jx(e):Yln(e);return n===null?{status:"error",message:`${r} ${vJt[t]}.`}:{status:"ok",dataUrl:`data:${n};base64,${e.toString("base64")}`}}function lle(e){return e.length<=fJt?`(${e})`:`(a ${e.length}-character string)`}async function Zln(e,t,r){try{const n=await q4.stat(e);return n.isFile()?n.size>r?{status:"error",message:`${t} ${lle(e)} is ${n.size} bytes; a request may carry at most ${r}.`}:{status:"ok",buffer:await q4.readFile(e)}:{status:"error",message:`${t} ${lle(e)} is not a file.`}}catch(n){const o=n instanceof Error&&"code"in n?String(n.code):"unreadable";return{status:"error",message:`Could not read ${t} ${lle(e)}: ${o}.`}}}async function pJt(e,t,r,n){if(typeof e!="string")return e.length===0?{status:"error",message:`${r} is an empty Buffer.`}:dJt(e,t,r);const o=e.trim();if(o==="")return{status:"error",message:`${r} is an empty string.`};if(mJt.test(o))return{status:"error",message:`${r} is a remote URL. Media is not fetched for you; pass a Buffer, a file path or a data: URL.`};if(/^data:/i.test(o))return gJt[t].test(o)?{status:"ok",dataUrl:o}:{status:"error",message:`${r} is a data: URL that is not base64 ${t} content.`};if(hJt.test(o))return{status:"error",message:`${r} uses an unsupported URL scheme. Pass a Buffer, a file path or a data: URL.`};const i=await Zln(o,r,n);return i.status==="ok"?dJt(i.buffer,t,r):i}async function Qln(e,t,r,n){const o=e.images??[];if(o.length===0&&e.video===void 0)return{status:"prepared",media:void 0};if(!t){const l=n.length>0?` Use a decision provider that does: ${n.join(", ")}.`:"";return{status:"refused",message:`${r} does not accept images or video.${l}`}}if(o.length>t.maxImages)return{status:"refused",message:`${r} accepts at most ${t.maxImages} images per request; this one has ${o.length}.`};if(e.video!==void 0&&!t.video)return{status:"refused",message:`${r} does not accept video.`};const i=[];for(const[l,c]of o.entries()){const u=await pJt(c,"image",`Image ${l+1}`,t.maxRequestBytes);if(u.status==="error")return{status:"refused",message:u.message};i.push(u.dataUrl)}let s;if(e.video!==void 0){const l=await pJt(e.video,"video","The video",t.maxRequestBytes);if(l.status==="error")return{status:"refused",message:l.message};s=l.dataUrl}const a=i.reduce((l,c)=>l+c.length,s?.length??0);return{status:"prepared",media:{images:i,...s?{video:s}:{},bytes:a}}}var mJt,hJt,fJt,gJt,yJt,vJt,ecn=E({"src/lib/utils/decisionMedia.ts"(){"use strict";Sn(),xw(),UM(),mJt=/^https?:\/\//i,hJt=/^[a-z][a-z0-9+.-]*:\/\//i,fJt=200,gJt={image:/^data:image\/[a-z0-9.+-]+;base64,/i,video:/^data:video\/[a-z0-9.+-]+;base64,/i},yJt=[26,69,223,163],vJt={image:"is not a recognised image format",video:"is not a recognised video format (MP4, MOV or WebM)"}}});function wJt(e){const t=Object.values(e);return t.length>0?Math.max(...t):0}function tcn(e,t){if(!Pr(e))return null;switch(e.type){case"noul":case"boolean":{const r=sc(e.noul)??sc(e.probability);return r===void 0?null:{type:"boolean",probability:r}}case"choice":{const r=dle(e.probabilities);return typeof e.choice!="string"||!r?null:{type:"choice",choice:e.choice,confidence:sc(e.confidence)??t??wJt(r),probabilities:r}}case"score":{const r=sc(e.score),n=bJt(e.legend),o=dle(e.probabilities);return r===void 0||!n||!o?null:{type:"score",score:r,confidence:sc(e.confidence)??t??wJt(o),legend:n,probabilities:o}}default:return null}}function cle(e){return e.filter(Pr).map(r=>{const n=Array.isArray(r.loc)?r.loc.filter(i=>typeof i=="string"||typeof i=="number").join("."):"",o=typeof r.msg=="string"?r.msg:"invalid";return n?`${n}: ${o}`:o}).slice(0,5).join("; ")||"unspecified field"}function yC(e,t){return(t?e.split(t).join("[redacted]"):e).replace(/\.?\s*Received API Key\s*=[\s\S]*$/,"").replace(/\bsk-[A-Za-z0-9._-]+/g,"[redacted]").replace(/\b[0-9a-f]{32,}\b/gi,"[redacted]").replace(/data:[a-z]+\/[a-z0-9.+-]+;base64,[A-Za-z0-9+/=]+/gi,"[media]").trim()}function rcn(e,t,r={}){const{digit:n,symbol:o,astral:i}=r;if(t===void 0&&n===void 0&&o===void 0&&i===void 0)return Vt(e);const s=m=>m>="0"&&m<="9",a=m=>/[!-/:-@[-`{-~]/.test(m);let l=0,c=0,u=0,d=0;const p=[];for(const m of e){const f=m.codePointAt(0)??0;f>65535&&i!==void 0?u+=1:f>127?d+=1:n!==void 0&&s(m)?l+=1:o!==void 0&&a(m)?c+=1:p.push(m)}return Vt(p.join(""))+Math.ceil(l*(n??0))+Math.ceil(c*(o??0))+Math.ceil(u*(i??0))+Math.ceil(d*(t??1/xv))}var ule,TJt,Pr,sc,dle,bJt,ple,CT,vC=E({async"src/lib/providers/systemOneDecision.ts"(){"use strict";pl(),Fl(),await tu(),Ln(),pt(),ecn(),z(),Nt(),di(),ule=5e3,TJt=1,Pr=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),sc=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,dle=e=>{if(!Pr(e))return;const t={};for(const[r,n]of Object.entries(e)){const o=sc(n);if(o===void 0)return;t[r]=o}return t},bJt=e=>{if(!Pr(e))return;const t={};for(const[r,n]of Object.entries(e)){if(typeof n!="string")return;t[r]=n}return t},ple=(e,t)=>new Promise((r,n)=>{if(t?.aborted){n(t.reason);return}const o=setTimeout(()=>{t?.removeEventListener("abort",i),r()},e);function i(){clearTimeout(o),n(t?.reason)}t?.addEventListener("abort",i,{once:!0})}),CT=class extends Ma{proxyFetch;maxRetries;authFailed=!1;constructor(e,t,r){super(e,t,ch(r)?r:void 0),this.proxyFetch=Ot(),this.maxRetries=TJt}missingConfigMessage(){}encodeQuestion(e){return e.type==="boolean"?{type:"noul",instructions:e.instructions,...e.criteria?{criteria:e.criteria}:{}}:e}readRetryAfterMs(e){}defaultTimeoutMs(e){return this.getDescriptorDecideMs()}readDecisionPayload(e){return e}reportedConfidence(e){return{}}resolveResponseModel(e,t){return typeof e.model=="string"?e.model:t}diagnosticContext(){return{}}getProviderName(){return this.providerName}getDefaultDecisionModel(){return this.getDefaultModel()}supportsTools(){return!1}getAISDKModel(){throw new ot(`${this.vendorDisplayName()} is a decision-only provider; it generates no text, so chat completions are not available. Use \`decide()\` instead, or pick a different provider for \`generate()\` / \`stream()\`.`,this.providerName)}async executeStream(e,t){throw new ot(`${this.vendorDisplayName()} is a decision-only provider; streaming is not available. Use \`decide()\`, or pick another provider for \`stream()\`.`,this.providerName)}formatProviderError(e){if(e instanceof ot)return e;const t=e instanceof Error?e.message:String(e);return new ot(`${this.vendorLabel()} request failed: ${t}`,this.providerName)}async decide(e){const t=this.vendorLabel();if(!this.decisionApiKey())throw this.decisionError({kind:"authentication",message:this.missingKeyMessage(),retryable:!1});const r=this.missingConfigMessage();if(r)throw this.decisionError({kind:"invalid_request",message:r,retryable:!1});if(this.authFailed)throw this.decisionError({kind:"authentication",message:`${t} rejected this API key earlier; not retrying. Fix the key and construct a new provider.`,retryable:!1});const n=Object.entries(e.questions);if(n.length===0)throw this.decisionError({kind:"invalid_request",message:"At least one question is required.",retryable:!1});const o=e.model??this.modelName??this.getDefaultModel();this.assertWithinDecisionLimits(e,o,n.length);const i=Object.fromEntries(n.map(([u,d])=>[u,this.encodeQuestion(d)])),s=await this.prepareMedia(e),a=JSON.stringify(this.buildDecisionBody(e.state,i,o,s));this.assertWithinRequestBytes(a);const l=e.timeoutMs??this.defaultTimeoutMs(n.length)??this.defaultTimeout??ule;let c;for(let u=0;u<=this.maxRetries;u++){const d=Date.now();try{const p=AbortSignal.timeout(l),m=e.signal?AbortSignal.any([e.signal,p]):p,f=await this.proxyFetch(this.decisionEndpoint(o),{method:"POST",headers:this.decisionHeaders(),body:a,signal:m}),g=Date.now()-d,y=this.readRequestId(f.headers),v=Number(f.headers.get("x-envoy-upstream-service-time"))||void 0,T=await f.json().catch(()=>null);if(!f.ok){if(c=this.parseDecisionError(f.status,T,y),c.kind==="authentication"&&(this.authFailed=!0,h.warn(`${t}: credential not accepted \u2014 disabling this provider instance. ${c.message}`,{status:c.status,...this.diagnosticContext(),requestId:y})),!c.retryable||u===this.maxRetries)throw this.decisionError(c);const x=this.readRetryAfterMs(f.headers);if(x!==void 0&&x>l-(Date.now()-d))throw this.decisionError(c);await ple(x??2**u*250+Math.random()*250,e.signal);continue}const b=this.readDecisionPayload(T);if(!Pr(b)||!Pr(b.answers))throw this.decisionError({kind:"server",message:`${t} returned a response without an answers map.`,status:f.status,requestId:y,retryable:!1});const S=this.reportedConfidence(b),k={};for(const[x,P]of Object.entries(b.answers)){const C=tcn(P,S[x]);C?k[x]=C:h.warn(`${t}: dropped unparseable answer "${x}"`,{requestId:y})}const A=Pr(b.usage)?b.usage:{};return{model:this.resolveResponseModel(b,o),provider:this.providerName,answers:k,usage:{inputTokens:sc(A.input_tokens)??sc(A.inputTokens)??0,outputTokens:sc(A.output_tokens)??sc(A.outputTokens)??0},requestId:y,latencyMs:g,upstreamMs:v,...s?{mediaBytes:s.bytes}:{}}}catch(p){if(p instanceof ot)throw p;const m=e.signal?.aborted===!0,f=p instanceof Error&&p.name==="TimeoutError";if(c={kind:m?"network":f?"timeout":"network",message:yC(dE(p instanceof Error?p.message:String(p)),this.decisionApiKey()),retryable:!m},m||u===this.maxRetries)throw this.decisionError(c);await ple(2**u*250+Math.random()*250)}}throw this.decisionError(c??{kind:"network",message:`${t} request failed.`,retryable:!1})}async prepareMedia(e){const t=hr.get(this.providerName)?.decisionLimits,r=await Qln(e,t?.media,this.vendorLabel(),oPr({video:e.video!==void 0}));if(r.status==="refused")throw this.decisionError({kind:"invalid_request",message:r.message,retryable:!1});return r.media}assertWithinRequestBytes(e){const t=hr.get(this.providerName)?.decisionLimits?.media,r=t?.maxRequestBytes;if(r===void 0)return;const n=Buffer.byteLength(e);if(n>r)throw this.decisionError({kind:"invalid_request",message:`The request is ${n} bytes; ${this.vendorLabel()} accepts at most ${r}. Send fewer or smaller images${t?.video?", or a shorter video":""}.`,retryable:!1})}assertWithinDecisionLimits(e,t,r){const n=hr.get(this.providerName)?.decisionLimits;if(!n)return;const o=this.vendorLabel();if(n.maxQuestions!==void 0&&r>n.maxQuestions)throw this.decisionError({kind:"max_tokens_exceeded",message:`${o} accepts at most ${n.maxQuestions} questions per request; this one has ${r}. Ask fewer, or use a decision provider without this cap.`,retryable:!1});const i=n.models?.[t],s=i?.maxStateTokens??n.maxStateTokens,a=rcn(xk(e.state),i?.nonAsciiTokensPerChar??n.nonAsciiTokensPerChar,{digit:n.digitTokensPerChar,symbol:n.symbolTokensPerChar,astral:n.astralTokensPerChar});if(a>s)throw this.decisionError({kind:"max_tokens_exceeded",message:`The state is ~${a} tokens; ${o}'s "${t}" model reads at most ${s}. Shorten the state, or use a decision provider with a larger window.`,retryable:!1})}decisionError(e){const t=new ot(e.message,this.providerName);return Object.defineProperty(t,"cause",{value:e,enumerable:!1,writable:!0,configurable:!0}),t}}}}),_Jt={};Z(_Jt,{TYPESAFE_MAX_REQUEST_TOKENS:()=>aF,TYPESAFE_MAX_STATE_TOKENS:()=>sF,TypeSafeProvider:()=>RJt});function ncn(e){if(!Pr(e)||!Pr(e.providerMetadata))return{};const t=e.providerMetadata.typesafe;if(!Pr(t)||!Pr(t.confidence))return{};const r={};for(const[n,o]of Object.entries(t.confidence)){const i=sc(o);i!==void 0&&(r[n]=i)}return r}function ocn(e,t,r,n){const o=typeof t.type=="string"?t.type:void 0,i=(o?IJt[o]:void 0)??(e===401||e===403?"authentication":e===429?"rate_limit":e>=500?"server":"invalid_request"),s=typeof t.message=="string"&&t.message.length>0?t.message:o??`AI Gateway request failed with HTTP ${e}`;return{kind:i,message:s,status:e,requestId:r,retryable:n}}function EJt(e,t,r){const n=e===429||e===529||e>=500,o=Pr(t)&&Pr(t.error)?t.error:void 0;if(o)return ocn(e,o,r,n);const i=Pr(t)?t.detail:void 0;if(Array.isArray(i))return{kind:"invalid_request",message:`Request failed validation \u2014 ${cle(i)}`,status:e,requestId:r,retryable:!1};const s=Pr(i)&&typeof i.error_type=="string"?i.error_type:void 0,a=s==="max_tokens_exceeded"?"max_tokens_exceeded":e===401||e===403?"authentication":e===429?"rate_limit":e===529?"overloaded":e>=500?"server":"invalid_request",l=a==="max_tokens_exceeded"?`State plus questions exceeded the model's input limit: keep state plus the longest single question under ~${sF} tokens, and state plus all questions under ~${aF}.`:s??`TypeSafe request failed with HTTP ${e}`,c=Pr(i)&&typeof i.message=="string"?i.message:l;return{kind:a,message:c,status:e,requestId:r,retryable:n}}var SJt,kJt,xJt,AJt,CJt,sF,aF,IJt,RJt,PJt=E({async"src/lib/providers/typesafe.ts"(){"use strict";z(),Nt(),Go(),await vC(),SJt="https://api.typesafe.ai",kJt="https://ai-gateway.vercel.sh/v4/ai/evaluation-model",xJt="typesafe-ai/jev",AJt="0.0.1",CJt="4",sF=33e3,aF=64e3,IJt={authentication_error:"authentication",customer_verification_required:"authentication",invalid_request_error:"invalid_request",rate_limit_exceeded:"rate_limit",internal_server_error:"server"},RJt=class extends CT{apiKey;baseURL;gatewayURL;transport;constructor(e,t,r,n){super(e,"typesafe",t);const o=n?.apiKey?.trim()||(process.env.TYPESAFE_API_KEY?.trim()??""),i=n?.gatewayApiKey?.trim()||(process.env.AI_GATEWAY_API_KEY?.trim()??""),s=n?.transport??process.env.TYPESAFE_TRANSPORT?.trim();this.transport=s==="gateway"||s==="direct"?s:!o&&i?"gateway":"direct",this.apiKey=this.transport==="gateway"?i:o,this.baseURL=(n?.baseURL??process.env.TYPESAFE_BASE_URL??SJt).replace(/\/+$/,""),this.gatewayURL=(n?.gatewayURL?.trim()||process.env.TYPESAFE_GATEWAY_URL?.trim()||kJt).replace(/\/+$/,""),h.debug("TypeSafe Provider initialized (decide only)",{modelName:this.modelName,transport:this.transport,baseURL:Xt(this.transport==="gateway"?this.gatewayURL:this.baseURL)})}getDefaultModel(){return Fi("TYPESAFE_MODEL","jev-latest")}vendorLabel(){return"TypeSafe"}vendorDisplayName(){return"TypeSafe (Jev)"}decisionApiKey(){return this.apiKey}missingKeyMessage(){return this.transport==="gateway"?"The TypeSafe gateway transport requires a Vercel AI Gateway key. Set AI_GATEWAY_API_KEY or pass credentials.typesafe.gatewayApiKey.":"TypeSafe requires an API key. Set TYPESAFE_API_KEY or pass credentials.typesafe.apiKey."}encodeQuestion(e){return this.transport==="gateway"?e:super.encodeQuestion(e)}buildDecisionBody(e,t,r){return this.transport==="gateway"?{state:e,questions:t}:{model:r,state:e,questions:t}}parseDecisionError(e,t,r){return EJt(e,t,r)}reportedConfidence(e){return ncn(e)}readRequestId(e){return e.get("x-typesafe-request-id")??void 0}diagnosticContext(){return{transport:this.transport}}decisionEndpoint(){return this.transport==="gateway"?this.gatewayURL:`${this.baseURL}/v1/systemone`}decisionHeaders(){const e={Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json"};return this.transport==="gateway"?{...e,"ai-gateway-auth-method":"api-key","ai-gateway-protocol-version":AJt,"ai-model-id":xJt,"ai-evaluation-model-specification-version":CJt}:e}getDecisionTransport(){return this.transport}async listDecisionModels(){if(this.transport==="gateway")throw this.decisionError({kind:"invalid_request",message:"Model listing is a TypeSafe API operation; the gateway transport has no equivalent endpoint.",retryable:!1});const e=await this.proxyFetch(`${this.baseURL}/v1/models`,{headers:{Authorization:`Bearer ${this.apiKey}`},signal:AbortSignal.timeout(this.defaultTimeout??ule)}),t=await e.json().catch(()=>null);if(!e.ok)throw this.decisionError(EJt(e.status,t,e.headers.get("x-typesafe-request-id")??void 0));return(Pr(t)&&Array.isArray(t.models)?t.models:[]).filter(Pr).map(n=>({name:typeof n.name=="string"?n.name:"",description:typeof n.description=="string"?n.description:"",releaseDate:typeof n.release_date=="string"?n.release_date:""}))}}}}),MJt={};Z(MJt,{LayaProvider:()=>OJt});function icn(e,t,r){const n=e===429||e>=500,o=e===401||e===403?"authentication":e===413?"max_tokens_exceeded":e===429?"rate_limit":e===503?"overloaded":e>=500?"server":"invalid_request",i=Pr(t)&&Pr(t.error)?t.error:void 0;if(i&&typeof i.message=="string"&&i.message.length>0)return{kind:o,message:i.message,status:e,requestId:r,retryable:n};const s=Pr(t)?t.detail:void 0;return Array.isArray(s)?{kind:"invalid_request",message:`Request failed validation \u2014 ${cle(s)}`,status:e,requestId:r,retryable:!1}:typeof s=="string"&&s.length>0?{kind:o,message:s,status:e,requestId:r,retryable:n}:{kind:o,message:`Laya request failed with HTTP ${e}`,status:e,requestId:r,retryable:n}}var OJt,scn=E({async"src/lib/providers/laya.ts"(){"use strict";z(),Nt(),Go(),await vC(),OJt=class extends CT{apiKey;baseURL;constructor(e,t,r,n){super(e,"laya",t),this.apiKey=n?.apiKey?.trim()||(process.env.LAYA_API_KEY?.trim()??""),this.baseURL=(n?.baseURL?.trim()||process.env.LAYA_BASE_URL?.trim()||"").replace(/\/+$/,""),h.debug("Laya Provider initialized (decide only)",{modelName:this.modelName,baseURL:this.baseURL?Xt(this.baseURL):"(not set)"})}getDefaultModel(){return Fi("LAYA_MODEL","typed-decisions")}vendorLabel(){return"Laya"}vendorDisplayName(){return"Laya"}decisionApiKey(){return this.apiKey}missingKeyMessage(){return"Laya requires an API key. Set LAYA_API_KEY or pass credentials.laya.apiKey."}missingConfigMessage(){return this.baseURL?void 0:"Laya requires a base URL. Set LAYA_BASE_URL or pass credentials.laya.baseURL."}decisionEndpoint(){return`${this.baseURL}/predict`}decisionHeaders(){return{Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json"}}buildDecisionBody(e,t,r){return r==="auto"?{state:e,questions:t}:{model:r,state:e,questions:t}}parseDecisionError(e,t,r){const n=icn(e,t,r),o=yC(n.message,this.apiKey);return{...n,message:o||`Laya request failed with HTTP ${e}`}}readRequestId(e){return e.get("x-litellm-call-id")??void 0}resolveResponseModel(e,t){const r=e.routing;return Pr(r)&&typeof r.model=="string"?r.model:super.resolveResponseModel(e,t)}}}}),DJt={};Z(DJt,{XorProvider:()=>FJt});function acn(e){return e.replace(/\/+$/,"").replace(/\/v1$/i,"")}function lcn(e){const t="Set XOR_BASE_URL or pass credentials.xor.baseURL to the origin, and give the key through XOR_API_KEY or credentials.xor.apiKey.";try{const r=new URL(e);return r.protocol!=="https:"&&r.protocol!=="http:"?`The XOR base URL must start with https:// or http://. ${t}`:r.username||r.password||r.search||r.hash?`The XOR base URL must not carry credentials, a query string or a fragment. ${t}`:void 0}catch{return`The XOR base URL is not a valid absolute URL. ${t}`}}function ccn(e,t){return e===401?"authentication":e===413?"max_tokens_exceeded":e===429?"rate_limit":e===503?"overloaded":e>=500?LJt.test(t)?"max_tokens_exceeded":"server":"invalid_request"}function ucn(e){if(!Pr(e))return;const{error:t,detail:r}=e;return Pr(t)&&typeof t.message=="string"&&t.message.length>0?t.message:typeof t=="string"&&t.length>0?t:Array.isArray(r)?`Request failed validation \u2014 ${cle(r)}`:typeof r=="string"&&r.length>0?r:void 0}var NJt,LJt,FJt,dcn=E({async"src/lib/providers/xor.ts"(){"use strict";z(),Nt(),Go(),await vC(),NJt="/v1/systemone",LJt=/(context|prefill|prompt).{0,40}(length|limit|too long|exceed)|(too long|exceeds?).{0,40}(context|tokens)/i,FJt=class extends CT{apiKey;baseURL;constructor(e,t,r,n){super(e,"xor",t),this.apiKey=n?.apiKey?.trim()||(process.env.XOR_API_KEY?.trim()??""),this.baseURL=acn(n?.baseURL?.trim()||process.env.XOR_BASE_URL?.trim()||""),h.debug("XOR Provider initialized (decide only)",{modelName:this.modelName,baseURL:this.baseURL?Xt(this.baseURL):"(not set)"})}getDefaultModel(){return Fi("XOR_MODEL","xor-1.1")}vendorLabel(){return"XOR"}vendorDisplayName(){return"XOR"}decisionApiKey(){return this.apiKey}missingKeyMessage(){return"XOR requires an API key. Set XOR_API_KEY or pass credentials.xor.apiKey."}missingConfigMessage(){return this.baseURL?lcn(this.baseURL):"XOR requires a base URL. Set XOR_BASE_URL or pass credentials.xor.baseURL."}decisionEndpoint(){return`${this.baseURL}${NJt}`}decisionHeaders(){return{Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json"}}buildDecisionBody(e,t,r,n){return{model:r,state:e,questions:t,...n&&n.images.length>0?{images:n.images}:{},...n?.video?{video:n.video}:{}}}parseDecisionError(e,t,r){const n=`XOR request failed with HTTP ${e}`,o=yC(ucn(t)??n,this.apiKey)||n,i=ccn(e,o);return{kind:i,message:o,status:e,requestId:r,retryable:i==="rate_limit"||i==="overloaded"||i==="server"}}readRequestId(e){return e.get("x-request-id")??e.get("x-typesafe-request-id")??e.get("x-litellm-call-id")??void 0}}}}),$Jt={};Z($Jt,{PerplexityDeciderProvider:()=>WJt});function pcn(e){return e.replace(/\/+$/,"").replace(/\/v1$/i,"")}function UJt(e){const t=`Set PERPLEXITY_DECIDER_BASE_URL or pass credentials.perplexityDecider.baseURL to an origin, or leave both unset to use ${mle}.`;try{const r=new URL(e);return r.protocol!=="https:"&&r.protocol!=="http:"?`The Perplexity base URL must start with https:// or http://. ${t}`:r.username||r.password||r.search||r.hash?`The Perplexity base URL must not carry credentials, a query string or a fragment. ${t}`:void 0}catch{return`The Perplexity base URL is not a valid absolute URL. ${t}`}}function mcn(e){try{return new URL(e).hostname===GJt}catch{return!1}}function hcn(e,t){return e===401?"authentication":e===413||e===400&&HJt.test(t)?"max_tokens_exceeded":e===429?"rate_limit":e===503?"overloaded":e>=500?"server":"invalid_request"}function fcn(e){if(!Pr(e)||!Pr(e.error))return;const{message:t,param:r}=e.error;if(!(typeof t!="string"||t.length===0))return typeof r=="string"&&r!==""&&!t.includes(r)?`${t} (field: ${r})`:t}function gcn(e){return e.length>=24&&e.toString("ascii",12,16)==="IHDR"?{width:e.readUInt32BE(16),height:e.readUInt32BE(20)}:void 0}function ycn(e){let t=2;for(;t+4<=e.length;){if(e[t]!==255)return;const r=e[t+1];if(r===255)t+=1;else if(r===1||r>=208&&r<=216)t+=2;else{if(r===217||r===218)return;if(r>=192&&r<=207&&r!==196&&r!==200&&r!==204)return t+9<=e.length?{height:e.readUInt16BE(t+5),width:e.readUInt16BE(t+7)}:void 0;t+=2+e.readUInt16BE(t+2)}}}function vcn(e){if(!(e.length<30))switch(e.toString("ascii",12,16)){case"VP8X":return{width:1+e.readUIntLE(24,3),height:1+e.readUIntLE(27,3)};case"VP8L":{const t=e.readUInt32LE(21);return e[20]===47?{width:(t&16383)+1,height:(t>>>14&16383)+1}:void 0}case"VP8 ":return{width:e.readUInt16LE(26)&16383,height:e.readUInt16LE(28)&16383};default:return}}function wcn(e){switch(Jx(e)){case"image/png":return gcn(e);case"image/jpeg":return ycn(e);case"image/webp":return vcn(e);default:return}}function Tcn(e,t){const r=/^data:([a-z]+\/[a-z0-9.+-]+);base64,/i.exec(e);if(!r||!VJt.has(r[1].toLowerCase()))return`Image ${t} is not a PNG, JPEG or WebP image, the only formats Perplexity reads.`;const n=wcn(Buffer.from(e.slice(r[0].length),"base64"));return n&&Math.round(n.width/wC)*Math.round(n.height/wC)>hle?`Image ${t} is ${n.width}x${n.height} pixels; Perplexity reads at most ${hle} tiles of ${wC}x${wC} pixels per image (1440x1440 and 2048x1024 fit), and a larger one stalls until the request times out. Resize it first.`:void 0}function BJt(e){return typeof e=="number"||typeof e=="boolean"?String(e):e}var mle,zJt,GJt,qJt,VJt,wC,hle,jJt,HJt,WJt,bcn=E({async"src/lib/providers/perplexityDecider.ts"(){"use strict";xw(),z(),Nt(),Go(),await vC(),mle="https://api.perplexity.ai",zJt="/v1/decisions",GJt="api.perplexity.ai",qJt="neurolink",VJt=new Set(["image/png","image/jpeg","image/webp"]),wC=32,hle=2048,jJt=100,HJt=/exceeds(?: or equals)?(?: model's)? maximum context length/i,WJt=class extends CT{apiKey;baseURL;constructor(e,t,r,n){super(e,"perplexity-decider",t),this.apiKey=n?.apiKey?.trim()||(process.env.PERPLEXITY_API_KEY?.trim()??""),this.baseURL=pcn(n?.baseURL?.trim()||process.env.PERPLEXITY_DECIDER_BASE_URL?.trim()||mle),h.debug("Perplexity decision provider initialized (decide only)",{modelName:this.modelName,baseURL:UJt(this.baseURL)?"(invalid)":Xt(this.baseURL)})}getDefaultModel(){return Fi("PERPLEXITY_DECIDER_MODEL","pplx-decider-v1-27b")}vendorLabel(){return"Perplexity"}vendorDisplayName(){return"Perplexity Decisions"}decisionApiKey(){return this.apiKey}missingKeyMessage(){return"Perplexity requires an API key. Set PERPLEXITY_API_KEY or pass credentials.perplexityDecider.apiKey."}missingConfigMessage(){return UJt(this.baseURL)}decisionEndpoint(){return`${this.baseURL}${zJt}`}decisionHeaders(){return{Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json",...mcn(this.baseURL)?{"X-Pplx-Integration":qJt}:{}}}buildDecisionBody(e,t,r,n){const o=n?.images??[];if(o.length===0)return{model:r,state:BJt(e),questions:t};o.forEach((s,a)=>{const l=Tcn(s,a+1);if(l)throw this.decisionError({kind:"invalid_request",message:l,retryable:!1})});const i=Array.isArray(e)?e:e===""?[]:[BJt(e)];return{model:r,state:[...i,...o.map(s=>({type:"image_url",image_url:{url:s}}))],questions:t}}parseDecisionError(e,t,r){const n=`Perplexity request failed with HTTP ${e}`,o=yC(fcn(t)??n,this.apiKey).replace(/\bpplx-[A-Za-z0-9_-]{30,}/g,"[redacted]").trim()||n,i=hcn(e,o);return{kind:i,message:o,status:e,requestId:r,retryable:i==="rate_limit"||i==="overloaded"||i==="server"}}readRequestId(e){return e.get("x-request-id")??void 0}defaultTimeoutMs(e){const t=this.getDescriptorDecideMs();return t===void 0?void 0:t+e*jJt}readRetryAfterMs(e){const t=e.get("retry-after")?.trim();if(!t)return;const r=/^\d+$/.test(t)?Number(t)*1e3:Date.parse(t)-Date.now();return Number.isFinite(r)&&r>0?Math.ceil(r):void 0}}}}),KJt={};Z(KJt,{CloudflareClefProvider:()=>nXt});function _cn(e){return e.replace(/\/+$/,"")}function JJt(e){const t=`Set CLOUDFLARE_CLEF_BASE_URL or pass credentials.cloudflareClef.baseURL to a base URL, or leave both unset to use ${fle}.`;try{const r=new URL(e);return r.protocol!=="https:"&&r.protocol!=="http:"?`The Cloudflare base URL must start with https:// or http://. ${t}`:r.username||r.password||r.search||r.hash||/[?#]/.test(e)?`The Cloudflare base URL must not carry credentials, a query string or a fragment. ${t}`:void 0}catch{return`The Cloudflare base URL is not a valid absolute URL. ${t}`}}function XJt(e){const t=e.trim().replace(/^@cf\/cloudflare\//i,"");return/^[a-z0-9][a-z0-9._-]*$/i.test(t)?t.toLowerCase():void 0}function Ecn(e,t){const r=/^data:([a-z]+\/[a-z0-9.+-]+);base64,/i.exec(e)?.[1]?.toLowerCase();return r&&QJt.has(r)?void 0:`Image ${t} is not a PNG, JPEG or WebP image, the only formats Cloudflare Clef reads.`}function Scn(e){return typeof e=="number"||typeof e=="boolean"?String(e):e}function kcn(e){if(!Pr(e)||!Array.isArray(e.errors))return;const t=e.errors.find(Pr);if(!t||typeof t.message!="string"||t.message==="")return;let r=t.message.slice(0,rXt).trimEnd(),n;const o=eXt.exec(r);if(o&&(n=o[1],r=r.slice(0,o.index).trimEnd()),r=r.replace(/^(?:AiError:\s*|Ai:\s*)+/,"").trim(),r.startsWith("{"))try{const i=JSON.parse(r);if(Pr(i)&&Pr(i.error)){const s=Pr(i.error.details)?i.error.details:void 0,a=Pr(s?.fieldErrors)?Object.entries(s.fieldErrors).flatMap(([c,u])=>Array.isArray(u)?u.filter(d=>typeof d=="string").map(d=>`${c}: ${d}`):[]):[],l=typeof i.error.message=="string"?i.error.message:r;r=a.length>0?`${l}: ${a.join("; ")}`:l}}catch{}return{message:r,code:typeof t.code=="number"?t.code:void 0,requestId:n}}function xcn(e,t){return e===401?"authentication":e===413||t===5021?"max_tokens_exceeded":e===429?"rate_limit":e===503?"overloaded":e>=500?"server":"invalid_request"}var fle,YJt,ZJt,QJt,eXt,tXt,rXt,nXt,Acn=E({async"src/lib/providers/cloudflareClef.ts"(){"use strict";z(),Nt(),Go(),await vC(),fle="https://api.cloudflare.com/client/v4",YJt="@cf/cloudflare/",ZJt=/^[A-Za-z0-9_-]{1,64}$/,QJt=new Set(["image/png","image/jpeg","image/webp"]),eXt=/\(([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\)\s*$/i,tXt=500,rXt=4096,nXt=class extends CT{apiKey;accountId;baseURL;constructor(e,t,r,n){super(e,"cloudflare-clef",t);const o=!!n?.baseURL?.trim();this.apiKey=n?.apiKey?.trim()||(o?"":process.env.CLOUDFLARE_API_KEY?.trim()??""),this.accountId=n?.accountId?.trim()||(process.env.CLOUDFLARE_ACCOUNT_ID?.trim()??""),this.baseURL=_cn(n?.baseURL?.trim()||process.env.CLOUDFLARE_CLEF_BASE_URL?.trim()||fle),h.debug("Cloudflare Clef decision provider initialized (decide only)",{modelName:this.modelName,baseURL:JJt(this.baseURL)?"(invalid)":Xt(this.baseURL),accountConfigured:this.accountId!==""})}getDefaultModel(){return Fi("CLOUDFLARE_CLEF_MODEL","clef")}vendorLabel(){return"Cloudflare"}vendorDisplayName(){return"Cloudflare Clef"}decisionApiKey(){return this.apiKey}missingKeyMessage(){return"Cloudflare Clef requires an API token with Workers AI permission. Set CLOUDFLARE_API_KEY or pass credentials.cloudflareClef.apiKey."}missingConfigMessage(){return this.accountId===""?"Cloudflare Clef requires the account id. Set CLOUDFLARE_ACCOUNT_ID or pass credentials.cloudflareClef.accountId.":ZJt.test(this.accountId)?JJt(this.baseURL):"The Cloudflare account id may contain only letters, digits, '-' and '_'. Copy it from the Cloudflare dashboard."}decisionEndpoint(e){return`${this.baseURL}/accounts/${encodeURIComponent(this.accountId)}/ai/run/${YJt}${encodeURIComponent(XJt(e)??e)}`}decisionHeaders(){return{Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json"}}buildDecisionBody(e,t,r,n){const o=XJt(r);if(!o)throw this.decisionError({kind:"invalid_request",message:`"${r.slice(0,40)}" is not a Cloudflare model name. Use "clef" or "clef-flash".`,retryable:!1});const i=(n?.images??[]).map(s=>s.replace(/^data:image\/jpg;base64,/i,"data:image/jpeg;base64,"));return i.forEach((s,a)=>{const l=Ecn(s,a+1);if(l)throw this.decisionError({kind:"invalid_request",message:l,retryable:!1})}),n&&(n.images=i,n.bytes=i.reduce((s,a)=>s+Buffer.byteLength(a),0)),{model:o,state:Scn(e),questions:t,...i.length>0?{images:i}:{}}}readDecisionPayload(e){return Pr(e)&&Pr(e.result)?e.result:e}parseDecisionError(e,t,r){const n=`Cloudflare request failed with HTTP ${e}`,o=kcn(t),i=xcn(e,o?.code);let s=yC(o?.message??n,this.apiKey).trim().slice(0,tXt)||n;return i==="max_tokens_exceeded"?s+=" Cloudflare counts the whole request, image data included, at about four characters per token.":o?.code===7e3&&(s+='. Check the model name (Clef is served as "clef" and "clef-flash") and the base URL, which must end in /client/v4 and name your account.'),{kind:i,message:s,status:e,requestId:r??o?.requestId,retryable:i==="rate_limit"||i==="overloaded"||i==="server"}}readRequestId(e){return e.get("cf-ai-req-id")??e.get("cf-ray")??void 0}}}}),oXt={};Z(oXt,{Agent:()=>WXt,BedrockClient:()=>sXt,BedrockRuntimeClient:()=>lXt,Blob:()=>HXt,Client:()=>JXt,ConverseCommand:()=>cXt,ConverseStreamCommand:()=>uXt,Cron:()=>CXt,Dispatcher:()=>XXt,File:()=>jXt,FlowProducer:()=>AXt,FormData:()=>VXt,GoogleAuth:()=>gXt,HTTPException:()=>NXt,Headers:()=>qXt,Hippocampus:()=>TXt,HippocampusConfig:()=>bXt,Hono:()=>OXt,ImageFormat:()=>dXt,InvokeEndpointCommand:()=>hXt,InvokeEndpointWithResponseStreamCommand:()=>fXt,InvokeModelCommand:()=>pXt,Job:()=>kXt,ListFoundationModelsCommand:()=>aXt,MockAgent:()=>QXt,Pool:()=>KXt,Queue:()=>EXt,QueueScheduler:()=>xXt,Request:()=>zXt,Response:()=>GXt,SageMakerRuntimeClient:()=>mXt,TextToSpeechClient:()=>vXt,VertexAI:()=>yXt,Webhook:()=>wXt,Worker:()=>SXt,convertToHtml:()=>MXt,cors:()=>DXt,createClient:()=>_Xt,default:()=>iXt,extractRawText:()=>PXt,fetch:()=>BXt,getGlobalDispatcher:()=>ZXt,interceptors:()=>eYt,logger:()=>LXt,parseBuffer:()=>IXt,request:()=>tYt,secureHeaders:()=>FXt,selectCover:()=>RXt,setGlobalDispatcher:()=>YXt,streamSSE:()=>$Xt,timeout:()=>UXt});var y0,Ri,iXt,sXt,aXt,lXt,cXt,uXt,dXt,pXt,mXt,hXt,fXt,gXt,yXt,vXt,wXt,TXt,bXt,_Xt,EXt,SXt,kXt,xXt,AXt,CXt,IXt,RXt,PXt,MXt,OXt,DXt,NXt,LXt,FXt,$Xt,UXt,BXt,zXt,GXt,qXt,VXt,jXt,HXt,WXt,KXt,JXt,XXt,YXt,ZXt,QXt,eYt,tYt,Ccn=E({"npm-stub:@google-cloud/text-to-speech"(){y0={get(e,t){return t==="__esModule"?!0:t==="default"?new Proxy({},{get:y0.get}):new Proxy(function(...r){return new Proxy({},{get:y0.get})},{get:y0.get,apply(r,n,o){return new Proxy({},{get:y0.get})},construct(r,n){return new Proxy({},{get:y0.get})}})}},Ri=new Proxy({},y0),iXt=Ri,{BedrockClient:sXt,ListFoundationModelsCommand:aXt,BedrockRuntimeClient:lXt,ConverseCommand:cXt,ConverseStreamCommand:uXt,ImageFormat:dXt,InvokeModelCommand:pXt}=Ri,{SageMakerRuntimeClient:mXt,InvokeEndpointCommand:hXt,InvokeEndpointWithResponseStreamCommand:fXt}=Ri,{GoogleAuth:gXt,VertexAI:yXt,TextToSpeechClient:vXt}=Ri,{Webhook:wXt}=Ri,{Hippocampus:TXt,HippocampusConfig:bXt}=Ri,{createClient:_Xt}=Ri,{Queue:EXt,Worker:SXt,Job:kXt,QueueScheduler:xXt,FlowProducer:AXt}=Ri,{Cron:CXt}=Ri,{parseBuffer:IXt,selectCover:RXt}=Ri,{extractRawText:PXt,convertToHtml:MXt}=Ri,{Hono:OXt}=Ri,{cors:DXt,HTTPException:NXt,logger:LXt,secureHeaders:FXt,streamSSE:$Xt,timeout:UXt}=Ri,BXt=globalThis.fetch,zXt=globalThis.Request,GXt=globalThis.Response,qXt=globalThis.Headers,VXt=globalThis.FormData,jXt=globalThis.File,HXt=globalThis.Blob,WXt=Ri.Agent,KXt=Ri.Pool,JXt=Ri.Client,XXt=Ri.Dispatcher,YXt=()=>{},ZXt=()=>Ri,QXt=Ri.MockAgent,eYt={redirect:()=>e=>e,retry:()=>e=>e},tYt=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()}}}}}),lF,rYt=E({"src/lib/adapters/tts/googleTTSHandler.ts"(){"use strict";al(),z(),pv(),No(),lF=class fd{client=null;voicesCache=null;static CACHE_TTL_MS=300*1e3;static DEFAULT_MAX_TEXT_LENGTH=5e3;static DEFAULT_API_TIMEOUT_MS=30*1e3;maxTextLength=fd.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(()=>(Ccn(),oXt));this.client=new t({keyFilename:this.credentialsPath})}return this.client}async getVoices(t){if(!this.isConfigured())throw new ft({code:Tt.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=Me.createSpan("tts","tts.google.listVoices",{"tts.operation":"listVoices","tts.provider":"google"});try{if(this.voicesCache&&Date.now()-this.voicesCache.timestamp<fd.CACHE_TTL_MS&&!t){const a=Me.endSpan(n,1);return it().recordSpan(a),this.voicesCache.voices}const[o]=await r.listVoices(t?{languageCode:t}:{});if(!o.voices||o.voices.length===0){h.warn("Google Cloud TTS returned no voices");const a=Me.endSpan(n,1);return it().recordSpan(a),[]}const i=[];for(const a of o.voices??[]){if(!a.name||!Array.isArray(a.languageCodes)||a.languageCodes.length===0){h.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),p=a.ssmlGender==="MALE"?"male":a.ssmlGender==="FEMALE"?"female":"neutral";i.push({id:l,name:l,languageCode:u,languageCodes:c,gender:p,type:d,naturalSampleRateHertz:a.naturalSampleRateHertz??void 0})}t||(this.voicesCache={voices:i,timestamp:Date.now()});const s=Me.endSpan(n,1);return it().recordSpan(s),i}catch(o){const i=Me.endSpan(n,2,o instanceof Error?o.message:"Unknown error");it().recordSpan(i);const s=o instanceof Error?o.message:"Unknown error";return h.error(`Failed to fetch Google TTS voices: ${s}`),[]}}async synthesize(t,r){if(!this.isConfigured())throw new ft({code:Tt.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",i=Me.createSpan("tts","tts.google.synthesize",{"tts.operation":"synthesize","tts.provider":"google","tts.voice":o,"tts.format":r.format??"mp3"}),s=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 ft({code:Tt.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:fd.DEFAULT_API_TIMEOUT_MS}),p=d.audioContent;if(!p)throw new ft({code:Tt.SYNTHESIS_FAILED,message:"Google TTS returned empty audio content",category:"execution",severity:"high",retriable:!0});const m=p instanceof Uint8Array?Buffer.from(p):typeof p=="string"?Buffer.from(p,"base64"):(()=>{throw new ft({code:Tt.SYNTHESIS_FAILED,message:"Unsupported audioContent type returned by Google TTS",category:"execution",severity:"high",retriable:!0,context:{type:typeof p}})})(),f=Date.now()-s,g=Me.endSpan(i,1);return it().recordSpan(g),{buffer:m,format:r.format??"mp3",size:m.length,voice:o,metadata:{latency:f,provider:"google-ai"}}}catch(a){const l=Me.endSpan(i,2,a instanceof Error?a.message:String(a));if(it().recordSpan(l),a instanceof ft)throw a;const c=Date.now()-s,u=a instanceof Error?a.message:"Unknown error";throw new ft({code:Tt.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})}}static STREAMING_VOICE_PATTERN=/^[a-z]{2,3}-[A-Z]{2}-(?:Chirp3-HD|Chirp-HD|Journey)-/;static STREAMING_SAMPLE_RATE_HZ=24e3;static STREAMING_IDLE_TIMEOUT_MS=30*1e3;static mapStreamingFormat(t){switch(t){case"pcm16":return"PCM";case"ogg":case"opus":return"OGG_OPUS";default:return}}static streamedAudio(t){if(t===null||typeof t!="object")return;const r=t.audioContent;if(r instanceof Uint8Array)return r.byteLength>0?Buffer.from(r.buffer,r.byteOffset,r.byteLength):void 0;if(typeof r=="string"&&r.length>0){const n=Buffer.from(r,"base64");return n.length>0?n:void 0}}synthesizeStream(t,r={}){const n=r.voice;if(n===void 0||!fd.STREAMING_VOICE_PATTERN.test(n))return;const o=r.format??"mp3",i=fd.mapStreamingFormat(o);if(i===void 0||t.trimStart().startsWith("<speak"))return;const s=this.extractLanguageCode(n),a=fd.STREAMING_SAMPLE_RATE_HZ,l=this;let c,u=!1,d=!1;const p=(async function*(){const m=await l.getClient();if(u)return;const f=Date.now(),g=m.streamingSynthesize();c=g;let y;const v=()=>{clearTimeout(y),y=setTimeout(()=>{d=!0,g.cancel()},fd.STREAMING_IDLE_TIMEOUT_MS)};let T=0,b=0;try{g.write({streamingConfig:{voice:{name:n,languageCode:s},streamingAudioConfig:{audioEncoding:i,sampleRateHertz:a,speakingRate:r.speed??1}}}),g.write({input:{text:t}}),g.end(),v();for await(const S of g){clearTimeout(y);const k=fd.streamedAudio(S);if(k===void 0){v();continue}b+=k.length,yield{data:k,format:o,index:T++,isFinal:!1,cumulativeSize:b,voice:n,sampleRate:a},v()}h.debug(`[GoogleTTSHandler] Streamed ${b} bytes in ${Date.now()-f}ms`)}catch(S){if(u)return;if(S instanceof ft)throw S;const k=S instanceof Error?S.message:"Unknown error";throw new ft({code:Tt.SYNTHESIS_FAILED,message:d?`Google TTS streaming synthesis stalled for ${fd.STREAMING_IDLE_TIMEOUT_MS}ms`:`Google TTS streaming synthesis failed: ${k}`,category:d?"network":"execution",severity:"high",retriable:!0,context:{voice:n,audioEncoding:i},originalError:S instanceof Error?S:void 0})}finally{clearTimeout(y),c=void 0,g.cancel()}})();return DS(p,()=>{u=!0,c?.cancel()})}extractLanguageCode(t){const r=t.split("-");if(r.length>=2)return`${r[0]}-${r[1]}`;throw new ft({code:Tt.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";case"pcm16":throw new ft({code:Tt.INVALID_INPUT,message:"Google Cloud TTS's buffered synthesis does not support pcm16 output. pcm16 is only delivered via native streaming, which requires a Chirp3-HD, Chirp-HD, or Journey voice and plain (non-SSML) text \u2014 check that both conditions hold, or request a different format.",category:"validation",severity:"medium",retriable:!1,context:{format:t}});default:throw new ft({code:Tt.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"}}}}),IT,TC,cF=E({"src/lib/voice/RealtimeVoiceAPI.ts"(){"use strict";z(),Wd(),pt(),uv(),IT=class{static registry=new Of("RealtimeProcessor");static sessions=new Map;static registerHandler(e,t){const r=e&&e.toLowerCase();this.registry.register(e,t),h.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 tr.providerNotSupported(e,this.registry.list());if(!n.isConfigured())throw tr.providerNotConfigured(e);if(n.isConnected())throw tr.sessionAlreadyActive(e);const o={...v4,...t};r&&n.on(r);try{h.debug(`[RealtimeProcessor] Connecting to provider: ${e}`);const i=await n.connect(o);return this.sessions.set(e.toLowerCase(),i),h.info(`[RealtimeProcessor] Connected to ${e} session: ${i.id}`),i}catch(i){if(r&&n.off(),i instanceof tr)throw i;const s=i instanceof Error?i.message:String(i||"Unknown error");throw tr.connectionFailed(s,e,i instanceof Error?i:void 0)}}static async disconnect(e){const t=this.getHandler(e);if(!t)throw tr.providerNotSupported(e,this.registry.list());if(!t.isConnected()){h.warn(`[RealtimeProcessor] No active session for provider: ${e}`);return}try{await t.disconnect(),this.sessions.delete(e.toLowerCase()),t.off(),h.info(`[RealtimeProcessor] Disconnected from ${e}`)}catch(r){if(r instanceof tr)throw r;const n=r instanceof Error?r.message:String(r||"Unknown error");throw tr.protocolError(`Disconnect failed: ${n}`,e,r instanceof Error?r:void 0)}}static async sendAudio(e,t){const r=this.getHandler(e);if(!r)throw tr.providerNotSupported(e,this.registry.list());if(!r.isConnected())throw tr.sessionNotActive(e);try{await r.sendAudio(t)}catch(n){if(n instanceof tr)throw n;const o=n instanceof Error?n.message:String(n||"Unknown error");throw tr.audioStreamError(o,e)}}static async sendText(e,t){const r=this.getHandler(e);if(!r)throw tr.providerNotSupported(e,this.registry.list());if(!r.isConnected())throw tr.sessionNotActive(e);if(!r.sendText)throw new tr({code:es.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 tr?n:new tr({code:es.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 tr.providerNotSupported(e,this.registry.list());if(!t.isConnected())throw tr.sessionNotActive(e);if(t.triggerResponse)try{await t.triggerResponse()}catch(r){throw r instanceof tr?r:new tr({code:es.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 tr.providerNotSupported(e,this.registry.list());if(t.isConnected()&&t.cancelResponse)try{await t.cancelResponse()}catch(r){throw r instanceof tr?r:new tr({code:es.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(),h.debug("[RealtimeProcessor] Cleared all handlers and sessions")}},TC=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 nYt(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 Icn(e){return Z_[e]?.mimeType??"application/octet-stream"}function Rcn(e){return Z_[e]?.extension??".bin"}function Pcn(e,t,r){const n=t??nYt(e);if(n)try{switch(n){case"wav":return Mcn(e);case"mp3":return Ocn(e);case"ogg":case"opus":return Dcn(e);default:return r?e.length/(r*2):void 0}}catch(o){h.debug(`[audio-utils] Failed to calculate duration: ${o instanceof Error?o.message:String(o)}`);return}}function Mcn(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),i=e.readUInt32LE(t+12),s=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=s/8*o;return c/u/i}a+=8+c+c%2}}t+=8+n+n%2}}function Ocn(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,i=e[t+2]>>2&3,a={3:[44100,48e3,32e3],2:[22050,24e3,16e3],0:[11025,12e3,8e3]}[r]?.[i],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 Dcn(e){return e.length*8/64e3}async function Ncn(e,t,r,n={}){if(t===r)return e;throw h.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 Lcn(e,t=16e3,r=16){const n=r/8,o=Buffer.alloc(e.length*n);for(let i=0;i<e.length;i++){const s=Math.max(-1,Math.min(1,e[i])),a=i*n;switch(r){case 8:o.writeUInt8(Math.round((s+1)*127.5),a);break;case 16:o.writeInt16LE(Math.round(s*32767),a);break;case 24:{const l=Math.round(s*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(s*2147483647),a);break}}return o}function Fcn(e,t=16){const r=t/8,n=Math.floor(e.length/r),o=[];for(let i=0;i<n;i++){const s=i*r;switch(t){case 8:o.push(e.readUInt8(s)/127.5-1);break;case 16:o.push(e.readInt16LE(s)/32767);break;case 24:{const a=e.readUInt8(s)|e.readUInt8(s+1)<<8|e.readUInt8(s+2)<<16;o.push((a>8388607?a-16777216:a)/8388607);break}case 32:o.push(e.readInt32LE(s)/2147483647);break}}return o}function $cn(e,t,r){if(t<=0||r<=0||t===r)return e;const n=t/r,o=Math.round(e.length/n),i=[];for(let s=0;s<o;s++){const a=s*n,l=Math.floor(a),c=Math.min(l+1,e.length-1),u=a-l,d=e[l]*(1-u)+e[c]*u;i.push(d)}return i}function Ucn(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 oYt(e,t=16e3,r=1,n=16){const o=Buffer.alloc(44),i=t*r*(n/8),s=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(i,28),o.writeUInt16LE(s,32),o.writeUInt16LE(n,34),o.write("data",36),o.writeUInt32LE(e,40),o}function iYt(e,t=16e3,r=1,n=16){const o=oYt(e.length,t,r,n);return Buffer.concat([o,e])}function Bcn(e,t,r=16e3,n=2){if(t<=0||r<=0||n<=0)return[e];const o=r*n/1e3,i=Math.round(t*o);if(i<=0)return[e];const s=[];for(let a=0;a<e.length;a+=i){const l=Math.min(a+i,e.length);s.push(e.subarray(a,l))}return s}var sYt,aYt,lYt=E({"src/lib/voice/audio-utils.ts"(){"use strict";pt(),z(),sYt={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])},aYt={wav:"audio/wav",mp3:"audio/mpeg",ogg:"audio/ogg",opus:"audio/opus"}}});function zcn(e){return{[Symbol.asyncIterator](){const t=[];let r=null,n=null,o=!1,i=null;const s=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=>{i=u,n&&(n(u),r=null,n=null)};e.on("chunk",s),e.on("end",a),e.on("error",l);const c=()=>{e.off("chunk",s),e.off("end",a),e.off("error",l)};return{async next(){if(i)throw i;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 Gcn(e,t={}){const r=new RT(t);return(async()=>{try{for await(const n of e)r.write(n)||await new Promise(i=>r.once("drain",i));r.end()}catch(n){r.emit("error",n instanceof Error?n:new Error(String(n)))}})(),r}var gle,RT,cYt,uYt,qcn=E({"src/lib/voice/stream-handler.ts"(){"use strict";Wn(),z(),gle={chunkDurationMs:100,sampleRate:16e3,bytesPerSample:2,format:"wav",highWaterMark:64*1024,bufferTimeoutMs:5e3},RT=class extends un{config;chunkSize;buffer;chunkIndex;timestampMs;isPaused;isEnded;pendingData;bufferTimeout;constructor(e={}){if(super(),this.config={...gle,...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&&(h.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}}},cYt=class extends un{streams;config;constructor(e={}){super(),this.streams=new Map,this.config={...gle,...e}}addStream(e){if(this.streams.has(e))throw new Error(`Stream ${e} already exists`);const t=new RT(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}},uYt=class extends un{consumers;input;constructor(e={}){super(),this.consumers=new Map,this.input=new RT(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}}}}),PT,dYt=E({"src/lib/voice/providers/AzureTTS.ts"(){"use strict";z(),al(),PT=class eSr{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 ft({code:Tt.PROVIDER_NOT_CONFIGURED,message:"Azure Speech key not configured",category:"configuration",severity:"high",retriable:!1});if(this.voicesCache&&Date.now()-this.voicesCache.timestamp<eSr.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 ft({code:Tt.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 s=(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&&(s=s.filter(a=>a.languageCode.toLowerCase().startsWith(t.toLowerCase())||a.languageCode.toLowerCase()===t.toLowerCase())),t||(this.voicesCache={voices:s,timestamp:Date.now()}),s}catch(r){if(r instanceof ft)throw r;const n=r instanceof Error?r.message:String(r||"Unknown error");throw h.error(`[AzureTTSHandler] Failed to get voices: ${n}`),new ft({code:Tt.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 ft({code:Tt.PROVIDER_NOT_CONFIGURED,message:"Azure Speech key not configured",category:"configuration",severity:"high",retriable:!1});const n=Date.now(),o=r;try{const i=r.voice??"en-US-JennyNeural",s=o.outputFormat??this.mapFormat(r.format??"mp3"),a=this.buildSSML(t,i,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":s},body:a,signal:l.signal})}catch(g){throw g instanceof Error&&g.name==="AbortError"?new ft({code:Tt.SYNTHESIS_FAILED,message:"Azure TTS request timed out after 30 seconds",category:"network",severity:"high",retriable:!0,originalError:g}):g}finally{clearTimeout(c)}if(!u.ok){const g=await u.text();throw new Error(`HTTP ${u.status}: ${g}`)}const d=Date.now()-n,p=await u.arrayBuffer(),m=Buffer.from(p),f={buffer:m,format:this.effectiveFormat(s),size:m.length,voice:i,sampleRate:this.getSampleRate(s),metadata:{latency:d,provider:"azure-tts",requestedFormat:r.format,outputFormat:s,region:this.region}};return h.info(`[AzureTTSHandler] Synthesized ${m.length} bytes in ${d}ms`),f}catch(i){if(i instanceof ft)throw i;const s=i instanceof Error?i.message:String(i||"Unknown error");throw h.error(`[AzureTTSHandler] Synthesis failed: ${s}`),new ft({code:Tt.SYNTHESIS_FAILED,message:`Synthesis failed: ${s}`,category:"execution",severity:"high",retriable:!0,context:{textLength:t.length},originalError:i instanceof Error?i: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 i=n.speed?`${Math.round((n.speed-1)*100)}%`:"0%",s=n.pitch??0,a=s>=0?`+${Math.round(s)}st`:`${Math.round(s)}st`;return`<speak version="1.0" xmlns="http://www.w3.org/2001/10/synthesis" xml:lang="${this.escapeXml(this.extractLanguage(r))}">
|
|
2152
|
+
${r}`:r}function Kln(e){return typeof e=="string"?e:Array.isArray(e)?e.map(t=>typeof t=="string"?t:"").join(""):""}function nle(e){const t=e?.apiKey?.trim()||e?.apiToken?.trim(),r=e?.baseURL||e?.baseUrl;return{apiToken:t,baseUrl:r}}var ole,sJt,Jln=E({async"src/lib/providers/replicate.ts"(){"use strict";pl(),If(),B3(),G3(),Oa(),await tu(),z(),et(),Go(),ole=()=>Fi("REPLICATE_MODEL","meta/meta-llama-3-70b-instruct"),sJt=class extends Ma{apiToken;baseURL;constructor(e,t,r,n){const o=ch(t)?t:void 0;super(e,"replicate",o);const{apiToken:i,baseUrl:s}=nle(n);this.apiToken=i&&i.length>0?i:_a(j4r()),this.baseURL=s,h.debug("Replicate Provider initialized",{modelName:this.modelName,baseURL:this.baseURL})}getProviderName(){return this.providerName}getDefaultModel(){return ole()}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=$d(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 De({code:He.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??"",i=Date.now(),s=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 s.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 h.info(`[ReplicateProvider] generate() complete in ${Date.now()-i}ms \u2014 ${a.length} chars`),l}async executeStream(e,t){const r=Date.now(),n=e.credentials?.replicate,o=nle(n),i=o.apiToken||this.apiToken,s=o.baseUrl||this.baseURL,a=ah({apiToken:i,baseUrl:s});if(!a)throw new De({code:He.MISSING_CONFIGURATION,message:"Replicate auth could not be resolved (REPLICATE_API_TOKEN missing).",category:"configuration",severity:"high",retriable:!1});const l=Wln(e);if(!l.trim())throw new De({code:He.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 mC(a,{model:this.modelName,input:c},{abortSignal:e.abortSignal})}catch(m){throw this.handleProviderError(m)}const d=Kln(u.output);if(!d)throw new Error(`Replicate prediction ${u.id} returned empty output`);const p={async*[Symbol.asyncIterator](){yield{content:d}}};return h.info(`[ReplicateProvider] Generated ${d.length} chars in ${Date.now()-r}ms \u2014 model ${this.modelName} (prediction ${u.id})`),{stream:p,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=nle(r),o=n.apiToken||this.apiToken,i=n.baseUrl||this.baseURL,s=ah({apiToken:o,baseUrl:i});if(!s)throw new De({code:He.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 De({code:He.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 mC(s,{model:this.modelName,input:c},{abortSignal:e.abortSignal})}catch(m){throw this.handleProviderError(m)}let d;try{d=await z3(u,Nm)}catch(m){throw this.handleProviderError(m)}const p=d.toString("base64");return h.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:p}}}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 De({code:He.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 De({code:He.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 De({code:He.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 De({code:He.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 De({code:He.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:ole(),baseURL:this.baseURL}}}}}),aJt={};Z(aJt,{RecraftProvider:()=>ale,default:()=>uJt});var lJt,ile,cJt,sle,ale,uJt,Xln=E({async"src/lib/providers/recraft.ts"(){"use strict";pl(),await tu(),Ln(),pt(),z(),Go(),Oa(),Fm(),xw(),lJt="https://external.api.recraft.ai/v1",ile=12e4,cJt=()=>_a(J4r()),sle=()=>Fi("RECRAFT_MODEL","recraftv3"),ale=class extends Ma{apiKey;baseURL;proxyFetch;constructor(e,t,r,n){const o=ch(t)?t:void 0;super(e,"recraft",o);const i=n?.apiKey?.trim();this.apiKey=i&&i.length>0?i:cJt(),this.baseURL=n?.baseURL??process.env.RECRAFT_BASE_URL??lJt,this.proxyFetch=Ot(),h.debug("Recraft Provider initialized (image-gen only)",{modelName:this.modelName,baseURL:this.baseURL})}getProviderName(){return this.providerName}getDefaultModel(){return sle()}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 Wr("Invalid Recraft API key. Get one at https://www.recraft.ai/api","recraft"):t.includes("429")||t.toLowerCase().includes("rate limit")?new Qi("Recraft rate limit exceeded. Back off and retry.","recraft"):t.includes("404")||t.includes("model_not_found")?new Jo(`Recraft model '${this.modelName}' not found. Use recraftv3, recraftv3-svg, or recraftv2.`,"recraft"):new nt(`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,i=e.prompt??e.input?.text??"";if(!i.trim())throw new Error("Recraft image generation requires a prompt (input.text or prompt)");const s=e,a={model:e.model??this.modelName,prompt:i,n:1,response_format:"b64_json"};s.negativePrompt&&(a.negative_prompt=s.negativePrompt),s.style&&(a.style=s.style),s.styleId&&(a.style_id=s.styleId),s.size&&(a.size=s.size);const l=new AbortController,c=setTimeout(()=>l.abort(),ile);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(g){throw g instanceof Error&&g.name==="AbortError"?this.formatProviderError(new Error(`Recraft image-gen request timed out after ${ile/1e3}s`)):this.formatProviderError(g)}finally{clearTimeout(c)}if(!u.ok){const g=await u.text();throw this.formatProviderError(new Error(`Recraft image-gen failed: ${u.status} \u2014 ${g}`))}const p=(await u.json()).data?.[0];if(!p)throw new Error("Recraft returned no image data");let m;if(p.b64_json)m=p.b64_json;else if(p.url)m=(await Lm(p.url,{label:"Recraft image",maxBytes:Nm,timeoutMs:6e4})).toString("base64");else throw new Error("Recraft response missing both b64_json and url");const f=Date.now()-t;return h.info(`[RecraftProvider] Generated image (${m.length} base64 chars) in ${f}ms \u2014 model ${this.modelName}`),{content:i,provider:this.providerName,model:this.modelName,usage:{input:0,output:1e3,total:1e3},imageOutput:{base64:m,mimeType:Xx(Buffer.from(m.slice(0,64),"base64"))}}}async validateConfiguration(){return typeof this.apiKey=="string"&&this.apiKey.trim().length>0}getConfiguration(){return{provider:this.providerName,model:this.modelName,defaultModel:sle(),baseURL:this.baseURL}}},uJt=ale}});function Yln(e){return ok(e)&&$M(e)===null?"video/mp4":yJt.every((t,r)=>e[r]===t)?"video/webm":null}function dJt(e,t,r){const n=t==="image"?Jx(e):Yln(e);return n===null?{status:"error",message:`${r} ${vJt[t]}.`}:{status:"ok",dataUrl:`data:${n};base64,${e.toString("base64")}`}}function lle(e){return e.length<=fJt?`(${e})`:`(a ${e.length}-character string)`}async function Zln(e,t,r){try{const n=await q4.stat(e);return n.isFile()?n.size>r?{status:"error",message:`${t} ${lle(e)} is ${n.size} bytes; a request may carry at most ${r}.`}:{status:"ok",buffer:await q4.readFile(e)}:{status:"error",message:`${t} ${lle(e)} is not a file.`}}catch(n){const o=n instanceof Error&&"code"in n?String(n.code):"unreadable";return{status:"error",message:`Could not read ${t} ${lle(e)}: ${o}.`}}}async function pJt(e,t,r,n){if(typeof e!="string")return e.length===0?{status:"error",message:`${r} is an empty Buffer.`}:dJt(e,t,r);const o=e.trim();if(o==="")return{status:"error",message:`${r} is an empty string.`};if(mJt.test(o))return{status:"error",message:`${r} is a remote URL. Media is not fetched for you; pass a Buffer, a file path or a data: URL.`};if(/^data:/i.test(o))return gJt[t].test(o)?{status:"ok",dataUrl:o}:{status:"error",message:`${r} is a data: URL that is not base64 ${t} content.`};if(hJt.test(o))return{status:"error",message:`${r} uses an unsupported URL scheme. Pass a Buffer, a file path or a data: URL.`};const i=await Zln(o,r,n);return i.status==="ok"?dJt(i.buffer,t,r):i}async function Qln(e,t,r,n){const o=e.images??[];if(o.length===0&&e.video===void 0)return{status:"prepared",media:void 0};if(!t){const l=n.length>0?` Use a decision provider that does: ${n.join(", ")}.`:"";return{status:"refused",message:`${r} does not accept images or video.${l}`}}if(o.length>t.maxImages)return{status:"refused",message:`${r} accepts at most ${t.maxImages} images per request; this one has ${o.length}.`};if(e.video!==void 0&&!t.video)return{status:"refused",message:`${r} does not accept video.`};const i=[];for(const[l,c]of o.entries()){const u=await pJt(c,"image",`Image ${l+1}`,t.maxRequestBytes);if(u.status==="error")return{status:"refused",message:u.message};i.push(u.dataUrl)}let s;if(e.video!==void 0){const l=await pJt(e.video,"video","The video",t.maxRequestBytes);if(l.status==="error")return{status:"refused",message:l.message};s=l.dataUrl}const a=i.reduce((l,c)=>l+c.length,s?.length??0);return{status:"prepared",media:{images:i,...s?{video:s}:{},bytes:a}}}var mJt,hJt,fJt,gJt,yJt,vJt,ecn=E({"src/lib/utils/decisionMedia.ts"(){"use strict";Sn(),xw(),UM(),mJt=/^https?:\/\//i,hJt=/^[a-z][a-z0-9+.-]*:\/\//i,fJt=200,gJt={image:/^data:image\/[a-z0-9.+-]+;base64,/i,video:/^data:video\/[a-z0-9.+-]+;base64,/i},yJt=[26,69,223,163],vJt={image:"is not a recognised image format",video:"is not a recognised video format (MP4, MOV or WebM)"}}});function wJt(e){const t=Object.values(e);return t.length>0?Math.max(...t):0}function tcn(e,t){if(!Pr(e))return null;switch(e.type){case"noul":case"boolean":{const r=sc(e.noul)??sc(e.probability);return r===void 0?null:{type:"boolean",probability:r}}case"choice":{const r=dle(e.probabilities);return typeof e.choice!="string"||!r?null:{type:"choice",choice:e.choice,confidence:sc(e.confidence)??t??wJt(r),probabilities:r}}case"score":{const r=sc(e.score),n=bJt(e.legend),o=dle(e.probabilities);return r===void 0||!n||!o?null:{type:"score",score:r,confidence:sc(e.confidence)??t??wJt(o),legend:n,probabilities:o}}default:return null}}function cle(e){return e.filter(Pr).map(r=>{const n=Array.isArray(r.loc)?r.loc.filter(i=>typeof i=="string"||typeof i=="number").join("."):"",o=typeof r.msg=="string"?r.msg:"invalid";return n?`${n}: ${o}`:o}).slice(0,5).join("; ")||"unspecified field"}function yC(e,t){return(t?e.split(t).join("[redacted]"):e).replace(/\.?\s*Received API Key\s*=[\s\S]*$/,"").replace(/\bsk-[A-Za-z0-9._-]+/g,"[redacted]").replace(/\b[0-9a-f]{32,}\b/gi,"[redacted]").replace(/data:[a-z]+\/[a-z0-9.+-]+;base64,[A-Za-z0-9+/=]+/gi,"[media]").trim()}function rcn(e,t,r={}){const{digit:n,symbol:o,astral:i}=r;if(t===void 0&&n===void 0&&o===void 0&&i===void 0)return Vt(e);const s=m=>m>="0"&&m<="9",a=m=>/[!-/:-@[-`{-~]/.test(m);let l=0,c=0,u=0,d=0;const p=[];for(const m of e){const f=m.codePointAt(0)??0;f>65535&&i!==void 0?u+=1:f>127?d+=1:n!==void 0&&s(m)?l+=1:o!==void 0&&a(m)?c+=1:p.push(m)}return Vt(p.join(""))+Math.ceil(l*(n??0))+Math.ceil(c*(o??0))+Math.ceil(u*(i??0))+Math.ceil(d*(t??1/xv))}var ule,TJt,Pr,sc,dle,bJt,ple,CT,vC=E({async"src/lib/providers/systemOneDecision.ts"(){"use strict";pl(),Fl(),await tu(),Ln(),pt(),ecn(),z(),Nt(),di(),ule=5e3,TJt=1,Pr=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),sc=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,dle=e=>{if(!Pr(e))return;const t={};for(const[r,n]of Object.entries(e)){const o=sc(n);if(o===void 0)return;t[r]=o}return t},bJt=e=>{if(!Pr(e))return;const t={};for(const[r,n]of Object.entries(e)){if(typeof n!="string")return;t[r]=n}return t},ple=(e,t)=>new Promise((r,n)=>{if(t?.aborted){n(t.reason);return}const o=setTimeout(()=>{t?.removeEventListener("abort",i),r()},e);function i(){clearTimeout(o),n(t?.reason)}t?.addEventListener("abort",i,{once:!0})}),CT=class extends Ma{proxyFetch;maxRetries;authFailed=!1;constructor(e,t,r){super(e,t,ch(r)?r:void 0),this.proxyFetch=Ot(),this.maxRetries=TJt}missingConfigMessage(){}encodeQuestion(e){return e.type==="boolean"?{type:"noul",instructions:e.instructions,...e.criteria?{criteria:e.criteria}:{}}:e}readRetryAfterMs(e){}defaultTimeoutMs(e){return this.getDescriptorDecideMs()}readDecisionPayload(e){return e}reportedConfidence(e){return{}}resolveResponseModel(e,t){return typeof e.model=="string"?e.model:t}diagnosticContext(){return{}}getProviderName(){return this.providerName}getDefaultDecisionModel(){return this.getDefaultModel()}supportsTools(){return!1}getAISDKModel(){throw new nt(`${this.vendorDisplayName()} is a decision-only provider; it generates no text, so chat completions are not available. Use \`decide()\` instead, or pick a different provider for \`generate()\` / \`stream()\`.`,this.providerName)}async executeStream(e,t){throw new nt(`${this.vendorDisplayName()} is a decision-only provider; streaming is not available. Use \`decide()\`, or pick another provider for \`stream()\`.`,this.providerName)}formatProviderError(e){if(e instanceof nt)return e;const t=e instanceof Error?e.message:String(e);return new nt(`${this.vendorLabel()} request failed: ${t}`,this.providerName)}async decide(e){const t=this.vendorLabel();if(!this.decisionApiKey())throw this.decisionError({kind:"authentication",message:this.missingKeyMessage(),retryable:!1});const r=this.missingConfigMessage();if(r)throw this.decisionError({kind:"invalid_request",message:r,retryable:!1});if(this.authFailed)throw this.decisionError({kind:"authentication",message:`${t} rejected this API key earlier; not retrying. Fix the key and construct a new provider.`,retryable:!1});const n=Object.entries(e.questions);if(n.length===0)throw this.decisionError({kind:"invalid_request",message:"At least one question is required.",retryable:!1});const o=e.model??this.modelName??this.getDefaultModel();this.assertWithinDecisionLimits(e,o,n.length);const i=Object.fromEntries(n.map(([u,d])=>[u,this.encodeQuestion(d)])),s=await this.prepareMedia(e),a=JSON.stringify(this.buildDecisionBody(e.state,i,o,s));this.assertWithinRequestBytes(a);const l=e.timeoutMs??this.defaultTimeoutMs(n.length)??this.defaultTimeout??ule;let c;for(let u=0;u<=this.maxRetries;u++){const d=Date.now();try{const p=AbortSignal.timeout(l),m=e.signal?AbortSignal.any([e.signal,p]):p,f=await this.proxyFetch(this.decisionEndpoint(o),{method:"POST",headers:this.decisionHeaders(),body:a,signal:m}),g=Date.now()-d,y=this.readRequestId(f.headers),v=Number(f.headers.get("x-envoy-upstream-service-time"))||void 0,T=await f.json().catch(()=>null);if(!f.ok){if(c=this.parseDecisionError(f.status,T,y),c.kind==="authentication"&&(this.authFailed=!0,h.warn(`${t}: credential not accepted \u2014 disabling this provider instance. ${c.message}`,{status:c.status,...this.diagnosticContext(),requestId:y})),!c.retryable||u===this.maxRetries)throw this.decisionError(c);const x=this.readRetryAfterMs(f.headers);if(x!==void 0&&x>l-(Date.now()-d))throw this.decisionError(c);await ple(x??2**u*250+Math.random()*250,e.signal);continue}const b=this.readDecisionPayload(T);if(!Pr(b)||!Pr(b.answers))throw this.decisionError({kind:"server",message:`${t} returned a response without an answers map.`,status:f.status,requestId:y,retryable:!1});const S=this.reportedConfidence(b),k={};for(const[x,P]of Object.entries(b.answers)){const C=tcn(P,S[x]);C?k[x]=C:h.warn(`${t}: dropped unparseable answer "${x}"`,{requestId:y})}const A=Pr(b.usage)?b.usage:{};return{model:this.resolveResponseModel(b,o),provider:this.providerName,answers:k,usage:{inputTokens:sc(A.input_tokens)??sc(A.inputTokens)??0,outputTokens:sc(A.output_tokens)??sc(A.outputTokens)??0},requestId:y,latencyMs:g,upstreamMs:v,...s?{mediaBytes:s.bytes}:{}}}catch(p){if(p instanceof nt)throw p;const m=e.signal?.aborted===!0,f=p instanceof Error&&p.name==="TimeoutError";if(c={kind:m?"network":f?"timeout":"network",message:yC(dE(p instanceof Error?p.message:String(p)),this.decisionApiKey()),retryable:!m},m||u===this.maxRetries)throw this.decisionError(c);await ple(2**u*250+Math.random()*250)}}throw this.decisionError(c??{kind:"network",message:`${t} request failed.`,retryable:!1})}async prepareMedia(e){const t=hr.get(this.providerName)?.decisionLimits,r=await Qln(e,t?.media,this.vendorLabel(),oPr({video:e.video!==void 0}));if(r.status==="refused")throw this.decisionError({kind:"invalid_request",message:r.message,retryable:!1});return r.media}assertWithinRequestBytes(e){const t=hr.get(this.providerName)?.decisionLimits?.media,r=t?.maxRequestBytes;if(r===void 0)return;const n=Buffer.byteLength(e);if(n>r)throw this.decisionError({kind:"invalid_request",message:`The request is ${n} bytes; ${this.vendorLabel()} accepts at most ${r}. Send fewer or smaller images${t?.video?", or a shorter video":""}.`,retryable:!1})}assertWithinDecisionLimits(e,t,r){const n=hr.get(this.providerName)?.decisionLimits;if(!n)return;const o=this.vendorLabel();if(n.maxQuestions!==void 0&&r>n.maxQuestions)throw this.decisionError({kind:"max_tokens_exceeded",message:`${o} accepts at most ${n.maxQuestions} questions per request; this one has ${r}. Ask fewer, or use a decision provider without this cap.`,retryable:!1});const i=n.models?.[t],s=i?.maxStateTokens??n.maxStateTokens,a=rcn(xk(e.state),i?.nonAsciiTokensPerChar??n.nonAsciiTokensPerChar,{digit:n.digitTokensPerChar,symbol:n.symbolTokensPerChar,astral:n.astralTokensPerChar});if(a>s)throw this.decisionError({kind:"max_tokens_exceeded",message:`The state is ~${a} tokens; ${o}'s "${t}" model reads at most ${s}. Shorten the state, or use a decision provider with a larger window.`,retryable:!1})}decisionError(e){const t=new nt(e.message,this.providerName);return Object.defineProperty(t,"cause",{value:e,enumerable:!1,writable:!0,configurable:!0}),t}}}}),_Jt={};Z(_Jt,{TYPESAFE_MAX_REQUEST_TOKENS:()=>aF,TYPESAFE_MAX_STATE_TOKENS:()=>sF,TypeSafeProvider:()=>RJt});function ncn(e){if(!Pr(e)||!Pr(e.providerMetadata))return{};const t=e.providerMetadata.typesafe;if(!Pr(t)||!Pr(t.confidence))return{};const r={};for(const[n,o]of Object.entries(t.confidence)){const i=sc(o);i!==void 0&&(r[n]=i)}return r}function ocn(e,t,r,n){const o=typeof t.type=="string"?t.type:void 0,i=(o?IJt[o]:void 0)??(e===401||e===403?"authentication":e===429?"rate_limit":e>=500?"server":"invalid_request"),s=typeof t.message=="string"&&t.message.length>0?t.message:o??`AI Gateway request failed with HTTP ${e}`;return{kind:i,message:s,status:e,requestId:r,retryable:n}}function EJt(e,t,r){const n=e===429||e===529||e>=500,o=Pr(t)&&Pr(t.error)?t.error:void 0;if(o)return ocn(e,o,r,n);const i=Pr(t)?t.detail:void 0;if(Array.isArray(i))return{kind:"invalid_request",message:`Request failed validation \u2014 ${cle(i)}`,status:e,requestId:r,retryable:!1};const s=Pr(i)&&typeof i.error_type=="string"?i.error_type:void 0,a=s==="max_tokens_exceeded"?"max_tokens_exceeded":e===401||e===403?"authentication":e===429?"rate_limit":e===529?"overloaded":e>=500?"server":"invalid_request",l=a==="max_tokens_exceeded"?`State plus questions exceeded the model's input limit: keep state plus the longest single question under ~${sF} tokens, and state plus all questions under ~${aF}.`:s??`TypeSafe request failed with HTTP ${e}`,c=Pr(i)&&typeof i.message=="string"?i.message:l;return{kind:a,message:c,status:e,requestId:r,retryable:n}}var SJt,kJt,xJt,AJt,CJt,sF,aF,IJt,RJt,PJt=E({async"src/lib/providers/typesafe.ts"(){"use strict";z(),Nt(),Go(),await vC(),SJt="https://api.typesafe.ai",kJt="https://ai-gateway.vercel.sh/v4/ai/evaluation-model",xJt="typesafe-ai/jev",AJt="0.0.1",CJt="4",sF=33e3,aF=64e3,IJt={authentication_error:"authentication",customer_verification_required:"authentication",invalid_request_error:"invalid_request",rate_limit_exceeded:"rate_limit",internal_server_error:"server"},RJt=class extends CT{apiKey;baseURL;gatewayURL;transport;constructor(e,t,r,n){super(e,"typesafe",t);const o=n?.apiKey?.trim()||(process.env.TYPESAFE_API_KEY?.trim()??""),i=n?.gatewayApiKey?.trim()||(process.env.AI_GATEWAY_API_KEY?.trim()??""),s=n?.transport??process.env.TYPESAFE_TRANSPORT?.trim();this.transport=s==="gateway"||s==="direct"?s:!o&&i?"gateway":"direct",this.apiKey=this.transport==="gateway"?i:o,this.baseURL=(n?.baseURL??process.env.TYPESAFE_BASE_URL??SJt).replace(/\/+$/,""),this.gatewayURL=(n?.gatewayURL?.trim()||process.env.TYPESAFE_GATEWAY_URL?.trim()||kJt).replace(/\/+$/,""),h.debug("TypeSafe Provider initialized (decide only)",{modelName:this.modelName,transport:this.transport,baseURL:Xt(this.transport==="gateway"?this.gatewayURL:this.baseURL)})}getDefaultModel(){return Fi("TYPESAFE_MODEL","jev-latest")}vendorLabel(){return"TypeSafe"}vendorDisplayName(){return"TypeSafe (Jev)"}decisionApiKey(){return this.apiKey}missingKeyMessage(){return this.transport==="gateway"?"The TypeSafe gateway transport requires a Vercel AI Gateway key. Set AI_GATEWAY_API_KEY or pass credentials.typesafe.gatewayApiKey.":"TypeSafe requires an API key. Set TYPESAFE_API_KEY or pass credentials.typesafe.apiKey."}encodeQuestion(e){return this.transport==="gateway"?e:super.encodeQuestion(e)}buildDecisionBody(e,t,r){return this.transport==="gateway"?{state:e,questions:t}:{model:r,state:e,questions:t}}parseDecisionError(e,t,r){return EJt(e,t,r)}reportedConfidence(e){return ncn(e)}readRequestId(e){return e.get("x-typesafe-request-id")??void 0}diagnosticContext(){return{transport:this.transport}}decisionEndpoint(){return this.transport==="gateway"?this.gatewayURL:`${this.baseURL}/v1/systemone`}decisionHeaders(){const e={Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json"};return this.transport==="gateway"?{...e,"ai-gateway-auth-method":"api-key","ai-gateway-protocol-version":AJt,"ai-model-id":xJt,"ai-evaluation-model-specification-version":CJt}:e}getDecisionTransport(){return this.transport}async listDecisionModels(){if(this.transport==="gateway")throw this.decisionError({kind:"invalid_request",message:"Model listing is a TypeSafe API operation; the gateway transport has no equivalent endpoint.",retryable:!1});const e=await this.proxyFetch(`${this.baseURL}/v1/models`,{headers:{Authorization:`Bearer ${this.apiKey}`},signal:AbortSignal.timeout(this.defaultTimeout??ule)}),t=await e.json().catch(()=>null);if(!e.ok)throw this.decisionError(EJt(e.status,t,e.headers.get("x-typesafe-request-id")??void 0));return(Pr(t)&&Array.isArray(t.models)?t.models:[]).filter(Pr).map(n=>({name:typeof n.name=="string"?n.name:"",description:typeof n.description=="string"?n.description:"",releaseDate:typeof n.release_date=="string"?n.release_date:""}))}}}}),MJt={};Z(MJt,{LayaProvider:()=>OJt});function icn(e,t,r){const n=e===429||e>=500,o=e===401||e===403?"authentication":e===413?"max_tokens_exceeded":e===429?"rate_limit":e===503?"overloaded":e>=500?"server":"invalid_request",i=Pr(t)&&Pr(t.error)?t.error:void 0;if(i&&typeof i.message=="string"&&i.message.length>0)return{kind:o,message:i.message,status:e,requestId:r,retryable:n};const s=Pr(t)?t.detail:void 0;return Array.isArray(s)?{kind:"invalid_request",message:`Request failed validation \u2014 ${cle(s)}`,status:e,requestId:r,retryable:!1}:typeof s=="string"&&s.length>0?{kind:o,message:s,status:e,requestId:r,retryable:n}:{kind:o,message:`Laya request failed with HTTP ${e}`,status:e,requestId:r,retryable:n}}var OJt,scn=E({async"src/lib/providers/laya.ts"(){"use strict";z(),Nt(),Go(),await vC(),OJt=class extends CT{apiKey;baseURL;constructor(e,t,r,n){super(e,"laya",t),this.apiKey=n?.apiKey?.trim()||(process.env.LAYA_API_KEY?.trim()??""),this.baseURL=(n?.baseURL?.trim()||process.env.LAYA_BASE_URL?.trim()||"").replace(/\/+$/,""),h.debug("Laya Provider initialized (decide only)",{modelName:this.modelName,baseURL:this.baseURL?Xt(this.baseURL):"(not set)"})}getDefaultModel(){return Fi("LAYA_MODEL","typed-decisions")}vendorLabel(){return"Laya"}vendorDisplayName(){return"Laya"}decisionApiKey(){return this.apiKey}missingKeyMessage(){return"Laya requires an API key. Set LAYA_API_KEY or pass credentials.laya.apiKey."}missingConfigMessage(){return this.baseURL?void 0:"Laya requires a base URL. Set LAYA_BASE_URL or pass credentials.laya.baseURL."}decisionEndpoint(){return`${this.baseURL}/predict`}decisionHeaders(){return{Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json"}}buildDecisionBody(e,t,r){return r==="auto"?{state:e,questions:t}:{model:r,state:e,questions:t}}parseDecisionError(e,t,r){const n=icn(e,t,r),o=yC(n.message,this.apiKey);return{...n,message:o||`Laya request failed with HTTP ${e}`}}readRequestId(e){return e.get("x-litellm-call-id")??void 0}resolveResponseModel(e,t){const r=e.routing;return Pr(r)&&typeof r.model=="string"?r.model:super.resolveResponseModel(e,t)}}}}),DJt={};Z(DJt,{XorProvider:()=>FJt});function acn(e){return e.replace(/\/+$/,"").replace(/\/v1$/i,"")}function lcn(e){const t="Set XOR_BASE_URL or pass credentials.xor.baseURL to the origin, and give the key through XOR_API_KEY or credentials.xor.apiKey.";try{const r=new URL(e);return r.protocol!=="https:"&&r.protocol!=="http:"?`The XOR base URL must start with https:// or http://. ${t}`:r.username||r.password||r.search||r.hash?`The XOR base URL must not carry credentials, a query string or a fragment. ${t}`:void 0}catch{return`The XOR base URL is not a valid absolute URL. ${t}`}}function ccn(e,t){return e===401?"authentication":e===413?"max_tokens_exceeded":e===429?"rate_limit":e===503?"overloaded":e>=500?LJt.test(t)?"max_tokens_exceeded":"server":"invalid_request"}function ucn(e){if(!Pr(e))return;const{error:t,detail:r}=e;return Pr(t)&&typeof t.message=="string"&&t.message.length>0?t.message:typeof t=="string"&&t.length>0?t:Array.isArray(r)?`Request failed validation \u2014 ${cle(r)}`:typeof r=="string"&&r.length>0?r:void 0}var NJt,LJt,FJt,dcn=E({async"src/lib/providers/xor.ts"(){"use strict";z(),Nt(),Go(),await vC(),NJt="/v1/systemone",LJt=/(context|prefill|prompt).{0,40}(length|limit|too long|exceed)|(too long|exceeds?).{0,40}(context|tokens)/i,FJt=class extends CT{apiKey;baseURL;constructor(e,t,r,n){super(e,"xor",t),this.apiKey=n?.apiKey?.trim()||(process.env.XOR_API_KEY?.trim()??""),this.baseURL=acn(n?.baseURL?.trim()||process.env.XOR_BASE_URL?.trim()||""),h.debug("XOR Provider initialized (decide only)",{modelName:this.modelName,baseURL:this.baseURL?Xt(this.baseURL):"(not set)"})}getDefaultModel(){return Fi("XOR_MODEL","xor-1.1")}vendorLabel(){return"XOR"}vendorDisplayName(){return"XOR"}decisionApiKey(){return this.apiKey}missingKeyMessage(){return"XOR requires an API key. Set XOR_API_KEY or pass credentials.xor.apiKey."}missingConfigMessage(){return this.baseURL?lcn(this.baseURL):"XOR requires a base URL. Set XOR_BASE_URL or pass credentials.xor.baseURL."}decisionEndpoint(){return`${this.baseURL}${NJt}`}decisionHeaders(){return{Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json"}}buildDecisionBody(e,t,r,n){return{model:r,state:e,questions:t,...n&&n.images.length>0?{images:n.images}:{},...n?.video?{video:n.video}:{}}}parseDecisionError(e,t,r){const n=`XOR request failed with HTTP ${e}`,o=yC(ucn(t)??n,this.apiKey)||n,i=ccn(e,o);return{kind:i,message:o,status:e,requestId:r,retryable:i==="rate_limit"||i==="overloaded"||i==="server"}}readRequestId(e){return e.get("x-request-id")??e.get("x-typesafe-request-id")??e.get("x-litellm-call-id")??void 0}}}}),$Jt={};Z($Jt,{PerplexityDeciderProvider:()=>WJt});function pcn(e){return e.replace(/\/+$/,"").replace(/\/v1$/i,"")}function UJt(e){const t=`Set PERPLEXITY_DECIDER_BASE_URL or pass credentials.perplexityDecider.baseURL to an origin, or leave both unset to use ${mle}.`;try{const r=new URL(e);return r.protocol!=="https:"&&r.protocol!=="http:"?`The Perplexity base URL must start with https:// or http://. ${t}`:r.username||r.password||r.search||r.hash?`The Perplexity base URL must not carry credentials, a query string or a fragment. ${t}`:void 0}catch{return`The Perplexity base URL is not a valid absolute URL. ${t}`}}function mcn(e){try{return new URL(e).hostname===GJt}catch{return!1}}function hcn(e,t){return e===401?"authentication":e===413||e===400&&HJt.test(t)?"max_tokens_exceeded":e===429?"rate_limit":e===503?"overloaded":e>=500?"server":"invalid_request"}function fcn(e){if(!Pr(e)||!Pr(e.error))return;const{message:t,param:r}=e.error;if(!(typeof t!="string"||t.length===0))return typeof r=="string"&&r!==""&&!t.includes(r)?`${t} (field: ${r})`:t}function gcn(e){return e.length>=24&&e.toString("ascii",12,16)==="IHDR"?{width:e.readUInt32BE(16),height:e.readUInt32BE(20)}:void 0}function ycn(e){let t=2;for(;t+4<=e.length;){if(e[t]!==255)return;const r=e[t+1];if(r===255)t+=1;else if(r===1||r>=208&&r<=216)t+=2;else{if(r===217||r===218)return;if(r>=192&&r<=207&&r!==196&&r!==200&&r!==204)return t+9<=e.length?{height:e.readUInt16BE(t+5),width:e.readUInt16BE(t+7)}:void 0;t+=2+e.readUInt16BE(t+2)}}}function vcn(e){if(!(e.length<30))switch(e.toString("ascii",12,16)){case"VP8X":return{width:1+e.readUIntLE(24,3),height:1+e.readUIntLE(27,3)};case"VP8L":{const t=e.readUInt32LE(21);return e[20]===47?{width:(t&16383)+1,height:(t>>>14&16383)+1}:void 0}case"VP8 ":return{width:e.readUInt16LE(26)&16383,height:e.readUInt16LE(28)&16383};default:return}}function wcn(e){switch(Jx(e)){case"image/png":return gcn(e);case"image/jpeg":return ycn(e);case"image/webp":return vcn(e);default:return}}function Tcn(e,t){const r=/^data:([a-z]+\/[a-z0-9.+-]+);base64,/i.exec(e);if(!r||!VJt.has(r[1].toLowerCase()))return`Image ${t} is not a PNG, JPEG or WebP image, the only formats Perplexity reads.`;const n=wcn(Buffer.from(e.slice(r[0].length),"base64"));return n&&Math.round(n.width/wC)*Math.round(n.height/wC)>hle?`Image ${t} is ${n.width}x${n.height} pixels; Perplexity reads at most ${hle} tiles of ${wC}x${wC} pixels per image (1440x1440 and 2048x1024 fit), and a larger one stalls until the request times out. Resize it first.`:void 0}function BJt(e){return typeof e=="number"||typeof e=="boolean"?String(e):e}var mle,zJt,GJt,qJt,VJt,wC,hle,jJt,HJt,WJt,bcn=E({async"src/lib/providers/perplexityDecider.ts"(){"use strict";xw(),z(),Nt(),Go(),await vC(),mle="https://api.perplexity.ai",zJt="/v1/decisions",GJt="api.perplexity.ai",qJt="neurolink",VJt=new Set(["image/png","image/jpeg","image/webp"]),wC=32,hle=2048,jJt=100,HJt=/exceeds(?: or equals)?(?: model's)? maximum context length/i,WJt=class extends CT{apiKey;baseURL;constructor(e,t,r,n){super(e,"perplexity-decider",t),this.apiKey=n?.apiKey?.trim()||(process.env.PERPLEXITY_API_KEY?.trim()??""),this.baseURL=pcn(n?.baseURL?.trim()||process.env.PERPLEXITY_DECIDER_BASE_URL?.trim()||mle),h.debug("Perplexity decision provider initialized (decide only)",{modelName:this.modelName,baseURL:UJt(this.baseURL)?"(invalid)":Xt(this.baseURL)})}getDefaultModel(){return Fi("PERPLEXITY_DECIDER_MODEL","pplx-decider-v1-27b")}vendorLabel(){return"Perplexity"}vendorDisplayName(){return"Perplexity Decisions"}decisionApiKey(){return this.apiKey}missingKeyMessage(){return"Perplexity requires an API key. Set PERPLEXITY_API_KEY or pass credentials.perplexityDecider.apiKey."}missingConfigMessage(){return UJt(this.baseURL)}decisionEndpoint(){return`${this.baseURL}${zJt}`}decisionHeaders(){return{Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json",...mcn(this.baseURL)?{"X-Pplx-Integration":qJt}:{}}}buildDecisionBody(e,t,r,n){const o=n?.images??[];if(o.length===0)return{model:r,state:BJt(e),questions:t};o.forEach((s,a)=>{const l=Tcn(s,a+1);if(l)throw this.decisionError({kind:"invalid_request",message:l,retryable:!1})});const i=Array.isArray(e)?e:e===""?[]:[BJt(e)];return{model:r,state:[...i,...o.map(s=>({type:"image_url",image_url:{url:s}}))],questions:t}}parseDecisionError(e,t,r){const n=`Perplexity request failed with HTTP ${e}`,o=yC(fcn(t)??n,this.apiKey).replace(/\bpplx-[A-Za-z0-9_-]{30,}/g,"[redacted]").trim()||n,i=hcn(e,o);return{kind:i,message:o,status:e,requestId:r,retryable:i==="rate_limit"||i==="overloaded"||i==="server"}}readRequestId(e){return e.get("x-request-id")??void 0}defaultTimeoutMs(e){const t=this.getDescriptorDecideMs();return t===void 0?void 0:t+e*jJt}readRetryAfterMs(e){const t=e.get("retry-after")?.trim();if(!t)return;const r=/^\d+$/.test(t)?Number(t)*1e3:Date.parse(t)-Date.now();return Number.isFinite(r)&&r>0?Math.ceil(r):void 0}}}}),KJt={};Z(KJt,{CloudflareClefProvider:()=>nXt});function _cn(e){return e.replace(/\/+$/,"")}function JJt(e){const t=`Set CLOUDFLARE_CLEF_BASE_URL or pass credentials.cloudflareClef.baseURL to a base URL, or leave both unset to use ${fle}.`;try{const r=new URL(e);return r.protocol!=="https:"&&r.protocol!=="http:"?`The Cloudflare base URL must start with https:// or http://. ${t}`:r.username||r.password||r.search||r.hash||/[?#]/.test(e)?`The Cloudflare base URL must not carry credentials, a query string or a fragment. ${t}`:void 0}catch{return`The Cloudflare base URL is not a valid absolute URL. ${t}`}}function XJt(e){const t=e.trim().replace(/^@cf\/cloudflare\//i,"");return/^[a-z0-9][a-z0-9._-]*$/i.test(t)?t.toLowerCase():void 0}function Ecn(e,t){const r=/^data:([a-z]+\/[a-z0-9.+-]+);base64,/i.exec(e)?.[1]?.toLowerCase();return r&&QJt.has(r)?void 0:`Image ${t} is not a PNG, JPEG or WebP image, the only formats Cloudflare Clef reads.`}function Scn(e){return typeof e=="number"||typeof e=="boolean"?String(e):e}function kcn(e){if(!Pr(e)||!Array.isArray(e.errors))return;const t=e.errors.find(Pr);if(!t||typeof t.message!="string"||t.message==="")return;let r=t.message.slice(0,rXt).trimEnd(),n;const o=eXt.exec(r);if(o&&(n=o[1],r=r.slice(0,o.index).trimEnd()),r=r.replace(/^(?:AiError:\s*|Ai:\s*)+/,"").trim(),r.startsWith("{"))try{const i=JSON.parse(r);if(Pr(i)&&Pr(i.error)){const s=Pr(i.error.details)?i.error.details:void 0,a=Pr(s?.fieldErrors)?Object.entries(s.fieldErrors).flatMap(([c,u])=>Array.isArray(u)?u.filter(d=>typeof d=="string").map(d=>`${c}: ${d}`):[]):[],l=typeof i.error.message=="string"?i.error.message:r;r=a.length>0?`${l}: ${a.join("; ")}`:l}}catch{}return{message:r,code:typeof t.code=="number"?t.code:void 0,requestId:n}}function xcn(e,t){return e===401?"authentication":e===413||t===5021?"max_tokens_exceeded":e===429?"rate_limit":e===503?"overloaded":e>=500?"server":"invalid_request"}var fle,YJt,ZJt,QJt,eXt,tXt,rXt,nXt,Acn=E({async"src/lib/providers/cloudflareClef.ts"(){"use strict";z(),Nt(),Go(),await vC(),fle="https://api.cloudflare.com/client/v4",YJt="@cf/cloudflare/",ZJt=/^[A-Za-z0-9_-]{1,64}$/,QJt=new Set(["image/png","image/jpeg","image/webp"]),eXt=/\(([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\)\s*$/i,tXt=500,rXt=4096,nXt=class extends CT{apiKey;accountId;baseURL;constructor(e,t,r,n){super(e,"cloudflare-clef",t);const o=!!n?.baseURL?.trim();this.apiKey=n?.apiKey?.trim()||(o?"":process.env.CLOUDFLARE_API_KEY?.trim()??""),this.accountId=n?.accountId?.trim()||(process.env.CLOUDFLARE_ACCOUNT_ID?.trim()??""),this.baseURL=_cn(n?.baseURL?.trim()||process.env.CLOUDFLARE_CLEF_BASE_URL?.trim()||fle),h.debug("Cloudflare Clef decision provider initialized (decide only)",{modelName:this.modelName,baseURL:JJt(this.baseURL)?"(invalid)":Xt(this.baseURL),accountConfigured:this.accountId!==""})}getDefaultModel(){return Fi("CLOUDFLARE_CLEF_MODEL","clef")}vendorLabel(){return"Cloudflare"}vendorDisplayName(){return"Cloudflare Clef"}decisionApiKey(){return this.apiKey}missingKeyMessage(){return"Cloudflare Clef requires an API token with Workers AI permission. Set CLOUDFLARE_API_KEY or pass credentials.cloudflareClef.apiKey."}missingConfigMessage(){return this.accountId===""?"Cloudflare Clef requires the account id. Set CLOUDFLARE_ACCOUNT_ID or pass credentials.cloudflareClef.accountId.":ZJt.test(this.accountId)?JJt(this.baseURL):"The Cloudflare account id may contain only letters, digits, '-' and '_'. Copy it from the Cloudflare dashboard."}decisionEndpoint(e){return`${this.baseURL}/accounts/${encodeURIComponent(this.accountId)}/ai/run/${YJt}${encodeURIComponent(XJt(e)??e)}`}decisionHeaders(){return{Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json"}}buildDecisionBody(e,t,r,n){const o=XJt(r);if(!o)throw this.decisionError({kind:"invalid_request",message:`"${r.slice(0,40)}" is not a Cloudflare model name. Use "clef" or "clef-flash".`,retryable:!1});const i=(n?.images??[]).map(s=>s.replace(/^data:image\/jpg;base64,/i,"data:image/jpeg;base64,"));return i.forEach((s,a)=>{const l=Ecn(s,a+1);if(l)throw this.decisionError({kind:"invalid_request",message:l,retryable:!1})}),n&&(n.images=i,n.bytes=i.reduce((s,a)=>s+Buffer.byteLength(a),0)),{model:o,state:Scn(e),questions:t,...i.length>0?{images:i}:{}}}readDecisionPayload(e){return Pr(e)&&Pr(e.result)?e.result:e}parseDecisionError(e,t,r){const n=`Cloudflare request failed with HTTP ${e}`,o=kcn(t),i=xcn(e,o?.code);let s=yC(o?.message??n,this.apiKey).trim().slice(0,tXt)||n;return i==="max_tokens_exceeded"?s+=" Cloudflare counts the whole request, image data included, at about four characters per token.":o?.code===7e3&&(s+='. Check the model name (Clef is served as "clef" and "clef-flash") and the base URL, which must end in /client/v4 and name your account.'),{kind:i,message:s,status:e,requestId:r??o?.requestId,retryable:i==="rate_limit"||i==="overloaded"||i==="server"}}readRequestId(e){return e.get("cf-ai-req-id")??e.get("cf-ray")??void 0}}}}),oXt={};Z(oXt,{Agent:()=>WXt,BedrockClient:()=>sXt,BedrockRuntimeClient:()=>lXt,Blob:()=>HXt,Client:()=>JXt,ConverseCommand:()=>cXt,ConverseStreamCommand:()=>uXt,Cron:()=>CXt,Dispatcher:()=>XXt,File:()=>jXt,FlowProducer:()=>AXt,FormData:()=>VXt,GoogleAuth:()=>gXt,HTTPException:()=>NXt,Headers:()=>qXt,Hippocampus:()=>TXt,HippocampusConfig:()=>bXt,Hono:()=>OXt,ImageFormat:()=>dXt,InvokeEndpointCommand:()=>hXt,InvokeEndpointWithResponseStreamCommand:()=>fXt,InvokeModelCommand:()=>pXt,Job:()=>kXt,ListFoundationModelsCommand:()=>aXt,MockAgent:()=>QXt,Pool:()=>KXt,Queue:()=>EXt,QueueScheduler:()=>xXt,Request:()=>zXt,Response:()=>GXt,SageMakerRuntimeClient:()=>mXt,TextToSpeechClient:()=>vXt,VertexAI:()=>yXt,Webhook:()=>wXt,Worker:()=>SXt,convertToHtml:()=>MXt,cors:()=>DXt,createClient:()=>_Xt,default:()=>iXt,extractRawText:()=>PXt,fetch:()=>BXt,getGlobalDispatcher:()=>ZXt,interceptors:()=>eYt,logger:()=>LXt,parseBuffer:()=>IXt,request:()=>tYt,secureHeaders:()=>FXt,selectCover:()=>RXt,setGlobalDispatcher:()=>YXt,streamSSE:()=>$Xt,timeout:()=>UXt});var y0,Ri,iXt,sXt,aXt,lXt,cXt,uXt,dXt,pXt,mXt,hXt,fXt,gXt,yXt,vXt,wXt,TXt,bXt,_Xt,EXt,SXt,kXt,xXt,AXt,CXt,IXt,RXt,PXt,MXt,OXt,DXt,NXt,LXt,FXt,$Xt,UXt,BXt,zXt,GXt,qXt,VXt,jXt,HXt,WXt,KXt,JXt,XXt,YXt,ZXt,QXt,eYt,tYt,Ccn=E({"npm-stub:@google-cloud/text-to-speech"(){y0={get(e,t){return t==="__esModule"?!0:t==="default"?new Proxy({},{get:y0.get}):new Proxy(function(...r){return new Proxy({},{get:y0.get})},{get:y0.get,apply(r,n,o){return new Proxy({},{get:y0.get})},construct(r,n){return new Proxy({},{get:y0.get})}})}},Ri=new Proxy({},y0),iXt=Ri,{BedrockClient:sXt,ListFoundationModelsCommand:aXt,BedrockRuntimeClient:lXt,ConverseCommand:cXt,ConverseStreamCommand:uXt,ImageFormat:dXt,InvokeModelCommand:pXt}=Ri,{SageMakerRuntimeClient:mXt,InvokeEndpointCommand:hXt,InvokeEndpointWithResponseStreamCommand:fXt}=Ri,{GoogleAuth:gXt,VertexAI:yXt,TextToSpeechClient:vXt}=Ri,{Webhook:wXt}=Ri,{Hippocampus:TXt,HippocampusConfig:bXt}=Ri,{createClient:_Xt}=Ri,{Queue:EXt,Worker:SXt,Job:kXt,QueueScheduler:xXt,FlowProducer:AXt}=Ri,{Cron:CXt}=Ri,{parseBuffer:IXt,selectCover:RXt}=Ri,{extractRawText:PXt,convertToHtml:MXt}=Ri,{Hono:OXt}=Ri,{cors:DXt,HTTPException:NXt,logger:LXt,secureHeaders:FXt,streamSSE:$Xt,timeout:UXt}=Ri,BXt=globalThis.fetch,zXt=globalThis.Request,GXt=globalThis.Response,qXt=globalThis.Headers,VXt=globalThis.FormData,jXt=globalThis.File,HXt=globalThis.Blob,WXt=Ri.Agent,KXt=Ri.Pool,JXt=Ri.Client,XXt=Ri.Dispatcher,YXt=()=>{},ZXt=()=>Ri,QXt=Ri.MockAgent,eYt={redirect:()=>e=>e,retry:()=>e=>e},tYt=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()}}}}}),lF,rYt=E({"src/lib/adapters/tts/googleTTSHandler.ts"(){"use strict";al(),z(),pv(),No(),lF=class fd{client=null;voicesCache=null;static CACHE_TTL_MS=300*1e3;static DEFAULT_MAX_TEXT_LENGTH=5e3;static DEFAULT_API_TIMEOUT_MS=30*1e3;maxTextLength=fd.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(()=>(Ccn(),oXt));this.client=new t({keyFilename:this.credentialsPath})}return this.client}async getVoices(t){if(!this.isConfigured())throw new ft({code:Tt.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=Me.createSpan("tts","tts.google.listVoices",{"tts.operation":"listVoices","tts.provider":"google"});try{if(this.voicesCache&&Date.now()-this.voicesCache.timestamp<fd.CACHE_TTL_MS&&!t){const a=Me.endSpan(n,1);return it().recordSpan(a),this.voicesCache.voices}const[o]=await r.listVoices(t?{languageCode:t}:{});if(!o.voices||o.voices.length===0){h.warn("Google Cloud TTS returned no voices");const a=Me.endSpan(n,1);return it().recordSpan(a),[]}const i=[];for(const a of o.voices??[]){if(!a.name||!Array.isArray(a.languageCodes)||a.languageCodes.length===0){h.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),p=a.ssmlGender==="MALE"?"male":a.ssmlGender==="FEMALE"?"female":"neutral";i.push({id:l,name:l,languageCode:u,languageCodes:c,gender:p,type:d,naturalSampleRateHertz:a.naturalSampleRateHertz??void 0})}t||(this.voicesCache={voices:i,timestamp:Date.now()});const s=Me.endSpan(n,1);return it().recordSpan(s),i}catch(o){const i=Me.endSpan(n,2,o instanceof Error?o.message:"Unknown error");it().recordSpan(i);const s=o instanceof Error?o.message:"Unknown error";return h.error(`Failed to fetch Google TTS voices: ${s}`),[]}}async synthesize(t,r){if(!this.isConfigured())throw new ft({code:Tt.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",i=Me.createSpan("tts","tts.google.synthesize",{"tts.operation":"synthesize","tts.provider":"google","tts.voice":o,"tts.format":r.format??"mp3"}),s=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 ft({code:Tt.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:fd.DEFAULT_API_TIMEOUT_MS}),p=d.audioContent;if(!p)throw new ft({code:Tt.SYNTHESIS_FAILED,message:"Google TTS returned empty audio content",category:"execution",severity:"high",retriable:!0});const m=p instanceof Uint8Array?Buffer.from(p):typeof p=="string"?Buffer.from(p,"base64"):(()=>{throw new ft({code:Tt.SYNTHESIS_FAILED,message:"Unsupported audioContent type returned by Google TTS",category:"execution",severity:"high",retriable:!0,context:{type:typeof p}})})(),f=Date.now()-s,g=Me.endSpan(i,1);return it().recordSpan(g),{buffer:m,format:r.format??"mp3",size:m.length,voice:o,metadata:{latency:f,provider:"google-ai"}}}catch(a){const l=Me.endSpan(i,2,a instanceof Error?a.message:String(a));if(it().recordSpan(l),a instanceof ft)throw a;const c=Date.now()-s,u=a instanceof Error?a.message:"Unknown error";throw new ft({code:Tt.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})}}static STREAMING_VOICE_PATTERN=/^[a-z]{2,3}-[A-Z]{2}-(?:Chirp3-HD|Chirp-HD|Journey)-/;static STREAMING_SAMPLE_RATE_HZ=24e3;static STREAMING_IDLE_TIMEOUT_MS=30*1e3;static mapStreamingFormat(t){switch(t){case"pcm16":return"PCM";case"ogg":case"opus":return"OGG_OPUS";default:return}}static streamedAudio(t){if(t===null||typeof t!="object")return;const r=t.audioContent;if(r instanceof Uint8Array)return r.byteLength>0?Buffer.from(r.buffer,r.byteOffset,r.byteLength):void 0;if(typeof r=="string"&&r.length>0){const n=Buffer.from(r,"base64");return n.length>0?n:void 0}}synthesizeStream(t,r={}){const n=r.voice;if(n===void 0||!fd.STREAMING_VOICE_PATTERN.test(n))return;const o=r.format??"mp3",i=fd.mapStreamingFormat(o);if(i===void 0||t.trimStart().startsWith("<speak"))return;const s=this.extractLanguageCode(n),a=fd.STREAMING_SAMPLE_RATE_HZ,l=this;let c,u=!1,d=!1;const p=(async function*(){const m=await l.getClient();if(u)return;const f=Date.now(),g=m.streamingSynthesize();c=g;let y;const v=()=>{clearTimeout(y),y=setTimeout(()=>{d=!0,g.cancel()},fd.STREAMING_IDLE_TIMEOUT_MS)};let T=0,b=0;try{g.write({streamingConfig:{voice:{name:n,languageCode:s},streamingAudioConfig:{audioEncoding:i,sampleRateHertz:a,speakingRate:r.speed??1}}}),g.write({input:{text:t}}),g.end(),v();for await(const S of g){clearTimeout(y);const k=fd.streamedAudio(S);if(k===void 0){v();continue}b+=k.length,yield{data:k,format:o,index:T++,isFinal:!1,cumulativeSize:b,voice:n,sampleRate:a},v()}h.debug(`[GoogleTTSHandler] Streamed ${b} bytes in ${Date.now()-f}ms`)}catch(S){if(u)return;if(S instanceof ft)throw S;const k=S instanceof Error?S.message:"Unknown error";throw new ft({code:Tt.SYNTHESIS_FAILED,message:d?`Google TTS streaming synthesis stalled for ${fd.STREAMING_IDLE_TIMEOUT_MS}ms`:`Google TTS streaming synthesis failed: ${k}`,category:d?"network":"execution",severity:"high",retriable:!0,context:{voice:n,audioEncoding:i},originalError:S instanceof Error?S:void 0})}finally{clearTimeout(y),c=void 0,g.cancel()}})();return DS(p,()=>{u=!0,c?.cancel()})}extractLanguageCode(t){const r=t.split("-");if(r.length>=2)return`${r[0]}-${r[1]}`;throw new ft({code:Tt.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";case"pcm16":throw new ft({code:Tt.INVALID_INPUT,message:"Google Cloud TTS's buffered synthesis does not support pcm16 output. pcm16 is only delivered via native streaming, which requires a Chirp3-HD, Chirp-HD, or Journey voice and plain (non-SSML) text \u2014 check that both conditions hold, or request a different format.",category:"validation",severity:"medium",retriable:!1,context:{format:t}});default:throw new ft({code:Tt.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"}}}}),IT,TC,cF=E({"src/lib/voice/RealtimeVoiceAPI.ts"(){"use strict";z(),Wd(),pt(),uv(),IT=class{static registry=new Of("RealtimeProcessor");static sessions=new Map;static registerHandler(e,t){const r=e&&e.toLowerCase();this.registry.register(e,t),h.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 tr.providerNotSupported(e,this.registry.list());if(!n.isConfigured())throw tr.providerNotConfigured(e);if(n.isConnected())throw tr.sessionAlreadyActive(e);const o={...v4,...t};r&&n.on(r);try{h.debug(`[RealtimeProcessor] Connecting to provider: ${e}`);const i=await n.connect(o);return this.sessions.set(e.toLowerCase(),i),h.info(`[RealtimeProcessor] Connected to ${e} session: ${i.id}`),i}catch(i){if(r&&n.off(),i instanceof tr)throw i;const s=i instanceof Error?i.message:String(i||"Unknown error");throw tr.connectionFailed(s,e,i instanceof Error?i:void 0)}}static async disconnect(e){const t=this.getHandler(e);if(!t)throw tr.providerNotSupported(e,this.registry.list());if(!t.isConnected()){h.warn(`[RealtimeProcessor] No active session for provider: ${e}`);return}try{await t.disconnect(),this.sessions.delete(e.toLowerCase()),t.off(),h.info(`[RealtimeProcessor] Disconnected from ${e}`)}catch(r){if(r instanceof tr)throw r;const n=r instanceof Error?r.message:String(r||"Unknown error");throw tr.protocolError(`Disconnect failed: ${n}`,e,r instanceof Error?r:void 0)}}static async sendAudio(e,t){const r=this.getHandler(e);if(!r)throw tr.providerNotSupported(e,this.registry.list());if(!r.isConnected())throw tr.sessionNotActive(e);try{await r.sendAudio(t)}catch(n){if(n instanceof tr)throw n;const o=n instanceof Error?n.message:String(n||"Unknown error");throw tr.audioStreamError(o,e)}}static async sendText(e,t){const r=this.getHandler(e);if(!r)throw tr.providerNotSupported(e,this.registry.list());if(!r.isConnected())throw tr.sessionNotActive(e);if(!r.sendText)throw new tr({code:es.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 tr?n:new tr({code:es.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 tr.providerNotSupported(e,this.registry.list());if(!t.isConnected())throw tr.sessionNotActive(e);if(t.triggerResponse)try{await t.triggerResponse()}catch(r){throw r instanceof tr?r:new tr({code:es.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 tr.providerNotSupported(e,this.registry.list());if(t.isConnected()&&t.cancelResponse)try{await t.cancelResponse()}catch(r){throw r instanceof tr?r:new tr({code:es.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(),h.debug("[RealtimeProcessor] Cleared all handlers and sessions")}},TC=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 nYt(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 Icn(e){return Z_[e]?.mimeType??"application/octet-stream"}function Rcn(e){return Z_[e]?.extension??".bin"}function Pcn(e,t,r){const n=t??nYt(e);if(n)try{switch(n){case"wav":return Mcn(e);case"mp3":return Ocn(e);case"ogg":case"opus":return Dcn(e);default:return r?e.length/(r*2):void 0}}catch(o){h.debug(`[audio-utils] Failed to calculate duration: ${o instanceof Error?o.message:String(o)}`);return}}function Mcn(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),i=e.readUInt32LE(t+12),s=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=s/8*o;return c/u/i}a+=8+c+c%2}}t+=8+n+n%2}}function Ocn(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,i=e[t+2]>>2&3,a={3:[44100,48e3,32e3],2:[22050,24e3,16e3],0:[11025,12e3,8e3]}[r]?.[i],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 Dcn(e){return e.length*8/64e3}async function Ncn(e,t,r,n={}){if(t===r)return e;throw h.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 Lcn(e,t=16e3,r=16){const n=r/8,o=Buffer.alloc(e.length*n);for(let i=0;i<e.length;i++){const s=Math.max(-1,Math.min(1,e[i])),a=i*n;switch(r){case 8:o.writeUInt8(Math.round((s+1)*127.5),a);break;case 16:o.writeInt16LE(Math.round(s*32767),a);break;case 24:{const l=Math.round(s*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(s*2147483647),a);break}}return o}function Fcn(e,t=16){const r=t/8,n=Math.floor(e.length/r),o=[];for(let i=0;i<n;i++){const s=i*r;switch(t){case 8:o.push(e.readUInt8(s)/127.5-1);break;case 16:o.push(e.readInt16LE(s)/32767);break;case 24:{const a=e.readUInt8(s)|e.readUInt8(s+1)<<8|e.readUInt8(s+2)<<16;o.push((a>8388607?a-16777216:a)/8388607);break}case 32:o.push(e.readInt32LE(s)/2147483647);break}}return o}function $cn(e,t,r){if(t<=0||r<=0||t===r)return e;const n=t/r,o=Math.round(e.length/n),i=[];for(let s=0;s<o;s++){const a=s*n,l=Math.floor(a),c=Math.min(l+1,e.length-1),u=a-l,d=e[l]*(1-u)+e[c]*u;i.push(d)}return i}function Ucn(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 oYt(e,t=16e3,r=1,n=16){const o=Buffer.alloc(44),i=t*r*(n/8),s=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(i,28),o.writeUInt16LE(s,32),o.writeUInt16LE(n,34),o.write("data",36),o.writeUInt32LE(e,40),o}function iYt(e,t=16e3,r=1,n=16){const o=oYt(e.length,t,r,n);return Buffer.concat([o,e])}function Bcn(e,t,r=16e3,n=2){if(t<=0||r<=0||n<=0)return[e];const o=r*n/1e3,i=Math.round(t*o);if(i<=0)return[e];const s=[];for(let a=0;a<e.length;a+=i){const l=Math.min(a+i,e.length);s.push(e.subarray(a,l))}return s}var sYt,aYt,lYt=E({"src/lib/voice/audio-utils.ts"(){"use strict";pt(),z(),sYt={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])},aYt={wav:"audio/wav",mp3:"audio/mpeg",ogg:"audio/ogg",opus:"audio/opus"}}});function zcn(e){return{[Symbol.asyncIterator](){const t=[];let r=null,n=null,o=!1,i=null;const s=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=>{i=u,n&&(n(u),r=null,n=null)};e.on("chunk",s),e.on("end",a),e.on("error",l);const c=()=>{e.off("chunk",s),e.off("end",a),e.off("error",l)};return{async next(){if(i)throw i;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 Gcn(e,t={}){const r=new RT(t);return(async()=>{try{for await(const n of e)r.write(n)||await new Promise(i=>r.once("drain",i));r.end()}catch(n){r.emit("error",n instanceof Error?n:new Error(String(n)))}})(),r}var gle,RT,cYt,uYt,qcn=E({"src/lib/voice/stream-handler.ts"(){"use strict";Wn(),z(),gle={chunkDurationMs:100,sampleRate:16e3,bytesPerSample:2,format:"wav",highWaterMark:64*1024,bufferTimeoutMs:5e3},RT=class extends un{config;chunkSize;buffer;chunkIndex;timestampMs;isPaused;isEnded;pendingData;bufferTimeout;constructor(e={}){if(super(),this.config={...gle,...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&&(h.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}}},cYt=class extends un{streams;config;constructor(e={}){super(),this.streams=new Map,this.config={...gle,...e}}addStream(e){if(this.streams.has(e))throw new Error(`Stream ${e} already exists`);const t=new RT(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}},uYt=class extends un{consumers;input;constructor(e={}){super(),this.consumers=new Map,this.input=new RT(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}}}}),PT,dYt=E({"src/lib/voice/providers/AzureTTS.ts"(){"use strict";z(),al(),PT=class eSr{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 ft({code:Tt.PROVIDER_NOT_CONFIGURED,message:"Azure Speech key not configured",category:"configuration",severity:"high",retriable:!1});if(this.voicesCache&&Date.now()-this.voicesCache.timestamp<eSr.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 ft({code:Tt.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 s=(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&&(s=s.filter(a=>a.languageCode.toLowerCase().startsWith(t.toLowerCase())||a.languageCode.toLowerCase()===t.toLowerCase())),t||(this.voicesCache={voices:s,timestamp:Date.now()}),s}catch(r){if(r instanceof ft)throw r;const n=r instanceof Error?r.message:String(r||"Unknown error");throw h.error(`[AzureTTSHandler] Failed to get voices: ${n}`),new ft({code:Tt.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 ft({code:Tt.PROVIDER_NOT_CONFIGURED,message:"Azure Speech key not configured",category:"configuration",severity:"high",retriable:!1});const n=Date.now(),o=r;try{const i=r.voice??"en-US-JennyNeural",s=o.outputFormat??this.mapFormat(r.format??"mp3"),a=this.buildSSML(t,i,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":s},body:a,signal:l.signal})}catch(g){throw g instanceof Error&&g.name==="AbortError"?new ft({code:Tt.SYNTHESIS_FAILED,message:"Azure TTS request timed out after 30 seconds",category:"network",severity:"high",retriable:!0,originalError:g}):g}finally{clearTimeout(c)}if(!u.ok){const g=await u.text();throw new Error(`HTTP ${u.status}: ${g}`)}const d=Date.now()-n,p=await u.arrayBuffer(),m=Buffer.from(p),f={buffer:m,format:this.effectiveFormat(s),size:m.length,voice:i,sampleRate:this.getSampleRate(s),metadata:{latency:d,provider:"azure-tts",requestedFormat:r.format,outputFormat:s,region:this.region}};return h.info(`[AzureTTSHandler] Synthesized ${m.length} bytes in ${d}ms`),f}catch(i){if(i instanceof ft)throw i;const s=i instanceof Error?i.message:String(i||"Unknown error");throw h.error(`[AzureTTSHandler] Synthesis failed: ${s}`),new ft({code:Tt.SYNTHESIS_FAILED,message:`Synthesis failed: ${s}`,category:"execution",severity:"high",retriable:!0,context:{textLength:t.length},originalError:i instanceof Error?i: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 i=n.speed?`${Math.round((n.speed-1)*100)}%`:"0%",s=n.pitch??0,a=s>=0?`+${Math.round(s)}st`:`${Math.round(s)}st`;return`<speak version="1.0" xmlns="http://www.w3.org/2001/10/synthesis" xml:lang="${this.escapeXml(this.extractLanguage(r))}">
|
|
2153
2153
|
<voice name="${this.escapeXml(r)}">
|
|
2154
2154
|
<prosody rate="${i}" pitch="${a}">
|
|
2155
2155
|
${this.escapeXml(t)}
|
|
@@ -2520,7 +2520,7 @@ Answer:`;return(await It(this.generationProvider.generate({prompt:i,systemPrompt
|
|
|
2520
2520
|
|
|
2521
2521
|
-- Return integers (tokens * 1000 to keep 3 decimal places)
|
|
2522
2522
|
return { math.floor(tokens * 1000), lastRefill, consumed }
|
|
2523
|
-
`,1,i,String(t),String(r),String(n),String(this.ttlSeconds),e);if(a==null)return null;const[l,c,u]=a;return{bucket:{tokens:l/1e3,lastRefill:c,userId:e},consumed:u===1}}catch(o){return h.warn("Redis atomicConsume failed, falling back to non-atomic:",o),null}}async healthCheck(){try{return await(await this.getClient()).ping()==="PONG"}catch{return!1}}async cleanup(){this.client&&(await this.client.quit(),this.client=null,this.initPromise=null)}},cme=class{storage;config;constructor(e,t){this.config={message:"Rate limit exceeded. Please try again later.",...e},this.storage=t||new lme(Math.max(6e4,e.windowMs),e.windowMs)}getLimitForUser(e){if(this.config.userLimits&&e.id in this.config.userLimits)return this.config.userLimits[e.id];if(this.config.roleLimits){let t=this.config.maxRequests;for(const r of e.roles)r in this.config.roleLimits&&(t=Math.max(t,this.config.roleLimits[r]));return t}return this.config.maxRequests}shouldSkipRateLimit(e){return!this.config.skipRoles||this.config.skipRoles.length===0?!1:e.roles.some(t=>this.config.skipRoles?.includes(t)??!1)}async consume(e){if(this.shouldSkipRateLimit(e))return{allowed:!0,remaining:1/0,resetIn:0,limit:1/0};const t=e.id,r=this.getLimitForUser(e),n=Date.now();if(this.storage.atomicConsume){const l=await this.storage.atomicConsume(t,r,this.config.windowMs,n);if(l!==null){const{bucket:c,consumed:u}=l;return u?{allowed:!0,remaining:Math.floor(c.tokens),resetIn:Math.ceil((r-c.tokens)/r*this.config.windowMs),limit:r}:{allowed:!1,remaining:0,resetIn:Math.ceil((1-c.tokens)/r*this.config.windowMs),limit:r,error:this.config.message}}}let o=await this.storage.getBucket(t);o||(o={tokens:r,lastRefill:n,userId:t});const s=(n-o.lastRefill)/this.config.windowMs*r;return o.tokens=Math.min(r,o.tokens+s),o.lastRefill=n,o.tokens>=1?(o.tokens-=1,await this.storage.setBucket(t,o),{allowed:!0,remaining:Math.floor(o.tokens),resetIn:Math.ceil((r-o.tokens)/r*this.config.windowMs),limit:r}):(await this.storage.setBucket(t,o),{allowed:!1,remaining:0,resetIn:Math.ceil((1-o.tokens)/r*this.config.windowMs),limit:r,error:this.config.message})}async getStatus(e){if(this.shouldSkipRateLimit(e))return{allowed:!0,remaining:1/0,resetIn:0,limit:1/0};const t=this.getLimitForUser(e),r=await this.storage.getBucket(e.id);if(!r)return{allowed:!0,remaining:t,resetIn:0,limit:t};const i=(Date.now()-r.lastRefill)/this.config.windowMs*t,s=Math.min(t,r.tokens+i);return{allowed:s>=1,remaining:Math.floor(s),resetIn:s>=1?0:Math.ceil((1-s)/t*this.config.windowMs),limit:t}}async resetUser(e){await this.storage.deleteBucket(e),h.debug(`Rate limit reset for user: ${mkn(e)}`)}async healthCheck(){return this.storage.healthCheck()}async cleanup(){await this.storage.cleanup()}};function hkn(e,t){const r=new cme(e,t);return async n=>{const o=await r.consume(n.user);if(!o.allowed){const i=pEr(o);return{proceed:!1,rateLimitResult:o,response:i}}return{proceed:!0,rateLimitResult:o}}}function fkn(e,t,r){const n=new cme(t,r);return async o=>{const i=await e(o);if(!i.proceed||!i.context)return i;const s=await n.consume(i.context.user);return s.allowed?{proceed:!0,context:i.context,rateLimitResult:s}:{proceed:!1,context:i.context,rateLimitResult:s,response:pEr(s)}}}function pEr(e){return new Response(JSON.stringify({error:"Too Many Requests",message:e.error||"Rate limit exceeded",statusCode:429,retryAfter:Math.ceil(e.resetIn/1e3),limit:e.limit,remaining:e.remaining}),{status:429,headers:{"Content-Type":"application/json","Retry-After":String(Math.ceil(e.resetIn/1e3)),"X-RateLimit-Limit":String(e.limit),"X-RateLimit-Remaining":String(e.remaining),"X-RateLimit-Reset":String(Date.now()+e.resetIn)}})}function gkn(e){return e.type==="redis"&&e.redis?new dEr(e.redis):new lme(e.cleanupIntervalMs)}Kr(),z(),Xr(),Sr();function gc(e){return e.length<=4?"***":`${e.slice(0,4)}***`}var mEr=5e3,V1=class{sessions=new Map;userSessions=new Map;async get(e){const t=this.sessions.get(e);return t?t.expiresAt&&new Date>t.expiresAt?(await this.delete(e),null):t:null}async set(e){this.sessions.set(e.id,e);let t=this.userSessions.get(e.user.id);t||(t=new Set,this.userSessions.set(e.user.id,t)),t.add(e.id)}async delete(e){const t=this.sessions.get(e);if(t){const r=this.userSessions.get(t.user.id);r&&(r.delete(e),r.size===0&&this.userSessions.delete(t.user.id)),this.sessions.delete(e)}}async getUserSessions(e){const t=this.userSessions.get(e);if(!t)return[];const r=[];for(const n of t){const o=await this.get(n);o&&r.push(o)}return r}async deleteUserSessions(e){const t=this.userSessions.get(e);if(t){for(const r of t)this.sessions.delete(r);this.userSessions.delete(e)}}async clear(){this.sessions.clear(),this.userSessions.clear()}async isHealthy(){return!0}},ume=class{prefix;ttl;redisUrl;client=null;initPromise=null;constructor(e){this.redisUrl=e.url,this.prefix=e.prefix||"neurolink:sessions:",this.ttl=e.ttl||3600}async getClient(){return this.client?this.client:(this.initPromise||(this.initPromise=this.createClient()),this.initPromise)}async createClient(){try{const r=(await import("redis")).createClient({url:this.redisUrl});return r.on("error",n=>{h.error("Redis session client error:",n.message)}),await It(r.connect(),mEr,`Redis session client connect timed out after ${mEr}ms`),this.client=r,r}catch(e){throw this.initPromise=null,h.error('Redis client not available. Ensure the "redis" package is installed and Redis is reachable when using storage: "redis".'),e instanceof Error?e:new Error("Redis client not available")}}sessionKey(e){return`${this.prefix}${e}`}userSessionsKey(e){return`${this.prefix}user:${e}`}async get(e){try{const r=await(await this.getClient()).get(this.sessionKey(e));if(!r)return null;if(typeof r!="string")return h.warn("Unexpected Redis session payload type",{sessionId:gc(e),type:typeof r}),null;const n=JSON.parse(r);return n.createdAt=new Date(n.createdAt),n.expiresAt!==null&&n.expiresAt!==void 0&&(n.expiresAt=new Date(n.expiresAt)),n.expiresAt&&new Date>n.expiresAt?(await this.delete(e),null):n}catch(t){return h.error("Redis session get error:",t),null}}async set(e){try{const t=await this.getClient(),r=e.expiresAt?Math.max(1,Math.floor((e.expiresAt.getTime()-Date.now())/1e3)):this.ttl;await t.setEx(this.sessionKey(e.id),r,JSON.stringify(e)),await t.sAdd(this.userSessionsKey(e.user.id),e.id),await t.expire(this.userSessionsKey(e.user.id),this.ttl)}catch(t){throw h.error("Redis session set error:",t),t}}async delete(e){try{const t=await this.getClient(),r=await t.get(this.sessionKey(e));if(r)if(typeof r!="string")h.warn("Unexpected Redis session payload type during delete",{sessionId:gc(e),type:typeof r});else try{const n=JSON.parse(r);await t.sRem(this.userSessionsKey(n.user.id),e)}catch{h.warn(`Failed to parse session data for cleanup: ${gc(e)}`)}await t.del(this.sessionKey(e))}catch(t){h.error("Redis session delete error:",t)}}async getUserSessions(e){try{const r=await(await this.getClient()).sMembers(this.userSessionsKey(e)),n=[];for(const o of r){const i=await this.get(o);i&&n.push(i)}return n}catch(t){return h.error("Redis getUserSessions error:",t),[]}}async deleteUserSessions(e){try{const t=await this.getClient(),r=await t.sMembers(this.userSessionsKey(e));for(const n of r)await t.del(this.sessionKey(n));await t.del(this.userSessionsKey(e))}catch(t){h.error("Redis deleteUserSessions error:",t)}}async clear(){try{const e=await this.getClient();let t="0";do{const r=await e.scan(t,{MATCH:`${this.prefix}*`,COUNT:100});t=r.cursor,r.keys.length>0&&await e.del(r.keys)}while(t!=="0")}catch(e){h.error("Redis clear error:",e)}}async isHealthy(){try{return await(await this.getClient()).ping()==="PONG"}catch{return!1}}async disconnect(){this.client&&(await this.client.quit(),this.client=null,this.initPromise=null)}},ykn=class{storage;config;constructor(e={}){this.config={...e,duration:e.duration||3600,autoRefresh:e.autoRefresh??!0,refreshThreshold:e.refreshThreshold||300,storage:e.storage||"memory"},this.storage=this.createStorage()}createStorage(){return this.config.storage==="redis"?this.config.redis?.url?new ume({url:this.config.redis.url,prefix:this.config.redis.prefix,ttl:this.config.redis.ttl||this.config.duration}):(h.warn("Redis URL not provided, falling back to memory storage"),new V1):new V1}async createSession(e,t){return mt({name:"neurolink.auth.session.create",tracer:Be.auth,attributes:{"auth.user_id":gc(e.id),"auth.storage":this.config.storage??"memory"}},async()=>this._createSession(e,t))}async _createSession(e,t){const r=crypto.randomUUID(),n=new Date,o=this.config.duration||3600,i={id:r,user:e,createdAt:n,expiresAt:new Date(n.getTime()+o*1e3),isValid:!0,ipAddress:t?.ipAddress,userAgent:t?.userAgent,deviceId:t?.deviceId};return await this.storage.set(i),h.debug(`Session created: ${gc(r)} for user: ${gc(e.id)}`),i}async getSession(e,t=this.config.autoRefresh){return mt({name:"neurolink.auth.session.get",tracer:Be.auth,attributes:{"auth.session_id":gc(e),"auth.auto_refresh":t??!1}},async r=>{const n=await this._getSession(e,t);return r.setAttribute("auth.found",n!==null),n})}async _getSession(e,t=this.config.autoRefresh){const r=await this.storage.get(e);return r?t&&this.shouldRefresh(r)?this.refreshSession(e):r:null}shouldRefresh(e){if(!e.expiresAt)return!1;const t=this.config.refreshThreshold||300;return(e.expiresAt.getTime()-Date.now())/1e3<t}async refreshSession(e){return mt({name:"neurolink.auth.session.refresh",tracer:Be.auth,attributes:{"auth.session_id":gc(e)}},async t=>{const r=await this.storage.get(e);if(!r)return t.setAttribute("auth.found",!1),null;const n=this.config.duration||3600;return r.expiresAt=new Date(Date.now()+n*1e3),await this.storage.set(r),t.setAttribute("auth.found",!0),h.debug(`Session refreshed: ${gc(e)}`),r})}async destroySession(e){await this.storage.delete(e),h.debug(`Session destroyed: ${gc(e)}`)}async getUserSessions(e){return this.storage.getUserSessions(e)}async destroyAllUserSessions(e){await this.storage.deleteUserSessions(e),h.debug(`All sessions destroyed for user: ${gc(e)}`)}async validateSession(e){return mt({name:"neurolink.auth.session.validate",tracer:Be.auth,attributes:{"auth.session_id":gc(e)}},async t=>{const r=await this.storage.get(e),n=r!==null&&r.isValid;return t.setAttribute("auth.valid",n),n})}async updateSessionMetadata(e,t){const r=await this.storage.get(e);return r?(r.metadata={...r.metadata,...t},await this.storage.set(r),r):null}async isHealthy(){return this.storage.isHealthy()}async clear(){await this.storage.clear()}};function vkn(e){return e.storage==="redis"?e.redis?.url?new ume({url:e.redis.url,prefix:e.redis.prefix,ttl:e.redis.ttl||e.duration}):(h.warn("Redis URL not provided, falling back to memory storage"),new V1):new V1}CA();var wkn="neurolink__resourceId",Tkn="neurolink__threadId",bkn="neurolink__",_kn=class{registry=new Map;constructor(e){if(Array.isArray(e))for(const[t,r]of e)this.registry.set(t,r);else if(e)for(const[t,r]of Object.entries(e))this.registry.set(t,r)}set(e,t){this.registry.set(e,t)}get(e){return this.registry.get(e)}has(e){return this.registry.has(e)}delete(e){return this.registry.delete(e)}get size(){return this.registry.size}mergeClientContext(e){for(const[t,r]of Object.entries(e))t.startsWith(bkn)&&this.registry.has(t)||this.registry.has(t)||this.registry.set(t,r)}toJSON(){const e={};for(const[t,r]of this.registry.entries())this.isSerializable(r)&&(e[t]=r);return e}isSerializable(e){if(e==null)return!0;const t=typeof e;if(t==="function"||t==="symbol")return!1;try{return JSON.stringify(e),!0}catch{return!1}}};function Ekn(e){return async(t,r)=>{const n=await e.authenticateToken(t,r);return n.valid&&n.user?{id:n.user.id,email:n.user.email,roles:n.user.roles}:null}}Kjt(),Yjt();var hEr=class{tripwires=[];register(e){const t=this.tripwires.findIndex(r=>r.id===e.id);t!==-1?this.tripwires[t]=e:this.tripwires.push(e)}unregister(e){const t=this.tripwires.findIndex(r=>r.id===e);return t!==-1?(this.tripwires.splice(t,1),!0):!1}evaluate(e){let t=null,r=null,n=null;for(const o of this.tripwires){let i;try{i=o.condition(e)}catch{continue}if(!i)continue;const s=typeof o.message=="function"?o.message(e):o.message,a={triggered:!0,tripwire:o,message:s,action:o.action};o.action==="abort"&&t===null?t=a:o.action==="warn"&&r===null?r=a:o.action==="log"&&n===null&&(n=a)}return t!==null?t:r!==null?r:n!==null?n:{triggered:!1}}evaluateAll(e){const t=[];for(const r of this.tripwires){let n;try{n=r.condition(e)}catch{continue}if(!n)continue;const o=typeof r.message=="function"?r.message(e):r.message;t.push({triggered:!0,tripwire:r,message:o,action:r.action})}return t}getTripwires(){return[...this.tripwires]}},Skn={id:"max-tokens",name:"Maximum Tokens Hit",description:"Triggers when the model stopped because it reached the token output limit.",action:"abort",condition:e=>e.finishReason==="length",message:"Model stopped at token limit \u2014 response may be truncated."},kkn={id:"empty-response",name:"Empty Response",description:"Triggers when the model returns an empty or whitespace-only response.",action:"abort",condition:e=>e.responseText!==void 0&&e.responseText.trim().length===0,message:"Model returned an empty response."},xkn={id:"repetition-loop",name:"Repetition Loop",description:"Detects when the model is generating repetitive content, indicating a loop.",action:"warn",condition:e=>{const t=e.responseText;if(!t)return!1;const r=t.split(/\s+/);if(r.length<30)return!1;const n=10,o=new Map;let i=0;const s=r.length-n+1;for(let a=0;a<=r.length-n;a++){const l=r.slice(a,a+n).join(" "),c=(o.get(l)??0)+1;o.set(l,c),c>1&&i++}return i/s>.2},message:"Response contains highly repetitive content \u2014 possible generation loop."},Akn={id:"input-too-long",name:"Input Too Long",description:"Triggers when the input text exceeds the recommended length.",action:"abort",condition:e=>e.inputText!==void 0&&e.inputText.length>1e5,message:e=>`Input is ${e.inputText?.length??0} characters \u2014 exceeds the 100 000-character limit.`},Ckn={id:"too-many-messages",name:"Too Many Messages",description:"Triggers when the conversation message count exceeds the recommended maximum.",action:"warn",condition:e=>e.messageCount!==void 0&&e.messageCount>100,message:e=>`Conversation has ${e.messageCount} messages \u2014 consider summarising context.`},Ikn={id:"response-too-long",name:"Response Too Long",description:"Triggers when the response text exceeds the recommended length.",action:"warn",condition:e=>e.responseText!==void 0&&e.responseText.length>5e4,message:e=>`Response is ${e.responseText?.length??0} characters \u2014 exceeds the 50 000-character limit.`},Rkn={id:"high-latency",name:"High Latency",description:"Triggers when the measured response latency exceeds the acceptable threshold.",action:"warn",condition:e=>e.latencyMs!==void 0&&e.latencyMs>3e4,message:e=>`Response latency was ${e.latencyMs}ms \u2014 exceeds the 30 000ms threshold.`},fEr=[Skn,kkn,xkn,Akn,Ckn,Ikn,Rkn];function Pkn(){const e=new hEr;for(const t of fEr)e.register(t);return e}Uae(),xKt(),Iqt(),MKt(),DKt(),RKt();var v6=new Map;function hd(e){v6.set(e.descriptor.id,e)}function Mkn(){return[...v6.values()].map(e=>e.descriptor)}function w6(){return[...v6.keys()]}async function gEr(e){const t=v6.get(e);if(!t)throw new Error(`No local-usage reader registered for "${e}". Registered: ${w6().join(", ")||"(none)"}`);return t.factory()}hd({descriptor:{id:"claude-code",displayName:"Claude Code",verified:!0,dedupStrategy:"message-id-keep-max",costConfidence:"modeled",requiresSqlite:!1},factory:async()=>{const{createClaudeCodeReader:e}=await Promise.resolve().then(()=>(hpn(),wfr));return e()}}),hd({descriptor:{id:"codex",displayName:"Codex",verified:!0,dedupStrategy:"session-dag",costConfidence:"unavailable",requiresSqlite:!1},factory:async()=>{const{createCodexReader:e}=await Promise.resolve().then(()=>(vpn(),_fr));return e()}}),hd({descriptor:{id:"opencode",displayName:"OpenCode",verified:!0,dedupStrategy:"rowid-high-water-mark",costConfidence:"unavailable",requiresSqlite:!0},factory:async()=>{const{createOpenCodeReader:e}=await Promise.resolve().then(()=>(bpn(),iyr));return e()}}),hd({descriptor:{id:"qwen-code",displayName:"Qwen Code",verified:!0,dedupStrategy:"message-id-keep-max",costConfidence:"unavailable",requiresSqlite:!1},factory:async()=>{const{createQwenCodeReader:e}=await Promise.resolve().then(()=>(xpn(),ayr));return e()}}),hd({descriptor:{id:"gemini-cli",displayName:"Gemini CLI",verified:!0,dedupStrategy:"message-id-keep-max",costConfidence:"unavailable",requiresSqlite:!1},factory:async()=>{const{createGeminiCliReader:e}=await Promise.resolve().then(()=>(Mpn(),dyr));return e()}}),hd({descriptor:{id:"copilot",displayName:"Copilot CLI",verified:!0,dedupStrategy:"rowid-high-water-mark",costConfidence:"unavailable",requiresSqlite:!0},factory:async()=>{const{createCopilotCliReader:e}=await Promise.resolve().then(()=>(Lpn(),fyr));return e()}}),hd({descriptor:{id:"cursor",displayName:"Cursor",verified:!0,dedupStrategy:"last-write-wins",costConfidence:"unavailable",requiresSqlite:!0,requestUnit:"session-snapshot"},factory:async()=>{const{createCursorReader:e}=await Promise.resolve().then(()=>(Gpn(),yyr));return e()}}),hd({descriptor:{id:"grok",displayName:"Grok Build",verified:!0,dedupStrategy:"last-write-wins",costConfidence:"unavailable",requiresSqlite:!1},factory:async()=>{const{createGrokReader:e}=await Promise.resolve().then(()=>(Zpn(),byr));return e()}}),hd({descriptor:{id:"hermes",displayName:"Hermes Agent",verified:!0,dedupStrategy:"last-write-wins",costConfidence:"modeled",requiresSqlite:!0},factory:async()=>{const{createHermesReader:e}=await Promise.resolve().then(()=>(nmn(),kyr));return e()}});async function Okn(e){const t={},r=[],n=[],o=[],i=e?.only,s=i?w6().filter(a=>i.includes(a)):w6();for(const a of s)try{const l=await gEr(a);if(!await l.detect()){n.push(a);continue}const c=await l.scan(e);t[a]=c.totals,o.push(...c.errors)}catch(l){r.push({cliId:a,message:l instanceof Error?l.message:String(l)})}return{generatedAt:new Date().toISOString(),totals:t,failures:r,notInstalled:n,scanErrors:o}}var Dkn="1.0.0";async function Nkn(e,t){return await Yn.createProvider(e||"bedrock",t)}async function Lkn(e,t,r){return await Yn.createProviderWithFallback(e||"bedrock",t||"vertex",r)}async function Fkn(e,t){return await Yn.createBestProvider(e,t)}async function $kn(){try{return!!await dBr()}catch{return!1}}async function Ukn(){return pBr()}async function Bkn(e){return await new AT().generateText(e)}Ga();var zkn=e=>typeof e=="object"&&e!==null&&typeof e.doGenerate=="function",Gkn=e=>typeof e=="object"&&e!==null&&typeof e.getModel=="function",qkn=(e,t,r)=>{let n;const o=async()=>{const s=await Yn.createProvider(e,t,!1,void 0,void 0,r);if(!Gkn(s))throw new Error(`[NeuroLink:browser] provider "${e}" exposes no getModel()`);const a=await s.getModel();if(!zkn(a))throw new Error(`[NeuroLink:browser] provider "${e}" resolved a model handle that cannot generate`);return a},i=()=>n??=o();return{specificationVersion:"v3",provider:e,modelId:t,supportedUrls:{},doGenerate:async s=>(await i()).doGenerate(s),doStream:async s=>(await i()).doStream(s)}},dme=(e,t)=>(n={})=>{const o=n.credentials??(n.apiKey||n.baseURL?{[e]:{...n.apiKey?{apiKey:n.apiKey}:{},...n.baseURL?{baseURL:n.baseURL}:{}}}:void 0),i=(s=t)=>qkn(e,s,o);return Object.assign(i,{languageModel:i,chat:i,provider:e})},yEr=dme("anthropic","claude-sonnet-4-5"),Vkn=yEr(),vEr=dme("openai","gpt-4o-mini"),jkn=vEr(),wEr=dme("mistral","mistral-small-latest"),Hkn=wEr();typeof globalThis.setImmediate>"u"&&(globalThis.setImmediate=(e,...t)=>setTimeout(e,0,...t),globalThis.clearImmediate=e=>clearTimeout(e)),typeof globalThis.process>"u"&&(globalThis.process=new Proxy({env:{},version:"v24.0.0",platform:"browser",argv:[],pid:1,ppid:0,arch:"wasm",cwd:()=>"/",exit:()=>{},on:()=>globalThis.process,off:()=>globalThis.process,once:()=>globalThis.process,emit:()=>!1,removeListener:()=>globalThis.process,addListener:()=>globalThis.process,stdout:{write:()=>!0,on:()=>{}},stderr:{write:()=>!0,on:()=>{}},stdin:{on:()=>{}},nextTick:(e,...t)=>setTimeout(()=>e(...t),0),hrtime:Object.assign(e=>{const t=performance.now()*1e6,r=Math.floor(t/1e9),n=Math.floor(t%1e9);return e?[r-e[0],n-e[1]]:[r,n]},{bigint:()=>BigInt(Math.floor(performance.now()*1e6))}),memoryUsage:()=>({rss:0,heapTotal:0,heapUsed:0,external:0,arrayBuffers:0}),cpuUsage:()=>({user:0,system:0}),versions:{browser:"1.0.0",v8:"0",modules:"0"},release:{name:"browser"},uptime:()=>performance.now()/1e3,title:"browser",execPath:"/browser",execArgv:[],features:{},config:{},kill:()=>{},abort:()=>{}},{get(e,t){return t in e?e[t]:()=>{}}})),typeof globalThis.Buffer>"u"&&(globalThis.Buffer=class extends Uint8Array{static from(t,r){if(typeof t=="string"){const n=(r||"utf8").toLowerCase();if(n==="base64"){const o=atob(t),i=o.length,s=new Uint8Array(i);for(let a=0;a<i;a++)s[a]=o.charCodeAt(a);return s}if(n==="hex"){const o=t.length,i=new Uint8Array(o/2);for(let s=0;s<o;s+=2)i[s/2]=parseInt(t.substring(s,s+2),16);return i}return new TextEncoder().encode(t)}return new Uint8Array(t)}static alloc(t){return new Uint8Array(t)}static isBuffer(t){return t instanceof Uint8Array}static concat(t){const r=t.reduce((i,s)=>i+s.length,0),n=new Uint8Array(r);let o=0;for(const i of t)n.set(i,o),o+=i.length;return n}static byteLength(t){return new TextEncoder().encode(t).length}toString(t){switch((t||"utf8").toLowerCase()){case"utf8":case"utf-8":return new TextDecoder().decode(this);case"hex":return Array.from(new Uint8Array(this.buffer,this.byteOffset,this.byteLength)).map(n=>n.toString(16).padStart(2,"0")).join("");case"base64":{let n="";const o=this.byteLength;for(let i=0;i<o;i++)n+=String.fromCharCode(this[i]);return btoa(n)}case"binary":case"latin1":{let n="";const o=this.byteLength;for(let i=0;i<o;i++)n+=String.fromCharCode(this[i]);return n}default:return new TextDecoder().decode(this)}}}),typeof globalThis.global>"u"&&(globalThis.global=globalThis);export{Ibe as AGENT_ATTRIBUTES,Rhn as AGGRESSIVE_FALLBACK_WORKFLOW,Yn as AIProviderFactory,sI as AIProviderName,Z_ as AUDIO_FORMAT_DETAILS,wd as AUTORESEARCH_DEFAULTS,At as AVATAR_ERROR_CODES,Byr as AbortError,Z3 as Agent,Q3 as AgentCoordinator,_F as AgentExecuteRequestSchema,K3 as AgentExposureManager,Bae as AgentNetwork,VT as AlreadyRunningError,SP as AlwaysSampler,mS as AnswerRelevancyScorer,FL as AuthContextHolder,OL as AuthErrorCodes,xt as AuthErrorFactory,ckn as AuthMiddlewareError,aEr as AuthMiddlewareErrorCodes,Wmr as AuthProviderError,Ss as AuthProviderFactory,lkn as AuthProviderRegistry,Wr as AuthenticationError,kI as AuthorizationError,kt as AvatarError,Ep as AvatarProcessor,Qf as AzureSTT,Qf as AzureSTTHandler,PT as AzureTTS,PT as AzureTTSHandler,tvr as BALANCED_ADAPTIVE_WORKFLOW,_l as BaseAuthProvider,ty as BaseError,IP as BaseFactory,ol as BaseLLMScorer,TC as BaseRealtimeHandler,jV as BaseRegistry,rv as BaseRuleScorer,xf as BaseScorer,jT as BaseServerAdapter,bS as BatchStrategy,yT as BeatovenMusic,yT as BeatovenMusicHandler,P6 as BedrockModels,fS as BiasDetectionScorer,nC as CLASSIFIER_CONTEXT_SCOPES,h0 as CLASSIFIER_DIFFICULTIES,qP as CODE_GENERATION_PIPELINE,UP as COMPREHENSIVE_PIPELINE,Chn as CONSENSUS_3_FAST_WORKFLOW,rvr as CONSENSUS_3_WORKFLOW,q_r as CSVLoader,GP as CUSTOMER_SUPPORT_PIPELINE,DT as CartesiaTTS,DT as CartesiaTTSHandler,M_r as CharacterChunker,nkn as ChromaVectorStore,Ch as ChunkerRegistry,Bre as CircuitBreakerManager,jp as CircuitBreakerOpenError,Hse as ClassifierRouter,Fyr as ClientAuthenticationError,$yr as ClientAuthorizationError,umn as ClientConfigurationError,cmn as ClientConnectionError,en as ClientErrorCode,lb as ClientNetworkError,pu as ClientNeuroLinkError,Cue as ClientProviderError,Nyr as ClientRateLimitError,Aue as ClientTimeoutError,Lyr as ClientValidationError,kHt as CohereRelevanceScorer,lmn as ConfigManager,Rdr as ConfigurationError,mmn as ContentFilterError,EP as ContextBuilder,O0e as ContextConverter,b5 as ContextFactory,pmn as ContextLengthError,hS as ContextPrecisionScorer,pS as ContextRelevancyScorer,Ya as ConversationMemoryError,xHt as CrossEncoderReranker,Ny as DECISION_PROVIDERS,cre as DEFAULT_ALIAS_BOOST,Dre as DEFAULT_BATCH_CONFIG,Nre as DEFAULT_CACHE_CONFIG,ire as DEFAULT_CANDIDATE_LIMIT,xN as DEFAULT_COMPACTION_THRESHOLD,T5 as DEFAULT_CONFIG,lre as DEFAULT_EXACT_BOOST,ore as DEFAULT_FIELD_WEIGHTS,Ku as DEFAULT_HTTP_RETRY_CONFIG,JG as DEFAULT_IMAGE_GEN_CONFIG,wbe as DEFAULT_IMAGE_MAX_SIZE_MB,vbe as DEFAULT_IMAGE_TIMEOUT_MS,X_ as DEFAULT_INFERENCE_KINDS,PP as DEFAULT_LLM_SCORER_CONFIG,ure as DEFAULT_MAX_CONTEXT_TOKENS,y4 as DEFAULT_MODEL_ALIASES,_be as DEFAULT_PROVIDER_CONFIGS,Gre as DEFAULT_RATE_LIMIT_CONFIG,v4 as DEFAULT_REALTIME_CONFIG,ON as DEFAULT_RECENT_TURNS,are as DEFAULT_RELATION_LIMIT,sre as DEFAULT_RESULT_LIMIT,zG as DEFAULT_RETRY_CONFIG,Eoe as DEFAULT_ROUTER_CONFIG,rre as DEFAULT_ROUTER_PROMPT_PREFIX,Af as DEFAULT_RULE_SCORER_CONFIG,hm as DEFAULT_SAMPLING_CONFIG,BVt as DEFAULT_SCORE_SCALE,jG as DEFAULT_STT_OPTIONS,ybe as DEFAULT_TEXT_MAX_SIZE_MB,gbe as DEFAULT_TEXT_TIMEOUT_MS,dre as DEFAULT_TIMEOUT_MS,_T as DIDAvatar,_T as DIDAvatarHandler,$T as DeepgramSTT,$T as DeepgramSTTHandler,Gi as EVAL_DEFAULT_SCORE_SCALE,vT as ElevenLabsMusic,vT as ElevenLabsMusicHandler,NT as ElevenLabsTTS,NT as ElevenLabsTTSHandler,kT as ElicitationManager,Zyr as ElicitationProtocolAdapter,zN as EnhancedToolDiscovery,Or as ErrorCategory,Ldr as ErrorRecoveryStrategies,no as ErrorSeverity,Nje as EvaluationAggregator,nv as EvaluationPipeline,Fu as Evaluator,kj as EvaluatorFactory,kUe as ExporterRegistry,gce as ExpressServerAdapter,noe as ExternalServerManager,Ihn as FAST_FALLBACK_WORKFLOW,dS as FaithfulnessScorer,yce as FastifyServerAdapter,BG as FileErrorCode,sie as FileSystemSkillStore,_5t as FileTokenStorage,LT as FishAudioTTS,LT as FishAudioTTSHandler,NP as FormatScorerPresets,Cbe as GENAI_ATTRIBUTES,UT as GeminiLive,UT as GeminiLiveHandler,Zf as GoogleSTT,Zf as GoogleSTTHandler,lF as GoogleTTSHandler,rme as GraphRAG,Ore as HITLManager,O_r as HTMLChunker,z_r as HTMLLoader,qre as HTTPRateLimiter,cS as HallucinationScorer,sce as HandlerError,ET as HeyGenAvatar,ET as HeyGenAvatarHandler,vce as HonoServerAdapter,ad as HttpError,shn as ImageGenService,W_r as InMemoryBM25Index,ivr as InMemoryCacheStore,svr as InMemoryRateLimitStore,Jce as InMemorySessionStorage,iie as InMemorySkillStore,qN as InMemoryTokenStorage,P3 as InMemoryVectorStore,wF as InvalidAuthenticationError,Jo as InvalidModelError,G_r as JSONLoader,Vmn as JWTTokenManager,fF as KlingVideoHandler,Cre as KnowledgeGroundingEngine,wre as KnowledgeLexicalIndex,wce as KoaServerAdapter,YC as LLMMetadataExtractor,N_r as LaTeXChunker,DP as LengthScorerPresets,loe as LocalTempArtifactStore,wT as LyriaMusic,wT as LyriaMusicHandler,mbe as MAX_SLIDES,Ure as MCPCircuitBreaker,Ww as MCPClientFactory,j3 as MCPRegistryClient,fhn as MCPServerBase,$L as MCPToolRegistry,gu as MDocument,BP as MINIMAL_PIPELINE,pbe as MIN_SLIDES,Mhn as MULTI_JUDGE_3_WORKFLOW,Phn as MULTI_JUDGE_5_WORKFLOW,Kt as MUSIC_ERROR_CODES,L_r as MarkdownChunker,B_r as MarkdownLoader,lme as MemoryRateLimitStorage,V1 as MemorySessionStorage,eF as MessageBus,AP as MetricsAggregator,jP as MetricsCollector,Mj as MiddlewareFactory,uce as MissingDependencyError,ry as ModelAccessDeniedError,_5 as ModelAccessError,bbe as ModelAliases,FG as ModelConfigSchema,Nse as ModelPool,$G as ModelRegistrySchema,cA as MultiServerManager,Ht as MusicError,bp as MusicProcessor,wkn as NEUROLINK_RESOURCE_ID_KEY,Tkn as NEUROLINK_THREAD_ID_KEY,ai as NetworkError,zae as NetworkOrchestrator,tF as NetworkTopology,AT as NeuroLink,Hyr as NeuroLinkAIProvider,ad as NeuroLinkApiError,Vyr as NeuroLinkClient,nS as NeuroLinkFeatureError,jyr as NeuroLinkLanguageModel,VN as NeuroLinkOAuthProvider,_Ue as NeverSampler,AUe as NoOpExporter,Uyr as NotFoundError,Ndr as NotRunningError,Xmn as OAuth2AuthError,Due as OAuth2Error,qmn as OAuth2TokenManager,z0e as OAuthCallbackServerError,L0e as OAuthConfigurationError,Kp as OAuthError,F0e as OAuthTokenExchangeError,$0e as OAuthTokenRefreshError,B0e as OAuthTokenRevocationError,U0e as OAuthTokenValidationError,ej as ObservabilityHooks,M6 as OpenAIModels,BT as OpenAIRealtime,BT as OpenAIRealtimeHandler,td as OpenAISTT,td as OpenAISTTHandler,FT as OpenAITTS,FT as OpenAITTSHandler,V_r as PDFLoader,Tbe as PROCESSOR_PRIORITIES,sm as PROVIDER_ALIAS_INDEX,xc as PROVIDER_DESCRIPTORS,hr as PROVIDER_DESCRIPTORS_BY_NAME,GSn as PgVectorStore,BSn as PineconeVectorStore,Nu as PipelineBuilder,gj as Pipelines,yS as PromptAlignmentScorer,ot as ProviderError,Cr as ProviderFactory,Sp as ProviderRegistry,Qyr as QUALITY_MAX_WORKFLOW,$P as QUALITY_PIPELINE,CP as RAGASEvaluator,Q_r as RAGCircuitBreaker,eEr as RAGCircuitBreakerManager,D_r as RAGJSONChunker,Z_r as RAGPipeline,h6 as RAGRetryHandler,FP as RAG_PIPELINE,es as REALTIME_ERROR_CODES,Qi as RateLimitError,Vre as RateLimiterManager,tr as RealtimeError,IT as RealtimeProcessor,F_r as RecursiveChunker,boe as RedisArtifactStore,dEr as RedisRateLimitStorage,ume as RedisSessionStorage,oie as RedisSkillStore,ST as ReplicateAvatar,ST as ReplicateAvatarHandler,bT as ReplicateMusic,bT as ReplicateMusicHandler,gF as ReplicateVideoHandler,Cf as ReportGenerator,Cje as Reports,$N as RequestBatcher,_kn as RequestContext,Uje as RetryManager,Pdr as RouteConflictError,Mdr as RouteNotFoundError,vF as RunwayVideoHandler,nie as S3SkillStore,LP as SAFETY_PIPELINE,Jp as SIZE_TIER_THRESHOLDS,g4 as SLIDE_DIMENSIONS,evr as SPEED_FIRST_WORKFLOW,Wyr as SSEClient,Zt as STTError,cT as STTProcessor,vs as STT_ERROR_CODES,zP as SUMMARIZATION_PIPELINE,Ebe as SUPPORTED_IMAGE_MIME_TYPES,Tj as SamplingStrategies,Lu as SamplingStrategy,gm as ScorerBuilder,TS as ScorerRegistry,_j as Scorers,Kce as SemanticChunker,$_r as SentenceChunker,Zn as ServerAdapterError,Ar as ServerAdapterErrorCode,Bue as ServerAdapterFactory,zT as ServerAuthenticationError,oce as ServerAuthorizationError,ghn as ServerCapabilitiesManager,HT as ServerNameParamSchema,TF as ServerRateLimitError,bF as ServerStartError,qT as ServerStopError,ice as ServerTimeoutError,v0 as ServerValidationError,mce as SessionIdParamSchema,ykn as SessionManager,OT as SixtyDBTTS,OT as SixtyDBTTSHandler,aie as SkillsManager,Me as SpanSerializer,KG as SpanStatus,WG as SpanType,Ddr as StreamAbortedError,dmn as StreamError,Odr as StreamingError,vS as SummarizationScorer,Xo as TASK_DEFAULTS,die as TERMINAL_AGENT_PROMPT_V1,pie as TERMINAL_AGENT_PROMPT_V2,uie as TERMINAL_AGENT_PROMPT_VERSION,KY as TOOL_COMPATIBILITY,ft as TTSError,Nc as TTSProcessor,Tt as TTS_ERROR_CODES,aF as TYPESAFE_MAX_REQUEST_TOKENS,sF as TYPESAFE_MAX_STATE_TOKENS,Vae as TaskDistributor,G0 as TextLoader,ice as TimeoutError,U_r as TokenChunker,Ymn as TokenRefreshError,hn as TokenStoreError,zV as TokenTracker,gS as ToneConsistencyScorer,EF as ToolArgumentsSchema,Ug as ToolCache,UN as ToolCallBatcher,Yte as ToolEmbeddingIndex,pce as ToolExecuteRequestSchema,Y3 as ToolIntegrationManager,SF as ToolNameParamSchema,BN as ToolResultCache,JL as ToolRouter,nre as ToolRoutingCache,$dr as ToolSearchQuerySchema,Gae as TopologyBuilder,uS as ToxicityScorer,hEr as TripwireEvaluator,QV as TypedEventEmitter,cme as UserRateLimiter,Y_ as VALID_AUDIO_FORMATS,Rbe as VALID_AVATAR_FORMATS,Pbe as VALID_MUSIC_FORMATS,VG as VALID_TTS_QUALITIES,Dkn as VERSION,Xe as VIDEO_ERROR_CODES,x2 as VIDEO_PROVIDER_CONFIGS,HG as VOICE_ERROR_CODES,v0 as ValidationError,O6 as VertexModels,TO as VertexVideoHandler,Ye as VideoError,qv as VideoProcessor,fk as VoiceError,Dhn as WORKFLOW_ENGINE_VERSION,j_r as WebLoader,GT as WebSocketConnectionError,gSn as WebSocketConnectionManager,ac as WebSocketError,P_r as WebSocketMessageRouter,Kyr as WebSocketStreamingClient,td as WhisperSTT,td as WhisperSTTHandler,Sd as WorkflowError,Vkn as anthropic,H_r as assembleContext,fre as assembleKnowledgeContext,cRt as batchConvertToMCP,uRt as batchConvertToNeuroLink,Can as batchRerank,bre as buildDocument,_re as buildIndexSnapshot,_jt as buildModelCatalog,ahn as buildObservabilityConfigFromEnv,A3 as buildRegistryIndex,u6t as buildRoutingQueryFromHistory,c6t as buildToolRoutingCatalog,Ls as calculateCost,Hre as calculateExpiresAt,Shn as calculateModelMetrics,vEt as canDeliverVideoNatively,wSn as chunkText,sT as classifyHeuristic,Cjt as classifyJev,iT as classifyProviderError,eUr as clearAnalyticsMetrics,_sn as clearWorkflowRegistry,Gmn as collectStream,fEr as commonTripwires,khn as compareWorkflows,$mn as composeMiddleware,bj as composeScorers,aQe as computeToolSignature,Umn as conditionalMiddleware,Lae as confirmationMiddleware,Ajt as contextScopeToThreshold,MUr as contextToErrorContext,Z$t as cosineSimilarity,Nkn as createAIProvider,Lkn as createAIProviderWithFallback,xhn as createAdaptiveWorkflow,bvr as createAgentRoutes,vSn as createAgentWebSocketHandler,C_r as createAllRoutes,_V as createAnalyticsMiddleware,vje as createAndInitializePipeline,rRt as createAnnotatedTool,sj as createAnswerRelevancyScorer,yEr as createAnthropic,kmn as createApiKeyAuthInterceptor,jmn as createApiKeyMiddleware,W8t as createArtifactStore,zmn as createAsyncStream,zhn as createAuthMiddleware,LKt as createAuthProvider,ame as createAuthProviderMiddleware,Ekn as createAuthValidatorFromProvider,Kmn as createAuthWithRetryMiddleware,bGt as createAuthenticatedContext,fkn as createAuthenticatedRateLimitMiddleware,PUr as createBatchEvaluationError,_je as createBatchStrategy,xmn as createBearerAuthInterceptor,Hmn as createBearerTokenMiddleware,Fkn as createBestAIProvider,lj as createBiasDetectionScorer,Nmn as createCacheInterceptor,Whn as createCacheInvalidator,jhn as createCacheMiddleware,bHt as createChunker,Rue as createClient,Qhn as createCompressionMiddleware,Mje as createConditionalScorer,aS as createConfigurationError,uhn as createConfirmationRequest,Ahn as createConsensus3WithPrompt,DUr as createConsoleLoggerHook,mj as createContentSimilarityScorer,OCt as createContextEnricher,aj as createContextPrecisionScorer,ij as createContextRelevancyScorer,ESn as createContextWindow,uSn as createDataStreamResponse,I_r as createDataStreamWriter,nan as createDefaultRequestRouter,Pkn as createDefaultTripwireEvaluator,Amn as createDynamicAuthInterceptor,lhn as createElicitationCancel,J3 as createElicitationContext,cb as createElicitationRequest,Xyr as createElicitationResponse,Sf as createErrorFactory,fmn as createErrorFromNative,hmn as createErrorFromResponse,Fmn as createErrorHandlerInterceptor,Xhn as createErrorHandlingMiddleware,Gt as createErrorResponse,AUr as createEvaluationFailedError,pkn as createExpressAuthMiddleware,oj as createFaithfulnessScorer,ifn as createFieldValidator,mhn as createFormRequest,fj as createFormatScorer,SS as createFunctionScorer,rj as createHallucinationScorer,E_r as createHealthRoutes,Y_r as createHybridSearch,Oje as createInvertedScorer,vhn as createJsonResource,pj as createKeywordCoverageScorer,Rje as createKeywordScorer,$Ur as createLangfuseAdapter,hj as createLengthScorer,Pj as createLifecycleMiddleware,gEr as createLocalUsageReader,Cmn as createLoggingInterceptor,Zhn as createLoggingMiddleware,k_r as createMCPRoutes,r9t as createMCPServer,RUr as createMaxRetriesExceededError,x_r as createMemoryRoutes,KUr as createMetricsCollector,NUr as createMetricsCollectorHook,wEr as createMistral,BUr as createMockLangfuseClient,Jmn as createMultiAuthMiddleware,Ohn as createMultiJudgeWorkflow,mSn as createNDJSONHeaders,bmn as createNeuroLinkModel,Pue as createNeuroLinkProvider,NYr as createOAuthProviderFromConfig,vEr as createOpenAI,Rfn as createOpenAPIGenerator,CUr as createParseError,yje as createPipeline,whn as createPrompt,uj as createPromptAlignmentScorer,ukn as createProtectedMiddleware,IUr as createProviderError,RSn as createRAGPipeline,cEr as createRBACMiddleware,hkn as createRateLimitByUserMiddleware,Pmn as createRateLimitInterceptor,efn as createRateLimitMiddleware,gkn as createRateLimitStorage,Ije as createRegexScorer,XUr as createReportGenerator,l5t as createRequestBatcher,uEr as createRequestContext,Jhn as createRequestIdMiddleware,Mmn as createRequestTransformInterceptor,rfn as createRequestValidationMiddleware,Omn as createResponseTransformInterceptor,Imn as createRetryInterceptor,wKt as createRetryMiddleware,Vhn as createRoleMiddleware,pSn as createSSEHeaders,kje as createSamplingStrategy,Fd as createScorerMetadata,Yhn as createSecurityHeadersMiddleware,phn as createSelectRequest,Uhn as createServer,vkn as createSessionStorage,Pje as createSimpleLengthScorer,mqt as createSkillStore,bqt as createSkillTools,tfn as createSlidingWindowRateLimitMiddleware,EVe as createStrategyNotFoundError,Bmn as createStreamingClient,Emn as createStreamingResponse,dj as createSummarizationScorer,dhn as createTextInputRequest,yhn as createTextResource,Lmn as createTimeoutInterceptor,vKt as createTimeoutMiddleware,Khn as createTimingMiddleware,Wmn as createTokenManagerMiddleware,cj as createToneConsistencyScorer,d5t as createToolCache,c5t as createToolCallBatcher,dRt as createToolFromFunction,Dae as createToolMiddlewareChain,p5t as createToolResultCache,e9t as createToolRouter,A_r as createToolRoutes,nj as createToxicityScorer,AHt as createVectorQueryTool,ovr as decideSearchPlan,Vte as decisionBooleanConfidence,oA as decisionKey,Nue as decodeJWTPayload,cQe as dedupeTools,Wse as detectAndRedactPII,Xx as detectImageMimeType,ak as dynamicModelProvider,Yyr as elicitationResponseToProtocol,$se as enrichCandidate,M8r as estimateVideoTokens,Eje as evaluateBatch,Qs as evaluationErrors,_hn as executeMCP,OSn as executeWithCircuitBreaker,H3 as exposeAgentAsTool,hKt as exposeAgentsAsTools,W3 as exposeWorkflowAsTool,fKt as exposeWorkflowsAsTools,mdn as extractMetadata,lEr as extractToken,iRt as filterToolsByAnnotations,aO as flushOpenTelemetry,_Sn as formatContextWithCitations,Km as gateDecisionBoolean,Mfn as generateOpenAPIFromConfig,Pfn as generateOpenAPISpec,Uue as generateSummaryStats,Bkn as generateText,pKt as getAllWellKnownServers,Q5r as getAnalyticsMetrics,sRt as getAnnotationSummary,ehn as getApiKeyFromEnv,NL as getAuthContext,Tse as getAvailableProviders,skn as getAvailableStrategies,oT as getBestProvider,MSn as getCircuitBreaker,hGt as getCurrentSession,AA as getCurrentUser,akn as getDefaultChunkerConfig,S0e as getErrorMessage,Lje as getEvaluatorFactory,$je as getEvaluatorRegistry,Qmn as getJWTExpiry,Bk as getLangfuseContext,zX as getLangfuseHealthStatus,PCt as getLangfuseSpanProcessor,Mkn as getLocalUsageDescriptors,Ehn as getMCPStats,it as getMetricsAggregator,Ztn as getPoolStats,Tje as getPreset,bje as getPresetNames,ikn as getRecommendedStrategy,w6 as getRegisteredLocalUsageCliIds,hrn as getServerInfo,DCt as getSpanProcessors,Ukn as getTelemetryStatus,oRt as getToolSafetyLevel,cO as getTracer,MCt as getTracerProvider,k2 as getVideoProviderConfig,dKt as getWellKnownServer,Ise as getWorkflow,Mae as globalAgentExposureManager,Qg as globalAuthContext,uA as globalCircuitBreakerManager,V3 as globalElicitationManager,hhn as globalElicitationProtocol,Rae as globalMCPRegistryClient,xje as globalMetricsCollector,Lre as globalMultiServerManager,jre as globalRateLimiterManager,$ae as globalToolIntegrationManager,vGt as hasAllPermissions,yGt as hasAnyRole,LL as hasPermission,Ud as hasPricing,Kne as hasRole,np as inferAnnotations,Thn as initializeMCPEcosystem,sO as initializeOpenTelemetry,$kn as initializeTelemetry,pr as isAbortError,_Rr as isAnthropicConfig,vmn as isApiError,Wxr as isAsyncFunction,aRr as isAudioContent,fGt as isAuthenticated,UG as isCSVContent,tAr as isCliGenerateResult,rAr as isCommandResult,chn as isElicitationProtocolMessage,g5 as isError,y5 as isErrorInfo,xUr as isEvaluationError,iRr as isImageContent,Zmn as isJWTExpired,E0e as isJsonRecord,UX as isLangfuseInternalSpan,N0e as isModelAccessDeniedMessage,uRr as isMultimodalInput,dRr as isMultimodalMessageContent,yEt as isNativeVideoMimeType,ymn as isNeuroLinkError,Uk as isOpenTelemetryInitialized,sRr as isPDFContent,gmn as isRetryableError,kUr as isRetryableEvaluationError,y5t as isRetryableHTTPError,Gyr as isRetryableStatus,GN as isRetryableStatusCode,Sbe as isSTTResult,qY as isSafeToRetry,_0e as isStandardRecord,Hxr as isStringArray,KRr as isTTSResult,dbe as isTextContent,b5t as isTokenExpired,VRr as isToolDefinition,qRr as isToolResult,xbe as isTranscriptionSegment,NCt as isUsingExternalTracerProvider,gRr as isValidHexColor,OVt as isValidProvider,Abe as isValidRealtimeConfig,kbe as isValidSTTOptions,JRr as isValidTTSOptions,lY as isVertexVideoConfigured,lRr as isVideoContent,CE as jsonSchema,BX as langfuseShouldExportSpan,J_r as linearCombination,bhn as listMCPs,bsn as listWorkflows,tme as loadDocument,bSn as loadDocuments,h as logger,Nae as loggingMiddleware,M6t as manifestToSources,zyr as mapStatusToErrorCode,re as mcpLogger,aRt as mcpProtocolToolToServerTool,HY as mcpToolToNeuroLink,GY as mergeAnnotations,Hkn as mistral,_mn as neuroLinkAIInstance,jY as neuroLinkToolToMCP,Ere as normalizeAndValidate,yRr as normalizeHexColor,gre as normalizePhrases,Pw as normalizeText,Bl as observabilityHooks,jkn as openai,D0e as parseAllowedModels,dSn as pipeAsyncIterableToDataStream,FUr as pipelineToSpanAttributes,RHt as prepareRAGTool,okn as processDocument,$ue as protocolMessageToElicitation,ome as ragCircuitBreakerManager,bjt as rankCatalogue,wjt as reachableTextProviders,Okn as readAllLocalUsage,PN as readDecisionBoolean,Gte as readDecisionChoice,qte as readDecisionScore,K_r as reciprocalRankFusion,lSn as registerAllRoutes,iKt as registerDefaultAvatarHandlers,HWt as registerDefaultMusicHandlers,ldr as registerDefaultRealtimeHandlers,adr as registerDefaultSTTHandlers,sdr as registerDefaultTTSHandlers,Sdr as registerDefaultVideoHandlers,hd as registerLocalUsageReader,Tsn as registerWorkflow,Ejt as renderCandidate,Wne as requireAuth,wGt as requirePermission,TGt as requireRole,gGt as requireUser,nRt as requiresConfirmation,aC as rerank,vUr as resetMetricsAggregator,_oe as resolveArtifactStorageType,pE as resolveDefaultDecisionProvider,NN as resolveEntry,kN as resolveHistoryBudget,d6t as resolveToolRoutingExclusions,Are as retrieve,mGt as runWithAuthContext,Uv as runWithCurrentLangfuseContext,Rse as runWorkflow,WY as sanitizeToolName,LUr as scorerToSpanAttributes,U$t as selectIrrelevantMessages,e6t as selectRelevantToolNames,o6t as selectServersByDecision,lRt as serverToolToMCPProtocol,lYr as servesInferenceKind,$v as setLangfuseContext,lO as shutdownOpenTelemetry,Ian as simpleRerank,Jx as sniffImageMimeType,UUr as startLangfuseAdapter,nOe as stepCountIs,Sje as streamBatchEvaluation,SSn as summarizeContext,B$t as summaryPreservesContext,gEt as supportsNativeVideo,sAr as toErrorInfo,hp as tokenize,UOr as tool,tRt as validateAnnotations,n9t as validateMCPTool,nu as validateParams,nun as validateQuery,rd as validateRequest,Xjt as validateResponse,frn as validateServerTools,ihn as validateTool,pRt as validateToolName,x3 as validateWorkflow,Fae as validationMiddleware,v5t as withHTTPRetry,G9e as withRetry,NC as wrapError,X3 as wrapToolWithElicitation,yKt as wrapToolsWithElicitation};/*! Bundled license information:
|
|
2523
|
+
`,1,i,String(t),String(r),String(n),String(this.ttlSeconds),e);if(a==null)return null;const[l,c,u]=a;return{bucket:{tokens:l/1e3,lastRefill:c,userId:e},consumed:u===1}}catch(o){return h.warn("Redis atomicConsume failed, falling back to non-atomic:",o),null}}async healthCheck(){try{return await(await this.getClient()).ping()==="PONG"}catch{return!1}}async cleanup(){this.client&&(await this.client.quit(),this.client=null,this.initPromise=null)}},cme=class{storage;config;constructor(e,t){this.config={message:"Rate limit exceeded. Please try again later.",...e},this.storage=t||new lme(Math.max(6e4,e.windowMs),e.windowMs)}getLimitForUser(e){if(this.config.userLimits&&e.id in this.config.userLimits)return this.config.userLimits[e.id];if(this.config.roleLimits){let t=this.config.maxRequests;for(const r of e.roles)r in this.config.roleLimits&&(t=Math.max(t,this.config.roleLimits[r]));return t}return this.config.maxRequests}shouldSkipRateLimit(e){return!this.config.skipRoles||this.config.skipRoles.length===0?!1:e.roles.some(t=>this.config.skipRoles?.includes(t)??!1)}async consume(e){if(this.shouldSkipRateLimit(e))return{allowed:!0,remaining:1/0,resetIn:0,limit:1/0};const t=e.id,r=this.getLimitForUser(e),n=Date.now();if(this.storage.atomicConsume){const l=await this.storage.atomicConsume(t,r,this.config.windowMs,n);if(l!==null){const{bucket:c,consumed:u}=l;return u?{allowed:!0,remaining:Math.floor(c.tokens),resetIn:Math.ceil((r-c.tokens)/r*this.config.windowMs),limit:r}:{allowed:!1,remaining:0,resetIn:Math.ceil((1-c.tokens)/r*this.config.windowMs),limit:r,error:this.config.message}}}let o=await this.storage.getBucket(t);o||(o={tokens:r,lastRefill:n,userId:t});const s=(n-o.lastRefill)/this.config.windowMs*r;return o.tokens=Math.min(r,o.tokens+s),o.lastRefill=n,o.tokens>=1?(o.tokens-=1,await this.storage.setBucket(t,o),{allowed:!0,remaining:Math.floor(o.tokens),resetIn:Math.ceil((r-o.tokens)/r*this.config.windowMs),limit:r}):(await this.storage.setBucket(t,o),{allowed:!1,remaining:0,resetIn:Math.ceil((1-o.tokens)/r*this.config.windowMs),limit:r,error:this.config.message})}async getStatus(e){if(this.shouldSkipRateLimit(e))return{allowed:!0,remaining:1/0,resetIn:0,limit:1/0};const t=this.getLimitForUser(e),r=await this.storage.getBucket(e.id);if(!r)return{allowed:!0,remaining:t,resetIn:0,limit:t};const i=(Date.now()-r.lastRefill)/this.config.windowMs*t,s=Math.min(t,r.tokens+i);return{allowed:s>=1,remaining:Math.floor(s),resetIn:s>=1?0:Math.ceil((1-s)/t*this.config.windowMs),limit:t}}async resetUser(e){await this.storage.deleteBucket(e),h.debug(`Rate limit reset for user: ${mkn(e)}`)}async healthCheck(){return this.storage.healthCheck()}async cleanup(){await this.storage.cleanup()}};function hkn(e,t){const r=new cme(e,t);return async n=>{const o=await r.consume(n.user);if(!o.allowed){const i=pEr(o);return{proceed:!1,rateLimitResult:o,response:i}}return{proceed:!0,rateLimitResult:o}}}function fkn(e,t,r){const n=new cme(t,r);return async o=>{const i=await e(o);if(!i.proceed||!i.context)return i;const s=await n.consume(i.context.user);return s.allowed?{proceed:!0,context:i.context,rateLimitResult:s}:{proceed:!1,context:i.context,rateLimitResult:s,response:pEr(s)}}}function pEr(e){return new Response(JSON.stringify({error:"Too Many Requests",message:e.error||"Rate limit exceeded",statusCode:429,retryAfter:Math.ceil(e.resetIn/1e3),limit:e.limit,remaining:e.remaining}),{status:429,headers:{"Content-Type":"application/json","Retry-After":String(Math.ceil(e.resetIn/1e3)),"X-RateLimit-Limit":String(e.limit),"X-RateLimit-Remaining":String(e.remaining),"X-RateLimit-Reset":String(Date.now()+e.resetIn)}})}function gkn(e){return e.type==="redis"&&e.redis?new dEr(e.redis):new lme(e.cleanupIntervalMs)}Kr(),z(),Xr(),Sr();function gc(e){return e.length<=4?"***":`${e.slice(0,4)}***`}var mEr=5e3,V1=class{sessions=new Map;userSessions=new Map;async get(e){const t=this.sessions.get(e);return t?t.expiresAt&&new Date>t.expiresAt?(await this.delete(e),null):t:null}async set(e){this.sessions.set(e.id,e);let t=this.userSessions.get(e.user.id);t||(t=new Set,this.userSessions.set(e.user.id,t)),t.add(e.id)}async delete(e){const t=this.sessions.get(e);if(t){const r=this.userSessions.get(t.user.id);r&&(r.delete(e),r.size===0&&this.userSessions.delete(t.user.id)),this.sessions.delete(e)}}async getUserSessions(e){const t=this.userSessions.get(e);if(!t)return[];const r=[];for(const n of t){const o=await this.get(n);o&&r.push(o)}return r}async deleteUserSessions(e){const t=this.userSessions.get(e);if(t){for(const r of t)this.sessions.delete(r);this.userSessions.delete(e)}}async clear(){this.sessions.clear(),this.userSessions.clear()}async isHealthy(){return!0}},ume=class{prefix;ttl;redisUrl;client=null;initPromise=null;constructor(e){this.redisUrl=e.url,this.prefix=e.prefix||"neurolink:sessions:",this.ttl=e.ttl||3600}async getClient(){return this.client?this.client:(this.initPromise||(this.initPromise=this.createClient()),this.initPromise)}async createClient(){try{const r=(await import("redis")).createClient({url:this.redisUrl});return r.on("error",n=>{h.error("Redis session client error:",n.message)}),await It(r.connect(),mEr,`Redis session client connect timed out after ${mEr}ms`),this.client=r,r}catch(e){throw this.initPromise=null,h.error('Redis client not available. Ensure the "redis" package is installed and Redis is reachable when using storage: "redis".'),e instanceof Error?e:new Error("Redis client not available")}}sessionKey(e){return`${this.prefix}${e}`}userSessionsKey(e){return`${this.prefix}user:${e}`}async get(e){try{const r=await(await this.getClient()).get(this.sessionKey(e));if(!r)return null;if(typeof r!="string")return h.warn("Unexpected Redis session payload type",{sessionId:gc(e),type:typeof r}),null;const n=JSON.parse(r);return n.createdAt=new Date(n.createdAt),n.expiresAt!==null&&n.expiresAt!==void 0&&(n.expiresAt=new Date(n.expiresAt)),n.expiresAt&&new Date>n.expiresAt?(await this.delete(e),null):n}catch(t){return h.error("Redis session get error:",t),null}}async set(e){try{const t=await this.getClient(),r=e.expiresAt?Math.max(1,Math.floor((e.expiresAt.getTime()-Date.now())/1e3)):this.ttl;await t.setEx(this.sessionKey(e.id),r,JSON.stringify(e)),await t.sAdd(this.userSessionsKey(e.user.id),e.id),await t.expire(this.userSessionsKey(e.user.id),this.ttl)}catch(t){throw h.error("Redis session set error:",t),t}}async delete(e){try{const t=await this.getClient(),r=await t.get(this.sessionKey(e));if(r)if(typeof r!="string")h.warn("Unexpected Redis session payload type during delete",{sessionId:gc(e),type:typeof r});else try{const n=JSON.parse(r);await t.sRem(this.userSessionsKey(n.user.id),e)}catch{h.warn(`Failed to parse session data for cleanup: ${gc(e)}`)}await t.del(this.sessionKey(e))}catch(t){h.error("Redis session delete error:",t)}}async getUserSessions(e){try{const r=await(await this.getClient()).sMembers(this.userSessionsKey(e)),n=[];for(const o of r){const i=await this.get(o);i&&n.push(i)}return n}catch(t){return h.error("Redis getUserSessions error:",t),[]}}async deleteUserSessions(e){try{const t=await this.getClient(),r=await t.sMembers(this.userSessionsKey(e));for(const n of r)await t.del(this.sessionKey(n));await t.del(this.userSessionsKey(e))}catch(t){h.error("Redis deleteUserSessions error:",t)}}async clear(){try{const e=await this.getClient();let t="0";do{const r=await e.scan(t,{MATCH:`${this.prefix}*`,COUNT:100});t=r.cursor,r.keys.length>0&&await e.del(r.keys)}while(t!=="0")}catch(e){h.error("Redis clear error:",e)}}async isHealthy(){try{return await(await this.getClient()).ping()==="PONG"}catch{return!1}}async disconnect(){this.client&&(await this.client.quit(),this.client=null,this.initPromise=null)}},ykn=class{storage;config;constructor(e={}){this.config={...e,duration:e.duration||3600,autoRefresh:e.autoRefresh??!0,refreshThreshold:e.refreshThreshold||300,storage:e.storage||"memory"},this.storage=this.createStorage()}createStorage(){return this.config.storage==="redis"?this.config.redis?.url?new ume({url:this.config.redis.url,prefix:this.config.redis.prefix,ttl:this.config.redis.ttl||this.config.duration}):(h.warn("Redis URL not provided, falling back to memory storage"),new V1):new V1}async createSession(e,t){return mt({name:"neurolink.auth.session.create",tracer:Be.auth,attributes:{"auth.user_id":gc(e.id),"auth.storage":this.config.storage??"memory"}},async()=>this._createSession(e,t))}async _createSession(e,t){const r=crypto.randomUUID(),n=new Date,o=this.config.duration||3600,i={id:r,user:e,createdAt:n,expiresAt:new Date(n.getTime()+o*1e3),isValid:!0,ipAddress:t?.ipAddress,userAgent:t?.userAgent,deviceId:t?.deviceId};return await this.storage.set(i),h.debug(`Session created: ${gc(r)} for user: ${gc(e.id)}`),i}async getSession(e,t=this.config.autoRefresh){return mt({name:"neurolink.auth.session.get",tracer:Be.auth,attributes:{"auth.session_id":gc(e),"auth.auto_refresh":t??!1}},async r=>{const n=await this._getSession(e,t);return r.setAttribute("auth.found",n!==null),n})}async _getSession(e,t=this.config.autoRefresh){const r=await this.storage.get(e);return r?t&&this.shouldRefresh(r)?this.refreshSession(e):r:null}shouldRefresh(e){if(!e.expiresAt)return!1;const t=this.config.refreshThreshold||300;return(e.expiresAt.getTime()-Date.now())/1e3<t}async refreshSession(e){return mt({name:"neurolink.auth.session.refresh",tracer:Be.auth,attributes:{"auth.session_id":gc(e)}},async t=>{const r=await this.storage.get(e);if(!r)return t.setAttribute("auth.found",!1),null;const n=this.config.duration||3600;return r.expiresAt=new Date(Date.now()+n*1e3),await this.storage.set(r),t.setAttribute("auth.found",!0),h.debug(`Session refreshed: ${gc(e)}`),r})}async destroySession(e){await this.storage.delete(e),h.debug(`Session destroyed: ${gc(e)}`)}async getUserSessions(e){return this.storage.getUserSessions(e)}async destroyAllUserSessions(e){await this.storage.deleteUserSessions(e),h.debug(`All sessions destroyed for user: ${gc(e)}`)}async validateSession(e){return mt({name:"neurolink.auth.session.validate",tracer:Be.auth,attributes:{"auth.session_id":gc(e)}},async t=>{const r=await this.storage.get(e),n=r!==null&&r.isValid;return t.setAttribute("auth.valid",n),n})}async updateSessionMetadata(e,t){const r=await this.storage.get(e);return r?(r.metadata={...r.metadata,...t},await this.storage.set(r),r):null}async isHealthy(){return this.storage.isHealthy()}async clear(){await this.storage.clear()}};function vkn(e){return e.storage==="redis"?e.redis?.url?new ume({url:e.redis.url,prefix:e.redis.prefix,ttl:e.redis.ttl||e.duration}):(h.warn("Redis URL not provided, falling back to memory storage"),new V1):new V1}CA();var wkn="neurolink__resourceId",Tkn="neurolink__threadId",bkn="neurolink__",_kn=class{registry=new Map;constructor(e){if(Array.isArray(e))for(const[t,r]of e)this.registry.set(t,r);else if(e)for(const[t,r]of Object.entries(e))this.registry.set(t,r)}set(e,t){this.registry.set(e,t)}get(e){return this.registry.get(e)}has(e){return this.registry.has(e)}delete(e){return this.registry.delete(e)}get size(){return this.registry.size}mergeClientContext(e){for(const[t,r]of Object.entries(e))t.startsWith(bkn)&&this.registry.has(t)||this.registry.has(t)||this.registry.set(t,r)}toJSON(){const e={};for(const[t,r]of this.registry.entries())this.isSerializable(r)&&(e[t]=r);return e}isSerializable(e){if(e==null)return!0;const t=typeof e;if(t==="function"||t==="symbol")return!1;try{return JSON.stringify(e),!0}catch{return!1}}};function Ekn(e){return async(t,r)=>{const n=await e.authenticateToken(t,r);return n.valid&&n.user?{id:n.user.id,email:n.user.email,roles:n.user.roles}:null}}Kjt(),Yjt();var hEr=class{tripwires=[];register(e){const t=this.tripwires.findIndex(r=>r.id===e.id);t!==-1?this.tripwires[t]=e:this.tripwires.push(e)}unregister(e){const t=this.tripwires.findIndex(r=>r.id===e);return t!==-1?(this.tripwires.splice(t,1),!0):!1}evaluate(e){let t=null,r=null,n=null;for(const o of this.tripwires){let i;try{i=o.condition(e)}catch{continue}if(!i)continue;const s=typeof o.message=="function"?o.message(e):o.message,a={triggered:!0,tripwire:o,message:s,action:o.action};o.action==="abort"&&t===null?t=a:o.action==="warn"&&r===null?r=a:o.action==="log"&&n===null&&(n=a)}return t!==null?t:r!==null?r:n!==null?n:{triggered:!1}}evaluateAll(e){const t=[];for(const r of this.tripwires){let n;try{n=r.condition(e)}catch{continue}if(!n)continue;const o=typeof r.message=="function"?r.message(e):r.message;t.push({triggered:!0,tripwire:r,message:o,action:r.action})}return t}getTripwires(){return[...this.tripwires]}},Skn={id:"max-tokens",name:"Maximum Tokens Hit",description:"Triggers when the model stopped because it reached the token output limit.",action:"abort",condition:e=>e.finishReason==="length",message:"Model stopped at token limit \u2014 response may be truncated."},kkn={id:"empty-response",name:"Empty Response",description:"Triggers when the model returns an empty or whitespace-only response.",action:"abort",condition:e=>e.responseText!==void 0&&e.responseText.trim().length===0,message:"Model returned an empty response."},xkn={id:"repetition-loop",name:"Repetition Loop",description:"Detects when the model is generating repetitive content, indicating a loop.",action:"warn",condition:e=>{const t=e.responseText;if(!t)return!1;const r=t.split(/\s+/);if(r.length<30)return!1;const n=10,o=new Map;let i=0;const s=r.length-n+1;for(let a=0;a<=r.length-n;a++){const l=r.slice(a,a+n).join(" "),c=(o.get(l)??0)+1;o.set(l,c),c>1&&i++}return i/s>.2},message:"Response contains highly repetitive content \u2014 possible generation loop."},Akn={id:"input-too-long",name:"Input Too Long",description:"Triggers when the input text exceeds the recommended length.",action:"abort",condition:e=>e.inputText!==void 0&&e.inputText.length>1e5,message:e=>`Input is ${e.inputText?.length??0} characters \u2014 exceeds the 100 000-character limit.`},Ckn={id:"too-many-messages",name:"Too Many Messages",description:"Triggers when the conversation message count exceeds the recommended maximum.",action:"warn",condition:e=>e.messageCount!==void 0&&e.messageCount>100,message:e=>`Conversation has ${e.messageCount} messages \u2014 consider summarising context.`},Ikn={id:"response-too-long",name:"Response Too Long",description:"Triggers when the response text exceeds the recommended length.",action:"warn",condition:e=>e.responseText!==void 0&&e.responseText.length>5e4,message:e=>`Response is ${e.responseText?.length??0} characters \u2014 exceeds the 50 000-character limit.`},Rkn={id:"high-latency",name:"High Latency",description:"Triggers when the measured response latency exceeds the acceptable threshold.",action:"warn",condition:e=>e.latencyMs!==void 0&&e.latencyMs>3e4,message:e=>`Response latency was ${e.latencyMs}ms \u2014 exceeds the 30 000ms threshold.`},fEr=[Skn,kkn,xkn,Akn,Ckn,Ikn,Rkn];function Pkn(){const e=new hEr;for(const t of fEr)e.register(t);return e}Uae(),xKt(),Iqt(),MKt(),DKt(),RKt();var v6=new Map;function hd(e){v6.set(e.descriptor.id,e)}function Mkn(){return[...v6.values()].map(e=>e.descriptor)}function w6(){return[...v6.keys()]}async function gEr(e){const t=v6.get(e);if(!t)throw new Error(`No local-usage reader registered for "${e}". Registered: ${w6().join(", ")||"(none)"}`);return t.factory()}hd({descriptor:{id:"claude-code",displayName:"Claude Code",verified:!0,dedupStrategy:"message-id-keep-max",costConfidence:"modeled",requiresSqlite:!1},factory:async()=>{const{createClaudeCodeReader:e}=await Promise.resolve().then(()=>(hpn(),wfr));return e()}}),hd({descriptor:{id:"codex",displayName:"Codex",verified:!0,dedupStrategy:"session-dag",costConfidence:"unavailable",requiresSqlite:!1},factory:async()=>{const{createCodexReader:e}=await Promise.resolve().then(()=>(vpn(),_fr));return e()}}),hd({descriptor:{id:"opencode",displayName:"OpenCode",verified:!0,dedupStrategy:"rowid-high-water-mark",costConfidence:"unavailable",requiresSqlite:!0},factory:async()=>{const{createOpenCodeReader:e}=await Promise.resolve().then(()=>(bpn(),iyr));return e()}}),hd({descriptor:{id:"qwen-code",displayName:"Qwen Code",verified:!0,dedupStrategy:"message-id-keep-max",costConfidence:"unavailable",requiresSqlite:!1},factory:async()=>{const{createQwenCodeReader:e}=await Promise.resolve().then(()=>(xpn(),ayr));return e()}}),hd({descriptor:{id:"gemini-cli",displayName:"Gemini CLI",verified:!0,dedupStrategy:"message-id-keep-max",costConfidence:"unavailable",requiresSqlite:!1},factory:async()=>{const{createGeminiCliReader:e}=await Promise.resolve().then(()=>(Mpn(),dyr));return e()}}),hd({descriptor:{id:"copilot",displayName:"Copilot CLI",verified:!0,dedupStrategy:"rowid-high-water-mark",costConfidence:"unavailable",requiresSqlite:!0},factory:async()=>{const{createCopilotCliReader:e}=await Promise.resolve().then(()=>(Lpn(),fyr));return e()}}),hd({descriptor:{id:"cursor",displayName:"Cursor",verified:!0,dedupStrategy:"last-write-wins",costConfidence:"unavailable",requiresSqlite:!0,requestUnit:"session-snapshot"},factory:async()=>{const{createCursorReader:e}=await Promise.resolve().then(()=>(Gpn(),yyr));return e()}}),hd({descriptor:{id:"grok",displayName:"Grok Build",verified:!0,dedupStrategy:"last-write-wins",costConfidence:"unavailable",requiresSqlite:!1},factory:async()=>{const{createGrokReader:e}=await Promise.resolve().then(()=>(Zpn(),byr));return e()}}),hd({descriptor:{id:"hermes",displayName:"Hermes Agent",verified:!0,dedupStrategy:"last-write-wins",costConfidence:"modeled",requiresSqlite:!0},factory:async()=>{const{createHermesReader:e}=await Promise.resolve().then(()=>(nmn(),kyr));return e()}});async function Okn(e){const t={},r=[],n=[],o=[],i=e?.only,s=i?w6().filter(a=>i.includes(a)):w6();for(const a of s)try{const l=await gEr(a);if(!await l.detect()){n.push(a);continue}const c=await l.scan(e);t[a]=c.totals,o.push(...c.errors)}catch(l){r.push({cliId:a,message:l instanceof Error?l.message:String(l)})}return{generatedAt:new Date().toISOString(),totals:t,failures:r,notInstalled:n,scanErrors:o}}var Dkn="1.0.0";async function Nkn(e,t){return await Yn.createProvider(e||"bedrock",t)}async function Lkn(e,t,r){return await Yn.createProviderWithFallback(e||"bedrock",t||"vertex",r)}async function Fkn(e,t){return await Yn.createBestProvider(e,t)}async function $kn(){try{return!!await dBr()}catch{return!1}}async function Ukn(){return pBr()}async function Bkn(e){return await new AT().generateText(e)}Ga();var zkn=e=>typeof e=="object"&&e!==null&&typeof e.doGenerate=="function",Gkn=e=>typeof e=="object"&&e!==null&&typeof e.getModel=="function",qkn=(e,t,r)=>{let n;const o=async()=>{const s=await Yn.createProvider(e,t,!1,void 0,void 0,r);if(!Gkn(s))throw new Error(`[NeuroLink:browser] provider "${e}" exposes no getModel()`);const a=await s.getModel();if(!zkn(a))throw new Error(`[NeuroLink:browser] provider "${e}" resolved a model handle that cannot generate`);return a},i=()=>n??=o();return{specificationVersion:"v3",provider:e,modelId:t,supportedUrls:{},doGenerate:async s=>(await i()).doGenerate(s),doStream:async s=>(await i()).doStream(s)}},dme=(e,t)=>(n={})=>{const o=n.credentials??(n.apiKey||n.baseURL?{[e]:{...n.apiKey?{apiKey:n.apiKey}:{},...n.baseURL?{baseURL:n.baseURL}:{}}}:void 0),i=(s=t)=>qkn(e,s,o);return Object.assign(i,{languageModel:i,chat:i,provider:e})},yEr=dme("anthropic","claude-sonnet-4-5"),Vkn=yEr(),vEr=dme("openai","gpt-4o-mini"),jkn=vEr(),wEr=dme("mistral","mistral-small-latest"),Hkn=wEr();typeof globalThis.setImmediate>"u"&&(globalThis.setImmediate=(e,...t)=>setTimeout(e,0,...t),globalThis.clearImmediate=e=>clearTimeout(e)),typeof globalThis.process>"u"&&(globalThis.process=new Proxy({env:{},version:"v24.0.0",platform:"browser",argv:[],pid:1,ppid:0,arch:"wasm",cwd:()=>"/",exit:()=>{},on:()=>globalThis.process,off:()=>globalThis.process,once:()=>globalThis.process,emit:()=>!1,removeListener:()=>globalThis.process,addListener:()=>globalThis.process,stdout:{write:()=>!0,on:()=>{}},stderr:{write:()=>!0,on:()=>{}},stdin:{on:()=>{}},nextTick:(e,...t)=>setTimeout(()=>e(...t),0),hrtime:Object.assign(e=>{const t=performance.now()*1e6,r=Math.floor(t/1e9),n=Math.floor(t%1e9);return e?[r-e[0],n-e[1]]:[r,n]},{bigint:()=>BigInt(Math.floor(performance.now()*1e6))}),memoryUsage:()=>({rss:0,heapTotal:0,heapUsed:0,external:0,arrayBuffers:0}),cpuUsage:()=>({user:0,system:0}),versions:{browser:"1.0.0",v8:"0",modules:"0"},release:{name:"browser"},uptime:()=>performance.now()/1e3,title:"browser",execPath:"/browser",execArgv:[],features:{},config:{},kill:()=>{},abort:()=>{}},{get(e,t){return t in e?e[t]:()=>{}}})),typeof globalThis.Buffer>"u"&&(globalThis.Buffer=class extends Uint8Array{static from(t,r){if(typeof t=="string"){const n=(r||"utf8").toLowerCase();if(n==="base64"){const o=atob(t),i=o.length,s=new Uint8Array(i);for(let a=0;a<i;a++)s[a]=o.charCodeAt(a);return s}if(n==="hex"){const o=t.length,i=new Uint8Array(o/2);for(let s=0;s<o;s+=2)i[s/2]=parseInt(t.substring(s,s+2),16);return i}return new TextEncoder().encode(t)}return new Uint8Array(t)}static alloc(t){return new Uint8Array(t)}static isBuffer(t){return t instanceof Uint8Array}static concat(t){const r=t.reduce((i,s)=>i+s.length,0),n=new Uint8Array(r);let o=0;for(const i of t)n.set(i,o),o+=i.length;return n}static byteLength(t){return new TextEncoder().encode(t).length}toString(t){switch((t||"utf8").toLowerCase()){case"utf8":case"utf-8":return new TextDecoder().decode(this);case"hex":return Array.from(new Uint8Array(this.buffer,this.byteOffset,this.byteLength)).map(n=>n.toString(16).padStart(2,"0")).join("");case"base64":{let n="";const o=this.byteLength;for(let i=0;i<o;i++)n+=String.fromCharCode(this[i]);return btoa(n)}case"binary":case"latin1":{let n="";const o=this.byteLength;for(let i=0;i<o;i++)n+=String.fromCharCode(this[i]);return n}default:return new TextDecoder().decode(this)}}}),typeof globalThis.global>"u"&&(globalThis.global=globalThis);export{Ibe as AGENT_ATTRIBUTES,Rhn as AGGRESSIVE_FALLBACK_WORKFLOW,Yn as AIProviderFactory,sI as AIProviderName,Z_ as AUDIO_FORMAT_DETAILS,wd as AUTORESEARCH_DEFAULTS,At as AVATAR_ERROR_CODES,Byr as AbortError,Z3 as Agent,Q3 as AgentCoordinator,_F as AgentExecuteRequestSchema,K3 as AgentExposureManager,Bae as AgentNetwork,VT as AlreadyRunningError,SP as AlwaysSampler,mS as AnswerRelevancyScorer,FL as AuthContextHolder,OL as AuthErrorCodes,xt as AuthErrorFactory,ckn as AuthMiddlewareError,aEr as AuthMiddlewareErrorCodes,Wmr as AuthProviderError,Ss as AuthProviderFactory,lkn as AuthProviderRegistry,Wr as AuthenticationError,kI as AuthorizationError,kt as AvatarError,Ep as AvatarProcessor,Qf as AzureSTT,Qf as AzureSTTHandler,PT as AzureTTS,PT as AzureTTSHandler,tvr as BALANCED_ADAPTIVE_WORKFLOW,_l as BaseAuthProvider,ty as BaseError,IP as BaseFactory,ol as BaseLLMScorer,TC as BaseRealtimeHandler,jV as BaseRegistry,rv as BaseRuleScorer,xf as BaseScorer,jT as BaseServerAdapter,bS as BatchStrategy,yT as BeatovenMusic,yT as BeatovenMusicHandler,P6 as BedrockModels,fS as BiasDetectionScorer,nC as CLASSIFIER_CONTEXT_SCOPES,h0 as CLASSIFIER_DIFFICULTIES,qP as CODE_GENERATION_PIPELINE,UP as COMPREHENSIVE_PIPELINE,Chn as CONSENSUS_3_FAST_WORKFLOW,rvr as CONSENSUS_3_WORKFLOW,q_r as CSVLoader,GP as CUSTOMER_SUPPORT_PIPELINE,DT as CartesiaTTS,DT as CartesiaTTSHandler,M_r as CharacterChunker,nkn as ChromaVectorStore,Ch as ChunkerRegistry,Bre as CircuitBreakerManager,jp as CircuitBreakerOpenError,Hse as ClassifierRouter,Fyr as ClientAuthenticationError,$yr as ClientAuthorizationError,umn as ClientConfigurationError,cmn as ClientConnectionError,en as ClientErrorCode,lb as ClientNetworkError,pu as ClientNeuroLinkError,Cue as ClientProviderError,Nyr as ClientRateLimitError,Aue as ClientTimeoutError,Lyr as ClientValidationError,kHt as CohereRelevanceScorer,lmn as ConfigManager,Rdr as ConfigurationError,mmn as ContentFilterError,EP as ContextBuilder,O0e as ContextConverter,b5 as ContextFactory,pmn as ContextLengthError,hS as ContextPrecisionScorer,pS as ContextRelevancyScorer,Ya as ConversationMemoryError,xHt as CrossEncoderReranker,Ny as DECISION_PROVIDERS,cre as DEFAULT_ALIAS_BOOST,Dre as DEFAULT_BATCH_CONFIG,Nre as DEFAULT_CACHE_CONFIG,ire as DEFAULT_CANDIDATE_LIMIT,xN as DEFAULT_COMPACTION_THRESHOLD,T5 as DEFAULT_CONFIG,lre as DEFAULT_EXACT_BOOST,ore as DEFAULT_FIELD_WEIGHTS,Ku as DEFAULT_HTTP_RETRY_CONFIG,JG as DEFAULT_IMAGE_GEN_CONFIG,wbe as DEFAULT_IMAGE_MAX_SIZE_MB,vbe as DEFAULT_IMAGE_TIMEOUT_MS,X_ as DEFAULT_INFERENCE_KINDS,PP as DEFAULT_LLM_SCORER_CONFIG,ure as DEFAULT_MAX_CONTEXT_TOKENS,y4 as DEFAULT_MODEL_ALIASES,_be as DEFAULT_PROVIDER_CONFIGS,Gre as DEFAULT_RATE_LIMIT_CONFIG,v4 as DEFAULT_REALTIME_CONFIG,ON as DEFAULT_RECENT_TURNS,are as DEFAULT_RELATION_LIMIT,sre as DEFAULT_RESULT_LIMIT,zG as DEFAULT_RETRY_CONFIG,Eoe as DEFAULT_ROUTER_CONFIG,rre as DEFAULT_ROUTER_PROMPT_PREFIX,Af as DEFAULT_RULE_SCORER_CONFIG,hm as DEFAULT_SAMPLING_CONFIG,BVt as DEFAULT_SCORE_SCALE,jG as DEFAULT_STT_OPTIONS,ybe as DEFAULT_TEXT_MAX_SIZE_MB,gbe as DEFAULT_TEXT_TIMEOUT_MS,dre as DEFAULT_TIMEOUT_MS,_T as DIDAvatar,_T as DIDAvatarHandler,$T as DeepgramSTT,$T as DeepgramSTTHandler,Gi as EVAL_DEFAULT_SCORE_SCALE,vT as ElevenLabsMusic,vT as ElevenLabsMusicHandler,NT as ElevenLabsTTS,NT as ElevenLabsTTSHandler,kT as ElicitationManager,Zyr as ElicitationProtocolAdapter,zN as EnhancedToolDiscovery,Or as ErrorCategory,Ldr as ErrorRecoveryStrategies,no as ErrorSeverity,Nje as EvaluationAggregator,nv as EvaluationPipeline,Fu as Evaluator,kj as EvaluatorFactory,kUe as ExporterRegistry,gce as ExpressServerAdapter,noe as ExternalServerManager,Ihn as FAST_FALLBACK_WORKFLOW,dS as FaithfulnessScorer,yce as FastifyServerAdapter,BG as FileErrorCode,sie as FileSystemSkillStore,_5t as FileTokenStorage,LT as FishAudioTTS,LT as FishAudioTTSHandler,NP as FormatScorerPresets,Cbe as GENAI_ATTRIBUTES,UT as GeminiLive,UT as GeminiLiveHandler,Zf as GoogleSTT,Zf as GoogleSTTHandler,lF as GoogleTTSHandler,rme as GraphRAG,Ore as HITLManager,O_r as HTMLChunker,z_r as HTMLLoader,qre as HTTPRateLimiter,cS as HallucinationScorer,sce as HandlerError,ET as HeyGenAvatar,ET as HeyGenAvatarHandler,vce as HonoServerAdapter,ad as HttpError,shn as ImageGenService,W_r as InMemoryBM25Index,ivr as InMemoryCacheStore,svr as InMemoryRateLimitStore,Jce as InMemorySessionStorage,iie as InMemorySkillStore,qN as InMemoryTokenStorage,P3 as InMemoryVectorStore,wF as InvalidAuthenticationError,Jo as InvalidModelError,G_r as JSONLoader,Vmn as JWTTokenManager,fF as KlingVideoHandler,Cre as KnowledgeGroundingEngine,wre as KnowledgeLexicalIndex,wce as KoaServerAdapter,YC as LLMMetadataExtractor,N_r as LaTeXChunker,DP as LengthScorerPresets,loe as LocalTempArtifactStore,wT as LyriaMusic,wT as LyriaMusicHandler,mbe as MAX_SLIDES,Ure as MCPCircuitBreaker,Ww as MCPClientFactory,j3 as MCPRegistryClient,fhn as MCPServerBase,$L as MCPToolRegistry,gu as MDocument,BP as MINIMAL_PIPELINE,pbe as MIN_SLIDES,Mhn as MULTI_JUDGE_3_WORKFLOW,Phn as MULTI_JUDGE_5_WORKFLOW,Kt as MUSIC_ERROR_CODES,L_r as MarkdownChunker,B_r as MarkdownLoader,lme as MemoryRateLimitStorage,V1 as MemorySessionStorage,eF as MessageBus,AP as MetricsAggregator,jP as MetricsCollector,Mj as MiddlewareFactory,uce as MissingDependencyError,ry as ModelAccessDeniedError,_5 as ModelAccessError,bbe as ModelAliases,FG as ModelConfigSchema,Nse as ModelPool,$G as ModelRegistrySchema,cA as MultiServerManager,Ht as MusicError,bp as MusicProcessor,wkn as NEUROLINK_RESOURCE_ID_KEY,Tkn as NEUROLINK_THREAD_ID_KEY,ai as NetworkError,zae as NetworkOrchestrator,tF as NetworkTopology,AT as NeuroLink,Hyr as NeuroLinkAIProvider,ad as NeuroLinkApiError,Vyr as NeuroLinkClient,nS as NeuroLinkFeatureError,jyr as NeuroLinkLanguageModel,VN as NeuroLinkOAuthProvider,_Ue as NeverSampler,AUe as NoOpExporter,Uyr as NotFoundError,Ndr as NotRunningError,Xmn as OAuth2AuthError,Due as OAuth2Error,qmn as OAuth2TokenManager,z0e as OAuthCallbackServerError,L0e as OAuthConfigurationError,Kp as OAuthError,F0e as OAuthTokenExchangeError,$0e as OAuthTokenRefreshError,B0e as OAuthTokenRevocationError,U0e as OAuthTokenValidationError,ej as ObservabilityHooks,M6 as OpenAIModels,BT as OpenAIRealtime,BT as OpenAIRealtimeHandler,td as OpenAISTT,td as OpenAISTTHandler,FT as OpenAITTS,FT as OpenAITTSHandler,V_r as PDFLoader,Tbe as PROCESSOR_PRIORITIES,sm as PROVIDER_ALIAS_INDEX,xc as PROVIDER_DESCRIPTORS,hr as PROVIDER_DESCRIPTORS_BY_NAME,GSn as PgVectorStore,BSn as PineconeVectorStore,Nu as PipelineBuilder,gj as Pipelines,yS as PromptAlignmentScorer,nt as ProviderError,Cr as ProviderFactory,Sp as ProviderRegistry,Qyr as QUALITY_MAX_WORKFLOW,$P as QUALITY_PIPELINE,CP as RAGASEvaluator,Q_r as RAGCircuitBreaker,eEr as RAGCircuitBreakerManager,D_r as RAGJSONChunker,Z_r as RAGPipeline,h6 as RAGRetryHandler,FP as RAG_PIPELINE,es as REALTIME_ERROR_CODES,Qi as RateLimitError,Vre as RateLimiterManager,tr as RealtimeError,IT as RealtimeProcessor,F_r as RecursiveChunker,boe as RedisArtifactStore,dEr as RedisRateLimitStorage,ume as RedisSessionStorage,oie as RedisSkillStore,ST as ReplicateAvatar,ST as ReplicateAvatarHandler,bT as ReplicateMusic,bT as ReplicateMusicHandler,gF as ReplicateVideoHandler,Cf as ReportGenerator,Cje as Reports,$N as RequestBatcher,_kn as RequestContext,Uje as RetryManager,Pdr as RouteConflictError,Mdr as RouteNotFoundError,vF as RunwayVideoHandler,nie as S3SkillStore,LP as SAFETY_PIPELINE,Jp as SIZE_TIER_THRESHOLDS,g4 as SLIDE_DIMENSIONS,evr as SPEED_FIRST_WORKFLOW,Wyr as SSEClient,Zt as STTError,cT as STTProcessor,vs as STT_ERROR_CODES,zP as SUMMARIZATION_PIPELINE,Ebe as SUPPORTED_IMAGE_MIME_TYPES,Tj as SamplingStrategies,Lu as SamplingStrategy,gm as ScorerBuilder,TS as ScorerRegistry,_j as Scorers,Kce as SemanticChunker,$_r as SentenceChunker,Zn as ServerAdapterError,Ar as ServerAdapterErrorCode,Bue as ServerAdapterFactory,zT as ServerAuthenticationError,oce as ServerAuthorizationError,ghn as ServerCapabilitiesManager,HT as ServerNameParamSchema,TF as ServerRateLimitError,bF as ServerStartError,qT as ServerStopError,ice as ServerTimeoutError,v0 as ServerValidationError,mce as SessionIdParamSchema,ykn as SessionManager,OT as SixtyDBTTS,OT as SixtyDBTTSHandler,aie as SkillsManager,Me as SpanSerializer,KG as SpanStatus,WG as SpanType,Ddr as StreamAbortedError,dmn as StreamError,Odr as StreamingError,vS as SummarizationScorer,Xo as TASK_DEFAULTS,die as TERMINAL_AGENT_PROMPT_V1,pie as TERMINAL_AGENT_PROMPT_V2,uie as TERMINAL_AGENT_PROMPT_VERSION,KY as TOOL_COMPATIBILITY,ft as TTSError,Nc as TTSProcessor,Tt as TTS_ERROR_CODES,aF as TYPESAFE_MAX_REQUEST_TOKENS,sF as TYPESAFE_MAX_STATE_TOKENS,Vae as TaskDistributor,G0 as TextLoader,ice as TimeoutError,U_r as TokenChunker,Ymn as TokenRefreshError,hn as TokenStoreError,zV as TokenTracker,gS as ToneConsistencyScorer,EF as ToolArgumentsSchema,Ug as ToolCache,UN as ToolCallBatcher,Yte as ToolEmbeddingIndex,pce as ToolExecuteRequestSchema,Y3 as ToolIntegrationManager,SF as ToolNameParamSchema,BN as ToolResultCache,JL as ToolRouter,nre as ToolRoutingCache,$dr as ToolSearchQuerySchema,Gae as TopologyBuilder,uS as ToxicityScorer,hEr as TripwireEvaluator,QV as TypedEventEmitter,cme as UserRateLimiter,Y_ as VALID_AUDIO_FORMATS,Rbe as VALID_AVATAR_FORMATS,Pbe as VALID_MUSIC_FORMATS,VG as VALID_TTS_QUALITIES,Dkn as VERSION,Xe as VIDEO_ERROR_CODES,x2 as VIDEO_PROVIDER_CONFIGS,HG as VOICE_ERROR_CODES,v0 as ValidationError,O6 as VertexModels,TO as VertexVideoHandler,Ye as VideoError,qv as VideoProcessor,fk as VoiceError,Dhn as WORKFLOW_ENGINE_VERSION,j_r as WebLoader,GT as WebSocketConnectionError,gSn as WebSocketConnectionManager,ac as WebSocketError,P_r as WebSocketMessageRouter,Kyr as WebSocketStreamingClient,td as WhisperSTT,td as WhisperSTTHandler,Sd as WorkflowError,Vkn as anthropic,H_r as assembleContext,fre as assembleKnowledgeContext,cRt as batchConvertToMCP,uRt as batchConvertToNeuroLink,Can as batchRerank,bre as buildDocument,_re as buildIndexSnapshot,_jt as buildModelCatalog,ahn as buildObservabilityConfigFromEnv,A3 as buildRegistryIndex,u6t as buildRoutingQueryFromHistory,c6t as buildToolRoutingCatalog,Ls as calculateCost,Hre as calculateExpiresAt,Shn as calculateModelMetrics,vEt as canDeliverVideoNatively,wSn as chunkText,sT as classifyHeuristic,Cjt as classifyJev,iT as classifyProviderError,eUr as clearAnalyticsMetrics,_sn as clearWorkflowRegistry,Gmn as collectStream,fEr as commonTripwires,khn as compareWorkflows,$mn as composeMiddleware,bj as composeScorers,aQe as computeToolSignature,Umn as conditionalMiddleware,Lae as confirmationMiddleware,Ajt as contextScopeToThreshold,MUr as contextToErrorContext,Z$t as cosineSimilarity,Nkn as createAIProvider,Lkn as createAIProviderWithFallback,xhn as createAdaptiveWorkflow,bvr as createAgentRoutes,vSn as createAgentWebSocketHandler,C_r as createAllRoutes,_V as createAnalyticsMiddleware,vje as createAndInitializePipeline,rRt as createAnnotatedTool,sj as createAnswerRelevancyScorer,yEr as createAnthropic,kmn as createApiKeyAuthInterceptor,jmn as createApiKeyMiddleware,W8t as createArtifactStore,zmn as createAsyncStream,zhn as createAuthMiddleware,LKt as createAuthProvider,ame as createAuthProviderMiddleware,Ekn as createAuthValidatorFromProvider,Kmn as createAuthWithRetryMiddleware,bGt as createAuthenticatedContext,fkn as createAuthenticatedRateLimitMiddleware,PUr as createBatchEvaluationError,_je as createBatchStrategy,xmn as createBearerAuthInterceptor,Hmn as createBearerTokenMiddleware,Fkn as createBestAIProvider,lj as createBiasDetectionScorer,Nmn as createCacheInterceptor,Whn as createCacheInvalidator,jhn as createCacheMiddleware,bHt as createChunker,Rue as createClient,Qhn as createCompressionMiddleware,Mje as createConditionalScorer,aS as createConfigurationError,uhn as createConfirmationRequest,Ahn as createConsensus3WithPrompt,DUr as createConsoleLoggerHook,mj as createContentSimilarityScorer,OCt as createContextEnricher,aj as createContextPrecisionScorer,ij as createContextRelevancyScorer,ESn as createContextWindow,uSn as createDataStreamResponse,I_r as createDataStreamWriter,nan as createDefaultRequestRouter,Pkn as createDefaultTripwireEvaluator,Amn as createDynamicAuthInterceptor,lhn as createElicitationCancel,J3 as createElicitationContext,cb as createElicitationRequest,Xyr as createElicitationResponse,Sf as createErrorFactory,fmn as createErrorFromNative,hmn as createErrorFromResponse,Fmn as createErrorHandlerInterceptor,Xhn as createErrorHandlingMiddleware,Gt as createErrorResponse,AUr as createEvaluationFailedError,pkn as createExpressAuthMiddleware,oj as createFaithfulnessScorer,ifn as createFieldValidator,mhn as createFormRequest,fj as createFormatScorer,SS as createFunctionScorer,rj as createHallucinationScorer,E_r as createHealthRoutes,Y_r as createHybridSearch,Oje as createInvertedScorer,vhn as createJsonResource,pj as createKeywordCoverageScorer,Rje as createKeywordScorer,$Ur as createLangfuseAdapter,hj as createLengthScorer,Pj as createLifecycleMiddleware,gEr as createLocalUsageReader,Cmn as createLoggingInterceptor,Zhn as createLoggingMiddleware,k_r as createMCPRoutes,r9t as createMCPServer,RUr as createMaxRetriesExceededError,x_r as createMemoryRoutes,KUr as createMetricsCollector,NUr as createMetricsCollectorHook,wEr as createMistral,BUr as createMockLangfuseClient,Jmn as createMultiAuthMiddleware,Ohn as createMultiJudgeWorkflow,mSn as createNDJSONHeaders,bmn as createNeuroLinkModel,Pue as createNeuroLinkProvider,NYr as createOAuthProviderFromConfig,vEr as createOpenAI,Rfn as createOpenAPIGenerator,CUr as createParseError,yje as createPipeline,whn as createPrompt,uj as createPromptAlignmentScorer,ukn as createProtectedMiddleware,IUr as createProviderError,RSn as createRAGPipeline,cEr as createRBACMiddleware,hkn as createRateLimitByUserMiddleware,Pmn as createRateLimitInterceptor,efn as createRateLimitMiddleware,gkn as createRateLimitStorage,Ije as createRegexScorer,XUr as createReportGenerator,l5t as createRequestBatcher,uEr as createRequestContext,Jhn as createRequestIdMiddleware,Mmn as createRequestTransformInterceptor,rfn as createRequestValidationMiddleware,Omn as createResponseTransformInterceptor,Imn as createRetryInterceptor,wKt as createRetryMiddleware,Vhn as createRoleMiddleware,pSn as createSSEHeaders,kje as createSamplingStrategy,Fd as createScorerMetadata,Yhn as createSecurityHeadersMiddleware,phn as createSelectRequest,Uhn as createServer,vkn as createSessionStorage,Pje as createSimpleLengthScorer,mqt as createSkillStore,bqt as createSkillTools,tfn as createSlidingWindowRateLimitMiddleware,EVe as createStrategyNotFoundError,Bmn as createStreamingClient,Emn as createStreamingResponse,dj as createSummarizationScorer,dhn as createTextInputRequest,yhn as createTextResource,Lmn as createTimeoutInterceptor,vKt as createTimeoutMiddleware,Khn as createTimingMiddleware,Wmn as createTokenManagerMiddleware,cj as createToneConsistencyScorer,d5t as createToolCache,c5t as createToolCallBatcher,dRt as createToolFromFunction,Dae as createToolMiddlewareChain,p5t as createToolResultCache,e9t as createToolRouter,A_r as createToolRoutes,nj as createToxicityScorer,AHt as createVectorQueryTool,ovr as decideSearchPlan,Vte as decisionBooleanConfidence,oA as decisionKey,Nue as decodeJWTPayload,cQe as dedupeTools,Wse as detectAndRedactPII,Xx as detectImageMimeType,ak as dynamicModelProvider,Yyr as elicitationResponseToProtocol,$se as enrichCandidate,M8r as estimateVideoTokens,Eje as evaluateBatch,Qs as evaluationErrors,_hn as executeMCP,OSn as executeWithCircuitBreaker,H3 as exposeAgentAsTool,hKt as exposeAgentsAsTools,W3 as exposeWorkflowAsTool,fKt as exposeWorkflowsAsTools,mdn as extractMetadata,lEr as extractToken,iRt as filterToolsByAnnotations,aO as flushOpenTelemetry,_Sn as formatContextWithCitations,Km as gateDecisionBoolean,Mfn as generateOpenAPIFromConfig,Pfn as generateOpenAPISpec,Uue as generateSummaryStats,Bkn as generateText,pKt as getAllWellKnownServers,Q5r as getAnalyticsMetrics,sRt as getAnnotationSummary,ehn as getApiKeyFromEnv,NL as getAuthContext,Tse as getAvailableProviders,skn as getAvailableStrategies,oT as getBestProvider,MSn as getCircuitBreaker,hGt as getCurrentSession,AA as getCurrentUser,akn as getDefaultChunkerConfig,S0e as getErrorMessage,Lje as getEvaluatorFactory,$je as getEvaluatorRegistry,Qmn as getJWTExpiry,Bk as getLangfuseContext,zX as getLangfuseHealthStatus,PCt as getLangfuseSpanProcessor,Mkn as getLocalUsageDescriptors,Ehn as getMCPStats,it as getMetricsAggregator,Ztn as getPoolStats,Tje as getPreset,bje as getPresetNames,ikn as getRecommendedStrategy,w6 as getRegisteredLocalUsageCliIds,hrn as getServerInfo,DCt as getSpanProcessors,Ukn as getTelemetryStatus,oRt as getToolSafetyLevel,cO as getTracer,MCt as getTracerProvider,k2 as getVideoProviderConfig,dKt as getWellKnownServer,Ise as getWorkflow,Mae as globalAgentExposureManager,Qg as globalAuthContext,uA as globalCircuitBreakerManager,V3 as globalElicitationManager,hhn as globalElicitationProtocol,Rae as globalMCPRegistryClient,xje as globalMetricsCollector,Lre as globalMultiServerManager,jre as globalRateLimiterManager,$ae as globalToolIntegrationManager,vGt as hasAllPermissions,yGt as hasAnyRole,LL as hasPermission,Ud as hasPricing,Kne as hasRole,np as inferAnnotations,Thn as initializeMCPEcosystem,sO as initializeOpenTelemetry,$kn as initializeTelemetry,pr as isAbortError,_Rr as isAnthropicConfig,vmn as isApiError,Wxr as isAsyncFunction,aRr as isAudioContent,fGt as isAuthenticated,UG as isCSVContent,tAr as isCliGenerateResult,rAr as isCommandResult,chn as isElicitationProtocolMessage,g5 as isError,y5 as isErrorInfo,xUr as isEvaluationError,iRr as isImageContent,Zmn as isJWTExpired,E0e as isJsonRecord,UX as isLangfuseInternalSpan,N0e as isModelAccessDeniedMessage,uRr as isMultimodalInput,dRr as isMultimodalMessageContent,yEt as isNativeVideoMimeType,ymn as isNeuroLinkError,Uk as isOpenTelemetryInitialized,sRr as isPDFContent,gmn as isRetryableError,kUr as isRetryableEvaluationError,y5t as isRetryableHTTPError,Gyr as isRetryableStatus,GN as isRetryableStatusCode,Sbe as isSTTResult,qY as isSafeToRetry,_0e as isStandardRecord,Hxr as isStringArray,KRr as isTTSResult,dbe as isTextContent,b5t as isTokenExpired,VRr as isToolDefinition,qRr as isToolResult,xbe as isTranscriptionSegment,NCt as isUsingExternalTracerProvider,gRr as isValidHexColor,OVt as isValidProvider,Abe as isValidRealtimeConfig,kbe as isValidSTTOptions,JRr as isValidTTSOptions,lY as isVertexVideoConfigured,lRr as isVideoContent,CE as jsonSchema,BX as langfuseShouldExportSpan,J_r as linearCombination,bhn as listMCPs,bsn as listWorkflows,tme as loadDocument,bSn as loadDocuments,h as logger,Nae as loggingMiddleware,M6t as manifestToSources,zyr as mapStatusToErrorCode,re as mcpLogger,aRt as mcpProtocolToolToServerTool,HY as mcpToolToNeuroLink,GY as mergeAnnotations,Hkn as mistral,_mn as neuroLinkAIInstance,jY as neuroLinkToolToMCP,Ere as normalizeAndValidate,yRr as normalizeHexColor,gre as normalizePhrases,Pw as normalizeText,Bl as observabilityHooks,jkn as openai,D0e as parseAllowedModels,dSn as pipeAsyncIterableToDataStream,FUr as pipelineToSpanAttributes,RHt as prepareRAGTool,okn as processDocument,$ue as protocolMessageToElicitation,ome as ragCircuitBreakerManager,bjt as rankCatalogue,wjt as reachableTextProviders,Okn as readAllLocalUsage,PN as readDecisionBoolean,Gte as readDecisionChoice,qte as readDecisionScore,K_r as reciprocalRankFusion,lSn as registerAllRoutes,iKt as registerDefaultAvatarHandlers,HWt as registerDefaultMusicHandlers,ldr as registerDefaultRealtimeHandlers,adr as registerDefaultSTTHandlers,sdr as registerDefaultTTSHandlers,Sdr as registerDefaultVideoHandlers,hd as registerLocalUsageReader,Tsn as registerWorkflow,Ejt as renderCandidate,Wne as requireAuth,wGt as requirePermission,TGt as requireRole,gGt as requireUser,nRt as requiresConfirmation,aC as rerank,vUr as resetMetricsAggregator,_oe as resolveArtifactStorageType,pE as resolveDefaultDecisionProvider,NN as resolveEntry,kN as resolveHistoryBudget,d6t as resolveToolRoutingExclusions,Are as retrieve,mGt as runWithAuthContext,Uv as runWithCurrentLangfuseContext,Rse as runWorkflow,WY as sanitizeToolName,LUr as scorerToSpanAttributes,U$t as selectIrrelevantMessages,e6t as selectRelevantToolNames,o6t as selectServersByDecision,lRt as serverToolToMCPProtocol,lYr as servesInferenceKind,$v as setLangfuseContext,lO as shutdownOpenTelemetry,Ian as simpleRerank,Jx as sniffImageMimeType,UUr as startLangfuseAdapter,nOe as stepCountIs,Sje as streamBatchEvaluation,SSn as summarizeContext,B$t as summaryPreservesContext,gEt as supportsNativeVideo,sAr as toErrorInfo,hp as tokenize,UOr as tool,tRt as validateAnnotations,n9t as validateMCPTool,nu as validateParams,nun as validateQuery,rd as validateRequest,Xjt as validateResponse,frn as validateServerTools,ihn as validateTool,pRt as validateToolName,x3 as validateWorkflow,Fae as validationMiddleware,v5t as withHTTPRetry,G9e as withRetry,NC as wrapError,X3 as wrapToolWithElicitation,yKt as wrapToolsWithElicitation};/*! Bundled license information:
|
|
2524
2524
|
|
|
2525
2525
|
@google/genai/dist/index.mjs:
|
|
2526
2526
|
(**
|