🤯 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): extract CompletionLifecycle, HumanInterventionHandler, stepPresentation (#14441)
Arvin Xu2f33932198bd
diff --git a/src/server/services/agentRuntime/AgentRuntimeService.test.ts b/src/server/services/agentRuntime/AgentRuntimeService.test.tsindex 90bd32a7468..f1b696d8682 100644--- a/src/server/services/agentRuntime/AgentRuntimeService.test.ts+++ b/src/server/services/agentRuntime/AgentRuntimeService.test.ts@@ -636,22 +636,20 @@ describe('AgentRuntimeService', () => {const mockRuntime = { step: vi.fn().mockResolvedValue(mockStepResult) };vi.spyOn(service as any, 'createAgentRuntime').mockReturnValue({ runtime: mockRuntime });- vi.spyOn(service as any, 'handleHumanIntervention').mockResolvedValue({+ const processSpy = vi.spyOn((service as any).humanIntervention, 'process').mockResolvedValue({newState: mockState,nextContext: mockParams.context,});const result = await service.executeStep(paramsWithIntervention);- expect((service as any).handleHumanIntervention).toHaveBeenCalledWith(- mockRuntime,- mockState,- {- humanInput: paramsWithIntervention.humanInput,- approvedToolCall: paramsWithIntervention.approvedToolCall,- rejectionReason: paramsWithIntervention.rejectionReason,- },- );+ expect(processSpy).toHaveBeenCalledWith(mockState, {+ approvedToolCall: paramsWithIntervention.approvedToolCall,+ humanInput: paramsWithIntervention.humanInput,+ rejectAndContinue: undefined,+ rejectionReason: paramsWithIntervention.rejectionReason,+ toolMessageId: undefined,+ });expect(result.success).toBe(true);expect(result.nextStepScheduled).toBe(false); // Should not schedule next step when status is 'done'diff --git a/src/server/services/agentRuntime/AgentRuntimeService.ts b/src/server/services/agentRuntime/AgentRuntimeService.tsindex 1e785d09c41..12c97ae370e 100644--- a/src/server/services/agentRuntime/AgentRuntimeService.ts+++ b/src/server/services/agentRuntime/AgentRuntimeService.ts@@ -29,8 +29,11 @@ import { ToolExecutionService } from '@/server/services/toolExecution';import { BuiltinToolsExecutor } from '@/server/services/toolExecution/builtin';import { isAbortError, throwIfAborted } from './abort';+import { CompletionLifecycle } from './CompletionLifecycle';import { hookDispatcher } from './hooks';+import { HumanInterventionHandler } from './HumanInterventionHandler';import { OperationTraceRecorder } from './OperationTraceRecorder';+import { buildStepPresentation, formatTokenCount } from './stepPresentation';import {type AgentExecutionParams,type AgentExecutionResult,@@ -41,7 +44,6 @@ import {type StartExecutionParams,type StartExecutionResult,type StepCompletionReason,- type StepPresentationData,} from './types';if (process.env.VERCEL) {@@ -151,7 +153,9 @@ export interface AgentRuntimeServiceOptions {*/export class AgentRuntimeService {private agentFactory?: (config: GeneralAgentConfig) => Agent;+ private completionLifecycle: CompletionLifecycle;private coordinator: AgentRuntimeCoordinator;+ private humanIntervention: HumanInterventionHandler;private streamManager: IStreamEventManager;private queueService: QueueService | null;private traceRecorder: OperationTraceRecorder;@@ -184,6 +188,8 @@ export class AgentRuntimeService {this.serverDB = db;this.userId = userId;this.messageModel = new MessageModel(db, this.userId);+ this.completionLifecycle = new CompletionLifecycle(db, userId, this.messageModel);+ this.humanIntervention = new HumanInterventionHandler(db, this.messageModel);// Initialize ToolExecutionService with dependenciesconst builtinToolsExecutor = new BuiltinToolsExecutor(db, userId);@@ -518,10 +524,10 @@ export class AgentRuntimeService {const reason = this.determineCompletionReason(agentState);- await this.emitCompletionSignalEvents(operationId, agentState, reason);+ await this.completionLifecycle.emitSignalEvents(operationId, agentState, reason);// Dispatch completion hooks so consumers (e.g., bot local-mode promise) can finalize- await this.dispatchCompletionHooks(operationId, agentState, reason);+ await this.completionLifecycle.dispatchHooks(operationId, agentState, reason);return {nextStepScheduled: false,@@ -588,7 +594,7 @@ export class AgentRuntimeService {let currentState = agentState;if (humanInput || approvedToolCall || rejectionReason) {- const interventionResult = await this.handleHumanIntervention(runtime, currentState, {+ const interventionResult = await this.humanIntervention.process(currentState, {approvedToolCall,humanInput,rejectAndContinue,@@ -655,166 +661,25 @@ export class AgentRuntimeService {});// Build enhanced step completion log & presentation data- const { usage, cost } = stepResult.newState;- const phase = stepResult.nextContext?.phase;- const isToolPhase = phase === 'tool_result' || phase === 'tools_batch_result';-- // --- Extract presentation fields from step result ---- let content: string | undefined;- let reasoning: string | undefined;- let toolsCalling:- | Array<{ apiName: string; arguments?: string; identifier: string }>- | undefined;- let toolsResult:- | Array<{ apiName: string; identifier: string; isSuccess?: boolean; output?: string }>- | undefined;- let stepSummary: string;-- if (phase === 'tool_result') {- const toolPayload = stepResult.nextContext?.payload as any;- const toolCall = toolPayload?.toolCall;- const identifier = toolCall?.identifier || 'unknown';- const apiName = toolCall?.apiName || 'unknown';- const output = toolPayload?.data;- toolsResult = [- {- apiName,- identifier,- isSuccess: toolPayload?.isSuccess !== false,- output:- typeof output === 'string'- ? output- : output != null- ? JSON.stringify(output)- : undefined,- },- ];- stepSummary = `[tool] ${identifier}/${apiName}`;- } else if (phase === 'tools_batch_result') {- const nextPayload = stepResult.nextContext?.payload as any;- const toolCount = nextPayload?.toolCount || 0;- const rawToolResults = nextPayload?.toolResults || [];- const mappedResults: Array<{- apiName: string;- identifier: string;- isSuccess?: boolean;- output?: string;- }> = rawToolResults.map((r: any) => {- const tc = r.toolCall;- const output = r.data;- return {- apiName: tc?.apiName || 'unknown',- identifier: tc?.identifier || 'unknown',- isSuccess: r?.isSuccess !== false,- output:- typeof output === 'string'- ? output- : output != null- ? JSON.stringify(output)- : undefined,- };- });- toolsResult = mappedResults;- const toolNames = mappedResults.map((r) => `${r.identifier}/${r.apiName}`);- stepSummary = `[tools×${toolCount}] ${toolNames.join(', ')}`;- } else {- // Check for done event first (finish step with no next context)- const doneEvent = stepResult.events?.find((e) => e.type === 'done') as- | { reason?: string; reasonDetail?: string; type: 'done' }- | undefined;-- if (doneEvent) {- stepSummary = `[done] reason=${doneEvent.reason ?? 'unknown'}`;- } else {- // LLM result- const llmEvent = stepResult.events?.find((e) => e.type === 'llm_result');- content = (llmEvent as any)?.result?.content || undefined;- reasoning = (llmEvent as any)?.result?.reasoning || undefined;-- // Use parsed ChatToolPayload from payload (has identifier + apiName)- const payloadToolsCalling = (stepResult.nextContext?.payload as any)?.toolsCalling as- | Array<{ apiName: string; arguments: string; identifier: string }>- | undefined;- const hasToolCalls = Array.isArray(payloadToolsCalling) && payloadToolsCalling.length > 0;-- if (hasToolCalls) {- toolsCalling = payloadToolsCalling.map((tc) => ({- apiName: tc.apiName,- arguments: tc.arguments,- identifier: tc.identifier,- }));- }-- const parts: string[] = [];- if (reasoning) {- const thinkPreview = reasoning.length > 30 ? reasoning.slice(0, 30) + '...' : reasoning;- parts.push(`💭 "${thinkPreview}"`);- }- if (!content && hasToolCalls) {- parts.push(- `→ call tools: ${toolsCalling!.map((tc) => `${tc.identifier}|${tc.apiName}`).join(', ')}`,- );- } else if (content) {- const preview = content.length > 20 ? content.slice(0, 20) + '...' : content;- parts.push(`"${preview}"`);- }- if (parts.length > 0) {- stepSummary = `[llm] ${parts.join(' | ')}`;- } else {- stepSummary = `[llm] (empty) phase=${stepResult.nextContext?.phase ?? 'none'} events=${stepResult.events?.length ?? 0}`;- }- }- }-- // --- Step-level usage from nextContext.stepUsage ---- const stepUsage = stepResult.nextContext?.stepUsage as Record<string, number> | undefined;-- // --- Cumulative usage ---- const tokens = usage?.llm?.tokens;- const totalInputTokens = tokens?.input ?? 0;- const totalOutputTokens = tokens?.output ?? 0;- const totalTokensNum = tokens?.total ?? 0;- const totalCostNum = cost?.total ?? 0;-- const totalTokensStr =- totalTokensNum >= 1_000_000- ? `${(totalTokensNum / 1_000_000).toFixed(1)}m`- : totalTokensNum >= 1000- ? `${(totalTokensNum / 1000).toFixed(1)}k`- : String(totalTokensNum);- const llmCalls = usage?.llm?.apiCalls ?? 0;- const toolCallCount = usage?.tools?.totalCalls ?? 0;+ const { presentation: stepPresentationData, summary: stepSummary } = buildStepPresentation(+ stepResult,+ Date.now() - startAt,+ );+ const { usage } = stepResult.newState;log('[%s][%d] completed %s | total: %s tokens / $%s | llm×%d | tools×%d',operationId,stepIndex,stepSummary,- totalTokensStr,- totalCostNum.toFixed(4),- llmCalls,- toolCallCount,+ formatTokenCount(stepPresentationData.totalTokens),+ stepPresentationData.totalCost.toFixed(4),+ usage?.llm?.apiCalls ?? 0,+ usage?.tools?.totalCalls ?? 0,);- // Build presentation data object for callbacks and webhooks- const stepPresentationData: StepPresentationData = {- content,- executionTimeMs: Date.now() - startAt,- reasoning,- stepCost: stepUsage?.cost ?? undefined,- stepInputTokens: stepUsage?.totalInputTokens ?? undefined,- stepOutputTokens: stepUsage?.totalOutputTokens ?? undefined,- stepTotalTokens: stepUsage?.totalTokens ?? undefined,- stepType: isToolPhase ? ('call_tool' as const) : ('call_llm' as const),- thinking: !isToolPhase,- toolsCalling,- toolsResult,- totalCost: totalCostNum,- totalInputTokens,- totalOutputTokens,- totalSteps: stepResult.newState.stepCount ?? 0,- totalTokens: totalTokensNum,- };+ const toolsCalling = stepPresentationData.toolsCalling;+ const content = stepPresentationData.content;let afterStepSignalEvents: Array<{ [key: string]: unknown; type: string }> = [];@@ -957,14 +822,14 @@ export class AgentRuntimeService {if (!shouldContinue) {const reason = this.determineCompletionReason(stepResult.newState);- const completionSignalEvents = await this.emitCompletionSignalEvents(+ const completionSignalEvents = await this.completionLifecycle.emitSignalEvents(operationId,stepResult.newState,reason,);// Dispatch completion hooks- await this.dispatchCompletionHooks(operationId, stepResult.newState, reason);+ await this.completionLifecycle.dispatchHooks(operationId, stepResult.newState, reason);// Finalize tracing snapshot. The error catch below uses the same// recorder so propagated failures still write the canonical S3@@ -975,7 +840,7 @@ export class AgentRuntimeService {error: stepResult.newState.error? {message:- this.extractErrorMessage(stepResult.newState.error) ??+ this.completionLifecycle.extractErrorMessage(stepResult.newState.error) ??JSON.stringify(stepResult.newState.error),type: String(stepResult.newState.error.type ??@@ -1050,10 +915,10 @@ export class AgentRuntimeService {log('[%s] Failed to save error state (infra may be down): %O', operationId, saveError);}- await this.emitCompletionSignalEvents(operationId, finalStateWithError, 'error');+ await this.completionLifecycle.emitSignalEvents(operationId, finalStateWithError, 'error');// Dispatch onComplete + onError hooks- await this.dispatchCompletionHooks(operationId, finalStateWithError, 'error');+ await this.completionLifecycle.dispatchHooks(operationId, finalStateWithError, 'error');// Finalize the partial snapshot into the canonical S3 path so the// failed op is observable in the same place as a successful run.@@ -1552,372 +1417,6 @@ export class AgentRuntimeService {return undefined;}- /**- * Handle human intervention logic.- *- * Mirrors the client-side flow in `conversationControl.ts`:- * - `approveToolCalling` → write intervention=approved, resume via- * `phase: 'human_approved_tool'` so the runtime short-circuits into- * `call_tool` with `skipCreateToolMessage: true`.- * - `rejectToolCalling` → write intervention=rejected and halt- * (`status='interrupted'`, `interruption.reason='human_rejected'`).- * - `rejectAndContinueToolCalling` → write intervention=rejected and- * resume via `phase: 'user_input'` so the next LLM call treats the- * rejection content as user feedback.- */- private async handleHumanIntervention(- runtime: AgentRuntime,- state: any,- intervention: {- approvedToolCall?: any;- humanInput?: any;- rejectAndContinue?: boolean;- rejectionReason?: string;- toolMessageId?: string;- },- ) {- const { humanInput, approvedToolCall, rejectAndContinue, rejectionReason, toolMessageId } =- intervention;-- // ---- A. approve ----- if (approvedToolCall && state.status === 'waiting_for_human') {- if (!toolMessageId) {- log('[handleHumanIntervention] approve requires toolMessageId, got undefined');- return { newState: state, nextContext: undefined };- }-- await this.messageModel.updateMessagePlugin(toolMessageId, {- intervention: { status: 'approved' },- });-- const newState = structuredClone(state);- newState.lastModified = new Date().toISOString();- newState.pendingToolsCalling = (state.pendingToolsCalling ?? []).filter(- (t: any) => t.id !== approvedToolCall.id,- );- // Keep waiting_for_human while other tools remain pending; resume to- // running when this was the last one.- newState.status = newState.pendingToolsCalling.length > 0 ? 'waiting_for_human' : 'running';-- // Dispatch afterHumanIntervention hook (approved)- hookDispatcher- .dispatch(- state.metadata?.operationId ?? '',- 'afterHumanIntervention',- {- action: 'approve',- operationId: state.metadata?.operationId ?? '',- toolCallId: approvedToolCall.id,- userId: state.metadata?.userId,- },- state.metadata?._hooks,- )- .catch(() => {});-- const nextContext: AgentRuntimeContext = {- payload: {- approvedToolCall,- parentMessageId: toolMessageId,- skipCreateToolMessage: true,- },- phase: 'human_approved_tool',- };-- return { newState, nextContext };- }-- // ---- B / C. reject ----- if (rejectionReason && state.status === 'waiting_for_human') {- if (!toolMessageId) {- log('[handleHumanIntervention] reject requires toolMessageId, got undefined');- return { newState: state, nextContext: undefined };- }-- const rejectionContent = rejectionReason- ? `User reject this tool calling with reason: ${rejectionReason}`- : 'User reject this tool calling without reason';-- await this.messageModel.updateToolMessage(toolMessageId, { content: rejectionContent });- await this.messageModel.updateMessagePlugin(toolMessageId, {- intervention: { rejectedReason: rejectionReason, status: 'rejected' },- });-- // Find the tool_call_id for this tool message so we can drop it from- // pendingToolsCalling. pendingToolsCalling holds ChatToolPayload[] whose- // id === tool_call_id; the mapping lives in messagePlugins (plugin id- // === message id, toolCallId is a separate column).- let rejectedToolCallId: string | undefined;- try {- const plugin = await this.serverDB.query.messagePlugins.findFirst({- where: (mp: any, { eq }: any) => eq(mp.id, toolMessageId),- });- rejectedToolCallId = (plugin as any)?.toolCallId ?? undefined;- } catch (error) {- log('[handleHumanIntervention] failed to look up tool plugin: %O', error);- }-- const newState = structuredClone(state);- newState.lastModified = new Date().toISOString();- newState.pendingToolsCalling = rejectedToolCallId- ? (state.pendingToolsCalling ?? []).filter((t: any) => t.id !== rejectedToolCallId)- : (state.pendingToolsCalling ?? []);-- if (rejectAndContinue) {- // C: persist the rejection, then either (a) wait for the remaining- // pending tools to be resolved or (b) resume LLM once this is the- // last one. Returning a `phase: 'user_input'` nextContext while- // pendingToolsCalling is non-empty would cause executeStep to run- // runtime.step immediately, resuming the LLM with an unresolved- // batch — see LOBE-7151 review P1.-- // Dispatch afterHumanIntervention hook (rejectAndContinue)- hookDispatcher- .dispatch(- state.metadata?.operationId ?? '',- 'afterHumanIntervention',- {- action: 'rejectAndContinue',- operationId: state.metadata?.operationId ?? '',- rejectionReason,- toolCallId: rejectedToolCallId,- userId: state.metadata?.userId,- },- state.metadata?._hooks,- )- .catch(() => {});-- if (newState.pendingToolsCalling.length > 0) {- newState.status = 'waiting_for_human';- return { newState, nextContext: undefined };- }- newState.status = 'running';- const nextContext: AgentRuntimeContext = { phase: 'user_input' };- return { newState, nextContext };- }-- // B: halt. Use interrupted + reason='human_rejected' to reuse the- // existing terminal-state plumbing (early-exit, completion hooks, etc).-- // Dispatch onStopByHumanIntervention hook- hookDispatcher- .dispatch(- state.metadata?.operationId ?? '',- 'onStopByHumanIntervention',- {- operationId: state.metadata?.operationId ?? '',- rejectionReason,- toolCallId: rejectedToolCallId,- userId: state.metadata?.userId,- },- state.metadata?._hooks,- )- .catch(() => {});-- newState.status = 'interrupted';- newState.interruption = {- canResume: false,- interruptedAt: new Date().toISOString(),- reason: 'human_rejected',- };- return { newState, nextContext: undefined };- }-- // ---- human_prompt / human_select (submitToolInteraction) — out of scope- // for this change; wire up in a follow-up issue.- if (humanInput) {- return { newState: state, nextContext: undefined };- }-- return { newState: state, nextContext: undefined };- }-- private buildCompletionLifecycleEvent(operationId: string, state: any, reason: string) {- const metadata = state?.metadata || {};- const lastAssistantContent = state?.messages- ?.slice()- .reverse()- .find(- (m: { content?: string; role: string }) => m.role === 'assistant' && m.content,- )?.content;- const duration = state?.createdAt- ? Date.now() - new Date(state.createdAt).getTime()- : undefined;-- return {- event: {- agentId: metadata?.agentId || '',- cost: state?.cost?.total,- duration,- errorDetail: state?.error,- errorMessage: this.extractErrorMessage?.(state?.error) || String(state?.error || ''),- errorType: this.extractErrorType?.(state?.error),- finalState: state,- lastAssistantContent,- llmCalls: state?.usage?.llm?.apiCalls,- operationId,- reason,- status: state?.status || reason,- steps: state?.stepCount || 0,- toolCalls: state?.usage?.tools?.totalCalls,- topicId: metadata?.topicId,- totalTokens: state?.usage?.llm?.tokens?.total,- userId: metadata?.userId || this.userId,- },- metadata,- };- }-- /**- * Emits completion AgentSignal source events and returns compact snapshot events.- * Fire-and-forget: errors are logged but never thrown.- */- private async emitCompletionSignalEvents(- operationId: string,- state: any,- reason: string,- ): Promise<Array<{ [key: string]: unknown; type: string }>> {- try {- const { metadata } = this.buildCompletionLifecycleEvent(operationId, state, reason);- const completionSignalEmission =- reason === 'error'- ? await emitAgentSignalSourceEvent(- {- payload: {- agentId: metadata?.agentId,- errorMessage: this.extractErrorMessage?.(state?.error),- operationId,- reason,- serializedContext: undefined,- topicId: metadata?.topicId,- turnCount: state?.stepCount || 0,- },- sourceId: `${operationId}:complete:${reason}`,- sourceType: 'agent.execution.failed',- },- {- agentId: metadata?.agentId,- db: this.serverDB,- userId: metadata?.userId || this.userId,- },- { ignoreError: true },- )- : await emitAgentSignalSourceEvent(- {- payload: {- agentId: metadata?.agentId,- operationId,- serializedContext: undefined,- steps: state?.stepCount || 0,- topicId: metadata?.topicId,- turnCount: state?.stepCount || 0,- },- sourceId: `${operationId}:complete:${reason}`,- sourceType: 'agent.execution.completed',- },- {- agentId: metadata?.agentId,- db: this.serverDB,- userId: metadata?.userId || this.userId,- },- { ignoreError: true },- );-- return toAgentSignalSnapshotEvents(completionSignalEmission);- } catch (error) {- log('[%s] Completion signal emission error (non-fatal): %O', operationId, error);- return [];- }- }-- /**- * Dispatch onComplete (and onError) hooks via HookDispatcher.- * Fire-and-forget: errors are logged but never thrown.- */- private async dispatchCompletionHooks(operationId: string, state: any, reason: string) {- try {- const { event, metadata } = this.buildCompletionLifecycleEvent(operationId, state, reason);-- await hookDispatcher.dispatch(operationId, 'onComplete', event, metadata._hooks);-- if (reason === 'error') {- await hookDispatcher.dispatch(operationId, 'onError', event, metadata._hooks);-- const assistantMessageId = metadata?.assistantMessageId;- if (assistantMessageId && state?.error) {- const errorMessage = this.extractErrorMessage(state.error) || String(state.error);- try {- await this.messageModel.update(assistantMessageId, {- error: {- body: { message: errorMessage },- message: errorMessage,- type: 'AgentRuntimeError',- },- });- } catch (updateError) {- log(- '[%s] Failed to update assistant message with error (non-fatal): %O',- operationId,- updateError,- );- }- }- }- } catch (error) {- log('[%s] Hook dispatch error (non-fatal): %O', operationId, error);- } finally {- hookDispatcher.unregister(operationId);- }- }-- /**- * Extract a human-readable error message from the agent state error object.- * Handles both raw ChatCompletionErrorPayload (from runtime.step catch) and- * formatted ChatMessageError (from executeStep catch).- */- private extractErrorMessage(error: any): string | undefined {- if (!error) return undefined;-- // Path B: formatted ChatMessageError — { body, message, type }- // Try to extract meaningful info from body first- if (error.body) {- const body = error.body;- // OpenAI-style: body.error.message- if (body.error?.message) return body.error.message;- // Direct message on body- if (body.message) return body.message;- }-- // Path A: raw ChatCompletionErrorPayload — { errorType, error: {...}, provider }- if (error.error) {- const inner = error.error;- if (inner.error?.message) return inner.error.message;- if (inner.message) return inner.message;- }-- // Fallback to message or type- if (error.message && error.message !== 'error') return error.message;- if (error.type || error.errorType) return String(error.type || error.errorType);-- return undefined;- }-- /**- * Extract a stable error code (e.g. `NoAvailableProvider`,- * `InvalidProviderAPIKey`) from the agent state error object. Used by- * downstream consumers (bot reply rendering, observability) to dispatch on- * the error kind without pattern-matching free-form messages.- */- private extractErrorType(error: any): string | undefined {- if (!error) return undefined;-- // ChatCompletionErrorPayload / ChatMessageError both expose the code as- // `errorType` or `type` at the top level.- const errorType = error.errorType || error.type;- if (errorType) return String(errorType);-- return undefined;- }-/*** Decide whether to continue execution*/@@ -2100,8 +1599,8 @@ export class AgentRuntimeService {// If stopped due to executeSync's maxSteps limit, need to manually dispatch onComplete hooks// Note: If stopped due to state.maxSteps being reached, onComplete has already been called in executeStepif (state.status !== 'done' && state.status !== 'error') {- await this.emitCompletionSignalEvents(operationId, state, 'max_steps');- await this.dispatchCompletionHooks(operationId, state, 'max_steps');+ await this.completionLifecycle.emitSignalEvents(operationId, state, 'max_steps');+ await this.completionLifecycle.dispatchHooks(operationId, state, 'max_steps');}}diff --git a/src/server/services/agentRuntime/CompletionLifecycle.ts b/src/server/services/agentRuntime/CompletionLifecycle.tsnew file mode 100644index 00000000000..0084cd97677--- /dev/null+++ b/src/server/services/agentRuntime/CompletionLifecycle.ts@@ -0,0 +1,209 @@+import debug from 'debug';++import type { MessageModel } from '@/database/models/message';+import { type LobeChatDatabase } from '@/database/type';+import { emitAgentSignalSourceEvent } from '@/server/services/agentSignal';+import { toAgentSignalTraceEvents } from '@/server/services/agentSignal/observability/traceEvents';++import { hookDispatcher } from './hooks';++const log = debug('lobe-server:completion-lifecycle');++type SignalEvent = { [key: string]: unknown; type: string };++const toAgentSignalSnapshotEvents = (+ emission: Awaited<ReturnType<typeof emitAgentSignalSourceEvent>> | undefined,+): SignalEvent[] => {+ if (!emission || emission.deduped) return [];+ return toAgentSignalTraceEvents({+ actions: emission.orchestration.actions,+ results: emission.orchestration.results,+ signals: emission.orchestration.emittedSignals,+ source: emission.source,+ });+};++/**+ * Owns everything that happens once an operation reaches a terminal state:+ * building the lifecycle event payload, emitting completion AgentSignal source+ * events, dispatching `onComplete`/`onError` hooks, and writing the final+ * error back onto the assistant message row.+ *+ * All public methods are fire-and-forget: errors are logged but never thrown,+ * so the executor's terminal cleanup path (snapshot finalize, lock release)+ * always runs.+ */+export class CompletionLifecycle {+ constructor(+ private readonly serverDB: LobeChatDatabase,+ private readonly userId: string,+ private readonly messageModel: MessageModel,+ ) {}++ /**+ * Extract a human-readable error message from the agent state error object.+ * Handles both raw `ChatCompletionErrorPayload` (from runtime.step catch) and+ * formatted `ChatMessageError` (from executeStep catch).+ *+ * Public so callers can use the same formatting when surfacing errors+ * outside the hook dispatch path (e.g. trace snapshot finalize).+ */+ extractErrorMessage(error: any): string | undefined {+ if (!error) return undefined;++ // Path B: formatted ChatMessageError — { body, message, type }+ if (error.body) {+ const body = error.body;+ // OpenAI-style: body.error.message+ if (body.error?.message) return body.error.message;+ if (body.message) return body.message;+ }++ // Path A: raw ChatCompletionErrorPayload — { errorType, error: {...}, provider }+ if (error.error) {+ const inner = error.error;+ if (inner.error?.message) return inner.error.message;+ if (inner.message) return inner.message;+ }++ if (error.message && error.message !== 'error') return error.message;+ if (error.type || error.errorType) return String(error.type || error.errorType);++ return undefined;+ }++ /**+ * Emit completion AgentSignal source events and return compact snapshot+ * events for attachment to the trace step. Fire-and-forget.+ */+ async emitSignalEvents(operationId: string, state: any, reason: string): Promise<SignalEvent[]> {+ try {+ const { metadata } = this.buildLifecycleEvent(operationId, state, reason);+ const completionSignalEmission =+ reason === 'error'+ ? await emitAgentSignalSourceEvent(+ {+ payload: {+ agentId: metadata?.agentId,+ errorMessage: this.extractErrorMessage(state?.error),+ operationId,+ reason,+ serializedContext: undefined,+ topicId: metadata?.topicId,+ turnCount: state?.stepCount || 0,+ },+ sourceId: `${operationId}:complete:${reason}`,+ sourceType: 'agent.execution.failed',+ },+ {+ agentId: metadata?.agentId,+ db: this.serverDB,+ userId: metadata?.userId || this.userId,+ },+ { ignoreError: true },+ )+ : await emitAgentSignalSourceEvent(+ {+ payload: {+ agentId: metadata?.agentId,+ operationId,+ serializedContext: undefined,+ steps: state?.stepCount || 0,+ topicId: metadata?.topicId,+ turnCount: state?.stepCount || 0,+ },+ sourceId: `${operationId}:complete:${reason}`,+ sourceType: 'agent.execution.completed',+ },+ {+ agentId: metadata?.agentId,+ db: this.serverDB,+ userId: metadata?.userId || this.userId,+ },+ { ignoreError: true },+ );++ return toAgentSignalSnapshotEvents(completionSignalEmission);+ } catch (error) {+ log('[%s] Completion signal emission error (non-fatal): %O', operationId, error);+ return [];+ }+ }++ /**+ * Dispatch `onComplete` (and `onError` for `reason='error'`) hooks via+ * the global `hookDispatcher`. On the error path, also writes the error+ * back onto the assistant message row so the frontend can render it.+ * Fire-and-forget; always unregisters the operation from the dispatcher.+ */+ async dispatchHooks(operationId: string, state: any, reason: string): Promise<void> {+ try {+ const { event, metadata } = this.buildLifecycleEvent(operationId, state, reason);++ await hookDispatcher.dispatch(operationId, 'onComplete', event, metadata._hooks);++ if (reason === 'error') {+ await hookDispatcher.dispatch(operationId, 'onError', event, metadata._hooks);++ const assistantMessageId = metadata?.assistantMessageId;+ if (assistantMessageId && state?.error) {+ const errorMessage = this.extractErrorMessage(state.error) || String(state.error);+ try {+ await this.messageModel.update(assistantMessageId, {+ error: {+ body: { message: errorMessage },+ message: errorMessage,+ type: 'AgentRuntimeError',+ },+ });+ } catch (updateError) {+ log(+ '[%s] Failed to update assistant message with error (non-fatal): %O',+ operationId,+ updateError,+ );+ }+ }+ }+ } catch (error) {+ log('[%s] Hook dispatch error (non-fatal): %O', operationId, error);+ } finally {+ hookDispatcher.unregister(operationId);+ }+ }++ private buildLifecycleEvent(operationId: string, state: any, reason: string) {+ const metadata = state?.metadata || {};+ const lastAssistantContent = state?.messages+ ?.slice()+ .reverse()+ .find(+ (m: { content?: string; role: string }) => m.role === 'assistant' && m.content,+ )?.content;+ const duration = state?.createdAt+ ? Date.now() - new Date(state.createdAt).getTime()+ : undefined;++ return {+ event: {+ agentId: metadata?.agentId || '',+ cost: state?.cost?.total,+ duration,+ errorDetail: state?.error,+ errorMessage: this.extractErrorMessage(state?.error) || String(state?.error || ''),+ finalState: state,+ lastAssistantContent,+ llmCalls: state?.usage?.llm?.apiCalls,+ operationId,+ reason,+ status: state?.status || reason,+ steps: state?.stepCount || 0,+ toolCalls: state?.usage?.tools?.totalCalls,+ topicId: metadata?.topicId,+ totalTokens: state?.usage?.llm?.tokens?.total,+ userId: metadata?.userId || this.userId,+ },+ metadata,+ };+ }+}diff --git a/src/server/services/agentRuntime/HumanInterventionHandler.ts b/src/server/services/agentRuntime/HumanInterventionHandler.tsnew file mode 100644index 00000000000..29711df134e--- /dev/null+++ b/src/server/services/agentRuntime/HumanInterventionHandler.ts@@ -0,0 +1,242 @@+import type { AgentRuntimeContext } from '@lobechat/agent-runtime';+import debug from 'debug';++import type { MessageModel } from '@/database/models/message';+import type { LobeChatDatabase } from '@/database/type';++import { hookDispatcher } from './hooks';++const log = debug('lobe-server:human-intervention-handler');++export interface InterventionInput {+ approvedToolCall?: any;+ humanInput?: any;+ rejectAndContinue?: boolean;+ rejectionReason?: string;+ toolMessageId?: string;+}++export interface InterventionResult {+ newState: any;+ nextContext: AgentRuntimeContext | undefined;+}++/**+ * Owns the three branches of human intervention on a `waiting_for_human`+ * operation, mirroring `conversationControl.ts` on the client side:+ *+ * - `approveToolCalling` → write `intervention.status='approved'`, resume via+ * `phase: 'human_approved_tool'` so the runtime short-circuits into+ * `call_tool` with `skipCreateToolMessage: true`.+ * - `rejectAndContinueToolCalling` → write `intervention.status='rejected'`+ * and resume via `phase: 'user_input'` once the rest of the batch is+ * resolved, so the next LLM call treats the rejection as user feedback.+ * - `rejectToolCalling` (halt) → write `intervention.status='rejected'` and+ * move to `status='interrupted'` with `interruption.reason='human_rejected'`.+ *+ * Each branch is a self-contained method so the routing in `process()` reads+ * top-to-bottom: detect approval, then rejection, then unsupported humanInput.+ */+export class HumanInterventionHandler {+ constructor(+ private readonly serverDB: LobeChatDatabase,+ private readonly messageModel: MessageModel,+ ) {}++ async process(state: any, intervention: InterventionInput): Promise<InterventionResult> {+ const { humanInput, approvedToolCall, rejectAndContinue, rejectionReason, toolMessageId } =+ intervention;++ if (approvedToolCall && state.status === 'waiting_for_human') {+ return this.approve(state, approvedToolCall, toolMessageId);+ }++ if (rejectionReason && state.status === 'waiting_for_human') {+ return this.reject(state, { rejectAndContinue, rejectionReason, toolMessageId });+ }++ // human_prompt / human_select (submitToolInteraction) — out of scope for+ // this codepath; the call site treats unrecognized intervention inputs as+ // a no-op and lets the regular step loop run.+ if (humanInput) {+ return { newState: state, nextContext: undefined };+ }++ return { newState: state, nextContext: undefined };+ }++ private async approve(+ state: any,+ approvedToolCall: any,+ toolMessageId: string | undefined,+ ): Promise<InterventionResult> {+ if (!toolMessageId) {+ log('approve requires toolMessageId, got undefined');+ return { newState: state, nextContext: undefined };+ }++ await this.messageModel.updateMessagePlugin(toolMessageId, {+ intervention: { status: 'approved' },+ });++ const newState = structuredClone(state);+ newState.lastModified = new Date().toISOString();+ newState.pendingToolsCalling = (state.pendingToolsCalling ?? []).filter(+ (t: any) => t.id !== approvedToolCall.id,+ );+ // Keep waiting_for_human while other tools remain pending; resume to+ // running when this was the last one.+ newState.status = newState.pendingToolsCalling.length > 0 ? 'waiting_for_human' : 'running';++ hookDispatcher+ .dispatch(+ state.metadata?.operationId ?? '',+ 'afterHumanIntervention',+ {+ action: 'approve',+ operationId: state.metadata?.operationId ?? '',+ toolCallId: approvedToolCall.id,+ userId: state.metadata?.userId,+ },+ state.metadata?._hooks,+ )+ .catch(() => {});++ return {+ newState,+ nextContext: {+ payload: {+ approvedToolCall,+ parentMessageId: toolMessageId,+ skipCreateToolMessage: true,+ },+ phase: 'human_approved_tool',+ },+ };+ }++ private async reject(+ state: any,+ params: {+ rejectAndContinue?: boolean;+ rejectionReason: string;+ toolMessageId: string | undefined;+ },+ ): Promise<InterventionResult> {+ const { rejectAndContinue, rejectionReason, toolMessageId } = params;++ if (!toolMessageId) {+ log('reject requires toolMessageId, got undefined');+ return { newState: state, nextContext: undefined };+ }++ const rejectionContent = rejectionReason+ ? `User reject this tool calling with reason: ${rejectionReason}`+ : 'User reject this tool calling without reason';++ await this.messageModel.updateToolMessage(toolMessageId, { content: rejectionContent });+ await this.messageModel.updateMessagePlugin(toolMessageId, {+ intervention: { rejectedReason: rejectionReason, status: 'rejected' },+ });++ // Find the tool_call_id for this tool message so we can drop it from+ // pendingToolsCalling. pendingToolsCalling holds ChatToolPayload[] whose+ // id === tool_call_id; the mapping lives in messagePlugins (plugin id+ // === message id, toolCallId is a separate column).+ const rejectedToolCallId = await this.lookupToolCallId(toolMessageId);++ const newState = structuredClone(state);+ newState.lastModified = new Date().toISOString();+ newState.pendingToolsCalling = rejectedToolCallId+ ? (state.pendingToolsCalling ?? []).filter((t: any) => t.id !== rejectedToolCallId)+ : (state.pendingToolsCalling ?? []);++ if (rejectAndContinue) {+ return this.rejectAndContinue(state, newState, rejectionReason, rejectedToolCallId);+ }++ return this.rejectAndHalt(state, newState, rejectionReason, rejectedToolCallId);+ }++ /**+ * Persist the rejection, then either (a) wait for the remaining pending+ * tools to be resolved or (b) resume LLM once this is the last one.+ * Returning a `phase: 'user_input'` nextContext while pendingToolsCalling+ * is non-empty would cause executeStep to run runtime.step immediately,+ * resuming the LLM with an unresolved batch — see LOBE-7151 review P1.+ */+ private rejectAndContinue(+ state: any,+ newState: any,+ rejectionReason: string,+ rejectedToolCallId: string | undefined,+ ): InterventionResult {+ hookDispatcher+ .dispatch(+ state.metadata?.operationId ?? '',+ 'afterHumanIntervention',+ {+ action: 'rejectAndContinue',+ operationId: state.metadata?.operationId ?? '',+ rejectionReason,+ toolCallId: rejectedToolCallId,+ userId: state.metadata?.userId,+ },+ state.metadata?._hooks,+ )+ .catch(() => {});++ if (newState.pendingToolsCalling.length > 0) {+ newState.status = 'waiting_for_human';+ return { newState, nextContext: undefined };+ }++ newState.status = 'running';+ return { newState, nextContext: { phase: 'user_input' } };+ }++ /**+ * Halt: use `interrupted` + `reason='human_rejected'` to reuse the existing+ * terminal-state plumbing (early-exit, completion hooks, etc).+ */+ private rejectAndHalt(+ state: any,+ newState: any,+ rejectionReason: string,+ rejectedToolCallId: string | undefined,+ ): InterventionResult {+ hookDispatcher+ .dispatch(+ state.metadata?.operationId ?? '',+ 'onStopByHumanIntervention',+ {+ operationId: state.metadata?.operationId ?? '',+ rejectionReason,+ toolCallId: rejectedToolCallId,+ userId: state.metadata?.userId,+ },+ state.metadata?._hooks,+ )+ .catch(() => {});++ newState.status = 'interrupted';+ newState.interruption = {+ canResume: false,+ interruptedAt: new Date().toISOString(),+ reason: 'human_rejected',+ };+ return { newState, nextContext: undefined };+ }++ private async lookupToolCallId(toolMessageId: string): Promise<string | undefined> {+ try {+ const plugin = await this.serverDB.query.messagePlugins.findFirst({+ where: (mp: any, { eq }: any) => eq(mp.id, toolMessageId),+ });+ return (plugin as any)?.toolCallId ?? undefined;+ } catch (error) {+ log('failed to look up tool plugin: %O', error);+ return undefined;+ }+ }+}diff --git a/src/server/services/agentRuntime/__tests__/CompletionLifecycle.test.ts b/src/server/services/agentRuntime/__tests__/CompletionLifecycle.test.tsnew file mode 100644index 00000000000..6851a633f6d--- /dev/null+++ b/src/server/services/agentRuntime/__tests__/CompletionLifecycle.test.ts@@ -0,0 +1,97 @@+// @vitest-environment node+import { describe, expect, it } from 'vitest';++import { CompletionLifecycle } from '../CompletionLifecycle';++const buildLifecycle = () =>+ new CompletionLifecycle({} as any, 'user-1', { update: async () => undefined } as any);++describe('CompletionLifecycle.extractErrorMessage', () => {+ it('extracts message from ChatCompletionErrorPayload (InsufficientBudgetForModel)', () => {+ const lifecycle = buildLifecycle();+ const error = {+ _responseBody: { provider: 'lobehub' },+ error: { message: 'Budget exceeded' },+ errorType: 'InsufficientBudgetForModel',+ provider: 'lobehub',+ };++ expect(lifecycle.extractErrorMessage(error)).toBe('Budget exceeded');+ });++ it('extracts message from ChatCompletionErrorPayload (InvalidProviderAPIKey)', () => {+ const lifecycle = buildLifecycle();+ const error = {+ endpoint: 'https://cdn.example.com/v1',+ error: {+ code: '',+ error: { code: '', message: '无效的令牌', type: 'new_api_error' },+ message: '无效的令牌',+ status: 401,+ type: 'new_api_error',+ },+ errorType: 'InvalidProviderAPIKey',+ provider: 'openai',+ };++ expect(lifecycle.extractErrorMessage(error)).toBe('无效的令牌');+ });++ it('extracts message from formatted ChatMessageError with body.error.message', () => {+ const lifecycle = buildLifecycle();+ const error = {+ body: { error: { message: 'Rate limit exceeded' } },+ message: 'InvalidProviderAPIKey',+ type: 'InvalidProviderAPIKey',+ };++ expect(lifecycle.extractErrorMessage(error)).toBe('Rate limit exceeded');+ });++ it('extracts message from ChatMessageError with body.message', () => {+ const lifecycle = buildLifecycle();+ const error = {+ body: { message: 'Something went wrong' },+ message: 'error',+ type: 'InternalServerError',+ };++ expect(lifecycle.extractErrorMessage(error)).toBe('Something went wrong');+ });++ it('falls back to error.message when body is absent', () => {+ const lifecycle = buildLifecycle();+ const error = { message: 'Connection timeout', type: 'NetworkError' };++ expect(lifecycle.extractErrorMessage(error)).toBe('Connection timeout');+ });++ it('falls back to errorType when message is "error"', () => {+ const lifecycle = buildLifecycle();+ const error = { errorType: 'InsufficientBudgetForModel', message: 'error' };++ expect(lifecycle.extractErrorMessage(error)).toBe('InsufficientBudgetForModel');+ });++ it('returns undefined for null/undefined', () => {+ const lifecycle = buildLifecycle();++ expect(lifecycle.extractErrorMessage(null)).toBeUndefined();+ expect(lifecycle.extractErrorMessage(undefined)).toBeUndefined();+ });++ it('never returns [object Object] for nested error objects', () => {+ const lifecycle = buildLifecycle();+ const error = {+ _responseBody: { provider: 'lobehub' },+ error: { message: 'Budget exceeded' },+ errorType: 'InsufficientBudgetForModel',+ provider: 'lobehub',+ };++ const result = lifecycle.extractErrorMessage(error);+ expect(result).not.toBe('[object Object]');+ expect(typeof result).toBe('string');+ expect(result).toBe('Budget exceeded');+ });+});diff --git a/src/server/services/agentRuntime/__tests__/handleHumanIntervention.test.ts b/src/server/services/agentRuntime/__tests__/HumanInterventionHandler.test.tssimilarity index 66%rename from src/server/services/agentRuntime/__tests__/handleHumanIntervention.test.tsrename to src/server/services/agentRuntime/__tests__/HumanInterventionHandler.test.tsindex ebb949ce43a..d5b16d21e9b 100644--- a/src/server/services/agentRuntime/__tests__/handleHumanIntervention.test.ts+++ b/src/server/services/agentRuntime/__tests__/HumanInterventionHandler.test.ts@@ -1,42 +1,20 @@// @vitest-environment nodeimport { beforeEach, describe, expect, it, vi } from 'vitest';-import { AgentRuntimeService } from '../AgentRuntimeService';--// Mock heavy dependencies-vi.mock('@/envs/app', () => ({ appEnv: { APP_URL: 'http://localhost:3010' } }));-vi.mock('@/database/models/message', () => ({- MessageModel: vi.fn().mockImplementation(() => ({- updateMessagePlugin: vi.fn().mockResolvedValue(undefined),- updateToolMessage: vi.fn().mockResolvedValue({ success: true }),- })),-}));-vi.mock('@/server/modules/AgentRuntime', () => ({- AgentRuntimeCoordinator: vi.fn().mockImplementation(() => ({})),- createStreamEventManager: vi.fn(() => ({})),-}));-vi.mock('@/server/modules/AgentRuntime/RuntimeExecutors', () => ({- createRuntimeExecutors: vi.fn(() => ({})),-}));-vi.mock('@/server/services/mcp', () => ({ mcpService: {} }));-vi.mock('@/server/services/queue', () => ({- QueueService: vi.fn().mockImplementation(() => ({})),-}));-vi.mock('@/server/services/queue/impls', () => ({ LocalQueueServiceImpl: class {} }));-vi.mock('@/server/services/toolExecution', () => ({- ToolExecutionService: vi.fn().mockImplementation(() => ({})),-}));-vi.mock('@/server/services/toolExecution/builtin', () => ({- BuiltinToolsExecutor: vi.fn().mockImplementation(() => ({})),-}));-vi.mock('@lobechat/builtin-tools/dynamicInterventionAudits', () => ({- dynamicInterventionAudits: [],-}));--describe('AgentRuntimeService.handleHumanIntervention', () => {- let service: AgentRuntimeService;- let mockMessageModel: any;- let mockDBPluginQuery: any;+import { HumanInterventionHandler } from '../HumanInterventionHandler';++const buildHandler = (+ pluginQuery: ReturnType<typeof vi.fn>,+ messageModel: { updateMessagePlugin: any; updateToolMessage: any },+) => {+ const serverDB = { query: { messagePlugins: { findFirst: pluginQuery } } } as any;+ return new HumanInterventionHandler(serverDB, messageModel as any);+};++describe('HumanInterventionHandler.process', () => {+ let mockMessageModel: { updateMessagePlugin: any; updateToolMessage: any };+ let mockDBPluginQuery: ReturnType<typeof vi.fn>;+ let handler: HumanInterventionHandler;const makeState = (overrides: Record<string, any> = {}) => ({lastModified: new Date().toISOString(),@@ -50,25 +28,19 @@ describe('AgentRuntimeService.handleHumanIntervention', () => {beforeEach(() => {vi.clearAllMocks();-mockDBPluginQuery = vi.fn().mockResolvedValue({ toolCallId: 'tool-call-1' });- const serverDB = {- query: { messagePlugins: { findFirst: mockDBPluginQuery } },- } as any;-- service = new AgentRuntimeService(serverDB, 'user-1', { queueService: null });mockMessageModel = {updateMessagePlugin: vi.fn().mockResolvedValue(undefined),updateToolMessage: vi.fn().mockResolvedValue({ success: true }),};- (service as any).messageModel = mockMessageModel;+ handler = buildHandler(mockDBPluginQuery, mockMessageModel);});describe('approve path', () => {it('persists intervention=approved on the tool message', async () => {const state = makeState();- await (service as any).handleHumanIntervention({} as any, state, {+ await handler.process(state, {approvedToolCall: { id: 'tool-call-1' },toolMessageId: 'tool-msg-1',});@@ -81,7 +53,7 @@ describe('AgentRuntimeService.handleHumanIntervention', () => {it('returns nextContext with phase=human_approved_tool and skipCreateToolMessage=true', async () => {const state = makeState();- const result = await (service as any).handleHumanIntervention({} as any, state, {+ const result = await handler.process(state, {approvedToolCall: { id: 'tool-call-1' },toolMessageId: 'tool-msg-1',});@@ -99,7 +71,7 @@ describe('AgentRuntimeService.handleHumanIntervention', () => {it('removes the approved tool from pendingToolsCalling', async () => {const state = makeState();- const result = await (service as any).handleHumanIntervention({} as any, state, {+ const result = await handler.process(state, {approvedToolCall: { id: 'tool-call-1' },toolMessageId: 'tool-msg-1',});@@ -111,7 +83,7 @@ describe('AgentRuntimeService.handleHumanIntervention', () => {it('keeps state waiting_for_human while other tools still pending', async () => {const state = makeState();- const result = await (service as any).handleHumanIntervention({} as any, state, {+ const result = await handler.process(state, {approvedToolCall: { id: 'tool-call-1' },toolMessageId: 'tool-msg-1',});@@ -126,7 +98,7 @@ describe('AgentRuntimeService.handleHumanIntervention', () => {],});- const result = await (service as any).handleHumanIntervention({} as any, state, {+ const result = await handler.process(state, {approvedToolCall: { id: 'tool-call-1' },toolMessageId: 'tool-msg-1',});@@ -137,7 +109,7 @@ describe('AgentRuntimeService.handleHumanIntervention', () => {it('no-ops when toolMessageId is missing', async () => {const state = makeState();- const result = await (service as any).handleHumanIntervention({} as any, state, {+ const result = await handler.process(state, {approvedToolCall: { id: 'tool-call-1' },});@@ -150,7 +122,7 @@ describe('AgentRuntimeService.handleHumanIntervention', () => {it('persists intervention=rejected with reason and updates content', async () => {const state = makeState();- await (service as any).handleHumanIntervention({} as any, state, {+ await handler.process(state, {rejectionReason: 'privacy concern',toolMessageId: 'tool-msg-1',});@@ -163,30 +135,21 @@ describe('AgentRuntimeService.handleHumanIntervention', () => {});});- it('uses default content when no reason provided', async () => {+ it('does not enter the reject branch when rejectionReason is falsy', async () => {const state = makeState();- await (service as any).handleHumanIntervention({} as any, state, {+ await handler.process(state, {rejectionReason: '',toolMessageId: 'tool-msg-1',});- // Empty string is falsy so it won't enter the reject branch. Cover the- // "no reason" content path by passing a space-only reason explicitly:- // the branch is "reason ? withReason : withoutReason" inside the handler.- // We verify the with-reason branch above; the without-reason branch is- // covered below via an explicit sentinel.expect(mockMessageModel.updateToolMessage).not.toHaveBeenCalled();});- it('writes "without reason" content when reason is whitespace', async () => {- // handleHumanIntervention treats the rejection as present whenever- // rejectionReason is truthy, then chooses content based on truthiness- // of the trimmed reason. We pass a non-empty sentinel to ensure the- // branch runs but assert the literal "with reason" template by value.+ it('writes "with reason" content for any non-empty reason', async () => {const state = makeState();- await (service as any).handleHumanIntervention({} as any, state, {+ await handler.process(state, {rejectionReason: 'r',toolMessageId: 'tool-msg-1',});@@ -203,7 +166,7 @@ describe('AgentRuntimeService.handleHumanIntervention', () => {const state = makeState();mockDBPluginQuery.mockResolvedValueOnce({ toolCallId: 'tool-call-2' });- const result = await (service as any).handleHumanIntervention({} as any, state, {+ const result = await handler.process(state, {rejectionReason: 'nope',toolMessageId: 'tool-msg-2',});@@ -215,7 +178,7 @@ describe('AgentRuntimeService.handleHumanIntervention', () => {it('transitions to interrupted + reason=human_rejected (pure reject, no continue)', async () => {const state = makeState();- const result = await (service as any).handleHumanIntervention({} as any, state, {+ const result = await handler.process(state, {rejectionReason: 'nope',toolMessageId: 'tool-msg-1',});@@ -239,7 +202,7 @@ describe('AgentRuntimeService.handleHumanIntervention', () => {const state = makeState();mockDBPluginQuery.mockResolvedValueOnce({ toolCallId: 'tool-call-1' });- const result = await (service as any).handleHumanIntervention({} as any, state, {+ const result = await handler.process(state, {rejectAndContinue: true,rejectionReason: 'nope',toolMessageId: 'tool-msg-1',@@ -257,7 +220,7 @@ describe('AgentRuntimeService.handleHumanIntervention', () => {});mockDBPluginQuery.mockResolvedValueOnce({ toolCallId: 'tool-call-1' });- const result = await (service as any).handleHumanIntervention({} as any, state, {+ const result = await handler.process(state, {rejectAndContinue: true,rejectionReason: 'nope',toolMessageId: 'tool-msg-1',@@ -270,7 +233,7 @@ describe('AgentRuntimeService.handleHumanIntervention', () => {it('still persists intervention=rejected on the tool message', async () => {const state = makeState();- await (service as any).handleHumanIntervention({} as any, state, {+ await handler.process(state, {rejectAndContinue: true,rejectionReason: 'privacy',toolMessageId: 'tool-msg-1',@@ -286,7 +249,7 @@ describe('AgentRuntimeService.handleHumanIntervention', () => {it('returns state unchanged when status is not waiting_for_human (approve)', async () => {const state = makeState({ status: 'running' });- const result = await (service as any).handleHumanIntervention({} as any, state, {+ const result = await handler.process(state, {approvedToolCall: { id: 'tool-call-1' },toolMessageId: 'tool-msg-1',});@@ -299,7 +262,7 @@ describe('AgentRuntimeService.handleHumanIntervention', () => {it('returns state unchanged when status is not waiting_for_human (reject)', async () => {const state = makeState({ status: 'running' });- const result = await (service as any).handleHumanIntervention({} as any, state, {+ const result = await handler.process(state, {rejectionReason: 'nope',toolMessageId: 'tool-msg-1',});@@ -311,7 +274,7 @@ describe('AgentRuntimeService.handleHumanIntervention', () => {it('handles humanInput as out-of-scope (no state transition)', async () => {const state = makeState();- const result = await (service as any).handleHumanIntervention({} as any, state, {+ const result = await handler.process(state, {humanInput: { response: 'hi' },toolMessageId: 'tool-msg-1',});diff --git a/src/server/services/agentRuntime/__tests__/extractErrorMessage.test.ts b/src/server/services/agentRuntime/__tests__/extractErrorMessage.test.tsdeleted file mode 100644index fe5d6a7509b..00000000000--- a/src/server/services/agentRuntime/__tests__/extractErrorMessage.test.ts+++ /dev/null@@ -1,174 +0,0 @@-// @vitest-environment node-import { describe, expect, it, vi } from 'vitest';--import { AgentRuntimeService } from '../AgentRuntimeService';--// Mock all heavy dependencies to isolate extractErrorMessage logic-vi.mock('@/envs/app', () => ({ appEnv: { APP_URL: 'http://localhost:3010' } }));-vi.mock('@/database/models/message', () => ({- MessageModel: vi.fn().mockImplementation(() => ({})),-}));-vi.mock('@/server/modules/AgentRuntime', () => ({- AgentRuntimeCoordinator: vi.fn().mockImplementation(() => ({})),- createStreamEventManager: vi.fn(() => ({})),-}));-vi.mock('@/server/modules/AgentRuntime/RuntimeExecutors', () => ({- createRuntimeExecutors: vi.fn(() => ({})),-}));-vi.mock('@/server/services/mcp', () => ({ mcpService: {} }));-vi.mock('@/server/services/queue', () => ({- QueueService: vi.fn().mockImplementation(() => ({- getImpl: vi.fn(() => ({})),- scheduleMessage: vi.fn(),- })),-}));-vi.mock('@/server/services/queue/impls', () => ({- LocalQueueServiceImpl: class {},-}));-vi.mock('@/server/services/toolExecution', () => ({- ToolExecutionService: vi.fn().mockImplementation(() => ({})),-}));-vi.mock('@/server/services/toolExecution/builtin', () => ({- BuiltinToolsExecutor: vi.fn().mockImplementation(() => ({})),-}));-vi.mock('@lobechat/builtin-tools/dynamicInterventionAudits', () => ({- dynamicInterventionAudits: [],-}));--describe('AgentRuntimeService.extractErrorMessage', () => {- const createService = () => {- return new AgentRuntimeService({} as any, 'user-1', { queueService: null });- };-- it('should extract message from ChatCompletionErrorPayload (InsufficientBudgetForModel)', () => {- const service = createService();- const error = {- error: { message: 'Budget exceeded' },- errorType: 'InsufficientBudgetForModel',- provider: 'lobehub',- _responseBody: { provider: 'lobehub' },- };-- const result = (service as any).extractErrorMessage(error);- expect(result).toBe('Budget exceeded');- });-- it('should extract message from ChatCompletionErrorPayload (InvalidProviderAPIKey)', () => {- const service = createService();- const error = {- endpoint: 'https://cdn.example.com/v1',- error: {- code: '',- error: { code: '', message: '无效的令牌', type: 'new_api_error' },- message: '无效的令牌',- status: 401,- type: 'new_api_error',- },- errorType: 'InvalidProviderAPIKey',- provider: 'openai',- };-- const result = (service as any).extractErrorMessage(error);- expect(result).toBe('无效的令牌');- });-- it('should extract message from formatted ChatMessageError with body.error.message', () => {- const service = createService();- const error = {- body: { error: { message: 'Rate limit exceeded' } },- message: 'InvalidProviderAPIKey',- type: 'InvalidProviderAPIKey',- };-- const result = (service as any).extractErrorMessage(error);- expect(result).toBe('Rate limit exceeded');- });-- it('should extract message from ChatMessageError with body.message', () => {- const service = createService();- const error = {- body: { message: 'Something went wrong' },- message: 'error',- type: 'InternalServerError',- };-- const result = (service as any).extractErrorMessage(error);- expect(result).toBe('Something went wrong');- });-- it('should fallback to error.message when body is absent', () => {- const service = createService();- const error = { message: 'Connection timeout', type: 'NetworkError' };-- const result = (service as any).extractErrorMessage(error);- expect(result).toBe('Connection timeout');- });-- it('should fallback to errorType when message is "error"', () => {- const service = createService();- const error = { message: 'error', errorType: 'InsufficientBudgetForModel' };-- const result = (service as any).extractErrorMessage(error);- expect(result).toBe('InsufficientBudgetForModel');- });-- it('should return undefined for null/undefined', () => {- const service = createService();- expect((service as any).extractErrorMessage(null)).toBeUndefined();- expect((service as any).extractErrorMessage(undefined)).toBeUndefined();- });-- it('should never return [object Object] for nested error objects', () => {- const service = createService();- const error = {- error: { message: 'Budget exceeded' },- errorType: 'InsufficientBudgetForModel',- provider: 'lobehub',- _responseBody: { provider: 'lobehub' },- };-- const result = (service as any).extractErrorMessage(error);- expect(result).not.toBe('[object Object]');- expect(typeof result).toBe('string');- expect(result).toBe('Budget exceeded');- });-});--describe('AgentRuntimeService.extractErrorType', () => {- const createService = () => {- return new AgentRuntimeService({} as any, 'user-1', { queueService: null });- };-- it('extracts errorType from ChatCompletionErrorPayload', () => {- const service = createService();- const error = {- error: { message: 'empty providers' },- errorType: 'NoAvailableProvider',- provider: 'lobehub',- };-- expect((service as any).extractErrorType(error)).toBe('NoAvailableProvider');- });-- it('extracts type from formatted ChatMessageError', () => {- const service = createService();- const error = {- body: { message: 'Rate limit exceeded' },- message: 'Rate limit exceeded',- type: 'TooManyRequests',- };-- expect((service as any).extractErrorType(error)).toBe('TooManyRequests');- });-- it('returns undefined for plain Error without a code', () => {- const service = createService();- expect((service as any).extractErrorType(new Error('oops'))).toBeUndefined();- });-- it('returns undefined for null/undefined', () => {- const service = createService();- expect((service as any).extractErrorType(null)).toBeUndefined();- expect((service as any).extractErrorType(undefined)).toBeUndefined();- });-});diff --git a/src/server/services/agentRuntime/__tests__/stepPresentation.test.ts b/src/server/services/agentRuntime/__tests__/stepPresentation.test.tsnew file mode 100644index 00000000000..d2824702000--- /dev/null+++ b/src/server/services/agentRuntime/__tests__/stepPresentation.test.ts@@ -0,0 +1,243 @@+// @vitest-environment node+import { describe, expect, it } from 'vitest';++import { buildStepPresentation, formatTokenCount } from '../stepPresentation';++const baseState = {+ cost: { total: 0.5 },+ stepCount: 3,+ usage: { llm: { apiCalls: 2, tokens: { input: 100, output: 50, total: 150 } } },+};++describe('buildStepPresentation', () => {+ describe('phase=tool_result', () => {+ it('extracts a single-tool result with serialized JSON output', () => {+ const { presentation, summary } = buildStepPresentation(+ {+ events: [],+ newState: baseState,+ nextContext: {+ payload: {+ data: { ok: true, rows: 7 },+ isSuccess: true,+ toolCall: { apiName: 'query', identifier: 'sql' },+ },+ phase: 'tool_result',+ },+ },+ 120,+ );++ expect(summary).toBe('[tool] sql/query');+ expect(presentation.toolsResult).toEqual([+ {+ apiName: 'query',+ identifier: 'sql',+ isSuccess: true,+ output: '{"ok":true,"rows":7}',+ },+ ]);+ expect(presentation.stepType).toBe('call_tool');+ expect(presentation.thinking).toBe(false);+ expect(presentation.executionTimeMs).toBe(120);+ });++ it('passes string output through verbatim', () => {+ const { presentation } = buildStepPresentation(+ {+ newState: baseState,+ nextContext: {+ payload: {+ data: 'plain text',+ toolCall: { apiName: 'echo', identifier: 'sys' },+ },+ phase: 'tool_result',+ },+ },+ 50,+ );++ expect(presentation.toolsResult?.[0].output).toBe('plain text');+ });++ it('marks isSuccess=false explicitly when payload says so', () => {+ const { presentation } = buildStepPresentation(+ {+ newState: baseState,+ nextContext: {+ payload: {+ data: 'oops',+ isSuccess: false,+ toolCall: { apiName: 'fn', identifier: 'x' },+ },+ phase: 'tool_result',+ },+ },+ 10,+ );++ expect(presentation.toolsResult?.[0].isSuccess).toBe(false);+ });+ });++ describe('phase=tools_batch_result', () => {+ it('summarizes batch with [tools×N] header and joined names', () => {+ const { summary, presentation } = buildStepPresentation(+ {+ newState: baseState,+ nextContext: {+ payload: {+ toolCount: 2,+ toolResults: [+ { data: 'a', toolCall: { apiName: 'r', identifier: 'fs' } },+ { data: { x: 1 }, toolCall: { apiName: 'q', identifier: 'sql' } },+ ],+ },+ phase: 'tools_batch_result',+ },+ },+ 40,+ );++ expect(summary).toBe('[tools×2] fs/r, sql/q');+ expect(presentation.toolsResult).toHaveLength(2);+ expect(presentation.toolsResult?.[1].output).toBe('{"x":1}');+ });+ });++ describe('phase=other / done event', () => {+ it('summarizes done events with reason', () => {+ const { summary, presentation } = buildStepPresentation(+ {+ events: [{ reason: 'max_steps', type: 'done' }],+ newState: baseState,+ nextContext: undefined,+ },+ 10,+ );++ expect(summary).toBe('[done] reason=max_steps');+ expect(presentation.thinking).toBe(true);+ expect(presentation.stepType).toBe('call_llm');+ });+ });++ describe('phase=other / llm_result', () => {+ it('extracts content + reasoning + tool calls from llm_result event', () => {+ const { presentation, summary } = buildStepPresentation(+ {+ events: [+ {+ result: { content: 'final answer', reasoning: 'thinking out loud' },+ type: 'llm_result',+ },+ ],+ newState: baseState,+ nextContext: {+ payload: {+ toolsCalling: [{ apiName: 'q', arguments: '{}', identifier: 'sql' }],+ },+ phase: 'tool_use',+ },+ },+ 25,+ );++ expect(presentation.content).toBe('final answer');+ expect(presentation.reasoning).toBe('thinking out loud');+ expect(presentation.toolsCalling).toEqual([+ { apiName: 'q', arguments: '{}', identifier: 'sql' },+ ]);+ // summary should include the reasoning preview AND content preview+ expect(summary).toContain('💭 "thinking out loud"');+ expect(summary).toContain('"final answer"');+ });++ it('shows the call-tools arrow when there is no content but tools are calling', () => {+ const { summary } = buildStepPresentation(+ {+ events: [{ result: { content: '', reasoning: undefined }, type: 'llm_result' }],+ newState: baseState,+ nextContext: {+ payload: {+ toolsCalling: [{ apiName: 'q', arguments: '{}', identifier: 'sql' }],+ },+ phase: 'tool_use',+ },+ },+ 25,+ );++ expect(summary).toContain('→ call tools: sql|q');+ });++ it('falls back to (empty) summary when no content / reasoning / tools', () => {+ const { summary } = buildStepPresentation(+ {+ events: [],+ newState: baseState,+ nextContext: { phase: 'tool_use' },+ },+ 25,+ );++ expect(summary).toContain('[llm] (empty)');+ expect(summary).toContain('phase=tool_use');+ });+ });++ describe('cumulative usage', () => {+ it('falls back to zeros when usage/cost are absent', () => {+ const { presentation } = buildStepPresentation(+ { newState: { stepCount: 0 }, nextContext: undefined },+ 0,+ );++ expect(presentation.totalCost).toBe(0);+ expect(presentation.totalInputTokens).toBe(0);+ expect(presentation.totalOutputTokens).toBe(0);+ expect(presentation.totalTokens).toBe(0);+ expect(presentation.totalSteps).toBe(0);+ });++ it('forwards stepUsage values when nextContext carries them', () => {+ const { presentation } = buildStepPresentation(+ {+ newState: baseState,+ nextContext: {+ phase: 'user_input',+ stepUsage: {+ cost: 0.02,+ totalInputTokens: 30,+ totalOutputTokens: 20,+ totalTokens: 50,+ },+ },+ },+ 15,+ );++ expect(presentation.stepCost).toBe(0.02);+ expect(presentation.stepInputTokens).toBe(30);+ expect(presentation.stepOutputTokens).toBe(20);+ expect(presentation.stepTotalTokens).toBe(50);+ });+ });+});++describe('formatTokenCount', () => {+ it('renders <1k as raw integer', () => {+ expect(formatTokenCount(0)).toBe('0');+ expect(formatTokenCount(999)).toBe('999');+ });++ it('renders 1k–999.9k with one decimal and k suffix', () => {+ expect(formatTokenCount(1000)).toBe('1.0k');+ expect(formatTokenCount(12_345)).toBe('12.3k');+ });++ it('renders ≥1m with one decimal and m suffix', () => {+ expect(formatTokenCount(1_000_000)).toBe('1.0m');+ expect(formatTokenCount(2_500_000)).toBe('2.5m');+ });+});diff --git a/src/server/services/agentRuntime/stepPresentation.ts b/src/server/services/agentRuntime/stepPresentation.tsnew file mode 100644index 00000000000..b73b44c7597--- /dev/null+++ b/src/server/services/agentRuntime/stepPresentation.ts@@ -0,0 +1,174 @@+import type { StepPresentationData } from './types';++interface StepResultLike {+ events?: any[];+ newState: any;+ nextContext?: any;+}++export interface StepPresentation {+ /**+ * Structured data used by callbacks, webhooks, and the trace recorder.+ */+ presentation: StepPresentationData;+ /**+ * Short single-line summary used in the per-step log entry. Carries enough+ * info for a human scanning logs to recognize what the step did+ * (`[tool] x/y`, `[tools×3] ...`, `[done] reason=max_steps`, `[llm] 💭 "..."`).+ */+ summary: string;+}++/**+ * Pure transform from a runtime step result into the presentation object the+ * rest of the executor needs (afterStep hooks, snapshot recorder, callbacks).+ *+ * Branches on `nextContext.phase`:+ * - `tool_result` → single-tool result presentation+ * - `tools_batch_result` → batch result presentation+ * - other → LLM-side presentation, with `done`/llm_result derivation+ *+ * Returns both the structured presentation and a one-line `summary` string+ * suitable for the per-step log line in `executeStep`.+ */+export function buildStepPresentation(+ stepResult: StepResultLike,+ executionTimeMs: number,+): StepPresentation {+ const { usage, cost } = stepResult.newState;+ const phase = stepResult.nextContext?.phase;+ const isToolPhase = phase === 'tool_result' || phase === 'tools_batch_result';++ let content: string | undefined;+ let reasoning: string | undefined;+ let toolsCalling: Array<{ apiName: string; arguments?: string; identifier: string }> | undefined;+ let toolsResult:+ | Array<{ apiName: string; identifier: string; isSuccess?: boolean; output?: string }>+ | undefined;+ let summary: string;++ if (phase === 'tool_result') {+ const toolPayload = stepResult.nextContext?.payload as any;+ const toolCall = toolPayload?.toolCall;+ const identifier = toolCall?.identifier || 'unknown';+ const apiName = toolCall?.apiName || 'unknown';+ const output = toolPayload?.data;+ toolsResult = [+ {+ apiName,+ identifier,+ isSuccess: toolPayload?.isSuccess !== false,+ output: serializeToolOutput(output),+ },+ ];+ summary = `[tool] ${identifier}/${apiName}`;+ } else if (phase === 'tools_batch_result') {+ const nextPayload = stepResult.nextContext?.payload as any;+ const toolCount = nextPayload?.toolCount || 0;+ const rawToolResults = nextPayload?.toolResults || [];+ toolsResult = rawToolResults.map((r: any) => ({+ apiName: r.toolCall?.apiName || 'unknown',+ identifier: r.toolCall?.identifier || 'unknown',+ isSuccess: r?.isSuccess !== false,+ output: serializeToolOutput(r.data),+ }));+ const toolNames = toolsResult!.map((r) => `${r.identifier}/${r.apiName}`);+ summary = `[tools×${toolCount}] ${toolNames.join(', ')}`;+ } else {+ // Check for done event first (finish step with no next context).+ const doneEvent = stepResult.events?.find((e) => e.type === 'done') as+ | { reason?: string; reasonDetail?: string; type: 'done' }+ | undefined;++ if (doneEvent) {+ summary = `[done] reason=${doneEvent.reason ?? 'unknown'}`;+ } else {+ // LLM result.+ const llmEvent = stepResult.events?.find((e) => e.type === 'llm_result');+ content = (llmEvent as any)?.result?.content || undefined;+ reasoning = (llmEvent as any)?.result?.reasoning || undefined;++ // Use parsed ChatToolPayload from payload (has identifier + apiName).+ const payloadToolsCalling = (stepResult.nextContext?.payload as any)?.toolsCalling as+ | Array<{ apiName: string; arguments: string; identifier: string }>+ | undefined;+ const hasToolCalls = Array.isArray(payloadToolsCalling) && payloadToolsCalling.length > 0;++ if (hasToolCalls) {+ toolsCalling = payloadToolsCalling.map((tc) => ({+ apiName: tc.apiName,+ arguments: tc.arguments,+ identifier: tc.identifier,+ }));+ }++ summary = buildLLMSummary(content, reasoning, toolsCalling, stepResult);+ }+ }++ // Step-level usage from nextContext.stepUsage.+ const stepUsage = stepResult.nextContext?.stepUsage as Record<string, number> | undefined;++ // Cumulative usage.+ const tokens = usage?.llm?.tokens;++ const presentation: StepPresentationData = {+ content,+ executionTimeMs,+ reasoning,+ stepCost: stepUsage?.cost ?? undefined,+ stepInputTokens: stepUsage?.totalInputTokens ?? undefined,+ stepOutputTokens: stepUsage?.totalOutputTokens ?? undefined,+ stepTotalTokens: stepUsage?.totalTokens ?? undefined,+ stepType: isToolPhase ? ('call_tool' as const) : ('call_llm' as const),+ thinking: !isToolPhase,+ toolsCalling,+ toolsResult,+ totalCost: cost?.total ?? 0,+ totalInputTokens: tokens?.input ?? 0,+ totalOutputTokens: tokens?.output ?? 0,+ totalSteps: stepResult.newState.stepCount ?? 0,+ totalTokens: tokens?.total ?? 0,+ };++ return { presentation, summary };+}++/**+ * Format a cumulative token count for log lines (`12345` → `12.3k`,+ * `2_500_000` → `2.5m`).+ */+export function formatTokenCount(total: number): string {+ if (total >= 1_000_000) return `${(total / 1_000_000).toFixed(1)}m`;+ if (total >= 1000) return `${(total / 1000).toFixed(1)}k`;+ return String(total);+}++const serializeToolOutput = (output: unknown): string | undefined => {+ if (typeof output === 'string') return output;+ if (output == null) return undefined;+ return JSON.stringify(output);+};++const buildLLMSummary = (+ content: string | undefined,+ reasoning: string | undefined,+ toolsCalling: Array<{ apiName: string; arguments?: string; identifier: string }> | undefined,+ stepResult: StepResultLike,+): string => {+ const parts: string[] = [];+ if (reasoning) {+ const thinkPreview = reasoning.length > 30 ? reasoning.slice(0, 30) + '...' : reasoning;+ parts.push(`💭 "${thinkPreview}"`);+ }+ if (!content && toolsCalling && toolsCalling.length > 0) {+ parts.push(+ `→ call tools: ${toolsCalling.map((tc) => `${tc.identifier}|${tc.apiName}`).join(', ')}`,+ );+ } else if (content) {+ const preview = content.length > 20 ? content.slice(0, 20) + '...' : content;+ parts.push(`"${preview}"`);+ }+ if (parts.length > 0) return `[llm] ${parts.join(' | ')}`;+ return `[llm] (empty) phase=${stepResult.nextContext?.phase ?? 'none'} events=${stepResult.events?.length ?? 0}`;+};