Skip to content

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

♻️ refactor(agent-runtime): move empty-completion + reasoning-replay utils into the package (#16460)

Arvin Xu42aa82127b64
diff --git a/apps/server/src/modules/AgentRuntime/ModelEmptyError.ts b/apps/server/src/modules/AgentRuntime/ModelEmptyError.ts
deleted file mode 100644
index 56def9cc582..00000000000
--- a/apps/server/src/modules/AgentRuntime/ModelEmptyError.ts
+++ /dev/null
@@ -1,27 +0,0 @@
-import { AgentRuntimeErrorType } from '@lobechat/types';
-
-/**
- * Thrown by the `call_llm` executor when the model returns an empty completion
- * β€” no text content, no reasoning, no tool calls, no images, and ~0 output
- * tokens. This is the "empty completion" failure mode: after a stalled tool loop the
- * model effectively gives up and emits a blank turn, which the harness used to
- * silently finalize to `done` while persisting an empty assistant message
- * (empty bubble, `status=done, error=null`).
- *
- * The `errorType` field tags it as the retryable `ModelEmptyCompletion` code so
- * that:
- * 1. `classifyLLMError` resolves it to `retry`, letting the executor's LLM
- * retry loop re-attempt the turn (a retry typically yields real content).
- * 2. If every retry is also empty, `formatErrorForState` enriches it into a
- * readable, dashboard-visible terminal error instead of a silent `done`.
- */
-export class ModelEmptyError extends Error {
- readonly errorType = AgentRuntimeErrorType.ModelEmptyCompletion;
-
- constructor(
- message = 'Model returned an empty completion (no content, no tool calls, no output tokens).',
- ) {
- super(message);
- this.name = 'ModelEmptyError';
- }
-}
diff --git a/apps/server/src/modules/AgentRuntime/__tests__/RuntimeExecutors.test.ts b/apps/server/src/modules/AgentRuntime/__tests__/RuntimeExecutors.test.ts
index 0c0d81ea972..251306e3bda 100644
--- a/apps/server/src/modules/AgentRuntime/__tests__/RuntimeExecutors.test.ts
+++ b/apps/server/src/modules/AgentRuntime/__tests__/RuntimeExecutors.test.ts
@@ -1,12 +1,11 @@
import { type AgentState } from '@lobechat/agent-runtime';
import { BRANDING_PROVIDER } from '@lobechat/business-const';
-import { consumeStreamUntilDone } from '@lobechat/model-runtime';
+import { consumeStreamUntilDone, ModelEmptyError } from '@lobechat/model-runtime';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import * as ContextEngineering from '@/server/modules/Mecha/ContextEngineering';
import { initModelRuntimeFromDB } from '@/server/modules/ModelRuntime';
-import { ModelEmptyError } from '../ModelEmptyError';
import { createRuntimeExecutors, type RuntimeExecutorContext } from '../RuntimeExecutors';
const mockCreateCompressionGroup = vi.fn();
@@ -64,26 +63,36 @@ vi.mock('@/server/services/message', () => ({
// @lobechat/model-runtime resolves to @cloud/business-model-runtime which has
// cloud-specific dependencies that are unavailable in the test environment
-vi.mock('@lobechat/model-runtime', () => ({
- // The executor resolves extend params via this helper; an empty result keeps
- // the runtime payload unchanged, matching this suite's pre-existing behavior.
- applyModelExtendParams: vi.fn(() => ({})),
- consumeStreamUntilDone: vi.fn().mockResolvedValue(undefined),
- // `llmErrorClassification.ts` reads these at module-load time; an empty
- // spec map is fine here because this suite never exercises the runtime
- // retry classifier path.
- ERROR_CODE_SPECS: {},
- getErrorCodeSpec: () => undefined,
- isDeepSeekThinkingEligibleModel: (model: string) =>
- typeof model === 'string' &&
- (model.toLowerCase().includes('deepseek-reasoner') ||
- model.toLowerCase().includes('deepseek-v4')),
- isDeepSeekV4FamilyModel: (model: string) =>
- typeof model === 'string' && model.toLowerCase().includes('deepseek-v4'),
- isKimiAlwaysPreserveThinkingModel: (model: string) =>
- /^kimi-k2\.(?:[7-9]|\d{2,})-code(?:$|-)/.test(model),
- refineErrorCode: () => undefined,
-}));
+vi.mock('@lobechat/model-runtime', async () => {
+ // ModelEmptyError + isEmptyModelCompletion are pure (they only depend on
+ // @lobechat/types), so import the real implementations directly from source β€”
+ // bypassing this cloud-package mock β€” so the executor's empty-completion
+ // retry path and these tests share a single class identity for instanceof.
+ const { isEmptyModelCompletion, ModelEmptyError } =
+ await import('../../../../../../packages/model-runtime/src/errors/modelEmptyCompletion');
+ return {
+ // The executor resolves extend params via this helper; an empty result keeps
+ // the runtime payload unchanged, matching this suite's pre-existing behavior.
+ applyModelExtendParams: vi.fn(() => ({})),
+ consumeStreamUntilDone: vi.fn().mockResolvedValue(undefined),
+ // `llmErrorClassification.ts` reads these at module-load time; an empty
+ // spec map is fine here because this suite never exercises the runtime
+ // retry classifier path.
+ ERROR_CODE_SPECS: {},
+ getErrorCodeSpec: () => undefined,
+ isDeepSeekThinkingEligibleModel: (model: string) =>
+ typeof model === 'string' &&
+ (model.toLowerCase().includes('deepseek-reasoner') ||
+ model.toLowerCase().includes('deepseek-v4')),
+ isDeepSeekV4FamilyModel: (model: string) =>
+ typeof model === 'string' && model.toLowerCase().includes('deepseek-v4'),
+ isEmptyModelCompletion,
+ isKimiAlwaysPreserveThinkingModel: (model: string) =>
+ /^kimi-k2\.(?:[7-9]|\d{2,})-code(?:$|-)/.test(model),
+ ModelEmptyError,
+ refineErrorCode: () => undefined,
+ };
+});
vi.mock('@/business/client/model-bank/loadModels', () => ({
loadModels: vi.fn().mockResolvedValue(mockBuiltinModels),
diff --git a/apps/server/src/modules/AgentRuntime/__tests__/llmErrorClassification.test.ts b/apps/server/src/modules/AgentRuntime/__tests__/llmErrorClassification.test.ts
index a015aa5f5a2..2ccff23eaf8 100644
--- a/apps/server/src/modules/AgentRuntime/__tests__/llmErrorClassification.test.ts
+++ b/apps/server/src/modules/AgentRuntime/__tests__/llmErrorClassification.test.ts
@@ -1,7 +1,7 @@
+import { ModelEmptyError } from '@lobechat/model-runtime';
import { describe, expect, it } from 'vitest';
import { classifyLLMError } from '../llmErrorClassification';
-import { ModelEmptyError } from '../ModelEmptyError';
describe('classifyLLMError', () => {
it('should classify rate limit errors as retry', () => {
diff --git a/apps/server/src/modules/AgentRuntime/executorHelpers.ts b/apps/server/src/modules/AgentRuntime/executorHelpers.ts
index de1f5ce67fd..4fbf325fe28 100644
--- a/apps/server/src/modules/AgentRuntime/executorHelpers.ts
+++ b/apps/server/src/modules/AgentRuntime/executorHelpers.ts
@@ -2,8 +2,9 @@ import { type AgentState } from '@lobechat/agent-runtime';
import { LobeActivatorIdentifier } from '@lobechat/builtin-tool-activator';
import { BRANDING_PROVIDER } from '@lobechat/business-const';
import { type OperationToolSet } from '@lobechat/context-engine';
+import { ModelEmptyError } from '@lobechat/model-runtime';
import { type ToolType } from '@lobechat/observability-otel/modules/agent-runtime';
-import { type ChatToolPayload, type UIChatMessage } from '@lobechat/types';
+import { type ChatToolPayload } from '@lobechat/types';
import debug from 'debug';
import { type LobeChatDatabase } from '@/database/type';
@@ -17,7 +18,6 @@ import { archiveToolResultIfNeeded } from '@/server/services/toolExecution/archi
import { type RuntimeExecutorContext } from './context';
import { type LLMErrorKind } from './llmErrorClassification';
-import { ModelEmptyError } from './ModelEmptyError';
export const log = debug('lobe-server:agent-runtime:streaming-executors');
export const timing = debug('lobe-server:agent-runtime:timing');
@@ -43,89 +43,6 @@ const LLM_RETRY_MAX_DELAY_MS = 30_000;
*/
const EMPTY_COMPLETION_MAX_RETRIES = 2;
-/**
- * Output-token count at or below this β€” combined with no content, reasoning,
- * tool calls, or images β€” marks a turn as an empty completion.
- * The observed failure case reported `out=1 token`.
- */
-const EMPTY_COMPLETION_MAX_OUTPUT_TOKENS = 1;
-
-/**
- * Detect the "empty completion" failure mode: the model returns a
- * turn with no text, no reasoning, no tool calls, no images, and ~0 output
- * tokens β€” typically after a stalled tool loop where it effectively gives up.
- * Callers throw `ModelEmptyError` on a hit so the LLM retry loop re-attempts
- * instead of silently finalizing to `done` with a blank assistant message.
- */
-export const isEmptyModelCompletion = (params: {
- content: string;
- imageCount: number;
- outputTokens: number | undefined;
- reasoning: string;
- toolCallCount: number;
-}): boolean => {
- const { content, reasoning, toolCallCount, imageCount, outputTokens } = params;
-
- if (content.trim().length > 0) return false;
- if (reasoning.trim().length > 0) return false;
- if (toolCallCount > 0) return false;
- if (imageCount > 0) return false;
-
- // When the provider reports output tokens, only treat as empty if it's ~0.
- // Guards against rare cases where structured output we don't accumulate into
- // `content`/`reasoning` here (e.g. grounding) still consumed real tokens.
- if (typeof outputTokens === 'number' && outputTokens > EMPTY_COMPLETION_MAX_OUTPUT_TOKENS) {
- return false;
- }
-
- return true;
-};
-
-type ReasoningReplayNode = {
- children?: ReasoningReplayNode[];
- members?: ReasoningReplayNode[];
- reasoning?: unknown;
-};
-
-export const stripAssistantReasoningForReplay = (messages: UIChatMessage[]): UIChatMessage[] => {
- const stripMessage = <T extends ReasoningReplayNode>(message: T): T => {
- let changed = false;
-
- const children = message.children?.map((child) => {
- const strippedChild = stripMessage(child);
- if (strippedChild !== child) changed = true;
- return strippedChild;
- });
-
- const members = message.members?.map((member) => {
- const strippedMember = stripMessage(member);
- if (strippedMember !== member) changed = true;
- return strippedMember;
- });
-
- if ('reasoning' in message) changed = true;
- if (!changed) return message;
-
- const { reasoning: _reasoning, ...messageWithoutReasoning } = message;
-
- return {
- ...messageWithoutReasoning,
- ...(children ? { children } : {}),
- ...(members ? { members } : {}),
- } as T;
- };
-
- let changed = false;
-
- const strippedMessages = messages.map((message) => {
- const strippedMessage = stripMessage(message);
- if (strippedMessage !== message) changed = true;
- return strippedMessage;
- });
-
- return changed ? strippedMessages : messages;
-};
-
export const GEN_AI_FUNCTION_TOOL_TYPE: ToolType = 'function';
type ToolFailureKind = 'replan' | 'retry' | 'stop';
diff --git a/apps/server/src/modules/AgentRuntime/executors/callLlm.ts b/apps/server/src/modules/AgentRuntime/executors/callLlm.ts
index 05e073de7e8..1a5b51bdcf0 100644
--- a/apps/server/src/modules/AgentRuntime/executors/callLlm.ts
+++ b/apps/server/src/modules/AgentRuntime/executors/callLlm.ts
@@ -4,6 +4,7 @@ import {
type CallLLMPayload,
type GeneralAgentCallLLMResultPayload,
type InstructionExecutor,
+ stripAssistantReasoningForReplay,
UsageCounter,
} from '@lobechat/agent-runtime';
import {
@@ -38,7 +39,9 @@ import {
consumeStreamUntilDone,
isDeepSeekThinkingEligibleModel,
isDeepSeekV4FamilyModel,
+ isEmptyModelCompletion,
isKimiAlwaysPreserveThinkingModel,
+ ModelEmptyError,
type ModelExtendParams,
} from '@lobechat/model-runtime';
import {
@@ -84,7 +87,6 @@ import {
buildPostProcessUrl,
buildToolDiscoveryConfig,
getLLMRetryDelayMs,
- isEmptyModelCompletion,
isOperationInterrupted,
log,
resolveLLMMaxAttempts,
@@ -92,13 +94,11 @@ import {
resolveRuntimeHistoryCount,
shouldRetryLLM,
sleep,
- stripAssistantReasoningForReplay,
timing,
} from '../executorHelpers';
import { formatErrorEventData } from '../formatErrorEventData';
import { classifyLLMError } from '../llmErrorClassification';
import { createConversationParentMissingError } from '../messagePersistErrors';
-import { ModelEmptyError } from '../ModelEmptyError';
export const callLlm =
(ctx: RuntimeExecutorContext): InstructionExecutor =>
diff --git a/apps/server/src/modules/AgentRuntime/formatErrorForState.test.ts b/apps/server/src/modules/AgentRuntime/formatErrorForState.test.ts
index b4dafd2df20..c9b74617bc5 100644
--- a/apps/server/src/modules/AgentRuntime/formatErrorForState.test.ts
+++ b/apps/server/src/modules/AgentRuntime/formatErrorForState.test.ts
@@ -1,8 +1,8 @@
+import { ModelEmptyError } from '@lobechat/model-runtime';
import { AgentRuntimeErrorType, ChatErrorType } from '@lobechat/types';
import { describe, expect, it } from 'vitest';
import { formatErrorForState } from './formatErrorForState';
-import { ModelEmptyError } from './ModelEmptyError';
describe('formatErrorForState', () => {
describe('input normalization', () => {
diff --git a/packages/agent-runtime/src/utils/index.ts b/packages/agent-runtime/src/utils/index.ts
index 9e88d101666..43d407b6842 100644
--- a/packages/agent-runtime/src/utils/index.ts
+++ b/packages/agent-runtime/src/utils/index.ts
@@ -1,4 +1,5 @@
export * from './messageSelectors';
+export * from './replay';
export * from './status';
export * from './stepContextComputer';
export * from './tokenCounter';
diff --git a/packages/agent-runtime/src/utils/replay.ts b/packages/agent-runtime/src/utils/replay.ts
new file mode 100644
index 00000000000..0d847b379ef
--- /dev/null
+++ b/packages/agent-runtime/src/utils/replay.ts
@@ -0,0 +1,56 @@
+import type { UIChatMessage } from '@lobechat/types';
+
+type ReasoningReplayNode = {
+ children?: ReasoningReplayNode[];
+ members?: ReasoningReplayNode[];
+ reasoning?: unknown;
+};
+
+/**
+ * Strip stored assistant `reasoning` from messages before they are replayed
+ * back into a model request. Recurses into `children` / `members` (grouped /
+ * council messages) and returns the same array reference when nothing changed,
+ * so callers can cheaply detect a no-op.
+ *
+ * Used by the `call_llm` stage when the reasoning-replay gate is off: most
+ * providers reject or mis-handle prior-turn reasoning fed back as input, so it
+ * is dropped unless replay is explicitly enabled.
+ */
+export const stripAssistantReasoningForReplay = (messages: UIChatMessage[]): UIChatMessage[] => {
+ const stripMessage = <T extends ReasoningReplayNode>(message: T): T => {
+ let changed = false;
+
+ const children = message.children?.map((child) => {
+ const strippedChild = stripMessage(child);
+ if (strippedChild !== child) changed = true;
+ return strippedChild;
+ });
+
+ const members = message.members?.map((member) => {
+ const strippedMember = stripMessage(member);
+ if (strippedMember !== member) changed = true;
+ return strippedMember;
+ });
+
+ if ('reasoning' in message) changed = true;
+ if (!changed) return message;
+
+ const { reasoning: _reasoning, ...messageWithoutReasoning } = message;
+
+ return {
+ ...messageWithoutReasoning,
+ ...(children ? { children } : {}),
+ ...(members ? { members } : {}),
+ } as T;
+ };
+
+ let changed = false;
+
+ const strippedMessages = messages.map((message) => {
+ const strippedMessage = stripMessage(message);
+ if (strippedMessage !== message) changed = true;
+ return strippedMessage;
+ });
+
+ return changed ? strippedMessages : messages;
+};
diff --git a/packages/model-runtime/src/errors/index.ts b/packages/model-runtime/src/errors/index.ts
index f2c90700b9a..2e66b9ce3ff 100644
--- a/packages/model-runtime/src/errors/index.ts
+++ b/packages/model-runtime/src/errors/index.ts
@@ -1,5 +1,6 @@
export { ErrorClassifier, type ErrorClassifierType } from './classifier';
export { isUserSideError, matchErrorPattern, type MatchInput, type MatchResult } from './match';
+export { isEmptyModelCompletion, ModelEmptyError } from './modelEmptyCompletion';
export { ERROR_PATTERNS, type ErrorPattern } from './patterns';
export { refineErrorCode, type RefineErrorInput } from './refine';
export {
diff --git a/packages/model-runtime/src/errors/modelEmptyCompletion.ts b/packages/model-runtime/src/errors/modelEmptyCompletion.ts
new file mode 100644
index 00000000000..bb25937a712
--- /dev/null
+++ b/packages/model-runtime/src/errors/modelEmptyCompletion.ts
@@ -0,0 +1,67 @@
+import { AgentRuntimeErrorType } from '@lobechat/types';
+
+/**
+ * Thrown when the model returns an empty completion β€” no text content, no
+ * reasoning, no tool calls, no images, and ~0 output tokens. This is the "empty
+ * completion" failure mode: after a stalled tool loop the model effectively
+ * gives up and emits a blank turn, which the harness used to silently finalize
+ * to `done` while persisting an empty assistant message (empty bubble,
+ * `status=done, error=null`).
+ *
+ * The `errorType` field tags it as the retryable `ModelEmptyCompletion` code
+ * (see `errors/specs.ts`, which classifies it as a retryable `provider` error)
+ * so that:
+ * 1. an LLM-error classifier resolves it to `retry`, letting the agent's
+ * `call_llm` retry loop re-attempt the turn (a retry typically yields real
+ * content).
+ * 2. If every retry is also empty, the terminal-error formatter enriches it
+ * into a readable, dashboard-visible error instead of a silent `done`.
+ */
+export class ModelEmptyError extends Error {
+ readonly errorType = AgentRuntimeErrorType.ModelEmptyCompletion;
+
+ constructor(
+ message = 'Model returned an empty completion (no content, no tool calls, no output tokens).',
+ ) {
+ super(message);
+ this.name = 'ModelEmptyError';
+ }
+}
+
+/**
+ * Output-token count at or below this β€” combined with no content, reasoning,
+ * tool calls, or images β€” marks a turn as an empty completion.
+ * The observed failure case reported `out=1 token`.
+ */
+const EMPTY_COMPLETION_MAX_OUTPUT_TOKENS = 1;
+
+/**
+ * Detect the "empty completion" failure mode: the model returns a turn with no
+ * text, no reasoning, no tool calls, no images, and ~0 output tokens β€”
+ * typically after a stalled tool loop where it effectively gives up. Callers
+ * throw {@link ModelEmptyError} on a hit so the LLM retry loop re-attempts
+ * instead of silently finalizing to `done` with a blank assistant message.
+ */
+export const isEmptyModelCompletion = (params: {
+ content: string;
+ imageCount: number;
+ outputTokens: number | undefined;
+ reasoning: string;
+ toolCallCount: number;
+}): boolean => {
+ const { content, reasoning, toolCallCount, imageCount, outputTokens } = params;
+
+ if (content.trim().length > 0) return false;
+ if (reasoning.trim().length > 0) return false;
+ if (toolCallCount > 0) return false;
+ if (imageCount > 0) return false;
+
+ // When the provider reports output tokens, only treat as empty if it's ~0.
+ // Guards against rare cases where structured output we don't accumulate into
+ // `content`/`reasoning` here (e.g. grounding) still consumed real tokens.
+ if (typeof outputTokens === 'number' && outputTokens > EMPTY_COMPLETION_MAX_OUTPUT_TOKENS) {
+ return false;
+ }
+
+ return true;
+};
diff --git a/packages/model-runtime/src/index.ts b/packages/model-runtime/src/index.ts
index f536478b365..8c4768bd467 100644
--- a/packages/model-runtime/src/index.ts
+++ b/packages/model-runtime/src/index.ts
@@ -21,10 +21,12 @@ export {
type ErrorSeverity,
formatErrorRef,
getErrorCodeSpec,
+ isEmptyModelCompletion,
isUserSideError,
matchErrorPattern,
type MatchInput,
type MatchResult,
+ ModelEmptyError,
parseErrorRef,
refineErrorCode,
type RefineErrorInput,