Skip to content

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

Python

v0.0.193: REPL UX handoff — credential sources, Codex catalog state, WebSocket/SSE/fallback, context limits, pickers, spinner, narrow-terminal, model preference, fallback PTY tests

Codegraff413536a5e8c5
diff --git a/TODO.md b/TODO.md
index 37e2d7cc..fc782096 100644
--- a/TODO.md
+++ b/TODO.md
@@ -1,7 +1,8 @@
# v0.0.193 handoff
-This release branch is intentionally unfinished. Do not tag or publish it until
-the remaining UX work and the full CI suite pass.
+The planned REPL UX hardening is implemented and the full local CI-equivalent
+suite passes. The newest changes are still local: review and commit them before
+updating the draft PR. Do not tag or publish without an explicit release request.
## Implemented
@@ -15,28 +16,37 @@ the remaining UX work and the full CI suite pass.
and preference recovery coverage.
- `/key <provider> <secret>` is masked while typed and excluded from both live
and persisted input history; legacy leaked key commands are filtered on load.
-- Initial cross-provider fallback allowlist storage/filtering and persistent
- provider/fallback prompt badges.
-
-## Finish in this order
-
-1. Complete the fallback-consent UX: add `/fallback` show/allow/remove/off,
- block an unallowlisted startup fallback before any prompt is sent, and carry
- the allowlist/state through `graff repl`, JSON, and one-shot modes.
-2. Reject unknown model names before `switchProvider` saves them as the default.
-3. Make model/settings pickers responsive to terminal rows/columns and initially
- highlight the current value.
-4. Generate `/help` from the same command registry as the bare `/` menu.
-5. Add `/models health` with unified env/Keychain/OAuth availability and recent
- fallback/failure state.
-6. Normalize prompt context units and clarify full context versus compact-at.
+- Cross-provider fallback is opt-in per workspace through `/fallback`; an
+ unallowlisted startup fallback is blocked before a prompt can reach it.
+- Unknown remote model names are rejected before switching or changing the
+ saved default. Explicit local LM Studio/MLX model IDs remain supported.
+- Model and settings pickers resize to the live terminal and initially select
+ the current value.
+- `/help`, the bare `/` menu, and tab completion share `command_catalog.zig`.
+- `/models health` reports active/saved model state, context/compaction limits,
+ credential source (never value), Codex catalog source/count, WebSocket→SSE
+ status, and fallback policy.
+- Prompt context is unambiguous (`used/full ctx (% · compact@limit)`) and token
+ counts are compacted to readable units.
+- API-key entry is hidden in both `/key` and the model picker's auth flow.
+
+## Remaining release handoff
+
+1. Review the local diff and commit only the tracked implementation files plus
+ `src/command_catalog.zig` and this handoff.
+2. Push `release/v0.0.193` to update draft PR #141.
+3. Run hosted checks. Tag/publish only after explicit approval.
## Validation state
-- `zig build test --summary all`: 147/147 passed before handoff.
-- The last combined PTY command was interrupted; rerun all PTY tests. Prompt
- expectations likely need the new provider and `Fallback` badges added.
-- Rerun JSON controls, SDK generation drift, formatting, and `git diff --check`.
+- `zig build test --summary all`: 150/150 passed.
+- `scripts/test-json-controls.py`: 19/19 passed.
+- `scripts/test-pty-spinner.py`: passed in repo, home, and `/tmp` cwd variants.
+- `scripts/test-pty-repl.py`: passed, including 44×12 responsive pickers,
+ secret masking/history, generated help, and `/models health`.
+- `scripts/test-pty-markdown.py`: passed.
+- `scripts/test-model-preference.py`: passed.
+- `zig build` and `git diff --check`: passed.
- No release tag, GitHub release, or deployment has been created.
## Scope warning
diff --git a/scripts/test-model-preference.py b/scripts/test-model-preference.py
index 8a24d84f..730c704d 100755
--- a/scripts/test-model-preference.py
+++ b/scripts/test-model-preference.py
@@ -109,22 +109,34 @@ def main() -> None:
cursor = len(session.raw)
session.send_line("/model codex")
session.wait_for_literal("switched to gpt-5.6-sol via codex", start=cursor)
- session.wait_for_literal("[gpt-5.6-sol · Medium · cwd", start=cursor)
+ session.wait_for_literal("[gpt-5.6-sol · Medium · codex · cwd", start=cursor)
clean_exit(session)
preference = home / ".simple-harness-model"
assert preference.read_text(encoding="utf-8") == "codex\ngpt-5.6-sol\n"
- # Missing Codex credentials use a working configured provider for this
- # session without replacing the saved preference.
+ # Missing Codex credentials select a fallback but do not send anything
+ # across providers until the workspace explicitly allowlists it.
with launch(str(cwd), env, codex_home=None) as session:
- session.wait_for_literal("saved preference kept")
- session.wait_for_literal("[deepseek-v4-pro · Medium · cwd")
+ session.wait_for_literal("Cross-provider use is blocked")
+ session.wait_for_literal("[deepseek-v4-pro · Medium · codegraff · Fallback · cwd")
+ cursor = len(session.raw)
+ session.send_line("must not reach a provider")
+ session.wait_for_literal("requires explicit consent", start=cursor)
+ cursor = len(session.raw)
+ session.send_line("/fallback allow codegraff")
+ session.wait_for_literal("cross-provider fallback allowed: codegraff", start=cursor)
clean_exit(session)
assert preference.read_text(encoding="utf-8") == "codex\ngpt-5.6-sol\n"
+ # With explicit consent persisted, the same fallback is ready for use.
+ with launch(str(cwd), env, codex_home=None) as session:
+ session.wait_for_literal("saved preference kept")
+ session.wait_for_literal("[deepseek-v4-pro · Medium · codegraff · Fallback · cwd")
+ clean_exit(session)
+
# Once credentials return, the preferred model is selected again.
with launch(str(cwd), env, codex_home=str(codex_home)) as session:
- session.wait_for_literal("[gpt-5.6-sol · Medium · cwd")
+ session.wait_for_literal("[gpt-5.6-sol · Medium · codex · cwd")
clean_exit(session)
# A removed rollout stays on the selected provider when that login is
@@ -141,7 +153,7 @@ def main() -> None:
)
with launch(str(cwd), env, codex_home=str(codex_home)) as session:
session.wait_for_literal("saved preference kept")
- session.wait_for_literal("[gpt-5.6-luna · Medium · cwd")
+ session.wait_for_literal("[gpt-5.6-luna · Medium · codex · Fallback · cwd")
clean_exit(session)
assert preference.read_text(encoding="utf-8") == "codex\ngpt-5.6-sol\n"
diff --git a/scripts/test-pty-repl.py b/scripts/test-pty-repl.py
index 8624d3c5..28cf5234 100755
--- a/scripts/test-pty-repl.py
+++ b/scripts/test-pty-repl.py
@@ -45,13 +45,38 @@ def main() -> None:
if color_bytes is not None and color_bytes not in bytes(session.raw[cursor:]):
raise AssertionError(f"missing colored badge {color_bytes!r} after {line}")
- base = "deepseek-v4-pro · Extra high"
+ base = "deepseek-v4-pro · Extra high · codegraff"
command(
"/effort xhigh",
"reasoning effort: Extra high",
f"[{base} · cwd {tmp}]",
b"\x1b[35mExtra high\x1b[0m",
)
+ command(
+ "/model definitely-not-a-model",
+ "unknown model 'definitely-not-a-model'",
+ f"[{base} · cwd {tmp}]",
+ None,
+ )
+ cursor = len(session.raw)
+ session.send_line("/help")
+ session.wait_for_literal("/models [health]", start=cursor)
+ session.wait_for_literal("/fallback [allow|remove|off]", start=cursor)
+ session.wait_for_literal("/login [codegraff|codex|kimi]", start=cursor)
+ session.wait_for_literal(f"[{base} · cwd {tmp}]", start=cursor)
+ cursor = len(session.raw)
+ session.send_line("/models health")
+ session.wait_for_literal("active: deepseek-v4-pro via codegraff", start=cursor)
+ session.wait_for_literal("Codex catalog:", start=cursor)
+ session.wait_for_literal(
+ "Codex transport: WebSocket primary with automatic SSE fallback",
+ start=cursor,
+ )
+ session.wait_for(r"✓\s+codegraff\s+environment", start=cursor)
+ session.wait_for(r"·\s+codex\s+missing", start=cursor)
+ session.wait_for_literal(f"[{base} · cwd {tmp}]", start=cursor)
+ if b"local-pty-test" in bytes(session.raw[cursor:]):
+ raise AssertionError("/models health exposed a credential value")
command(
"/plan",
"plan mode on",
@@ -93,6 +118,50 @@ def main() -> None:
history = os.path.join(tmp, ".simple-harness-history")
if os.path.exists(history) and "supersecret" in open(history, encoding="utf-8").read():
raise AssertionError("/key secret was persisted in REPL history")
+
+ # A short/narrow PTY used to overflow because both pickers always drew
+ # 18 rows with fixed 26/11-column cells. The model picker should fit in
+ # 12 rows and initially highlight the active model; the settings picker
+ # should retain its persisted current value too.
+ with PtySession(
+ GRAFF,
+ ["--model", "deepseek-v4-pro", "--no-telemetry"],
+ cwd=tmp,
+ env=env,
+ unset_env=("CODEX_HOME", "NO_COLOR"),
+ timeout=15.0,
+ rows=12,
+ cols=44,
+ ) as session:
+ session.wait_for_literal("] ›")
+ cursor = len(session.raw)
+ session.send_line("/model")
+ session.wait_for_literal("CTX/KEY", start=cursor)
+ session.pump_for(0.1)
+ paint = bytes(session.raw[cursor:]).rsplit(b"\x1b[2J\x1b[H", 1)[-1]
+ if paint.count(b"\n") != 11:
+ raise AssertionError("model picker exceeded its 12-row terminal budget")
+ if b"\x1b[7m\xe2\x96\x8c deepseek-v4-pro" not in paint:
+ raise AssertionError("model picker did not initially select the active model")
+ session.send_key("ctrl-c")
+ session.wait_for_literal("] ›", start=cursor)
+
+ cursor = len(session.raw)
+ session.send_line("/effort")
+ session.wait_for_literal("Reasoning level for", start=cursor)
+ session.wait_for_literal("Ultra", start=cursor)
+ session.pump_for(0.1)
+ paint = bytes(session.raw[cursor:]).rsplit(b"\x1b[2J\x1b[H", 1)[-1]
+ if b"\x1b[7m Extra high" not in paint:
+ raise AssertionError("reasoning picker did not initially select the current level")
+ session.send_key("ctrl-c")
+ session.wait_for_literal("] ›", start=cursor)
+ session.send_key("ctrl-d")
+ result = session.read_until_exit(5.0)
+ if result.timed_out or result.exit_code != 0:
+ raise SystemExit(
+ f"narrow REPL did not exit cleanly: exit={result.exit_code} timed_out={result.timed_out}"
+ )
print("ok PTY REPL commands, colored mode badges, redraws, and clean exit")
diff --git a/src/agent.zig b/src/agent.zig
index b7e76250..d3ddbeb1 100644
--- a/src/agent.zig
+++ b/src/agent.zig
@@ -64,6 +64,13 @@ fn writePromptBadge(w: *Io.Writer, color: []const u8, label: []const u8) !void {
try w.print("{s} · {s}{s}{s}{s}", .{ style.dim, style.reset, color, label, style.reset });
}
+fn compactTokenCount(buf: []u8, tokens: u64) []const u8 {
+ return if (tokens >= 1000)
+ std.fmt.bufPrint(buf, "{d}k", .{tokens / 1000}) catch "?"
+ else
+ std.fmt.bufPrint(buf, "{d}", .{tokens}) catch "?";
+}
+
pub const TodoItem = struct {
content: []const u8,
status: []const u8,
@@ -167,8 +174,9 @@ pub const Agent = struct {
};
// Prompt-cache hit from the last response — proof caching is working.
var kbuf: [32]u8 = undefined;
+ var kval: [24]u8 = undefined;
const cached: []const u8 = if (self.last_cache_read > 0)
- (std.fmt.bufPrint(&kbuf, " · ⚡{d} cached", .{self.last_cache_read}) catch "")
+ (std.fmt.bufPrint(&kbuf, " · ⚡{s} cached", .{compactTokenCount(&kval, self.last_cache_read)}) catch "")
else
"";
try w.print("\n{s}[{s}{s}{s}{s}", .{ style.dim, style.reset, style.cyan, self.provider.model, style.reset });
@@ -185,10 +193,18 @@ pub const Agent = struct {
try w.print("{s} · cwd {s}{s}{s}", .{ style.dim, style.reset, main_mod.g_cwd_display, style.dim });
if (self.last_context_tokens > 0) {
const threshold = self.provider.compactAt();
- // % of the compaction budget already used — glanceable headroom.
- const pct = if (threshold > 0) self.last_context_tokens * 100 / threshold else 0;
- try w.print(" · {d}/{d}k tok ({d}%){s}{s}]{s} {s}›{s} ", .{
- self.last_context_tokens, threshold / 1000, pct, cached, cost, style.reset, style.bold, style.reset,
+ const pct = if (self.provider.context > 0) self.last_context_tokens * 100 / self.provider.context else 0;
+ var used_buf: [24]u8 = undefined;
+ try w.print(" · {s}/{d}k ctx ({d}% · compact@{d}k){s}{s}]{s} {s}›{s} ", .{
+ compactTokenCount(&used_buf, self.last_context_tokens),
+ self.provider.context / 1000,
+ pct,
+ threshold / 1000,
+ cached,
+ cost,
+ style.reset,
+ style.bold,
+ style.reset,
});
} else {
try w.print("{s}]{s} {s}›{s} ", .{ cost, style.reset, style.bold, style.reset });
@@ -450,3 +466,9 @@ test "reasoning prompt label uses picker wording" {
try std.testing.expectEqualStrings("Max", reasoningPromptLabel(.max));
try std.testing.expectEqualStrings("Ultra", reasoningPromptLabel(.ultra));
}
+
+test "compact token counts keep prompt usage readable" {
+ var buf: [24]u8 = undefined;
+ try std.testing.expectEqualStrings("999", compactTokenCount(&buf, 999));
+ try std.testing.expectEqualStrings("138k", compactTokenCount(&buf, 138_082));
+}
diff --git a/src/commands_misc.zig b/src/commands_misc.zig
index 04f1ba19..e00bc161 100644
--- a/src/commands_misc.zig
+++ b/src/commands_misc.zig
@@ -34,6 +34,8 @@ const pricing = @import("pricing.zig");
const default_context = pricing.default_context;
const g_cost = &pricing.g_cost;
const models_cache = @import("models_cache.zig");
+const command_catalog = @import("command_catalog.zig");
+const serde = @import("serde.zig");
const schema = @import("schema.zig");
const renderRootTools = schema.renderRootTools;
@@ -55,6 +57,73 @@ const listPicker = pickers.listPicker;
const trace = @import("trace.zig");
const trace_path = trace.trace_path;
+fn providerModelCount(provider_id: []const u8) usize {
+ var count: usize = 0;
+ for (pricing.models()) |model| if (std.mem.eql(u8, model.provider, provider_id)) {
+ count += 1;
+ };
+ return count;
+}
+
+fn showModelsHealth(root: *Agent, keys: *Keys, arena: Allocator, out: *Io.Writer) !void {
+ 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", .{
+ root.provider.model,
+ root.provider.id,
+ root.provider.context / 1000,
+ root.provider.compactAt() / 1000,
+ if (root.fallback_active) " · temporary fallback" else "",
+ if (root.fallback_blocked) " · BLOCKED pending consent" else "",
+ });
+ if (saved) |preferred|
+ try out.print("saved default: {s} via {s}\n", .{ preferred.model, preferred.pid })
+ else
+ try out.writeAll("saved default: none\n");
+
+ var codex_models: usize = 0;
+ for (pricing.models()) |model| if (std.mem.eql(u8, model.provider, "codex")) {
+ codex_models += 1;
+ };
+ try out.print("Codex catalog: {s} · {d} model(s)\n", .{ models_cache.codex_catalog_source, codex_models });
+ const transport = if (!main_mod.g_codex_ws)
+ "SSE forced (GRAFF_CODEX_WS is off)"
+ else if (root.ws_off)
+ "SSE fallback (WebSocket failed this session)"
+ else
+ "WebSocket primary with automatic SSE fallback";
+ try out.print("Codex transport: {s}\n", .{transport});
+
+ if (root.fallback_allow.len == 0) {
+ try out.writeAll("cross-provider fallback: off; same-provider rollout replacement allowed\n");
+ } else {
+ try out.writeAll("cross-provider fallback allowlist:");
+ for (root.fallback_allow) |provider_id| try out.print(" {s}", .{provider_id});
+ try out.writeByte('\n');
+ }
+
+ try out.writeAll("providers (credential values are never shown):\n");
+ for (provider_specs) |spec| {
+ 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", .{
+ if (available) "✓" else "·",
+ spec.id,
+ if (available and source == .none) "resolved" else source.label(),
+ providerModelCount(spec.id),
+ if (std.mem.eql(u8, spec.id, root.provider.id)) " ← active" else "",
+ });
+ if (!available) {
+ if (std.mem.eql(u8, spec.id, "codex") or std.mem.eql(u8, spec.id, "codegraff") or std.mem.eql(u8, spec.id, "kimi"))
+ try out.print(" fix: /login {s}\n", .{spec.id})
+ else
+ try out.print(" fix: /key {s} <key> or set {s}\n", .{ spec.id, spec.env_key });
+ }
+ }
+ if (root.last_api_error != null) try out.writeAll("last request: provider/API failure recorded (details hidden; see trace for diagnostics)\n");
+ try out.flush();
+}
+
/// Try to handle a misc slash command. Returns false (line unhandled) if
/// `line` doesn't match any command in this file — the caller falls through
/// to handleRest() for the unknown-command/help terminal stage.
@@ -188,6 +257,10 @@ pub fn tryHandle(root: *Agent, keys: *Keys, arena: Allocator, line: []const u8,
try out.flush();
return true;
}
+ if (std.mem.eql(u8, line, "/models health")) {
+ try showModelsHealth(root, keys, arena, out);
+ return true;
+ }
if (std.mem.eql(u8, line, "/models")) {
try out.writeAll("model ctx compact@ provider key vision\n");
for (pricing.models()) |m| {
@@ -388,51 +461,18 @@ pub fn handleRest(line: []const u8, out: *Io.Writer) !void {
try out.flush();
return;
}
+ try out.writeAll("commands (bare / opens the filterable menu):\n");
+ for (command_catalog.commands) |command| {
+ const usage = if (command.usage.len > 0) command.usage else command.name;
+ try out.print(" {s:<32} {s}\n", .{ usage, command.desc });
+ }
try out.writeAll(
- \\commands: (a bare "/" opens this list as a filterable menu)
- \\ /model <name> switch model/provider, fuzzy match (e.g. "sonnet", "opus")
- \\ /models list known models, context windows, compaction points
- \\ /clear wipe the conversation and start fresh
- \\ /new start a fresh autosaved session
- \\ /rename <title> set the current session title
- \\ /goal [text] set/show a standing objective (tracked as a checklist); /goal clear clears
- \\ /loop <prompt> run an autonomous plan→act→verify pass
- \\ /plan toggle plan mode: read-only explore + propose; writes/edits denied
- \\ /ultracode toggle persistent workflow mode; bare opens on/off picker, or /ultracode on|off
- \\ /key [prov key] show API-key status; /key <provider> <key> adds one live (+ Keychain)
- \\ /login [tgt] OAuth sign-in (no key to paste): codegraff | codex (alias oai) | kimi; bare → picker
- \\ /keepcontext toggle keeping the conversation when /model switches wire format (default on)
- \\ /effort reasoning picker: low|medium|high|xhigh|max|ultra (persists)
- \\ /reasoning alias for /effort
- \\ /fast codex only: priority service tier for lower latency (toggle, persists)
- \\ /strict toggle "every message is a tool" mode
- \\ /yolo toggle bash auto-approval (skip permission prompts)
- \\ /trace toggle the JSONL event trace (harness.trace.jsonl)
- \\ /trajectory show this session's agent tree — turns + spawned
- \\ subagents with system-prompt fingerprints
- \\ (harness.trajectory.jsonl, DGM-style)
- \\ /agents list agent types — builtin personas + .harness/agents/*.md
- \\ (spawn with subagent agent:"<name>")
- \\ /compact summarize history into a fresh context
- \\ /rewind [n] list past prompts; /rewind <n> drops prompt n+after & reverts its file edits
- \\ /image <path> attach an image to your next message (vision models only)
- \\ /paste attach the clipboard image — macOS; also Ctrl-V (⌘V can't be captured)
- \\ /save [name] write the conversation to <name>.session.json (default: current)
- \\ /resume [name] restore a saved conversation (no arg → interactive picker)
- \\ /sessions list saved sessions in the cwd
- \\ /todo show the current task list
- \\ /animation pick the thinking animation (braille/pulse/orbit-dots/block-wave/
- \\ shimmer/matrix/pacman/starfield/random/off); persists to settings
- \\ /mcp [add …] list MCP servers/tools; /mcp add <name> <cmd> [args...] connects one live; /mcp trust connects skipped workspace servers
- \\ exit / /exit quit (also: ctrl-d, or ctrl-c on an empty line)
+ \\ exit | /exit | /quit quit (also ctrl-d or ctrl-c on an empty line)
\\
- \\esc during a response interrupts the turn (what streamed stays in history).
+ \\esc during a response interrupts the turn; streamed output remains in history.
\\"always allow" answers persist to .harness/settings.json in the cwd.
- \\codeword: include "ultracode" in any message to force one multi-agent
- \\workflow turn; /ultracode on persists that behavior for future prompts.
- \\
- \\launch flags: --model <name> · --yolo (skip prompts) · -p "prompt" (one-shot) · --system-prompt/--append-system-prompt · --timing · --cost · --json (SDK protocol) · --help · --version
- \\subcommands: `graff login [codex]` (OAuth) · `graff key set <provider> <key>` (Keychain) · `graff --schema`
+ \\launch flags: --model <name> · --yolo · -p "prompt" · --json · --help · --version
+ \\subcommands: graff login [codex] · graff key set <provider> <key> · graff --schema
\\
);
try out.flush();
diff --git a/src/commands_model.zig b/src/commands_model.zig
index 86d93ad5..f034fdd4 100644
--- a/src/commands_model.zig
+++ b/src/commands_model.zig
@@ -1,6 +1,6 @@
//! Model/provider/thinking slash commands, split out of main.zig's
//! handleCommand (600-line goal, issue #123): /model /compact /rewind /fast
-//! /thinking /title /ultracode /effort /keepcontext /key /login /image
+//! /thinking /title /ultracode /effort /keepcontext /fallback /key /login /image
//! /paste /strict.
const std = @import("std");
@@ -40,6 +40,8 @@ const offerProviderAuth = pickers.offerProviderAuth;
const providers = @import("providers.zig");
const switchProvider = providers.switchProvider;
+const fallback_config = @import("fallback_config.zig");
+const serde = @import("serde.zig");
const oauth = @import("oauth.zig");
@@ -57,9 +59,70 @@ const stageImagePath = vision.stageImagePath;
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;
+}
+
+fn showFallback(root: *Agent, arena: Allocator, out: *Io.Writer) !void {
+ const saved = serde.loadModel(root.io, arena, root.home);
+ try out.print("current: {s} via {s}{s}\n", .{ root.provider.model, root.provider.id, if (root.fallback_active) " (temporary fallback)" else "" });
+ if (saved) |preferred| try out.print("saved default: {s} via {s}\n", .{ preferred.model, preferred.pid });
+ if (root.fallback_allow.len == 0) {
+ try out.writeAll("cross-provider fallback: off (same-provider rollout replacement remains allowed)\n");
+ } else {
+ try out.writeAll("cross-provider fallback allowed:");
+ for (root.fallback_allow) |id| try out.print(" {s}", .{id});
+ try out.writeByte('\n');
+ }
+ if (root.fallback_blocked) try out.print("{s}blocked: allow {s} with /fallback allow {s}, or choose /model{s}\n", .{ style.yellow, root.provider.id, root.provider.id, style.reset });
+ try out.writeAll("manage: /fallback allow <provider> · remove <provider> · off\n");
+ try out.flush();
+}
+
+fn handleFallback(root: *Agent, arena: Allocator, line: []const u8, out: *Io.Writer) !bool {
+ if (!std.mem.eql(u8, line, "/fallback") and !std.mem.startsWith(u8, line, "/fallback ")) return false;
+ const rest = std.mem.trim(u8, line["/fallback".len..], " \t");
+ if (rest.len == 0) {
+ try showFallback(root, arena, out);
+ return true;
+ }
+ if (std.mem.eql(u8, rest, "off")) {
+ root.fallback_allow = &.{};
+ _ = fallback_config.save(root.io, root.gpa, root.fallback_allow);
+ try showFallback(root, arena, out);
+ return true;
+ }
+ var words = std.mem.tokenizeAny(u8, rest, " \t");
+ const action = words.next() orelse "";
+ const id = words.next() orelse {
+ try out.writeAll("usage: /fallback allow|remove <provider> | /fallback off\n");
+ try out.flush();
+ return true;
+ };
+ if ((!std.mem.eql(u8, action, "allow") and !std.mem.eql(u8, action, "remove")) or !providerKnown(id)) {
+ try out.print("unknown fallback action/provider — use /fallback allow|remove <provider>; provider '{s}' must appear in /models\n", .{id});
+ try out.flush();
+ return true;
+ }
+ var updated: std.ArrayList([]const u8) = .empty;
+ for (root.fallback_allow) |existing| {
+ if (std.mem.eql(u8, action, "remove") and std.mem.eql(u8, existing, id)) continue;
+ updated.append(arena, existing) catch {};
+ }
+ if (std.mem.eql(u8, action, "allow") and !fallback_config.contains(updated.items, id)) updated.append(arena, try arena.dupe(u8, id)) catch {};
+ root.fallback_allow = updated.toOwnedSlice(arena) catch updated.items;
+ const saved = fallback_config.save(root.io, root.gpa, root.fallback_allow);
+ if (std.mem.eql(u8, action, "allow") and std.mem.eql(u8, id, root.provider.id)) root.fallback_blocked = false;
+ if (!saved) try out.print("{s}warning: fallback setting is active now but was not persisted{s}\n", .{ style.yellow, style.reset });
+ try showFallback(root, arena, out);
+ return true;
+}
+
/// Try to handle a model/provider/thinking slash command. Returns false (line
/// unhandled) if `line` doesn't match any command in this file.
pub fn tryHandle(root: *Agent, keys: *Keys, arena: Allocator, line: []const u8, out: *Io.Writer) !bool {
+ if (try handleFallback(root, arena, line, out)) return true;
if (std.mem.startsWith(u8, line, "/model") and !std.mem.startsWith(u8, line, "/models")) {
const arg = std.mem.trim(u8, line["/model".len..], " \t");
if (arg.len == 0) {
@@ -98,6 +161,11 @@ pub fn tryHandle(root: *Agent, keys: *Keys, arena: Allocator, line: []const u8,
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 (!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();
+ return true;
+ }
const m = try arena.dupe(u8, mdl);
const provider = keys.providerById(pid, m) catch {
try offerProviderAuth(root, keys, arena, out, pid, m);
@@ -143,8 +211,12 @@ pub fn tryHandle(root: *Agent, keys: *Keys, arena: Allocator, line: []const u8,
try switchProvider(root, arena, provider, out);
return true;
}
- const resolved = resolveModelName(keys.*, arg);
- const name = try arena.dupe(u8, resolved orelse arg);
+ const resolved = resolveModelName(keys.*, arg) orelse {
+ try out.print("unknown model '{s}' — choose /model, or run `graff models refresh` first; preference unchanged\n", .{arg});
+ try out.flush();
+ return true;
+ };
+ const name = try arena.dupe(u8, resolved);
const provider = keys.providerFor(name) catch {
for (pricing.models()) |mt| if (std.mem.eql(u8, mt.name, name)) {
try offerProviderAuth(root, keys, arena, out, mt.provider, name);
@@ -155,12 +227,6 @@ pub fn tryHandle(root: *Agent, keys: *Keys, arena: Allocator, line: []const u8,
return true;
};
try switchProvider(root, arena, provider, out);
- if (resolved == null) {
- // Not in the model table: providerFor routed it to the claude*/
- // gateway fallback. Say so — the API will reject a typo'd name.
- try out.print("{s}⚠ '{s}' isn't in the model table — sent to {s} as-is; the first request will fail if it doesn't exist (/models lists known names){s}\n", .{ style.dim, name, provider.id, style.reset });
- try out.flush();
- }
return true;
}
if (std.mem.eql(u8, line, "/compact")) {
@@ -363,6 +429,7 @@ pub fn tryHandle(root: *Agent, keys: *Keys, arena: Allocator, line: []const u8,
keys.values[idx.?] = arena.dupe(u8, key) catch key; // live, usable immediately
const home = root.home;
const saved = storeKey(root.io, root.gpa, arena, home, pid, key); // persist
+ keys.sources[idx.?] = if (saved) .stored else .session;
try out.print("✓ {s} key set (live{s}) — now: /model {s}\n", .{ pid, if (saved) " + Keychain" else "", pid });
try out.flush();
return true;
diff --git a/src/main.zig b/src/main.zig
index 338083f6..de0c681f 100644
--- a/src/main.zig
+++ b/src/main.zig
@@ -51,6 +51,7 @@ pub var plan_mode = false; // /plan: read-only — mutating tools are denied, th
pub var unattended = false; // -p one-shot: no human to prompt; unapproved tool calls are denied
const pricing = @import("pricing.zig"); // model pricing/catalog + session cost tally
const models_cache = @import("models_cache.zig"); // graff models [refresh]: models.dev metadata cache + runtime overlay
+const command_catalog = @import("command_catalog.zig");
const util = @import("util.zig"); // shared JSON ObjectMap getters (strFieldObj/intFieldObj)
test {
// build.zig's unit_tests root is main.zig only — reference every split-out module so their test blocks keep running.
@@ -143,7 +144,7 @@ pub var g_fleet: bool = true;
const unixMs = util.unixMs;
/// Reasoning depth for codex/responses (OpenAI Responses `reasoning.effort`).
pub const ReasoningEffort = enum { low, medium, high, xhigh, max, ultra };
-pub const repl_commands = [_][]const u8{ "/model", "/models", "/clear", "/new", "/rename", "/goal", "/loop", "/bash", "/plan", "/key", "/keepcontext", "/effort", "/fast", "/ultracode", "/thinking", "/title", "/reasoning", "/strict", "/yolo", "/trace", "/fleet", "/trajectory", "/agents", "/skills", "/hooks", "/compact", "/rewind", "/image", "/paste", "/save", "/resume", "/sessions", "/todo", "/jobs", "/cost", "/animation", "/theme", "/mcp", "/help" };
+pub const repl_commands = command_catalog.names;
// Lifecycle hooks (Hook/Hooks config types + settings loader + per-hook subprocess runner) live in hooks.zig; g_hooks below, dispatch, and the codedb-guard cache stay here.
const hooks = @import("hooks.zig");
pub var g_hooks: hooks.Hooks = .{};
@@ -172,6 +173,7 @@ const title_mod = @import("title.zig");
// The `graff repl` bridge, steering-note assembly, steering queue drain, and /effort /fast /ultracode persistence live in repl_glue.zig. SteerEntry
// is read from here; the mutable steer/thinking globals stay here, read/written live via `main_mod.g_x` (never aliased — they're `var`s).
const repl_glue = @import("repl_glue.zig");
+const fallback_config = @import("fallback_config.zig");
/// Per-skill user opt-out, persisted as {"skills": {"kuri": false}} in .harness/settings.json. A disabled skill is treated as not installed
/// anywhere — no system-prompt note, /skills shows it disabled, and webfetch never shells out to it, even when its binaries are on PATH.
pub var g_skill_disabled = [_]bool{false} ** skills_registry.len;
@@ -223,13 +225,10 @@ pub fn main(init: std.process.Init) !void {
const gpa = init.gpa;
const io = init.io;
const arena = init.arena.allocator();
-
// Windows: let the console interpret ANSI/VT escapes so the harness's color and cursor sequences render instead of literal text.
if (builtin.os.tag == .windows) tty.enableVtOutput();
-
// CLI flags: the Flags struct + parsing loop live in args.zig; downstream code reads flags.<name> in place of ~27 locals this block used to declare.
const flags = try args.parse(init);
-
// --help / --version: handled before any subcommand dispatch, so `harness login --help` prints usage instead of starting an OAuth flow.
if (try startup.runSubcommand(io, gpa, arena, init, flags)) return;
// Credential/model resolution (env vars → on-disk logins → `harness key set` store, env always wins; then --model or the last-saved model) lives
@@ -238,11 +237,10 @@ pub fn main(init: std.process.Init) !void {
var keys = resolved_keys.keys;
const default_provider = resolved_keys.default_provider;
const stale_saved_model = resolved_keys.stale_saved_model;
+ const preferred_provider = resolved_keys.preferred_provider;
const codex_account = resolved_keys.codex_account;
-
var client: std.http.Client = .{ .allocator = gpa, .io = io };
defer client.deinit();
-
var stdin_buf: [64 * 1024]u8 = undefined;
var stdin_reader = Io.File.stdin().reader(io, &stdin_buf);
const in = &stdin_reader.interface;
@@ -253,7 +251,7 @@ pub fn main(init: std.process.Init) !void {
g_out = out;
if (try session_start.runTitleCommand(io, gpa, arena, &client, default_provider, out, flags)) return;
- try session_start.setupWorktreeAndBanner(io, gpa, arena, init.environ_map, flags, out, trace_path, codex_account, stale_saved_model, default_provider);
+ try session_start.setupWorktreeAndBanner(io, gpa, arena, init.environ_map, flags, out, trace_path, codex_account, stale_saved_model, preferred_provider, default_provider);
// Session trace (best-effort: a failed open just disables tracing).
var trace_buf: [8 * 1024]u8 = undefined;
@@ -352,6 +350,8 @@ pub fn main(init: std.process.Init) !void {
// backgrounded fleet-champion pull live in session_start.zig. `root`'s pointer fields (snapshots/client/tracer/approvals/registry) all reference
// already-stable main()-owned storage passed in by address, so returning the constructed Agent by value here is safe.
var root = try session_run.buildRootAgent(gpa, arena, io, &client, default_provider, init.environ_map, out, in, registry, &approvals, &tracer, sys_normal, sys_strict, mcp_tools, &snaps, flags, telem.endpoint);
+ root.fallback_active = stale_saved_model != null;
+ root.fallback_blocked = root.fallback_active and preferred_provider != null and !std.mem.eql(u8, preferred_provider.?, root.provider.id) and !fallback_config.contains(root.fallback_allow, root.provider.id);
defer joinElites(io); // reap if the session quits before any turn joins it
session_run.saveOrResumeSession(&root, keys, arena, flags);
diff --git a/src/mainloop.zig b/src/mainloop.zig
index 7ee733ea..4a4237aa 100644
--- a/src/mainloop.zig
+++ b/src/mainloop.zig
@@ -154,6 +154,7 @@ pub fn run(ctx: *Ctx) !void {
const label = providers.setModelRequestLabel(ctx.arena, provider_field, model_field, legacy_name) catch "<requested model>";
const message = switch (err) {
error.MissingKey => try std.fmt.allocPrint(ctx.arena, "no key/login for requested model '{s}'", .{label}),
+ error.InvalidModel => try std.fmt.allocPrint(ctx.arena, "unknown model '{s}'; refresh/list models before switching", .{label}),
error.InvalidModelRequest => "set_model needs a non-empty provider/model or legacy name",
else => try std.fmt.allocPrint(ctx.arena, "failed to switch model '{s}': {s}", .{ label, @errorName(err) }),
};
@@ -331,6 +332,15 @@ pub fn run(ctx: *Ctx) !void {
break :blk text;
} else line;
+ if (ctx.root.fallback_blocked) {
+ const message = try std.fmt.allocPrint(ctx.arena, "saved model unavailable; sending to {s} requires explicit consent — run /fallback allow {s} or choose /model", .{ ctx.root.provider.id, ctx.root.provider.id });
+ if (main_mod.json_mode) ctx.root.emit(.{ .type = "error", .message = message }) else {
+ try ctx.out.print("{s}⚠ {s}{s}\n", .{ style.yellow, message, style.reset });
+ try ctx.out.flush();
+ }
+ continue;
+ }
+
// Persistent goal steering: the objective plus a nudge to track it as a
// live todo_write checklist, with the current list appended so the model
// resumes the plan instead of re-deriving it (assembled by goalSteeringNote).
diff --git a/src/pickers.zig b/src/pickers.zig
index 6caae787..e4524e38 100644
--- a/src/pickers.zig
+++ b/src/pickers.zig
@@ -33,6 +33,7 @@ const Agent = agent_mod.Agent;
const Keys = provider_mod.Keys;
const provider_specs = provider_mod.provider_specs;
const storeKey = keys_cli.storeKey;
+const command_catalog = @import("command_catalog.zig");
/// Case-insensitive subsequence match (fzf-style): every char of `needle`
/// appears in `hay` in order, gaps allowed — so "gpt5.5" matches "gpt-5.5".
@@ -83,6 +84,107 @@ fn scoredLess(_: void, a: Scored, b: Scored) bool {
return a.idx < b.idx;
}
+const ModelPickerLayout = struct {
+ visible: usize,
+ name_width: usize,
+ provider_width: usize,
+ context_width: usize,
+ show_context: bool,
+ compact_context: bool,
+};
+
+const ListPickerLayout = struct {
+ visible: usize,
+ name_width: usize,
+ desc_width: usize,
+ show_desc: bool,
+};
+
+/// Leave room for the picker title/counter/header/footer instead of painting a
+/// fixed 18 rows past the bottom of short terminals.
+fn visibleRows(rows: usize, chrome_rows: usize) usize {
+ if (rows <= chrome_rows) return 1;
+ return @min(@as(usize, 18), rows - chrome_rows);
+}
+
+fn modelPickerLayout(rows: usize, cols: usize) ModelPickerLayout {
+ // Avoid the terminal's rightmost column: many terminals defer an automatic
+ // wrap there, which makes the following newline consume an extra row.
+ const budget = if (cols > 1) cols - 1 else 1;
+ const show_context = budget >= 34;
+ const compact_context = budget < 52;
+ const provider_width = @min(@as(usize, 11), @max(@as(usize, 3), budget / 4));
+ const context_width: usize = if (!show_context) 0 else if (compact_context) 7 else 13;
+ const fixed = 2 + provider_width + (if (show_context) context_width + 2 else 3);
+ const name_width = @min(@as(usize, 26), if (budget > fixed) budget - fixed else 1);
+ return .{
+ .visible = visibleRows(rows, 4),
+ .name_width = name_width,
+ .provider_width = provider_width,
+ .context_width = context_width,
+ .show_context = show_context,
+ .compact_context = compact_context,
+ };
+}
+
+fn listPickerLayout(rows: usize, cols: usize) ListPickerLayout {
+ const budget = if (cols > 1) cols - 1 else 1;
+ const show_desc = budget >= 32;
+ const name_width = if (show_desc)
+ @min(@as(usize, 24), @max(@as(usize, 12), budget / 3))
+ else if (budget > 1)
+ budget - 1
+ else
+ 1;
+ return .{
+ .visible = visibleRows(rows, 3),
+ .name_width = name_width,
+ .desc_width = if (show_desc and budget > name_width + 2) budget - name_width - 2 else 0,
+ .show_desc = show_desc,
+ };
+}
+
+fn visibleLen(text: []const u8) usize {
+ var columns: usize = 0;
+ var i: usize = 0;
+ while (i < text.len) : (columns += 1) {
+ i += std.unicode.utf8ByteSequenceLength(text[i]) catch 1;
+ }
+ return columns;
+}
+
+fn prefixBytes(text: []const u8, columns: usize) usize {
+ var seen: usize = 0;
+ var i: usize = 0;
+ while (i < text.len and seen < columns) : (seen += 1) {
+ i += std.unicode.utf8ByteSequenceLength(text[i]) catch 1;
+ }
+ return @min(i, text.len);
+}
+
+/// Write one plain-text table cell at exactly `width` visible columns,
+/// truncating by UTF-8 codepoint and reserving the final column for an ellipsis.
+fn writeCell(out: *Io.Writer, text: []const u8, width: usize) void {
+ if (width == 0) return;
+ const len = visibleLen(text);
+ if (len <= width) {
+ out.writeAll(text) catch return;
+ for (len..width) |_| out.writeByte(' ') catch return;
+ return;
+ }
+ if (width > 1) out.writeAll(text[0..prefixBytes(text, width - 1)]) catch return;
+ out.writeAll("…") catch return;
+}
+
+fn writeClipped(out: *Io.Writer, text: []const u8, width: usize) void {
+ if (visibleLen(text) <= width) {
+ out.writeAll(text) catch {};
+ } else if (width > 0) {
+ if (width > 1) out.writeAll(text[0..prefixBytes(text, width - 1)]) catch return;
+ out.writeAll("…") catch {};
+ }
+}
+
/// Interactive fuzzy model picker for a bare `/model` (codegraff-style). Opens
/// a full-screen alternate buffer: type to filter, ↑/↓ to move, Enter to pick,
/// Ctrl-C to cancel. Returns the chosen model_table index, or null.
@@ -104,9 +206,10 @@ pub fn modelPicker(root: *Agent, keys: *Keys, arena: Allocator, out: *Io.Writer)
var filtered: std.ArrayList(usize) = .empty;
defer filtered.deinit(arena);
var sel: usize = 0;
- const visible = 18;
+ var select_current = true;
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
@@ -123,29 +226,60 @@ pub fn modelPicker(root: *Agent, keys: *Keys, arena: Allocator, out: *Io.Writer)
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| {
+ const m = model_table[model_idx];
+ if (std.mem.eql(u8, m.name, root.provider.model) and std.mem.eql(u8, m.provider, root.provider.id)) {
+ sel = row;
+ break;
+ }
+ }
+ select_current = false;
+ }
out.writeAll("\x1b[2J\x1b[H") catch {};
out.print("{s}Model ›{s} {s}\n", .{ style.cyan, style.reset, query.items }) catch {};
out.print("{s}{d}/{d}{s}\n", .{ style.dim, filtered.items.len, model_table.len, style.reset }) catch {};
- out.print("{s} {s:<26} {s:<11} CTX{s}\n", .{ style.dim, "MODEL", "PROVIDER", style.reset }) catch {};
- const off = if (sel >= visible) sel - visible + 1 else 0;
+ out.writeAll(style.dim) catch {};
+ out.writeAll(" ") catch {};
+ writeCell(out, "MODEL", layout.name_width);
+ out.writeByte(' ') catch {};
+ writeCell(out, "PROVIDER", layout.provider_width);
+ if (layout.show_context) {
+ out.writeByte(' ') catch {};
+ writeCell(out, if (layout.compact_context) "CTX/KEY" else "CTX", layout.context_width);
+ }
+ out.print("{s}\n", .{style.reset}) catch {};
+ const off = if (sel >= layout.visible) sel - layout.visible + 1 else 0;
var row = off;
- while (row < filtered.items.len and row < off + visible) : (row += 1) {
+ while (row < filtered.items.len and row < off + layout.visible) : (row += 1) {
const m = model_table[filtered.items[row]];
const cur = std.mem.eql(u8, m.name, root.provider.model) and std.mem.eql(u8, m.provider, root.provider.id);
const keyed = keys.get(m.provider) != null;
const context = pricing.contextFor(m.provider, m.name);
if (row == sel) out.writeAll("\x1b[7m") catch {};
- out.print("{s} {s:<26} {s:<11} {d}k{s}{s}\n", .{
- if (cur) "▌" else " ",
- m.name,
- m.provider,
- context / 1000,
- if (keyed) "" else " ·no key",
- if (row == sel) "\x1b[0m" else "",
- }) catch {};
+ out.print("{s} ", .{if (cur) "▌" else " "}) catch {};
+ writeCell(out, m.name, layout.name_width);
+ out.writeByte(' ') catch {};
+ writeCell(out, m.provider, layout.provider_width);
+ if (layout.show_context) {
+ out.writeByte(' ') catch {};
+ var context_buf: [32]u8 = undefined;
+ const context_text = if (layout.compact_context)
+ std.fmt.bufPrint(&context_buf, "{d}k{s}", .{ context / 1000, if (keyed) "" else " !" }) catch "?"
+ else
+ std.fmt.bufPrint(&context_buf, "{d}k{s}", .{ context / 1000, if (keyed) "" else " ·no key" }) catch "?";
+ writeCell(out, context_text, layout.context_width);
+ } else if (!keyed) {
+ // Preserve the keyless warning even when CTX is hidden.
+ out.writeAll(" !") catch {};
+ }
+ if (row == sel) out.writeAll("\x1b[0m") catch {};
+ out.writeByte('\n') catch {};
}
- out.print("{s}↑/↓ move · type to filter · Enter switch · Ctrl-C cancel{s}", .{ style.dim, style.reset }) catch {};
+ out.writeAll(style.dim) catch {};
+ writeClipped(out, "↑/↓ move · type to filter · Enter switch · Ctrl-C cancel", if (term.termCols() > 1) term.termCols() - 1 else 1);
+ out.writeAll(style.reset) catch {};
out.flush() catch {};
const ch = in.takeByte() catch return null;
@@ -176,7 +310,7 @@ pub fn modelPicker(root: *Agent, keys: *Keys, arena: Allocator, out: *Io.Writer)
}
}
-pub const PickItem = struct { name: []const u8, desc: []const u8 = "" };
+pub const PickItem = command_catalog.Item;
/// Generic full-screen fuzzy picker (same UI as the /model picker): type to
/// filter on name or description, ↑/↓ to move, Enter picks, Ctrl-C cancels.
@@ -205,9 +339,9 @@ pub fn listPickerAt(root: *Agent, arena: Allocator, out: *Io.Writer, title: []co
var filtered: std.ArrayList(usize) = .empty;
defer filtered.deinit(arena);
var sel: usize = @min(initial, items.len - 1);
- const visible = 18;
while (true) {
+ const layout = listPickerLayout(term.termRows(), term.termCols());
// Score every item against the query and rank: best match on top
// (ties keep the original item order). An empty query scores all
// items 0, so the list stays in its given order.
@@ -224,20 +358,24 @@ pub fn listPickerAt(root: *Agent, arena: Allocator, out: *Io.Writer, title: []co
out.writeAll("\x1b[2J\x1b[H") catch {};
out.print("{s}{s}{s} {s}\n", .{ style.cyan, title, style.reset, query.items }) catch {};
out.print("{s}{d}/{d}{s}\n", .{ style.dim, filtered.items.len, items.len, style.reset }) catch {};
- const off = if (sel >= visible) sel - visible + 1 else 0;
+ const off = if (sel >= layout.visible) sel - layout.visible + 1 else 0;
var row = off;
- while (row < filtered.items.len and row < off + visible) : (row += 1) {
+ while (row < filtered.items.len and row < off + layout.visible) : (row += 1) {
const item = items[filtered.items[row]];
if (row == sel) out.writeAll("\x1b[7m") catch {};
- out.print(" {s:<16}{s} {s}{s}{s}\n", .{
- item.name,
- if (row == sel) "\x1b[0m" else "",
- style.dim,
- item.desc,
- style.reset,
- }) catch {};
+ out.writeByte(' ') catch {};
+ writeCell(out, item.name, layout.name_width);
+ if (row == sel) out.writeAll("\x1b[0m") catch {};
+ if (layout.show_desc) {
+ out.print(" {s}", .{style.dim}) catch {};
+ writeCell(out, item.desc, layout.desc_width);
+ out.writeAll(style.reset) catch {};
+ }
+ out.writeByte('\n') catch {};
}
- out.print("{s}↑/↓ move · type to filter · Enter pick · Ctrl-C cancel{s}", .{ style.dim, style.reset }) catch {};
+ out.writeAll(style.dim) catch {};
+ writeClipped(out, "↑/↓ move · type to filter · Enter pick · Ctrl-C cancel", if (term.termCols() > 1) term.termCols() - 1 else 1);
+ out.writeAll(style.reset) catch {};
out.flush() catch {};
const ch = in.takeByte() catch return null;
@@ -327,69 +465,70 @@ pub fn pickUltracodeMode(root: *Agent, arena: Allocator, out: *Io.Writer) ?bool
/// The slash-command menu shown for a bare "/": every REPL command with a
/// one-line description, picked via listPicker. Returns the command to run.
-pub const command_menu = [_]PickItem{
- .{ .name = "/model", .desc = "switch model/provider (picker)" },
- .{ .name = "/models", .desc = "list known models, context windows" },
- .{ .name = "/clear", .desc = "wipe the conversation, start fresh" },
- .{ .name = "/new", .desc = "start a new autosaved session" },
- .{ .name = "/rename", .desc = "rename the current session title" },
- .{ .name = "/goal", .desc = "set/show a standing objective, tracked as a live checklist" },
- .{ .name = "/loop", .desc = "run an autonomous plan→act→verify prompt" },
- .{ .name = "/bash", .desc = "run a shell command in the current workspace" },
- .{ .name = "/compact", .desc = "summarize history into a fresh context" },
- .{ .name = "/plan", .desc = "toggle plan mode (read-only, propose first)" },
- .{ .name = "/resume", .desc = "restore a saved session (picker)" },
- .{ .name = "/save", .desc = "save the conversation" },
- .{ .name = "/sessions", .desc = "list saved sessions" },
- .{ .name = "/rewind", .desc = "drop a past prompt & revert its file edits" },
- .{ .name = "/key", .desc = "API-key status / add one live" },
- .{ .name = "/login", .desc = "OAuth sign-in: codegraff | codex/oai | kimi" },
- .{ .name = "/yolo", .desc = "toggle permission prompts" },
- .{ .name = "/strict", .desc = "toggle every-message-is-a-tool mode" },
- .{ .name = "/keepcontext", .desc = "keep history across wire-format switches" },
- .{ .name = "/effort", .desc = "reasoning picker: low through ultra (Codex)" },
- .{ .name = "/reasoning", .desc = "alias for /effort" },
- .{ .name = "/fast", .desc = "codex priority service tier — lower latency on supported models" },
- .{ .name = "/ultracode", .desc = "toggle persistent ultracode (multi-agent workflow) mode" },
- .{ .name = "/thinking", .desc = "show/collapse the model's live reasoning stream" },
- .{ .name = "/title", .desc = "AI-name the tab from your first prompt (on by default)" },
- .{ .name = "/image", .desc = "attach an image to the next message" },
- .{ .name = "/paste", .desc = "attach the clipboard image" },
- .{ .name = "/trace", .desc = "toggle the JSONL event trace" },
- .{ .name = "/fleet", .desc = "toggle federated fleet contribution (DGM propose/submit/elite_pull)" },
- .{ .name = "/trajectory", .desc = "show this session's agent tree (DGM-style)" },
- .{ .name = "/agents", .desc = "list agent types (builtins + .harness/agents)" },
- .{ .name = "/skills", .desc = "optional companion tools: list, /skills add|remove <name>" },
- .{ .name = "/hooks", .desc = "list lifecycle hooks (pre_tool/post_tool/turn_end)" },
- .{ .name = "/todo", .desc = "show the task list" },
- .{ .name = "/jobs", .desc = "list background bash jobs (bash run_in_background)" },
- .{ .name = "/cost", .desc = "session usage: api calls, tokens, USD total" },
- .{ .name = "/animation", .desc = "pick the thinking animation (braille, matrix, pacman…)" },
- .{ .name = "/theme", .desc = "pick a terminal color theme (PastelPink/Midnight/Forest/Amber)" },
- .{ .name = "/mcp", .desc = "list/add/trust MCP servers" },
- .{ .name = "/help", .desc = "list all commands" },
-};
+pub const command_menu = command_catalog.commands;
/// After an in-session `/login` writes its credential file, pull the fresh key
/// (and the Codex account id) into the live Keys so the current conversation
/// uses it without a restart — the in-session twin of the startup loaders.
pub fn reloadLoginKey(root: *Agent, keys: *Keys, arena: Allocator, provider_id: []const u8) void {
const home = root.home;
- for (provider_specs, &keys.values) |spec, *value| {
+ for (provider_specs, &keys.values, &keys.sources) |spec, *value, *source| {
if (!std.mem.eql(u8, spec.id, provider_id)) continue;
if (std.mem.eql(u8, provider_id, "codegraff")) {
- if (oauth.loadCodegraffKey(root.io, arena, home)) |k| value.* = k;
+ if (oauth.loadCodegraffKey(root.io, arena, home)) |k| {
+ value.* = k;
+ source.* = .login;
+ }
} else if (std.mem.eql(u8, provider_id, "kimi")) {
- if (oauth.loadKimiOAuth(root.io, root.gpa, arena, home)) |k| value.* = k;
+ if (oauth.loadKimiOAuth(root.io, root.gpa, arena, home)) |k| {
+ value.* = k;
+ source.* = .login;
+ }
} else if (std.mem.eql(u8, provider_id, "codex")) {
if (oauth.loadCodexAuth(root.io, arena, home)) |auth| {
value.* = auth.token;
+ source.* = .login;
keys.codex_account = auth.account;
}
}
}
}
+/// Read an API key without terminal echo or history persistence. The ordinary
+/// REPL line editor masks `/key provider secret`; this covers the model
+/// picker's separate "paste an API key" flow too.
+fn readSecret(root: *Agent, arena: Allocator, out: *Io.Writer) ?[]const u8 {
+ const in = root.in orelse return null;
+ const raw_state = tty.enterRaw(true) orelse return null;
+ defer tty.restore(raw_state);
+ var secret: std.ArrayList(u8) = .empty;
+ while (true) {
+ const byte = in.takeByte() catch return null;
+ switch (byte) {
+ '\r', '\n' => {
+ out.writeByte('\n') catch {};
+ out.flush() catch {};
+ return secret.toOwnedSlice(arena) catch secret.items;
+ },
+ 0x03, 0x07 => {
+ out.writeByte('\n') catch {};
+ out.flush() catch {};
+ return null;
+ },
+ 0x7f, 0x08 => if (secret.items.len > 0) {
+ _ = secret.pop();
+ out.writeAll("\x08 \x08") catch {};
+ out.flush() catch {};
+ },
+ else => if (byte >= 0x20) {
+ secret.append(arena, byte) catch return null;
+ out.writeByte('*') catch {};
+ out.flush() catch {};
+ },
+ }
+ }
+}
+
/// Better UX when /model targets a provider with no key: instead of a flat
/// "no key" dead-end, offer to log in (OAuth, for providers that have a flow)
/// or paste an API key, then switch to pid/model. Esc/blank/"keep" stays on the
@@ -466,13 +605,9 @@ pub fn offerProviderAuth(root: *Agent, keys: *Keys, arena: Allocator, out: *Io.W
}
reloadLoginKey(root, keys, arena, pid);
} else {
- // Paste a key: one cooked-mode line read (echoes), same pattern as the
- // tool-approval prompt. Blank input cancels.
- const in = root.in orelse return;
- try out.print("paste your {s} API key, then Enter (blank cancels): ", .{pid});
+ try out.print("paste your {s} API key, then Enter (input is hidden; blank cancels): ", .{pid});
try out.flush();
- const raw = (in.takeDelimiter('\n') catch null) orelse "";
- const key = std.mem.trim(u8, raw, " \t\r\n");
+ const key = readSecret(root, arena, out) orelse "";
if (key.len == 0) {
try out.print("cancelled — kept {s}{s}{s}\n", .{ style.cyan, root.provider.model, style.reset });
try out.flush();
@@ -481,6 +616,7 @@ pub fn offerProviderAuth(root: *Agent, keys: *Keys, arena: Allocator, out: *Io.W
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;
try out.print("\xe2\x9c\x93 {s} key set (live{s})\n", .{ pid, if (saved) " + Keychain" else "" });
}
@@ -523,6 +659,29 @@ test "fuzzyScore ranks basename prefix above substring above subsequence" {
try std.testing.expectEqual(@as(?i32, 0), fuzzyScore("abc", ""));
}
+test "picker layouts honor terminal row and column budgets" {
+ try std.testing.expectEqual(@as(usize, 8), visibleRows(12, 4));
+ try std.testing.expectEqual(@as(usize, 18), visibleRows(80, 4));
+ try std.testing.expectEqual(@as(usize, 1), visibleRows(3, 4));
+
+ const model = modelPickerLayout(12, 44);
+ try std.testing.expectEqual(@as(usize, 8), model.visible);
+ try std.testing.expect(model.show_context);
+ const model_columns = 2 + model.name_width + 1 + model.provider_width + 1 + model.context_width;
+ try std.testing.expect(model_columns <= 43);
+
+ const narrow_model = modelPickerLayout(10, 28);
+ try std.testing.expect(!narrow_model.show_context);
+ const narrow_columns = 2 + narrow_model.name_width + 1 + narrow_model.provider_width + 2;
+ try std.testing.expect(narrow_columns <= 27);
+
+ const list = listPickerLayout(16, 44);
+ try std.testing.expectEqual(@as(usize, 13), list.visible);
+ try std.testing.expect(list.show_desc);
+ try std.testing.expect(1 + list.name_width + 1 + list.desc_width <= 43);
+ try std.testing.expect(!listPickerLayout(10, 24).show_desc);
+}
+
test "pickScore prefers name matches over desc matches" {
const by_name = pickScore(.{ .name = "/model", .desc = "switch model" }, "model").?;
const by_desc = pickScore(.{ .name = "/quit", .desc = "model goodbye" }, "model").?;
diff --git a/src/provider.zig b/src/provider.zig
index 04fa91ba..35b8917e 100644
--- a/src/provider.zig
+++ b/src/provider.zig
@@ -82,7 +82,26 @@ pub const Provider = struct {
/// One optional API key per provider_specs entry, read from the environment.
pub const Keys = struct {
+ pub const CredentialSource = enum {
+ none,
+ environment,
+ login,
+ stored,
+ session,
+
+ pub fn label(self: CredentialSource) []const u8 {
+ return switch (self) {
+ .none => "missing",
+ .environment => "environment",
+ .login => "OAuth/login",
+ .stored => "secure store",
+ .session => "this session",
+ };
+ }
+ };
+
values: [provider_specs.len]?[]const u8,
+ sources: [provider_specs.len]CredentialSource = [_]CredentialSource{.none} ** provider_specs.len,
codex_account: []const u8 = "", // ChatGPT account id for the codex provider
pub fn get(keys: Keys, provider_id: []const u8) ?[]const u8 {
@@ -92,6 +111,13 @@ pub const Keys = struct {
return null;
}
+ pub fn source(keys: Keys, provider_id: []const u8) CredentialSource {
+ for (provider_specs, keys.sources) |spec, source_value| {
+ if (std.mem.eql(u8, spec.id, provider_id)) return source_value;
+ }
+ return .none;
+ }
+
pub fn build(keys: Keys, spec: ProviderSpec, key: []const u8, model: []const u8) Provider {
return .{
.id = spec.id,
diff --git a/src/providers.zig b/src/providers.zig
index a8dd79cf..25b4c7ab 100644
--- a/src/providers.zig
+++ b/src/providers.zig
@@ -23,6 +23,10 @@ const textMessage = messages_mod.textMessage;
const ansi = @import("ansi.zig");
const fallback_config = @import("fallback_config.zig");
+fn localProviderUrl(url: []const u8) bool {
+ return std.mem.startsWith(u8, url, "http://127.0.0.1") or std.mem.startsWith(u8, url, "http://localhost") or std.mem.startsWith(u8, url, "http://[::1]");
+}
+
const main_mod = @import("main.zig");
const agent_mod = @import("agent.zig");
const provider_mod = @import("provider.zig");
@@ -229,14 +233,15 @@ pub fn resolveProviderControlRequest(
for (provider_specs) |spec| {
if (!std.mem.eql(u8, spec.id, provider_id)) continue;
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);
}
return error.InvalidProvider;
}
if (model.len != 0) {
- const resolved = resolveModelName(keys.*, model);
- const name = try arena.dupe(u8, resolved orelse model);
+ const resolved = resolveModelName(keys.*, model) orelse return error.InvalidModel;
+ const name = try arena.dupe(u8, resolved);
return keys.providerFor(name);
}
@@ -252,6 +257,7 @@ fn resolveProviderRequest(keys: *Keys, arena: Allocator, query: []const u8) !Pro
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 (!localProviderUrl(spec.url) and !pricing.providerModelInTable(pid, mdl)) return error.InvalidModel;
const m = try arena.dupe(u8, mdl);
return keys.providerById(pid, m);
}
@@ -262,8 +268,8 @@ fn resolveProviderRequest(keys: *Keys, arena: Allocator, query: []const u8) !Pro
return keys.providerById(spec.id, pricing.providerDefaultModel(spec.id, spec.default_model));
}
- const resolved = resolveModelName(keys.*, arg);
- const name = try arena.dupe(u8, resolved orelse arg);
+ const resolved = resolveModelName(keys.*, arg) orelse return error.InvalidModel;
+ const name = try arena.dupe(u8, resolved);
return keys.providerFor(name);
}
@@ -324,7 +330,7 @@ test "nextFallbackProvider: rotates after the failed provider and skips missing
const exhausted = [_][]const u8{ "codex", "codegraff", "openai" };
try std.testing.expect(nextFallbackProvider(sparse, "openai", &exhausted, &allow_all) == null);
const allow_codegraff = [_][]const u8{"codegraff"};
- try std.testing.expect(nextFallbackProvider(sparse, "codex", &tried_codex, &allow_codegraff).?.id.ptr == "codegraff".ptr);
+ try std.testing.expectEqualStrings("codegraff", nextFallbackProvider(sparse, "codex", &tried_codex, &allow_codegraff).?.id);
}
test "translateHistory: flattens to {role,content:string}, keeps user/assistant, drops the rest" {
@@ -363,6 +369,11 @@ test "set_model control resolves explicit provider/model fields" {
const legacy = try resolveProviderControlRequest(&all, arena, "", "", "codegraff gpt-5.5");
try std.testing.expectEqualStrings("codegraff", legacy.id);
try std.testing.expectEqualStrings("gpt-5.5", legacy.model);
+ try std.testing.expectError(error.InvalidModel, resolveProviderControlRequest(&all, arena, "", "definitely-not-a-model", ""));
+ try std.testing.expectError(error.InvalidModel, resolveProviderControlRequest(&all, arena, "openai", "definitely-not-a-model", ""));
+
+ const local = try resolveProviderControlRequest(&all, arena, "lmstudio", "user-loaded/model", "");
+ try std.testing.expectEqualStrings("user-loaded/model", local.model);
}
test "extractText: string content, joined text blocks, and empties" {
diff --git a/src/repl_glue.zig b/src/repl_glue.zig
index 6f5ed3ce..10e4896f 100644
--- a/src/repl_glue.zig
+++ b/src/repl_glue.zig
@@ -46,6 +46,9 @@ pub const ReplCtx = struct {
keys: Keys,
home: []const u8,
provider: Provider,
+ fallback_allow: []const []const u8,
+ fallback_active: bool,
+ fallback_blocked: bool,
registry: ?*mcp.Registry,
sys_normal: []const u8,
tools_anthropic: []const u8,
@@ -207,6 +210,9 @@ pub fn replTurnCb(ctx_ptr: ?*anyopaque, gpa: Allocator, history: []const repl.Tu
.ultra => .ultra,
},
.fast = params.fast,
+ .fallback_allow = c.fallback_allow,
+ .fallback_active = c.fallback_active,
+ .fallback_blocked = c.fallback_blocked,
.ultracode_mode = params.ultracode,
.show_thinking = params.thinking,
};
@@ -218,7 +224,11 @@ pub fn replTurnCb(ctx_ptr: ?*anyopaque, gpa: Allocator, history: []const repl.Tu
};
agent.messages.append(textMessage(arena, role, t.text) catch return null) catch return null;
}
- defer c.provider = agent.provider;
+ defer {
+ c.provider = agent.provider;
+ c.fallback_active = agent.fallback_active;
+ c.fallback_blocked = agent.fallback_blocked;
+ }
const final = providers.runTurnWithFallback(&agent, c.keys, arena, &sink.writer) catch |err| switch (err) {
// A mid-stream stall (#134): the repl turn IS live (stream_quiet=false),
// so postStream can return error.StreamStalled. Don't collapse it to
@@ -232,6 +242,7 @@ pub fn replTurnCb(ctx_ptr: ?*anyopaque, gpa: Allocator, history: []const repl.Tu
else
gpa.dupe(u8, "[response ended early: stream stalled]") catch null;
},
+ error.FallbackConsentRequired => return gpa.dupe(u8, "Saved model unavailable. Allow this provider with /fallback in the standard REPL, or choose another model.") catch null,
else => return null,
};
const trimmed = std.mem.trim(u8, final, " \t\r\n");
@@ -245,8 +256,10 @@ pub fn replTurnCb(ctx_ptr: ?*anyopaque, gpa: Allocator, history: []const repl.Tu
/// `c.provider`, never this preference file.
pub fn replModelCb(ctx_ptr: ?*anyopaque, gpa: Allocator, name: []const u8) ?[]const u8 {
const c: *ReplCtx = @ptrCast(@alignCast(ctx_ptr orelse return null));
- const resolved = pricing.resolveModelName(c.keys, name) orelse name;
+ const resolved = pricing.resolveModelName(c.keys, name) orelse return null;
c.provider = c.keys.providerFor(gpa.dupe(u8, resolved) catch return null) catch return null;
+ c.fallback_active = false;
+ c.fallback_blocked = false;
serde.saveModel(c.io, c.home, c.provider.id, c.provider.model);
return gpa.dupe(u8, c.provider.model) catch null;
}
diff --git a/src/session_run.zig b/src/session_run.zig
index 2a329bab..9e25e33b 100644
--- a/src/session_run.zig
+++ b/src/session_run.zig
@@ -68,6 +68,9 @@ pub fn runReplCommand(gpa: Allocator, io: Io, environ_map: anytype, root: *agent
.keys = keys,
.home = root.home,
.provider = root.provider,
+ .fallback_allow = root.fallback_allow,
+ .fallback_active = root.fallback_active,
+ .fallback_blocked = root.fallback_blocked,
.registry = root.registry,
.sys_normal = root.sys_normal,
.tools_anthropic = root.tools_anthropic,
@@ -110,6 +113,7 @@ pub fn runOneshotPrompt(gpa: Allocator, io: Io, arena: Allocator, root: *agent_m
try root.messages.append(try messages_mod.textMessage(arena, "user", oneshot_user));
if (telemetry.g_telem) |t| t.countTurn();
const final_text = providers.runTurnWithFallback(root, keys, arena, null) catch |err| switch (err) {
+ error.FallbackConsentRequired => std.process.fatal("saved model unavailable; provider '{s}' is not allowlisted — run graff interactively, then /fallback allow {s}", .{ root.provider.id, root.provider.id }),
error.ApiError => std.process.fatal("{s}", .{root.last_api_error orelse "api error"}),
else => |e| std.process.fatal("turn failed: {t}", .{e}),
};
diff --git a/src/session_start.zig b/src/session_start.zig
index f25aa42c..5a523a66 100644
--- a/src/session_start.zig
+++ b/src/session_start.zig
@@ -42,6 +42,7 @@ const telemetry = @import("telemetry.zig");
const util = @import("util.zig");
const ansi = @import("ansi.zig");
const title_mod = @import("title.zig");
+const fallback_config = @import("fallback_config.zig");
const repl = @import("repl.zig");
const pickers = @import("pickers.zig");
const repl_glue = @import("repl_glue.zig");
@@ -80,6 +81,7 @@ pub fn setupWorktreeAndBanner(
trace_path: []const u8,
codex_account: ?[]const u8,
stale_saved_model: ?[]const u8,
+ preferred_provider: ?[]const u8,
default_provider: provider_mod.Provider,
) !void {
// Color only on an interactive terminal, and honor NO_COLOR.
@@ -137,7 +139,18 @@ pub fn setupWorktreeAndBanner(
try out.flush();
}
if (stale_saved_model) |nm| {
- try out.print("{s}note: saved model '{s}' is unavailable with the current catalog/credentials — using {s} via {s} for this session; saved preference kept{s}\n", .{ style.dim, nm, default_provider.model, default_provider.id, style.reset });
+ const allowed = fallback_config.load(io, arena);
+ const cross_provider = preferred_provider != null and !std.mem.eql(u8, preferred_provider.?, default_provider.id);
+ const blocked = cross_provider and !fallback_config.contains(allowed, default_provider.id);
+ try out.print("{s}note: saved model '{s}' is unavailable — selected {s} via {s} for this session; saved preference kept{s}{s}\n", .{
+ style.dim,
+ nm,
+ default_provider.model,
+ default_provider.id,
+ if (blocked) ". Cross-provider use is blocked until /fallback allow " else "",
+ if (blocked) default_provider.id else "",
+ });
+ try out.writeAll(style.reset);
try out.flush();
}
if (main_mod.show_timing or main_mod.show_cost) {
diff --git a/src/startup.zig b/src/startup.zig
index 3d4c4caa..210b2071 100644
--- a/src/startup.zig
+++ b/src/startup.zig
@@ -41,6 +41,7 @@ pub const ResolvedKeys = struct {
keys: provider_mod.Keys,
default_provider: provider_mod.Provider,
stale_saved_model: ?[]const u8,
+ preferred_provider: ?[]const u8,
codex_account: ?[]const u8,
};
@@ -53,16 +54,21 @@ pub const ResolvedKeys = struct {
/// --model value).
pub fn resolveKeys(io: Io, gpa: Allocator, arena: Allocator, environ_map: anytype, model_flag: ?[]const u8) !ResolvedKeys {
var keys: provider_mod.Keys = .{ .values = undefined };
- for (provider_mod.provider_specs, &keys.values) |spec, *value| {
+ for (provider_mod.provider_specs, &keys.values, &keys.sources) |spec, *value, *source| {
value.* = environ_map.get(spec.env_key);
+ source.* = if (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.
if (keys_cli.homeEnv(environ_map)) |home| {
- for (provider_mod.provider_specs, &keys.values) |spec, *value| {
- if (std.mem.eql(u8, spec.id, "codegraff") and value.* == null)
- value.* = oauth.loadCodegraffKey(io, arena, home);
+ for (provider_mod.provider_specs, &keys.values, &keys.sources) |spec, *value, *source| {
+ if (std.mem.eql(u8, spec.id, "codegraff") and value.* == null) {
+ if (oauth.loadCodegraffKey(io, arena, home)) |key| {
+ value.* = key;
+ source.* = .login;
+ }
+ }
}
}
// Codex "login": read the ChatGPT OAuth token from CODEX_HOME/auth.json
@@ -73,8 +79,11 @@ pub fn resolveKeys(io: Io, gpa: Allocator, arena: Allocator, environ_map: anytyp
const codex_home = environ_map.get("CODEX_HOME") orelse
(std.fmt.allocPrint(arena, "{s}/.codex", .{home}) catch "");
if (oauth.loadCodexAuthFrom(io, arena, codex_home)) |auth| {
- for (provider_mod.provider_specs, &keys.values) |spec, *value| {
- if (std.mem.eql(u8, spec.id, "codex")) value.* = auth.token;
+ for (provider_mod.provider_specs, &keys.values, &keys.sources) |spec, *value, *source| {
+ if (std.mem.eql(u8, spec.id, "codex")) {
+ value.* = auth.token;
+ source.* = .login;
+ }
}
keys.codex_account = auth.account;
codex_account = auth.account;
@@ -84,16 +93,25 @@ pub fn resolveKeys(io: Io, gpa: Allocator, arena: Allocator, environ_map: anytyp
// (~/.kimi/credentials/graff-oauth.json), refreshed in place when near
// expiry. Same on-disk-credential pattern as codex/codegraff; env wins.
if (keys_cli.homeEnv(environ_map)) |home| {
- for (provider_mod.provider_specs, &keys.values) |spec, *value| {
- if (std.mem.eql(u8, spec.id, "kimi") and value.* == null)
- value.* = oauth.loadKimiOAuth(io, gpa, arena, home);
+ for (provider_mod.provider_specs, &keys.values, &keys.sources) |spec, *value, *source| {
+ if (std.mem.eql(u8, spec.id, "kimi") and value.* == null) {
+ if (oauth.loadKimiOAuth(io, gpa, arena, home)) |key| {
+ value.* = key;
+ source.* = .login;
+ }
+ }
}
}
// Stored keys (macOS Keychain / 0600 file via `harness key set`): fill any
// provider slot still empty after env + the login loaders. env always wins.
if (keys_cli.homeEnv(environ_map)) |home| {
- for (provider_mod.provider_specs, &keys.values) |spec, *value| {
- if (value.* == null) value.* = keys_cli.loadStoredKey(io, arena, home, spec.id);
+ for (provider_mod.provider_specs, &keys.values, &keys.sources) |spec, *value, *source| {
+ if (value.* == null) {
+ if (keys_cli.loadStoredKey(io, arena, home, spec.id)) |key| {
+ value.* = key;
+ source.* = .stored;
+ }
+ }
}
}
// Discover the account-scoped Codex catalog before model selection. This
@@ -128,6 +146,7 @@ pub fn resolveKeys(io: Io, gpa: Allocator, arena: Allocator, environ_map: anytyp
, .{});
};
var stale_saved_model: ?[]const u8 = null;
+ 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)) {
@@ -137,9 +156,10 @@ pub fn resolveKeys(io: Io, gpa: Allocator, arena: Allocator, environ_map: anytyp
break :pick;
} else |_| std.process.fatal("no key/login for provider '{s}' (--model)", .{mname});
};
- const nm = pricing.resolveModelName(keys, mname) orelse 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 std.process.fatal("no key/login for --model '{s}' — see /models", .{mname});
} else if (serde.loadModel(io, arena, keys_cli.homeEnv(environ_map) orelse "")) |saved| {
+ preferred_provider = saved.pid;
// No --model flag: resume the model chosen last session only if that
// exact provider/model pair is still in the catalog; model names can be
// shared by providers with different support.
@@ -162,7 +182,7 @@ pub fn resolveKeys(io: Io, gpa: Allocator, arena: Allocator, environ_map: anytyp
}
}
}
- return .{ .keys = keys, .default_provider = default_provider, .stale_saved_model = stale_saved_model, .codex_account = codex_account };
+ return .{ .keys = keys, .default_provider = default_provider, .stale_saved_model = stale_saved_model, .preferred_provider = preferred_provider, .codex_account = codex_account };
}
pub const SystemPrompt = struct {