@juspay/neurolink 13.10.0 → 13.10.2

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
@@ -6760,142 +6760,7 @@ Current user's request: ${currentInput}`;
6760
6760
  // AbortError propagation semantics. Falls through to the standard path
6761
6761
  // when no pool is configured.
6762
6762
  if (this.modelPool) {
6763
- const pool = this.modelPool;
6764
- const maxPoolAttempts = pool.maxAttempts;
6765
- const triedKeys = new Set();
6766
- let poolLastError = null;
6767
- for (let attempt = 0; attempt < maxPoolAttempts; attempt++) {
6768
- if (options.abortSignal?.aborted) {
6769
- throw new DOMException("The operation was aborted", "AbortError");
6770
- }
6771
- const member = pool.selectNext(triedKeys);
6772
- if (!member) {
6773
- // All available members exhausted.
6774
- break;
6775
- }
6776
- triedKeys.add(pool.memberKey(member));
6777
- // Temporarily override provider/model/region from the pool member.
6778
- const savedProvider = options.provider;
6779
- const savedModel = options.model;
6780
- const savedRegion = options.region;
6781
- options.provider = member.provider;
6782
- // When the member omits model/region, clear inherited values so the
6783
- // provider's own default is used rather than a mismatched caller value.
6784
- options.model = member.model ?? undefined;
6785
- options.region = member.region ?? undefined;
6786
- const poolProviderName = member.provider;
6787
- logger.debug(`[${functionTag}] ModelPool: attempting member`, {
6788
- provider: poolProviderName,
6789
- model: member.model ?? options.model,
6790
- attempt,
6791
- });
6792
- try {
6793
- // Get conversation messages for context (use pre-compacted if provided)
6794
- const poolOptionsWithMessages = options;
6795
- const poolConversationMessages = poolOptionsWithMessages
6796
- .conversationMessages?.length
6797
- ? poolOptionsWithMessages.conversationMessages
6798
- : await getConversationMessages(this.conversationMemory, options);
6799
- const poolProvider = await AIProviderFactory.createProvider(poolProviderName, options.model, !options.disableTools, this, options.region, this.resolveCredentials(options.credentials));
6800
- poolProvider.setTraceContext(this._metricsTraceContext);
6801
- poolProvider.setupToolExecutor({
6802
- customTools: this.getCustomTools(),
6803
- executeTool: (toolName, params) => this.executeTool(toolName, params, {
6804
- disableToolCache: options.disableToolCache,
6805
- }),
6806
- }, functionTag);
6807
- poolProvider.setFileToolRootPolicy?.(this.fileToolRootsFor(options));
6808
- const poolResult = await poolProvider.generate({
6809
- ...options,
6810
- conversationMessages: poolConversationMessages,
6811
- });
6812
- if (!poolResult) {
6813
- throw new Error(`ModelPool: provider ${poolProviderName} returned null result`);
6814
- }
6815
- pool.recordSuccess(member);
6816
- const responseTime = Date.now() - startTime;
6817
- // Restore original options fields so callers see a clean object.
6818
- options.provider = savedProvider;
6819
- options.model = savedModel;
6820
- options.region = savedRegion;
6821
- return {
6822
- content: poolResult.content || "",
6823
- provider: poolProviderName,
6824
- model: poolResult.model,
6825
- usage: poolResult.usage,
6826
- responseTime,
6827
- finishReason: poolResult.finishReason,
6828
- stopReason: poolResult.stopReason,
6829
- rawFinishReason: poolResult.rawFinishReason,
6830
- stepsUsed: poolResult.stepsUsed,
6831
- toolsUsed: poolResult.toolsUsed || [],
6832
- toolCalls: poolResult.toolCalls ?? [],
6833
- // Lossless pass-through: keep the full ToolExecutionRecord
6834
- // fields (params/resultText/isError/timing) alongside the
6835
- // legacy {toolName,executionTime,success} shape this internal
6836
- // result declares, so the final GenerateResult mapping
6837
- // reconstructs real records instead of empty ones.
6838
- toolExecutions: poolResult.toolExecutions?.map((te) => ({
6839
- ...te,
6840
- executionTime: te.durationMs,
6841
- success: !te.isError,
6842
- })),
6843
- // A tool RAN (toolsUsed), not merely dispatched.
6844
- enhancedWithTools: !!poolResult.toolsUsed?.length,
6845
- analytics: poolResult.analytics,
6846
- evaluation: poolResult.evaluation,
6847
- audio: poolResult.audio,
6848
- ttsMetadata: poolResult.ttsMetadata,
6849
- video: poolResult.video,
6850
- avatar: poolResult.avatar,
6851
- music: poolResult.music,
6852
- ppt: poolResult.ppt,
6853
- imageOutput: poolResult.imageOutput,
6854
- reasoning: poolResult.reasoning,
6855
- reasoningTokens: poolResult.reasoningTokens,
6856
- _generationEndEmitted: poolResult._generationEndEmitted,
6857
- };
6858
- }
6859
- catch (poolError) {
6860
- // Restore options unconditionally on failure.
6861
- options.provider = savedProvider;
6862
- options.model = savedModel;
6863
- options.region = savedRegion;
6864
- if (isAbortError(poolError)) {
6865
- throw poolError;
6866
- }
6867
- if (isNonRetryableForPool(poolError)) {
6868
- const poolErrMsg = poolError instanceof Error
6869
- ? poolError.message
6870
- : String(poolError);
6871
- logger.warn(`[${functionTag}] ModelPool: non-retryable error from ${poolProviderName}, stopping pool`, { error: poolErrMsg });
6872
- pool.recordFailure(member, classifyProviderError(poolError));
6873
- // Wrap in a plain Error so runWithFallbackOrchestration does not
6874
- // mistake this for a ModelAccessDeniedError and start a second
6875
- // retry layer on top of the already-exhausted pool.
6876
- throw new Error(`[ModelPool] non-retryable: ${poolErrMsg}`, {
6877
- cause: poolError,
6878
- });
6879
- }
6880
- pool.recordFailure(member, classifyProviderError(poolError));
6881
- poolLastError =
6882
- poolError instanceof Error
6883
- ? poolError
6884
- : new Error(String(poolError));
6885
- logger.warn(`[${functionTag}] ModelPool: member ${poolProviderName} failed`, { error: poolLastError.message });
6886
- }
6887
- }
6888
- // All pool members failed or were exhausted.
6889
- const poolResponseTime = Date.now() - startTime;
6890
- logger.error(`[${functionTag}] ModelPool: all members failed`, {
6891
- triedKeys: Array.from(triedKeys),
6892
- lastError: poolLastError?.message,
6893
- responseTime: poolResponseTime,
6894
- });
6895
- // Wrap in a plain Error (not a typed error class) so that
6896
- // runWithFallbackOrchestration does not re-activate the modelChain /
6897
- // providerFallback layer on top of an already-exhausted pool.
6898
- throw new Error(`[ModelPool] all members failed: ${poolLastError?.message ?? "no members available"}`);
6763
+ return this.generateViaModelPool(this.modelPool, options, startTime, functionTag);
6899
6764
  }
6900
6765
  // ─── End ModelPool path ───────────────────────────────────────────────────
6901
6766
  let lastError = null;
@@ -6967,211 +6832,14 @@ Current user's request: ${currentInput}`;
6967
6832
  // as an unbounded retry loop (93K→299K tokens, no verdict, ever).
6968
6833
  // The throw remains for the truly unrecoverable case: system
6969
6834
  // prompt + tool definitions alone exceed the budget.
6970
- let promptWindowRecovered = false;
6971
6835
  if (!budgetCheck.withinBudget && !dpgHasCompactableMessages) {
6972
- const fixedOverhead = (budgetCheck.breakdown?.systemPrompt ?? 0) +
6973
- (budgetCheck.breakdown?.toolDefinitions ?? 0) +
6974
- (budgetCheck.breakdown?.fileAttachments ?? 0);
6975
- // 3% margin against estimator drift; 1024-token floor — below
6976
- // that, a windowed prompt carries too little to answer from.
6977
- const promptBudget = Math.floor((budgetCheck.availableInputTokens - fixedOverhead) * 0.97);
6978
- const promptText = typeof options.prompt === "string" ? options.prompt : undefined;
6979
- if (promptText &&
6980
- promptBudget >= 1024 &&
6981
- (budgetCheck.breakdown?.currentPrompt ?? 0) > promptBudget) {
6982
- const marker = "\n\n[... middle of this prompt elided by NeuroLink to fit the model's context window ...]\n\n";
6983
- // Proportional char budget from the observed chars-per-token of
6984
- // THIS text, re-checked and shrunk until the estimator agrees.
6985
- let charBudget = Math.floor(promptText.length *
6986
- (promptBudget /
6987
- Math.max(budgetCheck.breakdown?.currentPrompt ?? 1, 1)));
6988
- let windowed = promptText;
6989
- for (let attempt = 0; attempt < 4; attempt++) {
6990
- const headChars = Math.floor(charBudget * 0.6);
6991
- const tailChars = Math.max(charBudget - headChars - marker.length, 0);
6992
- windowed =
6993
- promptText.slice(0, headChars) +
6994
- marker +
6995
- (tailChars > 0 ? promptText.slice(-tailChars) : "");
6996
- const recheck = checkContextBudget({
6997
- provider: providerName,
6998
- model: options.model,
6999
- maxTokens: options.maxTokens,
7000
- systemPrompt: options.systemPrompt,
7001
- conversationMessages: [],
7002
- currentPrompt: windowed,
7003
- toolReplayMode: this.resolveToolReplayModeForBudget(options),
7004
- toolDefinitions: options.tools
7005
- ? Object.values(options.tools)
7006
- : undefined,
7007
- });
7008
- if (recheck.withinBudget) {
7009
- break;
7010
- }
7011
- charBudget = Math.floor(charBudget * 0.8);
7012
- if (attempt === 3) {
7013
- windowed = promptText; // give up — fall through to the throw
7014
- }
7015
- }
7016
- if (windowed !== promptText) {
7017
- logger.warn("[NeuroLink] Prompt exceeded the model's context budget with nothing to compact — " +
7018
- "windowed the prompt (head+tail kept, middle elided) to fit.", {
7019
- provider: providerName,
7020
- model: options.model,
7021
- estimatedTokens: budgetCheck.estimatedInputTokens,
7022
- budget: budgetCheck.availableInputTokens,
7023
- originalPromptChars: promptText.length,
7024
- windowedPromptChars: windowed.length,
7025
- });
7026
- try {
7027
- this.emitter.emit("compaction.applied", {
7028
- stagesAttempted: ["pre-dispatch prompt window"],
7029
- finalTokens: budgetCheck.availableInputTokens,
7030
- budget: budgetCheck.availableInputTokens,
7031
- provider: providerName,
7032
- model: options.model,
7033
- phase: "pre-dispatch-prompt-window",
7034
- timestamp: Date.now(),
7035
- });
7036
- }
7037
- catch {
7038
- /* listener errors are non-fatal */
7039
- }
7040
- options.prompt = windowed;
7041
- const inputHolder = options
7042
- .input;
7043
- if (inputHolder && typeof inputHolder.text === "string") {
7044
- inputHolder.text = windowed;
7045
- }
7046
- promptWindowRecovered = true;
7047
- }
7048
- }
7049
- if (!promptWindowRecovered) {
7050
- try {
7051
- this.emitter.emit("compaction.insufficient", {
7052
- stagesAttempted: ["pre-dispatch hard cap"],
7053
- finalTokens: budgetCheck.estimatedInputTokens,
7054
- budget: budgetCheck.availableInputTokens,
7055
- provider: providerName,
7056
- model: options.model,
7057
- phase: "pre-dispatch-no-recovery",
7058
- timestamp: Date.now(),
7059
- });
7060
- }
7061
- catch {
7062
- /* listener errors are non-fatal */
7063
- }
7064
- throw new ContextBudgetExceededError(`Context exceeds model budget and no compaction is possible ` +
7065
- `(no conversationMemory, no inline conversationMessages — only ` +
7066
- `prompt + tools). Estimated: ${budgetCheck.estimatedInputTokens} ` +
7067
- `tokens, budget: ${budgetCheck.availableInputTokens} tokens. ` +
7068
- `Reduce prompt or tool-definition size, or trim the request.`, {
7069
- estimatedTokens: budgetCheck.estimatedInputTokens,
7070
- availableTokens: budgetCheck.availableInputTokens,
7071
- stagesUsed: [],
7072
- breakdown: budgetCheck.breakdown,
7073
- });
7074
- }
6836
+ this.windowOrRefuseOversizedPrompt(options, providerName, budgetCheck);
7075
6837
  }
7076
6838
  if (budgetCheck.shouldCompact &&
7077
6839
  (this.conversationMemory || dpgHasInlineMessages) &&
7078
6840
  dpgMessageCount >
7079
6841
  (this.lastCompactionMessageCount.get(dpgCompactionSessionId) ?? 0)) {
7080
- const compactor = new ContextCompactor({
7081
- provider: providerName,
7082
- summarizationProvider: this.conversationMemoryConfig?.conversationMemory
7083
- ?.summarizationProvider,
7084
- summarizationModel: this.conversationMemoryConfig?.conversationMemory
7085
- ?.summarizationModel,
7086
- }, this.contextCompactorDeps(this.decisionSiteContext(options, dpgCompactionSessionId)));
7087
- const compactionResult = await compactor.compact(conversationMessages, resolveHistoryBudget(budgetCheck, options.compactionThreshold), this.conversationMemoryConfig?.conversationMemory, options.context?.requestId, { currentRequest: options.prompt });
7088
- if (compactionResult.compacted) {
7089
- const repairedResult = repairToolPairs(compactionResult.messages);
7090
- conversationMessages = repairedResult.messages;
7091
- this.lastCompactionMessageCount.set(dpgCompactionSessionId, conversationMessages.length);
7092
- }
7093
- // POST-COMPACTION BUDGET RE-CHECK (BUG-003 fix)
7094
- const postCompactBudget = checkContextBudget({
7095
- provider: providerName,
7096
- model: options.model,
7097
- maxTokens: options.maxTokens,
7098
- systemPrompt: options.systemPrompt,
7099
- conversationMessages: conversationMessages,
7100
- currentPrompt: options.prompt,
7101
- toolReplayMode: this.resolveToolReplayModeForBudget(options),
7102
- toolDefinitions: options.tools
7103
- ? Object.values(options.tools)
7104
- : undefined,
7105
- });
7106
- if (!postCompactBudget.withinBudget) {
7107
- logger.warn("[NeuroLink] directProviderGeneration: post-compaction still over budget, emergency truncation", {
7108
- estimatedTokens: postCompactBudget.estimatedInputTokens,
7109
- availableTokens: postCompactBudget.availableInputTokens,
7110
- overagePercent: Math.round((postCompactBudget.usageRatio - 1.0) * 100),
7111
- });
7112
- // Curator P1-2: emit `compaction.insufficient` whenever a
7113
- // single round of compaction wasn't enough — even when
7114
- // emergency truncation will save the day. Lets cost / audit
7115
- // listeners track the "compaction was insufficient" signal
7116
- // separately from the eventual outcome.
7117
- try {
7118
- this.emitter.emit("compaction.insufficient", {
7119
- stagesAttempted: compactionResult.stagesUsed,
7120
- finalTokens: postCompactBudget.estimatedInputTokens,
7121
- budget: postCompactBudget.availableInputTokens,
7122
- provider: providerName,
7123
- model: options.model,
7124
- phase: "mid-compaction",
7125
- willEmergencyTruncate: true,
7126
- timestamp: Date.now(),
7127
- });
7128
- }
7129
- catch {
7130
- /* listener errors are non-fatal */
7131
- }
7132
- conversationMessages = emergencyContentTruncation(conversationMessages, postCompactBudget.availableInputTokens, postCompactBudget.breakdown, providerName);
7133
- const finalBudget = checkContextBudget({
7134
- provider: providerName,
7135
- model: options.model,
7136
- maxTokens: options.maxTokens,
7137
- systemPrompt: options.systemPrompt,
7138
- conversationMessages: conversationMessages,
7139
- currentPrompt: options.prompt,
7140
- toolReplayMode: this.resolveToolReplayModeForBudget(options),
7141
- toolDefinitions: options.tools
7142
- ? Object.values(options.tools)
7143
- : undefined,
7144
- });
7145
- if (!finalBudget.withinBudget) {
7146
- // Clear watermark so handleContextOverflow recovery can re-compact
7147
- this.lastCompactionMessageCount.delete(dpgCompactionSessionId);
7148
- // Curator P1-2: emit `compaction.insufficient` so cost / audit
7149
- // listeners can record the specific failure mode (separate
7150
- // from a generic provider error).
7151
- try {
7152
- this.emitter.emit("compaction.insufficient", {
7153
- stagesAttempted: compactionResult.stagesUsed,
7154
- finalTokens: finalBudget.estimatedInputTokens,
7155
- budget: finalBudget.availableInputTokens,
7156
- provider: providerName,
7157
- model: options.model,
7158
- phase: "post-emergency-truncation",
7159
- timestamp: Date.now(),
7160
- });
7161
- }
7162
- catch {
7163
- /* listener errors are non-fatal */
7164
- }
7165
- throw new ContextBudgetExceededError(`Context exceeds model budget after all compaction stages. ` +
7166
- `Estimated: ${finalBudget.estimatedInputTokens} tokens, ` +
7167
- `Budget: ${finalBudget.availableInputTokens} tokens.`, {
7168
- estimatedTokens: finalBudget.estimatedInputTokens,
7169
- availableTokens: finalBudget.availableInputTokens,
7170
- stagesUsed: compactionResult.stagesUsed,
7171
- breakdown: finalBudget.breakdown,
7172
- });
7173
- }
7174
- }
6842
+ conversationMessages = await this.compactHistoryForDispatch(options, providerName, budgetCheck, conversationMessages, dpgCompactionSessionId);
7175
6843
  }
7176
6844
  // ADD: Emit connection events for successful provider creation (Bedrock-compatible)
7177
6845
  this.emitter.emit("connected");
@@ -7196,50 +6864,7 @@ Current user's request: ${currentInput}`;
7196
6864
  responseTime,
7197
6865
  contentLength: result.content?.length || 0,
7198
6866
  });
7199
- return {
7200
- content: result.content || "",
7201
- provider: providerName,
7202
- model: result.model,
7203
- usage: result.usage,
7204
- responseTime,
7205
- finishReason: result.finishReason,
7206
- stopReason: result.stopReason,
7207
- rawFinishReason: result.rawFinishReason,
7208
- stepsUsed: result.stepsUsed,
7209
- toolsUsed: result.toolsUsed || [],
7210
- // The providers record executed calls; without this line the public
7211
- // result never carried them, whatever the provider returned.
7212
- toolCalls: result.toolCalls ?? [],
7213
- // Lossless pass-through: keep the full ToolExecutionRecord fields
7214
- // alongside the legacy {toolName,executionTime,success} shape this
7215
- // internal result declares, so the final GenerateResult mapping
7216
- // reconstructs real records instead of empty ones.
7217
- toolExecutions: result.toolExecutions?.map((te) => ({
7218
- ...te,
7219
- executionTime: te.durationMs,
7220
- success: !te.isError,
7221
- })),
7222
- // A tool RAN (toolsUsed), not merely dispatched.
7223
- enhancedWithTools: !!result.toolsUsed?.length,
7224
- analytics: result.analytics,
7225
- evaluation: result.evaluation,
7226
- audio: result.audio,
7227
- ttsMetadata: result.ttsMetadata,
7228
- video: result.video,
7229
- avatar: result.avatar,
7230
- music: result.music,
7231
- ppt: result.ppt,
7232
- // CRITICAL FIX: Include imageOutput for image generation models
7233
- imageOutput: result.imageOutput,
7234
- // Forward reasoning so callers asking for `result.reasoning`
7235
- // (DeepSeek `reasoning_content`, Anthropic thinking, Gemini
7236
- // thought parts, OpenAI o1) actually receive it.
7237
- reasoning: result.reasoning,
7238
- reasoningTokens: result.reasoningTokens,
7239
- // Propagate native-emission flag — see attemptMCPGeneration comment.
7240
- _generationEndEmitted: result
7241
- ._generationEndEmitted,
7242
- };
6867
+ return this.toDirectGenerationResult(result, providerName, responseTime);
7243
6868
  }
7244
6869
  catch (error) {
7245
6870
  // Immediately propagate AbortError — never fall back to next provider on abort
@@ -7265,6 +6890,374 @@ Current user's request: ${currentInput}`;
7265
6890
  }
7266
6891
  }
7267
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) {
7268
7261
  const responseTime = Date.now() - startTime;
7269
7262
  logger.error(`[${functionTag}] All providers failed`, {
7270
7263
  triedProviders: providersToTry,
@@ -7277,7 +7270,7 @@ Current user's request: ${currentInput}`;
7277
7270
  // rejected on budget the caller still needs the typed error to
7278
7271
  // distinguish "context too large" from a generic provider failure.
7279
7272
  if (lastError instanceof ContextBudgetExceededError) {
7280
- throw lastError;
7273
+ return lastError;
7281
7274
  }
7282
7275
  // A single-candidate list (an explicit provider, or
7283
7276
  // disableInternalFallback) never actually tried "all providers" —
@@ -7302,9 +7295,9 @@ Current user's request: ${currentInput}`;
7302
7295
  return wrapped;
7303
7296
  };
7304
7297
  if (providersToTry.length === 1) {
7305
- throw wrapProviderError(`Provider ${providersToTry[0]} failed: ${lastError?.message || "Unknown error"}`);
7298
+ return wrapProviderError(`Provider ${providersToTry[0]} failed: ${lastError?.message || "Unknown error"}`);
7306
7299
  }
7307
- 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"}`);
7308
7301
  }
7309
7302
  /**
7310
7303
  * Create tool-aware system prompt that informs AI about available tools
@@ -8009,43 +8002,7 @@ Current user's request: ${currentInput}`;
8009
8002
  // Constructed BEFORE the cache-hit check so it is available for all
8010
8003
  // outcome paths, including cache-hit turns (Finding 4).
8011
8004
  const routingStartTime = Date.now();
8012
- const emitDecision = (decision) => {
8013
- try {
8014
- const activeSpan = trace.getActiveSpan();
8015
- if (!activeSpan) {
8016
- return;
8017
- }
8018
- activeSpan.setAttribute("tool_routing.outcome", decision.outcome);
8019
- activeSpan.setAttribute("tool_routing.routable_server_count", decision.routableServerCount);
8020
- activeSpan.setAttribute("tool_routing.selected_server_ids", spanJsonAttribute(decision.selectedServerIds));
8021
- activeSpan.setAttribute("tool_routing.excluded_server_ids", spanJsonAttribute(decision.excludedServerIds));
8022
- activeSpan.setAttribute("tool_routing.hallucinated_ids", spanJsonAttribute(decision.hallucinatedIds));
8023
- activeSpan.setAttribute("tool_routing.excluded_tool_count", decision.excludedToolCount);
8024
- activeSpan.setAttribute("tool_routing.cache_hit", decision.cacheHit);
8025
- activeSpan.setAttribute("tool_routing.duration_ms", decision.durationMs);
8026
- // Optional L2 / tool-granularity fields (present only when embedding ran).
8027
- if (decision.embeddingActivated !== undefined) {
8028
- activeSpan.setAttribute("tool_routing.embedding_activated", decision.embeddingActivated);
8029
- }
8030
- if (decision.candidateToolCount !== undefined) {
8031
- activeSpan.setAttribute("tool_routing.candidate_tool_count", decision.candidateToolCount);
8032
- }
8033
- if (decision.granularity !== undefined) {
8034
- activeSpan.setAttribute("tool_routing.granularity", decision.granularity);
8035
- }
8036
- // Which router actually decided. Three strategies can produce an
8037
- // "applied" outcome and they have wildly different cost and
8038
- // latency profiles, so an outcome without a strategy cannot be
8039
- // acted on — and a decision router that silently stopped firing
8040
- // looks identical to one that was never configured.
8041
- if (decision.strategy !== undefined) {
8042
- activeSpan.setAttribute("tool_routing.strategy", decision.strategy);
8043
- }
8044
- }
8045
- catch {
8046
- // Telemetry must never affect routing behaviour.
8047
- }
8048
- };
8005
+ const emitDecision = (decision) => this.recordToolRoutingSpan(decision);
8049
8006
  // Check the cache first.
8050
8007
  if (cacheEnabled && cache && cacheKey !== undefined) {
8051
8008
  const cached = cache.get(cacheKey);
@@ -8109,46 +8066,12 @@ Current user's request: ${currentInput}`;
8109
8066
  // tool embedding vectors are computed once and reused across turns
8110
8067
  // (Finding 1 fix). It is cleared by setToolRoutingServers() when the
8111
8068
  // catalog changes so stale vectors are never used after an update.
8112
- let routingEmbedFn;
8113
8069
  // A host-owned routing callback owns every inference account. The
8114
8070
  // instance's embedding fast-path would otherwise borrow turn credentials.
8115
8071
  const embeddingCfg = routingConfig.generateFn
8116
8072
  ? undefined
8117
8073
  : routingConfig.embedding;
8118
- if (embeddingCfg?.enabled === true) {
8119
- try {
8120
- // Resolve the embedding provider: use the explicitly configured one
8121
- // if present, otherwise fall back to the stream/generate call's
8122
- // provider. The factory call is wrapped in try/catch so a provider
8123
- // that doesn't support embedMany (it throws at call time, not
8124
- // construction time) fails open when routingEmbedFn is invoked.
8125
- const embProviderName = embeddingCfg.provider ??
8126
- (options.provider && options.provider !== "auto"
8127
- ? options.provider
8128
- : undefined) ??
8129
- routingConfig.routerModel?.provider;
8130
- if (embProviderName) {
8131
- const embProvider = await AIProviderFactory.createProvider(embProviderName, embeddingCfg.model, true, this, undefined, this.resolveCredentials(options.credentials));
8132
- // Bind embedMany with the configured model (may be undefined —
8133
- // the provider uses its default embedding model in that case).
8134
- routingEmbedFn = (texts) => withTimeout(embProvider.embedMany(texts, embeddingCfg.model), embeddingCfg.timeoutMs ?? 10000);
8135
- // Lazy-init the persistent vector cache for this instance.
8136
- // Subsequent turns reuse the same Map so text→vector lookups
8137
- // already populated from earlier turns are served from memory.
8138
- if (!this.toolRoutingVectorCache) {
8139
- this.toolRoutingVectorCache = new Map();
8140
- }
8141
- }
8142
- }
8143
- catch (embSetupError) {
8144
- logger.debug("[ToolRouting] Embedding provider setup failed, L2 path disabled for this turn", {
8145
- error: embSetupError instanceof Error
8146
- ? embSetupError.message
8147
- : String(embSetupError),
8148
- });
8149
- // routingEmbedFn remains undefined — fast-path is skipped.
8150
- }
8151
- }
8074
+ const routingEmbedFn = await this.buildToolRoutingEmbedFn(options, routingConfig, embeddingCfg);
8152
8075
  routedExcludeTools = await resolveToolRoutingExclusions({
8153
8076
  catalog,
8154
8077
  alwaysIncludeServerIds: routingConfig.alwaysIncludeServerIds ?? [],
@@ -8219,31 +8142,7 @@ Current user's request: ${currentInput}`;
8219
8142
  }
8220
8143
  // --- ITEM C: store result for future turns ---
8221
8144
  if (resolvedDecision?.outcome === "applied" && cache) {
8222
- // Store the PRE-stickiness exclusion list in the cache so future hits
8223
- // re-apply the live stickiness window rather than the one from this
8224
- // turn (Finding 2).
8225
- if (cacheEnabled && cacheKey !== undefined) {
8226
- try {
8227
- cache.set(cacheKey, {
8228
- excludedToolNames: preStickinessExcludeTools,
8229
- selectedServerIds: resolvedDecision.selectedServerIds,
8230
- });
8231
- }
8232
- catch {
8233
- // Cache write failure is non-fatal.
8234
- }
8235
- }
8236
- // Record selected servers for stickiness on subsequent turns. This must
8237
- // come after getStickyServerIds so the window count is not consumed on
8238
- // the same turn it is set (the off-by-one fix above).
8239
- if (stickinessEnabled && sessionId) {
8240
- try {
8241
- cache.recordSelection(sessionId, resolvedDecision.selectedServerIds);
8242
- }
8243
- catch {
8244
- // Stickiness failure is non-fatal.
8245
- }
8246
- }
8145
+ this.storeToolRoutingOutcome(cache, resolvedDecision, cacheEnabled ? cacheKey : undefined, preStickinessExcludeTools, stickinessEnabled ? sessionId : "");
8247
8146
  }
8248
8147
  if (routedExcludeTools.length > 0) {
8249
8148
  options.excludeTools = [
@@ -8261,6 +8160,120 @@ Current user's request: ${currentInput}`;
8261
8160
  });
8262
8161
  }
8263
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
+ }
8264
8277
  /**
8265
8278
  * Loads a bounded window of prior conversation turns for the router so a
8266
8279
  * follow-up turn carries the context it needs to classify intent. Reads this
@@ -9717,104 +9730,7 @@ Current user's request: ${currentInput}`;
9717
9730
  (hasCallerConversationHistory || this.conversationMemory) &&
9718
9731
  streamMessageCount >
9719
9732
  (this.lastCompactionMessageCount.get(streamCompactionSessionId) ?? 0)) {
9720
- const compactor = new ContextCompactor({
9721
- provider: providerName,
9722
- summarizationProvider: this.conversationMemoryConfig?.conversationMemory
9723
- ?.summarizationProvider,
9724
- summarizationModel: this.conversationMemoryConfig?.conversationMemory
9725
- ?.summarizationModel,
9726
- }, this.contextCompactorDeps(this.decisionSiteContext(options, streamCompactionSessionId)));
9727
- const compactionResult = await compactor.compact(conversationMessages, resolveHistoryBudget(streamBudget, options.compactionThreshold), this.conversationMemoryConfig?.conversationMemory, options.context?.requestId, { currentRequest: options.input.text });
9728
- if (compactionResult.compacted) {
9729
- const repairedResult = repairToolPairs(compactionResult.messages);
9730
- conversationMessages = repairedResult.messages;
9731
- // Keep options.conversationMessages in sync so downstream consumers
9732
- // (e.g. handleStreamFallback) use the compacted history rather than
9733
- // re-reading from conversationMemory.
9734
- options.conversationMessages = conversationMessages;
9735
- this.lastCompactionMessageCount.set(streamCompactionSessionId, conversationMessages.length);
9736
- }
9737
- // POST-COMPACTION BUDGET RE-CHECK (mirrors tryMCPGeneration / directProviderGeneration)
9738
- const postCompactBudget = checkContextBudget({
9739
- provider: providerName,
9740
- model: options.model,
9741
- maxTokens: options.maxTokens,
9742
- systemPrompt: enhancedSystemPrompt,
9743
- toolReplayMode: this.resolveToolReplayModeForBudget(options),
9744
- conversationMessages: conversationMessages,
9745
- currentPrompt: options.input.text,
9746
- toolDefinitions: availableTools,
9747
- });
9748
- if (!postCompactBudget.withinBudget) {
9749
- logger.warn("[NeuroLink] Stream: post-compaction still over budget, emergency truncation", {
9750
- estimatedTokens: postCompactBudget.estimatedInputTokens,
9751
- availableTokens: postCompactBudget.availableInputTokens,
9752
- overagePercent: Math.round((postCompactBudget.usageRatio - 1.0) * 100),
9753
- });
9754
- // Curator P1-2: emit `compaction.insufficient` whenever a single
9755
- // round of compaction wasn't enough — even when emergency
9756
- // truncation will save the day. Lets cost / audit listeners track
9757
- // the "compaction was insufficient" signal separately from the
9758
- // eventual outcome.
9759
- try {
9760
- this.emitter.emit("compaction.insufficient", {
9761
- stagesAttempted: compactionResult.stagesUsed,
9762
- finalTokens: postCompactBudget.estimatedInputTokens,
9763
- budget: postCompactBudget.availableInputTokens,
9764
- provider: providerName,
9765
- model: options.model,
9766
- phase: "mid-compaction",
9767
- willEmergencyTruncate: true,
9768
- timestamp: Date.now(),
9769
- });
9770
- }
9771
- catch {
9772
- /* listener errors are non-fatal */
9773
- }
9774
- conversationMessages = emergencyContentTruncation(conversationMessages, postCompactBudget.availableInputTokens, postCompactBudget.breakdown, providerName);
9775
- // Keep options in sync after emergency truncation so fallback paths
9776
- // use the truncated history.
9777
- options.conversationMessages = conversationMessages;
9778
- const finalBudget = checkContextBudget({
9779
- provider: providerName,
9780
- model: options.model,
9781
- maxTokens: options.maxTokens,
9782
- systemPrompt: enhancedSystemPrompt,
9783
- toolReplayMode: this.resolveToolReplayModeForBudget(options),
9784
- conversationMessages: conversationMessages,
9785
- currentPrompt: options.input.text,
9786
- toolDefinitions: availableTools,
9787
- });
9788
- if (!finalBudget.withinBudget) {
9789
- // Clear watermark so handleContextOverflow recovery can re-compact
9790
- this.lastCompactionMessageCount.delete(streamCompactionSessionId);
9791
- // Curator P1-2: emit `compaction.insufficient` on the terminal
9792
- // failure path so cost / audit listeners can record the specific
9793
- // failure mode (compaction + emergency truncation both insufficient).
9794
- try {
9795
- this.emitter.emit("compaction.insufficient", {
9796
- stagesAttempted: compactionResult.stagesUsed,
9797
- finalTokens: finalBudget.estimatedInputTokens,
9798
- budget: finalBudget.availableInputTokens,
9799
- provider: providerName,
9800
- model: options.model,
9801
- phase: "post-emergency-truncation",
9802
- timestamp: Date.now(),
9803
- });
9804
- }
9805
- catch {
9806
- /* listener errors are non-fatal */
9807
- }
9808
- throw new ContextBudgetExceededError(`Stream context exceeds model budget after all compaction stages. ` +
9809
- `Estimated: ${finalBudget.estimatedInputTokens} tokens, ` +
9810
- `Budget: ${finalBudget.availableInputTokens} tokens.`, {
9811
- estimatedTokens: finalBudget.estimatedInputTokens,
9812
- availableTokens: finalBudget.availableInputTokens,
9813
- stagesUsed: compactionResult.stagesUsed,
9814
- breakdown: finalBudget.breakdown,
9815
- });
9816
- }
9817
- }
9733
+ conversationMessages = await this.compactStreamHistory(options, providerName, streamBudget, enhancedSystemPrompt, availableTools, conversationMessages);
9818
9734
  }
9819
9735
  // ─── ModelPool stream path ────────────────────────────────────────────────
9820
9736
  // When a pool is configured, replaces the single provider.stream() call
@@ -9826,101 +9742,7 @@ Current user's request: ${currentInput}`;
9826
9742
  // On exhaustion, throws the last member error — does NOT fall through to
9827
9743
  // the static provider path below.
9828
9744
  if (this.modelPool) {
9829
- const streamPool = this.modelPool;
9830
- const maxStreamAttempts = streamPool.maxAttempts;
9831
- const streamTriedKeys = new Set();
9832
- let streamLastError = null;
9833
- for (let attempt = 0; attempt < maxStreamAttempts; attempt++) {
9834
- if (options.abortSignal?.aborted) {
9835
- throw new DOMException("The operation was aborted", "AbortError");
9836
- }
9837
- const streamMember = streamPool.selectNext(streamTriedKeys);
9838
- if (!streamMember) {
9839
- break;
9840
- }
9841
- streamTriedKeys.add(streamPool.memberKey(streamMember));
9842
- // Override provider/model/region from the pool member.
9843
- // When the member omits model/region, use undefined (provider default)
9844
- // rather than inheriting the caller's value for a different provider.
9845
- const poolStreamProviderName = streamMember.provider;
9846
- const poolStreamModel = streamMember.model ?? undefined;
9847
- const poolStreamRegion = streamMember.region ?? undefined;
9848
- logger.debug(`[createMCPStream] ModelPool: attempting member ${poolStreamProviderName}`, { model: poolStreamModel, attempt });
9849
- try {
9850
- const poolStreamProvider = await AIProviderFactory.createProvider(poolStreamProviderName, poolStreamModel, !options.disableTools, this, poolStreamRegion, this.resolveCredentials(options.credentials));
9851
- poolStreamProvider.setTraceContext(this._metricsTraceContext);
9852
- poolStreamProvider.setupToolExecutor({
9853
- customTools: this.getCustomTools(),
9854
- executeTool: (toolName, params) => this.executeTool(toolName, params, {
9855
- disableToolCache: options.disableToolCache,
9856
- }),
9857
- }, "NeuroLink.createMCPStream");
9858
- poolStreamProvider.setFileToolRootPolicy?.(this.fileToolRootsFor(options));
9859
- const poolStreamResult = await poolStreamProvider.stream({
9860
- ...this.deferProviderStreamTTS(options),
9861
- provider: poolStreamProviderName,
9862
- model: poolStreamModel,
9863
- region: poolStreamRegion,
9864
- systemPrompt: enhancedSystemPrompt,
9865
- conversationMessages,
9866
- });
9867
- logger.debug("[createMCPStream] ModelPool stream handle obtained", {
9868
- provider: poolStreamProviderName,
9869
- });
9870
- // Wrap the stream so we can record success/failure based on what
9871
- // actually happens during consumption, not merely on obtaining the
9872
- // handle. Recording success at handle-acquisition time (before any
9873
- // tokens are delivered) would mean a mid-stream provider drop is
9874
- // never reflected as a cooldown.
9875
- const capturedMember = streamMember;
9876
- const wrappedStream = (async function* () {
9877
- try {
9878
- yield* poolStreamResult.stream;
9879
- streamPool.recordSuccess(capturedMember);
9880
- }
9881
- catch (streamConsumeErr) {
9882
- streamPool.recordFailure(capturedMember, classifyProviderError(streamConsumeErr));
9883
- throw streamConsumeErr;
9884
- }
9885
- })();
9886
- return preserveLiveStreamAccessors(poolStreamResult, {
9887
- ...poolStreamResult,
9888
- stream: wrappedStream,
9889
- provider: poolStreamProviderName,
9890
- model: poolStreamResult.model || poolStreamModel,
9891
- toolCalls: poolStreamResult.toolCalls ?? [],
9892
- toolResults: poolStreamResult.toolResults ?? [],
9893
- });
9894
- }
9895
- catch (poolStreamError) {
9896
- if (isAbortError(poolStreamError)) {
9897
- throw poolStreamError;
9898
- }
9899
- if (isNonRetryableForPool(poolStreamError)) {
9900
- const poolStreamErrMsg = poolStreamError instanceof Error
9901
- ? poolStreamError.message
9902
- : String(poolStreamError);
9903
- streamPool.recordFailure(streamMember, classifyProviderError(poolStreamError));
9904
- // Wrap in a plain Error so runWithFallbackOrchestration /
9905
- // streamWithIterationFallback does not re-activate the modelChain
9906
- // layer on top of an already-exhausted pool.
9907
- throw new Error(`[ModelPool] non-retryable: ${poolStreamErrMsg}`, {
9908
- cause: poolStreamError,
9909
- });
9910
- }
9911
- streamPool.recordFailure(streamMember, classifyProviderError(poolStreamError));
9912
- streamLastError =
9913
- poolStreamError instanceof Error
9914
- ? poolStreamError
9915
- : new Error(String(poolStreamError));
9916
- logger.warn(`[createMCPStream] ModelPool: member ${poolStreamProviderName} failed`, { error: streamLastError.message });
9917
- }
9918
- }
9919
- // All pool stream members failed.
9920
- // Wrap in a plain Error (not a typed error class) so that the
9921
- // surrounding fallback orchestrator does not start a second retry layer
9922
- // over the already-exhausted pool.
9923
- throw new Error(`[ModelPool] all stream members failed: ${streamLastError?.message ?? "no stream members available"}`);
9745
+ return this.streamViaModelPool(this.modelPool, options, enhancedSystemPrompt, conversationMessages);
9924
9746
  }
9925
9747
  // ─── End ModelPool stream path ────────────────────────────────────────────
9926
9748
  // 🔧 FIX: Pass enhanced system prompt to real streaming
@@ -9947,6 +9769,214 @@ Current user's request: ${currentInput}`;
9947
9769
  toolResults: streamResult.toolResults ?? [],
9948
9770
  });
9949
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
+ }
9950
9980
  /**
9951
9981
  * Process stream result
9952
9982
  */
@@ -11639,6 +11669,8 @@ Current user's request: ${currentInput}`;
11639
11669
  }
11640
11670
  structuredError = new NeuroLinkError({
11641
11671
  ...structuredError,
11672
+ // Error#message is non-enumerable, so the spread above drops it.
11673
+ message: structuredError.message,
11642
11674
  context: {
11643
11675
  ...structuredError.context,
11644
11676
  executionTime,