xonecas.io
79113
Ma

mini-coding-agent / commit 774ed07

feat: read tool improvements

xonecas2026-10-04 774ed0751573641a4a36198cd94556b2d582085e parent 2f5b9e6

5 files changed

src/agent.zig+2−1
@@ -19,7 +19,7 @@ pub const Event = union(enum) {
1919 tool_call_start: []const u8,
2020 tool_call: struct { name: []const u8, arguments: []const u8 },
2121 tool_output: []const u8,
22- tool_result: struct { name: []const u8, text: []const u8, is_error: bool, diffs: []const common.FileDiff },
22+ tool_result: struct { name: []const u8, text: []const u8, is_error: bool, diffs: []const common.FileDiff, body: ?[]const u8 },
2323 message: *types.AssistantMessage,
2424 no_model,
2525 err: []const u8,
@@ -256,6 +256,7 @@ pub fn runTurn(opts: Options, messages: *std.ArrayList(types.Message), interacti
256256 .text = result.text,
257257 .is_error = result.is_error,
258258 .diffs = result.diffs,
259+ .body = result.body,
259260 } });
260261 }
261262 const joined = tryJoin(opts.a, held.items) catch {
src/tools/common.zig+3−0
@@ -38,4 +38,7 @@ pub const Result = struct {
3838 images: []const types.ImageContent = &.{},
3939 /// Files the tool changed, for display only.
4040 diffs: []const FileDiff = &.{},
41+ /// One line that replaces the result body on screen, for display only.
42+ /// Null shows `text` instead.
43+ body: ?[]const u8 = null,
4144 };
src/tools/index.zig+3−3
@@ -12,7 +12,7 @@ const edit_tool = @import("edit.zig");
1212 const bash_tool = @import("bash.zig");
1313
1414 const read_params =
15- \\{"type":"object","required":["path"],"properties":{"path":{"type":"string","description":"File path"}},"additionalProperties":false}
15+ \\{"type":"object","required":["path"],"properties":{"path":{"type":"string","description":"File path"},"offset":{"type":"integer","description":"First line to return, 1-based"},"range":{"type":"integer","description":"Number of lines to return from offset"}},"additionalProperties":false}
1616 ;
1717
1818 const edit_params =
@@ -23,8 +23,8 @@ const bash_params =
2323 \\{"type":"object","required":["command"],"properties":{"command":{"type":"string","description":"Command to run"}},"additionalProperties":false}
2424 ;
2525
26-const read_description = "Read a file. Returns its text. Prefer bash for search, ranges, or binary files.";
27-const read_image_description = "Read a file. Returns its text, or the image itself when the file is a png, jpg, or webp. Prefer bash for search, ranges, or binary files.";
26+const read_description = "Read a file. Returns its text. Returns the whole file unless offset and range give a line window. Prefer bash for search or binary files.";
27+const read_image_description = "Read a file. Returns its text, or the image itself when the file is a png, jpg, or webp. Returns the whole file unless offset and range give a line window. Prefer bash for search or binary files.";
2828 const edit_description = "Edit a file by exact text replacement. oldText must occur exactly once. With empty oldText, create a new file (fails if it exists).";
2929 const bash_description = "Run a bash command in the current working directory.";
3030
src/tools/read.zig+79−9
@@ -6,7 +6,11 @@ const util = @import("../util.zig");
66 const types = @import("../types.zig");
77 const common = @import("common.zig");
88
9-const Args = struct { path: []const u8 };
9+const Args = struct {
10+ path: []const u8,
11+ offset: ?usize = null,
12+ range: ?usize = null,
13+};
1014
1115 const image_mime = [_]struct { ext: []const u8, mime: []const u8 }{
1216 .{ .ext = ".png", .mime = "image/png" },
@@ -34,10 +38,62 @@ fn mimeFor(path: []const u8) ?[]const u8 {
3438 return null;
3539 }
3640
41+/// The position `n` lines after `pos`, or null when fewer than `n` lines
42+/// remain. A huge `n` costs no more than the text has lines.
43+fn advance(text: []const u8, pos: usize, n: usize) ?usize {
44+ var p = pos;
45+ var left = n;
46+ while (left > 0) : (left -= 1) {
47+ const nl = std.mem.indexOfScalarPos(u8, text, p, '\n') orelse return null;
48+ p = nl + 1;
49+ }
50+ return p;
51+}
52+
53+/// The bytes of `range` lines starting at the 1-based line `offset`, each line
54+/// keeping its trailing newline so consecutive reads reassemble the file. Null
55+/// when the text has fewer than `offset` lines; a range that runs past the end
56+/// stops there.
57+fn lineSlice(text: []const u8, offset: usize, range: ?usize) ?[]const u8 {
58+ const start = advance(text, 0, offset - 1) orelse return null;
59+ if (offset > 1 and start >= text.len) return null;
60+ if (range) |r| if (advance(text, start, r)) |end| return text[start..end];
61+ return text[start..];
62+}
63+
64+fn countLines(text: []const u8) usize {
65+ if (text.len == 0) return 0;
66+ return std.mem.count(u8, text, "\n") + @intFromBool(text[text.len - 1] != '\n');
67+}
68+
69+/// The display body for a text read: the line window that was asked for, then
70+/// the number of lines returned, and whether the cap cut the read short. The
71+/// path stays out: the call line above the body already carries it.
72+fn bodyLine(a: std.mem.Allocator, args: Args, lines: usize, truncated: bool) ?[]const u8 {
73+ var out: std.Io.Writer.Allocating = .init(a);
74+ const w = &out.writer;
75+ var window = false;
76+ if (args.offset) |o| {
77+ w.print("offset {d}", .{o}) catch return null;
78+ window = true;
79+ }
80+ if (args.range) |r| {
81+ if (window) w.writeAll(", ") catch return null;
82+ w.print("range {d}", .{r}) catch return null;
83+ window = true;
84+ }
85+ if (window) w.writeAll(" · ") catch return null;
86+ if (lines == 1) w.writeAll("1 line") catch return null else w.print("{d} lines", .{lines}) catch return null;
87+ if (truncated) w.writeAll(", truncated") catch return null;
88+ return out.written();
89+}
90+
3791 pub fn run(a: std.mem.Allocator, scratch: std.mem.Allocator, args_json: []const u8, ctx: common.Context) common.Result {
3892 const args = std.json.parseFromSliceLeaky(Args, scratch, args_json, .{ .ignore_unknown_fields = true }) catch
3993 return fail(a, "read failed: invalid arguments", .{});
4094 const path = args.path;
95+ if (args.offset) |o| if (o < 1) return fail(a, "read failed: offset must be at least 1", .{});
96+ if (args.range) |r| if (r < 1) return fail(a, "read failed: range must be at least 1", .{});
4197
4298 const data = util.readFileAlloc(a, path, 1 << 30) catch |e|
4399 return fail(a, "read failed: {s}: {s}", .{ path, @errorName(e) });
@@ -55,7 +111,12 @@ pub fn run(a: std.mem.Allocator, scratch: std.mem.Allocator, args_json: []const
55111 const summary = std.fmt.allocPrint(a, "read {s} ({s}, {d} bytes)", .{ path, mime, data.len }) catch "read";
56112 const images = a.alloc(types.ImageContent, 1) catch return .{ .text = summary, .is_error = false };
57113 images[0] = .{ .data = b64, .mime_type = mime };
58- return .{ .text = summary, .is_error = false, .images = images };
114+ return .{
115+ .text = summary,
116+ .is_error = false,
117+ .images = images,
118+ .body = std.fmt.allocPrint(a, "{s}, {d} bytes", .{ mime, data.len }) catch null,
119+ };
59120 }
60121
61122 const head = data[0..@min(data.len, 8000)];
@@ -64,13 +125,22 @@ pub fn run(a: std.mem.Allocator, scratch: std.mem.Allocator, args_json: []const
64125 }
65126
66127 const text = util.utf8Clean(a, data) catch return fail(a, "read failed: out of memory", .{});
67- if (text.len > max_text_chars) {
68- // Cut back to a code point boundary so the truncation never splits a
69- // sequence and hands the provider bytes that are not valid UTF-8.
128+ const offset = args.offset orelse 1;
129+ const slice = lineSlice(text, offset, args.range) orelse
130+ return fail(a, "read failed: {s} has fewer than {d} lines", .{ path, offset });
131+
132+ // Cut back to a code point boundary so the truncation never splits a
133+ // sequence and hands the provider bytes that are not valid UTF-8.
134+ var sent = slice;
135+ if (slice.len > max_text_chars) {
70136 var cut: usize = max_text_chars;
71- while (cut > 0 and text[cut] & 0xC0 == 0x80) cut -= 1;
72- const truncated = std.fmt.allocPrint(a, "{s}\n\n... truncated ... {s} is {d} characters\n", .{ text[0..cut], path, text.len }) catch "read failed";
73- return .{ .text = truncated, .is_error = false };
137+ while (cut > 0 and slice[cut] & 0xC0 == 0x80) cut -= 1;
138+ sent = slice[0..cut];
74139 }
75- return .{ .text = text, .is_error = false };
140+ const truncated = sent.len < slice.len;
141+ const result_text = if (truncated)
142+ std.fmt.allocPrint(a, "{s}\n\n... truncated ... {s} is {d} characters\n", .{ sent, path, slice.len }) catch "read failed"
143+ else
144+ sent;
145+ return .{ .text = result_text, .is_error = false, .body = bodyLine(a, args, countLines(sent), truncated) };
76146 }
src/tui/tui.zig+10−3
@@ -624,7 +624,7 @@ const Tui = struct {
624624 .message => |am| self.commitMessage(am),
625625 .tool_result => |tr| {
626626 self.activity.reset();
627- self.commitToolResult(tr.name, tr.text, tr.is_error, tr.diffs);
627+ self.commitToolResult(tr.name, tr.text, tr.is_error, tr.diffs, tr.body);
628628 },
629629 .err => |m| self.endTurn(styles.red(self.s, std.fmt.allocPrint(self.s, "! {s}", .{m}) catch "! error")),
630630 .no_model => self.endTurn(styles.red(self.s, "! no model configured")),
@@ -660,14 +660,20 @@ const Tui = struct {
660660 }
661661 }
662662
663- fn commitToolResult(self: *Tui, name: []const u8, text: []const u8, is_error: bool, diffs: []const common.FileDiff) void {
663+ fn commitToolResult(self: *Tui, name: []const u8, text: []const u8, is_error: bool, diffs: []const common.FileDiff, body: ?[]const u8) void {
664664 self.separator = true;
665665 if (self.pending_calls.items.len > 0) {
666666 const call = self.pending_calls.orderedRemove(0);
667667 self.commitLines(&.{.{ .text = std.fmt.allocPrint(self.s, "{s} {s}", .{ callHead(self.s, call.name), call.summary }) catch call.summary }});
668668 }
669669 const width = @max(self.term.width() - BODY_PREFIX.len, 1);
670- const lines = resultLines(self.s, name, text, is_error);
670+ // A tool that supplies a body wants one line instead of its text: the
671+ // header already carries the path, so the body carries what is not
672+ // visible anywhere else.
673+ const lines: []const stream.BodyLine = if (!is_error and body != null)
674+ &.{.{ .text = body.? }}
675+ else
676+ resultLines(self.s, name, text, is_error);
671677 const rows = if (std.mem.eql(u8, name, "edit")) renderRows(self.s, lines, width) else bodyRows(self.s, lines, width);
672678 for (rows, 0..) |row, i| {
673679 const prefix = if (is_error and i == rows.len - 1) styles.red(self.s, ERROR_PREFIX) else styles.dim(self.s, BODY_PREFIX);
@@ -1110,6 +1116,7 @@ fn copyEvent(a: std.mem.Allocator, e: agent.Event) agent.Event {
11101116 .text = a.dupe(u8, tr.text) catch "",
11111117 .is_error = tr.is_error,
11121118 .diffs = diffs,
1119+ .body = if (tr.body) |b| a.dupe(u8, b) catch "" else null,
11131120 } };
11141121 },
11151122 else => e,