Skip to content

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

Python

feat(acp): richer mid-turn stream + graff/models vendor method

justrachbeef6439cd23
diff --git a/src/acp.zig b/src/acp.zig
index 5458b6b2..b560981a 100644
--- a/src/acp.zig
+++ b/src/acp.zig
@@ -31,6 +31,9 @@ const proto = @import("acp_protocol.zig");
const engine = @import("acp_engine.zig");
const stream = @import("acp_stream.zig");
const playbook_glue = @import("playbook_glue.zig");
+const pricing = @import("pricing.zig");
+const billing = @import("billing.zig");
+const models_rank = @import("models_rank");
pub const protocol_version = proto.protocol_version;
pub const err_method_not_found = proto.err_method_not_found;
@@ -77,6 +80,53 @@ fn liveBind(ctx: *anyopaque, session_id: []const u8) void {
live.session_id = session_id;
}
+/// `graff/models` (vendor extension, dispatched through `engine.Dispatch.extra`):
+/// the same catalog + credential view the REPL `/models` table prints, so an
+/// ACP client can offer only the models this install can actually reach.
+/// Rows come back in election order (plan, then local, credits, api).
+fn liveModels(ctx: *anyopaque, arena: Allocator, w: *Io.Writer, req: proto.Request) anyerror!bool {
+ if (!std.mem.eql(u8, req.method, "graff/models")) return false;
+ if (req.id == null) return true;
+ const live: *LiveTurn = @ptrCast(@alignCast(ctx));
+ const keys = live.keys;
+ const root = live.root;
+ const catalog = pricing.models();
+ const Row = struct {
+ name: []const u8,
+ provider: []const u8,
+ context: u64,
+ authenticated: bool,
+ cost: []const u8,
+ current: bool,
+ };
+ const ranked = try arena.alloc(models_rank.Scored, catalog.len);
+ for (catalog, 0..) |m, i| ranked[i] = .{
+ .idx = i,
+ .score = models_rank.electionRank(
+ keys.get(m.provider) != null,
+ billing.costFor(m.provider, keys.source(m.provider)),
+ ),
+ };
+ std.mem.sort(models_rank.Scored, ranked, {}, models_rank.scoredLess);
+ const rows = try arena.alloc(Row, catalog.len);
+ for (ranked, rows) |r, *row| {
+ const m = catalog[r.idx];
+ row.* = .{
+ .name = m.name,
+ .provider = m.provider,
+ .context = pricing.contextFor(m.provider, m.name),
+ .authenticated = keys.get(m.provider) != null,
+ .cost = billing.costFor(m.provider, keys.source(m.provider)).badge(),
+ .current = std.mem.eql(u8, m.name, root.provider.model) and std.mem.eql(u8, m.provider, root.provider.id),
+ };
+ }
+ try proto.writeResult(w, req.id, .{
+ .models = rows,
+ .current = .{ .model = root.provider.model, .provider = root.provider.id },
+ });
+ return true;
+}
+
pub fn handleLine(d: *Dispatch, arena: Allocator, w: *Io.Writer, line: []const u8) !void {
engine.implementation_version = main_mod.harness_version;
engine.on_cancel = syncEscCancel;
@@ -107,7 +157,15 @@ const LiveTurn = struct {
main_mod.g_out = null;
}
const final = try providers.runTurnWithFallback(self.root, self.keys, arena, null);
+ // saw_text is "the LAST streamed event was answer text" (tool events
+ // reset it in the sink): a turn that ended mid-text already delivered
+ // the answer; one that ended on tools (attempt_completion flows) has
+ // its answer only in `final`, so that must still go on the wire.
if (self.saw_text) return "";
+ // A streamed preamble and the final answer are separate paragraphs;
+ // without the break the client renders "…answering.The three files…".
+ if (final.len > 0 and sink.streamed_any)
+ return try std.fmt.allocPrint(arena, "\n\n{s}", .{final});
return final;
}
};
@@ -132,6 +190,7 @@ pub fn runAcpCommand(gpa: Allocator, io: Io, environ_map: anytype, root: *agent_
.slash = liveSlash,
.after_user = liveAfter,
.bind_session = liveBind,
+ .extra = liveModels,
};
while (true) {
const line = (in.takeDelimiter('\n') catch break) orelse break;
diff --git a/src/acp_engine.zig b/src/acp_engine.zig
index ede34dda..83eaf62c 100644
--- a/src/acp_engine.zig
+++ b/src/acp_engine.zig
@@ -31,6 +31,9 @@ pub const TurnFn = *const fn (ctx: *anyopaque, arena: Allocator, text: []const u
pub const SlashFn = *const fn (ctx: *anyopaque, arena: Allocator, text: []const u8) anyerror!?[]const u8;
pub const AfterUserFn = *const fn (ctx: *anyopaque, arena: Allocator, text: []const u8) void;
pub const BindSessionFn = *const fn (ctx: *anyopaque, session_id: []const u8) void;
+/// Vendor-method escape hatch: gets every request the core loop does not
+/// claim; returns true when it answered (false falls through to -32601).
+pub const ExtraFn = *const fn (ctx: *anyopaque, arena: Allocator, w: *Io.Writer, req: proto.Request) anyerror!bool;
pub const Dispatch = struct {
turn: TurnFn,
@@ -41,6 +44,7 @@ pub const Dispatch = struct {
slash: ?SlashFn = null,
after_user: ?AfterUserFn = null,
bind_session: ?BindSessionFn = null,
+ extra: ?ExtraFn = null,
};
fn respond(w: *Io.Writer, req: proto.Request, result: anytype) !void {
@@ -122,6 +126,7 @@ pub fn handleLine(d: *Dispatch, arena: Allocator, w: *Io.Writer, line: []const u
return;
}
if (std.mem.eql(u8, req.method, "session/prompt")) return promptTurn(d, arena, w, req);
+ if (d.extra) |extra| if (try extra(d.ctx, arena, w, req)) return;
if (req.id == null) return;
try writeError(w, req.id, err_method_not_found, try std.fmt.allocPrint(arena, "method not found: {s}", .{req.method}));
}
diff --git a/src/acp_stream.zig b/src/acp_stream.zig
index fa9e79d1..3a16ca75 100644
--- a/src/acp_stream.zig
+++ b/src/acp_stream.zig
@@ -19,14 +19,33 @@ pub fn kindFor(name: []const u8) []const u8 {
if (std.mem.eql(u8, name, "webfetch")) return "fetch";
if (std.mem.eql(u8, name, "todo_write") or std.mem.eql(u8, name, "todo_read"))
return "think";
+ // MCP tools arrive as mcp__<server>__<tool>; the tool half names the
+ // action, so keyword-match only that suffix (never bare catalog names —
+ // "todo_read" must stay `think` above, not become `read` here).
+ if (std.mem.startsWith(u8, name, "mcp__")) {
+ const tool = if (std.mem.lastIndexOf(u8, name, "__")) |i| name[i + 2 ..] else name;
+ const table = [_]struct { needle: []const u8, kind: []const u8 }{
+ .{ .needle = "search", .kind = "search" }, .{ .needle = "grep", .kind = "search" },
+ .{ .needle = "find", .kind = "search" }, .{ .needle = "list", .kind = "search" },
+ .{ .needle = "read", .kind = "read" }, .{ .needle = "status", .kind = "read" },
+ .{ .needle = "diff", .kind = "read" }, .{ .needle = "fetch", .kind = "fetch" },
+ .{ .needle = "edit", .kind = "edit" }, .{ .needle = "create", .kind = "edit" },
+ .{ .needle = "write", .kind = "edit" }, .{ .needle = "patch", .kind = "edit" },
+ .{ .needle = "replace", .kind = "edit" }, .{ .needle = "exec", .kind = "execute" },
+ .{ .needle = "run", .kind = "execute" },
+ };
+ for (table) |row| if (std.mem.indexOf(u8, tool, row.needle) != null) return row.kind;
+ }
return "other";
}
fn titleFor(name: []const u8, input: Value) []const u8 {
if (input == .object) {
if (util.strFieldObj(input.object, "path")) |p| return p;
+ if (util.strFieldObj(input.object, "file")) |f| return f;
if (util.strFieldObj(input.object, "command")) |c| return c;
if (util.strFieldObj(input.object, "url")) |u| return u;
+ if (util.strFieldObj(input.object, "description")) |d| return d;
}
return name;
}
@@ -59,13 +78,26 @@ pub fn writeToolCall(w: *Io.Writer, session_id: []const u8, id: []const u8, name
});
}
+pub fn writeToolStatus(w: *Io.Writer, session_id: []const u8, id: []const u8, status: []const u8) !void {
+ try proto.writeNotification(w, "session/update", .{
+ .sessionId = session_id,
+ .update = .{
+ .sessionUpdate = "tool_call_update",
+ .toolCallId = id,
+ .status = status,
+ },
+ });
+}
+
pub fn writeToolDone(w: *Io.Writer, session_id: []const u8, id: []const u8, is_error: bool, text: []const u8) !void {
+ const status: []const u8 = if (is_error) "failed" else "completed";
+ if (text.len == 0) return writeToolStatus(w, session_id, id, status);
try proto.writeNotification(w, "session/update", .{
.sessionId = session_id,
.update = .{
.sessionUpdate = "tool_call_update",
.toolCallId = id,
- .status = if (is_error) "failed" else "completed",
+ .status = status,
.content = .{
.{ .type = "content", .content = .{ .type = "text", .text = text } },
},
@@ -110,7 +142,18 @@ pub fn translateEvent(
}
if (std.mem.eql(u8, typ, "tool_call") or std.mem.eql(u8, typ, "tool_call_started")) {
const name = util.strFieldObj(ev.object, "name") orelse "tool";
+ // attempt_completion is the turn's answer, not work: its bracket would
+ // render as a bogus tool row while the payload arrives as final text.
+ if (std.mem.eql(u8, name, "attempt_completion")) return .none;
const input = ev.object.get("input") orelse Value{ .object = .empty };
+ // The engine brackets every call twice: `tool_call` announces it and
+ // `tool_call_started` marks dispatch of the SAME call (the TUI draws
+ // only the first). An id-less start therefore updates the announced
+ // row to in_progress — minting here doubled every tool in the client.
+ if (std.mem.eql(u8, typ, "tool_call_started") and util.strFieldObj(ev.object, "id") == null and id_buf[0] != 0) {
+ try writeToolStatus(w, session_id, lastId(id_buf), "in_progress");
+ return .tool;
+ }
const id = if (util.strFieldObj(ev.object, "id")) |given|
storeId(id_buf, given)
else blk: {
@@ -123,6 +166,8 @@ pub fn translateEvent(
return .tool;
}
if (std.mem.eql(u8, typ, "tool_result") or std.mem.eql(u8, typ, "tool_call_finished") or std.mem.eql(u8, typ, "tool_rejected")) {
+ if (util.strFieldObj(ev.object, "name")) |name|
+ if (std.mem.eql(u8, name, "attempt_completion")) return .none;
const use_id = if (util.strFieldObj(ev.object, "id")) |given| storeId(id_buf, given) else lastId(id_buf);
const text = util.strFieldObj(ev.object, "text") orelse util.strFieldObj(ev.object, "message") orelse "";
const is_error = switch (ev.object.get("is_error") orelse .null) {
@@ -140,6 +185,9 @@ pub const EventSink = struct {
out: *Io.Writer,
session_id: *[]const u8,
saw_text: *bool,
+ /// Any text delta this turn (never reset) — the final chunk needs a
+ /// paragraph break after a streamed preamble, or the two texts fuse.
+ streamed_any: bool = false,
pending: std.ArrayList(u8),
gpa: Allocator,
next_tool: u32 = 0,
@@ -182,7 +230,18 @@ pub const EventSink = struct {
var parsed = std.json.parseFromSlice(Value, self.gpa, trimmed, .{}) catch return;
defer parsed.deinit();
const kind = translateEvent(self.out, self.session_id.*, parsed.value, &self.last_id, &self.next_tool) catch return;
- if (kind == .text) self.saw_text.* = true;
+ // saw_text means "the last thing streamed was answer text". A tool
+ // event resets it: a completion-tool turn streams its preamble, THEN
+ // runs tools, and the real answer only exists in the turn's final
+ // result — suppressing that because a preamble streamed loses it.
+ switch (kind) {
+ .text => {
+ self.saw_text.* = true;
+ self.streamed_any = true;
+ },
+ .tool => self.saw_text.* = false,
+ else => {},
+ }
self.out.flush() catch {};
}
@@ -215,6 +274,47 @@ test "kindFor maps catalog tools onto ACP kinds" {
try testing.expectEqualStrings("other", kindFor("ask_user"));
}
+test "kindFor classifies MCP tools by their suffix, catalog names untouched" {
+ try testing.expectEqualStrings("read", kindFor("mcp__codedbpro__read"));
+ try testing.expectEqualStrings("search", kindFor("mcp__codedbpro__faster_search"));
+ try testing.expectEqualStrings("edit", kindFor("mcp__codedbpro__create"));
+ try testing.expectEqualStrings("other", kindFor("mcp__relay__room_post"));
+ // Suffix keywords must not reclassify bare catalog names.
+ try testing.expectEqualStrings("think", kindFor("todo_read"));
+}
+
+test "translateEvent: an id-less tool_call_started updates the announced call" {
+ var buf: [2048]u8 = undefined;
+ var w: Io.Writer = .fixed(&buf);
+ var arena_state = std.heap.ArenaAllocator.init(testing.allocator);
+ defer arena_state.deinit();
+ const a = arena_state.allocator();
+ var id_buf: [64]u8 = @splat(0);
+ var next: u32 = 0;
+
+ const call = try std.json.parseFromSlice(Value, a, "{\"type\":\"tool_call\",\"name\":\"bash\",\"input\":{\"command\":\"ls\"}}", .{});
+ defer call.deinit();
+ _ = try translateEvent(&w, "s1", call.value, &id_buf, &next);
+
+ w = .fixed(&buf);
+ const started = try std.json.parseFromSlice(Value, a, "{\"type\":\"tool_call_started\",\"name\":\"bash\",\"input\":{\"command\":\"ls\"}}", .{});
+ defer started.deinit();
+ try testing.expectEqual(.tool, try translateEvent(&w, "s1", started.value, &id_buf, &next));
+ // Same id, an update — a second tool_call here doubled every row.
+ try testing.expect(std.mem.indexOf(u8, w.buffered(), "tool_call_update") != null);
+ try testing.expect(std.mem.indexOf(u8, w.buffered(), "call-1") != null);
+ try testing.expect(std.mem.indexOf(u8, w.buffered(), "in_progress") != null);
+ try testing.expectEqual(@as(u32, 1), next);
+
+ // The timing bracket has no text: status only, no content array.
+ w = .fixed(&buf);
+ const finished = try std.json.parseFromSlice(Value, a, "{\"type\":\"tool_call_finished\",\"name\":\"bash\",\"is_error\":false,\"ms\":12}", .{});
+ defer finished.deinit();
+ _ = try translateEvent(&w, "s1", finished.value, &id_buf, &next);
+ try testing.expect(std.mem.indexOf(u8, w.buffered(), "completed") != null);
+ try testing.expect(std.mem.indexOf(u8, w.buffered(), "\"content\"") == null);
+}
+
test "translateEvent: reasoning and text become chunks" {
var buf: [1024]u8 = undefined;
var w: Io.Writer = .fixed(&buf);
@@ -261,6 +361,34 @@ test "translateEvent: tool_call then tool_result share a minted id" {
try testing.expect(std.mem.indexOf(u8, w.buffered(), "completed") != null);
}
+test "attempt_completion is no tool row, and tools reset saw_text" {
+ var buf: [4096]u8 = undefined;
+ var w: Io.Writer = .fixed(&buf);
+ var sid: []const u8 = "s1";
+ var saw = false;
+ var sink: EventSink = undefined;
+ sink.init(testing.allocator, &w, &sid, &saw);
+ defer sink.deinit();
+
+ try sink.writer.writeAll("{\"type\":\"text\",\"text\":\"preamble\"}\n");
+ try sink.writer.flush();
+ try testing.expect(saw);
+
+ // A tool after the preamble means the turn's answer is still to come —
+ // the final result must not be suppressed by the preamble's delta.
+ try sink.writer.writeAll("{\"type\":\"tool_call\",\"name\":\"read_file\",\"input\":{\"path\":\"a.zig\"}}\n");
+ try sink.writer.flush();
+ try testing.expect(!saw);
+
+ // The completion bracket is the answer's delivery, never a tool row.
+ const before = w.buffered().len;
+ try sink.writer.writeAll("{\"type\":\"tool_call\",\"name\":\"attempt_completion\",\"input\":{\"result\":\"done\"}}\n");
+ try sink.writer.writeAll("{\"type\":\"tool_result\",\"name\":\"attempt_completion\",\"is_error\":false,\"text\":\"done\"}\n");
+ try sink.writer.flush();
+ try testing.expectEqual(before, w.buffered().len);
+ try testing.expect(!saw);
+}
+
test "EventSink translates a JSONL reasoning line through the writer" {
var buf: [2048]u8 = undefined;
var w: Io.Writer = .fixed(&buf);