xonecas.io
79113
Ma

mini-coding-agent / files

mini-coding-agent / src / tools / bash.zig

9.7 KB
1const std = @import("std");
2const filesystem = @import("../filesystem.zig");
3const platform = @import("../platform.zig");
4const text = @import("../text.zig");
5const tools = @import("../tools.zig");
6const snapshot = @import("snapshot.zig");
7
8const max_head = 10_000;
9const max_tail = 6_000;
10const truncated_marker = "\n\n... output truncated ...\n\n";
11
12const default_timeout_s = 120;
13
14const description_fmt =
15    "Run a bash command and return its combined output.\n\n" ++
16    "The command runs with `bash -c` starting in {s}, your working directory. Use it for " ++
17    "builds, tests, git, package managers, and other file work. The output ends " ++
18    "with an `exit code:` line, or `killed: timed out after Ns` if it hits the time limit. " ++
19    "Pass `timeout` (seconds) to change the 120-second limit. Pass `cwd` to run the " ++
20    "command in another directory; it is shorter than prefixing the command with " ++
21    "`cd <dir> &&`, and it tells us which directory to track for the diff.";
22
23const params = [_]tools.Param{
24    .{ .name = "command", .kind = .string, .description = "Bash command line to execute." },
25    .{ .name = "cwd", .kind = .string, .required = false, .description = "Directory to run the command in, instead of `cd <dir> && ...`. Relative paths resolve against the working directory. Defaults to the working directory." },
26    .{ .name = "timeout", .kind = .integer, .required = false, .description = "Seconds to allow before the command is killed. Defaults to 120." },
27};
28
29fn describe(a: std.mem.Allocator, ctx: tools.Describe) []const u8 {
30    return std.fmt.allocPrint(a, description_fmt, .{ctx.cwd}) catch "Run a bash command.";
31}
32
33pub const tool = tools.Descriptor{
34    .name = .bash,
35    .description = describe,
36    .params = &params,
37    .run = run,
38};
39
40const Args = struct { command: []const u8, cwd: ?[]const u8 = null, timeout: ?u64 = null };
41
42fn trimRoot(path: []const u8) []const u8 {
43    var p = path;
44    while (std.mem.startsWith(u8, p, "./")) p = p[2..];
45    while (p.len > 1 and p[p.len - 1] == '/') p = p[0 .. p.len - 1];
46    return if (std.mem.eql(u8, p, ".")) "" else p;
47}
48
49const Acc = struct {
50    a: std.mem.Allocator,
51    head: std.ArrayList(u8) = .empty,
52    tail: std.ArrayList(u8) = .empty,
53    truncated: bool = false,
54    on_output: ?tools.OutputFn,
55
56    fn append(self: *Acc, chunk: []const u8) !void {
57        if (self.on_output) |cb| cb.call(chunk);
58        var rest = chunk;
59        if (self.head.items.len < max_head) {
60            const take = @min(max_head - self.head.items.len, rest.len);
61            try self.head.appendSlice(self.a, rest[0..take]);
62            rest = rest[take..];
63        }
64        if (rest.len == 0) return;
65        try self.tail.appendSlice(self.a, rest);
66        if (self.tail.items.len > max_tail) {
67            self.truncated = true;
68            const drop = self.tail.items.len - max_tail;
69            std.mem.copyForwards(u8, self.tail.items[0..], self.tail.items[drop..]);
70            self.tail.items.len = max_tail;
71        }
72    }
73
74    fn body(self: *Acc, a: std.mem.Allocator) ![]u8 {
75        var out: std.ArrayList(u8) = .empty;
76        try out.appendSlice(a, self.head.items);
77        if (self.truncated) try out.appendSlice(a, truncated_marker);
78        try out.appendSlice(a, self.tail.items);
79        return out.toOwnedSlice(a);
80    }
81};
82
83fn killGroup(pid: i32) void {
84    std.posix.kill(-pid, .TERM) catch {};
85    std.Io.sleep(platform.io, .{ .nanoseconds = 300 * std.time.ns_per_ms }, .boot) catch {};
86    std.posix.kill(-pid, .KILL) catch {};
87}
88
89fn bodyLine(a: std.mem.Allocator, code: ?u8, timed_out: bool, timeout_s: u64, output: []const u8) ?[]const u8 {
90    const label = if (code) |c|
91        std.fmt.allocPrint(a, "exit {d}", .{c}) catch return null
92    else if (timed_out)
93        std.fmt.allocPrint(a, "timed out after {d}s", .{timeout_s}) catch return null
94    else
95        "aborted";
96    const lines = text.countLines(output);
97    if (lines == 0) return label;
98    const truncated = std.mem.indexOf(u8, output, truncated_marker) != null;
99    return std.fmt.allocPrint(a, "{s} · {s}{s}", .{
100        label,
101        text.plural(a, lines, "line", "lines"),
102        if (truncated) ", truncated" else "",
103    }) catch null;
104}
105
106fn fail(a: std.mem.Allocator, comptime fmt: []const u8, args: anytype) tools.Result {
107    return tools.fail(a, "bash failed", fmt, args);
108}
109
110pub fn run(a: std.mem.Allocator, scratch: std.mem.Allocator, args_json: []const u8, ctx: tools.Context) tools.Result {
111    const args = std.json.parseFromSliceLeaky(Args, scratch, args_json, .{ .ignore_unknown_fields = true }) catch {
112        return fail(a, "bash failed: command must be a string", .{});
113    };
114
115    const cwd = if (args.cwd) |raw| trimRoot(filesystem.expandTilde(scratch, raw)) else "";
116    if (cwd.len > 0) {
117        const st = std.Io.Dir.cwd().statFile(platform.io, cwd, .{}) catch |e| return tools.ioFail(a, "bash", cwd, e);
118        if (st.kind != .directory) return fail(a, "bash failed: {s} is not a directory", .{cwd});
119    }
120
121    const ignore = snapshot.Ignore{ .root = cwd, .dirs = ctx.snapshot_ignore_dirs, .uses_gitignore = ctx.snapshot_uses_gitignore };
122    if (ctx.on_phase) |p| p.call(.snapshotting);
123    const before = snapshot.capture(scratch, ignore) catch return fail(a, "bash failed: out of memory", .{});
124    if (ctx.on_phase) |p| p.call(.running);
125
126    var child = std.process.spawn(platform.io, .{
127        .argv = &.{ "bash", "-c", args.command },
128        .cwd = if (cwd.len == 0) .inherit else .{ .path = cwd },
129        .stdin = .ignore,
130        .stdout = .pipe,
131        .stderr = .pipe,
132        .pgid = 0,
133    }) catch |e| return fail(a, "bash failed: {s}", .{@errorName(e)});
134
135    const pid = child.id.?;
136    var fds = [_]std.posix.pollfd{
137        .{ .fd = child.stdout.?.handle, .events = std.posix.POLL.IN, .revents = 0 },
138        .{ .fd = child.stderr.?.handle, .events = std.posix.POLL.IN, .revents = 0 },
139    };
140    var open = [_]bool{ true, true };
141
142    var acc = Acc{ .a = scratch, .on_output = ctx.on_output };
143    var cancelled = false;
144    var broken = false;
145    var oom = false;
146    var timed_out = false;
147
148    const timeout_s = args.timeout orelse default_timeout_s;
149    const start = std.Io.Clock.awake.now(platform.io);
150    const deadline = start.addDuration(.fromSeconds(@intCast(@min(timeout_s, std.math.maxInt(i64)))));
151
152    while (open[0] or open[1]) {
153        if (ctx.cancel.load(.acquire)) {
154            cancelled = true;
155            break;
156        }
157        const now = std.Io.Clock.awake.now(platform.io);
158        if (now.durationTo(deadline).nanoseconds <= 0) {
159            timed_out = true;
160            break;
161        }
162        const remaining = now.durationTo(deadline).toMilliseconds();
163        const wait_ms: i32 = @intCast(@min(100, @max(1, remaining)));
164        const ready = std.posix.poll(&fds, wait_ms) catch {
165            broken = true;
166            break;
167        };
168        if (ready == 0) continue;
169        for (0..2) |i| {
170            if (!open[i]) continue;
171            if (fds[i].revents & (std.posix.POLL.IN | std.posix.POLL.HUP | std.posix.POLL.ERR) == 0) continue;
172            var buf: [8192]u8 = undefined;
173            const n = std.posix.read(fds[i].fd, &buf) catch |e| switch (e) {
174                error.WouldBlock => continue,
175                else => {
176                    open[i] = false;
177                    continue;
178                },
179            };
180            if (n == 0) {
181                open[i] = false;
182                continue;
183            }
184            acc.append(buf[0..n]) catch {
185                oom = true;
186                break;
187            };
188        }
189        if (oom) break;
190    }
191
192    if (cancelled or timed_out or oom or broken) killGroup(pid);
193    const term = child.wait(platform.io) catch std.process.Child.Term{ .unknown = 0 };
194
195    if (oom) return fail(a, "bash failed: out of memory", .{});
196    if (broken) return fail(a, "bash failed: could not read the command's output", .{});
197
198    const code: ?u8 = switch (term) {
199        .exited => |c| c,
200        else => null,
201    };
202    const status: []const u8 = if (timed_out)
203        std.fmt.allocPrint(scratch, "killed: timed out after {d}s", .{timeout_s}) catch "killed: timed out"
204    else if (code) |c|
205        std.fmt.allocPrint(scratch, "exit code: {d}", .{c}) catch "exit code: unknown"
206    else if (cancelled)
207        "exit code: aborted"
208    else
209        "exit code: unknown";
210
211    const raw_body = acc.body(scratch) catch return fail(a, "bash failed: out of memory", .{});
212    const body = text.utf8Clean(scratch, raw_body) catch return fail(a, "bash failed: out of memory", .{});
213    var out: std.ArrayList(u8) = .empty;
214    out.appendSlice(a, body) catch return fail(a, "bash failed: out of memory", .{});
215    if (body.len > 0 and body[body.len - 1] != '\n') out.append(a, '\n') catch return fail(a, "bash failed: out of memory", .{});
216    out.appendSlice(a, status) catch return fail(a, "bash failed: out of memory", .{});
217
218    if (ctx.on_phase) |p| p.call(.snapshotting);
219    const after = snapshot.capture(scratch, ignore) catch return fail(a, "bash failed: out of memory", .{});
220    if (ctx.on_phase) |p| p.call(.running);
221    const diffs = snapshot.diffTrees(scratch, before, after) catch return fail(a, "bash failed: out of memory", .{});
222
223    var model_text: ?[]const u8 = null;
224    if (ctx.snapshot_diffs_in_context and diffs.len > 0) {
225        const patch = snapshot.diffText(scratch, diffs) catch return fail(a, "bash failed: out of memory", .{});
226        if (patch.len > 0) {
227            model_text = std.fmt.allocPrint(a, "{s}\n{s}", .{ out.items, patch }) catch
228                return fail(a, "bash failed: out of memory", .{});
229        }
230    }
231
232    return .{
233        .text = out.items,
234        .is_error = if (code) |c| c != 0 else true,
235        .diffs = diffs,
236        .body = bodyLine(a, code, timed_out, timeout_s, body),
237        .model_text = model_text,
238    };
239}