Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins
TypeScript ai-agentcoding-agentdesktop-appelectronglobali18nlocal-firstmcppipi-agentpi-desktoppluginsreactrusttypescript
fix(agent-runtime): stop retrying exhausted billing quotas
vastsae8f413bcaf80
diff --git a/docs/adr/0091-rate-limit-same-turn-retry.md b/docs/adr/0091-rate-limit-same-turn-retry.mdindex fbc494c31..fa268cbe4 100644--- a/docs/adr/0091-rate-limit-same-turn-retry.md+++ b/docs/adr/0091-rate-limit-same-turn-retry.md@@ -7,8 +7,8 @@## Context-A provider HTTP 429 is transient, but it can happen both before a response is-established and after a stream has already started. The old implementation+A provider HTTP 429 caused by a transient rate limit can happen both before a+response is established and after a stream has already started. The old implementationsplit those cases between pi-ai's one setup retry and the runtime's onemid-stream replay. That exposed persistent but still-recoverable rate limits tothe user too early, and made the effective budget depend on which phase failed.diff --git a/docs/spec/03-runtime/02-agent-runtime.md b/docs/spec/03-runtime/02-agent-runtime.mdindex ff14d6526..124541051 100644--- a/docs/spec/03-runtime/02-agent-runtime.md+++ b/docs/spec/03-runtime/02-agent-runtime.md@@ -182,8 +182,9 @@ host-confirmed transition.### 5d. Bounded provider recovery and diagnostics (D186, D245, D259, D378, ADR 0091, ADR 0128, ADR 0206)Provider request setup and stream delivery are separate failure phases, but-HTTP 429 handling is one response-recovery policy. pi-ai's nested adapter retry is-disabled for this path so the runtime can share one budget across both phases.+throughput-limit HTTP 429s use one response-recovery policy. pi-ai's nested+adapter retry is disabled for this path so the runtime can share one budget+across both phases.`PROVIDER_RATE_LIMITED` receives at most ten retries after the initialattempt, for eleven provider attempts total. A setup 429 is retried inside the@@ -192,8 +193,10 @@ the next model context and calls `continue()` in the same turn. Both phasesclaim the same counter, so a setup 429 followed by a stream 429 cannot reset ormultiply the budget. The captured response status is applied before classifyingthe provider message in both phases, so a generic 429 body still enters the-429 budget while known non-retryable classifications remain terminal. The main-session and builtin subagents use the same controller and policy.+429 budget while known non-retryable classifications remain terminal. Explicit+billing/account exhaustion (including `insufficient_quota` and spend-limit+codes) is terminal `PROVIDER_ERROR` even with HTTP 429. The main session and+builtin subagents use the same controller and policy.429 retries are silent at the transcript lifecycle: no intermediate assistanterror, lifecycle `error`, `turn_end`, `agent_end`, or duplicate assistantdiff --git a/docs/spec/03-runtime/08-error-codes.md b/docs/spec/03-runtime/08-error-codes.mdindex d99f8b3a3..186a6b75e 100644--- a/docs/spec/03-runtime/08-error-codes.md+++ b/docs/spec/03-runtime/08-error-codes.md@@ -99,9 +99,9 @@ does not turn temporary thread pressure into a host process exit.| `AGENT_SIDECAR_CRASHED` | no | the Node agent sidecar process died mid-turn; the owning turn settles as aborted with this code instead of an unrelated plan-approval code (issue #1077) || `AGENT_SIDECAR_OOM` | no | the sidecar died after its JavaScript heap hit the configured cap, diagnosed from the V8 fatal-error banner in its stderr tail; the same turn fails the same way until the input shrinks (issue #1077) || `MODEL_NOT_CONFIGURED` | no | no usable model selected, or provider rejects the selected model as unknown |-| `PROVIDER_ERROR` | yes | upstream provider failure; a retryable one (5xx gateway) gets up to ten same-turn retries, while a malformed 400/422 request or a request option the adapter itself refuses (a custom `fetch` for the Google adapters, issue #1072) is terminal |+| `PROVIDER_ERROR` | yes | upstream provider failure; retryable 5xx gateway errors get up to ten same-turn retries, while malformed 400/422 requests, adapter-refused options, and explicit billing, credit, spend, usage, or disk exhaustion (including `insufficient_quota`) are terminal || `PROVIDER_UNAUTHORIZED` | no | bad/missing provider credentials |-| `PROVIDER_RATE_LIMITED` | yes | provider rate limited; runtime silently retries up to ten times across setup/stream before the terminal event |+| `PROVIDER_RATE_LIMITED` | yes | temporary provider throughput limit; runtime retries up to ten times across setup/stream. Explicit billing/account exhaustion remains terminal `PROVIDER_ERROR`, including when returned with HTTP 429 || `CONTEXT_TOO_LARGE` | no | prompt/context still exceeds the safe model budget after recovery, the second provider overflow occurred, or automatic recovery is disabled || `CONTEXT_COMPACTION_FAILED` | no | automatic retained-tail recovery could not prepare, persist, or fit a checkpoint, or manual checkpoint summary generation / durable append failed; the guarded next provider request does not start || `STREAM_FAILED` | yes | provider stream was terminated, closed prematurely, or otherwise ended before a complete response; up to ten same-turn retries may precede the terminal event |@@ -376,9 +376,12 @@ example DashScope/Qwen `Range of input length should be`, z.ai `Promptexceeds max length`, xAI `maximum prompt length is`, Groq, llama.cpp, andBedrock `Input is too long for requested model`. `CONTEXT_TOO_LARGE` is neverreplayed by either retry budget, and a delegate reports it as-`SUBAGENT_CONTEXT_OVERFLOW`. Rate-limit wording, including Bedrock's-`Throttling error: Too many tokens, please wait before trying again.`, is-classified first and stays `PROVIDER_RATE_LIMITED`.+`SUBAGENT_CONTEXT_OVERFLOW`. Explicit billing/account exhaustion codes and+messages (including `insufficient_quota`, `credit_balance_exhausted`, and+organization/project spend-limit codes) map to terminal `PROVIDER_ERROR` even+when the HTTP status is 429. Throughput rate-limit wording, including+Bedrock's `Throttling error: Too many tokens, please wait before trying again.`,+stays `PROVIDER_RATE_LIMITED`.An exact `terminated` provider message and equivalent premature stream-closemessages map to `STREAM_FAILED`. A message is `TURN_ABORTED` only for adiff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.mdindex d2bf1b3cd..81ede2370 100644--- a/docs/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/spec/06-delivery/04-e2e-test-plan.md@@ -7728,7 +7728,9 @@ must keep splitting are covered by `markdown-blocks.test.mjs`.succeed after a retry and can return eleven consecutive 429 responses. Fixturescover `retry-after-ms`, `retry-after` seconds, and HTTP-date headers, andsupport aborting during the wait. A builtin subagent uses a- fixture with the same responses.+ fixture with the same responses. Billing/account-exhaustion fixtures also+ return HTTP 429 with `insufficient_quota`, `credit_balance_exhausted`,+ organization usage-limit, and spend-limit codes.- **Steps**:1. Start an Agent turn with a setup-429 fixture whose next request succeeds.2. Repeat with a mid-stream-429 fixture whose next request succeeds.@@ -7741,11 +7743,18 @@ must keep splitting are covered by `markdown-blocks.test.mjs`.later provider request or terminal retry is started.7. Repeat with authentication, model-selection, malformed-request, andcontext-error fixtures.+ 8. Repeat with the billing/account-exhaustion 429 fixtures and inspect the+ terminal assistant error and provider request count.- **Expected**:- - Every 429 is classified as retryable `PROVIDER_RATE_LIMITED` in both setup- and post-start recovery, including a response body that omits rate-limit- wording when the captured HTTP status is 429. Diagnostics retain- `providerStatus: 429`.+ - Throughput rate-limit 429s are classified as retryable+ `PROVIDER_RATE_LIMITED` in both setup and post-start recovery, including a+ response body that omits rate-limit wording when the captured HTTP status+ is 429. Diagnostics retain `providerStatus: 429`.+ - Explicit billing/account exhaustion is terminal `PROVIDER_ERROR` even+ when returned with HTTP 429, including `insufficient_quota`,+ `credit_balance_exhausted`, organization usage-limit, and organization/+ project spend-limit codes. It starts no retry and consumes neither retry+ budget.- Setup and mid-stream failures share one budget of ten retries after theinitial attempt. A persistent fixture therefore makes eleven providerattempts, never multiplies attempts through nested pi-ai retries, anddiff --git a/docs/zh-CN/spec/03-runtime/02-agent-runtime.md b/docs/zh-CN/spec/03-runtime/02-agent-runtime.mdindex b8fa938bc..dcde8a90d 100644--- a/docs/zh-CN/spec/03-runtime/02-agent-runtime.md+++ b/docs/zh-CN/spec/03-runtime/02-agent-runtime.md@@ -148,7 +148,7 @@ pi 消费排队输入时保留渲染器提供的消息 id;即使补充输入### 5d。有界提供商流恢复和诊断(D186、D245、D259、ADR 0091、ADR 0128)提供程序请求设置和流式传输交付是两个独立的故障阶段,但-HTTP 429 处理是一个响应恢复策略。此路径禁用了 pi-ai 的嵌套+吞吐限流 HTTP 429 使用同一个响应恢复策略。此路径禁用了 pi-ai 的嵌套适配器重试,因此运行时可以在两个阶段之间共享一个预算。`PROVIDER_RATE_LIMITED` 在初始尝试之后最多重试 10 次,总共 11 次@@ -157,7 +157,9 @@ HTTP 429 处理是一个响应恢复策略。此路径禁用了 pi-ai 的嵌套回合中调用 `continue()`。两个阶段占用同一个计数器,因此设置阶段的429 后跟流阶段的 429 无法重置或倍增该预算。在两个阶段中,捕获的响应状态都会在对提供商消息进行分类之前应用,因此通用的-429 正文仍会进入 429 预算,而已知的不可重试分类仍然是终止的。+429 正文仍会进入 429 预算,而已知的不可重试分类仍然是终止的。明确的+账单/账户额度耗尽(包括 `insufficient_quota` 和消费限额代码)即使状态为+HTTP 429,也会成为终止的 `PROVIDER_ERROR`。主会话和内置子代理使用相同的控制器和策略。429 重试在转录生命周期上是静默的:没有中间助手错误、生命周期 `error`、diff --git a/docs/zh-CN/spec/03-runtime/08-error-codes.md b/docs/zh-CN/spec/03-runtime/08-error-codes.mdindex 52d49ea4a..a2636a8d2 100644--- a/docs/zh-CN/spec/03-runtime/08-error-codes.md+++ b/docs/zh-CN/spec/03-runtime/08-error-codes.md@@ -100,9 +100,9 @@ stdio 与 Tokio 的动态阻塞池隔离,因此后一种情况| `AGENT_SIDECAR_CRASHED` | 不 | Node agent sidecar 进程在回合中途死亡;所属回合以中止收尾并使用此代码,而不是无关的 Plan 审批代码(issue #1077) || `AGENT_SIDECAR_OOM` | 不 | sidecar 在 JavaScript 堆触及配置上限后死亡,依据其 stderr 尾部的 V8 致命错误横幅判定;在输入缩小之前,同一回合会以同样方式失败(issue #1077) || `MODEL_NOT_CONFIGURED` | 不 | 未选择可用模型,或提供商因未知而拒绝所选模型 |-| `PROVIDER_ERROR` | 是的 | 上游提供商故障;可重试的故障(5xx 网关)最多获得四次同回合重试,而格式错误的 400/422 请求,以及适配器自身拒绝的请求选项(Google 适配器遇到自定义 `fetch`,issue #1072)都是终止的 |+| `PROVIDER_ERROR` | 是的 | 上游提供商故障;可重试的 5xx 网关错误最多获得 10 次同回合重试,而格式错误的 400/422 请求、适配器拒绝的选项,以及明确的账单、信用额度、消费、用量或磁盘额度耗尽(包括 `insufficient_quota`)都是终止错误 || `PROVIDER_UNAUTHORIZED` | 不 | bad/missing 提供商凭证 |-| `PROVIDER_RATE_LIMITED` | 是的 | 供应商费率有限 |+| `PROVIDER_RATE_LIMITED` | 是的 | Provider 的暂时性吞吐限流;运行时最多跨请求设置和流式传输重试 10 次。明确的账单或账户额度耗尽始终是终止的 `PROVIDER_ERROR`,即使 HTTP 状态为 429 || `CONTEXT_TOO_LARGE` | 不 | 恢复后 prompt/context 仍超出安全模型预算、发生第二个提供程序溢出或禁用自动恢复 || `CONTEXT_COMPACTION_FAILED` | 不 | 自动保留尾部恢复无法准备、持久或适合检查点,或手动检查点摘要生成/持久追加失败;受保护的下一个提供程序请求不会启动 || `STREAM_FAILED` | 是的 | 提供程序流在完整响应之前终止、提前关闭或以其他方式结束;最多四次同回合重试可能会在终止事件之前发生 |@@ -367,9 +367,11 @@ Node sidecar 将提供商 SDK 错误映射到:`Range of input length should be`、z.ai 的 `Prompt exceeds max length`、xAI 的`maximum prompt length is`、Groq、llama.cpp,以及 Bedrock 的`Input is too long for requested model`。`CONTEXT_TOO_LARGE` 不会进入任何重试-预算,子代理会将其报告为 `SUBAGENT_CONTEXT_OVERFLOW`。限流措辞(包括 Bedrock 的-`Throttling error: Too many tokens, please wait before trying again.`)优先判定,-仍为 `PROVIDER_RATE_LIMITED`。+预算,子代理会将其报告为 `SUBAGENT_CONTEXT_OVERFLOW`。明确的账单/账户耗尽代码和+消息(包括 `insufficient_quota`、`credit_balance_exhausted`、组织用量限额以及组织/项目消费限额代码)+即使 HTTP 状态为 429,也映射为终止的 `PROVIDER_ERROR`。吞吐限流措辞(包括 Bedrock 的+`Throttling error: Too many tokens, please wait before trying again.`)仍映射为+`PROVIDER_RATE_LIMITED`。精确的 `terminated` 提供商消息和等效的过早流关闭消息映射到 `STREAM_FAILED`。请求设置阶段或响应后的diff --git a/packages/agent-runtime/src/agent-errors.test.ts b/packages/agent-runtime/src/agent-errors.test.tsindex 754380aa2..885230610 100644--- a/packages/agent-runtime/src/agent-errors.test.ts+++ b/packages/agent-runtime/src/agent-errors.test.ts@@ -371,6 +371,11 @@ describe("classifyAgentError", () => {"Your credit quota is exhausted. Please top up.","Billing quota exceeded for this project","disk quota exceeded",+ "insufficient_quota",+ '429: {"error":{"message":"You exceeded your current quota, please check your plan and billing details.","type":"insufficient_quota","code":"insufficient_quota"}}',+ '429: {"error":{"code":"organization_spend_limit_exceeded"}}',+ '429: {"error":{"code":"organization_usage_limit_exceeded"}}',+ "429: Billing quota exceeded",])("does not retry exhausted account or disk quota: %s", (message) => {const classified = classifyAgentError(new Error(message));expect(classified).not.toMatchObject({@@ -383,13 +388,20 @@ describe("classifyAgentError", () => {});});+ it("classifies structured 429 quota errors before generic status handling", () => {+ expect(classifyAgentError(Object.assign(+ new Error("429: rate limit response"),+ { status: 429, code: "credit_balance_exhausted" },+ ))).toMatchObject({+ code: "PROVIDER_ERROR",+ retriable: false,+ });+ });+it.each(["Rate limit exceeded",- "insufficient_quota","Too many requests","quota exceeded",- "insufficient_quota: You exceeded your current quota, please check your plan and billing details.",- "insufficient_quota: Billing quota exceeded",])("keeps throughput quota wording retryable: %s", (message) => {expect(classifyAgentError(new Error(message))).toMatchObject({code: "PROVIDER_RATE_LIMITED",diff --git a/packages/agent-runtime/src/agent-errors.ts b/packages/agent-runtime/src/agent-errors.tsindex 7b5a1abe0..58acfab11 100644--- a/packages/agent-runtime/src/agent-errors.ts+++ b/packages/agent-runtime/src/agent-errors.ts@@ -39,24 +39,25 @@ const CONTEXT_PATTERN =** A bare `quota` must not be included. It also matches account and filesystem* exhaustion ("monthly spending quota", "credit quota is exhausted", "Billing- * quota exceeded", "disk quota exceeded"). Those failures do not recover by- * backing off, but `/quota/` classified them as `PROVIDER_RATE_LIMITED` and- * the runtime retried them up to about ten times. Throughput quotas stay- * here: `insufficient_quota`, plus `quota exceeded` after- * `EXHAUSTED_QUOTA_PATTERN` has taken the account and disk phrases.+ * quota exceeded", "disk quota exceeded"). Explicit exhaustion codes and+ * phrases are checked before this matcher, while generic `quota exceeded`+ * wording remains eligible for throughput-rate-limit retries.*/const RATE_LIMIT_PATTERN =- /rate.?limit|too many requests|insufficient_quota|quota.?exceeded|overloaded|throttl/i;+ /rate.?limit|too many requests|quota.?exceeded|overloaded|throttl/i;/**- * Spending, credit, billing, and disk quotas are terminal. Checked before- * `RATE_LIMIT_PATTERN` so "quota exceeded" inside those phrases is not read- * as a throughput throttle. `insufficient_quota` does not match this- * pattern: the underscore is a word character, so the provider code alone- * is not an account or disk failure.+ * Billing, spending, credit, and disk exhaustion are terminal, including+ * OpenAI's `insufficient_quota` type and explicit 429 error codes. Checked+ * before the status table because those conditions do not recover by backing+ * off. Generic "quota exceeded" wording remains eligible for rate-limit+ * classification below.*/-const EXHAUSTED_QUOTA_PATTERN =- /\b(?:billing|spending|credit|disk)\s+quotas?\b/i;+const EXHAUSTED_QUOTA_CODE_PATTERN =+ /\b(?:insufficient_quota|credit_balance_exhausted|organization_spend_limit_exceeded|project_spend_limit_exceeded|organization_usage_limit_exceeded)\b/i;++const EXHAUSTED_QUOTA_MESSAGE_PATTERN =+ /\b(?:billing|spending|credit|disk)\s+quotas?\b|\b(?:organization|project)\s+spend\s+limit\s+(?:reached|exceeded)\b|\bquota\b.{0,100}\b(?:plan|billing)\b/i;/*** Whether a provider message reports a context overflow.@@ -572,6 +573,18 @@ export function classifyAgentError(err: unknown): ClassifiedAgentError {return result("PROVIDER_ERROR", false);}+ // These terminal billing/account exhaustion errors can also be HTTP 429.+ // Inspect both the message and structured provider code before the generic+ // 429 retry branch so the rate-limit budget cannot replay them.+ if (+ EXHAUSTED_QUOTA_CODE_PATTERN.test(rawMessage) ||+ EXHAUSTED_QUOTA_MESSAGE_PATTERN.test(rawMessage) ||+ (typeof providerCode === "string" &&+ EXHAUSTED_QUOTA_CODE_PATTERN.test(providerCode))+ ) {+ return result("PROVIDER_ERROR", false);+ }+if (status !== undefined) {if (status === 401 || status === 403) return result("PROVIDER_UNAUTHORIZED", false);if (status === 408) return result("TIMEOUT", true);@@ -590,14 +603,6 @@ export function classifyAgentError(err: unknown): ClassifiedAgentError {if (isStatuslessCredentialFailure(rawMessage)) {return result("PROVIDER_UNAUTHORIZED", false);}- // Account and disk exhaustion cannot be repaired by the rate-limit budget.- // `insufficient_quota` is a throughput code and wins when both appear.- if (- EXHAUSTED_QUOTA_PATTERN.test(rawMessage) &&- !/insufficient_quota/i.test(rawMessage)- ) {- return result("PROVIDER_ERROR", false);- }if (RATE_LIMIT_PATTERN.test(rawMessage)) {return result("PROVIDER_RATE_LIMITED", true);}diff --git a/packages/agent-runtime/src/provider-retry.test.ts b/packages/agent-runtime/src/provider-retry.test.tsindex 15e1583dd..3c2136a4f 100644--- a/packages/agent-runtime/src/provider-retry.test.ts+++ b/packages/agent-runtime/src/provider-retry.test.ts@@ -309,6 +309,40 @@ describe("provider rate-limit retry", () => {});});+ it("does not retry billing exhaustion when the captured status is 429", async () => {+ let attempts = 0;+ let retryableClaims = 0;+ const claim = vi.fn((error: ClassifiedAgentError) => {+ if (!error.retriable) return undefined;+ retryableClaims += 1;+ return retryableClaims === 1 ? 1 : undefined;+ });+ const sleep = vi.fn(async () => undefined);+ const stream = createProviderRetryStream(+ model,+ context,+ {},+ () => {+ attempts += 1;+ return failedStream({+ errorMessage: '429: {"error":{"message":"You exceeded your current quota, please check your plan and billing details.","type":"insufficient_quota","code":"insufficient_quota"}}',+ });+ },+ { claim, headers: () => undefined, status: () => 429, sleep },+ );++ const events: string[] = [];+ for await (const event of stream) events.push(event.type);++ expect(attempts).toBe(1);+ expect(claim).toHaveBeenCalledWith(+ expect.objectContaining({ code: "PROVIDER_ERROR", retriable: false }),+ "request",+ );+ expect(sleep).not.toHaveBeenCalled();+ expect(events).toEqual(["error"]);+ });+it("prefers retry headers and bounds exponential fallback", () => {expect(providerRateLimitDelayMs(1, { "retry-after-ms": "1250" }, 0, 0)).toBe(1250);expect(providerRateLimitDelayMs(1, { "retry-after": "2" }, 0, 0)).toBe(2000);