Skip to content

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

Python

Serialize mutating tool batches in assistant order

justrach8212bb86942d
diff --git a/evals/harness_behavior.jsonl b/evals/harness_behavior.jsonl
index 8db1d3c8..cc6fd39d 100644
--- a/evals/harness_behavior.jsonl
+++ b/evals/harness_behavior.jsonl
@@ -107,3 +107,5 @@
{"id":"human-workflow-missing-config-clarify-followup","why":"#106: failed navigation cannot become an invented setting; a human supplies the actual path, then a later requested edit preserves unrelated configuration.","args":["--old"],"env":{"GRAFF_NO_CODEDB_GUARD":"1"},"workspace_seed":{"config/settings.json":"{\"retries\": 3, \"timeout\": 10}\n","README.md":"Do not change me.\n"},"prompt":"Check settings.json for the retry count. If it is missing, ask me where it lives; do not create a replacement or change anything yet.","controls_after_turn":[{"type":"answer","text":"It is config/settings.json. Read that existing file."}],"second_prompt":"Raise retries to 4 in that file, preserve timeout, and validate the JSON.","script":[{"tool":"read_file","arguments":{"path":"settings.json"}},{"tool":"ask_user","arguments":{"question":"Where is the existing settings file?"}},{"tool":"read_file","arguments":{"path":"config/settings.json"}},{"text":"The existing retry count is 3. No files were changed."},{"tool":"edit_file","arguments":{"path":"config/settings.json","old_string":"\"retries\": 3","new_string":"\"retries\": 4"}},{"tool":"bash","arguments":{"command":"python3 -c 'import json; x=json.load(open(\"config/settings.json\")); assert x=={\"retries\":4,\"timeout\":10}; print(\"configuration validated\")'"}},{"text":"Retries are 4; timeout remains 10. Configuration validated."}],"verify_command":["python3","-c","import json,pathlib; assert json.loads(pathlib.Path(\"config/settings.json\").read_text())=={\"retries\":4,\"timeout\":10}; assert not pathlib.Path(\"settings.json\").exists(); print(\"independent configuration passed\")"],"assert":[{"event":{"type":"tool_call_finished","name":"read_file","is_error":true}},{"event":{"type":"ask_user","question":"Where is the existing settings file?"}},{"events_at_least":{"match":{"type":"turn"},"count":2}},{"no_event":{"type":"tool_call","name":"write_file"}},{"request_contains":{"text":"Read that existing file"}},{"final_text_contains":"timeout remains 10"},{"file_equals":{"path":"config/settings.json","content":"{\"retries\": 4, \"timeout\": 10}\n"}},{"file_equals":{"path":"README.md","content":"Do not change me.\n"}},{"request_contains":{"index":2,"text":"config/settings.json. Read that existing file."}},{"request_tool_calls_at_most":{"index":2,"name":"edit_file","count":0}}]}
{"id": "current-head-receipt-names-actual-checks", "why": "#853: preserve the actual named CI outcomes; local schema success cannot replace failing packed SDK evidence.", "args": ["--old", "--goal", "Deliver a PR with passing current-head CI"], "env": {"GRAFF_NO_CODEDB_GUARD": "1"}, "github_fixture": {"runs": "none", "check_rollup": [{"name": "schema drift", "status": "COMPLETED", "conclusion": "SUCCESS"}, {"name": "packed SDK", "status": "COMPLETED", "conclusion": "FAILURE"}, {"context": "platform contract", "state": "PENDING"}], "review_files": ["notes.md"]}, "prompt": "Run the local publication fixture and fulfill the objective.", "script": [{"tool": "todo_write", "arguments": {"todos": [{"content": "inspect exact-head CI", "status": "pending"}]}}, {"tool": "bash", "arguments": {"command": "gh pr create --title fixture --body-file notes.md"}}, {"text": "{\"verdict\": \"supported\", \"reason\": \"Controlled committed fixture review.\"}"}, {"tool": "todo_write", "arguments": {"todos": [{"content": "provide draft handoff", "status": "completed"}]}}, {"tool": "attempt_completion", "arguments": {"result": "Draft handoff; the base checks also fail."}}, {"tool": "attempt_completion", "arguments": {"result": "Draft handoff; the base checks also fail."}}, {"text": "CI is unresolved."}], "assert": [{"events_at_least": {"match": {"type": "tool_call_finished", "name": "attempt_completion", "is_error": true}, "count": 2}}, {"no_event": {"type": "tool_call_finished", "name": "attempt_completion", "is_error": false}}, {"request_contains": {"text": "failed: CI reported a failure"}}, {"request_contains": {"text": "schema drift"}}, {"request_contains": {"text": "packed SDK"}}, {"request_contains": {"text": "platform contract"}}]}
{"id":"review-checkpoint-preserves-unfinished-scope","why":"#306: a long read-only review requests an evidence checkpoint without forcing completion or granting edits.","args":["--old"],"prompt_options":{"type":"review"},"prompt":"Review target.txt without modifying it.","workspace_seed":{"target.txt":"original\n"},"script":[{"tool":"read_file","arguments":{"path":"target.txt"}},{"tool":"read_file","arguments":{"path":"target.txt"}},{"tool":"read_file","arguments":{"path":"target.txt"}},{"tool":"read_file","arguments":{"path":"target.txt"}},{"tool":"read_file","arguments":{"path":"target.txt"}},{"tool":"read_file","arguments":{"path":"target.txt"}},{"tool":"read_file","arguments":{"path":"target.txt"}},{"tool":"read_file","arguments":{"path":"target.txt"}},{"tool":"read_file","arguments":{"path":"target.txt"}},{"tool":"read_file","arguments":{"path":"target.txt"}},{"tool":"read_file","arguments":{"path":"target.txt"}},{"tool":"read_file","arguments":{"path":"target.txt"}},{"tool":"read_file","arguments":{"path":"target.txt"}},{"tool":"read_file","arguments":{"path":"target.txt"}},{"tool":"read_file","arguments":{"path":"target.txt"}},{"tool":"read_file","arguments":{"path":"target.txt"}},{"tool":"read_file","arguments":{"path":"target.txt"}},{"tool":"read_file","arguments":{"path":"target.txt"}},{"tool":"read_file","arguments":{"path":"target.txt"}},{"tool":"read_file","arguments":{"path":"target.txt"}},{"text":"No findings. Review finished."}],"assert":[{"events_at_least":{"match":{"type":"review_checkpoint","complete":false},"count":1}},{"events_at_most":{"match":{"type":"review_checkpoint"},"count":1}},{"request_contains":{"text":"Review checkpoint:"}},{"request_contains":{"text":"next inspection tool call"}},{"file_equals":{"path":"target.txt","content":"original\n"}},{"final_text_contains":"No findings. Review finished."}]}
+{"id": "same-turn-two-writes-land", "why": "Two write_file calls in one assistant message must both land. Serial mutating batches must not drop the second write; parallel must not race-lose it either.", "args": [], "env": {"GRAFF_NO_CODEDB_GUARD": "1"}, "prompt": "create a.txt and b.txt", "script": [{"tools": [{"tool": "write_file", "arguments": {"path": "a.txt", "content": "alpha\n"}}, {"tool": "write_file", "arguments": {"path": "b.txt", "content": "beta\n"}}]}, {"tool": "bash", "arguments": {"command": "grep -qx alpha a.txt && grep -qx beta b.txt && echo BOTH_LANDED"}}, {"text": "both files are in"}], "assert": [{"events_at_least": {"match": {"type": "tool_call", "name": "write_file"}, "count": 2}}, {"events_at_most": {"match": {"type": "tool_call_finished", "is_error": true}, "count": 0}}, {"event": {"type": "tool_result", "name": "bash", "text": "BOTH_LANDED\n"}}, {"final_text_contains": "both files are in"}]}
+{"id": "same-turn-write-then-edit-same-file", "why": "write_file then edit_file on the same path in one assistant message used to race (#337). Serial batches make the edit see the write; a lost race fails old_string or missing file.", "args": [], "env": {"GRAFF_NO_CODEDB_GUARD": "1"}, "prompt": "create n.txt then change v1 to v2", "script": [{"tools": [{"tool": "write_file", "arguments": {"path": "n.txt", "content": "v1\n"}}, {"tool": "edit_file", "arguments": {"path": "n.txt", "old_string": "v1", "new_string": "v2"}}]}, {"tool": "bash", "arguments": {"command": "grep -qx v2 n.txt && echo EDIT_SAW_WRITE"}}, {"text": "the file now says v2"}], "assert": [{"event": {"type": "tool_call", "name": "write_file"}}, {"event": {"type": "tool_call", "name": "edit_file"}}, {"events_at_most": {"match": {"type": "tool_call_finished", "is_error": true}, "count": 0}}, {"event": {"type": "tool_result", "name": "bash", "text": "EDIT_SAW_WRITE\n"}}, {"final_text_contains": "v2"}]}
diff --git a/src/agent.zig b/src/agent.zig
index 3a0b51f7..569b3e61 100644
--- a/src/agent.zig
+++ b/src/agent.zig
@@ -31,10 +31,7 @@ const prompt_ui = @import("agent_prompt.zig");
const agent_tests = @import("agent_tests.zig");
const empty_completion = @import("agent_empty_completion.zig");
const goal_state = @import("goal_state.zig");
-const peer_channel = @import("peer_channel.zig"); // #469: turn-boundary peer message delivery
-const job_notify = @import("job_notify.zig");
-const schedule = @import("schedule.zig");
-const channel_worker = @import("channel_worker.zig");
+const turn_inbox = @import("turn_inbox.zig");
pub const TodoItem = struct {
content: []const u8,
@@ -347,16 +344,10 @@ pub const Agent = struct {
if (!self.sub) esc_cancel.store(false, .release);
return error.Interrupted;
}
- // #469: co-resident sessions' queued channel messages land at EVERY
- // step boundary, so a working session picks a peer's note up
- // mid-task (between tool batches) and can act on it in the same
- // turn — durable in history, visible as an event. Offset-based:
- // an empty channel costs one small stat per step.
- peer_channel.deliverInbound(self);
- try @import("subagent_feedback.zig").deliverToAgent(self);
- job_notify.deliver(self);
- schedule.deliver(self);
- channel_worker.deliver(self);
+ // Peer mail, job/schedule wakes, and REPL steer land here so a
+ // follow-up typed during tools is the next user message in this
+ // turn rather than the next prompt after runTurn returns.
+ try turn_inbox.deliver(self);
// #193: pre-send overflow gate. A single turn's tool-output burst can
// push the input past the model's wall before the between-turns 80%
// meter (last_context_tokens, server-reported) catches up. Estimate the
diff --git a/src/agent_tool_batch.zig b/src/agent_tool_batch.zig
new file mode 100644
index 00000000..909c9f51
--- /dev/null
+++ b/src/agent_tool_batch.zig
@@ -0,0 +1,210 @@
+//! External tool-batch execution: sequential when any mutating tool is in
+//! the batch, otherwise the existing parallel fan-out. Esc after preflight
+//! still writes an error result for every remaining call id so the model
+//! never sees a dangling tool_use.
+const std = @import("std");
+const Io = std.Io;
+
+const main_mod = @import("main.zig");
+const agent_mod = @import("agent.zig");
+const Agent = agent_mod.Agent;
+const tools_mod = @import("tools.zig");
+const ToolCall = tools_mod.ToolCall;
+const ExecResult = tools_mod.ExecResult;
+const ToolCtx = tools_mod.ToolCtx;
+const ToolOutput = tools_mod.ToolOutput;
+const exec = @import("exec.zig");
+const execTool = exec.execTool;
+const shell_tool = @import("shell_tool.zig");
+const imagegen = @import("imagegen.zig");
+const terminal = @import("term.zig");
+const tty = terminal.tty;
+const engine_events = @import("engine_events.zig");
+const engine_sink = @import("engine_sink.zig");
+const tool_handle = @import("tool_handle.zig");
+const eval_control = @import("agent_eval_control.zig");
+
+pub const skipped_text = "tool execution skipped because the operation was aborted";
+
+/// Write / edit / shell (and imagegen) serialize the whole batch, matching
+/// the Pi/MiniMax rule: if any call is sequential, none of them race.
+pub fn isSequential(name: []const u8) bool {
+ if (shell_tool.isFamily(name)) return true;
+ if (std.mem.eql(u8, name, "write_file")) return true;
+ if (std.mem.eql(u8, name, "edit_file")) return true;
+ if (std.mem.eql(u8, name, imagegen.tool_name)) return true;
+ return false;
+}
+
+pub fn batchNeedsSerial(calls: []const ToolCall, ext_idx: []const usize) bool {
+ for (ext_idx) |i| {
+ if (isSequential(calls[i].name)) return true;
+ }
+ return false;
+}
+
+pub fn runExternal(self: *Agent, calls: []const ToolCall, ext_idx: []const usize, results: []ExecResult) !void {
+ if (ext_idx.len == 0) return;
+ const serial = batchNeedsSerial(calls, ext_idx);
+ if (ext_idx.len > 1 and !self.sub and !serial) {
+ engine_sink.forAgent(self).emit(self.io, .{ .parallel_batch_started = .{ .count = ext_idx.len } });
+ }
+ const ctx: ToolCtx = .{
+ .gpa = self.gpa,
+ .io = self.io,
+ .client = self.client,
+ .provider = self.provider,
+ .subagent_provider = self.subagent_provider,
+ .subagent_cross_provider = self.subagent_cross_provider,
+ .mcp_context = self.mcp_context.value,
+ .registry = self.registry,
+ .from_sub = self.sub,
+ .interactive_children = !self.sub and @import("subagent_interactive.zig").enabled.load(.acquire),
+ .session_name = self.session_name,
+ .has_eval = self.eval_cmd != null,
+ .approvals = self.approvals,
+ .tracer = self.tracer,
+ .run_budget = self.run_budget,
+ .publication_checks = self.publication_checks,
+ .depth = self.depth,
+ .snapshots = self.snapshots,
+ .tools_used = &self.tools_used,
+ .loop_deadline_ms = self.loop_deadline_ms,
+ .agent_cwd = self.agent_cwd,
+ .subagent_feedback = self.feedback,
+ };
+ const esc_watch = !self.sub and self.in != null and main_mod.use_color and !main_mod.json_mode;
+ var esc_tio: ?tty.RawState = null;
+ var esc_fut: ?Io.Future(void) = null;
+ if (esc_watch) if (Agent.rawNonblockStdin()) |tio| {
+ esc_tio = tio;
+ Agent.esc_watch_done.store(false, .release);
+ esc_fut = self.io.async(Agent.escWatchTask, .{});
+ };
+ defer if (esc_tio) |tio| {
+ Agent.esc_watch_done.store(true, .release);
+ if (esc_fut) |*f| f.await(self.io);
+ Agent.drainStdin();
+ tty.restore(tio);
+ };
+
+ if (serial) {
+ try runSerial(self, ctx, calls, ext_idx, results);
+ } else {
+ try runParallel(self, ctx, calls, ext_idx, results);
+ }
+
+ if (ext_idx.len > 1 and !self.sub and !serial) {
+ var tally: engine_events.BatchOutcome = .{ .done = 0, .failed = 0, .cancelled = 0 };
+ for (ext_idx) |i| {
+ const r = results[i];
+ if (r.cancelled) tally.cancelled += 1 else if (r.is_error) tally.failed += 1 else tally.done += 1;
+ }
+ engine_sink.forAgent(self).emit(self.io, .{ .parallel_batch_finished = tally });
+ }
+}
+
+fn skipResult(self: *Agent, call: ToolCall) ExecResult {
+ engine_sink.forAgent(self).emit(self.io, .{ .tool_rejected = .{
+ .id = call.id,
+ .name = call.name,
+ .input = call.input,
+ .reason = "aborted",
+ .message = skipped_text,
+ } });
+ return .{ .text = skipped_text, .is_error = true, .cancelled = true };
+}
+
+fn aborted() bool {
+ return Agent.esc_cancel.load(.acquire);
+}
+
+fn takeOutput(self: *Agent, call: ToolCall, output: ToolOutput, handle_threshold: usize, handle_target: tool_handle.Target) !ExecResult {
+ try @import("pr_local_checks.zig").record(self, call, .{ .text = output.text, .is_error = output.is_error, .cancelled = output.cancelled });
+ const handled = try tool_handle.forResult(self.gpa, self.arena, handle_target, output.text, handle_threshold);
+ const text = try tool_handle.withFirstNote(self.arena, handled, &self.handle_note_shown);
+ if (self.eval_cmd != null and eval_control.toolInvalidatesEval(call)) {
+ self.eval_verified = false;
+ self.eval_repair_pending = false;
+ }
+ return .{ .text = text, .is_error = output.is_error, .cancelled = output.cancelled, .ms = output.ms };
+}
+
+fn handleTarget(self: *Agent) tool_handle.Target {
+ return .{
+ .io = self.io,
+ .dir = .cwd(),
+ .run_id = if (self.tracer) |tr| tr.identity.run_id else "untraced",
+ };
+}
+
+fn runSerial(self: *Agent, ctx: ToolCtx, calls: []const ToolCall, ext_idx: []const usize, results: []ExecResult) !void {
+ const handle_threshold = tool_handle.effectiveThreshold(self.provider.perOutputCap());
+ const handle_tgt = handleTarget(self);
+ for (ext_idx, 0..) |i, k| {
+ if (k > 0 and aborted()) {
+ results[i] = skipResult(self, calls[i]);
+ continue;
+ }
+ const output = execTool(ctx, calls[i]);
+ defer self.gpa.free(output.text);
+ results[i] = try takeOutput(self, calls[i], output, handle_threshold, handle_tgt);
+ }
+}
+
+fn runParallel(self: *Agent, ctx: ToolCtx, calls: []const ToolCall, ext_idx: []const usize, results: []ExecResult) !void {
+ var spawn_at: std.ArrayList(usize) = .empty;
+ defer spawn_at.deinit(self.gpa);
+ for (ext_idx, 0..) |i, k| {
+ if (k > 0 and aborted()) {
+ results[i] = skipResult(self, calls[i]);
+ continue;
+ }
+ try spawn_at.append(self.gpa, i);
+ }
+ if (spawn_at.items.len == 0) return;
+
+ const futures = try self.gpa.alloc(Io.Future(ToolOutput), spawn_at.items.len);
+ defer self.gpa.free(futures);
+ const outputs = try self.gpa.alloc(ToolOutput, spawn_at.items.len);
+ defer self.gpa.free(outputs);
+ for (spawn_at.items, futures) |i, *fut|
+ fut.* = self.io.concurrent(execTool, .{ ctx, calls[i] }) catch self.io.async(execTool, .{ ctx, calls[i] });
+ for (futures, outputs) |*fut, *output| output.* = fut.await(self.io);
+ defer for (outputs) |output| self.gpa.free(output.text);
+
+ const handle_threshold = tool_handle.effectiveThreshold(self.provider.perOutputCap());
+ const handle_tgt = handleTarget(self);
+ for (spawn_at.items, outputs) |i, output| {
+ results[i] = try takeOutput(self, calls[i], output, handle_threshold, handle_tgt);
+ }
+}
+
+test "isSequential: mutating file/shell tools, not reads" {
+ try std.testing.expect(isSequential("write_file"));
+ try std.testing.expect(isSequential("edit_file"));
+ try std.testing.expect(isSequential("shell"));
+ try std.testing.expect(isSequential("bash"));
+ try std.testing.expect(isSequential(imagegen.tool_name));
+ try std.testing.expect(!isSequential("read_file"));
+ try std.testing.expect(!isSequential("codedb"));
+ try std.testing.expect(!isSequential("webfetch"));
+ try std.testing.expect(!isSequential("subagent"));
+}
+
+test "batchNeedsSerial: any mutating call serializes the batch" {
+ const read = ToolCall{ .id = "1", .name = "read_file", .input = .{ .object = .empty } };
+ const write = ToolCall{ .id = "2", .name = "write_file", .input = .{ .object = .empty } };
+ const codedb = ToolCall{ .id = "3", .name = "codedb", .input = .{ .object = .empty } };
+ const mixed = [_]ToolCall{ read, write };
+ try std.testing.expect(batchNeedsSerial(&mixed, &.{ 0, 1 }));
+ const reads = [_]ToolCall{ read, codedb };
+ try std.testing.expect(!batchNeedsSerial(&reads, &.{ 0, 1 }));
+ const only_write = [_]ToolCall{write};
+ try std.testing.expect(batchNeedsSerial(&only_write, &.{0}));
+}
+
+test "skipped_text is a stable model-facing sentence" {
+ try std.testing.expect(std.mem.indexOf(u8, skipped_text, "skipped") != null);
+ try std.testing.expect(std.mem.indexOf(u8, skipped_text, "aborted") != null);
+}
diff --git a/src/agent_tools.zig b/src/agent_tools.zig
index 95b688cd..6ed020e3 100644
--- a/src/agent_tools.zig
+++ b/src/agent_tools.zig
@@ -1,5 +1,5 @@
//! Tool-call dispatch: the batch runner (runTools) that rejects/dedupes/
-//! gates each call then fans external ones out across the Io thread pool,
+//! gates each call then runs external ones (serial if any write/edit/shell),
//! the human-approval gate for bash/write_file/edit_file/MCP calls
//! (gateTool), meta-tool handling (attempt_completion/eval/todo_write/
//! todo_read/ask_user, on the agent's own thread — handleMeta/askUser),
@@ -23,8 +23,6 @@ const ExecResult = tools_mod.ExecResult;
// which belongs to the input-inversion issue (#430), not to this one.
const engine_events = @import("engine_events.zig");
const engine_sink = @import("engine_sink.zig");
-const terminal = @import("term.zig");
-const tty = terminal.tty;
const schema = @import("schema.zig");
const isMetaName = schema.isMetaName;
@@ -41,11 +39,6 @@ pub const gateTool = @import("agent_tool_gate.zig").gateTool;
pub const firstWord = @import("agent_tool_gate.zig").firstWord;
const tools_mod = @import("tools.zig");
-const ToolCtx = tools_mod.ToolCtx;
-const ToolOutput = tools_mod.ToolOutput;
-
-const exec = @import("exec.zig");
-const execTool = exec.execTool;
const brief_diversity = @import("brief_diversity.zig"); // #382: N sibling spawns in one batch are a fleet
const playbook_glue = @import("playbook_glue.zig"); // #381: the note_constraint meta arm
@@ -55,22 +48,12 @@ const local_tools = @import("local_tools.zig");
const schedule = @import("schedule.zig");
const util = @import("util.zig"); // #225: unixMs, for the clock_sleep interrupted-elapsed measurement
-// #440: the ONE size contract for a tool result — preview + durable handle +
-// byte count + shape hint, applied at tool time, clamped under the send-time cap.
-const tool_handle = @import("tool_handle.zig");
const cite_markup = @import("cite_markup.zig");
-// escWatchTask/drainStdin/rawNonblockStdin live in agent_interrupt.zig;
-// esc_cancel/esc_watch_done STAY declared on the Agent struct (never alias
-// a var — see agent_interrupt.zig's own header). Reached via Agent's namespace.
-const escWatchTask = Agent.escWatchTask;
-const drainStdin = Agent.drainStdin;
-const rawNonblockStdin = Agent.rawNonblockStdin;
-
/// Run a batch of tool calls. Meta tools are handled inline (they mutate
-/// agent state); everything else fans out across the Io thread pool.
-/// Bash calls must clear the permission gate before dispatch. Results
-/// are returned in call order, arena-owned.
+/// agent state); mutating file/shell calls run one at a time, otherwise
+/// external calls fan out across the Io thread pool. Results are returned
+/// in call order, arena-owned.
pub fn runTools(self: *Agent, calls: []const ToolCall) ![]ExecResult {
if (!self.sub and calls.len >= 4) {
var names: [32][]const u8 = undefined;
@@ -123,96 +106,8 @@ pub fn runTools(self: *Agent, calls: []const ToolCall) ![]ExecResult {
}
if (ext_idx.items.len > 0) {
- // A child's fan-out is the root's to announce, so the moment is not
- // produced at all for a subagent: engine policy about who owns the
- // terminal, kept at the emit site rather than re-derived by a sink
- // that would need to back-read the Agent to know (#422 slice-1 rule).
- if (ext_idx.items.len > 1 and !self.sub) {
- engine_sink.forAgent(self).emit(self.io, .{ .parallel_batch_started = .{ .count = ext_idx.items.len } });
- }
- const ctx: ToolCtx = .{
- .gpa = self.gpa,
- .io = self.io,
- .client = self.client,
- .provider = self.provider,
- .subagent_provider = self.subagent_provider,
- .subagent_cross_provider = self.subagent_cross_provider,
- .mcp_context = self.mcp_context.value,
- .registry = self.registry, // workers get licensed codedb-pro reads too (#627)
- .from_sub = self.sub,
- .interactive_children = !self.sub and @import("subagent_interactive.zig").enabled.load(.acquire),
- .session_name = self.session_name,
- .has_eval = self.eval_cmd != null,
- .approvals = self.approvals,
- .tracer = self.tracer,
- .run_budget = self.run_budget,
- .publication_checks = self.publication_checks,
- .depth = self.depth,
- .snapshots = self.snapshots,
- .tools_used = &self.tools_used,
- .loop_deadline_ms = self.loop_deadline_ms,
- .agent_cwd = self.agent_cwd,
- };
- // Esc while tools run: a stdin watcher for the join (esc_cancel);
- // subagents notice mid-flight, the root aborts at its next runTurn.
- const esc_watch = !self.sub and self.in != null and main_mod.use_color and !main_mod.json_mode;
- var esc_tio: ?tty.RawState = null;
- var esc_fut: ?Io.Future(void) = null;
- if (esc_watch) if (rawNonblockStdin()) |tio| {
- esc_tio = tio;
- Agent.esc_watch_done.store(false, .release);
- esc_fut = self.io.async(escWatchTask, .{});
- };
- defer if (esc_tio) |tio| {
- Agent.esc_watch_done.store(true, .release);
- if (esc_fut) |*f| f.await(self.io);
- drainStdin();
- tty.restore(tio);
- };
- // Join ALL futures before any fallible work: an early error
- // return would otherwise free the futures while pool tasks are
- // still writing into them (and abandon running tools).
- const futures = try self.gpa.alloc(Io.Future(ToolOutput), ext_idx.items.len);
- defer self.gpa.free(futures);
- const outputs = try self.gpa.alloc(ToolOutput, ext_idx.items.len);
- defer self.gpa.free(outputs);
- for (ext_idx.items, futures) |i, *fut| fut.* = self.io.concurrent(execTool, .{ ctx, calls[i] }) catch self.io.async(execTool, .{ ctx, calls[i] });
- for (futures, outputs) |*fut, *output| output.* = fut.await(self.io);
- defer for (outputs) |output| self.gpa.free(output.text);
- // #440: one threshold for the whole batch, pinned under this model's
- // send-time per-output cap so an oversized result is always turned into
- // a handle HERE rather than truncated later.
- const handle_threshold = tool_handle.effectiveThreshold(self.provider.perOutputCap());
- const handle_target: tool_handle.Target = .{
- .io = self.io,
- .dir = .cwd(),
- .run_id = if (self.tracer) |tr| tr.identity.run_id else "untraced",
- };
- for (ext_idx.items, outputs) |i, output| {
- try @import("pr_local_checks.zig").record(self, calls[i], .{ .text = output.text, .is_error = output.is_error, .cancelled = output.cancelled });
- // Over the threshold, the bytes go to a durable handle; the model
- // gets a bounded preview + path + byte count + shape hint.
- const handled = try tool_handle.forResult(self.gpa, self.arena, handle_target, output.text, handle_threshold);
- // #541: the handle-protocol lesson rides this agent's FIRST handle
- // instead of standing in every request's system prompt.
- const text = try tool_handle.withFirstNote(self.arena, handled, &self.handle_note_shown);
- results[i] = .{ .text = text, .is_error = output.is_error, .cancelled = output.cancelled, .ms = output.ms };
- if (self.eval_cmd != null and toolInvalidatesEval(calls[i])) {
- self.eval_verified = false;
- self.eval_repair_pending = false;
- }
- }
+ try @import("agent_tool_batch.zig").runExternal(self, calls, ext_idx.items, results);
brief_diversity.noteSiblingBatch(self.arena, self.tracer, calls, ext_idx.items, results); // #382
- // #266: a cancelled parallel batch used to just look "running" and then
- // failed — one terminal line says what completed, failed, and cancelled.
- if (ext_idx.items.len > 1 and !self.sub) { // root's line to draw, as above
- var tally: engine_events.BatchOutcome = .{ .done = 0, .failed = 0, .cancelled = 0 };
- for (ext_idx.items) |i| {
- const r = results[i];
- if (r.cancelled) tally.cancelled += 1 else if (r.is_error) tally.failed += 1 else tally.done += 1;
- }
- engine_sink.forAgent(self).emit(self.io, .{ .parallel_batch_finished = tally });
- }
}
if (defer_completion) if (eval_control.completionIndex(calls)) |i| {
var verify_failed = ext_idx.items.len == 0;
diff --git a/src/turn_inbox.zig b/src/turn_inbox.zig
new file mode 100644
index 00000000..ca157fe3
--- /dev/null
+++ b/src/turn_inbox.zig
@@ -0,0 +1,90 @@
+//! Step-boundary inbox: peer mail, jobs, schedule, channel workers, and
+//! REPL steer. One call from `Agent.runTurn` so a follow-up typed during
+//! tools lands as the next user message in the same turn (not the next
+//! prompt after `runTurn` returns). Force-steers stay queued for the
+//! interrupt path. TUI follow-ups still drain after the job.
+const std = @import("std");
+const Agent = @import("agent.zig").Agent;
+const repl_glue = @import("repl_glue.zig");
+const session_wake = @import("session_wake.zig");
+const main_mod = @import("main.zig");
+
+pub fn deliver(self: *Agent) !void {
+ @import("peer_channel.zig").deliverInbound(self);
+ try @import("subagent_feedback.zig").deliverToAgent(self);
+ @import("job_notify.zig").deliver(self);
+ @import("schedule.zig").deliver(self);
+ @import("channel_worker.zig").deliver(self);
+ deliverSteer(self);
+}
+
+/// Soft steer only: `force` stays at the head of `g_steer_queue` so the
+/// REPL interrupt path still sees it after this turn unwinds.
+fn popSteerSoft() ?repl_glue.SteerEntry {
+ repl_glue.steerLock();
+ defer repl_glue.steerUnlock();
+ const q = &main_mod.g_steer_queue;
+ if (q.items.len == 0) return null;
+ if (q.items[0].force) return null;
+ return q.orderedRemove(0);
+}
+
+fn deliverSteer(self: *Agent) void {
+ if (self.sub) return;
+ const entry = popSteerSoft() orelse return;
+ defer std.heap.page_allocator.free(entry.text);
+ session_wake.inject(self, entry.text);
+}
+
+test "deliverSteer injects one non-force line and leaves force queued" {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const drop = struct {
+ fn emit(_: *anyopaque, _: @import("engine_sink.zig").Stamped) void {}
+ };
+ const vt = @import("engine_sink.zig").VTable{ .emit = drop.emit, .durable = false };
+ var root: Agent = undefined;
+ root.sub = false;
+ root.arena = arena_state.allocator();
+ root.messages = std.json.Array.init(arena_state.allocator());
+ root.sink = .{ .ctx = undefined, .vt = &vt };
+
+ const page = std.heap.page_allocator;
+ const soft = try page.dupe(u8, "also run the tests");
+ const force = try page.dupe(u8, "stop");
+ repl_glue.steerLock();
+ for (main_mod.g_steer_queue.items) |e| page.free(e.text);
+ main_mod.g_steer_queue.clearRetainingCapacity();
+ try main_mod.g_steer_queue.append(page, .{ .text = soft, .force = false });
+ try main_mod.g_steer_queue.append(page, .{ .text = force, .force = true });
+ repl_glue.steerUnlock();
+ defer {
+ repl_glue.steerLock();
+ for (main_mod.g_steer_queue.items) |e| page.free(e.text);
+ main_mod.g_steer_queue.clearRetainingCapacity();
+ repl_glue.steerUnlock();
+ }
+
+ deliverSteer(&root);
+ try std.testing.expectEqual(@as(usize, 1), root.messages.items.len);
+ try std.testing.expectEqualStrings("also run the tests", root.messages.items[0].object.get("content").?.string);
+
+ repl_glue.steerLock();
+ defer repl_glue.steerUnlock();
+ try std.testing.expectEqual(@as(usize, 1), main_mod.g_steer_queue.items.len);
+ try std.testing.expect(main_mod.g_steer_queue.items[0].force);
+}
+
+test "deliverSteer is a no-op on subagents" {
+ var root: Agent = undefined;
+ root.sub = true;
+ deliverSteer(&root);
+}
+
+test "popSteerSoft leaves an empty queue alone" {
+ repl_glue.steerLock();
+ for (main_mod.g_steer_queue.items) |e| std.heap.page_allocator.free(e.text);
+ main_mod.g_steer_queue.clearRetainingCapacity();
+ repl_glue.steerUnlock();
+ try std.testing.expect(popSteerSoft() == null);
+}