Skip to content

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

Python

fix(bash): auto-background root foreground commands after 120s (#620)

justrach8280f78cc1ac
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 01ac2b15..9f0f28c6 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -10,6 +10,20 @@ The release workflow uses a tag's section here as its release notes (a
hand-written `docs/releases/<tag>.md` wins if present), so keeping this file
current is part of cutting a release.
+## v0.0.276 (2026-08-25)
+
+- Root foreground `bash` no longer waits forever: after 120s (or `timeout`
+ ms) a still-running command is moved to the background and the model
+ gets a job id, matching grok-build. Esc still kills; the cancelled
+ result tells the model to use `run_in_background`. Subagents keep the
+ #93 120s kill. (#620)
+
+## v0.0.275 (2026-08-24)
+
+- OpenRouter requests carry app attribution (`categories: cli-agent, programming-app`).
+- TUI: Esc with a draft in the composer never kills a live turn.
+- Agent retries degenerate empty completions and keep-alive-only bodies.
+
## v0.0.274 (2026-08-23)
- Rate-limit and 5xx retries no longer dump the provider's raw error JSON
diff --git a/docs/adr/0022-foreground-bash-auto-backgrounds.md b/docs/adr/0022-foreground-bash-auto-backgrounds.md
new file mode 100644
index 00000000..efd067d7
--- /dev/null
+++ b/docs/adr/0022-foreground-bash-auto-backgrounds.md
@@ -0,0 +1,37 @@
+# 0022. Foreground bash auto-backgrounds after 120s, it is not killed
+
+Status: accepted 2026-08-25
+
+## Context
+
+[#93](https://github.com/justrach/codegraff/issues/93) gave *subagent* bash a
+120s kill because those children have no TTY. The root was left unbounded:
+"a human is watching and may want a long build." #607 added a dim
+`· bash still running ·` pulse so a long command did not *look* hung.
+
+[#620](https://github.com/justrach/codegraff/issues/620) measured the leftover:
+a durability drill sat in that pulse for 83 minutes. The model never woke.
+Esc killed the process group; the model retried the same foreground hang.
+
+[xai-org/grok-build](https://github.com/xai-org/grok-build) `BashTool` waits
+120s (`timeout` default), then *promotes* a still-running command to a
+background task (`auto_background_on_timeout`) and returns a job id plus
+partial output. A real compile keeps running. The model gets the turn back.
+
+## Decision
+
+- Root foreground `bash` waits up to 120s (or `timeout` ms, capped at 10h).
+- If the child is still running, it is moved onto the existing job registry.
+ The model receives a job id. `bash_output` / `bash_kill` / `/jobs` work as
+ they do for `run_in_background: true`. The process is not killed.
+- Subagent `bash` still *kills* at 120s (#93). Children have no job UI.
+- Esc during the foreground wait still kills the process group. The cancelled
+ result tells the model to restart with `run_in_background: true`.
+- ADR 0010 is unchanged: `bash_output(wait_ms>0)` waits for exit, not a poll.
+
+## Consequences
+
+A 20-minute compile or a forgotten server no longer bricks the turn. The
+heartbeat (#607) still fires during the 120s wait. Root bash output that
+finishes inside the wait is interleaved stdout+stderr (the job buffer),
+not the old split `[stderr]` block — same shape as `bash_output`.
diff --git a/docs/adr/README.md b/docs/adr/README.md
index dfadd37e..91dc24d8 100644
--- a/docs/adr/README.md
+++ b/docs/adr/README.md
@@ -32,6 +32,7 @@ record only when you need the evidence or the edge cases.
| [0019](0019-codedb-one-shot-over-hop-chains.md) | Advertise only `context` / `around` / `callpath` / `list_dir` / `status`; hop verbs stay callable, not on the menu. |
| [0020](0020-transcript-shows-decisions.md) | Transcript shows decisions: one interpreted tool line, collapsed infra failures, compact WORKING; raw output is `/debug` / TUI-fold. |
| [0021](0021-transcript-is-the-task-not-the-bus.md) | Transcript is the task, not the event bus: bookkeeping is silent, todos are WORKING, subagents are scouts. |
+| [0022](0022-foreground-bash-auto-backgrounds.md) | Root foreground `bash` auto-backgrounds after 120s (or `timeout` ms); it is not killed. Subagents still kill at 120s (#93). |
## When to write one
diff --git a/src/cli.zig b/src/cli.zig
index ce288d3b..810cc2ea 100644
--- a/src/cli.zig
+++ b/src/cli.zig
@@ -21,6 +21,9 @@ const harness_version = root.harness_version;
pub const changelog_text =
\\What's new
\\──────────
+ \\0.0.276
+ \\ • foreground bash auto-backgrounds after 120s instead of waiting forever (#620)
+ \\
\\0.0.275
\\ • OpenRouter requests carry app attribution (categories: cli-agent, programming-app)
\\ • TUI: Esc with a draft in the composer never kills a live turn
diff --git a/src/exec.zig b/src/exec.zig
index e4ba58ea..1c171bab 100644
--- a/src/exec.zig
+++ b/src/exec.zig
@@ -28,8 +28,6 @@ const outsideCwd = tools.outsideCwd;
const beforeFromRead = tools.beforeFromRead; // /rewind snapshot classifier (snapshots.zig)
const blankText = tools.blankText;
const rawFetch = tools.rawFetch;
-const bash_stdout_cap = tools.bash_stdout_cap;
-const bash_stderr_cap = tools.bash_stderr_cap;
const webfetch_cap = tools.webfetch_cap;
const subagent = @import("subagent.zig");
@@ -45,13 +43,9 @@ const confinedPath = approvals_mod.confinedPath;
const noSymlinkEscape = approvals_mod.noSymlinkEscape;
const jobs = @import("jobs.zig");
const runCapped = jobs.runCapped;
-const runCappedWithOptions = jobs.runCappedWithOptions;
-const exec_bash_stream = @import("exec_bash_stream.zig");
-const toolRunOptions = jobs.toolRunOptions; // #266/#198: own the child's process group
-const spawnJob = jobs.spawnJob;
const jobOutput = jobs.jobOutput;
const jobKill = jobs.jobKill;
-const shellArgv = jobs.shellArgv;
+const exec_bash = @import("exec_bash.zig");
const skills = @import("skills.zig");
const skill_docs = @import("skill_docs.zig");
const mcp_schema_gate = @import("mcp_schema_gate.zig"); // #416: refuse an MCP tool whose schema was never loaded
@@ -73,29 +67,6 @@ const vision = @import("vision.zig"); // read_file stages images like MCP image
const input_util = @import("input_util.zig");
const imagegen = @import("imagegen.zig"); // #352: the codex-gated image tool (advertising lives in schema.zig/tool_gates.zig)
-/// Wall-clock ceiling for one *subagent* bash command. Subagents run on pool
-/// threads with no TTY, so there is no Esc to kill a runaway command — without
-/// this, a codedb refusal that pushes a subagent onto an unfiltered `grep ~/`
-/// hangs the whole workflow for ~48 min (#93). The root keeps its Esc-only,
-/// no-deadline behavior (a human is watching and may want a long build).
-const subagent_bash_deadline_ms: u64 = 120 * 1000;
-
-/// #266: killing a local `ssh` proves nothing about the remote command it was
-/// running — a cancelled or timed-out ssh result carries a caveat saying so.
-fn isSshCommand(cmd: []const u8) bool {
- var it = std.mem.tokenizeAny(u8, cmd, " \t\r\n");
- const first = it.next() orelse return false;
- return std.mem.eql(u8, std.fs.path.basename(first), "ssh");
-}
-
-test "isSshCommand: bare and pathed ssh, not scp or substrings" {
- try std.testing.expect(isSshCommand("ssh host uptime"));
- try std.testing.expect(isSshCommand(" /usr/bin/ssh -T host"));
- try std.testing.expect(!isSshCommand("scp file host:"));
- try std.testing.expect(!isSshCommand("echo ssh"));
- try std.testing.expect(!isSshCommand(""));
-}
-
fn learningArgv(argv: *[10][]const u8, exe_path: []const u8, contribute: bool) usize {
var argc: usize = 0;
for ([_][]const u8{ exe_path, "--learning-privacy", if (contribute) "aggregate" else "local", "learn", "run" }) |arg| {
@@ -283,68 +254,7 @@ fn execToolInner(ctx: ToolCtx, call: ToolCall) !ToolOutput {
if (run.stdout.len == 0 and run.stderr.len == 0) try aw.writer.writeAll(if (ok) "learning run completed" else "learning run failed without output");
return .{ .text = try aw.toOwnedSlice(), .is_error = !ok };
}
- if (std.mem.eql(u8, call.name, "bash")) {
- const cmd = strField(input, "command") orelse return missingArg(gpa, "command");
- // Subagents have no stdin to prompt on; their gate is the allowlist.
- if (ctx.from_sub) if (ctx.approvals) |ap| if (!ap.allowed(ctx.io, cmd)) return .{
- .text = try gpa.dupe(u8, "command not pre-approved — subagents may only run user-approved or read-only commands, with no chaining/pipes/redirection. Use read_file/edit_file/write_file, or report back what you need run."),
- .is_error = true,
- };
- const bg = tools.json_args.flag(input, "run_in_background");
- if (bg) {
- const job = spawnJob(gpa, io, cmd) catch |err| return .{
- // #122: backgrounding costs MORE fds (pipes + pump task), so the
- // generic "run it in the foreground" advice is right for every
- // error except the fd-quota ones — special-case those. #253: for
- // SYSTEM-wide exhaustion neither foregrounding nor ulimit helps.
- .text = if (err == error.ProcessFdQuotaExceeded)
- try gpa.dupe(u8, "could not start background job (ProcessFdQuotaExceeded) — graff hit its open-file limit. Wait for running jobs/tools to finish, then retry with less parallel fan-out; if it recurs, raise the limit (`ulimit -n 4096`) before starting graff.")
- else if (err == error.SystemFdQuotaExceeded)
- try gpa.dupe(u8, "could not start background job (SystemFdQuotaExceeded) — the SYSTEM-wide open-file table is full, so neither foregrounding nor `ulimit` helps. Wait for other processes to release files (or close some applications), then retry.")
- else
- try std.fmt.allocPrint(gpa, "could not start background job ({t}) — run it in the foreground instead", .{err}),
- .is_error = true,
- };
- return .{ .text = try std.fmt.allocPrint(gpa, "[job {d} started: {s}]\nIt keeps running across turns. You are notified on exit — do not poll. bash_output(id {d}, wait_ms>0) blocks until it exits; omit wait_ms for a snapshot. bash_kill stops it.{s}", .{
- job.id,
- job.cmd,
- job.id,
- if (isSshCommand(cmd)) " Killing the local SSH job cannot prove a detached remote process stopped; verify the remote host." else "",
- }) };
- }
- const sh = shellArgv(cmd);
- const deadline: u64 = if (ctx.from_sub) subagent_bash_deadline_ms else 0;
- var opts = toolRunOptions(ctx.agent_cwd);
- var live = exec_bash_stream.Ctx{ .io = io };
- exec_bash_stream.attach(&opts, !ctx.from_sub, &live);
- const run = try runCappedWithOptions(gpa, io, &sh, bash_stdout_cap, bash_stderr_cap, deadline, opts);
- defer gpa.free(run.stdout);
- defer gpa.free(run.stderr);
-
- const exit_code: ?u8 = switch (run.term) {
- .exited => |code| code,
- else => null,
- };
- var aw: Io.Writer.Allocating = .init(gpa);
- errdefer aw.deinit();
- const w = &aw.writer;
- if (run.stdout.len > 0) try w.writeAll(run.stdout);
- if (run.stdout_truncated) try w.print("\n[stdout truncated at {d} KB]", .{bash_stdout_cap / 1024});
- if (run.stderr.len > 0) try w.print("\n[stderr]\n{s}", .{run.stderr});
- if (run.stderr_truncated) try w.print("\n[stderr truncated at {d} KB]", .{bash_stderr_cap / 1024});
- if (run.cancelled) {
- try w.writeAll("\n[cancelled by user; local process group killed]");
- } else if (run.timed_out) {
- try w.print("\n[timed out after {d}s and was killed — too long for a subagent. Don't retry as-is: scope it to specific paths or globs instead of scanning the whole directory, or report back what you need run.]", .{subagent_bash_deadline_ms / 1000});
- } else if (exit_code) |code| {
- if (code != 0) try w.print("\n[exit code {d}]", .{code});
- } else try w.writeAll("\n[terminated abnormally]");
- if ((run.cancelled or run.timed_out) and isSshCommand(cmd)) {
- try w.writeAll("\n[ssh note: the local SSH client was killed, but a detached or disconnect-resistant remote process may survive; verify it on the remote host]");
- }
- if (run.stdout.len == 0 and run.stderr.len == 0 and exit_code == 0) try w.writeAll("(no output)");
- return .{ .text = try aw.toOwnedSlice(), .is_error = exit_code == null or exit_code.? != 0, .cancelled = run.cancelled };
- }
+ if (std.mem.eql(u8, call.name, "bash")) return exec_bash.exec(ctx, call);
if (std.mem.eql(u8, call.name, "bash_output")) {
const id = intField(input, "id") orelse return missingArg(gpa, "id");
const wait_ms = intField(input, "wait_ms") orelse 0;
@@ -530,7 +440,7 @@ test "internal learning respects the parent privacy ceiling" {
}
test { // main.zig is at the 600-line cap; exec.zig is these modules' importer, so the compiled-in references live here (the reach check diffs the test binary, not which file holds the line)
- _ = exec_bash_stream;
+ _ = exec_bash;
_ = @import("codedbpro_report.zig");
_ = @import("tool_balance.zig");
_ = @import("codedb_exec.zig");
diff --git a/src/exec_bash.zig b/src/exec_bash.zig
new file mode 100644
index 00000000..50486731
--- /dev/null
+++ b/src/exec_bash.zig
@@ -0,0 +1,224 @@
+//! Root and subagent `bash` dispatch. Split out of exec.zig so the grok-build
+//! auto-background path (#620) has room without growing exec.zig.
+//!
+//! Root foreground: spawn a job, wait up to 120s (or `timeout` ms), then
+//! promote rather than kill — the process keeps running and the model gets a
+//! job id. Subagents stay on the #93 kill-at-120s path (no TTY, no /jobs UI).
+
+const std = @import("std");
+const Io = std.Io;
+const Allocator = std.mem.Allocator;
+const Value = std.json.Value;
+
+const tools = @import("tools.zig");
+const ToolCtx = tools.ToolCtx;
+const ToolOutput = tools.ToolOutput;
+const strField = tools.strField;
+const intField = tools.intField;
+const missingArg = tools.missingArg;
+const bash_stdout_cap = tools.bash_stdout_cap;
+const bash_stderr_cap = tools.bash_stderr_cap;
+
+const jobs = @import("jobs.zig");
+const job_wait = @import("job_wait.zig");
+const exec_bash_stream = @import("exec_bash_stream.zig");
+
+/// grok-build's default foreground wait. After this, root bash is moved to
+/// the job registry instead of being killed (xai-org/grok-build BashTool).
+pub const root_wait_ms: u64 = 120 * 1000;
+
+/// Wall-clock ceiling for one *subagent* bash command. Subagents run on pool
+/// threads with no TTY, so there is no Esc to kill a runaway command — without
+/// this, a codedb refusal that pushes a subagent onto an unfiltered `grep ~/`
+/// hangs the whole workflow for ~48 min (#93).
+pub const subagent_deadline_ms: u64 = 120 * 1000;
+
+const cancel_hint =
+ "If this was a server, drill, or anything that should outlive one turn, restart with run_in_background: true — do not wait in the foreground again.";
+
+/// #266: killing a local `ssh` proves nothing about the remote command it was
+/// running — a cancelled or timed-out ssh result carries a caveat saying so.
+fn isSshCommand(cmd: []const u8) bool {
+ var it = std.mem.tokenizeAny(u8, cmd, " \t\r\n");
+ const first = it.next() orelse return false;
+ return std.mem.eql(u8, std.fs.path.basename(first), "ssh");
+}
+
+test "isSshCommand: bare and pathed ssh, not scp or substrings" {
+ try std.testing.expect(isSshCommand("ssh host uptime"));
+ try std.testing.expect(isSshCommand(" /usr/bin/ssh -T host"));
+ try std.testing.expect(!isSshCommand("scp file host:"));
+ try std.testing.expect(!isSshCommand("echo ssh"));
+ try std.testing.expect(!isSshCommand(""));
+}
+
+fn spawnFailText(gpa: Allocator, err: anyerror) ![]u8 {
+ // #122: backgrounding costs MORE fds (pipes + pump task), so the generic
+ // "run it in the foreground" advice is right for every error except the
+ // fd-quota ones. #253: SYSTEM-wide exhaustion is not a ulimit problem.
+ return if (err == error.ProcessFdQuotaExceeded)
+ try gpa.dupe(u8, "could not start background job (ProcessFdQuotaExceeded) — graff hit its open-file limit. Wait for running jobs/tools to finish, then retry with less parallel fan-out; if it recurs, raise the limit (`ulimit -n 4096`) before starting graff.")
+ else if (err == error.SystemFdQuotaExceeded)
+ try gpa.dupe(u8, "could not start background job (SystemFdQuotaExceeded) — the SYSTEM-wide open-file table is full, so neither foregrounding nor `ulimit` helps. Wait for other processes to release files (or close some applications), then retry.")
+ else
+ try std.fmt.allocPrint(gpa, "could not start background job ({t}) — run it in the foreground instead", .{err});
+}
+
+fn startedText(gpa: Allocator, id: u32, cmd: []const u8, ssh: bool, auto_bg: bool, wait_s: u64, partial: []const u8) ![]u8 {
+ var aw: Io.Writer.Allocating = .init(gpa);
+ errdefer aw.deinit();
+ const w = &aw.writer;
+ try w.print("[job {d} started: {s}]\n", .{ id, cmd });
+ if (auto_bg) {
+ try w.print("Command exceeded the {d}s foreground wait and was automatically moved to the background. Process is still running. ", .{wait_s});
+ }
+ try w.print("You are notified on exit — do not poll. bash_output(id {d}, wait_ms>0) blocks until it exits; omit wait_ms for a snapshot. bash_kill stops it.", .{id});
+ if (ssh) try w.writeAll(" Killing the local SSH job cannot prove a detached remote process stopped; verify the remote host.");
+ if (partial.len > 0) {
+ try w.writeAll("\n");
+ try w.writeAll(partial);
+ }
+ return aw.toOwnedSlice();
+}
+
+fn rootWaitMs(input: Value) u64 {
+ const t = intField(input, "timeout") orelse return root_wait_ms;
+ if (t <= 0) return root_wait_ms;
+ return @min(@as(u64, @intCast(t)), job_wait.wait_cap_ms);
+}
+
+test "rootWaitMs: omitted/zero use 120s; positive values clamp to the 10h cap" {
+ const empty = try std.json.parseFromSlice(Value, std.testing.allocator, "{}", .{});
+ defer empty.deinit();
+ try std.testing.expectEqual(root_wait_ms, rootWaitMs(empty.value));
+ const zero = try std.json.parseFromSlice(Value, std.testing.allocator, "{\"timeout\":0}", .{});
+ defer zero.deinit();
+ try std.testing.expectEqual(root_wait_ms, rootWaitMs(zero.value));
+ const custom = try std.json.parseFromSlice(Value, std.testing.allocator, "{\"timeout\":5000}", .{});
+ defer custom.deinit();
+ try std.testing.expectEqual(@as(u64, 5_000), rootWaitMs(custom.value));
+ const huge = try std.json.parseFromSlice(Value, std.testing.allocator, "{\"timeout\":999999999}", .{});
+ defer huge.deinit();
+ try std.testing.expectEqual(job_wait.wait_cap_ms, rootWaitMs(huge.value));
+}
+
+fn formatJobDone(gpa: Allocator, cmd: []const u8, wait: jobs.FgDone) !ToolOutput {
+ defer gpa.free(wait.output);
+ var aw: Io.Writer.Allocating = .init(gpa);
+ errdefer aw.deinit();
+ const w = &aw.writer;
+ if (wait.output.len > 0) try w.writeAll(wait.output);
+ if (wait.dropped) try w.print("\n[oldest unread output was dropped at the {d} KB cap]", .{jobs.job_unread_cap / 1024});
+ if (wait.killed) {
+ try w.writeAll("\n[cancelled by user; local process group killed]\n");
+ try w.writeAll(cancel_hint);
+ if (isSshCommand(cmd)) try w.writeAll("\n[ssh note: the local SSH client was killed, but a detached or disconnect-resistant remote process may survive; verify it on the remote host]");
+ if (wait.output.len == 0) try w.writeAll("\n(no output)");
+ return .{ .text = try aw.toOwnedSlice(), .is_error = true, .cancelled = true };
+ }
+ if (wait.exit_code) |code| {
+ if (code != 0) try w.print("\n[exit code {d}]", .{code});
+ } else try w.writeAll("\n[terminated abnormally]");
+ if (wait.output.len == 0 and (wait.exit_code orelse 1) == 0) try w.writeAll("(no output)");
+ const code = wait.exit_code;
+ return .{ .text = try aw.toOwnedSlice(), .is_error = code == null or code.? != 0 };
+}
+
+fn formatCancelled(gpa: Allocator, cmd: []const u8, wait: jobs.FgPartial) !ToolOutput {
+ defer gpa.free(wait.output);
+ var aw: Io.Writer.Allocating = .init(gpa);
+ errdefer aw.deinit();
+ const w = &aw.writer;
+ if (wait.output.len > 0) {
+ try w.writeAll(wait.output);
+ try w.writeAll("\n");
+ }
+ try w.writeAll("[cancelled by user; local process group killed]\n");
+ try w.writeAll(cancel_hint);
+ if (isSshCommand(cmd)) try w.writeAll("\n[ssh note: the local SSH client was killed, but a detached or disconnect-resistant remote process may survive; verify it on the remote host]");
+ return .{ .text = try aw.toOwnedSlice(), .is_error = true, .cancelled = true };
+}
+
+test "cancel hint tells the model to restart with run_in_background" {
+ try std.testing.expect(std.mem.indexOf(u8, cancel_hint, "run_in_background") != null);
+}
+
+fn formatCapped(gpa: Allocator, cmd: []const u8, run: jobs.CappedRun) !ToolOutput {
+ const exit_code: ?u8 = switch (run.term) {
+ .exited => |code| code,
+ else => null,
+ };
+ var aw: Io.Writer.Allocating = .init(gpa);
+ errdefer aw.deinit();
+ const w = &aw.writer;
+ if (run.stdout.len > 0) try w.writeAll(run.stdout);
+ if (run.stdout_truncated) try w.print("\n[stdout truncated at {d} KB]", .{bash_stdout_cap / 1024});
+ if (run.stderr.len > 0) try w.print("\n[stderr]\n{s}", .{run.stderr});
+ if (run.stderr_truncated) try w.print("\n[stderr truncated at {d} KB]", .{bash_stderr_cap / 1024});
+ if (run.cancelled) {
+ try w.writeAll("\n[cancelled by user; local process group killed]\n");
+ try w.writeAll(cancel_hint);
+ } else if (run.timed_out) {
+ try w.print("\n[timed out after {d}s and was killed — too long for a subagent. Don't retry as-is: scope it to specific paths or globs instead of scanning the whole directory, or report back what you need run.]", .{subagent_deadline_ms / 1000});
+ } else if (exit_code) |code| {
+ if (code != 0) try w.print("\n[exit code {d}]", .{code});
+ } else try w.writeAll("\n[terminated abnormally]");
+ if ((run.cancelled or run.timed_out) and isSshCommand(cmd)) {
+ try w.writeAll("\n[ssh note: the local SSH client was killed, but a detached or disconnect-resistant remote process may survive; verify it on the remote host]");
+ }
+ if (run.stdout.len == 0 and run.stderr.len == 0 and exit_code == 0) try w.writeAll("(no output)");
+ return .{ .text = try aw.toOwnedSlice(), .is_error = exit_code == null or exit_code.? != 0, .cancelled = run.cancelled };
+}
+
+pub fn exec(ctx: ToolCtx, call: tools.ToolCall) !ToolOutput {
+ const gpa = ctx.gpa;
+ const io = ctx.io;
+ const input = call.input;
+ const cmd = strField(input, "command") orelse return missingArg(gpa, "command");
+ // Subagents have no stdin to prompt on; their gate is the allowlist.
+ if (ctx.from_sub) if (ctx.approvals) |ap| if (!ap.allowed(ctx.io, cmd)) return .{
+ .text = try gpa.dupe(u8, "command not pre-approved — subagents may only run user-approved or read-only commands, with no chaining/pipes/redirection. Use read_file/edit_file/write_file, or report back what you need run."),
+ .is_error = true,
+ };
+ const ssh = isSshCommand(cmd);
+ const bg = tools.json_args.flag(input, "run_in_background");
+ if (bg or !ctx.from_sub) {
+ var live = exec_bash_stream.Ctx{ .io = io };
+ const job = jobs.spawnJobOpts(gpa, io, cmd, .{
+ .cwd = ctx.agent_cwd,
+ .stream = if (!ctx.from_sub and !bg) exec_bash_stream.emit else null,
+ .stream_ctx = if (!ctx.from_sub and !bg) &live else null,
+ .quiet = !bg, // foreground wait is not a /jobs event until auto-bg
+ }) catch |err| return .{ .text = try spawnFailText(gpa, err), .is_error = true };
+ if (bg) {
+ return .{ .text = try startedText(gpa, job.id, job.cmd, ssh, false, 0, "") };
+ }
+ const wait_ms = rootWaitMs(input);
+ const waited = jobs.waitForeground(gpa, io, job.id, wait_ms) catch |err| return .{
+ .text = try std.fmt.allocPrint(gpa, "could not wait on job {d} ({t})", .{ job.id, err }),
+ .is_error = true,
+ };
+ return switch (waited) {
+ .done => |d| blk: {
+ defer jobs.reapFinished(gpa, io, job.id);
+ break :blk try formatJobDone(gpa, cmd, d);
+ },
+ .running => |r| blk: {
+ defer gpa.free(r.output);
+ break :blk .{ .text = try startedText(gpa, r.id, cmd, ssh, true, wait_ms / 1000, r.output) };
+ },
+ .cancelled => |c| blk: {
+ defer jobs.reapFinished(gpa, io, c.id);
+ break :blk try formatCancelled(gpa, cmd, c);
+ },
+ };
+ }
+ const sh = jobs.shellArgv(cmd);
+ var opts = jobs.toolRunOptions(ctx.agent_cwd);
+ var live = exec_bash_stream.Ctx{ .io = io };
+ exec_bash_stream.attach(&opts, false, &live); // subagents stay quiet (#93)
+ const run = try jobs.runCappedWithOptions(gpa, io, &sh, bash_stdout_cap, bash_stderr_cap, subagent_deadline_ms, opts);
+ defer gpa.free(run.stdout);
+ defer gpa.free(run.stderr);
+ return formatCapped(gpa, cmd, run);
+}
diff --git a/src/jobs.zig b/src/jobs.zig
index b1973ff8..0a4c9e91 100644
--- a/src/jobs.zig
+++ b/src/jobs.zig
@@ -1,9 +1,5 @@
-//! Subprocess execution: the capped-output runner (runCapped), git-worktree
-//! management (`graff worktree` add/merge/remove + the -w auto-checkpoint
-//! commits), and the background bash-job pool (spawn/output/kill/reap). Split
-//! out of main.zig (600-line goal). Back-imports main for ToolOutput (the job
-//! tools' result shape). main re-exports runCapped (hooks.zig back-imports it)
-//! and aliases the worktree + job entry points back.
+//! Capped runner, worktree commands, and the background bash-job pool.
+//! Split out of main.zig (600-line goal). Back-imports main for ToolOutput.
const std = @import("std");
const builtin = @import("builtin");
@@ -19,7 +15,7 @@ pub const CappedRun = process_runner.CappedRun;
pub const CappedRunOptions = process_runner.CappedRunOptions;
pub const runCapped = process_runner.runCapped;
pub const runCappedWithOptions = process_runner.runCappedWithOptions;
-const ranOk = process_runner.ranOk;
+pub const ranOk = process_runner.ranOk;
/// Commit-message trailer that credits the harness assist. The commit AUTHOR
/// stays the user's own git identity (their GitHub account) — graff never
@@ -219,25 +215,27 @@ pub fn worktreeCommand(gpa: Allocator, io: Io, arena: Allocator, args: []const [
try out.print("unknown worktree command '{s}' — use: graff worktree list | merge <name> | remove <name> | prune [older-than <days>]\n", .{action});
}
-/// One background bash job. Pump drains pipes; session-global (survives Esc).
-const Job = struct {
+const Job = struct { // session-global; pump drains pipes; survives Esc
id: u32,
- cmd: []u8, // gpa-owned, for /jobs display
+ cmd: []u8,
child: std.process.Child,
- buf: std.ArrayList(u8) = .empty, // interleaved stdout+stderr
- cursor: usize = 0, // start of unread output
- exit_code: ?u8 = null, // meaningful once done
+ buf: std.ArrayList(u8) = .empty,
+ cursor: usize = 0,
+ exit_code: ?u8 = null,
done: bool = false,
- killed: bool = false, // ended via bash_kill rather than naturally
- kill_requested: bool = false, // pump notices within one 200ms tick
- dropped: bool = false, // unread output overflowed job_unread_cap
- future: Io.Future(void) = undefined, // the pump; awaited only by jobsReap
+ killed: bool = false,
+ kill_requested: bool = false,
+ dropped: bool = false,
+ quiet: bool = false, // skip job_notify until auto-bg (#620)
+ future: Io.Future(void) = undefined,
+ stream: ?process_runner.StreamFn = null,
+ stream_ctx: ?*anyopaque = null,
};
-const job_unread_cap = 256 * 1024;
+pub const job_unread_cap = 256 * 1024;
const job_wait = @import("job_wait.zig");
const job_notify = @import("job_notify.zig");
-const tool_pulse = @import("tool_pulse.zig");
+const tool_pulse = @import("tool_pulse.zig"); // silence heartbeat during waitForeground
/// POSIX process groups; windows/wasi have none, so the group kills below and
/// the job's own pgid are compiled out there (#198).
@@ -261,9 +259,10 @@ pub var g_jobs: Jobs = .{};
/// dropping the oldest *unread* bytes past the cap (a chatty server must not
/// grow memory unboundedly between bash_output polls). Caller holds the mutex.
fn jobDrain(job: *Job, gpa: Allocator, readers: []const *Io.Reader) void {
- for (readers) |r| {
+ for (readers, 0..) |r, i| {
const b = r.buffered();
if (b.len == 0) continue;
+ if (job.stream) |emit| emit(job.stream_ctx, @intCast(i), b);
job.buf.appendSlice(gpa, b) catch {};
r.toss(b.len);
}
@@ -319,33 +318,38 @@ fn jobPump(job: *Job, gpa: Allocator, io: Io) void {
job.done = true;
const id = job.id;
const cmd = job.cmd;
+ const quiet = job.quiet;
g_jobs.mutex.unlock(io);
- job_notify.record(io, id, code, killed, cmd);
+ if (!quiet) job_notify.record(io, id, code, killed, cmd);
}
-/// Argv that runs a shell command string: `/bin/sh -c` on POSIX, `cmd.exe /c`
-/// on Windows (which has no /bin/sh). The bash tool routes through this so the
-/// model's shell commands run on every platform.
-pub fn shellArgv(cmd: []const u8) [3][]const u8 {
+pub fn shellArgv(cmd: []const u8) [3][]const u8 { // /bin/sh -c, or cmd.exe /c on Windows
return if (builtin.os.tag == .windows)
.{ "cmd.exe", "/c", cmd }
else
.{ "/bin/sh", "-c", cmd };
}
-/// Spawn a background job and its pump. Uses io.concurrent (NOT io.async,
-/// which may run inline and block this tool forever on a long-lived child);
-/// no spare concurrency cleans up and surfaces the error to the model.
+pub const SpawnOpts = struct {
+ cwd: ?[]const u8 = null,
+ stream: ?process_runner.StreamFn = null,
+ stream_ctx: ?*anyopaque = null,
+ quiet: bool = false,
+};
+
pub fn spawnJob(gpa: Allocator, io: Io, cmd: []const u8) !*Job {
+ return spawnJobOpts(gpa, io, cmd, .{});
+}
+
+pub fn spawnJobOpts(gpa: Allocator, io: Io, cmd: []const u8, opts: SpawnOpts) !*Job {
const argv = shellArgv(cmd);
var child = try std.process.spawn(io, .{
.argv = &argv,
+ .cwd = if (opts.cwd) |path| .{ .path = path } else .inherit,
.stdin = .ignore,
.stdout = .pipe,
.stderr = .pipe,
- // #198: the job leads its own process group, so bash_kill / jobsReap
- // reach everything it spawned, not just the shell.
- .pgid = if (posix_groups) 0 else null,
+ .pgid = if (posix_groups) 0 else null, // #198: bash_kill reaches grandchildren
});
const cmd_copy = gpa.dupe(u8, cmd) catch |e| {
child.kill(io);
@@ -356,7 +360,7 @@ pub fn spawnJob(gpa: Allocator, io: Io, cmd: []const u8) !*Job {
child.kill(io);
return e;
};
- job.* = .{ .id = 0, .cmd = cmd_copy, .child = child };
+ job.* = .{ .id = 0, .cmd = cmd_copy, .child = child, .stream = opts.stream, .stream_ctx = opts.stream_ctx, .quiet = opts.quiet };
g_jobs.mutex.lockUncancelable(io);
job.id = g_jobs.next_id;
g_jobs.next_id += 1;
@@ -476,8 +480,102 @@ pub fn jobKill(gpa: Allocator, io: Io, id: u32) !ToolOutput {
return .{ .text = try std.fmt.allocPrint(gpa, "job {d}: kill requested (still shutting down — check bash_output)", .{id}) };
}
-/// Session end: kill every job, await the pumps (sole owner of the futures),
-/// free everything. Runs from main's defer, after the REPL/one-shot returns.
+/// Outcome of a root foreground wait (#620 / grok-build auto-background).
+pub const FgDone = struct { exit_code: ?u8, killed: bool, output: []u8, dropped: bool };
+pub const FgPartial = struct { id: u32, output: []u8, dropped: bool };
+pub const FgWait = union(enum) { done: FgDone, running: FgPartial, cancelled: FgPartial };
+
+fn takeUnread(gpa: Allocator, job: *Job) error{OutOfMemory}!struct { []u8, bool } {
+ job.stream = null;
+ job.stream_ctx = null;
+ const out = try gpa.dupe(u8, job.buf.items[job.cursor..]);
+ job.cursor = job.buf.items.len;
+ const dropped = job.dropped;
+ job.dropped = false;
+ return .{ out, dropped };
+}
+
+fn freeJob(gpa: Allocator, io: Io, job: *Job) void {
+ job.future.await(io);
+ job.buf.deinit(gpa);
+ gpa.free(job.cmd);
+ gpa.destroy(job);
+}
+
+pub fn reapFinished(gpa: Allocator, io: Io, id: u32) void {
+ g_jobs.mutex.lockUncancelable(io);
+ var found: ?*Job = null;
+ for (g_jobs.list.items, 0..) |j, i| {
+ if (j.id == id) {
+ if (j.done) found = g_jobs.list.swapRemove(i);
+ break;
+ }
+ }
+ if (g_jobs.list.items.len == 0) {
+ g_jobs.list.deinit(gpa);
+ g_jobs.list = .empty;
+ }
+ g_jobs.mutex.unlock(io);
+ if (found) |job| freeJob(gpa, io, job);
+}
+
+pub fn waitForeground(gpa: Allocator, io: Io, id: u32, wait_ms: u64) !FgWait {
+ const deadline = if (wait_ms == 0) job_wait.wait_cap_ms else @min(wait_ms, job_wait.wait_cap_ms);
+ var waited: u64 = 0;
+ var still = tool_pulse.Pulse{};
+ while (true) {
+ g_jobs.mutex.lockUncancelable(io);
+ const job = g_jobs.find(id) orelse {
+ g_jobs.mutex.unlock(io);
+ return error.NoSuchJob;
+ };
+ if (job.done) {
+ const pair = takeUnread(gpa, job) catch {
+ g_jobs.mutex.unlock(io);
+ return error.OutOfMemory;
+ };
+ const result: FgWait = .{ .done = .{ .exit_code = job.exit_code, .killed = job.killed, .output = pair[0], .dropped = pair[1] } };
+ g_jobs.mutex.unlock(io);
+ return result;
+ }
+ if (waited >= deadline) {
+ const pair = takeUnread(gpa, job) catch {
+ g_jobs.mutex.unlock(io);
+ return error.OutOfMemory;
+ };
+ job.quiet = false; // completion should now notify (#620)
+ const result: FgWait = .{ .running = .{ .id = id, .output = pair[0], .dropped = pair[1] } };
+ g_jobs.mutex.unlock(io);
+ return result;
+ }
+ g_jobs.mutex.unlock(io);
+ if (Agent.esc_cancel.load(.acquire)) {
+ _ = jobKill(gpa, io, id) catch {};
+ g_jobs.mutex.lockUncancelable(io);
+ if (g_jobs.find(id)) |j| {
+ const pair = takeUnread(gpa, j) catch {
+ g_jobs.mutex.unlock(io);
+ return error.OutOfMemory;
+ };
+ g_jobs.mutex.unlock(io);
+ return .{ .cancelled = .{ .id = id, .output = pair[0], .dropped = pair[1] } };
+ }
+ g_jobs.mutex.unlock(io);
+ return .{ .cancelled = .{ .id = id, .output = try gpa.dupe(u8, ""), .dropped = false } };
+ }
+ io.sleep(.fromMilliseconds(100), .awake) catch {
+ waited = deadline;
+ continue;
+ };
+ waited += 100;
+ if (still.due(waited)) {
+ var ebuf: [16]u8 = undefined;
+ tool_pulse.emitNotice(io, "· bash still running · {s}", .{tool_pulse.formatElapsed(&ebuf, waited)});
+ }
+ }
+}
+
+/// Session end: kill every job, await pumps, free. From main's defer.
pub fn jobsReap(gpa: Allocator, io: Io) void {
g_jobs.mutex.lockUncancelable(io);
const jobs = g_jobs.list.toOwnedSlice(gpa) catch {
@@ -486,12 +584,7 @@ pub fn jobsReap(gpa: Allocator, io: Io) void {
};
for (jobs) |job| job.kill_requested = true;
g_jobs.mutex.unlock(io);
- for (jobs) |job| {
- job.future.await(io);
- job.buf.deinit(gpa);
- gpa.free(job.cmd);
- gpa.destroy(job);
- }
+ for (jobs) |job| freeJob(gpa, io, job);
gpa.free(jobs);
g_jobs.list.deinit(gpa);
}
@@ -500,89 +593,5 @@ test { // split-out modules: unreferenced, their tests silently never run
_ = worktree_prune;
_ = @import("worktree_lease.zig");
_ = .{ job_wait, job_notify };
-}
-
-test "foreground tool subprocesses own their process group (#266, #198)" {
- const inherited = toolRunOptions(null);
- try std.testing.expect(inherited.kill_process_tree);
- try std.testing.expect(std.meta.activeTag(inherited.cwd) == .inherit);
- const pinned = toolRunOptions("/tmp/graff-worktree");
- try std.testing.expect(pinned.kill_process_tree);
- try std.testing.expectEqualStrings("/tmp/graff-worktree", pinned.cwd.path);
-}
-
-test "killing a background job takes its grandchildren with it (#198)" {
- if (builtin.os.tag == .windows or builtin.os.tag == .wasi) return error.SkipZigTest;
- g_jobs = .{};
- const gpa = std.testing.allocator;
- const io = std.testing.io;
- var tmp = std.testing.tmpDir(.{});
- defer tmp.cleanup();
- // The job inherits this process's cwd, the one tmpDir resolved .zig-cache
- // against, so the marker path is reachable from the shell. The grandchild
- // detaches from the job's pipes or the pump never sees EOF; `sh` execs the
- // trailing sleep, so a bare child kill orphans the marker subshell.
- const cmd = try std.fmt.allocPrint(gpa, "(sleep 0.8; printf survived > .zig-cache/tmp/{s}/marker) >/dev/null 2>&1 & sleep 30", .{&tmp.sub_path});
- defer gpa.free(cmd);
- const id = (try spawnJob(gpa, io, cmd)).id;
- defer jobsReap(gpa, io);
- const killed = try jobKill(gpa, io, id);
- gpa.free(killed.text);
- io.sleep(.fromMilliseconds(1_200), .awake) catch {};
- try std.testing.expectError(error.FileNotFound, tmp.dir.openFile(io, "marker", .{}));
-}
-
-test "isolated capped runs clean descendants after timeout and normal exit" {
- if (builtin.os.tag == .windows or builtin.os.tag == .wasi) return error.SkipZigTest;
- const io = std.testing.io;
- var tmp = std.testing.tmpDir(.{});
- defer tmp.cleanup();
-
- const timed = try runCappedWithOptions(
- std.testing.allocator,
- io,
- &.{ "/bin/sh", "-c", "(sleep 0.8; printf survived > timeout-marker) >/dev/null 2>&1 & sleep 30" },
- 1024,
- 1024,
- 50,
- .{ .cwd = .{ .dir = tmp.dir }, .kill_process_tree = true },
- );
- defer {
- std.testing.allocator.free(timed.stdout);
- std.testing.allocator.free(timed.stderr);
- }
- try std.testing.expect(timed.timed_out);
-
- const completed = try runCappedWithOptions(
- std.testing.allocator,
- io,
- &.{ "/bin/sh", "-c", "(sleep 0.8; printf survived > completed-marker) >/dev/null 2>&1 & exit 0" },
- 1024,
- 1024,
- 2_000,
- .{ .cwd = .{ .dir = tmp.dir }, .kill_process_tree = true },
- );
- defer {
- std.testing.allocator.free(completed.stdout);
- std.testing.allocator.free(completed.stderr);
- }
- try std.testing.expect(ranOk(completed));
- io.sleep(.fromMilliseconds(1_000), .awake) catch {};
- try std.testing.expectError(error.FileNotFound, tmp.dir.openFile(io, "timeout-marker", .{}));
- try std.testing.expectError(error.FileNotFound, tmp.dir.openFile(io, "completed-marker", .{}));
-}
-
-test "bash_output wait_ms>0 waits for exit, not the next byte (ADR 0010)" {
- if (builtin.os.tag == .windows or builtin.os.tag == .wasi) return error.SkipZigTest;
- g_jobs = .{};
- const gpa = std.testing.allocator;
- const io = std.testing.io;
- const id = (try spawnJob(gpa, io, "printf start; sleep 0.15; printf done; exit 7")).id;
- defer jobsReap(gpa, io);
- const snap = try jobOutput(gpa, io, id, 0);
- defer gpa.free(snap.text);
- const done = try jobOutput(gpa, io, id, 30_000);
- defer gpa.free(done.text);
- const text = if (std.mem.indexOf(u8, done.text, "exited with code 7") != null) done.text else snap.text;
- try std.testing.expect(std.mem.indexOf(u8, text, "exited with code 7") != null);
+ _ = @import("jobs_tests.zig");
}
diff --git a/src/jobs_tests.zig b/src/jobs_tests.zig
new file mode 100644
index 00000000..e42de30a
--- /dev/null
+++ b/src/jobs_tests.zig
@@ -0,0 +1,130 @@
+//! Job-pool tests. Split out of jobs.zig so waitForeground (#620) fits under
+//! the 600-line ceiling. Imported from jobs.zig's `test {}` so they stay in
+//! the suite.
+
+const std = @import("std");
+const builtin = @import("builtin");
+const jobs = @import("jobs.zig");
+
+test "foreground tool subprocesses own their process group (#266, #198)" {
+ const inherited = jobs.toolRunOptions(null);
+ try std.testing.expect(inherited.kill_process_tree);
+ try std.testing.expect(std.meta.activeTag(inherited.cwd) == .inherit);
+ const pinned = jobs.toolRunOptions("/tmp/graff-worktree");
+ try std.testing.expect(pinned.kill_process_tree);
+ try std.testing.expectEqualStrings("/tmp/graff-worktree", pinned.cwd.path);
+}
+
+test "killing a background job takes its grandchildren with it (#198)" {
+ if (builtin.os.tag == .windows or builtin.os.tag == .wasi) return error.SkipZigTest;
+ jobs.g_jobs = .{};
+ const gpa = std.testing.allocator;
+ const io = std.testing.io;
+ var tmp = std.testing.tmpDir(.{});
+ defer tmp.cleanup();
+ // The job inherits this process's cwd, the one tmpDir resolved .zig-cache
+ // against, so the marker path is reachable from the shell. The grandchild
+ // detaches from the job's pipes or the pump never sees EOF; `sh` execs the
+ // trailing sleep, so a bare child kill orphans the marker subshell.
+ const cmd = try std.fmt.allocPrint(gpa, "(sleep 0.8; printf survived > .zig-cache/tmp/{s}/marker) >/dev/null 2>&1 & sleep 30", .{&tmp.sub_path});
+ defer gpa.free(cmd);
+ const id = (try jobs.spawnJob(gpa, io, cmd)).id;
+ defer jobs.jobsReap(gpa, io);
+ const killed = try jobs.jobKill(gpa, io, id);
+ gpa.free(killed.text);
+ io.sleep(.fromMilliseconds(1_200), .awake) catch {};
+ try std.testing.expectError(error.FileNotFound, tmp.dir.openFile(io, "marker", .{}));
+}
+
+test "isolated capped runs clean descendants after timeout and normal exit" {
+ if (builtin.os.tag == .windows or builtin.os.tag == .wasi) return error.SkipZigTest;
+ const io = std.testing.io;
+ var tmp = std.testing.tmpDir(.{});
+ defer tmp.cleanup();
+
+ const timed = try jobs.runCappedWithOptions(
+ std.testing.allocator,
+ io,
+ &.{ "/bin/sh", "-c", "(sleep 0.8; printf survived > timeout-marker) >/dev/null 2>&1 & sleep 30" },
+ 1024,
+ 1024,
+ 50,
+ .{ .cwd = .{ .dir = tmp.dir }, .kill_process_tree = true },
+ );
+ defer {
+ std.testing.allocator.free(timed.stdout);
+ std.testing.allocator.free(timed.stderr);
+ }
+ try std.testing.expect(timed.timed_out);
+
+ const completed = try jobs.runCappedWithOptions(
+ std.testing.allocator,
+ io,
+ &.{ "/bin/sh", "-c", "(sleep 0.8; printf survived > completed-marker) >/dev/null 2>&1 & exit 0" },
+ 1024,
+ 1024,
+ 2_000,
+ .{ .cwd = .{ .dir = tmp.dir }, .kill_process_tree = true },
+ );
+ defer {
+ std.testing.allocator.free(completed.stdout);
+ std.testing.allocator.free(completed.stderr);
+ }
+ try std.testing.expect(jobs.ranOk(completed));
+ io.sleep(.fromMilliseconds(1_000), .awake) catch {};
+ try std.testing.expectError(error.FileNotFound, tmp.dir.openFile(io, "timeout-marker", .{}));
+ try std.testing.expectError(error.FileNotFound, tmp.dir.openFile(io, "completed-marker", .{}));
+}
+
+test "bash_output wait_ms>0 waits for exit, not the next byte (ADR 0010)" {
+ if (builtin.os.tag == .windows or builtin.os.tag == .wasi) return error.SkipZigTest;
+ jobs.g_jobs = .{};
+ const gpa = std.testing.allocator;
+ const io = std.testing.io;
+ const id = (try jobs.spawnJob(gpa, io, "printf start; sleep 0.15; printf done; exit 7")).id;
+ defer jobs.jobsReap(gpa, io);
+ const snap = try jobs.jobOutput(gpa, io, id, 0);
+ defer gpa.free(snap.text);
+ const done = try jobs.jobOutput(gpa, io, id, 30_000);
+ defer gpa.free(done.text);
+ const text = if (std.mem.indexOf(u8, done.text, "exited with code 7") != null) done.text else snap.text;
+ try std.testing.expect(std.mem.indexOf(u8, text, "exited with code 7") != null);
+}
+
+test "#620: a still-running foreground wait promotes instead of killing" {
+ if (builtin.os.tag == .windows or builtin.os.tag == .wasi) return error.SkipZigTest;
+ jobs.g_jobs = .{};
+ const gpa = std.testing.allocator;
+ const io = std.testing.io;
+ const id = (try jobs.spawnJob(gpa, io, "sleep 2; printf never")).id;
+ defer jobs.jobsReap(gpa, io);
+ const waited = try jobs.waitForeground(gpa, io, id, 200);
+ defer switch (waited) {
+ .running => |r| gpa.free(r.output),
+ .done => |d| gpa.free(d.output),
+ .cancelled => |c| gpa.free(c.output),
+ };
+ try std.testing.expect(waited == .running);
+ try std.testing.expectEqual(id, waited.running.id);
+ const snap = try jobs.jobOutput(gpa, io, id, 0);
+ defer gpa.free(snap.text);
+ try std.testing.expect(std.mem.indexOf(u8, snap.text, "running") != null);
+}
+
+test "#620: a short foreground command finishes as done, not a job" {
+ if (builtin.os.tag == .windows or builtin.os.tag == .wasi) return error.SkipZigTest;
+ jobs.g_jobs = .{};
+ const gpa = std.testing.allocator;
+ const io = std.testing.io;
+ const id = (try jobs.spawnJob(gpa, io, "printf hi; exit 0")).id;
+ defer jobs.jobsReap(gpa, io);
+ const waited = try jobs.waitForeground(gpa, io, id, 2_000);
+ defer switch (waited) {
+ .running => |r| gpa.free(r.output),
+ .done => |d| gpa.free(d.output),
+ .cancelled => |c| gpa.free(c.output),
+ };
+ try std.testing.expect(waited == .done);
+ try std.testing.expectEqual(@as(?u8, 0), waited.done.exit_code);
+ try std.testing.expect(std.mem.indexOf(u8, waited.done.output, "hi") != null);
+}
diff --git a/src/schema.zig b/src/schema.zig
index bf7c290f..5112bc78 100644
--- a/src/schema.zig
+++ b/src/schema.zig
@@ -52,9 +52,9 @@ const empty_schema =
const base_specs = [_]ToolSpec{
.{
.name = "bash",
- .desc = "Run a shell command via /bin/sh -c in the current working directory. Returns stdout, stderr, and the exit code. A user-cancelled command reports cancelled (its whole local process group is killed; a remote process started over ssh may survive on the remote host). For long-running commands set run_in_background true: it returns a job id immediately and you are notified on completion — do not poll. bash_output(wait_ms>0) blocks until exit (up to 10h); omit wait_ms for a snapshot. Stop it with bash_kill.",
+ .desc = "Run a shell command via /bin/sh -c in the current working directory. Returns stdout, stderr, and the exit code. A user-cancelled command reports cancelled (its whole local process group is killed; a remote process started over ssh may survive on the remote host). Foreground commands that are still running after 120s (or timeout ms) are moved to the background and return a job id — the process keeps running. For long-running commands set run_in_background true to skip the wait. You are notified on completion — do not poll. bash_output(wait_ms>0) blocks until exit (up to 10h); omit wait_ms for a snapshot. Stop it with bash_kill.",
.schema =
- \\{"type": "object", "properties": {"command": {"type": "string", "description": "Shell command to execute"}, "run_in_background": {"type": "boolean", "description": "Start as a background job and return its id immediately instead of waiting (default false)"}}, "required": ["command"]}
+ \\{"type": "object", "properties": {"command": {"type": "string", "description": "Shell command to execute"}, "timeout": {"type": "integer", "description": "Optional foreground wait in milliseconds before auto-background (default 120000, max 36000000). 0 uses the default. Ignored when run_in_background is true."}, "run_in_background": {"type": "boolean", "description": "Start as a background job and return its id immediately instead of waiting (default false)"}}, "required": ["command"]}
,
},
.{