Skip to content

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

Python

ACP: saved views carry _meta["graff/view"] on the completed tool update

justrachad68cd4cdf79
diff --git a/build.zig b/build.zig
index 5f3cbee0..2decf784 100644
--- a/build.zig
+++ b/build.zig
@@ -150,6 +150,9 @@ pub fn build(b: *std.Build) void {
const acp_harness_room_test = b.addSystemCommand(&.{ "python3", "scripts/test-acp-harness-room.py" });
acp_harness_room_test.addArtifactArg(exe);
test_step.dependOn(&acp_harness_room_test.step);
+ const acp_view_meta_test = b.addSystemCommand(&.{ "python3", "scripts/test-acp-view-meta.py" });
+ acp_view_meta_test.addArtifactArg(exe);
+ test_step.dependOn(&acp_view_meta_test.step);
const acp_ask_user_test = b.addSystemCommand(&.{ "python3", "scripts/test-acp-ask-user.py" });
acp_ask_user_test.addArtifactArg(exe);
test_step.dependOn(&acp_ask_user_test.step);
diff --git a/docs/acp-compatibility.md b/docs/acp-compatibility.md
index 7f805882..52f02bfc 100644
--- a/docs/acp-compatibility.md
+++ b/docs/acp-compatibility.md
@@ -37,6 +37,7 @@ optional feature or draft extension is enabled.
| Context meter | Standard `usage_update` (stable in ACP v1): `used` tokens in context and the model's `size`, plus `cost` `{amount, currency: "USD"}` only when every call so far was priced. Sent after tool steps whenever the count moved (so it drops visibly after compaction) and at the end of each prompt turn. | `src/acp_context_meter.zig`, `src/acp_engine_test.zig` |
| 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 | 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 |
+| Saved views | A completed `tool_call_update` whose result saved a `render_html` page or an MCP Apps result also carries `_meta["graff/view"]` = `{kind: "html" \| "mcp_app", id, path}`. `id` is the 32-hex snapshot name under `.graff/views` or `.graff/mcp-apps`; resolve by id and treat `path` as informational. The `[Rendered view](…)` / `[MCP app](…)` text link stays in the content. Replayed on `session/load`. | `scripts/test-acp-view-meta.py`, `src/acp_view_meta.zig` |
| Compaction | When the root agent compacts (automatically, `/compact`, or server-side), graff sends `compaction_update` `{compactionId, status}`: `in_progress`, then one of `completed` (a local summary rides `summary` as a text block), `failed` (with `error`) or `cancelled`. A provider that compacted in-stream gets one `completed`. ACP v1 marks this unstable, so it is sent only to clients that advertise `clientCapabilities.session.compaction`; ACP v2 clients always get it. | `src/acp_compaction.zig`, `scripts/test-acp-compaction.py` |
| 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` |
diff --git a/scripts/test-acp-view-meta.py b/scripts/test-acp-view-meta.py
new file mode 100644
index 00000000..29493504
--- /dev/null
+++ b/scripts/test-acp-view-meta.py
@@ -0,0 +1,102 @@
+#!/usr/bin/env python3
+"""A saved view reaches an ACP client as structured metadata.
+
+- a `render_html` result's completed `tool_call_update` carries
+ `_meta["graff/view"] = {kind: "html", id, path}`; the id names the snapshot
+ under `$HOME/.graff/views`, which holds the model's page byte-for-byte
+- the text link stays in the content for clients that do not read `_meta`
+- an ordinary tool result carries no `graff/view`
+"""
+import json, os, queue, shutil, subprocess, sys, tempfile, threading, time
+from pathlib import Path
+sys.path.insert(0, str(Path(__file__).resolve().parent / 'eval'))
+from mock_model import ScriptedModel
+
+PAGE = '<!doctype html><title>Flow</title><h1 style="color:#059669">Flow</h1>'
+
+
+def main():
+ binary = str(Path(sys.argv[1] if len(sys.argv) > 1 else 'zig-out/bin/graff').resolve())
+ temp = tempfile.mkdtemp(prefix='acp-view-meta-')
+ proc = None
+ model = ScriptedModel([
+ {'tool': 'read_file', 'arguments': {'path': 'notes.txt'}},
+ {'tool': 'render_html', 'arguments': {'html': PAGE}},
+ {'text': 'Drew it.'},
+ ])
+ try:
+ root = Path(temp)
+ work = root / 'proj'
+ work.mkdir()
+ (work / 'notes.txt').write_text('plain notes\n')
+ env = {k: v for k, v in os.environ.items() if not k.endswith('_API_KEY')}
+ env.update(HOME=temp, USERPROFILE=temp, AI_GATEWAY_API_KEY='local', GRAFF_NO_TELEMETRY='1',
+ GRAFF_FLEET='off', GRAFF_NO_SMOLIFY='1', GRAFF_NO_CODEDB_GUARD='1')
+ port = model.start(0)
+ env['GRAFF_VERCEL_URL'] = f'http://127.0.0.1:{port}/v1/chat/completions'
+ proc = subprocess.Popen([binary, 'acp', '--model', 'vercel', '--old', '--no-lean'], cwd=work, env=env,
+ stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True,
+ encoding='utf-8', errors='replace', start_new_session=os.name == 'posix')
+ messages = queue.Queue()
+
+ def read():
+ for line in proc.stdout:
+ try:
+ messages.put(json.loads(line))
+ except ValueError:
+ pass
+ messages.put(None)
+ threading.Thread(target=read, daemon=True).start()
+
+ def send(obj):
+ proc.stdin.write(json.dumps({'jsonrpc': '2.0', **obj}) + '\n')
+ proc.stdin.flush()
+
+ updates = []
+
+ def wait(id, timeout=60):
+ deadline = time.monotonic() + timeout
+ while True:
+ m = messages.get(timeout=max(.01, deadline - time.monotonic()))
+ assert m is not None, 'graff acp exited'
+ if m.get('method') == 'session/request_permission':
+ send({'id': m['id'], 'result': {'outcome': {'outcome': 'selected', 'optionId': 'allow_once'}}})
+ if m.get('method') == 'session/update':
+ updates.append(m['params']['update'])
+ if m.get('id') == id and 'method' not in m:
+ return m
+
+ send({'id': 1, 'method': 'initialize', 'params': {'protocolVersion': 1, 'clientCapabilities': {'fs': {}}}})
+ wait(1)
+ send({'id': 2, 'method': 'session/new', 'params': {'cwd': str(work), 'mcpServers': []}})
+ sid = wait(2)['result']['sessionId']
+ send({'id': 3, 'method': 'session/prompt', 'params': {'sessionId': sid, 'prompt': [{'type': 'text', 'text': 'draw the flow'}]}})
+ done = wait(3)
+ assert done.get('result', {}).get('stopReason') == 'end_turn', done
+
+ finished = [u for u in updates if u.get('sessionUpdate') == 'tool_call_update' and u.get('status') in ('completed', 'failed') and u.get('content')]
+ views = [u for u in finished if (u.get('_meta') or {}).get('graff/view')]
+ assert len(views) == 1, f'expected one view result, got {len(views)}: {finished}'
+ view = views[0]['_meta']['graff/view']
+ assert view['kind'] == 'html', view
+ assert len(view['id']) == 32 and all(c in '0123456789abcdef' for c in view['id']), view
+ saved = Path(temp) / '.graff' / 'views' / f"{view['id']}.html"
+ assert saved.read_text() == PAGE, 'the id does not name the saved page'
+ assert Path(view['path']).resolve() == saved.resolve(), view
+ text = views[0]['content'][0]['content']['text']
+ assert text.startswith('[Rendered view]('), text
+ print('PASS a render_html result carries _meta graff/view {kind, id, path}; the id names the saved page; the text link stays', flush=True)
+
+ plain = [u for u in finished if u is not views[0]]
+ assert plain and not any((u.get('_meta') or {}).get('graff/view') for u in plain), plain
+ print('PASS an ordinary tool result carries no graff/view', flush=True)
+ finally:
+ if proc and proc.poll() is None:
+ proc.kill()
+ proc.wait(timeout=10)
+ model.stop()
+ shutil.rmtree(temp, ignore_errors=True)
+
+
+if __name__ == '__main__':
+ main()
diff --git a/src/acp.zig b/src/acp.zig
index a9482def..26ca7386 100644
--- a/src/acp.zig
+++ b/src/acp.zig
@@ -546,6 +546,7 @@ test {
_ = @import("acp_stream.zig");
_ = @import("transport_gate.zig");
_ = @import("acp_mcp_app.zig");
+ _ = @import("acp_view_meta.zig");
}
test "ACP advertises the complete REPL command catalog including compact" {
diff --git a/src/acp_replay.zig b/src/acp_replay.zig
index 9a2b97f5..cc851cb7 100644
--- a/src/acp_replay.zig
+++ b/src/acp_replay.zig
@@ -81,15 +81,7 @@ fn finishCall(arena: Allocator, w: *Io.Writer, sid: []const u8, calls: *std.Arra
};
const text = try visibleText(arena, output);
if (text.len > 0) {
- try proto.writeNotification(w, "session/update", .{
- .sessionId = sid,
- .update = .{
- .sessionUpdate = "tool_call_update",
- .toolCallId = id,
- .status = if (failed) "failed" else "completed",
- .content = .{.{ .type = "content", .content = .{ .type = "text", .text = text } }},
- },
- });
+ try @import("acp_view_meta.zig").writeDone(w, sid, id, if (failed) "failed" else "completed", text);
} else {
try proto.writeNotification(w, "session/update", .{
.sessionId = sid,
diff --git a/src/acp_stream.zig b/src/acp_stream.zig
index 701aae2f..555e2dc2 100644
--- a/src/acp_stream.zig
+++ b/src/acp_stream.zig
@@ -112,17 +112,7 @@ pub fn writeToolDone(w: *Io.Writer, session_id: []const u8, id: []const u8, is_e
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,
- .update = .{
- .sessionUpdate = "tool_call_update",
- .toolCallId = id,
- .status = status,
- .content = .{
- .{ .type = "content", .content = .{ .type = "text", .text = text } },
- },
- },
- });
+ try @import("acp_view_meta.zig").writeDone(w, session_id, id, status, text);
}
fn storeId(id_buf: *[64]u8, id: []const u8) []const u8 {
diff --git a/src/acp_view_meta.zig b/src/acp_view_meta.zig
new file mode 100644
index 00000000..d63d1797
--- /dev/null
+++ b/src/acp_view_meta.zig
@@ -0,0 +1,108 @@
+//! A tool result that saved a view carries it as structured ACP metadata.
+//!
+//! `render_html` and MCP Apps results each write one private HTML snapshot
+//! (html_view.zig, mcp_apps.zig) and start their result text with a link to
+//! it. A client that shows views should not have to parse that text, so the
+//! completed `tool_call_update` also carries
+//! `_meta["graff/view"] = {"kind": "html" | "mcp_app", "path": …, "id": …}`.
+//! The text link stays for every other client.
+//!
+//! Only graff's own snapshot shape is recognized: the link opens the result,
+//! and its path ends in `/.graff/views/<32 hex>.html` or
+//! `/.graff/mcp-apps/<32 hex>.html`. A client must still refuse anything
+//! outside those two directories; this is a hint, not an authorization.
+
+const std = @import("std");
+const Io = std.Io;
+const proto = @import("acp_protocol.zig");
+
+pub const View = struct {
+ kind: []const u8,
+ path: []const u8,
+ id: []const u8,
+};
+
+const shapes = [_]struct { prefix: []const u8, kind: []const u8, dir: []const u8 }{
+ .{ .prefix = "[Rendered view](", .kind = "html", .dir = "/.graff/views/" },
+ .{ .prefix = "[MCP app](", .kind = "mcp_app", .dir = "/.graff/mcp-apps/" },
+};
+
+pub fn detect(text: []const u8) ?View {
+ for (shapes) |s| {
+ if (!std.mem.startsWith(u8, text, s.prefix)) continue;
+ const rest = text[s.prefix.len..];
+ const close = std.mem.indexOfScalar(u8, rest, ')') orelse return null;
+ const path = rest[0..close];
+ const tail_len = s.dir.len + 32 + ".html".len;
+ if (path.len <= tail_len) return null;
+ const tail = path[path.len - tail_len ..];
+ if (!std.mem.startsWith(u8, tail, s.dir) or !std.mem.endsWith(u8, tail, ".html")) return null;
+ const id = tail[s.dir.len .. s.dir.len + 32];
+ for (id) |c| if (!std.ascii.isDigit(c) and !(c >= 'a' and c <= 'f')) return null;
+ return .{ .kind = s.kind, .path = path, .id = id };
+ }
+ return null;
+}
+
+/// The completed `tool_call_update` for a result with text, plus the view
+/// metadata when the text opens with a saved view.
+pub fn writeDone(w: *Io.Writer, session_id: []const u8, id: []const u8, status: []const u8, text: []const u8) !void {
+ const content = .{.{ .type = "content", .content = .{ .type = "text", .text = text } }};
+ if (detect(text)) |v| {
+ return proto.writeNotification(w, "session/update", .{
+ .sessionId = session_id,
+ .update = .{
+ .sessionUpdate = "tool_call_update",
+ .toolCallId = id,
+ .status = status,
+ .content = content,
+ ._meta = .{ .@"graff/view" = v },
+ },
+ });
+ }
+ try proto.writeNotification(w, "session/update", .{
+ .sessionId = session_id,
+ .update = .{
+ .sessionUpdate = "tool_call_update",
+ .toolCallId = id,
+ .status = status,
+ .content = content,
+ },
+ });
+}
+
+const testing = std.testing;
+const hex = "0123456789abcdef0123456789abcdef";
+
+test "detect: graff's own view and MCP app snapshots" {
+ const html = detect("[Rendered view](/home/u/.graff/views/" ++ hex ++ ".html) — shown").?;
+ try testing.expectEqualStrings("html", html.kind);
+ try testing.expectEqualStrings("/home/u/.graff/views/" ++ hex ++ ".html", html.path);
+ try testing.expectEqualStrings(hex, html.id);
+ const app = detect("[MCP app](C:\\Users\\u/.graff/mcp-apps/" ++ hex ++ ".html) — saved\nrest").?;
+ try testing.expectEqualStrings("mcp_app", app.kind);
+ try testing.expectEqualStrings(hex, app.id);
+}
+
+test "detect: anything else is plain text" {
+ try testing.expect(detect("done") == null);
+ try testing.expect(detect("see [Rendered view](/home/u/.graff/views/" ++ hex ++ ".html)") == null); // not at the start
+ try testing.expect(detect("[Rendered view](/etc/passwd)") == null);
+ try testing.expect(detect("[Rendered view](/home/u/.graff/mcp-apps/" ++ hex ++ ".html)") == null); // wrong dir for the kind
+ try testing.expect(detect("[MCP app](/home/u/.graff/mcp-apps/" ++ "0123456789ABCDEF0123456789abcdef" ++ ".html)") == null);
+ try testing.expect(detect("[MCP app](/home/u/.graff/mcp-apps/short.html)") == null);
+ try testing.expect(detect("[Rendered view](/home/u/.graff/views/" ++ hex ++ ".html") == null); // unclosed
+}
+
+test "writeDone: a view result carries _meta graff/view; other results do not" {
+ var buf: [4096]u8 = undefined;
+ var w: Io.Writer = .fixed(&buf);
+ try writeDone(&w, "s1", "call-1", "completed", "[Rendered view](/h/.graff/views/" ++ hex ++ ".html) — shown");
+ const out = w.buffered();
+ try testing.expect(std.mem.indexOf(u8, out, "\"graff/view\":{\"kind\":\"html\",\"path\":\"/h/.graff/views/" ++ hex ++ ".html\",\"id\":\"" ++ hex ++ "\"}") != null);
+ try testing.expect(std.mem.indexOf(u8, out, "[Rendered view]") != null); // the text link stays
+ var buf2: [1024]u8 = undefined;
+ var w2: Io.Writer = .fixed(&buf2);
+ try writeDone(&w2, "s1", "call-2", "completed", "plain");
+ try testing.expect(std.mem.indexOf(u8, w2.buffered(), "graff/view") == null);
+}