graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
ACP: tool locations, edit diffs, execute kind, detailed approvals (#1287, #1288, #1289)
Rach Pradhanb3b7d07875ad
diff --git a/src/acp_permission.zig b/src/acp_permission.zigindex 4cc6179a..431bfe61 100644--- a/src/acp_permission.zig+++ b/src/acp_permission.zig@@ -58,6 +58,17 @@ pub const Bridge = struct {.{ .optionId = "reject_once", .name = "Reject", .kind = "reject_once" },.{ .optionId = "allow_always", .name = req.always_label, .kind = "allow_always" },};+ // What is being approved (#1289): kind, input, and for file tools+ // the same locations and diff the tool call itself announces.+ var arena_state = std.heap.ArenaAllocator.init(std.heap.page_allocator);+ defer arena_state.deinit();+ const arena = arena_state.allocator();+ const input = req.input orelse std.json.Value{ .object = .empty };+ const kind = @import("acp_stream.zig").kindFor(req.tool);+ const cwd = @import("main.zig").g_cwd_display;+ const view = @import("acp_tool_view.zig");+ const locations = view.locations(arena, kind, input, cwd) catch return .deny;+ const content = view.diffs(arena, req.tool, input, cwd) catch return .deny;{// Same order as tool dispatch: bridge state -> shared output.// Inbox responses/cancel never acquire the output lock. Release it@@ -69,7 +80,7 @@ pub const Bridge = struct {defer if (self.output_lock) |lock| lock.unlock(io);std.json.Stringify.value(.{ .jsonrpc = "2.0", .id = id, .method = "session/request_permission", .params = .{.sessionId = self.session,- .toolCall = .{ .toolCallId = req.call_id, .title = req.description, .status = "pending" },+ .toolCall = .{ .toolCallId = req.call_id, .title = req.description, .status = "pending", .kind = kind, .rawInput = input, .locations = locations, .content = content },.options = options[0..if (req.allow_always) @as(usize, 3) else 2],} }, .{}, self.out) catch return .deny;self.out.writeByte('\n') catch return .deny;diff --git a/src/acp_stream.zig b/src/acp_stream.zigindex caeb4a37..33f45e6d 100644--- a/src/acp_stream.zig+++ b/src/acp_stream.zig@@ -8,14 +8,14 @@ const Allocator = std.mem.Allocator;const Value = std.json.Value;const util = @import("util.zig");const proto = @import("acp_protocol.zig");+const view = @import("acp_tool_view.zig");pub fn kindFor(name: []const u8) []const u8 {if (std.mem.eql(u8, name, "read_file") or std.mem.eql(u8, name, "codedb") or std.mem.eql(u8, name, "skill"))return "read";if (std.mem.eql(u8, name, "edit_file") or std.mem.eql(u8, name, "write_file"))return "edit";- if (std.mem.eql(u8, name, "bash") or std.mem.eql(u8, name, "bash_output") or std.mem.eql(u8, name, "bash_kill"))- return "execute";+ if (@import("shell_tool.zig").isFamily(name)) return "execute";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";@@ -65,14 +65,21 @@ pub fn writeMessage(w: *Io.Writer, session_id: []const u8, text: []const u8) !vo}pub fn writeToolCall(w: *Io.Writer, session_id: []const u8, id: []const u8, name: []const u8, input: Value) !void {+ var arena_state = std.heap.ArenaAllocator.init(std.heap.page_allocator);+ defer arena_state.deinit();+ const a = arena_state.allocator();+ const kind = kindFor(name);+ const cwd = @import("main.zig").g_cwd_display;try proto.writeNotification(w, "session/update", .{.sessionId = session_id,.update = .{.sessionUpdate = "tool_call",.toolCallId = id,.title = titleFor(name, input),- .kind = kindFor(name),+ .kind = kind,.status = "in_progress",+ .locations = try view.locations(a, kind, input, cwd),+ .content = try view.diffs(a, name, input, cwd),.rawInput = input,._meta = .{ .@"graff/toolName" = name },},@@ -178,15 +185,25 @@ pub fn translateEvent(try writeToolCall(w, session_id, id, name, input);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;+ // The engine closes every call with tool_result and then+ // tool_call_finished (timing only, no text): the result already sent the+ // terminal update, so a second one would only duplicate it (#1288).+ if (std.mem.eql(u8, typ, "tool_call_finished")) return .tool;+ if (std.mem.eql(u8, typ, "tool_result") or std.mem.eql(u8, typ, "tool_rejected")) {+ const result_name = util.strFieldObj(ev.object, "name") orelse "";+ if (std.mem.eql(u8, result_name, "attempt_completion")) return .none;const use_id = if (util.strFieldObj(ev.object, "id")) |given| 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) {.bool => |b| b,else => std.mem.eql(u8, typ, "tool_rejected"),};+ // Content in an update replaces the call's content: a successful+ // native edit keeps its announced diff instead of "replaced 1 …".+ if (!is_error and (std.mem.eql(u8, result_name, "edit_file") or std.mem.eql(u8, result_name, "write_file"))) {+ try writeToolStatus(w, session_id, use_id, "completed");+ return .tool;+ }try writeToolDone(w, session_id, use_id, is_error, text);return .tool;}@@ -341,11 +358,44 @@ test "translateEvent: an id-less tool_call_started updates the announced call" {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.+ // An empty result closes the call with status only, no content array.+ w = .fixed(&buf);+ const result = try std.json.parseFromSlice(Value, a, "{\"type\":\"tool_result\",\"name\":\"bash\",\"is_error\":false,\"text\":\"\"}", .{});+ defer result.deinit();+ _ = try translateEvent(&w, "s1", result.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);++ // The timing bracket that follows every result sends nothing (#1288).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.expectEqual(.tool, try translateEvent(&w, "s1", finished.value, &id_buf, &next));+ try testing.expectEqual(@as(usize, 0), w.buffered().len);+}++test "translateEvent: shell is execute; edits carry locations and a diff that the result keeps" {+ var buf: [4096]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;+ try testing.expectEqualStrings("execute", kindFor("shell"));++ const call = try std.json.parseFromSlice(Value, a, "{\"type\":\"tool_call\",\"id\":\"e1\",\"name\":\"edit_file\",\"input\":{\"path\":\"calc.py\",\"old_string\":\"a - b\",\"new_string\":\"a + b\"}}", .{});+ defer call.deinit();+ _ = try translateEvent(&w, "s1", call.value, &id_buf, &next);+ const announced = w.buffered();+ try testing.expect(std.mem.indexOf(u8, announced, "\"locations\":[{\"path\":") != null);+ try testing.expect(std.mem.indexOf(u8, announced, "\"type\":\"diff\"") != null);+ try testing.expect(std.mem.indexOf(u8, announced, "\"oldText\":\"a - b\",\"newText\":\"a + b\"") != null);++ w = .fixed(&buf);+ const done = try std.json.parseFromSlice(Value, a, "{\"type\":\"tool_result\",\"id\":\"e1\",\"name\":\"edit_file\",\"is_error\":false,\"text\":\"replaced 1 occurrence(s) in calc.py\"}", .{});+ defer done.deinit();+ _ = try translateEvent(&w, "s1", done.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);}diff --git a/src/acp_tool_view.zig b/src/acp_tool_view.zignew file mode 100644index 00000000..691e4cd9--- /dev/null+++ b/src/acp_tool_view.zig@@ -0,0 +1,96 @@+//! What an ACP client needs to show a file tool call: where it works+//! (`locations`) and, for an edit, the change (`diff` content). Shared by+//! tool_call announcements and permission requests (#1287, #1289).++const std = @import("std");+const Allocator = std.mem.Allocator;+const Value = std.json.Value;+const util = @import("util.zig");++fn filePath(input: Value) ?[]const u8 {+ if (input != .object) return null;+ return util.strFieldObj(input.object, "path") orelse util.strFieldObj(input.object, "file");+}++/// ACP wants absolute paths; a relative tool path joins the session's+/// working directory when that is known to be absolute.+fn absolute(arena: Allocator, path: []const u8, cwd: []const u8) ![]const u8 {+ if (std.fs.path.isAbsolute(path) or !std.fs.path.isAbsolute(cwd)) return path;+ return std.fs.path.join(arena, &.{ cwd, path });+}++/// `[{path, line?}]` for a read or edit tool naming a file; empty otherwise.+pub fn locations(arena: Allocator, kind: []const u8, input: Value, cwd: []const u8) !Value {+ var out = std.json.Array.init(arena);+ if (!std.mem.eql(u8, kind, "read") and !std.mem.eql(u8, kind, "edit")) return .{ .array = out };+ const path = filePath(input) orelse return .{ .array = out };+ var loc: std.json.ObjectMap = .empty;+ try loc.put(arena, "path", .{ .string = try absolute(arena, path, cwd) });+ if (input.object.get("start_line")) |line| if (line == .integer and line.integer > 0) try loc.put(arena, "line", line);+ try out.append(.{ .object = loc });+ return .{ .array = out };+}++fn diff(arena: Allocator, path: []const u8, old: ?[]const u8, new: []const u8) !Value {+ var d: std.json.ObjectMap = .empty;+ try d.put(arena, "type", .{ .string = "diff" });+ try d.put(arena, "path", .{ .string = path });+ try d.put(arena, "oldText", if (old) |t| .{ .string = t } else .null);+ try d.put(arena, "newText", .{ .string = new });+ return .{ .object = d };+}++/// ACP `diff` content for a native file edit: each `edit_file` span (single+/// or batch form) as oldText/newText, `write_file` as new content. Empty for+/// every other tool.+pub fn diffs(arena: Allocator, name: []const u8, input: Value, cwd: []const u8) !Value {+ var out = std.json.Array.init(arena);+ const raw_path = filePath(input) orelse return .{ .array = out };+ const path = try absolute(arena, raw_path, cwd);+ if (std.mem.eql(u8, name, "write_file")) {+ if (util.strFieldObj(input.object, "content")) |content| try out.append(try diff(arena, path, null, content));+ } else if (std.mem.eql(u8, name, "edit_file")) {+ if (input.object.get("edits")) |edits| if (edits == .array) for (edits.array.items) |e| {+ if (e != .object) continue;+ const old = util.strFieldObj(e.object, "old_string") orelse continue;+ const new = util.strFieldObj(e.object, "new_string") orelse continue;+ try out.append(try diff(arena, path, old, new));+ };+ if (util.strFieldObj(input.object, "old_string")) |old| if (util.strFieldObj(input.object, "new_string")) |new|+ try out.append(try diff(arena, path, old, new));+ }+ return .{ .array = out };+}++test "locations: file tools name an absolute path and optional line; others none" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const a = arena_state.allocator();+ const read = try std.json.parseFromSliceLeaky(Value, a, "{\"path\":\"src/x.zig\",\"start_line\":40}", .{});+ const locs = try locations(a, "read", read, "/repo");+ try std.testing.expectEqual(@as(usize, 1), locs.array.items.len);+ try std.testing.expectEqualStrings("/repo/src/x.zig", locs.array.items[0].object.get("path").?.string);+ try std.testing.expectEqual(@as(i64, 40), locs.array.items[0].object.get("line").?.integer);+ const abs = try std.json.parseFromSliceLeaky(Value, a, "{\"path\":\"/etc/hosts\"}", .{});+ try std.testing.expectEqualStrings("/etc/hosts", (try locations(a, "edit", abs, "/repo")).array.items[0].object.get("path").?.string);+ try std.testing.expectEqual(@as(usize, 0), (try locations(a, "execute", read, "/repo")).array.items.len);+}++test "diffs: edit_file single and batch spans, write_file as new content, nothing else" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const a = arena_state.allocator();+ const single = try std.json.parseFromSliceLeaky(Value, a, "{\"path\":\"calc.py\",\"old_string\":\"a - b\",\"new_string\":\"a + b\"}", .{});+ const one = try diffs(a, "edit_file", single, "/repo");+ try std.testing.expectEqual(@as(usize, 1), one.array.items.len);+ try std.testing.expectEqualStrings("diff", one.array.items[0].object.get("type").?.string);+ try std.testing.expectEqualStrings("/repo/calc.py", one.array.items[0].object.get("path").?.string);+ try std.testing.expectEqualStrings("a - b", one.array.items[0].object.get("oldText").?.string);+ try std.testing.expectEqualStrings("a + b", one.array.items[0].object.get("newText").?.string);+ const batch = try std.json.parseFromSliceLeaky(Value, a, "{\"path\":\"f\",\"edits\":[{\"old_string\":\"1\",\"new_string\":\"2\"},{\"old_string\":\"3\",\"new_string\":\"4\"}]}", .{});+ try std.testing.expectEqual(@as(usize, 2), (try diffs(a, "edit_file", batch, "/repo")).array.items.len);+ const write = try std.json.parseFromSliceLeaky(Value, a, "{\"path\":\"new.txt\",\"content\":\"hi\"}", .{});+ const created = try diffs(a, "write_file", write, "/repo");+ try std.testing.expect(created.array.items[0].object.get("oldText").? == .null);+ try std.testing.expectEqual(@as(usize, 0), (try diffs(a, "read_file", single, "/repo")).array.items.len);+}diff --git a/src/agent_tool_gate.zig b/src/agent_tool_gate.zigindex 13adcf2d..e8a08502 100644--- a/src/agent_tool_gate.zig+++ b/src/agent_tool_gate.zig@@ -192,7 +192,7 @@ pub fn gateTool(self: *Agent, call: ToolCall) !?ExecResult {if (approvals.planReadAllowed(self.io, cmd)) return null;if (self.permission) |handler| {const description = try std.fmt.allocPrint(self.arena, "plan mode — read outside the project: {s}", .{cmd});- if (handler.ask(self.io, .{ .call_id = call.id, .tool = call.name, .description = description }) == .allow_once) {+ if (handler.ask(self.io, .{ .call_id = call.id, .tool = call.name, .description = description, .input = call.input }) == .allow_once) {try approvals.approvePlanReadOnce(self.io, self.arena, self, call.id, cmd);return null;}@@ -306,7 +306,7 @@ pub fn gateTool(self: *Agent, call: ToolCall) !?ExecResult {} else return null;if (self.permission) |handler| {- switch (handler.ask(self.io, .{ .call_id = call.id, .tool = call.name, .description = prompt_line, .allow_always = true, .always_label = try std.fmt.allocPrint(self.arena, "Always allow {s}", .{key}) })) {+ switch (handler.ask(self.io, .{ .call_id = call.id, .tool = call.name, .description = prompt_line, .input = call.input, .allow_always = true, .always_label = try std.fmt.allocPrint(self.arena, "Always allow {s}", .{key}) })) {.allow_once => return null,.allow_always => {try approvals.approve(self.io, self.gpa, key);diff --git a/src/engine_permission.zig b/src/engine_permission.zigindex 5bce8a62..1bc6bcfb 100644--- a/src/engine_permission.zig+++ b/src/engine_permission.zig@@ -1,7 +1,7 @@//! Frontend-owned permission input; the engine owns which calls need consent.const std = @import("std");pub const Decision = enum { allow_once, allow_always, deny };-pub const Request = struct { call_id: []const u8, tool: []const u8, description: []const u8, allow_always: bool = false, always_label: []const u8 = "Always allow this permission" };+pub const Request = struct { call_id: []const u8, tool: []const u8, description: []const u8, allow_always: bool = false, always_label: []const u8 = "Always allow this permission", input: ?std.json.Value = null };pub const Handler = struct {ctx: *anyopaque,request: *const fn (*anyopaque, std.Io, Request) Decision,diff --git a/src/test_hooks.zig b/src/test_hooks.zigindex 671be273..a44f625e 100644--- a/src/test_hooks.zig+++ b/src/test_hooks.zig@@ -370,6 +370,7 @@ test {_ = @import("tui_goal.zig"); // #716: typed TUI /goal is retirable, not standing_ = @import("net_efficiency_test.zig");_ = @import("codex_tool_search.zig"); // hosted tool_search on gpt-5.4+ Codex+ _ = @import("acp_tool_view.zig"); // #1287/#1289: ACP locations and edit diffs_ = @import("tool_call_args.zig"); // #752: truncated tool-call arguments must not poison history_ = @import("tool_call_repair.zig"); // MiMo: lost tool-call arguments rebuilt from markup_ = @import("cache_affinity.zig"); // ADR 0069: git-root / scratch cache seed