@juspay/neurolink 10.8.15 → 10.8.17

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,11 @@
1
+ ## [10.8.17](https://github.com/juspay/neurolink/compare/v10.8.16...v10.8.17) (2026-08-04)
2
+
3
+ ### Bug Fixes
4
+
5
+ - **(test):** revive two suites that had been dead since the provider split ([8d676b7](https://github.com/juspay/neurolink/commit/8d676b72e0c6f14de882449df66da407a78bb43e))
6
+
7
+ ## [10.8.16](https://github.com/juspay/neurolink/compare/v10.8.15...v10.8.16) (2026-08-04)
8
+
1
9
  ## [10.8.15](https://github.com/juspay/neurolink/compare/v10.8.14...v10.8.15) (2026-08-04)
2
10
 
3
11
  ## [10.8.14](https://github.com/juspay/neurolink/compare/v10.8.13...v10.8.14) (2026-08-04)
@@ -825,7 +825,7 @@ Call this with a task description or an exact tool name; matching tools are load
825
825
  ${t}
826
826
  ]`}function S(){let N=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1,W=arguments.length>1&&arguments[1]!==void 0?arguments[1]:-1,te=r[e]==="\\";if(te&&(e++,te=!0),SA(r[e])){let K=T7(r[e])?T7:S7(r[e])?S7:k2(r[e])?k2:b7,se=e,_e=t.length,G='"';for(e++;;){if(e>=r.length){let le=P(e-1);return!N&&TA(r.charAt(le))?(e=se,t=t.substring(0,_e),S(!0)):(G=wu(G,'"'),t+=G,!0)}if(e===W)return G=wu(G,'"'),t+=G,!0;if(K(r[e])){let le=e,ue=G.length;if(G+='"',e++,t+=G,i(!1),N||e>=r.length||TA(r[e])||SA(r[e])||Zf(r[e]))return w(),!0;let $e=P(le-1),we=r.charAt($e);if(we===",")return e=se,t=t.substring(0,_e),S(!1,$e);if(TA(we))return e=se,t=t.substring(0,_e),S(!0);t=t.substring(0,_e),e=le+1,G=`${G.substring(0,ue)}\\${G.substring(ue)}`}else if(N&&v7(r[e])){if(r[e-1]===":"&&h7.test(r.substring(se+1,e+2)))for(;e<r.length&&y7.test(r[e]);)G+=r[e],e++;return G=wu(G,'"'),t+=G,w(),!0}else if(r[e]==="\\"){let le=r.charAt(e+1);if(LFt[le]!==void 0)G+=r.slice(e,e+2),e+=2;else if(le==="u"){let $e=2;for(;$e<6&&dPe(r[e+$e]);)$e++;$e===6?(G+=r.slice(e,e+6),e+=6):e+$e>=r.length?e=r.length:F()}else le===`
827
827
  `?(G+="\\n",e+=2):(G+=le,e+=2)}else{let le=r.charAt(e);le==='"'&&r[e-1]!=="\\"?(G+=`\\${le}`,e++):mPe(le)?(G+=DFt[le],e++):(pPe(le)||B(le),G+=le,e++)}te&&f()}}return!1}function w(){let N=!1;for(i();r[e]==="+";){N=!0,e++,i(),t=QS(t,'"',!0);let W=t.length;S()?t=hPe(t,W,1):t=wu(t,'"')}return N}function C(){let N=e;if(r[e]==="-"){if(e++,M())return D(N),!0;if(!Zf(r[e]))return e=N,!1}for(;Zf(r[e]);)e++;if(r[e]==="."){if(e++,M())return D(N),!0;if(!Zf(r[e]))return e=N,!1;for(;Zf(r[e]);)e++}if(r[e]==="e"||r[e]==="E"){if(e++,(r[e]==="-"||r[e]==="+")&&e++,M())return D(N),!0;if(!Zf(r[e]))return e=N,!1;for(;Zf(r[e]);)e++}if(!M())return e=N,!1;if(e>N){let W=r.slice(N,e),te=/^0\d/.test(W);return t+=te?`"${W}"`:W,!0}return!1}function R(){return k("true","true")||k("false","false")||k("null","null")||k("True","true")||k("False","false")||k("None","null")}function k(N,W){return r.slice(e,e+N.length)===N?(t+=W,e+=N.length,!0):!1}function I(N){let W=e;if(g7(r[e])){for(;e<r.length&&f7(r[e]);)e++;let te=e;for(;Xf(r,te);)te++;if(r[te]==="(")return e=te+1,s(),r[e]===")"&&(e++,r[e]===";"&&e++),!0}for(;e<r.length&&!v7(r[e])&&!SA(r[e])&&(!N||r[e]!==":");)e++;if(r[e-1]===":"&&h7.test(r.substring(W,e+2)))for(;e<r.length&&y7.test(r[e]);)e++;if(e>W){for(;Xf(r,e-1)&&e>0;)e--;let te=r.slice(W,e);return t+=te==="undefined"?"null":JSON.stringify(te),r[e]==='"'&&e++,!0}}function A(){if(r[e]==="/"){let N=e;for(e++;e<r.length&&(r[e]!=="/"||r[e-1]==="\\");)e++;return e++,t+=JSON.stringify(r.substring(N,e)),!0}}function P(N){let W=N;for(;W>0&&Xf(r,W);)W--;return W}function M(){return e>=r.length||TA(r[e])||Xf(r,e)}function D(N){t+=`${r.slice(N,e)}0`}function B(N){throw new Fm(`Invalid character ${JSON.stringify(N)}`,e)}function L(){throw new Fm(`Unexpected character ${JSON.stringify(r[e])}`,e)}function $(){throw new Fm("Unexpected end of json string",r.length)}function H(){throw new Fm("Object key expected",e)}function j(){throw new Fm("Colon expected",e)}function F(){let N=r.slice(e,e+6);throw new Fm(`Invalid unicode character "${N}"`,e)}}function UFt(r,e){return r[e]==="*"&&r[e+1]==="/"}var DFt,LFt,xPe=E(()=>{uPe();vPe();DFt={"\b":"\\b","\f":"\\f","\n":"\\n","\r":"\\r"," ":"\\t"},LFt={'"':'"',"\\":"\\","/":"/",b:"\b",f:"\f",n:`
828
- `,r:"\r",t:" "}});var bPe=E(()=>{xPe()});function _7(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 TPe=E(()=>{"use strict"});function FFt(r){return typeof r.safeParse=="function"}function $Ft(r){try{return{value:JSON.parse(r),repaired:!1}}catch{}try{let e=w7(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 E7(r,e=0){if(e>BFt)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=E7(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=E7(s,e+1);i.changed&&(t=!0),n[o]=i.value}return{value:t?n:r,changed:t}}return{value:r,changed:!1}}function A2(r,e){if(typeof r!="string"||r.trim().length===0)return null;let t=[],n=0;for(;;){let h=_7(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 v=_7(h,y);if(!v)break;t.push({text:v.span,truncated:!1}),y=v.end}}}catch{}let c,l=[],d=!!(e&&FFt(e)),p=new Set;for(let h of t){if(p.has(h.text))continue;p.add(h.text);let y=$Ft(h.text);if(y===void 0||y.value===null||typeof y.value!="object")continue;let v={value:y.value,repaired:y.repaired,truncated:h.truncated};if(c===void 0&&(c=v),!d)break;let b=e;if(b.safeParse(y.value).success)l.push(v);else{let S=E7(y.value);S.changed&&S.value!==null&&typeof S.value=="object"&&b.safeParse(S.value).success?l.push({value:S.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 BFt,C7=E(()=>{"use strict";bPe();J();TPe();BFt=6});function SPe(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 wPe=E(()=>{"use strict"});var R7={};ce(R7,{coerceType:()=>I2,createToolCallRepair:()=>zFt});function zFt(){return async({toolCall:r,tools:e,inputSchema:t,error:n})=>{let{NoSuchToolError:o,InvalidToolInputError:s}=await Promise.resolve().then(()=>(gp(),yke));if(o.isInstance(n))return jFt(r,Object.keys(e));if(s.isInstance(n))try{let i=await t({toolName:r.toolName});return GFt(r,i)}catch{return null}return null}}function jFt(r,e){let t=r.toolName;if(!t||t.trim().length===0)return null;let n=e.find(c=>c.toLowerCase()===t.toLowerCase());if(n)return g.debug(`[ToolCallRepair] Name repair (case): "${t}" \u2192 "${n}"`),{...r,toolName:n};let o=t.toLowerCase(),s=e.filter(c=>{let l=c.toLowerCase();return l.includes(o)||o.includes(l)});if(s.length===1)return g.debug(`[ToolCallRepair] Name repair (substring): "${t}" \u2192 "${s[0]}"`),{...r,toolName:s[0]};let i=null,a=1/0;for(let c of e){let l=_Pe(o,c.toLowerCase()),d=Math.max(t.length,c.length),p=d===0?0:l/d;p<.3&&p<a&&(a=p,i=c)}return i?(g.debug(`[ToolCallRepair] Name repair (levenshtein ${a.toFixed(2)}): "${t}" \u2192 "${i}"`),{...r,toolName:i}):(g.debug(`[ToolCallRepair] Could not repair tool name "${t}". Available: [${e.join(", ")}]`),null)}function GFt(r,e){let t;try{t=JSON.parse(r.input)}catch{return null}if(!t||typeof t!="object"||Array.isArray(t))return null;let n=e.properties;if(!n)return null;let o=Object.keys(n),s=t,i=Object.keys(s),a=Object.create(null),c=!1,l=e.additionalProperties===!1;for(let d of i){if(o.includes(d)){a[d]=s[d];continue}let p=qFt(d,o);if(p){if(Object.prototype.hasOwnProperty.call(a,p)){c=!0;continue}g.debug(`[ToolCallRepair] Param repair: "${d}" \u2192 "${p}" (tool: ${r.toolName})`),a[p]=s[d],c=!0}else l?(g.debug(`[ToolCallRepair] Dropping unmapped key "${d}" (additionalProperties: false, tool: ${r.toolName})`),c=!0):a[d]=s[d]}for(let d of Object.keys(a)){let p=n[d];if(!p)continue;let m=I2(a[d],p);m!==a[d]&&(g.debug(`[ToolCallRepair] Type coercion on "${d}": ${typeof a[d]} \u2192 ${typeof m} (tool: ${r.toolName})`),a[d]=m,c=!0)}return c?{...r,input:JSON.stringify(a)}:null}function qFt(r,e){let t=r.toLowerCase(),n=e.find(i=>i.toLowerCase()===t);if(n)return n;let o=null,s=1/0;for(let i of e){let a=_Pe(t,i.toLowerCase());a<=2&&a<s&&(s=a,o=i)}return o}function I2(r,e){let t=e.type;if(!t||r===null||r===void 0)return r;if(t==="number"&&typeof r=="string"){let n=r.trim();if(n!==""){let o=Number(n);if(isFinite(o))return o}}if(t==="integer"&&typeof r=="string"){let n=r.trim();if(/^[+-]?\d+$/.test(n)){let o=Number(n);if(Number.isSafeInteger(o))return o}}if(t==="boolean"&&typeof r=="string"){if(r.toLowerCase()==="true")return!0;if(r.toLowerCase()==="false")return!1}if(t==="object"&&typeof r=="string")try{let n=JSON.parse(r);if(n&&typeof n=="object"&&!Array.isArray(n))return n}catch{}if(t==="array"&&typeof r=="string")try{let n=JSON.parse(r);if(Array.isArray(n))return n}catch{}return t==="array"&&!Array.isArray(r)&&typeof r!="string"?[r]:r}function _Pe(r,e){if(r===e)return 0;if(r.length===0)return e.length;if(e.length===0)return r.length;r.length>e.length&&([r,e]=[e,r]);let t=r.length,n=e.length,o=new Array(t+1),s=new Array(t+1);for(let i=0;i<=t;i++)o[i]=i;for(let i=1;i<=n;i++){s[0]=i;for(let a=1;a<=t;a++){let c=r[a-1]===e[i-1]?0:1;s[a]=Math.min(o[a]+1,s[a-1]+1,o[a-1]+c)}[o,s]=[s,o]}return o[t]}var P2=E(()=>{"use strict";J()});function HFt(r){if(r===void 0)return"";try{return((typeof r=="string"?r:JSON.stringify(r))??"").substring(0,200)}catch{return"[unserializable]"}}function KFt(r,e){let t=Va(r.timeout),n=typeof r.turnTimeoutMs=="number"&&Number.isFinite(r.turnTimeoutMs)&&r.turnTimeoutMs>0;r.turnTimeoutMs!==void 0&&!n&&g.warn("[GenerationHandler] Ignoring invalid turnTimeoutMs \u2014 expected a positive number of milliseconds; falling back to the timeout option",{turnTimeoutMs:r.turnTimeoutMs});let o=n?r.turnTimeoutMs:t,s=o?Math.min(r.wrapupTimeLeadMs??wk,Math.floor(o/4)):0;!n&&o!==void 0&&s>0&&(o=o-s,s=Math.min(s,Math.floor(o/4)));let i=o?e+o:void 0;return{callerTimeoutMs:t,turnBudgetMs:o,wrapupLeadMs:s,turnDeadline:i}}function WFt(r,e,t){let n={};return t!==void 0&&(n.neurolink={timeoutMs:t}),r.thinkingConfig?.enabled&&e&&(n.google={thinkingConfig:{...r.thinkingConfig.thinkingLevel&&{thinkingLevel:r.thinkingConfig.thinkingLevel},...r.thinkingConfig.budgetTokens&&!r.thinkingConfig.thinkingLevel&&{thinkingBudget:r.thinkingConfig.budgetTokens},includeThoughts:!0}}),Object.keys(n).length>0?n:void 0}function JFt(r,e){let t=r?.messages??e;return{...r??{},messages:[...t,{role:"user",content:"The time budget for this task is nearly exhausted. Do not call any more tools. Give your best final answer NOW from the information already gathered, and note anything you could not verify in the remaining time."}],toolChoice:"none"}}var VFt,wA,EPe=E(()=>{"use strict";yr();KIe();Om();Lr();J();fA();Su();Lk();Nn();ZS();zs();iPe();m7();C7();gp();Tk();dv();wPe();VFt=Oe.generation;wA=class{constructor(e,t,n,o,s,i){this.providerName=e;this.modelName=t;this.supportsToolsFn=n;this.getTelemetryConfigFn=o;this.handleToolStorageFn=s;this.getEmitterFn=i}providerName;modelName;supportsToolsFn;getTelemetryConfigFn;handleToolStorageFn;getEmitterFn;async callGenerateText(e,t,n,o,s){let{shouldUseTools:i,includeStructuredOutput:a,turnStartMs:c}=s,l=this.providerName==="google-ai"||this.providerName==="vertex",d=this.providerName==="anthropic"||this.providerName==="bedrock"||this.providerName==="vertex"&&this.modelName?.startsWith("claude-"),m=a&&(!!o.schema||o.output?.format==="json"||o.output?.format==="structured")&&!aPe(this.providerName,this.modelName,i,Object.keys(n).length),f=n;if(d&&i&&Object.keys(f).length>0){let D=Object.keys(f),B=D[D.length-1];if(B&&f[B]){let L=f[B];f[B]={...L,providerOptions:{...L.providerOptions??{},anthropic:{cacheControl:{type:"ephemeral"}}}}}}let h=o.prepareStep,{callerTimeoutMs:y,turnBudgetMs:v,wrapupLeadMs:b,turnDeadline:S}=KFt(o,c),w=!1,C=WFt(o,l,y),{system:R,messages:k}=SPe(t),I={toolCount:-1,tokens:0},A=sPe({provider:this.providerName??"unknown",model:this.modelName,maxTokens:o.maxTokens,getFixedOverheadTokens:()=>{let D=i?Object.keys(f).length:0;return D!==I.toolCount&&(I={toolCount:D,tokens:oPe(R,i?f:void 0,this.providerName)}),I.tokens}}),P=ua(this.providerName,gA(e,this.modelName||""),o.temperature!==void 0?{temperature:o.temperature}:{},"aiSdk.generateText"),M=await Cm({model:e,...R&&{system:R},messages:k,...i&&Object.keys(f).length>0&&{tools:f},stopWhen:xk(o.maxSteps??rs),...i&&o.toolChoice&&{toolChoice:o.toolChoice},experimental_prepareStep:(async D=>{let B=h?await h({...D,maxSteps:o.maxSteps??rs}):void 0,L=B?.messages,$=D.steps[D.steps.length-1],H=A(L??D.messages,$?.usage?.inputTokens),j=H?{...B??{},messages:H}:B;return S!==void 0&&i&&Date.now()>=S-b?(w||(w=!0,g.warn("[GenerationHandler] Turn budget nearly exhausted \u2014 forcing wrap-up (toolChoice: none)",{provider:this.providerName,turnBudgetMs:v,wrapupLeadMs:b,stepNumber:D.stepNumber})),JFt(j,D.messages)):j}),temperature:P.temperature,maxOutputTokens:o.maxTokens,maxRetries:0,abortSignal:o.abortSignal,...i&&!o.disableToolCallRepair&&{experimental_repairToolCall:(async(...D)=>{let{createToolCallRepair:B}=await Promise.resolve().then(()=>(P2(),R7));return B()(...D)})},...C&&{providerOptions:C},...m&&o.schema&&{experimental_output:VF.object({schema:o.schema})},...o.thinkingConfig?.enabled&&d&&o.thinkingConfig.budgetTokens&&!o.thinkingConfig.thinkingLevel&&{experimental_thinking:{type:"enabled",budgetTokens:o.thinkingConfig.budgetTokens}},experimental_telemetry:this.getTelemetryConfigFn(o,"generate"),onStepFinish:({toolCalls:D,toolResults:B})=>{g.info("Tool execution completed",{toolResults:B,toolCalls:D}),Wf(this.getEmitterFn?.(),B),this.handleToolStorageFn(D,B,o,new Date).catch(L=>{g.warn("[GenerationHandler] Failed to store tool executions",{provider:this.providerName,error:L instanceof Error?L.message:String(L)})})}});return w&&Object.defineProperty(M,"__nlTurnWrapup",{value:!0,enumerable:!1}),M}async executeGeneration(e,t,n,o){return VFt.startActiveSpan("neurolink.executeGeneration",{kind:Tr.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",gA(e,this.modelName||"unknown"));let l=o.requestId||o.context?.requestId||"unknown";if(g.info("[GenerationHandler] Calling generateText",{requestId:l,model:gA(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:gA(e),messageCount:t.length,messages:t.map((p,m)=>({index:m,role:p.role,contentLength:typeof p.content=="string"?p.content.length:HFt(p.content).length,contentPreview:typeof p.content=="string"?p.content.substring(0,200):"[multimodal]"})),toolNames:Object.keys(n||{}),toolCount:a,maxSteps:o.maxSteps,temperature:o.temperature,maxTokens:o.maxTokens})}catch{}let d=Date.now();try{let p=await OS(()=>this.callGenerateText(e,t,n,o,{shouldUseTools:i,includeStructuredOutput:!0,turnStartMs:d}),s,"generateText");return g.info("[GenerationHandler] generateText returned",{requestId:l,durationMs:Date.now()-d,finishReason:p.finishReason,steps:p.steps?.length||1,toolCallsTotal:p.toolCalls?.length||0,responseChars:p.text?.length||0}),g.shouldLog("debug")&&g.debug("[Observability] LLM response metadata",{requestId:l,responseLength:p.text?.length||0,hasToolCalls:!!(p.toolCalls&&p.toolCalls.length>0),toolCallCount:p.toolCalls?.length||0,toolNames:p.toolCalls?.map(m=>m.toolName),finishReason:p.finishReason,stepCount:p.steps?.length||0,steps:p.steps?.map((m,f)=>({stepIndex:f,stepType:m.stepType,textLength:m.text?.length||0,toolCallCount:m.toolCalls?.length||0,toolNames:m.toolCalls?.map(h=>h.toolName),toolResultCount:m.toolResults?.length||0,finishReason:m.finishReason})),usage:p.usage}),this.setUsageSpanAttributes(s,p),p.finishReason&&s.setAttribute("gen_ai.response.finish_reason",p.finishReason),s.setStatus({code:Ue.OK}),p}catch(p){let m=c&&R2(p);if(c&&(p instanceof Gi||cPe(p)||m)){s.setAttribute("neurolink.has_fallback",!0),s.addEvent("retry.initial_failure",{"error.message":p instanceof Error?p.message:String(p),"retry.attempt":1,"retry.reason":p instanceof Gi?"NoObjectGeneratedError_structured_output_fallback":m?"schema_complexity_structured_output_fallback":"tools_schema_conflict_structured_output_fallback"}),m?g.warn("[GenerationHandler] schema too complex for provider constrained decoding \u2014 retrying with prompt-based JSON",{provider:this.providerName,model:this.modelName,error:p instanceof Error?p.message:String(p)}):g.debug("[GenerationHandler] structured-output conflict caught - falling back to manual JSON extraction",{provider:this.providerName,model:this.modelName,error:p instanceof Error?p.message:String(p)});let h=await OS(()=>this.callGenerateText(e,t,n,o,{shouldUseTools:i,includeStructuredOutput:!1,turnStartMs:d}),s,"generateText(fallback)");return 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()-d,finishReason:h.finishReason,steps:h.steps?.length||1,toolCallsTotal:h.toolCalls?.length||0,responseChars:h.text?.length||0}),this.setUsageSpanAttributes(s,h),h.finishReason&&s.setAttribute("gen_ai.response.finish_reason",h.finishReason),s.setStatus({code:Ue.OK}),h}if(lPe(p)&&typeof o.temperature=="number"){s.setAttribute("neurolink.has_fallback",!0),s.addEvent("retry.initial_failure",{"error.message":p instanceof Error?p.message:String(p),"retry.attempt":1,"retry.reason":"temperature_deprecated"}),g.debug("[GenerationHandler] temperature-deprecated error caught - retrying without temperature",{provider:this.providerName,model:this.modelName,error:p instanceof Error?p.message:String(p)});let h=await OS(()=>this.callGenerateText(e,t,n,{...o,temperature:void 0},{shouldUseTools:i,includeStructuredOutput:!0,turnStartMs:d}),s,"generateText(no-temperature)");return s.addEvent("retry.recovered",{"retry.attempts":2,"retry.strategy":"temperature_omitted"}),s.setAttribute("retry.count",1),this.setUsageSpanAttributes(s,h),h.finishReason&&s.setAttribute("gen_ai.response.finish_reason",h.finishReason),s.setStatus({code:Ue.OK}),h}throw s.setStatus({code:Ue.ERROR,message:p instanceof Error?p.message:String(p)}),p}finally{s.end()}})}setUsageSpanAttributes(e,t){let n=t.totalUsage??t.usage;if(!n)return;e.setAttribute("gen_ai.usage.input_tokens",n.inputTokens||0),e.setAttribute("gen_ai.usage.output_tokens",n.outputTokens||0);let o=qo(this.providerName,this.modelName,yd(n));e.setAttribute("neurolink.cost",o??0)}extractCacheMetricsFromProviderMetadata(e){let t=e.providerMetadata;if(!t)return{};let n=t.anthropic;if(n){let o=i7(n),s=a7(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 d={};a.args?d=a.args:a.arguments?d=a.arguments:a.parameters&&(d=a.parameters),o.set(l,d),o.set(c,d)}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,d=a.args??a.arguments??a.parameters??a.input??o.get(l||c)??{};n.push({name:c,input:d,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,d=!1,p=C=>{let R=C.replace(/^```(?:json)?\s*\n?/i,"").replace(/\n?```\s*$/i,"").trim(),k=A2(R,s.schema);if(k)return c=k.structuredData,k.repaired&&(l=!0),k.truncated&&(d=!0),k.content;try{let I=JSON.parse(R);if(I==="")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(I!=null)return c=I,R}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}),R};if(i)try{let C=e.experimental_output,R=typeof C=="string"&&C===(e.text??"");C!==void 0&&!R?(c=C,a=JSON.stringify(C)):a=p(e.text||"")}catch(C){g.debug("[GenerationHandler] experimental_output threw, falling back to text parsing",{error:C instanceof Error?C.message:String(C)}),a=p(e.text||"")}else a=e.text;i&&e.finishReason==="length"&&(d=!0,g.warn("[GenerationHandler] Structured output truncated by token cap (finishReason=length); increase maxTokens",{provider:this.providerName,model:this.modelName}));let m=yd(e.totalUsage??e.usage);if(m.cacheCreationTokens===void 0||m.cacheReadTokens===void 0){let C=this.extractCacheMetricsFromProviderMetadata(e);if(m.cacheCreationTokens===void 0&&C.cacheCreationTokens!==void 0&&(m.cacheCreationTokens=C.cacheCreationTokens),m.cacheReadTokens===void 0&&C.cacheReadTokens!==void 0&&(m.cacheReadTokens=C.cacheReadTokens),m.cacheReadTokens!==void 0){let R=c7(m.cacheReadTokens,m.input);R!==void 0&&(m.cacheSavingsPercent=R)}}let f=e.reasoning,h=f?typeof f=="string"?f:Array.isArray(f)?f.map(C=>typeof C=="string"?C:C.text??JSON.stringify(C)).join(`
828
+ `,r:"\r",t:" "}});var bPe=E(()=>{xPe()});function _7(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 TPe=E(()=>{"use strict"});function FFt(r){return typeof r.safeParse=="function"}function $Ft(r){try{return{value:JSON.parse(r),repaired:!1}}catch{}try{let e=w7(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 E7(r,e=0){if(e>BFt)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=E7(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=E7(s,e+1);i.changed&&(t=!0),n[o]=i.value}return{value:t?n:r,changed:t}}return{value:r,changed:!1}}function A2(r,e){if(typeof r!="string"||r.trim().length===0)return null;let t=[],n=0;for(;;){let h=_7(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 v=_7(h,y);if(!v)break;t.push({text:v.span,truncated:!1}),y=v.end}}}catch{}let c,l=[],d=!!(e&&FFt(e)),p=new Set;for(let h of t){if(p.has(h.text))continue;p.add(h.text);let y=$Ft(h.text);if(y===void 0||y.value===null||typeof y.value!="object")continue;let v={value:y.value,repaired:y.repaired,truncated:h.truncated};if(c===void 0&&(c=v),!d)break;let b=e;if(b.safeParse(y.value).success)l.push(v);else{let S=E7(y.value);S.changed&&S.value!==null&&typeof S.value=="object"&&b.safeParse(S.value).success?l.push({value:S.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 BFt,C7=E(()=>{"use strict";bPe();J();TPe();BFt=6});function SPe(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 wPe=E(()=>{"use strict"});var R7={};ce(R7,{coerceType:()=>I2,createToolCallRepair:()=>zFt});function zFt(){return async({toolCall:r,tools:e,inputSchema:t,error:n})=>{let{NoSuchToolError:o,InvalidToolInputError:s}=await Promise.resolve().then(()=>(gp(),yke));if(o.isInstance(n))return jFt(r,Object.keys(e));if(s.isInstance(n))try{let i=await t({toolName:r.toolName});return GFt(r,i)}catch{return null}return null}}function jFt(r,e){let t=r.toolName;if(!t||t.trim().length===0)return null;let n=e.find(c=>c.toLowerCase()===t.toLowerCase());if(n)return g.debug(`[ToolCallRepair] Name repair (case): "${t}" \u2192 "${n}"`),{...r,toolName:n};let o=t.toLowerCase(),s=e.filter(c=>{let l=c.toLowerCase();return l.includes(o)||o.includes(l)});if(s.length===1)return g.debug(`[ToolCallRepair] Name repair (substring): "${t}" \u2192 "${s[0]}"`),{...r,toolName:s[0]};let i=null,a=1/0;for(let c of e){let l=_Pe(o,c.toLowerCase()),d=Math.max(t.length,c.length),p=d===0?0:l/d;p<.3&&p<a&&(a=p,i=c)}return i?(g.debug(`[ToolCallRepair] Name repair (levenshtein ${a.toFixed(2)}): "${t}" \u2192 "${i}"`),{...r,toolName:i}):(g.debug(`[ToolCallRepair] Could not repair tool name "${t}". Available: [${e.join(", ")}]`),null)}function GFt(r,e){let t;try{t=JSON.parse(r.input)}catch{return null}if(!t||typeof t!="object"||Array.isArray(t))return null;let n=e.properties;if(!n)return null;let o=Object.keys(n),s=t,i=Object.keys(s),a=Object.create(null),c=!1,l=e.additionalProperties===!1;for(let d of i){if(o.includes(d)){a[d]=s[d];continue}let p=qFt(d,o);if(p){if(Object.prototype.hasOwnProperty.call(a,p)){c=!0;continue}g.debug(`[ToolCallRepair] Param repair: "${d}" \u2192 "${p}" (tool: ${r.toolName})`),a[p]=s[d],c=!0}else l?(g.debug(`[ToolCallRepair] Dropping unmapped key "${d}" (additionalProperties: false, tool: ${r.toolName})`),c=!0):a[d]=s[d]}for(let d of Object.keys(a)){let p=n[d];if(!p)continue;let m=I2(a[d],p);m!==a[d]&&(g.debug(`[ToolCallRepair] Type coercion on "${d}": ${typeof a[d]} \u2192 ${typeof m} (tool: ${r.toolName})`),a[d]=m,c=!0)}return c?{...r,input:JSON.stringify(a)}:null}function qFt(r,e){let t=r.toLowerCase(),n=e.find(i=>i.toLowerCase()===t);if(n)return n;let o=null,s=1/0;for(let i of e){let a=_Pe(t,i.toLowerCase());a<=2&&a<s&&(s=a,o=i)}return o}function I2(r,e){let t=e.type;if(!t||r===null||r===void 0)return r;if(t==="number"&&typeof r=="string"){let n=r.trim();if(n!==""){let o=Number(n);if(isFinite(o))return o}}if(t==="integer"&&typeof r=="string"){let n=r.trim();if(/^[+-]?\d+$/.test(n)){let o=Number(n);if(Number.isSafeInteger(o))return o}}if(t==="boolean"&&typeof r=="string"){if(r.toLowerCase()==="true")return!0;if(r.toLowerCase()==="false")return!1}if(t==="object"&&typeof r=="string")try{let n=JSON.parse(r);if(n&&typeof n=="object"&&!Array.isArray(n))return n}catch{}if(t==="array"&&typeof r=="string")try{let n=JSON.parse(r);if(Array.isArray(n))return n}catch{}return t==="array"&&!Array.isArray(r)&&typeof r!="string"?[r]:r}function _Pe(r,e){if(r===e)return 0;if(r.length===0)return e.length;if(e.length===0)return r.length;r.length>e.length&&([r,e]=[e,r]);let t=r.length,n=e.length,o=new Array(t+1),s=new Array(t+1);for(let i=0;i<=t;i++)o[i]=i;for(let i=1;i<=n;i++){s[0]=i;for(let a=1;a<=t;a++){let c=r[a-1]===e[i-1]?0:1;s[a]=Math.min(o[a]+1,s[a-1]+1,o[a-1]+c)}[o,s]=[s,o]}return o[t]}var P2=E(()=>{"use strict";J()});function HFt(r){if(r===void 0)return"";try{return((typeof r=="string"?r:JSON.stringify(r))??"").substring(0,200)}catch{return"[unserializable]"}}function KFt(r,e){let t=Va(r.timeout),n=typeof r.turnTimeoutMs=="number"&&Number.isFinite(r.turnTimeoutMs)&&r.turnTimeoutMs>0;r.turnTimeoutMs!==void 0&&!n&&g.warn("[GenerationHandler] Ignoring invalid turnTimeoutMs \u2014 expected a positive number of milliseconds; falling back to the timeout option",{turnTimeoutMs:r.turnTimeoutMs});let o=n?r.turnTimeoutMs:t,s=o?Math.min(r.wrapupTimeLeadMs??wk,Math.floor(o/4)):0;!n&&o!==void 0&&s>0&&(o=o-s,s=Math.min(s,Math.floor(o/4)));let i=o?e+o:void 0;return{callerTimeoutMs:t,turnBudgetMs:o,wrapupLeadMs:s,turnDeadline:i}}function WFt(r,e,t){let n={};return t!==void 0&&(n.neurolink={timeoutMs:t}),r.thinkingConfig?.enabled&&e&&(n.google={thinkingConfig:{...r.thinkingConfig.thinkingLevel&&{thinkingLevel:r.thinkingConfig.thinkingLevel},...r.thinkingConfig.budgetTokens&&!r.thinkingConfig.thinkingLevel&&{thinkingBudget:r.thinkingConfig.budgetTokens},includeThoughts:!0}}),Object.keys(n).length>0?n:void 0}function JFt(r,e){let t=r?.messages??e;return{...r??{},messages:[...t,{role:"user",content:"The time budget for this task is nearly exhausted. Do not call any more tools. Give your best final answer NOW from the information already gathered, and note anything you could not verify in the remaining time."}],toolChoice:"none"}}var VFt,wA,EPe=E(()=>{"use strict";yr();KIe();Om();Lr();J();fA();Su();Lk();Nn();ZS();zs();iPe();m7();C7();gp();Tk();dv();wPe();VFt=Oe.generation;wA=class{constructor(e,t,n,o,s,i={}){this.providerName=e;this.modelName=t;this.supportsToolsFn=n;this.getTelemetryConfigFn=o;this.handleToolStorageFn=s;this.deps=i}providerName;modelName;supportsToolsFn;getTelemetryConfigFn;handleToolStorageFn;deps;async callGenerateText(e,t,n,o,s){let{shouldUseTools:i,includeStructuredOutput:a,turnStartMs:c}=s,l=this.providerName==="google-ai"||this.providerName==="vertex",d=this.providerName==="anthropic"||this.providerName==="bedrock"||this.providerName==="vertex"&&this.modelName?.startsWith("claude-"),m=a&&(!!o.schema||o.output?.format==="json"||o.output?.format==="structured")&&!aPe(this.providerName,this.modelName,i,Object.keys(n).length),f=n;if(d&&i&&Object.keys(f).length>0){let D=Object.keys(f),B=D[D.length-1];if(B&&f[B]){let L=f[B];f[B]={...L,providerOptions:{...L.providerOptions??{},anthropic:{cacheControl:{type:"ephemeral"}}}}}}let h=o.prepareStep,{callerTimeoutMs:y,turnBudgetMs:v,wrapupLeadMs:b,turnDeadline:S}=KFt(o,c),w=!1,C=WFt(o,l,y),{system:R,messages:k}=SPe(t),I={toolCount:-1,tokens:0},A=sPe({provider:this.providerName??"unknown",model:this.modelName,maxTokens:o.maxTokens,getFixedOverheadTokens:()=>{let D=i?Object.keys(f).length:0;return D!==I.toolCount&&(I={toolCount:D,tokens:oPe(R,i?f:void 0,this.providerName)}),I.tokens}}),P=ua(this.providerName,gA(e,this.modelName||""),o.temperature!==void 0?{temperature:o.temperature}:{},"aiSdk.generateText"),M=await(this.deps.generateTextFn??Cm)({model:e,...R&&{system:R},messages:k,...i&&Object.keys(f).length>0&&{tools:f},stopWhen:xk(o.maxSteps??rs),...i&&o.toolChoice&&{toolChoice:o.toolChoice},experimental_prepareStep:(async D=>{let B=h?await h({...D,maxSteps:o.maxSteps??rs}):void 0,L=B?.messages,$=D.steps[D.steps.length-1],H=A(L??D.messages,$?.usage?.inputTokens),j=H?{...B??{},messages:H}:B;return S!==void 0&&i&&Date.now()>=S-b?(w||(w=!0,g.warn("[GenerationHandler] Turn budget nearly exhausted \u2014 forcing wrap-up (toolChoice: none)",{provider:this.providerName,turnBudgetMs:v,wrapupLeadMs:b,stepNumber:D.stepNumber})),JFt(j,D.messages)):j}),temperature:P.temperature,maxOutputTokens:o.maxTokens,maxRetries:0,abortSignal:o.abortSignal,...i&&!o.disableToolCallRepair&&{experimental_repairToolCall:(async(...D)=>{let{createToolCallRepair:B}=await Promise.resolve().then(()=>(P2(),R7));return B()(...D)})},...C&&{providerOptions:C},...m&&o.schema&&{experimental_output:VF.object({schema:o.schema})},...o.thinkingConfig?.enabled&&d&&o.thinkingConfig.budgetTokens&&!o.thinkingConfig.thinkingLevel&&{experimental_thinking:{type:"enabled",budgetTokens:o.thinkingConfig.budgetTokens}},experimental_telemetry:this.getTelemetryConfigFn(o,"generate"),onStepFinish:({toolCalls:D,toolResults:B})=>{g.info("Tool execution completed",{toolResults:B,toolCalls:D}),Wf(this.deps.getEmitterFn?.(),B),this.handleToolStorageFn(D,B,o,new Date).catch(L=>{g.warn("[GenerationHandler] Failed to store tool executions",{provider:this.providerName,error:L instanceof Error?L.message:String(L)})})}});return w&&Object.defineProperty(M,"__nlTurnWrapup",{value:!0,enumerable:!1}),M}async executeGeneration(e,t,n,o){return VFt.startActiveSpan("neurolink.executeGeneration",{kind:Tr.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",gA(e,this.modelName||"unknown"));let l=o.requestId||o.context?.requestId||"unknown";if(g.info("[GenerationHandler] Calling generateText",{requestId:l,model:gA(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:gA(e),messageCount:t.length,messages:t.map((p,m)=>({index:m,role:p.role,contentLength:typeof p.content=="string"?p.content.length:HFt(p.content).length,contentPreview:typeof p.content=="string"?p.content.substring(0,200):"[multimodal]"})),toolNames:Object.keys(n||{}),toolCount:a,maxSteps:o.maxSteps,temperature:o.temperature,maxTokens:o.maxTokens})}catch{}let d=Date.now();try{let p=await OS(()=>this.callGenerateText(e,t,n,o,{shouldUseTools:i,includeStructuredOutput:!0,turnStartMs:d}),s,"generateText");return g.info("[GenerationHandler] generateText returned",{requestId:l,durationMs:Date.now()-d,finishReason:p.finishReason,steps:p.steps?.length||1,toolCallsTotal:p.toolCalls?.length||0,responseChars:p.text?.length||0}),g.shouldLog("debug")&&g.debug("[Observability] LLM response metadata",{requestId:l,responseLength:p.text?.length||0,hasToolCalls:!!(p.toolCalls&&p.toolCalls.length>0),toolCallCount:p.toolCalls?.length||0,toolNames:p.toolCalls?.map(m=>m.toolName),finishReason:p.finishReason,stepCount:p.steps?.length||0,steps:p.steps?.map((m,f)=>({stepIndex:f,stepType:m.stepType,textLength:m.text?.length||0,toolCallCount:m.toolCalls?.length||0,toolNames:m.toolCalls?.map(h=>h.toolName),toolResultCount:m.toolResults?.length||0,finishReason:m.finishReason})),usage:p.usage}),this.setUsageSpanAttributes(s,p),p.finishReason&&s.setAttribute("gen_ai.response.finish_reason",p.finishReason),s.setStatus({code:Ue.OK}),p}catch(p){let m=c&&R2(p);if(c&&(p instanceof Gi||cPe(p)||m)){s.setAttribute("neurolink.has_fallback",!0),s.addEvent("retry.initial_failure",{"error.message":p instanceof Error?p.message:String(p),"retry.attempt":1,"retry.reason":p instanceof Gi?"NoObjectGeneratedError_structured_output_fallback":m?"schema_complexity_structured_output_fallback":"tools_schema_conflict_structured_output_fallback"}),m?g.warn("[GenerationHandler] schema too complex for provider constrained decoding \u2014 retrying with prompt-based JSON",{provider:this.providerName,model:this.modelName,error:p instanceof Error?p.message:String(p)}):g.debug("[GenerationHandler] structured-output conflict caught - falling back to manual JSON extraction",{provider:this.providerName,model:this.modelName,error:p instanceof Error?p.message:String(p)});let h=await OS(()=>this.callGenerateText(e,t,n,o,{shouldUseTools:i,includeStructuredOutput:!1,turnStartMs:d}),s,"generateText(fallback)");return 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()-d,finishReason:h.finishReason,steps:h.steps?.length||1,toolCallsTotal:h.toolCalls?.length||0,responseChars:h.text?.length||0}),this.setUsageSpanAttributes(s,h),h.finishReason&&s.setAttribute("gen_ai.response.finish_reason",h.finishReason),s.setStatus({code:Ue.OK}),h}if(lPe(p)&&typeof o.temperature=="number"){s.setAttribute("neurolink.has_fallback",!0),s.addEvent("retry.initial_failure",{"error.message":p instanceof Error?p.message:String(p),"retry.attempt":1,"retry.reason":"temperature_deprecated"}),g.debug("[GenerationHandler] temperature-deprecated error caught - retrying without temperature",{provider:this.providerName,model:this.modelName,error:p instanceof Error?p.message:String(p)});let h=await OS(()=>this.callGenerateText(e,t,n,{...o,temperature:void 0},{shouldUseTools:i,includeStructuredOutput:!0,turnStartMs:d}),s,"generateText(no-temperature)");return s.addEvent("retry.recovered",{"retry.attempts":2,"retry.strategy":"temperature_omitted"}),s.setAttribute("retry.count",1),this.setUsageSpanAttributes(s,h),h.finishReason&&s.setAttribute("gen_ai.response.finish_reason",h.finishReason),s.setStatus({code:Ue.OK}),h}throw s.setStatus({code:Ue.ERROR,message:p instanceof Error?p.message:String(p)}),p}finally{s.end()}})}setUsageSpanAttributes(e,t){let n=t.totalUsage??t.usage;if(!n)return;e.setAttribute("gen_ai.usage.input_tokens",n.inputTokens||0),e.setAttribute("gen_ai.usage.output_tokens",n.outputTokens||0);let o=qo(this.providerName,this.modelName,yd(n));e.setAttribute("neurolink.cost",o??0)}extractCacheMetricsFromProviderMetadata(e){let t=e.providerMetadata;if(!t)return{};let n=t.anthropic;if(n){let o=i7(n),s=a7(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 d={};a.args?d=a.args:a.arguments?d=a.arguments:a.parameters&&(d=a.parameters),o.set(l,d),o.set(c,d)}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,d=a.args??a.arguments??a.parameters??a.input??o.get(l||c)??{};n.push({name:c,input:d,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,d=!1,p=C=>{let R=C.replace(/^```(?:json)?\s*\n?/i,"").replace(/\n?```\s*$/i,"").trim(),k=A2(R,s.schema);if(k)return c=k.structuredData,k.repaired&&(l=!0),k.truncated&&(d=!0),k.content;try{let I=JSON.parse(R);if(I==="")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(I!=null)return c=I,R}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}),R};if(i)try{let C=e.experimental_output,R=typeof C=="string"&&C===(e.text??"");C!==void 0&&!R?(c=C,a=JSON.stringify(C)):a=p(e.text||"")}catch(C){g.debug("[GenerationHandler] experimental_output threw, falling back to text parsing",{error:C instanceof Error?C.message:String(C)}),a=p(e.text||"")}else a=e.text;i&&e.finishReason==="length"&&(d=!0,g.warn("[GenerationHandler] Structured output truncated by token cap (finishReason=length); increase maxTokens",{provider:this.providerName,model:this.modelName}));let m=yd(e.totalUsage??e.usage);if(m.cacheCreationTokens===void 0||m.cacheReadTokens===void 0){let C=this.extractCacheMetricsFromProviderMetadata(e);if(m.cacheCreationTokens===void 0&&C.cacheCreationTokens!==void 0&&(m.cacheCreationTokens=C.cacheCreationTokens),m.cacheReadTokens===void 0&&C.cacheReadTokens!==void 0&&(m.cacheReadTokens=C.cacheReadTokens),m.cacheReadTokens!==void 0){let R=c7(m.cacheReadTokens,m.input);R!==void 0&&(m.cacheSavingsPercent=R)}}let f=e.reasoning,h=f?typeof f=="string"?f:Array.isArray(f)?f.map(C=>typeof C=="string"?C:C.text??JSON.stringify(C)).join(`
829
829
  `):String(f):void 0,y=m.reasoning??void 0,v=e.steps,b=Array.isArray(v)?v.length:void 0,S=s.maxSteps??rs,w;return e.__nlTurnWrapup===!0?w="time-limit":b!==void 0&&b>=S&&e.finishReason==="tool-calls"?w="step-cap":e.finishReason==="error"?w="provider-error":b!==void 0&&(w="completed"),{content:a,structuredData:c,usage:m,finishReason:e.finishReason,stopReason:w,stepsUsed:b,jsonRepaired:l||void 0,jsonTruncated:d||void 0,provider:this.providerName,model:this.modelName,reasoning:h,reasoningTokens:y,toolCalls:e.toolCalls?e.toolCalls.map(C=>({toolCallId:C.toolCallId||"unknown",toolName:C.toolName||"unknown",args:C.args||{}})):[],toolResults:e.toolResults??[],toolsUsed:n,toolExecutions:o,availableTools:Object.keys(t).map(C=>{let R=t[C];return{name:C,description:R.description||"No description available",parameters:R.inputSchema||{},server:R.serverId||"direct"}})}}analyzeAIResponse(e){if(e===null||typeof e!="object")return;let t=e;g.debug("NeuroLink Raw AI Response Analysis",{provider:this.providerName,model:this.modelName,responseTextLength:t.text?.length||0,responsePreview:t.text?.substring(0,500)??"",finishReason:t.finishReason,usage:t.usage});let n={hasToolCalls:!!t.toolCalls,toolCallsLength:t.toolCalls?.length||0,toolCalls:t.toolCalls?.map((o,s)=>{let i=o,a=i.toolName||i.name||"unknown";return{index:s+1,toolName:a,toolId:i.toolCallId||i.id||"none",hasArgs:!!i.args,argsKeys:i.args&&typeof i.args=="object"?Object.keys(i.args):[]}})||[]};g.debug("Tool Calls Analysis",n)}}});var $m={};ce($m,{AsyncLocalStorage:()=>h1t,Buffer:()=>r2t,Channel:()=>V$t,DatabaseSync:()=>t2t,Duplex:()=>v1t,EventEmitter:()=>f1t,Http2ServerRequest:()=>a2t,Http2ServerResponse:()=>c2t,Interface:()=>e2t,MIMEType:()=>g2t,PassThrough:()=>x1t,PerformanceObserver:()=>j$t,Readable:()=>RPe,ReadableStream:()=>b1t,Resolver:()=>B$t,TextDecoder:()=>IPe,TextEncoder:()=>M2,Transform:()=>y1t,URL:()=>R$t,URLSearchParams:()=>k$t,Worker:()=>J$t,Writable:()=>kPe,access:()=>q1t,appendFile:()=>R1t,appendFileSync:()=>r1t,arch:()=>i$t,arrayBuffer:()=>l2t,basename:()=>c1t,builtinModules:()=>w$t,callbackify:()=>D$t,channel:()=>q$t,chmodSync:()=>C1t,clearInterval:()=>m2t,clearTimeout:()=>d2t,closeSync:()=>P1t,connect:()=>u$t,constants:()=>n2t,copyFileSync:()=>A1t,cpSync:()=>n1t,cpus:()=>r$t,createConnection:()=>d$t,createGunzip:()=>v$t,createGzip:()=>x$t,createHash:()=>CPe,createHmac:()=>ZFt,createInterface:()=>Q$t,createReadStream:()=>z1t,createRequire:()=>S$t,createServer:()=>o1t,createWriteStream:()=>B1t,debug:()=>O$t,debuglog:()=>APe,default:()=>YFt,deflateSync:()=>m$t,deprecate:()=>N$t,deserialize:()=>W$t,dirname:()=>a1t,exec:()=>W1t,execFile:()=>Y1t,execFileSync:()=>X1t,execSync:()=>J1t,existsSync:()=>w1t,extname:()=>l1t,fileURLToPath:()=>A$t,finished:()=>S1t,format:()=>C$t,freemem:()=>n$t,fstatSync:()=>M1t,get:()=>l$t,gunzip:()=>y$t,gunzipSync:()=>g$t,gzip:()=>h$t,gzipSync:()=>f$t,hasSubscribers:()=>H$t,homedir:()=>Q1t,hostname:()=>t$t,inflateSync:()=>p$t,inherits:()=>P$t,inspect:()=>N2,isAbsolute:()=>d1t,isBuiltin:()=>_$t,isDeepStrictEqual:()=>L$t,isIP:()=>i2t,isIPv4:()=>s2t,isIPv6:()=>o2t,isMainThread:()=>Y$t,join:()=>s1t,lookup:()=>$$t,mkdir:()=>k7,mkdirSync:()=>O1t,monitorEventLoopDelay:()=>G$t,normalize:()=>g1t,ok:()=>b$t,open:()=>A7,openSync:()=>I1t,parentPort:()=>X$t,parse:()=>E$t,pathToFileURL:()=>I$t,performance:()=>z$t,pipeline:()=>T1t,platform:()=>Z1t,posix:()=>m1t,promises:()=>XFt,promisify:()=>M$t,randomBytes:()=>QFt,randomUUID:()=>e1t,readFile:()=>Qf,readFileSync:()=>_1t,readdir:()=>j1t,readdirSync:()=>D1t,realpath:()=>O2,realpathSync:()=>k1t,relative:()=>u1t,release:()=>a$t,rename:()=>V1t,renameSync:()=>U1t,request:()=>c$t,resolve:()=>i1t,rm:()=>H1t,rmSync:()=>$1t,rmdirSync:()=>F1t,sep:()=>p1t,serialize:()=>K$t,setInterval:()=>p2t,setTimeout:()=>u2t,spawn:()=>K1t,stat:()=>_A,statSync:()=>N1t,strict:()=>T$t,tmpdir:()=>e$t,toUSVString:()=>U$t,totalmem:()=>o$t,type:()=>s$t,types:()=>F$t,unlink:()=>G1t,unlinkSync:()=>L1t,webcrypto:()=>t1t,workerData:()=>Z$t,writeFile:()=>ew,writeFileSync:()=>E1t});var cs,Eo,YFt,XFt,CPe,ZFt,QFt,e1t,t1t,r1t,n1t,o1t,s1t,i1t,a1t,c1t,l1t,u1t,d1t,p1t,m1t,g1t,f1t,h1t,RPe,kPe,y1t,v1t,x1t,b1t,T1t,S1t,w1t,_1t,E1t,C1t,R1t,k1t,A1t,I1t,P1t,M1t,O1t,N1t,D1t,L1t,U1t,F1t,$1t,B1t,z1t,Qf,ew,k7,_A,j1t,G1t,q1t,V1t,H1t,A7,O2,K1t,W1t,J1t,Y1t,X1t,Z1t,Q1t,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,g$t,f$t,h$t,y$t,v$t,x$t,b$t,T$t,S$t,w$t,_$t,E$t,C$t,R$t,k$t,A$t,I$t,P$t,M$t,APe,O$t,N2,N$t,D$t,L$t,U$t,F$t,IPe,M2,$$t,B$t,z$t,j$t,G$t,q$t,V$t,H$t,K$t,W$t,J$t,Y$t,X$t,Z$t,Q$t,e2t,t2t,r2t,n2t,o2t,s2t,i2t,a2t,c2t,l2t,PPe,u2t,d2t,p2t,m2t,g2t,Ml=E(()=>{cs=()=>{},Eo=async()=>{},YFt={},XFt={readFile:Eo,writeFile:Eo,mkdir:Eo,stat:Eo,readdir:Eo,unlink:Eo,access:Eo,rm:Eo,rename:Eo},CPe=r=>{let e=[];return{update(t){return e.push(typeof t=="string"?new M2().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}}},ZFt=(r,e)=>CPe(r),QFt=r=>new Uint8Array(r||32),e1t=()=>globalThis.crypto?.randomUUID?.()||Math.random().toString(36),t1t=globalThis.crypto,r1t=()=>{throw new Error("[NeuroLink:browser] fs.appendFileSync is not supported in browser runtime \u2014 use server-side execution")},n1t=()=>{throw new Error("[NeuroLink:browser] fs.cpSync is not supported in browser runtime \u2014 use server-side execution")},o1t=()=>({listen:cs,close:cs,on:cs}),s1t=(...r)=>r.join("/"),i1t=(...r)=>r.join("/"),a1t=r=>r||"",c1t=r=>r?.split?.("/")?.pop?.()||"",l1t=r=>{let e=r?.match?.(/\.[^.]+$/);return e?e[0]:""},u1t=(r,e)=>e||"",d1t=()=>!1,p1t="/",m1t={normalize:r=>r,join:(...r)=>r.join("/"),resolve:(...r)=>r.join("/"),sep:"/"},g1t=r=>r,f1t=class{on(){return this}off(){return this}emit(){return this}once(){return this}removeListener(){return this}addListener(){return this}},h1t=class{getStore(){}run(r,e,...t){return e(...t)}enterWith(){}disable(){}},RPe=class{pipe(){return this}on(){return this}read(){return null}push(){}destroy(){}},kPe=class{write(){return!0}end(){}on(){return this}destroy(){}},y1t=class{push(){}on(){return this}},v1t=class{on(){return this}},x1t=class{pipe(){return this}on(){return this}},b1t=globalThis.ReadableStream||class{},T1t=cs,S1t=cs,w1t=()=>!1,_1t=()=>"",E1t=cs,C1t=cs,R1t=Eo,k1t=r=>r,A1t=cs,I1t=()=>0,P1t=cs,M1t=()=>({}),O1t=cs,N1t=()=>({}),D1t=()=>[],L1t=cs,U1t=cs,F1t=cs,$1t=cs,B1t=()=>new kPe,z1t=()=>new RPe,Qf=Eo,ew=Eo,k7=Eo,_A=Eo,j1t=Eo,G1t=Eo,q1t=Eo,V1t=Eo,H1t=Eo,A7=async()=>({stat:Eo,readFile:Eo,close:Eo,read:Eo,write:Eo}),O2=async r=>r,K1t=()=>({on:cs,stdout:{on:cs},stderr:{on:cs},kill:cs}),W1t=(r,e)=>e?.(null,"",""),J1t=()=>"",Y1t=(r,e,t)=>{typeof e=="function"?e(null,"",""):t?.(null,"","")},X1t=()=>"",Z1t="browser",Q1t=()=>"/",e$t=()=>"/tmp",t$t=()=>"browser",r$t=()=>[{}],n$t=()=>0,o$t=()=>0,s$t=()=>"Browser",i$t=()=>"wasm",a$t=()=>"0",c$t=()=>({}),l$t=()=>({}),u$t=()=>({}),d$t=()=>({}),p$t=()=>new Uint8Array,m$t=()=>new Uint8Array,g$t=()=>new Uint8Array,f$t=()=>new Uint8Array,h$t=(r,e)=>e?.(null,r),y$t=(r,e)=>e?.(null,r),v$t=()=>({}),x$t=()=>({}),b$t=cs,T$t={},S$t=()=>()=>({}),w$t=[],_$t=()=>!1,E$t=r=>({pathname:r||"",hostname:"",protocol:"",search:"",hash:""}),C$t=()=>"",R$t=globalThis.URL,k$t=globalThis.URLSearchParams,A$t=r=>typeof r=="string"?r.replace("file://",""):r,I$t=r=>new globalThis.URL("file://"+r),P$t=(r,e)=>{e&&(r.super_=e,Object.setPrototypeOf(r.prototype,e.prototype))},M$t=r=>(...e)=>new Promise((t,n)=>r(...e,(o,s)=>o?n(o):t(s))),APe=r=>{let e=(...t)=>{};return e.enabled=!1,e},O$t=APe,N2=r=>{try{return JSON.stringify(r,null,2)}catch{return String(r)}};N2.custom=Symbol.for("nodejs.util.inspect.custom");N2.colors={};N2.styles={};N$t=r=>r,D$t=r=>(...e)=>{let t=e.pop();r(...e).then(n=>t(null,n)).catch(t)},L$t=(r,e)=>JSON.stringify(r)===JSON.stringify(e),U$t=r=>String(r),F$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},IPe=globalThis.TextDecoder,M2=globalThis.TextEncoder,$$t=(r,e)=>e?.(null,"127.0.0.1",4),B$t=class{},z$t=globalThis.performance||{now:()=>Date.now()},j$t=class{observe(){}disconnect(){}},G$t=()=>({enable:cs,disable:cs,percentile:()=>0}),q$t=()=>({}),V$t=class{},H$t=()=>!1,K$t=()=>new Uint8Array,W$t=cs,J$t=class{},Y$t=!0,X$t=null,Z$t=null,Q$t=()=>({}),e2t=class{},t2t=class{},r2t=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 M2().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 M2().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 IPe().decode(this)}},n2t={F_OK:0,R_OK:4,W_OK:2,X_OK:1},o2t=()=>!1,s2t=()=>!1,i2t=()=>0,a2t=class{},c2t=class{},l2t=async()=>new ArrayBuffer(0),PPe=r=>({[Symbol.toPrimitive](){return r},ref(){return this},unref(){return this},hasRef(){return!1},refresh(){return this},close(){}}),u2t=(...r)=>PPe(globalThis.setTimeout(...r)),d2t=globalThis.clearTimeout,p2t=(...r)=>PPe(globalThis.setInterval(...r)),m2t=globalThis.clearInterval,g2t=class{constructor(r){this.type=r}toString(){return this.type}}});var P7={};ce(P7,{Agent:()=>EA,BedrockClient:()=>h2t,BedrockRuntimeClient:()=>v2t,Blob:()=>eBt,Client:()=>rBt,ConverseCommand:()=>x2t,ConverseStreamCommand:()=>b2t,Cron:()=>U2t,Dispatcher:()=>nBt,File:()=>Q2t,FlowProducer:()=>L2t,FormData:()=>Z2t,GoogleAuth:()=>E2t,HTTPException:()=>q2t,Headers:()=>X2t,Hippocampus:()=>A2t,HippocampusConfig:()=>I2t,Hono:()=>j2t,ImageFormat:()=>T2t,InvokeEndpointCommand:()=>w2t,InvokeEndpointWithResponseStreamCommand:()=>_2t,Job:()=>N2t,ListFoundationModelsCommand:()=>y2t,MockAgent:()=>sBt,Pool:()=>tBt,Queue:()=>M2t,QueueScheduler:()=>D2t,Request:()=>J2t,Response:()=>Y2t,SageMakerRuntimeClient:()=>S2t,TextToSpeechClient:()=>R2t,VertexAI:()=>C2t,Webhook:()=>k2t,Worker:()=>O2t,convertToHtml:()=>z2t,cors:()=>G2t,createClient:()=>P2t,default:()=>f2t,extractRawText:()=>B2t,fetch:()=>I7,getGlobalDispatcher:()=>$v,interceptors:()=>Bv,logger:()=>V2t,parseBuffer:()=>F2t,request:()=>zv,secureHeaders:()=>H2t,selectCover:()=>$2t,setGlobalDispatcher:()=>oBt,streamSSE:()=>K2t,timeout:()=>W2t});var tw,ni,f2t,h2t,y2t,v2t,x2t,b2t,T2t,S2t,w2t,_2t,E2t,C2t,R2t,k2t,A2t,I2t,P2t,M2t,O2t,N2t,D2t,L2t,U2t,F2t,$2t,B2t,z2t,j2t,G2t,q2t,V2t,H2t,K2t,W2t,I7,J2t,Y2t,X2t,Z2t,Q2t,eBt,EA,tBt,rBt,nBt,oBt,$v,sBt,Bv,zv,jv=E(()=>{tw={get(r,e){return e==="__esModule"?!0:e==="default"?new Proxy({},{get:tw.get}):new Proxy(function(...t){return new Proxy({},{get:tw.get})},{get:tw.get,apply(t,n,o){return new Proxy({},{get:tw.get})},construct(t,n){return new Proxy({},{get:tw.get})}})}},ni=new Proxy({},tw),f2t=ni,{BedrockClient:h2t,ListFoundationModelsCommand:y2t,BedrockRuntimeClient:v2t,ConverseCommand:x2t,ConverseStreamCommand:b2t,ImageFormat:T2t}=ni,{SageMakerRuntimeClient:S2t,InvokeEndpointCommand:w2t,InvokeEndpointWithResponseStreamCommand:_2t}=ni,{GoogleAuth:E2t,VertexAI:C2t,TextToSpeechClient:R2t}=ni,{Webhook:k2t}=ni,{Hippocampus:A2t,HippocampusConfig:I2t}=ni,{createClient:P2t}=ni,{Queue:M2t,Worker:O2t,Job:N2t,QueueScheduler:D2t,FlowProducer:L2t}=ni,{Cron:U2t}=ni,{parseBuffer:F2t,selectCover:$2t}=ni,{extractRawText:B2t,convertToHtml:z2t}=ni,{Hono:j2t}=ni,{cors:G2t,HTTPException:q2t,logger:V2t,secureHeaders:H2t,streamSSE:K2t,timeout:W2t}=ni,I7=globalThis.fetch,J2t=globalThis.Request,Y2t=globalThis.Response,X2t=globalThis.Headers,Z2t=globalThis.FormData,Q2t=globalThis.File,eBt=globalThis.Blob,EA=ni.Agent,tBt=ni.Pool,rBt=ni.Client,nBt=ni.Dispatcher,oBt=()=>{},$v=()=>ni,sBt=ni.MockAgent,Bv={redirect:()=>r=>r,retry:()=>r=>r},zv=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 CA={};ce(CA,{AsyncLocalStorage:()=>wBt,Buffer:()=>fjt,Channel:()=>ojt,DatabaseSync:()=>gjt,Duplex:()=>EBt,EventEmitter:()=>SBt,Http2ServerRequest:()=>bjt,Http2ServerResponse:()=>Tjt,Interface:()=>mjt,MIMEType:()=>Rjt,PassThrough:()=>CBt,PerformanceObserver:()=>tjt,Readable:()=>MPe,ReadableStream:()=>RBt,Resolver:()=>Qzt,TextDecoder:()=>DPe,TextEncoder:()=>D2,Transform:()=>_Bt,URL:()=>Bzt,URLSearchParams:()=>zzt,Worker:()=>cjt,Writable:()=>OPe,access:()=>tzt,appendFile:()=>NBt,appendFileSync:()=>lBt,arch:()=>xzt,arrayBuffer:()=>Sjt,basename:()=>fBt,builtinModules:()=>Lzt,callbackify:()=>Wzt,channel:()=>njt,chmodSync:()=>OBt,clearInterval:()=>Cjt,clearTimeout:()=>_jt,closeSync:()=>FBt,connect:()=>wzt,constants:()=>hjt,copyFileSync:()=>LBt,cpSync:()=>uBt,cpus:()=>fzt,createConnection:()=>_zt,createGunzip:()=>Pzt,createGzip:()=>Mzt,createHash:()=>oi,createHmac:()=>M7,createInterface:()=>pjt,createReadStream:()=>WBt,createRequire:()=>Dzt,createServer:()=>dBt,createWriteStream:()=>KBt,debug:()=>Hzt,debuglog:()=>NPe,default:()=>iBt,deflateSync:()=>Czt,deprecate:()=>Kzt,deserialize:()=>ajt,dirname:()=>gBt,exec:()=>azt,execFile:()=>lzt,execFileSync:()=>uzt,execSync:()=>czt,existsSync:()=>IBt,extname:()=>hBt,fileURLToPath:()=>jzt,finished:()=>ABt,format:()=>$zt,freemem:()=>hzt,fstatSync:()=>$Bt,get:()=>Szt,gunzip:()=>Izt,gunzipSync:()=>Rzt,gzip:()=>Azt,gzipSync:()=>kzt,hasSubscribers:()=>sjt,homedir:()=>pzt,hostname:()=>gzt,inflateSync:()=>Ezt,inherits:()=>qzt,inspect:()=>L2,isAbsolute:()=>vBt,isBuiltin:()=>Uzt,isDeepStrictEqual:()=>Jzt,isIP:()=>xjt,isIPv4:()=>vjt,isIPv6:()=>yjt,isMainThread:()=>ljt,join:()=>pBt,lookup:()=>Zzt,mkdir:()=>XBt,mkdirSync:()=>BBt,monitorEventLoopDelay:()=>rjt,normalize:()=>TBt,ok:()=>Ozt,open:()=>ozt,openSync:()=>UBt,parentPort:()=>ujt,parse:()=>Fzt,pathToFileURL:()=>Gzt,performance:()=>ejt,pipeline:()=>kBt,platform:()=>dzt,posix:()=>bBt,promises:()=>aBt,promisify:()=>Vzt,randomBytes:()=>bp,randomUUID:()=>We,readFile:()=>JBt,readFileSync:()=>PBt,readdir:()=>QBt,readdirSync:()=>jBt,realpath:()=>szt,realpathSync:()=>DBt,relative:()=>yBt,release:()=>bzt,rename:()=>rzt,renameSync:()=>qBt,request:()=>Tzt,resolve:()=>mBt,rm:()=>nzt,rmSync:()=>HBt,rmdirSync:()=>VBt,sep:()=>xBt,serialize:()=>ijt,setInterval:()=>Ejt,setTimeout:()=>wjt,spawn:()=>izt,stat:()=>ZBt,statSync:()=>zBt,strict:()=>Nzt,tmpdir:()=>mzt,toUSVString:()=>Yzt,totalmem:()=>yzt,type:()=>vzt,types:()=>Xzt,unlink:()=>ezt,unlinkSync:()=>GBt,webcrypto:()=>cBt,workerData:()=>djt,writeFile:()=>YBt,writeFileSync:()=>MBt});var ls,Co,iBt,aBt,oi,M7,bp,We,cBt,lBt,uBt,dBt,pBt,mBt,gBt,fBt,hBt,yBt,vBt,xBt,bBt,TBt,SBt,wBt,MPe,OPe,_Bt,EBt,CBt,RBt,kBt,ABt,IBt,PBt,MBt,OBt,NBt,DBt,LBt,UBt,FBt,$Bt,BBt,zBt,jBt,GBt,qBt,VBt,HBt,KBt,WBt,JBt,YBt,XBt,ZBt,QBt,ezt,tzt,rzt,nzt,ozt,szt,izt,azt,czt,lzt,uzt,dzt,pzt,mzt,gzt,fzt,hzt,yzt,vzt,xzt,bzt,Tzt,Szt,wzt,_zt,Ezt,Czt,Rzt,kzt,Azt,Izt,Pzt,Mzt,Ozt,Nzt,Dzt,Lzt,Uzt,Fzt,$zt,Bzt,zzt,jzt,Gzt,qzt,Vzt,NPe,Hzt,L2,Kzt,Wzt,Jzt,Yzt,Xzt,DPe,D2,Zzt,Qzt,ejt,tjt,rjt,njt,ojt,sjt,ijt,ajt,cjt,ljt,ujt,djt,pjt,mjt,gjt,fjt,hjt,yjt,vjt,xjt,bjt,Tjt,Sjt,LPe,wjt,_jt,Ejt,Cjt,Rjt,or=E(()=>{ls=()=>{},Co=async()=>{},iBt={},aBt={readFile:Co,writeFile:Co,mkdir:Co,stat:Co,readdir:Co,unlink:Co,access:Co,rm:Co,rename:Co},oi=r=>{let e=[];return{update(t){return e.push(typeof t=="string"?new D2().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}}},M7=(r,e)=>oi(r),bp=r=>new Uint8Array(r||32),We=()=>globalThis.crypto?.randomUUID?.()||Math.random().toString(36),cBt=globalThis.crypto,lBt=()=>{throw new Error("[NeuroLink:browser] fs.appendFileSync is not supported in browser runtime \u2014 use server-side execution")},uBt=()=>{throw new Error("[NeuroLink:browser] fs.cpSync is not supported in browser runtime \u2014 use server-side execution")},dBt=()=>({listen:ls,close:ls,on:ls}),pBt=(...r)=>r.join("/"),mBt=(...r)=>r.join("/"),gBt=r=>r||"",fBt=r=>r?.split?.("/")?.pop?.()||"",hBt=r=>{let e=r?.match?.(/\.[^.]+$/);return e?e[0]:""},yBt=(r,e)=>e||"",vBt=()=>!1,xBt="/",bBt={normalize:r=>r,join:(...r)=>r.join("/"),resolve:(...r)=>r.join("/"),sep:"/"},TBt=r=>r,SBt=class{on(){return this}off(){return this}emit(){return this}once(){return this}removeListener(){return this}addListener(){return this}},wBt=class{getStore(){}run(r,e,...t){return e(...t)}enterWith(){}disable(){}},MPe=class{pipe(){return this}on(){return this}read(){return null}push(){}destroy(){}},OPe=class{write(){return!0}end(){}on(){return this}destroy(){}},_Bt=class{push(){}on(){return this}},EBt=class{on(){return this}},CBt=class{pipe(){return this}on(){return this}},RBt=globalThis.ReadableStream||class{},kBt=ls,ABt=ls,IBt=()=>!1,PBt=()=>"",MBt=ls,OBt=ls,NBt=Co,DBt=r=>r,LBt=ls,UBt=()=>0,FBt=ls,$Bt=()=>({}),BBt=ls,zBt=()=>({}),jBt=()=>[],GBt=ls,qBt=ls,VBt=ls,HBt=ls,KBt=()=>new OPe,WBt=()=>new MPe,JBt=Co,YBt=Co,XBt=Co,ZBt=Co,QBt=Co,ezt=Co,tzt=Co,rzt=Co,nzt=Co,ozt=async()=>({stat:Co,readFile:Co,close:Co,read:Co,write:Co}),szt=async r=>r,izt=()=>({on:ls,stdout:{on:ls},stderr:{on:ls},kill:ls}),azt=(r,e)=>e?.(null,"",""),czt=()=>"",lzt=(r,e,t)=>{typeof e=="function"?e(null,"",""):t?.(null,"","")},uzt=()=>"",dzt="browser",pzt=()=>"/",mzt=()=>"/tmp",gzt=()=>"browser",fzt=()=>[{}],hzt=()=>0,yzt=()=>0,vzt=()=>"Browser",xzt=()=>"wasm",bzt=()=>"0",Tzt=()=>({}),Szt=()=>({}),wzt=()=>({}),_zt=()=>({}),Ezt=()=>new Uint8Array,Czt=()=>new Uint8Array,Rzt=()=>new Uint8Array,kzt=()=>new Uint8Array,Azt=(r,e)=>e?.(null,r),Izt=(r,e)=>e?.(null,r),Pzt=()=>({}),Mzt=()=>({}),Ozt=ls,Nzt={},Dzt=()=>()=>({}),Lzt=[],Uzt=()=>!1,Fzt=r=>({pathname:r||"",hostname:"",protocol:"",search:"",hash:""}),$zt=()=>"",Bzt=globalThis.URL,zzt=globalThis.URLSearchParams,jzt=r=>typeof r=="string"?r.replace("file://",""):r,Gzt=r=>new globalThis.URL("file://"+r),qzt=(r,e)=>{e&&(r.super_=e,Object.setPrototypeOf(r.prototype,e.prototype))},Vzt=r=>(...e)=>new Promise((t,n)=>r(...e,(o,s)=>o?n(o):t(s))),NPe=r=>{let e=(...t)=>{};return e.enabled=!1,e},Hzt=NPe,L2=r=>{try{return JSON.stringify(r,null,2)}catch{return String(r)}};L2.custom=Symbol.for("nodejs.util.inspect.custom");L2.colors={};L2.styles={};Kzt=r=>r,Wzt=r=>(...e)=>{let t=e.pop();r(...e).then(n=>t(null,n)).catch(t)},Jzt=(r,e)=>JSON.stringify(r)===JSON.stringify(e),Yzt=r=>String(r),Xzt={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},DPe=globalThis.TextDecoder,D2=globalThis.TextEncoder,Zzt=(r,e)=>e?.(null,"127.0.0.1",4),Qzt=class{},ejt=globalThis.performance||{now:()=>Date.now()},tjt=class{observe(){}disconnect(){}},rjt=()=>({enable:ls,disable:ls,percentile:()=>0}),njt=()=>({}),ojt=class{},sjt=()=>!1,ijt=()=>new Uint8Array,ajt=ls,cjt=class{},ljt=!0,ujt=null,djt=null,pjt=()=>({}),mjt=class{},gjt=class{},fjt=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 D2().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 D2().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 DPe().decode(this)}},hjt={F_OK:0,R_OK:4,W_OK:2,X_OK:1},yjt=()=>!1,vjt=()=>!1,xjt=()=>0,bjt=class{},Tjt=class{},Sjt=async()=>new ArrayBuffer(0),LPe=r=>({[Symbol.toPrimitive](){return r},ref(){return this},unref(){return this},hasRef(){return!1},refresh(){return this},close(){}}),wjt=(...r)=>LPe(globalThis.setTimeout(...r)),_jt=globalThis.clearTimeout,Ejt=(...r)=>LPe(globalThis.setInterval(...r)),Cjt=globalThis.clearInterval,Rjt=class{constructor(r){this.type=r}toString(){return this.type}}});function Hn(r,e=500){return r&&r.slice(0,e).replace(Ijt,"***")}function Tp(r){if(typeof r=="string")return r;try{return JSON.stringify(r)??String(r)}catch{return"[content too large to serialize]"}}function rw(r,e=1e4){try{let t=JSON.stringify(r);return t===void 0?String(r):t.length>e?`${t.slice(0,e)}\u2026[truncated ${t.length-e} chars]`:t}catch(t){return`[unserializable: ${t instanceof Error?t.message:String(t)}]`}}function nr(r){return r.replace(/\/\/[^/\s"'<>]*@/g,"//***@").replace(/\/\/(?:(?!\/\/)[^\s"'<>])*@/g,"//***@")}function qs(r){let e=t=>t.length>200?`${t.slice(0,200)}\u2026`:t;try{let t=new URL(r);return e(`${t.protocol}//${t.host}${t.pathname}`)}catch{let t=r.split(/[?#]/)[0];return e(nr(t))}}function Njt(r){Ojt.forEach(e=>r.searchParams.delete(e))}function Djt(r){let e=[],t=[];for(let[o,s]of r.searchParams.entries())Mjt.includes(o.toLowerCase())&&(e.push(`${o.toLowerCase()}=${s}`),t.push(o));return e.length===0?"":(t.forEach(o=>r.searchParams.delete(o)),e.sort(),`\0auth=${oi("sha256").update(e.join("&")).digest("hex").slice(0,16)}`)}function U2(r){try{let e=new URL(r);Njt(e);let t=Djt(e);return e.toString()+t}catch{return r}}function RA(r){return r.replace(/[a-zA-Z][a-zA-Z0-9+.-]*:\/\/[^\s"'<>)]+/g,e=>qs(e))}function O7(r,e){let t=Cs(e);return r.split(cu(e)).join(t).split(e).join(t)}function eh(r,e){let t=s=>{let i=RA(s);return e?.filePath?O7(i,e.filePath):i};if(!(r instanceof Error))return new Error(t(String(r)));let n=new Error(t(r.message));n.name=r.name;let o=r.code;return o!==void 0&&(n.code=o),n}function nw(r,e=1e3){let t=new WeakSet,n=o=>{if(o==null)return o;if(typeof o=="string")return Hn(o,e);if(typeof o!="object")return o;if(t.has(o))return"[Circular]";if(t.add(o),Array.isArray(o))return o.map(n);let s={};for(let[i,a]of Object.entries(o))Pjt.some(c=>c.toLowerCase()===i.toLowerCase())?s[i]="***":s[i]=n(a);return s};return n(r)}var kjt,Ajt,Ijt,Pjt,Mjt,Ojt,qr=E(()=>{"use strict";or();Wr();kjt=["sk","pk","r8","gsk","xai","tgp","fw","pplx","pa","jina","fish"],Ajt=kjt.join("|"),Ijt=new RegExp(`\\bBearer\\s+[A-Za-z0-9_\\-\\.]{8,}\\b|\\bToken\\s+[A-Za-z0-9_\\-\\.]{8,}\\b|\\bBasic\\s+[A-Za-z0-9+/=]{12,}\\b|\\b(?:${Ajt})[_\\-][A-Za-z0-9_\\-\\.]{8,}\\b|\\b(?:api[_-]?key|access[_-]?token|secret[_-]?key|refresh[_-]?token)\\s*[:=]\\s*['"]?[^\\s,;'"&]+`,"gi"),Pjt=["apikey","api_key","apiKey","access_token","accessToken","refresh_token","refreshToken","secret","secretkey","secret_key","secretKey","password","authorization","oauth","oauthToken","credentials","authContext","authToken","sessionToken","serviceAccountKey","secretAccessKey","userEmail"];Mjt=["token","signature","x-amz-signature","x-amz-credential","x-amz-security-token","awsaccesskeyid","expires","sig","se","sp","sr","sv","x-goog-signature","x-goog-credential","x-goog-algorithm","x-goog-date","x-goog-expires","x-goog-signedheaders"],Ojt=["utm_source","utm_medium","utm_campaign","utm_term","utm_content","fbclid","gclid","_ga"]});var Ljt,N7,F2,D7=E(()=>{"use strict";J();St();Ljt={maxTokens:10,refillIntervalMs:1e3,tokensPerRefill:10,maxQueueSize:100,queueTimeoutMs:3e4},N7=class{tokens;config;queue=[];refillTimer=null;lastRefillTime;constructor(e={}){this.config={...Ljt,...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(he.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)`),he.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(he.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(he.rateLimiterReset()))}}stop(){this.refillTimer&&(clearInterval(this.refillTimer),this.refillTimer=null),this.reset()}},F2=new N7({maxTokens:10,refillIntervalMs:1e3,tokensPerRefill:10,maxQueueSize:100,queueTimeoutMs:3e4})});function z7(r,e=qi.DEFAULT_INITIAL_DELAY,t=qi.DEFAULT_BACKOFF_MULTIPLIER,n=qi.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 j7(r){return new Promise(e=>setTimeout(e,r))}async function UPe(r,e={}){let t={...Ujt,...e},n;for(let o=1;o<=t.maxAttempts;o++)try{return await r()}catch(s){if(n=s,o===t.maxAttempts||!t.retryCondition(s))break;t.onRetry(o,s);let i=z7(o,t.initialDelay,t.backoffMultiplier,t.maxDelay,!0);await j7(i)}throw n}var L7,U7,Ujt,F7,$7,B7,c0n,l0n,u0n,G7=E(()=>{"use strict";J();zs();L7=class extends Error{constructor(t,n){super(t);this.cause=n;this.name="NetworkError"}cause},U7=class extends Error{constructor(t,n){super(t);this.cause=n;this.name="TemporaryError"}cause},Ujt={maxAttempts:qi.DEFAULT_RETRY_ATTEMPTS,initialDelay:qi.DEFAULT_INITIAL_DELAY,maxDelay:qi.DEFAULT_MAX_DELAY,backoffMultiplier:qi.DEFAULT_BACKOFF_MULTIPLIER,retryCondition:r=>{if(r instanceof L7||r instanceof U7||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}`)}};F7=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"}},$7=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 j7(n),this.acquire()}this.requests.push(e)}},B7=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),j7(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 B7,l0n=new F7(3,3e4),u0n=new $7(100,6e4)});var pc,Bm,th,$2,FPe,si,q7=E(()=>{"use strict";pc={IMAGE_MAX_MB:10,PDF_MAX_MB:100,DOCUMENT_MAX_MB:100,WORD_MAX_MB:100,TEXT_MAX_MB:50,CSV_MAX_MB:50,EXCEL_MAX_MB:100,SOURCE_CODE_MAX_MB:20,JSON_MAX_MB:20,YAML_MAX_MB:20,XML_MAX_MB:20,VIDEO_MAX_MB:500,AUDIO_MAX_MB:500,ARCHIVE_MAX_MB:200,GENERAL_MAX_MB:200},Bm={IMAGE_MAX:10*1024*1024,PDF_MAX:100*1024*1024,DOCUMENT_MAX:100*1024*1024,WORD_MAX:100*1024*1024,TEXT_MAX:50*1024*1024,CSV_MAX:50*1024*1024,EXCEL_MAX:100*1024*1024,SOURCE_CODE_MAX:20*1024*1024,JSON_MAX:20*1024*1024,YAML_MAX:20*1024*1024,XML_MAX:20*1024*1024,VIDEO_MAX:500*1024*1024,AUDIO_MAX:500*1024*1024,ARCHIVE_MAX:200*1024*1024,GENERAL_MAX:200*1024*1024},th={MAX_SOURCE_CODE_LINES:1e4,MAX_TEXT_LINES:1e4,MAX_TEXT_LENGTH:1e6,MAX_CSV_ROWS:1e4,MAX_EXCEL_ROWS:5e3,MAX_EXCEL_SHEETS:10,MAX_PDF_PAGES:100,MAX_OBJECT_DEPTH:50,MAX_ARRAY_LENGTH:1e4},$2={MAX_DECOMPRESSED_SIZE:100*1024*1024,MAX_COMPRESSION_RATIO:100,MAX_ENTRIES:1e3,MAX_NESTING_DEPTH:5},FPe={MAX_ALIAS_COUNT:100,MAX_DOCUMENTS:10,MAX_ANCHORS:100},si={IMAGE_MAX_MB:pc.IMAGE_MAX_MB,PDF_MAX_MB:pc.PDF_MAX_MB,DOCUMENT_MAX_MB:pc.DOCUMENT_MAX_MB,WORD_MAX_MB:pc.WORD_MAX_MB,TEXT_MAX_MB:pc.TEXT_MAX_MB,CSV_MAX_MB:pc.CSV_MAX_MB,EXCEL_MAX_MB:pc.EXCEL_MAX_MB,SOURCE_CODE_MAX_MB:pc.SOURCE_CODE_MAX_MB,MAX_FILE_SIZE:Bm.GENERAL_MAX,MAX_IMAGE_SIZE:Bm.IMAGE_MAX,MAX_TEXT_SIZE:Bm.TEXT_MAX,MAX_SOURCE_CODE_LINES:th.MAX_SOURCE_CODE_LINES,MAX_TEXT_LINES:th.MAX_TEXT_LINES,MAX_TEXT_LENGTH:th.MAX_TEXT_LENGTH,MAX_CSV_ROWS:th.MAX_CSV_ROWS,EXCEL_MAX_ROWS:th.MAX_EXCEL_ROWS,EXCEL_MAX_SHEETS:th.MAX_EXCEL_SHEETS,MAX_PDF_PAGES:th.MAX_PDF_PAGES,MAX_DECOMPRESSED_SIZE:$2.MAX_DECOMPRESSED_SIZE,MAX_COMPRESSION_RATIO:$2.MAX_COMPRESSION_RATIO,MAX_ZIP_ENTRIES:$2.MAX_ENTRIES,YAML_MAX_ALIAS_COUNT:FPe.MAX_ALIAS_COUNT}});function B2(r){return V7||(V7=new H7(r)),V7}var H7,V7,K7=E(()=>{"use strict";or();J();qr();H7=class{cache=new Map;contentHashIndex=new Map;maxSize;ttlMs;maxImageSize;enabled;stats={hits:0,misses:0,evictions:0,expirations:0,totalRequests:0};constructor(e={}){let t=process.env.NEUROLINK_IMAGE_CACHE_ENABLED,n=process.env.NEUROLINK_IMAGE_CACHE_SIZE,o=process.env.NEUROLINK_IMAGE_CACHE_TTL_MS,s=process.env.NEUROLINK_IMAGE_MAX_SIZE;this.enabled=t!==void 0?t.toLowerCase()==="true":!1,this.maxSize=this.parseConfigValue(n,e.maxSize,100,1,1e3),this.ttlMs=this.parseConfigValue(o,e.ttlMs,1800*1e3,1e3,1440*60*1e3),this.maxImageSize=this.parseConfigValue(s,e.maxImageSize,10*1024*1024,1024,100*1024*1024),g.debug("ImageCache initialized",{enabled:this.enabled,maxSize:this.maxSize,ttlMs:this.ttlMs,maxImageSize:this.maxImageSize})}parseConfigValue(e,t,n,o,s){let i;if(e!==void 0){let a=parseInt(e,10);i=isNaN(a)?n:a}else t!==void 0?i=t:i=n;return i<o?(g.warn(`Cache config value ${i} below minimum ${o}, using min`),o):i>s?(g.warn(`Cache config value ${i} above maximum ${s}, using max`),s):i}normalizeUrl(e){return U2(e)}generateContentHash(e){let t=typeof e=="string"?Buffer.from(e,"base64"):e;return oi("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:qs(t)}),null):(n.lastAccessedAt=Date.now(),n.accessCount++,this.cache.delete(t),this.cache.set(t,n),this.stats.hits++,g.debug("Image cache hit",{url:qs(t),accessCount:n.accessCount}),n):(this.stats.misses++,g.debug("Image cache miss",{url:qs(t)}),null)}getByContentHash(e){let t=this.contentHashIndex.get(e);if(!t)return null;let n=null;for(let o of[...t]){let s=this.cache.get(o);if(!s){t.delete(o);continue}if(this.isExpired(s)){this.cache.delete(o),t.delete(o);continue}n===null&&(n=o)}return t.size===0&&this.contentHashIndex.delete(e),n?this.get(n):null}set(e,t,n,o){if(!this.enabled){g.debug("Image caching disabled, skipping cache storage");return}let s=this.normalizeUrl(e),i=o.length;if(i>this.maxImageSize){g.debug("Image too large to cache",{url:qs(s),size:i,maxSize:this.maxImageSize});return}let a=this.generateContentHash(o),c=this.contentHashIndex.get(a);if(c)for(let m of c){if(m===s)continue;let f=this.cache.get(m);if(f&&!this.isExpired(f)){for(;this.cache.size>=this.maxSize&&this.cache.size>0;)this.evictOldest();this.cache.set(s,{...f});let h=this.contentHashIndex.get(a);h||(h=new Set,this.contentHashIndex.set(a,h)),h.add(s),g.debug("Image cache dedup hit",{newUrl:qs(s),existingUrl:qs(m)});return}}for(;this.cache.size>=this.maxSize;)this.evictOldest();let l=Date.now(),d={dataUri:t,contentType:n,size:i,contentHash:a,createdAt:l,lastAccessedAt:l,accessCount:1};this.cache.set(s,d);let p=this.contentHashIndex.get(a);p||(p=new Set,this.contentHashIndex.set(a,p)),p.add(s),g.debug("Image cached",{url:qs(s),size:i,contentHash:a.substring(0,8),cacheSize:this.cache.size})}delete(e){let t=this.normalizeUrl(e),n=this.cache.get(t);if(n){let o=this.contentHashIndex.get(n.contentHash);return o&&(o.delete(t),o.size===0&&this.contentHashIndex.delete(n.contentHash)),this.cache.delete(t),!0}return!1}evictOldest(){let e=this.cache.keys().next().value;if(e!==void 0){let t=this.cache.get(e);if(t){let n=this.contentHashIndex.get(t.contentHash);n&&(n.delete(e),n.size===0&&this.contentHashIndex.delete(t.contentHash))}this.cache.delete(e),this.stats.evictions++,g.debug("Image cache eviction",{url:qs(String(e))})}}evictExpired(){let e=0,t=Date.now();for(let[n,o]of this.cache.entries())t-o.createdAt>this.ttlMs&&(this.delete(n),e++,this.stats.expirations++);return e>0&&g.debug(`Evicted ${e} expired image cache entries`),e}clear(){let e=this.cache.size;this.cache.clear(),this.contentHashIndex.clear(),g.debug(`Image cache cleared (${e} entries removed)`)}getStats(){let e=0;for(let n of this.cache.values())e+=n.size;let t=this.stats.totalRequests>0?Number((this.stats.hits/this.stats.totalRequests*100).toFixed(2)):0;return{...this.stats,size:this.cache.size,totalBytes:e,hitRate:t}}has(e){let t=this.normalizeUrl(e),n=this.cache.get(t);return n!=null&&!this.isExpired(n)}getSize(){return this.cache.size}getConfig(){return{enabled:this.enabled,maxSize:this.maxSize,ttlMs:this.ttlMs,maxImageSize:this.maxImageSize}}},V7=null});function ow(r){return r.length>=8&&r[4]===102&&r[5]===116&&r[6]===121&&r[7]===112}function $jt(r){let e=new Set;if(r.length<20)return e;let t=r.readUInt32BE(0),n=t===0?r.length:Math.min(r.length,t);for(let o=16;o+4<=n;o+=4)e.add(r.toString("latin1",o,o+4));return e}function zPe(r,e){for(let t of r)if(e.has(t))return!0;return!1}function z2(r){if(r.length<12||!ow(r))return null;let e=r.toString("latin1",8,12);if($Pe.has(e))return"image/avif";if(BPe.has(e))return"image/heic";if(!Fjt.has(e))return null;let t=$jt(r);return zPe(t,BPe)?"image/heif":zPe(t,$Pe)?"image/avif":null}var $Pe,BPe,Fjt,W7=E(()=>{"use strict";$Pe=new Set(["avif","avis","avio"]),BPe=new Set(["heic","heix","hevc","hevx","heim","heis","hevm","hevs"]),Fjt=new Set(["mif1","msf1"])});function jjt(r){if(r&&typeof r=="object"){let e=r.code,t=r.name;if(zjt.has(e||"")||t==="AbortError")return!0}if(r instanceof Error){let e=r.message,t=e.match(/HTTP (\d{3}):/);if(t){let n=parseInt(t[1],10);return n>=500||n===429||n===408}if(/\b(request timed out|operation timed out|connection timed out|timed out)\b/i.test(e)||/\bnetwork (error|failure|unreachable|down)\b/i.test(e))return!0}return!1}function J7(r){if(r==="application/octet-stream")throw g.error("Unable to detect a supported image format from file content"),new Error("Unsupported or corrupted image: no known image signature (PNG/JPEG/GIF/WebP/BMP/TIFF/ICO/SVG/AVIF/HEIC/HEIF) was found in the file content.")}var jPe,Bjt,zjt,Ol,Gjt,qjt,kA,j2=E(()=>{"use strict";Wr();J();qr();D7();G7();zs();q7();K7();St();W7();jPe=12,Bjt={"image/png":67,"image/jpeg":125,"image/gif":43,"image/webp":20,"image/avif":100},zjt=new Set(["ECONNRESET","ENOTFOUND","ECONNREFUSED","ETIMEDOUT","ERR_NETWORK"]);Ol=class r{static async process(e,t){let n=this.validateBufferNotEmpty(e);J7(n);let o=r.safeBase64Convert(e,"image processing"),s=`data:${n};base64,${o}`;return this.validateProcessOutput(s,o,n),{type:"image",content:s,mimeType:n,metadata:{confidence:100,size:e.length}}}static hasStrictImageMagic(e,t){let n=e;switch(t){case"image/png":return n.length>=4&&n[0]===137&&n[1]===80&&n[2]===78&&n[3]===71;case"image/jpeg":return n.length>=3&&n[0]===255&&n[1]===216&&n[2]===255;case"image/gif":return n.length>=3&&n[0]===71&&n[1]===73&&n[2]===70;case"image/webp":return n.length>=12&&n.subarray(0,4).toString("latin1")==="RIFF"&&n.subarray(8,12).toString("latin1")==="WEBP";case"image/avif":return n.length>=12&&n.subarray(4,8).toString("latin1")==="ftyp"&&n.subarray(8,12).toString("latin1").startsWith("avif");default:return!1}}static validateBufferNotEmpty(e){if(e.length===0)throw g.error("Empty buffer provided"),he.imageBufferInvalid("Invalid image processing: buffer is empty");let t=this.detectImageType(e);if(t==="image/svg+xml")return t;if(e.length<jPe)throw he.imageBufferInvalid(`Invalid image processing: buffer too small (${e.length} bytes) \u2014 a minimum of ${jPe} bytes is required for a valid image.`);let n=Bjt[t];if(n!==void 0&&e.length<n&&this.hasStrictImageMagic(e,t))throw he.imageBufferInvalid(`Invalid image processing: ${t} buffer is truncated (${e.length} bytes, minimum ${n} for a valid ${t}).`);return t}static validateProcessOutput(e,t,n){if(t.length===0)throw g.error("Empty base64 content generated"),new Error("Invalid image processing: base64 content is empty");if(!/^data:[^;]+;base64,[A-Za-z0-9+/]*={0,2}$/.test(e))throw g.error("Invalid data URI format generated",{dataUri:e}),new Error("Invalid data URI format: must be data:{mimeType};base64,{content}");if(!this.validateImageFormat(n))throw g.error("Invalid MIME type generated",{mediaType:n}),new Error(`Invalid MIME type: ${n} is not in allowed list`)}static processImageForOpenAI(e){try{return typeof e=="string"?e.startsWith("http")||e.startsWith("data:")?e:`data:image/jpeg;base64,${e}`:`data:image/jpeg;base64,${r.safeBase64Convert(e,"OpenAI image input")}`}catch(t){throw t instanceof Ne?t:(g.error("Failed to process image for OpenAI:",t),new Error(`Image processing failed for OpenAI: ${t instanceof Error?t.message:"Unknown error"}`,{cause:t}))}}static processImageForGoogle(e){try{let t,n="image/jpeg";if(typeof e=="string")if(e.startsWith("data:")){let o=e.match(/^data:([^;]+);base64,(.+)$/);o?(n=o[1],t=o[2]):t=e.split(",")[1]||e}else t=e;else t=r.safeBase64Convert(e,"provider image input");return{mimeType:n,data:t}}catch(t){throw t instanceof Ne?t:(g.error("Failed to process image for Google AI:",t),new Error(`Image processing failed for Google AI: ${t instanceof Error?t.message:"Unknown error"}`,{cause:t}))}}static processImageForAnthropic(e){try{let t,n="image/jpeg";if(typeof e=="string")if(e.startsWith("data:")){let o=e.match(/^data:([^;]+);base64,(.+)$/);o?(n=o[1],t=o[2]):t=e.split(",")[1]||e}else t=e;else t=r.safeBase64Convert(e,"provider image input");return{mediaType:n,data:t}}catch(t){throw t instanceof Ne?t:(g.error("Failed to process image for Anthropic:",t),new Error(`Image processing failed for Anthropic: ${t instanceof Error?t.message:"Unknown error"}`,{cause:t}))}}static processImageForVertex(e,t){try{return t.includes("gemini")?r.processImageForGoogle(e):t.includes("claude")?r.processImageForAnthropic(e):r.processImageForGoogle(e)}catch(n){throw n instanceof Ne?n:(g.error("Failed to process image for Vertex AI:",n),new Error(`Image processing failed for Vertex AI: ${n instanceof Error?n.message:"Unknown error"}`,{cause:n}))}}static detectImageType(e){try{if(typeof e=="string"){if(e.startsWith("data:")){let o=e.match(/^data:([^;]+);/);return o?o[1]:"image/jpeg"}let t=e.toLowerCase().split(".").pop();return{jpg:"image/jpeg",jpeg:"image/jpeg",png:"image/png",gif:"image/gif",webp:"image/webp",bmp:"image/bmp",tiff:"image/tiff",tif:"image/tiff",svg:"image/svg+xml",avif:"image/avif"}[t||""]||"image/jpeg"}if(e.length>=4){let t=e.subarray(0,4);if(t[0]===137&&t[1]===80&&t[2]===78&&t[3]===71)return"image/png";if(t[0]===255&&t[1]===216&&t[2]===255)return"image/jpeg";if(t[0]===71&&t[1]===73&&t[2]===70&&t[3]===56)return"image/gif";if(e.length>=12){let o=e.subarray(0,4),s=e.subarray(8,12);if(o.toString()==="RIFF"&&s.toString()==="WEBP")return"image/webp"}if(e.length>=4){let o=e.subarray(0,4).toString();if(o==="<svg"||o==="<?xm")return"image/svg+xml"}let n=z2(e);if(n)return n;if(e[0]===0&&e[1]===0&&e[2]===1&&e[3]===0&&!ow(e))return"image/x-icon";if(e[0]===66&&e[1]===77)return"image/bmp";if(e[0]===73&&e[1]===73&&e[2]===42&&e[3]===0||e[0]===77&&e[1]===77&&e[2]===0&&e[3]===42)return"image/tiff"}return g.warn("Could not detect image type from magic bytes; using application/octet-stream"),"application/octet-stream"}catch(t){return g.warn("Failed to detect image type, using default:",t),"application/octet-stream"}}static validateSize(e,t,n=Bm.IMAGE_MAX){if(!Number.isFinite(n)||n<0)throw he.invalidConfiguration("maxSize","must be a finite, non-negative byte count",{maxSize:n,context:t});if(!Number.isFinite(e)||e<0)throw he.invalidImageSize(e);if(e>n){let o=(e/1048576).toFixed(1),s=(n/(1024*1024)).toFixed(0);throw he.imageTooLarge(o,s)}}static validateBufferSize(e,t,n=Bm.IMAGE_MAX){r.validateSize(e.length,t,n)}static safeBase64Convert(e,t,n=Bm.IMAGE_MAX){return r.validateBufferSize(e,t,n),e.toString("base64")}static validateImageFormat(e){return["image/jpeg","image/png","image/gif","image/webp","image/bmp","image/tiff","image/svg+xml","image/avif"].includes(e.toLowerCase())}static getImageDimensions(e){try{if(e.length>=24&&e.subarray(0,8).toString("hex")==="89504e470d0a1a0a"){let t=e.readUInt32BE(16),n=e.readUInt32BE(20);return{width:t,height:n}}if(e.length>=4&&e[0]===255&&e[1]===216){let t=2;for(;t<e.length-1;){if(e[t]!==255){t++;continue}for(;t<e.length&&e[t]===255;)t++;if(t>=e.length)break;let n=e[t];if(t++,n===192||n===194){if(t+7>e.length)break;let s=e.readUInt16BE(t+3);return{width:e.readUInt16BE(t+5),height:s}}if(n===208||n===209||n===210||n===211||n===212||n===213||n===214||n===215||n===216||n===217||n===1)continue;if(t+2>e.length)break;let o=e.readUInt16BE(t);t+=o}return null}return null}catch(t){return g.warn("Failed to extract image dimensions:",t),null}}static processImage(e,t,n){try{Buffer.isBuffer(e)&&r.validateBufferSize(e,"image processing");let o=r.detectImageType(e);J7(o);let s=typeof e=="string"?Buffer.byteLength(e,"base64"):e.length,i,a;switch(t.toLowerCase()){case"openai":i=r.processImageForOpenAI(e),a="data_uri";break;case"google-ai":case"google":{i=r.processImageForGoogle(e).data,a="base64";break}case"anthropic":{i=r.processImageForAnthropic(e).data,a="base64";break}case"vertex":{i=r.processImageForVertex(e,n||"").data,a="base64";break}default:typeof e=="string"?i=e.startsWith("data:")&&e.split(",")[1]||e:i=r.safeBase64Convert(e,"image input"),a="base64"}return{data:i,mediaType:o,size:s,format:a}}catch(o){throw o instanceof Ne?o:(g.error(`Failed to process image for ${t}:`,o),new Error(`Image processing failed: ${o instanceof Error?o.message:"Unknown error"}`,{cause:o}))}}},Gjt=["jpg","jpeg","png","gif","webp","bmp","tiff","tif","svg","avif","ico","heic","heif"],qjt=new Set(Gjt),kA={isDataUri:r=>typeof r=="string"&&r.startsWith("data:")&&r.includes("base64,"),isUrl:r=>{try{return new URL(r),r.startsWith("http://")||r.startsWith("https://")}catch{return!1}},isBase64:r=>kA.isValidBase64(r),getFileExtension:r=>{let t=r.split(/[?#]/)[0].match(/\.([^.]+)$/);if(!t)return null;let n=t[1].toLowerCase();return/^[a-z0-9]+$/.test(n)?n:null},isValidImageExtension:r=>{if(!r||typeof r!="string")return!1;let e=r.toLowerCase();return/^[a-z0-9]+$/.test(e)?qjt.has(e):!1},getValidatedImageExtension:r=>{let e=kA.getFileExtension(r);return e&&kA.isValidImageExtension(e)?e:null},formatFileSize:r=>{if(r===0)return"0 Bytes";let e=1024,t=["Bytes","KB","MB","GB"],n=Math.floor(Math.log(r)/Math.log(e));return parseFloat((r/Math.pow(e,n)).toFixed(2))+" "+t[n]},bufferToBase64:(r,e=Bm.IMAGE_MAX)=>Ol.safeBase64Convert(r,"buffer-to-base64",e),base64ToBuffer:r=>{let e=r.includes(",")?r.split(",")[1]:r;return Buffer.from(e,"base64")},redactPathFromMessage:O7,fileToBase64DataUri:async(r,e=10*1024*1024)=>{try{let t=await Promise.resolve().then(()=>(Ml(),$m)),n=await t.stat(r);if(!n.isFile())throw new Error("Not a file");if(n.size>e)throw new Error(`File too large: ${n.size} bytes (max: ${e} bytes)`);let o=await t.readFile(r),s=Ol.detectImageType(o)||Ol.detectImageType(r);J7(s);let i=o.toString("base64");return`data:${s};base64,${i}`}catch(t){g.debug("fileToBase64DataUri failed",{filePath:r,error:t});let n=Cs(r),o=eh(t,{filePath:r}),s=t instanceof Error?o.message:"Unknown error";throw new Error(`Failed to convert file to base64 (${n}): ${s}`,{cause:o})}},urlToBase64DataUri:async(r,{timeoutMs:e=15e3,maxBytes:t=10*1024*1024,maxAttempts:n=3}={})=>{let o=B2(),s=o.get(r);if(s)return g.debug("Using cached image for URL",{url:qs(r)}),s.dataUri;if(await F2.acquire(),!/^https?:\/\//i.test(r))throw new Error("Unsupported protocol");let i=async()=>{let a=new AbortController,c=setTimeout(()=>a.abort(),e);try{let l=await fetch(r,{signal:a.signal});if(!l.ok)throw new Error(`HTTP ${l.status}: ${l.statusText}`);let d=l.headers.get("content-type")||"";if(!/^image\//i.test(d))throw new Error(`Unsupported content-type: ${d||"unknown"}`);let p=l.headers.get("content-length"),m=Number(p||0);if(p!==null&&m===0)throw new Error("Empty response: content-length is 0");if(m&&m>t)throw new Error(`Content too large: ${m} bytes`);let f=await l.arrayBuffer();if(f.byteLength>t)throw new Error(`Downloaded content too large: ${f.byteLength} bytes`);let h=Buffer.from(f),y=h.toString("base64"),v=`data:${d||"image/jpeg"};base64,${y}`;return o.set(r,v,d||"image/jpeg",h),v}finally{clearTimeout(c)}};try{return await UPe(i,{maxAttempts:n,initialDelay:qi.DEFAULT_INITIAL_DELAY,backoffMultiplier:qi.DEFAULT_BACKOFF_MULTIPLIER,maxDelay:qi.DEFAULT_MAX_DELAY,retryCondition:jjt,onRetry:(a,c)=>{let l=RA(c instanceof Error?c.message:String(c)),d=n-a;g.warn(`\u26A0\uFE0F Image download attempt ${a} failed for ${qs(r)}: ${l}. ${d} ${d===1?"attempt":"attempts"} remaining...`)}})}catch(a){let c=qs(r),l=eh(a);throw new Error(`Failed to download and convert URL to base64 (${c}): ${l.message}`,{cause:l})}},extractBase64FromDataUri:r=>r.includes(",")?r.split(",")[1]:r,extractMimeTypeFromDataUri:r=>{let e=r.match(/^data:([^;]+);base64,/);return e?e[1]:"image/jpeg"},createDataUri:(r,e="image/jpeg")=>{let t=r.includes(",")?r.split(",")[1]:r;return`data:${e};base64,${t}`},isValidBase64:r=>{try{let e=r.includes(",")?r.split(",")[1]:r;if(!e||e.length===0||!/^[A-Za-z0-9+/]*={0,2}$/.test(e)||e.length%4!==0)return!1;let n=e.indexOf("=");if(n!==-1){if(n<e.length-2)return!1;let a=e.slice(n);if(!/^=+$/.test(a))return!1}let s=Buffer.from(e,"base64").toString("base64"),i=a=>a.replace(/=+$/,"");return i(e)===i(s)}catch{return!1}},getBase64Size:r=>{let e=r.includes(",")?r.split(",")[1]:r;return Buffer.byteLength(e,"base64")},compressBase64:(r,e=.8)=>(g.warn("Base64 compression not implemented - returning original"),r)}});function Kjt(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 rh,AA,Vjt,GPe,Hjt,Y7,sw,qPe=E(()=>{"use strict";j2();J();rh=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))}},AA={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},Vjt=new Set(["litellm","openrouter"]),GPe=[/claude-(?:opus|sonnet|haiku)-(?:[4-9]|\d{2,})/i,/claude-(?:fable|mythos)-\d/i],Hjt={anthropic:GPe,vertex:GPe};Y7={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:[]},sw=class{static validateImageCount(e,t,n){let o=t.toLowerCase(),s;if(o==="vertex"&&n)n.includes("claude")?s=AA.vertex.claude:n.includes("gemini")?s=AA.vertex.gemini:s=AA.vertex.default;else{let a=o in AA?AA[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:Ol.detectImageType(s)})}),n}static supportsVision(e,t){try{let n=Kjt(e);if(n==="anthropic"&&process.env.ANTHROPIC_BASE_URL)return!0;let o=Y7[n];if(!o||o.length===0)return!1;if(!t)return!0;let s=o.some(i=>t.toLowerCase().includes(i.toLowerCase()));return!s&&Hjt[n]?.some(i=>i.test(t))||!s&&Vjt.has(n)?!0:s}catch{return!1}}static getSupportedModels(e){let t=e.toLowerCase(),n=Y7[t];return n?[...n]:[]}static getVisionProviders(){return Object.entries(Y7).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 VPe(){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 X7,Z7,Q7=E(()=>{"use strict";X7=`
830
830
 
831
831
  IMPORTANT: You are continuing an ongoing conversation. The previous messages in this conversation contain important context including:
@@ -1040,7 +1040,7 @@ Reasoning: [Provide a detailed explanation of your evaluation, explaining why yo
1040
1040
  Known schemas:
1041
1041
  - ${Object.keys(n).join(`
1042
1042
  - `)}`,new Error(Re)}let He=`${a}/$ref`,Be=uo(r,ge,t,n,o,s,i,He,c);if(Be.valid||Te.push({instanceLocation:i,keyword:"$ref",keywordLocation:He,error:"A subschema had errors."},...Be.errors),t==="4"||t==="7")return{valid:Te.length===0,errors:Te}}if(Array.isArray(h)){let Ge=h.length,ge=!1;for(let He=0;He<Ge;He++)if(d===h[He]||h[He]==="integer"&&d==="number"&&r%1===0&&r===r){ge=!0;break}ge||Te.push({instanceLocation:i,keyword:"type",keywordLocation:`${a}/type`,error:`Instance type "${d}" is invalid. Expected "${h.join('", "')}".`})}else h==="integer"?(d!=="number"||r%1||r!==r)&&Te.push({instanceLocation:i,keyword:"type",keywordLocation:`${a}/type`,error:`Instance type "${d}" is invalid. Expected "${h}".`}):h!==void 0&&d!==h&&Te.push({instanceLocation:i,keyword:"type",keywordLocation:`${a}/type`,error:`Instance type "${d}" is invalid. Expected "${h}".`});if(y!==void 0&&(d==="object"||d==="array"?Qv(r,y)||Te.push({instanceLocation:i,keyword:"const",keywordLocation:`${a}/const`,error:`Instance does not match ${JSON.stringify(y)}.`}):r!==y&&Te.push({instanceLocation:i,keyword:"const",keywordLocation:`${a}/const`,error:`Instance does not match ${JSON.stringify(y)}.`})),v!==void 0&&(d==="object"||d==="array"?v.some(Ge=>Qv(r,Ge))||Te.push({instanceLocation:i,keyword:"enum",keywordLocation:`${a}/enum`,error:`Instance does not match any of ${JSON.stringify(v)}.`}):v.some(Ge=>r===Ge)||Te.push({instanceLocation:i,keyword:"enum",keywordLocation:`${a}/enum`,error:`Instance does not match any of ${JSON.stringify(v)}.`})),S!==void 0){let Ge=`${a}/not`;uo(r,S,t,n,o,s,i,Ge).valid&&Te.push({instanceLocation:i,keyword:"not",keywordLocation:Ge,error:'Instance matched "not" schema.'})}let Ze=[];if(w!==void 0){let Ge=`${a}/anyOf`,ge=Te.length,He=!1;for(let Be=0;Be<w.length;Be++){let Re=w[Be],Ye=Object.create(c),_=uo(r,Re,t,n,o,f===!0?s:null,i,`${Ge}/${Be}`,Ye);Te.push(..._.errors),He=He||_.valid,_.valid&&Ze.push(Ye)}He?Te.length=ge:Te.splice(ge,0,{instanceLocation:i,keyword:"anyOf",keywordLocation:Ge,error:"Instance does not match any subschemas."})}if(C!==void 0){let Ge=`${a}/allOf`,ge=Te.length,He=!0;for(let Be=0;Be<C.length;Be++){let Re=C[Be],Ye=Object.create(c),_=uo(r,Re,t,n,o,f===!0?s:null,i,`${Ge}/${Be}`,Ye);Te.push(..._.errors),He=He&&_.valid,_.valid&&Ze.push(Ye)}He?Te.length=ge:Te.splice(ge,0,{instanceLocation:i,keyword:"allOf",keywordLocation:Ge,error:"Instance does not match every subschema."})}if(R!==void 0){let Ge=`${a}/oneOf`,ge=Te.length,He=R.filter((Be,Re)=>{let Ye=Object.create(c),_=uo(r,Be,t,n,o,f===!0?s:null,i,`${Ge}/${Re}`,Ye);return Te.push(..._.errors),_.valid&&Ze.push(Ye),_.valid}).length;He===1?Te.length=ge:Te.splice(ge,0,{instanceLocation:i,keyword:"oneOf",keywordLocation:Ge,error:`Instance does not match exactly one subschema (${He} matches).`})}if((d==="object"||d==="array")&&Object.assign(c,...Ze),k!==void 0){let Ge=`${a}/if`;if(uo(r,k,t,n,o,s,i,Ge,c).valid){if(I!==void 0){let He=uo(r,I,t,n,o,s,i,`${a}/then`,c);He.valid||Te.push({instanceLocation:i,keyword:"if",keywordLocation:Ge,error:'Instance does not match "then" schema.'},...He.errors)}}else if(A!==void 0){let He=uo(r,A,t,n,o,s,i,`${a}/else`,c);He.valid||Te.push({instanceLocation:i,keyword:"if",keywordLocation:Ge,error:'Instance does not match "else" schema.'},...He.errors)}}if(d==="object"){if(b!==void 0)for(let Be of b)Be in r||Te.push({instanceLocation:i,keyword:"required",keywordLocation:`${a}/required`,error:`Instance does not have required property "${Be}".`});let Ge=Object.keys(r);if($!==void 0&&Ge.length<$&&Te.push({instanceLocation:i,keyword:"minProperties",keywordLocation:`${a}/minProperties`,error:`Instance does not have at least ${$} properties.`}),H!==void 0&&Ge.length>H&&Te.push({instanceLocation:i,keyword:"maxProperties",keywordLocation:`${a}/maxProperties`,error:`Instance does not have at least ${H} properties.`}),j!==void 0){let Be=`${a}/propertyNames`;for(let Re in r){let Ye=`${i}/${Jc(Re)}`,_=uo(Re,j,t,n,o,s,Ye,Be);_.valid||Te.push({instanceLocation:i,keyword:"propertyNames",keywordLocation:Be,error:`Property name "${Re}" does not match schema.`},..._.errors)}}if(F!==void 0){let Be=`${a}/dependantRequired`;for(let Re in F)if(Re in r){let Ye=F[Re];for(let _ of Ye)_ in r||Te.push({instanceLocation:i,keyword:"dependentRequired",keywordLocation:Be,error:`Instance has "${Re}" but does not have "${_}".`})}}if(N!==void 0)for(let Be in N){let Re=`${a}/dependentSchemas`;if(Be in r){let Ye=uo(r,N[Be],t,n,o,s,i,`${Re}/${Jc(Be)}`,c);Ye.valid||Te.push({instanceLocation:i,keyword:"dependentSchemas",keywordLocation:Re,error:`Instance has "${Be}" but does not match dependant schema.`},...Ye.errors)}}if(W!==void 0){let Be=`${a}/dependencies`;for(let Re in W)if(Re in r){let Ye=W[Re];if(Array.isArray(Ye))for(let _ of Ye)_ in r||Te.push({instanceLocation:i,keyword:"dependencies",keywordLocation:Be,error:`Instance has "${Re}" but does not have "${_}".`});else{let _=uo(r,Ye,t,n,o,s,i,`${Be}/${Jc(Re)}`);_.valid||Te.push({instanceLocation:i,keyword:"dependencies",keywordLocation:Be,error:`Instance has "${Re}" but does not match dependant schema.`},..._.errors)}}}let ge=Object.create(null),He=!1;if(M!==void 0){let Be=`${a}/properties`;for(let Re in M){if(!(Re in r))continue;let Ye=`${i}/${Jc(Re)}`,_=uo(r[Re],M[Re],t,n,o,s,Ye,`${Be}/${Jc(Re)}`);if(_.valid)c[Re]=ge[Re]=!0;else if(He=o,Te.push({instanceLocation:i,keyword:"properties",keywordLocation:Be,error:`Property "${Re}" does not match schema.`},..._.errors),He)break}}if(!He&&D!==void 0){let Be=`${a}/patternProperties`;for(let Re in D){let Ye=new RegExp(Re,"u"),_=D[Re];for(let z in r){if(!Ye.test(z))continue;let X=`${i}/${Jc(z)}`,q=uo(r[z],_,t,n,o,s,X,`${Be}/${Jc(Re)}`);q.valid?c[z]=ge[z]=!0:(He=o,Te.push({instanceLocation:i,keyword:"patternProperties",keywordLocation:Be,error:`Property "${z}" matches pattern "${Re}" but does not match associated schema.`},...q.errors))}}}if(!He&&B!==void 0){let Be=`${a}/additionalProperties`;for(let Re in r){if(ge[Re])continue;let Ye=`${i}/${Jc(Re)}`,_=uo(r[Re],B,t,n,o,s,Ye,Be);_.valid?c[Re]=!0:(He=o,Te.push({instanceLocation:i,keyword:"additionalProperties",keywordLocation:Be,error:`Property "${Re}" does not match additional properties schema.`},..._.errors))}}else if(!He&&L!==void 0){let Be=`${a}/unevaluatedProperties`;for(let Re in r)if(!c[Re]){let Ye=`${i}/${Jc(Re)}`,_=uo(r[Re],L,t,n,o,s,Ye,Be);_.valid?c[Re]=!0:Te.push({instanceLocation:i,keyword:"unevaluatedProperties",keywordLocation:Be,error:`Property "${Re}" does not match unevaluated properties schema.`},..._.errors)}}}else if(d==="array"){we!==void 0&&r.length>we&&Te.push({instanceLocation:i,keyword:"maxItems",keywordLocation:`${a}/maxItems`,error:`Array has too many items (${r.length} > ${we}).`}),$e!==void 0&&r.length<$e&&Te.push({instanceLocation:i,keyword:"minItems",keywordLocation:`${a}/minItems`,error:`Array has too few items (${r.length} < ${$e}).`});let Ge=r.length,ge=0,He=!1;if(te!==void 0){let Be=`${a}/prefixItems`,Re=Math.min(te.length,Ge);for(;ge<Re;ge++){let Ye=uo(r[ge],te[ge],t,n,o,s,`${i}/${ge}`,`${Be}/${ge}`);if(c[ge]=!0,!Ye.valid&&(He=o,Te.push({instanceLocation:i,keyword:"prefixItems",keywordLocation:Be,error:"Items did not match schema."},...Ye.errors),He))break}}if(K!==void 0){let Be=`${a}/items`;if(Array.isArray(K)){let Re=Math.min(K.length,Ge);for(;ge<Re;ge++){let Ye=uo(r[ge],K[ge],t,n,o,s,`${i}/${ge}`,`${Be}/${ge}`);if(c[ge]=!0,!Ye.valid&&(He=o,Te.push({instanceLocation:i,keyword:"items",keywordLocation:Be,error:"Items did not match schema."},...Ye.errors),He))break}}else for(;ge<Ge;ge++){let Re=uo(r[ge],K,t,n,o,s,`${i}/${ge}`,Be);if(c[ge]=!0,!Re.valid&&(He=o,Te.push({instanceLocation:i,keyword:"items",keywordLocation:Be,error:"Items did not match schema."},...Re.errors),He))break}if(!He&&se!==void 0){let Re=`${a}/additionalItems`;for(;ge<Ge;ge++){let Ye=uo(r[ge],se,t,n,o,s,`${i}/${ge}`,Re);c[ge]=!0,Ye.valid||(He=o,Te.push({instanceLocation:i,keyword:"additionalItems",keywordLocation:Re,error:"Items did not match additional items schema."},...Ye.errors))}}}if(G!==void 0)if(Ge===0&&le===void 0)Te.push({instanceLocation:i,keyword:"contains",keywordLocation:`${a}/contains`,error:"Array is empty. It must contain at least one item matching the schema."});else if(le!==void 0&&Ge<le)Te.push({instanceLocation:i,keyword:"minContains",keywordLocation:`${a}/minContains`,error:`Array has less items (${Ge}) than minContains (${le}).`});else{let Be=`${a}/contains`,Re=Te.length,Ye=0;for(let _=0;_<Ge;_++){let z=uo(r[_],G,t,n,o,s,`${i}/${_}`,Be);z.valid?(c[_]=!0,Ye++):Te.push(...z.errors)}Ye>=(le||0)&&(Te.length=Re),le===void 0&&ue===void 0&&Ye===0?Te.splice(Re,0,{instanceLocation:i,keyword:"contains",keywordLocation:Be,error:"Array does not contain item matching schema."}):le!==void 0&&Ye<le?Te.push({instanceLocation:i,keyword:"minContains",keywordLocation:`${a}/minContains`,error:`Array must contain at least ${le} items matching schema. Only ${Ye} items were found.`}):ue!==void 0&&Ye>ue&&Te.push({instanceLocation:i,keyword:"maxContains",keywordLocation:`${a}/maxContains`,error:`Array may contain at most ${ue} items matching schema. ${Ye} items were found.`})}if(!He&&_e!==void 0){let Be=`${a}/unevaluatedItems`;for(ge;ge<Ge;ge++){if(c[ge])continue;let Re=uo(r[ge],_e,t,n,o,s,`${i}/${ge}`,Be);c[ge]=!0,Re.valid||Te.push({instanceLocation:i,keyword:"unevaluatedItems",keywordLocation:Be,error:"Items did not match unevaluated items schema."},...Re.errors)}}if(Z)for(let Be=0;Be<Ge;Be++){let Re=r[Be],Ye=typeof Re=="object"&&Re!==null;for(let _=0;_<Ge;_++){if(Be===_)continue;let z=r[_];(Re===z||Ye&&(typeof z=="object"&&z!==null)&&Qv(Re,z))&&(Te.push({instanceLocation:i,keyword:"uniqueItems",keywordLocation:`${a}/uniqueItems`,error:`Duplicate items at indexes ${Be} and ${_}.`}),Be=Number.MAX_SAFE_INTEGER,_=Number.MAX_SAFE_INTEGER)}}}else if(d==="number"){if(t==="4"?(ee!==void 0&&(re===!0&&r<=ee||r<ee)&&Te.push({instanceLocation:i,keyword:"minimum",keywordLocation:`${a}/minimum`,error:`${r} is less than ${re?"or equal to ":""} ${ee}.`}),Y!==void 0&&(O===!0&&r>=Y||r>Y)&&Te.push({instanceLocation:i,keyword:"maximum",keywordLocation:`${a}/maximum`,error:`${r} is greater than ${O?"or equal to ":""} ${Y}.`})):(ee!==void 0&&r<ee&&Te.push({instanceLocation:i,keyword:"minimum",keywordLocation:`${a}/minimum`,error:`${r} is less than ${ee}.`}),Y!==void 0&&r>Y&&Te.push({instanceLocation:i,keyword:"maximum",keywordLocation:`${a}/maximum`,error:`${r} is greater than ${Y}.`}),re!==void 0&&r<=re&&Te.push({instanceLocation:i,keyword:"exclusiveMinimum",keywordLocation:`${a}/exclusiveMinimum`,error:`${r} is less than ${re}.`}),O!==void 0&&r>=O&&Te.push({instanceLocation:i,keyword:"exclusiveMaximum",keywordLocation:`${a}/exclusiveMaximum`,error:`${r} is greater than or equal to ${O}.`})),ie!==void 0){let Ge=r%ie;Math.abs(0-Ge)>=11920929e-14&&Math.abs(ie-Ge)>=11920929e-14&&Te.push({instanceLocation:i,keyword:"multipleOf",keywordLocation:`${a}/multipleOf`,error:`${r} is not a multiple of ${ie}.`})}}else if(d==="string"){let Ge=Q===void 0&&ae===void 0?0:lee(r);Q!==void 0&&Ge<Q&&Te.push({instanceLocation:i,keyword:"minLength",keywordLocation:`${a}/minLength`,error:`String is too short (${Ge} < ${Q}).`}),ae!==void 0&&Ge>ae&&Te.push({instanceLocation:i,keyword:"maxLength",keywordLocation:`${a}/maxLength`,error:`String is too long (${Ge} > ${ae}).`}),oe!==void 0&&!new RegExp(oe,"u").test(r)&&Te.push({instanceLocation:i,keyword:"pattern",keywordLocation:`${a}/pattern`,error:"String does not match pattern."}),P!==void 0&&$B[P]&&!$B[P](r)&&Te.push({instanceLocation:i,keyword:"format",keywordLocation:`${a}/format`,error:`String does not match format "${P}".`})}return{valid:Te.length===0,errors:Te}}var dee=E(()=>{iee();FB();aee();UB();uee()});var pee,ENe=E(()=>{FB();dee();pee=class{schema;draft;shortCircuit;lookup;constructor(e,t="2019-09",n=!0){this.schema=e,this.draft=t,this.shortCircuit=n,this.lookup=Cp(e)}validate(e){return uo(e,this.schema,this.draft,this.lookup,this.shortCircuit)}addSchema(e,t){t&&(e={...e,$id:t}),Cp(e,this.lookup)}}});var CNe={};ce(CNe,{OutputFormat:()=>cee,Validator:()=>pee,deepCompareStrict:()=>Qv,dereference:()=>Cp,encodePointer:()=>Jc,escapePointer:()=>yNe,format:()=>$B,ignoredKeyword:()=>bNe,initialBaseURI:()=>TNe,schemaArrayKeyword:()=>vNe,schemaKeyword:()=>M7t,schemaMapKeyword:()=>xNe,ucs2length:()=>lee,validate:()=>uo});var RNe=E(()=>{iee();FB();aee();UB();_Ne();uee();dee();ENe()});function kNe(){let r=new Error("Tool execution aborted");return r.name="AbortError",r}async function rQt(r,e){try{let{Validator:t}=await Promise.resolve().then(()=>(RNe(),CNe)),n=new t(e,"7",!1),o=Array.isArray(e.required)?e.required:[],s=e.properties&&typeof e.properties=="object"?e.properties:{},i=Object.entries(s).map(([a,c])=>`${a}${o.includes(a)?"":"?"}: ${c?.type??"any"}`).join(", ");return a=>{try{let c=n.validate(a);if(c.valid)return{success:!0,value:a};let l=c.errors.filter(d=>d.instanceLocation!=="#"||/required property/i.test(d.error)).slice(0,3).map(d=>{let p=d.instanceLocation.replace(/^#\/?/,"");return p?`${p}: ${d.error}`:d.error}).join("; ");return{success:!1,error:new Error(`Invalid arguments for tool '${r}'${l?` \u2014 ${l}`:""}. Expected: { ${i} } (send every non-optional property with the exact name and JSON type).`)}}catch(c){return g.debug(`[ToolsManager] Schema validator failed for '${r}', passing through`,{error:c instanceof Error?c.message:String(c)}),{success:!0,value:a}}}}catch(t){g.debug(`[ToolsManager] Could not compile schema validator for '${r}' \u2014 arguments will not be pre-validated`,{error:t instanceof Error?t.message:String(t)});return}}function nQt(r,e){return e.aborted?(r.catch(()=>{}),Promise.reject(kNe())):new Promise((t,n)=>{let o=()=>{r.catch(()=>{}),n(kNe())};e.addEventListener("abort",o,{once:!0}),r.then(s=>{e.removeEventListener("abort",o),t(s)},s=>{e.removeEventListener("abort",o),n(s)})})}var mee,BB,ANe=E(()=>{"use strict";Fn();T2();Bc();yr();J();fp();jc();xA();Tk();mee=new WeakMap;BB=class{constructor(e,t,n,o){this.providerName=e;this.directTools=t;this.neurolink=n;this.utilities=o;this.mcpTools={}}providerName;directTools;neurolink;utilities;mcpTools;customTools;toolExecutor;sessionId;userId;wrapExecuteWithTruncation(e,t){return async(n,o)=>{let s=o?.abortSignal,i=t(n,o),a=s&&typeof s.addEventListener=="function"?await nQt(i,s):await i;return this.truncateToolResult(e,a)}}truncateToolResult(e,t){if(t==null)return t;if(typeof t=="string"){let{preview:n,truncated:o,originalSize:s}=vd(t);return o&&g.debug(`[ToolsManager] Truncated '${e}' string output: ${s} bytes \u2192 ${Buffer.byteLength(n,"utf-8")} bytes`),o?n:t}if(typeof t=="object"){let n=t,o=null;if(typeof n.content=="string"){let{preview:s,truncated:i,originalSize:a}=vd(n.content);i&&(g.debug(`[ToolsManager] Truncated '${e}' content field: ${a} bytes \u2192 ${Buffer.byteLength(s,"utf-8")} bytes`),o={...o??n,content:s})}if(typeof n.data=="string"){let{preview:s,truncated:i,originalSize:a}=vd(n.data);i&&(g.debug(`[ToolsManager] Truncated '${e}' data field: ${a} bytes \u2192 ${Buffer.byteLength(s,"utf-8")} bytes`),o={...o??n,data:s})}if(o)return o;try{let s=JSON.stringify(t);if(Buffer.byteLength(s,"utf-8")>51200){let{preview:i,truncated:a,originalSize:c}=vd(s);if(a)return g.debug(`[ToolsManager] Truncated '${e}' JSON output: ${c} bytes \u2192 ${Buffer.byteLength(i,"utf-8")} bytes`),{_truncated:!0,_originalSize:c,_preview:i}}}catch{}}return t}setSessionContext(e,t){this.sessionId=e,this.userId=t}emitToolEvent(e,t,n){this.neurolink?.getEventEmitter&&this.neurolink.getEventEmitter().emit(e,Lm(t,n))}setupToolExecutor(e,t){let n=Oe.sdk.startSpan("neurolink.tools.register",{attributes:{[Pe.NL_PROVIDER]:this.providerName,"tools.custom_count":e.customTools.size}});try{this.customTools=e.customTools,this.toolExecutor=e.executeTool.bind(e),g.debug(`[${t}] Setting up tool executor for provider`,{providerName:this.providerName,availableCustomTools:e.customTools.size,customToolsStored:!!this.customTools,toolExecutorStored:!!this.toolExecutor}),n.setStatus({code:Ue.OK})}catch(o){throw n.setStatus({code:Ue.ERROR,message:o instanceof Error?o.message:String(o)}),o instanceof Error&&n.recordException(o),o}finally{n.end()}}async getAllTools(){return Xe({name:"neurolink.tools.getAll",tracer:Oe.sdk,attributes:{[Pe.NL_PROVIDER]:this.providerName}},async e=>{let t={};await this.processDirectTools(t);let n=Object.keys(t).length;e.setAttribute("tools.direct_count",n),g.debug(`[ToolsManager] getAllTools called for ${this.providerName}`,{directToolsCount:LS(this.directTools)}),await this.processCustomTools(t);let o=Object.keys(t).length-n;e.setAttribute("tools.custom_count",o),await this.processExternalMCPTools(t);let s=Object.keys(t).length-n-o;e.setAttribute("tools.external_mcp_count",s),await this.processMCPTools(t);let i=Object.keys(t).length;e.setAttribute(Pe.NL_TOOL_COUNT,i);let a=Object.keys(t);return e.setAttribute("tools.names",a.slice(0,20).join(",")+(a.length>20?`...+${a.length-20}`:"")),g.debug(`[ToolsManager] getAllTools complete: ${a.length} tools available`,{provider:this.providerName,toolCount:a.length,toolNames:a.length<=10?a:[...a.slice(0,10),`... and ${a.length-10} more`]}),t})}getDirectTools(){return this.directTools}getMCPTools(){return this.mcpTools}getCustomTools(){return this.customTools}async processDirectTools(e){if(!(!this.directTools||Object.keys(this.directTools).length===0)){g.debug(`[ToolsManager] Loading ${Object.keys(this.directTools).length} direct tools`);for(let[t,n]of Object.entries(this.directTools))if(n&&typeof n=="object"&&"execute"in n){let o=n.execute,s=this.wrapExecuteWithTruncation(t,o);e[t]={...n,execute:async(i,a)=>{let c=Date.now();this.emitToolEvent("tool:start",t,{input:i});try{let l=await s(i,a);return this.emitToolEvent("tool:end",t,{result:l,success:!0,responseTime:Date.now()-c}),l}catch(l){let d=l instanceof Error?l.message:String(l);throw this.emitToolEvent("tool:end",t,{error:d,success:!1,responseTime:Date.now()-c}),l}}}}else e[t]=n}}async processCustomTools(e){if(!(!this.customTools||this.customTools.size===0)){g.debug(`[ToolsManager] Loading ${this.customTools.size} custom tools from setupToolExecutor`);for(let[t,n]of this.customTools.entries()){let o=n||{};if(o&&typeof o.execute=="function"){let s=await this.createCustomToolFromDefinition(t,o);if(s&&!e[t]){let i=s.execute;if(i){let a=this.wrapExecuteWithTruncation(t,i);s.execute=a}e[t]=s}}}}}async processMCPTools(e){if(this.mcpTools||(this.mcpTools={}),this.mcpTools)for(let[t,n]of Object.entries(this.mcpTools))e[t]||(e[t]=n)}async processExternalMCPTools(e){if(!(!this.neurolink||typeof this.neurolink.getExternalMCPTools!="function"))try{let t=await this.neurolink.getExternalMCPTools(),n=0;for(let o of t){let s=await this.createExternalMCPTool(o);s&&!e[o.name]&&(e[o.name]=s,n++)}g.debug("[ToolsManager] External MCP tools loaded",{found:t.length,added:n})}catch(t){g.error(`[ToolsManager] Failed to load external MCP tools for ${this.providerName}:`,t)}}async createCustomToolFromDefinition(e,t){try{let n,o;return t.parameters&&this.utilities?.isZodSchema?.(t.parameters)?n=t.parameters:t.inputSchema&&this.utilities?.isZodSchema?.(t.inputSchema)?n=t.inputSchema:t.inputSchema&&typeof t.inputSchema=="object"?(o=t.inputSchema,n=bl(o)):t.parameters&&typeof t.parameters=="object"?n=Hke(t.parameters):n=u.object({}),{description:t.description||`Tool ${e}`,inputSchema:n,execute:async s=>{let i=Oe.sdk.startSpan("neurolink.tools.execute_custom",{attributes:{"tool.name":e,"tool.type":"custom","langfuse.internal":!0}}),a=Date.now(),c;try{if(this.toolExecutor){let f=t.timeoutMs,h=t.maxRetries,y=f!==void 0||h!==void 0,v=await this.toolExecutor(e,s,y?{...f!==void 0&&{timeout:f},...h!==void 0&&{maxRetries:h}}:void 0),b=this.utilities?.convertToolResult?await this.utilities.convertToolResult(v):v,S=Date.now();i.setAttribute("tool.duration_ms",S-a);let w;if(b&&typeof b=="object"&&"isError"in b&&b.isError)try{w=JSON.stringify(b)}catch(C){g.error(`Failed to serialize error result for ${e}`,C)}return i.setAttribute("tool.result.status",w?"error":"success"),w?i.setStatus({code:Ue.ERROR,message:`Tool ${e} returned isError: true`}):i.setStatus({code:Ue.OK}),b}this.neurolink?.emitToolStart&&(c=this.neurolink.emitToolStart(e,s,a));let l=await t.execute(s),d=this.utilities?.convertToolResult?await this.utilities.convertToolResult(l):l,p=Date.now(),m;if(d&&typeof d=="object"&&"isError"in d&&d.isError)try{m=JSON.stringify(d)}catch(f){g.error(`Failed to serialize error result for ${e}`,f)}return this.neurolink?.emitToolEnd&&this.neurolink.emitToolEnd(e,d,m,a,p,c),i.setAttribute("tool.duration_ms",p-a),i.setAttribute("tool.result.status",m?"error":"success"),m?i.setStatus({code:Ue.ERROR,message:`Tool ${e} returned isError: true`}):i.setStatus({code:Ue.OK}),d}catch(l){let d=Date.now(),p=l instanceof Error?l.message:String(l);throw!this.toolExecutor&&this.neurolink?.emitToolEnd&&(this.neurolink.emitToolEnd(e,void 0,p,a,d,c),g.debug(`Custom tool error: ${e} (${d-a}ms)`,{error:p})),i.setAttribute("tool.duration_ms",d-a),i.setAttribute("tool.result.status","error"),i.recordException(l instanceof Error?l:new Error(p)),i.setStatus({code:Ue.ERROR,message:p}),l}finally{i.end()}}}}catch(n){return g.error(`Failed to create tool: ${e}`,n),null}}async createExternalMCPTool(e){try{let t;if(e.inputSchema&&typeof e.inputSchema=="object"){let s=e.inputSchema,i=this.utilities?.fixSchemaForOpenAIStrictMode?this.utilities.fixSchemaForOpenAIStrictMode(s):s,a;mee.has(s)?a=mee.get(s):(a=await rQt(e.name,i),mee.set(s,a)),t=bl(i,a?{validate:a}:{})}else t=this.utilities?.createPermissiveZodSchema?this.utilities.createPermissiveZodSchema():u.object({});let n=async s=>{if(this.neurolink&&typeof this.neurolink.executeExternalMCPTool=="function")return this.neurolink.executeExternalMCPTool(e.serverId||"unknown",e.name,s);throw new Error("Cannot execute external MCP tool: NeuroLink executeExternalMCPTool not available")},o=this.wrapExecuteWithTruncation(e.name,n);return{description:e.description||`External MCP tool ${e.name}`,inputSchema:t,execute:async(s,i)=>{let a=Date.now();this.emitToolEvent("tool:start",e.name,{input:s});try{let c=await o(s,i);return this.emitToolEvent("tool:end",e.name,{result:c,success:!0,responseTime:Date.now()-a}),c}catch(c){let l=c instanceof Error?c.message:String(c);throw this.emitToolEvent("tool:end",e.name,{error:l,success:!1,responseTime:Date.now()-a}),g.error(`External MCP tool failed: ${e.name}`,{serverId:e.serverId,error:l}),c}}}}catch(t){return g.error(`Failed to create external MCP tool: ${e.name}`,t),null}}}});function INe(r){return typeof r=="string"&&r.length>0}function PNe(r){return INe(r)?/^gemini-2\.5(-.*)?$/i.test(r):!1}function ZA(r){return INe(r)?!!(/^gemini-3/i.test(r)||oQt.some(e=>e.test(r))):!1}function gee(r){if(!r.startsWith("claude-")||r.includes("@"))return r;let e=r.match(/^(claude-[a-z0-9-]+)-(\d{8})$/);return e?`${e[1]}@${e[2]}`:r}var oQt,hc,zB=E(()=>{"use strict";zs();oQt=_l.map(r=>new RegExp(`^${r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}`,"i"));hc=32768});function QA(r,e,t){if(e?ZA(e):!1)return t!=null&&t>hc?(g.warn(`Requested maxTokens ${t} exceeds ${e} limit of ${hc}. Using ${hc} instead.`),hc):t??hc;let o=E2(r,e);if(o!==void 0)return t==null?o:t>o?(g.warn(`Requested maxTokens ${t} exceeds the advertised ${r}/${e} output ceiling of ${o}. Using ${o} instead.`),o):t;let s=ZF[r];if(!s)return g.warn(`Unknown provider ${r}, no token limits enforced`),t??void 0;let i;return e&&typeof s=="object"&&s[e]?i=s[e]:typeof s=="object"&&s.default?i=s.default:typeof s=="number"?i=s:i=ZF.default,t==null?i:t>i?(g.warn(`Requested maxTokens ${t} exceeds ${r}/${e} limit of ${i}. Using ${i} instead.`),i):t}function sQt(r){let e=(r??"").toLowerCase();return/opus[-_.]?4/.test(e)?32e3:/sonnet[-_.]?4/.test(e)||/haiku[-_.]?4/.test(e)||/3[-_.]?7[-_.]?sonnet/.test(e)?64e3:/3[-_.]?5[-_.]?(sonnet|haiku)/.test(e)?8192:/claude-3-(opus|sonnet|haiku)/.test(e)||/3[-_.]?opus/.test(e)?4096:e.includes("opus")?32e3:e.includes("sonnet")||e.includes("haiku")?64e3:8192}function Rw(r,e){let t=sQt(r);return e!=null&&e>0?Math.min(e,t):t}var jB=E(()=>{"use strict";Um();zs();J();zB()});var eI,MNe=E(()=>{"use strict";Fn();J();jB();Nn();ch();zs();eI=class{constructor(e,t,n=3e4,o){this.providerName=e;this.modelName=t;this.defaultTimeout=n;this.middlewareOptions=o}providerName;modelName;defaultTimeout;middlewareOptions;validateOptions(e){let t=QQ(e);if(!t.isValid){let n=ah(t);throw new Wt(`Text generation options validation failed: ${n}`,"options","VALIDATION_FAILED",t.suggestions)}if(t.warnings.length>0&&g.warn("Text generation options validation warnings:",t.warnings),e.maxSteps!==void 0&&(e.maxSteps<Rs.min||e.maxSteps>Rs.max))throw new Wt(`maxSteps must be between ${Rs.min} and ${Rs.max}`,"maxSteps","OUT_OF_RANGE",[`Use a value between ${Rs.min} and ${Rs.max} for optimal performance`])}validateStreamOptions(e){let t=zA(e);if(!t.isValid){let n=ah(t);throw new Wt(`Stream options validation failed: ${n}`,"options","VALIDATION_FAILED",t.suggestions)}if(t.warnings.length>0&&g.warn("Stream options validation warnings:",t.warnings),e.maxSteps!==void 0&&(e.maxSteps<Rs.min||e.maxSteps>Rs.max))throw new Wt(`maxSteps must be between ${Rs.min} and ${Rs.max}`,"maxSteps","OUT_OF_RANGE",[`Use a value between ${Rs.min} and ${Rs.max} for optimal performance`])}normalizeTextOptions(e){if(typeof e=="string"){let a=QA(this.providerName,this.modelName);return{prompt:e,provider:this.providerName,model:this.modelName,maxTokens:a}}let t=e.prompt||e.input?.text||"",n=e.model||this.modelName,o=e.provider||this.providerName,s=QA(o,n,e.maxTokens),i={...e,prompt:t,provider:o,model:n,maxTokens:s};return e.input&&(i.input={...e.input,text:t}),i}normalizeStreamOptions(e){if(typeof e=="string"){let s=QA(this.providerName,this.modelName);return{input:{text:e},provider:this.providerName,model:this.modelName,maxTokens:s}}let t=e.model||this.modelName,n=e.provider||this.providerName,o=QA(n,t,e.maxTokens);return{...e,provider:n,model:t,maxTokens:o}}getProviderInfo(){return{provider:this.providerName,model:this.modelName}}getTimeout(e){if(e.timeout!==void 0&&e.timeout!==null){let n=Va(e.timeout);if(n!==void 0)return n}return Va(xke(this.providerName,"generate"))??this.defaultTimeout}getContextAwareTimeout(e,t){let n=this.getTimeout(e);if(!t||t<=1e5)return n;let o=1+Math.floor((t-1)/1e5)*.5;return Math.round(n*Math.min(o,4))}isZodSchema(e){return typeof e=="object"&&e!==null&&typeof e.parse=="function"}async convertToolResult(e){if(e&&typeof e=="object"&&"success"in e){let t=e;if(t.success)return t.data!==void 0?t.data:e;{let n=typeof t.error=="string"?t.error:"Tool execution failed";return g.warn(`Tool execution failed: ${n}`),{isError:!0,error:n,content:[{type:"text",text:`Tool execution failed: ${n}`}]}}}return e}createPermissiveZodSchema(){return u.record(u.string(),u.unknown()).transform(e=>e)}fixSchemaForOpenAIStrictMode(e){let t=JSON.parse(JSON.stringify(e));if(t.type==="object"&&t.properties&&typeof t.properties=="object"){let n=Object.keys(t.properties);(!t.required||!Array.isArray(t.required))&&(t.required=[]),t.additionalProperties=!1;for(let o of n){let s=t.properties[o];s&&typeof s=="object"&&(s.type==="object"?t.properties[o]=this.fixSchemaForOpenAIStrictMode(s):s.type==="array"&&s.items&&typeof s.items=="object"&&(t.properties[o].items=this.fixSchemaForOpenAIStrictMode(s.items)))}}return t}extractMiddlewareOptions(e){let t=e.middleware??this.middlewareOptions;if(!t||typeof t!="object"||t===null||t instanceof Date||t instanceof RegExp)return null;let n=t,o=i=>Array.isArray(i)&&i.length>0;return!!n.middlewareConfig||o(n.enabledMiddleware)||o(n.disabledMiddleware)||!!n.preset||o(n.middleware)?{...n,global:{collectStats:!0,continueOnError:!0,...n.global||{}}}:null}handleCommonErrors(e){if(e instanceof Yt)return new Error(`${this.providerName} request timed out after ${e.timeout}ms. Consider increasing timeout or using a lighter model.`);let t=e instanceof Error?e.message:String(e);return t.includes("API_KEY_INVALID")||t.includes("Invalid API key")||t.includes("authentication")||t.includes("unauthorized")?new Error(`Invalid API key for ${this.providerName}. Please check your API key environment variable.`):t.includes("rate limit")||t.includes("quota")||t.includes("429")?new Error(`Rate limit exceeded for ${this.providerName}. Please wait before making more requests.`):null}}});var GB={};ce(GB,{Agent:()=>HQt,BedrockClient:()=>aQt,BedrockRuntimeClient:()=>lQt,Blob:()=>VQt,Client:()=>WQt,ConverseCommand:()=>uQt,ConverseStreamCommand:()=>dQt,Cron:()=>RQt,Dispatcher:()=>JQt,File:()=>qQt,FlowProducer:()=>CQt,FormData:()=>GQt,GoogleAuth:()=>tI,HTTPException:()=>NQt,Headers:()=>jQt,Hippocampus:()=>xQt,HippocampusConfig:()=>bQt,Hono:()=>MQt,ImageFormat:()=>pQt,InvokeEndpointCommand:()=>gQt,InvokeEndpointWithResponseStreamCommand:()=>fQt,Job:()=>_Qt,ListFoundationModelsCommand:()=>cQt,MockAgent:()=>ZQt,Pool:()=>KQt,Queue:()=>SQt,QueueScheduler:()=>EQt,Request:()=>BQt,Response:()=>zQt,SageMakerRuntimeClient:()=>mQt,TextToSpeechClient:()=>yQt,VertexAI:()=>hQt,Webhook:()=>vQt,Worker:()=>wQt,convertToHtml:()=>PQt,cors:()=>OQt,createClient:()=>TQt,default:()=>iQt,extractRawText:()=>IQt,fetch:()=>$Qt,getGlobalDispatcher:()=>XQt,interceptors:()=>QQt,logger:()=>DQt,parseBuffer:()=>kQt,request:()=>eer,secureHeaders:()=>LQt,selectCover:()=>AQt,setGlobalDispatcher:()=>YQt,streamSSE:()=>UQt,timeout:()=>FQt});var kw,mi,iQt,aQt,cQt,lQt,uQt,dQt,pQt,mQt,gQt,fQt,tI,hQt,yQt,vQt,xQt,bQt,TQt,SQt,wQt,_Qt,EQt,CQt,RQt,kQt,AQt,IQt,PQt,MQt,OQt,NQt,DQt,LQt,UQt,FQt,$Qt,BQt,zQt,jQt,GQt,qQt,VQt,HQt,KQt,WQt,JQt,YQt,XQt,ZQt,QQt,eer,Aw=E(()=>{kw={get(r,e){return e==="__esModule"?!0:e==="default"?new Proxy({},{get:kw.get}):new Proxy(function(...t){return new Proxy({},{get:kw.get})},{get:kw.get,apply(t,n,o){return new Proxy({},{get:kw.get})},construct(t,n){return new Proxy({},{get:kw.get})}})}},mi=new Proxy({},kw),iQt=mi,{BedrockClient:aQt,ListFoundationModelsCommand:cQt,BedrockRuntimeClient:lQt,ConverseCommand:uQt,ConverseStreamCommand:dQt,ImageFormat:pQt}=mi,{SageMakerRuntimeClient:mQt,InvokeEndpointCommand:gQt,InvokeEndpointWithResponseStreamCommand:fQt}=mi,{GoogleAuth:tI,VertexAI:hQt,TextToSpeechClient:yQt}=mi,{Webhook:vQt}=mi,{Hippocampus:xQt,HippocampusConfig:bQt}=mi,{createClient:TQt}=mi,{Queue:SQt,Worker:wQt,Job:_Qt,QueueScheduler:EQt,FlowProducer:CQt}=mi,{Cron:RQt}=mi,{parseBuffer:kQt,selectCover:AQt}=mi,{extractRawText:IQt,convertToHtml:PQt}=mi,{Hono:MQt}=mi,{cors:OQt,HTTPException:NQt,logger:DQt,secureHeaders:LQt,streamSSE:UQt,timeout:FQt}=mi,$Qt=globalThis.fetch,BQt=globalThis.Request,zQt=globalThis.Response,jQt=globalThis.Headers,GQt=globalThis.FormData,qQt=globalThis.File,VQt=globalThis.Blob,HQt=mi.Agent,KQt=mi.Pool,WQt=mi.Client,JQt=mi.Dispatcher,YQt=()=>{},XQt=()=>mi,ZQt=mi.MockAgent,QQt={redirect:()=>r=>r,retry:()=>r=>r},eer=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 UNe={};ce(UNe,{VIDEO_ERROR_CODES:()=>dt,VertexVideoHandler:()=>VB,VideoError:()=>pt,generateTransitionWithVertex:()=>KB,generateVideoWithVertex:()=>HB,isVertexVideoConfigured:()=>yee});function yee(){return!!(process.env.GOOGLE_APPLICATION_CREDENTIALS||process.env.GOOGLE_APPLICATION_CREDENTIALS_NEUROLINK||process.env.GOOGLE_SERVICE_ACCOUNT_KEY||process.env.GOOGLE_AUTH_CLIENT_EMAIL&&process.env.GOOGLE_AUTH_PRIVATE_KEY)}async function NNe(){let r=process.env.GOOGLE_VEO_LOCATION||process.env.GOOGLE_VERTEX_VIDEO_LOCATION||rer,e=process.env.GOOGLE_VERTEX_PROJECT||process.env.GOOGLE_CLOUD_PROJECT||process.env.GOOGLE_CLOUD_PROJECT_ID||process.env.VERTEX_PROJECT_ID;if(!e&&process.env.GOOGLE_APPLICATION_CREDENTIALS)try{let t=JSON.parse(await En(process.env.GOOGLE_APPLICATION_CREDENTIALS,"utf-8"));e=t.quota_project_id||t.project_id}catch(t){g.debug("Failed to read project from credentials file",{error:t instanceof Error?t.message:String(t)})}if(!e)throw new pt({code:dt.PROVIDER_NOT_CONFIGURED,message:"Google Cloud project not found. Set GOOGLE_VERTEX_PROJECT or GOOGLE_CLOUD_PROJECT environment variable, or ensure ADC credentials contain project_id",category:"configuration",severity:"high",retriable:!1,context:{missingVar:"GOOGLE_VERTEX_PROJECT",feature:"video-generation",checkedEnvVars:["GOOGLE_VERTEX_PROJECT","GOOGLE_CLOUD_PROJECT","GOOGLE_CLOUD_PROJECT_ID","VERTEX_PROJECT_ID"]}});return{project:e,location:r}}async function DNe(){try{let r=await Promise.resolve().then(()=>(Aw(),GB)),e=new r.GoogleAuth({keyFilename:process.env.GOOGLE_APPLICATION_CREDENTIALS,scopes:["https://www.googleapis.com/auth/cloud-platform"]}),t=await je(e.getAccessToken(),YR.PROVIDER.AUTH_MS);if(!t)throw new pt({code:dt.PROVIDER_NOT_CONFIGURED,message:"Failed to obtain access token from Google Cloud credentials",category:"configuration",severity:"high",retriable:!1,context:{provider:"vertex",feature:"video-generation"}});return t}catch(r){throw r instanceof pt?r:new pt({code:dt.PROVIDER_NOT_CONFIGURED,message:`Google Cloud authentication failed: ${r instanceof Error?r.message:String(r)}`,category:"configuration",severity:"high",retriable:!1,context:{provider:"vertex",feature:"video-generation"},originalError:r instanceof Error?r:void 0})}}function hee(r){return r.length<4?(g.warn("Image buffer too small for format detection",{size:r.length}),"image/jpeg"):r[0]===255&&r[1]===216&&r[2]===255?"image/jpeg":r[0]===137&&r[1]===80&&r[2]===78&&r[3]===71?"image/png":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?"image/webp":(g.warn("Unknown image format detected, defaulting to image/jpeg",{firstBytes:r.slice(0,12).toString("hex"),size:r.length}),"image/jpeg")}function ner(r,e){return r==="1080p"?e==="9:16"?{width:1080,height:1920}:{width:1920,height:1080}:e==="9:16"?{width:720,height:1280}:{width:1280,height:720}}async function HB(r,e,t={},n){let o=await NNe(),s=o.project,i=n||o.location,a=Date.now(),c=t.resolution||"720p",l=t.length||6,d=t.aspectRatio||"16:9",p=t.audio??!0;g.debug("Starting Vertex video generation",{project:s,location:i,model:qB,resolution:c,durationSeconds:l,aspectRatio:d,generateAudio:p,promptLength:e.length,imageSize:r.length});try{let m=r.toString("base64"),f=hee(r),h=await DNe(),v=`https://${i==="global"?"aiplatform.googleapis.com":`${i}-aiplatform.googleapis.com`}/v1/projects/${s}/locations/${i}/publishers/google/models/${qB}:predictLongRunning`,b={instances:[{prompt:e,image:{bytesBase64Encoded:m,mimeType:f}}],parameters:{sampleCount:1,durationSeconds:l,aspectRatio:d,resolution:c,generateAudio:p,resizeMode:"pad"}};g.debug("Sending video generation request",{endpoint:v});let S=new AbortController,w=setTimeout(()=>S.abort(),3e4),C;try{C=await fetch(v,{method:"POST",headers:{Authorization:`Bearer ${h}`,"Content-Type":"application/json; charset=utf-8"},body:JSON.stringify(b),signal:S.signal})}catch(D){throw clearTimeout(w),Ar(D)?new pt({code:dt.GENERATION_FAILED,message:"Video generation request timed out after 30 seconds",category:"execution",severity:"high",retriable:!0,context:{provider:"vertex",endpoint:v,timeout:3e4}}):D}if(clearTimeout(w),!C.ok){let D=await C.text();throw new pt({code:dt.GENERATION_FAILED,message:`Vertex API error: ${C.status} - ${D}`,category:"execution",severity:"high",retriable:C.status>=500,context:{status:C.status,error:D,provider:"vertex",endpoint:v}})}let R=await C.json(),k=R.name;if(!k)throw new pt({code:dt.GENERATION_FAILED,message:"Vertex API did not return an operation name",category:"execution",severity:"high",retriable:!1,context:{response:R,provider:"vertex"}});g.debug("Video generation operation started",{operationName:k});let I=ONe-(Date.now()-a),A=await ier(k,h,s,i,Math.max(1e3,I)),P=Date.now()-a,M=ner(c,d);return g.info("Video generation complete",{processingTime:P,videoSizeKB:Math.round(A.length/1024),dimensions:M}),{data:A,mediaType:"video/mp4",metadata:{duration:l,dimensions:M,model:qB,provider:"vertex",aspectRatio:d,audioEnabled:p,processingTime:P}}}catch(m){throw m instanceof pt?m:new pt({code:dt.GENERATION_FAILED,message:`Video generation failed: ${m instanceof Error?m.message:String(m)}`,category:"execution",severity:"high",retriable:!0,context:{provider:"vertex"},originalError:m instanceof Error?m:void 0})}}function oer(r,e){if(r.error)throw new pt({code:dt.GENERATION_FAILED,message:`Video generation failed: ${r.error.message||JSON.stringify(r.error)}`,category:"execution",severity:"high",retriable:!1,context:{operationName:e,error:r.error,provider:"vertex"}});let t=r.response?.videos?.[0];if(!t)throw new pt({code:dt.GENERATION_FAILED,message:"No video data in response from Vertex AI",category:"execution",severity:"high",retriable:!1,context:{operationName:e,response:r.response,provider:"vertex"}});if(t.gcsUri)throw new pt({code:dt.GENERATION_FAILED,message:`Video stored at GCS: ${t.gcsUri}. GCS download not yet implemented.`,category:"execution",severity:"high",retriable:!1,context:{operationName:e,gcsUri:t.gcsUri,provider:"vertex",suggestion:"Do not set storageUri parameter to receive video as base64 inline"}});if(t.bytesBase64Encoded)return Buffer.from(t.bytesBase64Encoded,"base64");throw new pt({code:dt.GENERATION_FAILED,message:"No video bytes in response - unexpected response format",category:"execution",severity:"high",retriable:!1,context:{operationName:e,videoData:t,provider:"vertex"}})}async function ser(r,e,t,n=3e4){let o=new AbortController,s=setTimeout(()=>o.abort(),n),i;try{i=await fetch(r,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json; charset=utf-8"},body:JSON.stringify({operationName:e}),signal:o.signal})}catch(a){throw clearTimeout(s),Ar(a)?new pt({code:dt.GENERATION_FAILED,message:`Poll request timed out after ${n}ms`,category:"execution",severity:"high",retriable:!0,context:{provider:"vertex",operationName:e,timeout:n}}):a}if(clearTimeout(s),!i.ok){let a=await i.text();throw new pt({code:dt.GENERATION_FAILED,message:`Failed to poll video operation: ${i.status} - ${a}`,category:"execution",severity:"high",retriable:i.status>=500,context:{operationName:e,status:i.status,error:a,provider:"vertex"}})}return i.json()}async function ier(r,e,t,n,o){return LNe(qB,r,e,t,n,o)}async function KB(r,e,t,n={},o=4,s){let i=await NNe(),a=i.project,c=s||i.location,l=Date.now(),d=n.aspectRatio||"16:9",p=n.resolution||"720p",m=n.audio??!0;g.debug("Starting transition clip generation",{model:fee,durationSeconds:o,firstFrameSize:r.length,lastFrameSize:e.length,promptLength:t.length});try{let f=r.toString("base64"),h=e.toString("base64"),y=hee(r),v=hee(e),b=await DNe(),S=`https://${c}-aiplatform.googleapis.com/v1/projects/${a}/locations/${c}/publishers/google/models/${fee}:predictLongRunning`,w={instances:[{prompt:t,image:{bytesBase64Encoded:f,mimeType:y},lastFrame:{bytesBase64Encoded:h,mimeType:v}}],parameters:{sampleCount:1,durationSeconds:o,aspectRatio:d,resolution:p,generateAudio:m}},C=new AbortController,R=setTimeout(()=>C.abort(),3e4),k;try{k=await fetch(S,{method:"POST",headers:{Authorization:`Bearer ${b}`,"Content-Type":"application/json; charset=utf-8"},body:JSON.stringify(w),signal:C.signal})}catch(D){throw clearTimeout(R),Ar(D)?new pt({code:dt.DIRECTOR_TRANSITION_FAILED,message:"Transition generation request timed out after 30 seconds",category:"execution",severity:"medium",retriable:!0}):D}if(clearTimeout(R),!k.ok){let D=await k.text();throw new pt({code:dt.DIRECTOR_TRANSITION_FAILED,message:`Transition API error: ${k.status} - ${D}`,category:"execution",severity:"medium",retriable:k.status>=500,context:{status:k.status,error:D}})}let A=(await k.json()).name;if(!A)throw new pt({code:dt.DIRECTOR_TRANSITION_FAILED,message:"Transition API did not return an operation name",category:"execution",severity:"medium",retriable:!1});let P=ONe-(Date.now()-l),M=await aer(A,b,a,c,Math.max(1e3,P));return g.debug("Transition clip generated",{processingTime:Date.now()-l,videoSize:M.length}),M}catch(f){throw f instanceof pt?f:new pt({code:dt.DIRECTOR_TRANSITION_FAILED,message:`Transition generation failed: ${f instanceof Error?f.message:String(f)}`,category:"execution",severity:"medium",retriable:!0,originalError:f instanceof Error?f:void 0})}}async function LNe(r,e,t,n,o,s){let i=Date.now(),c=`https://${o==="global"?"aiplatform.googleapis.com":`${o}-aiplatform.googleapis.com`}/v1/projects/${n}/locations/${o}/publishers/google/models/${r}:fetchPredictOperation`;for(;Date.now()-i<s;){let l=await ser(c,e,t);if(l.done)return oer(l,e);g.debug("Polling operation...",{operationName:e,elapsed:Date.now()-i}),await new Promise(d=>setTimeout(d,ter))}throw new pt({code:dt.POLL_TIMEOUT,message:`Operation timed out after ${Math.round(s/1e3)}s`,category:"timeout",severity:"medium",retriable:!0,context:{operationName:e,timeoutMs:s}})}async function aer(r,e,t,n,o){return LNe(fee,r,e,t,n,o)}var pt,ONe,ter,qB,fee,rer,VB,ex=E(()=>{"use strict";pa();XR();np();St();J();pt=class extends Ne{constructor(e){super({code:e.code,message:e.message,category:e.category??"execution",severity:e.severity??"high",retriable:e.retriable??!1,context:e.context,originalError:e.originalError}),this.name="VideoError"}},ONe=18e4,ter=5e3,qB="veo-3.1-generate-001",fee="veo-3.1-fast-generate-001",rer="us-central1";VB=class{maxDurationSeconds=8;supportedAspectRatios=["9:16","16:9"];supportedResolutions=["720p","1080p"];isConfigured(){return yee()}generate(e,t,n,o){return HB(e,t,n,o)}generateTransition(e,t,n,o,s){return KB(e,t,n,{aspectRatio:o?.aspectRatio,resolution:o?.resolution,audio:o?.audio},o?.durationSeconds??4,s)}}});var vee={};ce(vee,{VIDEO_ERROR_CODES:()=>dt,VideoError:()=>pt,VideoProcessor:()=>WB});var WB,fh=E(()=>{"use strict";np();ao();J();ex();WB=class{static handlers=new Map;static registerHandler(e,t){if(!e)throw new Error("Provider name is required");if(!t)throw new Error("Handler is required");let n=e.toLowerCase();this.handlers.has(n)&&g.warn(`[VideoProcessor] Overwriting existing handler for provider: ${n}`),this.handlers.set(n,t),g.debug(`[VideoProcessor] Registered video handler: ${n}`)}static supports(e){return e?this.handlers.has(e.toLowerCase()):!1}static listProviders(){return Array.from(this.handlers.keys())}static getHandler(e){return this.handlers.get(e.toLowerCase())}static buildSpanAttributes(e,t){return{"video.operation":"generate","video.provider":e,"video.resolution":t.resolution,"video.duration":t.length,"video.aspect_ratio":t.aspectRatio,"video.audio":t.audio}}static async generate(e,t,n,o,s){let i=Ae.createSpan("media.generation","video.generate",this.buildSpanAttributes(e,o));try{let a=this.getHandler(e);if(!a)throw new pt({code:dt.PROVIDER_NOT_SUPPORTED,message:`Video provider "${e}" is not registered. Available: ${this.listProviders().join(", ")}`,category:"configuration",severity:"high",retriable:!1,context:{provider:e,available:this.listProviders()}});if(!a.isConfigured())throw new pt({code:dt.PROVIDER_NOT_CONFIGURED,message:`Video provider "${e}" is not configured. Set the required credentials.`,category:"configuration",severity:"high",retriable:!1,context:{provider:e}});g.debug(`[VideoProcessor] Starting video generation with provider: ${e}`);let c=await a.generate(t,n,o,s),l=Ae.endSpan(i,1);return nt().recordSpan(l),g.info(`[VideoProcessor] Generated ${c.data.length} bytes (${e})`),c}catch(a){let c=Ae.endSpan(i,2,a instanceof Error?a.message:String(a));if(nt().recordSpan(c),a instanceof pt)throw a;let l=a instanceof Error?a.message:String(a);throw new pt({code:dt.GENERATION_FAILED,message:`Video generation failed for provider "${e}": ${l}`,category:"execution",severity:"high",retriable:!0,context:{provider:e,options:o,region:s},originalError:a instanceof Error?a:void 0})}}static async generateTransition(e,t,n,o,s,i){let a=this.getHandler(e);if(!a)throw new pt({code:dt.PROVIDER_NOT_SUPPORTED,message:`Video provider "${e}" is not registered for transitions`,category:"configuration",severity:"high",retriable:!1,context:{provider:e,available:this.listProviders()}});if(!a.generateTransition)throw new pt({code:dt.TRANSITION_NOT_SUPPORTED,message:`Video provider "${e}" does not support transition clips`,category:"validation",severity:"medium",retriable:!1,context:{provider:e}});if(!a.isConfigured())throw new pt({code:dt.PROVIDER_NOT_CONFIGURED,message:`Video provider "${e}" is not configured`,category:"configuration",severity:"high",retriable:!1,context:{provider:e}});try{return await a.generateTransition(t,n,o,s,i)}catch(c){if(c instanceof pt)throw c;let l=c instanceof Error?c.message:String(c);throw new pt({code:dt.DIRECTOR_TRANSITION_FAILED,message:`Video transition generation failed for provider "${e}": ${l}`,category:"execution",severity:"medium",retriable:!0,context:{provider:e,firstFrameSize:t.length,lastFrameSize:n.length,durationSeconds:s?.durationSeconds},originalError:c instanceof Error?c:void 0})}}}});var xee,rI,FNe=E(()=>{xee=class{value;next;constructor(e){this.value=e}},rI=class{#e;#t;#r;constructor(){this.clear()}enqueue(e){let t=new xee(e);this.#e?(this.#t.next=t,this.#t=t):(this.#e=t,this.#t=t),this.#r++}dequeue(){let e=this.#e;if(e)return this.#e=this.#e.next,this.#r--,this.#e||(this.#t=void 0),e.value}peek(){if(this.#e)return this.#e.value}clear(){this.#e=void 0,this.#t=void 0,this.#r=0}get size(){return this.#r}*[Symbol.iterator](){let e=this.#e;for(;e;)yield e.value,e=e.next}*drain(){for(;this.#e;)yield this.dequeue()}}});function kp(r){let e=!1;if(typeof r=="object"&&({concurrency:r,rejectOnClear:e=!1}=r),$Ne(r),typeof e!="boolean")throw new TypeError("Expected `rejectOnClear` to be a boolean");let t=new rI,n=0,o=()=>{n<r&&t.size>0&&(n++,t.dequeue().run())},s=()=>{n--,o()},i=async(l,d,p)=>{let m=(async()=>l(...p))();d(m);try{await m}catch{}s()},a=(l,d,p,m)=>{let f={reject:p};new Promise(h=>{f.run=h,t.enqueue(f)}).then(i.bind(void 0,l,d,m)),n<r&&o()},c=(l,...d)=>new Promise((p,m)=>{a(l,p,m,d)});return Object.defineProperties(c,{activeCount:{get:()=>n},pendingCount:{get:()=>t.size},clearQueue:{value(){if(!e){t.clear();return}let l=AbortSignal.abort().reason;for(;t.size>0;)t.dequeue().reject(l)}},concurrency:{get:()=>r,set(l){$Ne(l),r=l,queueMicrotask(()=>{for(;n<r&&t.size>0;)o()})}},map:{async value(l,d){let p=Array.from(l,(m,f)=>this(d,m,f));return Promise.all(p)}}}),c}function $Ne(r){if(!((Number.isInteger(r)||r===Number.POSITIVE_INFINITY)&&r>0))throw new TypeError("Expected `concurrency` to be a number from 1 and up")}var nI=E(()=>{FNe()});var wd={};ce(wd,{AsyncLocalStorage:()=>Rer,Buffer:()=>arr,Channel:()=>Ytr,DatabaseSync:()=>irr,Duplex:()=>Aer,EventEmitter:()=>Cer,Http2ServerRequest:()=>drr,Http2ServerResponse:()=>prr,Interface:()=>srr,MIMEType:()=>vrr,PassThrough:()=>Ier,PerformanceObserver:()=>Ktr,Readable:()=>zNe,ReadableStream:()=>Per,Resolver:()=>Vtr,TextDecoder:()=>qNe,TextEncoder:()=>JB,Transform:()=>ker,URL:()=>Mtr,URLSearchParams:()=>Otr,Worker:()=>err,Writable:()=>jNe,access:()=>Ker,appendFile:()=>Der,appendFileSync:()=>YB,arch:()=>dtr,arrayBuffer:()=>mrr,basename:()=>xer,builtinModules:()=>ktr,callbackify:()=>Btr,channel:()=>Jtr,chmodSync:()=>Ner,clearInterval:()=>yrr,clearTimeout:()=>frr,closeSync:()=>Fer,connect:()=>ftr,constants:()=>wee,copyFileSync:()=>Ler,cpSync:()=>ger,cpus:()=>atr,createConnection:()=>htr,createGunzip:()=>wtr,createGzip:()=>_tr,createHash:()=>BNe,createHmac:()=>uer,createInterface:()=>orr,createReadStream:()=>hh,createRequire:()=>Rtr,createServer:()=>fer,createWriteStream:()=>See,debug:()=>Ftr,debuglog:()=>GNe,default:()=>cer,deflateSync:()=>vtr,deprecate:()=>$tr,deserialize:()=>Qtr,dirname:()=>ver,exec:()=>Qer,execFile:()=>ttr,execFileSync:()=>rtr,execSync:()=>etr,existsSync:()=>gs,extname:()=>ber,fileURLToPath:()=>Ntr,finished:()=>Oer,format:()=>Ptr,freemem:()=>ctr,fstatSync:()=>$er,get:()=>gtr,gunzip:()=>Str,gunzipSync:()=>xtr,gzip:()=>Ttr,gzipSync:()=>btr,hasSubscribers:()=>Xtr,homedir:()=>otr,hostname:()=>itr,inflateSync:()=>ytr,inherits:()=>Ltr,inspect:()=>ZB,isAbsolute:()=>Ser,isBuiltin:()=>Atr,isDeepStrictEqual:()=>ztr,isIP:()=>urr,isIPv4:()=>lrr,isIPv6:()=>crr,isMainThread:()=>trr,join:()=>her,lookup:()=>qtr,mkdir:()=>Ger,mkdirSync:()=>Nl,monitorEventLoopDelay:()=>Wtr,normalize:()=>Eer,ok:()=>Etr,open:()=>Yer,openSync:()=>Uer,parentPort:()=>rrr,parse:()=>Itr,pathToFileURL:()=>Dtr,performance:()=>Htr,pipeline:()=>Mer,platform:()=>ntr,posix:()=>_er,promises:()=>ler,promisify:()=>Utr,randomBytes:()=>der,randomUUID:()=>per,readFile:()=>zer,readFileSync:()=>fs,readdir:()=>Ver,readdirSync:()=>Iw,realpath:()=>Xer,realpathSync:()=>XB,relative:()=>Ter,release:()=>ptr,rename:()=>Wer,renameSync:()=>bee,request:()=>mtr,resolve:()=>yer,rm:()=>Jer,rmSync:()=>Ber,rmdirSync:()=>Tee,sep:()=>wer,serialize:()=>Ztr,setInterval:()=>hrr,setTimeout:()=>grr,spawn:()=>Zer,stat:()=>qer,statSync:()=>tx,strict:()=>Ctr,tmpdir:()=>str,toUSVString:()=>jtr,totalmem:()=>ltr,type:()=>utr,types:()=>Gtr,unlink:()=>Her,unlinkSync:()=>oI,webcrypto:()=>mer,workerData:()=>nrr,writeFile:()=>jer,writeFileSync:()=>Sd});var ms,Io,cer,ler,BNe,uer,der,per,mer,YB,ger,fer,her,yer,ver,xer,ber,Ter,Ser,wer,_er,Eer,Cer,Rer,zNe,jNe,ker,Aer,Ier,Per,Mer,Oer,gs,fs,Sd,Ner,Der,XB,Ler,Uer,Fer,$er,Nl,tx,Iw,oI,bee,Tee,Ber,See,hh,zer,jer,Ger,qer,Ver,Her,Ker,Wer,Jer,Yer,Xer,Zer,Qer,etr,ttr,rtr,ntr,otr,str,itr,atr,ctr,ltr,utr,dtr,ptr,mtr,gtr,ftr,htr,ytr,vtr,xtr,btr,Ttr,Str,wtr,_tr,Etr,Ctr,Rtr,ktr,Atr,Itr,Ptr,Mtr,Otr,Ntr,Dtr,Ltr,Utr,GNe,Ftr,ZB,$tr,Btr,ztr,jtr,Gtr,qNe,JB,qtr,Vtr,Htr,Ktr,Wtr,Jtr,Ytr,Xtr,Ztr,Qtr,err,trr,rrr,nrr,orr,srr,irr,arr,wee,crr,lrr,urr,drr,prr,mrr,VNe,grr,frr,hrr,yrr,vrr,Is=E(()=>{ms=()=>{},Io=async()=>{},cer={},ler={readFile:Io,writeFile:Io,mkdir:Io,stat:Io,readdir:Io,unlink:Io,access:Io,rm:Io,rename:Io},BNe=r=>{let e=[];return{update(t){return e.push(typeof t=="string"?new JB().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}}},uer=(r,e)=>BNe(r),der=r=>new Uint8Array(r||32),per=()=>globalThis.crypto?.randomUUID?.()||Math.random().toString(36),mer=globalThis.crypto,YB=()=>{throw new Error("[NeuroLink:browser] fs.appendFileSync is not supported in browser runtime \u2014 use server-side execution")},ger=()=>{throw new Error("[NeuroLink:browser] fs.cpSync is not supported in browser runtime \u2014 use server-side execution")},fer=()=>({listen:ms,close:ms,on:ms}),her=(...r)=>r.join("/"),yer=(...r)=>r.join("/"),ver=r=>r||"",xer=r=>r?.split?.("/")?.pop?.()||"",ber=r=>{let e=r?.match?.(/\.[^.]+$/);return e?e[0]:""},Ter=(r,e)=>e||"",Ser=()=>!1,wer="/",_er={normalize:r=>r,join:(...r)=>r.join("/"),resolve:(...r)=>r.join("/"),sep:"/"},Eer=r=>r,Cer=class{on(){return this}off(){return this}emit(){return this}once(){return this}removeListener(){return this}addListener(){return this}},Rer=class{getStore(){}run(r,e,...t){return e(...t)}enterWith(){}disable(){}},zNe=class{pipe(){return this}on(){return this}read(){return null}push(){}destroy(){}},jNe=class{write(){return!0}end(){}on(){return this}destroy(){}},ker=class{push(){}on(){return this}},Aer=class{on(){return this}},Ier=class{pipe(){return this}on(){return this}},Per=globalThis.ReadableStream||class{},Mer=ms,Oer=ms,gs=()=>!1,fs=()=>"",Sd=ms,Ner=ms,Der=Io,XB=r=>r,Ler=ms,Uer=()=>0,Fer=ms,$er=()=>({}),Nl=ms,tx=()=>({}),Iw=()=>[],oI=ms,bee=ms,Tee=ms,Ber=ms,See=()=>new jNe,hh=()=>new zNe,zer=Io,jer=Io,Ger=Io,qer=Io,Ver=Io,Her=Io,Ker=Io,Wer=Io,Jer=Io,Yer=async()=>({stat:Io,readFile:Io,close:Io,read:Io,write:Io}),Xer=async r=>r,Zer=()=>({on:ms,stdout:{on:ms},stderr:{on:ms},kill:ms}),Qer=(r,e)=>e?.(null,"",""),etr=()=>"",ttr=(r,e,t)=>{typeof e=="function"?e(null,"",""):t?.(null,"","")},rtr=()=>"",ntr="browser",otr=()=>"/",str=()=>"/tmp",itr=()=>"browser",atr=()=>[{}],ctr=()=>0,ltr=()=>0,utr=()=>"Browser",dtr=()=>"wasm",ptr=()=>"0",mtr=()=>({}),gtr=()=>({}),ftr=()=>({}),htr=()=>({}),ytr=()=>new Uint8Array,vtr=()=>new Uint8Array,xtr=()=>new Uint8Array,btr=()=>new Uint8Array,Ttr=(r,e)=>e?.(null,r),Str=(r,e)=>e?.(null,r),wtr=()=>({}),_tr=()=>({}),Etr=ms,Ctr={},Rtr=()=>()=>({}),ktr=[],Atr=()=>!1,Itr=r=>({pathname:r||"",hostname:"",protocol:"",search:"",hash:""}),Ptr=()=>"",Mtr=globalThis.URL,Otr=globalThis.URLSearchParams,Ntr=r=>typeof r=="string"?r.replace("file://",""):r,Dtr=r=>new globalThis.URL("file://"+r),Ltr=(r,e)=>{e&&(r.super_=e,Object.setPrototypeOf(r.prototype,e.prototype))},Utr=r=>(...e)=>new Promise((t,n)=>r(...e,(o,s)=>o?n(o):t(s))),GNe=r=>{let e=(...t)=>{};return e.enabled=!1,e},Ftr=GNe,ZB=r=>{try{return JSON.stringify(r,null,2)}catch{return String(r)}};ZB.custom=Symbol.for("nodejs.util.inspect.custom");ZB.colors={};ZB.styles={};$tr=r=>r,Btr=r=>(...e)=>{let t=e.pop();r(...e).then(n=>t(null,n)).catch(t)},ztr=(r,e)=>JSON.stringify(r)===JSON.stringify(e),jtr=r=>String(r),Gtr={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},qNe=globalThis.TextDecoder,JB=globalThis.TextEncoder,qtr=(r,e)=>e?.(null,"127.0.0.1",4),Vtr=class{},Htr=globalThis.performance||{now:()=>Date.now()},Ktr=class{observe(){}disconnect(){}},Wtr=()=>({enable:ms,disable:ms,percentile:()=>0}),Jtr=()=>({}),Ytr=class{},Xtr=()=>!1,Ztr=()=>new Uint8Array,Qtr=ms,err=class{},trr=!0,rrr=null,nrr=null,orr=()=>({}),srr=class{},irr=class{},arr=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 JB().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 JB().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 qNe().decode(this)}},wee={F_OK:0,R_OK:4,W_OK:2,X_OK:1},crr=()=>!1,lrr=()=>!1,urr=()=>0,drr=class{},prr=class{},mrr=async()=>new ArrayBuffer(0),VNe=r=>({[Symbol.toPrimitive](){return r},ref(){return this},unref(){return this},hasRef(){return!1},refresh(){return this},close(){}}),grr=(...r)=>VNe(globalThis.setTimeout(...r)),frr=globalThis.clearTimeout,hrr=(...r)=>VNe(globalThis.setInterval(...r)),yrr=globalThis.clearInterval,vrr=class{constructor(r){this.type=r}toString(){return this.type}}});var fNn,hNn,QB,Pw,yNn,vNn,_ee,xrr,HNe,xNn,bNn,SNn,wNn,Mw=E(()=>{fNn=globalThis.crypto,hNn=globalThis.ReadableStream||class{},QB=()=>"/",Pw=()=>"/tmp",yNn=globalThis.URL,vNn=globalThis.URLSearchParams,_ee=r=>{try{return JSON.stringify(r,null,2)}catch{return String(r)}};_ee.custom=Symbol.for("nodejs.util.inspect.custom");_ee.colors={};_ee.styles={};xrr=globalThis.TextDecoder,HNe=globalThis.TextEncoder,xNn=globalThis.performance||{now:()=>Date.now()},bNn=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 HNe().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 HNe().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 xrr().decode(this)}},SNn=globalThis.clearTimeout,wNn=globalThis.clearInterval});var Cee={};ce(Cee,{AsyncLocalStorage:()=>Brr,Buffer:()=>Ior,Channel:()=>xor,DatabaseSync:()=>Aor,Duplex:()=>jrr,EventEmitter:()=>$rr,Http2ServerRequest:()=>Dor,Http2ServerResponse:()=>Lor,Interface:()=>kor,MIMEType:()=>jor,PassThrough:()=>Grr,PerformanceObserver:()=>hor,Readable:()=>WNe,ReadableStream:()=>qrr,Resolver:()=>mor,TextDecoder:()=>XNe,TextEncoder:()=>ez,Transform:()=>zrr,URL:()=>eor,URLSearchParams:()=>tor,Worker:()=>wor,Writable:()=>JNe,access:()=>vnr,appendFile:()=>Xrr,appendFileSync:()=>Crr,arch:()=>Onr,arrayBuffer:()=>Uor,basename:()=>Mrr,builtinModules:()=>Ynr,callbackify:()=>cor,channel:()=>vor,chmodSync:()=>Yrr,clearInterval:()=>zor,clearTimeout:()=>$or,closeSync:()=>tnr,connect:()=>Unr,constants:()=>Por,copyFileSync:()=>Qrr,cpSync:()=>Rrr,cpus:()=>Anr,createConnection:()=>Fnr,createGunzip:()=>Vnr,createGzip:()=>Hnr,createHash:()=>KNe,createHmac:()=>Srr,createInterface:()=>Ror,createReadStream:()=>dnr,createRequire:()=>Jnr,createServer:()=>krr,createWriteStream:()=>unr,debug:()=>ior,debuglog:()=>YNe,default:()=>brr,deflateSync:()=>Bnr,deprecate:()=>aor,deserialize:()=>Sor,dirname:()=>Prr,exec:()=>wnr,execFile:()=>Eee,execFileSync:()=>gi,execSync:()=>_nr,existsSync:()=>Krr,extname:()=>Orr,fileURLToPath:()=>ror,finished:()=>Hrr,format:()=>Qnr,freemem:()=>Inr,fstatSync:()=>rnr,get:()=>Lnr,gunzip:()=>qnr,gunzipSync:()=>znr,gzip:()=>Gnr,gzipSync:()=>jnr,hasSubscribers:()=>bor,homedir:()=>Cnr,hostname:()=>knr,inflateSync:()=>$nr,inherits:()=>oor,inspect:()=>tz,isAbsolute:()=>Drr,isBuiltin:()=>Xnr,isDeepStrictEqual:()=>lor,isIP:()=>Nor,isIPv4:()=>Oor,isIPv6:()=>Mor,isMainThread:()=>_or,join:()=>Arr,lookup:()=>por,mkdir:()=>gnr,mkdirSync:()=>nnr,monitorEventLoopDelay:()=>yor,normalize:()=>Frr,ok:()=>Knr,open:()=>Tnr,openSync:()=>enr,parentPort:()=>Eor,parse:()=>Znr,pathToFileURL:()=>nor,performance:()=>gor,pipeline:()=>Vrr,platform:()=>Enr,posix:()=>Urr,promises:()=>Trr,promisify:()=>sor,randomBytes:()=>wrr,randomUUID:()=>_rr,readFile:()=>pnr,readFileSync:()=>Wrr,readdir:()=>hnr,readdirSync:()=>snr,realpath:()=>Snr,realpathSync:()=>Zrr,relative:()=>Nrr,release:()=>Nnr,rename:()=>xnr,renameSync:()=>anr,request:()=>Dnr,resolve:()=>Irr,rm:()=>bnr,rmSync:()=>lnr,rmdirSync:()=>cnr,sep:()=>Lrr,serialize:()=>Tor,setInterval:()=>Bor,setTimeout:()=>For,spawn:()=>Ow,stat:()=>fnr,statSync:()=>onr,strict:()=>Wnr,tmpdir:()=>Rnr,toUSVString:()=>uor,totalmem:()=>Pnr,type:()=>Mnr,types:()=>dor,unlink:()=>ynr,unlinkSync:()=>inr,webcrypto:()=>Err,workerData:()=>Cor,writeFile:()=>mnr,writeFileSync:()=>Jrr});var hs,Po,brr,Trr,KNe,Srr,wrr,_rr,Err,Crr,Rrr,krr,Arr,Irr,Prr,Mrr,Orr,Nrr,Drr,Lrr,Urr,Frr,$rr,Brr,WNe,JNe,zrr,jrr,Grr,qrr,Vrr,Hrr,Krr,Wrr,Jrr,Yrr,Xrr,Zrr,Qrr,enr,tnr,rnr,nnr,onr,snr,inr,anr,cnr,lnr,unr,dnr,pnr,mnr,gnr,fnr,hnr,ynr,vnr,xnr,bnr,Tnr,Snr,Ow,wnr,_nr,Eee,gi,Enr,Cnr,Rnr,knr,Anr,Inr,Pnr,Mnr,Onr,Nnr,Dnr,Lnr,Unr,Fnr,$nr,Bnr,znr,jnr,Gnr,qnr,Vnr,Hnr,Knr,Wnr,Jnr,Ynr,Xnr,Znr,Qnr,eor,tor,ror,nor,oor,sor,YNe,ior,tz,aor,cor,lor,uor,dor,XNe,ez,por,mor,gor,hor,yor,vor,xor,bor,Tor,Sor,wor,_or,Eor,Cor,Ror,kor,Aor,Ior,Por,Mor,Oor,Nor,Dor,Lor,Uor,ZNe,For,$or,Bor,zor,jor,yh=E(()=>{hs=()=>{},Po=async()=>{},brr={},Trr={readFile:Po,writeFile:Po,mkdir:Po,stat:Po,readdir:Po,unlink:Po,access:Po,rm:Po,rename:Po},KNe=r=>{let e=[];return{update(t){return e.push(typeof t=="string"?new ez().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}}},Srr=(r,e)=>KNe(r),wrr=r=>new Uint8Array(r||32),_rr=()=>globalThis.crypto?.randomUUID?.()||Math.random().toString(36),Err=globalThis.crypto,Crr=()=>{throw new Error("[NeuroLink:browser] fs.appendFileSync is not supported in browser runtime \u2014 use server-side execution")},Rrr=()=>{throw new Error("[NeuroLink:browser] fs.cpSync is not supported in browser runtime \u2014 use server-side execution")},krr=()=>({listen:hs,close:hs,on:hs}),Arr=(...r)=>r.join("/"),Irr=(...r)=>r.join("/"),Prr=r=>r||"",Mrr=r=>r?.split?.("/")?.pop?.()||"",Orr=r=>{let e=r?.match?.(/\.[^.]+$/);return e?e[0]:""},Nrr=(r,e)=>e||"",Drr=()=>!1,Lrr="/",Urr={normalize:r=>r,join:(...r)=>r.join("/"),resolve:(...r)=>r.join("/"),sep:"/"},Frr=r=>r,$rr=class{on(){return this}off(){return this}emit(){return this}once(){return this}removeListener(){return this}addListener(){return this}},Brr=class{getStore(){}run(r,e,...t){return e(...t)}enterWith(){}disable(){}},WNe=class{pipe(){return this}on(){return this}read(){return null}push(){}destroy(){}},JNe=class{write(){return!0}end(){}on(){return this}destroy(){}},zrr=class{push(){}on(){return this}},jrr=class{on(){return this}},Grr=class{pipe(){return this}on(){return this}},qrr=globalThis.ReadableStream||class{},Vrr=hs,Hrr=hs,Krr=()=>!1,Wrr=()=>"",Jrr=hs,Yrr=hs,Xrr=Po,Zrr=r=>r,Qrr=hs,enr=()=>0,tnr=hs,rnr=()=>({}),nnr=hs,onr=()=>({}),snr=()=>[],inr=hs,anr=hs,cnr=hs,lnr=hs,unr=()=>new JNe,dnr=()=>new WNe,pnr=Po,mnr=Po,gnr=Po,fnr=Po,hnr=Po,ynr=Po,vnr=Po,xnr=Po,bnr=Po,Tnr=async()=>({stat:Po,readFile:Po,close:Po,read:Po,write:Po}),Snr=async r=>r,Ow=()=>({on:hs,stdout:{on:hs},stderr:{on:hs},kill:hs}),wnr=(r,e)=>e?.(null,"",""),_nr=()=>"",Eee=(r,e,t)=>{typeof e=="function"?e(null,"",""):t?.(null,"","")},gi=()=>"",Enr="browser",Cnr=()=>"/",Rnr=()=>"/tmp",knr=()=>"browser",Anr=()=>[{}],Inr=()=>0,Pnr=()=>0,Mnr=()=>"Browser",Onr=()=>"wasm",Nnr=()=>"0",Dnr=()=>({}),Lnr=()=>({}),Unr=()=>({}),Fnr=()=>({}),$nr=()=>new Uint8Array,Bnr=()=>new Uint8Array,znr=()=>new Uint8Array,jnr=()=>new Uint8Array,Gnr=(r,e)=>e?.(null,r),qnr=(r,e)=>e?.(null,r),Vnr=()=>({}),Hnr=()=>({}),Knr=hs,Wnr={},Jnr=()=>()=>({}),Ynr=[],Xnr=()=>!1,Znr=r=>({pathname:r||"",hostname:"",protocol:"",search:"",hash:""}),Qnr=()=>"",eor=globalThis.URL,tor=globalThis.URLSearchParams,ror=r=>typeof r=="string"?r.replace("file://",""):r,nor=r=>new globalThis.URL("file://"+r),oor=(r,e)=>{e&&(r.super_=e,Object.setPrototypeOf(r.prototype,e.prototype))},sor=r=>(...e)=>new Promise((t,n)=>r(...e,(o,s)=>o?n(o):t(s))),YNe=r=>{let e=(...t)=>{};return e.enabled=!1,e},ior=YNe,tz=r=>{try{return JSON.stringify(r,null,2)}catch{return String(r)}};tz.custom=Symbol.for("nodejs.util.inspect.custom");tz.colors={};tz.styles={};aor=r=>r,cor=r=>(...e)=>{let t=e.pop();r(...e).then(n=>t(null,n)).catch(t)},lor=(r,e)=>JSON.stringify(r)===JSON.stringify(e),uor=r=>String(r),dor={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},XNe=globalThis.TextDecoder,ez=globalThis.TextEncoder,por=(r,e)=>e?.(null,"127.0.0.1",4),mor=class{},gor=globalThis.performance||{now:()=>Date.now()},hor=class{observe(){}disconnect(){}},yor=()=>({enable:hs,disable:hs,percentile:()=>0}),vor=()=>({}),xor=class{},bor=()=>!1,Tor=()=>new Uint8Array,Sor=hs,wor=class{},_or=!0,Eor=null,Cor=null,Ror=()=>({}),kor=class{},Aor=class{},Ior=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 ez().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 ez().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 XNe().decode(this)}},Por={F_OK:0,R_OK:4,W_OK:2,X_OK:1},Mor=()=>!1,Oor=()=>!1,Nor=()=>0,Dor=class{},Lor=class{},Uor=async()=>new ArrayBuffer(0),ZNe=r=>({[Symbol.toPrimitive](){return r},ref(){return this},unref(){return this},hasRef(){return!1},refresh(){return this},close(){}}),For=(...r)=>ZNe(globalThis.setTimeout(...r)),$or=globalThis.clearTimeout,Bor=(...r)=>ZNe(globalThis.setInterval(...r)),zor=globalThis.clearInterval,jor=class{constructor(r){this.type=r}toString(){return this.type}}});function Vor(){if(QNe)return;QNe=!0;let r=()=>{for(let e of rz)try{let t=Iw(e);for(let n of t)try{oI(Gt(e,n))}catch{}Tee(e)}catch{}rz.clear()};process.on("exit",r)}async function nz(r){Vor();let e=Gt(Pw(),`neurolink-${r}-${Vn()}`);return await Ka(e,{recursive:!0}),rz.add(e),e}async function oz(r,...e){for(let t of e)try{await hp(t)}catch(n){g.debug("Failed to clean up temp file",{path:t,error:n instanceof Error?n.message:String(n)})}try{await da(r,{recursive:!0,force:!0})}catch(t){g.debug("Failed to remove temp directory",{path:r,error:t instanceof Error?t.message:String(t)})}rz.delete(r)}async function Hor(){if(vh)return vh;if(process.env.FFMPEG_PATH)return vh=process.env.FFMPEG_PATH,vh;try{let r=await Promise.resolve().then(()=>(lQ(),cQ)),e=r.default??r;if(typeof e=="string"&&e.length>0)return vh=e,vh}catch{g.debug("ffmpeg-static not available, using system ffmpeg binary")}return vh="ffmpeg",g.warn("Using system ffmpeg binary. If video operations fail with ENOENT, install ffmpeg-static or set FFMPEG_PATH."),vh}async function sI(r,e={}){let{execFile:t}=await Promise.resolve().then(()=>(yh(),Cee)),n=await Hor(),o=e.timeoutMs??Ree,s=e.maxBuffer??kee;return new Promise((i,a)=>{t(n,r,{timeout:o,maxBuffer:s},(l,d,p)=>{l?a(l):i({stdout:d||"",stderr:p||""})}).on("error",a)})}function sz(r){return r.length<Gor?!1:r.subarray(4,8).equals(qor)}var Ree,eDe,kee,tDe,Aee,rDe,Gor,qor,rz,QNe,vh,Iee=E(()=>{"use strict";uc();Is();pa();Mw();to();J();Ree=3e4,eDe=12e4,kee=10*1024*1024,tDe=50*1024*1024,Aee="2",rDe="0.5",Gor=12,qor=Buffer.from([102,116,121,112]),rz=new Set,QNe=!1;vh=null});function Kor(r,e){if(!Buffer.isBuffer(r)||r.length===0)throw new pt({code:dt.DIRECTOR_FRAME_EXTRACTION_FAILED,message:`Cannot ${e}: video buffer is empty or not a Buffer`,category:"validation",severity:"high",retriable:!1,context:{operation:e,bufferSize:r?.length??0}});if(!sz(r))throw new pt({code:dt.DIRECTOR_FRAME_EXTRACTION_FAILED,message:`Cannot ${e}: buffer does not appear to be a valid MP4 (missing ftyp header)`,category:"validation",severity:"high",retriable:!1,context:{operation:e,bufferSize:r.length,headerHex:r.subarray(0,12).toString("hex")}})}async function nDe(r,e){let t=Date.now();Kor(r,`extract ${e} frame`);let n=await nz("frame"),o=Gt(n,"input.mp4"),s=Gt(n,`${e}_frame.jpg`);try{await Ha(o,r);let i=e==="first"?["-y","-i",o,"-vframes","1","-q:v",Aee,"-f","image2",s]:["-y","-sseof",`-${rDe}`,"-i",o,"-update","1","-q:v",Aee,"-f","image2",s];await sI(i,{timeoutMs:Ree,maxBuffer:kee});let a=await En(s);return g.debug(`Extracted ${e} frame`,{inputSize:r.length,frameSize:a.length,elapsedMs:Date.now()-t}),a}catch(i){throw i instanceof pt?i:new pt({code:dt.DIRECTOR_FRAME_EXTRACTION_FAILED,message:`Failed to extract ${e} frame: ${i instanceof Error?i.message:String(i)}`,category:"execution",severity:"high",retriable:!1,context:{position:e,bufferSize:r.length},originalError:i instanceof Error?i:void 0})}finally{await oz(n,o,s)}}async function oDe(r){return nDe(r,"first")}async function sDe(r){return nDe(r,"last")}var iDe=E(()=>{"use strict";J();Iee();np();ex()});async function Wor(r,e,t){let n=[],o=[];for(let s=0;s<r.length;s++){let i=Gt(e,`clip_${s}.mp4`);await Ha(i,r[s]),n.push(i);let a=i.replace(/\\/g,"/").replace(/'/g,"'\\''");o.push(`file '${a}'`)}return await Ha(t,o.join(`
1043
- `)),n}async function Jor(r,e){let t={timeoutMs:eDe,maxBuffer:tDe};try{await sI(["-y","-f","concat","-safe","0","-i",r,"-c","copy",e],t)}catch(n){g.warn("Lossless concat failed, falling back to H.264 re-encoding",{error:n instanceof Error?n.message:String(n)}),await sI(["-y","-f","concat","-safe","0","-i",r,"-c:v","libx264","-preset","fast","-crf","18","-c:a","aac","-b:a","192k","-movflags","+faststart",e],t)}}async function aDe(r){if(r.length===0)throw new pt({code:dt.DIRECTOR_MERGE_FAILED,message:"No video buffers provided to merge",category:"validation",severity:"high",retriable:!1});for(let i=0;i<r.length;i++)if(!sz(r[i]))throw new pt({code:dt.DIRECTOR_MERGE_FAILED,message:`Clip ${i} is not a valid MP4 buffer (missing ftyp header or too small)`,category:"validation",severity:"high",retriable:!1,context:{clipIndex:i,bufferSize:r[i].length,headerHex:r[i].subarray(0,12).toString("hex")}});if(r.length===1)return r[0];let e=Date.now(),t=await nz("merge"),n=Gt(t,"concat.txt"),o=Gt(t,"merged.mp4"),s=[];try{s=await Wor(r,t,n),await Jor(n,o);let i=await En(o);return g.info("Video merge complete",{inputClips:r.length,totalInputSize:r.reduce((a,c)=>a+c.length,0),outputSize:i.length,elapsedMs:Date.now()-e}),i}catch(i){throw i instanceof pt?i:new pt({code:dt.DIRECTOR_MERGE_FAILED,message:`Video merge failed: ${i instanceof Error?i.message:String(i)}`,category:"execution",severity:"high",retriable:!1,context:{clipCount:r.length},originalError:i instanceof Error?i:void 0})}finally{await oz(t,n,o,...s)}}var cDe=E(()=>{"use strict";J();Iee();np();ex()});var mDe={};ce(mDe,{DIRECTOR_PIPELINE_TIMEOUT_MS:()=>Zor,executeDirectorPipeline:()=>ssr});async function esr(r,e){if(Buffer.isBuffer(r))return r;if(typeof r=="string")return r.startsWith("http://")||r.startsWith("https://")?lDe(r,e):uDe(r,e);if(typeof r=="object"&&"data"in r){let t=r.data;if(Buffer.isBuffer(t))return t;if(typeof t=="string"){if(t.startsWith("http://")||t.startsWith("https://"))return lDe(t,e);if(t.startsWith("data:")){let n=t.match(/^data:[^;]+;base64,(.+)$/);if(n&&n[1])return Buffer.from(n[1],"base64");throw new pt({code:dt.INVALID_INPUT,message:`Invalid data URI format for segment ${e}. Expected format: data:<mime>;base64,<data>`,category:"execution",severity:"high",retriable:!1,context:{segmentIndex:e,dataUriPrefix:t.substring(0,50)}})}try{return await uDe(t,e)}catch(n){throw new pt({code:dt.INVALID_INPUT,message:`Invalid image input for segment ${e}: not a valid URL, file path, or data URI`,category:"execution",severity:"high",retriable:!1,context:{segmentIndex:e,inputType:"string",inputPrefix:t.substring(0,50),fileError:n instanceof Error?n.message:String(n)},originalError:n instanceof Error?n:void 0})}}}throw new pt({code:dt.INVALID_INPUT,message:`Invalid image type for segment ${e}`,category:"execution",severity:"high",retriable:!1,context:{segmentIndex:e}})}async function lDe(r,e){let t=new AbortController,n=setTimeout(()=>t.abort(),Yor);try{let o=await fetch(r,{signal:t.signal});if(!o.ok)throw new pt({code:dt.INVALID_INPUT,message:`Failed to fetch image for segment ${e}: HTTP ${o.status}`,category:"execution",severity:"high",retriable:o.status>=500,context:{segmentIndex:e,url:r.substring(0,100)}});return Buffer.from(await o.arrayBuffer())}catch(o){throw o instanceof pt?o:new pt({code:dt.INVALID_INPUT,message:`Failed to fetch image for segment ${e}: ${o instanceof Error?o.message:String(o)}`,category:"execution",severity:"high",retriable:!0,context:{segmentIndex:e},originalError:o instanceof Error?o:void 0})}finally{clearTimeout(n)}}async function uDe(r,e){let{readFile:t}=await Promise.resolve().then(()=>(pa(),bu));try{return await t(r)}catch(n){throw new pt({code:dt.INVALID_INPUT,message:`Failed to read image file for segment ${e}: ${n instanceof Error?n.message:String(n)}`,category:"execution",severity:"high",retriable:!1,context:{segmentIndex:e,path:r},originalError:n instanceof Error?n:void 0})}}function dDe(r){for(;r.nextExpectedIndex<r.completions.length;){let e=r.completions[r.nextExpectedIndex];if(e.status==="pending")break;e.status==="success"?r.consecutiveFailures=0:(r.consecutiveFailures++,r.consecutiveFailures>=Pee&&(r.circuitOpen=!0,g.error(`Circuit breaker tripped after ${Pee} consecutive clip failures`))),r.nextExpectedIndex++}}async function tsr(r,e,t,n,o){if(o.circuitOpen)throw new pt({code:dt.DIRECTOR_CLIP_FAILED,message:`Clip ${e} skipped \u2014 circuit breaker open after ${Pee} consecutive failures`,category:"execution",severity:"high",retriable:!0,context:{segmentIndex:e}});let s=Date.now();try{let i=await esr(r.image,e),a=IB(i);if(a)throw new pt({code:dt.INVALID_INPUT,message:`Segment ${e} image validation failed: ${a.message}`,category:"execution",severity:"high",retriable:!1,context:{segmentIndex:e,validation:a},originalError:a});let l={buffer:(await HB(i,r.prompt,t,n)).data,processingTime:Date.now()-s};o.results[e]=l,o.completions[e]={status:"success",result:l},dDe(o)}catch(i){let a=i instanceof Error?i:new Error(String(i));throw o.completions[e]={status:"failure",error:a},dDe(o),new pt({code:dt.DIRECTOR_CLIP_FAILED,message:`Clip ${e} generation failed: ${a.message}`,category:"execution",severity:"high",retriable:!0,context:{segmentIndex:e,consecutiveFailures:o.consecutiveFailures},originalError:a})}}async function rsr(r,e,t){let n=kp(iz),o={consecutiveFailures:0,circuitOpen:!1,results:new Array(r.length).fill(null),completions:new Array(r.length).fill({status:"pending"}),nextExpectedIndex:0},s=r.map((c,l)=>n(()=>tsr(c,l,e,t,o))),a=(await Promise.allSettled(s)).filter(c=>c.status==="rejected");if(a.length>0){let c=a[0].reason instanceof Error?a[0].reason:new Error(String(a[0].reason));throw new pt({code:dt.DIRECTOR_CLIP_FAILED,message:`Director Mode: ${a.length}/${r.length} clip(s) failed. First: ${c.message}`,category:"execution",severity:"high",retriable:!0,context:{failedCount:a.length,totalSegments:r.length,circuitBreakerTripped:o.circuitOpen},originalError:c})}return g.info("All clips generated successfully",{clipCount:r.length,concurrency:iz}),o.results}async function nsr(r,e,t,n,o){let s=r.length-1;if(s===0)return[];let i=kp(iz),a=Array.from({length:s},(c,l)=>i(async()=>{let d=Date.now(),p=e[l]??Xor,m=t[l]??Qor;try{let f=await pDe(r[l].buffer,"last",l),h=await pDe(r[l+1].buffer,"first",l+1),y=await KB(f,h,p,{aspectRatio:n.aspectRatio,resolution:n.resolution,audio:n.audio},m,o);return g.debug(`Transition ${l}\u2192${l+1} generated`,{duration:m,size:y.length,elapsedMs:Date.now()-d}),{buffer:y,fromSegment:l,toSegment:l+1,duration:m,processingTime:Date.now()-d}}catch(f){return g.warn(`Transition ${l}\u2192${l+1} failed, falling back to hard cut`,{error:f instanceof Error?f.message:String(f)}),{buffer:null,fromSegment:l,toSegment:l+1,duration:0,processingTime:Date.now()-d}}}));return Promise.all(a)}async function pDe(r,e,t){let n=e==="first"?oDe:sDe;try{return await n(r)}catch(o){return g.warn(`Frame extraction (${e}) failed for clip ${t}, retrying once`,{error:o instanceof Error?o.message:String(o)}),await n(r)}}async function osr(r,e){let t=[],n=r.length,o=e.length;for(let s=0;s<n;s++)t.push(r[s].buffer),s<o&&e[s].buffer&&t.push(e[s].buffer);try{return await aDe(t)}catch(s){throw new pt({code:dt.DIRECTOR_MERGE_FAILED,message:`Director Mode merge failed: ${s instanceof Error?s.message:String(s)}`,category:"execution",severity:"high",retriable:!1,context:{clipCount:n,transitionCount:e.filter(i=>i.buffer).length},originalError:s instanceof Error?s:void 0})}}async function ssr(r,e={},t={},n){let o=Date.now(),s=r.length,i=s-1,a=e.length??6,c=t.transitionPrompts??[],l=t.transitionDurations??[];g.info("Starting Director Mode pipeline",{segmentCount:s,transitionCount:i,concurrency:iz,clipDuration:a,resolution:e.resolution??"720p"});let d=await rsr(r,e,n);g.info("Phase 1 complete \u2014 all clips generated",{clipCount:d.length,elapsedMs:Date.now()-o});let p=await nsr(d,c,l,e,n),m=p.filter(R=>R.buffer).length,f=i-m;f>0&&g.warn(`${f}/${i} transition(s) fell back to hard cut`),g.info("Phase 2 complete \u2014 transitions generated",{successful:m,hardCuts:f,elapsedMs:Date.now()-o});let h=await osr(d,p),y=p.map(R=>R.duration),v=s*a+y.reduce((R,k)=>R+k,0),b=e.resolution??"720p",S=e.aspectRatio??"16:9",w=b==="1080p"?S==="9:16"?{width:1080,height:1920}:{width:1920,height:1080}:S==="9:16"?{width:720,height:1280}:{width:1280,height:720},C=Date.now()-o;return g.info("Director Mode pipeline complete",{totalDuration:v,segmentCount:s,transitionsGenerated:m,hardCuts:f,mergedSize:h.length,processingTime:C}),{data:h,mediaType:"video/mp4",metadata:{duration:v,dimensions:w,model:"veo-3.1-generate-001",provider:"vertex",aspectRatio:S,audioEnabled:e.audio??!0,processingTime:C,segmentCount:s,transitionCount:m,clipDuration:a,transitionDurations:y,segments:d.map((R,k)=>({index:k,duration:a,processingTime:R.processingTime})),transitions:p.map(R=>({fromSegment:R.fromSegment,toSegment:R.toSegment,duration:R.duration,processingTime:R.processingTime}))}}}var iz,Pee,Yor,Xor,Zor,Qor,gDe=E(()=>{"use strict";nI();J();ch();np();iDe();ex();cDe();iz=2,Pee=2,Yor=15e3,Xor="Smooth cinematic transition between scenes",Zor=6e5,Qor=4});function fDe(r){return r?.middleware?.middlewareConfig?.lifecycle?.config}var ro,Dl=E(()=>{"use strict";yr();Sk();zs();uY();Om();Bc();St();Lk();q1();wY();J();jo();Nn();ok();fp();qk();Vi();DIe();r7();x2();o7();XS();EPe();gOe();IOe();hNe();ANe();MNe();dv();ZS();ro=class r{modelName;providerName;defaultTimeout=3e4;middlewareOptions;directTools=ZT()?{}:lp;mcpTools;customTools;toolExecutor;sessionId;userId;neurolink;_traceContext=null;setTraceContext(e){this._traceContext=e}messageBuilder;streamHandler;generationHandler;telemetryHandler;utilities;toolsManager;constructor(e,t,n,o){this.modelName=e||this.getDefaultModel(),this.providerName=t||this.getProviderName(),this.neurolink=n,this.middlewareOptions=o,this.messageBuilder=new $A(this.providerName,this.modelName),this.streamHandler=new qA(this.providerName,this.modelName),this.telemetryHandler=new XA(this.providerName,this.modelName,this.neurolink),this.generationHandler=new wA(this.providerName,this.modelName,()=>this.supportsTools(),(s,i)=>this.telemetryHandler.getTelemetryConfig(s,i),(s,i,a,c)=>this.handleToolExecutionStorage(s,i,a,c),()=>this.neurolink?.getEventEmitter()),this.utilities=new eI(this.providerName,this.modelName,this.defaultTimeout,this.middlewareOptions),this.toolsManager=new BB(this.providerName,this.directTools,this.neurolink,{isZodSchema:s=>this.isZodSchema(s),convertToolResult:s=>this.convertToolResult(s),createPermissiveZodSchema:()=>this.createPermissiveZodSchema(),fixSchemaForOpenAIStrictMode:s=>this.fixSchemaForOpenAIStrictMode(s)})}refreshHandlersForModel(e){this.modelName=e,ft.getSpan(hr.active())?.setAttribute(Pe.GEN_AI_MODEL,this.modelName),this.messageBuilder=new $A(this.providerName,this.modelName),this.streamHandler=new qA(this.providerName,this.modelName),this.telemetryHandler=new XA(this.providerName,this.modelName,this.neurolink),this.generationHandler=new wA(this.providerName,this.modelName,()=>this.supportsTools(),(t,n)=>this.telemetryHandler.getTelemetryConfig(t,n),(t,n,o,s)=>this.handleToolExecutionStorage(t,n,o,s),()=>this.neurolink?.getEventEmitter()),this.utilities=new eI(this.providerName,this.modelName,this.defaultTimeout,this.middlewareOptions)}supportsTools(){return eke("functionCalling",this.providerName,this.modelName)}shouldUseTools(e,t=!1){if(e.disableTools)return!1;let n=this.supportsTools();return!n&&t&&g.warn(`Tools disabled for ${this.providerName}/${this.modelName} because the model does not support function calling`,{provider:this.providerName,model:this.modelName}),n}async stream(e,t){await this.ensureModelLimits();let n=this.normalizeStreamOptions(e);if(g.info("Starting stream",{provider:this.providerName,hasTools:!n.disableTools&&this.supportsTools(),disableTools:!!n.disableTools,supportsTools:this.supportsTools(),inputLength:n.input?.text?.length||0,maxTokens:n.maxTokens,temperature:n.temperature,timestamp:Date.now()}),!!n.input?.files?.length||!!n.input?.videoFiles?.length||!!n.input?.audioFiles?.length){let a=await this.buildMessagesForStream(n);if(e7(a)){g.info("Video frames detected in stream, using fake streaming for video analysis",{provider:this.providerName,model:this.modelName});let c=await this.executeFakeStreaming(n,t);return this.wrapStreamWithLifecycleCallbacks(c,n)}}let s=_l.some(a=>this.modelName.includes(a)),i=n.output?.format==="json"||n.output?.format==="structured"||n.output?.format==="text";if(s&&!i){g.info("Image model detected, forcing fake streaming",{provider:this.providerName,model:this.modelName,reason:"Image generation requires fake streaming to yield image output"});let a=await this.executeFakeStreaming(n,t);return this.wrapStreamWithLifecycleCallbacks(a,n)}if(this.shouldUseTools(n,!0)){let a=await this.getToolsForStream(n);n={...n,tools:a}}else n={...n,tools:{}};try{g.debug("Attempting real streaming",{provider:this.providerName,timestamp:Date.now()});let a=await this.executeStream(n,t);return g.info("Real streaming succeeded",{provider:this.providerName,timestamp:Date.now()}),this.wrapStreamWithLifecycleCallbacks(a,n)}catch(a){let c=a instanceof Error?a.message:String(a);if((a instanceof Error?a.name:"")==="AbortError"||c.includes("abort")||c.includes("timeout")||c.includes("401")||c.includes("403")||c.includes("quota")||c.includes("rate limit")||c.includes("authentication"))throw await this.fireLifecycleErrorCallback(n,a),this.handleProviderError(a);if(g.warn(`Real streaming failed for ${this.providerName}, falling back to fake streaming:`,{error:c,timestamp:Date.now()}),!n.disableTools&&this.supportsTools()){let d=await this.executeFakeStreaming(n,t);return this.wrapStreamWithLifecycleCallbacks(d,n)}else throw await this.fireLifecycleErrorCallback(n,a),g.error(`Real streaming failed for ${this.providerName}:`,a),this.handleProviderError(a)}}wrapStreamWithLifecycleCallbacks(e,t){let n=fDe(t);if(!n?.onChunk&&!n?.onFinish&&!n?.onError)return e;let{onChunk:o,onFinish:s,onError:i}=n,a=Date.now(),c=e.stream,l=Uk(n),d=async(m,f)=>{try{await YT(async()=>{let h=m();h&&typeof h.then=="function"&&await h},l,`[lifecycle] ${f} callback exceeded ${l}ms`)}catch(h){g.warn(`[lifecycle] ${f} callback error:`,h)}},p=(async function*(){let m="",f=0;try{for await(let h of c){let y=h&&typeof h=="object"&&"content"in h&&typeof h.content=="string"?h.content:"";if(o&&y){let v=f++;await d(()=>o({type:"text-delta",textDelta:y,sequenceNumber:v}),"onChunk")}y&&(m+=y),yield h}s&&await d(()=>s({text:m,duration:Date.now()-a}),"onFinish")}catch(h){let y=h instanceof Error?h:new Error(String(h));throw i&&!Iv(y)&&(IS(y),await d(()=>i({error:y,duration:Date.now()-a,recoverable:!1}),"onError")),y}})();return{...e,stream:p}}async fireLifecycleErrorCallback(e,t){let n=t instanceof Error?t:new Error(String(t));if(Iv(n))return;let o=fDe(e),s=o?.onError;if(!s)return;IS(n);let i=Uk(o);try{await YT(async()=>{let a=s({error:n,duration:0,recoverable:!1});a&&typeof a.then=="function"&&await a},i,`[lifecycle] onError callback exceeded ${i}ms`)}catch(a){g.warn("[lifecycle] onError callback error:",a)}}async executeFakeStreaming(e,t){try{g.info("Starting fake streaming with tools",{provider:this.providerName,supportsTools:this.supportsTools(),timestamp:Date.now()});let n={prompt:e.input?.text||"",input:e.input,systemPrompt:e.systemPrompt,temperature:e.temperature,maxTokens:e.maxTokens,tools:e.tools,disableTools:!!e.disableTools,maxSteps:e.maxSteps||5,provider:e.provider,model:e.model,region:e.region,enableAnalytics:e.enableAnalytics,enableEvaluation:e.enableEvaluation,evaluationDomain:e.evaluationDomain,toolUsageContext:e.toolUsageContext,context:e.context,csvOptions:e.csvOptions,pdfOptions:e.pdfOptions,abortSignal:e.abortSignal,toolFilter:e.toolFilter,excludeTools:e.excludeTools,skipToolPromptInjection:e.skipToolPromptInjection,timeout:e.timeout,stt:e.stt,tts:e.tts};g.debug("Calling generate for fake streaming",{provider:this.providerName,maxSteps:n.maxSteps,disableTools:n.disableTools,timestamp:Date.now()});let o=await this.generate(n,t);return g.info("Generate completed for fake streaming",{provider:this.providerName,hasContent:!!o?.content,contentLength:o?.content?.length||0,toolsUsed:o?.toolsUsed?.length||0,hasImageOutput:!!o?.imageOutput,timestamp:Date.now()}),{stream:(async function*(){if(o?.content){let s=o.content.split(/(\s+)/),i="";for(let a=0;a<s.length;a++)i+=s[a],(a===s.length-1||i.length>50||/[.!?;,]\s*$/.test(i))&&i.trim()&&(yield{content:i},i="",await new Promise(l=>{setTimeout(l,Math.random()*9+1)}));i.trim()&&(yield{content:i})}o?.imageOutput&&(yield{type:"image",imageOutput:o.imageOutput}),o?.audio&&(yield{type:"tts_audio",audio:{data:o.audio.buffer,format:o.audio.format,index:0,isFinal:!0,cumulativeSize:o.audio.size,voice:o.audio.voice,sampleRate:o.audio.sampleRate}})})(),usage:o?.usage,provider:o?.provider,model:o?.model,toolCalls:o?.toolCalls?.map(s=>({toolName:s.toolName,parameters:s.args,id:s.toolCallId})),toolResults:o?.toolResults?o.toolResults.map(s=>({toolName:s.toolName||"unknown",status:s.status==="error"?"failure":"success",result:s.output??s.result,error:s.error})):void 0,analytics:o?.analytics,evaluation:o?.evaluation}}catch(n){throw g.error(`Fake streaming fallback failed for ${this.providerName}:`,n),await this.fireLifecycleErrorCallback(e,n),this.handleProviderError(n)}}getToolPolicy(e){return v2({options:{disableTools:e.disableTools,toolFilter:e.toolFilter,excludeTools:e.excludeTools,enabledToolNames:e.enabledToolNames},instanceConfig:this.neurolink?.getToolsConfig(),builtinToolNames:Object.keys(this.directTools??{})})}applyToolFiltering(e,t){let n=this.getToolPolicy(t),o=this.neurolink?.getToolDedupConfig(),s=o!==void 0&&o.enabled===!0,i=Object.keys(e).length,a=b2(e,n),c=Object.keys(a).length;if(i!==c&&g.debug("Tool filtering applied",{provider:this.providerName,beforeCount:i,afterCount:c,policySources:n.sources,toolFilter:t.toolFilter,excludeTools:t.excludeTools,enabledToolNames:t.enabledToolNames}),!s||o===void 0)return this.sortToolRecord(a);let l=this.applyDedupPass(a,o),d=t.toolChoice?.toolName;return typeof d=="string"&&!Object.hasOwn(l,d)&&Object.hasOwn(a,d)&&(l[d]=a[d],g.debug("Restored toolChoice-forced tool removed by signature dedup",{provider:this.providerName,toolName:d})),this.sortToolRecord(l)}sortToolRecord(e){let t=Object.create(null);for(let n of Object.keys(e).sort())t[n]=e[n];return t}async applyToolDiscovery(e,t){let n=e;if(VIe(n.search_tools)){let{search_tools:y,...v}=n;n=v}let o=Object.keys(n).length;if(!this.getToolPolicy(t).discovery)return o>GIe&&this.warnLargeCatalogOnce(o),n;let i=this.neurolink?.getExternalMCPTools()??[];if(i.length===0)return n;let a=t.context?.sessionId,c=typeof a=="string"&&a.length>0?a:typeof a=="number"?String(a):void 0,l=(c?this.neurolink?.getDiscoveryPins(c):void 0)??new Set,d=new Set(Object.keys(t.tools??{})),p=[...t.toolFilter??[],...t.enabledToolNames??[]],m=t.toolChoice;m&&typeof m.toolName=="string"&&p.push(m.toolName);let f=p.length>0?YS(p):null,h=i.map(y=>y.name).filter(y=>y in n&&!d.has(y)&&!(f&&f(y)));return HIe(n,{deferrableNames:h,pinnedNames:l,onHydrate:y=>{c&&this.neurolink?.pinDiscoveredTools(c,y)}})}static warnedLargeCatalog=!1;warnLargeCatalogOnce(e){r.warnedLargeCatalog||(r.warnedLargeCatalog=!0,g.warn(`[ToolDiscovery] ${e} tools are being sent in full on every request (~${Math.round(e*175/100)/10}K tokens). Tool-selection accuracy degrades past 30-50 tools \u2014 consider enabling on-demand discovery: new NeuroLink({ tools: { discovery: true } })`,{toolCount:e,provider:this.providerName}))}applyDedupPass(e,t){let{tools:n,removed:o}=t7(e,t);return o.length>0&&g.shouldLog("debug")&&g.debug("Tool signature dedup removed duplicates",{provider:this.providerName,removedCount:o.length,removed:o.map(s=>({name:s.name,duplicateOf:s.duplicateOf,similarity:s.similarity}))}),n}async prepareGenerationContext(e){let t=this.shouldUseTools(e,!0),n=t?await this.getAllTools():{},o=t?{...n,...e.tools||{}}:{};o=this.applyToolFiltering(o,e),o=this.wrapToolsForExecutionCapture(o,e),o=await this.applyToolDiscovery(o,e),g.debug("Final tools prepared for AI",{provider:this.providerName,directTools:LS(n),directToolNames:d$(n),externalTools:LS(e.tools||{}),externalToolNames:d$(e.tools||{}),totalTools:LS(o),totalToolNames:d$(o),shouldUseTools:t,timestamp:Date.now()});let s=await this.getAISDKModelWithMiddleware(e);return{tools:o,model:s}}async getToolsForStream(e){if(!this.shouldUseTools(e))return{};let n=await this.getAllTools(),o=e.tools||{},s={...n,...o};return s=this.applyToolFiltering(s,e),s=this.wrapToolsForExecutionCapture(s,e),s=await this.applyToolDiscovery(s,e),g.debug("Tools prepared for streaming",{provider:this.providerName,baseToolCount:Object.keys(n).length,externalToolCount:Object.keys(o).length,totalToolCount:Object.keys(s).length}),s}wrapToolsForExecutionCapture(e,t){if(Object.keys(e).length===0)return e;let n=US.from(t);return n||(n=new US(t.toolExecutionCapture),n.attachTo(t)),n.wrapTools(e)}async buildMessages(e){return this.messageBuilder.buildMessages(e)}async buildMessagesForStream(e){return this.messageBuilder.buildMessagesForStream(e)}async executeGeneration(e,t,n,o){return this.generationHandler.executeGeneration(e,t,n,o)}logGenerationComplete(e){this.generationHandler.logGenerationComplete(e)}async recordPerformanceMetrics(e,t){await this.telemetryHandler.recordPerformanceMetrics(e,t)}extractToolInformation(e){return this.generationHandler.extractToolInformation(e)}formatEnhancedResult(e,t,n,o,s){return this.generationHandler.formatEnhancedResult(e,t,n,o,s)}analyzeAIResponse(e){this.generationHandler.analyzeAIResponse(e)}async ensureModelLimits(){}async generate(e,t){await this.ensureModelLimits();let n=this.normalizeTextOptions(e);this.validateOptions(n);let o=Date.now(),s=Oe.provider.startSpan("neurolink.provider.generate",{kind:Tr.CLIENT,attributes:{[Pe.GEN_AI_SYSTEM]:this.providerName||"unknown",[Pe.GEN_AI_MODEL]:this.modelName||n.model||"unknown",[Pe.GEN_AI_OPERATION]:"generate",[Pe.NL_PROVIDER]:this.providerName||"unknown"}}),i=ft.setSpan(hr.active(),s),a={ended:!1};return await hr.with(i,async()=>this.runGenerateInActiveContext(n,o,s,a))}async gen(e,t){return this.generate(e,t)}async runGenerateInActiveContext(e,t,n,o){try{if(e.output?.mode==="video")return await this.handleVideoGeneration(e,t);let s=_l.some(p=>this.modelName.includes(p)),i=e.output?.format==="json"||e.output?.format==="structured"||e.output?.format==="text";if(s&&!i){g.info("Image generation model detected, routing to executeImageGeneration",{provider:this.providerName,model:this.modelName});let p=await this.executeImageGeneration(e);return await this.enhanceResult(p,e,t)}if(e.tts?.enabled&&!e.tts?.useAiResponse)return this.handleDirectTTSSynthesis(e,t);let{tools:a,model:c}=await this.prepareGenerationContext(e),l=await this.buildMessages(e),d=await this.handleVideoFrameGeneration(e,l,c,t);return d||await this.executeStandardGenerateFlow(e,t,c,l,a)}catch(s){throw n.setStatus({code:Ue.ERROR,message:s instanceof Error?s.message:String(s)}),n.end(),o.ended=!0,Ar(s)?g.info(`Generate aborted for ${this.providerName}`,{error:s instanceof Error?s.message:String(s)}):g.error(`Generate failed for ${this.providerName}:`,s),this.handleProviderError(s)}finally{o.ended||(n.setStatus({code:Ue.OK}),n.end())}}async handleDirectTTSSynthesis(e,t){let n=e.prompt??e.input?.text??"",o={content:n,provider:e.provider??this.providerName,model:this.modelName,usage:{input:0,output:0,total:0}},s=e.tts;if(!s)return this.enhanceResult(o,e,t);let i=Date.now(),a=s.provider??e.provider??this.providerName,c=this.getTimeout(e);try{o.audio=await YT(()=>pd.synthesize(n,a,s),c,`TTS synthesis timed out after ${c}ms for provider "${a}"`),o.ttsMetadata={attempted:!0,success:!0,latency:Date.now()-i}}catch(l){let d=Date.now()-i,p=this.getTTSErrorDetails(l);o.ttsMetadata={attempted:!0,success:!1,error:p,latency:d},this.telemetryHandler.recordTTSFailure(a,p,d),g.error("TTS synthesis failed in Mode 1 (direct input synthesis):",l)}return this.enhanceResult(o,e,t)}async handleVideoFrameGeneration(e,t,n,o){if(!e7(t))return null;if(e.schema!==void 0||e.output?.format!==void 0)return g.info("[VideoFrameGen] Skipping video-frame analysis route; caller requested structured output",{provider:this.providerName,model:this.modelName,hasSchema:e.schema!==void 0,outputFormat:e.output?.format}),null;let s=await NIe(t,{provider:e.provider,providerName:this.providerName,region:e.region}),i=t.filter(l=>l.role==="user").flatMap(l=>Array.isArray(l.content)?l.content.filter(d=>d.type==="text").map(d=>d.text):[typeof l.content=="string"?l.content:""]).filter(Boolean).join(`
1043
+ `)),n}async function Jor(r,e){let t={timeoutMs:eDe,maxBuffer:tDe};try{await sI(["-y","-f","concat","-safe","0","-i",r,"-c","copy",e],t)}catch(n){g.warn("Lossless concat failed, falling back to H.264 re-encoding",{error:n instanceof Error?n.message:String(n)}),await sI(["-y","-f","concat","-safe","0","-i",r,"-c:v","libx264","-preset","fast","-crf","18","-c:a","aac","-b:a","192k","-movflags","+faststart",e],t)}}async function aDe(r){if(r.length===0)throw new pt({code:dt.DIRECTOR_MERGE_FAILED,message:"No video buffers provided to merge",category:"validation",severity:"high",retriable:!1});for(let i=0;i<r.length;i++)if(!sz(r[i]))throw new pt({code:dt.DIRECTOR_MERGE_FAILED,message:`Clip ${i} is not a valid MP4 buffer (missing ftyp header or too small)`,category:"validation",severity:"high",retriable:!1,context:{clipIndex:i,bufferSize:r[i].length,headerHex:r[i].subarray(0,12).toString("hex")}});if(r.length===1)return r[0];let e=Date.now(),t=await nz("merge"),n=Gt(t,"concat.txt"),o=Gt(t,"merged.mp4"),s=[];try{s=await Wor(r,t,n),await Jor(n,o);let i=await En(o);return g.info("Video merge complete",{inputClips:r.length,totalInputSize:r.reduce((a,c)=>a+c.length,0),outputSize:i.length,elapsedMs:Date.now()-e}),i}catch(i){throw i instanceof pt?i:new pt({code:dt.DIRECTOR_MERGE_FAILED,message:`Video merge failed: ${i instanceof Error?i.message:String(i)}`,category:"execution",severity:"high",retriable:!1,context:{clipCount:r.length},originalError:i instanceof Error?i:void 0})}finally{await oz(t,n,o,...s)}}var cDe=E(()=>{"use strict";J();Iee();np();ex()});var mDe={};ce(mDe,{DIRECTOR_PIPELINE_TIMEOUT_MS:()=>Zor,executeDirectorPipeline:()=>ssr});async function esr(r,e){if(Buffer.isBuffer(r))return r;if(typeof r=="string")return r.startsWith("http://")||r.startsWith("https://")?lDe(r,e):uDe(r,e);if(typeof r=="object"&&"data"in r){let t=r.data;if(Buffer.isBuffer(t))return t;if(typeof t=="string"){if(t.startsWith("http://")||t.startsWith("https://"))return lDe(t,e);if(t.startsWith("data:")){let n=t.match(/^data:[^;]+;base64,(.+)$/);if(n&&n[1])return Buffer.from(n[1],"base64");throw new pt({code:dt.INVALID_INPUT,message:`Invalid data URI format for segment ${e}. Expected format: data:<mime>;base64,<data>`,category:"execution",severity:"high",retriable:!1,context:{segmentIndex:e,dataUriPrefix:t.substring(0,50)}})}try{return await uDe(t,e)}catch(n){throw new pt({code:dt.INVALID_INPUT,message:`Invalid image input for segment ${e}: not a valid URL, file path, or data URI`,category:"execution",severity:"high",retriable:!1,context:{segmentIndex:e,inputType:"string",inputPrefix:t.substring(0,50),fileError:n instanceof Error?n.message:String(n)},originalError:n instanceof Error?n:void 0})}}}throw new pt({code:dt.INVALID_INPUT,message:`Invalid image type for segment ${e}`,category:"execution",severity:"high",retriable:!1,context:{segmentIndex:e}})}async function lDe(r,e){let t=new AbortController,n=setTimeout(()=>t.abort(),Yor);try{let o=await fetch(r,{signal:t.signal});if(!o.ok)throw new pt({code:dt.INVALID_INPUT,message:`Failed to fetch image for segment ${e}: HTTP ${o.status}`,category:"execution",severity:"high",retriable:o.status>=500,context:{segmentIndex:e,url:r.substring(0,100)}});return Buffer.from(await o.arrayBuffer())}catch(o){throw o instanceof pt?o:new pt({code:dt.INVALID_INPUT,message:`Failed to fetch image for segment ${e}: ${o instanceof Error?o.message:String(o)}`,category:"execution",severity:"high",retriable:!0,context:{segmentIndex:e},originalError:o instanceof Error?o:void 0})}finally{clearTimeout(n)}}async function uDe(r,e){let{readFile:t}=await Promise.resolve().then(()=>(pa(),bu));try{return await t(r)}catch(n){throw new pt({code:dt.INVALID_INPUT,message:`Failed to read image file for segment ${e}: ${n instanceof Error?n.message:String(n)}`,category:"execution",severity:"high",retriable:!1,context:{segmentIndex:e,path:r},originalError:n instanceof Error?n:void 0})}}function dDe(r){for(;r.nextExpectedIndex<r.completions.length;){let e=r.completions[r.nextExpectedIndex];if(e.status==="pending")break;e.status==="success"?r.consecutiveFailures=0:(r.consecutiveFailures++,r.consecutiveFailures>=Pee&&(r.circuitOpen=!0,g.error(`Circuit breaker tripped after ${Pee} consecutive clip failures`))),r.nextExpectedIndex++}}async function tsr(r,e,t,n,o){if(o.circuitOpen)throw new pt({code:dt.DIRECTOR_CLIP_FAILED,message:`Clip ${e} skipped \u2014 circuit breaker open after ${Pee} consecutive failures`,category:"execution",severity:"high",retriable:!0,context:{segmentIndex:e}});let s=Date.now();try{let i=await esr(r.image,e),a=IB(i);if(a)throw new pt({code:dt.INVALID_INPUT,message:`Segment ${e} image validation failed: ${a.message}`,category:"execution",severity:"high",retriable:!1,context:{segmentIndex:e,validation:a},originalError:a});let l={buffer:(await HB(i,r.prompt,t,n)).data,processingTime:Date.now()-s};o.results[e]=l,o.completions[e]={status:"success",result:l},dDe(o)}catch(i){let a=i instanceof Error?i:new Error(String(i));throw o.completions[e]={status:"failure",error:a},dDe(o),new pt({code:dt.DIRECTOR_CLIP_FAILED,message:`Clip ${e} generation failed: ${a.message}`,category:"execution",severity:"high",retriable:!0,context:{segmentIndex:e,consecutiveFailures:o.consecutiveFailures},originalError:a})}}async function rsr(r,e,t){let n=kp(iz),o={consecutiveFailures:0,circuitOpen:!1,results:new Array(r.length).fill(null),completions:new Array(r.length).fill({status:"pending"}),nextExpectedIndex:0},s=r.map((c,l)=>n(()=>tsr(c,l,e,t,o))),a=(await Promise.allSettled(s)).filter(c=>c.status==="rejected");if(a.length>0){let c=a[0].reason instanceof Error?a[0].reason:new Error(String(a[0].reason));throw new pt({code:dt.DIRECTOR_CLIP_FAILED,message:`Director Mode: ${a.length}/${r.length} clip(s) failed. First: ${c.message}`,category:"execution",severity:"high",retriable:!0,context:{failedCount:a.length,totalSegments:r.length,circuitBreakerTripped:o.circuitOpen},originalError:c})}return g.info("All clips generated successfully",{clipCount:r.length,concurrency:iz}),o.results}async function nsr(r,e,t,n,o){let s=r.length-1;if(s===0)return[];let i=kp(iz),a=Array.from({length:s},(c,l)=>i(async()=>{let d=Date.now(),p=e[l]??Xor,m=t[l]??Qor;try{let f=await pDe(r[l].buffer,"last",l),h=await pDe(r[l+1].buffer,"first",l+1),y=await KB(f,h,p,{aspectRatio:n.aspectRatio,resolution:n.resolution,audio:n.audio},m,o);return g.debug(`Transition ${l}\u2192${l+1} generated`,{duration:m,size:y.length,elapsedMs:Date.now()-d}),{buffer:y,fromSegment:l,toSegment:l+1,duration:m,processingTime:Date.now()-d}}catch(f){return g.warn(`Transition ${l}\u2192${l+1} failed, falling back to hard cut`,{error:f instanceof Error?f.message:String(f)}),{buffer:null,fromSegment:l,toSegment:l+1,duration:0,processingTime:Date.now()-d}}}));return Promise.all(a)}async function pDe(r,e,t){let n=e==="first"?oDe:sDe;try{return await n(r)}catch(o){return g.warn(`Frame extraction (${e}) failed for clip ${t}, retrying once`,{error:o instanceof Error?o.message:String(o)}),await n(r)}}async function osr(r,e){let t=[],n=r.length,o=e.length;for(let s=0;s<n;s++)t.push(r[s].buffer),s<o&&e[s].buffer&&t.push(e[s].buffer);try{return await aDe(t)}catch(s){throw new pt({code:dt.DIRECTOR_MERGE_FAILED,message:`Director Mode merge failed: ${s instanceof Error?s.message:String(s)}`,category:"execution",severity:"high",retriable:!1,context:{clipCount:n,transitionCount:e.filter(i=>i.buffer).length},originalError:s instanceof Error?s:void 0})}}async function ssr(r,e={},t={},n){let o=Date.now(),s=r.length,i=s-1,a=e.length??6,c=t.transitionPrompts??[],l=t.transitionDurations??[];g.info("Starting Director Mode pipeline",{segmentCount:s,transitionCount:i,concurrency:iz,clipDuration:a,resolution:e.resolution??"720p"});let d=await rsr(r,e,n);g.info("Phase 1 complete \u2014 all clips generated",{clipCount:d.length,elapsedMs:Date.now()-o});let p=await nsr(d,c,l,e,n),m=p.filter(R=>R.buffer).length,f=i-m;f>0&&g.warn(`${f}/${i} transition(s) fell back to hard cut`),g.info("Phase 2 complete \u2014 transitions generated",{successful:m,hardCuts:f,elapsedMs:Date.now()-o});let h=await osr(d,p),y=p.map(R=>R.duration),v=s*a+y.reduce((R,k)=>R+k,0),b=e.resolution??"720p",S=e.aspectRatio??"16:9",w=b==="1080p"?S==="9:16"?{width:1080,height:1920}:{width:1920,height:1080}:S==="9:16"?{width:720,height:1280}:{width:1280,height:720},C=Date.now()-o;return g.info("Director Mode pipeline complete",{totalDuration:v,segmentCount:s,transitionsGenerated:m,hardCuts:f,mergedSize:h.length,processingTime:C}),{data:h,mediaType:"video/mp4",metadata:{duration:v,dimensions:w,model:"veo-3.1-generate-001",provider:"vertex",aspectRatio:S,audioEnabled:e.audio??!0,processingTime:C,segmentCount:s,transitionCount:m,clipDuration:a,transitionDurations:y,segments:d.map((R,k)=>({index:k,duration:a,processingTime:R.processingTime})),transitions:p.map(R=>({fromSegment:R.fromSegment,toSegment:R.toSegment,duration:R.duration,processingTime:R.processingTime}))}}}var iz,Pee,Yor,Xor,Zor,Qor,gDe=E(()=>{"use strict";nI();J();ch();np();iDe();ex();cDe();iz=2,Pee=2,Yor=15e3,Xor="Smooth cinematic transition between scenes",Zor=6e5,Qor=4});function fDe(r){return r?.middleware?.middlewareConfig?.lifecycle?.config}var ro,Dl=E(()=>{"use strict";yr();Sk();zs();uY();Om();Bc();St();Lk();q1();wY();J();jo();Nn();ok();fp();qk();Vi();DIe();r7();x2();o7();XS();EPe();gOe();IOe();hNe();ANe();MNe();dv();ZS();ro=class r{modelName;providerName;defaultTimeout=3e4;middlewareOptions;directTools=ZT()?{}:lp;mcpTools;customTools;toolExecutor;sessionId;userId;neurolink;_traceContext=null;setTraceContext(e){this._traceContext=e}messageBuilder;streamHandler;generationHandler;telemetryHandler;utilities;toolsManager;constructor(e,t,n,o){this.modelName=e||this.getDefaultModel(),this.providerName=t||this.getProviderName(),this.neurolink=n,this.middlewareOptions=o,this.messageBuilder=new $A(this.providerName,this.modelName),this.streamHandler=new qA(this.providerName,this.modelName),this.telemetryHandler=new XA(this.providerName,this.modelName,this.neurolink),this.generationHandler=new wA(this.providerName,this.modelName,()=>this.supportsTools(),(s,i)=>this.telemetryHandler.getTelemetryConfig(s,i),(s,i,a,c)=>this.handleToolExecutionStorage(s,i,a,c),{getEmitterFn:()=>this.neurolink?.getEventEmitter()}),this.utilities=new eI(this.providerName,this.modelName,this.defaultTimeout,this.middlewareOptions),this.toolsManager=new BB(this.providerName,this.directTools,this.neurolink,{isZodSchema:s=>this.isZodSchema(s),convertToolResult:s=>this.convertToolResult(s),createPermissiveZodSchema:()=>this.createPermissiveZodSchema(),fixSchemaForOpenAIStrictMode:s=>this.fixSchemaForOpenAIStrictMode(s)})}refreshHandlersForModel(e){this.modelName=e,ft.getSpan(hr.active())?.setAttribute(Pe.GEN_AI_MODEL,this.modelName),this.messageBuilder=new $A(this.providerName,this.modelName),this.streamHandler=new qA(this.providerName,this.modelName),this.telemetryHandler=new XA(this.providerName,this.modelName,this.neurolink),this.generationHandler=new wA(this.providerName,this.modelName,()=>this.supportsTools(),(t,n)=>this.telemetryHandler.getTelemetryConfig(t,n),(t,n,o,s)=>this.handleToolExecutionStorage(t,n,o,s),{getEmitterFn:()=>this.neurolink?.getEventEmitter()}),this.utilities=new eI(this.providerName,this.modelName,this.defaultTimeout,this.middlewareOptions)}supportsTools(){return eke("functionCalling",this.providerName,this.modelName)}shouldUseTools(e,t=!1){if(e.disableTools)return!1;let n=this.supportsTools();return!n&&t&&g.warn(`Tools disabled for ${this.providerName}/${this.modelName} because the model does not support function calling`,{provider:this.providerName,model:this.modelName}),n}async stream(e,t){await this.ensureModelLimits();let n=this.normalizeStreamOptions(e);if(g.info("Starting stream",{provider:this.providerName,hasTools:!n.disableTools&&this.supportsTools(),disableTools:!!n.disableTools,supportsTools:this.supportsTools(),inputLength:n.input?.text?.length||0,maxTokens:n.maxTokens,temperature:n.temperature,timestamp:Date.now()}),!!n.input?.files?.length||!!n.input?.videoFiles?.length||!!n.input?.audioFiles?.length){let a=await this.buildMessagesForStream(n);if(e7(a)){g.info("Video frames detected in stream, using fake streaming for video analysis",{provider:this.providerName,model:this.modelName});let c=await this.executeFakeStreaming(n,t);return this.wrapStreamWithLifecycleCallbacks(c,n)}}let s=_l.some(a=>this.modelName.includes(a)),i=n.output?.format==="json"||n.output?.format==="structured"||n.output?.format==="text";if(s&&!i){g.info("Image model detected, forcing fake streaming",{provider:this.providerName,model:this.modelName,reason:"Image generation requires fake streaming to yield image output"});let a=await this.executeFakeStreaming(n,t);return this.wrapStreamWithLifecycleCallbacks(a,n)}if(this.shouldUseTools(n,!0)){let a=await this.getToolsForStream(n);n={...n,tools:a}}else n={...n,tools:{}};try{g.debug("Attempting real streaming",{provider:this.providerName,timestamp:Date.now()});let a=await this.executeStream(n,t);return g.info("Real streaming succeeded",{provider:this.providerName,timestamp:Date.now()}),this.wrapStreamWithLifecycleCallbacks(a,n)}catch(a){let c=a instanceof Error?a.message:String(a);if((a instanceof Error?a.name:"")==="AbortError"||c.includes("abort")||c.includes("timeout")||c.includes("401")||c.includes("403")||c.includes("quota")||c.includes("rate limit")||c.includes("authentication"))throw await this.fireLifecycleErrorCallback(n,a),this.handleProviderError(a);if(g.warn(`Real streaming failed for ${this.providerName}, falling back to fake streaming:`,{error:c,timestamp:Date.now()}),!n.disableTools&&this.supportsTools()){let d=await this.executeFakeStreaming(n,t);return this.wrapStreamWithLifecycleCallbacks(d,n)}else throw await this.fireLifecycleErrorCallback(n,a),g.error(`Real streaming failed for ${this.providerName}:`,a),this.handleProviderError(a)}}wrapStreamWithLifecycleCallbacks(e,t){let n=fDe(t);if(!n?.onChunk&&!n?.onFinish&&!n?.onError)return e;let{onChunk:o,onFinish:s,onError:i}=n,a=Date.now(),c=e.stream,l=Uk(n),d=async(m,f)=>{try{await YT(async()=>{let h=m();h&&typeof h.then=="function"&&await h},l,`[lifecycle] ${f} callback exceeded ${l}ms`)}catch(h){g.warn(`[lifecycle] ${f} callback error:`,h)}},p=(async function*(){let m="",f=0;try{for await(let h of c){let y=h&&typeof h=="object"&&"content"in h&&typeof h.content=="string"?h.content:"";if(o&&y){let v=f++;await d(()=>o({type:"text-delta",textDelta:y,sequenceNumber:v}),"onChunk")}y&&(m+=y),yield h}s&&await d(()=>s({text:m,duration:Date.now()-a}),"onFinish")}catch(h){let y=h instanceof Error?h:new Error(String(h));throw i&&!Iv(y)&&(IS(y),await d(()=>i({error:y,duration:Date.now()-a,recoverable:!1}),"onError")),y}})();return{...e,stream:p}}async fireLifecycleErrorCallback(e,t){let n=t instanceof Error?t:new Error(String(t));if(Iv(n))return;let o=fDe(e),s=o?.onError;if(!s)return;IS(n);let i=Uk(o);try{await YT(async()=>{let a=s({error:n,duration:0,recoverable:!1});a&&typeof a.then=="function"&&await a},i,`[lifecycle] onError callback exceeded ${i}ms`)}catch(a){g.warn("[lifecycle] onError callback error:",a)}}async executeFakeStreaming(e,t){try{g.info("Starting fake streaming with tools",{provider:this.providerName,supportsTools:this.supportsTools(),timestamp:Date.now()});let n={prompt:e.input?.text||"",input:e.input,systemPrompt:e.systemPrompt,temperature:e.temperature,maxTokens:e.maxTokens,tools:e.tools,disableTools:!!e.disableTools,maxSteps:e.maxSteps||5,provider:e.provider,model:e.model,region:e.region,enableAnalytics:e.enableAnalytics,enableEvaluation:e.enableEvaluation,evaluationDomain:e.evaluationDomain,toolUsageContext:e.toolUsageContext,context:e.context,csvOptions:e.csvOptions,pdfOptions:e.pdfOptions,abortSignal:e.abortSignal,toolFilter:e.toolFilter,excludeTools:e.excludeTools,skipToolPromptInjection:e.skipToolPromptInjection,timeout:e.timeout,stt:e.stt,tts:e.tts};g.debug("Calling generate for fake streaming",{provider:this.providerName,maxSteps:n.maxSteps,disableTools:n.disableTools,timestamp:Date.now()});let o=await this.generate(n,t);return g.info("Generate completed for fake streaming",{provider:this.providerName,hasContent:!!o?.content,contentLength:o?.content?.length||0,toolsUsed:o?.toolsUsed?.length||0,hasImageOutput:!!o?.imageOutput,timestamp:Date.now()}),{stream:(async function*(){if(o?.content){let s=o.content.split(/(\s+)/),i="";for(let a=0;a<s.length;a++)i+=s[a],(a===s.length-1||i.length>50||/[.!?;,]\s*$/.test(i))&&i.trim()&&(yield{content:i},i="",await new Promise(l=>{setTimeout(l,Math.random()*9+1)}));i.trim()&&(yield{content:i})}o?.imageOutput&&(yield{type:"image",imageOutput:o.imageOutput}),o?.audio&&(yield{type:"tts_audio",audio:{data:o.audio.buffer,format:o.audio.format,index:0,isFinal:!0,cumulativeSize:o.audio.size,voice:o.audio.voice,sampleRate:o.audio.sampleRate}})})(),usage:o?.usage,provider:o?.provider,model:o?.model,toolCalls:o?.toolCalls?.map(s=>({toolName:s.toolName,parameters:s.args,id:s.toolCallId})),toolResults:o?.toolResults?o.toolResults.map(s=>({toolName:s.toolName||"unknown",status:s.status==="error"?"failure":"success",result:s.output??s.result,error:s.error})):void 0,analytics:o?.analytics,evaluation:o?.evaluation}}catch(n){throw g.error(`Fake streaming fallback failed for ${this.providerName}:`,n),await this.fireLifecycleErrorCallback(e,n),this.handleProviderError(n)}}getToolPolicy(e){return v2({options:{disableTools:e.disableTools,toolFilter:e.toolFilter,excludeTools:e.excludeTools,enabledToolNames:e.enabledToolNames},instanceConfig:this.neurolink?.getToolsConfig(),builtinToolNames:Object.keys(this.directTools??{})})}applyToolFiltering(e,t){let n=this.getToolPolicy(t),o=this.neurolink?.getToolDedupConfig(),s=o!==void 0&&o.enabled===!0,i=Object.keys(e).length,a=b2(e,n),c=Object.keys(a).length;if(i!==c&&g.debug("Tool filtering applied",{provider:this.providerName,beforeCount:i,afterCount:c,policySources:n.sources,toolFilter:t.toolFilter,excludeTools:t.excludeTools,enabledToolNames:t.enabledToolNames}),!s||o===void 0)return this.sortToolRecord(a);let l=this.applyDedupPass(a,o),d=t.toolChoice?.toolName;return typeof d=="string"&&!Object.hasOwn(l,d)&&Object.hasOwn(a,d)&&(l[d]=a[d],g.debug("Restored toolChoice-forced tool removed by signature dedup",{provider:this.providerName,toolName:d})),this.sortToolRecord(l)}sortToolRecord(e){let t=Object.create(null);for(let n of Object.keys(e).sort())t[n]=e[n];return t}async applyToolDiscovery(e,t){let n=e;if(VIe(n.search_tools)){let{search_tools:y,...v}=n;n=v}let o=Object.keys(n).length;if(!this.getToolPolicy(t).discovery)return o>GIe&&this.warnLargeCatalogOnce(o),n;let i=this.neurolink?.getExternalMCPTools()??[];if(i.length===0)return n;let a=t.context?.sessionId,c=typeof a=="string"&&a.length>0?a:typeof a=="number"?String(a):void 0,l=(c?this.neurolink?.getDiscoveryPins(c):void 0)??new Set,d=new Set(Object.keys(t.tools??{})),p=[...t.toolFilter??[],...t.enabledToolNames??[]],m=t.toolChoice;m&&typeof m.toolName=="string"&&p.push(m.toolName);let f=p.length>0?YS(p):null,h=i.map(y=>y.name).filter(y=>y in n&&!d.has(y)&&!(f&&f(y)));return HIe(n,{deferrableNames:h,pinnedNames:l,onHydrate:y=>{c&&this.neurolink?.pinDiscoveredTools(c,y)}})}static warnedLargeCatalog=!1;warnLargeCatalogOnce(e){r.warnedLargeCatalog||(r.warnedLargeCatalog=!0,g.warn(`[ToolDiscovery] ${e} tools are being sent in full on every request (~${Math.round(e*175/100)/10}K tokens). Tool-selection accuracy degrades past 30-50 tools \u2014 consider enabling on-demand discovery: new NeuroLink({ tools: { discovery: true } })`,{toolCount:e,provider:this.providerName}))}applyDedupPass(e,t){let{tools:n,removed:o}=t7(e,t);return o.length>0&&g.shouldLog("debug")&&g.debug("Tool signature dedup removed duplicates",{provider:this.providerName,removedCount:o.length,removed:o.map(s=>({name:s.name,duplicateOf:s.duplicateOf,similarity:s.similarity}))}),n}async prepareGenerationContext(e){let t=this.shouldUseTools(e,!0),n=t?await this.getAllTools():{},o=t?{...n,...e.tools||{}}:{};o=this.applyToolFiltering(o,e),o=this.wrapToolsForExecutionCapture(o,e),o=await this.applyToolDiscovery(o,e),g.debug("Final tools prepared for AI",{provider:this.providerName,directTools:LS(n),directToolNames:d$(n),externalTools:LS(e.tools||{}),externalToolNames:d$(e.tools||{}),totalTools:LS(o),totalToolNames:d$(o),shouldUseTools:t,timestamp:Date.now()});let s=await this.getAISDKModelWithMiddleware(e);return{tools:o,model:s}}async getToolsForStream(e){if(!this.shouldUseTools(e))return{};let n=await this.getAllTools(),o=e.tools||{},s={...n,...o};return s=this.applyToolFiltering(s,e),s=this.wrapToolsForExecutionCapture(s,e),s=await this.applyToolDiscovery(s,e),g.debug("Tools prepared for streaming",{provider:this.providerName,baseToolCount:Object.keys(n).length,externalToolCount:Object.keys(o).length,totalToolCount:Object.keys(s).length}),s}wrapToolsForExecutionCapture(e,t){if(Object.keys(e).length===0)return e;let n=US.from(t);return n||(n=new US(t.toolExecutionCapture),n.attachTo(t)),n.wrapTools(e)}async buildMessages(e){return this.messageBuilder.buildMessages(e)}async buildMessagesForStream(e){return this.messageBuilder.buildMessagesForStream(e)}async executeGeneration(e,t,n,o){return this.generationHandler.executeGeneration(e,t,n,o)}logGenerationComplete(e){this.generationHandler.logGenerationComplete(e)}async recordPerformanceMetrics(e,t){await this.telemetryHandler.recordPerformanceMetrics(e,t)}extractToolInformation(e){return this.generationHandler.extractToolInformation(e)}formatEnhancedResult(e,t,n,o,s){return this.generationHandler.formatEnhancedResult(e,t,n,o,s)}analyzeAIResponse(e){this.generationHandler.analyzeAIResponse(e)}async ensureModelLimits(){}async generate(e,t){await this.ensureModelLimits();let n=this.normalizeTextOptions(e);this.validateOptions(n);let o=Date.now(),s=Oe.provider.startSpan("neurolink.provider.generate",{kind:Tr.CLIENT,attributes:{[Pe.GEN_AI_SYSTEM]:this.providerName||"unknown",[Pe.GEN_AI_MODEL]:this.modelName||n.model||"unknown",[Pe.GEN_AI_OPERATION]:"generate",[Pe.NL_PROVIDER]:this.providerName||"unknown"}}),i=ft.setSpan(hr.active(),s),a={ended:!1};return await hr.with(i,async()=>this.runGenerateInActiveContext(n,o,s,a))}async gen(e,t){return this.generate(e,t)}async runGenerateInActiveContext(e,t,n,o){try{if(e.output?.mode==="video")return await this.handleVideoGeneration(e,t);let s=_l.some(p=>this.modelName.includes(p)),i=e.output?.format==="json"||e.output?.format==="structured"||e.output?.format==="text";if(s&&!i){g.info("Image generation model detected, routing to executeImageGeneration",{provider:this.providerName,model:this.modelName});let p=await this.executeImageGeneration(e);return await this.enhanceResult(p,e,t)}if(e.tts?.enabled&&!e.tts?.useAiResponse)return this.handleDirectTTSSynthesis(e,t);let{tools:a,model:c}=await this.prepareGenerationContext(e),l=await this.buildMessages(e),d=await this.handleVideoFrameGeneration(e,l,c,t);return d||await this.executeStandardGenerateFlow(e,t,c,l,a)}catch(s){throw n.setStatus({code:Ue.ERROR,message:s instanceof Error?s.message:String(s)}),n.end(),o.ended=!0,Ar(s)?g.info(`Generate aborted for ${this.providerName}`,{error:s instanceof Error?s.message:String(s)}):g.error(`Generate failed for ${this.providerName}:`,s),this.handleProviderError(s)}finally{o.ended||(n.setStatus({code:Ue.OK}),n.end())}}async handleDirectTTSSynthesis(e,t){let n=e.prompt??e.input?.text??"",o={content:n,provider:e.provider??this.providerName,model:this.modelName,usage:{input:0,output:0,total:0}},s=e.tts;if(!s)return this.enhanceResult(o,e,t);let i=Date.now(),a=s.provider??e.provider??this.providerName,c=this.getTimeout(e);try{o.audio=await YT(()=>pd.synthesize(n,a,s),c,`TTS synthesis timed out after ${c}ms for provider "${a}"`),o.ttsMetadata={attempted:!0,success:!0,latency:Date.now()-i}}catch(l){let d=Date.now()-i,p=this.getTTSErrorDetails(l);o.ttsMetadata={attempted:!0,success:!1,error:p,latency:d},this.telemetryHandler.recordTTSFailure(a,p,d),g.error("TTS synthesis failed in Mode 1 (direct input synthesis):",l)}return this.enhanceResult(o,e,t)}async handleVideoFrameGeneration(e,t,n,o){if(!e7(t))return null;if(e.schema!==void 0||e.output?.format!==void 0)return g.info("[VideoFrameGen] Skipping video-frame analysis route; caller requested structured output",{provider:this.providerName,model:this.modelName,hasSchema:e.schema!==void 0,outputFormat:e.output?.format}),null;let s=await NIe(t,{provider:e.provider,providerName:this.providerName,region:e.region}),i=t.filter(l=>l.role==="user").flatMap(l=>Array.isArray(l.content)?l.content.filter(d=>d.type==="text").map(d=>d.text):[typeof l.content=="string"?l.content:""]).filter(Boolean).join(`
1044
1044
  `).trim(),a=s,c={input:0,output:0,total:0};if(e.systemPrompt)try{let l=i?`The user asked: "${i}"
1045
1045
 
1046
1046
  Here is the video/image analysis result from the visual analysis system:
@@ -90,7 +90,7 @@ export class BaseProvider {
90
90
  this.messageBuilder = new MessageBuilder(this.providerName, this.modelName);
91
91
  this.streamHandler = new StreamHandler(this.providerName, this.modelName);
92
92
  this.telemetryHandler = new TelemetryHandler(this.providerName, this.modelName, this.neurolink);
93
- this.generationHandler = new GenerationHandler(this.providerName, this.modelName, () => this.supportsTools(), (options, type) => this.telemetryHandler.getTelemetryConfig(options, type), (toolCalls, toolResults, options, timestamp) => this.handleToolExecutionStorage(toolCalls, toolResults, options, timestamp), () => this.neurolink?.getEventEmitter());
93
+ this.generationHandler = new GenerationHandler(this.providerName, this.modelName, () => this.supportsTools(), (options, type) => this.telemetryHandler.getTelemetryConfig(options, type), (toolCalls, toolResults, options, timestamp) => this.handleToolExecutionStorage(toolCalls, toolResults, options, timestamp), { getEmitterFn: () => this.neurolink?.getEventEmitter() });
94
94
  this.utilities = new Utilities(this.providerName, this.modelName, this.defaultTimeout, this.middlewareOptions);
95
95
  this.toolsManager = new ToolsManager(this.providerName, this.directTools, this.neurolink, {
96
96
  isZodSchema: (schema) => this.isZodSchema(schema),
@@ -115,7 +115,7 @@ export class BaseProvider {
115
115
  this.messageBuilder = new MessageBuilder(this.providerName, this.modelName);
116
116
  this.streamHandler = new StreamHandler(this.providerName, this.modelName);
117
117
  this.telemetryHandler = new TelemetryHandler(this.providerName, this.modelName, this.neurolink);
118
- this.generationHandler = new GenerationHandler(this.providerName, this.modelName, () => this.supportsTools(), (options, type) => this.telemetryHandler.getTelemetryConfig(options, type), (toolCalls, toolResults, options, timestamp) => this.handleToolExecutionStorage(toolCalls, toolResults, options, timestamp), () => this.neurolink?.getEventEmitter());
118
+ this.generationHandler = new GenerationHandler(this.providerName, this.modelName, () => this.supportsTools(), (options, type) => this.telemetryHandler.getTelemetryConfig(options, type), (toolCalls, toolResults, options, timestamp) => this.handleToolExecutionStorage(toolCalls, toolResults, options, timestamp), { getEmitterFn: () => this.neurolink?.getEventEmitter() });
119
119
  this.utilities = new Utilities(this.providerName, this.modelName, this.defaultTimeout, this.middlewareOptions);
120
120
  }
121
121
  /**
@@ -48,12 +48,44 @@ export declare class GenerationHandler {
48
48
  private readonly supportsToolsFn;
49
49
  private readonly getTelemetryConfigFn;
50
50
  private readonly handleToolStorageFn;
51
- private readonly getEmitterFn?;
51
+ /**
52
+ * The remaining, optional dependencies.
53
+ *
54
+ * Grouped rather than added as further positional parameters: the
55
+ * constructor is already at the six-parameter cap, and both of these are
56
+ * optional injection seams rather than required collaborators.
57
+ *
58
+ * `generateTextFn` exists because every other dependency of this class
59
+ * arrives through the constructor while `generateText` was reached by
60
+ * static import. `utils/generation.ts` is a bare re-export of `ai`, and an
61
+ * ESM re-export cannot be substituted from a test, so asserting on the
62
+ * arguments this class builds — the entire contract of the system-message
63
+ * hoisting below — had no seam to work through. Production passes neither.
64
+ */
65
+ private readonly deps;
52
66
  constructor(providerName: AIProviderName, modelName: string, supportsToolsFn: () => boolean, getTelemetryConfigFn: (options: TextGenerationOptions, type: string) => {
53
67
  isEnabled: boolean;
54
68
  functionId?: string;
55
69
  metadata?: Record<string, string | number | boolean>;
56
- } | undefined, handleToolStorageFn: (toolCalls: unknown[], toolResults: unknown[], options: TextGenerationOptions, timestamp: Date) => Promise<void>, getEmitterFn?: (() => TypedEventEmitter<NeuroLinkEvents> | undefined) | undefined);
70
+ } | undefined, handleToolStorageFn: (toolCalls: unknown[], toolResults: unknown[], options: TextGenerationOptions, timestamp: Date) => Promise<void>,
71
+ /**
72
+ * The remaining, optional dependencies.
73
+ *
74
+ * Grouped rather than added as further positional parameters: the
75
+ * constructor is already at the six-parameter cap, and both of these are
76
+ * optional injection seams rather than required collaborators.
77
+ *
78
+ * `generateTextFn` exists because every other dependency of this class
79
+ * arrives through the constructor while `generateText` was reached by
80
+ * static import. `utils/generation.ts` is a bare re-export of `ai`, and an
81
+ * ESM re-export cannot be substituted from a test, so asserting on the
82
+ * arguments this class builds — the entire contract of the system-message
83
+ * hoisting below — had no seam to work through. Production passes neither.
84
+ */
85
+ deps?: {
86
+ getEmitterFn?: () => TypedEventEmitter<NeuroLinkEvents> | undefined;
87
+ generateTextFn?: typeof generateText;
88
+ });
57
89
  /**
58
90
  * Helper method to call generateText with optional structured output
59
91
  * @private
@@ -159,14 +159,29 @@ export class GenerationHandler {
159
159
  supportsToolsFn;
160
160
  getTelemetryConfigFn;
161
161
  handleToolStorageFn;
162
- getEmitterFn;
163
- constructor(providerName, modelName, supportsToolsFn, getTelemetryConfigFn, handleToolStorageFn, getEmitterFn) {
162
+ deps;
163
+ constructor(providerName, modelName, supportsToolsFn, getTelemetryConfigFn, handleToolStorageFn,
164
+ /**
165
+ * The remaining, optional dependencies.
166
+ *
167
+ * Grouped rather than added as further positional parameters: the
168
+ * constructor is already at the six-parameter cap, and both of these are
169
+ * optional injection seams rather than required collaborators.
170
+ *
171
+ * `generateTextFn` exists because every other dependency of this class
172
+ * arrives through the constructor while `generateText` was reached by
173
+ * static import. `utils/generation.ts` is a bare re-export of `ai`, and an
174
+ * ESM re-export cannot be substituted from a test, so asserting on the
175
+ * arguments this class builds — the entire contract of the system-message
176
+ * hoisting below — had no seam to work through. Production passes neither.
177
+ */
178
+ deps = {}) {
164
179
  this.providerName = providerName;
165
180
  this.modelName = modelName;
166
181
  this.supportsToolsFn = supportsToolsFn;
167
182
  this.getTelemetryConfigFn = getTelemetryConfigFn;
168
183
  this.handleToolStorageFn = handleToolStorageFn;
169
- this.getEmitterFn = getEmitterFn;
184
+ this.deps = deps;
170
185
  }
171
186
  /**
172
187
  * Helper method to call generateText with optional structured output
@@ -265,7 +280,7 @@ export class GenerationHandler {
265
280
  const samplingParams = resolveSamplingParams(this.providerName, getModelId(model, this.modelName || ""), options.temperature !== undefined
266
281
  ? { temperature: options.temperature }
267
282
  : {}, "aiSdk.generateText");
268
- const result = await generateText({
283
+ const result = await (this.deps.generateTextFn ?? generateText)({
269
284
  model,
270
285
  ...(system && { system }),
271
286
  messages: nonSystemMessages,
@@ -364,7 +379,7 @@ export class GenerationHandler {
364
379
  // This surfaces AI-SDK-driven tool completions as telemetry events
365
380
  // so that tool spans are created even when the SDK runs tools
366
381
  // internally (gaps G5 / S2).
367
- emitToolEndFromStepFinish(this.getEmitterFn?.(), toolResults);
382
+ emitToolEndFromStepFinish(this.deps.getEmitterFn?.(), toolResults);
368
383
  // Handle tool execution storage
369
384
  this.handleToolStorageFn(toolCalls, toolResults, options, new Date()).catch((error) => {
370
385
  logger.warn("[GenerationHandler] Failed to store tool executions", {
@@ -90,7 +90,7 @@ export class BaseProvider {
90
90
  this.messageBuilder = new MessageBuilder(this.providerName, this.modelName);
91
91
  this.streamHandler = new StreamHandler(this.providerName, this.modelName);
92
92
  this.telemetryHandler = new TelemetryHandler(this.providerName, this.modelName, this.neurolink);
93
- this.generationHandler = new GenerationHandler(this.providerName, this.modelName, () => this.supportsTools(), (options, type) => this.telemetryHandler.getTelemetryConfig(options, type), (toolCalls, toolResults, options, timestamp) => this.handleToolExecutionStorage(toolCalls, toolResults, options, timestamp), () => this.neurolink?.getEventEmitter());
93
+ this.generationHandler = new GenerationHandler(this.providerName, this.modelName, () => this.supportsTools(), (options, type) => this.telemetryHandler.getTelemetryConfig(options, type), (toolCalls, toolResults, options, timestamp) => this.handleToolExecutionStorage(toolCalls, toolResults, options, timestamp), { getEmitterFn: () => this.neurolink?.getEventEmitter() });
94
94
  this.utilities = new Utilities(this.providerName, this.modelName, this.defaultTimeout, this.middlewareOptions);
95
95
  this.toolsManager = new ToolsManager(this.providerName, this.directTools, this.neurolink, {
96
96
  isZodSchema: (schema) => this.isZodSchema(schema),
@@ -115,7 +115,7 @@ export class BaseProvider {
115
115
  this.messageBuilder = new MessageBuilder(this.providerName, this.modelName);
116
116
  this.streamHandler = new StreamHandler(this.providerName, this.modelName);
117
117
  this.telemetryHandler = new TelemetryHandler(this.providerName, this.modelName, this.neurolink);
118
- this.generationHandler = new GenerationHandler(this.providerName, this.modelName, () => this.supportsTools(), (options, type) => this.telemetryHandler.getTelemetryConfig(options, type), (toolCalls, toolResults, options, timestamp) => this.handleToolExecutionStorage(toolCalls, toolResults, options, timestamp), () => this.neurolink?.getEventEmitter());
118
+ this.generationHandler = new GenerationHandler(this.providerName, this.modelName, () => this.supportsTools(), (options, type) => this.telemetryHandler.getTelemetryConfig(options, type), (toolCalls, toolResults, options, timestamp) => this.handleToolExecutionStorage(toolCalls, toolResults, options, timestamp), { getEmitterFn: () => this.neurolink?.getEventEmitter() });
119
119
  this.utilities = new Utilities(this.providerName, this.modelName, this.defaultTimeout, this.middlewareOptions);
120
120
  }
121
121
  /**
@@ -48,12 +48,44 @@ export declare class GenerationHandler {
48
48
  private readonly supportsToolsFn;
49
49
  private readonly getTelemetryConfigFn;
50
50
  private readonly handleToolStorageFn;
51
- private readonly getEmitterFn?;
51
+ /**
52
+ * The remaining, optional dependencies.
53
+ *
54
+ * Grouped rather than added as further positional parameters: the
55
+ * constructor is already at the six-parameter cap, and both of these are
56
+ * optional injection seams rather than required collaborators.
57
+ *
58
+ * `generateTextFn` exists because every other dependency of this class
59
+ * arrives through the constructor while `generateText` was reached by
60
+ * static import. `utils/generation.ts` is a bare re-export of `ai`, and an
61
+ * ESM re-export cannot be substituted from a test, so asserting on the
62
+ * arguments this class builds — the entire contract of the system-message
63
+ * hoisting below — had no seam to work through. Production passes neither.
64
+ */
65
+ private readonly deps;
52
66
  constructor(providerName: AIProviderName, modelName: string, supportsToolsFn: () => boolean, getTelemetryConfigFn: (options: TextGenerationOptions, type: string) => {
53
67
  isEnabled: boolean;
54
68
  functionId?: string;
55
69
  metadata?: Record<string, string | number | boolean>;
56
- } | undefined, handleToolStorageFn: (toolCalls: unknown[], toolResults: unknown[], options: TextGenerationOptions, timestamp: Date) => Promise<void>, getEmitterFn?: (() => TypedEventEmitter<NeuroLinkEvents> | undefined) | undefined);
70
+ } | undefined, handleToolStorageFn: (toolCalls: unknown[], toolResults: unknown[], options: TextGenerationOptions, timestamp: Date) => Promise<void>,
71
+ /**
72
+ * The remaining, optional dependencies.
73
+ *
74
+ * Grouped rather than added as further positional parameters: the
75
+ * constructor is already at the six-parameter cap, and both of these are
76
+ * optional injection seams rather than required collaborators.
77
+ *
78
+ * `generateTextFn` exists because every other dependency of this class
79
+ * arrives through the constructor while `generateText` was reached by
80
+ * static import. `utils/generation.ts` is a bare re-export of `ai`, and an
81
+ * ESM re-export cannot be substituted from a test, so asserting on the
82
+ * arguments this class builds — the entire contract of the system-message
83
+ * hoisting below — had no seam to work through. Production passes neither.
84
+ */
85
+ deps?: {
86
+ getEmitterFn?: () => TypedEventEmitter<NeuroLinkEvents> | undefined;
87
+ generateTextFn?: typeof generateText;
88
+ });
57
89
  /**
58
90
  * Helper method to call generateText with optional structured output
59
91
  * @private
@@ -159,14 +159,29 @@ export class GenerationHandler {
159
159
  supportsToolsFn;
160
160
  getTelemetryConfigFn;
161
161
  handleToolStorageFn;
162
- getEmitterFn;
163
- constructor(providerName, modelName, supportsToolsFn, getTelemetryConfigFn, handleToolStorageFn, getEmitterFn) {
162
+ deps;
163
+ constructor(providerName, modelName, supportsToolsFn, getTelemetryConfigFn, handleToolStorageFn,
164
+ /**
165
+ * The remaining, optional dependencies.
166
+ *
167
+ * Grouped rather than added as further positional parameters: the
168
+ * constructor is already at the six-parameter cap, and both of these are
169
+ * optional injection seams rather than required collaborators.
170
+ *
171
+ * `generateTextFn` exists because every other dependency of this class
172
+ * arrives through the constructor while `generateText` was reached by
173
+ * static import. `utils/generation.ts` is a bare re-export of `ai`, and an
174
+ * ESM re-export cannot be substituted from a test, so asserting on the
175
+ * arguments this class builds — the entire contract of the system-message
176
+ * hoisting below — had no seam to work through. Production passes neither.
177
+ */
178
+ deps = {}) {
164
179
  this.providerName = providerName;
165
180
  this.modelName = modelName;
166
181
  this.supportsToolsFn = supportsToolsFn;
167
182
  this.getTelemetryConfigFn = getTelemetryConfigFn;
168
183
  this.handleToolStorageFn = handleToolStorageFn;
169
- this.getEmitterFn = getEmitterFn;
184
+ this.deps = deps;
170
185
  }
171
186
  /**
172
187
  * Helper method to call generateText with optional structured output
@@ -265,7 +280,7 @@ export class GenerationHandler {
265
280
  const samplingParams = resolveSamplingParams(this.providerName, getModelId(model, this.modelName || ""), options.temperature !== undefined
266
281
  ? { temperature: options.temperature }
267
282
  : {}, "aiSdk.generateText");
268
- const result = await generateText({
283
+ const result = await (this.deps.generateTextFn ?? generateText)({
269
284
  model,
270
285
  ...(system && { system }),
271
286
  messages: nonSystemMessages,
@@ -364,7 +379,7 @@ export class GenerationHandler {
364
379
  // This surfaces AI-SDK-driven tool completions as telemetry events
365
380
  // so that tool spans are created even when the SDK runs tools
366
381
  // internally (gaps G5 / S2).
367
- emitToolEndFromStepFinish(this.getEmitterFn?.(), toolResults);
382
+ emitToolEndFromStepFinish(this.deps.getEmitterFn?.(), toolResults);
368
383
  // Handle tool execution storage
369
384
  this.handleToolStorageFn(toolCalls, toolResults, options, new Date()).catch((error) => {
370
385
  logger.warn("[GenerationHandler] Failed to store tool executions", {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@juspay/neurolink",
3
- "version": "10.8.15",
3
+ "version": "10.8.17",
4
4
  "packageManager": "pnpm@10.15.1",
5
5
  "description": "TypeScript AI SDK with 24+ LLM providers behind one consistent API. MCP-native (connect any MCP server), voice TTS/STT/realtime, RAG, agents, memory, context compaction. OpenAI · Anthropic · Gemini · Bedrock · Azure · Ollama · DeepSeek · NVIDIA NIM and more.",
6
6
  "author": {
@@ -138,24 +138,20 @@
138
138
  "test:anthropic-multimodal": "npx tsx test/continuous-test-suite-anthropic-multimodal.ts",
139
139
  "test:excel-interop": "npx tsx test/continuous-test-suite-excel-interop.ts",
140
140
  "test:envguard": "npx tsx test/helpers/envGuard.test.ts",
141
- "test:tool-routing-cli:vitest": "pnpm exec vitest run test/toolRoutingCli.test.ts",
142
- "test:tool-routing-cli": "pnpm run test:tool-routing-cli:vitest && npx tsx test/continuous-test-suite-tool-routing-cli.ts",
143
- "test:tool-dedup:vitest": "pnpm exec vitest run test/toolDedup.test.ts",
144
- "test:tool-dedup": "pnpm run test:tool-dedup:vitest && npx tsx test/continuous-test-suite-tool-dedup.ts",
145
- "test:model-pool:vitest": "pnpm exec vitest run test/modelPool.test.ts",
146
- "test:model-pool": "pnpm run test:model-pool:vitest && npx tsx test/continuous-test-suite-model-pool.ts",
141
+ "test:tool-routing-cli": "npx tsx test/continuous-test-suite-tool-routing-flags.ts && npx tsx test/continuous-test-suite-tool-routing-cli.ts",
142
+ "test:tool-dedup": "npx tsx test/continuous-test-suite-tool-dedup.ts",
143
+ "test:model-pool": "npx tsx test/continuous-test-suite-model-pool.ts",
147
144
  "test:model-capabilities": "npx tsx test/continuous-test-suite-model-capabilities.ts",
148
145
  "test:agent-runtime:vitest": "pnpm exec vitest run test/agentRuntime.test.ts test/agentDelegation.test.ts test/agentPlumbing.test.ts test/toolExecutionRecorder.test.ts",
149
146
  "test:retry-after:vitest": "pnpm exec vitest run test/retryAfter.test.ts",
150
147
  "test:ci": "pnpm run test && pnpm run test:client && pnpm run test:hitl",
151
148
  "// CI tier — fast, no live AI calls, safe for every commit": "",
152
- "test:unit:vitest": "pnpm exec vitest run test/toolRouting.test.ts",
153
- "test:tool-routing": "pnpm run test:unit:vitest && npx tsx test/continuous-test-suite-tool-routing.ts",
149
+ "test:tool-routing": "npx tsx test/continuous-test-suite-tool-routing.ts",
154
150
  "test:classifier-router": "npx tsx test/continuous-test-suite-classifier-router.ts",
155
- "test:system-messages:vitest": "pnpm exec vitest run test/systemMessages.test.ts",
156
- "test:tool-routing-semantic:vitest": "pnpm exec vitest run test/toolRoutingSemantic.test.ts",
157
- "test:tool-routing-semantic": "pnpm run test:tool-routing-semantic:vitest && npx tsx test/continuous-test-suite-tool-routing-semantic.ts",
158
- "test:unit": "pnpm run test:envguard && pnpm run test:bugfixes && pnpm run test:file-detector-extension && pnpm run test:file-detector-magic-bytes && pnpm run test:mcp:infra && pnpm run test:mcp:bash && pnpm run test:mcp:limits && pnpm run test:mcp:spans && pnpm run test:autoresearch:redis && pnpm run test:unit:vitest && pnpm run test:tool-routing-cli:vitest && pnpm run test:tool-dedup:vitest && pnpm run test:model-pool:vitest && pnpm run test:litellm-context:vitest && pnpm run test:step-budget-guard:vitest && pnpm run test:system-messages:vitest && pnpm run test:tool-routing-semantic:vitest && pnpm run test:anthropic-tools-policy && pnpm run test:sagemaker-tools && pnpm run test:anthropic-multimodal && pnpm run test:excel-interop && pnpm run test:model-capabilities && pnpm run test:agent-runtime:vitest && pnpm run test:retry-after:vitest && pnpm run test:sampling-params && pnpm run test:structured-recovery && pnpm run test:prompt-redaction && pnpm run test:mcp-result-cache",
151
+ "test:system-messages": "npx tsx test/continuous-test-suite-system-messages.ts",
152
+ "test:test-stubs": "npx tsx test/continuous-test-suite-test-stubs.ts",
153
+ "test:tool-routing-semantic": "npx tsx test/continuous-test-suite-tool-routing-semantic.ts",
154
+ "test:unit": "pnpm run test:envguard && pnpm run test:bugfixes && pnpm run test:file-detector-extension && pnpm run test:file-detector-magic-bytes && pnpm run test:mcp:infra && pnpm run test:mcp:bash && pnpm run test:mcp:limits && pnpm run test:mcp:spans && pnpm run test:autoresearch:redis && pnpm run test:tool-routing && pnpm run test:tool-routing-cli && pnpm run test:tool-dedup && pnpm run test:model-pool && pnpm run test:litellm-context && pnpm run test:dedup-execute-map && pnpm run test:step-budget-guard:vitest && pnpm run test:system-messages && pnpm run test:tool-routing-semantic && pnpm run test:anthropic-tools-policy && pnpm run test:sagemaker-tools && pnpm run test:anthropic-multimodal && pnpm run test:excel-interop && pnpm run test:model-capabilities && pnpm run test:agent-runtime:vitest && pnpm run test:retry-after:vitest && pnpm run test:sampling-params && pnpm run test:structured-recovery && pnpm run test:prompt-redaction && pnpm run test:mcp-result-cache && pnpm run test:test-stubs",
159
155
  "// CI tier — live providers, runs only when API keys are present (test:credentials and test:dynamic make real provider calls when keys are set, so they live here, not in test:unit)": "",
160
156
  "test:live": "pnpm run test:providers && pnpm run test:mcp:http && pnpm run test:mcp:sdk && pnpm run test:mcp:cli && pnpm run test:observability && pnpm run test:context && pnpm run test:memory && pnpm run test:tool-reliability && pnpm run test:evaluation && pnpm run test:autoresearch && pnpm run test:credentials && pnpm run test:dynamic",
161
157
  "// CI tier — product output (image/video/TTS/PPT) — costs $$ per run": "",
@@ -217,7 +213,8 @@
217
213
  "pre-commit": "lint-staged",
218
214
  "pre-push": "pnpm run validate:commit && pnpm run validate:env && pnpm run validate && pnpm run test:ci",
219
215
  "check:all": "pnpm run lint && pnpm run format --check && pnpm run validate && pnpm run validate:commit",
220
- "test:litellm-context:vitest": "pnpm exec vitest run test/litellmContextWindows.test.ts",
216
+ "test:litellm-context": "npx tsx test/continuous-test-suite-litellm-context-windows.ts",
217
+ "test:dedup-execute-map": "npx tsx test/continuous-test-suite-dedup-execute-map.ts",
221
218
  "test:step-budget-guard:vitest": "pnpm exec vitest run test/stepBudgetGuard.test.ts",
222
219
  "test:audio": "npx tsx test/continuous-test-suite-audio.ts",
223
220
  "test:office": "npx tsx test/continuous-test-suite-office.ts",