graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
Speak the ACP v2 draft behind GRAFF_ACP_V2=1
justrachbe8cdfa52326
diff --git a/build.zig b/build.zigindex b0235cb2..c2d740f2 100644--- a/build.zig+++ b/build.zig@@ -137,6 +137,9 @@ pub fn build(b: *std.Build) void {const acp_startup_test = b.addSystemCommand(&.{ "python3", "scripts/test-acp-startup.py" });acp_startup_test.addArtifactArg(exe);test_step.dependOn(&acp_startup_test.step);+ const acp_v2_test = b.addSystemCommand(&.{ "python3", "scripts/test-acp-v2.py" });+ acp_v2_test.addArtifactArg(exe);+ test_step.dependOn(&acp_v2_test.step);const acp_effort_test = b.addSystemCommand(&.{ "python3", "scripts/test-acp-effort-config.py" });acp_effort_test.addArtifactArg(exe);test_step.dependOn(&acp_effort_test.step);diff --git a/docs/acp-compatibility.md b/docs/acp-compatibility.mdindex 10b205c4..2d304290 100644--- a/docs/acp-compatibility.md+++ b/docs/acp-compatibility.md@@ -1,7 +1,9 @@# ACP compatibilityGraff implements ACP wire protocol **v1**. The upstream repository identifies-v1 as stable; v2 is a draft and is not a compatibility target for this release.+v1 as stable. The v2 draft is available as a preview: a client that sends+`protocolVersion` 2 or higher to a graff started with `GRAFF_ACP_V2=1` gets the+v2 shapes (ADR 0206); every other connection gets v1, unchanged.Protocol versions are negotiated through `initialize.protocolVersion`, notinferred from SDK package versions.@@ -35,6 +37,23 @@ optional feature or draft extension is enabled.| Subagents | Default: a top-level subagent streams its work onto the parent tool call as standard `tool_call_update` content (a rolling log of its tool calls, failures and message tail), with no `status` change and `_meta["graff/subagent"]` = `{sessionId, name, state}`; `GRAFF_ACP_SUBAGENT_PROGRESS=0` disables it. Opt-in preview: the proposed child-session stream (client `subagents` capability plus `GRAFF_ACP_DRAFT_SUBAGENTS=1`) replaces it for foreground children. Detached workers also keep `graff/agents` inspection. Child history is not yet replayed on `session/load`. | `scripts/test-acp-subagent-update.py`, ADR 0194, ADR 0205 || 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` |+## ACP v2 preview (`GRAFF_ACP_V2=1`)++| Surface | v2 behavior | Coverage |+| --- | --- | --- |+| Initialization | `protocolVersion: 2`, `info`, and object-marker `capabilities.session` (`prompt.image`/`embeddedContext`, `mcp.stdio`/`http`); graff extensions in `capabilities._meta`. `authMethods` uses `methodId`, and the terminal login is listed only when the client sends `capabilities.auth.terminal`. | `src/acp_v2.zig`, `scripts/test-acp-v2.py` |+| Prompt lifecycle | `session/prompt` is answered with `{messageId}` once the user message is inserted, before the turn runs. Then `user_message` (same ID), `state_update` `running`, the turn's updates, and `state_update` `idle` with `stopReason`. A turn that fails after acceptance idles with `stopReason: "_error"` and `_meta["graff/error"]`. Agent-started turns (peer mail) use the same updates with no request. | `src/acp_v2_prompt.zig`, `scripts/test-acp-v2.py` |+| Messages | Every chunk has a `messageId`. A new ID starts when output switches between thought and text or after a tool event, so later text never appends above an earlier tool row. | `src/acp_v2.zig` |+| Tool calls | No `tool_call`: the first `tool_call_update` for an ID creates the row. Subagent progress keeps replacing that call's `content`. | `src/acp_stream.zig` |+| Permissions | `state_update` `requires_action` while a `session/request_permission` is pending, `running` once it is answered. | `src/acp_permission.zig` |+| Usage | `usage_update` `{used, size}` replaces `gui_context_meter`. Graff-only session updates are `_`-prefixed (`_gui_ask_user`). | `src/acp_engine.zig` |+| Sessions | `session/close` cancels any running turn and answers `{}`. `session/resume` restores a saved session without replay, and replays it only for `replayFrom: {type: "start"}`. | `src/acp_session_load.zig` |++Not yet: stable message IDs across replay (replayed messages get fresh IDs),+`session/list`, `auth/login` / `auth/logout`, `plan_update`, structured diffs,+terminal updates, JSON-RPC batches, the draft child-session stream, and+subagent progress after the prompt goes idle.+## Client acceptance checklistA replacement client should be exercised against the release binary fordiff --git a/docs/adr/0206-acp-v2-preview-behind-a-gate.md b/docs/adr/0206-acp-v2-preview-behind-a-gate.mdnew file mode 100644index 00000000..507b6ae6--- /dev/null+++ b/docs/adr/0206-acp-v2-preview-behind-a-gate.md@@ -0,0 +1,41 @@+# 0206. ACP v2 preview behind a gate++Status: accepted 2026-09-26.++## Context++ACP v2 is a draft. It changes the prompt contract: `session/prompt` is+answered once the user message is inserted, with that message's `messageId`,+and the turn's outcome arrives later as a `state_update` (`running`, then+`idle` with a `stopReason`). It also requires a `messageId` on every message+chunk, removes `tool_call` (the first `tool_call_update` creates the row),+renames `initialize`'s `agentInfo`/`agentCapabilities` to `info`/`capabilities`+with object markers, and reserves non-underscore variants for the spec.++Every client graff ships to today speaks v1. A v1 client that is sent v2 shapes+would silently lose turn completion.++## Decision++- v2 is used only when the client asks for `protocolVersion` >= 2 **and**+ graff was started with `GRAFF_ACP_V2=1`. Otherwise `initialize` answers 1+ and every byte stays as it was.+- The negotiated wire is a process global (one ACP connection per process),+ latched at `initialize`. The v1 writers branch on it rather than a second+ set of writers, so a feature cannot reach one version and miss the other.+- A v2 prompt is acknowledged before the turn runs. Errors that happen before+ insertion are still JSON-RPC errors; a turn that fails later idles with the+ custom stop reason `_error` and the message in `_meta["graff/error"]`.+- Message IDs are minted per process (`msg_<role>_<seed>_<n>`). A new ID+ starts when output switches between thought and text, or after a tool event.+- The draft child-session stream (ADR 0194) is a v1-era proposal and is off in+ v2; subagents report through tool-call content (ADR 0205).++## Consequences++Harness and other clients can build against the v2 lifecycle now without+graff changing behavior for anyone else. Replayed history gets fresh message+IDs, which v2 forbids for retained prompts; persisting IDs in the saved+session is the next step. `session/list`, `auth/login`/`auth/logout`,+`plan_update`, structured diffs, terminal updates and JSON-RPC batches are+not implemented yet.diff --git a/docs/adr/README.md b/docs/adr/README.mdindex dcc70f36..33243a3b 100644--- a/docs/adr/README.md+++ b/docs/adr/README.md@@ -232,6 +232,7 @@ record only when you need the evidence or the edge cases.| [0203](0203-external-agents-join-rooms-through-graff-peer.md) | Other agents join the device rooms with `graff peer list/send/inbox`: same JSONL rooms and records, owned by the agent's process; a DM is held while the recipient's newer message is unread; drains read only new bytes. || [0204](0204-kimi-platform-is-graff.md) | Kimi requests send `X-Msh-Platform: graff` and `graff/<version>` everywhere (OAuth and inference), never `kimi_code_cli`; a Kimi Code console key bills as plan quota. Supersedes 0027. || [0205](0205-subagent-progress-is-standard-tool-content.md) | By default a subagent streams its work onto the parent tool call as content-only `tool_call_update` rows (rolling log + `_meta["graff/subagent"]`); the draft child-session stream only when both sides opt in; `GRAFF_ACP_SUBAGENT_PROGRESS=0` turns it off. |+| [0206](0206-acp-v2-preview-behind-a-gate.md) | ACP v2 draft shapes behind `GRAFF_ACP_V2=1` plus a client `protocolVersion` >= 2; v1 stays the default and unchanged. Prompt is acknowledged with `messageId` on insertion, the outcome travels as `state_update`. |## When to write onediff --git a/scripts/test-acp-v2.py b/scripts/test-acp-v2.pynew file mode 100644index 00000000..c4e5722c--- /dev/null+++ b/scripts/test-acp-v2.py@@ -0,0 +1,133 @@+#!/usr/bin/env python3+"""ACP v2 (GRAFF_ACP_V2=1) wire shapes over a real `graff acp` process, and+v1 staying byte-compatible when the gate is closed."""+import json+import os+import selectors+import subprocess+import sys+import tempfile+import time+from pathlib import Path+++class Acp:+ def __init__(self, binary, root, v2):+ env = {"HOME": str(root), "PATH": "/usr/bin:/bin", "TERM": "dumb",+ "LMSTUDIO_API_KEY": "fixture", "GRAFF_NO_ADOPT": "1",+ "GRAFF_NO_TELEMETRY": "1", "GRAFF_FLEET": "off"}+ if v2:+ env["GRAFF_ACP_V2"] = "1"+ self.child = subprocess.Popen([str(binary), "acp", "--yolo", "--model", "lmstudio"],+ cwd=root, env=env, stdin=subprocess.PIPE,+ stdout=subprocess.PIPE, stderr=subprocess.DEVNULL)+ self.poll = selectors.DefaultSelector()+ self.poll.register(self.child.stdout, selectors.EVENT_READ)+ self.buffer = b""+ self.seen = []++ def send(self, message):+ self.child.stdin.write((json.dumps(message) + "\n").encode())+ self.child.stdin.flush()++ def until(self, done, timeout=10):+ deadline = time.monotonic() + timeout+ while time.monotonic() < deadline:+ while b"\n" in self.buffer:+ line, self.buffer = self.buffer.split(b"\n", 1)+ message = json.loads(line) # stdout must stay protocol-clean+ self.seen.append(message)+ if done(message):+ return message+ if self.poll.select(.1):+ chunk = os.read(self.child.stdout.fileno(), 65536)+ assert chunk, "ACP exited early"+ self.buffer += chunk+ raise AssertionError("timed out; saw:\n" + "\n".join(json.dumps(m) for m in self.seen[-20:]))++ def close(self):+ self.poll.close()+ self.child.kill()+ self.child.wait()+++def updates(seen, kind):+ return [m["params"]["update"] for m in seen+ if m.get("method") == "session/update" and m["params"]["update"].get("sessionUpdate") == kind]+++def v2(binary, root):+ acp = Acp(binary, root, True)+ try:+ acp.send({"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {+ "protocolVersion": 2, "capabilities": {"auth": {"terminal": {}}},+ "info": {"name": "v2-test", "version": "1"}}})+ init = acp.until(lambda m: m.get("id") == 1)["result"]+ assert init["protocolVersion"] == 2, init+ assert "agentCapabilities" not in init and "agentInfo" not in init, init+ assert init["capabilities"]["session"]["mcp"] == {"stdio": {}, "http": {}}, init+ assert init["info"]["name"] == "graff", init+ assert init["authMethods"][0]["methodId"] == "graff-login", init+ acp.send({"jsonrpc": "2.0", "id": 2, "method": "session/new",+ "params": {"cwd": str(root), "mcpServers": []}})+ sid = acp.until(lambda m: m.get("id") == 2)["result"]["sessionId"]+ # A local slash command inserts a user message without a model call.+ acp.send({"jsonrpc": "2.0", "id": 3, "method": "session/prompt",+ "params": {"sessionId": sid, "prompt": [{"type": "text", "text": "/help"}]}})+ acp.until(lambda m: m.get("method") == "session/update"+ and m["params"]["update"].get("sessionUpdate") == "state_update"+ and m["params"]["update"].get("state") == "idle")+ ack = next(m for m in acp.seen if m.get("id") == 3)+ message_id = ack["result"]["messageId"]+ assert list(ack["result"]) == ["messageId"], ack+ users = updates(acp.seen, "user_message")+ assert users and users[-1]["messageId"] == message_id, users+ assert users[-1]["content"] == [{"type": "text", "text": "/help"}], users+ states = [(u["state"], u.get("stopReason")) for u in updates(acp.seen, "state_update")]+ assert states == [("running", None), ("idle", "end_turn")], states+ chunks = updates(acp.seen, "agent_message_chunk")+ assert chunks and all(c.get("messageId") for c in chunks), chunks+ names = {m["params"]["update"]["sessionUpdate"] for m in acp.seen if m.get("method") == "session/update"}+ assert not {n for n in names if n.startswith("gui_")}, names+ order = [i for i, m in enumerate(acp.seen) if m.get("id") == 3+ or (m.get("method") == "session/update" and m["params"]["update"].get("state") == "idle")]+ assert order == sorted(order) and len(order) == 2, "prompt ack must precede idle"+ acp.send({"jsonrpc": "2.0", "id": 4, "method": "session/close", "params": {"sessionId": sid}})+ closed = acp.until(lambda m: m.get("id") == 4)+ assert closed.get("result") == {}, closed+ finally:+ acp.close()+++def v1(binary, root):+ acp = Acp(binary, root, False)+ try:+ acp.send({"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {"protocolVersion": 2}})+ init = acp.until(lambda m: m.get("id") == 1)["result"]+ assert init["protocolVersion"] == 1 and "agentCapabilities" in init, init+ acp.send({"jsonrpc": "2.0", "id": 2, "method": "session/new", "params": {"cwd": str(root), "mcpServers": []}})+ sid = acp.until(lambda m: m.get("id") == 2)["result"]["sessionId"]+ acp.send({"jsonrpc": "2.0", "id": 3, "method": "session/prompt",+ "params": {"sessionId": sid, "prompt": [{"type": "text", "text": "/help"}]}})+ done = acp.until(lambda m: m.get("id") == 3)+ assert done["result"] == {"stopReason": "end_turn"}, done+ assert not updates(acp.seen, "state_update") and not updates(acp.seen, "user_message")+ assert all("messageId" not in c for c in updates(acp.seen, "agent_message_chunk"))+ finally:+ acp.close()+++def main():+ if os.name != "posix":+ print("ACP v2 wire integration: POSIX only")+ return+ binary = Path(sys.argv[1] if len(sys.argv) > 1 else "zig-out/bin/graff").resolve()+ with tempfile.TemporaryDirectory(prefix="graff-acp-v2-") as temporary:+ v2(binary, Path(temporary).resolve())+ with tempfile.TemporaryDirectory(prefix="graff-acp-v1-") as temporary:+ v1(binary, Path(temporary).resolve())+ print("ACP v2 wire integration: ok")+++if __name__ == "__main__":+ main()diff --git a/src/acp_engine.zig b/src/acp_engine.zigindex 56a6a3ad..fae28e1d 100644--- a/src/acp_engine.zig+++ b/src/acp_engine.zig@@ -10,6 +10,8 @@ const proto = @import("acp_protocol.zig");const acp_workspace = @import("acp_workspace.zig");const util = @import("util.zig");const acp_auth = @import("acp_auth.zig");+const v2 = @import("acp_v2.zig");+const v2_prompt = @import("acp_v2_prompt.zig");pub const parseRequest = proto.parseRequest;pub const negotiateVersion = proto.negotiateVersion;@@ -123,7 +125,7 @@ fn sameConfig(before: []const ConfigOption, after: []const ConfigOption) bool {return true;}-fn emitConfigChange(d: *Dispatch, arena: Allocator, w: *Io.Writer, sid: []const u8, before: []const ConfigOption) !void {+pub fn emitConfigChange(d: *Dispatch, arena: Allocator, w: *Io.Writer, sid: []const u8, before: []const ConfigOption) !void {if (d.config == null) return;const after = try configOptions(d, arena);if (sameConfig(before, after)) return;@@ -138,7 +140,7 @@ fn respond(w: *Io.Writer, req: proto.Request, result: anytype) !void {try writeResult(w, req.id, result);}-fn respondError(w: *Io.Writer, req: proto.Request, code: i32, message: []const u8) !void {+pub fn respondError(w: *Io.Writer, req: proto.Request, code: i32, message: []const u8) !void {if (req.id == null) return;try writeError(w, req.id, code, message);}@@ -168,6 +170,7 @@ fn turnError(d: *Dispatch, w: *Io.Writer, req: proto.Request, err: anyerror) !vo}fn promptTurn(d: *Dispatch, arena: Allocator, w: *Io.Writer, req: proto.Request) !void {+ if (v2.on()) return v2_prompt.promptTurn(d, arena, w, req);const obj: ?std.json.ObjectMap = if (req.params) |p| (if (p == .object) p.object else null) else null;const sid = blk: {if (obj) |o| if (util.strFieldObj(o, "sessionId")) |s| break :blk s;@@ -204,10 +207,11 @@ fn promptTurn(d: *Dispatch, arena: Allocator, w: *Io.Writer, req: proto.Request)try respond(w, req, .{ .stopReason = stop });}-fn emitMeter(d: *Dispatch, w: *Io.Writer, sid: []const u8) !void {+pub fn emitMeter(d: *Dispatch, w: *Io.Writer, sid: []const u8) !void {if (d.meter) |meter| {// Report live occupancy independently of the model catalog.const m = meter(d.ctx);+ if (m.window > 0 and v2.on()) return v2.writeUsage(w, sid, m.used, m.window);if (m.window > 0) try proto.writeNotification(w, "session/update", .{.sessionId = sid,.update = .{@@ -219,54 +223,8 @@ fn emitMeter(d: *Dispatch, w: *Io.Writer, sid: []const u8) !void {}}-test "slash commands refresh occupancy before their terminal response" {- const Fixture = struct {- fn slash(_: *anyopaque, _: Allocator, _: []const u8) anyerror!?[]const u8 {- return "compacted";- }- fn meter(_: *anyopaque) Meter {- return .{ .used = 20, .window = 100 };- }- };- var arena = std.heap.ArenaAllocator.init(std.testing.allocator);- defer arena.deinit();- var buffer: [2048]u8 = undefined;- var writer: Io.Writer = .fixed(&buffer);- var dispatch: Dispatch = .{ .turn = echoTurn, .ctx = undefined, .slash = Fixture.slash, .meter = Fixture.meter };- try handleLine(&dispatch, arena.allocator(), &writer, "{\"id\":1,\"method\":\"session/prompt\",\"params\":{\"prompt\":[{\"type\":\"text\",\"text\":\"/compact\"}]}}");- const output = writer.buffered();- const meter_pos = std.mem.indexOf(u8, output, "\"used\":20,\"window\":100") orelse return error.MissingMeter;- const end_pos = std.mem.indexOf(u8, output, "stopReason") orelse return error.MissingResponse;- 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 {+ if (v2.on()) return respond(w, req, v2.initializeResult(req.params, can_load, implementation_version));return respond(w, req, .{.protocolVersion = negotiateVersion(req.params),.agentCapabilities = .{@@ -287,14 +245,19 @@ fn respondInitialize(w: *Io.Writer, req: proto.Request, can_load: bool) !void {/// engine response; every request that needs a live Agent is auth-gated.pub fn handlePreAuthLine(arena: Allocator, w: *Io.Writer, line: []const u8) !void {const req = parseRequest(arena, line) orelse return;- if (std.mem.eql(u8, req.method, "initialize")) return respondInitialize(w, req, false);+ if (std.mem.eql(u8, req.method, "initialize")) {+ v2.negotiate(req.params, 0);+ return respondInitialize(w, req, false);+ }return respondError(w, req, err_auth_required, acp_auth.required_message);}pub fn handleLine(d: *Dispatch, arena: Allocator, w: *Io.Writer, line: []const u8) !void {const req = parseRequest(arena, line) orelse return;if (std.mem.eql(u8, req.method, "initialize")) {- d.subagents = supportsSubagents(req.params);+ v2.negotiate(req.params, d.seed);+ // The draft child-session RFD is a v1 shape; v2 gets tool-call progress.+ d.subagents = !v2.on() and supportsSubagents(req.params);d.background_subagents = supportsBackgroundSubagents(req.params);return respondInitialize(w, req, d.load_session != null);}@@ -323,7 +286,7 @@ pub fn handleLine(d: *Dispatch, arena: Allocator, w: *Io.Writer, line: []const utry proto.writeAvailableCommands(w, d.session_id.?, proto.slashCommands());return;}- if ((d.load_session != null and (std.mem.eql(u8, req.method, "session/prompt") or std.mem.eql(u8, req.method, "session/cancel"))) or+ if ((d.load_session != null and (std.mem.eql(u8, req.method, "session/prompt") or std.mem.eql(u8, req.method, "session/cancel") or std.mem.eql(u8, req.method, "session/close"))) or(d.set_config != null and std.mem.eql(u8, req.method, "session/set_config_option"))){const params = req.params orelse return respondError(w, req, -32602, "Invalid session ID");@@ -335,10 +298,11 @@ pub fn handleLine(d: *Dispatch, arena: Allocator, w: *Io.Writer, line: []const uif (std.mem.eql(u8, req.method, "session/cancel")) {cancel_flag.store(true, .release);if (on_cancel) |hook| hook();- if (req.id != null) return respond(w, req, .{});+ if (req.id != null) return respond(w, req, struct {}{});return;}- if (std.mem.eql(u8, req.method, "session/load")) {+ if (v2.on() and std.mem.eql(u8, req.method, "session/close")) return respond(w, req, struct {}{});+ if (std.mem.eql(u8, req.method, if (v2.on()) "session/resume" else "session/load")) {if (d.load_session) |load| {if (d.mcp_servers) |attach| attach(d.ctx, arena, req.params) catch {};return load(d.ctx, arena, w, req);diff --git a/src/acp_engine_test.zig b/src/acp_engine_test.zignew file mode 100644index 00000000..bd7394b2--- /dev/null+++ b/src/acp_engine_test.zig@@ -0,0 +1,59 @@+//! acp_engine.zig's prompt/meter ordering tests (split for the 600-line cap).+const std = @import("std");+const Io = std.Io;+const Allocator = std.mem.Allocator;+const engine = @import("acp_engine.zig");+const Dispatch = engine.Dispatch;+const Meter = engine.Meter;+const handleLine = engine.handleLine;++fn echoTurn(_: *anyopaque, arena: Allocator, text: []const u8) anyerror![]const u8 {+ return std.fmt.allocPrint(arena, "echo:{s}", .{text});+}++test "slash commands refresh occupancy before their terminal response" {+ const Fixture = struct {+ fn slash(_: *anyopaque, _: Allocator, _: []const u8) anyerror!?[]const u8 {+ return "compacted";+ }+ fn meter(_: *anyopaque) Meter {+ return .{ .used = 20, .window = 100 };+ }+ };+ var arena = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena.deinit();+ var buffer: [2048]u8 = undefined;+ var writer: Io.Writer = .fixed(&buffer);+ var dispatch: Dispatch = .{ .turn = echoTurn, .ctx = undefined, .slash = Fixture.slash, .meter = Fixture.meter };+ try handleLine(&dispatch, arena.allocator(), &writer, "{\"id\":1,\"method\":\"session/prompt\",\"params\":{\"prompt\":[{\"type\":\"text\",\"text\":\"/compact\"}]}}");+ const output = writer.buffered();+ const meter_pos = std.mem.indexOf(u8, output, "\"used\":20,\"window\":100") orelse return error.MissingMeter;+ const end_pos = std.mem.indexOf(u8, output, "stopReason") orelse return error.MissingResponse;+ try std.testing.expect(meter_pos < end_pos);+}++test "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(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);+}diff --git a/src/acp_idle.zig b/src/acp_idle.zigindex fbb3c444..f538b07b 100644--- a/src/acp_idle.zig+++ b/src/acp_idle.zig@@ -59,6 +59,8 @@ pub fn promptWake(d: *engine.Dispatch, arena: Allocator, w: *Io.Writer, wake: []},});try engine.handleLine(d, arena, w, aw.writer.buffered());+ // v2's idle `state_update` already closes an agent-started turn.+ if (@import("acp_v2.zig").on()) return;try proto.writeNotification(w, "session/update", .{.sessionId = sid,.update = .{diff --git a/src/acp_inbox.zig b/src/acp_inbox.zigindex aa831466..9431534d 100644--- a/src/acp_inbox.zig+++ b/src/acp_inbox.zig@@ -121,7 +121,10 @@ pub const Inbox = struct {const value = params.object.get("sessionId") orelse break :blk null;break :blk if (value == .string) value.string else null;};- if (std.mem.eql(u8, r.method, "session/cancel") and r.id == null) {+ // v2 session/close cancels like session/cancel, then still queues+ // so dispatch answers it once the turn has unwound.+ const closing = std.mem.eql(u8, r.method, "session/close");+ if ((std.mem.eql(u8, r.method, "session/cancel") and r.id == null) or closing) {if (self.session_id) |current| {if (sid == null or std.mem.eql(u8, sid.?, current)) {self.cancelled = true;@@ -130,7 +133,7 @@ pub const Inbox = struct {if (self.permission) |bridge| bridge.cancel();}}- return;+ if (!closing) return;}if (std.mem.eql(u8, r.method, "session/answer")) {const obj: ?std.json.ObjectMap = if (r.params) |p| (if (p == .object) p.object else null) else null;diff --git a/src/acp_permission.zig b/src/acp_permission.zigindex 4cc6179a..58d30bd6 100644--- a/src/acp_permission.zig+++ b/src/acp_permission.zig@@ -3,6 +3,7 @@ const std = @import("std");const Io = std.Io;const permission = @import("engine_permission.zig");const util = @import("util.zig");+const v2 = @import("acp_v2.zig");pub const Bridge = struct {io: Io,out: *Io.Writer,@@ -73,9 +74,19 @@ pub const Bridge = struct {.options = options[0..if (req.allow_always) @as(usize, 3) else 2],} }, .{}, self.out) catch return .deny;self.out.writeByte('\n') catch return .deny;+ if (v2.on()) v2.writeRequiresAction(self.out, self.session) catch return .deny;self.out.flush() catch return .deny;}while (self.decision == null and !self.closed) self.ready.waitUncancelable(io, &self.mutex);+ if (v2.on() and !self.closed) {+ 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);+ v2.writeRunning(self.out, self.session) catch {};+ self.out.flush() catch {};+ }return self.decision orelse .deny;}/// Responses have no method. Only the currently pending server ID can resolve.diff --git a/src/acp_protocol.zig b/src/acp_protocol.zigindex 6e2bc80d..1a66037f 100644--- a/src/acp_protocol.zig+++ b/src/acp_protocol.zig@@ -60,9 +60,8 @@ pub fn parseRequest(arena: Allocator, line: []const u8) ?Request {pub fn negotiateVersion(params: ?Value) i64 {// ACP requires the requested version if supported, otherwise our latest.- // We implement only v1: echoing an older number would promise other shapes.- _ = params;- return protocol_version;+ // v2 is supported only behind GRAFF_ACP_V2=1 (acp_v2.zig); never echo 0.+ return @import("acp_v2.zig").negotiated(params);}fn blockText(block: Value) ?[]const u8 {@@ -187,6 +186,8 @@ pub fn writeNotification(w: *Io.Writer, method: []const u8, params: anytype) !vo/// One `agent_message_chunk` notification (the v0 final-text update).pub fn writeSessionUpdate(w: *Io.Writer, session_id: []const u8, text: []const u8) !void {+ const v2 = @import("acp_v2.zig");+ if (v2.on()) return v2.writeChunk(w, session_id, false, text);try writeNotification(w, "session/update", .{.sessionId = session_id,.update = .{diff --git a/src/acp_replay.zig b/src/acp_replay.zigindex 63babd82..d32770f6 100644--- a/src/acp_replay.zig+++ b/src/acp_replay.zig@@ -1,4 +1,4 @@-//! Project saved provider history onto ACP v1's user-visible replay stream.+//! Project saved provider history onto ACP's user-visible replay stream.//! This never invokes a tool: orphaned calls become failed historical rows.const std = @import("std");const Io = std.Io;@@ -7,6 +7,7 @@ const Value = std.json.Value;const proto = @import("acp_protocol.zig");const util = @import("util.zig");const session_peer = @import("session_peer.zig");+const v2 = @import("acp_v2.zig");const Call = struct { id: []const u8, finished: bool = false };@@ -35,6 +36,16 @@ fn visibleText(arena: Allocator, value: Value) ![]const u8 {fn message(w: *Io.Writer, sid: []const u8, role: []const u8, text: []const u8) !void {if (text.len == 0) return;+ if (v2.on()) {+ // Full-content upserts need no `content: []` reset before them.+ var id: [48]u8 = undefined;+ const user = std.mem.eql(u8, role, "user");+ return proto.writeNotification(w, "session/update", .{ .sessionId = sid, .update = .{+ .sessionUpdate = if (user) "user_message" else "agent_message",+ .messageId = v2.mint(&id, if (user) "user" else "agent"),+ .content = .{.{ .type = "text", .text = text }},+ } });+ }try proto.writeNotification(w, "session/update", .{.sessionId = sid,.update = .{@@ -50,7 +61,7 @@ fn beginCall(arena: Allocator, w: *Io.Writer, sid: []const u8, calls: *std.Arraytry proto.writeNotification(w, "session/update", .{.sessionId = sid,.update = .{- .sessionUpdate = "tool_call",+ .sessionUpdate = if (v2.on()) "tool_call_update" else "tool_call",.toolCallId = id,.title = name,.kind = "other",diff --git a/src/acp_session_load.zig b/src/acp_session_load.zigindex a35b07c0..05c54225 100644--- a/src/acp_session_load.zig+++ b/src/acp_session_load.zig@@ -11,6 +11,7 @@ const replay = @import("acp_replay.zig");const transcript = @import("session_transcript.zig");const LiveTurn = @import("acp_live_turn.zig").LiveTurn;const util = @import("util.zig");+const v2 = @import("acp_v2.zig");const acp_workspace = @import("acp_workspace.zig");const workspace_switch = @import("workspace_switch.zig");@@ -98,8 +99,15 @@ pub fn load(ctx: *anyopaque, arena: Allocator, w: *Io.Writer, req: proto.Requestlive.session_id = live.root.session_name;d.session_id = live.session_id;d.durable_session_id = live.session_id;- try replayHistory(arena, live.root, w, live.session_id);+ // v2 session/resume replays only when asked (`replayFrom: {type: start}`).+ if (!v2.on() or replayFromStart(params)) try replayHistory(arena, live.root, w, live.session_id);const options = engine.configOptions(d, arena) catch |err| return proto.writeError(w, req.id, engine.err_internal, @errorName(err));try proto.writeResult(w, req.id, .{ .configOptions = options, ._meta = acp_workspace.meta(env, arena) });try proto.writeAvailableCommands(w, live.session_id, proto.slashCommands());}++fn replayFromStart(params: std.json.Value) bool {+ const from = params.object.get("replayFrom") orelse return false;+ if (from != .object) return false;+ return std.mem.eql(u8, util.strFieldObj(from.object, "type") orelse "", "start");+}diff --git a/src/acp_stream.zig b/src/acp_stream.zigindex 22493180..5ddf2490 100644--- a/src/acp_stream.zig+++ b/src/acp_stream.zig@@ -8,6 +8,7 @@ const Allocator = std.mem.Allocator;const Value = std.json.Value;const util = @import("util.zig");const proto = @import("acp_protocol.zig");+const v2 = @import("acp_v2.zig");pub fn kindFor(name: []const u8) []const u8 {if (std.mem.eql(u8, name, "read_file") or std.mem.eql(u8, name, "codedb") or std.mem.eql(u8, name, "skill"))@@ -51,6 +52,7 @@ pub fn titleFor(name: []const u8, input: Value) []const u8 {}pub fn writeThought(w: *Io.Writer, session_id: []const u8, text: []const u8) !void {+ if (v2.on()) return v2.writeChunk(w, session_id, true, text);try proto.writeNotification(w, "session/update", .{.sessionId = session_id,.update = .{@@ -65,10 +67,13 @@ pub fn writeMessage(w: *Io.Writer, session_id: []const u8, text: []const u8) !vo}pub fn writeToolCall(w: *Io.Writer, session_id: []const u8, id: []const u8, name: []const u8, input: Value) !void {+ // v2 removed `tool_call`: the first `tool_call_update` for an ID creates it,+ // and text after a tool row is a new message.+ v2.breakMessage();try proto.writeNotification(w, "session/update", .{.sessionId = session_id,.update = .{- .sessionUpdate = "tool_call",+ .sessionUpdate = if (v2.on()) "tool_call_update" else "tool_call",.toolCallId = id,.title = titleFor(name, input),.kind = kindFor(name),@@ -80,6 +85,7 @@ pub fn writeToolCall(w: *Io.Writer, session_id: []const u8, id: []const u8, name}pub fn writeToolStatus(w: *Io.Writer, session_id: []const u8, id: []const u8, status: []const u8) !void {+ v2.breakMessage();try proto.writeNotification(w, "session/update", .{.sessionId = session_id,.update = .{@@ -92,6 +98,7 @@ pub fn writeToolStatus(w: *Io.Writer, session_id: []const u8, id: []const u8, stpub fn writeToolDone(w: *Io.Writer, session_id: []const u8, id: []const u8, is_error: bool, text: []const u8) !void {const status: []const u8 = if (is_error) "failed" else "completed";+ v2.breakMessage();if (text.len == 0) return writeToolStatus(w, session_id, id, status);try proto.writeNotification(w, "session/update", .{.sessionId = session_id,@@ -194,7 +201,8 @@ pub fn translateEvent(try proto.writeNotification(w, "session/update", .{.sessionId = session_id,.update = .{- .sessionUpdate = "gui_ask_user",+ // v2 reserves non-underscore variants for the spec.+ .sessionUpdate = if (v2.on()) "_gui_ask_user" else "gui_ask_user",.callId = util.strFieldObj(ev.object, "call_id") orelse "",.question = util.strFieldObj(ev.object, "question") orelse "",.input = ev.object.get("input") orelse Value{ .object = .empty },diff --git a/src/acp_v2.zig b/src/acp_v2.zignew file mode 100644index 00000000..91a988f2--- /dev/null+++ b/src/acp_v2.zig@@ -0,0 +1,268 @@+//! ACP v2 (draft) wire shapes. Negotiated per process at `initialize` when+//! the client asks for protocolVersion >= 2 AND `GRAFF_ACP_V2=1`; every other+//! connection keeps the v1 shapes byte-for-byte (ADR 0206). One ACP+//! connection per process, so the negotiated state is a process global.+const std = @import("std");+const Io = std.Io;+const Value = std.json.Value;+const acp_auth = @import("acp_auth.zig");++pub const version: i64 = 2;++var active = std.atomic.Value(bool).init(false);+/// Tests pin the gate; null reads `GRAFF_ACP_V2`.+pub var gate: ?bool = null;++pub fn on() bool {+ return active.load(.acquire);+}++pub fn gateOpen() bool {+ if (gate) |g| return g;+ const v = std.c.getenv("GRAFF_ACP_V2") orelse return false;+ return std.mem.eql(u8, std.mem.span(v), "1");+}++fn requested(params: ?Value) i64 {+ const p = params orelse return 1;+ if (p != .object) return 1;+ const v = p.object.get("protocolVersion") orelse return 1;+ return if (v == .integer) v.integer else 1;+}++/// The version to answer with. ACP: the requested one when supported, else+/// our latest — v2 is only "supported" behind the gate.+pub fn negotiated(params: ?Value) i64 {+ return if (gateOpen() and requested(params) >= version) version else 1;+}++/// Latch the connection's wire at `initialize` (a re-initialize may downgrade).+pub fn negotiate(params: ?Value, seed: u64) void {+ const v2 = negotiated(params) == version;+ if (v2) prefix = seed;+ kind = .none;+ active.store(v2, .release);+}++// ── message IDs ─────────────────────────────────────────────────────────+// A message is one contiguous run of agent text or thought. Switching kind or+// reporting a tool starts a new ID, so later text never appends above a tool+// row that the client already rendered. Callers hold the ACP output lock.++const Kind = enum { none, agent, thought };+var prefix: u64 = 0;+var counter = std.atomic.Value(u64).init(0);+var kind: Kind = .none;+var current: [48]u8 = undefined;+var current_len: usize = 0;++pub fn mint(buf: *[48]u8, role: []const u8) []const u8 {+ const n = counter.fetchAdd(1, .monotonic) + 1;+ return std.fmt.bufPrint(buf, "msg_{s}_{x}_{d}", .{ role, prefix, n }) catch "msg";+}++fn messageId(k: Kind) []const u8 {+ if (kind != k or current_len == 0) {+ current_len = mint(¤t, @tagName(k)).len;+ kind = k;+ }+ return current[0..current_len];+}++/// A tool event or turn boundary ends the current message.+pub fn breakMessage() void {+ kind = .none;+}++pub fn writeChunk(w: *Io.Writer, sid: []const u8, thought: bool, text: []const u8) !void {+ const id = messageId(if (thought) .thought else .agent);+ try notify(w, sid, .{+ .sessionUpdate = if (thought) "agent_thought_chunk" else "agent_message_chunk",+ .messageId = id,+ .content = .{ .type = "text", .text = text },+ });+}++pub fn writeUserMessage(w: *Io.Writer, sid: []const u8, id: []const u8, prompt: ?Value, text: []const u8) !void {+ breakMessage();+ if (prompt) |p| if (p == .array) return notify(w, sid, .{ .sessionUpdate = "user_message", .messageId = id, .content = p });+ try notify(w, sid, .{ .sessionUpdate = "user_message", .messageId = id, .content = .{.{ .type = "text", .text = text }} });+}++pub fn writeRunning(w: *Io.Writer, sid: []const u8) !void {+ try notify(w, sid, .{ .sessionUpdate = "state_update", .state = "running" });+}++pub fn writeRequiresAction(w: *Io.Writer, sid: []const u8) !void {+ try notify(w, sid, .{ .sessionUpdate = "state_update", .state = "requires_action" });+}++pub fn writeIdle(w: *Io.Writer, sid: []const u8, stop: []const u8) !void {+ breakMessage();+ try notify(w, sid, .{ .sessionUpdate = "state_update", .state = "idle", .stopReason = stop });+}++/// A turn that failed after its prompt was accepted: the JSON-RPC request is+/// already answered, so the error rides the idle transition (custom `_` reason).+pub fn writeFailed(w: *Io.Writer, sid: []const u8, message: []const u8) !void {+ breakMessage();+ try notify(w, sid, .{+ .sessionUpdate = "state_update",+ .state = "idle",+ .stopReason = "_error",+ ._meta = .{ .@"graff/error" = message },+ });+}++pub fn writeUsage(w: *Io.Writer, sid: []const u8, used: u64, size: u64) !void {+ try notify(w, sid, .{ .sessionUpdate = "usage_update", .used = used, .size = size });+}++fn notify(w: *Io.Writer, sid: []const u8, update: anytype) !void {+ var s: std.json.Stringify = .{ .writer = w };+ try s.write(.{ .jsonrpc = "2.0", .method = "session/update", .params = .{ .sessionId = sid, .update = update } });+ try w.writeByte('\n');+}++// ── initialize ──────────────────────────────────────────────────────────++pub const Info = struct {+ name: []const u8 = "graff",+ title: []const u8 = "graff",+ version: []const u8,+};++const Empty = struct {};++/// v2 `initialize` result: `info` + object-marker `capabilities` (an absent+/// capability is omitted, never `false`/`null`). Graff extensions ride `_meta`.+pub fn initializeResult(params: ?Value, can_load: bool, impl_version: []const u8) InitializeResult {+ return .{ .can_load = can_load, .terminal_auth = clientTerminalAuth(params), .info = .{ .version = impl_version } };+}++/// v2 renames the method key to `methodId`, and a `terminal` method may be+/// advertised only to a client that sent `capabilities.auth.terminal`.+const TerminalAuth = struct {+ methodId: []const u8,+ name: []const u8,+ description: []const u8,+ type: []const u8 = "terminal",+ args: []const []const u8,+};+const terminal_login = [_]TerminalAuth{.{+ .methodId = acp_auth.terminal_login.id,+ .name = acp_auth.terminal_login.name,+ .description = acp_auth.terminal_login.description,+ .args = acp_auth.terminal_login.args,+}};++fn clientTerminalAuth(params: ?Value) bool {+ const p = params orelse return false;+ if (p != .object) return false;+ const caps = p.object.get("capabilities") orelse return false;+ if (caps != .object) return false;+ const auth = caps.object.get("auth") orelse return false;+ if (auth != .object) return false;+ const terminal = auth.object.get("terminal") orelse return false;+ return terminal == .object;+}++const InitializeResult = struct {+ can_load: bool,+ terminal_auth: bool,+ info: Info,++ pub fn jsonStringify(self: @This(), s: anytype) !void {+ try s.beginObject();+ try s.objectField("protocolVersion");+ try s.write(version);+ try s.objectField("capabilities");+ try s.beginObject();+ try s.objectField("session");+ try s.beginObject();+ try s.objectField("prompt");+ try s.beginObject();+ if (self.can_load) {+ try s.objectField("image");+ try s.write(Empty{});+ }+ try s.objectField("embeddedContext");+ try s.write(Empty{});+ try s.endObject();+ try s.objectField("mcp");+ try s.write(.{ .stdio = Empty{}, .http = Empty{} });+ try s.endObject();+ try s.objectField("_meta");+ try s.write(.{ .@"codegraff/usage" = self.can_load, .@"graff/backgroundSubagents" = true });+ try s.endObject();+ try s.objectField("info");+ try s.write(self.info);+ try s.objectField("authMethods");+ try s.write(if (self.terminal_auth) terminal_login[0..] else terminal_login[0..0]);+ try s.endObject();+ }+};++pub fn resetForTest() void {+ active.store(false, .release);+ gate = null;+ kind = .none;+}++test "v2 needs both the client's request and the GRAFF_ACP_V2 gate" {+ defer resetForTest();+ var arena = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena.deinit();+ const two = try std.json.parseFromSliceLeaky(Value, arena.allocator(), "{\"protocolVersion\":2}", .{});+ const one = try std.json.parseFromSliceLeaky(Value, arena.allocator(), "{\"protocolVersion\":1}", .{});+ const nine = try std.json.parseFromSliceLeaky(Value, arena.allocator(), "{\"protocolVersion\":9}", .{});+ gate = false;+ try std.testing.expectEqual(@as(i64, 1), negotiated(two));+ gate = true;+ try std.testing.expectEqual(@as(i64, 2), negotiated(two));+ try std.testing.expectEqual(@as(i64, 2), negotiated(nine));+ try std.testing.expectEqual(@as(i64, 1), negotiated(one));+ try std.testing.expectEqual(@as(i64, 1), negotiated(null));+ negotiate(two, 7);+ try std.testing.expect(on());+ negotiate(one, 7);+ try std.testing.expect(!on());+}++test "message IDs change with the message kind and after a tool" {+ defer resetForTest();+ var buf: [2048]u8 = undefined;+ var w: Io.Writer = .fixed(&buf);+ try writeChunk(&w, "s", false, "a");+ try writeChunk(&w, "s", false, "b");+ const first = current[0..current_len];+ var keep: [48]u8 = undefined;+ @memcpy(keep[0..first.len], first);+ try writeChunk(&w, "s", true, "think");+ try std.testing.expect(!std.mem.eql(u8, keep[0..first.len], current[0..current_len]));+ breakMessage();+ try writeChunk(&w, "s", false, "c");+ const out = w.buffered();+ try std.testing.expectEqual(@as(usize, 4), std.mem.count(u8, out, "\"messageId\":"));+ try std.testing.expectEqual(@as(usize, 2), std.mem.count(u8, out, keep[0..first.len]));+}++test "v2 initialize uses info and object-marker capabilities" {+ var buf: [1024]u8 = undefined;+ var w: Io.Writer = .fixed(&buf);+ var arena = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena.deinit();+ try std.json.Stringify.value(initializeResult(null, false, "t"), .{}, &w);+ var out = w.buffered();+ try std.testing.expect(std.mem.startsWith(u8, out, "{\"protocolVersion\":2,\"capabilities\":{\"session\":{\"prompt\":{\"embeddedContext\":{}},\"mcp\":{\"stdio\":{},\"http\":{}}}"));+ try std.testing.expect(std.mem.indexOf(u8, out, "\"info\":{\"name\":\"graff\"") != null);+ try std.testing.expect(std.mem.indexOf(u8, out, "agentCapabilities") == null);+ try std.testing.expect(std.mem.indexOf(u8, out, "null") == null);+ try std.testing.expect(std.mem.endsWith(u8, out, "\"authMethods\":[]}"));+ const params = try std.json.parseFromSliceLeaky(Value, arena.allocator(), "{\"capabilities\":{\"auth\":{\"terminal\":{}}}}", .{});+ w = .fixed(&buf);+ try std.json.Stringify.value(initializeResult(params, true, "t"), .{}, &w);+ out = w.buffered();+ try std.testing.expect(std.mem.indexOf(u8, out, "\"image\":{}") != null);+ try std.testing.expect(std.mem.indexOf(u8, out, "\"methodId\":\"graff-login\"") != null);+}diff --git a/src/acp_v2_prompt.zig b/src/acp_v2_prompt.zignew file mode 100644index 00000000..b8d60eb7--- /dev/null+++ b/src/acp_v2_prompt.zig@@ -0,0 +1,144 @@+//! ACP v2 `session/prompt`: acceptance means insertion. The request is+//! answered with the user message's `messageId` before the turn runs; the+//! turn's outcome travels as `state_update` (running → idle + stopReason).+const std = @import("std");+const Io = std.Io;+const Allocator = std.mem.Allocator;++const engine = @import("acp_engine.zig");+const proto = @import("acp_protocol.zig");+const acp_workspace = @import("acp_workspace.zig");+const util = @import("util.zig");+const v2 = @import("acp_v2.zig");++pub fn promptTurn(d: *engine.Dispatch, arena: Allocator, w: *Io.Writer, req: proto.Request) !void {+ const obj: ?std.json.ObjectMap = if (req.params) |p| (if (p == .object) p.object else null) else null;+ const sid = blk: {+ if (obj) |o| if (util.strFieldObj(o, "sessionId")) |s| break :blk s;+ break :blk d.session_id orelse "";+ };+ const prompt = if (obj) |o| o.get("prompt") else null;+ if (d.bind_session) |bind| bind(d.ctx, sid);+ // Everything that can reject the prompt happens before insertion, where a+ // JSON-RPC error is still the right answer.+ const config_before = engine.configOptions(d, arena) catch |err|+ return engine.respondError(w, req, proto.err_internal, @errorName(err));+ const workspace_before = acp_workspace.snapshot(d.workspace, arena);+ const text = try proto.flattenPrompt(arena, prompt);+ var id_buf: [48]u8 = undefined;+ const message_id = v2.mint(&id_buf, "user");+ if (req.id != null) try proto.writeResult(w, req.id, .{ .messageId = message_id });+ try v2.writeUserMessage(w, sid, message_id, prompt, text);+ try v2.writeRunning(w, sid);+ try w.flush();++ const outcome = run(d, arena, w, sid, text, prompt);+ engine.emitConfigChange(d, arena, w, sid, config_before) catch {};+ acp_workspace.emitChange(d.workspace, arena, w, sid, workspace_before) catch {};+ try engine.emitMeter(d, w, sid);+ switch (outcome) {+ .stop => |stop| try v2.writeIdle(w, sid, stop),+ .failed => |message| try v2.writeFailed(w, sid, message),+ }+}++const Outcome = union(enum) { stop: []const u8, failed: []const u8 };++fn run(d: *engine.Dispatch, arena: Allocator, w: *Io.Writer, sid: []const u8, text: []const u8, prompt: ?std.json.Value) Outcome {+ if (d.slash) |slash| {+ const reply = slash(d.ctx, arena, text) catch |err| return failure(d, err);+ if (reply) |plain| {+ if (plain.len > 0) proto.writeSessionUpdate(w, sid, plain) catch |err| return failure(d, err);+ return .{ .stop = "end_turn" };+ }+ }+ if (d.after_user) |after| after(d.ctx, arena, text, prompt);+ const final = d.turn(d.ctx, arena, text) catch |err| return failure(d, err);+ if (final.len > 0) proto.writeSessionUpdate(w, sid, final) catch |err| return failure(d, err);+ const extra = if (engine.extra_cancelled) |f| f() else false;+ return .{ .stop = if (engine.cancel_flag.load(.acquire) or extra) "cancelled" else "end_turn" };+}++fn failure(d: *engine.Dispatch, err: anyerror) Outcome {+ if (err == error.Interrupted or err == error.Canceled) return .{ .stop = "cancelled" };+ if (err == error.RunBudgetExhausted) return .{ .stop = "max_turn_requests" };+ return .{ .failed = if (d.error_message) |message| message(d.ctx, err) else @errorName(err) };+}++fn echoTurn(_: *anyopaque, arena: Allocator, text: []const u8) anyerror![]const u8 {+ return std.fmt.allocPrint(arena, "echo:{s}", .{text});+}++fn v2Session(d: *engine.Dispatch, a: Allocator, w: *Io.Writer) !void {+ v2.gate = true;+ try engine.handleLine(d, a, w, "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"initialize\",\"params\":{\"protocolVersion\":2,\"capabilities\":{},\"info\":{\"name\":\"t\",\"version\":\"1\"}}}");+ try engine.handleLine(d, a, w, "{\"jsonrpc\":\"2.0\",\"id\":2,\"method\":\"session/new\",\"params\":{\"cwd\":\"/tmp\",\"mcpServers\":[]}}");+}++test "v2 prompt: messageId ack, user_message, running, chunks, idle end_turn" {+ defer v2.resetForTest();+ const was = engine.cancel_flag.swap(false, .acq_rel);+ defer engine.cancel_flag.store(was, .release);+ const extra = engine.extra_cancelled;+ engine.extra_cancelled = null;+ defer engine.extra_cancelled = extra;+ var state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer state.deinit();+ const a = state.allocator();+ var out: Io.Writer.Allocating = .init(a);+ var d: engine.Dispatch = .{ .turn = echoTurn, .ctx = undefined };+ try v2Session(&d, a, &out.writer);+ const init = out.writer.buffered();+ try std.testing.expect(std.mem.indexOf(u8, init, "\"protocolVersion\":2,\"capabilities\"") != null);+ try std.testing.expect(v2.on());+ out.clearRetainingCapacity();+ try engine.handleLine(&d, a, &out.writer, "{\"jsonrpc\":\"2.0\",\"id\":3,\"method\":\"session/prompt\",\"params\":{\"sessionId\":\"acp-0-1\",\"prompt\":[{\"type\":\"text\",\"text\":\"ping\"}]}}");+ const bytes = out.writer.buffered();+ const ack = std.mem.indexOf(u8, bytes, "\"id\":3,\"result\":{\"messageId\":\"msg_user_") orelse return error.MissingAck;+ const user = std.mem.indexOf(u8, bytes, "\"sessionUpdate\":\"user_message\"") orelse return error.MissingUserMessage;+ const running = std.mem.indexOf(u8, bytes, "\"state\":\"running\"") orelse return error.MissingRunning;+ const chunk = std.mem.indexOf(u8, bytes, "\"sessionUpdate\":\"agent_message_chunk\",\"messageId\":\"msg_agent_") orelse return error.MissingChunk;+ const idle = std.mem.indexOf(u8, bytes, "\"state\":\"idle\",\"stopReason\":\"end_turn\"") orelse return error.MissingIdle;+ try std.testing.expect(ack < user and user < running and running < chunk and chunk < idle);+ try std.testing.expect(std.mem.indexOf(u8, bytes, "\"text\":\"echo:ping\"") != null);+ try std.testing.expect(std.mem.indexOf(u8, bytes, "stopReason\":\"end_turn\"}}") != null);+ try std.testing.expectEqual(@as(usize, 1), std.mem.count(u8, bytes, "\"id\":3"));+}++test "v2 prompt: a failed turn is already accepted, so it idles with _error" {+ defer v2.resetForTest();+ const Failing = struct {+ fn turn(_: *anyopaque, _: Allocator, _: []const u8) anyerror![]const u8 {+ return error.ApiError;+ }+ };+ var state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer state.deinit();+ const a = state.allocator();+ var out: Io.Writer.Allocating = .init(a);+ var d: engine.Dispatch = .{ .turn = Failing.turn, .ctx = undefined };+ try v2Session(&d, a, &out.writer);+ out.clearRetainingCapacity();+ try engine.handleLine(&d, a, &out.writer, "{\"jsonrpc\":\"2.0\",\"id\":4,\"method\":\"session/prompt\",\"params\":{\"sessionId\":\"acp-0-1\",\"prompt\":\"x\"}}");+ const bytes = out.writer.buffered();+ try std.testing.expect(std.mem.indexOf(u8, bytes, "\"error\"") == null);+ try std.testing.expect(std.mem.indexOf(u8, bytes, "\"stopReason\":\"_error\",\"_meta\":{\"graff/error\":\"ApiError\"}") != null);+}++test "v1 prompt shape is untouched when the gate is closed" {+ defer v2.resetForTest();+ var state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer state.deinit();+ const a = state.allocator();+ var out: Io.Writer.Allocating = .init(a);+ var d: engine.Dispatch = .{ .turn = echoTurn, .ctx = undefined };+ v2.gate = false;+ try engine.handleLine(&d, a, &out.writer, "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"initialize\",\"params\":{\"protocolVersion\":2}}");+ try engine.handleLine(&d, a, &out.writer, "{\"jsonrpc\":\"2.0\",\"id\":2,\"method\":\"session/new\"}");+ try engine.handleLine(&d, a, &out.writer, "{\"jsonrpc\":\"2.0\",\"id\":3,\"method\":\"session/prompt\",\"params\":{\"prompt\":\"x\"}}");+ const bytes = out.writer.buffered();+ try std.testing.expect(std.mem.indexOf(u8, bytes, "\"protocolVersion\":1,\"agentCapabilities\"") != null);+ try std.testing.expect(std.mem.indexOf(u8, bytes, "\"id\":3,\"result\":{\"stopReason\":\"end_turn\"}") != null);+ try std.testing.expect(std.mem.indexOf(u8, bytes, "messageId") == null);+ try std.testing.expect(std.mem.indexOf(u8, bytes, "state_update") == null);+}diff --git a/src/main.zig b/src/main.zigindex 4967db7a..72898916 100644--- a/src/main.zig+++ b/src/main.zig@@ -579,7 +579,7 @@ test { // ── Unit tests (`zig build test`): pull in tests from imported modu_ = .{ @import("http2_pool.zig"), @import("agent_stream_h2.zig"), @import("agent_stream_h2_transport_test.zig") }; // h2 stream path, and graff's request/response contract over the pinned http-zig_ = @import("tui_acp_updates.zig");_ = @import("acp_preauth.zig"); // credential-free ACP loop must stay in the test root- _ = .{ @import("acp_protocol.zig"), @import("subagent_mimo_tests.zig"), @import("mimo_effort_tests.zig"), @import("gateway_picker_catalog.zig") };+ _ = .{ @import("acp_protocol.zig"), @import("acp_v2.zig"), @import("acp_v2_prompt.zig"), @import("acp_engine_test.zig"), @import("subagent_mimo_tests.zig"), @import("mimo_effort_tests.zig"), @import("gateway_picker_catalog.zig") };_ = @import("task_outcome.zig"); // goal-outcome telemetry events_ = @import("learn_delete.zig"); // #303: its tests were dead until listed here_ = .{ @import("additional_tests.zig"), @import("req_stats.zig"), @import("exact_reply.zig"), @import("rlm_order_tests.zig"), @import("async_tool_policy.zig"), @import("agent_async_tools.zig"), @import("request_usage_attempts.zig"), @import("learn_formal.zig") };