@juspay/neurolink 10.4.0 → 10.4.1

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 CHANGED
@@ -1,3 +1,9 @@
1
+ ## [10.4.1](https://github.com/juspay/neurolink/compare/v10.4.0...v10.4.1) (2026-07-22)
2
+
3
+ ### Bug Fixes
4
+
5
+ - **(context):** end the derived turn deadline one wrap-up lead before the hard abort ([b2f2d77](https://github.com/juspay/neurolink/commit/b2f2d77599dc0582c75ca3306353e3271a66a1ad))
6
+
1
7
  ## [10.4.0](https://github.com/juspay/neurolink/compare/v10.3.1...v10.4.0) (2026-07-22)
2
8
 
3
9
  ### Features
@@ -825,7 +825,7 @@ Call this with a task description or an exact tool name; matching tools are load
825
825
  ${t}
826
826
  ]`}function T(){let B=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1,W=arguments.length>1&&arguments[1]!==void 0?arguments[1]:-1,X=r[e]==="\\";if(X&&(e++,X=!0),AM(r[e])){let q=kne(r[e])?kne:Cne(r[e])?Cne:TG(r[e])?TG:_ne,ae=e,be=t.length,J='"';for(e++;;){if(e>=r.length){let ve=I(e-1);return!B&&RM(r.charAt(ve))?(e=ae,t=t.substring(0,be),T(!0)):(J=Id(J,'"'),t+=J,!0)}if(e===W)return J=Id(J,'"'),t+=J,!0;if(q(r[e])){let ve=e,me=J.length;if(J+='"',e++,t+=J,i(!1),B||e>=r.length||RM(r[e])||AM(r[e])||jy(r[e]))return S(),!0;let je=I(ve-1),ge=r.charAt(je);if(ge===",")return e=ae,t=t.substring(0,be),T(!1,je);if(RM(ge))return e=ae,t=t.substring(0,be),T(!0);t=t.substring(0,be),e=ve+1,J=`${J.substring(0,me)}\\${J.substring(me)}`}else if(B&&wne(r[e])){if(r[e-1]===":"&&Tne.test(r.substring(ae+1,e+2)))for(;e<r.length&&Sne.test(r[e]);)J+=r[e],e++;return J=Id(J,'"'),t+=J,S(),!0}else if(r[e]==="\\"){let ve=r.charAt(e+1);if(ajt[ve]!==void 0)J+=r.slice(e,e+2),e+=2;else if(ve==="u"){let je=2;for(;je<6&&KLe(r[e+je]);)je++;je===6?(J+=r.slice(e,e+6),e+=6):e+je>=r.length?e=r.length:G()}else ve===`
827
827
  `?(J+="\\n",e+=2):(J+=ve,e+=2)}else{let ve=r.charAt(e);ve==='"'&&r[e-1]!=="\\"?(J+=`\\${ve}`,e++):YLe(ve)?(J+=ijt[ve],e++):(JLe(ve)||z(ve),J+=ve,e++)}X&&f()}}return!1}function S(){let B=!1;for(i();r[e]==="+";){B=!0,e++,i(),t=T_(t,'"',!0);let W=t.length;T()?t=QLe(t,W,1):t=Id(t,'"')}return B}function E(){let B=e;if(r[e]==="-"){if(e++,M())return N(B),!0;if(!jy(r[e]))return e=B,!1}for(;jy(r[e]);)e++;if(r[e]==="."){if(e++,M())return N(B),!0;if(!jy(r[e]))return e=B,!1;for(;jy(r[e]);)e++}if(r[e]==="e"||r[e]==="E"){if(e++,(r[e]==="-"||r[e]==="+")&&e++,M())return N(B),!0;if(!jy(r[e]))return e=B,!1;for(;jy(r[e]);)e++}if(!M())return e=B,!1;if(e>B){let W=r.slice(B,e),X=/^0\d/.test(W);return t+=X?`"${W}"`:W,!0}return!1}function C(){return R("true","true")||R("false","false")||R("null","null")||R("True","true")||R("False","false")||R("None","null")}function R(B,W){return r.slice(e,e+B.length)===B?(t+=W,e+=B.length,!0):!1}function P(B){let W=e;if(bne(r[e])){for(;e<r.length&&vne(r[e]);)e++;let X=e;for(;zy(r,X);)X++;if(r[X]==="(")return e=X+1,s(),r[e]===")"&&(e++,r[e]===";"&&e++),!0}for(;e<r.length&&!wne(r[e])&&!AM(r[e])&&(!B||r[e]!==":");)e++;if(r[e-1]===":"&&Tne.test(r.substring(W,e+2)))for(;e<r.length&&Sne.test(r[e]);)e++;if(e>W){for(;zy(r,e-1)&&e>0;)e--;let X=r.slice(W,e);return t+=X==="undefined"?"null":JSON.stringify(X),r[e]==='"'&&e++,!0}}function A(){if(r[e]==="/"){let B=e;for(e++;e<r.length&&(r[e]!=="/"||r[e-1]==="\\");)e++;return e++,t+=JSON.stringify(r.substring(B,e)),!0}}function I(B){let W=B;for(;W>0&&zy(r,W);)W--;return W}function M(){return e>=r.length||RM(r[e])||zy(r,e)}function N(B){t+=`${r.slice(B,e)}0`}function z(B){throw new yg(`Invalid character ${JSON.stringify(B)}`,e)}function O(){throw new yg(`Unexpected character ${JSON.stringify(r[e])}`,e)}function L(){throw new yg("Unexpected end of json string",r.length)}function U(){throw new yg("Object key expected",e)}function $(){throw new yg("Colon expected",e)}function G(){let B=r.slice(e,e+6);throw new yg(`Invalid unicode character "${B}"`,e)}}function cjt(r,e){return r[e]==="*"&&r[e+1]==="/"}var ijt,ajt,r1e=k(()=>{WLe();t1e();ijt={"\b":"\\b","\f":"\\f","\n":"\\n","\r":"\\r"," ":"\\t"},ajt={'"':'"',"\\":"\\","/":"/",b:"\b",f:"\f",n:`
828
- `,r:"\r",t:" "}});var n1e=k(()=>{r1e()});function Ane(r,e=0){for(let t=e;t<r.length;t++){let n=r[t];if(n!=="{"&&n!=="[")continue;let o=n==="{"?"}":"]",s=0,i=!1,a=!1;for(let c=t;c<r.length;c++){let l=r[c];if(a){a=!1;continue}if(l==="\\"){a=!0;continue}if(l==='"'){i=!i;continue}if(!i){if(l===n)s++;else if(l===o&&(s--,s===0))return{span:r.substring(t,c+1),end:c+1}}}}return null}var o1e=k(()=>{"use strict"});function ljt(r){return typeof r.safeParse=="function"}function ujt(r){try{return{value:JSON.parse(r),repaired:!1}}catch{}try{let e=Rne(r),t=JSON.parse(e);return e!==r&&g.shouldLog("debug")&&g.debug("[coerceJsonToSchema] jsonrepair altered model output",{originalLength:r.length,repairedLength:e.length}),{value:t,repaired:e!==r}}catch{return}}function Ine(r,e=0){if(e>djt)return{value:r,changed:!1};if(typeof r=="string"){let t=r.trim();if(t.startsWith("{")&&t.endsWith("}")||t.startsWith("[")&&t.endsWith("]"))try{let o=JSON.parse(t);if(o!==null&&typeof o=="object")return{value:o,changed:!0}}catch{}return{value:r,changed:!1}}if(Array.isArray(r)){let t=!1,n=r.map(o=>{let s=Ine(o,e+1);return s.changed&&(t=!0),s.value});return{value:t?n:r,changed:t}}if(r!==null&&typeof r=="object"){let t=!1,n={};for(let[o,s]of Object.entries(r)){let i=Ine(s,e+1);i.changed&&(t=!0),n[o]=i.value}return{value:t?n:r,changed:t}}return{value:r,changed:!1}}function SG(r,e){if(typeof r!="string"||r.trim().length===0)return null;let t=[],n=0;for(;;){let h=Ane(r,n);if(!h)break;t.push({text:h.span,truncated:!1}),n=h.end}let o=[r.indexOf("{"),r.indexOf("[")].filter(h=>h>=0),s=o.length>0?Math.min(...o):-1,i=Math.max(r.lastIndexOf("}"),r.lastIndexOf("]"));s>=0&&i>s&&t.push({text:r.slice(s,i+1),truncated:!1}),s>=0&&t.push({text:r.slice(s),truncated:!0});let a=r.trim();if(a.length>1&&a.startsWith('"')&&a.endsWith('"'))try{let h=JSON.parse(a);if(typeof h=="string"){let y=0;for(;;){let x=Ane(h,y);if(!x)break;t.push({text:x.span,truncated:!1}),y=x.end}}}catch{}let c,l=[],u=!!(e&&ljt(e)),d=new Set;for(let h of t){if(d.has(h.text))continue;d.add(h.text);let y=ujt(h.text);if(y===void 0||y.value===null||typeof y.value!="object")continue;let x={value:y.value,repaired:y.repaired,truncated:h.truncated};if(c===void 0&&(c=x),!u)break;let b=e;if(b.safeParse(y.value).success)l.push(x);else{let T=Ine(y.value);T.changed&&T.value!==null&&typeof T.value=="object"&&b.safeParse(T.value).success?l.push({value:T.value,repaired:!0,truncated:h.truncated}):Array.isArray(y.value)&&y.value.length===1&&y.value[0]!==null&&typeof y.value[0]=="object"&&!Array.isArray(y.value[0])&&b.safeParse(y.value[0]).success&&l.push({value:y.value[0],repaired:!0,truncated:h.truncated})}}let f=(l.length>0?l.reduce((h,y)=>JSON.stringify(y.value).length>JSON.stringify(h.value).length?y:h):void 0)??c;return f===void 0?null:{content:JSON.stringify(f.value),structuredData:f.value,repaired:f.repaired,truncated:f.truncated}}var djt,Pne=k(()=>{"use strict";n1e();H();o1e();djt=6});function s1e(r){let e=[],t=[];for(let n of r)n.role==="system"?e.push(n):t.push(n);return e.length===0||t.length===0?{system:void 0,messages:r}:{system:e,messages:t}}var i1e=k(()=>{"use strict"});var Mne={};re(Mne,{coerceType:()=>wG,createToolCallRepair:()=>pjt});function pjt(){return async({toolCall:r,tools:e,inputSchema:t,error:n})=>{let{NoSuchToolError:o,InvalidToolInputError:s}=await Promise.resolve().then(()=>(Um(),ILe));if(o.isInstance(n))return mjt(r,Object.keys(e));if(s.isInstance(n))try{let i=await t({toolName:r.toolName});return fjt(r,i)}catch{return null}return null}}function mjt(r,e){let t=r.toolName;if(!t||t.trim().length===0)return null;let n=e.find(c=>c.toLowerCase()===t.toLowerCase());if(n)return g.debug(`[ToolCallRepair] Name repair (case): "${t}" \u2192 "${n}"`),{...r,toolName:n};let o=t.toLowerCase(),s=e.filter(c=>{let l=c.toLowerCase();return l.includes(o)||o.includes(l)});if(s.length===1)return g.debug(`[ToolCallRepair] Name repair (substring): "${t}" \u2192 "${s[0]}"`),{...r,toolName:s[0]};let i=null,a=1/0;for(let c of e){let l=a1e(o,c.toLowerCase()),u=Math.max(t.length,c.length),d=u===0?0:l/u;d<.3&&d<a&&(a=d,i=c)}return i?(g.debug(`[ToolCallRepair] Name repair (levenshtein ${a.toFixed(2)}): "${t}" \u2192 "${i}"`),{...r,toolName:i}):(g.debug(`[ToolCallRepair] Could not repair tool name "${t}". Available: [${e.join(", ")}]`),null)}function fjt(r,e){let t;try{t=JSON.parse(r.input)}catch{return null}if(!t||typeof t!="object"||Array.isArray(t))return null;let n=e.properties;if(!n)return null;let o=Object.keys(n),s=t,i=Object.keys(s),a=Object.create(null),c=!1,l=e.additionalProperties===!1;for(let u of i){if(o.includes(u)){a[u]=s[u];continue}let d=gjt(u,o);if(d){if(Object.prototype.hasOwnProperty.call(a,d)){c=!0;continue}g.debug(`[ToolCallRepair] Param repair: "${u}" \u2192 "${d}" (tool: ${r.toolName})`),a[d]=s[u],c=!0}else l?(g.debug(`[ToolCallRepair] Dropping unmapped key "${u}" (additionalProperties: false, tool: ${r.toolName})`),c=!0):a[u]=s[u]}for(let u of Object.keys(a)){let d=n[u];if(!d)continue;let p=wG(a[u],d);p!==a[u]&&(g.debug(`[ToolCallRepair] Type coercion on "${u}": ${typeof a[u]} \u2192 ${typeof p} (tool: ${r.toolName})`),a[u]=p,c=!0)}return c?{...r,input:JSON.stringify(a)}:null}function gjt(r,e){let t=r.toLowerCase(),n=e.find(i=>i.toLowerCase()===t);if(n)return n;let o=null,s=1/0;for(let i of e){let a=a1e(t,i.toLowerCase());a<=2&&a<s&&(s=a,o=i)}return o}function wG(r,e){let t=e.type;if(!t||r===null||r===void 0)return r;if(t==="number"&&typeof r=="string"){let n=r.trim();if(n!==""){let o=Number(n);if(isFinite(o))return o}}if(t==="integer"&&typeof r=="string"){let n=r.trim();if(/^[+-]?\d+$/.test(n)){let o=Number(n);if(Number.isSafeInteger(o))return o}}if(t==="boolean"&&typeof r=="string"){if(r.toLowerCase()==="true")return!0;if(r.toLowerCase()==="false")return!1}if(t==="object"&&typeof r=="string")try{let n=JSON.parse(r);if(n&&typeof n=="object"&&!Array.isArray(n))return n}catch{}if(t==="array"&&typeof r=="string")try{let n=JSON.parse(r);if(Array.isArray(n))return n}catch{}return t==="array"&&!Array.isArray(r)&&typeof r!="string"?[r]:r}function a1e(r,e){if(r===e)return 0;if(r.length===0)return e.length;if(e.length===0)return r.length;r.length>e.length&&([r,e]=[e,r]);let t=r.length,n=e.length,o=new Array(t+1),s=new Array(t+1);for(let i=0;i<=t;i++)o[i]=i;for(let i=1;i<=n;i++){s[0]=i;for(let a=1;a<=t;a++){let c=r[a-1]===e[i-1]?0:1;s[a]=Math.min(o[a]+1,s[a-1]+1,o[a-1]+c)}[o,s]=[s,o]}return o[t]}var EG=k(()=>{"use strict";H()});function yjt(r){if(r===void 0)return"";try{return((typeof r=="string"?r:JSON.stringify(r))??"").substring(0,200)}catch{return"[unserializable]"}}function xjt(r,e){let t=Nc(r.timeout),n=typeof r.turnTimeoutMs=="number"&&Number.isFinite(r.turnTimeoutMs)&&r.turnTimeoutMs>0;r.turnTimeoutMs!==void 0&&!n&&g.warn("[GenerationHandler] Ignoring invalid turnTimeoutMs \u2014 expected a positive number of milliseconds; falling back to the timeout option",{turnTimeoutMs:r.turnTimeoutMs});let o=n?r.turnTimeoutMs:t,s=o?Math.min(r.wrapupTimeLeadMs??OP,Math.floor(o/4)):0,i=o?e+o:void 0;return{callerTimeoutMs:t,turnBudgetMs:o,wrapupLeadMs:s,turnDeadline:i}}function bjt(r,e,t){let n={};return t!==void 0&&(n.neurolink={timeoutMs:t}),r.thinkingConfig?.enabled&&e&&(n.google={thinkingConfig:{...r.thinkingConfig.thinkingLevel&&{thinkingLevel:r.thinkingConfig.thinkingLevel},...r.thinkingConfig.budgetTokens&&!r.thinkingConfig.thinkingLevel&&{thinkingBudget:r.thinkingConfig.budgetTokens},includeThoughts:!0}}),Object.keys(n).length>0?n:void 0}function vjt(r,e){let t=r?.messages??e;return{...r??{},messages:[...t,{role:"user",content:"The time budget for this task is nearly exhausted. Do not call any more tools. Give your best final answer NOW from the information already gathered, and note anything you could not verify in the remaining time."}],toolChoice:"none"}}var hjt,IM,c1e=k(()=>{"use strict";Lr();RLe();Hr();H();SM();Ad();PLe();Hn();fG();mi();GLe();vG();Pne();Um();PP();hv();i1e();hjt=Pe.generation;IM=class{constructor(e,t,n,o,s,i){this.providerName=e;this.modelName=t;this.supportsToolsFn=n;this.getTelemetryConfigFn=o;this.handleToolStorageFn=s;this.getEmitterFn=i}providerName;modelName;supportsToolsFn;getTelemetryConfigFn;handleToolStorageFn;getEmitterFn;async callGenerateText(e,t,n,o,s){let{shouldUseTools:i,includeStructuredOutput:a,turnStartMs:c}=s,l=this.providerName==="google-ai"||this.providerName==="vertex",u=this.providerName==="anthropic"||this.providerName==="bedrock"||this.providerName==="vertex"&&this.modelName?.startsWith("claude-"),p=a&&(!!o.schema||o.output?.format==="json"||o.output?.format==="structured")&&!VLe(this.providerName,this.modelName,i,Object.keys(n).length),f=n;if(u&&i&&Object.keys(f).length>0){let M=Object.keys(f),N=M[M.length-1];if(N&&f[N]){let z=f[N];f[N]={...z,providerOptions:{...z.providerOptions??{},anthropic:{cacheControl:{type:"ephemeral"}}}}}}let h=o.prepareStep,{callerTimeoutMs:y,turnBudgetMs:x,wrapupLeadMs:b,turnDeadline:T}=xjt(o,c),S=!1,E=bjt(o,l,y),{system:C,messages:R}=s1e(t),P={toolCount:-1,tokens:0},A=jLe({provider:this.providerName??"unknown",model:this.modelName,maxTokens:o.maxTokens,getFixedOverheadTokens:()=>{let M=i?Object.keys(f).length:0;return M!==P.toolCount&&(P={toolCount:M,tokens:zLe(C,i?f:void 0,this.providerName)}),P.tokens}}),I=await ig({model:e,...C&&{system:C},messages:R,...i&&Object.keys(f).length>0&&{tools:f},stopWhen:AP(o.maxSteps??Ss),...i&&o.toolChoice&&{toolChoice:o.toolChoice},experimental_prepareStep:(async M=>{let N=h?await h({...M,maxSteps:o.maxSteps??Ss}):void 0,z=N?.messages,O=M.steps[M.steps.length-1],L=A(z??M.messages,O?.usage?.inputTokens),U=L?{...N??{},messages:L}:N;return T!==void 0&&i&&Date.now()>=T-b?(S||(S=!0,g.warn("[GenerationHandler] Turn budget nearly exhausted \u2014 forcing wrap-up (toolChoice: none)",{provider:this.providerName,turnBudgetMs:x,wrapupLeadMs:b,stepNumber:M.stepNumber})),vjt(U,M.messages)):U}),temperature:o.temperature,maxOutputTokens:o.maxTokens,maxRetries:0,abortSignal:o.abortSignal,...i&&!o.disableToolCallRepair&&{experimental_repairToolCall:(async(...M)=>{let{createToolCallRepair:N}=await Promise.resolve().then(()=>(EG(),Mne));return N()(...M)})},...E&&{providerOptions:E},...p&&o.schema&&{experimental_output:FB.object({schema:o.schema})},...o.thinkingConfig?.enabled&&u&&o.thinkingConfig.budgetTokens&&!o.thinkingConfig.thinkingLevel&&{experimental_thinking:{type:"enabled",budgetTokens:o.thinkingConfig.budgetTokens}},experimental_telemetry:this.getTelemetryConfigFn(o,"generate"),onStepFinish:({toolCalls:M,toolResults:N})=>{g.info("Tool execution completed",{toolResults:N,toolCalls:M}),Uy(this.getEmitterFn?.(),N),this.handleToolStorageFn(M,N,o,new Date).catch(z=>{g.warn("[GenerationHandler] Failed to store tool executions",{provider:this.providerName,error:z instanceof Error?z.message:String(z)})})}});return S&&Object.defineProperty(I,"__nlTurnWrapup",{value:!0,enumerable:!1}),I}async executeGeneration(e,t,n,o){return hjt.startActiveSpan("neurolink.executeGeneration",{kind:Cr.INTERNAL},async s=>{let i=!o.disableTools&&this.supportsToolsFn(),a=Object.keys(n||{}).length,c=!!o.schema||o.output?.format==="json"||o.output?.format==="structured";s.setAttribute("gen_ai.system",this.providerName||"unknown"),s.setAttribute("neurolink.structured_output",c),s.setAttribute("neurolink.tool_count",a),s.setAttribute("neurolink.message_count",t.length),s.setAttribute("gen_ai.request.model",uG(e,this.modelName||"unknown"));let l=o.requestId||o.context?.requestId||"unknown";if(g.info("[GenerationHandler] Calling generateText",{requestId:l,model:uG(e),messageCount:t.length,toolCount:a,maxSteps:o.maxSteps,temperature:o.temperature}),g.shouldLog("debug"))try{g.debug("[Observability] Full generateText parameters",{requestId:l,model:uG(e),messageCount:t.length,messages:t.map((d,p)=>({index:p,role:d.role,contentLength:typeof d.content=="string"?d.content.length:yjt(d.content).length,contentPreview:typeof d.content=="string"?d.content.substring(0,200):"[multimodal]"})),toolNames:Object.keys(n||{}),toolCount:a,maxSteps:o.maxSteps,temperature:o.temperature,maxTokens:o.maxTokens})}catch{}let u=Date.now();try{let d=await mG(()=>this.callGenerateText(e,t,n,o,{shouldUseTools:i,includeStructuredOutput:!0,turnStartMs:u}),s,"generateText");if(g.info("[GenerationHandler] generateText returned",{requestId:l,durationMs:Date.now()-u,finishReason:d.finishReason,steps:d.steps?.length||1,toolCallsTotal:d.toolCalls?.length||0,responseChars:d.text?.length||0}),g.shouldLog("debug")&&g.debug("[Observability] LLM response metadata",{requestId:l,responseLength:d.text?.length||0,hasToolCalls:!!(d.toolCalls&&d.toolCalls.length>0),toolCallCount:d.toolCalls?.length||0,toolNames:d.toolCalls?.map(p=>p.toolName),finishReason:d.finishReason,stepCount:d.steps?.length||0,steps:d.steps?.map((p,f)=>({stepIndex:f,stepType:p.stepType,textLength:p.text?.length||0,toolCallCount:p.toolCalls?.length||0,toolNames:p.toolCalls?.map(h=>h.toolName),toolResultCount:p.toolResults?.length||0,finishReason:p.finishReason})),usage:d.usage}),d.usage){s.setAttribute("gen_ai.usage.input_tokens",d.usage.inputTokens||0),s.setAttribute("gen_ai.usage.output_tokens",d.usage.outputTokens||0);let p=wo(this.providerName,this.modelName,{input:d.usage.inputTokens||0,output:d.usage.outputTokens||0,total:(d.usage.inputTokens||0)+(d.usage.outputTokens||0)});s.setAttribute("neurolink.cost",p??0)}return d.finishReason&&s.setAttribute("gen_ai.response.finish_reason",d.finishReason),s.setStatus({code:Le.OK}),d}catch(d){let p=c&&bG(d);if(c&&(d instanceof wa||qLe(d)||p)){s.setAttribute("neurolink.has_fallback",!0),s.addEvent("retry.initial_failure",{"error.message":d instanceof Error?d.message:String(d),"retry.attempt":1,"retry.reason":d instanceof wa?"NoObjectGeneratedError_structured_output_fallback":p?"schema_complexity_structured_output_fallback":"tools_schema_conflict_structured_output_fallback"}),p?g.warn("[GenerationHandler] schema too complex for provider constrained decoding \u2014 retrying with prompt-based JSON",{provider:this.providerName,model:this.modelName,error:d instanceof Error?d.message:String(d)}):g.debug("[GenerationHandler] structured-output conflict caught - falling back to manual JSON extraction",{provider:this.providerName,model:this.modelName,error:d instanceof Error?d.message:String(d)});let h=await mG(()=>this.callGenerateText(e,t,n,o,{shouldUseTools:i,includeStructuredOutput:!1,turnStartMs:u}),s,"generateText(fallback)");if(s.addEvent("retry.recovered",{"retry.attempts":2,"retry.strategy":"structured_output_disabled"}),s.setAttribute("retry.count",1),g.info("[GenerationHandler] generateText returned (fallback)",{requestId:l,durationMs:Date.now()-u,finishReason:h.finishReason,steps:h.steps?.length||1,toolCallsTotal:h.toolCalls?.length||0,responseChars:h.text?.length||0}),h.usage){s.setAttribute("gen_ai.usage.input_tokens",h.usage.inputTokens||0),s.setAttribute("gen_ai.usage.output_tokens",h.usage.outputTokens||0);let y=wo(this.providerName,this.modelName,{input:h.usage.inputTokens||0,output:h.usage.outputTokens||0,total:(h.usage.inputTokens||0)+(h.usage.outputTokens||0)});s.setAttribute("neurolink.cost",y??0)}return h.finishReason&&s.setAttribute("gen_ai.response.finish_reason",h.finishReason),s.setStatus({code:Le.OK}),h}if(HLe(d)&&typeof o.temperature=="number"){s.setAttribute("neurolink.has_fallback",!0),s.addEvent("retry.initial_failure",{"error.message":d instanceof Error?d.message:String(d),"retry.attempt":1,"retry.reason":"temperature_deprecated"}),g.debug("[GenerationHandler] temperature-deprecated error caught - retrying without temperature",{provider:this.providerName,model:this.modelName,error:d instanceof Error?d.message:String(d)});let h=await mG(()=>this.callGenerateText(e,t,n,{...o,temperature:void 0},{shouldUseTools:i,includeStructuredOutput:!0,turnStartMs:u}),s,"generateText(no-temperature)");if(s.addEvent("retry.recovered",{"retry.attempts":2,"retry.strategy":"temperature_omitted"}),s.setAttribute("retry.count",1),h.usage){s.setAttribute("gen_ai.usage.input_tokens",h.usage.inputTokens||0),s.setAttribute("gen_ai.usage.output_tokens",h.usage.outputTokens||0);let y=wo(this.providerName,this.modelName,{input:h.usage.inputTokens||0,output:h.usage.outputTokens||0,total:(h.usage.inputTokens||0)+(h.usage.outputTokens||0)});s.setAttribute("neurolink.cost",y??0)}return h.finishReason&&s.setAttribute("gen_ai.response.finish_reason",h.finishReason),s.setStatus({code:Le.OK}),h}throw s.setStatus({code:Le.ERROR,message:d instanceof Error?d.message:String(d)}),d}finally{s.end()}})}extractCacheMetricsFromProviderMetadata(e){let t=e.providerMetadata;if(!t)return{};let n=t.anthropic;if(n){let o=dne(n),s=pne(n);return{...o!==void 0&&{cacheCreationTokens:o},...s!==void 0&&{cacheReadTokens:s}}}return{}}logGenerationComplete(e){let t=this.extractCacheMetricsFromProviderMetadata(e);g.shouldLog("debug")&&g.debug("generateText completed",{provider:this.providerName,model:this.modelName,responseLength:e.text?.length||0,toolResultsCount:e.toolResults?.length||0,finishReason:e.finishReason,usage:e.usage,...t.cacheCreationTokens!==void 0&&{cacheCreationTokens:t.cacheCreationTokens},...t.cacheReadTokens!==void 0&&{cacheReadTokens:t.cacheReadTokens},timestamp:Date.now()})}extractToolInformation(e){let t=[],n=[];if(e.toolCalls&&e.toolCalls.length>0&&t.push(...e.toolCalls.map(o=>o.toolName||o.name||"unknown")),e.steps&&Array.isArray(e.steps)){let o=new Map;for(let s of e.steps||[]){if(s?.toolCalls&&Array.isArray(s.toolCalls))for(let i of s.toolCalls){let a=i,c=a.toolName||a.name||"unknown",l=a.toolCallId||a.id||c;t.push(c);let u={};a.args?u=a.args:a.arguments?u=a.arguments:a.parameters&&(u=a.parameters),o.set(l,u),o.set(c,u)}if(s?.toolResults&&Array.isArray(s.toolResults))for(let i of s.toolResults){let a=i,c=a.toolName||"unknown",l=a.toolCallId||a.id,u=a.args??a.arguments??a.parameters??a.input??o.get(l||c)??{};n.push({name:c,input:u,output:a.output??a.result??"success"})}}}return{toolsUsed:[...new Set(t)],toolExecutions:n}}formatEnhancedResult(e,t,n,o,s){let i=!!s.schema||s.output?.format==="json"||s.output?.format==="structured",a,c,l=!1,u=!1,d=E=>{let C=E.replace(/^```(?:json)?\s*\n?/i,"").replace(/\n?```\s*$/i,"").trim(),R=SG(C,s.schema);if(R)return c=R.structuredData,R.repaired&&(l=!0),R.truncated&&(u=!0),R.content;try{let P=JSON.parse(C);if(P==="")return g.warn("[GenerationHandler] schema requested but the model returned an empty JSON string; normalizing to empty content",{provider:this.providerName,model:this.modelName}),"";if(P!=null)return c=P,C}catch{}return g.warn("[GenerationHandler] schema requested but no JSON could be recovered from model text; returning raw text",{provider:this.providerName,model:this.modelName}),C};if(i)try{let E=e.experimental_output,C=typeof E=="string"&&E===(e.text??"");E!==void 0&&!C?(c=E,a=JSON.stringify(E)):a=d(e.text||"")}catch(E){g.debug("[GenerationHandler] experimental_output threw, falling back to text parsing",{error:E instanceof Error?E.message:String(E)}),a=d(e.text||"")}else a=e.text;i&&e.finishReason==="length"&&(u=!0,g.warn("[GenerationHandler] Structured output truncated by token cap (finishReason=length); increase maxTokens",{provider:this.providerName,model:this.modelName}));let p=v_(e.usage);if(p.cacheCreationTokens===void 0||p.cacheReadTokens===void 0){let E=this.extractCacheMetricsFromProviderMetadata(e);if(p.cacheCreationTokens===void 0&&E.cacheCreationTokens!==void 0&&(p.cacheCreationTokens=E.cacheCreationTokens),p.cacheReadTokens===void 0&&E.cacheReadTokens!==void 0&&(p.cacheReadTokens=E.cacheReadTokens),p.cacheReadTokens!==void 0){let C=mne(p.cacheReadTokens,p.input);C!==void 0&&(p.cacheSavingsPercent=C)}}let f=e.reasoning,h=f?typeof f=="string"?f:Array.isArray(f)?f.map(E=>typeof E=="string"?E:E.text??JSON.stringify(E)).join(`
828
+ `,r:"\r",t:" "}});var n1e=k(()=>{r1e()});function Ane(r,e=0){for(let t=e;t<r.length;t++){let n=r[t];if(n!=="{"&&n!=="[")continue;let o=n==="{"?"}":"]",s=0,i=!1,a=!1;for(let c=t;c<r.length;c++){let l=r[c];if(a){a=!1;continue}if(l==="\\"){a=!0;continue}if(l==='"'){i=!i;continue}if(!i){if(l===n)s++;else if(l===o&&(s--,s===0))return{span:r.substring(t,c+1),end:c+1}}}}return null}var o1e=k(()=>{"use strict"});function ljt(r){return typeof r.safeParse=="function"}function ujt(r){try{return{value:JSON.parse(r),repaired:!1}}catch{}try{let e=Rne(r),t=JSON.parse(e);return e!==r&&g.shouldLog("debug")&&g.debug("[coerceJsonToSchema] jsonrepair altered model output",{originalLength:r.length,repairedLength:e.length}),{value:t,repaired:e!==r}}catch{return}}function Ine(r,e=0){if(e>djt)return{value:r,changed:!1};if(typeof r=="string"){let t=r.trim();if(t.startsWith("{")&&t.endsWith("}")||t.startsWith("[")&&t.endsWith("]"))try{let o=JSON.parse(t);if(o!==null&&typeof o=="object")return{value:o,changed:!0}}catch{}return{value:r,changed:!1}}if(Array.isArray(r)){let t=!1,n=r.map(o=>{let s=Ine(o,e+1);return s.changed&&(t=!0),s.value});return{value:t?n:r,changed:t}}if(r!==null&&typeof r=="object"){let t=!1,n={};for(let[o,s]of Object.entries(r)){let i=Ine(s,e+1);i.changed&&(t=!0),n[o]=i.value}return{value:t?n:r,changed:t}}return{value:r,changed:!1}}function SG(r,e){if(typeof r!="string"||r.trim().length===0)return null;let t=[],n=0;for(;;){let h=Ane(r,n);if(!h)break;t.push({text:h.span,truncated:!1}),n=h.end}let o=[r.indexOf("{"),r.indexOf("[")].filter(h=>h>=0),s=o.length>0?Math.min(...o):-1,i=Math.max(r.lastIndexOf("}"),r.lastIndexOf("]"));s>=0&&i>s&&t.push({text:r.slice(s,i+1),truncated:!1}),s>=0&&t.push({text:r.slice(s),truncated:!0});let a=r.trim();if(a.length>1&&a.startsWith('"')&&a.endsWith('"'))try{let h=JSON.parse(a);if(typeof h=="string"){let y=0;for(;;){let x=Ane(h,y);if(!x)break;t.push({text:x.span,truncated:!1}),y=x.end}}}catch{}let c,l=[],u=!!(e&&ljt(e)),d=new Set;for(let h of t){if(d.has(h.text))continue;d.add(h.text);let y=ujt(h.text);if(y===void 0||y.value===null||typeof y.value!="object")continue;let x={value:y.value,repaired:y.repaired,truncated:h.truncated};if(c===void 0&&(c=x),!u)break;let b=e;if(b.safeParse(y.value).success)l.push(x);else{let T=Ine(y.value);T.changed&&T.value!==null&&typeof T.value=="object"&&b.safeParse(T.value).success?l.push({value:T.value,repaired:!0,truncated:h.truncated}):Array.isArray(y.value)&&y.value.length===1&&y.value[0]!==null&&typeof y.value[0]=="object"&&!Array.isArray(y.value[0])&&b.safeParse(y.value[0]).success&&l.push({value:y.value[0],repaired:!0,truncated:h.truncated})}}let f=(l.length>0?l.reduce((h,y)=>JSON.stringify(y.value).length>JSON.stringify(h.value).length?y:h):void 0)??c;return f===void 0?null:{content:JSON.stringify(f.value),structuredData:f.value,repaired:f.repaired,truncated:f.truncated}}var djt,Pne=k(()=>{"use strict";n1e();H();o1e();djt=6});function s1e(r){let e=[],t=[];for(let n of r)n.role==="system"?e.push(n):t.push(n);return e.length===0||t.length===0?{system:void 0,messages:r}:{system:e,messages:t}}var i1e=k(()=>{"use strict"});var Mne={};re(Mne,{coerceType:()=>wG,createToolCallRepair:()=>pjt});function pjt(){return async({toolCall:r,tools:e,inputSchema:t,error:n})=>{let{NoSuchToolError:o,InvalidToolInputError:s}=await Promise.resolve().then(()=>(Um(),ILe));if(o.isInstance(n))return mjt(r,Object.keys(e));if(s.isInstance(n))try{let i=await t({toolName:r.toolName});return fjt(r,i)}catch{return null}return null}}function mjt(r,e){let t=r.toolName;if(!t||t.trim().length===0)return null;let n=e.find(c=>c.toLowerCase()===t.toLowerCase());if(n)return g.debug(`[ToolCallRepair] Name repair (case): "${t}" \u2192 "${n}"`),{...r,toolName:n};let o=t.toLowerCase(),s=e.filter(c=>{let l=c.toLowerCase();return l.includes(o)||o.includes(l)});if(s.length===1)return g.debug(`[ToolCallRepair] Name repair (substring): "${t}" \u2192 "${s[0]}"`),{...r,toolName:s[0]};let i=null,a=1/0;for(let c of e){let l=a1e(o,c.toLowerCase()),u=Math.max(t.length,c.length),d=u===0?0:l/u;d<.3&&d<a&&(a=d,i=c)}return i?(g.debug(`[ToolCallRepair] Name repair (levenshtein ${a.toFixed(2)}): "${t}" \u2192 "${i}"`),{...r,toolName:i}):(g.debug(`[ToolCallRepair] Could not repair tool name "${t}". Available: [${e.join(", ")}]`),null)}function fjt(r,e){let t;try{t=JSON.parse(r.input)}catch{return null}if(!t||typeof t!="object"||Array.isArray(t))return null;let n=e.properties;if(!n)return null;let o=Object.keys(n),s=t,i=Object.keys(s),a=Object.create(null),c=!1,l=e.additionalProperties===!1;for(let u of i){if(o.includes(u)){a[u]=s[u];continue}let d=gjt(u,o);if(d){if(Object.prototype.hasOwnProperty.call(a,d)){c=!0;continue}g.debug(`[ToolCallRepair] Param repair: "${u}" \u2192 "${d}" (tool: ${r.toolName})`),a[d]=s[u],c=!0}else l?(g.debug(`[ToolCallRepair] Dropping unmapped key "${u}" (additionalProperties: false, tool: ${r.toolName})`),c=!0):a[u]=s[u]}for(let u of Object.keys(a)){let d=n[u];if(!d)continue;let p=wG(a[u],d);p!==a[u]&&(g.debug(`[ToolCallRepair] Type coercion on "${u}": ${typeof a[u]} \u2192 ${typeof p} (tool: ${r.toolName})`),a[u]=p,c=!0)}return c?{...r,input:JSON.stringify(a)}:null}function gjt(r,e){let t=r.toLowerCase(),n=e.find(i=>i.toLowerCase()===t);if(n)return n;let o=null,s=1/0;for(let i of e){let a=a1e(t,i.toLowerCase());a<=2&&a<s&&(s=a,o=i)}return o}function wG(r,e){let t=e.type;if(!t||r===null||r===void 0)return r;if(t==="number"&&typeof r=="string"){let n=r.trim();if(n!==""){let o=Number(n);if(isFinite(o))return o}}if(t==="integer"&&typeof r=="string"){let n=r.trim();if(/^[+-]?\d+$/.test(n)){let o=Number(n);if(Number.isSafeInteger(o))return o}}if(t==="boolean"&&typeof r=="string"){if(r.toLowerCase()==="true")return!0;if(r.toLowerCase()==="false")return!1}if(t==="object"&&typeof r=="string")try{let n=JSON.parse(r);if(n&&typeof n=="object"&&!Array.isArray(n))return n}catch{}if(t==="array"&&typeof r=="string")try{let n=JSON.parse(r);if(Array.isArray(n))return n}catch{}return t==="array"&&!Array.isArray(r)&&typeof r!="string"?[r]:r}function a1e(r,e){if(r===e)return 0;if(r.length===0)return e.length;if(e.length===0)return r.length;r.length>e.length&&([r,e]=[e,r]);let t=r.length,n=e.length,o=new Array(t+1),s=new Array(t+1);for(let i=0;i<=t;i++)o[i]=i;for(let i=1;i<=n;i++){s[0]=i;for(let a=1;a<=t;a++){let c=r[a-1]===e[i-1]?0:1;s[a]=Math.min(o[a]+1,s[a-1]+1,o[a-1]+c)}[o,s]=[s,o]}return o[t]}var EG=k(()=>{"use strict";H()});function yjt(r){if(r===void 0)return"";try{return((typeof r=="string"?r:JSON.stringify(r))??"").substring(0,200)}catch{return"[unserializable]"}}function xjt(r,e){let t=Nc(r.timeout),n=typeof r.turnTimeoutMs=="number"&&Number.isFinite(r.turnTimeoutMs)&&r.turnTimeoutMs>0;r.turnTimeoutMs!==void 0&&!n&&g.warn("[GenerationHandler] Ignoring invalid turnTimeoutMs \u2014 expected a positive number of milliseconds; falling back to the timeout option",{turnTimeoutMs:r.turnTimeoutMs});let o=n?r.turnTimeoutMs:t,s=o?Math.min(r.wrapupTimeLeadMs??OP,Math.floor(o/4)):0;!n&&o!==void 0&&s>0&&(o=o-s,s=Math.min(s,Math.floor(o/4)));let i=o?e+o:void 0;return{callerTimeoutMs:t,turnBudgetMs:o,wrapupLeadMs:s,turnDeadline:i}}function bjt(r,e,t){let n={};return t!==void 0&&(n.neurolink={timeoutMs:t}),r.thinkingConfig?.enabled&&e&&(n.google={thinkingConfig:{...r.thinkingConfig.thinkingLevel&&{thinkingLevel:r.thinkingConfig.thinkingLevel},...r.thinkingConfig.budgetTokens&&!r.thinkingConfig.thinkingLevel&&{thinkingBudget:r.thinkingConfig.budgetTokens},includeThoughts:!0}}),Object.keys(n).length>0?n:void 0}function vjt(r,e){let t=r?.messages??e;return{...r??{},messages:[...t,{role:"user",content:"The time budget for this task is nearly exhausted. Do not call any more tools. Give your best final answer NOW from the information already gathered, and note anything you could not verify in the remaining time."}],toolChoice:"none"}}var hjt,IM,c1e=k(()=>{"use strict";Lr();RLe();Hr();H();SM();Ad();PLe();Hn();fG();mi();GLe();vG();Pne();Um();PP();hv();i1e();hjt=Pe.generation;IM=class{constructor(e,t,n,o,s,i){this.providerName=e;this.modelName=t;this.supportsToolsFn=n;this.getTelemetryConfigFn=o;this.handleToolStorageFn=s;this.getEmitterFn=i}providerName;modelName;supportsToolsFn;getTelemetryConfigFn;handleToolStorageFn;getEmitterFn;async callGenerateText(e,t,n,o,s){let{shouldUseTools:i,includeStructuredOutput:a,turnStartMs:c}=s,l=this.providerName==="google-ai"||this.providerName==="vertex",u=this.providerName==="anthropic"||this.providerName==="bedrock"||this.providerName==="vertex"&&this.modelName?.startsWith("claude-"),p=a&&(!!o.schema||o.output?.format==="json"||o.output?.format==="structured")&&!VLe(this.providerName,this.modelName,i,Object.keys(n).length),f=n;if(u&&i&&Object.keys(f).length>0){let M=Object.keys(f),N=M[M.length-1];if(N&&f[N]){let z=f[N];f[N]={...z,providerOptions:{...z.providerOptions??{},anthropic:{cacheControl:{type:"ephemeral"}}}}}}let h=o.prepareStep,{callerTimeoutMs:y,turnBudgetMs:x,wrapupLeadMs:b,turnDeadline:T}=xjt(o,c),S=!1,E=bjt(o,l,y),{system:C,messages:R}=s1e(t),P={toolCount:-1,tokens:0},A=jLe({provider:this.providerName??"unknown",model:this.modelName,maxTokens:o.maxTokens,getFixedOverheadTokens:()=>{let M=i?Object.keys(f).length:0;return M!==P.toolCount&&(P={toolCount:M,tokens:zLe(C,i?f:void 0,this.providerName)}),P.tokens}}),I=await ig({model:e,...C&&{system:C},messages:R,...i&&Object.keys(f).length>0&&{tools:f},stopWhen:AP(o.maxSteps??Ss),...i&&o.toolChoice&&{toolChoice:o.toolChoice},experimental_prepareStep:(async M=>{let N=h?await h({...M,maxSteps:o.maxSteps??Ss}):void 0,z=N?.messages,O=M.steps[M.steps.length-1],L=A(z??M.messages,O?.usage?.inputTokens),U=L?{...N??{},messages:L}:N;return T!==void 0&&i&&Date.now()>=T-b?(S||(S=!0,g.warn("[GenerationHandler] Turn budget nearly exhausted \u2014 forcing wrap-up (toolChoice: none)",{provider:this.providerName,turnBudgetMs:x,wrapupLeadMs:b,stepNumber:M.stepNumber})),vjt(U,M.messages)):U}),temperature:o.temperature,maxOutputTokens:o.maxTokens,maxRetries:0,abortSignal:o.abortSignal,...i&&!o.disableToolCallRepair&&{experimental_repairToolCall:(async(...M)=>{let{createToolCallRepair:N}=await Promise.resolve().then(()=>(EG(),Mne));return N()(...M)})},...E&&{providerOptions:E},...p&&o.schema&&{experimental_output:FB.object({schema:o.schema})},...o.thinkingConfig?.enabled&&u&&o.thinkingConfig.budgetTokens&&!o.thinkingConfig.thinkingLevel&&{experimental_thinking:{type:"enabled",budgetTokens:o.thinkingConfig.budgetTokens}},experimental_telemetry:this.getTelemetryConfigFn(o,"generate"),onStepFinish:({toolCalls:M,toolResults:N})=>{g.info("Tool execution completed",{toolResults:N,toolCalls:M}),Uy(this.getEmitterFn?.(),N),this.handleToolStorageFn(M,N,o,new Date).catch(z=>{g.warn("[GenerationHandler] Failed to store tool executions",{provider:this.providerName,error:z instanceof Error?z.message:String(z)})})}});return S&&Object.defineProperty(I,"__nlTurnWrapup",{value:!0,enumerable:!1}),I}async executeGeneration(e,t,n,o){return hjt.startActiveSpan("neurolink.executeGeneration",{kind:Cr.INTERNAL},async s=>{let i=!o.disableTools&&this.supportsToolsFn(),a=Object.keys(n||{}).length,c=!!o.schema||o.output?.format==="json"||o.output?.format==="structured";s.setAttribute("gen_ai.system",this.providerName||"unknown"),s.setAttribute("neurolink.structured_output",c),s.setAttribute("neurolink.tool_count",a),s.setAttribute("neurolink.message_count",t.length),s.setAttribute("gen_ai.request.model",uG(e,this.modelName||"unknown"));let l=o.requestId||o.context?.requestId||"unknown";if(g.info("[GenerationHandler] Calling generateText",{requestId:l,model:uG(e),messageCount:t.length,toolCount:a,maxSteps:o.maxSteps,temperature:o.temperature}),g.shouldLog("debug"))try{g.debug("[Observability] Full generateText parameters",{requestId:l,model:uG(e),messageCount:t.length,messages:t.map((d,p)=>({index:p,role:d.role,contentLength:typeof d.content=="string"?d.content.length:yjt(d.content).length,contentPreview:typeof d.content=="string"?d.content.substring(0,200):"[multimodal]"})),toolNames:Object.keys(n||{}),toolCount:a,maxSteps:o.maxSteps,temperature:o.temperature,maxTokens:o.maxTokens})}catch{}let u=Date.now();try{let d=await mG(()=>this.callGenerateText(e,t,n,o,{shouldUseTools:i,includeStructuredOutput:!0,turnStartMs:u}),s,"generateText");if(g.info("[GenerationHandler] generateText returned",{requestId:l,durationMs:Date.now()-u,finishReason:d.finishReason,steps:d.steps?.length||1,toolCallsTotal:d.toolCalls?.length||0,responseChars:d.text?.length||0}),g.shouldLog("debug")&&g.debug("[Observability] LLM response metadata",{requestId:l,responseLength:d.text?.length||0,hasToolCalls:!!(d.toolCalls&&d.toolCalls.length>0),toolCallCount:d.toolCalls?.length||0,toolNames:d.toolCalls?.map(p=>p.toolName),finishReason:d.finishReason,stepCount:d.steps?.length||0,steps:d.steps?.map((p,f)=>({stepIndex:f,stepType:p.stepType,textLength:p.text?.length||0,toolCallCount:p.toolCalls?.length||0,toolNames:p.toolCalls?.map(h=>h.toolName),toolResultCount:p.toolResults?.length||0,finishReason:p.finishReason})),usage:d.usage}),d.usage){s.setAttribute("gen_ai.usage.input_tokens",d.usage.inputTokens||0),s.setAttribute("gen_ai.usage.output_tokens",d.usage.outputTokens||0);let p=wo(this.providerName,this.modelName,{input:d.usage.inputTokens||0,output:d.usage.outputTokens||0,total:(d.usage.inputTokens||0)+(d.usage.outputTokens||0)});s.setAttribute("neurolink.cost",p??0)}return d.finishReason&&s.setAttribute("gen_ai.response.finish_reason",d.finishReason),s.setStatus({code:Le.OK}),d}catch(d){let p=c&&bG(d);if(c&&(d instanceof wa||qLe(d)||p)){s.setAttribute("neurolink.has_fallback",!0),s.addEvent("retry.initial_failure",{"error.message":d instanceof Error?d.message:String(d),"retry.attempt":1,"retry.reason":d instanceof wa?"NoObjectGeneratedError_structured_output_fallback":p?"schema_complexity_structured_output_fallback":"tools_schema_conflict_structured_output_fallback"}),p?g.warn("[GenerationHandler] schema too complex for provider constrained decoding \u2014 retrying with prompt-based JSON",{provider:this.providerName,model:this.modelName,error:d instanceof Error?d.message:String(d)}):g.debug("[GenerationHandler] structured-output conflict caught - falling back to manual JSON extraction",{provider:this.providerName,model:this.modelName,error:d instanceof Error?d.message:String(d)});let h=await mG(()=>this.callGenerateText(e,t,n,o,{shouldUseTools:i,includeStructuredOutput:!1,turnStartMs:u}),s,"generateText(fallback)");if(s.addEvent("retry.recovered",{"retry.attempts":2,"retry.strategy":"structured_output_disabled"}),s.setAttribute("retry.count",1),g.info("[GenerationHandler] generateText returned (fallback)",{requestId:l,durationMs:Date.now()-u,finishReason:h.finishReason,steps:h.steps?.length||1,toolCallsTotal:h.toolCalls?.length||0,responseChars:h.text?.length||0}),h.usage){s.setAttribute("gen_ai.usage.input_tokens",h.usage.inputTokens||0),s.setAttribute("gen_ai.usage.output_tokens",h.usage.outputTokens||0);let y=wo(this.providerName,this.modelName,{input:h.usage.inputTokens||0,output:h.usage.outputTokens||0,total:(h.usage.inputTokens||0)+(h.usage.outputTokens||0)});s.setAttribute("neurolink.cost",y??0)}return h.finishReason&&s.setAttribute("gen_ai.response.finish_reason",h.finishReason),s.setStatus({code:Le.OK}),h}if(HLe(d)&&typeof o.temperature=="number"){s.setAttribute("neurolink.has_fallback",!0),s.addEvent("retry.initial_failure",{"error.message":d instanceof Error?d.message:String(d),"retry.attempt":1,"retry.reason":"temperature_deprecated"}),g.debug("[GenerationHandler] temperature-deprecated error caught - retrying without temperature",{provider:this.providerName,model:this.modelName,error:d instanceof Error?d.message:String(d)});let h=await mG(()=>this.callGenerateText(e,t,n,{...o,temperature:void 0},{shouldUseTools:i,includeStructuredOutput:!0,turnStartMs:u}),s,"generateText(no-temperature)");if(s.addEvent("retry.recovered",{"retry.attempts":2,"retry.strategy":"temperature_omitted"}),s.setAttribute("retry.count",1),h.usage){s.setAttribute("gen_ai.usage.input_tokens",h.usage.inputTokens||0),s.setAttribute("gen_ai.usage.output_tokens",h.usage.outputTokens||0);let y=wo(this.providerName,this.modelName,{input:h.usage.inputTokens||0,output:h.usage.outputTokens||0,total:(h.usage.inputTokens||0)+(h.usage.outputTokens||0)});s.setAttribute("neurolink.cost",y??0)}return h.finishReason&&s.setAttribute("gen_ai.response.finish_reason",h.finishReason),s.setStatus({code:Le.OK}),h}throw s.setStatus({code:Le.ERROR,message:d instanceof Error?d.message:String(d)}),d}finally{s.end()}})}extractCacheMetricsFromProviderMetadata(e){let t=e.providerMetadata;if(!t)return{};let n=t.anthropic;if(n){let o=dne(n),s=pne(n);return{...o!==void 0&&{cacheCreationTokens:o},...s!==void 0&&{cacheReadTokens:s}}}return{}}logGenerationComplete(e){let t=this.extractCacheMetricsFromProviderMetadata(e);g.shouldLog("debug")&&g.debug("generateText completed",{provider:this.providerName,model:this.modelName,responseLength:e.text?.length||0,toolResultsCount:e.toolResults?.length||0,finishReason:e.finishReason,usage:e.usage,...t.cacheCreationTokens!==void 0&&{cacheCreationTokens:t.cacheCreationTokens},...t.cacheReadTokens!==void 0&&{cacheReadTokens:t.cacheReadTokens},timestamp:Date.now()})}extractToolInformation(e){let t=[],n=[];if(e.toolCalls&&e.toolCalls.length>0&&t.push(...e.toolCalls.map(o=>o.toolName||o.name||"unknown")),e.steps&&Array.isArray(e.steps)){let o=new Map;for(let s of e.steps||[]){if(s?.toolCalls&&Array.isArray(s.toolCalls))for(let i of s.toolCalls){let a=i,c=a.toolName||a.name||"unknown",l=a.toolCallId||a.id||c;t.push(c);let u={};a.args?u=a.args:a.arguments?u=a.arguments:a.parameters&&(u=a.parameters),o.set(l,u),o.set(c,u)}if(s?.toolResults&&Array.isArray(s.toolResults))for(let i of s.toolResults){let a=i,c=a.toolName||"unknown",l=a.toolCallId||a.id,u=a.args??a.arguments??a.parameters??a.input??o.get(l||c)??{};n.push({name:c,input:u,output:a.output??a.result??"success"})}}}return{toolsUsed:[...new Set(t)],toolExecutions:n}}formatEnhancedResult(e,t,n,o,s){let i=!!s.schema||s.output?.format==="json"||s.output?.format==="structured",a,c,l=!1,u=!1,d=E=>{let C=E.replace(/^```(?:json)?\s*\n?/i,"").replace(/\n?```\s*$/i,"").trim(),R=SG(C,s.schema);if(R)return c=R.structuredData,R.repaired&&(l=!0),R.truncated&&(u=!0),R.content;try{let P=JSON.parse(C);if(P==="")return g.warn("[GenerationHandler] schema requested but the model returned an empty JSON string; normalizing to empty content",{provider:this.providerName,model:this.modelName}),"";if(P!=null)return c=P,C}catch{}return g.warn("[GenerationHandler] schema requested but no JSON could be recovered from model text; returning raw text",{provider:this.providerName,model:this.modelName}),C};if(i)try{let E=e.experimental_output,C=typeof E=="string"&&E===(e.text??"");E!==void 0&&!C?(c=E,a=JSON.stringify(E)):a=d(e.text||"")}catch(E){g.debug("[GenerationHandler] experimental_output threw, falling back to text parsing",{error:E instanceof Error?E.message:String(E)}),a=d(e.text||"")}else a=e.text;i&&e.finishReason==="length"&&(u=!0,g.warn("[GenerationHandler] Structured output truncated by token cap (finishReason=length); increase maxTokens",{provider:this.providerName,model:this.modelName}));let p=v_(e.usage);if(p.cacheCreationTokens===void 0||p.cacheReadTokens===void 0){let E=this.extractCacheMetricsFromProviderMetadata(e);if(p.cacheCreationTokens===void 0&&E.cacheCreationTokens!==void 0&&(p.cacheCreationTokens=E.cacheCreationTokens),p.cacheReadTokens===void 0&&E.cacheReadTokens!==void 0&&(p.cacheReadTokens=E.cacheReadTokens),p.cacheReadTokens!==void 0){let C=mne(p.cacheReadTokens,p.input);C!==void 0&&(p.cacheSavingsPercent=C)}}let f=e.reasoning,h=f?typeof f=="string"?f:Array.isArray(f)?f.map(E=>typeof E=="string"?E:E.text??JSON.stringify(E)).join(`
829
829
  `):String(f):void 0,y=p.reasoning??void 0,x=e.steps,b=Array.isArray(x)?x.length:void 0,T=s.maxSteps??Ss,S;return e.__nlTurnWrapup===!0?S="time-limit":b!==void 0&&b>=T&&e.finishReason==="tool-calls"?S="step-cap":e.finishReason==="error"?S="provider-error":b!==void 0&&(S="completed"),{content:a,structuredData:c,usage:p,finishReason:e.finishReason,stopReason:S,stepsUsed:b,jsonRepaired:l||void 0,jsonTruncated:u||void 0,provider:this.providerName,model:this.modelName,reasoning:h,reasoningTokens:y,toolCalls:e.toolCalls?e.toolCalls.map(E=>({toolCallId:E.toolCallId||"unknown",toolName:E.toolName||"unknown",args:E.args||{}})):[],toolResults:e.toolResults??[],toolsUsed:n,toolExecutions:o,availableTools:Object.keys(t).map(E=>{let C=t[E];return{name:E,description:C.description||"No description available",parameters:C.inputSchema||{},server:C.serverId||"direct"}})}}analyzeAIResponse(e){g.debug("NeuroLink Raw AI Response Analysis",{provider:this.providerName,model:this.modelName,responseTextLength:e.text?.length||0,responsePreview:e.text?.substring(0,500)??"",finishReason:e.finishReason,usage:e.usage});let t={hasToolCalls:!!e.toolCalls,toolCallsLength:e.toolCalls?.length||0,toolCalls:e.toolCalls?.map((n,o)=>{let s=n,i=s.toolName||s.name||"unknown";return{index:o+1,toolName:i,toolId:s.toolCallId||s.id||"none",hasArgs:!!s.args,argsKeys:s.args&&typeof s.args=="object"?Object.keys(s.args):[]}})||[]};g.debug("Tool Calls Analysis",t)}}});var xg={};re(xg,{AsyncLocalStorage:()=>zjt,Buffer:()=>kVt,Channel:()=>gVt,DatabaseSync:()=>_Vt,Duplex:()=>Gjt,EventEmitter:()=>Bjt,Http2ServerRequest:()=>PVt,Http2ServerResponse:()=>MVt,Interface:()=>EVt,MIMEType:()=>UVt,PassThrough:()=>Vjt,PerformanceObserver:()=>pVt,Readable:()=>u1e,ReadableStream:()=>qjt,Resolver:()=>uVt,TextDecoder:()=>m1e,TextEncoder:()=>_G,Transform:()=>jjt,URL:()=>XGt,URLSearchParams:()=>ZGt,Worker:()=>bVt,Writable:()=>d1e,access:()=>fGt,appendFile:()=>PM,appendFileSync:()=>Cjt,arch:()=>IGt,arrayBuffer:()=>OVt,basename:()=>Ojt,builtinModules:()=>WGt,callbackify:()=>sVt,channel:()=>fVt,chmodSync:()=>Xjt,clearInterval:()=>FVt,clearTimeout:()=>DVt,closeSync:()=>tGt,connect:()=>NGt,constants:()=>CVt,copyFileSync:()=>Qjt,cpSync:()=>Rjt,cpus:()=>kGt,createConnection:()=>DGt,createGunzip:()=>jGt,createGzip:()=>GGt,createHash:()=>l1e,createHmac:()=>wjt,createInterface:()=>wVt,createReadStream:()=>dGt,createRequire:()=>HGt,createServer:()=>Ajt,createWriteStream:()=>uGt,debug:()=>nVt,debuglog:()=>p1e,default:()=>Tjt,deflateSync:()=>FGt,deprecate:()=>oVt,deserialize:()=>xVt,dirname:()=>Mjt,exec:()=>xGt,execFile:()=>vGt,execFileSync:()=>TGt,execSync:()=>bGt,existsSync:()=>Kjt,extname:()=>Njt,fileURLToPath:()=>QGt,finished:()=>Wjt,format:()=>YGt,freemem:()=>CGt,fstatSync:()=>rGt,get:()=>OGt,gunzip:()=>zGt,gunzipSync:()=>UGt,gzip:()=>BGt,gzipSync:()=>$Gt,hasSubscribers:()=>hVt,homedir:()=>wGt,hostname:()=>_Gt,inflateSync:()=>LGt,inherits:()=>tVt,inspect:()=>CG,isAbsolute:()=>Ljt,isBuiltin:()=>KGt,isDeepStrictEqual:()=>iVt,isIP:()=>IVt,isIPv4:()=>AVt,isIPv6:()=>RVt,isMainThread:()=>vVt,join:()=>Ijt,lookup:()=>lVt,mkdir:()=>Nne,mkdirSync:()=>nGt,monitorEventLoopDelay:()=>mVt,normalize:()=>$jt,ok:()=>VGt,open:()=>Dne,openSync:()=>eGt,parentPort:()=>TVt,parse:()=>JGt,pathToFileURL:()=>eVt,performance:()=>dVt,pipeline:()=>Hjt,platform:()=>SGt,posix:()=>Ujt,promises:()=>Sjt,promisify:()=>rVt,randomBytes:()=>Ejt,randomUUID:()=>_jt,readFile:()=>Gy,readFileSync:()=>Jjt,readdir:()=>pGt,readdirSync:()=>sGt,realpath:()=>kG,realpathSync:()=>Zjt,relative:()=>Djt,release:()=>PGt,rename:()=>gGt,renameSync:()=>aGt,request:()=>MGt,resolve:()=>Pjt,rm:()=>hGt,rmSync:()=>lGt,rmdirSync:()=>cGt,sep:()=>Fjt,serialize:()=>yVt,setInterval:()=>LVt,setTimeout:()=>NVt,spawn:()=>yGt,stat:()=>MM,statSync:()=>oGt,strict:()=>qGt,tmpdir:()=>EGt,toUSVString:()=>aVt,totalmem:()=>RGt,type:()=>AGt,types:()=>cVt,unlink:()=>mGt,unlinkSync:()=>iGt,webcrypto:()=>kjt,workerData:()=>SVt,writeFile:()=>One,writeFileSync:()=>Yjt});var Rs,zo,Tjt,Sjt,l1e,wjt,Ejt,_jt,kjt,Cjt,Rjt,Ajt,Ijt,Pjt,Mjt,Ojt,Njt,Djt,Ljt,Fjt,Ujt,$jt,Bjt,zjt,u1e,d1e,jjt,Gjt,Vjt,qjt,Hjt,Wjt,Kjt,Jjt,Yjt,Xjt,PM,Zjt,Qjt,eGt,tGt,rGt,nGt,oGt,sGt,iGt,aGt,cGt,lGt,uGt,dGt,Gy,One,Nne,MM,pGt,mGt,fGt,gGt,hGt,Dne,kG,yGt,xGt,bGt,vGt,TGt,SGt,wGt,EGt,_Gt,kGt,CGt,RGt,AGt,IGt,PGt,MGt,OGt,NGt,DGt,LGt,FGt,UGt,$Gt,BGt,zGt,jGt,GGt,VGt,qGt,HGt,WGt,KGt,JGt,YGt,XGt,ZGt,QGt,eVt,tVt,rVt,p1e,nVt,CG,oVt,sVt,iVt,aVt,cVt,m1e,_G,lVt,uVt,dVt,pVt,mVt,fVt,gVt,hVt,yVt,xVt,bVt,vVt,TVt,SVt,wVt,EVt,_Vt,kVt,CVt,RVt,AVt,IVt,PVt,MVt,OVt,f1e,NVt,DVt,LVt,FVt,UVt,Lu=k(()=>{Rs=()=>{},zo=async()=>{},Tjt={},Sjt={readFile:zo,writeFile:zo,mkdir:zo,stat:zo,readdir:zo,unlink:zo,access:zo,rm:zo,rename:zo},l1e=r=>{let e=[];return{update(t){return e.push(typeof t=="string"?new _G().encode(t):t),this},digest(t){let n=0;for(let s of e)for(let i=0;i<s.length;i++)n=(n<<5)-n+s[i]|0;let o=(n>>>0).toString(16).padStart(8,"0");return t==="hex"?o:t==="base64"?btoa(o):o}}},wjt=(r,e)=>l1e(r),Ejt=r=>new Uint8Array(r||32),_jt=()=>globalThis.crypto?.randomUUID?.()||Math.random().toString(36),kjt=globalThis.crypto,Cjt=()=>{throw new Error("[NeuroLink:browser] fs.appendFileSync is not supported in browser runtime \u2014 use server-side execution")},Rjt=()=>{throw new Error("[NeuroLink:browser] fs.cpSync is not supported in browser runtime \u2014 use server-side execution")},Ajt=()=>({listen:Rs,close:Rs,on:Rs}),Ijt=(...r)=>r.join("/"),Pjt=(...r)=>r.join("/"),Mjt=r=>r||"",Ojt=r=>r?.split?.("/")?.pop?.()||"",Njt=r=>{let e=r?.match?.(/\.[^.]+$/);return e?e[0]:""},Djt=(r,e)=>e||"",Ljt=()=>!1,Fjt="/",Ujt={normalize:r=>r,join:(...r)=>r.join("/"),resolve:(...r)=>r.join("/"),sep:"/"},$jt=r=>r,Bjt=class{on(){return this}off(){return this}emit(){return this}once(){return this}removeListener(){return this}addListener(){return this}},zjt=class{getStore(){}run(r,e,...t){return e(...t)}enterWith(){}disable(){}},u1e=class{pipe(){return this}on(){return this}read(){return null}push(){}destroy(){}},d1e=class{write(){return!0}end(){}on(){return this}destroy(){}},jjt=class{push(){}on(){return this}},Gjt=class{on(){return this}},Vjt=class{pipe(){return this}on(){return this}},qjt=globalThis.ReadableStream||class{},Hjt=Rs,Wjt=Rs,Kjt=()=>!1,Jjt=()=>"",Yjt=Rs,Xjt=Rs,PM=zo,Zjt=r=>r,Qjt=Rs,eGt=()=>0,tGt=Rs,rGt=()=>({}),nGt=Rs,oGt=()=>({}),sGt=()=>[],iGt=Rs,aGt=Rs,cGt=Rs,lGt=Rs,uGt=()=>new d1e,dGt=()=>new u1e,Gy=zo,One=zo,Nne=zo,MM=zo,pGt=zo,mGt=zo,fGt=zo,gGt=zo,hGt=zo,Dne=async()=>({stat:zo,readFile:zo,close:zo,read:zo,write:zo}),kG=async r=>r,yGt=()=>({on:Rs,stdout:{on:Rs},stderr:{on:Rs},kill:Rs}),xGt=(r,e)=>e?.(null,"",""),bGt=()=>"",vGt=(r,e,t)=>{typeof e=="function"?e(null,"",""):t?.(null,"","")},TGt=()=>"",SGt="browser",wGt=()=>"/",EGt=()=>"/tmp",_Gt=()=>"browser",kGt=()=>[{}],CGt=()=>0,RGt=()=>0,AGt=()=>"Browser",IGt=()=>"wasm",PGt=()=>"0",MGt=()=>({}),OGt=()=>({}),NGt=()=>({}),DGt=()=>({}),LGt=()=>new Uint8Array,FGt=()=>new Uint8Array,UGt=()=>new Uint8Array,$Gt=()=>new Uint8Array,BGt=(r,e)=>e?.(null,r),zGt=(r,e)=>e?.(null,r),jGt=()=>({}),GGt=()=>({}),VGt=Rs,qGt={},HGt=()=>()=>({}),WGt=[],KGt=()=>!1,JGt=r=>({pathname:r||"",hostname:"",protocol:"",search:"",hash:""}),YGt=()=>"",XGt=globalThis.URL,ZGt=globalThis.URLSearchParams,QGt=r=>typeof r=="string"?r.replace("file://",""):r,eVt=r=>new globalThis.URL("file://"+r),tVt=(r,e)=>{e&&(r.super_=e,Object.setPrototypeOf(r.prototype,e.prototype))},rVt=r=>(...e)=>new Promise((t,n)=>r(...e,(o,s)=>o?n(o):t(s))),p1e=r=>{let e=(...t)=>{};return e.enabled=!1,e},nVt=p1e,CG=r=>{try{return JSON.stringify(r,null,2)}catch{return String(r)}};CG.custom=Symbol.for("nodejs.util.inspect.custom");CG.colors={};CG.styles={};oVt=r=>r,sVt=r=>(...e)=>{let t=e.pop();r(...e).then(n=>t(null,n)).catch(t)},iVt=(r,e)=>JSON.stringify(r)===JSON.stringify(e),aVt=r=>String(r),cVt={isPromise:r=>r instanceof Promise,isDate:r=>r instanceof Date,isRegExp:r=>r instanceof RegExp,isNativeError:r=>r instanceof Error,isArrayBuffer:r=>r instanceof ArrayBuffer,isTypedArray:r=>ArrayBuffer.isView(r),isUint8Array:r=>r instanceof Uint8Array,isProxy:()=>!1},m1e=globalThis.TextDecoder,_G=globalThis.TextEncoder,lVt=(r,e)=>e?.(null,"127.0.0.1",4),uVt=class{},dVt=globalThis.performance||{now:()=>Date.now()},pVt=class{observe(){}disconnect(){}},mVt=()=>({enable:Rs,disable:Rs,percentile:()=>0}),fVt=()=>({}),gVt=class{},hVt=()=>!1,yVt=()=>new Uint8Array,xVt=Rs,bVt=class{},vVt=!0,TVt=null,SVt=null,wVt=()=>({}),EVt=class{},_Vt=class{},kVt=globalThis.Buffer||class extends Uint8Array{static from(e,t){if(typeof e=="string"){let n=(t||"utf8").toLowerCase();if(n==="base64"){let o=atob(e),s=new Uint8Array(o.length);for(let i=0;i<o.length;i++)s[i]=o.charCodeAt(i);return s}if(n==="hex"){let o=new Uint8Array(e.length/2);for(let s=0;s<e.length;s+=2)o[s/2]=parseInt(e.substr(s,2),16);return o}return new _G().encode(e)}return new Uint8Array(e)}static alloc(e){return new Uint8Array(e)}static isBuffer(e){return e instanceof Uint8Array}static concat(e){let t=e.reduce((s,i)=>s+i.length,0),n=new Uint8Array(t),o=0;for(let s of e)n.set(s,o),o+=s.length;return n}static byteLength(e,t){return t==="base64"?Math.ceil(e.length*3/4):new _G().encode(e).length}toString(e){let t=(e||"utf8").toLowerCase();if(t==="hex")return Array.from(new Uint8Array(this.buffer,this.byteOffset,this.byteLength)).map(n=>n.toString(16).padStart(2,"0")).join("");if(t==="base64"){let n="";for(let o=0;o<this.length;o++)n+=String.fromCharCode(this[o]);return btoa(n)}return new m1e().decode(this)}},CVt={F_OK:0,R_OK:4,W_OK:2,X_OK:1},RVt=()=>!1,AVt=()=>!1,IVt=()=>0,PVt=class{},MVt=class{},OVt=async()=>new ArrayBuffer(0),f1e=r=>({[Symbol.toPrimitive](){return r},ref(){return this},unref(){return this},hasRef(){return!1},refresh(){return this},close(){}}),NVt=(...r)=>f1e(globalThis.setTimeout(...r)),DVt=globalThis.clearTimeout,LVt=(...r)=>f1e(globalThis.setInterval(...r)),FVt=globalThis.clearInterval,UVt=class{constructor(r){this.type=r}toString(){return this.type}}});var Une={};re(Une,{Agent:()=>Fne,BedrockClient:()=>BVt,BedrockRuntimeClient:()=>jVt,Blob:()=>E4t,Client:()=>k4t,ConverseCommand:()=>GVt,ConverseStreamCommand:()=>VVt,Cron:()=>a4t,Dispatcher:()=>C4t,File:()=>w4t,FlowProducer:()=>i4t,FormData:()=>S4t,GoogleAuth:()=>JVt,HTTPException:()=>f4t,Headers:()=>T4t,Hippocampus:()=>QVt,HippocampusConfig:()=>e4t,Hono:()=>p4t,ImageFormat:()=>qVt,InvokeEndpointCommand:()=>WVt,InvokeEndpointWithResponseStreamCommand:()=>KVt,Job:()=>o4t,ListFoundationModelsCommand:()=>zVt,MockAgent:()=>A4t,Pool:()=>_4t,Queue:()=>r4t,QueueScheduler:()=>s4t,Request:()=>b4t,Response:()=>v4t,SageMakerRuntimeClient:()=>HVt,TextToSpeechClient:()=>XVt,VertexAI:()=>YVt,Webhook:()=>ZVt,Worker:()=>n4t,convertToHtml:()=>d4t,cors:()=>m4t,createClient:()=>t4t,default:()=>$Vt,extractRawText:()=>u4t,fetch:()=>Lne,getGlobalDispatcher:()=>jv,interceptors:()=>Gv,logger:()=>g4t,parseBuffer:()=>c4t,request:()=>Vv,secureHeaders:()=>h4t,selectCover:()=>l4t,setGlobalDispatcher:()=>R4t,streamSSE:()=>y4t,timeout:()=>x4t});var S_,Ai,$Vt,BVt,zVt,jVt,GVt,VVt,qVt,HVt,WVt,KVt,JVt,YVt,XVt,ZVt,QVt,e4t,t4t,r4t,n4t,o4t,s4t,i4t,a4t,c4t,l4t,u4t,d4t,p4t,m4t,f4t,g4t,h4t,y4t,x4t,Lne,b4t,v4t,T4t,S4t,w4t,E4t,Fne,_4t,k4t,C4t,R4t,jv,A4t,Gv,Vv,w_=k(()=>{S_={get(r,e){return e==="__esModule"?!0:e==="default"?new Proxy({},{get:S_.get}):new Proxy(function(...t){return new Proxy({},{get:S_.get})},{get:S_.get,apply(t,n,o){return new Proxy({},{get:S_.get})},construct(t,n){return new Proxy({},{get:S_.get})}})}},Ai=new Proxy({},S_),$Vt=Ai,{BedrockClient:BVt,ListFoundationModelsCommand:zVt,BedrockRuntimeClient:jVt,ConverseCommand:GVt,ConverseStreamCommand:VVt,ImageFormat:qVt}=Ai,{SageMakerRuntimeClient:HVt,InvokeEndpointCommand:WVt,InvokeEndpointWithResponseStreamCommand:KVt}=Ai,{GoogleAuth:JVt,VertexAI:YVt,TextToSpeechClient:XVt}=Ai,{Webhook:ZVt}=Ai,{Hippocampus:QVt,HippocampusConfig:e4t}=Ai,{createClient:t4t}=Ai,{Queue:r4t,Worker:n4t,Job:o4t,QueueScheduler:s4t,FlowProducer:i4t}=Ai,{Cron:a4t}=Ai,{parseBuffer:c4t,selectCover:l4t}=Ai,{extractRawText:u4t,convertToHtml:d4t}=Ai,{Hono:p4t}=Ai,{cors:m4t,HTTPException:f4t,logger:g4t,secureHeaders:h4t,streamSSE:y4t,timeout:x4t}=Ai,Lne=globalThis.fetch,b4t=globalThis.Request,v4t=globalThis.Response,T4t=globalThis.Headers,S4t=globalThis.FormData,w4t=globalThis.File,E4t=globalThis.Blob,Fne=Ai.Agent,_4t=Ai.Pool,k4t=Ai.Client,C4t=Ai.Dispatcher,R4t=()=>{},jv=()=>Ai,A4t=Ai.MockAgent,Gv={redirect:()=>r=>r,retry:()=>r=>r},Vv=async(r,e)=>{let t=await globalThis.fetch(r,e);return{statusCode:t.status,headers:Object.fromEntries(t.headers.entries()),body:{text:()=>t.text(),json:()=>t.json(),arrayBuffer:()=>t.arrayBuffer()}}}});var OM={};re(OM,{AsyncLocalStorage:()=>W4t,Buffer:()=>$Ht,Channel:()=>RHt,DatabaseSync:()=>UHt,Duplex:()=>J4t,EventEmitter:()=>H4t,Http2ServerRequest:()=>VHt,Http2ServerResponse:()=>qHt,Interface:()=>FHt,MIMEType:()=>XHt,PassThrough:()=>Y4t,PerformanceObserver:()=>_Ht,Readable:()=>g1e,ReadableStream:()=>X4t,Resolver:()=>wHt,TextDecoder:()=>x1e,TextEncoder:()=>RG,Transform:()=>K4t,URL:()=>uHt,URLSearchParams:()=>dHt,Worker:()=>MHt,Writable:()=>h1e,access:()=>_qt,appendFile:()=>oqt,appendFileSync:()=>O4t,arch:()=>Gqt,arrayBuffer:()=>HHt,basename:()=>$4t,builtinModules:()=>iHt,callbackify:()=>xHt,channel:()=>CHt,chmodSync:()=>nqt,clearInterval:()=>YHt,clearTimeout:()=>KHt,closeSync:()=>cqt,connect:()=>Wqt,constants:()=>BHt,copyFileSync:()=>iqt,cpSync:()=>N4t,cpus:()=>$qt,createConnection:()=>Kqt,createGunzip:()=>tHt,createGzip:()=>rHt,createHash:()=>Ii,createHmac:()=>$ne,createInterface:()=>LHt,createReadStream:()=>xqt,createRequire:()=>sHt,createServer:()=>D4t,createWriteStream:()=>yqt,debug:()=>hHt,debuglog:()=>y1e,default:()=>I4t,deflateSync:()=>Yqt,deprecate:()=>yHt,deserialize:()=>PHt,dirname:()=>U4t,exec:()=>Pqt,execFile:()=>Oqt,execFileSync:()=>Nqt,execSync:()=>Mqt,existsSync:()=>eqt,extname:()=>B4t,fileURLToPath:()=>pHt,finished:()=>Q4t,format:()=>lHt,freemem:()=>Bqt,fstatSync:()=>lqt,get:()=>Hqt,gunzip:()=>eHt,gunzipSync:()=>Xqt,gzip:()=>Qqt,gzipSync:()=>Zqt,hasSubscribers:()=>AHt,homedir:()=>Lqt,hostname:()=>Uqt,inflateSync:()=>Jqt,inherits:()=>fHt,inspect:()=>AG,isAbsolute:()=>j4t,isBuiltin:()=>aHt,isDeepStrictEqual:()=>bHt,isIP:()=>GHt,isIPv4:()=>jHt,isIPv6:()=>zHt,isMainThread:()=>OHt,join:()=>L4t,lookup:()=>SHt,mkdir:()=>Tqt,mkdirSync:()=>uqt,monitorEventLoopDelay:()=>kHt,normalize:()=>q4t,ok:()=>nHt,open:()=>Rqt,openSync:()=>aqt,parentPort:()=>NHt,parse:()=>cHt,pathToFileURL:()=>mHt,performance:()=>EHt,pipeline:()=>Z4t,platform:()=>Dqt,posix:()=>V4t,promises:()=>P4t,promisify:()=>gHt,randomBytes:()=>Bm,randomUUID:()=>Xe,readFile:()=>bqt,readFileSync:()=>tqt,readdir:()=>wqt,readdirSync:()=>pqt,realpath:()=>Aqt,realpathSync:()=>sqt,relative:()=>z4t,release:()=>Vqt,rename:()=>kqt,renameSync:()=>fqt,request:()=>qqt,resolve:()=>F4t,rm:()=>Cqt,rmSync:()=>hqt,rmdirSync:()=>gqt,sep:()=>G4t,serialize:()=>IHt,setInterval:()=>JHt,setTimeout:()=>WHt,spawn:()=>Iqt,stat:()=>Sqt,statSync:()=>dqt,strict:()=>oHt,tmpdir:()=>Fqt,toUSVString:()=>vHt,totalmem:()=>zqt,type:()=>jqt,types:()=>THt,unlink:()=>Eqt,unlinkSync:()=>mqt,webcrypto:()=>M4t,workerData:()=>DHt,writeFile:()=>vqt,writeFileSync:()=>rqt});var As,jo,I4t,P4t,Ii,$ne,Bm,Xe,M4t,O4t,N4t,D4t,L4t,F4t,U4t,$4t,B4t,z4t,j4t,G4t,V4t,q4t,H4t,W4t,g1e,h1e,K4t,J4t,Y4t,X4t,Z4t,Q4t,eqt,tqt,rqt,nqt,oqt,sqt,iqt,aqt,cqt,lqt,uqt,dqt,pqt,mqt,fqt,gqt,hqt,yqt,xqt,bqt,vqt,Tqt,Sqt,wqt,Eqt,_qt,kqt,Cqt,Rqt,Aqt,Iqt,Pqt,Mqt,Oqt,Nqt,Dqt,Lqt,Fqt,Uqt,$qt,Bqt,zqt,jqt,Gqt,Vqt,qqt,Hqt,Wqt,Kqt,Jqt,Yqt,Xqt,Zqt,Qqt,eHt,tHt,rHt,nHt,oHt,sHt,iHt,aHt,cHt,lHt,uHt,dHt,pHt,mHt,fHt,gHt,y1e,hHt,AG,yHt,xHt,bHt,vHt,THt,x1e,RG,SHt,wHt,EHt,_Ht,kHt,CHt,RHt,AHt,IHt,PHt,MHt,OHt,NHt,DHt,LHt,FHt,UHt,$Ht,BHt,zHt,jHt,GHt,VHt,qHt,HHt,b1e,WHt,KHt,JHt,YHt,XHt,fr=k(()=>{As=()=>{},jo=async()=>{},I4t={},P4t={readFile:jo,writeFile:jo,mkdir:jo,stat:jo,readdir:jo,unlink:jo,access:jo,rm:jo,rename:jo},Ii=r=>{let e=[];return{update(t){return e.push(typeof t=="string"?new RG().encode(t):t),this},digest(t){let n=0;for(let s of e)for(let i=0;i<s.length;i++)n=(n<<5)-n+s[i]|0;let o=(n>>>0).toString(16).padStart(8,"0");return t==="hex"?o:t==="base64"?btoa(o):o}}},$ne=(r,e)=>Ii(r),Bm=r=>new Uint8Array(r||32),Xe=()=>globalThis.crypto?.randomUUID?.()||Math.random().toString(36),M4t=globalThis.crypto,O4t=()=>{throw new Error("[NeuroLink:browser] fs.appendFileSync is not supported in browser runtime \u2014 use server-side execution")},N4t=()=>{throw new Error("[NeuroLink:browser] fs.cpSync is not supported in browser runtime \u2014 use server-side execution")},D4t=()=>({listen:As,close:As,on:As}),L4t=(...r)=>r.join("/"),F4t=(...r)=>r.join("/"),U4t=r=>r||"",$4t=r=>r?.split?.("/")?.pop?.()||"",B4t=r=>{let e=r?.match?.(/\.[^.]+$/);return e?e[0]:""},z4t=(r,e)=>e||"",j4t=()=>!1,G4t="/",V4t={normalize:r=>r,join:(...r)=>r.join("/"),resolve:(...r)=>r.join("/"),sep:"/"},q4t=r=>r,H4t=class{on(){return this}off(){return this}emit(){return this}once(){return this}removeListener(){return this}addListener(){return this}},W4t=class{getStore(){}run(r,e,...t){return e(...t)}enterWith(){}disable(){}},g1e=class{pipe(){return this}on(){return this}read(){return null}push(){}destroy(){}},h1e=class{write(){return!0}end(){}on(){return this}destroy(){}},K4t=class{push(){}on(){return this}},J4t=class{on(){return this}},Y4t=class{pipe(){return this}on(){return this}},X4t=globalThis.ReadableStream||class{},Z4t=As,Q4t=As,eqt=()=>!1,tqt=()=>"",rqt=As,nqt=As,oqt=jo,sqt=r=>r,iqt=As,aqt=()=>0,cqt=As,lqt=()=>({}),uqt=As,dqt=()=>({}),pqt=()=>[],mqt=As,fqt=As,gqt=As,hqt=As,yqt=()=>new h1e,xqt=()=>new g1e,bqt=jo,vqt=jo,Tqt=jo,Sqt=jo,wqt=jo,Eqt=jo,_qt=jo,kqt=jo,Cqt=jo,Rqt=async()=>({stat:jo,readFile:jo,close:jo,read:jo,write:jo}),Aqt=async r=>r,Iqt=()=>({on:As,stdout:{on:As},stderr:{on:As},kill:As}),Pqt=(r,e)=>e?.(null,"",""),Mqt=()=>"",Oqt=(r,e,t)=>{typeof e=="function"?e(null,"",""):t?.(null,"","")},Nqt=()=>"",Dqt="browser",Lqt=()=>"/",Fqt=()=>"/tmp",Uqt=()=>"browser",$qt=()=>[{}],Bqt=()=>0,zqt=()=>0,jqt=()=>"Browser",Gqt=()=>"wasm",Vqt=()=>"0",qqt=()=>({}),Hqt=()=>({}),Wqt=()=>({}),Kqt=()=>({}),Jqt=()=>new Uint8Array,Yqt=()=>new Uint8Array,Xqt=()=>new Uint8Array,Zqt=()=>new Uint8Array,Qqt=(r,e)=>e?.(null,r),eHt=(r,e)=>e?.(null,r),tHt=()=>({}),rHt=()=>({}),nHt=As,oHt={},sHt=()=>()=>({}),iHt=[],aHt=()=>!1,cHt=r=>({pathname:r||"",hostname:"",protocol:"",search:"",hash:""}),lHt=()=>"",uHt=globalThis.URL,dHt=globalThis.URLSearchParams,pHt=r=>typeof r=="string"?r.replace("file://",""):r,mHt=r=>new globalThis.URL("file://"+r),fHt=(r,e)=>{e&&(r.super_=e,Object.setPrototypeOf(r.prototype,e.prototype))},gHt=r=>(...e)=>new Promise((t,n)=>r(...e,(o,s)=>o?n(o):t(s))),y1e=r=>{let e=(...t)=>{};return e.enabled=!1,e},hHt=y1e,AG=r=>{try{return JSON.stringify(r,null,2)}catch{return String(r)}};AG.custom=Symbol.for("nodejs.util.inspect.custom");AG.colors={};AG.styles={};yHt=r=>r,xHt=r=>(...e)=>{let t=e.pop();r(...e).then(n=>t(null,n)).catch(t)},bHt=(r,e)=>JSON.stringify(r)===JSON.stringify(e),vHt=r=>String(r),THt={isPromise:r=>r instanceof Promise,isDate:r=>r instanceof Date,isRegExp:r=>r instanceof RegExp,isNativeError:r=>r instanceof Error,isArrayBuffer:r=>r instanceof ArrayBuffer,isTypedArray:r=>ArrayBuffer.isView(r),isUint8Array:r=>r instanceof Uint8Array,isProxy:()=>!1},x1e=globalThis.TextDecoder,RG=globalThis.TextEncoder,SHt=(r,e)=>e?.(null,"127.0.0.1",4),wHt=class{},EHt=globalThis.performance||{now:()=>Date.now()},_Ht=class{observe(){}disconnect(){}},kHt=()=>({enable:As,disable:As,percentile:()=>0}),CHt=()=>({}),RHt=class{},AHt=()=>!1,IHt=()=>new Uint8Array,PHt=As,MHt=class{},OHt=!0,NHt=null,DHt=null,LHt=()=>({}),FHt=class{},UHt=class{},$Ht=globalThis.Buffer||class extends Uint8Array{static from(e,t){if(typeof e=="string"){let n=(t||"utf8").toLowerCase();if(n==="base64"){let o=atob(e),s=new Uint8Array(o.length);for(let i=0;i<o.length;i++)s[i]=o.charCodeAt(i);return s}if(n==="hex"){let o=new Uint8Array(e.length/2);for(let s=0;s<e.length;s+=2)o[s/2]=parseInt(e.substr(s,2),16);return o}return new RG().encode(e)}return new Uint8Array(e)}static alloc(e){return new Uint8Array(e)}static isBuffer(e){return e instanceof Uint8Array}static concat(e){let t=e.reduce((s,i)=>s+i.length,0),n=new Uint8Array(t),o=0;for(let s of e)n.set(s,o),o+=s.length;return n}static byteLength(e,t){return t==="base64"?Math.ceil(e.length*3/4):new RG().encode(e).length}toString(e){let t=(e||"utf8").toLowerCase();if(t==="hex")return Array.from(new Uint8Array(this.buffer,this.byteOffset,this.byteLength)).map(n=>n.toString(16).padStart(2,"0")).join("");if(t==="base64"){let n="";for(let o=0;o<this.length;o++)n+=String.fromCharCode(this[o]);return btoa(n)}return new x1e().decode(this)}},BHt={F_OK:0,R_OK:4,W_OK:2,X_OK:1},zHt=()=>!1,jHt=()=>!1,GHt=()=>0,VHt=class{},qHt=class{},HHt=async()=>new ArrayBuffer(0),b1e=r=>({[Symbol.toPrimitive](){return r},ref(){return this},unref(){return this},hasRef(){return!1},refresh(){return this},close(){}}),WHt=(...r)=>b1e(globalThis.setTimeout(...r)),KHt=globalThis.clearTimeout,JHt=(...r)=>b1e(globalThis.setInterval(...r)),YHt=globalThis.clearInterval,XHt=class{constructor(r){this.type=r}toString(){return this.type}}});function as(r,e=500){return r&&r.slice(0,e).replace(e3t,"***")}function zm(r){if(typeof r=="string")return r;try{return JSON.stringify(r)??String(r)}catch{return"[content too large to serialize]"}}function E_(r,e=1e4){try{let t=JSON.stringify(r);return t===void 0?String(r):t.length>e?`${t.slice(0,e)}\u2026[truncated ${t.length-e} chars]`:t}catch(t){return`[unserializable: ${t instanceof Error?t.message:String(t)}]`}}function lr(r){return r.replace(/\/\/[^/\s"'<>]*@/g,"//***@").replace(/\/\/(?:(?!\/\/)[^\s"'<>])*@/g,"//***@")}function tc(r){let e=t=>t.length>200?`${t.slice(0,200)}\u2026`:t;try{let t=new URL(r);return e(`${t.protocol}//${t.host}${t.pathname}`)}catch{let t=r.split(/[?#]/)[0];return e(lr(t))}}function o3t(r){n3t.forEach(e=>r.searchParams.delete(e))}function s3t(r){let e=[],t=[];for(let[o,s]of r.searchParams.entries())r3t.includes(o.toLowerCase())&&(e.push(`${o.toLowerCase()}=${s}`),t.push(o));return e.length===0?"":(t.forEach(o=>r.searchParams.delete(o)),e.sort(),`\0auth=${Ii("sha256").update(e.join("&")).digest("hex").slice(0,16)}`)}function IG(r){try{let e=new URL(r);o3t(e);let t=s3t(e);return e.toString()+t}catch{return r}}function Bne(r){return r.replace(/[a-zA-Z][a-zA-Z0-9+.-]*:\/\/[^\s"'<>)]+/g,e=>tc(e))}function zne(r,e){let t=Ks(e);return r.split(yd(e)).join(t).split(e).join(t)}function Vy(r,e){let t=s=>{let i=Bne(s);return e?.filePath?zne(i,e.filePath):i};if(!(r instanceof Error))return new Error(t(String(r)));let n=new Error(t(r.message));n.name=r.name;let o=r.code;return o!==void 0&&(n.code=o),n}function __(r,e=1e3){let t=new WeakSet,n=o=>{if(o==null)return o;if(typeof o=="string")return as(o,e);if(typeof o!="object")return o;if(t.has(o))return"[Circular]";if(t.add(o),Array.isArray(o))return o.map(n);let s={};for(let[i,a]of Object.entries(o))t3t.some(c=>c.toLowerCase()===i.toLowerCase())?s[i]="***":s[i]=n(a);return s};return n(r)}var ZHt,QHt,e3t,t3t,r3t,n3t,fn=k(()=>{"use strict";fr();pn();ZHt=["sk","pk","r8","gsk","xai","tgp","fw","pplx","pa","jina","fish"],QHt=ZHt.join("|"),e3t=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(?:${QHt})[_\\-][A-Za-z0-9_\\-\\.]{8,}\\b|\\b(?:api[_-]?key|access[_-]?token|secret[_-]?key|refresh[_-]?token)\\s*[:=]\\s*['"]?[^\\s,;'"&]+`,"gi"),t3t=["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"];r3t=["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"],n3t=["utm_source","utm_medium","utm_campaign","utm_term","utm_content","fbclid","gclid","_ga"]});var i3t,jne,PG,Gne=k(()=>{"use strict";H();Rt();i3t={maxTokens:10,refillIntervalMs:1e3,tokensPerRefill:10,maxQueueSize:100,queueTimeoutMs:3e4},jne=class{tokens;config;queue=[];refillTimer=null;lastRefillTime;constructor(e={}){this.config={...i3t,...e},this.tokens=this.config.maxTokens,this.lastRefillTime=Date.now(),this.startRefillTimer()}startRefillTimer(){this.refillTimer||(this.refillTimer=setInterval(()=>{this.refillTokens(),this.processQueue()},this.config.refillIntervalMs),this.refillTimer.unref())}refillTokens(){let e=Date.now(),t=e-this.lastRefillTime,n=Math.floor(t/this.config.refillIntervalMs);if(n>0){let o=n*this.config.tokensPerRefill;this.tokens=Math.min(this.config.maxTokens,this.tokens+o),this.lastRefillTime=e}}processQueue(){let e=Date.now();for(;this.queue.length>0;){let t=this.queue[0];if(e-t.timestamp>this.config.queueTimeoutMs)this.queue.shift(),t.timeoutTimer&&clearTimeout(t.timeoutTimer),t.reject(pe.rateLimiterQueueTimeout(this.config.queueTimeoutMs));else break}for(;this.tokens>0&&this.queue.length>0;){let t=this.queue.shift();t&&(t.timeoutTimer&&clearTimeout(t.timeoutTimer),this.tokens--,t.resolve())}}async acquire(){if(this.refillTokens(),this.tokens>0){this.tokens--;return}if(this.queue.length>=this.config.maxQueueSize)throw g.warn(`Rate limiter queue full (${this.config.maxQueueSize} requests pending)`),pe.rateLimiterQueueFull(this.config.maxQueueSize);return new Promise((e,t)=>{let n=setTimeout(()=>{let o=this.queue.findIndex(s=>s.timeoutTimer===n);o!==-1&&(this.queue.splice(o,1),t(pe.rateLimiterQueueTimeout(this.config.queueTimeoutMs)))},this.config.queueTimeoutMs);this.queue.push({resolve:e,reject:t,timestamp:Date.now(),timeoutTimer:n})})}getStats(){return{availableTokens:this.tokens,queueLength:this.queue.length,maxTokens:this.config.maxTokens,maxQueueSize:this.config.maxQueueSize}}reset(){for(this.tokens=this.config.maxTokens,this.lastRefillTime=Date.now();this.queue.length>0;){let e=this.queue.shift();e&&(e.timeoutTimer&&clearTimeout(e.timeoutTimer),e.reject(pe.rateLimiterReset()))}}stop(){this.refillTimer&&(clearInterval(this.refillTimer),this.refillTimer=null),this.reset()}},PG=new jne({maxTokens:10,refillIntervalMs:1e3,tokensPerRefill:10,maxQueueSize:100,queueTimeoutMs:3e4})});function Jne(r,e=Ea.DEFAULT_INITIAL_DELAY,t=Ea.DEFAULT_BACKOFF_MULTIPLIER,n=Ea.DEFAULT_MAX_DELAY,o=!0){let s=e*Math.pow(t,r-1),i=Math.min(s,n),a=o?Math.random()*Math.min(i*.1,1e3):0;return i+a}function Yne(r){return new Promise(e=>setTimeout(e,r))}async function v1e(r,e={}){let t={...a3t,...e},n;for(let o=1;o<=t.maxAttempts;o++)try{return await r()}catch(s){if(n=s,o===t.maxAttempts||!t.retryCondition(s))break;t.onRetry(o,s);let i=Jne(o,t.initialDelay,t.backoffMultiplier,t.maxDelay,!0);await Yne(i)}throw n}var Vne,qne,a3t,Hne,Wne,Kne,MDn,ODn,NDn,Xne=k(()=>{"use strict";H();mi();Vne=class extends Error{constructor(t,n){super(t);this.cause=n;this.name="NetworkError"}cause},qne=class extends Error{constructor(t,n){super(t);this.cause=n;this.name="TemporaryError"}cause},a3t={maxAttempts:Ea.DEFAULT_RETRY_ATTEMPTS,initialDelay:Ea.DEFAULT_INITIAL_DELAY,maxDelay:Ea.DEFAULT_MAX_DELAY,backoffMultiplier:Ea.DEFAULT_BACKOFF_MULTIPLIER,retryCondition:r=>{if(r instanceof Vne||r instanceof qne||r&&typeof r=="object"&&(r.name==="TimeoutError"||r.code==="TIMEOUT")||r&&typeof r=="object"&&(r.code==="ECONNRESET"||r.code==="ENOTFOUND"||r.code==="ECONNREFUSED"||r.code==="ETIMEDOUT"))return!0;if(r&&typeof r=="object"&&r.status){let e=Number(r.status);return e>=500||e===429||e===408}return!1},onRetry:(r,e)=>{let t=e instanceof Error?e.message:String(e);g.warn(`\u26A0\uFE0F Retry attempt ${r}: ${t}`)}};Hne=class{constructor(e=5,t=6e4,n=6e5){this.threshold=e;this.timeout=t;this.monitorWindow=n}threshold;timeout;monitorWindow;failures=0;lastFailureTime=0;state="closed";async execute(e){if(this.state==="open")if(Date.now()-this.lastFailureTime>this.timeout)this.state="half-open";else throw new Error("Circuit breaker is open - operation rejected");try{let 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.threshold&&(this.state="open")}getState(){return this.state}reset(){this.failures=0,this.lastFailureTime=0,this.state="closed"}},Wne=class{constructor(e,t){this.maxRequests=e;this.windowMs=t}maxRequests;windowMs;requests=[];async acquire(){let e=Date.now();if(this.requests=this.requests.filter(t=>e-t<this.windowMs),this.requests.length>=this.maxRequests){let t=Math.min(...this.requests),n=this.windowMs-(e-t);if(n>0)return await Yne(n),this.acquire()}this.requests.push(e)}},Kne=class{operations=new Set;shutdownPromise=null;track(e){return this.operations.add(e),e.finally(()=>{this.operations.delete(e)}),e}async shutdown(e=3e4){return this.shutdownPromise?this.shutdownPromise:(this.shutdownPromise=this.performShutdown(e),this.shutdownPromise)}async performShutdown(e){g.debug(`\u{1F504} Graceful shutdown: waiting for ${this.operations.size} operations...`);try{await Promise.race([Promise.all(this.operations),Yne(e).then(()=>{throw new Error(`Shutdown timeout: ${this.operations.size} operations still running`)})]),g.debug("\u2705 Graceful shutdown completed")}catch(t){g.warn(`\u26A0\uFE0F Shutdown warning: ${t instanceof Error?t.message:String(t)}`)}}},MDn=new Kne,ODn=new Hne(3,3e4),NDn=new Wne(100,6e4)});var rl,bg,qy,MG,T1e,Pi,Zne=k(()=>{"use strict";rl={IMAGE_MAX_MB:10,PDF_MAX_MB:100,DOCUMENT_MAX_MB:100,WORD_MAX_MB:100,TEXT_MAX_MB:50,CSV_MAX_MB:50,EXCEL_MAX_MB:100,SOURCE_CODE_MAX_MB:20,JSON_MAX_MB:20,YAML_MAX_MB:20,XML_MAX_MB:20,VIDEO_MAX_MB:500,AUDIO_MAX_MB:500,ARCHIVE_MAX_MB:200,GENERAL_MAX_MB:200},bg={IMAGE_MAX:10*1024*1024,PDF_MAX:100*1024*1024,DOCUMENT_MAX:100*1024*1024,WORD_MAX:100*1024*1024,TEXT_MAX:50*1024*1024,CSV_MAX:50*1024*1024,EXCEL_MAX:100*1024*1024,SOURCE_CODE_MAX:20*1024*1024,JSON_MAX:20*1024*1024,YAML_MAX:20*1024*1024,XML_MAX:20*1024*1024,VIDEO_MAX:500*1024*1024,AUDIO_MAX:500*1024*1024,ARCHIVE_MAX:200*1024*1024,GENERAL_MAX:200*1024*1024},qy={MAX_SOURCE_CODE_LINES:1e4,MAX_TEXT_LINES:1e4,MAX_TEXT_LENGTH:1e6,MAX_CSV_ROWS:1e4,MAX_EXCEL_ROWS:5e3,MAX_EXCEL_SHEETS:10,MAX_PDF_PAGES:100,MAX_OBJECT_DEPTH:50,MAX_ARRAY_LENGTH:1e4},MG={MAX_DECOMPRESSED_SIZE:100*1024*1024,MAX_COMPRESSION_RATIO:100,MAX_ENTRIES:1e3,MAX_NESTING_DEPTH:5},T1e={MAX_ALIAS_COUNT:100,MAX_DOCUMENTS:10,MAX_ANCHORS:100},Pi={IMAGE_MAX_MB:rl.IMAGE_MAX_MB,PDF_MAX_MB:rl.PDF_MAX_MB,DOCUMENT_MAX_MB:rl.DOCUMENT_MAX_MB,WORD_MAX_MB:rl.WORD_MAX_MB,TEXT_MAX_MB:rl.TEXT_MAX_MB,CSV_MAX_MB:rl.CSV_MAX_MB,EXCEL_MAX_MB:rl.EXCEL_MAX_MB,SOURCE_CODE_MAX_MB:rl.SOURCE_CODE_MAX_MB,MAX_FILE_SIZE:bg.GENERAL_MAX,MAX_IMAGE_SIZE:bg.IMAGE_MAX,MAX_TEXT_SIZE:bg.TEXT_MAX,MAX_SOURCE_CODE_LINES:qy.MAX_SOURCE_CODE_LINES,MAX_TEXT_LINES:qy.MAX_TEXT_LINES,MAX_TEXT_LENGTH:qy.MAX_TEXT_LENGTH,MAX_CSV_ROWS:qy.MAX_CSV_ROWS,EXCEL_MAX_ROWS:qy.MAX_EXCEL_ROWS,EXCEL_MAX_SHEETS:qy.MAX_EXCEL_SHEETS,MAX_PDF_PAGES:qy.MAX_PDF_PAGES,MAX_DECOMPRESSED_SIZE:MG.MAX_DECOMPRESSED_SIZE,MAX_COMPRESSION_RATIO:MG.MAX_COMPRESSION_RATIO,MAX_ZIP_ENTRIES:MG.MAX_ENTRIES,YAML_MAX_ALIAS_COUNT:T1e.MAX_ALIAS_COUNT}});function OG(r){return Qne||(Qne=new eoe(r)),Qne}var eoe,Qne,toe=k(()=>{"use strict";fr();H();fn();eoe=class{cache=new Map;contentHashIndex=new Map;maxSize;ttlMs;maxImageSize;enabled;stats={hits:0,misses:0,evictions:0,expirations:0,totalRequests:0};constructor(e={}){let t=process.env.NEUROLINK_IMAGE_CACHE_ENABLED,n=process.env.NEUROLINK_IMAGE_CACHE_SIZE,o=process.env.NEUROLINK_IMAGE_CACHE_TTL_MS,s=process.env.NEUROLINK_IMAGE_MAX_SIZE;this.enabled=t!==void 0?t.toLowerCase()==="true":!1,this.maxSize=this.parseConfigValue(n,e.maxSize,100,1,1e3),this.ttlMs=this.parseConfigValue(o,e.ttlMs,1800*1e3,1e3,1440*60*1e3),this.maxImageSize=this.parseConfigValue(s,e.maxImageSize,10*1024*1024,1024,100*1024*1024),g.debug("ImageCache initialized",{enabled:this.enabled,maxSize:this.maxSize,ttlMs:this.ttlMs,maxImageSize:this.maxImageSize})}parseConfigValue(e,t,n,o,s){let i;if(e!==void 0){let a=parseInt(e,10);i=isNaN(a)?n:a}else t!==void 0?i=t:i=n;return i<o?(g.warn(`Cache config value ${i} below minimum ${o}, using min`),o):i>s?(g.warn(`Cache config value ${i} above maximum ${s}, using max`),s):i}normalizeUrl(e){return IG(e)}generateContentHash(e){let t=typeof e=="string"?Buffer.from(e,"base64"):e;return Ii("sha256").update(t).digest("hex").substring(0,16)}isExpired(e){return Date.now()-e.createdAt>this.ttlMs}isEnabled(){return this.enabled}get(e){if(!this.enabled)return null;this.stats.totalRequests++;let t=this.normalizeUrl(e),n=this.cache.get(t);return n?this.isExpired(n)?(this.stats.expirations++,this.delete(t),g.debug("Image cache entry expired",{url:tc(t)}),null):(n.lastAccessedAt=Date.now(),n.accessCount++,this.cache.delete(t),this.cache.set(t,n),this.stats.hits++,g.debug("Image cache hit",{url:tc(t),accessCount:n.accessCount}),n):(this.stats.misses++,g.debug("Image cache miss",{url:tc(t)}),null)}getByContentHash(e){let t=this.contentHashIndex.get(e);if(!t)return null;let n=null;for(let o of[...t]){let s=this.cache.get(o);if(!s){t.delete(o);continue}if(this.isExpired(s)){this.cache.delete(o),t.delete(o);continue}n===null&&(n=o)}return t.size===0&&this.contentHashIndex.delete(e),n?this.get(n):null}set(e,t,n,o){if(!this.enabled){g.debug("Image caching disabled, skipping cache storage");return}let s=this.normalizeUrl(e),i=o.length;if(i>this.maxImageSize){g.debug("Image too large to cache",{url:tc(s),size:i,maxSize:this.maxImageSize});return}let a=this.generateContentHash(o),c=this.contentHashIndex.get(a);if(c)for(let p of c){if(p===s)continue;let f=this.cache.get(p);if(f&&!this.isExpired(f)){for(;this.cache.size>=this.maxSize&&this.cache.size>0;)this.evictOldest();this.cache.set(s,{...f});let h=this.contentHashIndex.get(a);h||(h=new Set,this.contentHashIndex.set(a,h)),h.add(s),g.debug("Image cache dedup hit",{newUrl:tc(s),existingUrl:tc(p)});return}}for(;this.cache.size>=this.maxSize;)this.evictOldest();let l=Date.now(),u={dataUri:t,contentType:n,size:i,contentHash:a,createdAt:l,lastAccessedAt:l,accessCount:1};this.cache.set(s,u);let d=this.contentHashIndex.get(a);d||(d=new Set,this.contentHashIndex.set(a,d)),d.add(s),g.debug("Image cached",{url:tc(s),size:i,contentHash:a.substring(0,8),cacheSize:this.cache.size})}delete(e){let t=this.normalizeUrl(e),n=this.cache.get(t);if(n){let o=this.contentHashIndex.get(n.contentHash);return o&&(o.delete(t),o.size===0&&this.contentHashIndex.delete(n.contentHash)),this.cache.delete(t),!0}return!1}evictOldest(){let e=this.cache.keys().next().value;if(e!==void 0){let t=this.cache.get(e);if(t){let n=this.contentHashIndex.get(t.contentHash);n&&(n.delete(e),n.size===0&&this.contentHashIndex.delete(t.contentHash))}this.cache.delete(e),this.stats.evictions++,g.debug("Image cache eviction",{url:tc(String(e))})}}evictExpired(){let e=0,t=Date.now();for(let[n,o]of this.cache.entries())t-o.createdAt>this.ttlMs&&(this.delete(n),e++,this.stats.expirations++);return e>0&&g.debug(`Evicted ${e} expired image cache entries`),e}clear(){let e=this.cache.size;this.cache.clear(),this.contentHashIndex.clear(),g.debug(`Image cache cleared (${e} entries removed)`)}getStats(){let e=0;for(let n of this.cache.values())e+=n.size;let t=this.stats.totalRequests>0?Number((this.stats.hits/this.stats.totalRequests*100).toFixed(2)):0;return{...this.stats,size:this.cache.size,totalBytes:e,hitRate:t}}has(e){let t=this.normalizeUrl(e),n=this.cache.get(t);return n!=null&&!this.isExpired(n)}getSize(){return this.cache.size}getConfig(){return{enabled:this.enabled,maxSize:this.maxSize,ttlMs:this.ttlMs,maxImageSize:this.maxImageSize}}},Qne=null});function u3t(r){if(r&&typeof r=="object"){let e=r.code,t=r.name;if(l3t.has(e||"")||t==="AbortError")return!0}if(r instanceof Error){let e=r.message,t=e.match(/HTTP (\d{3}):/);if(t){let n=parseInt(t[1],10);return n>=500||n===429||n===408}if(/\b(request timed out|operation timed out|connection timed out|timed out)\b/i.test(e)||/\bnetwork (error|failure|unreachable|down)\b/i.test(e))return!0}return!1}function roe(r){if(r==="application/octet-stream")throw g.error("Unable to detect a supported image format from file content"),new Error("Unsupported or corrupted image: no known image signature (PNG/JPEG/GIF/WebP/BMP/TIFF/SVG/AVIF) was found in the file content.")}var S1e,c3t,l3t,Fu,d3t,p3t,NM,NG=k(()=>{"use strict";pn();H();fn();Gne();Xne();mi();Zne();toe();Rt();S1e=12,c3t={"image/png":67,"image/jpeg":125,"image/gif":43,"image/webp":20,"image/avif":100},l3t=new Set(["ECONNRESET","ENOTFOUND","ECONNREFUSED","ETIMEDOUT","ERR_NETWORK"]);Fu=class r{static async process(e,t){let n=this.validateBufferNotEmpty(e);roe(n);let o=r.safeBase64Convert(e,"image processing"),s=`data:${n};base64,${o}`;return this.validateProcessOutput(s,o,n),{type:"image",content:s,mimeType:n,metadata:{confidence:100,size:e.length}}}static hasStrictImageMagic(e,t){let n=e;switch(t){case"image/png":return n.length>=4&&n[0]===137&&n[1]===80&&n[2]===78&&n[3]===71;case"image/jpeg":return n.length>=3&&n[0]===255&&n[1]===216&&n[2]===255;case"image/gif":return n.length>=3&&n[0]===71&&n[1]===73&&n[2]===70;case"image/webp":return n.length>=12&&n.subarray(0,4).toString("latin1")==="RIFF"&&n.subarray(8,12).toString("latin1")==="WEBP";case"image/avif":return n.length>=12&&n.subarray(4,8).toString("latin1")==="ftyp"&&n.subarray(8,12).toString("latin1").startsWith("avif");default:return!1}}static validateBufferNotEmpty(e){if(e.length===0)throw g.error("Empty buffer provided"),pe.imageBufferInvalid("Invalid image processing: buffer is empty");let t=this.detectImageType(e);if(t==="image/svg+xml")return t;if(e.length<S1e)throw pe.imageBufferInvalid(`Invalid image processing: buffer too small (${e.length} bytes) \u2014 a minimum of ${S1e} bytes is required for a valid image.`);let n=c3t[t];if(n!==void 0&&e.length<n&&this.hasStrictImageMagic(e,t))throw pe.imageBufferInvalid(`Invalid image processing: ${t} buffer is truncated (${e.length} bytes, minimum ${n} for a valid ${t}).`);return t}static validateProcessOutput(e,t,n){if(t.length===0)throw g.error("Empty base64 content generated"),new Error("Invalid image processing: base64 content is empty");if(!/^data:[^;]+;base64,[A-Za-z0-9+/]*={0,2}$/.test(e))throw g.error("Invalid data URI format generated",{dataUri:e}),new Error("Invalid data URI format: must be data:{mimeType};base64,{content}");if(!this.validateImageFormat(n))throw g.error("Invalid MIME type generated",{mediaType:n}),new Error(`Invalid MIME type: ${n} is not in allowed list`)}static processImageForOpenAI(e){try{return typeof e=="string"?e.startsWith("http")||e.startsWith("data:")?e:`data:image/jpeg;base64,${e}`:`data:image/jpeg;base64,${r.safeBase64Convert(e,"OpenAI image input")}`}catch(t){throw t instanceof Fe?t:(g.error("Failed to process image for OpenAI:",t),new Error(`Image processing failed for OpenAI: ${t instanceof Error?t.message:"Unknown error"}`,{cause:t}))}}static processImageForGoogle(e){try{let t,n="image/jpeg";if(typeof e=="string")if(e.startsWith("data:")){let o=e.match(/^data:([^;]+);base64,(.+)$/);o?(n=o[1],t=o[2]):t=e.split(",")[1]||e}else t=e;else t=r.safeBase64Convert(e,"provider image input");return{mimeType:n,data:t}}catch(t){throw t instanceof Fe?t:(g.error("Failed to process image for Google AI:",t),new Error(`Image processing failed for Google AI: ${t instanceof Error?t.message:"Unknown error"}`,{cause:t}))}}static processImageForAnthropic(e){try{let t,n="image/jpeg";if(typeof e=="string")if(e.startsWith("data:")){let o=e.match(/^data:([^;]+);base64,(.+)$/);o?(n=o[1],t=o[2]):t=e.split(",")[1]||e}else t=e;else t=r.safeBase64Convert(e,"provider image input");return{mediaType:n,data:t}}catch(t){throw t instanceof Fe?t:(g.error("Failed to process image for Anthropic:",t),new Error(`Image processing failed for Anthropic: ${t instanceof Error?t.message:"Unknown error"}`,{cause:t}))}}static processImageForVertex(e,t){try{return t.includes("gemini")?r.processImageForGoogle(e):t.includes("claude")?r.processImageForAnthropic(e):r.processImageForGoogle(e)}catch(n){throw n instanceof Fe?n:(g.error("Failed to process image for Vertex AI:",n),new Error(`Image processing failed for Vertex AI: ${n instanceof Error?n.message:"Unknown error"}`,{cause:n}))}}static detectImageType(e){try{if(typeof e=="string"){if(e.startsWith("data:")){let o=e.match(/^data:([^;]+);/);return o?o[1]:"image/jpeg"}let t=e.toLowerCase().split(".").pop();return{jpg:"image/jpeg",jpeg:"image/jpeg",png:"image/png",gif:"image/gif",webp:"image/webp",bmp:"image/bmp",tiff:"image/tiff",tif:"image/tiff",svg:"image/svg+xml",avif:"image/avif"}[t||""]||"image/jpeg"}if(e.length>=4){let t=e.subarray(0,4);if(t[0]===137&&t[1]===80&&t[2]===78&&t[3]===71)return"image/png";if(t[0]===255&&t[1]===216&&t[2]===255)return"image/jpeg";if(t[0]===71&&t[1]===73&&t[2]===70&&t[3]===56)return"image/gif";if(e.length>=12){let n=e.subarray(0,4),o=e.subarray(8,12);if(n.toString()==="RIFF"&&o.toString()==="WEBP")return"image/webp"}if(e.length>=4){let n=e.subarray(0,4).toString();if(n==="<svg"||n==="<?xm")return"image/svg+xml"}if(e.length>=12){let n=e[4]===102&&e[5]===116&&e[6]===121&&e[7]===112,o=String.fromCharCode(e[8],e[9],e[10],e[11]);if(n&&(o==="avif"||o==="avis"||o==="avio"))return"image/avif"}if(e[0]===66&&e[1]===77)return"image/bmp";if(e[0]===73&&e[1]===73&&e[2]===42&&e[3]===0||e[0]===77&&e[1]===77&&e[2]===0&&e[3]===42)return"image/tiff"}return g.warn("Could not detect image type from magic bytes; using application/octet-stream"),"application/octet-stream"}catch(t){return g.warn("Failed to detect image type, using default:",t),"application/octet-stream"}}static validateSize(e,t,n=bg.IMAGE_MAX){if(!Number.isFinite(n)||n<0)throw pe.invalidConfiguration("maxSize","must be a finite, non-negative byte count",{maxSize:n,context:t});if(!Number.isFinite(e)||e<0)throw pe.invalidImageSize(e);if(e>n){let o=(e/1048576).toFixed(1),s=(n/(1024*1024)).toFixed(0);throw pe.imageTooLarge(o,s)}}static validateBufferSize(e,t,n=bg.IMAGE_MAX){r.validateSize(e.length,t,n)}static safeBase64Convert(e,t,n=bg.IMAGE_MAX){return r.validateBufferSize(e,t,n),e.toString("base64")}static validateImageFormat(e){return["image/jpeg","image/png","image/gif","image/webp","image/bmp","image/tiff","image/svg+xml","image/avif"].includes(e.toLowerCase())}static getImageDimensions(e){try{if(e.length>=24&&e.subarray(0,8).toString("hex")==="89504e470d0a1a0a"){let t=e.readUInt32BE(16),n=e.readUInt32BE(20);return{width:t,height:n}}if(e.length>=4&&e[0]===255&&e[1]===216){let t=2;for(;t<e.length-1;){if(e[t]!==255){t++;continue}for(;t<e.length&&e[t]===255;)t++;if(t>=e.length)break;let n=e[t];if(t++,n===192||n===194){if(t+7>e.length)break;let s=e.readUInt16BE(t+3);return{width:e.readUInt16BE(t+5),height:s}}if(n===208||n===209||n===210||n===211||n===212||n===213||n===214||n===215||n===216||n===217||n===1)continue;if(t+2>e.length)break;let o=e.readUInt16BE(t);t+=o}return null}return null}catch(t){return g.warn("Failed to extract image dimensions:",t),null}}static processImage(e,t,n){try{Buffer.isBuffer(e)&&r.validateBufferSize(e,"image processing");let o=r.detectImageType(e);roe(o);let s=typeof e=="string"?Buffer.byteLength(e,"base64"):e.length,i,a;switch(t.toLowerCase()){case"openai":i=r.processImageForOpenAI(e),a="data_uri";break;case"google-ai":case"google":{i=r.processImageForGoogle(e).data,a="base64";break}case"anthropic":{i=r.processImageForAnthropic(e).data,a="base64";break}case"vertex":{i=r.processImageForVertex(e,n||"").data,a="base64";break}default:typeof e=="string"?i=e.startsWith("data:")&&e.split(",")[1]||e:i=r.safeBase64Convert(e,"image input"),a="base64"}return{data:i,mediaType:o,size:s,format:a}}catch(o){throw o instanceof Fe?o:(g.error(`Failed to process image for ${t}:`,o),new Error(`Image processing failed: ${o instanceof Error?o.message:"Unknown error"}`,{cause:o}))}}},d3t=["jpg","jpeg","png","gif","webp","bmp","tiff","tif","svg","avif","ico","heic","heif"],p3t=new Set(d3t),NM={isDataUri:r=>typeof r=="string"&&r.startsWith("data:")&&r.includes("base64,"),isUrl:r=>{try{return new URL(r),r.startsWith("http://")||r.startsWith("https://")}catch{return!1}},isBase64:r=>NM.isValidBase64(r),getFileExtension:r=>{let t=r.split(/[?#]/)[0].match(/\.([^.]+)$/);if(!t)return null;let n=t[1].toLowerCase();return/^[a-z0-9]+$/.test(n)?n:null},isValidImageExtension:r=>{if(!r||typeof r!="string")return!1;let e=r.toLowerCase();return/^[a-z0-9]+$/.test(e)?p3t.has(e):!1},getValidatedImageExtension:r=>{let e=NM.getFileExtension(r);return e&&NM.isValidImageExtension(e)?e:null},formatFileSize:r=>{if(r===0)return"0 Bytes";let e=1024,t=["Bytes","KB","MB","GB"],n=Math.floor(Math.log(r)/Math.log(e));return parseFloat((r/Math.pow(e,n)).toFixed(2))+" "+t[n]},bufferToBase64:(r,e=bg.IMAGE_MAX)=>Fu.safeBase64Convert(r,"buffer-to-base64",e),base64ToBuffer:r=>{let e=r.includes(",")?r.split(",")[1]:r;return Buffer.from(e,"base64")},redactPathFromMessage:zne,fileToBase64DataUri:async(r,e=10*1024*1024)=>{try{let t=await Promise.resolve().then(()=>(Lu(),xg)),n=await t.stat(r);if(!n.isFile())throw new Error("Not a file");if(n.size>e)throw new Error(`File too large: ${n.size} bytes (max: ${e} bytes)`);let o=await t.readFile(r),s=Fu.detectImageType(o)||Fu.detectImageType(r);roe(s);let i=o.toString("base64");return`data:${s};base64,${i}`}catch(t){g.debug("fileToBase64DataUri failed",{filePath:r,error:t});let n=Ks(r),o=Vy(t,{filePath:r}),s=t instanceof Error?o.message:"Unknown error";throw new Error(`Failed to convert file to base64 (${n}): ${s}`,{cause:o})}},urlToBase64DataUri:async(r,{timeoutMs:e=15e3,maxBytes:t=10*1024*1024,maxAttempts:n=3}={})=>{let o=OG(),s=o.get(r);if(s)return g.debug("Using cached image for URL",{url:tc(r)}),s.dataUri;if(await PG.acquire(),!/^https?:\/\//i.test(r))throw new Error("Unsupported protocol");let i=async()=>{let a=new AbortController,c=setTimeout(()=>a.abort(),e);try{let l=await fetch(r,{signal:a.signal});if(!l.ok)throw new Error(`HTTP ${l.status}: ${l.statusText}`);let u=l.headers.get("content-type")||"";if(!/^image\//i.test(u))throw new Error(`Unsupported content-type: ${u||"unknown"}`);let d=l.headers.get("content-length"),p=Number(d||0);if(d!==null&&p===0)throw new Error("Empty response: content-length is 0");if(p&&p>t)throw new Error(`Content too large: ${p} bytes`);let f=await l.arrayBuffer();if(f.byteLength>t)throw new Error(`Downloaded content too large: ${f.byteLength} bytes`);let h=Buffer.from(f),y=h.toString("base64"),x=`data:${u||"image/jpeg"};base64,${y}`;return o.set(r,x,u||"image/jpeg",h),x}finally{clearTimeout(c)}};try{return await v1e(i,{maxAttempts:n,initialDelay:Ea.DEFAULT_INITIAL_DELAY,backoffMultiplier:Ea.DEFAULT_BACKOFF_MULTIPLIER,maxDelay:Ea.DEFAULT_MAX_DELAY,retryCondition:u3t,onRetry:(a,c)=>{let l=Bne(c instanceof Error?c.message:String(c)),u=n-a;g.warn(`\u26A0\uFE0F Image download attempt ${a} failed for ${tc(r)}: ${l}. ${u} ${u===1?"attempt":"attempts"} remaining...`)}})}catch(a){let c=tc(r),l=Vy(a);throw new Error(`Failed to download and convert URL to base64 (${c}): ${l.message}`,{cause:l})}},extractBase64FromDataUri:r=>r.includes(",")?r.split(",")[1]:r,extractMimeTypeFromDataUri:r=>{let e=r.match(/^data:([^;]+);base64,/);return e?e[1]:"image/jpeg"},createDataUri:(r,e="image/jpeg")=>{let t=r.includes(",")?r.split(",")[1]:r;return`data:${e};base64,${t}`},isValidBase64:r=>{try{let e=r.includes(",")?r.split(",")[1]:r;if(!e||e.length===0||!/^[A-Za-z0-9+/]*={0,2}$/.test(e)||e.length%4!==0)return!1;let n=e.indexOf("=");if(n!==-1){if(n<e.length-2)return!1;let a=e.slice(n);if(!/^=+$/.test(a))return!1}let s=Buffer.from(e,"base64").toString("base64"),i=a=>a.replace(/=+$/,"");return i(e)===i(s)}catch{return!1}},getBase64Size:r=>{let e=r.includes(",")?r.split(",")[1]:r;return Buffer.byteLength(e,"base64")},compressBase64:(r,e=.8)=>(g.warn("Base64 compression not implemented - returning original"),r)}});function f3t(r){let e=r.toLowerCase();switch(e.replace(/[^a-z]/g,"")){case"lmstudio":return"lm-studio";case"llamacpp":return"llamacpp";case"nvidianim":return"nvidia-nim";case"googleaistudio":return"google-ai";case"or":return"openrouter";default:return e}}var Hy,DM,m3t,noe,k_,w1e=k(()=>{"use strict";NG();H();Hy=class{static logError(e,t,n){g.error(`Multimodal ${e} failed: ${t.message}`),process.env.NODE_ENV==="development"&&(g.error("Context:",JSON.stringify(n,null,2)),g.error("Stack:",t.stack))}},DM={openai:10,azure:10,"google-ai":16,google:16,anthropic:20,vertex:{claude:20,gemini:16,default:16},ollama:10,litellm:10,mistral:10,bedrock:20,openrouter:10},m3t=new Set(["litellm","openrouter"]);noe={openai:["gpt-5.4","gpt-5.4-mini","gpt-5.4-nano","gpt-5.4-pro","gpt-5.2","gpt-5.2-chat-latest","gpt-5.2-pro","gpt-5","gpt-5-2025-08-07","gpt-5-pro","gpt-5-mini","gpt-5-nano","gpt-4.1","gpt-4.1-mini","gpt-4.1-nano","o3","o3-mini","o3-pro","o4","o4-mini","o4-mini-deep-research","gpt-4o","gpt-4o-mini","gpt-4-turbo","gpt-4-vision-preview"],"google-ai":["gemini-3.1-pro-preview","gemini-3.1-flash-lite-preview","gemini-3.1-flash-image-preview","gemini-3.1-pro-preview-customtools","gemini-3-flash-preview","gemini-3-pro-image-preview","gemini-3-pro-preview","gemini-2.5-pro","gemini-2.5-flash","gemini-2.5-flash-lite","gemini-2.5-flash-image","gemini-2.0-flash","gemini-2.0-flash-001","gemini-2.0-flash-lite","gemini-2.0-flash-preview-image-generation","gemini-1.5-pro","gemini-1.5-flash","gemini-pro-vision"],anthropic:["claude-opus-4-6","claude-sonnet-4-6","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-opus-4-1","claude-opus-4-1-20250805","claude-opus-4","claude-opus-4-20250514","claude-sonnet-4","claude-sonnet-4-20250514","claude-3-7-sonnet","claude-3-7-sonnet-20250219","claude-3-5-sonnet","claude-3-5-sonnet-20241022","claude-3-opus","claude-3-sonnet","claude-3-haiku"],azure:["gpt-5.1","gpt-5.1-chat","gpt-5.1-codex","gpt-5","gpt-5-pro","gpt-5-turbo","gpt-5-chat","gpt-5-mini","gpt-4.1","gpt-4.1-mini","gpt-4.1-nano","o3","o3-mini","o3-pro","o4-mini","gpt-4o","gpt-4o-mini","gpt-4-turbo","gpt-4-vision-preview","gpt-4"],vertex:["gemini-3.1-pro-preview","gemini-3.1-flash-lite-preview","gemini-3.1-flash-image-preview","gemini-3.1-pro-preview-customtools","gemini-3-flash-preview","gemini-3-pro-image-preview","gemini-3-pro-preview","gemini-2.5-pro","gemini-2.5-flash","gemini-2.5-flash-lite","gemini-2.5-flash-image","gemini-2.0-flash-001","gemini-2.0-flash-lite","gemini-2.0-flash","gemini-1.5-pro","gemini-1.5-flash","claude-sonnet-4-5@","claude-opus-4-5@","claude-haiku-4-5@","claude-haiku-4-5","claude-sonnet-4@","claude-opus-4@","claude-opus-4-1@","claude-3-7-sonnet@","claude-3-5-sonnet@","claude-opus-3@","claude-haiku-3@","claude-3-7-sonnet","claude-3-5-sonnet","claude-3-opus","claude-3-sonnet","claude-3-haiku","claude-sonnet-4","claude-sonnet-3","claude-opus-3","claude-haiku-3","claude-haiku-4","claude-3.5-sonnet","claude-3.5-haiku","claude-4.5-sonnet","claude-4.5-opus","claude-4.5-haiku","claude-haiku-4-5","claude-3.0-sonnet","claude-3.0-opus"],litellm:["openai/gpt-5","openai/gpt-4o","openai/gpt-4o-mini","openai/gpt-4-turbo","gpt-5","gpt-4o","gpt-4.1","anthropic/claude-sonnet-4-5-20250929","anthropic/claude-opus-4-1-20250805","anthropic/claude-3-5-sonnet-20240620","claude-sonnet-4-5","claude-sonnet-4-5-20250929","claude-opus-4-5","claude-opus-4-5-20251101","claude-haiku-4-5-20251001","claude-sonnet-4","claude-opus-4-1","vertex_ai/gemini-2.5-pro","gemini/gemini-2.5-pro","gemini/gemini-2.0-flash","gemini-3.1-pro-preview","gemini-3-flash-preview","gemini-2.5-pro","gemini-2.5-flash","gemini-2.0-flash-lite","groq/llama-3.2-11b-vision-preview"],openrouter:["anthropic/claude-3.7-sonnet","anthropic/claude-3-5-haiku","anthropic/claude-3-opus","anthropic/claude-3-sonnet","anthropic/claude-3-haiku","openai/gpt-4o","openai/gpt-4o-mini","openai/gpt-4-turbo","openai/gpt-4-vision-preview","google/gemini-2.5-pro","google/gemini-2.5-flash","google/gemini-2.0-flash","google/gemini-2.0-flash-001","google/gemini-1.5-pro","google/gemini-1.5-flash","google/gemini-pro-vision","meta-llama/llama-3.2-90b-vision-instruct","meta-llama/llama-3.2-11b-vision-instruct","mistralai/pixtral-12b","mistralai/pixtral-large","qwen/qwen-2-vl-72b-instruct","qwen/qwen-2-vl-7b-instruct"],mistral:["mistral-large-latest","mistral-large-2512","mistral-small","mistral-small-latest","mistral-small-3.2","mistral-small-2506","mistral-medium","mistral-medium-latest","mistral-medium-3.1","mistral-medium-2508","magistral-small","magistral-small-latest","magistral-medium","magistral-medium-latest","pixtral-12b","pixtral-12b-latest","pixtral-large","pixtral-large-latest","pixtral-large-2502"],ollama:["llama4:scout","llama4:maverick","llama4:latest","llama4","llama3.2-vision","llama3.2-vision:11b","llama3.2-vision:90b","gemma3","gemma3:4b","gemma3:12b","gemma3:27b","gemma3:latest","qwen2.5-vl","qwen2.5-vl:72b","qwen2.5-vl:32b","mistral-small3.1","mistral-small3.1:large","mistral-small3.1:medium","mistral-small3.1:small","llava","llava:7b","llava:13b","llava:34b","llava-llama3","llava-llama3:8b"],bedrock:["amazon.nova-premier","amazon.nova-premier-v1:0","amazon.nova-pro","amazon.nova-pro-v1:0","amazon.nova-lite","amazon.nova-lite-v1:0","amazon.nova-2-lite-v1:0","nova-premier","nova-pro","nova-lite","claude-sonnet-4-5","claude-sonnet-4.5","anthropic.claude-sonnet-4-5","anthropic.claude-sonnet-4-5-20250929-v1:0","claude-opus-4-5","claude-opus-4.5","anthropic.claude-opus-4-5","anthropic.claude-opus-4-5-20251124-v1:0","claude-haiku-4-5","claude-haiku-4.5","anthropic.claude-haiku-4-5","anthropic.claude-haiku-4-5-20251001-v1:0","claude-sonnet-4","claude-sonnet-4@","anthropic.claude-sonnet-4","anthropic.claude-sonnet-4-20250514-v1:0","claude-opus-4","claude-opus-4-1","claude-opus-4@","anthropic.claude-opus-4","anthropic.claude-opus-4-1-20250805-v1:0","claude-3-7-sonnet","claude-3.7-sonnet","anthropic.claude-3-7-sonnet","anthropic.claude-3-7-sonnet-20250219-v1:0","claude-3-5-sonnet","claude-3.5-sonnet","anthropic.claude-3-5-sonnet","anthropic.claude-3-5-sonnet-20241022-v1:0","claude-3-opus","anthropic.claude-3-opus","claude-3-sonnet","anthropic.claude-3-sonnet","claude-3-haiku","anthropic.claude-3-haiku","meta.llama4-maverick-17b-instruct-v1:0","meta.llama4-scout-17b-instruct-v1:0","meta.llama3-2-90b-instruct-v1:0","meta.llama3-2-11b-instruct-v1:0","mistral.pixtral-large-2502-v1:0","anthropic.claude"],huggingface:["Qwen/Qwen2.5-VL-32B-Instruct","Qwen/Qwen2.5-VL-7B-Instruct","microsoft/Phi-3-vision-128k-instruct","llava-hf/llava-1.5-7b-hf","llava-hf/llava-v1.6-mistral-7b-hf"],sagemaker:["meta-llama-4-maverick-17b-128e-instruct","meta-llama-4-scout-17b-16e-instruct"],deepseek:[],"nvidia-nim":["meta/llama-3.2-90b-vision-instruct","meta/llama-3.2-11b-vision-instruct"],"lm-studio":["llava","llama-3.2-11b-vision","llama-3.2-90b-vision","vision-instruct","qwen2-vl","qwen2.5-vl","phi-3-vision"],llamacpp:["llava","llama-3.2-11b-vision","llama-3.2-90b-vision","vision-instruct","qwen2-vl","phi-3-vision"],xai:["grok-2-vision-latest"],groq:["llama-3.2-90b-vision-preview","llama-3.2-11b-vision-preview"],cohere:[],"together-ai":[],fireworks:["accounts/fireworks/models/phi-3-vision-128k-instruct","accounts/fireworks/models/llama-v3p2-90b-vision-instruct","accounts/fireworks/models/llama-v3p2-11b-vision-instruct"],perplexity:[],cloudflare:["@cf/meta/llama-3.2-11b-vision-instruct"],replicate:["llava","llama-3.2-vision","moondream","qwen2-vl"],voyage:[],jina:[],stability:[],ideogram:[],recraft:[]},k_=class{static validateImageCount(e,t,n){let o=t.toLowerCase(),s;if(o==="vertex"&&n)n.includes("claude")?s=DM.vertex.claude:n.includes("gemini")?s=DM.vertex.gemini:s=DM.vertex.default;else{let a=o in DM?DM[o]:void 0;a===void 0?(s=10,g.warn(`Image count limit not defined for provider ${t}. Using conservative default of 10 images.`)):s=a}let i=Math.floor(s*.8);if(e===i&&g.warn(`Image count (${e}) is approaching the limit for ${t}. Maximum allowed: ${s}. Please reduce the number of images.`),e>s)throw new Error(`Image count (${e}) exceeds the maximum limit for ${t}. Maximum allowed: ${s}. Please reduce the number of images.`)}static convertToContent(e,t){let n=[{type:"text",text:e}];return t&&t.length>0&&t.forEach(o=>{let s=typeof o=="object"&&"data"in o&&!Buffer.isBuffer(o)?o.data:o,i=typeof o=="object"&&"data"in o&&!Buffer.isBuffer(o)?o.altText:void 0;n.push({type:"image",data:s,altText:i,mediaType:Fu.detectImageType(s)})}),n}static supportsVision(e,t){try{let n=f3t(e),o=noe[n];if(!o||o.length===0)return!1;if(!t)return!0;let s=o.some(i=>t.toLowerCase().includes(i.toLowerCase()));return!s&&m3t.has(n)?!0:s}catch{return!1}}static getSupportedModels(e){let t=e.toLowerCase(),n=noe[t];return n?[...n]:[]}static getVisionProviders(){return Object.entries(noe).filter(([,e])=>e.length>0).map(([e])=>e)}static countImagesInMessage(e,t){return(e?.length||0)+(t??0)}static countImagesInPages(e){return!e||e.length===0?0:e.reduce((t,n)=>t+(n.pageCount??0),0)}}});function E1e(){return{enabled:process.env.NEUROLINK_MEMORY_ENABLED==="true",maxSessions:Number(process.env.NEUROLINK_MEMORY_MAX_SESSIONS)||50,enableSummarization:process.env.NEUROLINK_SUMMARIZATION_ENABLED!=="false",tokenThreshold:process.env.NEUROLINK_TOKEN_THRESHOLD?Number(process.env.NEUROLINK_TOKEN_THRESHOLD):void 0,summarizationProvider:process.env.NEUROLINK_SUMMARIZATION_PROVIDER||"vertex",summarizationModel:process.env.NEUROLINK_SUMMARIZATION_MODEL||"gemini-2.5-flash",maxTurnsPerSession:50}}var ooe,soe,ioe=k(()=>{"use strict";ooe=`
830
830
 
831
831
  IMPORTANT: You are continuing an ongoing conversation. The previous messages in this conversation contain important context including:
@@ -15,6 +15,30 @@
15
15
  import type { AIProviderName, EnhancedGenerateResult, NeuroLinkEvents, StandardRecord, TextGenerationOptions, TypedEventEmitter } from "../../types/index.js";
16
16
  import type { LanguageModel, ModelMessage, Tool } from "../../types/index.js";
17
17
  import { generateText } from "../../utils/generation.js";
18
+ /**
19
+ * Turn budget + wrap-up deadline (parity with the googleVertex native loops).
20
+ * A deadline is engaged only when the caller expressed one: turnTimeoutMs
21
+ * wins, else an explicit generate timeout. Callers that set neither keep the
22
+ * pre-existing behaviour (no wrap-up; the outer defensive timeout in
23
+ * executeStandardGenerateFlow still applies). With `wrapupTimeLeadMs` left of
24
+ * the deadline, the loop stops offering tools (toolChoice: "none") so the
25
+ * model spends the remaining budget producing a final answer instead of being
26
+ * guillotined mid-tool-loop with all work discarded. The lead is clamped to a
27
+ * quarter of the budget so short explicit timeouts (e.g. 30s) don't trigger
28
+ * wrap-up on the very first step.
29
+ *
30
+ * `turnStartMs` anchors the deadline to the ORIGINAL generation start:
31
+ * callGenerateText re-runs on executeGeneration's fallback retries
32
+ * (structured-output conflict, temperature-deprecated) and provider retries,
33
+ * and a deadline computed from Date.now() per attempt would hand each retry
34
+ * a fresh budget — multiplying the caller's wall-clock cap.
35
+ */
36
+ export declare function resolveTurnBudget(options: TextGenerationOptions, turnStartMs: number): {
37
+ callerTimeoutMs: number | undefined;
38
+ turnBudgetMs: number | undefined;
39
+ wrapupLeadMs: number;
40
+ turnDeadline: number | undefined;
41
+ };
18
42
  /**
19
43
  * GenerationHandler class - Handles text generation operations for AI providers
20
44
  */
@@ -64,7 +64,7 @@ function safePreview(v) {
64
64
  * and a deadline computed from Date.now() per attempt would hand each retry
65
65
  * a fresh budget — multiplying the caller's wall-clock cap.
66
66
  */
67
- function resolveTurnBudget(options, turnStartMs) {
67
+ export function resolveTurnBudget(options, turnStartMs) {
68
68
  const callerTimeoutMs = parseTimeout(options.timeout);
69
69
  const hasValidTurnTimeout = typeof options.turnTimeoutMs === "number" &&
70
70
  Number.isFinite(options.turnTimeoutMs) &&
@@ -72,12 +72,27 @@ function resolveTurnBudget(options, turnStartMs) {
72
72
  if (options.turnTimeoutMs !== undefined && !hasValidTurnTimeout) {
73
73
  logger.warn("[GenerationHandler] Ignoring invalid turnTimeoutMs — expected a positive number of milliseconds; falling back to the timeout option", { turnTimeoutMs: options.turnTimeoutMs });
74
74
  }
75
- const turnBudgetMs = hasValidTurnTimeout
75
+ let turnBudgetMs = hasValidTurnTimeout
76
76
  ? options.turnTimeoutMs
77
77
  : callerTimeoutMs;
78
- const wrapupLeadMs = turnBudgetMs
78
+ let wrapupLeadMs = turnBudgetMs
79
79
  ? Math.min(options.wrapupTimeLeadMs ?? DEFAULT_WRAPUP_TIME_LEAD_MS, Math.floor(turnBudgetMs / 4))
80
80
  : 0;
81
+ // When the budget is DERIVED from the generate `timeout`, the hard abort in
82
+ // executeStandardGenerateFlow fires at exactly callerTimeoutMs — the same
83
+ // instant as the turn deadline. Wrap-up would engage at (deadline − lead)
84
+ // but its final, tools-off generation then RACES the abort and loses on
85
+ // slow models (observed: wrap-up engaged at T−lead, final answer killed at
86
+ // exactly T → TimeoutError, all work discarded). Pull the turn deadline one
87
+ // wrap-up lead earlier so the final generation runs in EXCLUSIVE margin
88
+ // before the abort. An explicit turnTimeoutMs is left untouched — the
89
+ // caller separated the two deadlines deliberately.
90
+ if (!hasValidTurnTimeout && turnBudgetMs !== undefined && wrapupLeadMs > 0) {
91
+ turnBudgetMs = turnBudgetMs - wrapupLeadMs;
92
+ // Keep the quarter-budget clamp invariant against the reduced budget so
93
+ // short timeouts still don't wrap up on the very first step.
94
+ wrapupLeadMs = Math.min(wrapupLeadMs, Math.floor(turnBudgetMs / 4));
95
+ }
81
96
  const turnDeadline = turnBudgetMs ? turnStartMs + turnBudgetMs : undefined;
82
97
  return { callerTimeoutMs, turnBudgetMs, wrapupLeadMs, turnDeadline };
83
98
  }
@@ -15,6 +15,30 @@
15
15
  import type { AIProviderName, EnhancedGenerateResult, NeuroLinkEvents, StandardRecord, TextGenerationOptions, TypedEventEmitter } from "../../types/index.js";
16
16
  import type { LanguageModel, ModelMessage, Tool } from "../../types/index.js";
17
17
  import { generateText } from "../../utils/generation.js";
18
+ /**
19
+ * Turn budget + wrap-up deadline (parity with the googleVertex native loops).
20
+ * A deadline is engaged only when the caller expressed one: turnTimeoutMs
21
+ * wins, else an explicit generate timeout. Callers that set neither keep the
22
+ * pre-existing behaviour (no wrap-up; the outer defensive timeout in
23
+ * executeStandardGenerateFlow still applies). With `wrapupTimeLeadMs` left of
24
+ * the deadline, the loop stops offering tools (toolChoice: "none") so the
25
+ * model spends the remaining budget producing a final answer instead of being
26
+ * guillotined mid-tool-loop with all work discarded. The lead is clamped to a
27
+ * quarter of the budget so short explicit timeouts (e.g. 30s) don't trigger
28
+ * wrap-up on the very first step.
29
+ *
30
+ * `turnStartMs` anchors the deadline to the ORIGINAL generation start:
31
+ * callGenerateText re-runs on executeGeneration's fallback retries
32
+ * (structured-output conflict, temperature-deprecated) and provider retries,
33
+ * and a deadline computed from Date.now() per attempt would hand each retry
34
+ * a fresh budget — multiplying the caller's wall-clock cap.
35
+ */
36
+ export declare function resolveTurnBudget(options: TextGenerationOptions, turnStartMs: number): {
37
+ callerTimeoutMs: number | undefined;
38
+ turnBudgetMs: number | undefined;
39
+ wrapupLeadMs: number;
40
+ turnDeadline: number | undefined;
41
+ };
18
42
  /**
19
43
  * GenerationHandler class - Handles text generation operations for AI providers
20
44
  */
@@ -64,7 +64,7 @@ function safePreview(v) {
64
64
  * and a deadline computed from Date.now() per attempt would hand each retry
65
65
  * a fresh budget — multiplying the caller's wall-clock cap.
66
66
  */
67
- function resolveTurnBudget(options, turnStartMs) {
67
+ export function resolveTurnBudget(options, turnStartMs) {
68
68
  const callerTimeoutMs = parseTimeout(options.timeout);
69
69
  const hasValidTurnTimeout = typeof options.turnTimeoutMs === "number" &&
70
70
  Number.isFinite(options.turnTimeoutMs) &&
@@ -72,12 +72,27 @@ function resolveTurnBudget(options, turnStartMs) {
72
72
  if (options.turnTimeoutMs !== undefined && !hasValidTurnTimeout) {
73
73
  logger.warn("[GenerationHandler] Ignoring invalid turnTimeoutMs — expected a positive number of milliseconds; falling back to the timeout option", { turnTimeoutMs: options.turnTimeoutMs });
74
74
  }
75
- const turnBudgetMs = hasValidTurnTimeout
75
+ let turnBudgetMs = hasValidTurnTimeout
76
76
  ? options.turnTimeoutMs
77
77
  : callerTimeoutMs;
78
- const wrapupLeadMs = turnBudgetMs
78
+ let wrapupLeadMs = turnBudgetMs
79
79
  ? Math.min(options.wrapupTimeLeadMs ?? DEFAULT_WRAPUP_TIME_LEAD_MS, Math.floor(turnBudgetMs / 4))
80
80
  : 0;
81
+ // When the budget is DERIVED from the generate `timeout`, the hard abort in
82
+ // executeStandardGenerateFlow fires at exactly callerTimeoutMs — the same
83
+ // instant as the turn deadline. Wrap-up would engage at (deadline − lead)
84
+ // but its final, tools-off generation then RACES the abort and loses on
85
+ // slow models (observed: wrap-up engaged at T−lead, final answer killed at
86
+ // exactly T → TimeoutError, all work discarded). Pull the turn deadline one
87
+ // wrap-up lead earlier so the final generation runs in EXCLUSIVE margin
88
+ // before the abort. An explicit turnTimeoutMs is left untouched — the
89
+ // caller separated the two deadlines deliberately.
90
+ if (!hasValidTurnTimeout && turnBudgetMs !== undefined && wrapupLeadMs > 0) {
91
+ turnBudgetMs = turnBudgetMs - wrapupLeadMs;
92
+ // Keep the quarter-budget clamp invariant against the reduced budget so
93
+ // short timeouts still don't wrap up on the very first step.
94
+ wrapupLeadMs = Math.min(wrapupLeadMs, Math.floor(turnBudgetMs / 4));
95
+ }
81
96
  const turnDeadline = turnBudgetMs ? turnStartMs + turnBudgetMs : undefined;
82
97
  return { callerTimeoutMs, turnBudgetMs, wrapupLeadMs, turnDeadline };
83
98
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@juspay/neurolink",
3
- "version": "10.4.0",
3
+ "version": "10.4.1",
4
4
  "packageManager": "pnpm@10.15.1",
5
5
  "description": "TypeScript AI SDK with 24+ LLM providers behind one consistent API. MCP-native (connect any MCP server), voice TTS/STT/realtime, RAG, agents, memory, context compaction. OpenAI · Anthropic · Gemini · Bedrock · Azure · Ollama · DeepSeek · NVIDIA NIM and more.",
6
6
  "author": {