Claude Code. Any Model. The most powerful AI coding agent now speaks every language.
fix(routing): try other subscriptions after a subscription login fails
Jack Rudenko8c069277c153
diff --git a/ai-docs/architecture/adapters.md b/ai-docs/architecture/adapters.mdindex a3e38720..4b55d493 100644--- a/ai-docs/architecture/adapters.md+++ b/ai-docs/architecture/adapters.md@@ -445,6 +445,19 @@ walked onto the next hop, usually metered, and never told to log in. Jack's decicredential failure of any subscription provider stops with its message, and a transient faultnever becomes a 401. This narrows the "strictly additive" property for exactly that case.+**Amended 2026-10-20: the chain moves on to the other SUBSCRIPTIONS, never to a metered hop.**+The Bench run of that day (`ai-docs/reports/recommended-models-bench-run-20261020.md`) showed the+stop costing availability the rule was never meant to cost: a bare `glm-5.3` whose Zen Go key had+expired stopped dead although the Qwen Token Plan, also a subscription, was two hops later. Jack:+"it should not go to metered providers, but that models has native subscription". So after a+subscription candidate's terminal verdict (or a headerless 401/403 credential rejection,+`isSubscriptionCredentialRejection`), `FallbackHandler.handle` skips every metered candidate and+tries only the remaining subscription ones. Any failure of those is logged and passed over; if none+serves, 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]`) has+one 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`.+**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 400so Claude Code shows it inline, and a 400 with `upstream_status: 401` is precisely what thediff --git a/packages/cli/src/handlers/fallback-handler.subscription-only.test.ts b/packages/cli/src/handlers/fallback-handler.subscription-only.test.tsnew file mode 100644index 00000000..3027acc5--- /dev/null+++ b/packages/cli/src/handlers/fallback-handler.subscription-only.test.ts@@ -0,0 +1,353 @@+import { afterAll, afterEach, beforeEach, describe, expect, test } from "bun:test";+import { mkdtempSync, rmSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { Hono } from "hono";++const savedEnvironment = new Map(+ ["CLAUDISH_DISABLE_KEYCHAIN", "API_TIMEOUT_MS"].map((k) => [k, process.env[k]])+);+const testHome = mkdtempSync(join(tmpdir(), "claudish-subscription-only-"));+process.env.CLAUDISH_DISABLE_KEYCHAIN = "1";+const realFetch = globalThis.fetch;+const keychain = await import("../providers/keychain.js");+const fakeKeychainDeps = {+ platform: () => "darwin",+ run: () => ({ code: 44, stdout: "", stderr: "test: absent" }),+ runAsync: async () => ({ code: 44, stdout: "", stderr: "test: absent" }),+ spawnAsync: () => ({+ done: Promise.resolve({ code: 44, stdout: "", stderr: "test: absent" }),+ pid: undefined,+ }),+};+keychain.setKeychainTestDeps(fakeKeychainDeps);+beforeEach(() => {+ keychain.setKeychainTestDeps(fakeKeychainDeps);+});+afterEach(() => {+ keychain.setKeychainTestDeps(null);+ keychain.invalidateKeychainCache();+});+const guardedFetch = Object.assign(+ (input: Parameters<typeof fetch>[0], init?: Parameters<typeof fetch>[1]) => {+ const url = new URL(input instanceof Request ? input.url : String(input));+ if (url.hostname === "127.0.0.1" && url.protocol === "http:") return realFetch(input, init);+ throw new Error(`Unexpected external request: ${url.origin}${url.pathname}`);+ },+ { preconnect: () => {} }+) as typeof fetch;+globalThis.fetch = guardedFetch;+const { credentials } = await import("../auth/credentials/authority.js");+const { clearSignedArm } = await import("../auth/credentials/billing-probe.js");+const core = await import("../providers/meta-muse/muse-credentials.js");+const museKeychain = await import("../providers/meta-muse/muse-keychain.js");+const roles = await import("../auth/credentials/prompt-role.js");+const catalog = await import("../providers/catalog-client.js");+const cache = await import("../providers/all-models-cache.js");+// Every seam is a complete fake: omitted fields would restore machine defaults.+beforeEach(() => {+ core.setMuseCoreTestDeps({+ dir: () => testHome,+ now: () => 1_800_000_000_000,+ readStore: () => null,+ writeBorrowedCopy: () => {+ throw new Error("unexpected borrowed-copy write");+ },+ mint: async () => {+ throw new Error("unexpected Muse mint");+ },+ keychainLogin: async () => ({ kind: "not-allowed" }),+ });+ museKeychain.setMuseKeychainTestDeps({+ dir: () => testHome,+ env: () => ({}),+ now: () => 1_800_000_000_000,+ sleep: async () => {+ throw new Error("unexpected Muse Keychain wait");+ },+ pid: () => 424242,+ isAlive: () => false,+ presence: async () => ({ kind: "absent" }),+ startRead: () => ({ done: Promise.resolve({ kind: "absent" as const }), pid: undefined }),+ });+});+afterEach(() => {+ globalThis.fetch = guardedFetch;+ credentials.invalidate();+ clearSignedArm();+ core.setMuseCoreTestDeps(null);+ core.resetMuseCredentialState();+ museKeychain.setMuseKeychainTestDeps(null);+ museKeychain.resetMuseKeychainState();+ roles._resetCredentialPromptRoleForTest();+ catalog._resetCatalogClient();+ cache._clearAllModelsCacheMemo();+ keychain.invalidateKeychainCache();+});+afterAll(() => {+ globalThis.fetch = realFetch;+ keychain.setKeychainTestDeps(null);+ keychain.invalidateKeychainCache();+ for (const [key, value] of savedEnvironment) {+ if (value === undefined) delete process.env[key];+ else process.env[key] = value;+ }+ rmSync(testHome, { recursive: true, force: true });+});+const { FallbackHandler } = await import("./fallback-handler.js");+import { authVerdictHeaders } from "./shared/auth-failure.js";++function terminalLoginFailure(message = "This API key has expired.") {+ return new Response(JSON.stringify({ error: { message, upstream_status: 401 } }), {+ status: 400,+ headers: authVerdictHeaders("terminal"),+ });+}++function rawLoginFailure() {+ return new Response(+ JSON.stringify({ error: { type: "invalid_api_key", message: "Unauthorized" } }),+ { status: 401 }+ );+}++function usageLimit() {+ return new Response(JSON.stringify({ error: { message: "usage limit reached" } }), {+ status: 429,+ });+}++const loginFailures = [+ {+ response: terminalLoginFailure,+ status: 400,+ verdict: "terminal",+ message: "This API key has expired.",+ },+ { response: rawLoginFailure, status: 401, verdict: null, message: "Unauthorized" },+];++async function runChain(candidates: { provider: string; response: Response }[]) {+ const calls = candidates.map(() => 0);+ const originalWrite = process.stderr.write;+ process.stderr.write = ((_chunk: unknown, ..._rest: unknown[]) => {+ return true;+ }) as typeof process.stderr.write;+ const chain = new FallbackHandler(+ candidates.map(({ provider, response }, index) => ({+ name: `${provider}@subscription-only-test-${index}`,+ provider,+ handler: {+ handle: async () => {+ calls[index]++;+ return response;+ },+ shutdown: async () => {},+ },+ }))+ );+ try {+ const app = new Hono();+ app.post("/", (c) =>+ chain.handle(c, {+ model: "glm-5.3",+ messages: [{ role: "user", content: "PONG" }],+ })+ );+ const response = await app.request("http://localhost/", { method: "POST" });+ return {+ status: response.status,+ verdict: response.headers.get("x-claudish-auth-verdict"),+ body: await response.text(),+ calls,+ };+ } finally {+ process.stderr.write = originalWrite;+ await chain.shutdown();+ }+}++const subscriptions = [+ "glm-coding",+ "opencode-zen-go",+ "qwen-token-plan",+ "kimi-coding",+ "minimax-coding",+ "qwen-coding",+ "devin",+ "antigravity",+ "sakana-subscription",+ "grok-subscription",+];++describe("subscription-only routing after a login failure", () => {+ test("rule 1: either login failure skips every later metered candidate", async () => {+ for (const provider of subscriptions) {+ for (const failure of loginFailures) {+ const result = await runChain([+ { provider, response: failure.response() },+ { provider: "glm", response: new Response("metered glm success") },+ {+ provider: provider === "qwen-token-plan" ? "kimi-coding" : "qwen-token-plan",+ response: new Response("remaining subscription success"),+ },+ { provider: "z-ai", response: new Response("metered z-ai success") },+ ]);+ expect(result.calls).toEqual([1, 0, 1, 0]);+ expect(result.status).toBe(200);+ expect(result.body).toBe("remaining subscription success");+ }+ }+ });++ test("rule 2: returns the later subscription's successful response", async () => {+ const body = JSON.stringify({ answer: "served by kimi-coding" });+ const result = await runChain([+ { provider: "opencode-zen-go", response: terminalLoginFailure() },+ { provider: "kimi-coding", response: new Response(body, { status: 200 }) },+ { provider: "meta", response: new Response("metered success") },+ ]);+ expect(result.status).toBe(200);+ expect(result.body).toBe(body);+ expect(result.calls).toEqual([1, 1, 0]);+ });++ test("rule 3: later login, usage-limit, and server failures continue to subscriptions", 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: "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]);+ }+ });++ test("rule 4: exhausted subscriptions return the first login failure unchanged", 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: "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") },+ ]);+ 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]);+ }+ });++ test("rule 5: a transient subscription verdict returns without advancing", async () => {+ const body = JSON.stringify({+ error: { message: "Subscription login temporarily unavailable" },+ });+ const result = await runChain([+ {+ provider: "opencode-zen-go",+ response: new Response(body, { status: 503, headers: authVerdictHeaders("transient") }),+ },+ { provider: "qwen-token-plan", response: new Response("subscription success") },+ { provider: "meta", response: new Response("metered success") },+ ]);+ expect(result.status).toBe(503);+ expect(result.verdict).toBe("transient");+ expect(result.body).toBe(body);+ expect(result.calls).toEqual([1, 0, 0]);+ });++ test("rule 5: a terminal metered verdict returns without advancing", async () => {+ const body = JSON.stringify({+ error: { message: "Metered login failed", upstream_status: 401 },+ });+ const result = await runChain([+ {+ provider: "meta",+ response: new Response(body, { status: 400, headers: authVerdictHeaders("terminal") }),+ },+ { provider: "qwen-token-plan", response: new Response("subscription success") },+ { provider: "openrouter", response: new Response("metered success") },+ ]);+ expect(result.status).toBe(400);+ expect(result.verdict).toBe("terminal");+ expect(result.body).toBe(body);+ expect(result.calls).toEqual([1, 0, 0]);+ });++ test("rule 5: a usage limit before any login failure can advance to metered", async () => {+ const result = await runChain([+ { provider: "kimi-coding", response: usageLimit() },+ { provider: "deepseek", response: new Response("metered success") },+ { provider: "qwen-token-plan", response: new Response("subscription success") },+ ]);+ expect(result.status).toBe(200);+ expect(result.body).toBe("metered success");+ expect(result.calls).toEqual([1, 1, 0]);+ });++ test("rule 6: each candidate is called at most once per request", async () => {+ 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: "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]);+ for (const count of result.calls) expect(count).toBeLessThanOrEqual(1);+ });++ test("real glm-5.3 chain: expired package, expired key, then qwen-token-plan", async () => {+ const result = await runChain([+ {+ provider: "glm-coding",+ response: new Response(+ JSON.stringify({ error: { message: "Your plan package has expired" } }),+ { status: 429 }+ ),+ },+ { provider: "opencode-zen-go", response: terminalLoginFailure("This API key has expired") },+ { provider: "qwen-token-plan", response: new Response("qwen-token-plan serves glm-5.3") },+ { provider: "glm", response: new Response("metered glm success") },+ { provider: "z-ai", response: new Response("metered z-ai success") },+ ]);+ expect(result.status).toBe(200);+ expect(result.body).toBe("qwen-token-plan serves glm-5.3");+ expect(result.calls).toEqual([1, 1, 1, 0, 0]);+ });++ test("real interleaved chain: terminal Zen Go skips metered DeepSeek before Qwen", 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]);+ });+});diff --git a/packages/cli/src/handlers/fallback-handler.ts b/packages/cli/src/handlers/fallback-handler.tsindex dad939be..7d0f983f 100644--- a/packages/cli/src/handlers/fallback-handler.ts+++ b/packages/cli/src/handlers/fallback-handler.ts@@ -49,11 +49,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;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;try {// If previous attempts failed, signal the winning handler to include fallback metadata@@ -128,8 +133,16 @@ export class FallbackHandler implements ModelHandler {// Claude Code stopped instead of retrying the same hop, and the verdict// 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.const verdict = authVerdict(response.headers);- if (verdict) {+ const subscriptionRejected =+ verdict === "terminal" && !!provider && isSubscriptionProvider(provider);+ if (verdict && !subscriptionRejected) {if (errors.length > 0) {logStderr(`[Fallback] ${name}: credential ${verdict === "terminal" ? "rejected" : "temporarily unavailable"} — stopping the chain here.`@@ -141,6 +154,31 @@ export class FallbackHandler implements ModelHandler {// Clone before reading body so we can still return the original if neededconst errorBody = await response.clone().text();+ if (+ subscriptionRejected ||+ 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.`+ );+ }+ 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) {@@ -181,6 +219,15 @@ 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;+ }+// All providers failedreturn this.formatCombinedError(c, errors, payload.model);}@@ -226,6 +273,37 @@ export class FallbackHandler implements ModelHandler {}}+/**+ * A subscription candidate's dead or rejected login, answered WITHOUT the+ * verdict header. The header 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.+ * Asked of the uid — a display name is never a subscription.+ */+export function isSubscriptionCredentialRejection(+ status: number,+ errorBody: string,+ providerId?: string+): boolean {+ if (!providerId || !isSubscriptionProvider(providerId)) return false;+ const recovered = status === 400 ? extractUpstreamStatus(errorBody) : undefined;+ // A credential rejection only: a 401 that says the MODEL is not carried+ // (OpenCode Zen Go's "Model <id> is not supported") is a per-model miss and+ // advances, as it always did (`isCredentialRejection`).+ if ((status === 401 || recovered === 401) && isCredentialRejection(401, errorBody)) {+ return true;+ }+ // A RAW 403 credential rejection counts too (measured: `403+ // {"error":{"type":"invalid_api_key"}}` from a subscription hop advanced+ // onto the metered `meta@`). Raw only: the upstream body still carries the+ // provider's own `error.type`, so `isCredentialRejection` can tell Zen Go's+ // `403 RegionError` (a model opt-in, which advances) from a dead login. A+ // RECOVERED 403 cannot be told apart that way — claudish's remapped 400+ // body says `invalid_request_error` — so it keeps advancing; a 403 the+ // ComposedHandler placed already carries the terminal verdict header.+ return status === 403 && isCredentialRejection(403, errorBody);+}+/*** Determine if an HTTP error is retryable (should try next provider).* Auth errors, billing errors, rate limits, model-not-found errors and an@@ -306,32 +384,11 @@ 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;- // A credential rejection only: a 401 that says the MODEL is not carried- // (OpenCode Zen Go's "Model <id> is not supported") is a per-model miss and- // advances, as it always did (`isCredentialRejection`).- if ((status === 401 || recovered === 401) && isCredentialRejection(401, errorBody)) {- return false;- }- // A RAW 403 credential rejection stops it too (measured: `403- // {"error":{"type":"invalid_api_key"}}` from a subscription hop advanced- // onto the metered `meta@`). Raw only: the upstream body still carries the- // provider's own `error.type`, so `isCredentialRejection` can tell Zen Go's- // `403 RegionError` (a model opt-in, which advances) from a dead login. A- // RECOVERED 403 cannot be told apart that way — claudish's remapped 400- // body says `invalid_request_error` — so it keeps advancing; a 403 the- // ComposedHandler placed already carries the terminal verdict header above.- if (status === 403 && isCredentialRejection(403, errorBody)) {- return false;- }- }+ // 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;// ── Recover the ORIGINAL status from a remapped terminal error (#148) ──────//diff --git a/packages/cli/src/handlers/shared/auth-failure.ts b/packages/cli/src/handlers/shared/auth-failure.tsindex 71124353..3bc28119 100644--- a/packages/cli/src/handlers/shared/auth-failure.ts+++ b/packages/cli/src/handlers/shared/auth-failure.ts@@ -5,9 +5,11 @@* ## 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.+ * 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`).* - 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.