🤯 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: move LLM retry orchestration into agent runtime (#17069)
Arvin Xu202991d38445
diff --git a/apps/server/src/modules/AgentRuntime/adapters/ServerLLMTransport.ts b/apps/server/src/modules/AgentRuntime/adapters/ServerLLMTransport.tsindex 49c22d3ea2f..40b7122befc 100644--- a/apps/server/src/modules/AgentRuntime/adapters/ServerLLMTransport.ts+++ b/apps/server/src/modules/AgentRuntime/adapters/ServerLLMTransport.ts@@ -6,6 +6,7 @@ import type {LLMStreamResult,LLMTransport,LLMTurnInput,+ LLMTurnSession,} from '@lobechat/agent-runtime';import {type ChatStreamPayload,@@ -17,7 +18,7 @@ import { initModelRuntimeFromDB } from '@/server/modules/ModelRuntime';import type { RuntimeExecutorContext } from '../context';import { createServerCallLlmAttempt } from './serverCallLlmAttempt';-import { executeServerCallLlmTurn } from './serverCallLlmExecutor';+import { openServerCallLlmTurn } from './serverCallLlmExecutor';const getErrorMessage = (error: unknown): string => {if (error instanceof Error && error.message) return error.message;@@ -39,10 +40,10 @@ export class ServerLLMTransport implements LLMTransport {private readonly blobStore?: BlobStore,) {}- executeTurn(input: LLMTurnInput): ReturnType<NonNullable<LLMTransport['executeTurn']>> {+ openTurn(input: LLMTurnInput): LLMTurnSession {let modelRuntimePromise: ReturnType<ServerLLMTransport['createModelRuntime']> | undefined;- return executeServerCallLlmTurn(this.ctx, {+ return openServerCallLlmTurn(this.ctx, {assistantMessage: input.assistantMessage,context: input.context,model: input.model,diff --git a/apps/server/src/modules/AgentRuntime/adapters/ServerOperationStore.ts b/apps/server/src/modules/AgentRuntime/adapters/ServerOperationStore.tsindex dcc3f449e19..83a93ecada1 100644--- a/apps/server/src/modules/AgentRuntime/adapters/ServerOperationStore.ts+++ b/apps/server/src/modules/AgentRuntime/adapters/ServerOperationStore.ts@@ -1,4 +1,4 @@-import type { OperationStore } from '@lobechat/agent-runtime';+import type { AgentState, OperationStore } from '@lobechat/agent-runtime';import { TopicModel } from '@/database/models/topic';import { type LobeChatDatabase } from '@/database/type';@@ -15,6 +15,7 @@ export class ServerOperationStore implements OperationStore {private readonly userId: string | undefined,private readonly workspaceId: string | undefined,private readonly topicId: string | undefined,+ private readonly loadAgentState?: (operationId: string) => Promise<AgentState | null>,) {}async clearRunningMark(): Promise<void> {@@ -26,4 +27,8 @@ export class ServerOperationStore implements OperationStore {// best-effort — swallow}}++ async loadState(operationId: string): Promise<AgentState | null> {+ return (await this.loadAgentState?.(operationId)) ?? null;+ }}diff --git a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmExecutor.ts b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmExecutor.tsindex 145d366cf69..4cb1c7305cd 100644--- a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmExecutor.ts+++ b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmExecutor.ts@@ -1,14 +1,16 @@import {- type AgentEvent,type AgentState,type ContextBuildOutput,type GeneralAgentCallLLMResultPayload,- getLLMRetryDelayMs,type InstructionExecutionResult,type LLMTransport,+ type LLMTurnAttemptInput,+ type LLMTurnErrorInput,+ type LLMTurnFinalizeInput,+ type LLMTurnRetryInput,+ type LLMTurnSession,resolveLLMMaxAttempts,resolveLLMRetryBudget,- shouldRetryLLM,} from '@lobechat/agent-runtime';import { BRANDING_PROVIDER } from '@lobechat/business-const';import { ModelEmptyError } from '@lobechat/model-runtime';@@ -26,8 +28,7 @@ import {} from '@lobechat/observability-otel/modules/agent-runtime';import { type RuntimeExecutorContext } from '../context';-import { isOperationInterrupted, log, sleep } from '../executorHelpers';-import { formatErrorEventData } from '../formatErrorEventData';+import { log, sleep } from '../executorHelpers';import { classifyLLMError } from '../llmErrorClassification';import {finalizeServerCallLlmResult,@@ -49,320 +50,254 @@ const SERVER_LLM_RETRY_POLICY = {noRetryProviders: [BRANDING_PROVIDER],};-class ServerCallLlmTurn {+class ServerCallLlmTurnSession implements LLMTurnSession {+ readonly maxAttempts: number;++ private readonly chatContext: ReturnType<typeof otelTrace.setSpan>;+ private readonly chatSpan: ReturnType<typeof agentRuntimeTracer.startSpan>;+ private firstChunkAt?: number;+ private readonly llmStartTime = Date.now();+ private readonly operationLogId: string;+constructor(private readonly ctx: RuntimeExecutorContext,private readonly prepared: ServerCallLlmExecutionContext,- ) {}+ ) {+ const { context, model, provider, state } = prepared;+ const processedMessages = context.messages as Array<{ role?: string }>;++ if (!context.resolvedTools) {+ throw new Error('Resolved tools are required for a server LLM turn');+ }+ if (!processedMessages.some((message) => message.role !== 'system')) {+ throw new Error(+ `call_llm produced no non-system messages for ${provider}/${model} ` ++ `(topic=${state.metadata?.topicId ?? 'n/a'}, step=${ctx.stepIndex}); refusing to dispatch`,+ );+ }- async execute(): Promise<InstructionExecutionResult> {- const { ctx, prepared } = this;- const { state } = prepared;- const { operationId, stepIndex, streamManager } = ctx;- const events: AgentEvent[] = [];- let visibleOutputEndPublishedStepIndex: number | undefined;- const {- assistantMessage: assistantMessageItem,- context,- model,- provider,- runAttempt,- stepLabel,- } = prepared;- const { messages: preparedMessages, replayAssistantReasoning: shouldReplayAssistantReasoning } =- context;- const processedMessages = preparedMessages as Array<{ role?: string }>;- const operationLogId = `${operationId}:${stepIndex}`;+ this.operationLogId = `${ctx.operationId}:${ctx.stepIndex}`;+ this.maxAttempts = resolveLLMMaxAttempts(provider, SERVER_LLM_RETRY_POLICY);log('[%s][call_llm] Starting operation with prepared assistant message: %s',- operationLogId,- assistantMessageItem.id,+ this.operationLogId,+ prepared.assistantMessage.id,);- try {- if (!context.resolvedTools) {- throw new Error('Resolved tools are required for a server LLM turn');- }-- // A turn must carry at least one non-system message. Anthropic-compatible- // providers (anthropic / deepseek) move `role: system` into a separate- // top-level field, so a system-only array dispatches `messages: []` and- // the upstream rejects it with a 400 `messages: at least one message is- // required` (surfaced as an opaque UpstreamHttpError); for other providers- // a system-only turn has nothing to respond to. Either way the context- // pipeline dropped everything real — fail fast with a locatable internal- // error instead of a doomed round-trip. Attributed here (agent-runtime),- // not the provider layer, since it's our own pipeline that emptied it.- if (!processedMessages.some((message) => message.role !== 'system')) {- throw new Error(- `call_llm produced no non-system messages for ${provider}/${model} ` +- `(topic=${state.metadata?.topicId ?? 'n/a'}, step=${stepIndex}); refusing to dispatch`,- );- }+ this.chatSpan = agentRuntimeTracer.startSpan(chatSpanName(model), {+ attributes: buildChatRequestAttributes({+ conversationId: state.metadata?.topicId,+ operationId: ctx.operationId,+ provider,+ requestModel: model,+ stepIndex: ctx.stepIndex,+ stream: ctx.stream ?? true,+ }),+ kind: SpanKind.CLIENT,+ });+ this.chatContext = otelTrace.setSpan(otelContext.active(), this.chatSpan);+ }- const stream = ctx.stream ?? true;- const maxAttempts = resolveLLMMaxAttempts(provider, SERVER_LLM_RETRY_POLICY);+ classifyError(error: unknown) {+ return classifyLLMError(error);+ }- // OTel chat span — wraps all retry attempts; TTFT recorded on the first- // text/reasoning chunk regardless of which attempt produced it (the- // semantic span represents the LLM call from the agent's perspective).- const llmStartTime = Date.now();- let firstChunkAt: number | undefined;- const onFirstChunk = () => {- if (firstChunkAt === undefined) firstChunkAt = Date.now() - llmStartTime;- };- const chatSpan = agentRuntimeTracer.startSpan(chatSpanName(model), {- attributes: buildChatRequestAttributes({- conversationId: state.metadata?.topicId,- operationId,- provider,- requestModel: model,- stepIndex,- stream,- }),- kind: SpanKind.CLIENT,+ close(error?: unknown) {+ if (error) {+ this.chatSpan.recordException(error as Error);+ this.chatSpan.setStatus({+ code: SpanStatusCode.ERROR,+ message: error instanceof Error ? error.message : String(error),});- const chatCtx = otelTrace.setSpan(otelContext.active(), chatSpan);-- try {- return await otelContext.with(chatCtx, async () => {- for (let attempt = 1; attempt <= maxAttempts; attempt++) {- const execution = await runAttempt({- attempt,- context,- events,- maxAttempts,- model,- onFirstChunk,- provider,- state,- });- const llmAttempt = execution.output;-- try {- if (!execution.ok) throw execution.error;-- const {- answerSalvagedFromReasoning,- finishReason: currentStepFinishReason,- grounding,- imageList,- speed: currentStepSpeed,- toolCalls: tool_calls,- toolsCalling,- usage: currentStepUsage,- } = llmAttempt;-- // Add a complete llm_stream event (including all streaming chunks)- events.push({- result: {- content: llmAttempt.content,- finishReason: currentStepFinishReason,- reasoning: llmAttempt.thinkingContent,- tool_calls,- usage: currentStepUsage,- },- type: 'llm_result',- });-- // Publish stream end event- await streamManager.publishStreamEvent(operationId, {- data: {- finalContent: llmAttempt.content,- grounding,- ...(stepLabel && { stepLabel }),- imageList: imageList.length > 0 ? imageList : undefined,- reasoning: llmAttempt.thinkingContent || undefined,- toolsCalling,- usage: currentStepUsage,- },- stepIndex,- type: 'stream_end',- });-- const canPublishEarlyFinalAnswerVisibleEnd =- ctx.allowEarlyFinalAnswerVisibleOutputEnd ?? true;- if (- canPublishEarlyFinalAnswerVisibleEnd &&- toolsCalling.length === 0 &&- tool_calls.length === 0- ) {- try {- // Example: a no-tool answer can publish stream_end, then spend- // several seconds in DB/Redis persistence before terminal done.- // Clear visible loading once no more text/tool output can appear.- await streamManager.publishStreamEvent(operationId, {- data: { reason: 'final_answer' },- stepIndex,- type: 'visible_output_end',- });- visibleOutputEndPublishedStepIndex = stepIndex;- } catch (error) {- // Terminal saveStepResult still publishes the same hint as a fallback.- console.error('Failed to publish visible_output_end:', error);- }- }-- log('[%s:%d] call_llm completed', operationId, stepIndex);-- const newState = await finalizeServerCallLlmResult({- answerSalvagedFromReasoning,- assistantMessageId: assistantMessageItem.id,- currentStepSpeed,- currentStepUsage,- grounding,- imageList,- messageModel: ctx.messageModel,- model,- provider,- shouldReplayAssistantReasoning,- state,- stepLabel,- streamOutput: llmAttempt,- toolCalls: tool_calls,- toolsCalling,- visibleOutputEndPublishedStepIndex,- });-- // Record chat response attributes on the OTel span.- chatSpan.setAttributes(- buildChatResponseAttributes({- cacheReadInputTokens: currentStepUsage?.inputCachedTokens,- finishReasons: currentStepFinishReason ? [currentStepFinishReason] : undefined,- inputTokens: currentStepUsage?.totalInputTokens,- outputTokens: currentStepUsage?.totalOutputTokens,- reasoningOutputTokens: currentStepUsage?.outputReasoningTokens,- timeToFirstChunkMs: firstChunkAt,- }),- );-- return {- events,- newState,- nextContext: {- payload: {- hasToolsCalling: toolsCalling.length > 0,- // Pass assistant message ID as parentMessageId for tool calls- parentMessageId: assistantMessageItem.id,- result: { content: llmAttempt.content, tool_calls },- toolsCalling,- } as GeneralAgentCallLLMResultPayload,- phase: 'llm_result' as const,- session: {- eventCount: events.length,- messageCount: newState.messages.length,- sessionId: operationId,- status: 'running' as const,- stepCount: state.stepCount + 1,- },- stepUsage: currentStepUsage,- },- };- } catch (error) {- const classified = classifyLLMError(error);- const interrupted = await isOperationInterrupted(ctx);-- const retryBudget = resolveLLMRetryBudget(provider, error, SERVER_LLM_RETRY_POLICY);-- if (!interrupted && shouldRetryLLM(classified.kind, attempt, retryBudget)) {- const delayMs = getLLMRetryDelayMs(attempt);-- log(- '[%s] LLM call failed with kind=%s (attempt %d/%d), retrying in %dms ...',- operationLogId,- classified.kind,- attempt,- maxAttempts,- delayMs,- );-- const retryEvent: AgentEvent = {- data: {- attempt: attempt + 1,- delayMs,- errorType: classified.code,- kind: classified.kind,- maxAttempts,- },- type: 'stream_retry',- };- events.push(retryEvent);+ }+ this.chatSpan.end();+ }- await streamManager.publishStreamEvent(operationId, {- data: retryEvent.data,- stepIndex,- type: 'stream_retry',- });+ async finalize({ events, output }: LLMTurnFinalizeInput): Promise<InstructionExecutionResult> {+ return otelContext.with(this.chatContext, async () => {+ const { ctx, prepared } = this;+ const { operationId, stepIndex, streamManager } = ctx;+ const { assistantMessage, model, provider, state, stepLabel } = prepared;+ const {+ answerSalvagedFromReasoning,+ finishReason,+ grounding,+ imageList,+ speed,+ thinkingContent,+ toolCalls,+ toolsCalling,+ usage,+ } = output;++ events.push({+ result: {+ content: output.content,+ finishReason,+ reasoning: thinkingContent,+ tool_calls: toolCalls,+ usage,+ },+ type: 'llm_result',+ });- await sleep(delayMs);+ await streamManager.publishStreamEvent(operationId, {+ data: {+ finalContent: output.content,+ grounding,+ ...(stepLabel && { stepLabel }),+ imageList: imageList.length > 0 ? imageList : undefined,+ reasoning: thinkingContent || undefined,+ toolsCalling,+ usage,+ },+ stepIndex,+ type: 'stream_end',+ });- if (await isOperationInterrupted(ctx)) {- throw error;- }+ let visibleOutputEndPublishedStepIndex: number | undefined;+ const canPublishEarlyFinalAnswerVisibleEnd =+ ctx.allowEarlyFinalAnswerVisibleOutputEnd ?? true;+ if (+ canPublishEarlyFinalAnswerVisibleEnd &&+ toolsCalling.length === 0 &&+ toolCalls.length === 0+ ) {+ try {+ await streamManager.publishStreamEvent(operationId, {+ data: { reason: 'final_answer' },+ stepIndex,+ type: 'visible_output_end',+ });+ visibleOutputEndPublishedStepIndex = stepIndex;+ } catch (error) {+ console.error('Failed to publish visible_output_end:', error);+ }+ }- continue;- }+ log('[%s:%d] call_llm completed', operationId, stepIndex);+ const newState = await finalizeServerCallLlmResult({+ answerSalvagedFromReasoning,+ assistantMessageId: assistantMessage.id,+ currentStepSpeed: speed,+ currentStepUsage: usage,+ grounding,+ imageList,+ messageModel: ctx.messageModel,+ model,+ provider,+ shouldReplayAssistantReasoning: prepared.context.replayAssistantReasoning,+ state,+ stepLabel,+ streamOutput: output,+ toolCalls,+ toolsCalling,+ visibleOutputEndPublishedStepIndex,+ });- if (error instanceof ModelEmptyError && error.diagnostics) {- error.diagnostics.retryBudget = retryBudget;- error.diagnostics.retryEvents = events- .filter((event) => event.type === 'stream_retry')- .map((event) => event.data);- }+ this.chatSpan.setAttributes(+ buildChatResponseAttributes({+ cacheReadInputTokens: usage?.inputCachedTokens,+ finishReasons: finishReason ? [finishReason] : undefined,+ inputTokens: usage?.totalInputTokens,+ outputTokens: usage?.totalOutputTokens,+ reasoningOutputTokens: usage?.outputReasoningTokens,+ timeToFirstChunkMs: this.firstChunkAt,+ }),+ );- // Cancel/interrupt path: when the user stops mid-stream, the model-runtime- // stream is aborted before reaching the post-stream finalize,- // so the DB row remains a LOADING_FLAT placeholder. Without this fix,- // agent_runtime_end would push the placeholder as the source-of-truth- // to the client, clobbering the streamed content accumulated in memory.- // We persist whatever partial content the stream callbacks already- // accumulated so that reload/end snapshots reflect actual progress.- if (interrupted) {- await persistInterruptedServerCallLlmResult({- assistantMessageId: assistantMessageItem.id,- currentStepSpeed: llmAttempt.speed,- currentStepUsage: llmAttempt.usage,- messageModel: ctx.messageModel,- operationLogId,- streamOutput: llmAttempt,- toolsCalling: llmAttempt.toolsCalling,- });- }+ return {+ events,+ newState,+ nextContext: {+ payload: {+ hasToolsCalling: toolsCalling.length > 0,+ parentMessageId: assistantMessage.id,+ result: { content: output.content, tool_calls: toolCalls },+ toolsCalling,+ } as GeneralAgentCallLLMResultPayload,+ phase: 'llm_result' as const,+ session: {+ eventCount: events.length,+ messageCount: newState.messages.length,+ sessionId: operationId,+ status: 'running' as const,+ stepCount: state.stepCount + 1,+ },+ stepUsage: usage,+ },+ };+ });+ }- throw error;- }- }+ async handleError({ error, events, interrupted, output, retryBudget }: LLMTurnErrorInput) {+ await otelContext.with(this.chatContext, async () => {+ if (error instanceof ModelEmptyError && error.diagnostics) {+ error.diagnostics.retryBudget = retryBudget;+ error.diagnostics.retryEvents = events+ .filter((event) => event.type === 'stream_retry')+ .map((event) => event.data);+ }- throw new Error('LLM execution retry loop exited unexpectedly');+ if (interrupted && output) {+ await persistInterruptedServerCallLlmResult({+ assistantMessageId: this.prepared.assistantMessage.id,+ currentStepSpeed: output.speed,+ currentStepUsage: output.usage,+ messageModel: this.ctx.messageModel,+ operationLogId: this.operationLogId,+ streamOutput: output,+ toolsCalling: output.toolsCalling,});- } catch (error) {- chatSpan.recordException(error as Error);- chatSpan.setStatus({- code: SpanStatusCode.ERROR,- message: error instanceof Error ? error.message : String(error),- });- throw error;- } finally {- chatSpan.end();}- } catch (error) {- // Publish error event- await streamManager.publishStreamEvent(operationId, {- data: formatErrorEventData(error, 'llm_execution'),- stepIndex,- type: 'error',- });console.error(- `[StreamingLLMExecutor][${operationId}:${stepIndex}] LLM execution failed:`,+ `[StreamingLLMExecutor][${this.ctx.operationId}:${this.ctx.stepIndex}] LLM execution failed:`,error,);- throw error;- }+ });+ }++ resolveRetryBudget(error: unknown) {+ return resolveLLMRetryBudget(this.prepared.provider, error, SERVER_LLM_RETRY_POLICY);+ }++ onRetry({ attempt, delayMs, error, maxAttempts }: LLMTurnRetryInput) {+ log(+ '[%s] LLM call failed with kind=%s (attempt %d/%d), retrying in %dms ...',+ this.operationLogId,+ error.kind,+ attempt,+ maxAttempts,+ delayMs,+ );+ }++ runAttempt({ attempt, events }: LLMTurnAttemptInput) {+ return otelContext.with(this.chatContext, () =>+ this.prepared.runAttempt({+ attempt,+ context: this.prepared.context,+ events,+ maxAttempts: this.maxAttempts,+ model: this.prepared.model,+ onFirstChunk: () => {+ if (this.firstChunkAt === undefined) {+ this.firstChunkAt = Date.now() - this.llmStartTime;+ }+ },+ provider: this.prepared.provider,+ state: this.prepared.state,+ }),+ );+ }++ async waitForRetry(delayMs: number): Promise<void> {+ await sleep(delayMs);}}-export const executeServerCallLlmTurn = (+export const openServerCallLlmTurn = (ctx: RuntimeExecutorContext,prepared: ServerCallLlmExecutionContext,-): Promise<InstructionExecutionResult> => new ServerCallLlmTurn(ctx, prepared).execute();+): LLMTurnSession => new ServerCallLlmTurnSession(ctx, prepared);diff --git a/apps/server/src/modules/AgentRuntime/buildHost.ts b/apps/server/src/modules/AgentRuntime/buildHost.tsindex 629f5def374..89d0f716107 100644--- a/apps/server/src/modules/AgentRuntime/buildHost.ts+++ b/apps/server/src/modules/AgentRuntime/buildHost.ts@@ -56,6 +56,7 @@ export const buildHost = (ctx: RuntimeExecutorContext): AgentRuntimeHost => {ctx.userId,ctx.workspaceId,ctx.topicId,+ ctx.loadAgentState,),stream: new ServerStreamSink(ctx.streamManager, ctx.operationId),subAgent: ctx.execSubAgent ? new ServerSubAgentTransport(ctx) : undefined,diff --git a/packages/agent-runtime/src/executors/callLlm.test.ts b/packages/agent-runtime/src/executors/callLlm.test.tsindex d31e18654b7..2d7bffb3961 100644--- a/packages/agent-runtime/src/executors/callLlm.test.ts+++ b/packages/agent-runtime/src/executors/callLlm.test.ts@@ -4,8 +4,11 @@ import type {AgentRuntimeHost,ContextBuilder,ContextBuildOutput,+ LLMAttemptOutput,LLMTransport,+ LLMTurnSession,MessageTransport,+ OperationStore,StreamSink,} from '../transport';import type { AgentInstructionCallLlm, AgentState } from '../types';@@ -87,17 +90,45 @@ const createContextBuilder = (): ContextBuilder => ({build: vi.fn().mockResolvedValue(contextOutput),});+const createAttemptOutput = (content = 'answer'): LLMAttemptOutput => ({+ answerSalvagedFromReasoning: false,+ content,+ contentParts: [],+ grounding: null,+ hasContentImages: false,+ hasReasoningImages: false,+ imageList: [],+ reasoningParts: [],+ thinkingContent: '',+ toolCalls: [],+ toolsCalling: [],+});++const createTurnSession = (overrides: Partial<LLMTurnSession> = {}): LLMTurnSession => ({+ classifyError: vi.fn().mockReturnValue({ kind: 'stop', message: 'failed' }),+ close: vi.fn(),+ finalize: vi.fn().mockResolvedValue({ events: [], newState: createState() }),+ handleError: vi.fn().mockResolvedValue(undefined),+ maxAttempts: 3,+ resolveRetryBudget: vi.fn().mockReturnValue(2),+ runAttempt: vi.fn().mockResolvedValue({ ok: true, output: createAttemptOutput() }),+ waitForRetry: vi.fn().mockResolvedValue(undefined),+ ...overrides,+});+const createHost = (llm: LLMTransport,messages = createMessageTransport(),stream = createStreamSink(),context = createContextBuilder(),+ operationStore?: OperationStore,): AgentRuntimeHost => ({operation: { operationId: 'op-1', stepIndex: 0 },transports: {context,llm,messages,+ operationStore,stream,},});@@ -109,13 +140,14 @@ describe('callLlm executor', () => {events: [],newState: state,};- const executeTurn = vi.fn().mockResolvedValue(expected);+ const session = createTurnSession({ finalize: vi.fn().mockResolvedValue(expected) });+ const openTurn = vi.fn().mockReturnValue(session);const messages = createMessageTransport();const stream = createStreamSink();const context = createContextBuilder();const host = createHost({- executeTurn,+ openTurn,stream: vi.fn(),},messages,@@ -159,7 +191,7 @@ describe('callLlm executor', () => {provider: 'openai',state,});- expect(executeTurn).toHaveBeenCalledWith({+ expect(openTurn).toHaveBeenCalledWith({assistantMessage: { id: 'assistant-1' },context: contextOutput,model: 'gpt-4',@@ -167,6 +199,12 @@ describe('callLlm executor', () => {state,stepLabel: undefined,});+ expect(session.runAttempt).toHaveBeenCalledWith({ attempt: 1, events: [] });+ expect(session.finalize).toHaveBeenCalledWith({+ events: [],+ output: createAttemptOutput(),+ });+ expect(session.close).toHaveBeenCalledWith(undefined);});it('reuses an existing assistant message without creating a new one', async () => {@@ -175,11 +213,12 @@ describe('callLlm executor', () => {events: [],newState: state,};- const executeTurn = vi.fn().mockResolvedValue(expected);+ const session = createTurnSession({ finalize: vi.fn().mockResolvedValue(expected) });+ const openTurn = vi.fn().mockReturnValue(session);const messages = createMessageTransport();const host = createHost({- executeTurn,+ openTurn,stream: vi.fn(),},messages,@@ -194,30 +233,30 @@ describe('callLlm executor', () => {await expect(callLlm(host)(reuseInstruction, state)).resolves.toBe(expected);expect(messages.createAssistantMessage).not.toHaveBeenCalled();- expect(executeTurn).toHaveBeenCalledWith(+ expect(openTurn).toHaveBeenCalledWith(expect.objectContaining({assistantMessage: { id: 'assistant-existing' },}),);});- it('throws when the LLM transport does not provide executeTurn', async () => {+ it('throws when the LLM transport does not provide openTurn', async () => {const host = createHost({stream: vi.fn(),});await expect(callLlm(host)(instruction, createState())).rejects.toThrow(- 'LLMTransport.executeTurn is required for call_llm executor',+ 'LLMTransport.openTurn is required for call_llm executor',);});it('publishes context build failures without executing the model turn', async () => {const error = new Error('context failed');const context: ContextBuilder = { build: vi.fn().mockRejectedValue(error) };- const executeTurn = vi.fn();+ const openTurn = vi.fn();const stream = createStreamSink();const host = createHost(- { executeTurn, stream: vi.fn() },+ { openTurn, stream: vi.fn() },createMessageTransport(),stream,context,@@ -229,7 +268,7 @@ describe('callLlm executor', () => {phase: 'llm_execution',stepIndex: 0,});- expect(executeTurn).not.toHaveBeenCalled();+ expect(openTurn).not.toHaveBeenCalled();});it('fails before creating an assistant message when the parent message is missing', async () => {@@ -238,7 +277,7 @@ describe('callLlm executor', () => {const stream = createStreamSink();const host = createHost({- executeTurn: vi.fn(),+ openTurn: vi.fn(),stream: vi.fn(),},messages,@@ -268,4 +307,113 @@ describe('callLlm executor', () => {type: 'error',});});++ it('owns retries and publishes stream_retry before finalizing the successful attempt', async () => {+ const state = createState();+ const error = new Error('temporary outage');+ const firstOutput = createAttemptOutput('partial');+ const finalOutput = createAttemptOutput('complete');+ const expected = { events: [], newState: state };+ const runAttempt = vi+ .fn()+ .mockResolvedValueOnce({ error, ok: false, output: firstOutput })+ .mockResolvedValueOnce({ ok: true, output: finalOutput });+ const onRetry = vi.fn();+ const session = createTurnSession({+ classifyError: vi.fn().mockReturnValue({+ code: 'UPSTREAM_TIMEOUT',+ kind: 'retry',+ message: error.message,+ }),+ finalize: vi.fn().mockResolvedValue(expected),+ onRetry,+ runAttempt,+ });+ const stream = createStreamSink();+ const operationStore: OperationStore = {+ clearRunningMark: vi.fn(),+ loadState: vi.fn().mockResolvedValue(null),+ };+ const host = createHost(+ { openTurn: vi.fn().mockReturnValue(session), stream: vi.fn() },+ createMessageTransport(),+ stream,+ createContextBuilder(),+ operationStore,+ );++ await expect(callLlm(host)(instruction, state)).resolves.toBe(expected);++ const retryEvent = {+ data: {+ attempt: 2,+ delayMs: 1000,+ errorType: 'UPSTREAM_TIMEOUT',+ kind: 'retry',+ maxAttempts: 3,+ },+ type: 'stream_retry' as const,+ };+ expect(runAttempt).toHaveBeenNthCalledWith(1, { attempt: 1, events: [retryEvent] });+ expect(runAttempt).toHaveBeenNthCalledWith(2, { attempt: 2, events: [retryEvent] });+ expect(onRetry).toHaveBeenCalledWith({+ attempt: 1,+ delayMs: 1000,+ error: {+ code: 'UPSTREAM_TIMEOUT',+ kind: 'retry',+ message: error.message,+ },+ maxAttempts: 3,+ });+ expect(stream.publishEvent).toHaveBeenCalledWith({+ data: retryEvent.data,+ stepIndex: 0,+ type: 'stream_retry',+ });+ expect(session.waitForRetry).toHaveBeenCalledWith(1000);+ expect(session.finalize).toHaveBeenCalledWith({ events: [retryEvent], output: finalOutput });+ expect(session.handleError).not.toHaveBeenCalled();+ expect(session.close).toHaveBeenCalledWith(undefined);+ });++ it('stops retrying and persists the partial attempt when the operation is interrupted', async () => {+ const state = createState();+ const error = new Error('stream aborted');+ const output = createAttemptOutput('partial');+ const session = createTurnSession({+ classifyError: vi.fn().mockReturnValue({ kind: 'retry', message: error.message }),+ runAttempt: vi.fn().mockResolvedValue({ error, ok: false, output }),+ });+ const operationStore: OperationStore = {+ clearRunningMark: vi.fn(),+ loadState: vi.fn().mockResolvedValue({ ...state, status: 'interrupted' }),+ };+ const stream = createStreamSink();+ const host = createHost(+ { openTurn: vi.fn().mockReturnValue(session), stream: vi.fn() },+ createMessageTransport(),+ stream,+ createContextBuilder(),+ operationStore,+ );++ await expect(callLlm(host)(instruction, state)).rejects.toBe(error);++ expect(session.runAttempt).toHaveBeenCalledTimes(1);+ expect(session.waitForRetry).not.toHaveBeenCalled();+ expect(session.handleError).toHaveBeenCalledWith({+ error,+ events: [],+ interrupted: true,+ output,+ retryBudget: 2,+ });+ expect(session.close).toHaveBeenCalledWith(error);+ expect(stream.publishError).toHaveBeenCalledWith({+ error,+ phase: 'llm_execution',+ stepIndex: 0,+ });+ });});diff --git a/packages/agent-runtime/src/executors/callLlm.ts b/packages/agent-runtime/src/executors/callLlm.tsindex 477dee533e7..318bdbfd21f 100644--- a/packages/agent-runtime/src/executors/callLlm.ts+++ b/packages/agent-runtime/src/executors/callLlm.ts@@ -1,20 +1,121 @@-import type { AgentRuntimeHost, LLMTurnInput } from '../transport';-import type { AgentInstruction, CallLLMPayload, InstructionExecutor } from '../types';+import type {+ AgentRuntimeHost,+ LLMAttemptOutput,+ LLMTurnInput,+ LLMTurnSession,+} from '../transport';+import type { AgentEvent, AgentInstruction, CallLLMPayload, InstructionExecutor } from '../types';+import { getLLMRetryDelayMs, shouldRetryLLM } from '../utils';const CONVERSATION_PARENT_MISSING_ERROR_TYPE = 'ConversationParentMissing';interface LLMCallTransport {- executeTurn: (input: LLMTurnInput) => ReturnType<InstructionExecutor>;+ openTurn: (input: LLMTurnInput) => Promise<LLMTurnSession> | LLMTurnSession;}const requireLLMCallTransport = (host: AgentRuntimeHost) => {const llm = host.transports.llm;- if (!llm?.executeTurn) {- throw new Error('LLMTransport.executeTurn is required for call_llm executor');+ if (!llm?.openTurn) {+ throw new Error('LLMTransport.openTurn is required for call_llm executor');}return llm as NonNullable<AgentRuntimeHost['transports']['llm']> & LLMCallTransport;};+const waitForRetry = (delayMs: number) =>+ new Promise<void>((resolve) => {+ setTimeout(resolve, delayMs);+ });++const isOperationInterrupted = async (host: AgentRuntimeHost) => {+ const operationStore = host.transports.operationStore;+ if (!operationStore?.loadState) return false;++ try {+ const latestState = await operationStore.loadState(host.operation.operationId);+ return latestState?.status === 'interrupted';+ } catch (error) {+ console.error('[call_llm] Failed to load operation state for retry guard:', error);+ return false;+ }+};++const executeTurnSession = async (host: AgentRuntimeHost, session: LLMTurnSession) => {+ const events: AgentEvent[] = [];+ let errorHandled = false;+ let lastOutput: LLMAttemptOutput | undefined;+ let terminalError: unknown;++ try {+ for (let attempt = 1; attempt <= session.maxAttempts; attempt++) {+ const execution = await session.runAttempt({ attempt, events });+ lastOutput = execution.output;++ if (execution.ok) return await session.finalize({ events, output: execution.output });++ const { error } = execution;+ const classified = session.classifyError(error);+ const retryBudget = session.resolveRetryBudget(error);+ let interrupted = await isOperationInterrupted(host);++ if (!interrupted && shouldRetryLLM(classified.kind, attempt, retryBudget)) {+ const delayMs = getLLMRetryDelayMs(attempt);+ const retryEvent: AgentEvent = {+ data: {+ attempt: attempt + 1,+ delayMs,+ errorType: classified.code,+ kind: classified.kind,+ maxAttempts: session.maxAttempts,+ },+ type: 'stream_retry',+ };+ events.push(retryEvent);++ await session.onRetry?.({+ attempt,+ delayMs,+ error: classified,+ maxAttempts: session.maxAttempts,+ });+ await host.transports.stream.publishEvent({+ data: retryEvent.data,+ stepIndex: host.operation.stepIndex,+ type: 'stream_retry',+ });+ await (session.waitForRetry ?? waitForRetry)(delayMs);++ interrupted = await isOperationInterrupted(host);+ if (!interrupted) continue;+ }++ errorHandled = true;+ await session.handleError({+ error,+ events,+ interrupted,+ output: execution.output,+ retryBudget,+ });+ throw error;+ }++ throw new Error('LLM execution retry loop exited unexpectedly');+ } catch (error) {+ terminalError = error;+ if (!errorHandled) {+ await session.handleError({+ error,+ events,+ interrupted: await isOperationInterrupted(host),+ output: lastOutput,+ });+ }+ throw error;+ } finally {+ await session.close(terminalError);+ }+};+const requireContextBuilder = (host: AgentRuntimeHost) => {const context = host.transports.context;if (!context) {@@ -75,10 +176,9 @@ const buildAssistantMessageSeed = (/*** Package-owned `call_llm` executor entry point.*- * The server-specific implementation still lives behind the LLM transport while- * the remaining context/stream/persist internals are broken into narrower- * package-owned ports. The transport executes a prepared turn rather than- * masquerading as another instruction executor.+ * The package prepares the turn and owns retry/interruption orchestration. The+ * host-bound session temporarily retains model execution, tracing, and result+ * persistence until those responsibilities move onto narrower ports.*/export const callLlm =(host: AgentRuntimeHost): InstructionExecutor =>@@ -159,12 +259,22 @@ export const callLlm =throw error;});- return llm.executeTurn({- assistantMessage,- context,- model,- provider,- state,- stepLabel,- });+ try {+ const session = await llm.openTurn({+ assistantMessage,+ context,+ model,+ provider,+ state,+ stepLabel,+ });+ return await executeTurnSession(host, session);+ } catch (error) {+ await transports.stream.publishError?.({+ error,+ phase: 'llm_execution',+ stepIndex: operation.stepIndex,+ });+ throw error;+ }};diff --git a/packages/agent-runtime/src/transport/llm.ts b/packages/agent-runtime/src/transport/llm.tsindex e5308007af2..af7f48133de 100644--- a/packages/agent-runtime/src/transport/llm.ts+++ b/packages/agent-runtime/src/transport/llm.ts@@ -9,6 +9,7 @@ import type {} from '@lobechat/types';import type { AgentEvent, AgentState, CallLLMPayload, InstructionExecutionResult } from '../types';+import type { ClassifiedLLMError } from '../utils';import type { ContextBuildOutput } from './context';import type { RuntimeMessageRef } from './message';@@ -86,6 +87,44 @@ export interface LLMTurnInput {stepLabel?: string;}+export interface LLMTurnAttemptInput {+ attempt: number;+ events: AgentEvent[];+}++export interface LLMTurnErrorInput {+ error: unknown;+ events: AgentEvent[];+ interrupted: boolean;+ output?: LLMAttemptOutput;+ retryBudget?: number;+}++export interface LLMTurnFinalizeInput {+ events: AgentEvent[];+ output: LLMAttemptOutput;+}++export interface LLMTurnRetryInput {+ attempt: number;+ delayMs: number;+ error: ClassifiedLLMError;+ maxAttempts: number;+}++/** Host-bound lifecycle for one logical model turn across all retry attempts. */+export interface LLMTurnSession {+ classifyError: (error: unknown) => ClassifiedLLMError;+ close: (error?: unknown) => Promise<void> | void;+ finalize: (input: LLMTurnFinalizeInput) => Promise<InstructionExecutionResult>;+ handleError: (input: LLMTurnErrorInput) => Promise<void>;+ maxAttempts: number;+ onRetry?: (input: LLMTurnRetryInput) => Promise<void> | void;+ resolveRetryBudget: (error: unknown) => number;+ runAttempt: (input: LLMTurnAttemptInput) => Promise<LLMAttemptExecution>;+ waitForRetry?: (delayMs: number) => Promise<void>;+}+/*** Streams a model completion. Server adapter wraps `initModelRuntimeFromDB` +* `ModelRuntime.chat` + `consumeStreamUntilDone`; the client adapter wraps@@ -97,11 +136,10 @@ export interface LLMTurnInput {*/export interface LLMTransport {/**- * Executes one prepared model turn. The package executor owns instruction- * setup/context while the adapter owns retry and persistence until those- * phases move onto narrower transport ports.+ * Opens a host-bound turn session. The package owns retry orchestration while+ * the session retains host-specific tracing and finalization temporarily.*/- executeTurn?: (input: LLMTurnInput) => Promise<InstructionExecutionResult>;+ openTurn?: (input: LLMTurnInput) => Promise<LLMTurnSession> | LLMTurnSession;/** Executes one model attempt and returns both successful or partial output. */runAttempt?: (input: LLMAttemptInput) => Promise<LLMAttemptExecution>;stream: (