graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
fix(oauth): auto-refresh login tokens in-session (kimi/xai) — closes #148
justrach5833cace31af
diff --git a/src/agent_request.zig b/src/agent_request.zigindex 91682e89..eeb747fa 100644--- a/src/agent_request.zig+++ b/src/agent_request.zig@@ -18,6 +18,7 @@ const Agent = agent_mod.Agent;const max_tokens = main_mod.max_tokens;const pricing = @import("pricing.zig");+const oauth = @import("oauth.zig");const g_cost = &pricing.g_cost;const messages_mod = @import("messages.zig");@@ -46,9 +47,44 @@ const telemetry = @import("telemetry.zig");/// and lean on the strict system prompt instead. Root requests stream:/// text deltas print live (postStream) and the buffered SSE events are/// reassembled into the non-streaming response shape afterwards.+/// #148: does a provider error message look like an auth failure (a stale/+/// revoked OAuth token), so we refresh + retry rather than give up? Matches the+/// common 401 phrasings ("invalid api key", "expired", "unauthorized", …).+fn isAuthError(msg: []const u8) bool {+ return std.ascii.indexOfIgnoreCase(msg, "api key") != null or+ std.ascii.indexOfIgnoreCase(msg, "unauthorized") != null or+ std.ascii.indexOfIgnoreCase(msg, "expired") != null or+ std.ascii.indexOfIgnoreCase(msg, "authentication") != null or+ std.ascii.indexOfIgnoreCase(msg, "invalid_api_key") != null;+}++test "isAuthError (#148): auth failures only, not credits/rate/other" {+ // real provider 401 phrasings → refresh + retry+ try std.testing.expect(isAuthError("The API Key appears to be invalid or may have expired."));+ try std.testing.expect(isAuthError("Unauthorized"));+ try std.testing.expect(isAuthError("authentication_error"));+ try std.testing.expect(isAuthError("invalid_api_key"));+ // NOT auth — must never trigger a refresh loop+ try std.testing.expect(!isAuthError("You have run out of credits or need a Grok subscription."));+ try std.testing.expect(!isAuthError("rate limit exceeded"));+ try std.testing.expect(!isAuthError("model not found"));+ try std.testing.expect(!isAuthError("context length exceeded"));+}+pub fn request(self: *Agent, tools: ?[]const u8) !std.json.ObjectMap {var force = self.strict and tools != null;var stream_usage = true; // openai stream_options; dropped if rejected+ var auth_refreshed = false; // #148: at most one forced token refresh + retry+ // #148: a login-sourced OAuth token (kimi/xai, ~1h) expires mid-session and+ // is minted only at startup; refresh it in place before the call when near+ // expiry so a long session — or a subagent that inherited the on-disk token —+ // never 401s. Login-sourced keys only (env keys untouched); a cheap disk read+ // unless actually near expiry.+ if (self.provider.source == .login) {+ if (oauth.refreshOAuthKey(self.io, self.gpa, self.arena, self.home, self.provider.id, false)) |fresh| {+ self.provider.api_key = fresh;+ }+ }// #95: scrub any malformed function_call_output before it hits the wire.sanitizeMessagesUtf8(self.arena, &self.messages); // invalid UTF-8 (any source/format) -> '?' so content never serializes as a byte-int array the API rejectsif (self.provider.kind == .responses) normalizeResponsesHistory(self.arena, &self.messages);@@ -229,6 +265,17 @@ pub fn request(self: *Agent, tools: ?[]const u8) !std.json.ObjectMap {self.effort_rejected = true; // model rejects the effort hint here; drop + retrycontinue;}+ // #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.arena, self.home, self.provider.id, true)) |fresh| {+ auth_refreshed = true;+ self.provider.api_key = fresh;+ if (self.tracer) |tr| tr.note("oauth_refresh", "auth error — refreshed login token, retrying");+ continue;+ }+ }if (self.tracer) |tr| tr.api(self.label, self.provider.model, ms, body.len, resp_body.len, 0, 0, true);try self.sayApiError("api error: {s}", .{msg});return error.ApiError;diff --git a/src/oauth.zig b/src/oauth.zigindex 35979b54..12c3c6d5 100644--- a/src/oauth.zig+++ b/src/oauth.zig@@ -52,6 +52,15 @@ pub fn loadCodexAuth(io: Io, arena: Allocator, home: []const u8) ?CodexAuth {return loadCodexAuthFrom(io, arena, codex_home);}+// #148: how long before an OAuth access token's expiry to proactively refresh+// it — wider than the old 60s so a mid-session refresh has headroom before a+// turn's request would otherwise cross the expiry and 401. kimi-code uses the+// same "ensureFresh near expiry + force-refresh on 401" shape.+const oauth_refresh_margin_s: i64 = 300;+// Serializes concurrent token refreshes (parallel subagents share the on-disk+// token) so they don't race the single-use refresh_token.+var oauth_refresh_mutex: Io.Mutex = .init;+// Codex / ChatGPT OAuth (PKCE) — same client + endpoints the Codex CLI uses// (verified from the live id_token: aud/client_id app_EMoamEEZ…, iss// auth.openai.com). `harness login` runs the browser flow; `harness login@@ -357,13 +366,13 @@ pub fn kimiLogin(io: Io, gpa: Allocator, arena: Allocator, home: []const u8) !vo/// Reads the stored Kimi OAuth access token, refreshing it in place when within/// 60s of expiry. Returns null if not logged in. Mirrors loadCodexAuth.-pub fn loadKimiOAuth(io: Io, gpa: Allocator, arena: Allocator, home: []const u8) ?[]const u8 {+pub fn loadKimiOAuth(io: Io, gpa: Allocator, arena: Allocator, home: []const u8, force: bool) ?[]const u8 {const data = Io.Dir.cwd().readFileAlloc(io, kimiAuthPath(arena, home), arena, .limited(64 * 1024)) catch return null;const v = std.json.parseFromSliceLeaky(Value, arena, data, .{ .allocate = .alloc_always }) catch return null;if (v != .object) return null;const access = strFieldObj(v.object, "access_token") orelse return null;const expires_at: i64 = if (v.object.get("expires_at")) |e| (if (e == .integer) e.integer else 0) else 0;- if (expires_at != 0 and @divTrunc(unixMs(io), 1000) >= expires_at - 60) {+ if (force or (expires_at != 0 and @divTrunc(unixMs(io), 1000) >= expires_at - oauth_refresh_margin_s)) {if (strFieldObj(v.object, "refresh_token")) |refresh| {const body = std.fmt.allocPrint(arena, "client_id={s}&grant_type=refresh_token&refresh_token={s}", .{ kimi_client_id, refresh }) catch return access;const resp = kimiOAuthPost(io, gpa, arena, kimi_token_url, body) catch return access;@@ -378,6 +387,21 @@ 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) ?[]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;+ oauth_refresh_mutex.lockUncancelable(io);+ defer oauth_refresh_mutex.unlock(io);+ return if (is_kimi) loadKimiOAuth(io, gpa, arena, home, force) else loadXaiOAuth(io, gpa, arena, home, force);+}+// The Kimi for Coding plan's model-listing endpoint (sibling of the// chat/completions URL in provider_specs). The official Kimi Code client reads// the served model id from here rather than baking in a version, so login does@@ -539,13 +563,13 @@ pub fn xaiLogin(io: Io, gpa: Allocator, arena: Allocator, home: []const u8) !voi/// Reads the stored xAI OAuth access token, refreshing in place near expiry./// Returns null if not logged in. Mirrors loadKimiOAuth.-pub fn loadXaiOAuth(io: Io, gpa: Allocator, arena: Allocator, home: []const u8) ?[]const u8 {+pub fn loadXaiOAuth(io: Io, gpa: Allocator, arena: Allocator, home: []const u8, force: bool) ?[]const u8 {const data = Io.Dir.cwd().readFileAlloc(io, xaiAuthPath(arena, home), arena, .limited(64 * 1024)) catch return null;const v = std.json.parseFromSliceLeaky(Value, arena, data, .{ .allocate = .alloc_always }) catch return null;if (v != .object) return null;const access = strFieldObj(v.object, "access_token") orelse return null;const expires_at: i64 = if (v.object.get("expires_at")) |e| (if (e == .integer) e.integer else 0) else 0;- if (expires_at != 0 and @divTrunc(unixMs(io), 1000) >= expires_at - 60) {+ if (force or (expires_at != 0 and @divTrunc(unixMs(io), 1000) >= expires_at - oauth_refresh_margin_s)) {if (strFieldObj(v.object, "refresh_token")) |refresh| {const body = std.fmt.allocPrint(arena, "client_id={s}&grant_type=refresh_token&refresh_token={s}", .{ xai_client_id, refresh }) catch return access;const resp = xaiOAuthPost(io, gpa, arena, xai_token_url, body) catch return access;diff --git a/src/pickers.zig b/src/pickers.zigindex a57b46cb..8ec89f88 100644--- a/src/pickers.zig+++ b/src/pickers.zig@@ -480,12 +480,12 @@ pub fn reloadLoginKey(root: *Agent, keys: *Keys, arena: Allocator, provider_id:source.* = .login;}} else if (std.mem.eql(u8, provider_id, "kimi")) {- if (oauth.loadKimiOAuth(root.io, root.gpa, arena, home)) |k| {+ if (oauth.loadKimiOAuth(root.io, root.gpa, arena, home, false)) |k| {value.* = k;source.* = .login;}} else if (std.mem.eql(u8, provider_id, "xai")) {- if (oauth.loadXaiOAuth(root.io, root.gpa, arena, home)) |k| {+ if (oauth.loadXaiOAuth(root.io, root.gpa, arena, home, false)) |k| {value.* = k;source.* = .login;}diff --git a/src/provider.zig b/src/provider.zigindex 35b8917e..6f84e263 100644--- a/src/provider.zig+++ b/src/provider.zig@@ -68,6 +68,7 @@ pub const Provider = struct {model: []const u8,context: u64,account: []const u8 = "", // ChatGPT account id, codex/responses only+ source: Keys.CredentialSource = .none, // #148: how api_key was obtained — only .login tokens auto-refresh// Wire format. `responses` is the OpenAI Responses API as served by the// ChatGPT backend (Codex login) — input items, not chat messages.@@ -128,6 +129,7 @@ pub const Keys = struct {.model = model,.context = contextFor(spec.id, model),.account = if (std.mem.eql(u8, spec.id, "codex")) keys.codex_account else "",+ .source = keys.source(spec.id),};}diff --git a/src/startup.zig b/src/startup.zigindex d586a7c3..8c01186d 100644--- a/src/startup.zig+++ b/src/startup.zig@@ -95,13 +95,13 @@ pub fn resolveKeys(io: Io, gpa: Allocator, arena: Allocator, environ_map: anytypif (keys_cli.homeEnv(environ_map)) |home| {for (provider_mod.provider_specs, &keys.values, &keys.sources) |spec, *value, *source| {if (std.mem.eql(u8, spec.id, "kimi") and value.* == null) {- if (oauth.loadKimiOAuth(io, gpa, arena, home)) |key| {+ if (oauth.loadKimiOAuth(io, gpa, arena, home, false)) |key| {value.* = key;source.* = .login;}}if (std.mem.eql(u8, spec.id, "xai") and value.* == null) {- if (oauth.loadXaiOAuth(io, gpa, arena, home)) |key| {+ if (oauth.loadXaiOAuth(io, gpa, arena, home, false)) |key| {value.* = key;source.* = .login;}