graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
merge: fix/402-codex-auth-hot-reload into release/0.0.239
Rach Pradhan319861e52c36
diff --cc src/oauth_helpers.zigindex a6f2b492,1ddaf91c..bb3fd082--- a/src/oauth_helpers.zig+++ b/src/oauth_helpers.zig@@@ -7,7 -9,15 +9,16 @@@ const Io = std.Ioconst Value = std.json.Value;const Allocator = std.mem.Allocator;+const credential_store = @import("credential_store.zig");+ const strFieldObj = @import("util.zig").strFieldObj;+ const unixMs = @import("util.zig").unixMs;++ // 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;@@@ -32,9 -42,88 +43,86 @@@ pub fn accountFromIdToken(arena: Allocareturn if (account == .string) account.string else "";}+ /// THE codex credential directory for this process: `$CODEX_HOME`, or+ /// `<HOME>/.codex` when it is unset. Pinned once at startup — before any+ /// subcommand or session can log in — and read by every reader and writer of+ /// auth.json below.+ ///+ /// #402: there used to be two answers. The mid-turn refresh resolved+ /// $CODEX_HOME off the ROOT's model catalog while every login flow hardcoded+ /// ~/.codex, so with CODEX_HOME set a successful `/login` was silently REVERTED+ /// by the next request's proactive re-read (the reported symptom), and a+ /// subagent — which carries neither a catalog nor a `home` — resolved neither+ /// and got no recovery at all. One resolver, one file, catalog or not.+ pub var g_codex_home: []const u8 = "";++ /// Pin it. `$CODEX_HOME` and `$HOME` are taken by value rather than as an+ /// environ map so a test can drive the precedence with plain strings.+ pub fn initCodexHome(arena: Allocator, env_codex_home: ?[]const u8, home: ?[]const u8) void {+ if (env_codex_home) |value| if (value.len > 0) {+ g_codex_home = value;+ return;+ };+ const h = home orelse return;+ if (h.len == 0) return;+ g_codex_home = std.fmt.allocPrint(arena, "{s}/.codex", .{h}) catch "";+ }++ /// Where auth.json lives. `home` is only the fallback for callers that can run+ /// before startup pinned the global (and for tests); null when neither is+ /// known, which every caller reads as "not logged in".+ pub fn codexHomeDir(arena: Allocator, home: []const u8) ?[]const u8 {+ if (g_codex_home.len > 0) return g_codex_home;+ if (home.len == 0) return null;+ return std.fmt.allocPrint(arena, "{s}/.codex", .{home}) catch null;+ }++ pub fn codexAuthPath(arena: Allocator, codex_home: []const u8) ![]const u8 {+ return std.fmt.allocPrint(arena, "{s}/auth.json", .{codex_home});+ }++ /// Write the credential to THE codex auth.json (codexHomeDir). `home` is its+ /// pre-startup fallback only — never a second location.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 = codexHomeDir(arena, home) orelse return error.NoCodexHome;+ return writeCodexAuthAt(io, arena, dir, id_token, access, refresh, account);+ }+-const private_file_permissions: Io.File.Permissions = if (Io.File.Permissions.has_executable_bit) @enumFromInt(0o600) else .default_file;-+ /// `last_refresh` in the shape the real codex CLI stores it (serde+ /// `Option<DateTime<Utc>>`). The literal "harness-login" this used to write is+ /// not a timestamp — tolerable in a file only `graff login` touched, not in one+ /// a silent mid-turn refresh now rewrites under the other CLI's feet.+ fn rfc3339Utc(buf: *[24]u8, unix_ms: i64) []const u8 {+ const es: std.time.epoch.EpochSeconds = .{ .secs = @intCast(@max(0, @divFloor(unix_ms, 1000))) };+ const yd = es.getEpochDay().calculateYearDay();+ const md = yd.calculateMonthDay();+ const ds = es.getDaySeconds();+ return std.fmt.bufPrint(buf, "{d:0>4}-{d:0>2}-{d:0>2}T{d:0>2}:{d:0>2}:{d:0>2}Z", .{+ yd.year, md.month.numeric(), @as(u16, md.day_index) + 1,+ ds.getHoursIntoDay(), ds.getMinutesIntoHour(), ds.getSecondsIntoMinute(),+ }) catch "1970-01-01T00:00:00Z";+ }++ /// Write the ChatGPT credential into `<codex_home>/auth.json`, PRESERVING every+ /// field this harness does not own.+ ///+ /// #402: auth.json is co-owned with the real `codex` CLI, whose AuthDotJson also+ /// carries openai_api_key / agent_identity / personal_access_token /+ /// bedrock_api_key. The previous write emitted a fixed four-field object and+ /// destroyed the rest — survivable while only an explicit `graff login` ran it,+ /// not now that a silent mid-turn refresh fires it unattended. So:+ /// read-modify-write replacing ONLY the token fields, and 0600 like every other+ /// credential this repo writes (oauth.writeKimiAuth).+ 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 object: std.json.ObjectMap = .empty;var tokens: std.json.ObjectMap = .empty;+ if (readCodexJson(io, arena, path)) |existing| {+ object = existing;+ if (existing.get("tokens")) |t| if (t == .object) {+ tokens = t.object;+ };+ }try tokens.put(arena, "id_token", .{ .string = id_token });try tokens.put(arena, "access_token", .{ .string = access });try tokens.put(arena, "refresh_token", .{ .string = refresh });@@@ -46,12 -135,191 +134,176 @@@var aw: Io.Writer.Allocating = .init(arena);var stringify: std.json.Stringify = .{ .writer = &aw.writer };try stringify.write(Value{ .object = object });- // 0600: this holds the id/access/refresh triple. ~/.codex/auth.json is- // co-owned with the openai/codex CLI, which writes it 0600 itself, so the- // tighter mode is what the other writer already expects.+ Io.Dir.cwd().createDirPath(io, codex_home) catch {}; // a freshly-pointed $CODEX_HOME- // Stage + rename rather than truncate in place. A co-owned file that a silent- // mid-turn refresh rewrites must never be observable half-written — by the- // real codex CLI, or by our own next read-modify-write, which would then- // PERSIST the loss. The staging name is per-writer (random, not a fixed- // suffix) so two concurrent refreshers cannot interleave into one temp file.- var rnd: [8]u8 = undefined;- io.random(&rnd);- const staged = try std.fmt.allocPrint(arena, "{s}.graff-{d}.tmp", .{ path, std.mem.readInt(u64, &rnd, .little) });- {- const file = try Io.Dir.cwd().createFile(io, staged, .{ .permissions = private_file_permissions });- defer file.close(io);- file.setPermissions(io, private_file_permissions) catch {};- var write_buffer: [4096]u8 = undefined;- var writer = file.writer(io, &write_buffer);- try writer.interface.writeAll(aw.writer.buffered());- try writer.interface.flush();- }- Io.Dir.cwd().rename(staged, Io.Dir.cwd(), path, io) catch |err| {- Io.Dir.cwd().deleteFile(io, staged) catch {}; // never leave litter next to a credential- return err;- };++ // 0600, staged + renamed by the shared credential writer: this holds the++ // id/access/refresh triple, is co-owned with the openai/codex CLI (which++ // writes it 0600 itself), and a silent mid-turn refresh must never leave it++ // observable half-written — a torn read here would be re-PERSISTED by our++ // own next read-modify-write.+ try credential_store.replaceFile(io, Io.Dir.cwd(), path, aw.writer.buffered(), credential_store.private_file);}+ /// 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 = "",+ };++ /// The parsed top-level object of an auth.json, or null when it is missing or+ /// unparseable. Shared by the reader and by the read-modify-write above, so the+ /// fields graff does not own survive a refresh.+ fn readCodexJson(io: Io, arena: Allocator, path: []const u8) ?std.json.ObjectMap {+ 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;+ return if (v == .object) v.object else null;+ }++ /// 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 object = readCodexJson(io, arena, path) orelse return null;+ const tokens = 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;++ /// A credential the request loop may adopt: the bearer AND the ChatGPT account+ /// id it belongs to. They travel together because `account` is the+ /// chatgpt-account-id header on every codex request (http_headers.zig,+ /// agent_ws.zig) — a new bearer paired with the previous account's id just+ /// 401/403s again. Empty `account` means "unchanged / not applicable" (kimi, xai).+ pub const FreshKey = struct { key: []const u8, account: []const u8 = "" };++ /// Set when a refreshed credential could NOT be written back, so the caller can+ /// warn. OpenAI rotates the refresh_token on the grant, which kills the old one+ /// server-side the moment the POST succeeds: swallowing this write failure would+ /// leave only a dead credential on disk and log the user out at next start with+ /// no diagnostic (codex-rs propagates it as RefreshTokenError). `@errorName` is+ /// static, so the slice outlives every arena. Written under refreshOAuthKey's+ /// mutex; a concurrent reader can at worst attribute one warning to the wrong+ /// agent, never miss that something failed.+ pub var persist_error: ?[]const u8 = null;++ pub fn takePersistError() ?[]const u8 {+ defer persist_error = null;+ return persist_error;+ }++ /// Persist a refreshed credential, retrying once. The failures that reach here+ /// (a concurrent writer's truncate, a transient EIO) are usually not sticky;+ /// a still-failing write is recorded for the caller to surface.+ fn persistRefreshed(io: Io, arena: Allocator, codex_home: []const u8, id_token: []const u8, access: []const u8, refresh: []const u8, account: []const u8) void {+ writeCodexAuthAt(io, arena, codex_home, id_token, access, refresh, account) catch {+ writeCodexAuthAt(io, arena, codex_home, id_token, access, refresh, account) catch |err| {+ persist_error = @errorName(err);+ };+ };+ }++ /// #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.+ ///+ /// `expect_account` is codex-rs's `reload_if_account_id_matches`: a credential+ /// minted for a DIFFERENT ChatGPT account is never adopted (null = give up,+ /// which the caller surfaces as the original auth error) rather than silently+ /// paired with this session's account header.+ pub fn loadCodexOAuth(io: Io, gpa: Allocator, arena: Allocator, codex_home: []const u8, force: bool, stale: ?[]const u8, expect_account: []const u8) ?FreshKey {+ const auth = readCodexAuth(io, arena, codex_home) orelse return null;+ if (expect_account.len > 0 and auth.account.len > 0 and !std.mem.eql(u8, expect_account, auth.account)) return null;+ const on_disk: FreshKey = .{ .key = auth.access, .account = auth.account };+ if (supersededToken(force, auth.access, stale)) return on_disk;+ if (!force or auth.refresh.len == 0) return on_disk;+ const refresh_id = std.hash.Wyhash.hash(0, auth.refresh);+ if (refresh_id == dead_refresh_token) return on_disk; // 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 on_disk;+ const resp = oauthFormPost(io, gpa, arena, codex_token_url, body) catch return on_disk; // transient: retryable, do not cache+ if (resp.get("error")) |e| {+ if (permanentRefreshFailure(if (e == .string) e.string else "")) dead_refresh_token = refresh_id;+ return on_disk;+ }+ const access = strFieldObj(resp, "access_token") orelse return on_disk;+ if (access.len == 0) return on_disk;+ 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+ persistRefreshed(io, arena, codex_home, id_token, access, refresh, account);+ return .{ .key = access, .account = account };+ }+/// 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.