graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
anthropic: use an Anthropic Console sign-in (`graff login anthropic`)
justrach0d8feace4dd9
diff --git a/README.md b/README.mdindex 133a2c98..e7c5ab26 100644--- a/README.md+++ b/README.md@@ -65,6 +65,7 @@ graff login chatgpt # ChatGPT sign-in (same as: graff login codex)graff login kimigraff login zaigraff login xai+graff login anthropic # Anthropic Console account (API credits), via Anthropic's `ant` CLIgraff key set deepseek sk-... # any provider by API keygraff --model grok-4.6```diff --git a/docs/adr/0281-anthropic-console-sign-in-reads-the-sdk-profile.md b/docs/adr/0281-anthropic-console-sign-in-reads-the-sdk-profile.mdnew file mode 100644index 00000000..45b337bf--- /dev/null+++ b/docs/adr/0281-anthropic-console-sign-in-reads-the-sdk-profile.md@@ -0,0 +1,39 @@+# 0281. Anthropic Console sign-in reads the SDK's profile++Status: accepted 2026-10-11++## Context++Claude models on graff needed `ANTHROPIC_API_KEY`. Users with an Anthropic+Console account wanted to sign in instead and spend that account's API credits.+Anthropic does not allow third-party products to offer a claude.ai+(subscription) login, so that credential is out of scope. A Console sign-in+is offered through Anthropic's own CLI (`ant auth login`). It writes a+`user_oauth` profile that Anthropic's SDKs read as a credential.++## Decision++- graff reads the same profile the SDKs read, in their order. The directory+ is `ANTHROPIC_CONFIG_DIR`, then `%APPDATA%\Anthropic`, then+ `$XDG_CONFIG_HOME/anthropic`, then `~/.config/anthropic`. The profile is+ `ANTHROPIC_PROFILE`, then `active_config`, then `default`.+- Only `user_oauth` profiles for the default API host are used. Federation+ profiles and profiles that set another `base_url` are left alone.+- Precedence: `ANTHROPIC_API_KEY` wins and profiles are not read (the SDK's+ rule). A profile named by `ANTHROPIC_PROFILE` outranks a key stored with+ `graff key`. The active profile fills in only when nothing else did.+- The token is sent as `Authorization: Bearer`; API keys keep `x-api-key`.+- graff never runs Anthropic's OAuth client itself. Before each request it+ re-reads the credentials file. Within two minutes of expiry, or after an+ auth error, it runs `ant auth print-credentials --access-token`, which+ refreshes and rewrites the file. `graff login anthropic` runs+ `ant auth login`, or prints how to install `ant`.+- Billing is metered: the sign-in spends the workspace's API credits, not a+ flat-rate plan.++## Consequences++A Console account works without creating a key, and a sign-in made for the+SDK or Claude Code is picked up by graff too. Refresh needs `ant` on `PATH`.+Without it, an expired token fails with the provider's auth error until+`ant auth login` is run again.diff --git a/docs/adr/README.md b/docs/adr/README.mdindex 92ceaf64..52edc2ad 100644--- a/docs/adr/README.md+++ b/docs/adr/README.md@@ -289,6 +289,7 @@ record only when you need the evidence or the edge cases.| [0260](0260-clef-compaction-replaces-client-summary.md) | `GRAFF_CLEF_COMPACT=1` routes client-summary compactions through the gateway's server-side `POST /v1/compact` (Clef decision-model pruning, text verbatim); OpenAI-family server paths are untouched and any failure falls back to the summary. || [0261](0261-client-summary-stays-the-compactor.md) | The client summary stays the compactor: `GRAFF_CLEF_COMPACT` defaults off (Clef rarely pruned and mostly fell back to the summary in measurement); first-party Responses routes use only the provider's own compaction. Supersedes 0260's default. || [0270](0270-a-closed-stdio-mcp-server-restarts-on-its-next-call.md) | A stdio MCP server whose connection closes goes back to dormant with its launch config and restarts on its next call; the failed call is never replayed, and after two restarts in a session its tools are withdrawn as before. |+| [0281](0281-anthropic-console-sign-in-reads-the-sdk-profile.md) | Anthropic Console sign-in: graff reads the `user_oauth` profile Anthropic's CLI writes (`ant auth login`), in the SDK's precedence (API key wins), sends it as Bearer, and refreshes through `ant auth print-credentials`; `graff login anthropic` runs `ant auth login`. No claude.ai subscription login. |## When to write onediff --git a/docs/architecture.md b/docs/architecture.mdindex 8568666a..fea5288a 100644--- a/docs/architecture.md+++ b/docs/architecture.md@@ -81,14 +81,13 @@ window, so compaction is per-provider-per-model.| Provider | Kind | Auth | Key env ||---|---|---|---|-| anthropic | anthropic | x-api-key | `ANTHROPIC_API_KEY` |+| anthropic | anthropic | x-api-key (bearer for a Console sign-in) | `ANTHROPIC_API_KEY`, or `graff login anthropic` || codegraff | openai | bearer | `CODEGRAFF_API_KEY` || deepseek | openai | bearer | `DEEPSEEK_API_KEY` || openai | openai | bearer | `OPENAI_API_KEY` || minimax | anthropic | bearer | `MINIMAX_API_KEY` || xiaomi | openai | bearer | `XIAOMI_API_KEY` || codex | responses | bearer | `~/.codex/auth.json` (ChatGPT OAuth) |-| claude | anthropic | bearer | Claude Code OAuth (`~/.claude/.credentials.json` or macOS keychain) |`Provider.Kind` has a third variant, `responses` — the OpenAI **ResponsesAPI** as served by the ChatGPT backend (Codex login). `loadCodexAuth` reads@@ -103,22 +102,12 @@ synthetic `{output, usage}` object that `stepResponses` consumes — appendingmessage/function_call/reasoning items verbatim (they're valid next-turn input)and emitting `function_call_output` items for tool results.-The `claude` provider is the **subscription-login** analogue of codex, on the-Anthropic side: same `anthropic` wire format as the `anthropic` provider, but-it authenticates with the Claude Code subscription instead of an API key.-`loadClaudeAuth` reads the `sk-ant-oat…` OAuth access token from Claude Code's-credentials at startup — `~/.claude/.credentials.json` on Linux, or the macOS-login keychain (service `Claude Code-credentials`, read by spawning the-`security` CLI) — and injects it into the `claude` key slot (its `env_key` is a-non-existent var). Two extra requirements gate that token to the official-client, both satisfied for this provider: `providerHeaders` adds-`anthropic-beta: oauth-2025-04-20`, and `buildBody` sends `system` as an array-of text blocks whose **first** block is exactly the Claude Code identity line,-with the harness's real prompt as a second (cache-broken) block. Routing places-`claude` late in `provider_specs`, so a real `ANTHROPIC_API_KEY` always wins for-the same model name; the subscription is the fallback. The token is read, never-refreshed — on a 401 after expiry, run `claude` once to refresh it (same caveat-as codex).+The `anthropic` provider also accepts an **Anthropic Console sign-in** (ADR+0281): the `user_oauth` profile Anthropic's CLI writes with `ant auth login`,+read in the Anthropic SDK's precedence (`ANTHROPIC_API_KEY` wins). Its+`sk-ant-oat…` token is sent as `Authorization: Bearer` and refreshed through+`ant auth print-credentials --access-token`. It bills the workspace's API+credits. graff does not use a claude.ai subscription login.### Streamingdiff --git a/src/anthropic_profile.zig b/src/anthropic_profile.zignew file mode 100644index 00000000..3fcbab12--- /dev/null+++ b/src/anthropic_profile.zig@@ -0,0 +1,313 @@+//! Anthropic Console sign-in: graff uses the credential Anthropic's own CLI+//! (`ant auth login`) writes, exactly as Anthropic's SDKs do, so a Console+//! account and its workspace's API credits run claude-* models without an API+//! key. graff never runs Anthropic's OAuth client itself: `ant auth login`+//! signs in, and `ant auth print-credentials --access-token` refreshes.+//!+//! Layout (Anthropic SDK `config` package): the directory is+//! `ANTHROPIC_CONFIG_DIR`, else `%APPDATA%\Anthropic` on Windows, else+//! `$XDG_CONFIG_HOME/anthropic`, else `~/.config/anthropic`. The profile is+//! `ANTHROPIC_PROFILE`, else the one-line `active_config`, else `default`.+//! `configs/<p>.json` holds `authentication.type` (only `user_oauth` is read+//! here), `base_url` and `workspace_id`; `credentials/<p>.json` (or the+//! profile's `authentication.credentials_path`) holds `access_token` and+//! `expires_at` in Unix seconds.+//!+//! Precedence follows the SDK's: `ANTHROPIC_API_KEY` wins and profiles are+//! not read; a profile named by `ANTHROPIC_PROFILE` outranks a key stored with+//! `graff key`; the active profile fills in only when nothing else did.+//! A claude.ai subscription login is not a credential graff uses.++const std = @import("std");+const builtin = @import("builtin");+const Io = std.Io;+const Value = std.json.Value;+const Allocator = std.mem.Allocator;++/// Where the profile in use lives. Remembered at startup for the per-request+/// refresh, which has no environment of its own.+pub const Located = struct {+ dir: []const u8,+ profile: []const u8,+ /// Named by `ANTHROPIC_PROFILE` (outranks a stored key).+ named: bool,+};++pub const Profile = struct {+ token: []const u8,+ /// Unix seconds; null when the credential carries none.+ expires_at: ?i64 = null,+ workspace_id: ?[]const u8 = null,+ email: ?[]const u8 = null,+ workspace_name: ?[]const u8 = null,+};++/// Refresh this close to expiry; `ant` refreshes at the same threshold.+const refresh_margin_s: i64 = 120;+/// After a failed `ant` refresh, don't spawn it again on every request.+const retry_after_ms: i64 = 30_000;++var remembered: ?Located = null;+/// Anthropic's CLI; tests point it at a stand-in.+pub var ant_bin: []const u8 = "ant";+var last_failed_ms: i64 = 0;++pub fn locate(arena: Allocator, environ_map: anytype, home: []const u8) ?Located {+ const dir: []const u8 = blk: {+ if (environ_map.get("ANTHROPIC_CONFIG_DIR")) |d| break :blk d;+ if (builtin.os.tag == .windows) {+ const appdata = environ_map.get("APPDATA") orelse return null;+ break :blk std.fs.path.join(arena, &.{ appdata, "Anthropic" }) catch return null;+ }+ if (environ_map.get("XDG_CONFIG_HOME")) |x| if (x.len > 0) break :blk std.fs.path.join(arena, &.{ x, "anthropic" }) catch return null;+ if (home.len == 0) return null;+ break :blk std.fs.path.join(arena, &.{ home, ".config", "anthropic" }) catch return null;+ };+ if (dir.len == 0) return null;+ if (environ_map.get("ANTHROPIC_PROFILE")) |p| if (p.len > 0) return .{ .dir = dir, .profile = p, .named = true };+ return .{ .dir = dir, .profile = "", .named = false };+}++/// `active_config`, else `default`, for an unnamed location.+fn profileName(io: Io, arena: Allocator, loc: Located) []const u8 {+ if (loc.profile.len > 0) return loc.profile;+ const path = std.fs.path.join(arena, &.{ loc.dir, "active_config" }) catch return "default";+ const text = Io.Dir.cwd().readFileAlloc(io, path, arena, .limited(4096)) catch return "default";+ const name = std.mem.trim(u8, text, " \t\r\n");+ return if (name.len == 0) "default" else name;+}++fn readJson(io: Io, arena: Allocator, path: []const u8) ?std.json.ObjectMap {+ const text = Io.Dir.cwd().readFileAlloc(io, path, arena, .limited(1 << 20)) catch return null;+ const v = std.json.parseFromSliceLeaky(Value, arena, text, .{ .allocate = .alloc_always }) catch return null;+ return if (v == .object) v.object else null;+}++fn str(obj: std.json.ObjectMap, field: []const u8) ?[]const u8 {+ const v = obj.get(field) orelse return null;+ return if (v == .string and v.string.len > 0) v.string else null;+}++/// The profile's current credential, from disk only (no network, no `ant`).+/// Null unless it is a `user_oauth` profile for the default API host.+pub fn read(io: Io, arena: Allocator, loc: Located) ?Profile {+ const name = profileName(io, arena, loc);+ const cfg_path = std.fs.path.join(arena, &.{ loc.dir, "configs", std.fmt.allocPrint(arena, "{s}.json", .{name}) catch return null }) catch return null;+ const cfg = readJson(io, arena, cfg_path) orelse return null;+ const auth = cfg.get("authentication") orelse return null;+ if (auth != .object) return null;+ if (!std.mem.eql(u8, str(auth.object, "type") orelse "", "user_oauth")) return null;+ // A profile minted against another API host must not send its token to+ // the default one, nor the default host's traffic to it.+ if (str(cfg, "base_url")) |base| if (!std.mem.eql(u8, std.mem.trimEnd(u8, base, "/"), "https://api.anthropic.com")) return null;+ const creds_path = str(auth.object, "credentials_path") orelse+ (std.fs.path.join(arena, &.{ loc.dir, "credentials", std.fmt.allocPrint(arena, "{s}.json", .{name}) catch return null }) catch return null);+ const creds = readJson(io, arena, creds_path) orelse return null;+ const token = str(creds, "access_token") orelse return null;+ return .{+ .token = token,+ .expires_at = if (creds.get("expires_at")) |v| (if (v == .integer) v.integer else null) else null,+ .workspace_id = str(cfg, "workspace_id") orelse str(creds, "workspace_id"),+ .email = str(creds, "account_email"),+ .workspace_name = str(creds, "workspace_name"),+ };+}++/// Startup: the profile's token for the key table, and remember where it+/// lives for the per-request refresh. `named_only` reads only a profile named+/// by `ANTHROPIC_PROFILE` (the pass before stored keys).+pub fn load(io: Io, arena: Allocator, environ_map: anytype, home: []const u8, named_only: bool) ?[]const u8 {+ if (environ_map.get("ANTHROPIC_API_KEY") != null) return null; // the SDK's rule: a key shadows every profile+ const loc = locate(arena, environ_map, home) orelse return null;+ if (named_only and !loc.named) return null;+ const p = read(io, arena, loc) orelse return null;+ remember(loc, p);+ return std.heap.page_allocator.dupe(u8, p.token) catch null;+}++fn remember(loc: Located, p: Profile) void {+ const a = std.heap.page_allocator;+ _ = p;+ // The token is already bound to the workspace chosen at sign-in, so no+ // `anthropic-workspace-id` header is needed alongside it.+ remembered = .{ .dir = a.dupe(u8, loc.dir) catch return, .profile = a.dupe(u8, loc.profile) catch return, .named = loc.named };+}++/// Before a request (and, forced, after an auth error): the current token.+/// Reads the file; only near expiry (or forced) asks `ant` to refresh.+pub fn fresh(io: Io, gpa: Allocator, arena: Allocator, force: bool) ?[]const u8 {+ const loc = remembered orelse return null;+ const p = read(io, arena, loc) orelse return null;+ const now_ms = @import("util.zig").unixMs(io);+ const near = if (p.expires_at) |exp| exp * 1000 - now_ms <= refresh_margin_s * 1000 else false;+ if (!force and !near) return p.token;+ if (now_ms - last_failed_ms < retry_after_ms) return p.token;+ return refreshViaAnt(io, gpa, arena, profileName(io, arena, loc)) orelse {+ last_failed_ms = now_ms;+ return p.token;+ };+}++fn refreshViaAnt(io: Io, gpa: Allocator, arena: Allocator, profile: []const u8) ?[]const u8 {+ _ = gpa;+ const pr = @import("process_runner.zig");+ const run = pr.runCappedWithOptions(arena, io, &.{ ant_bin, "auth", "print-credentials", "--access-token", "--profile", profile }, 8192, 8192, 20_000, .{}) catch return null;+ if (!pr.ranOk(run)) return null;+ const token = std.mem.trim(u8, run.stdout, " \t\r\n");+ if (!std.mem.startsWith(u8, token, "sk-ant-")) return null;+ return token;+}++/// Console OAuth tokens go in `Authorization: Bearer`; API keys keep `x-api-key`.+pub fn bearerToken(provider_id: []const u8, key: []const u8) bool {+ return std.mem.eql(u8, provider_id, "anthropic") and std.mem.startsWith(u8, key, "sk-ant-oat");+}++/// `graff login anthropic`: Anthropic's CLI signs in (browser, Console+/// account, workspace); graff then reads what it wrote.+pub fn login(io: Io, arena: Allocator, environ_map: anytype, home: []const u8) !void {+ const style = &@import("ansi.zig").style;+ var buf: [1024]u8 = undefined;+ var w = Io.File.stdout().writerStreaming(io, &buf);+ const out = &w.interface;+ var child = std.process.spawn(io, .{ .argv = &.{ ant_bin, "auth", "login" }, .stdin = .inherit, .stdout = .inherit, .stderr = .inherit }) catch |err| switch (err) {+ error.FileNotFound => {+ try out.writeAll(+ \\graff signs in to an Anthropic Console account through Anthropic's CLI, `ant`, which isn't installed.+ \\Install it, then run `graff login anthropic` again:+ \\ macOS: brew install anthropics/tap/ant+ \\ Linux: release binaries at https://github.com/anthropics/anthropic-cli/releases+ \\ Go: go install github.com/anthropics/anthropic-cli/cmd/ant@latest+ \\Or use an API key instead: export ANTHROPIC_API_KEY=sk-ant-…+ \\+ );+ try out.flush();+ std.process.exit(1);+ },+ else => return err,+ };+ const term = try child.wait(io);+ if (term != .exited or term.exited != 0) std.process.fatal("ant auth login did not finish; nothing changed", .{});+ const loc = locate(arena, environ_map, home) orelse std.process.fatal("signed in, but no Anthropic config directory was found", .{});+ const p = read(io, arena, loc) orelse std.process.fatal("signed in, but the profile has no Console credential graff can use", .{});+ try out.print("{s}✓{s} graff will use your Anthropic Console sign-in for claude-* models", .{ style.green, style.reset });+ if (p.email) |e| try out.print(" — {s}", .{e});+ if (p.workspace_name) |ws| try out.print(", workspace {s}", .{ws});+ try out.writeAll(".\n Requests are billed to that workspace's API credits.");+ if (environ_map.get("ANTHROPIC_API_KEY") != null) try out.writeAll("\n ANTHROPIC_API_KEY is set and takes precedence; unset it to use this sign-in.");+ try out.writeAll("\n");+ try out.flush();+}++const testing = std.testing;++const Env = struct {+ map: []const [2][]const u8,+ pub fn get(self: Env, key: []const u8) ?[]const u8 {+ for (self.map) |kv| if (std.mem.eql(u8, kv[0], key)) return kv[1];+ return null;+ }+};++fn writeFile(io: Io, dir: Io.Dir, sub: []const u8, data: []const u8) !void {+ if (std.fs.path.dirname(sub)) |d| try dir.createDirPath(io, d);+ try dir.writeFile(io, .{ .sub_path = sub, .data = data });+}++test "Console profile: read like the SDK; API key and other hosts shadow it" {+ const io = testing.io;+ var tmp = testing.tmpDir(.{});+ defer tmp.cleanup();+ var arena_state = std.heap.ArenaAllocator.init(testing.allocator);+ defer arena_state.deinit();+ const a = arena_state.allocator();+ var buf: [std.fs.max_path_bytes]u8 = undefined;+ const dir = buf[0..try tmp.dir.realPath(io, &buf)];++ try writeFile(io, tmp.dir, "active_config", "work\n");+ try writeFile(io, tmp.dir, "configs/work.json",+ \\{"version":"1.0","authentication":{"type":"user_oauth","client_id":"c"},"workspace_id":"wrkspc_1"}+ );+ try writeFile(io, tmp.dir, "credentials/work.json",+ \\{"version":"1.0","type":"oauth_token","access_token":"sk-ant-oat01-abc","expires_at":4102444800,"account_email":"[email protected]","workspace_name":"Eng"}+ );+ try writeFile(io, tmp.dir, "configs/fed.json",+ \\{"authentication":{"type":"oidc_federation","federation_rule_id":"fdrl_1"}}+ );+ try writeFile(io, tmp.dir, "configs/staging.json",+ \\{"authentication":{"type":"user_oauth"},"base_url":"https://staging.example.com"}+ );+ try writeFile(io, tmp.dir, "credentials/staging.json",+ \\{"access_token":"sk-ant-oat01-stg"}+ );++ const active = Env{ .map = &.{.{ "ANTHROPIC_CONFIG_DIR", dir }} };+ const p = read(io, a, locate(a, active, "").?).?;+ try testing.expectEqualStrings("sk-ant-oat01-abc", p.token);+ try testing.expectEqual(@as(?i64, 4102444800), p.expires_at);+ try testing.expectEqualStrings("wrkspc_1", p.workspace_id.?);+ try testing.expectEqualStrings("Eng", p.workspace_name.?);+ try testing.expectEqualStrings("sk-ant-oat01-abc", load(io, a, active, "", false).?);+ // Only a named profile is read before stored keys.+ try testing.expect(load(io, a, active, "", true) == null);+ // ANTHROPIC_API_KEY shadows every profile, as in the SDK.+ try testing.expect(load(io, a, Env{ .map = &.{ .{ "ANTHROPIC_CONFIG_DIR", dir }, .{ "ANTHROPIC_API_KEY", "sk-ant-api03-x" } } }, "", false) == null);+ // Federation profiles and profiles for another API host are not used.+ try testing.expect(load(io, a, Env{ .map = &.{ .{ "ANTHROPIC_CONFIG_DIR", dir }, .{ "ANTHROPIC_PROFILE", "fed" } } }, "", true) == null);+ try testing.expect(load(io, a, Env{ .map = &.{ .{ "ANTHROPIC_CONFIG_DIR", dir }, .{ "ANTHROPIC_PROFILE", "staging" } } }, "", true) == null);+ // A named profile is read in the first pass.+ try testing.expectEqualStrings("sk-ant-oat01-abc", load(io, a, Env{ .map = &.{ .{ "ANTHROPIC_CONFIG_DIR", dir }, .{ "ANTHROPIC_PROFILE", "work" } } }, "", true).?);+ // A fresh token is returned from disk without asking `ant`.+ try testing.expectEqualStrings("sk-ant-oat01-abc", fresh(io, testing.allocator, a, false).?);+}++test "default directory follows the SDK: XDG, then ~/.config/anthropic" {+ var arena_state = std.heap.ArenaAllocator.init(testing.allocator);+ defer arena_state.deinit();+ const a = arena_state.allocator();+ if (builtin.os.tag == .windows) return error.SkipZigTest;+ try testing.expectEqualStrings("/x/anthropic", locate(a, Env{ .map = &.{.{ "XDG_CONFIG_HOME", "/x" }} }, "/home/u").?.dir);+ try testing.expectEqualStrings("/home/u/.config/anthropic", locate(a, Env{ .map = &.{} }, "/home/u").?.dir);+ try testing.expect(locate(a, Env{ .map = &.{} }, "") == null);+ try testing.expect(bearerToken("anthropic", "sk-ant-oat01-x"));+ try testing.expect(!bearerToken("anthropic", "sk-ant-api03-x"));+ try testing.expect(!bearerToken("minimax", "sk-ant-oat01-x"));+}++test "an expiring Console token is refreshed through ant, and sent as a bearer token" {+ if (builtin.os.tag == .windows) return error.SkipZigTest; // /bin/sh stand-in+ const io = testing.io;+ var tmp = testing.tmpDir(.{});+ defer tmp.cleanup();+ var arena_state = std.heap.ArenaAllocator.init(testing.allocator);+ defer arena_state.deinit();+ const a = arena_state.allocator();+ var buf: [std.fs.max_path_bytes]u8 = undefined;+ const dir = buf[0..try tmp.dir.realPath(io, &buf)];+ try writeFile(io, tmp.dir, "configs/default.json",+ \\{"authentication":{"type":"user_oauth","client_id":"c"}}+ );+ try writeFile(io, tmp.dir, "credentials/default.json",+ \\{"access_token":"sk-ant-oat01-old","expires_at":1}+ );+ try writeFile(io, tmp.dir, "ant", "#!/bin/sh\necho sk-ant-oat01-new\n");+ const script = try std.fs.path.join(a, &.{ dir, "ant" });+ try Io.Dir.cwd().setFilePermissions(io, script, .fromMode(0o755), .{});+ const saved = ant_bin;+ defer ant_bin = saved;+ ant_bin = script;+ last_failed_ms = 0;++ const env = Env{ .map = &.{.{ "ANTHROPIC_CONFIG_DIR", dir }} };+ try testing.expectEqualStrings("sk-ant-oat01-old", load(io, a, env, "", false).?);+ try testing.expectEqualStrings("sk-ant-oat01-new", fresh(io, testing.allocator, a, false).?);++ // The provider built from it authenticates with Bearer, not x-api-key.+ const provider_mod = @import("provider.zig");+ var keys: provider_mod.Keys = .{ .values = @splat(null) };+ try testing.expect(keys.set("anthropic", "sk-ant-oat01-new", .login));+ const p = keys.build(provider_mod.specFor("anthropic").?, "sk-ant-oat01-new", "claude-opus-5-5");+ try testing.expectEqual(provider_mod.Provider.Auth.bearer, p.auth);+ const api_key = keys.build(provider_mod.specFor("anthropic").?, "sk-ant-api03-k", "claude-opus-5-5");+ try testing.expectEqual(provider_mod.Provider.Auth.x_api_key, api_key.auth);+}diff --git a/src/args.zig b/src/args.zigindex 0ba8650c..2906db5f 100644--- a/src/args.zig+++ b/src/args.zig@@ -45,6 +45,7 @@ pub const Flags = struct {xai_login: bool = false,zai_login: bool = false,chatgpt_login: bool = false,+ anthropic_login: bool = false,help_flag: bool = false,version_flag: bool = false,print_flag: bool = false,@@ -261,12 +262,13 @@ pub fn parse(init: std.process.Init) !Flags {if (flags.login_flag and flags.positionals.items.len > 1) {const name = flags.positionals.items[1];const target = loginTarget(name) orelse- std.process.fatal("unknown login '{s}' — graff login [codegraff|chatgpt|kimi|xai|zai]", .{name});+ std.process.fatal("unknown login '{s}' — graff login [codegraff|chatgpt|kimi|xai|zai|anthropic]", .{name});flags.codex_login = std.mem.eql(u8, target, "codex");flags.kimi_login = std.mem.eql(u8, target, "kimi");flags.xai_login = std.mem.eql(u8, target, "xai");flags.zai_login = std.mem.eql(u8, target, "zai");flags.chatgpt_login = std.mem.eql(u8, target, "chatgpt-new");+ flags.anthropic_login = std.mem.eql(u8, target, "anthropic");}}@@ -320,9 +322,9 @@ pub fn parse(init: std.process.Init) !Flags {/// not a login.pub fn loginTarget(name: []const u8) ?[]const u8 {const aliases = [_][2][]const u8{- .{ "codex", "chatgpt-new" }, .{ "chatgpt", "chatgpt-new" }, .{ "openai", "chatgpt-new" }, .{ "gpt", "chatgpt-new" },- .{ "oai", "chatgpt-new" }, .{ "codegraff", "codegraff" }, .{ "graff", "codegraff" }, .{ "kimi", "kimi" },- .{ "xai", "xai" }, .{ "grok", "xai" },+ .{ "codex", "chatgpt-new" }, .{ "chatgpt", "chatgpt-new" }, .{ "openai", "chatgpt-new" }, .{ "gpt", "chatgpt-new" },+ .{ "oai", "chatgpt-new" }, .{ "codegraff", "codegraff" }, .{ "graff", "codegraff" }, .{ "kimi", "kimi" },+ .{ "xai", "xai" }, .{ "grok", "xai" }, .{ "anthropic", "anthropic" }, .{ "console", "anthropic" },};for (aliases) |pair| if (std.ascii.eqlIgnoreCase(name, pair[0])) return pair[1];if (@import("oauth_zai.zig").isLoginName(name)) return "zai";@@ -337,6 +339,7 @@ test "loginTarget: every ChatGPT name, codex included, is the plan's sign-in; untry std.testing.expectEqualStrings("xai", loginTarget("grok").?);try std.testing.expectEqualStrings("kimi", loginTarget("kimi").?);try std.testing.expectEqualStrings("zai", loginTarget("zai").?);+ try std.testing.expectEqualStrings("anthropic", loginTarget("anthropic").?);try std.testing.expect(loginTarget("chatgptt") == null);try std.testing.expect(loginTarget("") == null);}diff --git a/src/oauth.zig b/src/oauth.zigindex 8559d33d..885b570c 100644--- a/src/oauth.zig+++ b/src/oauth.zig@@ -345,6 +345,7 @@ pub fn refreshOAuthKey(io: Io, gpa: Allocator, arena: Allocator, home: []const uconst is_xai = std.mem.eql(u8, provider_id, "xai");const is_codex = std.mem.eql(u8, provider_id, "codex");const is_chatgpt = std.mem.eql(u8, provider_id, "chatgpt-new");+ if (std.mem.eql(u8, provider_id, "anthropic")) return .{ .key = @import("anthropic_profile.zig").fresh(io, gpa, arena, force) orelse return null };if (!is_kimi and !is_xai and !is_codex and !is_chatgpt) return null;oauth_refresh_mutex.lockUncancelable(io);defer oauth_refresh_mutex.unlock(io);diff --git a/src/provider.zig b/src/provider.zigindex 7ae665e5..676fd24c 100644--- a/src/provider.zig+++ b/src/provider.zig@@ -275,7 +275,7 @@ pub const Provider = struct {return .{.id = spec.id,.kind = if (is_kimi_anthropic or @import("provider_codegraff.zig").usesMessages(spec.id, model)) .anthropic else if (is_xai_responses or @import("provider_codegraff.zig").usesResponses(spec.id, model)) .responses else spec.kind,- .auth = if (is_kimi_anthropic) .x_api_key else spec.auth,+ .auth = if (is_kimi_anthropic) .x_api_key else if (@import("anthropic_profile.zig").bearerToken(spec.id, base.api_key)) .bearer else spec.auth,.url = resolvedUrl(spec, model),.api_key = base.api_key,.model = model,@@ -371,7 +371,7 @@ pub const Keys = struct {return .{.id = spec.id,.kind = if (is_kimi_anthropic or @import("provider_codegraff.zig").usesMessages(spec.id, model)) .anthropic else if (is_xai_responses or @import("provider_codegraff.zig").usesResponses(spec.id, model)) .responses else spec.kind,- .auth = if (is_kimi_anthropic) .x_api_key else spec.auth,+ .auth = if (is_kimi_anthropic) .x_api_key else if (@import("anthropic_profile.zig").bearerToken(spec.id, key)) .bearer else spec.auth,.url = resolvedUrl(spec, model),.api_key = key,.model = model,diff --git a/src/startup.zig b/src/startup.zigindex 9f18c3d8..5aba65a9 100644--- a/src/startup.zig+++ b/src/startup.zig@@ -321,7 +321,7 @@ pub fn runSubcommand(io: Io, gpa: Allocator, arena: Allocator, init: std.process// args.loginTarget owns the names.if (flags.login_flag) {const home = keys_cli.homeEnv(init.environ_map) orelse std.process.fatal("no HOME/USERPROFILE", .{});- if (flags.chatgpt_login) try @import("oauth_chatgpt.zig").login(io, gpa, arena, home) else if (flags.xai_login) try oauth.xaiLogin(io, gpa, arena, home) else if (flags.kimi_login) try oauth.kimiLogin(io, gpa, arena, home) else if (flags.zai_login) try oauth.zaiLogin(io, gpa, arena, home) else if (flags.codex_login or flags.refresh_flag) try oauth.codexLogin(io, gpa, arena, home, flags.refresh_flag) else try oauth.codegraffLogin(io, gpa, arena, home);+ if (flags.anthropic_login) try @import("anthropic_profile.zig").login(io, arena, init.environ_map, home) else if (flags.chatgpt_login) try @import("oauth_chatgpt.zig").login(io, gpa, arena, home) else if (flags.xai_login) try oauth.xaiLogin(io, gpa, arena, home) else if (flags.kimi_login) try oauth.kimiLogin(io, gpa, arena, home) else if (flags.zai_login) try oauth.zaiLogin(io, gpa, arena, home) else if (flags.codex_login or flags.refresh_flag) try oauth.codexLogin(io, gpa, arena, home, flags.refresh_flag) else try oauth.codegraffLogin(io, gpa, arena, home);return true;}diff --git a/src/startup_keys.zig b/src/startup_keys.zigindex e516a0fe..9ab9678a 100644--- a/src/startup_keys.zig+++ b/src/startup_keys.zig@@ -254,6 +254,7 @@ fn missingCredentials() noreturn {\\no API key found. quickest fixes:\\ graff login free codegraff key (device-code OAuth)\\ graff key set <provider> <key> store a key (macOS Keychain, else 0600 file)+ \\ graff login anthropic Anthropic Console account (its workspace's API credits)\\ export ANTHROPIC_API_KEY=sk-ant-… or CODEGRAFF/DEEPSEEK/OPENAI/MINIMAX/XIAOMI/KIMI/MOONSHOT/XAI/ZAI _API_KEY\\a Codex CLI login (~/.codex/auth.json) is also picked up automatically., .{});@@ -316,6 +317,12 @@ pub fn resolveKeysOptional(io: Io, gpa: Allocator, arena: Allocator, environ_map// candidate providers. Load those stored keys now; model/fallback/resume// surfaces fill the rest on demand. Aliases/default startup still need all// keys because availability participates in their routing tie-break.+ // Anthropic Console sign-in (anthropic_profile.zig): a profile named by+ // ANTHROPIC_PROFILE outranks a stored key; the active one fills in after.+ const ap = @import("anthropic_profile.zig");+ if (keys.get("anthropic") == null) if (ap.load(io, arena, environ_map, keys_cli.homeEnv(environ_map) orelse "", true)) |t| {+ _ = keys.set("anthropic", t, .login);+ };const selective_stored_keys = hasSelectiveStoredKeyScope(model_flag);var stored_keys_loaded = !selective_stored_keys;if (keys_cli.homeEnv(environ_map)) |home| {@@ -331,6 +338,9 @@ pub fn resolveKeysOptional(io: Io, gpa: Allocator, arena: Allocator, environ_map} else keys_cli.loadMissingStoredKeys(io, gpa, arena, home, &keys, .all);}const home = keys_cli.homeEnv(environ_map) orelse "";+ if (keys.get("anthropic") == null) if (ap.load(io, arena, environ_map, home, false)) |t| {+ _ = keys.set("anthropic", t, .login);+ };var model_catalog: models_cache.LazyCodexCatalog = .{ .codex_home = oauth.codexHomeDir(arena, home) orelse "" };const saved_model: ?serde.SavedModel = if (model_flag == null) serde.loadModel(io, arena, home) else null;// Dynamic Codex discovery is observable only when startup may select@@ -397,3 +407,7 @@ pub fn resolveKeysOptional(io: Io, gpa: Allocator, arena: Allocator, environ_map}return .{ .keys = @import("bench_priors.zig").noteKeysAtStartup(keys, io, arena, keys_cli.homeEnv(environ_map)), .default_provider = default_provider, .stale_saved_model = stale_saved_model, .preferred_provider = preferred_provider, .codex_account = codex_account, .model_catalog = model_catalog, .stored_keys_loaded = stored_keys_loaded };}++test {+ _ = @import("anthropic_profile.zig");+}