Skip to content

🤯 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.

🐛 fix(hetero): classify a CLI agent's exhausted quota as a rate limit (#19856)

Arvin Xu917348348eee
diff --git a/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler.ts b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler.ts
index cc95afa564f..988dd05fcae 100644
--- a/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler.ts
+++ b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler.ts
@@ -22,6 +22,7 @@ import {
reduceMainAgent,
rehydrateSubagentRunsState,
} from '@lobechat/heterogeneous-agents';
+import { isEchoedErrorText } from '@lobechat/heterogeneous-agents/errors';
import { type ChatToolPayload, ThreadStatus, ThreadType } from '@lobechat/types';
import { createNanoId } from '@lobechat/utils';
import debug from 'debug';
@@ -298,6 +299,16 @@ const INTERVENTION_KINDS = new Set<AgentInterventionInteractionKind>([
'question',
]);
+/** The raw text a CLI would have echoed into the answer for this failure. */
+const errorEchoText = (error: { body?: Record<string, unknown>; message?: string }): string => {
+ const body = error.body ?? {};
+ const candidate = [body.stderr, body.message, error.message].find(
+ (value): value is string => typeof value === 'string' && value.trim().length > 0,
+ );
+
+ return candidate ?? '';
+};
+
const INTERVENTION_PROVIDERS = new Set<AgentInterventionProvider>([
'claude-code',
'cursor',
@@ -1484,7 +1495,20 @@ export class HeterogeneousPersistenceHandler {
error: { body?: Record<string, unknown>; message: string; type: string },
) {
const updateValue: Record<string, any> = {};
- if (error.body?.clearEchoedContent === true) updateValue.content = '';
+ const clearsEcho = error.body?.clearEchoedContent === true;
+ // One read serves both decisions below.
+ const persisted =
+ clearsEcho || !isHeteroStatusGuideErrorData(error.body)
+ ? await this.deps.messageModel.findById(state.main.currentAssistantId)
+ : undefined;
+ // `clearEchoedContent` marks an error the CLI may ALSO have printed into
+ // the answer — it does not mean the answer is disposable. Quota rejections
+ // carry the flag too, and a run that worked for ten minutes before its
+ // weekly window closed must keep what it wrote, so only an exact echo is
+ // dropped (same rule as the client and the coordinator reducer).
+ if (clearsEcho && isEchoedErrorText(persisted?.content, errorEchoText(error))) {
+ updateValue.content = '';
+ }
// Same canonical normalization as the in-stream `setError` path — the CLI's
// free-form `{ message, type }` runs through formatErrorForState so the
// finish-only write and the in-stream write produce one classified error shape.
@@ -1498,9 +1522,7 @@ export class HeterogeneousPersistenceHandler {
// the generic error alert — keep the richer persisted error instead.
const overwritesGuideError =
!isHeteroStatusGuideErrorData(error.body) &&
- isHeteroStatusGuideErrorData(
- (await this.deps.messageModel.findById(state.main.currentAssistantId))?.error?.body,
- );
+ isHeteroStatusGuideErrorData(persisted?.error?.body);
if (!overwritesGuideError) updateValue.error = formatErrorForState(error);
if (Object.keys(updateValue).length > 0) {
diff --git a/apps/server/src/services/heterogeneousAgent/__tests__/HeterogeneousPersistenceHandler.test.ts b/apps/server/src/services/heterogeneousAgent/__tests__/HeterogeneousPersistenceHandler.test.ts
index 36fa827acf2..ed70d9cebb5 100644
--- a/apps/server/src/services/heterogeneousAgent/__tests__/HeterogeneousPersistenceHandler.test.ts
+++ b/apps/server/src/services/heterogeneousAgent/__tests__/HeterogeneousPersistenceHandler.test.ts
@@ -1591,7 +1591,9 @@ describe('HeterogeneousPersistenceHandler', () => {
operationId: 'op-1',
topicId: 'topic-1',
});
- h.messages.get('asst-1')!.content = '...';
+ // The CLI echoed the failure into the answer before reporting it — that
+ // echo is what `clearEchoedContent` drops.
+ h.messages.get('asst-1')!.content = "You've hit your session limit";
h.topicModel.findById.mockResolvedValue({
agentId: null,
id: 'topic-1',
@@ -1627,6 +1629,44 @@ describe('HeterogeneousPersistenceHandler', () => {
expect(asst.content).toBe('');
});
+ it('finish() keeps real work when a quota error only marks an echo', async () => {
+ // Kimi Code can burn a full run and only then hit its weekly window. The
+ // finish error carries clearEchoedContent (every rate_limit does), but
+ // the streamed answer is not an echo of it and must survive.
+ const h = createHarness({
+ assistantMessageId: 'asst-1',
+ operationId: 'op-1',
+ topicId: 'topic-1',
+ });
+ h.messages.get('asst-1')!.content = 'Refactored the adapter and ran the tests.';
+ h.topicModel.findById.mockResolvedValue({
+ agentId: null,
+ id: 'topic-1',
+ metadata: {},
+ });
+
+ await h.handler.finish({
+ assistantMessageId: 'asst-1',
+ error: {
+ body: {
+ agentType: 'kimi-code',
+ clearEchoedContent: true,
+ code: 'rate_limit',
+ details: { kind: 'usage_limit' },
+ },
+ message: "You've reached your weekly (7-day) usage limit.",
+ type: 'AgentRuntimeError',
+ },
+ operationId: 'op-1',
+ result: 'error',
+ topicId: 'topic-1',
+ });
+
+ const asst = h.messages.get('asst-1')!;
+ expect(asst.content).toBe('Refactored the adapter and ran the tests.');
+ expect(asst.error).toMatchObject({ body: { agentType: 'kimi-code', code: 'rate_limit' } });
+ });
+
it('finish() with no state stays a no-op for a stale operation (mismatched runningOperation)', async () => {
const h = createHarness({
assistantMessageId: 'asst-1',
diff --git a/apps/server/src/services/heterogeneousAgent/__tests__/index.test.ts b/apps/server/src/services/heterogeneousAgent/__tests__/index.test.ts
index e4c3f0b4919..9355f46a0b2 100644
--- a/apps/server/src/services/heterogeneousAgent/__tests__/index.test.ts
+++ b/apps/server/src/services/heterogeneousAgent/__tests__/index.test.ts
@@ -122,6 +122,30 @@ describe('HeterogeneousAgentService', () => {
});
});
+ it('turns a Kimi Code quota exit into the rate-limit guide instead of a JSON card', () => {
+ // Verbatim stderr from a real run: Kimi Code reports a spent weekly
+ // window through `provider.auth_error`, and used to land as the generic
+ // AgentRuntimeError catch-all with no reset / schedule / transfer action.
+ expect(
+ normalizeHeterogeneousFinishError('kimi-code', {
+ message:
+ "error: failed to run prompt: provider.auth_error: 403 You've reached your weekly (7-day) usage limit. Your quota will reset when the current 7-day window ends. To continue now, purchase extra usage or upgrade your plan: https://www.kimi.com/membership/subscription?tab=quota",
+ type: 'AgentRuntimeError',
+ }),
+ ).toMatchObject({
+ attribution: 'user',
+ category: 'quota',
+ countAsFailure: false,
+ errorRef: 'H2001',
+ body: {
+ agentType: 'kimi-code',
+ code: 'rate_limit',
+ details: { kind: 'usage_limit' },
+ rateLimitInfo: { rateLimitType: 'seven_day', status: 'rejected' },
+ },
+ });
+ });
+
it('classifies a flattened Claude Code login failure for the frontend status guide', () => {
expect(
normalizeHeterogeneousFinishError('claude-code', {
diff --git a/packages/heterogeneous-agents/src/adapters/claudeCode.ts b/packages/heterogeneous-agents/src/adapters/claudeCode.ts
index 5239387dbcc..43ab27db3bb 100644
--- a/packages/heterogeneous-agents/src/adapters/claudeCode.ts
+++ b/packages/heterogeneous-agents/src/adapters/claudeCode.ts
@@ -38,10 +38,10 @@
import { getHeterogeneousAgentConfigOrThrow } from '../config';
import {
- CLI_CREDIT_LIMIT_PATTERNS,
+ classifyCliQuotaMessage,
CLI_SERVER_THROTTLE_PATTERNS,
CLI_USER_RATE_LIMIT_PATTERNS,
-} from '../errors/claudeCodeQuota';
+} from '../errors/cliQuota';
import type { HeteroErrorKind } from '../errors/specs';
import { imagePlaceholder } from '../imageEcho';
import type {
@@ -874,11 +874,9 @@ const getRateLimitTerminalError = (
// A credit/balance limit shares the `rate_limit` guide but not its remedy:
// waiting for a reset never clears it, so it is a distinct taxonomy kind.
- const kind: HeteroErrorKind = CLI_CREDIT_LIMIT_PATTERNS.some((pattern) =>
- pattern.test(rawMessage),
- )
- ? 'credit_limit'
- : 'usage_limit';
+ // A `rate_limit_info`-only rejection (no quota wording in the text) is a
+ // plan window by definition — that structured event only ever reports one.
+ const kind: HeteroErrorKind = classifyCliQuotaMessage(rawMessage)?.kind ?? 'usage_limit';
return {
agentType,
diff --git a/packages/heterogeneous-agents/src/errors/claudeCodeQuota.ts b/packages/heterogeneous-agents/src/errors/claudeCodeQuota.ts
deleted file mode 100644
index 68b8ef2bf18..00000000000
--- a/packages/heterogeneous-agents/src/errors/claudeCodeQuota.ts
+++ /dev/null
@@ -1,35 +0,0 @@
-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/cliQuota.test.ts b/packages/heterogeneous-agents/src/errors/cliQuota.test.ts
new file mode 100644
index 00000000000..326567871fc
--- /dev/null
+++ b/packages/heterogeneous-agents/src/errors/cliQuota.test.ts
@@ -0,0 +1,57 @@
+import { describe, expect, it } from 'vitest';
+
+import { classifyCliQuotaMessage } from './cliQuota';
+
+// The exact stderr Kimi Code exits with when the subscription window closes.
+const KIMI_WEEKLY_LIMIT = [
+ "error: failed to run prompt: provider.auth_error: 403 You've reached your weekly (7-day) usage",
+ 'limit. Your quota will reset when the current 7-day window ends. To continue now, purchase extra',
+ 'usage or upgrade your plan: https://www.kimi.com/membership/subscription?tab=quota',
+ 'See log: /Users/user/.kimi-code/logs/kimi-code.log',
+].join(' ');
+
+describe('classifyCliQuotaMessage', () => {
+ it('reads a Kimi Code weekly window as a resetting plan limit', () => {
+ expect(classifyCliQuotaMessage(KIMI_WEEKLY_LIMIT)).toEqual({
+ kind: 'usage_limit',
+ rateLimitType: 'seven_day',
+ });
+ });
+
+ it('keeps a credit limit distinct from a window that resets', () => {
+ expect(
+ classifyCliQuotaMessage(
+ "You've reached your Fable 5 limit. Run /usage-credits to continue or switch models.",
+ ),
+ ).toEqual({ kind: 'credit_limit' });
+ });
+
+ it('names the window CC reports in prose', () => {
+ expect(
+ classifyCliQuotaMessage("You've hit your session limit · resets 6:30pm (Asia/Shanghai)"),
+ ).toEqual({ kind: 'usage_limit', rateLimitType: 'five_hour' });
+ expect(classifyCliQuotaMessage("You've hit your weekly limit · resets Jul 3 at 1pm")).toEqual({
+ kind: 'usage_limit',
+ rateLimitType: 'seven_day',
+ });
+ });
+
+ it('classifies a localized gateway rejection', () => {
+ expect(
+ classifyCliQuotaMessage(
+ 'API Error: Request rejected (429) · [1234][已达到 5 小时使用上限,2026-06-19 22:00:00 后可继续使用。]',
+ ),
+ ).toEqual({ kind: 'usage_limit', rateLimitType: 'five_hour' });
+ });
+
+ it('leaves transient throttling and bare rate limits to the retry path', () => {
+ expect(
+ classifyCliQuotaMessage(
+ 'API Error: Server is temporarily limiting requests (not your usage limit) · Rate limited',
+ ),
+ ).toBeUndefined();
+ expect(classifyCliQuotaMessage('429 Too Many Requests')).toBeUndefined();
+ expect(classifyCliQuotaMessage('rate limited')).toBeUndefined();
+ expect(classifyCliQuotaMessage(undefined)).toBeUndefined();
+ });
+});
diff --git a/packages/heterogeneous-agents/src/errors/cliQuota.ts b/packages/heterogeneous-agents/src/errors/cliQuota.ts
new file mode 100644
index 00000000000..1186ca26900
--- /dev/null
+++ b/packages/heterogeneous-agents/src/errors/cliQuota.ts
@@ -0,0 +1,117 @@
+/**
+ * Quota wording shared by CLI-wrapped agents.
+ *
+ * Every local CLI agent bills against its own subscription and prints the
+ * same kind of sentence when that subscription is spent — CC's `You've hit
+ * your weekly limit`, Kimi Code's `You've reached your weekly (7-day) usage
+ * limit`, a gateway's `已达到 5 小时使用上限`. The patterns therefore live here
+ * rather than in one adapter, and `classifyCliQuotaMessage` is the single
+ * place that turns them into a taxonomy kind.
+ */
+
+/** Remedies that only a top-up clears — waiting for a window never helps. */
+const CLI_CREDIT_REMEDY_PATTERNS = [/\/usage-credits\b/i] as const;
+
+export const CLI_CREDIT_LIMIT_PATTERNS = [
+ /you'?ve reached your .{0,40}\blimit\b/i,
+ ...CLI_CREDIT_REMEDY_PATTERNS,
+] 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;
+
+/**
+ * Wording that promises the window reopens by itself — Kimi Code's
+ * `Your quota will reset when the current 7-day window ends`, CC's
+ * `resets 6:30pm (Asia/Shanghai)`, a gateway's `2026-06-19 22:00:00 后可继续
+ * 使用`. It is what separates a plan window (wait, or schedule the
+ * continuation) from exhausted credits (top up or switch model), because both
+ * open with the same "you've reached your … limit" sentence.
+ */
+const CLI_QUOTA_RESET_PATTERNS = [
+ // The verb alone is the signal: a message that already qualified as a
+ // user-quota rejection only says "reset" / "refresh" about its own window.
+ /\bresets?\b/i,
+ /\b(?:refresh|renew)(?:ed|es|s)?\b/i,
+ /后可继续使用/,
+ /(?:额度|配额|上限)[^。]{0,12}(?:重置|刷新|恢复)/,
+] as const;
+
+/**
+ * The window a rejected quota belongs to, in the vocabulary the rate-limit
+ * guide already renders (`seven_day` → 周期上限, `five_hour` → 5 小时上限).
+ * CC ships it as structured `rate_limit_info`; CLIs that only print prose
+ * (Kimi Code: `You've reached your weekly (7-day) usage limit`) get it read
+ * back out of the sentence so the card can name the window.
+ */
+const CLI_RATE_LIMIT_TYPE_PATTERNS: readonly (readonly [RegExp, string])[] = [
+ [/\bweekly\b|\b7[\s-]?day\b|\bseven[\s-]?day\b|每周|7\s*天|七天/i, 'seven_day'],
+ [/\b5[\s-]?hour\b|\bfive[\s-]?hour\b|\bsession limit\b|5\s*小时/i, 'five_hour'],
+] as const;
+
+export interface CliQuotaClassification {
+ /** `usage_limit` resets on its own; `credit_limit` needs a top-up. */
+ kind: 'credit_limit' | 'usage_limit';
+ /** Window name for the guide card, when the message states one. */
+ rateLimitType?: string;
+}
+
+/**
+ * Classify a CLI's free-form failure text as a user-side quota rejection.
+ *
+ * Deliberately agent-agnostic: every CLI-wrapped agent bills against its own
+ * subscription and prints the same kind of sentence when that subscription is
+ * spent, so the classification lives with the patterns rather than in one
+ * adapter. Returns `undefined` for anything that is not unambiguously the
+ * user's own quota — a bare 429, `rate limited`, or a provider-side throttle
+ * that disclaims the plan limit belongs to the retry (overloaded) path.
+ */
+export const classifyCliQuotaMessage = (
+ message: string | undefined,
+): CliQuotaClassification | undefined => {
+ if (!message) return;
+ if (CLI_SERVER_THROTTLE_PATTERNS.some((pattern) => pattern.test(message))) return;
+ if (!CLI_USER_RATE_LIMIT_PATTERNS.some((pattern) => pattern.test(message))) return;
+
+ // A message that names both a top-up remedy and a reset is still a window:
+ // waiting clears it, which is the remedy the guide offers first.
+ const resets = CLI_QUOTA_RESET_PATTERNS.some((pattern) => pattern.test(message));
+ const kind =
+ CLI_CREDIT_REMEDY_PATTERNS.some((pattern) => pattern.test(message)) ||
+ (!resets && CLI_CREDIT_LIMIT_PATTERNS.some((pattern) => pattern.test(message)))
+ ? 'credit_limit'
+ : 'usage_limit';
+ const rateLimitType = CLI_RATE_LIMIT_TYPE_PATTERNS.find(([pattern]) =>
+ pattern.test(message),
+ )?.[1];
+
+ return { kind, ...(rateLimitType ? { rateLimitType } : {}) };
+};
diff --git a/packages/heterogeneous-agents/src/errors/echo.ts b/packages/heterogeneous-agents/src/errors/echo.ts
new file mode 100644
index 00000000000..e68d3825d9a
--- /dev/null
+++ b/packages/heterogeneous-agents/src/errors/echo.ts
@@ -0,0 +1,24 @@
+const normalizeErrorText = (value?: string | null) => value?.replaceAll(/\s+/g, ' ').trim();
+
+/**
+ * Whether an assistant's streamed `content` is nothing but an echo of the
+ * terminal error.
+ *
+ * Some CLIs print the failure to stdout before (or instead of) reporting it
+ * structurally — CC echoes the stderr line for an auth failure, and a quota
+ * rejection can arrive the same way. Dropping that content leaves the error
+ * card as the only rendering of the failure instead of showing it twice.
+ *
+ * Equality, never containment: a run that produced real work and THEN died on
+ * its quota (Kimi Code exits mid-run when the weekly window closes) must keep
+ * every word it wrote. Accidental partial overlap is not an echo.
+ */
+export const isEchoedErrorText = (
+ content: string | null | undefined,
+ errorText: string | null | undefined,
+): boolean => {
+ const normalizedContent = normalizeErrorText(content);
+ const normalizedError = normalizeErrorText(errorText);
+
+ return !!normalizedContent && !!normalizedError && normalizedContent === normalizedError;
+};
diff --git a/packages/heterogeneous-agents/src/errors/index.ts b/packages/heterogeneous-agents/src/errors/index.ts
index 590fbb749b2..d309845c80c 100644
--- a/packages/heterogeneous-agents/src/errors/index.ts
+++ b/packages/heterogeneous-agents/src/errors/index.ts
@@ -1,3 +1,6 @@
+export type { CliQuotaClassification } from './cliQuota';
+export { classifyCliQuotaMessage } from './cliQuota';
+export { isEchoedErrorText } from './echo';
export { normalizeHeterogeneousMessageError, readHeterogeneousErrorContext } from './messageError';
export type { HeteroErrorKind, HeteroErrorSpec } from './specs';
export {
diff --git a/packages/heterogeneous-agents/src/errors/messageError.test.ts b/packages/heterogeneous-agents/src/errors/messageError.test.ts
index 16f5d8a3f44..831bc87c2f3 100644
--- a/packages/heterogeneous-agents/src/errors/messageError.test.ts
+++ b/packages/heterogeneous-agents/src/errors/messageError.test.ts
@@ -19,6 +19,31 @@ describe('heterogeneous message errors', () => {
});
expect(normalizeHeterogeneousMessageError(result)).toEqual(result);
});
+ it('recovers a Kimi Code quota rejection the CLI printed as a bare message', () => {
+ const result = normalizeHeterogeneousMessageError(
+ {
+ type: 'AgentRuntimeError',
+ message:
+ "error: failed to run prompt: provider.auth_error: 403 You've reached your weekly (7-day) usage limit. Your quota will reset when the current 7-day window ends.",
+ },
+ 'kimi-code',
+ );
+ expect(result).toMatchObject({
+ errorRef: 'H2001',
+ countAsFailure: false,
+ body: {
+ agentType: 'kimi-code',
+ code: 'rate_limit',
+ details: { kind: 'usage_limit' },
+ rateLimitInfo: { rateLimitType: 'seven_day', status: 'rejected' },
+ },
+ });
+ expect(readHeterogeneousErrorContext(result)).toEqual({
+ agentType: 'kimi-code',
+ kind: 'usage_limit',
+ rateLimitType: 'seven_day',
+ });
+ });
it('does not classify temporary throttling as exhausted quota', () => {
const error = {
type: 'AgentRuntimeError' as const,
diff --git a/packages/heterogeneous-agents/src/errors/messageError.ts b/packages/heterogeneous-agents/src/errors/messageError.ts
index d7c5a14fc05..79d5ccd2dd1 100644
--- a/packages/heterogeneous-agents/src/errors/messageError.ts
+++ b/packages/heterogeneous-agents/src/errors/messageError.ts
@@ -2,11 +2,7 @@ import type { ChatErrorHeterogeneousContext, ChatMessageError } from '@lobechat/
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 { classifyCliQuotaMessage } from './cliQuota';
import { formatHeteroErrorId, HETERO_ERROR_SPECS, type HeteroErrorKind } from './specs';
const GUIDE_KINDS: Record<string, HeteroErrorKind> = {
@@ -34,18 +30,16 @@ export const normalizeHeterogeneousMessageError = (
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';
- }
+ // A CLI that dies on its own quota before any adapter saw a stream reaches
+ // here as a bare { message } — Kimi Code exits with `error: failed to run
+ // prompt: provider.auth_error: 403 You've reached your weekly (7-day) usage
+ // limit…`. Read it back for EVERY local CLI, not just CC: they all bill
+ // against their own subscription, and an unclassified quota rejection
+ // renders as the generic JSON card with no reset/schedule/transfer action.
+ // Never inferred from a bare 429 or a throttle that disclaims the plan
+ // limit — `classifyCliQuotaMessage` requires explicit user-quota wording.
+ const quota = kind ? undefined : classifyCliQuotaMessage(message);
+ if (quota) kind = quota.kind;
kind ??=
typeof body.code === 'string' && Object.hasOwn(GUIDE_KINDS, body.code)
? GUIDE_KINDS[body.code]
@@ -62,6 +56,12 @@ export const normalizeHeterogeneousMessageError = (
details: { ...details, kind },
message: typeof body.message === 'string' ? body.message : error.message,
...(spec.guideCode === 'rate_limit' ? { clearEchoedContent: true } : {}),
+ // CLIs that only print prose carry no structured `rate_limit_info`;
+ // naming the window it rejected lets the guide card say which limit
+ // ran out instead of just "quota exhausted".
+ ...(quota?.rateLimitType && !isRecord(body.rateLimitInfo)
+ ? { rateLimitInfo: { rateLimitType: quota.rateLimitType, status: 'rejected' } }
+ : {}),
},
category: spec.category,
countAsFailure: spec.countAsFailure,
diff --git a/packages/heterogeneous-agents/src/mainAgentCoordinator/reducer.ts b/packages/heterogeneous-agents/src/mainAgentCoordinator/reducer.ts
index 858d0cb755c..76e896de7fc 100644
--- a/packages/heterogeneous-agents/src/mainAgentCoordinator/reducer.ts
+++ b/packages/heterogeneous-agents/src/mainAgentCoordinator/reducer.ts
@@ -1,5 +1,6 @@
import type { AgentInterventionRequestData } from '@lobechat/agent-gateway-client';
+import { isEchoedErrorText } from '../errors/echo';
import type { SubagentIntent, SubagentReduceCtx } from '../subagentCoordinator';
import { getEventScope, reduceSubagentRuns } from '../subagentCoordinator';
import type { ToolCallPayload } from '../types';
@@ -57,8 +58,6 @@ const copyState = (s: MainAgentRunState): MainAgentRunState => ({
// ─── Echo suppression (pure; mirrors both engines' shouldSuppressTerminalErrorEcho) ───
-const normalizeErrorText = (value?: string) => value?.replaceAll(/\s+/g, ' ').trim();
-
/**
* CC sometimes streams the error string into `content` BEFORE emitting the
* structured error event (e.g. AuthRequired echoes the stderr line). Only
@@ -72,9 +71,7 @@ const shouldSuppressTerminalErrorEcho = (content: string, errorData: unknown): b
{ clearEchoedContent?: boolean; code?: string; message?: string; stderr?: string } | undefined;
// Keep in sync with the interpreters' ECHO_TRIGGER_CODES.
if (!body?.clearEchoedContent && body?.code !== 'AuthRequired') return false;
- const normalizedContent = normalizeErrorText(content);
- const normalizedError = normalizeErrorText(body?.stderr || body?.message);
- return !!normalizedContent && !!normalizedError && normalizedContent === normalizedError;
+ return isEchoedErrorText(content, body?.stderr || body?.message);
};
// ─── Subagent delegation ───
diff --git a/packages/heterogeneous-agents/src/spawn/classifyProcessFailure.test.ts b/packages/heterogeneous-agents/src/spawn/classifyProcessFailure.test.ts
index f60009b7f4b..534fada3eaa 100644
--- a/packages/heterogeneous-agents/src/spawn/classifyProcessFailure.test.ts
+++ b/packages/heterogeneous-agents/src/spawn/classifyProcessFailure.test.ts
@@ -289,6 +289,32 @@ describe('classifyHeteroProcessFailure', () => {
).toMatchObject({ agentType: 'amp', code: 'auth_required', command: 'amp' });
});
+ it('classifies a spent subscription the CLI reported through its auth layer', () => {
+ // Kimi Code exits with `provider.auth_error` for a quota rejection; signing
+ // in again never clears it, so the quota wording has to win over auth.
+ expect(
+ classifyHeteroProcessFailure({
+ agentType: 'kimi-code',
+ detail:
+ "error: failed to run prompt: provider.auth_error: 403 You've reached your weekly (7-day) usage limit. Your quota will reset when the current 7-day window ends.",
+ }),
+ ).toMatchObject({
+ agentType: 'kimi-code',
+ code: 'rate_limit',
+ details: { kind: 'usage_limit' },
+ rateLimitInfo: { rateLimitType: 'seven_day', status: 'rejected' },
+ });
+ });
+
+ it('still reads a real Kimi Code sign-in failure as auth', () => {
+ expect(
+ classifyHeteroProcessFailure({
+ agentType: 'kimi-code',
+ detail: 'error: failed to run prompt: provider.auth_error: 401 Unauthorized',
+ }),
+ ).toMatchObject({ agentType: 'kimi-code', code: 'auth_required', command: 'kimi' });
+ });
+
it('returns undefined for unsupported agent types', () => {
expect(
classifyHeteroProcessFailure({
diff --git a/packages/heterogeneous-agents/src/spawn/classifyProcessFailure.ts b/packages/heterogeneous-agents/src/spawn/classifyProcessFailure.ts
index 48688b3b61e..7299cd644ed 100644
--- a/packages/heterogeneous-agents/src/spawn/classifyProcessFailure.ts
+++ b/packages/heterogeneous-agents/src/spawn/classifyProcessFailure.ts
@@ -5,6 +5,7 @@ import {
isHeterogeneousAgentAuthRequired,
isLocalHeterogeneousType,
} from '../config';
+import { classifyCliQuotaMessage } from '../errors/cliQuota';
import type { HeterogeneousTerminalErrorData } from '../types';
/**
@@ -19,9 +20,9 @@ import type { HeterogeneousTerminalErrorData } from '../types';
* error card instead of the heterogeneous status guide (install CLI / sign in).
*
* This helper mirrors the desktop in-process classifier
- * (`HeterogeneousAgentCtr.getSessionErrorPayload`) for the two guide codes a
+ * (`HeterogeneousAgentCtr.getSessionErrorPayload`) for the guide codes a
* process-level failure can produce: `cli_not_found`,
- * `working_directory_not_found`, and `auth_required`.
+ * `working_directory_not_found`, `rate_limit` and `auth_required`.
* The returned shape is persisted verbatim as the `ChatMessageError.body`, so
* it must carry `agentType` + `code` — that pair is what
* `isHeterogeneousAgentStatusGuideError` gates the dedicated UI on.
@@ -119,6 +120,25 @@ export const classifyHeteroProcessFailure = (
});
}
+ // Before auth: a CLI can report a spent subscription through its auth layer
+ // (Kimi Code exits with `provider.auth_error: 403 You've reached your weekly
+ // (7-day) usage limit…`). Signing in again never fixes that, so the quota
+ // wording has to win over anything the auth patterns recognize.
+ const quota = classifyCliQuotaMessage(detail);
+ if (detail && quota) {
+ return {
+ agentType,
+ code: 'rate_limit',
+ details: { kind: quota.kind },
+ error: detail,
+ message: detail,
+ ...(quota.rateLimitType
+ ? { rateLimitInfo: { rateLimitType: quota.rateLimitType, status: 'rejected' } }
+ : {}),
+ stderr: detail,
+ };
+ }
+
if (detail && isHeterogeneousAgentAuthRequired(agentType, detail)) {
return buildHeterogeneousAgentAuthRequiredError({
agentType,
diff --git a/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts b/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts
index 36bd781ee9c..655a7b8a8e2 100644
--- a/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts
+++ b/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts
@@ -22,7 +22,10 @@ import {
type SubagentIntent,
type SubagentRunSnapshot,
} from '@lobechat/heterogeneous-agents';
-import { normalizeHeterogeneousMessageError } from '@lobechat/heterogeneous-agents/errors';
+import {
+ isEchoedErrorText,
+ normalizeHeterogeneousMessageError,
+} from '@lobechat/heterogeneous-agents/errors';
import { formatContextSelections, formatPageSelections } from '@lobechat/prompts';
import type {
ChatMessageError,
@@ -98,8 +101,6 @@ const markSkipMessageFetch = (event: AgentStreamEvent): void => {
event.data = { ...event.data, skipMessageFetch: true };
};
-const normalizeErrorText = (value?: string) => value?.replaceAll(/\s+/g, ' ').trim();
-
const maybeClassifyCliAuthRequiredError = (
error: unknown,
agentType?: string,
@@ -134,12 +135,7 @@ const shouldSuppressTerminalErrorEcho = (content: string, error: ChatMessageErro
return false;
}
- const normalizedContent = normalizeErrorText(content);
- const normalizedRawError = normalizeErrorText(
- errorBody?.stderr || errorBody?.message || error.message,
- );
-
- return !!normalizedContent && !!normalizedRawError && normalizedContent === normalizedRawError;
+ return isEchoedErrorText(content, errorBody?.stderr || errorBody?.message || error.message);
};
const toRawHeterogeneousAgentMessageError = (