graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
fix(xai): always-live catalog + SuperGrok token header (v0.0.252)
Rach Pradhan3c24144d42c4
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 7e8d65c9..56b983c2 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -13,9 +13,10 @@ current is part of cutting a release.## v0.0.252 (2026-08-13)- Grok models are discovered live: xAI joins the generic `/v1/models`- catalog discovery (6h disk cache, offline fallback, demand-gated), so new- Grok rollouts no longer need a release to become routable — the- grok-build parity model.+ catalog and always fetches `api.x.ai` (disk cache is offline fallback+ only), so new Grok rollouts become routable without a release. SuperGrok+ login tokens send `X-XAI-Token-Auth` on chat and catalog requests, matching+ grok-build.- The #469 peer-message spacing bracket is pinned by a unit test on theemitted event sequence, plus a CI-wired PTY smoke test for device-roomdelivery.diff --git a/docs/releases/v0.0.252.md b/docs/releases/v0.0.252.mdindex c61b3c2a..09eb1898 100644--- a/docs/releases/v0.0.252.md+++ b/docs/releases/v0.0.252.md@@ -3,18 +3,17 @@xAI joins the live-catalog club, the peer-channel spacing fix grows teeth,and the release workflow learns to survive a pre-existing release.-- **Grok models are discovered live.** The xAI provider spec was the last- major catalog still baked into the binary — new Grok rollouts needed a- release to become routable. xAI is now enrolled in the generic live- discovery every other router already used: an authenticated- `https://api.x.ai/v1/models` fetch, cached for 6h at- `~/.codegraff/xai-models.json` (stale cache is the offline fallback), and- demand-gated so nothing hits the network without an xAI credential. Live- rows replace the provider slice 1:1; context windows the endpoint omits- inherit from the baked table (a `grok-4.3-fast` rollout inherits at the- `-` boundary), and unknown families take the conservative default. This- mirrors how grok-build itself resolves its catalog — backend-first,- etag-cached, bundled fallback — so Grok parity no longer waits on us.+- **Grok models are discovered live, every load.** The xAI provider spec+ was the last major catalog still baked into the binary. It is now+ enrolled in the generic `/v1/models` discovery (`https://api.x.ai/v1/models`)+ and marked always-live: every catalog load hits the network first, and+ `~/.codegraff/xai-models.json` is only the offline fallback. Demand-gated+ so nothing hits the network without an xAI credential. Live rows replace+ the provider slice 1:1; omitted windows inherit from the baked table+ (`grok-4.3-fast` at the `-` boundary). SuperGrok device logins send+ `X-XAI-Token-Auth: xai-grok-cli` on chat and catalog GETs — the same+ routing header grok-build uses for user tokens — and request the frozen+ 10-scope OAuth set plus `referrer=grok-build`.- **The #469 peer-message bracket is pinned as an event sequence.** Thev0.0.251 spacing fix extracted its emission into one helper(`renderPeerBlock`: blank, markers, lines, blank — silence for adiff --git a/src/cli.zig b/src/cli.zigindex 68f2d100..e34d55aa 100644--- a/src/cli.zig+++ b/src/cli.zig@@ -21,6 +21,10 @@ const harness_version = root.harness_version;pub const changelog_text =\\What's new\\──────────+ \\0.0.252+ \\ • Grok models come from a live api.x.ai /v1/models fetch every load — new rollouts no longer wait for a release+ \\ • SuperGrok OAuth tokens send X-XAI-Token-Auth like grok-build, so login sessions can actually call the API+ \\\\0.0.250\\ • First-party OpenAI compaction preserves the complete canonical compact output on both Codex subscription and official Platform Responses routes\\ • Invalid remote compaction falls back locally without mutating history; non-OpenAI providers remain local-onlydiff --git a/src/http_headers.zig b/src/http_headers.zigindex ab1081c7..f61340d3 100644--- a/src/http_headers.zig+++ b/src/http_headers.zig@@ -85,6 +85,11 @@ pub fn providerHeaders(io: Io, provider: Provider, bearer: []const u8, buf: *[12count += 1;},}+ // SuperGrok user tokens need the grok-build routing header.+ if (std.mem.eql(u8, provider.id, "xai") and provider.source == .login) {+ buf[count] = .{ .name = "X-XAI-Token-Auth", .value = "xai-grok-cli" };+ count += 1;+ }if (provider.kind == .anthropic) {buf[count] = .{ .name = "anthropic-version", .value = root.anthropic_version };count += 1;@@ -155,3 +160,42 @@ test "adoptSessionId validates length and never overwrites a minted id" {adoptSessionId("00000000-0000-4000-8000-000000000000");try std.testing.expectEqualStrings(before, sessionId(io));}++test "xai login tokens send X-XAI-Token-Auth; API keys do not" {+ const io = std.testing.io;+ var buf: [12]std.http.Header = undefined;+ const login: Provider = .{+ .id = "xai",+ .kind = .openai,+ .auth = .bearer,+ .url = "",+ .api_key = "oauth-tok",+ .model = "grok-4.3",+ .context = 256_000,+ .source = .login,+ };+ const login_headers = providerHeaders(io, login, "Bearer oauth-tok", &buf);+ var saw_token_auth = false;+ for (login_headers) |h| {+ if (std.mem.eql(u8, h.name, "X-XAI-Token-Auth")) {+ try std.testing.expectEqualStrings("xai-grok-cli", h.value);+ saw_token_auth = true;+ }+ }+ try std.testing.expect(saw_token_auth);++ const env_key: Provider = .{+ .id = "xai",+ .kind = .openai,+ .auth = .bearer,+ .url = "",+ .api_key = "xai-api-key",+ .model = "grok-4.3",+ .context = 256_000,+ .source = .environment,+ };+ const env_headers = providerHeaders(io, env_key, "Bearer xai-api-key", &buf);+ for (env_headers) |h| {+ try std.testing.expect(!std.mem.eql(u8, h.name, "X-XAI-Token-Auth"));+ }+}diff --git a/src/oauth.zig b/src/oauth.zigindex a749579d..18a8fb13 100644--- a/src/oauth.zig+++ b/src/oauth.zig@@ -375,8 +375,9 @@ const xai_oauth_host = "https://auth.x.ai";const xai_device_auth_url = xai_oauth_host ++ "/oauth2/device/code";const xai_token_url = xai_oauth_host ++ "/oauth2/token";const xai_client_id = "b1a00492-073a-47ea-816f-4c329264a828";-const xai_scope = "openid profile email offline_access grok-cli:access api:access";+const xai_scope_form = "openid+profile+email+offline_access+grok-cli:access+api:access+conversations:read+conversations:write+workspaces:read+workspaces:write";const xai_user_agent = "grok-cli/1.0";+const xai_referrer = "grok-build";/// POST a form body to an xAI OAuth endpoint (with a CLI User-Agent); return the/// parsed JSON object.@@ -416,7 +417,7 @@ pub fn xaiLogin(io: Io, gpa: Allocator, arena: Allocator, home: []const u8) !voivar ow = Io.File.stdout().writer(io, &obuf);const out = &ow.interface;- const da_body = try std.fmt.allocPrint(arena, "client_id={s}&scope={s}", .{ xai_client_id, xai_scope });+ const da_body = try std.fmt.allocPrint(arena, "client_id={s}&scope={s}&referrer={s}", .{ xai_client_id, xai_scope_form, xai_referrer });const da = xaiOAuthPost(io, gpa, arena, xai_device_auth_url, da_body) catch |err| {try out.print("✗ xAI device authorization failed: {t}\n", .{err});try out.flush();diff --git a/src/router_catalog.zig b/src/router_catalog.zigindex 0194d9ed..c4e3a226 100644--- a/src/router_catalog.zig+++ b/src/router_catalog.zig@@ -1,7 +1,8 @@-//! Model discovery for Codegraff, Anthropic, and the optional workspace router.+//! Model discovery for Codegraff, Anthropic, xAI, and the optional workspace router.//!//! The workspace router is declared by `.graff/.config.router`; its catalog-//! cache stays beside that config. Catalog failures never prevent startup.+//! cache stays beside that config. xAI is always-live (never TTL-short-circuits).+//! Catalog failures never prevent startup.//! Anthropic's `/v1/models` (catalog kind `.anthropic`) rides the same//! machinery so new Claude releases appear without a rebuild. It differs in//! auth (x-api-key + anthropic-version, like Messages) and in pagination:@@ -29,6 +30,13 @@ const cache_ttl_ms: i64 = 6 * 60 * 60 * 1000;var attempted: [provider.provider_specs.len]bool = @splat(false);var additional_attempted = false;+/// Providers whose live /models list must win over a disk cache every load.+/// xAI ships new Grok ids often enough that a 6h snapshot is actively wrong;+/// always hit api.x.ai and only fall back to cache/baked when offline.+pub fn alwaysLive(spec: provider.ProviderSpec) bool {+ return std.mem.eql(u8, spec.id, "xai");+}+pub const Snapshot = struct {models: []const pricing.ModelInfo,fetched_at_ms: i64 = 0,@@ -176,7 +184,7 @@ pub fn parseModels(arena: Allocator, provider_id: []const u8, data: []const u8)/// Catalog GET auth mirrors the provider's chat auth: OpenAI-style routers/// take a bearer token; Anthropic's /v1/models wants the same x-api-key +/// anthropic-version pair as the Messages endpoint itself.-pub fn catalogHeaders(arena: Allocator, spec: provider.ProviderSpec, key: []const u8, buf: *[3]std.http.Header) ?[]const std.http.Header {+pub fn catalogHeaders(arena: Allocator, spec: provider.ProviderSpec, key: []const u8, source: provider.Keys.CredentialSource, buf: *[4]std.http.Header) ?[]const std.http.Header {buf[0] = .{ .name = "Accept", .value = "application/json" };if (spec.auth == .x_api_key) {buf[1] = .{ .name = "x-api-key", .value = key };@@ -185,6 +193,10 @@ pub fn catalogHeaders(arena: Allocator, spec: provider.ProviderSpec, key: []cons}const bearer = std.fmt.allocPrint(arena, "Bearer {s}", .{key}) catch return null;buf[1] = .{ .name = "Authorization", .value = bearer };+ if (std.mem.eql(u8, spec.id, "xai") and source == .login) {+ buf[2] = .{ .name = "X-XAI-Token-Auth", .value = "xai-grok-cli" };+ return buf[0..3];+ }return buf[0..2];}@@ -208,12 +220,12 @@ fn containsName(rows: []const pricing.ModelInfo, name: []const u8) bool {return false;}-fn fetchPage(io: Io, gpa: Allocator, arena: Allocator, spec: provider.ProviderSpec, key: []const u8, url: []const u8) ?Snapshot {+fn fetchPage(io: Io, gpa: Allocator, arena: Allocator, spec: provider.ProviderSpec, key: []const u8, source: provider.Keys.CredentialSource, url: []const u8) ?Snapshot {var client: std.http.Client = .{ .allocator = gpa, .io = io };defer client.deinit();var aw: Io.Writer.Allocating = .init(arena);- var headers_buf: [3]std.http.Header = undefined;- const headers = catalogHeaders(arena, spec, key, &headers_buf) orelse return null;+ var headers_buf: [4]std.http.Header = undefined;+ const headers = catalogHeaders(arena, spec, key, source, &headers_buf) orelse return null;const res = client.fetch(.{.location = .{ .url = url },.method = .GET,@@ -230,7 +242,7 @@ fn fetchPage(io: Io, gpa: Allocator, arena: Allocator, spec: provider.ProviderSp/// A failed later page keeps the rows already gathered rather than/// discarding a valid prefix; the page cap only guards against a server/// that always answers has_more.-fn fetch(io: Io, gpa: Allocator, arena: Allocator, spec: provider.ProviderSpec, key: []const u8) ?Snapshot {+fn fetch(io: Io, gpa: Allocator, arena: Allocator, spec: provider.ProviderSpec, key: []const u8, source: provider.Keys.CredentialSource) ?Snapshot {const base = modelsUrl(spec);if (base.len == 0) return null;var rows: std.ArrayList(pricing.ModelInfo) = .empty;@@ -238,7 +250,7 @@ fn fetch(io: Io, gpa: Allocator, arena: Allocator, spec: provider.ProviderSpec,var pages: usize = 0;while (pages < 16) : (pages += 1) {const url = pageUrl(arena, base, cursor) orelse break;- const page = fetchPage(io, gpa, arena, spec, key, url) orelse break;+ const page = fetchPage(io, gpa, arena, spec, key, source, url) orelse break;for (page.models) |m| {if (containsName(rows.items, m.name)) continue;rows.append(arena, m) catch return null;@@ -298,14 +310,15 @@ pub fn activate(arena: Allocator, spec: provider.ProviderSpec, discovered: []conreturn pricing.activateProviderModels(arena, spec.id, discovered);}-fn loadSpec(io: Io, gpa: Allocator, arena: Allocator, home: []const u8, spec: provider.ProviderSpec, key: []const u8, force_refresh: bool) bool {+fn loadSpec(io: Io, gpa: Allocator, arena: Allocator, home: []const u8, spec: provider.ProviderSpec, key: []const u8, source: provider.Keys.CredentialSource, force_refresh: bool) bool {if (!dynamic(spec) or key.len == 0) return false;const cached = cachedSnapshot(io, arena, home, spec);- if (!force_refresh) if (cached) |snapshot| {+ const skip_cache = force_refresh or alwaysLive(spec);+ if (!skip_cache) if (cached) |snapshot| {const age = util.unixMs(io) - snapshot.fetched_at_ms;if (age >= 0 and age <= cache_ttl_ms and activate(arena, spec, snapshot.models)) return true;};- if (fetch(io, gpa, arena, spec, key)) |snapshot| {+ if (fetch(io, gpa, arena, spec, key, source)) |snapshot| {if (activate(arena, spec, snapshot.models)) {if (home.len != 0 or isAdditional(spec)) writeCache(io, arena, home, spec, snapshot.models);return true;@@ -315,10 +328,13 @@ fn loadSpec(io: Io, gpa: Allocator, arena: Allocator, home: []const u8, spec: prreturn false;}-fn ensureAt(io: Io, gpa: Allocator, arena: Allocator, home: []const u8, index: usize, key: []const u8) void {- if (attempted[index] or key.len == 0) return;+fn ensureAt(io: Io, gpa: Allocator, arena: Allocator, home: []const u8, keys: provider.Keys, index: usize) void {+ if (attempted[index]) return;+ const spec = provider.provider_specs[index];+ const key = keys.get(spec.id) orelse return;+ if (key.len == 0) return;attempted[index] = true;- _ = loadSpec(io, gpa, arena, home, provider.provider_specs[index], key, false);+ _ = loadSpec(io, gpa, arena, home, spec, key, keys.source(spec.id), false);}fn ensureAdditional(io: Io, gpa: Allocator, arena: Allocator, home: []const u8, keys: provider.Keys) void {@@ -326,13 +342,13 @@ fn ensureAdditional(io: Io, gpa: Allocator, arena: Allocator, home: []const u8,const spec = provider.additional_router orelse return;const key = keys.get(spec.id) orelse return;additional_attempted = true;- _ = loadSpec(io, gpa, arena, home, spec, key, false);+ _ = loadSpec(io, gpa, arena, home, spec, key, keys.source(spec.id), false);}pub fn ensureForStartup(io: Io, gpa: Allocator, arena: Allocator, home: []const u8, keys: provider.Keys, model_flag: ?[]const u8, saved: ?serde.SavedModel) void {for (provider.provider_specs, 0..) |spec, index| {if (!dynamic(spec) or !catalog_selection.startupMayUse(keys, spec.id, model_flag, saved)) continue;- ensureAt(io, gpa, arena, home, index, keys.get(spec.id) orelse "");+ ensureAt(io, gpa, arena, home, keys, index);}if (provider.additional_router) |spec|if (catalog_selection.startupMayUse(keys, spec.id, model_flag, saved))@@ -342,7 +358,7 @@ pub fn ensureForStartup(io: Io, gpa: Allocator, arena: Allocator, home: []constpub fn ensureForQuery(io: Io, gpa: Allocator, arena: Allocator, home: []const u8, keys: provider.Keys, query: []const u8) void {for (provider.provider_specs, 0..) |spec, index| {if (!dynamic(spec) or !catalog_selection.queryMayUse(spec.id, query)) continue;- ensureAt(io, gpa, arena, home, index, keys.get(spec.id) orelse "");+ ensureAt(io, gpa, arena, home, keys, index);}if (provider.additional_router) |spec|if (catalog_selection.queryMayUse(spec.id, query))@@ -353,11 +369,11 @@ pub fn loadAll(io: Io, gpa: Allocator, arena: Allocator, home: []const u8, keys:for (provider.provider_specs, 0..) |spec, index| {if (!dynamic(spec)) continue;attempted[index] = true;- _ = loadSpec(io, gpa, arena, home, spec, keys.get(spec.id) orelse "", force_refresh);+ _ = loadSpec(io, gpa, arena, home, spec, keys.get(spec.id) orelse "", keys.source(spec.id), force_refresh);}if (provider.additional_router) |spec| {additional_attempted = true;- _ = loadSpec(io, gpa, arena, home, spec, keys.get(spec.id) orelse "", force_refresh);+ _ = loadSpec(io, gpa, arena, home, spec, keys.get(spec.id) orelse "", keys.source(spec.id), force_refresh);}}@@ -375,6 +391,32 @@ pub fn loadCachedAll(io: Io, arena: Allocator, home: []const u8) void {}}+pub fn fillDynamicKeys(io: Io, gpa: Allocator, arena: Allocator, home: []const u8, environ_map: anytype, keys: *provider.Keys) void {+ const oauth = @import("oauth.zig");+ const keys_cli = @import("keys_cli.zig");+ for (provider.provider_specs, &keys.values, &keys.sources) |spec, *value, *source| {+ if (!dynamic(spec)) continue;+ const login = switch (spec.login) {+ .xai_device => oauth.loadXaiOAuth(io, gpa, arena, home, false, null),+ .kimi_device => oauth.loadKimiOAuth(io, gpa, arena, home, false, null),+ .codegraff_device => oauth.loadCodegraffKey(io, arena, home),+ else => null,+ };+ if (login) |tok| {+ value.* = tok;+ source.* = .login;+ continue;+ }+ if (environ_map.get(spec.env_key)) |env_key| {+ value.* = env_key;+ source.* = .environment;+ } else if (keys_cli.loadStoredKey(io, arena, home, spec.id)) |stored| {+ value.* = stored;+ source.* = .stored;+ }+ }+}+test {_ = @import("router_catalog_tests.zig");}diff --git a/src/router_catalog_tests.zig b/src/router_catalog_tests.zigindex ca73ed94..11aa8f18 100644--- a/src/router_catalog_tests.zig+++ b/src/router_catalog_tests.zig@@ -13,6 +13,7 @@ const rc = @import("router_catalog.zig");const parseModels = rc.parseModels;const modelsUrl = rc.modelsUrl;const dynamic = rc.dynamic;+const alwaysLive = rc.alwaysLive;const catalogHeaders = rc.catalogHeaders;const cacheDocument = rc.cacheDocument;const pageUrl = rc.pageUrl;@@ -114,8 +115,8 @@ test "Anthropic catalog is live and authenticates like Messages" {try std.testing.expectEqualStrings("https://api.anthropic.com/v1/models?limit=1000", modelsUrl(spec));var state = std.heap.ArenaAllocator.init(std.testing.allocator);defer state.deinit();- var buf: [3]std.http.Header = undefined;- const headers = catalogHeaders(state.allocator(), spec, "sk-test", &buf) orelse+ var buf: [4]std.http.Header = undefined;+ const headers = catalogHeaders(state.allocator(), spec, "sk-test", .none, &buf) orelsereturn error.TestUnexpectedResult;try std.testing.expectEqual(@as(usize, 3), headers.len);try std.testing.expectEqualStrings("x-api-key", headers[1].name);@@ -123,7 +124,7 @@ test "Anthropic catalog is live and authenticates like Messages" {try std.testing.expectEqualStrings("anthropic-version", headers[2].name);// Bearer routers are unchanged by the x-api-key branch.const router = provider.specFor("codegraff") orelse return error.TestUnexpectedResult;- const bearer = catalogHeaders(state.allocator(), router, "key", &buf) orelse+ const bearer = catalogHeaders(state.allocator(), router, "key", .none, &buf) orelsereturn error.TestUnexpectedResult;try std.testing.expectEqual(@as(usize, 2), bearer.len);try std.testing.expectEqualStrings("Authorization", bearer[1].name);@@ -133,16 +134,29 @@ test "xAI catalog is live (grok-build parity: fetch /v1/models, never a baked-onconst spec = provider.specFor("xai") orelse return error.TestUnexpectedResult;try std.testing.expectEqual(provider.ProviderSpec.CatalogKind.openai, spec.catalog);try std.testing.expect(dynamic(spec));+ try std.testing.expect(alwaysLive(spec));try std.testing.expectEqualStrings("https://api.x.ai/v1/models", modelsUrl(spec));// Catalog GET auth mirrors chat auth: plain bearer, like every OpenAI router.var state = std.heap.ArenaAllocator.init(std.testing.allocator);defer state.deinit();- var buf: [3]std.http.Header = undefined;- const headers = catalogHeaders(state.allocator(), spec, "xai-test", &buf) orelse+ var buf: [4]std.http.Header = undefined;+ const headers = catalogHeaders(state.allocator(), spec, "xai-test", .environment, &buf) orelsereturn error.TestUnexpectedResult;try std.testing.expectEqual(@as(usize, 2), headers.len);try std.testing.expectEqualStrings("Authorization", headers[1].name);try std.testing.expectEqualStrings("Bearer xai-test", headers[1].value);+ const login_headers = catalogHeaders(state.allocator(), spec, "oauth-tok", .login, &buf) orelse+ return error.TestUnexpectedResult;+ try std.testing.expectEqual(@as(usize, 3), login_headers.len);+ try std.testing.expectEqualStrings("X-XAI-Token-Auth", login_headers[2].name);+ try std.testing.expectEqualStrings("xai-grok-cli", login_headers[2].value);+}++test "alwaysLive is xAI-only so other OpenAI routers keep the disk TTL" {+ try std.testing.expect(alwaysLive(provider.specFor("xai").?));+ try std.testing.expect(!alwaysLive(provider.specFor("codegraff").?));+ try std.testing.expect(!alwaysLive(provider.specFor("anthropic").?));+ try std.testing.expect(!alwaysLive(provider.specFor("fireworks").?));}test "xAI /v1/models rows inherit baked context windows" {diff --git a/src/startup.zig b/src/startup.zigindex a154cd8a..4d8b4357 100644--- a/src/startup.zig+++ b/src/startup.zig@@ -567,12 +567,7 @@ pub fn runSubcommand(io: Io, gpa: Allocator, arena: Allocator, init: std.processconst kimi_token = init.environ_map.get("KIMI_API_KEY") orelse oauth.loadKimiOAuth(io, gpa, arena, home, false, null) orelse "";_ = kimi_catalog.load(io, gpa, arena, home, kimi_token);var router_keys: provider_mod.Keys = .{ .values = @splat(null) };- for (provider_mod.provider_specs, &router_keys.values) |spec, *value| {- if (!router_catalog.dynamic(spec)) continue;- const login_key = if (spec.login == .codegraff_device) oauth.loadCodegraffKey(io, arena, home) else null;- value.* = init.environ_map.get(spec.env_key) orelse- login_key orelse keys_cli.loadStoredKey(io, arena, home, spec.id);- }+ router_catalog.fillDynamicKeys(io, gpa, arena, home, init.environ_map, &router_keys);if (provider_mod.additional_router) |spec| {router_keys.router_value = init.environ_map.get(spec.env_key) orelsekeys_cli.loadStoredKey(io, arena, home, spec.id);