Skip to content

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

Python

fix(tui): !cmd goes through the engine's gate, not around it

Rach Pradhanff8ba0dfb55d
diff --git a/TUI/bgop.zig b/TUI/bgop.zig
index 4bc82f71..3753ebcc 100644
--- a/TUI/bgop.zig
+++ b/TUI/bgop.zig
@@ -23,7 +23,9 @@ const Op = engine.BgOp;
pub fn start(self: *Model, kind: Op.Kind, turns: []engine.Turn, cmd: []const u8, label: []const u8) bool {
if (self.bg != null or self.pending != null) return false;
const op = self.alloc.create(Op) catch return false;
- op.* = .{ .kind = kind, .gpa = self.alloc, .turns = turns, .cmd = cmd };
+ // The op carries the same policy a turn does: `!cmd` goes through the
+ // engine's gate now, and /plan has to reach it (#551).
+ op.* = .{ .kind = kind, .gpa = self.alloc, .turns = turns, .cmd = cmd, .params = turn.paramsOf(self) };
if (label.len > 0) self.push(.pending, label) catch {};
self.bg = op;
if (std.Thread.spawn(.{}, engine.bgRun, .{op})) |th| {
@@ -156,7 +158,7 @@ fn drain(m: *Model) !void {
test "a bash op runs off the render thread and its output lands in the scrollback (#533)" {
engine.g_bash_fn = struct {
- fn f(_: ?*anyopaque, gpa: std.mem.Allocator, cmd: []const u8) ?[]const u8 {
+ fn f(_: ?*anyopaque, gpa: std.mem.Allocator, cmd: []const u8, _: engine.Params) ?[]const u8 {
return std.fmt.allocPrint(gpa, "ran: {s}", .{cmd}) catch null;
}
}.f;
@@ -207,7 +209,7 @@ test "a second op is refused while one is in flight, and Esc cancels the live on
var go: std.atomic.Value(bool) = std.atomic.Value(bool).init(false);
var entered: std.atomic.Value(bool) = std.atomic.Value(bool).init(false);
var saw_cancel: std.atomic.Value(bool) = std.atomic.Value(bool).init(false);
- fn bash(_: ?*anyopaque, gpa: std.mem.Allocator, _: []const u8) ?[]const u8 {
+ fn bash(_: ?*anyopaque, gpa: std.mem.Allocator, _: []const u8, _: engine.Params) ?[]const u8 {
entered.store(true, .release);
while (!go.load(.acquire)) std.Thread.yield() catch {};
return gpa.dupe(u8, "done") catch null;
diff --git a/TUI/dispatch_tests.zig b/TUI/dispatch_tests.zig
index b2cc9ebd..dc6eae94 100644
--- a/TUI/dispatch_tests.zig
+++ b/TUI/dispatch_tests.zig
@@ -23,7 +23,7 @@ fn settle(m: *Model) !void {
test "! runs through the bash callback in the background and lands in the scrollback (#533)" {
engine.g_bash_fn = struct {
- fn f(_: ?*anyopaque, gpa: std.mem.Allocator, cmd: []const u8) ?[]const u8 {
+ fn f(_: ?*anyopaque, gpa: std.mem.Allocator, cmd: []const u8, _: engine.Params) ?[]const u8 {
return std.fmt.allocPrint(gpa, "ran: {s}", .{cmd}) catch null;
}
}.f;
diff --git a/TUI/engine.zig b/TUI/engine.zig
index 61e6bc68..e1f54c5a 100644
--- a/TUI/engine.zig
+++ b/TUI/engine.zig
@@ -67,9 +67,11 @@ pub const ModelFn = *const fn (turn_ctx: ?*anyopaque, gpa: std.mem.Allocator, na
pub const CancelFn = *const fn (turn_ctx: ?*anyopaque) void;
/// Fill dest with a staged image path (return >0) or an error line (return <0).
pub const PasteFn = *const fn (turn_ctx: ?*anyopaque, dest: []u8) isize;
-/// Run a user-typed `!` shell line in the session cwd; return combined
-/// output (caller frees) or null when the spawn itself failed.
-pub const BashFn = *const fn (turn_ctx: ?*anyopaque, gpa: std.mem.Allocator, cmd: []const u8) ?[]const u8;
+/// Run a user-typed `!` shell line; return combined output (caller frees), the
+/// gate's refusal, or null when the harness could not produce either. `params`
+/// carries the session's policy because `!` goes through the same gate the
+/// model's bash tool does — a `!` under /plan must be refused (#551).
+pub const BashFn = *const fn (turn_ctx: ?*anyopaque, gpa: std.mem.Allocator, cmd: []const u8, params: Params) ?[]const u8;
/// Newline-joined repo-relative paths for @-search (caller frees), or null.
pub const FilesFn = *const fn (turn_ctx: ?*anyopaque, gpa: std.mem.Allocator) ?[]const u8;
/// Copy text to the system clipboard; true on success.
@@ -123,6 +125,8 @@ pub const BgOp = struct {
turns: []Turn = &.{},
/// bash input — gpa-owned command line.
cmd: []const u8 = "",
+ /// The session policy this op runs under, same as a turn's (#551).
+ params: Params = .{},
/// compact output — gpa-owned.
compact: CompactOut = .{},
ok: bool = false,
@@ -136,7 +140,7 @@ pub fn bgRun(op: *BgOp) void {
op.ok = f(g_turn_ctx, op.gpa, op.turns, &op.compact);
},
.bash => if (g_bash_fn) |f| {
- op.text = f(g_turn_ctx, op.gpa, op.cmd);
+ op.text = f(g_turn_ctx, op.gpa, op.cmd, op.params);
},
.files => if (g_files_fn) |f| {
op.text = f(g_turn_ctx, op.gpa);
diff --git a/TUI/turn.zig b/TUI/turn.zig
index 710529ca..574d4190 100644
--- a/TUI/turn.zig
+++ b/TUI/turn.zig
@@ -8,6 +8,21 @@ const engine = @import("engine.zig");
const Model = app.Model;
const Effect = app.Effect;
+/// What the session is currently asking the engine to do. Shared by a model
+/// turn and by `!cmd` (bgop), because both run under the SAME policy — a /plan
+/// that only reached one of them is the #551 bug in miniature.
+pub fn paramsOf(self: *const Model) engine.Params {
+ return .{
+ .effort = self.effort,
+ .fast = self.fast,
+ .thinking = self.thinking_show,
+ .ultracode = self.ultracode or self.effort == .ultra,
+ .mode = self.mode,
+ .strict = self.strict,
+ .goal = self.goal orelse "",
+ };
+}
+
pub fn startJob(self: *Model) void {
var turns = std.array_list.Managed(engine.Turn).init(self.alloc);
for (self.history.items) |e| {
@@ -33,18 +48,10 @@ pub fn startJob(self: *Model) void {
job.* = .{
.gpa = self.alloc,
.history = turns.toOwnedSlice() catch &.{},
- .params = .{
- .effort = self.effort,
- .fast = self.fast,
- .thinking = self.thinking_show,
- .ultracode = self.ultracode or self.effort == .ultra,
- // Policy travels WITH the turn (#551): the engine applies the plan
- // gate and the strict prompt from these, so the footer and the run
- // can no longer disagree.
- .mode = self.mode,
- .strict = self.strict,
- .goal = self.goal orelse "",
- },
+ // Policy travels WITH the turn (#551): the engine applies the plan gate
+ // and the strict prompt from these, so the footer and the run can no
+ // longer disagree.
+ .params = paramsOf(self),
.stream = .{ .buf = self.alloc.alloc(u8, 256 * 1024) catch &.{} },
};
// The queue must own its copies before the turn thread can push: the
diff --git a/src/repl_bash.zig b/src/repl_bash.zig
new file mode 100644
index 00000000..bb321807
--- /dev/null
+++ b/src/repl_bash.zig
@@ -0,0 +1,173 @@
+//! `!cmd` — the user's own shell line, run through the ENGINE (#551).
+//!
+//! It used to call process_runner.runCapped directly from the TUI glue, which
+//! skipped every rail the same command gets when the model asks for it: no
+//! approval gate, no plan-mode denial, no hooks, no tracer, no tool
+//! accounting. `/plan` then `!rm -rf build` ran the rm. And because the output
+//! went straight to a system row, the model never saw what the user had just
+//! run, so the next question about it landed with no context.
+//!
+//! Now it builds the same ToolCall the model's `bash` tool produces, sends it
+//! through Agent.gateTool and exec.execTool, and folds the command and its
+//! output into the session conversation. Esc still lands: process_runner polls
+//! Agent.esc_cancel, which is what the frontend's cancel callback sets.
+
+const std = @import("std");
+const Io = std.Io;
+const Allocator = std.mem.Allocator;
+
+const main_mod = @import("main.zig");
+const agent_mod = @import("agent.zig");
+const Agent = agent_mod.Agent;
+const approvals_mod = @import("approvals.zig");
+const Approvals = approvals_mod.Approvals;
+const exec = @import("exec.zig");
+const tools_mod = @import("tools.zig");
+const ToolCall = tools_mod.ToolCall;
+const repl = @import("repl.zig");
+const repl_glue = @import("repl_glue.zig");
+const repl_turn = @import("repl_turn.zig");
+const ReplCtx = repl_glue.ReplCtx;
+
+/// How much of a `!` command's output the model is shown. The transcript row
+/// is already tailed for display; this bound is about the request body, where
+/// a 200 KB build log would evict the rest of the conversation.
+pub const note_cap: usize = 4000;
+
+/// Run `cmd` exactly as the bash TOOL runs it. Returns the combined output
+/// (gpa-owned, the frontend frees it) or the gate's refusal text; null only
+/// when the harness could not produce either.
+pub fn replBashCb(ctx_ptr: ?*anyopaque, gpa: Allocator, cmd: []const u8, params: repl.Params) ?[]const u8 {
+ const c: *ReplCtx = @ptrCast(@alignCast(ctx_ptr orelse return null));
+ // A cancel that ended the PREVIOUS op must not kill this one before it
+ // starts: esc_cancel is a process-wide latch and a turn clears it the same
+ // way at its own start.
+ Agent.esc_cancel.store(false, .release);
+ var scratch_state = std.heap.ArenaAllocator.init(gpa);
+ defer scratch_state.deinit();
+ const arena = scratch_state.allocator();
+ var discard_buf: [256]u8 = undefined;
+ var discarding: Io.Writer.Discarding = .init(&discard_buf);
+
+ const policy = repl_turn.Policy.from(params);
+ const plan_saved = main_mod.plan_mode;
+ main_mod.plan_mode = policy.plan;
+ defer main_mod.plan_mode = plan_saved;
+ var approvals: Approvals = .{ .yolo = policy.yolo };
+ var agent = repl_turn.turnAgent(c, gpa, arena, params, &discarding.writer, &approvals) catch return null;
+ defer agent.tools_used.deinit(gpa);
+
+ var input: std.json.ObjectMap = .empty;
+ input.put(arena, "command", .{ .string = cmd }) catch return null;
+ const call: ToolCall = .{ .id = "tui-bang", .name = "bash", .input = .{ .object = input } };
+
+ if (agent.gateTool(call)) |maybe_denied| {
+ if (maybe_denied) |denied| {
+ // The refusal is the user's answer AND the model's: it explains why
+ // nothing ran, and the next prompt is usually about that.
+ noteToModel(c, gpa, cmd, denied.text);
+ return gpa.dupe(u8, denied.text) catch null;
+ }
+ } else |_| return null;
+
+ const result = exec.execTool(.{
+ .gpa = gpa,
+ .io = c.io,
+ .client = c.client,
+ .provider = c.provider,
+ .registry = c.registry,
+ .from_sub = false,
+ .approvals = &approvals,
+ .tracer = c.tracer,
+ .run_budget = c.run_budget,
+ .tools_used = &agent.tools_used,
+ }, call);
+ noteToModel(c, gpa, cmd, result.text);
+ return result.text; // gpa-owned, exactly what BashFn promises
+}
+
+/// Put the command and what it printed into the conversation, so the model can
+/// answer "why did that fail?" without being told the whole thing again.
+fn noteToModel(c: *ReplCtx, gpa: Allocator, cmd: []const u8, output: []const u8) void {
+ const cv = c.convo orelse return;
+ const shown = capped(output, note_cap);
+ const line = std.fmt.allocPrint(
+ gpa,
+ "I ran a shell command myself:\n$ {s}\n\n{s}{s}",
+ .{ cmd, shown, if (shown.len < output.len) "\n[output truncated]" else "" },
+ ) catch return;
+ defer gpa.free(line);
+ cv.note(line) catch {};
+}
+
+/// Head of `text`, at most `cap` bytes and never splitting a UTF-8 sequence —
+/// half a codepoint here would be half a codepoint on the wire.
+pub fn capped(text: []const u8, cap: usize) []const u8 {
+ if (text.len <= cap) return text;
+ var end = cap;
+ while (end > 0 and text[end] & 0xC0 == 0x80) end -= 1;
+ return text[0..end];
+}
+
+const testing = std.testing;
+
+fn lastNote(convo: *repl_glue.Conversation) []const u8 {
+ const items = convo.list().items;
+ if (items.len == 0) return "";
+ return items[items.len - 1].object.get("content").?.string;
+}
+
+test "!cmd runs through the engine's gate, and plan mode refuses it (#551)" {
+ const gpa = testing.allocator;
+ var client: std.http.Client = undefined;
+ var c = repl_turn.testCtx(&client);
+ var convo = repl_glue.Conversation.init(gpa);
+ defer convo.deinit();
+ c.convo = &convo;
+ const saved_plan = main_mod.plan_mode;
+ defer main_mod.plan_mode = saved_plan;
+
+ // Plan mode: the command never runs, so its output never appears.
+ const refused = replBashCb(&c, gpa, "printf bang-sentinel", .{ .mode = .plan }) orelse
+ return error.NoResult;
+ defer gpa.free(refused);
+ try testing.expect(std.mem.indexOf(u8, refused, "plan mode") != null);
+ try testing.expect(std.mem.indexOf(u8, refused, "bang-sentinel") == null);
+ // …and the refusal is in the conversation, because the next prompt is
+ // usually "why didn't that work?".
+ try testing.expect(std.mem.indexOf(u8, lastNote(&convo), "plan mode") != null);
+ const after_refusal = convo.len();
+
+ // The same command outside plan mode runs and produces its output.
+ const ran = replBashCb(&c, gpa, "printf bang-sentinel", .{ .mode = .always_approve }) orelse
+ return error.NoResult;
+ defer gpa.free(ran);
+ try testing.expect(std.mem.indexOf(u8, ran, "bang-sentinel") != null);
+
+ // The model sees the command AND what it printed — the old `!` path put
+ // the output on a system row the conversation never carried.
+ try testing.expectEqual(after_refusal + 1, convo.len());
+ const note = lastNote(&convo);
+ try testing.expect(std.mem.indexOf(u8, note, "$ printf bang-sentinel") != null);
+ try testing.expect(std.mem.indexOf(u8, note, "bang-sentinel") != null);
+ // plan_mode is a process global: the op restores whatever it found.
+ try testing.expectEqual(saved_plan, main_mod.plan_mode);
+}
+
+test "a session with no conversation still runs !cmd and keeps no note" {
+ const gpa = testing.allocator;
+ var client: std.http.Client = undefined;
+ var c = repl_turn.testCtx(&client);
+ const out = replBashCb(&c, gpa, "printf no-convo", .{ .mode = .always_approve }) orelse
+ return error.NoResult;
+ defer gpa.free(out);
+ try testing.expect(std.mem.indexOf(u8, out, "no-convo") != null);
+}
+
+test "capped never splits a multi-byte character" {
+ try testing.expectEqualStrings("abc", capped("abc", 8));
+ // "…" is three bytes; a cap landing inside it must drop the whole glyph.
+ try testing.expectEqualStrings("ab", capped("ab…cd", 3));
+ try testing.expectEqualStrings("ab…", capped("ab…cd", 5));
+ try testing.expect(std.unicode.utf8ValidateSlice(capped("ab…cd", 4)));
+}
diff --git a/src/repl_turn.zig b/src/repl_turn.zig
index e96372a0..9aad4834 100644
--- a/src/repl_turn.zig
+++ b/src/repl_turn.zig
@@ -203,7 +203,10 @@ fn earlyEnd(gpa: Allocator, agent: *Agent, why: []const u8) ?[]const u8 {
const testing = std.testing;
-fn testCtx(client: *std.http.Client) ReplCtx {
+/// A session context with no provider behind it — enough for anything that
+/// exercises gates, prompts or history rather than a model call. Shared with
+/// repl_bash.zig's tests, which drive the same turnAgent.
+pub fn testCtx(client: *std.http.Client) ReplCtx {
return .{
.io = testing.io,
.client = client,
diff --git a/src/tui_launch.zig b/src/tui_launch.zig
index 87e4b890..addb26af 100644
--- a/src/tui_launch.zig
+++ b/src/tui_launch.zig
@@ -12,6 +12,7 @@ const pricing = @import("pricing.zig");
const providers = @import("providers.zig");
const process_runner = @import("process_runner.zig");
const repl = @import("repl.zig");
+const repl_bash = @import("repl_bash.zig");
const repl_glue = @import("repl_glue.zig");
const tui = @import("tui");
const engine_sink = @import("engine_sink.zig");
@@ -276,39 +277,23 @@ fn pasteErr(dest: []u8, msg: []const u8) isize {
return -@as(isize, @intCast(n));
}
-/// `!cmd` bash mode: run in the session cwd, cap output, 20s deadline.
-fn bashCb(ctx: ?*anyopaque, gpa: Allocator, cmd: []const u8) ?[]const u8 {
- const c: *repl_glue.ReplCtx = @ptrCast(@alignCast(ctx orelse return null));
- const argv: []const []const u8 = if (builtin.os.tag == .windows)
- &.{ "cmd.exe", "/C", cmd }
- else
- &.{ "/bin/sh", "-c", cmd };
- const run_res = process_runner.runCapped(gpa, c.io, argv, 64 * 1024, 16 * 1024, 20_000) catch return null;
- defer gpa.free(run_res.stdout);
- defer gpa.free(run_res.stderr);
- var out = std.array_list.Managed(u8).init(gpa);
- defer out.deinit();
- const so = std.mem.trimEnd(u8, run_res.stdout, "\r\n");
- const se = std.mem.trimEnd(u8, run_res.stderr, "\r\n");
- out.appendSlice(so) catch {};
- if (se.len > 0) {
- if (out.items.len > 0) out.append('\n') catch {};
- out.appendSlice(se) catch {};
- }
- if (run_res.timed_out) {
- if (out.items.len > 0) out.append('\n') catch {};
- out.appendSlice("(timed out after 20s)") catch {};
- } else if (!process_runner.ranOk(run_res)) {
- if (out.items.len > 0) out.append('\n') catch {};
- var nb: [32]u8 = undefined;
- const note = switch (run_res.term) {
- .exited => |code| std.fmt.bufPrint(&nb, "(exit {d})", .{code}) catch "(exit ?)",
- else => "(terminated)",
- };
- out.appendSlice(note) catch {};
- }
- if (out.items.len == 0) out.appendSlice("(no output)") catch {};
- return out.toOwnedSlice() catch null;
+/// `!cmd` bash mode — the engine's bash tool, gate and all (repl_bash.zig).
+/// It used to call process_runner directly, which is how `/plan` + `!rm -rf`
+/// ran the rm and how the model never learned what the user had run (#551).
+fn bashCb(ctx: ?*anyopaque, gpa: Allocator, cmd: []const u8, params: tui.Params) ?[]const u8 {
+ return repl_bash.replBashCb(ctx, gpa, cmd, .{
+ .effort = @enumFromInt(@intFromEnum(params.effort)),
+ .fast = params.fast,
+ .thinking = params.thinking,
+ .ultracode = params.ultracode,
+ .mode = switch (params.mode) {
+ .normal => .normal,
+ .plan => .plan,
+ .always_approve => .always_approve,
+ },
+ .strict = params.strict,
+ .goal = params.goal,
+ });
}
/// @-mention source: tracked+untracked files (gitignore honored), find fallback.
@@ -360,6 +345,7 @@ fn hudCb(kind: tui.HudKind, buf: []u8) usize {
test {
_ = tui;
_ = tui_sink;
+ _ = repl_bash;
}
test "hudCb usage/debug use the cost-tally renderer, not chars" {