Skip to content

graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs

Python

Expose route-specific ACP reauthentication recovery

justrach5f9c9d9eec9d
diff --git a/docs/adr/0246-acp-reauth-is-route-specific.md b/docs/adr/0246-acp-reauth-is-route-specific.md
new file mode 100644
index 00000000..6075249a
--- /dev/null
+++ b/docs/adr/0246-acp-reauth-is-route-specific.md
@@ -0,0 +1,52 @@
+# 0246. ACP reauthentication recovery identifies the exact credential route
+
+Status: accepted 2026-10-03
+
+## Context
+
+A terminal ChatGPT authentication rejection was an ACP internal error with
+only a human-readable message. Clients could not reliably offer sign-in or
+choose its credential store. ADR 0229 makes this distinction important:
+`graff login codex` signs into `chatgpt-new`, not the legacy Codex CLI store.
+Renewal rejection is not repaired by giving a client a login action.
+
+## Decision
+
+Carry fixed recovery metadata from a parsed Responses authentication failure,
+after the existing bounded recovery attempts, without changing retries or
+provider fallback. Only login-sourced `chatgpt-new` and `codex` credentials
+qualify. Known non-auth error codes take precedence over message wording;
+quota, server, transport and request-id expiry errors remain generic failures.
+
+ACP v1 `session/prompt` returns `error.code = -32000` and `error.data`:
+
+```json
+{
+ "kind": "reauth_required",
+ "provider": "chatgpt-new",
+ "login": { "command": "graff", "args": ["login", "chatgpt-new"] }
+}
+```
+
+A legacy `codex` failure instead names `provider: "codex"` and
+`login: {"command":"codex","args":["login"]}`. Its host must retain the
+same `CODEX_HOME` when launching that command. The new route reads Graff's
+`credentials/chatgpt-new.json`; the legacy route reads Codex CLI `auth.json`.
+
+ACP v2 has already accepted the prompt: the same object travels on the failed
+idle `state_update` in `_meta["graff/reauth"]`, alongside `graff/error`, with
+`stopReason: "_error"`. Other errors keep their existing payload.
+
+Recovery metadata contains only fixed route and command names, never raw
+OAuth errors, account details, credential paths or tokens. Clear it at each
+prompt/request so an old authentication failure cannot annotate a later one.
+
+## Consequences
+
+Clients can offer an explicit, host-side sign-in action without parsing error
+text or writing the wrong store. Sign-in is out-of-band; the ACP worker and
+conversation remain usable for another prompt. Clients must not silently
+change a saved Codex session to the new route, automatically execute arbitrary
+commands from other agents, or infer that renewal now works from this signal.
+The signal identifies a rejected model credential, not the permanent/transient
+cause of the preceding refresh attempt.
diff --git a/docs/adr/README.md b/docs/adr/README.md
index 98265dc7..155c9cef 100644
--- a/docs/adr/README.md
+++ b/docs/adr/README.md
@@ -265,6 +265,7 @@ record only when you need the evidence or the edge cases.
| [0236](0236-rlm-takes-json-literals-and-each-maps-plain-values.md) | `rlm` takes JSON array/object literals as arguments and binds (`name = [...]`, bound names allowed inside); its splitters nest `[]`/`{}`; `each(arr, tool[, field])` passes plain items as is, picks `field` from objects (default: an MCP tool's first parameter) and names the fields it found; an unsupported statement lists the forms that work. |
| [0237](0237-deepseek-thinks-at-its-low-level-by-default.md) | DeepSeek's default effort (`medium`) sends `reasoning_effort: low` with thinking enabled; `/effort low` still turns thinking off (ADR 0054), and `high` and above are unchanged. |
| [0238](0238-rlm-binds-keep-the-whole-mcp-result.md) | An MCP call inside an rlm script binds the whole result; `print()` shows the slim view (each item of an `each()` bind cut on its own), `project(x, field)` reads any field (`n`/`latest_author` through a comment list's fold), and `write_file` saves the whole result; inside rlm, `read_tool_result("tr_N")` with no range binds a stored result whole. |
+| [0246](0246-acp-reauth-is-route-specific.md) | Terminal ChatGPT auth rejection carries fixed route-specific recovery metadata: ACP v1 `-32000` + `error.data`, v2 failed idle `_meta["graff/reauth"]`; `graff login chatgpt-new` repairs the new store, `codex login` the legacy one. Retry and non-auth error behavior stay unchanged. |
## When to write one
diff --git a/src/acp.zig b/src/acp.zig
index f375d0e7..44685e12 100644
--- a/src/acp.zig
+++ b/src/acp.zig
@@ -99,6 +99,7 @@ fn liveAfter(ctx: *anyopaque, arena: Allocator, text: []const u8, prompt: ?std.j
fn liveBind(ctx: *anyopaque, session_id: []const u8) void {
const live: *LiveTurn = @ptrCast(@alignCast(ctx));
live.session_id = session_id;
+ live.root.last_api_reauth = null;
}
/// Per-turn context meter: the live occupancy estimate against the model's
@@ -243,6 +244,7 @@ pub fn runAcpCommand(gpa: Allocator, io: Io, environ_map: anytype, root: *agent_
var d: Dispatch = .{
.turn = LiveTurn.run,
.error_message = LiveTurn.errorMessage,
+ .error_recovery = LiveTurn.errorRecovery,
.ctx = &live,
.seed = @bitCast(util.unixMs(io)),
.slash = liveSlash,
diff --git a/src/acp_engine.zig b/src/acp_engine.zig
index feb54de7..4c3e64f3 100644
--- a/src/acp_engine.zig
+++ b/src/acp_engine.zig
@@ -79,6 +79,7 @@ pub const Dispatch = struct {
set_config: ?SetConfigFn = null,
mcp_servers: ?McpServersFn = null,
error_message: ?*const fn (ctx: *anyopaque, err: anyerror) []const u8 = null,
+ error_recovery: ?*const fn (ctx: *anyopaque, err: anyerror) ?@import("auth_recovery.zig").Recovery = null,
/// Live CLI: adopt the client's cwd, report `_meta["graff/worktree"]` (acp_workspace.zig).
workspace: ?acp_workspace.Env = null,
/// ACP v1 draft subagent updates are opt-in at initialize.
@@ -169,7 +170,12 @@ fn turnError(d: *Dispatch, w: *Io.Writer, req: proto.Request, err: anyerror) !vo
return respond(w, req, .{ .stopReason = "cancelled" });
if (err == error.RunBudgetExhausted)
return respond(w, req, .{ .stopReason = "max_turn_requests" });
- return respondError(w, req, err_internal, if (d.error_message) |message| message(d.ctx, err) else @errorName(err));
+ 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);
+ return;
+ };
+ return respondError(w, req, err_internal, message);
}
fn promptTurn(d: *Dispatch, arena: Allocator, w: *Io.Writer, req: proto.Request) !void {
diff --git a/src/acp_live_turn.zig b/src/acp_live_turn.zig
index 8db79ae5..e03eb4f3 100644
--- a/src/acp_live_turn.zig
+++ b/src/acp_live_turn.zig
@@ -42,6 +42,11 @@ pub const LiveTurn = struct {
meter.write(w, self.session_id, used, window, meter.knownCostUsd(self.root.io)) catch {};
}
+ pub fn errorRecovery(ctx: *anyopaque, err: anyerror) ?@import("auth_recovery.zig").Recovery {
+ const self: *LiveTurn = @ptrCast(@alignCast(ctx));
+ return if (err == error.ApiError) self.root.last_api_reauth else null;
+ }
+
pub fn errorMessage(ctx: *anyopaque, err: anyerror) []const u8 {
const self: *LiveTurn = @ptrCast(@alignCast(ctx));
return if (err == error.ApiError) self.root.last_api_error orelse "Provider request failed" else @errorName(err);
diff --git a/src/acp_protocol.zig b/src/acp_protocol.zig
index 76d917e9..48547666 100644
--- a/src/acp_protocol.zig
+++ b/src/acp_protocol.zig
@@ -176,6 +176,10 @@ pub fn writeResult(w: *Io.Writer, id: ?Value, result: anytype) !void {
}
pub fn writeError(w: *Io.Writer, id: ?Value, code: i32, message: []const u8) !void {
+ return writeErrorData(w, id, code, message, null);
+}
+
+pub fn writeErrorData(w: *Io.Writer, id: ?Value, code: i32, message: []const u8, data: anytype) !void {
var s: std.json.Stringify = .{ .writer = w };
try s.beginObject();
try s.objectField("jsonrpc");
@@ -188,6 +192,10 @@ pub fn writeError(w: *Io.Writer, id: ?Value, code: i32, message: []const u8) !vo
try s.write(code);
try s.objectField("message");
try s.write(message);
+ if (@TypeOf(data) != @TypeOf(null)) {
+ try s.objectField("data");
+ try s.write(data);
+ }
try s.endObject();
try s.endObject();
try w.writeByte('\n');
diff --git a/src/acp_reauth_tests.zig b/src/acp_reauth_tests.zig
new file mode 100644
index 00000000..753d45a9
--- /dev/null
+++ b/src/acp_reauth_tests.zig
@@ -0,0 +1,148 @@
+//! Focused regression on parsed Responses failures and both ACP dispatch paths.
+const std = @import("std");
+const Io = std.Io;
+const Agent = @import("agent.zig").Agent;
+const provider = @import("provider.zig");
+const recovery = @import("auth_recovery.zig");
+const engine = @import("acp_engine.zig");
+const LiveTurn = @import("acp_live_turn.zig").LiveTurn;
+const v2 = @import("acp_v2.zig");
+
+fn route(id: []const u8) provider.Provider {
+ return .{ .id = id, .kind = .responses, .auth = .bearer, .url = "", .api_key = "fixture", .model = "fixture", .context = 1000, .source = .login };
+}
+
+fn root(a: std.mem.Allocator) Agent {
+ return .{ .gpa = std.testing.allocator, .arena = a, .io = std.testing.io, .client = undefined, .provider = route("chatgpt-new"), .messages = std.json.Array.init(a), .sub = false, .label = "test", .out = null };
+}
+
+fn parsedFailure(ctx: *anyopaque, a: std.mem.Allocator, text: []const u8) anyerror![]const u8 {
+ const live: *LiveTurn = @ptrCast(@alignCast(ctx));
+ live.root.last_api_reauth = null;
+ if (std.mem.eql(u8, text, "ok")) return "recovered";
+ const parsed = try live.root.parseResponses(text);
+ const failure = parsed.err;
+ live.root.last_api_reauth = recovery.forFailure(live.root.provider, failure.code, failure.message);
+ live.root.last_api_error = try @import("agent_responses.zig").failureDiagnostic(a, live.root.provider.id, failure);
+ return error.ApiError;
+}
+
+const invalid_token = "{\"detail\":{\"error_code\":\"invalid_token\"}}";
+
+fn prompt(a: std.mem.Allocator, text: []const u8) ![]const u8 {
+ var w: Io.Writer.Allocating = .init(a);
+ var s: std.json.Stringify = .{ .writer = &w.writer };
+ try s.write(.{ .id = 3, .method = "session/prompt", .params = .{ .prompt = text } });
+ return w.writer.buffered();
+}
+
+fn dispatch(live: *LiveTurn) engine.Dispatch {
+ return .{ .turn = parsedFailure, .ctx = live, .error_message = LiveTurn.errorMessage, .error_recovery = LiveTurn.errorRecovery };
+}
+
+fn assertLogin(data: std.json.ObjectMap, id: []const u8, command: []const u8) !void {
+ try std.testing.expectEqualStrings("reauth_required", data.get("kind").?.string);
+ try std.testing.expectEqualStrings(id, data.get("provider").?.string);
+ const login = data.get("login").?.object;
+ try std.testing.expectEqualStrings(command, login.get("command").?.string);
+ const args = login.get("args").?.array.items;
+ try std.testing.expectEqualStrings("login", args[0].string);
+ try std.testing.expectEqual(@as(usize, if (std.mem.eql(u8, id, "codex")) 1 else 2), args.len);
+ if (args.len == 2) try std.testing.expectEqualStrings("chatgpt-new", args[1].string);
+ try std.testing.expectEqual(@as(usize, 3), data.count());
+}
+
+test "typed reauth: route and credential source gate the action; non-auth codes win" {
+ var p = route("chatgpt-new");
+ for ([_][]const u8{ "invalid_token", "invalid_api_key", "authentication_error", "token_expired", "subscription_sharing_invalid_user", "subscription_sharing_v2_invalid_user" }) |code| {
+ try std.testing.expect(recovery.forFailure(p, code, "User cannot be verified") != null);
+ }
+ try std.testing.expect(recovery.forFailure(p, null, "Provided authentication token is expired.") != null);
+ for ([_][]const u8{ "server_error", "rate_limit_exceeded", "subscription_sharing_usage_limit_exceeded", "subscription_sharing_v2_usage_limit_exceeded", "context_length_exceeded" }) |code| {
+ try std.testing.expect(recovery.forFailure(p, code, "authentication service unavailable") == null);
+ }
+ try std.testing.expect(recovery.forFailure(p, null, "request id expired") == null);
+ try std.testing.expect(recovery.forFailure(p, null, "connection refused") == null);
+ p.source = .environment;
+ try std.testing.expect(recovery.forFailure(p, "invalid_token", "Unauthorized") == null);
+ p = route("openai");
+ try std.testing.expect(recovery.forFailure(p, "invalid_api_key", "Unauthorized") == null);
+}
+
+test "typed reauth: v1 parsed HTTP and stream auth errors carry route-specific login; next prompt recovers" {
+ defer v2.resetForTest();
+ v2.gate = false;
+ const cancelled = engine.cancel_flag.swap(false, .acq_rel);
+ defer engine.cancel_flag.store(cancelled, .release);
+ var state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer state.deinit();
+ const a = state.allocator();
+ var agent = root(a);
+ var keys: provider.Keys = .{ .values = @splat(null) };
+ var out: Io.Writer.Allocating = .init(a);
+ var live: LiveTurn = .{ .root = &agent, .keys = &keys, .out = &out.writer };
+ var d = dispatch(&live);
+ const bodies = [_][]const u8{
+ invalid_token,
+ "{\"error\":{\"code\":\"token_expired\",\"message\":\"Provided authentication token is expired. Please try signing in again.\"}}",
+ "data: {\"type\":\"response.failed\",\"response\":{\"error\":{\"code\":\"token_expired\",\"message\":\"Provided authentication token is expired. Please try signing in again.\"}}}\n",
+ "data: {\"type\":\"response.failed\",\"response\":{\"error\":{\"code\":\"subscription_sharing_invalid_user\",\"message\":\"User cannot be verified\"}}}\n",
+ };
+ for ([_][]const u8{ "chatgpt-new", "codex" }) |id| {
+ agent.provider = route(id);
+ for (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, -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.expect(LiveTurn.errorRecovery(&live, error.StreamDropped) == null);
+ }
+ }
+ // A subsequent server/quota rejection must not reuse the previous action.
+ for ([_][]const u8{ "server_error", "subscription_sharing_usage_limit_exceeded" }) |code| {
+ out.clearRetainingCapacity();
+ const body = try std.fmt.allocPrint(a, "{{\"error\":{{\"code\":\"{s}\",\"message\":\"authentication service unavailable\"}}}}", .{code});
+ 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);
+ }
+ out.clearRetainingCapacity();
+ try engine.handleLine(&d, a, &out.writer, try prompt(a, "ok"));
+ try 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: v2 accepted prompt carries the same action on the failed idle update" {
+ defer v2.resetForTest();
+ v2.gate = true;
+ var state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer state.deinit();
+ const a = state.allocator();
+ var agent = root(a);
+ var keys: provider.Keys = .{ .values = @splat(null) };
+ var out: Io.Writer.Allocating = .init(a);
+ var live: LiveTurn = .{ .root = &agent, .keys = &keys, .out = &out.writer };
+ var d = dispatch(&live);
+ try engine.handleLine(&d, a, &out.writer, "{\"id\":1,\"method\":\"initialize\",\"params\":{\"protocolVersion\":2}}");
+ out.clearRetainingCapacity();
+ try engine.handleLine(&d, a, &out.writer, try prompt(a, invalid_token));
+ var lines = std.mem.tokenizeScalar(u8, out.writer.buffered(), '\n');
+ var actions: usize = 0;
+ while (lines.next()) |line| {
+ const value = try std.json.parseFromSliceLeaky(std.json.Value, a, line, .{});
+ try std.testing.expect(value.object.get("error") == null);
+ const params = value.object.get("params") orelse continue;
+ const update = params.object.get("update") orelse continue;
+ const meta = update.object.get("_meta") orelse continue;
+ const data = meta.object.get("graff/reauth") orelse continue;
+ try std.testing.expectEqualStrings("_error", update.object.get("stopReason").?.string);
+ try assertLogin(data.object, "chatgpt-new", "graff");
+ actions += 1;
+ }
+ try std.testing.expectEqual(@as(usize, 1), actions);
+}
diff --git a/src/acp_v2.zig b/src/acp_v2.zig
index 91a988f2..f150a8db 100644
--- a/src/acp_v2.zig
+++ b/src/acp_v2.zig
@@ -114,6 +114,17 @@ 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();
+ try notify(w, sid, .{
+ .sessionUpdate = "state_update",
+ .state = "idle",
+ .stopReason = "_error",
+ ._meta = .{ .@"graff/error" = message, .@"graff/reauth" = data },
+ });
+}
+
pub fn writeUsage(w: *Io.Writer, sid: []const u8, used: u64, size: u64) !void {
try notify(w, sid, .{ .sessionUpdate = "usage_update", .used = used, .size = size });
}
diff --git a/src/acp_v2_prompt.zig b/src/acp_v2_prompt.zig
index 8964dd69..53a89e48 100644
--- a/src/acp_v2_prompt.zig
+++ b/src/acp_v2_prompt.zig
@@ -39,11 +39,14 @@ pub fn promptTurn(d: *engine.Dispatch, arena: Allocator, w: *Io.Writer, req: pro
try engine.emitMeter(d, w, sid);
switch (outcome) {
.stop => |stop| try v2.writeIdle(w, sid, stop),
- .failed => |message| try v2.writeFailed(w, sid, message),
+ .failed => |failed| try v2.writeFailedRecovery(w, sid, failed.message, failed.recovery),
}
}
-const Outcome = union(enum) { stop: []const u8, failed: []const u8 };
+const Outcome = union(enum) {
+ stop: []const u8,
+ failed: struct { message: []const u8, recovery: ?@import("auth_recovery.zig").Recovery },
+};
fn run(d: *engine.Dispatch, arena: Allocator, w: *Io.Writer, sid: []const u8, text: []const u8, prompt: ?std.json.Value) Outcome {
@import("acp_citations.zig").endTurn(sid); // a failed turn must not leave a marker open
@@ -64,7 +67,10 @@ fn run(d: *engine.Dispatch, arena: Allocator, w: *Io.Writer, sid: []const u8, te
fn failure(d: *engine.Dispatch, err: anyerror) Outcome {
if (err == error.Interrupted or err == error.Canceled) return .{ .stop = "cancelled" };
if (err == error.RunBudgetExhausted) return .{ .stop = "max_turn_requests" };
- return .{ .failed = if (d.error_message) |message| message(d.ctx, err) else @errorName(err) };
+ return .{ .failed = .{
+ .message = if (d.error_message) |message| message(d.ctx, err) else @errorName(err),
+ .recovery = if (d.error_recovery) |recover| recover(d.ctx, err) else null,
+ } };
}
fn echoTurn(_: *anyopaque, arena: Allocator, text: []const u8) anyerror![]const u8 {
diff --git a/src/agent.zig b/src/agent.zig
index 2316ed89..30adf847 100644
--- a/src/agent.zig
+++ b/src/agent.zig
@@ -203,6 +203,7 @@ pub const Agent = struct {
/// Detail of the most recent API error — carried into the --json `error`
/// event, which otherwise only knows "api error".
last_api_error: ?[]const u8 = null,
+ last_api_reauth: ?@import("auth_recovery.zig").Recovery = null,
/// Text streamed so far in the current request — on Esc-interrupt this is
/// what survives into history (with an "[interrupted]" marker appended).
partial_text: std.ArrayList(u8) = .empty,
diff --git a/src/agent_request.zig b/src/agent_request.zig
index c595f57e..d57bb211 100644
--- a/src/agent_request.zig
+++ b/src/agent_request.zig
@@ -85,6 +85,7 @@ fn sayTypedApiError(self: *Agent, etype: []const u8, ecode: ?[]const u8, emsg: [
}
pub fn request(self: *Agent, tools_in: ?[]const u8) !std.json.ObjectMap {
+ self.last_api_reauth = null;
// Pool-thread Jev results become session state only on this owner thread.
if (Agent.esc_cancel.load(.acquire) or @import("acp_engine.zig").cancel_flag.load(.acquire))
self.jev_effort_pending.invalidate(self.io)
@@ -440,6 +441,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});
return error.ApiError;
}
@@ -480,6 +482,7 @@ pub fn request(self: *Agent, tools_in: ?[]const u8) !std.json.ObjectMap {
// response.failed arm too. Keep it on the same bounded
// overload retry path as SSE and JSON error envelopes.
if (try policy.afterServerErrorOrParseReject(self, "", failure.code, msg, &server_retries, &gw_retry)) continue :rebuild;
+ self.last_api_reauth = @import("auth_recovery.zig").forFailure(self.provider, failure.code, msg);
if (self.tracer) |tr| tr.api(self.label, self.sub, self.provider.model, ms, body.len, resp_body.len, 0, 0, true);
try self.sayApiError("{s}", .{diagnostic});
return error.ApiError;
diff --git a/src/auth_recovery.zig b/src/auth_recovery.zig
new file mode 100644
index 00000000..df348a32
--- /dev/null
+++ b/src/auth_recovery.zig
@@ -0,0 +1,40 @@
+//! Recovery metadata for a terminal model-auth rejection, not a diagnosis of
+//! why renewal failed. Only fixed route/command names cross the client boundary.
+const std = @import("std");
+const provider = @import("provider.zig");
+const util = @import("util.zig");
+
+pub const Recovery = struct {
+ kind: []const u8 = "reauth_required",
+ provider: []const u8,
+ login: struct { command: []const u8, args: []const []const u8 },
+};
+
+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.
+ if (code) |c| {
+ var auth = false;
+ for ([_][]const u8{ "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 (!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;
+ }
+ if (std.mem.eql(u8, p.id, "chatgpt-new")) return .{
+ .provider = "chatgpt-new",
+ .login = .{ .command = "graff", .args = &.{ "login", "chatgpt-new" } },
+ };
+ // ADR 0229: `graff login codex` now logs into chatgpt-new, NOT auth.json.
+ if (std.mem.eql(u8, p.id, "codex")) return .{
+ .provider = "codex",
+ .login = .{ .command = "codex", .args = &.{"login"} },
+ };
+ return null;
+}
diff --git a/src/main.zig b/src/main.zig
index 7a65d043..58adbb83 100644
--- a/src/main.zig
+++ b/src/main.zig
@@ -54,7 +54,7 @@ test {
_ = @import("server_orphan.zig");
_ = @import("repo_transaction.zig");
_ = .{ @import("pr_command.zig"), @import("pr_evidence.zig"), @import("pr_verify.zig"), @import("artifact_repository.zig"), @import("artifact_claim_ledger.zig"), @import("artifact_claim_store.zig"), @import("artifact_claim_stale.zig"), @import("pr_review_input_tests.zig"), @import("artifact_claim_unresolved.zig") };
- _ = @import("argstream_citation_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") }; // 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.zig
index e33f4bdb..534483f6 100644
--- a/src/providers.zig
+++ b/src/providers.zig
@@ -211,6 +211,7 @@ pub fn runTurnWithFallback(root: *Agent, keys: *Keys, arena: Allocator, out: ?*I
attempted[0] = root.provider.id;
while (true) {
root.last_api_error = null;
+ root.last_api_reauth = null;
const result = root.runTurn();
if (result) |text| {
// #255: no clean per-segment choke point exists across the