graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
feat(acp): stream thought and tool updates mid-turn
Cursor Agentf82b8a004b93
diff --git a/apps/native/.env.example b/apps/native/.env.exampleindex 55eb9d1c..57855c78 100644--- a/apps/native/.env.example+++ b/apps/native/.env.example@@ -1,18 +1,14 @@-# Optional. The Next.js proxy talks to graff serve on this URL.-# Start the bridge from the repo root: zig-out/bin/graff serve --port 8787-GRAFF_SERVE_URL=http://127.0.0.1:8787+# Optional path to the graff binary. Defaults to ../../zig-out/bin/graff+# when this app is started from apps/native.+GRAFF_BIN=-# Optional Bearer token (HARNESS_SERVE_TOKEN / graff serve --token).-# Required by graff on non-loopback binds; also the switch that opens CORS-# on the bridge itself. The UI always goes through /api/graff, so the-# browser never needs this.-HARNESS_SERVE_TOKEN=+# Workspace the ACP child should run in. Defaults to the repo root.+GRAFF_CWD=+GRAFF_ACP_CWD=-# Skip bash/tool permission prompts on the child (graff --yolo).-GRAFF_YOLO=1+# Skip bash/tool permission prompts on the child (graff acp --yolo).+# Default is on: ACP has no session/request_permission UI yet.+# GRAFF_YOLO=0-# Default model or provider id for new sessions (e.g. gpt-5.5, claude-opus-4-8, codex).+# Default model or provider id for new sessions (e.g. gpt-5.5, claude-opus-4-8, grok-4.6).NEXT_PUBLIC_GRAFF_MODEL=--# Workspace the child process should run in. Defaults to the repo root.-GRAFF_CWD=diff --git a/apps/native/README.md b/apps/native/README.mdindex b7158bbf..b437d920 100644--- a/apps/native/README.md+++ b/apps/native/README.md@@ -7,8 +7,9 @@ surface:(no Electron). merjs is a separate repo; we copied only the window pattern.- **UI:** [Beautiful UI](https://github.com/slev12397/beautiful-ui) primitives(MIT) + design tokens, composed as a graff harness.-- **Backend:** this repo's `graff serve` HTTP/NDJSON bridge (same `--json`- events the TypeScript SDK already speaks).+- **Backend:** this repo's `graff acp` (Agent Client Protocol over stdio).+ Mid-turn `session/update` notifications render thinking and tool use from+ the first call (ADR 0032). `graff serve` is not required.## What was copied, what was dropped@@ -35,33 +36,33 @@ Kept (free): `tailwindcss` v4, `shadow-plugin`, `glimm` (prompt-bar sweep),## How the harness talks to graff```-browser → Next.js /api/graff/* → graff serve → graff --json child- (this app) :8787 NDJSON events+browser → Next.js /api/acp → graff acp --yolo (stdio JSON-RPC)+ (this app) session/update → thought / tools / text```-The proxy exists because `graff serve` only opens CORS when a Bearer token is-set. Same-origin `/api/graff` keeps the browser simple.+The Next.js route owns one `graff acp` child. The browser never speaks+stdio; it POSTs ACP methods and reads an NDJSON stream of the same+JSON-RPC lines the agent wrote.-| graff event | primitive |+| ACP `sessionUpdate` | primitive || --- | --- |-| `reasoning` / `model_call_started` | `ThinkingState` |-| `text` | `StreamingText` |-| `tool_call` / `tool_result` | `ToolChips` (+ diff chips for edits) |-| `ask_user` | `ApprovalCard` → `{"type":"answer"}` |-| `todo_write` | `TaskRows` in the side pane |-| `turn` / `error` | settle / error line |+| `agent_thought_chunk` | `ThinkingState` |+| `agent_message_chunk` | `StreamingText` |+| `tool_call` / `tool_call_update` | `ToolChips` (+ diff chips for edits) |+| `todo_write` in `rawInput` | `TaskRows` in the side pane |-Live-control (`set_model`, `cancel`) uses the same protocol as-`sdk/ts/remote.ts`.+`session/cancel` sets the agent's Esc interrupt. A model change respawns+the child with `--model`. Approvals (`ask_user` / `session/request_permission`)+are not on this path: the child runs `--yolo` so tools execute from the+first turn.## Run```bash-# 1. agent backend (repo root)+# 1. agent binary (repo root)zig build-./zig-out/bin/graff serve --port 8787-# 2. UI+# 2. UI — it spawns zig-out/bin/graff acp itselfcd apps/nativecp .env.example .env.local # optionalnpm install@@ -80,7 +81,10 @@ GRAFF_NATIVE_URL=http://127.0.0.1:3000 ./zig-out/bin/graff-nativeLinux has no WKWebView in the merjs shell — use the browser, or `xdg-open`from `desktop/main.zig`. See `desktop/README.md`.-`npm test` runs the event-mapper unit tests (no provider calls).+`npm test` runs the ACP and `--json` event-mapper unit tests (no provider+calls).-Offline UI check (not the real agent): `npm run mock-serve` on :8787 streams-the same NDJSON shapes so the page can be clicked without a provider key.+Set `GRAFF_BIN` if the binary is not at `zig-out/bin/graff`. Set+`GRAFF_CWD` / `GRAFF_ACP_CWD` to pin the workspace (defaults to the repo+root when the app is started from `apps/native`). `GRAFF_YOLO=0` opts out+of auto-approve (tools will be denied; ACP has no permission UI yet).diff --git a/apps/native/app/api/acp/route.ts b/apps/native/app/api/acp/route.tsnew file mode 100644index 00000000..716bd029--- /dev/null+++ b/apps/native/app/api/acp/route.ts@@ -0,0 +1,205 @@+import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process";+import { existsSync } from "node:fs";+import path from "node:path";+import { NextRequest } from "next/server";++export const runtime = "nodejs";+export const dynamic = "force-dynamic";++type Slot = {+ child: ChildProcessWithoutNullStreams;+ buf: string;+ nextId: number;+ sessionId: string | null;+ model: string | null;+};++const g = globalThis as typeof globalThis & { __graffAcp?: Slot };++function graffBin(): string {+ if (process.env.GRAFF_BIN) return process.env.GRAFF_BIN;+ const fromApp = path.resolve(process.cwd(), "../../zig-out/bin/graff");+ if (existsSync(fromApp)) return fromApp;+ const fromRoot = path.resolve(process.cwd(), "zig-out/bin/graff");+ if (existsSync(fromRoot)) return fromRoot;+ return "graff";+}++function workspace(): string {+ if (process.env.GRAFF_ACP_CWD) return process.env.GRAFF_ACP_CWD;+ if (process.env.GRAFF_CWD) return process.env.GRAFF_CWD;+ const fromApp = path.resolve(process.cwd(), "../..");+ if (existsSync(path.join(fromApp, "build.zig"))) return fromApp;+ return process.cwd();+}++function yolo(): boolean {+ const raw = process.env.GRAFF_YOLO;+ if (raw === "0" || raw === "false" || raw === "off" || raw === "no") return false;+ return true;+}++function killSlot() {+ const slot = g.__graffAcp;+ if (!slot) return;+ slot.child.kill("SIGTERM");+ g.__graffAcp = undefined;+}++function spawnAgent(model?: string): Slot {+ killSlot();+ const args = ["acp"];+ if (yolo()) args.push("--yolo");+ if (model) args.push("--model", model);+ const child = spawn(graffBin(), args, {+ stdio: ["pipe", "pipe", "inherit"],+ cwd: workspace(),+ env: process.env,+ });+ const slot: Slot = { child, buf: "", nextId: 1, sessionId: null, model: model ?? null };+ child.on("exit", () => {+ if (g.__graffAcp === slot) g.__graffAcp = undefined;+ });+ g.__graffAcp = slot;+ return slot;+}++function writeLine(slot: Slot, obj: unknown) {+ slot.child.stdin.write(`${JSON.stringify(obj)}\n`);+}++function readLine(slot: Slot, timeoutMs: number): Promise<string> {+ return new Promise((resolve, reject) => {+ const timer = setTimeout(() => reject(new Error("ACP agent timed out")), timeoutMs);+ const onData = () => {+ const nl = slot.buf.indexOf("\n");+ if (nl < 0) return;+ const line = slot.buf.slice(0, nl);+ slot.buf = slot.buf.slice(nl + 1);+ clearTimeout(timer);+ slot.child.stdout.off("data", onData);+ resolve(line);+ };+ slot.child.stdout.on("data", (chunk: Buffer) => {+ slot.buf += chunk.toString("utf8");+ onData();+ });+ onData();+ });+}++async function rpc(slot: Slot, method: string, params?: unknown): Promise<unknown> {+ const id = slot.nextId++;+ writeLine(slot, { jsonrpc: "2.0", id, method, params });+ for (;;) {+ const line = await readLine(slot, 30_000);+ let msg: { id?: unknown; result?: unknown; error?: { message?: string }; method?: string };+ try {+ msg = JSON.parse(line) as typeof msg;+ } catch {+ continue;+ }+ if (msg.method) continue;+ if (msg.id !== id) continue;+ if (msg.error) throw new Error(msg.error.message ?? "ACP error");+ return msg.result;+ }+}++async function bootstrap(model?: string, reset = false): Promise<Slot> {+ if (!reset && g.__graffAcp && (!model || g.__graffAcp.model === model) && g.__graffAcp.sessionId) {+ return g.__graffAcp;+ }+ const slot = spawnAgent(model);+ await rpc(slot, "initialize", { protocolVersion: 1, clientCapabilities: { fs: {} } });+ const created = (await rpc(slot, "session/new", { cwd: workspace() })) as {+ sessionId?: string;+ };+ if (!created?.sessionId) throw new Error("session/new returned no sessionId");+ slot.sessionId = created.sessionId;+ return slot;+}++export async function GET() {+ try {+ const slot = await bootstrap();+ return Response.json({ ok: true, sessionId: slot.sessionId });+ } catch (err) {+ return Response.json(+ {+ ok: false,+ detail: err instanceof Error ? err.message : String(err),+ hint: "Build graff (zig build) or set GRAFF_BIN. The native app speaks ACP via `graff acp`.",+ },+ { status: 502 },+ );+ }+}++export async function POST(req: NextRequest) {+ const body = (await req.json()) as { method?: string; params?: Record<string, unknown>; stream?: boolean };+ const method = body.method ?? "";+ try {+ if (method === "bootstrap") {+ const slot = await bootstrap(+ typeof body.params?.model === "string" ? body.params.model : undefined,+ body.params?.reset === true,+ );+ return Response.json({ sessionId: slot.sessionId });+ }+ const slot = await bootstrap(typeof body.params?.model === "string" ? body.params.model : undefined);+ if (method === "session/cancel") {+ writeLine(slot, { jsonrpc: "2.0", method: "session/cancel", params: body.params });+ return Response.json({ ok: true });+ }+ if (method === "session/prompt") {+ const id = slot.nextId++;+ const encoder = new TextEncoder();+ const stream = new ReadableStream({+ start(controller) {+ const onData = (chunk: Buffer) => {+ slot.buf += chunk.toString("utf8");+ let nl: number;+ while ((nl = slot.buf.indexOf("\n")) >= 0) {+ const line = slot.buf.slice(0, nl);+ slot.buf = slot.buf.slice(nl + 1);+ if (!line.trim()) continue;+ let msg: { id?: unknown; method?: string };+ try {+ msg = JSON.parse(line) as typeof msg;+ } catch {+ continue;+ }+ controller.enqueue(encoder.encode(`${line}\n`));+ if (msg.id === id && !msg.method) {+ slot.child.stdout.off("data", onData);+ controller.close();+ return;+ }+ }+ };+ slot.child.stdout.on("data", onData);+ writeLine(slot, {+ jsonrpc: "2.0",+ id,+ method: "session/prompt",+ params: { sessionId: slot.sessionId, ...body.params },+ });+ },+ cancel() {+ writeLine(slot, { jsonrpc: "2.0", method: "session/cancel", params: { sessionId: slot.sessionId } });+ },+ });+ return new Response(stream, {+ headers: { "content-type": "application/x-ndjson", "cache-control": "no-store" },+ });+ }+ const result = await rpc(slot, method, body.params);+ return Response.json({ result });+ } catch (err) {+ return Response.json(+ { error: err instanceof Error ? err.message : String(err) },+ { status: 502 },+ );+ }+}diff --git a/apps/native/components/site/GraffHarness.tsx b/apps/native/components/site/GraffHarness.tsxindex 7bc05e10..be3d3d4e 100644--- a/apps/native/components/site/GraffHarness.tsx+++ b/apps/native/components/site/GraffHarness.tsx@@ -1,8 +1,6 @@"use client";import { useEffect, useRef, useState, type CSSProperties } from "react";-import ApprovalCard from "@/components/primitives/ApprovalCard";-import LoadingState from "@/components/primitives/LoadingState";import PromptBar from "@/components/primitives/PromptBar";import SidebarNav from "@/components/primitives/SidebarNav";import StreamingText from "@/components/primitives/StreamingText";@@ -13,19 +11,13 @@ import { ThemeToggle } from "@/components/site/ThemeToggle";import {MODELS,STARTER_PROMPTS,- answer,cancel,- chat,checkHealth,- createSession,- setModel,+ ensureSession,+ prompt,type Health,-} from "@/lib/graff-client";-import {- applyEvent,- emptyTurn,- type AssistantTurn,-} from "@/lib/graff-events";+} from "@/lib/acp-client";+import { applyAcpUpdate, emptyTurn, finishAcpTurn, type AssistantTurn } from "@/lib/acp";const NAME = "there";@@ -55,13 +47,7 @@ function UserBubble({ text }: { text: string }) {);}-function AssistantBody({- turn,- onAnswer,-}: {- turn: AssistantTurn;- onAnswer: (text: string, callId?: string) => void;-}) {+function AssistantBody({ turn }: { turn: AssistantTurn }) {const reasoningRows = turn.reasoning? turn.reasoning.split(/\n+/)@@ -105,24 +91,6 @@ function AssistantBody({/></div>)}- {turn.ask && (- <div className="mt-5">- <ApprovalCard- resettable={false}- questions={[- {- q: turn.ask.question,- type: "radio",- options: ["Continue", "Skip"],- },- ]}- onSubmitted={(answers) => {- const text = answers?.[0] && answers[0] !== "Skip" ? answers[0] : answers?.[0] === "Skip" ? "" : "continue";- onAnswer(text || "continue", turn.ask?.callId);- }}- />- </div>- )}{turn.error && (<p className="mt-4 max-w-[620px] text-[13.5px] leading-[1.65] text-red">{turn.error}</p>)}@@ -187,8 +155,8 @@ function EmptyState({/>{health && !health.ok && (<p className="mt-3 text-[12.5px] text-orange">- graff serve is not reachable. From the repo root run{" "}- <span className="font-mono text-ink">graff serve --port 8787</span>+ graff acp is not reachable. From the repo root run{" "}+ <span className="font-mono text-ink">zig build</span>{health.detail ? ` — ${health.detail}` : ""}.</p>)}@@ -213,7 +181,7 @@ function EmptyState({<div className="mt-1 flex items-center gap-5 pl-0.5 text-[13px] text-ink-3"><span className="flex items-center gap-2 py-1"><span className={`size-1.5 rounded-full ${health?.ok ? "bg-green" : "bg-orange"}`} />- {health?.ok ? "Connected to graff serve" : "Waiting for graff serve"}+ {health?.ok ? "Connected over ACP" : "Waiting for graff acp"}</span><button type="button" onClick={shuffle} className="flex items-center gap-2 py-1 transition-colors duration-150 hover:text-ink">Shuffle suggestions@@ -249,10 +217,10 @@ export default function GraffHarness() {setHealth(h);if (!h.ok) return;try {- const info = await createSession({ model, yolo: true });+ const id = await ensureSession(model);if (cancelled) return;- sessionRef.current = info.session_id;- setSessionId(info.session_id);+ sessionRef.current = id;+ setSessionId(id);} catch (err) {if (!cancelled) {setHealth({ ok: false, detail: err instanceof Error ? err.message : String(err) });@@ -262,7 +230,7 @@ export default function GraffHarness() {return () => {cancelled = true;};- // session is created once per mount; model changes go through set_model+ // ACP session is created once per mount; model changes respawn the agent.// eslint-disable-next-line react-hooks/exhaustive-deps}, []);@@ -279,13 +247,13 @@ export default function GraffHarness() {);};- const ensureSession = async (): Promise<string> => {- if (sessionRef.current) return sessionRef.current;- const info = await createSession({ model, yolo: true });- sessionRef.current = info.session_id;- setSessionId(info.session_id);+ const requireSession = async (reset = false): Promise<string> => {+ if (!reset && sessionRef.current) return sessionRef.current;+ const id = await ensureSession(model, reset);+ sessionRef.current = id;+ setSessionId(id);setHealth({ ok: true });- return info.session_id;+ return id;};const send = async (text: string) => {@@ -304,46 +272,35 @@ export default function GraffHarness() {messages: [...c.messages,{ id: userId, role: "user", text: trimmed },- { id: asstId, role: "assistant", turn: emptyTurn() },+ { id: asstId, role: "assistant", turn: { ...emptyTurn(), model } },],},),);setBusy(true);- let turn = emptyTurn();+ let turn: AssistantTurn = { ...emptyTurn(), model };try {- const id = await ensureSession();- for await (const ev of chat(id, trimmed)) {- turn = applyEvent(turn, ev);+ const id = await requireSession();+ for await (const update of prompt(id, trimmed)) {+ turn = applyAcpUpdate(turn, update);patchAssistant(chatThread.id, asstId, turn);}+ turn = finishAcpTurn(turn);+ patchAssistant(chatThread.id, asstId, turn);} catch (err) {- turn = applyEvent(turn, { type: "error", message: err instanceof Error ? err.message : String(err) });+ turn = { ...turn, error: err instanceof Error ? err.message : String(err), status: "error" };patchAssistant(chatThread.id, asstId, turn);} finally {setBusy(false);}};- const answerAsk = async (text: string, callId?: string) => {- const id = sessionRef.current;- if (!id || !lastAssistant) return;- try {- await answer(id, { text, callId });- patchAssistant(chatThread.id, lastAssistant.id, { ...lastAssistant.turn, ask: undefined, status: "streaming" });- } catch (err) {- patchAssistant(chatThread.id, lastAssistant.id, {- ...lastAssistant.turn,- error: err instanceof Error ? err.message : String(err),- status: "error",- });- }- };-const newChat = () => {const id = (chatIdRef.current += 1);setChats((current) => [...current, { id, title: null, messages: [] }]);setActiveId(id);+ sessionRef.current = null;+ void requireSession(true).catch(() => undefined);};const closeChat = (id: number) => {@@ -452,14 +409,9 @@ export default function GraffHarness() {message.role === "user" ? (<UserBubble key={message.id} text={message.text} />) : (- <AssistantBody key={message.id} turn={message.turn} onAnswer={answerAsk} />+ <AssistantBody key={message.id} turn={message.turn} />),)}- {busy && lastAssistant?.turn.status === "thinking" && !lastAssistant.turn.reasoning && (- <div className="flex min-h-6 items-center">- <LoadingState label="Thinking" variant="Dots" />- </div>- )}</div></div><div className="shrink-0 bg-page px-4 pt-3 pb-6 sm:px-8">@@ -472,7 +424,13 @@ export default function GraffHarness() {modelKey={model}onModelChange={(key) => {setModelKey(key);- if (sessionRef.current) void setModel(sessionRef.current, key);+ sessionRef.current = null;+ void ensureSession(key, true)+ .then((id) => {+ sessionRef.current = id;+ setSessionId(id);+ })+ .catch(() => undefined);}}onSend={send}disabled={busy}diff --git a/apps/native/desktop/README.md b/apps/native/desktop/README.mdindex b43b1d1b..9f1a7303 100644--- a/apps/native/desktop/README.md+++ b/apps/native/desktop/README.md@@ -6,10 +6,9 @@ no Electron, no merjs SSR). merjs itself stays a separate repo; we onlycopied the window shell.```bash-# UI + graff serve (any OS)+# UI (any OS) — Next.js spawns `graff acp` itself+# from the repo root: zig buildcd apps/native && npm install && npm run dev-# in another terminal, from the repo root-./zig-out/bin/graff serve --port 8787# macOS window (after the UI is listening)zig build-exe apps/native/desktop/main.zig -O ReleaseSmall \diff --git a/apps/native/lib/acp-client.ts b/apps/native/lib/acp-client.tsnew file mode 100644index 00000000..4a75f6b0--- /dev/null+++ b/apps/native/lib/acp-client.ts@@ -0,0 +1,110 @@+import { parseRpcLine, type AcpUpdate, type JsonRpcLine } from "./acp";++const BASE = "/api/acp";++export type Health = { ok: boolean; detail?: string };++async function* ndjson(res: Response): AsyncGenerator<JsonRpcLine> {+ const body = res.body;+ if (!body) throw new Error("ACP bridge had no body");+ const reader = body.getReader();+ const dec = new TextDecoder();+ let buf = "";+ try {+ while (true) {+ const { done, value } = await reader.read();+ if (done) break;+ buf += dec.decode(value, { stream: true });+ let i: number;+ while ((i = buf.indexOf("\n")) >= 0) {+ const line = buf.slice(0, i);+ buf = buf.slice(i + 1);+ const ev = parseRpcLine(line);+ if (ev) yield ev;+ }+ }+ const tail = parseRpcLine(buf);+ if (tail) yield tail;+ } finally {+ await reader.cancel().catch(() => {});+ }+}++async function rpc(method: string, params?: unknown, stream = false): Promise<Response> {+ const res = await fetch(BASE, {+ method: "POST",+ headers: { "content-type": "application/json" },+ body: JSON.stringify({ method, params, stream }),+ cache: "no-store",+ });+ if (!res.ok) {+ const detail = await res.text().catch(() => "");+ throw new Error(`ACP ${method} → ${res.status}: ${detail.slice(0, 240)}`);+ }+ return res;+}++export async function checkHealth(): Promise<Health> {+ try {+ const res = await fetch(BASE, { method: "GET", cache: "no-store" });+ if (!res.ok) return { ok: false, detail: `acp ${res.status}` };+ return (await res.json()) as Health;+ } catch (err) {+ return { ok: false, detail: err instanceof Error ? err.message : String(err) };+ }+}++export async function ensureSession(model?: string, reset = false): Promise<string> {+ const res = await rpc("bootstrap", { model, reset });+ const body = (await res.json()) as { sessionId?: string; error?: string };+ if (!body.sessionId) throw new Error(body.error ?? "ACP session/new failed");+ return body.sessionId;+}++export async function* prompt(+ sessionId: string,+ text: string,+): AsyncGenerator<AcpUpdate> {+ const res = await rpc("session/prompt", {+ sessionId,+ prompt: [{ type: "text", text }],+ }, true);+ let terminal = false;+ for await (const line of ndjson(res)) {+ if ("method" in line && line.method === "session/update") {+ yield line.params.update;+ continue;+ }+ if ("error" in line && line.error) {+ throw new Error(line.error.message);+ }+ if ("result" in line) {+ terminal = true;+ break;+ }+ }+ if (!terminal) throw new Error("ACP stream ended before session/prompt returned");+}++export async function cancel(sessionId: string): Promise<void> {+ await fetch(BASE, {+ method: "POST",+ headers: { "content-type": "application/json" },+ body: JSON.stringify({ method: "session/cancel", params: { sessionId } }),+ }).catch(() => {});+}++export const STARTER_PROMPTS = [+ { id: "files", label: "What files are here?", prompt: "What files are in this workspace? Be brief." },+ { id: "readme", label: "Summarize README.md", prompt: "Read README.md and summarize it in a short paragraph." },+ { id: "review", label: "Review the last commit", prompt: "Review HEAD against the previous commit. Stay read-only." },+ { id: "todos", label: "What's on the checklist?", prompt: "Read the current todo list and tell me what's open." },+] as const;++export const MODELS = [+ { key: "gpt-5.5", name: "GPT-5.5", tag: "OpenAI" },+ { key: "claude-opus-4-8", name: "Opus 4.8", tag: "Anthropic" },+ { key: "codex", name: "Codex", tag: "ChatGPT" },+ { key: "grok-4.6", name: "Grok 4.6", tag: "xAI" },+ { key: "kimi-k2.6", name: "Kimi K2.6", tag: "Moonshot" },+];diff --git a/apps/native/lib/acp.test.ts b/apps/native/lib/acp.test.tsnew file mode 100644index 00000000..ec5396f1--- /dev/null+++ b/apps/native/lib/acp.test.ts@@ -0,0 +1,104 @@+import { describe, it } from "node:test";+import assert from "node:assert/strict";+import { applyAcpUpdate, emptyTurn, finishAcpTurn, parseRpcLine } from "./acp.ts";++describe("parseRpcLine", () => {+ it("skips blanks and noise", () => {+ assert.equal(parseRpcLine(""), null);+ assert.equal(parseRpcLine("not-json"), null);+ });++ it("parses a session/update notification", () => {+ const line = parseRpcLine(+ '{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"s1","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"hi"}}}}',+ );+ assert.ok(line && "method" in line && line.method === "session/update");+ assert.equal(line.params.update.sessionUpdate, "agent_message_chunk");+ });+});++describe("applyAcpUpdate", () => {+ it("streams thought then text onto a live turn", () => {+ let turn = emptyTurn();+ turn = applyAcpUpdate(turn, { sessionUpdate: "agent_thought_chunk", content: { type: "text", text: "look around" } });+ assert.equal(turn.reasoning, "look around");+ assert.equal(turn.status, "thinking");+ turn = applyAcpUpdate(turn, { sessionUpdate: "agent_message_chunk", content: { type: "text", text: "Hello" } });+ turn = applyAcpUpdate(turn, { sessionUpdate: "agent_message_chunk", content: { type: "text", text: " world" } });+ assert.equal(turn.text, "Hello world");+ assert.equal(turn.status, "streaming");+ });++ it("pairs tool_call and tool_call_update onto one chip", () => {+ let turn = emptyTurn();+ turn = applyAcpUpdate(turn, {+ sessionUpdate: "tool_call",+ toolCallId: "call-1",+ title: "src/main.zig",+ kind: "read",+ status: "pending",+ rawInput: { path: "src/main.zig" },+ });+ assert.equal(turn.tools[0]?.status, "running");+ assert.equal(turn.tools[0]?.chip, "src/main.zig");+ assert.equal(turn.tools[0]?.name, "Read");+ turn = applyAcpUpdate(turn, {+ sessionUpdate: "tool_call_update",+ toolCallId: "call-1",+ status: "completed",+ content: [{ type: "content", content: { type: "text", text: "fn main" } }],+ });+ assert.equal(turn.tools[0]?.status, "ok");+ assert.equal(turn.tools[0]?.id, "call-1");+ assert.match(turn.tools[0]?.detail.at(-1)?.text ?? "", /fn main/);+ });++ it("lifts todo_write items and edit diffs", () => {+ let turn = emptyTurn();+ turn = applyAcpUpdate(turn, {+ sessionUpdate: "tool_call",+ toolCallId: "call-2",+ title: "src/main.zig",+ kind: "edit",+ status: "pending",+ rawInput: { path: "src/main.zig", old_string: "foo", new_string: "bar" },+ });+ turn = applyAcpUpdate(turn, {+ sessionUpdate: "tool_call_update",+ toolCallId: "call-2",+ status: "completed",+ content: [{ type: "content", content: { type: "text", text: "replaced 1 span" } }],+ });+ assert.equal(turn.diffs[0]?.file, "src/main.zig");++ turn = applyAcpUpdate(turn, {+ sessionUpdate: "tool_call",+ toolCallId: "call-3",+ title: "todo_write",+ kind: "think",+ status: "pending",+ rawInput: {+ todos: [+ { id: "a", content: "Read README", status: "completed" },+ { id: "b", content: "Edit main", status: "in_progress" },+ ],+ },+ });+ assert.equal(turn.todos.length, 2);+ assert.equal(turn.todos[1]?.status, "in_progress");+ });++ it("finishAcpTurn settles running chips", () => {+ let turn = emptyTurn();+ turn = applyAcpUpdate(turn, {+ sessionUpdate: "tool_call",+ toolCallId: "call-9",+ title: "ls",+ kind: "execute",+ status: "in_progress",+ });+ turn = finishAcpTurn(turn);+ assert.equal(turn.status, "done");+ assert.equal(turn.tools[0]?.status, "ok");+ });+});diff --git a/apps/native/lib/acp.ts b/apps/native/lib/acp.tsnew file mode 100644index 00000000..7b301fa5--- /dev/null+++ b/apps/native/lib/acp.ts@@ -0,0 +1,225 @@+/** ACP v1 session/update shapes the native harness renders. */++export type AcpContent = { type: "text"; text: string };++export type AcpToolKind = "read" | "edit" | "delete" | "move" | "search" | "execute" | "think" | "fetch" | "other";++export type AcpToolStatus = "pending" | "in_progress" | "completed" | "failed";++export type AcpUpdate =+ | { sessionUpdate: "agent_thought_chunk"; content: AcpContent }+ | { sessionUpdate: "agent_message_chunk"; content: AcpContent }+ | {+ sessionUpdate: "tool_call";+ toolCallId: string;+ title?: string;+ kind?: AcpToolKind | string;+ status?: AcpToolStatus | string;+ rawInput?: Record<string, unknown>;+ locations?: { path: string }[];+ }+ | {+ sessionUpdate: "tool_call_update";+ toolCallId: string;+ title?: string;+ kind?: AcpToolKind | string;+ status?: AcpToolStatus | string;+ rawInput?: Record<string, unknown>;+ content?: { type: string; content?: AcpContent }[];+ }+ | { sessionUpdate: string; [key: string]: unknown };++export type JsonRpcLine =+ | { jsonrpc?: string; method: "session/update"; params: { sessionId?: string; update: AcpUpdate } }+ | { jsonrpc?: string; id: number | string; result: unknown }+ | { jsonrpc?: string; id: number | string; error: { code: number; message: string } };++import {+ emptyTurn,+ type AssistantTurn,+ type ToolIcon,+ type ToolRow,+ type TodoItem,+} from "./graff-events";++function iconForKind(kind: string | undefined, title: string): ToolIcon {+ if (kind === "execute") return "run";+ if (kind === "edit" || kind === "delete" || kind === "move") return "write";+ if (kind === "read" || kind === "fetch" || kind === "search") return "read";+ if (title.includes("bash") || title.includes("run")) return "run";+ return "think";+}++function labelForKind(kind: string | undefined, title: string): string {+ if (kind === "execute") return "Run";+ if (kind === "edit") return "Edit";+ if (kind === "delete") return "Delete";+ if (kind === "move") return "Move";+ if (kind === "read") return "Read";+ if (kind === "fetch") return "Fetch";+ if (kind === "search") return "Search";+ if (kind === "think") return "Plan";+ return title;+}++function firstLine(s: string): string {+ const line = s.split("\n")[0] ?? s;+ return line.length > 80 ? `${line.slice(0, 79)}…` : line;+}++function detailFromInput(input: Record<string, unknown>): ToolRow["detail"] {+ const oldS = typeof input.old_string === "string" ? input.old_string : "";+ const newS = typeof input.new_string === "string" ? input.new_string : "";+ if (oldS || newS) {+ const lines: ToolRow["detail"] = [];+ if (oldS) lines.push({ text: firstLine(oldS) });+ if (newS) lines.push({ text: firstLine(newS), tone: "add" });+ return lines;+ }+ if (typeof input.command === "string") return [{ text: input.command }];+ if (typeof input.content === "string") {+ return [{ text: `${input.content.split("\n").length} lines`, tone: "add" }];+ }+ return [];+}++function mergeDiff(turn: AssistantTurn, row: ToolRow, text: string): AssistantTurn["diffs"] {+ const file = row.path ?? (row.chip !== row.name ? row.chip : "");+ if (!file) return turn.diffs;+ const lines = (text || row.detail.map((d) => d.text).join("\n"))+ .split("\n")+ .slice(0, 8)+ .map((line) => ({+ text: line.slice(0, 80),+ tone: (line.startsWith("+") ? "add" : line.startsWith("-") ? "del" : row.icon === "write" && line ? "add" : "ctx") as+ | "add"+ | "del"+ | "ctx",+ }));+ const chip = {+ file,+ add: Math.max(1, row.detail.filter((d) => d.tone === "add").length),+ del: row.icon === "write" ? 1 : 0,+ lines: lines.length ? lines : [{ text: file, tone: "ctx" as const }],+ };+ const idx = turn.diffs.findIndex((d) => d.file === file);+ if (idx < 0) return [...turn.diffs, chip];+ const next = turn.diffs.slice();+ next[idx] = chip;+ return next;+}++function parseTodos(input: Record<string, unknown> | undefined): TodoItem[] {+ const raw = input?.todos ?? input?.items ?? input?.list;+ if (!Array.isArray(raw)) return [];+ return raw.flatMap((item, i) => {+ if (!item || typeof item !== "object") return [];+ const rec = item as Record<string, unknown>;+ const content = typeof rec.content === "string" ? rec.content : typeof rec.text === "string" ? rec.text : "";+ if (!content) return [];+ const status =+ rec.status === "completed" || rec.status === "in_progress" || rec.status === "pending" ? rec.status : "pending";+ const id = typeof rec.id === "string" ? rec.id : `todo-${i}`;+ return [{ id, content, status }];+ });+}++function upsertTool(turn: AssistantTurn, update: Extract<AcpUpdate, { toolCallId: string }>): AssistantTurn {+ const id = update.toolCallId;+ const idx = turn.tools.findIndex((t) => t.id === id);+ const prev = idx >= 0 ? turn.tools[idx] : undefined;+ const title = typeof update.title === "string" ? update.title : prev?.chip ?? id;+ const kind = typeof update.kind === "string" ? update.kind : prev ? undefined : "other";+ const statusRaw = typeof update.status === "string" ? update.status : prev ? undefined : "pending";+ const status: ToolRow["status"] = statusRaw+ ? statusRaw === "completed"+ ? "ok"+ : statusRaw === "failed"+ ? "error"+ : "running"+ : (prev?.status ?? "running");+ const rawInput = update.rawInput && typeof update.rawInput === "object" ? update.rawInput : {};+ const path = typeof rawInput.path === "string" ? rawInput.path : prev?.path;+ const contentItems = "content" in update && Array.isArray(update.content) ? update.content : [];+ const contentText = contentItems+ .map((item) => item.content?.text)+ .filter((t): t is string => typeof t === "string")+ .join("\n");+ const fromInput = detailFromInput(rawInput);+ const detail = contentText+ ? [...(prev?.detail ?? fromInput), { text: firstLine(contentText) }]+ : fromInput.length+ ? fromInput+ : (prev?.detail ?? []);+ const row: ToolRow = {+ id,+ name: labelForKind(kind, title),+ icon: iconForKind(kind, title),+ chip: path ?? title,+ status,+ detail,+ path,+ };+ const tools = turn.tools.slice();+ if (idx >= 0) tools[idx] = { ...prev!, ...row, name: kind ? row.name : prev!.name, icon: kind ? row.icon : prev!.icon };+ else tools.push(row);+ const todos = parseTodos(rawInput);+ const next: AssistantTurn = {+ ...turn,+ tools,+ todos: todos.length ? todos : turn.todos,+ status: turn.status === "ask" ? "ask" : status === "running" || turn.status === "thinking" ? "streaming" : turn.status,+ };+ if ((row.icon === "write" || kind === "edit") && (status === "ok" || status === "error")) {+ return { ...next, diffs: mergeDiff(next, tools[idx >= 0 ? idx : tools.length - 1], contentText) };+ }+ return next;+}++export function finishAcpTurn(turn: AssistantTurn): AssistantTurn {+ if (turn.status === "error") return turn;+ return {+ ...turn,+ tools: turn.tools.map((t) => (t.status === "running" ? { ...t, status: "ok" as const } : t)),+ status: "done",+ };+}++export function applyAcpUpdate(turn: AssistantTurn, update: AcpUpdate): AssistantTurn {+ switch (update.sessionUpdate) {+ case "agent_thought_chunk": {+ const text = update.content?.text ?? "";+ return {+ ...turn,+ reasoning: `${turn.reasoning}${text}`,+ status: turn.status === "ask" ? "ask" : turn.text ? "streaming" : "thinking",+ };+ }+ case "agent_message_chunk": {+ const text = update.content?.text ?? "";+ return {+ ...turn,+ text: `${turn.text}${text}`,+ status: turn.status === "ask" ? "ask" : "streaming",+ };+ }+ case "tool_call":+ case "tool_call_update":+ return upsertTool(turn, update);+ default:+ return turn;+ }+}++export function parseRpcLine(line: string): JsonRpcLine | null {+ const trimmed = line.trim();+ if (!trimmed) return null;+ try {+ return JSON.parse(trimmed) as JsonRpcLine;+ } catch {+ return null;+ }+}++export { emptyTurn };+export type { AssistantTurn };diff --git a/apps/native/package.json b/apps/native/package.jsonindex 9698fa2d..b4514e7a 100644--- a/apps/native/package.json+++ b/apps/native/package.json@@ -10,7 +10,7 @@"start": "NEXT_TELEMETRY_DISABLED=1 next start --port 3000","mock-serve": "node scripts/mock-serve.mjs","lint": "next lint",- "test": "node --experimental-strip-types --test lib/graff-events.test.ts"+ "test": "node --experimental-strip-types --test lib/graff-events.test.ts lib/acp.test.ts"},"dependencies": {"glimm": "^0.3.0",diff --git a/docs/adr/0032-acp-streams-mid-turn.md b/docs/adr/0032-acp-streams-mid-turn.mdnew file mode 100644index 00000000..9ea2e691--- /dev/null+++ b/docs/adr/0032-acp-streams-mid-turn.md@@ -0,0 +1,45 @@+# 0032. ACP streams mid-turn thought, tools, and text++Status: accepted 2026-08-26++## Context++`graff acp` (#375) was v0: one `session/update` `agent_message_chunk` with+the final answer. A client could not render thinking or tool use until the+turn ended. The Beautiful UI native app first spoke `graff serve` NDJSON,+which has those events, but that is a second protocol and a second process+from the editor-facing agent.++ACP v1 already names `agent_thought_chunk`, `tool_call`, and+`tool_call_update`. Emitting those from the same `--json` events the rest+of the harness already produces keeps one translation point.++## Decision++During `session/prompt`, install a translating `Io.Writer` on `root.out`+and `g_out`. `--json` lines become ACP `session/update` notifications:++| `--json` | `sessionUpdate` |+|---|---|+| `reasoning` | `agent_thought_chunk` |+| `text` | `agent_message_chunk` |+| `tool_call` / `tool_call_started` | `tool_call` (kind from the catalog name) |+| `tool_result` / `tool_call_finished` / `tool_rejected` | `tool_call_update` |++A stub turn that emits no events still writes one final+`agent_message_chunk` (the v0 contract). A live turn that already streamed+text returns `""` so the final chunk is not duplicated.++Between prompts both writers are null (stdout stays JSON-RPC). Protocol+version stays 1 for Zed. `session/cancel` sets `esc_cancel`.+`session/request_permission` is not implemented: unattended + `--yolo` is+how a UI that wants tools from the first call runs the agent.++The native app (`apps/native`) is an ACP client via `/api/acp` →+`graff acp --yolo`. It does not require `graff serve`.++## Consequences++- Zed and the native app see the same mid-turn shapes.+- Approvals stay off ACP until we grow `session/request_permission`.+- `set_model` is not an ACP method; a model change respawns the child.diff --git a/docs/adr/README.md b/docs/adr/README.mdindex e1afd392..aa6b60a9 100644--- a/docs/adr/README.md+++ b/docs/adr/README.md@@ -42,6 +42,7 @@ record only when you need the evidence or the edge cases.| [0029](0029-mcp-inside-rlm-and-return-shapes.md) | Loaded MCP tools are rlm host functions; persist return shapes on the load result, never the prefix; fat MCP results auto-slim; default `-p` connects `.mcp.json` (folded, not skipped). || [0030](0030-rlm-late-showcase.md) | Small turns hide `rlm` (and sPTC). Showcase on `--rlm`, a ≥4 native batch, context ≥50% of compactAt, or an explicit load — never on MCP fan-out or the prefix. || [0031](0031-xai-hosted-x-search.md) | xAI Responses splices hosted `x_search` onto tools turns. It is not a catalog function; `GRAFF_XAI_X_SEARCH=0` opts out. |+| [0032](0032-acp-streams-mid-turn.md) | `graff acp` streams thought / tool / text `session/update`s mid-turn. The native app is an ACP client; it does not need `graff serve`. |## When to write onediff --git a/src/acp.zig b/src/acp.zigindex f421bfcd..c0d07c8f 100644--- a/src/acp.zig+++ b/src/acp.zig@@ -1,48 +1,18 @@//! ACP (Agent Client Protocol) AGENT mode — `graff acp` (#375, "ACP first").//!//! ACP is Zed's editor↔agent protocol: JSON-RPC 2.0 over stdio, one message-//! per line. The editor is the CLIENT, graff is the AGENT. This module is the-//! whole surface: the read loop, the method dispatch, and the translation-//! between ACP content blocks and one real graff root turn.+//! per line. The editor is the CLIENT, graff is the AGENT.//!-//! v0 scope (deliberate, see "deviations" at the bottom of this comment):-//! initialize → protocolVersion (min of the client's and ours) + our-//! agentCapabilities.-//! session/new → mints one session id. ONE live session per process.-//! session/prompt → flattens the ContentBlock array to text, runs ONE full-//! root turn (tools + MCP + subagents, same loop `-p` uses),-//! emits one `session/update` agent_message_chunk carrying-//! the final text, then answers `{stopReason:"end_turn"}`.-//! anything else → -32601. Notifications (no `id`) are NEVER answered.+//! Mid-turn, --json events become `session/update` notifications (thought,+//! text, tool_call / tool_call_update) so a client can render tools from the+//! first call. A stub turn that emits no events still writes one final+//! agent_message_chunk (the v0 contract the unit tests pin).//!-//! Why the conversation persists: unlike `-p`, every session/prompt appends to-//! the SAME `root.messages`, so turn N sees turns 1..N-1. That is the entire-//! point of a session protocol, and it is why the unattended setup below runs-//! exactly once, outside the loop.-//!-//! stdout discipline — the load-bearing invariant. Only protocol JSON may ever-//! reach stdout, so three separate producers are shut off:-//! 1. `isAcpSubcommand` (called from args.zig's positional-subcommand test)-//! flips `main_mod.json_mode`, which is what silences every startup banner-//! — those print long before this function runs, so the switch has to be-//! thrown during flag parsing, not here.-//! 2. `root.out = null` kills the root agent's own say()/emit() (say falls-//! back to stderr; emit no-ops on a null writer).-//! 3. `main_mod.g_out = null` kills guiEmit — the pool-thread subagent and-//! workflow-progress emitters write --json events straight to that global-//! stdout alias, and json_mode is now on, so leaving it set would let a-//! subagent interleave JSONL into the ACP stream.-//!-//! Deviations from the spec, made knowingly for v0:-//! * No client callbacks at all (no fs/read_text_file, no-//! session/request_permission). graff reads and writes files itself and-//! the gate runs unattended, exactly as in `-p`.-//! * `sessionId` on session/prompt is accepted as given rather than checked-//! against the live session, and it is echoed back on the update. One-//! process holds one session, so there is nothing to disambiguate, and a-//! scripted client can prompt without first parsing session/new's reply.-//! * loadSession is advertised false; session/load is therefore -32601.-//! * One update per turn (the final text), not streaming chunks.+//! stdout discipline: `isAcpSubcommand` flips `json_mode` during flag parse+//! so startup banners never hit stdout. `root.out` is the translating sink+//! only for the duration of a prompt; `g_out` is the same writer so pool-+//! thread subagent tool rows translate too. Between prompts both are null.+const std = @import("std");const Io = std.Io;const Allocator = std.mem.Allocator;@@ -57,280 +27,130 @@ const messages_mod = @import("messages.zig");const session = @import("session.zig");const telemetry = @import("telemetry.zig");const util = @import("util.zig");+const proto = @import("acp_protocol.zig");+const stream = @import("acp_stream.zig");++pub const protocol_version = proto.protocol_version;+pub const err_method_not_found = proto.err_method_not_found;+pub const err_internal = proto.err_internal;+pub const Request = proto.Request;+pub const parseRequest = proto.parseRequest;+pub const negotiateVersion = proto.negotiateVersion;+pub const flattenPrompt = proto.flattenPrompt;+pub const writeResult = proto.writeResult;+pub const writeError = proto.writeError;+pub const writeSessionUpdate = proto.writeSessionUpdate;-/// Highest ACP protocol version this agent implements.-pub const protocol_version: i64 = 1;--// JSON-RPC 2.0 error codes used on this surface.-pub const err_method_not_found: i32 = -32601;-pub const err_internal: i32 = -32603;--/// ACP's `promptCapabilities` — empty for v0 (no audio, no embedded context,-/// no image blocks). A NAMED empty struct, not `.{}`: an empty anonymous-/// literal is a TUPLE, and std.json writes tuples as `[]`, so the inline form-/// would put an array where the spec requires an object.-const PromptCapabilities = struct {};--/// True when this positional selects `graff acp`.-///-/// SIDE EFFECT, and the reason this predicate lives here instead of inline in-/// args.zig: it also arms ACP's stdout discipline by turning on `json_mode`.-/// stdout stops being human text and becomes a strict machine protocol for the-/// rest of the process — which is exactly what `json_mode` already means, and-/// what every startup banner is already gated on. Those banners print between-/// flag parsing and `runAcpCommand`, so the flag has to be set during the-/// parse; there is no later hook that would still be early enough.pub fn isAcpSubcommand(positional: []const u8) bool {if (!std.mem.eql(u8, positional, "acp")) return false;main_mod.json_mode = true;return true;}-/// One decoded JSON-RPC message. `id == null` means NOTIFICATION — the caller-/// must not send any reply for it (a JSON `"id": null` is treated the same-/// way: it is not a value a response could be correlated by).-pub const Request = struct {- id: ?Value = null,- method: []const u8 = "",- params: ?Value = null,-};--/// Decode one inbound line, or null when there is nothing to answer: a blank-/// line, malformed JSON, a non-object, or a message with no `method` (i.e. a-/// RESPONSE to something we sent — we send no requests, so it is not ours).-/// Values borrow `arena`, which must outlive the returned Request.-pub fn parseRequest(arena: Allocator, line: []const u8) ?Request {- const trimmed = std.mem.trim(u8, line, " \t\r\n");- if (trimmed.len == 0) return null;- const v = std.json.parseFromSliceLeaky(Value, arena, trimmed, .{ .allocate = .alloc_always }) catch return null;- if (v != .object) return null;- const method = util.strFieldObj(v.object, "method") orelse return null;- const raw_id = v.object.get("id");- return .{- .id = if (raw_id) |id| (if (id == .null) null else id) else null,- .method = method,- .params = v.object.get("params"),- };-}--/// The version both sides can speak: the lower of the client's proposal and-/// ours. A missing/garbage proposal is read as "whatever you support".-pub fn negotiateVersion(params: ?Value) i64 {- const p = params orelse return protocol_version;- if (p != .object) return protocol_version;- const v = p.object.get("protocolVersion") orelse return protocol_version;- return switch (v) {- .integer => |n| @min(n, protocol_version),- .float => |f| @min(@as(i64, @intFromFloat(f)), protocol_version),- else => protocol_version,- };-}--/// The text a single ContentBlock contributes to the prompt, or null when it-/// carries none. `text` blocks give their text; `resource_link` blocks give-/// their uri (falling back to the display name) so the model at least learns-/// WHICH file the user attached. Unknown block kinds are probed for the same-/// two fields rather than dropped — a future block type that happens to carry-/// text is more useful half-read than silently discarded.-fn blockText(block: Value) ?[]const u8 {- if (block == .string) return block.string;- if (block != .object) return null;- const o = block.object;- const kind = util.strFieldObj(o, "type") orelse "";- if (std.mem.eql(u8, kind, "text")) return util.strFieldObj(o, "text");- if (std.mem.eql(u8, kind, "resource_link"))- return util.strFieldObj(o, "uri") orelse util.strFieldObj(o, "name");- return util.strFieldObj(o, "text") orelse util.strFieldObj(o, "uri");-}--/// Flatten a `prompt: [ContentBlock...]` into the single user message a graff-/// turn takes. Blocks join with a newline; empty and unreadable blocks are-/// skipped. A bare string prompt is tolerated (non-spec clients send one).-pub fn flattenPrompt(arena: Allocator, prompt: ?Value) ![]const u8 {- const blocks = switch (prompt orelse return "") {- .array => |a| a,- .string => |s| return s,- else => return "",- };- var buf: std.array_list.Managed(u8) = .init(arena);- for (blocks.items) |block| {- const text = blockText(block) orelse continue;- if (text.len == 0) continue;- if (buf.items.len != 0) try buf.append('\n');- try buf.appendSlice(text);- }- return buf.items;-}--/// `{"jsonrpc":"2.0","id":<id>,"result":<result>}` + newline.-///-/// None of the three writers below flush: the caller owns line framing and-/// flushing (and unit tests hand them a fixed writer, which cannot drain).-pub fn writeResult(w: *Io.Writer, id: ?Value, result: anytype) !void {- var s: std.json.Stringify = .{ .writer = w };- try s.beginObject();- try s.objectField("jsonrpc");- try s.write("2.0");- try s.objectField("id");- try s.write(id);- try s.objectField("result");- try s.write(result);- try s.endObject();- try w.writeByte('\n');-}--/// `{"jsonrpc":"2.0","id":<id>,"error":{"code":…,"message":…}}` + newline.-pub fn writeError(w: *Io.Writer, id: ?Value, code: i32, message: []const u8) !void {- var s: std.json.Stringify = .{ .writer = w };- try s.beginObject();- try s.objectField("jsonrpc");- try s.write("2.0");- try s.objectField("id");- try s.write(id);- try s.objectField("error");- try s.beginObject();- try s.objectField("code");- try s.write(code);- try s.objectField("message");- try s.write(message);- try s.endObject();- try s.endObject();- try w.writeByte('\n');-}--/// The one `session/update` NOTIFICATION a turn emits: an agent_message_chunk-/// carrying the turn's final text. No `id` — a notification is never answered,-/// in either direction.-pub fn writeSessionUpdate(w: *Io.Writer, session_id: []const u8, text: []const u8) !void {- var s: std.json.Stringify = .{ .writer = w };- try s.write(.{- .jsonrpc = "2.0",- .method = "session/update",- .params = .{- .sessionId = session_id,- .update = .{- .sessionUpdate = "agent_message_chunk",- .content = .{ .type = "text", .text = text },- },- },- });- try w.writeByte('\n');-}--/// Runs one root turn on `text` and returns its final text. Injected as a-/// function pointer so the protocol dispatch is unit-testable without a-/// provider, a network, or a constructed Agent.pub const TurnFn = *const fn (ctx: *anyopaque, arena: Allocator, text: []const u8) anyerror![]const u8;-/// Protocol state for one connection. `arena` values handed to `handleLine`-/// must outlive the connection — `session_id` is allocated from one.pub const Dispatch = struct {turn: TurnFn,ctx: *anyopaque,- /// Live session id, minted on the first `session/new`.session_id: ?[]const u8 = null,- /// Per-process entropy for the minted ids, so two graff agents on one bus- /// never present the same session id to a client.seed: u64 = 0,- /// How many sessions have been minted (the id's suffix).created: u32 = 0,+ /// Set only for the real stdio agent so a prompt can publish the+ /// session id onto the translating sink. Unit-test stubs leave this null.+ live: ?*LiveTurn = null,};-/// Answer a request; a notification is silently dropped instead.fn respond(w: *Io.Writer, req: Request, result: anytype) !void {if (req.id == null) return;try writeResult(w, req.id, result);}-/// Fail a request; a notification is silently dropped instead.fn respondError(w: *Io.Writer, req: Request, code: i32, message: []const u8) !void {if (req.id == null) return;try writeError(w, req.id, code, message);}-/// session/prompt: flatten the blocks, run ONE root turn, emit the update,-/// then answer with a stopReason. A budget-exhausted turn is a normal ACP-/// outcome (`max_turn_requests`), not a protocol error; anything else is-/// -32603 with the error's name, which is all a client can act on.fn promptTurn(d: *Dispatch, arena: Allocator, w: *Io.Writer, req: 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 "";};+ if (d.live) |live| live.session_id = sid;const text = try flattenPrompt(arena, if (obj) |o| o.get("prompt") else null);const final = d.turn(d.ctx, arena, text) catch |err| {if (err == error.RunBudgetExhausted)return respond(w, req, .{ .stopReason = "max_turn_requests" });return respondError(w, req, err_internal, @errorName(err));};- try writeSessionUpdate(w, sid, final);+ // Stub turns (and live turns that never streamed a text delta) still+ // publish the final answer as one chunk. A live turn that already+ // streamed `agent_message_chunk` returns "" so we do not duplicate.+ if (final.len > 0) try writeSessionUpdate(w, sid, final);try respond(w, req, .{ .stopReason = "end_turn" });}-/// Handle one inbound line, writing zero or more protocol lines to `w`.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")) return respond(w, req, .{.protocolVersion = negotiateVersion(req.params),- .agentCapabilities = .{ .loadSession = false, .promptCapabilities = PromptCapabilities{} },+ .agentCapabilities = .{ .loadSession = false, .promptCapabilities = proto.PromptCapabilities{} },});if (std.mem.eql(u8, req.method, "session/new")) {d.created += 1;d.session_id = try std.fmt.allocPrint(arena, "acp-{x}-{d}", .{ d.seed, d.created });return respond(w, req, .{ .sessionId = d.session_id.? });}+ if (std.mem.eql(u8, req.method, "session/cancel")) {+ agent_mod.Agent.esc_cancel.store(true, .release);+ if (req.id != null) return respond(w, req, .{});+ return;+ }if (std.mem.eql(u8, req.method, "session/prompt")) return promptTurn(d, arena, w, req);- // An unimplemented NOTIFICATION (session/cancel, notifications/*) is- // ignored, never answered — replying to one is itself a protocol error.- // Checked BEFORE formatting the message so a chatty client cannot make us- // allocate a reply it will never receive.if (req.id == null) return;try writeError(w, req.id, err_method_not_found, try std.fmt.allocPrint(arena, "method not found: {s}", .{req.method}));}-/// The real turn: appends to the SAME root history every time, which is what-/// makes an ACP session a conversation rather than N independent one-shots.const LiveTurn = struct {root: *agent_mod.Agent,keys: *provider_mod.Keys,+ out: *Io.Writer,+ session_id: []const u8 = "",+ saw_text: bool = false,fn run(ctx: *anyopaque, arena: Allocator, text: []const u8) anyerror![]const u8 {const self: *LiveTurn = @ptrCast(@alignCast(ctx));try self.root.messages.append(try messages_mod.textMessage(arena, "user", text));if (telemetry.g_telem) |t| t.beginTurn(@intCast(@min(text.len, std.math.maxInt(u32))), self.root.provider.model);- return providers.runTurnWithFallback(self.root, self.keys, arena, null);+ self.saw_text = false;+ var sink: stream.EventSink = undefined;+ sink.init(self.root.gpa, self.out, &self.session_id, &self.saw_text);+ defer sink.deinit();+ self.root.out = &sink.writer;+ main_mod.g_out = &sink.writer;+ defer {+ sink.writer.flush() catch {};+ self.root.out = null;+ main_mod.g_out = null;+ }+ const final = try providers.runTurnWithFallback(self.root, self.keys, arena, null);+ if (self.saw_text) return "";+ return final;}};-/// `graff acp`: serve the Agent Client Protocol on stdio until the client-/// closes stdin. Mirrors `runReplCommand`'s contract — returns false (having-/// done nothing) when this invocation is not `acp`, true once it has run the-/// whole session, at which point main() returns immediately.-///-/// `root` is already a stable, fully-constructed main()-owned Agent (keys,-/// provider, tools, MCP) by the time this is called, so taking its address is-/// ordinary pointer-passing. `arena` is the process-lifetime session arena:-/// the minted session id, every parsed request and every turn's history all-/// live there for the life of the connection, which is what lets turn N see-/// turns 1..N-1.pub fn runAcpCommand(gpa: Allocator, io: Io, environ_map: anytype, root: *agent_mod.Agent, keys: *provider_mod.Keys, client: *std.http.Client, in: *Io.Reader, out: *Io.Writer, arena: Allocator, flags: args.Flags) !bool {if (!(flags.positionals.items.len > 0 and std.mem.eql(u8, flags.positionals.items[0], "acp"))) return false;_ = environ_map;_ = client;- // Unattended setup, ONCE (see the header): the gate denies instead of- // prompting, tool progress goes to stderr, and stdout is protocol-only.main_mod.unattended = true;root.in = null;root.out = null;root.stream_quiet = true;- main_mod.g_out = null; // no guiEmit into the ACP stream- var live: LiveTurn = .{ .root = root, .keys = keys };- var d: Dispatch = .{ .turn = LiveTurn.run, .ctx = &live, .seed = @bitCast(util.unixMs(io)) };+ main_mod.g_out = null;+ var live: LiveTurn = .{ .root = root, .keys = keys, .out = out };+ var d: Dispatch = .{ .turn = LiveTurn.run, .ctx = &live, .live = &live, .seed = @bitCast(util.unixMs(io)) };while (true) {- // A read failure (including a line longer than stdin's buffer, which- // takeDelimiter leaves unconsumed) ends the session rather than- // spinning on bytes we can never make progress past.const line = (in.takeDelimiter('\n') catch break) orelse break;handleLine(&d, arena, out, line) catch |err| {std.debug.print("acp: dispatch failed: {t}\n", .{err});@@ -339,8 +159,6 @@ pub fn runAcpCommand(gpa: Allocator, io: Io, environ_map: anytype, root: *agent_out.flush() catch break;}session.saveSession(root, arena, root.session_name) catch {};- // This path returns before main() registers its REPL cleanup defer, so the- // root's gpa-backed buffers are freed here (same as the one-shot path).root.md_buf.deinit(gpa);root.md_word.deinit(gpa);for (root.md_table.items) |r| gpa.free(r);@@ -349,10 +167,6 @@ pub fn runAcpCommand(gpa: Allocator, io: Io, environ_map: anytype, root: *agent_return true;}-// ── Tests ─────────────────────────────────────────────────────────────────-// The protocol half is pure, so all of it is tested here with a stub turn:-// no provider, no network, no Agent.-const testing = std.testing;fn echoTurn(ctx: *anyopaque, arena: Allocator, text: []const u8) anyerror![]const u8 {@@ -384,16 +198,12 @@ test "parseRequest: requests, notifications, and lines that are not ours" {try testing.expectEqual(@as(i64, 7), req.id.?.integer);try testing.expectEqual(@as(i64, 3), req.params.?.object.get("protocolVersion").?.integer);- // A string id is just as valid as a numeric one and must round-trip.const str_id = parseRequest(a, "{\"id\":\"a1\",\"method\":\"session/new\"}").?;try testing.expectEqualStrings("a1", str_id.id.?.string);- // No id, and an explicit null id, are both notifications.try testing.expect(parseRequest(a, "{\"method\":\"session/cancel\"}").?.id == null);try testing.expect(parseRequest(a, "{\"id\":null,\"method\":\"x\"}").?.id == null);- // Nothing to answer: blank, malformed, non-object, and a RESPONSE (no- // method) that some client bounced back at us.try testing.expect(parseRequest(a, " \r\n") == null);try testing.expect(parseRequest(a, "{not json") == null);try testing.expect(parseRequest(a, "[1,2]") == null);@@ -412,7 +222,6 @@ test "negotiateVersion takes the lower of the two proposals" {try testing.expectEqual(@as(i64, 1), negotiateVersion(parse(a, "{\"protocolVersion\":5}")));try testing.expectEqual(@as(i64, 0), negotiateVersion(parse(a, "{\"protocolVersion\":0}")));try testing.expectEqual(@as(i64, 1), negotiateVersion(parse(a, "{\"protocolVersion\":1}")));- // Missing, mistyped, or absent params all fall back to our own version.try testing.expectEqual(@as(i64, 1), negotiateVersion(parse(a, "{}")));try testing.expectEqual(@as(i64, 1), negotiateVersion(parse(a, "{\"protocolVersion\":\"1\"}")));try testing.expectEqual(@as(i64, 1), negotiateVersion(null));@@ -433,13 +242,10 @@ test "flattenPrompt: text blocks join, resource_links contribute their uri" {"look at\nfile:///tmp/a.zig",try flattenPrompt(a, parse(a, "[{\"type\":\"text\",\"text\":\"look at\"},{\"type\":\"resource_link\",\"uri\":\"file:///tmp/a.zig\",\"name\":\"a.zig\"}]")),);- // A resource_link with no uri still names the attachment.try testing.expectEqualStrings("a.zig", try flattenPrompt(a, parse(a, "[{\"type\":\"resource_link\",\"name\":\"a.zig\"}]")));- // Empty and unreadable blocks are skipped, not rendered as blank lines.try testing.expectEqualStrings("x", try flattenPrompt(a, parse(a, "[{\"type\":\"text\",\"text\":\"\"},{\"type\":\"image\"},{\"type\":\"text\",\"text\":\"x\"}]")));try testing.expectEqualStrings("", try flattenPrompt(a, parse(a, "[]")));try testing.expectEqualStrings("", try flattenPrompt(a, null));- // Non-spec clients that send a bare string are tolerated.try testing.expectEqualStrings("bare", try flattenPrompt(a, parse(a, "\"bare\"")));}@@ -453,7 +259,6 @@ test "writers compose valid, newline-framed JSON-RPC envelopes" {try writeResult(&w, .{ .integer = 4 }, .{ .stopReason = "end_turn" });try testing.expectEqualStrings("{\"jsonrpc\":\"2.0\",\"id\":4,\"result\":{\"stopReason\":\"end_turn\"}}\n", w.buffered());- // A string id round-trips as a string, not as a number.w = .fixed(&buf);try writeResult(&w, .{ .string = "x1" }, .{ .sessionId = "s" });try testing.expectEqualStrings("{\"jsonrpc\":\"2.0\",\"id\":\"x1\",\"result\":{\"sessionId\":\"s\"}}\n", w.buffered());@@ -462,8 +267,6 @@ test "writers compose valid, newline-framed JSON-RPC envelopes" {try writeError(&w, .{ .integer = 9 }, err_method_not_found, "method not found: nope");try testing.expectEqualStrings("{\"jsonrpc\":\"2.0\",\"id\":9,\"error\":{\"code\":-32601,\"message\":\"method not found: nope\"}}\n", w.buffered());- // The update is a NOTIFICATION: no id field at all, and the payload is- // escaped rather than pasted in raw.w = .fixed(&buf);try writeSessionUpdate(&w, "sess-1", "line\"one\"\nline two");const update = w.buffered();@@ -498,7 +301,6 @@ test "handleLine: initialize, session/new, then a prompt turn" {try testing.expectEqualStrings("{\"jsonrpc\":\"2.0\",\"id\":2,\"result\":{\"sessionId\":\"acp-abc-1\"}}\n", w.buffered());try testing.expectEqualStrings("acp-abc-1", d.session_id.?);- // One turn: exactly one session/update notification, THEN the response.w = .fixed(&buf);try handleLine(&d, a, &w, "{\"jsonrpc\":\"2.0\",\"id\":3,\"method\":\"session/prompt\",\"params\":{\"sessionId\":\"acp-abc-1\",\"prompt\":[{\"type\":\"text\",\"text\":\"ping\"}]}}");var lines = std.mem.splitScalar(u8, w.buffered(), '\n');@@ -506,8 +308,8 @@ test "handleLine: initialize, session/new, then a prompt turn" {try testing.expect(std.mem.indexOf(u8, first, "\"method\":\"session/update\"") != null);try testing.expect(std.mem.indexOf(u8, first, "\"text\":\"echo:ping\"") != null);try testing.expectEqualStrings("{\"jsonrpc\":\"2.0\",\"id\":3,\"result\":{\"stopReason\":\"end_turn\"}}", lines.next().?);- try testing.expectEqualStrings("", lines.next().?); // the response's own trailing newline- try testing.expect(lines.next() == null); // and nothing after it+ try testing.expectEqualStrings("", lines.next().?);+ try testing.expect(lines.next() == null);}test "handleLine: a prompt with no sessionId falls back to the live session" {@@ -537,9 +339,11 @@ test "handleLine: unknown methods get -32601 and notifications are never answerew.buffered(),);- // Notifications produce no bytes at all — not a result, not an error.w = .fixed(&buf);+ agent_mod.Agent.esc_cancel.store(false, .release);try handleLine(&d, a, &w, "{\"jsonrpc\":\"2.0\",\"method\":\"session/cancel\",\"params\":{\"sessionId\":\"s\"}}");+ try testing.expect(agent_mod.Agent.esc_cancel.load(.acquire));+ agent_mod.Agent.esc_cancel.store(false, .release);try handleLine(&d, a, &w, "{\"jsonrpc\":\"2.0\",\"method\":\"initialize\"}");try handleLine(&d, a, &w, "");try handleLine(&d, a, &w, "{ garbage");@@ -553,8 +357,6 @@ test "handleLine: turn failures map to a stopReason or a -32603" {var buf: [1024]u8 = undefined;const prompt = "{\"id\":1,\"method\":\"session/prompt\",\"params\":{\"sessionId\":\"s\",\"prompt\":[{\"type\":\"text\",\"text\":\"go\"}]}}";- // Budget exhaustion is a normal ACP outcome, not a protocol error, and it- // emits no update (there is no final text to carry).var w: Io.Writer = .fixed(&buf);var budget: Dispatch = .{ .turn = budgetTurn, .ctx = undefined };try handleLine(&budget, a, &w, prompt);@@ -573,7 +375,12 @@ test "isAcpSubcommand claims only `acp`, and arms the stdout discipline" {try testing.expect(!isAcpSubcommand("repl"));try testing.expect(!isAcpSubcommand("acpx"));try testing.expect(!isAcpSubcommand(""));- try testing.expect(!main_mod.json_mode); // no side effect on a miss+ try testing.expect(!main_mod.json_mode);try testing.expect(isAcpSubcommand("acp"));- try testing.expect(main_mod.json_mode); // stdout is protocol-only from here+ try testing.expect(main_mod.json_mode);+}++test {+ _ = @import("acp_protocol.zig");+ _ = @import("acp_stream.zig");}diff --git a/src/acp_protocol.zig b/src/acp_protocol.zignew file mode 100644index 00000000..512197ee--- /dev/null+++ b/src/acp_protocol.zig@@ -0,0 +1,124 @@+//! ACP JSON-RPC envelopes: parse, version negotiate, prompt flatten, writers.+//! Split from acp.zig so the agent loop can stream session/update without+//! growing that file past 600.++const std = @import("std");+const Io = std.Io;+const Allocator = std.mem.Allocator;+const Value = std.json.Value;+const util = @import("util.zig");++/// Highest ACP protocol version this agent implements (v1 shapes).+pub const protocol_version: i64 = 1;++pub const err_method_not_found: i32 = -32601;+pub const err_internal: i32 = -32603;++/// ACP's `promptCapabilities` — named empty struct, not `.{}` (that is a tuple).+pub const PromptCapabilities = struct {};++pub const Request = struct {+ id: ?Value = null,+ method: []const u8 = "",+ params: ?Value = null,+};++pub fn parseRequest(arena: Allocator, line: []const u8) ?Request {+ const trimmed = std.mem.trim(u8, line, " \t\r\n");+ if (trimmed.len == 0) return null;+ const v = std.json.parseFromSliceLeaky(Value, arena, trimmed, .{ .allocate = .alloc_always }) catch return null;+ if (v != .object) return null;+ const method = util.strFieldObj(v.object, "method") orelse return null;+ const raw_id = v.object.get("id");+ return .{+ .id = if (raw_id) |id| (if (id == .null) null else id) else null,+ .method = method,+ .params = v.object.get("params"),+ };+}++pub fn negotiateVersion(params: ?Value) i64 {+ const p = params orelse return protocol_version;+ if (p != .object) return protocol_version;+ const v = p.object.get("protocolVersion") orelse return protocol_version;+ return switch (v) {+ .integer => |n| @min(n, protocol_version),+ .float => |f| @min(@as(i64, @intFromFloat(f)), protocol_version),+ else => protocol_version,+ };+}++fn blockText(block: Value) ?[]const u8 {+ if (block == .string) return block.string;+ if (block != .object) return null;+ const o = block.object;+ const kind = util.strFieldObj(o, "type") orelse "";+ if (std.mem.eql(u8, kind, "text")) return util.strFieldObj(o, "text");+ if (std.mem.eql(u8, kind, "resource_link"))+ return util.strFieldObj(o, "uri") orelse util.strFieldObj(o, "name");+ return util.strFieldObj(o, "text") orelse util.strFieldObj(o, "uri");+}++pub fn flattenPrompt(arena: Allocator, prompt: ?Value) ![]const u8 {+ const blocks = switch (prompt orelse return "") {+ .array => |a| a,+ .string => |s| return s,+ else => return "",+ };+ var buf: std.array_list.Managed(u8) = .init(arena);+ for (blocks.items) |block| {+ const text = blockText(block) orelse continue;+ if (text.len == 0) continue;+ if (buf.items.len != 0) try buf.append('\n');+ try buf.appendSlice(text);+ }+ return buf.items;+}++pub fn writeResult(w: *Io.Writer, id: ?Value, result: anytype) !void {+ var s: std.json.Stringify = .{ .writer = w };+ try s.beginObject();+ try s.objectField("jsonrpc");+ try s.write("2.0");+ try s.objectField("id");+ try s.write(id);+ try s.objectField("result");+ try s.write(result);+ try s.endObject();+ try w.writeByte('\n');+}++pub fn writeError(w: *Io.Writer, id: ?Value, code: i32, message: []const u8) !void {+ var s: std.json.Stringify = .{ .writer = w };+ try s.beginObject();+ try s.objectField("jsonrpc");+ try s.write("2.0");+ try s.objectField("id");+ try s.write(id);+ try s.objectField("error");+ try s.beginObject();+ try s.objectField("code");+ try s.write(code);+ try s.objectField("message");+ try s.write(message);+ try s.endObject();+ try s.endObject();+ try w.writeByte('\n');+}++pub fn writeNotification(w: *Io.Writer, method: []const u8, params: anytype) !void {+ var s: std.json.Stringify = .{ .writer = w };+ try s.write(.{ .jsonrpc = "2.0", .method = method, .params = params });+ try w.writeByte('\n');+}++/// One `agent_message_chunk` notification (the v0 final-text update).+pub fn writeSessionUpdate(w: *Io.Writer, session_id: []const u8, text: []const u8) !void {+ try writeNotification(w, "session/update", .{+ .sessionId = session_id,+ .update = .{+ .sessionUpdate = "agent_message_chunk",+ .content = .{ .type = "text", .text = text },+ },+ });+}diff --git a/src/acp_stream.zig b/src/acp_stream.zignew file mode 100644index 00000000..3c03f8d1--- /dev/null+++ b/src/acp_stream.zig@@ -0,0 +1,276 @@+//! Mid-turn ACP `session/update` stream. The agent's --json events (thought,+//! text, tool_call, tool_result) become v1 session updates so a client can+//! render tools from the first call — not only the final answer.++const std = @import("std");+const Io = std.Io;+const Allocator = std.mem.Allocator;+const Value = std.json.Value;+const util = @import("util.zig");+const proto = @import("acp_protocol.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"))+ return "read";+ if (std.mem.eql(u8, name, "edit_file") or std.mem.eql(u8, name, "write_file"))+ return "edit";+ if (std.mem.eql(u8, name, "bash") or std.mem.eql(u8, name, "bash_output") or std.mem.eql(u8, name, "bash_kill"))+ return "execute";+ if (std.mem.eql(u8, name, "webfetch")) return "fetch";+ if (std.mem.eql(u8, name, "todo_write") or std.mem.eql(u8, name, "todo_read"))+ return "think";+ return "other";+}++fn titleFor(name: []const u8, input: Value) []const u8 {+ if (input == .object) {+ if (util.strFieldObj(input.object, "path")) |p| return p;+ if (util.strFieldObj(input.object, "command")) |c| return c;+ if (util.strFieldObj(input.object, "url")) |u| return u;+ }+ return name;+}++pub fn writeThought(w: *Io.Writer, session_id: []const u8, text: []const u8) !void {+ try proto.writeNotification(w, "session/update", .{+ .sessionId = session_id,+ .update = .{+ .sessionUpdate = "agent_thought_chunk",+ .content = .{ .type = "text", .text = text },+ },+ });+}++pub fn writeMessage(w: *Io.Writer, session_id: []const u8, text: []const u8) !void {+ try proto.writeSessionUpdate(w, session_id, text);+}++pub fn writeToolCall(w: *Io.Writer, session_id: []const u8, id: []const u8, name: []const u8, input: Value) !void {+ try proto.writeNotification(w, "session/update", .{+ .sessionId = session_id,+ .update = .{+ .sessionUpdate = "tool_call",+ .toolCallId = id,+ .title = titleFor(name, input),+ .kind = kindFor(name),+ .status = "pending",+ .rawInput = input,+ },+ });+}++pub fn writeToolDone(w: *Io.Writer, session_id: []const u8, id: []const u8, is_error: bool, text: []const u8) !void {+ try proto.writeNotification(w, "session/update", .{+ .sessionId = session_id,+ .update = .{+ .sessionUpdate = "tool_call_update",+ .toolCallId = id,+ .status = if (is_error) "failed" else "completed",+ .content = .{+ .{ .type = "content", .content = .{ .type = "text", .text = text } },+ },+ },+ });+}++fn storeId(id_buf: *[64]u8, id: []const u8) []const u8 {+ @memset(id_buf, 0);+ const n = @min(id.len, id_buf.len - 1);+ @memcpy(id_buf[0..n], id[0..n]);+ return id_buf[0..n];+}++fn lastId(id_buf: *const [64]u8) []const u8 {+ const n = std.mem.indexOfScalar(u8, id_buf, 0) orelse id_buf.len;+ return if (n == 0) "call-1" else id_buf[0..n];+}++/// Translate one --json event object into zero or one session/update.+/// `id_buf` holds the last minted toolCallId when the event has no `id`.+pub fn translateEvent(+ w: *Io.Writer,+ session_id: []const u8,+ ev: Value,+ id_buf: *[64]u8,+ next_tool: *u32,+) !enum { none, thought, text, tool } {+ if (ev != .object) return .none;+ const typ = util.strFieldObj(ev.object, "type") orelse return .none;+ if (std.mem.eql(u8, typ, "reasoning")) {+ const text = util.strFieldObj(ev.object, "text") orelse return .none;+ if (text.len == 0) return .none;+ try writeThought(w, session_id, text);+ return .thought;+ }+ if (std.mem.eql(u8, typ, "text")) {+ const text = util.strFieldObj(ev.object, "text") orelse return .none;+ if (text.len == 0) return .none;+ try writeMessage(w, session_id, text);+ return .text;+ }+ if (std.mem.eql(u8, typ, "tool_call") or std.mem.eql(u8, typ, "tool_call_started")) {+ const name = util.strFieldObj(ev.object, "name") orelse "tool";+ const input = ev.object.get("input") orelse Value{ .object = .empty };+ const id = if (util.strFieldObj(ev.object, "id")) |given|+ storeId(id_buf, given)+ else blk: {+ next_tool.* += 1;+ var tmp: [32]u8 = undefined;+ const minted = std.fmt.bufPrint(&tmp, "call-{d}", .{next_tool.*}) catch "call";+ break :blk storeId(id_buf, minted);+ };+ try writeToolCall(w, session_id, id, name, input);+ return .tool;+ }+ if (std.mem.eql(u8, typ, "tool_result") or std.mem.eql(u8, typ, "tool_call_finished") or std.mem.eql(u8, typ, "tool_rejected")) {+ const use_id = if (util.strFieldObj(ev.object, "id")) |given| storeId(id_buf, given) else lastId(id_buf);+ const text = util.strFieldObj(ev.object, "text") orelse util.strFieldObj(ev.object, "message") orelse "";+ const is_error = switch (ev.object.get("is_error") orelse .null) {+ .bool => |b| b,+ else => std.mem.eql(u8, typ, "tool_rejected"),+ };+ try writeToolDone(w, session_id, use_id, is_error, text);+ return .tool;+ }+ return .none;+}++/// Line-splitting writer: --json JSONL in, ACP session/update out.+pub const EventSink = struct {+ out: *Io.Writer,+ session_id: *[]const u8,+ saw_text: *bool,+ pending: std.ArrayList(u8),+ gpa: Allocator,+ next_tool: u32 = 0,+ last_id: [64]u8 = @splat(0),+ buf: [4096]u8 = undefined,+ writer: Io.Writer = undefined,++ const vtable: Io.Writer.VTable = .{ .drain = drain };++ pub fn init(self: *EventSink, gpa: Allocator, out: *Io.Writer, session_id: *[]const u8, saw_text: *bool) void {+ self.* = .{+ .out = out,+ .session_id = session_id,+ .saw_text = saw_text,+ .pending = .empty,+ .gpa = gpa,+ .writer = .{ .vtable = &vtable, .buffer = &self.buf, .end = 0 },+ };+ }++ pub fn deinit(self: *EventSink) void {+ self.writer.flush() catch {};+ if (self.pending.items.len > 0) self.translateLine(self.pending.items);+ self.pending.deinit(self.gpa);+ }++ fn feed(self: *EventSink, bytes: []const u8) void {+ self.pending.appendSlice(self.gpa, bytes) catch return;+ while (std.mem.indexOfScalar(u8, self.pending.items, '\n')) |nl| {+ const line = self.pending.items[0..nl];+ self.translateLine(line);+ std.mem.copyForwards(u8, self.pending.items, self.pending.items[nl + 1 ..]);+ self.pending.shrinkRetainingCapacity(self.pending.items.len - (nl + 1));+ }+ }++ fn translateLine(self: *EventSink, line: []const u8) void {+ const trimmed = std.mem.trim(u8, line, " \t\r");+ if (trimmed.len == 0) return;+ var parsed = std.json.parseFromSlice(Value, self.gpa, trimmed, .{}) catch return;+ defer parsed.deinit();+ const kind = translateEvent(self.out, self.session_id.*, parsed.value, &self.last_id, &self.next_tool) catch return;+ if (kind == .text) self.saw_text.* = true;+ self.out.flush() catch {};+ }++ fn drain(w: *Io.Writer, data: []const []const u8, splat: usize) Io.Writer.Error!usize {+ const self: *EventSink = @alignCast(@fieldParentPtr("writer", w));+ self.feed(w.buffer[0..w.end]);+ w.end = 0;+ const slices = data[0 .. data.len - 1];+ const pattern = data[data.len - 1];+ var written: usize = 0;+ for (slices) |b| {+ self.feed(b);+ written += b.len;+ }+ var i: usize = 0;+ while (i < splat) : (i += 1) self.feed(pattern);+ written += pattern.len * splat;+ return written;+ }+};++const testing = std.testing;++test "kindFor maps catalog tools onto ACP kinds" {+ try testing.expectEqualStrings("read", kindFor("read_file"));+ try testing.expectEqualStrings("edit", kindFor("edit_file"));+ try testing.expectEqualStrings("execute", kindFor("bash"));+ try testing.expectEqualStrings("fetch", kindFor("webfetch"));+ try testing.expectEqualStrings("think", kindFor("todo_write"));+ try testing.expectEqualStrings("other", kindFor("ask_user"));+}++test "translateEvent: reasoning and text become chunks" {+ var buf: [1024]u8 = undefined;+ var w: Io.Writer = .fixed(&buf);+ var arena_state = std.heap.ArenaAllocator.init(testing.allocator);+ defer arena_state.deinit();+ const a = arena_state.allocator();+ const thought = try std.json.parseFromSlice(Value, a, "{\"type\":\"reasoning\",\"text\":\"look\"}", .{});+ defer thought.deinit();+ var id_buf: [64]u8 = @splat(0);+ var next: u32 = 0;+ try testing.expectEqual(.thought, try translateEvent(&w, "s1", thought.value, &id_buf, &next));+ try testing.expect(std.mem.indexOf(u8, w.buffered(), "agent_thought_chunk") != null);+ try testing.expect(std.mem.indexOf(u8, w.buffered(), "look") != null);++ w = .fixed(&buf);+ const text = try std.json.parseFromSlice(Value, a, "{\"type\":\"text\",\"text\":\"hi\"}", .{});+ defer text.deinit();+ try testing.expectEqual(.text, try translateEvent(&w, "s1", text.value, &id_buf, &next));+ try testing.expect(std.mem.indexOf(u8, w.buffered(), "agent_message_chunk") != null);+}++test "translateEvent: tool_call then tool_result share a minted id" {+ var buf: [2048]u8 = undefined;+ var w: Io.Writer = .fixed(&buf);+ var arena_state = std.heap.ArenaAllocator.init(testing.allocator);+ defer arena_state.deinit();+ const a = arena_state.allocator();+ const call = try std.json.parseFromSlice(Value, a, "{\"type\":\"tool_call\",\"name\":\"read_file\",\"input\":{\"path\":\"a.zig\"}}", .{});+ defer call.deinit();+ var id_buf: [64]u8 = @splat(0);+ var next: u32 = 0;+ try testing.expectEqual(.tool, try translateEvent(&w, "s1", call.value, &id_buf, &next));+ try testing.expect(std.mem.indexOf(u8, w.buffered(), "\"sessionUpdate\":\"tool_call\"") != null);+ try testing.expect(std.mem.indexOf(u8, w.buffered(), "call-1") != null);+ try testing.expect(std.mem.indexOf(u8, w.buffered(), "\"kind\":\"read\"") != null);++ w = .fixed(&buf);+ const result = try std.json.parseFromSlice(Value, a, "{\"type\":\"tool_result\",\"name\":\"read_file\",\"is_error\":false,\"text\":\"fn main\"}", .{});+ defer result.deinit();+ try testing.expectEqual(.tool, try translateEvent(&w, "s1", result.value, &id_buf, &next));+ try testing.expect(std.mem.indexOf(u8, w.buffered(), "tool_call_update") != null);+ try testing.expect(std.mem.indexOf(u8, w.buffered(), "call-1") != null);+ try testing.expect(std.mem.indexOf(u8, w.buffered(), "completed") != null);+}++test "EventSink translates a JSONL reasoning line through the writer" {+ var buf: [2048]u8 = undefined;+ var w: Io.Writer = .fixed(&buf);+ var sid: []const u8 = "s1";+ var saw = false;+ var sink: EventSink = undefined;+ sink.init(testing.allocator, &w, &sid, &saw);+ defer sink.deinit();+ try sink.writer.writeAll("{\"type\":\"reasoning\",\"text\":\"hmm\"}\n");+ try sink.writer.flush();+ try testing.expect(std.mem.indexOf(u8, w.buffered(), "agent_thought_chunk") != null);+ try testing.expect(std.mem.indexOf(u8, w.buffered(), "hmm") != null);+ try testing.expect(!saw);+}diff --git a/src/engine_sink.zig b/src/engine_sink.zigindex a73da4d3..b2c46634 100644--- a/src/engine_sink.zig+++ b/src/engine_sink.zig@@ -103,7 +103,8 @@ pub fn tuiSink(a: *Agent) EngineSink {/// The --json wire, for an agent that HAS one. A frontendless agent — a/// pool-thread subagent (subagent_run.zig builds every child with-/// `.out = null`) or the ACP root (acp.zig nulls it while json_mode is on) —+/// `.out = null`) or the ACP root between prompts (acp.zig nulls `out`+/// except during session/prompt, when a translating sink is installed) —/// gets the same emitter but a NON-durable vtable: jsonEmit drops every line/// for it, and a durable sink would have reserved a sequence id for each of/// those dropped lines, opening exactly the gap #330 promises cannot exist.