graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
Name the rejected credential in auth failure text
justrach3a978d81ea79
diff --git a/docs/adr/0310-auth-failures-name-the-rejected-credential.md b/docs/adr/0310-auth-failures-name-the-rejected-credential.mdnew file mode 100644index 00000000..ad5ee79b--- /dev/null+++ b/docs/adr/0310-auth-failures-name-the-rejected-credential.md@@ -0,0 +1,54 @@+# 0310. Authentication failures name the rejected credential++Status: accepted 2026-11-01++## Context++A provider can hold a sign-in (a flat-rate plan) and a metered API key at the+same time (#471). The plan is seated first; when it reports a quota cap,+`handOffExhaustedPlan` promotes the parked key for the rest of the session.+Every terminal authentication rejection used one text, "provider+authentication failed: sign in again or check the API key", whichever seat+failed. Clients read "sign in again" as signed out, so a rejected API key —+including the key a spent plan just handed over to — showed a sign-in prompt+although the sign-in was fine and could not fix it.++ADR 0285 already carries a `reauth_required` action for sign-in seats on the+ChatGPT routes; metered seats carried nothing.++## Decision++`auth_recovery.failureText` words the rejection after the seat+(`Provider.source`) and whether the seat is a promoted key+(`credential_failover.promoted`):++- Sign-in seat: `<Name> sign-in was rejected: sign in again (<login command>)`.+ It keeps "sign in again", so existing clients still read it as signed out.+- Key seat: `<Name> API key was rejected (<source label>): replace or remove+ the key. Your sign-in is not affected.`+- Promoted key: `<Name> plan is out of usage, and the fallback API key was+ rejected (<source label>): replace or remove the key, or wait for the plan+ to reset.`++Both key texts carry the stable phrase "API key was rejected" and never "sign+in again", "log in again", "not signed in", "unauthorized", "authentication+failed" or "invalid api key". The same text is used when the failure lands+after async tools started. Provider failover and subagent failure classes+treat the new texts as the old one.++A key seat's failure carries fixed metadata with no login action:++```json+{ "kind": "api_key_rejected", "provider": "anthropic" }+```++ACP v1 returns it as `error.data` on `-32603` (only a sign-in action is+`-32000`, authentication required). ACP v2 puts it on the failed idle update's+`_meta["graff/recovery"]`, never on `_meta["graff/reauth"]`, which clients read+as signed out. `reauth_required` and its wire positions are unchanged.++## Consequences++A client can tell "replace the key" from "sign in" without parsing provider+words, and an old client no longer offers a sign-in for a rejected key. The+generic message text is gone; anything matching it must match the new phrases.diff --git a/docs/adr/README.md b/docs/adr/README.mdindex 04737f5d..8ac45994 100644--- a/docs/adr/README.md+++ b/docs/adr/README.md@@ -333,6 +333,7 @@ record only when you need the evidence or the edge cases.| [0306](0306-model-catalogs-never-hold-startup.md) | Boot and `graff/models` never wait on a catalog GET past a budget: cached catalogs activate now and refresh behind on detached workers whose only output is the disk cache; only uncached ones wait, together, up to 800ms. || [0307](0307-resumed-sessions-keep-their-compaction-state-count.md) | A session saves the provider's count of its compaction state, scoped to provider, model, size and digest; loading reapplies it before rebasing the meter, so a restart neither inflates the meter nor forces a compaction. || [0309](0309-claude-agent-runs-the-users-claude.md) | Claude Agent runs the user's own `claude` over the SDK control protocol: graff's tools as an in-process MCP server with held calls, graff's history as the source of truth, never reading Claude Code's login. |+| [0310](0310-auth-failures-name-the-rejected-credential.md) | A terminal auth rejection names the seat that failed: sign-in text keeps "sign in again"; key and promoted-key texts say "API key was rejected" and never the signed-out phrases. Key seats carry `{"kind":"api_key_rejected","provider":…}` (v1 `-32603` data, v2 `_meta["graff/recovery"]`); `reauth_required` is unchanged. || [0302](0302-sse-idle-watchdogs-follow-body-byte-progress.md) | SSE idle watchdogs observe partial body-byte progress, while separate unfinished-event time and size bounds preserve recovery. |diff --git a/src/acp_engine.zig b/src/acp_engine.zigindex 3771b87d..e41e9c14 100644--- a/src/acp_engine.zig+++ b/src/acp_engine.zig@@ -177,7 +177,7 @@ fn turnError(d: *Dispatch, w: *Io.Writer, req: proto.Request, err: anyerror) !voreturn respond(w, req, .{ .stopReason = "max_turn_requests" });const message = if (d.error_message) |describe| describe(d.ctx, err) else @errorName(err);if (d.error_recovery) |recover| if (recover(d.ctx, err)) |data| {- if (req.id != null) try proto.writeErrorData(w, req.id, err_auth_required, message, data);+ if (req.id != null) try proto.writeErrorData(w, req.id, data.rpcCode(), message, data);return;};return respondError(w, req, err_internal, message);diff --git a/src/acp_reauth_tests.zig b/src/acp_reauth_tests.zigindex 6a9eb552..5a2060c4 100644--- a/src/acp_reauth_tests.zig+++ b/src/acp_reauth_tests.zig@@ -78,7 +78,22 @@ fn assertLogin(data: std.json.ObjectMap, id: []const u8, command: []const u8) !vtry std.testing.expectEqual(@as(usize, 3), data.count());}-fn assertV2Failure(a: std.mem.Allocator, output: []const u8, id: ?[]const u8) !void {+fn assertKeyRejected(a: std.mem.Allocator, output: []const u8, id: []const u8, suffix: []const u8) !void {+ const result = try std.json.parseFromSliceLeaky(std.json.Value, a, std.mem.sliceTo(output, '\n'), .{});+ const err = result.object.get("error").?.object;+ try std.testing.expectEqual(@as(i64, -32603), err.get("code").?.integer);+ const data = err.get("data").?.object;+ try std.testing.expectEqualStrings("api_key_rejected", data.get("kind").?.string);+ try std.testing.expectEqualStrings(id, data.get("provider").?.string);+ try std.testing.expectEqual(@as(usize, 2), data.count());+ const message = err.get("message").?.string;+ try std.testing.expect(std.mem.endsWith(u8, message, suffix));+ for (recovery.signed_out_phrases) |phrase| try std.testing.expect(@import("util.zig").indexOfIgnoreCase(message, phrase) == null);+}++const V2Expect = union(enum) { none, reauth: []const u8, key_rejected: []const u8 };++fn assertV2Failure(a: std.mem.Allocator, output: []const u8, expect: V2Expect) !void {var lines = std.mem.tokenizeScalar(u8, output, '\n');var accepted: usize = 0;var failures: usize = 0;@@ -95,9 +110,26 @@ fn assertV2Failure(a: std.mem.Allocator, output: []const u8, id: ?[]const u8) !vif (meta.object.get("graff/error") == null) continue;try std.testing.expectEqualStrings("idle", update.object.get("state").?.string);try std.testing.expectEqualStrings("_error", update.object.get("stopReason").?.string);- if (id) |expected| {- try assertLogin(meta.object.get("graff/reauth").?.object, expected, if (std.mem.eql(u8, expected, "codex")) "codex" else "graff");- } else try std.testing.expect(meta.object.get("graff/reauth") == null);+ switch (expect) {+ .reauth => |expected| {+ try assertLogin(meta.object.get("graff/reauth").?.object, expected, if (std.mem.eql(u8, expected, "codex")) "codex" else "graff");+ try std.testing.expect(meta.object.get("graff/recovery") == null);+ },+ .key_rejected => |expected| {+ // Never on `graff/reauth`: clients read that as signed out.+ try std.testing.expect(meta.object.get("graff/reauth") == null);+ const data = meta.object.get("graff/recovery").?.object;+ try std.testing.expectEqualStrings("api_key_rejected", data.get("kind").?.string);+ try std.testing.expectEqualStrings(expected, data.get("provider").?.string);+ try std.testing.expectEqual(@as(usize, 2), data.count());+ const message = meta.object.get("graff/error").?.string;+ try std.testing.expect(std.mem.indexOf(u8, message, recovery.api_key_rejected_phrase) != null);+ },+ .none => {+ try std.testing.expect(meta.object.get("graff/reauth") == null);+ try std.testing.expect(meta.object.get("graff/recovery") == null);+ },+ }failures += 1;}try std.testing.expectEqual(@as(usize, 1), accepted);@@ -150,10 +182,24 @@ test "typed reauth: production terminal handler gates actions and clears stale mtry std.testing.expectError(case.err, quota.handle(&agent, case.etype, case.code, case.msg, &refreshed));try std.testing.expect(refreshed);const action = case.action and source == .login and !std.mem.eql(u8, id, "openai");- try std.testing.expectEqual(action, agent.last_api_reauth != null);+ // ADR 0310: a metered seat names the rejected key, never a login.+ const key_rejected = case.action and source != .login;+ try std.testing.expectEqual(action or key_rejected, agent.last_api_reauth != null);if (agent.last_api_reauth) |data| {try std.testing.expectEqualStrings(id, data.provider);- try std.testing.expectEqualStrings(if (std.mem.eql(u8, id, "codex")) "codex" else "graff", data.login.command);+ if (key_rejected) {+ try std.testing.expectEqualStrings("api_key_rejected", data.kind);+ try std.testing.expect(data.login == null);+ } else try std.testing.expectEqualStrings(if (std.mem.eql(u8, id, "codex")) "codex" else "graff", data.login.?.command);+ }+ if (case.err == error.ProviderAuthenticationFailed) {+ const text = agent.last_api_error.?;+ if (source == .login) {+ try std.testing.expect(std.mem.indexOf(u8, text, "sign-in was rejected: sign in again") != null);+ } else {+ try std.testing.expect(std.mem.indexOf(u8, text, recovery.api_key_rejected_phrase) != null);+ for (recovery.signed_out_phrases) |phrase| try std.testing.expect(@import("util.zig").indexOfIgnoreCase(text, phrase) == null);+ }}}agent.last_api_reauth = recovery.forFailure(route("codex"), "401", "");@@ -191,7 +237,10 @@ test "typed reauth: v1 parsed HTTP and stream auth errors carry route-specific ltry std.testing.expectEqual(@as(i64, -32000), err.get("code").?.integer);try assertLogin(err.get("data").?.object, id, if (std.mem.eql(u8, id, "codex")) "codex" else "graff");try std.testing.expect(result.object.get("result") == null);- try std.testing.expectEqualStrings("provider authentication failed: sign in again or check the API key", err.get("message").?.string);+ try std.testing.expectEqualStrings(if (std.mem.eql(u8, id, "codex"))+ "Codex (ChatGPT) sign-in was rejected: sign in again (codex login)"+ else+ "ChatGPT plan (new sign-in) sign-in was rejected: sign in again (graff login chatgpt-new)", err.get("message").?.string);try std.testing.expect(LiveTurn.errorRecovery(&live, error.StreamDropped) == null);try std.testing.expect(LiveTurn.errorRecovery(&live, error.ProviderQuotaExceeded) == null);try std.testing.expect(LiveTurn.errorRecovery(&live, error.ProviderAccessDenied) == null);@@ -209,16 +258,23 @@ test "typed reauth: v1 parsed HTTP and stream auth errors carry route-specific ltry std.testing.expectEqual(@as(i64, -32603), err.get("code").?.integer);try std.testing.expect(err.get("data") == null);}+ // ADR 0310: a metered seat stays an internal error, with data naming+ // the rejected key and no login action.agent.provider.source = .environment;for (auth_bodies) |body| {out.clearRetainingCapacity();try engine.handleLine(&d, a, &out.writer, try prompt(a, body));- const result = try std.json.parseFromSliceLeaky(std.json.Value, a, std.mem.sliceTo(out.writer.buffered(), '\n'), .{});- const err = result.object.get("error").?.object;- try std.testing.expectEqual(@as(i64, -32603), err.get("code").?.integer);- try std.testing.expect(err.get("data") == null);+ try assertKeyRejected(a, out.writer.buffered(), id, "API key was rejected (environment): replace or remove the key. Your sign-in is not affected.");}}+ // A key a spent plan handed over to says so.+ failover.park("anthropic", "metered", .profile);+ _ = failover.promote("anthropic").?;+ agent.provider = route("anthropic");+ agent.provider.source = .profile;+ out.clearRetainingCapacity();+ try engine.handleLine(&d, a, &out.writer, try prompt(a, "http:401"));+ try assertKeyRejected(a, out.writer.buffered(), "anthropic", "plan is out of usage, and the fallback API key was rejected (Console profile): replace or remove the key, or wait for the plan to reset.");out.clearRetainingCapacity();agent.last_api_reauth = recovery.forFailure(route("codex"), "invalid_token", "Unauthorized");try engine.handleLine(&d, a, &out.writer, try prompt(a, "ok"));@@ -250,19 +306,19 @@ test "typed reauth: v2 accepted prompt carries the same action on the failed idlfor (auth_bodies) |body| {out.clearRetainingCapacity();try engine.handleLine(&d, a, &out.writer, try prompt(a, body));- try assertV2Failure(a, out.writer.buffered(), id);+ try assertV2Failure(a, out.writer.buffered(), .{ .reauth = id });}for (non_auth_bodies) |body| {out.clearRetainingCapacity();agent.last_api_reauth = recovery.forFailure(agent.provider, "401", "");try engine.handleLine(&d, a, &out.writer, try prompt(a, body));- try assertV2Failure(a, out.writer.buffered(), null);+ try assertV2Failure(a, out.writer.buffered(), .none);}agent.provider.source = .environment;for (auth_bodies) |body| {out.clearRetainingCapacity();try engine.handleLine(&d, a, &out.writer, try prompt(a, body));- try assertV2Failure(a, out.writer.buffered(), null);+ try assertV2Failure(a, out.writer.buffered(), .{ .key_rejected = id });}}out.clearRetainingCapacity();@@ -272,3 +328,22 @@ test "typed reauth: v2 accepted prompt carries the same action on the failed idltry std.testing.expect(std.mem.indexOf(u8, out.writer.buffered(), "end_turn") != null);try std.testing.expect(std.mem.indexOf(u8, out.writer.buffered(), "reauth_required") == null);}++test "typed reauth: a failure after async tools started names the rejected credential too" {+ var state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer state.deinit();+ var agent = root(state.allocator());+ agent.provider = route("openai");+ agent.provider.source = .stored;+ try quota.afterToolsStarted(&agent, "invalid_api_key", "Incorrect API key provided", "raw provider diagnostic");+ try std.testing.expectEqualStrings("OpenAI API key was rejected (secure store): replace or remove the key. Your sign-in is not affected.", agent.last_api_error.?);+ try std.testing.expectEqualStrings("api_key_rejected", agent.last_api_reauth.?.kind);+ agent.provider = route("chatgpt-new");+ try quota.afterToolsStarted(&agent, "token_expired", "Provided authentication token is expired.", "raw provider diagnostic");+ try std.testing.expectEqualStrings("ChatGPT plan (new sign-in) sign-in was rejected: sign in again (graff login chatgpt-new)", agent.last_api_error.?);+ try std.testing.expectEqualStrings("reauth_required", agent.last_api_reauth.?.kind);+ // A non-auth failure keeps the provider's own diagnostic and no metadata.+ try quota.afterToolsStarted(&agent, "server_error", "upstream unavailable", "raw provider diagnostic");+ try std.testing.expectEqualStrings("raw provider diagnostic", agent.last_api_error.?);+ try std.testing.expect(agent.last_api_reauth == null);+}diff --git a/src/acp_v2.zig b/src/acp_v2.zigindex 076d7b69..ba3e3ca4 100644--- a/src/acp_v2.zig+++ b/src/acp_v2.zig@@ -117,6 +117,14 @@ pub fn writeFailed(w: *Io.Writer, sid: []const u8, message: []const u8) !void {pub fn writeFailedRecovery(w: *Io.Writer, sid: []const u8, message: []const u8, recovery: ?@import("auth_recovery.zig").Recovery) !void {const data = recovery orelse return writeFailed(w, sid, message);breakMessage();+ // ADR 0310: only a sign-in action rides `graff/reauth`, which clients read+ // as "signed out"; a rejected API key rides `graff/recovery`.+ if (data.login == null) return notify(w, sid, .{+ .sessionUpdate = "state_update",+ .state = "idle",+ .stopReason = "_error",+ ._meta = .{ .@"graff/error" = message, .@"graff/recovery" = data },+ });try notify(w, sid, .{.sessionUpdate = "state_update",.state = "idle",diff --git a/src/agent_request.zig b/src/agent_request.zigindex e79c8155..87b7c5db 100644--- a/src/agent_request.zig+++ b/src/agent_request.zig@@ -440,8 +440,7 @@ pub fn request(self: *Agent, tools_in: ?[]const u8) !std.json.ObjectMap {self.ws_api_error_pending = false;const diagnostic = try responses.failureDiagnostic(self.arena, self.provider.id, failure);if (@import("agent_async_tools.zig").started(self)) {- self.last_api_reauth = @import("auth_recovery.zig").forFailure(self.provider, failure.code, msg);- try self.sayApiError("{s}", .{diagnostic});+ try quota.afterToolsStarted(self, failure.code, msg, diagnostic);return error.ApiError;}if (ws_error_frame) if (self.tracer) |tr| tr.note("ws_api_error", diagnostic);diff --git a/src/agent_request_quota.zig b/src/agent_request_quota.zigindex a771de07..03b6aa34 100644--- a/src/agent_request_quota.zig+++ b/src/agent_request_quota.zig@@ -119,11 +119,13 @@ pub fn handle(self: *@import("agent.zig").Agent, etype: []const u8, code: ?[]con// faults, after the existing refresh/handoff policy has declined a retry.// Classification already established auth; retain any structured code so// a non-auth code still vetoes a login action (including generic 403).- if (fault == .authentication)- self.last_api_reauth = @import("auth_recovery.zig").forFailure(self.provider, code orelse "authentication_error", "");+ // ADR 0310: the text and metadata name the seat that failed: a sign-in,+ // or a metered key (perhaps the one a spent plan handed over to).+ const auth = @import("auth_recovery.zig");+ if (fault == .authentication) self.last_api_reauth = auth.forAuthFault(self.provider, code orelse "authentication_error");self.last_api_error = switch (fault) {.quota => "provider quota/billing cap: credit or allowance exhausted; retry requires account action",- .authentication => "provider authentication failed: sign in again or check the API key",+ .authentication => auth.failureText(self.arena, self.provider, @import("credential_failover.zig").promoted(self.provider.id)),.access_denied => "provider access denied: check account permissions or route eligibility",};if (self.tracer) |tr| tr.note("provider_terminal", self.last_api_error.?);@@ -134,6 +136,19 @@ pub fn handle(self: *@import("agent.zig").Agent, etype: []const u8, code: ?[]con};}+/// A failure after async tools started skips the retry ladder (the turn has+/// side effects in flight), but an authentication rejection still names the+/// credential that failed, as handle() does.+pub fn afterToolsStarted(self: *@import("agent.zig").Agent, code: ?[]const u8, msg: []const u8, diagnostic: []const u8) !void {+ const auth = @import("auth_recovery.zig");+ if (classify("", code, msg) != .authentication) {+ self.last_api_reauth = auth.forFailure(self.provider, code, msg);+ return self.sayApiError("{s}", .{diagnostic});+ }+ self.last_api_reauth = if (self.provider.source == .login) auth.forFailure(self.provider, code, msg) else auth.forAuthFault(self.provider, code orelse "authentication_error");+ try self.sayApiError("{s}", .{auth.failureText(self.arena, self.provider, @import("credential_failover.zig").promoted(self.provider.id))});+}+// ChatGPT plan errors, as OpenAI's errors-and-recovery page classifies them// (ADR 0221). Only a spent allowance is a limit (429, resets after hours).const plan_limit_code = "subscription_sharing_usage_limit_exceeded";@@ -250,15 +265,20 @@ test "terminal provider faults: numeric HTTP status codes survive envelope parsi}test "terminal provider faults: hard caps and env auth stop without a refresh or retry" {+ var arena = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena.deinit();var self: @import("agent.zig").Agent = undefined;self.provider = .{ .id = "codegraff", .kind = .openai, .auth = .bearer, .url = "", .api_key = "", .model = "test", .context = 1000, .source = .environment };self.tracer = null;+ self.arena = arena.allocator();var refreshed = false;try std.testing.expectError(error.ProviderQuotaExceeded, handle(&self, "server_error", null, "API key: exhausted credit; try again", &refreshed));try std.testing.expect(!refreshed);try std.testing.expect(isQuotaExceeded(self.last_api_error.?));try std.testing.expectError(error.ProviderAuthenticationFailed, handle(&self, "authentication_error", null, "overloaded", &refreshed));try std.testing.expect(!refreshed);+ try std.testing.expectEqualStrings("Codegraff API key was rejected (environment): replace or remove the key. Your sign-in is not affected.", self.last_api_error.?);+ try std.testing.expectEqualStrings("api_key_rejected", self.last_api_reauth.?.kind);try std.testing.expectError(error.ProviderAccessDenied, handle(&self, "permission_error", "403", "", &refreshed));try std.testing.expect(!try handle(&self, "server_error", null, "overloaded", &refreshed));self.provider.source = .login;diff --git a/src/auth_recovery.zig b/src/auth_recovery.zigindex 731a9be5..48b4bc45 100644--- a/src/auth_recovery.zig+++ b/src/auth_recovery.zig@@ -1,33 +1,63 @@-//! Recovery metadata for a terminal model-auth rejection, not a diagnosis of-//! why renewal failed. Only fixed route/command names cross the client boundary.+//! Recovery metadata and wording for a terminal model-auth rejection, not a+//! diagnosis of why renewal failed. Only fixed route/command names cross the+//! client boundary.+//!+//! A provider can hold a sign-in and a metered API key at once (#471), so the+//! text and the metadata name which one was rejected (ADR 0310): a rejected+//! key must not read as "signed out" to a client while the sign-in is fine.const std = @import("std");const provider = @import("provider.zig");const util = @import("util.zig");+pub const Login = struct { command: []const u8, args: []const []const u8 };+pub const Recovery = struct {+ /// "reauth_required" (sign-in seat; carries `login`) or+ /// "api_key_rejected" (metered key seat; no login action).kind: []const u8 = "reauth_required",provider: []const u8,- login: struct { command: []const u8, args: []const []const u8 },+ login: ?Login = null,++ /// `login` is omitted, not null, when there is no sign-in to repair.+ pub fn jsonStringify(self: Recovery, jws: anytype) !void {+ try jws.beginObject();+ try jws.objectField("kind");+ try jws.write(self.kind);+ try jws.objectField("provider");+ try jws.write(self.provider);+ if (self.login) |login| {+ try jws.objectField("login");+ try jws.write(login);+ }+ try jws.endObject();+ }++ /// Only a sign-in action is ACP's "authentication required"; a rejected+ /// key is an ordinary failure that happens to carry data.+ pub fn rpcCode(self: Recovery) i32 {+ const proto = @import("acp_protocol.zig");+ return if (self.login != null) proto.err_auth_required else proto.err_internal;+ }};-pub fn forFailure(p: provider.Provider, code: ?[]const u8, message: []const u8) ?Recovery {- if (p.source != .login) return null;- // A structured non-auth code wins over incidental auth words in a message.- // Do not turn quota, server errors or expired request ids into login actions.- // 401 is preserved by the HTTP adapter/envelope parser, not guessed from text.+/// A structured non-auth code wins over incidental auth words in a message.+/// Do not turn quota, server errors or expired request ids into login actions.+/// 401 is preserved by the HTTP adapter/envelope parser, not guessed from text.+fn authSignal(code: ?[]const u8, message: []const u8) bool {if (code) |c| {- var auth = false;for ([_][]const u8{ "401", "invalid_token", "invalid_api_key", "authentication_error", "token_expired", "subscription_sharing_invalid_user", "subscription_sharing_v2_invalid_user" }) |known| {- if (std.mem.eql(u8, c, known)) auth = true;+ if (std.mem.eql(u8, c, known)) return true;}- if (!auth) return null;- } else {- var auth = false;- for ([_][]const u8{ "unauthorized", "authentication token", "authentication failed", "authentication_error", "invalid_api_key", "invalid_token" }) |needle| {- if (util.indexOfIgnoreCase(message, needle) != null) auth = true;- }- if (!auth) return null;+ return false;+ }+ for ([_][]const u8{ "unauthorized", "authentication token", "authentication failed", "authentication_error", "invalid_api_key", "invalid_token" }) |needle| {+ if (util.indexOfIgnoreCase(message, needle) != null) return true;}+ return false;+}++pub fn forFailure(p: provider.Provider, code: ?[]const u8, message: []const u8) ?Recovery {+ if (p.source != .login or !authSignal(code, message)) return null;if (std.mem.eql(u8, p.id, "chatgpt-new")) return .{.provider = "chatgpt-new",.login = .{ .command = "graff", .args = &.{ "login", "chatgpt-new" } },@@ -39,3 +69,100 @@ pub fn forFailure(p: provider.Provider, code: ?[]const u8, message: []const u8)};return null;}++/// The terminal ProviderAuthenticationFailed boundary: a sign-in seat keeps+/// forFailure's route-specific reauth action; any other seat ran on a metered+/// key, so the metadata says the key was rejected and offers no login.+pub fn forAuthFault(p: provider.Provider, code: ?[]const u8) ?Recovery {+ if (p.source == .login) return forFailure(p, code, "");+ if (!authSignal(code, "")) return null;+ return .{ .kind = "api_key_rejected", .provider = p.id };+}++/// Words the rejected-key texts must never contain: a client reads each of+/// them as "signed out" and offers a sign-in that cannot help.+pub const signed_out_phrases = [_][]const u8{ "sign in again", "log in again", "not signed in", "unauthorized", "authentication failed", "invalid api key" };++/// The stable phrase in both rejected-key texts.+pub const api_key_rejected_phrase = "API key was rejected";++/// The terminal text for an authentication rejection, naming the credential+/// that failed. `promoted`: the seat is the metered key a spent plan handed+/// over to (credential_failover.promoted).+pub fn failureText(a: std.mem.Allocator, p: provider.Provider, promoted: bool) []const u8 {+ const name = if (provider.specFor(p.id)) |spec| spec.display_name else p.id;+ if (p.source == .login) {+ const login: Login = if (forFailure(p, "401", "")) |r| r.login.? else .{ .command = "graff", .args = &.{ "login", p.id } };+ const args = std.mem.join(a, " ", login.args) catch return "provider sign-in was rejected: sign in again";+ return std.fmt.allocPrint(a, "{s} sign-in was rejected: sign in again ({s} {s})", .{ name, login.command, args }) catch+ "provider sign-in was rejected: sign in again";+ }+ if (promoted) return std.fmt.allocPrint(+ a,+ "{s} plan is out of usage, and the fallback " ++ api_key_rejected_phrase ++ " ({s}): replace or remove the key, or wait for the plan to reset.",+ .{ name, p.source.label() },+ ) catch "provider plan is out of usage, and the fallback " ++ api_key_rejected_phrase ++ ": replace or remove the key, or wait for the plan to reset.";+ return std.fmt.allocPrint(+ a,+ "{s} " ++ api_key_rejected_phrase ++ " ({s}): replace or remove the key. Your sign-in is not affected.",+ .{ name, p.source.label() },+ ) catch "provider " ++ api_key_rejected_phrase ++ ": replace or remove the key. Your sign-in is not affected.";+}++fn seat(id: []const u8, source: provider.Keys.CredentialSource) provider.Provider {+ return .{ .id = id, .kind = .anthropic, .auth = .x_api_key, .url = "", .api_key = "k", .model = "m", .context = 1000, .source = source };+}++fn expectNoSignedOutPhrase(text: []const u8) !void {+ for (signed_out_phrases) |phrase| try std.testing.expect(util.indexOfIgnoreCase(text, phrase) == null);+ try std.testing.expect(std.mem.indexOf(u8, text, api_key_rejected_phrase) != null);+}++test "auth failure text names the rejected credential: sign-in, key, promoted key" {+ var arena = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena.deinit();+ const a = arena.allocator();+ try std.testing.expectEqualStrings(+ "Anthropic sign-in was rejected: sign in again (graff login anthropic)",+ failureText(a, seat("anthropic", .login), false),+ );+ try std.testing.expectEqualStrings(+ "ChatGPT plan (new sign-in) sign-in was rejected: sign in again (graff login chatgpt-new)",+ failureText(a, seat("chatgpt-new", .login), false),+ );+ try std.testing.expectEqualStrings(+ "Codex (ChatGPT) sign-in was rejected: sign in again (codex login)",+ failureText(a, seat("codex", .login), false),+ );+ const key = failureText(a, seat("anthropic", .profile), false);+ try std.testing.expectEqualStrings("Anthropic API key was rejected (Console profile): replace or remove the key. Your sign-in is not affected.", key);+ try expectNoSignedOutPhrase(key);+ try expectNoSignedOutPhrase(failureText(a, seat("openai", .environment), false));+ try expectNoSignedOutPhrase(failureText(a, seat("xai", .stored), false));+ const handed = failureText(a, seat("anthropic", .profile), true);+ try std.testing.expectEqualStrings("Anthropic plan is out of usage, and the fallback API key was rejected (Console profile): replace or remove the key, or wait for the plan to reset.", handed);+ try expectNoSignedOutPhrase(handed);+ // Only the sign-in text keeps the words existing clients read as signed out.+ try std.testing.expect(std.mem.indexOf(u8, failureText(a, seat("kimi", .login), false), "sign in again") != null);+}++test "api_key_rejected recovery: metered seats only, no login, internal error code" {+ const r = forAuthFault(seat("anthropic", .profile), "401").?;+ try std.testing.expectEqualStrings("api_key_rejected", r.kind);+ try std.testing.expectEqualStrings("anthropic", r.provider);+ try std.testing.expect(r.login == null);+ try std.testing.expectEqual(@import("acp_protocol.zig").err_internal, r.rpcCode());+ var out: std.Io.Writer.Allocating = .init(std.testing.allocator);+ defer out.deinit();+ var s: std.json.Stringify = .{ .writer = &out.writer };+ try s.write(r);+ try std.testing.expectEqualStrings("{\"kind\":\"api_key_rejected\",\"provider\":\"anthropic\"}", out.writer.buffered());+ // A structured non-auth code still vetoes the metadata.+ try std.testing.expect(forAuthFault(seat("openai", .environment), "403") == null);+ try std.testing.expect(forAuthFault(seat("openai", .environment), "authentication_error") != null);+ // A sign-in seat is unchanged: route-specific reauth, or nothing.+ const reauth = forAuthFault(seat("chatgpt-new", .login), "401").?;+ try std.testing.expectEqualStrings("reauth_required", reauth.kind);+ try std.testing.expectEqual(@import("acp_protocol.zig").err_auth_required, reauth.rpcCode());+ try std.testing.expect(forAuthFault(seat("anthropic", .login), "401") == null);+}diff --git a/src/main.zig b/src/main.zigindex ac5e99f3..26906a5c 100644--- a/src/main.zig+++ b/src/main.zig@@ -53,7 +53,7 @@ test {_ = .{ @import("server_orphan.zig"), @import("term_sender.zig") };_ = @import("repo_transaction.zig");_ = .{ @import("pr_command.zig"), @import("pr_evidence.zig"), @import("artifact_repository.zig"), @import("artifact_claim_ledger.zig"), @import("artifact_claim_store.zig"), @import("artifact_claim_stale.zig"), @import("artifact_claim_unresolved.zig"), @import("artifact_claim_inventory.zig") };- _ = .{ @import("argstream_citation_tests.zig"), @import("acp_reauth_tests.zig") }; // unit_tests' root is main.zig only, so reference every split-out module or its tests silently never run+ _ = .{ @import("argstream_citation_tests.zig"), @import("acp_reauth_tests.zig"), @import("auth_recovery.zig") }; // unit_tests' root is main.zig only, so reference every split-out module or its tests silently never run_ = @import("codex_node_repl.zig");_ = pricing;_ = models_cache;diff --git a/src/providers.zig b/src/providers.zigindex 699a3204..cedf97ba 100644--- a/src/providers.zig+++ b/src/providers.zig@@ -160,6 +160,8 @@ pub fn failoverEligible(provider_id: []const u8, detail: []const u8) bool {"authentication_error","authentication token","authentication failed",+ "sign-in was rejected", // auth_recovery.failureText (ADR 0310)+ "api key was rejected","invalid api key","invalid_api_key","invalid x-api-key",@@ -395,6 +397,8 @@ test "failoverEligible: accepts unavailable credentials/models, rejects transientry std.testing.expect(failoverEligible("codex", "codex api error: Unauthorized"));try std.testing.expect(failoverEligible("codex", "access token has expired"));try std.testing.expect(failoverEligible("codex", "model_not_found: rollout ended"));+ try std.testing.expect(failoverEligible("kimi", "Kimi sign-in was rejected: sign in again (graff login kimi)"));+ try std.testing.expect(failoverEligible("anthropic", "Anthropic plan is out of usage, and the fallback API key was rejected (Console profile): wait"));try std.testing.expect(failoverEligible("codegraff", "insufficient_quota"));try std.testing.expect(!failoverEligible("codex", "network error: HttpConnectionClosing"));try std.testing.expect(!failoverEligible("codex", "rate limited (429)"));diff --git a/src/subagent_run.zig b/src/subagent_run.zigindex f309f119..7e90b4f1 100644--- a/src/subagent_run.zig+++ b/src/subagent_run.zig@@ -118,7 +118,7 @@ pub fn classifyFailure(err: anyerror, detail: ?[]const u8) FailKind {if (containsAnyCI(msg, &.{ "500", "502", "503", "504", "service unavailable", "temporarily unavailable", "bad gateway", "gateway timeout", "internal server error", "overloaded_error" })) return .transport;if (containsAnyCI(msg, &.{ "network error", "stream stalled", "stream dropped", "timed out", "connection reset", "connection closed" })) return .transport;if (containsAnyCI(msg, &.{ "rate limit", "rate_limit", "quota", "429", "overloaded", "out of credits", "credits", "billing", "too many requests" })) return .quota;- if (containsAnyCI(msg, &.{ "api key", "unauthorized", "expired", "authentication", "invalid_api_key", "401" })) return .auth;+ if (containsAnyCI(msg, &.{ "api key", "unauthorized", "expired", "authentication", "invalid_api_key", "401", "sign-in was rejected" })) return .auth;// "unavailable" must stay qualified: bare, it swallows every 5xx above.if (containsAnyCI(msg, &.{ "does not exist", "not found", "no such model", "decommission", "no longer", "model_not_found", "model unavailable", "model is unavailable", "404" })) return .model;if (containsAnyCI(msg, &.{ "context length", "context window", "invalid", "unsupported", "not supported", "must be", "too long", "400", "parameter", "max_tokens", "bad request" })) return .invalid;