Skip to content

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

Python

feat(providers): add workspace router configuration

Rach Pradhanee5283a8e553
diff --git a/README.md b/README.md
index 952f98ba..e8455946 100644
--- a/README.md
+++ b/README.md
@@ -277,7 +277,7 @@ yet an implemented remote authority.
## Providers & models
Direct API-key and OAuth providers across three wire formats. A
-`ProviderSpec` table (`provider_specs` in `src/main.zig`) holds each provider's
+`ProviderSpec` table holds each built-in provider's
endpoint, auth style, env var, and default model; base URLs and key names come
from [models.dev](https://models.dev)'s `api.json` (snapshot 2026-06-10).
@@ -305,6 +305,29 @@ The same pattern works for every API-key row above: swap in the provider id
and one of its models (`graff key set openai sk-...` → `--model gpt-...`,
`graff key set anthropic sk-ant-...` → `--model sonnet`, and so on).
+To add one workspace-local OpenAI-compatible router without changing Graff,
+create `.graff/.config.router`:
+
+```json
+{
+ "id": "openrouter",
+ "name": "OpenRouter",
+ "base_url": "https://openrouter.ai/api/v1",
+ "env_key": "OPENROUTER_API_KEY",
+ "default_model": "anthropic/claude-sonnet-4"
+}
+```
+
+`name` is optional. `takes_effort: true` is also available for routers that
+accept OpenAI-style reasoning-effort requests. The file contains no secret;
+use `export OPENROUTER_API_KEY=...` or `graff key set openrouter ...`.
+Select it with `graff --model openrouter` or `/model openrouter`;
+`graff models refresh` pulls its full catalog. Graff derives
+`/chat/completions` and `/models` from `base_url`, caches that router's model
+catalog in `.graff/.models.router`, and exposes it to the CLI and GUI schema.
+Only one additional router is configured per workspace. `.graff/` is ignored
+by Git in this repository.
+
A model is routed to the first provider (in the table order above) that both has
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`
@@ -319,7 +342,8 @@ 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). `graff models refresh` forces a fresh Codex catalog request and refreshes
-the independent models.dev price/context metadata cache.
+the Codegraff/workspace-router catalogs plus the independent models.dev
+price/context metadata cache.
<details>
<summary><strong>Codex login (ChatGPT subscription)</strong> · <strong>why no Claude login</strong></summary>
diff --git a/src/catalog_selection.zig b/src/catalog_selection.zig
new file mode 100644
index 00000000..6ba64f6e
--- /dev/null
+++ b/src/catalog_selection.zig
@@ -0,0 +1,66 @@
+//! Shared routing predicates for demand-loaded model catalogs.
+//!
+//! Catalog implementations differ (Codex account data, Kimi metadata, generic
+//! OpenAI-compatible routers), but deciding whether a user selection can see a
+//! provider is identical. Keeping that rule provider-id-driven means a new
+//! dynamic router does not need another startup or `/model` special case.
+
+const std = @import("std");
+const pricing = @import("pricing.zig");
+const provider = @import("provider.zig");
+const serde = @import("serde.zig");
+
+pub fn explicitProvider(query: []const u8) ?[]const u8 {
+ const trimmed = std.mem.trim(u8, query, " \t");
+ const end = std.mem.indexOfAny(u8, trimmed, " /\t") orelse trimmed.len;
+ const id = trimmed[0..end];
+ return if (provider.specFor(id)) |spec| spec.id else null;
+}
+
+/// Empty and unknown/fuzzy model queries may observe a provider's newly
+/// discovered rows. An explicit provider or exact baked model narrows the load.
+pub fn queryMayUse(provider_id: []const u8, query: []const u8) bool {
+ const trimmed = std.mem.trim(u8, query, " \t");
+ if (trimmed.len == 0) return true;
+ if (explicitProvider(trimmed)) |id| return std.mem.eql(u8, id, provider_id);
+ if (pricing.modelInTable(trimmed)) return pricing.providerModelInTable(provider_id, trimmed);
+ return true;
+}
+
+pub fn startupMayUse(keys: provider.Keys, provider_id: []const u8, model_flag: ?[]const u8, saved: ?serde.SavedModel) bool {
+ if (keys.get(provider_id) == null) return false;
+ if (model_flag) |query| return queryMayUse(provider_id, query);
+ if (saved) |selection| {
+ if (std.mem.eql(u8, selection.pid, provider_id)) return true;
+ if (pricing.providerModelInTable(selection.pid, selection.model) and keys.get(selection.pid) != null) return false;
+ return true;
+ }
+ const fallback = keys.defaultProvider() catch return false;
+ return std.mem.eql(u8, fallback.id, provider_id);
+}
+
+/// Structured `set_model` has separate provider/model fields. Return the part
+/// whose routing reachability should decide which catalogs are demand-loaded.
+pub fn controlQuery(provider_query: []const u8, model_query: []const u8, legacy_name: []const u8) []const u8 {
+ if (std.mem.trim(u8, provider_query, " \t").len != 0) return provider_query;
+ if (std.mem.trim(u8, model_query, " \t").len != 0) return model_query;
+ return legacy_name;
+}
+
+test "catalog selection is provider-driven rather than catalog-specific" {
+ try std.testing.expect(queryMayUse("codegraff", ""));
+ try std.testing.expect(queryMayUse("codegraff", "codegraff"));
+ try std.testing.expect(!queryMayUse("codegraff", "kimi"));
+ try std.testing.expect(queryMayUse("kimi", "k3"));
+ try std.testing.expect(!queryMayUse("codegraff", "k3"));
+ try std.testing.expect(queryMayUse("codegraff", "future-router-rollout"));
+
+ var keys: provider.Keys = .{ .values = @splat(null) };
+ for (provider.provider_specs, &keys.values) |spec, *value| {
+ if (std.mem.eql(u8, spec.id, "kimi") or std.mem.eql(u8, spec.id, "codegraff")) value.* = "token";
+ }
+ try std.testing.expect(startupMayUse(keys, "codegraff", "codegraff", null));
+ try std.testing.expect(!startupMayUse(keys, "codegraff", "kimi", null));
+ try std.testing.expect(startupMayUse(keys, "codegraff", null, .{ .pid = "codegraff", .model = "deepseek-v4-pro" }));
+ try std.testing.expect(!startupMayUse(keys, "codegraff", null, .{ .pid = "kimi", .model = "k3" }));
+}
diff --git a/src/commands_misc.zig b/src/commands_misc.zig
index ff9078f0..03d66f64 100644
--- a/src/commands_misc.zig
+++ b/src/commands_misc.zig
@@ -12,7 +12,6 @@ const main_mod = @import("main.zig");
const provider_mod = @import("provider.zig");
const agent_mod = @import("agent.zig");
const util = @import("util.zig");
-const provider_specs = provider_mod.provider_specs;
const Agent = agent_mod.Agent;
const Keys = provider_mod.Keys;
const utf8Prefix = util.utf8Prefix;
@@ -68,7 +67,7 @@ fn providerModelCount(provider_id: []const u8) usize {
fn showModelsHealth(root: *Agent, keys: *Keys, arena: Allocator, out: *Io.Writer) !void {
root.ensureStoredKeys(keys);
- root.ensureModelCatalog(keys.*);
+ providers.ensureModelQueryCatalogs(root, keys.*, "");
const saved = serde.loadModel(root.io, arena, root.home);
try out.print("{s}model health{s}\n", .{ style.bold, style.reset });
try out.print("active: {s} via {s} · {d}k ctx · compact@{d}k{s}{s}\n", .{
@@ -106,7 +105,8 @@ fn showModelsHealth(root: *Agent, keys: *Keys, arena: Allocator, out: *Io.Writer
}
try out.writeAll("providers (credential values are never shown):\n");
- for (provider_specs) |spec| {
+ for (0..provider_mod.specCount()) |i| {
+ const spec = provider_mod.specAt(i).?;
const available = keys.get(spec.id) != null;
const source = keys.source(spec.id);
try out.print(" {s} {s:<11} {s:<12} {d:>2} model(s){s}\n", .{
@@ -328,14 +328,7 @@ pub fn tryHandle(root: *Agent, keys: *Keys, arena: Allocator, line: []const u8,
// server is down. Only probe when the user actually uses lmstudio (key set
// or it's the current provider) so we never make a stray localhost hit.
if (keys.get("lmstudio") != null or std.mem.eql(u8, root.provider.id, "lmstudio")) lmstudio: {
- var base: []const u8 = "";
- for (provider_specs) |sp| {
- if (std.mem.eql(u8, sp.id, "lmstudio")) {
- base = sp.url;
- break;
- }
- }
- if (base.len == 0) break :lmstudio;
+ const base = (provider_mod.specFor("lmstudio") orelse break :lmstudio).url;
const suffix = "/chat/completions";
const root_url = if (std.mem.endsWith(u8, base, suffix)) base[0 .. base.len - suffix.len] else base;
const url = std.fmt.allocPrint(arena, "{s}/models", .{root_url}) catch break :lmstudio;
diff --git a/src/commands_model.zig b/src/commands_model.zig
index 1c42ac62..be4b6b62 100644
--- a/src/commands_model.zig
+++ b/src/commands_model.zig
@@ -16,7 +16,6 @@ const agent_mod = @import("agent.zig");
const provider_mod = @import("provider.zig");
const Agent = agent_mod.Agent;
const Keys = provider_mod.Keys;
-const provider_specs = provider_mod.provider_specs;
const storeKey = keys_cli.storeKey;
const repl_glue = @import("repl_glue.zig");
const saveThinkingSettings = repl_glue.saveThinkingSettings;
@@ -61,8 +60,7 @@ const visionCapable = vision.visionCapable;
const grabClipboardImage = vision.grabClipboardImage;
fn providerKnown(id: []const u8) bool {
- for (provider_specs) |spec| if (std.mem.eql(u8, spec.id, id)) return true;
- return false;
+ return provider_mod.specFor(id) != null;
}
fn showFallback(root: *Agent, arena: Allocator, out: *Io.Writer) !void {
@@ -142,7 +140,8 @@ pub fn tryHandle(root: *Agent, keys: *Keys, arena: Allocator, line: []const u8,
}
try out.print("current model: {s}{s}{s} via {s}\n", .{ style.accent, root.provider.model, style.reset, root.provider.id });
try out.writeAll("switch with /model <name> or /model <provider>:\n");
- for (provider_specs) |spec| {
+ for (0..provider_mod.specCount()) |i| {
+ const spec = provider_mod.specAt(i).?;
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", .{
@@ -162,8 +161,8 @@ pub fn tryHandle(root: *Agent, keys: *Keys, arena: Allocator, line: []const u8,
if (std.mem.indexOfAny(u8, arg, " /\t")) |i| {
const pid = arg[0..i];
const mdl = std.mem.trim(u8, arg[i + 1 ..], " \t");
- for (provider_specs) |spec| {
- if (!std.mem.eql(u8, spec.id, pid) or mdl.len == 0) continue;
+ if (provider_mod.specFor(pid)) |spec| {
+ if (mdl.len == 0) return true;
if (!isLocalUrl(spec.url) and !pricing.providerModelInTable(pid, mdl)) {
try out.print("unknown model '{s}' for {s} — choose /model, or run `graff models refresh` first\n", .{ mdl, pid });
try out.flush();
@@ -180,8 +179,7 @@ pub fn tryHandle(root: *Agent, keys: *Keys, arena: Allocator, line: []const u8,
}
// If the query names a provider (e.g. "openai"), switch to THAT
// provider on its default model — not the priority router's pick.
- for (provider_specs) |spec| {
- if (!std.mem.eql(u8, spec.id, arg)) continue;
+ if (provider_mod.specFor(arg)) |spec| {
// Local OpenAI-compatible servers (LM Studio :1234, mlx-lm :8080) serve a
// live, user-loaded model set — list what's actually there instead of a
// baked default. One loaded → switch straight to it; many → list to pick.
@@ -406,7 +404,8 @@ pub fn tryHandle(root: *Agent, keys: *Keys, arena: Allocator, line: []const u8,
const rest = std.mem.trim(u8, line["/key".len..], " \t");
if (rest.len == 0) { // show key status + how to add
try out.writeAll("API keys (✓ = set via env / Keychain / login):\n");
- for (provider_specs) |spec| {
+ for (0..provider_mod.specCount()) |i| {
+ const spec = provider_mod.specAt(i).?;
try out.print(" {s} {s:<10} {s}\n", .{ if (keys.get(spec.id) != null) "✓" else "·", spec.id, spec.env_key });
}
try out.print("{s}add one: /key <provider> <key> (used now + saved to the macOS Keychain){s}\n", .{ style.dim, style.reset });
@@ -420,11 +419,7 @@ pub fn tryHandle(root: *Agent, keys: *Keys, arena: Allocator, line: []const u8,
};
const pid = rest[0..sp];
const key = std.mem.trim(u8, rest[sp + 1 ..], " \t");
- var idx: ?usize = null;
- for (provider_specs, 0..) |spec, i| if (std.mem.eql(u8, spec.id, pid)) {
- idx = i;
- };
- if (idx == null) {
+ if (provider_mod.specFor(pid) == null) {
try out.print("unknown provider '{s}' — see /model for the list\n", .{pid});
try out.flush();
return true;
@@ -434,11 +429,11 @@ pub fn tryHandle(root: *Agent, keys: *Keys, arena: Allocator, line: []const u8,
try out.flush();
return true;
}
- keys.values[idx.?] = arena.dupe(u8, key) catch key; // live, usable immediately
+ const live_key = arena.dupe(u8, key) catch key;
const home = root.home;
const saved = storeKey(root.io, root.gpa, arena, home, pid, key); // persist
- keys.sources[idx.?] = if (saved) .stored else .session;
- if (std.mem.eql(u8, pid, "kimi")) _ = kimi_catalog.load(root.io, root.gpa, arena, home, keys.values[idx.?].?);
+ _ = keys.set(pid, live_key, if (saved) .stored else .session);
+ if (std.mem.eql(u8, pid, "kimi")) _ = kimi_catalog.load(root.io, root.gpa, arena, home, live_key);
try out.print("✓ {s} key set (live{s}) — now: /model {s}\n", .{ pid, if (saved) " + Keychain" else "", pid });
try out.flush();
return true;
@@ -510,11 +505,11 @@ pub fn tryHandle(root: *Agent, keys: *Keys, arena: Allocator, line: []const u8,
};
} else {
// A pure API-key provider, or something unrecognized.
- for (provider_specs) |spec| if (std.mem.eql(u8, spec.id, target)) {
+ if (provider_mod.specFor(target) != null) {
try out.print("{s} uses an API key, not a login \xe2\x80\x94 /key {s} <key>\n", .{ target, target });
try out.flush();
return true;
- };
+ }
try out.print("can't log into '{s}' \xe2\x80\x94 try /login codegraff | codex | kimi | xai (others: /key <provider> <key>)\n", .{target});
try out.flush();
return true;
diff --git a/src/input_util.zig b/src/input_util.zig
index 52ed7a2e..163ee720 100644
--- a/src/input_util.zig
+++ b/src/input_util.zig
@@ -27,7 +27,6 @@ const util = @import("util.zig");
const main_mod = @import("main.zig");
const provider_mod = @import("provider.zig");
const tools_mod = @import("tools.zig");
-const provider_specs = provider_mod.provider_specs;
const repl_commands = main_mod.repl_commands;
const bash_stdout_cap = tools_mod.bash_stdout_cap;
@@ -49,7 +48,10 @@ pub fn fillCompletions(gpa: Allocator, line: []const u8, out: *std.ArrayList([]c
};
if (!dup) out.append(gpa, m.name) catch {};
}
- for (provider_specs) |s| if (std.mem.startsWith(u8, s.id, partial)) out.append(gpa, s.id) catch {};
+ for (0..provider_mod.specCount()) |i| {
+ const spec = provider_mod.specAt(i).?;
+ if (std.mem.startsWith(u8, spec.id, partial)) out.append(gpa, spec.id) catch {};
+ }
return mp.len;
}
if (line.len > 0 and line[0] == '/' and std.mem.indexOfScalar(u8, line, ' ') == null) {
diff --git a/src/keys_cli.zig b/src/keys_cli.zig
index 7e6fe39d..54f7dcff 100644
--- a/src/keys_cli.zig
+++ b/src/keys_cli.zig
@@ -166,6 +166,14 @@ pub const StoredKeyScope = union(enum) {
.mask => |mask| mask[index],
};
}
+
+ pub fn includesRouter(scope: StoredKeyScope, provider_id: []const u8) bool {
+ return switch (scope) {
+ .all => true,
+ .provider => |id| std.mem.eql(u8, id, provider_id),
+ .mask => false,
+ };
+ }
};
test "StoredKeyScope selects all, one provider, or an exact mask" {
@@ -207,6 +215,12 @@ pub fn loadMissingStoredKeys(io: Io, gpa: Allocator, arena: Allocator, home: []c
gpa.free(owned);
if (value.* != null) source.* = .stored;
}
+ if (provider_mod.additional_router) |spec| {
+ if (keys.router_value == null and scope.includesRouter(spec.id)) {
+ keys.router_value = loadStoredKey(io, arena, home, spec.id);
+ if (keys.router_value != null) keys.router_source = .stored;
+ }
+ }
return;
}
@@ -221,10 +235,20 @@ pub fn loadMissingStoredKeys(io: Io, gpa: Allocator, arena: Allocator, home: []c
value.* = stored.string;
source.* = .stored;
}
+ if (provider_mod.additional_router) |spec| {
+ if (keys.router_value == null and scope.includesRouter(spec.id)) {
+ const stored = parsed.object.get(spec.id) orelse return;
+ if (stored == .string and stored.string.len > 0) {
+ keys.router_value = stored.string;
+ keys.router_source = .stored;
+ }
+ }
+ }
}
/// `harness key set <provider> <key>` / `harness key list` — manage the safe
-/// key store. Validates the provider id against provider_specs.
+/// key store. Validates the provider id against built-ins plus the optional
+/// workspace router.
pub fn keyCommand(io: Io, gpa: Allocator, arena: Allocator, home: []const u8, args: []const []const u8) !void {
var obuf: [4096]u8 = undefined;
var ow = Io.File.stdout().writer(io, &obuf);
@@ -234,7 +258,8 @@ pub fn keyCommand(io: Io, gpa: Allocator, arena: Allocator, home: []const u8, ar
var stored_keys: provider_mod.Keys = .{ .values = @splat(null) };
loadMissingStoredKeys(io, gpa, arena, home, &stored_keys, .all);
try out.writeAll("provider env var stored\n");
- for (provider_specs) |spec| {
+ for (0..provider_mod.specCount()) |i| {
+ const spec = provider_mod.specAt(i).?;
const stored = stored_keys.get(spec.id) != null;
try out.print(" {s:<14}{s:<22}{s}\n", .{ spec.id, spec.env_key, if (stored) "yes" else "—" });
}
@@ -249,11 +274,7 @@ pub fn keyCommand(io: Io, gpa: Allocator, arena: Allocator, home: []const u8, ar
}
const provider = args[1];
const key = args[2];
- var known = false;
- for (provider_specs) |spec| {
- if (std.mem.eql(u8, spec.id, provider)) known = true;
- }
- if (!known) {
+ if (provider_mod.specFor(provider) == null) {
try out.print("unknown provider '{s}' — see /models for valid ids\n", .{provider});
try out.flush();
return;
diff --git a/src/picker_auth.zig b/src/picker_auth.zig
index fc00fa4e..de398ac4 100644
--- a/src/picker_auth.zig
+++ b/src/picker_auth.zig
@@ -117,11 +117,7 @@ pub fn offerProviderAuth(
use_color: bool,
pick: PickerFn,
) !void {
- var spec_idx: ?usize = null;
- for (provider_specs, 0..) |spec, i| if (std.mem.eql(u8, spec.id, pid)) {
- spec_idx = i;
- };
- const si = spec_idx orelse {
+ const spec = provider_mod.specFor(pid) orelse {
try out.print("unknown provider '{s}' — see /model for the list\n", .{pid});
try out.flush();
return;
@@ -133,7 +129,7 @@ pub fn offerProviderAuth(
if (can_login)
try out.print("no key for {s} — /login {s} (OAuth) or /key {s} <key>\n", .{ pid, pid, pid })
else
- try out.print("no key for {s} — /key {s} <key> (or set {s})\n", .{ pid, pid, provider_specs[si].env_key });
+ try out.print("no key for {s} — /key {s} <key> (or set {s})\n", .{ pid, pid, spec.env_key });
try out.flush();
return;
}
@@ -203,16 +199,15 @@ pub fn offerProviderAuth(
return;
}
const dup = arena.dupe(u8, key) catch key;
- keys.values[si] = dup;
const saved = storeKey(root.io, root.gpa, arena, root.home, pid, dup);
- keys.sources[si] = if (saved) .stored else .session;
+ _ = keys.set(pid, dup, if (saved) .stored else .session);
if (std.mem.eql(u8, pid, "kimi")) _ = kimi_catalog.load(root.io, root.gpa, arena, root.home, dup);
try out.print("\xe2\x9c\x93 {s} key set (live{s})\n", .{ pid, if (saved) " + Keychain" else "" });
}
// Auth done — switch now if the key/login took, else keep the current model.
const selected_model = if (default_selection and std.mem.eql(u8, pid, "codex"))
- pricing.providerDefaultModel(pid, provider_specs[si].default_model)
+ pricing.providerDefaultModel(pid, spec.default_model)
else
model;
const provider = keys.providerById(pid, selected_model) catch {
diff --git a/src/pricing.zig b/src/pricing.zig
index 37f0a36f..52483fa2 100644
--- a/src/pricing.zig
+++ b/src/pricing.zig
@@ -329,7 +329,7 @@ pub fn providerDefaultModel(provider_id: []const u8, fallback: []const u8) []con
return fallback;
}
-fn activateProviderModels(arena: std.mem.Allocator, provider_id: []const u8, discovered: []const ModelInfo) bool {
+pub fn activateProviderModels(arena: std.mem.Allocator, provider_id: []const u8, discovered: []const ModelInfo) bool {
if (discovered.len == 0) return false;
var retained: usize = 0;
for (active_model_table) |m| if (!std.mem.eql(u8, m.provider, provider_id)) {
@@ -516,10 +516,8 @@ test "baked Codex catalog is an offline fallback, not rollout data" {
try std.testing.expect(providerModelInTable("openai", "gpt-5.6"));
}
-test "every provider default_model is catalog-present for that provider" {
- // Guards the codex/openai gpt-5.6 default flip (and any future one): a
- // provider whose default_model isn't in model_table would boot on a model
- // contextFor()/routing can't resolve.
+test "every built-in provider default_model is catalog-present for that provider" {
+ // Workspace routers are runtime configuration and are tested separately.
const specs = @import("provider.zig").provider_specs;
for (specs) |spec|
try std.testing.expect(providerModelInTable(spec.id, spec.default_model));
diff --git a/src/provider.zig b/src/provider.zig
index 933a4efd..3adc8b24 100644
--- a/src/provider.zig
+++ b/src/provider.zig
@@ -34,53 +34,78 @@ fn contextWindowFor(provider_id: []const u8, model: []const u8) u64 {
return contextFor(provider_id, model);
}
-/// 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
-/// openai bases are the canonical ones (models.dev lists them as null).
-/// minimax serves the Anthropic Messages format with bearer auth. Order is
-/// the default-provider priority at startup, and the tiebreak when one model
-/// name is served by several providers.
-const ProviderSpec = struct {
+/// One built-in or workspace-configured provider. Built-ins live in
+/// provider_specs; one additional OpenAI-compatible router may be loaded from
+/// `.graff/.config.router` at startup.
+pub const ProviderSpec = struct {
+ pub const LoginKind = enum { api_key, codegraff_device, codex_device, kimi_device };
+ pub const CatalogKind = enum { baked, codex, kimi, openai };
+
id: []const u8,
+ display_name: []const u8,
kind: Provider.Kind, // wire format
auth: Provider.Auth, // header style
url: []const u8,
env_key: []const u8,
default_model: []const u8,
+ login: LoginKind = .api_key,
+ catalog: CatalogKind = .baked,
+ models_url: []const u8 = "",
+ takes_effort: bool = false,
};
pub const provider_specs = [_]ProviderSpec{
- .{ .id = "anthropic", .kind = .anthropic, .auth = .x_api_key, .url = "https://api.anthropic.com/v1/messages", .env_key = "ANTHROPIC_API_KEY", .default_model = "claude-opus-4-8" },
- .{ .id = "codegraff", .kind = .openai, .auth = .bearer, .url = "https://gateway.codegraff.com/v1/chat/completions", .env_key = "CODEGRAFF_API_KEY", .default_model = "deepseek-v4-pro" },
- .{ .id = "deepseek", .kind = .openai, .auth = .bearer, .url = "https://api.deepseek.com/chat/completions", .env_key = "DEEPSEEK_API_KEY", .default_model = "deepseek-v4-pro" },
- .{ .id = "openai", .kind = .openai, .auth = .bearer, .url = "https://api.openai.com/v1/chat/completions", .env_key = "OPENAI_API_KEY", .default_model = "gpt-5.6" },
- .{ .id = "minimax", .kind = .anthropic, .auth = .bearer, .url = "https://api.minimax.io/anthropic/v1/messages", .env_key = "MINIMAX_API_KEY", .default_model = "MiniMax-M3" },
- .{ .id = "xiaomi", .kind = .openai, .auth = .bearer, .url = "https://api.xiaomimimo.com/v1/chat/completions", .env_key = "XIAOMI_API_KEY", .default_model = "mimo-v2.5-pro" },
+ .{ .id = "anthropic", .display_name = "Anthropic", .kind = .anthropic, .auth = .x_api_key, .url = "https://api.anthropic.com/v1/messages", .env_key = "ANTHROPIC_API_KEY", .default_model = "claude-opus-4-8" },
+ .{ .id = "codegraff", .display_name = "Codegraff", .kind = .openai, .auth = .bearer, .url = "https://gateway.codegraff.com/v1/chat/completions", .env_key = "CODEGRAFF_API_KEY", .default_model = "deepseek-v4-pro", .login = .codegraff_device, .catalog = .openai, .models_url = "https://gateway.codegraff.com/v1/models", .takes_effort = true },
+ .{ .id = "deepseek", .display_name = "DeepSeek", .kind = .openai, .auth = .bearer, .url = "https://api.deepseek.com/chat/completions", .env_key = "DEEPSEEK_API_KEY", .default_model = "deepseek-v4-pro", .takes_effort = true },
+ .{ .id = "openai", .display_name = "OpenAI", .kind = .openai, .auth = .bearer, .url = "https://api.openai.com/v1/chat/completions", .env_key = "OPENAI_API_KEY", .default_model = "gpt-5.6" },
+ .{ .id = "minimax", .display_name = "MiniMax", .kind = .anthropic, .auth = .bearer, .url = "https://api.minimax.io/anthropic/v1/messages", .env_key = "MINIMAX_API_KEY", .default_model = "MiniMax-M3" },
+ .{ .id = "xiaomi", .display_name = "Xiaomi", .kind = .openai, .auth = .bearer, .url = "https://api.xiaomimimo.com/v1/chat/completions", .env_key = "XIAOMI_API_KEY", .default_model = "mimo-v2.5-pro" },
// Kimi Code publishes the protocol per model. Missing/`kimi` is the native
// chat-completions wire; a live `protocol: anthropic` row is switched in
// Keys.build to the beta Messages endpoint + x-api-key, matching kimi-code.
- .{ .id = "kimi", .kind = .openai, .auth = .bearer, .url = kimi_native_url, .env_key = "KIMI_API_KEY", .default_model = "k3" },
+ .{ .id = "kimi", .display_name = "Kimi", .kind = .openai, .auth = .bearer, .url = kimi_native_url, .env_key = "KIMI_API_KEY", .default_model = "k3", .login = .kimi_device, .catalog = .kimi },
// moonshot: the regular Kimi Open Platform (pay-as-you-go API key, not the
// Coding plan). OpenAI-compatible; .cn host for China. kimi-latest tracks
// the newest Kimi. Same /v1/models discovery applies if wired later.
- .{ .id = "moonshot", .kind = .openai, .auth = .bearer, .url = "https://api.moonshot.ai/v1/chat/completions", .env_key = "MOONSHOT_API_KEY", .default_model = "kimi-latest" },
- .{ .id = "xai", .kind = .openai, .auth = .bearer, .url = "https://api.x.ai/v1/chat/completions", .env_key = "XAI_API_KEY", .default_model = "grok-4.3" },
- .{ .id = "zai", .kind = .openai, .auth = .bearer, .url = "https://api.z.ai/api/paas/v4/chat/completions", .env_key = "ZAI_API_KEY", .default_model = "glm-5.2" },
- .{ .id = "fugu", .kind = .openai, .auth = .bearer, .url = "https://api.sakana.ai/v1/chat/completions", .env_key = "FUGU_API_KEY", .default_model = "fugu-ultra" },
- .{ .id = "fireworks", .kind = .openai, .auth = .bearer, .url = "https://api.fireworks.ai/inference/v1/chat/completions", .env_key = "FIREWORKS_API_KEY", .default_model = "accounts/fireworks/models/deepseek-v4-pro" },
+ .{ .id = "moonshot", .display_name = "Moonshot", .kind = .openai, .auth = .bearer, .url = "https://api.moonshot.ai/v1/chat/completions", .env_key = "MOONSHOT_API_KEY", .default_model = "kimi-latest" },
+ .{ .id = "xai", .display_name = "xAI", .kind = .openai, .auth = .bearer, .url = "https://api.x.ai/v1/chat/completions", .env_key = "XAI_API_KEY", .default_model = "grok-4.3" },
+ .{ .id = "zai", .display_name = "Z.AI", .kind = .openai, .auth = .bearer, .url = "https://api.z.ai/api/paas/v4/chat/completions", .env_key = "ZAI_API_KEY", .default_model = "glm-5.2" },
+ .{ .id = "fugu", .display_name = "fugu", .kind = .openai, .auth = .bearer, .url = "https://api.sakana.ai/v1/chat/completions", .env_key = "FUGU_API_KEY", .default_model = "fugu-ultra" },
+ .{ .id = "fireworks", .display_name = "fireworks", .kind = .openai, .auth = .bearer, .url = "https://api.fireworks.ai/inference/v1/chat/completions", .env_key = "FIREWORKS_API_KEY", .default_model = "accounts/fireworks/models/deepseek-v4-pro" },
// mlx: a local model served by mlx-lm (`mlx_lm.server`) on Apple Silicon —
// OpenAI-compatible, no real key (MLX_API_KEY=local just clears graff's boot gate).
- .{ .id = "mlx", .kind = .openai, .auth = .bearer, .url = "http://127.0.0.1:8080/v1/chat/completions", .env_key = "MLX_API_KEY", .default_model = "mlx-community/Qwen3.6-27B-OptiQ-4bit" },
+ .{ .id = "mlx", .display_name = "mlx", .kind = .openai, .auth = .bearer, .url = "http://127.0.0.1:8080/v1/chat/completions", .env_key = "MLX_API_KEY", .default_model = "mlx-community/Qwen3.6-27B-OptiQ-4bit" },
// lm-studio: the LM Studio app's local OpenAI-compatible server (default :1234).
// Load a model in LM Studio, then `LMSTUDIO_API_KEY=local graff --model lmstudio`.
- .{ .id = "lmstudio", .kind = .openai, .auth = .bearer, .url = "http://127.0.0.1:1234/v1/chat/completions", .env_key = "LMSTUDIO_API_KEY", .default_model = "lmstudio" },
+ .{ .id = "lmstudio", .display_name = "lmstudio", .kind = .openai, .auth = .bearer, .url = "http://127.0.0.1:1234/v1/chat/completions", .env_key = "LMSTUDIO_API_KEY", .default_model = "lmstudio" },
// codex: ChatGPT login via the Responses API. Its "key" isn't an env var
// — it's the OAuth access token read from CODEX_HOME/auth.json at startup
// (see loadCodexAuth), the same on-disk-credential trick used for the
// codegraff gateway key in ~/forge/.credentials.json.
- .{ .id = "codex", .kind = .responses, .auth = .bearer, .url = "https://chatgpt.com/backend-api/codex/responses", .env_key = "CODEX_DISABLED", .default_model = "gpt-5.6-sol" },
+ .{ .id = "codex", .display_name = "Codex (ChatGPT)", .kind = .responses, .auth = .bearer, .url = "https://chatgpt.com/backend-api/codex/responses", .env_key = "CODEX_DISABLED", .default_model = "gpt-5.6-sol", .login = .codex_device, .catalog = .codex },
};
+/// Optional workspace-local router loaded from `.graff/.config.router`.
+/// Its strings are owned by the process arena.
+pub var additional_router: ?ProviderSpec = null;
+
+pub fn specCount() usize {
+ return provider_specs.len + @intFromBool(additional_router != null);
+}
+
+pub fn specAt(index: usize) ?ProviderSpec {
+ if (index < provider_specs.len) return provider_specs[index];
+ if (index == provider_specs.len) return additional_router;
+ return null;
+}
+
+pub fn specFor(id: []const u8) ?ProviderSpec {
+ for (provider_specs) |spec| if (std.mem.eql(u8, spec.id, id)) return spec;
+ if (additional_router) |spec| if (std.mem.eql(u8, spec.id, id)) return spec;
+ return null;
+}
+
pub const kimi_native_url = "https://api.kimi.com/coding/v1/chat/completions";
pub const kimi_anthropic_url = "https://api.kimi.com/coding/v1/messages?beta=true";
@@ -153,7 +178,8 @@ pub const Provider = struct {
/// expired ~/.codex/auth.json silently rerouted them to the gateway.
pub fn catalogProvidersFor(buf: [][]const u8, model: []const u8) [][]const u8 {
var n: usize = 0;
- for (provider_specs) |spec| {
+ for (0..specCount()) |i| {
+ const spec = specAt(i).?;
if (n >= buf.len) break;
if (!pricing.providerModelInTable(spec.id, model)) continue;
buf[n] = spec.id;
@@ -184,12 +210,16 @@ pub const Keys = struct {
values: [provider_specs.len]?[]const u8,
sources: [provider_specs.len]CredentialSource = @splat(.none),
+ router_value: ?[]const u8 = null,
+ router_source: CredentialSource = .none,
codex_account: []const u8 = "", // ChatGPT account id for the codex provider
pub fn get(keys: Keys, provider_id: []const u8) ?[]const u8 {
for (provider_specs, keys.values) |spec, value| {
if (std.mem.eql(u8, spec.id, provider_id)) return value;
}
+ if (additional_router) |spec|
+ if (std.mem.eql(u8, spec.id, provider_id)) return keys.router_value;
return null;
}
@@ -197,9 +227,28 @@ pub const Keys = struct {
for (provider_specs, keys.sources) |spec, source_value| {
if (std.mem.eql(u8, spec.id, provider_id)) return source_value;
}
+ if (additional_router) |spec|
+ if (std.mem.eql(u8, spec.id, provider_id)) return keys.router_source;
return .none;
}
+ pub fn set(keys: *Keys, provider_id: []const u8, value: []const u8, source_value: CredentialSource) bool {
+ for (provider_specs, &keys.values, &keys.sources) |spec, *slot, *source_slot| {
+ if (!std.mem.eql(u8, spec.id, provider_id)) continue;
+ slot.* = value;
+ source_slot.* = source_value;
+ return true;
+ }
+ if (additional_router) |spec| {
+ if (std.mem.eql(u8, spec.id, provider_id)) {
+ keys.router_value = value;
+ keys.router_source = source_value;
+ return true;
+ }
+ }
+ return false;
+ }
+
pub fn build(keys: Keys, spec: ProviderSpec, key: []const u8, model: []const u8) Provider {
const is_codex = std.mem.eql(u8, spec.id, "codex");
const is_kimi_anthropic = std.mem.eql(u8, spec.id, "kimi") and pricing.kimiProtocol(model) == .anthropic;
@@ -225,8 +274,9 @@ pub const Keys = struct {
// otherwise block models the user can serve with their own key. Pass 1
// skips the gateway (direct keys win); pass 2 lets it back in as fallback.
for ([_]bool{ false, true }) |allow_gateway| {
- for (provider_specs, keys.values) |spec, value| {
- const key = value orelse continue;
+ for (0..specCount()) |i| {
+ const spec = specAt(i).?;
+ const key = keys.get(spec.id) orelse continue;
if (std.mem.eql(u8, spec.id, "codegraff") != allow_gateway) continue;
for (pricing.models()) |m| {
if (std.mem.eql(u8, m.provider, spec.id) and std.mem.eql(u8, m.name, model))
@@ -247,19 +297,17 @@ pub const Keys = struct {
// which is what that fallback was always for ("any other unknown model").
if (pricing.modelInTable(model)) return error.MissingKey;
const fallback_id: []const u8 = if (std.mem.startsWith(u8, model, "claude")) "anthropic" else "codegraff";
- for (provider_specs, keys.values) |spec, value| {
- if (!std.mem.eql(u8, spec.id, fallback_id)) continue;
- const key = value orelse break;
- return keys.build(spec, key, model);
- }
- return error.MissingKey;
+ const spec = specFor(fallback_id) orelse return error.MissingKey;
+ const key = keys.get(fallback_id) orelse return error.MissingKey;
+ return keys.build(spec, key, model);
}
/// The startup default: the first provider (in spec order) with a key,
/// on its default model.
pub fn defaultProvider(keys: Keys) error{MissingKey}!Provider {
- for (provider_specs, keys.values) |spec, value| {
- const key = value orelse continue;
+ for (0..specCount()) |i| {
+ const spec = specAt(i).?;
+ const key = keys.get(spec.id) orelse continue;
return keys.build(spec, key, pricing.providerDefaultModel(spec.id, spec.default_model));
}
return error.MissingKey;
@@ -268,9 +316,8 @@ pub const Keys = struct {
/// Rebuild a provider from a saved session's (id, model). Falls back to
/// model-based routing if the id is unknown.
pub fn providerById(keys: Keys, id: []const u8, model: []const u8) error{MissingKey}!Provider {
- for (provider_specs, keys.values) |spec, value| {
- if (!std.mem.eql(u8, spec.id, id)) continue;
- const key = value orelse return error.MissingKey;
+ if (specFor(id)) |spec| {
+ const key = keys.get(id) orelse return error.MissingKey;
return keys.build(spec, key, model);
}
return keys.providerFor(model);
@@ -356,6 +403,44 @@ test "Keys.defaultProvider: first keyed provider on its default model" {
try std.testing.expectError(error.MissingKey, none.defaultProvider());
}
+test "workspace router behaves like an additional provider" {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const saved_router = additional_router;
+ const saved_models = pricing.active_model_table;
+ defer {
+ additional_router = saved_router;
+ pricing.active_model_table = saved_models;
+ }
+ additional_router = .{
+ .id = "openrouter",
+ .display_name = "OpenRouter",
+ .kind = .openai,
+ .auth = .bearer,
+ .url = "https://openrouter.ai/api/v1/chat/completions",
+ .env_key = "OPENROUTER_API_KEY",
+ .default_model = "anthropic/claude-sonnet-4",
+ .catalog = .openai,
+ .models_url = "https://openrouter.ai/api/v1/models",
+ };
+ const rows = [_]pricing.ModelInfo{
+ .{ .provider = "openrouter", .name = "anthropic/claude-sonnet-4", .context = 200_000 },
+ };
+ try std.testing.expect(pricing.activateProviderModels(arena_state.allocator(), "openrouter", &rows));
+
+ var keys: Keys = .{ .values = @splat(null) };
+ try std.testing.expect(keys.set("openrouter", "token", .session));
+ try std.testing.expectEqualStrings("token", keys.get("openrouter").?);
+ try std.testing.expectEqual(Keys.CredentialSource.session, keys.source("openrouter"));
+ const explicit = try keys.providerById("openrouter", "anthropic/claude-sonnet-4");
+ try std.testing.expectEqualStrings("https://openrouter.ai/api/v1/chat/completions", explicit.url);
+ try std.testing.expectEqualStrings("openrouter", (try keys.providerFor("anthropic/claude-sonnet-4")).id);
+ try std.testing.expectEqualStrings("openrouter", (try keys.defaultProvider()).id);
+ var ids: [provider_specs.len + 1][]const u8 = undefined;
+ const serving = catalogProvidersFor(&ids, "anthropic/claude-sonnet-4");
+ try std.testing.expectEqualStrings("openrouter", serving[0]);
+}
+
test "Keys.build: g_codex_url_override rewires only the codex endpoint" {
const all = Keys{ .values = @splat("k") };
g_codex_url_override = "http://127.0.0.1:8765/responses";
diff --git a/src/providers.zig b/src/providers.zig
index be1a63ac..0d81fe82 100644
--- a/src/providers.zig
+++ b/src/providers.zig
@@ -15,6 +15,8 @@ const Value = std.json.Value;
const pricing = @import("pricing.zig");
const resolveModelName = pricing.resolveModelName;
const kimi_catalog = @import("kimi_catalog.zig");
+const catalog_selection = @import("catalog_selection.zig");
+const router_catalog = @import("router_catalog.zig");
const serde = @import("serde.zig");
const saveModel = serde.saveModel;
@@ -135,15 +137,15 @@ fn triedProvider(ids: []const []const u8, id: []const u8) bool {
/// failed provider and wrapping once. Providers without credentials and ids
/// already attempted during this turn are skipped.
pub fn nextFallbackProvider(keys: Keys, after_id: []const u8, tried: []const []const u8, allow: []const []const u8) ?Provider {
+ const count = provider_mod.specCount();
var start: usize = 0;
- for (provider_specs, 0..) |spec, i| if (std.mem.eql(u8, spec.id, after_id)) {
- start = (i + 1) % provider_specs.len;
+ for (0..count) |i| if (std.mem.eql(u8, provider_mod.specAt(i).?.id, after_id)) {
+ start = (i + 1) % count;
break;
};
- for (0..provider_specs.len) |offset| {
- const i = (start + offset) % provider_specs.len;
- const spec = provider_specs[i];
- const key = keys.values[i] orelse continue;
+ for (0..count) |offset| {
+ const spec = provider_mod.specAt((start + offset) % count).?;
+ const key = keys.get(spec.id) orelse continue;
if (triedProvider(tried, spec.id)) continue;
if (!fallback_config.contains(allow, spec.id)) continue;
return keys.build(spec, key, pricing.providerDefaultModel(spec.id, spec.default_model));
@@ -203,7 +205,7 @@ pub fn runTurnWithFallback(root: *Agent, keys: *Keys, arena: Allocator, out: ?*I
const behavior_turn = trace.beginRootTurn(root.tracer);
defer trace.endRootTurn(root.tracer, behavior_turn);
if (root.fallback_blocked) return error.FallbackConsentRequired;
- var attempted: [provider_specs.len][]const u8 = undefined;
+ var attempted: [provider_specs.len + 1][]const u8 = undefined;
var attempted_len: usize = 1;
attempted[0] = root.provider.id;
while (true) {
@@ -267,8 +269,7 @@ pub fn resolveProviderControlRequest(
const model = std.mem.trim(u8, model_query, " \t");
if (provider_id.len != 0) {
- for (provider_specs) |spec| {
- if (!std.mem.eql(u8, spec.id, provider_id)) continue;
+ if (provider_mod.specFor(provider_id)) |spec| {
const selected_model = if (model.len == 0) pricing.providerDefaultModel(spec.id, spec.default_model) else try arena.dupe(u8, model);
if (model.len != 0 and !localProviderUrl(spec.url) and !pricing.providerModelInTable(spec.id, selected_model)) return error.InvalidModel;
return keys.providerById(spec.id, selected_model);
@@ -289,55 +290,32 @@ pub fn resolveProviderControlRequest(
/// Explicit non-Codex providers never need the dynamic catalog; bare/fuzzy
/// model queries do because they may name a new account rollout.
pub fn modelQueryMayUseCodex(query: []const u8) bool {
- const arg = std.mem.trim(u8, query, " \t");
- if (arg.len == 0) return true;
- const provider_end = std.mem.indexOfAny(u8, arg, " /\t") orelse arg.len;
- const provider_id = arg[0..provider_end];
- for (provider_specs) |spec| {
- if (!std.mem.eql(u8, spec.id, provider_id)) continue;
- return std.mem.eql(u8, spec.id, "codex");
- }
- return true;
+ return catalog_selection.queryMayUse("codex", query);
}
fn modelQueryMayUseKimi(query: []const u8) bool {
- const arg = std.mem.trim(u8, query, " \t");
- if (arg.len == 0) return true;
- const provider_end = std.mem.indexOfAny(u8, arg, " /\t") orelse arg.len;
- const provider_id = arg[0..provider_end];
- for (provider_specs) |spec| {
- if (!std.mem.eql(u8, spec.id, provider_id)) continue;
- return std.mem.eql(u8, spec.id, "kimi");
- }
- if (pricing.modelInTable(arg)) return pricing.providerModelInTable("kimi", arg);
- return true;
+ return catalog_selection.queryMayUse("kimi", query);
}
pub fn ensureModelQueryCatalogs(root: *Agent, keys: Keys, query: []const u8) void {
if (modelQueryMayUseCodex(query)) root.ensureModelCatalog(keys);
if (modelQueryMayUseKimi(query))
kimi_catalog.ensure(root.io, root.gpa, root.arena, root.home, keys.get("kimi") orelse "");
+ router_catalog.ensureForQuery(root.io, root.gpa, root.arena, root.home, keys, query);
}
/// Structured set_model has separate provider/model fields. An explicit
/// provider fully determines routing; a model-only request remains fuzzy.
pub fn controlRequestMayUseCodex(provider_query: []const u8, model_query: []const u8, legacy_name: []const u8) bool {
- const provider_id = std.mem.trim(u8, provider_query, " \t");
- if (provider_id.len != 0) return std.mem.eql(u8, provider_id, "codex");
- if (std.mem.trim(u8, model_query, " \t").len != 0) return true;
- return modelQueryMayUseCodex(legacy_name);
+ return modelQueryMayUseCodex(catalog_selection.controlQuery(provider_query, model_query, legacy_name));
}
pub fn ensureControlRequestCatalogs(root: *Agent, keys: Keys, provider_query: []const u8, model_query: []const u8, legacy_name: []const u8) void {
if (controlRequestMayUseCodex(provider_query, model_query, legacy_name)) root.ensureModelCatalog(keys);
- const query = if (std.mem.trim(u8, provider_query, " \t").len != 0)
- provider_query
- else if (std.mem.trim(u8, model_query, " \t").len != 0)
- model_query
- else
- legacy_name;
+ const query = catalog_selection.controlQuery(provider_query, model_query, legacy_name);
if (modelQueryMayUseKimi(query))
kimi_catalog.ensure(root.io, root.gpa, root.arena, root.home, keys.get("kimi") orelse "");
+ router_catalog.ensureForQuery(root.io, root.gpa, root.arena, root.home, keys, query);
}
fn resolveProviderRequest(keys: *Keys, arena: Allocator, query: []const u8) !Provider {
@@ -347,16 +325,15 @@ fn resolveProviderRequest(keys: *Keys, arena: Allocator, query: []const u8) !Pro
if (std.mem.indexOfAny(u8, arg, " /\t")) |i| {
const pid = arg[0..i];
const mdl = std.mem.trim(u8, arg[i + 1 ..], " \t");
- for (provider_specs) |spec| {
- if (!std.mem.eql(u8, spec.id, pid) or mdl.len == 0) continue;
+ if (provider_mod.specFor(pid)) |spec| {
+ if (mdl.len == 0) return error.InvalidModel;
if (!localProviderUrl(spec.url) and !pricing.providerModelInTable(pid, mdl)) return error.InvalidModel;
const m = try arena.dupe(u8, mdl);
return keys.providerById(pid, m);
}
}
- for (provider_specs) |spec| {
- if (!std.mem.eql(u8, spec.id, arg)) continue;
+ if (provider_mod.specFor(arg)) |spec| {
return keys.providerById(spec.id, pricing.providerDefaultModel(spec.id, spec.default_model));
}
diff --git a/src/router_catalog.zig b/src/router_catalog.zig
new file mode 100644
index 00000000..5fe1186e
--- /dev/null
+++ b/src/router_catalog.zig
@@ -0,0 +1,312 @@
+//! Model discovery for Codegraff 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.
+
+const std = @import("std");
+const Io = std.Io;
+const Allocator = std.mem.Allocator;
+const Value = std.json.Value;
+
+const catalog_selection = @import("catalog_selection.zig");
+const pricing = @import("pricing.zig");
+const provider = @import("provider.zig");
+const serde = @import("serde.zig");
+const util = @import("util.zig");
+
+/// Router catalogs change on the order of weeks; favour instant startup.
+const cache_ttl_ms: i64 = 6 * 60 * 60 * 1000;
+var attempted: [provider.provider_specs.len]bool = @splat(false);
+var additional_attempted = false;
+
+const Snapshot = struct {
+ models: []const pricing.ModelInfo,
+ fetched_at_ms: i64 = 0,
+};
+
+fn isAdditional(spec: provider.ProviderSpec) bool {
+ return if (provider.additional_router) |configured|
+ std.mem.eql(u8, configured.id, spec.id)
+ else
+ false;
+}
+
+fn dirPath(arena: Allocator, home: []const u8, spec: provider.ProviderSpec) []const u8 {
+ if (isAdditional(spec)) return ".graff/.models.router";
+ if (home.len == 0) return "";
+ return std.fmt.allocPrint(arena, "{s}/.codegraff/{s}-models.json", .{ home, spec.id }) catch "";
+}
+
+fn flatPath(arena: Allocator, home: []const u8, spec: provider.ProviderSpec) []const u8 {
+ if (isAdditional(spec) or home.len == 0) return "";
+ return std.fmt.allocPrint(arena, "{s}/.codegraff-{s}-models.json", .{ home, spec.id }) catch "";
+}
+
+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(1024 * 1024)) catch null;
+}
+
+pub fn modelsUrl(spec: provider.ProviderSpec) []const u8 {
+ return if (spec.catalog == .openai) spec.models_url else "";
+}
+
+fn validModelId(id: []const u8) bool {
+ if (id.len == 0 or id.len > 256) return false;
+ for (id) |c| if (!(std.ascii.isAlphanumeric(c) or std.mem.indexOfScalar(u8, "-_./:@+", c) != null)) return false;
+ return true;
+}
+
+fn positiveInt(obj: std.json.ObjectMap, name: []const u8) u64 {
+ const value = obj.get(name) orelse return 0;
+ return switch (value) {
+ .integer => |i| if (i > 0) @intCast(i) else 0,
+ .float => |f| if (f > 0) @intFromFloat(f) else 0,
+ else => 0,
+ };
+}
+
+fn boolField(obj: std.json.ObjectMap, name: []const u8) bool {
+ const value = obj.get(name) orelse return false;
+ return value == .bool and value.bool;
+}
+
+fn listsReasoning(obj: std.json.ObjectMap) bool {
+ const params = obj.get("supported_parameters") orelse return false;
+ if (params != .array) return false;
+ for (params.array.items) |param| {
+ if (param == .string and std.mem.eql(u8, param.string, "reasoning")) return true;
+ }
+ return false;
+}
+
+/// Accept the common OpenAI `/models` shape and this module's compact cache
+/// shape. `provider_id` is data, so the parser is reusable by every router.
+pub fn parseModels(arena: Allocator, provider_id: []const u8, data: []const u8) ?Snapshot {
+ const value = std.json.parseFromSliceLeaky(Value, arena, data, .{ .allocate = .alloc_always }) catch return null;
+ if (value != .object) return null;
+ const items = value.object.get("data") orelse value.object.get("models") orelse return null;
+ if (items != .array) return null;
+ var rows: std.ArrayList(pricing.ModelInfo) = .empty;
+ for (items.array.items) |item| {
+ if (item != .object) continue;
+ const id = util.strFieldObj(item.object, "id") orelse util.strFieldObj(item.object, "name") orelse continue;
+ if (!validModelId(id)) continue;
+ var duplicate = false;
+ for (rows.items) |row| if (std.mem.eql(u8, row.name, id)) {
+ duplicate = true;
+ };
+ if (duplicate) continue;
+ var context = positiveInt(item.object, "context_length");
+ if (context == 0) context = positiveInt(item.object, "context");
+ if (context == 0) context = pricing.default_context;
+ rows.append(arena, .{
+ .provider = provider_id,
+ .name = arena.dupe(u8, id) catch continue,
+ .context = context,
+ .supports_reasoning = listsReasoning(item.object) or boolField(item.object, "supports_reasoning"),
+ }) catch continue;
+ }
+ const owned = rows.toOwnedSlice(arena) catch return null;
+ if (owned.len == 0) return null;
+ return .{
+ .models = owned,
+ .fetched_at_ms = switch (value.object.get("fetched_at_ms") orelse Value{ .null = {} }) {
+ .integer => |i| i,
+ else => 0,
+ },
+ };
+}
+
+fn fetch(io: Io, gpa: Allocator, arena: Allocator, spec: provider.ProviderSpec, key: []const u8) ?Snapshot {
+ const url = modelsUrl(spec);
+ if (url.len == 0) return null;
+ var client: std.http.Client = .{ .allocator = gpa, .io = io };
+ defer client.deinit();
+ var aw: Io.Writer.Allocating = .init(arena);
+ const bearer = std.fmt.allocPrint(arena, "Bearer {s}", .{key}) catch return null;
+ const headers = [_]std.http.Header{
+ .{ .name = "Accept", .value = "application/json" },
+ .{ .name = "Authorization", .value = bearer },
+ };
+ 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 parseModels(arena, spec.id, aw.writer.buffered());
+}
+
+fn writeCache(io: Io, arena: Allocator, home: []const u8, spec: provider.ProviderSpec, models: []const pricing.ModelInfo) void {
+ var aw: Io.Writer.Allocating = .init(arena);
+ aw.writer.writeAll("{\"source\":") catch return;
+ var stringify: std.json.Stringify = .{ .writer = &aw.writer };
+ stringify.write(spec.models_url) catch return;
+ aw.writer.print(",\"fetched_at_ms\":{d},\"models\":[", .{util.unixMs(io)}) catch return;
+ for (models, 0..) |model, i| {
+ if (i > 0) aw.writer.writeByte(',') catch return;
+ aw.writer.writeAll("{\"name\":") catch return;
+ stringify.write(model.name) catch return;
+ aw.writer.print(",\"context\":{d},\"supports_reasoning\":{}}}", .{ model.context, model.supports_reasoning }) catch return;
+ }
+ aw.writer.writeAll("]}\n") catch return;
+ for ([_][]const u8{ dirPath(arena, home, spec), flatPath(arena, home, spec) }) |path| {
+ if (path.len == 0) continue;
+ const file = Io.Dir.cwd().createFile(io, path, .{}) catch continue;
+ defer file.close(io);
+ var buffer: [4096]u8 = undefined;
+ var writer = file.writer(io, &buffer);
+ writer.interface.writeAll(aw.writer.buffered()) catch continue;
+ writer.interface.flush() catch continue;
+ return;
+ }
+}
+
+fn cachedSnapshot(io: Io, arena: Allocator, home: []const u8, spec: provider.ProviderSpec) ?Snapshot {
+ const data = readSmall(io, arena, dirPath(arena, home, spec)) orelse
+ readSmall(io, arena, flatPath(arena, home, spec)) orelse return null;
+ const value = std.json.parseFromSliceLeaky(Value, arena, data, .{ .allocate = .alloc_always }) catch return null;
+ if (value != .object) return null;
+ if (util.strFieldObj(value.object, "source")) |source|
+ if (!std.mem.eql(u8, source, spec.models_url)) return null;
+ return parseModels(arena, spec.id, data);
+}
+
+/// Activate one router's catalog. Fresh cache short-circuits the network; stale
+/// cache remains an offline fallback. No failure is fatal.
+fn loadSpec(io: Io, gpa: Allocator, arena: Allocator, home: []const u8, spec: provider.ProviderSpec, key: []const u8, force_refresh: bool) bool {
+ if (spec.catalog != .openai or key.len == 0) return false;
+ const cached = cachedSnapshot(io, arena, home, spec);
+ if (!force_refresh) if (cached) |snapshot| {
+ const age = util.unixMs(io) - snapshot.fetched_at_ms;
+ if (age >= 0 and age <= cache_ttl_ms and pricing.activateProviderModels(arena, spec.id, snapshot.models)) return true;
+ };
+ if (fetch(io, gpa, arena, spec, key)) |snapshot| {
+ if (pricing.activateProviderModels(arena, spec.id, snapshot.models)) {
+ if (home.len != 0 or isAdditional(spec)) writeCache(io, arena, home, spec, snapshot.models);
+ return true;
+ }
+ }
+ if (cached) |snapshot| return pricing.activateProviderModels(arena, spec.id, snapshot.models);
+ return 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;
+ attempted[index] = true;
+ _ = loadSpec(io, gpa, arena, home, provider.provider_specs[index], key, false);
+}
+
+fn ensureAdditional(io: Io, gpa: Allocator, arena: Allocator, home: []const u8, keys: provider.Keys) void {
+ if (additional_attempted) return;
+ 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);
+}
+
+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 (spec.catalog != .openai or !catalog_selection.startupMayUse(keys, spec.id, model_flag, saved)) continue;
+ ensureAt(io, gpa, arena, home, index, keys.get(spec.id) orelse "");
+ }
+ if (provider.additional_router) |spec|
+ if (catalog_selection.startupMayUse(keys, spec.id, model_flag, saved))
+ ensureAdditional(io, gpa, arena, home, keys);
+}
+
+pub 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 (spec.catalog != .openai or !catalog_selection.queryMayUse(spec.id, query)) continue;
+ ensureAt(io, gpa, arena, home, index, keys.get(spec.id) orelse "");
+ }
+ if (provider.additional_router) |spec|
+ if (catalog_selection.queryMayUse(spec.id, query))
+ ensureAdditional(io, gpa, arena, home, keys);
+}
+
+pub fn loadAll(io: Io, gpa: Allocator, arena: Allocator, home: []const u8, keys: provider.Keys, force_refresh: bool) void {
+ for (provider.provider_specs, 0..) |spec, index| {
+ if (spec.catalog != .openai) continue;
+ attempted[index] = true;
+ _ = loadSpec(io, gpa, arena, home, spec, keys.get(spec.id) orelse "", force_refresh);
+ }
+ if (provider.additional_router) |spec| {
+ additional_attempted = true;
+ _ = loadSpec(io, gpa, arena, home, spec, keys.get(spec.id) orelse "", force_refresh);
+ }
+}
+
+/// Activate previous-run caches without credentials or network. `--schema`
+/// uses this so GUI model metadata follows router rollouts.
+pub fn loadCachedAll(io: Io, arena: Allocator, home: []const u8) void {
+ for (provider.provider_specs) |spec| {
+ if (spec.catalog != .openai) continue;
+ const snapshot = cachedSnapshot(io, arena, home, spec) orelse continue;
+ _ = pricing.activateProviderModels(arena, spec.id, snapshot.models);
+ }
+ if (provider.additional_router) |spec| {
+ const snapshot = cachedSnapshot(io, arena, home, spec) orelse return;
+ _ = pricing.activateProviderModels(arena, spec.id, snapshot.models);
+ }
+}
+
+test "OpenAI catalog configuration carries its models endpoint" {
+ const spec = provider.specFor("codegraff") orelse return error.TestUnexpectedResult;
+ try std.testing.expectEqual(provider.ProviderSpec.CatalogKind.openai, spec.catalog);
+ try std.testing.expectEqualStrings("https://gateway.codegraff.com/v1/models", modelsUrl(spec));
+ for (provider.provider_specs) |candidate| {
+ if (candidate.catalog != .openai) continue;
+ try std.testing.expect(candidate.kind == .openai);
+ try std.testing.expect(candidate.models_url.len != 0);
+ }
+}
+
+test "parseModels is reusable for a newly configured router" {
+ var state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer state.deinit();
+ const snapshot = parseModels(state.allocator(), "new-router",
+ \\{"object":"list","data":[
+ \\ {"id":"glm-5.2","context_length":1000000,"supported_parameters":["reasoning","tools"]},
+ \\ {"id":"openai/gpt-oss:free","context_length":131072},
+ \\ {"id":"no-window"},
+ \\ {"id":"glm-5.2","context_length":128000},
+ \\ {"id":"bad id!","context_length":999}
+ \\]}
+ ) orelse return error.TestUnexpectedResult;
+ try std.testing.expectEqual(@as(usize, 3), snapshot.models.len);
+ try std.testing.expectEqualStrings("new-router", snapshot.models[0].provider);
+ try std.testing.expectEqual(@as(u64, 1_000_000), snapshot.models[0].context);
+ try std.testing.expect(snapshot.models[0].supports_reasoning);
+ try std.testing.expectEqualStrings("openai/gpt-oss:free", snapshot.models[1].name);
+ try std.testing.expectEqual(pricing.default_context, snapshot.models[2].context);
+}
+
+test "parseModels round-trips the generic cache shape" {
+ var state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer state.deinit();
+ const snapshot = parseModels(state.allocator(), "router",
+ \\{"fetched_at_ms":1700000000000,
+ \\ "models":[{"name":"minimax-m3","context":1000000,"supports_reasoning":true}]}
+ ) orelse return error.TestUnexpectedResult;
+ try std.testing.expectEqual(@as(i64, 1_700_000_000_000), snapshot.fetched_at_ms);
+ try std.testing.expectEqualStrings("router", snapshot.models[0].provider);
+ try std.testing.expect(snapshot.models[0].supports_reasoning);
+}
+
+test "router discovery replaces only its provider slice" {
+ const saved = pricing.active_model_table;
+ defer pricing.active_model_table = saved;
+ var state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer state.deinit();
+ const discovered = [_]pricing.ModelInfo{
+ .{ .provider = "codegraff", .name = "kimi-k3", .context = 1_048_576 },
+ };
+ try std.testing.expect(pricing.activateProviderModels(state.allocator(), "codegraff", &discovered));
+ try std.testing.expect(pricing.providerModelInTable("codegraff", "kimi-k3"));
+ try std.testing.expect(!pricing.providerModelInTable("codegraff", "claude-opus-4.8"));
+ try std.testing.expect(pricing.providerModelInTable("anthropic", "claude-opus-4-8"));
+ try std.testing.expect(pricing.providerModelInTable("codex", "gpt-5.6-sol"));
+}
diff --git a/src/router_config.zig b/src/router_config.zig
new file mode 100644
index 00000000..359572da
--- /dev/null
+++ b/src/router_config.zig
@@ -0,0 +1,168 @@
+//! Workspace-local OpenAI-compatible router configuration.
+//!
+//! `.graff/.config.router` contains endpoint metadata only. Credentials stay
+//! in the named environment variable or Graff's existing secure key store.
+
+const std = @import("std");
+const Io = std.Io;
+const Allocator = std.mem.Allocator;
+const Value = std.json.Value;
+
+const provider = @import("provider.zig");
+const pricing = @import("pricing.zig");
+
+pub const path = ".graff/.config.router";
+
+pub const Error = error{
+ InvalidJson,
+ ExpectedObject,
+ MissingId,
+ MissingBaseUrl,
+ MissingEnvKey,
+ MissingDefaultModel,
+ InvalidId,
+ DuplicateId,
+ InvalidBaseUrl,
+ InvalidEnvKey,
+ InvalidDefaultModel,
+ InvalidName,
+ InlineSecret,
+};
+
+fn stringField(object: std.json.ObjectMap, name: []const u8) ?[]const u8 {
+ const value = object.get(name) orelse return null;
+ return if (value == .string) value.string else null;
+}
+
+fn validId(id: []const u8) bool {
+ if (id.len == 0 or id.len > 48 or !std.ascii.isAlphanumeric(id[0])) return false;
+ for (id) |c| if (!(std.ascii.isAlphanumeric(c) or c == '-' or c == '_')) return false;
+ return true;
+}
+
+fn validEnvKey(key: []const u8) bool {
+ if (key.len == 0 or key.len > 128 or !(std.ascii.isAlphabetic(key[0]) or key[0] == '_')) return false;
+ for (key) |c| if (!(std.ascii.isAlphanumeric(c) or c == '_')) return false;
+ return true;
+}
+
+fn validModel(model: []const u8) bool {
+ if (model.len == 0 or model.len > 256) return false;
+ for (model) |c| if (std.ascii.isWhitespace(c) or c < 0x20 or c == 0x7f) return false;
+ return true;
+}
+
+fn validBaseUrl(url: []const u8) bool {
+ if (url.len == 0 or url.len > 2048) return false;
+ const scheme_len: usize = if (std.mem.startsWith(u8, url, "https://"))
+ "https://".len
+ else if (std.mem.startsWith(u8, url, "http://"))
+ "http://".len
+ else
+ return false;
+ if (url.len <= scheme_len or url[scheme_len] == '/' or std.mem.indexOfAny(u8, url, "?#") != null) return false;
+ for (url) |c| if (std.ascii.isWhitespace(c) or c < 0x20 or c == 0x7f) return false;
+ return true;
+}
+
+fn validName(name: []const u8) bool {
+ if (name.len == 0 or name.len > 128) return false;
+ for (name) |c| if (c < 0x20 or c == 0x7f) return false;
+ return true;
+}
+
+pub fn parse(arena: Allocator, data: []const u8) (Error || Allocator.Error)!provider.ProviderSpec {
+ const value = std.json.parseFromSliceLeaky(Value, arena, data, .{ .allocate = .alloc_always }) catch
+ return error.InvalidJson;
+ if (value != .object) return error.ExpectedObject;
+ if (value.object.get("api_key") != null or value.object.get("key") != null or value.object.get("token") != null)
+ return error.InlineSecret;
+ const id = stringField(value.object, "id") orelse return error.MissingId;
+ const base_value = stringField(value.object, "base_url") orelse return error.MissingBaseUrl;
+ const env_key = stringField(value.object, "env_key") orelse return error.MissingEnvKey;
+ const default_model = stringField(value.object, "default_model") orelse return error.MissingDefaultModel;
+ if (!validId(id)) return error.InvalidId;
+ for (provider.provider_specs) |spec|
+ if (std.mem.eql(u8, spec.id, id)) return error.DuplicateId;
+ if (!validBaseUrl(base_value)) return error.InvalidBaseUrl;
+ if (!validEnvKey(env_key)) return error.InvalidEnvKey;
+ if (!validModel(default_model)) return error.InvalidDefaultModel;
+
+ const base_url = std.mem.trimEnd(u8, base_value, "/");
+ const display_name = stringField(value.object, "name") orelse id;
+ if (!validName(display_name)) return error.InvalidName;
+ const takes_effort = if (value.object.get("takes_effort")) |field|
+ field == .bool and field.bool
+ else
+ false;
+ return .{
+ .id = try arena.dupe(u8, id),
+ .display_name = try arena.dupe(u8, display_name),
+ .kind = .openai,
+ .auth = .bearer,
+ .url = try std.fmt.allocPrint(arena, "{s}/chat/completions", .{base_url}),
+ .env_key = try arena.dupe(u8, env_key),
+ .default_model = try arena.dupe(u8, default_model),
+ .catalog = .openai,
+ .models_url = try std.fmt.allocPrint(arena, "{s}/models", .{base_url}),
+ .takes_effort = takes_effort,
+ };
+}
+
+/// Load the optional project router. A missing file is normal; malformed
+/// configuration is returned so startup can explain it instead of ignoring it.
+pub fn load(io: Io, arena: Allocator) !void {
+ const data = Io.Dir.cwd().readFileAlloc(io, path, arena, .limited(64 * 1024)) catch |err| switch (err) {
+ error.FileNotFound => {
+ provider.additional_router = null;
+ return;
+ },
+ else => return err,
+ };
+ const spec = try parse(arena, data);
+ provider.additional_router = spec;
+ const fallback = [_]pricing.ModelInfo{.{
+ .provider = spec.id,
+ .name = spec.default_model,
+ .context = pricing.default_context,
+ .supports_reasoning = spec.takes_effort,
+ }};
+ _ = pricing.activateProviderModels(arena, spec.id, &fallback);
+}
+
+test "parse derives OpenAI-compatible endpoints without accepting a secret" {
+ var state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer state.deinit();
+ const spec = try parse(state.allocator(),
+ \\{
+ \\ "id": "openrouter",
+ \\ "name": "OpenRouter",
+ \\ "base_url": "https://openrouter.ai/api/v1/",
+ \\ "env_key": "OPENROUTER_API_KEY",
+ \\ "default_model": "anthropic/claude-sonnet-4",
+ \\ "takes_effort": true
+ \\}
+ );
+ try std.testing.expectEqualStrings("openrouter", spec.id);
+ try std.testing.expectEqualStrings("https://openrouter.ai/api/v1/chat/completions", spec.url);
+ try std.testing.expectEqualStrings("https://openrouter.ai/api/v1/models", spec.models_url);
+ try std.testing.expect(spec.takes_effort);
+}
+
+test "parse rejects collisions and malformed router fields" {
+ var state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer state.deinit();
+ const allocator = state.allocator();
+ try std.testing.expectError(error.DuplicateId, parse(allocator,
+ \\{"id":"openai","base_url":"https://example.com/v1","env_key":"KEY","default_model":"m"}
+ ));
+ try std.testing.expectError(error.InvalidBaseUrl, parse(allocator,
+ \\{"id":"custom","base_url":"file:///tmp","env_key":"KEY","default_model":"m"}
+ ));
+ try std.testing.expectError(error.InvalidEnvKey, parse(allocator,
+ \\{"id":"custom","base_url":"https://example.com/v1","env_key":"BAD-KEY","default_model":"m"}
+ ));
+ try std.testing.expectError(error.InlineSecret, parse(allocator,
+ \\{"id":"custom","base_url":"https://example.com/v1","env_key":"KEY","default_model":"m","api_key":"secret"}
+ ));
+}
diff --git a/src/schema.zig b/src/schema.zig
index b5bf60c3..17113ed7 100644
--- a/src/schema.zig
+++ b/src/schema.zig
@@ -2,7 +2,7 @@
//! catalog, the per-provider tool-array renderers (anthropic/openai/responses),
//! and emitSchema (the --schema / `graff serve` /v1/schema document). Split out
//! of main.zig (#123). Back-imports main for Provider (.Kind) and the
-//! provider_specs catalog; pulls model_table straight from pricing.zig. main
+//! provider catalog and the active model table. main
//! re-exports emitSchema + schema_version so serve.zig stays untouched.
const std = @import("std");
@@ -12,13 +12,11 @@ const Allocator = std.mem.Allocator;
const mcp = @import("mcp.zig");
const pricing = @import("pricing.zig");
-const model_table = pricing.model_table;
const learn_store = @import("learn_store.zig");
const root = @import("main.zig");
const provider_mod = @import("provider.zig");
const Provider = provider_mod.Provider;
-const provider_specs = provider_mod.provider_specs;
/// Documentation of the `--json` stdio protocol, embedded verbatim in
/// `--schema` output so SDK generators/users know the request/event contract.
@@ -390,28 +388,14 @@ pub const schema_version = "0.8"; // #276 P0-3: subagent gained run_in_backgroun
/// Human-facing provider name for the `--schema` providers array (consumed by
/// the GUI settings page so its provider list stays tied to the harness).
fn providerDisplayName(id: []const u8) []const u8 {
- const names = .{
- .{ "codegraff", "Codegraff" }, .{ "anthropic", "Anthropic" },
- .{ "deepseek", "DeepSeek" }, .{ "openai", "OpenAI" },
- .{ "minimax", "MiniMax" }, .{ "xiaomi", "Xiaomi" },
- .{ "kimi", "Kimi" }, .{ "xai", "xAI" },
- .{ "moonshot", "Moonshot" }, .{ "zai", "Z.AI" },
- .{ "codex", "Codex (ChatGPT)" },
- };
- inline for (names) |n| {
- if (std.mem.eql(u8, id, n[0])) return n[1];
- }
- return id;
+ return if (provider_mod.specFor(id)) |spec| spec.display_name else id;
}
/// How a provider's credential is acquired, for the GUI settings page:
/// `codegraff`/`codex` use device/OAuth login flows; everything else is a
/// drop-in API key (env var or `graff key set <id>`).
fn providerLoginKind(id: []const u8) []const u8 {
- if (std.mem.eql(u8, id, "codegraff")) return "codegraff_device";
- if (std.mem.eql(u8, id, "codex")) return "codex_device";
- if (std.mem.eql(u8, id, "kimi")) return "kimi_device";
- return "api_key";
+ return if (provider_mod.specFor(id)) |spec| @tagName(spec.login) else "api_key";
}
/// Whether a model exposes a user-selectable reasoning effort. Kimi maps the
@@ -425,8 +409,7 @@ pub fn providerTakesEffort(kind: Provider.Kind, id: []const u8, model: []const u
if (std.mem.startsWith(u8, model, "grok")) return false;
return kind == .responses or
(std.mem.eql(u8, id, "kimi") and pricing.kimiSupportsThinking(model)) or
- std.mem.eql(u8, id, "codegraff") or
- std.mem.eql(u8, id, "deepseek");
+ (if (provider_mod.specFor(id)) |spec| spec.takes_effort else false);
}
pub fn emitSchema(w: *Io.Writer) !void {
@@ -438,12 +421,13 @@ pub fn emitSchema(w: *Io.Writer) !void {
try s.write(schema_version);
try s.objectField("providers");
try s.beginArray();
- for (provider_specs) |p| {
+ for (0..provider_mod.specCount()) |i| {
+ const p = provider_mod.specAt(i).?;
try s.beginObject();
try s.objectField("id");
try s.write(p.id);
try s.objectField("name");
- try s.write(providerDisplayName(p.id));
+ try s.write(p.display_name);
try s.objectField("kind");
try s.write(@tagName(p.kind));
try s.objectField("auth");
@@ -451,10 +435,10 @@ pub fn emitSchema(w: *Io.Writer) !void {
try s.objectField("env_key");
try s.write(p.env_key);
try s.objectField("login");
- try s.write(providerLoginKind(p.id));
+ try s.write(@tagName(p.login));
try s.objectField("default_model");
try s.write(p.default_model);
- if (std.mem.eql(u8, p.id, "kimi")) {
+ if (p.catalog == .kimi) {
try s.objectField("protocol_source");
try s.write("live_model_catalog");
try s.objectField("anthropic_auth");
@@ -465,7 +449,7 @@ pub fn emitSchema(w: *Io.Writer) !void {
try s.endArray();
try s.objectField("models");
try s.beginArray();
- for (model_table) |m| {
+ for (pricing.models()) |m| {
try s.beginObject();
try s.objectField("provider");
try s.write(m.provider);
@@ -478,8 +462,10 @@ pub fn emitSchema(w: *Io.Writer) !void {
try s.endArray();
try s.objectField("dynamic_model_providers");
try s.beginArray();
- try s.write("codex");
- try s.write("kimi");
+ for (0..provider_mod.specCount()) |i| {
+ const p = provider_mod.specAt(i).?;
+ if (p.catalog != .baked) try s.write(p.id);
+ }
try s.endArray();
try s.objectField("tools");
try s.beginArray();
diff --git a/src/startup.zig b/src/startup.zig
index 397aac95..01217fed 100644
--- a/src/startup.zig
+++ b/src/startup.zig
@@ -34,6 +34,9 @@ const oauth = @import("oauth.zig");
const pricing = @import("pricing.zig");
const models_cache = @import("models_cache.zig");
const kimi_catalog = @import("kimi_catalog.zig");
+const catalog_selection = @import("catalog_selection.zig");
+const router_config = @import("router_config.zig");
+const router_catalog = @import("router_catalog.zig");
const subagent_selection = @import("subagent_selection.zig");
const serde = @import("serde.zig");
const skills = @import("skills.zig");
@@ -50,10 +53,7 @@ pub const ResolvedKeys = struct {
};
fn explicitProvider(model_flag: ?[]const u8) ?[]const u8 {
- const query = model_flag orelse return null;
- for (provider_mod.provider_specs) |spec|
- if (std.mem.eql(u8, spec.id, query)) return spec.id;
- return null;
+ return catalog_selection.explicitProvider(model_flag orelse return null);
}
/// Whether one stored credential can affect an explicit startup selection.
@@ -74,48 +74,13 @@ fn hasSelectiveStoredKeyScope(model_flag: ?[]const u8) bool {
fn startupStoredKeyScope(model_flag: ?[]const u8, selective: bool) keys_cli.StoredKeyScope {
if (!selective) return .all;
+ if (explicitProvider(model_flag)) |id| return .{ .provider = id };
var mask: [provider_mod.provider_specs.len]bool = @splat(false);
for (provider_mod.provider_specs, 0..) |spec, i|
mask[i] = storedKeyMayAffectSelection(spec.id, model_flag);
return .{ .mask = mask };
}
-fn startupNeedsCodexCatalog(keys: provider_mod.Keys, model_flag: ?[]const u8, saved: ?serde.SavedModel) bool {
- if (keys.get("codex") == null) return false;
- if (model_flag) |query| {
- for (provider_mod.provider_specs) |spec| if (std.mem.eql(u8, spec.id, query))
- return std.mem.eql(u8, spec.id, "codex");
- // A free-form query may name an account-only rollout.
- return true;
- }
- if (saved) |selection| {
- if (std.mem.eql(u8, selection.pid, "codex")) return true;
- if (pricing.providerModelInTable(selection.pid, selection.model) and keys.get(selection.pid) != null) return false;
- // A stale/keyless preference may fall through to Codex.
- return true;
- }
- const fallback = keys.defaultProvider() catch return false;
- return std.mem.eql(u8, fallback.id, "codex");
-}
-
-fn startupNeedsKimiCatalog(keys: provider_mod.Keys, model_flag: ?[]const u8, saved: ?serde.SavedModel) bool {
- if (keys.get("kimi") == null) return false;
- if (model_flag) |query| {
- if (explicitProvider(query)) |id| return std.mem.eql(u8, id, "kimi");
- if (pricing.modelInTable(query)) return pricing.providerModelInTable("kimi", query);
- // A free-form query may name an account-only rollout.
- return true;
- }
- if (saved) |selection| {
- if (std.mem.eql(u8, selection.pid, "kimi")) return true;
- if (pricing.providerModelInTable(selection.pid, selection.model) and keys.get(selection.pid) != null) return false;
- // A stale/keyless preference may fall through to Kimi.
- return true;
- }
- const fallback = keys.defaultProvider() catch return false;
- return std.mem.eql(u8, fallback.id, "kimi");
-}
-
pub const resolveSubagentProvider = subagent_selection.resolveSubagentProvider;
test "Codex catalog loads at startup only when selection can observe it" {
@@ -139,22 +104,22 @@ test "Codex catalog loads at startup only when selection can observe it" {
}
keys.codex_account = "account";
- try std.testing.expect(!startupNeedsCodexCatalog(keys, "deepseek", null));
- try std.testing.expect(startupNeedsCodexCatalog(keys, "codex", null));
- try std.testing.expect(startupNeedsCodexCatalog(keys, "future-account-rollout", null));
- try std.testing.expect(!startupNeedsCodexCatalog(keys, null, .{ .pid = "deepseek", .model = "deepseek-v4-pro" }));
- try std.testing.expect(!startupNeedsCodexCatalog(keys, null, null));
+ try std.testing.expect(!catalog_selection.startupMayUse(keys, "codex", "deepseek", null));
+ try std.testing.expect(catalog_selection.startupMayUse(keys, "codex", "codex", null));
+ try std.testing.expect(catalog_selection.startupMayUse(keys, "codex", "future-account-rollout", null));
+ try std.testing.expect(!catalog_selection.startupMayUse(keys, "codex", null, .{ .pid = "deepseek", .model = "deepseek-v4-pro" }));
+ try std.testing.expect(!catalog_selection.startupMayUse(keys, "codex", null, null));
for (provider_mod.provider_specs, &keys.values) |spec, *value| {
if (std.mem.eql(u8, spec.id, "deepseek")) value.* = null;
}
- try std.testing.expect(startupNeedsCodexCatalog(keys, null, null));
- try std.testing.expect(startupNeedsCodexCatalog(keys, null, .{ .pid = "deepseek", .model = "deepseek-v4-pro" }));
+ try std.testing.expect(catalog_selection.startupMayUse(keys, "codex", null, null));
+ try std.testing.expect(catalog_selection.startupMayUse(keys, "codex", null, .{ .pid = "deepseek", .model = "deepseek-v4-pro" }));
for (provider_mod.provider_specs, &keys.values) |spec, *value| {
if (std.mem.eql(u8, spec.id, "codex")) value.* = null;
}
- try std.testing.expect(!startupNeedsCodexCatalog(keys, "codex", null));
+ try std.testing.expect(!catalog_selection.startupMayUse(keys, "codex", "codex", null));
}
test "Kimi catalog loads at startup only when selection can observe it" {
@@ -162,12 +127,12 @@ test "Kimi catalog loads at startup only when selection can observe it" {
for (provider_mod.provider_specs, &keys.values) |spec, *value| {
if (std.mem.eql(u8, spec.id, "kimi") or std.mem.eql(u8, spec.id, "codegraff")) value.* = "token";
}
- try std.testing.expect(!startupNeedsKimiCatalog(keys, "codegraff", null));
- try std.testing.expect(startupNeedsKimiCatalog(keys, "kimi", null));
- try std.testing.expect(startupNeedsKimiCatalog(keys, "k3", null));
- try std.testing.expect(startupNeedsKimiCatalog(keys, "future-kimi-rollout", null));
- try std.testing.expect(!startupNeedsKimiCatalog(keys, null, .{ .pid = "codegraff", .model = "deepseek-v4-pro" }));
- try std.testing.expect(startupNeedsKimiCatalog(keys, null, .{ .pid = "kimi", .model = "k3" }));
+ try std.testing.expect(!catalog_selection.startupMayUse(keys, "kimi", "codegraff", null));
+ try std.testing.expect(catalog_selection.startupMayUse(keys, "kimi", "kimi", null));
+ try std.testing.expect(catalog_selection.startupMayUse(keys, "kimi", "k3", null));
+ try std.testing.expect(catalog_selection.startupMayUse(keys, "kimi", "future-kimi-rollout", null));
+ try std.testing.expect(!catalog_selection.startupMayUse(keys, "kimi", null, .{ .pid = "codegraff", .model = "deepseek-v4-pro" }));
+ try std.testing.expect(catalog_selection.startupMayUse(keys, "kimi", null, .{ .pid = "kimi", .model = "k3" }));
}
/// Resolves API keys/credentials (env vars → codegraff/codex/kimi on-disk
@@ -183,6 +148,10 @@ pub fn resolveKeys(io: Io, gpa: Allocator, arena: Allocator, environ_map: anytyp
value.* = environ_map.get(spec.env_key);
source.* = if (value.* != null) .environment else .none;
}
+ if (provider_mod.additional_router) |spec| {
+ keys.router_value = environ_map.get(spec.env_key);
+ keys.router_source = if (keys.router_value != null) .environment else .none;
+ }
// Codegraff "login": if CODEGRAFF_API_KEY isn't set, pick up a key from
// `harness login codegraff` (~/.simple-harness-codegraff.json) or graff's
// own store (~/forge/.credentials.json) — read-only, env always wins.
@@ -259,10 +228,11 @@ pub fn resolveKeys(io: Io, gpa: Allocator, arena: Allocator, environ_map: anytyp
// Dynamic Codex discovery is observable only when startup may select
// Codex. Explicit/saved non-Codex launches defer the version subprocess,
// native-cache parse, and possible refresh until a model surface needs it.
- if (startupNeedsCodexCatalog(keys, model_flag, saved_model))
+ if (catalog_selection.startupMayUse(keys, "codex", model_flag, saved_model))
model_catalog.ensure(io, gpa, arena, home, keys.get("codex") orelse "", keys.codex_account);
- if (startupNeedsKimiCatalog(keys, model_flag, saved_model))
+ if (catalog_selection.startupMayUse(keys, "kimi", model_flag, saved_model))
kimi_catalog.ensure(io, gpa, arena, home, keys.get("kimi") orelse "");
+ router_catalog.ensureForStartup(io, gpa, arena, home, keys, model_flag, saved_model);
if (home.len != 0) {
// Apply the independent models.dev price/context overlay after routing
// discovery. Provider-specific Codex windows remain authoritative.
@@ -281,20 +251,20 @@ pub fn resolveKeys(io: Io, gpa: Allocator, arena: Allocator, environ_map: anytyp
var preferred_provider: ?[]const u8 = null;
// `--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 (provider_mod.specFor(mname)) |spec| {
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});
- };
+ }
const nm = pricing.resolveModelName(keys, mname) orelse std.process.fatal("unknown --model '{s}' — run `graff models refresh` or see /models", .{mname});
default_provider = keys.providerFor(nm) catch {
// #294: name the credential that actually needs repair. A Codex-only
// model with an expired ~/.codex/auth.json used to be rerouted to the
// gateway and surface as a CodeGraff error; now it fails here, so the
// message must point at the right login rather than "see /models".
- var pbuf: [provider_mod.provider_specs.len][]const u8 = undefined;
+ var pbuf: [provider_mod.provider_specs.len + 1][]const u8 = undefined;
const serving = provider_mod.catalogProvidersFor(&pbuf, nm);
if (serving.len > 0) std.process.fatal(
"'{s}' is served by {s}, which has no valid credential — run `graff login {s}` or `graff key set {s} <key>`",
@@ -318,11 +288,9 @@ pub fn resolveKeys(io: Io, gpa: Allocator, arena: Allocator, environ_map: anytyp
// A rollout may remove only this model while the provider login is
// still healthy. Prefer that provider's current dynamic default
// before crossing provider/account boundaries.
- for (provider_mod.provider_specs) |spec| {
- if (!std.mem.eql(u8, spec.id, saved.pid)) continue;
+ if (provider_mod.specFor(saved.pid)) |spec| {
const replacement = pricing.providerDefaultModel(spec.id, spec.default_model);
if (keys.providerById(spec.id, replacement)) |p| default_provider = p else |_| {}
- break;
}
}
}
@@ -415,6 +383,8 @@ pub fn runSubcommand(io: Io, gpa: Allocator, arena: Allocator, init: std.process
try hw.interface.flush();
return true;
}
+ router_config.load(io, arena) catch |err|
+ std.process.fatal("invalid {s}: {s}", .{ router_config.path, @errorName(err) });
// `harness key set <provider> <key>` / `harness key list`: safe key store
// (macOS Keychain, else a 0600 file). Exits after.
@@ -524,6 +494,10 @@ pub fn runSubcommand(io: Io, gpa: Allocator, arena: Allocator, init: std.process
const codex_home = init.environ_map.get("CODEX_HOME") orelse
(std.fmt.allocPrint(arena, "{s}/.codex", .{home}) catch "");
const codex_auth = oauth.loadCodexAuthFrom(io, arena, codex_home);
+ const refreshing = 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"));
models_cache.loadCodexCatalog(
io,
gpa,
@@ -532,20 +506,35 @@ pub fn runSubcommand(io: Io, gpa: Allocator, arena: Allocator, init: std.process
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")),
+ refreshing,
);
const 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 (spec.catalog != .openai) 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);
+ }
+ if (provider_mod.additional_router) |spec| {
+ router_keys.router_value = init.environ_map.get(spec.env_key) orelse
+ keys_cli.loadStoredKey(io, arena, home, spec.id);
+ router_keys.router_source = if (router_keys.router_value != null) .stored else .none;
+ }
+ router_catalog.loadAll(io, gpa, arena, home, router_keys, refreshing);
try models_cache.command(io, gpa, arena, home, flags.positionals.items[1..]);
return true;
}
- // `--schema`: print the machine-readable interface and exit. No keys,
- // network, or MCP — so it works anywhere (CI codegen calls this).
+ // `--schema`: print the machine-readable interface and exit. Still no keys,
+ // network, or MCP — so it works anywhere (CI codegen calls this). The one
+ // reads are router catalog caches a normal run already wrote: the GUI
+ // builds its model picker from this output, so without it the picker shows
+ // a release-old snapshot of a list the gateway changes on its own schedule.
+ // No cache (CI, fresh install) → the baked table, byte-identical to before.
if (flags.schema_flag) {
+ router_catalog.loadCachedAll(io, arena, keys_cli.homeEnv(init.environ_map) orelse "");
var sbuf: [8 * 1024]u8 = undefined;
var sw = Io.File.stdout().writer(io, &sbuf);
try schema.emitSchema(&sw.interface);
diff --git a/src/subagent_selection.zig b/src/subagent_selection.zig
index b89af288..ef239c06 100644
--- a/src/subagent_selection.zig
+++ b/src/subagent_selection.zig
@@ -18,10 +18,7 @@ pub const Error = error{
};
fn knownProvider(id: []const u8) bool {
- for (provider_mod.provider_specs) |spec| {
- if (std.mem.eql(u8, spec.id, id)) return true;
- }
- return false;
+ return provider_mod.specFor(id) != null;
}
fn modelForProvider(provider_id: []const u8, query: []const u8) ?[]const u8 {