🤯 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(model-runtime): keep content-policy stream errors and gateway 403s out of the unknown bucket (#21608)
Arvin Xu63acbe9c7583
diff --git a/packages/model-runtime/src/core/RouterRuntime/chatAttempt.test.ts b/packages/model-runtime/src/core/RouterRuntime/chatAttempt.test.tsindex 5f106cc4ced..3be6e848444 100644--- a/packages/model-runtime/src/core/RouterRuntime/chatAttempt.test.ts+++ b/packages/model-runtime/src/core/RouterRuntime/chatAttempt.test.ts@@ -389,6 +389,40 @@ describe('observeChatAttempt', () => {},);+ it.each([+ {+ error: {+ body: { message: 'The content was blocked for safety reasons.', provider: 'google' },+ type: 'ProviderContentPolicyViolation',+ },+ errorType: 'ProviderContentPolicyViolation',+ },+ {+ error: { errorType: 'ContentModeration', message: 'blocked by moderation' },+ errorType: 'ContentModeration',+ },+ // Fallback buckets carry no classification of their own, so they stay StreamChunkError.+ { error: { message: 'boom', type: 'ProviderBizError' }, errorType: 'StreamChunkError' },+ { error: { message: 'Internal error encountered.' }, errorType: 'StreamChunkError' },+ ])('keeps the code a stream error already carries: $errorType', async ({ error, errorType }) => {+ const finished = vi.fn();+ const response = await observeChatAttempt(+ async ({ callback }) => {+ await callback?.onText?.('partial');+ await callback?.onError?.(error);+ await callback?.onFinal?.({ text: 'partial' });+ return new Response('done');+ },+ undefined,+ attempt,+ true,+ finished,+ );+ await response.text();++ expect(finished.mock.calls[0][0].error).toMatchObject({ errorType });+ });+it.each([{ expectedOutcome: 'completed', text: 'I cannot help with that.' },{ expectedOutcome: 'empty', text: '' },diff --git a/packages/model-runtime/src/core/RouterRuntime/chatAttempt.ts b/packages/model-runtime/src/core/RouterRuntime/chatAttempt.tsindex 374f87d876d..c307c7bd9eb 100644--- a/packages/model-runtime/src/core/RouterRuntime/chatAttempt.ts+++ b/packages/model-runtime/src/core/RouterRuntime/chatAttempt.ts@@ -3,6 +3,7 @@ import { AgentRuntimeErrorType } from '@lobechat/types';import {extractErrorMessage,+ getErrorCodeSpec,isEmptyModelCompletion,isModelRefusalFinishReason,ModelEmptyError,@@ -38,8 +39,25 @@ const getReasoningContent = (data: OnFinishData | undefined) =>const streamErrorMessage = (error: unknown): string =>(error instanceof Error ? error.message : extractErrorMessage(error)) ?? String(error);+/**+ * The code a stream error payload already carries, when it is a specific one. Provider stream+ * adapters emit typed errors such as `ProviderContentPolicyViolation` for a Gemini `SAFETY`+ * finish; wrapping them as `StreamChunkError` recorded content-policy blocks as harness stream+ * failures. Fallback buckets carry no classification of their own, so they keep the wrapper.+ */+const classifiedStreamErrorType = (error: unknown) => {+ if (!error || typeof error !== 'object') return;+ const { errorType, type } = error as { errorType?: unknown; type?: unknown };+ const code =+ typeof errorType === 'string' ? errorType : typeof type === 'string' ? type : undefined;+ if (!code || code === AgentRuntimeErrorType.StreamChunkError) return;+ const spec = getErrorCodeSpec(code);+ return spec && !spec.isFallback ? spec.code : undefined;+};+const createStreamChunkError = (error: unknown, provider: string) => {const message = streamErrorMessage(error);+ const errorType = classifiedStreamErrorType(error) ?? AgentRuntimeErrorType.StreamChunkError;return Object.assign(new Error(message, { cause: error }),@@ -49,7 +67,7 @@ const createStreamChunkError = (error: unknown, provider: string) => {message,name: 'StreamChunkError',},- errorType: AgentRuntimeErrorType.StreamChunkError,+ errorType,provider,}),{ name: 'StreamChunkError' },diff --git a/packages/model-runtime/src/errors/normalizeChatMessageError.test.ts b/packages/model-runtime/src/errors/normalizeChatMessageError.test.tsindex 2939a0656b0..74b77c23487 100644--- a/packages/model-runtime/src/errors/normalizeChatMessageError.test.ts+++ b/packages/model-runtime/src/errors/normalizeChatMessageError.test.ts@@ -107,3 +107,70 @@ describe('normalizeChatMessageError', () => {});});});++describe('platform admission 403s', () => {+ const planGate =+ 'Model "gemini-4-argon" is available on paid plans only (model tier: pro). Current personal plan: free.';++ it('classifies a plan-tier refusal as a user-side quota state, keeping its type', () => {+ expect(+ normalizeChatMessageError({+ error: { message: 403 },+ errorType: 403,+ message: planGate,+ provider: 'lobehub',+ }),+ ).toMatchObject({+ attribution: 'user',+ category: 'quota',+ countAsFailure: false,+ message: planGate,+ retryable: false,+ type: 403,+ });+ });++ it('classifies a usage-security refusal by its reason, as stored and as thrown', () => {+ const thrown = {+ _responseBody: { provider: 'lobehub', reason: 'not_onboarded' },+ error: { message: 403 },+ errorType: 403,+ message: 'Request blocked.',+ provider: 'lobehub',+ };+ const stored = {+ body: {+ error: { message: 403 },+ message: 'Request blocked.',+ provider: 'lobehub',+ reason: 'not_onboarded',+ },+ message: 'Request blocked.',+ type: 403,+ };++ for (const error of [thrown, stored])+ expect(normalizeChatMessageError(error)).toMatchObject({+ attribution: 'user',+ category: 'auth',+ countAsFailure: false,+ type: 403,+ });+ });++ it('leaves a bare Forbidden that lost its explanation unclassified', () => {+ const normalized = normalizeChatMessageError({+ body: {+ error: { message: 403 },+ message: 'Forbidden',+ model: 'gpt-6-astra',+ provider: 'lobehub',+ },+ message: 'Forbidden',+ type: 403,+ });++ expect(normalized.category).toBeUndefined();+ expect(normalized.attribution).toBeUndefined();+ });+});diff --git a/packages/model-runtime/src/errors/normalizeChatMessageError.ts b/packages/model-runtime/src/errors/normalizeChatMessageError.tsindex 39dccbd3131..a744b1f1b3d 100644--- a/packages/model-runtime/src/errors/normalizeChatMessageError.ts+++ b/packages/model-runtime/src/errors/normalizeChatMessageError.ts@@ -1,6 +1,6 @@import { AgentRuntimeErrorType, ChatErrorType, type ChatMessageError } from '@lobechat/types';-import { isRecord } from '../utils/object';+import { isRecord } from '../utils/object';import { refineErrorCode } from './refine';import { getErrorCodeSpec } from './specs';@@ -138,6 +138,45 @@ const truncateStack = (stack: string | undefined): string | undefined => {* JSONB, S3 trace snapshots, agent-gateway WS push, dashboards) all get the* same shape without re-running pattern matching themselves.*/+/** The model gateway's message for a model tier the user's plan does not include. */+const PLAN_GATE_PATTERN = /available on paid plans only/i;++/**+ * Classification for a platform admission refusal that arrives as a bare HTTP 403.+ *+ * The model gateway rejects a call it will not serve before any provider sees it, either+ * because the user's plan does not include the model tier or because a usage-security gate+ * holds the account (`body.reason`). Both carry the numeric `Forbidden` type, which has no+ * spec, so they were stored with no category and read as unknown failures. Both are the+ * account's state, not a runtime fault, so they are classified as user-side. The `type`+ * stays as is, because the chat error renderer picks its card from it.+ *+ * A bare `Forbidden` with neither marker is left unclassified on purpose: the refusal lost+ * its explanation somewhere upstream, which is a defect to fix rather than a user state.+ */+const classifyForbidden = (formatted: ChatMessageError): ChatMessageError | undefined => {+ if (String(formatted.type) !== String(ChatErrorType.Forbidden)) return undefined;+ const reason = isRecord(formatted.body) ? formatted.body.reason : undefined;+ const category =+ typeof reason === 'string' && reason+ ? 'auth'+ : PLAN_GATE_PATTERN.test(formatted.message ?? '')+ ? 'quota'+ : undefined;+ if (!category) return undefined;++ return {+ ...formatted,+ attribution: 'user',+ category,+ countAsFailure: false,+ httpStatus: 403,+ isFallback: false,+ retryable: false,+ severity: 'warning',+ };+};+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@@ -154,7 +193,7 @@ const enrichWithSpec = (formatted: ChatMessageError): ChatMessageError => {// 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;+ if (!spec) return classifyForbidden(formatted) ?? formatted;return {...formatted,