Skip to content

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

fix(errors): stop the routing chain on a subscription credential failure

Jack Rudenko72d63cc34419
diff --git a/packages/cli/src/handlers/composed-handler.ts b/packages/cli/src/handlers/composed-handler.ts
index c1e9e4fe..700f1bb7 100644
--- a/packages/cli/src/handlers/composed-handler.ts
+++ b/packages/cli/src/handlers/composed-handler.ts
@@ -87,6 +87,7 @@ import {
isTerminalError,
wrapAnthropicError,
} from "./shared/anthropic-error.js";
+import { authVerdictHeaders } from "./shared/auth-failure.js";
import { sseResponseToJson } from "./shared/collect-sse-message.js";
import type { ConnectionErrorKind } from "./shared/connection-error.js";
import {
@@ -99,6 +100,7 @@ import { hasActionableLink, hasModelUnsupportedWording } from "./shared/model-un
import { filterIdentity } from "./shared/openai-compat.js";
import { hasPlanLimitWording, isQuotaExhaustionError } from "./shared/quota-exhaustion.js";
import { connectionFaultHeaders, recoveryHoldHeaders } from "./shared/recovery-marker.js";
+import { isSubscriptionProvider } from "./shared/remote-provider-types.js";
import {
CONTEXT_OVERFLOW_PHRASE,
isContextOverflowError,
@@ -2001,6 +2003,15 @@ export class ComposedHandler implements ModelHandler {
? CONTEXT_OVERFLOW_PHRASE
: undefined,
});
+ // A SUBSCRIPTION's rejected credential stops the routing chain here
+ // (`auth-failure.ts`): the next hop would bill the user per token for a
+ // login they can fix. A spent allowance (402/429) is not a credential
+ // failure and still advances, with its warning.
+ const verdictHeaders =
+ (response.status === 401 || response.status === 403) &&
+ isSubscriptionProvider(this.provider.name)
+ ? authVerdictHeaders("terminal")
+ : undefined;
// Carry the ORIGINAL upstream status as a structured field so
// machine consumers (probe classification) can tell a remapped
// auth failure from a genuine 400.
@@ -2015,7 +2026,8 @@ export class ComposedHandler implements ModelHandler {
// useless to a probe row that clips.
providerMsg
),
- 400 as any
+ 400 as any,
+ verdictHeaders
);
}
return c.json(
diff --git a/packages/cli/src/handlers/fallback-handler.ts b/packages/cli/src/handlers/fallback-handler.ts
index 93bc2a27..e5fa2199 100644
--- a/packages/cli/src/handlers/fallback-handler.ts
+++ b/packages/cli/src/handlers/fallback-handler.ts
@@ -13,13 +13,21 @@ import type { Context } from "hono";
import { logStderr } from "../logger.js";
import { ComposedHandler } from "./composed-handler.js";
import { extractUpstreamStatus } from "./shared/anthropic-error.js";
+import { authVerdict } from "./shared/auth-failure.js";
import { hasQuotaExhaustionWording } from "./shared/quota-exhaustion.js";
import { isClaudishConnectionVerdict, isRecoveryHoldResponse } from "./shared/recovery-marker.js";
+import { isSubscriptionProvider } from "./shared/remote-provider-types.js";
import type { ModelHandler } from "./types.js";
export interface FallbackCandidate {
/** Human-readable provider name for logging */
name: string;
+ /**
+ * The claudish provider uid (`kimi-coding`), when the caller knows it. `name`
+ * is a DISPLAY name, so a billing question asked of it answers for nobody:
+ * `isSubscriptionProvider("Kimi Coding")` is false.
+ */
+ provider?: string;
/** The handler to try */
handler: ModelHandler;
}
@@ -44,7 +52,7 @@ export class FallbackHandler implements ModelHandler {
for (let attempt = 0; attempt < this.candidates.length; attempt++) {
const idx = (startIndex + attempt) % this.candidates.length;
- const { name, handler } = this.candidates[idx];
+ const { name, handler, provider } = this.candidates[idx];
const isLast = attempt === this.candidates.length - 1;
try {
@@ -117,7 +125,7 @@ export class FallbackHandler implements ModelHandler {
const errorBody = await response.clone().text();
// Non-retryable error (rate limit, server error, bad format) — stop trying
- if (!isRetryableError(response.status, errorBody, name, response.headers)) {
+ if (!isRetryableError(response.status, errorBody, name, response.headers, provider)) {
if (errors.length > 0) {
// We had previous fallback attempts; show combined error
errors.push({ provider: name, status: response.status, message: errorBody });
@@ -212,7 +220,8 @@ export function isRetryableError(
status: number,
errorBody: string,
provider?: string,
- headers?: Headers
+ headers?: Headers,
+ providerId?: string
): boolean {
// ── CLAUDISH'S OWN "CANNOT REACH THE HOST" IS NEVER A REASON TO ADVANCE ────
//
@@ -234,6 +243,18 @@ export function isRetryableError(
// property of which arm happened to answer.
if (isClaudishConnectionVerdict(headers)) return false;
+ // ── A CREDENTIAL VERDICT IS NEVER A REASON TO ADVANCE EITHER ──────────────
+ //
+ // `ComposedHandler` marks its answer to a credential failure it could place
+ // (`auth-failure.ts`): `terminal` — a subscription login that cannot succeed
+ // on retry, answered 400 so the message lands inline — or `transient` — a
+ // 5xx/429 on the credential path, which the SAME hop answers on Claude Code's
+ // own retry. Either way the next candidate is the wrong remedy, and for a
+ // subscription it is a metered one (project owner, 2026-10-16). Above the
+ // quota wording and the `upstream_status` recovery below, because a terminal
+ // 400 carries `upstream_status: 401`, which that recovery reads as retryable.
+ if (authVerdict(headers)) return false;
+
// A spent subscription allowance is retryable AT THE CHAIN LEVEL: this
// provider cannot serve, but the next one can.
//
@@ -268,6 +289,17 @@ export function isRetryableError(
// prevented at the cost of the request.
if (hasQuotaExhaustionWording(errorBody)) return true;
+ // A SUBSCRIPTION's 401 stops the chain whatever its transport answered. The
+ // verdict header above covers every 401 a ComposedHandler places; this covers
+ // a candidate that answers one without it, so the rule holds for every
+ // subscription provider and not only for the code paths that mint the header.
+ // AFTER the quota wording: a spent allowance still advances, with its warning.
+ // Asked of the uid — a display name is never a subscription.
+ if (providerId && isSubscriptionProvider(providerId)) {
+ const recovered = status === 400 ? extractUpstreamStatus(errorBody) : undefined;
+ if (status === 401 || recovered === 401) return false;
+ }
+
// ── Recover the ORIGINAL status from a remapped terminal error (#148) ──────
//
// `composed-handler` remaps terminal upstream failures (401/403/terminal-429)
diff --git a/packages/cli/src/handlers/shared/auth-failure.ts b/packages/cli/src/handlers/shared/auth-failure.ts
new file mode 100644
index 00000000..2d1ed6e7
--- /dev/null
+++ b/packages/cli/src/handlers/shared/auth-failure.ts
@@ -0,0 +1,166 @@
+/**
+ * One classifier for every failure that reaches a credential site, and one way
+ * to answer it.
+ *
+ * ## The rule (project owner, 2026-10-16)
+ *
+ * - A TERMINAL credential failure of a SUBSCRIPTION provider answers 400 with
+ * its message, and the routing chain stops there. It never walks onto a
+ * metered provider: a user whose flat-rate login expired is told to log in,
+ * not silently billed per token by the next hop.
+ * - A TRANSIENT failure (network fault, 5xx, 429) never becomes a 401. A 401 is
+ * the one status `FallbackHandler.isRetryableError` reads as "try another
+ * credential", so a blip answered 401 walked the chain mid-outage.
+ *
+ * ## Why a header carries the verdict
+ *
+ * The status alone cannot: a terminal failure is answered 400 so Claude Code
+ * shows it inline instead of retrying it behind "API error · Retrying", and a
+ * 400 carrying `upstream_status: 401` is exactly what `isRetryableError`'s
+ * remap recovery reads as retryable. So the verdict rides
+ * {@link AUTH_VERDICT_HEADER}, which `isRetryableError` reads BEFORE any status
+ * or wording rule — the same structural pattern as the connection-fault marker
+ * (`recovery-marker.ts`), and unforgeable for the same reason: every non-ok
+ * response of `ComposedHandler` is a `c.json(...)` whose headers Hono builds
+ * from nothing.
+ *
+ * ## The order of classification
+ *
+ * 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.
+ */
+import type { Context } from "hono";
+import type { ContentfulStatusCode } from "hono/utils/http-status";
+import { wrapAnthropicError } from "./anthropic-error.js";
+import { classifyConnectionError } from "./connection-error.js";
+
+/** The header name. Referenced by name in no other file — import this. */
+export const AUTH_VERDICT_HEADER = "x-claudish-auth-verdict";
+
+/**
+ * - `terminal`: the credential cannot succeed on retry; the chain must stop here.
+ * - `transient`: retrying the SAME hop is the remedy; the chain must not walk.
+ */
+export type AuthVerdict = "terminal" | "transient";
+
+/** The headers a response with this verdict carries. */
+export function authVerdictHeaders(verdict: AuthVerdict): Record<string, string> {
+ return { [AUTH_VERDICT_HEADER]: verdict };
+}
+
+/** The verdict a header bag carries, if any. Tolerates `undefined` and non-Headers values. */
+export function authVerdict(headers: Headers | undefined | null): AuthVerdict | undefined {
+ try {
+ const value = headers?.get(AUTH_VERDICT_HEADER);
+ return value === "terminal" || value === "transient" ? value : undefined;
+ } catch {
+ return undefined;
+ }
+}
+
+export type AuthFailure =
+ | { kind: "connection"; conn: NonNullable<ReturnType<typeof classifyConnectionError>> }
+ | { kind: "transient"; status: number; message: string }
+ | { kind: "terminal"; message: string; upstreamStatus?: number }
+ | { kind: "unknown"; message: string };
+
+/** The fields a credential path sets on what it throws. */
+interface ErrorFields {
+ message?: unknown;
+ terminal?: unknown;
+ transient?: unknown;
+ upstreamStatus?: unknown;
+}
+
+/** The status a transient failure carries, from the fields a credential path sets. */
+function transientStatus(e: ErrorFields | undefined): number | undefined {
+ const status = typeof e?.upstreamStatus === "number" ? e.upstreamStatus : undefined;
+ if (status === 429 || (status !== undefined && status >= 500 && status <= 599)) return status;
+ if (e?.transient === true) return status ?? 503;
+ return undefined;
+}
+
+/**
+ * Classify a failure thrown at a credential site. ONE place, in one order:
+ * connection → terminal → transient → unknown.
+ *
+ * Reads only fields a credential path sets on purpose: `classifyConnectionError`
+ * for a network fault, `terminal: true`, `upstreamStatus` (429 or 5xx) or
+ * `transient: true`. The message is never parsed.
+ */
+export function classifyAuthFailure(err: unknown): AuthFailure {
+ const conn = classifyConnectionError(err);
+ if (conn) return { kind: "connection", conn };
+ const e = err as ErrorFields | undefined;
+ const message = typeof e?.message === "string" && e.message ? e.message : String(err);
+ if (e?.terminal === true) {
+ const upstreamStatus = typeof e.upstreamStatus === "number" ? e.upstreamStatus : undefined;
+ return {
+ kind: "terminal",
+ message,
+ ...(upstreamStatus !== undefined ? { upstreamStatus } : {}),
+ };
+ }
+ const status = transientStatus(e);
+ if (status !== undefined) return { kind: "transient", status, message };
+ return { kind: "unknown", message };
+}
+
+/**
+ * Answer a classified credential failure. Never called for `connection`: the
+ * caller recovers those first (and gets `null` back if it does not).
+ *
+ * - terminal → 400 `invalid_request_error`, verdict `terminal`. `upstream_status`
+ * 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 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)
+ * may ask for this; every other site rethrows an unknown metered failure
+ * unchanged rather than invent a status.
+ */
+export function respondAuthFailure(
+ c: Context,
+ failure: AuthFailure,
+ opts: { isSubscription: boolean; providerDisplayName: string }
+): Response | null {
+ switch (failure.kind) {
+ case "connection":
+ return null;
+ case "terminal":
+ return terminalResponse(c, failure.message, failure.upstreamStatus);
+ case "transient": {
+ const status = failure.status === 429 ? 429 : 503;
+ return c.json(
+ wrapAnthropicError(
+ status,
+ `${opts.providerDisplayName} could not confirm the credential (HTTP ${failure.status}): ${failure.message}`,
+ status === 429 ? "rate_limit_error" : "overloaded_error",
+ failure.status
+ ),
+ status as ContentfulStatusCode,
+ authVerdictHeaders("transient")
+ );
+ }
+ case "unknown":
+ if (opts.isSubscription) return terminalResponse(c, failure.message);
+ return c.json(wrapAnthropicError(401, failure.message, "authentication_error"), 401);
+ }
+}
+
+function terminalResponse(c: Context, message: string, upstreamStatus?: number): Response {
+ return c.json(
+ wrapAnthropicError(400, message, "invalid_request_error", upstreamStatus),
+ 400,
+ authVerdictHeaders("terminal")
+ );
+}
diff --git a/packages/cli/src/proxy-server.ts b/packages/cli/src/proxy-server.ts
index e222658e..07883fd4 100644
--- a/packages/cli/src/proxy-server.ts
+++ b/packages/cli/src/proxy-server.ts
@@ -831,7 +831,11 @@ export async function createProxyServer(
// differs (a provider it cannot construct), and the remaining candidates
// are still strictly better than failing the request.
if (handler) {
- candidates.push({ name: DISPLAY_NAMES[parsed.provider] ?? parsed.provider, handler });
+ candidates.push({
+ name: DISPLAY_NAMES[parsed.provider] ?? parsed.provider,
+ provider: parsed.provider,
+ handler,
+ });
}
}
@@ -935,7 +939,11 @@ export async function createProxyServer(
handler = await getRemoteProviderHandler(candidate.modelSpec, invocationMode);
}
if (handler) {
- candidates.push({ name: candidate.displayName, handler });
+ candidates.push({
+ name: candidate.displayName,
+ provider: candidate.provider,
+ handler,
+ });
}
}