π€― 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
β¨ feat(agent-runtime): decide which errors go on the gateway error board (#19995)
Arvin Xu4cdb80806eb8
diff --git a/apps/server/src/modules/AgentRuntime/GatewayStreamNotifier.ts b/apps/server/src/modules/AgentRuntime/GatewayStreamNotifier.tsindex 0fb7acc2af4..f5ea9154ed5 100644--- a/apps/server/src/modules/AgentRuntime/GatewayStreamNotifier.ts+++ b/apps/server/src/modules/AgentRuntime/GatewayStreamNotifier.ts@@ -6,6 +6,7 @@ import urlJoin from 'url-join';import { sanitizeVisitorError } from '@/database/models/message';+import { shouldRecordGatewayError } from './gatewayErrorRecord';import {buildPublicEndEventData,buildPublicInitEventData,@@ -392,6 +393,14 @@ export class GatewayStreamNotifier implements IStreamEventManager {// snapshot, so dropping it here would break the SoT contract.const endEventData = {errorType,+ // The gateway files errors on its board only when told to β the+ // user-side / board-worthy decision lives here, next to the error spec.+ ...(reason === 'error' && {+ recordError: shouldRecordGatewayError({+ errorType: rawErrorType,+ provider: finalState?.modelRuntimeConfig?.provider,+ }),+ }),...(!messagePatchMode && { finalState }),...(messagePatchMode && { messagePatchMode: true, messageRevision }),reason,diff --git a/apps/server/src/modules/AgentRuntime/__tests__/GatewayStreamNotifier.test.ts b/apps/server/src/modules/AgentRuntime/__tests__/GatewayStreamNotifier.test.tsindex 15ae248c97f..a3626c4b49c 100644--- a/apps/server/src/modules/AgentRuntime/__tests__/GatewayStreamNotifier.test.ts+++ b/apps/server/src/modules/AgentRuntime/__tests__/GatewayStreamNotifier.test.ts@@ -3,7 +3,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';import { GatewayStreamNotifier } from '../GatewayStreamNotifier';import { FULL_STRIP_REDACTION, sanitizeGatewayEventData } from '../gatewayVisitorRedaction';import type { StreamChunkData } from '../StreamEventManager';-import type { IStreamEventManager } from '../types';+import type { IStreamEventManager, PublishAgentRuntimeEndParams } from '../types';// Mock global fetchconst mockFetch = vi.fn().mockResolvedValue({ ok: true, text: () => Promise.resolve('') });@@ -666,6 +666,61 @@ describe('GatewayStreamNotifier', () => {expect(body.event.data.reasonDetail).toBe('Custom detail');});+ describe('recordError', () => {+ const endEventData = async (+ params: Omit<PublishAgentRuntimeEndParams, 'operationId' | 'stepIndex'>,+ ) => {+ await notifier.publishAgentRuntimeEnd({ operationId: 'op-1', stepIndex: 0, ...params });+ await new Promise((r) => setTimeout(r, 50));+ const pushCall = mockFetch.mock.calls.find((c: any[]) => c[0].includes('push-event'));+ return JSON.parse(pushCall![1].body).event.data;+ };++ it('keeps a user-side error off the gateway board', async () => {+ const data = await endEventData({+ finalState: {+ error: { message: 'insufficient quota', type: 'InsufficientQuota' },+ modelRuntimeConfig: { model: 'gpt-5.6-sol', provider: 'openai' },+ },+ reason: 'error',+ });++ expect(data.recordError).toBe(false);+ });++ it('files a provider rate limit on our own provider', async () => {+ const data = await endEventData({+ finalState: {+ error: { message: '429', type: 'RateLimitExceeded' },+ modelRuntimeConfig: { model: 'claude-opus-5', provider: 'lobehub' },+ },+ reason: 'error',+ });++ expect(data.recordError).toBe(true);+ });++ it('classifies by the configured provider, not the upstream named in the error body', async () => {+ // On our provider the normalized error names the upstream the router+ // reached, never `lobehub` β trusting it would hide our own rate limit.+ const data = await endEventData({+ finalState: {+ error: { body: { provider: 'azure' }, message: '429', type: 'RateLimitExceeded' },+ modelRuntimeConfig: { model: 'gpt-5.6-sol', provider: 'lobehub' },+ },+ reason: 'error',+ });++ expect(data.recordError).toBe(true);+ });++ it('omits the flag on a non-error end', async () => {+ const data = await endEventData({ finalState: {}, reason: 'completed' });++ expect(data).not.toHaveProperty('recordError');+ });+ });+it('includes errorType from finalState.error.type', async () => {const finalState = {error: { message: 'Budget exceeded', type: 'InsufficientBudgetForModel' },diff --git a/apps/server/src/modules/AgentRuntime/gatewayErrorRecord.test.ts b/apps/server/src/modules/AgentRuntime/gatewayErrorRecord.test.tsnew file mode 100644index 00000000000..fb0998ec12e--- /dev/null+++ b/apps/server/src/modules/AgentRuntime/gatewayErrorRecord.test.ts@@ -0,0 +1,35 @@+import { BRANDING_PROVIDER } from '@lobechat/business-const';+import { AgentRuntimeErrorType } from '@lobechat/types';+import { describe, expect, it } from 'vitest';++import { shouldRecordGatewayError } from './gatewayErrorRecord';++describe('shouldRecordGatewayError', () => {+ it.each([+ ['operational failure', AgentRuntimeErrorType.ProviderBizError, 'openai', true],+ ['empty completion', AgentRuntimeErrorType.ModelEmptyCompletion, 'openai', true],+ ['unknown code', 'SomethingNew', 'openai', true],+ ['missing code', undefined, 'openai', true],+ ['user quota', AgentRuntimeErrorType.InsufficientQuota, 'openai', false],+ [+ 'user quota on our provider',+ AgentRuntimeErrorType.InsufficientQuota,+ BRANDING_PROVIDER,+ false,+ ],+ ['content policy', AgentRuntimeErrorType.ProviderContentPolicyViolation, 'google', false],+ ['config error', AgentRuntimeErrorType.UserConfigError, 'openai', false],+ ['BYOK rate limit', AgentRuntimeErrorType.RateLimitExceeded, 'openai', false],+ ['BYOK outage', AgentRuntimeErrorType.ProviderServiceUnavailable, 'newapi', false],+ ['our rate limit', AgentRuntimeErrorType.RateLimitExceeded, BRANDING_PROVIDER, true],+ ['our outage', AgentRuntimeErrorType.ProviderServiceUnavailable, BRANDING_PROVIDER, true],+ ['rate limit with unknown provider', AgentRuntimeErrorType.RateLimitExceeded, undefined, true],+ ['aliased quota limit on BYOK', AgentRuntimeErrorType.QuotaLimitReached, 'openai', false],+ ['system network error', AgentRuntimeErrorType.ProviderNetworkError, 'openai', true],+ ['context window', AgentRuntimeErrorType.ExceededContextWindow, 'openai', true],+ ['request body too large', AgentRuntimeErrorType.RequestBodyTooLarge, 'openai', true],+ ['request shape', AgentRuntimeErrorType.InvalidRequestFormat, 'google', true],+ ] as const)('%s β %s', (_label, errorType, provider, expected) => {+ expect(shouldRecordGatewayError({ errorType, provider })).toBe(expected);+ });+});diff --git a/apps/server/src/modules/AgentRuntime/gatewayErrorRecord.ts b/apps/server/src/modules/AgentRuntime/gatewayErrorRecord.tsnew file mode 100644index 00000000000..8d59bc7ecce--- /dev/null+++ b/apps/server/src/modules/AgentRuntime/gatewayErrorRecord.ts@@ -0,0 +1,58 @@+import { BRANDING_PROVIDER } from '@lobechat/business-const';+import { getErrorCodeSpec } from '@lobechat/model-runtime';+import { AgentRuntimeErrorType } from '@lobechat/types';++/**+ * User-attributed codes that still point at something the harness could have+ * prevented β a context or payload the harness should have trimmed, or a request+ * shape the provider rejected. Adapter bugs hide in `InvalidRequestFormat` in+ * particular, so these stay on the board even though users see them as their own.+ */+const HARNESS_SIGNAL_ERROR_TYPES = new Set<string>([+ AgentRuntimeErrorType.ExceededContextWindow,+ AgentRuntimeErrorType.ExceededImageLimit,+ AgentRuntimeErrorType.ExceededToolLimit,+ AgentRuntimeErrorType.InvalidRequestFormat,+ AgentRuntimeErrorType.RequestBodyTooLarge,+]);++/**+ * Whether a terminal error belongs on the agent-gateway error board β the queue+ * of failures someone on our side should look at. The full error is persisted on+ * the operation either way; this only decides what the board is told about.+ *+ * - Codes that count as operational failures always go on the board.+ * - `user`-attributed codes (quota, bad key, content policy, β¦) stay off it.+ * - `provider`-attributed codes (rate limits, upstream outages) stay off it for a+ * user's own provider, but go on it for ours: there they mean our upstream+ * accounts are limited or down. When the provider is unknown they go on it too,+ * so a lost provider can never hide an outage of ours.+ *+ * `provider` is the operation's configured provider β the one the board shows.+ * The normalized error's `body.provider` is not a substitute: for our provider it+ * names the upstream the router reached (`azure`, `google`, β¦), never ours.+ */+export const shouldRecordGatewayError = ({+ errorType,+ provider,+}: {+ errorType?: string;+ provider?: string;+}): boolean => {+ if (!errorType || HARNESS_SIGNAL_ERROR_TYPES.has(errorType)) return true;++ const spec = getErrorCodeSpec(errorType);+ if (!spec || spec.countAsFailure) return true;++ switch (spec.attribution) {+ case 'user': {+ return false;+ }+ case 'provider': {+ return !provider || provider === BRANDING_PROVIDER;+ }+ default: {+ return true;+ }+ }+};