🤯 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
🐛 fix: stop misreporting refusals and dropped streams as empty output (#19925)
YuTengjing565df269b564
diff --git a/apps/server/src/modules/AgentRuntime/__tests__/RuntimeExecutors.test.ts b/apps/server/src/modules/AgentRuntime/__tests__/RuntimeExecutors.test.tsindex 330324e3981..17fdd86049b 100644--- a/apps/server/src/modules/AgentRuntime/__tests__/RuntimeExecutors.test.ts+++ b/apps/server/src/modules/AgentRuntime/__tests__/RuntimeExecutors.test.ts@@ -81,7 +81,7 @@ vi.mock('@lobechat/model-runtime', async () => {// retry path and these tests share a single class identity for instanceof.const { isEmptyModelCompletion, ModelEmptyError } =await import('../../../../../../packages/model-runtime/src/errors/modelEmptyCompletion');- const { ModelRefusalError } =+ const { isModelRefusalFinishReason, ModelRefusalError } =await import('../../../../../../packages/model-runtime/src/errors/modelRefusal');// Same treatment: the reasoning-config merge is pure, and the replay gate// reads its output (e.g. the DeepSeek V4 thinking opt-out), so use the real@@ -116,6 +116,7 @@ vi.mock('@lobechat/model-runtime', async () => {isDeepSeekV4FamilyModel: (model: string) =>typeof model === 'string' && model.toLowerCase().includes('deepseek-v4'),isEmptyModelCompletion,+ isModelRefusalFinishReason,isKimiAlwaysPreserveThinkingModel: (model: string) =>/^kimi-k2\.(?:[7-9]|\d{2,})-code(?:$|-)/.test(model),ModelEmptyError,diff --git a/apps/server/src/modules/AgentRuntime/__tests__/formatErrorEventData.test.ts b/apps/server/src/modules/AgentRuntime/__tests__/formatErrorEventData.test.tsindex 039b831e97a..23e5021d6d5 100644--- a/apps/server/src/modules/AgentRuntime/__tests__/formatErrorEventData.test.ts+++ b/apps/server/src/modules/AgentRuntime/__tests__/formatErrorEventData.test.ts@@ -1,3 +1,4 @@+import { ModelEmptyError, ModelRefusalError } from '@lobechat/model-runtime';import { AgentRuntimeErrorType } from '@lobechat/types';import { describe, expect, it } from 'vitest';@@ -156,6 +157,24 @@ describe('formatErrorEventData', () => {expect(out.error).toBe('Conversation parent message msg_abc no longer exists.');});+ it.each([+ ['ModelRefusalError', ModelRefusalError, AgentRuntimeErrorType.ModelRefusal],+ ['ModelEmptyError', ModelEmptyError, AgentRuntimeErrorType.ModelEmptyCompletion],+ ])('keeps %s diagnostics in the event body', (_, ErrorClass, errorType) => {+ const diagnostics = {+ finishReason: 'sensitive',+ model: 'glm-5.3-flash',+ provider: 'lobehub',+ };+ const out = formatErrorEventData(new ErrorClass(undefined, diagnostics), 'call_llm');++ expect(out).toMatchObject({+ body: { diagnostics },+ errorType,+ phase: 'call_llm',+ });+ });+it('preserves a custom errorType even when no .cause PG info exists', () => {const err = Object.assign(new Error('rate limited'), {errorType: 'ProviderRateLimited',diff --git a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmAttempt.test.ts b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmAttempt.test.tsindex 6368f459048..a75050dfdb8 100644--- a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmAttempt.test.ts+++ b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmAttempt.test.ts@@ -22,7 +22,7 @@ const attachTraceIdLater = async (error: { _responseBody?: unknown }) => {vi.mock('@lobechat/model-runtime', async () => {const { isEmptyModelCompletion, ModelEmptyError } =await import('../../../../../../packages/model-runtime/src/errors/modelEmptyCompletion');- const { ModelRefusalError } =+ const { isModelRefusalFinishReason, ModelRefusalError } =await import('../../../../../../packages/model-runtime/src/errors/modelRefusal');const { consumeStreamUntilDone } =await import('../../../../../../packages/model-runtime/src/utils/consumeStream');@@ -30,6 +30,7 @@ vi.mock('@lobechat/model-runtime', async () => {return {consumeStreamUntilDone,isEmptyModelCompletion,+ isModelRefusalFinishReason,ModelEmptyError,ModelRefusalError,};@@ -621,6 +622,20 @@ describe('ServerCallLlmAttempt', () => {);});+ it('classifies a blank GLM sensitive-content stop as ModelRefusal', async () => {+ const { attempt } = createAttempt(async ({ callback }) => {+ await callback?.onCompletion?.({ finishReason: 'sensitive', text: '' });+ });++ await expect(attempt.execute()).rejects.toMatchObject({+ diagnostics: expect.objectContaining({ finishReason: 'sensitive' }),+ errorType: 'ModelRefusal',+ });+ expect(recordModelCompletionFailureMock).toHaveBeenCalledWith(+ expect.objectContaining({ reason: 'refusal' }),+ );+ });+it('records an unexplained blank completion before throwing ModelEmptyError', async () => {const { attempt } = createAttempt(async ({ callback }) => {await callback?.onCompletion?.({diff --git a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmAttempt.ts b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmAttempt.tsindex 1e44692f67f..20d23c99d41 100644--- a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmAttempt.ts+++ b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmAttempt.ts@@ -12,6 +12,7 @@ import type {import {consumeStreamUntilDone,isEmptyModelCompletion,+ isModelRefusalFinishReason,ModelEmptyError,ModelRefusalError,} from '@lobechat/model-runtime';@@ -398,7 +399,7 @@ export class ServerCallLlmAttempt {private async assertNonEmptyCompletion() {const imageCount = this.getOutputImageCount();- const isRefusal = this.finishReason?.toLowerCase() === 'refusal';+ const isRefusal = isModelRefusalFinishReason(this.finishReason);/*** A refusal needs ordinary response output to count as a successful* completion. Provider-internal reasoning alone must not turn a blankdiff --git a/apps/server/src/modules/AgentRuntime/formatErrorEventData.ts b/apps/server/src/modules/AgentRuntime/formatErrorEventData.tsindex c7017ec0aaa..dc2fe6e8d89 100644--- a/apps/server/src/modules/AgentRuntime/formatErrorEventData.ts+++ b/apps/server/src/modules/AgentRuntime/formatErrorEventData.ts@@ -1,3 +1,4 @@+import { ModelEmptyError, ModelRefusalError } from '@lobechat/model-runtime';import { pickNonEmptyString, toRecord } from '@lobechat/utils/object';import { formatErrorForState } from './formatErrorForState';@@ -32,8 +33,16 @@ export const formatErrorEventData = (error: unknown, phase: string) => {const payload = toRecord(error);const rawPayloadErrorType = payload?.errorType ?? payload?.type;const payloadErrorType = isErrorType(rawPayloadErrorType) ? rawPayloadErrorType : undefined;- const structuredError =- error instanceof Error || payloadErrorType === undefined+ /**+ * Runtime completion errors carry their provider/model diagnostics on the Error instance.+ * Keep that body so the client can persist it and render provider-specific error UI;+ * other Error instances keep the flat shape.+ */+ const isRuntimeCompletionError =+ error instanceof ModelEmptyError || error instanceof ModelRefusalError;+ const structuredError = isRuntimeCompletionError+ ? formatErrorForState(error)+ : error instanceof Error || payloadErrorType === undefined? undefined: formatErrorForState(payload);const body = structuredError?.body;diff --git a/packages/model-runtime/src/core/RouterRuntime/chatAttempt.test.ts b/packages/model-runtime/src/core/RouterRuntime/chatAttempt.test.tsindex b24811c84af..0a412262aff 100644--- a/packages/model-runtime/src/core/RouterRuntime/chatAttempt.test.ts+++ b/packages/model-runtime/src/core/RouterRuntime/chatAttempt.test.ts@@ -180,6 +180,62 @@ describe('observeChatAttempt', () => {expect(finished).toHaveBeenCalledWith(expect.objectContaining({ outcome: 'completed' }));});+ it.each([+ ['refusal', 'ModelRefusalError'],+ ['sensitive', 'ModelRefusalError'],+ ['end_turn', 'ModelEmptyError'],+ ] as const)(+ 'reports an empty completion stopped by %s as %s',+ async (finishReason, errorName) => {+ const finished = vi.fn();+ const attemptRun = observeChatAttempt(+ async ({ callback }) => {+ await callback?.onFinal?.({ finishReason, text: '' });+ return new Response(null);+ },+ undefined,+ attempt,+ true,+ finished,+ );++ await expect(attemptRun).rejects.toMatchObject({ name: errorName });+ expect(finished).toHaveBeenCalledWith(+ expect.objectContaining({+ error: expect.objectContaining({+ diagnostics: expect.objectContaining({ finishReason }),+ }),+ outcome: 'empty',+ }),+ );+ },+ );++ it('reports a reasoning-only refusal as a refusal', async () => {+ const finished = vi.fn();+ const attemptRun = observeChatAttempt(+ async ({ callback }) => {+ await callback?.onReasoningPart?.({ content: 'reason', partType: 'text' });+ await callback?.onFinal?.({ finishReason: 'refusal', text: '' });+ return new Response(null);+ },+ undefined,+ attempt,+ true,+ finished,+ );++ await expect(attemptRun).rejects.toMatchObject({ name: 'ModelRefusalError' });+ expect(finished).toHaveBeenCalledWith(+ expect.objectContaining({+ error: expect.objectContaining({+ diagnostics: expect.objectContaining({ reasoningLength: 6 }),+ }),+ outcome: 'empty',+ }),+ );+ });+it('adds attempt identity without replacing provider performance', async () => {let now = 1000;vi.spyOn(Date, 'now').mockImplementation(() => now);diff --git a/packages/model-runtime/src/core/RouterRuntime/chatAttempt.ts b/packages/model-runtime/src/core/RouterRuntime/chatAttempt.tsindex 2967c721027..6f976a2ac3d 100644--- a/packages/model-runtime/src/core/RouterRuntime/chatAttempt.ts+++ b/packages/model-runtime/src/core/RouterRuntime/chatAttempt.ts@@ -1,7 +1,12 @@import type { ModelUsage } from '@lobechat/types';import { AgentRuntimeErrorType } from '@lobechat/types';-import { isEmptyModelCompletion, ModelEmptyError } from '../../errors';+import {+ isEmptyModelCompletion,+ isModelRefusalFinishReason,+ ModelEmptyError,+ ModelRefusalError,+} from '../../errors';import type { ChatMethodOptions, ChatStreamCallbacks, OnFinishData } from '../../types';import type { ModelRuntimeDiagnostics } from '../../types/providerDiagnostics';import { AgentRuntimeError } from '../../utils/createError';@@ -201,30 +206,45 @@ export const observeChatAttempt = async (const finalContent = content || latestFinishData.text;const finalReasoning = reasoning || getReasoningContent(latestFinishData);const finalToolCallCount = Math.max(latestFinishData.toolsCalling?.length ?? 0, toolCallCount);+ /**+ * A refusal needs ordinary response output to count as a successful completion.+ * Provider-internal reasoning alone must not turn a blank refusal into a success.+ */+ const isRefusal = isModelRefusalFinishReason(latestFinishData.finishReason);const empty = isEmptyModelCompletion({content: finalContent,hasGrounding: Boolean(latestFinishData.grounding ?? grounding),imageCount,outputTokens: latestFinishData.usage?.totalOutputTokens ?? observedUsage?.totalOutputTokens,- reasoning: finalReasoning,+ reasoning: isRefusal ? '' : finalReasoning,toolCallCount: finalToolCallCount,});if (!empty) return finish('completed');+ const diagnostics = {+ contentLength: finalContent.length,+ cost: latestFinishData.usage?.cost,+ finishReason: latestFinishData.finishReason,+ imageCount,+ model: attempt.model,+ outputTokens: latestFinishData.usage?.totalOutputTokens ?? observedUsage?.totalOutputTokens,+ provider: attempt.providerId,+ reasoningLength: finalReasoning.length,+ toolCallCount: finalToolCallCount,+ };++ /**+ * A blank turn stopped by a provider refusal or moderation finish reason (e.g. Anthropic+ * `refusal`, GLM `sensitive`) is a policy decision, not a provider malfunction. Keep the+ * `empty` outcome for route metrics, but surface the refusal so callers can show a+ * policy-specific message instead of the generic empty-completion error.+ */return finish('empty',- new ModelEmptyError(undefined, {- contentLength: finalContent.length,- cost: latestFinishData.usage?.cost,- finishReason: latestFinishData.finishReason,- imageCount,- model: attempt.model,- outputTokens: latestFinishData.usage?.totalOutputTokens ?? observedUsage?.totalOutputTokens,- provider: attempt.providerId,- reasoningLength: finalReasoning.length,- toolCallCount: finalToolCallCount,- }),+ isRefusal+ ? new ModelRefusalError(undefined, diagnostics)+ : new ModelEmptyError(undefined, diagnostics),);};diff --git a/packages/model-runtime/src/core/openaiCompatibleFactory/nonStreamToStream.test.ts b/packages/model-runtime/src/core/openaiCompatibleFactory/nonStreamToStream.test.tsindex 06be6983ce2..9927e9cedee 100644--- a/packages/model-runtime/src/core/openaiCompatibleFactory/nonStreamToStream.test.ts+++ b/packages/model-runtime/src/core/openaiCompatibleFactory/nonStreamToStream.test.ts@@ -465,6 +465,46 @@ describe('nonStreamToStream', () => {]);});+ it('should preserve function calls in a non-streaming response', async () => {+ const functionCall = {+ arguments: '{"description":"Check menus"}',+ call_id: 'call_001',+ id: 'fc_001',+ name: 'lobe-agent____callSubAgent',+ status: 'completed',+ type: 'function_call',+ };+ const mockResponse = {+ id: 'resp_tool_only',+ output: [{ id: 'rs_001', summary: [], type: 'reasoning' }, functionCall],+ status: 'completed',+ } as unknown as OpenAI.Responses.Response;++ const stream = transformResponseAPIToStream(mockResponse);+ const reader = stream.getReader();+ const events: OpenAI.Responses.ResponseStreamEvent[] = [];++ while (true) {+ const { value, done } = await reader.read();+ if (done) break;+ events.push(value);+ }++ expect(events).toEqual([+ {+ item: functionCall,+ output_index: 1,+ sequence_number: 1,+ type: 'response.output_item.added',+ },+ {+ response: mockResponse,+ sequence_number: 999,+ type: 'response.completed',+ },+ ]);+ });+it('should preserve encrypted reasoning in a non-streaming response', async () => {const reasoning = {encrypted_content: 'encrypted-signature',diff --git a/packages/model-runtime/src/core/openaiCompatibleFactory/nonStreamToStream.ts b/packages/model-runtime/src/core/openaiCompatibleFactory/nonStreamToStream.tsindex b6c980b78ef..c580dcd2605 100644--- a/packages/model-runtime/src/core/openaiCompatibleFactory/nonStreamToStream.ts+++ b/packages/model-runtime/src/core/openaiCompatibleFactory/nonStreamToStream.ts@@ -130,6 +130,20 @@ export const transformResponseAPIToStream = (data: OpenAI.Responses.Response) =>}break;}+ /**+ * A completed function call already carries its full arguments. The stream parser+ * reads them from `output_item.added`, so no argument deltas are needed; dropping+ * this item would turn a tool-call-only response into an empty completion.+ */+ case 'function_call': {+ controller.enqueue({+ item: output,+ output_index: outputIndex,+ sequence_number: outputIndex,+ type: 'response.output_item.added',+ } as OpenAI.Responses.ResponseOutputItemAddedEvent);+ break;+ }}});}diff --git a/packages/model-runtime/src/core/streams/anthropic.test.ts b/packages/model-runtime/src/core/streams/anthropic.test.tsindex 3d16d7ffd01..63569303af5 100644--- a/packages/model-runtime/src/core/streams/anthropic.test.ts+++ b/packages/model-runtime/src/core/streams/anthropic.test.ts@@ -917,4 +917,45 @@ describe('AnthropicStream', () => {].map((item) => `${item}\n`),);});+ it('should report a dropped connection as a stream error instead of ending normally', async () => {+ // @ts-ignore+ const mockAnthropicStream: Stream = {+ [Symbol.asyncIterator]() {+ let count = 0;+ return {+ next: async () => {+ if (count++ === 0) {+ return {+ done: false,+ value: { type: 'message_start', message: { id: 'message_1', usage: {} } },+ };+ }+ throw new TypeError('terminated');+ },+ };+ },+ };++ const onErrorMock = vi.fn();+ const onFinalMock = vi.fn();+ const protocolStream = AnthropicStream(mockAnthropicStream, {+ callbacks: { onError: onErrorMock, onFinal: onFinalMock },+ payload: { apiMode: 'messages', model: 'deepseek-flash', provider: 'deepseek' },+ });++ const decoder = new TextDecoder();+ const chunks: string[] = [];+ // @ts-ignore+ for await (const chunk of protocolStream) {+ chunks.push(decoder.decode(chunk, { stream: true }));+ }++ expect(chunks).toContain('event: error\n');+ expect(onErrorMock).toHaveBeenCalledWith(+ expect.objectContaining({ message: 'terminated', type: 'ProviderBizError' }),+ );+ expect(onFinalMock).toHaveBeenCalledWith(+ expect.objectContaining({ error: expect.objectContaining({ message: 'terminated' }) }),+ );+ });});diff --git a/packages/model-runtime/src/core/streams/anthropic.ts b/packages/model-runtime/src/core/streams/anthropic.tsindex b4cb4147ede..b9dedccb604 100644--- a/packages/model-runtime/src/core/streams/anthropic.ts+++ b/packages/model-runtime/src/core/streams/anthropic.ts@@ -1,8 +1,9 @@import type Anthropic from '@anthropic-ai/sdk';import type { Stream } from '@anthropic-ai/sdk/streaming';-import type { ChatCitationItem } from '@lobechat/types';+import type { ChatCitationItem, ChatMessageError } from '@lobechat/types';import type { ChatStreamCallbacks } from '../../types';+import { AgentRuntimeErrorType } from '../../types/error';import { convertAnthropicUsage } from '../usageConverters';import type {ChatPayloadForTransformStream,@@ -14,8 +15,10 @@ import type {import {convertIterableToStream,createCallbacksTransformer,+ createFirstErrorHandleTransformer,createSSEProtocolTransformer,createTokenSpeedCalculator,+ FIRST_CHUNK_ERROR_KEY,} from './protocol';export const transformAnthropicStream = (@@ -23,6 +26,30 @@ export const transformAnthropicStream = (context: StreamContext,payload?: ChatPayloadForTransformStream,): StreamProtocolChunk | StreamProtocolChunk[] => {+ /**+ * `convertIterableToStream` turns an SDK iterator failure (e.g. `TypeError: terminated` when+ * the upstream connection drops mid-stream) into an error chunk. Without surfacing it here the+ * chunk fell through as unknown data, the stream closed normally, and the dropped connection+ * was misreported as an empty completion instead of an interrupted, fallback-eligible one.+ */+ if (FIRST_CHUNK_ERROR_KEY in chunk) {+ const {+ [FIRST_CHUNK_ERROR_KEY]: _,+ name: _name,+ stack: _stack,+ ...body+ } = chunk as Record<string, unknown>;+ const errorData = {+ body,+ message: typeof body.message === 'string' ? body.message : JSON.stringify(body),+ type:+ typeof body.errorType === 'string'+ ? (body.errorType as typeof AgentRuntimeErrorType.ProviderBizError)+ : AgentRuntimeErrorType.ProviderBizError,+ } satisfies ChatMessageError;+ return { data: errorData, id: 'first_chunk_error', type: 'error' };+ }+// maybe need another structure to add support for multiple choicesswitch (chunk.type) {case 'message_start': {@@ -267,6 +294,7 @@ export const AnthropicStream = (transformAnthropicStream(chunk, ctx, payload);return readableStream+ .pipeThrough(createFirstErrorHandleTransformer(undefined, payload?.provider)).pipeThrough(createTokenSpeedCalculator(transformWithPayload, {enableStreaming,diff --git a/packages/model-runtime/src/errors/index.ts b/packages/model-runtime/src/errors/index.tsindex d3c1890c903..de6bf1a79d0 100644--- a/packages/model-runtime/src/errors/index.ts+++ b/packages/model-runtime/src/errors/index.ts@@ -3,7 +3,7 @@ export { ErrorClassifier, type ErrorClassifierType } from './classifier';export { getRuntimeErrorI18nKey, type RuntimeErrorI18nKey } from './i18nKey';export { isUserSideError, matchErrorPattern, type MatchInput, type MatchResult } from './match';export { isEmptyModelCompletion, ModelEmptyError } from './modelEmptyCompletion';-export { ModelRefusalError } from './modelRefusal';+export { isModelRefusalFinishReason, ModelRefusalError } from './modelRefusal';export { normalizeChatMessageError } from './normalizeChatMessageError';export { ERROR_PATTERNS, type ErrorPattern } from './patterns';export { refineErrorCode, type RefineErrorInput } from './refine';diff --git a/packages/model-runtime/src/errors/modelRefusal.ts b/packages/model-runtime/src/errors/modelRefusal.tsindex 68ac4092e3d..ae493b950dc 100644--- a/packages/model-runtime/src/errors/modelRefusal.ts+++ b/packages/model-runtime/src/errors/modelRefusal.ts@@ -4,6 +4,28 @@ import type { ModelEmptyCompletionDiagnostics } from './modelEmptyCompletion';export type ModelRefusalDiagnostics = ModelEmptyCompletionDiagnostics;+/**+ * Terminal finish reasons that mean the provider declined to answer or blocked the output.+ * - `refusal`: Anthropic (and OpenAI-compatible proxies relaying it)+ * - `content_filter`: OpenAI / Azure OpenAI+ * - `sensitive`: Zhipu GLM+ * - `safety`, `prohibited_content`, `blocklist`, `spii`: Google Gemini / Vertex AI+ *+ * `recitation` is excluded: it is a copyright stop, not a policy refusal of the request.+ */+const MODEL_REFUSAL_FINISH_REASONS = new Set([+ 'blocklist',+ 'content_filter',+ 'prohibited_content',+ 'refusal',+ 'safety',+ 'sensitive',+ 'spii',+]);++export const isModelRefusalFinishReason = (finishReason?: string | null): boolean =>+ Boolean(finishReason && MODEL_REFUSAL_FINISH_REASONS.has(finishReason.toLowerCase()));+/*** Thrown when the provider explicitly refuses an otherwise empty completion.* Refusals with user-visible text remain normal completions so the provider'sdiff --git a/packages/model-runtime/src/index.ts b/packages/model-runtime/src/index.tsindex 67e19b43a5d..dbbcbb55ffe 100644--- a/packages/model-runtime/src/index.ts+++ b/packages/model-runtime/src/index.ts@@ -23,6 +23,7 @@ export {getErrorCodeSpec,getRuntimeErrorI18nKey,isEmptyModelCompletion,+ isModelRefusalFinishReason,isUserSideError,matchErrorPattern,type MatchInput,