Skip to content

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

Python

refactor: split repl.zig Model struct into repl_model_*.zig (600-line goal)

justrach9d64757385fd
diff --git a/src/repl.zig b/src/repl.zig
index ec748207..c2b02b98 100644
--- a/src/repl.zig
+++ b/src/repl.zig
@@ -11,93 +11,39 @@
//! conversation is sent each turn (multi-turn memory). Without a model wired in
//! (standalone exe) it falls back to a pure i64 arithmetic evaluator, which
//! keeps it fully unit-testable.
+//!
+//! Split across sibling files (#123, 600-line goal): repl_parser.zig (the
+//! offline arithmetic evaluator), repl_util.zig (stateless string/format
+//! helpers), and repl_model_{turn,commands,render}.zig (the Model struct's
+//! method bodies, reached back through the member aliases below via the
+//! same technique used for the Agent struct split — self.method() and
+//! Model.method() resolve unchanged regardless of which file backs them).
const std = @import("std");
const zz = @import("zigzag");
+const parser_mod = @import("repl_parser.zig");
+const util = @import("repl_util.zig");
+const model_turn = @import("repl_model_turn.zig");
+const model_commands = @import("repl_model_commands.zig");
+const model_render = @import("repl_model_render.zig");
+const repl_run = @import("repl_run.zig");
+
+test {
+ _ = parser_mod;
+ _ = util;
+ _ = model_turn;
+ _ = model_commands;
+ _ = model_render;
+ _ = repl_run;
+}
+
// ---------------------------------------------------------------------------
-// Arithmetic evaluator — pure, allocation-free. Offline fallback engine + the
-// thing the headless tests exercise.
+// Arithmetic evaluator — split out to repl_parser.zig (#123, 600-line goal):
+// EvalError/Parser/eval (+ their tests) live there now. Offline fallback
+// engine + the thing the headless tests exercise when no turn_fn is wired in.
// ---------------------------------------------------------------------------
-pub const EvalError = error{ SyntaxError, DivByZero, Overflow };
-
-const Parser = struct {
- src: []const u8,
- pos: usize = 0,
-
- fn skipWs(self: *Parser) void {
- while (self.pos < self.src.len and (self.src[self.pos] == ' ' or
- self.src[self.pos] == '\t')) : (self.pos += 1)
- {}
- }
- fn peek(self: *Parser) ?u8 {
- self.skipWs();
- return if (self.pos < self.src.len) self.src[self.pos] else null;
- }
- fn expr(self: *Parser) EvalError!i64 {
- var acc = try self.term();
- while (self.peek()) |c| {
- if (c != '+' and c != '-') break;
- self.pos += 1;
- const rhs = try self.term();
- acc = if (c == '+') try std.math.add(i64, acc, rhs) else try std.math.sub(i64, acc, rhs);
- }
- return acc;
- }
- fn term(self: *Parser) EvalError!i64 {
- var acc = try self.factor();
- while (self.peek()) |c| {
- if (c != '*' and c != '/' and c != '%') break;
- self.pos += 1;
- const rhs = try self.factor();
- switch (c) {
- '*' => acc = try std.math.mul(i64, acc, rhs),
- '/' => {
- if (rhs == 0) return error.DivByZero;
- if (acc == std.math.minInt(i64) and rhs == -1) return error.Overflow;
- acc = @divTrunc(acc, rhs);
- },
- else => {
- if (rhs == 0) return error.DivByZero;
- if (acc == std.math.minInt(i64) and rhs == -1) return error.Overflow;
- acc = @rem(acc, rhs);
- },
- }
- }
- return acc;
- }
- fn factor(self: *Parser) EvalError!i64 {
- const c = self.peek() orelse return error.SyntaxError;
- if (c == '-') {
- self.pos += 1;
- return std.math.negate(try self.factor()) catch error.Overflow;
- }
- if (c == '+') {
- self.pos += 1;
- return self.factor();
- }
- if (c == '(') {
- self.pos += 1;
- const v = try self.expr();
- if (self.peek() != @as(?u8, ')')) return error.SyntaxError;
- self.pos += 1;
- return v;
- }
- if (!std.ascii.isDigit(c)) return error.SyntaxError;
- const start = self.pos;
- while (self.pos < self.src.len and std.ascii.isDigit(self.src[self.pos])) : (self.pos += 1) {}
- return std.fmt.parseInt(i64, self.src[start..self.pos], 10) catch error.Overflow;
- }
-};
-
-pub fn eval(src: []const u8) EvalError!i64 {
- var p = Parser{ .src = src };
- const v = try p.expr();
- if (p.peek() != null) return error.SyntaxError;
- return v;
-}
-
// ---------------------------------------------------------------------------
// Model hook — injected by the host (src/main.zig). The callback receives the
// whole conversation + the current thinking settings and returns a reply
@@ -146,31 +92,31 @@ pub const StreamBuf = struct {
pub const TurnFn = *const fn (turn_ctx: ?*anyopaque, gpa: std.mem.Allocator, history: []const Turn, params: Params, stream: *StreamBuf) ?[]const u8;
-var g_turn_fn: ?TurnFn = null;
-var g_turn_ctx: ?*anyopaque = null;
-var g_model_name: []const u8 = "";
+pub var g_turn_fn: ?TurnFn = null;
+pub var g_turn_ctx: ?*anyopaque = null;
+pub var g_model_name: []const u8 = "";
pub const ModelFn = *const fn (turn_ctx: ?*anyopaque, gpa: std.mem.Allocator, name: []const u8) ?[]const u8;
-var g_models: []const u8 = ""; // comma-joined model names (for /models)
-var g_model_fn: ?ModelFn = null; // switch the active model by name
+pub var g_models: []const u8 = ""; // comma-joined model names (for /models)
+pub var g_model_fn: ?ModelFn = null; // switch the active model by name
pub const CancelFn = *const fn (turn_ctx: ?*anyopaque) void;
-var g_cancel_fn: ?CancelFn = null; // force-interrupt the running turn (steer drain)
-var g_debug: bool = false; // GRAFF_REPL_DEBUG / `/debug` → dump raw stream + frames to stderr
+pub var g_cancel_fn: ?CancelFn = null; // force-interrupt the running turn (steer drain)
+pub var g_debug: bool = false; // GRAFF_REPL_DEBUG / `/debug` → dump raw stream + frames to stderr
// ---------------------------------------------------------------------------
// Look & feel.
// ---------------------------------------------------------------------------
-const accent = zz.Color.fromRgb(0xD9, 0x77, 0x57); // Claude coral
+pub const accent = zz.Color.fromRgb(0xD9, 0x77, 0x57); // Claude coral
/// `/ultracode` rainbow shine — sweeps across the input border per frame.
-const rainbow = [_]zz.Color{
+pub const rainbow = [_]zz.Color{
zz.Color.fromRgb(0xFF, 0x5C, 0x57), zz.Color.fromRgb(0xFF, 0x9F, 0x43),
zz.Color.fromRgb(0xFE, 0xD3, 0x30), zz.Color.fromRgb(0x6B, 0xCB, 0x77),
zz.Color.fromRgb(0x4D, 0x96, 0xFF), zz.Color.fromRgb(0xB1, 0x7A, 0xFF),
};
-const braille_frames = [_][]const u8{ "⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏" };
-const dragon_frames = [_][]const u8{ "🐉 ", "🐉 ✦", "🐉 ✧", "🐉 ✦" };
+pub const braille_frames = [_][]const u8{ "⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏" };
+pub const dragon_frames = [_][]const u8{ "🐉 ", "🐉 ✦", "🐉 ✧", "🐉 ✦" };
const Anim = enum { braille, dragon };
@@ -180,7 +126,7 @@ const POLL_NS: u64 = 50 * std.time.ns_per_ms;
// Background model call.
// ---------------------------------------------------------------------------
-const Job = struct {
+pub const Job = struct {
thread: std.Thread = undefined,
threaded: bool = true,
done: std.atomic.Value(bool) = std.atomic.Value(bool).init(false),
@@ -191,7 +137,7 @@ const Job = struct {
stream: StreamBuf,
};
-fn jobRun(job: *Job) void {
+pub fn jobRun(job: *Job) void {
const reply = if (g_turn_fn) |f| f(g_turn_ctx, job.gpa, job.history, job.params, &job.stream) else null;
job.result = reply;
job.done.store(true, .release);
@@ -201,13 +147,13 @@ fn jobRun(job: *Job) void {
// Model.
// ---------------------------------------------------------------------------
-const Entry = struct {
+pub const Entry = struct {
kind: Kind,
text: []const u8, // owned by Model.alloc
const Kind = enum { welcome, input, result, err, info, pending, assistant };
};
-const Effect = enum { stay, quit };
+pub const Effect = enum { stay, quit };
pub const Model = struct {
alloc: std.mem.Allocator,
@@ -289,127 +235,34 @@ pub const Model = struct {
self.input.deinit();
}
- fn push(self: *Model, kind: Entry.Kind, text: []const u8) !void {
+ pub fn push(self: *Model, kind: Entry.Kind, text: []const u8) !void {
const owned = try self.alloc.dupe(u8, text);
errdefer self.alloc.free(owned);
try self.history.append(.{ .kind = kind, .text = owned });
}
- fn pushFmt(self: *Model, kind: Entry.Kind, comptime fmt: []const u8, args: anytype) !void {
+ pub fn pushFmt(self: *Model, kind: Entry.Kind, comptime fmt: []const u8, args: anytype) !void {
const text = try std.fmt.allocPrint(self.alloc, fmt, args);
errdefer self.alloc.free(text);
try self.history.append(.{ .kind = kind, .text = text });
}
- fn pushOwned(self: *Model, kind: Entry.Kind, owned: []const u8) !void {
+ pub fn pushOwned(self: *Model, kind: Entry.Kind, owned: []const u8) !void {
try self.history.append(.{ .kind = kind, .text = owned });
}
- fn clearHistory(self: *Model) void {
+ pub fn clearHistory(self: *Model) void {
for (self.history.items) |e| self.alloc.free(e.text);
self.history.clearRetainingCapacity();
self.push(.welcome, "") catch {};
}
- /// Snapshot the conversation, push the `thinking…` placeholder, and spawn
- /// the model call on a background thread (so the spinner can animate).
- fn startJob(self: *Model) void {
- var turns = std.array_list.Managed(Turn).init(self.alloc);
- for (self.history.items) |e| {
- const role: ?Turn.Role = switch (e.kind) {
- .input => .user,
- .assistant => .assistant,
- else => null,
- };
- if (role) |r| {
- const t = self.alloc.dupe(u8, e.text) catch continue;
- turns.append(.{ .role = r, .text = t }) catch {
- self.alloc.free(t);
- continue;
- };
- }
- }
- const job = self.alloc.create(Job) catch {
- for (turns.items) |t| self.alloc.free(t.text);
- turns.deinit();
- self.push(.err, "out of memory") catch {};
- return;
- };
- job.* = .{
- .gpa = self.alloc,
- .history = turns.toOwnedSlice() catch &.{},
- .params = .{
- .effort = self.effort,
- .fast = self.fast,
- .thinking = self.thinking_show,
- .ultracode = self.ultracode,
- .goal = self.goal orelse "",
- },
- .stream = .{ .buf = self.alloc.alloc(u8, 256 * 1024) catch &.{} },
- };
- self.push(.pending, "") catch {};
- self.pending = job;
- if (std.Thread.spawn(.{}, jobRun, .{job})) |th| {
- job.thread = th;
- } else |_| {
- job.threaded = false;
- jobRun(job); // no threads → run synchronously (spinner just won't animate)
- }
- }
-
- /// Collect a finished job: drop the placeholder, append the reply, free.
- fn finishJob(self: *Model) void {
- const job = self.pending orelse return;
- if (!job.done.load(.acquire)) return;
- if (job.threaded) job.thread.join();
- if (g_debug) {
- if (job.stream.snapshot(self.alloc)) |raw| {
- std.debug.print("\n[repl-debug] raw agent stream ({d} bytes):\n{s}\n", .{ raw.len, raw });
- self.alloc.free(raw);
- }
- std.debug.print("[repl-debug] final reply:\n{s}\n[repl-debug] ----- end turn -----\n", .{job.result orelse "(model call failed)"});
- }
-
- const n = self.history.items.len;
- if (n > 0 and self.history.items[n - 1].kind == .pending) {
- self.alloc.free(self.history.items[n - 1].text);
- self.history.shrinkRetainingCapacity(n - 1);
- }
- if (job.result) |r| {
- self.chars_out += r.len;
- if (renderMarkdown(self.alloc, r)) |rendered| {
- self.alloc.free(r);
- self.pushOwned(.assistant, rendered) catch self.alloc.free(rendered);
- } else |_| {
- self.pushOwned(.assistant, r) catch self.alloc.free(r);
- }
- } else if (self.cancel_requested) {
- // Force-steer interrupted this turn (runTurn → error.Interrupted →
- // replTurnCb returns null); not an error.
- self.push(.info, "⏹ interrupted") catch {};
- } else {
- self.push(.err, "model call failed — check /model and your API key") catch {};
- }
- for (job.history) |t| self.alloc.free(t.text);
- self.alloc.free(job.history);
- if (job.stream.buf.len > 0) self.alloc.free(job.stream.buf);
- self.alloc.destroy(job);
- self.pending = null;
- self.cancel_requested = false;
- self.scroll = 0; // reply landed → jump to the latest
- }
-
- /// Pop the next queued steer line (FIFO) and run it as the next turn.
- /// Returns the applyLine Effect so a steered "/quit" still propagates.
- fn drainSteer(self: *Model) Effect {
- if (self.steer_queue.items.len == 0) return .stay;
- const text = self.steer_queue.orderedRemove(0);
- defer self.alloc.free(text);
- return self.applyLine(text);
- }
+ // Chat-turn/background-thread logic (startJob/finishJob/drainSteer/
+ // steerEnter) lives in repl_model_turn.zig.
+ pub const startJob = model_turn.startJob;
+ pub const finishJob = model_turn.finishJob;
+ pub const drainSteer = model_turn.drainSteer;
- fn setGoal(self: *Model, text: []const u8) void {
- if (self.goal) |g| self.alloc.free(g);
- self.goal = if (text.len > 0) (self.alloc.dupe(u8, text) catch null) else null;
- }
+ // /command handlers live in repl_model_commands.zig.
+ pub const setGoal = model_commands.setGoal;
/// Core submit logic. Returns the Effect; on a chat prompt it spawns a job
/// (self.pending becomes non-null), which the caller turns into a poll tick.
@@ -429,7 +282,7 @@ pub const Model = struct {
self.startJob();
return .stay;
}
- if (eval(line)) |v| {
+ if (parser_mod.eval(line)) |v| {
self.pushFmt(.result, "{d}", .{v}) catch {};
} else |e| {
self.pushFmt(.err, "{s}", .{@errorName(e)}) catch {};
@@ -437,166 +290,12 @@ pub const Model = struct {
return .stay;
}
- fn runCommand(self: *Model, line: []const u8) void {
- const sp = std.mem.indexOfScalar(u8, line, ' ');
- const cmd = if (sp) |i| line[0..i] else line;
- const arg = std.mem.trim(u8, if (sp) |i| line[i + 1 ..] else "", " \t");
-
- if (eqlAny(cmd, &.{ "/q", "/quit", "/exit" })) {
- self.quit_requested = true;
- } else if (std.mem.eql(u8, cmd, "/clear")) {
- self.clearHistory();
- } else if (std.mem.eql(u8, cmd, "/new")) {
- self.clearHistory();
- self.turns = 0;
- self.chars_in = 0;
- self.chars_out = 0;
- self.push(.info, "started a new conversation") catch {};
- } else if (std.mem.eql(u8, cmd, "/rewind")) {
- self.rewind();
- } else if (std.mem.eql(u8, cmd, "/compact")) {
- self.compact();
- } else if (std.mem.eql(u8, cmd, "/help")) {
- self.push(.info, if (self.chat) HELP_CHAT else HELP_CALC) catch {};
- } else if (std.mem.eql(u8, cmd, "/model")) {
- if (arg.len == 0) {
- if (g_model_name.len > 0) self.pushFmt(.info, "model: {s}", .{g_model_name}) catch {} else self.push(.info, "no model configured") catch {};
- } else if (g_model_fn) |f| {
- if (f(g_turn_ctx, self.alloc, arg)) |nm| {
- g_model_name = nm;
- self.pushFmt(.info, "switched to {s}", .{nm}) catch {};
- } else self.pushFmt(.err, "couldn't switch to '{s}' — see /models (need a key/login for it)", .{arg}) catch {};
- } else self.push(.info, "model switching isn't available (offline mode)") catch {};
- } else if (std.mem.eql(u8, cmd, "/models")) {
- if (g_models.len > 0) self.pushFmt(.info, "available models:\n {s}\nswitch with /model <name>", .{g_models}) catch {} else self.push(.info, "no model table (offline mode)") catch {};
- } else if (eqlAny(cmd, &.{ "/effort", "/reasoning" })) {
- if (std.mem.eql(u8, arg, "low")) self.effort = .low else if (std.mem.eql(u8, arg, "high")) self.effort = .high else if (std.mem.eql(u8, arg, "medium") or std.mem.eql(u8, arg, "med")) self.effort = .medium else {
- self.push(.info, "usage: /effort low|medium|high") catch {};
- return;
- }
- self.pushFmt(.info, "reasoning effort: {s}", .{@tagName(self.effort)}) catch {};
- } else if (std.mem.eql(u8, cmd, "/fast")) {
- self.fast = parseToggle(arg, self.fast);
- self.pushFmt(.info, "fast mode: {s}", .{onOff(self.fast)}) catch {};
- } else if (std.mem.eql(u8, cmd, "/thinking")) {
- self.thinking_show = parseToggle(arg, self.thinking_show);
- self.pushFmt(.info, "show thinking: {s}", .{onOff(self.thinking_show)}) catch {};
- } else if (eqlAny(cmd, &.{ "/ultracode", "/ult" })) {
- self.ultracode = parseToggle(arg, self.ultracode);
- self.pushFmt(.info, "ultracode: {s}", .{onOff(self.ultracode)}) catch {};
- } else if (std.mem.eql(u8, cmd, "/strict")) {
- self.strict = parseToggle(arg, self.strict);
- self.pushFmt(.info, "strict mode: {s}", .{onOff(self.strict)}) catch {};
- } else if (std.mem.eql(u8, cmd, "/keepcontext")) {
- self.keepcontext = parseToggle(arg, self.keepcontext);
- self.pushFmt(.info, "keep context: {s}", .{onOff(self.keepcontext)}) catch {};
- } else if (std.mem.eql(u8, cmd, "/plan")) {
- self.plan = parseToggle(arg, self.plan);
- self.pushFmt(.info, "plan mode: {s} (no tools to plan over in the chat repl)", .{onOff(self.plan)}) catch {};
- } else if (std.mem.eql(u8, cmd, "/yolo")) {
- self.yolo = parseToggle(arg, self.yolo);
- self.pushFmt(.info, "yolo: {s} (the chat repl runs no tools — nothing to skip)", .{onOff(self.yolo)}) catch {};
- } else if (std.mem.eql(u8, cmd, "/title")) {
- self.title = parseToggle(arg, self.title);
- self.pushFmt(.info, "ai title: {s}", .{onOff(self.title)}) catch {};
- } else if (std.mem.eql(u8, cmd, "/goal")) {
- self.setGoal(arg);
- if (self.goal) |g| self.pushFmt(.info, "goal set: {s} - I'll track it as a checklist", .{g}) catch {} else self.push(.info, "goal cleared") catch {};
- } else if (std.mem.eql(u8, cmd, "/rename")) {
- self.setSession(arg);
- self.pushFmt(.info, "session renamed: {s}", .{self.session_name orelse "repl"}) catch {};
- } else if (std.mem.eql(u8, cmd, "/animation")) {
- if (std.mem.eql(u8, arg, "dragon")) self.anim = .dragon else if (std.mem.eql(u8, arg, "braille")) self.anim = .braille else {
- self.push(.info, "usage: /animation braille|dragon") catch {};
- return;
- }
- self.pushFmt(.info, "spinner: {s}", .{@tagName(self.anim)}) catch {};
- } else if (std.mem.eql(u8, cmd, "/cost")) {
- self.pushFmt(.info, "session: {d} turn(s) · ~{d} chars sent · ~{d} received", .{ self.turns, self.chars_in, self.chars_out }) catch {};
- } else if (std.mem.eql(u8, cmd, "/debug")) {
- g_debug = !g_debug;
- self.dump_next = g_debug;
- self.pushFmt(.info, "debug: {s} — run `graff repl 2>/tmp/repl.log` to capture (raw agent stream per turn + frames → stderr)", .{onOff(g_debug)}) catch {};
- } else if (std.mem.eql(u8, cmd, "/bash")) {
- self.push(.info, "running shell commands needs the agent loop — use the main `graff` session, or your shell") catch {};
- } else if (std.mem.eql(u8, cmd, "/mcp")) {
- self.push(.info, "MCP servers attach to the agent loop, not the chat repl") catch {};
- } else if (std.mem.eql(u8, cmd, "/skills")) {
- self.push(.info, "skills (codedb, zigrep, …) attach to the agent loop, not the chat repl") catch {};
- } else if (std.mem.eql(u8, cmd, "/agents")) {
- self.push(.info, "named agents are used by the agent loop, not single-shot chat") catch {};
- } else if (std.mem.eql(u8, cmd, "/hooks")) {
- self.push(.info, "hooks run around the agent loop, not the chat repl") catch {};
- } else if (std.mem.eql(u8, cmd, "/loop")) {
- self.push(.info, "`/loop` schedules repeated runs in the main session, not the chat repl") catch {};
- } else if (eqlAny(cmd, &.{ "/trace", "/trajectory" })) {
- self.push(.info, "trace/trajectory logging is a main-session feature") catch {};
- } else if (eqlAny(cmd, &.{ "/save", "/resume", "/sessions" })) {
- self.push(.info, "the chat repl is ephemeral — session save/resume/list lives in the main `graff` session") catch {};
- } else if (eqlAny(cmd, &.{ "/image", "/paste" })) {
- self.push(.info, "image/paste input isn't wired into the chat repl yet") catch {};
- } else if (std.mem.eql(u8, cmd, "/key")) {
- self.push(.info, "manage API keys with `graff key set|list` outside the repl") catch {};
- } else {
- self.pushFmt(.err, "unknown command: {s} — try /help", .{cmd}) catch {};
- }
- }
-
- /// Remove the last user turn and everything after it (its reply).
- fn rewind(self: *Model) void {
- var i = self.history.items.len;
- while (i > 0) : (i -= 1) {
- if (self.history.items[i - 1].kind == .input) break;
- }
- if (i == 0) {
- self.push(.info, "nothing to rewind") catch {};
- return;
- }
- var j = self.history.items.len;
- while (j > i - 1) : (j -= 1) self.alloc.free(self.history.items[j - 1].text);
- self.history.shrinkRetainingCapacity(i - 1);
- self.push(.info, "rewound the last turn") catch {};
- }
+ pub const runCommand = model_commands.runCommand;
+ pub const rewind = model_commands.rewind;
+ pub const compact = model_commands.compact;
+ pub const setSession = model_commands.setSession;
- /// Drop older turns, keeping the welcome banner + the most recent lines.
- fn compact(self: *Model) void {
- const keep_recent = 6;
- const n = self.history.items.len;
- if (n <= keep_recent + 1) {
- self.push(.info, "nothing to compact") catch {};
- return;
- }
- const drop_to = n - keep_recent;
- var k: usize = 1;
- while (k < drop_to) : (k += 1) self.alloc.free(self.history.items[k].text);
- std.mem.copyForwards(Entry, self.history.items[1..], self.history.items[drop_to..]);
- self.history.shrinkRetainingCapacity(1 + (n - drop_to));
- self.push(.info, "compacted — kept the welcome banner + recent turns") catch {};
- }
-
- fn setSession(self: *Model, name: []const u8) void {
- if (self.session_name) |s| self.alloc.free(s);
- self.session_name = if (name.len > 0) (self.alloc.dupe(u8, name) catch null) else null;
- }
-
- /// Handle Enter while a turn streams. A typed line is queued as a steer
- /// (runs as a follow-up turn after the current one finishes); an empty line
- /// with a non-empty queue FORCES — flags the turn for interrupt and signals
- /// the harness via the cancel callback so the queue drains immediately.
- fn steerEnter(self: *Model) void {
- const v = std.mem.trim(u8, self.input.getValue(), " \t\r\n");
- if (v.len > 0) {
- if (self.alloc.dupe(u8, v)) |dup| {
- self.steer_queue.append(dup) catch self.alloc.free(dup);
- self.input.setValue("") catch {};
- self.pushFmt(.info, "↳ steer › queued ({d} waiting)", .{self.steer_queue.items.len}) catch {};
- } else |_| {}
- } else if (self.steer_queue.items.len > 0) {
- self.cancel_requested = true;
- if (g_cancel_fn) |f| f(g_turn_ctx);
- self.push(.info, "↳ force › interrupting…") catch {};
- }
- }
+ pub const steerEnter = model_turn.steerEnter;
pub fn update(self: *Model, msg: Msg, ctx: *zz.Context) zz.Cmd(Msg) {
switch (msg) {
@@ -659,196 +358,20 @@ pub const Model = struct {
return .none;
}
- fn spinnerFrame(self: *const Model, now_ms: u64) []const u8 {
- return switch (self.anim) {
- .braille => braille_frames[(now_ms / 80) % braille_frames.len],
- .dragon => dragon_frames[(now_ms / 220) % dragon_frames.len],
- };
- }
-
- fn statusLine(self: *const Model, a: std.mem.Allocator) ![]const u8 {
- var b = std.array_list.Managed(u8).init(a);
- if (self.scroll > 0) try b.appendSlice("↑ scrolled · PgDn to bottom · ");
- if (self.chat and g_model_name.len > 0) try b.appendSlice(g_model_name) else try b.appendSlice("offline · arithmetic");
- try b.appendSlice(try std.fmt.allocPrint(a, " · effort:{s}", .{@tagName(self.effort)}));
- if (self.fast) try b.appendSlice(" · ⚡fast");
- if (self.ultracode) try b.appendSlice(" · ✦ultracode");
- if (self.plan) try b.appendSlice(" · plan");
- if (self.yolo) try b.appendSlice(" · yolo");
- if (self.strict) try b.appendSlice(" · strict");
- if (self.thinking_show) try b.appendSlice(" · thinking");
- if (!self.keepcontext) try b.appendSlice(" · no-ctx");
- if (self.goal != null) try b.appendSlice(" · 🎯goal");
- if (self.turns > 0) try b.appendSlice(try std.fmt.allocPrint(a, " · {d}t", .{self.turns}));
- try b.appendSlice(" · /help");
- return b.items;
- }
-
- /// Render at `term_width` x `term_height`; `now_ms` drives animations. Input
- /// box is pinned to the bottom; conversation fills from the top.
- pub fn render(self: *Model, gpa: std.mem.Allocator, term_width: usize, term_height: usize, now_ms: u64) ![]const u8 {
- var arena_state = std.heap.ArenaAllocator.init(gpa);
- defer arena_state.deinit();
- const a = arena_state.allocator();
-
- const inner: u16 = @intCast(@max(@as(usize, 8), term_width) - 4);
- const border_color = if (self.ultracode) rainbow[(now_ms / 90) % rainbow.len] else zz.Color.brightBlack;
- const box = (zz.Style{}).borderAll(zz.Border.rounded)
- .borderForeground(border_color).paddingLeft(1).paddingRight(1).width(inner);
-
- var top = std.array_list.Managed(u8).init(a);
- for (self.history.items) |e| {
- switch (e.kind) {
- .welcome => {
- const star = try (zz.Style{}).fg(accent).bold(true).render(a, "✻");
- const sub = if (self.chat) "Chat with the model — ask anything." else "i64 arithmetic — + - * / %, parens, unary minus.";
- const body = try std.fmt.allocPrint(a, "{s} Welcome to graff repl\n\n {s}\n /help for commands · ctrl-c to quit", .{ star, sub });
- try top.appendSlice(try box.render(a, body));
- try top.append('\n');
- },
- .input => {
- const g = try (zz.Style{}).fg(.brightBlack).render(a, ">");
- try top.appendSlice(try std.fmt.allocPrint(a, "{s} {s}\n", .{ g, e.text }));
- },
- .result => {
- const g = try (zz.Style{}).fg(.green).bold(true).render(a, "⏺");
- try top.appendSlice(try std.fmt.allocPrint(a, "{s} {s}\n", .{ g, e.text }));
- },
- .assistant => {
- const g = try (zz.Style{}).fg(accent).bold(true).render(a, "⏺");
- try top.appendSlice(try std.fmt.allocPrint(a, "{s} {s}\n", .{ g, e.text }));
- },
- .pending => {
- const g = try (zz.Style{}).fg(accent).bold(true).render(a, self.spinnerFrame(now_ms));
- const live = if (self.pending) |job| job.stream.snapshot(a) else null;
- if (live) |s| {
- // Compact live activity: the last few lines of the
- // agent's output, control-stripped + width-truncated,
- // so tool chatter can't flood the pane.
- try top.appendSlice(try std.fmt.allocPrint(a, "{s} working…\n", .{g}));
- try top.appendSlice(try tailPreview(a, stripControl(a, s), term_width, 3));
- } else {
- const t = try (zz.Style{}).dim(true).render(a, "thinking…");
- try top.appendSlice(try std.fmt.allocPrint(a, "{s} {s}\n", .{ g, t }));
- }
- if (self.steer_queue.items.len > 0) {
- try top.appendSlice(try (zz.Style{}).dim(true).render(a, try std.fmt.allocPrint(a, " ↳ {d} steer queued · empty Enter runs now\n", .{self.steer_queue.items.len})));
- } else {
- try top.appendSlice(try (zz.Style{}).dim(true).render(a, " ↳ type to steer · Enter queues\n"));
- }
- },
- .err => {
- const g = try (zz.Style{}).fg(.red).bold(true).render(a, "⏺");
- const m = try (zz.Style{}).fg(.red).render(a, e.text);
- try top.appendSlice(try std.fmt.allocPrint(a, "{s} {s}\n", .{ g, m }));
- },
- .info => {
- try top.appendSlice(try (zz.Style{}).dim(true).render(a, e.text));
- try top.append('\n');
- },
- }
- }
-
- var bottom = std.array_list.Managed(u8).init(a);
- try bottom.appendSlice(try box.render(a, try self.input.view(a)));
- try bottom.append('\n');
- try bottom.appendSlice(try (zz.Style{}).dim(true).render(a, try self.statusLine(a)));
-
- // The conversation is a scrollable viewport above the pinned input box.
- // scroll = lines scrolled up from the bottom (0 = latest). Clamped here.
- const bottom_lines = std.mem.count(u8, bottom.items, "\n") + 1;
- const view_h = if (term_height > bottom_lines) term_height - bottom_lines else 1;
-
- var lines = std.array_list.Managed([]const u8).init(a);
- var it = std.mem.splitScalar(u8, top.items, '\n');
- while (it.next()) |ln| try lines.append(ln);
- if (lines.items.len > 0 and lines.items[lines.items.len - 1].len == 0) _ = lines.pop();
- const n = lines.items.len;
-
- var out = std.array_list.Managed(u8).init(a);
- // Reset the per-frame visible-row snapshot (Model-owned plaintext, so a
- // mouse row can be mapped back to conversation text for copy — #91).
- for (self.visible_text.items) |l| self.alloc.free(l);
- self.visible_text.clearRetainingCapacity();
- self.view_start = 0;
- self.view_rows = 0;
- if (n <= view_h) {
- self.scroll = 0;
- try out.appendSlice(top.items);
- for (0..(view_h - n)) |_| try out.append('\n');
- self.view_rows = n;
- for (lines.items[0..n]) |ln| {
- self.visible_text.append(self.alloc.dupe(u8, stripControl(a, ln)) catch continue) catch {};
- }
- } else {
- const max_scroll = n - view_h;
- if (self.scroll > max_scroll) self.scroll = max_scroll;
- const start = max_scroll - self.scroll;
- self.view_start = start;
- self.view_rows = view_h;
- for (lines.items[start .. start + view_h]) |ln| {
- try out.appendSlice(ln);
- try out.append('\n');
- self.visible_text.append(self.alloc.dupe(u8, stripControl(a, ln)) catch continue) catch {};
- }
- }
- try out.appendSlice(bottom.items);
- if (self.dump_next) {
- std.debug.print("\n[repl-debug] ===== rendered frame ({d}x{d}) =====\n{s}\n[repl-debug] ===== end frame =====\n", .{ term_width, term_height, out.items });
- self.dump_next = false;
- }
- return gpa.dupe(u8, out.items);
- }
+ // Pane rendering (spinnerFrame/statusLine/render/copySelection) lives in
+ // repl_model_render.zig.
+ pub const spinnerFrame = model_render.spinnerFrame;
+ pub const statusLine = model_render.statusLine;
+ pub const render = model_render.render;
pub fn view(self: *Model, ctx: *const zz.Context) []const u8 {
return self.render(ctx.allocator, ctx.width, ctx.height, ctx.elapsed / std.time.ns_per_ms) catch "repl: render error";
}
- /// Copy the conversation lines spanned by a drag-selection (screen rows
- /// r0..r1 inclusive, 0-based) to the clipboard via OSC52. Line-granular —
- /// restores copy after mouse mode disabled native terminal selection (#91).
- fn copySelection(self: *Model, ctx: *zz.Context, r0: usize, r1: usize) void {
- if (self.view_rows == 0 or self.visible_text.items.len == 0) return;
- const lo = @min(r0, r1);
- var hi = @max(r0, r1);
- if (lo >= self.view_rows) return; // selection started below the conversation
- if (hi >= self.view_rows) hi = self.view_rows - 1;
- if (hi >= self.visible_text.items.len) hi = self.visible_text.items.len - 1;
-
- var buf = std.array_list.Managed(u8).init(self.alloc);
- defer buf.deinit();
- var r = lo;
- while (r <= hi) : (r += 1) {
- const ln = std.mem.trimEnd(u8, self.visible_text.items[r], " \t");
- buf.appendSlice(ln) catch return;
- if (r != hi) buf.append('\n') catch return;
- }
- const text = std.mem.trim(u8, buf.items, " \t\r\n");
- if (text.len == 0) return;
- _ = ctx.setClipboard(text) catch false;
- // render() is hash-gated and may skip its flush; push the OSC52 out now.
- if (ctx._terminal) |term| term.flush() catch {};
- }
+ pub const copySelection = model_render.copySelection;
};
-const HELP_CHAT =
- \\Commands (mirrors the graff session):
- \\ /help /clear /new /quit conversation
- \\ /rewind /compact /cost history
- \\ /model [name] /models model (switch / list)
- \\ /effort low|med|high /reasoning reasoning depth
- \\ /fast /thinking /ultracode thinking controls (toggles)
- \\ /goal <text> standing objective (tracked as a checklist)
- \\ /plan /strict /yolo /keepcontext /title modes
- \\ /rename <name> /animation braille|dragon
- \\ /bash /save /resume /sessions /trace /trajectory
- \\ /agents /skills /hooks /mcp /loop /image /paste /key
- \\
- \\Type a message and press enter to send it to the model. Toggles accept
- \\[on|off] or flip when bare. Commands needing the agent loop explain so.
-;
-
-const HELP_CALC =
+pub const HELP_CALC =
\\Commands:
\\ /help this help
\\ /clear clear the conversation
@@ -862,7 +385,7 @@ const HELP_CALC =
/// streamed renderer: fenced code blocks (left bar), inline `code`, **bold**,
/// # headers, and - bullets. Temporaries live in a local arena; the result is
/// owned by `gpa`.
-fn renderMarkdown(gpa: std.mem.Allocator, src: []const u8) ![]const u8 {
+pub fn renderMarkdown(gpa: std.mem.Allocator, src: []const u8) ![]const u8 {
var arena_state = std.heap.ArenaAllocator.init(gpa);
defer arena_state.deinit();
const a = arena_state.allocator();
@@ -897,227 +420,23 @@ fn renderMarkdown(gpa: std.mem.Allocator, src: []const u8) ![]const u8 {
try out.appendSlice(try (zz.Style{}).fg(accent).render(a, " • "));
rest = t[2..];
}
- try renderInline(&out, a, rest);
+ try util.renderInline(&out, a, rest);
}
return gpa.dupe(u8, out.items);
}
-fn renderInline(out: *std.array_list.Managed(u8), a: std.mem.Allocator, line: []const u8) !void {
- var i: usize = 0;
- while (i < line.len) {
- const c = line[i];
- if (c == '`') {
- if (std.mem.indexOfScalarPos(u8, line, i + 1, '`')) |end| {
- try out.appendSlice(try (zz.Style{}).fg(.cyan).render(a, line[i + 1 .. end]));
- i = end + 1;
- continue;
- }
- } else if (c == '*' and i + 1 < line.len and line[i + 1] == '*') {
- if (std.mem.indexOfPos(u8, line, i + 2, "**")) |end| {
- try out.appendSlice(try (zz.Style{}).bold(true).render(a, line[i + 2 .. end]));
- i = end + 2;
- continue;
- }
- }
- try out.append(c);
- i += 1;
- }
-}
-fn eqlAny(s: []const u8, options: []const []const u8) bool {
- for (options) |o| if (std.mem.eql(u8, s, o)) return true;
- return false;
-}
-
-/// Strip ANSI/control sequences (and CR) so the agent's live streamed output
-/// can be shown as plain text — cursor moves/redraws can't corrupt the pane.
-/// Result owned by `a`.
-fn stripControl(a: std.mem.Allocator, s: []const u8) []const u8 {
- var out = std.array_list.Managed(u8).init(a);
- var i: usize = 0;
- while (i < s.len) {
- const c = s[i];
- if (c == 0x1b) {
- i += 1;
- if (i < s.len and s[i] == '[') {
- i += 1;
- while (i < s.len and !std.ascii.isAlphabetic(s[i])) i += 1;
- if (i < s.len) i += 1;
- } else if (i < s.len and s[i] == ']') {
- i += 1;
- while (i < s.len and s[i] != 0x07 and s[i] != 0x1b) i += 1;
- if (i < s.len) i += 1;
- } else if (i < s.len) {
- i += 1;
- }
- } else if (c == '\r') {
- i += 1;
- } else {
- out.append(c) catch {};
- i += 1;
- }
- }
- return out.items;
-}
-
-/// Compact live-activity preview: the last `n` non-empty lines of `plain`, each
-/// width-truncated (UTF-8 safe) and dimmed, indented. Keeps the agent's tool
-/// chatter from flooding the pane while still showing live progress.
-fn tailPreview(a: std.mem.Allocator, plain: []const u8, width: usize, n: usize) ![]const u8 {
- var lines = std.array_list.Managed([]const u8).init(a);
- var it = std.mem.splitScalar(u8, plain, '\n');
- while (it.next()) |ln| {
- const t = std.mem.trim(u8, ln, " \t");
- if (t.len > 0) try lines.append(t);
- }
- const start = if (lines.items.len > n) lines.items.len - n else 0;
- const cap = if (width > 6) width - 4 else 12;
- var out = std.array_list.Managed(u8).init(a);
- for (lines.items[start..]) |ln| {
- var tw = @min(ln.len, cap);
- while (tw > 0 and tw < ln.len and (ln[tw] & 0xC0) == 0x80) tw -= 1; // don't cut mid-UTF-8
- try out.appendSlice(" ");
- try out.appendSlice(try (zz.Style{}).dim(true).render(a, ln[0..tw]));
- try out.append('\n');
- }
- return out.items;
-}
-
-fn parseToggle(arg: []const u8, current: bool) bool {
- if (std.mem.eql(u8, arg, "on")) return true;
- if (std.mem.eql(u8, arg, "off")) return false;
- return !current; // bare toggle
-}
-
-fn onOff(v: bool) []const u8 {
- return if (v) "on" else "off";
-}
-
-/// Run the REPL. Pass a `turn_fn` (+ opaque ctx + model name) to chat with a
-/// model; pass null/null/"" for the offline arithmetic engine.
-pub fn run(
- gpa: std.mem.Allocator,
- io: std.Io,
- environ_map: *const std.process.Environ.Map,
- turn_ctx: ?*anyopaque,
- turn_fn: ?TurnFn,
- model_fn: ?ModelFn,
- cancel_fn: ?CancelFn,
- model_name: []const u8,
- models: []const u8,
-) !void {
- g_turn_ctx = turn_ctx;
- g_turn_fn = turn_fn;
- g_model_fn = model_fn;
- g_cancel_fn = cancel_fn;
- g_model_name = model_name;
- g_debug = environ_map.get("GRAFF_REPL_DEBUG") != null;
- g_models = models;
- var program = zz.Program(Model).initWithOptions(gpa, io, environ_map, .{ .mouse = true });
- defer program.deinit();
- try program.run();
-}
-
-/// Headless, scriptable twin of run(): drives the SAME Model + turn_fn as the
-/// live TUI, but reads input lines from `in` and prints each turn's new output to
-/// `out` instead of taking over the terminal. Lets
-/// printf '/goal X\n<prompt>\n' | graff repl
-/// exercise the exact repl path (goal steering, todo_write, cross-turn continuity)
-/// from a script / CI / test — a 1:1 map of the interactive behavior. main() routes
-/// here automatically when stdin is not a TTY. GRAFF_REPL_DEBUG=1 additionally dumps
-/// each turn's raw agent stream to stderr (where mid-turn renders like the
-/// todo_write checklist appear).
-pub fn runScripted(
- gpa: std.mem.Allocator,
- io: std.Io,
- environ_map: *const std.process.Environ.Map,
- in: *std.Io.Reader,
- out: *std.Io.Writer,
- turn_ctx: ?*anyopaque,
- turn_fn: ?TurnFn,
- model_fn: ?ModelFn,
- cancel_fn: ?CancelFn,
- model_name: []const u8,
- models: []const u8,
-) !void {
- g_turn_ctx = turn_ctx;
- g_turn_fn = turn_fn;
- g_model_fn = model_fn;
- g_cancel_fn = cancel_fn;
- g_model_name = model_name;
- g_debug = environ_map.get("GRAFF_REPL_DEBUG") != null;
- g_models = models;
-
- var m: Model = undefined;
- m.setup(gpa);
- defer m.deinit();
-
- while (true) {
- const raw = (in.takeDelimiter('\n') catch null) orelse break; // EOF ends the script
- const line = std.mem.trim(u8, raw, " \t\r\n");
- if (line.len == 0) continue;
-
- try out.print("\n> {s}\n", .{line});
- try out.flush();
-
- const before = m.history.items.len;
- const eff = m.applyLine(line);
-
- // A chat line spawns a background turn; a slash command runs inline.
- if (m.pending != null) {
- while (m.pending) |job| {
- if (job.done.load(.acquire)) {
- m.finishJob();
- break;
- }
- io.sleep(.fromMilliseconds(20), .awake) catch {};
- }
- }
-
- // Print what the line produced — slash-command info, the assistant reply,
- // or an error. The user line is already echoed above; the pending
- // placeholder is gone once finishJob ran.
- var i = before;
- while (i < m.history.items.len) : (i += 1) {
- switch (m.history.items[i].kind) {
- .pending, .input, .welcome => {},
- else => try out.print("{s}\n", .{m.history.items[i].text}),
- }
- }
- try out.flush();
-
- if (eff == .quit) break;
- }
-
- const pane = try m.render(gpa, 100, 60, 0);
- defer gpa.free(pane);
- try out.print("\n===== final repl pane =====\n{s}\n===========================\n", .{pane});
- try out.flush();
-}
-
-pub fn main(init: std.process.Init) !void {
- return run(init.gpa, init.io, init.environ_map, null, null, null, null, "", "");
-}
+// run/runScripted (the live TUI loop + the headless/scriptable twin) and
+// main() (the standalone `graff-repl` exe's entry point) live in
+// repl_run.zig.
+pub const run = repl_run.run;
+pub const runScripted = repl_run.runScripted;
+pub const main = repl_run.main;
// ---------------------------------------------------------------------------
// Tests — headless. Chat path uses a stubbed turn_fn (no network); it still
// exercises the real background-thread path.
// ---------------------------------------------------------------------------
-test "eval: precedence and parentheses" {
- try std.testing.expectEqual(@as(i64, 14), try eval("2 + 3 * 4"));
- try std.testing.expectEqual(@as(i64, 20), try eval("(2 + 3) * 4"));
- try std.testing.expectEqual(@as(i64, -6), try eval("-(2 * 3)"));
- try std.testing.expectEqual(@as(i64, 2), try eval("7 / 3"));
- try std.testing.expectEqual(@as(i64, 1), try eval("7 % 3"));
-}
-
-test "eval: error cases" {
- try std.testing.expectError(error.DivByZero, eval("1 / 0"));
- try std.testing.expectError(error.SyntaxError, eval("2 +"));
- try std.testing.expectError(error.SyntaxError, eval("2 2"));
- try std.testing.expectError(error.Overflow, eval("9223372036854775807 + 1"));
-}
-
test "model: offline arithmetic path (no turn_fn)" {
g_turn_fn = null;
var m: Model = undefined;
diff --git a/src/repl_model_commands.zig b/src/repl_model_commands.zig
new file mode 100644
index 00000000..4c906329
--- /dev/null
+++ b/src/repl_model_commands.zig
@@ -0,0 +1,163 @@
+//! `graff repl` Model — the `/`-command dispatcher and the small session
+//! mutators it drives (goal text, rewind/compact history, session rename).
+//! Split out of the Model struct in repl.zig (#123, 600-line goal); reached
+//! through repl.zig's member aliases, so both `self.runCommand(...)` and
+//! `Model.runCommand(...)` resolve here unchanged.
+
+const std = @import("std");
+
+const repl = @import("repl.zig");
+const Model = repl.Model;
+
+const util = @import("repl_util.zig");
+const eqlAny = util.eqlAny;
+const parseToggle = util.parseToggle;
+const onOff = util.onOff;
+const HELP_CHAT = util.HELP_CHAT;
+
+pub fn setGoal(self: *Model, text: []const u8) void {
+ if (self.goal) |g| self.alloc.free(g);
+ self.goal = if (text.len > 0) (self.alloc.dupe(u8, text) catch null) else null;
+}
+
+pub fn runCommand(self: *Model, line: []const u8) void {
+ const sp = std.mem.indexOfScalar(u8, line, ' ');
+ const cmd = if (sp) |i| line[0..i] else line;
+ const arg = std.mem.trim(u8, if (sp) |i| line[i + 1 ..] else "", " \t");
+
+ if (eqlAny(cmd, &.{ "/q", "/quit", "/exit" })) {
+ self.quit_requested = true;
+ } else if (std.mem.eql(u8, cmd, "/clear")) {
+ self.clearHistory();
+ } else if (std.mem.eql(u8, cmd, "/new")) {
+ self.clearHistory();
+ self.turns = 0;
+ self.chars_in = 0;
+ self.chars_out = 0;
+ self.push(.info, "started a new conversation") catch {};
+ } else if (std.mem.eql(u8, cmd, "/rewind")) {
+ self.rewind();
+ } else if (std.mem.eql(u8, cmd, "/compact")) {
+ self.compact();
+ } else if (std.mem.eql(u8, cmd, "/help")) {
+ self.push(.info, if (self.chat) HELP_CHAT else repl.HELP_CALC) catch {};
+ } else if (std.mem.eql(u8, cmd, "/model")) {
+ if (arg.len == 0) {
+ if (repl.g_model_name.len > 0) self.pushFmt(.info, "model: {s}", .{repl.g_model_name}) catch {} else self.push(.info, "no model configured") catch {};
+ } else if (repl.g_model_fn) |f| {
+ if (f(repl.g_turn_ctx, self.alloc, arg)) |nm| {
+ repl.g_model_name = nm;
+ self.pushFmt(.info, "switched to {s}", .{nm}) catch {};
+ } else self.pushFmt(.err, "couldn't switch to '{s}' — see /models (need a key/login for it)", .{arg}) catch {};
+ } else self.push(.info, "model switching isn't available (offline mode)") catch {};
+ } else if (std.mem.eql(u8, cmd, "/models")) {
+ if (repl.g_models.len > 0) self.pushFmt(.info, "available models:\n {s}\nswitch with /model <name>", .{repl.g_models}) catch {} else self.push(.info, "no model table (offline mode)") catch {};
+ } else if (eqlAny(cmd, &.{ "/effort", "/reasoning" })) {
+ if (std.mem.eql(u8, arg, "low")) self.effort = .low else if (std.mem.eql(u8, arg, "high")) self.effort = .high else if (std.mem.eql(u8, arg, "medium") or std.mem.eql(u8, arg, "med")) self.effort = .medium else {
+ self.push(.info, "usage: /effort low|medium|high") catch {};
+ return;
+ }
+ self.pushFmt(.info, "reasoning effort: {s}", .{@tagName(self.effort)}) catch {};
+ } else if (std.mem.eql(u8, cmd, "/fast")) {
+ self.fast = parseToggle(arg, self.fast);
+ self.pushFmt(.info, "fast mode: {s}", .{onOff(self.fast)}) catch {};
+ } else if (std.mem.eql(u8, cmd, "/thinking")) {
+ self.thinking_show = parseToggle(arg, self.thinking_show);
+ self.pushFmt(.info, "show thinking: {s}", .{onOff(self.thinking_show)}) catch {};
+ } else if (eqlAny(cmd, &.{ "/ultracode", "/ult" })) {
+ self.ultracode = parseToggle(arg, self.ultracode);
+ self.pushFmt(.info, "ultracode: {s}", .{onOff(self.ultracode)}) catch {};
+ } else if (std.mem.eql(u8, cmd, "/strict")) {
+ self.strict = parseToggle(arg, self.strict);
+ self.pushFmt(.info, "strict mode: {s}", .{onOff(self.strict)}) catch {};
+ } else if (std.mem.eql(u8, cmd, "/keepcontext")) {
+ self.keepcontext = parseToggle(arg, self.keepcontext);
+ self.pushFmt(.info, "keep context: {s}", .{onOff(self.keepcontext)}) catch {};
+ } else if (std.mem.eql(u8, cmd, "/plan")) {
+ self.plan = parseToggle(arg, self.plan);
+ self.pushFmt(.info, "plan mode: {s} (no tools to plan over in the chat repl)", .{onOff(self.plan)}) catch {};
+ } else if (std.mem.eql(u8, cmd, "/yolo")) {
+ self.yolo = parseToggle(arg, self.yolo);
+ self.pushFmt(.info, "yolo: {s} (the chat repl runs no tools — nothing to skip)", .{onOff(self.yolo)}) catch {};
+ } else if (std.mem.eql(u8, cmd, "/title")) {
+ self.title = parseToggle(arg, self.title);
+ self.pushFmt(.info, "ai title: {s}", .{onOff(self.title)}) catch {};
+ } else if (std.mem.eql(u8, cmd, "/goal")) {
+ self.setGoal(arg);
+ if (self.goal) |g| self.pushFmt(.info, "goal set: {s} - I'll track it as a checklist", .{g}) catch {} else self.push(.info, "goal cleared") catch {};
+ } else if (std.mem.eql(u8, cmd, "/rename")) {
+ self.setSession(arg);
+ self.pushFmt(.info, "session renamed: {s}", .{self.session_name orelse "repl"}) catch {};
+ } else if (std.mem.eql(u8, cmd, "/animation")) {
+ if (std.mem.eql(u8, arg, "dragon")) self.anim = .dragon else if (std.mem.eql(u8, arg, "braille")) self.anim = .braille else {
+ self.push(.info, "usage: /animation braille|dragon") catch {};
+ return;
+ }
+ self.pushFmt(.info, "spinner: {s}", .{@tagName(self.anim)}) catch {};
+ } else if (std.mem.eql(u8, cmd, "/cost")) {
+ self.pushFmt(.info, "session: {d} turn(s) · ~{d} chars sent · ~{d} received", .{ self.turns, self.chars_in, self.chars_out }) catch {};
+ } else if (std.mem.eql(u8, cmd, "/debug")) {
+ repl.g_debug = !repl.g_debug;
+ self.dump_next = repl.g_debug;
+ self.pushFmt(.info, "debug: {s} — run `graff repl 2>/tmp/repl.log` to capture (raw agent stream per turn + frames → stderr)", .{onOff(repl.g_debug)}) catch {};
+ } else if (std.mem.eql(u8, cmd, "/bash")) {
+ self.push(.info, "running shell commands needs the agent loop — use the main `graff` session, or your shell") catch {};
+ } else if (std.mem.eql(u8, cmd, "/mcp")) {
+ self.push(.info, "MCP servers attach to the agent loop, not the chat repl") catch {};
+ } else if (std.mem.eql(u8, cmd, "/skills")) {
+ self.push(.info, "skills (codedb, zigrep, …) attach to the agent loop, not the chat repl") catch {};
+ } else if (std.mem.eql(u8, cmd, "/agents")) {
+ self.push(.info, "named agents are used by the agent loop, not single-shot chat") catch {};
+ } else if (std.mem.eql(u8, cmd, "/hooks")) {
+ self.push(.info, "hooks run around the agent loop, not the chat repl") catch {};
+ } else if (std.mem.eql(u8, cmd, "/loop")) {
+ self.push(.info, "`/loop` schedules repeated runs in the main session, not the chat repl") catch {};
+ } else if (eqlAny(cmd, &.{ "/trace", "/trajectory" })) {
+ self.push(.info, "trace/trajectory logging is a main-session feature") catch {};
+ } else if (eqlAny(cmd, &.{ "/save", "/resume", "/sessions" })) {
+ self.push(.info, "the chat repl is ephemeral — session save/resume/list lives in the main `graff` session") catch {};
+ } else if (eqlAny(cmd, &.{ "/image", "/paste" })) {
+ self.push(.info, "image/paste input isn't wired into the chat repl yet") catch {};
+ } else if (std.mem.eql(u8, cmd, "/key")) {
+ self.push(.info, "manage API keys with `graff key set|list` outside the repl") catch {};
+ } else {
+ self.pushFmt(.err, "unknown command: {s} — try /help", .{cmd}) catch {};
+ }
+}
+
+/// Remove the last user turn and everything after it (its reply).
+pub fn rewind(self: *Model) void {
+ var i = self.history.items.len;
+ while (i > 0) : (i -= 1) {
+ if (self.history.items[i - 1].kind == .input) break;
+ }
+ if (i == 0) {
+ self.push(.info, "nothing to rewind") catch {};
+ return;
+ }
+ var j = self.history.items.len;
+ while (j > i - 1) : (j -= 1) self.alloc.free(self.history.items[j - 1].text);
+ self.history.shrinkRetainingCapacity(i - 1);
+ self.push(.info, "rewound the last turn") catch {};
+}
+
+/// Drop older turns, keeping the welcome banner + the most recent lines.
+pub fn compact(self: *Model) void {
+ const keep_recent = 6;
+ const n = self.history.items.len;
+ if (n <= keep_recent + 1) {
+ self.push(.info, "nothing to compact") catch {};
+ return;
+ }
+ const drop_to = n - keep_recent;
+ var k: usize = 1;
+ while (k < drop_to) : (k += 1) self.alloc.free(self.history.items[k].text);
+ std.mem.copyForwards(repl.Entry, self.history.items[1..], self.history.items[drop_to..]);
+ self.history.shrinkRetainingCapacity(1 + (n - drop_to));
+ self.push(.info, "compacted — kept the welcome banner + recent turns") catch {};
+}
+
+pub fn setSession(self: *Model, name: []const u8) void {
+ if (self.session_name) |s| self.alloc.free(s);
+ self.session_name = if (name.len > 0) (self.alloc.dupe(u8, name) catch null) else null;
+}
diff --git a/src/repl_model_render.zig b/src/repl_model_render.zig
new file mode 100644
index 00000000..4bfc83ed
--- /dev/null
+++ b/src/repl_model_render.zig
@@ -0,0 +1,183 @@
+//! `graff repl` Model — pane rendering: spinner frame selection, the status
+//! line, the full frame draw (conversation history + input box, clamped to
+//! the terminal size), and mouse drag-selection copy. Split out of the
+//! Model struct in repl.zig (#123, 600-line goal); reached through
+//! repl.zig's member aliases, so both `self.render(...)` and
+//! `Model.render(...)` resolve here unchanged.
+
+const std = @import("std");
+const zz = @import("zigzag");
+
+const repl = @import("repl.zig");
+const Model = repl.Model;
+
+const util = @import("repl_util.zig");
+const stripControl = util.stripControl;
+const tailPreview = util.tailPreview;
+
+pub fn spinnerFrame(self: *const Model, now_ms: u64) []const u8 {
+ return switch (self.anim) {
+ .braille => repl.braille_frames[(now_ms / 80) % repl.braille_frames.len],
+ .dragon => repl.dragon_frames[(now_ms / 220) % repl.dragon_frames.len],
+ };
+}
+
+pub fn statusLine(self: *const Model, a: std.mem.Allocator) ![]const u8 {
+ var b = std.array_list.Managed(u8).init(a);
+ if (self.scroll > 0) try b.appendSlice("↑ scrolled · PgDn to bottom · ");
+ if (self.chat and repl.g_model_name.len > 0) try b.appendSlice(repl.g_model_name) else try b.appendSlice("offline · arithmetic");
+ try b.appendSlice(try std.fmt.allocPrint(a, " · effort:{s}", .{@tagName(self.effort)}));
+ if (self.fast) try b.appendSlice(" · ⚡fast");
+ if (self.ultracode) try b.appendSlice(" · ✦ultracode");
+ if (self.plan) try b.appendSlice(" · plan");
+ if (self.yolo) try b.appendSlice(" · yolo");
+ if (self.strict) try b.appendSlice(" · strict");
+ if (self.thinking_show) try b.appendSlice(" · thinking");
+ if (!self.keepcontext) try b.appendSlice(" · no-ctx");
+ if (self.goal != null) try b.appendSlice(" · 🎯goal");
+ if (self.turns > 0) try b.appendSlice(try std.fmt.allocPrint(a, " · {d}t", .{self.turns}));
+ try b.appendSlice(" · /help");
+ return b.items;
+}
+
+/// Render at `term_width` x `term_height`; `now_ms` drives animations. Input
+/// box is pinned to the bottom; conversation fills from the top.
+pub fn render(self: *Model, gpa: std.mem.Allocator, term_width: usize, term_height: usize, now_ms: u64) ![]const u8 {
+ var arena_state = std.heap.ArenaAllocator.init(gpa);
+ defer arena_state.deinit();
+ const a = arena_state.allocator();
+
+ const inner: u16 = @intCast(@max(@as(usize, 8), term_width) - 4);
+ const border_color = if (self.ultracode) repl.rainbow[(now_ms / 90) % repl.rainbow.len] else zz.Color.brightBlack;
+ const box = (zz.Style{}).borderAll(zz.Border.rounded)
+ .borderForeground(border_color).paddingLeft(1).paddingRight(1).width(inner);
+
+ var top = std.array_list.Managed(u8).init(a);
+ for (self.history.items) |e| {
+ switch (e.kind) {
+ .welcome => {
+ const star = try (zz.Style{}).fg(repl.accent).bold(true).render(a, "✻");
+ const sub = if (self.chat) "Chat with the model — ask anything." else "i64 arithmetic — + - * / %, parens, unary minus.";
+ const body = try std.fmt.allocPrint(a, "{s} Welcome to graff repl\n\n {s}\n /help for commands · ctrl-c to quit", .{ star, sub });
+ try top.appendSlice(try box.render(a, body));
+ try top.append('\n');
+ },
+ .input => {
+ const g = try (zz.Style{}).fg(.brightBlack).render(a, ">");
+ try top.appendSlice(try std.fmt.allocPrint(a, "{s} {s}\n", .{ g, e.text }));
+ },
+ .result => {
+ const g = try (zz.Style{}).fg(.green).bold(true).render(a, "⏺");
+ try top.appendSlice(try std.fmt.allocPrint(a, "{s} {s}\n", .{ g, e.text }));
+ },
+ .assistant => {
+ const g = try (zz.Style{}).fg(repl.accent).bold(true).render(a, "⏺");
+ try top.appendSlice(try std.fmt.allocPrint(a, "{s} {s}\n", .{ g, e.text }));
+ },
+ .pending => {
+ const g = try (zz.Style{}).fg(repl.accent).bold(true).render(a, self.spinnerFrame(now_ms));
+ const live = if (self.pending) |job| job.stream.snapshot(a) else null;
+ if (live) |s| {
+ // Compact live activity: the last few lines of the
+ // agent's output, control-stripped + width-truncated,
+ // so tool chatter can't flood the pane.
+ try top.appendSlice(try std.fmt.allocPrint(a, "{s} working…\n", .{g}));
+ try top.appendSlice(try tailPreview(a, stripControl(a, s), term_width, 3));
+ } else {
+ const t = try (zz.Style{}).dim(true).render(a, "thinking…");
+ try top.appendSlice(try std.fmt.allocPrint(a, "{s} {s}\n", .{ g, t }));
+ }
+ if (self.steer_queue.items.len > 0) {
+ try top.appendSlice(try (zz.Style{}).dim(true).render(a, try std.fmt.allocPrint(a, " ↳ {d} steer queued · empty Enter runs now\n", .{self.steer_queue.items.len})));
+ } else {
+ try top.appendSlice(try (zz.Style{}).dim(true).render(a, " ↳ type to steer · Enter queues\n"));
+ }
+ },
+ .err => {
+ const g = try (zz.Style{}).fg(.red).bold(true).render(a, "⏺");
+ const m = try (zz.Style{}).fg(.red).render(a, e.text);
+ try top.appendSlice(try std.fmt.allocPrint(a, "{s} {s}\n", .{ g, m }));
+ },
+ .info => {
+ try top.appendSlice(try (zz.Style{}).dim(true).render(a, e.text));
+ try top.append('\n');
+ },
+ }
+ }
+
+ var bottom = std.array_list.Managed(u8).init(a);
+ try bottom.appendSlice(try box.render(a, try self.input.view(a)));
+ try bottom.append('\n');
+ try bottom.appendSlice(try (zz.Style{}).dim(true).render(a, try self.statusLine(a)));
+
+ // The conversation is a scrollable viewport above the pinned input box.
+ // scroll = lines scrolled up from the bottom (0 = latest). Clamped here.
+ const bottom_lines = std.mem.count(u8, bottom.items, "\n") + 1;
+ const view_h = if (term_height > bottom_lines) term_height - bottom_lines else 1;
+
+ var lines = std.array_list.Managed([]const u8).init(a);
+ var it = std.mem.splitScalar(u8, top.items, '\n');
+ while (it.next()) |ln| try lines.append(ln);
+ if (lines.items.len > 0 and lines.items[lines.items.len - 1].len == 0) _ = lines.pop();
+ const n = lines.items.len;
+
+ var out = std.array_list.Managed(u8).init(a);
+ // Reset the per-frame visible-row snapshot (Model-owned plaintext, so a
+ // mouse row can be mapped back to conversation text for copy — #91).
+ for (self.visible_text.items) |l| self.alloc.free(l);
+ self.visible_text.clearRetainingCapacity();
+ self.view_start = 0;
+ self.view_rows = 0;
+ if (n <= view_h) {
+ self.scroll = 0;
+ try out.appendSlice(top.items);
+ for (0..(view_h - n)) |_| try out.append('\n');
+ self.view_rows = n;
+ for (lines.items[0..n]) |ln| {
+ self.visible_text.append(self.alloc.dupe(u8, stripControl(a, ln)) catch continue) catch {};
+ }
+ } else {
+ const max_scroll = n - view_h;
+ if (self.scroll > max_scroll) self.scroll = max_scroll;
+ const start = max_scroll - self.scroll;
+ self.view_start = start;
+ self.view_rows = view_h;
+ for (lines.items[start .. start + view_h]) |ln| {
+ try out.appendSlice(ln);
+ try out.append('\n');
+ self.visible_text.append(self.alloc.dupe(u8, stripControl(a, ln)) catch continue) catch {};
+ }
+ }
+ try out.appendSlice(bottom.items);
+ if (self.dump_next) {
+ std.debug.print("\n[repl-debug] ===== rendered frame ({d}x{d}) =====\n{s}\n[repl-debug] ===== end frame =====\n", .{ term_width, term_height, out.items });
+ self.dump_next = false;
+ }
+ return gpa.dupe(u8, out.items);
+}
+
+/// Copy the conversation lines spanned by a drag-selection (screen rows
+/// r0..r1 inclusive, 0-based) to the clipboard via OSC52. Line-granular —
+/// restores copy after mouse mode disabled native terminal selection (#91).
+pub fn copySelection(self: *Model, ctx: *zz.Context, r0: usize, r1: usize) void {
+ if (self.view_rows == 0 or self.visible_text.items.len == 0) return;
+ const lo = @min(r0, r1);
+ var hi = @max(r0, r1);
+ if (lo >= self.view_rows) return; // selection started below the conversation
+ if (hi >= self.view_rows) hi = self.view_rows - 1;
+ if (hi >= self.visible_text.items.len) hi = self.visible_text.items.len - 1;
+
+ var buf = std.array_list.Managed(u8).init(self.alloc);
+ defer buf.deinit();
+ var r = lo;
+ while (r <= hi) : (r += 1) {
+ const ln = std.mem.trimEnd(u8, self.visible_text.items[r], " \t");
+ buf.appendSlice(ln) catch return;
+ if (r != hi) buf.append('\n') catch return;
+ }
+ const text = std.mem.trim(u8, buf.items, " \t\r\n");
+ if (text.len == 0) return;
+ _ = ctx.setClipboard(text) catch false;
+ // render() is hash-gated and may skip its flush; push the OSC52 out now.
+ if (ctx._terminal) |term| term.flush() catch {};
+}
diff --git a/src/repl_model_turn.zig b/src/repl_model_turn.zig
new file mode 100644
index 00000000..25f79beb
--- /dev/null
+++ b/src/repl_model_turn.zig
@@ -0,0 +1,133 @@
+//! `graff repl` Model — background chat-turn lifecycle: spawn the model call
+//! on a worker thread, collect its result, and steering-queue plumbing
+//! (queue a line while a turn streams, drain it as the next turn, or
+//! force-interrupt with an empty Enter). Split out of the Model struct in
+//! repl.zig (#123, 600-line goal); reached through repl.zig's member
+//! aliases, so both `self.startJob()` and `Model.startJob(...)` resolve
+//! here unchanged.
+
+const std = @import("std");
+
+const repl = @import("repl.zig");
+const Model = repl.Model;
+const Job = repl.Job;
+const jobRun = repl.jobRun;
+const Turn = repl.Turn;
+const Effect = repl.Effect;
+const renderMarkdown = repl.renderMarkdown;
+
+/// Snapshot the conversation, push the `thinking…` placeholder, and spawn
+/// the model call on a background thread (so the spinner can animate).
+pub fn startJob(self: *Model) void {
+ var turns = std.array_list.Managed(Turn).init(self.alloc);
+ for (self.history.items) |e| {
+ const role: ?Turn.Role = switch (e.kind) {
+ .input => .user,
+ .assistant => .assistant,
+ else => null,
+ };
+ if (role) |r| {
+ const t = self.alloc.dupe(u8, e.text) catch continue;
+ turns.append(.{ .role = r, .text = t }) catch {
+ self.alloc.free(t);
+ continue;
+ };
+ }
+ }
+ const job = self.alloc.create(Job) catch {
+ for (turns.items) |t| self.alloc.free(t.text);
+ turns.deinit();
+ self.push(.err, "out of memory") catch {};
+ return;
+ };
+ job.* = .{
+ .gpa = self.alloc,
+ .history = turns.toOwnedSlice() catch &.{},
+ .params = .{
+ .effort = self.effort,
+ .fast = self.fast,
+ .thinking = self.thinking_show,
+ .ultracode = self.ultracode,
+ .goal = self.goal orelse "",
+ },
+ .stream = .{ .buf = self.alloc.alloc(u8, 256 * 1024) catch &.{} },
+ };
+ self.push(.pending, "") catch {};
+ self.pending = job;
+ if (std.Thread.spawn(.{}, jobRun, .{job})) |th| {
+ job.thread = th;
+ } else |_| {
+ job.threaded = false;
+ jobRun(job); // no threads → run synchronously (spinner just won't animate)
+ }
+}
+
+/// Collect a finished job: drop the placeholder, append the reply, free.
+pub fn finishJob(self: *Model) void {
+ const job = self.pending orelse return;
+ if (!job.done.load(.acquire)) return;
+ if (job.threaded) job.thread.join();
+ if (repl.g_debug) {
+ if (job.stream.snapshot(self.alloc)) |raw| {
+ std.debug.print("\n[repl-debug] raw agent stream ({d} bytes):\n{s}\n", .{ raw.len, raw });
+ self.alloc.free(raw);
+ }
+ std.debug.print("[repl-debug] final reply:\n{s}\n[repl-debug] ----- end turn -----\n", .{job.result orelse "(model call failed)"});
+ }
+
+ const n = self.history.items.len;
+ if (n > 0 and self.history.items[n - 1].kind == .pending) {
+ self.alloc.free(self.history.items[n - 1].text);
+ self.history.shrinkRetainingCapacity(n - 1);
+ }
+ if (job.result) |r| {
+ self.chars_out += r.len;
+ if (renderMarkdown(self.alloc, r)) |rendered| {
+ self.alloc.free(r);
+ self.pushOwned(.assistant, rendered) catch self.alloc.free(rendered);
+ } else |_| {
+ self.pushOwned(.assistant, r) catch self.alloc.free(r);
+ }
+ } else if (self.cancel_requested) {
+ // Force-steer interrupted this turn (runTurn → error.Interrupted →
+ // replTurnCb returns null); not an error.
+ self.push(.info, "⏹ interrupted") catch {};
+ } else {
+ self.push(.err, "model call failed — check /model and your API key") catch {};
+ }
+ for (job.history) |t| self.alloc.free(t.text);
+ self.alloc.free(job.history);
+ if (job.stream.buf.len > 0) self.alloc.free(job.stream.buf);
+ self.alloc.destroy(job);
+ self.pending = null;
+ self.cancel_requested = false;
+ self.scroll = 0; // reply landed → jump to the latest
+}
+
+/// Pop the next queued steer line (FIFO) and run it as the next turn.
+/// Returns the applyLine Effect so a steered "/quit" still propagates.
+pub fn drainSteer(self: *Model) Effect {
+ if (self.steer_queue.items.len == 0) return .stay;
+ const text = self.steer_queue.orderedRemove(0);
+ defer self.alloc.free(text);
+ return self.applyLine(text);
+}
+
+/// Handle Enter while a turn streams. A typed line is queued as a steer
+/// (runs as a follow-up turn after the current one finishes); an empty line
+/// with a non-empty queue FORCES — flags the turn for interrupt and signals
+/// the harness via the cancel callback so the queue drains immediately.
+pub fn steerEnter(self: *Model) void {
+ const v = std.mem.trim(u8, self.input.getValue(), " \t\r\n");
+ if (v.len > 0) {
+ if (self.alloc.dupe(u8, v)) |dup| {
+ self.steer_queue.append(dup) catch self.alloc.free(dup);
+ self.input.setValue("") catch {};
+ self.pushFmt(.info, "↳ steer › queued ({d} waiting)", .{self.steer_queue.items.len}) catch {};
+ } else |_| {}
+ } else if (self.steer_queue.items.len > 0) {
+ self.cancel_requested = true;
+ if (repl.g_cancel_fn) |f| f(repl.g_turn_ctx);
+ self.push(.info, "↳ force › interrupting…") catch {};
+ }
+}
diff --git a/src/repl_parser.zig b/src/repl_parser.zig
new file mode 100644
index 00000000..93f63e78
--- /dev/null
+++ b/src/repl_parser.zig
@@ -0,0 +1,99 @@
+//! Arithmetic expression evaluator for `graff repl` — pure, allocation-free.
+//! Offline fallback engine + the thing the headless tests exercise. Split
+//! out of repl.zig (#123, 600-line goal); Parser is used only by eval()
+//! here, so it stays private to this file.
+
+const std = @import("std");
+
+pub const EvalError = error{ SyntaxError, DivByZero, Overflow };
+
+const Parser = struct {
+ src: []const u8,
+ pos: usize = 0,
+
+ fn skipWs(self: *Parser) void {
+ while (self.pos < self.src.len and (self.src[self.pos] == ' ' or
+ self.src[self.pos] == '\t')) : (self.pos += 1)
+ {}
+ }
+ fn peek(self: *Parser) ?u8 {
+ self.skipWs();
+ return if (self.pos < self.src.len) self.src[self.pos] else null;
+ }
+ fn expr(self: *Parser) EvalError!i64 {
+ var acc = try self.term();
+ while (self.peek()) |c| {
+ if (c != '+' and c != '-') break;
+ self.pos += 1;
+ const rhs = try self.term();
+ acc = if (c == '+') try std.math.add(i64, acc, rhs) else try std.math.sub(i64, acc, rhs);
+ }
+ return acc;
+ }
+ fn term(self: *Parser) EvalError!i64 {
+ var acc = try self.factor();
+ while (self.peek()) |c| {
+ if (c != '*' and c != '/' and c != '%') break;
+ self.pos += 1;
+ const rhs = try self.factor();
+ switch (c) {
+ '*' => acc = try std.math.mul(i64, acc, rhs),
+ '/' => {
+ if (rhs == 0) return error.DivByZero;
+ if (acc == std.math.minInt(i64) and rhs == -1) return error.Overflow;
+ acc = @divTrunc(acc, rhs);
+ },
+ else => {
+ if (rhs == 0) return error.DivByZero;
+ if (acc == std.math.minInt(i64) and rhs == -1) return error.Overflow;
+ acc = @rem(acc, rhs);
+ },
+ }
+ }
+ return acc;
+ }
+ fn factor(self: *Parser) EvalError!i64 {
+ const c = self.peek() orelse return error.SyntaxError;
+ if (c == '-') {
+ self.pos += 1;
+ return std.math.negate(try self.factor()) catch error.Overflow;
+ }
+ if (c == '+') {
+ self.pos += 1;
+ return self.factor();
+ }
+ if (c == '(') {
+ self.pos += 1;
+ const v = try self.expr();
+ if (self.peek() != @as(?u8, ')')) return error.SyntaxError;
+ self.pos += 1;
+ return v;
+ }
+ if (!std.ascii.isDigit(c)) return error.SyntaxError;
+ const start = self.pos;
+ while (self.pos < self.src.len and std.ascii.isDigit(self.src[self.pos])) : (self.pos += 1) {}
+ return std.fmt.parseInt(i64, self.src[start..self.pos], 10) catch error.Overflow;
+ }
+};
+
+pub fn eval(src: []const u8) EvalError!i64 {
+ var p = Parser{ .src = src };
+ const v = try p.expr();
+ if (p.peek() != null) return error.SyntaxError;
+ return v;
+}
+
+test "eval: precedence and parentheses" {
+ try std.testing.expectEqual(@as(i64, 14), try eval("2 + 3 * 4"));
+ try std.testing.expectEqual(@as(i64, 20), try eval("(2 + 3) * 4"));
+ try std.testing.expectEqual(@as(i64, -6), try eval("-(2 * 3)"));
+ try std.testing.expectEqual(@as(i64, 2), try eval("7 / 3"));
+ try std.testing.expectEqual(@as(i64, 1), try eval("7 % 3"));
+}
+
+test "eval: error cases" {
+ try std.testing.expectError(error.DivByZero, eval("1 / 0"));
+ try std.testing.expectError(error.SyntaxError, eval("2 +"));
+ try std.testing.expectError(error.SyntaxError, eval("2 2"));
+ try std.testing.expectError(error.Overflow, eval("9223372036854775807 + 1"));
+}
diff --git a/src/repl_run.zig b/src/repl_run.zig
new file mode 100644
index 00000000..bd9c0b13
--- /dev/null
+++ b/src/repl_run.zig
@@ -0,0 +1,116 @@
+//! `graff repl` — top-level entry points: the live TUI loop (run), the
+//! headless/scriptable twin for CI and non-TTY stdin (runScripted), and the
+//! standalone `graff-repl` exe's main(). Split out of repl.zig (#123,
+//! 600-line goal).
+
+const std = @import("std");
+const zz = @import("zigzag");
+
+const repl = @import("repl.zig");
+const Model = repl.Model;
+
+/// Run the REPL. Pass a `turn_fn` (+ opaque ctx + model name) to chat with a
+/// model; pass null/null/"" for the offline arithmetic engine.
+pub fn run(
+ gpa: std.mem.Allocator,
+ io: std.Io,
+ environ_map: *const std.process.Environ.Map,
+ turn_ctx: ?*anyopaque,
+ turn_fn: ?repl.TurnFn,
+ model_fn: ?repl.ModelFn,
+ cancel_fn: ?repl.CancelFn,
+ model_name: []const u8,
+ models: []const u8,
+) !void {
+ repl.g_turn_ctx = turn_ctx;
+ repl.g_turn_fn = turn_fn;
+ repl.g_model_fn = model_fn;
+ repl.g_cancel_fn = cancel_fn;
+ repl.g_model_name = model_name;
+ repl.g_debug = environ_map.get("GRAFF_REPL_DEBUG") != null;
+ repl.g_models = models;
+ var program = zz.Program(Model).initWithOptions(gpa, io, environ_map, .{ .mouse = true });
+ defer program.deinit();
+ try program.run();
+}
+
+/// Headless, scriptable twin of run(): drives the SAME Model + turn_fn as the
+/// live TUI, but reads input lines from `in` and prints each turn's new output to
+/// `out` instead of taking over the terminal. Lets
+/// printf '/goal X\n<prompt>\n' | graff repl
+/// exercise the exact repl path (goal steering, todo_write, cross-turn continuity)
+/// from a script / CI / test — a 1:1 map of the interactive behavior. main() routes
+/// here automatically when stdin is not a TTY. GRAFF_REPL_DEBUG=1 additionally dumps
+/// each turn's raw agent stream to stderr (where mid-turn renders like the
+/// todo_write checklist appear).
+pub fn runScripted(
+ gpa: std.mem.Allocator,
+ io: std.Io,
+ environ_map: *const std.process.Environ.Map,
+ in: *std.Io.Reader,
+ out: *std.Io.Writer,
+ turn_ctx: ?*anyopaque,
+ turn_fn: ?repl.TurnFn,
+ model_fn: ?repl.ModelFn,
+ cancel_fn: ?repl.CancelFn,
+ model_name: []const u8,
+ models: []const u8,
+) !void {
+ repl.g_turn_ctx = turn_ctx;
+ repl.g_turn_fn = turn_fn;
+ repl.g_model_fn = model_fn;
+ repl.g_cancel_fn = cancel_fn;
+ repl.g_model_name = model_name;
+ repl.g_debug = environ_map.get("GRAFF_REPL_DEBUG") != null;
+ repl.g_models = models;
+
+ var m: Model = undefined;
+ m.setup(gpa);
+ defer m.deinit();
+
+ while (true) {
+ const raw = (in.takeDelimiter('\n') catch null) orelse break; // EOF ends the script
+ const line = std.mem.trim(u8, raw, " \t\r\n");
+ if (line.len == 0) continue;
+
+ try out.print("\n> {s}\n", .{line});
+ try out.flush();
+
+ const before = m.history.items.len;
+ const eff = m.applyLine(line);
+
+ // A chat line spawns a background turn; a slash command runs inline.
+ if (m.pending != null) {
+ while (m.pending) |job| {
+ if (job.done.load(.acquire)) {
+ m.finishJob();
+ break;
+ }
+ io.sleep(.fromMilliseconds(20), .awake) catch {};
+ }
+ }
+
+ // Print what the line produced — slash-command info, the assistant reply,
+ // or an error. The user line is already echoed above; the pending
+ // placeholder is gone once finishJob ran.
+ var i = before;
+ while (i < m.history.items.len) : (i += 1) {
+ switch (m.history.items[i].kind) {
+ .pending, .input, .welcome => {},
+ else => try out.print("{s}\n", .{m.history.items[i].text}),
+ }
+ }
+ try out.flush();
+
+ if (eff == .quit) break;
+ }
+
+ const pane = try m.render(gpa, 100, 60, 0);
+ defer gpa.free(pane);
+ try out.print("\n===== final repl pane =====\n{s}\n===========================\n", .{pane});
+ try out.flush();
+}
+
+pub fn main(init: std.process.Init) !void {
+ return run(init.gpa, init.io, init.environ_map, null, null, null, null, "", "");
+}
diff --git a/src/repl_util.zig b/src/repl_util.zig
new file mode 100644
index 00000000..4d5d76be
--- /dev/null
+++ b/src/repl_util.zig
@@ -0,0 +1,114 @@
+//! Stateless string/format helpers shared by the `graff repl` Model: help
+//! text, inline markdown span rendering, and small string utilities used by
+//! the command dispatcher and the pane renderer. Split out of repl.zig
+//! (#123, 600-line goal) — pure functions, no Model dependency.
+
+const std = @import("std");
+const zz = @import("zigzag");
+
+pub const HELP_CHAT =
+ \\Commands (mirrors the graff session):
+ \\ /help /clear /new /quit conversation
+ \\ /rewind /compact /cost history
+ \\ /model [name] /models model (switch / list)
+ \\ /effort low|med|high /reasoning reasoning depth
+ \\ /fast /thinking /ultracode thinking controls (toggles)
+ \\ /goal <text> standing objective (tracked as a checklist)
+ \\ /plan /strict /yolo /keepcontext /title modes
+ \\ /rename <name> /animation braille|dragon
+ \\ /bash /save /resume /sessions /trace /trajectory
+ \\ /agents /skills /hooks /mcp /loop /image /paste /key
+ \\
+ \\Type a message and press enter to send it to the model. Toggles accept
+ \\[on|off] or flip when bare. Commands needing the agent loop explain so.
+;
+
+pub fn renderInline(out: *std.array_list.Managed(u8), a: std.mem.Allocator, line: []const u8) !void {
+ var i: usize = 0;
+ while (i < line.len) {
+ const c = line[i];
+ if (c == '`') {
+ if (std.mem.indexOfScalarPos(u8, line, i + 1, '`')) |end| {
+ try out.appendSlice(try (zz.Style{}).fg(.cyan).render(a, line[i + 1 .. end]));
+ i = end + 1;
+ continue;
+ }
+ } else if (c == '*' and i + 1 < line.len and line[i + 1] == '*') {
+ if (std.mem.indexOfPos(u8, line, i + 2, "**")) |end| {
+ try out.appendSlice(try (zz.Style{}).bold(true).render(a, line[i + 2 .. end]));
+ i = end + 2;
+ continue;
+ }
+ }
+ try out.append(c);
+ i += 1;
+ }
+}
+pub fn eqlAny(s: []const u8, options: []const []const u8) bool {
+ for (options) |o| if (std.mem.eql(u8, s, o)) return true;
+ return false;
+}
+
+/// Strip ANSI/control sequences (and CR) so the agent's live streamed output
+/// can be shown as plain text — cursor moves/redraws can't corrupt the pane.
+/// Result owned by `a`.
+pub fn stripControl(a: std.mem.Allocator, s: []const u8) []const u8 {
+ var out = std.array_list.Managed(u8).init(a);
+ var i: usize = 0;
+ while (i < s.len) {
+ const c = s[i];
+ if (c == 0x1b) {
+ i += 1;
+ if (i < s.len and s[i] == '[') {
+ i += 1;
+ while (i < s.len and !std.ascii.isAlphabetic(s[i])) i += 1;
+ if (i < s.len) i += 1;
+ } else if (i < s.len and s[i] == ']') {
+ i += 1;
+ while (i < s.len and s[i] != 0x07 and s[i] != 0x1b) i += 1;
+ if (i < s.len) i += 1;
+ } else if (i < s.len) {
+ i += 1;
+ }
+ } else if (c == '\r') {
+ i += 1;
+ } else {
+ out.append(c) catch {};
+ i += 1;
+ }
+ }
+ return out.items;
+}
+
+/// Compact live-activity preview: the last `n` non-empty lines of `plain`, each
+/// width-truncated (UTF-8 safe) and dimmed, indented. Keeps the agent's tool
+/// chatter from flooding the pane while still showing live progress.
+pub fn tailPreview(a: std.mem.Allocator, plain: []const u8, width: usize, n: usize) ![]const u8 {
+ var lines = std.array_list.Managed([]const u8).init(a);
+ var it = std.mem.splitScalar(u8, plain, '\n');
+ while (it.next()) |ln| {
+ const t = std.mem.trim(u8, ln, " \t");
+ if (t.len > 0) try lines.append(t);
+ }
+ const start = if (lines.items.len > n) lines.items.len - n else 0;
+ const cap = if (width > 6) width - 4 else 12;
+ var out = std.array_list.Managed(u8).init(a);
+ for (lines.items[start..]) |ln| {
+ var tw = @min(ln.len, cap);
+ while (tw > 0 and tw < ln.len and (ln[tw] & 0xC0) == 0x80) tw -= 1; // don't cut mid-UTF-8
+ try out.appendSlice(" ");
+ try out.appendSlice(try (zz.Style{}).dim(true).render(a, ln[0..tw]));
+ try out.append('\n');
+ }
+ return out.items;
+}
+
+pub fn parseToggle(arg: []const u8, current: bool) bool {
+ if (std.mem.eql(u8, arg, "on")) return true;
+ if (std.mem.eql(u8, arg, "off")) return false;
+ return !current; // bare toggle
+}
+
+pub fn onOff(v: bool) []const u8 {
+ return if (v) "on" else "off";
+}