@juspay/neurolink 9.92.0 → 9.92.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,3 +1,9 @@
1
+ ## [9.92.1](https://github.com/juspay/neurolink/compare/v9.92.0...v9.92.1) (2026-07-17)
2
+
3
+ ### Bug Fixes
4
+
5
+ - **(tools):** null-prototype prompt-listing record + forward disableTools to gate ([c2a2718](https://github.com/juspay/neurolink/commit/c2a27187098cb12a4804a82621771fcc3d51b07f))
6
+
1
7
  ## [9.92.0](https://github.com/juspay/neurolink/compare/v9.91.1...v9.92.0) (2026-07-17)
2
8
 
3
9
  ### Features
@@ -1144,7 +1144,7 @@ Reasoning: [Provide a detailed explanation of your evaluation, explaining why yo
1144
1144
  [... ${Math.max(0,c-Buffer.byteLength(h,"utf-8")-Buffer.byteLength(y,"utf-8"))} bytes omitted. Use ${Bor} tool to access full output ...]
1145
1145
 
1146
1146
  `;return{preview:h+S+y,truncated:!0,originalSize:c}}var Bor,y4=k(()=>{"use strict";Bor="retrieve_context"});function o$e(){let r=new Error("Tool execution aborted");return r.name="AbortError",r}function zor(r,e){return e.aborted?(r.catch(()=>{}),Promise.reject(o$e())):new Promise((t,n)=>{let o=()=>{r.catch(()=>{}),n(o$e())};e.addEventListener("abort",o,{once:!0}),r.then(s=>{e.removeEventListener("abort",o),t(s)},s=>{e.removeEventListener("abort",o),n(s)})})}var x4,s$e=k(()=>{"use strict";Jn();mj();Sl();Dr();H();dy();Su();y4();VI();x4=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 zor(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}=bg(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}=bg(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}=bg(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}=bg(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,Jf(t,n))}setupToolExecutor(e,t){let n=ke.sdk.startSpan("neurolink.tools.register",{attributes:{[we.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:Pe.OK})}catch(o){throw n.setStatus({code:Pe.ERROR,message:o instanceof Error?o.message:String(o)}),o instanceof Error&&n.recordException(o),o}finally{n.end()}}async getAllTools(){return Ke({name:"neurolink.tools.getAll",tracer:ke.sdk,attributes:{[we.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:kE(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(we.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 u=l instanceof Error?l.message:String(l);throw this.emitToolEvent("tool:end",t,{error:u,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=mu(o)):t.parameters&&typeof t.parameters=="object"?n=iMe(t.parameters):n=m.object({}),{description:t.description||`Tool ${e}`,inputSchema:n,execute:async s=>{let i=ke.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,x=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(x):x,T=Date.now();i.setAttribute("tool.duration_ms",T-a);let S;if(b&&typeof b=="object"&&"isError"in b&&b.isError)try{S=JSON.stringify(b)}catch(_){g.error(`Failed to serialize error result for ${e}`,_)}return i.setAttribute("tool.result.status",S?"error":"success"),S?i.setStatus({code:Pe.ERROR,message:`Tool ${e} returned isError: true`}):i.setStatus({code:Pe.OK}),b}this.neurolink?.emitToolStart&&(c=this.neurolink.emitToolStart(e,s,a));let l=await t.execute(s),u=this.utilities?.convertToolResult?await this.utilities.convertToolResult(l):l,d=Date.now(),p;if(u&&typeof u=="object"&&"isError"in u&&u.isError)try{p=JSON.stringify(u)}catch(f){g.error(`Failed to serialize error result for ${e}`,f)}return this.neurolink?.emitToolEnd&&this.neurolink.emitToolEnd(e,u,p,a,d,c),i.setAttribute("tool.duration_ms",d-a),i.setAttribute("tool.result.status",p?"error":"success"),p?i.setStatus({code:Pe.ERROR,message:`Tool ${e} returned isError: true`}):i.setStatus({code:Pe.OK}),u}catch(l){let u=Date.now(),d=l instanceof Error?l.message:String(l);throw!this.toolExecutor&&this.neurolink?.emitToolEnd&&(this.neurolink.emitToolEnd(e,void 0,d,a,u,c),g.debug(`Custom tool error: ${e} (${u-a}ms)`,{error:d})),i.setAttribute("tool.duration_ms",u-a),i.setAttribute("tool.result.status","error"),i.recordException(l instanceof Error?l:new Error(d)),i.setStatus({code:Pe.ERROR,message:d}),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;t=mu(i)}else t=this.utilities?.createPermissiveZodSchema?this.utilities.createPermissiveZodSchema():m.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 i$e(r){return typeof r=="string"&&r.length>0}function a$e(r){return i$e(r)?/^gemini-2\.5(-.*)?$/i.test(r):!1}function RO(r){return i$e(r)?!!(/^gemini-3/i.test(r)||jor.some(e=>e.test(r))):!1}function fse(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 jor,Yc,v4=k(()=>{"use strict";xa();jor=hu.map(r=>new RegExp(`^${r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}`,"i"));Yc=32768});function AO(r,e,t){if(e?RO(e):!1)return t!=null&&t>Yc?(g.warn(`Requested maxTokens ${t} exceeds ${e} limit of ${Yc}. Using ${Yc} instead.`),Yc):t??Yc;let o=P2[r];if(!o)return g.warn(`Unknown provider ${r}, no token limits enforced`),t??void 0;let s;return e&&typeof o=="object"&&o[e]?s=o[e]:typeof o=="object"&&o.default?s=o.default:typeof o=="number"?s=o:s=P2.default,t==null?s:t>s?(g.warn(`Requested maxTokens ${t} exceeds ${r}/${e} limit of ${s}. Using ${s} instead.`),s):t}function Gor(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 i0(r,e){let t=Gor(r);return e!=null&&e>0?Math.min(e,t):t}var b4=k(()=>{"use strict";xa();H();v4()});var IO,c$e=k(()=>{"use strict";Jn();H();b4();no();Yy();xa();IO=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=ose(e);if(!t.isValid){let n=Jy(t);throw new Qt(`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<Hs.min||e.maxSteps>Hs.max))throw new Qt(`maxSteps must be between ${Hs.min} and ${Hs.max}`,"maxSteps","OUT_OF_RANGE",[`Use a value between ${Hs.min} and ${Hs.max} for optimal performance`])}validateStreamOptions(e){let t=hO(e);if(!t.isValid){let n=Jy(t);throw new Qt(`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<Hs.min||e.maxSteps>Hs.max))throw new Qt(`maxSteps must be between ${Hs.min} and ${Hs.max}`,"maxSteps","OUT_OF_RANGE",[`Use a value between ${Hs.min} and ${Hs.max} for optimal performance`])}normalizeTextOptions(e){if(typeof e=="string"){let a=AO(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=AO(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=AO(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=AO(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=wl(e.timeout);if(n!==void 0)return n}return wl(UPe(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 m.record(m.string(),m.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 tr)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 u$e={};Q(u$e,{createToolCallRepair:()=>Vor});function Vor(){return async({toolCall:r,tools:e,inputSchema:t,error:n})=>{let{NoSuchToolError:o,InvalidToolInputError:s}=await Promise.resolve().then(()=>(Em(),nNe));if(o.isInstance(n))return qor(r,Object.keys(e));if(s.isInstance(n))try{let i=await t({toolName:r.toolName});return Hor(r,i)}catch{return null}return null}}function qor(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=l$e(o,c.toLowerCase()),u=Math.max(t.length,c.length),d=u===0?0:l/u;d<.3&&d<a&&(a=d,i=c)}return i?(g.debug(`[ToolCallRepair] Name repair (levenshtein ${a.toFixed(2)}): "${t}" \u2192 "${i}"`),{...r,toolName:i}):(g.debug(`[ToolCallRepair] Could not repair tool name "${t}". Available: [${e.join(", ")}]`),null)}function Hor(r,e){let t;try{t=JSON.parse(r.input)}catch{return null}if(!t||typeof t!="object"||Array.isArray(t))return null;let n=e.properties;if(!n)return null;let o=Object.keys(n),s=t,i=Object.keys(s),a=Object.create(null),c=!1,l=e.additionalProperties===!1;for(let u of i){if(o.includes(u)){a[u]=s[u];continue}let d=Wor(u,o);if(d){if(Object.prototype.hasOwnProperty.call(a,d)){c=!0;continue}g.debug(`[ToolCallRepair] Param repair: "${u}" \u2192 "${d}" (tool: ${r.toolName})`),a[d]=s[u],c=!0}else l?(g.debug(`[ToolCallRepair] Dropping unmapped key "${u}" (additionalProperties: false, tool: ${r.toolName})`),c=!0):a[u]=s[u]}for(let u of Object.keys(a)){let d=n[u];if(!d)continue;let p=Kor(a[u],d);p!==a[u]&&(g.debug(`[ToolCallRepair] Type coercion on "${u}": ${typeof a[u]} \u2192 ${typeof p} (tool: ${r.toolName})`),a[u]=p,c=!0)}return c?{...r,input:JSON.stringify(a)}:null}function Wor(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=l$e(t,i.toLowerCase());a<=2&&a<s&&(s=a,o=i)}return o}function Kor(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 l$e(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 d$e=k(()=>{"use strict";H()});var T4={};Q(T4,{Agent:()=>Dsr,BedrockClient:()=>Yor,BedrockRuntimeClient:()=>Zor,Blob:()=>Nsr,Client:()=>Usr,ConverseCommand:()=>Qor,ConverseStreamCommand:()=>esr,Cron:()=>hsr,Dispatcher:()=>Fsr,File:()=>Osr,FlowProducer:()=>gsr,FormData:()=>Msr,GoogleAuth:()=>gse,HTTPException:()=>wsr,Headers:()=>Psr,Hippocampus:()=>csr,HippocampusConfig:()=>lsr,Hono:()=>Tsr,ImageFormat:()=>tsr,InvokeEndpointCommand:()=>nsr,InvokeEndpointWithResponseStreamCommand:()=>osr,Job:()=>msr,ListFoundationModelsCommand:()=>Xor,MockAgent:()=>zsr,Pool:()=>Lsr,Queue:()=>dsr,QueueScheduler:()=>fsr,Request:()=>Asr,Response:()=>Isr,SageMakerRuntimeClient:()=>rsr,TextToSpeechClient:()=>isr,VertexAI:()=>ssr,Webhook:()=>asr,Worker:()=>psr,convertToHtml:()=>bsr,cors:()=>Ssr,createClient:()=>usr,default:()=>Jor,extractRawText:()=>vsr,fetch:()=>Rsr,getGlobalDispatcher:()=>Bsr,interceptors:()=>jsr,logger:()=>Esr,parseBuffer:()=>ysr,request:()=>Gsr,secureHeaders:()=>_sr,selectCover:()=>xsr,setGlobalDispatcher:()=>$sr,streamSSE:()=>ksr,timeout:()=>Csr});var a0,Fi,Jor,Yor,Xor,Zor,Qor,esr,tsr,rsr,nsr,osr,gse,ssr,isr,asr,csr,lsr,usr,dsr,psr,msr,fsr,gsr,hsr,ysr,xsr,vsr,bsr,Tsr,Ssr,wsr,Esr,_sr,ksr,Csr,Rsr,Asr,Isr,Psr,Msr,Osr,Nsr,Dsr,Lsr,Usr,Fsr,$sr,Bsr,zsr,jsr,Gsr,PO=k(()=>{a0={get(r,e){return e==="__esModule"?!0:e==="default"?new Proxy({},{get:a0.get}):new Proxy(function(...t){return new Proxy({},{get:a0.get})},{get:a0.get,apply(t,n,o){return new Proxy({},{get:a0.get})},construct(t,n){return new Proxy({},{get:a0.get})}})}},Fi=new Proxy({},a0),Jor=Fi,{BedrockClient:Yor,ListFoundationModelsCommand:Xor,BedrockRuntimeClient:Zor,ConverseCommand:Qor,ConverseStreamCommand:esr,ImageFormat:tsr}=Fi,{SageMakerRuntimeClient:rsr,InvokeEndpointCommand:nsr,InvokeEndpointWithResponseStreamCommand:osr}=Fi,{GoogleAuth:gse,VertexAI:ssr,TextToSpeechClient:isr}=Fi,{Webhook:asr}=Fi,{Hippocampus:csr,HippocampusConfig:lsr}=Fi,{createClient:usr}=Fi,{Queue:dsr,Worker:psr,Job:msr,QueueScheduler:fsr,FlowProducer:gsr}=Fi,{Cron:hsr}=Fi,{parseBuffer:ysr,selectCover:xsr}=Fi,{extractRawText:vsr,convertToHtml:bsr}=Fi,{Hono:Tsr}=Fi,{cors:Ssr,HTTPException:wsr,logger:Esr,secureHeaders:_sr,streamSSE:ksr,timeout:Csr}=Fi,Rsr=globalThis.fetch,Asr=globalThis.Request,Isr=globalThis.Response,Psr=globalThis.Headers,Msr=globalThis.FormData,Osr=globalThis.File,Nsr=globalThis.Blob,Dsr=Fi.Agent,Lsr=Fi.Pool,Usr=Fi.Client,Fsr=Fi.Dispatcher,$sr=()=>{},Bsr=()=>Fi,zsr=Fi.MockAgent,jsr={redirect:()=>r=>r,retry:()=>r=>r},Gsr=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 h$e={};Q(h$e,{VIDEO_ERROR_CODES:()=>st,VertexVideoHandler:()=>w4,VideoError:()=>it,generateTransitionWithVertex:()=>_4,generateVideoWithVertex:()=>E4,isVertexVideoConfigured:()=>xse});function xse(){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 m$e(){let r=process.env.GOOGLE_VEO_LOCATION||process.env.GOOGLE_VERTEX_VIDEO_LOCATION||qsr,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 bo(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 it({code:st.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 f$e(){try{let r=await Promise.resolve().then(()=>(PO(),T4)),e=new r.GoogleAuth({keyFilename:process.env.GOOGLE_APPLICATION_CREDENTIALS,scopes:["https://www.googleapis.com/auth/cloud-platform"]}),t=await Ge(e.getAccessToken(),WI.PROVIDER.AUTH_MS);if(!t)throw new it({code:st.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 it?r:new it({code:st.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 yse(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 Hsr(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 E4(r,e,t={},n){let o=await m$e(),s=o.project,i=n||o.location,a=Date.now(),c=t.resolution||"720p",l=t.length||6,u=t.aspectRatio||"16:9",d=t.audio??!0;g.debug("Starting Vertex video generation",{project:s,location:i,model:S4,resolution:c,durationSeconds:l,aspectRatio:u,generateAudio:d,promptLength:e.length,imageSize:r.length});try{let p=r.toString("base64"),f=yse(r),h=await f$e(),x=`https://${i==="global"?"aiplatform.googleapis.com":`${i}-aiplatform.googleapis.com`}/v1/projects/${s}/locations/${i}/publishers/google/models/${S4}:predictLongRunning`,b={instances:[{prompt:e,image:{bytesBase64Encoded:p,mimeType:f}}],parameters:{sampleCount:1,durationSeconds:l,aspectRatio:u,resolution:c,generateAudio:d,resizeMode:"pad"}};g.debug("Sending video generation request",{endpoint:x});let T=new AbortController,S=setTimeout(()=>T.abort(),3e4),_;try{_=await fetch(x,{method:"POST",headers:{Authorization:`Bearer ${h}`,"Content-Type":"application/json; charset=utf-8"},body:JSON.stringify(b),signal:T.signal})}catch(D){throw clearTimeout(S),Hr(D)?new it({code:st.GENERATION_FAILED,message:"Video generation request timed out after 30 seconds",category:"execution",severity:"high",retriable:!0,context:{provider:"vertex",endpoint:x,timeout:3e4}}):D}if(clearTimeout(S),!_.ok){let D=await _.text();throw new it({code:st.GENERATION_FAILED,message:`Vertex API error: ${_.status} - ${D}`,category:"execution",severity:"high",retriable:_.status>=500,context:{status:_.status,error:D,provider:"vertex",endpoint:x}})}let C=await _.json(),R=C.name;if(!R)throw new it({code:st.GENERATION_FAILED,message:"Vertex API did not return an operation name",category:"execution",severity:"high",retriable:!1,context:{response:C,provider:"vertex"}});g.debug("Video generation operation started",{operationName:R});let P=p$e-(Date.now()-a),A=await Jsr(R,h,s,i,Math.max(1e3,P)),I=Date.now()-a,M=Hsr(c,u);return g.info("Video generation complete",{processingTime:I,videoSizeKB:Math.round(A.length/1024),dimensions:M}),{data:A,mediaType:"video/mp4",metadata:{duration:l,dimensions:M,model:S4,provider:"vertex",aspectRatio:u,audioEnabled:d,processingTime:I}}}catch(p){throw p instanceof it?p:new it({code:st.GENERATION_FAILED,message:`Video generation failed: ${p instanceof Error?p.message:String(p)}`,category:"execution",severity:"high",retriable:!0,context:{provider:"vertex"},originalError:p instanceof Error?p:void 0})}}function Wsr(r,e){if(r.error)throw new it({code:st.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 it({code:st.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 it({code:st.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 it({code:st.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 Ksr(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),Hr(a)?new it({code:st.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 it({code:st.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 Jsr(r,e,t,n,o){return g$e(S4,r,e,t,n,o)}async function _4(r,e,t,n={},o=4,s){let i=await m$e(),a=i.project,c=s||i.location,l=Date.now(),u=n.aspectRatio||"16:9",d=n.resolution||"720p",p=n.audio??!0;g.debug("Starting transition clip generation",{model:hse,durationSeconds:o,firstFrameSize:r.length,lastFrameSize:e.length,promptLength:t.length});try{let f=r.toString("base64"),h=e.toString("base64"),y=yse(r),x=yse(e),b=await f$e(),T=`https://${c}-aiplatform.googleapis.com/v1/projects/${a}/locations/${c}/publishers/google/models/${hse}:predictLongRunning`,S={instances:[{prompt:t,image:{bytesBase64Encoded:f,mimeType:y},lastFrame:{bytesBase64Encoded:h,mimeType:x}}],parameters:{sampleCount:1,durationSeconds:o,aspectRatio:u,resolution:d,generateAudio:p}},_=new AbortController,C=setTimeout(()=>_.abort(),3e4),R;try{R=await fetch(T,{method:"POST",headers:{Authorization:`Bearer ${b}`,"Content-Type":"application/json; charset=utf-8"},body:JSON.stringify(S),signal:_.signal})}catch(D){throw clearTimeout(C),Hr(D)?new it({code:st.DIRECTOR_TRANSITION_FAILED,message:"Transition generation request timed out after 30 seconds",category:"execution",severity:"medium",retriable:!0}):D}if(clearTimeout(C),!R.ok){let D=await R.text();throw new it({code:st.DIRECTOR_TRANSITION_FAILED,message:`Transition API error: ${R.status} - ${D}`,category:"execution",severity:"medium",retriable:R.status>=500,context:{status:R.status,error:D}})}let A=(await R.json()).name;if(!A)throw new it({code:st.DIRECTOR_TRANSITION_FAILED,message:"Transition API did not return an operation name",category:"execution",severity:"medium",retriable:!1});let I=p$e-(Date.now()-l),M=await Ysr(A,b,a,c,Math.max(1e3,I));return g.debug("Transition clip generated",{processingTime:Date.now()-l,videoSize:M.length}),M}catch(f){throw f instanceof it?f:new it({code:st.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 g$e(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 Ksr(c,e,t);if(l.done)return Wsr(l,e);g.debug("Polling operation...",{operationName:e,elapsed:Date.now()-i}),await new Promise(u=>setTimeout(u,Vsr))}throw new it({code:st.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 Ysr(r,e,t,n,o){return g$e(hse,r,e,t,n,o)}var it,p$e,Vsr,S4,hse,qsr,w4,rT=k(()=>{"use strict";qa();KI();mm();It();H();it=class extends $e{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"}},p$e=18e4,Vsr=5e3,S4="veo-3.1-generate-001",hse="veo-3.1-fast-generate-001",qsr="us-central1";w4=class{maxDurationSeconds=8;supportedAspectRatios=["9:16","16:9"];supportedResolutions=["720p","1080p"];isConfigured(){return xse()}generate(e,t,n,o){return E4(e,t,n,o)}generateTransition(e,t,n,o,s){return _4(e,t,n,{aspectRatio:o?.aspectRatio,resolution:o?.resolution,audio:o?.audio},o?.durationSeconds??4,s)}}});var vse={};Q(vse,{VIDEO_ERROR_CODES:()=>st,VideoError:()=>it,VideoProcessor:()=>k4});var k4,nx=k(()=>{"use strict";mm();xo();H();rT();k4=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=ve.createSpan("media.generation","video.generate",this.buildSpanAttributes(e,o));try{let a=this.getHandler(e);if(!a)throw new it({code:st.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 it({code:st.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=ve.endSpan(i,1);return Ze().recordSpan(l),g.info(`[VideoProcessor] Generated ${c.data.length} bytes (${e})`),c}catch(a){let c=ve.endSpan(i,2,a instanceof Error?a.message:String(a));if(Ze().recordSpan(c),a instanceof it)throw a;let l=a instanceof Error?a.message:String(a);throw new it({code:st.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 it({code:st.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 it({code:st.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 it({code:st.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 it)throw c;let l=c instanceof Error?c.message:String(c);throw new it({code:st.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 bse,MO,y$e=k(()=>{bse=class{value;next;constructor(e){this.value=e}},MO=class{#e;#t;#r;constructor(){this.clear()}enqueue(e){let t=new bse(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 Vm(r){let e=!1;if(typeof r=="object"&&({concurrency:r,rejectOnClear:e=!1}=r),x$e(r),typeof e!="boolean")throw new TypeError("Expected `rejectOnClear` to be a boolean");let t=new MO,n=0,o=()=>{n<r&&t.size>0&&(n++,t.dequeue().run())},s=()=>{n--,o()},i=async(l,u,d)=>{let p=(async()=>l(...d))();u(p);try{await p}catch{}s()},a=(l,u,d,p)=>{let f={reject:d};new Promise(h=>{f.run=h,t.enqueue(f)}).then(i.bind(void 0,l,u,p)),n<r&&o()},c=(l,...u)=>new Promise((d,p)=>{a(l,d,p,u)});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){x$e(l),r=l,queueMicrotask(()=>{for(;n<r&&t.size>0;)o()})}},map:{async value(l,u){let d=Array.from(l,(p,f)=>this(u,p,f));return Promise.all(d)}}}),c}function x$e(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 OO=k(()=>{y$e()});var Dp={};Q(Dp,{AsyncLocalStorage:()=>hir,Buffer:()=>Xar,Channel:()=>Bar,DatabaseSync:()=>Yar,Duplex:()=>xir,EventEmitter:()=>gir,Http2ServerRequest:()=>tcr,Http2ServerResponse:()=>rcr,Interface:()=>Jar,MIMEType:()=>ccr,PassThrough:()=>vir,PerformanceObserver:()=>Uar,Readable:()=>b$e,ReadableStream:()=>bir,Resolver:()=>Dar,TextDecoder:()=>w$e,TextEncoder:()=>C4,Transform:()=>yir,URL:()=>Sar,URLSearchParams:()=>war,Worker:()=>Var,Writable:()=>T$e,access:()=>Lir,appendFile:()=>Eir,appendFileSync:()=>R4,arch:()=>ear,arrayBuffer:()=>ncr,basename:()=>cir,builtinModules:()=>yar,callbackify:()=>Iar,channel:()=>$ar,chmodSync:()=>wir,clearInterval:()=>acr,clearTimeout:()=>scr,closeSync:()=>Cir,connect:()=>oar,constants:()=>Ese,copyFileSync:()=>_ir,cpSync:()=>nir,cpus:()=>Yir,createConnection:()=>sar,createGunzip:()=>par,createGzip:()=>mar,createHash:()=>v$e,createHmac:()=>Qsr,createInterface:()=>Kar,createReadStream:()=>ox,createRequire:()=>har,createServer:()=>oir,createWriteStream:()=>wse,debug:()=>Rar,debuglog:()=>S$e,default:()=>Xsr,deflateSync:()=>aar,deprecate:()=>Aar,deserialize:()=>Gar,dirname:()=>air,exec:()=>jir,execFile:()=>Vir,execFileSync:()=>qir,execSync:()=>Gir,existsSync:()=>Os,extname:()=>lir,fileURLToPath:()=>Ear,finished:()=>Sir,format:()=>Tar,freemem:()=>Xir,fstatSync:()=>Rir,get:()=>nar,gunzip:()=>dar,gunzipSync:()=>car,gzip:()=>uar,gzipSync:()=>lar,hasSubscribers:()=>zar,homedir:()=>Wir,hostname:()=>Jir,inflateSync:()=>iar,inherits:()=>kar,inspect:()=>I4,isAbsolute:()=>dir,isBuiltin:()=>xar,isDeepStrictEqual:()=>Par,isIP:()=>ecr,isIPv4:()=>Qar,isIPv6:()=>Zar,isMainThread:()=>qar,join:()=>sir,lookup:()=>Nar,mkdir:()=>Mir,mkdirSync:()=>Au,monitorEventLoopDelay:()=>Far,normalize:()=>fir,ok:()=>far,open:()=>$ir,openSync:()=>kir,parentPort:()=>Har,parse:()=>bar,pathToFileURL:()=>_ar,performance:()=>Lar,pipeline:()=>Tir,platform:()=>Hir,posix:()=>mir,promises:()=>Zsr,promisify:()=>Car,randomBytes:()=>eir,randomUUID:()=>tir,readFile:()=>Iir,readFileSync:()=>Ns,readdir:()=>Nir,readdirSync:()=>c0,realpath:()=>Bir,realpathSync:()=>A4,relative:()=>uir,release:()=>tar,rename:()=>Uir,renameSync:()=>Tse,request:()=>rar,resolve:()=>iir,rm:()=>Fir,rmSync:()=>Air,rmdirSync:()=>Sse,sep:()=>pir,serialize:()=>jar,setInterval:()=>icr,setTimeout:()=>ocr,spawn:()=>zir,stat:()=>Oir,statSync:()=>nT,strict:()=>gar,tmpdir:()=>Kir,toUSVString:()=>Mar,totalmem:()=>Zir,type:()=>Qir,types:()=>Oar,unlink:()=>Dir,unlinkSync:()=>NO,webcrypto:()=>rir,workerData:()=>War,writeFile:()=>Pir,writeFileSync:()=>Np});var Ms,qo,Xsr,Zsr,v$e,Qsr,eir,tir,rir,R4,nir,oir,sir,iir,air,cir,lir,uir,dir,pir,mir,fir,gir,hir,b$e,T$e,yir,xir,vir,bir,Tir,Sir,Os,Ns,Np,wir,Eir,A4,_ir,kir,Cir,Rir,Au,nT,c0,NO,Tse,Sse,Air,wse,ox,Iir,Pir,Mir,Oir,Nir,Dir,Lir,Uir,Fir,$ir,Bir,zir,jir,Gir,Vir,qir,Hir,Wir,Kir,Jir,Yir,Xir,Zir,Qir,ear,tar,rar,nar,oar,sar,iar,aar,car,lar,uar,dar,par,mar,far,gar,har,yar,xar,bar,Tar,Sar,war,Ear,_ar,kar,Car,S$e,Rar,I4,Aar,Iar,Par,Mar,Oar,w$e,C4,Nar,Dar,Lar,Uar,Far,$ar,Bar,zar,jar,Gar,Var,qar,Har,War,Kar,Jar,Yar,Xar,Ese,Zar,Qar,ecr,tcr,rcr,ncr,E$e,ocr,scr,icr,acr,ccr,ei=k(()=>{Ms=()=>{},qo=async()=>{},Xsr={},Zsr={readFile:qo,writeFile:qo,mkdir:qo,stat:qo,readdir:qo,unlink:qo,access:qo,rm:qo,rename:qo},v$e=r=>{let e=[];return{update(t){return e.push(typeof t=="string"?new C4().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}}},Qsr=(r,e)=>v$e(r),eir=r=>new Uint8Array(r||32),tir=()=>globalThis.crypto?.randomUUID?.()||Math.random().toString(36),rir=globalThis.crypto,R4=()=>{throw new Error("[NeuroLink:browser] fs.appendFileSync is not supported in browser runtime \u2014 use server-side execution")},nir=()=>{throw new Error("[NeuroLink:browser] fs.cpSync is not supported in browser runtime \u2014 use server-side execution")},oir=()=>({listen:Ms,close:Ms,on:Ms}),sir=(...r)=>r.join("/"),iir=(...r)=>r.join("/"),air=r=>r||"",cir=r=>r?.split?.("/")?.pop?.()||"",lir=r=>{let e=r?.match?.(/\.[^.]+$/);return e?e[0]:""},uir=(r,e)=>e||"",dir=()=>!1,pir="/",mir={normalize:r=>r,join:(...r)=>r.join("/"),resolve:(...r)=>r.join("/"),sep:"/"},fir=r=>r,gir=class{on(){return this}off(){return this}emit(){return this}once(){return this}removeListener(){return this}addListener(){return this}},hir=class{getStore(){}run(r,e,...t){return e(...t)}enterWith(){}disable(){}},b$e=class{pipe(){return this}on(){return this}read(){return null}push(){}destroy(){}},T$e=class{write(){return!0}end(){}on(){return this}destroy(){}},yir=class{push(){}on(){return this}},xir=class{on(){return this}},vir=class{pipe(){return this}on(){return this}},bir=globalThis.ReadableStream||class{},Tir=Ms,Sir=Ms,Os=()=>!1,Ns=()=>"",Np=Ms,wir=Ms,Eir=qo,A4=r=>r,_ir=Ms,kir=()=>0,Cir=Ms,Rir=()=>({}),Au=Ms,nT=()=>({}),c0=()=>[],NO=Ms,Tse=Ms,Sse=Ms,Air=Ms,wse=()=>new T$e,ox=()=>new b$e,Iir=qo,Pir=qo,Mir=qo,Oir=qo,Nir=qo,Dir=qo,Lir=qo,Uir=qo,Fir=qo,$ir=async()=>({stat:qo,readFile:qo,close:qo,read:qo,write:qo}),Bir=async r=>r,zir=()=>({on:Ms,stdout:{on:Ms},stderr:{on:Ms},kill:Ms}),jir=(r,e)=>e?.(null,"",""),Gir=()=>"",Vir=(r,e,t)=>{typeof e=="function"?e(null,"",""):t?.(null,"","")},qir=()=>"",Hir="browser",Wir=()=>"/",Kir=()=>"/tmp",Jir=()=>"browser",Yir=()=>[{}],Xir=()=>0,Zir=()=>0,Qir=()=>"Browser",ear=()=>"wasm",tar=()=>"0",rar=()=>({}),nar=()=>({}),oar=()=>({}),sar=()=>({}),iar=()=>new Uint8Array,aar=()=>new Uint8Array,car=()=>new Uint8Array,lar=()=>new Uint8Array,uar=(r,e)=>e?.(null,r),dar=(r,e)=>e?.(null,r),par=()=>({}),mar=()=>({}),far=Ms,gar={},har=()=>()=>({}),yar=[],xar=()=>!1,bar=r=>({pathname:r||"",hostname:"",protocol:"",search:"",hash:""}),Tar=()=>"",Sar=globalThis.URL,war=globalThis.URLSearchParams,Ear=r=>typeof r=="string"?r.replace("file://",""):r,_ar=r=>new globalThis.URL("file://"+r),kar=(r,e)=>{e&&(r.super_=e,Object.setPrototypeOf(r.prototype,e.prototype))},Car=r=>(...e)=>new Promise((t,n)=>r(...e,(o,s)=>o?n(o):t(s))),S$e=r=>{let e=(...t)=>{};return e.enabled=!1,e},Rar=S$e,I4=r=>{try{return JSON.stringify(r,null,2)}catch{return String(r)}};I4.custom=Symbol.for("nodejs.util.inspect.custom");I4.colors={};I4.styles={};Aar=r=>r,Iar=r=>(...e)=>{let t=e.pop();r(...e).then(n=>t(null,n)).catch(t)},Par=(r,e)=>JSON.stringify(r)===JSON.stringify(e),Mar=r=>String(r),Oar={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},w$e=globalThis.TextDecoder,C4=globalThis.TextEncoder,Nar=(r,e)=>e?.(null,"127.0.0.1",4),Dar=class{},Lar=globalThis.performance||{now:()=>Date.now()},Uar=class{observe(){}disconnect(){}},Far=()=>({enable:Ms,disable:Ms,percentile:()=>0}),$ar=()=>({}),Bar=class{},zar=()=>!1,jar=()=>new Uint8Array,Gar=Ms,Var=class{},qar=!0,Har=null,War=null,Kar=()=>({}),Jar=class{},Yar=class{},Xar=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 C4().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 C4().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 w$e().decode(this)}},Ese={F_OK:0,R_OK:4,W_OK:2,X_OK:1},Zar=()=>!1,Qar=()=>!1,ecr=()=>0,tcr=class{},rcr=class{},ncr=async()=>new ArrayBuffer(0),E$e=r=>({[Symbol.toPrimitive](){return r},ref(){return this},unref(){return this},hasRef(){return!1},refresh(){return this},close(){}}),ocr=(...r)=>E$e(globalThis.setTimeout(...r)),scr=globalThis.clearTimeout,icr=(...r)=>E$e(globalThis.setInterval(...r)),acr=globalThis.clearInterval,ccr=class{constructor(r){this.type=r}toString(){return this.type}}});var mzn,fzn,P4,l0,gzn,hzn,_se,lcr,_$e,yzn,xzn,bzn,Tzn,u0=k(()=>{mzn=globalThis.crypto,fzn=globalThis.ReadableStream||class{},P4=()=>"/",l0=()=>"/tmp",gzn=globalThis.URL,hzn=globalThis.URLSearchParams,_se=r=>{try{return JSON.stringify(r,null,2)}catch{return String(r)}};_se.custom=Symbol.for("nodejs.util.inspect.custom");_se.colors={};_se.styles={};lcr=globalThis.TextDecoder,_$e=globalThis.TextEncoder,yzn=globalThis.performance||{now:()=>Date.now()},xzn=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 _$e().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 _$e().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 lcr().decode(this)}},bzn=globalThis.clearTimeout,Tzn=globalThis.clearInterval});var Cse={};Q(Cse,{AsyncLocalStorage:()=>Icr,Buffer:()=>vur,Channel:()=>cur,DatabaseSync:()=>xur,Duplex:()=>Mcr,EventEmitter:()=>Acr,Http2ServerRequest:()=>Eur,Http2ServerResponse:()=>_ur,Interface:()=>yur,MIMEType:()=>Pur,PassThrough:()=>Ocr,PerformanceObserver:()=>sur,Readable:()=>C$e,ReadableStream:()=>Ncr,Resolver:()=>nur,TextDecoder:()=>I$e,TextEncoder:()=>M4,Transform:()=>Pcr,URL:()=>Vlr,URLSearchParams:()=>qlr,Worker:()=>pur,Writable:()=>R$e,access:()=>clr,appendFile:()=>zcr,appendFileSync:()=>hcr,arch:()=>wlr,arrayBuffer:()=>kur,basename:()=>Scr,builtinModules:()=>Blr,callbackify:()=>Zlr,channel:()=>aur,chmodSync:()=>Bcr,clearInterval:()=>Iur,clearTimeout:()=>Rur,closeSync:()=>qcr,connect:()=>Clr,constants:()=>bur,copyFileSync:()=>Gcr,cpSync:()=>ycr,cpus:()=>vlr,createConnection:()=>Rlr,createGunzip:()=>Dlr,createGzip:()=>Llr,createHash:()=>k$e,createHmac:()=>pcr,createInterface:()=>hur,createReadStream:()=>tlr,createRequire:()=>$lr,createServer:()=>xcr,createWriteStream:()=>elr,debug:()=>Ylr,debuglog:()=>A$e,default:()=>ucr,deflateSync:()=>Ilr,deprecate:()=>Xlr,deserialize:()=>dur,dirname:()=>Tcr,exec:()=>mlr,execFile:()=>kse,execFileSync:()=>$i,execSync:()=>flr,existsSync:()=>Ucr,extname:()=>wcr,fileURLToPath:()=>Hlr,finished:()=>Lcr,format:()=>Glr,freemem:()=>blr,fstatSync:()=>Hcr,get:()=>klr,gunzip:()=>Nlr,gunzipSync:()=>Plr,gzip:()=>Olr,gzipSync:()=>Mlr,hasSubscribers:()=>lur,homedir:()=>hlr,hostname:()=>xlr,inflateSync:()=>Alr,inherits:()=>Klr,inspect:()=>O4,isAbsolute:()=>_cr,isBuiltin:()=>zlr,isDeepStrictEqual:()=>Qlr,isIP:()=>wur,isIPv4:()=>Sur,isIPv6:()=>Tur,isMainThread:()=>mur,join:()=>vcr,lookup:()=>rur,mkdir:()=>olr,mkdirSync:()=>Wcr,monitorEventLoopDelay:()=>iur,normalize:()=>Rcr,ok:()=>Ulr,open:()=>dlr,openSync:()=>Vcr,parentPort:()=>fur,parse:()=>jlr,pathToFileURL:()=>Wlr,performance:()=>our,pipeline:()=>Dcr,platform:()=>glr,posix:()=>Ccr,promises:()=>dcr,promisify:()=>Jlr,randomBytes:()=>mcr,randomUUID:()=>fcr,readFile:()=>rlr,readFileSync:()=>Fcr,readdir:()=>ilr,readdirSync:()=>Jcr,realpath:()=>plr,realpathSync:()=>jcr,relative:()=>Ecr,release:()=>Elr,rename:()=>llr,renameSync:()=>Xcr,request:()=>_lr,resolve:()=>bcr,rm:()=>ulr,rmSync:()=>Qcr,rmdirSync:()=>Zcr,sep:()=>kcr,serialize:()=>uur,setInterval:()=>Aur,setTimeout:()=>Cur,spawn:()=>d0,stat:()=>slr,statSync:()=>Kcr,strict:()=>Flr,tmpdir:()=>ylr,toUSVString:()=>eur,totalmem:()=>Tlr,type:()=>Slr,types:()=>tur,unlink:()=>alr,unlinkSync:()=>Ycr,webcrypto:()=>gcr,workerData:()=>gur,writeFile:()=>nlr,writeFileSync:()=>$cr});var Ds,Ho,ucr,dcr,k$e,pcr,mcr,fcr,gcr,hcr,ycr,xcr,vcr,bcr,Tcr,Scr,wcr,Ecr,_cr,kcr,Ccr,Rcr,Acr,Icr,C$e,R$e,Pcr,Mcr,Ocr,Ncr,Dcr,Lcr,Ucr,Fcr,$cr,Bcr,zcr,jcr,Gcr,Vcr,qcr,Hcr,Wcr,Kcr,Jcr,Ycr,Xcr,Zcr,Qcr,elr,tlr,rlr,nlr,olr,slr,ilr,alr,clr,llr,ulr,dlr,plr,d0,mlr,flr,kse,$i,glr,hlr,ylr,xlr,vlr,blr,Tlr,Slr,wlr,Elr,_lr,klr,Clr,Rlr,Alr,Ilr,Plr,Mlr,Olr,Nlr,Dlr,Llr,Ulr,Flr,$lr,Blr,zlr,jlr,Glr,Vlr,qlr,Hlr,Wlr,Klr,Jlr,A$e,Ylr,O4,Xlr,Zlr,Qlr,eur,tur,I$e,M4,rur,nur,our,sur,iur,aur,cur,lur,uur,dur,pur,mur,fur,gur,hur,yur,xur,vur,bur,Tur,Sur,wur,Eur,_ur,kur,P$e,Cur,Rur,Aur,Iur,Pur,sx=k(()=>{Ds=()=>{},Ho=async()=>{},ucr={},dcr={readFile:Ho,writeFile:Ho,mkdir:Ho,stat:Ho,readdir:Ho,unlink:Ho,access:Ho,rm:Ho,rename:Ho},k$e=r=>{let e=[];return{update(t){return e.push(typeof t=="string"?new M4().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}}},pcr=(r,e)=>k$e(r),mcr=r=>new Uint8Array(r||32),fcr=()=>globalThis.crypto?.randomUUID?.()||Math.random().toString(36),gcr=globalThis.crypto,hcr=()=>{throw new Error("[NeuroLink:browser] fs.appendFileSync is not supported in browser runtime \u2014 use server-side execution")},ycr=()=>{throw new Error("[NeuroLink:browser] fs.cpSync is not supported in browser runtime \u2014 use server-side execution")},xcr=()=>({listen:Ds,close:Ds,on:Ds}),vcr=(...r)=>r.join("/"),bcr=(...r)=>r.join("/"),Tcr=r=>r||"",Scr=r=>r?.split?.("/")?.pop?.()||"",wcr=r=>{let e=r?.match?.(/\.[^.]+$/);return e?e[0]:""},Ecr=(r,e)=>e||"",_cr=()=>!1,kcr="/",Ccr={normalize:r=>r,join:(...r)=>r.join("/"),resolve:(...r)=>r.join("/"),sep:"/"},Rcr=r=>r,Acr=class{on(){return this}off(){return this}emit(){return this}once(){return this}removeListener(){return this}addListener(){return this}},Icr=class{getStore(){}run(r,e,...t){return e(...t)}enterWith(){}disable(){}},C$e=class{pipe(){return this}on(){return this}read(){return null}push(){}destroy(){}},R$e=class{write(){return!0}end(){}on(){return this}destroy(){}},Pcr=class{push(){}on(){return this}},Mcr=class{on(){return this}},Ocr=class{pipe(){return this}on(){return this}},Ncr=globalThis.ReadableStream||class{},Dcr=Ds,Lcr=Ds,Ucr=()=>!1,Fcr=()=>"",$cr=Ds,Bcr=Ds,zcr=Ho,jcr=r=>r,Gcr=Ds,Vcr=()=>0,qcr=Ds,Hcr=()=>({}),Wcr=Ds,Kcr=()=>({}),Jcr=()=>[],Ycr=Ds,Xcr=Ds,Zcr=Ds,Qcr=Ds,elr=()=>new R$e,tlr=()=>new C$e,rlr=Ho,nlr=Ho,olr=Ho,slr=Ho,ilr=Ho,alr=Ho,clr=Ho,llr=Ho,ulr=Ho,dlr=async()=>({stat:Ho,readFile:Ho,close:Ho,read:Ho,write:Ho}),plr=async r=>r,d0=()=>({on:Ds,stdout:{on:Ds},stderr:{on:Ds},kill:Ds}),mlr=(r,e)=>e?.(null,"",""),flr=()=>"",kse=(r,e,t)=>{typeof e=="function"?e(null,"",""):t?.(null,"","")},$i=()=>"",glr="browser",hlr=()=>"/",ylr=()=>"/tmp",xlr=()=>"browser",vlr=()=>[{}],blr=()=>0,Tlr=()=>0,Slr=()=>"Browser",wlr=()=>"wasm",Elr=()=>"0",_lr=()=>({}),klr=()=>({}),Clr=()=>({}),Rlr=()=>({}),Alr=()=>new Uint8Array,Ilr=()=>new Uint8Array,Plr=()=>new Uint8Array,Mlr=()=>new Uint8Array,Olr=(r,e)=>e?.(null,r),Nlr=(r,e)=>e?.(null,r),Dlr=()=>({}),Llr=()=>({}),Ulr=Ds,Flr={},$lr=()=>()=>({}),Blr=[],zlr=()=>!1,jlr=r=>({pathname:r||"",hostname:"",protocol:"",search:"",hash:""}),Glr=()=>"",Vlr=globalThis.URL,qlr=globalThis.URLSearchParams,Hlr=r=>typeof r=="string"?r.replace("file://",""):r,Wlr=r=>new globalThis.URL("file://"+r),Klr=(r,e)=>{e&&(r.super_=e,Object.setPrototypeOf(r.prototype,e.prototype))},Jlr=r=>(...e)=>new Promise((t,n)=>r(...e,(o,s)=>o?n(o):t(s))),A$e=r=>{let e=(...t)=>{};return e.enabled=!1,e},Ylr=A$e,O4=r=>{try{return JSON.stringify(r,null,2)}catch{return String(r)}};O4.custom=Symbol.for("nodejs.util.inspect.custom");O4.colors={};O4.styles={};Xlr=r=>r,Zlr=r=>(...e)=>{let t=e.pop();r(...e).then(n=>t(null,n)).catch(t)},Qlr=(r,e)=>JSON.stringify(r)===JSON.stringify(e),eur=r=>String(r),tur={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},I$e=globalThis.TextDecoder,M4=globalThis.TextEncoder,rur=(r,e)=>e?.(null,"127.0.0.1",4),nur=class{},our=globalThis.performance||{now:()=>Date.now()},sur=class{observe(){}disconnect(){}},iur=()=>({enable:Ds,disable:Ds,percentile:()=>0}),aur=()=>({}),cur=class{},lur=()=>!1,uur=()=>new Uint8Array,dur=Ds,pur=class{},mur=!0,fur=null,gur=null,hur=()=>({}),yur=class{},xur=class{},vur=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 M4().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 M4().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 I$e().decode(this)}},bur={F_OK:0,R_OK:4,W_OK:2,X_OK:1},Tur=()=>!1,Sur=()=>!1,wur=()=>0,Eur=class{},_ur=class{},kur=async()=>new ArrayBuffer(0),P$e=r=>({[Symbol.toPrimitive](){return r},ref(){return this},unref(){return this},hasRef(){return!1},refresh(){return this},close(){}}),Cur=(...r)=>P$e(globalThis.setTimeout(...r)),Rur=globalThis.clearTimeout,Aur=(...r)=>P$e(globalThis.setInterval(...r)),Iur=globalThis.clearInterval,Pur=class{constructor(r){this.type=r}toString(){return this.type}}});function Nur(){if(M$e)return;M$e=!0;let r=()=>{for(let e of N4)try{let t=c0(e);for(let n of t)try{NO(cr(e,n))}catch{}Sse(e)}catch{}N4.clear()};process.on("exit",r)}async function D4(r){Nur();let e=cr(l0(),`neurolink-${r}-${vs()}`);return await _l(e,{recursive:!0}),N4.add(e),e}async function L4(r,...e){for(let t of e)try{await Tm(t)}catch(n){g.debug("Failed to clean up temp file",{path:t,error:n instanceof Error?n.message:String(n)})}try{await md(r,{recursive:!0,force:!0})}catch(t){g.debug("Failed to remove temp directory",{path:r,error:t instanceof Error?t.message:String(t)})}N4.delete(r)}async function Dur(){if(ix)return ix;if(process.env.FFMPEG_PATH)return ix=process.env.FFMPEG_PATH,ix;try{let r=await Promise.resolve().then(()=>(goe(),foe)),e=r.default??r;if(typeof e=="string"&&e.length>0)return ix=e,ix}catch{g.debug("ffmpeg-static not available, using system ffmpeg binary")}return ix="ffmpeg",g.warn("Using system ffmpeg binary. If video operations fail with ENOENT, install ffmpeg-static or set FFMPEG_PATH."),ix}async function DO(r,e={}){let{execFile:t}=await Promise.resolve().then(()=>(sx(),Cse)),n=await Dur(),o=e.timeoutMs??Rse,s=e.maxBuffer??Ase;return new Promise((i,a)=>{t(n,r,{timeout:o,maxBuffer:s},(l,u,d)=>{l?a(l):i({stdout:u||"",stderr:d||""})}).on("error",a)})}function U4(r){return r.length<Mur?!1:r.subarray(4,8).equals(Our)}var Rse,O$e,Ase,N$e,Ise,D$e,Mur,Our,N4,M$e,ix,Pse=k(()=>{"use strict";vl();ei();qa();u0();To();H();Rse=3e4,O$e=12e4,Ase=10*1024*1024,N$e=50*1024*1024,Ise="2",D$e="0.5",Mur=12,Our=Buffer.from([102,116,121,112]),N4=new Set,M$e=!1;ix=null});function Lur(r,e){if(!Buffer.isBuffer(r)||r.length===0)throw new it({code:st.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(!U4(r))throw new it({code:st.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 L$e(r,e){let t=Date.now();Lur(r,`extract ${e} frame`);let n=await D4("frame"),o=cr(n,"input.mp4"),s=cr(n,`${e}_frame.jpg`);try{await wc(o,r);let i=e==="first"?["-y","-i",o,"-vframes","1","-q:v",Ise,"-f","image2",s]:["-y","-sseof",`-${D$e}`,"-i",o,"-update","1","-q:v",Ise,"-f","image2",s];await DO(i,{timeoutMs:Rse,maxBuffer:Ase});let a=await bo(s);return g.debug(`Extracted ${e} frame`,{inputSize:r.length,frameSize:a.length,elapsedMs:Date.now()-t}),a}catch(i){throw i instanceof it?i:new it({code:st.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 L4(n,o,s)}}async function U$e(r){return L$e(r,"first")}async function F$e(r){return L$e(r,"last")}var $$e=k(()=>{"use strict";H();Pse();mm();rT()});async function Uur(r,e,t){let n=[],o=[];for(let s=0;s<r.length;s++){let i=cr(e,`clip_${s}.mp4`);await wc(i,r[s]),n.push(i);let a=i.replace(/\\/g,"/").replace(/'/g,"'\\''");o.push(`file '${a}'`)}return await wc(t,o.join(`
1147
- `)),n}async function Fur(r,e){let t={timeoutMs:O$e,maxBuffer:N$e};try{await DO(["-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 DO(["-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 B$e(r){if(r.length===0)throw new it({code:st.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(!U4(r[i]))throw new it({code:st.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 D4("merge"),n=cr(t,"concat.txt"),o=cr(t,"merged.mp4"),s=[];try{s=await Uur(r,t,n),await Fur(n,o);let i=await bo(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 it?i:new it({code:st.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 L4(t,n,o,...s)}}var z$e=k(()=>{"use strict";H();Pse();mm();rT()});var H$e={};Q(H$e,{DIRECTOR_PIPELINE_TIMEOUT_MS:()=>zur,executeDirectorPipeline:()=>Kur});async function Gur(r,e){if(Buffer.isBuffer(r))return r;if(typeof r=="string")return r.startsWith("http://")||r.startsWith("https://")?j$e(r,e):G$e(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 j$e(t,e);if(t.startsWith("data:")){let n=t.match(/^data:[^;]+;base64,(.+)$/);if(n&&n[1])return Buffer.from(n[1],"base64");throw new it({code:st.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 G$e(t,e)}catch(n){throw new it({code:st.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 it({code:st.INVALID_INPUT,message:`Invalid image type for segment ${e}`,category:"execution",severity:"high",retriable:!1,context:{segmentIndex:e}})}async function j$e(r,e){let t=new AbortController,n=setTimeout(()=>t.abort(),$ur);try{let o=await fetch(r,{signal:t.signal});if(!o.ok)throw new it({code:st.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 it?o:new it({code:st.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 G$e(r,e){let{readFile:t}=await Promise.resolve().then(()=>(qa(),kl));try{return await t(r)}catch(n){throw new it({code:st.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 V$e(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>=Mse&&(r.circuitOpen=!0,g.error(`Circuit breaker tripped after ${Mse} consecutive clip failures`))),r.nextExpectedIndex++}}async function Vur(r,e,t,n,o){if(o.circuitOpen)throw new it({code:st.DIRECTOR_CLIP_FAILED,message:`Clip ${e} skipped \u2014 circuit breaker open after ${Mse} consecutive failures`,category:"execution",severity:"high",retriable:!0,context:{segmentIndex:e}});let s=Date.now();try{let i=await Gur(r.image,e),a=c4(i);if(a)throw new it({code:st.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 E4(i,r.prompt,t,n)).data,processingTime:Date.now()-s};o.results[e]=l,o.completions[e]={status:"success",result:l},V$e(o)}catch(i){let a=i instanceof Error?i:new Error(String(i));throw o.completions[e]={status:"failure",error:a},V$e(o),new it({code:st.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 qur(r,e,t){let n=Vm(F4),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(()=>Vur(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 it({code:st.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:F4}),o.results}async function Hur(r,e,t,n,o){let s=r.length-1;if(s===0)return[];let i=Vm(F4),a=Array.from({length:s},(c,l)=>i(async()=>{let u=Date.now(),d=e[l]??Bur,p=t[l]??jur;try{let f=await q$e(r[l].buffer,"last",l),h=await q$e(r[l+1].buffer,"first",l+1),y=await _4(f,h,d,{aspectRatio:n.aspectRatio,resolution:n.resolution,audio:n.audio},p,o);return g.debug(`Transition ${l}\u2192${l+1} generated`,{duration:p,size:y.length,elapsedMs:Date.now()-u}),{buffer:y,fromSegment:l,toSegment:l+1,duration:p,processingTime:Date.now()-u}}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()-u}}}));return Promise.all(a)}async function q$e(r,e,t){let n=e==="first"?U$e:F$e;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 Wur(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 B$e(t)}catch(s){throw new it({code:st.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 Kur(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:F4,clipDuration:a,resolution:e.resolution??"720p"});let u=await qur(r,e,n);g.info("Phase 1 complete \u2014 all clips generated",{clipCount:u.length,elapsedMs:Date.now()-o});let d=await Hur(u,c,l,e,n),p=d.filter(C=>C.buffer).length,f=i-p;f>0&&g.warn(`${f}/${i} transition(s) fell back to hard cut`),g.info("Phase 2 complete \u2014 transitions generated",{successful:p,hardCuts:f,elapsedMs:Date.now()-o});let h=await Wur(u,d),y=d.map(C=>C.duration),x=s*a+y.reduce((C,R)=>C+R,0),b=e.resolution??"720p",T=e.aspectRatio??"16:9",S=b==="1080p"?T==="9:16"?{width:1080,height:1920}:{width:1920,height:1080}:T==="9:16"?{width:720,height:1280}:{width:1280,height:720},_=Date.now()-o;return g.info("Director Mode pipeline complete",{totalDuration:x,segmentCount:s,transitionsGenerated:p,hardCuts:f,mergedSize:h.length,processingTime:_}),{data:h,mediaType:"video/mp4",metadata:{duration:x,dimensions:S,model:"veo-3.1-generate-001",provider:"vertex",aspectRatio:T,audioEnabled:e.audio??!0,processingTime:_,segmentCount:s,transitionCount:p,clipDuration:a,transitionDurations:y,segments:u.map((C,R)=>({index:R,duration:a,processingTime:C.processingTime})),transitions:d.map(C=>({fromSegment:C.fromSegment,toSegment:C.toSegment,duration:C.duration,processingTime:C.processingTime}))}}}var F4,Mse,$ur,Bur,zur,jur,W$e=k(()=>{"use strict";OO();H();Yy();mm();$$e();rT();z$e();F4=2,Mse=2,$ur=15e3,Bur="Smooth cinematic transition between scenes",zur=6e5,jur=4});var po,Iu=k(()=>{"use strict";Dr();qI();xa();G7();Sl();It();$B();Z7();H();ui();no();gI();dy();va();GOe();Ate();uj();Pte();eNe();SNe();HUe();lFe();n$e();s$e();c$e();Gv();po=class r{modelName;providerName;defaultTimeout=3e4;middlewareOptions;directTools=_w()?{}:dm;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 mO(this.providerName,this.modelName),this.streamHandler=new vO(this.providerName,this.modelName),this.telemetryHandler=new CO(this.providerName,this.modelName,this.neurolink),this.generationHandler=new JP(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 IO(this.providerName,this.modelName,this.defaultTimeout,this.middlewareOptions),this.toolsManager=new x4(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,Tt.getSpan(wr.active())?.setAttribute(we.GEN_AI_MODEL,this.modelName),this.messageBuilder=new mO(this.providerName,this.modelName),this.streamHandler=new vO(this.providerName,this.modelName),this.telemetryHandler=new CO(this.providerName,this.modelName,this.neurolink),this.generationHandler=new JP(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 IO(this.providerName,this.modelName,this.defaultTimeout,this.middlewareOptions)}supportsTools(){return!0}async stream(e,t){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){let a=await this.buildMessagesForStream(n);if(Cte(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=hu.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(!n.disableTools&&this.supportsTools()){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 u=await this.executeFakeStreaming(n,t);return this.wrapStreamWithLifecycleCallbacks(u,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=t?.middleware?.middlewareConfig?.lifecycle?.config;if(!n?.onChunk&&!n?.onFinish&&!n?.onError)return e;let{onChunk:o,onFinish:s,onError:i}=n,a=Date.now(),c=e.stream,l=pP(n),u=async(p,f)=>{try{await KB(async()=>{let h=p();h&&typeof h.then=="function"&&await h},l,`[lifecycle] ${f} callback exceeded ${l}ms`)}catch(h){g.warn(`[lifecycle] ${f} callback error:`,h)}},d=(async function*(){let p="",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 x=f++;await u(()=>o({type:"text-delta",textDelta:y,sequenceNumber:x}),"onChunk")}y&&(p+=y),yield h}s&&await u(()=>s({text:p,duration:Date.now()-a}),"onFinish")}catch(h){let y=h instanceof Error?h:new Error(String(h));throw i&&!ub(y)&&(SE(y),await u(()=>i({error:y,duration:Date.now()-a,recoverable:!1}),"onError")),y}})();return{...e,stream:d}}async fireLifecycleErrorCallback(e,t){let n=t instanceof Error?t:new Error(String(t));if(ub(n))return;let o=e?.middleware?.middlewareConfig?.lifecycle?.config,s=o?.onError;if(!s)return;SE(n);let i=pP(o);try{await KB(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,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 lj({options:{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=dj(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),u=t.toolChoice?.toolName;return typeof u=="string"&&!Object.hasOwn(l,u)&&Object.hasOwn(a,u)&&(l[u]=a[u],g.debug("Restored toolChoice-forced tool removed by signature dedup",{provider:this.providerName,toolName:u})),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(ZOe(n.search_tools)){let{search_tools:y,...x}=n;n=x}let o=Object.keys(n).length;if(!this.getToolPolicy(t).discovery)return o>YOe&&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,u=new Set(Object.keys(t.tools??{})),d=[...t.toolFilter??[],...t.enabledToolNames??[]],p=t.toolChoice;p&&typeof p.toolName=="string"&&d.push(p.toolName);let f=d.length>0?UE(d):null,h=i.map(y=>y.name).filter(y=>y in n&&!u.has(y)&&!(f&&f(y)));return QOe(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}=Rte(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=!e.disableTools&&this.supportsTools(),n=t?await this.getAllTools():{},o=t?{...n,...e.tools||{}}:{};o=this.applyToolFiltering(o,e),o=await this.applyToolDiscovery(o,e),g.debug("Final tools prepared for AI",{provider:this.providerName,directTools:kE(n),directToolNames:rz(n),externalTools:kE(e.tools||{}),externalToolNames:rz(e.tools||{}),totalTools:kE(o),totalToolNames:rz(o),shouldUseTools:t,timestamp:Date.now()});let s=await this.getAISDKModelWithMiddleware(e);return{tools:o,model:s}}async getToolsForStream(e){if(!(!e.disableTools&&this.supportsTools()))return{};let n=await this.getAllTools(),o=e.tools||{},s={...n,...o};return s=this.applyToolFiltering(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}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 generate(e,t){let n=this.normalizeTextOptions(e);this.validateOptions(n);let o=Date.now(),s=ke.provider.startSpan("neurolink.provider.generate",{kind:Cr.CLIENT,attributes:{[we.GEN_AI_SYSTEM]:this.providerName||"unknown",[we.GEN_AI_MODEL]:this.modelName||n.model||"unknown",[we.GEN_AI_OPERATION]:"generate",[we.NL_PROVIDER]:this.providerName||"unknown"}}),i=Tt.setSpan(wr.active(),s),a={ended:!1};return await wr.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=hu.some(d=>this.modelName.includes(d)),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 d=await this.executeImageGeneration(e);return await this.enhanceResult(d,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),u=await this.handleVideoFrameGeneration(e,l,c,t);return u||await this.executeStandardGenerateFlow(e,t,c,l,a)}catch(s){throw n.setStatus({code:Pe.ERROR,message:s instanceof Error?s.message:String(s)}),n.end(),o.ended=!0,Hr(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:Pe.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}};try{if(!e.tts)return this.enhanceResult(o,e,t);o.audio=await dp.synthesize(n,e.tts.provider??e.provider??this.providerName,e.tts)}catch(s){g.error("TTS synthesis failed in Mode 1 (direct input synthesis):",s)}return this.enhanceResult(o,e,t)}async handleVideoFrameGeneration(e,t,n,o){if(!Cte(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 jOe(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(u=>u.type==="text").map(u=>u.text):[typeof l.content=="string"?l.content:""]).filter(Boolean).join(`
1147
+ `)),n}async function Fur(r,e){let t={timeoutMs:O$e,maxBuffer:N$e};try{await DO(["-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 DO(["-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 B$e(r){if(r.length===0)throw new it({code:st.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(!U4(r[i]))throw new it({code:st.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 D4("merge"),n=cr(t,"concat.txt"),o=cr(t,"merged.mp4"),s=[];try{s=await Uur(r,t,n),await Fur(n,o);let i=await bo(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 it?i:new it({code:st.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 L4(t,n,o,...s)}}var z$e=k(()=>{"use strict";H();Pse();mm();rT()});var H$e={};Q(H$e,{DIRECTOR_PIPELINE_TIMEOUT_MS:()=>zur,executeDirectorPipeline:()=>Kur});async function Gur(r,e){if(Buffer.isBuffer(r))return r;if(typeof r=="string")return r.startsWith("http://")||r.startsWith("https://")?j$e(r,e):G$e(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 j$e(t,e);if(t.startsWith("data:")){let n=t.match(/^data:[^;]+;base64,(.+)$/);if(n&&n[1])return Buffer.from(n[1],"base64");throw new it({code:st.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 G$e(t,e)}catch(n){throw new it({code:st.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 it({code:st.INVALID_INPUT,message:`Invalid image type for segment ${e}`,category:"execution",severity:"high",retriable:!1,context:{segmentIndex:e}})}async function j$e(r,e){let t=new AbortController,n=setTimeout(()=>t.abort(),$ur);try{let o=await fetch(r,{signal:t.signal});if(!o.ok)throw new it({code:st.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 it?o:new it({code:st.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 G$e(r,e){let{readFile:t}=await Promise.resolve().then(()=>(qa(),kl));try{return await t(r)}catch(n){throw new it({code:st.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 V$e(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>=Mse&&(r.circuitOpen=!0,g.error(`Circuit breaker tripped after ${Mse} consecutive clip failures`))),r.nextExpectedIndex++}}async function Vur(r,e,t,n,o){if(o.circuitOpen)throw new it({code:st.DIRECTOR_CLIP_FAILED,message:`Clip ${e} skipped \u2014 circuit breaker open after ${Mse} consecutive failures`,category:"execution",severity:"high",retriable:!0,context:{segmentIndex:e}});let s=Date.now();try{let i=await Gur(r.image,e),a=c4(i);if(a)throw new it({code:st.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 E4(i,r.prompt,t,n)).data,processingTime:Date.now()-s};o.results[e]=l,o.completions[e]={status:"success",result:l},V$e(o)}catch(i){let a=i instanceof Error?i:new Error(String(i));throw o.completions[e]={status:"failure",error:a},V$e(o),new it({code:st.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 qur(r,e,t){let n=Vm(F4),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(()=>Vur(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 it({code:st.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:F4}),o.results}async function Hur(r,e,t,n,o){let s=r.length-1;if(s===0)return[];let i=Vm(F4),a=Array.from({length:s},(c,l)=>i(async()=>{let u=Date.now(),d=e[l]??Bur,p=t[l]??jur;try{let f=await q$e(r[l].buffer,"last",l),h=await q$e(r[l+1].buffer,"first",l+1),y=await _4(f,h,d,{aspectRatio:n.aspectRatio,resolution:n.resolution,audio:n.audio},p,o);return g.debug(`Transition ${l}\u2192${l+1} generated`,{duration:p,size:y.length,elapsedMs:Date.now()-u}),{buffer:y,fromSegment:l,toSegment:l+1,duration:p,processingTime:Date.now()-u}}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()-u}}}));return Promise.all(a)}async function q$e(r,e,t){let n=e==="first"?U$e:F$e;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 Wur(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 B$e(t)}catch(s){throw new it({code:st.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 Kur(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:F4,clipDuration:a,resolution:e.resolution??"720p"});let u=await qur(r,e,n);g.info("Phase 1 complete \u2014 all clips generated",{clipCount:u.length,elapsedMs:Date.now()-o});let d=await Hur(u,c,l,e,n),p=d.filter(C=>C.buffer).length,f=i-p;f>0&&g.warn(`${f}/${i} transition(s) fell back to hard cut`),g.info("Phase 2 complete \u2014 transitions generated",{successful:p,hardCuts:f,elapsedMs:Date.now()-o});let h=await Wur(u,d),y=d.map(C=>C.duration),x=s*a+y.reduce((C,R)=>C+R,0),b=e.resolution??"720p",T=e.aspectRatio??"16:9",S=b==="1080p"?T==="9:16"?{width:1080,height:1920}:{width:1920,height:1080}:T==="9:16"?{width:720,height:1280}:{width:1280,height:720},_=Date.now()-o;return g.info("Director Mode pipeline complete",{totalDuration:x,segmentCount:s,transitionsGenerated:p,hardCuts:f,mergedSize:h.length,processingTime:_}),{data:h,mediaType:"video/mp4",metadata:{duration:x,dimensions:S,model:"veo-3.1-generate-001",provider:"vertex",aspectRatio:T,audioEnabled:e.audio??!0,processingTime:_,segmentCount:s,transitionCount:p,clipDuration:a,transitionDurations:y,segments:u.map((C,R)=>({index:R,duration:a,processingTime:C.processingTime})),transitions:d.map(C=>({fromSegment:C.fromSegment,toSegment:C.toSegment,duration:C.duration,processingTime:C.processingTime}))}}}var F4,Mse,$ur,Bur,zur,jur,W$e=k(()=>{"use strict";OO();H();Yy();mm();$$e();rT();z$e();F4=2,Mse=2,$ur=15e3,Bur="Smooth cinematic transition between scenes",zur=6e5,jur=4});var po,Iu=k(()=>{"use strict";Dr();qI();xa();G7();Sl();It();$B();Z7();H();ui();no();gI();dy();va();GOe();Ate();uj();Pte();eNe();SNe();HUe();lFe();n$e();s$e();c$e();Gv();po=class r{modelName;providerName;defaultTimeout=3e4;middlewareOptions;directTools=_w()?{}:dm;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 mO(this.providerName,this.modelName),this.streamHandler=new vO(this.providerName,this.modelName),this.telemetryHandler=new CO(this.providerName,this.modelName,this.neurolink),this.generationHandler=new JP(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 IO(this.providerName,this.modelName,this.defaultTimeout,this.middlewareOptions),this.toolsManager=new x4(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,Tt.getSpan(wr.active())?.setAttribute(we.GEN_AI_MODEL,this.modelName),this.messageBuilder=new mO(this.providerName,this.modelName),this.streamHandler=new vO(this.providerName,this.modelName),this.telemetryHandler=new CO(this.providerName,this.modelName,this.neurolink),this.generationHandler=new JP(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 IO(this.providerName,this.modelName,this.defaultTimeout,this.middlewareOptions)}supportsTools(){return!0}async stream(e,t){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){let a=await this.buildMessagesForStream(n);if(Cte(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=hu.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(!n.disableTools&&this.supportsTools()){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 u=await this.executeFakeStreaming(n,t);return this.wrapStreamWithLifecycleCallbacks(u,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=t?.middleware?.middlewareConfig?.lifecycle?.config;if(!n?.onChunk&&!n?.onFinish&&!n?.onError)return e;let{onChunk:o,onFinish:s,onError:i}=n,a=Date.now(),c=e.stream,l=pP(n),u=async(p,f)=>{try{await KB(async()=>{let h=p();h&&typeof h.then=="function"&&await h},l,`[lifecycle] ${f} callback exceeded ${l}ms`)}catch(h){g.warn(`[lifecycle] ${f} callback error:`,h)}},d=(async function*(){let p="",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 x=f++;await u(()=>o({type:"text-delta",textDelta:y,sequenceNumber:x}),"onChunk")}y&&(p+=y),yield h}s&&await u(()=>s({text:p,duration:Date.now()-a}),"onFinish")}catch(h){let y=h instanceof Error?h:new Error(String(h));throw i&&!ub(y)&&(SE(y),await u(()=>i({error:y,duration:Date.now()-a,recoverable:!1}),"onError")),y}})();return{...e,stream:d}}async fireLifecycleErrorCallback(e,t){let n=t instanceof Error?t:new Error(String(t));if(ub(n))return;let o=e?.middleware?.middlewareConfig?.lifecycle?.config,s=o?.onError;if(!s)return;SE(n);let i=pP(o);try{await KB(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,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 lj({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=dj(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),u=t.toolChoice?.toolName;return typeof u=="string"&&!Object.hasOwn(l,u)&&Object.hasOwn(a,u)&&(l[u]=a[u],g.debug("Restored toolChoice-forced tool removed by signature dedup",{provider:this.providerName,toolName:u})),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(ZOe(n.search_tools)){let{search_tools:y,...x}=n;n=x}let o=Object.keys(n).length;if(!this.getToolPolicy(t).discovery)return o>YOe&&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,u=new Set(Object.keys(t.tools??{})),d=[...t.toolFilter??[],...t.enabledToolNames??[]],p=t.toolChoice;p&&typeof p.toolName=="string"&&d.push(p.toolName);let f=d.length>0?UE(d):null,h=i.map(y=>y.name).filter(y=>y in n&&!u.has(y)&&!(f&&f(y)));return QOe(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}=Rte(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=!e.disableTools&&this.supportsTools(),n=t?await this.getAllTools():{},o=t?{...n,...e.tools||{}}:{};o=this.applyToolFiltering(o,e),o=await this.applyToolDiscovery(o,e),g.debug("Final tools prepared for AI",{provider:this.providerName,directTools:kE(n),directToolNames:rz(n),externalTools:kE(e.tools||{}),externalToolNames:rz(e.tools||{}),totalTools:kE(o),totalToolNames:rz(o),shouldUseTools:t,timestamp:Date.now()});let s=await this.getAISDKModelWithMiddleware(e);return{tools:o,model:s}}async getToolsForStream(e){if(!(!e.disableTools&&this.supportsTools()))return{};let n=await this.getAllTools(),o=e.tools||{},s={...n,...o};return s=this.applyToolFiltering(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}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 generate(e,t){let n=this.normalizeTextOptions(e);this.validateOptions(n);let o=Date.now(),s=ke.provider.startSpan("neurolink.provider.generate",{kind:Cr.CLIENT,attributes:{[we.GEN_AI_SYSTEM]:this.providerName||"unknown",[we.GEN_AI_MODEL]:this.modelName||n.model||"unknown",[we.GEN_AI_OPERATION]:"generate",[we.NL_PROVIDER]:this.providerName||"unknown"}}),i=Tt.setSpan(wr.active(),s),a={ended:!1};return await wr.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=hu.some(d=>this.modelName.includes(d)),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 d=await this.executeImageGeneration(e);return await this.enhanceResult(d,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),u=await this.handleVideoFrameGeneration(e,l,c,t);return u||await this.executeStandardGenerateFlow(e,t,c,l,a)}catch(s){throw n.setStatus({code:Pe.ERROR,message:s instanceof Error?s.message:String(s)}),n.end(),o.ended=!0,Hr(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:Pe.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}};try{if(!e.tts)return this.enhanceResult(o,e,t);o.audio=await dp.synthesize(n,e.tts.provider??e.provider??this.providerName,e.tts)}catch(s){g.error("TTS synthesis failed in Mode 1 (direct input synthesis):",s)}return this.enhanceResult(o,e,t)}async handleVideoFrameGeneration(e,t,n,o){if(!Cte(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 jOe(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(u=>u.type==="text").map(u=>u.text):[typeof l.content=="string"?l.content:""]).filter(Boolean).join(`
1148
1148
  `).trim(),a=s,c={input:0,output:0,total:0};if(e.systemPrompt)try{let l=i?`The user asked: "${i}"
1149
1149
 
1150
1150
  Here is the video/image analysis result from the visual analysis system:
@@ -2201,7 +2201,7 @@ ${t}`:a.text:t,u=this.finalizeGenerateRequestResult({generateSpan:n,options:e,te
2201
2201
 
2202
2202
  IMPORTANT: You have a tool called "${o.toolName}" that searches through`,`${o.filesLoaded} loaded document(s) containing ${o.chunksIndexed} indexed chunks.`,`ALWAYS use the "${o.toolName}" tool FIRST to answer the user's question before using any other tools.`,"This tool searches your local knowledge base of pre-loaded documents and is the primary source of truth.","Do NOT use websearchGrounding or any web search tools when the answer can be found in the loaded documents."].join(" "),g.info("[RAG] Tool injected into generate()",{toolName:o.toolName,filesLoaded:o.filesLoaded,chunksIndexed:o.chunksIndexed})}catch(n){g.warn("[RAG] Failed to prepare RAG tool, continuing without RAG",{error:n instanceof Error?n.message:String(n)})}if(await this.applySkillsAugmentation(e),!(e.output?.mode==="avatar"||e.output?.mode==="music"||e.output?.mode==="video"||e.output?.mode==="ppt"||!this.shouldReadMemory(e.memory,e.context?.userId)||!e.context?.userId))try{e.input&&(e.input.text=await this.retrieveMemory(e.input.text??"",e.context.userId,e.memory?.additionalUsers)),g.debug("Memory retrieval successful (generate)")}catch(n){g.warn("Memory retrieval failed (generate):",n)}}async buildGenerateTextOptions(e,t,n){let o={prompt:e.input?.text,provider:e.provider,model:e.model,temperature:e.temperature,maxTokens:e.maxTokens,systemPrompt:e.systemPrompt,schema:e.schema,output:e.output,tools:e.tools,disableTools:e.disableTools,toolFilter:e.toolFilter,excludeTools:e.excludeTools,maxSteps:e.maxSteps,toolChoice:e.toolChoice,prepareStep:e.prepareStep,enabledToolNames:e.enabledToolNames,enableAnalytics:e.enableAnalytics,enableEvaluation:e.enableEvaluation,context:e.context,evaluationDomain:e.evaluationDomain,toolUsageContext:e.toolUsageContext,input:e.input,region:e.region,tts:e.tts,stt:e.stt,fileRegistry:this.fileRegistry,timeout:e.timeout,turnTimeoutMs:e.turnTimeoutMs,stallTimeoutMs:e.stallTimeoutMs,wrapupTimeLeadMs:e.wrapupTimeLeadMs,toolTimeoutMs:e.toolTimeoutMs,abortSignal:e.abortSignal,skipToolPromptInjection:e.skipToolPromptInjection,middleware:e.middleware,conversationMessages:e.conversationMessages,credentials:e.credentials,onFinish:e.onFinish,onError:e.onError},s=e;(s.sessionId||s.userId)&&(o.context={...o.context,...s.sessionId&&!o.context?.sessionId?{sessionId:s.sessionId}:{},...s.userId&&!o.context?.userId?{userId:s.userId}:{}});let i=kWe(o,n);this.conversationMemory&&(i.conversationMemoryConfig=this.conversationMemory.config,i.originalPrompt=t);let{toolResults:a,enhancedPrompt:c}=await this.detectAndExecuteTools(i.prompt||e.input?.text||"",n.domainType);return c!==i.prompt&&(i.prompt=c,g.debug("Enhanced prompt with tool results",{originalLength:(e.input?.text??"").length,enhancedLength:c.length,toolResults:a.length})),i}finalizeGenerateRequestResult(e){let{generateSpan:t,options:n,textOptions:o,textResult:s,factoryResult:i,originalPrompt:a,startTime:c}=e;if(o.schema&&s.structuredData===void 0&&typeof s.content=="string"){let f=bj(s.content,o.schema);if(f)s.content=f.content,s.structuredData=f.structuredData,f.repaired&&(s.jsonRepaired=!0),f.truncated&&(s.jsonTruncated=!0);else try{let h=JSON.parse(s.content);h===""?(s.content="",g.warn("[NeuroLink] schema requested but the model returned an empty JSON string; normalizing to empty content",{provider:s.provider,model:s.model})):h!=null&&(s.structuredData=h)}catch{g.warn("[NeuroLink] schema requested but no JSON could be recovered from model output; returning raw text",{provider:s.provider,model:s.model})}}o.schema&&(s.finishReason==="length"&&(s.jsonTruncated=!0),s.jsonTruncated&&g.warn("[NeuroLink] Structured output may be truncated (finishReason=length or unclosed JSON); increase maxTokens to fit the full response.",{provider:s.provider,model:s.model,finishReason:s.finishReason,outputTokens:s.usage?.output})),s._generationEndEmitted||this.emitter.emit("generation:end",{provider:s.provider,responseTime:Date.now()-c,toolsUsed:s.toolsUsed,timestamp:Date.now(),result:s,prompt:a||n.input?.text||n.prompt,temperature:o.temperature,maxTokens:o.maxTokens,pipelineAHandled:!0}),this.emitter.emit("response:end",s.content||""),this.emitter.emit("message",`Generation completed in ${Date.now()-c}ms`);let u={content:s.content,structuredData:s.structuredData,finishReason:s.finishReason,stopReason:s.stopReason,rawFinishReason:s.rawFinishReason,stepsUsed:s.stepsUsed,jsonRepaired:s.jsonRepaired,jsonTruncated:s.jsonTruncated,provider:s.provider,model:s.model,usage:s.usage?{input:s.usage.input||0,output:s.usage.output||0,total:s.usage.total||0}:void 0,responseTime:s.responseTime,toolsUsed:s.toolsUsed,toolExecutions:pd(s.toolExecutions),enhancedWithTools:s.enhancedWithTools,availableTools:cMe(s.availableTools),analytics:s.analytics,imageOutput:s.imageOutput,evaluation:s.evaluation?{...s.evaluation,isOffTopic:s.evaluation.isOffTopic??!1,alertSeverity:s.evaluation.alertSeverity??"none",reasoning:s.evaluation.reasoning??"No evaluation provided",evaluationModel:s.evaluation.evaluationModel??"unknown",evaluationTime:s.evaluation.evaluationTime??Date.now(),evaluationDomain:s.evaluation.evaluationDomain??o.evaluationDomain??i.domainType}:void 0,audio:s.audio,transcription:s.transcription,video:s.video,avatar:s.avatar,music:s.music,ppt:s.ppt,reasoning:s.reasoning,reasoningTokens:s.reasoningTokens,...s.retries&&{retries:s.retries}};if(n.responseValidation){let f=Vpe(u.content??"",{minLength:n.responseValidation.minLength,maxLength:n.responseValidation.maxLength,requiredPhrases:n.responseValidation.requiredPhrases,forbiddenPhrases:n.responseValidation.forbiddenPhrases,jsonSchema:n.responseValidation.jsonSchema,customValidator:n.responseValidation.customValidator,truncationAction:n.responseValidation.truncationAction,truncationSuffix:n.responseValidation.truncationSuffix,retryOnFailure:n.responseValidation.retryOnFailure,maxRetries:n.responseValidation.maxRetries});if(f.action==="abort")throw new Error(f.feedback??`Response validation failed: ${f.issues.map(h=>h.message).join("; ")}`);f.text!==u.content&&(u.content=f.text)}u.analytics?.cost&&u.analytics.cost>0&&(this._sessionCostUsd+=u.analytics.cost),this.scheduleGenerateMemoryStorage(n,a,u),t.setAttribute("neurolink.output_length",u.content?.length||0),t.setAttribute("neurolink.tokens.input",u.usage?.input||0),t.setAttribute("neurolink.tokens.output",u.usage?.output||0),t.setAttribute("neurolink.finish_reason",u.finishReason||"unknown");let d=s?.steps?.length??1,p=n.maxSteps??200;return t.setAttribute("neurolink.step_count",d),t.setAttribute("neurolink.max_steps_reached",d>=p),t.setAttribute("neurolink.result_provider",u.provider||"unknown"),t.setAttribute("neurolink.result_model",u.model||"unknown"),t.setAttribute("generate.retry_count",u.retries?.count||0),t.setStatus({code:Pe.OK}),u}emitGenerateErrorEvent(e,t){let n=typeof e=="object"&&e.provider||"unknown",o=typeof e=="object"&&e.model||"unknown",s=Hr(t);try{this.emitter.emit("generation:end",{provider:n,model:o,responseTime:0,error:t instanceof Error?t.message:String(t),success:!1,aborted:s})}catch(i){}}scheduleGenerateMemoryStorage(e,t,n){this.shouldWriteMemory(e.memory,e.context?.userId,n.content)&&e.context?.userId&&this.storeMemoryInBackground(t??"",n.content.trim(),e.context.userId,e.memory?.additionalUsers,e.context)}async generateWithPPT(e){let t=Date.now(),{generatePresentation:n}=await r6e().then(()=>t6e),{extractPPTContext:o,getEffectivePPTProvider:s}=await Promise.resolve().then(()=>(AW(),yKe)),i=e.provider||"vertex",a=await dn.createProvider(i,e.model,!0,this,void 0,this.resolveCredentials(e.credentials)),c=await s(a,i,e.model||"default",this),l=o(e),u=await n({context:l,provider:c.provider,providerName:c.providerName,modelName:c.modelName,neurolink:this});return{content:`Presentation generated: ${u.filePath} (${u.totalSlides} slides)`,finishReason:"stop",provider:u.provider||i,model:u.model||e.model||"default",usage:void 0,responseTime:Date.now()-t,ppt:u}}async generateWithMusic(e,t){let n=Date.now(),o=e.output?.music;if(!o)throw new Error('output.mode="music" requires output.music with at least { provider, prompt }.');let s=o.provider;if(!s)throw new Error('output.music.provider is required (e.g. "beatoven", "elevenlabs-music", "lyria", "replicate").');let{MusicProcessor:i}=await Promise.resolve().then(()=>(cf(),Ome)),a=await i.generate(s,{...o,prompt:o.prompt??e.input?.text??""});return t.setAttribute("neurolink.music.provider",s),t.setAttribute("neurolink.music.bytes",a.size),t.setStatus({code:Pe.OK}),{content:`Music generated (${s}, ${a.size} bytes, ${a.format}).`,finishReason:"stop",provider:s,model:a.metadata?.model??s,usage:void 0,responseTime:Date.now()-n,music:a}}async generateWithAvatar(e,t){let n=Date.now(),o=e.output?.avatar;if(!o)throw new Error('output.mode="avatar" requires output.avatar with at least { provider, image, audio|text }.');let s=o.provider;if(!s)throw new Error('output.avatar.provider is required (e.g. "d-id", "heygen", "replicate").');let{AvatarProcessor:i}=await Promise.resolve().then(()=>(Jg(),Nme)),a=await i.generate(s,o);return t.setAttribute("neurolink.avatar.provider",s),t.setAttribute("neurolink.avatar.bytes",a.size),t.setStatus({code:Pe.OK}),{content:`Avatar generated (${s}, ${a.size} bytes, ${a.format}).`,finishReason:"stop",provider:s,model:a.metadata?.model??s,usage:void 0,responseTime:Date.now()-n,avatar:a}}async generateWithWorkflow(e){let t=Date.now();g.debug("[NeuroLink] Executing workflow generation",{workflowId:e.workflow,hasInlineConfig:!!e.workflowConfig,prompt:(e.input?.text??"").substring(0,100),startTime:t});let n;if(e.workflowConfig)n=e.workflowConfig;else if(e.workflow){if(n=iW(e.workflow),!n)throw new Error(`Workflow '${e.workflow}' not found in registry`)}else throw new Error("Either workflow or workflowConfig must be provided");let o=await aW(n,{prompt:e.input?.text??"",conversationHistory:e.conversationMessages?.filter(i=>i.role==="user"||i.role==="assistant").map(i=>({role:i.role,content:qm(i.content)}))??e.conversationHistory,timeout:e.timeout,verbose:!1,metadata:e.context}),s={content:o.content,provider:o.selectedResponse?.provider||n.models[0]?.provider,model:o.selectedResponse?.model||n.models[0]?.model,usage:o.usage?{input:o.usage.totalInputTokens,output:o.usage.totalOutputTokens,total:o.usage.totalTokens}:void 0,responseTime:o.totalTime,workflow:{originalResponse:o.originalContent||o.content,processedResponse:o.content,ensembleResponses:o.ensembleResponses.map(i=>({provider:i.provider,model:i.model,content:i.content,responseTime:i.responseTime,status:i.status,error:i.error})),judgeScores:o.judgeScores?{scores:o.judgeScores.scores,reasoning:o.reasoning,selectedModel:`${o.selectedResponse?.provider}-${o.selectedResponse?.model}`}:void 0,selectedModel:`${o.selectedResponse?.provider}-${o.selectedResponse?.model}`,metrics:{totalTime:o.totalTime,ensembleTime:o.ensembleTime,judgeTime:o.judgeTime,conditioningTime:o.conditioningTime},workflowId:o.workflow,workflowName:o.workflowName}};return g.debug("[NeuroLink] Workflow generation complete",{workflowId:o.workflow,selectedModel:s.workflow?.selectedModel,score:o.score,totalTime:o.totalTime}),s}async streamWithWorkflow(e,t){g.debug("[NeuroLink] Executing workflow streaming (progressive)",{workflowId:e.workflow,hasInlineConfig:!!e.workflowConfig,prompt:(e.input?.text??"").substring(0,100)});let n;if(e.workflowConfig)n=e.workflowConfig;else if(e.workflow){if(n=iW(e.workflow),!n)throw new Error(`Workflow '${e.workflow}' not found in registry`)}else throw new Error("Either workflow or workflowConfig must be provided");let{runWorkflowWithStreaming:o}=await Promise.resolve().then(()=>(cW(),v5e)),s=o(n,{prompt:e.input?.text??"",conversationHistory:e.conversationMessages?.filter(d=>d.role==="user"||d.role==="assistant").map(d=>({role:d.role,content:qm(d.content)}))??e.conversationHistory,timeout:e.timeout,verbose:!1,metadata:e.context,streaming:!0}),i=null,a=0,l={stream:(async function*(){for await(let d of s)if(d.type==="preliminary")a=Date.now()-t,g.debug("[NeuroLink] Streaming preliminary response",{responseTime:a,contentLength:d.content.length}),yield{content:d.content,type:"preliminary"};else if(d.type==="final"){i=d.partialResult??null;let p=Date.now()-t;g.debug("[NeuroLink] Streaming final synthesis",{responseTime:p,contentLength:d.content.length}),yield{content:d.content,type:"final"}}})(),provider:n.models[0]?.provider,model:n.models[0]?.model,metadata:{streamId:`workflow-${n.id}-${Date.now()}`,startTime:t,responseTime:0}},u=l.stream;return l.stream=(async function*(){for await(let d of u)yield d;if(i){let d=i,p=Date.now()-t;d.usage&&(l.usage={input:d.usage.totalInputTokens,output:d.usage.totalOutputTokens,total:d.usage.totalTokens}),l.metadata={...l.metadata,totalChunks:2,responseTime:p,preliminaryTime:a};let f=d.ensembleResponses?.map(y=>({provider:y.provider,model:y.model,content:y.content,responseTime:y.responseTime,status:y.status,error:y.error}))??[],h=d.judgeScores?{scores:d.judgeScores.scores,reasoning:d.reasoning??"",selectedModel:d.selectedResponse?`${d.selectedResponse.provider}-${d.selectedResponse.model}`:"unknown"}:void 0;l.workflow={originalResponse:d.originalContent??d.content??"",processedResponse:d.content??"",ensembleResponses:f,judgeScores:h,selectedModel:d.selectedResponse?`${d.selectedResponse.provider}-${d.selectedResponse.model}`:"unknown",metrics:{totalTime:d.totalTime??p,ensembleTime:d.ensembleTime??0,judgeTime:d.judgeTime,conditioningTime:d.conditioningTime},workflowId:d.workflow??n.id,workflowName:d.workflowName??n.name}}})(),g.debug("[NeuroLink] Workflow streaming initialized",{workflowId:n.id}),l}async generateText(e){if(!e.prompt||typeof e.prompt!="string"||e.prompt.trim()==="")throw new Error("GenerateText options must include prompt as a non-empty string");return e.model=tC(e.model,this.modelAliasConfig),await this.generateTextInternal(e)}async generateTextInternal(e){return ke.sdk.startActiveSpan("neurolink.generateTextInternal",{kind:Cr.INTERNAL},t=>this.executeGenerateTextInternalWithSpan(e,t))}async executeGenerateTextInternalWithSpan(e,t){try{let n=this.initializeGenerateTextInternalContext(e);return t.setAttribute("neurolink.request_id",n.requestId),t.setAttribute("neurolink.has_conversation_memory",!!this.conversationMemory),t.setAttribute("neurolink.provider",e.provider||"auto"),t.setAttribute("neurolink.model",e.model||"default"),this.logGenerateTextInternalStart(n.generateInternalId,n.generateInternalStartTime,n.generateInternalHrTimeStart,e,n.functionTag),this.emitGenerationStartEvents(e),await this.runGenerateTextInternalFlow(e,t,n)}catch(n){throw Hr(n)?(t.setAttribute("ai.finishReason","aborted"),t.setAttribute("neurolink.aborted",!0)):(t.recordException(n instanceof Error?n:new Error(String(n))),t.setStatus({code:Pe.ERROR,message:n instanceof Error?n.message:String(n)})),n}finally{t.end()}}initializeGenerateTextInternalContext(e){let t=`generate-internal-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,n=e.context?.requestId,o=typeof n=="string"&&n?n:`req-${Date.now()}-${Math.random().toString(36).substr(2,9)}`;return e.context={...e.context,requestId:o},{generateInternalId:t,generateInternalStartTime:Date.now(),generateInternalHrTimeStart:process.hrtime.bigint(),functionTag:"NeuroLink.generateTextInternal",requestId:o}}async runGenerateTextInternalFlow(e,t,n){try{await this.initializeConversationMemoryForGeneration(n.generateInternalId,n.generateInternalStartTime,n.generateInternalHrTimeStart);let o=await this.attemptMCPGeneration(e,n.generateInternalId,n.generateInternalStartTime,n.generateInternalHrTimeStart,n.functionTag);if(o)return this.finalizeGenerateTextInternalResult({path:"mcp",result:o,options:e,internalSpan:t,requestId:n.requestId,startTime:n.generateInternalStartTime});if(e.abortSignal?.aborted)throw new DOMException("The operation was aborted","AbortError");await this.captureOriginalConversationMessagesForRecovery(e);let s=await this.directProviderGeneration(e);return g.debug(`[${n.functionTag}] Direct generation successful`),this.finalizeGenerateTextInternalResult({path:"direct",result:s,options:e,internalSpan:t,requestId:n.requestId,startTime:n.generateInternalStartTime})}catch(o){let s=await this.handleGenerateTextInternalFailure(e,n,o);if(s)return s;throw Hr(o)&&!(o instanceof $e)?he.aborted(o instanceof Error?o:new Error(String(o))):o}}async captureOriginalConversationMessagesForRecovery(e){if(!this.conversationMemory)return;let t=await Lg(this.conversationMemory,e);e._originalConversationMessages=t?[...t]:void 0}async finalizeGenerateTextInternalResult(e){let{path:t,result:n,options:o,internalSpan:s,requestId:i,startTime:a}=e;g.info(`[NeuroLink.generateTextInternal] generate() - COMPLETE SUCCESS${t==="mcp"?" (MCP path)":""}`,{provider:n.provider,model:n.model,responseTimeMs:Date.now()-a,tokensUsed:n.usage?.total||0,toolsUsed:n.toolsUsed?.length||0,...n.usage?.cacheCreationTokens!==void 0&&{cacheCreationTokens:n.usage.cacheCreationTokens},...n.usage?.cacheReadTokens!==void 0&&{cacheReadTokens:n.usage.cacheReadTokens},...n.usage?.cacheSavingsPercent!==void 0&&{cacheSavingsPercent:n.usage.cacheSavingsPercent}});let c=Date.now();try{await QVe(this.conversationMemory,o,n,new Date(a),i,this.drainPendingSkillMessages(o.context?.sessionId)),this.recordMemorySpan("memory.store",{"memory.operation":"store","memory.path":t},Date.now()-c,1)}catch(l){this.recordMemorySpan("memory.store",{"memory.operation":"store","memory.path":t},Date.now()-c,2,l instanceof Error?l.message:String(l))}return this.emitter.emit("response:end",n.content||""),t==="direct"&&this.emitter.emit("message","Text generation completed successfully"),s.setAttribute("neurolink.path",t),s.setAttribute("neurolink.tokens.input",n.usage?.input||0),s.setAttribute("neurolink.tokens.output",n.usage?.output||0),s.setAttribute("neurolink.result_provider",n.provider||"unknown"),s.setStatus({code:Pe.OK}),n}async handleGenerateTextInternalFailure(e,t,n){let o=await this.tryRecoverGenerateTextOverflow(e,t.functionTag,n,t.generateInternalStartTime);return o||(Hr(n)?g.info(`[${t.functionTag}] Generation aborted \u2014 skipping memory write (aborts must not pollute conversation history)`,{hasMemory:!!this.conversationMemory,memoryType:this.conversationMemory?.constructor?.name||"NONE",sessionId:e.context?.sessionId||"unknown"}):g.error(`[${t.functionTag}] All generation methods failed`,{error:n instanceof Error?n.message:String(n)}),this.emitter.emit("response:end",""),this.emitter.listenerCount("error")>0&&this.emitter.emit("error",n instanceof Error?n:new Error(String(n))),null)}async tryRecoverGenerateTextOverflow(e,t,n,o){if(!fle(n))return null;let s=e._originalConversationMessages,i=e.conversationMessages;if(!this.conversationMemory&&!s&&!i)return null;g.warn(`[${t}] Context overflow detected by provider, attempting smart recovery`,{error:n instanceof Error?n.message:String(n),overflowProvider:s4e(n)});try{let a=i4e(n),c=s??i??(this.conversationMemory?await Lg(this.conversationMemory,e):[]),l=Qc({provider:e.provider||"openai",model:e.model,maxTokens:e.maxTokens,currentPrompt:e.prompt,systemPrompt:e.systemPrompt}),u=a?.actualTokens??l.estimatedInputTokens,d=a?.budgetTokens??l.availableInputTokens,p=Math.floor(d*.7),f=u>0?(u-p)/u:.5,h=[Math.min(.9,f+.15),.5,.75,.9],y=null,x=c,b=null,T=-1;for(let _=0;_<h.length;_++){let C=h[_],P=await new bx({enableSummarize:!1,enablePrune:!0,enableDeduplicate:!0,enableTruncate:!0,truncationFraction:C}).compact(c,p,void 0,e.context?.requestId);if(!P.compacted)continue;y=P;let A=Tk(P.messages),I=Qc({provider:e.provider||"openai",model:e.model,maxTokens:e.maxTokens,systemPrompt:e.systemPrompt,currentPrompt:e.prompt,conversationMessages:A.messages});if(I.withinBudget){x=A.messages,b=I,T=C;break}b=I}if(!y){try{this.emitter.emit("compaction.insufficient",{stagesAttempted:[],finalTokens:u,budget:d,provider:e.provider||"openai",model:e.model,phase:"post-provider-recovery-no-compaction",fractionsTried:h,timestamp:Date.now()})}catch{}throw new Hl(`Context overflow recovery: no compaction stage was able to reduce conversation messages. Provider rejected at ~${u} tokens; budget is ${d} tokens.`,{estimatedTokens:u,availableTokens:d,stagesUsed:[],breakdown:{}})}if(!b?.withinBudget){g.error(`[${t}] Recovery compaction insufficient after escalation, aborting retry`,{estimatedTokens:b?.estimatedInputTokens,availableTokens:b?.availableInputTokens,stagesAttempted:y.stagesUsed,fractionsTried:h});try{this.emitter.emit("compaction.insufficient",{stagesAttempted:y.stagesUsed,finalTokens:b?.estimatedInputTokens,budget:b?.availableInputTokens,provider:e.provider||"openai",model:e.model,phase:"post-provider-recovery",fractionsTried:h,timestamp:Date.now()})}catch{}throw new Hl(`Context overflow recovery failed. Provider rejected at ~${u} tokens, recovery compaction achieved ${y.tokensAfter} tokens but budget is ${d} tokens (after escalation through ${h.length} fractions).`,{estimatedTokens:y.tokensAfter,availableTokens:d,stagesUsed:y.stagesUsed,breakdown:b?.breakdown??{}})}let S=e.turnTimeoutMs;if(typeof e.turnTimeoutMs=="number"&&Number.isFinite(e.turnTimeoutMs)&&o!==void 0){let _=Date.now()-o;S=Math.max(e.turnTimeoutMs-_,Math.min(WX,e.turnTimeoutMs))}return g.info(`[${t}] Smart recovery verified, retrying generation`,{tokensSaved:y.tokensSaved,compactionTarget:p,verifiedTokens:b.estimatedInputTokens,verifiedBudget:b.availableInputTokens,recoveredFraction:T,retryTurnTimeoutMs:S}),this.directProviderGeneration({...e,conversationMessages:x,...S!==void 0&&{turnTimeoutMs:S}})}catch(a){if(a instanceof Hl)throw a;return g.error(`[${t}] Recovery attempt failed`,{error:a instanceof Error?a.message:String(a)}),null}}logGenerateTextInternalStart(e,t,n,o,s){g.debug(`[${s}] Starting generation`,{provider:o.provider||"auto",promptLength:o.prompt?.length||0,hasConversationMemory:!!this.conversationMemory})}emitGenerationStartEvents(e){this.emitter.emit("response:start"),this.emitter.emit("message",`Starting ${e.provider||"auto"} text generation (internal)...`)}async initializeConversationMemoryForGeneration(e,t,n){let o=process.hrtime.bigint();if(this.conversationMemoryNeedsInit&&this.conversationMemoryConfig&&await this.lazyInitializeConversationMemory(e,t,n),this.conversationMemory){g.debug("[NeuroLink] \u{1F9E0} LOG_POINT_G003_CONVERSATION_MEMORY_INIT_START",{logPoint:"G003_CONVERSATION_MEMORY_INIT_START",generateInternalId:e,timestamp:new Date().toISOString(),elapsedMs:Date.now()-t,elapsedNs:(process.hrtime.bigint()-n).toString(),message:"Starting conversation memory initialization"});try{await this.conversationMemory.initialize()}catch(a){g.warn("[NEUROLINK] Redis memory init failed, falling back to in-memory",{error:a instanceof Error?a.message:String(a),generateInternalId:e});let c=this.conversationMemoryConfig?.conversationMemory;this.conversationMemory=new OT({enabled:!0,maxSessions:c?.maxSessions??100,maxTurnsPerSession:c?.maxTurnsPerSession??50}),await this.conversationMemory.initialize()}let i=process.hrtime.bigint()-o;g.debug("[NeuroLink] \u2705 LOG_POINT_G004_CONVERSATION_MEMORY_INIT_SUCCESS",{logPoint:"G004_CONVERSATION_MEMORY_INIT_SUCCESS",generateInternalId:e,timestamp:new Date().toISOString(),elapsedMs:Date.now()-t,elapsedNs:(process.hrtime.bigint()-n).toString(),conversationMemoryDurationNs:i.toString(),conversationMemoryDurationMs:Number(i)/cp,message:"Conversation memory initialization completed successfully"})}}async attemptMCPGeneration(e,t,n,o,s){return!e.disableTools&&!(e.tts?.enabled&&!e.tts?.useAiResponse)?await this.performMCPGenerationRetries(e,t,n,o,s):null}static isNonRetryableToolError(e){if(e instanceof Error&&(Fv.isInstance(e)||Bv.isInstance(e)))return!0;let t=e,n=t&&typeof t.name=="string"?t.name:"",o=t&&typeof t.message=="string"?t.message:String(e??"");return n==="AI_NoSuchToolError"||n==="AI_InvalidToolInputError"||n==="AI_InvalidToolArgumentsError"||o.includes("NoSuchToolError")||o.includes("InvalidToolInputError")||o.includes("InvalidToolArgumentsError")||o.includes("Model tried to call unavailable tool")}async performMCPGenerationRetries(e,t,n,o,s){let i=xs.QUICK,a=e.timeout!==void 0,c=[],l=0,u=i+1;for(let d=1;d<=u;d++){if(e.abortSignal?.aborted)throw g.debug(`[${s}] Abort signal already fired before attempt ${d}, stopping retries`),new DOMException("The operation was aborted","AbortError");try{g.debug(`[${s}] Attempting MCP generation (attempt ${d}/${u})...`);let p=await this.tryMCPGeneration(e);if(p&&(p.content||p.toolExecutions&&p.toolExecutions.length>0))return g.debug(`[${s}] MCP generation successful on attempt ${d}`,{contentLength:p.content?.length||0,toolsUsed:p.toolsUsed?.length||0,toolExecutions:p.toolExecutions?.length||0,retryCount:l}),l>0&&(p.retries={count:l,errors:c}),p;g.debug(`[${s}] MCP generation returned empty result on attempt ${d}`,{hasResult:!!p,hasContent:!!(p&&p.content),contentLength:p?.content?.length||0,toolExecutions:p?.toolExecutions?.length||0})}catch(p){if(Hr(p))throw g.debug(`[${s}] AbortError detected on attempt ${d}, stopping retries`),p;if(a&&p instanceof Error&&p.name==="TimeoutError")throw g.warn(`[${s}] Per-step timeout (${String(e.timeout)}) exhausted on attempt ${d} \u2014 surfacing instead of retrying with the same budget`),p;l++;let f=p instanceof Error?p.message:String(p),h=p instanceof $e?p.code:p instanceof Error?p.name:"UNKNOWN";c.push({code:h,message:f.substring(0,500)}),g.debug(`[${s}] MCP generation failed on attempt ${d}/${u}`,{error:f,willRetry:d<u,retryCount:l});let y=r.isNonRetryableToolError(p);if(fle(p)||y||qW(p)||p instanceof Error&&p.isRetryable===!1||p instanceof Error&&p.statusCode===400){g.debug(`[${s}] Non-retryable error detected, skipping remaining retries`);break}if(d>=u){g.debug(`[${s}] All MCP attempts exhausted, falling back to direct generation`);break}if(await new Promise(b=>{let T=setTimeout(b,500);if(e.abortSignal){let S=()=>{clearTimeout(T),b()};e.abortSignal.addEventListener("abort",S,{once:!0})}}),e.abortSignal?.aborted)throw new DOMException("The operation was aborted","AbortError")}}return null}async tryMCPGeneration(e){if(e.abortSignal?.aborted)throw new DOMException("The operation was aborted","AbortError");let t=e.context?.requestId||"unknown",n=`try-mcp-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,o=Date.now(),s=process.hrtime.bigint(),i="NeuroLink.tryMCPGeneration";try{let a=await this.prepareMCPGenerationContext(e,t,n,o,s);if(!a)return null;let c=await this.ensureMCPGenerationBudget(e,t,a.providerName,a.enhancedSystemPrompt,a.availableTools,a.conversationMessages);return this.generateWithMCPProvider({options:e,requestId:t,functionTag:i,tryMCPStartTime:o,providerName:a.providerName,availableTools:a.availableTools,enhancedSystemPrompt:a.enhancedSystemPrompt,conversationMessages:c})}catch(a){if(Hr(a))throw ie.debug(`[${i}] AbortError detected, rethrowing`),a;if(r.isNonRetryableToolError(a))throw ie.warn(`[${i}] Non-retryable tool error, rethrowing`,{error:a instanceof Error?a.message:String(a)}),a;return ie.warn(`[${i}] MCP generation failed`,{error:a instanceof Error?a.message:String(a)}),null}}async prepareMCPGenerationContext(e,t,n,o,s){if(await this.initializeMCP(),!this.mcpInitialized)return g.warn("[NeuroLink] \u26A0\uFE0F LOG_POINT_T004_MCP_NOT_AVAILABLE",{logPoint:"T004_MCP_NOT_AVAILABLE",tryMCPId:n,timestamp:new Date().toISOString(),elapsedMs:Date.now()-o,elapsedNs:(process.hrtime.bigint()-s).toString(),mcpInitialized:this.mcpInitialized,mcpComponents:{hasExternalServerManager:!!this.externalServerManager,hasToolRegistry:!!this.toolRegistry,hasProviderRegistry:!!dn},fallbackReason:"MCP_NOT_INITIALIZED",message:"MCP not available - returning null for fallback to direct generation"}),null;let i=e.provider==="auto"||!e.provider?await Nx():e.provider,a=await this.getAllAvailableTools(),{tools:c,unavailableTools:l}=this.toolRegistry.getAvailableTools(this.toolCircuitBreakers),u=new Set(c.map(x=>x.name));a=a.filter(x=>u.has(x.name)),a=this.applyToolInfoFiltering(a,e);let d=a.find(x=>x.name.includes("SuccessRateSRByTime")||x.name.includes("juspay-analytics"));g.debug("Available tools for AI prompt generation",{toolsCount:a.length,toolNames:a.map(x=>x.name),unavailableToolsCount:l.length,unavailableTools:l,hasTargetTool:!!d,targetToolDetails:d?{name:d.name,description:d.description,server:d.server}:null});let p=l.length>0?`
2203
2203
 
2204
- NOTE: The following tools are temporarily unavailable due to repeated failures: ${l.join(", ")}. Do not attempt to call these tools.`:"";l.length>0&&(e.excludeTools=[...new Set([...e.excludeTools??[],...l])]);let f=!wPr.has(String(i).toLowerCase()),h=e.skipToolPromptInjection?(e.systemPrompt||"")+p:this.createToolAwareSystemPrompt(e.systemPrompt,a,f)+p;g.debug("Tool-aware system prompt created",{requestId:t,originalPromptLength:e.systemPrompt?.length||0,enhancedPromptLength:h.length,skippedToolInjection:!!e.skipToolPromptInjection,enhancedPromptPreview:h.substring(0,80)+"..."}),g.debug("[Observability] System prompt metadata",{requestId:t,systemPromptLength:h.length,systemPromptHash:h.length>0?`sha256:${h.slice(0,8)}...`:"empty",hasCustomSystemPrompt:!!e.systemPrompt});let y=await Lg(this.conversationMemory,e);return this.logMCPConversationSummary(t,y),g.debug("[Observability] Available tools for LLM",{requestId:t,toolCount:a.length,toolNames:a.map(x=>x.name)}),{providerName:i,availableTools:a,enhancedSystemPrompt:h,conversationMessages:y}}logMCPConversationSummary(e,t){if(g.shouldLog("debug"))try{g.debug("[Observability] Conversation history summary",{requestId:e,messageCount:t.length,messages:t.map((n,o)=>{let s;if(typeof n.content=="string")s=n.content.length;else try{s=JSON.stringify(n.content).length}catch{s=0}return{index:o,role:n.role,contentLength:s,contentPreview:typeof n.content=="string"?n.content.substring(0,200):"[multimodal]"}})})}catch{}}async ensureMCPGenerationBudget(e,t,n,o,s,i){let a=Qc({provider:n,model:e.model,maxTokens:e.maxTokens,systemPrompt:o,conversationMessages:i,currentPrompt:e.prompt,toolDefinitions:s});if(g.info("[TokenBudget] Token breakdown",{requestId:t,system:a.breakdown?.systemPrompt||0,history:a.breakdown?.conversationHistory||0,tools:a.breakdown?.toolDefinitions||0,currentPrompt:a.breakdown?.currentPrompt||0,files:a.breakdown?.fileAttachments||0,total:a.estimatedInputTokens,budget:a.availableInputTokens,usagePercent:Math.round(a.usageRatio*1e3)/10,conversationMessageCount:i.length,shouldCompact:a.shouldCompact}),e.timeout===void 0&&a.estimatedInputTokens>1e5){let u=1+Math.floor((a.estimatedInputTokens-1)/1e5)*.5,d=Math.round(6e4*Math.min(u,4));e.timeout=d,g.info("[TokenBudget] Scaled timeout for large context",{requestId:t,estimatedTokens:a.estimatedInputTokens,scaledTimeoutMs:d})}let c=this.getCompactionSessionId(e),l=this.lastCompactionMessageCount.get(c)??0;return!a.shouldCompact||!this.conversationMemory||i.length<=l?i:this.compactMCPConversationForBudget({options:e,requestId:t,providerName:n,enhancedSystemPrompt:o,availableTools:s,conversationMessages:i,availableInputTokens:a.availableInputTokens,usageRatio:a.usageRatio,estimatedInputTokens:a.estimatedInputTokens,compactionSessionId:c})}async compactMCPConversationForBudget(e){let{options:t,requestId:n,providerName:o,enhancedSystemPrompt:s,availableTools:i,conversationMessages:a,availableInputTokens:c,usageRatio:l,estimatedInputTokens:u,compactionSessionId:d}=e;g.info("[NeuroLink] Context budget exceeded, triggering auto-compaction",{usageRatio:l,estimatedTokens:u,availableTokens:c});let f=await new bx({provider:o,summarizationProvider:this.conversationMemoryConfig?.conversationMemory?.summarizationProvider,summarizationModel:this.conversationMemoryConfig?.conversationMemory?.summarizationModel}).compact(a,c,this.conversationMemoryConfig?.conversationMemory,n),h=a;f.compacted&&(h=Tk(f.messages).messages,this.lastCompactionMessageCount.set(d,h.length),g.info("[NeuroLink] Context compacted successfully",{stagesUsed:f.stagesUsed,tokensSaved:f.tokensSaved}));let y=Qc({provider:o,model:t.model,maxTokens:t.maxTokens,systemPrompt:s,conversationMessages:h,currentPrompt:t.prompt,toolDefinitions:i});if(y.withinBudget)return h;let x=y.usageRatio-1;g.warn("[NeuroLink] Post-compaction still over budget, attempting emergency content truncation",{requestId:n,estimatedTokens:y.estimatedInputTokens,availableTokens:y.availableInputTokens,overagePercent:Math.round(x*100),stagesUsedInCompaction:f.stagesUsed}),h=EH(h,y.availableInputTokens,y.breakdown,o);let b=Qc({provider:o,model:t.model,maxTokens:t.maxTokens,systemPrompt:s,conversationMessages:h,currentPrompt:t.prompt,toolDefinitions:i});if(!b.withinBudget)throw this.lastCompactionMessageCount.delete(d),new Hl(`Context exceeds model budget after all compaction stages. Estimated: ${b.estimatedInputTokens} tokens, Budget: ${b.availableInputTokens} tokens. Conversation is too large to fit in the model's context window.`,{estimatedTokens:b.estimatedInputTokens,availableTokens:b.availableInputTokens,stagesUsed:f.stagesUsed,breakdown:b.breakdown});return h}async generateWithMCPProvider(e){let{options:t,requestId:n,functionTag:o,tryMCPStartTime:s,providerName:i,availableTools:a,enhancedSystemPrompt:c,conversationMessages:l}=e,u=await dn.createProvider(i,t.model,!t.disableTools,this,t.region,this.resolveCredentials(t.credentials));u.setTraceContext(this._metricsTraceContext),this.emitter.emit("connected"),this.emitter.emit("message",`${i} provider initialized successfully`),u.setupToolExecutor({customTools:this.getCustomTools(),executeTool:(x,b)=>this.executeTool(x,b,{disableToolCache:t.disableToolCache})},o),g.debug("[Observability] User input to LLM",{requestId:n,promptPreview:t.prompt?.substring(0,200),promptLength:t.prompt?.length||0,model:t.model,maxTokens:t.maxTokens,temperature:t.temperature,maxSteps:t.maxSteps,skipToolPromptInjection:t.skipToolPromptInjection});let d=await u.generate({...t,systemPrompt:c,conversationMessages:l}),p=Date.now()-s,f=!!(d?.content&&d.content.trim().length>0),h=!!(d?.toolExecutions&&d.toolExecutions.length>0);if(ie.debug(`[${o}] Result validation:`,{hasResult:!!d,hasContent:f,hasToolExecutions:h,contentLength:d?.content?.length||0,toolExecutionsCount:d?.toolExecutions?.length||0,toolsUsedCount:d?.toolsUsed?.length||0}),!f&&!h)return ie.debug(`[${o}] Result rejected: no content and no tool executions`),null;let y=aMe(d.toolExecutions);return ie.debug(`[${o}] Tool execution transformation:`,{originalCount:d?.toolExecutions?.length||0,transformedCount:y.length,transformedTools:y.map(x=>x.toolName)}),{content:d.content||"",provider:i,model:d.model,usage:d.usage,responseTime:p,finishReason:d.finishReason,stopReason:d.stopReason,rawFinishReason:d.rawFinishReason,stepsUsed:d.stepsUsed,toolsUsed:d.toolsUsed||[],toolExecutions:y,enhancedWithTools:!!h,availableTools:lMe(uMe(a)),audio:d.audio,video:d.video,avatar:d.avatar,music:d.music,ppt:d.ppt,imageOutput:d.imageOutput,analytics:d.analytics,evaluation:d.evaluation,reasoning:d.reasoning,reasoningTokens:d.reasoningTokens,_generationEndEmitted:d._generationEndEmitted}}async directProviderGeneration(e){let t=Date.now(),n="NeuroLink.directProviderGeneration",o=["openai","vertex","bedrock","anthropic","azure","google-ai","huggingface","ollama"],s=e.provider==="auto"?void 0:e.provider,i=e.context&&typeof e.context=="object"&&"__orchestratedPreferredProvider"in e.context?e.context.__orchestratedPreferredProvider:void 0,a=i?[i,...o.filter(u=>u!==i)]:s?[s]:o;if(g.debug(`[${n}] Starting direct generation`,{requestedProvider:s||"auto",preferredOrchestrated:i||"none",tryProviders:a,allowFallback:!s||!!i}),this.modelPool){let u=this.modelPool,d=u.maxAttempts,p=new Set,f=null;for(let y=0;y<d;y++){if(e.abortSignal?.aborted)throw new DOMException("The operation was aborted","AbortError");let x=u.selectNext(p);if(!x)break;p.add(u.memberKey(x));let b=e.provider,T=e.model,S=e.region;e.provider=x.provider,e.model=x.model??void 0,e.region=x.region??void 0;let _=x.provider;g.debug(`[${n}] ModelPool: attempting member`,{provider:_,model:x.model??e.model,attempt:y});try{let C=e,R=C.conversationMessages?.length?C.conversationMessages:await Lg(this.conversationMemory,e),P=await dn.createProvider(_,e.model,!e.disableTools,this,e.region,this.resolveCredentials(e.credentials));P.setTraceContext(this._metricsTraceContext),P.setupToolExecutor({customTools:this.getCustomTools(),executeTool:(M,D)=>this.executeTool(M,D,{disableToolCache:e.disableToolCache})},n);let A=await P.generate({...e,conversationMessages:R});if(!A)throw new Error(`ModelPool: provider ${_} returned null result`);u.recordSuccess(x);let I=Date.now()-t;return e.provider=b,e.model=T,e.region=S,{content:A.content||"",provider:_,model:A.model,usage:A.usage,responseTime:I,finishReason:A.finishReason,stopReason:A.stopReason,rawFinishReason:A.rawFinishReason,stepsUsed:A.stepsUsed,toolsUsed:A.toolsUsed||[],toolExecutions:A.toolExecutions?.map(M=>{let D=M;return{...M,toolName:M.name,executionTime:typeof D.executionTime=="number"?D.executionTime:typeof D.duration=="number"?D.duration:0,success:typeof D.success=="boolean"?D.success:D.status==="success"}}),enhancedWithTools:!!A.toolExecutions?.length,analytics:A.analytics,evaluation:A.evaluation,audio:A.audio,video:A.video,avatar:A.avatar,music:A.music,ppt:A.ppt,imageOutput:A.imageOutput,reasoning:A.reasoning,reasoningTokens:A.reasoningTokens,_generationEndEmitted:A._generationEndEmitted}}catch(C){if(e.provider=b,e.model=T,e.region=S,Hr(C))throw C;if(qW(C)){let R=C instanceof Error?C.message:String(C);throw g.warn(`[${n}] ModelPool: non-retryable error from ${_}, stopping pool`,{error:R}),u.recordFailure(x,Ux(C)),new Error(`[ModelPool] non-retryable: ${R}`,{cause:C})}u.recordFailure(x,Ux(C)),f=C instanceof Error?C:new Error(String(C)),g.warn(`[${n}] ModelPool: member ${_} failed`,{error:f.message})}}let h=Date.now()-t;throw g.error(`[${n}] ModelPool: all members failed`,{triedKeys:Array.from(p),lastError:f?.message,responseTime:h}),new Error(`[ModelPool] all members failed: ${f?.message??"no members available"}`)}let c=null;for(let u of a){if(e.abortSignal?.aborted)throw new DOMException("The operation was aborted","AbortError");try{g.debug(`[${n}] Attempting provider: ${u}`);let d=e,p=d.conversationMessages?.length?d.conversationMessages:await Lg(this.conversationMemory,e),f=Qc({provider:u,model:e.model,maxTokens:e.maxTokens,systemPrompt:e.systemPrompt,conversationMessages:p,currentPrompt:e.prompt,toolDefinitions:e.tools?Object.values(e.tools):void 0}),h=p?.length||0,y=this.getCompactionSessionId(e),x=!!d.conversationMessages?.length,b=h>0;if(!f.withinBudget&&!b){try{this.emitter.emit("compaction.insufficient",{stagesAttempted:["pre-dispatch hard cap"],finalTokens:f.estimatedInputTokens,budget:f.availableInputTokens,provider:u,model:e.model,phase:"pre-dispatch-no-recovery",timestamp:Date.now()})}catch{}throw new Hl(`Context exceeds model budget and no compaction is possible (no conversationMemory, no inline conversationMessages \u2014 only prompt + tools). Estimated: ${f.estimatedInputTokens} tokens, budget: ${f.availableInputTokens} tokens. Reduce prompt or tool-definition size, or trim the request.`,{estimatedTokens:f.estimatedInputTokens,availableTokens:f.availableInputTokens,stagesUsed:[],breakdown:f.breakdown})}if(f.shouldCompact&&(this.conversationMemory||x)&&h>(this.lastCompactionMessageCount.get(y)??0)){let R=await new bx({provider:u,summarizationProvider:this.conversationMemoryConfig?.conversationMemory?.summarizationProvider,summarizationModel:this.conversationMemoryConfig?.conversationMemory?.summarizationModel}).compact(p,f.availableInputTokens,this.conversationMemoryConfig?.conversationMemory,e.context?.requestId);R.compacted&&(p=Tk(R.messages).messages,this.lastCompactionMessageCount.set(y,p.length));let P=Qc({provider:u,model:e.model,maxTokens:e.maxTokens,systemPrompt:e.systemPrompt,conversationMessages:p,currentPrompt:e.prompt,toolDefinitions:e.tools?Object.values(e.tools):void 0});if(!P.withinBudget){g.warn("[NeuroLink] directProviderGeneration: post-compaction still over budget, emergency truncation",{estimatedTokens:P.estimatedInputTokens,availableTokens:P.availableInputTokens,overagePercent:Math.round((P.usageRatio-1)*100)});try{this.emitter.emit("compaction.insufficient",{stagesAttempted:R.stagesUsed,finalTokens:P.estimatedInputTokens,budget:P.availableInputTokens,provider:u,model:e.model,phase:"mid-compaction",willEmergencyTruncate:!0,timestamp:Date.now()})}catch{}p=EH(p,P.availableInputTokens,P.breakdown,u);let A=Qc({provider:u,model:e.model,maxTokens:e.maxTokens,systemPrompt:e.systemPrompt,conversationMessages:p,currentPrompt:e.prompt,toolDefinitions:e.tools?Object.values(e.tools):void 0});if(!A.withinBudget){this.lastCompactionMessageCount.delete(y);try{this.emitter.emit("compaction.insufficient",{stagesAttempted:R.stagesUsed,finalTokens:A.estimatedInputTokens,budget:A.availableInputTokens,provider:u,model:e.model,phase:"post-emergency-truncation",timestamp:Date.now()})}catch{}throw new Hl(`Context exceeds model budget after all compaction stages. Estimated: ${A.estimatedInputTokens} tokens, Budget: ${A.availableInputTokens} tokens.`,{estimatedTokens:A.estimatedInputTokens,availableTokens:A.availableInputTokens,stagesUsed:R.stagesUsed,breakdown:A.breakdown})}}}let T=await dn.createProvider(u,e.model,!e.disableTools,this,e.region,this.resolveCredentials(e.credentials));T.setTraceContext(this._metricsTraceContext),this.emitter.emit("connected"),this.emitter.emit("message",`${u} provider initialized successfully`),T.setupToolExecutor({customTools:this.getCustomTools(),executeTool:(C,R)=>this.executeTool(C,R,{disableToolCache:e.disableToolCache})},n);let S=await T.generate({...e,conversationMessages:p}),_=Date.now()-t;if(!S)throw new Error(`Provider ${u} returned null result`);return g.debug(`[${n}] Provider ${u} succeeded`,{responseTime:_,contentLength:S.content?.length||0}),{content:S.content||"",provider:u,model:S.model,usage:S.usage,responseTime:_,finishReason:S.finishReason,stopReason:S.stopReason,rawFinishReason:S.rawFinishReason,stepsUsed:S.stepsUsed,toolsUsed:S.toolsUsed||[],toolExecutions:S.toolExecutions?.map(C=>{let R=C;return{...C,toolName:C.name,executionTime:typeof R.executionTime=="number"?R.executionTime:typeof R.duration=="number"?R.duration:0,success:typeof R.success=="boolean"?R.success:R.status==="success"}}),enhancedWithTools:!!S.toolExecutions?.length,analytics:S.analytics,evaluation:S.evaluation,audio:S.audio,video:S.video,avatar:S.avatar,music:S.music,ppt:S.ppt,imageOutput:S.imageOutput,reasoning:S.reasoning,reasoningTokens:S.reasoningTokens,_generationEndEmitted:S._generationEndEmitted}}catch(d){if(Hr(d))throw g.debug(`[${n}] AbortError detected on provider ${u}, stopping fallback`),d;if(qW(d))throw g.warn(`[${n}] Non-retryable error from provider ${u}, stopping fallback chain`,{error:d instanceof Error?d.message:String(d),errorType:d instanceof Error?d.constructor.name:typeof d}),d instanceof Error?d:new Error(String(d));c=d instanceof Error?d:new Error(String(d)),g.warn(`[${n}] Provider ${u} failed`,{error:c.message})}}let l=Date.now()-t;throw g.error(`[${n}] All providers failed`,{triedProviders:a,lastError:c?.message,responseTime:l}),c instanceof Hl?c:new Error(`Failed to generate text with all providers. Last error: ${c?.message||"Unknown error"}`)}applyToolInfoFiltering(e,t){let n=lj({options:{disableTools:t.disableTools,toolFilter:t.toolFilter,enabledToolNames:t.enabledToolNames,excludeTools:t.excludeTools},instanceConfig:this.toolsConfig,builtinToolNames:Object.keys(dm)}),o={};for(let a of e)a.name in o||(o[a.name]=a);let s=dj(o,n),i=e.filter(a=>a.name in s);return i.length!==e.length&&g.debug("Tool info filtering applied for system prompt",{beforeCount:e.length,afterCount:i.length,policySources:n.sources,toolFilter:t.toolFilter,excludeTools:t.excludeTools}),i}createToolAwareSystemPrompt(e,t,n){let o={originalPromptLength:e?.length||0,availableToolsCount:t.length,hasOriginalPrompt:!!e,nativeToolSupport:n};if(g.debug("AI prompt generation with tool schemas",o),t.length===0)return g.debug("No tools available - returning original prompt"),e||"";if(n)return(e||"")+`
2204
+ NOTE: The following tools are temporarily unavailable due to repeated failures: ${l.join(", ")}. Do not attempt to call these tools.`:"";l.length>0&&(e.excludeTools=[...new Set([...e.excludeTools??[],...l])]);let f=!wPr.has(String(i).toLowerCase()),h=e.skipToolPromptInjection?(e.systemPrompt||"")+p:this.createToolAwareSystemPrompt(e.systemPrompt,a,f)+p;g.debug("Tool-aware system prompt created",{requestId:t,originalPromptLength:e.systemPrompt?.length||0,enhancedPromptLength:h.length,skippedToolInjection:!!e.skipToolPromptInjection,enhancedPromptPreview:h.substring(0,80)+"..."}),g.debug("[Observability] System prompt metadata",{requestId:t,systemPromptLength:h.length,systemPromptHash:h.length>0?`sha256:${h.slice(0,8)}...`:"empty",hasCustomSystemPrompt:!!e.systemPrompt});let y=await Lg(this.conversationMemory,e);return this.logMCPConversationSummary(t,y),g.debug("[Observability] Available tools for LLM",{requestId:t,toolCount:a.length,toolNames:a.map(x=>x.name)}),{providerName:i,availableTools:a,enhancedSystemPrompt:h,conversationMessages:y}}logMCPConversationSummary(e,t){if(g.shouldLog("debug"))try{g.debug("[Observability] Conversation history summary",{requestId:e,messageCount:t.length,messages:t.map((n,o)=>{let s;if(typeof n.content=="string")s=n.content.length;else try{s=JSON.stringify(n.content).length}catch{s=0}return{index:o,role:n.role,contentLength:s,contentPreview:typeof n.content=="string"?n.content.substring(0,200):"[multimodal]"}})})}catch{}}async ensureMCPGenerationBudget(e,t,n,o,s,i){let a=Qc({provider:n,model:e.model,maxTokens:e.maxTokens,systemPrompt:o,conversationMessages:i,currentPrompt:e.prompt,toolDefinitions:s});if(g.info("[TokenBudget] Token breakdown",{requestId:t,system:a.breakdown?.systemPrompt||0,history:a.breakdown?.conversationHistory||0,tools:a.breakdown?.toolDefinitions||0,currentPrompt:a.breakdown?.currentPrompt||0,files:a.breakdown?.fileAttachments||0,total:a.estimatedInputTokens,budget:a.availableInputTokens,usagePercent:Math.round(a.usageRatio*1e3)/10,conversationMessageCount:i.length,shouldCompact:a.shouldCompact}),e.timeout===void 0&&a.estimatedInputTokens>1e5){let u=1+Math.floor((a.estimatedInputTokens-1)/1e5)*.5,d=Math.round(6e4*Math.min(u,4));e.timeout=d,g.info("[TokenBudget] Scaled timeout for large context",{requestId:t,estimatedTokens:a.estimatedInputTokens,scaledTimeoutMs:d})}let c=this.getCompactionSessionId(e),l=this.lastCompactionMessageCount.get(c)??0;return!a.shouldCompact||!this.conversationMemory||i.length<=l?i:this.compactMCPConversationForBudget({options:e,requestId:t,providerName:n,enhancedSystemPrompt:o,availableTools:s,conversationMessages:i,availableInputTokens:a.availableInputTokens,usageRatio:a.usageRatio,estimatedInputTokens:a.estimatedInputTokens,compactionSessionId:c})}async compactMCPConversationForBudget(e){let{options:t,requestId:n,providerName:o,enhancedSystemPrompt:s,availableTools:i,conversationMessages:a,availableInputTokens:c,usageRatio:l,estimatedInputTokens:u,compactionSessionId:d}=e;g.info("[NeuroLink] Context budget exceeded, triggering auto-compaction",{usageRatio:l,estimatedTokens:u,availableTokens:c});let f=await new bx({provider:o,summarizationProvider:this.conversationMemoryConfig?.conversationMemory?.summarizationProvider,summarizationModel:this.conversationMemoryConfig?.conversationMemory?.summarizationModel}).compact(a,c,this.conversationMemoryConfig?.conversationMemory,n),h=a;f.compacted&&(h=Tk(f.messages).messages,this.lastCompactionMessageCount.set(d,h.length),g.info("[NeuroLink] Context compacted successfully",{stagesUsed:f.stagesUsed,tokensSaved:f.tokensSaved}));let y=Qc({provider:o,model:t.model,maxTokens:t.maxTokens,systemPrompt:s,conversationMessages:h,currentPrompt:t.prompt,toolDefinitions:i});if(y.withinBudget)return h;let x=y.usageRatio-1;g.warn("[NeuroLink] Post-compaction still over budget, attempting emergency content truncation",{requestId:n,estimatedTokens:y.estimatedInputTokens,availableTokens:y.availableInputTokens,overagePercent:Math.round(x*100),stagesUsedInCompaction:f.stagesUsed}),h=EH(h,y.availableInputTokens,y.breakdown,o);let b=Qc({provider:o,model:t.model,maxTokens:t.maxTokens,systemPrompt:s,conversationMessages:h,currentPrompt:t.prompt,toolDefinitions:i});if(!b.withinBudget)throw this.lastCompactionMessageCount.delete(d),new Hl(`Context exceeds model budget after all compaction stages. Estimated: ${b.estimatedInputTokens} tokens, Budget: ${b.availableInputTokens} tokens. Conversation is too large to fit in the model's context window.`,{estimatedTokens:b.estimatedInputTokens,availableTokens:b.availableInputTokens,stagesUsed:f.stagesUsed,breakdown:b.breakdown});return h}async generateWithMCPProvider(e){let{options:t,requestId:n,functionTag:o,tryMCPStartTime:s,providerName:i,availableTools:a,enhancedSystemPrompt:c,conversationMessages:l}=e,u=await dn.createProvider(i,t.model,!t.disableTools,this,t.region,this.resolveCredentials(t.credentials));u.setTraceContext(this._metricsTraceContext),this.emitter.emit("connected"),this.emitter.emit("message",`${i} provider initialized successfully`),u.setupToolExecutor({customTools:this.getCustomTools(),executeTool:(x,b)=>this.executeTool(x,b,{disableToolCache:t.disableToolCache})},o),g.debug("[Observability] User input to LLM",{requestId:n,promptPreview:t.prompt?.substring(0,200),promptLength:t.prompt?.length||0,model:t.model,maxTokens:t.maxTokens,temperature:t.temperature,maxSteps:t.maxSteps,skipToolPromptInjection:t.skipToolPromptInjection});let d=await u.generate({...t,systemPrompt:c,conversationMessages:l}),p=Date.now()-s,f=!!(d?.content&&d.content.trim().length>0),h=!!(d?.toolExecutions&&d.toolExecutions.length>0);if(ie.debug(`[${o}] Result validation:`,{hasResult:!!d,hasContent:f,hasToolExecutions:h,contentLength:d?.content?.length||0,toolExecutionsCount:d?.toolExecutions?.length||0,toolsUsedCount:d?.toolsUsed?.length||0}),!f&&!h)return ie.debug(`[${o}] Result rejected: no content and no tool executions`),null;let y=aMe(d.toolExecutions);return ie.debug(`[${o}] Tool execution transformation:`,{originalCount:d?.toolExecutions?.length||0,transformedCount:y.length,transformedTools:y.map(x=>x.toolName)}),{content:d.content||"",provider:i,model:d.model,usage:d.usage,responseTime:p,finishReason:d.finishReason,stopReason:d.stopReason,rawFinishReason:d.rawFinishReason,stepsUsed:d.stepsUsed,toolsUsed:d.toolsUsed||[],toolExecutions:y,enhancedWithTools:!!h,availableTools:lMe(uMe(a)),audio:d.audio,video:d.video,avatar:d.avatar,music:d.music,ppt:d.ppt,imageOutput:d.imageOutput,analytics:d.analytics,evaluation:d.evaluation,reasoning:d.reasoning,reasoningTokens:d.reasoningTokens,_generationEndEmitted:d._generationEndEmitted}}async directProviderGeneration(e){let t=Date.now(),n="NeuroLink.directProviderGeneration",o=["openai","vertex","bedrock","anthropic","azure","google-ai","huggingface","ollama"],s=e.provider==="auto"?void 0:e.provider,i=e.context&&typeof e.context=="object"&&"__orchestratedPreferredProvider"in e.context?e.context.__orchestratedPreferredProvider:void 0,a=i?[i,...o.filter(u=>u!==i)]:s?[s]:o;if(g.debug(`[${n}] Starting direct generation`,{requestedProvider:s||"auto",preferredOrchestrated:i||"none",tryProviders:a,allowFallback:!s||!!i}),this.modelPool){let u=this.modelPool,d=u.maxAttempts,p=new Set,f=null;for(let y=0;y<d;y++){if(e.abortSignal?.aborted)throw new DOMException("The operation was aborted","AbortError");let x=u.selectNext(p);if(!x)break;p.add(u.memberKey(x));let b=e.provider,T=e.model,S=e.region;e.provider=x.provider,e.model=x.model??void 0,e.region=x.region??void 0;let _=x.provider;g.debug(`[${n}] ModelPool: attempting member`,{provider:_,model:x.model??e.model,attempt:y});try{let C=e,R=C.conversationMessages?.length?C.conversationMessages:await Lg(this.conversationMemory,e),P=await dn.createProvider(_,e.model,!e.disableTools,this,e.region,this.resolveCredentials(e.credentials));P.setTraceContext(this._metricsTraceContext),P.setupToolExecutor({customTools:this.getCustomTools(),executeTool:(M,D)=>this.executeTool(M,D,{disableToolCache:e.disableToolCache})},n);let A=await P.generate({...e,conversationMessages:R});if(!A)throw new Error(`ModelPool: provider ${_} returned null result`);u.recordSuccess(x);let I=Date.now()-t;return e.provider=b,e.model=T,e.region=S,{content:A.content||"",provider:_,model:A.model,usage:A.usage,responseTime:I,finishReason:A.finishReason,stopReason:A.stopReason,rawFinishReason:A.rawFinishReason,stepsUsed:A.stepsUsed,toolsUsed:A.toolsUsed||[],toolExecutions:A.toolExecutions?.map(M=>{let D=M;return{...M,toolName:M.name,executionTime:typeof D.executionTime=="number"?D.executionTime:typeof D.duration=="number"?D.duration:0,success:typeof D.success=="boolean"?D.success:D.status==="success"}}),enhancedWithTools:!!A.toolExecutions?.length,analytics:A.analytics,evaluation:A.evaluation,audio:A.audio,video:A.video,avatar:A.avatar,music:A.music,ppt:A.ppt,imageOutput:A.imageOutput,reasoning:A.reasoning,reasoningTokens:A.reasoningTokens,_generationEndEmitted:A._generationEndEmitted}}catch(C){if(e.provider=b,e.model=T,e.region=S,Hr(C))throw C;if(qW(C)){let R=C instanceof Error?C.message:String(C);throw g.warn(`[${n}] ModelPool: non-retryable error from ${_}, stopping pool`,{error:R}),u.recordFailure(x,Ux(C)),new Error(`[ModelPool] non-retryable: ${R}`,{cause:C})}u.recordFailure(x,Ux(C)),f=C instanceof Error?C:new Error(String(C)),g.warn(`[${n}] ModelPool: member ${_} failed`,{error:f.message})}}let h=Date.now()-t;throw g.error(`[${n}] ModelPool: all members failed`,{triedKeys:Array.from(p),lastError:f?.message,responseTime:h}),new Error(`[ModelPool] all members failed: ${f?.message??"no members available"}`)}let c=null;for(let u of a){if(e.abortSignal?.aborted)throw new DOMException("The operation was aborted","AbortError");try{g.debug(`[${n}] Attempting provider: ${u}`);let d=e,p=d.conversationMessages?.length?d.conversationMessages:await Lg(this.conversationMemory,e),f=Qc({provider:u,model:e.model,maxTokens:e.maxTokens,systemPrompt:e.systemPrompt,conversationMessages:p,currentPrompt:e.prompt,toolDefinitions:e.tools?Object.values(e.tools):void 0}),h=p?.length||0,y=this.getCompactionSessionId(e),x=!!d.conversationMessages?.length,b=h>0;if(!f.withinBudget&&!b){try{this.emitter.emit("compaction.insufficient",{stagesAttempted:["pre-dispatch hard cap"],finalTokens:f.estimatedInputTokens,budget:f.availableInputTokens,provider:u,model:e.model,phase:"pre-dispatch-no-recovery",timestamp:Date.now()})}catch{}throw new Hl(`Context exceeds model budget and no compaction is possible (no conversationMemory, no inline conversationMessages \u2014 only prompt + tools). Estimated: ${f.estimatedInputTokens} tokens, budget: ${f.availableInputTokens} tokens. Reduce prompt or tool-definition size, or trim the request.`,{estimatedTokens:f.estimatedInputTokens,availableTokens:f.availableInputTokens,stagesUsed:[],breakdown:f.breakdown})}if(f.shouldCompact&&(this.conversationMemory||x)&&h>(this.lastCompactionMessageCount.get(y)??0)){let R=await new bx({provider:u,summarizationProvider:this.conversationMemoryConfig?.conversationMemory?.summarizationProvider,summarizationModel:this.conversationMemoryConfig?.conversationMemory?.summarizationModel}).compact(p,f.availableInputTokens,this.conversationMemoryConfig?.conversationMemory,e.context?.requestId);R.compacted&&(p=Tk(R.messages).messages,this.lastCompactionMessageCount.set(y,p.length));let P=Qc({provider:u,model:e.model,maxTokens:e.maxTokens,systemPrompt:e.systemPrompt,conversationMessages:p,currentPrompt:e.prompt,toolDefinitions:e.tools?Object.values(e.tools):void 0});if(!P.withinBudget){g.warn("[NeuroLink] directProviderGeneration: post-compaction still over budget, emergency truncation",{estimatedTokens:P.estimatedInputTokens,availableTokens:P.availableInputTokens,overagePercent:Math.round((P.usageRatio-1)*100)});try{this.emitter.emit("compaction.insufficient",{stagesAttempted:R.stagesUsed,finalTokens:P.estimatedInputTokens,budget:P.availableInputTokens,provider:u,model:e.model,phase:"mid-compaction",willEmergencyTruncate:!0,timestamp:Date.now()})}catch{}p=EH(p,P.availableInputTokens,P.breakdown,u);let A=Qc({provider:u,model:e.model,maxTokens:e.maxTokens,systemPrompt:e.systemPrompt,conversationMessages:p,currentPrompt:e.prompt,toolDefinitions:e.tools?Object.values(e.tools):void 0});if(!A.withinBudget){this.lastCompactionMessageCount.delete(y);try{this.emitter.emit("compaction.insufficient",{stagesAttempted:R.stagesUsed,finalTokens:A.estimatedInputTokens,budget:A.availableInputTokens,provider:u,model:e.model,phase:"post-emergency-truncation",timestamp:Date.now()})}catch{}throw new Hl(`Context exceeds model budget after all compaction stages. Estimated: ${A.estimatedInputTokens} tokens, Budget: ${A.availableInputTokens} tokens.`,{estimatedTokens:A.estimatedInputTokens,availableTokens:A.availableInputTokens,stagesUsed:R.stagesUsed,breakdown:A.breakdown})}}}let T=await dn.createProvider(u,e.model,!e.disableTools,this,e.region,this.resolveCredentials(e.credentials));T.setTraceContext(this._metricsTraceContext),this.emitter.emit("connected"),this.emitter.emit("message",`${u} provider initialized successfully`),T.setupToolExecutor({customTools:this.getCustomTools(),executeTool:(C,R)=>this.executeTool(C,R,{disableToolCache:e.disableToolCache})},n);let S=await T.generate({...e,conversationMessages:p}),_=Date.now()-t;if(!S)throw new Error(`Provider ${u} returned null result`);return g.debug(`[${n}] Provider ${u} succeeded`,{responseTime:_,contentLength:S.content?.length||0}),{content:S.content||"",provider:u,model:S.model,usage:S.usage,responseTime:_,finishReason:S.finishReason,stopReason:S.stopReason,rawFinishReason:S.rawFinishReason,stepsUsed:S.stepsUsed,toolsUsed:S.toolsUsed||[],toolExecutions:S.toolExecutions?.map(C=>{let R=C;return{...C,toolName:C.name,executionTime:typeof R.executionTime=="number"?R.executionTime:typeof R.duration=="number"?R.duration:0,success:typeof R.success=="boolean"?R.success:R.status==="success"}}),enhancedWithTools:!!S.toolExecutions?.length,analytics:S.analytics,evaluation:S.evaluation,audio:S.audio,video:S.video,avatar:S.avatar,music:S.music,ppt:S.ppt,imageOutput:S.imageOutput,reasoning:S.reasoning,reasoningTokens:S.reasoningTokens,_generationEndEmitted:S._generationEndEmitted}}catch(d){if(Hr(d))throw g.debug(`[${n}] AbortError detected on provider ${u}, stopping fallback`),d;if(qW(d))throw g.warn(`[${n}] Non-retryable error from provider ${u}, stopping fallback chain`,{error:d instanceof Error?d.message:String(d),errorType:d instanceof Error?d.constructor.name:typeof d}),d instanceof Error?d:new Error(String(d));c=d instanceof Error?d:new Error(String(d)),g.warn(`[${n}] Provider ${u} failed`,{error:c.message})}}let l=Date.now()-t;throw g.error(`[${n}] All providers failed`,{triedProviders:a,lastError:c?.message,responseTime:l}),c instanceof Hl?c:new Error(`Failed to generate text with all providers. Last error: ${c?.message||"Unknown error"}`)}applyToolInfoFiltering(e,t){let n=lj({options:{disableTools:t.disableTools,toolFilter:t.toolFilter,enabledToolNames:t.enabledToolNames,excludeTools:t.excludeTools},instanceConfig:this.toolsConfig,builtinToolNames:Object.keys(dm)}),o=Object.create(null);for(let a of e)Object.hasOwn(o,a.name)||(o[a.name]=a);let s=dj(o,n),i=e.filter(a=>Object.hasOwn(s,a.name));return i.length!==e.length&&g.debug("Tool info filtering applied for system prompt",{beforeCount:e.length,afterCount:i.length,policySources:n.sources,toolFilter:t.toolFilter,excludeTools:t.excludeTools}),i}createToolAwareSystemPrompt(e,t,n){let o={originalPromptLength:e?.length||0,availableToolsCount:t.length,hasOriginalPrompt:!!e,nativeToolSupport:n};if(g.debug("AI prompt generation with tool schemas",o),t.length===0)return g.debug("No tools available - returning original prompt"),e||"";if(n)return(e||"")+`
2205
2205
 
2206
2206
  Tools are available via native tool calling. Use them only when they genuinely improve your response; for creative or conversational requests, respond naturally without tools.`;let s=pMe(t.map(u=>({name:u.name,description:u.description??"",server:u.serverId??"unknown",inputSchema:u.inputSchema}))),i={toolDescriptionsLength:s.length,toolDescriptionsCharCount:s.length,hasDescriptions:s.length>0};g.debug("Tool descriptions transformation completed",i);let a=`
2207
2207
 
@@ -550,6 +550,11 @@ export class BaseProvider {
550
550
  getToolPolicy(options) {
551
551
  return resolveToolPolicy({
552
552
  options: {
553
+ // Defense-in-depth: both current call sites already zero the tool
554
+ // record via shouldUseTools before the gate runs, but forwarding
555
+ // disableTools makes the gate self-sufficient for any future call
556
+ // site that forgets the upstream check.
557
+ disableTools: options.disableTools,
553
558
  toolFilter: options.toolFilter,
554
559
  excludeTools: options.excludeTools,
555
560
  enabledToolNames: options.enabledToolNames,
@@ -550,6 +550,11 @@ export class BaseProvider {
550
550
  getToolPolicy(options) {
551
551
  return resolveToolPolicy({
552
552
  options: {
553
+ // Defense-in-depth: both current call sites already zero the tool
554
+ // record via shouldUseTools before the gate runs, but forwarding
555
+ // disableTools makes the gate self-sufficient for any future call
556
+ // site that forgets the upstream check.
557
+ disableTools: options.disableTools,
553
558
  toolFilter: options.toolFilter,
554
559
  excludeTools: options.excludeTools,
555
560
  enabledToolNames: options.enabledToolNames,
@@ -5968,14 +5968,19 @@ Current user's request: ${currentInput}`;
5968
5968
  instanceConfig: this.toolsConfig,
5969
5969
  builtinToolNames: Object.keys(directAgentTools),
5970
5970
  });
5971
- const record = {};
5971
+ // Null prototype + own-property checks: a tool named "__proto__" must
5972
+ // become an own entry — with a plain `{}`, `"__proto__" in record` is
5973
+ // truthy via the prototype and the tool would be silently dropped from
5974
+ // the listing while surviving the native gate. Matches the hardening on
5975
+ // every other record in the tool-resolution pipeline.
5976
+ const record = Object.create(null);
5972
5977
  for (const tool of tools) {
5973
- if (!(tool.name in record)) {
5978
+ if (!Object.hasOwn(record, tool.name)) {
5974
5979
  record[tool.name] = tool;
5975
5980
  }
5976
5981
  }
5977
5982
  const gated = applyToolGate(record, policy);
5978
- const filtered = tools.filter((t) => t.name in gated);
5983
+ const filtered = tools.filter((t) => Object.hasOwn(gated, t.name));
5979
5984
  if (filtered.length !== tools.length) {
5980
5985
  logger.debug(`Tool info filtering applied for system prompt`, {
5981
5986
  beforeCount: tools.length,
package/dist/neurolink.js CHANGED
@@ -5968,14 +5968,19 @@ Current user's request: ${currentInput}`;
5968
5968
  instanceConfig: this.toolsConfig,
5969
5969
  builtinToolNames: Object.keys(directAgentTools),
5970
5970
  });
5971
- const record = {};
5971
+ // Null prototype + own-property checks: a tool named "__proto__" must
5972
+ // become an own entry — with a plain `{}`, `"__proto__" in record` is
5973
+ // truthy via the prototype and the tool would be silently dropped from
5974
+ // the listing while surviving the native gate. Matches the hardening on
5975
+ // every other record in the tool-resolution pipeline.
5976
+ const record = Object.create(null);
5972
5977
  for (const tool of tools) {
5973
- if (!(tool.name in record)) {
5978
+ if (!Object.hasOwn(record, tool.name)) {
5974
5979
  record[tool.name] = tool;
5975
5980
  }
5976
5981
  }
5977
5982
  const gated = applyToolGate(record, policy);
5978
- const filtered = tools.filter((t) => t.name in gated);
5983
+ const filtered = tools.filter((t) => Object.hasOwn(gated, t.name));
5979
5984
  if (filtered.length !== tools.length) {
5980
5985
  logger.debug(`Tool info filtering applied for system prompt`, {
5981
5986
  beforeCount: tools.length,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@juspay/neurolink",
3
- "version": "9.92.0",
3
+ "version": "9.92.1",
4
4
  "packageManager": "pnpm@10.15.1",
5
5
  "description": "TypeScript AI SDK with 24+ LLM providers behind one consistent API. MCP-native (connect any MCP server), voice TTS/STT/realtime, RAG, agents, memory, context compaction. OpenAI · Anthropic · Gemini · Bedrock · Azure · Ollama · DeepSeek · NVIDIA NIM and more.",
6
6
  "author": {