Skip to content

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

Python

feat(models): signed-in plan seats sit above paid ones in /models (#596)

Rach4ba84b34749f
diff --git a/TUI/models.zig b/TUI/models.zig
index 29c6cf6d..692c63ea 100644
--- a/TUI/models.zig
+++ b/TUI/models.zig
@@ -6,6 +6,7 @@ const app = @import("app.zig");
const engine = @import("engine.zig");
const panel = @import("panel.zig");
const theme_mod = @import("theme.zig");
+const models_rank = @import("models_rank");
const Model = app.Model;
pub const max_models = 256;
@@ -83,23 +84,16 @@ fn nameScore(name: []const u8, query: []const u8) i32 {
return -len_pen;
}
-/// Rank a keyed plan above a metered/reseller hit. "5.6 sol" with a Codex
-/// login should land on `gpt-5.6-sol` / codex, not openai or a gateway slug.
+/// Rank a keyed plan above a metered/reseller hit. Same `electionRank` the
+/// line-REPL `/model` picker and `/models` table use — an empty query is
+/// still an election, not catalog order. "5.6 sol" with a Codex login
+/// lands on `gpt-5.6-sol` / codex, not openai or a gateway slug.
fn entryScore(e: engine.ModelEntry, query: []const u8) i32 {
- var s: i32 = nameScore(e.name, query);
- if (e.has_key) s += 1_000_000;
- s += switch (e.cost) {
- .plan => 400_000,
- .local => 300_000,
- .credits => 200_000,
- .api => 0,
- };
- return s;
+ return nameScore(e.name, query) + models_rank.electionRank(e.has_key, e.cost);
}
-/// Keep the catalog rows matching `query`. An empty query stays in catalog
-/// order (the map of what exists). A typed query ranks: keyed plan first,
-/// then tighter name match, then original order.
+/// Keep the catalog rows matching `query`, ranked: keyed plan first, then
+/// local, then credits, then api; a typed query adds the name score.
pub fn filterModels(list: []const engine.ModelEntry, query: []const u8, out: []engine.ModelEntry) usize {
var tmp: [max_models]Ranked = undefined;
var k: usize = 0;
@@ -107,10 +101,10 @@ pub fn filterModels(list: []const engine.ModelEntry, query: []const u8, out: []e
if (e.name.len == 0) continue;
if (!entryMatch(e, query)) continue;
if (k >= tmp.len) break;
- tmp[k] = .{ .e = e, .score = if (query.len == 0) 0 else entryScore(e, query), .idx = i };
+ tmp[k] = .{ .e = e, .score = entryScore(e, query), .idx = i };
k += 1;
}
- if (query.len > 0) std.mem.sort(Ranked, tmp[0..k], {}, rankedLess);
+ std.mem.sort(Ranked, tmp[0..k], {}, rankedLess);
const n = @min(k, out.len);
for (0..n) |i| out[i] = tmp[i].e;
return n;
@@ -357,12 +351,21 @@ test "a 5.6 sol search ranks keyed Codex above openai and a gateway slug" {
try std.testing.expectEqualStrings("openai/gpt-5.6-sol", buf[1].name);
}
-test "an empty query keeps catalog order" {
+test "an empty query ranks signed-in plan above credits above api" {
+ // Catalog order is openai / codegraff / keyless-codex / fireworks / keyed-codex.
+ // Opening /models with a Codex login should put that plan on top, not
+ // leave it at the bake position under Codegraff.
var buf: [8]engine.ModelEntry = undefined;
const n = filterModels(&sample, "", &buf);
try std.testing.expectEqual(@as(usize, 5), n);
- try std.testing.expectEqualStrings("aaa", buf[0].name);
- try std.testing.expectEqualStrings("gpt-5.6", buf[4].name);
+ try std.testing.expectEqualStrings("gpt-5.6", buf[0].name);
+ try std.testing.expectEqualStrings("codex", buf[0].provider);
+ try std.testing.expect(buf[0].has_key);
+ try std.testing.expectEqualStrings("bbb", buf[1].name);
+ try std.testing.expectEqualStrings("codegraff", buf[1].provider);
+ try std.testing.expectEqualStrings("aaa", buf[2].name);
+ try std.testing.expectEqualStrings("ccc", buf[4].name);
+ try std.testing.expect(!buf[4].has_key);
}
/// `line` with its SGR sequences removed, written into `buf`. The padding is
diff --git a/build.zig b/build.zig
index 7856dcb9..ae4ded6e 100644
--- a/build.zig
+++ b/build.zig
@@ -54,11 +54,20 @@ pub fn build(b: *std.Build) void {
// standalone graff-repl exe below). The repo's first dependency.
const zigzag = b.dependency("zigzag", .{ .target = target, .optimize = optimize });
exe.root_module.addImport("zigzag", zigzag.module("zigzag"));
+ // Shared by the line-REPL picker and the TUI overlay so they cannot
+ // drift: a file import from both modules is illegal in Zig 0.17.
+ const models_rank_mod = b.createModule(.{
+ .root_source_file = b.path("src/models_rank.zig"),
+ .target = target,
+ .optimize = optimize,
+ });
+ exe.root_module.addImport("models_rank", models_rank_mod);
const tui_mod = b.createModule(.{
.root_source_file = b.path("TUI/root.zig"),
.target = target,
.optimize = optimize,
});
+ tui_mod.addImport("models_rank", models_rank_mod);
exe.root_module.addImport("tui", tui_mod);
const install_graff = b.addInstallArtifact(exe, .{});
b.getInstallStep().dependOn(&install_graff.step);
@@ -90,6 +99,7 @@ pub fn build(b: *std.Build) void {
});
unit_tests.root_module.addOptions("build_options", opts);
unit_tests.root_module.addImport("zigzag", zigzag.module("zigzag"));
+ unit_tests.root_module.addImport("models_rank", models_rank_mod);
unit_tests.root_module.addImport("tui", tui_mod);
// spec/ fixtures live outside src/; importing them here makes @embedFile
// legal and rebuilds the suite when the exported semantics change.
@@ -180,6 +190,7 @@ pub fn build(b: *std.Build) void {
.strip = lean_release,
}),
});
+ tui_exe.root_module.addImport("models_rank", models_rank_mod);
b.installArtifact(tui_exe);
const tui_tests = b.addTest(.{
@@ -196,6 +207,7 @@ pub fn build(b: *std.Build) void {
// be runnable on its own, ReleaseFast, without the rest of the suite.
.filters = test_filters,
});
+ tui_tests.root_module.addImport("models_rank", models_rank_mod);
tui_tests.root_module.addAnonymousImport("spec_terminal_modes", .{ .root_source_file = b.path("spec/kernels/terminal_modes.json") });
const tui_test_step = b.step("tui-test", "Run fullscreen TUI unit tests");
diff --git a/docs/adr/0017-model-election-ranks-signed-in-plans-first.md b/docs/adr/0017-model-election-ranks-signed-in-plans-first.md
new file mode 100644
index 00000000..223de53f
--- /dev/null
+++ b/docs/adr/0017-model-election-ranks-signed-in-plans-first.md
@@ -0,0 +1,36 @@
+# 0017. Model election ranks signed-in plans first
+
+Status: accepted 2026-08-21
+
+## Context
+
+The same model is often three seats: Codex (a ChatGPT plan), Codegraff
+(gateway credits), and a metered vendor key. Opening `/models` (TUI
+overlay; line-REPL table) used to walk `pricing.models()` in catalog
+order, so a signed-in Codex row sat wherever the bake put it — often
+below Codegraff. The TUI picker already preferred plan once the user
+typed; the empty list and the line-REPL dump did not. Two ranking
+functions (TUI `CostClass` weights vs REPL `sub_login`) were a drift
+waiting to happen.
+
+## Decision
+
+One rank, in `src/models_rank.zig`, imported as the `models_rank` build
+module (Zig 0.17 will not let the harness and TUI file-import the same
+source). Both frontends call it:
+
+1. a credential beats no credential (a signed-in paid seat is usable;
+ an unsigned plan is only a map entry);
+2. then plan, then local, then credits, then api;
+3. then catalog index.
+
+Empty query and typed query share (1) and (2). A typed query adds the
+existing name/fuzzy score on top. Do not hide unpaid rows.
+
+## Consequences
+
+The empty `/models` list is no longer "the map of what exists" in
+catalog order; it is an election. Catalog order remains the tie-break
+and the source of the rows. Revisit if a user needs a stable
+alphabetical or provider-grouped dump — that would be a separate
+command or a sort toggle, not a silent revert of this rank.
diff --git a/docs/adr/README.md b/docs/adr/README.md
index 764c44cd..6cf44511 100644
--- a/docs/adr/README.md
+++ b/docs/adr/README.md
@@ -27,6 +27,7 @@ record only when you need the evidence or the edge cases.
| [0014](0014-session-resume-carries-the-room-cursor.md) | `/resume` restores the peer-channel byte cursor and inbox; it does not replay the room into history. |
| [0015](0015-ask-user-images-are-a-follow-up-user-message.md) | `ask_user` images ride a follow-up user message after the text tool result; Responses/OpenAI tool output stays text-only. |
| [0016](0016-line-repl-is-a-working-block.md) | Line REPL chrome is a `WORKING` block plus a bare `›`; tool fan-out is a tree, never `✓ bash`. |
+| [0017](0017-model-election-ranks-signed-in-plans-first.md) | `/model` and `/models` on both frontends rank signed-in plan seats above credits and metered keys (`src/models_rank.zig`). |
## When to write one
diff --git a/scripts/test-tui-model-picker.py b/scripts/test-tui-model-picker.py
index 78d2fa3e..c2709c5d 100755
--- a/scripts/test-tui-model-picker.py
+++ b/scripts/test-tui-model-picker.py
@@ -195,9 +195,19 @@ def check(h):
if badge not in ("plan", "credits", "api", "local"):
return f"a picker row has no cost badge: {row!r}"
+ # Signed-in plan seats sit above credits / api on the empty list (ADR 0017).
+ badges_in_order = [seat(r)[2] for r in rows]
+ if "plan" in badges_in_order and "credits" in badges_in_order:
+ if badges_in_order.index("plan") > badges_in_order.index("credits"):
+ return f"signed-in plan seats sit below credits\n{chr(10).join(rows)}"
+
# (4) a provider with no credential keeps its rows, marked rather than gone.
- if not any(r.rstrip().endswith("\u2014") for r in rows):
- return f"no keyless row is marked\n{chr(10).join(rows)}"
+ # Keyed plan/credits now fill the first page, so filter to a keyless
+ # provider instead of requiring an em-dash on the resting window.
+ close_picker(h)
+ bare = open_picker(h, b"anthropic")
+ if not any(r.rstrip().endswith("\u2014") for r in bare):
+ return f"no keyless row is marked\n{chr(10).join(bare)}"
# (2) THE report: one model, three providers, three different bills, and
# three rows a human can tell apart.
close_picker(h)
diff --git a/src/commands_misc.zig b/src/commands_misc.zig
index 347f12d3..ebae797f 100644
--- a/src/commands_misc.zig
+++ b/src/commands_misc.zig
@@ -34,7 +34,6 @@ const jobs = @import("jobs.zig");
const mcp_schema_gate = @import("mcp_schema_gate.zig"); // #416: which listed MCP tools are still schema-deferred
const subagent = @import("subagent.zig"); // #276 P0-3: g_agent_jobs, for /jobs
-const billing = @import("billing.zig");
const models_table = @import("models_table.zig");
test { // main.zig is the test root, so this reference is what runs its tests
@@ -383,15 +382,7 @@ pub fn tryHandle(root: *Agent, keys: *Keys, arena: Allocator, line: []const u8,
// (plan), codegraff (credits) and openai (api) is three different
// bills. Same wording as the TUI picker; the surfaces must agree.
try out.writeAll(models_table.header);
- for (pricing.models()) |m| try models_table.writeRow(out, .{
- .name = m.name,
- .context = pricing.contextFor(m.provider, m.name),
- .provider = m.provider,
- .cost = billing.costFor(m.provider, keys.source(m.provider)).badge(),
- .has_key = keys.get(m.provider) != null,
- .vision = visionModel(m.name),
- .current = std.mem.eql(u8, m.name, root.provider.model) and std.mem.eql(u8, m.provider, root.provider.id),
- });
+ try models_table.writeRows(out, arena, pricing.models(), keys.*, root.provider.model, root.provider.id, visionModel);
try out.print("(codex catalog: {s})\n", .{models_cache.codex_catalog_source});
try out.print("(kimi catalog: {s})\n", .{kimi_catalog.catalog_source});
if (pricing_db.source.len != 0) try out.print("(price db: {s})\n", .{pricing_db.source});
diff --git a/src/models_rank.zig b/src/models_rank.zig
new file mode 100644
index 00000000..1ccca674
--- /dev/null
+++ b/src/models_rank.zig
@@ -0,0 +1,41 @@
+//! Shared election rank for the model picker and the `/models` listing.
+//!
+//! Line REPL `/model`, line REPL `/models`, and the TUI `/model` overlay
+//! (`/models` is an alias there) all rank seats through this module so a
+//! signed-in plan (Codex, SuperGrok, Kimi) cannot sit below a paid seat
+//! (Codegraff credits, a metered vendor key) on one surface and above it
+//! on the other. Wired as the `models_rank` build import — a file import
+//! from both the harness and TUI modules is illegal in Zig 0.17. The
+//! class itself is `billing.CostClass`; this module is only the order.
+
+const std = @import("std");
+
+pub const Class = enum { plan, local, credits, api };
+
+/// Map a `billing.CostClass` / TUI `engine.CostClass` / `.plan` literal.
+pub fn from(cost: anytype) Class {
+ return std.meta.stringToEnum(Class, @tagName(cost)) orelse .api;
+}
+
+/// Higher wins. A credential is the first cut — a signed-in Codegraff
+/// seat is usable and an unsigned Codex seat is not — then the bill:
+/// plan, then a machine-local server, then gateway credits, then a
+/// metered API key. Catalog index is the tie-break, applied by the
+/// caller so a stable empty-query list does not reshuffle every render.
+pub fn electionRank(has_key: bool, cost: anytype) i32 {
+ const keyed: i32 = if (has_key) 1_000_000 else 0;
+ const seat: i32 = switch (from(cost)) {
+ .plan => 400_000,
+ .local => 300_000,
+ .credits => 200_000,
+ .api => 0,
+ };
+ return keyed + seat;
+}
+
+pub const Scored = struct { idx: usize, score: i32 };
+
+pub fn scoredLess(_: void, a: Scored, b: Scored) bool {
+ if (a.score != b.score) return a.score > b.score;
+ return a.idx < b.idx;
+}
diff --git a/src/models_table.zig b/src/models_table.zig
index 94b88086..2853bb00 100644
--- a/src/models_table.zig
+++ b/src/models_table.zig
@@ -4,10 +4,18 @@
//! 80-column budget is something a test can hold us to. The `cost` column is
//! the point: `/models` used to say WHICH provider serves a model but not what
//! that seat costs, and the TUI picker did not even say the provider — the two
-//! surfaces now print the same provider and the same badge.
+//! surfaces now print the same provider and the same badge. Row order is the
+//! shared election (`models_rank.zig`): signed-in plan, then local, then
+//! credits, then api.
const std = @import("std");
const Io = std.Io;
+const Allocator = std.mem.Allocator;
+
+const billing = @import("billing.zig");
+const models_rank = @import("models_rank");
+const pricing = @import("pricing.zig");
+const provider_mod = @import("provider.zig");
pub const header = "model ctx compact@ provider cost key vision\n";
const row_fmt = "{s:<24} {d:>5}k {d:>5}k {s:<10} {s:<7} {s} {s}{s}\n";
@@ -24,6 +32,43 @@ pub const Row = struct {
current: bool = false,
};
+/// Catalog rows in election order. The TUI overlay ranks the same way
+/// through `models_rank.electionRank`; this is the dump that has to agree.
+pub fn writeRows(
+ out: *Io.Writer,
+ alloc: Allocator,
+ models: []const pricing.ModelInfo,
+ keys: provider_mod.Keys,
+ current_model: []const u8,
+ current_provider: []const u8,
+ is_vision: *const fn ([]const u8) bool,
+) !void {
+ const ranked = try alloc.alloc(models_rank.Scored, models.len);
+ defer alloc.free(ranked);
+ for (models, 0..) |m, i| {
+ ranked[i] = .{
+ .idx = i,
+ .score = models_rank.electionRank(
+ keys.get(m.provider) != null,
+ billing.costFor(m.provider, keys.source(m.provider)),
+ ),
+ };
+ }
+ std.mem.sort(models_rank.Scored, ranked, {}, models_rank.scoredLess);
+ for (ranked) |r| {
+ const m = models[r.idx];
+ try writeRow(out, .{
+ .name = m.name,
+ .context = pricing.contextFor(m.provider, m.name),
+ .provider = m.provider,
+ .cost = billing.costFor(m.provider, keys.source(m.provider)).badge(),
+ .has_key = keys.get(m.provider) != null,
+ .vision = is_vision(m.name),
+ .current = std.mem.eql(u8, m.name, current_model) and std.mem.eql(u8, m.provider, current_provider),
+ });
+ }
+}
+
pub fn writeRow(out: *Io.Writer, r: Row) !void {
try out.print(row_fmt, .{
r.name,
@@ -116,3 +161,33 @@ test "a keyless row is marked, not dropped" {
try std.testing.expect(std.mem.indexOf(u8, line, "—") != null);
try std.testing.expect(std.mem.indexOf(u8, line, "✓") == null);
}
+
+test "electionRank: a signed-in plan outranks credits and a metered key" {
+ const rank = models_rank.electionRank;
+ try std.testing.expect(rank(true, .plan) > rank(true, .local));
+ try std.testing.expect(rank(true, .local) > rank(true, .credits));
+ try std.testing.expect(rank(true, .credits) > rank(true, .api));
+ // Unsigned Codex is a map entry; keyed Codegraff is a seat.
+ try std.testing.expect(rank(true, .credits) > rank(false, .plan));
+}
+
+test "writeRows puts a signed-in Codex plan above Codegraff credits" {
+ var keys: provider_mod.Keys = .{ .values = @splat(null) };
+ _ = keys.set("codex", "tok", .login);
+ _ = keys.set("codegraff", "cg", .login);
+ const models = [_]pricing.ModelInfo{
+ .{ .provider = "codegraff", .name = "gpt-5.6", .context = 200_000 },
+ .{ .provider = "codex", .name = "gpt-5.6", .context = 200_000 },
+ };
+ var buf: [512]u8 = undefined;
+ var w: Io.Writer = .fixed(&buf);
+ try writeRows(&w, std.testing.allocator, &models, keys, "", "", struct {
+ fn v(_: []const u8) bool {
+ return false;
+ }
+ }.v);
+ const out = w.buffered();
+ const plan = std.mem.indexOf(u8, out, "codex") orelse return error.MissingPlan;
+ const credits = std.mem.indexOf(u8, out, "codegraff") orelse return error.MissingCredits;
+ try std.testing.expect(plan < credits);
+}
diff --git a/src/pickers.zig b/src/pickers.zig
index 30fb3cd0..dae31274 100644
--- a/src/pickers.zig
+++ b/src/pickers.zig
@@ -16,6 +16,8 @@ const term = @import("term.zig");
const tty = term.tty;
const pricing = @import("pricing.zig");
+const billing = @import("billing.zig");
+const models_rank = @import("models_rank");
const main_mod = @import("main.zig");
const agent_mod = @import("agent.zig");
@@ -251,25 +253,18 @@ pub fn modelPicker(root: *Agent, keys: *Keys, arena: Allocator, out: *Io.Writer)
while (true) {
const layout = modelPickerLayout(term.termRows(), term.termCols());
filtered.clearRetainingCapacity();
- // Two passes: models whose provider has a key/login first, so the
- // initial selection (and Enter) lands on something usable; keyless
- // rows trail with their ·no key tag. Within each pass the best
- // fuzzy match ranks first (ties keep table order).
- for ([2]bool{ true, false }) |want_keyed| {
- scored.clearRetainingCapacity();
- for (model_table, 0..) |m, i| {
- if ((keys.get(m.provider) != null) != want_keyed) continue;
- if (pickScore(.{ .name = m.name, .desc = m.provider }, query.items)) |s| {
- const plan: i32 = if (provider_mod.specFor(m.provider)) |spec|
- @as(i32, @intFromBool(spec.sub_login)) * 400_000
- else
- 0;
- scored.append(arena, .{ .idx = i, .score = s + plan }) catch {};
- }
+ scored.clearRetainingCapacity();
+ // Same election as the TUI overlay and `/models` (models_rank.zig):
+ // keyed plan, then local, then credits, then api; keyless rows trail.
+ for (model_table, 0..) |m, i| {
+ if (pickScore(.{ .name = m.name, .desc = m.provider }, query.items)) |s| {
+ const has_key = keys.get(m.provider) != null;
+ const seat = billing.costFor(m.provider, keys.source(m.provider));
+ scored.append(arena, .{ .idx = i, .score = s + models_rank.electionRank(has_key, seat) }) catch {};
}
- std.mem.sort(Scored, scored.items, {}, scoredLess);
- for (scored.items) |s| filtered.append(arena, s.idx) catch {};
}
+ std.mem.sort(Scored, scored.items, {}, scoredLess);
+ for (scored.items) |s| filtered.append(arena, s.idx) catch {};
if (filtered.items.len == 0) sel = 0 else if (sel >= filtered.items.len) sel = filtered.items.len - 1;
if (select_current) {
for (filtered.items, 0..) |model_idx, row| {