@juspay/neurolink 13.9.0 → 13.10.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/neurolink.js CHANGED
@@ -76,7 +76,7 @@ import { SkillsManager } from "./skills/skillsManager.js";
76
76
  import { createSkillCallTools, createSkillTools } from "./skills/skillTools.js";
77
77
  import { getMetricsAggregator, MetricsAggregator, } from "./observability/metricsAggregator.js";
78
78
  import { AnalyticsService, calculateAdvancedCost, parseAnalyticsQualityScore, } from "./analytics/index.js";
79
- import { SpanStatus, SpanType, CircuitBreakerOpenError, ConversationMemoryError, DEFAULT_DECISION_HOOK_TIMEOUT_MS, MAX_DECISION_HOOK_TIMEOUT_MS, ModelAccessDeniedError, } from "./types/index.js";
79
+ import { SpanStatus, SpanType, CircuitBreakerOpenError, ConversationMemoryError, ConversationWriterEpochError, DEFAULT_DECISION_HOOK_TIMEOUT_MS, MAX_DECISION_HOOK_TIMEOUT_MS, ModelAccessDeniedError, } from "./types/index.js";
80
80
  import { resolveTerminalAgentMode } from "./agent/prompts/terminalAgentPrompt.js";
81
81
  import { getExporterRegistry } from "./observability/exporterRegistry.js";
82
82
  import { SpanSerializer } from "./observability/utils/spanSerializer.js";
@@ -6053,6 +6053,11 @@ Current user's request: ${currentInput}`;
6053
6053
  await this.conversationMemory.initialize();
6054
6054
  }
6055
6055
  catch (err) {
6056
+ // Strict storage admission must not silently downgrade to process-local history.
6057
+ if (this.conversationMemoryConfig?.conversationMemory
6058
+ ?.erasureWriteProtocol === "conversation-erasure-v1") {
6059
+ throw err;
6060
+ }
6056
6061
  logger.warn("[NEUROLINK] Redis memory init failed, falling back to in-memory", {
6057
6062
  error: err instanceof Error ? err.message : String(err),
6058
6063
  generateInternalId,
@@ -6755,142 +6760,7 @@ Current user's request: ${currentInput}`;
6755
6760
  // AbortError propagation semantics. Falls through to the standard path
6756
6761
  // when no pool is configured.
6757
6762
  if (this.modelPool) {
6758
- const pool = this.modelPool;
6759
- const maxPoolAttempts = pool.maxAttempts;
6760
- const triedKeys = new Set();
6761
- let poolLastError = null;
6762
- for (let attempt = 0; attempt < maxPoolAttempts; attempt++) {
6763
- if (options.abortSignal?.aborted) {
6764
- throw new DOMException("The operation was aborted", "AbortError");
6765
- }
6766
- const member = pool.selectNext(triedKeys);
6767
- if (!member) {
6768
- // All available members exhausted.
6769
- break;
6770
- }
6771
- triedKeys.add(pool.memberKey(member));
6772
- // Temporarily override provider/model/region from the pool member.
6773
- const savedProvider = options.provider;
6774
- const savedModel = options.model;
6775
- const savedRegion = options.region;
6776
- options.provider = member.provider;
6777
- // When the member omits model/region, clear inherited values so the
6778
- // provider's own default is used rather than a mismatched caller value.
6779
- options.model = member.model ?? undefined;
6780
- options.region = member.region ?? undefined;
6781
- const poolProviderName = member.provider;
6782
- logger.debug(`[${functionTag}] ModelPool: attempting member`, {
6783
- provider: poolProviderName,
6784
- model: member.model ?? options.model,
6785
- attempt,
6786
- });
6787
- try {
6788
- // Get conversation messages for context (use pre-compacted if provided)
6789
- const poolOptionsWithMessages = options;
6790
- const poolConversationMessages = poolOptionsWithMessages
6791
- .conversationMessages?.length
6792
- ? poolOptionsWithMessages.conversationMessages
6793
- : await getConversationMessages(this.conversationMemory, options);
6794
- const poolProvider = await AIProviderFactory.createProvider(poolProviderName, options.model, !options.disableTools, this, options.region, this.resolveCredentials(options.credentials));
6795
- poolProvider.setTraceContext(this._metricsTraceContext);
6796
- poolProvider.setupToolExecutor({
6797
- customTools: this.getCustomTools(),
6798
- executeTool: (toolName, params) => this.executeTool(toolName, params, {
6799
- disableToolCache: options.disableToolCache,
6800
- }),
6801
- }, functionTag);
6802
- poolProvider.setFileToolRootPolicy?.(this.fileToolRootsFor(options));
6803
- const poolResult = await poolProvider.generate({
6804
- ...options,
6805
- conversationMessages: poolConversationMessages,
6806
- });
6807
- if (!poolResult) {
6808
- throw new Error(`ModelPool: provider ${poolProviderName} returned null result`);
6809
- }
6810
- pool.recordSuccess(member);
6811
- const responseTime = Date.now() - startTime;
6812
- // Restore original options fields so callers see a clean object.
6813
- options.provider = savedProvider;
6814
- options.model = savedModel;
6815
- options.region = savedRegion;
6816
- return {
6817
- content: poolResult.content || "",
6818
- provider: poolProviderName,
6819
- model: poolResult.model,
6820
- usage: poolResult.usage,
6821
- responseTime,
6822
- finishReason: poolResult.finishReason,
6823
- stopReason: poolResult.stopReason,
6824
- rawFinishReason: poolResult.rawFinishReason,
6825
- stepsUsed: poolResult.stepsUsed,
6826
- toolsUsed: poolResult.toolsUsed || [],
6827
- toolCalls: poolResult.toolCalls ?? [],
6828
- // Lossless pass-through: keep the full ToolExecutionRecord
6829
- // fields (params/resultText/isError/timing) alongside the
6830
- // legacy {toolName,executionTime,success} shape this internal
6831
- // result declares, so the final GenerateResult mapping
6832
- // reconstructs real records instead of empty ones.
6833
- toolExecutions: poolResult.toolExecutions?.map((te) => ({
6834
- ...te,
6835
- executionTime: te.durationMs,
6836
- success: !te.isError,
6837
- })),
6838
- // A tool RAN (toolsUsed), not merely dispatched.
6839
- enhancedWithTools: !!poolResult.toolsUsed?.length,
6840
- analytics: poolResult.analytics,
6841
- evaluation: poolResult.evaluation,
6842
- audio: poolResult.audio,
6843
- ttsMetadata: poolResult.ttsMetadata,
6844
- video: poolResult.video,
6845
- avatar: poolResult.avatar,
6846
- music: poolResult.music,
6847
- ppt: poolResult.ppt,
6848
- imageOutput: poolResult.imageOutput,
6849
- reasoning: poolResult.reasoning,
6850
- reasoningTokens: poolResult.reasoningTokens,
6851
- _generationEndEmitted: poolResult._generationEndEmitted,
6852
- };
6853
- }
6854
- catch (poolError) {
6855
- // Restore options unconditionally on failure.
6856
- options.provider = savedProvider;
6857
- options.model = savedModel;
6858
- options.region = savedRegion;
6859
- if (isAbortError(poolError)) {
6860
- throw poolError;
6861
- }
6862
- if (isNonRetryableForPool(poolError)) {
6863
- const poolErrMsg = poolError instanceof Error
6864
- ? poolError.message
6865
- : String(poolError);
6866
- logger.warn(`[${functionTag}] ModelPool: non-retryable error from ${poolProviderName}, stopping pool`, { error: poolErrMsg });
6867
- pool.recordFailure(member, classifyProviderError(poolError));
6868
- // Wrap in a plain Error so runWithFallbackOrchestration does not
6869
- // mistake this for a ModelAccessDeniedError and start a second
6870
- // retry layer on top of the already-exhausted pool.
6871
- throw new Error(`[ModelPool] non-retryable: ${poolErrMsg}`, {
6872
- cause: poolError,
6873
- });
6874
- }
6875
- pool.recordFailure(member, classifyProviderError(poolError));
6876
- poolLastError =
6877
- poolError instanceof Error
6878
- ? poolError
6879
- : new Error(String(poolError));
6880
- logger.warn(`[${functionTag}] ModelPool: member ${poolProviderName} failed`, { error: poolLastError.message });
6881
- }
6882
- }
6883
- // All pool members failed or were exhausted.
6884
- const poolResponseTime = Date.now() - startTime;
6885
- logger.error(`[${functionTag}] ModelPool: all members failed`, {
6886
- triedKeys: Array.from(triedKeys),
6887
- lastError: poolLastError?.message,
6888
- responseTime: poolResponseTime,
6889
- });
6890
- // Wrap in a plain Error (not a typed error class) so that
6891
- // runWithFallbackOrchestration does not re-activate the modelChain /
6892
- // providerFallback layer on top of an already-exhausted pool.
6893
- throw new Error(`[ModelPool] all members failed: ${poolLastError?.message ?? "no members available"}`);
6763
+ return this.generateViaModelPool(this.modelPool, options, startTime, functionTag);
6894
6764
  }
6895
6765
  // ─── End ModelPool path ───────────────────────────────────────────────────
6896
6766
  let lastError = null;
@@ -6962,211 +6832,14 @@ Current user's request: ${currentInput}`;
6962
6832
  // as an unbounded retry loop (93K→299K tokens, no verdict, ever).
6963
6833
  // The throw remains for the truly unrecoverable case: system
6964
6834
  // prompt + tool definitions alone exceed the budget.
6965
- let promptWindowRecovered = false;
6966
6835
  if (!budgetCheck.withinBudget && !dpgHasCompactableMessages) {
6967
- const fixedOverhead = (budgetCheck.breakdown?.systemPrompt ?? 0) +
6968
- (budgetCheck.breakdown?.toolDefinitions ?? 0) +
6969
- (budgetCheck.breakdown?.fileAttachments ?? 0);
6970
- // 3% margin against estimator drift; 1024-token floor — below
6971
- // that, a windowed prompt carries too little to answer from.
6972
- const promptBudget = Math.floor((budgetCheck.availableInputTokens - fixedOverhead) * 0.97);
6973
- const promptText = typeof options.prompt === "string" ? options.prompt : undefined;
6974
- if (promptText &&
6975
- promptBudget >= 1024 &&
6976
- (budgetCheck.breakdown?.currentPrompt ?? 0) > promptBudget) {
6977
- const marker = "\n\n[... middle of this prompt elided by NeuroLink to fit the model's context window ...]\n\n";
6978
- // Proportional char budget from the observed chars-per-token of
6979
- // THIS text, re-checked and shrunk until the estimator agrees.
6980
- let charBudget = Math.floor(promptText.length *
6981
- (promptBudget /
6982
- Math.max(budgetCheck.breakdown?.currentPrompt ?? 1, 1)));
6983
- let windowed = promptText;
6984
- for (let attempt = 0; attempt < 4; attempt++) {
6985
- const headChars = Math.floor(charBudget * 0.6);
6986
- const tailChars = Math.max(charBudget - headChars - marker.length, 0);
6987
- windowed =
6988
- promptText.slice(0, headChars) +
6989
- marker +
6990
- (tailChars > 0 ? promptText.slice(-tailChars) : "");
6991
- const recheck = checkContextBudget({
6992
- provider: providerName,
6993
- model: options.model,
6994
- maxTokens: options.maxTokens,
6995
- systemPrompt: options.systemPrompt,
6996
- conversationMessages: [],
6997
- currentPrompt: windowed,
6998
- toolReplayMode: this.resolveToolReplayModeForBudget(options),
6999
- toolDefinitions: options.tools
7000
- ? Object.values(options.tools)
7001
- : undefined,
7002
- });
7003
- if (recheck.withinBudget) {
7004
- break;
7005
- }
7006
- charBudget = Math.floor(charBudget * 0.8);
7007
- if (attempt === 3) {
7008
- windowed = promptText; // give up — fall through to the throw
7009
- }
7010
- }
7011
- if (windowed !== promptText) {
7012
- logger.warn("[NeuroLink] Prompt exceeded the model's context budget with nothing to compact — " +
7013
- "windowed the prompt (head+tail kept, middle elided) to fit.", {
7014
- provider: providerName,
7015
- model: options.model,
7016
- estimatedTokens: budgetCheck.estimatedInputTokens,
7017
- budget: budgetCheck.availableInputTokens,
7018
- originalPromptChars: promptText.length,
7019
- windowedPromptChars: windowed.length,
7020
- });
7021
- try {
7022
- this.emitter.emit("compaction.applied", {
7023
- stagesAttempted: ["pre-dispatch prompt window"],
7024
- finalTokens: budgetCheck.availableInputTokens,
7025
- budget: budgetCheck.availableInputTokens,
7026
- provider: providerName,
7027
- model: options.model,
7028
- phase: "pre-dispatch-prompt-window",
7029
- timestamp: Date.now(),
7030
- });
7031
- }
7032
- catch {
7033
- /* listener errors are non-fatal */
7034
- }
7035
- options.prompt = windowed;
7036
- const inputHolder = options
7037
- .input;
7038
- if (inputHolder && typeof inputHolder.text === "string") {
7039
- inputHolder.text = windowed;
7040
- }
7041
- promptWindowRecovered = true;
7042
- }
7043
- }
7044
- if (!promptWindowRecovered) {
7045
- try {
7046
- this.emitter.emit("compaction.insufficient", {
7047
- stagesAttempted: ["pre-dispatch hard cap"],
7048
- finalTokens: budgetCheck.estimatedInputTokens,
7049
- budget: budgetCheck.availableInputTokens,
7050
- provider: providerName,
7051
- model: options.model,
7052
- phase: "pre-dispatch-no-recovery",
7053
- timestamp: Date.now(),
7054
- });
7055
- }
7056
- catch {
7057
- /* listener errors are non-fatal */
7058
- }
7059
- throw new ContextBudgetExceededError(`Context exceeds model budget and no compaction is possible ` +
7060
- `(no conversationMemory, no inline conversationMessages — only ` +
7061
- `prompt + tools). Estimated: ${budgetCheck.estimatedInputTokens} ` +
7062
- `tokens, budget: ${budgetCheck.availableInputTokens} tokens. ` +
7063
- `Reduce prompt or tool-definition size, or trim the request.`, {
7064
- estimatedTokens: budgetCheck.estimatedInputTokens,
7065
- availableTokens: budgetCheck.availableInputTokens,
7066
- stagesUsed: [],
7067
- breakdown: budgetCheck.breakdown,
7068
- });
7069
- }
6836
+ this.windowOrRefuseOversizedPrompt(options, providerName, budgetCheck);
7070
6837
  }
7071
6838
  if (budgetCheck.shouldCompact &&
7072
6839
  (this.conversationMemory || dpgHasInlineMessages) &&
7073
6840
  dpgMessageCount >
7074
6841
  (this.lastCompactionMessageCount.get(dpgCompactionSessionId) ?? 0)) {
7075
- const compactor = new ContextCompactor({
7076
- provider: providerName,
7077
- summarizationProvider: this.conversationMemoryConfig?.conversationMemory
7078
- ?.summarizationProvider,
7079
- summarizationModel: this.conversationMemoryConfig?.conversationMemory
7080
- ?.summarizationModel,
7081
- }, this.contextCompactorDeps(this.decisionSiteContext(options, dpgCompactionSessionId)));
7082
- const compactionResult = await compactor.compact(conversationMessages, resolveHistoryBudget(budgetCheck, options.compactionThreshold), this.conversationMemoryConfig?.conversationMemory, options.context?.requestId, { currentRequest: options.prompt });
7083
- if (compactionResult.compacted) {
7084
- const repairedResult = repairToolPairs(compactionResult.messages);
7085
- conversationMessages = repairedResult.messages;
7086
- this.lastCompactionMessageCount.set(dpgCompactionSessionId, conversationMessages.length);
7087
- }
7088
- // POST-COMPACTION BUDGET RE-CHECK (BUG-003 fix)
7089
- const postCompactBudget = checkContextBudget({
7090
- provider: providerName,
7091
- model: options.model,
7092
- maxTokens: options.maxTokens,
7093
- systemPrompt: options.systemPrompt,
7094
- conversationMessages: conversationMessages,
7095
- currentPrompt: options.prompt,
7096
- toolReplayMode: this.resolveToolReplayModeForBudget(options),
7097
- toolDefinitions: options.tools
7098
- ? Object.values(options.tools)
7099
- : undefined,
7100
- });
7101
- if (!postCompactBudget.withinBudget) {
7102
- logger.warn("[NeuroLink] directProviderGeneration: post-compaction still over budget, emergency truncation", {
7103
- estimatedTokens: postCompactBudget.estimatedInputTokens,
7104
- availableTokens: postCompactBudget.availableInputTokens,
7105
- overagePercent: Math.round((postCompactBudget.usageRatio - 1.0) * 100),
7106
- });
7107
- // Curator P1-2: emit `compaction.insufficient` whenever a
7108
- // single round of compaction wasn't enough — even when
7109
- // emergency truncation will save the day. Lets cost / audit
7110
- // listeners track the "compaction was insufficient" signal
7111
- // separately from the eventual outcome.
7112
- try {
7113
- this.emitter.emit("compaction.insufficient", {
7114
- stagesAttempted: compactionResult.stagesUsed,
7115
- finalTokens: postCompactBudget.estimatedInputTokens,
7116
- budget: postCompactBudget.availableInputTokens,
7117
- provider: providerName,
7118
- model: options.model,
7119
- phase: "mid-compaction",
7120
- willEmergencyTruncate: true,
7121
- timestamp: Date.now(),
7122
- });
7123
- }
7124
- catch {
7125
- /* listener errors are non-fatal */
7126
- }
7127
- conversationMessages = emergencyContentTruncation(conversationMessages, postCompactBudget.availableInputTokens, postCompactBudget.breakdown, providerName);
7128
- const finalBudget = checkContextBudget({
7129
- provider: providerName,
7130
- model: options.model,
7131
- maxTokens: options.maxTokens,
7132
- systemPrompt: options.systemPrompt,
7133
- conversationMessages: conversationMessages,
7134
- currentPrompt: options.prompt,
7135
- toolReplayMode: this.resolveToolReplayModeForBudget(options),
7136
- toolDefinitions: options.tools
7137
- ? Object.values(options.tools)
7138
- : undefined,
7139
- });
7140
- if (!finalBudget.withinBudget) {
7141
- // Clear watermark so handleContextOverflow recovery can re-compact
7142
- this.lastCompactionMessageCount.delete(dpgCompactionSessionId);
7143
- // Curator P1-2: emit `compaction.insufficient` so cost / audit
7144
- // listeners can record the specific failure mode (separate
7145
- // from a generic provider error).
7146
- try {
7147
- this.emitter.emit("compaction.insufficient", {
7148
- stagesAttempted: compactionResult.stagesUsed,
7149
- finalTokens: finalBudget.estimatedInputTokens,
7150
- budget: finalBudget.availableInputTokens,
7151
- provider: providerName,
7152
- model: options.model,
7153
- phase: "post-emergency-truncation",
7154
- timestamp: Date.now(),
7155
- });
7156
- }
7157
- catch {
7158
- /* listener errors are non-fatal */
7159
- }
7160
- throw new ContextBudgetExceededError(`Context exceeds model budget after all compaction stages. ` +
7161
- `Estimated: ${finalBudget.estimatedInputTokens} tokens, ` +
7162
- `Budget: ${finalBudget.availableInputTokens} tokens.`, {
7163
- estimatedTokens: finalBudget.estimatedInputTokens,
7164
- availableTokens: finalBudget.availableInputTokens,
7165
- stagesUsed: compactionResult.stagesUsed,
7166
- breakdown: finalBudget.breakdown,
7167
- });
7168
- }
7169
- }
6842
+ conversationMessages = await this.compactHistoryForDispatch(options, providerName, budgetCheck, conversationMessages, dpgCompactionSessionId);
7170
6843
  }
7171
6844
  // ADD: Emit connection events for successful provider creation (Bedrock-compatible)
7172
6845
  this.emitter.emit("connected");
@@ -7191,50 +6864,7 @@ Current user's request: ${currentInput}`;
7191
6864
  responseTime,
7192
6865
  contentLength: result.content?.length || 0,
7193
6866
  });
7194
- return {
7195
- content: result.content || "",
7196
- provider: providerName,
7197
- model: result.model,
7198
- usage: result.usage,
7199
- responseTime,
7200
- finishReason: result.finishReason,
7201
- stopReason: result.stopReason,
7202
- rawFinishReason: result.rawFinishReason,
7203
- stepsUsed: result.stepsUsed,
7204
- toolsUsed: result.toolsUsed || [],
7205
- // The providers record executed calls; without this line the public
7206
- // result never carried them, whatever the provider returned.
7207
- toolCalls: result.toolCalls ?? [],
7208
- // Lossless pass-through: keep the full ToolExecutionRecord fields
7209
- // alongside the legacy {toolName,executionTime,success} shape this
7210
- // internal result declares, so the final GenerateResult mapping
7211
- // reconstructs real records instead of empty ones.
7212
- toolExecutions: result.toolExecutions?.map((te) => ({
7213
- ...te,
7214
- executionTime: te.durationMs,
7215
- success: !te.isError,
7216
- })),
7217
- // A tool RAN (toolsUsed), not merely dispatched.
7218
- enhancedWithTools: !!result.toolsUsed?.length,
7219
- analytics: result.analytics,
7220
- evaluation: result.evaluation,
7221
- audio: result.audio,
7222
- ttsMetadata: result.ttsMetadata,
7223
- video: result.video,
7224
- avatar: result.avatar,
7225
- music: result.music,
7226
- ppt: result.ppt,
7227
- // CRITICAL FIX: Include imageOutput for image generation models
7228
- imageOutput: result.imageOutput,
7229
- // Forward reasoning so callers asking for `result.reasoning`
7230
- // (DeepSeek `reasoning_content`, Anthropic thinking, Gemini
7231
- // thought parts, OpenAI o1) actually receive it.
7232
- reasoning: result.reasoning,
7233
- reasoningTokens: result.reasoningTokens,
7234
- // Propagate native-emission flag — see attemptMCPGeneration comment.
7235
- _generationEndEmitted: result
7236
- ._generationEndEmitted,
7237
- };
6867
+ return this.toDirectGenerationResult(result, providerName, responseTime);
7238
6868
  }
7239
6869
  catch (error) {
7240
6870
  // Immediately propagate AbortError — never fall back to next provider on abort
@@ -7260,6 +6890,374 @@ Current user's request: ${currentInput}`;
7260
6890
  }
7261
6891
  }
7262
6892
  // All providers failed
6893
+ throw this.buildAllProvidersFailedError(providersToTry, lastError, startTime, functionTag);
6894
+ }
6895
+ /**
6896
+ * Generate through the configured ModelPool, walking its members until one
6897
+ * answers. Always returns or throws; never falls through to the static
6898
+ * provider list.
6899
+ */
6900
+ async generateViaModelPool(pool, options, startTime, functionTag) {
6901
+ const maxPoolAttempts = pool.maxAttempts;
6902
+ const triedKeys = new Set();
6903
+ let poolLastError = null;
6904
+ for (let attempt = 0; attempt < maxPoolAttempts; attempt++) {
6905
+ if (options.abortSignal?.aborted) {
6906
+ throw new DOMException("The operation was aborted", "AbortError");
6907
+ }
6908
+ const member = pool.selectNext(triedKeys);
6909
+ if (!member) {
6910
+ // All available members exhausted.
6911
+ break;
6912
+ }
6913
+ triedKeys.add(pool.memberKey(member));
6914
+ // Temporarily override provider/model/region from the pool member.
6915
+ const savedProvider = options.provider;
6916
+ const savedModel = options.model;
6917
+ const savedRegion = options.region;
6918
+ options.provider = member.provider;
6919
+ // When the member omits model/region, clear inherited values so the
6920
+ // provider's own default is used rather than a mismatched caller value.
6921
+ options.model = member.model ?? undefined;
6922
+ options.region = member.region ?? undefined;
6923
+ const poolProviderName = member.provider;
6924
+ logger.debug(`[${functionTag}] ModelPool: attempting member`, {
6925
+ provider: poolProviderName,
6926
+ model: member.model ?? options.model,
6927
+ attempt,
6928
+ });
6929
+ try {
6930
+ // Get conversation messages for context (use pre-compacted if provided)
6931
+ const poolOptionsWithMessages = options;
6932
+ const poolConversationMessages = poolOptionsWithMessages
6933
+ .conversationMessages?.length
6934
+ ? poolOptionsWithMessages.conversationMessages
6935
+ : await getConversationMessages(this.conversationMemory, options);
6936
+ const poolProvider = await AIProviderFactory.createProvider(poolProviderName, options.model, !options.disableTools, this, options.region, this.resolveCredentials(options.credentials));
6937
+ poolProvider.setTraceContext(this._metricsTraceContext);
6938
+ poolProvider.setupToolExecutor({
6939
+ customTools: this.getCustomTools(),
6940
+ executeTool: (toolName, params) => this.executeTool(toolName, params, {
6941
+ disableToolCache: options.disableToolCache,
6942
+ }),
6943
+ }, functionTag);
6944
+ poolProvider.setFileToolRootPolicy?.(this.fileToolRootsFor(options));
6945
+ const poolResult = await poolProvider.generate({
6946
+ ...options,
6947
+ conversationMessages: poolConversationMessages,
6948
+ });
6949
+ if (!poolResult) {
6950
+ throw new Error(`ModelPool: provider ${poolProviderName} returned null result`);
6951
+ }
6952
+ pool.recordSuccess(member);
6953
+ const responseTime = Date.now() - startTime;
6954
+ // Restore original options fields so callers see a clean object.
6955
+ options.provider = savedProvider;
6956
+ options.model = savedModel;
6957
+ options.region = savedRegion;
6958
+ return this.toDirectGenerationResult(poolResult, poolProviderName, responseTime);
6959
+ }
6960
+ catch (poolError) {
6961
+ // Restore options unconditionally on failure.
6962
+ options.provider = savedProvider;
6963
+ options.model = savedModel;
6964
+ options.region = savedRegion;
6965
+ if (isAbortError(poolError)) {
6966
+ throw poolError;
6967
+ }
6968
+ if (isNonRetryableForPool(poolError)) {
6969
+ const poolErrMsg = poolError instanceof Error ? poolError.message : String(poolError);
6970
+ logger.warn(`[${functionTag}] ModelPool: non-retryable error from ${poolProviderName}, stopping pool`, { error: poolErrMsg });
6971
+ pool.recordFailure(member, classifyProviderError(poolError));
6972
+ // Wrap in a plain Error so runWithFallbackOrchestration does not
6973
+ // mistake this for a ModelAccessDeniedError and start a second
6974
+ // retry layer on top of the already-exhausted pool.
6975
+ throw new Error(`[ModelPool] non-retryable: ${poolErrMsg}`, {
6976
+ cause: poolError,
6977
+ });
6978
+ }
6979
+ pool.recordFailure(member, classifyProviderError(poolError));
6980
+ poolLastError =
6981
+ poolError instanceof Error ? poolError : new Error(String(poolError));
6982
+ logger.warn(`[${functionTag}] ModelPool: member ${poolProviderName} failed`, { error: poolLastError.message });
6983
+ }
6984
+ }
6985
+ // All pool members failed or were exhausted.
6986
+ const poolResponseTime = Date.now() - startTime;
6987
+ logger.error(`[${functionTag}] ModelPool: all members failed`, {
6988
+ triedKeys: Array.from(triedKeys),
6989
+ lastError: poolLastError?.message,
6990
+ responseTime: poolResponseTime,
6991
+ });
6992
+ // Wrap in a plain Error (not a typed error class) so that
6993
+ // runWithFallbackOrchestration does not re-activate the modelChain /
6994
+ // providerFallback layer on top of an already-exhausted pool.
6995
+ throw new Error(`[ModelPool] all members failed: ${poolLastError?.message ?? "no members available"}`);
6996
+ }
6997
+ /**
6998
+ * Map a provider's answer to the internal generation result.
6999
+ */
7000
+ toDirectGenerationResult(result, providerName, responseTime) {
7001
+ return {
7002
+ content: result.content || "",
7003
+ provider: providerName,
7004
+ model: result.model,
7005
+ usage: result.usage,
7006
+ responseTime,
7007
+ finishReason: result.finishReason,
7008
+ stopReason: result.stopReason,
7009
+ rawFinishReason: result.rawFinishReason,
7010
+ stepsUsed: result.stepsUsed,
7011
+ toolsUsed: result.toolsUsed || [],
7012
+ // The providers record executed calls; without this line the public
7013
+ // result never carried them, whatever the provider returned.
7014
+ toolCalls: result.toolCalls ?? [],
7015
+ // Lossless pass-through: keep the full ToolExecutionRecord fields
7016
+ // alongside the legacy {toolName,executionTime,success} shape this
7017
+ // internal result declares, so the final GenerateResult mapping
7018
+ // reconstructs real records instead of empty ones.
7019
+ toolExecutions: result.toolExecutions?.map((te) => ({
7020
+ ...te,
7021
+ executionTime: te.durationMs,
7022
+ success: !te.isError,
7023
+ })),
7024
+ // A tool RAN (toolsUsed), not merely dispatched.
7025
+ enhancedWithTools: !!result.toolsUsed?.length,
7026
+ analytics: result.analytics,
7027
+ evaluation: result.evaluation,
7028
+ audio: result.audio,
7029
+ ttsMetadata: result.ttsMetadata,
7030
+ video: result.video,
7031
+ avatar: result.avatar,
7032
+ music: result.music,
7033
+ ppt: result.ppt,
7034
+ // CRITICAL FIX: Include imageOutput for image generation models
7035
+ imageOutput: result.imageOutput,
7036
+ // Forward reasoning so callers asking for `result.reasoning`
7037
+ // (DeepSeek `reasoning_content`, Anthropic thinking, Gemini
7038
+ // thought parts, OpenAI o1) actually receive it.
7039
+ reasoning: result.reasoning,
7040
+ reasoningTokens: result.reasoningTokens,
7041
+ // Propagate native-emission flag — see attemptMCPGeneration comment.
7042
+ _generationEndEmitted: result
7043
+ ._generationEndEmitted,
7044
+ };
7045
+ }
7046
+ /**
7047
+ * Pre-dispatch hard cap for a request over budget with nothing to compact:
7048
+ * window the prompt to fit when the prompt is what blew the budget, else
7049
+ * throw ContextBudgetExceededError.
7050
+ */
7051
+ windowOrRefuseOversizedPrompt(options, providerName, budgetCheck) {
7052
+ let promptWindowRecovered = false;
7053
+ const fixedOverhead = (budgetCheck.breakdown?.systemPrompt ?? 0) +
7054
+ (budgetCheck.breakdown?.toolDefinitions ?? 0) +
7055
+ (budgetCheck.breakdown?.fileAttachments ?? 0);
7056
+ // 3% margin against estimator drift; 1024-token floor — below
7057
+ // that, a windowed prompt carries too little to answer from.
7058
+ const promptBudget = Math.floor((budgetCheck.availableInputTokens - fixedOverhead) * 0.97);
7059
+ const promptText = typeof options.prompt === "string" ? options.prompt : undefined;
7060
+ if (promptText &&
7061
+ promptBudget >= 1024 &&
7062
+ (budgetCheck.breakdown?.currentPrompt ?? 0) > promptBudget) {
7063
+ const marker = "\n\n[... middle of this prompt elided by NeuroLink to fit the model's context window ...]\n\n";
7064
+ // Proportional char budget from the observed chars-per-token of
7065
+ // THIS text, re-checked and shrunk until the estimator agrees.
7066
+ let charBudget = Math.floor(promptText.length *
7067
+ (promptBudget /
7068
+ Math.max(budgetCheck.breakdown?.currentPrompt ?? 1, 1)));
7069
+ let windowed = promptText;
7070
+ for (let attempt = 0; attempt < 4; attempt++) {
7071
+ const headChars = Math.floor(charBudget * 0.6);
7072
+ const tailChars = Math.max(charBudget - headChars - marker.length, 0);
7073
+ windowed =
7074
+ promptText.slice(0, headChars) +
7075
+ marker +
7076
+ (tailChars > 0 ? promptText.slice(-tailChars) : "");
7077
+ const recheck = checkContextBudget({
7078
+ provider: providerName,
7079
+ model: options.model,
7080
+ maxTokens: options.maxTokens,
7081
+ systemPrompt: options.systemPrompt,
7082
+ conversationMessages: [],
7083
+ currentPrompt: windowed,
7084
+ toolReplayMode: this.resolveToolReplayModeForBudget(options),
7085
+ toolDefinitions: options.tools
7086
+ ? Object.values(options.tools)
7087
+ : undefined,
7088
+ });
7089
+ if (recheck.withinBudget) {
7090
+ break;
7091
+ }
7092
+ charBudget = Math.floor(charBudget * 0.8);
7093
+ if (attempt === 3) {
7094
+ windowed = promptText; // give up — fall through to the throw
7095
+ }
7096
+ }
7097
+ if (windowed !== promptText) {
7098
+ logger.warn("[NeuroLink] Prompt exceeded the model's context budget with nothing to compact — " +
7099
+ "windowed the prompt (head+tail kept, middle elided) to fit.", {
7100
+ provider: providerName,
7101
+ model: options.model,
7102
+ estimatedTokens: budgetCheck.estimatedInputTokens,
7103
+ budget: budgetCheck.availableInputTokens,
7104
+ originalPromptChars: promptText.length,
7105
+ windowedPromptChars: windowed.length,
7106
+ });
7107
+ try {
7108
+ this.emitter.emit("compaction.applied", {
7109
+ stagesAttempted: ["pre-dispatch prompt window"],
7110
+ finalTokens: budgetCheck.availableInputTokens,
7111
+ budget: budgetCheck.availableInputTokens,
7112
+ provider: providerName,
7113
+ model: options.model,
7114
+ phase: "pre-dispatch-prompt-window",
7115
+ timestamp: Date.now(),
7116
+ });
7117
+ }
7118
+ catch {
7119
+ /* listener errors are non-fatal */
7120
+ }
7121
+ options.prompt = windowed;
7122
+ const inputHolder = options.input;
7123
+ if (inputHolder && typeof inputHolder.text === "string") {
7124
+ inputHolder.text = windowed;
7125
+ }
7126
+ promptWindowRecovered = true;
7127
+ }
7128
+ }
7129
+ if (!promptWindowRecovered) {
7130
+ try {
7131
+ this.emitter.emit("compaction.insufficient", {
7132
+ stagesAttempted: ["pre-dispatch hard cap"],
7133
+ finalTokens: budgetCheck.estimatedInputTokens,
7134
+ budget: budgetCheck.availableInputTokens,
7135
+ provider: providerName,
7136
+ model: options.model,
7137
+ phase: "pre-dispatch-no-recovery",
7138
+ timestamp: Date.now(),
7139
+ });
7140
+ }
7141
+ catch {
7142
+ /* listener errors are non-fatal */
7143
+ }
7144
+ throw new ContextBudgetExceededError(`Context exceeds model budget and no compaction is possible ` +
7145
+ `(no conversationMemory, no inline conversationMessages — only ` +
7146
+ `prompt + tools). Estimated: ${budgetCheck.estimatedInputTokens} ` +
7147
+ `tokens, budget: ${budgetCheck.availableInputTokens} tokens. ` +
7148
+ `Reduce prompt or tool-definition size, or trim the request.`, {
7149
+ estimatedTokens: budgetCheck.estimatedInputTokens,
7150
+ availableTokens: budgetCheck.availableInputTokens,
7151
+ stagesUsed: [],
7152
+ breakdown: budgetCheck.breakdown,
7153
+ });
7154
+ }
7155
+ }
7156
+ /**
7157
+ * Compact the conversation history before dispatch, re-checking the budget
7158
+ * and truncating as a last resort. Returns the history to send.
7159
+ */
7160
+ async compactHistoryForDispatch(options, providerName, budgetCheck, history, compactionSessionId) {
7161
+ let conversationMessages = history;
7162
+ const dpgCompactionSessionId = compactionSessionId;
7163
+ const compactor = new ContextCompactor({
7164
+ provider: providerName,
7165
+ summarizationProvider: this.conversationMemoryConfig?.conversationMemory
7166
+ ?.summarizationProvider,
7167
+ summarizationModel: this.conversationMemoryConfig?.conversationMemory?.summarizationModel,
7168
+ }, this.contextCompactorDeps(this.decisionSiteContext(options, dpgCompactionSessionId)));
7169
+ const compactionResult = await compactor.compact(conversationMessages, resolveHistoryBudget(budgetCheck, options.compactionThreshold), this.conversationMemoryConfig?.conversationMemory, options.context?.requestId, { currentRequest: options.prompt });
7170
+ if (compactionResult.compacted) {
7171
+ const repairedResult = repairToolPairs(compactionResult.messages);
7172
+ conversationMessages = repairedResult.messages;
7173
+ this.lastCompactionMessageCount.set(dpgCompactionSessionId, conversationMessages.length);
7174
+ }
7175
+ // POST-COMPACTION BUDGET RE-CHECK (BUG-003 fix)
7176
+ const postCompactBudget = checkContextBudget({
7177
+ provider: providerName,
7178
+ model: options.model,
7179
+ maxTokens: options.maxTokens,
7180
+ systemPrompt: options.systemPrompt,
7181
+ conversationMessages: conversationMessages,
7182
+ currentPrompt: options.prompt,
7183
+ toolReplayMode: this.resolveToolReplayModeForBudget(options),
7184
+ toolDefinitions: options.tools ? Object.values(options.tools) : undefined,
7185
+ });
7186
+ if (!postCompactBudget.withinBudget) {
7187
+ logger.warn("[NeuroLink] directProviderGeneration: post-compaction still over budget, emergency truncation", {
7188
+ estimatedTokens: postCompactBudget.estimatedInputTokens,
7189
+ availableTokens: postCompactBudget.availableInputTokens,
7190
+ overagePercent: Math.round((postCompactBudget.usageRatio - 1.0) * 100),
7191
+ });
7192
+ // Curator P1-2: emit `compaction.insufficient` whenever a
7193
+ // single round of compaction wasn't enough — even when
7194
+ // emergency truncation will save the day. Lets cost / audit
7195
+ // listeners track the "compaction was insufficient" signal
7196
+ // separately from the eventual outcome.
7197
+ try {
7198
+ this.emitter.emit("compaction.insufficient", {
7199
+ stagesAttempted: compactionResult.stagesUsed,
7200
+ finalTokens: postCompactBudget.estimatedInputTokens,
7201
+ budget: postCompactBudget.availableInputTokens,
7202
+ provider: providerName,
7203
+ model: options.model,
7204
+ phase: "mid-compaction",
7205
+ willEmergencyTruncate: true,
7206
+ timestamp: Date.now(),
7207
+ });
7208
+ }
7209
+ catch {
7210
+ /* listener errors are non-fatal */
7211
+ }
7212
+ conversationMessages = emergencyContentTruncation(conversationMessages, postCompactBudget.availableInputTokens, postCompactBudget.breakdown, providerName);
7213
+ const finalBudget = checkContextBudget({
7214
+ provider: providerName,
7215
+ model: options.model,
7216
+ maxTokens: options.maxTokens,
7217
+ systemPrompt: options.systemPrompt,
7218
+ conversationMessages: conversationMessages,
7219
+ currentPrompt: options.prompt,
7220
+ toolReplayMode: this.resolveToolReplayModeForBudget(options),
7221
+ toolDefinitions: options.tools
7222
+ ? Object.values(options.tools)
7223
+ : undefined,
7224
+ });
7225
+ if (!finalBudget.withinBudget) {
7226
+ // Clear watermark so handleContextOverflow recovery can re-compact
7227
+ this.lastCompactionMessageCount.delete(dpgCompactionSessionId);
7228
+ // Curator P1-2: emit `compaction.insufficient` so cost / audit
7229
+ // listeners can record the specific failure mode (separate
7230
+ // from a generic provider error).
7231
+ try {
7232
+ this.emitter.emit("compaction.insufficient", {
7233
+ stagesAttempted: compactionResult.stagesUsed,
7234
+ finalTokens: finalBudget.estimatedInputTokens,
7235
+ budget: finalBudget.availableInputTokens,
7236
+ provider: providerName,
7237
+ model: options.model,
7238
+ phase: "post-emergency-truncation",
7239
+ timestamp: Date.now(),
7240
+ });
7241
+ }
7242
+ catch {
7243
+ /* listener errors are non-fatal */
7244
+ }
7245
+ throw new ContextBudgetExceededError(`Context exceeds model budget after all compaction stages. ` +
7246
+ `Estimated: ${finalBudget.estimatedInputTokens} tokens, ` +
7247
+ `Budget: ${finalBudget.availableInputTokens} tokens.`, {
7248
+ estimatedTokens: finalBudget.estimatedInputTokens,
7249
+ availableTokens: finalBudget.availableInputTokens,
7250
+ stagesUsed: compactionResult.stagesUsed,
7251
+ breakdown: finalBudget.breakdown,
7252
+ });
7253
+ }
7254
+ }
7255
+ return conversationMessages;
7256
+ }
7257
+ /**
7258
+ * The error thrown once every candidate provider has failed.
7259
+ */
7260
+ buildAllProvidersFailedError(providersToTry, lastError, startTime, functionTag) {
7263
7261
  const responseTime = Date.now() - startTime;
7264
7262
  logger.error(`[${functionTag}] All providers failed`, {
7265
7263
  triedProviders: providersToTry,
@@ -7272,7 +7270,7 @@ Current user's request: ${currentInput}`;
7272
7270
  // rejected on budget the caller still needs the typed error to
7273
7271
  // distinguish "context too large" from a generic provider failure.
7274
7272
  if (lastError instanceof ContextBudgetExceededError) {
7275
- throw lastError;
7273
+ return lastError;
7276
7274
  }
7277
7275
  // A single-candidate list (an explicit provider, or
7278
7276
  // disableInternalFallback) never actually tried "all providers" —
@@ -7297,9 +7295,9 @@ Current user's request: ${currentInput}`;
7297
7295
  return wrapped;
7298
7296
  };
7299
7297
  if (providersToTry.length === 1) {
7300
- throw wrapProviderError(`Provider ${providersToTry[0]} failed: ${lastError?.message || "Unknown error"}`);
7298
+ return wrapProviderError(`Provider ${providersToTry[0]} failed: ${lastError?.message || "Unknown error"}`);
7301
7299
  }
7302
- throw wrapProviderError(`Failed to generate text with all providers. Last error: ${lastError?.message || "Unknown error"}`);
7300
+ return wrapProviderError(`Failed to generate text with all providers. Last error: ${lastError?.message || "Unknown error"}`);
7303
7301
  }
7304
7302
  /**
7305
7303
  * Create tool-aware system prompt that informs AI about available tools
@@ -8004,43 +8002,7 @@ Current user's request: ${currentInput}`;
8004
8002
  // Constructed BEFORE the cache-hit check so it is available for all
8005
8003
  // outcome paths, including cache-hit turns (Finding 4).
8006
8004
  const routingStartTime = Date.now();
8007
- const emitDecision = (decision) => {
8008
- try {
8009
- const activeSpan = trace.getActiveSpan();
8010
- if (!activeSpan) {
8011
- return;
8012
- }
8013
- activeSpan.setAttribute("tool_routing.outcome", decision.outcome);
8014
- activeSpan.setAttribute("tool_routing.routable_server_count", decision.routableServerCount);
8015
- activeSpan.setAttribute("tool_routing.selected_server_ids", spanJsonAttribute(decision.selectedServerIds));
8016
- activeSpan.setAttribute("tool_routing.excluded_server_ids", spanJsonAttribute(decision.excludedServerIds));
8017
- activeSpan.setAttribute("tool_routing.hallucinated_ids", spanJsonAttribute(decision.hallucinatedIds));
8018
- activeSpan.setAttribute("tool_routing.excluded_tool_count", decision.excludedToolCount);
8019
- activeSpan.setAttribute("tool_routing.cache_hit", decision.cacheHit);
8020
- activeSpan.setAttribute("tool_routing.duration_ms", decision.durationMs);
8021
- // Optional L2 / tool-granularity fields (present only when embedding ran).
8022
- if (decision.embeddingActivated !== undefined) {
8023
- activeSpan.setAttribute("tool_routing.embedding_activated", decision.embeddingActivated);
8024
- }
8025
- if (decision.candidateToolCount !== undefined) {
8026
- activeSpan.setAttribute("tool_routing.candidate_tool_count", decision.candidateToolCount);
8027
- }
8028
- if (decision.granularity !== undefined) {
8029
- activeSpan.setAttribute("tool_routing.granularity", decision.granularity);
8030
- }
8031
- // Which router actually decided. Three strategies can produce an
8032
- // "applied" outcome and they have wildly different cost and
8033
- // latency profiles, so an outcome without a strategy cannot be
8034
- // acted on — and a decision router that silently stopped firing
8035
- // looks identical to one that was never configured.
8036
- if (decision.strategy !== undefined) {
8037
- activeSpan.setAttribute("tool_routing.strategy", decision.strategy);
8038
- }
8039
- }
8040
- catch {
8041
- // Telemetry must never affect routing behaviour.
8042
- }
8043
- };
8005
+ const emitDecision = (decision) => this.recordToolRoutingSpan(decision);
8044
8006
  // Check the cache first.
8045
8007
  if (cacheEnabled && cache && cacheKey !== undefined) {
8046
8008
  const cached = cache.get(cacheKey);
@@ -8104,46 +8066,12 @@ Current user's request: ${currentInput}`;
8104
8066
  // tool embedding vectors are computed once and reused across turns
8105
8067
  // (Finding 1 fix). It is cleared by setToolRoutingServers() when the
8106
8068
  // catalog changes so stale vectors are never used after an update.
8107
- let routingEmbedFn;
8108
8069
  // A host-owned routing callback owns every inference account. The
8109
8070
  // instance's embedding fast-path would otherwise borrow turn credentials.
8110
8071
  const embeddingCfg = routingConfig.generateFn
8111
8072
  ? undefined
8112
8073
  : routingConfig.embedding;
8113
- if (embeddingCfg?.enabled === true) {
8114
- try {
8115
- // Resolve the embedding provider: use the explicitly configured one
8116
- // if present, otherwise fall back to the stream/generate call's
8117
- // provider. The factory call is wrapped in try/catch so a provider
8118
- // that doesn't support embedMany (it throws at call time, not
8119
- // construction time) fails open when routingEmbedFn is invoked.
8120
- const embProviderName = embeddingCfg.provider ??
8121
- (options.provider && options.provider !== "auto"
8122
- ? options.provider
8123
- : undefined) ??
8124
- routingConfig.routerModel?.provider;
8125
- if (embProviderName) {
8126
- const embProvider = await AIProviderFactory.createProvider(embProviderName, embeddingCfg.model, true, this, undefined, this.resolveCredentials(options.credentials));
8127
- // Bind embedMany with the configured model (may be undefined —
8128
- // the provider uses its default embedding model in that case).
8129
- routingEmbedFn = (texts) => withTimeout(embProvider.embedMany(texts, embeddingCfg.model), embeddingCfg.timeoutMs ?? 10000);
8130
- // Lazy-init the persistent vector cache for this instance.
8131
- // Subsequent turns reuse the same Map so text→vector lookups
8132
- // already populated from earlier turns are served from memory.
8133
- if (!this.toolRoutingVectorCache) {
8134
- this.toolRoutingVectorCache = new Map();
8135
- }
8136
- }
8137
- }
8138
- catch (embSetupError) {
8139
- logger.debug("[ToolRouting] Embedding provider setup failed, L2 path disabled for this turn", {
8140
- error: embSetupError instanceof Error
8141
- ? embSetupError.message
8142
- : String(embSetupError),
8143
- });
8144
- // routingEmbedFn remains undefined — fast-path is skipped.
8145
- }
8146
- }
8074
+ const routingEmbedFn = await this.buildToolRoutingEmbedFn(options, routingConfig, embeddingCfg);
8147
8075
  routedExcludeTools = await resolveToolRoutingExclusions({
8148
8076
  catalog,
8149
8077
  alwaysIncludeServerIds: routingConfig.alwaysIncludeServerIds ?? [],
@@ -8214,31 +8142,7 @@ Current user's request: ${currentInput}`;
8214
8142
  }
8215
8143
  // --- ITEM C: store result for future turns ---
8216
8144
  if (resolvedDecision?.outcome === "applied" && cache) {
8217
- // Store the PRE-stickiness exclusion list in the cache so future hits
8218
- // re-apply the live stickiness window rather than the one from this
8219
- // turn (Finding 2).
8220
- if (cacheEnabled && cacheKey !== undefined) {
8221
- try {
8222
- cache.set(cacheKey, {
8223
- excludedToolNames: preStickinessExcludeTools,
8224
- selectedServerIds: resolvedDecision.selectedServerIds,
8225
- });
8226
- }
8227
- catch {
8228
- // Cache write failure is non-fatal.
8229
- }
8230
- }
8231
- // Record selected servers for stickiness on subsequent turns. This must
8232
- // come after getStickyServerIds so the window count is not consumed on
8233
- // the same turn it is set (the off-by-one fix above).
8234
- if (stickinessEnabled && sessionId) {
8235
- try {
8236
- cache.recordSelection(sessionId, resolvedDecision.selectedServerIds);
8237
- }
8238
- catch {
8239
- // Stickiness failure is non-fatal.
8240
- }
8241
- }
8145
+ this.storeToolRoutingOutcome(cache, resolvedDecision, cacheEnabled ? cacheKey : undefined, preStickinessExcludeTools, stickinessEnabled ? sessionId : "");
8242
8146
  }
8243
8147
  if (routedExcludeTools.length > 0) {
8244
8148
  options.excludeTools = [
@@ -8256,6 +8160,120 @@ Current user's request: ${currentInput}`;
8256
8160
  });
8257
8161
  }
8258
8162
  }
8163
+ /**
8164
+ * Record a tool routing decision on the active span. Telemetry only.
8165
+ */
8166
+ recordToolRoutingSpan(decision) {
8167
+ try {
8168
+ const activeSpan = trace.getActiveSpan();
8169
+ if (!activeSpan) {
8170
+ return;
8171
+ }
8172
+ activeSpan.setAttribute("tool_routing.outcome", decision.outcome);
8173
+ activeSpan.setAttribute("tool_routing.routable_server_count", decision.routableServerCount);
8174
+ activeSpan.setAttribute("tool_routing.selected_server_ids", spanJsonAttribute(decision.selectedServerIds));
8175
+ activeSpan.setAttribute("tool_routing.excluded_server_ids", spanJsonAttribute(decision.excludedServerIds));
8176
+ activeSpan.setAttribute("tool_routing.hallucinated_ids", spanJsonAttribute(decision.hallucinatedIds));
8177
+ activeSpan.setAttribute("tool_routing.excluded_tool_count", decision.excludedToolCount);
8178
+ activeSpan.setAttribute("tool_routing.cache_hit", decision.cacheHit);
8179
+ activeSpan.setAttribute("tool_routing.duration_ms", decision.durationMs);
8180
+ // Optional L2 / tool-granularity fields (present only when embedding ran).
8181
+ if (decision.embeddingActivated !== undefined) {
8182
+ activeSpan.setAttribute("tool_routing.embedding_activated", decision.embeddingActivated);
8183
+ }
8184
+ if (decision.candidateToolCount !== undefined) {
8185
+ activeSpan.setAttribute("tool_routing.candidate_tool_count", decision.candidateToolCount);
8186
+ }
8187
+ if (decision.granularity !== undefined) {
8188
+ activeSpan.setAttribute("tool_routing.granularity", decision.granularity);
8189
+ }
8190
+ // Which router actually decided. Three strategies can produce an
8191
+ // "applied" outcome and they have wildly different cost and
8192
+ // latency profiles, so an outcome without a strategy cannot be
8193
+ // acted on — and a decision router that silently stopped firing
8194
+ // looks identical to one that was never configured.
8195
+ if (decision.strategy !== undefined) {
8196
+ activeSpan.setAttribute("tool_routing.strategy", decision.strategy);
8197
+ }
8198
+ }
8199
+ catch {
8200
+ // Telemetry must never affect routing behaviour.
8201
+ }
8202
+ }
8203
+ /**
8204
+ * Build the embedding function for the L2 routing fast-path, or undefined
8205
+ * when embedding is off or its provider cannot be set up. Fails open.
8206
+ */
8207
+ async buildToolRoutingEmbedFn(options, routingConfig, embeddingCfg) {
8208
+ let routingEmbedFn;
8209
+ if (embeddingCfg?.enabled === true) {
8210
+ try {
8211
+ // Resolve the embedding provider: use the explicitly configured one
8212
+ // if present, otherwise fall back to the stream/generate call's
8213
+ // provider. The factory call is wrapped in try/catch so a provider
8214
+ // that doesn't support embedMany (it throws at call time, not
8215
+ // construction time) fails open when routingEmbedFn is invoked.
8216
+ const embProviderName = embeddingCfg.provider ??
8217
+ (options.provider && options.provider !== "auto"
8218
+ ? options.provider
8219
+ : undefined) ??
8220
+ routingConfig.routerModel?.provider;
8221
+ if (embProviderName) {
8222
+ const embProvider = await AIProviderFactory.createProvider(embProviderName, embeddingCfg.model, true, this, undefined, this.resolveCredentials(options.credentials));
8223
+ // Bind embedMany with the configured model (may be undefined —
8224
+ // the provider uses its default embedding model in that case).
8225
+ routingEmbedFn = (texts) => withTimeout(embProvider.embedMany(texts, embeddingCfg.model), embeddingCfg.timeoutMs ?? 10000);
8226
+ // Lazy-init the persistent vector cache for this instance.
8227
+ // Subsequent turns reuse the same Map so text→vector lookups
8228
+ // already populated from earlier turns are served from memory.
8229
+ if (!this.toolRoutingVectorCache) {
8230
+ this.toolRoutingVectorCache = new Map();
8231
+ }
8232
+ }
8233
+ }
8234
+ catch (embSetupError) {
8235
+ logger.debug("[ToolRouting] Embedding provider setup failed, L2 path disabled for this turn", {
8236
+ error: embSetupError instanceof Error
8237
+ ? embSetupError.message
8238
+ : String(embSetupError),
8239
+ });
8240
+ // routingEmbedFn remains undefined — fast-path is skipped.
8241
+ }
8242
+ }
8243
+ return routingEmbedFn;
8244
+ }
8245
+ /**
8246
+ * Store an applied routing decision for later turns: the cache entry (under
8247
+ * `cacheKey`, when caching is on) and the sticky servers (for
8248
+ * `stickySessionId`, when stickiness is on).
8249
+ */
8250
+ storeToolRoutingOutcome(cache, decision, cacheKey, preStickinessExcludeTools, stickySessionId) {
8251
+ // Store the PRE-stickiness exclusion list in the cache so future hits
8252
+ // re-apply the live stickiness window rather than the one from this
8253
+ // turn (Finding 2).
8254
+ if (cacheKey !== undefined) {
8255
+ try {
8256
+ cache.set(cacheKey, {
8257
+ excludedToolNames: preStickinessExcludeTools,
8258
+ selectedServerIds: decision.selectedServerIds,
8259
+ });
8260
+ }
8261
+ catch {
8262
+ // Cache write failure is non-fatal.
8263
+ }
8264
+ }
8265
+ // Record selected servers for stickiness on subsequent turns. This must
8266
+ // come after getStickyServerIds so the window count is not consumed on
8267
+ // the same turn it is set (the off-by-one fix above).
8268
+ if (stickySessionId) {
8269
+ try {
8270
+ cache.recordSelection(stickySessionId, decision.selectedServerIds);
8271
+ }
8272
+ catch {
8273
+ // Stickiness failure is non-fatal.
8274
+ }
8275
+ }
8276
+ }
8259
8277
  /**
8260
8278
  * Loads a bounded window of prior conversation turns for the router so a
8261
8279
  * follow-up turn carries the context it needs to classify intent. Reads this
@@ -9712,104 +9730,7 @@ Current user's request: ${currentInput}`;
9712
9730
  (hasCallerConversationHistory || this.conversationMemory) &&
9713
9731
  streamMessageCount >
9714
9732
  (this.lastCompactionMessageCount.get(streamCompactionSessionId) ?? 0)) {
9715
- const compactor = new ContextCompactor({
9716
- provider: providerName,
9717
- summarizationProvider: this.conversationMemoryConfig?.conversationMemory
9718
- ?.summarizationProvider,
9719
- summarizationModel: this.conversationMemoryConfig?.conversationMemory
9720
- ?.summarizationModel,
9721
- }, this.contextCompactorDeps(this.decisionSiteContext(options, streamCompactionSessionId)));
9722
- const compactionResult = await compactor.compact(conversationMessages, resolveHistoryBudget(streamBudget, options.compactionThreshold), this.conversationMemoryConfig?.conversationMemory, options.context?.requestId, { currentRequest: options.input.text });
9723
- if (compactionResult.compacted) {
9724
- const repairedResult = repairToolPairs(compactionResult.messages);
9725
- conversationMessages = repairedResult.messages;
9726
- // Keep options.conversationMessages in sync so downstream consumers
9727
- // (e.g. handleStreamFallback) use the compacted history rather than
9728
- // re-reading from conversationMemory.
9729
- options.conversationMessages = conversationMessages;
9730
- this.lastCompactionMessageCount.set(streamCompactionSessionId, conversationMessages.length);
9731
- }
9732
- // POST-COMPACTION BUDGET RE-CHECK (mirrors tryMCPGeneration / directProviderGeneration)
9733
- const postCompactBudget = checkContextBudget({
9734
- provider: providerName,
9735
- model: options.model,
9736
- maxTokens: options.maxTokens,
9737
- systemPrompt: enhancedSystemPrompt,
9738
- toolReplayMode: this.resolveToolReplayModeForBudget(options),
9739
- conversationMessages: conversationMessages,
9740
- currentPrompt: options.input.text,
9741
- toolDefinitions: availableTools,
9742
- });
9743
- if (!postCompactBudget.withinBudget) {
9744
- logger.warn("[NeuroLink] Stream: post-compaction still over budget, emergency truncation", {
9745
- estimatedTokens: postCompactBudget.estimatedInputTokens,
9746
- availableTokens: postCompactBudget.availableInputTokens,
9747
- overagePercent: Math.round((postCompactBudget.usageRatio - 1.0) * 100),
9748
- });
9749
- // Curator P1-2: emit `compaction.insufficient` whenever a single
9750
- // round of compaction wasn't enough — even when emergency
9751
- // truncation will save the day. Lets cost / audit listeners track
9752
- // the "compaction was insufficient" signal separately from the
9753
- // eventual outcome.
9754
- try {
9755
- this.emitter.emit("compaction.insufficient", {
9756
- stagesAttempted: compactionResult.stagesUsed,
9757
- finalTokens: postCompactBudget.estimatedInputTokens,
9758
- budget: postCompactBudget.availableInputTokens,
9759
- provider: providerName,
9760
- model: options.model,
9761
- phase: "mid-compaction",
9762
- willEmergencyTruncate: true,
9763
- timestamp: Date.now(),
9764
- });
9765
- }
9766
- catch {
9767
- /* listener errors are non-fatal */
9768
- }
9769
- conversationMessages = emergencyContentTruncation(conversationMessages, postCompactBudget.availableInputTokens, postCompactBudget.breakdown, providerName);
9770
- // Keep options in sync after emergency truncation so fallback paths
9771
- // use the truncated history.
9772
- options.conversationMessages = conversationMessages;
9773
- const finalBudget = checkContextBudget({
9774
- provider: providerName,
9775
- model: options.model,
9776
- maxTokens: options.maxTokens,
9777
- systemPrompt: enhancedSystemPrompt,
9778
- toolReplayMode: this.resolveToolReplayModeForBudget(options),
9779
- conversationMessages: conversationMessages,
9780
- currentPrompt: options.input.text,
9781
- toolDefinitions: availableTools,
9782
- });
9783
- if (!finalBudget.withinBudget) {
9784
- // Clear watermark so handleContextOverflow recovery can re-compact
9785
- this.lastCompactionMessageCount.delete(streamCompactionSessionId);
9786
- // Curator P1-2: emit `compaction.insufficient` on the terminal
9787
- // failure path so cost / audit listeners can record the specific
9788
- // failure mode (compaction + emergency truncation both insufficient).
9789
- try {
9790
- this.emitter.emit("compaction.insufficient", {
9791
- stagesAttempted: compactionResult.stagesUsed,
9792
- finalTokens: finalBudget.estimatedInputTokens,
9793
- budget: finalBudget.availableInputTokens,
9794
- provider: providerName,
9795
- model: options.model,
9796
- phase: "post-emergency-truncation",
9797
- timestamp: Date.now(),
9798
- });
9799
- }
9800
- catch {
9801
- /* listener errors are non-fatal */
9802
- }
9803
- throw new ContextBudgetExceededError(`Stream context exceeds model budget after all compaction stages. ` +
9804
- `Estimated: ${finalBudget.estimatedInputTokens} tokens, ` +
9805
- `Budget: ${finalBudget.availableInputTokens} tokens.`, {
9806
- estimatedTokens: finalBudget.estimatedInputTokens,
9807
- availableTokens: finalBudget.availableInputTokens,
9808
- stagesUsed: compactionResult.stagesUsed,
9809
- breakdown: finalBudget.breakdown,
9810
- });
9811
- }
9812
- }
9733
+ conversationMessages = await this.compactStreamHistory(options, providerName, streamBudget, enhancedSystemPrompt, availableTools, conversationMessages);
9813
9734
  }
9814
9735
  // ─── ModelPool stream path ────────────────────────────────────────────────
9815
9736
  // When a pool is configured, replaces the single provider.stream() call
@@ -9821,101 +9742,7 @@ Current user's request: ${currentInput}`;
9821
9742
  // On exhaustion, throws the last member error — does NOT fall through to
9822
9743
  // the static provider path below.
9823
9744
  if (this.modelPool) {
9824
- const streamPool = this.modelPool;
9825
- const maxStreamAttempts = streamPool.maxAttempts;
9826
- const streamTriedKeys = new Set();
9827
- let streamLastError = null;
9828
- for (let attempt = 0; attempt < maxStreamAttempts; attempt++) {
9829
- if (options.abortSignal?.aborted) {
9830
- throw new DOMException("The operation was aborted", "AbortError");
9831
- }
9832
- const streamMember = streamPool.selectNext(streamTriedKeys);
9833
- if (!streamMember) {
9834
- break;
9835
- }
9836
- streamTriedKeys.add(streamPool.memberKey(streamMember));
9837
- // Override provider/model/region from the pool member.
9838
- // When the member omits model/region, use undefined (provider default)
9839
- // rather than inheriting the caller's value for a different provider.
9840
- const poolStreamProviderName = streamMember.provider;
9841
- const poolStreamModel = streamMember.model ?? undefined;
9842
- const poolStreamRegion = streamMember.region ?? undefined;
9843
- logger.debug(`[createMCPStream] ModelPool: attempting member ${poolStreamProviderName}`, { model: poolStreamModel, attempt });
9844
- try {
9845
- const poolStreamProvider = await AIProviderFactory.createProvider(poolStreamProviderName, poolStreamModel, !options.disableTools, this, poolStreamRegion, this.resolveCredentials(options.credentials));
9846
- poolStreamProvider.setTraceContext(this._metricsTraceContext);
9847
- poolStreamProvider.setupToolExecutor({
9848
- customTools: this.getCustomTools(),
9849
- executeTool: (toolName, params) => this.executeTool(toolName, params, {
9850
- disableToolCache: options.disableToolCache,
9851
- }),
9852
- }, "NeuroLink.createMCPStream");
9853
- poolStreamProvider.setFileToolRootPolicy?.(this.fileToolRootsFor(options));
9854
- const poolStreamResult = await poolStreamProvider.stream({
9855
- ...this.deferProviderStreamTTS(options),
9856
- provider: poolStreamProviderName,
9857
- model: poolStreamModel,
9858
- region: poolStreamRegion,
9859
- systemPrompt: enhancedSystemPrompt,
9860
- conversationMessages,
9861
- });
9862
- logger.debug("[createMCPStream] ModelPool stream handle obtained", {
9863
- provider: poolStreamProviderName,
9864
- });
9865
- // Wrap the stream so we can record success/failure based on what
9866
- // actually happens during consumption, not merely on obtaining the
9867
- // handle. Recording success at handle-acquisition time (before any
9868
- // tokens are delivered) would mean a mid-stream provider drop is
9869
- // never reflected as a cooldown.
9870
- const capturedMember = streamMember;
9871
- const wrappedStream = (async function* () {
9872
- try {
9873
- yield* poolStreamResult.stream;
9874
- streamPool.recordSuccess(capturedMember);
9875
- }
9876
- catch (streamConsumeErr) {
9877
- streamPool.recordFailure(capturedMember, classifyProviderError(streamConsumeErr));
9878
- throw streamConsumeErr;
9879
- }
9880
- })();
9881
- return preserveLiveStreamAccessors(poolStreamResult, {
9882
- ...poolStreamResult,
9883
- stream: wrappedStream,
9884
- provider: poolStreamProviderName,
9885
- model: poolStreamResult.model || poolStreamModel,
9886
- toolCalls: poolStreamResult.toolCalls ?? [],
9887
- toolResults: poolStreamResult.toolResults ?? [],
9888
- });
9889
- }
9890
- catch (poolStreamError) {
9891
- if (isAbortError(poolStreamError)) {
9892
- throw poolStreamError;
9893
- }
9894
- if (isNonRetryableForPool(poolStreamError)) {
9895
- const poolStreamErrMsg = poolStreamError instanceof Error
9896
- ? poolStreamError.message
9897
- : String(poolStreamError);
9898
- streamPool.recordFailure(streamMember, classifyProviderError(poolStreamError));
9899
- // Wrap in a plain Error so runWithFallbackOrchestration /
9900
- // streamWithIterationFallback does not re-activate the modelChain
9901
- // layer on top of an already-exhausted pool.
9902
- throw new Error(`[ModelPool] non-retryable: ${poolStreamErrMsg}`, {
9903
- cause: poolStreamError,
9904
- });
9905
- }
9906
- streamPool.recordFailure(streamMember, classifyProviderError(poolStreamError));
9907
- streamLastError =
9908
- poolStreamError instanceof Error
9909
- ? poolStreamError
9910
- : new Error(String(poolStreamError));
9911
- logger.warn(`[createMCPStream] ModelPool: member ${poolStreamProviderName} failed`, { error: streamLastError.message });
9912
- }
9913
- }
9914
- // All pool stream members failed.
9915
- // Wrap in a plain Error (not a typed error class) so that the
9916
- // surrounding fallback orchestrator does not start a second retry layer
9917
- // over the already-exhausted pool.
9918
- throw new Error(`[ModelPool] all stream members failed: ${streamLastError?.message ?? "no stream members available"}`);
9745
+ return this.streamViaModelPool(this.modelPool, options, enhancedSystemPrompt, conversationMessages);
9919
9746
  }
9920
9747
  // ─── End ModelPool stream path ────────────────────────────────────────────
9921
9748
  // 🔧 FIX: Pass enhanced system prompt to real streaming
@@ -9942,6 +9769,214 @@ Current user's request: ${currentInput}`;
9942
9769
  toolResults: streamResult.toolResults ?? [],
9943
9770
  });
9944
9771
  }
9772
+ /**
9773
+ * Compact the history before a stream, re-checking the budget and
9774
+ * truncating as a last resort; keeps `options.conversationMessages` in sync.
9775
+ * Returns the history to send.
9776
+ */
9777
+ async compactStreamHistory(options, providerName, streamBudget, enhancedSystemPrompt, availableTools, history) {
9778
+ let conversationMessages = history;
9779
+ const streamCompactionSessionId = this.getCompactionSessionId(options);
9780
+ const compactor = new ContextCompactor({
9781
+ provider: providerName,
9782
+ summarizationProvider: this.conversationMemoryConfig?.conversationMemory
9783
+ ?.summarizationProvider,
9784
+ summarizationModel: this.conversationMemoryConfig?.conversationMemory?.summarizationModel,
9785
+ }, this.contextCompactorDeps(this.decisionSiteContext(options, streamCompactionSessionId)));
9786
+ const compactionResult = await compactor.compact(conversationMessages, resolveHistoryBudget(streamBudget, options.compactionThreshold), this.conversationMemoryConfig?.conversationMemory, options.context?.requestId, { currentRequest: options.input.text });
9787
+ if (compactionResult.compacted) {
9788
+ const repairedResult = repairToolPairs(compactionResult.messages);
9789
+ conversationMessages = repairedResult.messages;
9790
+ // Keep options.conversationMessages in sync so downstream consumers
9791
+ // (e.g. handleStreamFallback) use the compacted history rather than
9792
+ // re-reading from conversationMemory.
9793
+ options.conversationMessages = conversationMessages;
9794
+ this.lastCompactionMessageCount.set(streamCompactionSessionId, conversationMessages.length);
9795
+ }
9796
+ // POST-COMPACTION BUDGET RE-CHECK (mirrors tryMCPGeneration / directProviderGeneration)
9797
+ const postCompactBudget = checkContextBudget({
9798
+ provider: providerName,
9799
+ model: options.model,
9800
+ maxTokens: options.maxTokens,
9801
+ systemPrompt: enhancedSystemPrompt,
9802
+ toolReplayMode: this.resolveToolReplayModeForBudget(options),
9803
+ conversationMessages: conversationMessages,
9804
+ currentPrompt: options.input.text,
9805
+ toolDefinitions: availableTools,
9806
+ });
9807
+ if (!postCompactBudget.withinBudget) {
9808
+ logger.warn("[NeuroLink] Stream: post-compaction still over budget, emergency truncation", {
9809
+ estimatedTokens: postCompactBudget.estimatedInputTokens,
9810
+ availableTokens: postCompactBudget.availableInputTokens,
9811
+ overagePercent: Math.round((postCompactBudget.usageRatio - 1.0) * 100),
9812
+ });
9813
+ // Curator P1-2: emit `compaction.insufficient` whenever a single
9814
+ // round of compaction wasn't enough — even when emergency
9815
+ // truncation will save the day. Lets cost / audit listeners track
9816
+ // the "compaction was insufficient" signal separately from the
9817
+ // eventual outcome.
9818
+ try {
9819
+ this.emitter.emit("compaction.insufficient", {
9820
+ stagesAttempted: compactionResult.stagesUsed,
9821
+ finalTokens: postCompactBudget.estimatedInputTokens,
9822
+ budget: postCompactBudget.availableInputTokens,
9823
+ provider: providerName,
9824
+ model: options.model,
9825
+ phase: "mid-compaction",
9826
+ willEmergencyTruncate: true,
9827
+ timestamp: Date.now(),
9828
+ });
9829
+ }
9830
+ catch {
9831
+ /* listener errors are non-fatal */
9832
+ }
9833
+ conversationMessages = emergencyContentTruncation(conversationMessages, postCompactBudget.availableInputTokens, postCompactBudget.breakdown, providerName);
9834
+ // Keep options in sync after emergency truncation so fallback paths
9835
+ // use the truncated history.
9836
+ options.conversationMessages = conversationMessages;
9837
+ const finalBudget = checkContextBudget({
9838
+ provider: providerName,
9839
+ model: options.model,
9840
+ maxTokens: options.maxTokens,
9841
+ systemPrompt: enhancedSystemPrompt,
9842
+ toolReplayMode: this.resolveToolReplayModeForBudget(options),
9843
+ conversationMessages: conversationMessages,
9844
+ currentPrompt: options.input.text,
9845
+ toolDefinitions: availableTools,
9846
+ });
9847
+ if (!finalBudget.withinBudget) {
9848
+ // Clear watermark so handleContextOverflow recovery can re-compact
9849
+ this.lastCompactionMessageCount.delete(streamCompactionSessionId);
9850
+ // Curator P1-2: emit `compaction.insufficient` on the terminal
9851
+ // failure path so cost / audit listeners can record the specific
9852
+ // failure mode (compaction + emergency truncation both insufficient).
9853
+ try {
9854
+ this.emitter.emit("compaction.insufficient", {
9855
+ stagesAttempted: compactionResult.stagesUsed,
9856
+ finalTokens: finalBudget.estimatedInputTokens,
9857
+ budget: finalBudget.availableInputTokens,
9858
+ provider: providerName,
9859
+ model: options.model,
9860
+ phase: "post-emergency-truncation",
9861
+ timestamp: Date.now(),
9862
+ });
9863
+ }
9864
+ catch {
9865
+ /* listener errors are non-fatal */
9866
+ }
9867
+ throw new ContextBudgetExceededError(`Stream context exceeds model budget after all compaction stages. ` +
9868
+ `Estimated: ${finalBudget.estimatedInputTokens} tokens, ` +
9869
+ `Budget: ${finalBudget.availableInputTokens} tokens.`, {
9870
+ estimatedTokens: finalBudget.estimatedInputTokens,
9871
+ availableTokens: finalBudget.availableInputTokens,
9872
+ stagesUsed: compactionResult.stagesUsed,
9873
+ breakdown: finalBudget.breakdown,
9874
+ });
9875
+ }
9876
+ }
9877
+ return conversationMessages;
9878
+ }
9879
+ /**
9880
+ * Stream through the configured ModelPool, walking its members until one
9881
+ * yields a stream. Always returns or throws; never falls through to the
9882
+ * single-provider path.
9883
+ */
9884
+ async streamViaModelPool(streamPool, options, enhancedSystemPrompt, conversationMessages) {
9885
+ const maxStreamAttempts = streamPool.maxAttempts;
9886
+ const streamTriedKeys = new Set();
9887
+ let streamLastError = null;
9888
+ for (let attempt = 0; attempt < maxStreamAttempts; attempt++) {
9889
+ if (options.abortSignal?.aborted) {
9890
+ throw new DOMException("The operation was aborted", "AbortError");
9891
+ }
9892
+ const streamMember = streamPool.selectNext(streamTriedKeys);
9893
+ if (!streamMember) {
9894
+ break;
9895
+ }
9896
+ streamTriedKeys.add(streamPool.memberKey(streamMember));
9897
+ // Override provider/model/region from the pool member.
9898
+ // When the member omits model/region, use undefined (provider default)
9899
+ // rather than inheriting the caller's value for a different provider.
9900
+ const poolStreamProviderName = streamMember.provider;
9901
+ const poolStreamModel = streamMember.model ?? undefined;
9902
+ const poolStreamRegion = streamMember.region ?? undefined;
9903
+ logger.debug(`[createMCPStream] ModelPool: attempting member ${poolStreamProviderName}`, { model: poolStreamModel, attempt });
9904
+ try {
9905
+ const poolStreamProvider = await AIProviderFactory.createProvider(poolStreamProviderName, poolStreamModel, !options.disableTools, this, poolStreamRegion, this.resolveCredentials(options.credentials));
9906
+ poolStreamProvider.setTraceContext(this._metricsTraceContext);
9907
+ poolStreamProvider.setupToolExecutor({
9908
+ customTools: this.getCustomTools(),
9909
+ executeTool: (toolName, params) => this.executeTool(toolName, params, {
9910
+ disableToolCache: options.disableToolCache,
9911
+ }),
9912
+ }, "NeuroLink.createMCPStream");
9913
+ poolStreamProvider.setFileToolRootPolicy?.(this.fileToolRootsFor(options));
9914
+ const poolStreamResult = await poolStreamProvider.stream({
9915
+ ...this.deferProviderStreamTTS(options),
9916
+ provider: poolStreamProviderName,
9917
+ model: poolStreamModel,
9918
+ region: poolStreamRegion,
9919
+ systemPrompt: enhancedSystemPrompt,
9920
+ conversationMessages,
9921
+ });
9922
+ logger.debug("[createMCPStream] ModelPool stream handle obtained", {
9923
+ provider: poolStreamProviderName,
9924
+ });
9925
+ // Wrap the stream so we can record success/failure based on what
9926
+ // actually happens during consumption, not merely on obtaining the
9927
+ // handle. Recording success at handle-acquisition time (before any
9928
+ // tokens are delivered) would mean a mid-stream provider drop is
9929
+ // never reflected as a cooldown.
9930
+ const capturedMember = streamMember;
9931
+ const wrappedStream = (async function* () {
9932
+ try {
9933
+ yield* poolStreamResult.stream;
9934
+ streamPool.recordSuccess(capturedMember);
9935
+ }
9936
+ catch (streamConsumeErr) {
9937
+ streamPool.recordFailure(capturedMember, classifyProviderError(streamConsumeErr));
9938
+ throw streamConsumeErr;
9939
+ }
9940
+ })();
9941
+ return preserveLiveStreamAccessors(poolStreamResult, {
9942
+ ...poolStreamResult,
9943
+ stream: wrappedStream,
9944
+ provider: poolStreamProviderName,
9945
+ model: poolStreamResult.model || poolStreamModel,
9946
+ toolCalls: poolStreamResult.toolCalls ?? [],
9947
+ toolResults: poolStreamResult.toolResults ?? [],
9948
+ });
9949
+ }
9950
+ catch (poolStreamError) {
9951
+ if (isAbortError(poolStreamError)) {
9952
+ throw poolStreamError;
9953
+ }
9954
+ if (isNonRetryableForPool(poolStreamError)) {
9955
+ const poolStreamErrMsg = poolStreamError instanceof Error
9956
+ ? poolStreamError.message
9957
+ : String(poolStreamError);
9958
+ streamPool.recordFailure(streamMember, classifyProviderError(poolStreamError));
9959
+ // Wrap in a plain Error so runWithFallbackOrchestration /
9960
+ // streamWithIterationFallback does not re-activate the modelChain
9961
+ // layer on top of an already-exhausted pool.
9962
+ throw new Error(`[ModelPool] non-retryable: ${poolStreamErrMsg}`, {
9963
+ cause: poolStreamError,
9964
+ });
9965
+ }
9966
+ streamPool.recordFailure(streamMember, classifyProviderError(poolStreamError));
9967
+ streamLastError =
9968
+ poolStreamError instanceof Error
9969
+ ? poolStreamError
9970
+ : new Error(String(poolStreamError));
9971
+ logger.warn(`[createMCPStream] ModelPool: member ${poolStreamProviderName} failed`, { error: streamLastError.message });
9972
+ }
9973
+ }
9974
+ // All pool stream members failed.
9975
+ // Wrap in a plain Error (not a typed error class) so that the
9976
+ // surrounding fallback orchestrator does not start a second retry layer
9977
+ // over the already-exhausted pool.
9978
+ throw new Error(`[ModelPool] all stream members failed: ${streamLastError?.message ?? "no stream members available"}`);
9979
+ }
9945
9980
  /**
9946
9981
  * Process stream result
9947
9982
  */
@@ -10067,6 +10102,20 @@ Current user's request: ${currentInput}`;
10067
10102
  });
10068
10103
  return response;
10069
10104
  }
10105
+ /**
10106
+ * Whether `error` is the refusal of a conversation memory writer that opted in
10107
+ * to the erasure write protocol: the typed epoch error, or the CONFIG_ERROR
10108
+ * that storage which is unreachable, or not Redis, raises while the protocol is on.
10109
+ */
10110
+ isStrictConversationAdmissionFailure(error) {
10111
+ if (error instanceof ConversationWriterEpochError) {
10112
+ return true;
10113
+ }
10114
+ return (error instanceof ConversationMemoryError &&
10115
+ error.code === "CONFIG_ERROR" &&
10116
+ this.conversationMemoryConfig?.conversationMemory
10117
+ ?.erasureWriteProtocol === "conversation-erasure-v1");
10118
+ }
10070
10119
  /**
10071
10120
  * Handle stream error with fallback
10072
10121
  */
@@ -10080,6 +10129,12 @@ Current user's request: ${currentInput}`;
10080
10129
  if (error instanceof ContextBudgetExceededError) {
10081
10130
  throw error;
10082
10131
  }
10132
+ // A writer that opted in to the erasure write protocol and could not be
10133
+ // admitted must not be answered by a fallback provider that has none of
10134
+ // its history and stores nothing: fail closed, as generate() does.
10135
+ if (this.isStrictConversationAdmissionFailure(error)) {
10136
+ throw error;
10137
+ }
10083
10138
  logger.error("Stream generation failed, attempting fallback", {
10084
10139
  error: error instanceof Error ? error.message : String(error),
10085
10140
  });