graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
//! The terminal half of the interactive status line (#422/#429): everything
//! about how `.prompt_ready` is DRAWN — the palette, the badge frame, and the
//! #209 width budget. Reached only from engine_sink's TuiSink, the same shape
//! agent_stream_render.zig and agent_tool_render.zig have for their clusters;
//! this is one of the few files down here that may touch ansi/term.
//!
//! The session strip separates identity, operational modes and quiet metrics.
//! A colored terminal replaces the existing blank row with a subtle divider;
//! plain output keeps the unframed status and bare prompt. This is terminal
//! presentation only: the engine still owns every fact in PromptStatus.
const std = @import("std");
const Io = std.Io;
const style = &@import("ansi.zig").style;
const terminal = @import("term.zig");
const engine_events = @import("engine_events.zig");
const PromptStatus = engine_events.PromptStatus;
const working = @import("agent_working.zig");
pub fn reasoningLabel(effort: anytype) []const u8 {
return switch (effort) {
.low => "Low",
.medium => "Medium",
.high => "High",
.xhigh => "Extra high",
.max => "Max",
.ultra => "Ultra",
.none => "Off",
};
}
pub fn reasoningColor(effort: anytype) []const u8 {
return switch (effort) {
.low => style.green,
.medium => style.accent,
.high => style.yellow,
.xhigh => style.accent,
.max => style.red,
.ultra => style.accent,
.none => style.green,
};
}
/// Include a status-line segment only if its width still fits the remaining
/// budget, charging it against `used` when it does. Lets the status line drop
/// low-priority metadata (cwd, context meter, cache/cost) instead of letting
/// the terminal soft-wrap the line mid-badge in a narrow pane — e.g. splitting
/// `codex` across the edge and stranding the cursor inside the label (#209).
pub fn fitsSegment(used: *usize, avail: usize, seg_width: usize) bool {
if (used.* + seg_width <= avail) {
used.* += seg_width;
return true;
}
return false;
}
pub 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 fn contextPercent(tokens: u64, window: u64) u64 {
if (window == 0) return 0;
return @min((tokens *| 100) / window, 100);
}
/// Draw the status line for one `.prompt_ready`. Width-budgeted against the
/// terminal so a narrow pane never soft-wraps mid-badge (splitting e.g.
/// `codex`) and strands the cursor inside a label (#209); low-priority
/// metadata (cwd, context, cache, cost) is the first to drop when it no longer
/// fits. See fitsSegment's doc comment for the rest.
pub fn promptLine(w: *Io.Writer, st: PromptStatus) void {
// The one environment read in this file, kept at the edge so the layout
// below is a pure function of (status, width) and can be pinned by tests.
line(w, st, terminal.termCols()) catch return;
}
fn cwdName(cwd: []const u8) []const u8 {
var end = cwd.len;
while (end > 1 and cwd[end - 1] == '/') end -= 1;
const t = cwd[0..end];
if (t.len == 0) return cwd;
if (std.mem.lastIndexOfScalar(u8, t, '/')) |idx| {
const rest = t[idx + 1 ..];
return if (rest.len == 0) t else rest;
}
return t;
}
fn modeSegment(w: *Io.Writer, text: []const u8) !void {
try w.print(" · {s}{s}{s}{s}{s}{s}", .{ style.reset, style.accent, style.bold, text, style.reset, style.muted });
}
fn metadataPrefix(w: *Io.Writer, first: *bool, gap: usize) !void {
if (first.* and gap > 0) {
for (0..gap) |_| try w.writeByte(' ');
} else {
try w.writeAll(" · ");
}
first.* = false;
}
fn line(w: *Io.Writer, st: PromptStatus, cols: usize) !void {
working.writeFromStanding(w, st.standing);
// Reuse the blank separator row, not another panel or an editor border.
// Leave a column free so the rule never triggers terminal autowrap.
if (style.accent.len > 0 and cols > 1) {
const lead = @min(@as(usize, 3), cols - 1);
try w.writeAll(style.accent);
for (0..lead) |_| try w.writeAll("─");
try w.print("{s}{s}", .{ style.reset, style.faint });
for (lead..cols - 1) |_| try w.writeAll("─");
try w.writeAll(style.reset);
}
try w.writeByte('\n');
var cbuf: [24]u8 = undefined;
const cost: []const u8 = switch (st.cost) {
.hidden => "",
.subscription => "sub",
.unpriced => "$?",
.usd => |usd| std.fmt.bufPrint(&cbuf, "${d:.2}", .{usd}) catch "",
};
var ctxbuf: [24]u8 = undefined;
const ctx: []const u8 = if (st.context) |meter|
(std.fmt.bufPrint(&ctxbuf, "ctx {d}%", .{contextPercent(meter.tokens, meter.window)}) catch "")
else
"";
var cachebuf: [24]u8 = undefined;
// Last-turn hit rate: cached tokens over the prompt that produced them.
// Rides with ctx — a lone cache badge has no denominator. 0% after a
// measured turn is still a reading (the fun is watching it jump).
const cache: []const u8 = if (st.context) |meter|
(if (meter.tokens > 0)
(std.fmt.bufPrint(&cachebuf, "cache {d}%", .{contextPercent(st.cache_read, meter.tokens)}) catch "")
else
"")
else
"";
var resumebuf: [24]u8 = undefined;
const resume_hint: []const u8 = if (st.saved_sessions > 0)
(std.fmt.bufPrint(&resumebuf, "/resume {d}", .{st.saved_sessions}) catch "")
else
"";
// Identity anchors the strip; modes that affect the next turn take
// priority over workspace and usage. Everything stays above a bare `›`.
// #209: drop lower-priority segments instead of wrapping the strip.
const avail = cols -| 1;
var used: usize = st.model.len;
const folder = cwdName(st.cwd);
const show_fast = st.fast and fitsSegment(&used, avail, 3 + "Fast".len);
const show_effort = st.effort != null and
fitsSegment(&used, avail, 3 + reasoningLabel(st.effort.?).len);
const show_fallback = st.fallback and
fitsSegment(&used, avail, 3 + "Fallback".len);
const show_plan = st.plan and fitsSegment(&used, avail, 3 + "Plan".len);
const show_strict = st.strict and fitsSegment(&used, avail, 3 + "Strict".len);
const show_ultra = st.ultracode and fitsSegment(&used, avail, 3 + "Ultracode".len);
const identity_width = used;
const show_cwd = folder.len > 0 and fitsSegment(&used, avail, 3 + 2 + folder.len);
const show_ctx = ctx.len > 0 and fitsSegment(&used, avail, 3 + ctx.len);
const show_cache = show_ctx and cache.len > 0 and fitsSegment(&used, avail, 3 + cache.len);
const show_cost = cost.len > 0 and fitsSegment(&used, avail, 3 + cost.len);
const show_resume = resume_hint.len > 0 and fitsSegment(&used, avail, 3 + resume_hint.len);
const show_image = st.standing.image and fitsSegment(&used, avail, 3 + "image".len);
const show_session = st.standing.session.len > 0 and
fitsSegment(&used, avail, 3 + st.standing.session.len);
try w.print("{s}{s}{s}{s}{s}", .{ style.bold, style.accent, st.model, style.reset, style.muted });
if (show_fast) try modeSegment(w, "Fast");
if (show_effort) try w.print(" · {s}", .{reasoningLabel(st.effort.?)});
if (show_fallback) try modeSegment(w, "Fallback");
if (show_plan) try modeSegment(w, "Plan");
if (show_strict) try modeSegment(w, "Strict");
if (show_ultra) try modeSegment(w, "Ultracode");
// Keep the active seat on the left and quiet metadata on the right.
// The first metadata separator becomes whitespace, not another badge.
// Byte-based budgets remain conservative for non-ASCII labels; plain
// terminals retain their exact compact, unpadded transcript.
const gap = if (style.accent.len > 0 and used > identity_width)
avail -| (used - 3)
else
0;
var first_metadata = true;
if (show_cwd) {
try metadataPrefix(w, &first_metadata, gap);
try w.print("~/{s}", .{folder});
}
const Metadata = struct { show: bool, text: []const u8 };
for ([_]Metadata{
.{ .show = show_ctx, .text = ctx },
.{ .show = show_cache, .text = cache },
.{ .show = show_cost, .text = cost },
.{ .show = show_resume, .text = resume_hint },
.{ .show = show_image, .text = "image" },
.{ .show = show_session, .text = st.standing.session },
}) |segment| {
if (!segment.show) continue;
try metadataPrefix(w, &first_metadata, gap);
try w.writeAll(segment.text);
}
try w.print("{s}\n{s}{s}›{s} ", .{ style.reset, style.bold, style.accent, style.reset });
try w.flush();
}
test "reasoning prompt label uses picker wording" {
const Effort = enum { low, medium, high, xhigh, max, ultra, none };
try std.testing.expectEqualStrings("Low", reasoningLabel(Effort.low));
try std.testing.expectEqualStrings("Medium", reasoningLabel(Effort.medium));
try std.testing.expectEqualStrings("High", reasoningLabel(Effort.high));
try std.testing.expectEqualStrings("Extra high", reasoningLabel(Effort.xhigh));
try std.testing.expectEqualStrings("Max", reasoningLabel(Effort.max));
try std.testing.expectEqualStrings("Ultra", reasoningLabel(Effort.ultra));
try std.testing.expectEqualStrings("Off", reasoningLabel(Effort.none));
}
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));
}
test "context percent saturates malformed or over-window server meters" {
try std.testing.expectEqual(@as(u64, 0), contextPercent(100, 0));
try std.testing.expectEqual(@as(u64, 50), contextPercent(50_000, 100_000));
try std.testing.expectEqual(@as(u64, 100), contextPercent(150_000, 100_000));
try std.testing.expectEqual(@as(u64, 100), contextPercent(std.math.maxInt(u64), 100_000));
}
test "fitsSegment charges the budget only on a fit, #209" {
var used: usize = 10;
try std.testing.expect(fitsSegment(&used, 20, 5)); // 10 + 5 <= 20
try std.testing.expectEqual(@as(usize, 15), used);
try std.testing.expect(!fitsSegment(&used, 20, 10)); // 15 + 10 > 20: rejected
try std.testing.expectEqual(@as(usize, 15), used); // unchanged on rejection
try std.testing.expect(fitsSegment(&used, 20, 5)); // exact fit still counts
try std.testing.expectEqual(@as(usize, 20), used);
}
test "narrow pane drops cwd/context but keeps model+mode badges whole, #209" {
// Reproduces the issue's 28-col tmux repro: `[gpt-5.6-sol · High · codex`
// used to soft-wrap mid-badge because the status line never budgeted
// against termCols(). Budgeting the same segment widths here must keep the
// high-priority model/effort/provider badges intact and never let the
// running total exceed the pane, while cwd/context (low priority) give way.
const cols: usize = 28;
const avail = cols -| 6; // fixed frame ('[' + '] › ') + 1 col slack
var used: usize = "gpt-5.6-sol".len;
const show_effort = fitsSegment(&used, avail, 3 + "High".len);
const show_provider = fitsSegment(&used, avail, 3 + "codex".len);
const show_cwd = fitsSegment(&used, avail, 7 + "/path/to/project".len);
const show_ctx = fitsSegment(&used, avail, " · 12k/100k ctx (12% · compact@80k)".len);
try std.testing.expect(show_effort);
try std.testing.expect(used <= avail); // never overflows the pane itself
_ = show_provider; // may or may not fit at this extreme width; never split either way
try std.testing.expect(!show_cwd); // low-priority metadata is the first to go
try std.testing.expect(!show_ctx);
}
test "wide pane keeps every segment, matching the pre-#209 behaviour" {
// A generous pane must still show everything, proving the budget is real
// width-awareness and not an unconditional strip of metadata.
const cols: usize = 200;
const avail = cols -| 6;
var used: usize = "gpt-5.6-sol".len;
try std.testing.expect(fitsSegment(&used, avail, 3 + "High".len));
try std.testing.expect(fitsSegment(&used, avail, 3 + "codex".len));
try std.testing.expect(fitsSegment(&used, avail, 7 + "/path/to/project".len));
try std.testing.expect(fitsSegment(&used, avail, " · 12k/100k ctx (12% · compact@80k)".len));
}
/// The unstyled strip as a plain-terminal reader sees it, with enough room
/// for every optional segment.
fn renderPlain(buf: *Io.Writer.Allocating, st: PromptStatus) []const u8 {
line(&buf.writer, st, 400) catch unreachable; // a pane wide enough to keep everything
return buf.writer.buffered();
}
test "terminal status keeps every segment and prioritizes operational modes" {
const saved = style.*;
style.* = .{}; // assert the text, not the palette
defer style.* = saved;
var aw: Io.Writer.Allocating = .init(std.testing.allocator);
defer aw.deinit();
// A wide pane keeps everything: model, every badge, cwd, meter, cache, cost.
const full: PromptStatus = .{
.model = "gpt-5.6",
.provider_id = "codex",
.cwd = "~/src/graff",
.privacy_label = "Privacy:Aggregate",
.privacy = .aggregate,
.effort = .high,
.context = .{ .tokens = 12_345, .window = 200_000, .compact_at = 160_000 },
.cache_read = 2048,
.cost = .{ .usd = 0.5 },
.fast = true,
.fallback = true,
.plan = true,
.strict = true,
.ultracode = true,
};
try std.testing.expectEqualStrings(
"\ngpt-5.6 · Fast · High · Fallback · Plan · Strict · Ultracode · ~/graff · ctx 6% · cache 16% · $0.50\n› ",
renderPlain(&aw, full),
);
// The bare line: no usage yet, meter off, no optional badge.
aw.clearRetainingCapacity();
try std.testing.expectEqualStrings(
"\nlmstudio · ~/w\n› ",
renderPlain(&aw, .{
.model = "lmstudio",
.provider_id = "lmstudio",
.cwd = "/w",
.privacy_label = "Privacy:Local",
.privacy = .local,
}),
);
// A flat-rate provider says so instead of showing a figure, and an
// unpriced model admits it rather than printing a fabricated 0.0000.
aw.clearRetainingCapacity();
try std.testing.expectEqualStrings(
"\nm · ~/w · sub\n› ",
renderPlain(&aw, .{
.model = "m",
.provider_id = "p",
.cwd = "/w",
.privacy_label = "Privacy:Local",
.privacy = .local,
.cost = .subscription,
}),
);
aw.clearRetainingCapacity();
try std.testing.expectEqualStrings(
"\nm · ~/w · $?\n› ",
renderPlain(&aw, .{
.model = "m",
.provider_id = "p",
.cwd = "/w",
.privacy_label = "Privacy:Local",
.privacy = .local,
.cost = .unpriced,
}),
);
}
test "batch 3: a shrinking pane sheds segments in the #209 priority order" {
// The budget is what a narrow tmux pane actually exercises, and it is the
// part of this move most able to drift silently: assert the WHOLE line at
// three widths rather than the fitsSegment arithmetic alone.
const saved = style.*;
style.* = .{};
defer style.* = saved;
var aw: Io.Writer.Allocating = .init(std.testing.allocator);
defer aw.deinit();
const st: PromptStatus = .{
.model = "gpt-5.6",
.provider_id = "codex",
.cwd = "~/src/graff",
.privacy_label = "Privacy:Local",
.privacy = .local,
.effort = .high,
.context = .{ .tokens = 12_345, .window = 200_000, .compact_at = 160_000 },
.cache_read = 2048,
.cost = .unpriced,
};
const cases = [_]struct { cols: usize, want: []const u8 }{
.{ .cols = 80, .want = "\ngpt-5.6 · High · ~/graff · ctx 6% · cache 16% · $?\n› " },
.{ .cols = 28, .want = "\ngpt-5.6 · High · ~/graff\n› " },
.{ .cols = 18, .want = "\ngpt-5.6 · High\n› " },
};
for (cases) |c| {
aw.clearRetainingCapacity();
try line(&aw.writer, st, c.cols);
try std.testing.expectEqualStrings(c.want, aw.writer.buffered());
}
}
test "batch 3: the cache badge rides with the context meter, never alone" {
// Both come from the same response's usage payload, and the pre-#209
// layout never showed one without the other — a rule that lived in the
// `show_ctx and …` gate and has to survive the move.
const saved = style.*;
style.* = .{};
defer style.* = saved;
var aw: Io.Writer.Allocating = .init(std.testing.allocator);
defer aw.deinit();
const out = renderPlain(&aw, .{
.model = "m",
.provider_id = "p",
.cwd = "/w",
.privacy_label = "Privacy:Local",
.privacy = .local,
.cache_read = 4096, // reported, but no context meter to ride with
});
try std.testing.expect(std.mem.indexOf(u8, out, "cached") == null);
try std.testing.expect(std.mem.indexOf(u8, out, "cache ") == null);
}
test "a measured turn prints last-turn cache hit next to ctx" {
const saved = style.*;
style.* = .{};
defer style.* = saved;
var aw: Io.Writer.Allocating = .init(std.testing.allocator);
defer aw.deinit();
// 2048 of 12345 input tokens ≈ 16%; the window share stays ctx 6%.
const out = renderPlain(&aw, .{
.model = "m",
.provider_id = "p",
.cwd = "/w",
.privacy_label = "Privacy:Local",
.privacy = .local,
.context = .{ .tokens = 12_345, .window = 200_000, .compact_at = 160_000 },
.cache_read = 2048,
});
try std.testing.expect(std.mem.indexOf(u8, out, "ctx 6%") != null);
try std.testing.expect(std.mem.indexOf(u8, out, "cache 16%") != null);
}
test "standing work draws a WORKING block above the prompt" {
const saved = style.*;
style.* = .{};
defer style.* = saved;
var aw: Io.Writer.Allocating = .init(std.testing.allocator);
defer aw.deinit();
const bare: PromptStatus = .{
.model = "m",
.provider_id = "p",
.cwd = "/w",
.privacy_label = "Privacy:Local",
.privacy = .local,
};
try std.testing.expectEqualStrings(
"\nm · ~/w\n› ",
renderPlain(&aw, bare),
);
aw.clearRetainingCapacity();
const items = [_]engine_events.StandingTodo{
.{ .content = "inspect current prompt", .done = true },
.{ .content = "update implementation", .done = false },
};
const full: PromptStatus = .{
.model = "m",
.provider_id = "p",
.cwd = "/w",
.privacy_label = "Privacy:Local",
.privacy = .local,
.standing = .{
.session = "login-fix",
.goal = "ship the repl standing line",
.goal_status = "paused",
.todos_done = 1,
.todos_total = 2,
.todos = &items,
.image = true,
},
};
try line(&aw.writer, full, 80);
try std.testing.expectEqualStrings(
"WORKING ship the repl standing line 1/2\n" ++
"├ ✓ inspect current prompt\n" ++
"└ ○ update implementation\n" ++
"\nm · ~/w · image · login-fix\n› ",
aw.writer.buffered(),
);
}
test "terminal chrome bounds its divider and separates identity from metadata" {
const saved = style.*;
style.* = @import("ansi.zig").Style.ansi;
defer style.* = saved;
var aw: Io.Writer.Allocating = .init(std.testing.allocator);
defer aw.deinit();
const st: PromptStatus = .{
.model = "m",
.provider_id = "p",
.cwd = "/w",
.privacy_label = "",
.privacy = .local,
.plan = true,
};
for ([_]usize{ 1, 18, 80 }) |cols| {
aw.clearRetainingCapacity();
try line(&aw.writer, st, cols);
const text = aw.written();
const end = std.mem.indexOfScalar(u8, text, '\n').?;
try std.testing.expectEqual(cols - 1, std.mem.count(u8, text[0..end], "─"));
if (cols >= 4) try std.testing.expect(std.mem.startsWith(u8, text, "\x1b[38;2;5;150;105m───\x1b[0m\x1b[2m"));
try std.testing.expect(std.mem.indexOf(u8, text, " · ~/w") == null);
if (cols == 18) try std.testing.expect(std.mem.indexOf(u8, text, " ~/w\x1b[0m\n") != null);
try std.testing.expect(std.mem.indexOf(u8, text, "\x1b[1m\x1b[38;2;5;150;105mm\x1b[0m\x1b[2m") != null);
try std.testing.expect(std.mem.endsWith(u8, text, "\n\x1b[1m\x1b[38;2;5;150;105m›\x1b[0m "));
}
}
test "terminal status keeps operational modes before a long workspace" {
const saved = style.*;
style.* = .{};
defer style.* = saved;
var aw: Io.Writer.Allocating = .init(std.testing.allocator);
defer aw.deinit();
try line(&aw.writer, .{
.model = "m",
.provider_id = "p",
.cwd = "/a-very-long-workspace-name",
.privacy_label = "",
.privacy = .local,
.fallback = true,
.plan = true,
.strict = true,
}, 36);
try std.testing.expectEqualStrings("\nm · Fallback · Plan · Strict\n› ", aw.written());
}
test {
_ = working;
}