graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
chatgpt: an interactive session signs in again when the token lapses (ADR 0253)
justrachbde0e5757d29
diff --git a/docs/adr/0253-an-interactive-session-signs-in-to-chatgpt-again.md b/docs/adr/0253-an-interactive-session-signs-in-to-chatgpt-again.mdnew file mode 100644index 00000000..40b9a3e1--- /dev/null+++ b/docs/adr/0253-an-interactive-session-signs-in-to-chatgpt-again.md@@ -0,0 +1,38 @@+# 0253. An interactive session signs in to ChatGPT again by itself++Status: accepted 2026-10-04. Builds on 0221 and 0229.++## Context++The ChatGPT sign-in (0221, 0229) issues an access token that lasts an hour and+a refresh token to renew it. The token endpoint currently answers every+renewal with `invalid_grant`, including requests that match the documented+refresh request field for field and the reference implementations that send+it. So a sign-in lasts about an hour. When it lapses, the next request fails+with "sign in again with `graff login chatgpt`", the turn ends, and the person+has to run the sign-in and repeat the request.++A sign-in after the first is short: graff reuses the issued app registration+and fills in the account, so with a live browser session it is one click.++## Decision++- When a ChatGPT request's credential is rejected and the refresh cannot+ replace it, a session with a person at the terminal opens the same browser+ sign-in as `/login chatgpt`, waits up to three minutes, adopts the new token+ and retries the request once.+- Only an interactive root session does this. `-p`, piped and `--json` runs,+ ACP sessions (the client owns sign-in) and sub-agents never open a browser;+ they fail as before.+- A sign-in that does not finish ends it for the process. Later requests fail+ with the usual error instead of reopening the browser.+- The refresh path is unchanged: graff still renews inside the window OpenAI+ allows, so renewals start working again with no change here once the token+ endpoint accepts them.++## Consequences++An expired sign-in costs one click in the browser instead of a failed turn.+A person who walks away from a long task still finds it stopped at the first+request after expiry, now with the sign-in waiting in the browser for three+minutes before the request fails.diff --git a/docs/adr/README.md b/docs/adr/README.mdindex a0a0ea29..07937ac0 100644--- a/docs/adr/README.md+++ b/docs/adr/README.md@@ -278,6 +278,7 @@ record only when you need the evidence or the edge cases.| [0249](0249-a-spec-task-ends-at-its-own-tests.md) | The work note no longer says a green public test is not the whole spec: it made the model write an extra verification script on every spec task without changing the pass rate. Spec tasks end at their own tests; the lean note is unchanged. Refines 0024. || [0250](0250-pr-publication-is-not-gated.md) | PR publication is not gated: no local-check, head-CI or claim-review preflight and no completion obligation; drafts complete like any task. Artifact claims and disclosure policy are unchanged. Supersedes 0120, 0123, 0126, 0133 and parts of 0100/0104. || [0251](0251-tool-results-inline-up-to-64-kib.md) | Tool results inline up to 64 KiB (was 16 KiB); `effectiveThreshold` still clamps to half the context window, so small windows are unchanged. The codedb small-read exemption follows the same number. |+| [0253](0253-an-interactive-session-signs-in-to-chatgpt-again.md) | When a ChatGPT request is rejected and the refresh cannot replace the token, an interactive root session opens the browser sign-in, waits up to three minutes and retries once; `-p`, piped, `--json`, ACP and sub-agents never do. One unfinished sign-in ends it for the process. |## When to write onediff --git a/src/agent_request_policy.zig b/src/agent_request_policy.zigindex 900e491e..88424c3c 100644--- a/src/agent_request_policy.zig+++ b/src/agent_request_policy.zig@@ -208,9 +208,10 @@ pub fn retryWithout(self: *Agent, msg: []const u8, force: *bool, stream_usage: *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, self.provider.account) orelse return false;+ // ADR 0253: when the refresh cannot help, an interactive ChatGPT session signs in again.+ const fresh = oauth.refreshOAuthKey(self.io, self.gpa, self.scratchAlloc(), self.home, self.provider.id, true, self.provider.api_key, self.provider.account) orelse return @import("chatgpt_reauth.zig").renewed(self);warnUnpersistedRefresh(self);- if (std.mem.eql(u8, fresh.key, self.provider.api_key)) return false;+ if (std.mem.eql(u8, fresh.key, self.provider.api_key)) return @import("chatgpt_reauth.zig").renewed(self);adoptFreshAuth(self, fresh);if (self.tracer) |tr| tr.note("oauth_refresh", "auth error — refreshed login token, retrying");return true;diff --git a/src/chatgpt_reauth.zig b/src/chatgpt_reauth.zignew file mode 100644index 00000000..59642724--- /dev/null+++ b/src/chatgpt_reauth.zig@@ -0,0 +1,93 @@+//! ADR 0253: an interactive session signs in to ChatGPT again by itself.+//!+//! OpenAI currently refuses every renewal of a Sign in with ChatGPT session+//! (`invalid_grant`), for graff and for every other client that sends the+//! documented refresh request, so a sign-in lasts about an hour. When a+//! request's credential is rejected and the refresh could not help, a session+//! with a person at the terminal opens the same browser sign-in as+//! `/login chatgpt`, waits a bounded time, and retries the request with the+//! new token. One unfinished attempt ends it for the process: later requests+//! fail with the usual "sign in again" error instead of reopening the browser.+//! `-p`, piped and `--json` runs, ACP sessions (the client owns sign-in) and+//! sub-agents never open a browser.++const std = @import("std");+const Io = std.Io;+const Agent = @import("agent.zig").Agent;+const oauth = @import("oauth.zig");++/// How long a request waits for the browser sign-in.+pub const wait_s: i64 = 180;++/// Set once a sign-in started here did not finish.+var gave_up = false;++/// Whether a rejected request may open the browser sign-in.+pub fn eligible(provider_id: []const u8, no_human: bool, json: bool, unattended: bool, sub: bool, has_out: bool, home: []const u8) bool {+ return std.mem.eql(u8, provider_id, "chatgpt-new") and !no_human and !json and !unattended and !sub and has_out and home.len > 0;+}++/// After the refresh failed: sign in again and adopt the new token. True when+/// the request should be retried.+pub fn renewed(self: *Agent) bool {+ const main_mod = @import("main.zig");+ if (gave_up or !eligible(self.provider.id, @import("ask_user.zig").g_no_human, main_mod.json_mode, main_mod.unattended, self.sub, self.out != null, self.home)) return false;+ self.say("\n[ChatGPT sign-in expired — opening your browser to sign in again; this request waits up to {d} min]\n", .{@divTrunc(wait_s, 60)}) catch {};+ if (!signInWithin(self.io, self.gpa, self.home)) return giveUp(self);+ // The sign-in wrote a new token to disk: a forced load with the rejected+ // token as `stale` adopts it without another refresh.+ const fresh = oauth.refreshOAuthKey(self.io, self.gpa, self.scratchAlloc(), self.home, "chatgpt-new", true, self.provider.api_key, self.provider.account) orelse return giveUp(self);+ if (std.mem.eql(u8, fresh.key, self.provider.api_key)) return giveUp(self);+ @import("agent_request_policy.zig").adoptFreshAuth(self, fresh);+ if (self.tracer) |tr| tr.note("oauth_refresh", "ChatGPT sign-in renewed in place, retrying");+ return true;+}++fn giveUp(self: *Agent) bool {+ gave_up = true;+ self.say("[ChatGPT sign-in did not finish — run `/login chatgpt` when you are ready]\n", .{}) catch {};+ return false;+}++const Done = union(enum) { signed_in: bool, timeout };++fn loginTask(io: Io, gpa: std.mem.Allocator, home: []const u8) bool {+ var arena_state = std.heap.ArenaAllocator.init(gpa);+ defer arena_state.deinit();+ @import("oauth_chatgpt.zig").login(io, gpa, arena_state.allocator(), home) catch return false;+ return true;+}++fn deadline(io: Io) void {+ io.sleep(.fromSeconds(wait_s), .awake) catch {};+}++/// Run the browser sign-in, giving up after `wait_s`. Cancelling the login+/// task closes its loopback listener, so a late redirect finds nothing.+fn signInWithin(io: Io, gpa: std.mem.Allocator, home: []const u8) bool {+ var buf: [2]Done = undefined;+ var sel: Io.Select(Done) = .init(io, &buf);+ sel.concurrent(.signed_in, loginTask, .{ io, gpa, home }) catch return loginTask(io, gpa, home);+ sel.concurrent(.timeout, deadline, .{io}) catch {+ const only = sel.await() catch return false;+ sel.cancelDiscard();+ return only == .signed_in and only.signed_in;+ };+ const first = sel.await() catch {+ sel.cancelDiscard();+ return false;+ };+ sel.cancelDiscard();+ return first == .signed_in and first.signed_in;+}++test "eligible: only an interactive root ChatGPT session opens the browser" {+ try std.testing.expect(eligible("chatgpt-new", false, false, false, false, true, "/home/u"));+ try std.testing.expect(!eligible("codex", false, false, false, false, true, "/home/u"));+ try std.testing.expect(!eligible("chatgpt-new", true, false, false, false, true, "/home/u")); // -p / piped+ try std.testing.expect(!eligible("chatgpt-new", false, true, false, false, true, "/home/u")); // --json / ACP+ try std.testing.expect(!eligible("chatgpt-new", false, false, true, false, true, "/home/u")); // ACP (unattended)+ try std.testing.expect(!eligible("chatgpt-new", false, false, false, true, true, "/home/u")); // sub-agent+ try std.testing.expect(!eligible("chatgpt-new", false, false, false, false, false, "/home/u")); // no terminal output+ try std.testing.expect(!eligible("chatgpt-new", false, false, false, false, true, "")); // no home+}diff --git a/src/main.zig b/src/main.zigindex 8c8dcbf6..d3009a54 100644--- a/src/main.zig+++ b/src/main.zig@@ -562,7 +562,7 @@ test { // ── Unit tests (`zig build test`): pull in tests from imported modu_ = .{ @import("mcp_apps.zig"), @import("html_view.zig"), @import("usage_trace.zig"), @import("providers_confirmation_tests.zig"), @import("repl_model_confirmation_tests.zig"), @import("repl_model_pick_tests.zig"), @import("engine_sink_citation_tests.zig"), @import("cite_markup_stream_tests.zig"), @import("oneshot_citation_tests.zig"), @import("acp_permission.zig"), @import("acp_usage.zig") };_ = .{ @import("mcp_server_tests.zig"), @import("main_test.zig"), @import("artifact_claim_command.zig"), @import("cli_path_hint.zig"), @import("run_budget.zig") };_ = .{ @import("session_catalog.zig"), @import("session_prompt.zig"), @import("session_discovery.zig"), @import("session_workspaces.zig"), @import("commands_resume.zig"), @import("peer_live.zig"), @import("presence_tests.zig"), @import("mcp_rpc_tests.zig") };- _ = .{ @import("prompt_astra.zig"), @import("prompt_guidance.zig"), @import("oauth_chatgpt.zig") }; // per-model guidance (Astra, GPT-5.6); ChatGPT plan sign-in+ _ = .{ @import("prompt_astra.zig"), @import("prompt_guidance.zig"), @import("oauth_chatgpt.zig"), @import("chatgpt_reauth.zig") }; // per-model guidance (Astra, GPT-5.6); ChatGPT plan sign-in (ADR 0253)_ = .{ @import("agent_empty_completion.zig"), @import("agent_model_loop.zig"), @import("publication_policy_tests.zig"), @import("jobs_completion_tests.zig") };_ = .{ @import("provider_routing_tests.zig"), @import("history_wire.zig"), @import("readline_paste_number_tests.zig"), @import("test_hooks.zig"), @import("peer_wake_loop.zig") };_ = .{ @import("list_dir_nearmiss.zig"), @import("tool_preview_tests.zig") };