Skip to content

graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs

Python

fix(codex): discover models dynamically and harden fallback

Rach Pradhanb5dced706632
diff --git a/README.md b/README.md
index 88be5328..5bff93f7 100644
--- a/README.md
+++ b/README.md
@@ -294,14 +294,18 @@ and one of its models (`graff key set openai sk-...` → `--model gpt-...`,
`graff key set anthropic sk-ant-...` → `--model sonnet`, and so on).
A model is routed to the first provider (in the table order above) that both has
-a key set **and** lists the model in `model_table`. Unknown `claude*` models
+a key set **and** lists the model in the active catalog. Codex names, rollout
+visibility, ordering, and context windows come from its account-scoped `/models`
+endpoint, cached for five minutes with the installed Codex client version; baked
+Codex rows are only the offline fallback. Unknown `claude*` models
fall back to Anthropic; any other unknown model falls back to the codegraff
gateway, and `/model` prints a warning when that fallback fires, since a typo'd
name will be rejected by the API on the first request. The startup default is
the first provider with a key, on its default model. `/models` prints the full
table: context window, compaction point, provider, and which providers you have
keys for; `/model <name>` switches (a bare `/model` opens an interactive fuzzy
-picker).
+picker). `graff models refresh` forces a fresh Codex catalog request and refreshes
+the independent models.dev price/context metadata cache.
<details>
<summary><strong>Codex login (ChatGPT subscription)</strong> · <strong>why no Claude login</strong></summary>
@@ -311,7 +315,8 @@ picker).
If you're logged into the Codex CLI, the harness reads the ChatGPT OAuth token
from `~/.codex/auth.json` at startup (the same on-disk-credential trick used for
the codegraff key) and prints `logged into Codex (ChatGPT account …)`. Switch to
-it with `/model gpt-5.5` (or `gpt-5-codex`). This is a third wire format: the
+it with `/model codex`; Graff selects the first visible model in your live,
+account-scoped Codex catalog. This is a third wire format: the
**Responses API** against the ChatGPT backend
(`chatgpt.com/backend-api/codex/responses`), not `api.openai.com`, so it uses
your ChatGPT Pro/Plus subscription rather than a paid API key. Text, tool
diff --git a/sdk/generate.py b/sdk/generate.py
index 2b602e90..567ba1a0 100644
--- a/sdk/generate.py
+++ b/sdk/generate.py
@@ -45,6 +45,8 @@ def gen_ts(schema):
providers = [p["id"] for p in schema["providers"]]
version = schema.get("version", "0")
model_union = " | ".join(f'"{m}"' for m in models)
+ if schema.get("dynamic_model_providers"):
+ model_union += " | (string & {})"
tool_union = " | ".join(f'"{t}"' for t in tools)
provider_union = " | ".join(f'"{p}"' for p in providers)
header = "// AUTO-GENERATED by sdk/generate.py from `harness --schema`. Do not edit.\n"
@@ -475,6 +477,8 @@ def gen_ts_remote(schema):
providers = [p["id"] for p in schema["providers"]]
version = schema.get("version", "0")
model_union = " | ".join(f'"{m}"' for m in models)
+ if schema.get("dynamic_model_providers"):
+ model_union += " | (string & {})"
tool_union = " | ".join(f'"{t}"' for t in tools)
provider_union = " | ".join(f'"{p}"' for p in providers)
header = "// AUTO-GENERATED by sdk/generate.py from `harness --schema`. Do not edit.\n"
diff --git a/sdk/ts/harness.ts b/sdk/ts/harness.ts
index 1f4bfbc8..f3da6e5e 100644
--- a/sdk/ts/harness.ts
+++ b/sdk/ts/harness.ts
@@ -10,7 +10,7 @@ import { createInterface } from "node:readline";
export const HARNESS_VERSION = "0.4";
-export type ModelName = "MiniMax-M2.5" | "MiniMax-M2.7" | "MiniMax-M3" | "accounts/fireworks/models/deepseek-v4-flash" | "accounts/fireworks/models/deepseek-v4-pro" | "accounts/fireworks/models/glm-5p2" | "accounts/fireworks/models/gpt-oss-120b" | "accounts/fireworks/models/kimi-k2p6" | "accounts/fireworks/models/kimi-k2p7-code" | "accounts/fireworks/models/minimax-m3" | "accounts/fireworks/models/qwen3p7-plus" | "claude-fable-5" | "claude-haiku-4-5" | "claude-opus-4-5" | "claude-opus-4-6" | "claude-opus-4-7" | "claude-opus-4-8" | "claude-opus-4.8" | "claude-sonnet-4-5" | "claude-sonnet-4-6" | "claude-sonnet-4.6" | "deepseek-chat" | "deepseek-reasoner" | "deepseek-v4-flash" | "deepseek-v4-pro" | "fugu" | "fugu-ultra" | "fugu-ultra-20260615" | "glm-4.5" | "glm-4.7" | "glm-5" | "glm-5.2" | "gpt-5-codex" | "gpt-5.2" | "gpt-5.3-codex" | "gpt-5.4" | "gpt-5.4-mini" | "gpt-5.4-pro" | "gpt-5.5" | "gpt-5.6" | "gpt-5.6-luna" | "gpt-5.6-terra" | "grok-4.3" | "grok-build" | "kimi-k2.6" | "kimi-k2.7" | "kimi-latest" | "lmstudio" | "mimo-v2-flash" | "mimo-v2.5" | "mimo-v2.5-pro" | "mimo-v2.5-pro-ultraspeed" | "minimax-m3" | "mlx-community/Qwen3.6-27B-OptiQ-4bit";
+export type ModelName = "MiniMax-M2.5" | "MiniMax-M2.7" | "MiniMax-M3" | "accounts/fireworks/models/deepseek-v4-flash" | "accounts/fireworks/models/deepseek-v4-pro" | "accounts/fireworks/models/glm-5p2" | "accounts/fireworks/models/gpt-oss-120b" | "accounts/fireworks/models/kimi-k2p6" | "accounts/fireworks/models/kimi-k2p7-code" | "accounts/fireworks/models/minimax-m3" | "accounts/fireworks/models/qwen3p7-plus" | "claude-fable-5" | "claude-haiku-4-5" | "claude-opus-4-5" | "claude-opus-4-6" | "claude-opus-4-7" | "claude-opus-4-8" | "claude-opus-4.8" | "claude-sonnet-4-5" | "claude-sonnet-4-6" | "claude-sonnet-4.6" | "deepseek-chat" | "deepseek-reasoner" | "deepseek-v4-flash" | "deepseek-v4-pro" | "fugu" | "fugu-ultra" | "fugu-ultra-20260615" | "glm-4.5" | "glm-4.7" | "glm-5" | "glm-5.2" | "gpt-5-codex" | "gpt-5.2" | "gpt-5.3-codex" | "gpt-5.4" | "gpt-5.4-mini" | "gpt-5.4-pro" | "gpt-5.5" | "gpt-5.6" | "gpt-5.6-luna" | "gpt-5.6-terra" | "grok-4.3" | "grok-build" | "kimi-k2.6" | "kimi-k2.7" | "kimi-latest" | "lmstudio" | "mimo-v2-flash" | "mimo-v2.5" | "mimo-v2.5-pro" | "mimo-v2.5-pro-ultraspeed" | "minimax-m3" | "mlx-community/Qwen3.6-27B-OptiQ-4bit" | (string & {});
export type ToolName = "bash" | "bash_output" | "bash_kill" | "read_file" | "edit_file" | "write_file" | "webfetch" | "codedb" | "todo_write" | "todo_read" | "eval" | "ask_user" | "attempt_completion" | "subagent" | "workflow";
export type ProviderId = "anthropic" | "codegraff" | "deepseek" | "openai" | "minimax" | "xiaomi" | "kimi" | "moonshot" | "xai" | "zai" | "fugu" | "fireworks" | "mlx" | "lmstudio" | "codex";
diff --git a/sdk/ts/remote.ts b/sdk/ts/remote.ts
index f706bb67..afafbd0f 100644
--- a/sdk/ts/remote.ts
+++ b/sdk/ts/remote.ts
@@ -9,7 +9,7 @@
export const HARNESS_VERSION = "0.4";
-export type ModelName = "MiniMax-M2.5" | "MiniMax-M2.7" | "MiniMax-M3" | "accounts/fireworks/models/deepseek-v4-flash" | "accounts/fireworks/models/deepseek-v4-pro" | "accounts/fireworks/models/glm-5p2" | "accounts/fireworks/models/gpt-oss-120b" | "accounts/fireworks/models/kimi-k2p6" | "accounts/fireworks/models/kimi-k2p7-code" | "accounts/fireworks/models/minimax-m3" | "accounts/fireworks/models/qwen3p7-plus" | "claude-fable-5" | "claude-haiku-4-5" | "claude-opus-4-5" | "claude-opus-4-6" | "claude-opus-4-7" | "claude-opus-4-8" | "claude-opus-4.8" | "claude-sonnet-4-5" | "claude-sonnet-4-6" | "claude-sonnet-4.6" | "deepseek-chat" | "deepseek-reasoner" | "deepseek-v4-flash" | "deepseek-v4-pro" | "fugu" | "fugu-ultra" | "fugu-ultra-20260615" | "glm-4.5" | "glm-4.7" | "glm-5" | "glm-5.2" | "gpt-5-codex" | "gpt-5.2" | "gpt-5.3-codex" | "gpt-5.4" | "gpt-5.4-mini" | "gpt-5.4-pro" | "gpt-5.5" | "gpt-5.6" | "gpt-5.6-luna" | "gpt-5.6-terra" | "grok-4.3" | "grok-build" | "kimi-k2.6" | "kimi-k2.7" | "kimi-latest" | "lmstudio" | "mimo-v2-flash" | "mimo-v2.5" | "mimo-v2.5-pro" | "mimo-v2.5-pro-ultraspeed" | "minimax-m3" | "mlx-community/Qwen3.6-27B-OptiQ-4bit";
+export type ModelName = "MiniMax-M2.5" | "MiniMax-M2.7" | "MiniMax-M3" | "accounts/fireworks/models/deepseek-v4-flash" | "accounts/fireworks/models/deepseek-v4-pro" | "accounts/fireworks/models/glm-5p2" | "accounts/fireworks/models/gpt-oss-120b" | "accounts/fireworks/models/kimi-k2p6" | "accounts/fireworks/models/kimi-k2p7-code" | "accounts/fireworks/models/minimax-m3" | "accounts/fireworks/models/qwen3p7-plus" | "claude-fable-5" | "claude-haiku-4-5" | "claude-opus-4-5" | "claude-opus-4-6" | "claude-opus-4-7" | "claude-opus-4-8" | "claude-opus-4.8" | "claude-sonnet-4-5" | "claude-sonnet-4-6" | "claude-sonnet-4.6" | "deepseek-chat" | "deepseek-reasoner" | "deepseek-v4-flash" | "deepseek-v4-pro" | "fugu" | "fugu-ultra" | "fugu-ultra-20260615" | "glm-4.5" | "glm-4.7" | "glm-5" | "glm-5.2" | "gpt-5-codex" | "gpt-5.2" | "gpt-5.3-codex" | "gpt-5.4" | "gpt-5.4-mini" | "gpt-5.4-pro" | "gpt-5.5" | "gpt-5.6" | "gpt-5.6-luna" | "gpt-5.6-terra" | "grok-4.3" | "grok-build" | "kimi-k2.6" | "kimi-k2.7" | "kimi-latest" | "lmstudio" | "mimo-v2-flash" | "mimo-v2.5" | "mimo-v2.5-pro" | "mimo-v2.5-pro-ultraspeed" | "minimax-m3" | "mlx-community/Qwen3.6-27B-OptiQ-4bit" | (string & {});
export type ToolName = "bash" | "bash_output" | "bash_kill" | "read_file" | "edit_file" | "write_file" | "webfetch" | "codedb" | "todo_write" | "todo_read" | "eval" | "ask_user" | "attempt_completion" | "subagent" | "workflow";
export type ProviderId = "anthropic" | "codegraff" | "deepseek" | "openai" | "minimax" | "xiaomi" | "kimi" | "moonshot" | "xai" | "zai" | "fugu" | "fireworks" | "mlx" | "lmstudio" | "codex";
diff --git a/src/agent.zig b/src/agent.zig
index 48378873..b0a0349b 100644
--- a/src/agent.zig
+++ b/src/agent.zig
@@ -328,8 +328,9 @@ pub const Agent = struct {
pub const closeThinkingBlock = @import("agent_stream.zig").closeThinkingBlock;
pub const toggleThinkingFold = @import("agent_stream.zig").toggleThinkingFold;
pub const postStream = @import("agent_stream.zig").postStream;
+ pub const postStreamWithClient = @import("agent_stream.zig").postStreamWithClient;
pub const printDelta = @import("agent_stream.zig").printDelta;
- // Codex/gpt-5.5 Responses-over-WebSocket transport (+ its SSE-fallback
+ // Codex Responses-over-WebSocket transport (+ its fresh-client SSE fallback
// wrapper postLive) lives in agent_ws.zig (#codex-ws). Member-aliased.
pub const postResponsesWs = @import("agent_ws.zig").postResponsesWs;
pub const postLive = @import("agent_ws.zig").postLive;
diff --git a/src/agent_stream.zig b/src/agent_stream.zig
index b7313527..360dac7a 100644
--- a/src/agent_stream.zig
+++ b/src/agent_stream.zig
@@ -168,6 +168,14 @@ pub fn toggleThinkingFold(self: *Agent) void {
}
pub fn postStream(self: *Agent, body: []const u8) ![]u8 {
+ return postStreamWithClient(self, self.client, body);
+}
+
+/// SSE stream using an explicit HTTP client. Normal traffic uses the Agent's
+/// shared pool; a WebSocket failure supplies a fresh client so a stale pooled
+/// keep-alive cannot poison the WS→SSE handoff and every fallback retry dials
+/// from a clean pool.
+pub fn postStreamWithClient(self: *Agent, client: *std.http.Client, body: []const u8) ![]u8 {
self.spinnerStart();
defer self.spinnerStop();
self.thinking_open = false; // fresh "Thinking" block state per request
@@ -223,7 +231,7 @@ pub fn postStream(self: *Agent, body: []const u8) ![]u8 {
_ = drainSteerStdin(true);
tty.restore(o);
};
- var req = try self.client.request(.POST, try std.Uri.parse(provider.url), .{
+ var req = try client.request(.POST, try std.Uri.parse(provider.url), .{
.redirect_behavior = .unhandled,
.headers = .{
.content_type = .{ .override = "application/json" },
diff --git a/src/agent_ws.zig b/src/agent_ws.zig
index 2fd5b914..d92ca30d 100644
--- a/src/agent_ws.zig
+++ b/src/agent_ws.zig
@@ -1,4 +1,4 @@
-//! Codex/gpt-5.5 Responses turn over WebSocket. OpenAI's codex prefers ws and
+//! Codex Responses turns over WebSocket. OpenAI's codex prefers ws and
//! falls back to SSE; graff mirrors that. The ws frames carry the SAME event
//! `type`s as the Responses SSE stream (response.output_text.delta,
//! response.completed, …), so each frame is wrapped as a `data: {json}` line
@@ -48,15 +48,22 @@ pub fn wsEligible(self: *Agent) bool {
/// A ws transport/handshake failure disables ws for the session and falls back
/// to SSE; a deliberate Esc/stall propagates unchanged.
pub fn postLive(self: *Agent, body: []const u8) ![]u8 {
- if (!wsEligible(self)) return self.postStream(body);
+ if (!wsEligible(self)) return if (self.ws_off) postStreamFresh(self, body) else self.postStream(body);
return postResponsesWs(self, body) catch |e| {
if (e == error.Interrupted or e == error.StreamStalled) return e;
self.ws_off = true;
- if (self.tracer) |tr| tr.note("ws", "transport error — falling back to SSE for this session");
- return self.postStream(body);
+ if (self.tracer) |tr| tr.note("ws", "transport error — falling back to fresh-client SSE for this session");
+ return postStreamFresh(self, body);
};
}
+fn postStreamFresh(self: *Agent, body: []const u8) ![]u8 {
+ var client: std.http.Client = .{ .allocator = self.gpa, .io = self.io };
+ defer client.deinit();
+ if (self.tracer) |tr| tr.note("sse_fallback", "fresh HTTP client");
+ return self.postStreamWithClient(&client, body);
+}
+
fn wssUrl(arena: std.mem.Allocator, https_url: []const u8) ![]u8 {
if (std.mem.startsWith(u8, https_url, "https://"))
return std.fmt.allocPrint(arena, "wss://{s}", .{https_url["https://".len..]});
@@ -175,7 +182,6 @@ pub fn postResponsesWs(self: *Agent, body: []const u8) ![]u8 {
return full.toOwnedSlice();
}
-
test "wssUrl: https->wss, http->ws" {
var a = std.heap.ArenaAllocator.init(std.testing.allocator);
defer a.deinit();
diff --git a/src/cli.zig b/src/cli.zig
index 10e6b3a2..bf379e20 100644
--- a/src/cli.zig
+++ b/src/cli.zig
@@ -42,7 +42,7 @@ pub const usage_text =
\\ graff login kimi Kimi Code OAuth login (device-code)
\\ graff key set <provider> <key> store a key (macOS Keychain, else 0600 file)
\\ graff key list show which providers have keys
- \\ graff models [refresh] list the model catalog; refresh pulls window/price from models.dev
+ \\ graff models [refresh] list the live catalog; refresh Codex + models.dev metadata
\\ graff mcp add <name> -- <cmd> add an MCP server to .mcp.json
\\ graff mcp list configured MCP servers
\\ graff worktree list list the per-tab worktrees created by -w
diff --git a/src/commands_misc.zig b/src/commands_misc.zig
index 759ff382..010ebb5e 100644
--- a/src/commands_misc.zig
+++ b/src/commands_misc.zig
@@ -31,9 +31,9 @@ const style = &ansi.style;
const jobs = @import("jobs.zig");
const pricing = @import("pricing.zig");
-const model_table = pricing.model_table;
const default_context = pricing.default_context;
const g_cost = &pricing.g_cost;
+const models_cache = @import("models_cache.zig");
const schema = @import("schema.zig");
const renderRootTools = schema.renderRootTools;
@@ -190,19 +190,21 @@ pub fn tryHandle(root: *Agent, keys: *Keys, arena: Allocator, line: []const u8,
}
if (std.mem.eql(u8, line, "/models")) {
try out.writeAll("model ctx compact@ provider key vision\n");
- for (model_table) |m| {
+ for (pricing.models()) |m| {
const has_key = keys.get(m.provider) != null;
const current = std.mem.eql(u8, m.name, root.provider.model) and std.mem.eql(u8, m.provider, root.provider.id);
+ const context = pricing.contextFor(m.provider, m.name);
try out.print("{s:<26} {d:>5}k {d:>5}k {s:<11} {s} {s}{s}\n", .{
m.name,
- m.context / 1000,
- m.context / 10 * 8 / 1000,
+ context / 1000,
+ context / 10 * 8 / 1000,
m.provider,
if (has_key) "✓" else "—",
if (visionModel(m.name)) "✓" else "—",
if (current) " ← current" else "",
});
}
+ try out.print("(codex catalog: {s})\n", .{models_cache.codex_catalog_source});
try out.print("(unknown models: {d}k ctx; claude* → anthropic, else → codegraff)\n", .{default_context / 1000});
// Live LM Studio models: query the local server so loaded models show up
// in /models without hand-typing their ids. Best-effort and silent if the
diff --git a/src/commands_model.zig b/src/commands_model.zig
index ef26cda5..976c27a4 100644
--- a/src/commands_model.zig
+++ b/src/commands_model.zig
@@ -27,7 +27,6 @@ const fetchOpenAIModels = keys_cli.fetchOpenAIModels;
const harness_version = main_mod.harness_version;
const pricing = @import("pricing.zig");
-const model_table = pricing.model_table;
const resolveModelName = pricing.resolveModelName;
const pickers = @import("pickers.zig");
@@ -56,7 +55,7 @@ pub fn tryHandle(root: *Agent, keys: *Keys, arena: Allocator, line: []const u8,
if (arg.len == 0) {
if (main_mod.use_color) { // interactive TTY → fuzzy picker
if (modelPicker(root, keys, arena, out)) |idx| {
- const m = model_table[idx];
+ const m = pricing.models()[idx];
const provider = keys.providerById(m.provider, m.name) catch {
try offerProviderAuth(root, keys, arena, out, m.provider, m.name);
return true;
@@ -69,11 +68,12 @@ pub fn tryHandle(root: *Agent, keys: *Keys, arena: Allocator, line: []const u8,
try out.writeAll("switch with /model <name> or /model <provider>:\n");
for (provider_specs) |spec| {
const keyed = keys.get(spec.id) != null;
+ const default_model = pricing.providerDefaultModel(spec.id, spec.default_model);
try out.print(" {s} {s:<10}{s} default {s}\n", .{
if (keyed) "✓" else "·",
spec.id,
if (keyed) "" else " (no key)",
- spec.default_model,
+ default_model,
});
}
try out.print("{s}add a key now: /key <provider> <key> · full model list: /models{s}\n", .{ style.dim, style.reset });
@@ -106,7 +106,7 @@ pub fn tryHandle(root: *Agent, keys: *Keys, arena: Allocator, line: []const u8,
// baked default. One loaded → switch straight to it; many → list to pick.
if (isLocalUrl(spec.url)) {
const key = keys.get(spec.id) orelse {
- try offerProviderAuth(root, keys, arena, out, spec.id, spec.default_model);
+ try offerProviderAuth(root, keys, arena, out, spec.id, pricing.providerDefaultModel(spec.id, spec.default_model));
return true;
};
const murl = openAiModelsUrl(arena, spec.url);
@@ -125,8 +125,9 @@ pub fn tryHandle(root: *Agent, keys: *Keys, arena: Allocator, line: []const u8,
try out.flush();
return true;
}
- const provider = keys.providerById(spec.id, spec.default_model) catch {
- try offerProviderAuth(root, keys, arena, out, spec.id, spec.default_model);
+ const default_model = pricing.providerDefaultModel(spec.id, spec.default_model);
+ const provider = keys.providerById(spec.id, default_model) catch {
+ try offerProviderAuth(root, keys, arena, out, spec.id, default_model);
return true;
};
try switchProvider(root, arena, provider, out);
@@ -135,7 +136,7 @@ pub fn tryHandle(root: *Agent, keys: *Keys, arena: Allocator, line: []const u8,
const resolved = resolveModelName(keys.*, arg);
const name = try arena.dupe(u8, resolved orelse arg);
const provider = keys.providerFor(name) catch {
- for (model_table) |mt| if (std.mem.eql(u8, mt.name, name)) {
+ for (pricing.models()) |mt| if (std.mem.eql(u8, mt.name, name)) {
try offerProviderAuth(root, keys, arena, out, mt.provider, name);
return true;
};
diff --git a/src/input_util.zig b/src/input_util.zig
index b95c91f8..fd868bb1 100644
--- a/src/input_util.zig
+++ b/src/input_util.zig
@@ -22,7 +22,6 @@ const jobs = @import("jobs.zig");
const runCapped = jobs.runCapped;
const pricing = @import("pricing.zig");
-const model_table = pricing.model_table;
const main_mod = @import("main.zig");
const provider_mod = @import("provider.zig");
@@ -41,7 +40,7 @@ pub fn fillCompletions(gpa: Allocator, line: []const u8, out: *std.ArrayList([]c
const mp = "/model ";
if (std.mem.startsWith(u8, line, mp)) {
const partial = line[mp.len..];
- for (model_table) |m| {
+ for (pricing.models()) |m| {
if (!std.mem.startsWith(u8, m.name, partial)) continue;
var dup = false;
for (out.items) |x| if (std.mem.eql(u8, x, m.name)) {
diff --git a/src/main.zig b/src/main.zig
index 3325ca1a..11b2f294 100644
--- a/src/main.zig
+++ b/src/main.zig
@@ -44,7 +44,7 @@ pub var use_color = false; // stdout is a TTY and NO_COLOR unset → enables col
pub var show_timing = false;
pub var show_cost = false;
pub var json_mode = false; // --json: structured JSONL events on stdout instead of human text
-pub var g_codex_ws = true; // codex/gpt-5.5 uses the WebSocket transport (Responses API over wss) with SSE fallback; GRAFF_CODEX_WS=off|0 forces SSE
+pub var g_codex_ws = true; // root Codex turns use the WebSocket transport (Responses API over wss) with SSE fallback; GRAFF_CODEX_WS=off|0 forces SSE
pub var max_tool_calls: ?u64 = null; // --max-tool-calls: hard per-turn root tool budget
pub var dedupe_tool_calls = false; // --dedupe-tool-calls: reject duplicate root calls in a turn
pub var plan_mode = false; // /plan: read-only — mutating tools are denied, the model proposes
diff --git a/src/models_cache.zig b/src/models_cache.zig
index 18386ad8..55a25d44 100644
--- a/src/models_cache.zig
+++ b/src/models_cache.zig
@@ -1,22 +1,23 @@
//! `graff models` — the model-catalog CLI and the models.dev refresh cache.
//!
-//! graff's catalog (pricing.model_table / price_table) is a hand-maintained
-//! snapshot: instant to read, works offline, and the source of truth for
-//! ROUTING (which provider serves a name). But snapshots drift as OpenAI/etc.
-//! ship models. This module keeps the METADATA (context window + per-token
-//! price) fresh without a rebuild and without slowing startup:
+//! Non-Codex routing starts from pricing.model_table. Codex model names and
+//! windows are account-scoped and discovered from the same authenticated
+//! `/models?client_version=…` endpoint and 5-minute cache design as openai/codex;
+//! the baked Codex rows are only an offline fallback. Separately, models.dev
+//! keeps context/price METADATA fresh for the non-Codex catalog:
//!
//! * `graff models` — print the effective catalog (baked + overlay)
-//! * `graff models refresh` — GET https://models.dev/api.json, extract the
-//! window/price for every model graff already
-//! knows by name, and cache it to disk
+//! * `graff models refresh` — force the Codex account catalog refresh, then
+//! refresh known window/price rows from models.dev
//!
-//! At startup resolveKeys() calls loadOverlay(), which reads that small cache
+//! At startup resolveKeys() first calls loadCodexCatalog(), then loadOverlay().
+//! Codex discovery swaps only the Codex rows in pricing.active_model_table.
+//! loadOverlay() reads the small models.dev cache
//! (NOT the 3 MB models.dev doc — startup stays instant) into two runtime
//! overlays in pricing.zig that priceFor()/contextFor() consult before the
//! baked table. No cache / offline / fresh install → the baked table is the
-//! sole source, so nothing here can break a run. Routing is untouched: the
-//! overlay only refreshes numbers for names the baked table already routes.
+//! sole source, so nothing here can break a run. The models.dev overlay only
+//! refreshes numbers for names the active table already routes.
//!
//! Cache path: ~/.codegraff/models.json, falling back to the flat dotfile
//! ~/.codegraff-models.json when that directory doesn't exist (zig 0.16's
@@ -32,16 +33,19 @@ const util = @import("util.zig");
const strFieldObj = util.strFieldObj;
const models_dev_url = "https://models.dev/api.json";
+const codex_models_url = "https://chatgpt.com/backend-api/codex/models";
+const codex_cache_ttl_ms: i64 = 5 * 60 * 1000;
+pub var codex_catalog_source: []const u8 = "baked offline fallback";
/// models.dev provider ids to trust FIRST when a model id appears under
/// several providers — a vendor's own listing beats a reseller's markup
/// (models.dev keys resellers like requesty/openrouter/vercel alongside the
/// canonical labs). Names not found here fall back to an any-provider scan.
const canonical_providers = [_][]const u8{
- "openai", "anthropic", "deepseek", "xai", "zai",
- "z-ai", "zhipuai", "google", "minimax", "moonshotai",
- "moonshot", "mistral", "meta", "xiaomi", "fireworks-ai",
- "fireworks", "alibaba",
+ "openai", "anthropic", "deepseek", "xai", "zai",
+ "z-ai", "zhipuai", "google", "minimax", "moonshotai",
+ "moonshot", "mistral", "meta", "xiaomi", "fireworks-ai",
+ "fireworks", "alibaba",
};
/// One refreshed metadata row — the subset of a models.dev model we cache.
@@ -75,6 +79,177 @@ fn flatPath(arena: Allocator, home: []const u8) []const u8 {
return std.fmt.allocPrint(arena, "{s}/.codegraff-models.json", .{home}) catch "";
}
+fn codexDirPath(arena: Allocator, home: []const u8) []const u8 {
+ return std.fmt.allocPrint(arena, "{s}/.codegraff/codex-models.json", .{home}) catch "";
+}
+fn codexFlatPath(arena: Allocator, home: []const u8) []const u8 {
+ return std.fmt.allocPrint(arena, "{s}/.codegraff-codex-models.json", .{home}) catch "";
+}
+fn nativeCodexPath(arena: Allocator, codex_home: []const u8) []const u8 {
+ return std.fmt.allocPrint(arena, "{s}/models_cache.json", .{codex_home}) catch "";
+}
+
+const CodexSnapshot = struct {
+ models: []const pricing.ModelInfo,
+ client_version: []const u8 = "",
+ fetched_at_ms: i64 = 0,
+};
+
+fn validModelSlug(slug: []const u8) bool {
+ if (slug.len == 0 or slug.len > 256) return false;
+ for (slug) |c| if (!(std.ascii.isAlphanumeric(c) or c == '-' or c == '_' or c == '.' or c == '/')) return false;
+ return true;
+}
+
+/// Accepts both Codex's native cache/remote shape (`slug`, `context_window`)
+/// and graff's compact cache shape (`name`, `context`). Hidden models stay out
+/// of user-facing routing and pickers, matching Codex's ModelPreset behavior.
+fn parseCodexSnapshot(arena: Allocator, data: []const u8) ?CodexSnapshot {
+ const v = std.json.parseFromSliceLeaky(Value, arena, data, .{ .allocate = .alloc_always }) catch return null;
+ if (v != .object) return null;
+ const arr = v.object.get("models") orelse return null;
+ if (arr != .array) return null;
+ var rows: std.ArrayList(pricing.ModelInfo) = .empty;
+ for (arr.array.items) |item| {
+ if (item != .object) continue;
+ if (strFieldObj(item.object, "visibility")) |visibility|
+ if (!std.mem.eql(u8, visibility, "list")) continue;
+ const slug = strFieldObj(item.object, "name") orelse strFieldObj(item.object, "slug") orelse continue;
+ if (!validModelSlug(slug)) continue;
+ var duplicate = false;
+ for (rows.items) |row| if (std.mem.eql(u8, row.name, slug)) {
+ duplicate = true;
+ };
+ if (duplicate) continue;
+ var context = u64Field(item.object, "context");
+ if (context == 0) context = u64Field(item.object, "context_window");
+ if (context == 0) context = pricing.codex_context_window;
+ rows.append(arena, .{
+ .provider = "codex",
+ .name = arena.dupe(u8, slug) catch continue,
+ .context = context,
+ }) catch continue;
+ }
+ const models = rows.toOwnedSlice(arena) catch return null;
+ if (models.len == 0) return null;
+ return .{
+ .models = models,
+ .client_version = strFieldObj(v.object, "client_version") orelse "",
+ .fetched_at_ms = util.intFieldObj(v.object, "fetched_at_ms", 0),
+ };
+}
+
+fn readSmall(io: Io, arena: Allocator, path: []const u8) ?[]const u8 {
+ if (path.len == 0) return null;
+ return Io.Dir.cwd().readFileAlloc(io, path, arena, .limited(4 * 1024 * 1024)) catch null;
+}
+
+fn installedCodexVersion(io: Io, arena: Allocator) ?[]const u8 {
+ var child = std.process.spawn(io, .{
+ .argv = &.{ "codex", "--version" },
+ .stdin = .ignore,
+ .stdout = .pipe,
+ .stderr = .ignore,
+ }) catch return null;
+ defer _ = child.wait(io) catch {};
+ const f = child.stdout orelse return null;
+ var rbuf: [1024]u8 = undefined;
+ var fr = f.readerStreaming(io, &rbuf);
+ const output = fr.interface.allocRemaining(arena, .limited(8 * 1024)) catch return null;
+ const trimmed = std.mem.trim(u8, output, " \t\r\n");
+ const at = std.mem.lastIndexOfAny(u8, trimmed, " \t") orelse return null;
+ const version = std.mem.trim(u8, trimmed[at + 1 ..], " \t");
+ if (version.len == 0 or !std.ascii.isDigit(version[0]) or std.mem.indexOfScalar(u8, version, '.') == null) return null;
+ return version;
+}
+
+fn fetchCodexSnapshot(io: Io, gpa: Allocator, arena: Allocator, token: []const u8, account: []const u8, version: []const u8) ?CodexSnapshot {
+ if (token.len == 0 or account.len == 0 or version.len == 0) return null;
+ const url = std.fmt.allocPrint(arena, "{s}?client_version={s}", .{ codex_models_url, version }) catch return null;
+ const bearer = std.fmt.allocPrint(arena, "Bearer {s}", .{token}) catch return null;
+ const user_agent = std.fmt.allocPrint(arena, "codex_cli_rs/{s} (graff)", .{version}) catch return null;
+ var client: std.http.Client = .{ .allocator = gpa, .io = io };
+ defer client.deinit();
+ var aw: Io.Writer.Allocating = .init(arena);
+ const headers = [_]std.http.Header{
+ .{ .name = "Accept", .value = "application/json" },
+ .{ .name = "Authorization", .value = bearer },
+ .{ .name = "chatgpt-account-id", .value = account },
+ .{ .name = "originator", .value = "codex_cli_rs" },
+ .{ .name = "User-Agent", .value = user_agent },
+ };
+ const res = client.fetch(.{
+ .location = .{ .url = url },
+ .method = .GET,
+ .response_writer = &aw.writer,
+ .extra_headers = &headers,
+ }) catch return null;
+ if (@intFromEnum(res.status) != 200) return null;
+ return parseCodexSnapshot(arena, aw.writer.buffered());
+}
+
+fn writeCodexCache(io: Io, arena: Allocator, home: []const u8, version: []const u8, models: []const pricing.ModelInfo) void {
+ var aw: Io.Writer.Allocating = .init(arena);
+ aw.writer.writeAll("{\"source\":\"chatgpt.com/backend-api/codex/models\",\"fetched_at_ms\":") catch return;
+ aw.writer.print("{d},\"client_version\":", .{util.unixMs(io)}) catch return;
+ var version_stringify: std.json.Stringify = .{ .writer = &aw.writer };
+ version_stringify.write(version) catch return;
+ aw.writer.writeAll(",\"models\":[") catch return;
+ for (models, 0..) |model, i| {
+ if (i > 0) aw.writer.writeByte(',') catch return;
+ aw.writer.writeAll("{\"name\":") catch return;
+ var name_stringify: std.json.Stringify = .{ .writer = &aw.writer };
+ name_stringify.write(model.name) catch return;
+ aw.writer.print(",\"context\":{d}}}", .{model.context}) catch return;
+ }
+ aw.writer.writeAll("]}\n") catch return;
+ for ([_][]const u8{ codexDirPath(arena, home), codexFlatPath(arena, home) }) |path| {
+ if (path.len == 0) continue;
+ const f = Io.Dir.cwd().createFile(io, path, .{}) catch continue;
+ defer f.close(io);
+ var wbuf: [4096]u8 = undefined;
+ var fw = f.writer(io, &wbuf);
+ fw.interface.writeAll(aw.writer.buffered()) catch continue;
+ fw.interface.flush() catch continue;
+ return;
+ }
+}
+
+/// Activate an account-scoped Codex catalog. Match openai/codex's policy:
+/// a client-version-keyed cache is fresh for five minutes, then remote refresh;
+/// remote failure falls back to stale graff cache, native Codex cache, and
+/// finally pricing.zig's minimal baked rows. Tokens are never persisted.
+pub fn loadCodexCatalog(io: Io, gpa: Allocator, arena: Allocator, home: []const u8, codex_home: []const u8, token: []const u8, account: []const u8, force_refresh: bool) void {
+ const native_data = readSmall(io, arena, nativeCodexPath(arena, codex_home));
+ const native = if (native_data) |data| parseCodexSnapshot(arena, data) else null;
+ const version = installedCodexVersion(io, arena) orelse if (native) |snapshot| snapshot.client_version else "";
+ const cached_data = readSmall(io, arena, codexDirPath(arena, home)) orelse readSmall(io, arena, codexFlatPath(arena, home));
+ const cached = if (cached_data) |data| parseCodexSnapshot(arena, data) else null;
+ const now = util.unixMs(io);
+ if (!force_refresh) if (cached) |snapshot| {
+ const age = now - snapshot.fetched_at_ms;
+ if (std.mem.eql(u8, snapshot.client_version, version) and age >= 0 and age <= codex_cache_ttl_ms) {
+ if (pricing.activateCodexModels(arena, snapshot.models)) codex_catalog_source = "dynamic cache";
+ return;
+ }
+ };
+ if (fetchCodexSnapshot(io, gpa, arena, token, account, version)) |snapshot| {
+ if (pricing.activateCodexModels(arena, snapshot.models)) {
+ codex_catalog_source = "live account catalog";
+ writeCodexCache(io, arena, home, version, snapshot.models);
+ return;
+ }
+ }
+ if (cached) |snapshot| if (pricing.activateCodexModels(arena, snapshot.models)) {
+ codex_catalog_source = "stale dynamic cache (offline)";
+ return;
+ };
+ if (native) |snapshot| if (pricing.activateCodexModels(arena, snapshot.models)) {
+ codex_catalog_source = "Codex native cache (offline)";
+ return;
+ };
+}
+
/// GET models.dev/api.json (~3 MB) and parse it into the arena, or null on any
/// failure (offline, non-200, malformed) — the caller falls back to baked data.
fn fetchModelsDev(io: Io, gpa: Allocator, arena: Allocator) ?Value {
@@ -235,8 +410,9 @@ fn reportNew(doc: std.json.ObjectMap, out: *Io.Writer) void {
if (shown > 12) out.print(" … and {d} more\n", .{shown - 12}) catch {};
}
-/// `graff models refresh`: pull models.dev, cache window+price for every model
-/// graff knows by name, apply it live, and report what changed / what's new.
+/// `graff models refresh`: Codex was force-refreshed by startup.runSubcommand;
+/// now pull models.dev, cache window+price for every active model name, apply it
+/// live, and report what changed / what's new.
pub fn refresh(io: Io, gpa: Allocator, arena: Allocator, home: []const u8, out: *Io.Writer) !void {
try out.print("fetching {s} …\n", .{models_dev_url});
try out.flush();
@@ -247,9 +423,10 @@ pub fn refresh(io: Io, gpa: Allocator, arena: Allocator, home: []const u8, out:
};
var metas: std.ArrayList(Meta) = .empty;
defer metas.deinit(gpa);
- for (pricing.model_table, 0..) |mi, i| {
+ const catalog = pricing.models();
+ for (catalog, 0..) |mi, i| {
var dup = false; // dedupe: the same name can appear under several providers
- for (pricing.model_table[0..i]) |prev| {
+ for (catalog[0..i]) |prev| {
if (std.mem.eql(u8, prev.name, mi.name)) {
dup = true;
break;
@@ -273,21 +450,27 @@ pub fn refresh(io: Io, gpa: Allocator, arena: Allocator, home: []const u8, out:
/// overlay), grouped by provider, with the live window and per-1M price.
pub fn list(out: *Io.Writer) !void {
const fresh = pricing.price_overlay.len > 0 or pricing.context_overlay.len > 0;
- try out.print("model catalog — {d} entries{s}\n", .{ pricing.model_table.len, if (fresh) " (refreshed from models.dev)" else "" });
+ const catalog = pricing.models();
+ try out.print("model catalog — {d} entries{s}\n", .{ catalog.len, if (fresh) " (refreshed from models.dev)" else "" });
var last: []const u8 = "";
- for (pricing.model_table) |m| {
+ for (catalog) |m| {
if (!std.mem.eql(u8, m.provider, last)) {
- try out.print("\n{s}:\n", .{m.provider});
+ if (std.mem.eql(u8, m.provider, "codex"))
+ try out.print("\n{s} ({s}):\n", .{ m.provider, codex_catalog_source })
+ else
+ try out.print("\n{s}:\n", .{m.provider});
last = m.provider;
}
const ctx = pricing.contextFor(m.provider, m.name);
- if (pricing.priceFor(m.name)) |p| {
+ if (std.mem.eql(u8, m.provider, "codex")) {
+ try out.print(" {s:<34}{d:>10} ctx (subscription)\n", .{ m.name, ctx });
+ } else if (pricing.priceFor(m.name)) |p| {
try out.print(" {s:<34}{d:>10} ctx ${d}/{d} per 1M\n", .{ m.name, ctx, p.in, p.out });
} else {
try out.print(" {s:<34}{d:>10} ctx (unpriced)\n", .{ m.name, ctx });
}
}
- try out.writeAll("\nrefresh window/price from models.dev: graff models refresh\n");
+ try out.writeAll("\nrefresh Codex catalog + models.dev metadata: graff models refresh\n");
try out.flush();
}
@@ -336,3 +519,21 @@ test "findModel prefers the canonical vendor over a reseller markup" {
try std.testing.expect(findModel(v.object, "gpt5.6") != null);
try std.testing.expect(findModel(v.object, "no-such-model") == null);
}
+
+test "Codex snapshot uses visible remote slugs and their advertised contexts" {
+ var a = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer a.deinit();
+ const snapshot = parseCodexSnapshot(a.allocator(),
+ \\{"client_version":"9.9.9","models":[
+ \\ {"slug":"future-sol","visibility":"list","context_window":372000},
+ \\ {"slug":"future-hidden","visibility":"hide","context_window":999000},
+ \\ {"slug":"future-luna","visibility":"list","context_window":128000},
+ \\ {"slug":"future-luna","visibility":"list","context_window":1}]}
+ ).?;
+ try std.testing.expectEqualStrings("9.9.9", snapshot.client_version);
+ try std.testing.expectEqual(@as(usize, 2), snapshot.models.len);
+ try std.testing.expectEqualStrings("future-sol", snapshot.models[0].name);
+ try std.testing.expectEqual(@as(u64, 372_000), snapshot.models[0].context);
+ try std.testing.expectEqualStrings("future-luna", snapshot.models[1].name);
+ try std.testing.expectEqual(@as(u64, 128_000), snapshot.models[1].context);
+}
diff --git a/src/oauth.zig b/src/oauth.zig
index e06277c0..e6e7a0d0 100644
--- a/src/oauth.zig
+++ b/src/oauth.zig
@@ -212,7 +212,7 @@ pub fn codexLogin(io: Io, gpa: Allocator, arena: Allocator, home: []const u8, re
const refresh = strFieldObj(resp, "refresh_token") orelse "";
const account = accountFromIdToken(arena, id_token);
try writeCodexAuth(io, arena, home, id_token, access, refresh, account);
- try out.print("✓ logged into Codex (account {s}…) — wrote ~/.codex/auth.json. /model gpt-5.5\n", .{account[0..@min(account.len, 8)]});
+ try out.print("✓ logged into Codex (account {s}…) — wrote ~/.codex/auth.json. /model codex\n", .{account[0..@min(account.len, 8)]});
try out.flush();
}
diff --git a/src/pickers.zig b/src/pickers.zig
index 3b799669..0e9ba9d8 100644
--- a/src/pickers.zig
+++ b/src/pickers.zig
@@ -19,7 +19,6 @@ const term = @import("term.zig");
const tty = term.tty;
const pricing = @import("pricing.zig");
-const model_table = pricing.model_table;
const oauth = @import("oauth.zig");
@@ -88,6 +87,7 @@ fn scoredLess(_: void, a: Scored, b: Scored) bool {
/// a full-screen alternate buffer: type to filter, ↑/↓ to move, Enter to pick,
/// Ctrl-C to cancel. Returns the chosen model_table index, or null.
pub fn modelPicker(root: *Agent, keys: *Keys, arena: Allocator, out: *Io.Writer) ?usize {
+ const model_table = pricing.models();
const in = root.in orelse return null;
const raw_state = tty.enterRaw(true) orelse return null;
defer tty.restore(raw_state);
@@ -134,12 +134,13 @@ pub fn modelPicker(root: *Agent, keys: *Keys, arena: Allocator, out: *Io.Writer)
const m = model_table[filtered.items[row]];
const cur = std.mem.eql(u8, m.name, root.provider.model) and std.mem.eql(u8, m.provider, root.provider.id);
const keyed = keys.get(m.provider) != null;
+ const context = pricing.contextFor(m.provider, m.name);
if (row == sel) out.writeAll("\x1b[7m") catch {};
out.print("{s} {s:<26} {s:<11} {d}k{s}{s}\n", .{
if (cur) "▌" else " ",
m.name,
m.provider,
- m.context / 1000,
+ context / 1000,
if (keyed) "" else " ·no key",
if (row == sel) "\x1b[0m" else "",
}) catch {};
@@ -342,7 +343,7 @@ pub const command_menu = [_]PickItem{
.{ .name = "/keepcontext", .desc = "keep history across wire-format switches" },
.{ .name = "/effort", .desc = "thinking depth: low|medium|high (codex, deepseek, codegraff)" },
.{ .name = "/reasoning", .desc = "alias for /effort" },
- .{ .name = "/fast", .desc = "codex priority service tier — lower latency (gpt-5.6)" },
+ .{ .name = "/fast", .desc = "codex priority service tier — lower latency on supported models" },
.{ .name = "/ultracode", .desc = "toggle persistent ultracode (multi-agent workflow) mode" },
.{ .name = "/thinking", .desc = "show/collapse the model's live reasoning stream" },
.{ .name = "/title", .desc = "AI-name the tab from your first prompt (on by default)" },
diff --git a/src/pricing.zig b/src/pricing.zig
index aeb78160..b2c5f4e4 100644
--- a/src/pricing.zig
+++ b/src/pricing.zig
@@ -139,9 +139,8 @@ pub const ModelInfo = struct {
context: u64,
};
-// Codex/ChatGPT backend: gpt-5.x window is 272k (codex-rs models.json); budget
-// 270k so compaction (80% -> 216k) fires just under the hard cap and absorbs our
-// token under-count (a turn displaying 270k still 400'd). Not the API's 1.05M.
+// Conservative fallback when Codex's live catalog is unavailable. Normal
+// sessions replace every baked Codex row from the authenticated /models cache.
pub const codex_context_window: u64 = 270_000;
pub const model_table = [_]ModelInfo{
@@ -178,17 +177,9 @@ pub const model_table = [_]ModelInfo{
.{ .provider = "xiaomi", .name = "mimo-v2.5", .context = 1_048_576 },
.{ .provider = "xiaomi", .name = "mimo-v2.5-pro-ultraspeed", .context = 1_048_576 },
.{ .provider = "xiaomi", .name = "mimo-v2-flash", .context = 262_144 },
- // Codex/ChatGPT backend lineup (codex-rs models.json): the slugs the
- // chatgpt.com/backend-api/codex/responses endpoint accepts. Default is
- // gpt-5.5 (available to every Codex account); gpt-5.6 is the newest but
- // ENTITLEMENT-GATED — OpenAI rolls it out to Codex accounts gradually, and
- // one without it 400s ("model not supported when using Codex with a ChatGPT
- // account"), so it is a selectable opt-in here, NOT the default. Verified
- // live 2026-07-10. The -codex-suffixed API-only names (gpt-5.5-codex,
- // gpt-5-codex) are NOT codex-backend slugs and stay openai-only. All share
- // the ~272k backend window (codex_context_window), not the API's 1.05M.
+ // Offline fallback only. At startup models_cache.zig replaces the entire
+ // Codex slice from the account-scoped /models response (5-minute cache).
.{ .provider = "codex", .name = "gpt-5.5", .context = codex_context_window },
- .{ .provider = "codex", .name = "gpt-5.6", .context = codex_context_window }, // newest; entitlement-gated opt-in
.{ .provider = "codex", .name = "gpt-5.4", .context = codex_context_window },
.{ .provider = "codex", .name = "gpt-5.4-mini", .context = codex_context_window },
.{ .provider = "codex", .name = "gpt-5.3-codex", .context = codex_context_window },
@@ -238,6 +229,42 @@ pub const model_table = [_]ModelInfo{
.{ .provider = "zai", .name = "glm-4.5", .context = 131_072 },
};
+/// Active catalog for routing, pickers, completion, and runtime listings.
+/// It starts with the offline table above; authenticated Codex discovery swaps
+/// only the Codex rows while keeping every other provider unchanged.
+pub var active_model_table: []const ModelInfo = model_table[0..];
+
+pub fn models() []const ModelInfo {
+ return active_model_table;
+}
+
+/// Codex's first visible account model is its dynamic default, matching
+/// openai/codex's priority-sorted picker. Other providers retain their baked
+/// default; the supplied fallback also covers offline Codex startup.
+pub fn providerDefaultModel(provider_id: []const u8, fallback: []const u8) []const u8 {
+ if (!std.mem.eql(u8, provider_id, "codex")) return fallback;
+ for (models()) |model| if (std.mem.eql(u8, model.provider, "codex")) return model.name;
+ return fallback;
+}
+
+pub fn activateCodexModels(arena: std.mem.Allocator, discovered: []const ModelInfo) bool {
+ if (discovered.len == 0) return false;
+ var non_codex: usize = 0;
+ for (model_table) |m| if (!std.mem.eql(u8, m.provider, "codex")) {
+ non_codex += 1;
+ };
+ const combined = arena.alloc(ModelInfo, non_codex + discovered.len) catch return false;
+ var n: usize = 0;
+ for (model_table) |m| {
+ if (std.mem.eql(u8, m.provider, "codex")) continue;
+ combined[n] = m;
+ n += 1;
+ }
+ @memcpy(combined[n..], discovered);
+ active_model_table = combined;
+ return true;
+}
+
pub const default_context = 200_000;
/// Runtime context-window overlay from `graff models refresh` (name-keyed;
@@ -253,7 +280,7 @@ pub fn contextFor(provider_id: []const u8, model: []const u8) u64 {
const is_codex = std.mem.eql(u8, provider_id, "codex");
// Provider-specific baked row is authoritative (gateway gpt-5.5 = 400k, not
// the API's 1.05M), so it wins over the fresh name-only overlay below.
- for (model_table) |m| {
+ for (models()) |m| {
if (std.mem.eql(u8, m.provider, provider_id) and std.mem.eql(u8, m.name, model)) return m.context;
}
// Fresh overlay (models.dev refresh), then the baked name-only fallback. A
@@ -261,7 +288,7 @@ pub fn contextFor(provider_id: []const u8, model: []const u8) u64 {
for (context_overlay) |m| {
if (std.mem.eql(u8, m.name, model)) return if (is_codex) @min(m.context, codex_context_window) else m.context;
}
- for (model_table) |m| {
+ for (models()) |m| {
if (std.mem.eql(u8, m.name, model)) return if (is_codex) @min(m.context, codex_context_window) else m.context;
}
return default_context;
@@ -292,12 +319,12 @@ pub fn modelAliasEquals(name: []const u8, query: []const u8) bool {
/// `keys` is main.zig's Keys (anytype to keep provider wiring out of this
/// module) — anything with `get(provider_id) ?[]const u8`.
pub fn resolveModelName(keys: anytype, query: []const u8) ?[]const u8 {
- for (model_table) |m| if (std.mem.eql(u8, m.name, query)) return m.name;
- for (model_table) |m| if (modelAliasEquals(m.name, query)) return m.name;
+ for (models()) |m| if (std.mem.eql(u8, m.name, query)) return m.name;
+ for (models()) |m| if (modelAliasEquals(m.name, query)) return m.name;
var qbuf: [128]u8 = undefined;
const qnorm = normalizeModelAlias(&qbuf, query);
var fallback: ?[]const u8 = null;
- for (model_table) |m| {
+ for (models()) |m| {
var nbuf: [128]u8 = undefined;
const nnorm = normalizeModelAlias(&nbuf, m.name);
if (std.ascii.indexOfIgnoreCase(m.name, query) == null and std.mem.indexOf(u8, nnorm, qnorm) == null) continue;
@@ -307,15 +334,15 @@ pub fn resolveModelName(keys: anytype, query: []const u8) ?[]const u8 {
return fallback;
}
-/// Exact membership test against the comptime model table — used to ignore a
+/// Exact membership test against the active model table — used to ignore a
/// remembered startup model that no provider actually serves.
pub fn modelInTable(name: []const u8) bool {
- for (model_table) |m| if (std.mem.eql(u8, m.name, name)) return true;
+ for (models()) |m| if (std.mem.eql(u8, m.name, name)) return true;
return false;
}
pub fn providerModelInTable(provider_id: []const u8, model: []const u8) bool {
- for (model_table) |m| {
+ for (models()) |m| {
if (std.mem.eql(u8, m.provider, provider_id) and std.mem.eql(u8, m.name, model)) return true;
}
return false;
@@ -326,11 +353,25 @@ test "contextFor known model and default fallback" {
try std.testing.expectEqual(@as(u64, default_context), contextFor("nope", "unknown-xyz"));
}
-test "codex catalog matches the codex backend lineup" {
- // The codex ChatGPT backend serves the codex-rs models.json slugs; the
- // -codex-suffixed API-only names (gpt-5.5-codex, gpt-5-codex) are NOT
- // backend slugs, so they stay openai-served and out of the codex catalog.
- try std.testing.expect(providerModelInTable("codex", "gpt-5.6")); // newest, entitlement-gated opt-in
+test "Codex discovery replaces only the baked Codex fallback" {
+ const saved = active_model_table;
+ defer active_model_table = saved;
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const discovered = [_]ModelInfo{
+ .{ .provider = "codex", .name = "future-sol", .context = 372_000 },
+ .{ .provider = "codex", .name = "future-luna", .context = 128_000 },
+ };
+ try std.testing.expect(activateCodexModels(arena_state.allocator(), &discovered));
+ try std.testing.expect(providerModelInTable("codex", "future-sol"));
+ try std.testing.expect(providerModelInTable("codex", "future-luna"));
+ try std.testing.expect(!providerModelInTable("codex", "gpt-5.5"));
+ try std.testing.expectEqual(@as(u64, 372_000), contextFor("codex", "future-sol"));
+ try std.testing.expectEqualStrings("future-sol", providerDefaultModel("codex", "fallback"));
+ try std.testing.expect(providerModelInTable("openai", "gpt-5.6"));
+}
+
+test "baked Codex catalog is an offline fallback, not rollout data" {
try std.testing.expect(providerModelInTable("codex", "gpt-5.5"));
try std.testing.expect(providerModelInTable("codex", "gpt-5.4"));
try std.testing.expect(providerModelInTable("codex", "gpt-5.3-codex"));
diff --git a/src/provider.zig b/src/provider.zig
index e638b271..42b4b0c5 100644
--- a/src/provider.zig
+++ b/src/provider.zig
@@ -7,13 +7,12 @@
//! (`pub const Provider = provider.Provider;` etc.) so the ~everywhere
//! `main_mod.Provider`/`main_mod.Keys`/`main_mod.provider_specs`
//! back-imports across the other split files keep resolving unchanged.
-//! Only needs pricing.zig (contextFor/model_table) for Keys.build/providerFor.
+//! Only needs pricing.zig (contextFor/models) for Keys.build/providerFor.
const std = @import("std");
const pricing = @import("pricing.zig");
const contextFor = pricing.contextFor;
-const model_table = pricing.model_table;
/// Wire format + auth style + endpoint per provider. Base URLs and env-var
/// names from models.dev/api.json (snapshot 2026-06-10); the anthropic and
@@ -106,7 +105,7 @@ pub const Keys = struct {
};
}
- /// Route a model to a provider: first model_table row whose provider has
+ /// Route a model to a provider: first active catalog row whose provider has
/// a key wins (spec order breaks ties). Unknown claude* models go to
/// Anthropic; any other unknown model goes to the codegraff gateway.
pub fn providerFor(keys: Keys, model: []const u8) error{MissingKey}!Provider {
@@ -118,7 +117,7 @@ pub const Keys = struct {
for (provider_specs, keys.values) |spec, value| {
const key = value orelse continue;
if (std.mem.eql(u8, spec.id, "codegraff") != allow_gateway) continue;
- for (model_table) |m| {
+ for (pricing.models()) |m| {
if (std.mem.eql(u8, m.provider, spec.id) and std.mem.eql(u8, m.name, model))
return keys.build(spec, key, model);
}
@@ -138,7 +137,7 @@ pub const Keys = struct {
pub fn defaultProvider(keys: Keys) error{MissingKey}!Provider {
for (provider_specs, keys.values) |spec, value| {
const key = value orelse continue;
- return keys.build(spec, key, spec.default_model);
+ return keys.build(spec, key, pricing.providerDefaultModel(spec.id, spec.default_model));
}
return error.MissingKey;
}
diff --git a/src/providers.zig b/src/providers.zig
index ecbb1685..1944b40c 100644
--- a/src/providers.zig
+++ b/src/providers.zig
@@ -96,7 +96,7 @@ pub fn resolveProviderControlRequest(
if (provider_id.len != 0) {
for (provider_specs) |spec| {
if (!std.mem.eql(u8, spec.id, provider_id)) continue;
- const selected_model = if (model.len == 0) spec.default_model else try arena.dupe(u8, model);
+ const selected_model = if (model.len == 0) pricing.providerDefaultModel(spec.id, spec.default_model) else try arena.dupe(u8, model);
return keys.providerById(spec.id, selected_model);
}
return error.InvalidProvider;
@@ -127,7 +127,7 @@ fn resolveProviderRequest(keys: *Keys, arena: Allocator, query: []const u8) !Pro
for (provider_specs) |spec| {
if (!std.mem.eql(u8, spec.id, arg)) continue;
- return keys.providerById(spec.id, spec.default_model);
+ return keys.providerById(spec.id, pricing.providerDefaultModel(spec.id, spec.default_model));
}
const resolved = resolveModelName(keys.*, arg);
diff --git a/src/schema.zig b/src/schema.zig
index 27dc5916..64bc1c1e 100644
--- a/src/schema.zig
+++ b/src/schema.zig
@@ -424,6 +424,10 @@ pub fn emitSchema(w: *Io.Writer) !void {
try s.endObject();
}
try s.endArray();
+ try s.objectField("dynamic_model_providers");
+ try s.beginArray();
+ try s.write("codex");
+ try s.endArray();
try s.objectField("tools");
try s.beginArray();
for (root_specs) |t| {
diff --git a/src/session_run.zig b/src/session_run.zig
index 4eb116f0..a62e4ab4 100644
--- a/src/session_run.zig
+++ b/src/session_run.zig
@@ -72,7 +72,7 @@ pub fn runReplCommand(gpa: Allocator, io: Io, environ_map: anytype, root: *agent
.tools_responses = root.tools_responses,
};
var models_buf = std.array_list.Managed(u8).init(arena);
- for (pricing.model_table) |mi| {
+ for (pricing.models()) |mi| {
if (mi.name.len == 0) continue;
if (models_buf.items.len != 0) models_buf.appendSlice(", ") catch {};
models_buf.appendSlice(mi.name) catch {};
@@ -347,6 +347,7 @@ pub fn setupSkillsAndTheme(io: Io, arena: Allocator, environ_map: anytype, out:
main_mod.g_codex_ws = !(std.mem.eql(u8, v, "off") or std.mem.eql(u8, v, "0") or std.mem.eql(u8, v, "false") or std.mem.eql(u8, v, "no"));
}
ws.g_debug = environ_map.get("GRAFF_WS_DEBUG") != null;
+ ws.g_force_connect_failure_once = environ_map.get("GRAFF_WS_FORCE_FAIL_ONCE") != null;
skills.loadSkillSettings(io, arena); // per-skill opt-outs, also gates the auto-connect
anim.loadAnimationSetting(io, arena); // {"animation": "..."} → thinking spinner choice
anim.loadThemeSetting(io, arena); // {"theme": "<name>"} → opt-in terminal color theme
diff --git a/src/session_start.zig b/src/session_start.zig
index 63fb06f9..4ae54c88 100644
--- a/src/session_start.zig
+++ b/src/session_start.zig
@@ -129,7 +129,7 @@ pub fn setupWorktreeAndBanner(
try out.print("{s}codegraff{s} · folder: {s}{s}{s} · / for commands · @ picks a file · esc interrupts · ↑/↓ history · tab completes · ctrl-d quits · trace → {s}\n", .{ style.bold, style.reset, style.cyan, main_mod.g_cwd_display, style.reset, trace_path });
try out.flush();
if (codex_account) |acct| {
- try out.print("logged into Codex (ChatGPT account {s}…) — /model gpt-5.5\n", .{acct[0..@min(acct.len, 8)]});
+ try out.print("logged into Codex (ChatGPT account {s}…) — /model codex\n", .{acct[0..@min(acct.len, 8)]});
try out.flush();
}
if (flags.yolo_flag) {
diff --git a/src/startup.zig b/src/startup.zig
index 8c8fba17..05786efd 100644
--- a/src/startup.zig
+++ b/src/startup.zig
@@ -94,10 +94,28 @@ pub fn resolveKeys(io: Io, gpa: Allocator, arena: Allocator, environ_map: anytyp
if (value.* == null) value.* = keys_cli.loadStoredKey(io, arena, home, spec.id);
}
}
- // Apply the models.dev refresh cache (if `graff models refresh` ever ran)
- // before any Provider is built, so contextFor()/priceFor() use the fresh
- // window/price. No cache → a no-op; the baked catalog stays authoritative.
- if (keys_cli.homeEnv(environ_map)) |home| models_cache.loadOverlay(io, arena, home);
+ // Discover the account-scoped Codex catalog before model selection. This
+ // mirrors openai/codex: 5-minute cache keyed by installed Codex version,
+ // authenticated /models refresh, then stale/native/baked offline fallback.
+ // Model names, rollout visibility, and context windows therefore do not
+ // need a graff release. No Codex login/cache → the baked fallback remains.
+ if (keys_cli.homeEnv(environ_map)) |home| {
+ const codex_home = environ_map.get("CODEX_HOME") orelse
+ (std.fmt.allocPrint(arena, "{s}/.codex", .{home}) catch "");
+ models_cache.loadCodexCatalog(
+ io,
+ gpa,
+ arena,
+ home,
+ codex_home,
+ keys.get("codex") orelse "",
+ keys.codex_account,
+ false,
+ );
+ // Apply the independent models.dev price/context overlay after routing
+ // discovery. Provider-specific Codex windows remain authoritative.
+ models_cache.loadOverlay(io, arena, home);
+ }
var default_provider = keys.defaultProvider() catch {
std.process.fatal(
\\no API key found. quickest fixes:
@@ -111,7 +129,8 @@ pub fn resolveKeys(io: Io, gpa: Allocator, arena: Allocator, environ_map: anytyp
// `--model <name|provider>` pins the startup model (same resolution as /model).
if (model_flag) |mname| pick: {
for (provider_mod.provider_specs) |spec| if (std.mem.eql(u8, spec.id, mname)) {
- if (keys.providerById(spec.id, spec.default_model)) |p| {
+ const model = pricing.providerDefaultModel(spec.id, spec.default_model);
+ if (keys.providerById(spec.id, model)) |p| {
default_provider = p;
break :pick;
} else |_| std.process.fatal("no key/login for provider '{s}' (--model)", .{mname});
@@ -304,6 +323,22 @@ pub fn runSubcommand(io: Io, gpa: Allocator, arena: Allocator, init: std.process
// fresh window/price metadata from models.dev into the local cache.
if (flags.positionals.items.len > 0 and std.mem.eql(u8, flags.positionals.items[0], "models")) {
const home = keys_cli.homeEnv(init.environ_map) orelse std.process.fatal("no HOME/USERPROFILE", .{});
+ const codex_home = init.environ_map.get("CODEX_HOME") orelse
+ (std.fmt.allocPrint(arena, "{s}/.codex", .{home}) catch "");
+ const codex_auth = oauth.loadCodexAuth(io, arena, home);
+ models_cache.loadCodexCatalog(
+ io,
+ gpa,
+ arena,
+ home,
+ codex_home,
+ if (codex_auth) |auth| auth.token else "",
+ if (codex_auth) |auth| auth.account else "",
+ flags.positionals.items.len > 1 and
+ (std.mem.eql(u8, flags.positionals.items[1], "refresh") or
+ std.mem.eql(u8, flags.positionals.items[1], "--refresh") or
+ std.mem.eql(u8, flags.positionals.items[1], "update")),
+ );
try models_cache.command(io, gpa, arena, home, flags.positionals.items[1..]);
return true;
}
diff --git a/src/ws.zig b/src/ws.zig
index 0bfffa78..16727cc5 100644
--- a/src/ws.zig
+++ b/src/ws.zig
@@ -24,6 +24,9 @@ const tls = std.crypto.tls;
/// GRAFF_WS_DEBUG=1 → dump the handshake + frame headers to stderr.
pub var g_debug: bool = false;
+/// Deterministic integration-test seam: fail the next WS connect so the live
+/// binary can prove its SSE fallback against the real endpoint.
+pub var g_force_connect_failure_once: bool = false;
fn dbg(comptime fmt: []const u8, args: anytype) void {
if (g_debug) std.debug.print("[ws] " ++ fmt ++ "\n", args);
@@ -84,6 +87,11 @@ pub const WsClient = struct {
/// Reader/Writer interfaces and the TLS client reference its inline buffers
/// and each other).
pub fn connect(gpa: Allocator, io: Io, url: []const u8, insecure: bool, headers: []const Header) Error!*WsClient {
+ if (g_force_connect_failure_once) {
+ g_force_connect_failure_once = false;
+ dbg("forced connect failure (GRAFF_WS_FORCE_FAIL_ONCE)", .{});
+ return error.HandshakeFailed;
+ }
const u = parseUrl(url) orelse return error.BadUrl;
dbg("connect {s} host={s} port={d} path={s} tls={}", .{ url, u.host, u.port, u.path, u.tls });
@@ -315,3 +323,15 @@ test "parseUrl: wss/ws, default ports, path" {
try std.testing.expectEqual(@as(u16, 8080), b.port);
try std.testing.expect(parseUrl("https://nope") == null);
}
+
+test "forced WS failure is one-shot for SSE fallback integration tests" {
+ g_force_connect_failure_once = true;
+ try std.testing.expectError(error.HandshakeFailed, WsClient.connect(
+ std.testing.allocator,
+ std.testing.io,
+ "wss://unused.invalid/x",
+ false,
+ &.{},
+ ));
+ try std.testing.expect(!g_force_connect_failure_once);
+}