Skip to content

Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins

fix(agent-runtime): classify HTTP 400 API-key rejections as PROVIDER_UNAUTHORIZED

xpeng5278-web5476e5469104
diff --git a/docs/spec/03-runtime/08-error-codes.md b/docs/spec/03-runtime/08-error-codes.md
index 6f7ca857f..cceed87c3 100644
--- a/docs/spec/03-runtime/08-error-codes.md
+++ b/docs/spec/03-runtime/08-error-codes.md
@@ -387,7 +387,11 @@ stays `PROVIDER_RATE_LIMITED`. An unprefixed JSON error body that carries an
HTTP status in `error.code` (Gemini's `@google/genai` `ApiError.message`) is
classified from that 400-599 code the same way as a `<status>:` message:
400/422 stay terminal unless they report a context overflow, 404 is
-`MODEL_NOT_CONFIGURED`, and 429 / 5xx stay retryable.
+`MODEL_NOT_CONFIGURED`, and 429 / 5xx stay retryable. A 400 or 422 that
+explicitly rejects the API key (`invalid api key`, `api key not valid`, or
+`API_KEY_INVALID`, including Gemini's `API key not valid` body) is terminal
+`PROVIDER_UNAUTHORIZED`; `permission denied` and a bare `unauthorized` on
+those statuses stay `PROVIDER_ERROR`.
An exact `terminated` provider message and equivalent premature stream-close
messages map to `STREAM_FAILED`. A message is `TURN_ABORTED` only for a
diff --git a/packages/agent-runtime/src/agent-errors.test.ts b/packages/agent-runtime/src/agent-errors.test.ts
index b0168a4cf..57ff79feb 100644
--- a/packages/agent-runtime/src/agent-errors.test.ts
+++ b/packages/agent-runtime/src/agent-errors.test.ts
@@ -406,6 +406,65 @@ describe("classifyAgentError", () => {
},
);
+ // Gemini's native API and some OpenAI-compatible gateways reject a bad key
+ // with HTTP 400, not 401. The status table must still call that a
+ // credential failure. A 400 that only says "permission denied" or
+ // "unauthorized" stays a malformed request.
+ it("classifies an HTTP 400 API-key rejection as unauthorized", () => {
+ const errorMessage = JSON.stringify({
+ error: {
+ code: 400,
+ message: "API key not valid. Please pass a valid API key.",
+ status: "INVALID_ARGUMENT",
+ details: [
+ {
+ "@type": "type.googleapis.com/google.rpc.ErrorInfo",
+ reason: "API_KEY_INVALID",
+ domain: "googleapis.com",
+ },
+ ],
+ },
+ });
+ const expected = {
+ code: "PROVIDER_UNAUTHORIZED",
+ retriable: false,
+ details: { providerStatus: 400 },
+ };
+ const message = { role: "assistant", stopReason: "error", errorMessage };
+ expect(classifyAgentError(errorMessage)).toMatchObject(expected);
+ expect(classifyAgentError(new Error(errorMessage))).toMatchObject(expected);
+ expect(classifyAgentError(message)).toMatchObject(expected);
+ expect(classifyProviderError(message)).toMatchObject(expected);
+ expect(classifyAgentError(`400: ${errorMessage}`)).toMatchObject(expected);
+ expect(classifyProviderError({
+ role: "assistant",
+ stopReason: "error",
+ errorMessage: "400: API key not valid. Please pass a valid API key.",
+ })).toMatchObject(expected);
+ expect(classifyAgentError("400: Invalid API key")).toMatchObject(expected);
+ expect(classifyAgentError('400: {"reason":"API_KEY_INVALID"}')).toMatchObject(expected);
+ expect(classifyAgentError("422: invalid_api_key")).toMatchObject({
+ code: "PROVIDER_UNAUTHORIZED",
+ retriable: false,
+ details: { providerStatus: 422 },
+ });
+
+ for (const ordinary of [
+ "400: Invalid value at 'contents'",
+ "400: permission denied",
+ "422: unauthorized",
+ "400: unknown parameter",
+ ]) {
+ expect(classifyAgentError(ordinary)).toMatchObject({
+ code: "PROVIDER_ERROR",
+ retriable: false,
+ });
+ }
+ expect(classifyAgentError(
+ "400: The input token count exceeds the maximum number of tokens allowed.",
+ )).toMatchObject({ code: "CONTEXT_TOO_LARGE", retriable: false });
+ });
+
it("does not treat a non-HTTP JSON code as a provider status", () => {
const cases = [
JSON.stringify({ error: { code: 123, message: "not an http status" } }),
diff --git a/packages/agent-runtime/src/agent-errors.ts b/packages/agent-runtime/src/agent-errors.ts
index e772759b2..0f9ba51fe 100644
--- a/packages/agent-runtime/src/agent-errors.ts
+++ b/packages/agent-runtime/src/agent-errors.ts
@@ -470,17 +470,33 @@ export function networkFailureDiagnostics(
return { category: network.category, fields: networkDetailFields(network) };
}
+/**
+ * Explicit API-key rejection. Safe on HTTP 400/422 as well as on a
+ * statusless message: Gemini's `@google/genai` ApiError reports a bad key
+ * as 400 `API key not valid` / `API_KEY_INVALID`, and some OpenAI-compatible
+ * gateways do the same.
+ *
+ * Broader words such as "unauthorized" and "permission denied" stay out of
+ * this pattern. On a 400 they can describe a bad parameter or a tool
+ * argument rather than a rejected credential, so only the statusless path
+ * below treats them as an auth failure.
+ */
+const API_KEY_REJECTION_PATTERN =
+ /invalid[ _]api[ _]key|api key not valid|API_KEY_INVALID/i;
+
/**
* Credential rejection worded without an HTTP status.
*
- * Bare "authentication" is not enough. Keep the API-key / unauthorized
- * phrases, and keep "authentication" only beside an API key, bearer token,
- * or credentials — or as a short provider phrase such as "authentication
- * failed". Handshake, TLS/SSL, and certificate text is transport, so it
- * never counts.
+ * Bare "authentication" is not enough. Explicit API-key phrases live in
+ * `API_KEY_REJECTION_PATTERN`. This pattern keeps the broader
+ * "unauthorized" / "permission denied" words, which are only trusted when
+ * no status is present. "authentication" counts only beside an API key,
+ * bearer token, or credentials — or as a short provider phrase such as
+ * "authentication failed". Handshake, TLS/SSL, and certificate text is
+ * transport, so it never counts.
*/
const STATUSLESS_CREDENTIAL_PATTERN =
- /invalid[ _]api[ _]key|api key not valid|unauthorized|permission denied/i;
+ /unauthorized|permission denied/i;
const AUTHENTICATION_WITH_CREDENTIAL_PATTERN =
/(?:api[-_ ]?key|credentials|bearer).{0,48}\bauthentication\b|\bauthentication\b.{0,48}(?:api[-_ ]?key|credentials|bearer)/i;
@@ -489,6 +505,7 @@ const AUTHENTICATION_FAILURE_PATTERN =
/\bauthentication[_ ](?:failed|failure|error)\b/i;
function isStatuslessCredentialFailure(message: string): boolean {
+ if (API_KEY_REJECTION_PATTERN.test(message)) return true;
if (STATUSLESS_CREDENTIAL_PATTERN.test(message)) return true;
if (isTlsTransportText(message)) return false;
return (
@@ -646,6 +663,12 @@ export function classifyAgentError(err: unknown): ClassifiedAgentError {
if (status >= 500) return result("PROVIDER_ERROR", true);
if (status === 400 || status === 422) {
if (isContextOverflowMessage(rawMessage)) return result("CONTEXT_TOO_LARGE", false);
+ // Only an explicit API-key rejection is a credential failure here.
+ // "unauthorized" / "permission denied" stay PROVIDER_ERROR: a 400 often
+ // uses those words for a parameter or tool problem, not the key.
+ if (API_KEY_REJECTION_PATTERN.test(rawMessage)) {
+ return result("PROVIDER_UNAUTHORIZED", false);
+ }
// Malformed request (wrong apiStyle, bad params) — retrying won't help.
return result("PROVIDER_ERROR", false);
}