๐คฏ 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: normalize agent message errors and structured IM replies (#19676)
Arvin Xu33244b9a926c
diff --git a/apps/server/src/modules/AgentRuntime/formatErrorForState.test.ts b/apps/server/src/modules/AgentRuntime/formatErrorForState.test.tsindex 03ac464f703..8a1b23b2af6 100644--- a/apps/server/src/modules/AgentRuntime/formatErrorForState.test.ts+++ b/apps/server/src/modules/AgentRuntime/formatErrorForState.test.ts@@ -5,6 +5,20 @@ import { describe, expect, it } from 'vitest';import { formatErrorForState, readErrorBudgetContext } from './formatErrorForState';describe('formatErrorForState', () => {+ it('classifies an already-wrapped error using its nested provider message', () => {+ const error = {+ body: { error: { message: 'insufficient quota' }, provider: 'openai' },+ type: AgentRuntimeErrorType.ProviderBizError,+ };+ const result = formatErrorForState(error);+ expect(result).toMatchObject({+ attribution: 'user',+ body: error.body,+ type: AgentRuntimeErrorType.InsufficientQuota,+ });+ expect(formatErrorForState(result)).toEqual(result);+ });+describe('input normalization', () => {it('handles ChatCompletionErrorPayload โ extracts errorType and message', () => {const result = formatErrorForState({diff --git a/apps/server/src/modules/AgentRuntime/formatErrorForState.ts b/apps/server/src/modules/AgentRuntime/formatErrorForState.tsindex f597550bc5b..b11ab5e283f 100644--- a/apps/server/src/modules/AgentRuntime/formatErrorForState.ts+++ b/apps/server/src/modules/AgentRuntime/formatErrorForState.ts@@ -1,210 +1,12 @@-import { getErrorCodeSpec, refineErrorCode } from '@lobechat/model-runtime';-import {- AgentRuntimeErrorType,- type ChatErrorBudgetContext,- ChatErrorType,- type ChatMessageError,-} from '@lobechat/types';-import { isRecord } from '@lobechat/utils';+import { normalizeHeterogeneousMessageError } from '@lobechat/heterogeneous-agents/errors';+import { normalizeChatMessageError } from '@lobechat/model-runtime/errors';+import type { ChatErrorBudgetContext, ChatMessageError } from '@lobechat/types';+import { isRecord } from '@lobechat/utils/object';import { formatPgError, pgErrorType, unwrapPgError } from './pgError';-/** Pull a usable HTTP status out of the nested upstream error object. */-const extractHttpStatus = (body: unknown): number | undefined => {- if (!body || typeof body !== 'object') return undefined;- const b = body as { error?: { status?: unknown }; status?: unknown; statusCode?: unknown };- if (typeof b.status === 'number') return b.status;- if (typeof b.statusCode === 'number') return b.statusCode;- if (b.error && typeof b.error === 'object' && typeof b.error.status === 'number') {- return b.error.status;- }- return undefined;-};--const extractProvider = (body: unknown): string | undefined => {- if (!body || typeof body !== 'object') return undefined;- const p = (body as { provider?: unknown }).provider;- return typeof p === 'string' ? p : undefined;-};--const extractMessage = (value: unknown): string | undefined => {- if (!isRecord(value)) return undefined;-- const message = value.message;- if (typeof message === 'string' && message) return message;-- const nestedError = value.error;- if (isRecord(nestedError)) {- const nestedMessage = nestedError.message;- if (typeof nestedMessage === 'string' && nestedMessage) return nestedMessage;- }-};--interface ChatCompletionErrorPayloadLike {- _responseBody?: unknown;- budget?: unknown;- error?: unknown;- errorType: ChatMessageError['type'];- message?: string;- provider?: unknown;-}--const mergePayloadError = (- sourceBody: Record<string, unknown>,- payload: ChatCompletionErrorPayloadLike,-): unknown | undefined => {- if (payload._responseBody === undefined || payload.error === undefined) return undefined;- if (!('error' in sourceBody)) return payload.error;- if (isRecord(sourceBody.error) && isRecord(payload.error)) {- return { ...payload.error, ...sourceBody.error };- }-};--const buildPayloadBody = (- payload: ChatCompletionErrorPayloadLike,- originalError: unknown,- message: string,-): unknown => {- // Runtime payloads often keep UI context (for example quota hints) next to- // `error`, while `error` itself only carries the display message. Merge both- // layers so normalizing `{ errorType, error }` does not drop the fields the- // chat error renderer needs later.- const sourceBody = payload._responseBody ?? payload.error ?? originalError;- const context: Record<string, unknown> = {};-- if (payload.budget !== undefined) context.budget = payload.budget;- if (typeof payload.provider === 'string') context.provider = payload.provider;-- if (isRecord(sourceBody)) {- const payloadError = mergePayloadError(sourceBody, payload);-- return {- ...sourceBody,- // `_responseBody` is the display-facing body, but gateway/model-runtime- // still carries status/provider details in `error` for some failures:- // `{ _responseBody: { error: { message } }, error: { status: 402 } }`.- ...(payloadError === undefined ? {} : { error: payloadError }),- ...(payload.budget !== undefined && !('budget' in sourceBody)- ? { budget: payload.budget }- : {}),- ...(typeof payload.provider === 'string' && !('provider' in sourceBody)- ? { provider: payload.provider }- : {}),- ...('message' in sourceBody ? {} : { message }),- };- }-- return {- ...context,- ...(sourceBody === undefined ? {} : { error: sourceBody }),- message,- };-};--/**- * Cap a stack before it lands in `agent_operations.error` / trace snapshots.- * The top frames identify the throw site; the rest is runtime plumbing that- * would only bloat every stored error row.- */-const STACK_MAX_CHARS = 1000;--const truncateStack = (stack: string | undefined): string | undefined => {- if (!stack) return undefined;- return stack.length > STACK_MAX_CHARS ? `${stack.slice(0, STACK_MAX_CHARS)}โฆ` : stack;-};--/**- * Merge classification metadata from `ERROR_CODE_SPECS` onto a normalized- * `ChatMessageError`. Codes that aren't in the spec table (fallbacks like- * `InternalServerError`, or numeric ChatErrorType values) pass through- * unchanged โ every classification field stays optional.- *- * Keeping enrichment in one place means downstream consumers (`agent_operations.error`- * JSONB, S3 trace snapshots, agent-gateway WS push, dashboards) all get the- * same shape without re-running pattern matching themselves.- */-const enrichWithSpec = (formatted: ChatMessageError): ChatMessageError => {- // Generic `ProviderBizError` is re-derived from the message / HTTP status into- // a more specific code before enrichment, so the catch-all doesn't swallow- // rate-limits, network drops, quota, etc. Specific codes pass through.- const refined = refineErrorCode({- errorType: String(formatted.type),- httpStatus: extractHttpStatus(formatted.body),- message: formatted.message,- provider: extractProvider(formatted.body),- });- const type = (refined ?? formatted.type) as ChatMessageError['type'];-- // `getErrorCodeSpec` is keyed by `ILobeAgentRuntimeErrorType` strings; coerce- // because `ChatMessageError['type']` widens to include numeric `ChatErrorType`- // values, which simply miss the lookup and pass through unenriched.- const spec = getErrorCodeSpec(String(type));- if (!spec) return formatted;-- return {- ...formatted,- attribution: spec.attribution,- category: spec.category,- countAsFailure: spec.countAsFailure,- httpStatus: spec.httpStatus,- isFallback: spec.isFallback ?? false,- numericId: spec.numericId,- retryable: spec.retryable,- severity: spec.severity,- type,- };-};--/**- * Normalize an arbitrary thrown value into `ChatMessageError`, then attach- * classification metadata from `ERROR_CODE_SPECS` so the resulting object- * is self-describing for everything downstream of the runtime catch block.- *- * Handles four input shapes:- *- * 1. `ChatCompletionErrorPayload` โ what `model-runtime` throws on LLM- * failures: `{ errorType, error, provider?, message? }`.- * 2. Already-normalized `ChatMessageError` (`{ type, message?, body? }`)- * โ re-enriched in place so the helper is safe to call twice (the inner- * `runtime.step()` non-throwing error path and the outer `executeStep`- * catch can both run through here without double-wrapping).- * 3. Standard `Error` instance โ wrapped as `InternalServerError`.- * 4. Anything else โ a loosely-typed `{ message }` body (e.g. a heterogeneous CLI- * agent's wire `error` event data `{ code, message, stderr }`) or a raw string โ- * mapped to `AgentRuntimeError` with a real extracted message. This branch is- * the single canonical replacement for the hetero-specific `toChatMessageError`.- */+/** Add server-only database diagnostics before shared message normalization. */export const formatErrorForState = (error: unknown): ChatMessageError => {- if (error && typeof error === 'object' && 'errorType' in error) {- const payload = error as ChatCompletionErrorPayloadLike;- const message =- (payload.message && payload.message !== 'error' ? payload.message : undefined) ??- extractMessage(payload._responseBody) ??- extractMessage(payload.error) ??- String(payload.errorType);-- return enrichWithSpec({- body: buildPayloadBody(payload, error, message),- message,- type: payload.errorType,- });- }-- // Path 2: already-normalized ChatMessageError shape โ has `type` but not- // `errorType`, and isn't a thrown Error instance. Common when the inner- // runtime.step() catch has already stuffed a partial ChatMessageError into- // `newState.error` and the outer service is just topping it up.- if (- error &&- typeof error === 'object' &&- !(error instanceof Error) &&- 'type' in error &&- (typeof (error as { type: unknown }).type === 'string' ||- typeof (error as { type: unknown }).type === 'number')- ) {- return enrichWithSpec(error as ChatMessageError);- }-if (error instanceof Error) {const pg = unwrapPgError(error);if (pg) {@@ -224,41 +26,8 @@ export const formatErrorForState = (error: unknown): ChatMessageError => {type: pgErrorType(pg) as ChatMessageError['type'],};}-- // Unclassified harness throw: nothing upstream recognized it, so `name` +- // `message` are all the triage signal there is โ and for a `SyntaxError`- // out of some `JSON.parse` those two say nothing about WHERE it blew up.- // Persist the stack (bounded; frames are what matter, not a runaway trace)- // the way the pg branch already persists `pg`, so a recurring 500 is- // locatable from the stored operation instead of needing a live repro.- return enrichWithSpec({- body: { name: error.name, stack: truncateStack(error.stack) },- message: error.message,- type: ChatErrorType.InternalServerError,- });}-- // Path 4: arbitrary thrown value. A loosely-typed object (no `errorType`, no- // string/number `type`) keeps its body and contributes its `.message` rather- // than being stringified to '[object Object]' โ this is what the heterogeneous- // CLI agents emit on the wire (`{ code, message, stderr }`). A raw string or any- // other primitive becomes a `{ message }` body. Mirrors the former- // `toChatMessageError`, then runs through `enrichWithSpec` so even these get- // classification (the bare hetero formatter never did).- if (isRecord(error)) {- return enrichWithSpec({- body: error,- message: extractMessage(error) ?? 'Agent runtime error',- type: AgentRuntimeErrorType.AgentRuntimeError,- });- }-- const message = typeof error === 'string' ? error : 'Agent runtime error';- return enrichWithSpec({- body: { message },- message,- type: AgentRuntimeErrorType.AgentRuntimeError,- });+ return normalizeHeterogeneousMessageError(normalizeChatMessageError(error));};const readFiniteNumber = (value: unknown): number | undefined =>diff --git a/apps/server/src/services/agentRuntime/CompletionLifecycle.ts b/apps/server/src/services/agentRuntime/CompletionLifecycle.tsindex 8d5de20eeac..e1193041d9d 100644--- a/apps/server/src/services/agentRuntime/CompletionLifecycle.ts+++ b/apps/server/src/services/agentRuntime/CompletionLifecycle.ts@@ -1,4 +1,5 @@import { isParkedStatus } from '@lobechat/agent-runtime';+import { readHeterogeneousErrorContext } from '@lobechat/heterogeneous-agents/errors';import { RequestTrigger } from '@lobechat/types';import { deserializeParts } from '@lobechat/utils';import { isRecord } from '@lobechat/utils/object';@@ -1208,6 +1209,7 @@ export class CompletionLifecycle {duration,errorAttribution: formattedError?.attribution,errorBudget: readErrorBudgetContext(formattedError),+ errorHeterogeneous: readHeterogeneousErrorContext(formattedError),errorDetail: state?.error,errorMessage: this.extractErrorMessage(state?.error) || String(state?.error || ''),errorType: formattedError?.type === undefined ? undefined : String(formattedError.type),diff --git a/apps/server/src/services/agentRuntime/__tests__/CompletionLifecycle.test.ts b/apps/server/src/services/agentRuntime/__tests__/CompletionLifecycle.test.tsindex 0111f67e0d5..3491e753cfb 100644--- a/apps/server/src/services/agentRuntime/__tests__/CompletionLifecycle.test.ts+++ b/apps/server/src/services/agentRuntime/__tests__/CompletionLifecycle.test.ts@@ -441,6 +441,32 @@ describe('CompletionLifecycle.buildLifecycleEvent', () => {expect(event.agentId).toBe('a');});+ it('preserves safe external-agent context on completion hooks', () => {+ const { event } = callBuild(+ {+ error: {+ type: 'AgentRuntimeError',+ body: {+ agentType: 'claude-code',+ code: 'rate_limit',+ details: { kind: 'usage_limit' },+ stderr: 'secret path',+ rateLimitInfo: { status: 'rejected', rateLimitType: 'seven_day', resetsAt: 1789826400 },+ },+ },+ origin: { agentId: 'agent-1', userId: 'user-1' },+ },+ 'error',+ );+ expect(event.errorAttribution).toBe('user');+ expect(event.errorHeterogeneous).toEqual({+ agentType: 'claude-code',+ kind: 'usage_limit',+ rateLimitType: 'seven_day',+ resetsAt: 1789826400,+ });+ });+it('populates errorType + attribution from the normalized error on the error path', () => {// Regression: the event previously carried only errorDetail/errorMessage, so// bot reply renderers never saw the stable code/attribution and always felldiff --git a/apps/server/src/services/bot/AgentBridgeService.ts b/apps/server/src/services/bot/AgentBridgeService.tsindex cfd8c61ef76..45cd537505a 100644--- a/apps/server/src/services/bot/AgentBridgeService.ts+++ b/apps/server/src/services/bot/AgentBridgeService.ts@@ -1450,6 +1450,7 @@ export class AgentBridgeService {replyLocale,event.errorAttribution,event.errorBudget,+ event.errorHeterogeneous,);// Wrap in `{ markdown }` so the Chat SDK adapter sets the// platform's markdown parse_mode (e.g. Telegram `Markdown`,diff --git a/apps/server/src/services/bot/BotCallbackService.ts b/apps/server/src/services/bot/BotCallbackService.tsindex d4d3100eda9..1744512c126 100644--- a/apps/server/src/services/bot/BotCallbackService.ts+++ b/apps/server/src/services/bot/BotCallbackService.ts@@ -1,6 +1,6 @@import { randomUUID } from 'node:crypto';-import type { ChatErrorBudgetContext } from '@lobechat/types';+import type { ChatErrorBudgetContext, ChatErrorHeterogeneousContext } from '@lobechat/types';import debug from 'debug';import type { MessengerPlatform } from '@/config/messenger';@@ -97,6 +97,7 @@ export interface BotCallbackBody {* Forwarded verbatim from the agent lifecycle event.*/errorBudget?: ChatErrorBudgetContext;+ errorHeterogeneous?: ChatErrorHeterogeneousContext;errorMessage?: string;errorType?: string;executionTimeMs?: number;@@ -474,6 +475,7 @@ export class BotCallbackService {lastAssistantContent,errorAttribution,errorBudget,+ errorHeterogeneous,errorMessage,errorType,operationId,@@ -494,6 +496,7 @@ export class BotCallbackService {replyLocale,errorAttribution,errorBudget,+ errorHeterogeneous,);const errorText = client.formatMarkdown?.(errorBody) ?? errorBody;if (deliveredChunkCount < 1) {diff --git a/apps/server/src/services/bot/__tests__/renderHeterogeneousError.test.ts b/apps/server/src/services/bot/__tests__/renderHeterogeneousError.test.tsnew file mode 100644index 00000000000..d3360f1ee47--- /dev/null+++ b/apps/server/src/services/bot/__tests__/renderHeterogeneousError.test.ts@@ -0,0 +1,54 @@+import { HETERO_ERROR_SPECS } from '@lobechat/heterogeneous-agents/errors';+import { describe, expect, it } from 'vitest';++import { renderAgentError } from '../replyTemplate';++describe('heterogeneous IM errors', () => {+ it.each(Object.values(HETERO_ERROR_SPECS))(+ 'renders known kind $kind with its H reference',+ (spec) => {+ for (const lng of ['en-US', 'zh-CN'] as const) {+ const reply = renderAgentError(+ 'AgentRuntimeError',+ 'secret CLI stderr',+ 'op-test',+ lng,+ 'harness',+ undefined,+ {+ agentType: 'claude-code',+ kind: spec.kind,+ rateLimitType: 'seven_day',+ resetsAt: 1789826400,+ },+ );+ expect(reply).toContain(`H${spec.numericId}`);+ expect(reply).toContain('op-test');+ expect(reply).not.toContain('secret CLI stderr');+ expect(reply).not.toContain('undefined');+ expect(reply).not.toContain('{{');+ if (spec.kind !== 'usage_limit') expect(reply).not.toContain('2026-09-19');+ }+ },+ );+ it('renders a weekly quota reset instead of an internal-error retry prompt', () => {+ const reply = renderAgentError(+ 'AgentRuntimeError',+ undefined,+ 'op-quota',+ 'zh-CN',+ 'harness',+ undefined,+ {+ agentType: 'claude-code',+ kind: 'usage_limit',+ rateLimitType: 'seven_day',+ resetsAt: 1789826400,+ },+ );+ expect(reply).toContain('ๆฌๅจ้ขๅบฆๅทฒ็จๅฎ');+ expect(reply).toContain('2026-09-19 14:00');+ expect(reply).toContain('UTC');+ expect(reply).not.toContain('E8001');+ });+});diff --git a/apps/server/src/services/bot/__tests__/replyTemplate.test.ts b/apps/server/src/services/bot/__tests__/replyTemplate.test.tsindex 9d324cddbc7..dcfd2fd724e 100644--- a/apps/server/src/services/bot/__tests__/replyTemplate.test.ts+++ b/apps/server/src/services/bot/__tests__/replyTemplate.test.ts@@ -1,3 +1,4 @@+import { ERROR_CODE_SPECS, formatErrorRef } from '@lobechat/model-runtime/errors';import { describe, expect, it } from 'vitest';import type { RenderStepParams } from '../replyTemplate';@@ -364,6 +365,53 @@ describe('replyTemplate', () => {// ==================== renderAgentError ====================describe('renderAgentError', () => {+ it.each(Object.values(ERROR_CODE_SPECS).filter((spec) => !spec.isFallback))(+ 'renders actionable localized copy and a stable reference for $code',+ (spec) => {+ for (const locale of ['en-US', 'zh-CN'] as const) {+ const output = renderAgentError(+ spec.code,+ 'private upstream payload',+ 'op-known',+ locale,+ );+ expect(output).toContain(formatErrorRef(spec.code));+ expect(output).toContain('op-known');+ expect(output).not.toContain('private upstream payload');+ expect(output).not.toContain('{{');+ expect(output.split('\n').length).toBeGreaterThanOrEqual(3);+ }+ },+ );++ it('renders a known request error instead of the attribution fallback', () => {+ const output = renderAgentError(+ 'RequestBodyTooLarge',+ 'secret upstream payload',+ 'op-size',+ 'en-US',+ 'harness',+ );+ expect(output).toContain('request is too large');+ expect(output).toContain('Error code: `E');+ expect(output).toContain('op-size');+ expect(output).not.toContain('Something went wrong on our side');+ expect(output).not.toContain('secret upstream payload');+ });++ it('classifies a legacy envelope before choosing IM copy', () => {+ const output = renderAgentError('ProviderBizError', 'insufficient quota', 'op-quota');+ expect(output).toContain('Provider quota exhausted');+ expect(output).toContain('Error code: `E');+ });++ it('renders a known request error in Chinese with a stable reference', () => {+ const output = renderAgentError('RequestBodyTooLarge', undefined, 'op-size', 'zh-CN');+ expect(output).toContain('้่ฏฏ็ :');+ expect(output).not.toContain('Something went wrong');+ expect(output).not.toContain('RequestBodyTooLarge');+ });+it('returns the friendly NoAvailableProvider copy and appends the operation id footer', () => {const out = renderAgentError('NoAvailableProvider', undefined, 'op-abc');expect(out).toContain('No model provider configured');@@ -563,12 +611,13 @@ describe('replyTemplate', () => {});});- it('maps both QuotaLimitReached and InsufficientQuota to the same quota copy', () => {+ it('resolves the legacy rate-limit alias separately from exhausted quota', () => {const a = renderAgentError('QuotaLimitReached', undefined, 'op-1');const b = renderAgentError('InsufficientQuota', undefined, 'op-1');- expect(a).toContain('quota');+ expect(a).toContain('Too many requests');expect(b).toContain('quota');- expect(a).toBe(b);+ expect(a).toContain('E3001');+ expect(b).toContain('E2001');});it('uses friendly copy for command connection close failures wrapped as 500 errors', () => {@@ -620,7 +669,7 @@ describe('replyTemplate', () => {'en-US','system',);- expect(en).toContain('temporary system error');+ expect(en).toContain('session state was unavailable');expect(en).not.toContain('model provider');expect(en).not.toMatch(/switch to a different model/i);expect(en).toContain('op-1');@@ -632,7 +681,7 @@ describe('replyTemplate', () => {'zh-CN','system',);- expect(zh).toContain('ไธดๆถ็ณป็ป้่ฏฏ');+ expect(zh).toContain('ไผ่ฏ็ถๆไธๅฏ็จ');});it('still gives ProviderNetworkError the provider-specific network copy', () => {@@ -685,7 +734,9 @@ describe('replyTemplate', () => {const unavailable = renderAgentError('ProviderServiceUnavailable', undefined, 'op-1');const noChannel = renderAgentError('NoAvailableChannel', undefined, 'op-1');expect(unavailable).toContain('temporarily unavailable');- expect(unavailable).toBe(noChannel);+ expect(noChannel).toContain('temporarily unavailable');+ expect(unavailable).toContain('E3002');+ expect(noChannel).toContain('E3003');expect(renderAgentError('RateLimitExceeded', undefined, 'op-1')).toContain('Too many requests',diff --git a/apps/server/src/services/bot/renderHeterogeneousError.ts b/apps/server/src/services/bot/renderHeterogeneousError.tsnew file mode 100644index 00000000000..cd6d7e620cc--- /dev/null+++ b/apps/server/src/services/bot/renderHeterogeneousError.ts@@ -0,0 +1,48 @@+import {+ getHeterogeneousTypeLabel,+ isLocalHeterogeneousType,+} from '@lobechat/heterogeneous-agents';+import { formatHeteroErrorId, HETERO_ERROR_SPECS } from '@lobechat/heterogeneous-agents/errors';+import type { ChatErrorHeterogeneousContext } from '@lobechat/types';++import english from '@/locales/default/modelRuntime';++import chinese from '../../../../../locales/zh-CN/modelRuntime.json';+import type { BotReplyLocale } from './platforms/const';++/** Render only allowlisted context. Raw CLI stderr and paths stay in diagnostics. */+export const renderHeterogeneousError = (+ context: ChatErrorHeterogeneousContext | undefined,+ lng?: BotReplyLocale,+): string | undefined => {+ if (+ !context ||+ !isLocalHeterogeneousType(context.agentType) ||+ !Object.hasOwn(HETERO_ERROR_SPECS, context.kind)+ )+ return;+ const spec = HETERO_ERROR_SPECS[context.kind as keyof typeof HETERO_ERROR_SPECS];+ const catalog: Record<string, string> = lng === 'zh-CN' ? chinese : english;+ const prefix = `heterogeneous.${spec.kind}`;+ const agent = getHeterogeneousTypeLabel(context.agentType) ?? 'Agent';+ const lines = [+ `**${agent}: ${catalog[`${prefix}.title`]}**`,+ catalog[`${prefix}.description`].replaceAll('{{agent}}', agent),+ ];+ if (spec.kind === 'usage_limit') {+ if (context.rateLimitType === 'seven_day' || context.rateLimitType === 'five_hour') {+ lines.push(catalog[`heterogeneous.window.${context.rateLimitType}`]);+ }+ if (+ typeof context.resetsAt === 'number' &&+ Number.isFinite(context.resetsAt) &&+ context.resetsAt > 0 &&+ context.resetsAt < 8640000000000+ ) {+ const time = new Date(context.resetsAt * 1000).toISOString().replace('T', ' ').slice(0, 16);+ lines.push(catalog['heterogeneous.reset'].replace('{{time}}', time));+ }+ }+ lines.push(`${lng === 'zh-CN' ? '้่ฏฏ็ ' : 'Error code'}: \`${formatHeteroErrorId(spec.kind)}\``);+ return lines.join('\n');+};diff --git a/apps/server/src/services/bot/renderThrownError.ts b/apps/server/src/services/bot/renderThrownError.tsindex cbcfc68d898..75de9718bec 100644--- a/apps/server/src/services/bot/renderThrownError.ts+++ b/apps/server/src/services/bot/renderThrownError.ts@@ -1,3 +1,5 @@+import { readHeterogeneousErrorContext } from '@lobechat/heterogeneous-agents/errors';+import {formatErrorForState,readErrorBudgetContext,@@ -44,5 +46,6 @@ export const renderThrownAgentError = (replyLocale,formatted.attribution ?? 'harness',readErrorBudgetContext(formatted),+ readHeterogeneousErrorContext(formatted),);};diff --git a/apps/server/src/services/bot/replyTemplate.ts b/apps/server/src/services/bot/replyTemplate.tsindex b7a892dfe45..d1b6d1103e2 100644--- a/apps/server/src/services/bot/replyTemplate.ts+++ b/apps/server/src/services/bot/replyTemplate.ts@@ -1,5 +1,13 @@-import type { ChatErrorBudgetContext } from '@lobechat/types';+import {+ formatErrorRef,+ getErrorCodeSpec,+ normalizeChatMessageError,+} from '@lobechat/model-runtime/errors';+import type { ChatErrorBudgetContext, ChatErrorHeterogeneousContext } from '@lobechat/types';+import modelRuntimeEnglish from '@/locales/default/modelRuntime';++import modelRuntimeChinese from '../../../../../locales/zh-CN/modelRuntime.json';import type { StepPresentationData } from '../agentRuntime/types';import { getExtremeAck } from './ackPhrases';// Import from the leaf modules (`const` / `utils`) instead of the@@ -8,6 +16,7 @@ import { getExtremeAck } from './ackPhrases';// Telegram Guest outbound path import this template for localized copy.import { type BotReplyLocale } from './platforms/const';import { formatDuration } from './platforms/utils';+import { renderHeterogeneousError } from './renderHeterogeneousError';// Use raw Unicode emoji instead of Chat SDK emoji placeholders,// because bot-callback webhooks send via DiscordPlatformClient directly@@ -717,14 +726,44 @@ export function renderAgentError(lng?: BotReplyLocale,attribution?: string,budget?: ChatErrorBudgetContext,+ heterogeneous?: ChatErrorHeterogeneousContext,): string {const strings = getSystemStrings(lng);+ const heteroReply = renderHeterogeneousError(heterogeneous, lng);+ if (heteroReply) return appendOperationId(heteroReply, operationId);++ const normalized = normalizeChatMessageError({+ message: errorMessage,+ type: errorType ?? 'AgentRuntimeError',+ });+ // Classify legacy generic envelopes before selecting channel-specific copy.+ // Unknown inputs retain the caller's fallback behavior.+ const spec = getErrorCodeSpec(String(normalized.type));+ if (spec && !spec.isFallback) {+ errorType = spec.code;+ attribution = spec.attribution;+ }+ const withReference = (value: string) => {+ const reference = formatErrorRef(errorType);+ const footer = reference+ ? `\n${lng === 'zh-CN' ? '้่ฏฏ็ ' : 'Error code'}: \`${reference}\``+ : '';+ return appendOperationId(`${value}${footer}`, operationId);+ };if (isCommandConnectionClosedError(errorType, errorMessage)) {- return appendOperationId(strings.errorCommandConnectionClosed, operationId);+ return withReference(strings.errorCommandConnectionClosed);}const friendlyKey = errorType ? FRIENDLY_ERROR_BY_TYPE[errorType] : undefined;+ if (!friendlyKey && spec && !spec.isFallback) {+ // Reuse the same maintained translations as message error cards. Never+ // interpolate raw provider error text into a shared IM channel.+ const catalog: Record<string, string> =+ lng === 'zh-CN' ? modelRuntimeChinese : modelRuntimeEnglish;+ const copy = catalog[spec.code];+ if (copy && !copy.includes('{{')) return withReference(`${strings.error}\n${copy}`);+ }const stringKey =(friendlyKey && BUDGET_ADMISSION_KEYS.has(friendlyKey) && budget?.budgetTypeAtError? BUDGET_SCOPE_ERROR.get(budget.budgetTypeAtError)@@ -734,7 +773,7 @@ export function renderAgentError(if (stringKey) {const value = strings[stringKey];if (typeof value === 'string') {- return appendOperationId(value, operationId);+ return withReference(value);}}diff --git a/apps/server/src/services/heterogeneousAgent/__tests__/index.test.ts b/apps/server/src/services/heterogeneousAgent/__tests__/index.test.tsindex 1306578b48a..e4c3f0b4919 100644--- a/apps/server/src/services/heterogeneousAgent/__tests__/index.test.ts+++ b/apps/server/src/services/heterogeneousAgent/__tests__/index.test.ts@@ -108,6 +108,20 @@ const createService = (describe('HeterogeneousAgentService', () => {describe('normalizeHeterogeneousFinishError', () => {+ it('enriches a flattened weekly limit with the stable quota fields', () => {+ expect(+ normalizeHeterogeneousFinishError('claude-code', {+ message: "You've hit your weekly limit ยท resets 10pm (Asia/Shanghai)",+ type: 'AgentRuntimeError',+ }),+ ).toMatchObject({+ errorRef: 'H2001',+ attribution: 'user',+ retryable: false,+ body: { agentType: 'claude-code', code: 'rate_limit', details: { kind: 'usage_limit' } },+ });+ });+it('classifies a flattened Claude Code login failure for the frontend status guide', () => {expect(normalizeHeterogeneousFinishError('claude-code', {@@ -120,6 +134,7 @@ describe('HeterogeneousAgentService', () => {code: 'auth_required',stderr: 'Not logged in ยท Please run /login',},+ errorRef: 'H1001',type: 'AgentRuntimeError',});});@@ -145,7 +160,7 @@ describe('HeterogeneousAgentService', () => {type: 'AgentRuntimeError',};- expect(normalizeHeterogeneousFinishError('claude-code', error)).toBe(error);+ expect(normalizeHeterogeneousFinishError('claude-code', error)).toMatchObject(error);});});diff --git a/apps/server/src/services/heterogeneousAgent/index.ts b/apps/server/src/services/heterogeneousAgent/index.tsindex 0a45d5b80b9..096d4f152bd 100644--- a/apps/server/src/services/heterogeneousAgent/index.ts+++ b/apps/server/src/services/heterogeneousAgent/index.ts@@ -6,6 +6,7 @@ import {isHeteroStatusGuideErrorData,type LocalHeterogeneousAgentType,} from '@lobechat/heterogeneous-agents';+import { normalizeHeterogeneousMessageError } from '@lobechat/heterogeneous-agents/errors';import { ThreadStatus } from '@lobechat/types';import debug from 'debug';@@ -99,7 +100,18 @@ export const normalizeHeterogeneousFinishError = (agentType: HeterogeneousAgentType,error: HeterogeneousFinishError | undefined,): HeterogeneousFinishError | undefined => {- if (!error || isHeteroStatusGuideErrorData(error.body)) return error;+ if (!error) return error;+ const normalized = normalizeHeterogeneousMessageError(+ { ...error, type: 'AgentRuntimeError' },+ agentType,+ );+ if (normalized.errorRef)+ return {+ ...normalized,+ message: normalized.message ?? error.message,+ type: 'AgentRuntimeError',+ };+ if (isHeteroStatusGuideErrorData(error.body)) return error;const body = error.body;const bodyDetails = body@@ -112,11 +124,11 @@ export const normalizeHeterogeneousFinishError = (if (!classified) return error;- return {+ return normalizeHeterogeneousMessageError({body: { ...classified },message: classified.message,type: 'AgentRuntimeError',- };+ }) as HeterogeneousFinishError;};/**diff --git a/apps/server/src/services/message/__tests__/index.integration.test.ts b/apps/server/src/services/message/__tests__/index.integration.test.tsindex bedb46aaf43..de116f46638 100644--- a/apps/server/src/services/message/__tests__/index.integration.test.ts+++ b/apps/server/src/services/message/__tests__/index.integration.test.ts@@ -267,7 +267,7 @@ describe('MessageService Integration Tests', () => {expect(result.messages![0].content).toBe('updated content');});- it('should persist message errors and return them in queried messages', async () => {+ it('should persist normalized message errors and return them in queried messages', async () => {const messageService = new MessageService(serverDB, userId);await serverDB.insert(agents).values({ id: 'agent-1', userId });@@ -304,7 +304,31 @@ describe('MessageService Integration Tests', () => {expect(result.success).toBe(true);expect(result.messages).toHaveLength(1);- expect(result.messages![0].error).toEqual(messageError);+ const expectedError = {+ ...messageError,+ attribution: 'user',+ body: {+ ...messageError.body,+ details: { kind: 'auth_required' },+ },+ category: 'auth',+ countAsFailure: false,+ errorRef: 'H1001',+ httpStatus: 470,+ isFallback: false,+ numericId: 1001,+ retryable: false,+ severity: 'warning',+ };++ expect(result.messages![0].error).toEqual(expectedError);++ const [persistedMessage] = await serverDB+ .select({ error: messages.error })+ .from(messages)+ .where(eq(messages.id, 'msg-err-1'));++ expect(persistedMessage.error).toEqual(expectedError);});});diff --git a/apps/server/src/services/message/__tests__/index.test.ts b/apps/server/src/services/message/__tests__/index.test.tsindex 4178c416fff..cb2eafc7a73 100644--- a/apps/server/src/services/message/__tests__/index.test.ts+++ b/apps/server/src/services/message/__tests__/index.test.ts@@ -300,6 +300,24 @@ describe('MessageService', () => {});describe('updateMessage', () => {+ it('normalizes a known error from a legacy client before persistence', async () => {+ await messageService.updateMessage(+ 'msg-error',+ {+ error: { body: { message: 'insufficient quota' }, type: 'ProviderBizError' },+ },+ {},+ );+ expect(mockMessageModel.update).toHaveBeenCalledWith('msg-error', {+ error: expect.objectContaining({ attribution: 'user', type: 'InsufficientQuota' }),+ });+ });++ it('preserves an explicit error clear', async () => {+ await messageService.updateMessage('msg-error', { error: null }, {});+ expect(mockMessageModel.update).toHaveBeenCalledWith('msg-error', { error: null });+ });+it('should update message and return { success: true } when no sessionId/topicId provided', async () => {const messageId = 'msg-1';const value = { content: 'updated content' };@@ -328,6 +346,25 @@ describe('MessageService', () => {});describe('batchMutate', () => {+ it('normalizes known errors on creation and batched updates too', async () => {+ vi.mocked(mockMessageModel.create).mockResolvedValue({ id: 'msg-error' } as any);+ vi.mocked(mockMessageModel.update).mockResolvedValue({ success: true } as any);+ const error = { type: 'ProviderBizError' as const, body: { message: 'insufficient quota' } };+ const message = { content: '', error, role: 'assistant' as const };+ await messageService.createMessage(message);+ await messageService.batchMutate([+ { type: 'createMessage', message },+ { type: 'updateMessage', id: 'msg-error', value: { error } },+ ]);+ const normalized = expect.objectContaining({+ error: expect.objectContaining({ type: 'InsufficientQuota', attribution: 'user' }),+ });+ expect(mockMessageModel.create).toHaveBeenNthCalledWith(1, normalized, undefined);+ expect(mockMessageModel.create).toHaveBeenNthCalledWith(2, normalized, undefined);+ expect(mockMessageModel.update).toHaveBeenCalledWith('msg-error', normalized);+ expect(message.error).toBe(error);+ });+it('quietly applies create/update/tool updates without querying messages', async () => {vi.mocked(mockMessageModel.create).mockResolvedValue({ id: 'msg-created' } as any);vi.mocked(mockMessageModel.update).mockResolvedValue({ success: true } as any);diff --git a/apps/server/src/services/message/index.ts b/apps/server/src/services/message/index.tsindex 33a13c34543..a46e6228217 100644--- a/apps/server/src/services/message/index.ts+++ b/apps/server/src/services/message/index.ts@@ -1,5 +1,7 @@import { type LobeChatDatabase } from '@lobechat/database';import { CompressionRepository } from '@lobechat/database';+import { normalizeHeterogeneousMessageError } from '@lobechat/heterogeneous-agents/errors';+import { normalizeChatMessageError } from '@lobechat/model-runtime/errors';import { projectToolViewModels } from '@lobechat/tool-view-model';import {type CreateMessageParams,@@ -15,6 +17,15 @@ import { UserModel } from '@/database/models/user';import { FileService } from '../file';+/** Apply the same error contract to single and batched message writes. */+const normalizeMessageError = <T extends Pick<UpdateMessageParams, 'error'>>(value: T): T =>+ value.error+ ? {+ ...value,+ error: normalizeHeterogeneousMessageError(normalizeChatMessageError(value.error)),+ }+ : value;+interface QueryOptions {agentId?: string | null;groupId?: string | null;@@ -287,7 +298,10 @@ export class MessageService {for (const [index, operation] of operations.entries()) {try {if (operation.type === 'createMessage') {- const item = await this.messageModel.create(operation.message, operation.message.id);+ const item = await this.messageModel.create(+ normalizeMessageError(operation.message),+ operation.message.id,+ );results.push({ id: item.id, index, success: true, type: operation.type });continue;}@@ -298,7 +312,10 @@ export class MessageService {continue;}- const result = await this.messageModel.update(operation.id, operation.value as any);+ const result = await this.messageModel.update(+ operation.id,+ normalizeMessageError(operation.value),+ );results.push({ id: operation.id, index, success: result.success, type: operation.type });} catch (error) {console.error('[MessageService] batchMutate operation failed:', error);@@ -327,7 +344,7 @@ export class MessageService {// when present (passing `undefined` falls back to the model's genId// default), so flows that chain parentId across not-yet-created messages// (e.g. the subagent run coordinator) can assign ids up front.- const item = await this.messageModel.create(params, params.id);+ const item = await this.messageModel.create(normalizeMessageError(params), params.id);// 2. Query all messages for this agent/topic// Use agentId field for query@@ -423,6 +440,8 @@ export class MessageService {value: UpdateMessageParams,options: QueryOptions,): Promise<{ messages?: UIChatMessage[]; success: boolean }> {+ value = normalizeMessageError(value);+const updateStartedAt = Date.now();const modelTiming = createModelTiming(options, 'lambda.message.update.dbUpdate');if (modelTiming) {diff --git a/locales/en-US/modelRuntime.json b/locales/en-US/modelRuntime.jsonindex 1995977780a..4cd7484e9a7 100644--- a/locales/en-US/modelRuntime.json+++ b/locales/en-US/modelRuntime.json@@ -11,17 +11,21 @@"ConnectionCheckFailed": "The request returned empty. Please check if the API proxy address does not end with `/v1`.","ContentModeration": "Sorry, the content was rejected by the upstream safety filter. Please revise your prompt and try again.","ContextEnginePipelineError": "Failed to assemble the conversation context for this request. Please try again; if it persists, contact support.",+ "ConversationParentMissing": "The conversation context for this message could not be found. Reopen the conversation or start a new topic, then send the request again.","DatabasePersistError": "A database operation failed while saving or loading this conversation. Please try again; if it persists, contact support.","ExceededContextWindow": "The current request content exceeds the length that the model can handle. Please reduce the amount of content and try again.",+ "ExceededToolLimit": "This run reached its tool-call limit. Break the task into smaller steps, or ask the agent owner to adjust the tool-call limit.","HarnessJsonParseError": "An internal payload could not be read back, so this operation stopped. Retrying the same request will hit the same failure โ please start a new message; if it persists, contact support.","InsufficientQuota": "Sorry, the quota for this key has been reached. Please check if your account balance is sufficient or try again after increasing the key's quota.","InvalidBedrockCredentials": "Bedrock authentication failed. Please check the AccessKeyId/SecretAccessKey and retry.","InvalidComfyUIArgs": "Invalid ComfyUI configuration. Please check the settings and try again.",+ "InvalidGithubCopilotToken": "GitHub Copilot authentication failed. Ask the bot or agent owner to refresh the GitHub Copilot credentials, then try again.","InvalidGithubToken": "The GitHub Personal Access Token is incorrect or empty. Please check your GitHub Personal Access Token and try again.","InvalidOllamaArgs": "Invalid Ollama configuration, please check Ollama configuration and try again","InvalidProviderAPIKey": "{{provider}} API Key is incorrect or empty, please check your {{provider}} API Key and try again","InvalidRequestFormat": "Sorry, the upstream provider rejected the request as malformed. Please check the input or try a different model.","InvalidVertexCredentials": "Vertex authentication failed. Please check your credentials and try again.",+ "LobeHubModelDeprecated": "The selected model is no longer available. Ask the bot or agent owner to select an available model, then try again.","LocationNotSupportError": "We're sorry, your current location does not support this model service. This may be due to regional restrictions or the service not being available. Please confirm if the current location supports using this service, or try using a different location.","ModelEmptyCompletion": "The model provider returned an empty response. Even without visible content, this request may still incur charges. You can retry or switch models and try again.","ModelEmptyCompletionWithCost": "The model provider returned an empty response. This request cost {{credits}} credits. Retrying may incur a similar cost, or you can switch models.",@@ -35,6 +39,7 @@"ProviderBizError": "Error requesting {{provider}} service, please troubleshoot or retry based on the following information","ProviderContentPolicyViolation": "The provider blocked this request or its output due to content policy. Please revise your prompt and try again.","ProviderNetworkError": "Connection to the provider timed out or was dropped. Please check your network and try again.",+ "ProviderNoImageGenerated": "The provider returned no image for this request. Try rephrasing the request, or choose a model that supports image generation.","ProviderServiceUnavailable": "The provider is temporarily overloaded or unavailable. Please try again shortly.","QuotaLimitReached": "Sorry, the token usage or request count has reached the quota limit for this key. Please increase the key's quota or try again later.","RateLimitExceeded": "Sorry, the token usage or request count has reached the rate limit for this key. Please try again later or increase the key's quota.",@@ -45,5 +50,40 @@"UpstreamGatewayError": "The upstream gateway or proxy returned an error. Please try again shortly; if it persists, check your proxy / endpoint configuration.","UpstreamHttpError": "The provider returned an HTTP error without further detail. Please try again, or check your request and model configuration.","UpstreamMalformedResponse": "The provider returned a malformed response that could not be parsed. Please retry; if it persists, try a different model or provider.",- "UserConfigError": "Provider configuration is invalid (incorrect base URL, missing environment variable, virtual-key restriction, etc.). Please review the provider settings."+ "UserConfigError": "Provider configuration is invalid (incorrect base URL, missing environment variable, virtual-key restriction, etc.). Please review the provider settings.",+ "heterogeneous.aborted.description": "This {{agent}} task was stopped. Send a new request when you want to continue.",+ "heterogeneous.aborted.title": "Task stopped",+ "heterogeneous.agent_failed.description": "{{agent}} stopped without a recognized cause. Share the Operation ID with the bot owner or support to investigate.",+ "heterogeneous.agent_failed.title": "Agent task failed",+ "heterogeneous.auth_required.description": "Ask the bot owner to sign in again on the device running {{agent}}.",+ "heterogeneous.auth_required.title": "Sign-in required",+ "heterogeneous.cli_not_found.description": "Ask the bot owner to install or repair {{agent}} on the device running this task.",+ "heterogeneous.cli_not_found.title": "Agent CLI unavailable",+ "heterogeneous.credit_limit.description": "Ask the bot owner to add credits to the account used by {{agent}}, or switch models. Waiting for a quota reset will not restore these credits.",+ "heterogeneous.credit_limit.title": "Credits exhausted",+ "heterogeneous.invalid_request.description": "The provider rejected the request sent by {{agent}}. Try a new topic; if it persists, share the Operation ID with support.",+ "heterogeneous.invalid_request.title": "Request rejected",+ "heterogeneous.max_turns.description": "{{agent}} reached its step limit before finishing. Split the task into smaller steps, or ask the bot owner to adjust the limit.",+ "heterogeneous.max_turns.title": "Step limit reached",+ "heterogeneous.model_unavailable.description": "The model selected for {{agent}} is unavailable. Ask the bot owner to choose another model.",+ "heterogeneous.model_unavailable.title": "Model unavailable",+ "heterogeneous.network_drop.description": "{{agent}} lost its connection before finishing. Retry; if it happens again, ask the bot owner to check the running deviceโs network and proxy settings.",+ "heterogeneous.network_drop.title": "Connection interrupted",+ "heterogeneous.reset": "Quota resets at {{time}} (UTC).",+ "heterogeneous.resume_cwd_mismatch.description": "Ask the bot owner to restore the working directory used by this {{agent}} session, or start a new topic.",+ "heterogeneous.resume_cwd_mismatch.title": "Session directory changed",+ "heterogeneous.resume_thread_not_found.description": "{{agent}} could not find the previous session. Start a new topic and resend the request.",+ "heterogeneous.resume_thread_not_found.title": "Previous session unavailable",+ "heterogeneous.server_overloaded.description": "The provider behind {{agent}} is busy or unavailable. Please try again shortly.",+ "heterogeneous.server_overloaded.title": "Provider temporarily unavailable",+ "heterogeneous.server_throttle.description": "The provider is temporarily limiting requests from {{agent}}. Please wait a moment and try again.",+ "heterogeneous.server_throttle.title": "Requests temporarily limited",+ "heterogeneous.unsupported_attachment.description": "{{agent}} could not read an attachment. Remove it or convert it to a supported format, then resend the request.",+ "heterogeneous.unsupported_attachment.title": "Attachment unsupported",+ "heterogeneous.usage_limit.description": "The account used by {{agent}} has exhausted its allowance. Wait for the quota to reset, or ask the bot owner to switch to an account or model with available quota.",+ "heterogeneous.usage_limit.title": "Usage limit reached",+ "heterogeneous.window.five_hour": "Session allowance exhausted.",+ "heterogeneous.window.seven_day": "Weekly allowance exhausted.",+ "heterogeneous.working_directory_not_found.description": "The working directory for {{agent}} is missing. Ask the bot owner to restore it or choose an existing directory.",+ "heterogeneous.working_directory_not_found.title": "Working directory unavailable"}diff --git a/locales/zh-CN/modelRuntime.json b/locales/zh-CN/modelRuntime.jsonindex 83b630ddd1c..14d4b555e04 100644--- a/locales/zh-CN/modelRuntime.json+++ b/locales/zh-CN/modelRuntime.json@@ -11,17 +11,21 @@"ConnectionCheckFailed": "่ฏทๆฑ่ฟๅไธบ็ฉบใ่ฏทๆฃๆฅAPIไปฃ็ๅฐๅๆฏๅฆๆชไปฅ`/v1`็ปๅฐพใ","ContentModeration": "ๆฑๆญ๏ผๅ ๅฎน่ขซไธๆธธๅฎๅ จ่ฟๆปคๅจๆ็ปใ่ฏทไฟฎๆนๆจ็ๆ็คบ่ฏๅนถ้่ฏใ","ContextEnginePipelineError": "็ป่ฃ ๆญค่ฏทๆฑ็ๅฏน่ฏไธไธๆๅคฑ่ดฅใ่ฏท้่ฏ๏ผๅฆๆ้ฎ้ขไป็ถๅญๅจ๏ผ่ฏท่็ณปๆฏๆใ",+ "ConversationParentMissing": "ๆพไธๅฐ่ฟๆกๆถๆฏๅฏนๅบ็ไผ่ฏไธไธๆใ่ฏท้ๆฐๆๅผๅฏน่ฏๆๆฐๅปบ่ฏ้ข๏ผๅๆฌกๅ้่ฏทๆฑใ","DatabasePersistError": "ไฟๅญๆๅ ่ฝฝๆญคๅฏน่ฏๆถๆฐๆฎๅบๆไฝๅคฑ่ดฅใ่ฏท้่ฏ๏ผๅฆๆ้ฎ้ขไป็ถๅญๅจ๏ผ่ฏท่็ณปๆฏๆใ","ExceededContextWindow": "ๅฝๅ่ฏทๆฑๅ ๅฎน่ถ ๅบไบๆจกๅๅฏๅค็็้ฟๅบฆใ่ฏทๅๅฐๅ ๅฎน้ๅนถ้่ฏใ",+ "ExceededToolLimit": "ๆฌๆฌกไปปๅกๅทฒ่พพๅฐๅทฅๅ ท่ฐ็จๆฌกๆฐไธ้ใ่ฏทๅฐไปปๅกๆๅๆ่พๅฐๆญฅ้ชค๏ผๆ่็ณป Agent ็ฎก็ๅ่ฐๆด่ฐ็จๆฌกๆฐไธ้ใ","HarnessJsonParseError": "ๅ ้จๆฐๆฎๅ่ฏปๅคฑ่ดฅ๏ผๆฌๆฌกๆไฝๅทฒไธญๆญขใ้่ฏๅไธ่ฏทๆฑไผ้ๅฐๅๆ ท็ๅคฑ่ดฅ๏ผ่ฏท้ๆฐๅ่ตทไธๆกๆถๆฏ๏ผๅฆๆ้ฎ้ขไป็ถๅญๅจ๏ผ่ฏท่็ณปๆฏๆใ","InsufficientQuota": "ๆฑๆญ๏ผๆญคๅฏ้ฅ็้ ้ขๅทฒ็จๅฐฝใ่ฏทๆฃๆฅๆจ็่ดฆๆทไฝ้ขๆฏๅฆๅ ่ถณๆๅจๅขๅ ๅฏ้ฅ้ ้ขๅ้่ฏใ","InvalidBedrockCredentials": "Bedrock่บซไปฝ้ช่ฏๅคฑ่ดฅใ่ฏทๆฃๆฅAccessKeyId/SecretAccessKeyๅนถ้่ฏใ","InvalidComfyUIArgs": "ComfyUI้ ็ฝฎๆ ๆใ่ฏทๆฃๆฅ่ฎพ็ฝฎๅนถ้่ฏใ",+ "InvalidGithubCopilotToken": "GitHub Copilot ่บซไปฝ้ช่ฏๅคฑ่ดฅใ่ฏท่็ณปๆบๅจไบบๆ Agent ็็ฎก็ๅๆดๆฐ GitHub Copilot ๅญๆฎๅ้่ฏใ","InvalidGithubToken": "GitHubไธชไบบ่ฎฟ้ฎไปค็ไธๆญฃ็กฎๆไธบ็ฉบใ่ฏทๆฃๆฅๆจ็GitHubไธชไบบ่ฎฟ้ฎไปค็ๅนถ้่ฏใ","InvalidOllamaArgs": "Ollama้ ็ฝฎๆ ๆ๏ผ่ฏทๆฃๆฅOllama้ ็ฝฎๅนถ้่ฏใ","InvalidProviderAPIKey": "{{provider}} APIๅฏ้ฅไธๆญฃ็กฎๆไธบ็ฉบ๏ผ่ฏทๆฃๆฅๆจ็{{provider}} APIๅฏ้ฅๅนถ้่ฏใ","InvalidRequestFormat": "ๆฑๆญ๏ผไธๆธธๆไพๅๆ็ปไบ่ฏทๆฑ๏ผๅ ไธบๆ ผๅผไธๆญฃ็กฎใ่ฏทๆฃๆฅ่พๅ ฅๆๅฐ่ฏไฝฟ็จๅ ถไปๆจกๅใ","InvalidVertexCredentials": "Vertex่บซไปฝ้ช่ฏๅคฑ่ดฅใ่ฏทๆฃๆฅๆจ็ๅญๆฎๅนถ้่ฏใ",+ "LobeHubModelDeprecated": "ๆ้ๆจกๅๅทฒไธ็บฟใ่ฏท่็ณปๆบๅจไบบๆ Agent ็็ฎก็ๅๅๆขๅฏ็จๆจกๅๅ้่ฏใ","LocationNotSupportError": "ๆฑๆญ๏ผๆจๅฝๅ็ไฝ็ฝฎไธๆฏๆๆญคๆจกๅๆๅกใ่ฟๅฏ่ฝๆฏ็ฑไบๅฐๅบ้ๅถๆๆๅกไธๅฏ็จใ่ฏท็กฎ่ฎคๅฝๅๅฐ็นๆฏๅฆๆฏๆไฝฟ็จๆญคๆๅก๏ผๆๅฐ่ฏไฝฟ็จๅ ถไปๅฐ็นใ","ModelEmptyCompletion": "ๆจกๅไพๅบๅ่ฟๅไบ็ฉบๅ ๅฎนใๅณไฝฟๆฒกๆๅฏๆพ็คบ็ๅ ๅฎน๏ผๆฌๆฌก่ฏทๆฑไปๅฏ่ฝไบง็่ดน็จใไฝ ๅฏไปฅ้่ฏ๏ผๆๅๆขๆจกๅๅๅ่ฏใ","ModelEmptyCompletionWithCost": "ๆจกๅไพๅบๅ่ฟๅ็ฉบๅ ๅฎน๏ผๆฌๆฌก่ดน็จไธบ {{credits}} ็งฏๅใ้่ฏๅฏ่ฝไบง็็ธ่ฟ่ดน็จ๏ผไนๅฏๅๆขๆจกๅใ",@@ -35,6 +39,7 @@"ProviderBizError": "่ฏทๆฑ{{provider}}ๆๅกๆถๅ็้่ฏฏ๏ผ่ฏทๆ นๆฎไปฅไธไฟกๆฏ่ฟ่กๆๆฅๆ้่ฏใ","ProviderContentPolicyViolation": "ไพๅบๅๅ ๅ ๅฎนๆฟ็ญๆฆๆชไบๆญค่ฏทๆฑๆๅ ถ่พๅบใ่ฏทไฟฎๆนๆ็คบ่ฏๅ้่ฏใ","ProviderNetworkError": "ไธๆไพๅ็่ฟๆฅ่ถ ๆถๆ่ขซไธญๆญใ่ฏทๆฃๆฅๆจ็็ฝ็ปๅนถ้่ฏใ",+ "ProviderNoImageGenerated": "ๆไพๅๆชไธบ่ฟๆฌก่ฏทๆฑ่ฟๅๅพ็ใ่ฏท่ฐๆดๆ็คบ่ฏๅ้่ฏ๏ผๆ้ๆฉๆฏๆๅพ็็ๆ็ๆจกๅใ","ProviderServiceUnavailable": "ๆไพๅๆๆถ่ฟ่ฝฝๆไธๅฏ็จใ่ฏท็จๅ้่ฏใ","QuotaLimitReached": "ๆฑๆญ๏ผๆญคๅฏ้ฅ็ไปค็ไฝฟ็จ้ๆ่ฏทๆฑๆฌกๆฐๅทฒ่พพๅฐ้ ้ข้ๅถใ่ฏทๅขๅ ๅฏ้ฅ้ ้ขๆ็จๅ้่ฏใ","RateLimitExceeded": "ๆฑๆญ๏ผๆญคๅฏ้ฅ็ไปค็ไฝฟ็จ้ๆ่ฏทๆฑๆฌกๆฐๅทฒ่พพๅฐ้็้ๅถใ่ฏท็จๅ้่ฏๆๅขๅ ๅฏ้ฅ้ ้ขใ",@@ -45,5 +50,40 @@"UpstreamGatewayError": "ไธๆธธ็ฝๅ ณๆไปฃ็่ฟๅ้่ฏฏใ่ฏท็จๅ้่ฏ๏ผๅฆๆ้ฎ้ขไป็ถๅญๅจ๏ผ่ฏทๆฃๆฅๆจ็ไปฃ็/็ซฏ็น้ ็ฝฎใ","UpstreamHttpError": "ๆไพๅ่ฟๅไบHTTP้่ฏฏ๏ผไฝๆชๆไพ่ฟไธๆญฅ่ฏฆ็ปไฟกๆฏใ่ฏท้่ฏ๏ผๆๆฃๆฅๆจ็่ฏทๆฑๅๆจกๅ้ ็ฝฎใ","UpstreamMalformedResponse": "ๆไพๅ่ฟๅไบๆ ๆณ่งฃๆ็ๆ ผๅผ้่ฏฏๅๅบใ่ฏท้่ฏ๏ผๅฆๆ้ฎ้ขไป็ถๅญๅจ๏ผ่ฏทๅฐ่ฏไฝฟ็จๅ ถไปๆจกๅๆๆไพๅใ",- "UserConfigError": "ๆไพๅ้ ็ฝฎๆ ๆ๏ผๅบ็กURL้่ฏฏใ็ผบๅฐ็ฏๅขๅ้ใ่ๆๅฏ้ฅ้ๅถ็ญ๏ผใ่ฏทๆฃๆฅๆไพๅ่ฎพ็ฝฎใ"+ "UserConfigError": "ๆไพๅ้ ็ฝฎๆ ๆ๏ผๅบ็กURL้่ฏฏใ็ผบๅฐ็ฏๅขๅ้ใ่ๆๅฏ้ฅ้ๅถ็ญ๏ผใ่ฏทๆฃๆฅๆไพๅ่ฎพ็ฝฎใ",+ "heterogeneous.aborted.description": "ๆฌๆฌก {{agent}} ไปปๅกๅทฒๅๆญขใๅฆ้็ปง็ปญ๏ผ่ฏทๅ้ๆฐ็่ฏทๆฑใ",+ "heterogeneous.aborted.title": "ไปปๅกๅทฒๅๆญข",+ "heterogeneous.agent_failed.description": "{{agent}} ๅทฒๅๆญข๏ผ็ฎๅๆ ๆณ็กฎๅฎๅ ทไฝๅๅ ใ่ฏทๅฐ Operation ID ๆไพ็ปๆบๅจไบบ็ฎก็ๅๆๆฏๆไบบๅๆๆฅใ",+ "heterogeneous.agent_failed.title": "Agent ไปปๅกๅคฑ่ดฅ",+ "heterogeneous.auth_required.description": "่ฏท่็ณปๆบๅจไบบ็ฎก็ๅ๏ผๅจ่ฟ่ก {{agent}} ็่ฎพๅคไธ้ๆฐ็ปๅฝใ",+ "heterogeneous.auth_required.title": "้่ฆ้ๆฐ็ปๅฝ",+ "heterogeneous.cli_not_found.description": "่ฏท่็ณปๆบๅจไบบ็ฎก็ๅ๏ผๅจ่ฟ่กไปปๅก็่ฎพๅคไธๅฎ่ฃ ๆไฟฎๅค {{agent}}ใ",+ "heterogeneous.cli_not_found.title": "Agent CLI ไธๅฏ็จ",+ "heterogeneous.credit_limit.description": "่ฏท่็ณปๆบๅจไบบ็ฎก็ๅ๏ผไธบ {{agent}} ไฝฟ็จ็่ดฆๅท่กฅๅ ็งฏๅๆๅๆขๆจกๅใ็ญๅพ ้ขๅบฆๅจๆ้็ฝฎไธไผๆขๅค่ฟ้จๅ็งฏๅใ",+ "heterogeneous.credit_limit.title": "็งฏๅๅทฒ่ๅฐฝ",+ "heterogeneous.invalid_request.description": "ๆไพๅๆ็ปไบ {{agent}} ๅ้็่ฏทๆฑใ่ฏทๆฐๅปบ่ฏ้ขๅ้่ฏ๏ผ่ฅๆ็ปญๅ็๏ผ่ฏทๅๆฏๆไบบๅๆไพ Operation IDใ",+ "heterogeneous.invalid_request.title": "่ฏทๆฑ่ขซๆ็ป",+ "heterogeneous.max_turns.description": "{{agent}} ๅจๅฎๆไปปๅกๅ่พพๅฐๆญฅ้ชคไธ้ใ่ฏทๆๅไปปๅก๏ผๆ่็ณปๆบๅจไบบ็ฎก็ๅ่ฐๆดไธ้ใ",+ "heterogeneous.max_turns.title": "ๅทฒ่พพๅฐๆญฅ้ชคไธ้",+ "heterogeneous.model_unavailable.description": "{{agent}} ๆ้็ๆจกๅๅฝๅไธๅฏ็จใ่ฏท่็ณปๆบๅจไบบ็ฎก็ๅๅๆขๆจกๅใ",+ "heterogeneous.model_unavailable.title": "ๆจกๅไธๅฏ็จ",+ "heterogeneous.network_drop.description": "{{agent}} ๅจๅฎๆไปปๅกๅ่ฟๆฅไธญๆญใ่ฏท้่ฏ๏ผ่ฅๆ็ปญๅ็๏ผ่ฏท่็ณปๆบๅจไบบ็ฎก็ๅๆฃๆฅ่ฟ่ก่ฎพๅค็็ฝ็ปๅไปฃ็่ฎพ็ฝฎใ",+ "heterogeneous.network_drop.title": "่ฟๆฅไธญๆญ",+ "heterogeneous.reset": "้ขๅบฆๆขๅคๆถ้ด๏ผ{{time}}๏ผUTC๏ผใ",+ "heterogeneous.resume_cwd_mismatch.description": "่ฏท่็ณปๆบๅจไบบ็ฎก็ๅๆขๅคๆฌๆฌก {{agent}} ไผ่ฏๅๆฅ็ๅทฅไฝ็ฎๅฝ๏ผๆๆฐๅปบ่ฏ้ขใ",+ "heterogeneous.resume_cwd_mismatch.title": "ไผ่ฏๅทฅไฝ็ฎๅฝๅทฒๅๅ",+ "heterogeneous.resume_thread_not_found.description": "{{agent}} ๆพไธๅฐๅๆฅ็ไผ่ฏใ่ฏทๆฐๅปบ่ฏ้ขๅนถ้ๆฐๅ้่ฏทๆฑใ",+ "heterogeneous.resume_thread_not_found.title": "ๅไผ่ฏไธๅฏ็จ",+ "heterogeneous.server_overloaded.description": "{{agent}} ็ไธๆธธๆๅกๅฝๅ็นๅฟๆไธๅฏ็จ๏ผ่ฏท็จๅ้่ฏใ",+ "heterogeneous.server_overloaded.title": "ไธๆธธๆๅกๆไธๅฏ็จ",+ "heterogeneous.server_throttle.description": "ๆไพๅๆๆถ้ๅถไบ {{agent}} ็่ฏทๆฑ๏ผ่ฏท็จ็ญ็ๅปๅ้่ฏใ",+ "heterogeneous.server_throttle.title": "่ฏทๆฑๆๆถๅๅฐ้ๆต",+ "heterogeneous.unsupported_attachment.description": "{{agent}} ๆ ๆณ่ฏปๅ้ไปถใ่ฏท็งป้ค้ไปถๆ่ฝฌๆขไธบๆฏๆ็ๆ ผๅผๅ้ๆฐๅ้ใ",+ "heterogeneous.unsupported_attachment.title": "้ไปถๆ ๆณ่ฏปๅ",+ "heterogeneous.usage_limit.description": "{{agent}} ไฝฟ็จ็่ดฆๅท้ขๅบฆๅทฒ่ๅฐฝใ่ฏท็ญๅพ ้ขๅบฆๆขๅค๏ผๆ่็ณปๆบๅจไบบ็ฎก็ๅๅๆขๆๅฏ็จ้ขๅบฆ็่ดฆๅทๆๆจกๅใ",+ "heterogeneous.usage_limit.title": "ไฝฟ็จ้ขๅบฆๅทฒ็จๅฎ",+ "heterogeneous.window.five_hour": "ๅฝๅไผ่ฏๅจๆ้ขๅบฆๅทฒ็จๅฎใ",+ "heterogeneous.window.seven_day": "ๆฌๅจ้ขๅบฆๅทฒ็จๅฎใ",+ "heterogeneous.working_directory_not_found.description": "{{agent}} ็ๅทฅไฝ็ฎๅฝไธๅญๅจใ่ฏท่็ณปๆบๅจไบบ็ฎก็ๅๆขๅค็ฎๅฝ๏ผๆ้ๆฉไธไธช็ฐๆ็ฎๅฝใ",+ "heterogeneous.working_directory_not_found.title": "ๅทฅไฝ็ฎๅฝไธๅญๅจ"}diff --git a/packages/agent-runtime/src/types/hooks.ts b/packages/agent-runtime/src/types/hooks.tsindex 75b7ff7fe8b..4a98f8c597c 100644--- a/packages/agent-runtime/src/types/hooks.ts+++ b/packages/agent-runtime/src/types/hooks.ts@@ -1,4 +1,4 @@-import type { ChatErrorBudgetContext } from '@lobechat/types';+import type { ChatErrorBudgetContext, ChatErrorHeterogeneousContext } from '@lobechat/types';import type { ToolRunResult } from '../transport/tool';@@ -83,6 +83,7 @@ export interface AgentHookEvent {errorBudget?: ChatErrorBudgetContext;// ContenterrorDetail?: string;+ errorHeterogeneous?: ChatErrorHeterogeneousContext;errorMessage?: string;diff --git a/packages/fetch-sse/src/__tests__/parseError.test.ts b/packages/fetch-sse/src/__tests__/parseError.test.tsindex ef8b84d1781..41d54751891 100644--- a/packages/fetch-sse/src/__tests__/parseError.test.ts+++ b/packages/fetch-sse/src/__tests__/parseError.test.ts@@ -50,6 +50,22 @@ beforeEach(() => {});describe('getMessageError', () => {+ it('classifies a generic quota response before choosing its translated message', async () => {+ const response = Response.json(+ {+ body: { error: { message: 'insufficient quota' } },+ errorType: 'ProviderBizError',+ },+ { status: 429 },+ );+ const error = await getMessageError(response);+ expect(error).toMatchObject({+ attribution: 'user',+ message: 'translated_InsufficientQuota',+ type: 'InsufficientQuota',+ });+ });+it('should handle business error correctly', async () => {const mockErrorResponse: ErrorResponse = {body: 'Error occurred',diff --git a/packages/fetch-sse/src/parseError.ts b/packages/fetch-sse/src/parseError.tsindex 8f5c7655603..44c5b1851ec 100644--- a/packages/fetch-sse/src/parseError.ts+++ b/packages/fetch-sse/src/parseError.ts@@ -1,4 +1,4 @@-import { getRuntimeErrorI18nKey } from '@lobechat/model-runtime/errors';+import { getRuntimeErrorI18nKey, normalizeChatMessageError } from '@lobechat/model-runtime/errors';import type { ChatMessageError, ErrorResponse, ErrorType } from '@lobechat/types';import { isRecord, pickTrimmedString } from '@lobechat/utils';import i18next, { t } from 'i18next';@@ -12,7 +12,7 @@ import { getProviderDisplayName } from 'model-bank/modelProviders';* which is how users ended up seeing raw `response.InvalidProviderAPIKey` text* in the "fetch model list" toast.*/-const translateErrorType = (errorType: ErrorResponse['errorType'], body: unknown) => {+const translateErrorType = (errorType: ChatMessageError['type'], body: unknown) => {const { key, ns } = getRuntimeErrorI18nKey(errorType);// Both namespaces interpolate `{{provider}}`; the backend puts the provider@@ -52,10 +52,11 @@ export const getMessageError = async (response: Response): Promise<ChatMessageEr// try to get the biz errortry {const data = (await response.json()) as ErrorResponse;+ const normalized = normalizeChatMessageError({ body: data.body, errorType: data.errorType });chatMessageError = {+ ...normalized,body: data.body,- message: translateErrorType(data.errorType, data.body),- type: data.errorType,+ message: translateErrorType(normalized.type, data.body),};} catch {// if not return, then it's a common errordiff --git a/packages/heterogeneous-agents/package.json b/packages/heterogeneous-agents/package.jsonindex 2532166b47f..28bb31d7ee8 100644--- a/packages/heterogeneous-agents/package.json+++ b/packages/heterogeneous-agents/package.json@@ -7,6 +7,7 @@".": "./src/index.ts","./askUser": "./src/askUser/index.ts","./builtinMcp": "./src/builtinMcp/index.ts",+ "./errors": "./src/errors/index.ts","./client": "./src/client/index.ts","./models": "./src/models/index.ts","./protocol": "./src/protocol/index.ts",diff --git a/packages/heterogeneous-agents/src/adapters/claudeCode.ts b/packages/heterogeneous-agents/src/adapters/claudeCode.tsindex 2b544cc2962..5239387dbcc 100644--- a/packages/heterogeneous-agents/src/adapters/claudeCode.ts+++ b/packages/heterogeneous-agents/src/adapters/claudeCode.ts@@ -37,6 +37,11 @@*/import { getHeterogeneousAgentConfigOrThrow } from '../config';+import {+ CLI_CREDIT_LIMIT_PATTERNS,+ CLI_SERVER_THROTTLE_PATTERNS,+ CLI_USER_RATE_LIMIT_PATTERNS,+} from '../errors/claudeCodeQuota';import type { HeteroErrorKind } from '../errors/specs';import { imagePlaceholder } from '../imageEcho';import type {@@ -255,55 +260,6 @@ export interface ClaudeCompatibleAdapterProfile {ignoreDuplicateInit: boolean;}-/**- * Genuinely user-side limit wording. Used only as the text fallback for- * batch CLI / sandbox runs that don't emit a structured `rate_limit_event`- * (so {@link isUserQuotaRateLimit} can't fire). The ambiguous bare- * `rate limit` / `rate limited` substring is deliberately NOT here โ it also- * appears in Anthropic's transient server throttle, so leaning on it would- * reintroduce the very misclassification this set exists to avoid.- */-/**- * Credit/balance exhaustion, e.g. `You've reached your Fable 5 limit. Run- * /usage-credits to continue or switch models with /model.` It renders the- * same guide as a plan window, but waiting for a reset never clears it.- */-const CLI_CREDIT_LIMIT_PATTERNS = [- /you'?ve reached your .{0,40}\blimit\b/i,- /\/usage-credits\b/i,-] as const;--const CLI_USER_RATE_LIMIT_PATTERNS = [- /you'?ve hit your limit/i,- // CC names the window in the wording it actually ships โ `You've hit your- // session limit ยท resets 6:30pm (Asia/Shanghai)` and `You've hit your weekly- // limit ยท resets Jul 3 at 1pm`. Without these the bare `you've hit your- // limit` pattern misses every real message, leaving the 429 to fall through- // to the overloaded (retry) guide.- /you'?ve hit your \S+ limit/i,- ...CLI_CREDIT_LIMIT_PATTERNS,- /usage limit reached/i,- /\blimit reached\b/i,- // Gateways/proxies in front of the API localize the same quota rejection,- // e.g. `API Error: Request rejected (429) ยท [1234][ๅทฒ่พพๅฐ 5 ๅฐๆถไฝฟ็จไธ้๏ผ- // 2026-06-19 22:00:00 ๅๅฏ็ปง็ปญไฝฟ็จใโฆ]`. English-only patterns classified- // these as a transient overload and told the user to just retry.- /ไฝฟ็จไธ้/,-] as const;--/**- * Anthropic's server-side transient throttle. CC surfaces this as a 429 with- * a message that explicitly disclaims the user's plan limit ("not your usage- * limit") โ e.g. `API Error: Server is temporarily limiting requests (not your- * usage limit) ยท Rate limited`. It clears on its own in moments, so it must be- * classified as `overloaded` (retry UX), NOT `rate_limit` (which renders a- * misleading "usage limit reached" reset-time guide).- */-const CLI_SERVER_THROTTLE_PATTERNS = [- /not your usage limit/i,- /server is temporarily limiting requests/i,-] as const;-/*** Transport-level failures: the connection dropped, stalled, or timed out* before the run could finish. CC reports these as an `API Error:` line withdiff --git a/packages/heterogeneous-agents/src/errors/claudeCodeQuota.ts b/packages/heterogeneous-agents/src/errors/claudeCodeQuota.tsnew file mode 100644index 00000000000..68b8ef2bf18--- /dev/null+++ b/packages/heterogeneous-agents/src/errors/claudeCodeQuota.ts@@ -0,0 +1,35 @@+export const CLI_CREDIT_LIMIT_PATTERNS = [+ /you'?ve reached your .{0,40}\blimit\b/i,+ /\/usage-credits\b/i,+] as const;++export const CLI_USER_RATE_LIMIT_PATTERNS = [+ /you'?ve hit your limit/i,+ // CC names the window in the wording it actually ships โ `You've hit your+ // session limit ยท resets 6:30pm (Asia/Shanghai)` and `You've hit your weekly+ // limit ยท resets Jul 3 at 1pm`. Without these the bare `you've hit your+ // limit` pattern misses every real message, leaving the 429 to fall through+ // to the overloaded (retry) guide.+ /you'?ve hit your \S+ limit/i,+ ...CLI_CREDIT_LIMIT_PATTERNS,+ /usage limit reached/i,+ /\blimit reached\b/i,+ // Gateways/proxies in front of the API localize the same quota rejection,+ // e.g. `API Error: Request rejected (429) ยท [1234][ๅทฒ่พพๅฐ 5 ๅฐๆถไฝฟ็จไธ้๏ผ+ // 2026-06-19 22:00:00 ๅๅฏ็ปง็ปญไฝฟ็จใโฆ]`. English-only patterns classified+ // these as a transient overload and told the user to just retry.+ /ไฝฟ็จไธ้/,+] as const;++/**+ * Anthropic's server-side transient throttle. CC surfaces this as a 429 with+ * a message that explicitly disclaims the user's plan limit ("not your usage+ * limit") โ e.g. `API Error: Server is temporarily limiting requests (not your+ * usage limit) ยท Rate limited`. It clears on its own in moments, so it must be+ * classified as `overloaded` (retry UX), NOT `rate_limit` (which renders a+ * misleading "usage limit reached" reset-time guide).+ */+export const CLI_SERVER_THROTTLE_PATTERNS = [+ /not your usage limit/i,+ /server is temporarily limiting requests/i,+] as const;diff --git a/packages/heterogeneous-agents/src/errors/index.ts b/packages/heterogeneous-agents/src/errors/index.tsindex 037d2f02b4f..590fbb749b2 100644--- a/packages/heterogeneous-agents/src/errors/index.ts+++ b/packages/heterogeneous-agents/src/errors/index.ts@@ -1,3 +1,4 @@+export { normalizeHeterogeneousMessageError, readHeterogeneousErrorContext } from './messageError';export type { HeteroErrorKind, HeteroErrorSpec } from './specs';export {formatHeteroErrorId,diff --git a/packages/heterogeneous-agents/src/errors/messageError.test.ts b/packages/heterogeneous-agents/src/errors/messageError.test.tsnew file mode 100644index 00000000000..16f5d8a3f44--- /dev/null+++ b/packages/heterogeneous-agents/src/errors/messageError.test.ts@@ -0,0 +1,65 @@+import { describe, expect, it } from 'vitest';++import { normalizeHeterogeneousMessageError, readHeterogeneousErrorContext } from './messageError';++describe('heterogeneous message errors', () => {+ it('recovers a flattened weekly limit for local and remote callers', () => {+ const result = normalizeHeterogeneousMessageError(+ {+ type: 'AgentRuntimeError',+ message: "You've hit your weekly limit ยท resets 10pm (Asia/Shanghai)",+ },+ 'claude-code',+ );+ expect(result).toMatchObject({+ errorRef: 'H2001',+ attribution: 'user',+ retryable: false,+ body: { agentType: 'claude-code', code: 'rate_limit', details: { kind: 'usage_limit' } },+ });+ expect(normalizeHeterogeneousMessageError(result)).toEqual(result);+ });+ it('does not classify temporary throttling as exhausted quota', () => {+ const error = {+ type: 'AgentRuntimeError' as const,+ message: 'Server is temporarily limiting requests (not your usage limit)',+ };+ expect(normalizeHeterogeneousMessageError(error, 'claude-code')).toBe(error);+ });+ it('projects only safe quota context and rejects an allowed window', () => {+ const error = {+ type: 'AgentRuntimeError' as const,+ body: {+ agentType: 'claude-code',+ code: 'rate_limit',+ details: { kind: 'usage_limit' },+ stderr: '/private/key secret',+ rateLimitInfo: { status: 'rejected', rateLimitType: 'seven_day', resetsAt: 1789826400 },+ },+ };+ expect(readHeterogeneousErrorContext(error)).toEqual({+ agentType: 'claude-code',+ kind: 'usage_limit',+ rateLimitType: 'seven_day',+ resetsAt: 1789826400,+ });+ error.body.rateLimitInfo.status = 'allowed';+ expect(readHeterogeneousErrorContext(error)).toEqual({+ agentType: 'claude-code',+ kind: 'usage_limit',+ });+ });+ it('does not attach a quota reset to network failures or credits', () => {+ for (const kind of ['network_drop', 'credit_limit']) {+ const result = readHeterogeneousErrorContext({+ type: 'AgentRuntimeError',+ body: {+ agentType: 'claude-code',+ details: { kind },+ rateLimitInfo: { status: 'rejected', resetsAt: 1789826400 },+ },+ });+ expect(result).toEqual({ agentType: 'claude-code', kind });+ }+ });+});diff --git a/packages/heterogeneous-agents/src/errors/messageError.ts b/packages/heterogeneous-agents/src/errors/messageError.tsnew file mode 100644index 00000000000..d7c5a14fc05--- /dev/null+++ b/packages/heterogeneous-agents/src/errors/messageError.ts@@ -0,0 +1,104 @@+import type { ChatErrorHeterogeneousContext, ChatMessageError } from '@lobechat/types';+import { isRecord } from '@lobechat/utils/object';++import { isLocalHeterogeneousType } from '../config';+import {+ CLI_CREDIT_LIMIT_PATTERNS,+ CLI_SERVER_THROTTLE_PATTERNS,+ CLI_USER_RATE_LIMIT_PATTERNS,+} from './claudeCodeQuota';+import { formatHeteroErrorId, HETERO_ERROR_SPECS, type HeteroErrorKind } from './specs';++const GUIDE_KINDS: Record<string, HeteroErrorKind> = {+ auth_required: 'auth_required',+ cli_not_found: 'cli_not_found',+ overloaded: 'server_overloaded',+ rate_limit: 'usage_limit',+ working_directory_not_found: 'working_directory_not_found',+};+const knownKind = (value: unknown): HeteroErrorKind | undefined =>+ typeof value === 'string' && Object.hasOwn(HETERO_ERROR_SPECS, value)+ ? (value as HeteroErrorKind)+ : undefined;++/** Recover classified CLI failures without losing their guide payload or diagnostics. */+export const normalizeHeterogeneousMessageError = (+ error: ChatMessageError,+ agentTypeHint?: string,+): ChatMessageError => {+ const body = isRecord(error.body) ? error.body : {};+ const agentType = typeof body.agentType === 'string' ? body.agentType : agentTypeHint;+ if (!agentType || !isLocalHeterogeneousType(agentType)) return error;+ const details = isRecord(body.details) ? body.details : {};+ let kind = knownKind(details.kind) ?? knownKind(body.code);+ const message = [error.message, body.message, body.error, body.stderr]+ .filter((value): value is string => typeof value === 'string')+ .join('\n');+ // Older local/remote producers may have sent only { message }. Never infer+ // quota exhaustion from a bare 429 or an allowed rolling-window snapshot.+ if (+ !kind &&+ agentType === 'claude-code' &&+ !CLI_SERVER_THROTTLE_PATTERNS.some((pattern) => pattern.test(message)) &&+ CLI_USER_RATE_LIMIT_PATTERNS.some((pattern) => pattern.test(message))+ ) {+ kind = CLI_CREDIT_LIMIT_PATTERNS.some((pattern) => pattern.test(message))+ ? 'credit_limit'+ : 'usage_limit';+ }+ kind ??=+ typeof body.code === 'string' && Object.hasOwn(GUIDE_KINDS, body.code)+ ? GUIDE_KINDS[body.code]+ : undefined;+ if (!kind) return error;+ const spec = HETERO_ERROR_SPECS[kind];+ return {+ ...error,+ attribution: spec.attribution,+ body: {+ ...body,+ agentType,+ code: spec.guideCode ?? body.code ?? kind,+ details: { ...details, kind },+ message: typeof body.message === 'string' ? body.message : error.message,+ ...(spec.guideCode === 'rate_limit' ? { clearEchoedContent: true } : {}),+ },+ category: spec.category,+ countAsFailure: spec.countAsFailure,+ errorRef: formatHeteroErrorId(kind),+ isFallback: spec.isFallback ?? false,+ numericId: spec.numericId,+ retryable: spec.retryable,+ severity: spec.severity,+ type: 'AgentRuntimeError',+ };+};++/** Project only documented, non-sensitive fields into webhook payloads. */+export const readHeterogeneousErrorContext = (+ error: ChatMessageError | undefined,+): ChatErrorHeterogeneousContext | undefined => {+ if (!error) return;+ const normalized = normalizeHeterogeneousMessageError(error);+ const body = isRecord(normalized.body) ? normalized.body : {};+ const details = isRecord(body.details) ? body.details : {};+ const kind = knownKind(details.kind);+ if (!kind || typeof body.agentType !== 'string' || !isLocalHeterogeneousType(body.agentType))+ return;+ const info = isRecord(body.rateLimitInfo) ? body.rateLimitInfo : {};+ const rejectedQuota = kind === 'usage_limit' && info.status === 'rejected';+ return {+ agentType: body.agentType,+ kind,+ ...(rejectedQuota && typeof info.rateLimitType === 'string'+ ? { rateLimitType: info.rateLimitType }+ : {}),+ ...(rejectedQuota &&+ typeof info.resetsAt === 'number' &&+ Number.isFinite(info.resetsAt) &&+ info.resetsAt > 0 &&+ info.resetsAt < 8640000000000+ ? { resetsAt: info.resetsAt }+ : {}),+ };+};diff --git a/packages/locales/src/default/modelRuntime.ts b/packages/locales/src/default/modelRuntime.tsindex d61409ad90c..90eae7d6f05 100644--- a/packages/locales/src/default/modelRuntime.ts+++ b/packages/locales/src/default/modelRuntime.ts@@ -1,94 +1,155 @@export default {- AccountDeactivated:+ 'AccountDeactivated':'Your account has been deactivated or suspended. This may be due to policy, security, or account review reasons. Please contact the provider support for assistance.',- AgentRuntimeError:+ 'AgentRuntimeError':'Lobe language model runtime execution error. Please troubleshoot or retry based on the following information.',- CapabilityNotSupported:+ 'CapabilityNotSupported':'Sorry, this model does not support the requested capability (such as vision input or tool calling). Please switch to a model that supports it.',- ComfyUIBizError:+ 'ComfyUIBizError':'An error occurred while requesting the ComfyUI service. Please troubleshoot using the information below or try again.',- ComfyUIEmptyResult:+ 'ComfyUIEmptyResult':'No image was generated by ComfyUI. Please check the model configuration or try again.',- ComfyUIModelError: 'Failed to load the ComfyUI model. Please ensure the model file exists.',- ComfyUIServiceUnavailable:+ 'ComfyUIModelError': 'Failed to load the ComfyUI model. Please ensure the model file exists.',+ 'ComfyUIServiceUnavailable':'Failed to connect to the ComfyUI service. Please ensure it is running properly and the service URL is correctly configured.',- ComfyUIUploadFailed:+ 'ComfyUIUploadFailed':'Failed to upload image to ComfyUI. Please check the server connection or try again.',- ComfyUIWorkflowError:+ 'ComfyUIWorkflowError':'ComfyUI workflow execution failed. Please verify the workflow configuration.',- ConnectionCheckFailed:+ 'ConnectionCheckFailed':'The request returned empty. Please check if the API proxy address does not end with `/v1`.',- ContentModeration:+ 'ContentModeration':'Sorry, the content was rejected by the upstream safety filter. Please revise your prompt and try again.',- ContextEnginePipelineError:+ 'ContextEnginePipelineError':'Failed to assemble the conversation context for this request. Please try again; if it persists, contact support.',- DatabasePersistError:+ 'ConversationParentMissing':+ 'The conversation context for this message could not be found. Reopen the conversation or start a new topic, then send the request again.',+ 'DatabasePersistError':'A database operation failed while saving or loading this conversation. Please try again; if it persists, contact support.',- ExceededContextWindow:+ 'ExceededContextWindow':'The current request content exceeds the length that the model can handle. Please reduce the amount of content and try again.',- HarnessJsonParseError:+ 'ExceededToolLimit':+ 'This run reached its tool-call limit. Break the task into smaller steps, or ask the agent owner to adjust the tool-call limit.',+ 'HarnessJsonParseError':'An internal payload could not be read back, so this operation stopped. Retrying the same request will hit the same failure โ please start a new message; if it persists, contact support.',- InsufficientQuota:+ 'InsufficientQuota':"Sorry, the quota for this key has been reached. Please check if your account balance is sufficient or try again after increasing the key's quota.",- InvalidBedrockCredentials:+ 'InvalidBedrockCredentials':'Bedrock authentication failed. Please check the AccessKeyId/SecretAccessKey and retry.',- InvalidComfyUIArgs: 'Invalid ComfyUI configuration. Please check the settings and try again.',- InvalidGithubToken:+ 'InvalidComfyUIArgs': 'Invalid ComfyUI configuration. Please check the settings and try again.',+ 'InvalidGithubCopilotToken':+ 'GitHub Copilot authentication failed. Ask the bot or agent owner to refresh the GitHub Copilot credentials, then try again.',+ 'InvalidGithubToken':'The GitHub Personal Access Token is incorrect or empty. Please check your GitHub Personal Access Token and try again.',- InvalidOllamaArgs:+ 'InvalidOllamaArgs':'Invalid Ollama configuration, please check Ollama configuration and try again',- InvalidProviderAPIKey:+ 'InvalidProviderAPIKey':'{{provider}} API Key is incorrect or empty, please check your {{provider}} API Key and try again',- InvalidRequestFormat:+ 'InvalidRequestFormat':'Sorry, the upstream provider rejected the request as malformed. Please check the input or try a different model.',- InvalidVertexCredentials:+ 'InvalidVertexCredentials':'Vertex authentication failed. Please check your credentials and try again.',- LocationNotSupportError:+ 'LobeHubModelDeprecated':+ 'The selected model is no longer available. Ask the bot or agent owner to select an available model, then try again.',+ 'LocationNotSupportError':"We're sorry, your current location does not support this model service. This may be due to regional restrictions or the service not being available. Please confirm if the current location supports using this service, or try using a different location.",- ModelEmptyCompletion:+ 'ModelEmptyCompletion':'The model provider returned an empty response. Even without visible content, this request may still incur charges. You can retry or switch models and try again.',- ModelEmptyCompletionWithCost:+ 'ModelEmptyCompletionWithCost':'The model provider returned an empty response. This request cost {{credits}} credits. Retrying may incur a similar cost, or you can switch models.',- ModelRefusal:+ 'ModelRefusal':'The model declined to answer this request. Try rephrasing it or choose another model.',- ModelNotFound:+ 'ModelNotFound':'Sorry, the requested model could not be found. It may not exist or you may not have the necessary access permissions. Please try again after changing the API Key or adjusting your access permissions.',- NoAvailableChannel:+ 'NoAvailableChannel':'Sorry, the proxy or router has no available channel for the requested model. Please switch the channel/key configuration or try again later.',- OllamaBizError:+ 'OllamaBizError':'Error requesting Ollama service, please troubleshoot or retry based on the following information',- OllamaServiceUnavailable:+ 'OllamaServiceUnavailable':'Ollama service is unavailable. Please check if Ollama is running properly or if the cross-origin configuration of Ollama is set correctly.',- OperationInactivityTimeout:+ 'OperationInactivityTimeout':'The agent operation was idle for too long and was terminated. Please retry the request.',- PermissionDenied:+ 'PermissionDenied':'Sorry, you do not have permission to access this service. Please check if your key has the necessary access rights.',- ProviderBizError:+ 'ProviderBizError':'Error requesting {{provider}} service, please troubleshoot or retry based on the following information',- ProviderContentPolicyViolation:+ 'ProviderContentPolicyViolation':'The provider blocked this request or its output due to content policy. Please revise your prompt and try again.',- ProviderNetworkError:+ 'ProviderNetworkError':'Connection to the provider timed out or was dropped. Please check your network and try again.',- ProviderServiceUnavailable:+ 'ProviderNoImageGenerated':+ 'The provider returned no image for this request. Try rephrasing the request, or choose a model that supports image generation.',+ 'ProviderServiceUnavailable':'The provider is temporarily overloaded or unavailable. Please try again shortly.',- QuotaLimitReached:+ 'QuotaLimitReached':"Sorry, the token usage or request count has reached the quota limit for this key. Please increase the key's quota or try again later.",- RateLimitExceeded:+ 'RateLimitExceeded':"Sorry, the token usage or request count has reached the rate limit for this key. Please try again later or increase the key's quota.",- RequestBodyTooLarge:+ 'RequestBodyTooLarge':'This request is too large for the model provider. Compact the conversation or reduce attached content, then try again.',- StateStorePersistError:+ 'StateStorePersistError':'A temporary issue with the conversation state store interrupted this operation. Please try again; if it persists, contact support.',- StateStoreReadError:+ 'StateStoreReadError':'This operation could not be resumed because its session state was unavailable. Please reopen the conversation to continue; if it persists, contact support.',- StreamChunkError:+ 'StreamChunkError':'Error parsing the message chunk of the streaming request. Please check if the current API interface complies with the standard specifications, or contact your API provider for assistance.',- UpstreamGatewayError:+ 'UpstreamGatewayError':'The upstream gateway or proxy returned an error. Please try again shortly; if it persists, check your proxy / endpoint configuration.',- UpstreamHttpError:+ 'UpstreamHttpError':'The provider returned an HTTP error without further detail. Please try again, or check your request and model configuration.',- UpstreamMalformedResponse:+ 'UpstreamMalformedResponse':'The provider returned a malformed response that could not be parsed. Please retry; if it persists, try a different model or provider.',- UserConfigError:+ 'UserConfigError':'Provider configuration is invalid (incorrect base URL, missing environment variable, virtual-key restriction, etc.). Please review the provider settings.',+ 'heterogeneous.auth_required.title': 'Sign-in required',+ 'heterogeneous.auth_required.description':+ 'Ask the bot owner to sign in again on the device running {{agent}}.',+ 'heterogeneous.usage_limit.title': 'Usage limit reached',+ 'heterogeneous.usage_limit.description':+ 'The account used by {{agent}} has exhausted its allowance. Wait for the quota to reset, or ask the bot owner to switch to an account or model with available quota.',+ 'heterogeneous.credit_limit.title': 'Credits exhausted',+ 'heterogeneous.credit_limit.description':+ 'Ask the bot owner to add credits to the account used by {{agent}}, or switch models. Waiting for a quota reset will not restore these credits.',+ 'heterogeneous.server_overloaded.title': 'Provider temporarily unavailable',+ 'heterogeneous.server_overloaded.description':+ 'The provider behind {{agent}} is busy or unavailable. Please try again shortly.',+ 'heterogeneous.server_throttle.title': 'Requests temporarily limited',+ 'heterogeneous.server_throttle.description':+ 'The provider is temporarily limiting requests from {{agent}}. Please wait a moment and try again.',+ 'heterogeneous.network_drop.title': 'Connection interrupted',+ 'heterogeneous.network_drop.description':+ '{{agent}} lost its connection before finishing. Retry; if it happens again, ask the bot owner to check the running deviceโs network and proxy settings.',+ 'heterogeneous.invalid_request.title': 'Request rejected',+ 'heterogeneous.invalid_request.description':+ 'The provider rejected the request sent by {{agent}}. Try a new topic; if it persists, share the Operation ID with support.',+ 'heterogeneous.unsupported_attachment.title': 'Attachment unsupported',+ 'heterogeneous.unsupported_attachment.description':+ '{{agent}} could not read an attachment. Remove it or convert it to a supported format, then resend the request.',+ 'heterogeneous.aborted.title': 'Task stopped',+ 'heterogeneous.aborted.description':+ 'This {{agent}} task was stopped. Send a new request when you want to continue.',+ 'heterogeneous.max_turns.title': 'Step limit reached',+ 'heterogeneous.max_turns.description':+ '{{agent}} reached its step limit before finishing. Split the task into smaller steps, or ask the bot owner to adjust the limit.',+ 'heterogeneous.resume_thread_not_found.title': 'Previous session unavailable',+ 'heterogeneous.resume_thread_not_found.description':+ '{{agent}} could not find the previous session. Start a new topic and resend the request.',+ 'heterogeneous.resume_cwd_mismatch.title': 'Session directory changed',+ 'heterogeneous.resume_cwd_mismatch.description':+ 'Ask the bot owner to restore the working directory used by this {{agent}} session, or start a new topic.',+ 'heterogeneous.cli_not_found.title': 'Agent CLI unavailable',+ 'heterogeneous.cli_not_found.description':+ 'Ask the bot owner to install or repair {{agent}} on the device running this task.',+ 'heterogeneous.working_directory_not_found.title': 'Working directory unavailable',+ 'heterogeneous.working_directory_not_found.description':+ 'The working directory for {{agent}} is missing. Ask the bot owner to restore it or choose an existing directory.',+ 'heterogeneous.model_unavailable.title': 'Model unavailable',+ 'heterogeneous.model_unavailable.description':+ 'The model selected for {{agent}} is unavailable. Ask the bot owner to choose another model.',+ 'heterogeneous.agent_failed.title': 'Agent task failed',+ 'heterogeneous.agent_failed.description':+ '{{agent}} stopped without a recognized cause. Share the Operation ID with the bot owner or support to investigate.',+ 'heterogeneous.reset': 'Quota resets at {{time}} (UTC).',+ 'heterogeneous.window.seven_day': 'Weekly allowance exhausted.',+ 'heterogeneous.window.five_hour': 'Session allowance exhausted.',};diff --git a/packages/model-runtime/src/errors/index.ts b/packages/model-runtime/src/errors/index.tsindex 3e9b8eef3bd..0da080e38cd 100644--- a/packages/model-runtime/src/errors/index.ts+++ b/packages/model-runtime/src/errors/index.ts@@ -3,6 +3,7 @@ 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 { normalizeChatMessageError } from './normalizeChatMessageError';export { ERROR_PATTERNS, type ErrorPattern } from './patterns';export { refineErrorCode, type RefineErrorInput } from './refine';export {diff --git a/packages/model-runtime/src/errors/normalizeChatMessageError.test.ts b/packages/model-runtime/src/errors/normalizeChatMessageError.test.tsnew file mode 100644index 00000000000..fd1eaf0099a--- /dev/null+++ b/packages/model-runtime/src/errors/normalizeChatMessageError.test.ts@@ -0,0 +1,73 @@+import { describe, expect, it } from 'vitest';++import { normalizeChatMessageError } from './normalizeChatMessageError';++describe('normalizeChatMessageError', () => {+ it.each([+ { body: { error: { message: 'insufficient quota' } }, type: 'ProviderBizError' },+ { error: { message: 'insufficient quota' }, errorType: 'ProviderBizError' },+ { message: 'insufficient quota' },+ 'insufficient quota',+ ])('normalizes equivalent quota errors: %j', (input) => {+ const result = normalizeChatMessageError(input);+ expect(result).toMatchObject({+ attribution: 'user',+ message: 'insufficient quota',+ numericId: 2001,+ retryable: false,+ type: 'InsufficientQuota',+ });+ expect(normalizeChatMessageError(result)).toEqual(result);+ });++ it('preserves a non-enumerable Error message with a known errorType', () => {+ const error = Object.assign(new Error('provider credentials rejected'), {+ errorType: 'InvalidProviderAPIKey',+ });+ expect(normalizeChatMessageError(error)).toMatchObject({+ message: 'provider credentials rejected',+ type: 'InvalidProviderAPIKey',+ });+ });++ it('keeps a known code authoritative over a misleading message', () => {+ expect(+ normalizeChatMessageError({ code: 'PermissionDenied', message: 'insufficient quota' }),+ ).toMatchObject({ type: 'PermissionDenied' });+ });++ it('preserves hetero guide metadata and recovery context', () => {+ const body = {+ agentType: 'claude-code',+ code: 'rate_limit',+ details: { kind: 'usage_limit' },+ message: 'Weekly allowance exhausted',+ rateLimitInfo: { rateLimitType: 'seven_day', resetsAt: 1789826400 },+ };+ expect(normalizeChatMessageError(body)).toMatchObject({ body });+ });++ it('merges upstream status with display context and preserves budget', () => {+ const result = normalizeChatMessageError({+ _responseBody: { error: { message: 'Payment required' } },+ budget: { budgetTypeAtError: 'workspace' },+ error: { status: 402 },+ errorType: 'ProviderBizError',+ provider: 'lobehub',+ });+ expect(result).toMatchObject({+ body: {+ budget: { budgetTypeAtError: 'workspace' },+ error: { message: 'Payment required', status: 402 },+ provider: 'lobehub',+ },+ type: 'InsufficientQuota',+ });+ });++ it('does not infer a provider outage from an unclassified internal 500', () => {+ expect(normalizeChatMessageError(new Error('500 unexpected internal failure'))).toMatchObject({+ type: 500,+ });+ });+});diff --git a/packages/model-runtime/src/errors/normalizeChatMessageError.ts b/packages/model-runtime/src/errors/normalizeChatMessageError.tsnew file mode 100644index 00000000000..ee557215991--- /dev/null+++ b/packages/model-runtime/src/errors/normalizeChatMessageError.ts@@ -0,0 +1,255 @@+import { AgentRuntimeErrorType, ChatErrorType, type ChatMessageError } from '@lobechat/types';+import { isRecord } from '@lobechat/utils/object';++import { refineErrorCode } from './refine';+import { getErrorCodeSpec } from './specs';++/** Pull a usable HTTP status out of the nested upstream error object. */+const extractHttpStatus = (body: unknown): number | undefined => {+ if (!body || typeof body !== 'object') return undefined;+ const b = body as { error?: { status?: unknown }; status?: unknown; statusCode?: unknown };+ if (typeof b.status === 'number') return b.status;+ if (typeof b.statusCode === 'number') return b.statusCode;+ if (b.error && typeof b.error === 'object' && typeof b.error.status === 'number') {+ return b.error.status;+ }+ return undefined;+};++const extractProvider = (body: unknown): string | undefined => {+ if (!body || typeof body !== 'object') return undefined;+ const p = (body as { provider?: unknown }).provider;+ return typeof p === 'string' ? p : undefined;+};++const extractMessage = (value: unknown, depth = 0): string | undefined => {+ if (typeof value === 'string') return value.trim() ? value : undefined;+ if (!isRecord(value) || depth > 5) return undefined;+ if (typeof value.message === 'string' && value.message.trim() && value.message !== 'error') {+ return value.message;+ }+ for (const nested of [value.error, value._responseBody, value.body]) {+ const message = extractMessage(nested, depth + 1);+ if (message) return message;+ }+};++interface ChatCompletionErrorPayloadLike {+ _responseBody?: unknown;+ body?: unknown;+ budget?: unknown;+ error?: unknown;+ errorType: ChatMessageError['type'];+ message?: string;+ provider?: unknown;+}++const mergePayloadError = (+ sourceBody: Record<string, unknown>,+ payload: ChatCompletionErrorPayloadLike,+): unknown | undefined => {+ if (+ payload.body !== undefined ||+ payload._responseBody === undefined ||+ payload.error === undefined+ )+ return undefined;+ if (!('error' in sourceBody)) return payload.error;+ if (isRecord(sourceBody.error) && isRecord(payload.error)) {+ return { ...payload.error, ...sourceBody.error };+ }+};++const buildPayloadBody = (+ payload: ChatCompletionErrorPayloadLike,+ originalError: unknown,+ message: string,+): unknown => {+ // Runtime payloads often keep UI context (for example quota hints) next to+ // `error`, while `error` itself only carries the display message. Merge both+ // layers so normalizing `{ errorType, error }` does not drop the fields the+ // chat error renderer needs later.+ const sourceBody = payload.body ?? payload._responseBody ?? payload.error ?? originalError;+ const context: Record<string, unknown> = {};++ if (payload.budget !== undefined) context.budget = payload.budget;+ if (typeof payload.provider === 'string') context.provider = payload.provider;++ if (isRecord(sourceBody)) {+ const payloadError = mergePayloadError(sourceBody, payload);++ return {+ ...sourceBody,+ // `_responseBody` is the display-facing body, but gateway/model-runtime+ // still carries status/provider details in `error` for some failures:+ // `{ _responseBody: { error: { message } }, error: { status: 402 } }`.+ ...(payloadError === undefined ? {} : { error: payloadError }),+ ...(payload.budget !== undefined && !('budget' in sourceBody)+ ? { budget: payload.budget }+ : {}),+ ...(typeof payload.provider === 'string' && !('provider' in sourceBody)+ ? { provider: payload.provider }+ : {}),+ ...('message' in sourceBody ? {} : { message }),+ };+ }++ return {+ ...context,+ ...(sourceBody === undefined ? {} : { error: sourceBody }),+ message,+ };+};++/**+ * Cap a stack before it lands in `agent_operations.error` / trace snapshots.+ * The top frames identify the throw site; the rest is runtime plumbing that+ * would only bloat every stored error row.+ */+const STACK_MAX_CHARS = 1000;++const truncateStack = (stack: string | undefined): string | undefined => {+ if (!stack) return undefined;+ return stack.length > STACK_MAX_CHARS ? `${stack.slice(0, STACK_MAX_CHARS)}โฆ` : stack;+};++/**+ * Merge classification metadata from `ERROR_CODE_SPECS` onto a normalized+ * `ChatMessageError`. Codes that aren't in the spec table (fallbacks like+ * `InternalServerError`, or numeric ChatErrorType values) pass through+ * unchanged โ every classification field stays optional.+ *+ * Keeping enrichment in one place means downstream consumers (`agent_operations.error`+ * JSONB, S3 trace snapshots, agent-gateway WS push, dashboards) all get the+ * same shape without re-running pattern matching themselves.+ */+const enrichWithSpec = (formatted: ChatMessageError): ChatMessageError => {+ // Generic `ProviderBizError` is re-derived from the message / HTTP status into+ // a more specific code before enrichment, so the catch-all doesn't swallow+ // rate-limits, network drops, quota, etc. Specific codes pass through.+ const refined = refineErrorCode({+ errorType: String(formatted.type),+ httpStatus: extractHttpStatus(formatted.body),+ message: formatted.message,+ provider: extractProvider(formatted.body),+ });+ const type = (refined ?? formatted.type) as ChatMessageError['type'];++ // `getErrorCodeSpec` is keyed by `ILobeAgentRuntimeErrorType` strings; coerce+ // because `ChatMessageError['type']` widens to include numeric `ChatErrorType`+ // values, which simply miss the lookup and pass through unenriched.+ const spec = getErrorCodeSpec(String(type));+ if (!spec) return formatted;++ return {+ ...formatted,+ attribution: spec.attribution,+ category: spec.category,+ countAsFailure: spec.countAsFailure,+ httpStatus: spec.httpStatus,+ isFallback: spec.isFallback ?? false,+ numericId: spec.numericId,+ retryable: spec.retryable,+ severity: spec.severity,+ type,+ };+};++/**+ * Normalize an arbitrary thrown value into `ChatMessageError`, then attach+ * classification metadata from `ERROR_CODE_SPECS` so the resulting object+ * is self-describing for everything downstream of the runtime catch block.+ *+ * Handles four input shapes:+ *+ * 1. `ChatCompletionErrorPayload` โ what `model-runtime` throws on LLM+ * failures: `{ errorType, error, provider?, message? }`.+ * 2. Already-normalized `ChatMessageError` (`{ type, message?, body? }`)+ * โ re-enriched in place so the helper is safe to call twice (the inner+ * `runtime.step()` non-throwing error path and the outer `executeStep`+ * catch can both run through here without double-wrapping).+ * 3. Standard `Error` instance โ wrapped as `InternalServerError`.+ * 4. Anything else โ a loosely-typed `{ message }` body (e.g. a heterogeneous CLI+ * agent's wire `error` event data `{ code, message, stderr }`) or a raw string โ+ * mapped to `AgentRuntimeError` with a real extracted message. This branch is+ * the single canonical replacement for the hetero-specific `toChatMessageError`.+ */+export const normalizeChatMessageError = (error: unknown): ChatMessageError => {+ if (+ isRecord(error) &&+ (typeof error.errorType === 'string' || typeof error.errorType === 'number')+ ) {+ const payload: ChatCompletionErrorPayloadLike = {+ ...error,+ errorType: error.errorType as ChatMessageError['type'],+ message: typeof error.message === 'string' ? error.message : undefined,+ };+ const message =+ (payload.message && payload.message !== 'error' ? payload.message : undefined) ??+ extractMessage(payload.body) ??+ extractMessage(payload._responseBody) ??+ extractMessage(payload.error) ??+ String(payload.errorType);++ return enrichWithSpec({+ body: buildPayloadBody(payload, error, message),+ message,+ type: payload.errorType,+ });+ }++ // Path 2: already-normalized ChatMessageError shape โ has `type` but not+ // `errorType`, and isn't a thrown Error instance. Common when the inner+ // runtime.step() catch has already stuffed a partial ChatMessageError into+ // `newState.error` and the outer service is just topping it up.+ if (+ error &&+ typeof error === 'object' &&+ !(error instanceof Error) &&+ 'type' in error &&+ (typeof (error as { type: unknown }).type === 'string' ||+ typeof (error as { type: unknown }).type === 'number')+ ) {+ const formatted = error as ChatMessageError;+ const message = extractMessage(formatted);+ return enrichWithSpec({ ...formatted, ...(message ? { message } : {}) });+ }++ if (error instanceof Error) {+ // Unclassified harness throw: nothing upstream recognized it, so `name` ++ // `message` are all the triage signal there is โ and for a `SyntaxError`+ // out of some `JSON.parse` those two say nothing about WHERE it blew up.+ // Persist a bounded stack so a recurring 500 is locatable from the stored+ // operation instead of needing a live repro.+ return enrichWithSpec({+ body: { name: error.name, stack: truncateStack(error.stack) },+ message: error.message,+ type: ChatErrorType.InternalServerError,+ });+ }++ // Path 4: arbitrary thrown value. A loosely-typed object (no `errorType`, no+ // string/number `type`) keeps its body and contributes its `.message` rather+ // than being stringified to '[object Object]' โ this is what the heterogeneous+ // CLI agents emit on the wire (`{ code, message, stderr }`). A raw string or any+ // other primitive becomes a `{ message }` body. Mirrors the former+ // `toChatMessageError`, then runs through `enrichWithSpec` so even these get+ // classification (the bare hetero formatter never did).+ if (isRecord(error)) {+ return enrichWithSpec({+ body: error,+ message: extractMessage(error) ?? 'Agent runtime error',+ type:+ typeof error.code === 'string'+ ? (getErrorCodeSpec(error.code)?.code ?? AgentRuntimeErrorType.AgentRuntimeError)+ : AgentRuntimeErrorType.AgentRuntimeError,+ });+ }++ const message = typeof error === 'string' ? error : 'Agent runtime error';+ return enrichWithSpec({+ body: { message },+ message,+ type: AgentRuntimeErrorType.AgentRuntimeError,+ });+};diff --git a/packages/types/src/message/common/base.ts b/packages/types/src/message/common/base.tsindex 78ee7136eec..9f31e91d4e0 100644--- a/packages/types/src/message/common/base.ts+++ b/packages/types/src/message/common/base.ts@@ -42,6 +42,15 @@ export interface ChatErrorBudgetContext {shortfallCredits?: number;}+/** Safe external-agent error context for completion hooks and IM replies. */+export interface ChatErrorHeterogeneousContext {+ agentType: string;+ kind: string;+ rateLimitType?: string;+ /** Quota reset as Unix epoch seconds, only from a rejected quota window. */+ resetsAt?: number;+}+/*** Chat message error object*/@@ -53,6 +62,8 @@ export interface ChatMessageError {category?: string;/** Whether this counts toward operational failure metrics. */countAsFailure?: boolean;+ /** Namespaced support reference, e.g. H2001 for an external agent. */+ errorRef?: string;/** HTTP status the runtime returned (or would return) for this error. */httpStatus?: number;/**@@ -74,6 +85,7 @@ export interface ChatMessageError {export const ChatMessageErrorSchema = z.object({attribution: z.enum(['user', 'provider', 'harness', 'system']).optional(),body: z.any().optional(),+ errorRef: z.string().optional(),category: z.string().optional(),countAsFailure: z.boolean().optional(),httpStatus: z.number().optional(),diff --git a/src/features/Conversation/ChatItem/components/ErrorContent.test.tsx b/src/features/Conversation/ChatItem/components/ErrorContent.test.tsxindex 0416edd07b4..e5ba5e13ace 100644--- a/src/features/Conversation/ChatItem/components/ErrorContent.test.tsx+++ b/src/features/Conversation/ChatItem/components/ErrorContent.test.tsx@@ -2,7 +2,6 @@* @vitest-environment happy-dom*/import { fireEvent, render, screen } from '@testing-library/react';-import type { ReactNode } from 'react';import { beforeEach, describe, expect, it, vi } from 'vitest';import ErrorContent from './ErrorContent';@@ -12,20 +11,6 @@ const updateMessageErrorMock = vi.fn();let messageContent: string | undefined = '';let isRegenerating = false;-// Drive the Alert's `afterClose` directly via a click, so we exercise-// ErrorContent's dismiss branching without the real close animation.-vi.mock('@lobehub/ui/base-ui', async (importOriginal) => ({- ...(await importOriginal<object>()),- Alert: ({ action, afterClose }: { action?: ReactNode; afterClose?: () => void }) => (- <div>- <button type="button" onClick={() => afterClose?.()}>- close- </button>- {action}- </div>- ),-}));-vi.mock('@/features/Conversation/store', () => ({dataSelectors: {getDisplayMessageById: (id: string) => () => ({ content: messageContent, id }),@@ -47,11 +32,29 @@ describe('ErrorContent dismiss behavior', () => {isRegenerating = false;});+ it('starts with collapsed diagnostics while keeping the reason and retry available', () => {+ const retry = vi.fn();+ const { container } = render(+ <ErrorContent+ error={{ message: 'Quota exhausted', extra: <pre>provider diagnostics</pre> }}+ id="msg-1"+ onRegenerate={retry}+ />,+ );++ expect(screen.getByRole('alert')).toHaveAttribute('data-alert-variant', 'outlined');+ expect(screen.getByText('Quota exhausted')).toBeVisible();+ expect(container.querySelector('details')).not.toHaveAttribute('open');+ expect(screen.getByText('Show Details')).toBeVisible();+ fireEvent.click(screen.getByRole('button', { name: /regenerate/i }));+ expect(retry).toHaveBeenCalledOnce();+ });+it('clears only the error (keeps the message) when the turn already streamed content', () => {messageContent = 'already streamed text';render(<ErrorContent error={{ message: 'boom' } as any} id="msg-1" />);- fireEvent.click(screen.getByText('close'));+ fireEvent.click(screen.getByRole('button', { name: 'Close alert' }));expect(updateMessageErrorMock).toHaveBeenCalledWith('msg-1', null);expect(deleteMessageMock).not.toHaveBeenCalled();@@ -61,7 +64,7 @@ describe('ErrorContent dismiss behavior', () => {messageContent = '';render(<ErrorContent error={{ message: 'boom' } as any} id="msg-1" />);- fireEvent.click(screen.getByText('close'));+ fireEvent.click(screen.getByRole('button', { name: 'Close alert' }));expect(deleteMessageMock).toHaveBeenCalledWith('msg-1');expect(updateMessageErrorMock).not.toHaveBeenCalled();diff --git a/src/features/Conversation/ChatItem/components/ErrorContent.tsx b/src/features/Conversation/ChatItem/components/ErrorContent.tsxindex 00528725de0..c45109793b9 100644--- a/src/features/Conversation/ChatItem/components/ErrorContent.tsx+++ b/src/features/Conversation/ChatItem/components/ErrorContent.tsx@@ -1,4 +1,5 @@import { Alert, Button, Skeleton } from '@lobehub/ui/base-ui';+import { createStaticStyles, cx } from 'antd-style';import { RotateCcw } from 'lucide-react';import { memo, Suspense } from 'react';import { useTranslation } from 'react-i18next';@@ -11,6 +12,34 @@ import {import { type ChatItemProps } from '../type';+const styles = createStaticStyles(({ css }) => ({+ close: css`+ @media (width <= 480px) {+ width: 24px;+ height: 24px;+ }+ `,+ extraContent: css`+ padding: 0;+ background: transparent;++ @media (width <= 480px) {+ margin-inline: 8px;+ }+ `,+ extraHeader: css`+ @media (width <= 480px) {+ padding-inline: 8px;+ }+ `,+ root: css`+ @media (width <= 480px) {+ gap: 6px;+ padding-inline: 8px;+ }+ `,+}));+export interface ErrorContentProps {customErrorRender?: ChatItemProps['customErrorRender'];error: ChatItemProps['error'];@@ -43,10 +72,10 @@ const ErrorContent = memo<ErrorContentProps>(({ customErrorRender, error, id, onreturn (<Alertclosable- extraDefaultExpandshowIconextraIsolate={false}type={'secondary'}+ variant={'outlined'}action={onRegenerate && (<Button@@ -75,6 +104,13 @@ const ErrorContent = memo<ErrorContentProps>(({ customErrorRender, error, id, ondeleteMessage(id);}}}+ classNames={{+ ...error.classNames,+ close: cx(styles.close, error.classNames?.close),+ extraContent: cx(styles.extraContent, error.classNames?.extraContent),+ extraHeader: cx(styles.extraHeader, error.classNames?.extraHeader),+ root: cx(styles.root, error.classNames?.root),+ }}style={{overflow: 'hidden',position: 'relative',diff --git a/src/features/Conversation/Error/index.tsx b/src/features/Conversation/Error/index.tsxindex ac4033c3c25..8dd235e606b 100644--- a/src/features/Conversation/Error/index.tsx+++ b/src/features/Conversation/Error/index.tsx@@ -1,5 +1,6 @@import { isDesktop } from '@lobechat/const';import { HeterogeneousAgentSessionErrorCode } from '@lobechat/electron-client-ipc';+import { readHeterogeneousErrorContext } from '@lobechat/heterogeneous-agents/errors';import { type ILobeAgentRuntimeErrorType } from '@lobechat/model-runtime';import { AgentRuntimeErrorType, getErrorCodeSpec } from '@lobechat/model-runtime';import { type ChatMessageError, type ErrorType, type IToolErrorType } from '@lobechat/types';@@ -400,7 +401,7 @@ const ErrorMessageExtra = memo<ErrorExtraProps>(isHeterogeneousAgentStatusGuideError(sessionErrorBody) &&sessionErrorBody.code === HeterogeneousAgentSessionErrorCode.RateLimit;const rateLimitInfo = isHeterogeneousAgentStatusGuideError(sessionErrorBody)- ? sessionErrorBody.rateLimitInfo+ ? readHeterogeneousErrorContext({ type: 'AgentRuntimeError', body: sessionErrorBody }): undefined;const schedule: HeterogeneousAgentScheduleState | undefined = isRateLimitErrordiff --git a/src/features/Electron/HeterogeneousAgent/StatusGuide/states/RateLimitState.tsx b/src/features/Electron/HeterogeneousAgent/StatusGuide/states/RateLimitState.tsxindex ea2f171c272..2cfee370ecf 100644--- a/src/features/Electron/HeterogeneousAgent/StatusGuide/states/RateLimitState.tsx+++ b/src/features/Electron/HeterogeneousAgent/StatusGuide/states/RateLimitState.tsx@@ -1,3 +1,4 @@+import { readHeterogeneousErrorContext } from '@lobechat/heterogeneous-agents/errors';import { Flexbox } from '@lobehub/ui';import { Button, Text } from '@lobehub/ui/base-ui';import { CalendarClock, Play, RotateCcw } from 'lucide-react';@@ -25,11 +26,12 @@ const RateLimitState = ({variant,}: HeterogeneousAgentGuideStateProps) => {const { t, i18n } = useTranslation('chat');+ const quotaContext = readHeterogeneousErrorContext({ type: 'AgentRuntimeError', body: error });const rawErrorDetails = error?.stderr || error?.message;const dateLocale = i18n.resolvedLanguage || i18n.language || undefined;// Prefer the persisted scheduled reset time so the "ๅทฒๅฎๆ" copy stays stable// even if the live error payload is missing it on reload.- const effectiveResetsAt = schedule?.resetsAt ?? error?.rateLimitInfo?.resetsAt;+ const effectiveResetsAt = schedule?.resetsAt ?? quotaContext?.resetsAt;const timezoneLabel = useMemo(() => extractTimezoneLabel(rawErrorDetails) || Intl.DateTimeFormat().resolvedOptions().timeZone,[rawErrorDetails],@@ -56,7 +58,7 @@ const RateLimitState = ({}}, [dateLocale, effectiveResetsAt, timezoneLabel]);const rateLimitTypeLabel = useMemo(() => {- const rateLimitType = error?.rateLimitInfo?.rateLimitType;+ const rateLimitType = quotaContext?.rateLimitType;if (!rateLimitType) return;if (rateLimitType === 'seven_day') {@@ -68,7 +70,7 @@ const RateLimitState = ({}return rateLimitType.replaceAll('_', ' ');- }, [error?.rateLimitInfo?.rateLimitType, t]);+ }, [quotaContext?.rateLimitType, t]);// The "~X h Y m" duration string, reused both for the header hint and the// scheduling action/label copy.const relativeDuration = useMemo(() => {diff --git a/src/services/message/index.ts b/src/services/message/index.tsindex 0ec677b0582..e709acfb7bb 100644--- a/src/services/message/index.ts+++ b/src/services/message/index.ts@@ -1,3 +1,5 @@+import { normalizeHeterogeneousMessageError } from '@lobechat/heterogeneous-agents/errors';+import { normalizeChatMessageError } from '@lobechat/model-runtime/errors';import {type ChatMessageError,type ChatMessagePluginError,@@ -222,9 +224,7 @@ export class MessageService {};updateMessageError = async (id: string, value: ChatMessageError, ctx?: MessageQueryContext) => {- const error = value.type- ? value- : { body: value, message: value.message, type: 'ApplicationRuntimeError' };+ const error = normalizeHeterogeneousMessageError(normalizeChatMessageError(value));return lambdaClient.message.update.mutate({...ctx,diff --git a/src/store/chat/slices/agentRun/actions/__tests__/gatewayEventHandler.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/gatewayEventHandler.test.tsindex c0fda039d21..77a0bba4ee2 100644--- a/src/store/chat/slices/agentRun/actions/__tests__/gatewayEventHandler.test.ts+++ b/src/store/chat/slices/agentRun/actions/__tests__/gatewayEventHandler.test.ts@@ -1110,11 +1110,11 @@ describe('createGatewayEventHandler', () => {expect(store.completeOperation).not.toHaveBeenCalled();expect(messageService.updateMessageError).toHaveBeenCalledWith('msg-initial',- {+ expect.objectContaining({body: { message: 'Something went wrong' },message: 'Something went wrong',type: 'AgentRuntimeError',- },+ }),{agentId: 'agent-1',groupId: undefined,@@ -1129,11 +1129,11 @@ describe('createGatewayEventHandler', () => {id: 'msg-initial',type: 'updateMessage',value: {- error: {+ error: expect.objectContaining({body: { message: 'Something went wrong' },message: 'Something went wrong',type: 'AgentRuntimeError',- },+ }),},},{ operationId: 'op-1' },@@ -1159,11 +1159,11 @@ describe('createGatewayEventHandler', () => {expect(store.completeOperation).not.toHaveBeenCalled();expect(messageService.updateMessageError).toHaveBeenCalledWith('msg-step2',- {- body: { message: 'Timeout' },+ expect.objectContaining({+ body: { error: 'Timeout' },message: 'Timeout',type: 'AgentRuntimeError',- },+ }),{agentId: 'agent-1',groupId: undefined,@@ -1179,7 +1179,7 @@ describe('createGatewayEventHandler', () => {value: expect.objectContaining({error: expect.objectContaining({message: 'Timeout',- body: { message: 'Timeout' },+ body: { error: 'Timeout' },}),}),}),@@ -1209,33 +1209,37 @@ describe('createGatewayEventHandler', () => {expect(messageService.updateMessageError).toHaveBeenCalledWith('msg-initial',- {+ expect.objectContaining({+ errorRef: 'H8001',body: {agentType: 'codex',code: 'cli_not_found',+ details: { kind: 'cli_not_found' },docsUrl: 'https://github.com/openai/codex',installCommands: ['npm install -g @openai/codex'],message: 'Codex CLI was not found',},message: 'Codex CLI was not found',type: 'AgentRuntimeError',- },+ }),expect.any(Object),);expect(store.internal_dispatchMessage).toHaveBeenCalledWith(expect.objectContaining({value: {- error: {+ error: expect.objectContaining({+ errorRef: 'H8001',body: {agentType: 'codex',code: 'cli_not_found',+ details: { kind: 'cli_not_found' },docsUrl: 'https://github.com/openai/codex',installCommands: ['npm install -g @openai/codex'],message: 'Codex CLI was not found',},message: 'Codex CLI was not found',type: 'AgentRuntimeError',- },+ }),},}),{ operationId: 'op-1' },@@ -1479,7 +1483,7 @@ describe('createGatewayEventHandler', () => {provider: 'lobehub',}),message: 'Payment required',- type: 'ProviderBizError',+ type: 'InsufficientQuota',}),expect.anything(),);diff --git a/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.test.tsindex f0ebc49cd82..8e8d6d6415f 100644--- a/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.test.ts+++ b/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.test.ts@@ -1712,6 +1712,43 @@ describe('heterogeneousAgentExecutor DB persistence', () => {// โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโdescribe('error handling', () => {+ const authMetadata = {+ attribution: 'user',+ category: 'auth',+ countAsFailure: false,+ errorRef: 'H1001',+ isFallback: false,+ numericId: 1001,+ retryable: false,+ severity: 'warning',+ };++ it('preserves structured quota fields for a flattened local CLI error', async () => {+ const store = createMockStore();+ mockSendPrompt.mockRejectedValueOnce({+ message: "You've hit your weekly limit ยท resets 10pm (Asia/Shanghai)",+ });+ await executeHeterogeneousAgent(+ vi.fn(() => store),+ defaultParams,+ );+ await flush();+ expect(mockUpdateMessageError).toHaveBeenCalledWith(+ 'ast-initial',+ expect.objectContaining({+ errorRef: 'H2001',+ attribution: 'user',+ retryable: false,+ body: expect.objectContaining({+ agentType: 'claude-code',+ code: 'rate_limit',+ details: { kind: 'usage_limit' },+ }),+ }),+ expect.any(Object),+ );+ });+it('should persist accumulated content on error', async () => {const store = createMockStore();const get = vi.fn(() => store);@@ -1777,6 +1814,7 @@ describe('heterogeneousAgentExecutor DB persistence', () => {expect(mockUpdateMessageError).toHaveBeenCalledWith('ast-initial',{+ ...authMetadata,body: expect.objectContaining({agentType: 'claude-code',code: HeterogeneousAgentSessionErrorCode.AuthRequired,@@ -1795,6 +1833,7 @@ describe('heterogeneousAgentExecutor DB persistence', () => {value: {content: '',error: {+ ...authMetadata,body: expect.objectContaining({agentType: 'claude-code',code: HeterogeneousAgentSessionErrorCode.AuthRequired,@@ -1828,6 +1867,7 @@ describe('heterogeneousAgentExecutor DB persistence', () => {expect(mockUpdateMessageError).toHaveBeenCalledWith('ast-initial',{+ ...authMetadata,body: expect.objectContaining({agentType: 'claude-code',code: HeterogeneousAgentSessionErrorCode.AuthRequired,@@ -1846,6 +1886,7 @@ describe('heterogeneousAgentExecutor DB persistence', () => {value: {content: '',error: {+ ...authMetadata,body: expect.objectContaining({agentType: 'claude-code',code: HeterogeneousAgentSessionErrorCode.AuthRequired,@@ -1896,6 +1937,7 @@ describe('heterogeneousAgentExecutor DB persistence', () => {expect(mockUpdateMessageError).toHaveBeenCalledWith('ast-initial',{+ ...authMetadata,body: expect.objectContaining({agentType: 'claude-code',code: HeterogeneousAgentSessionErrorCode.AuthRequired,@@ -1914,6 +1956,7 @@ describe('heterogeneousAgentExecutor DB persistence', () => {value: {content: '',error: {+ ...authMetadata,body: expect.objectContaining({agentType: 'claude-code',code: HeterogeneousAgentSessionErrorCode.AuthRequired,@@ -2015,7 +2058,15 @@ describe('heterogeneousAgentExecutor DB persistence', () => {expect(mockUpdateMessageError).toHaveBeenCalledWith('ast-initial',{- body: cliError,+ attribution: 'user',+ category: 'environment',+ countAsFailure: false,+ errorRef: 'H8001',+ isFallback: false,+ numericId: 8001,+ retryable: false,+ severity: 'warning',+ body: { ...cliError, details: { kind: 'cli_not_found' } },message: 'Claude Code CLI was not found',type: 'AgentRuntimeError',},@@ -2033,7 +2084,15 @@ describe('heterogeneousAgentExecutor DB persistence', () => {type: 'updateMessage',value: {error: {- body: cliError,+ attribution: 'user',+ category: 'environment',+ countAsFailure: false,+ errorRef: 'H8001',+ isFallback: false,+ numericId: 8001,+ retryable: false,+ severity: 'warning',+ body: { ...cliError, details: { kind: 'cli_not_found' } },message: 'Claude Code CLI was not found',type: 'AgentRuntimeError',},diff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.tsindex 919ab1e6eb3..9142662c6e8 100644--- a/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.ts+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.ts@@ -12,13 +12,9 @@ import type {ToolStartData,ToolStateChunkData,} from '@lobechat/agent-gateway-client';-import type {- BuiltinToolResult,- ChatMessageError,- ConversationContext,- UIChatMessage,-} from '@lobechat/types';-import { AgentRuntimeErrorType } from '@lobechat/types';+import { normalizeHeterogeneousMessageError } from '@lobechat/heterogeneous-agents/errors';+import { normalizeChatMessageError } from '@lobechat/model-runtime/errors';+import type { BuiltinToolResult, ConversationContext, UIChatMessage } from '@lobechat/types';import { isRecord, pickNonEmptyString, toRecord } from '@lobechat/utils/object';import { messageService } from '@/services/message';@@ -279,111 +275,6 @@ const findNextAssistantMessageId = (}};-const isErrorType = (value: unknown): value is ChatMessageError['type'] =>- typeof value === 'string' || typeof value === 'number';--const getMessageFromErrorData = (data: unknown): string | undefined => {- if (!isRecord(data)) return undefined;-- const message = pickNonEmptyString(data.message);- if (message) return message;-- const error = data.error;- const errorString = pickNonEmptyString(error);- if (errorString) return errorString;- if (isRecord(error)) {- const errorMessage = pickNonEmptyString(error.message);- if (errorMessage) return errorMessage;-- const nestedError = error.error;- if (isRecord(nestedError)) {- const nestedMessage = pickNonEmptyString(nestedError.message);- if (nestedMessage) return nestedMessage;- }- }-- const responseBody = data._responseBody;- const responseBodyMessage = getMessageFromErrorData(responseBody);- if (responseBodyMessage) return responseBodyMessage;-- const body = data.body;- if (isRecord(body)) {- const bodyMessage = pickNonEmptyString(body.message);- if (bodyMessage) return bodyMessage;- }-};--const mergeGatewayPayloadError = (- sourceBody: Record<string, unknown>,- payloadError: unknown,-): Record<string, unknown> => {- if (payloadError === undefined) return sourceBody;- if (!('error' in sourceBody)) return { ...sourceBody, error: payloadError };- if (isRecord(sourceBody.error) && isRecord(payloadError)) {- return { ...sourceBody, error: { ...payloadError, ...sourceBody.error } };- }- return sourceBody;-};--const buildGatewayRuntimeErrorBody = (- data: Record<string, unknown>,- message: string,-): Record<string, unknown> => {- const body = toRecord(data.body);- const responseBody = toRecord(data._responseBody);- const errorBody = toRecord(data.error);- const sourceBody = body ?? responseBody ?? errorBody ?? {};- const shouldMergePayloadError = body === undefined && data._responseBody !== undefined;- const mergedBody = shouldMergePayloadError- ? mergeGatewayPayloadError(sourceBody, data.error)- : sourceBody;-- return {- ...mergedBody,- ...(data.budget === undefined || 'budget' in mergedBody ? {} : { budget: data.budget }),- ...(typeof data.provider === 'string' && !('provider' in mergedBody)- ? { provider: data.provider }- : {}),- ...('message' in mergedBody ? {} : { message }),- };-};--const toChatMessageError = (data: unknown): ChatMessageError => {- if (isRecord(data) && isErrorType(data.type)) {- const message =- typeof data.message === 'string' && data.message- ? data.message- : getMessageFromErrorData({ body: data.body });-- return {- ...data,- ...(message ? { message } : {}),- type: data.type,- };- }-- // Gateway realtime error events can carry the model-runtime payload shape- // (`errorType` + `error`) before the terminal DB message is refreshed. Treat- // it as the same semantic error instead of falling back to AgentRuntimeError.- if (isRecord(data) && isErrorType(data.errorType)) {- const message = getMessageFromErrorData(data) || String(data.errorType);-- return {- body: buildGatewayRuntimeErrorBody(data, message),- message,- type: data.errorType,- };- }-- const message = getMessageFromErrorData(data) || 'Unknown error';-- return {- body: { message },- message,- type: AgentRuntimeErrorType.AgentRuntimeError,- };-};-/*** Creates a handler function that processes Agent Gateway events* and maps them to the chat store's message update actions.@@ -1418,7 +1309,9 @@ export const createGatewayEventHandler = (case 'error': {enqueue(async () => {- const messageError = toChatMessageError(event.data);+ const messageError = normalizeHeterogeneousMessageError(+ normalizeChatMessageError(event.data),+ );const errorMessage = messageError.message;void emitAgentSignal({diff --git a/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts b/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.tsindex ac50d9f642c..41cc44d10ac 100644--- a/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts+++ b/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts@@ -22,6 +22,7 @@ import {type SubagentIntent,type SubagentRunSnapshot,} from '@lobechat/heterogeneous-agents';+import { normalizeHeterogeneousMessageError } from '@lobechat/heterogeneous-agents/errors';import { formatContextSelections, formatPageSelections } from '@lobechat/prompts';import type {ChatMessageError,@@ -139,7 +140,10 @@ const shouldSuppressTerminalErrorEcho = (content: string, error: ChatMessageErroreturn !!normalizedContent && !!normalizedRawError && normalizedContent === normalizedRawError;};-const toHeterogeneousAgentMessageError = (error: unknown, agentType?: string): ChatMessageError => {+const toRawHeterogeneousAgentMessageError = (+ error: unknown,+ agentType?: string,+): ChatMessageError => {const authRequiredError = maybeClassifyCliAuthRequiredError(error, agentType);if (authRequiredError) {return {@@ -199,6 +203,12 @@ const toHeterogeneousAgentMessageError = (error: unknown, agentType?: string): C};};+const toHeterogeneousAgentMessageError = (error: unknown, agentType?: string): ChatMessageError =>+ normalizeHeterogeneousMessageError(+ toRawHeterogeneousAgentMessageError(error, agentType),+ agentType,+ );+const isRecoverableResumeError = (error: unknown,): error is HeterogeneousAgentSessionError & {