graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
fix(codex): recover an expired ChatGPT token instead of 401ing forever (#402)
Rach Pradhanb229468e8d73
diff --git a/src/agent_request.zig b/src/agent_request.zigindex 3f5de815..432b5b5a 100644--- a/src/agent_request.zig+++ b/src/agent_request.zig@@ -29,9 +29,9 @@ const run_budget_mod = @import("run_budget.zig");const policy = @import("agent_request_policy.zig");const errorCode = policy.errorCode;-const isAuthError = policy.isAuthError;const isQuotaExceeded = policy.isQuotaExceeded;const recoverContextOverflow = policy.recoverContextOverflow;+const retryAfterAuthRefresh = policy.retryAfterAuthRefresh;const retryTransientServerError = policy.retryTransientServerError;const context = @import("agent_context.zig");@@ -108,9 +108,16 @@ pub fn request(self: *Agent, tools: ?[]const u8) !std.json.ObjectMap {// unless actually near expiry. The refresh internals (file read + JSON parse,// ~1-2KB) are scratch (#124); only the token itself is duped to survive// future requests.+ // #402: codex joins this path. Its on-disk read is unconditional (a ChatGPT+ // token carries no expiry we can cheaply check), which is also codex-rs's+ // STEP 1 — a `graff login` in another terminal is picked up here, without+ // waiting for a 401.if (self.provider.source == .login) {- if (oauth.refreshOAuthKey(self.io, self.gpa, self.scratchAlloc(), self.home, self.provider.id, false, null)) |fresh| {- self.provider.api_key = self.arena.dupe(u8, fresh) catch self.provider.api_key;+ if (oauth.refreshOAuthKey(self.io, self.gpa, self.scratchAlloc(), self.home, self.provider.id, false, null, policy.codexHome(self))) |fresh| {+ // Only re-dupe on a real change: this runs every request, and the+ // session arena is never reclaimed.+ if (!std.mem.eql(u8, fresh, self.provider.api_key))+ self.provider.api_key = self.arena.dupe(u8, fresh) catch self.provider.api_key;}}// #95: scrub any malformed function_call_output before it hits the wire.@@ -348,6 +355,20 @@ pub fn request(self: *Agent, tools: ?[]const u8) !std.json.ObjectMap {self.closeCodexWs();continue :rebuild;}+ // #402: a ChatGPT-backend 401 ("Provided authentication+ // token is expired") lands here as a plain JSON error body,+ // so the #148 reactive refresh further down — which only+ // anthropic/openai bodies reach — never saw it. Auth-expired+ // was terminal on this path: the session, and every+ // auto-compaction it triggered, 401'd forever even after a+ // successful /login.+ if (retryAfterAuthRefresh(self, msg, &auth_refreshed)) {+ // PR #195: a mid-turn resend must re-anchor — the chained+ // WS meter desyncs otherwise — and the held socket was+ // dialed with the stale bearer besides.+ self.closeCodexWs();+ continue :rebuild;+ }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("codex api error: {s}", .{msg});return error.ApiError;@@ -417,18 +438,11 @@ pub fn request(self: *Agent, tools: ?[]const u8) !std.json.ObjectMap {continue;}// #148: a stale login token 401s here with the provider's "API Key- // invalid/expired"; force a refresh and retry once (kimi-code's- // buildAuth(true)). Give up only if the fresh token also fails.- if (!auth_refreshed and self.provider.source == .login and isAuthError(msg)) {- if (oauth.refreshOAuthKey(self.io, self.gpa, self.scratchAlloc(), self.home, self.provider.id, true, self.provider.api_key)) |fresh| {- auth_refreshed = true;- // #124: dupe off the scratch refresh internals — the key must- // survive every later request of the session.- self.provider.api_key = self.arena.dupe(u8, fresh) catch self.provider.api_key;- if (self.tracer) |tr| tr.note("oauth_refresh", "auth error — refreshed login token, retrying");- continue;- }- }+ // invalid/expired"; adopt a newer on-disk token or force a refresh+ // and retry once (kimi-code's buildAuth(true)). Give up only if the+ // fresh token also fails. No closeCodexWs — this branch is never on+ // the codex WS.+ if (retryAfterAuthRefresh(self, msg, &auth_refreshed)) continue;// #193 follow-up: recover an anthropic/openai context-window rejection// in-turn instead of failing the turn (before this only codex recovered;// anthropic and openai died). Shared with the two error branches above.diff --git a/src/agent_request_policy.zig b/src/agent_request_policy.zigindex 96309d51..459e1f66 100644--- a/src/agent_request_policy.zig+++ b/src/agent_request_policy.zig@@ -5,6 +5,7 @@ const std = @import("std");const Agent = @import("agent.zig").Agent;const http = @import("http.zig");const RetryPlan = http.RetryPlan;+const oauth = @import("oauth.zig");const telemetry = @import("telemetry.zig");const util = @import("util.zig");@@ -29,6 +30,124 @@ test "isAuthError (#148): auth failures only, not credits/rate/other" {try std.testing.expect(!isAuthError("context length exceeded"));}+/// The CODEX_HOME this session authenticated against. startup.zig resolves+/// $CODEX_HOME once and parks it on the catalog; the login flows instead always+/// write ~/.codex, which is the `null` fallback inside refreshOAuthKey. Reading+/// or writing the other one would silently refresh a credential the session is+/// not using.+pub fn codexHome(self: *Agent) ?[]const u8 {+ const catalog = self.model_catalog orelse return null;+ return if (catalog.codex_home.len > 0) catalog.codex_home else null;+}++/// #148/#402: a login-sourced credential was rejected. Adopt a token an+/// in-session `/login` (or another process) has already written to disk, else+/// spend the refresh grant — then retry the request once with the new bearer.+///+/// Bounded exactly like codex-rs's UnauthorizedRecovery (reload → refresh →+/// give up and surface the error): `refreshed` is declared OUTSIDE the caller's+/// rebuild loop and is set the moment we attempt anything, so a permanently+/// dead credential fails the turn instead of re-sending a full history forever+/// — the #402 symptom, where every user message re-fired a ~302KB turn body and+/// a ~868KB compaction body. A refresh that hands back the SAME token could not+/// have helped either, so it does not earn a retry.+pub fn retryAfterAuthRefresh(self: *Agent, msg: []const u8, refreshed: *bool) bool {+ if (refreshed.* or self.provider.source != .login or !isAuthError(msg)) return false;+ refreshed.* = true;+ const fresh = oauth.refreshOAuthKey(self.io, self.gpa, self.scratchAlloc(), self.home, self.provider.id, true, self.provider.api_key, codexHome(self)) orelse return false;+ if (std.mem.eql(u8, fresh, self.provider.api_key)) return false;+ // #124: dupe off the scratch refresh internals — the key must survive every+ // later request of the session.+ self.provider.api_key = self.arena.dupe(u8, fresh) catch self.provider.api_key;+ if (self.tracer) |tr| tr.note("oauth_refresh", "auth error — refreshed login token, retrying");+ return true;+}++test "retryAfterAuthRefresh (#402): one attempt per request, login-sourced auth errors only" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ var agent: Agent = undefined;+ agent.arena = arena_state.allocator();+ agent.tracer = null;+ agent.provider = .{ .id = "codex", .kind = .responses, .auth = .bearer, .url = "", .api_key = "expired-tok", .model = "gpt-5.6", .context = 272000, .source = .environment };+ const expired = "Provided authentication token is expired. Please re-authenticate.";++ // An env key has no refresh flow — it must never reach the network.+ var refreshed = false;+ try std.testing.expect(!retryAfterAuthRefresh(&agent, expired, &refreshed));+ try std.testing.expect(!refreshed);++ // Already attempted this request: no second refresh, so no second resend of a+ // full history (#402's runaway 302KB + 868KB bodies).+ agent.provider.source = .login;+ refreshed = true;+ try std.testing.expect(!retryAfterAuthRefresh(&agent, expired, &refreshed));++ // Non-auth failures must never burn a refresh token. A broadened isAuthError+ // would rotate credentials on quota 429s and context rejections.+ for ([_][]const u8{+ "rate limit exceeded",+ "You have run out of credits or need a Grok subscription.",+ "prompt is too long: 219373 tokens > 200000 maximum",+ "model not found",+ }) |msg| {+ var not_auth = false;+ try std.testing.expect(!retryAfterAuthRefresh(&agent, msg, ¬_auth));+ try std.testing.expect(!not_auth);+ }+}++test "retryAfterAuthRefresh (#402): a codex 401 adopts the token /login wrote, then stops" {+ const io = std.testing.io;+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const arena = arena_state.allocator();++ var tmp = std.testing.tmpDir(.{});+ defer tmp.cleanup();+ var real_buf: [std.fs.max_path_bytes]u8 = undefined;+ const codex_home = real_buf[0..try tmp.dir.realPath(io, &real_buf)];+ const auth_path = try std.fmt.allocPrint(arena, "{s}/auth.json", .{codex_home});+ try std.Io.Dir.cwd().writeFile(io, .{+ .sub_path = auth_path,+ .data =+ \\{"tokens":{"access_token":"fresh-tok","refresh_token":"r1","account_id":"a"}}+ ,+ });++ var agent: Agent = undefined;+ agent.io = io;+ agent.gpa = std.testing.allocator;+ agent.arena = arena;+ agent.scratch_arena = null;+ agent.home = "/graff-test-no-such-home";+ agent.tracer = null;+ agent.model_catalog = .{ .codex_home = codex_home }; // startup's resolved $CODEX_HOME+ agent.provider = .{ .id = "codex", .kind = .responses, .auth = .bearer, .url = "", .api_key = "expired-tok", .model = "gpt-5.6", .context = 272000, .source = .login };+ const expired = "Provided authentication token is expired. Please re-authenticate.";++ // The literal issue reproduction: /login rewrote auth.json, the live session was+ // still on the expired bearer. The retry must pick the new one up with no+ // network call and no restart.+ var refreshed = false;+ try std.testing.expect(retryAfterAuthRefresh(&agent, expired, &refreshed));+ try std.testing.expect(refreshed);+ try std.testing.expectEqualStrings("fresh-tok", agent.provider.api_key);+ try std.testing.expect(!retryAfterAuthRefresh(&agent, expired, &refreshed)); // bounded++ // A refresh that can only hand back the SAME token cannot help; retrying would+ // just re-send the whole history for another guaranteed 401.+ try std.Io.Dir.cwd().writeFile(io, .{+ .sub_path = auth_path,+ .data =+ \\{"tokens":{"access_token":"fresh-tok","refresh_token":"","account_id":"a"}}+ ,+ });+ var again = false;+ try std.testing.expect(!retryAfterAuthRefresh(&agent, expired, &again));+ try std.testing.expect(again); // attempt was spent, so the turn fails instead of looping+}+/// True if `msg` is a provider's "input is over the context window" rejection,/// across wire formats: codex/responses ("exceeds the context window"), openai/// ("maximum context length", "context_length_exceeded"), anthropic ("prompt isdiff --git a/src/agent_ws_test.zig b/src/agent_ws_test.zigindex 2a3f0ce1..695d19ed 100644--- a/src/agent_ws_test.zig+++ b/src/agent_ws_test.zig@@ -48,6 +48,42 @@ test "codexWsIdleExpired: fires only strictly past the idle limit (codex-ws)" {try std.testing.expect(agent_ws.codexWsIdleExpired(1_000_000 + 510 * std.time.ms_per_s, 1_000_000)); // the real 8.5-min trace gap}+// (#402) The codex `.responses` error arm must recover from a rejected auth+// token the way the anthropic/openai arm does. Before the fix the #148 refresh+// lived only inside the generic apiErrorMessage branch, which a ChatGPT-backend+// 401 never reaches (the whole responses arm returns above it), so "Provided+// authentication token is expired" was terminal for the rest of the session.+//+// And because the retry re-sends the full history mid-turn, it must re-anchor+// first (PR #195): `continue :rebuild` over a live previous_response_id desyncs+// the chained WS meter, and the held socket still carries the stale bearer.+//+// The pure unit tests over retryAfterAuthRefresh all pass even if this call site+// is deleted, so pin the site itself — same shape as the source pins in+// route_policy_tests.zig / route_phase_tests.zig.+test "the codex .responses arm refreshes auth and re-anchors before resending (#402)" {+ const src = @embedFile("agent_request.zig");+ const arm_start = std.mem.indexOf(u8, src, "unparseable codex response").?;+ const arm_end = std.mem.indexOf(u8, src, "codex api error: {s}").?;+ const arm = src[arm_start..arm_end];++ const call = std.mem.indexOf(u8, arm, "retryAfterAuthRefresh(self, msg, &auth_refreshed)") orelse+ return error.ResponsesPathHasNoAuthRecovery;+ const after = arm[call..];+ const reanchor = std.mem.indexOf(u8, after, "closeCodexWs()") orelse return error.RetryDoesNotReanchor;+ const resend = std.mem.indexOf(u8, after, "continue :rebuild") orelse return error.RetryDoesNotRebuild;+ try std.testing.expect(reanchor < resend);++ // Both wire formats go through the one helper — no second, drifting copy.+ try std.testing.expect(std.mem.indexOf(u8, src[arm_end..], "retryAfterAuthRefresh(self, msg, &auth_refreshed)") != null);++ // The guard bool is declared OUTSIDE `rebuild:`. Reset it inside the loop and a+ // permanently dead credential refresh-and-resends a full history forever, which+ // is strictly worse than the bug being fixed.+ try std.testing.expect(std.mem.indexOf(u8, src, "var auth_refreshed = false;").? <+ std.mem.indexOf(u8, src, "rebuild: while (true)").?);+}+test "WS fallback latches only after a retry" {try std.testing.expect(!agent_ws.wsShouldFallback(0));try std.testing.expect(!agent_ws.wsShouldFallback(1));diff --git a/src/oauth.zig b/src/oauth.zigindex c19545b9..58f35591 100644--- a/src/oauth.zig+++ b/src/oauth.zig@@ -72,27 +72,15 @@ var oauth_refresh_mutex: Io.Mutex = .init;// auth.openai.com). `harness login` runs the browser flow; `harness login// --refresh` refreshes the stored token (no browser).const oauth_authorize_url = "https://auth.openai.com/oauth/authorize";-const oauth_token_url = "https://auth.openai.com/oauth/token";-const codex_client_id = "app_EMoamEEZ73f0CkXaXp7hrann";+const oauth_token_url = helpers.codex_token_url;+const codex_client_id = helpers.codex_client_id;const codex_redirect = "http://localhost:1455/auth/callback";const codex_redirect_enc = "http%3A%2F%2Flocalhost%3A1455%2Fauth%2Fcallback";-const oauth_scope_enc = "openid%20profile%20email%20offline_access";+const oauth_scope_enc = helpers.codex_scope_enc;/// POST a form body to the OAuth token endpoint; return the parsed JSON object.fn oauthTokenPost(io: Io, gpa: Allocator, arena: Allocator, body: []const u8) !std.json.ObjectMap {- var client: std.http.Client = .{ .allocator = gpa, .io = io };- defer client.deinit();- var aw: Io.Writer.Allocating = .init(arena);- _ = try client.fetch(.{- .location = .{ .url = oauth_token_url },- .method = .POST,- .payload = body,- .response_writer = &aw.writer,- .headers = .{ .content_type = .{ .override = "application/x-www-form-urlencoded" } },- });- const v = try std.json.parseFromSliceLeaky(Value, arena, aw.writer.buffered(), .{ .allocate = .alloc_always });- if (v != .object) return error.BadOAuthResponse;- return v.object;+ return helpers.oauthFormPost(io, gpa, arena, oauth_token_url, body);}/// `harness login [--refresh]`: the ChatGPT/Codex OAuth flow. Fresh login runs@@ -326,24 +314,9 @@ pub fn kimiLogin(io: Io, gpa: Allocator, arena: Allocator, home: []const u8) !vo}/// #245 single-flight guard: has the token that just 401'd already been replaced-/// on disk by another concurrent refresher?-///-/// `force` means "the access token I was holding just failed with a 401". The-/// refresh mutex serializes concurrent refreshers but does NOT dedupe them, so a-/// fleet of subagents that all 401 on the same expired token would each re-mint-/// in turn. Kimi (and xAI) rotate refresh tokens and INVALIDATE the superseded-/// access token, so refresher N+1 kills the token refresher N just adopted — the-/// 401 cascade that wipes out a whole fleet.-///-/// If the on-disk token already differs from the one that failed, the 401 was-/// about the OLD token and somebody else has already done the work: adopt theirs-/// instead of minting another. `stale == null` keeps the previous behaviour for-/// callers that cannot say which token failed.-fn supersededToken(force: bool, on_disk: []const u8, stale: ?[]const u8) bool {- if (!force) return false;- const failed = stale orelse return false;- return !std.mem.eql(u8, on_disk, failed);-}+/// on disk by another concurrent refresher? Defined in oauth_helpers.zig, where+/// the silent codex refresh (#402) needs the same primitive.+const supersededToken = helpers.supersededToken;/// Reads the stored Kimi OAuth access token, refreshing it in place when within/// 60s of expiry. Returns null if not logged in. Mirrors loadCodexAuth.@@ -373,18 +346,28 @@ pub fn loadKimiOAuth(io: Io, gpa: Allocator, arena: Allocator, home: []const u8,return access;}-/// #148: mid-session refresh for a login-sourced key. For the short-lived-/// refreshable OAuth providers (kimi/xai) returns the current access token,-/// refreshed in place if within oauth_refresh_margin_s of expiry (or `force`d,-/// e.g. after a 401). Returns null for providers with no auto-refresh flow-/// (env keys, and the long-lived codex/codegraff tokens), so the caller keeps-/// the key it has. Mutex-guarded so concurrent subagents don't double-refresh.-pub fn refreshOAuthKey(io: Io, gpa: Allocator, arena: Allocator, home: []const u8, provider_id: []const u8, force: bool, stale: ?[]const u8) ?[]const u8 {+/// #148: mid-session refresh for a login-sourced key. For the refreshable OAuth+/// providers (kimi/xai/codex) returns the current access token, refreshed in+/// place if near expiry or `force`d (e.g. after a 401). Returns null for+/// providers with no auto-refresh flow (env keys, the long-lived codegraff+/// token), so the caller keeps the key it has. Mutex-guarded so concurrent+/// subagents don't double-refresh.+///+/// #402: codex used to be excluded here as "long-lived" — it is not, and that+/// premise is what made an expired ChatGPT token unrecoverable for the life of+/// a session. `codex_home` must be the dir startup resolved from $CODEX_HOME;+/// null falls back to ~/.codex, which is what the login flows write.+pub fn refreshOAuthKey(io: Io, gpa: Allocator, arena: Allocator, home: []const u8, provider_id: []const u8, force: bool, stale: ?[]const u8, codex_home: ?[]const u8) ?[]const u8 {const is_kimi = std.mem.eql(u8, provider_id, "kimi");const is_xai = std.mem.eql(u8, provider_id, "xai");- if (!is_kimi and !is_xai) return null;+ const is_codex = std.mem.eql(u8, provider_id, "codex");+ if (!is_kimi and !is_xai and !is_codex) return null;oauth_refresh_mutex.lockUncancelable(io);defer oauth_refresh_mutex.unlock(io);+ if (is_codex) {+ const dir = codex_home orelse (std.fmt.allocPrint(arena, "{s}/.codex", .{home}) catch return null);+ return helpers.loadCodexOAuth(io, gpa, arena, dir, force, stale);+ }return if (is_kimi) loadKimiOAuth(io, gpa, arena, home, force, stale) else loadXaiOAuth(io, gpa, arena, home, force, stale);}diff --git a/src/oauth_helpers.zig b/src/oauth_helpers.zigindex 9dad99c8..254ca256 100644--- a/src/oauth_helpers.zig+++ b/src/oauth_helpers.zig@@ -1,4 +1,6 @@-//! Codex callback parsing and common browser helpers used by OAuth login flows.+//! Codex credential IO, callback parsing and the common browser helpers used by+//! the OAuth login flows — plus the silent codex token refresh the request loop+//! runs mid-turn (#402), which must stay off stdout.const std = @import("std");const builtin = @import("builtin");@@ -7,6 +9,15 @@ const Io = std.Io;const Value = std.json.Value;const Allocator = std.mem.Allocator;+const strFieldObj = @import("util.zig").strFieldObj;++// Codex / ChatGPT OAuth client — the same client + endpoints the Codex CLI+// uses. Owned here (not in oauth.zig) so the silent refresh below can reach+// them without importing back into its own importer.+pub const codex_client_id = "app_EMoamEEZ73f0CkXaXp7hrann";+pub const codex_token_url = "https://auth.openai.com/oauth/token";+pub const codex_scope_enc = "openid%20profile%20email%20offline_access";+pub fn b64url(arena: Allocator, bytes: []const u8) []const u8 {const enc = std.base64.url_safe_no_pad.Encoder;const buf = arena.alloc(u8, enc.calcSize(bytes.len)) catch return "";@@ -30,8 +41,21 @@ pub fn accountFromIdToken(arena: Allocator, id_token: []const u8) []const u8 {return if (account == .string) account.string else "";}+pub fn codexAuthPath(arena: Allocator, codex_home: []const u8) ![]const u8 {+ return std.fmt.allocPrint(arena, "{s}/auth.json", .{codex_home});+}+pub fn writeCodexAuth(io: Io, arena: Allocator, home: []const u8, id_token: []const u8, access: []const u8, refresh: []const u8, account: []const u8) !void {- const path = try std.fmt.allocPrint(arena, "{s}/.codex/auth.json", .{home});+ const dir = try std.fmt.allocPrint(arena, "{s}/.codex", .{home});+ return writeCodexAuthAt(io, arena, dir, id_token, access, refresh, account);+}++/// Same, against an explicit CODEX_HOME. The silent refresh must write back to+/// the file it read: startup resolves $CODEX_HOME (startup.zig), while the login+/// flows always target ~/.codex, and refreshing the wrong file would either+/// no-op or clobber an unrelated credential.+pub fn writeCodexAuthAt(io: Io, arena: Allocator, codex_home: []const u8, id_token: []const u8, access: []const u8, refresh: []const u8, account: []const u8) !void {+ const path = try codexAuthPath(arena, codex_home);var tokens: std.json.ObjectMap = .empty;try tokens.put(arena, "id_token", .{ .string = id_token });try tokens.put(arena, "access_token", .{ .string = access });@@ -52,6 +76,120 @@ pub fn writeCodexAuth(io: Io, arena: Allocator, home: []const u8, id_token: []cotry writer.interface.flush();}+/// POST a urlencoded form body to an OAuth token endpoint; return the parsed+/// JSON object. Shared by the interactive login flows and by the silent+/// mid-turn refresh below (#402), which cannot use codexLogin: that one prints+/// progress to stdout and would corrupt a live stream.+pub fn oauthFormPost(io: Io, gpa: Allocator, arena: Allocator, url: []const u8, body: []const u8) !std.json.ObjectMap {+ var client: std.http.Client = .{ .allocator = gpa, .io = io };+ defer client.deinit();+ var aw: Io.Writer.Allocating = .init(arena);+ _ = try client.fetch(.{+ .location = .{ .url = url },+ .method = .POST,+ .payload = body,+ .response_writer = &aw.writer,+ .headers = .{ .content_type = .{ .override = "application/x-www-form-urlencoded" } },+ });+ const v = try std.json.parseFromSliceLeaky(Value, arena, aw.writer.buffered(), .{ .allocate = .alloc_always });+ if (v != .object) return error.BadOAuthResponse;+ return v.object;+}++/// #245: `force` means "the access token I was holding just failed with a 401".+/// The refresh mutex serializes concurrent refreshers but does NOT dedupe them,+/// so a fleet of subagents that all 401 on the same expired token would each+/// re-mint in turn. Kimi (and xAI) rotate refresh tokens and INVALIDATE the+/// superseded access token, so refresher N+1 kills the token refresher N just+/// adopted — the 401 cascade that wipes out a whole fleet.+///+/// If the on-disk token already differs from the one that failed, the 401 was+/// about the OLD token and somebody else has already done the work: adopt theirs+/// instead of minting another. `stale == null` keeps the previous behaviour for+/// callers that cannot say which token failed.+pub fn supersededToken(force: bool, on_disk: []const u8, stale: ?[]const u8) bool {+ if (!force) return false;+ const failed = stale orelse return false;+ return !std.mem.eql(u8, on_disk, failed);+}++/// The stored Codex credential, including the refresh_token that+/// oauth.loadCodexAuthFrom drops.+pub const StoredCodexAuth = struct {+ access: []const u8,+ refresh: []const u8 = "",+ id_token: []const u8 = "",+ account: []const u8 = "",+};++/// Read <codex_home>/auth.json in full. Null when missing/unparseable/empty,+/// i.e. not logged in.+pub fn readCodexAuth(io: Io, arena: Allocator, codex_home: []const u8) ?StoredCodexAuth {+ const path = codexAuthPath(arena, codex_home) catch return null;+ const data = Io.Dir.cwd().readFileAlloc(io, path, arena, .limited(256 * 1024)) catch return null;+ const v = std.json.parseFromSliceLeaky(Value, arena, data, .{ .allocate = .alloc_always }) catch return null;+ if (v != .object) return null;+ const tokens = v.object.get("tokens") orelse return null;+ if (tokens != .object) return null;+ const access = strFieldObj(tokens.object, "access_token") orelse return null;+ if (access.len == 0) return null;+ return .{+ .access = access,+ .refresh = strFieldObj(tokens.object, "refresh_token") orelse "",+ .id_token = strFieldObj(tokens.object, "id_token") orelse "",+ .account = strFieldObj(tokens.object, "account_id") orelse "",+ };+}++/// A refresh grant that this refresh_token can never satisfy, however often it+/// is retried — as opposed to a transient 5xx/offline failure, which must stay+/// retryable. codex-rs caches exactly these for the current auth snapshot so a+/// dead credential stops costing a round trip per request.+pub fn permanentRefreshFailure(code: []const u8) bool {+ const permanent = [_][]const u8{ "invalid_grant", "invalid_client", "refresh_token_expired", "refresh_token_reused", "refresh_token_invalidated" };+ for (permanent) |p| if (std.mem.eql(u8, code, p)) return true;+ return false;+}++/// Set to the Wyhash of a refresh_token whose grant failed permanently. Only+/// ever read/written under oauth.refreshOAuthKey's mutex, and a lost race costs+/// one extra POST, never a wrong credential.+var dead_refresh_token: u64 = 0;++/// #402: the codex sibling of oauth.loadKimiOAuth — the current ChatGPT access+/// token for `codex_home`, refreshed in place when `force` (i.e. the token we+/// were holding just 401'd). ChatGPT access tokens DO expire; treating them as+/// long-lived is what left an expired session unrecoverable.+///+/// Order matters and mirrors codex-rs's UnauthorizedRecovery. STEP 1: re-read+/// auth.json and adopt whatever is on disk if it already differs from the token+/// that failed — an in-session `/login`, a second graff, or the real Codex CLI+/// has already done the work, and re-minting would rotate-kill their token.+/// STEP 2, only then, spend the refresh_token. On a failed grant it returns the+/// token it read, so the caller (which compares against the stale one) gives up+/// instead of resending forever.+pub fn loadCodexOAuth(io: Io, gpa: Allocator, arena: Allocator, codex_home: []const u8, force: bool, stale: ?[]const u8) ?[]const u8 {+ const auth = readCodexAuth(io, arena, codex_home) orelse return null;+ if (supersededToken(force, auth.access, stale)) return auth.access;+ if (!force or auth.refresh.len == 0) return auth.access;+ const refresh_id = std.hash.Wyhash.hash(0, auth.refresh);+ if (refresh_id == dead_refresh_token) return auth.access; // known dead: no round trip+ const body = std.fmt.allocPrint(arena, "grant_type=refresh_token&client_id={s}&refresh_token={s}&scope={s}", .{ codex_client_id, auth.refresh, codex_scope_enc }) catch return auth.access;+ const resp = oauthFormPost(io, gpa, arena, codex_token_url, body) catch return auth.access; // transient: retryable, do not cache+ if (resp.get("error")) |e| {+ if (permanentRefreshFailure(if (e == .string) e.string else "")) dead_refresh_token = refresh_id;+ return auth.access;+ }+ const access = strFieldObj(resp, "access_token") orelse return auth.access;+ if (access.len == 0) return auth.access;+ const id_token = strFieldObj(resp, "id_token") orelse auth.id_token;+ const refresh = strFieldObj(resp, "refresh_token") orelse auth.refresh;+ var account = if (id_token.len > 0) accountFromIdToken(arena, id_token) else "";+ if (account.len == 0) account = auth.account; // a rotated grant may omit id_token+ writeCodexAuthAt(io, arena, codex_home, id_token, access, refresh, account) catch {};+ return access;+}+/// The page the Codex OAuth callback tab lands on after a successful login./// A branded, dark-mode-aware confirmation card; the local server writes this/// back, then reads the ?code out of the same request for the token exchange.@@ -97,6 +235,82 @@ pub fn queryParam(req_line: []const u8, key: []const u8) ?[]const u8 {return null;}+test "#402: loadCodexOAuth adopts the token /login wrote instead of minting a new one" {+ const io = std.testing.io;+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const arena = arena_state.allocator();++ var tmp = std.testing.tmpDir(.{});+ defer tmp.cleanup();+ var real_buf: [std.fs.max_path_bytes]u8 = undefined;+ const codex_home = real_buf[0..try tmp.dir.realPath(io, &real_buf)];++ // Not logged in: nothing to adopt or refresh, the caller keeps its own key.+ try std.testing.expect(loadCodexOAuth(io, std.testing.allocator, arena, codex_home, false, null) == null);++ // Proactive read (force=false): the on-disk token, no grant spent.+ try writeCodexAuthAt(io, arena, codex_home, "", "tok-expired", "refresh-1", "acct-1");+ try std.testing.expectEqualStrings("tok-expired", loadCodexOAuth(io, std.testing.allocator, arena, codex_home, false, null).?);++ // The #402 case: `/login` (or a second graff, or the real Codex CLI) rewrote+ // auth.json while this session still held the old token. Recovering from that+ // 401 must adopt what is on disk — no network call, and no #245 rotate-kill of+ // the credential the other writer just minted.+ try writeCodexAuthAt(io, arena, codex_home, "", "tok-fresh", "refresh-2", "acct-2");+ try std.testing.expectEqualStrings("tok-fresh", loadCodexOAuth(io, std.testing.allocator, arena, codex_home, true, "tok-expired").?);++ // Same token still on disk and no refresh_token to spend: hand back what was+ // read so the caller can see the refresh did not help and stop.+ try writeCodexAuthAt(io, arena, codex_home, "", "tok-fresh", "", "acct-2");+ try std.testing.expectEqualStrings("tok-fresh", loadCodexOAuth(io, std.testing.allocator, arena, codex_home, true, "tok-fresh").?);++ // readCodexAuth surfaces the refresh_token that oauth.loadCodexAuthFrom drops.+ try writeCodexAuthAt(io, arena, codex_home, "", "tok-fresh", "refresh-3", "acct-9");+ const stored = readCodexAuth(io, arena, codex_home).?;+ try std.testing.expectEqualStrings("refresh-3", stored.refresh);+ try std.testing.expectEqualStrings("acct-9", stored.account);+}++test "#402: permanentRefreshFailure separates a dead refresh_token from a retryable blip" {+ // These can never succeed on a retry — cache them so a dead credential stops+ // costing a token-endpoint round trip on every request.+ try std.testing.expect(permanentRefreshFailure("invalid_grant"));+ try std.testing.expect(permanentRefreshFailure("refresh_token_expired"));+ try std.testing.expect(permanentRefreshFailure("refresh_token_reused"));+ try std.testing.expect(permanentRefreshFailure("refresh_token_invalidated"));+ // Transient / unknown: must stay retryable, or one bad minute would wedge the+ // credential for the rest of the session.+ try std.testing.expect(!permanentRefreshFailure("server_error"));+ try std.testing.expect(!permanentRefreshFailure("temporarily_unavailable"));+ try std.testing.expect(!permanentRefreshFailure("slow_down"));+ try std.testing.expect(!permanentRefreshFailure(""));+}++test "#402: writeCodexAuth targets ~/.codex while writeCodexAuthAt honours CODEX_HOME" {+ const io = std.testing.io;+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const arena = arena_state.allocator();++ var tmp = std.testing.tmpDir(.{});+ defer tmp.cleanup();+ var real_buf: [std.fs.max_path_bytes]u8 = undefined;+ const base = real_buf[0..try tmp.dir.realPath(io, &real_buf)];++ // A custom CODEX_HOME must not be redirected to ~/.codex: startup reads+ // $CODEX_HOME, so refreshing the wrong file would silently no-op.+ const custom = try std.fmt.allocPrint(arena, "{s}/custom", .{base});+ try Io.Dir.cwd().createDirPath(io, custom);+ try writeCodexAuthAt(io, arena, custom, "", "at-tok", "r", "a");+ try std.testing.expectEqualStrings("at-tok", readCodexAuth(io, arena, custom).?.access);++ try Io.Dir.cwd().createDirPath(io, try std.fmt.allocPrint(arena, "{s}/.codex", .{base}));+ try writeCodexAuth(io, arena, base, "", "home-tok", "r", "a");+ try std.testing.expectEqualStrings("home-tok", readCodexAuth(io, arena, try std.fmt.allocPrint(arena, "{s}/.codex", .{base})).?.access);+ try std.testing.expectEqualStrings("at-tok", readCodexAuth(io, arena, custom).?.access); // untouched+}+pub fn openBrowser(io: Io, url: []const u8) void {const argv: []const []const u8 = if (builtin.os.tag == .macos)&.{ "open", url }diff --git a/src/picker_auth.zig b/src/picker_auth.zigindex de398ac4..a9ebf512 100644--- a/src/picker_auth.zig+++ b/src/picker_auth.zig@@ -35,39 +35,111 @@ pub const PickerFn = *const fn () ?usize;/// After an in-session `/login` writes its credential file, pull the fresh key-/// (and the Codex account id) into the live Keys so the current conversation-/// uses it without a restart — the in-session twin of the startup loaders.+/// (and the Codex account id) into the live Keys AND into the running agent, so+/// the current conversation uses it without a restart — the in-session twin of+/// the startup loaders.pub fn reloadLoginKey(root: *Agent, keys: *Keys, arena: Allocator, provider_id: []const u8) void {const home = root.home;for (provider_specs, &keys.values, &keys.sources) |spec, *value, *source| {if (!std.mem.eql(u8, spec.id, provider_id)) continue;+ var reloaded = false;if (std.mem.eql(u8, provider_id, "codegraff")) {if (oauth.loadCodegraffKey(root.io, arena, home)) |k| {value.* = k;source.* = .login;+ reloaded = true;}} else if (std.mem.eql(u8, provider_id, "kimi")) {if (oauth.loadKimiOAuth(root.io, root.gpa, arena, home, false, null)) |k| {value.* = k;source.* = .login;+ reloaded = true;}} else if (std.mem.eql(u8, provider_id, "xai")) {if (oauth.loadXaiOAuth(root.io, root.gpa, arena, home, false, null)) |k| {value.* = k;source.* = .login;+ reloaded = true;}} else if (std.mem.eql(u8, provider_id, "codex")) {if (oauth.loadCodexAuth(root.io, arena, home)) |auth| {value.* = auth.token;source.* = .login;keys.codex_account = auth.account;+ reloaded = true;}}+ // #402: the live Agent holds its OWN Provider copy — providers.applyProviderInner+ // is otherwise the only writer — so refreshing Keys alone left the active+ // session bound to the token that had just expired: `/login` reported success+ // and every following turn (plus its auto-compaction) kept 401ing. The+ // provider.id guard is what keeps `/login kimi` from hijacking a live codex+ // session; the model-picker path re-assigns via switchProvider anyway.+ if (reloaded and std.mem.eql(u8, root.provider.id, provider_id)) {+ const key = value.* orelse continue;+ root.provider.api_key = root.arena.dupe(u8, key) catch key;+ root.provider.source = .login;+ if (std.mem.eql(u8, provider_id, "codex")) root.provider.account = keys.codex_account;+ root.closeCodexWs(); // the held socket was dialed with the stale bearer+ }}if (std.mem.eql(u8, provider_id, "codex") and keys.get("codex") != null)root.reloadModelCatalog(keys.*);}+test "#402: reloadLoginKey hot-reloads the ACTIVE agent's credential, not just Keys" {+ const io = std.testing.io;+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const arena = arena_state.allocator();++ var tmp = std.testing.tmpDir(.{});+ defer tmp.cleanup();+ var real_buf: [std.fs.max_path_bytes]u8 = undefined;+ const home = real_buf[0..try tmp.dir.realPath(io, &real_buf)];+ try Io.Dir.cwd().createDirPath(io, try std.fmt.allocPrint(arena, "{s}/.codex", .{home}));+ try Io.Dir.cwd().writeFile(io, .{+ .sub_path = try std.fmt.allocPrint(arena, "{s}/.codex/auth.json", .{home}),+ .data =+ \\{"tokens":{"access_token":"fresh-tok","refresh_token":"r1","account_id":"acct-2"}}+ ,+ });++ var root: Agent = undefined;+ root.io = io;+ root.gpa = std.testing.allocator;+ root.arena = arena;+ root.home = home;+ root.model_catalog = null; // the catalog reload would go to the network+ root.codex_ws = null;+ root.codex_prev_id = try std.testing.allocator.dupe(u8, "resp_stale");+ root.codex_sent_upto = 7;+ root.provider = .{ .id = "codex", .kind = .responses, .auth = .bearer, .url = "", .api_key = "expired-tok", .model = "gpt-5.6", .context = 272000, .account = "acct-1", .source = .login };++ var keys: Keys = .{ .values = @splat(null) };+ reloadLoginKey(&root, &keys, arena, "codex");++ try std.testing.expectEqualStrings("fresh-tok", keys.get("codex").?);+ // The #402 fix: the LIVE provider, not only Keys. Without this, /login reported+ // success while every subsequent turn and auto-compaction kept 401ing.+ try std.testing.expectEqualStrings("fresh-tok", root.provider.api_key);+ try std.testing.expectEqualStrings("acct-2", root.provider.account);+ // The held WS was dialed with the stale bearer, and PR #195 forbids resending+ // against a chain the new credential never anchored.+ try std.testing.expect(root.codex_prev_id == null);+ try std.testing.expectEqual(@as(usize, 0), root.codex_sent_upto);++ // `/login kimi` mid-codex-session must not repoint the active provider — that+ // would silently switch the user's model AND wire format.+ root.provider.api_key = "expired-tok";+ root.codex_prev_id = try std.testing.allocator.dupe(u8, "resp_two");+ reloadLoginKey(&root, &keys, arena, "kimi"); // no kimi credential on disk here+ try std.testing.expectEqualStrings("expired-tok", root.provider.api_key);+ try std.testing.expectEqualStrings("codex", root.provider.id);+ try std.testing.expect(root.codex_prev_id != null);+ std.testing.allocator.free(root.codex_prev_id.?);+}+/// Read an API key without terminal echo or history persistence. The ordinary/// REPL line editor masks `/key provider secret`; this covers the model/// picker's separate "paste an API key" flow too.