Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

♻️ refactor: Agent Runtime stability improvement (#13257)

Rylan Cai7be18092d366
diff --git a/src/server/modules/AgentRuntime/RuntimeExecutors.ts b/src/server/modules/AgentRuntime/RuntimeExecutors.ts
index d7de2bf4d0e..526be6d486a 100644
--- a/src/server/modules/AgentRuntime/RuntimeExecutors.ts
+++ b/src/server/modules/AgentRuntime/RuntimeExecutors.ts
@@ -2,6 +2,7 @@ import {
type AgentEvent,
type AgentInstruction,
type AgentInstructionCompressContext,
+ type AgentState,
type CallLLMPayload,
type GeneralAgentCallLLMResultPayload,
type GeneralAgentCompressionResultPayload,
@@ -37,8 +38,12 @@ import { type EvalContext } from '@/server/modules/Mecha/ContextEngineering/type
import { initModelRuntimeFromDB } from '@/server/modules/ModelRuntime';
import { AgentDocumentsService } from '@/server/services/agentDocuments';
import { MessageService } from '@/server/services/message';
-import { type ToolExecutionService } from '@/server/services/toolExecution';
+import {
+ type ToolExecutionResultResponse,
+ type ToolExecutionService,
+} from '@/server/services/toolExecution';
+import { classifyLLMError, type LLMErrorKind } from './llmErrorClassification';
import { type IStreamEventManager } from './types';
const log = debug('lobe-server:agent-runtime:streaming-executors');
@@ -63,6 +68,83 @@ const TOOL_PRICING: Record<string, number> = {
'lobe-web-browsing/search': 0,
};
+const TOOL_MAX_RETRIES = 2;
+const LLM_MAX_RETRIES = 5;
+const LLM_RETRY_BASE_DELAY_MS = 1000;
+const LLM_RETRY_MAX_DELAY_MS = 30_000;
+
+type ToolFailureKind = 'replan' | 'retry' | 'stop';
+
+const getToolFailureKind = (result: ToolExecutionResultResponse): ToolFailureKind | undefined => {
+ if (!result.error || typeof result.error !== 'object') return;
+
+ const { kind } = result.error as { kind?: unknown };
+ return kind === 'replan' || kind === 'retry' || kind === 'stop' ? kind : undefined;
+};
+
+const shouldRetryTool = (kind: ToolFailureKind | undefined, attempt: number, maxRetries: number) =>
+ kind === 'retry' && attempt <= maxRetries;
+
+const shouldRetryLLM = (kind: LLMErrorKind, attempt: number, maxRetries: number) =>
+ kind === 'retry' && attempt <= maxRetries;
+
+const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
+
+const getLLMRetryDelayMs = (attempt: number) =>
+ Math.min(LLM_RETRY_BASE_DELAY_MS * 2 ** Math.max(attempt - 1, 0), LLM_RETRY_MAX_DELAY_MS);
+
+const isOperationInterrupted = async (ctx: RuntimeExecutorContext) => {
+ if (!ctx.loadAgentState) return false;
+
+ try {
+ const latestState = await ctx.loadAgentState(ctx.operationId);
+ return latestState?.status === 'interrupted';
+ } catch (error) {
+ console.error('[RuntimeExecutors] Failed to load operation state for retry guard:', error);
+ return false;
+ }
+};
+
+const executeToolWithRetry = async (
+ execute: () => Promise<ToolExecutionResultResponse>,
+ params: {
+ isInterrupted?: () => Promise<boolean>;
+ maxRetries: number;
+ operationLogId: string;
+ toolName: string;
+ },
+): Promise<{ attempts: number; result: ToolExecutionResultResponse }> => {
+ const maxAttempts = params.maxRetries + 1;
+
+ for (let attempt = 1; attempt <= maxAttempts; attempt++) {
+ const result = await execute();
+
+ if (result.success) return { attempts: attempt, result };
+
+ const kind = getToolFailureKind(result);
+
+ if (shouldRetryTool(kind, attempt, params.maxRetries)) {
+ if (await params.isInterrupted?.()) {
+ return { attempts: attempt, result };
+ }
+
+ log(
+ '[%s] Tool %s failed with kind=%s (attempt %d/%d), retrying ...',
+ params.operationLogId,
+ params.toolName,
+ kind,
+ attempt,
+ maxAttempts,
+ );
+ continue;
+ }
+
+ return { attempts: attempt, result };
+ }
+
+ throw new Error('Tool execution retry loop exited unexpectedly');
+};
+
const formatErrorEventData = (error: unknown, phase: string) => {
let errorMessage = 'Unknown error';
let errorType: string | undefined;
@@ -114,6 +196,7 @@ export interface RuntimeExecutorContext {
discordContext?: any;
evalContext?: EvalContext;
fileService?: any;
+ loadAgentState?: (operationId: string) => Promise<AgentState | null>;
messageModel: MessageModel;
operationId: string;
serverDB: LobeChatDatabase;
@@ -233,21 +316,7 @@ export const createRuntimeExecutors = (
});
try {
- let content = '';
- let toolsCalling: ChatToolPayload[] = [];
- let tool_calls: MessageToolCall[] = [];
- let thinkingContent = '';
- const imageList: any[] = [];
- let grounding: any = null;
- let currentStepUsage: any = undefined;
- let streamError: any = undefined;
-
- // Multimodal content parts tracking
type ContentPart = { text: string; type: 'text' } | { image: string; type: 'image' };
- const contentParts: ContentPart[] = [];
- const reasoningParts: ContentPart[] = [];
- const hasContentImages = false;
- const hasReasoningImages = false;
// Process messages through serverMessagesEngine to inject system role, knowledge, etc.
// Rebuild params from agentConfig at execution time (capabilities built dynamically)
@@ -403,23 +472,14 @@ export const createRuntimeExecutors = (
// Construct ChatStreamPayload
const stream = ctx.stream ?? true;
-
const chatPayload = { messages: processedMessages, model, stream, tools };
- log(
- `${stagePrefix} calling model-runtime chat (model: %s, messages: %d, tools: %d)`,
- model,
- processedMessages.length,
- tools?.length ?? 0,
- );
-
// Buffer: accumulate text and reasoning, send every 50ms
const BUFFER_INTERVAL = 50;
let textBuffer = '';
let reasoningBuffer = '';
let textBufferTimer: NodeJS.Timeout | null = null;
-
let reasoningBufferTimer: NodeJS.Timeout | null = null;
const flushTextBuffer = async () => {
@@ -478,254 +538,331 @@ export const createRuntimeExecutors = (
}
};
- // Call model-runtime chat
- const response = await modelRuntime.chat(chatPayload, {
- callback: {
- onCompletion: async (data) => {
- // Capture usage (may or may not include cost)
- if (data.usage) {
- currentStepUsage = data.usage;
- }
- },
- onGrounding: async (groundingData) => {
- log(`[${operationLogId}][grounding] %O`, groundingData);
- grounding = groundingData;
+ const maxAttempts = LLM_MAX_RETRIES + 1;
+
+ for (let attempt = 1; attempt <= maxAttempts; attempt++) {
+ let content = '';
+ let toolsCalling: ChatToolPayload[] = [];
+ let tool_calls: MessageToolCall[] = [];
+ let thinkingContent = '';
+ const imageList: any[] = [];
+ let grounding: any = null;
+ let currentStepUsage: any = undefined;
+ let streamError: any = undefined;
+ const contentParts: ContentPart[] = [];
+ const reasoningParts: ContentPart[] = [];
+ const hasContentImages = false;
+ const hasReasoningImages = false;
+ textBuffer = '';
+ reasoningBuffer = '';
- await streamManager.publishStreamChunk(operationId, stepIndex, {
- chunkType: 'grounding',
- grounding: groundingData,
- });
- },
- onText: async (text) => {
- timing(
- '[%s] onText received chunk at %d, length: %d',
- operationLogId,
- Date.now(),
- text.length,
- );
- content += text;
+ const clearAttemptBuffers = () => {
+ if (textBufferTimer) {
+ clearTimeout(textBufferTimer);
+ textBufferTimer = null;
+ }
- textBuffer += text;
+ if (reasoningBufferTimer) {
+ clearTimeout(reasoningBufferTimer);
+ reasoningBufferTimer = null;
+ }
- // If no timer exists, create one
- if (!textBufferTimer) {
- textBufferTimer = setTimeout(async () => {
- await flushTextBuffer();
- textBufferTimer = null;
- }, BUFFER_INTERVAL);
- }
- },
- onThinking: async (reasoning) => {
- timing(
- '[%s] onThinking received chunk at %d, length: %d',
- operationLogId,
- Date.now(),
- reasoning.length,
+ textBuffer = '';
+ reasoningBuffer = '';
+ };
+
+ try {
+ log(
+ `${stagePrefix} calling model-runtime chat (attempt %d/%d, model: %s, messages: %d, tools: %d)`,
+ attempt,
+ maxAttempts,
+ model,
+ processedMessages.length,
+ tools?.length ?? 0,
+ );
+
+ // Call model-runtime chat
+ const response = await modelRuntime.chat(chatPayload, {
+ callback: {
+ onCompletion: async (data) => {
+ // Capture usage (may or may not include cost)
+ if (data.usage) {
+ currentStepUsage = data.usage;
+ }
+ },
+ onGrounding: async (groundingData) => {
+ log(`[${operationLogId}][grounding] %O`, groundingData);
+ grounding = groundingData;
+
+ await streamManager.publishStreamChunk(operationId, stepIndex, {
+ chunkType: 'grounding',
+ grounding: groundingData,
+ });
+ },
+ onText: async (text) => {
+ timing(
+ '[%s] onText received chunk at %d, length: %d',
+ operationLogId,
+ Date.now(),
+ text.length,
+ );
+ content += text;
+
+ textBuffer += text;
+
+ // If no timer exists, create one
+ if (!textBufferTimer) {
+ textBufferTimer = setTimeout(async () => {
+ await flushTextBuffer();
+ textBufferTimer = null;
+ }, BUFFER_INTERVAL);
+ }
+ },
+ onThinking: async (reasoning) => {
+ timing(
+ '[%s] onThinking received chunk at %d, length: %d',
+ operationLogId,
+ Date.now(),
+ reasoning.length,
+ );
+ thinkingContent += reasoning;
+
+ // Buffer reasoning content
+ reasoningBuffer += reasoning;
+
+ // If no timer exists, create one
+ if (!reasoningBufferTimer) {
+ reasoningBufferTimer = setTimeout(async () => {
+ await flushReasoningBuffer();
+ reasoningBufferTimer = null;
+ }, BUFFER_INTERVAL);
+ }
+ },
+ onToolsCalling: async ({ toolsCalling: raw }) => {
+ const resolvedCalls = new ToolNameResolver().resolve(raw, resolved.manifestMap);
+ // Add source field from resolved sourceMap for routing tool execution
+ const payload = resolvedCalls.map((p) => ({
+ ...p,
+ source: resolved.sourceMap[p.identifier],
+ }));
+ // log(`[${operationLogId}][toolsCalling]`, payload);
+ toolsCalling = payload;
+ tool_calls = raw;
+
+ // If textBuffer exists, flush it first
+ if (!!textBuffer) {
+ await flushTextBuffer();
+ }
+
+ await streamManager.publishStreamChunk(operationId, stepIndex, {
+ chunkType: 'tools_calling',
+ toolsCalling: payload,
+ });
+ },
+ onError: async (errorData) => {
+ streamError = errorData;
+ console.error(`[${operationLogId}][stream_error]`, errorData);
+ },
+ },
+ metadata: {
+ operationId,
+ topicId: state.metadata?.topicId,
+ trigger: state.metadata?.trigger,
+ },
+ user: ctx.userId,
+ });
+
+ // Consume stream to ensure all callbacks complete execution
+ await consumeStreamUntilDone(response);
+
+ // If a stream error was captured via onError callback, throw to propagate the error
+ if (streamError) {
+ const streamExecutionError = new Error(
+ typeof streamError.message === 'string'
+ ? `LLM stream error: ${streamError.message}`
+ : `LLM stream error: ${JSON.stringify(streamError)}`,
);
- thinkingContent += reasoning;
+ const { message: _message, ...restStreamError } = streamError as Record<
+ string,
+ unknown
+ >;
+ Object.assign(streamExecutionError, restStreamError);
+ throw streamExecutionError;
+ }
- // Buffer reasoning content
- reasoningBuffer += reasoning;
+ await flushTextBuffer();
+ await flushReasoningBuffer();
+ clearAttemptBuffers();
- // If no timer exists, create one
- if (!reasoningBufferTimer) {
- reasoningBufferTimer = setTimeout(async () => {
- await flushReasoningBuffer();
- reasoningBufferTimer = null;
- }, BUFFER_INTERVAL);
- }
- },
- onToolsCalling: async ({ toolsCalling: raw }) => {
- const resolvedCalls = new ToolNameResolver().resolve(raw, resolved.manifestMap);
- // Add source field from resolved sourceMap for routing tool execution
- const payload = resolvedCalls.map((p) => ({
- ...p,
- source: resolved.sourceMap[p.identifier],
- }));
- // log(`[${operationLogId}][toolsCalling]`, payload);
- toolsCalling = payload;
- tool_calls = raw;
-
- // If textBuffer exists, flush it first
- if (!!textBuffer) {
- await flushTextBuffer();
- }
+ log(
+ `[${operationLogId}] finish model-runtime calling | content: %d chars | reasoning: %d chars | tools: %d | usage: %s`,
+ content.length,
+ thinkingContent.length,
+ toolsCalling.length,
+ currentStepUsage ? 'yes' : 'none',
+ );
- await streamManager.publishStreamChunk(operationId, stepIndex, {
- chunkType: 'tools_calling',
- toolsCalling: payload,
- });
- },
- onError: async (errorData) => {
- streamError = errorData;
- console.error(`[${operationLogId}][stream_error]`, errorData);
- },
- },
- metadata: {
- operationId,
- topicId: state.metadata?.topicId,
- trigger: state.metadata?.trigger,
- },
- user: ctx.userId,
- });
+ if (thinkingContent) {
+ log(`[${operationLogId}][reasoning]`, thinkingContent);
+ }
+ if (content) {
+ log(`[${operationLogId}][content]`, content);
+ }
+ if (toolsCalling.length > 0) {
+ log(`[${operationLogId}][toolsCalling] `, toolsCalling);
+ }
- // Consume stream to ensure all callbacks complete execution
- await consumeStreamUntilDone(response);
+ // Log usage information
+ if (currentStepUsage) {
+ log(`[${operationLogId}][usage] %O`, currentStepUsage);
+ }
- // If a stream error was captured via onError callback, throw to propagate the error
- if (streamError) {
- const errorMessage =
- typeof streamError.message === 'string'
- ? streamError.message
- : JSON.stringify(streamError);
- throw new Error(`LLM stream error: ${errorMessage}`);
- }
+ // Add a complete llm_stream event (including all streaming chunks)
+ events.push({
+ result: { content, reasoning: thinkingContent, tool_calls, usage: currentStepUsage },
+ type: 'llm_result',
+ });
- await flushTextBuffer();
- await flushReasoningBuffer();
+ // Publish stream end event
+ await streamManager.publishStreamEvent(operationId, {
+ data: {
+ finalContent: content,
+ grounding,
+ imageList: imageList.length > 0 ? imageList : undefined,
+ reasoning: thinkingContent || undefined,
+ toolsCalling,
+ usage: currentStepUsage,
+ },
+ stepIndex,
+ type: 'stream_end',
+ });
- // Clean up timers and flush remaining buffers
- if (textBufferTimer) {
- clearTimeout(textBufferTimer);
- textBufferTimer = null;
- }
+ log('[%s:%d] call_llm completed', operationId, stepIndex);
+
+ // ===== 1. First save original usage to message.metadata =====
+ // Determine final content - use serialized parts if has images, otherwise plain text
+ const finalContent = hasContentImages ? serializePartsForStorage(contentParts) : content;
+
+ // Determine final reasoning - handle multimodal reasoning
+ let finalReasoning: any = undefined;
+ if (hasReasoningImages) {
+ // Has images, use multimodal format
+ finalReasoning = {
+ content: serializePartsForStorage(reasoningParts),
+ isMultimodal: true,
+ };
+ } else if (thinkingContent) {
+ // Has text from reasoning but no images
+ finalReasoning = {
+ content: thinkingContent,
+ };
+ }
- if (reasoningBufferTimer) {
- clearTimeout(reasoningBufferTimer);
- reasoningBufferTimer = null;
- }
+ try {
+ // Build metadata object
+ const metadata: Record<string, any> = {};
+ if (currentStepUsage && typeof currentStepUsage === 'object') {
+ Object.assign(metadata, currentStepUsage);
+ }
+ if (hasContentImages) {
+ metadata.isMultimodal = true;
+ }
- log(
- `[${operationLogId}] finish model-runtime calling | content: %d chars | reasoning: %d chars | tools: %d | usage: %s`,
- content.length,
- thinkingContent.length,
- toolsCalling.length,
- currentStepUsage ? 'yes' : 'none',
- );
+ await ctx.messageModel.update(assistantMessageItem.id, {
+ content: finalContent,
+ imageList: imageList.length > 0 ? imageList : undefined,
+ metadata: Object.keys(metadata).length > 0 ? metadata : undefined,
+ reasoning: finalReasoning,
+ search: grounding,
+ tools: toolsCalling.length > 0 ? toolsCalling : undefined,
+ });
+ } catch (error) {
+ console.error('[call_llm] Failed to update message:', error);
+ }
- if (thinkingContent) {
- log(`[${operationLogId}][reasoning]`, thinkingContent);
- }
- if (content) {
- log(`[${operationLogId}][content]`, content);
- }
- if (toolsCalling.length > 0) {
- log(`[${operationLogId}][toolsCalling] `, toolsCalling);
- }
+ // ===== 2. Then accumulate to AgentState =====
+ const newState = structuredClone(state);
- // Log usage information
- if (currentStepUsage) {
- log(`[${operationLogId}][usage] %O`, currentStepUsage);
- }
+ newState.messages.push({
+ content,
+ role: 'assistant',
+ tool_calls: tool_calls.length > 0 ? tool_calls : undefined,
+ });
- // Add a complete llm_stream event (including all streaming chunks)
- events.push({
- result: { content, reasoning: thinkingContent, tool_calls, usage: currentStepUsage },
- type: 'llm_result',
- });
+ if (currentStepUsage) {
+ // Use UsageCounter to uniformly accumulate usage and cost
+ const { usage, cost } = UsageCounter.accumulateLLM({
+ cost: newState.cost,
+ model: llmPayload.model,
+ modelUsage: currentStepUsage,
+ provider: llmPayload.provider,
+ usage: newState.usage,
+ });
- // Publish stream end event
- await streamManager.publishStreamEvent(operationId, {
- data: {
- finalContent: content,
- grounding,
- imageList: imageList.length > 0 ? imageList : undefined,
- reasoning: thinkingContent || undefined,
- toolsCalling,
- usage: currentStepUsage,
- },
- stepIndex,
- type: 'stream_end',
- });
+ newState.usage = usage;
+ if (cost) newState.cost = cost;
+ }
- log('[%s:%d] call_llm completed', operationId, stepIndex);
+ return {
+ events,
+ newState,
+ nextContext: {
+ payload: {
+ hasToolsCalling: toolsCalling.length > 0,
+ // Pass assistant message ID as parentMessageId for tool calls
+ parentMessageId: assistantMessageItem.id,
+ result: { content, tool_calls },
+ toolsCalling,
+ } as GeneralAgentCallLLMResultPayload,
+ phase: 'llm_result',
+ session: {
+ eventCount: events.length,
+ messageCount: newState.messages.length,
+ sessionId: operationId,
+ status: 'running',
+ stepCount: state.stepCount + 1,
+ },
+ stepUsage: currentStepUsage,
+ },
+ };
+ } catch (error) {
+ clearAttemptBuffers();
- // ===== 1. First save original usage to message.metadata =====
- // Determine final content - use serialized parts if has images, otherwise plain text
- const finalContent = hasContentImages ? serializePartsForStorage(contentParts) : content;
+ const classified = classifyLLMError(error);
+ const interrupted = await isOperationInterrupted(ctx);
- // Determine final reasoning - handle multimodal reasoning
- let finalReasoning: any = undefined;
- if (hasReasoningImages) {
- // Has images, use multimodal format
- finalReasoning = {
- content: serializePartsForStorage(reasoningParts),
- isMultimodal: true,
- };
- } else if (thinkingContent) {
- // Has text from reasoning but no images
- finalReasoning = {
- content: thinkingContent,
- };
- }
+ if (!interrupted && shouldRetryLLM(classified.kind, attempt, LLM_MAX_RETRIES)) {
+ const delayMs = getLLMRetryDelayMs(attempt);
- try {
- // Build metadata object
- const metadata: Record<string, any> = {};
- if (currentStepUsage && typeof currentStepUsage === 'object') {
- Object.assign(metadata, currentStepUsage);
- }
- if (hasContentImages) {
- metadata.isMultimodal = true;
- }
+ log(
+ '[%s] LLM call failed with kind=%s (attempt %d/%d), retrying in %dms ...',
+ operationLogId,
+ classified.kind,
+ attempt,
+ maxAttempts,
+ delayMs,
+ );
- await ctx.messageModel.update(assistantMessageItem.id, {
- content: finalContent,
- imageList: imageList.length > 0 ? imageList : undefined,
- metadata: Object.keys(metadata).length > 0 ? metadata : undefined,
- reasoning: finalReasoning,
- search: grounding,
- tools: toolsCalling.length > 0 ? toolsCalling : undefined,
- });
- } catch (error) {
- console.error('[call_llm] Failed to update message:', error);
- }
+ await streamManager.publishStreamEvent(operationId, {
+ data: { attempt: attempt + 1, delayMs, maxAttempts },
+ stepIndex,
+ type: 'stream_retry',
+ });
- // ===== 2. Then accumulate to AgentState =====
- const newState = structuredClone(state);
+ await sleep(delayMs);
- newState.messages.push({
- content,
- role: 'assistant',
- tool_calls: tool_calls.length > 0 ? tool_calls : undefined,
- });
+ if (await isOperationInterrupted(ctx)) {
+ throw error;
+ }
- if (currentStepUsage) {
- // Use UsageCounter to uniformly accumulate usage and cost
- const { usage, cost } = UsageCounter.accumulateLLM({
- cost: newState.cost,
- model: llmPayload.model,
- modelUsage: currentStepUsage,
- provider: llmPayload.provider,
- usage: newState.usage,
- });
+ continue;
+ }
- newState.usage = usage;
- if (cost) newState.cost = cost;
+ throw error;
+ }
}
- return {
- events,
- newState,
- nextContext: {
- payload: {
- hasToolsCalling: toolsCalling.length > 0,
- // Pass assistant message ID as parentMessageId for tool calls
- parentMessageId: assistantMessageItem.id,
- result: { content, tool_calls },
- toolsCalling,
- } as GeneralAgentCallLLMResultPayload,
- phase: 'llm_result',
- session: {
- eventCount: events.length,
- messageCount: newState.messages.length,
- sessionId: operationId,
- status: 'running',
- stepCount: state.stepCount + 1,
- },
- stepUsage: currentStepUsage,
- },
- };
+ throw new Error('LLM execution retry loop exited unexpectedly');
} catch (error) {
// Publish error event
await streamManager.publishStreamEvent(operationId, {
@@ -1033,18 +1170,28 @@ export const createRuntimeExecutors = (
// Execute tool using ToolExecutionService
log(`[${operationLogId}] Executing tool ${toolName} ...`);
- const executionResult = await toolExecutionService.executeTool(chatToolPayload, {
- activeDeviceId: state.metadata?.activeDeviceId,
- agentId: state.metadata?.agentId,
- memoryToolPermission: agentConfig?.chatConfig?.memory?.toolPermission,
- serverDB: ctx.serverDB,
- taskId: state.metadata?.taskId,
- toolManifestMap: effectiveManifestMap,
- toolResultMaxLength,
- topicId: ctx.topicId,
- userId: ctx.userId,
- });
+ const execution = await executeToolWithRetry(
+ () =>
+ toolExecutionService.executeTool(chatToolPayload, {
+ activeDeviceId: state.metadata?.activeDeviceId,
+ agentId: state.metadata?.agentId,
+ memoryToolPermission: agentConfig?.chatConfig?.memory?.toolPermission,
+ serverDB: ctx.serverDB,
+ taskId: state.metadata?.taskId,
+ toolManifestMap: effectiveManifestMap,
+ toolResultMaxLength,
+ topicId: ctx.topicId,
+ userId: ctx.userId,
+ }),
+ {
+ isInterrupted: () => isOperationInterrupted(ctx),
+ maxRetries: TOOL_MAX_RETRIES,
+ operationLogId,
+ toolName,
+ },
+ );
+ const executionResult = execution.result;
const executionTime = executionResult.executionTime;
const isSuccess = executionResult.success;
log(
@@ -1057,6 +1204,8 @@ export const createRuntimeExecutors = (
data: {
executionTime,
isSuccess,
+ attempts: execution.attempts,
+ maxAttempts: TOOL_MAX_RETRIES + 1,
payload,
phase: 'tool_execution',
result: executionResult,
@@ -1251,18 +1400,28 @@ export const createRuntimeExecutors = (
const batchAgentConfig = state.metadata?.agentConfig;
- const executionResult = await toolExecutionService.executeTool(chatToolPayload, {
- activeDeviceId: state.metadata?.activeDeviceId,
- agentId: state.metadata?.agentId,
- memoryToolPermission: batchAgentConfig?.chatConfig?.memory?.toolPermission,
- serverDB: ctx.serverDB,
- taskId: state.metadata?.taskId,
- toolManifestMap: batchManifestMap,
- toolResultMaxLength: batchAgentConfig?.chatConfig?.toolResultMaxLength,
- topicId: ctx.topicId,
- userId: ctx.userId,
- });
+ const execution = await executeToolWithRetry(
+ () =>
+ toolExecutionService.executeTool(chatToolPayload, {
+ activeDeviceId: state.metadata?.activeDeviceId,
+ agentId: state.metadata?.agentId,
+ memoryToolPermission: batchAgentConfig?.chatConfig?.memory?.toolPermission,
+ serverDB: ctx.serverDB,
+ taskId: state.metadata?.taskId,
+ toolManifestMap: batchManifestMap,
+ toolResultMaxLength: batchAgentConfig?.chatConfig?.toolResultMaxLength,
+ topicId: ctx.topicId,
+ userId: ctx.userId,
+ }),
+ {
+ isInterrupted: () => isOperationInterrupted(ctx),
+ maxRetries: TOOL_MAX_RETRIES,
+ operationLogId,
+ toolName,
+ },
+ );
+ const executionResult = execution.result;
const executionTime = executionResult.executionTime;
const isSuccess = executionResult.success;
log(
@@ -1274,6 +1433,8 @@ export const createRuntimeExecutors = (
data: {
executionTime,
isSuccess,
+ attempts: execution.attempts,
+ maxAttempts: TOOL_MAX_RETRIES + 1,
payload: { parentMessageId, toolCalling: chatToolPayload },
phase: 'tool_execution',
result: executionResult,
diff --git a/src/server/modules/AgentRuntime/StreamEventManager.ts b/src/server/modules/AgentRuntime/StreamEventManager.ts
index 48fed84ab93..aef379fc3b0 100644
--- a/src/server/modules/AgentRuntime/StreamEventManager.ts
+++ b/src/server/modules/AgentRuntime/StreamEventManager.ts
@@ -31,6 +31,7 @@ export interface StreamEvent {
| 'stream_start'
| 'stream_chunk'
| 'stream_end'
+ | 'stream_retry'
| 'tool_start'
| 'tool_end'
| 'step_start'
diff --git a/src/server/modules/AgentRuntime/__tests__/RuntimeExecutors.test.ts b/src/server/modules/AgentRuntime/__tests__/RuntimeExecutors.test.ts
index 700b18b38e5..d042abff503 100644
--- a/src/server/modules/AgentRuntime/__tests__/RuntimeExecutors.test.ts
+++ b/src/server/modules/AgentRuntime/__tests__/RuntimeExecutors.test.ts
@@ -83,6 +83,7 @@ describe('RuntimeExecutors', () => {
};
ctx = {
+ loadAgentState: vi.fn().mockResolvedValue(null),
messageModel: mockMessageModel,
operationId: 'op-123',
serverDB: {} as any, // Mock serverDB
@@ -1327,6 +1328,176 @@ describe('RuntimeExecutors', () => {
const payload = result.nextContext!.payload as { parentMessageId?: string };
expect(payload.parentMessageId).toBeUndefined();
});
+
+ it('should retry tool execution when kind is retry and eventually succeed', async () => {
+ mockToolExecutionService.executeTool
+ .mockResolvedValueOnce({
+ content: 'timeout-1',
+ error: { kind: 'retry', message: 'timeout' },
+ executionTime: 50,
+ state: {},
+ success: false,
+ })
+ .mockResolvedValueOnce({
+ content: 'timeout-2',
+ error: { kind: 'retry', message: 'timeout' },
+ executionTime: 50,
+ state: {},
+ success: false,
+ })
+ .mockResolvedValueOnce({
+ content: 'Tool result success',
+ error: null,
+ executionTime: 80,
+ state: {},
+ success: true,
+ });
+
+ const executors = createRuntimeExecutors(ctx);
+ const state = createMockState();
+
+ const instruction = {
+ payload: {
+ parentMessageId: 'assistant-msg-123',
+ toolCalling: {
+ apiName: 'search',
+ arguments: '{}',
+ id: 'tool-call-retry-1',
+ identifier: 'web-search',
+ type: 'default' as const,
+ },
+ },
+ type: 'call_tool' as const,
+ };
+
+ const result = await executors.call_tool!(instruction, state);
+
+ expect(mockToolExecutionService.executeTool).toHaveBeenCalledTimes(3);
+ expect((result.nextContext!.payload as any).isSuccess).toBe(true);
+ });
+
+ it('should stop retrying tool execution after operation is interrupted', async () => {
+ mockToolExecutionService.executeTool.mockResolvedValue({
+ content: 'timeout',
+ error: { kind: 'retry', message: 'timeout' },
+ executionTime: 50,
+ state: {},
+ success: false,
+ });
+ const loadAgentState = vi.fn().mockResolvedValue({ status: 'interrupted' });
+
+ const executors = createRuntimeExecutors({
+ ...ctx,
+ loadAgentState,
+ });
+ const state = createMockState();
+
+ const instruction = {
+ payload: {
+ parentMessageId: 'assistant-msg-123',
+ toolCalling: {
+ apiName: 'search',
+ arguments: '{}',
+ id: 'tool-call-retry-1',
+ identifier: 'web-search',
+ type: 'default' as const,
+ },
+ },
+ type: 'call_tool' as const,
+ };
+
+ const result = await executors.call_tool!(instruction, state);
+
+ expect(mockToolExecutionService.executeTool).toHaveBeenCalledTimes(1);
+ expect(loadAgentState).toHaveBeenCalledWith('op-123');
+ expect((result.nextContext!.payload as any).isSuccess).toBe(false);
+ });
+
+ it('should materialize failed tool result after retry exhaustion', async () => {
+ mockToolExecutionService.executeTool.mockResolvedValue({
+ content: 'still failing',
+ error: { kind: 'retry', message: 'timeout' },
+ executionTime: 50,
+ state: {},
+ success: false,
+ });
+
+ const executors = createRuntimeExecutors(ctx);
+ const state = createMockState();
+
+ const instruction = {
+ payload: {
+ parentMessageId: 'assistant-msg-123',
+ toolCalling: {
+ apiName: 'search',
+ arguments: '{}',
+ id: 'tool-call-retry-2',
+ identifier: 'web-search',
+ type: 'default' as const,
+ },
+ },
+ type: 'call_tool' as const,
+ };
+
+ const result = await executors.call_tool!(instruction, state);
+
+ expect(mockToolExecutionService.executeTool).toHaveBeenCalledTimes(3);
+ expect((result.nextContext!.payload as any).isSuccess).toBe(false);
+ });
+
+ it('should not retry for replan or stop kinds', async () => {
+ mockToolExecutionService.executeTool
+ .mockResolvedValueOnce({
+ content: 'invalid args',
+ error: { kind: 'replan', message: 'invalid schema' },
+ executionTime: 30,
+ state: {},
+ success: false,
+ })
+ .mockResolvedValueOnce({
+ content: 'permission denied',
+ error: { kind: 'stop', message: 'forbidden' },
+ executionTime: 30,
+ state: {},
+ success: false,
+ });
+
+ const executors = createRuntimeExecutors(ctx);
+ const state = createMockState();
+
+ const replanInstruction = {
+ payload: {
+ parentMessageId: 'assistant-msg-123',
+ toolCalling: {
+ apiName: 'search',
+ arguments: '{}',
+ id: 'tool-call-replan-1',
+ identifier: 'web-search',
+ type: 'default' as const,
+ },
+ },
+ type: 'call_tool' as const,
+ };
+
+ const stopInstruction = {
+ payload: {
+ parentMessageId: 'assistant-msg-123',
+ toolCalling: {
+ apiName: 'search',
+ arguments: '{}',
+ id: 'tool-call-stop-1',
+ identifier: 'web-search',
+ type: 'default' as const,
+ },
+ },
+ type: 'call_tool' as const,
+ };
+
+ await executors.call_tool!(replanInstruction, state);
+ await executors.call_tool!(stopInstruction, state);
+
+ expect(mockToolExecutionService.executeTool).toHaveBeenCalledTimes(2);
+ });
});
describe('call_tools_batch executor', () => {
@@ -1422,6 +1593,80 @@ describe('RuntimeExecutors', () => {
);
});
+ it('should apply retry policy per tool in batch mode', async () => {
+ const attemptsByTool: Record<string, number> = {};
+
+ mockToolExecutionService.executeTool.mockImplementation((payload: any) => {
+ const toolId = payload.id as string;
+ const nextAttempt = (attemptsByTool[toolId] || 0) + 1;
+ attemptsByTool[toolId] = nextAttempt;
+
+ if (toolId === 'tool-call-retry-batch' && nextAttempt < 3) {
+ return Promise.resolve({
+ content: 'timeout',
+ error: { kind: 'retry', message: 'timeout' },
+ executionTime: 40,
+ state: {},
+ success: false,
+ });
+ }
+
+ if (toolId === 'tool-call-stop-batch') {
+ return Promise.resolve({
+ content: 'permission denied',
+ error: { kind: 'stop', message: 'forbidden' },
+ executionTime: 40,
+ state: {},
+ success: false,
+ });
+ }
+
+ return Promise.resolve({
+ content: 'ok',
+ error: null,
+ executionTime: 60,
+ state: {},
+ success: true,
+ });
+ });
+
+ const executors = createRuntimeExecutors(ctx);
+ const state = createMockState();
+
+ const instruction = {
+ payload: {
+ parentMessageId: 'assistant-msg-123',
+ toolsCalling: [
+ {
+ apiName: 'search',
+ arguments: '{}',
+ id: 'tool-call-retry-batch',
+ identifier: 'web-search',
+ type: 'default' as const,
+ },
+ {
+ apiName: 'search',
+ arguments: '{}',
+ id: 'tool-call-stop-batch',
+ identifier: 'web-search',
+ type: 'default' as const,
+ },
+ ],
+ },
+ type: 'call_tools_batch' as const,
+ };
+
+ const result = await executors.call_tools_batch!(instruction, state);
+
+ expect(mockToolExecutionService.executeTool).toHaveBeenCalledTimes(4);
+ expect((result.nextContext!.payload as any).toolResults).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({ isSuccess: true }),
+ expect.objectContaining({ isSuccess: false }),
+ ]),
+ );
+ });
+
it('should refresh messages from database after batch execution', async () => {
const executors = createRuntimeExecutors(ctx);
const state = createMockState({ messages: [{ content: 'old', role: 'user' }] });
@@ -2431,7 +2676,9 @@ describe('RuntimeExecutors', () => {
vi.mocked(consumeStreamUntilDone).mockResolvedValue(undefined);
});
- it('should throw when LLM stream contains error events from provider', async () => {
+ it('should retry and eventually throw when LLM stream contains error events from provider', async () => {
+ vi.useFakeTimers();
+
// Import real implementations directly from source (bypassing the @lobechat/model-runtime mock)
const { consumeStreamUntilDone: realConsume } =
await import('../../../../../packages/model-runtime/src/utils/consumeStream');
@@ -2475,15 +2722,33 @@ describe('RuntimeExecutors', () => {
type: 'call_llm' as const,
};
- await expect(executors.call_llm!(instruction, state)).rejects.toThrow(/LLM stream error/);
+ try {
+ const resultPromise = executors.call_llm!(instruction, state);
+ const rejectionExpectation = expect(resultPromise).rejects.toThrow(/LLM stream error/);
- // Error event should be published to stream manager
- expect(mockStreamManager.publishStreamEvent).toHaveBeenCalledWith(
- 'op-123',
- expect.objectContaining({
- type: 'error',
- }),
- );
+ await Promise.resolve();
+ await vi.runAllTimersAsync();
+
+ await rejectionExpectation;
+
+ expect(mockChat).toHaveBeenCalledTimes(6);
+
+ const retryEvents = mockStreamManager.publishStreamEvent.mock.calls.filter(
+ ([, event]: [string, { type: string }]) => event.type === 'stream_retry',
+ );
+
+ expect(retryEvents).toHaveLength(5);
+
+ // Error event should be published to stream manager after retries are exhausted
+ expect(mockStreamManager.publishStreamEvent).toHaveBeenCalledWith(
+ 'op-123',
+ expect.objectContaining({
+ type: 'error',
+ }),
+ );
+ } finally {
+ vi.useRealTimers();
+ }
});
it('should throw and not produce llm_result when modelRuntime.chat rejects', async () => {
@@ -2520,5 +2785,216 @@ describe('RuntimeExecutors', () => {
}),
);
});
+
+ it('should retry llm execution, emit stream_retry, and commit only the successful attempt', async () => {
+ vi.useFakeTimers();
+
+ const toolCallPayload = [
+ {
+ function: { arguments: '{}', name: 'search' },
+ id: 'tool-call-1',
+ type: 'function',
+ },
+ ];
+
+ const mockChat = vi
+ .fn()
+ .mockImplementationOnce(async (_payload: any, options: any) => {
+ await options.callback.onGrounding?.({ query: 'draft' });
+ await options.callback.onToolsCalling?.({ toolsCalling: toolCallPayload });
+ throw new Error('network timeout');
+ })
+ .mockImplementationOnce(async (_payload: any, options: any) => {
+ await options.callback.onText?.('final');
+ await options.callback.onCompletion?.({
+ usage: { totalInputTokens: 1, totalOutputTokens: 2, totalTokens: 3 },
+ });
+ return new Response('done');
+ });
+
+ vi.mocked(initModelRuntimeFromDB).mockResolvedValue({ chat: mockChat } as any);
+
+ const executors = createRuntimeExecutors(ctx);
+ const state = createMockState();
+ const instruction = {
+ payload: {
+ messages: [{ content: 'Hello', role: 'user' }],
+ model: 'gpt-4',
+ parentMessageId: 'parent-msg-123',
+ provider: 'openai',
+ tools: [],
+ },
+ type: 'call_llm' as const,
+ };
+
+ try {
+ const resultPromise = executors.call_llm!(instruction, state);
+
+ await vi.runOnlyPendingTimersAsync();
+
+ const result = await resultPromise;
+
+ expect(mockChat).toHaveBeenCalledTimes(2);
+ expect(mockMessageModel.create).toHaveBeenCalledTimes(1);
+ expect(mockMessageModel.update).toHaveBeenCalledWith(
+ 'msg-123',
+ expect.objectContaining({ content: 'final' }),
+ );
+ expect(mockStreamManager.publishStreamEvent).toHaveBeenCalledWith(
+ 'op-123',
+ expect.objectContaining({
+ type: 'stream_retry',
+ data: { attempt: 2, delayMs: 1000, maxAttempts: 6 },
+ }),
+ );
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('should not retry llm execution after operation is interrupted', async () => {
+ const mockChat = vi.fn().mockRejectedValue(new Error('network timeout'));
+ vi.mocked(initModelRuntimeFromDB).mockResolvedValue({ chat: mockChat } as any);
+ const loadAgentState = vi.fn().mockResolvedValue({ status: 'interrupted' });
+
+ const executors = createRuntimeExecutors({
+ ...ctx,
+ loadAgentState,
+ });
+ const state = createMockState();
+ const instruction = {
+ payload: {
+ messages: [{ content: 'Hello', role: 'user' }],
+ model: 'gpt-4',
+ parentMessageId: 'parent-msg-123',
+ provider: 'openai',
+ tools: [],
+ },
+ type: 'call_llm' as const,
+ };
+
+ await expect(executors.call_llm!(instruction, state)).rejects.toThrow('network timeout');
+
+ expect(mockChat).toHaveBeenCalledTimes(1);
+ expect(loadAgentState).toHaveBeenCalledWith('op-123');
+ expect(
+ mockStreamManager.publishStreamEvent.mock.calls.some(
+ ([, event]: [string, { type: string }]) => event.type === 'stream_retry',
+ ),
+ ).toBe(false);
+ });
+
+ it('should not retry llm execution if operation is interrupted during backoff', async () => {
+ vi.useFakeTimers();
+
+ const mockChat = vi.fn().mockRejectedValue(new Error('network timeout'));
+ vi.mocked(initModelRuntimeFromDB).mockResolvedValue({ chat: mockChat } as any);
+ const loadAgentState = vi
+ .fn()
+ .mockResolvedValueOnce({ status: 'running' })
+ .mockResolvedValueOnce({ status: 'interrupted' });
+
+ const executors = createRuntimeExecutors({
+ ...ctx,
+ loadAgentState,
+ });
+ const state = createMockState();
+ const instruction = {
+ payload: {
+ messages: [{ content: 'Hello', role: 'user' }],
+ model: 'gpt-4',
+ parentMessageId: 'parent-msg-123',
+ provider: 'openai',
+ tools: [],
+ },
+ type: 'call_llm' as const,
+ };
+
+ try {
+ const resultPromise = executors.call_llm!(instruction, state);
+ const rejectionExpectation = expect(resultPromise).rejects.toThrow('network timeout');
+
+ await Promise.resolve();
+ await vi.runOnlyPendingTimersAsync();
+
+ await rejectionExpectation;
+
+ expect(mockChat).toHaveBeenCalledTimes(1);
+ expect(loadAgentState).toHaveBeenCalledTimes(2);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('should apply exponential backoff across multiple llm retries', async () => {
+ vi.useFakeTimers();
+
+ const mockChat = vi
+ .fn()
+ .mockRejectedValueOnce(new Error('network timeout-1'))
+ .mockRejectedValueOnce(new Error('network timeout-2'))
+ .mockRejectedValueOnce(new Error('network timeout-3'))
+ .mockImplementationOnce(async (_payload: any, options: any) => {
+ await options.callback.onText?.('final');
+ await options.callback.onCompletion?.({
+ usage: { totalInputTokens: 1, totalOutputTokens: 2, totalTokens: 3 },
+ });
+ return new Response('done');
+ });
+
+ vi.mocked(initModelRuntimeFromDB).mockResolvedValue({ chat: mockChat } as any);
+
+ const executors = createRuntimeExecutors(ctx);
+ const state = createMockState();
+ const instruction = {
+ payload: {
+ messages: [{ content: 'Hello', role: 'user' }],
+ model: 'gpt-4',
+ parentMessageId: 'parent-msg-123',
+ provider: 'openai',
+ tools: [],
+ },
+ type: 'call_llm' as const,
+ };
+
+ try {
+ const resultPromise = executors.call_llm!(instruction, state);
+
+ await vi.runOnlyPendingTimersAsync();
+ await Promise.resolve();
+ await vi.runOnlyPendingTimersAsync();
+ await Promise.resolve();
+ await vi.runOnlyPendingTimersAsync();
+
+ const result = await resultPromise;
+
+ expect(mockChat).toHaveBeenCalledTimes(4);
+ expect(result.nextContext?.phase).toBe('llm_result');
+
+ expect(mockStreamManager.publishStreamEvent).toHaveBeenCalledWith(
+ 'op-123',
+ expect.objectContaining({
+ type: 'stream_retry',
+ data: { attempt: 2, delayMs: 1000, maxAttempts: 6 },
+ }),
+ );
+ expect(mockStreamManager.publishStreamEvent).toHaveBeenCalledWith(
+ 'op-123',
+ expect.objectContaining({
+ type: 'stream_retry',
+ data: { attempt: 3, delayMs: 2000, maxAttempts: 6 },
+ }),
+ );
+ expect(mockStreamManager.publishStreamEvent).toHaveBeenCalledWith(
+ 'op-123',
+ expect.objectContaining({
+ type: 'stream_retry',
+ data: { attempt: 4, delayMs: 4000, maxAttempts: 6 },
+ }),
+ );
+ } finally {
+ vi.useRealTimers();
+ }
+ });
});
});
diff --git a/src/server/modules/AgentRuntime/__tests__/llmErrorClassification.test.ts b/src/server/modules/AgentRuntime/__tests__/llmErrorClassification.test.ts
new file mode 100644
index 00000000000..b2025e329b2
--- /dev/null
+++ b/src/server/modules/AgentRuntime/__tests__/llmErrorClassification.test.ts
@@ -0,0 +1,52 @@
+import { describe, expect, it } from 'vitest';
+
+import { classifyLLMError } from '../llmErrorClassification';
+
+describe('classifyLLMError', () => {
+ it('should classify rate limit errors as retry', () => {
+ expect(
+ classifyLLMError({ errorType: 'QuotaLimitReached', message: '429 rate limit' }).kind,
+ ).toBe('retry');
+ });
+
+ it('should classify invalid api key errors as stop', () => {
+ expect(
+ classifyLLMError({ errorType: 'InvalidProviderAPIKey', message: '401 unauthorized' }).kind,
+ ).toBe('stop');
+ });
+
+ it('should classify context window errors as stop', () => {
+ expect(
+ classifyLLMError({ errorType: 'ExceededContextWindow', message: 'maximum context length' })
+ .kind,
+ ).toBe('stop');
+ });
+
+ it('should classify ProviderBizError invalid_request errors as stop', () => {
+ expect(
+ classifyLLMError({
+ error: {
+ error: {
+ message: 'tools.0.custom.input_schema: Field required',
+ type: 'invalid_request_error',
+ },
+ errorType: 'ProviderBizError',
+ },
+ errorType: 'ProviderBizError',
+ }).kind,
+ ).toBe('stop');
+ });
+
+ it('should keep ProviderBizError rate limit errors as retry', () => {
+ expect(
+ classifyLLMError({
+ error: { message: '429 rate limit exceeded' },
+ errorType: 'ProviderBizError',
+ }).kind,
+ ).toBe('retry');
+ });
+
+ it('should default unknown errors to retry', () => {
+ expect(classifyLLMError(new Error('unexpected upstream issue')).kind).toBe('retry');
+ });
+});
diff --git a/src/server/modules/AgentRuntime/llmErrorClassification.ts b/src/server/modules/AgentRuntime/llmErrorClassification.ts
new file mode 100644
index 00000000000..88ffe718441
--- /dev/null
+++ b/src/server/modules/AgentRuntime/llmErrorClassification.ts
@@ -0,0 +1,210 @@
+type LLMErrorKind = 'retry' | 'stop';
+
+interface ClassifiedLLMError {
+ code?: string;
+ kind: LLMErrorKind;
+ message: string;
+}
+
+interface LLMErrorSignal {
+ code?: string;
+ errorType?: string;
+ message: string;
+ status?: number;
+}
+
+const RETRY_ERROR_TYPES = new Set([
+ 'AgentRuntimeError',
+ 'OllamaServiceUnavailable',
+ 'ProviderBizError',
+ 'QuotaLimitReached',
+ 'StreamChunkError',
+]);
+const STOP_ERROR_TYPES = new Set([
+ 'ExceededContextWindow',
+ 'InsufficientQuota',
+ 'InvalidBedrockCredentials',
+ 'InvalidGithubCopilotToken',
+ 'InvalidGithubToken',
+ 'InvalidOllamaArgs',
+ 'InvalidProviderAPIKey',
+ 'InvalidVertexCredentials',
+ 'ModelNotFound',
+ 'PermissionDenied',
+ 'Unauthorized',
+]);
+
+const RETRY_KEYWORDS = [
+ '429',
+ 'connection',
+ 'econn',
+ 'network',
+ 'rate limit',
+ 'timeout',
+ 'timed out',
+ 'temporarily unavailable',
+];
+const STOP_KEYWORDS = [
+ '403',
+ 'context window',
+ 'api key',
+ 'billing',
+ 'forbidden',
+ 'insufficient quota',
+ 'invalid request',
+ 'maximum context length',
+ 'model not found',
+ 'permission denied',
+ 'payload',
+ 'too many tokens',
+ 'unauthorized',
+];
+
+const hasAnyKeyword = (text: string, keywords: string[]) =>
+ keywords.some((keyword) => text.includes(keyword));
+
+const normalizeCode = (value?: string) => {
+ if (!value) return;
+
+ return value
+ .trim()
+ .toUpperCase()
+ .replaceAll(/[\s-]+/g, '_');
+};
+
+const normalizeErrorType = (value?: string) => value?.trim();
+
+const tryExtractStatus = (message: string) => {
+ const matches = message.match(/\b([45]\d{2})\b/);
+ if (!matches) return;
+
+ const status = Number(matches[1]);
+ return Number.isNaN(status) ? undefined : status;
+};
+
+const normalizeSignal = (error: unknown): LLMErrorSignal => {
+ if (typeof error === 'string') {
+ const message = error.toLowerCase();
+ return { message, status: tryExtractStatus(message) };
+ }
+
+ if (error instanceof Error) {
+ const raw = error as Error & {
+ code?: string;
+ errorType?: string;
+ status?: number;
+ statusCode?: number;
+ type?: string;
+ };
+ const message = (raw.message || raw.name || 'unknown error').toLowerCase();
+
+ return {
+ code: normalizeCode(raw.code),
+ errorType: normalizeErrorType(raw.errorType || raw.type),
+ message,
+ status:
+ typeof raw.status === 'number'
+ ? raw.status
+ : typeof raw.statusCode === 'number'
+ ? raw.statusCode
+ : tryExtractStatus(message),
+ };
+ }
+
+ if (error && typeof error === 'object') {
+ const raw = error as {
+ code?: string;
+ error?: {
+ code?: string;
+ error?: { code?: string; message?: string; status?: number; type?: string };
+ errorType?: string;
+ message?: string;
+ status?: number;
+ type?: string;
+ };
+ errorType?: string;
+ message?: string;
+ status?: number;
+ statusCode?: number;
+ type?: string;
+ };
+ const nested = raw.error;
+ const nestedError = nested?.error;
+ const message = (
+ raw.message ||
+ nested?.message ||
+ nestedError?.message ||
+ 'unknown error'
+ ).toLowerCase();
+
+ return {
+ code: normalizeCode(raw.code || nested?.code || nestedError?.code),
+ errorType: normalizeErrorType(
+ raw.errorType || raw.type || nested?.errorType || nested?.type || nestedError?.type,
+ ),
+ message,
+ status:
+ typeof raw.status === 'number'
+ ? raw.status
+ : typeof raw.statusCode === 'number'
+ ? raw.statusCode
+ : typeof nested?.status === 'number'
+ ? nested.status
+ : typeof nestedError?.status === 'number'
+ ? nestedError.status
+ : tryExtractStatus(message),
+ };
+ }
+
+ return { message: 'unknown error' };
+};
+
+const classifyKind = ({ code, errorType, message, status }: LLMErrorSignal): LLMErrorKind => {
+ if (errorType === 'ProviderBizError') {
+ if (status === 400 || status === 422) return 'stop';
+ if (message.includes('invalid_request_error') || message.includes('invalid request')) {
+ return 'stop';
+ }
+ if (
+ message.includes('input_schema') ||
+ message.includes('field required') ||
+ message.includes('missing required')
+ ) {
+ return 'stop';
+ }
+ }
+
+ if (errorType) {
+ if (STOP_ERROR_TYPES.has(errorType)) return 'stop';
+ if (RETRY_ERROR_TYPES.has(errorType)) return 'retry';
+ }
+
+ if (code) {
+ if (code.includes('UNAUTHORIZED') || code.includes('FORBIDDEN')) return 'stop';
+ if (code.includes('MODEL_NOT_FOUND')) return 'stop';
+ if (code.includes('RATE_LIMIT') || code.includes('TIMEOUT')) return 'retry';
+ }
+
+ if (status !== undefined) {
+ if (status === 401 || status === 403) return 'stop';
+ if (status === 400 || status === 404 || status === 409 || status === 422) return 'stop';
+ if (status === 408 || status === 425 || status === 429 || status >= 500) return 'retry';
+ }
+
+ if (hasAnyKeyword(message, STOP_KEYWORDS)) return 'stop';
+ if (hasAnyKeyword(message, RETRY_KEYWORDS)) return 'retry';
+
+ return 'retry';
+};
+
+export const classifyLLMError = (error: unknown): ClassifiedLLMError => {
+ const signal = normalizeSignal(error);
+
+ return {
+ code: signal.code || signal.errorType,
+ kind: classifyKind(signal),
+ message: signal.message,
+ };
+};
+
+export type { ClassifiedLLMError, LLMErrorKind };
diff --git a/src/server/services/agentRuntime/AgentRuntimeService.ts b/src/server/services/agentRuntime/AgentRuntimeService.ts
index 2065f5144e8..075e451a791 100644
--- a/src/server/services/agentRuntime/AgentRuntimeService.ts
+++ b/src/server/services/agentRuntime/AgentRuntimeService.ts
@@ -1503,6 +1503,7 @@ export class AgentRuntimeService {
discordContext: metadata?.discordContext,
userTimezone: metadata?.userTimezone,
evalContext: metadata?.evalContext,
+ loadAgentState: this.coordinator.loadAgentState.bind(this.coordinator),
messageModel: this.messageModel,
operationId,
serverDB: this.serverDB,
diff --git a/src/server/services/toolExecution/__tests__/errorClassification.test.ts b/src/server/services/toolExecution/__tests__/errorClassification.test.ts
new file mode 100644
index 00000000000..7672bbf9f2a
--- /dev/null
+++ b/src/server/services/toolExecution/__tests__/errorClassification.test.ts
@@ -0,0 +1,29 @@
+import { describe, expect, it } from 'vitest';
+
+import { classifyToolError } from '../errorClassification';
+
+describe('classifyToolError', () => {
+ it('should classify rate limit as retry', () => {
+ const result = classifyToolError({ code: 'TOO_MANY_REQUESTS', message: 'rate limit' });
+
+ expect(result.kind).toBe('retry');
+ });
+
+ it('should classify forbidden as stop', () => {
+ const result = classifyToolError({ message: 'request failed 403 forbidden' });
+
+ expect(result.kind).toBe('stop');
+ });
+
+ it('should classify invalid schema as replan', () => {
+ const result = classifyToolError(new Error('invalid schema for tool arguments'));
+
+ expect(result.kind).toBe('replan');
+ });
+
+ it('should default unknown errors to stop', () => {
+ const result = classifyToolError(new Error('unexpected issue'));
+
+ expect(result.kind).toBe('stop');
+ });
+});
diff --git a/src/server/services/toolExecution/errorClassification.ts b/src/server/services/toolExecution/errorClassification.ts
new file mode 100644
index 00000000000..c88cff0567d
--- /dev/null
+++ b/src/server/services/toolExecution/errorClassification.ts
@@ -0,0 +1,164 @@
+export type ToolErrorKind = 'replan' | 'retry' | 'stop';
+
+interface ToolErrorSignal {
+ code?: string;
+ message: string;
+ status?: number;
+}
+
+interface ClassifiedToolError {
+ code?: string;
+ kind: ToolErrorKind;
+ message: string;
+}
+
+const RETRY_CODES = new Set(['RATE_LIMITED', 'SERVICE_UNAVAILABLE', 'TOO_MANY_REQUESTS']);
+const REPLAN_CODES = new Set([
+ 'BAD_REQUEST',
+ 'INVALID_ARGUMENT',
+ 'MANIFEST_NOT_FOUND',
+ 'MCP_CONFIG_NOT_FOUND',
+ 'MCP_EXECUTION_ERROR',
+]);
+const STOP_CODES = new Set([
+ 'FORBIDDEN',
+ 'INSUFFICIENT_PERMISSIONS',
+ 'NOT_IMPLEMENTED',
+ 'PERMISSION_DENIED',
+ 'UNAUTHORIZED',
+]);
+
+const RETRY_KEYWORDS = [
+ 'timeout',
+ 'timed out',
+ 'too many requests',
+ 'temporarily unavailable',
+ 'service unavailable',
+ 'network',
+ 'socket hang up',
+ 'econnreset',
+ 'econnrefused',
+ 'enotfound',
+];
+const REPLAN_KEYWORDS = [
+ 'invalid',
+ 'malformed',
+ 'schema',
+ 'parse',
+ 'not found',
+ 'missing required',
+ 'manifest not found',
+ 'not implemented',
+];
+const STOP_KEYWORDS = [
+ 'unauthorized',
+ 'forbidden',
+ 'permission denied',
+ 'api key',
+ 'quota',
+ 'billing',
+ 'not configured',
+];
+
+const hasAnyKeyword = (text: string, keywords: string[]) =>
+ keywords.some((keyword) => text.includes(keyword));
+
+const normalizeCode = (value?: string): string | undefined => {
+ if (!value) return;
+
+ return value
+ .trim()
+ .toUpperCase()
+ .replaceAll(/[\s-]+/g, '_');
+};
+
+const tryExtractStatus = (message: string): number | undefined => {
+ const matches = message.match(/\b([45]\d{2})\b/);
+ if (!matches) return;
+
+ const status = Number(matches[1]);
+ return Number.isNaN(status) ? undefined : status;
+};
+
+const normalizeSignal = (error: unknown): ToolErrorSignal => {
+ if (typeof error === 'string') {
+ const message = error.toLowerCase();
+ return { message, status: tryExtractStatus(message) };
+ }
+
+ if (error instanceof Error) {
+ const message = (error.message || error.name || 'unknown error').toLowerCase();
+ const raw = error as Error & { code?: string; status?: number; statusCode?: number };
+ return {
+ code: normalizeCode(raw.code),
+ message,
+ status:
+ typeof raw.status === 'number'
+ ? raw.status
+ : typeof raw.statusCode === 'number'
+ ? raw.statusCode
+ : tryExtractStatus(message),
+ };
+ }
+
+ if (error && typeof error === 'object') {
+ const raw = error as {
+ code?: string;
+ error?: { code?: string; message?: string; status?: number; statusCode?: number };
+ message?: string;
+ status?: number;
+ statusCode?: number;
+ };
+
+ const nestedCode = raw.error?.code;
+ const nestedMessage = raw.error?.message;
+ const message = (raw.message || nestedMessage || 'unknown error').toLowerCase();
+
+ return {
+ code: normalizeCode(raw.code || nestedCode),
+ message,
+ status:
+ typeof raw.status === 'number'
+ ? raw.status
+ : typeof raw.statusCode === 'number'
+ ? raw.statusCode
+ : typeof raw.error?.status === 'number'
+ ? raw.error.status
+ : raw.error?.statusCode,
+ };
+ }
+
+ return { message: 'unknown error' };
+};
+
+const classifyKind = ({ code, message, status }: ToolErrorSignal): ToolErrorKind => {
+ if (code) {
+ if (STOP_CODES.has(code)) return 'stop';
+ if (REPLAN_CODES.has(code)) return 'replan';
+ if (RETRY_CODES.has(code)) return 'retry';
+ }
+
+ if (status !== undefined) {
+ if (status === 401 || status === 403) return 'stop';
+ if (status === 400 || status === 404 || status === 409 || status === 422) return 'replan';
+ if (status === 408 || status === 425 || status === 429 || status >= 500) return 'retry';
+ }
+
+ if (hasAnyKeyword(message, STOP_KEYWORDS)) return 'stop';
+ if (hasAnyKeyword(message, REPLAN_KEYWORDS)) return 'replan';
+ if (hasAnyKeyword(message, RETRY_KEYWORDS)) return 'retry';
+
+ // Unknown failures may happen after a side effect already succeeded, so only
+ // explicitly classified retryable errors should be replayed.
+ return 'stop';
+};
+
+export const classifyToolError = (error: unknown): ClassifiedToolError => {
+ const signal = normalizeSignal(error);
+
+ return {
+ code: signal.code,
+ kind: classifyKind(signal),
+ message: signal.message,
+ };
+};
diff --git a/src/server/services/toolExecution/index.ts b/src/server/services/toolExecution/index.ts
index 28086108a2d..275acf15ebf 100644
--- a/src/server/services/toolExecution/index.ts
+++ b/src/server/services/toolExecution/index.ts
@@ -13,6 +13,7 @@ import { DiscoverService } from '../discover';
import { type MCPService } from '../mcp';
import { type PluginGatewayService } from '../pluginGateway';
import { type BuiltinToolsExecutor } from './builtin';
+import { classifyToolError } from './errorClassification';
import {
type ToolExecutionContext,
type ToolExecutionResult,
@@ -27,6 +28,37 @@ interface ToolExecutionServiceDeps {
pluginGatewayService: PluginGatewayService;
}
+const normalizeExecutionError = (error: unknown, fallbackMessage: string) => {
+ const normalized = classifyToolError(error || fallbackMessage);
+ const message = fallbackMessage || normalized.message;
+
+ if (error && typeof error === 'object') {
+ if (error instanceof Error) {
+ return {
+ code: normalized.code,
+ kind: normalized.kind,
+ message: error.message || message,
+ name: error.name,
+ };
+ }
+
+ const plainError = error as Record<string, unknown>;
+
+ return {
+ ...plainError,
+ code: (plainError.code as string | undefined) || normalized.code,
+ kind: normalized.kind,
+ message: (plainError.message as string | undefined) || message,
+ };
+ }
+
+ if (typeof error === 'string') {
+ return { code: normalized.code, kind: normalized.kind, message: error };
+ }
+
+ return { code: normalized.code, kind: normalized.kind, message };
+};
+
export class ToolExecutionService {
private builtinToolsExecutor: BuiltinToolsExecutor;
private mcpService: MCPService;
@@ -91,6 +123,15 @@ export class ToolExecutionService {
);
}
+ if (!data.success) {
+ return {
+ ...data,
+ content: truncatedContent,
+ error: normalizeExecutionError(data.error, data.content),
+ executionTime,
+ };
+ }
+
return {
...data,
content: truncatedContent,
@@ -105,9 +146,7 @@ export class ToolExecutionService {
return {
content: truncateToolResult(errorMessage),
- error: {
- message: errorMessage,
- },
+ error: normalizeExecutionError(error, errorMessage),
executionTime,
success: false,
};
diff --git a/src/services/agentRuntime/type.ts b/src/services/agentRuntime/type.ts
index f4eb05ab4fb..fa9d4433a01 100644
--- a/src/services/agentRuntime/type.ts
+++ b/src/services/agentRuntime/type.ts
@@ -12,6 +12,7 @@ export interface StreamEvent {
| 'stream_start'
| 'stream_chunk'
| 'stream_end'
+ | 'stream_retry'
| 'step_start'
| 'step_complete'
| 'error'