π€― 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.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
β»οΈ refactor(agent-runtime): host resolve tools and retry helpers in package (#16862)
Arvin Xu2f269ddaa4a0
diff --git a/apps/server/src/modules/AgentRuntime/RuntimeExecutors.ts b/apps/server/src/modules/AgentRuntime/RuntimeExecutors.tsindex 150e6511cd5..5b59f2aa2ec 100644--- a/apps/server/src/modules/AgentRuntime/RuntimeExecutors.ts+++ b/apps/server/src/modules/AgentRuntime/RuntimeExecutors.ts@@ -3,6 +3,8 @@ import {finish as createFinishExecutor,type InstructionExecutor,requestHumanApprove as createRequestHumanApproveExecutor,+ resolveAbortedTools as createResolveAbortedToolsExecutor,+ resolveBlockedTools as createResolveBlockedToolsExecutor,} from '@lobechat/agent-runtime';import { buildHost } from './buildHost';@@ -12,7 +14,6 @@ import { callTool } from './executors/callTool';import { callToolsBatch } from './executors/callToolsBatch';import { compressContext } from './executors/compressContext';import { execSubAgent, execSubAgents } from './executors/execSubAgent';-import { resolveAbortedTools, resolveBlockedTools } from './executors/resolveTools';export { type RuntimeExecutorContext } from './context';@@ -34,7 +35,7 @@ export const createRuntimeExecutors = (// abstraction β the server now only registers adapters via buildHost.finish: createFinishExecutor(host),request_human_approve: createRequestHumanApproveExecutor(host),- resolve_aborted_tools: resolveAbortedTools(ctx),- resolve_blocked_tools: resolveBlockedTools(ctx),+ resolve_aborted_tools: createResolveAbortedToolsExecutor(host),+ resolve_blocked_tools: createResolveBlockedToolsExecutor(host),};};diff --git a/apps/server/src/modules/AgentRuntime/adapters/ServerMessageTransport.ts b/apps/server/src/modules/AgentRuntime/adapters/ServerMessageTransport.tsindex 1e9b2730958..5d2cc7f5453 100644--- a/apps/server/src/modules/AgentRuntime/adapters/ServerMessageTransport.ts+++ b/apps/server/src/modules/AgentRuntime/adapters/ServerMessageTransport.ts@@ -8,13 +8,13 @@ import type { CreateMessageParams, UIChatMessage, UpdateMessageParams } from '@limport { type MessageModel } from '@/database/models/message';+import {+ createConversationParentMissingError,+ isMidOperationReferenceMissingError,+} from '../messagePersistErrors';+/*** Server {@link MessageTransport} adapter β delegates to `MessageModel` (DB).- *- * NOTE: DB-error normalization (PG FK-violation β typed user-side error) is a- * DB-backed-transport concern and will be folded in here when the persisting- * executors (`resolve_*`, `call_tool`) migrate; today's callers keep their own- * catch blocks, so this stays a thin delegation.*/export class ServerMessageTransport implements MessageTransport {constructor(private readonly messageModel: MessageModel) {}@@ -23,8 +23,15 @@ export class ServerMessageTransport implements MessageTransport {return this.messageModel.create(params);}- createToolMessage(params: CreateMessageParams): Promise<RuntimeMessageRef> {- return this.messageModel.create(params);+ async createToolMessage(params: CreateMessageParams): Promise<RuntimeMessageRef> {+ try {+ return await this.messageModel.create(params);+ } catch (error) {+ if (typeof params.parentId === 'string' && isMidOperationReferenceMissingError(error)) {+ throw createConversationParentMissingError(params.parentId, error);+ }+ throw error;+ }}async deleteMessage(id: string): Promise<void> {diff --git a/apps/server/src/modules/AgentRuntime/adapters/ServerStreamSink.ts b/apps/server/src/modules/AgentRuntime/adapters/ServerStreamSink.tsindex 42513a91252..646b24c6460 100644--- a/apps/server/src/modules/AgentRuntime/adapters/ServerStreamSink.ts+++ b/apps/server/src/modules/AgentRuntime/adapters/ServerStreamSink.ts@@ -1,5 +1,11 @@-import type { RuntimeStreamEvent, StreamChunkInput, StreamSink } from '@lobechat/agent-runtime';+import type {+ RuntimeStreamEvent,+ StreamChunkInput,+ StreamErrorInput,+ StreamSink,+} from '@lobechat/agent-runtime';+import { formatErrorEventData } from '../formatErrorEventData';import { type IStreamEventManager } from '../types';/**@@ -19,6 +25,14 @@ export class ServerStreamSink implements StreamSink {await this.streamManager.publishStreamChunk(this.operationId, stepIndex, data as any);}+ async publishError({ error, phase, stepIndex }: StreamErrorInput): Promise<void> {+ await this.streamManager.publishStreamEvent(this.operationId, {+ data: formatErrorEventData(error, phase),+ stepIndex,+ type: 'error',+ });+ }+async publishEvent(event: RuntimeStreamEvent): Promise<void> {await this.streamManager.publishStreamEvent(this.operationId, {data: event.data,diff --git a/apps/server/src/modules/AgentRuntime/buildHost.ts b/apps/server/src/modules/AgentRuntime/buildHost.tsindex 9bed32b5cd8..583da756f98 100644--- a/apps/server/src/modules/AgentRuntime/buildHost.ts+++ b/apps/server/src/modules/AgentRuntime/buildHost.ts@@ -14,7 +14,8 @@ import { type RuntimeExecutorContext } from './context';* the host instead of the raw ctx.** Grows as more executors migrate (tools / llm / context / blob / lifecycle- * adapters get added here); today it covers the `finish` executor.+ * adapters get added here); today it covers the transport-backed lightweight+ * executors such as `finish`, `request_human_approve`, and `resolve_*`.*/export const buildHost = (ctx: RuntimeExecutorContext): AgentRuntimeHost => ({// Only present when the operation registered hooks β mirrors the priordiff --git a/apps/server/src/modules/AgentRuntime/executorHelpers.ts b/apps/server/src/modules/AgentRuntime/executorHelpers.tsindex 4fbf325fe28..524b4815ac6 100644--- a/apps/server/src/modules/AgentRuntime/executorHelpers.ts+++ b/apps/server/src/modules/AgentRuntime/executorHelpers.ts@@ -1,8 +1,6 @@import { type AgentState } from '@lobechat/agent-runtime';import { LobeActivatorIdentifier } from '@lobechat/builtin-tool-activator';-import { BRANDING_PROVIDER } from '@lobechat/business-const';import { type OperationToolSet } from '@lobechat/context-engine';-import { ModelEmptyError } from '@lobechat/model-runtime';import { type ToolType } from '@lobechat/observability-otel/modules/agent-runtime';import { type ChatToolPayload } from '@lobechat/types';import debug from 'debug';@@ -17,7 +15,6 @@ import {import { archiveToolResultIfNeeded } from '@/server/services/toolExecution/archiveToolResult';import { type RuntimeExecutorContext } from './context';-import { type LLMErrorKind } from './llmErrorClassification';export const log = debug('lobe-server:agent-runtime:streaming-executors');export const timing = debug('lobe-server:agent-runtime:timing');@@ -29,34 +26,9 @@ export const TOOL_PRICING: Record<string, number> = {};export 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;--/**- * Retry budget for empty completions, applied independently of- * `resolveLLMMaxRetries`. The branded provider gets 0 general retries because- * its own fallback chain already re-routes failed requests β but an- * HTTP-200-but-empty turn never triggered that chain, so it must still be- * re-issued. A small budget is enough: empty turns almost always self-heal on- * the first retry.- */-const EMPTY_COMPLETION_MAX_RETRIES = 2;export const GEN_AI_FUNCTION_TOOL_TYPE: ToolType = 'function';-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;-export const archiveRuntimeToolResult = async (result: ToolExecutionResultResponse,{@@ -174,8 +146,7 @@ export const buildServerVirtualSubAgentRunner = (title: description,topicId,})) as- | { error?: string; operationId?: string; success?: boolean; threadId?: string }- | undefined;+ { error?: string; operationId?: string; success?: boolean; threadId?: string } | undefined;// 3. If the child op never started, no completion bridge will fire β parking// the parent on it would hang forever. Drop the placeholder and signal@@ -367,32 +338,6 @@ export const buildServerAgentMemberRunner = (};};-export const shouldRetryLLM = (kind: LLMErrorKind, attempt: number, maxRetries: number) =>- kind === 'retry' && attempt <= maxRetries;--const resolveLLMMaxRetries = (provider: string) =>- // The branded provider already routes through its own fallback chain. Retrying- // again here multiplies the same failed routed request across every channel.- provider === BRANDING_PROVIDER ? 0 : LLM_MAX_RETRIES;--/**- * Retry budget for a *specific* failed attempt. This is provider policy +- * error-type override, so it can only be resolved once the error exists (in the- * catch) β unlike {@link resolveLLMMaxRetries}, which runs before the request.- *- * Empty completions bypass the per-provider policy: the branded- * provider's 0-retry rule exists to avoid re-routing its own already-failed- * requests, but an HTTP-200-but-empty turn never hit that fallback chain, so it- * must still be re-issued. Folding this into `resolveLLMMaxRetries` would wrongly- * grant the floor to *every* branded error.- */-export const resolveLLMRetryBudget = (provider: string, error: unknown) =>- error instanceof ModelEmptyError ? EMPTY_COMPLETION_MAX_RETRIES : resolveLLMMaxRetries(provider);--/** Loop bound β must accommodate the largest budget any error kind can request. */-export const resolveLLMMaxAttempts = (provider: string) =>- Math.max(resolveLLMMaxRetries(provider), EMPTY_COMPLETION_MAX_RETRIES) + 1;-export const resolveRuntimeHistoryCount = (historyCount?: number) => {if (historyCount === undefined) return undefined;@@ -405,9 +350,6 @@ export const resolveRuntimeHistoryCount = (historyCount?: number) => {export const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));-export const getLLMRetryDelayMs = (attempt: number) =>- Math.min(LLM_RETRY_BASE_DELAY_MS * 2 ** Math.max(attempt - 1, 0), LLM_RETRY_MAX_DELAY_MS);-export const isOperationInterrupted = async (ctx: RuntimeExecutorContext) => {if (!ctx.loadAgentState) return false;@@ -420,46 +362,6 @@ export const isOperationInterrupted = async (ctx: RuntimeExecutorContext) => {}};-export 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');-};-export const buildToolDiscoveryConfig = (operationToolSet: OperationToolSet,enabledToolIds: string[],diff --git a/apps/server/src/modules/AgentRuntime/executors/callLlm.ts b/apps/server/src/modules/AgentRuntime/executors/callLlm.tsindex 50babf75f8c..13004955972 100644--- a/apps/server/src/modules/AgentRuntime/executors/callLlm.ts+++ b/apps/server/src/modules/AgentRuntime/executors/callLlm.ts@@ -3,7 +3,11 @@ import {type AgentInstruction,type CallLLMPayload,type GeneralAgentCallLLMResultPayload,+ getLLMRetryDelayMs,type InstructionExecutor,+ resolveLLMMaxAttempts,+ resolveLLMRetryBudget,+ shouldRetryLLM,stripAssistantReasoningForReplay,UsageCounter,} from '@lobechat/agent-runtime';@@ -85,13 +89,9 @@ import { type RuntimeExecutorContext } from '../context';import {buildPostProcessUrl,buildToolDiscoveryConfig,- getLLMRetryDelayMs,isOperationInterrupted,log,- resolveLLMMaxAttempts,- resolveLLMRetryBudget,resolveRuntimeHistoryCount,- shouldRetryLLM,sleep,timing,} from '../executorHelpers';@@ -101,6 +101,11 @@ import { createConversationParentMissingError } from '../messagePersistErrors';import { VISIBLE_OUTPUT_END_PUBLISHED_STEP_INDEX_METADATA_KEY } from '../visibleOutputEnd';import { resolveRunActiveDeviceId } from './resolveRunActiveDeviceId';+const SERVER_LLM_RETRY_POLICY = {+ isEmptyCompletionError: (error: unknown) => error instanceof ModelEmptyError,+ noRetryProviders: [BRANDING_PROVIDER],+};+export const callLlm =(ctx: RuntimeExecutorContext): InstructionExecutor =>async (instruction, state) => {@@ -1075,7 +1080,7 @@ export const callLlm =});};- const maxAttempts = resolveLLMMaxAttempts(provider);+ const maxAttempts = resolveLLMMaxAttempts(provider, SERVER_LLM_RETRY_POLICY);// OTel chat span β wraps all retry attempts; TTFT recorded on the first// text/reasoning chunk regardless of which attempt produced it (the@@ -1689,7 +1694,7 @@ export const callLlm =const classified = classifyLLMError(error);const interrupted = await isOperationInterrupted(ctx);- const retryBudget = resolveLLMRetryBudget(provider, error);+ const retryBudget = resolveLLMRetryBudget(provider, error, SERVER_LLM_RETRY_POLICY);if (!interrupted && shouldRetryLLM(classified.kind, attempt, retryBudget)) {const delayMs = getLLMRetryDelayMs(attempt);diff --git a/apps/server/src/modules/AgentRuntime/executors/callTool.ts b/apps/server/src/modules/AgentRuntime/executors/callTool.tsindex 4d1b629a00f..47a7ec4043f 100644--- a/apps/server/src/modules/AgentRuntime/executors/callTool.ts+++ b/apps/server/src/modules/AgentRuntime/executors/callTool.ts@@ -1,6 +1,7 @@import {type AgentEvent,type AgentInstruction,+ executeToolWithRetry,extractActivatedSkillsFromMessages,type InstructionExecutor,UsageCounter,@@ -29,7 +30,6 @@ import {archiveRuntimeToolResult,buildServerAgentMemberRunner,buildServerVirtualSubAgentRunner,- executeToolWithRetry,GEN_AI_FUNCTION_TOOL_TYPE,isOperationInterrupted,log,@@ -321,8 +321,15 @@ export const callTool ={isInterrupted: () => isOperationInterrupted(ctx),maxRetries: TOOL_MAX_RETRIES,- operationLogId,- toolName,+ onRetry: ({ attempt, kind, maxAttempts }) =>+ log(+ '[%s] Tool %s failed with kind=%s (attempt %d/%d), retrying ...',+ operationLogId,+ toolName,+ kind,+ attempt,+ maxAttempts,+ ),},);}diff --git a/apps/server/src/modules/AgentRuntime/executors/callToolsBatch.ts b/apps/server/src/modules/AgentRuntime/executors/callToolsBatch.tsindex 8ccda3fdb80..82e5d3de1b1 100644--- a/apps/server/src/modules/AgentRuntime/executors/callToolsBatch.ts+++ b/apps/server/src/modules/AgentRuntime/executors/callToolsBatch.ts@@ -1,6 +1,7 @@import {type AgentEvent,type AgentInstruction,+ executeToolWithRetry,extractActivatedSkillsFromMessages,type InstructionExecutor,UsageCounter,@@ -30,7 +31,6 @@ import {buildPostProcessUrl,buildServerAgentMemberRunner,buildServerVirtualSubAgentRunner,- executeToolWithRetry,GEN_AI_FUNCTION_TOOL_TYPE,isOperationInterrupted,log,@@ -321,8 +321,15 @@ export const callToolsBatch ={isInterrupted: () => isOperationInterrupted(ctx),maxRetries: TOOL_MAX_RETRIES,- operationLogId,- toolName,+ onRetry: ({ attempt, kind, maxAttempts }) =>+ log(+ '[%s] Tool %s failed with kind=%s (attempt %d/%d), retrying ...',+ operationLogId,+ toolName,+ kind,+ attempt,+ maxAttempts,+ ),},);}diff --git a/apps/server/src/modules/AgentRuntime/executors/resolveTools.ts b/apps/server/src/modules/AgentRuntime/executors/resolveTools.tsdeleted file mode 100644index 7ad3a10fb60..00000000000--- a/apps/server/src/modules/AgentRuntime/executors/resolveTools.ts+++ /dev/null@@ -1,222 +0,0 @@-import {- type AgentEvent,- type AgentInstruction,- type InstructionExecutor,-} from '@lobechat/agent-runtime';--import { type ToolExecutionResultResponse } from '@/server/services/toolExecution';--import { type RuntimeExecutorContext } from '../context';-import { log } from '../executorHelpers';-import { formatErrorEventData } from '../formatErrorEventData';-import {- createConversationParentMissingError,- isMidOperationReferenceMissingError,-} from '../messagePersistErrors';--export const resolveBlockedTools =- (ctx: RuntimeExecutorContext): InstructionExecutor =>- async (instruction, state) => {- const { payload } = instruction as Extract<AgentInstruction, { type: 'resolve_blocked_tools' }>;- const { parentMessageId, toolsCalling } = payload;- const { operationId, stepIndex, streamManager } = ctx;- const events: AgentEvent[] = [];- const newState = structuredClone(state);- const toolResults: Array<{ data: ToolExecutionResultResponse; toolCallId: string }> = [];- const toolMessageIds: string[] = [];-- log('[%s:%d] Resolving %d blocked tools', operationId, stepIndex, toolsCalling.length);-- for (const toolPayload of toolsCalling) {- const result: ToolExecutionResultResponse = {- content: 'Blocked by security/privacy.',- error: 'blocked_by_security_privacy',- executionTime: 0,- state: { type: 'blocked' },- success: false,- };-- await streamManager.publishStreamEvent(operationId, {- data: {- executionTime: 0,- isSuccess: false,- attempts: 0,- maxAttempts: 0,- payload: { parentMessageId, toolCalling: toolPayload },- phase: 'tool_execution',- result,- },- stepIndex,- type: 'tool_end',- });-- try {- const toolMessage = await ctx.messageModel.create({- agentId: state.metadata!.agentId!,- content: result.content,- groupId: state.metadata?.groupId ?? undefined,- metadata: { toolExecutionTimeMs: 0 },- parentId: parentMessageId,- plugin: toolPayload as any,- pluginError: result.error,- pluginIntervention: { rejectedReason: result.error, status: 'rejected' },- pluginState: result.state,- role: 'tool',- threadId: state.metadata?.threadId,- tool_call_id: toolPayload.id,- topicId: state.metadata?.topicId,- });- toolMessageIds.push(toolMessage.id);- } catch (error) {- console.error('[resolve_blocked_tools] Failed to create blocked tool message: %O', error);- const fatal = isMidOperationReferenceMissingError(error)- ? createConversationParentMissingError(parentMessageId, error)- : error instanceof Error- ? error- : new Error(String(error));- await streamManager.publishStreamEvent(operationId, {- data: formatErrorEventData(fatal, 'tool_message_persist'),- stepIndex,- type: 'error',- });- throw fatal;- }-- newState.messages.push({- content: result.content,- role: 'tool',- tool_call_id: toolPayload.id,- });- events.push({ id: toolPayload.id, result, type: 'tool_result' });- toolResults.push({ data: result, toolCallId: toolPayload.id });- }-- newState.lastModified = new Date().toISOString();-- return {- events,- newState,- nextContext: {- payload: {- parentMessageId: toolMessageIds.at(-1) ?? parentMessageId,- toolCount: toolsCalling.length,- toolResults,- },- phase: 'tools_batch_result',- session: {- eventCount: events.length,- messageCount: newState.messages.length,- sessionId: operationId,- status: 'running',- stepCount: state.stepCount + 1,- },- },- };- };--export const resolveAbortedTools =- (ctx: RuntimeExecutorContext): InstructionExecutor =>- async (instruction, state) => {- const { payload } = instruction as Extract<AgentInstruction, { type: 'resolve_aborted_tools' }>;- const { parentMessageId, toolsCalling } = payload;- const { operationId, stepIndex, streamManager } = ctx;- const events: AgentEvent[] = [];-- log('[%s:%d] Resolving %d aborted tools', operationId, stepIndex, toolsCalling.length);-- // Publish tool cancellation event- await streamManager.publishStreamEvent(operationId, {- data: {- parentMessageId,- phase: 'tools_aborted',- toolsCalling,- },- stepIndex,- type: 'step_start',- });-- const newState = structuredClone(state);-- // Create tool message for each canceled tool call- for (const toolPayload of toolsCalling) {- const toolName = `${toolPayload.identifier}/${toolPayload.apiName}`;- log('[%s:%d] Creating aborted tool message for %s', operationId, stepIndex, toolName);-- try {- const toolMessage = await ctx.messageModel.create({- agentId: state.metadata!.agentId!,- content: 'Tool execution was aborted by user.',- groupId: state.metadata?.groupId ?? undefined,- parentId: parentMessageId,- plugin: toolPayload as any,- pluginIntervention: { status: 'aborted' },- role: 'tool',- threadId: state.metadata?.threadId,- tool_call_id: toolPayload.id,- topicId: state.metadata?.topicId,- });-- log(- '[%s:%d] Created aborted tool message: %s for %s',- operationId,- stepIndex,- toolMessage.id,- toolName,- );-- // Update state messages- newState.messages.push({- content: 'Tool execution was aborted by user.',- role: 'tool',- tool_call_id: toolPayload.id,- });- } catch (error) {- console.error(- '[resolve_aborted_tools] Failed to create aborted tool message for %s: %O',- toolName,- error,- );- // Normalize BEFORE publishing so clients surface the typed business- // error instead of the raw driver text (see review).- const fatal = isMidOperationReferenceMissingError(error)- ? createConversationParentMissingError(parentMessageId, error)- : error instanceof Error- ? error- : new Error(String(error));- await streamManager.publishStreamEvent(operationId, {- data: formatErrorEventData(fatal, 'tool_message_persist'),- stepIndex,- type: 'error',- });- throw fatal;- }- }-- log('[%s:%d] All aborted tool messages created', operationId, stepIndex);-- // Mark status as complete- newState.lastModified = new Date().toISOString();- newState.status = 'done';-- // Publish completion event. finalState stripped centrally inside- // `publishStreamEvent`.- await streamManager.publishStreamEvent(operationId, {- data: {- finalState: newState,- phase: 'execution_complete',- reason: 'user_aborted',- reasonDetail: 'User aborted operation with pending tool calls',- },- stepIndex,- type: 'step_complete',- });-- events.push({- finalState: newState,- reason: 'user_aborted',- reasonDetail: 'User aborted operation with pending tool calls',- type: 'done',- });-- return { events, newState };- };diff --git a/packages/agent-runtime/src/executors/index.ts b/packages/agent-runtime/src/executors/index.tsindex 9ec04f6b4d5..77732cf0ffb 100644--- a/packages/agent-runtime/src/executors/index.ts+++ b/packages/agent-runtime/src/executors/index.ts@@ -1,2 +1,3 @@export * from './finish';export * from './humanApprove';+export * from './resolveTools';diff --git a/packages/agent-runtime/src/executors/resolveTools.test.ts b/packages/agent-runtime/src/executors/resolveTools.test.tsnew file mode 100644index 00000000000..48961627f18--- /dev/null+++ b/packages/agent-runtime/src/executors/resolveTools.test.ts@@ -0,0 +1,194 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++import type { AgentRuntimeHost } from '../transport';+import type { AgentInstruction, AgentState } from '../types';+import { resolveAbortedTools, resolveBlockedTools } from './resolveTools';++const createState = (overrides?: Partial<AgentState>): AgentState => ({+ cost: {+ calculatedAt: '2026-07-07T00:00:00.000Z',+ currency: 'USD',+ llm: { byModel: [], currency: 'USD', total: 0 },+ tools: { byTool: [], currency: 'USD', total: 0 },+ total: 0,+ },+ createdAt: '2026-07-07T00:00:00.000Z',+ lastModified: '2026-07-07T00:00:00.000Z',+ maxSteps: 100,+ messages: [],+ metadata: {+ agentId: 'agent-1',+ threadId: 'thread-1',+ topicId: 'topic-1',+ },+ operationId: 'op-1',+ status: 'running',+ stepCount: 0,+ toolManifestMap: {},+ usage: {+ humanInteraction: {+ approvalRequests: 0,+ promptRequests: 0,+ selectRequests: 0,+ totalWaitingTimeMs: 0,+ },+ llm: { apiCalls: 0, processingTimeMs: 0, tokens: { input: 0, output: 0, total: 0 } },+ tools: { byTool: [], totalCalls: 0, totalTimeMs: 0 },+ },+ ...overrides,+});++const createToolCall = (id = 'tool-call-1') => ({+ apiName: 'search',+ arguments: '{"query":"test"}',+ id,+ identifier: 'web-search',+ type: 'default' as const,+});++describe('resolveTools executors', () => {+ let createToolMessage: ReturnType<typeof vi.fn>;+ let publishError: ReturnType<typeof vi.fn>;+ let publishEvent: ReturnType<typeof vi.fn>;+ let host: AgentRuntimeHost;++ beforeEach(() => {+ createToolMessage = vi.fn().mockResolvedValue({ id: 'tool-msg-1' });+ publishError = vi.fn().mockResolvedValue(undefined);+ publishEvent = vi.fn().mockResolvedValue(undefined);++ host = {+ operation: {+ operationId: 'op-1',+ stepIndex: 2,+ },+ transports: {+ messages: {+ createAssistantMessage: vi.fn(),+ createToolMessage,+ deleteMessage: vi.fn(),+ findById: vi.fn(),+ query: vi.fn(),+ update: vi.fn(),+ updatePluginState: vi.fn(),+ updateToolMessage: vi.fn(),+ },+ stream: {+ publishChunk: vi.fn(),+ publishError,+ publishEvent,+ },+ },+ } as unknown as AgentRuntimeHost;+ });++ it('persists blocked tools as rejected tool messages and continues', async () => {+ const instruction: Extract<AgentInstruction, { type: 'resolve_blocked_tools' }> = {+ payload: {+ parentMessageId: 'assistant-msg-1',+ toolsCalling: [createToolCall()],+ },+ type: 'resolve_blocked_tools',+ };++ const result = await resolveBlockedTools(host)(instruction, createState());++ expect(createToolMessage).toHaveBeenCalledWith(+ expect.objectContaining({+ content: 'Blocked by security/privacy.',+ parentId: 'assistant-msg-1',+ pluginError: 'blocked_by_security_privacy',+ pluginIntervention: {+ rejectedReason: 'blocked_by_security_privacy',+ status: 'rejected',+ },+ role: 'tool',+ tool_call_id: 'tool-call-1',+ }),+ );+ expect(publishEvent).toHaveBeenCalledWith(+ expect.objectContaining({+ data: expect.objectContaining({+ isSuccess: false,+ phase: 'tool_execution',+ }),+ stepIndex: 2,+ type: 'tool_end',+ }),+ );+ expect(result.events).toContainEqual(+ expect.objectContaining({ id: 'tool-call-1', type: 'tool_result' }),+ );+ expect(result.nextContext?.phase).toBe('tools_batch_result');+ expect(result.nextContext?.payload).toMatchObject({+ parentMessageId: 'tool-msg-1',+ toolCount: 1,+ });+ });++ it('persists aborted tools and completes the operation as user_aborted', async () => {+ const instruction: Extract<AgentInstruction, { type: 'resolve_aborted_tools' }> = {+ payload: {+ parentMessageId: 'assistant-msg-1',+ toolsCalling: [createToolCall('tool-call-1'), createToolCall('tool-call-2')],+ },+ type: 'resolve_aborted_tools',+ };++ const result = await resolveAbortedTools(host)(instruction, createState());++ expect(createToolMessage).toHaveBeenCalledTimes(2);+ expect(createToolMessage).toHaveBeenCalledWith(+ expect.objectContaining({+ content: 'Tool execution was aborted by user.',+ parentId: 'assistant-msg-1',+ pluginIntervention: { status: 'aborted' },+ role: 'tool',+ tool_call_id: 'tool-call-1',+ }),+ );+ expect(result.newState.status).toBe('done');+ expect(result.newState.messages).toHaveLength(2);+ expect(result.events).toContainEqual(+ expect.objectContaining({+ reason: 'user_aborted',+ reasonDetail: 'User aborted operation with pending tool calls',+ type: 'done',+ }),+ );+ expect(publishEvent).toHaveBeenCalledWith(+ expect.objectContaining({+ data: expect.objectContaining({ phase: 'tools_aborted' }),+ type: 'step_start',+ }),+ );+ expect(publishEvent).toHaveBeenCalledWith(+ expect.objectContaining({+ data: expect.objectContaining({ phase: 'execution_complete', reason: 'user_aborted' }),+ type: 'step_complete',+ }),+ );+ });++ it('publishes and rethrows persist errors', async () => {+ const error = new Error('database went away');+ createToolMessage.mockRejectedValueOnce(error);++ const instruction: Extract<AgentInstruction, { type: 'resolve_blocked_tools' }> = {+ payload: {+ parentMessageId: 'assistant-msg-1',+ toolsCalling: [createToolCall()],+ },+ type: 'resolve_blocked_tools',+ };++ await expect(resolveBlockedTools(host)(instruction, createState())).rejects.toThrow(+ 'database went away',+ );+ expect(publishError).toHaveBeenCalledWith({+ error,+ phase: 'tool_message_persist',+ stepIndex: 2,+ });+ });+});diff --git a/packages/agent-runtime/src/executors/resolveTools.ts b/packages/agent-runtime/src/executors/resolveTools.tsnew file mode 100644index 00000000000..39bf6d35d6a--- /dev/null+++ b/packages/agent-runtime/src/executors/resolveTools.ts@@ -0,0 +1,236 @@+import type { AgentRuntimeHost, ToolRunResult } from '../transport';+import type {+ AgentEvent,+ AgentInstruction,+ AgentRuntimeContext,+ AgentState,+ InstructionExecutor,+} from '../types';++const BLOCKED_TOOL_CONTENT = 'Blocked by security/privacy.';+const BLOCKED_TOOL_ERROR = 'blocked_by_security_privacy';+const ABORTED_TOOL_CONTENT = 'Tool execution was aborted by user.';+const USER_ABORTED_REASON = 'user_aborted';+const USER_ABORTED_REASON_DETAIL = 'User aborted operation with pending tool calls';+const TOOL_MESSAGE_PERSIST_PHASE = 'tool_message_persist';++type RuntimeSessionWithEventCount = NonNullable<AgentRuntimeContext['session']> & {+ eventCount?: number;+};++const getErrorType = (error: unknown): string | undefined => {+ if (!error || typeof error !== 'object') return;++ const value = (error as { errorType?: unknown; name?: unknown; type?: unknown }).errorType;+ if (typeof value === 'string' || typeof value === 'number') return String(value);++ const type = (error as { type?: unknown }).type;+ if (typeof type === 'string' || typeof type === 'number') return String(type);++ const name = error instanceof Error ? error.name : undefined;+ return name || undefined;+};++const getErrorMessage = (error: unknown): string => {+ if (error instanceof Error && error.message) return error.message;+ if (typeof error === 'string' && error) return error;+ if (error && typeof error === 'object') {+ const message = (error as { message?: unknown }).message;+ if (typeof message === 'string' && message) return message;+ }+ return 'Unknown error';+};++const publishPersistError = async (host: AgentRuntimeHost, error: unknown) => {+ const { stepIndex } = host.operation;++ if (host.transports.stream.publishError) {+ await host.transports.stream.publishError({+ error,+ phase: TOOL_MESSAGE_PERSIST_PHASE,+ stepIndex,+ });+ return;+ }++ await host.transports.stream.publishEvent({+ data: {+ error: getErrorMessage(error),+ errorType: getErrorType(error),+ phase: TOOL_MESSAGE_PERSIST_PHASE,+ },+ stepIndex,+ type: 'error',+ });+};++const createSession = (state: AgentState, operationId: string): RuntimeSessionWithEventCount => ({+ messageCount: state.messages.length,+ sessionId: operationId,+ status: state.status,+ stepCount: state.stepCount + 1,+});++/**+ * `resolve_blocked_tools` executor β turns policy-blocked tool calls into+ * persisted rejected tool messages so the runtime can continue planning.+ */+export const resolveBlockedTools =+ (host: AgentRuntimeHost): InstructionExecutor =>+ async (instruction, state) => {+ const { payload } = instruction as Extract<AgentInstruction, { type: 'resolve_blocked_tools' }>;+ const { operation, transports } = host;+ const events: AgentEvent[] = [];+ const newState = structuredClone(state);+ const toolResults: Array<{ data: ToolRunResult; toolCallId: string }> = [];+ const toolMessageIds: string[] = [];++ for (const toolPayload of payload.toolsCalling) {+ const result: ToolRunResult = {+ content: BLOCKED_TOOL_CONTENT,+ error: BLOCKED_TOOL_ERROR,+ executionTime: 0,+ state: { type: 'blocked' },+ success: false,+ };++ await transports.stream.publishEvent({+ data: {+ executionTime: 0,+ isSuccess: false,+ attempts: 0,+ maxAttempts: 0,+ payload: { parentMessageId: payload.parentMessageId, toolCalling: toolPayload },+ phase: 'tool_execution',+ result,+ },+ stepIndex: operation.stepIndex,+ type: 'tool_end',+ });++ try {+ const toolMessage = await transports.messages.createToolMessage({+ agentId: state.metadata!.agentId!,+ content: result.content,+ groupId: state.metadata?.groupId ?? undefined,+ metadata: { toolExecutionTimeMs: 0 },+ parentId: payload.parentMessageId,+ plugin: toolPayload as any,+ pluginError: result.error,+ pluginIntervention: {+ rejectedReason: BLOCKED_TOOL_ERROR,+ status: 'rejected',+ },+ pluginState: result.state,+ role: 'tool',+ threadId: state.metadata?.threadId,+ tool_call_id: toolPayload.id,+ topicId: state.metadata?.topicId,+ });+ toolMessageIds.push(toolMessage.id);+ } catch (error) {+ await publishPersistError(host, error);+ throw error;+ }++ newState.messages.push({+ content: result.content,+ role: 'tool',+ tool_call_id: toolPayload.id,+ });+ events.push({ id: toolPayload.id, result, type: 'tool_result' });+ toolResults.push({ data: result, toolCallId: toolPayload.id });+ }++ newState.lastModified = new Date().toISOString();++ return {+ events,+ newState,+ nextContext: {+ payload: {+ parentMessageId: toolMessageIds.at(-1) ?? payload.parentMessageId,+ toolCount: payload.toolsCalling.length,+ toolResults,+ },+ phase: 'tools_batch_result',+ session: {+ ...createSession(newState, operation.operationId),+ eventCount: events.length,+ },+ },+ };+ };++/**+ * `resolve_aborted_tools` executor β persists cancelled tool calls and marks+ * the operation as completed by user abort.+ */+export const resolveAbortedTools =+ (host: AgentRuntimeHost): InstructionExecutor =>+ async (instruction, state) => {+ const { payload } = instruction as Extract<AgentInstruction, { type: 'resolve_aborted_tools' }>;+ const { operation, transports } = host;+ const events: AgentEvent[] = [];++ await transports.stream.publishEvent({+ data: {+ parentMessageId: payload.parentMessageId,+ phase: 'tools_aborted',+ toolsCalling: payload.toolsCalling,+ },+ stepIndex: operation.stepIndex,+ type: 'step_start',+ });++ const newState = structuredClone(state);++ for (const toolPayload of payload.toolsCalling) {+ try {+ await transports.messages.createToolMessage({+ agentId: state.metadata!.agentId!,+ content: ABORTED_TOOL_CONTENT,+ groupId: state.metadata?.groupId ?? undefined,+ parentId: payload.parentMessageId,+ plugin: toolPayload as any,+ pluginIntervention: { status: 'aborted' },+ role: 'tool',+ threadId: state.metadata?.threadId,+ tool_call_id: toolPayload.id,+ topicId: state.metadata?.topicId,+ });+ } catch (error) {+ await publishPersistError(host, error);+ throw error;+ }++ newState.messages.push({+ content: ABORTED_TOOL_CONTENT,+ role: 'tool',+ tool_call_id: toolPayload.id,+ });+ }++ newState.lastModified = new Date().toISOString();+ newState.status = 'done';++ await transports.stream.publishEvent({+ data: {+ finalState: newState,+ phase: 'execution_complete',+ reason: USER_ABORTED_REASON,+ reasonDetail: USER_ABORTED_REASON_DETAIL,+ },+ stepIndex: operation.stepIndex,+ type: 'step_complete',+ });++ events.push({+ finalState: newState,+ reason: USER_ABORTED_REASON,+ reasonDetail: USER_ABORTED_REASON_DETAIL,+ type: 'done',+ });++ return { events, newState };+ };diff --git a/packages/agent-runtime/src/transport/stream.ts b/packages/agent-runtime/src/transport/stream.tsindex 70d04fbba37..bc8c704ab7b 100644--- a/packages/agent-runtime/src/transport/stream.ts+++ b/packages/agent-runtime/src/transport/stream.ts@@ -29,11 +29,18 @@ export interface StreamChunkInput {text?: string;}+export interface StreamErrorInput {+ error: unknown;+ phase: string;+ stepIndex: number;+}+/*** Egress for live streaming. Server adapter forwards to the Redis stream* (`IStreamEventManager`); the client adapter dispatches into the UI store.*/export interface StreamSink {publishChunk: (chunk: StreamChunkInput) => Promise<void>;+ publishError?: (input: StreamErrorInput) => Promise<void>;publishEvent: (event: RuntimeStreamEvent) => Promise<void>;}diff --git a/packages/agent-runtime/src/utils/index.ts b/packages/agent-runtime/src/utils/index.tsindex 43d407b6842..f0d41690228 100644--- a/packages/agent-runtime/src/utils/index.ts+++ b/packages/agent-runtime/src/utils/index.ts@@ -1,5 +1,6 @@export * from './messageSelectors';export * from './replay';+export * from './runtimeRetry';export * from './status';export * from './stepContextComputer';export * from './tokenCounter';diff --git a/packages/agent-runtime/src/utils/runtimeRetry.test.ts b/packages/agent-runtime/src/utils/runtimeRetry.test.tsnew file mode 100644index 00000000000..e685852c987--- /dev/null+++ b/packages/agent-runtime/src/utils/runtimeRetry.test.ts@@ -0,0 +1,63 @@+import { describe, expect, it, vi } from 'vitest';++import {+ executeToolWithRetry,+ getLLMRetryDelayMs,+ resolveLLMMaxAttempts,+ resolveLLMRetryBudget,+ shouldRetryLLM,+} from './runtimeRetry';++describe('runtimeRetry', () => {+ it('resolves LLM retry policy with provider disables and empty completion floor', () => {+ const emptyError = new Error('empty');+ const options = {+ isEmptyCompletionError: (error: unknown) => error === emptyError,+ noRetryProviders: ['lobehub'],+ };++ expect(resolveLLMRetryBudget('openai', new Error('rate limit'), options)).toBe(5);+ expect(resolveLLMRetryBudget('lobehub', new Error('upstream failed'), options)).toBe(0);+ expect(resolveLLMRetryBudget('lobehub', emptyError, options)).toBe(2);+ expect(resolveLLMMaxAttempts('lobehub', options)).toBe(3);+ });++ it('calculates exponential LLM retry delay with a cap', () => {+ expect(getLLMRetryDelayMs(1)).toBe(1000);+ expect(getLLMRetryDelayMs(2)).toBe(2000);+ expect(getLLMRetryDelayMs(99)).toBe(30_000);+ expect(shouldRetryLLM('retry', 2, 2)).toBe(true);+ expect(shouldRetryLLM('retry', 3, 2)).toBe(false);+ expect(shouldRetryLLM('stop', 1, 2)).toBe(false);+ });++ it('retries tool execution while kind is retry and stops on success', async () => {+ const execute = vi+ .fn()+ .mockResolvedValueOnce({ error: { kind: 'retry' }, success: false })+ .mockResolvedValueOnce({ content: 'done', success: true });+ const onRetry = vi.fn();++ const result = await executeToolWithRetry(execute, {+ maxRetries: 2,+ onRetry,+ });++ expect(result.attempts).toBe(2);+ expect(result.result).toEqual({ content: 'done', success: true });+ expect(onRetry).toHaveBeenCalledWith({ attempt: 1, kind: 'retry', maxAttempts: 3 });+ });++ it('stops tool retries when interrupted', async () => {+ const firstResult = { error: { kind: 'retry' }, success: false };+ const execute = vi.fn().mockResolvedValue(firstResult);++ const result = await executeToolWithRetry(execute, {+ isInterrupted: async () => true,+ maxRetries: 2,+ });++ expect(result).toEqual({ attempts: 1, result: firstResult });+ expect(execute).toHaveBeenCalledTimes(1);+ });+});diff --git a/packages/agent-runtime/src/utils/runtimeRetry.ts b/packages/agent-runtime/src/utils/runtimeRetry.tsnew file mode 100644index 00000000000..0d06d2e65cb--- /dev/null+++ b/packages/agent-runtime/src/utils/runtimeRetry.ts@@ -0,0 +1,100 @@+const DEFAULT_LLM_MAX_RETRIES = 5;+const DEFAULT_EMPTY_COMPLETION_MAX_RETRIES = 2;+const DEFAULT_LLM_RETRY_BASE_DELAY_MS = 1000;+const DEFAULT_LLM_RETRY_MAX_DELAY_MS = 30_000;++export type RuntimeRetryKind = 'retry' | 'stop';+export type RuntimeToolFailureKind = 'replan' | 'retry' | 'stop';++export interface LLMRetryPolicyOptions {+ emptyCompletionMaxRetries?: number;+ isEmptyCompletionError?: (error: unknown) => boolean;+ maxRetries?: number;+ noRetryProviders?: readonly string[];+ retryBaseDelayMs?: number;+ retryMaxDelayMs?: number;+}++export interface RetryableToolResult {+ error?: unknown;+ success: boolean;+}++export interface ExecuteToolWithRetryParams {+ isInterrupted?: () => Promise<boolean>;+ maxRetries: number;+ onRetry?: (info: {+ attempt: number;+ kind: RuntimeToolFailureKind;+ maxAttempts: number;+ }) => Promise<void> | void;+}++const resolveLLMMaxRetries = (provider: string, options: LLMRetryPolicyOptions = {}) =>+ options.noRetryProviders?.includes(provider)+ ? 0+ : (options.maxRetries ?? DEFAULT_LLM_MAX_RETRIES);++export const shouldRetryLLM = (kind: RuntimeRetryKind, attempt: number, maxRetries: number) =>+ kind === 'retry' && attempt <= maxRetries;++/**+ * Retry budget for a specific failed attempt. Empty completions can opt into a+ * dedicated floor even when the provider-level policy disables general retries.+ */+export const resolveLLMRetryBudget = (+ provider: string,+ error: unknown,+ options: LLMRetryPolicyOptions = {},+) =>+ options.isEmptyCompletionError?.(error)+ ? (options.emptyCompletionMaxRetries ?? DEFAULT_EMPTY_COMPLETION_MAX_RETRIES)+ : resolveLLMMaxRetries(provider, options);++/** Loop bound β must accommodate the largest budget any error kind can request. */+export const resolveLLMMaxAttempts = (provider: string, options: LLMRetryPolicyOptions = {}) =>+ Math.max(+ resolveLLMMaxRetries(provider, options),+ options.emptyCompletionMaxRetries ?? DEFAULT_EMPTY_COMPLETION_MAX_RETRIES,+ ) + 1;++export const getLLMRetryDelayMs = (attempt: number, options: LLMRetryPolicyOptions = {}) =>+ Math.min(+ (options.retryBaseDelayMs ?? DEFAULT_LLM_RETRY_BASE_DELAY_MS) * 2 ** Math.max(attempt - 1, 0),+ options.retryMaxDelayMs ?? DEFAULT_LLM_RETRY_MAX_DELAY_MS,+ );++const getToolFailureKind = (result: RetryableToolResult): RuntimeToolFailureKind | 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;+};++export const executeToolWithRetry = async <TResult extends RetryableToolResult>(+ execute: () => Promise<TResult>,+ params: ExecuteToolWithRetryParams,+): Promise<{ attempts: number; result: TResult }> => {+ 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 (kind === 'retry' && attempt <= params.maxRetries) {+ if (await params.isInterrupted?.()) {+ return { attempts: attempt, result };+ }++ await params.onRetry?.({ attempt, kind, maxAttempts });+ continue;+ }++ return { attempts: attempt, result };+ }++ throw new Error('Tool execution retry loop exited unexpectedly');+};