Skip to content

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

Python

wip: prepare v0.0.193 REPL UX handoff

Codegraff2f657059da3b
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index a1ce6c82..ed13618e 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -54,6 +54,12 @@ jobs:
- name: PTY REPL interaction test
run: python3 scripts/test-pty-repl.py zig-out/bin/graff
+ - name: PTY Markdown rendering test
+ run: python3 scripts/test-pty-markdown.py zig-out/bin/graff
+
+ - name: PTY model preference and fallback test
+ run: python3 scripts/test-model-preference.py zig-out/bin/graff
+
- name: SDK generation drift
run: |
python3 sdk/generate.py --harness ./zig-out/bin/graff
diff --git a/README.md b/README.md
index 1c66f72f..ebde6275 100644
--- a/README.md
+++ b/README.md
@@ -394,6 +394,12 @@ scrolling up to re-read earlier output works like any normal terminal (parity wi
Claude Code). Folding the Thinking block is keyboard-only (`^T`). There is no
click-to-fold.
+Streaming Markdown is rendered for terminal readability: heading levels get a
+clear colored hierarchy; bullets, numbered items, nested lists, task checkboxes,
+and blockquotes use terminal-native markers; bold and inline code drop their raw
+delimiters; tables align; and fenced code stays copyable without decorative
+prefixes on body lines.
+
```
/model [name] no arg → interactive fuzzy picker; or /model <name|provider|provider model>
/models list known models, context windows, compaction points
@@ -425,11 +431,18 @@ The line editor supports ↑/↓ history (persisted to `~/.simple-harness-histor
Tab completion (commands, and model names after `/model `), and emacs-style
editing (Ctrl-A/E/W/U/K, Option+Delete, word moves). The selected model is
remembered in `~/.simple-harness-model` and resumed next launch
-(`--model <name>` overrides; a remembered model that's no longer in the table is
-ignored with a note). The prompt is a small statusline:
-`[model · Extra high · Fast · Plan · cwd /repo · 12345/800k tok (1%) · ⚡cached]`.
-Active modes are visible at a glance: Low is green, Medium cyan, High yellow,
-Extra high/Ultra/Ultracode magenta, Max/Strict/YOLO red, and Plan yellow.
+(`--model <name>` overrides). If the remembered provider/model is absent from
+the current catalog or its credentials are missing, graff falls back for that
+session with a note, without overwriting the preference. If the preferred
+provider later returns a clear authentication, access, removed-model, quota, or
+credit failure before producing text or running tools, graff tries the next
+configured provider and keeps the saved preference for a future launch. The
+prompt is a small statusline:
+`[model · Fast · Extra high · Plan · cwd /repo · 12345/800k tok (1%) · ⚡cached]`.
+Fast stays immediately beside the model. Active reasoning/workflow modes are
+visible at a glance: Low is green, Medium cyan, High yellow, Extra
+high/Ultra/Ultracode magenta, Max/Strict red, and Plan yellow. YOLO is reported
+as an explicit warning when enabled instead of occupying the compact prompt.
Badges for unsupported settings are hidden instead of implying they apply. The
tail shows context used vs the compaction budget, last cache hit, and (for
metered providers) session spend.
@@ -566,7 +579,10 @@ heads-up that it grants arbitrary code execution.
**Path confinement.** `read_file`/`write_file`/`edit_file` are confined to the
working-directory subtree: no absolute paths, no `..`. This is structural (not
bypassed by `/yolo`): `read_file /etc/shadow` and `write_file ../../x` are
-refused with an error.
+refused with an error. When the user explicitly names a sibling repository, the
+root agent can continue there through permission-gated bash without relaunching;
+it checks the target's git status first and quotes its path. Those external edits
+are deliberately not tracked by `/rewind`, and subagents remain confined.
**bash is cwd-locked by default too.** A seed/approved command auto-runs only
when all its path arguments stay in the cwd (`escapesCwd` rejects absolute, `~`,
diff --git a/TODO.md b/TODO.md
new file mode 100644
index 00000000..37e2d7cc
--- /dev/null
+++ b/TODO.md
@@ -0,0 +1,46 @@
+# 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.
+
+## Implemented
+
+- Terminal Markdown hierarchy, lists, task boxes, quotes, inline styles, and a
+ deterministic real-PTY regression.
+- Colored prompt modes with `Fast` prioritized and YOLO moved to warning/status
+ output.
+- Explicit sibling-repository guidance that preserves native cwd confinement.
+- Persisted model choice plus session-local model/provider fallback plumbing.
+- Real-PTY model preference, missing-credential fallback, rollout replacement,
+ 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.
+
+## 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`.
+- No release tag, GitHub release, or deployment has been created.
+
+## Scope warning
+
+The unrelated untracked design drafts (`Agentic_Operating_System.md`,
+`graff-dgm.md`, `phase2-escalation.md`, and `vision.md`) are user-owned and were
+not included in this branch.
diff --git a/docs/debugging-the-harness.md b/docs/debugging-the-harness.md
index 07cda391..485c8a60 100644
--- a/docs/debugging-the-harness.md
+++ b/docs/debugging-the-harness.md
@@ -38,7 +38,15 @@ Full-screen pickers can be driven with real key sequences:
```bash
scripts/pty-debug.py --bin zig-out/bin/graff \
--cmd /effort --expect 'Reasoning level for' \
- --key down --key enter --expect 'reasoning effort:'
+ --key down --key enter --expect 'reasoning effort:'
+```
+
+The Markdown renderer has its own deterministic PTY fixture—no model call:
+
+```bash
+zig-out/bin/graff --selftest-markdown
+python3 scripts/test-pty-markdown.py zig-out/bin/graff
+python3 scripts/test-model-preference.py zig-out/bin/graff
```
Useful debugging options:
diff --git a/scripts/test-model-preference.py b/scripts/test-model-preference.py
new file mode 100755
index 00000000..8a24d84f
--- /dev/null
+++ b/scripts/test-model-preference.py
@@ -0,0 +1,152 @@
+#!/usr/bin/env python3
+"""Real-PTY regression for persisted model preference and startup fallback."""
+
+from __future__ import annotations
+
+import json
+import os
+import sys
+import tempfile
+import time
+from pathlib import Path
+
+from pty_harness import PtySession
+
+
+_arg = sys.argv[1] if len(sys.argv) > 1 else "graff"
+GRAFF = os.path.abspath(_arg) if os.sep in _arg else _arg
+PROVIDER_KEYS = (
+ "ANTHROPIC_API_KEY",
+ "DEEPSEEK_API_KEY",
+ "OPENAI_API_KEY",
+ "MINIMAX_API_KEY",
+ "XIAOMI_API_KEY",
+ "KIMI_API_KEY",
+ "MOONSHOT_API_KEY",
+ "XAI_API_KEY",
+ "ZAI_API_KEY",
+ "FUGU_API_KEY",
+ "FIREWORKS_API_KEY",
+ "MLX_API_KEY",
+ "LMSTUDIO_API_KEY",
+ "CODEX_DISABLED",
+)
+
+
+def launch(
+ cwd: str,
+ env: dict[str, str],
+ *,
+ codex_home: str | None,
+) -> PtySession:
+ child_env = dict(env)
+ if codex_home is not None:
+ child_env["CODEX_HOME"] = codex_home
+ return PtySession(
+ GRAFF,
+ ["--no-telemetry"],
+ cwd=cwd,
+ env=child_env,
+ unset_env=PROVIDER_KEYS + (("CODEX_HOME",) if codex_home is None else ()) + ("NO_COLOR",),
+ timeout=15.0,
+ )
+
+
+def clean_exit(session: PtySession) -> None:
+ session.send_key("ctrl-d")
+ result = session.read_until_exit(5.0)
+ if result.timed_out or result.exit_code != 0:
+ raise AssertionError(
+ f"REPL did not exit cleanly: exit={result.exit_code} timed_out={result.timed_out}"
+ )
+
+
+def main() -> None:
+ with tempfile.TemporaryDirectory(prefix="graff-model-pref-") as tmp:
+ base = Path(tmp)
+ home = base / "home"
+ cwd = base / "repo"
+ codex_home = base / "codex-home"
+ home.mkdir()
+ cwd.mkdir()
+ codex_home.mkdir()
+ (codex_home / "auth.json").write_text(
+ json.dumps(
+ {
+ "auth_mode": "chatgpt",
+ "tokens": {
+ "access_token": "test-codex-token",
+ "account_id": "test-account",
+ },
+ }
+ ),
+ encoding="utf-8",
+ )
+ # Keep catalog discovery deterministic/offline: with Codex hidden from
+ # PATH, this fresh floor-version cache is accepted without an HTTP GET.
+ cache = home / ".codegraff-codex-models.json"
+ cache.write_text(
+ json.dumps(
+ {
+ "client_version": "0.144.1",
+ "fetched_at_ms": int(time.time() * 1000),
+ "models": [{"name": "gpt-5.6-sol", "context": 372000}],
+ }
+ ),
+ encoding="utf-8",
+ )
+ env = {
+ "HOME": str(home),
+ "PATH": "/usr/bin:/bin",
+ "CODEGRAFF_API_KEY": "local-pty-test",
+ "GRAFF_FLEET": "off",
+ "GRAFF_NO_TELEMETRY": "1",
+ }
+
+ # An explicit picker/command selection is persisted.
+ with launch(str(cwd), env, codex_home=str(codex_home)) as session:
+ session.wait_for_literal("] ›")
+ 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)
+ 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.
+ 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")
+ clean_exit(session)
+ assert preference.read_text(encoding="utf-8") == "codex\ngpt-5.6-sol\n"
+
+ # 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")
+ clean_exit(session)
+
+ # A removed rollout stays on the selected provider when that login is
+ # healthy and the live catalog advertises a replacement model.
+ cache.write_text(
+ json.dumps(
+ {
+ "client_version": "0.144.1",
+ "fetched_at_ms": int(time.time() * 1000),
+ "models": [{"name": "gpt-5.6-luna", "context": 372000}],
+ }
+ ),
+ encoding="utf-8",
+ )
+ 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")
+ clean_exit(session)
+ assert preference.read_text(encoding="utf-8") == "codex\ngpt-5.6-sol\n"
+
+ print("ok persisted preference, provider/model fallback, and preference recovery")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/scripts/test-pty-markdown.py b/scripts/test-pty-markdown.py
new file mode 100755
index 00000000..a9735e28
--- /dev/null
+++ b/scripts/test-pty-markdown.py
@@ -0,0 +1,58 @@
+#!/usr/bin/env python3
+"""Render the real streaming Markdown fixture in a PTY and verify its UI."""
+
+import os
+import sys
+import tempfile
+
+from pty_harness import run_to_exit
+
+
+_arg = sys.argv[1] if len(sys.argv) > 1 else "graff"
+GRAFF = os.path.abspath(_arg) if os.sep in _arg else _arg
+
+
+def main() -> None:
+ with tempfile.TemporaryDirectory(prefix="graff-md-pty-") as tmp:
+ result = run_to_exit(
+ GRAFF,
+ ["--selftest-markdown", "--no-telemetry"],
+ cwd=tmp,
+ env={
+ "HOME": tmp,
+ "LMSTUDIO_API_KEY": "local-pty-test",
+ "GRAFF_FLEET": "off",
+ "GRAFF_NO_TELEMETRY": "1",
+ },
+ unset_env=("CODEX_HOME", "NO_COLOR"),
+ rows=30,
+ cols=100,
+ timeout=15.0,
+ )
+ if result.timed_out or result.exit_code != 0:
+ raise SystemExit(
+ f"Markdown self-test failed: exit={result.exit_code} timed_out={result.timed_out}"
+ )
+ expected = (
+ "◆ Gaps",
+ "• No bot-specific route tests exist.",
+ "• Pin install.sh and verify its checksum.",
+ "◆ Recommended implementation order",
+ "1. Immediately: require collaborator permission.",
+ "2) Next: deduplicate X-GitHub-Delivery.",
+ "☐ Add a Daytona credential preflight.",
+ "☑ Sanitize public errors.",
+ " ◦ Preserve private incident detail.",
+ "│ Public errors must never expose secrets.",
+ )
+ missing = [line for line in expected if line not in result.text]
+ if missing:
+ raise SystemExit(f"Markdown render missing {missing!r}\n--- transcript ---\n{result.text}")
+ for ansi in (b"\x1b[36m", b"\x1b[33m", b"\x1b[32m"):
+ if ansi not in result.raw:
+ raise SystemExit(f"Markdown render missing ANSI style {ansi!r}")
+ print("ok PTY Markdown headings, lists, tasks, quotes, inline styles, and ANSI")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/scripts/test-pty-repl.py b/scripts/test-pty-repl.py
index eacaa506..8624d3c5 100755
--- a/scripts/test-pty-repl.py
+++ b/scripts/test-pty-repl.py
@@ -32,12 +32,17 @@ def main() -> None:
) as session:
session.wait_for_literal("] ›")
- def command(line: str, output: str, prompt: str, color_bytes: bytes) -> None:
+ def command(
+ line: str,
+ output: str,
+ prompt: str,
+ color_bytes: bytes | None,
+ ) -> None:
cursor = len(session.raw)
session.send_line(line)
session.wait_for_literal(output, start=cursor)
session.wait_for_literal(prompt, start=cursor)
- if color_bytes not in bytes(session.raw[cursor:]):
+ 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"
@@ -68,15 +73,26 @@ def main() -> None:
command(
"/yolo",
"yolo mode ON",
- f"[{base} · Plan · Strict · Ultracode · YOLO · cwd {tmp}]",
- b"\x1b[31mYOLO\x1b[0m",
+ f"[{base} · Plan · Strict · Ultracode · cwd {tmp}]",
+ None,
)
+ if b"\x1b[31mYOLO\x1b[0m" in bytes(session.raw):
+ raise AssertionError("YOLO should be reported outside the compact prompt")
+ cursor = len(session.raw)
+ session.send_line("/key no-such-provider supersecret")
+ session.wait_for_literal("unknown provider 'no-such-provider'", start=cursor)
+ session.wait_for_literal(f"cwd {tmp}]", start=cursor)
+ if b"supersecret" in bytes(session.raw[cursor:]):
+ raise AssertionError("/key secret was echoed to the terminal")
session.send_key("ctrl-d")
result = session.read_until_exit(5.0)
if result.timed_out or result.exit_code != 0:
raise SystemExit(
f"REPL did not exit cleanly: exit={result.exit_code} timed_out={result.timed_out}"
)
+ 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")
print("ok PTY REPL commands, colored mode badges, redraws, and clean exit")
diff --git a/src/agent.zig b/src/agent.zig
index c59839f1..b7e76250 100644
--- a/src/agent.zig
+++ b/src/agent.zig
@@ -108,6 +108,9 @@ pub const Agent = struct {
keep_context: bool = true, // carry the conversation across wire-format model switches (/keepcontext)
reasoning: ReasoningEffort = .medium, // reasoning/thinking depth — codex, deepseek, codegraff (/effort, /reasoning)
fast: bool = false, // codex "fast" mode → priority service_tier (/fast)
+ fallback_allow: []const []const u8 = &.{}, // explicit cross-provider allowlist from .harness/settings.json
+ fallback_active: bool = false, // current provider/model is a temporary fallback, not the saved preference
+ fallback_blocked: bool = false, // startup found a cross-provider fallback that is not allowlisted yet
ultracode_mode: bool = false, // persistent ultracode (multi-agent workflow) mode (/ultracode)
show_thinking: bool = true, // stream the model's reasoning live in the TUI (/thinking); off = spinner only
ai_title: bool = true, // AI-generate the tab/session title from the first prompt (/title)
@@ -169,12 +172,16 @@ pub const Agent = struct {
else
"";
try w.print("\n{s}[{s}{s}{s}{s}", .{ style.dim, style.reset, style.cyan, self.provider.model, style.reset });
- if (self.effortApplies()) try writePromptBadge(w, reasoningPromptColor(self.reasoning), reasoningPromptLabel(self.reasoning));
+ // Fast is the most operationally important model setting, so keep it
+ // immediately beside the model instead of letting permission modes
+ // push it deeper into the status line.
if (self.fast and self.provider.kind == .responses) try writePromptBadge(w, style.green, "Fast");
+ if (self.effortApplies()) try writePromptBadge(w, reasoningPromptColor(self.reasoning), reasoningPromptLabel(self.reasoning));
+ try writePromptBadge(w, style.cyan, self.provider.id);
+ if (self.fallback_active) try writePromptBadge(w, style.yellow, "Fallback");
if (main_mod.plan_mode) try writePromptBadge(w, style.yellow, "Plan");
if (self.strict) try writePromptBadge(w, style.red, "Strict");
if (self.ultracode_mode) try writePromptBadge(w, style.magenta, "Ultracode");
- if (self.approvals) |approvals| if (approvals.yoloEnabled(self.io)) try writePromptBadge(w, style.red, "YOLO");
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();
diff --git a/src/agent_render.zig b/src/agent_render.zig
index ad8f96fd..c52dd45e 100644
--- a/src/agent_render.zig
+++ b/src/agent_render.zig
@@ -45,6 +45,40 @@ pub const MdKind = enum { classify, hold, prose, header, fenced };
pub const MdSpan = enum { normal, star, bold, bold_star, code };
+const TaskItem = struct { checked: bool, text: []const u8 };
+
+fn taskItem(body: []const u8) ?TaskItem {
+ if (body.len < 6 or (body[0] != '-' and body[0] != '*' and body[0] != '+') or body[1] != ' ' or body[2] != '[' or body[4] != ']' or body[5] != ' ') return null;
+ if (body[3] != ' ' and body[3] != 'x' and body[3] != 'X') return null;
+ return .{ .checked = body[3] != ' ', .text = body[6..] };
+}
+
+fn headingColor(level: usize) []const u8 {
+ return if (level == 1) style.magenta else if (level == 2) style.cyan else style.yellow;
+}
+
+fn renderHeading(w: *Io.Writer, level: usize, text: []const u8) void {
+ const marker: []const u8 = if (level <= 2) "◆" else "▸";
+ w.print("{s}{s}{s} ", .{ style.bold, headingColor(level), marker }) catch {};
+ renderInline(w, text);
+ w.writeAll(style.reset) catch {};
+}
+
+fn mdStartItem(self: *Agent, w: *Io.Writer, held: []const u8, lead: usize, prefix_len: usize, marker: []const u8, color: []const u8) void {
+ self.md_kind = .prose;
+ self.md_span = .normal;
+ self.md_col = lead + 2;
+ self.md_indent = lead + 2;
+ w.writeAll(held[0..lead]) catch {};
+ w.print("{s}{s}{s} ", .{ color, marker, style.reset }) catch {};
+ const rest = held[lead + prefix_len ..];
+ var tmp: [8]u8 = undefined;
+ const n = @min(rest.len, tmp.len);
+ @memcpy(tmp[0..n], rest[0..n]);
+ self.md_buf.clearRetainingCapacity();
+ for (tmp[0..n]) |rb| self.mdSpanByte(w, rb);
+}
+
pub fn mdByte(self: *Agent, w: *Io.Writer, b: u8) void {
if (b == '\n') {
// A swallowed line (table row joining the buffer) keeps its
@@ -106,33 +140,24 @@ pub fn mdTryClassify(self: *Agent, w: *Io.Writer) void {
self.mdStartProse(w);
return;
}
- // Header. Mirror renderMdLine's left-trim: wait for the first
- // non-space byte of the title, then style and stream.
+ // Hold headings to line end so inline bold/code renders too.
var ns = hn + 1;
while (ns < body.len and body[ns] == ' ') ns += 1;
if (ns == body.len) return;
- self.md_kind = .header;
- w.print("{s}{s}{s}", .{ style.bold, style.cyan, body[ns..] }) catch {};
- self.md_buf.clearRetainingCapacity();
+ self.md_kind = .hold;
},
'|' => self.md_kind = .hold, // table row: cells need the whole line
'-', '_', '*', '+' => {
const run = countPrefix(body, body[0]);
if (body[0] != '+' and run == body.len) return; // possible rule
if ((body[0] == '-' or body[0] == '*' or body[0] == '+') and run == 1 and body.len >= 2 and body[1] == ' ') {
- // Bullet: emit indent + styled marker, stream the rest.
- self.md_kind = .prose;
- self.md_span = .normal;
- self.md_col = lead + 2; // "• " — wrapped lines align under the text
- self.md_indent = lead + 2;
- w.writeAll(held[0..lead]) catch {};
- w.print("{s}•{s} ", .{ style.cyan, style.reset }) catch {};
- const rest = body[2..];
- self.md_buf.clearRetainingCapacity(); // before re-dispatch
- var tmp: [8]u8 = undefined;
- const n = @min(rest.len, tmp.len);
- @memcpy(tmp[0..n], rest[0..n]);
- for (tmp[0..n]) |rb| self.mdSpanByte(w, rb);
+ if (body.len == 2) return;
+ if (body[2] == '[' and body.len < 6) return;
+ if (taskItem(body)) |task| {
+ mdStartItem(self, w, held, lead, 6, if (task.checked) "☑" else "☐", if (task.checked) style.green else style.yellow);
+ } else {
+ mdStartItem(self, w, held, lead, 2, if (lead == 0) "•" else "◦", style.cyan);
+ }
return;
}
if (body[0] == '+' and body.len == 1) return; // "+ " bullet still possible
@@ -150,7 +175,7 @@ pub fn mdTryClassify(self: *Agent, w: *Io.Writer) void {
self.md_col = lead + d + 2; // "12. " — align under the text
self.md_indent = lead + d + 2;
w.writeAll(held[0..lead]) catch {};
- w.print("{s}{s}.{s} ", .{ style.cyan, body[0..d], style.reset }) catch {};
+ w.print("{s}{s}{c}{s} ", .{ style.cyan, body[0..d], body[d], style.reset }) catch {};
const rest = body[d + 2 ..];
var tmp: [8]u8 = undefined;
const n = @min(rest.len, tmp.len);
@@ -162,6 +187,14 @@ pub fn mdTryClassify(self: *Agent, w: *Io.Writer) void {
}
self.mdStartProse(w);
},
+ '>' => {
+ if (body.len == 1) return;
+ if (body[1] == ' ') {
+ mdStartItem(self, w, held, lead, 2, "│", style.dim);
+ return;
+ }
+ self.mdStartProse(w);
+ },
else => self.mdStartProse(w),
}
}
@@ -417,7 +450,7 @@ pub fn renderMdLine(self: *Agent, w: *Io.Writer, line: []const u8) void {
while (h < body.len and body[h] == '#') h += 1;
if (h >= 1 and h <= 6 and h < body.len and body[h] == ' ') {
const head = std.mem.trim(u8, body[h + 1 ..], " ");
- w.print("{s}{s}{s}{s}", .{ style.bold, style.cyan, head, style.reset }) catch {};
+ renderHeading(w, h, head);
return;
}
// Horizontal rule: a line of only -, *, or _ (3+).
@@ -443,10 +476,22 @@ pub fn renderMdLine(self: *Agent, w: *Io.Writer, line: []const u8) void {
}
return;
}
+ if (taskItem(body)) |task| {
+ w.writeAll(line[0..lead]) catch {};
+ w.print("{s}{s}{s} ", .{ if (task.checked) style.green else style.yellow, if (task.checked) "☑" else "☐", style.reset }) catch {};
+ renderInline(w, task.text);
+ return;
+ }
+ if (std.mem.startsWith(u8, body, "> ")) {
+ w.writeAll(line[0..lead]) catch {};
+ w.print("{s}│{s} ", .{ style.dim, style.reset }) catch {};
+ renderInline(w, body[2..]);
+ return;
+ }
// Bullet list item.
if (std.mem.startsWith(u8, body, "- ") or std.mem.startsWith(u8, body, "* ") or std.mem.startsWith(u8, body, "+ ")) {
w.writeAll(line[0..lead]) catch {};
- w.print("{s}•{s} ", .{ style.cyan, style.reset }) catch {};
+ w.print("{s}{s}{s} ", .{ style.cyan, if (lead == 0) "•" else "◦", style.reset }) catch {};
renderInline(w, body[2..]);
return;
}
@@ -455,7 +500,7 @@ pub fn renderMdLine(self: *Agent, w: *Io.Writer, line: []const u8) void {
while (d < body.len and body[d] >= '0' and body[d] <= '9') d += 1;
if (d >= 1 and d + 1 < body.len and (body[d] == '.' or body[d] == ')') and body[d + 1] == ' ') {
w.writeAll(line[0..lead]) catch {};
- w.print("{s}{s}.{s} ", .{ style.cyan, body[0..d], style.reset }) catch {};
+ w.print("{s}{s}{c}{s} ", .{ style.cyan, body[0..d], body[d], style.reset }) catch {};
renderInline(w, body[d + 2 ..]);
return;
}
diff --git a/src/args.zig b/src/args.zig
index e1c8bd4f..79e7d006 100644
--- a/src/args.zig
+++ b/src/args.zig
@@ -40,6 +40,7 @@ pub const Flags = struct {
print_flag: bool = false,
update_force: bool = false, // graff update --force
selftest_spinner_flag: bool = false, // --selftest-spinner: headless spinner render for the PTY anti-stealth test
+ selftest_markdown_flag: bool = false, // --selftest-markdown: render the real streaming markdown fixture in a PTY
update_check: bool = false, // graff update --check
model_flag: ?[]const u8 = null,
system_prompt_flag: ?[]const u8 = null,
@@ -118,6 +119,8 @@ pub fn parse(init: std.process.Init) !Flags {
flags.version_flag = true;
} else if (std.mem.eql(u8, arg, "--selftest-spinner")) {
flags.selftest_spinner_flag = true;
+ } else if (std.mem.eql(u8, arg, "--selftest-markdown")) {
+ flags.selftest_markdown_flag = true;
} else if (std.mem.eql(u8, arg, "--print") or std.mem.eql(u8, arg, "-p")) {
flags.print_flag = true;
} else if (std.mem.eql(u8, arg, "--force")) {
diff --git a/src/commands_misc.zig b/src/commands_misc.zig
index d1f24173..04f1ba19 100644
--- a/src/commands_misc.zig
+++ b/src/commands_misc.zig
@@ -267,8 +267,10 @@ pub fn tryHandle(root: *Agent, keys: *Keys, arena: Allocator, line: []const u8,
}
if (std.mem.eql(u8, line, "/yolo")) {
const on = root.approvals.?.toggleYolo(root.io);
- try out.print("yolo mode {s} — {s}\n", .{
+ try out.print("yolo mode {s}{s}{s} — {s}\n", .{
+ if (on) style.red else style.green,
if (on) "ON" else "off",
+ style.reset,
if (on) "bash runs without asking" else "unapproved bash commands prompt y/a/n",
});
try out.flush();
diff --git a/src/fallback_config.zig b/src/fallback_config.zig
new file mode 100644
index 00000000..764fb62d
--- /dev/null
+++ b/src/fallback_config.zig
@@ -0,0 +1,70 @@
+//! Per-workspace automatic cross-provider fallback allowlist. Empty is the
+//! safe default: same-provider model replacement is allowed, but sending a
+//! prompt to another vendor requires an explicit `/fallback allow <provider>`.
+
+const std = @import("std");
+const Io = std.Io;
+const Allocator = std.mem.Allocator;
+const Value = std.json.Value;
+
+const settings_dir = ".harness";
+const settings_path = ".harness/settings.json";
+const field = "fallback_providers";
+
+pub fn contains(providers: []const []const u8, id: []const u8) bool {
+ for (providers) |provider| if (std.mem.eql(u8, provider, id)) return true;
+ return false;
+}
+
+pub fn load(io: Io, arena: Allocator) []const []const u8 {
+ const data = Io.Dir.cwd().readFileAlloc(io, settings_path, arena, .limited(1 << 20)) catch return &.{};
+ const parsed = std.json.parseFromSliceLeaky(Value, arena, data, .{ .allocate = .alloc_always }) catch return &.{};
+ if (parsed != .object) return &.{};
+ const raw = parsed.object.get(field) orelse return &.{};
+ if (raw != .array) return &.{};
+ var out: std.ArrayList([]const u8) = .empty;
+ for (raw.array.items) |item| {
+ if (item != .string or item.string.len == 0 or contains(out.items, item.string)) continue;
+ out.append(arena, item.string) catch return out.items;
+ }
+ return out.toOwnedSlice(arena) catch out.items;
+}
+
+pub fn save(io: Io, gpa: Allocator, providers: []const []const u8) bool {
+ Io.Dir.cwd().createDir(io, settings_dir, .default_dir) catch {};
+ var arena_state = std.heap.ArenaAllocator.init(gpa);
+ defer arena_state.deinit();
+ const arena = arena_state.allocator();
+ var root: std.json.ObjectMap = .empty;
+ if (Io.Dir.cwd().readFileAlloc(io, settings_path, arena, .limited(1 << 20))) |data| {
+ if (std.json.parseFromSliceLeaky(Value, arena, data, .{ .allocate = .alloc_always })) |parsed| {
+ if (parsed == .object) root = parsed.object;
+ } else |_| {}
+ } else |_| {}
+ if (providers.len == 0) {
+ _ = root.orderedRemove(field);
+ } else {
+ var array = std.json.Array.init(arena);
+ for (providers) |provider| array.append(.{ .string = provider }) catch return false;
+ root.put(arena, field, .{ .array = array }) catch return false;
+ }
+ var aw: Io.Writer.Allocating = .init(gpa);
+ defer aw.deinit();
+ var stringify: std.json.Stringify = .{ .writer = &aw.writer, .options = .{ .whitespace = .indent_2 } };
+ stringify.write(Value{ .object = root }) catch return false;
+ const file = Io.Dir.cwd().createFile(io, settings_path, .{}) catch return false;
+ defer file.close(io);
+ var buf: [4096]u8 = undefined;
+ var writer = file.writer(io, &buf);
+ writer.interface.writeAll(aw.writer.buffered()) catch return false;
+ writer.interface.writeByte('\n') catch return false;
+ writer.interface.flush() catch return false;
+ return true;
+}
+
+test "contains: exact provider ids only" {
+ const providers = [_][]const u8{ "codex", "anthropic" };
+ try std.testing.expect(contains(&providers, "codex"));
+ try std.testing.expect(!contains(&providers, "openai"));
+ try std.testing.expect(!contains(&providers, "code"));
+}
diff --git a/src/input_util.zig b/src/input_util.zig
index fd868bb1..92044915 100644
--- a/src/input_util.zig
+++ b/src/input_util.zig
@@ -22,6 +22,7 @@ const jobs = @import("jobs.zig");
const runCapped = jobs.runCapped;
const pricing = @import("pricing.zig");
+const util = @import("util.zig");
const main_mod = @import("main.zig");
const provider_mod = @import("provider.zig");
@@ -306,6 +307,7 @@ pub fn redraw(o: *Io.Writer, items: []const u8, c: usize, marks: []const []const
var vcol: usize = plen;
var mark_end: usize = 0;
var mark_open = false;
+ const secret_start = util.sensitiveInputStart(items);
// `ultracode` shines the input itself: each letter of every
// (case-insensitive) occurrence renders in a rotating rainbow hue.
var shine_starts: [8]usize = undefined;
@@ -325,6 +327,7 @@ pub fn redraw(o: *Io.Writer, items: []const u8, c: usize, marks: []const []const
}
var shine_active = false;
while (i < items.len) {
+ const masked = if (secret_start) |start| i >= start else false;
if (vcol >= cols) { // row full → wrap to the next
o.writeAll("\r\n") catch {};
row += 1;
@@ -347,7 +350,7 @@ pub fn redraw(o: *Io.Writer, items: []const u8, c: usize, marks: []const []const
}
}
// Rainbow shine for an `ultracode` span (skipped inside a chip).
- if (!mark_open) {
+ if (!mark_open and !masked) {
var in_shine = false;
for (shine_starts[0..nshine], shine_ends[0..nshine]) |sstart, send| {
if (i >= sstart and i < send) {
@@ -366,7 +369,7 @@ pub fn redraw(o: *Io.Writer, items: []const u8, c: usize, marks: []const []const
shine_active = false;
}
}
- o.writeByte(items[i]) catch {};
+ o.writeByte(if (masked) '*' else items[i]) catch {};
vcol += 1;
i += 1;
if (mark_open and i == mark_end) {
diff --git a/src/main.zig b/src/main.zig
index 8b60b121..338083f6 100644
--- a/src/main.zig
+++ b/src/main.zig
@@ -358,10 +358,10 @@ pub fn main(init: std.process.Init) !void {
// `graff repl`: interactive chat REPL on the zigzag TUI, backed by the REAL agent loop — each prompt runs a full root turn (tools + MCP) via
// replTurnCb, reusing the root agent's tool set + registry + system prompt. Self-contained — exits after.
- if (try session_run.runReplCommand(gpa, io, init.environ_map, &root, &client, in, out, arena, flags)) return;
+ if (try session_run.runReplCommand(gpa, io, init.environ_map, &root, keys, &client, in, out, arena, flags)) return;
// One-shot print mode: run the single prompt to completion, print the final text to stdout, exit.
if (flags.oneshot_prompt) |prompt_text| {
- try session_run.runOneshotPrompt(gpa, io, arena, &root, &tracer, out, prompt_text);
+ try session_run.runOneshotPrompt(gpa, io, arena, &root, keys, &tracer, out, prompt_text);
return;
}
@@ -494,9 +494,9 @@ test "incremental markdown streaming renders like renderMdLine" {
try std.testing.expectEqualStrings("• has bold spans\n", aw.writer.buffered());
aw.clearRetainingCapacity();
- // Numbered items, headers, inline code.
- a.streamMarkdown("12) point\n## Title\nuse `zig build` here\n");
- try std.testing.expectEqualStrings("12. point\nTitle\nuse zig build here\n", aw.writer.buffered());
+ // Numbered/task/nested items, headings, quotes, and inline code.
+ a.streamMarkdown("12) **Immediately:** point\n## Title\nuse `zig build` here\n- [ ] ship it\n - nested\n> warning\n");
+ try std.testing.expectEqualStrings("12) Immediately: point\n◆ Title\nuse zig build here\n☐ ship it\n ◦ nested\n│ warning\n", aw.writer.buffered());
aw.clearRetainingCapacity();
// Fences: open/close render as labeled dim rules, body streams unprefixed.
diff --git a/src/mainloop.zig b/src/mainloop.zig
index 453d57d8..7ee733ea 100644
--- a/src/mainloop.zig
+++ b/src/mainloop.zig
@@ -437,7 +437,7 @@ pub fn run(ctx: *Ctx) !void {
// A failed turn must never kill the session: ApiError is already
// reported inside request(); anything else is surfaced here. Either
// way we drop back to the prompt (or emit a JSON error/turn event).
- const turn_result = ctx.root.runTurn();
+ const turn_result = providers.runTurnWithFallback(ctx.root, ctx.keys.*, ctx.arena, ctx.out);
if (trace.g_traj) |tj| {
const fp = scoring.promptFingerprint(ctx.root.systemPrompt());
const turn_ms: i64 = @intCast(@max(0, turn_started.untilNow(ctx.io, .awake).toMilliseconds()));
diff --git a/src/prompts.zig b/src/prompts.zig
index 21849aac..23ed7e86 100644
--- a/src/prompts.zig
+++ b/src/prompts.zig
@@ -13,7 +13,13 @@ pub const main_system_prompt =
\\files or full rewrites. To navigate code — finding symbols, callers,
\\definitions, or where logic lives — prefer the codedb tool (it's indexed
\\and structural) over bash grep/find/ls. Some bash commands need user approval — if one
- \\is declined, try another approach or ask. For independent,
+ \\is declined, try another approach or ask. Native file tools deliberately
+ \\stay inside the current working directory. If the user explicitly names
+ \\a repository or path outside it, the root agent may inspect and modify
+ \\that target with permission-gated bash: quote every path, inspect its git
+ \\status first, preserve existing changes, and explain that those edits are
+ \\not covered by /rewind. Do not claim a relaunch is required. Never extend
+ \\this exception to an inferred path or to a subagent. For independent,
\\self-contained chunks of work — exploring several directories, running
\\unrelated checks, summarizing multiple files — fan out: call the
\\subagent tool several times in a single response and the subagents run
@@ -74,3 +80,12 @@ pub const compact_instruction =
\\pending or unfinished work. Be thorough but compact. Reply with only
\\the summary.
;
+
+test "root prompt permits explicit external targets without weakening confinement" {
+ const std = @import("std");
+ try std.testing.expect(std.mem.indexOf(u8, main_system_prompt, "explicitly names") != null);
+ try std.testing.expect(std.mem.indexOf(u8, main_system_prompt, "permission-gated bash") != null);
+ try std.testing.expect(std.mem.indexOf(u8, main_system_prompt, "not covered by /rewind") != null);
+ try std.testing.expect(std.mem.indexOf(u8, main_system_prompt, "Do not claim a relaunch is required") != null);
+ try std.testing.expect(std.mem.indexOf(u8, main_system_prompt, "Never extend") != null);
+}
diff --git a/src/providers.zig b/src/providers.zig
index 1944b40c..a8dd79cf 100644
--- a/src/providers.zig
+++ b/src/providers.zig
@@ -20,6 +20,8 @@ const saveModel = serde.saveModel;
const messages_mod = @import("messages.zig");
const textMessage = messages_mod.textMessage;
+const ansi = @import("ansi.zig");
+const fallback_config = @import("fallback_config.zig");
const main_mod = @import("main.zig");
const agent_mod = @import("agent.zig");
@@ -63,7 +65,7 @@ fn translateHistory(arena: Allocator, msgs: *std.json.Array, to_kind: Provider.K
msgs.* = out;
}
-pub fn applyProvider(root: *Agent, arena: Allocator, p: Provider) []const u8 {
+fn applyProviderInner(root: *Agent, arena: Allocator, p: Provider, persist: bool) []const u8 {
const same_format = root.provider.kind == p.kind;
var note: []const u8 = "context kept";
if (!same_format) {
@@ -78,11 +80,141 @@ pub fn applyProvider(root: *Agent, arena: Allocator, p: Provider) []const u8 {
}
root.cap_new = false; // per-provider token-cap quirk; relearn on rejection
root.effort_rejected = false; // new model may accept reasoning_effort; relearn
+ root.ws_off = false; // a previous Codex WS fallback must not leak across switches
root.provider = p;
- saveModel(root.io, root.home, p.id, p.model); // remember for next launch
+ root.fallback_active = !persist;
+ root.fallback_blocked = false;
+ if (persist) saveModel(root.io, root.home, p.id, p.model);
return note;
}
+/// An explicit /model or set_model selection becomes the next-launch default.
+pub fn applyProvider(root: *Agent, arena: Allocator, p: Provider) []const u8 {
+ return applyProviderInner(root, arena, p, true);
+}
+
+/// Automatic failover is session-local: preserve the user's saved preference
+/// so a repaired credential/model is tried again on the next fresh launch.
+pub fn applyFallbackProvider(root: *Agent, arena: Allocator, p: Provider) []const u8 {
+ return applyProviderInner(root, arena, p, false);
+}
+
+fn triedProvider(ids: []const []const u8, id: []const u8) bool {
+ for (ids) |candidate| if (std.mem.eql(u8, candidate, id)) return true;
+ return false;
+}
+
+/// Walk configured providers in stable priority order, beginning after the
+/// 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 {
+ 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;
+ 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;
+ 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));
+ }
+ return null;
+}
+
+/// Only failures that clearly mean "this credential/model cannot serve the
+/// request" are safe to fail over. Network flakes, rate limits, malformed
+/// replies, context overflow, and interrupts stay on the selected provider.
+pub fn failoverEligible(detail: []const u8) bool {
+ const needles = [_][]const u8{
+ "unauthorized",
+ "authentication_error",
+ "authentication token",
+ "authentication failed",
+ "invalid api key",
+ "invalid_api_key",
+ "invalid x-api-key",
+ "incorrect api key",
+ "api key not valid",
+ "invalid token",
+ "token expired",
+ "expired token",
+ "access token has expired",
+ "401",
+ "403",
+ "forbidden",
+ "access denied",
+ "permission denied",
+ "permission_denied",
+ "model_not_found",
+ "model not found",
+ "model is not available",
+ "model unavailable",
+ "model does not exist",
+ "does not exist or you do not have access",
+ "you do not have access to model",
+ "you do not have access to this model",
+ "insufficient_quota",
+ "quota exceeded",
+ "credits exhausted",
+ "insufficient credits",
+ "credit balance",
+ "no credits",
+ "billing limit",
+ };
+ for (needles) |needle| if (std.ascii.indexOfIgnoreCase(detail, needle) != null) return true;
+ return false;
+}
+
+/// Run a root turn and, before any text/tools have escaped, rotate through
+/// credential-backed providers on a clear auth/model/quota failure. Successful
+/// fallback becomes active for this session but does not replace the saved
+/// model preference.
+pub fn runTurnWithFallback(root: *Agent, keys: Keys, arena: Allocator, out: ?*Io.Writer) anyerror![]const u8 {
+ if (root.fallback_blocked) return error.FallbackConsentRequired;
+ var attempted: [provider_specs.len][]const u8 = undefined;
+ var attempted_len: usize = 1;
+ attempted[0] = root.provider.id;
+ while (true) {
+ root.last_api_error = null;
+ const result = root.runTurn();
+ if (result) |text| return text else |err| {
+ if (err != error.ApiError or root.partial_text.items.len != 0 or root.tool_calls_this_turn != 0)
+ return err;
+ const detail = root.last_api_error orelse return err;
+ if (!failoverEligible(detail)) return err;
+ const failed_id = root.provider.id;
+ const failed_model = root.provider.model;
+ const fallback = nextFallbackProvider(keys, failed_id, attempted[0..attempted_len], root.fallback_allow) orelse return err;
+ attempted[attempted_len] = fallback.id;
+ attempted_len += 1;
+ const note = applyFallbackProvider(root, arena, fallback);
+ if (main_mod.json_mode) {
+ root.emit(.{ .type = "model", .ok = true, .provider = fallback.id, .model = fallback.model, .context = fallback.context, .note = "automatic session fallback; saved model preference kept" });
+ } else if (out) |w| {
+ try w.print("{s}⚠ {s} via {s} is unavailable; trying {s} via {s} for this session ({s}) — saved default kept{s}\n", .{
+ ansi.style.yellow,
+ failed_model,
+ failed_id,
+ fallback.model,
+ fallback.id,
+ note,
+ ansi.style.reset,
+ });
+ try w.flush();
+ } else {
+ std.debug.print("⚠ {s} via {s} is unavailable; trying {s} via {s} for this session ({s}) — saved default kept\n", .{ failed_model, failed_id, fallback.model, fallback.id, note });
+ }
+ if (root.tracer) |tr| {
+ const trace_note = std.fmt.allocPrint(arena, "{s}/{s} -> {s}/{s}", .{ failed_id, failed_model, fallback.id, fallback.model }) catch "automatic provider fallback";
+ tr.note("model_fallback", trace_note);
+ }
+ }
+ }
+}
+
pub fn resolveProviderControlRequest(
keys: *Keys,
arena: Allocator,
@@ -151,7 +283,7 @@ pub fn setModelRequestLabel(arena: Allocator, provider_query: []const u8, model_
pub fn switchProvider(root: *Agent, arena: Allocator, p: Provider, out: *Io.Writer) !void {
const note = applyProvider(root, arena, p);
- try out.print("switched to {s} via {s} ({t} format, {d}k ctx) — {s}\n", .{
+ try out.print("switched to {s} via {s} ({t} format, {d}k ctx) — {s} · saved for next session\n", .{
p.model, p.id, p.kind, p.context / 1000, note,
});
try out.flush();
@@ -159,6 +291,42 @@ pub fn switchProvider(root: *Agent, arena: Allocator, p: Provider, out: *Io.Writ
// Tests moved from main.zig alongside the functions they cover (#123 split).
+test "failoverEligible: accepts unavailable credentials/models, rejects transient or prompt errors" {
+ try std.testing.expect(failoverEligible("codex api error: Unauthorized"));
+ try std.testing.expect(failoverEligible("access token has expired"));
+ try std.testing.expect(failoverEligible("model_not_found: rollout ended"));
+ try std.testing.expect(failoverEligible("insufficient_quota"));
+ try std.testing.expect(!failoverEligible("network error: HttpConnectionClosing"));
+ try std.testing.expect(!failoverEligible("rate limited (429)"));
+ try std.testing.expect(!failoverEligible("maximum context length exceeded"));
+ try std.testing.expect(!failoverEligible("unparseable response"));
+}
+
+test "nextFallbackProvider: rotates after the failed provider and skips missing or tried credentials" {
+ const all = Keys{ .values = [_]?[]const u8{"k"} ** provider_specs.len };
+ const tried_codex = [_][]const u8{"codex"};
+ const allow_all = blk: {
+ var ids: [provider_specs.len][]const u8 = undefined;
+ for (provider_specs, 0..) |spec, i| ids[i] = spec.id;
+ break :blk ids;
+ };
+ const wrapped = nextFallbackProvider(all, "codex", &tried_codex, &allow_all).?;
+ try std.testing.expectEqualStrings("anthropic", wrapped.id);
+
+ var values = [_]?[]const u8{null} ** provider_specs.len;
+ for (provider_specs, 0..) |spec, i| {
+ if (std.mem.eql(u8, spec.id, "codegraff") or std.mem.eql(u8, spec.id, "openai")) values[i] = "k";
+ }
+ const sparse = Keys{ .values = values };
+ const tried = [_][]const u8{ "codex", "codegraff" };
+ const next = nextFallbackProvider(sparse, "codex", &tried, &allow_all).?;
+ try std.testing.expectEqualStrings("openai", next.id);
+ 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);
+}
+
test "translateHistory: flattens to {role,content:string}, keeps user/assistant, drops the rest" {
var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena_state.deinit();
diff --git a/src/readline.zig b/src/readline.zig
index 5d9f096f..9810b68e 100644
--- a/src/readline.zig
+++ b/src/readline.zig
@@ -43,6 +43,7 @@ const delRange = input_util.delRange;
const prevWord = input_util.prevWord;
const nextWord = input_util.nextWord;
const addMark = input_util.addMark;
+const util = @import("util.zig");
const main_mod = @import("main.zig");
const agent_mod = @import("agent.zig");
@@ -590,7 +591,7 @@ pub fn readLine(
}
const trimmed = std.mem.trim(u8, buf.items, " \t\r");
- if (trimmed.len > 0 and (history.items.len == 0 or !std.mem.eql(u8, history.items[history.items.len - 1], buf.items))) {
+ if (trimmed.len > 0 and util.rememberInput(buf.items) and (history.items.len == 0 or !std.mem.eql(u8, history.items[history.items.len - 1], buf.items))) {
const dup = gpa.dupe(u8, buf.items) catch return buf.items;
history.append(gpa, dup) catch {};
}
diff --git a/src/repl_glue.zig b/src/repl_glue.zig
index 93ddd98a..6f5ed3ce 100644
--- a/src/repl_glue.zig
+++ b/src/repl_glue.zig
@@ -26,6 +26,7 @@ const agent_mod = @import("agent.zig");
const provider_mod = @import("provider.zig");
const Agent = agent_mod.Agent;
const Provider = provider_mod.Provider;
+const Keys = provider_mod.Keys;
const ReasoningEffort = main_mod.ReasoningEffort;
const mcp = @import("mcp.zig");
@@ -35,11 +36,15 @@ const Approvals = approvals_mod.Approvals;
const messages_mod = @import("messages.zig");
const textMessage = messages_mod.textMessage;
const pricing = @import("pricing.zig");
-const contextFor = pricing.contextFor;
+const providers = @import("providers.zig");
+const serde = @import("serde.zig");
+const fallback_config = @import("fallback_config.zig");
pub const ReplCtx = struct {
io: Io,
client: *std.http.Client,
+ keys: Keys,
+ home: []const u8,
provider: Provider,
registry: ?*mcp.Registry,
sys_normal: []const u8,
@@ -213,7 +218,8 @@ 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;
}
- const final = agent.runTurn() catch |err| switch (err) {
+ defer c.provider = agent.provider;
+ 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
// null — the pane renders that as "model call failed — check /model and
@@ -233,16 +239,16 @@ pub fn replTurnCb(ctx_ptr: ?*anyopaque, gpa: Allocator, history: []const repl.Tu
return gpa.dupe(u8, trimmed) catch null;
}
-/// repl.ModelFn adapter — switch the active model by name. Keeps the working
-/// provider resolved at startup (its url/key/kind — e.g. the codegraff gateway
-/// login) and only swaps the model field; re-resolving via providerFor can pick
-/// a different, unauthenticated provider for the same model name. Returns the
-/// new model name, or null on failure.
+/// repl.ModelFn adapter — switch the active model by name. Resolve its provider
+/// using the same model-routing rules as /model, then persist that
+/// explicit choice for the next launch. Automatic turn fallback updates only
+/// `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));
- c.provider.model = gpa.dupe(u8, name) catch return null;
- c.provider.context = contextFor(c.provider.id, c.provider.model);
- return gpa.dupe(u8, name) catch null;
+ const resolved = pricing.resolveModelName(c.keys, name) orelse name;
+ c.provider = c.keys.providerFor(gpa.dupe(u8, resolved) catch return null) catch return null;
+ serde.saveModel(c.io, c.home, c.provider.id, c.provider.model);
+ return gpa.dupe(u8, c.provider.model) catch null;
}
/// repl.CancelFn adapter — force-interrupt the running repl turn. Sets the
/// Agent-wide esc_cancel flag the streaming loops + watchdog poll, so the
@@ -337,6 +343,7 @@ pub fn saveThinkingSettings(io: Io, gpa: Allocator, effort: ReasoningEffort, fas
/// {"effort": "low|medium|high|xhigh|max|ultra"} and {"fast": true}. Best-effort — a missing
/// or garbled file just leaves the defaults (medium, off).
pub fn loadThinkingSettings(io: Io, arena: Allocator, root: *Agent) void {
+ root.fallback_allow = fallback_config.load(io, arena);
const data = Io.Dir.cwd().readFileAlloc(io, Approvals.settings_path, arena, .limited(1 << 20)) catch return;
const v = std.json.parseFromSliceLeaky(Value, arena, data, .{ .allocate = .alloc_always }) catch return;
if (v != .object) return;
diff --git a/src/serde.zig b/src/serde.zig
index 26e5a8cc..569e3409 100644
--- a/src/serde.zig
+++ b/src/serde.zig
@@ -9,6 +9,7 @@ const std = @import("std");
const Io = std.Io;
const Value = std.json.Value;
const Allocator = std.mem.Allocator;
+const util = @import("util.zig");
const history_file = ".simple-harness-history";
const model_file = ".simple-harness-model"; // remembers the last-selected provider+model
@@ -50,7 +51,7 @@ pub fn loadHistory(io: Io, gpa: Allocator, home: []const u8, history: *std.Array
var it = std.mem.splitScalar(u8, data, '\n');
while (it.next()) |ln| {
const l = std.mem.trim(u8, ln, " \t\r");
- if (l.len == 0) continue;
+ if (l.len == 0 or !util.rememberInput(l)) continue;
const dup = gpa.dupe(u8, l) catch continue;
history.append(gpa, dup) catch gpa.free(dup);
}
@@ -71,6 +72,7 @@ pub fn saveHistory(io: Io, arena: Allocator, home: []const u8, history: []const
var fw = f.writer(io, &wbuf);
const start = if (history.len > history_cap) history.len - history_cap else 0;
for (history[start..]) |h| {
+ if (!util.rememberInput(h)) continue;
fw.interface.writeAll(h) catch return;
fw.interface.writeByte('\n') catch return;
}
diff --git a/src/session_run.zig b/src/session_run.zig
index 38f5b5fc..2a329bab 100644
--- a/src/session_run.zig
+++ b/src/session_run.zig
@@ -2,7 +2,7 @@
//! (600-line goal — session_start.zig itself crossed the line goal once
//! this content grew). Covers everything from approvals/hooks/fleet-type
//! loading through Agent construction, the `graff repl`/one-shot early-exit
-//! paths, session resume/finalize, and the skills/theme/`--selftest-spinner`
+//! paths, session resume/finalize, and the skills/theme/PTY self-tests
//! setup.
//!
//! Same dangling-pointer discipline as session_start.zig: `buildRootAgent`
@@ -46,6 +46,7 @@ const title_mod = @import("title.zig");
const repl = @import("repl.zig");
const pickers = @import("pickers.zig");
const repl_glue = @import("repl_glue.zig");
+const providers = @import("providers.zig");
const messages_mod = @import("messages.zig");
const session = @import("session.zig");
const fleet = @import("fleet.zig");
@@ -59,11 +60,13 @@ const schema = @import("schema.zig");
/// `root` is already a stable, fully-constructed main()-owned Agent by the
/// time this is called, so taking its address here is safe (this helper
/// only reads through the pointer, it never owns or returns Agent storage).
-pub fn runReplCommand(gpa: Allocator, io: Io, environ_map: anytype, root: *agent_mod.Agent, client: *std.http.Client, in: *Io.Reader, out: *Io.Writer, arena: Allocator, flags: args.Flags) !bool {
+pub fn runReplCommand(gpa: Allocator, io: Io, environ_map: anytype, root: *agent_mod.Agent, keys: provider_mod.Keys, client: *std.http.Client, in: *Io.Reader, out: *Io.Writer, arena: Allocator, flags: args.Flags) !bool {
if (!(flags.positionals.items.len > 0 and std.mem.eql(u8, flags.positionals.items[0], "repl"))) return false;
var repl_ctx = repl_glue.ReplCtx{
.io = io,
.client = client,
+ .keys = keys,
+ .home = root.home,
.provider = root.provider,
.registry = root.registry,
.sys_normal = root.sys_normal,
@@ -90,7 +93,7 @@ pub fn runReplCommand(gpa: Allocator, io: Io, environ_map: anytype, root: *agent
/// denies anything not pre-approved instead of prompting (there's no one to
/// ask). Moved out of main() verbatim (600-line goal); `root`/`tracer` are
/// already stable main()-owned storage by the time this runs.
-pub fn runOneshotPrompt(gpa: Allocator, io: Io, arena: Allocator, root: *agent_mod.Agent, tracer: *trace.Tracer, out: *Io.Writer, prompt_text: []const u8) !void {
+pub fn runOneshotPrompt(gpa: Allocator, io: Io, arena: Allocator, root: *agent_mod.Agent, keys: provider_mod.Keys, tracer: *trace.Tracer, out: *Io.Writer, prompt_text: []const u8) !void {
main_mod.unattended = true;
root.in = null; // gate: deny instead of prompt; ask_user: self-decide
root.out = null; // tool progress → stderr; stdout carries only the answer
@@ -106,7 +109,7 @@ pub fn runOneshotPrompt(gpa: Allocator, io: Io, arena: Allocator, root: *agent_m
if (eval_note.len > 0) oneshot_user = try std.fmt.allocPrint(arena, "{s}\n\n{s}", .{ oneshot_user, eval_note });
try root.messages.append(try messages_mod.textMessage(arena, "user", oneshot_user));
if (telemetry.g_telem) |t| t.countTurn();
- const final_text = root.runTurn() catch |err| switch (err) {
+ const final_text = providers.runTurnWithFallback(root, keys, arena, null) catch |err| switch (err) {
error.ApiError => std.process.fatal("{s}", .{root.last_api_error orelse "api error"}),
else => |e| std.process.fatal("turn failed: {t}", .{e}),
};
@@ -310,15 +313,15 @@ pub fn finalizeSession(gpa: Allocator, io: Io, arena: Allocator, out: *Io.Writer
pub const ThemeSetup = struct {
theme_on: bool,
limyuxi_glam: bool,
- /// True when `--selftest-spinner` already ran + printed the headless
- /// spinner render — main() should return immediately without going any
+ /// True when a PTY self-test already ran + printed its render — main()
+ /// should return immediately without going any
/// further (but AFTER registering the theme/limyuxi reset defers below,
/// exactly like the original inline code did).
should_exit: bool,
};
/// Per-skill/companion opt-outs, animation + terminal-theme settings, the
-/// `--selftest-spinner` headless render (PTY anti-stealth test), and the
+/// headless PTY render self-tests, and the
/// yxlyx-birthday cosmetic theme. Moved out of main() verbatim (600-line
/// goal). Returns which reset defers main() needs to register — the
/// escape-code RESETS must fire when main() itself returns (not when this
@@ -388,6 +391,36 @@ pub fn setupSkillsAndTheme(io: Io, arena: Allocator, environ_map: anytype, out:
out.flush() catch {};
return .{ .theme_on = theme_on, .limyuxi_glam = limyuxi_glam, .should_exit = true };
}
+ if (flags.selftest_markdown_flag) {
+ var probe: agent_mod.Agent = .{
+ .gpa = arena,
+ .arena = arena,
+ .io = io,
+ .client = undefined,
+ .provider = undefined,
+ .messages = undefined,
+ .sub = false,
+ .label = "markdown-selftest",
+ .out = out,
+ };
+ probe.streamMarkdown(
+ \\## Gaps
+ \\- No bot-specific route tests exist.
+ \\- Pin `install.sh` and verify its checksum.
+ \\
+ \\## Recommended implementation order
+ \\1. **Immediately:** require collaborator permission.
+ \\2) **Next:** deduplicate `X-GitHub-Delivery`.
+ \\- [ ] Add a Daytona credential preflight.
+ \\- [x] Sanitize public errors.
+ \\ - Preserve private incident detail.
+ \\> Public errors must never expose secrets.
+ );
+ probe.flushStreamTail();
+ out.writeByte('\n') catch {};
+ out.flush() catch {};
+ return .{ .theme_on = theme_on, .limyuxi_glam = limyuxi_glam, .should_exit = true };
+ }
anim.loadDevSpinnerOptOut(io, arena, environ_map);
return .{ .theme_on = theme_on, .limyuxi_glam = limyuxi_glam, .should_exit = false };
}
diff --git a/src/session_start.zig b/src/session_start.zig
index 4ae54c88..f25aa42c 100644
--- a/src/session_start.zig
+++ b/src/session_start.zig
@@ -133,11 +133,11 @@ pub fn setupWorktreeAndBanner(
try out.flush();
}
if (flags.yolo_flag) {
- try out.print("⚠ yolo mode (--yolo): all bash/tool/MCP permission prompts are skipped\n", .{});
+ try out.print("{s}⚠ YOLO{s} mode (--yolo): all bash/tool/MCP permission prompts are skipped\n", .{ style.red, style.reset });
try out.flush();
}
if (stale_saved_model) |nm| {
- try out.print("{s}note: remembered model '{s}' isn't in the model table — starting on {s} instead{s}\n", .{ style.dim, nm, default_provider.model, style.reset });
+ 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 });
try out.flush();
}
if (main_mod.show_timing or main_mod.show_cost) {
diff --git a/src/skills.zig b/src/skills.zig
index d2147191..d5ae58a8 100644
--- a/src/skills.zig
+++ b/src/skills.zig
@@ -63,19 +63,20 @@ pub const skills_registry = [_]SkillDef{
/// Licensed-aware variant of the codedbpro note. When `codedb-pro probe`
/// succeeds (paid + usable) we inject THIS instead of the conservative
/// "prefer free codedb" note below — leaning into the tools the user pays for.
-/// Edits still stay native: edit_file/write_file are /rewind-snapshotted and
-/// already splice via zigpatch, whereas codedb-pro edit/patch/replace bypass /rewind.
-const codedbpro_note_licensed = "The codedb-pro MCP server is connected and LICENSED (mcp__codedbpro__* tools) — prefer it, you are paying for it. Use mcp__codedbpro__read (mode=outline first, then symbol/lines) instead of read_file for navigating code, mcp__codedbpro__faster_search / meta_search for content and fuzzy search (the native codedb tool stays a fine fast path for indexed symbol/outline/callers/find lookups), and mcp__codedbpro__batch to run several independent reads/searches in one round-trip. KEEP EDITS on the native edit_file/write_file tools — they are snapshot-tracked for /rewind and already splice via zigpatch; codedb-pro edit/patch/replace bypass /rewind, so do not route edits through it. Whenever an mcp__codedbpro__ call fails, fall back to read_file/codedb/bash.";
+/// Edits inside the cwd stay native: edit_file/write_file are
+/// /rewind-snapshotted and already splice via zigpatch, whereas codedb-pro
+/// edit/patch/replace bypass /rewind. Explicit external targets use gated bash.
+const codedbpro_note_licensed = "The codedb-pro MCP server is connected and LICENSED (mcp__codedbpro__* tools) — prefer it, you are paying for it. Use mcp__codedbpro__read (mode=outline first, then symbol/lines) instead of read_file for navigating code, mcp__codedbpro__faster_search / meta_search for content and fuzzy search (the native codedb tool stays a fine fast path for indexed symbol/outline/callers/find lookups), and mcp__codedbpro__batch to run several independent reads/searches in one round-trip. KEEP EDITS inside the cwd on the native edit_file/write_file tools — they are snapshot-tracked for /rewind and already splice via zigpatch; codedb-pro edit/patch/replace bypass /rewind, so do not route edits through it. An explicitly user-requested external target is the exception: use permission-gated bash with quoted paths and explain that /rewind does not cover it. Whenever an mcp__codedbpro__ call fails, fall back to read_file/codedb/bash.";
const McpNote = struct { server: []const u8, note: []const u8 };
pub const mcp_notes = [_]McpNote{
.{
.server = "codedbpro",
- .note = "The codedb-pro MCP server is connected (mcp__codedbpro__* tools). SEARCH ORDER: the native codedb tool is free and indexed — always try it first for code search (search/symbol/callers/outline/find); reach for mcp__codedbpro__faster_search or meta_search only when codedb can't answer (raw literal/regex content matches, fuzzy queries, non-indexed files) — codedb-pro is metered. Prefer mcp__codedbpro__read (mode=outline first, then symbol) over read_file for navigating large code files, and mcp__codedbpro__batch to run several independent reads/searches/edits in one round-trip. Keep edits on the native edit_file/write_file tools (they are snapshot-tracked for /rewind). These tools are accelerators, not requirements: whenever an mcp__codedbpro__ call fails or is unavailable, fall back to read_file/codedb/bash and continue.",
+ .note = "The codedb-pro MCP server is connected (mcp__codedbpro__* tools). SEARCH ORDER: the native codedb tool is free and indexed — always try it first for code search (search/symbol/callers/outline/find); reach for mcp__codedbpro__faster_search or meta_search only when codedb can't answer (raw literal/regex content matches, fuzzy queries, non-indexed files) — codedb-pro is metered. Prefer mcp__codedbpro__read (mode=outline first, then symbol) over read_file for navigating large code files, and mcp__codedbpro__batch to run several independent reads/searches/edits in one round-trip. Keep edits inside the cwd on the native edit_file/write_file tools (they are snapshot-tracked for /rewind); for an explicitly user-requested external target, use permission-gated bash with quoted paths and disclose that /rewind does not cover it. These tools are accelerators, not requirements: whenever an mcp__codedbpro__ call fails or is unavailable, fall back to read_file/codedb/bash and continue.",
},
.{
.server = "muonry",
- .note = "The muonry MCP server is connected (mcp__muonry__* tools). SEARCH ORDER: the native codedb tool is free and indexed — always try it first for code search (search/symbol/callers/outline/find); use mcp__muonry__search or faster_search only when codedb can't answer (raw literal/regex content matches, non-code or non-indexed files) — muonry is metered. Prefer mcp__muonry__read (mode=outline first, then symbol) over read_file for navigating large code files, and mcp__muonry__batch to run several independent reads/searches in one round-trip. Keep edits on the native edit_file/write_file tools (they are snapshot-tracked for /rewind). These tools are accelerators, not requirements: whenever an mcp__muonry__ call fails or is unavailable, fall back to read_file/codedb/bash and continue.",
+ .note = "The muonry MCP server is connected (mcp__muonry__* tools). SEARCH ORDER: the native codedb tool is free and indexed — always try it first for code search (search/symbol/callers/outline/find); use mcp__muonry__search or faster_search only when codedb can't answer (raw literal/regex content matches, non-code or non-indexed files) — muonry is metered. Prefer mcp__muonry__read (mode=outline first, then symbol) over read_file for navigating large code files, and mcp__muonry__batch to run several independent reads/searches/edits in one round-trip. Keep edits inside the cwd on the native edit_file/write_file tools (they are snapshot-tracked for /rewind); for an explicitly user-requested external target, use permission-gated bash with quoted paths and disclose that /rewind does not cover it. These tools are accelerators, not requirements: whenever an mcp__muonry__ call fails or is unavailable, fall back to read_file/codedb/bash and continue.",
},
};
diff --git a/src/startup.zig b/src/startup.zig
index 8fa27f28..3d4c4caa 100644
--- a/src/startup.zig
+++ b/src/startup.zig
@@ -144,8 +144,23 @@ pub fn resolveKeys(io: Io, gpa: Allocator, arena: Allocator, environ_map: anytyp
// exact provider/model pair is still in the catalog; model names can be
// shared by providers with different support.
if (pricing.providerModelInTable(saved.pid, saved.model)) {
- if (keys.providerById(saved.pid, saved.model)) |p| default_provider = p else |_| {}
- } else stale_saved_model = saved.model;
+ if (keys.providerById(saved.pid, saved.model)) |p| {
+ default_provider = p;
+ } else |_| {
+ stale_saved_model = std.fmt.allocPrint(arena, "{s}/{s}", .{ saved.pid, saved.model }) catch saved.model;
+ }
+ } else {
+ stale_saved_model = std.fmt.allocPrint(arena, "{s}/{s}", .{ saved.pid, saved.model }) catch saved.model;
+ // 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;
+ const replacement = pricing.providerDefaultModel(spec.id, spec.default_model);
+ if (keys.providerById(spec.id, replacement)) |p| default_provider = p else |_| {}
+ break;
+ }
+ }
}
return .{ .keys = keys, .default_provider = default_provider, .stale_saved_model = stale_saved_model, .codex_account = codex_account };
}
diff --git a/src/tools.zig b/src/tools.zig
index 991b1e8c..c1c955a4 100644
--- a/src/tools.zig
+++ b/src/tools.zig
@@ -398,7 +398,7 @@ pub fn missingArg(gpa: Allocator, name: []const u8) !ToolOutput {
pub fn outsideCwd(gpa: Allocator, path: []const u8) !ToolOutput {
return .{
- .text = try std.fmt.allocPrint(gpa, "path '{s}' is outside the working directory — file tools are confined to the cwd subtree (no absolute paths, no '..'). Use bash for paths elsewhere.", .{path}),
+ .text = try std.fmt.allocPrint(gpa, "path '{s}' is outside the working directory — native file tools are confined to the cwd subtree (no absolute paths, no '..'). If the user explicitly requested that external target, the root agent may continue with permission-gated bash using quoted paths after checking git status; those edits are not covered by /rewind. A relaunch is not required. Subagents remain confined.", .{path}),
.is_error = true,
};
}
@@ -517,6 +517,17 @@ test "missingArg: builds an is_error result naming the argument" {
try std.testing.expect(std.mem.indexOf(u8, o.text, "path") != null);
}
+test "outsideCwd: points an explicitly authorized root agent at the safe fallback" {
+ const o = try outsideCwd(std.testing.allocator, "../zigrepper");
+ defer std.testing.allocator.free(o.text);
+ try std.testing.expect(o.is_error);
+ try std.testing.expect(std.mem.indexOf(u8, o.text, "permission-gated bash") != null);
+ try std.testing.expect(std.mem.indexOf(u8, o.text, "quoted paths") != null);
+ try std.testing.expect(std.mem.indexOf(u8, o.text, "not covered by /rewind") != null);
+ try std.testing.expect(std.mem.indexOf(u8, o.text, "relaunch is not required") != null);
+ try std.testing.expect(std.mem.indexOf(u8, o.text, "Subagents remain confined") != null);
+}
+
test "apiErrorMessage: object-message, bare-string, and absent envelopes" {
var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena_state.deinit();
diff --git a/src/util.zig b/src/util.zig
index 94831cfc..781ac229 100644
--- a/src/util.zig
+++ b/src/util.zig
@@ -9,6 +9,25 @@ const std = @import("std");
const Io = std.Io;
const Value = std.json.Value;
+/// Byte offset where a secret begins in an interactive command, or null when
+/// the line is safe to render/store verbatim. `/key` with no value remains a
+/// useful history entry; `/key <provider> <secret>` is masked and forgotten.
+pub fn sensitiveInputStart(line: []const u8) ?usize {
+ var i: usize = 0;
+ while (i < line.len and (line[i] == ' ' or line[i] == '\t')) : (i += 1) {}
+ if (!std.mem.startsWith(u8, line[i..], "/key")) return null;
+ i += "/key".len;
+ if (i >= line.len or (line[i] != ' ' and line[i] != '\t')) return null;
+ while (i < line.len and (line[i] == ' ' or line[i] == '\t')) : (i += 1) {}
+ while (i < line.len and line[i] != ' ' and line[i] != '\t') : (i += 1) {}
+ while (i < line.len and (line[i] == ' ' or line[i] == '\t')) : (i += 1) {}
+ return if (i < line.len) i else null;
+}
+
+pub fn rememberInput(line: []const u8) bool {
+ return sensitiveInputStart(line) == null;
+}
+
/// Read a string field from a JSON object, or null if absent/non-string.
pub fn strFieldObj(obj: std.json.ObjectMap, name: []const u8) ?[]const u8 {
const v = obj.get(name) orelse return null;
@@ -33,6 +52,16 @@ test "strFieldObj/intFieldObj: object-map variants with defaults" {
try std.testing.expectEqual(@as(i64, -1), intFieldObj(v.object, "missing", -1));
}
+test "sensitiveInputStart: masks key values but keeps status/partial commands" {
+ try std.testing.expect(sensitiveInputStart("/key") == null);
+ try std.testing.expect(sensitiveInputStart("/key openai") == null);
+ try std.testing.expectEqual(@as(usize, 12), sensitiveInputStart("/key openai sk-secret").?);
+ try std.testing.expectEqual(@as(usize, 15), sensitiveInputStart(" /key codex token").?);
+ try std.testing.expect(!rememberInput("/key openai sk-secret"));
+ try std.testing.expect(rememberInput("/key"));
+ try std.testing.expect(rememberInput("explain /key openai sk-secret"));
+}
+
/// Largest prefix of `s` up to `max` bytes that doesn't split a UTF-8
/// codepoint (std.json would otherwise serialize the slice as an int array).
pub fn utf8Prefix(s: []const u8, max: usize) []const u8 {