Skip to content

Claude Code. Any Model. The most powerful AI coding agent now speaks every language.

fix(errors): classify auth failures alike at every auth site

Jack Rudenko7fbd96f184dc
diff --git a/packages/cli/src/handlers/composed-handler.ts b/packages/cli/src/handlers/composed-handler.ts
index 700f1bb7..cc8c2469 100644
--- a/packages/cli/src/handlers/composed-handler.ts
+++ b/packages/cli/src/handlers/composed-handler.ts
@@ -87,7 +87,11 @@ import {
isTerminalError,
wrapAnthropicError,
} from "./shared/anthropic-error.js";
-import { authVerdictHeaders } from "./shared/auth-failure.js";
+import {
+ authVerdictHeaders,
+ classifyAuthFailure,
+ respondAuthFailure,
+} from "./shared/auth-failure.js";
import { sseResponseToJson } from "./shared/collect-sse-message.js";
import type { ConnectionErrorKind } from "./shared/connection-error.js";
import {
@@ -746,6 +750,59 @@ export class ComposedHandler implements ModelHandler {
return null;
}
+ /**
+ * Answer a failure at a credential site that is NOT a connection fault
+ * (`auth-failure.ts`): a terminal one — and any unclassifiable one of a
+ * SUBSCRIPTION — as 400 with the terminal verdict, so the chain stops and the
+ * message lands inline; a transient one as 503/429 with the transient
+ * verdict, never 401.
+ *
+ * An unclassifiable failure of a METERED provider gets 401 only where
+ * `meteredUnknown` is `"401"` (the refreshAuth and forceRefreshAuth catches,
+ * which always answered it, so the chain may try another credential).
+ * Everywhere else it returns null and the caller rethrows it unchanged:
+ * classify first or rethrow — never invent a status.
+ */
+ private answerAuthFailure(
+ c: Context,
+ err: unknown,
+ meteredUnknown: "401" | "rethrow"
+ ): Response | null {
+ const failure = classifyAuthFailure(err);
+ const isSubscription = isSubscriptionProvider(this.provider.name);
+ if (failure.kind === "connection") return null;
+ if (failure.kind === "unknown" && !isSubscription && meteredUnknown === "rethrow") return null;
+ return respondAuthFailure(c, failure, {
+ isSubscription,
+ providerDisplayName: this.provider.displayName,
+ });
+ }
+
+ /**
+ * {@link recoverConnection} at a credential site. A failure the ladder could
+ * not classify as a connection fault (its `"threw"` outcome, e.g. a token
+ * refresh that timed out and was then answered "login expired") is answered by
+ * {@link answerAuthFailure} instead of escaping `handle()` — where
+ * FallbackHandler would record status 0 and advance the chain.
+ */
+ private async recoverAtAuthSite<T>(
+ c: Context,
+ first: unknown,
+ conn: ConnectionErrorInfo,
+ endpoint: string,
+ op: (signal: AbortSignal) => Promise<T>,
+ ctx: Parameters<ComposedHandler["recoverConnection"]>[5],
+ meteredUnknown: "401" | "rethrow"
+ ): Promise<{ kind: "value"; value: T } | { kind: "respond"; response: Response }> {
+ try {
+ return await this.recoverConnection<T>(c, first, conn, endpoint, op, ctx);
+ } catch (thrown) {
+ const response = this.answerAuthFailure(c, thrown, meteredUnknown);
+ if (response) return { kind: "respond", response };
+ throw thrown;
+ }
+ }
+
/**
* Run tier-1 recovery for one classified connection failure.
*
@@ -1290,7 +1347,7 @@ export class ComposedHandler implements ModelHandler {
// expression and therefore unclamped — and a maximal connect hang
// would land the response write a whole connect timeout past the
// deadline.
- const outcome = await this.recoverConnection(
+ const outcome = await this.recoverAtAuthSite(
c,
err,
conn,
@@ -1303,7 +1360,8 @@ export class ComposedHandler implements ModelHandler {
authType: "oauth",
site: "refreshAuth",
recovery: recoveryTally,
- }
+ },
+ "401"
);
if (outcome.kind === "respond") return outcome.response;
// Recovered: fall through as if the first refresh had succeeded.
@@ -1324,21 +1382,20 @@ export class ComposedHandler implements ModelHandler {
isInteractive: this.isInteractive,
authType: "oauth",
});
- // A terminal setup failure (misconfiguration, revoked entitlement) can
- // never succeed on retry. Answering 401 sent the client into ~11 retries
- // over two minutes of backoff, with the actionable message hidden behind
- // "API error · Retrying". 400 is not retryable, so the explanation lands
- // inline on the first attempt.
- if (err?.terminal) {
- return c.json(
- wrapAnthropicError(400, err.message, "invalid_request_error"),
- 400 as any
- );
- }
- // Return 401 (auth failure) so FallbackHandler treats this as retryable and
- // moves to the next provider in the chain. 503 (connection error) would stop
- // the fallback chain since it is not retryable by design.
- return c.json(wrapAnthropicError(401, err.message, "authentication_error"), 401 as any);
+ // One classifier for every credential site (`auth-failure.ts`):
+ // - terminal (misconfiguration, revoked entitlement, expired login)
+ // → 400 with the terminal verdict. Answering 401 sent the client
+ // into ~11 retries over two minutes of backoff with the message
+ // hidden behind "API error · Retrying", and walked the chain.
+ // - transient (the token host answered 5xx/429) → 503/429 with the
+ // transient verdict, never 401: the same hop answers on retry.
+ // - unclassifiable: a SUBSCRIPTION → terminal 400 (Kimi's plain
+ // "run `claudish login kimi`" error lands inline); a METERED
+ // provider → 401 as before, so the chain may try a provider with
+ // another credential.
+ const answered = this.answerAuthFailure(c, err, "401");
+ if (answered) return answered;
+ throw err;
}
}
// Update display name in case auth resolved it (e.g., Gemini tier
@@ -1402,10 +1459,15 @@ export class ComposedHandler implements ModelHandler {
} catch (err: any) {
const conn = classifyConnectionError(err);
if (!conn) {
- // Anything else keeps its existing route out of here untouched.
+ // A credential failure this site can place is answered here — terminal
+ // or a subscription's unclassifiable one as 400, transient as 503/429.
+ // Anything else (a metered provider's unclassifiable throw) keeps its
+ // existing route out of here untouched.
+ const answered = this.answerAuthFailure(c, err, "rethrow");
+ if (answered) return answered;
throw err;
}
- const outcome = await this.recoverConnection<Record<string, string>>(
+ const outcome = await this.recoverAtAuthSite<Record<string, string>>(
c,
err,
conn,
@@ -1420,7 +1482,8 @@ export class ComposedHandler implements ModelHandler {
authType: "oauth",
site: "getHeaders",
recovery: recoveryTally,
- }
+ },
+ "rethrow"
);
if (outcome.kind === "respond") return outcome.response;
headers = outcome.value;
@@ -1532,14 +1595,25 @@ export class ComposedHandler implements ModelHandler {
: attempt();
};
- const outcome = await this.recoverConnection<Response>(c, error, conn, endpoint, reissue, {
- startTime,
- // The SAME value the primary attempt was bounded by, not a fresh read.
- deadlineAt,
- fallbackMeta,
- site: "fetch",
- recovery: recoveryTally,
- });
+ // Through the auth-site wrapper: a re-issue that fails with something
+ // other than a connection fault is classified like any credential
+ // failure, not rethrown out of `handle()` into a status-0 chain advance.
+ const outcome = await this.recoverAtAuthSite<Response>(
+ c,
+ error,
+ conn,
+ endpoint,
+ reissue,
+ {
+ startTime,
+ // The SAME value the primary attempt was bounded by, not a fresh read.
+ deadlineAt,
+ fallbackMeta,
+ site: "fetch",
+ recovery: recoveryTally,
+ },
+ "rethrow"
+ );
if (outcome.kind === "respond") return outcome.response;
response = outcome.value;
}
@@ -1668,8 +1742,14 @@ export class ComposedHandler implements ModelHandler {
retryResp = await doParamRetry();
} catch (err: any) {
const conn = classifyConnectionError(err);
- if (!conn) throw err;
- const outcome = await this.recoverConnection<Response>(
+ if (!conn) {
+ // The re-fetch re-reads the headers, so a credential failure can
+ // surface here too; one this site can place is answered.
+ const answered = this.answerAuthFailure(c, err, "rethrow");
+ if (answered) return answered;
+ throw err;
+ }
+ const outcome = await this.recoverAtAuthSite<Response>(
c,
err,
conn,
@@ -1684,7 +1764,8 @@ export class ComposedHandler implements ModelHandler {
retriedBeforeLadder: true,
site: "parameter-recovery",
recovery: recoveryTally,
- }
+ },
+ "rethrow"
);
if (outcome.kind === "respond") return outcome.response;
retryResp = outcome.value;
@@ -1713,7 +1794,9 @@ export class ComposedHandler implements ModelHandler {
// transiently, so a ladder that could only re-run one of them would
// leave the other exactly as exposed as it was.
const doAuthRetry = async (sig?: AbortSignal): Promise<Response> => {
- await this.provider.forceRefreshAuth!();
+ // The headers of the request the upstream rejected, so a transport can
+ // tell a stale failure from one naming the credential it holds now.
+ await this.provider.forceRefreshAuth!({ rejectedHeaders: headers });
const retryHeaders = await fetchHeaders();
// Same serialization as the primary request — this is a separate call
// site and the easy one to forget, which is why both are pinned by
@@ -1782,6 +1865,50 @@ export class ComposedHandler implements ModelHandler {
} catch {
// Stats must never crash claudish
}
+ // A 401/403 that SURVIVED a fresh credential is terminal for a
+ // subscription, or wherever the transport says so: answered 400 with
+ // the terminal verdict and the same hint and wording as the generic
+ // remap below, so the login line lands inline and the chain stops.
+ // 401/403 ONLY: Antigravity's terminal 429 keeps its own route.
+ if (retryResp.status === 401 || retryResp.status === 403) {
+ const transportTerminal = this.provider.classifyTerminalError?.(
+ retryResp.status,
+ errorText
+ );
+ if (isSubscriptionProvider(this.provider.name) || transportTerminal === true) {
+ const hint = getRecoveryHint(
+ retryResp.status,
+ errorText,
+ this.provider.displayName,
+ transportTerminal,
+ this.provider.name
+ );
+ let parsed: unknown;
+ try {
+ parsed = JSON.parse(errorText);
+ } catch {
+ parsed = undefined;
+ }
+ const providerMsg = extractProviderMessage(parsed ?? errorText);
+ const surfaced = buildSurfacedErrorMessage({
+ providerDisplayName: this.provider.displayName,
+ status: retryResp.status,
+ hint,
+ providerMessage: providerMsg,
+ });
+ return c.json(
+ wrapAnthropicError(
+ 400,
+ surfaced,
+ "invalid_request_error",
+ retryResp.status,
+ providerMsg
+ ),
+ 400 as any,
+ authVerdictHeaders("terminal")
+ );
+ }
+ }
return c.json(wrapAnthropicError(retryResp.status, errorText), retryResp.status as any);
}
return null;
@@ -1801,7 +1928,7 @@ export class ComposedHandler implements ModelHandler {
// this whole area exists to prevent.
const conn = classifyConnectionError(err);
if (conn) {
- const outcome = await this.recoverConnection<Response>(
+ const outcome = await this.recoverAtAuthSite<Response>(
c,
err,
conn,
@@ -1815,7 +1942,8 @@ export class ComposedHandler implements ModelHandler {
authType: "oauth",
site: "forceRefreshAuth",
recovery: recoveryTally,
- }
+ },
+ "401"
);
if (outcome.kind === "respond") return outcome.response;
const answered = await settleAuthRetry(outcome.value);
@@ -1862,7 +1990,13 @@ export class ComposedHandler implements ModelHandler {
} catch {
// Stats must never crash claudish
}
- return c.json(wrapAnthropicError(401, err.message, "authentication_error"), 401 as any);
+ // The same classifier as the refreshAuth catch: terminal (and a
+ // subscription's unclassifiable failure) → 400 with the terminal
+ // verdict; transient → 503/429; a metered provider's
+ // unclassifiable failure → 401 as before.
+ const answered = this.answerAuthFailure(c, err, "401");
+ if (answered) return answered;
+ throw err;
}
}
} else {
diff --git a/packages/cli/src/providers/transport/types.ts b/packages/cli/src/providers/transport/types.ts
index 440a179e..47a89779 100644
--- a/packages/cli/src/providers/transport/types.ts
+++ b/packages/cli/src/providers/transport/types.ts
@@ -108,8 +108,13 @@ export interface ProviderTransport {
* Force refresh auth credentials after a 401 response.
* Used by OAuth providers (Vertex, CodeAssist) to handle token expiry.
* ComposedHandler calls this automatically on 401 and retries the request.
+ *
+ * `ctx.rejectedHeaders` are the headers of the request the upstream just
+ * rejected, so a transport holding several credentials can tell a stale
+ * failure (its credential already changed) from one that names the
+ * credential it holds now.
*/
- forceRefreshAuth?(): Promise<void>;
+ forceRefreshAuth?(ctx?: { rejectedHeaders?: Record<string, string> }): Promise<void>;
/**
* Optional per-provider verdict on whether an error response is TERMINAL