π€― 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(agent-runtime): keep stream error classification instead of collapsing to 500 (#19005)
Arvin Xu618337287fdb
diff --git a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmAttempt.ts b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmAttempt.tsindex 5353642dbaf..2a7ddc4479c 100644--- a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmAttempt.ts+++ b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmAttempt.ts@@ -23,6 +23,7 @@ import type {ModelReasoning,ModelUsage,} from '@lobechat/types';+import { AgentRuntimeErrorType, ChatErrorType } from '@lobechat/types';import { pickString, toRecord } from '@lobechat/utils/object';import type { ModelCompletionFailureReason } from '@/business/server/recordModelCompletionFailure';@@ -58,9 +59,41 @@ interface CreateServerCallLlmAttemptInput {userAgent?: string;}-const createStreamExecutionError = (errorData: unknown) => {+/**+ * Codes a stream `error` payload may legitimately carry in its `type` field.+ *+ * Stream error data is untyped: providers pass their own vocabulary through+ * (`api_error`, `invalid_request_error`, the bare string `error`, β¦), so `type`+ * is only promoted to a classification when it names a code we actually own.+ */+const KNOWN_ERROR_CODES = new Set<string>([+ ...Object.values(AgentRuntimeErrorType),+ ...Object.values(ChatErrorType).map(String),+]);++/**+ * Wrap a stream `error` event payload into a throwable Error.+ *+ * Stream sources emit two shapes. A flat one carries `message` at the top+ * level; the classified one β what provider stream transformers produce for+ * terminal policy rejections β nests the human text under `body` and puts the+ * code in `type`:+ *+ * ```ts+ * { body: { context: {β¦}, message: 'The content was blocked (SAFETY)β¦' }, type: 'ProviderContentPolicyViolation' }+ * ```+ *+ * Both halves of that shape used to be dropped. `message` was read only from+ * the top level, so the entire payload was `JSON.stringify`-ed into the text,+ * and the code was copied onto the Error as `type` β which `formatErrorForState`+ * does not read (it keys off `errorType`, and its `type`-only path deliberately+ * excludes Error instances). A classified provider rejection therefore landed as+ * an opaque bare 500 carrying a JSON blob for a message.+ */+export const createStreamExecutionError = (errorData: unknown) => {const errorRecord = toRecord(errorData);- const message = pickString(errorRecord?.message);+ const body = toRecord(errorRecord?.body);+ const message = pickString(errorRecord?.message) ?? pickString(body?.message);const error = new Error(message ? `LLM stream error: ${message}` : `LLM stream error: ${JSON.stringify(errorData)}`,);@@ -68,6 +101,19 @@ const createStreamExecutionError = (errorData: unknown) => {if (errorRecord) {const { message: _message, ...details } = errorRecord;Object.assign(error, details);++ // Surface the classification under the key the error formatter reads, so a+ // typed stream rejection keeps its code instead of collapsing into a 500.+ const errorType = pickString(errorRecord.errorType) ?? pickString(errorRecord.type);+ if (errorType && KNOWN_ERROR_CODES.has(errorType)) {+ // Hand the payload's `body` over as `_responseBody` in the same step.+ // `formatErrorForState` builds the display body from+ // `_responseBody ?? error ?? <the thrown value>`; without this it would+ // fall through to the Error itself and emit `body: { body: {β¦}, type,+ // errorType }`, pushing `provider` / `context` one level below the+ // `ChatMessageError.body` contract that the renderers read.+ Object.assign(error, { errorType, ...(body ? { _responseBody: body } : {}) });+ }}return error;diff --git a/apps/server/src/modules/AgentRuntime/adapters/streamExecutionError.test.ts b/apps/server/src/modules/AgentRuntime/adapters/streamExecutionError.test.tsnew file mode 100644index 00000000000..7d4b485af96--- /dev/null+++ b/apps/server/src/modules/AgentRuntime/adapters/streamExecutionError.test.ts@@ -0,0 +1,68 @@+import { AgentRuntimeErrorType } from '@lobechat/types';+import { describe, expect, it } from 'vitest';++import { formatErrorForState } from '../formatErrorForState';+import { createStreamExecutionError } from './serverCallLlmAttempt';++describe('createStreamExecutionError', () => {+ // Shape emitted by the Google stream transformer for a terminal policy block.+ const policyBlock = {+ body: {+ context: { finishReason: 'SAFETY' },+ message: 'The content was blocked (SAFETY). Please adjust it and try again.',+ provider: 'google',+ },+ type: AgentRuntimeErrorType.ProviderContentPolicyViolation,+ };++ it('reads the human message out of the nested body instead of stringifying the payload', () => {+ const error = createStreamExecutionError(policyBlock);++ expect(error.message).toBe(+ 'LLM stream error: The content was blocked (SAFETY). Please adjust it and try again.',+ );+ expect(error.message).not.toContain('{');+ });++ it('keeps the classification so the error is not recorded as a bare 500', () => {+ const formatted = formatErrorForState(createStreamExecutionError(policyBlock));++ expect(formatted.type).toBe(AgentRuntimeErrorType.ProviderContentPolicyViolation);+ });++ it('keeps the payload body flat so renderers still find provider and context', () => {+ // The conversation error renderer branches on `body.provider === 'google'`+ // and reads `body.context.finishReason`; nesting the payload one level down+ // would silently drop the Google policy view.+ const formatted = formatErrorForState(createStreamExecutionError(policyBlock));++ expect(formatted.body).toMatchObject({+ context: { finishReason: 'SAFETY' },+ provider: 'google',+ });+ expect((formatted.body as { body?: unknown }).body).toBeUndefined();+ });++ it('still prefers a top-level message when the payload is flat', () => {+ const error = createStreamExecutionError({ message: 'terminated' });++ expect(error.message).toBe('LLM stream error: terminated');+ });++ it('ignores provider-vocabulary type values that are not our codes', () => {+ // OpenAI-compatible upstreams pass their own taxonomy through; promoting it+ // would invent a code that no spec can classify.+ const error = createStreamExecutionError({+ error: { message: '500 API error', type: 'api_error' },+ type: 'error',+ });++ expect((error as { errorType?: string }).errorType).toBeUndefined();+ });++ it('falls back to stringifying when no message can be found anywhere', () => {+ const error = createStreamExecutionError({ code: 42 });++ expect(error.message).toBe('LLM stream error: {"code":42}');+ });+});