Skip to content

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

Python

fix(acp): stream foreground child sessions safely

Rach Pradhan3fc57131cf41
diff --git a/build.zig b/build.zig
index 42bb594d..64d521af 100644
--- a/build.zig
+++ b/build.zig
@@ -143,6 +143,9 @@ pub fn build(b: *std.Build) void {
const acp_agent_wait_test = b.addSystemCommand(&.{ "python3", "scripts/test-acp-agent-output-wait.py" });
acp_agent_wait_test.addArtifactArg(exe);
test_step.dependOn(&acp_agent_wait_test.step);
+ const acp_child_update_test = b.addSystemCommand(&.{ "python3", "scripts/test-acp-subagent-update.py" });
+ acp_child_update_test.addArtifactArg(exe);
+ test_step.dependOn(&acp_child_update_test.step);
const workflow_isolation_test = b.addSystemCommand(&.{ "python3", "scripts/test-workflow-isolation.py" });
workflow_isolation_test.addArtifactArg(exe);
test_step.dependOn(&workflow_isolation_test.step);
diff --git a/docs/acp-compatibility.md b/docs/acp-compatibility.md
index 48337880..5136220f 100644
--- a/docs/acp-compatibility.md
+++ b/docs/acp-compatibility.md
@@ -31,7 +31,7 @@ optional feature or draft extension is enabled.
| Content | Text, resource links and supported embedded text resources are accepted. Image and audio prompt capabilities are currently advertised as false. | `src/acp_protocol.zig` |
| Client filesystem and terminals | These are optional negotiated ACP facilities, not a requirement that local harness tools be replaced by client tools. The local tool implementation does not imply support for every client-side method. | Capability negotiation and the upstream v1 schema |
| Usage | Connection usage is a namespaced extension. It preserves unknown totals and is not a standard ACP v1 billing contract. | `scripts/test-acp-usage.py`, ADR 0182 |
-| Subagents | The proposed child-session update stream is an opt-in live preview: client `subagents` capability plus `GRAFF_ACP_DRAFT_SUBAGENTS=1`. Foreground children stream separately; detached workers use `graff/agents`. Child history is not yet replayed on `session/load`. | `src/acp_subagent_live.zig`, ADR 0194 |
+| Subagents | The proposed child-session update stream is an opt-in live preview: client `subagents` capability plus `GRAFF_ACP_DRAFT_SUBAGENTS=1`. Explicit `run_in_background:false` foreground children stream separately; the default detached workers retain their parent tool row and `graff/agents` inspection. Child history is not yet replayed on `session/load`. | `scripts/test-acp-subagent-update.py`, ADR 0194 |
| Transport | ACP uses JSON-RPC over stdio. HTTP/2 checks exercise the model request transport behind ACP; they do not redefine ACP as an HTTP/2 protocol. | `scripts/test-acp-http2.py`, `scripts/test-acp-http2-retry.py` |
## Client acceptance checklist
diff --git a/docs/adr/0194-acp-child-sessions-are-an-opt-in-preview.md b/docs/adr/0194-acp-child-sessions-are-an-opt-in-preview.md
index 327efcbb..f991247d 100644
--- a/docs/adr/0194-acp-child-sessions-are-an-opt-in-preview.md
+++ b/docs/adr/0194-acp-child-sessions-are-an-opt-in-preview.md
@@ -15,8 +15,10 @@ Keep stable ACP behavior as the default. A client that advertises
`clientCapabilities.subagents` can receive live `subagent_update` and child
session updates only when Graff is also launched with
`GRAFF_ACP_DRAFT_SUBAGENTS=1`. Announce only foreground children that complete
-within the active parent prompt; detached workers remain available through
-`graff/agents`. Preserve the parent tool call for clients and early failures,
+within the active parent prompt. Interactive sessions default to detached
+workers; `run_in_background:false` explicitly selects a foreground child on
+every frontend. Detached workers remain available through `graff/agents` and
+their parent tool rows. Preserve the parent tool call for clients and early failures,
with a namespaced tool name and parent call ID for exact UI correlation.
## Consequences
diff --git a/scripts/test-acp-subagent-update.py b/scripts/test-acp-subagent-update.py
new file mode 100644
index 00000000..7ae1cdfe
--- /dev/null
+++ b/scripts/test-acp-subagent-update.py
@@ -0,0 +1,94 @@
+#!/usr/bin/env python3
+"""Offline ACP child-session regression through the real subagent tool path."""
+import importlib.util
+import sys
+import tempfile
+from pathlib import Path
+
+REPO = Path(__file__).resolve().parents[1]
+spec = importlib.util.spec_from_file_location('acp_load', REPO / 'scripts/test-acp-session-load.py')
+load = importlib.util.module_from_spec(spec)
+spec.loader.exec_module(load)
+
+
+def updates(client):
+ return [(index, event['params']['sessionId'], event['params']['update'])
+ for index, event in enumerate(client.events)
+ if event.get('method') == 'session/update']
+
+
+def run(binary, preview, capability, json_mode=False):
+ with tempfile.TemporaryDirectory(prefix='graff-acp-child-') as temporary:
+ work = Path(temporary)
+ home = work / 'home'
+ home.mkdir()
+ (work / 'example.txt').write_text('SUBAGENT-FIXTURE-CONTENT\n')
+ model = load.ScriptedModel([
+ {'tool': 'subagent', 'arguments': {'description': 'Inspect example',
+ 'prompt': 'Read example.txt and report its content.', 'isolation': 'shared_cwd',
+ 'run_in_background': False}},
+ {'text': 'Child is inspecting.', 'tool': 'read_file',
+ 'arguments': {'path': 'example.txt'}},
+ {'text': 'Child found SUBAGENT-FIXTURE-CONTENT.'},
+ {'text': 'Parent received the child report.'},
+ ], exhausted_text='unexpected extra model call')
+ port = model.start(0)
+ env = {'GRAFF_NO_NATIVE_FOLD': '1'}
+ if preview:
+ env['GRAFF_ACP_DRAFT_SUBAGENTS'] = '1'
+ args = ('--max-model-calls', '6', '--max-run-tool-calls', '8')
+ if json_mode:
+ args += ('--json',)
+ client = load.Acp(binary, work, home, port, extra_env=env, extra_args=args)
+ try:
+ capabilities = {'subagents': {}} if capability else {}
+ client.request('initialize', {'protocolVersion': 1,
+ 'clientCapabilities': capabilities})
+ sid = client.request('session/new', {'cwd': str(work),
+ 'mcpServers': []})['result']['sessionId']
+ response = client.request('session/prompt', {'sessionId': sid,
+ 'prompt': [{'type': 'text', 'text': 'Delegate the local inspection.'}]}, timeout=25)
+ assert response['result']['stopReason'] == 'end_turn', response
+ rows = updates(client)
+ parent_calls = [(i, update) for i, session, update in rows
+ if session == sid and update.get('sessionUpdate') == 'tool_call'
+ and update.get('_meta', {}).get('graff/toolName') == 'subagent']
+ assert len(parent_calls) == 1, rows
+ parent_id = parent_calls[0][1]['toolCallId']
+ child_updates = [(i, update) for i, session, update in rows
+ if session == sid and update.get('sessionUpdate') == 'subagent_update']
+ if not (preview and capability):
+ assert not child_updates, rows
+ assert all(session == sid for _, session, _ in rows), rows
+ return
+ assert len(child_updates) == 2, rows
+ announced_at, announced = child_updates[0]
+ finished_at, finished = child_updates[1]
+ child_id = announced['subagentSessionId']
+ assert child_id != sid
+ assert announced['task'] == 'Read example.txt and report its content.'
+ assert announced['_meta']['graff/parentToolCallId'] == parent_id
+ assert finished['subagentSessionId'] == child_id
+ assert finished['state'] == 'completed'
+ assert finished['_meta']['graff/parentToolCallId'] == parent_id
+ activity = [(i, update) for i, session, update in rows if session == child_id]
+ assert any(update.get('sessionUpdate') == 'tool_call' and
+ update.get('_meta', {}).get('graff/toolName') == 'read_file'
+ for _, update in activity), activity
+ assert any('SUBAGENT-FIXTURE-CONTENT' in str(update)
+ for _, update in activity), activity
+ assert parent_calls[0][0] < announced_at < activity[0][0]
+ assert all(announced_at < i < finished_at for i, _ in activity), rows
+ assert finished_at < next(i for i, event in enumerate(client.events)
+ if event.get('id') == client.next_id)
+ finally:
+ client.close()
+ model.stop()
+
+
+if __name__ == '__main__':
+ binary = Path(sys.argv[1] if len(sys.argv) > 1 else REPO / 'zig-out/bin/graff').resolve()
+ for preview, capability in ((False, True), (True, False), (True, True)):
+ run(binary, preview, capability)
+ run(binary, True, True, json_mode=True)
+ print('ACP child sessions: gated fallback, negotiated announcement, child activity, terminal, --json')
diff --git a/src/acp_live_turn.zig b/src/acp_live_turn.zig
index 8356ce45..7c56b258 100644
--- a/src/acp_live_turn.zig
+++ b/src/acp_live_turn.zig
@@ -36,6 +36,9 @@ pub const LiveTurn = struct {
pub fn run(ctx: *anyopaque, arena: Allocator, text: []const u8) anyerror![]const u8 {
const self: *LiveTurn = @ptrCast(@alignCast(ctx));
+ var output_lock: Io.Mutex = .init;
+ if (self.inbox) |inbox| if (inbox.permission) |bridge| bridge.setOutputLock(&output_lock);
+ defer if (self.inbox) |inbox| if (inbox.permission) |bridge| bridge.setOutputLock(null);
// Receipt marker before any dedup/turn work: a worker that logged its
// recipe but never this line never received its prompt — the stall is
// upstream (client dispatch / bootstrap / transport), not in the turn.
@@ -72,9 +75,11 @@ pub const LiveTurn = struct {
self.saw_text = false;
var sink: stream.EventSink = undefined;
sink.init(self.root.gpa, self.out, &self.session_id, &self.saw_text);
+ sink.output_lock = &output_lock;
+ sink.output_io = self.root.io;
const subagents = self.dispatch != null and self.dispatch.?.subagents and self.dispatch.?.draft_subagents_enabled;
defer sink.deinit();
- var child_state: @import("acp_subagent_live.zig").State = .{ .out = self.out, .parent = self.session_id };
+ var child_state: @import("acp_subagent_live.zig").State = .{ .out = self.out, .parent = self.session_id, .output_lock = &output_lock };
if (subagents) @import("acp_subagent_live.zig").install(self.root.io, &child_state);
defer if (subagents) @import("acp_subagent_live.zig").uninstall(self.root.io);
self.root.out = &sink.writer;
@@ -103,6 +108,8 @@ pub const LiveTurn = struct {
sink.writer.flush() catch {};
main_mod.g_gui_mu.lockUncancelable(self.root.io);
defer main_mod.g_gui_mu.unlock(self.root.io);
+ output_lock.lockUncancelable(self.root.io);
+ defer output_lock.unlock(self.root.io);
@import("acp_usage.zig").writeBestEffort(self.out, self.session_id, &@import("pricing.zig").g_cost, self.root.io);
}
turn_trace.record(self.root, self.root.io, arena, text, turn_id, started, result, self.root.effectiveContextTokens(), before, &self.prev_turn_id, &self.prev_prompt_fp);
@@ -123,6 +130,8 @@ pub const LiveTurn = struct {
const report = try std.fmt.allocPrint(arena, "{s}\n\n{s}", .{ partial, marker });
try self.root.messages.append(try messages.textMessage(arena, "assistant", report));
try sink.writer.flush();
+ output_lock.lockUncancelable(self.root.io);
+ defer output_lock.unlock(self.root.io);
try proto.writeSessionUpdate(self.out, self.session_id, marker);
}
// #753: an API interruption is a failed turn, not a dead ACP
diff --git a/src/acp_permission.zig b/src/acp_permission.zig
index 9edd099a..4cc6179a 100644
--- a/src/acp_permission.zig
+++ b/src/acp_permission.zig
@@ -6,6 +6,7 @@ const util = @import("util.zig");
pub const Bridge = struct {
io: Io,
out: *Io.Writer,
+ output_lock: ?*Io.Mutex = null,
session: []const u8 = "",
mutex: Io.Mutex = .init,
ready: Io.Condition = .init,
@@ -18,6 +19,11 @@ pub const Bridge = struct {
pub fn handler(self: *Bridge) permission.Handler {
return .{ .ctx = self, .request = ask };
}
+ pub fn setOutputLock(self: *Bridge, lock: ?*Io.Mutex) void {
+ self.mutex.lockUncancelable(self.io);
+ defer self.mutex.unlock(self.io);
+ self.output_lock = lock;
+ }
pub fn cancel(self: *Bridge) void {
self.mutex.lockUncancelable(self.io);
defer self.mutex.unlock(self.io);
@@ -59,6 +65,8 @@ pub const Bridge = struct {
const main = @import("main.zig");
main.g_gui_mu.lockUncancelable(io);
defer main.g_gui_mu.unlock(io);
+ if (self.output_lock) |lock| lock.lockUncancelable(io);
+ defer if (self.output_lock) |lock| lock.unlock(io);
std.json.Stringify.value(.{ .jsonrpc = "2.0", .id = id, .method = "session/request_permission", .params = .{
.sessionId = self.session,
.toolCall = .{ .toolCallId = req.call_id, .title = req.description, .status = "pending" },
diff --git a/src/acp_stream.zig b/src/acp_stream.zig
index 9b70330a..caeb4a37 100644
--- a/src/acp_stream.zig
+++ b/src/acp_stream.zig
@@ -208,6 +208,8 @@ pub fn translateEvent(
/// Line-splitting writer: --json JSONL in, ACP session/update out.
pub const EventSink = struct {
out: *Io.Writer,
+ output_lock: ?*Io.Mutex = null,
+ output_io: ?Io = null,
session_id: *[]const u8,
saw_text: *bool,
/// Any text delta this turn (never reset) — the final chunk needs a
@@ -254,6 +256,10 @@ pub const EventSink = struct {
if (trimmed.len == 0) return;
var parsed = std.json.parseFromSlice(Value, self.gpa, trimmed, .{}) catch return;
defer parsed.deinit();
+ // Child-session notifications and ordinary root events share the
+ // transport writer. Both acquire this per-turn lock before output.
+ if (self.output_lock) |lock| lock.lockUncancelable(self.output_io.?);
+ defer if (self.output_lock) |lock| lock.unlock(self.output_io.?);
const kind = translateEvent(self.out, self.session_id.*, parsed.value, &self.last_id, &self.next_tool) catch return;
// saw_text means "the last thing streamed was answer text". A tool
// event resets it: a completion-tool turn streams its preamble, THEN
diff --git a/src/acp_subagent_live.zig b/src/acp_subagent_live.zig
index 1f0d0080..8f14df2d 100644
--- a/src/acp_subagent_live.zig
+++ b/src/acp_subagent_live.zig
@@ -11,6 +11,7 @@ const util = @import("util.zig");
pub const State = struct {
out: *Io.Writer,
parent: []const u8,
+ output_lock: *Io.Mutex,
};
var active: ?*State = null;
@@ -35,6 +36,8 @@ pub fn announce(io: Io, id: []const u8, name: []const u8, task: []const u8, pare
main.g_gui_mu.lockUncancelable(io);
defer main.g_gui_mu.unlock(io);
const state = active orelse return false;
+ state.output_lock.lockUncancelable(io);
+ defer state.output_lock.unlock(io);
proto.writeNotification(state.out, "session/update", .{ .sessionId = state.parent, .update = .{
.sessionUpdate = "subagent_update",
.subagentSessionId = id,
@@ -50,6 +53,8 @@ pub fn finish(io: Io, id: []const u8, outcome: []const u8, parent_call_id: []con
main.g_gui_mu.lockUncancelable(io);
defer main.g_gui_mu.unlock(io);
const state = active orelse return;
+ state.output_lock.lockUncancelable(io);
+ defer state.output_lock.unlock(io);
proto.writeNotification(state.out, "session/update", .{ .sessionId = state.parent, .update = .{
.sessionUpdate = "subagent_update",
.subagentSessionId = id,
@@ -78,6 +83,8 @@ pub const ChildSink = struct {
main.g_gui_mu.lockUncancelable(self.io);
defer main.g_gui_mu.unlock(self.io);
const state = active orelse return;
+ state.output_lock.lockUncancelable(self.io);
+ defer state.output_lock.unlock(self.io);
const w = state.out;
switch (stamped.event) {
.reasoning_delta => |v| stream.writeThought(w, self.id, v.text) catch return,
@@ -101,7 +108,8 @@ test "negotiated child stream announces before activity and terminates on parent
var buffer: [8192]u8 = undefined;
var out: Io.Writer = .fixed(&buffer);
const io = std.testing.io;
- var state: State = .{ .out = &out, .parent = "parent" };
+ var output_lock: Io.Mutex = .init;
+ var state: State = .{ .out = &out, .parent = "parent", .output_lock = &output_lock };
install(io, &state);
defer uninstall(io);
try std.testing.expect(announce(io, "child", "Scout", "Inspect the code", "spawn-1"));
diff --git a/src/schema_agents.zig b/src/schema_agents.zig
index 4d4e5db5..e653debf 100644
--- a/src/schema_agents.zig
+++ b/src/schema_agents.zig
@@ -3,9 +3,9 @@ const ToolSpec = @import("schema.zig").ToolSpec;
pub const subagent_spec = ToolSpec{
.name = "subagent",
- .desc = "Delegate a self-contained sidecar task; children have file, shell, codedb and skill tools, no parent context, and cannot spawn children. Brief once with context, prompt, established_facts, scope and deliverable. Keep critical-path work local; use disjoint write sets for parallel tasks. Do not set model without a user request or task-specific reason. agent selects a persona; system_prompt overrides it. Set retained=true to preserve conversation and workspace for follow-up and return a durable task_id; omitted/false leaves the worker ephemeral. Interactive calls run in background; headless calls return the report unless run_in_background=true. agent_message queues feedback without starting a turn; subagent_resume continues a completed worker with its history. agent_output fetches background results; wait_ms>0 waits in headless mode. Do not poll.",
+ .desc = "Delegate a sidecar task; children have file, shell, codedb and skill tools, no parent context, and cannot spawn children. Brief once with context, prompt, established_facts, scope and deliverable. Keep critical-path work local; use disjoint write sets for parallel tasks. Do not set model without a user request or task-specific reason. agent selects a persona; system_prompt overrides it. retained=true preserves history and workspace for follow-up; otherwise the worker is ephemeral. Interactive calls run in background by default; run_in_background=false waits for the child's report on every surface. Headless calls wait by default. agent_message queues feedback without starting a turn; subagent_resume continues a completed worker. agent_output fetches background results; wait_ms>0 waits in headless mode. Do not poll.",
.schema =
- \\{"type": "object", "properties": {"description": {"type": "string", "description": "Short label for logs, 3-5 words"}, "prompt": {"type": "string", "description": "Numbered steps and search hints; the complete task. Optional context/established_facts/scope/deliverable render as headed sections around this"}, "context": {"type": "string", "description": "Optional: repo and hard constraints the child must not re-derive"}, "established_facts": {"type": "string", "description": "Optional: observed facts, paths, and line numbers the child must treat as given"}, "scope": {"type": "string", "description": "Optional: what not to touch or broaden into"}, "deliverable": {"type": "string", "description": "Optional: required report shape; default is files changed, verified, skipped, open questions"}, "agent": {"type": "string", "description": "Optional: a named agent type (reviewer, researcher, implementer, skeptic, or a .harness/agents/ name) whose persona the child runs with"}, "system_prompt": {"type": "string", "description": "Optional: replace the child's system prompt with a custom one (overrides agent)"}, "model": {"type": "string", "description": "Optional: run THIS child on an exact model name available on the current provider (e.g. \"gpt-5.6-luna\"). Highest precedence — beats the persona's own pin and the session default. Ignored (spawn still runs on the session default, with a trace note) if the name is unknown, ambiguous, or not served by this provider — except that a logged-in flat-rate subscription serving the exact name honors it (sub-first routing; the login is the standing consent). For a portable 'cheapest seat' ask, tier is still the better lever."}, "tier": {"type": "string", "enum": ["frontier", "mid", "small"], "description": "Optional: run THIS child on a rung of the current provider's model ladder instead of an exact name — frontier (planner/judge class), mid (reviewers, implementers, researchers), small (mechanical transform/extract/label). Prefer this over model: it stays correct when the root model changes. If the provider has no ladder or no model at that rung, sub-first routing seats the child on a logged-in flat-rate subscription's rung when one exists (no login → the pin is ignored); model wins if both are given."}, "effort": {"type": "string", "enum": ["low", "medium", "high", "xhigh", "max", "none"], "description": "Optional: reasoning effort for THIS child — beats the persona's effort: frontmatter; unpinned children run at medium. An axis independent of model/tier: an effort-only override keeps the persona's model pin. none disables thinking only on supported binary-thinking routes and is rejected before child inference elsewhere. An off-vocabulary value is ignored with a trace note."}, "isolation": {"type": "string", "enum": ["shared_cwd", "worktree"], "description": "Optional: independent / fan-out children default to \"worktree\" (own branch + checkout; clean unchanged trees are removed unless retained=true; dirty or uniquely committed trees are kept + reported). Use \"shared_cwd\" only for same-branch collaboration (review + fix, a pipeline). isolation_fallback:true is the only way a failed git worktree add may share the caller tree."}, "isolation_fallback": {"type": "boolean", "description": "Optional: if isolation:\"worktree\" fails to set up (not a git repo, git error), run in the shared working tree instead of failing the spawn. Default false (fails the spawn on setup failure)."}, "retained": {"type": "boolean", "description": "Optional: persist conversation and workspace for subagent_resume (default false)."}, "run_in_background": {"type": "boolean", "description": "Optional: start this subagent asynchronously and return its agent id immediately instead of waiting for it to finish (headless default false; interactive REPL always backgrounds direct subagents). Do not poll; headless agent_output(wait_ms>0) blocks until it finishes. A spawn at the live concurrency cap is refused; do not spawn a child to clean up a finished worktree."}}, "required": ["description", "prompt"]}
+ \\{"type": "object", "properties": {"description": {"type": "string", "description": "Short label for logs, 3-5 words"}, "prompt": {"type": "string", "description": "Numbered steps and search hints; the complete task. Optional context/established_facts/scope/deliverable render as headed sections around this"}, "context": {"type": "string", "description": "Optional: repo and hard constraints the child must not re-derive"}, "established_facts": {"type": "string", "description": "Optional: observed facts, paths, and line numbers the child must treat as given"}, "scope": {"type": "string", "description": "Optional: what not to touch or broaden into"}, "deliverable": {"type": "string", "description": "Optional: required report shape; default is files changed, verified, skipped, open questions"}, "agent": {"type": "string", "description": "Optional: a named agent type (reviewer, researcher, implementer, skeptic, or a .harness/agents/ name) whose persona the child runs with"}, "system_prompt": {"type": "string", "description": "Optional: replace the child's system prompt with a custom one (overrides agent)"}, "model": {"type": "string", "description": "Optional: run THIS child on an exact model name available on the current provider (e.g. \"gpt-5.6-luna\"). Highest precedence — beats the persona's own pin and the session default. Ignored (spawn still runs on the session default, with a trace note) if the name is unknown, ambiguous, or not served by this provider — except that a logged-in flat-rate subscription serving the exact name honors it (sub-first routing; the login is the standing consent). For a portable 'cheapest seat' ask, tier is still the better lever."}, "tier": {"type": "string", "enum": ["frontier", "mid", "small"], "description": "Optional: run THIS child on a rung of the current provider's model ladder instead of an exact name — frontier (planner/judge class), mid (reviewers, implementers, researchers), small (mechanical transform/extract/label). Prefer this over model: it stays correct when the root model changes. If the provider has no ladder or no model at that rung, sub-first routing seats the child on a logged-in flat-rate subscription's rung when one exists (no login → the pin is ignored); model wins if both are given."}, "effort": {"type": "string", "enum": ["low", "medium", "high", "xhigh", "max", "none"], "description": "Optional: reasoning effort for THIS child — beats the persona's effort: frontmatter; unpinned children run at medium. An axis independent of model/tier: an effort-only override keeps the persona's model pin. none disables thinking only on supported binary-thinking routes and is rejected before child inference elsewhere. An off-vocabulary value is ignored with a trace note."}, "isolation": {"type": "string", "enum": ["shared_cwd", "worktree"], "description": "Optional: independent / fan-out children default to \"worktree\" (own branch + checkout; clean unchanged trees are removed unless retained=true; dirty or uniquely committed trees are kept + reported). Use \"shared_cwd\" only for same-branch collaboration (review + fix, a pipeline). isolation_fallback:true is the only way a failed git worktree add may share the caller tree."}, "isolation_fallback": {"type": "boolean", "description": "Optional: if isolation:\"worktree\" fails to set up (not a git repo, git error), run in the shared working tree instead of failing the spawn. Default false (fails the spawn on setup failure)."}, "retained": {"type": "boolean", "description": "Optional: persist conversation and workspace for subagent_resume (default false)."}, "run_in_background": {"type": "boolean", "description": "Optional: true starts asynchronously and immediately returns an agent id; false explicitly waits for the child report on every surface. Defaults to true in interactive sessions and false in headless sessions. Do not poll; agent_output(wait_ms>0) blocks until it finishes. A spawn at the live concurrency cap is refused; do not spawn a child to clean up a finished worktree."}}, "required": ["description", "prompt"]}
,
};
diff --git a/src/subagent.zig b/src/subagent.zig
index 94d0f8ea..9f48060b 100644
--- a/src/subagent.zig
+++ b/src/subagent.zig
@@ -74,7 +74,13 @@ pub fn execSubagent(ctx: ToolCtx, input: Value) !ToolOutput {
if (ask.pin.effort_outcome == .unsupported_effort) return .{ .text = try ctx.gpa.dupe(u8, "subagent: Off is unsupported by this model; choose a supported effort"), .is_error = true };
if (ask.blocked) return .{ .text = try vision_ask.blockMessage(ctx.gpa, ask), .is_error = true };
const keep = tools.json_args.flag(input, "retained");
- if (ctx.interactive_children or tools.json_args.flag(input, "run_in_background")) {
+ // Interactive roots default to detached workers, but an explicit false
+ // asks for a foreground child that completes within this prompt turn.
+ const explicit_foreground = switch (obj.get("run_in_background") orelse .null) {
+ .bool => |value| !value,
+ else => false,
+ };
+ if ((ctx.interactive_children and !explicit_foreground) or tools.json_args.flag(input, "run_in_background")) {
var child = ctx;
if (keep) child.retained_worker = try @import("subagent_retained.zig").create(ctx, label);
errdefer if (keep) child.retained_worker.?.deinit(ctx.gpa, ctx.io);