Claude Code. Any Model. The most powerful AI coding agent now speaks every language.
fix(routing): advance past a rejected subscription key to metered hops
Jack Rudenko9ace3fe5bf8d
diff --git a/ai-docs/architecture/adapters.md b/ai-docs/architecture/adapters.mdindex 6c04447e..c98b7377 100644--- a/ai-docs/architecture/adapters.md+++ b/ai-docs/architecture/adapters.md@@ -608,7 +608,7 @@ The exclusion rested on "a 503 cannot silently switch the user off a pinned mode(found by the 10.3.0 release review, source-traced; the status alone could not tell aconnection fault from an overload).-### A subscription's credential failure stops the chain (2026-10-16)+### A subscription's credential failure (2026-10-16, replaced 2026-10-21)The `upstream_status` recovery above made a remapped 401/403 advance the chain, on the reasoningthat a revoked key on one provider is exactly when the next should be tried. For a SUBSCRIPTION@@ -628,7 +628,31 @@ tries only the remaining subscription ones. Any failure of those is logged and pserves, the answer is the FIRST rejection's response unchanged (its status, verdict header and"log in" message), never a combined `all_providers_failed`. An explicit spec (`[email protected]`) hasone candidate, so it still stops. A transient verdict, and a terminal verdict from a metered-candidate, still return at once. Tests: `fallback-handler.subscription-only.test.ts`.+candidate, still return at once.++**Replaced 2026-10-21: the chain moves on to its next hop, metered included.** The preflight run of+that day (`ai-docs/reports/model-failures-2026-10-21.md`, D7) showed what the subscription-only+rule cost: one expired subscription key blocked every metered hop of the chain, although the user+had configured those keys. Jack: an expired key must not block the chain; a configured metered key+is consent to be billed by it. So a subscription candidate's terminal verdict (or a headerless+401/403 credential rejection, `isSubscriptionCredentialRejection`) is retryable:+`isRetryableError` returns `true` for both, and `FallbackHandler.handle` advances to the next hop+whatever it bills. `announceCredentialRejection` says so on stderr once per (provider uid,+upstream status) per process, and in the log every time:++```+[claudish] Kimi Coding rejected its credential (401: Invalid token) — moving to OpenRouter (metered, billed per token). The Kimi Coding login was rejected (HTTP 401). Run `claudish login kimi` to sign in again.+```++The next hop's billing comes from `isSubscriptionProvider` on its uid; a hop with no uid reads+metered. When every hop fails, the answer is the usual combined `all_providers_failed`, with the+first rejection's message appended to `error.message` (the per-attempt list clips at 200+characters, which cut the login line off). When the rejection was the only failure, its own+response is returned unchanged. Unchanged and still ahead of this rule: connection verdicts, the+recovery hold and stream failures return before any credential reading, so a network fault never+walks onto metered billing; a transient verdict and a metered hop's terminal verdict return at+once. Billing follows the signing arm of the hop that served. Tests:+`fallback-handler.subscription-only.test.ts`, `fallback-handler.muse-code.test.ts`.**The verdict rides a header, `x-claudish-auth-verdict`** (`terminal` or `transient`), from`handlers/shared/auth-failure.ts`. The status cannot carry it: a terminal failure is answered 400@@ -649,8 +673,8 @@ in one order:| unknown, subscription | anything else | 503 `overloaded_error`, verdict `transient` (retried on the same hop, never walked) || unknown, metered | anything else | 401 at `refreshAuth` and `forceRefreshAuth` only; other sites rethrow |-**The rule: a dead or unsubscribed credential is a terminal 400 that stops the chain; an-unclassified failure is a retryable 503.** It holds because the PRODUCERS say what their failure+**The rule: a dead or unsubscribed credential is a terminal 400 (an explicit spec stops on it; a+chain moves past a subscription's, above); an unclassified failure is a retryable 503.** It holds because the PRODUCERS say what their failureis, through `auth/credentials/credential-error.ts` (`d86e3d86`): a missing login or a rejectedgrant is `terminalCredentialError`, a token host's 429/5xx is `credentialHttpError` (transient,with its `upstreamStatus`). Kimi's "No Kimi OAuth credentials found. Please run `claudish logindiff --git a/ai-docs/architecture/providers/meta-muse-code.md b/ai-docs/architecture/providers/meta-muse-code.mdindex 8624ac3b..b6b18bab 100644--- a/ai-docs/architecture/providers/meta-muse-code.md+++ b/ai-docs/architecture/providers/meta-muse-code.md@@ -335,8 +335,10 @@ continues. A network or transient fault warns and continues.## Classification at the auth sitesThe terminal/transient contract every subscription now follows is in [`adapters.md`](../adapters.md)-("A subscription's credential failure stops the chain"). For `muse@` the consequence is direct: an-expired Muse login answers 400 with the login hint, and the chain never walks onto metered `meta@`.+("A subscription's credential failure"). For `muse@` the consequence is direct: an expired Muse+login answers 400 with the login hint. An explicit `muse@` stops there; since 2026-10-21 a routing+chain moves on to its next hop, metered `meta@` included, with a stderr notice naming that hop and+its billing.`probe-live.ts` lists `meta-muse-code` in `OAUTH_PROVIDERS`. A login-fixable failure gets the`claudish login muse` hint. An unsubscribed account gets `subscribe at <url>` instead.diff --git a/ai-docs/architecture/routing.md b/ai-docs/architecture/routing.mdindex b28aa654..85cae565 100644--- a/ai-docs/architecture/routing.md+++ b/ai-docs/architecture/routing.md@@ -403,11 +403,19 @@ seven chains lost only their subscription hop (`zengo@` for `qwen3.7-max`, `glm-`qwen3.6-plus`, `minimax-m2.5`, `omen-alpha`; `qtoken@` for `deepseek-v3.2`,`deepseek-v4-flash`).-**A subscription's terminal credential failure stops the chain.** An expired or revoked login on-any `SUBSCRIPTION_PROVIDERS` member (and `openai-codex` when its OAuth arm signed) answers 400-with its login hint and never walks onto the next, usually metered, hop. A model the plan does not-carry and a spent allowance still advance. The mechanism is in `adapters.md` ("A subscription's-credential failure stops the chain").+**A subscription's rejected credential moves the chain to its next hop, metered included**+(owner, 2026-10-21). An expired, wrong or revoked credential on any `SUBSCRIPTION_PROVIDERS`+member (and `openai-codex` when its OAuth arm signed) answers 400 with its login hint and the+terminal verdict. An explicit spec stops there. A routing chain moves on to its next hop, whatever+that hop bills, and prints one stderr notice per provider and upstream status naming the next hop+and its billing (`subscription` or `metered, billed per token`) with the login or renewal hint.+The reason: an expired key must not block the chain, and a metered key the user configured is+consent to be billed by it. The rule it replaced (2026-10-16, amended 2026-10-20) stopped the+chain, then tried only later subscription hops, so one stale key on a plan the user had stopped+paying for hid every metered key they held. Billing follows the signing arm of the hop that+served. Connection faults, the recovery hold and stream failures still hold the chain, so a network+fault never walks onto metered billing. The mechanism is in `adapters.md` ("A subscription's+credential failure").The backend recommendation projection supplies canonical model IDs and exactroute/profile identities. Claudish resolves them against the generation-pinneddiff --git a/packages/cli/src/handlers/composed-handler.ts b/packages/cli/src/handlers/composed-handler.tsindex a9525c5f..5b68174b 100644--- a/packages/cli/src/handlers/composed-handler.ts+++ b/packages/cli/src/handlers/composed-handler.ts@@ -2644,10 +2644,11 @@ 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.+ // A SUBSCRIPTION's rejected credential carries the terminal verdict+ // (`auth-failure.ts`): an explicit spec stops with the login hint, and+ // a routing chain moves to its next hop with a notice naming that+ // hop's billing (`FallbackHandler`). A spent allowance (402/429) is+ // not a credential failure and advances with its own warning.// A model the provider does not carry (Zen Go's 401 "Model <id> is not// supported") is NOT a credential rejection and keeps advancing.const verdictHeaders =diff --git a/packages/cli/src/handlers/fallback-handler.muse-code.test.ts b/packages/cli/src/handlers/fallback-handler.muse-code.test.tsindex 08fb8666..9aaf9d83 100644--- a/packages/cli/src/handlers/fallback-handler.muse-code.test.ts+++ b/packages/cli/src/handlers/fallback-handler.muse-code.test.ts@@ -94,7 +94,9 @@ afterAll(() => {}rmSync(testHome, { recursive: true, force: true });});-const { FallbackHandler, isRetryableError } = await import("./fallback-handler.js");+const { FallbackHandler, isRetryableError, _resetCredentialRejectionNotices } = await import(+ "./fallback-handler.js"+);import { authVerdictHeaders } from "./shared/auth-failure.js";const subscriptions = [@@ -115,9 +117,12 @@ const rejection = JSON.stringify({error: { type: "invalid_api_key", message: "Unauthorized", upstream_status: 401 },});-describe("B1: routing-chain stop decisions", () => {+// Owner rule 2026-10-21: a subscription's rejected credential advances to the+// next hop, metered included; a transient verdict still holds. (These tests+// pinned the earlier stop and were updated.)+describe("B1: routing-chain decisions on a subscription credential verdict", () => {test.each(subscriptions)(- "%s holds terminal/transient verdicts before status recovery",+ "%s advances a terminal verdict and holds a transient one before status recovery",(provider) => {for (const verdict of ["terminal", "transient"] as const) {for (const upstream of [401, 403]) {@@ -132,13 +137,13 @@ describe("B1: routing-chain stop decisions", () => {new Headers(authVerdictHeaders(verdict)),provider)- ).toBe(false);+ ).toBe(verdict === "terminal");}}});- test.each(subscriptions)("%s stops a credential rejection without a verdict", (provider) => {- expect(isRetryableError(401, rejection, provider, new Headers(), provider)).toBe(false);+ test.each(subscriptions)("%s advances a credential rejection without a verdict", (provider) => {+ expect(isRetryableError(401, rejection, provider, new Headers(), provider)).toBe(true);});test("metered Meta 401 remains eligible to advance", () => {expect(isRetryableError(401, rejection, "meta", new Headers(), "meta")).toBe(true);@@ -231,13 +236,14 @@ async function twoHop(provider: string, firstResponse: () => Response) {}}-describe("B1: actual two-hop subscription stops", () => {+describe("B1: actual two-hop chain after a subscription credential verdict", () => {test.each([...subscriptions, "openai-codex"])(- "%s never calls metered Meta on auth failure",+ "%s moves on to metered Meta, announced, on a rejected credential",async (provider) => {recordSignedArm("openai-codex", "subscription");for (const verdict of ["terminal", "transient"] as const) {for (const upstream of [401, 403]) {+ _resetCredentialRejectionNotices();const result = await twoHop(provider,() =>@@ -251,19 +257,26 @@ describe("B1: actual two-hop subscription stops", () => {{ status: verdict === "terminal" ? 400 : 503, headers: authVerdictHeaders(verdict) }));- expect(result.status).toBe(verdict === "terminal" ? 400 : 503);- expect(result.verdict).toBe(verdict);- expect(result.body).toContain("login muse");expect(result.firstCalls).toBe(1);- expect(result.meteredCalls).toBe(0);+ if (verdict === "terminal") {+ expect(result.status).toBe(200);+ expect(result.body).toBe("metered success");+ expect(result.meteredCalls).toBe(1);+ expect(result.warnings).toContain("meta@fixture (metered, billed per token)");+ } else {+ expect(result.status).toBe(503);+ expect(result.verdict).toBe("transient");+ expect(result.body).toContain("login muse");+ expect(result.meteredCalls).toBe(0);+ }}}for (const upstream of [401, 403]) {const result = await twoHop(provider, () => new Response(rejection, { status: upstream }));- expect(result.status).not.toBe(200);- expect(result.body).toContain("Unauthorized");+ expect(result.status).toBe(200);+ expect(result.body).toBe("metered success");expect(result.firstCalls).toBe(1);- expect(result.meteredCalls).toBe(0);+ expect(result.meteredCalls).toBe(1);}});diff --git a/packages/cli/src/handlers/fallback-handler.subscription-only.test.ts b/packages/cli/src/handlers/fallback-handler.subscription-only.test.tsindex 3027acc5..553b1c4a 100644--- a/packages/cli/src/handlers/fallback-handler.subscription-only.test.ts+++ b/packages/cli/src/handlers/fallback-handler.subscription-only.test.ts@@ -180,8 +180,11 @@ const subscriptions = ["grok-subscription",];-describe("subscription-only routing after a login failure", () => {- test("rule 1: either login failure skips every later metered candidate", async () => {+// Owner rule 2026-10-21: a subscription's rejected credential advances the+// chain to its NEXT hop, metered included. (Until then only later+// subscription hops were tried; these tests pinned that and were updated.)+describe("routing after a subscription credential rejection", () => {+ test("rule 1: either rejection advances to the next hop, metered included", async () => {for (const provider of subscriptions) {for (const failure of loginFailures) {const result = await runChain([@@ -193,14 +196,14 @@ describe("subscription-only routing after a login failure", () => {},{ provider: "z-ai", response: new Response("metered z-ai success") },]);- expect(result.calls).toEqual([1, 0, 1, 0]);+ expect(result.calls).toEqual([1, 1, 0, 0]);expect(result.status).toBe(200);- expect(result.body).toBe("remaining subscription success");+ expect(result.body).toBe("metered glm success");}}});- test("rule 2: returns the later subscription's successful response", async () => {+ test("rule 2: returns the next subscription's successful response", async () => {const body = JSON.stringify({ answer: "served by kimi-coding" });const result = await runChain([{ provider: "opencode-zen-go", response: terminalLoginFailure() },@@ -212,47 +215,37 @@ describe("subscription-only routing after a login failure", () => {expect(result.calls).toEqual([1, 1, 0]);});- test("rule 3: later login, usage-limit, and server failures continue to subscriptions", async () => {+ test("rule 3: later hops follow the ordinary retry rules", async () => {const laterFailures = [() => terminalLoginFailure("Later subscription login failed"),rawLoginFailure,usageLimit,- () => new Response("Internal Server Error", { status: 500 }),];for (const laterFailure of laterFailures) {const result = await runChain([{ provider: "opencode-zen-go", response: terminalLoginFailure() },- { provider: "deepseek", response: new Response("metered deepseek success") },{ provider: "kimi-coding", response: laterFailure() },- { provider: "openrouter", response: new Response("metered openrouter success") },+ { provider: "deepseek", response: new Response("metered deepseek success") },{ provider: "qwen-token-plan", response: new Response("subscription success") },- { provider: "poe", response: new Response("metered poe success") },]);expect(result.status).toBe(200);- expect(result.body).toBe("subscription success");- expect(result.calls).toEqual([1, 0, 1, 0, 1, 0]);+ expect(result.body).toBe("metered deepseek success");+ expect(result.calls).toEqual([1, 1, 1, 0]);}});- test("rule 4: exhausted subscriptions return the first login failure unchanged", async () => {+ test("rule 4: an exhausted chain keeps the first rejection's message", async () => {for (const failure of loginFailures) {- const firstFailure = failure.response();- const firstBody = await firstFailure.clone().text();const result = await runChain([- { provider: "opencode-zen-go", response: firstFailure },- { provider: "meta", response: new Response("metered meta success") },+ { provider: "opencode-zen-go", response: failure.response() },{ provider: "kimi-coding", response: terminalLoginFailure("Later login failed") },{ provider: "qwen-token-plan", response: usageLimit() },- { provider: "glm-coding", response: new Response("Server failure", { status: 500 }) },- { provider: "openrouter", response: new Response("metered openrouter success") },+ { provider: "openrouter", response: new Response("Not found", { status: 404 }) },]);- expect(result.status).toBe(failure.status);- expect(result.verdict).toBe(failure.verdict);- expect(result.body).toBe(firstBody);- expect(result.body).toContain(failure.message);- expect(result.body).not.toContain("all_providers_failed");- expect(result.body).not.toContain("Later login failed");- expect(result.calls).toEqual([1, 0, 1, 1, 1, 0]);+ expect(result.status).toBe(400);+ expect(result.body).toContain("all_providers_failed");+ expect(JSON.parse(result.body).error.message).toContain(failure.message);+ expect(result.calls).toEqual([1, 1, 1, 1]);}});@@ -307,17 +300,14 @@ describe("subscription-only routing after a login failure", () => {const result = await runChain([{ provider: "glm-coding", response: usageLimit() },{ provider: "opencode-zen-go", response: terminalLoginFailure() },- { provider: "glm", response: new Response("metered glm success") },{ provider: "kimi-coding", response: rawLoginFailure() },- { provider: "z-ai", response: new Response("metered z-ai success") },{ provider: "minimax-coding", response: usageLimit() },- { provider: "qwen-coding", response: new Response("Server failure", { status: 500 }) },+ { provider: "glm", response: new Response("metered glm success") },{ provider: "qwen-token-plan", response: new Response("subscription success") },- { provider: "poe", response: new Response("metered poe success") },]);expect(result.status).toBe(200);- expect(result.body).toBe("subscription success");- expect(result.calls).toEqual([1, 1, 0, 1, 0, 1, 1, 1, 0]);+ expect(result.body).toBe("metered glm success");+ expect(result.calls).toEqual([1, 1, 1, 1, 1, 0]);for (const count of result.calls) expect(count).toBeLessThanOrEqual(1);});@@ -340,14 +330,14 @@ describe("subscription-only routing after a login failure", () => {expect(result.calls).toEqual([1, 1, 1, 0, 0]);});- test("real interleaved chain: terminal Zen Go skips metered DeepSeek before Qwen", async () => {+ test("real interleaved chain: rejected Zen Go key moves on to metered DeepSeek", async () => {const result = await runChain([{ provider: "opencode-zen-go", response: terminalLoginFailure() },{ provider: "deepseek", response: new Response("metered deepseek success") },{ provider: "qwen-token-plan", response: new Response("qwen-token-plan success") },]);expect(result.status).toBe(200);- expect(result.body).toBe("qwen-token-plan success");- expect(result.calls).toEqual([1, 0, 1]);+ expect(result.body).toBe("metered deepseek success");+ expect(result.calls).toEqual([1, 1, 0]);});});diff --git a/packages/cli/src/handlers/fallback-handler.ts b/packages/cli/src/handlers/fallback-handler.tsindex bf987e67..b9f49d6b 100644--- a/packages/cli/src/handlers/fallback-handler.ts+++ b/packages/cli/src/handlers/fallback-handler.ts@@ -10,9 +10,9 @@*/import type { Context } from "hono";-import { logStderr } from "../logger.js";+import { log, logStderr } from "../logger.js";import { redactForClient } from "../redact.js";-import { ComposedHandler } from "./composed-handler.js";+import { ComposedHandler, getRecoveryHint } from "./composed-handler.js";import { extractUpstreamStatus } from "./shared/anthropic-error.js";import { authVerdict, isCredentialRejection } from "./shared/auth-failure.js";import { abortedResponse, callAborted } from "./shared/call-context.js";@@ -56,16 +56,16 @@ export class FallbackHandler implements ModelHandler {async handle(c: Context, payload: any): Promise<Response> {const errors: Array<{ provider: string; status: number; message: string }> = [];const startIndex = this.lastSuccessIndex;- // Set by the first subscription candidate whose login is rejected. From- // then on only subscription candidates are tried, and this response is the- // answer if none of them serves.- let credentialStop: Response | undefined;+ // The first subscription candidate whose credential was rejected. The chain+ // moves past it like any retryable failure; this is kept because its+ // message (log in again, renew the key) is the one a user can act on, so+ // an exhausted chain still shows it.+ let firstRejection: { name: string; response: Response; body: string } | undefined;for (let attempt = 0; attempt < this.candidates.length; attempt++) {const idx = (startIndex + attempt) % this.candidates.length;const { name, handler, provider } = this.candidates[idx];const isLast = attempt === this.candidates.length - 1;- if (credentialStop && !(provider && isSubscriptionProvider(provider))) continue;// An internal call whose deadline passed (call-context.ts) never reaches// another hop. Never true for a request from Claude Code.if (callAborted(c)) return abortedResponse();@@ -160,11 +160,14 @@ export class FallbackHandler implements ModelHandler {// header was dropped. A terminal verdict keeps its exact message and// `upstream_status` the same way (`auth-failure.ts`).//- // One exception, for a TERMINAL verdict on a subscription: the chain- // moves on to its remaining SUBSCRIPTION candidates, never a metered one- // (project owner, 2026-10-20). A bare `glm-5.3` whose Zen Go key expired- // is served by the Token Plan the user also holds, not stopped and not- // billed per token.+ // One exception, for a TERMINAL verdict on a subscription (an expired,+ // wrong or revoked credential): the chain moves on to its next hop,+ // metered included (project owner, 2026-10-21). An expired key must not+ // block the chain, and a metered key the user configured is consent to+ // be billed by it. The move is announced, once per provider and status+ // (`announceCredentialRejection`). The connection, recovery-hold and+ // stream-failure verdicts above still answer first, so a network fault+ // never walks onto metered billing.const verdict = authVerdict(response.headers);const subscriptionRejected =verdict === "terminal" && !!provider && isSubscriptionProvider(provider);@@ -185,32 +188,20 @@ export class FallbackHandler implements ModelHandler {isSubscriptionCredentialRejection(response.status, errorBody, provider)) {errors.push({ provider: name, status: response.status, message: errorBody });- if (!credentialStop) {- credentialStop = response;- logStderr(- `[Fallback] ${name}: subscription login rejected — trying the chain's other subscription providers only; metered providers are skipped.`- );+ if (!firstRejection) firstRejection = { name, response, body: errorBody };+ if (!isLast) {+ const next = this.candidates[(idx + 1) % this.candidates.length];+ announceCredentialRejection({ name, provider }, response.status, errorBody, next);}continue;}- // A later subscription candidate that fails in any other way does not- // end the search either: the answer, if none serves, is the login- // failure that started it.- if (credentialStop) {- errors.push({ provider: name, status: response.status, message: errorBody });- logStderr(- `[Fallback] ${name} failed (HTTP ${response.status}), trying the next subscription provider...`- );- continue;- }-// Non-retryable error (rate limit, server error, bad format) — stop tryingif (!isRetryableError(response.status, errorBody, name, response.headers, provider)) {if (errors.length > 0) {// We had previous fallback attempts; show combined errorerrors.push({ provider: name, status: response.status, message: errorBody });- return this.formatCombinedError(c, errors, payload.model);+ return this.formatCombinedError(c, errors, payload.model, firstRejection);}// First and only attempt — return original response as-isreturn response;@@ -246,23 +237,27 @@ export class FallbackHandler implements ModelHandler {}}- // No subscription served after a login failure: the user is told to renew- // that login, with its own message and verdict, not shown a combined error.- if (credentialStop) {- logStderr(- `[Fallback] No subscription provider could serve ${payload.model || "the model"}; metered providers were skipped.`- );- return credentialStop;- }+ // The rejected credential was the only failure (a chain whose other hops+ // were never reached): answered as a chain of one would be, with its own+ // message, status and verdict.+ if (firstRejection && errors.length === 1) return firstRejection.response;// All providers failed- return this.formatCombinedError(c, errors, payload.model);+ return this.formatCombinedError(c, errors, payload.model, firstRejection);}+ /**+ * The combined answer of an exhausted chain. When a subscription's+ * credential was rejected on the way, its message leads: the later hops'+ * failures (a missing key, a model they do not carry) are not what the user+ * can fix, and the per-attempt list clips each message at 200 characters,+ * which cut the `claudish login …` line off.+ */private formatCombinedError(c: Context,errors: Array<{ provider: string; status: number; message: string }>,- modelName?: string+ modelName?: string,+ firstRejection?: { name: string; body: string }): Response {const summary = errors.map(@@ -271,15 +266,20 @@ export class FallbackHandler implements ModelHandler {).join("\n");+ const rejection = firstRejection+ ? ` First, ${firstRejection.name} rejected its credential: ${parseErrorMessage(redactForClient(firstRejection.body))}`+ : "";+logStderr(- `[Fallback] All ${errors.length} provider(s) failed for ${modelName || "model"}:\n${summary}`+ `[Fallback] All ${errors.length} provider(s) failed for ${modelName || "model"}:\n${summary}` ++ (rejection ? `\n ${rejection.trim()}` : ""));return c.json({error: {type: "all_providers_failed",- message: `All ${errors.length} providers failed for model '${modelName || "unknown"}'`,+ message: `All ${errors.length} providers failed for model '${modelName || "unknown"}'${rejection ? `.${rejection}` : ""}`,attempts: errors.map((e) => ({provider: e.provider,status: e.status,@@ -331,6 +331,60 @@ export function isSubscriptionCredentialRejection(return status === 403 && isCredentialRejection(403, errorBody);}+/** `<provider uid>|<upstream status>` of every rejection already announced on stderr. */+const announcedRejections = new Set<string>();++/** Test seam: forget which credential rejections were announced. */+export function _resetCredentialRejectionNotices(): void {+ announcedRejections.clear();+}++/** The billing words for a hop the chain moves to; a hop of unknown billing reads metered. */+function hopBillingWords(provider: string | undefined): string {+ return provider && isSubscriptionProvider(provider)+ ? "subscription"+ : "metered, billed per token";+}++/**+ * Say that a subscription's credential was rejected and which hop the chain+ * moves to, and how that hop bills. The user did not choose the move (claudish+ * assembled the chain), and the next hop may bill per token, so it is said on+ * stderr, once per provider and upstream status per process; every occurrence+ * is written to the log. The provider message has already been redacted for+ * the client by `ComposedHandler`; it is redacted again here, and `logStderr`+ * redacts the request's signing values.+ */+export function announceCredentialRejection(+ rejected: { name: string; provider?: string },+ status: number,+ errorBody: string,+ next: { name: string; provider?: string }+): void {+ const upstreamStatus = (status === 400 ? extractUpstreamStatus(errorBody) : undefined) ?? status;+ const providerMessage = truncate(+ parseProviderMessage(redactForClient(errorBody)).replace(/\s+/g, " ").trim(),+ 300+ );+ const hint = getRecoveryHint(+ upstreamStatus,+ errorBody,+ rejected.name,+ undefined,+ rejected.provider+ );+ const line =+ `${rejected.name} rejected its credential (${upstreamStatus}: ${providerMessage}) — ` ++ `moving to ${next.name} (${hopBillingWords(next.provider)}). ${hint}`;+ const key = `${rejected.provider ?? rejected.name}|${upstreamStatus}`;+ if (announcedRejections.has(key)) {+ log(`[Fallback] ${line}`);+ return;+ }+ announcedRejections.add(key);+ logStderr(line);+}+/*** Determine if an HTTP error is retryable (should try next provider).* Auth errors, billing errors, rate limits, model-not-found errors and an@@ -369,17 +423,21 @@ export function isRetryableError(// the same reason as the line above.if (hasStreamFailureMarker(headers)) return false;- // ── A CREDENTIAL VERDICT IS NEVER A REASON TO ADVANCE EITHER ──────────────+ // ── A CREDENTIAL VERDICT: TERMINAL ON A SUBSCRIPTION ADVANCES, ELSE HOLDS ──//// `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+ // (`auth-failure.ts`): `terminal` — a credential 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;+ // own retry, so the next candidate is the wrong remedy for it. A terminal+ // verdict on a SUBSCRIPTION hop (an expired, wrong or revoked credential)+ // advances to the next hop, metered included (project owner, 2026-10-21:+ // an expired key must not block the chain). A terminal verdict on any other+ // hop still holds. Above the quota wording and the `upstream_status`+ // recovery below, because a terminal 400 carries `upstream_status: 401`,+ // which that recovery reads as retryable whatever the hop.+ const verdict = authVerdict(headers);+ if (verdict) return verdict === "terminal" && !!providerId && isSubscriptionProvider(providerId);// A spent subscription allowance is retryable AT THE CHAIN LEVEL: this// provider cannot serve, but the next one can.@@ -415,11 +473,9 @@ export function isRetryableError(// prevented at the cost of the request.if (hasQuotaExhaustionWording(errorBody)) return true;- // A SUBSCRIPTION's 401 never advances in the ordinary way, whatever its- // transport answered. AFTER the quota wording: a spent allowance still- // advances, with its warning. `handle()` moves such a rejection on to the- // chain's remaining subscription candidates only.- if (isSubscriptionCredentialRejection(status, errorBody, providerId)) return false;+ // A SUBSCRIPTION's rejected credential, answered without the verdict header,+ // advances like the terminal verdict above (`handle()` announces it).+ if (isSubscriptionCredentialRejection(status, errorBody, providerId)) return true;// ── Recover the ORIGINAL status from a remapped terminal error (#148) ──────//@@ -681,6 +737,22 @@ export function isProvider(provider: string | undefined, needle: string): boolea.includes(needle);}+/**+ * The upstream's own words from a claudish error body (`provider_message`,+ * which carries no hint, provider name or status), else its message.+ */+function parseProviderMessage(body: string): string {+ try {+ const parsed = JSON.parse(body);+ if (typeof parsed?.error?.provider_message === "string" && parsed.error.provider_message) {+ return parsed.error.provider_message;+ }+ } catch {+ // Not JSON — fall through+ }+ return parseErrorMessage(body);+}+/** Extract a human-readable message from a JSON error body */function parseErrorMessage(body: string): string {try {diff --git a/packages/cli/src/handlers/shared/auth-failure.ts b/packages/cli/src/handlers/shared/auth-failure.tsindex 3af889d0..f4f87ff9 100644--- a/packages/cli/src/handlers/shared/auth-failure.ts+++ b/packages/cli/src/handlers/shared/auth-failure.ts@@ -2,14 +2,14 @@* One classifier for every failure that reaches a credential site, and one way* to answer it.*- * ## The rule (project owner, 2026-10-16)+ * ## The rule (project owner, 2026-10-16, amended 2026-10-21)** - A TERMINAL credential failure of a SUBSCRIPTION provider answers 400 with- * its message. 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. The routing chain tries only its remaining SUBSCRIPTION- * candidates, and answers with this failure if none serves (2026-10-20,- * `FallbackHandler.handle`).+ * its message and the terminal verdict. An explicit spec stops there and the+ * user is told to log in. In a routing chain, `FallbackHandler.handle` moves+ * on to the next hop, metered included, and says so on stderr with the next+ * hop's billing (2026-10-21: an expired key must not block the chain; a+ * metered key the user configured is consent to be billed by it).* - 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.@@ -51,7 +51,8 @@ import { isQuotaExhaustionError } from "./quota-exhaustion.js";export const AUTH_VERDICT_HEADER = "x-claudish-auth-verdict";/**- * - `terminal`: the credential cannot succeed on retry; the chain must stop here.+ * - `terminal`: the credential cannot succeed on retry. A metered hop stops the chain+ * here; a subscription hop is moved past, with a notice (`FallbackHandler`).* - `transient`: retrying the SAME hop is the remedy; the chain must not walk.*/export type AuthVerdict = "terminal" | "transient";@@ -102,7 +103,8 @@ export type AuthFailure =* (measured 2026-08-19, `model-unsupported.ts`). Read from the provider's* own error TYPE, which names a region rather than a credential.*- * Only what is left is a credential verdict that stops the chain.+ * Only what is left is a credential verdict: the terminal 400 that stops an+ * explicit spec, and that a routing chain announces as it moves to the next hop.*/export function isCredentialRejection(status: number, errorBody: string): boolean {if (status !== 401 && status !== 403) return false;@@ -116,8 +118,8 @@ export function isCredentialRejection(status: number, errorBody: string): boolea* The provider's own `error.type` in a raw upstream JSON error body. Read at* the sites that hold the upstream body (the generic remap, settleAuthRetry);* claudish's remapped 400 does not carry it. FallbackHandler's own- * subscription rule therefore stops on a RAW 403 (whose body still carries the- * type, so a 403 RegionError advances) and not on a recovered one.+ * subscription rule therefore treats a RAW 403 as a rejection (whose body still+ * carries the type, so a 403 RegionError is a per-model miss) and not a recovered one.*/function providerErrorType(errorBody: string): string | undefined {try {diff --git a/packages/cli/src/providers/meta-muse/muse-reporting.test.ts b/packages/cli/src/providers/meta-muse/muse-reporting.test.tsindex faa372cc..7acf01ab 100644--- a/packages/cli/src/providers/meta-muse/muse-reporting.test.ts+++ b/packages/cli/src/providers/meta-muse/muse-reporting.test.ts@@ -495,7 +495,7 @@ async function responseScenario({ name: "[email protected]", provider: "meta", handler: {handle: async () => {await credentials.getRequestAuth("meta", { model: "muse-spark-1.3" });- return new Response("unexpected metered fallback");+ return new Response("metered fallback");}, shutdown: async () => {},} },]);@@ -630,18 +630,18 @@ describe("revision 2: HTTP reporting and terminal routing", () => {for (const status of [401, 403]) {for (const kind of ["own-login", "borrowed-copy"] as const) {- test(`${kind} mint ${status}: terminal 400 keeps status and file without metered signing`, async () => {+ // Owner rule 2026-10-21: a rejected subscription login moves a routing+ // chain on to its next hop, metered included. This test pinned the+ // earlier stop (no metered signing) and was updated.+ test(`${kind} mint ${status}: the chain moves past the rejected login to metered Meta and keeps the file`, async () => {const result = await responseScenario("rejected", status, kind);const response = result.results[0];- expect(response.status).toBe(400);- expect(response.verdict).toBe("terminal");- expect(response.upstreamStatus).toBe(status);- expect(JSON.parse(response.body).error.upstream_status).toBe(status);- expect(response.body).toContain(rejectedMessage(status));+ expect(response.status).toBe(200);+ expect(response.body).toBe("metered fallback");expect(response.body).not.toContain("dca:");expect(result.fileKept).toBe(true);expect(result.mintTokens).toEqual([kind === "own-login" ? OWN : BORROWED]);- expect(result.meteredSigns).toBe(0);+ expect(result.meteredSigns).toBe(1);expect(result.inferenceCalls).toBe(0);expect(result.keychainUses).toBe(0);expect(result.valueReads).toBe(0);