Claude Code. Any Model. The most powerful AI coding agent now speaks every language.
fix(errors): retry a subscription token host's 429/5xx instead of a 400
Jack Rudenko264b275907af
diff --git a/packages/cli/src/auth/antigravity-token.ts b/packages/cli/src/auth/antigravity-token.tsindex 76efd735..1e1eaecf 100644--- a/packages/cli/src/auth/antigravity-token.ts+++ b/packages/cli/src/auth/antigravity-token.ts@@ -34,6 +34,7 @@ import { existsSync } from "node:fs";import { homedir } from "node:os";import { join } from "node:path";import { log, logStderr } from "../logger.js";+import { terminalCredentialError } from "./credentials/credential-error.js";// ---------------------------------------------------------------------------// Constants@@ -413,7 +414,7 @@ let inFlight: Promise<string> | null = null;async function resolveValidToken(deps: AntigravityTokenDeps): Promise<string> {if (process.platform !== "darwin") {- throw new Error(+ throw terminalCredentialError("[Antigravity] The shared Antigravity token store is macOS-only for now. " +"Use g@<model> with GEMINI_API_KEY on this platform.");@@ -421,7 +422,7 @@ async function resolveValidToken(deps: AntigravityTokenDeps): Promise<string> {const rec = parseRecord(deps.readStore());if (!rec) {- throw new Error(+ throw terminalCredentialError("[Antigravity] No Antigravity session found. Sign in with `claudish login antigravity`, " +"or use g@<model> with GEMINI_API_KEY " +"(get one at https://aistudio.google.com/app/apikey)."@@ -447,7 +448,14 @@ async function resolveValidToken(deps: AntigravityTokenDeps): Promise<string> {// these four is fixed by signing in again. Reporting them all as "session// expired, re-login" sent users through an OAuth flow that could not help,// most often while agy was simply mid-self-update.- throw new Error(`[Antigravity] ${describeRefreshFailure(outcome)}`);+ // What the outcome says about the login decides the error's class: a slow or+ // failing `agy` is not a dead session (retryable), a missing CLI or a revoked+ // session is (terminal). `credential-error.ts`.+ const message = `[Antigravity] ${describeRefreshFailure(outcome)}`;+ if (outcome.kind === "timeout")+ throw Object.assign(new Error(message), { transient: true as const });+ if (outcome.kind === "failed") throw new Error(message);+ throw terminalCredentialError(message);}/** Turn a refresh outcome into the remediation that actually applies to it. */@@ -529,7 +537,7 @@ export async function forceRefreshAntigravityToken(deps: AntigravityTokenDeps = defaultDeps): Promise<string> {if (process.platform !== "darwin") {- throw new Error(+ throw terminalCredentialError("[Antigravity] The shared Antigravity token store is macOS-only for now. " +"Use g@<model> with GEMINI_API_KEY on this platform.");@@ -541,7 +549,7 @@ export async function forceRefreshAntigravityToken(const rec = parseRecord(deps.readStore());if (!rec) {- throw new Error(+ throw terminalCredentialError("[Antigravity] No Antigravity session found. Sign in with `claudish login antigravity`, " +"or use g@<model> with GEMINI_API_KEY " +"(get one at https://aistudio.google.com/app/apikey)."@@ -572,7 +580,7 @@ export async function forceRefreshAntigravityToken(writeSharedAntigravityToken(original, deps);}_resetAntigravityTokenState();- throw new Error(+ throw terminalCredentialError("[Antigravity] The Antigravity session was rejected upstream and could not be re-minted. " +"Run `claudish login antigravity` to sign in again.");diff --git a/packages/cli/src/auth/antigravity-user.ts b/packages/cli/src/auth/antigravity-user.tsindex 7ba881b4..f7d29153 100644--- a/packages/cli/src/auth/antigravity-user.ts+++ b/packages/cli/src/auth/antigravity-user.ts@@ -14,6 +14,7 @@*/import { log } from "../logger.js";+import { credentialHttpError } from "./credentials/credential-error.js";/*** The Antigravity backend host.@@ -129,7 +130,11 @@ async function callLoadCodeAssistAntigravity(accessToken: string): Promise<LoadC});if (!res.ok) {- throw new Error(`loadCodeAssist (antigravity) failed: ${res.status} ${await res.text()}`);+ // 429/5xx is transient (retry), a 4xx a terminal setup verdict (`credential-error.ts`).+ throw credentialHttpError(+ `loadCodeAssist (antigravity) failed: ${res.status} ${await res.text()}`,+ res.status+ );}return (await res.json()) as LoadCodeAssistResponse;diff --git a/packages/cli/src/auth/codex-oauth.ts b/packages/cli/src/auth/codex-oauth.tsindex 09ae4378..6a1aa4f7 100644--- a/packages/cli/src/auth/codex-oauth.ts+++ b/packages/cli/src/auth/codex-oauth.ts@@ -22,6 +22,11 @@ import { promisify } from "node:util";import { markOwnTimeout } from "../handlers/shared/connection-error.js";import { TOKEN_REFRESH_TIMEOUT_MS } from "../handlers/shared/transient-retry.js";import { log } from "../logger.js";+import {+ credentialHttpError,+ isTransientCredentialError,+ terminalCredentialError,+} from "./credentials/credential-error.js";const execAsync = promisify(exec);@@ -295,7 +300,10 @@ export class CodexOAuth {try {if (!response.ok) {const errorText = await response.text();- throw new Error(`Token refresh failed: ${response.status} - ${errorText}`);+ throw credentialHttpError(+ `Token refresh failed: ${response.status} - ${errorText}`,+ response.status+ );}const tokens = (await response.json()) as TokenResponse;@@ -323,10 +331,15 @@ export class CodexOAuth {return updatedCredentials.access_token;} catch (e: any) {log(`[CodexOAuth] Refresh failed: ${e.message}`);+ // A 429/5xx from the token host is retryable and keeps its fields; it is+ // not "credentials invalid" (`credential-error.ts`).+ if (isTransientCredentialError(e)) throw e;// `{ cause }` here too: a connection reset while reading the response body// is a network fault that arrives after the fetch resolved.- throw new Error(- `OAuth credentials invalid. Please run \`claudish login codex\` again.\n\nDetails: ${e.message}`,+ throw Object.assign(+ terminalCredentialError(+ `OAuth credentials invalid. Please run \`claudish login codex\` again.\n\nDetails: ${e.message}`+ ),{ cause: e });}diff --git a/packages/cli/src/auth/credentials/credential-error.ts b/packages/cli/src/auth/credentials/credential-error.tsnew file mode 100644index 00000000..f99f08a2--- /dev/null+++ b/packages/cli/src/auth/credentials/credential-error.ts@@ -0,0 +1,53 @@+/**+ * Structured errors for credential producers (token refresh, project lookup,+ * login files), so `classifyAuthFailure` (`handlers/shared/auth-failure.ts`)+ * reads FIELDS, never prose:+ *+ * - a missing login or a rejected grant (400/401/403 from a token host) is+ * `terminal`: only a new login fixes it, and the routing chain stops with+ * the message on the first attempt;+ * - a 429 or 5xx from a token host is `transient` with its `upstreamStatus`:+ * the same hop answers on retry, so it is never a reason to stop, nor to+ * walk onto another provider.+ *+ * A plain `Error` from a credential path is `unknown`, which a subscription+ * answers as retryable (transient 503): a producer that has not said what its+ * failure is gets the conservative answer, never a fatal one.+ */++export interface CredentialFailureFields {+ terminal?: true;+ transient?: true;+ upstreamStatus?: number;+}++/** A credential failure no retry can fix (no login, a revoked or rejected grant). */+export function terminalCredentialError(+ message: string,+ upstreamStatus?: number+): Error & CredentialFailureFields {+ return Object.assign(new Error(message), {+ terminal: true as const,+ ...(upstreamStatus !== undefined ? { upstreamStatus } : {}),+ });+}++/**+ * The error for a token host's non-2xx answer: 429 and 5xx are transient,+ * everything else (a rejected grant, a bad request) is terminal. The status+ * travels either way.+ */+export function credentialHttpError(+ message: string,+ status: number+): Error & CredentialFailureFields {+ if (status === 429 || (status >= 500 && status <= 599)) {+ return Object.assign(new Error(message), { transient: true as const, upstreamStatus: status });+ }+ return terminalCredentialError(message, status);+}++/** Whether a producer marked this error retryable (429/5xx from its token host). */+export function isTransientCredentialError(err: unknown): boolean {+ return (err as CredentialFailureFields | null)?.transient === true;+}diff --git a/packages/cli/src/auth/grok-oauth.ts b/packages/cli/src/auth/grok-oauth.tsindex 9ccf9cfc..c00e40aa 100644--- a/packages/cli/src/auth/grok-oauth.ts+++ b/packages/cli/src/auth/grok-oauth.ts@@ -29,6 +29,7 @@*/import { log } from "../logger.js";+import { credentialHttpError, terminalCredentialError } from "./credentials/credential-error.js";import { type BaseCredentials, OAuthManager } from "./oauth-manager.js";/** OIDC issuer for the Grok CLI's identity provider. */@@ -164,7 +165,9 @@ export class GrokOAuth extends OAuthManager<GrokOAuthCredentials> {protected async doRefreshToken(): Promise<string> {const current = this.credentials;if (!current) {- throw new Error(`No Grok credentials found. Please run \`${this.loginHint}\` first.`);+ throw terminalCredentialError(+ `No Grok credentials found. Please run \`${this.loginHint}\` first.`+ );}const body = new URLSearchParams({@@ -183,8 +186,16 @@ export class GrokOAuth extends OAuthManager<GrokOAuthCredentials> {if (!response.ok || !parsed.access_token) {const detail = parsed.error_description ?? parsed.error ?? `HTTP ${response.status}`;// `invalid_grant` means the refresh token is dead — only a new login- // fixes it, so say that rather than leaving the user to guess.- throw new Error(+ // fixes it, so say that rather than leaving the user to guess. A 429 or+ // 5xx from the token host is NOT that: it is marked transient, so the+ // request retries instead of stopping on a login instruction.+ if (!response.ok) {+ throw credentialHttpError(+ `Grok token refresh failed: ${detail}. Run \`${this.loginHint}\` to sign in.`,+ response.status+ );+ }+ throw terminalCredentialError(`Grok token refresh failed: ${detail}. Run \`${this.loginHint}\` to sign in.`);}diff --git a/packages/cli/src/auth/kimi-oauth.ts b/packages/cli/src/auth/kimi-oauth.tsindex 596db726..d8d4c016 100644--- a/packages/cli/src/auth/kimi-oauth.ts+++ b/packages/cli/src/auth/kimi-oauth.ts@@ -21,8 +21,14 @@ import { closeSync, existsSync, openSync, readFileSync, unlinkSync, writeSync }import { homedir, hostname, platform, release } from "node:os";import { join } from "node:path";import { promisify } from "node:util";+import { classifyConnectionError } from "../handlers/shared/connection-error.js";import { log } from "../logger.js";import { VERSION } from "../version.js";+import {+ credentialHttpError,+ isTransientCredentialError,+ terminalCredentialError,+} from "./credentials/credential-error.js";const execAsync = promisify(exec);@@ -449,7 +455,9 @@ export class KimiOAuth {// Check if we have credentialsif (!this.credentials) {- throw new Error("No Kimi OAuth credentials found. Please run `claudish login kimi` first.");+ throw terminalCredentialError(+ "No Kimi OAuth credentials found. Please run `claudish login kimi` first."+ );}// Check if token is still valid (with 5-minute buffer)@@ -481,7 +489,9 @@ export class KimiOAuth {*/private async doRefreshToken(): Promise<string> {if (!this.credentials) {- throw new Error("No Kimi OAuth credentials found. Please run `claudish login kimi` first.");+ throw terminalCredentialError(+ "No Kimi OAuth credentials found. Please run `claudish login kimi` first."+ );}log("[KimiOAuth] Refreshing access token");@@ -507,7 +517,10 @@ export class KimiOAuth {if (!response.ok) {const errorText = await response.text();- throw new Error(`Token refresh failed: ${response.status} - ${errorText}`);+ throw credentialHttpError(+ `Token refresh failed: ${response.status} - ${errorText}`,+ response.status+ );}const tokens = (await response.json()) as TokenResponse;@@ -532,6 +545,11 @@ export class KimiOAuth {} catch (e: any) {log(`[KimiOAuth] Refresh failed: ${e.message}`);+ // A token host that is down or busy (network fault, 429, 5xx) says+ // nothing about the login. Keep the credentials and let the request+ // retry; deleting them here turned a blip into a forced re-login.+ if (isTransientCredentialError(e) || classifyConnectionError(e)) throw e;+// Delete invalid credentialsconst credPath = this.getCredentialsPath();if (existsSync(credPath)) {@@ -548,7 +566,7 @@ export class KimiOAuth {}// No API key available, throw error with instructions- throw new Error(+ throw terminalCredentialError(`OAuth credentials invalid. Please re-login or set API key:\n - Run: claudish login kimi\n - Or set: export MOONSHOT_API_KEY='your-api-key'\n\nDetails: ${e.message}`);}diff --git a/packages/cli/src/auth/oauth-manager.ts b/packages/cli/src/auth/oauth-manager.tsindex 606223bf..f78686d5 100644--- a/packages/cli/src/auth/oauth-manager.ts+++ b/packages/cli/src/auth/oauth-manager.ts@@ -25,6 +25,7 @@ import { homedir } from "node:os";import { join } from "node:path";import { promisify } from "node:util";import { log } from "../logger.js";+import { terminalCredentialError } from "./credentials/credential-error.js";const execAsync = promisify(exec);@@ -129,7 +130,7 @@ export abstract class OAuthManager<T extends BaseCredentials = BaseCredentials>}if (!this.credentials) {- throw new Error(+ throw terminalCredentialError(`No ${this.providerName} credentials found. Please run \`${this.loginHint}\` first.`);}@@ -147,7 +148,7 @@ export abstract class OAuthManager<T extends BaseCredentials = BaseCredentials>async refreshToken(): Promise<void> {if (!this.credentials) {- throw new Error(+ throw terminalCredentialError(`No ${this.providerName} credentials found. Please run \`${this.loginHint}\` first.`);}diff --git a/packages/cli/src/handlers/shared/auth-failure.ts b/packages/cli/src/handlers/shared/auth-failure.tsindex 2a775d71..4e10dcca 100644--- a/packages/cli/src/handlers/shared/auth-failure.ts+++ b/packages/cli/src/handlers/shared/auth-failure.ts@@ -28,13 +28,14 @@** connection → terminal → transient → unknown. A connection fault is never* answered here at all: the caller runs connection recovery first, and only a- * failure recovery could not place comes back. `unknown` on a SUBSCRIPTION is- * answered as terminal, not transient: connection faults are classified first- * and real transients carry `upstreamStatus` or `transient`, so what is left is- * overwhelmingly a credential or configuration fault — Kimi's "No Kimi OAuth- * credentials found. Please run `claudish login kimi` first." is a plain- * `Error`. Answered 503 it would hide behind about two minutes of Claude Code's- * silent retries; answered 400 it is read on the first attempt.+ * failure recovery could not place comes back.+ *+ * The producers say what their failure is (`auth/credentials/credential-error.ts`):+ * a missing login or a rejected grant is `terminal`, a token host's 429/5xx is+ * `transient` with its status. What is left — `unknown` — is a failure nobody+ * classified, and on a SUBSCRIPTION it is answered as RETRYABLE (503, verdict+ * transient), never fatal: stopping a working subscription with a login+ * instruction because a token host blinked is the worse error of the two.*/import type { Context } from "hono";import type { ContentfulStatusCode } from "hono/utils/http-status";@@ -173,7 +174,8 @@ export function classifyAuthFailure(err: unknown): AuthFailure {* is kept for probes.* - transient → 429 for a 429, 503 for any 5xx, verdict `transient`: Claude* Code's own retry re-sends to the same hop. Never 401.- * - unknown on a subscription → as terminal (see the module comment).+ * - unknown on a subscription → as transient: 503 and the transient verdict (see+ * the module comment).* - unknown on a metered provider → 401 `authentication_error`, unchanged from* before, so the chain may try a provider holding another credential. Only* the two sites that already answered 401 (refreshAuth, forceRefreshAuth)@@ -204,7 +206,17 @@ export function respondAuthFailure();}case "unknown":- if (opts.isSubscription) return terminalResponse(c, failure.message);+ if (opts.isSubscription) {+ return c.json(+ wrapAnthropicError(+ 503,+ `${opts.providerDisplayName} could not confirm the credential: ${failure.message}`,+ "overloaded_error"+ ),+ 503,+ authVerdictHeaders("transient")+ );+ }return c.json(wrapAnthropicError(401, failure.message, "authentication_error"), 401);}}diff --git a/packages/cli/src/providers/grok/grok-credentials.ts b/packages/cli/src/providers/grok/grok-credentials.tsindex f4e2bd10..78ea13ef 100644--- a/packages/cli/src/providers/grok/grok-credentials.ts+++ b/packages/cli/src/providers/grok/grok-credentials.ts@@ -42,8 +42,12 @@import { existsSync, readFileSync, renameSync, writeFileSync } from "node:fs";import { homedir } from "node:os";import { join } from "node:path";+import {+ credentialHttpError,+ isTransientCredentialError,+} from "../../auth/credentials/credential-error.js";import { GROK_PUBLIC_CLIENT_ID, GrokOAuth } from "../../auth/grok-oauth.js";-import { markOwnTimeout } from "../../handlers/shared/connection-error.js";+import { classifyConnectionError, markOwnTimeout } from "../../handlers/shared/connection-error.js";import { TOKEN_REFRESH_TIMEOUT_MS } from "../../handlers/shared/transient-retry.js";/** Base-URL override, the same variable the Grok CLI installer honours. */@@ -464,7 +468,12 @@ async function performRefresh(cred: GrokCredential): Promise<string> {// `invalid_grant` means the refresh token is dead — only a new login fixes// it. Terminal, so ComposedHandler renders it inline instead of sending// Claude Code into ~11 rounds of "API error · Retrying".- throw terminal(`Grok token refresh failed (${response.status}): ${detail}. ${SIGN_IN_HINT}`);+ // 429/5xx from the token host is transient (retry the same hop); anything+ // else is a dead grant and terminal (`credential-error.ts`).+ throw credentialHttpError(+ `Grok token refresh failed (${response.status}): ${detail}. ${SIGN_IN_HINT}`,+ response.status+ );}const parsed = JSON.parse(text) as {@@ -513,7 +522,12 @@ export async function resolveGrokAccessToken(): Promise<string> {// Fall through to the CLI credential rather than failing outright: a// user who has BOTH should not be blocked by one being broken. If there// is no CLI credential either, the throw below carries the real message.- if (!readGrokCredential()) throw terminal(`${(error as Error).message}`);+ // A transient or network failure keeps its own classification: wrapping+ // it terminal would stop a working subscription on a token-host blip.+ if (!readGrokCredential()) {+ if (isTransientCredentialError(error) || classifyConnectionError(error)) throw error;+ throw terminal(`${(error as Error).message}`);+ }}}diff --git a/packages/cli/src/providers/transport/openai-codex.ts b/packages/cli/src/providers/transport/openai-codex.tsindex 225af8b0..020785ab 100644--- a/packages/cli/src/providers/transport/openai-codex.ts+++ b/packages/cli/src/providers/transport/openai-codex.ts@@ -25,6 +25,7 @@ import { normalizeCodexModel } from "../../adapters/codex-api-format.js";import { lookupModelForProvider } from "../../adapters/model-catalog.js";import { credentials } from "../../auth/credentials/authority.js";import { recordSignedArm } from "../../auth/credentials/billing-probe.js";+import { isTransientCredentialError } from "../../auth/credentials/credential-error.js";import type { RequestAuth } from "../../auth/credentials/types.js";import { classifyConnectionError } from "../../handlers/shared/connection-error.js";import { conversationKey } from "./conversation-key.js";@@ -54,6 +55,9 @@ export class OpenAICodexTransport extends OpenAIProviderTransport {// it and holds the request (CLAUDE.md: a connection failure wearing an// auth status, the five sites; this catch was a sixth that swallowed).if (classifyConnectionError(err)) throw err;+ // A token host's 429/5xx is the same kind of fact: the subscription is+ // there and busy, so the request retries rather than moving to metered.+ if (isTransientCredentialError(err)) throw err;// The refresh was REJECTED (or no OAuth) → use the api-key path below.this.cachedAuth = null;}