@juspay/neurolink 9.88.8 → 9.88.10
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,15 @@
|
|
|
1
|
+
## [9.88.10](https://github.com/juspay/neurolink/compare/v9.88.9...v9.88.10) (2026-07-16)
|
|
2
|
+
|
|
3
|
+
### Bug Fixes
|
|
4
|
+
|
|
5
|
+
- **(message-builder):** image input download + data-URI safety ([746eab5](https://github.com/juspay/neurolink/commit/746eab54cce86a47ceec3049e46e2f51c4ef8547)), closes [#334](https://github.com/juspay/neurolink/issues/334) [#270](https://github.com/juspay/neurolink/issues/270) [#348](https://github.com/juspay/neurolink/issues/348)
|
|
6
|
+
|
|
7
|
+
## [9.88.9](https://github.com/juspay/neurolink/compare/v9.88.8...v9.88.9) (2026-07-15)
|
|
8
|
+
|
|
9
|
+
### Bug Fixes
|
|
10
|
+
|
|
11
|
+
- **(json):** unwrap single-element array wrapper for object schemas ([344ee70](https://github.com/juspay/neurolink/commit/344ee70c645ff52fbf3292bf48de98106b33a325))
|
|
12
|
+
|
|
1
13
|
## [9.88.8](https://github.com/juspay/neurolink/compare/v9.88.7...v9.88.8) (2026-07-15)
|
|
2
14
|
|
|
3
15
|
### Bug Fixes
|
|
@@ -807,7 +807,7 @@ Ensure the final response is fully self-sufficient and does not reference extern
|
|
|
807
807
|
${t}
|
|
808
808
|
]`}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,J=r[e]==="\\";if(J&&(e++,J=!0),GP(r[e])){let K=Ote(r[e])?Ote:Nte(r[e])?Nte:mj(r[e])?mj:Mte,me=e,De=t.length,re='"';for(e++;;){if(e>=r.length){let Pe=I(e-1);return!B&&jP(r.charAt(Pe))?(e=me,t=t.substring(0,De),T(!0)):(re=md(re,'"'),t+=re,!0)}if(e===W)return re=md(re,'"'),t+=re,!0;if(K(r[e])){let Pe=e,fe=re.length;if(re+='"',e++,t+=re,i(!1),B||e>=r.length||jP(r[e])||GP(r[e])||hy(r[e]))return S(),!0;let Ve=I(Pe-1),ge=r.charAt(Ve);if(ge===",")return e=me,t=t.substring(0,De),T(!1,Ve);if(jP(ge))return e=me,t=t.substring(0,De),T(!0);t=t.substring(0,De),e=Pe+1,re=`${re.substring(0,fe)}\\${re.substring(fe)}`}else if(B&&Ite(r[e])){if(r[e-1]===":"&&Rte.test(r.substring(me+1,e+2)))for(;e<r.length&&Ate.test(r[e]);)re+=r[e],e++;return re=md(re,'"'),t+=re,S(),!0}else if(r[e]==="\\"){let Pe=r.charAt(e+1);if(nUt[Pe]!==void 0)re+=r.slice(e,e+2),e+=2;else if(Pe==="u"){let Ve=2;for(;Ve<6&&NOe(r[e+Ve]);)Ve++;Ve===6?(re+=r.slice(e,e+6),e+=6):e+Ve>=r.length?e=r.length:V()}else Pe===`
|
|
809
809
|
`?(re+="\\n",e+=2):(re+=Pe,e+=2)}else{let Pe=r.charAt(e);Pe==='"'&&r[e-1]!=="\\"?(re+=`\\${Pe}`,e++):LOe(Pe)?(re+=rUt[Pe],e++):(DOe(Pe)||F(Pe),re+=Pe,e++)}J&&f()}}return!1}function S(){let B=!1;for(i();r[e]==="+";){B=!0,e++,i(),t=UE(t,'"',!0);let W=t.length;T()?t=$Oe(t,W,1):t=md(t,'"')}return B}function _(){let B=e;if(r[e]==="-"){if(e++,M())return O(B),!0;if(!hy(r[e]))return e=B,!1}for(;hy(r[e]);)e++;if(r[e]==="."){if(e++,M())return O(B),!0;if(!hy(r[e]))return e=B,!1;for(;hy(r[e]);)e++}if(r[e]==="e"||r[e]==="E"){if(e++,(r[e]==="-"||r[e]==="+")&&e++,M())return O(B),!0;if(!hy(r[e]))return e=B,!1;for(;hy(r[e]);)e++}if(!M())return e=B,!1;if(e>B){let W=r.slice(B,e),J=/^0\d/.test(W);return t+=J?`"${W}"`:W,!0}return!1}function C(){return A("true","true")||A("false","false")||A("null","null")||A("True","true")||A("False","false")||A("None","null")}function A(B,W){return r.slice(e,e+B.length)===B?(t+=W,e+=B.length,!0):!1}function P(B){let W=e;if(kte(r[e])){for(;e<r.length&&Cte(r[e]);)e++;let J=e;for(;gy(r,J);)J++;if(r[J]==="(")return e=J+1,s(),r[e]===")"&&(e++,r[e]===";"&&e++),!0}for(;e<r.length&&!Ite(r[e])&&!GP(r[e])&&(!B||r[e]!==":");)e++;if(r[e-1]===":"&&Rte.test(r.substring(W,e+2)))for(;e<r.length&&Ate.test(r[e]);)e++;if(e>W){for(;gy(r,e-1)&&e>0;)e--;let J=r.slice(W,e);return t+=J==="undefined"?"null":JSON.stringify(J),r[e]==='"'&&e++,!0}}function R(){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&&gy(r,W);)W--;return W}function M(){return e>=r.length||jP(r[e])||gy(r,e)}function O(B){t+=`${r.slice(B,e)}0`}function F(B){throw new Wf(`Invalid character ${JSON.stringify(B)}`,e)}function D(){throw new Wf(`Unexpected character ${JSON.stringify(r[e])}`,e)}function G(){throw new Wf("Unexpected end of json string",r.length)}function $(){throw new Wf("Object key expected",e)}function U(){throw new Wf("Colon expected",e)}function V(){let B=r.slice(e,e+6);throw new Wf(`Invalid unicode character "${B}"`,e)}}function oUt(r,e){return r[e]==="*"&&r[e+1]==="/"}var rUt,nUt,jOe=k(()=>{OOe();zOe();rUt={"\b":"\\b","\f":"\\f","\n":"\\n","\r":"\\r"," ":"\\t"},nUt={'"':'"',"\\":"\\","/":"/",b:"\b",f:"\f",n:`
|
|
810
|
-
`,r:"\r",t:" "}});var GOe=k(()=>{jOe()});function Lte(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 VOe=k(()=>{"use strict"});function sUt(r){return typeof r.safeParse=="function"}function iUt(r){try{return{value:JSON.parse(r),repaired:!1}}catch{}try{let e=Dte(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 Ute(r,e=0){if(e>aUt)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=Ute(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=Ute(s,e+1);i.changed&&(t=!0),n[o]=i.value}return{value:t?n:r,changed:t}}return{value:r,changed:!1}}function fj(r,e){if(typeof r!="string"||r.trim().length===0)return null;let t=[],n=0;for(;;){let h=Lte(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=Lte(h,y);if(!x)break;t.push({text:x.span,truncated:!1}),y=x.end}}}catch{}let c,l=[],u=!!(e&&sUt(e)),d=new Set;for(let h of t){if(d.has(h.text))continue;d.add(h.text);let y=iUt(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=Ute(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})}}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 aUt,Fte=k(()=>{"use strict";GOe();H();VOe();aUt=6});function qOe(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 HOe=k(()=>{"use strict"});function lUt(r){if(r===void 0)return"";try{return((typeof r=="string"?r:JSON.stringify(r))??"").substring(0,200)}catch{return"[unserializable]"}}var cUt,VP,WOe=k(()=>{"use strict";Dr();kOe();Vr();H();BP();gp();AOe();uj();fa();pj();Fte();Tm();zI();jv();HOe();cUt=_e.generation;VP=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,i){let a=this.providerName==="google-ai"||this.providerName==="vertex",c=this.providerName==="anthropic"||this.providerName==="bedrock"||this.providerName==="vertex"&&this.modelName?.startsWith("claude-"),u=i&&(!!o.schema||o.output?.format==="json"||o.output?.format==="structured")&&!IOe(this.providerName,this.modelName,s,Object.keys(n).length),d={...n};if(c&&s&&Object.keys(d).length>0){let y=Object.keys(d),x=y[y.length-1];if(x&&d[x]){let b=d[x];d[x]={...b,providerOptions:{...b.providerOptions??{},anthropic:{cacheControl:{type:"ephemeral"}}}}}}let p=o.prepareStep,{system:f,messages:h}=qOe(t);return await Nf({model:e,...f&&{system:f},messages:h,...s&&Object.keys(d).length>0&&{tools:d},stopWhen:$I(o.maxSteps??Gs),...s&&o.toolChoice&&{toolChoice:o.toolChoice},...p&&{experimental_prepareStep:(y=>p({...y,maxSteps:o.maxSteps??Gs}))},temperature:o.temperature,maxOutputTokens:o.maxTokens,maxRetries:0,abortSignal:o.abortSignal,...u&&o.schema&&{experimental_output:b2.object({schema:o.schema})},...o.thinkingConfig?.enabled&&{...c&&o.thinkingConfig.budgetTokens&&!o.thinkingConfig.thinkingLevel&&{experimental_thinking:{type:"enabled",budgetTokens:o.thinkingConfig.budgetTokens}},...a&&{providerOptions:{google:{thinkingConfig:{...o.thinkingConfig.thinkingLevel&&{thinkingLevel:o.thinkingConfig.thinkingLevel},...o.thinkingConfig.budgetTokens&&!o.thinkingConfig.thinkingLevel&&{thinkingBudget:o.thinkingConfig.budgetTokens},includeThoughts:!0}}}}},experimental_telemetry:this.getTelemetryConfigFn(o,"generate"),onStepFinish:({toolCalls:y,toolResults:x})=>{g.info("Tool execution completed",{toolResults:x,toolCalls:y}),fy(this.getEmitterFn?.(),x),this.handleToolStorageFn(y,x,o,new Date).catch(b=>{g.warn("[GenerationHandler] Failed to store tool executions",{provider:this.providerName,error:b instanceof Error?b.message:String(b)})})}})}async executeGeneration(e,t,n,o){return cUt.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",ij(e,this.modelName||"unknown"));let l=o.requestId||o.context?.requestId||"unknown";if(g.info("[GenerationHandler] Calling generateText",{requestId:l,model:ij(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:ij(e),messageCount:t.length,messages:t.map((d,p)=>({index:p,role:d.role,contentLength:typeof d.content=="string"?d.content.length:lUt(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 lj(()=>this.callGenerateText(e,t,n,o,i,!0),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=ns(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:Ie.OK}),d}catch(d){let p=c&&dj(d);if(c&&(d instanceof ma||POe(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 ma?"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 lj(()=>this.callGenerateText(e,t,n,o,i,!1),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=ns(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:Ie.OK}),h}if(MOe(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 lj(()=>this.callGenerateText(e,t,n,{...o,temperature:void 0},i,!0),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=ns(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:Ie.OK}),h}throw s.setStatus({code:Ie.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=Tte(n),s=Ste(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=x=>{let b=x.replace(/^```(?:json)?\s*\n?/i,"").replace(/\n?```\s*$/i,"").trim(),T=fj(b,s.schema);if(T)return c=T.structuredData,T.repaired&&(l=!0),T.truncated&&(u=!0),T.content;try{let S=JSON.parse(b);if(S==="")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(S!=null)return c=S,b}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}),b};if(i)try{let x=e.experimental_output,b=typeof x=="string"&&x===(e.text??"");x!==void 0&&!b?(c=x,a=JSON.stringify(x)):a=d(e.text||"")}catch(x){g.debug("[GenerationHandler] experimental_output threw, falling back to text parsing",{error:x instanceof Error?x.message:String(x)}),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=LE(e.usage);if(p.cacheCreationTokens===void 0||p.cacheReadTokens===void 0){let x=this.extractCacheMetricsFromProviderMetadata(e);if(p.cacheCreationTokens===void 0&&x.cacheCreationTokens!==void 0&&(p.cacheCreationTokens=x.cacheCreationTokens),p.cacheReadTokens===void 0&&x.cacheReadTokens!==void 0&&(p.cacheReadTokens=x.cacheReadTokens),p.cacheReadTokens!==void 0){let b=wte(p.cacheReadTokens,p.input);b!==void 0&&(p.cacheSavingsPercent=b)}}let f=e.reasoning,h=f?typeof f=="string"?f:Array.isArray(f)?f.map(x=>typeof x=="string"?x:x.text??JSON.stringify(x)).join(`
|
|
810
|
+
`,r:"\r",t:" "}});var GOe=k(()=>{jOe()});function Lte(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 VOe=k(()=>{"use strict"});function sUt(r){return typeof r.safeParse=="function"}function iUt(r){try{return{value:JSON.parse(r),repaired:!1}}catch{}try{let e=Dte(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 Ute(r,e=0){if(e>aUt)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=Ute(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=Ute(s,e+1);i.changed&&(t=!0),n[o]=i.value}return{value:t?n:r,changed:t}}return{value:r,changed:!1}}function fj(r,e){if(typeof r!="string"||r.trim().length===0)return null;let t=[],n=0;for(;;){let h=Lte(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=Lte(h,y);if(!x)break;t.push({text:x.span,truncated:!1}),y=x.end}}}catch{}let c,l=[],u=!!(e&&sUt(e)),d=new Set;for(let h of t){if(d.has(h.text))continue;d.add(h.text);let y=iUt(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=Ute(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 aUt,Fte=k(()=>{"use strict";GOe();H();VOe();aUt=6});function qOe(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 HOe=k(()=>{"use strict"});function lUt(r){if(r===void 0)return"";try{return((typeof r=="string"?r:JSON.stringify(r))??"").substring(0,200)}catch{return"[unserializable]"}}var cUt,VP,WOe=k(()=>{"use strict";Dr();kOe();Vr();H();BP();gp();AOe();uj();fa();pj();Fte();Tm();zI();jv();HOe();cUt=_e.generation;VP=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,i){let a=this.providerName==="google-ai"||this.providerName==="vertex",c=this.providerName==="anthropic"||this.providerName==="bedrock"||this.providerName==="vertex"&&this.modelName?.startsWith("claude-"),u=i&&(!!o.schema||o.output?.format==="json"||o.output?.format==="structured")&&!IOe(this.providerName,this.modelName,s,Object.keys(n).length),d={...n};if(c&&s&&Object.keys(d).length>0){let y=Object.keys(d),x=y[y.length-1];if(x&&d[x]){let b=d[x];d[x]={...b,providerOptions:{...b.providerOptions??{},anthropic:{cacheControl:{type:"ephemeral"}}}}}}let p=o.prepareStep,{system:f,messages:h}=qOe(t);return await Nf({model:e,...f&&{system:f},messages:h,...s&&Object.keys(d).length>0&&{tools:d},stopWhen:$I(o.maxSteps??Gs),...s&&o.toolChoice&&{toolChoice:o.toolChoice},...p&&{experimental_prepareStep:(y=>p({...y,maxSteps:o.maxSteps??Gs}))},temperature:o.temperature,maxOutputTokens:o.maxTokens,maxRetries:0,abortSignal:o.abortSignal,...u&&o.schema&&{experimental_output:b2.object({schema:o.schema})},...o.thinkingConfig?.enabled&&{...c&&o.thinkingConfig.budgetTokens&&!o.thinkingConfig.thinkingLevel&&{experimental_thinking:{type:"enabled",budgetTokens:o.thinkingConfig.budgetTokens}},...a&&{providerOptions:{google:{thinkingConfig:{...o.thinkingConfig.thinkingLevel&&{thinkingLevel:o.thinkingConfig.thinkingLevel},...o.thinkingConfig.budgetTokens&&!o.thinkingConfig.thinkingLevel&&{thinkingBudget:o.thinkingConfig.budgetTokens},includeThoughts:!0}}}}},experimental_telemetry:this.getTelemetryConfigFn(o,"generate"),onStepFinish:({toolCalls:y,toolResults:x})=>{g.info("Tool execution completed",{toolResults:x,toolCalls:y}),fy(this.getEmitterFn?.(),x),this.handleToolStorageFn(y,x,o,new Date).catch(b=>{g.warn("[GenerationHandler] Failed to store tool executions",{provider:this.providerName,error:b instanceof Error?b.message:String(b)})})}})}async executeGeneration(e,t,n,o){return cUt.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",ij(e,this.modelName||"unknown"));let l=o.requestId||o.context?.requestId||"unknown";if(g.info("[GenerationHandler] Calling generateText",{requestId:l,model:ij(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:ij(e),messageCount:t.length,messages:t.map((d,p)=>({index:p,role:d.role,contentLength:typeof d.content=="string"?d.content.length:lUt(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 lj(()=>this.callGenerateText(e,t,n,o,i,!0),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=ns(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:Ie.OK}),d}catch(d){let p=c&&dj(d);if(c&&(d instanceof ma||POe(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 ma?"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 lj(()=>this.callGenerateText(e,t,n,o,i,!1),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=ns(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:Ie.OK}),h}if(MOe(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 lj(()=>this.callGenerateText(e,t,n,{...o,temperature:void 0},i,!0),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=ns(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:Ie.OK}),h}throw s.setStatus({code:Ie.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=Tte(n),s=Ste(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=x=>{let b=x.replace(/^```(?:json)?\s*\n?/i,"").replace(/\n?```\s*$/i,"").trim(),T=fj(b,s.schema);if(T)return c=T.structuredData,T.repaired&&(l=!0),T.truncated&&(u=!0),T.content;try{let S=JSON.parse(b);if(S==="")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(S!=null)return c=S,b}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}),b};if(i)try{let x=e.experimental_output,b=typeof x=="string"&&x===(e.text??"");x!==void 0&&!b?(c=x,a=JSON.stringify(x)):a=d(e.text||"")}catch(x){g.debug("[GenerationHandler] experimental_output threw, falling back to text parsing",{error:x instanceof Error?x.message:String(x)}),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=LE(e.usage);if(p.cacheCreationTokens===void 0||p.cacheReadTokens===void 0){let x=this.extractCacheMetricsFromProviderMetadata(e);if(p.cacheCreationTokens===void 0&&x.cacheCreationTokens!==void 0&&(p.cacheCreationTokens=x.cacheCreationTokens),p.cacheReadTokens===void 0&&x.cacheReadTokens!==void 0&&(p.cacheReadTokens=x.cacheReadTokens),p.cacheReadTokens!==void 0){let b=wte(p.cacheReadTokens,p.input);b!==void 0&&(p.cacheSavingsPercent=b)}}let f=e.reasoning,h=f?typeof f=="string"?f:Array.isArray(f)?f.map(x=>typeof x=="string"?x:x.text??JSON.stringify(x)).join(`
|
|
811
811
|
`):String(f):void 0,y=p.reasoning??void 0;return{content:a,structuredData:c,usage:p,finishReason:e.finishReason,jsonRepaired:l||void 0,jsonTruncated:u||void 0,provider:this.providerName,model:this.modelName,reasoning:h,reasoningTokens:y,toolCalls:e.toolCalls?e.toolCalls.map(x=>({toolCallId:x.toolCallId||"unknown",toolName:x.toolName||"unknown",args:x.args||{}})):[],toolResults:e.toolResults??[],toolsUsed:n,toolExecutions:o,availableTools:Object.keys(t).map(x=>{let b=t[x];return{name:x,description:b.description||"No description available",parameters:b.inputSchema||{},server:b.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 zte={};te(zte,{Agent:()=>Bte,BedrockClient:()=>dUt,BedrockRuntimeClient:()=>mUt,Blob:()=>JUt,Client:()=>XUt,ConverseCommand:()=>fUt,ConverseStreamCommand:()=>gUt,Cron:()=>MUt,Dispatcher:()=>ZUt,File:()=>KUt,FlowProducer:()=>PUt,FormData:()=>WUt,GoogleAuth:()=>bUt,HTTPException:()=>$Ut,Headers:()=>HUt,Hippocampus:()=>EUt,HippocampusConfig:()=>_Ut,Hono:()=>UUt,ImageFormat:()=>hUt,InvokeEndpointCommand:()=>xUt,InvokeEndpointWithResponseStreamCommand:()=>vUt,Job:()=>AUt,ListFoundationModelsCommand:()=>pUt,MockAgent:()=>eFt,Pool:()=>YUt,Queue:()=>CUt,QueueScheduler:()=>IUt,Request:()=>VUt,Response:()=>qUt,SageMakerRuntimeClient:()=>yUt,TextToSpeechClient:()=>SUt,VertexAI:()=>TUt,Webhook:()=>wUt,Worker:()=>RUt,convertToHtml:()=>LUt,cors:()=>FUt,createClient:()=>kUt,default:()=>uUt,extractRawText:()=>DUt,fetch:()=>$te,getGlobalDispatcher:()=>$E,interceptors:()=>BE,logger:()=>BUt,parseBuffer:()=>OUt,request:()=>zE,secureHeaders:()=>zUt,selectCover:()=>NUt,setGlobalDispatcher:()=>QUt,streamSSE:()=>jUt,timeout:()=>GUt});var FE,Si,uUt,dUt,pUt,mUt,fUt,gUt,hUt,yUt,xUt,vUt,bUt,TUt,SUt,wUt,EUt,_Ut,kUt,CUt,RUt,AUt,IUt,PUt,MUt,OUt,NUt,DUt,LUt,UUt,FUt,$Ut,BUt,zUt,jUt,GUt,$te,VUt,qUt,HUt,WUt,KUt,JUt,Bte,YUt,XUt,ZUt,QUt,$E,eFt,BE,zE,jE=k(()=>{FE={get(r,e){return e==="__esModule"?!0:e==="default"?new Proxy({},{get:FE.get}):new Proxy(function(...t){return new Proxy({},{get:FE.get})},{get:FE.get,apply(t,n,o){return new Proxy({},{get:FE.get})},construct(t,n){return new Proxy({},{get:FE.get})}})}},Si=new Proxy({},FE),uUt=Si,{BedrockClient:dUt,ListFoundationModelsCommand:pUt,BedrockRuntimeClient:mUt,ConverseCommand:fUt,ConverseStreamCommand:gUt,ImageFormat:hUt}=Si,{SageMakerRuntimeClient:yUt,InvokeEndpointCommand:xUt,InvokeEndpointWithResponseStreamCommand:vUt}=Si,{GoogleAuth:bUt,VertexAI:TUt,TextToSpeechClient:SUt}=Si,{Webhook:wUt}=Si,{Hippocampus:EUt,HippocampusConfig:_Ut}=Si,{createClient:kUt}=Si,{Queue:CUt,Worker:RUt,Job:AUt,QueueScheduler:IUt,FlowProducer:PUt}=Si,{Cron:MUt}=Si,{parseBuffer:OUt,selectCover:NUt}=Si,{extractRawText:DUt,convertToHtml:LUt}=Si,{Hono:UUt}=Si,{cors:FUt,HTTPException:$Ut,logger:BUt,secureHeaders:zUt,streamSSE:jUt,timeout:GUt}=Si,$te=globalThis.fetch,VUt=globalThis.Request,qUt=globalThis.Response,HUt=globalThis.Headers,WUt=globalThis.FormData,KUt=globalThis.File,JUt=globalThis.Blob,Bte=Si.Agent,YUt=Si.Pool,XUt=Si.Client,ZUt=Si.Dispatcher,QUt=()=>{},$E=()=>Si,eFt=Si.MockAgent,BE={redirect:()=>r=>r,retry:()=>r=>r},zE=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 tFt,jte,KOe,JOe=k(()=>{"use strict";H();It();tFt={maxTokens:10,refillIntervalMs:1e3,tokensPerRefill:10,maxQueueSize:100,queueTimeoutMs:3e4},jte=class{tokens;config;queue=[];refillTimer=null;lastRefillTime;constructor(e={}){this.config={...tFt,...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()}},KOe=new jte({maxTokens:10,refillIntervalMs:1e3,tokensPerRefill:10,maxQueueSize:100,queueTimeoutMs:3e4})});function YOe(r,e=ml.DEFAULT_INITIAL_DELAY,t=ml.DEFAULT_BACKOFF_MULTIPLIER,n=ml.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 XOe(r){return new Promise(e=>setTimeout(e,r))}var Gte,Vte,k0n,qte,Hte,Wte,C0n,R0n,A0n,ZOe=k(()=>{"use strict";H();fa();Gte=class extends Error{constructor(t,n){super(t);this.cause=n;this.name="NetworkError"}cause},Vte=class extends Error{constructor(t,n){super(t);this.cause=n;this.name="TemporaryError"}cause},k0n={maxAttempts:ml.DEFAULT_RETRY_ATTEMPTS,initialDelay:ml.DEFAULT_INITIAL_DELAY,maxDelay:ml.DEFAULT_MAX_DELAY,backoffMultiplier:ml.DEFAULT_BACKOFF_MULTIPLIER,retryCondition:r=>{if(r instanceof Gte||r instanceof Vte||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}`)}};qte=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"}},Hte=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 XOe(n),this.acquire()}this.requests.push(e)}},Wte=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),XOe(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)}`)}}},C0n=new Wte,R0n=new qte(3,3e4),A0n=new Hte(100,6e4)});var qP={};te(qP,{AsyncLocalStorage:()=>vFt,Buffer:()=>d2t,Channel:()=>e2t,DatabaseSync:()=>u2t,Duplex:()=>TFt,EventEmitter:()=>xFt,Http2ServerRequest:()=>h2t,Http2ServerResponse:()=>y2t,Interface:()=>l2t,MIMEType:()=>w2t,PassThrough:()=>SFt,PerformanceObserver:()=>X$t,Readable:()=>QOe,ReadableStream:()=>wFt,Resolver:()=>J$t,TextDecoder:()=>rNe,TextEncoder:()=>gj,Transform:()=>bFt,URL:()=>L$t,URLSearchParams:()=>U$t,Worker:()=>o2t,Writable:()=>eNe,access:()=>XFt,appendFile:()=>IFt,appendFileSync:()=>sFt,arch:()=>g$t,arrayBuffer:()=>x2t,basename:()=>dFt,builtinModules:()=>M$t,callbackify:()=>V$t,channel:()=>Q$t,chmodSync:()=>AFt,clearInterval:()=>S2t,clearTimeout:()=>b2t,closeSync:()=>NFt,connect:()=>v$t,constants:()=>p2t,copyFileSync:()=>MFt,cpSync:()=>iFt,cpus:()=>d$t,createConnection:()=>b$t,createGunzip:()=>C$t,createGzip:()=>R$t,createHash:()=>Bc,createHmac:()=>Kte,createInterface:()=>c2t,createReadStream:()=>VFt,createRequire:()=>P$t,createServer:()=>aFt,createWriteStream:()=>GFt,debug:()=>j$t,debuglog:()=>tNe,default:()=>rFt,deflateSync:()=>S$t,deprecate:()=>G$t,deserialize:()=>n2t,dirname:()=>uFt,exec:()=>n$t,execFile:()=>s$t,execFileSync:()=>i$t,execSync:()=>o$t,existsSync:()=>kFt,extname:()=>pFt,fileURLToPath:()=>F$t,finished:()=>_Ft,format:()=>D$t,freemem:()=>p$t,fstatSync:()=>DFt,get:()=>x$t,gunzip:()=>k$t,gunzipSync:()=>w$t,gzip:()=>_$t,gzipSync:()=>E$t,hasSubscribers:()=>t2t,homedir:()=>c$t,hostname:()=>u$t,inflateSync:()=>T$t,inherits:()=>B$t,inspect:()=>hj,isAbsolute:()=>fFt,isBuiltin:()=>O$t,isDeepStrictEqual:()=>q$t,isIP:()=>g2t,isIPv4:()=>f2t,isIPv6:()=>m2t,isMainThread:()=>s2t,join:()=>cFt,lookup:()=>K$t,mkdir:()=>WFt,mkdirSync:()=>LFt,monitorEventLoopDelay:()=>Z$t,normalize:()=>yFt,ok:()=>A$t,open:()=>e$t,openSync:()=>OFt,parentPort:()=>i2t,parse:()=>N$t,pathToFileURL:()=>$$t,performance:()=>Y$t,pipeline:()=>EFt,platform:()=>a$t,posix:()=>hFt,promises:()=>nFt,promisify:()=>z$t,randomBytes:()=>Sm,randomUUID:()=>We,readFile:()=>qFt,readFileSync:()=>CFt,readdir:()=>JFt,readdirSync:()=>FFt,realpath:()=>t$t,realpathSync:()=>PFt,relative:()=>mFt,release:()=>h$t,rename:()=>ZFt,renameSync:()=>BFt,request:()=>y$t,resolve:()=>lFt,rm:()=>QFt,rmSync:()=>jFt,rmdirSync:()=>zFt,sep:()=>gFt,serialize:()=>r2t,setInterval:()=>T2t,setTimeout:()=>v2t,spawn:()=>r$t,stat:()=>KFt,statSync:()=>UFt,strict:()=>I$t,tmpdir:()=>l$t,toUSVString:()=>H$t,totalmem:()=>m$t,type:()=>f$t,types:()=>W$t,unlink:()=>YFt,unlinkSync:()=>$Ft,webcrypto:()=>oFt,workerData:()=>a2t,writeFile:()=>HFt,writeFileSync:()=>RFt});var ws,Uo,rFt,nFt,Bc,Kte,Sm,We,oFt,sFt,iFt,aFt,cFt,lFt,uFt,dFt,pFt,mFt,fFt,gFt,hFt,yFt,xFt,vFt,QOe,eNe,bFt,TFt,SFt,wFt,EFt,_Ft,kFt,CFt,RFt,AFt,IFt,PFt,MFt,OFt,NFt,DFt,LFt,UFt,FFt,$Ft,BFt,zFt,jFt,GFt,VFt,qFt,HFt,WFt,KFt,JFt,YFt,XFt,ZFt,QFt,e$t,t$t,r$t,n$t,o$t,s$t,i$t,a$t,c$t,l$t,u$t,d$t,p$t,m$t,f$t,g$t,h$t,y$t,x$t,v$t,b$t,T$t,S$t,w$t,E$t,_$t,k$t,C$t,R$t,A$t,I$t,P$t,M$t,O$t,N$t,D$t,L$t,U$t,F$t,$$t,B$t,z$t,tNe,j$t,hj,G$t,V$t,q$t,H$t,W$t,rNe,gj,K$t,J$t,Y$t,X$t,Z$t,Q$t,e2t,t2t,r2t,n2t,o2t,s2t,i2t,a2t,c2t,l2t,u2t,d2t,p2t,m2t,f2t,g2t,h2t,y2t,x2t,nNe,v2t,b2t,T2t,S2t,w2t,vr=k(()=>{ws=()=>{},Uo=async()=>{},rFt={},nFt={readFile:Uo,writeFile:Uo,mkdir:Uo,stat:Uo,readdir:Uo,unlink:Uo,access:Uo,rm:Uo,rename:Uo},Bc=r=>{let e=[];return{update(t){return e.push(typeof t=="string"?new gj().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}}},Kte=(r,e)=>Bc(r),Sm=r=>new Uint8Array(r||32),We=()=>globalThis.crypto?.randomUUID?.()||Math.random().toString(36),oFt=globalThis.crypto,sFt=()=>{throw new Error("[NeuroLink:browser] fs.appendFileSync is not supported in browser runtime \u2014 use server-side execution")},iFt=()=>{throw new Error("[NeuroLink:browser] fs.cpSync is not supported in browser runtime \u2014 use server-side execution")},aFt=()=>({listen:ws,close:ws,on:ws}),cFt=(...r)=>r.join("/"),lFt=(...r)=>r.join("/"),uFt=r=>r||"",dFt=r=>r?.split?.("/")?.pop?.()||"",pFt=r=>{let e=r?.match?.(/\.[^.]+$/);return e?e[0]:""},mFt=(r,e)=>e||"",fFt=()=>!1,gFt="/",hFt={normalize:r=>r,join:(...r)=>r.join("/"),resolve:(...r)=>r.join("/"),sep:"/"},yFt=r=>r,xFt=class{on(){return this}off(){return this}emit(){return this}once(){return this}removeListener(){return this}addListener(){return this}},vFt=class{getStore(){}run(r,e,...t){return e(...t)}enterWith(){}disable(){}},QOe=class{pipe(){return this}on(){return this}read(){return null}push(){}destroy(){}},eNe=class{write(){return!0}end(){}on(){return this}destroy(){}},bFt=class{push(){}on(){return this}},TFt=class{on(){return this}},SFt=class{pipe(){return this}on(){return this}},wFt=globalThis.ReadableStream||class{},EFt=ws,_Ft=ws,kFt=()=>!1,CFt=()=>"",RFt=ws,AFt=ws,IFt=Uo,PFt=r=>r,MFt=ws,OFt=()=>0,NFt=ws,DFt=()=>({}),LFt=ws,UFt=()=>({}),FFt=()=>[],$Ft=ws,BFt=ws,zFt=ws,jFt=ws,GFt=()=>new eNe,VFt=()=>new QOe,qFt=Uo,HFt=Uo,WFt=Uo,KFt=Uo,JFt=Uo,YFt=Uo,XFt=Uo,ZFt=Uo,QFt=Uo,e$t=async()=>({stat:Uo,readFile:Uo,close:Uo,read:Uo,write:Uo}),t$t=async r=>r,r$t=()=>({on:ws,stdout:{on:ws},stderr:{on:ws},kill:ws}),n$t=(r,e)=>e?.(null,"",""),o$t=()=>"",s$t=(r,e,t)=>{typeof e=="function"?e(null,"",""):t?.(null,"","")},i$t=()=>"",a$t="browser",c$t=()=>"/",l$t=()=>"/tmp",u$t=()=>"browser",d$t=()=>[{}],p$t=()=>0,m$t=()=>0,f$t=()=>"Browser",g$t=()=>"wasm",h$t=()=>"0",y$t=()=>({}),x$t=()=>({}),v$t=()=>({}),b$t=()=>({}),T$t=()=>new Uint8Array,S$t=()=>new Uint8Array,w$t=()=>new Uint8Array,E$t=()=>new Uint8Array,_$t=(r,e)=>e?.(null,r),k$t=(r,e)=>e?.(null,r),C$t=()=>({}),R$t=()=>({}),A$t=ws,I$t={},P$t=()=>()=>({}),M$t=[],O$t=()=>!1,N$t=r=>({pathname:r||"",hostname:"",protocol:"",search:"",hash:""}),D$t=()=>"",L$t=globalThis.URL,U$t=globalThis.URLSearchParams,F$t=r=>typeof r=="string"?r.replace("file://",""):r,$$t=r=>new globalThis.URL("file://"+r),B$t=(r,e)=>{e&&(r.super_=e,Object.setPrototypeOf(r.prototype,e.prototype))},z$t=r=>(...e)=>new Promise((t,n)=>r(...e,(o,s)=>o?n(o):t(s))),tNe=r=>{let e=(...t)=>{};return e.enabled=!1,e},j$t=tNe,hj=r=>{try{return JSON.stringify(r,null,2)}catch{return String(r)}};hj.custom=Symbol.for("nodejs.util.inspect.custom");hj.colors={};hj.styles={};G$t=r=>r,V$t=r=>(...e)=>{let t=e.pop();r(...e).then(n=>t(null,n)).catch(t)},q$t=(r,e)=>JSON.stringify(r)===JSON.stringify(e),H$t=r=>String(r),W$t={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},rNe=globalThis.TextDecoder,gj=globalThis.TextEncoder,K$t=(r,e)=>e?.(null,"127.0.0.1",4),J$t=class{},Y$t=globalThis.performance||{now:()=>Date.now()},X$t=class{observe(){}disconnect(){}},Z$t=()=>({enable:ws,disable:ws,percentile:()=>0}),Q$t=()=>({}),e2t=class{},t2t=()=>!1,r2t=()=>new Uint8Array,n2t=ws,o2t=class{},s2t=!0,i2t=null,a2t=null,c2t=()=>({}),l2t=class{},u2t=class{},d2t=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 gj().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 gj().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 rNe().decode(this)}},p2t={F_OK:0,R_OK:4,W_OK:2,X_OK:1},m2t=()=>!1,f2t=()=>!1,g2t=()=>0,h2t=class{},y2t=class{},x2t=async()=>new ArrayBuffer(0),nNe=r=>({[Symbol.toPrimitive](){return r},ref(){return this},unref(){return this},hasRef(){return!1},refresh(){return this},close(){}}),v2t=(...r)=>nNe(globalThis.setTimeout(...r)),b2t=globalThis.clearTimeout,T2t=(...r)=>nNe(globalThis.setInterval(...r)),S2t=globalThis.clearInterval,w2t=class{constructor(r){this.type=r}toString(){return this.type}}});function oNe(r){return Jte||(Jte=new Yte(r)),Jte}var Yte,Jte,sNe=k(()=>{"use strict";vr();H();Yte=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){try{let t=new URL(e);return["utm_source","utm_medium","utm_campaign","utm_term","utm_content","fbclid","gclid","_ga"].forEach(o=>t.searchParams.delete(o)),t.toString()}catch{return e}}generateContentHash(e){let t=typeof e=="string"?Buffer.from(e,"base64"):e;return Bc("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:t.substring(0,50)}),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:t.substring(0,50),accessCount:n.accessCount}),n):(this.stats.misses++,g.debug("Image cache miss",{url:t.substring(0,50)}),null)}getByContentHash(e){let t=this.contentHashIndex.get(e);return t?this.get(t):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:s.substring(0,50),size:i,maxSize:this.maxImageSize});return}let a=this.generateContentHash(o),c=this.contentHashIndex.get(a);if(c&&c!==s){let d=this.cache.get(c);if(d&&!this.isExpired(d)){this.cache.set(s,{...d}),this.contentHashIndex.set(a,s),g.debug("Image cache dedup hit",{newUrl:s.substring(0,50),existingUrl:c.substring(0,50)});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),this.contentHashIndex.set(a,s),g.debug("Image cached",{url:s.substring(0,50),size:i,contentHash:a.substring(0,8),cacheSize:this.cache.size})}delete(e){let t=this.normalizeUrl(e),n=this.cache.get(t);return n?(this.contentHashIndex.get(n.contentHash)===t&&this.contentHashIndex.delete(n.contentHash),this.cache.delete(t),!0):!1}evictOldest(){let e=this.cache.keys().next().value;if(e!==void 0){let t=this.cache.get(e);t&&this.contentHashIndex.get(t.contentHash)===e&&this.contentHashIndex.delete(t.contentHash),this.cache.delete(e),this.stats.evictions++,g.debug("Image cache eviction",{url:String(e).substring(0,50)})}}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}}},Jte=null});var GE,E2t,Q0n,Xte=k(()=>{"use strict";H();GE=class r{static async process(e,t){if(e.length===0)throw g.error("Empty buffer provided"),new Error("Invalid image processing: buffer is empty");let n=this.detectImageType(e),o=e.toString("base64"),s=`data:${n};base64,${o}`;return this.validateProcessOutput(s,o,n),{type:"image",content:s,mimeType:n,metadata:{confidence:100,size:e.length}}}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,${e.toString("base64")}`}catch(t){throw 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=e.toString("base64");return{mimeType:n,data:t}}catch(t){throw 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=e.toString("base64");return{mediaType:n,data:t}}catch(t){throw 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 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.subarray(4,8).toString(),o=e.subarray(8,12).toString();if(n==="ftyp"&&o==="avif")return"image/avif"}}return"image/jpeg"}catch(t){return g.warn("Failed to detect image type, using default:",t),"image/jpeg"}}static validateImageSize(e,t=10*1024*1024){try{return(typeof e=="string"?Buffer.byteLength(e,"base64"):e.length)<=t}catch(n){return g.warn("Failed to validate image size:",n),!1}}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{let o=r.detectImageType(e),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=e.toString("base64"),a="base64"}return{data:i,mediaType:o,size:s,format:a}}catch(o){throw g.error(`Failed to process image for ${t}:`,o),new Error(`Image processing failed: ${o instanceof Error?o.message:"Unknown error"}`,{cause:o})}}},E2t=["jpg","jpeg","png","gif","webp","bmp","tiff","tif","svg","avif","ico","heic","heif"],Q0n=new Set(E2t)});function k2t(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 yy,HP,_2t,Zte,VE,iNe=k(()=>{"use strict";Xte();H();yy=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))}},HP={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},_2t=new Set(["litellm","openrouter"]);Zte={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:[]},VE=class{static validateImageCount(e,t,n){let o=t.toLowerCase(),s;if(o==="vertex"&&n)n.includes("claude")?s=HP.vertex.claude:n.includes("gemini")?s=HP.vertex.gemini:s=HP.vertex.default;else{let a=o in HP?HP[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:GE.detectImageType(s)})}),n}static supportsVision(e,t){try{let n=k2t(e),o=Zte[n];if(!o||o.length===0)return!1;if(!t)return!0;let s=o.some(i=>t.toLowerCase().includes(i.toLowerCase()));return!s&&_2t.has(n)?!0:s}catch{return!1}}static getSupportedModels(e){let t=e.toLowerCase(),n=Zte[t];return n?[...n]:[]}static getVisionProviders(){return Object.entries(Zte).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 aNe(){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 Qte,ere,tre=k(()=>{"use strict";Qte=`
|
|
812
812
|
|
|
813
813
|
IMPORTANT: You are continuing an ongoing conversation. The previous messages in this conversation contain important context including:
|
|
@@ -1101,7 +1101,7 @@ IMPORTANT FILE HANDLING INSTRUCTIONS:
|
|
|
1101
1101
|
- DO NOT use GitHub tools (get_file_contents, search_code, etc.) for local files - they only work for remote repository files
|
|
1102
1102
|
- Analyze the provided file content directly without attempting to fetch or read files using tools
|
|
1103
1103
|
- GitHub MCP tools are ONLY for remote repository operations, not local filesystem access
|
|
1104
|
-
- Use the file content shown in this message for your analysis`}return t}async function J_(r,e,t){r.input||(r.input={});let n=r.input,o=Ty.getProviderConfig(e),s=o?o.maxSizeMB*1024*1024:10*1024*1024;eQt(r,e,t),await iO(r,s,e),await rQt(r),nQt(r,e,t);let i=await oQt(r,s,e),a=n.images&&n.images.length>0||n.content&&n.content.some(p=>p.type==="image"),c=i.length>0;if(!a&&!c)return n.csvFiles&&(n.csvFiles=[]),n.pdfFiles&&(n.pdfFiles=[]),n.files&&(n.files=[]),(await t4(r)).map(f=>{let h=f.providerOptions;return{role:f.role,content:f.content,...h&&{providerOptions:h}}});if(!VE.supportsVision(e,t))throw new Error(`Provider ${e} with model ${t} does not support vision processing. Supported providers: ${VE.getVisionProviders().join(", ")}`);let l=[],u=sQt(r,i.length>0);if(u.trim()&&l.push({role:"system",content:u.trim(),providerOptions:{anthropic:{cacheControl:{type:"ephemeral"}}}}),r.conversationHistory&&r.conversationHistory.length>0&&r.conversationHistory){for(let p of r.conversationHistory)if(p.role==="user"||p.role==="assistant"||p.role==="system"){let f=p.providerOptions,h=p.content;if(p.role==="assistant"&&Array.isArray(p.content)){let y=p.content.filter(b=>!!b&&typeof b=="object"&&b.type==="text"&&typeof b.text=="string");if(y.length===0)continue;y.some(b=>!!b.providerOptions)?h=y:h=y.length===1?y[0].text:y.map(b=>b.text).join(" ")}if(h==="")continue;l.push({role:p.role,content:h,...f&&{providerOptions:f}})}}try{let p;n.content&&n.content.length>0?p=await iQt(n.content,e,t):n.images&&n.images.length>0||i.length>0?p=await fUe(n.text??"",n.images||[],i,e,t):p=n.text,typeof p=="string"?l.push({role:"user",content:p}):l.push({role:"user",content:p});let f=r.context?.requestId;return pUe(l,f),l}catch(p){throw yy.logError("MULTIMODAL_BUILD",p,{provider:e,model:t,hasImages:a,imageCount:n.images?.length||0}),p}}async function iQt(r,e,t){let n=r.find(u=>u.type==="text"),o=r.filter(u=>u.type==="image"),s=r.filter(u=>u.type==="pdf"),i=n?.text||"";if(!(o.length>0||s.length>0)&&!i)throw new Error("Content must include either text or multimodal content");if(o.length===0&&s.length===0)return i;let c=o.map(u=>u.data),l=s.map(u=>({buffer:typeof u.data=="string"?Buffer.from(u.data,"base64"):u.data,filename:u.metadata?.filename||"document.pdf",pageCount:u.metadata?.pages??null}));return await fUe(i,c,l,e,t)}function mUe(r){
|
|
1104
|
+
- Use the file content shown in this message for your analysis`}return t}async function J_(r,e,t){r.input||(r.input={});let n=r.input,o=Ty.getProviderConfig(e),s=o?o.maxSizeMB*1024*1024:10*1024*1024;eQt(r,e,t),await iO(r,s,e),await rQt(r),nQt(r,e,t);let i=await oQt(r,s,e),a=n.images&&n.images.length>0||n.content&&n.content.some(p=>p.type==="image"),c=i.length>0;if(!a&&!c)return n.csvFiles&&(n.csvFiles=[]),n.pdfFiles&&(n.pdfFiles=[]),n.files&&(n.files=[]),(await t4(r)).map(f=>{let h=f.providerOptions;return{role:f.role,content:f.content,...h&&{providerOptions:h}}});if(!VE.supportsVision(e,t))throw new Error(`Provider ${e} with model ${t} does not support vision processing. Supported providers: ${VE.getVisionProviders().join(", ")}`);let l=[],u=sQt(r,i.length>0);if(u.trim()&&l.push({role:"system",content:u.trim(),providerOptions:{anthropic:{cacheControl:{type:"ephemeral"}}}}),r.conversationHistory&&r.conversationHistory.length>0&&r.conversationHistory){for(let p of r.conversationHistory)if(p.role==="user"||p.role==="assistant"||p.role==="system"){let f=p.providerOptions,h=p.content;if(p.role==="assistant"&&Array.isArray(p.content)){let y=p.content.filter(b=>!!b&&typeof b=="object"&&b.type==="text"&&typeof b.text=="string");if(y.length===0)continue;y.some(b=>!!b.providerOptions)?h=y:h=y.length===1?y[0].text:y.map(b=>b.text).join(" ")}if(h==="")continue;l.push({role:p.role,content:h,...f&&{providerOptions:f}})}}try{let p;n.content&&n.content.length>0?p=await iQt(n.content,e,t):n.images&&n.images.length>0||i.length>0?p=await fUe(n.text??"",n.images||[],i,e,t):p=n.text,typeof p=="string"?l.push({role:"user",content:p}):l.push({role:"user",content:p});let f=r.context?.requestId;return pUe(l,f),l}catch(p){throw yy.logError("MULTIMODAL_BUILD",p,{provider:e,model:t,hasImages:a,imageCount:n.images?.length||0}),p}}async function iQt(r,e,t){let n=r.find(u=>u.type==="text"),o=r.filter(u=>u.type==="image"),s=r.filter(u=>u.type==="pdf"),i=n?.text||"";if(!(o.length>0||s.length>0)&&!i)throw new Error("Content must include either text or multimodal content");if(o.length===0&&s.length===0)return i;let c=o.map(u=>u.data),l=s.map(u=>({buffer:typeof u.data=="string"?Buffer.from(u.data,"base64"):u.data,filename:u.metadata?.filename||"document.pdf",pageCount:u.metadata?.pages??null}));return await fUe(i,c,l,e,t)}function mUe(r){let e=r.toLowerCase();return e.startsWith("http://")||e.startsWith("https://")}async function aQt(r){let e=oNe(),t=e.get(r);if(t)return g.debug("Using cached image for URL",{url:r.substring(0,50)}),t.dataUri;await KOe.acquire();try{let n=await zE(r,{dispatcher:$E().compose(BE.redirect({maxRedirections:5})),method:"GET",headersTimeout:1e4,bodyTimeout:3e4});if(n.statusCode!==200)throw new Error(`HTTP ${n.statusCode}: Failed to download image from ${r}`);let o=n.headers["content-type"]||"image/jpeg";if(!o.startsWith("image/"))throw new Error(`URL does not point to an image. Content-Type: ${o}`);let s=10*1024*1024,i=[],a=0;for await(let d of n.body){if(a+=d.length,a>s)throw new Error(`Image too large: exceeds ${s} bytes while downloading from ${r}`);i.push(d)}let c=Buffer.concat(i),l=c.toString("base64"),u=`data:${o};base64,${l}`;return e.set(r,u,o,c),u}catch(n){throw yy.logError("URL_DOWNLOAD_FAILED",n,{url:r}),new Error(`Failed to download image from ${r}: ${n instanceof Error?n.message:String(n)}`,{cause:n})}}function cQt(r){switch(r.toLowerCase().split(".").pop()){case"png":return"image/png";case"gif":return"image/gif";case"webp":return"image/webp";case"bmp":return"image/bmp";case"tiff":case"tif":return"image/tiff";default:return"image/jpeg"}}function lQt(r){if(r.length>=3&&r[0]===255&&r[1]===216&&r[2]===255)return"image/jpeg";if(r.length>=8&&r[0]===137&&r[1]===80&&r[2]===78&&r[3]===71&&r[4]===13&&r[5]===10&&r[6]===26&&r[7]===10)return"image/png";if(r.length>=6&&r[0]===71&&r[1]===73&&r[2]===70&&r[3]===56&&(r[4]===55||r[4]===57)&&r[5]===97)return"image/gif";if(r.length>=12&&r[0]===82&&r[1]===73&&r[2]===70&&r[3]===70&&r[8]===87&&r[9]===69&&r[10]===66&&r[11]===80)return"image/webp";if(r.length>=2&&r[0]===66&&r[1]===77)return"image/bmp";if(r.length>=4&&(r[0]===73&&r[1]===73&&r[2]===42&&r[3]===0||r[0]===77&&r[1]===77&&r[2]===0&&r[3]===42))return"image/tiff"}function uQt(r){if(!Jn(r))throw new Error(`Image file not found: ${r}`);return cl(r).toString("base64")}function dQt(r,e){let t,n="image/jpeg";if(typeof r=="string")if(r.startsWith("data:")){let o=r.match(/^data:([^;]+);base64,(.+)$/);if(o){let s=o[1];if(!s.startsWith("image/"))throw new Error(`Unsupported data URI MIME type for image input at index ${e}: "${s}" (expected image/*)`);n=s,t=o[2]}else throw new Error(`Malformed image data URI at index ${e} (expected "data:<image/...>;base64,<data>")`)}else{if(mUe(r))throw new Error(`Unprocessed URL found in actualImages: ${r}`);try{t=uQt(r),n=cQt(r)}catch(o){throw yy.logError("FILE_PATH_CONVERSION",o,{index:e,filePath:r}),new Error(`Failed to convert file path to base64: ${r}. ${o}`,{cause:o})}}else{let o=lQt(r);o&&(n=o),t=r.toString("base64")}return{imageData:t,mimeType:n}}async function pQt(r,e,t,n){VE.validateImageCount(e.length,t,n);let o=e.map((l,u)=>{let d=lUe(l);return d?`[Image ${u+1}: ${d}]`:null}).filter(Boolean),s=o.length>0?`${r}
|
|
1105
1105
|
|
|
1106
1106
|
Image descriptions for context: ${o.join(" ")}`:r,i=[],a=[];e.forEach((l,u)=>{let d=Z7t(l),p=lUe(l);typeof d=="string"&&mUe(d)?i.push({url:d,altText:p}):a.push({data:d,altText:p})});for(let{url:l,altText:u}of i)try{let d=await aQt(l);a.push({data:d,altText:u})}catch(d){yy.logError("URL_DOWNLOAD_FAILED_SKIPPING",d,{url:l}),g.warn(`Failed to download image from ${l}, skipping: ${d instanceof Error?d.message:String(d)}`)}let c=[{type:"text",text:s}];return a.forEach(({data:l},u)=>{try{let{imageData:d,mimeType:p}=dQt(l,u);c.push({type:"image",image:d,mimeType:p})}catch(d){throw yy.logError("ADD_IMAGE_TO_CONTENT",d,{index:u,provider:t}),d}}),c}async function fUe(r,e,t,n,o){let s=[{type:"text",text:r}];if(e.length>0){let a=await pQt("",e,n,o);Array.isArray(a)&&a.forEach(c=>{c.type!=="text"&&s.push(c)})}if(Ty.supportsNativePDF(n))s.push(...t.map(a=>(g.info(`[PDF] \u2705 Added to content (native PDF format): ${a.filename}`),{type:"file",data:a.buffer,mediaType:"application/pdf"})));else{g.info(`[PDF\u2192Image] Provider ${n} doesn't support native PDF. Converting ${t.length} PDF(s) to images...`);for(let a of t)try{let c=await yNe.convertToImages(a.buffer,{scale:2,maxPages:20});g.info(`[PDF\u2192Image] \u2705 Converted ${a.filename}: ${c.pageCount} page(s) \u2192 images`),c.images.forEach((l,u)=>{s.push({type:"image",image:l,mimeType:"image/png"}),g.debug(`[PDF\u2192Image] Added page ${u+1}/${c.pageCount} of ${a.filename}`)}),c.warnings&&c.warnings.forEach(l=>{g.warn(`[PDF\u2192Image] ${l}`)})}catch(c){let l=c instanceof Error?c.message:String(c);throw g.error(`[PDF\u2192Image] \u274C Failed to convert ${a.filename}: ${l}`),new Error(`PDF to image conversion failed for ${a.filename}: ${l}. Provider ${n} doesn't support native PDFs and image conversion failed.`,{cause:c})}}return s}function Hb(r){return typeof r=="object"&&!Buffer.isBuffer(r)&&"buffer"in r&&"filename"in r}function Wy(r,e=0){if(Hb(r))return r.filename;if(typeof r=="string"){if(r.startsWith("http"))try{return new URL(r).pathname.split("/").pop()||`file-${e+1}`}catch{return`file-${e+1}`}return r.split("/").pop()||r.split("\\").pop()||`file-${e+1}`}return`file-${e+1}`}function mQt(r){if(Hb(r))return r.buffer.length;if(Buffer.isBuffer(r))return r.length;if(typeof r=="string"&&Jn(r))try{return tm(r).size}catch{return 0}return typeof r=="string"?r.length:0}async function fQt(r){if(Hb(r))return r.buffer;if(Buffer.isBuffer(r))return r;if(typeof r=="string"&&Jn(r))try{return cl(r)}catch{return null}return null}function gQt(r){if(Hb(r)||Buffer.isBuffer(r))return"buffer";if(typeof r=="string"){if(r.startsWith("data:"))return"datauri";if(r.startsWith("http://")||r.startsWith("https://"))return"url";if(Jn(r))return"path"}return"buffer"}async function hQt(r,e,t,n=0){try{let o=await fQt(r);if(!o)return!1;let s=Wy(r,n),i=typeof r=="object"&&!Buffer.isBuffer(r)?r.mimetype:void 0;return await t.register(o,gQt(r),{filename:s,mimetype:i}),g.info(`[FileDetector] Registered "${s}" (${(e/1024).toFixed(0)} KB) as lazy reference \u2014 skipping upfront processing`),!0}catch(o){return g.warn(`[FileDetector] Failed to register file as reference, falling back to full processing: ${o instanceof Error?o.message:String(o)}`),!1}}function yQt(r,e){let t={"text/javascript":"javascript","text/typescript":"typescript","text/x-python":"python","text/x-java-source":"java","text/x-go":"go","text/x-rustsrc":"rust","text/x-ruby":"ruby","text/x-php":"php","text/x-c":"c","text/x-c++":"cpp","text/x-csharp":"csharp","text/x-swift":"swift","text/x-kotlin":"kotlin","text/x-scala":"scala","text/x-shellscript":"bash","text/x-powershell":"powershell","text/x-sql":"sql","text/x-r":"r","text/x-lua":"lua","text/x-perl":"perl","text/x-dart":"dart","text/x-elixir":"elixir","text/x-erlang":"erlang","text/x-haskell":"haskell","text/x-clojure":"clojure","text/x-lisp":"lisp","text/html":"html","text/css":"css","text/markdown":"markdown","application/json":"json","application/xml":"xml","text/xml":"xml","application/yaml":"yaml","application/x-yaml":"yaml"},n=r.toLowerCase().split(";")[0].trim();if(t[n])return t[n];let o=e.split(".").pop()?.toLowerCase();return o&&{js:"javascript",mjs:"javascript",cjs:"javascript",jsx:"javascript",ts:"typescript",tsx:"typescript",py:"python",java:"java",go:"go",rs:"rust",rb:"ruby",php:"php",c:"c",cpp:"cpp",cc:"cpp",h:"c",hpp:"cpp",cs:"csharp",swift:"swift",kt:"kotlin",kts:"kotlin",scala:"scala",sh:"bash",bash:"bash",zsh:"bash",ps1:"powershell",sql:"sql",r:"r",lua:"lua",pl:"perl",perl:"perl",dart:"dart",ex:"elixir",exs:"elixir",erl:"erlang",hs:"haskell",clj:"clojure",lisp:"lisp",vim:"vim",html:"html",htm:"html",css:"css",md:"markdown",markdown:"markdown",json:"json",xml:"xml",yaml:"yaml",yml:"yaml",toml:"toml",ini:"ini",cfg:"ini"}[o]||null}function $oe(r){return`
|
|
1107
1107
|
**NOTE**: You can perform calculations directly on the CSV data shown above. For advanced operations on the full file (counting by column, grouping, etc.), you may optionally use the analyzeCSV tool with filePath="${r}".
|
|
@@ -231,6 +231,24 @@ export function coerceJsonToSchema(text, schema) {
|
|
|
231
231
|
truncated: candidate.truncated,
|
|
232
232
|
});
|
|
233
233
|
}
|
|
234
|
+
else if (
|
|
235
|
+
// Single-element array wrapper: for an OBJECT schema, models sometimes
|
|
236
|
+
// return `[{...}]` instead of `{...}` (seen on the native Anthropic
|
|
237
|
+
// path under escaping stress). Unwrap a lone object element and
|
|
238
|
+
// re-validate — the safeParse gate rejects an incorrect unwrap, so an
|
|
239
|
+
// array schema (which validates the array directly above) is untouched.
|
|
240
|
+
Array.isArray(outcome.value) &&
|
|
241
|
+
outcome.value.length === 1 &&
|
|
242
|
+
outcome.value[0] !== null &&
|
|
243
|
+
typeof outcome.value[0] === "object" &&
|
|
244
|
+
!Array.isArray(outcome.value[0]) &&
|
|
245
|
+
safeParseable.safeParse(outcome.value[0]).success) {
|
|
246
|
+
schemaValid.push({
|
|
247
|
+
value: outcome.value[0],
|
|
248
|
+
repaired: true,
|
|
249
|
+
truncated: candidate.truncated,
|
|
250
|
+
});
|
|
251
|
+
}
|
|
234
252
|
}
|
|
235
253
|
}
|
|
236
254
|
// Among schema-valid candidates prefer the MOST COMPLETE one. With nullable
|
|
@@ -1245,7 +1245,10 @@ async function convertContentToProviderFormat(content, provider, _model) {
|
|
|
1245
1245
|
* Check if a string is an internet URL
|
|
1246
1246
|
*/
|
|
1247
1247
|
function isInternetUrl(input) {
|
|
1248
|
-
|
|
1248
|
+
// Scheme is case-insensitive (RFC 3986) — "HTTPS://..." must still be a URL,
|
|
1249
|
+
// not fall through to the file-path branch and produce a confusing error.
|
|
1250
|
+
const lower = input.toLowerCase();
|
|
1251
|
+
return lower.startsWith("http://") || lower.startsWith("https://");
|
|
1249
1252
|
}
|
|
1250
1253
|
/**
|
|
1251
1254
|
* Download image from URL and convert to base64 data URI
|
|
@@ -1278,17 +1281,21 @@ async function downloadImageFromUrl(url) {
|
|
|
1278
1281
|
if (!contentType.startsWith("image/")) {
|
|
1279
1282
|
throw new Error(`URL does not point to an image. Content-Type: ${contentType}`);
|
|
1280
1283
|
}
|
|
1281
|
-
// Read the response body
|
|
1284
|
+
// Read the response body, enforcing the size cap INCREMENTALLY: a
|
|
1285
|
+
// misbehaving/malicious server on a user-supplied URL must not be able to
|
|
1286
|
+
// force unbounded memory growth by streaming gigabytes before we ever
|
|
1287
|
+
// check the total (the previous code concat'd everything first).
|
|
1288
|
+
const maxSize = 10 * 1024 * 1024; // 10MB
|
|
1282
1289
|
const chunks = [];
|
|
1290
|
+
let totalSize = 0;
|
|
1283
1291
|
for await (const chunk of response.body) {
|
|
1292
|
+
totalSize += chunk.length;
|
|
1293
|
+
if (totalSize > maxSize) {
|
|
1294
|
+
throw new Error(`Image too large: exceeds ${maxSize} bytes while downloading from ${url}`);
|
|
1295
|
+
}
|
|
1284
1296
|
chunks.push(chunk);
|
|
1285
1297
|
}
|
|
1286
1298
|
const buffer = Buffer.concat(chunks);
|
|
1287
|
-
// Check file size (limit to 10MB)
|
|
1288
|
-
const maxSize = 10 * 1024 * 1024; // 10MB
|
|
1289
|
-
if (buffer.length > maxSize) {
|
|
1290
|
-
throw new Error(`Image too large: ${buffer.length} bytes (max: ${maxSize} bytes)`);
|
|
1291
|
-
}
|
|
1292
1299
|
// Convert to base64 data URI
|
|
1293
1300
|
const base64 = buffer.toString("base64");
|
|
1294
1301
|
const dataUri = `data:${contentType};base64,${base64}`;
|
|
@@ -1414,11 +1421,20 @@ function processImageToBase64(image, index) {
|
|
|
1414
1421
|
// Data URI (including downloaded URLs) - extract mime type and raw base64
|
|
1415
1422
|
const match = image.match(/^data:([^;]+);base64,(.+)$/);
|
|
1416
1423
|
if (match) {
|
|
1417
|
-
|
|
1424
|
+
const declaredMime = match[1];
|
|
1425
|
+
// #348: only accept image/* data URIs; reject a non-image MIME before
|
|
1426
|
+
// it reaches a provider API rather than passing it through unchecked.
|
|
1427
|
+
if (!declaredMime.startsWith("image/")) {
|
|
1428
|
+
throw new Error(`Unsupported data URI MIME type for image input at index ${index}: "${declaredMime}" (expected image/*)`);
|
|
1429
|
+
}
|
|
1430
|
+
mimeType = declaredMime;
|
|
1418
1431
|
imageData = match[2]; // Raw base64 only — NOT the full data: URI
|
|
1419
1432
|
}
|
|
1420
1433
|
else {
|
|
1421
|
-
|
|
1434
|
+
// #270: a malformed data: URI must fail loudly, not silently pass the
|
|
1435
|
+
// raw string through as if it were valid base64 (which corrupts the
|
|
1436
|
+
// request and surfaces as an opaque provider error later).
|
|
1437
|
+
throw new Error(`Malformed image data URI at index ${index} (expected "data:<image/...>;base64,<data>")`);
|
|
1422
1438
|
}
|
|
1423
1439
|
}
|
|
1424
1440
|
else if (isInternetUrl(image)) {
|
|
@@ -231,6 +231,24 @@ export function coerceJsonToSchema(text, schema) {
|
|
|
231
231
|
truncated: candidate.truncated,
|
|
232
232
|
});
|
|
233
233
|
}
|
|
234
|
+
else if (
|
|
235
|
+
// Single-element array wrapper: for an OBJECT schema, models sometimes
|
|
236
|
+
// return `[{...}]` instead of `{...}` (seen on the native Anthropic
|
|
237
|
+
// path under escaping stress). Unwrap a lone object element and
|
|
238
|
+
// re-validate — the safeParse gate rejects an incorrect unwrap, so an
|
|
239
|
+
// array schema (which validates the array directly above) is untouched.
|
|
240
|
+
Array.isArray(outcome.value) &&
|
|
241
|
+
outcome.value.length === 1 &&
|
|
242
|
+
outcome.value[0] !== null &&
|
|
243
|
+
typeof outcome.value[0] === "object" &&
|
|
244
|
+
!Array.isArray(outcome.value[0]) &&
|
|
245
|
+
safeParseable.safeParse(outcome.value[0]).success) {
|
|
246
|
+
schemaValid.push({
|
|
247
|
+
value: outcome.value[0],
|
|
248
|
+
repaired: true,
|
|
249
|
+
truncated: candidate.truncated,
|
|
250
|
+
});
|
|
251
|
+
}
|
|
234
252
|
}
|
|
235
253
|
}
|
|
236
254
|
// Among schema-valid candidates prefer the MOST COMPLETE one. With nullable
|
|
@@ -1245,7 +1245,10 @@ async function convertContentToProviderFormat(content, provider, _model) {
|
|
|
1245
1245
|
* Check if a string is an internet URL
|
|
1246
1246
|
*/
|
|
1247
1247
|
function isInternetUrl(input) {
|
|
1248
|
-
|
|
1248
|
+
// Scheme is case-insensitive (RFC 3986) — "HTTPS://..." must still be a URL,
|
|
1249
|
+
// not fall through to the file-path branch and produce a confusing error.
|
|
1250
|
+
const lower = input.toLowerCase();
|
|
1251
|
+
return lower.startsWith("http://") || lower.startsWith("https://");
|
|
1249
1252
|
}
|
|
1250
1253
|
/**
|
|
1251
1254
|
* Download image from URL and convert to base64 data URI
|
|
@@ -1278,17 +1281,21 @@ async function downloadImageFromUrl(url) {
|
|
|
1278
1281
|
if (!contentType.startsWith("image/")) {
|
|
1279
1282
|
throw new Error(`URL does not point to an image. Content-Type: ${contentType}`);
|
|
1280
1283
|
}
|
|
1281
|
-
// Read the response body
|
|
1284
|
+
// Read the response body, enforcing the size cap INCREMENTALLY: a
|
|
1285
|
+
// misbehaving/malicious server on a user-supplied URL must not be able to
|
|
1286
|
+
// force unbounded memory growth by streaming gigabytes before we ever
|
|
1287
|
+
// check the total (the previous code concat'd everything first).
|
|
1288
|
+
const maxSize = 10 * 1024 * 1024; // 10MB
|
|
1282
1289
|
const chunks = [];
|
|
1290
|
+
let totalSize = 0;
|
|
1283
1291
|
for await (const chunk of response.body) {
|
|
1292
|
+
totalSize += chunk.length;
|
|
1293
|
+
if (totalSize > maxSize) {
|
|
1294
|
+
throw new Error(`Image too large: exceeds ${maxSize} bytes while downloading from ${url}`);
|
|
1295
|
+
}
|
|
1284
1296
|
chunks.push(chunk);
|
|
1285
1297
|
}
|
|
1286
1298
|
const buffer = Buffer.concat(chunks);
|
|
1287
|
-
// Check file size (limit to 10MB)
|
|
1288
|
-
const maxSize = 10 * 1024 * 1024; // 10MB
|
|
1289
|
-
if (buffer.length > maxSize) {
|
|
1290
|
-
throw new Error(`Image too large: ${buffer.length} bytes (max: ${maxSize} bytes)`);
|
|
1291
|
-
}
|
|
1292
1299
|
// Convert to base64 data URI
|
|
1293
1300
|
const base64 = buffer.toString("base64");
|
|
1294
1301
|
const dataUri = `data:${contentType};base64,${base64}`;
|
|
@@ -1414,11 +1421,20 @@ function processImageToBase64(image, index) {
|
|
|
1414
1421
|
// Data URI (including downloaded URLs) - extract mime type and raw base64
|
|
1415
1422
|
const match = image.match(/^data:([^;]+);base64,(.+)$/);
|
|
1416
1423
|
if (match) {
|
|
1417
|
-
|
|
1424
|
+
const declaredMime = match[1];
|
|
1425
|
+
// #348: only accept image/* data URIs; reject a non-image MIME before
|
|
1426
|
+
// it reaches a provider API rather than passing it through unchecked.
|
|
1427
|
+
if (!declaredMime.startsWith("image/")) {
|
|
1428
|
+
throw new Error(`Unsupported data URI MIME type for image input at index ${index}: "${declaredMime}" (expected image/*)`);
|
|
1429
|
+
}
|
|
1430
|
+
mimeType = declaredMime;
|
|
1418
1431
|
imageData = match[2]; // Raw base64 only — NOT the full data: URI
|
|
1419
1432
|
}
|
|
1420
1433
|
else {
|
|
1421
|
-
|
|
1434
|
+
// #270: a malformed data: URI must fail loudly, not silently pass the
|
|
1435
|
+
// raw string through as if it were valid base64 (which corrupts the
|
|
1436
|
+
// request and surfaces as an opaque provider error later).
|
|
1437
|
+
throw new Error(`Malformed image data URI at index ${index} (expected "data:<image/...>;base64,<data>")`);
|
|
1422
1438
|
}
|
|
1423
1439
|
}
|
|
1424
1440
|
else if (isInternetUrl(image)) {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@juspay/neurolink",
|
|
3
|
-
"version": "9.88.
|
|
3
|
+
"version": "9.88.10",
|
|
4
4
|
"packageManager": "pnpm@10.15.1",
|
|
5
5
|
"description": "TypeScript AI SDK with 24+ LLM providers behind one consistent API. MCP-native (58+ servers), voice TTS/STT/realtime, RAG, agents, memory, context compaction. OpenAI · Anthropic · Gemini · Bedrock · Azure · Ollama · DeepSeek · NVIDIA NIM and more.",
|
|
6
6
|
"author": {
|