@juspay/neurolink 10.10.10 → 10.10.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,3 +1,9 @@
1
+ ## [10.10.11](https://github.com/juspay/neurolink/compare/v10.10.10...v10.10.11) (2026-08-08)
2
+
3
+ ### Bug Fixes
4
+
5
+ - **(tts):** stop downgrading OpenAI flac requests to mp3 ([65aba26](https://github.com/juspay/neurolink/commit/65aba267d4997614925978f02f817e50eed5abc7)), closes [#479](https://github.com/juspay/neurolink/issues/479)
6
+
1
7
  ## [10.10.10](https://github.com/juspay/neurolink/compare/v10.10.9...v10.10.10) (2026-08-07)
2
8
 
3
9
  ### Bug Fixes
@@ -2155,7 +2155,7 @@ ${t}`:t}async retrieveKnowledgeGrounding(e){let t=this.knowledgeGroundingEngine;
2155
2155
 
2156
2156
  IMPORTANT: You have a tool called "${c.toolName}" that searches through`,`${c.filesLoaded} loaded document(s) containing ${c.chunksIndexed} indexed chunks.`,`ALWAYS use the "${c.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(" ");e.systemPrompt=(e.systemPrompt||"")+l,g.info("[RAG] Tool injected into stream()",{toolName:c.toolName,filesLoaded:c.filesLoaded,chunksIndexed:c.chunksIndexed})}catch(a){g.warn("[RAG] Failed to prepare RAG tool, continuing without RAG",{error:a instanceof Error?a.message:String(a)})}let s=tKe(e),i=rKe(e);if(e.input?.text){let{toolResults:a,enhancedPrompt:c}=await this.detectAndExecuteTools(e.input.text,void 0);c!==e.input.text&&(i.input.text=c)}return{enhancedOptions:i,factoryResult:s}}async autoDisableOllamaStreamTools(e){if((e.provider==="ollama"||e.provider?.toLowerCase().includes("ollama"))&&!e.disableTools){let{ModelConfigurationManager:t}=await Promise.resolve().then(()=>(uh(),nNe)),s=t.getInstance().getProviderConfiguration("ollama")?.modelBehavior?.toolCapableModels||[],i=e.model;s.length>0&&i&&(s.some(c=>i.toLowerCase().includes(c.toLowerCase()))||(e.disableTools=!0,g.debug("Auto-disabled tools for Ollama model that doesn't support them (stream)",{model:e.model,toolCapableModels:s.slice(0,3)})))}}setupStreamEventListeners(){let e=[],t=0,n=(p,m)=>{e.push({type:p,seq:t++,timestamp:Date.now(),...m&&typeof m=="object"?m:{data:m}})},o=(...p)=>{let m=p[0];n("response:chunk",{content:m})},s=(...p)=>{let m=p[0];n("tool:start",{...m,toolName:m.toolName??m.tool})},i=(...p)=>{let m=p[0],f=m.toolName??m.tool,h=m.responseTime??m.duration,y=m.success??(m.error!==void 0?!1:void 0),v={...m,toolName:f,...h!==void 0?{responseTime:h}:{},...y!==void 0?{success:y}:{},...m.error!==void 0?{error:m.error}:{}};n("tool:end",v),v.result&&v.result.uiComponent===!0&&n("ui-component",{toolName:f,componentData:v.result,timestamp:Date.now(),...y!==void 0?{success:y}:{},...h!==void 0?{responseTime:h}:{}})},a=(...p)=>{n("ui-component",p[0])},c=(...p)=>{n("hitl:confirmation-request",p[0])},l=(...p)=>{n("hitl:confirmation-response",p[0])};return this.emitter.on("response:chunk",o),this.emitter.on("tool:start",s),this.emitter.on("tool:end",i),this.emitter.on("ui-component",a),this.emitter.on("hitl:confirmation-request",c),this.emitter.on("hitl:confirmation-response",l),{eventSequence:e,cleanup:()=>{this.emitter.off("response:chunk",o),this.emitter.off("tool:start",s),this.emitter.off("tool:end",i),this.emitter.off("ui-component",a),this.emitter.off("hitl:confirmation-request",c),this.emitter.off("hitl:confirmation-response",l)}}}async*handleStreamFallback(e,t,n,o,s,i){e.fallbackAttempted=!0;let a="Stream completed with 0 chunks (possible guardrails block)";e.error=a;try{let h=this._metricsTraceContext,y=Re.createGenerationSpan({provider:s,model:o.model||"unknown",name:`gen_ai.${s}.stream.failed`,traceId:h?.traceId,parentSpanId:h?.parentSpanId});y=Re.endSpan(y,2),y.statusMessage=a,y.durationMs=0,this.metricsAggregator.recordSpan(y),nt().recordSpan(y)}catch{}let c=o.fallbackProvider?.trim()||void 0,l=o.fallbackModel?.trim()||void 0,d=process.env.FALLBACK_PROVIDER?.trim()||void 0,p=process.env.FALLBACK_MODEL?.trim()||void 0,m=NE.getFallbackRoute(n||o.input.text||"",{provider:s,model:o.model||"gpt-4o",reasoning:"primary failed",confidence:.5},{fallbackStrategy:"auto"}),f={...m,provider:c??d??m.provider,model:l??p??m.model};g.warn("Retrying with fallback provider",{originalProvider:s,fallbackProvider:f.provider,fallbackModel:f.model,fallbackSource:c||l?"options":d||p?"env":"model_config",reason:a});try{let h=await Qr.createProvider(f.provider,f.model,!0,void 0,void 0,this.resolveCredentials(o.credentials));h.setupToolExecutor({customTools:this.getCustomTools(),executeTool:(R,k)=>this.executeTool(R,k,{disableToolCache:o.disableToolCache})},"NeuroLink.fallbackStream");let y=o.conversationMessages!==void 0?o.conversationMessages:await fg(this.conversationMemory,{prompt:o.input.text,context:o.context}),v=await h.stream({...o,model:f.model,conversationMessages:y}),b=v.toolCalls??[],S=v.toolResults??[];(b.length>0||S.length>0)&&(t.toolCalls=b,t.toolResults=S,t.finishReason=v.finishReason??t.finishReason);let w=0,C=0;for await(let R of v.stream){w++;let k=R!==null&&typeof R=="object"&&"metadata"in R&&R.metadata?.noOutput===!0,I=R&&"content"in R&&typeof R.content=="string"&&R.content.length>0,P=R!==null&&typeof R=="object"&&"type"in R&&(R.type==="audio"||R.type==="tts_audio"||R.type==="image");!k&&(I||P)&&C++,R&&"content"in R&&typeof R.content=="string"&&(i(R.content),this.emitter.emit("response:chunk",R.content)),yield R}if(C===0&&b.length===0&&S.length===0)throw new Error(`Fallback provider ${f.provider} also returned 0 real output chunks (chunkCount=${w}, sentinel-only or empty)`);e.fallbackProvider=f.provider,e.fallbackModel=f.model,e.guardrailsBlocked=!0}catch(h){let y=h instanceof Error?h.message:String(h);throw e.error=`${a}; Fallback failed: ${y}`,g.error("Fallback provider failed",{fallbackProvider:f.provider,error:y}),h}}async storeStreamConversationMemory(e){let{enhancedOptions:t,providerName:n,originalPrompt:o,accumulatedContent:s,startTime:i,eventSequence:a}=e;g.shouldLog("debug")&&g.debug("[NeuroLink.stream] Preparing to store conversation turn in memory",{options:pw(mw(t)),sessionId:t.context?.sessionId});let c=a.some(l=>l.type==="tool:start"||l.type==="tool:end");if(!s.trim()&&!c){g.warn("[NeuroLink.stream] Skipping conversation turn storage \u2014 no text content or tool activity",{sessionId:t.context?.sessionId});return}if(g.shouldLog("debug")&&g.debug("[NeuroLink.stream] Storing conversation turn in memory",{options:pw(mw(t)),sessionId:t.context?.sessionId,conversationMemoryExists:!!this.conversationMemory}),this.conversationMemory&&t.context?.sessionId){let l=t.context?.sessionId,d=t.context?.userId,p;t.model&&(p={provider:n,model:t.model});let m=Date.now();try{let f=this.drainPendingSkillMessages(l);await this.conversationMemory.storeConversationTurn({sessionId:l,userId:d,userMessage:o??"",aiResponse:s,startTimeStamp:new Date(i),providerDetails:p,enableSummarization:t.enableSummarization,events:a.length>0?a:void 0,requestId:t.context?.requestId,...f.length>0?{skillMessages:f}:{}}),this.recordMemorySpan("memory.store",{"memory.operation":"store","memory.path":"stream"},Date.now()-m,1),g.debug("[NeuroLink.stream] Stored conversation turn with events",{sessionId:l,eventCount:a.length,eventTypes:[...new Set(a.map(h=>h.type))]})}catch(f){this.recordMemorySpan("memory.store",{"memory.operation":"store","memory.path":"stream"},Date.now()-m,2,f instanceof Error?f.message:String(f)),g.warn("Failed to store stream conversation turn",{error:f instanceof Error?f.message:String(f)})}}this.shouldWriteMemory(t.memory,t.context?.userId,s)&&this.storeMemoryInBackground(o??"",s.trim(),t.context?.userId,t.memory?.additionalUsers,t.context)}async validateStreamInput(e){let t=process.hrtime.bigint();g.debug("[NeuroLink] \u{1F3AF} LOG_POINT_003_VALIDATION_START",{logPoint:"003_VALIDATION_START",validationStartTimeNs:t.toString(),message:"Starting comprehensive input validation process"});let n=typeof e?.input?.text=="string"&&e.input.text.trim().length>0,o=!!(e?.input?.audio&&e.input.audio.frames&&typeof e.input.audio.frames[Symbol.asyncIterator]=="function"),s=!!(e?.stt?.enabled&&e?.stt?.audio);if(!n&&!o&&!s)throw new Error("Stream options must include either input.text, input.audio, or stt.audio")}emitStreamStartEvents(e,t){this.emitter.emit("stream:start",{provider:e.provider||"auto",timestamp:t}),this.emitter.emit("response:start"),this.emitter.emit("message",`Starting ${e.provider||"auto"} stream...`)}async createMCPStream(e){let t=await Qh(e.provider),n=await Qr.createProvider(t,e.model,!e.disableTools,this,e.region,this.resolveCredentials(e.credentials));await n.ensureModelLimits?.(),n.setTraceContext(this._metricsTraceContext),n.setupToolExecutor({customTools:this.getCustomTools(),executeTool:(h,y)=>this.executeTool(h,y,{disableToolCache:e.disableToolCache})},"NeuroLink.createMCPStream");let o=await this.getAllAvailableTools();o=this.applyToolInfoFiltering(o,e);let s=e.skipToolPromptInjection?e.systemPrompt||"":this.createToolAwareSystemPrompt(e.systemPrompt,o,n.supportsTools?.()??!0),i=e.conversationMessages!==void 0,a=i?e.conversationMessages:await fg(this.conversationMemory,{...e,prompt:e.input.text,context:e.context});e.conversationMessages=a;let c=a,l=Cc({provider:t,model:e.model,maxTokens:e.maxTokens,systemPrompt:s,conversationMessages:c,currentPrompt:e.input.text,toolDefinitions:o}),d=c?.length||0,p=this.getCompactionSessionId(e),m=d>0;if(!l.withinBudget&&!m){try{this.emitter.emit("compaction.insufficient",{stagesAttempted:["pre-dispatch hard cap"],finalTokens:l.estimatedInputTokens,budget:l.availableInputTokens,provider:t,model:e.model,phase:"pre-dispatch-no-recovery",timestamp:Date.now()})}catch{}throw new ya(`Stream context exceeds model budget and no compaction is possible (no conversationMemory, no inline conversationMessages \u2014 only prompt + tools). Estimated: ${l.estimatedInputTokens} tokens, budget: ${l.availableInputTokens} tokens. Reduce prompt or tool-definition size, or trim the request.`,{estimatedTokens:l.estimatedInputTokens,availableTokens:l.availableInputTokens,stagesUsed:[],breakdown:l.breakdown})}if(l.shouldCompact&&(i||this.conversationMemory)&&d>(this.lastCompactionMessageCount.get(p)??0)){let y=await new Fh({provider:t,summarizationProvider:this.conversationMemoryConfig?.conversationMemory?.summarizationProvider,summarizationModel:this.conversationMemoryConfig?.conversationMemory?.summarizationModel}).compact(c,OG(l),this.conversationMemoryConfig?.conversationMemory,e.context?.requestId);y.compacted&&(c=Uh(y.messages).messages,e.conversationMessages=c,this.lastCompactionMessageCount.set(p,c.length));let v=Cc({provider:t,model:e.model,maxTokens:e.maxTokens,systemPrompt:s,conversationMessages:c,currentPrompt:e.input.text,toolDefinitions:o});if(!v.withinBudget){g.warn("[NeuroLink] Stream: post-compaction still over budget, emergency truncation",{estimatedTokens:v.estimatedInputTokens,availableTokens:v.availableInputTokens,overagePercent:Math.round((v.usageRatio-1)*100)});try{this.emitter.emit("compaction.insufficient",{stagesAttempted:y.stagesUsed,finalTokens:v.estimatedInputTokens,budget:v.availableInputTokens,provider:t,model:e.model,phase:"mid-compaction",willEmergencyTruncate:!0,timestamp:Date.now()})}catch{}c=UG(c,v.availableInputTokens,v.breakdown,t),e.conversationMessages=c;let b=Cc({provider:t,model:e.model,maxTokens:e.maxTokens,systemPrompt:s,conversationMessages:c,currentPrompt:e.input.text,toolDefinitions:o});if(!b.withinBudget){this.lastCompactionMessageCount.delete(p);try{this.emitter.emit("compaction.insufficient",{stagesAttempted:y.stagesUsed,finalTokens:b.estimatedInputTokens,budget:b.availableInputTokens,provider:t,model:e.model,phase:"post-emergency-truncation",timestamp:Date.now()})}catch{}throw new ya(`Stream context exceeds model budget after all compaction stages. Estimated: ${b.estimatedInputTokens} tokens, Budget: ${b.availableInputTokens} tokens.`,{estimatedTokens:b.estimatedInputTokens,availableTokens:b.availableInputTokens,stagesUsed:y.stagesUsed,breakdown:b.breakdown})}}}if(this.modelPool){let h=this.modelPool,y=h.maxAttempts,v=new Set,b=null;for(let S=0;S<y;S++){if(e.abortSignal?.aborted)throw new DOMException("The operation was aborted","AbortError");let w=h.selectNext(v);if(!w)break;v.add(h.memberKey(w));let C=w.provider,R=w.model??void 0,k=w.region??void 0;g.debug(`[createMCPStream] ModelPool: attempting member ${C}`,{model:R,attempt:S});try{let I=await Qr.createProvider(C,R,!e.disableTools,this,k,this.resolveCredentials(e.credentials));I.setTraceContext(this._metricsTraceContext),I.setupToolExecutor({customTools:this.getCustomTools(),executeTool:(L,B)=>this.executeTool(L,B,{disableToolCache:e.disableToolCache})},"NeuroLink.createMCPStream");let P=await I.stream({...e,provider:C,model:R,region:k,systemPrompt:s,conversationMessages:c});g.debug("[createMCPStream] ModelPool stream handle obtained",{provider:C});let A=w;return{stream:(async function*(){try{yield*P.stream,h.recordSuccess(A)}catch(L){throw h.recordFailure(A,ry(L)),L}})(),provider:C,usage:P.usage,model:P.model||R,finishReason:P.finishReason,toolCalls:P.toolCalls??[],toolResults:P.toolResults??[],analytics:P.analytics,metadata:P.metadata}}catch(I){if(Ar(I))throw I;if(n3e(I)){let P=I instanceof Error?I.message:String(I);throw h.recordFailure(w,ry(I)),new Error(`[ModelPool] non-retryable: ${P}`,{cause:I})}h.recordFailure(w,ry(I)),b=I instanceof Error?I:new Error(String(I)),g.warn(`[createMCPStream] ModelPool: member ${C} failed`,{error:b.message})}}throw new Error(`[ModelPool] all stream members failed: ${b?.message??"no stream members available"}`)}let f=await n.stream({...e,systemPrompt:s,conversationMessages:c});return g.debug("[createMCPStream] Stream created successfully",{provider:t,systemPromptPassedLength:s.length}),{stream:f.stream,provider:t,usage:f.usage,model:f.model||e.model,finishReason:f.finishReason,toolCalls:f.toolCalls??[],toolResults:f.toolResults??[],analytics:f.analytics,metadata:f.metadata}}async processStreamResult(e,t,n){return{content:"",usage:void 0,finishReason:"stop",toolCalls:[],toolResults:[],analytics:void 0,evaluation:void 0}}emitStreamEndEvents(e){this.emitter.emit("stream:end",{responseTime:Date.now(),timestamp:Date.now()}),this.emitter.emit("response:end",e.content||"")}createStreamResponse(e,t,n){return{stream:t,provider:n.providerName,model:n.options.model,usage:e.usage,finishReason:e.finishReason,toolCalls:e.toolCalls,toolResults:e.toolResults,analytics:e.analytics,evaluation:e.evaluation,events:n.events&&n.events.length>0?n.events:void 0,metadata:Object.assign(n.providerMetadata??{},{streamId:n.streamId,startTime:n.startTime,responseTime:n.responseTime,fallback:n.fallback||!1,guardrailsBlocked:n.guardrailsBlocked,error:n.error})}}async handleStreamError(e,t,n,o,s,i){if(e instanceof ya)throw e;g.error("Stream generation failed, attempting fallback",{error:e instanceof Error?e.message:String(e)});try{this.emitter.emit("stream:error",{content:e instanceof Error?e.message:String(e),metadata:{errorName:e instanceof Error?e.name:"UnknownError",durationMs:Date.now()-n,chunkCount:0},provider:t.provider||"unknown",model:t.model||"unknown"})}catch{}let a=t.input.text,c=Date.now()-n,l=await Qh(t.provider),p=await(await Qr.createProvider(l,t.model,!0,void 0,void 0,this.resolveCredentials(t.credentials))).stream({input:{text:t.input.text},model:t.model,temperature:t.temperature,maxTokens:t.maxTokens,conversationMessages:t.conversationMessages}),m="";return{stream:(async function*(h){try{for await(let y of p.stream)y&&"content"in y&&typeof y.content=="string"&&(m+=y.content,h.emitter.emit("response:chunk",y.content)),yield y}finally{if(m.trim()){g.info("[NeuroLink.handleStreamError] stream() - COMPLETE SUCCESS (fallback)",{provider:l,model:t.model,responseTimeMs:Date.now()-n,contentLength:m.length});try{let y=t.model||"unknown",v=Date.now()-n;h.emitter.emit("stream:complete",{content:m,provider:l,model:y,finishReason:"stop",metadata:{durationMs:v,chunkCount:0,totalLength:m.length,isFallback:!0,finishReason:"stop"}}),h.emitter.emit("generation:end",{provider:l,model:y,responseTime:v,timestamp:Date.now(),result:{content:m,usage:{input:0,output:0,total:0},model:y,provider:l,finishReason:"stop"},success:!0,pipelineAHandled:!0})}catch{}}if(h.conversationMemory&&s?.context?.sessionId&&m.trim()){let y=s?.context?.sessionId,v=s?.context?.userId,b;t.model&&(b={provider:l,model:t.model});let S=Date.now();try{let w=y||t.context?.sessionId,C=h.drainPendingSkillMessages(w);await h.conversationMemory.storeConversationTurn({sessionId:w,userId:v||t.context?.userId,userMessage:a??"",aiResponse:m,startTimeStamp:new Date(n),providerDetails:b,enableSummarization:s?.enableSummarization,requestId:s?.context?.requestId||t.context?.requestId,...C.length>0?{skillMessages:C}:{}}),h.recordMemorySpan("memory.store",{"memory.operation":"store","memory.path":"fallback-stream"},Date.now()-S,1)}catch(w){h.recordMemorySpan("memory.store",{"memory.operation":"store","memory.path":"fallback-stream"},Date.now()-S,2,w instanceof Error?w.message:String(w)),g.warn("Failed to store fallback stream conversation turn",{error:w instanceof Error?w.message:String(w)})}}}})(this),provider:l,model:t.model,usage:p.usage,finishReason:p.finishReason||"stop",toolCalls:p.toolCalls||[],toolResults:p.toolResults||[],analytics:p.analytics,evaluation:p.evaluation,metadata:{streamId:o,startTime:n,responseTime:c,fallback:!0}}}getEventEmitter(){return this.emitter}getToolDedupConfig(){return this.toolDedupConfig}getToolsConfig(){return this.toolsConfig}getDiscoveryPins(e){let t=this.discoveryPins.get(e);return t?(this.discoveryPins.delete(e),this.discoveryPins.set(e,t),t):new Set}pinDiscoveredTools(e,t){let n=this.discoveryPins.get(e);n?this.discoveryPins.delete(e):n=new Set,this.discoveryPins.set(e,n);for(let o of t)n.add(o);if(this.discoveryPins.size>1e3){let o=this.discoveryPins.keys().next().value;o!==void 0&&this.discoveryPins.delete(o)}}async checkCredentials(e){let{provider:t,model:n}=e,o="ping";try{return await this.generate({provider:t,...n&&{model:n},input:{text:o},maxTokens:16,disableTools:!0}),{provider:t,status:"ok",detail:"credentials valid"}}catch(s){let i=s instanceof Error?s.message:String(s),a=i.toLowerCase();return s instanceof up?{provider:t,status:"denied",detail:i}:a.includes("authentication")||a.includes("401")||a.includes("invalid api key")||a.includes("incorrect api key")||a.includes("api_key_invalid")||a.includes("token has expired")||a.includes("expired credentials")?{provider:t,status:"expired",detail:i}:a.includes("not configured")||a.includes("missing api")||a.includes("api key is required")||a.includes("no api key")||a.includes("application default credentials")||a.includes("google_application_credentials")||a.includes("project_id")||a.includes("default credentials")||a.includes("service account")?{provider:t,status:"missing",detail:i}:a.includes("econnrefused")||a.includes("enotfound")||a.includes("could not resolve")||a.includes("timeout")||a.includes("network")||a.includes("cannot connect")?{provider:t,status:"network",detail:i}:{provider:t,status:"unknown",detail:i}}}emitToolStart(e,t,n=Date.now()){let o=`${e}-${n}-${Math.random().toString(36).substr(2,9)}`,s={executionId:o,tool:e,startTime:n,metadata:{inputType:typeof t,hasInput:t!=null}};return this.activeToolExecutions.set(o,s),this.currentStreamToolExecutions.push(s),this.emitter.emit("tool:start",jm(e,{input:t,timestamp:n,executionId:o})),g.debug(`tool:start emitted for ${e}`,{toolName:e,executionId:o,timestamp:n,inputProvided:t!==void 0}),o}emitToolEnd(e,t,n,o,s=Date.now(),i){let a=o||s-1e3,c=s-a,l=!n,d;i?d=this.activeToolExecutions.get(i):d=Array.from(this.activeToolExecutions.values()).find(f=>f.tool===e&&!f.endTime);let p=i||d?.executionId||`${e}-${a}-fallback-${Math.random().toString(36).substr(2,9)}`;d&&(d.endTime=s,d.result=t,d.error=n,this.activeToolExecutions.delete(d.executionId));let m={tool:e,startTime:a,endTime:s,duration:c,success:l,result:t,error:n,executionId:p,metadata:{toolCategory:"custom"}};this.toolExecutionHistory.push(m),this.emitter.emit("tool:end",jm(e,{result:t,error:n,success:l,responseTime:c,timestamp:s,duration:c,executionId:p})),g.debug(`tool:end emitted for ${e}`,{toolName:e,executionId:p,duration:c,success:l,hasResult:t!==void 0,hasError:!!n})}getCurrentToolExecutions(){return[...this.currentStreamToolExecutions]}getToolExecutionHistory(){return[...this.toolExecutionHistory]}clearCurrentStreamExecutions(){this.currentStreamToolExecutions=[]}registerTool(e,t,n){this.invalidateToolCache(),this.emitter.emit("tools-register:start",{toolName:e,timestamp:Date.now()});try{if(!e||typeof e!="string")throw new Error("Invalid tool name");if(!t||typeof t!="object")throw new Error(`Invalid tool object provided for tool: ${e}`);if(typeof t.execute!="function")throw new Error(`Tool '${e}' must have an execute method.`);if(e.trim()==="")throw new Error("Tool name cannot be empty");if(e.length>100)throw new Error("Tool name is too long (maximum 100 characters)");if(/[\x00-\x1F\x7F]/.test(e))throw new Error("Tool name contains invalid control characters");let o={name:t.name||e,description:t.description||e,execute:t.execute,inputSchema:"parameters"in t&&t.parameters&&(hA(t.parameters)||typeof t.parameters=="object")?t.parameters:t.inputSchema||{}};if(n?.timeout!==void 0&&n.timeout>0&&Number.isFinite(n.timeout)&&typeof o.execute=="function"){let i=o.execute,a=n.timeout,c=e;o.execute=async(...l)=>{let d=AbortSignal.timeout(a),p=l[1],m=p?.abortSignal,f=m?AbortSignal.any([m,d]):d,h={...p,abortSignal:f};return Promise.race([i(l[0],h),new Promise((y,v)=>{f.addEventListener("abort",()=>{d.aborted?v(ve.toolTimeout(c,a)):v(new DOMException("The operation was aborted","AbortError"))},{once:!0})})])}}let s=GVe(e,o,n?.timeout,n?.maxRetries);this.toolRegistry.registerServer(s),this.emitter.emit("tools-register:end",{toolName:e,success:!0,timestamp:Date.now(),timeoutMs:n?.timeout})}catch(o){throw g.error(`Failed to register tool ${e}:`,o),o}}setToolContext(e){this.toolExecutionContext={...e},g.debug("Tool execution context updated",{sessionId:e.sessionId,contextKeys:Object.keys(e),hasJuspayToken:!!e.juspayToken,hasShopId:!!e.shopId})}getToolContext(){return this.toolExecutionContext?{...this.toolExecutionContext}:void 0}clearToolContext(){this.toolExecutionContext=void 0,g.debug("Tool execution context cleared")}registerTools(e){if(Array.isArray(e))for(let{name:t,tool:n}of e)this.registerTool(t,n);else for(let[t,n]of Object.entries(e))this.registerTool(t,n)}unregisterTool(e){this.invalidateToolCache();let t=`custom-tool-${e}`,n=this.toolRegistry.unregisterServer(t);return n&&g.info(`Unregistered custom tool: ${e}`),n}useToolMiddleware(e){return this.mcpToolMiddlewares.push(e),g.debug(`[NeuroLink] Registered tool middleware (total: ${this.mcpToolMiddlewares.length})`),this}getToolMiddlewares(){return[...this.mcpToolMiddlewares]}async flushToolBatch(){this.mcpToolBatcher&&await this.mcpToolBatcher.flush()}getMCPEnhancementsConfig(){return this.mcpEnhancementsConfig}async updateAgenticLoopReport(e,t,n){if(!this.conversationMemory)throw new qa("Conversation memory is not initialized. Enable conversationMemory in NeuroLink options.","CONFIG_ERROR");if(!("updateAgenticLoopReport"in this.conversationMemory)||typeof this.conversationMemory.updateAgenticLoopReport!="function")throw new qa("updateAgenticLoopReport is only supported with Redis conversation memory.","CONFIG_ERROR");await qe(this.conversationMemory.updateAgenticLoopReport(e,n,t),5e3)}getCustomTools(){let e=this.toolRegistry.getToolsByCategory(ta({isCustomTool:!0})),t=new Map;for(let o of e){let s=o.inputSchema||o.parameters;g.debug("Processing tool schema for Claude",{toolName:o.name,hasDescription:!!o.description,description:o.description,hasParameters:!!o.parameters,parametersType:typeof o.parameters,parametersKeys:o.parameters&&typeof o.parameters=="object"?Object.keys(o.parameters):"NOT_OBJECT",hasInputSchema:!!o.inputSchema,inputSchemaType:typeof o.inputSchema,inputSchemaKeys:o.inputSchema&&typeof o.inputSchema=="object"?Object.keys(o.inputSchema):"NOT_OBJECT",hasEffectiveSchema:!!s,effectiveSchemaType:typeof s,effectiveSchemaHasProperties:!!s?.properties,effectiveSchemaHasRequired:!!s?.required,originalInputSchema:o.inputSchema,phase:"AFTER_SCHEMA_FIX",timestamp:Date.now()}),t.set(o.name,{name:o.name,description:o.description||"",inputSchema:typeof o.inputSchema=="object"&&o.inputSchema!==null?o.inputSchema:typeof o.parameters=="object"&&o.parameters!==null?o.parameters:{},execute:async(i,a)=>{let c=this.toolExecutionContext||{},l=a&&xr(a)?a:{},d={...c,...l,sessionId:l.sessionId||c.sessionId||`fallback-${Date.now()}`};return g.debug("Tool execution context merged",{toolName:o.name,storedContextKeys:Object.keys(c),runtimeContextKeys:Object.keys(l),finalContextKeys:Object.keys(d),hasJuspayToken:!!d.juspayToken,hasShopId:!!d.shopId,sessionId:d.sessionId}),await this.toolRegistry.executeTool(o.name,i,d)}})}this.cachedFileTools||(this.cachedFileTools=die(this.fileRegistry));let n=this.cachedFileTools;for(let[o,s]of Object.entries(n))if(!t.has(o)){let i=s,a=i.inputSchema??i.parameters;t.set(o,{name:o,description:s.description||`File tool: ${o}`,inputSchema:typeof a=="object"&&a!==null?a:{type:"object",properties:{}},execute:async c=>await s.execute(c,{toolCallId:`file-tool-${Date.now()}`,messages:[]})})}return t}async addInMemoryMCPServer(e,t){this.invalidateToolCache();try{fe.debug(`[NeuroLink] Registering in-memory MCP server: ${e}`),t.tools||(t.tools=[]),await this.toolRegistry.registerServer(t),fe.info(`[NeuroLink] Successfully registered in-memory server: ${e}`,{category:t.metadata?.category,provider:t.metadata?.provider,version:t.metadata?.version})}catch(n){throw fe.error(`[NeuroLink] Failed to register in-memory server ${e}:`,n),n}}getInMemoryServers(){let e=this.getInMemoryServerInfos(),t=new Map;for(let n of e)t.set(n.id,n);return t}getInMemoryServerInfos(){return this.toolRegistry.getBuiltInServerInfos().filter(t=>ta({existingCategory:t.metadata?.category,serverId:t.id})==="in-memory")}getAutoDiscoveredServerInfos(){return this.autoDiscoveredServerInfos}async executeTool(e,t={},n){if(this.mcpToolBatcher&&!n?.bypassBatcher)return this.mcpToolBatcher.execute(e,t);let o=this.createToolExecutionContext(e,t,n);return Ne.mcp.startActiveSpan("neurolink.tool.execute",{attributes:{"tool.name":e,"tool.type":o.toolType,"tool.input_size":o.inputSize,"tool.input_preview":o.truncatedInput}},s=>this.executeToolWithSpan(e,t,n,o,s))}createToolExecutionContext(e,t,n){let o=this.externalServerManager.getAllTools().find(l=>l.name===e),s=o?"mcp":this.getCustomTools().has(e)?"custom":"external",i=t?Cp(t):"",a=Date.now(),c=`${e}-${a}-${Math.random().toString(36).slice(2,11)}`;return{functionTag:"NeuroLink.executeTool",executionStartTime:a,executionId:c,externalTool:o,toolType:s,inputSize:i.length,truncatedInput:i.length>2048?i.substring(0,2048):i,options:n,hitlState:{triggered:!1}}}async executeToolWithSpan(e,t,n,o,s){try{let i=await this.prepareToolExecutionState(e,t,n,o);return await this.runPreparedToolExecution(e,t,i,o,s)}catch(i){if(!(i instanceof Me)){let a=i instanceof Error?i.message:String(i);s.recordException(i instanceof Error?i:new Error(a)),s.setStatus({code:Fe.ERROR,message:a})}throw i}finally{s.end()}}async prepareToolExecutionState(e,t,n,o){g.debug(`[${o.functionTag}] Tool execution requested:`,{toolName:e,params:xr(t)?R2(t):t,hasExternalManager:!!this.externalServerManager}),g.debug("Tool execution detailed analysis",{toolName:e,executionStartTime:o.executionStartTime,paramsAnalysis:{type:typeof t,isNull:t===null,isUndefined:t===void 0,isEmpty:t&&typeof t=="object"&&Object.keys(t).length===0,keys:t&&typeof t=="object"?Object.keys(t):"NOT_OBJECT",keysLength:t&&typeof t=="object"?Object.keys(t).length:0},isTargetTool:e==="juspay-analytics_SuccessRateSRByTime",options:n,hasExternalManager:!!this.externalServerManager}),this.emitter.emit("tool:start",jm(e,{timestamp:o.executionStartTime,input:t,executionId:o.executionId}));let s=this.toolRegistry.getToolInfo(e),i={timeout:n?.timeout??s?.tool?.timeoutMs??Uc.EXECUTION_BATCH_MS,maxRetries:n?.maxRetries??s?.tool?.maxRetries??Xo.DEFAULT,retryDelayMs:n?.retryDelayMs||Bn.BASE_MS,authContext:n?.authContext,disableToolCache:n?.disableToolCache},{MemoryManager:a}=await Promise.resolve().then(()=>(jE(),zE)),c=a.getMemoryUsageMB(),d=`${o.externalTool?.serverId||s?.tool?.serverId||"unknown"}.${e}`,p=this.toolCircuitBreakers.get(d);p||(p=new cS(ak.FAILURE_THRESHOLD,SF),this.toolCircuitBreakers.set(d,p));let m=this.toolExecutionMetrics.get(e);return m||(m={totalExecutions:0,successfulExecutions:0,failedExecutions:0,averageExecutionTime:0,lastExecutionTime:0,errorCategories:{}},this.toolExecutionMetrics.set(e,m)),m.totalExecutions++,{finalOptions:i,startMemory:c,circuitBreaker:p,breakerKey:d,metrics:m}}async runPreparedToolExecution(e,t,n,o,s){let i=0;try{fe.debug(`[${o.functionTag}] Executing tool: ${e}`,{toolName:e,params:t,options:n.finalOptions,circuitBreakerState:n.circuitBreaker.getState()});let a=await n.circuitBreaker.execute(async()=>T8(async()=>qe(this.executeToolInternal(e,t,n.finalOptions,o.hitlState),n.finalOptions.timeout,ve.toolTimeout(e,n.finalOptions.timeout)),{maxAttempts:n.finalOptions.maxRetries+1,delayMs:n.finalOptions.retryDelayMs,isRetriable:EF,onRetry:(c,l)=>{i=c,fe.warn(`[${o.functionTag}] Retrying tool execution (attempt ${c})`,{toolName:e,error:l.message,attempt:c})}}));return s.setAttribute("tool.retry_count",i),await this.handleSuccessfulToolExecution(e,a,n,o,s)}catch(a){return s.setAttribute("tool.retry_count",i),this.handleFailedToolExecution(e,t,a,n,o,s)}}async handleSuccessfulToolExecution(e,t,n,o,s){let i=Date.now()-o.executionStartTime;n.metrics.successfulExecutions++,n.metrics.lastExecutionTime=i,n.metrics.averageExecutionTime=(n.metrics.averageExecutionTime*(n.metrics.successfulExecutions-1)+i)/n.metrics.successfulExecutions;let{MemoryManager:a}=await Promise.resolve().then(()=>(jE(),zE)),l=a.getMemoryUsageMB().heapUsed-n.startMemory.heapUsed;l>20&&fe.warn(`Tool '${e}' used excessive memory: ${l}MB`,{toolName:e,memoryDelta:l,executionTime:i}),fe.debug(`[${o.functionTag}] Tool executed successfully`,{toolName:e,executionTime:i,memoryDelta:l,circuitBreakerState:n.circuitBreaker.getState()});let d=t&&typeof t=="object"?t:void 0,p=d&&"isError"in d&&d.isError===!0||d&&"success"in d&&d.success===!1,m=p?d?.content:void 0,f=p?m?.filter(h=>h.type==="text"&&h.text).map(h=>h.text).join(" ")||(typeof d?.error=="string"?d.error:"Unknown error"):void 0;if(p){try{await n.circuitBreaker.execute(async()=>{throw new Error(`Tool ${e} returned isError:true`)})}catch{}fe.debug(`[${o.functionTag}] Circuit breaker failure recorded for isError result`,{toolName:e,circuitBreakerState:n.circuitBreaker.getState(),circuitBreakerFailures:n.circuitBreaker.getFailureCount()});let h=WRr(f??"Unknown error"),y=`[TOOL_ERROR: ${e} failed (${h})] `;if(d&&Array.isArray(m)){let S=m.map(w=>({...w}));for(let w of S)if(w.type==="text"&&w.text){w.text=y+w.text;break}d.content=S}s.setAttribute("tool.error.message",(f??"Unknown error").substring(0,500)),s.setAttribute("tool.error.category",h),s.setStatus({code:Fe.ERROR,message:`MCP tool returned isError: ${(f??"Unknown error").substring(0,200)}`}),n.metrics.failedExecutions++;let v=n.metrics.successfulExecutions;n.metrics.successfulExecutions=Math.max(0,n.metrics.successfulExecutions-1),n.metrics.averageExecutionTime=v>1?(n.metrics.averageExecutionTime*v-i)/(v-1):0;let b=JRr(h);n.metrics.errorCategories[b]=(n.metrics.errorCategories[b]||0)+1}return this.emitToolEndEvent(e,o.executionStartTime,!p,t,p&&f?new Error(f):void 0,o.executionId),s.setAttribute("tool.result.status",p?"error":"success"),s.setAttribute("tool.duration_ms",i),t}async handleFailedToolExecution(e,t,n,o,s,i){o.metrics.failedExecutions++;let a=Date.now()-s.executionStartTime;if(n instanceof Ga)return fe.warn(`[${s.functionTag}] Tool blocked by circuit breaker: ${e}`,{toolName:e,breakerState:n.breakerState,retryAfter:n.retryAfter,retryAfterMs:n.retryAfterMs,failureCount:n.failureCount,executionTime:a}),o.metrics.errorCategories.execution=(o.metrics.errorCategories.execution||0)+1,this.emitToolEndEvent(e,s.executionStartTime,!1,void 0,new Error(`Circuit breaker open for ${e} (state=${n.breakerState}, failures=${n.failureCount})`),s.executionId),i.setAttribute("tool.result.status","circuit_breaker_open"),i.setAttribute("tool.duration_ms",a),i.setAttribute("tool.circuit_breaker.state",n.breakerState),i.setAttribute("tool.circuit_breaker.retry_after_ms",n.retryAfterMs),i.setAttribute("tool.circuit_breaker.failure_count",n.failureCount),i.setStatus({code:Fe.ERROR,message:`Circuit breaker open for ${e}: ${n.message}`}),{isError:!0,content:[{type:"text",text:`TOOL TEMPORARILY UNAVAILABLE: "${e}" has been disabled after ${n.failureCount} failures. This is a circuit breaker protection \u2014 do NOT retry this tool. It will become available again after ${Math.ceil(n.retryAfterMs/1e3)} seconds (at ${n.retryAfter}). Instead, inform the user that the operation failed and suggest trying again later.`}]};let c;if(n instanceof Me)c=n;else if(n instanceof Error)if(n.message.includes("timeout"))c=ve.toolTimeout(e,o.finalOptions.timeout);else if(n.message.includes("not found")){let d=await this.getAllAvailableTools();c=ve.toolNotFound(e,jIe(d.map(p=>({name:p.name}))))}else n.message.includes("validation")||n.message.includes("parameter")?c=ve.invalidParameters(e,n,t):n.message.includes("network")||n.message.includes("connection")?c=ve.networkError(e,n):c=ve.toolExecutionFailed(e,n);else c=ve.toolExecutionFailed(e,new Error(String(n)));let l=c.category||"execution";throw o.metrics.errorCategories[l]=(o.metrics.errorCategories[l]||0)+1,this.emitToolEndEvent(e,s.executionStartTime,!1,void 0,c,s.executionId),this.emitter.listenerCount("error")>0&&this.emitter.emit("error",c),c=new Me({...c,context:{...c.context,executionTime:a,params:t,options:o.finalOptions,circuitBreakerState:o.circuitBreaker.getState(),circuitBreakerFailures:o.circuitBreaker.getFailureCount(),metrics:{...o.metrics}}}),S8(c),i.setAttribute("tool.result.status","error"),i.setAttribute("tool.duration_ms",a),i.recordException(c),i.setStatus({code:Fe.ERROR,message:c.message}),c}async executeToolInternal(e,t,n,o){let s="NeuroLink.executeToolInternal",i=this.getToolAnnotationsForExecution(e),a=this.mcpToolResultCache&&!n.disableToolCache&&!this._disableToolCacheForCurrentRequest&&!i?.destructiveHint,c=this.mcpToolResultCache,l=n.authContext||this.toolExecutionContext?{__args:t,__ctx:n.authContext??this.toolExecutionContext}:t;if(a&&c){let m=c.getCachedResult(e,l);if(m!==void 0)return g.debug(`[${s}] Cache HIT for tool: ${e}`),m}let d=async m=>{if(this.mcpToolMiddlewares.length===0)return m();let f=0,h=async()=>{if(f<this.mcpToolMiddlewares.length){let y=this.mcpToolMiddlewares[f++];return y({name:e,description:"",inputSchema:{},annotations:i,execute:async()=>({})},t,{toolMeta:{name:e,annotations:i}},h)}return m()};return await h()},p=async()=>{let m=this.externalServerManager.getAllTools(),f=m.filter(y=>y.name===e&&y.isAvailable),h;if(f.length>1&&this.mcpToolRouter)try{let y={name:e,description:f[0].description??"",serverId:f[0].serverId,inputSchema:{}},v=this.mcpToolRouter.route(y);h=f.find(b=>b.serverId===v.serverId)||f[0],g.debug(`[${s}] Router selected server: ${v.serverId}`,{strategy:v.strategy,confidence:v.confidence})}catch(y){g.warn(`[${s}] Router failed, falling back to first match`,{error:y}),h=f[0]}else h=f[0];if(g.debug(`[${s}] External MCP tool search:`,{toolName:e,externalToolsCount:m.length,foundTool:!!h,isAvailable:h?.isAvailable,serverId:h?.serverId}),h&&h.isAvailable)try{fe.debug(`[${s}] Executing external MCP tool: ${e} from ${h.serverId}`);let y=await this.externalServerManager.executeTool(h.serverId,e,t,{timeout:n.timeout});return g.debug(`[${s}] External MCP tool execution successful:`,{toolName:e,serverId:h.serverId,resultType:typeof y}),y}catch(y){throw g.error(`[${s}] External MCP tool execution failed:`,{toolName:e,serverId:h.serverId,error:y instanceof Error?y.message:String(y)}),ve.toolExecutionFailed(e,y instanceof Error?y:new Error(String(y)),h.serverId)}try{let y=this.toolExecutionContext||{},v=n.authContext||{},b={...y,...v,hitlState:o};g.debug("[Using merged context for unified registry tool:",{toolName:e,storedContextKeys:Object.keys(y),finalContextKeys:Object.keys(b)});let S=await this.toolRegistry.executeTool(e,t,b);if(S&&typeof S=="object"&&"success"in S&&S.success===!1){let w=S.error||"Tool execution failed",C=new Error(w);this.emitter.listenerCount("error")>0&&this.emitter.emit("error",C)}return S}catch(y){let v=y instanceof Error?y:new Error(String(y));if(this.emitter.listenerCount("error")>0&&this.emitter.emit("error",v),y instanceof Error&&y.message.includes("not found")){let b=await this.getAllAvailableTools();throw ve.toolNotFound(e,b.map(S=>S.name))}throw ve.toolExecutionFailed(e,y instanceof Error?y:new Error(String(y)))}};try{let m=await d(p);return a&&c&&m!==void 0&&(c.cacheResult(e,l,m),g.debug(`[${s}] Cached result for tool: ${e}`)),m}catch(m){let f=i?{name:e,description:"",annotations:i,execute:async()=>({})}:void 0;if(f&&xI(f)&&m instanceof Error&&EF(m)){g.debug(`[${s}] Tool ${e} is safe to retry, attempting once more`);try{let h=await d(p);return a&&c&&h!==void 0&&c.cacheResult(e,l,h),h}catch{}}throw m}}getToolAnnotationsForExecution(e){if(this.toolCache?.tools){let t=this.toolCache.tools.find(n=>n.name===e);if(t?.annotations)return t.annotations}if(this.mcpEnhancementsConfig?.annotations?.autoInfer!==!1)return ql({name:e,description:""})}invalidateToolCache(){this.toolCache=null,g.debug("Tool cache invalidated")}async getAllAvailableTools(){if(this.toolCache&&Date.now()-this.toolCache.timestamp<this.toolCacheDuration)return g.debug("Returning available tools from cache"),this.toolCache.tools;let e=`get-all-tools-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,t=Date.now(),n=process.hrtime.bigint();g.debug("[NeuroLink] \u{1F6E0}\uFE0F LOG_POINT_A001_GET_ALL_TOOLS_START",{logPoint:"A001_GET_ALL_TOOLS_START",getAllToolsId:e,timestamp:new Date().toISOString(),getAllToolsStartTime:t,getAllToolsHrTimeStart:n.toString(),toolRegistryState:{hasToolRegistry:!!this.toolRegistry,toolRegistrySize:0,toolRegistryType:this.toolRegistry?.constructor?.name||"NOT_SET",hasExternalServerManager:!!this.externalServerManager,externalServerManagerType:this.externalServerManager?.constructor?.name||"NOT_SET"},mcpState:{mcpInitialized:this.mcpInitialized,hasProviderRegistry:!!Qr,providerRegistrySize:0},message:"Starting comprehensive tool discovery across all sources"});let{MemoryManager:o}=await Promise.resolve().then(()=>(jE(),zE)),s=o.getMemoryUsageMB();try{let i=new Map,a=await this.toolRegistry.listTools();for(let y of a)if(!i.has(y.name)){let v=yA(y,{serverId:y.serverId==="direct"?"neurolink-direct":y.serverId});i.set(y.name,v)}let c=this.toolRegistry.getToolsByCategory(ta({isCustomTool:!0}));for(let y of c)if(!i.has(y.name)){let v=yA(y,{description:"Custom tool",serverId:`custom-tool-${y.name}`,category:ta({isCustomTool:!0,serverId:y.serverId}),inputSchema:{}});i.set(y.name,v)}let l=this.toolRegistry.getToolsByCategory("in-memory");for(let y of l)if(!i.has(y.name)){let v=yA(y,{description:"In-memory MCP tool",serverId:"unknown",category:"in-memory",inputSchema:{}});i.set(y.name,v)}let d=this.externalServerManager.getAllTools();for(let y of d)if(!i.has(y.name)){let v=yA(y,{category:ta({existingCategory:typeof y.metadata?.category=="string"?y.metadata.category:void 0,isExternal:!0,serverId:y.serverId}),inputSchema:{}});i.set(y.name,v)}let p=Array.from(i.values());fe.debug("Tool discovery results",{mcpTools:a.length,customTools:c.length,inMemoryTools:l.length,externalMCPTools:d.length,total:p.length});let f=o.getMemoryUsageMB().heapUsed-s.heapUsed;if(f>cp.LOW_USAGE_MB&&(fe.debug(`\u{1F50D} Tool listing used ${f}MB memory (large tool registry detected)`),p.length>g8.LARGE_TOOL_COLLECTION&&fe.debug("\u{1F4A1} Tool collection optimized for large sets. Memory usage reduced through efficient object reuse.")),this.mcpEnhancementsConfig?.annotations?.autoInfer!==!1)for(let y of p)y.annotations||(y.annotations=ql({name:y.name,description:y.description||""}));let h=p.sort((y,v)=>y.name<v.name?-1:y.name>v.name?1:0);return this.toolCache={tools:h,timestamp:Date.now()},h}catch(i){return fe.error("Failed to list available tools",{error:i}),[]}}async getProviderStatus(e){let{MemoryManager:t}=await Promise.resolve().then(()=>(jE(),zE)),n=t.getMemoryUsageMB();e?.quiet||fe.debug("\u{1F50D} DEBUG: Initializing MCP for provider status..."),await this.initializeMCP(),e?.quiet||fe.debug("\u{1F50D} DEBUG: MCP initialized:",this.mcpInitialized);let{AIProviderFactory:o}=await Promise.resolve().then(()=>(Il(),m4)),{hasProviderEnvVars:s}=await Promise.resolve().then(()=>(_g(),$M)),i=["openai","bedrock","vertex","googleVertex","anthropic","azure","google-ai","huggingface","ollama","mistral","litellm"],a=Np(Ji.DEFAULT_CONCURRENCY_LIMIT),c=i.map(m=>a(async()=>{let f=Date.now();try{if(!await this.hasProviderEnvVars(m)&&m!=="ollama")return{provider:m,status:"not-configured",configured:!1,authenticated:!1,error:"Missing required environment variables",responseTime:Date.now()-f};if(m==="ollama")try{let S=await fetch("http://localhost:11434/api/tags",{method:"GET",signal:AbortSignal.timeout(Fc.AUTH_MS)});if(!S.ok)throw new Error("Ollama service not responding");let w=await S.json(),C=w?.models;if(!Array.isArray(C))throw g.warn("Ollama API returned invalid models format in testProvider",{responseData:w,modelsType:typeof C}),new Error("Invalid models format from Ollama API");let R=C.filter(k=>k&&typeof k=="object"&&typeof k.name=="string");return R.length>0?{provider:m,status:"working",configured:!0,authenticated:!0,responseTime:Date.now()-f,model:R[0].name}:{provider:m,status:"failed",configured:!0,authenticated:!1,error:"Ollama service running but no models installed",responseTime:Date.now()-f}}catch(S){return{provider:m,status:"failed",configured:!1,authenticated:!1,error:S instanceof Error?S.message:"Ollama service not running",responseTime:Date.now()-f}}let y=5e3,v=this.testProviderConnection(m),b=new Promise((S,w)=>{setTimeout(()=>w(new Error("Provider test timeout (5s)")),y)});return await Promise.race([v,b]),{provider:m,status:"working",configured:!0,authenticated:!0,responseTime:Date.now()-f}}catch(h){let y=h instanceof Error?h.message:String(h);return{provider:m,status:"failed",configured:!0,authenticated:!1,error:y,responseTime:Date.now()-f}}})),l=await Promise.all(c),p=t.getMemoryUsageMB().heapUsed-n.heapUsed;return!e?.quiet&&p>20&&fe.debug(`\u{1F50D} Memory usage: +${p}MB (consider cleanup for large operations)`),p>50&&t.forceGC(),l}async testProvider(e){try{return await this.testProviderConnection(e),!0}catch{return!1}}async testProviderConnection(e){let{AIProviderFactory:t}=await Promise.resolve().then(()=>(Il(),m4));await(await t.createProvider(e,null)).generate({prompt:"test",maxTokens:1,disableTools:!0})}async getBestProvider(e){let{getBestProvider:t}=await Promise.resolve().then(()=>(_g(),$M));return t(e)}async getAvailableProviders(){let{getAvailableProviders:e}=await Promise.resolve().then(()=>(_g(),$M));return e()}async isValidProvider(e){let{isValidProvider:t}=await Promise.resolve().then(()=>(_g(),$M));return t(e)}async getMCPStatus(){try{await this.initializeMCP();let e=await this.toolRegistry.listTools(),t=this.externalServerManager.getStatistics(),n=this.externalServerManager.listServers(),o=this.getInMemoryServerInfos(),s=this.toolRegistry.getBuiltInServerInfos(),i=this.getAutoDiscoveredServerInfos(),a=n.length+o.length+s.length+i.length,c=t.connectedServers+o.length+s.length,l=e.length+t.totalTools;return{mcpInitialized:this.mcpInitialized,totalServers:a,availableServers:c,autoDiscoveredCount:i.length,totalTools:l,autoDiscoveredServers:i,customToolsCount:this.toolRegistry.getToolsByCategory(ta({isCustomTool:!0})).length,inMemoryServersCount:o.length,externalMCPServersCount:n.length,externalMCPConnectedCount:t.connectedServers,externalMCPFailedCount:t.failedServers,externalMCPServers:n}}catch(e){return{mcpInitialized:!1,totalServers:0,availableServers:0,autoDiscoveredCount:0,totalTools:0,autoDiscoveredServers:[],customToolsCount:this.toolRegistry.getToolsByCategory(ta({isCustomTool:!0})).length,inMemoryServersCount:0,externalMCPServersCount:0,externalMCPConnectedCount:0,externalMCPFailedCount:0,externalMCPServers:[],error:e instanceof Error?e.message:String(e)}}}async listMCPServers(){return[...this.externalServerManager.listServers(),...this.getInMemoryServerInfos(),...this.toolRegistry.getBuiltInServerInfos(),...this.getAutoDiscoveredServerInfos()]}async testMCPServer(e){try{if(e==="neurolink-direct")return(await this.toolRegistry.listTools()).length>0;let t=this.getInMemoryServers();if(t.has(e)){let o=t.get(e);return!!(o?.tools&&o.tools.length>0)}let n=this.externalServerManager.getServer(e);return n?n.status==="connected"&&n.client!==null:!1}catch(t){return fe.error(`[NeuroLink] Error testing MCP server ${e}:`,t),!1}}async hasProviderEnvVars(e){let{ProviderHealthChecker:t}=await Promise.resolve().then(()=>(Zh(),LE));try{let n=await t.checkProviderHealth(e,{includeConnectivityTest:!1,cacheResults:!1});return n.isConfigured&&n.hasApiKey}catch(n){return g.warn(`Provider env var check failed for ${e}`,{error:n instanceof Error?n.message:String(n)}),!1}}async checkProviderHealth(e,t={}){let{ProviderHealthChecker:n}=await Promise.resolve().then(()=>(Zh(),LE)),o=await n.checkProviderHealth(e,t);return{provider:o.provider,isHealthy:o.isHealthy,isConfigured:o.isConfigured,hasApiKey:o.hasApiKey,lastChecked:o.lastChecked,error:o.error,warning:o.warning,responseTime:o.responseTime,configurationIssues:o.configurationIssues,recommendations:o.recommendations}}async checkAllProvidersHealth(e={}){let{ProviderHealthChecker:t}=await Promise.resolve().then(()=>(Zh(),LE));return(await t.checkAllProvidersHealth(e)).map(o=>({provider:o.provider,isHealthy:o.isHealthy,isConfigured:o.isConfigured,hasApiKey:o.hasApiKey,lastChecked:o.lastChecked,error:o.error,warning:o.warning,responseTime:o.responseTime,configurationIssues:o.configurationIssues,recommendations:o.recommendations}))}async getProviderHealthSummary(){let{ProviderHealthChecker:e}=await Promise.resolve().then(()=>(Zh(),LE)),t=await e.checkAllProvidersHealth({cacheResults:!0,includeConnectivityTest:!1}),n=e.getHealthSummary(t),o=[];return n.healthy===0?o.push("No providers are healthy. Check your environment configuration."):n.healthy<2&&o.push("Consider configuring additional providers for better reliability."),n.hasIssues>0&&o.push("Some providers have configuration issues. Run checkAllProvidersHealth() for details."),{...n,recommendations:o}}async clearProviderHealthCache(e){let{ProviderHealthChecker:t}=await Promise.resolve().then(()=>(Zh(),LE));t.clearHealthCache(e)}getToolExecutionMetrics(){let e={};for(let[t,n]of this.toolExecutionMetrics.entries())e[t]={...n,errorCategories:{...n.errorCategories},successRate:n.totalExecutions>0?n.successfulExecutions/n.totalExecutions:0};return e}setModelAliasConfig(e){this.modelAliasConfig=e,g.info(`[ModelAlias] Configured ${Object.keys(e.aliases).length} model aliases`)}getToolCircuitBreakerStatus(){let e={};for(let[t,n]of this.toolCircuitBreakers.entries())e[t]={state:n.getState(),failureCount:n.getFailureCount(),isHealthy:n.getState()==="closed"};return e}resetToolCircuitBreaker(e){this.toolCircuitBreakers.has(e)&&(this.toolCircuitBreakers.set(e,new cS(ak.FAILURE_THRESHOLD,SF)),fe.info(`Circuit breaker reset for tool: ${e}`))}clearToolExecutionMetrics(){this.toolExecutionMetrics.clear(),fe.info("All tool execution metrics cleared")}async getToolHealthReport(){let e={},t=0,n=await this.toolRegistry.listTools(),o=new Set(n.map(i=>i.name)),s=new Map;for(let i of n)s.has(i.name)||s.set(i.name,i.serverId||"unknown");for(let i of o){let a=this.toolExecutionMetrics.get(i),c=`${s.get(i)||"unknown"}.${i}`,l=this.toolCircuitBreakers.get(c),d=a&&a.totalExecutions>0?a.successfulExecutions/a.totalExecutions:0,p=(!l||l.getState()==="closed")&&d>=.8;p&&t++;let m=[],f=[];if(l&&l.getState()==="open"&&(m.push("Circuit breaker is open due to repeated failures"),f.push("Check tool implementation and fix underlying issues")),d<.8&&a&&a.totalExecutions>0&&(m.push(`Low success rate: ${(d*100).toFixed(1)}%`),f.push("Review error logs and improve tool reliability")),a&&a.averageExecutionTime>1e4&&(m.push("High average execution time"),f.push("Optimize tool performance or increase timeout")),a&&a.errorCategories){let h=a.errorCategories;h.timeout>0&&(m.push(`Timeout errors: ${h.timeout}`),f.push("Consider increasing the tool timeout configuration")),h.validation>0&&(m.push(`Validation errors: ${h.validation}`),f.push("Review input schemas and parameter validation")),h.network>0&&(m.push(`Network errors: ${h.network}`),f.push("Check network connectivity and endpoint availability"))}e[i]={name:i,isHealthy:p,metrics:{totalExecutions:a?.totalExecutions||0,successRate:d,averageExecutionTime:a?.averageExecutionTime||0,lastExecutionTime:a?.lastExecutionTime||0,errorCategories:a?.errorCategories?{...a.errorCategories}:{}},circuitBreaker:{state:l?.getState()||"closed",failureCount:l?.getFailureCount()||0},issues:m,recommendations:f}}return{totalTools:o.size,healthyTools:t,unhealthyTools:o.size-t,tools:e}}async ensureConversationMemoryInitialized(){try{let e=`manual-init-${Date.now()}`;return await this.initializeConversationMemoryForGeneration(e,Date.now(),process.hrtime.bigint()),!!this.conversationMemory}catch(e){return g.error("Failed to initialize conversation memory",{error:e instanceof Error?e.message:String(e)}),!1}}async getConversationStats(){let e=`stats-init-${Date.now()}`;if(await this.initializeConversationMemoryForGeneration(e,Date.now(),process.hrtime.bigint()),!this.conversationMemory)throw new Me({code:Ze.MISSING_CONFIGURATION,message:"Conversation memory is not enabled",category:"validation",severity:"high",retriable:!1});return await this.conversationMemory.getStats()}async getConversationHistory(e){let t=`history-init-${Date.now()}`;if(await this.initializeConversationMemoryForGeneration(t,Date.now(),process.hrtime.bigint()),!this.conversationMemory)throw new Me({code:Ze.MISSING_CONFIGURATION,message:"Conversation memory is not enabled",category:"validation",severity:"high",retriable:!1});if(!e||typeof e!="string")throw new Me({code:Ze.INVALID_PARAMETERS,message:"Session ID must be a non-empty string",category:"validation",severity:"medium",retriable:!1,context:{sessionId:e}});try{let n=await this.conversationMemory.buildContextMessages(e);return g.debug("Retrieved conversation history",{sessionId:e,messageCount:n.length,turnCount:n.length/2}),n}catch(n){return g.error("Failed to retrieve conversation history",{sessionId:e,error:n instanceof Error?n.message:String(n)}),[]}}async clearConversationSession(e){let t=`clear-session-init-${Date.now()}`;if(await this.initializeConversationMemoryForGeneration(t,Date.now(),process.hrtime.bigint()),!this.conversationMemory)throw new Me({code:Ze.MISSING_CONFIGURATION,message:"Conversation memory is not enabled",category:"validation",severity:"high",retriable:!1});return this.lastCompactionMessageCount.delete(e),await this.conversationMemory.clearSession(e)}async clearAllConversations(){let e=`clear-all-init-${Date.now()}`;if(await this.initializeConversationMemoryForGeneration(e,Date.now(),process.hrtime.bigint()),!this.conversationMemory)throw new Me({code:Ze.MISSING_CONFIGURATION,message:"Conversation memory is not enabled",category:"validation",severity:"high",retriable:!1});this.lastCompactionMessageCount.clear(),await this.conversationMemory.clearAllSessions()}async listSessions(e){let t=`list-sessions-init-${Date.now()}`;if(await this.initializeConversationMemoryForGeneration(t,Date.now(),process.hrtime.bigint()),!this.conversationMemory)throw new Error("Conversation memory is not enabled");if(!this.conversationMemory.listSessions)return g.warn("listSessions not available on current memory manager"),[];let n=3e4;try{let o=await qe(this.conversationMemory.listSessions(e),n,new Error("listSessions operation timed out after 30s"));return g.debug("Listed conversation sessions",{userId:e,sessionCount:o.length}),o}catch(o){return g.error("Failed to list conversation sessions",{userId:e,error:o instanceof Error?o.message:String(o)}),[]}}async exportSession(e,t={}){let n=`export-session-init-${Date.now()}`;if(await this.initializeConversationMemoryForGeneration(n,Date.now(),process.hrtime.bigint()),!this.conversationMemory)throw new Error("Conversation memory is not enabled");if(!e||typeof e!="string")throw new Error("Session ID must be a non-empty string");let o=3e4;try{let s=await qe(this.conversationMemory.buildContextMessages(e),o,new Error("buildContextMessages operation timed out after 30s"));if(s.length===0)return g.debug("No messages found for session export",{sessionId:e}),null;let i=this.conversationMemory.getSession(e),a=await qe(i instanceof Promise?i:Promise.resolve(i),o,new Error("getSession operation timed out after 30s")),c=new Date().toISOString(),l={sessionId:e,title:e,userId:a?.userId,createdAt:a?.createdAt?new Date(a.createdAt).toISOString():c,updatedAt:a?.lastActivity?new Date(a.lastActivity).toISOString():c,messages:s};return t.includeMetadata&&(l.exportMetadata={exportedAt:c,exportFormat:t.format||"json"}),g.debug("Exported conversation session",{sessionId:e,messageCount:s.length}),l}catch(s){return g.error("Failed to export conversation session",{sessionId:e,error:s instanceof Error?s.message:String(s)}),null}}async exportAllSessions(e,t={}){let n=`export-all-init-${Date.now()}`;if(await this.initializeConversationMemoryForGeneration(n,Date.now(),process.hrtime.bigint()),!this.conversationMemory)throw new Error("Conversation memory is not enabled");let o=3e4,s=6e4;try{let i=await qe(this.listSessions(e),o,new Error("listSessions operation timed out after 30s")),a=[];for(let c of i){let l=await qe(this.exportSession(c.id,t),s,new Error(`exportSession operation timed out after 60s for session ${c.id}`));l&&a.push(l)}return g.debug("Exported all conversation sessions",{userId:e,sessionCount:a.length}),a}catch(i){return g.error("Failed to export all conversation sessions",{userId:e,error:i instanceof Error?i.message:String(i)}),[]}}async storeToolExecutions(e,t,n,o,s){let i=n&&n.length>0||o&&o.length>0;if(!i){g.debug("Tool execution storage skipped",{hasToolData:i,toolCallsCount:n?.length||0,toolResultsCount:o?.length||0});return}let a=this.conversationMemory;if(!a?.storeToolExecution){g.debug("Tool execution storage not supported by this memory backend");return}try{await a.storeToolExecution(e,t,n,o,s)}catch(c){g.warn("Failed to store tool executions",{sessionId:e,userId:t,error:c instanceof Error?c.message:String(c)})}}isToolExecutionStorageAvailable(){return typeof this.conversationMemory?.storeToolExecution=="function"}async getSessionMessages(e,t){let n=`get-msgs-init-${Date.now()}`;if(await this.initializeConversationMemoryForGeneration(n,Date.now(),process.hrtime.bigint()),!this.conversationMemory)throw new Me({code:Ze.MISSING_CONFIGURATION,message:"Conversation memory is not enabled",category:"validation",severity:"high",retriable:!1});if(!e||typeof e!="string")throw new Me({code:Ze.INVALID_PARAMETERS,message:"Session ID must be a non-empty string",category:"validation",severity:"medium",retriable:!1,context:{sessionId:e}});return await this.conversationMemory.getSessionMessages(e,t)}async setSessionMessages(e,t,n){let o=`set-msgs-init-${Date.now()}`;if(await this.initializeConversationMemoryForGeneration(o,Date.now(),process.hrtime.bigint()),!this.conversationMemory)throw new Me({code:Ze.MISSING_CONFIGURATION,message:"Conversation memory is not enabled",category:"validation",severity:"high",retriable:!1});if(!e||typeof e!="string")throw new Me({code:Ze.INVALID_PARAMETERS,message:"Session ID must be a non-empty string",category:"validation",severity:"medium",retriable:!1,context:{sessionId:e}});await this.conversationMemory.setSessionMessages(e,t,n)}async modifyLastAssistantMessage(e,t,n){let o=await this.getSessionMessages(e,n);for(let s=o.length-1;s>=0;s--)if(o[s].role==="assistant")return o[s]={...o[s],content:t(o[s].content)},await this.setSessionMessages(e,o,n),!0;return!1}async addExternalMCPServer(e,t){this.invalidateToolCache();try{fe.info(`[NeuroLink] Adding external MCP server: ${e}`,{command:t.command,transport:t.transport});let n=await this.externalServerManager.addServer(e,t);if(n.success){if(fe.info(`[NeuroLink] External MCP server added successfully: ${e}`,{toolsDiscovered:n.metadata?.toolsDiscovered||0,duration:n.duration}),this.mcpEnhancementsConfig?.router?.enabled!==!1){let o=this.externalServerManager.listServers();if(o.length>=2&&!this.mcpToolRouter){this.mcpToolRouter=new Jh({strategy:this.mcpEnhancementsConfig?.router?.strategy??"least-loaded",enableAffinity:this.mcpEnhancementsConfig?.router?.enableAffinity??!1});for(let s of o)this.mcpToolRouter.registerServer(s.id||e);g.debug("[NeuroLink] ToolRouter auto-initialized (2+ external servers)")}else this.mcpToolRouter&&this.mcpToolRouter.registerServer(e)}this.emitter.emit("externalMCP:serverAdded",{serverId:e,serverName:t.name||e,config:t,toolCount:n.metadata?.toolsDiscovered||0,timestamp:Date.now()})}else fe.error(`[NeuroLink] Failed to add external MCP server: ${e}`,{error:n.error,transport:t.transport,command:t.command,url:t.url?sr(t.url):void 0});return n}catch(n){throw fe.error(`[NeuroLink] Error adding external MCP server: ${e}`,n),n}}async removeExternalMCPServer(e){this.invalidateToolCache();try{fe.info(`[NeuroLink] Removing external MCP server: ${e}`);let t=this.externalServerManager.getServerName(e),n=await this.externalServerManager.removeServer(e);return n.success?(fe.info(`[NeuroLink] External MCP server removed successfully: ${e}`),this.emitter.emit("externalMCP:serverRemoved",{serverId:e,serverName:t,timestamp:Date.now()})):n.error?.includes("not found")?fe.debug(`[NeuroLink] Remove skipped \u2014 external MCP server not registered: ${e}`):fe.error(`[NeuroLink] Failed to remove external MCP server: ${e}`,{error:n.error}),n}catch(t){throw fe.error(`[NeuroLink] Error removing external MCP server: ${e}`,t),t}}listExternalMCPServers(){let e=this.externalServerManager.getServerStatuses(),t=this.externalServerManager.listServers();return e.map(n=>{let o=t.find(s=>s.id===n.serverId);return{serverId:n.serverId,status:n.status,toolCount:n.toolCount,uptime:n.performance.uptime,isHealthy:n.isHealthy,config:o||{}}})}getExternalMCPServer(e){return this.externalServerManager.getServer(e)}async executeExternalMCPTool(e,t,n,o){try{fe.debug(`[NeuroLink] Executing external MCP tool: ${t} on ${e}`);let s=this.getToolAnnotationsForExecution(t),i=!!this.mcpToolResultCache&&!this._disableToolCacheForCurrentRequest&&!s?.destructiveHint,a={__serverId:e,__args:n,...this.toolExecutionContext?{__ctx:this.toolExecutionContext}:{}};if(i&&this.mcpToolResultCache){let p=this.mcpToolResultCache.getCachedResult(t,a);if(p!==void 0)return fe.debug(`[NeuroLink] Tool result cache HIT: ${t} on ${e}`),p}let c=await this.externalServerManager.executeTool(e,t,n,o),l=c&&typeof c=="object"?c:void 0,d=!!(l&&"isError"in l&&l.isError===!0||l&&"success"in l&&l.success===!1);return i&&this.mcpToolResultCache&&!d&&c!==void 0&&this.mcpToolResultCache.cacheResult(t,a,c),fe.debug(`[NeuroLink] External MCP tool ${d?"returned error":"executed successfully"}: ${t}`),c}catch(s){throw fe.error(`[NeuroLink] External MCP tool execution failed: ${t}`,s),s}}getExternalMCPTools(){return this.externalServerManager.getAllTools()}getExternalMCPServerTools(e){return this.externalServerManager.getServerTools(e)}async testExternalMCPConnection(e){try{let{MCPClientFactory:t}=await qe(Promise.resolve().then(()=>(Fq(),FVe)),1e4),n=await t.testConnection(e,1e4);return{success:n.success,error:n.error,toolCount:n.capabilities?1:0}}catch(t){return{success:!1,error:t instanceof Error?t.message:String(t)}}}getExternalMCPStatistics(){return this.externalServerManager.getStatistics()}async shutdownExternalMCPServers(){try{fe.info("[NeuroLink] Shutting down all external MCP servers..."),this.unregisterAllExternalMCPToolsFromRegistry(),await this.externalServerManager.shutdown(),fe.info("[NeuroLink] All external MCP servers shut down successfully")}catch(e){throw fe.error("[NeuroLink] Error shutting down external MCP servers:",e),e}}async getElicitationManager(){return(await qe(Promise.resolve().then(()=>(wue(),DWe)),1e4)).globalElicitationManager}async registerElicitationHandler(e){(await this.getElicitationManager()).registerHandler(e)}async getMultiServerManager(){return(await qe(Promise.resolve().then(()=>(oq(),WGe)),1e4)).globalMultiServerManager}async getEnhancedToolDiscovery(){let e=await qe(Promise.resolve().then(()=>(sq(),JGe)),1e4);return new e.EnhancedToolDiscovery(this.toolRegistry)}async getMCPRegistryClient(){return(await qe(Promise.resolve().then(()=>(Rue(),UWe)),1e4)).globalMCPRegistryClient}async exposeAgentAsTool(e,t){return(await qe(Promise.resolve().then(()=>(b4(),Pue)),1e4)).exposeAgentAsTool(e,t)}async exposeWorkflowAsTool(e,t){return(await qe(Promise.resolve().then(()=>(b4(),Pue)),1e4)).exposeWorkflowAsTool(e,t)}async getToolIntegrationManager(){return(await qe(Promise.resolve().then(()=>($ue(),FWe)),1e4)).globalToolIntegrationManager}async convertToolsToMCPFormat(e,t={}){let n=await qe(Promise.resolve().then(()=>(TI(),Pte)),1e4),o=e.map(s=>({...s,execute:s.execute??(async()=>({success:!1,error:"No execute function provided"}))}));return n.batchConvertToMCP(o,t)}async convertToolsFromMCPFormat(e,t={}){return(await qe(Promise.resolve().then(()=>(TI(),Pte)),1e4)).batchConvertToNeuroLink(e,t)}async getToolAnnotations(e){let{inferAnnotations:t,mergeAnnotations:n,getAnnotationSummary:o}=await qe(Promise.resolve().then(()=>(Ww(),KDe)),1e4),s=this.toolRegistry.getToolInfo(e);if(!s)return null;let i=s.tool.annotations,a=t({name:s.tool.name,description:s.tool.description??""}),c=n(a,i);return{annotations:c,summary:o(c)}}convertExternalMCPToolsToAISDKFormat(){let e=this.externalServerManager.getAllTools(),t={};for(let n of e)if(n.isAvailable){let o={description:n.description,execute:async s=>{try{fe.debug(`[NeuroLink] Executing external MCP tool via AI SDK: ${n.name}`,{params:s});let i=await this.externalServerManager.executeTool(n.serverId,n.name,s,{timeout:3e4});return fe.debug(`[NeuroLink] External MCP tool execution result: ${n.name}`,{success:!!i,hasData:!!(i&&typeof i=="object"&&"content"in i)}),i}catch(i){throw fe.error(`[NeuroLink] External MCP tool execution failed: ${n.name}`,i),i}}};t[n.name]=o,fe.debug(`[NeuroLink] Converted external MCP tool to AI SDK format: ${n.name} from server ${n.serverId}`)}return fe.info(`[NeuroLink] Converted ${Object.keys(t).length} external MCP tools to AI SDK format`),t}convertJSONSchemaToAISDKFormat(e){}unregisterExternalMCPToolsFromRegistry(e){try{let t=this.externalServerManager.getServerTools(e);for(let n of t)this.toolRegistry.removeTool(n.name),fe.debug(`[NeuroLink] Unregistered external MCP tool from main registry: ${n.name}`)}catch(t){fe.error(`[NeuroLink] Failed to unregister external MCP tools from registry for server ${e}:`,t)}}unregisterExternalMCPToolFromRegistry(e){try{this.toolRegistry.removeTool(e),fe.debug(`[NeuroLink] Unregistered external MCP tool from main registry: ${e}`)}catch(t){fe.error(`[NeuroLink] Failed to unregister external MCP tool ${e} from registry:`,t)}}async lazyInitializeConversationMemory(e,t,n){try{let{initializeConversationMemory:o}=await qWe().then(()=>GWe),s=await o(this.conversationMemoryConfig);this.conversationMemory=s,this.conversationMemoryNeedsInit=!1}catch(o){throw g.error("[NeuroLink] \u274C LOG_POINT_G005_MEMORY_LAZY_INIT_ERROR",{logPoint:"G005_MEMORY_LAZY_INIT_ERROR",generateInternalId:e,timestamp:new Date().toISOString(),elapsedMs:Date.now()-t,elapsedNs:(process.hrtime.bigint()-n).toString(),error:o instanceof Error?o.message:String(o),errorName:o instanceof Error?o.name:"UnknownError",errorStack:o instanceof Error?o.stack:void 0,message:"Lazy conversation memory initialization failed"}),o}}unregisterAllExternalMCPToolsFromRegistry(){try{let e=this.externalServerManager.getAllTools();for(let t of e)this.toolRegistry.removeTool(t.name);fe.debug(`[NeuroLink] Unregistered ${e.length} external MCP tools from main registry`)}catch(e){fe.error("[NeuroLink] Failed to unregister all external MCP tools from registry:",e)}}async createEvaluationPipeline(e){let{EvaluationPipeline:t,getPreset:n}=await qe(Promise.resolve().then(()=>(YS(),sA)),1e4,ve.evaluationTimeout("evaluation module load",1e4)),o;typeof e=="string"?o=n(e):o=e;let s=new t(o);return await qe(s.initialize(),3e4,ve.evaluationTimeout("pipeline initialization",3e4)),g.debug(`[NeuroLink] Created evaluation pipeline: ${o.name??"custom"}`),s}async evaluate(e,t){let{EvaluationPipeline:n,getPreset:o}=await qe(Promise.resolve().then(()=>(YS(),sA)),1e4,ve.evaluationTimeout("evaluation module load",1e4)),s;if(t?.pipeline&&t?.scorers)throw new Error("Cannot specify both 'pipeline' and 'scorers' options. Use one or the other.");if(t?.scorers&&t.scorers.length===0)throw new Error("The 'scorers' array must not be empty. Provide at least one scorer ID or omit the option to use the default 'quality' preset.");t?.pipeline?s={...o(t.pipeline)}:t?.scorers&&t.scorers.length>0?s={name:"SDK Evaluation",description:"Evaluation from NeuroLink SDK",scorers:t.scorers.map(l=>({id:l})),executionMode:t.executionMode??"parallel",passThreshold:t.passThreshold??.7}:s=o("quality"),t?.passThreshold!==void 0&&(s.passThreshold=t.passThreshold),t?.executionMode!==void 0&&(s.executionMode=t.executionMode);let i=new n(s);await qe(i.initialize(),3e4,ve.evaluationTimeout("pipeline initialization",3e4));let a=t?.timeoutMs??6e4,c=await qe(i.execute(e,{correlationId:t?.correlationId}),a,ve.evaluationTimeout("pipeline execution",a));return g.debug("[NeuroLink] Evaluation completed",{pipeline:s.name,overallScore:c.overallScore,passed:c.passed,scorerCount:c.scores.length}),c}async score(e,t,n){let{ScorerRegistry:o}=await qe(Promise.resolve().then(()=>(Q$(),IZ)),1e4,ve.evaluationTimeout("scorer module load",1e4));await qe(o.registerBuiltInScorers(),3e4,ve.evaluationTimeout("scorer bootstrap",3e4));let s=await qe(o.getScorer(e,n),3e4,ve.evaluationTimeout(`scorer load: ${e}`,3e4));if(!s)throw ve.scorerNotFound(e);let i=s.validateInput(t);if(!i.valid)throw ve.evaluationValidationFailed(e,i.errors);let a=await qe(s.score(t),6e4,ve.evaluationTimeout("scorer execution",6e4));return g.debug("[NeuroLink] Scoring completed",{scorerId:e,score:a.score,passed:a.passed,computeTime:a.computeTime}),a}async getAvailableScorers(e){let{ScorerRegistry:t}=await qe(Promise.resolve().then(()=>(Q$(),IZ)),1e4,ve.evaluationTimeout("scorer module load",1e4));await qe(t.registerBuiltInScorers(),3e4,ve.evaluationTimeout("scorer bootstrap",3e4));let n=t.list();return e?.category&&(n=n.filter(o=>o.category===e.category)),e?.type&&(n=n.filter(o=>o.type===e.type)),n}async getEvaluationPresets(){let{getPresetNames:e}=await qe(Promise.resolve().then(()=>(YS(),sA)),1e4,ve.evaluationTimeout("evaluation module load",1e4));return e()}async getEvaluationPreset(e){let{getPreset:t}=await qe(Promise.resolve().then(()=>(YS(),sA)),1e4,ve.evaluationTimeout("evaluation module load",1e4));return t(e)}async createAgent(e){let{Agent:t}=await Promise.resolve().then(()=>(w4(),VWe));return g.debug("[NeuroLink] Creating agent",{id:e.id,name:e.name,tools:e.tools?.length||0}),new t(e,this)}async createNetwork(e){let{AgentNetwork:t}=await Promise.resolve().then(()=>(zue(),HWe));return g.debug("[NeuroLink] Creating agent network",{name:e.name,agentCount:e.agents.length,workflowCount:e.workflows?.length||0,toolCount:e.tools?.length||0}),new t(e,this)}createWorkerInstance(e){let t=e?.logTag??"worker",n=this.emitter,o=e?.config??{},s={...this.credentials?{credentials:this.credentials}:{},...o,conversationMemory:{enabled:!1},enableOrchestration:!1,observability:{...this.observabilityConfig??{},langfuse:{...this.observabilityConfig?.langfuse??{},autoDetectExternalProvider:!0,skipLangfuseSpanProcessor:!0}},...e?.shareToolRegistry!==!1&&{toolRegistry:this.toolRegistry}},i=new r(s);if(g.setEventEmitter(n),e?.onLog){let a=e.onLog,c=d=>{try{let p=d??{};a({tag:t,level:String(p.level??"info"),message:String(p.message??""),timestamp:typeof p.timestamp=="number"?p.timestamp:Date.now(),data:p.data})}catch{}};n.on("log-event",c);let l=i.dispose.bind(i);i.dispose=async()=>{n.off("log-event",c),await l()}}return g.debug("[NeuroLink] Created worker instance",{tag:t,sharedToolRegistry:e?.shareToolRegistry!==!1}),i}async runIsolatedAgent(e,t,n){let{runIsolatedAgent:o}=await Promise.resolve().then(()=>(KM(),JV));return o(this,e,t,n)}async continueAgent(e,t){let{continueIsolatedAgent:n}=await Promise.resolve().then(()=>(KM(),JV));return n(this,e,t)}async stopAgent(e){let{stopIsolatedAgent:t}=await Promise.resolve().then(()=>(KM(),JV));return t(this,e)}async registerAgentTool(e,t){let{registerAgentTool:n}=await Promise.resolve().then(()=>(XM(),XV)),o=n(this,e,t);return this.hasAgentTools=!0,o}async executeNetwork(e,t,n){return g.debug("[NeuroLink] Executing agent network",{networkId:e.id,networkName:e.name,hasContext:!!t.context}),e.execute(t,n)}async*streamNetwork(e,t,n){g.debug("[NeuroLink] Streaming agent network",{networkId:e.id,networkName:e.name,hasContext:!!t.context}),yield*e.stream(t,n)}async createOrchestrator(e){let{NetworkOrchestrator:t}=await Promise.resolve().then(()=>(que(),JWe));return g.debug("[NeuroLink] Creating network orchestrator",{maxConcurrentExecutions:e?.maxConcurrentExecutions,defaultMode:e?.defaultMode}),new t(this,e)}async createCoordinator(e){let{AgentCoordinator:t}=await Promise.resolve().then(()=>(Vue(),ZWe));return g.debug("[NeuroLink] Creating agent coordinator",{strategy:e?.strategy,maxConcurrency:e?.maxConcurrency}),new t(e)}async createMessageBus(e){let{MessageBus:t}=await Promise.resolve().then(()=>(Hue(),QWe));return g.debug("[NeuroLink] Creating message bus",{maxHistorySize:e?.maxHistorySize}),new t(e)}async dispose(){g.debug("[NeuroLink] Starting disposal of resources..."),this.lastCompactionMessageCount.clear();let e=[];try{try{g.debug("[NeuroLink] Flushing and shutting down OpenTelemetry..."),await tI(),await rI(),g.debug("[NeuroLink] OpenTelemetry shutdown successfully")}catch(t){let n=t instanceof Error?t:new Error(`OpenTelemetry shutdown error: ${String(t)}`);e.push(n),g.warn("[NeuroLink] Error shutting down OpenTelemetry:",t)}if(this.externalServerManager)try{g.debug("[NeuroLink] Shutting down external MCP servers..."),await this.externalServerManager.shutdown(),g.debug("[NeuroLink] External MCP servers shutdown successfully")}catch(t){let n=t instanceof Error?t:new Error(`External server shutdown error: ${String(t)}`);e.push(n),g.warn("[NeuroLink] Error shutting down external MCP servers:",t)}if(this.emitter)try{g.debug("[NeuroLink] Removing all event listeners..."),this.emitter.removeAllListeners(),g.clearEventEmitter(this.emitter),g.debug("[NeuroLink] Event listeners removed successfully")}catch(t){let n=t instanceof Error?t:new Error(`Event emitter cleanup error: ${String(t)}`);e.push(n),g.warn("[NeuroLink] Error removing event listeners:",t)}if(this.toolCircuitBreakers&&this.toolCircuitBreakers.size>0)try{g.debug(`[NeuroLink] Clearing ${this.toolCircuitBreakers.size} circuit breakers...`),this.toolCircuitBreakers.clear(),g.debug("[NeuroLink] Circuit breakers cleared successfully")}catch(t){let n=t instanceof Error?t:new Error(`Circuit breaker cleanup error: ${String(t)}`);e.push(n),g.warn("[NeuroLink] Error clearing circuit breakers:",t)}try{g.debug("[NeuroLink] Clearing maps and caches..."),this.toolExecutionMetrics&&this.toolExecutionMetrics.clear(),this.activeToolExecutions&&this.activeToolExecutions.clear(),this.currentStreamToolExecutions&&(this.currentStreamToolExecutions.length=0),this.toolExecutionHistory&&(this.toolExecutionHistory.length=0),this.toolCache&&(this.toolCache.tools=[],this.toolCache.timestamp=0),this.mcpToolResultCache?.destroy(),this.mcpToolRouter?.destroy(),this.mcpToolBatcher?.destroy(),this.mcpToolResultCache=void 0,this.mcpToolRouter=void 0,this.mcpToolBatcher=void 0,this.mcpEnhancedDiscovery=void 0,this.mcpToolMiddlewares=[],g.debug("[NeuroLink] Maps and caches cleared successfully")}catch(t){let n=t instanceof Error?t:new Error(`Cache cleanup error: ${String(t)}`);e.push(n),g.warn("[NeuroLink] Error clearing caches:",t)}if(this._taskManager)try{g.debug("[NeuroLink] Shutting down TaskManager..."),await qe(this._taskManager.shutdown(),5e3,new Error("TaskManager shutdown timed out"))}catch(t){g.warn("[NeuroLink] TaskManager shutdown error:",t)}finally{this._taskManager=void 0}try{g.debug("[NeuroLink] Resetting initialization state..."),this.mcpInitialized=!1,this.mcpInitPromise=null,this.conversationMemoryNeedsInit=!1,this.credentials=void 0,g.debug("[NeuroLink] Initialization state reset successfully")}catch(t){let n=t instanceof Error?t:new Error(`State reset error: ${String(t)}`);e.push(n),g.warn("[NeuroLink] Error resetting state:",t)}e.length===0?g.debug("[NeuroLink] \u2705 Resource disposal completed successfully"):g.warn(`[NeuroLink] \u26A0\uFE0F Resource disposal completed with ${e.length} errors`,{errors:e.map(t=>t.message)})}catch(t){throw g.error("[NeuroLink] Critical error during disposal:",t),t}}getToolRegistry(){return this.toolRegistry}async compactSession(e,t){if(!this.conversationMemory)return null;let n=await this.conversationMemory.buildContextMessages(e);if(!n||n.length===0)return null;let o=new Fh({...t,summarizationProvider:t?.summarizationProvider??this.conversationMemoryConfig?.conversationMemory?.summarizationProvider,summarizationModel:t?.summarizationModel??this.conversationMemoryConfig?.conversationMemory?.summarizationModel}),s=Cc({provider:t?.provider||"openai",conversationMessages:n}),i=Math.floor(s.availableInputTokens*.6),a=await o.compact(n,i,this.conversationMemoryConfig?.conversationMemory);return a.compacted&&Uh(a.messages),a}async getContextStats(e,t,n){if(!this.conversationMemory)return null;let o=await this.conversationMemory.buildContextMessages(e);if(!o||o.length===0)return null;let s=Cc({provider:t||"openai",model:n,conversationMessages:o});return{estimatedInputTokens:s.estimatedInputTokens,availableInputTokens:s.availableInputTokens,usageRatio:s.usageRatio,shouldCompact:s.shouldCompact,messageCount:o.length}}needsCompaction(e,t,n){if(!this.conversationMemory)return!1;let o=this.conversationMemory.getSession?.(e);return o?Cc({provider:t||"openai",model:n,conversationMessages:o.messages}).shouldCompact:!1}async setAuthProvider(e){this.authInitPromise=void 0,await this.initializeAuthProviderFromConfig(e)}async initializeAuthProviderFromConfig(e){let t,n;if("authenticateToken"in e&&typeof e.authenticateToken=="function")t=e,n=t.type;else if("provider"in e)t=e.provider,n=t.type;else{let o=e,{AuthProviderFactory:s}=await Promise.resolve().then(()=>(pO(),e3e));t=await s.createProvider(o.type,o.config),n=o.type}this.authProvider=t,g.info(`Auth provider set: ${n}`),this.emitter.emit("auth:provider:set",{type:t.type,timestamp:Date.now()})}getAuthProvider(){return this.authProvider}async ensureAuthProvider(){if(this.authProvider||!this.pendingAuthConfig)return;let e=this.pendingAuthConfig;this.authInitPromise??=(async()=>{try{await this.initializeAuthProviderFromConfig(e),this.pendingAuthConfig=void 0}finally{this.authInitPromise&&(this.pendingAuthConfig===void 0||this.pendingAuthConfig===e)&&(this.authInitPromise=void 0)}})(),await this.authInitPromise}async setAuthContext(e){let{globalAuthContext:t}=await Promise.resolve().then(()=>(EE(),Kq));t.set(e),g.debug("Auth context set",{userId:e.user.id,provider:e.provider,sessionId:e.session?.id})}async getAuthContext(){let{getAuthContext:e}=await Promise.resolve().then(()=>(EE(),Kq));return e()}async clearAuthContext(){let{globalAuthContext:e}=await Promise.resolve().then(()=>(EE(),Kq)),t=e.get()?.user.id;e.clear(),t&&g.debug(`Auth context cleared for user: ${t}`)}getExternalServerManager(){return this.externalServerManager}buildResolutionContext(e,t){return{requestContext:t||{},signal:e}}async resolveDynamicOptions(e){let t=["model","provider","temperature","maxTokens","systemPrompt","timeout","thinkingLevel","disableTools","enableAnalytics","enableEvaluation"];if(!(t.some(s=>typeof e[s]=="function")||typeof e.tools=="function"))return;let o=e.dynamicContext;await this.resolveDynamicFields(e,t,o)}async resolveDynamicFields(e,t,n){let o=this.buildResolutionContext(e.abortSignal,n);if(g.debug("[NeuroLink] Resolving dynamic arguments"),await Promise.all(t.map(async s=>{if(typeof e[s]=="function"){let i=await eV(e[s],o);e[s]=i.value,g.debug(`[NeuroLink] Resolved dynamic ${s}: ${i.resolutionType}`)}})),typeof e.tools=="function"){let s=await eV(e.tools,o);if(!Array.isArray(s.value))throw new TypeError(`Dynamic tools resolver must return string[] (tool names), got ${typeof s.value=="object"?"object":typeof s.value}`);e.enabledToolNames=s.value,delete e.tools}}},o3e=new fb,ekr=o3e});var i3e={};ue(i3e,{VoyageProvider:()=>C4,default:()=>nkr});var tkr,s3e,rkr,Jue,C4,nkr,a3e=E(async()=>{"use strict";$l();await Fd();Dn();Pt();St();W();an();tkr="https://api.voyageai.com/v1",s3e=6e4,rkr=()=>Ht(kDe()),Jue=()=>Kt("VOYAGE_MODEL","voyage-3.5"),C4=class extends no{apiKey;baseURL;proxyFetch;constructor(e,t,n,o){let s=Zl(t)?t:void 0;super(e,"voyage",s);let i=o?.apiKey?.trim();this.apiKey=i&&i.length>0?i:rkr(),this.baseURL=o?.baseURL??process.env.VOYAGE_BASE_URL??tkr,this.proxyFetch=gt(),g.debug("Voyage Provider initialized (embeddings only)",{modelName:this.modelName,baseURL:this.baseURL})}getProviderName(){return this.providerName}getDefaultModel(){return Jue()}supportsTools(){return!1}getDefaultEmbeddingModel(){return Jue()}getAISDKModel(){throw new We("Voyage AI is an embedding-only provider; chat completions are not available. Use `embed()` or `embedMany()` instead, or pick a different provider for `generate()` / `stream()`.","voyage")}async executeStream(e,t){throw new We("Voyage AI is an embedding-only provider; streaming chat is not available. Use `embed()` / `embedMany()`, or pick another provider for `stream()`.","voyage")}formatProviderError(e){let t=e instanceof Error?e.message:typeof e=="string"?e:"Unknown error";return t.includes("401")||t.toLowerCase().includes("unauthorized")||t.includes("invalid_api_key")?new It("Invalid Voyage AI API key. Get one at https://dash.voyageai.com/api-keys","voyage"):t.includes("429")||t.toLowerCase().includes("rate limit")?new Yt("Voyage AI rate limit exceeded. Back off and retry.","voyage"):t.includes("404")||t.toLowerCase().includes("model_not_found")?new qt(`Voyage AI model '${this.modelName}' not found. Browse https://docs.voyageai.com/docs/embeddings`,"voyage"):new We(`Voyage AI error: ${t}`,"voyage")}async embed(e,t){let n=await this.callEmbeddings([e],t);if(!n[0])throw new We("Voyage AI returned no embedding for the provided text","voyage");return n[0]}async embedMany(e,t){if(e.length===0)return[];let n=128,o=[];for(let s=0;s<e.length;s+=n){let i=e.slice(s,s+n),a=await this.callEmbeddings(i,t);o.push(...a)}return o}async callEmbeddings(e,t){let n=t??this.modelName,o;try{o=await qe(this.proxyFetch(`${this.baseURL}/embeddings`,{method:"POST",headers:{Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify({input:e,model:n})}),s3e,new We(`Voyage embeddings request timed out after ${s3e/1e3}s`,"voyage"))}catch(a){throw a instanceof We?a:this.formatProviderError(a)}if(!o.ok){let a=await o.text();throw this.formatProviderError(new Error(`Voyage embeddings failed: ${o.status} \u2014 ${a}`))}let s=await o.json();if(!s.data||s.data.length===0)throw new We("Voyage embeddings response missing data","voyage");if(s.data.length!==e.length)throw new We(`Voyage embeddings response count mismatch: expected ${e.length}, got ${s.data.length}`,"voyage");let i=s.data.slice().sort((a,c)=>a.index-c.index);for(let a=0;a<i.length;a++)if(i[a].index!==a)throw new We(`Voyage embeddings response has unexpected index ordering: position ${a} has index ${i[a].index}`,"voyage");return i.map(a=>a.embedding)}async validateConfiguration(){return typeof this.apiKey=="string"&&this.apiKey.trim().length>0}getConfiguration(){return{provider:this.providerName,model:this.modelName,defaultModel:Jue(),baseURL:this.baseURL}}},nkr=C4});var c3e={};ue(c3e,{JinaProvider:()=>k4,default:()=>ikr});var okr,R4,skr,Yue,k4,ikr,l3e=E(async()=>{"use strict";$l();await Fd();Dn();Pt();W();an();okr="https://api.jina.ai/v1",R4=6e4,skr=()=>Ht(ADe()),Yue=()=>Kt("JINA_MODEL","jina-embeddings-v3"),k4=class extends no{apiKey;baseURL;proxyFetch;constructor(e,t,n,o){let s=Zl(t)?t:void 0;super(e,"jina",s);let i=o?.apiKey?.trim();this.apiKey=i&&i.length>0?i:skr(),this.baseURL=o?.baseURL??process.env.JINA_BASE_URL??okr,this.proxyFetch=gt(),g.debug("Jina Provider initialized (embeddings + reranking)",{modelName:this.modelName,baseURL:this.baseURL})}getProviderName(){return this.providerName}getDefaultModel(){return Yue()}supportsTools(){return!1}getDefaultEmbeddingModel(){return Yue()}getAISDKModel(){throw new Error("Jina AI is an embeddings + reranking provider; chat completions are not available. Use `embed()` / `embedMany()` / `rerank()`.")}async executeStream(e,t){throw new Error("Jina AI is an embeddings + reranking provider; streaming chat is not available.")}formatProviderError(e){let t=e instanceof Error?e.message:typeof e=="string"?e:"Unknown error";return t.includes("401")||t.toLowerCase().includes("unauthorized")?new It("Invalid Jina AI API key. Get one at https://jina.ai/?sui=apikey","jina"):t.includes("429")||t.toLowerCase().includes("rate limit")?new Yt("Jina AI rate limit exceeded. Back off and retry.","jina"):t.includes("404")||t.toLowerCase().includes("model_not_found")?new qt(`Jina AI model '${this.modelName}' not found. See https://jina.ai/embeddings/`,"jina"):new We(`Jina AI error: ${t}`,"jina")}async embed(e,t){let n=await this.callEmbeddings([e],t);if(!n[0])throw new Error("Jina AI returned no embedding for the provided text");return n[0]}async embedMany(e,t){return e.length===0?[]:this.callEmbeddings(e,t)}async rerank(e,t,n={}){if(t.length===0)return[];let o=n.model??"jina-reranker-v2-base-multilingual",s=n.credentials,i=s?.apiKey?.trim()||this.apiKey,a=s?.baseURL||this.baseURL,c=new AbortController,l=setTimeout(()=>c.abort(),R4),d;try{d=await this.proxyFetch(`${a}/rerank`,{method:"POST",headers:{Authorization:`Bearer ${i}`,"Content-Type":"application/json"},body:JSON.stringify({model:o,query:e,documents:t,top_n:n.topN??t.length}),signal:c.signal})}catch(m){throw m instanceof Error&&m.name==="AbortError"?this.formatProviderError(new Error(`Jina rerank request timed out after ${R4/1e3}s`)):this.formatProviderError(m)}finally{clearTimeout(l)}if(!d.ok){let m=await d.text();throw this.formatProviderError(new Error(`Jina rerank failed: ${d.status} \u2014 ${m}`))}return((await d.json()).results??[]).map(m=>({index:m.index,score:m.relevance_score,document:t[m.index]??m.document?.text??""}))}async callEmbeddings(e,t,n){let o=t??this.modelName,s=n?.apiKey?.trim()||this.apiKey,i=n?.baseURL||this.baseURL,a=new AbortController,c=setTimeout(()=>a.abort(),R4),l;try{l=await this.proxyFetch(`${i}/embeddings`,{method:"POST",headers:{Authorization:`Bearer ${s}`,"Content-Type":"application/json"},body:JSON.stringify({input:e,model:o}),signal:a.signal})}catch(m){throw m instanceof Error&&m.name==="AbortError"?this.formatProviderError(new Error(`Jina embeddings request timed out after ${R4/1e3}s`)):this.formatProviderError(m)}finally{clearTimeout(c)}if(!l.ok){let m=await l.text();throw this.formatProviderError(new Error(`Jina embeddings failed: ${l.status} \u2014 ${m}`))}let d=await l.json();if(!d.data||d.data.length===0)throw new Error("Jina embeddings response missing data");if(d.data.length!==e.length)throw new Error(`Jina embeddings response count mismatch: expected ${e.length}, got ${d.data.length}`);let p=d.data.slice().sort((m,f)=>m.index-f.index);for(let m=0;m<p.length;m++)if(p[m].index!==m)throw new Error(`Jina embeddings response has unexpected index ordering: position ${m} has index ${p[m].index}`);return p.map(m=>m.embedding)}async validateConfiguration(){return typeof this.apiKey=="string"&&this.apiKey.trim().length>0}getConfiguration(){return{provider:this.providerName,model:this.modelName,defaultModel:Yue(),baseURL:this.baseURL}}},ikr=k4});var p3e={};ue(p3e,{StabilityProvider:()=>A4,default:()=>lkr});var akr,u3e,ckr,d3e,A4,lkr,m3e=E(async()=>{"use strict";$l();await Fd();Dn();Pt();W();an();akr="https://api.stability.ai",u3e=12e4,ckr=()=>(process.env.STABILITY_API_KEY??process.env.STABILITY_AI_API_KEY??"").trim()||void 0,d3e=()=>Kt("STABILITY_MODEL","stable-image-ultra"),A4=class extends no{apiKey;baseURL;proxyFetch;constructor(e,t,n,o){let s=Zl(t)?t:void 0;super(e,"stability",s);let i=o?.apiKey?.trim();this.apiKey=i&&i.length>0?i:ckr(),this.baseURL=o?.baseURL??process.env.STABILITY_BASE_URL??akr,this.proxyFetch=gt(),g.debug("Stability AI Provider initialized (image-gen only)",{modelName:this.modelName,baseURL:this.baseURL})}getProviderName(){return this.providerName}getDefaultModel(){return d3e()}supportsTools(){return!1}getAISDKModel(){throw new Error("Stability AI is an image-generation-only provider; chat completions are not available.")}async executeStream(e,t){throw new Error("Stability AI is an image-generation-only provider; streaming chat is not available. Use generate({output:{format:'binary'}}) with a Stable Image / SD 3.5 model.")}formatProviderError(e){let t=e instanceof Error?e.message:typeof e=="string"?e:"Unknown error";return t.includes("401")||t.toLowerCase().includes("unauthorized")?new It("Invalid Stability AI API key. Get one at https://platform.stability.ai/account/keys","stability"):t.includes("429")||t.toLowerCase().includes("rate limit")?new Yt("Stability AI rate limit exceeded. Back off and retry.","stability"):t.includes("content_filtered")||t.includes("CONTENT_FILTERED")?new We("Stability AI declined the request due to content policy. Adjust the prompt and retry.","stability"):t.includes("404")?new qt(`Stability AI model '${this.modelName}' not found. Use stable-image-ultra, stable-image-core, sd3.5-large, sd3.5-large-turbo, or sd3.5-medium.`,"stability"):new We(`Stability AI error: ${t}`,"stability")}async executeImageGeneration(e){let t=Date.now(),n=e.credentials?.stability,o=n?.apiKey?.trim()||this.apiKey;if(!o)throw new Error("Stability AI API key is required. Set STABILITY_API_KEY or pass credentials.stability.apiKey per-call.");let s=o,i=n?.baseURL||this.baseURL,a=e.prompt??e.input?.text??"";if(!a.trim())throw new Error("Stability AI image generation requires a prompt (input.text or prompt)");let c=this.modelName.startsWith("sd3.5-")?"sd3":this.modelName==="stable-image-ultra"?"ultra":this.modelName==="stable-image-core"?"core":this.modelName,l=e,d=new FormData;d.append("prompt",a),d.append("output_format","png"),l.aspectRatio&&d.append("aspect_ratio",String(l.aspectRatio)),l.negativePrompt&&d.append("negative_prompt",l.negativePrompt),this.modelName.startsWith("sd3.5-")&&d.append("model",this.modelName),l.seed!==void 0&&d.append("seed",String(l.seed));let p=new AbortController,m=setTimeout(()=>p.abort(),u3e),f;try{f=await this.proxyFetch(`${i}/v2beta/stable-image/generate/${c}`,{method:"POST",headers:{Authorization:`Bearer ${s}`,Accept:"application/json"},body:d,signal:p.signal})}catch(v){throw v instanceof Error&&v.name==="AbortError"?this.formatProviderError(new Error(`Stability image-gen request timed out after ${u3e/1e3}s`)):this.formatProviderError(v)}finally{clearTimeout(m)}if(!f.ok){let v=await f.text();throw this.formatProviderError(new Error(`Stability image-gen failed: ${f.status} \u2014 ${v}`))}let h=await f.json();if(!h.image)throw new Error(`Stability AI returned no image (finish_reason: ${h.finish_reason??"unknown"})`);let y=Date.now()-t;return g.info(`[StabilityProvider] Generated image (${h.image.length} base64 chars) in ${y}ms \u2014 model ${this.modelName}`),{content:a,provider:this.providerName,model:this.modelName,usage:{input:0,output:1e3,total:1e3},imageOutput:{base64:h.image}}}async validateConfiguration(){return this.apiKey!==void 0&&this.apiKey.trim().length>0}getConfiguration(){return{provider:this.providerName,model:this.modelName,defaultModel:d3e(),baseURL:this.baseURL}}},lkr=A4});var h3e={};ue(h3e,{IdeogramProvider:()=>I4,default:()=>pkr});var ukr,g3e,dkr,f3e,I4,pkr,y3e=E(async()=>{"use strict";$l();await Fd();Dn();Pt();W();an();ukr="https://api.ideogram.ai",g3e=12e4,dkr=()=>Ht(IDe()),f3e=()=>Kt("IDEOGRAM_MODEL","V_3"),I4=class extends no{apiKey;baseURL;proxyFetch;constructor(e,t,n,o){let s=Zl(t)?t:void 0;super(e,"ideogram",s);let i=o?.apiKey?.trim();this.apiKey=i&&i.length>0?i:dkr(),this.baseURL=o?.baseURL??process.env.IDEOGRAM_BASE_URL??ukr,this.proxyFetch=gt(),g.debug("Ideogram Provider initialized (image-gen only)",{modelName:this.modelName,baseURL:this.baseURL})}getProviderName(){return this.providerName}getDefaultModel(){return f3e()}supportsTools(){return!1}getAISDKModel(){throw new Error("Ideogram is an image-generation-only provider; chat completions are not available.")}async executeStream(e,t){throw new Error("Ideogram is an image-generation-only provider; streaming chat is not available.")}formatProviderError(e){let t=e instanceof Error?e.message:typeof e=="string"?e:"Unknown error";return t.includes("401")||t.toLowerCase().includes("unauthorized")?new It("Invalid Ideogram API key. Get one at https://developer.ideogram.ai/","ideogram"):t.includes("429")||t.toLowerCase().includes("rate limit")?new Yt("Ideogram rate limit exceeded. Back off and retry.","ideogram"):t.includes("safety")||t.includes("is_image_safe")?new We("Ideogram declined the request due to safety filters. Adjust the prompt and retry.","ideogram"):new We(`Ideogram error: ${t}`,"ideogram")}async executeImageGeneration(e){let t=Date.now(),n=e.credentials?.ideogram,o=n?.apiKey?.trim()||this.apiKey,s=n?.baseURL||this.baseURL,i=e.prompt??e.input?.text??"";if(!i.trim())throw new Error("Ideogram image generation requires a prompt (input.text or prompt)");let a=e,c={prompt:i,model:this.modelName,magic_prompt:a.magicPrompt??"AUTO"};a.aspectRatio&&(c.aspect_ratio=a.aspectRatio),a.negativePrompt&&(c.negative_prompt=a.negativePrompt),a.seed!==void 0&&(c.seed=a.seed),a.style&&(c.style_type=a.style);let l=new AbortController,d=setTimeout(()=>l.abort(),g3e),p;try{p=await this.proxyFetch(`${s}/v1/ideogram-v3/generate`,{method:"POST",headers:{"Api-Key":o,"Content-Type":"application/json"},body:JSON.stringify(c),signal:l.signal})}catch(C){throw C instanceof Error&&C.name==="AbortError"?this.formatProviderError(new Error(`Ideogram image-gen request timed out after ${g3e/1e3}s`)):this.formatProviderError(C)}finally{clearTimeout(d)}if(!p.ok){let C=await p.text();throw this.formatProviderError(new Error(`Ideogram image-gen failed: ${p.status} \u2014 ${C}`))}let f=(await p.json()).data?.[0]?.url;if(!f)throw new Error("Ideogram returned no image URL");let h=new AbortController,y=setTimeout(()=>h.abort(),6e4),v;try{v=await this.proxyFetch(f,{signal:h.signal})}catch(C){throw C instanceof Error&&C.name==="AbortError"?new Error("Ideogram image download timed out after 60s",{cause:C}):C}finally{clearTimeout(y)}if(!v.ok)throw new Error(`Failed to download Ideogram image: ${v.status}`);let b=Buffer.from(await v.arrayBuffer()),S=b.toString("base64"),w=Date.now()-t;return g.info(`[IdeogramProvider] Generated image (${b.length} bytes) in ${w}ms \u2014 model ${this.modelName}`),{content:i,provider:this.providerName,model:this.modelName,usage:{input:0,output:1e3,total:1e3},imageOutput:{base64:S}}}async validateConfiguration(){return typeof this.apiKey=="string"&&this.apiKey.trim().length>0}getConfiguration(){return{provider:this.providerName,model:this.modelName,defaultModel:f3e(),baseURL:this.baseURL}}},pkr=I4});function $u(r){let e=(r?.apiToken??process.env.REPLICATE_API_TOKEN??"").trim();return e?{apiToken:e,baseUrl:(r?.baseUrl??process.env.REPLICATE_BASE_URL??mkr).replace(/\/$/,"")}:null}var mkr,mO=E(()=>{"use strict";mkr="https://api.replicate.com"});function fkr(r,e){let t=e[0];if(!t)throw new Error(`safeFetch: no validated addresses to pin for "${r}"`);return new OA({connect:{lookup:(n,o,s)=>{if(n.toLowerCase()!==r.toLowerCase()){s(new Error(`safeFetch: refusing to resolve "${n}" \u2014 expected "${r}"`),"",0);return}if(o?.all){s(null,e.map(i=>({address:i.ip,family:i.family})));return}s(null,t.ip,t.family)}}})}function hkr(r){if(typeof r!="object"||r===null)return!1;let e=r;return typeof e.arrayBuffer=="function"&&typeof e.headers=="object"&&e.headers!==null&&typeof e.headers.get=="function"}async function cy(r,e){let{url:t,addresses:n}=await HDe(r),s=new URL(t).hostname.replace(/^\[|\]$/g,""),i=fkr(s,n),a=new AbortController,c=setTimeout(()=>a.abort(),e.timeoutMs??gkr),l=e.signal?AbortSignal.any([e.signal,a.signal]):a.signal,d;try{d=await Y7(t,{method:"GET",signal:l,redirect:"manual",dispatcher:i})}finally{clearTimeout(c),i.close().catch(()=>{})}if(d.status>=300&&d.status<400)throw new Error(`safeDownload(${e.label}): refused to follow redirect ${d.status} \u2192 ${d.headers.get("location")??"<no-location>"} (for ${r})`);if(!d.ok)throw new Error(`safeDownload(${e.label}) failed: HTTP ${d.status} for ${r}`);if(!hkr(d))throw new Error(`safeDownload(${e.label}): response is missing headers.get()/arrayBuffer()`);return ha(d,e.maxBytes,e.label)}var gkr,gO=E(()=>{"use strict";Jv();Zm();Sh();gkr=6e4});async function xkr(r,e,t){let n=r.baseUrl??"https://api.replicate.com",[o,s]=e.model.split(":",2),i=s?`${n}/v1/predictions`:`${n}/v1/models/${o}/predictions`,a=s?{version:s,input:e.input}:{input:e.input};return e.webhook&&(a.webhook=e.webhook),e.webhookEventsFilter&&e.webhookEventsFilter.length>0&&(a.webhook_events_filter=e.webhookEventsFilter),tw(async()=>{let c=new AbortController,l=setTimeout(()=>c.abort(),fO);try{let d=await fetch(i,{method:"POST",headers:{Authorization:`Token ${r.apiToken}`,"Content-Type":"application/json",Prefer:"wait=60"},body:JSON.stringify(a),signal:c.signal});if(!d.ok){let p=await d.text();throw new Me({code:Ze.PROVIDER_NOT_AVAILABLE,message:`Replicate predictions submit failed: ${d.status} \u2014 ${Wn(p,500)}`,category:"network",severity:"high",retriable:d.status>=500||d.status===429,retryAfterMs:Wf(d.headers)})}return await d.json()}catch(d){throw d instanceof Me?d:d instanceof Error&&d.name==="AbortError"?new Me({code:Ze.OPERATION_ABORTED,message:`Replicate predictions submit timed out after ${fO/1e3}s`,category:"timeout",severity:"high",retriable:!0,originalError:d}):d}finally{clearTimeout(l)}},void 0,"Replicate prediction submission",t)}async function bkr(r,e,t={}){let n=r.baseUrl??"https://api.replicate.com",o=Date.now(),s=t.timeoutMs??vkr,i=t.pollIntervalMs??ykr;for(;Date.now()-o<s;){if(t.abortSignal?.aborted)throw new Me({code:Ze.OPERATION_ABORTED,message:"Replicate poll aborted by caller",category:"abort",severity:"low",retriable:!1});let a=new AbortController,c=setTimeout(()=>a.abort(),fO),l=()=>a.abort();t.abortSignal?.addEventListener("abort",l,{once:!0});let d;try{d=await fetch(`${n}/v1/predictions/${e}`,{method:"GET",headers:{Authorization:`Token ${r.apiToken}`},signal:a.signal})}catch(m){throw m instanceof Me?m:m instanceof Error&&m.name==="AbortError"?t.abortSignal?.aborted?new Me({code:Ze.OPERATION_ABORTED,message:"Replicate poll aborted by caller",category:"abort",severity:"low",retriable:!1,originalError:m}):new Me({code:Ze.OPERATION_ABORTED,message:`Replicate poll request timed out after ${fO/1e3}s`,category:"timeout",severity:"high",retriable:!0,originalError:m}):m}finally{t.abortSignal?.removeEventListener("abort",l),clearTimeout(c)}if(!d.ok){let m=await d.text();throw new Me({code:Ze.PROVIDER_NOT_AVAILABLE,message:`Replicate poll failed: ${d.status} \u2014 ${Wn(m,500)}`,category:"network",severity:"high",retriable:d.status>=500||d.status===429,retryAfterMs:Wf(d.headers)})}let p=await d.json();if(p.status==="succeeded")return p;if(p.status==="failed"||p.status==="canceled")throw new Me({code:Ze.PROVIDER_NOT_AVAILABLE,message:`Replicate prediction ${p.id} ${p.status}: ${p.error??"unknown"}`,category:"execution",severity:"high",retriable:p.status==="failed"});await new Promise((m,f)=>{let h=()=>{clearTimeout(y),f(new Me({code:Ze.OPERATION_ABORTED,message:"Replicate poll aborted by caller",category:"abort",severity:"low",retriable:!1}))},y=setTimeout(()=>{t.abortSignal?.removeEventListener("abort",h),m()},i);t.abortSignal?.addEventListener("abort",h,{once:!0})})}throw new Me({code:Ze.OPERATION_ABORTED,message:`Replicate prediction ${e} did not complete within ${Math.round(s/1e3)}s`,category:"timeout",severity:"high",retriable:!0})}async function Ag(r,e,t={}){let n=await xkr(r,e);if(n.status==="succeeded")return n;if(n.status==="failed"||n.status==="canceled")throw new Me({code:Ze.PROVIDER_NOT_AVAILABLE,message:`Replicate prediction ${n.id} ${n.status} on submit: ${n.error??"unknown"}`,category:"execution",severity:"high",retriable:n.status==="failed"});return bkr(r,n.id,t)}async function ly(r,e=268435456){let t=r.output,n=Array.isArray(t)?t[0]:t;if(typeof n!="string")throw new Me({code:Ze.PROVIDER_NOT_AVAILABLE,message:`Replicate prediction ${r.id} output is not a URL: ${typeof t}`,category:"execution",severity:"high",retriable:!1});try{let o=await cy(n,{maxBytes:e,label:`Replicate prediction ${r.id}`,timeoutMs:fO});return g.debug(`[Replicate] Downloaded prediction ${r.id} output: ${o.length} bytes`),o}catch(o){if(o instanceof Me)throw o;let s=o instanceof Error?o.message:String(o);throw new Me({code:Ze.PROVIDER_NOT_AVAILABLE,message:`Replicate output download failed: ${s} \u2014 ${n}`,category:"network",severity:"high",retriable:!0,originalError:o instanceof Error?o:void 0})}}var fO,ykr,vkr,hO=E(()=>{"use strict";W();St();qr();uA();g2();gO();fO=9e4,ykr=2e3,vkr=5*6e4});var x3e={};ue(x3e,{ReplicateProvider:()=>P4,default:()=>wkr});function Tkr(r){let e=r,t=e.prompt??e.input?.text??"",n=e.systemPrompt;return n?`${n}
2157
2157
 
2158
- ${t}`:t}function Skr(r){return typeof r=="string"?r:Array.isArray(r)?r.map(e=>typeof e=="string"?e:"").join(""):""}var v3e,P4,wkr,b3e=E(async()=>{"use strict";$l();mO();hO();await Fd();W();St();an();v3e=()=>Kt("REPLICATE_MODEL","meta/meta-llama-3-70b-instruct");P4=class extends no{apiToken;baseURL;constructor(e,t,n,o){let s=Zl(t)?t:void 0;super(e,"replicate",s);let i=o?.apiToken?.trim();this.apiToken=i&&i.length>0?i:Ht(_De()),this.baseURL=o?.baseUrl,g.debug("Replicate Provider initialized",{modelName:this.modelName,baseURL:this.baseURL})}getProviderName(){return this.providerName}getDefaultModel(){return v3e()}supportsTools(){return!1}getAISDKModel(){throw new Error("Replicate routes through the predictions API, not the AI SDK chat models. Streaming uses the predict-then-stream path inside executeStream.")}async generate(e,t){let n=typeof e=="string"?{prompt:e}:e,{IMAGE_GENERATION_MODELS:o}=await Promise.resolve().then(()=>(ns(),rke));if(n.output?.mode==="video"||n.output?.mode==="avatar"||n.output?.mode==="music")return super.generate(n,t);let s=o.some(m=>this.modelName.includes(m)),i=n.output?.format==="json"||n.output?.format==="structured"||n.output?.format==="text";if(s&&!i)return super.generate(n,t);if(n.output?.format==="json"||n.output?.format==="structured"||t!=null)throw new Me({code:Ze.PROVIDER_NOT_AVAILABLE,message:"Replicate models do not support structured-output / JSON schema. Remove output.format or _analysisSchema, or use a provider that implements the OpenAI chat-completions contract (e.g. openai, anthropic).",category:"validation",severity:"medium",retriable:!1});let a=n.prompt??n.input?.text??"",c=Date.now(),l=await this.executeStream({input:{text:a},systemPrompt:n.systemPrompt,maxTokens:n.maxTokens,temperature:n.temperature,abortSignal:n.abortSignal,timeout:n.timeout}),d="";for await(let m of l.stream)"content"in m&&typeof m.content=="string"&&(d+=m.content);let p={content:d,provider:this.providerName,model:this.modelName,usage:{input:0,output:0,total:0}};return g.info(`[ReplicateProvider] generate() complete in ${Date.now()-c}ms \u2014 ${d.length} chars`),p}async executeStream(e,t){let n=Date.now(),o=e.credentials?.replicate,s=o?.apiToken?.trim()||this.apiToken,i=o?.baseUrl||this.baseURL,a=$u({apiToken:s,baseUrl:i});if(!a)throw new Me({code:Ze.MISSING_CONFIGURATION,message:"Replicate auth could not be resolved (REPLICATE_API_TOKEN missing).",category:"configuration",severity:"high",retriable:!1});let c=Tkr(e);if(!c.trim())throw new Me({code:Ze.INVALID_PARAMETERS,message:"Replicate predictions require a prompt (input.text or prompt)",category:"validation",severity:"medium",retriable:!1});let l={prompt:c,...e.maxTokens!==void 0&&{max_new_tokens:e.maxTokens},temperature:e.temperature,top_p:1},d;try{d=await Ag(a,{model:this.modelName,input:l},{abortSignal:e.abortSignal})}catch(f){throw this.handleProviderError(f)}let p=Skr(d.output);if(!p)throw new Error(`Replicate prediction ${d.id} returned empty output`);let m={async*[Symbol.asyncIterator](){yield{content:p}}};return g.info(`[ReplicateProvider] Generated ${p.length} chars in ${Date.now()-n}ms \u2014 model ${this.modelName} (prediction ${d.id})`),{stream:m,provider:this.providerName,model:this.modelName,finishReason:"stop",metadata:{startTime:n,streamId:`replicate-${d.id}`}}}async executeImageGeneration(e){let t=Date.now(),n=e.credentials?.replicate,o=n?.apiToken?.trim()||this.apiToken,s=n?.baseUrl||this.baseURL,i=$u({apiToken:o,baseUrl:s});if(!i)throw new Me({code:Ze.MISSING_CONFIGURATION,message:"Replicate auth could not be resolved (REPLICATE_API_TOKEN missing).",category:"configuration",severity:"high",retriable:!1});let a=e.prompt??e.input?.text??"";if(!a.trim())throw new Me({code:Ze.INVALID_PARAMETERS,message:"Replicate image-gen requires a prompt",category:"validation",severity:"medium",retriable:!1});let c=e,l={prompt:a,output_format:"png"};c.aspectRatio&&(l.aspect_ratio=c.aspectRatio),c.negativePrompt&&(l.negative_prompt=c.negativePrompt),c.seed!==void 0&&(l.seed=c.seed);let d;try{d=await Ag(i,{model:this.modelName,input:l},{abortSignal:e.abortSignal})}catch(f){throw this.handleProviderError(f)}let p;try{p=await ly(d,26214400)}catch(f){throw this.handleProviderError(f)}let m=p.toString("base64");return g.info(`[ReplicateProvider] Generated image (${p.length} bytes) in ${Date.now()-t}ms \u2014 model ${this.modelName}`),{content:a,provider:this.providerName,model:this.modelName,usage:{input:0,output:0,total:0},imageOutput:{base64:m}}}formatProviderError(e){let t=e instanceof Error?e.message:typeof e=="string"?e:"Unknown error",n=e instanceof Error?e:void 0;return t.includes("401")||t.toLowerCase().includes("unauthorized")||t.toLowerCase().includes("invalid token")?new Me({code:Ze.PROVIDER_AUTH_FAILED,message:"Invalid Replicate API token. Get one at https://replicate.com/account/api-tokens",category:"configuration",severity:"high",retriable:!1,context:{provider:"replicate"},originalError:n}):t.includes("402")||t.toLowerCase().includes("insufficient credit")?new Me({code:Ze.PROVIDER_QUOTA_EXCEEDED,message:"Replicate insufficient credit. Top up at https://replicate.com/account/billing \u2014 most image/music models require a paid balance.",category:"resource",severity:"high",retriable:!1,context:{provider:"replicate"},originalError:n}):t.includes("429")||t.toLowerCase().includes("rate limit")?new Me({code:Ze.PROVIDER_QUOTA_EXCEEDED,message:"Replicate rate limit exceeded. Back off and retry.",category:"resource",severity:"high",retriable:!0,context:{provider:"replicate"},originalError:n}):t.toLowerCase().includes("not found")||t.includes("404")?new Me({code:Ze.PROVIDER_NOT_AVAILABLE,message:`Replicate model '${this.modelName}' not found. Use owner/name or owner/name:version format. Browse https://replicate.com/explore`,category:"validation",severity:"medium",retriable:!1,context:{provider:"replicate",model:this.modelName},originalError:n}):new Me({code:Ze.PROVIDER_NOT_AVAILABLE,message:`Replicate error: ${t}`,category:"execution",severity:"high",retriable:!1,context:{provider:"replicate"},originalError:n})}async validateConfiguration(){return typeof this.apiToken=="string"&&this.apiToken.trim().length>0}getConfiguration(){return{provider:this.providerName,model:this.modelName,defaultModel:v3e(),baseURL:this.baseURL}}},wkr=P4});var w3e={};ue(w3e,{RecraftProvider:()=>M4,default:()=>Ckr});var _kr,T3e,Ekr,S3e,M4,Ckr,_3e=E(async()=>{"use strict";$l();await Fd();Dn();Pt();W();an();Zm();Sh();_kr="https://external.api.recraft.ai/v1",T3e=12e4,Ekr=()=>Ht(PDe()),S3e=()=>Kt("RECRAFT_MODEL","recraftv3"),M4=class extends no{apiKey;baseURL;proxyFetch;constructor(e,t,n,o){let s=Zl(t)?t:void 0;super(e,"recraft",s);let i=o?.apiKey?.trim();this.apiKey=i&&i.length>0?i:Ekr(),this.baseURL=o?.baseURL??process.env.RECRAFT_BASE_URL??_kr,this.proxyFetch=gt(),g.debug("Recraft Provider initialized (image-gen only)",{modelName:this.modelName,baseURL:this.baseURL})}getProviderName(){return this.providerName}getDefaultModel(){return S3e()}supportsTools(){return!1}getAISDKModel(){throw new Error("Recraft is an image-generation-only provider; chat completions are not available.")}async executeStream(e,t){throw new Error("Recraft is an image-generation-only provider; streaming chat is not available.")}formatProviderError(e){let t=e instanceof Error?e.message:typeof e=="string"?e:"Unknown error";return t.includes("401")||t.toLowerCase().includes("unauthorized")?new It("Invalid Recraft API key. Get one at https://www.recraft.ai/api","recraft"):t.includes("429")||t.toLowerCase().includes("rate limit")?new Yt("Recraft rate limit exceeded. Back off and retry.","recraft"):t.includes("404")||t.includes("model_not_found")?new qt(`Recraft model '${this.modelName}' not found. Use recraftv3, recraftv3-svg, or recraftv2.`,"recraft"):new We(`Recraft error: ${t}`,"recraft")}async executeImageGeneration(e){let t=Date.now(),n=e.credentials?.recraft,o=n?.apiKey?.trim()||this.apiKey,s=n?.baseURL||this.baseURL,i=e.prompt??e.input?.text??"";if(!i.trim())throw new Error("Recraft image generation requires a prompt (input.text or prompt)");let a=e,c={model:e.model??this.modelName,prompt:i,n:1,response_format:"b64_json"};a.negativePrompt&&(c.negative_prompt=a.negativePrompt),a.style&&(c.style=a.style),a.styleId&&(c.style_id=a.styleId),a.size&&(c.size=a.size);let l=new AbortController,d=setTimeout(()=>l.abort(),T3e),p;try{p=await this.proxyFetch(`${s}/images/generations`,{method:"POST",headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json"},body:JSON.stringify(c),signal:l.signal})}catch(v){throw v instanceof Error&&v.name==="AbortError"?this.formatProviderError(new Error(`Recraft image-gen request timed out after ${T3e/1e3}s`)):this.formatProviderError(v)}finally{clearTimeout(d)}if(!p.ok){let v=await p.text();throw this.formatProviderError(new Error(`Recraft image-gen failed: ${p.status} \u2014 ${v}`))}let f=(await p.json()).data?.[0];if(!f)throw new Error("Recraft returned no image data");let h;if(f.b64_json)h=f.b64_json;else if(f.url){await Gl(f.url);let v=new AbortController,b=setTimeout(()=>v.abort(),6e4),S;try{S=await this.proxyFetch(f.url,{signal:v.signal})}catch(C){throw C instanceof Error&&C.name==="AbortError"?new Error("Recraft image download timed out after 60s",{cause:C}):C}finally{clearTimeout(b)}if(!S.ok)throw new Error(`Failed to download Recraft image: ${S.status}`);h=(await ha(S,26214400,"Recraft image")).toString("base64")}else throw new Error("Recraft response missing both b64_json and url");let y=Date.now()-t;return g.info(`[RecraftProvider] Generated image (${h.length} base64 chars) in ${y}ms \u2014 model ${this.modelName}`),{content:i,provider:this.providerName,model:this.modelName,usage:{input:0,output:1e3,total:1e3},imageOutput:{base64:h}}}async validateConfiguration(){return typeof this.apiKey=="string"&&this.apiKey.trim().length>0}getConfiguration(){return{provider:this.providerName,model:this.modelName,defaultModel:S3e(),baseURL:this.baseURL}}},Ckr=M4});var E3e={};ue(E3e,{Agent:()=>gAr,BedrockClient:()=>kkr,BedrockRuntimeClient:()=>Ikr,Blob:()=>mAr,Client:()=>hAr,ConverseCommand:()=>Pkr,ConverseStreamCommand:()=>Mkr,Cron:()=>Jkr,Dispatcher:()=>yAr,File:()=>pAr,FlowProducer:()=>Wkr,FormData:()=>dAr,GoogleAuth:()=>Ukr,HTTPException:()=>rAr,Headers:()=>uAr,Hippocampus:()=>zkr,HippocampusConfig:()=>jkr,Hono:()=>eAr,ImageFormat:()=>Okr,InvokeEndpointCommand:()=>Lkr,InvokeEndpointWithResponseStreamCommand:()=>Dkr,Job:()=>Hkr,ListFoundationModelsCommand:()=>Akr,MockAgent:()=>bAr,Pool:()=>fAr,Queue:()=>qkr,QueueScheduler:()=>Kkr,Request:()=>cAr,Response:()=>lAr,SageMakerRuntimeClient:()=>Nkr,TextToSpeechClient:()=>$kr,VertexAI:()=>Fkr,Webhook:()=>Bkr,Worker:()=>Vkr,convertToHtml:()=>Qkr,cors:()=>tAr,createClient:()=>Gkr,default:()=>Rkr,extractRawText:()=>Zkr,fetch:()=>aAr,getGlobalDispatcher:()=>xAr,interceptors:()=>TAr,logger:()=>nAr,parseBuffer:()=>Ykr,request:()=>SAr,secureHeaders:()=>oAr,selectCover:()=>Xkr,setGlobalDispatcher:()=>vAr,streamSSE:()=>sAr,timeout:()=>iAr});var nC,Ii,Rkr,kkr,Akr,Ikr,Pkr,Mkr,Okr,Nkr,Lkr,Dkr,Ukr,Fkr,$kr,Bkr,zkr,jkr,Gkr,qkr,Vkr,Hkr,Kkr,Wkr,Jkr,Ykr,Xkr,Zkr,Qkr,eAr,tAr,rAr,nAr,oAr,sAr,iAr,aAr,cAr,lAr,uAr,dAr,pAr,mAr,gAr,fAr,hAr,yAr,vAr,xAr,bAr,TAr,SAr,C3e=E(()=>{nC={get(r,e){return e==="__esModule"?!0:e==="default"?new Proxy({},{get:nC.get}):new Proxy(function(...t){return new Proxy({},{get:nC.get})},{get:nC.get,apply(t,n,o){return new Proxy({},{get:nC.get})},construct(t,n){return new Proxy({},{get:nC.get})}})}},Ii=new Proxy({},nC),Rkr=Ii,{BedrockClient:kkr,ListFoundationModelsCommand:Akr,BedrockRuntimeClient:Ikr,ConverseCommand:Pkr,ConverseStreamCommand:Mkr,ImageFormat:Okr}=Ii,{SageMakerRuntimeClient:Nkr,InvokeEndpointCommand:Lkr,InvokeEndpointWithResponseStreamCommand:Dkr}=Ii,{GoogleAuth:Ukr,VertexAI:Fkr,TextToSpeechClient:$kr}=Ii,{Webhook:Bkr}=Ii,{Hippocampus:zkr,HippocampusConfig:jkr}=Ii,{createClient:Gkr}=Ii,{Queue:qkr,Worker:Vkr,Job:Hkr,QueueScheduler:Kkr,FlowProducer:Wkr}=Ii,{Cron:Jkr}=Ii,{parseBuffer:Ykr,selectCover:Xkr}=Ii,{extractRawText:Zkr,convertToHtml:Qkr}=Ii,{Hono:eAr}=Ii,{cors:tAr,HTTPException:rAr,logger:nAr,secureHeaders:oAr,streamSSE:sAr,timeout:iAr}=Ii,aAr=globalThis.fetch,cAr=globalThis.Request,lAr=globalThis.Response,uAr=globalThis.Headers,dAr=globalThis.FormData,pAr=globalThis.File,mAr=globalThis.Blob,gAr=Ii.Agent,fAr=Ii.Pool,hAr=Ii.Client,yAr=Ii.Dispatcher,vAr=()=>{},xAr=()=>Ii,bAr=Ii.MockAgent,TAr={redirect:()=>r=>r,retry:()=>r=>r},SAr=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 R3e={};ue(R3e,{GoogleTTSHandler:()=>vb});var vb,O4=E(()=>{"use strict";Yi();W();co();vb=class r{client=null;voicesCache=null;static CACHE_TTL_MS=300*1e3;static DEFAULT_MAX_TEXT_LENGTH=5e3;static DEFAULT_API_TIMEOUT_MS=30*1e3;maxTextLength=r.DEFAULT_MAX_TEXT_LENGTH;credentialsPath;constructor(e){this.credentialsPath=e??process.env.GOOGLE_APPLICATION_CREDENTIALS}isConfigured(){return this.credentialsPath!==void 0}async getClient(){if(!this.client){let{TextToSpeechClient:e}=await Promise.resolve().then(()=>(C3e(),E3e));this.client=new e({keyFilename:this.credentialsPath})}return this.client}async getVoices(e){if(!this.isConfigured())throw new zt({code:Zt.PROVIDER_NOT_CONFIGURED,message:"Google Cloud TTS client not initialized. Set GOOGLE_APPLICATION_CREDENTIALS or pass credentials path.",category:"configuration",severity:"high",retriable:!1});let t=await this.getClient(),n=Re.createSpan("tts","tts.google.listVoices",{"tts.operation":"listVoices","tts.provider":"google"});try{if(this.voicesCache&&Date.now()-this.voicesCache.timestamp<r.CACHE_TTL_MS&&!e){let a=Re.endSpan(n,1);return nt().recordSpan(a),this.voicesCache.voices}let[o]=await t.listVoices(e?{languageCode:e}:{});if(!o.voices||o.voices.length===0){g.warn("Google Cloud TTS returned no voices");let a=Re.endSpan(n,1);return nt().recordSpan(a),[]}let s=[];for(let a of o.voices??[]){if(!a.name||!Array.isArray(a.languageCodes)||a.languageCodes.length===0){g.warn("Skipping voice with missing required fields",{name:a.name,languageCodesCount:a.languageCodes?.length});continue}let c=a.name,l=a.languageCodes,d=l[0],p=this.detectVoiceType(c),m=a.ssmlGender==="MALE"?"male":a.ssmlGender==="FEMALE"?"female":"neutral";s.push({id:c,name:c,languageCode:d,languageCodes:l,gender:m,type:p,naturalSampleRateHertz:a.naturalSampleRateHertz??void 0})}e||(this.voicesCache={voices:s,timestamp:Date.now()});let i=Re.endSpan(n,1);return nt().recordSpan(i),s}catch(o){let s=Re.endSpan(n,2,o instanceof Error?o.message:"Unknown error");nt().recordSpan(s);let i=o instanceof Error?o.message:"Unknown error";return g.error(`Failed to fetch Google TTS voices: ${i}`),[]}}async synthesize(e,t){if(!this.isConfigured())throw new zt({code:Zt.PROVIDER_NOT_CONFIGURED,message:"Google Cloud TTS client not initialized. Set GOOGLE_APPLICATION_CREDENTIALS or pass credentials path.",category:"configuration",severity:"high",retriable:!1});let n=await this.getClient(),o=t.voice??"en-US-Neural2-C",s=Re.createSpan("tts","tts.google.synthesize",{"tts.operation":"synthesize","tts.provider":"google","tts.voice":o,"tts.format":t.format??"mp3"}),i=Date.now();try{let a=e.startsWith("<speak>")&&e.endsWith("</speak>");if(e.startsWith("<speak>")&&!e.endsWith("</speak>")||!e.startsWith("<speak>")&&e.endsWith("</speak>"))throw new zt({code:Zt.INVALID_INPUT,message:"Malformed SSML: missing opening <speak> or closing </speak> tag.",category:"validation",severity:"medium",retriable:!1});let c=this.extractLanguageCode(o),l=this.mapFormat(t.format??"mp3"),d={input:a?{ssml:e}:{text:e},voice:{name:o,languageCode:c},audioConfig:{audioEncoding:l,speakingRate:t.speed??1,pitch:t.pitch??0,volumeGainDb:t.volumeGainDb??0}},[p]=await n.synthesizeSpeech(d,{timeout:r.DEFAULT_API_TIMEOUT_MS}),m=p.audioContent;if(!m)throw new zt({code:Zt.SYNTHESIS_FAILED,message:"Google TTS returned empty audio content",category:"execution",severity:"high",retriable:!0});let f=m instanceof Uint8Array?Buffer.from(m):typeof m=="string"?Buffer.from(m,"base64"):(()=>{throw new zt({code:Zt.SYNTHESIS_FAILED,message:"Unsupported audioContent type returned by Google TTS",category:"execution",severity:"high",retriable:!0,context:{type:typeof m}})})(),h=Date.now()-i,y=Re.endSpan(s,1);return nt().recordSpan(y),{buffer:f,format:t.format??"mp3",size:f.length,voice:o,metadata:{latency:h,provider:"google-ai"}}}catch(a){let c=Re.endSpan(s,2,a instanceof Error?a.message:String(a));if(nt().recordSpan(c),a instanceof zt)throw a;let l=Date.now()-i,d=a instanceof Error?a.message:"Unknown error";throw new zt({code:Zt.SYNTHESIS_FAILED,message:`Google TTS failed after ${l}ms: ${d}`,category:"execution",severity:"high",retriable:!0,context:{latency:l},originalError:a instanceof Error?a:void 0})}}extractLanguageCode(e){let t=e.split("-");if(t.length>=2)return`${t[0]}-${t[1]}`;throw new zt({code:Zt.INVALID_INPUT,message:`Invalid Google TTS voiceId format: "${e}". Expected format like "en-US-Neural2-C".`,category:"validation",severity:"medium",retriable:!1,context:{voiceId:e}})}mapFormat(e){switch(e.toLowerCase()){case"mp3":return"MP3";case"wav":return"LINEAR16";case"ogg":case"opus":return"OGG_OPUS";default:throw new zt({code:Zt.INVALID_INPUT,message:`Unsupported audio format: ${e}`,category:"validation",severity:"medium",retriable:!1,context:{format:e}})}}detectVoiceType(e){let t=e.toLowerCase().split("-");return t.some(n=>n.startsWith("chirp"))?"chirp":t.includes("neural2")?"neural":t.includes("wavenet")?"wavenet":t.includes("standard")?"standard":"unknown"}}});var k3e={};ue(k3e,{OpenAITTS:()=>Ig});var Ig,N4=E(()=>{"use strict";W();Yi();Ig=class r{apiKey;baseUrl="https://api.openai.com/v1";maxTextLength=4096;static VOICES=[{id:"alloy",name:"Alloy",languageCode:"en",languageCodes:["en"],gender:"neutral",type:"neural"},{id:"echo",name:"Echo",languageCode:"en",languageCodes:["en"],gender:"male",type:"neural"},{id:"fable",name:"Fable",languageCode:"en",languageCodes:["en"],gender:"neutral",type:"neural"},{id:"onyx",name:"Onyx",languageCode:"en",languageCodes:["en"],gender:"male",type:"neural"},{id:"nova",name:"Nova",languageCode:"en",languageCodes:["en"],gender:"female",type:"neural"},{id:"shimmer",name:"Shimmer",languageCode:"en",languageCodes:["en"],gender:"female",type:"neural"}];constructor(e){let t=(e??process.env.OPENAI_API_KEY??"").trim();this.apiKey=t.length>0?t:null}isConfigured(){return this.apiKey!==null}async getVoices(e){return e&&!e.startsWith("en"),r.VOICES}async synthesize(e,t={}){if(!this.apiKey)throw new zt({code:Zt.PROVIDER_NOT_CONFIGURED,message:"OpenAI TTS API key not configured",category:"configuration",severity:"high",retriable:!1});let n=Date.now(),o=t;try{let s=o.model??(t.quality==="hd"?"tts-1-hd":"tts-1"),i=t.voice??"alloy",a=this.mapFormat(t.format??"mp3"),c={model:s,input:e,voice:i,response_format:a,speed:t.speed??1},l=new AbortController,d=setTimeout(()=>l.abort(),3e4),p;try{p=await fetch(`${this.baseUrl}/audio/speech`,{method:"POST",headers:{Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify(c),signal:l.signal})}catch(b){throw b instanceof Error&&b.name==="AbortError"?new zt({code:Zt.SYNTHESIS_FAILED,message:"OpenAI TTS request timed out after 30 seconds",category:"network",severity:"high",retriable:!0,originalError:b}):b}finally{clearTimeout(d)}if(!p.ok){let S=(await p.json().catch(()=>Object.create(null))).error?.message||`HTTP ${p.status}`,w=p.status===408||p.status===429||p.status>=500;throw new zt({code:Zt.SYNTHESIS_FAILED,message:S,category:w?"network":"execution",severity:"high",retriable:w,context:{status:p.status,model:s,responseFormat:a}})}let m=Date.now()-n,f=await p.arrayBuffer(),h=Buffer.from(f),y=this.effectiveFormat(a),v={buffer:h,format:y,size:h.length,voice:i,sampleRate:this.getSampleRate(y),metadata:{latency:m,provider:"openai-tts",model:s,requestedFormat:t.format,responseFormat:a}};return g.info(`[OpenAITTSHandler] Synthesized ${h.length} bytes in ${m}ms`),v}catch(s){if(s instanceof zt)throw s;let i=s instanceof Error?s.message:String(s||"Unknown error");throw g.error(`[OpenAITTSHandler] Synthesis failed: ${i}`),new zt({code:Zt.SYNTHESIS_FAILED,message:`Synthesis failed: ${i}`,category:"execution",severity:"high",retriable:!0,context:{textLength:e.length},originalError:s instanceof Error?s:void 0})}}mapFormat(e){let n={mp3:"mp3",wav:"wav",ogg:"opus",opus:"opus",pcm16:"pcm"}[e];return n===void 0?(g.warn(`[OpenAITTSHandler] Unsupported format "${e}" \u2014 falling back to "mp3". Supported formats: mp3, wav, ogg, opus, pcm16.`),"mp3"):n}getSampleRate(e){switch(e){case"opus":case"ogg":return 48e3;default:return 24e3}}effectiveFormat(e){switch(e){case"mp3":return"mp3";case"wav":return"wav";case"opus":return"opus";case"pcm":return"pcm16";default:return"mp3"}}}});var A3e={};ue(A3e,{ElevenLabsTTS:()=>Pg});var Pg,L4=E(()=>{"use strict";W();Yi();Pg=class r{apiKey;baseUrl="https://api.elevenlabs.io/v1";voicesCache=null;static CACHE_TTL_MS=300*1e3;maxTextLength=5e3;constructor(e){let t=(e??process.env.ELEVENLABS_API_KEY??"").trim();this.apiKey=t.length>0?t:null}isConfigured(){return this.apiKey!==null}async getVoices(e){if(!this.apiKey)throw new zt({code:Zt.PROVIDER_NOT_CONFIGURED,message:"ElevenLabs API key not configured",category:"configuration",severity:"high",retriable:!1});if(this.voicesCache&&Date.now()-this.voicesCache.timestamp<r.CACHE_TTL_MS&&!e)return this.voicesCache.voices;try{let t=new AbortController,n=setTimeout(()=>t.abort(),3e4),o;try{o=await fetch(`${this.baseUrl}/voices`,{method:"GET",headers:{"xi-api-key":this.apiKey},signal:t.signal})}catch(a){throw a instanceof Error&&a.name==="AbortError"?new zt({code:Zt.SYNTHESIS_FAILED,message:"ElevenLabs voices request timed out after 30 seconds",category:"network",severity:"medium",retriable:!0,originalError:a}):a}finally{clearTimeout(n)}if(!o.ok)throw new Error(`HTTP ${o.status}`);let i=(await o.json()).voices.map(a=>({id:a.voice_id,name:a.name,languageCode:"en",languageCodes:["en","es","fr","de","it","pt","pl","hi","ar","zh","ja","ko"],gender:this.mapGender(a.labels?.gender),type:"neural",description:a.labels?.description}));if(e){let a=e.toLowerCase(),c=a.split("-")[0];i=i.filter(l=>l.languageCodes?.some(d=>{let p=d.toLowerCase();return p===a||p===c||p.startsWith(c)}))}return e||(this.voicesCache={voices:i,timestamp:Date.now()}),i}catch(t){let n=t instanceof Error?t.message:String(t||"Unknown error");throw g.error(`[ElevenLabsTTSHandler] Failed to get voices: ${n}`),new zt({code:Zt.SYNTHESIS_FAILED,message:`Failed to get voices: ${n}`,category:"network",severity:"medium",retriable:!0,originalError:t instanceof Error?t:void 0})}}async synthesize(e,t={}){if(!this.apiKey)throw new zt({code:Zt.PROVIDER_NOT_CONFIGURED,message:"ElevenLabs API key not configured",category:"configuration",severity:"high",retriable:!1});let n=Date.now(),o=t;try{let s=t.voice??"21m00Tcm4TlvDq8ikWAM",i=o.model??"eleven_multilingual_v2",a={text:e,model_id:i,voice_settings:{stability:o.stability??.5,similarity_boost:o.similarityBoost??.75,style:o.style??0,use_speaker_boost:o.useSpeakerBoost??!0}},c=this.mapFormat(t.format??"mp3"),l=new AbortController,d=setTimeout(()=>l.abort(),3e4),p;try{p=await fetch(`${this.baseUrl}/text-to-speech/${s}?output_format=${c}`,{method:"POST",headers:{"xi-api-key":this.apiKey,"Content-Type":"application/json"},body:JSON.stringify(a),signal:l.signal})}catch(v){throw v instanceof Error&&v.name==="AbortError"?new zt({code:Zt.SYNTHESIS_FAILED,message:"ElevenLabs TTS request timed out after 30 seconds",category:"network",severity:"high",retriable:!0,originalError:v}):v}finally{clearTimeout(d)}if(!p.ok){let b=(await p.json().catch(()=>Object.create(null))).detail?.message||`HTTP ${p.status}`;throw new Error(b)}let m=Date.now()-n,f=await p.arrayBuffer(),h=Buffer.from(f),y={buffer:h,format:this.effectiveFormat(c),size:h.length,voice:s,sampleRate:this.getSampleRate(c),metadata:{latency:m,provider:"elevenlabs-tts",model:i,requestedFormat:t.format,outputFormat:c}};return g.info(`[ElevenLabsTTSHandler] Synthesized ${h.length} bytes in ${m}ms`),y}catch(s){if(s instanceof zt)throw s;let i=s instanceof Error?s.message:String(s||"Unknown error");throw g.error(`[ElevenLabsTTSHandler] Synthesis failed: ${i}`),new zt({code:Zt.SYNTHESIS_FAILED,message:`Synthesis failed: ${i}`,category:"execution",severity:"high",retriable:!0,context:{textLength:e.length},originalError:s instanceof Error?s:void 0})}}mapGender(e){if(!e)return"neutral";let t=e.toLowerCase();return t.includes("male")&&!t.includes("female")?"male":t.includes("female")?"female":"neutral"}mapFormat(e){return{mp3:"mp3_44100_128",wav:"pcm_44100",ogg:"ogg_22050",opus:"ogg_22050"}[e]??"mp3_44100_128"}getSampleRate(e){return e.includes("44100")?44100:e.includes("22050")?22050:e.includes("24000")?24e3:44100}effectiveFormat(e){return e.startsWith("mp3")?"mp3":e.startsWith("pcm")?"pcm16":e.startsWith("ogg")?"opus":"mp3"}}});var I3e={};ue(I3e,{AzureTTS:()=>Mg});var Mg,D4=E(()=>{"use strict";W();Yi();Mg=class r{apiKey;region;voicesCache=null;static CACHE_TTL_MS=1800*1e3;maxTextLength=1e4;constructor(e,t){let n=(e??process.env.AZURE_SPEECH_KEY??"").trim();this.apiKey=n.length>0?n:null;let o=(t??process.env.AZURE_SPEECH_REGION??"").trim();this.region=o.length>0?o:"eastus"}isConfigured(){return this.apiKey!==null&&this.region.length>0}async getVoices(e){if(!this.apiKey)throw new zt({code:Zt.PROVIDER_NOT_CONFIGURED,message:"Azure Speech key not configured",category:"configuration",severity:"high",retriable:!1});if(this.voicesCache&&Date.now()-this.voicesCache.timestamp<r.CACHE_TTL_MS&&!e)return this.voicesCache.voices;try{let t=new AbortController,n=setTimeout(()=>t.abort(),3e4),o;try{o=await fetch(`https://${this.region}.tts.speech.microsoft.com/cognitiveservices/voices/list`,{method:"GET",headers:{"Ocp-Apim-Subscription-Key":this.apiKey},signal:t.signal})}catch(a){throw a instanceof Error&&a.name==="AbortError"?new zt({code:Zt.SYNTHESIS_FAILED,message:"Azure TTS voices request timed out after 30 seconds",category:"network",severity:"medium",retriable:!0,originalError:a}):a}finally{clearTimeout(n)}if(!o.ok)throw new Error(`HTTP ${o.status}`);let i=(await o.json()).map(a=>({id:a.ShortName,name:a.DisplayName,languageCode:a.Locale,languageCodes:[a.Locale],gender:this.mapGender(a.Gender),type:a.VoiceType.toLowerCase().includes("neural")?"neural":"standard",description:a.LocaleName}));return e&&(i=i.filter(a=>a.languageCode.toLowerCase().startsWith(e.toLowerCase())||a.languageCode.toLowerCase()===e.toLowerCase())),e||(this.voicesCache={voices:i,timestamp:Date.now()}),i}catch(t){if(t instanceof zt)throw t;let n=t instanceof Error?t.message:String(t||"Unknown error");throw g.error(`[AzureTTSHandler] Failed to get voices: ${n}`),new zt({code:Zt.SYNTHESIS_FAILED,message:`Failed to get voices: ${n}`,category:"network",severity:"medium",retriable:!0,originalError:t instanceof Error?t:void 0})}}async synthesize(e,t={}){if(!this.apiKey)throw new zt({code:Zt.PROVIDER_NOT_CONFIGURED,message:"Azure Speech key not configured",category:"configuration",severity:"high",retriable:!1});let n=Date.now(),o=t;try{let s=t.voice??"en-US-JennyNeural",i=o.outputFormat??this.mapFormat(t.format??"mp3"),a=this.buildSSML(e,s,t),c=new AbortController,l=setTimeout(()=>c.abort(),3e4),d;try{d=await fetch(`https://${this.region}.tts.speech.microsoft.com/cognitiveservices/v1`,{method:"POST",headers:{"Ocp-Apim-Subscription-Key":this.apiKey,"Content-Type":"application/ssml+xml","X-Microsoft-OutputFormat":i},body:a,signal:c.signal})}catch(y){throw y instanceof Error&&y.name==="AbortError"?new zt({code:Zt.SYNTHESIS_FAILED,message:"Azure TTS request timed out after 30 seconds",category:"network",severity:"high",retriable:!0,originalError:y}):y}finally{clearTimeout(l)}if(!d.ok){let y=await d.text();throw new Error(`HTTP ${d.status}: ${y}`)}let p=Date.now()-n,m=await d.arrayBuffer(),f=Buffer.from(m),h={buffer:f,format:this.effectiveFormat(i),size:f.length,voice:s,sampleRate:this.getSampleRate(i),metadata:{latency:p,provider:"azure-tts",requestedFormat:t.format,outputFormat:i,region:this.region}};return g.info(`[AzureTTSHandler] Synthesized ${f.length} bytes in ${p}ms`),h}catch(s){if(s instanceof zt)throw s;let i=s instanceof Error?s.message:String(s||"Unknown error");throw g.error(`[AzureTTSHandler] Synthesis failed: ${i}`),new zt({code:Zt.SYNTHESIS_FAILED,message:`Synthesis failed: ${i}`,category:"execution",severity:"high",retriable:!0,context:{textLength:e.length},originalError:s instanceof Error?s:void 0})}}buildSSML(e,t,n){let o=n;if(o.ssmlTemplate)return o.ssmlTemplate.replace("{text}",this.escapeXml(e)).replace("{voice}",this.escapeXml(t));if(o.allowRawSSML&&e.trim().startsWith("<speak"))return e;let s=n.speed?`${Math.round((n.speed-1)*100)}%`:"0%",i=n.pitch??0,a=i>=0?`+${Math.round(i)}st`:`${Math.round(i)}st`;return`<speak version="1.0" xmlns="http://www.w3.org/2001/10/synthesis" xml:lang="${this.escapeXml(this.extractLanguage(t))}">
2158
+ ${t}`:t}function Skr(r){return typeof r=="string"?r:Array.isArray(r)?r.map(e=>typeof e=="string"?e:"").join(""):""}var v3e,P4,wkr,b3e=E(async()=>{"use strict";$l();mO();hO();await Fd();W();St();an();v3e=()=>Kt("REPLICATE_MODEL","meta/meta-llama-3-70b-instruct");P4=class extends no{apiToken;baseURL;constructor(e,t,n,o){let s=Zl(t)?t:void 0;super(e,"replicate",s);let i=o?.apiToken?.trim();this.apiToken=i&&i.length>0?i:Ht(_De()),this.baseURL=o?.baseUrl,g.debug("Replicate Provider initialized",{modelName:this.modelName,baseURL:this.baseURL})}getProviderName(){return this.providerName}getDefaultModel(){return v3e()}supportsTools(){return!1}getAISDKModel(){throw new Error("Replicate routes through the predictions API, not the AI SDK chat models. Streaming uses the predict-then-stream path inside executeStream.")}async generate(e,t){let n=typeof e=="string"?{prompt:e}:e,{IMAGE_GENERATION_MODELS:o}=await Promise.resolve().then(()=>(ns(),rke));if(n.output?.mode==="video"||n.output?.mode==="avatar"||n.output?.mode==="music")return super.generate(n,t);let s=o.some(m=>this.modelName.includes(m)),i=n.output?.format==="json"||n.output?.format==="structured"||n.output?.format==="text";if(s&&!i)return super.generate(n,t);if(n.output?.format==="json"||n.output?.format==="structured"||t!=null)throw new Me({code:Ze.PROVIDER_NOT_AVAILABLE,message:"Replicate models do not support structured-output / JSON schema. Remove output.format or _analysisSchema, or use a provider that implements the OpenAI chat-completions contract (e.g. openai, anthropic).",category:"validation",severity:"medium",retriable:!1});let a=n.prompt??n.input?.text??"",c=Date.now(),l=await this.executeStream({input:{text:a},systemPrompt:n.systemPrompt,maxTokens:n.maxTokens,temperature:n.temperature,abortSignal:n.abortSignal,timeout:n.timeout}),d="";for await(let m of l.stream)"content"in m&&typeof m.content=="string"&&(d+=m.content);let p={content:d,provider:this.providerName,model:this.modelName,usage:{input:0,output:0,total:0}};return g.info(`[ReplicateProvider] generate() complete in ${Date.now()-c}ms \u2014 ${d.length} chars`),p}async executeStream(e,t){let n=Date.now(),o=e.credentials?.replicate,s=o?.apiToken?.trim()||this.apiToken,i=o?.baseUrl||this.baseURL,a=$u({apiToken:s,baseUrl:i});if(!a)throw new Me({code:Ze.MISSING_CONFIGURATION,message:"Replicate auth could not be resolved (REPLICATE_API_TOKEN missing).",category:"configuration",severity:"high",retriable:!1});let c=Tkr(e);if(!c.trim())throw new Me({code:Ze.INVALID_PARAMETERS,message:"Replicate predictions require a prompt (input.text or prompt)",category:"validation",severity:"medium",retriable:!1});let l={prompt:c,...e.maxTokens!==void 0&&{max_new_tokens:e.maxTokens},temperature:e.temperature,top_p:1},d;try{d=await Ag(a,{model:this.modelName,input:l},{abortSignal:e.abortSignal})}catch(f){throw this.handleProviderError(f)}let p=Skr(d.output);if(!p)throw new Error(`Replicate prediction ${d.id} returned empty output`);let m={async*[Symbol.asyncIterator](){yield{content:p}}};return g.info(`[ReplicateProvider] Generated ${p.length} chars in ${Date.now()-n}ms \u2014 model ${this.modelName} (prediction ${d.id})`),{stream:m,provider:this.providerName,model:this.modelName,finishReason:"stop",metadata:{startTime:n,streamId:`replicate-${d.id}`}}}async executeImageGeneration(e){let t=Date.now(),n=e.credentials?.replicate,o=n?.apiToken?.trim()||this.apiToken,s=n?.baseUrl||this.baseURL,i=$u({apiToken:o,baseUrl:s});if(!i)throw new Me({code:Ze.MISSING_CONFIGURATION,message:"Replicate auth could not be resolved (REPLICATE_API_TOKEN missing).",category:"configuration",severity:"high",retriable:!1});let a=e.prompt??e.input?.text??"";if(!a.trim())throw new Me({code:Ze.INVALID_PARAMETERS,message:"Replicate image-gen requires a prompt",category:"validation",severity:"medium",retriable:!1});let c=e,l={prompt:a,output_format:"png"};c.aspectRatio&&(l.aspect_ratio=c.aspectRatio),c.negativePrompt&&(l.negative_prompt=c.negativePrompt),c.seed!==void 0&&(l.seed=c.seed);let d;try{d=await Ag(i,{model:this.modelName,input:l},{abortSignal:e.abortSignal})}catch(f){throw this.handleProviderError(f)}let p;try{p=await ly(d,26214400)}catch(f){throw this.handleProviderError(f)}let m=p.toString("base64");return g.info(`[ReplicateProvider] Generated image (${p.length} bytes) in ${Date.now()-t}ms \u2014 model ${this.modelName}`),{content:a,provider:this.providerName,model:this.modelName,usage:{input:0,output:0,total:0},imageOutput:{base64:m}}}formatProviderError(e){let t=e instanceof Error?e.message:typeof e=="string"?e:"Unknown error",n=e instanceof Error?e:void 0;return t.includes("401")||t.toLowerCase().includes("unauthorized")||t.toLowerCase().includes("invalid token")?new Me({code:Ze.PROVIDER_AUTH_FAILED,message:"Invalid Replicate API token. Get one at https://replicate.com/account/api-tokens",category:"configuration",severity:"high",retriable:!1,context:{provider:"replicate"},originalError:n}):t.includes("402")||t.toLowerCase().includes("insufficient credit")?new Me({code:Ze.PROVIDER_QUOTA_EXCEEDED,message:"Replicate insufficient credit. Top up at https://replicate.com/account/billing \u2014 most image/music models require a paid balance.",category:"resource",severity:"high",retriable:!1,context:{provider:"replicate"},originalError:n}):t.includes("429")||t.toLowerCase().includes("rate limit")?new Me({code:Ze.PROVIDER_QUOTA_EXCEEDED,message:"Replicate rate limit exceeded. Back off and retry.",category:"resource",severity:"high",retriable:!0,context:{provider:"replicate"},originalError:n}):t.toLowerCase().includes("not found")||t.includes("404")?new Me({code:Ze.PROVIDER_NOT_AVAILABLE,message:`Replicate model '${this.modelName}' not found. Use owner/name or owner/name:version format. Browse https://replicate.com/explore`,category:"validation",severity:"medium",retriable:!1,context:{provider:"replicate",model:this.modelName},originalError:n}):new Me({code:Ze.PROVIDER_NOT_AVAILABLE,message:`Replicate error: ${t}`,category:"execution",severity:"high",retriable:!1,context:{provider:"replicate"},originalError:n})}async validateConfiguration(){return typeof this.apiToken=="string"&&this.apiToken.trim().length>0}getConfiguration(){return{provider:this.providerName,model:this.modelName,defaultModel:v3e(),baseURL:this.baseURL}}},wkr=P4});var w3e={};ue(w3e,{RecraftProvider:()=>M4,default:()=>Ckr});var _kr,T3e,Ekr,S3e,M4,Ckr,_3e=E(async()=>{"use strict";$l();await Fd();Dn();Pt();W();an();Zm();Sh();_kr="https://external.api.recraft.ai/v1",T3e=12e4,Ekr=()=>Ht(PDe()),S3e=()=>Kt("RECRAFT_MODEL","recraftv3"),M4=class extends no{apiKey;baseURL;proxyFetch;constructor(e,t,n,o){let s=Zl(t)?t:void 0;super(e,"recraft",s);let i=o?.apiKey?.trim();this.apiKey=i&&i.length>0?i:Ekr(),this.baseURL=o?.baseURL??process.env.RECRAFT_BASE_URL??_kr,this.proxyFetch=gt(),g.debug("Recraft Provider initialized (image-gen only)",{modelName:this.modelName,baseURL:this.baseURL})}getProviderName(){return this.providerName}getDefaultModel(){return S3e()}supportsTools(){return!1}getAISDKModel(){throw new Error("Recraft is an image-generation-only provider; chat completions are not available.")}async executeStream(e,t){throw new Error("Recraft is an image-generation-only provider; streaming chat is not available.")}formatProviderError(e){let t=e instanceof Error?e.message:typeof e=="string"?e:"Unknown error";return t.includes("401")||t.toLowerCase().includes("unauthorized")?new It("Invalid Recraft API key. Get one at https://www.recraft.ai/api","recraft"):t.includes("429")||t.toLowerCase().includes("rate limit")?new Yt("Recraft rate limit exceeded. Back off and retry.","recraft"):t.includes("404")||t.includes("model_not_found")?new qt(`Recraft model '${this.modelName}' not found. Use recraftv3, recraftv3-svg, or recraftv2.`,"recraft"):new We(`Recraft error: ${t}`,"recraft")}async executeImageGeneration(e){let t=Date.now(),n=e.credentials?.recraft,o=n?.apiKey?.trim()||this.apiKey,s=n?.baseURL||this.baseURL,i=e.prompt??e.input?.text??"";if(!i.trim())throw new Error("Recraft image generation requires a prompt (input.text or prompt)");let a=e,c={model:e.model??this.modelName,prompt:i,n:1,response_format:"b64_json"};a.negativePrompt&&(c.negative_prompt=a.negativePrompt),a.style&&(c.style=a.style),a.styleId&&(c.style_id=a.styleId),a.size&&(c.size=a.size);let l=new AbortController,d=setTimeout(()=>l.abort(),T3e),p;try{p=await this.proxyFetch(`${s}/images/generations`,{method:"POST",headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json"},body:JSON.stringify(c),signal:l.signal})}catch(v){throw v instanceof Error&&v.name==="AbortError"?this.formatProviderError(new Error(`Recraft image-gen request timed out after ${T3e/1e3}s`)):this.formatProviderError(v)}finally{clearTimeout(d)}if(!p.ok){let v=await p.text();throw this.formatProviderError(new Error(`Recraft image-gen failed: ${p.status} \u2014 ${v}`))}let f=(await p.json()).data?.[0];if(!f)throw new Error("Recraft returned no image data");let h;if(f.b64_json)h=f.b64_json;else if(f.url){await Gl(f.url);let v=new AbortController,b=setTimeout(()=>v.abort(),6e4),S;try{S=await this.proxyFetch(f.url,{signal:v.signal})}catch(C){throw C instanceof Error&&C.name==="AbortError"?new Error("Recraft image download timed out after 60s",{cause:C}):C}finally{clearTimeout(b)}if(!S.ok)throw new Error(`Failed to download Recraft image: ${S.status}`);h=(await ha(S,26214400,"Recraft image")).toString("base64")}else throw new Error("Recraft response missing both b64_json and url");let y=Date.now()-t;return g.info(`[RecraftProvider] Generated image (${h.length} base64 chars) in ${y}ms \u2014 model ${this.modelName}`),{content:i,provider:this.providerName,model:this.modelName,usage:{input:0,output:1e3,total:1e3},imageOutput:{base64:h}}}async validateConfiguration(){return typeof this.apiKey=="string"&&this.apiKey.trim().length>0}getConfiguration(){return{provider:this.providerName,model:this.modelName,defaultModel:S3e(),baseURL:this.baseURL}}},Ckr=M4});var E3e={};ue(E3e,{Agent:()=>gAr,BedrockClient:()=>kkr,BedrockRuntimeClient:()=>Ikr,Blob:()=>mAr,Client:()=>hAr,ConverseCommand:()=>Pkr,ConverseStreamCommand:()=>Mkr,Cron:()=>Jkr,Dispatcher:()=>yAr,File:()=>pAr,FlowProducer:()=>Wkr,FormData:()=>dAr,GoogleAuth:()=>Ukr,HTTPException:()=>rAr,Headers:()=>uAr,Hippocampus:()=>zkr,HippocampusConfig:()=>jkr,Hono:()=>eAr,ImageFormat:()=>Okr,InvokeEndpointCommand:()=>Lkr,InvokeEndpointWithResponseStreamCommand:()=>Dkr,Job:()=>Hkr,ListFoundationModelsCommand:()=>Akr,MockAgent:()=>bAr,Pool:()=>fAr,Queue:()=>qkr,QueueScheduler:()=>Kkr,Request:()=>cAr,Response:()=>lAr,SageMakerRuntimeClient:()=>Nkr,TextToSpeechClient:()=>$kr,VertexAI:()=>Fkr,Webhook:()=>Bkr,Worker:()=>Vkr,convertToHtml:()=>Qkr,cors:()=>tAr,createClient:()=>Gkr,default:()=>Rkr,extractRawText:()=>Zkr,fetch:()=>aAr,getGlobalDispatcher:()=>xAr,interceptors:()=>TAr,logger:()=>nAr,parseBuffer:()=>Ykr,request:()=>SAr,secureHeaders:()=>oAr,selectCover:()=>Xkr,setGlobalDispatcher:()=>vAr,streamSSE:()=>sAr,timeout:()=>iAr});var nC,Ii,Rkr,kkr,Akr,Ikr,Pkr,Mkr,Okr,Nkr,Lkr,Dkr,Ukr,Fkr,$kr,Bkr,zkr,jkr,Gkr,qkr,Vkr,Hkr,Kkr,Wkr,Jkr,Ykr,Xkr,Zkr,Qkr,eAr,tAr,rAr,nAr,oAr,sAr,iAr,aAr,cAr,lAr,uAr,dAr,pAr,mAr,gAr,fAr,hAr,yAr,vAr,xAr,bAr,TAr,SAr,C3e=E(()=>{nC={get(r,e){return e==="__esModule"?!0:e==="default"?new Proxy({},{get:nC.get}):new Proxy(function(...t){return new Proxy({},{get:nC.get})},{get:nC.get,apply(t,n,o){return new Proxy({},{get:nC.get})},construct(t,n){return new Proxy({},{get:nC.get})}})}},Ii=new Proxy({},nC),Rkr=Ii,{BedrockClient:kkr,ListFoundationModelsCommand:Akr,BedrockRuntimeClient:Ikr,ConverseCommand:Pkr,ConverseStreamCommand:Mkr,ImageFormat:Okr}=Ii,{SageMakerRuntimeClient:Nkr,InvokeEndpointCommand:Lkr,InvokeEndpointWithResponseStreamCommand:Dkr}=Ii,{GoogleAuth:Ukr,VertexAI:Fkr,TextToSpeechClient:$kr}=Ii,{Webhook:Bkr}=Ii,{Hippocampus:zkr,HippocampusConfig:jkr}=Ii,{createClient:Gkr}=Ii,{Queue:qkr,Worker:Vkr,Job:Hkr,QueueScheduler:Kkr,FlowProducer:Wkr}=Ii,{Cron:Jkr}=Ii,{parseBuffer:Ykr,selectCover:Xkr}=Ii,{extractRawText:Zkr,convertToHtml:Qkr}=Ii,{Hono:eAr}=Ii,{cors:tAr,HTTPException:rAr,logger:nAr,secureHeaders:oAr,streamSSE:sAr,timeout:iAr}=Ii,aAr=globalThis.fetch,cAr=globalThis.Request,lAr=globalThis.Response,uAr=globalThis.Headers,dAr=globalThis.FormData,pAr=globalThis.File,mAr=globalThis.Blob,gAr=Ii.Agent,fAr=Ii.Pool,hAr=Ii.Client,yAr=Ii.Dispatcher,vAr=()=>{},xAr=()=>Ii,bAr=Ii.MockAgent,TAr={redirect:()=>r=>r,retry:()=>r=>r},SAr=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 R3e={};ue(R3e,{GoogleTTSHandler:()=>vb});var vb,O4=E(()=>{"use strict";Yi();W();co();vb=class r{client=null;voicesCache=null;static CACHE_TTL_MS=300*1e3;static DEFAULT_MAX_TEXT_LENGTH=5e3;static DEFAULT_API_TIMEOUT_MS=30*1e3;maxTextLength=r.DEFAULT_MAX_TEXT_LENGTH;credentialsPath;constructor(e){this.credentialsPath=e??process.env.GOOGLE_APPLICATION_CREDENTIALS}isConfigured(){return this.credentialsPath!==void 0}async getClient(){if(!this.client){let{TextToSpeechClient:e}=await Promise.resolve().then(()=>(C3e(),E3e));this.client=new e({keyFilename:this.credentialsPath})}return this.client}async getVoices(e){if(!this.isConfigured())throw new zt({code:Zt.PROVIDER_NOT_CONFIGURED,message:"Google Cloud TTS client not initialized. Set GOOGLE_APPLICATION_CREDENTIALS or pass credentials path.",category:"configuration",severity:"high",retriable:!1});let t=await this.getClient(),n=Re.createSpan("tts","tts.google.listVoices",{"tts.operation":"listVoices","tts.provider":"google"});try{if(this.voicesCache&&Date.now()-this.voicesCache.timestamp<r.CACHE_TTL_MS&&!e){let a=Re.endSpan(n,1);return nt().recordSpan(a),this.voicesCache.voices}let[o]=await t.listVoices(e?{languageCode:e}:{});if(!o.voices||o.voices.length===0){g.warn("Google Cloud TTS returned no voices");let a=Re.endSpan(n,1);return nt().recordSpan(a),[]}let s=[];for(let a of o.voices??[]){if(!a.name||!Array.isArray(a.languageCodes)||a.languageCodes.length===0){g.warn("Skipping voice with missing required fields",{name:a.name,languageCodesCount:a.languageCodes?.length});continue}let c=a.name,l=a.languageCodes,d=l[0],p=this.detectVoiceType(c),m=a.ssmlGender==="MALE"?"male":a.ssmlGender==="FEMALE"?"female":"neutral";s.push({id:c,name:c,languageCode:d,languageCodes:l,gender:m,type:p,naturalSampleRateHertz:a.naturalSampleRateHertz??void 0})}e||(this.voicesCache={voices:s,timestamp:Date.now()});let i=Re.endSpan(n,1);return nt().recordSpan(i),s}catch(o){let s=Re.endSpan(n,2,o instanceof Error?o.message:"Unknown error");nt().recordSpan(s);let i=o instanceof Error?o.message:"Unknown error";return g.error(`Failed to fetch Google TTS voices: ${i}`),[]}}async synthesize(e,t){if(!this.isConfigured())throw new zt({code:Zt.PROVIDER_NOT_CONFIGURED,message:"Google Cloud TTS client not initialized. Set GOOGLE_APPLICATION_CREDENTIALS or pass credentials path.",category:"configuration",severity:"high",retriable:!1});let n=await this.getClient(),o=t.voice??"en-US-Neural2-C",s=Re.createSpan("tts","tts.google.synthesize",{"tts.operation":"synthesize","tts.provider":"google","tts.voice":o,"tts.format":t.format??"mp3"}),i=Date.now();try{let a=e.startsWith("<speak>")&&e.endsWith("</speak>");if(e.startsWith("<speak>")&&!e.endsWith("</speak>")||!e.startsWith("<speak>")&&e.endsWith("</speak>"))throw new zt({code:Zt.INVALID_INPUT,message:"Malformed SSML: missing opening <speak> or closing </speak> tag.",category:"validation",severity:"medium",retriable:!1});let c=this.extractLanguageCode(o),l=this.mapFormat(t.format??"mp3"),d={input:a?{ssml:e}:{text:e},voice:{name:o,languageCode:c},audioConfig:{audioEncoding:l,speakingRate:t.speed??1,pitch:t.pitch??0,volumeGainDb:t.volumeGainDb??0}},[p]=await n.synthesizeSpeech(d,{timeout:r.DEFAULT_API_TIMEOUT_MS}),m=p.audioContent;if(!m)throw new zt({code:Zt.SYNTHESIS_FAILED,message:"Google TTS returned empty audio content",category:"execution",severity:"high",retriable:!0});let f=m instanceof Uint8Array?Buffer.from(m):typeof m=="string"?Buffer.from(m,"base64"):(()=>{throw new zt({code:Zt.SYNTHESIS_FAILED,message:"Unsupported audioContent type returned by Google TTS",category:"execution",severity:"high",retriable:!0,context:{type:typeof m}})})(),h=Date.now()-i,y=Re.endSpan(s,1);return nt().recordSpan(y),{buffer:f,format:t.format??"mp3",size:f.length,voice:o,metadata:{latency:h,provider:"google-ai"}}}catch(a){let c=Re.endSpan(s,2,a instanceof Error?a.message:String(a));if(nt().recordSpan(c),a instanceof zt)throw a;let l=Date.now()-i,d=a instanceof Error?a.message:"Unknown error";throw new zt({code:Zt.SYNTHESIS_FAILED,message:`Google TTS failed after ${l}ms: ${d}`,category:"execution",severity:"high",retriable:!0,context:{latency:l},originalError:a instanceof Error?a:void 0})}}extractLanguageCode(e){let t=e.split("-");if(t.length>=2)return`${t[0]}-${t[1]}`;throw new zt({code:Zt.INVALID_INPUT,message:`Invalid Google TTS voiceId format: "${e}". Expected format like "en-US-Neural2-C".`,category:"validation",severity:"medium",retriable:!1,context:{voiceId:e}})}mapFormat(e){switch(e.toLowerCase()){case"mp3":return"MP3";case"wav":return"LINEAR16";case"ogg":case"opus":return"OGG_OPUS";default:throw new zt({code:Zt.INVALID_INPUT,message:`Unsupported audio format: ${e}`,category:"validation",severity:"medium",retriable:!1,context:{format:e}})}}detectVoiceType(e){let t=e.toLowerCase().split("-");return t.some(n=>n.startsWith("chirp"))?"chirp":t.includes("neural2")?"neural":t.includes("wavenet")?"wavenet":t.includes("standard")?"standard":"unknown"}}});var k3e={};ue(k3e,{OpenAITTS:()=>Ig});var Ig,N4=E(()=>{"use strict";W();Yi();Ig=class r{apiKey;baseUrl="https://api.openai.com/v1";maxTextLength=4096;static VOICES=[{id:"alloy",name:"Alloy",languageCode:"en",languageCodes:["en"],gender:"neutral",type:"neural"},{id:"echo",name:"Echo",languageCode:"en",languageCodes:["en"],gender:"male",type:"neural"},{id:"fable",name:"Fable",languageCode:"en",languageCodes:["en"],gender:"neutral",type:"neural"},{id:"onyx",name:"Onyx",languageCode:"en",languageCodes:["en"],gender:"male",type:"neural"},{id:"nova",name:"Nova",languageCode:"en",languageCodes:["en"],gender:"female",type:"neural"},{id:"shimmer",name:"Shimmer",languageCode:"en",languageCodes:["en"],gender:"female",type:"neural"}];constructor(e){let t=(e??process.env.OPENAI_API_KEY??"").trim();this.apiKey=t.length>0?t:null}isConfigured(){return this.apiKey!==null}async getVoices(e){return e&&!e.startsWith("en"),r.VOICES}async synthesize(e,t={}){if(!this.apiKey)throw new zt({code:Zt.PROVIDER_NOT_CONFIGURED,message:"OpenAI TTS API key not configured",category:"configuration",severity:"high",retriable:!1});let n=Date.now(),o=t;try{let s=o.model??(t.quality==="hd"?"tts-1-hd":"tts-1"),i=t.voice??"alloy",a=this.mapFormat(t.format??"mp3"),c={model:s,input:e,voice:i,response_format:a,speed:t.speed??1},l=new AbortController,d=setTimeout(()=>l.abort(),3e4),p;try{p=await fetch(`${this.baseUrl}/audio/speech`,{method:"POST",headers:{Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify(c),signal:l.signal})}catch(b){throw b instanceof Error&&b.name==="AbortError"?new zt({code:Zt.SYNTHESIS_FAILED,message:"OpenAI TTS request timed out after 30 seconds",category:"network",severity:"high",retriable:!0,originalError:b}):b}finally{clearTimeout(d)}if(!p.ok){let S=(await p.json().catch(()=>Object.create(null))).error?.message||`HTTP ${p.status}`,w=p.status===408||p.status===429||p.status>=500;throw new zt({code:Zt.SYNTHESIS_FAILED,message:S,category:w?"network":"execution",severity:"high",retriable:w,context:{status:p.status,model:s,responseFormat:a}})}let m=Date.now()-n,f=await p.arrayBuffer(),h=Buffer.from(f),y=this.effectiveFormat(a),v={buffer:h,format:y,size:h.length,voice:i,sampleRate:this.getSampleRate(y),metadata:{latency:m,provider:"openai-tts",model:s,requestedFormat:t.format,responseFormat:a}};return g.info(`[OpenAITTSHandler] Synthesized ${h.length} bytes in ${m}ms`),v}catch(s){if(s instanceof zt)throw s;let i=s instanceof Error?s.message:String(s||"Unknown error");throw g.error(`[OpenAITTSHandler] Synthesis failed: ${i}`),new zt({code:Zt.SYNTHESIS_FAILED,message:`Synthesis failed: ${i}`,category:"execution",severity:"high",retriable:!0,context:{textLength:e.length},originalError:s instanceof Error?s:void 0})}}mapFormat(e){let n={mp3:"mp3",wav:"wav",ogg:"opus",opus:"opus",flac:"flac",pcm16:"pcm"}[e];return n===void 0?(g.warn(`[OpenAITTSHandler] Unsupported format "${e}" \u2014 falling back to "mp3". Supported formats: mp3, wav, ogg, opus, flac, pcm16.`),"mp3"):n}getSampleRate(e){switch(e){case"opus":case"ogg":return 48e3;default:return 24e3}}effectiveFormat(e){switch(e){case"mp3":return"mp3";case"wav":return"wav";case"opus":return"opus";case"flac":return"flac";case"pcm":return"pcm16";default:return"mp3"}}}});var A3e={};ue(A3e,{ElevenLabsTTS:()=>Pg});var Pg,L4=E(()=>{"use strict";W();Yi();Pg=class r{apiKey;baseUrl="https://api.elevenlabs.io/v1";voicesCache=null;static CACHE_TTL_MS=300*1e3;maxTextLength=5e3;constructor(e){let t=(e??process.env.ELEVENLABS_API_KEY??"").trim();this.apiKey=t.length>0?t:null}isConfigured(){return this.apiKey!==null}async getVoices(e){if(!this.apiKey)throw new zt({code:Zt.PROVIDER_NOT_CONFIGURED,message:"ElevenLabs API key not configured",category:"configuration",severity:"high",retriable:!1});if(this.voicesCache&&Date.now()-this.voicesCache.timestamp<r.CACHE_TTL_MS&&!e)return this.voicesCache.voices;try{let t=new AbortController,n=setTimeout(()=>t.abort(),3e4),o;try{o=await fetch(`${this.baseUrl}/voices`,{method:"GET",headers:{"xi-api-key":this.apiKey},signal:t.signal})}catch(a){throw a instanceof Error&&a.name==="AbortError"?new zt({code:Zt.SYNTHESIS_FAILED,message:"ElevenLabs voices request timed out after 30 seconds",category:"network",severity:"medium",retriable:!0,originalError:a}):a}finally{clearTimeout(n)}if(!o.ok)throw new Error(`HTTP ${o.status}`);let i=(await o.json()).voices.map(a=>({id:a.voice_id,name:a.name,languageCode:"en",languageCodes:["en","es","fr","de","it","pt","pl","hi","ar","zh","ja","ko"],gender:this.mapGender(a.labels?.gender),type:"neural",description:a.labels?.description}));if(e){let a=e.toLowerCase(),c=a.split("-")[0];i=i.filter(l=>l.languageCodes?.some(d=>{let p=d.toLowerCase();return p===a||p===c||p.startsWith(c)}))}return e||(this.voicesCache={voices:i,timestamp:Date.now()}),i}catch(t){let n=t instanceof Error?t.message:String(t||"Unknown error");throw g.error(`[ElevenLabsTTSHandler] Failed to get voices: ${n}`),new zt({code:Zt.SYNTHESIS_FAILED,message:`Failed to get voices: ${n}`,category:"network",severity:"medium",retriable:!0,originalError:t instanceof Error?t:void 0})}}async synthesize(e,t={}){if(!this.apiKey)throw new zt({code:Zt.PROVIDER_NOT_CONFIGURED,message:"ElevenLabs API key not configured",category:"configuration",severity:"high",retriable:!1});let n=Date.now(),o=t;try{let s=t.voice??"21m00Tcm4TlvDq8ikWAM",i=o.model??"eleven_multilingual_v2",a={text:e,model_id:i,voice_settings:{stability:o.stability??.5,similarity_boost:o.similarityBoost??.75,style:o.style??0,use_speaker_boost:o.useSpeakerBoost??!0}},c=this.mapFormat(t.format??"mp3"),l=new AbortController,d=setTimeout(()=>l.abort(),3e4),p;try{p=await fetch(`${this.baseUrl}/text-to-speech/${s}?output_format=${c}`,{method:"POST",headers:{"xi-api-key":this.apiKey,"Content-Type":"application/json"},body:JSON.stringify(a),signal:l.signal})}catch(v){throw v instanceof Error&&v.name==="AbortError"?new zt({code:Zt.SYNTHESIS_FAILED,message:"ElevenLabs TTS request timed out after 30 seconds",category:"network",severity:"high",retriable:!0,originalError:v}):v}finally{clearTimeout(d)}if(!p.ok){let b=(await p.json().catch(()=>Object.create(null))).detail?.message||`HTTP ${p.status}`;throw new Error(b)}let m=Date.now()-n,f=await p.arrayBuffer(),h=Buffer.from(f),y={buffer:h,format:this.effectiveFormat(c),size:h.length,voice:s,sampleRate:this.getSampleRate(c),metadata:{latency:m,provider:"elevenlabs-tts",model:i,requestedFormat:t.format,outputFormat:c}};return g.info(`[ElevenLabsTTSHandler] Synthesized ${h.length} bytes in ${m}ms`),y}catch(s){if(s instanceof zt)throw s;let i=s instanceof Error?s.message:String(s||"Unknown error");throw g.error(`[ElevenLabsTTSHandler] Synthesis failed: ${i}`),new zt({code:Zt.SYNTHESIS_FAILED,message:`Synthesis failed: ${i}`,category:"execution",severity:"high",retriable:!0,context:{textLength:e.length},originalError:s instanceof Error?s:void 0})}}mapGender(e){if(!e)return"neutral";let t=e.toLowerCase();return t.includes("male")&&!t.includes("female")?"male":t.includes("female")?"female":"neutral"}mapFormat(e){return{mp3:"mp3_44100_128",wav:"pcm_44100",ogg:"ogg_22050",opus:"ogg_22050"}[e]??"mp3_44100_128"}getSampleRate(e){return e.includes("44100")?44100:e.includes("22050")?22050:e.includes("24000")?24e3:44100}effectiveFormat(e){return e.startsWith("mp3")?"mp3":e.startsWith("pcm")?"pcm16":e.startsWith("ogg")?"opus":"mp3"}}});var I3e={};ue(I3e,{AzureTTS:()=>Mg});var Mg,D4=E(()=>{"use strict";W();Yi();Mg=class r{apiKey;region;voicesCache=null;static CACHE_TTL_MS=1800*1e3;maxTextLength=1e4;constructor(e,t){let n=(e??process.env.AZURE_SPEECH_KEY??"").trim();this.apiKey=n.length>0?n:null;let o=(t??process.env.AZURE_SPEECH_REGION??"").trim();this.region=o.length>0?o:"eastus"}isConfigured(){return this.apiKey!==null&&this.region.length>0}async getVoices(e){if(!this.apiKey)throw new zt({code:Zt.PROVIDER_NOT_CONFIGURED,message:"Azure Speech key not configured",category:"configuration",severity:"high",retriable:!1});if(this.voicesCache&&Date.now()-this.voicesCache.timestamp<r.CACHE_TTL_MS&&!e)return this.voicesCache.voices;try{let t=new AbortController,n=setTimeout(()=>t.abort(),3e4),o;try{o=await fetch(`https://${this.region}.tts.speech.microsoft.com/cognitiveservices/voices/list`,{method:"GET",headers:{"Ocp-Apim-Subscription-Key":this.apiKey},signal:t.signal})}catch(a){throw a instanceof Error&&a.name==="AbortError"?new zt({code:Zt.SYNTHESIS_FAILED,message:"Azure TTS voices request timed out after 30 seconds",category:"network",severity:"medium",retriable:!0,originalError:a}):a}finally{clearTimeout(n)}if(!o.ok)throw new Error(`HTTP ${o.status}`);let i=(await o.json()).map(a=>({id:a.ShortName,name:a.DisplayName,languageCode:a.Locale,languageCodes:[a.Locale],gender:this.mapGender(a.Gender),type:a.VoiceType.toLowerCase().includes("neural")?"neural":"standard",description:a.LocaleName}));return e&&(i=i.filter(a=>a.languageCode.toLowerCase().startsWith(e.toLowerCase())||a.languageCode.toLowerCase()===e.toLowerCase())),e||(this.voicesCache={voices:i,timestamp:Date.now()}),i}catch(t){if(t instanceof zt)throw t;let n=t instanceof Error?t.message:String(t||"Unknown error");throw g.error(`[AzureTTSHandler] Failed to get voices: ${n}`),new zt({code:Zt.SYNTHESIS_FAILED,message:`Failed to get voices: ${n}`,category:"network",severity:"medium",retriable:!0,originalError:t instanceof Error?t:void 0})}}async synthesize(e,t={}){if(!this.apiKey)throw new zt({code:Zt.PROVIDER_NOT_CONFIGURED,message:"Azure Speech key not configured",category:"configuration",severity:"high",retriable:!1});let n=Date.now(),o=t;try{let s=t.voice??"en-US-JennyNeural",i=o.outputFormat??this.mapFormat(t.format??"mp3"),a=this.buildSSML(e,s,t),c=new AbortController,l=setTimeout(()=>c.abort(),3e4),d;try{d=await fetch(`https://${this.region}.tts.speech.microsoft.com/cognitiveservices/v1`,{method:"POST",headers:{"Ocp-Apim-Subscription-Key":this.apiKey,"Content-Type":"application/ssml+xml","X-Microsoft-OutputFormat":i},body:a,signal:c.signal})}catch(y){throw y instanceof Error&&y.name==="AbortError"?new zt({code:Zt.SYNTHESIS_FAILED,message:"Azure TTS request timed out after 30 seconds",category:"network",severity:"high",retriable:!0,originalError:y}):y}finally{clearTimeout(l)}if(!d.ok){let y=await d.text();throw new Error(`HTTP ${d.status}: ${y}`)}let p=Date.now()-n,m=await d.arrayBuffer(),f=Buffer.from(m),h={buffer:f,format:this.effectiveFormat(i),size:f.length,voice:s,sampleRate:this.getSampleRate(i),metadata:{latency:p,provider:"azure-tts",requestedFormat:t.format,outputFormat:i,region:this.region}};return g.info(`[AzureTTSHandler] Synthesized ${f.length} bytes in ${p}ms`),h}catch(s){if(s instanceof zt)throw s;let i=s instanceof Error?s.message:String(s||"Unknown error");throw g.error(`[AzureTTSHandler] Synthesis failed: ${i}`),new zt({code:Zt.SYNTHESIS_FAILED,message:`Synthesis failed: ${i}`,category:"execution",severity:"high",retriable:!0,context:{textLength:e.length},originalError:s instanceof Error?s:void 0})}}buildSSML(e,t,n){let o=n;if(o.ssmlTemplate)return o.ssmlTemplate.replace("{text}",this.escapeXml(e)).replace("{voice}",this.escapeXml(t));if(o.allowRawSSML&&e.trim().startsWith("<speak"))return e;let s=n.speed?`${Math.round((n.speed-1)*100)}%`:"0%",i=n.pitch??0,a=i>=0?`+${Math.round(i)}st`:`${Math.round(i)}st`;return`<speak version="1.0" xmlns="http://www.w3.org/2001/10/synthesis" xml:lang="${this.escapeXml(this.extractLanguage(t))}">
2159
2159
  <voice name="${this.escapeXml(t)}">
2160
2160
  <prosody rate="${s}" pitch="${a}">
2161
2161
  ${this.escapeXml(e)}
@@ -30,8 +30,14 @@ export declare class OpenAITTS implements TTSHandler {
30
30
  synthesize(text: string, options?: TTSOptions): Promise<TTSResult>;
31
31
  /**
32
32
  * Map TTSAudioFormat to OpenAI response_format.
33
- * OpenAI TTS supports: mp3, wav, opus (ogg maps to opus).
34
- * Unsupported formats are coerced to mp3 with a warning.
33
+ *
34
+ * OpenAI's /audio/speech accepts mp3, opus, aac, flac, wav and pcm. This map
35
+ * previously stopped at mp3/wav/ogg/opus/pcm16, so `flac` — a valid
36
+ * TTSAudioFormat *and* a real OpenAI response_format — was treated as
37
+ * unsupported and silently downgraded to mp3 (#479). A caller who asked for
38
+ * lossless got lossy, and the only signal was a warn-level log.
39
+ *
40
+ * Formats OpenAI genuinely cannot produce still coerce to mp3 with a warning.
35
41
  */
36
42
  private mapFormat;
37
43
  /**
@@ -212,8 +212,14 @@ export class OpenAITTS {
212
212
  }
213
213
  /**
214
214
  * Map TTSAudioFormat to OpenAI response_format.
215
- * OpenAI TTS supports: mp3, wav, opus (ogg maps to opus).
216
- * Unsupported formats are coerced to mp3 with a warning.
215
+ *
216
+ * OpenAI's /audio/speech accepts mp3, opus, aac, flac, wav and pcm. This map
217
+ * previously stopped at mp3/wav/ogg/opus/pcm16, so `flac` — a valid
218
+ * TTSAudioFormat *and* a real OpenAI response_format — was treated as
219
+ * unsupported and silently downgraded to mp3 (#479). A caller who asked for
220
+ * lossless got lossy, and the only signal was a warn-level log.
221
+ *
222
+ * Formats OpenAI genuinely cannot produce still coerce to mp3 with a warning.
217
223
  */
218
224
  mapFormat(format) {
219
225
  const formats = {
@@ -221,13 +227,19 @@ export class OpenAITTS {
221
227
  wav: "wav",
222
228
  ogg: "opus", // OpenAI uses opus for ogg
223
229
  opus: "opus",
230
+ // #479: flac is the entry this fix added. It is a first-class OpenAI
231
+ // response_format and was the only TTSAudioFormat member missing from
232
+ // this map, so it fell through to the mp3 coercion below. The issue also
233
+ // mentions aac, but aac is not a member of TTSAudioFormat and therefore
234
+ // cannot be requested — no mapping is needed or possible for it.
235
+ flac: "flac",
224
236
  // OpenAI's "pcm" is raw 16-bit signed LE @ 24kHz (no header) — maps to
225
237
  // canonical pcm16 in TTSResult.format. See effectiveFormat() below.
226
238
  pcm16: "pcm",
227
239
  };
228
240
  const mapped = formats[format];
229
241
  if (mapped === undefined) {
230
- logger.warn(`[OpenAITTSHandler] Unsupported format "${format}" — falling back to "mp3". Supported formats: mp3, wav, ogg, opus, pcm16.`);
242
+ logger.warn(`[OpenAITTSHandler] Unsupported format "${format}" — falling back to "mp3". Supported formats: mp3, wav, ogg, opus, flac, pcm16.`);
231
243
  return "mp3";
232
244
  }
233
245
  return mapped;
@@ -259,6 +271,8 @@ export class OpenAITTS {
259
271
  return "wav";
260
272
  case "opus":
261
273
  return "opus";
274
+ case "flac":
275
+ return "flac";
262
276
  // Raw PCM (16-bit signed LE @ 24kHz, no header) — keep semantics in
263
277
  // TTSResult.format so consumers don't write raw bytes to a .wav file.
264
278
  case "pcm":
@@ -30,8 +30,14 @@ export declare class OpenAITTS implements TTSHandler {
30
30
  synthesize(text: string, options?: TTSOptions): Promise<TTSResult>;
31
31
  /**
32
32
  * Map TTSAudioFormat to OpenAI response_format.
33
- * OpenAI TTS supports: mp3, wav, opus (ogg maps to opus).
34
- * Unsupported formats are coerced to mp3 with a warning.
33
+ *
34
+ * OpenAI's /audio/speech accepts mp3, opus, aac, flac, wav and pcm. This map
35
+ * previously stopped at mp3/wav/ogg/opus/pcm16, so `flac` — a valid
36
+ * TTSAudioFormat *and* a real OpenAI response_format — was treated as
37
+ * unsupported and silently downgraded to mp3 (#479). A caller who asked for
38
+ * lossless got lossy, and the only signal was a warn-level log.
39
+ *
40
+ * Formats OpenAI genuinely cannot produce still coerce to mp3 with a warning.
35
41
  */
36
42
  private mapFormat;
37
43
  /**
@@ -212,8 +212,14 @@ export class OpenAITTS {
212
212
  }
213
213
  /**
214
214
  * Map TTSAudioFormat to OpenAI response_format.
215
- * OpenAI TTS supports: mp3, wav, opus (ogg maps to opus).
216
- * Unsupported formats are coerced to mp3 with a warning.
215
+ *
216
+ * OpenAI's /audio/speech accepts mp3, opus, aac, flac, wav and pcm. This map
217
+ * previously stopped at mp3/wav/ogg/opus/pcm16, so `flac` — a valid
218
+ * TTSAudioFormat *and* a real OpenAI response_format — was treated as
219
+ * unsupported and silently downgraded to mp3 (#479). A caller who asked for
220
+ * lossless got lossy, and the only signal was a warn-level log.
221
+ *
222
+ * Formats OpenAI genuinely cannot produce still coerce to mp3 with a warning.
217
223
  */
218
224
  mapFormat(format) {
219
225
  const formats = {
@@ -221,13 +227,19 @@ export class OpenAITTS {
221
227
  wav: "wav",
222
228
  ogg: "opus", // OpenAI uses opus for ogg
223
229
  opus: "opus",
230
+ // #479: flac is the entry this fix added. It is a first-class OpenAI
231
+ // response_format and was the only TTSAudioFormat member missing from
232
+ // this map, so it fell through to the mp3 coercion below. The issue also
233
+ // mentions aac, but aac is not a member of TTSAudioFormat and therefore
234
+ // cannot be requested — no mapping is needed or possible for it.
235
+ flac: "flac",
224
236
  // OpenAI's "pcm" is raw 16-bit signed LE @ 24kHz (no header) — maps to
225
237
  // canonical pcm16 in TTSResult.format. See effectiveFormat() below.
226
238
  pcm16: "pcm",
227
239
  };
228
240
  const mapped = formats[format];
229
241
  if (mapped === undefined) {
230
- logger.warn(`[OpenAITTSHandler] Unsupported format "${format}" — falling back to "mp3". Supported formats: mp3, wav, ogg, opus, pcm16.`);
242
+ logger.warn(`[OpenAITTSHandler] Unsupported format "${format}" — falling back to "mp3". Supported formats: mp3, wav, ogg, opus, flac, pcm16.`);
231
243
  return "mp3";
232
244
  }
233
245
  return mapped;
@@ -259,6 +271,8 @@ export class OpenAITTS {
259
271
  return "wav";
260
272
  case "opus":
261
273
  return "opus";
274
+ case "flac":
275
+ return "flac";
262
276
  // Raw PCM (16-bit signed LE @ 24kHz, no header) — keep semantics in
263
277
  // TTSResult.format so consumers don't write raw bytes to a .wav file.
264
278
  case "pcm":
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@juspay/neurolink",
3
- "version": "10.10.10",
3
+ "version": "10.10.11",
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": {