Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(codex): 自动重试终态 429 (#1523)

Dash0c7228ff9d02
diff --git a/apps/desktop/src/main/hook-control/__tests__/session-runner.test.ts b/apps/desktop/src/main/hook-control/__tests__/session-runner.test.ts
index d2ca6629ed..125f9871c4 100644
--- a/apps/desktop/src/main/hook-control/__tests__/session-runner.test.ts
+++ b/apps/desktop/src/main/hook-control/__tests__/session-runner.test.ts
@@ -95,6 +95,7 @@ vi.mock('@cindy/maker-core', async (importOriginal) => {
isTerminalAgentErrorEvent: actual.isTerminalAgentErrorEvent,
parseOverloadError: actual.parseOverloadError,
parseOverloadRetryProgress: actual.parseOverloadRetryProgress,
+ parseTerminalRateLimitRetryProgress: actual.parseTerminalRateLimitRetryProgress,
};
});
vi.mock('../../device-link/broadcast-tap.js', () => ({
diff --git a/apps/desktop/src/main/hook-control/turnObserver.ts b/apps/desktop/src/main/hook-control/turnObserver.ts
index 851703e3eb..d20c69c9c7 100644
--- a/apps/desktop/src/main/hook-control/turnObserver.ts
+++ b/apps/desktop/src/main/hook-control/turnObserver.ts
@@ -31,7 +31,7 @@ import {
renderActivity,
setActivityNotice,
} from '../im/shared/turnActivity.js';
-import { overloadFailureNotice, overloadRetryNotice } from '../im/shared/turnRetryNotice.js';
+import { overloadFailureNotice, turnRetryNotice } from '../im/shared/turnRetryNotice.js';
/*
* ── 为什么这里**没有**整轮静默兜底 ──────────────────────────────────────────
@@ -395,10 +395,10 @@ export function observeHookTurn(
return;
}
if (ev.type === 'error' && !isTerminalAgentErrorEvent(ev)) {
- // 非终止 error = agent 正在自愈(当前只透过载类的自动重试)。turn 没
+ // 非终止 error = agent 正在自愈(仅透已有本地化契约的自动重试)。turn 没
// 结束, 不收口; 但必须在过程区留一行, 否则零产出的退避窗口里渠道那
// 条消息整段静止(见 turnRetryNotice.ts 的模块注释)。
- const notice = overloadRetryNotice(ev.data);
+ const notice = turnRetryNotice(ev.data);
if (notice !== null && setActivityNotice(activity, notice)) {
// ticker 让"第 N 步 · 42s"与这行状态一起走时间, 重试期间没有任何
// 新事件也能看出还在动。
diff --git a/apps/desktop/src/main/im/shared/__tests__/turnRetryNotice.test.ts b/apps/desktop/src/main/im/shared/__tests__/turnRetryNotice.test.ts
index 26f6b59784..04d57242ed 100644
--- a/apps/desktop/src/main/im/shared/__tests__/turnRetryNotice.test.ts
+++ b/apps/desktop/src/main/im/shared/__tests__/turnRetryNotice.test.ts
@@ -10,8 +10,45 @@ import {
overloadFailureNotice,
overloadRetryNotice,
terminalErrorText,
+ turnRetryNotice,
} from '../turnRetryNotice';
+describe('turnRetryNotice', () => {
+ it('终态 429 外层重投 → 渠道侧限流进度', () => {
+ expect(
+ turnRetryNotice({
+ message:
+ 'exceeded retry limit, last status: 429 Too Many Requests (rate-limit-retry 1/2)',
+ reason: 'terminal-rate-limit-retry',
+ }),
+ ).toBe('请求受到限流,正在自动重试(1/2)…');
+ });
+
+ it('reason 与 marker 必须同时命中,普通 429 仍保持静默', () => {
+ expect(
+ turnRetryNotice({
+ message: 'provider failed (rate-limit-retry 1/2)',
+ reason: 'other-reason',
+ }),
+ ).toBeNull();
+ expect(
+ turnRetryNotice({
+ message: 'HTTP 429 Too Many Requests',
+ reason: 'terminal-rate-limit-retry',
+ }),
+ ).toBeNull();
+ expect(turnRetryNotice({ message: 'rate limit exceeded', errorStatus: 429 })).toBeNull();
+ });
+
+ it('继续覆盖原有过载进度', () => {
+ expect(
+ turnRetryNotice({
+ message: 'Selected model is at capacity. (auto-retry 2/4)',
+ }),
+ ).toBe('模型服务繁忙,正在自动重试(2/4)…');
+ });
+});
+
describe('overloadRetryNotice', () => {
it('带次数的 Codex 容量重投 → 带进度的中文提示', () => {
expect(
diff --git a/apps/desktop/src/main/im/shared/turnRetryNotice.ts b/apps/desktop/src/main/im/shared/turnRetryNotice.ts
index 0176d3d346..20ea0e2835 100644
--- a/apps/desktop/src/main/im/shared/turnRetryNotice.ts
+++ b/apps/desktop/src/main/im/shared/turnRetryNotice.ts
@@ -17,7 +17,8 @@
* currentTurnProducedOutput 守卫), 于是那段退避窗口(交互式约 22-38s)里过程区
* 与正文都是空的, 渠道那条占位消息一个字都不变 —— 用户看到的就是"卡死了"。
*
- * 只认过载一类, 其它非终止 error(429 / 5xx / 网络重连等)保持既有静默行为:
+ * 只认已有本地化契约的过载与终态 429 外层重投;其它非终止 error(普通 429 /
+ * 5xx / 网络重连等)保持既有静默行为:
* 它们的 message 是内部英文串, 渠道侧没有对应的中文表达, 贸然透出等于把裸英文
* 推给用户(这也是 maker-core 侧 claude translator 只透过载类的同一条理由)。
* 将来要放开某一类, 在这里按 kind 补一条文案即可, 不要直接外发原文。
@@ -27,7 +28,24 @@
* (见 docs/dev-rules/engineering-conventions.md §5)。
*/
-import { parseOverloadError, parseOverloadRetryProgress } from '@cindy/maker-core';
+import {
+ parseOverloadError,
+ parseOverloadRetryProgress,
+ parseTerminalRateLimitRetryProgress,
+} from '@cindy/maker-core';
+
+/** 已知的非终止自动重试事件 -> 渠道侧本地化进度;其它错误保持静默。 */
+export function turnRetryNotice(data: unknown): string | null {
+ if (!data || typeof data !== 'object') return null;
+ const record = data as { message?: unknown; reason?: unknown };
+ const message = typeof record.message === 'string' ? record.message : '';
+ const reason = typeof record.reason === 'string' ? record.reason : undefined;
+ const rateLimitProgress = parseTerminalRateLimitRetryProgress(message, reason);
+ if (rateLimitProgress) {
+ return `请求受到限流,正在自动重试(${rateLimitProgress.attempt}/${rateLimitProgress.maxAttempts})…`;
+ }
+ return overloadRetryNotice(data);
+}
/**
* 非终止 error 事件的 data -> 状态说明文案; 不是"正在自动重试的过载错误"时返回
diff --git a/apps/desktop/src/main/im/shared/turnRunner.ts b/apps/desktop/src/main/im/shared/turnRunner.ts
index 4c501a2d78..b0719eb468 100644
--- a/apps/desktop/src/main/im/shared/turnRunner.ts
+++ b/apps/desktop/src/main/im/shared/turnRunner.ts
@@ -109,7 +109,7 @@ import {
setActivityNotice,
type TurnActivityState,
} from './turnActivity';
-import { overloadRetryNotice, terminalErrorText } from './turnRetryNotice';
+import { terminalErrorText, turnRetryNotice } from './turnRetryNotice';
import {
toCoreAgentKind,
readPermissionMode,
@@ -1766,8 +1766,8 @@ export function createTurnRunner(
/**
* 非终止 error → 过程区状态行 + 卡片刷新。turn 不收口。
*
- * 只对"正在自动重试的过载"出提示(见 turnRetryNotice.ts): 其它非终止 error 的
- * message 是内部英文串, 没有对应中文表达, 保持既有静默。
+ * 只对已有本地化契约的自动重试出提示(见 turnRetryNotice.ts): 其它非终止
+ * error 的 message 是内部英文串, 没有对应中文表达, 保持既有静默。
*
* **要惰性建卡**(与 ensureActivityTicker「ticker 不该是创建卡片的理由」相反):
* 过载重投只在本 turn 零产出时发生(maker-core 的 currentTurnProducedOutput
@@ -1776,7 +1776,7 @@ export function createTurnRunner(
* 同一张卡上, 重试耗尽时 handleTurnErrorAsync 会把它 finalize 成失败说明。
*/
function handleRetryNoticeEvent(turn: TurnState, event: AgentEvent): void {
- const notice = overloadRetryNotice(event.data);
+ const notice = turnRetryNotice(event.data);
if (notice === null) return;
if (!setActivityNotice(turn.activity, notice)) return;
ensureActivityTicker(turn);
@@ -1919,7 +1919,7 @@ export function createTurnRunner(
// 取舍不同 —— 转播是自动任务的旁路展示, 没有人在等它; 为一条重试提示开卡,
// 万一那轮重试成功后 agent 零输出收口, thread 里就多出一张只有标题的卡。
{
- const notice = overloadRetryNotice(event.data);
+ const notice = turnRetryNotice(event.data);
if (notice !== null && setActivityNotice(t.activity, notice)) {
t.streamingHandle?.replace(composeTranspondView(t, false));
}
diff --git a/apps/desktop/src/renderer/__tests__/errorBannerCodexXaiAuth.test.tsx b/apps/desktop/src/renderer/__tests__/errorBannerCodexXaiAuth.test.tsx
index d9e372ff24..be4f0a7f15 100644
--- a/apps/desktop/src/renderer/__tests__/errorBannerCodexXaiAuth.test.tsx
+++ b/apps/desktop/src/renderer/__tests__/errorBannerCodexXaiAuth.test.tsx
@@ -178,3 +178,33 @@ describe('ErrorBanner overload guidance', () => {
expect(screen.getByText('chat.errorBanner.overloadRetrying:3/10')).toBeTruthy();
});
});
+
+describe('ErrorBanner terminal rate-limit retry guidance', () => {
+ const RATE_LIMIT =
+ 'exceeded retry limit, last status: 429 Too Many Requests (rate-limit-retry 1/2)';
+
+ it('shows localized rate-limit progress without calling it model overload', () => {
+ render(createElement(ErrorBanner, {
+ error: RATE_LIMIT,
+ errorReason: 'terminal-rate-limit-retry',
+ onRetry: vi.fn(),
+ isRecoverable: true,
+ }));
+
+ expect(screen.getByText('chat.errorBanner.rateLimitRetrying:1/2')).toBeTruthy();
+ expect(screen.queryByText('chat.errorBanner.overloadRetrying:1/2')).toBeNull();
+ expect(screen.queryByTitle('chat.errorBanner.retryTitle')).toBeNull();
+ });
+
+ it('keeps the raw provider error available for diagnosis', () => {
+ render(createElement(ErrorBanner, {
+ error: RATE_LIMIT,
+ errorReason: 'terminal-rate-limit-retry',
+ onRetry: vi.fn(),
+ isRecoverable: true,
+ }));
+
+ fireEvent.click(screen.getByText('chat.errorBanner.networkShowRaw'));
+ expect(screen.getByText(RATE_LIMIT)).toBeTruthy();
+ });
+});
diff --git a/apps/desktop/src/renderer/__tests__/rateLimitRetry.test.ts b/apps/desktop/src/renderer/__tests__/rateLimitRetry.test.ts
new file mode 100644
index 0000000000..4ee70d38a3
--- /dev/null
+++ b/apps/desktop/src/renderer/__tests__/rateLimitRetry.test.ts
@@ -0,0 +1,34 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ parseTerminalRateLimitRetryProgress,
+ TERMINAL_RATE_LIMIT_RETRY_REASON,
+} from '@/utils/rateLimitRetry';
+
+describe('parseTerminalRateLimitRetryProgress', () => {
+ it('requires the dedicated reason and marker', () => {
+ const message =
+ 'exceeded retry limit, last status: 429 Too Many Requests (rate-limit-retry 1/2)';
+ expect(parseTerminalRateLimitRetryProgress(message, TERMINAL_RATE_LIMIT_RETRY_REASON)).toEqual({
+ attempt: 1,
+ maxAttempts: 2,
+ });
+ expect(parseTerminalRateLimitRetryProgress(message, undefined)).toBeNull();
+ expect(
+ parseTerminalRateLimitRetryProgress(
+ 'Selected model is at capacity (auto-retry 1/4)',
+ TERMINAL_RATE_LIMIT_RETRY_REASON,
+ ),
+ ).toBeNull();
+ });
+
+ it.each([
+ 'provider failed (rate-limit-retry 0/2)',
+ 'provider failed (rate-limit-retry 3/2)',
+ 'provider failed (rate-limit-retry 1/2) trailing text',
+ ])('rejects an invalid progress marker: %s', (message) => {
+ expect(
+ parseTerminalRateLimitRetryProgress(message, TERMINAL_RATE_LIMIT_RETRY_REASON),
+ ).toBeNull();
+ });
+});
diff --git a/apps/desktop/src/renderer/components/chat/ErrorBanner.tsx b/apps/desktop/src/renderer/components/chat/ErrorBanner.tsx
index 194dc8c5d6..b75b13efc6 100644
--- a/apps/desktop/src/renderer/components/chat/ErrorBanner.tsx
+++ b/apps/desktop/src/renderer/components/chat/ErrorBanner.tsx
@@ -41,6 +41,7 @@ import { isInvalidEncryptedContentError } from '@/utils/encryptedContentError';
import { isNetworkishErrorMessage, parseReconnectAttemptMessage } from '@/utils/networkError';
import { isOverloadErrorMessage, parseOverloadRetryProgress } from '@/utils/overloadError';
import { isQuotaExhaustedErrorMessage } from '@/utils/quotaError';
+import { parseTerminalRateLimitRetryProgress } from '@/utils/rateLimitRetry';
import { ERROR_REASON_I18N_KEYS } from './errorReasonI18n';
import { CLAUDE_GATEWAY_OPUS_PLAN_MISMATCH_REASON } from '../../../shared/claudeGatewayError';
import { isPiImageInputUnsupportedError } from '../../../shared/inputError';
@@ -254,6 +255,7 @@ export function ErrorBanner({
const isOverloadError = isOverloadErrorMessage(error, undefined, errorReason);
const overloadRetryProgress = parseOverloadRetryProgress(error);
const errorReasonI18nKey = errorReason ? ERROR_REASON_I18N_KEYS[errorReason] : undefined;
+ const terminalRateLimitRetryProgress = parseTerminalRateLimitRetryProgress(error, errorReason);
// Retry 的显示条件与网络错误文案必须共用同一个判定。外部发起的 turn(例如
// scheduler / goal)失败时没有安全的 recovery target,errorRetryText 会是 null;
// 此时不能一边隐藏按钮,一边仍提示用户“点击重试”。
@@ -310,6 +312,13 @@ export function ErrorBanner({
// 「配额或余额不足,请检查供应商账户」对网关用户是半句话:账户就在 Cindy 里,
// 该说的是「去充值」而不是「去检查」。右端的内联出口负责「去哪充」。
displayError = t('chat.errorBanner.gatewayQuotaExhausted');
+ } else if (terminalRateLimitRetryProgress) {
+ // daemon 已耗尽内部 retry budget 的终态 429,由 maker-core 做受限外层重投。
+ // 它不是模型容量过载,也不是用户网络异常;独立文案避免误导用户切模型或查网络。
+ displayError = t('chat.errorBanner.rateLimitRetrying', {
+ attempt: terminalRateLimitRetryProgress.attempt,
+ maxAttempts: terminalRateLimitRetryProgress.maxAttempts,
+ });
} else if (isOverloadError) {
// 服务过载:上游模型没有可用容量。原始英文("Selected model is at capacity")
// 对用户没有行动价值,换成友好文案 + 明确的下一步;原始错误折叠可查。
@@ -493,7 +502,10 @@ export function ErrorBanner({
{t('chat.errorBanner.budgetModelHint')}
</span>
)}
- {(isNetworkishError || isOverloadError || isClaudeGatewayOpusPlanMismatch) && (
+ {(isNetworkishError ||
+ isOverloadError ||
+ terminalRateLimitRetryProgress ||
+ isClaudeGatewayOpusPlanMismatch) && (
// 网络类与过载类的原始错误折叠可查:友好文案替换了原文,但排障(端口/URL/
// errno/上游原话)仍需要原文,点击展开。新增控件走 --error-fg token(规则 16;
// 本组件其余 red-600/400 为历史存量,error 属语义豁免色但新代码仍走 token)。
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index 8e5a604e07..2de1183357 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -5567,6 +5567,7 @@
"networkAutoRetrying": "Network error — retrying automatically…",
"networkReconnecting": "Connection interrupted — reconnecting ({{attempt}}/{{maxAttempts}})…",
"overloadRetrying": "The model service is busy — retrying automatically ({{attempt}}/{{maxAttempts}})…",
+ "rateLimitRetrying": "Request rate limited — retrying automatically ({{attempt}}/{{maxAttempts}})…",
"overloadBusy": "The model service is busy — the upstream has no capacity right now. Click \"Retry\", or switch to another model.",
"overloadBusyNoRetry": "The model service is busy — the upstream has no capacity right now. Try again later, or switch to another model.",
"networkShowRaw": "Show raw error",
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index 2fb9e697b9..450805e5d9 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -5565,6 +5565,7 @@
"networkAutoRetrying": "ネットワークエラー:自動的に再試行しています…",
"networkReconnecting": "接続が中断されました。再接続中({{attempt}}/{{maxAttempts}})…",
"overloadRetrying": "モデルサービスが混雑しています:自動的に再試行しています({{attempt}}/{{maxAttempts}})…",
+ "rateLimitRetrying": "リクエストがレート制限されました。自動的に再試行しています({{attempt}}/{{maxAttempts}})…",
"overloadBusy": "モデルサービスが混雑しています。上流に空き容量がありません。「再試行」を押すか、別のモデルに切り替えてください",
"overloadBusyNoRetry": "モデルサービスが混雑しています。上流に空き容量がありません。しばらくしてから再試行するか、別のモデルに切り替えてください",
"networkShowRaw": "元のエラーを表示",
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index 4e706fe378..b919900d28 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -5565,6 +5565,7 @@
"networkAutoRetrying": "네트워크 오류: 자동으로 다시 시도하는 중…",
"networkReconnecting": "연결이 끊어졌습니다. 다시 연결하는 중({{attempt}}/{{maxAttempts}})…",
"overloadRetrying": "모델 서비스가 혼잡합니다. 자동으로 다시 시도하는 중({{attempt}}/{{maxAttempts}})…",
+ "rateLimitRetrying": "요청이 속도 제한에 걸렸습니다. 자동으로 다시 시도하는 중({{attempt}}/{{maxAttempts}})…",
"overloadBusy": "모델 서비스가 혼잡합니다. 상위 서비스에 여유 용량이 없습니다. \"재시도\"를 누르거나 다른 모델로 바꿔 보세요",
"overloadBusyNoRetry": "모델 서비스가 혼잡합니다. 상위 서비스에 여유 용량이 없습니다. 잠시 후 다시 시도하거나 다른 모델로 바꿔 보세요",
"networkShowRaw": "원본 오류 보기",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
index 96c60a3ba1..8e9d55f4eb 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -5565,6 +5565,7 @@
"networkAutoRetrying": "网络异常,正在自动重试…",
"networkReconnecting": "网络连接中断,正在重新连接({{attempt}}/{{maxAttempts}})…",
"overloadRetrying": "模型服务繁忙,正在自动重试({{attempt}}/{{maxAttempts}})…",
+ "rateLimitRetrying": "请求受到限流,正在自动重试({{attempt}}/{{maxAttempts}})…",
"overloadBusy": "模型服务繁忙,上游暂时没有可用容量。可点击「重试」,或换一个模型。",
"overloadBusyNoRetry": "模型服务繁忙,上游暂时没有可用容量。可稍后重试,或换一个模型。",
"networkShowRaw": "查看原始错误",
diff --git a/apps/desktop/src/renderer/utils/rateLimitRetry.ts b/apps/desktop/src/renderer/utils/rateLimitRetry.ts
new file mode 100644
index 0000000000..1f01919d3c
--- /dev/null
+++ b/apps/desktop/src/renderer/utils/rateLimitRetry.ts
@@ -0,0 +1,32 @@
+/**
+ * Codex daemon 耗尽内部 retry budget 后,maker-core 接管终态 429 时使用的
+ * renderer 契约。reason 与进度 marker 必须同时命中,避免把普通 429 或模型容量
+ * 过载误归类成这条外层重投路径。
+ *
+ * maker-core 侧同名常量与 formatter 位于
+ * `packages/maker-core/src/agents/codex/terminal-rate-limit-retry.ts`;两端不跨 bundle
+ * 共享代码,修改契约时必须同步。
+ */
+export const TERMINAL_RATE_LIMIT_RETRY_REASON = 'terminal-rate-limit-retry';
+
+const TERMINAL_RATE_LIMIT_RETRY_PROGRESS_RE = /\(rate-limit-retry\s+(\d+)\s*\/\s*(\d+)\)\s*$/;
+
+export function parseTerminalRateLimitRetryProgress(
+ message: string,
+ reason?: string | null,
+): { attempt: number; maxAttempts: number } | null {
+ if (reason !== TERMINAL_RATE_LIMIT_RETRY_REASON) return null;
+ const match = TERMINAL_RATE_LIMIT_RETRY_PROGRESS_RE.exec(message);
+ if (!match) return null;
+ const attempt = Number(match[1]);
+ const maxAttempts = Number(match[2]);
+ if (
+ !Number.isSafeInteger(attempt) ||
+ !Number.isSafeInteger(maxAttempts) ||
+ attempt < 1 ||
+ maxAttempts < attempt
+ ) {
+ return null;
+ }
+ return { attempt, maxAttempts };
+}
diff --git a/apps/desktop/src/shared/providerErrors.ts b/apps/desktop/src/shared/providerErrors.ts
index 30a109b496..c46b6d1326 100644
--- a/apps/desktop/src/shared/providerErrors.ts
+++ b/apps/desktop/src/shared/providerErrors.ts
@@ -12,7 +12,10 @@
*/
/** 结构化错误码 —— renderer 按 `providerError.<code>` 取 i18n 文案。 */
-import { redactSensitiveText } from '@cindy/maker-shared/error-redaction';
+import {
+ matchesDeterministicUsageExhaustionText,
+ redactSensitiveText,
+} from '@cindy/maker-shared/error-redaction';
export type ProviderErrorCode =
/** 401:key 无效 / OAuth token 失效。 */
@@ -80,8 +83,6 @@ const MODEL_NOT_FOUND_RE =
/** 上下文超长:Anthropic "prompt is too long"、OpenAI "maximum context length"、通用 token limit 措辞。 */
const CONTEXT_TOO_LONG_RE =
/prompt is too long|maximum context length|context.{0,20}(length|window).{0,40}(exceed|too)|too many tokens|input length.{0,20}exceed|context_length_exceeded/i;
-/** 余额 / 配额:OpenAI "insufficient_quota"、通用 balance / credit 措辞。 */
-const QUOTA_RE = /insufficient_quota|insufficient.{0,12}(balance|credit|funds)|quota.{0,20}exceed|余额不足|欠费/i;
/** wire 兼容性:端点不认识请求里的字段 / 参数(典型:litellm/Azure 对 Anthropic-only 字段报错)。 */
const WIRE_RE =
/(unknown|unexpected|unsupported|extra|unrecognized).{0,16}(field|parameter|argument|inputs?|property|request param)|extra inputs are not permitted|invalid_request_error[^\n]{0,120}(field|param)/i;
@@ -98,7 +99,7 @@ const AUTH_RE = /invalid.{0,10}(api.?key|token)|authentication_error|unauthorize
* 新增 pattern 仍需真实错误体为证(见文件头注释)。
*/
export function matchesQuotaExhaustedText(text: string): boolean {
- return QUOTA_RE.test(text);
+ return matchesDeterministicUsageExhaustionText(text);
}
/**
@@ -136,7 +137,9 @@ export function classifyProviderError(input: ProviderErrorInput): ProviderErrorC
if (status === 400 || status === 422) {
if (MODEL_NOT_FOUND_RE.test(body)) return { code: 'MODEL_NOT_FOUND', retryable: false, detail };
if (CONTEXT_TOO_LONG_RE.test(body)) return { code: 'CONTEXT_TOO_LONG', retryable: false, detail };
- if (QUOTA_RE.test(body)) return { code: 'QUOTA_EXCEEDED', retryable: false, detail };
+ if (matchesDeterministicUsageExhaustionText(body)) {
+ return { code: 'QUOTA_EXCEEDED', retryable: false, detail };
+ }
if (AUTH_RE.test(body)) return { code: 'AUTH_INVALID', retryable: false, detail };
if (WIRE_RE.test(body)) return { code: 'WIRE_INCOMPATIBLE', retryable: false, detail };
return { code: 'UNKNOWN', retryable: false, detail };
diff --git a/apps/mobile/app/sessions/[sessionId].tsx b/apps/mobile/app/sessions/[sessionId].tsx
index 9f0c89f92e..81b80ff35e 100644
--- a/apps/mobile/app/sessions/[sessionId].tsx
+++ b/apps/mobile/app/sessions/[sessionId].tsx
@@ -9195,14 +9195,15 @@ function ComposerActivityStatus({
const elapsedText = formatComposerActivityElapsed(elapsed);
const tokenText = formatComposerActivityTokens(tokenUsage);
- // 过载退避与传输层重连共用这一个 attempt 字段, 但说法必须分开: 前者是上游没有可用
- // 容量、agent 在退避重投, 说「正在重新连接」会把用户引向排查自己的网络
- // (review #844 codex P1)。
+ // 三类进度共用这一个 attempt 字段, 但说法必须分开: 模型容量、请求限流与传输层重连
+ // 的用户含义不同,混用会把用户引向错误的排查方向。
const activityText = reconnectAttempt
? t(
reconnectAttempt.kind === 'overload'
? 'session.screen.modelBusyRetrying'
- : 'session.screen.networkReconnecting',
+ : reconnectAttempt.kind === 'rate-limit'
+ ? 'session.screen.rateLimitRetrying'
+ : 'session.screen.networkReconnecting',
)
: t('session.screen.thinking');
diff --git a/apps/mobile/src/__tests__/remoteSessionStore.test.ts b/apps/mobile/src/__tests__/remoteSessionStore.test.ts
index b9f3058b99..33af072015 100644
--- a/apps/mobile/src/__tests__/remoteSessionStore.test.ts
+++ b/apps/mobile/src/__tests__/remoteSessionStore.test.ts
@@ -1816,6 +1816,51 @@ describe('remoteSessionStore', () => {
});
});
+ it('projects terminal 429 retries as rate-limit attempts only with their reason', () => {
+ const message =
+ 'exceeded retry limit, last status: 429 Too Many Requests (rate-limit-retry 1/2)';
+ remoteSessionStore.applyRemotePush('dev-1', 'maker:event', {
+ sessionId: 's1',
+ event: {
+ type: 'error',
+ data: {
+ message,
+ reason: 'terminal-rate-limit-retry',
+ isTerminal: false,
+ willRetry: true,
+ },
+ },
+ });
+ expect(remoteSessionStore.getSessionRunStatus('s1').reconnectAttempt).toEqual({
+ attempt: 1,
+ maxAttempts: 2,
+ kind: 'rate-limit',
+ });
+
+ remoteSessionStore.applyRemotePush('dev-1', 'maker:event', {
+ sessionId: 's1',
+ event: {
+ type: 'error',
+ data: { message, isTerminal: false, willRetry: true },
+ },
+ });
+ expect(remoteSessionStore.getSessionRunStatus('s1').reconnectAttempt).toBeNull();
+
+ remoteSessionStore.applyRemotePush('dev-1', 'maker:event', {
+ sessionId: 's1',
+ event: {
+ type: 'error',
+ data: {
+ message: 'provider failed (auto-retry 1/2)',
+ reason: 'terminal-rate-limit-retry',
+ isTerminal: false,
+ willRetry: true,
+ },
+ },
+ });
+ expect(remoteSessionStore.getSessionRunStatus('s1').reconnectAttempt).toBeNull();
+ });
+
it('tracks session running state from maker event push boundaries', () => {
vi.useFakeTimers();
vi.setSystemTime(new Date('2026-01-01T00:00:10.000Z'));
diff --git a/apps/mobile/src/__tests__/sessionComposerDesktopFirst.test.ts b/apps/mobile/src/__tests__/sessionComposerDesktopFirst.test.ts
index 0a521b4383..a148b48d24 100644
--- a/apps/mobile/src/__tests__/sessionComposerDesktopFirst.test.ts
+++ b/apps/mobile/src/__tests__/sessionComposerDesktopFirst.test.ts
@@ -149,6 +149,7 @@ describe('mobile session composer desktop-first surface', () => {
// (review #844 codex P1)。字符串按 i18n key 断言, 不断言三元表达式的写法。
expect(source).toContain("'session.screen.networkReconnecting'");
expect(source).toContain("'session.screen.modelBusyRetrying'");
+ expect(source).toContain("'session.screen.rateLimitRetrying'");
expect(source).toContain('{reconnectAttempt.attempt}/{reconnectAttempt.maxAttempts}');
expect(source).toContain('ArrowDown');
expect(source).toContain('useSessionRunStatus');
diff --git a/apps/mobile/src/i18n/locales/en/session.json b/apps/mobile/src/i18n/locales/en/session.json
index 58063efdeb..6a69b5ded4 100644
--- a/apps/mobile/src/i18n/locales/en/session.json
+++ b/apps/mobile/src/i18n/locales/en/session.json
@@ -28,6 +28,7 @@
"thinking": "Thinking…",
"networkReconnecting": "Reconnecting…",
"modelBusyRetrying": "Model service busy — retrying…",
+ "rateLimitRetrying": "Request rate limited — retrying…",
"composerSyncing": "Syncing session data; you can send once it finishes.",
"composerSessionNotSynced": "This session has not finished syncing yet.",
"composerCreating": "Creating the session; you can keep sending after the first message goes out.",
diff --git a/apps/mobile/src/i18n/locales/ja/session.json b/apps/mobile/src/i18n/locales/ja/session.json
index ba117524e7..2c4ff0ca81 100644
--- a/apps/mobile/src/i18n/locales/ja/session.json
+++ b/apps/mobile/src/i18n/locales/ja/session.json
@@ -28,6 +28,7 @@
"thinking": "考えています…",
"networkReconnecting": "再接続中…",
"modelBusyRetrying": "モデルサービスが混雑、再試行中…",
+ "rateLimitRetrying": "リクエストがレート制限されました。再試行中…",
"composerSyncing": "セッションデータを同期中です。完了すると送信できます。",
"composerSessionNotSynced": "このセッションはまだ同期が完了していません。",
"composerCreating": "セッションを作成中です。最初のメッセージ送信後に続けて送信できます。",
diff --git a/apps/mobile/src/i18n/locales/ko/session.json b/apps/mobile/src/i18n/locales/ko/session.json
index 767277c2cc..38083d142b 100644
--- a/apps/mobile/src/i18n/locales/ko/session.json
+++ b/apps/mobile/src/i18n/locales/ko/session.json
@@ -28,6 +28,7 @@
"thinking": "생각 중…",
"networkReconnecting": "다시 연결하는 중…",
"modelBusyRetrying": "모델 서비스 혼잡, 다시 시도 중…",
+ "rateLimitRetrying": "요청이 속도 제한에 걸렸습니다. 다시 시도 중…",
"composerSyncing": "세션 데이터를 동기화 중입니다. 완료되면 보낼 수 있습니다.",
"composerSessionNotSynced": "이 세션은 아직 동기화가 끝나지 않았습니다.",
"composerCreating": "세션을 만드는 중입니다. 첫 메시지가 전송되면 계속 보낼 수 있습니다.",
diff --git a/apps/mobile/src/i18n/locales/zh-CN/session.json b/apps/mobile/src/i18n/locales/zh-CN/session.json
index 1441d7c23c..4790ca9df7 100644
--- a/apps/mobile/src/i18n/locales/zh-CN/session.json
+++ b/apps/mobile/src/i18n/locales/zh-CN/session.json
@@ -28,6 +28,7 @@
"thinking": "思考中…",
"networkReconnecting": "正在重新连接…",
"modelBusyRetrying": "模型服务繁忙,正在重试…",
+ "rateLimitRetrying": "请求受到限流,正在重试…",
"composerSyncing": "正在同步任务数据,同步完成后即可发送。",
"composerSessionNotSynced": "当前任务还没有同步完成。",
"composerCreating": "任务创建中,首条消息发出后即可继续发送。",
diff --git a/apps/mobile/src/session/remoteSessionStore.ts b/apps/mobile/src/session/remoteSessionStore.ts
index 2b5b0b535d..35ade2f015 100644
--- a/apps/mobile/src/session/remoteSessionStore.ts
+++ b/apps/mobile/src/session/remoteSessionStore.ts
@@ -71,13 +71,13 @@ export interface RemoteSessionReconnectAttempt {
attempt: number;
maxAttempts: number;
/**
- * 重试原因。`'overload'` = 上游模型没有可用容量、agent 正在退避重投
- * (maker-core 的 `(auto-retry N/M)` 标记); 缺省 / `'reconnect'` = 传输层重连。
+ * 重试原因。`'overload'` = 上游模型没有可用容量;`'rate-limit'` = Codex daemon
+ * 已耗尽内部 retry budget 后的受限外层重投;缺省 / `'reconnect'` = 传输层重连。
*
* 刻意复用同一个字段而不是新加一个: 这个 attempt 有 6 处清理点(turn 边界 / 快照 /
* 收口 / 活动流), 拆成两个字段就得在每处各清一次, 漏一处就会残留一个假状态。
*/
- kind?: 'reconnect' | 'overload';
+ kind?: 'reconnect' | 'overload' | 'rate-limit';
}
interface SessionMessageSyncMarker {
@@ -2355,7 +2355,10 @@ export const remoteSessionStore = {
if (type === 'error') {
const data = isRecord(event.data) ? event.data : null;
const reconnectAttempt = data?.willRetry === true
- ? parseReconnectAttemptMessage(readString(data, 'message') ?? '')
+ ? parseReconnectAttemptMessage(
+ readString(data, 'message') ?? '',
+ readString(data, 'reason'),
+ )
: null;
const current = readSessionRunStatus(sessionId);
const changed = writeSessionRunStatus(sessionId, {
@@ -2796,17 +2799,30 @@ function parseAttemptPair(
/**
* 非终止 error 的 message → 重试进度。
*
- * 两类各有自己的标记:
+ * 三类各有自己的标记:
* - 传输层重连: `Reconnecting... N/M`;
* - 上游过载退避重投: `(auto-retry N/M)`(maker-core 的
* agents/shared/overload-error.ts 统一后缀, Codex 与 Claude 两侧同款)。
+ * - daemon 终态 429 外层重投: reason=`terminal-rate-limit-retry` +
+ * `(rate-limit-retry N/M)`;reason 与 marker 必须同时命中。
*
- * 后者不认的话, 整个退避窗口(交互式最长约 30s)手机端只显示笼统的「思考中」, 用户看不出
+ * 过载 marker 不认的话, 整个退避窗口(交互式最长约 30s)手机端只显示笼统的「思考中」, 用户看不出
* 是在等上游容量(review #844 codex P1)。这里刻意在 mobile 侧独立实现一份判定, 与
* renderer 的 utils/overloadError.ts 同规 —— maker-core 是 desktop/node 侧包, 不跨
* bundle 共享。
*/
-function parseReconnectAttemptMessage(message: string): RemoteSessionReconnectAttempt | null {
+const TERMINAL_RATE_LIMIT_RETRY_REASON = 'terminal-rate-limit-retry';
+
+function parseReconnectAttemptMessage(
+ message: string,
+ reason?: string | null,
+): RemoteSessionReconnectAttempt | null {
+ if (reason === TERMINAL_RATE_LIMIT_RETRY_REASON) {
+ const rateLimit = parseAttemptPair(
+ /\(rate-limit-retry\s+(\d+)\s*\/\s*(\d+)\)\s*$/i.exec(message),
+ );
+ return rateLimit ? { ...rateLimit, kind: 'rate-limit' } : null;
+ }
const reconnect = parseAttemptPair(
/\bReconnecting(?:\.{3}|…)\s*(\d+)\s*\/\s*(\d+)\b/i.exec(message),
);
diff --git a/packages/maker-core/src/agents/codex/index.test.ts b/packages/maker-core/src/agents/codex/index.test.ts
index a23d2d7334..f1aef067d1 100644
--- a/packages/maker-core/src/agents/codex/index.test.ts
+++ b/packages/maker-core/src/agents/codex/index.test.ts
@@ -5830,6 +5830,27 @@ describe('CodexAgent MCP thread context hooks', () => {
}
const CAPACITY_MESSAGE = 'Selected model is at capacity. Please try a different model.';
+ const TERMINAL_RATE_LIMIT_MESSAGE =
+ 'exceeded retry limit, last status: 429 Too Many Requests';
+
+ async function rejectCurrentTurnForTerminalRateLimit(
+ handle: AgentSessionHandle,
+ handlers: ThreadEventHandlers,
+ ): Promise<void> {
+ const turnId = handle.getCurrentTurnId?.() ?? '';
+ handlers.error?.({
+ threadId: 'start-thread-id',
+ turnId,
+ willRetry: false,
+ error: {
+ message: TERMINAL_RATE_LIMIT_MESSAGE,
+ codexErrorInfo: {
+ responseTooManyFailedAttempts: { httpStatusCode: 429 },
+ },
+ },
+ });
+ await vi.advanceTimersByTimeAsync(40_000);
+ }
function turnStartCount(host: ReturnType<typeof installFakeHost>): number {
return host.request.mock.calls.filter(([method]) => method === Method.TurnStart).length;
@@ -5910,6 +5931,254 @@ describe('CodexAgent MCP thread context hooks', () => {
}
});
+ it('retries a zero-output terminal 429 after the daemon exhausts its own retry budget', async () => {
+ vi.useFakeTimers();
+ try {
+ const agent = new CodexAgent(createDeps());
+ const host = installCapacityHost(agent);
+ const handle = await agent.startSession({
+ sessionId: 'session-terminal-rate-limit-retry',
+ model: 'gpt-5.4',
+ workingDir: '/repo',
+ });
+ await handle.send({ type: 'user', content: 'hello' });
+
+ const handlers = host.getThreadHandlers();
+ if (!handlers?.error) throw new Error('expected error handler');
+ const events: AgentEvent[] = [];
+ void (async () => {
+ for await (const event of handle.events()) events.push(event);
+ })();
+
+ handlers.error({
+ threadId: 'start-thread-id',
+ turnId: 'turn-1',
+ willRetry: false,
+ error: {
+ message: TERMINAL_RATE_LIMIT_MESSAGE,
+ codexErrorInfo: {
+ responseTooManyFailedAttempts: { httpStatusCode: 429 },
+ },
+ },
+ });
+ await vi.advanceTimersByTimeAsync(0);
+
+ const errorEvents = events.filter((event) => event.type === 'error');
+ expect(errorEvents).toHaveLength(1);
+ expect(errorEvents[0].data).toMatchObject({
+ errorStatus: 429,
+ isTerminal: false,
+ willRetry: true,
+ });
+ expect((errorEvents[0].data as { message: string }).message).toContain(
+ 'rate-limit-retry 1/2',
+ );
+ expect(errorEvents[0].data).toMatchObject({
+ reason: 'terminal-rate-limit-retry',
+ });
+ expect(
+ events.some(
+ (event) =>
+ event.type === 'status' &&
+ (event.data as { isRunning?: boolean }).isRunning === false,
+ ),
+ ).toBe(false);
+
+ await vi.advanceTimersByTimeAsync(20_000);
+ expect(turnStartCount(host)).toBe(2);
+
+ await handle.close();
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('stops terminal 429 outer retries after two attempts', async () => {
+ vi.useFakeTimers();
+ try {
+ const agent = new CodexAgent(createDeps());
+ const host = installCapacityHost(agent);
+ const handle = await agent.startSession({
+ sessionId: 'session-terminal-rate-limit-budget',
+ model: 'gpt-5.4',
+ workingDir: '/repo',
+ });
+ await handle.send({ type: 'user', content: 'hello' });
+
+ const handlers = host.getThreadHandlers();
+ if (!handlers?.error) throw new Error('expected error handler');
+ const events: AgentEvent[] = [];
+ void (async () => {
+ for await (const event of handle.events()) events.push(event);
+ })();
+
+ for (let i = 0; i < 3; i += 1) {
+ await rejectCurrentTurnForTerminalRateLimit(handle, handlers);
+ }
+
+ expect(turnStartCount(host)).toBe(1 + 2);
+ expect(
+ events.filter(
+ (event) =>
+ event.type === 'error' &&
+ (event.data as { isTerminal?: boolean }).isTerminal === true,
+ ),
+ ).toHaveLength(1);
+ expect(
+ events.some(
+ (event) =>
+ event.type === 'status' &&
+ (event.data as { isRunning?: boolean }).isRunning === false,
+ ),
+ ).toBe(true);
+
+ await handle.close();
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it.each([
+ {
+ name: 'capacity then terminal rate limit',
+ failures: ['capacity', 'terminal-rate-limit', 'terminal-rate-limit'] as const,
+ expectedTurnStarts: 3,
+ },
+ {
+ name: 'terminal rate limit then capacity',
+ failures: [
+ 'terminal-rate-limit',
+ 'terminal-rate-limit',
+ 'capacity',
+ 'capacity',
+ 'capacity',
+ ] as const,
+ expectedTurnStarts: 5,
+ },
+ ])(
+ 'shares one replay budget across policies: $name',
+ async ({ failures, expectedTurnStarts }) => {
+ vi.useFakeTimers();
+ try {
+ const agent = new CodexAgent(createDeps());
+ const host = installCapacityHost(agent);
+ const handle = await agent.startSession({
+ sessionId: `session-shared-replay-budget-${failures[0]}`,
+ model: 'gpt-5.4',
+ workingDir: '/repo',
+ });
+ await handle.send({ type: 'user', content: 'hello' });
+
+ const handlers = host.getThreadHandlers();
+ if (!handlers?.error) throw new Error('expected error handler');
+ const events: AgentEvent[] = [];
+ void (async () => {
+ for await (const event of handle.events()) events.push(event);
+ })();
+
+ for (const failure of failures) {
+ if (failure === 'capacity') {
+ await rejectCurrentTurnForCapacity(handle, handlers);
+ } else {
+ await rejectCurrentTurnForTerminalRateLimit(handle, handlers);
+ }
+ }
+
+ // 两类错误共享同一 logical send 的 attempt:策略切换不能各自续满预算。
+ // 顺序不同只会选择当前 policy 的上限,绝不会叠成 4 + 2 次外层重投。
+ expect(turnStartCount(host)).toBe(expectedTurnStarts);
+ expect(
+ events.filter(
+ (event) =>
+ event.type === 'error' &&
+ (event.data as { isTerminal?: boolean }).isTerminal === true,
+ ),
+ ).toHaveLength(1);
+
+ await handle.close();
+ } finally {
+ vi.useRealTimers();
+ }
+ },
+ );
+
+ it('does not outer-retry a terminal 429 after the turn produced output', async () => {
+ vi.useFakeTimers();
+ try {
+ const agent = new CodexAgent(createDeps());
+ const host = installCapacityHost(agent);
+ const handle = await agent.startSession({
+ sessionId: 'session-terminal-rate-limit-output',
+ model: 'gpt-5.4',
+ workingDir: '/repo',
+ });
+ await handle.send({ type: 'user', content: 'hello' });
+
+ const handlers = host.getThreadHandlers();
+ if (!handlers?.error || !handlers.reasoningTextDelta) {
+ throw new Error('expected handlers');
+ }
+ handlers.reasoningTextDelta({
+ threadId: 'start-thread-id',
+ turnId: 'turn-1',
+ delta: 'already working',
+ } as never);
+ handlers.error({
+ threadId: 'start-thread-id',
+ turnId: 'turn-1',
+ willRetry: false,
+ error: {
+ message: TERMINAL_RATE_LIMIT_MESSAGE,
+ codexErrorInfo: {
+ responseTooManyFailedAttempts: { httpStatusCode: 429 },
+ },
+ },
+ });
+ await vi.advanceTimersByTimeAsync(40_000);
+
+ expect(turnStartCount(host)).toBe(1);
+ expect(handle.isTurnRunning?.()).toBe(false);
+
+ await handle.close();
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('does not outer-retry terminal account usage limits even when the text contains 429', async () => {
+ vi.useFakeTimers();
+ try {
+ const agent = new CodexAgent(createDeps());
+ const host = installCapacityHost(agent);
+ const handle = await agent.startSession({
+ sessionId: 'session-terminal-usage-limit',
+ model: 'gpt-5.4',
+ workingDir: '/repo',
+ });
+ await handle.send({ type: 'user', content: 'hello' });
+
+ const handlers = host.getThreadHandlers();
+ if (!handlers?.error) throw new Error('expected error handler');
+ handlers.error({
+ threadId: 'start-thread-id',
+ turnId: 'turn-1',
+ willRetry: false,
+ error: {
+ message: TERMINAL_RATE_LIMIT_MESSAGE,
+ codexErrorInfo: 'usageLimitExceeded',
+ },
+ });
+ await vi.advanceTimersByTimeAsync(40_000);
+
+ expect(turnStartCount(host)).toBe(1);
+ expect(handle.isTurnRunning?.()).toBe(false);
+
+ await handle.close();
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
it('stops after the retry budget and only then reports a terminal error', async () => {
vi.useFakeTimers();
try {
@@ -6196,7 +6465,7 @@ describe('CodexAgent MCP thread context hooks', () => {
(e) =>
e.type === 'error' &&
(e.data as { isTerminal?: boolean; reason?: string }).isTerminal === true &&
- (e.data as { reason?: string }).reason === 'codex-overload-retry-aborted',
+ (e.data as { reason?: string }).reason === 'codex-turn-replay-retry-aborted',
),
).toBe(true);
expect(
@@ -8036,7 +8305,13 @@ describe('CodexAgent MCP thread context hooks', () => {
controller.abort();
await vi.advanceTimersByTimeAsync(0);
const after = events.slice(before);
- expect(after.filter((e) => e.type === 'error' && e.data?.isTerminal === true)).toHaveLength(1);
+ const terminalAfterSignal = after.filter(
+ (e) => e.type === 'error' && e.data?.isTerminal === true,
+ );
+ expect(terminalAfterSignal).toHaveLength(1);
+ expect(terminalAfterSignal[0].data).toMatchObject({
+ reason: 'codex-turn-replay-retry-cancelled',
+ });
expect(after.some((e) => e.type === 'status' && e.data?.isRunning === false)).toBe(true);
expect(handle.isTurnRunning?.()).toBe(false);
@@ -9354,7 +9629,7 @@ describe('CodexAgent MCP thread context hooks', () => {
);
expect(terminalAfterAbort).toHaveLength(1);
expect(terminalAfterAbort[0].data).toMatchObject({
- reason: 'codex-overload-retry-aborted',
+ reason: 'codex-turn-replay-retry-aborted',
});
// 随后在途的重投 RPC 失败:**不得**再补第二条 terminal error / Done。
diff --git a/packages/maker-core/src/agents/codex/index.ts b/packages/maker-core/src/agents/codex/index.ts
index 6fe344cfb1..a79d410a9e 100644
--- a/packages/maker-core/src/agents/codex/index.ts
+++ b/packages/maker-core/src/agents/codex/index.ts
@@ -122,6 +122,11 @@ import { parseReconnectAttemptMessage } from '../shared/network-error.js';
import { extractNonSecretErrorSignals } from '@cindy/maker-shared/error-redaction';
import { AppServerHost, type ThreadEventHandlers, type ThreadSubscription } from './app-server/host.js';
import { AppServerRequestTimeoutError } from './app-server/client.js';
+import {
+ isTerminalRateLimitRetryExhaustion,
+ TERMINAL_RATE_LIMIT_RETRY_MAX_ATTEMPTS,
+ terminalRateLimitRetryDelayMs,
+} from './terminal-rate-limit-retry.js';
import { createStdioTransport } from './app-server/stdioTransport.js';
import { CodexInteractionBroker } from './interaction-broker.js';
import { SYSTEM_PROMPT_APPEND as MAKER_CODEX_SYSTEM_PROMPT_APPEND } from './system-prompt-append.js';
@@ -186,6 +191,24 @@ import {
type UserInput,
} from './app-server/protocol.js';
+interface TurnReplayRetryPolicy {
+ kind: 'capacity' | 'terminal-rate-limit';
+ maxAttempts: number;
+ delayMs: (attempt: number) => number;
+}
+
+const CAPACITY_RETRY_POLICY: TurnReplayRetryPolicy = {
+ kind: 'capacity',
+ maxAttempts: OVERLOAD_RETRY_MAX_ATTEMPTS,
+ delayMs: overloadRetryDelayMs,
+};
+
+const TERMINAL_RATE_LIMIT_RETRY_POLICY: TurnReplayRetryPolicy = {
+ kind: 'terminal-rate-limit',
+ maxAttempts: TERMINAL_RATE_LIMIT_RETRY_MAX_ATTEMPTS,
+ delayMs: terminalRateLimitRetryDelayMs,
+};
+
type CodexEffort = 'minimal' | 'low' | 'medium' | 'high' | 'xhigh' | 'max' | 'ultra';
const CODEX_MINIMAL_EFFORT_MODELS = new Set([
@@ -2429,7 +2452,7 @@ export class CodexAgent extends BaseAgent {
* 回包(那要按"有产出"处理), 标量写的是**当前**这一轮的账 —— 而新一轮的 turnStarted 若
* 进过缓冲或作为同 turn 通知到达, 都不会把它清掉, 于是新消息一次本来安全的零产出容量
* 重投被误判成"有产出, 不重投", 自动重试静默失效(review #844 codex P1)。
- * 每个写入方都拿得到自己的 turnId, 读取方(scheduleOverloadRetry)拿得到死 turn 的 id,
+ * 每个写入方都拿得到自己的 turnId, 读取方(scheduleTurnReplayRetry)拿得到死 turn 的 id,
* 按 id 记账后跨轮污染在结构上就不成立, 也不再需要"换 turn 才清零"这类时序守卫。
*/
const producedOutputTurnIds = new Set<string>();
@@ -2440,6 +2463,12 @@ export class CodexAgent extends BaseAgent {
*/
let overloadRetry: {
retry: () => Promise<void>;
+ /**
+ * 同一 logical send 已消耗的外层重放次数,所有 provider failure policy 共享。
+ * policy 切换不重置:否则 capacity 4 次 + terminal-rate-limit 2 次会把同一条
+ * 用户输入最多重放 6 次,扩大请求量与重复副作用风险。各 policy 的
+ * maxAttempts 是它愿意接受的**总重放上限**,不是独立配额。
+ */
attempt: number;
/** 同一逻辑 send 最多接管一次 WS→HTTP body recovery,避免坏响应形成重投环。 */
httpRecoveryRetryAttempted: boolean;
@@ -6413,7 +6442,7 @@ export class CodexAgent extends BaseAgent {
/**
* 彻底废弃当前的重投状态:清计时器、摘 signal 监听、置空引用。
*
- * 与 cancelOverloadRetry 的分工:后者只清计时器(scheduleOverloadRetry 排新档
+ * 与 cancelOverloadRetry 的分工:后者只清计时器(scheduleTurnReplayRetry 排新档
* 前的 'superseded' 就靠它,那时状态本身还要继续用)。凡是**状态整体作废**的地方
* 都必须走这个,否则 signal 的 abort 监听会残留在一个已废弃的闭包上。
*/
@@ -6616,9 +6645,9 @@ export class CodexAgent extends BaseAgent {
eventQueue.push({
type: 'error',
data: {
- message: 'Codex turn cancelled while waiting to retry a model-capacity failure',
+ message: 'Codex turn cancelled while waiting for an automatic retry',
isTerminal: true,
- reason: 'codex-overload-retry-cancelled',
+ reason: 'codex-turn-replay-retry-cancelled',
},
source: 'codex',
});
@@ -6630,24 +6659,27 @@ export class CodexAgent extends BaseAgent {
};
/**
- * 服务过载退避重投调度。
+ * 零产出 provider 终态错误的退避重投调度。
*
* 返回进度表示已接管本次错误,**调用方必须跳过终态收口**(不推 terminal
* error、不推 Done status)——否则 UI 会先收口成失败再重投,用户看到一次假
* 失败闪烁,非交互入口更会直接把这一轮判死。返回 null 表示不接管,按原
* 终止路径报错。
*
- * 为什么必须由我们重投:`Selected model is at capacity` 是模型服务槽位不足,
+ * capacity 必须由我们重投:`Selected model is at capacity` 是模型服务槽位不足,
* OpenAI 侧不做任何重试就把 turn 判死(openai/codex#22390 请求 backoff 重试
* 至今 open),用户只能手动再发一次。这类抖动通常几秒内自愈,正是客户端该
* 兜住的部分。
+ * terminal-rate-limit 则只接 daemon 已明确耗尽自身 retry budget 的 429,再给
+ * 两次较长退避;仍在 willRetry 的 429 与账号额度耗尽都不会进入本函数。
*
* 为什么不自动换模型:容量故障往往横扫同一模型的所有 effort 档
* (2026-06-16 那次 medium/high/xhigh 全线不可用),换档无效;而换模型会
* 悄悄改变输出的判断风格,属于隐蔽的质量变更。降级留给用户显式选择。
*/
- const scheduleOverloadRetry = (
+ const scheduleTurnReplayRetry = (
deadTurnId: string | null,
+ policy: TurnReplayRetryPolicy = CAPACITY_RETRY_POLICY,
): { attempt: number; maxAttempts: number } | null => {
const state = overloadRetry;
if (!state || closed) return null;
@@ -6670,7 +6702,8 @@ export class CodexAgent extends BaseAgent {
// 两件事一起做才与 settleCancelledOverloadRetry 同构(它也是 mark + quarantine)。
markInFlightStartsTerminallySettled();
quarantineAllInFlightStarts();
- log.info('codex not taking over a capacity failure for an already-cancelled send', {
+ log.info('codex not taking over a replayable failure for an already-cancelled send', {
+ kind: policy.kind,
quarantinedStarts: inFlightStarts.size,
threadId,
});
@@ -6682,7 +6715,8 @@ export class CodexAgent extends BaseAgent {
// 的新 turn 落墓碑并重放它的输入 → 副作用执行两遍(review #844 codex P1)。
// 这里选择不接管: 代价只是这一轮要用户自己再发一次, 而错误的一侧是重复副作用。
if (!deadTurnId && inFlightStarts.size > 1) {
- log.warn('codex id-less capacity failure not attributable — declining takeover', {
+ log.warn('codex id-less replayable failure not attributable — declining takeover', {
+ kind: policy.kind,
inFlightStarts: inFlightStarts.size,
threadId,
});
@@ -6702,7 +6736,8 @@ export class CodexAgent extends BaseAgent {
// 名下(全被 stale 闸或缓冲挡住)。缓冲事件那种"看不见的产出"由
// adoptUnidentifiedDeadTurn 在响应回来、id 已知时补记, 补排再查一次就拦住了。
if (deadTurnId && producedOutputTurnIds.has(deadTurnId)) {
- log.info('codex overload error after partial output — not auto-retrying', {
+ log.info('codex replayable error after partial output — not auto-retrying', {
+ kind: policy.kind,
threadId,
deadTurnId,
inFlight: state.inFlight,
@@ -6714,6 +6749,17 @@ export class CodexAgent extends BaseAgent {
// 的工具副作用就会执行两遍(review #844 codex P1)。在途那次自己会走完
// 成功/失败路径,届时若仍缺容量会重新进入本函数。
if (inFlightStarts.size > 0) {
+ // terminal 429 只在 turn 身份已经明确、没有其它 start 在途时接管。容量拒绝
+ // 才有完整的空 id / started-before-response 对账协议;把 429 塞进那套延后
+ // 状态会扩大错误归属面,猜错就可能重放已经执行过工具的 turn。
+ if (policy.kind !== 'capacity') {
+ log.warn('codex terminal rate-limit retry declined while turn/start is pending', {
+ inFlightStarts: inFlightStarts.size,
+ threadId,
+ deadTurnId,
+ });
+ return null;
+ }
// 关键:**不能返回 null**。null 会让 translator 把这条错误报成终态,把逻辑
// turn 判死(review #844 codex P1),而在途那次 RPC 随后还可能成功并激活
// turn —— UI 已收口。这里返回当前进度:错误照样透成非终止状态(UI 继续显示
@@ -6736,7 +6782,8 @@ export class CodexAgent extends BaseAgent {
isTurnInFlight = false;
currentTurnId = null;
}
- log.info('codex overload retry already in flight — deferring this failure to it', {
+ log.info('codex turn replay retry already in flight — deferring this failure to it', {
+ kind: policy.kind,
attempt: state.attempt,
threadId,
deadTurnId,
@@ -6745,11 +6792,14 @@ export class CodexAgent extends BaseAgent {
// 延后的这条失败补排时会消耗第 1 档,所以下限取 1。
return {
attempt: Math.max(1, state.attempt),
- maxAttempts: OVERLOAD_RETRY_MAX_ATTEMPTS,
+ maxAttempts: policy.maxAttempts,
};
}
- if (state.attempt >= OVERLOAD_RETRY_MAX_ATTEMPTS) {
- log.warn('codex overload retry budget exhausted — surfacing terminal error', {
+ // attempt 是 logical send 级共享预算,不按 failure kind 分桶。混合故障时沿用
+ // 已消耗次数,保证策略切换不会续满另一份外层重放额度。
+ if (state.attempt >= policy.maxAttempts) {
+ log.warn('codex turn replay retry budget exhausted — surfacing terminal error', {
+ kind: policy.kind,
attempts: state.attempt,
threadId,
});
@@ -6759,7 +6809,7 @@ export class CodexAgent extends BaseAgent {
cancelOverloadRetry('superseded');
const attempt = state.attempt + 1;
state.attempt = attempt;
- const delayMs = overloadRetryDelayMs(attempt);
+ const delayMs = policy.delayMs(attempt);
// 该 turn 在 app-server 侧确实已经死了:它挂起的审批 / user-input 必须清掉,
// 否则重投出来的新 turn 会与旧 turn 的悬空交互混在一起。
if (deadTurnId) {
@@ -6774,9 +6824,10 @@ export class CodexAgent extends BaseAgent {
stopActiveRolloutPlanFallback();
isTurnInFlight = false;
currentTurnId = null;
- log.info('codex model at capacity — scheduling turn/start retry', {
+ log.info('codex replayable provider failure — scheduling turn/start retry', {
+ kind: policy.kind,
attempt,
- maxAttempts: OVERLOAD_RETRY_MAX_ATTEMPTS,
+ maxAttempts: policy.maxAttempts,
delayMs,
threadId,
deadTurnId,
@@ -6837,7 +6888,7 @@ export class CodexAgent extends BaseAgent {
});
});
}, delayMs);
- return { attempt, maxAttempts: OVERLOAD_RETRY_MAX_ATTEMPTS };
+ return { attempt, maxAttempts: policy.maxAttempts };
};
/**
@@ -6953,7 +7004,7 @@ export class CodexAgent extends BaseAgent {
// 否则又回到"两个 start 并存"的形状(review #844 codex P1)。
if (inFlightStarts.size > 0) return;
state.deferredCapacityFailure = null;
- if (scheduleOverloadRetry(deferred.deadTurnId)) return;
+ if (scheduleTurnReplayRetry(deferred.deadTurnId)) return;
log.warn('codex deferred capacity failure exhausted the retry budget', {
attempt: state.attempt,
threadId,
@@ -7400,7 +7451,7 @@ export class CodexAgent extends BaseAgent {
// 告诉你是哪个 turn", 也就是容量在 admission 阶段被拒。活跃 turn 的 turn/start 若已
// 经回包, 它早就过了 admission —— 之后真为它发的容量错误一定带得上 turnId。所以此时
// 的空 id 通知只可能来自别处(最典型: 被 Stop 的旧 send, 它的 turn id 我们从没学到),
- // 认在活跃 turn 头上的后果是: scheduleOverloadRetry 拿 currentTurnId 当死 turn, 把一
+ // 认在活跃 turn 头上的后果是: scheduleTurnReplayRetry 拿 currentTurnId 当死 turn, 把一
// 个正常在跑的 turn 落墓碑、撤销重投、推 Done, 而 server 侧那个 turn 还在执行工具
// (review #844 codex/greptile P1)。
//
@@ -7534,7 +7585,7 @@ export class CodexAgent extends BaseAgent {
}
// 服务过载(模型容量不足)时接管重投:translator 命中 capacity 才回调,
// 拿到进度就把错误透成非终止状态,本函数随后跳过 Done 收口。
- let overloadRetryScheduled = false;
+ let turnReplayRetryScheduled = false;
translateErrorNotification(effectiveParams, eventQueue, {
rt: translatorRt,
log,
@@ -7543,15 +7594,39 @@ export class CodexAgent extends BaseAgent {
// TurnRetryTracker 把持续 retry 升级成终态的那条路径不接管:那说明
// daemon 已经重试很久仍不行,我们再叠一层退避重投属于双层重试。
if (params.willRetry === true) return null;
- const progress = scheduleOverloadRetry(effectiveParams.turnId || currentTurnId);
- if (progress) overloadRetryScheduled = true;
+ const progress = scheduleTurnReplayRetry(effectiveParams.turnId || currentTurnId);
+ if (progress) turnReplayRetryScheduled = true;
+ return progress;
+ },
+ tryTakeOverTerminalRateLimit: () => {
+ // willRetry=true 仍归 daemon 自己退避,绝不叠第二层。这里只接它已经明确
+ // 耗尽内部 retry budget 的终态 429;usageLimitExceeded 由判定器排除。
+ if (params.willRetry === true) return null;
+ const rawMessage = effectiveParams.error?.message ?? '';
+ const signals = extractNonSecretErrorSignals(rawMessage);
+ if (
+ !isTerminalRateLimitRetryExhaustion(
+ rawMessage,
+ signals.errorStatus,
+ effectiveParams.error?.codexErrorInfo,
+ )
+ ) {
+ return null;
+ }
+ const deadTurnId = effectiveParams.turnId || currentTurnId;
+ if (!deadTurnId || inFlightStarts.size > 0) return null;
+ const progress = scheduleTurnReplayRetry(
+ deadTurnId,
+ TERMINAL_RATE_LIMIT_RETRY_POLICY,
+ );
+ if (progress) turnReplayRetryScheduled = true;
return progress;
},
});
// 与 translator 的 terminal 判定保持一致:willRetry=false 或缺省都视为终态。
if (!isTerminalError) return;
const terminalTurnId = effectiveParams.turnId || currentTurnId;
- if (overloadRetryScheduled) {
+ if (turnReplayRetryScheduled) {
// 死掉的 turn **必须**落墓碑:app-server 随后还会为它发正常的
// turn/completed(failed),没有墓碑 handleTurnCompleted 就会 emit terminal
// error + done,把 UI 与 goal turn 直接收口,我们刚透出的非终止重试状态
@@ -8526,7 +8601,7 @@ export class CodexAgent extends BaseAgent {
data: {
message: 'Codex turn stopped while waiting for an automatic retry',
isTerminal: true,
- reason: 'codex-overload-retry-aborted',
+ reason: 'codex-turn-replay-retry-aborted',
},
source: 'codex',
});
diff --git a/packages/maker-core/src/agents/codex/terminal-rate-limit-retry.test.ts b/packages/maker-core/src/agents/codex/terminal-rate-limit-retry.test.ts
new file mode 100644
index 0000000000..32fe5fcc09
--- /dev/null
+++ b/packages/maker-core/src/agents/codex/terminal-rate-limit-retry.test.ts
@@ -0,0 +1,164 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ formatTerminalRateLimitRetryMessage,
+ isTerminalRateLimitRetryExhaustion,
+ parseTerminalRateLimitRetryProgress,
+ TERMINAL_RATE_LIMIT_RETRY_REASON,
+ terminalRateLimitRetryDelayMs,
+} from './terminal-rate-limit-retry.js';
+
+describe('terminal rate-limit retry', () => {
+ it('recognizes structured exhausted retries whose final response is 429', () => {
+ expect(
+ isTerminalRateLimitRetryExhaustion(
+ 'provider retries exhausted',
+ undefined,
+ { responseTooManyFailedAttempts: { httpStatusCode: 429 } },
+ ),
+ ).toBe(true);
+ expect(
+ isTerminalRateLimitRetryExhaustion(
+ 'retry budget exhausted',
+ undefined,
+ { responseTooManyFailedAttempts: { httpStatusCode: 429 } },
+ ),
+ ).toBe(true);
+ expect(
+ isTerminalRateLimitRetryExhaustion(
+ 'exceeded retry limit, retry budget exceeded, last status: 429',
+ undefined,
+ { responseTooManyFailedAttempts: { httpStatusCode: 429 } },
+ ),
+ ).toBe(true);
+ });
+
+ it('recognizes the legacy text fallback only when it also carries status 429', () => {
+ expect(
+ isTerminalRateLimitRetryExhaustion(
+ 'exceeded retry limit, last status: 429 Too Many Requests',
+ 429,
+ undefined,
+ ),
+ ).toBe(true);
+ expect(
+ isTerminalRateLimitRetryExhaustion(
+ 'exceeded retry limit, last status: 503 Service Unavailable',
+ undefined,
+ undefined,
+ ),
+ ).toBe(false);
+ expect(
+ isTerminalRateLimitRetryExhaustion(
+ 'exceeded retry limit, retry budget exhausted, last status: 429',
+ 429,
+ undefined,
+ ),
+ ).toBe(true);
+ });
+
+ it('does not short-retry account usage limits', () => {
+ expect(
+ isTerminalRateLimitRetryExhaustion(
+ 'exceeded retry limit, last status: 429 Too Many Requests',
+ 429,
+ 'usageLimitExceeded',
+ ),
+ ).toBe(false);
+ expect(
+ isTerminalRateLimitRetryExhaustion(
+ 'exceeded retry limit, last status: 429 Too Many Requests',
+ 429,
+ 'sessionBudgetExceeded',
+ ),
+ ).toBe(false);
+ expect(
+ isTerminalRateLimitRetryExhaustion(
+ 'exceeded retry limit, quota exhausted, status: 429',
+ 429,
+ undefined,
+ ),
+ ).toBe(false);
+ expect(
+ isTerminalRateLimitRetryExhaustion(
+ 'exceeded retry limit, last status: 429: You exceeded your current quota',
+ 429,
+ undefined,
+ ),
+ ).toBe(false);
+ expect(
+ isTerminalRateLimitRetryExhaustion(
+ 'exceeded retry limit, last status: 429: Your quota has been exceeded',
+ 429,
+ undefined,
+ ),
+ ).toBe(false);
+ expect(
+ isTerminalRateLimitRetryExhaustion(
+ 'exceeded retry limit, last status: 429: insufficient credit balance',
+ 429,
+ undefined,
+ ),
+ ).toBe(false);
+ expect(
+ isTerminalRateLimitRetryExhaustion(
+ 'exceeded retry limit, last status: 429: ExceededBudget',
+ 429,
+ undefined,
+ ),
+ ).toBe(false);
+ });
+
+ it('does not retry a plain terminal 429 or a non-429 exhausted response', () => {
+ expect(
+ isTerminalRateLimitRetryExhaustion(
+ 'HTTP status: 429 Too Many Requests',
+ 429,
+ undefined,
+ ),
+ ).toBe(false);
+ expect(
+ isTerminalRateLimitRetryExhaustion(
+ 'provider retries exhausted',
+ undefined,
+ { responseTooManyFailedAttempts: { httpStatusCode: 500 } },
+ ),
+ ).toBe(false);
+ });
+
+ it('uses bounded jittered 15s and 30s delays', () => {
+ expect(terminalRateLimitRetryDelayMs(1, () => 0.5)).toBe(15_000);
+ expect(terminalRateLimitRetryDelayMs(2, () => 0.5)).toBe(30_000);
+ expect(terminalRateLimitRetryDelayMs(2, () => 0)).toBe(22_500);
+ expect(terminalRateLimitRetryDelayMs(2, () => 0.999999)).toBe(30_000);
+ });
+
+ it('uses a dedicated reason and progress marker instead of the overload contract', () => {
+ expect(TERMINAL_RATE_LIMIT_RETRY_REASON).toBe('terminal-rate-limit-retry');
+ expect(
+ formatTerminalRateLimitRetryMessage(
+ 'exceeded retry limit, last status: 429 Too Many Requests',
+ 1,
+ 2,
+ ),
+ ).toBe(
+ 'exceeded retry limit, last status: 429 Too Many Requests (rate-limit-retry 1/2)',
+ );
+ expect(
+ parseTerminalRateLimitRetryProgress(
+ 'exceeded retry limit, last status: 429 Too Many Requests (rate-limit-retry 1/2)',
+ TERMINAL_RATE_LIMIT_RETRY_REASON,
+ ),
+ ).toEqual({ attempt: 1, maxAttempts: 2 });
+ });
+
+ it.each([
+ ['provider failed (rate-limit-retry 1/2)', 'other-reason'],
+ ['provider failed', TERMINAL_RATE_LIMIT_RETRY_REASON],
+ ['provider failed (rate-limit-retry 0/2)', TERMINAL_RATE_LIMIT_RETRY_REASON],
+ ['provider failed (rate-limit-retry 3/2)', TERMINAL_RATE_LIMIT_RETRY_REASON],
+ ['provider failed (rate-limit-retry 1/2) trailing', TERMINAL_RATE_LIMIT_RETRY_REASON],
+ ])('rejects malformed or mismatched progress: %s', (message, reason) => {
+ expect(parseTerminalRateLimitRetryProgress(message, reason)).toBeNull();
+ });
+});
diff --git a/packages/maker-core/src/agents/codex/terminal-rate-limit-retry.ts b/packages/maker-core/src/agents/codex/terminal-rate-limit-retry.ts
new file mode 100644
index 0000000000..ad5065ad5e
--- /dev/null
+++ b/packages/maker-core/src/agents/codex/terminal-rate-limit-retry.ts
@@ -0,0 +1,104 @@
+import { matchesDeterministicUsageExhaustionText } from '@cindy/maker-shared/error-redaction';
+
+import {
+ codexErrorInfoTag,
+ type CodexErrorInfo,
+} from './app-server/protocol.js';
+
+/** Cindy 只在 daemon 自己的 retry budget 已耗尽后,再给短时 429 两次外层机会。 */
+export const TERMINAL_RATE_LIMIT_RETRY_MAX_ATTEMPTS = 2;
+/** 终态 429 外层重投的稳定 reason key;Desktop / Mobile 镜像同值。 */
+export const TERMINAL_RATE_LIMIT_RETRY_REASON = 'terminal-rate-limit-retry';
+
+const TERMINAL_RATE_LIMIT_RETRY_BASE_DELAY_MS = 15_000;
+const TERMINAL_RATE_LIMIT_RETRY_MAX_DELAY_MS = 30_000;
+const TERMINAL_RATE_LIMIT_RETRY_JITTER_RATIO = 0.25;
+const TERMINAL_RATE_LIMIT_RETRY_PROGRESS_RE =
+ /\(rate-limit-retry\s+(\d+)\s*\/\s*(\d+)\)\s*$/;
+
+const RETRY_LIMIT_EXHAUSTED_PATTERN =
+ /\b(?:exceeded\s+(?:the\s+)?retry\s+limit|retry\s+limit\s+exceeded|too\s+many\s+failed\s+attempts)\b/i;
+
+/** reason 与 marker 同时命中时,解析终态 429 外层重投进度。 */
+export function parseTerminalRateLimitRetryProgress(
+ message: string,
+ reason?: string | null,
+): { attempt: number; maxAttempts: number } | null {
+ if (reason !== TERMINAL_RATE_LIMIT_RETRY_REASON) return null;
+ const match = TERMINAL_RATE_LIMIT_RETRY_PROGRESS_RE.exec(message);
+ if (!match) return null;
+ const attempt = Number(match[1]);
+ const maxAttempts = Number(match[2]);
+ if (
+ !Number.isSafeInteger(attempt) ||
+ !Number.isSafeInteger(maxAttempts) ||
+ attempt < 1 ||
+ maxAttempts < attempt
+ ) {
+ return null;
+ }
+ return { attempt, maxAttempts };
+}
+
+function responseTooManyFailedAttemptsStatus(
+ info: CodexErrorInfo | null | undefined,
+): number | undefined {
+ if (!info || typeof info !== 'object' || Array.isArray(info)) return undefined;
+ if (!('responseTooManyFailedAttempts' in info)) return undefined;
+ const detail = info.responseTooManyFailedAttempts;
+ return typeof detail?.httpStatusCode === 'number'
+ ? detail.httpStatusCode
+ : undefined;
+}
+
+/**
+ * 是否是「daemon 已结束内部重试,最后一次仍为 429」的终态错误。
+ *
+ * `usageLimitExceeded` 是账号/套餐周期额度,短退避没有意义;即使文案也带 429,
+ * 仍必须排除。老 daemon 没有结构化 tag 时,只接受明确的 retry-budget 耗尽文案,
+ * 避免把普通 quota / rate-limit 错误一概重放。
+ */
+export function isTerminalRateLimitRetryExhaustion(
+ message: string,
+ errorStatus: number | undefined,
+ info: CodexErrorInfo | null | undefined,
+): boolean {
+ const tag = codexErrorInfoTag(info);
+ if (tag === 'usageLimitExceeded' || tag === 'sessionBudgetExceeded') return false;
+ if (matchesDeterministicUsageExhaustionText(message)) {
+ return false;
+ }
+ const status = responseTooManyFailedAttemptsStatus(info) ?? errorStatus;
+ if (status !== 429) return false;
+ return (
+ tag === 'responseTooManyFailedAttempts' ||
+ RETRY_LIMIT_EXHAUSTED_PATTERN.test(message)
+ );
+}
+
+/** 第 attempt 次外层重投前的退避:15s、30s,带 ±25% jitter,单次不超过 30s。 */
+export function terminalRateLimitRetryDelayMs(
+ attempt: number,
+ random: () => number = Math.random,
+): number {
+ const exponent = Math.max(0, attempt - 1);
+ const base = Math.min(
+ TERMINAL_RATE_LIMIT_RETRY_BASE_DELAY_MS * 2 ** exponent,
+ TERMINAL_RATE_LIMIT_RETRY_MAX_DELAY_MS,
+ );
+ const factor =
+ 1 + (random() * 2 - 1) * TERMINAL_RATE_LIMIT_RETRY_JITTER_RATIO;
+ return Math.min(
+ Math.round(base * factor),
+ TERMINAL_RATE_LIMIT_RETRY_MAX_DELAY_MS,
+ );
+}
+
+/** 给终态 429 原文追加独立进度后缀,避免被下游误判成模型容量过载。 */
+export function formatTerminalRateLimitRetryMessage(
+ message: string,
+ attempt: number,
+ maxAttempts: number,
+): string {
+ return `${message} (rate-limit-retry ${attempt}/${maxAttempts})`;
+}
diff --git a/packages/maker-core/src/agents/codex/translator.test.ts b/packages/maker-core/src/agents/codex/translator.test.ts
index 47ef571007..ba3b9a5533 100644
--- a/packages/maker-core/src/agents/codex/translator.test.ts
+++ b/packages/maker-core/src/agents/codex/translator.test.ts
@@ -437,6 +437,34 @@ describe('translateErrorNotification', () => {
});
});
+ it('终态 429 被 agent 接管时透成非终止限流进度且不冒充过载', async () => {
+ const rt = newCodexRuntimeState();
+ const q = createAsyncQueue<AgentEvent>();
+ translateErrorNotification(
+ makeParams({
+ willRetry: false,
+ message: 'exceeded retry limit, last status: 429 Too Many Requests',
+ }),
+ q,
+ {
+ ...makeCtx(rt),
+ tryTakeOverTerminalRateLimit: () => ({ attempt: 1, maxAttempts: 2 }),
+ },
+ );
+ const events = await collect(q);
+ expect(events).toHaveLength(1);
+ expect(events[0]!.data).toMatchObject({
+ errorStatus: 429,
+ isTerminal: false,
+ willRetry: true,
+ reason: 'terminal-rate-limit-retry',
+ });
+ expect((events[0]!.data as { message: string }).message).toContain(
+ 'rate-limit-retry 1/2',
+ );
+ expect((events[0]!.data as { message: string }).message).not.toContain('auto-retry');
+ });
+
it('容量拒绝改了文案措辞时,结构化 tag 仍触发接管重投', async () => {
// 本用例锁的是这次改动的核心目标: 重投不再依赖 codex 的英文文案。
// message 故意完全不含 "at capacity" —— 模拟 codex 升级改了措辞。若判定回退到
diff --git a/packages/maker-core/src/agents/codex/translator.ts b/packages/maker-core/src/agents/codex/translator.ts
index 0103c155e4..f24bb3011c 100644
--- a/packages/maker-core/src/agents/codex/translator.ts
+++ b/packages/maker-core/src/agents/codex/translator.ts
@@ -47,6 +47,10 @@ import {
} from '../shared/context-overflow-error.js';
import { commandExecutionDisplayInput, type CommandExecutionDisplayInput } from './command-display.js';
import { codexErrorInfoTag } from './app-server/protocol.js';
+import {
+ formatTerminalRateLimitRetryMessage,
+ TERMINAL_RATE_LIMIT_RETRY_REASON,
+} from './terminal-rate-limit-retry.js';
import type {
ItemCompletedNotification,
ItemStartedNotification,
@@ -137,6 +141,14 @@ export interface CodexTranslateContext {
* 会话是否已关), 而错误脱敏与 error 事件构造在 translator。缺省 = 不接管。
*/
tryTakeOverOverload?: () => { attempt: number; maxAttempts: number } | null;
+ /**
+ * daemon 已耗尽内部 retry budget 的终态 429 接管钩子。agent 层负责严格分类、
+ * turn 归属、产出守卫与预算;translator 只编码独立 reason / 进度契约。
+ */
+ tryTakeOverTerminalRateLimit?: () => {
+ attempt: number;
+ maxAttempts: number;
+ } | null;
}
// ── 主入口: 三个 item.* notification 的统一分发 ────────────────────────────────
@@ -371,6 +383,27 @@ export function translateErrorNotification(
return;
}
}
+ if (!params.willRetry && !isCapacityError) {
+ const progress = ctx.tryTakeOverTerminalRateLimit?.();
+ if (progress) {
+ queue.push({
+ type: 'error',
+ data: {
+ ...safeErrorData,
+ reason: TERMINAL_RATE_LIMIT_RETRY_REASON,
+ message: formatTerminalRateLimitRetryMessage(
+ safeMessage,
+ progress.attempt,
+ progress.maxAttempts,
+ ),
+ isTerminal: false,
+ willRetry: true,
+ },
+ source: 'codex',
+ });
+ return;
+ }
+ }
ctx.log.warn('codex turn error', { message: safeMessage, willRetry: params.willRetry, isAuthMissing, threadId: params.threadId, turnId: params.turnId });
queue.push({
type: 'error',
diff --git a/packages/maker-core/src/agents/index.ts b/packages/maker-core/src/agents/index.ts
index 19aabd75a4..9bfba72c66 100644
--- a/packages/maker-core/src/agents/index.ts
+++ b/packages/maker-core/src/agents/index.ts
@@ -48,6 +48,12 @@ export {
type OverloadError,
type OverloadErrorKind,
} from './shared/overload-error.js';
+// Desktop main 的 IM / hook 渠道与 maker-core 同 bundle,直接复用终态 429 的
+// reason + marker 解析契约,避免渠道侧再维护一份正则。
+export {
+ TERMINAL_RATE_LIMIT_RETRY_REASON,
+ parseTerminalRateLimitRetryProgress,
+} from './codex/terminal-rate-limit-retry.js';
// 同上理由(同 bundle 直接复用): desktop main 的错误投影 / IM 渠道要认「上下文超限」
// 这一类 —— 原样重试必败, 恢复动作是压缩上下文或新开会话, 与过载 / 网络类的自动
// 重试语义相反。详见 shared/context-overflow-error.ts 的模块注释(#1429)。
diff --git a/packages/maker-shared/src/errorRedaction.test.ts b/packages/maker-shared/src/errorRedaction.test.ts
index 4b416a67e4..5e89117594 100644
--- a/packages/maker-shared/src/errorRedaction.test.ts
+++ b/packages/maker-shared/src/errorRedaction.test.ts
@@ -2,9 +2,46 @@ import { describe, expect, it } from 'vitest';
import {
extractNonSecretErrorSignals,
+ matchesDeterministicUsageExhaustionText,
redactSensitiveText,
} from './errorRedaction.js';
+describe('matchesDeterministicUsageExhaustionText', () => {
+ it.each([
+ 'insufficient_quota',
+ 'insufficient credit balance',
+ 'insufficient balance',
+ 'insufficient funds',
+ 'quota exhausted for this key',
+ 'Your quota has been exceeded',
+ 'You exceeded your current quota',
+ 'usage limit',
+ 'account budget exhausted',
+ 'session budget exhausted',
+ 'usage budget has been exceeded',
+ 'ExceededBudget',
+ 'budget_exceeded',
+ 'exceeded_budget',
+ '账户余额不足,请充值',
+ '账户欠费',
+ ])('recognizes deterministic usage exhaustion: %s', (message) => {
+ expect(matchesDeterministicUsageExhaustionText(message)).toBe(true);
+ });
+
+ it.each([
+ '429',
+ 'HTTP 429 Too Many Requests',
+ 'Too Many Requests',
+ 'rate limit exceeded',
+ 'retry budget exhausted',
+ 'retry budget exceeded',
+ 'exhausted daemon retry budget',
+ 'exceeded retry limit, last status: 429 Too Many Requests',
+ ])('does not treat transient or retry exhaustion as usage exhaustion: %s', (message) => {
+ expect(matchesDeterministicUsageExhaustionText(message)).toBe(false);
+ });
+});
+
describe('redactSensitiveText', () => {
it('redacts LiteLLM credential fields and bearer tokens while preserving context', () => {
const input =
diff --git a/packages/maker-shared/src/errorRedaction.ts b/packages/maker-shared/src/errorRedaction.ts
index 40b75a5706..47883d66c1 100644
--- a/packages/maker-shared/src/errorRedaction.ts
+++ b/packages/maker-shared/src/errorRedaction.ts
@@ -43,6 +43,28 @@ export interface NonSecretErrorSignals {
usageLimit: boolean;
}
+const DETERMINISTIC_USAGE_EXHAUSTION_PATTERNS = [
+ /\binsufficient[-_ ]?quota\b/i,
+ /\binsufficient.{0,12}\b(?:balance|credit|funds)\b/i,
+ /\bquota\b.{0,24}\b(?:exhausted|exceeded)\b/i,
+ /\b(?:exhausted|exceeded)\b.{0,24}\bquota\b/i,
+ /\busage\s+limit\b/i,
+ /\b(?:exceeded[-_]?budget|budget[-_]?exceeded)\b/i,
+ /\b(?:account|session|usage)\s+budget\b.{0,16}\b(?:exhausted|exceeded)\b/i,
+ /\b(?:exhausted|exceeded)\b.{0,16}\b(?:account|session|usage)\s+budget\b/i,
+ /余额不足|欠费/i,
+];
+
+/**
+ * Match only explicit account/quota/budget exhaustion text whose recovery
+ * requires more capacity or a reset. Unlike `usageLimit` below, this strict
+ * signal deliberately excludes transient rate limiting (`429`, `Too Many
+ * Requests`, `rate limit`) and retry-budget exhaustion.
+ */
+export function matchesDeterministicUsageExhaustionText(input: string): boolean {
+ return DETERMINISTIC_USAGE_EXHAUSTION_PATTERNS.some((pattern) => pattern.test(input));
+}
+
/**
* Preserve explicit, non-secret routing signals before the surrounding error
* text is redacted. Requiring a field/phrase boundary avoids interpreting