graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
chatgpt-new: keep the sign-in in graff's own directory
justrachd89bd53d0222
diff --git a/docs/adr/0221-chatgpt-new-sign-in.md b/docs/adr/0221-chatgpt-new-sign-in.mdindex 7777f0b3..fbd77c65 100644--- a/docs/adr/0221-chatgpt-new-sign-in.md+++ b/docs/adr/0221-chatgpt-new-sign-in.md@@ -100,8 +100,12 @@ process rather than restarting anything.published JWKS, then issuer, audience (the issued client id), expiry andnonce. Plan usage needs the `chatgpt.tokens.use.direct` scope; a sign-inwithout it is saved but never used for requests.-- **One record per machine** in `<home>/.openai/credentials/graff-oauth.json`- (0600, atomic), with the host id beside it. Refresh sends `resource` and the+- **One record per machine** in graff's own directory,+ `<home>/.graff/credentials/chatgpt-new.json` (0600 in a 0700 directory,+ written atomically), with the host id beside it. A sign-in saved under the+ earlier `<home>/.openai/credentials/graff-oauth.json` moves there on first+ read: a rename, never a copy, because two copies of a rotating refresh token+ split and the stale one spends the sign-in. Refresh sends `resource` and theissued client id five minutes before expiry (inside the six-minute window)or after a 401, under the existing refresh mutex, and never before`earliest_refresh_at`: OpenAI answers an early refresh withdiff --git a/src/credential_store.zig b/src/credential_store.zigindex 8fc192e7..f1ef8d51 100644--- a/src/credential_store.zig+++ b/src/credential_store.zig@@ -155,6 +155,12 @@ pub fn oauthPath(arena: Allocator, home: []const u8, provider_dir: []const u8) [return std.fmt.allocPrint(arena, "{s}/{s}/credentials/graff-oauth.json", .{ resolveHome(home), provider_dir }) catch "";}+/// `<home>/.graff/credentials/<name>` — a login graff owns outright keeps its+/// record here, beside the rest of graff's per-user state.+pub fn graffCredentialPath(arena: Allocator, home: []const u8, name: []const u8) []const u8 {+ return std.fmt.allocPrint(arena, "{s}/.graff/credentials/{s}", .{ resolveHome(home), name }) catch "";+}+/// Store an access/refresh/expiry triple at `oauthPath`, 0600 inside 0700 dirs.pub fn writeOAuth(io: Io, arena: Allocator, home: []const u8, provider_dir: []const u8, access: []const u8, refresh: []const u8, expires_at: i64) !void {// createDir is one level, so make <home>/<provider_dir> then its credentials/.diff --git a/src/oauth_chatgpt.zig b/src/oauth_chatgpt.zigindex 8188fe4b..7d955b85 100644--- a/src/oauth_chatgpt.zig+++ b/src/oauth_chatgpt.zig@@ -4,9 +4,10 @@//! (`client_id=dynamic_agent_client` plus `agent_name_hint`); later sign-ins//! reuse the issued `oaiapp_…` id and skip consent. Browser PKCE with an OIDC//! nonce, a loopback callback on 127.0.0.1, and one stable-//! `ext_agent_host_id` per machine. The record lives in-//! <home>/.openai/credentials/graff-oauth.json (0600); requests go to the-//! public Responses endpoint with the access token as the bearer.+//! `ext_agent_host_id` per machine. The record lives in graff's own+//! directory, <home>/.graff/credentials/chatgpt-new.json (0600 in a 0700+//! directory); requests go to the public Responses endpoint with the access+//! token as the bearer.const std = @import("std");const builtin = @import("builtin");@@ -29,7 +30,8 @@ const scopes = "openid profile email offline_access resource.invoke chatgpt.tokepub const plan_scope = "chatgpt.tokens.use.direct";pub const dynamic_client = "dynamic_agent_client";pub const agent_name = "Graff";-pub const oauth_dir = ".openai";+/// Where sign-ins were saved before the record moved into graff's directory.+const legacy_dir = ".openai";pub const manage_usage_url = "https://chatgpt.com/settings/usage";/// Appended to a plan-usage failure so the person knows where to look.pub const usage_hint = "ChatGPT plan usage limit; manage usage at " ++ manage_usage_url;@@ -41,12 +43,43 @@ pub fn isLoginName(name: []const u8) bool {}pub fn recordPath(arena: Allocator, home: []const u8) []const u8 {- return credential_store.oauthPath(arena, home, oauth_dir);+ return credential_store.graffCredentialPath(arena, home, "chatgpt-new.json");}fn hostPath(arena: Allocator, home: []const u8) []const u8 {- const dir = std.fs.path.dirname(recordPath(arena, home)) orelse return "";- return std.fmt.allocPrint(arena, "{s}/graff-host-id", .{dir}) catch "";+ return credential_store.graffCredentialPath(arena, home, "chatgpt-new-host-id");+}++/// A saved sign-in, here or still at its old path. Presence only, so listing+/// providers never moves or refreshes anything.+pub fn onDisk(io: Io, arena: Allocator, home: []const u8) bool {+ for ([_][]const u8{ recordPath(arena, home), credential_store.oauthPath(arena, home, legacy_dir) }) |path| {+ if (Io.Dir.cwd().statFile(io, path, .{})) |_| return true else |_| {}+ }+ return false;+}++/// Move a sign-in saved under <home>/.openai/credentials into graff's+/// directory, so nobody signs in again. A rename, never a copy: two copies of+/// a rotating refresh token split, and the stale one spends the sign-in.+fn adoptLegacy(io: Io, arena: Allocator, home: []const u8) void {+ const cwd = Io.Dir.cwd();+ const old_record = credential_store.oauthPath(arena, home, legacy_dir);+ const old_dir = std.fs.path.dirname(old_record) orelse return;+ const old_host = std.fmt.allocPrint(arena, "{s}/graff-host-id", .{old_dir}) catch return;+ var moved = false;+ for ([_][2][]const u8{ .{ old_record, recordPath(arena, home) }, .{ old_host, hostPath(arena, home) } }) |move| {+ _ = cwd.statFile(io, move[0], .{}) catch continue;+ if (cwd.statFile(io, move[1], .{})) |_| continue else |_| {}+ ensureDirs(io, arena, home);+ cwd.rename(move[0], cwd, move[1], io) catch continue;+ moved = true;+ }+ if (!moved) return;+ cwd.deleteFile(io, std.fmt.allocPrint(arena, "{s}.lock", .{old_record}) catch return) catch {};+ // Only once empty: another tool may keep its own files there.+ cwd.deleteDir(io, old_dir) catch return;+ cwd.deleteDir(io, std.fs.path.dirname(old_dir) orelse return) catch {};}/// One registration's saved sign-in, in the JSON shape OpenAI's docs show.@@ -122,19 +155,25 @@ pub fn serializeRecord(arena: Allocator, r: Record, saved_at: []const u8) ![]con}fn readRecord(io: Io, arena: Allocator, home: []const u8) ?Record {- const data = Io.Dir.cwd().readFileAlloc(io, recordPath(arena, home), arena, .limited(64 * 1024)) catch return null;+ const path = recordPath(arena, home);+ const data = Io.Dir.cwd().readFileAlloc(io, path, arena, .limited(64 * 1024)) catch |err| retry: {+ if (err != error.FileNotFound) return null;+ adoptLegacy(io, arena, home);+ break :retry Io.Dir.cwd().readFileAlloc(io, path, arena, .limited(64 * 1024)) catch return null;+ };return parseRecord(arena, data);}+/// <home>/.graff keeps whatever mode it has (it holds sessions too); the+/// credentials directory under it is owner-only.fn ensureDirs(io: Io, arena: Allocator, home: []const u8) void {const credentials = std.fs.path.dirname(recordPath(arena, home)) orelse return;- const base = std.fs.path.dirname(credentials) orelse return;- for ([_][]const u8{ base, credentials }) |path| {- Io.Dir.cwd().createDir(io, path, credential_store.private_dir) catch {};- const dir = Io.Dir.cwd().openDir(io, path, .{ .iterate = true }) catch continue;- defer dir.close(io);- if (builtin.os.tag != .windows) dir.setPermissions(io, credential_store.private_dir) catch {};- }+ Io.Dir.cwd().createDir(io, std.fs.path.dirname(credentials) orelse return, credential_store.private_dir) catch {};+ Io.Dir.cwd().createDir(io, credentials, credential_store.private_dir) catch {};+ // iterate=true: a default openDir can be O_PATH on Linux, where fchmod panics.+ const dir = Io.Dir.cwd().openDir(io, credentials, .{ .iterate = true }) catch return;+ defer dir.close(io);+ if (builtin.os.tag != .windows) dir.setPermissions(io, credential_store.private_dir) catch {};}fn writeRecord(io: Io, arena: Allocator, home: []const u8, r: Record) !void {diff --git a/src/oauth_chatgpt_tests.zig b/src/oauth_chatgpt_tests.zigindex 24715c5a..4134de28 100644--- a/src/oauth_chatgpt_tests.zig+++ b/src/oauth_chatgpt_tests.zig@@ -125,11 +125,11 @@ test "ChatGPT sign-in: loading needs plan usage and never refreshes a fresh tokevar real_buf: [std.fs.max_path_bytes]u8 = undefined;const home = real_buf[0..try tmp.dir.realPath(io, &real_buf)];try std.testing.expect(chatgpt.loadChatgptOAuth(io, std.testing.allocator, a, home, false, null) == null);- try tmp.dir.createDir(io, ".openai", credential_store.private_dir);- try tmp.dir.createDir(io, ".openai/credentials", credential_store.private_dir);+ try tmp.dir.createDir(io, ".graff", credential_store.private_dir);+ try tmp.dir.createDir(io, ".graff/credentials", credential_store.private_dir);const write = struct {fn record(d: std.Io.Dir, alloc: std.mem.Allocator, r: chatgpt.Record) !void {- try credential_store.replaceFile(std.testing.io, d, ".openai/credentials/graff-oauth.json", try chatgpt.serializeRecord(alloc, r, "now"), credential_store.private_file);+ try credential_store.replaceFile(std.testing.io, d, ".graff/credentials/chatgpt-new.json", try chatgpt.serializeRecord(alloc, r, "now"), credential_store.private_file);}};var r = chatgpt.parseRecord(a, probe_record).?;@@ -155,13 +155,13 @@ test "ChatGPT sign-in: loading needs plan usage and never refreshes a fresh tokefn tmpHome(tmp: *std.testing.TmpDir, buf: *[std.fs.max_path_bytes]u8) ![]const u8 {const io = std.testing.io;- try tmp.dir.createDir(io, ".openai", credential_store.private_dir);- try tmp.dir.createDir(io, ".openai/credentials", credential_store.private_dir);+ try tmp.dir.createDir(io, ".graff", credential_store.private_dir);+ try tmp.dir.createDir(io, ".graff/credentials", credential_store.private_dir);return buf[0..try tmp.dir.realPath(io, buf)];}fn saveIn(dir: std.Io.Dir, alloc: std.mem.Allocator, r: chatgpt.Record) !void {- try credential_store.replaceFile(std.testing.io, dir, ".openai/credentials/graff-oauth.json", try chatgpt.serializeRecord(alloc, r, "now"), credential_store.private_file);+ try credential_store.replaceFile(std.testing.io, dir, ".graff/credentials/chatgpt-new.json", try chatgpt.serializeRecord(alloc, r, "now"), credential_store.private_file);}test "ChatGPT sign-in: a refresh takes a lock a second graff would block on" {@@ -209,6 +209,34 @@ test "ChatGPT sign-in: a refresh another graff already made is adopted, not repetry std.testing.expect(chatgpt.refreshLocked(io, std.testing.allocator, a, home, before) == null);}+test "ChatGPT sign-in: a sign-in saved before the move is adopted, never copied" {+ const io = std.testing.io;+ var arena = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena.deinit();+ const a = arena.allocator();+ var tmp = std.testing.tmpDir(.{});+ defer tmp.cleanup();+ var buf: [std.fs.max_path_bytes]u8 = undefined;+ const home = buf[0..try tmp.dir.realPath(io, &buf)];+ try tmp.dir.createDir(io, ".openai", credential_store.private_dir);+ try tmp.dir.createDir(io, ".openai/credentials", credential_store.private_dir);+ try credential_store.replaceFile(io, tmp.dir, ".openai/credentials/graff-oauth.json", try chatgpt.serializeRecord(a, chatgpt.parseRecord(a, probe_record).?, "now"), credential_store.private_file);+ try tmp.dir.writeFile(io, .{ .sub_path = ".openai/credentials/graff-host-id", .data = host ++ "\n" });+ try tmp.dir.writeFile(io, .{ .sub_path = ".openai/credentials/graff-oauth.json.lock", .data = "" });+ try std.testing.expect(chatgpt.onDisk(io, a, home)); // listing providers still sees it+ // The first read moves it into graff's directory: no sign-in, no network.+ try std.testing.expectEqualStrings("tok-1", chatgpt.loadChatgptOAuth(io, std.testing.allocator, a, home, false, null).?);+ try std.testing.expectEqualStrings(host ++ "\n", try tmp.dir.readFileAlloc(io, ".graff/credentials/chatgpt-new-host-id", a, .limited(128)));+ try std.testing.expectError(error.FileNotFound, tmp.dir.statFile(io, ".openai", .{})); // emptied, so removed+ try std.testing.expect(chatgpt.onDisk(io, a, home));+ try std.testing.expectEqualStrings("tok-1", chatgpt.loadChatgptOAuth(io, std.testing.allocator, a, home, false, null).?);+ if (@import("builtin").os.tag == .windows) return;+ const dir = try tmp.dir.openDir(io, ".graff/credentials", .{});+ defer dir.close(io);+ try std.testing.expectEqual(@as(u32, 0o700), (try dir.stat(io)).permissions.toMode() & 0o777);+ try std.testing.expectEqual(@as(u32, 0o600), (try dir.statFile(io, "chatgpt-new.json", .{})).permissions.toMode() & 0o777);+}+test "ChatGPT sign-in: an unusable refresh token is cleared and the access token kept" {const io = std.testing.io;var arena = std.heap.ArenaAllocator.init(std.testing.allocator);diff --git a/src/route_report.zig b/src/route_report.zigindex 5e290c93..0c217bb1 100644--- a/src/route_report.zig+++ b/src/route_report.zig@@ -52,7 +52,7 @@ pub fn loginOnDisk(io: Io, arena: Allocator, home: []const u8, spec: provider_mo.kimi_device => credential_store.oauthPath(arena, home, ".kimi"),.xai_device => credential_store.oauthPath(arena, home, ".xai"),.zai_cli => credential_store.oauthPath(arena, home, ".zai"),- .chatgpt_browser => credential_store.oauthPath(arena, home, ".openai"),+ .chatgpt_browser => return @import("oauth_chatgpt.zig").onDisk(io, arena, home),.codex_device => blk: {const dir = oauth_helpers.codexHomeDir(arena, home) orelse return false;break :blk std.fmt.allocPrint(arena, "{s}/auth.json", .{dir}) catch return false;