Claude Code. Any Model. The most powerful AI coding agent now speaks every language.
fix: show the provider's own error, not claudish's guess about it
Jack Rudenko196e6f8f8caa
diff --git a/packages/cli/src/handlers/composed-handler.ts b/packages/cli/src/handlers/composed-handler.tsindex 3c0be6e4..4319bbb1 100644--- a/packages/cli/src/handlers/composed-handler.ts+++ b/packages/cli/src/handlers/composed-handler.ts@@ -1043,7 +1043,16 @@ export class ComposedHandler implements ModelHandler {// machine consumers (probe classification) can tell a remapped// auth failure from a genuine 400.return c.json(- wrapAnthropicError(400, surfaced, "invalid_request_error", response.status),+ wrapAnthropicError(+ 400,+ surfaced,+ "invalid_request_error",+ response.status,+ // The upstream's own sentence, kept whole and separate. `surfaced`+ // leads with claudish's hint, which is correct for Claude Code and+ // useless to a probe row that clips.+ providerMsg+ ),400 as any);}@@ -1098,7 +1107,13 @@ export class ComposedHandler implements ModelHandler {} catch {// Stats must never crash claudish}- return c.json(wrapAnthropicError(503, surfaced, "overloaded_error"), 503 as any);+ // `settled.message` is the upstream's own text; `surfaced` wraps it in+ // claudish's retry narration. Both travel, so a probe row can lead with+ // the provider's words.+ return c.json(+ wrapAnthropicError(503, surfaced, "overloaded_error", undefined, settled.message),+ 503 as any+ );}response = settled.response;}@@ -1157,8 +1172,20 @@ export class ComposedHandler implements ModelHandler {// Stats must never crash claudish}return isTerminal- ? c.json(wrapAnthropicError(400, surfaced, "invalid_request_error"), 400 as any)- : c.json(wrapAnthropicError(503, surfaced, "overloaded_error"), 503 as any);+ ? c.json(+ wrapAnthropicError(+ 400,+ surfaced,+ "invalid_request_error",+ undefined,+ settled.message+ ),+ 400 as any+ )+ : c.json(+ wrapAnthropicError(503, surfaced, "overloaded_error", undefined, settled.message),+ 503 as any+ );}response = settled.response;}diff --git a/packages/cli/src/handlers/shared/anthropic-error.test.ts b/packages/cli/src/handlers/shared/anthropic-error.test.tsindex 5391e011..1b8ac701 100644--- a/packages/cli/src/handlers/shared/anthropic-error.test.ts+++ b/packages/cli/src/handlers/shared/anthropic-error.test.ts@@ -5,6 +5,7 @@ import {extractProviderMessage,isTerminalError,sanitizeErrorMessage,+ sseDataPayload,statusToErrorType,wrapAnthropicError,} from "./anthropic-error.js";@@ -12,6 +13,13 @@ import {const CAPTURED_BUN_DUMP ='error: Unable to connect. Is the computer able to access the url?\n path: "https://chatgpt.com/backend-api/codex/responses",\n errno: 0,\n code: "ConnectionRefused"\n';+const ALIBABA_ACCESS_DENIED_PAYLOAD =+ '{"code":"AccessDenied","message":"Model access denied.","request_id":"ecbdbfc8-..."}';+const ALIBABA_ACCESS_DENIED_SSE = `event:error\ndata:${ALIBABA_ACCESS_DENIED_PAYLOAD}`;+const ALIBABA_INVALID_PARAMETER_PAYLOAD =+ '{"code":"InvalidParameter","message":"Model access denied.","request_id":"200170c3-..."}';+const ALIBABA_INVALID_PARAMETER_SSE = `event:error\ndata:${ALIBABA_INVALID_PARAMETER_PAYLOAD}`;+describe("statusToErrorType", () => {it("maps 400 to invalid_request_error", () => {expect(statusToErrorType(400)).toBe("invalid_request_error");@@ -84,6 +92,52 @@ describe("wrapAnthropicError", () => {expect(result.error.message).toBe("first line second line");expect(result.error.message).not.toMatch(/[\r\n\t]/);});++ it("preserves sanitized provider evidence and omits the field when absent or blank", () => {+ const result = wrapAnthropicError(+ 400,+ "Alibaba PAYG error",+ "invalid_request_error",+ 403,+ " \u001b[31mModel\n access denied.\u001b[0m "+ );++ expect(result.error.provider_message).toBe("Model access denied.");+ const omitted = wrapAnthropicError(400, "Alibaba PAYG error");+ const blank = wrapAnthropicError(+ 400,+ "Alibaba PAYG error",+ "invalid_request_error",+ 403,+ " \n\t "+ );++ expect(Object.hasOwn(omitted.error, "provider_message")).toBe(false);+ expect(Object.hasOwn(blank.error, "provider_message")).toBe(false);+ });+});++describe("sseDataPayload", () => {+ it("handles real and flattened SSE frames without consuming non-SSE bodies", () => {+ expect(sseDataPayload(ALIBABA_ACCESS_DENIED_SSE)).toBe(ALIBABA_ACCESS_DENIED_PAYLOAD);+ expect(sseDataPayload(ALIBABA_INVALID_PARAMETER_SSE)).toBe(ALIBABA_INVALID_PARAMETER_PAYLOAD);++ const frame = [+ "event:error",+ 'data:{"code":"AccessDenied",',+ 'data:"message":"Model access denied.",',+ 'data:"request_id":"ecbdbfc8-..."}',+ ].join("\n");++ expect(sseDataPayload(frame)).toBe(ALIBABA_ACCESS_DENIED_PAYLOAD);++ const flattened = sanitizeErrorMessage(ALIBABA_INVALID_PARAMETER_SSE);++ expect(sseDataPayload(flattened)).toBe(ALIBABA_INVALID_PARAMETER_PAYLOAD);++ expect(sseDataPayload("Model access denied.")).toBeUndefined();+ expect(sseDataPayload(ALIBABA_ACCESS_DENIED_PAYLOAD)).toBeUndefined();+ });});describe("sanitizeErrorMessage", () => {@@ -235,8 +289,16 @@ describe("ensureAnthropicErrorFormat", () => {});describe("extractProviderMessage", () => {- it("returns a raw string as-is", () => {+ it("unwraps a nested SSE frame while preserving an ordinary string", () => {expect(extractProviderMessage("plain error")).toBe("plain error");+ expect(+ extractProviderMessage({+ error: {+ message:+ 'event:error data:{"code":"AccessDenied","message":"Model access denied.","request_id":"x"}',+ },+ })+ ).toBe("Model access denied.");});it("pulls error.message from OpenAI-style bodies", () => {diff --git a/packages/cli/src/handlers/shared/anthropic-error.ts b/packages/cli/src/handlers/shared/anthropic-error.tsindex 99baafc3..94a45379 100644--- a/packages/cli/src/handlers/shared/anthropic-error.ts+++ b/packages/cli/src/handlers/shared/anthropic-error.ts@@ -28,6 +28,23 @@ export interface AnthropicErrorEnvelope {* instead of the proxy's 400. Extra JSON fields are ignored by Claude Code.*/upstream_status?: number;+ /**+ * The UPSTREAM'S OWN WORDS, unedited — no hint, no provider name, no status.+ *+ * `message` is a composed sentence: claudish's recovery hint first, then the+ * provider's text after an em dash. That order is right for Claude Code,+ * which shows one line and needs the advice in it, and wrong for anything+ * that has to fit the failure into a column. The probe row clips, so it was+ * showing 100% of claudish's guess and 0% of the provider's fact — Alibaba+ * said "Model access denied." and the row said "The provider accepted the+ * credential but denied access to this model — check model access or…".+ *+ * A guess displacing the evidence is the wrong trade at any width, so the+ * evidence travels separately and the probe leads with it. Same precedent as+ * `upstream_status`: machine-readable, and extra JSON fields are ignored by+ * Claude Code.+ */+ provider_message?: string;};}@@ -108,11 +125,17 @@ export function wrapAnthropicError(status: number,message: string,errorType?: string,- upstreamStatus?: number+ upstreamStatus?: number,+ providerMessage?: string): AnthropicErrorEnvelope {const type = (errorType as AnthropicErrorType) || statusToErrorType(status);const error: AnthropicErrorEnvelope["error"] = { type, message: sanitizeErrorMessage(message) };if (upstreamStatus !== undefined) error.upstream_status = upstreamStatus;+ // Flattened to one line here rather than at each caller: the field exists to+ // be rendered in a single row, and a provider may answer with a multi-line SSE+ // frame. Sanitised like `message`, because it is provider text either way.+ const oneLine = (providerMessage ?? "").replace(/\s+/g, " ").trim();+ if (oneLine) error.provider_message = sanitizeErrorMessage(oneLine);return { type: "error", error };}@@ -164,13 +187,28 @@ export function extractUpstreamStatus(body: string): number | undefined {* per the SSE specification.*/export function sseDataPayload(body: string): string | undefined {- if (!/(^|\n)\s*(event|data):/.test(body)) return undefined;- const data = body- .split(/\r?\n/)- .filter((line) => line.startsWith("data:"))- .map((line) => line.slice("data:".length).trim())- .join("");- return data.length > 0 ? data : undefined;+ if (!/(^|\s)(event|data):/.test(body)) return undefined;++ // Shape 1: a real frame, still carrying its line breaks. Multiple `data:`+ // lines concatenate, per the specification.+ const lines = body.split(/\r?\n/).filter((line) => line.startsWith("data:"));+ if (lines.length > 0) {+ const joined = lines.map((line) => line.slice("data:".length).trim()).join("");+ if (joined.length > 0) return joined;+ }++ // Shape 2: the SAME frame after its newlines became spaces. `sanitizeErrorMessage`+ // does that to every message the proxy returns — deliberately, so a provider+ // cannot corrupt a client's terminal — and it runs BEFORE the probe reads the+ // text. So the probe never sees shape 1 on a proxied error, only+ // `event:error data:{…}` on one line, where no line starts with `data:` and+ // shape 1 finds nothing. Everything after the first `data:` is the payload;+ // a frame carrying several data fields has already lost its boundaries by+ // this point, and one JSON object is the case that occurs.+ const at = body.search(/(^|\s)data:/);+ if (at === -1) return undefined;+ const payload = body.slice(body.indexOf("data:", at) + "data:".length).trim();+ return payload.length > 0 ? payload : undefined;}/**@@ -204,7 +242,11 @@ export function extractProviderMessage(body: any): string {body?.detail,];for (const c of candidates) {- if (typeof c === "string" && c.length > 0) return c;+ // Re-entered through the string arm, not returned directly: a message field+ // can itself hold a whole SSE frame. claudish re-wraps a raw upstream body+ // as `{error:{message: <that body>}}` on the auth-retry return, which is+ // valid JSON, so this ladder succeeded and handed back wire protocol.+ if (typeof c === "string" && c.length > 0) return extractProviderMessage(c);// FastAPI validation errors use `detail: [{ msg, loc, ... }]`.if (Array.isArray(c)) {const first = c.find((e) => typeof e?.msg === "string" && e.msg.length > 0);diff --git a/packages/cli/src/providers/probe-live-classify.test.ts b/packages/cli/src/providers/probe-live-classify.test.tsindex d2b59f06..3f9e7b5f 100644--- a/packages/cli/src/providers/probe-live-classify.test.ts+++ b/packages/cli/src/providers/probe-live-classify.test.ts@@ -34,7 +34,42 @@ const REGION_ERROR_BODY = JSON.stringify({},});+const ALIBABA_ACCESS_DENIED_SSE =+ 'event:error\ndata:{"code":"AccessDenied","message":"Model access denied.","request_id":"ecbdbfc8-..."}';+const ALIBABA_COMPOSED_MESSAGE =+ "Alibaba PAYG error (HTTP 403): The provider accepted the credential but denied access to this model — check model access or activation for this account in the provider's console, not the key. — Model access denied.";+describe("classifyHttpError — auth-shaped model errors", () => {+ test("prefers provider evidence while preserving composed and raw-SSE fallbacks", () => {+ const proxyBody = JSON.stringify({+ type: "error",+ error: {+ type: "invalid_request_error",+ message: ALIBABA_COMPOSED_MESSAGE,+ upstream_status: 403,+ provider_message: "Model access denied.",+ },+ });++ expect(classifyHttpError(400, proxyBody, 1200).errorMessage).toBe("Model access denied.");++ const bodyWithoutProviderMessage = JSON.stringify({+ type: "error",+ error: {+ type: "invalid_request_error",+ message: ALIBABA_COMPOSED_MESSAGE,+ upstream_status: 403,+ },+ });++ expect(classifyHttpError(400, bodyWithoutProviderMessage, 1200).errorMessage).toBe(+ ALIBABA_COMPOSED_MESSAGE+ );+ expect(classifyHttpError(403, ALIBABA_ACCESS_DENIED_SSE, 1200).errorMessage).toBe(+ "Model access denied."+ );+ });+test("classifies a 401 unsupported-model response without rewriting its status", () => {const body = proxyErrorBody(401, "Model deepseek-v4-pro-0813 is not supported");diff --git a/packages/cli/src/providers/probe-live.ts b/packages/cli/src/providers/probe-live.tsindex 3a0687fa..d225ebd7 100644--- a/packages/cli/src/providers/probe-live.ts+++ b/packages/cli/src/providers/probe-live.ts@@ -588,34 +588,66 @@ function oneLine(text: string): string {return text.replace(/\s+/g, " ").trim();}-/** The message a JSON error document carries, under any of the shapes seen. */+/**+ * The message a JSON error document carries, under any of the shapes seen.+ *+ * `error.provider_message` is read FIRST and it is the whole point of this+ * order: it is the upstream's own sentence, while `error.message` beside it is+ * claudish's composed one — the recovery hint, then the provider's text after an+ * em dash. A probe row clips, so composing put the guess where the reader looks+ * and the evidence where they never get to. "Model access denied." is three+ * words and says what happened; "The provider accepted the credential but denied+ * access to this model — check model access or activation for this account in+ * the provider's console, not the key." is 150 characters of inference about it.+ *+ * The hint is not thrown away — `probe-results-printer` still word-wraps the+ * full composed `message` in the Details box, which has the room for both.+ */function messageFromJson(text: string): string | undefined {try {const parsed = JSON.parse(text);const msg =- parsed?.error?.message || parsed?.error?.error?.message || parsed?.message || parsed?.detail;+ parsed?.error?.provider_message ||+ parsed?.error?.message ||+ parsed?.error?.error?.message ||+ parsed?.message ||+ parsed?.detail;return typeof msg === "string" && msg.length > 0 ? msg : undefined;} catch {return undefined;}}+/**+ * Open an SSE frame if that is what this text is, otherwise hand it back.+ *+ * Applied to the EXTRACTED message and not only to the raw body, because the+ * frame arrives both ways and the JSON ladder hides the second one. A provider+ * answering a stream request with an error may send the frame as the body —+ * caught by parsing the body — but claudish also re-wraps a raw upstream body+ * into `{error:{message: <that body>}}` (`composed-handler.ts`, the auth-retry+ * return). That parses as perfectly good JSON, so `messageFromJson` succeeded+ * and returned a whole wire frame wearing a message field. Measured against+ * dashscope-intl: the row read+ * `event:error data:{"code":"InvalidParameter","message":"Model access+ * denied.","request_id":"0d6a48d4-…"}`+ * where "Model access denied." was the entire content.+ */+function unwrapFrame(text: string): string {+ const payload = sseDataPayload(text);+ if (!payload) return text;+ return messageFromJson(payload) ?? payload;+}+function extractErrorMessage(body: string): string | undefined {if (!body) return undefined;const direct = messageFromJson(body);- if (direct) return truncateKeepingLink(oneLine(direct));+ if (direct) return truncateKeepingLink(oneLine(unwrapFrame(direct)));// Not a JSON document. It may still be an SSE frame carrying one.- const payload = sseDataPayload(body);- if (payload) {- const streamed = messageFromJson(payload);- if (streamed) return truncateKeepingLink(oneLine(streamed));- // A `data:` payload that is not JSON is still better than the whole frame.- return truncateKeepingLink(oneLine(payload));- }-- const trimmed = oneLine(body);+ const unwrapped = unwrapFrame(body);+ const trimmed = oneLine(unwrapped);if (!trimmed) return undefined;return truncateKeepingLink(trimmed);}