graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
feat(acp): stream background child activity across turns
Rach Pradhan55480a3871b3
diff --git a/build.zig b/build.zigindex 64c63d82..91a82372 100644--- a/build.zig+++ b/build.zig@@ -146,6 +146,9 @@ pub fn build(b: *std.Build) void {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 acp_background_child_test = b.addSystemCommand(&.{ "python3", "scripts/test-acp-background-subagent.py" });+ acp_background_child_test.addArtifactArg(exe);+ test_step.dependOn(&acp_background_child_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/adr/0196-background-acp-agents-use-a-graff-extension.md b/docs/adr/0196-background-acp-agents-use-a-graff-extension.mdnew file mode 100644index 00000000..eecf43ac--- /dev/null+++ b/docs/adr/0196-background-acp-agents-use-a-graff-extension.md@@ -0,0 +1,30 @@+# 0196. Background ACP workers use a Graff extension++Status: accepted 2026-09-24++## Context++The draft ACP child-session update expects the child to terminate before its+parent prompt returns. A detached Graff worker can continue through later+parent turns. The draft update would either close that worker too early or send+activity outside its defined lifetime. The current child activity snapshots+are bounded and cannot provide complete historical ACP replay.++## Decision++Keep draft `subagent_update` for negotiated foreground children. A client may+separately request `clientCapabilities._meta["graff/backgroundSubagents"] = true`.+Graff advertises this extension in `agentCapabilities._meta` and, only for+opted-in clients, sends `graff/subagent_event` notifications for detached+children. Each notification carries parent session, child session, parent tool+call, and a per-child sequence number. Spawn precedes semantic activity, and a+terminal state follows it. The ACP connection owns the output lock across+prompt boundaries and detaches the worker emitter before closing stdout.++## Consequences++Clients can render a live background child without treating the parent prompt+as the child's lifetime. Standard ACP clients continue to see the parent tool+call and result. This extension currently streams only while the ACP process+is connected; a reconnect must use the bounded `graff/agents` snapshot and+report truncation rather than claim exact draft child-session replay.diff --git a/docs/adr/README.md b/docs/adr/README.mdindex 64add5d8..1dceacaa 100644--- a/docs/adr/README.md+++ b/docs/adr/README.md@@ -221,6 +221,7 @@ record only when you need the evidence or the edge cases.| [0193](0193-jev-selects-effort-only.md) | Optional Jev selects only supported session effort at the next request boundary; arbitrary judgments are not exposed. || [0194](0194-acp-child-sessions-are-an-opt-in-preview.md) | Draft ACP child sessions stream live only with explicit opt-in; durable replay is required before default enablement. || [0195](0195-embedded-browser-replaces-kuri.md) | Desktop browser uses embedded Chromium, web preview uses the paired extension, and CLI fetch uses built-in HTTP without a sidecar. |+| [0196](0196-background-acp-agents-use-a-graff-extension.md) | Detached ACP workers stream through an opted-in Graff extension with connection-lifetime output ownership; draft child sessions remain foreground-only. |## When to write onediff --git a/scripts/test-acp-background-subagent.py b/scripts/test-acp-background-subagent.pynew file mode 100644index 00000000..bbd4375c--- /dev/null+++ b/scripts/test-acp-background-subagent.py@@ -0,0 +1,149 @@+#!/usr/bin/env python3+"""Offline ACP background-child stream across parent prompt boundaries."""+import importlib.util+import json+import queue+import sys+import tempfile+import threading+import time+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)+++class Model(load.ScriptedModel):+ def __init__(self):+ super().__init__([], exhausted_text='unexpected model request')+ self.child_started = threading.Event()+ self.release_child = threading.Event()+ self.root_calls = 0++ def next_reply(self, body):+ names = [item.get('function', item).get('name') for item in body.get('tools', [])]+ with self._lock:+ self.requests.append(body)+ if 'subagent' in names:+ self.root_calls += 1+ number = self.root_calls+ elif names:+ number = 0+ else:+ return {'text': 'Short title'}+ if number == 0:+ self.child_started.set()+ assert self.release_child.wait(15), 'child release timed out'+ return {'text': 'The child finished after the parent prompt.'}+ if number == 1:+ return {'tool': 'subagent', 'arguments': {+ 'description': 'Inspect in background', 'prompt': 'Return a short report.',+ 'isolation': 'shared_cwd', 'run_in_background': True}}+ return {'text': 'Parent turn finished while child runs.'}+++def drain_until(client, predicate, timeout=8):+ deadline = time.monotonic() + timeout+ while time.monotonic() < deadline:+ while b'\n' in client.pending:+ line, client.pending = client.pending.split(b'\n', 1)+ event = json.loads(line) # A torn/interleaved JSON frame fails here.+ client.events.append(event)+ if predicate(event):+ return event+ try:+ chunk = client.chunks.get(timeout=.1)+ except queue.Empty:+ continue+ assert chunk is not None, 'ACP exited before child terminal state'+ client.pending += chunk+ raise AssertionError('background child notification timed out')+++def child_events(client):+ return [row['params'] for row in client.events if row.get('method') == 'graff/subagent_event']+++def run(binary, capability=True, cancel=False, disconnect=False):+ with tempfile.TemporaryDirectory(prefix='graff-acp-background-') as temporary:+ work = Path(temporary)+ home = work / 'home'+ home.mkdir()+ model = Model()+ port = model.start(0)+ client = load.Acp(binary, work, home, port, extra_env={'GRAFF_NO_NATIVE_FOLD': '1'},+ extra_args=('--max-model-calls', '6', '--max-run-tool-calls', '8'))+ try:+ caps = {'_meta': {'graff/backgroundSubagents': True}} if capability else {}+ init = client.request('initialize', {'protocolVersion': 1, 'clientCapabilities': caps})+ assert init['result']['agentCapabilities']['_meta']['graff/backgroundSubagents'] is True+ sid = client.request('session/new', {'cwd': str(work), 'mcpServers': []})['result']['sessionId']+ first = client.request('session/prompt', {'sessionId': sid,+ 'prompt': [{'type': 'text', 'text': 'Delegate in the background.'}]}, timeout=15)+ assert first['result']['stopReason'] == 'end_turn', first+ assert model.child_started.wait(8), 'child did not start'+ assert not model.release_child.is_set()+ second = client.request('session/prompt', {'sessionId': sid,+ 'prompt': [{'type': 'text', 'text': 'Continue while the child runs.'}]}, timeout=15)+ assert second['result']['stopReason'] == 'end_turn', second+ rows = child_events(client)+ if not capability:+ assert not rows, rows+ return+ assert rows and rows[0]['event']['type'] == 'spawn', rows+ spawn = rows[0]+ assert spawn['parentSessionId'] == sid and spawn['seq'] == 0, spawn+ assert spawn['parentToolCallId'], spawn+ assert all(row['subagentSessionId'] == spawn['subagentSessionId'] and+ row['parentToolCallId'] == spawn['parentToolCallId'] for row in rows), rows+ assert not any(row['event']['type'] == 'terminal' for row in rows), rows+ if disconnect:+ client.proc.stdin.close()+ # ACP detaches its emitter before waiting for the held worker+ # during process teardown. Releasing it afterward must not+ # write a frame into the closed connection.+ time.sleep(.2)+ model.release_child.set()+ assert client.proc.wait(timeout=8) == 0+ while True:+ try:+ chunk = client.chunks.get_nowait()+ except queue.Empty:+ break+ if chunk is not None:+ client.pending += chunk+ while b'\n' in client.pending:+ line, client.pending = client.pending.split(b'\n', 1)+ client.events.append(json.loads(line))+ assert not client.pending, 'partial JSON frame on ACP teardown'+ assert not any(row['event']['type'] == 'terminal' for row in child_events(client))+ return+ if cancel:+ agents = client.request('graff/agents', {'action': 'list', 'scope': 'device'})+ parent = next(row for row in agents['result']['agents'] if row['session'] == sid)+ client.request('graff/agents', {'action': 'cancel', 'scope': 'device',+ 'target': sid, 'startId': parent['startId'],+ 'child': spawn['subagentSessionId']})+ model.release_child.set()+ terminal = drain_until(client, lambda row: row.get('method') == 'graff/subagent_event'+ and row['params']['event']['type'] == 'terminal')+ assert terminal['params']['event']['state'] == ('cancelled' if cancel else 'completed')+ rows = child_events(client)+ assert [row['seq'] for row in rows] == list(range(len(rows))), rows+ assert rows[-1]['event']['type'] == 'terminal', rows+ assert rows[-1]['seq'] > 0, rows+ finally:+ model.release_child.set()+ client.close()+ model.stop()+++if __name__ == '__main__':+ binary = Path(sys.argv[1] if len(sys.argv) > 1 else REPO / 'zig-out/bin/graff').resolve()+ run(binary, capability=False)+ run(binary)+ run(binary, cancel=True)+ run(binary, disconnect=True)+ print('ACP background subagents: opt-in, cross-turn stream, cancellation, ordered JSON frames, teardown')diff --git a/src/acp.zig b/src/acp.zigindex a620b912..c36f86a6 100644--- a/src/acp.zig+++ b/src/acp.zig@@ -207,7 +207,12 @@ pub fn runAcpCommand(gpa: Allocator, io: Io, environ_map: anytype, root: *agent_engine.implementation_version = main_mod.harness_version;engine.cancel_flag.store(false, .release);engine.on_cancel = syncEscCancel;- var permission_bridge: @import("acp_permission.zig").Bridge = .{ .io = io, .out = out };+ var transport_lock: Io.Mutex = .init;+ var framed: @import("acp_line_writer.zig").LineWriter = undefined;+ framed.init(io, out, &transport_lock);+ defer framed.deinit();+ const wire = &framed.writer;+ var permission_bridge: @import("acp_permission.zig").Bridge = .{ .io = io, .out = wire };const previous_permission = root.permission;root.permission = permission_bridge.handler();defer root.permission = previous_permission;@@ -223,7 +228,7 @@ pub fn runAcpCommand(gpa: Allocator, io: Io, environ_map: anytype, root: *agent_}@import("acp_ask.zig").attach(io, gpa);defer @import("acp_ask.zig").detach();- var live: LiveTurn = .{ .root = root, .keys = keys, .out = out, .inbox = &inbox };+ var live: LiveTurn = .{ .root = root, .keys = keys, .out = wire, .inbox = &inbox };var d: Dispatch = .{.turn = LiveTurn.run,.error_message = LiveTurn.errorMessage,@@ -238,21 +243,28 @@ pub fn runAcpCommand(gpa: Allocator, io: Io, environ_map: anytype, root: *agent_.draft_subagents_enabled = std.mem.eql(u8, environ_map.get("GRAFF_ACP_DRAFT_SUBAGENTS") orelse "", "1"),};@import("acp_session_load.zig").configure(&d, &live);+ var background_state: @import("acp_subagent_live.zig").BackgroundState = .{+ .out = out,+ .output_lock = &transport_lock,+ };+ @import("acp_subagent_live.zig").installBackground(io, &background_state);+ defer @import("acp_subagent_live.zig").uninstallBackground(io);while (true) {const event = (inbox.wait(arena) catch break) orelse break;switch (event) {- .tick => @import("acp_idle.zig").maybeWake(&d, arena, out, io, root.session_name) catch |err| {+ .tick => @import("acp_idle.zig").maybeWake(&d, arena, wire, io, root.session_name) catch |err| {std.debug.print("acp: idle wake failed: {t}\n", .{err});},.line => |line| {- handleLine(&d, arena, out, line) catch |err| {+ handleLine(&d, arena, wire, line) catch |err| {std.debug.print("acp: dispatch failed: {t}\n", .{err});break;};- @import("acp_idle.zig").startupEffortNotice(&d, root, out) catch break;+ @import("acp_subagent_live.zig").configureBackground(io, d.session_id orelse "", d.background_subagents);+ @import("acp_idle.zig").startupEffortNotice(&d, root, wire) catch break;},}- out.flush() catch break;+ wire.flush() catch break;}session.saveSession(root, arena, root.session_name) catch {};root.md_buf.deinit(gpa);@@ -572,29 +584,3 @@ test "OpenAI effort menu omits Max and keeps Ultra on the Responses wire" {try testing.expectEqualStrings("xhigh", extra_request.object.get("reasoning").?.object.get("effort").?.string);}}--test "handleLine: live context occupancy precedes the terminal prompt reply" {- const was_cancelled = engine.cancel_flag.swap(false, .acq_rel);- defer engine.cancel_flag.store(was_cancelled, .release);- const extra = engine.extra_cancelled;- engine.extra_cancelled = null;- defer engine.extra_cancelled = extra;- var state = std.heap.ArenaAllocator.init(testing.allocator);- defer state.deinit();- const a = state.allocator();- var buf: [16384]u8 = undefined;- var w: Io.Writer = .fixed(&buf);- const meter = struct {- fn read(_: *anyopaque) engine.Meter {- return .{ .used = 123, .window = 1000 };- }- }.read;- var d: Dispatch = .{ .turn = echoTurn, .ctx = undefined, .meter = meter };- try handleLine(&d, a, &w, "{\"id\":1,\"method\":\"session/new\"}");- w = .fixed(&buf);- try handleLine(&d, a, &w, "{\"id\":2,\"method\":\"session/prompt\",\"params\":{\"prompt\":[{\"type\":\"text\",\"text\":\"hi\"}]}}");- const output = w.buffered();- const occupancy = std.mem.indexOf(u8, output, "\"gui_context_meter\",\"used\":123,\"window\":1000") orelse return error.MissingMeter;- const terminal = std.mem.indexOf(u8, output, "\"stopReason\":\"end_turn\"") orelse return error.MissingTerminalReply;- try testing.expect(occupancy < terminal);-}diff --git a/src/acp_engine.zig b/src/acp_engine.zigindex dbe2f4e5..ffb2e28c 100644--- a/src/acp_engine.zig+++ b/src/acp_engine.zig@@ -74,6 +74,9 @@ pub const Dispatch = struct {cwd: []const u8 = "",/// ACP v1 draft subagent updates are opt-in at initialize.subagents: bool = false,+ /// Graff extension: detached children may outlive a prompt. The client+ /// must request it independently of the draft ACP child-session shape.+ background_subagents: bool = false,/// The current implementation streams live child activity; historical/// child replay is not yet available, so CLI leaves this off by default.draft_subagents_enabled: bool = false,@@ -88,6 +91,17 @@ fn supportsSubagents(params: ?std.json.Value) bool {return subagents == .object;}+fn supportsBackgroundSubagents(params: ?std.json.Value) bool {+ const root = params orelse return false;+ if (root != .object) return false;+ const caps = root.object.get("clientCapabilities") orelse return false;+ if (caps != .object) return false;+ const meta = caps.object.get("_meta") orelse return false;+ if (meta != .object) return false;+ const value = meta.object.get("graff/backgroundSubagents") orelse return false;+ return value == .bool and value.bool;+}+pub fn configOptions(d: *Dispatch, arena: Allocator) ![]const ConfigOption {const config = d.config orelse return &.{};const option = try config(d.ctx, arena) orelse return &.{};@@ -219,12 +233,38 @@ test "slash commands refresh occupancy before their terminal response" {try std.testing.expect(meter_pos < end_pos);}+test "live context occupancy precedes the terminal prompt reply" {+ const was_cancelled = cancel_flag.swap(false, .acq_rel);+ defer cancel_flag.store(was_cancelled, .release);+ const extra = extra_cancelled;+ extra_cancelled = null;+ defer extra_cancelled = extra;+ var state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer state.deinit();+ const a = state.allocator();+ var buf: [16384]u8 = undefined;+ var w: Io.Writer = .fixed(&buf);+ const meter = struct {+ fn read(_: *anyopaque) Meter {+ return .{ .used = 123, .window = 1000 };+ }+ }.read;+ var d: Dispatch = .{ .turn = echoTurn, .ctx = undefined, .meter = meter };+ try handleLine(&d, a, &w, "{\"id\":1,\"method\":\"session/new\"}");+ w = .fixed(&buf);+ try handleLine(&d, a, &w, "{\"id\":2,\"method\":\"session/prompt\",\"params\":{\"prompt\":[{\"type\":\"text\",\"text\":\"hi\"}]}}");+ const output = w.buffered();+ const occupancy = std.mem.indexOf(u8, output, "\"gui_context_meter\",\"used\":123,\"window\":1000") orelse return error.MissingMeter;+ const terminal = std.mem.indexOf(u8, output, "\"stopReason\":\"end_turn\"") orelse return error.MissingTerminalReply;+ try std.testing.expect(occupancy < terminal);+}+fn respondInitialize(w: *Io.Writer, req: proto.Request, can_load: bool) !void {return respond(w, req, .{.protocolVersion = negotiateVersion(req.params),.agentCapabilities = .{.loadSession = can_load,- ._meta = .{ .@"codegraff/usage" = can_load },+ ._meta = .{ .@"codegraff/usage" = can_load, .@"graff/backgroundSubagents" = true },.promptCapabilities = proto.PromptCapabilities{},},.agentInfo = proto.AgentImplementation{ .version = implementation_version },@@ -245,6 +285,7 @@ pub fn handleLine(d: *Dispatch, arena: Allocator, w: *Io.Writer, line: []const uconst req = parseRequest(arena, line) orelse return;if (std.mem.eql(u8, req.method, "initialize")) {d.subagents = supportsSubagents(req.params);+ d.background_subagents = supportsBackgroundSubagents(req.params);return respondInitialize(w, req, d.load_session != null);}if (std.mem.eql(u8, req.method, "authenticate"))@@ -352,6 +393,21 @@ test "subagent draft updates require explicit client capability" {try std.testing.expect(!dispatch.subagents);}+test "background child extension negotiates independently of draft sessions" {+ var arena = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena.deinit();+ var buf: [2048]u8 = undefined;+ var out: Io.Writer = .fixed(&buf);+ var dispatch: Dispatch = .{ .turn = echoTurn, .ctx = undefined };+ try handleLine(&dispatch, arena.allocator(), &out, "{\"id\":1,\"method\":\"initialize\",\"params\":{\"clientCapabilities\":{\"_meta\":{\"graff/backgroundSubagents\":true}}}}");+ try std.testing.expect(dispatch.background_subagents);+ try std.testing.expect(!dispatch.subagents);+ try std.testing.expect(std.mem.indexOf(u8, out.buffered(), "\"graff/backgroundSubagents\":true") != null);+ out = .fixed(&buf);+ try handleLine(&dispatch, arena.allocator(), &out, "{\"id\":2,\"method\":\"initialize\",\"params\":{\"clientCapabilities\":{\"_meta\":{\"graff/backgroundSubagents\":false}}}}");+ try std.testing.expect(!dispatch.background_subagents);+}+test "session/new reports an isolated checkout when Dispatch.cwd is set" {var state = std.heap.ArenaAllocator.init(std.testing.allocator);defer state.deinit();diff --git a/src/acp_line_writer.zig b/src/acp_line_writer.zignew file mode 100644index 00000000..5052cee1--- /dev/null+++ b/src/acp_line_writer.zig@@ -0,0 +1,70 @@+//! Serialize complete ACP JSONL frames with notifications from background+//! workers. Each writer has its own staging buffer; the transport is shared.+const std = @import("std");+const Io = std.Io;++pub const LineWriter = struct {+ io: Io,+ out: *Io.Writer,+ lock: *Io.Mutex,+ pending: std.ArrayList(u8) = .empty,+ buf: [4096]u8 = undefined,+ writer: Io.Writer = undefined,++ const vtable: Io.Writer.VTable = .{ .drain = drain };++ pub fn init(self: *LineWriter, io: Io, out: *Io.Writer, lock: *Io.Mutex) void {+ self.* = .{ .io = io, .out = out, .lock = lock, .writer = .{ .vtable = &vtable, .buffer = &self.buf, .end = 0 } };+ }++ pub fn deinit(self: *LineWriter) void {+ self.writer.flush() catch {};+ self.pending.deinit(std.heap.page_allocator);+ }++ fn writeLine(self: *LineWriter, line: []const u8) Io.Writer.Error!void {+ self.lock.lockUncancelable(self.io);+ defer self.lock.unlock(self.io);+ try self.out.writeAll(line);+ try self.out.flush();+ }++ fn feed(self: *LineWriter, bytes: []const u8) Io.Writer.Error!void {+ self.pending.appendSlice(std.heap.page_allocator, bytes) catch return error.WriteFailed;+ while (std.mem.indexOfScalar(u8, self.pending.items, '\n')) |end| {+ try self.writeLine(self.pending.items[0 .. end + 1]);+ std.mem.copyForwards(u8, self.pending.items, self.pending.items[end + 1 ..]);+ self.pending.shrinkRetainingCapacity(self.pending.items.len - end - 1);+ }+ }++ fn drain(w: *Io.Writer, data: []const []const u8, splat: usize) Io.Writer.Error!usize {+ const self: *LineWriter = @alignCast(@fieldParentPtr("writer", w));+ try self.feed(w.buffer[0..w.end]);+ w.end = 0;+ var n: usize = 0;+ for (data[0 .. data.len - 1]) |part| {+ try self.feed(part);+ n += part.len;+ }+ const pattern = data[data.len - 1];+ for (0..splat) |_| try self.feed(pattern);+ return n + pattern.len * splat;+ }+};++test "ACP writer does not expose partial JSON lines" {+ const io = std.testing.io;+ var transport_buf: [256]u8 = undefined;+ var transport: Io.Writer = .fixed(&transport_buf);+ var lock: Io.Mutex = .init;+ var framed: LineWriter = undefined;+ framed.init(io, &transport, &lock);+ defer framed.deinit();+ try framed.writer.writeAll("{\"id\":1");+ try framed.writer.flush();+ try std.testing.expectEqual(@as(usize, 0), transport.buffered().len);+ try framed.writer.writeAll("}\n{\"id\":2}\n");+ try framed.writer.flush();+ try std.testing.expectEqualStrings("{\"id\":1}\n{\"id\":2}\n", transport.buffered());+}diff --git a/src/acp_subagent_live.zig b/src/acp_subagent_live.zigindex 8f14df2d..d8f57256 100644--- a/src/acp_subagent_live.zig+++ b/src/acp_subagent_live.zig@@ -16,6 +16,69 @@ pub const State = struct {var active: ?*State = null;+/// Connection-owned extension state. Unlike `active`, this survives parent+/// prompt boundaries so detached workers can keep reporting their progress.+pub const BackgroundState = struct {+ out: *Io.Writer,+ output_lock: *Io.Mutex,+ parent: []const u8 = "",+ enabled: bool = false,+};++var background: ?*BackgroundState = null;++pub fn installBackground(io: Io, state: *BackgroundState) void {+ main.g_gui_mu.lockUncancelable(io);+ defer main.g_gui_mu.unlock(io);+ background = state;+}++/// Detach before the ACP transport is destroyed. Child jobs can still finish+/// during the parent process's final reap, but must not write to a dead pipe.+pub fn uninstallBackground(io: Io) void {+ main.g_gui_mu.lockUncancelable(io);+ defer main.g_gui_mu.unlock(io);+ background = null;+}++pub fn configureBackground(io: Io, parent: []const u8, enabled: bool) void {+ main.g_gui_mu.lockUncancelable(io);+ defer main.g_gui_mu.unlock(io);+ const state = background orelse return;+ state.parent = parent;+ state.enabled = enabled;+}++fn backgroundSend(io: Io, id: []const u8, parent_call_id: []const u8, seq: u64, event: anytype) bool {+ main.g_gui_mu.lockUncancelable(io);+ defer main.g_gui_mu.unlock(io);+ const state = background orelse return false;+ if (!state.enabled or state.parent.len == 0) return false;+ state.output_lock.lockUncancelable(io);+ defer state.output_lock.unlock(io);+ proto.writeNotification(state.out, "graff/subagent_event", .{+ .parentSessionId = state.parent,+ .subagentSessionId = id,+ .parentToolCallId = parent_call_id,+ .seq = seq,+ .event = event,+ }) catch return false;+ state.out.flush() catch {};+ return true;+}++pub fn announceBackground(io: Io, id: []const u8, name: []const u8, task: []const u8, parent_call_id: []const u8) bool {+ return backgroundSend(io, id, parent_call_id, 0, .{+ .type = "spawn",+ .name = util.utf8Prefix(name, 256),+ .task = util.utf8Prefix(task, 2048),+ });+}++pub fn finishBackground(io: Io, id: []const u8, parent_call_id: []const u8, seq: u64, outcome: []const u8) void {+ _ = backgroundSend(io, id, parent_call_id, seq, .{ .type = "terminal", .state = outcome });+}+pub fn eligible(kind: []const u8, depth: u8, detached: bool) bool {return depth == 0 and !detached and std.mem.eql(u8, kind, "subagent");}@@ -70,6 +133,8 @@ pub const ChildSink = struct {id: []const u8,io: Io,recorder: ?sink.EngineSink = null,+ background_call_id: ?[]const u8 = null,+ seq: u64 = 1,pub fn engineSink(self: *ChildSink) sink.EngineSink {return .{ .ctx = self, .vt = &vtable };@@ -80,6 +145,10 @@ pub const ChildSink = struct {fn emit(ctx: *anyopaque, stamped: sink.Stamped) void {const self: *ChildSink = @ptrCast(@alignCast(ctx));if (self.recorder) |record| record.vt.emit(record.ctx, stamped);+ if (self.background_call_id) |call_id| {+ self.emitBackground(stamped, call_id);+ return;+ }main.g_gui_mu.lockUncancelable(self.io);defer main.g_gui_mu.unlock(self.io);const state = active orelse return;@@ -102,6 +171,35 @@ pub const ChildSink = struct {}w.flush() catch {};}++ fn emitBackground(self: *ChildSink, stamped: sink.Stamped, call_id: []const u8) void {+ var arena_state = std.heap.ArenaAllocator.init(std.heap.page_allocator);+ defer arena_state.deinit();+ const a = arena_state.allocator();+ var bytes: Io.Writer.Allocating = .init(a);+ defer bytes.deinit();+ const w = &bytes.writer;+ switch (stamped.event) {+ .reasoning_delta => |v| stream.writeThought(w, self.id, v.text) catch return,+ .text_delta => |v| stream.writeMessage(w, self.id, v.text) catch return,+ .tool_call_announced => |v| {+ if (v.ask_user or std.mem.eql(u8, v.name, "attempt_completion")) return;+ stream.writeToolCall(w, self.id, v.id, v.name, v.input) catch return;+ },+ .tool_result => |v| {+ if (v.ask_user or std.mem.eql(u8, v.name, "attempt_completion")) return;+ stream.writeToolDone(w, self.id, v.id, v.is_error or v.cancelled, v.text) catch return;+ },+ .tool_rejected => |v| stream.writeToolDone(w, self.id, v.id, true, v.message) catch return,+ else => return,+ }+ const parsed = std.json.parseFromSliceLeaky(std.json.Value, a, w.buffered(), .{}) catch return;+ const params = parsed.object.get("params") orelse return;+ if (params != .object) return;+ const update = params.object.get("update") orelse return;+ if (backgroundSend(self.io, self.id, call_id, self.seq, .{ .type = "update", .update = update }))+ self.seq += 1;+ }};test "negotiated child stream announces before activity and terminates on parent" {diff --git a/src/main.zig b/src/main.zigindex 59ec1a60..8a41ea9c 100644--- a/src/main.zig+++ b/src/main.zig@@ -593,7 +593,7 @@ test { // ── Unit tests (`zig build test`): pull in tests from imported modu_ = .{ @import("presence_accord.zig"), @import("peer_idle.zig"), @import("acp_idle.zig"), @import("presence_chan.zig"), @import("presence_record.zig"), @import("daddy.zig"), @import("peer_inbox_content_test.zig"), @import("peer_inbox_failure_test.zig"), @import("peer_inbox_storage_test.zig"), @import("peer_inbox_sequence_test.zig"), @import("peer_inbox_snapshot_test.zig") };_ = @import("acp_agents.zig");_ = .{ @import("subagent_activity.zig"), @import("subagent_interactive.zig"), @import("subagent_recovery.zig"), @import("subagent_retained.zig"), @import("subagent_run_tests.zig") };- _ = .{ @import("acp_agent_activity.zig"), @import("acp_subagent_live.zig") };+ _ = .{ @import("acp_agent_activity.zig"), @import("acp_subagent_live.zig"), @import("acp_line_writer.zig") };_ = @import("acp_replay.zig");_ = @import("read_image.zig");_ = .{ @import("pr_local_checks.zig"), @import("mcp_names.zig"), @import("workspace_history.zig"), @import("file_worktree.zig"), @import("mcp_turn_context.zig"), @import("review_deadline.zig"), @import("issue_cmd.zig"), @import("shell_tool.zig"), @import("acp_ask.zig"), @import("side_steer.zig"), @import("task_workspace_tests.zig"), @import("workspace_prepare_tests.zig"), @import("worktree_reap.zig") };diff --git a/src/subagent_owned.zig b/src/subagent_owned.zigindex df8f290f..3c92639a 100644--- a/src/subagent_owned.zig+++ b/src/subagent_owned.zig@@ -30,6 +30,7 @@ pub const Owned = struct {copy.plan_read_owner = null;copy.worker_family = try a.dupe(u8, source.worker_family);copy.session_name = try a.dupe(u8, source.session_name);+ copy.parent_tool_call_id = try a.dupe(u8, source.parent_tool_call_id);if (source.worker_id) |id| copy.worker_id = try a.dupe(u8, id);if (source.approvals) |ap| {ap.mutex.lockUncancelable(source.io);diff --git a/src/subagent_run.zig b/src/subagent_run.zigindex 8de25fe8..5ea50c05 100644--- a/src/subagent_run.zig+++ b/src/subagent_run.zig@@ -357,15 +357,24 @@ pub fn runSub(ctx: ToolCtx, kind: []const u8, label: []const u8, prompt: []const}// ACP v1's draft child-session scope is one foreground prompt. Detached- // workers keep the existing graff/agents inspection path: they may finish- // after session/prompt has returned, which v1 child sessions forbid.+ // workers use a separate opted-in Graff notification and retain the+ // graff/agents inspection path after session/prompt returns.const acp_children = @import("acp_subagent_live.zig");- const announce_child = acp_children.eligible(kind, ctx.depth, ctx.subagent_feedback != null);+ const detached = ctx.subagent_feedback != null;+ const announce_child = acp_children.eligible(kind, ctx.depth, detached);const announced = announce_child and acp_children.announce(ctx.io, sub_id, label, prompt, ctx.parent_tool_call_id);- var child_stream: acp_children.ChildSink = .{ .id = sub_id, .io = ctx.io, .recorder = agent.sink };- if (announced) agent.sink = child_stream.engineSink();+ const background_announced = detached and std.mem.eql(u8, kind, "subagent") and ctx.depth == 0 and ctx.parent_tool_call_id.len > 0 and+ acp_children.announceBackground(ctx.io, sub_id, label, prompt, ctx.parent_tool_call_id);+ var child_stream: acp_children.ChildSink = .{+ .id = sub_id,+ .io = ctx.io,+ .recorder = agent.sink,+ .background_call_id = if (background_announced) ctx.parent_tool_call_id else null,+ };+ if (announced or background_announced) agent.sink = child_stream.engineSink();var child_state: []const u8 = "failed";defer if (announced) acp_children.finish(ctx.io, sub_id, child_state, ctx.parent_tool_call_id);+ defer if (background_announced) acp_children.finishBackground(ctx.io, sub_id, ctx.parent_tool_call_id, child_stream.seq, child_state);const wf_task = std.mem.eql(u8, kind, "workflow_task");if (wf_task) guiEmit(ctx.io, .{ .type = "tool_call", .name = "subagent", .input = .{ .description = label }, .id = sub_id });