Skip to content

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

Python

docs(embed): host recipe for graff acp plus a thin SDK helper

Cursor Agenta49f65c3b656
diff --git a/CHANGELOG.md b/CHANGELOG.md
index f92152e8..d6a65f77 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -27,7 +27,11 @@ current is part of cutting a release.
- `bash_output` / `agent_output` `wait_ms>0` always waits for exit
(10h). Mid-range values like 60s–240s are no longer a bounded
deadline (#640).
-- Existing Tauri `gui/` is unchanged. No `v0.0.279` tag until asked.
+- Host embed path: [docs/embedding.md](docs/embedding.md) names the two
+ stdio APIs (`graff acp` and `@codegraff/sdk` `Harness`), with a Node
+ JSON-RPC recipe and a thin `@codegraff/sdk/acp` helper (`spawnAcp` /
+ `acp`). Not WASM / libgraff. No `v0.0.279` tag until asked.
+- Existing Tauri `gui/` is unchanged.
## v0.0.278 (2026-08-26)
diff --git a/README.md b/README.md
index 73aa676e..141a6e73 100644
--- a/README.md
+++ b/README.md
@@ -277,7 +277,8 @@ First things to try once you're at the `›` prompt:
### Zed (External Agents / ACP)
`graff acp` speaks the Agent Client Protocol, so Zed can drive it as an
-External Agent. Register it in `~/.config/zed/settings.json`:
+External Agent. The same spawn is the hosted-agent recipe — see
+[Embedding graff](docs/embedding.md). Register it in `~/.config/zed/settings.json`:
```json
{
@@ -902,7 +903,9 @@ Can't spawn a local process (edge runtimes, browsers, other machines)? Run
`graff serve` and both SDKs ship matching **remote clients** that drive it over
HTTP: `@graff-new/sdk/remote` (fetch-only: Workers/Deno/Bun/browsers) and
Python's `RemoteHarness` (stdlib only). Same method surface, same event stream.
-See [`sdk/README.md`](sdk/README.md).
+See [`sdk/README.md`](sdk/README.md). A host that wants ACP (thought / tool /
+text `session/update`s) instead of `--json` events should spawn `graff acp` —
+recipe and `@codegraff/sdk/acp` helper in [Embedding graff](docs/embedding.md).
---
@@ -910,7 +913,8 @@ See [`sdk/README.md`](sdk/README.md).
If you are embedding graff in a product, the safe shape is to run the agent loop
on your trusted backend and let it reach an isolated sandbox only through tool
-calls. `--no-local-tools` is what makes that shape enforceable:
+calls. How to spawn the binary (ACP vs `--json`) is [Embedding graff](docs/embedding.md).
+`--no-local-tools` is what makes the sandbox shape enforceable:
```bash
graff --json --no-local-tools --model gpt-5.5
@@ -1550,7 +1554,8 @@ issues for what's in flight:
the host. It's the natural next layer above today's cwd-confinement and
permission gate, and the safe substrate for hands-off evolutionary runs.
[Embedder mode](#embedder-mode-run-the-harness-outside-the-sandbox) is the
- first half of this today: `--no-local-tools` plus a sandbox MCP server. A
+ first half of this today: `--no-local-tools` plus a sandbox MCP server
+ ([Embedding graff](docs/embedding.md)). A
first-class sandbox backend (create/exec/read/write/destroy with provider
adapters) would remove the proxy you have to write yourself.
- **Scaling the evolution loop.** The local half shipped in v0.0.219:
diff --git a/docs/embedding.md b/docs/embedding.md
new file mode 100644
index 00000000..9e71f765
--- /dev/null
+++ b/docs/embedding.md
@@ -0,0 +1,133 @@
+# Embedding graff
+
+graff is a subprocess a host spawns, not a library you link and not a WASM
+runtime. Two stdio APIs cover a hosted agent. Pick one; do not speak both on
+the same child.
+
+| Host API | Wire | When |
+|---|---|---|
+| `graff acp` | ACP v1 JSON-RPC, one message per line | The host wants thought / tool / text `session/update`s (Zed, a product UI) |
+| `@codegraff/sdk` `Harness` | `graff --json` — JSON requests in, JSONL events out | The host wants our event types (`text`, `tool_call`, `turn`, …) |
+
+The real ACP host in this repo is [`apps/native`](../apps/native): Next.js
+`/api/acp` → `graff acp --yolo`. Mid-turn updates map onto thinking and tool
+chips (ADR [0032](adr/0032-acp-streams-mid-turn.md)). `graff serve` is not
+required.
+
+Methods and shapes below are what `src/acp.zig` / `src/acp_protocol.zig`
+actually implement. `session/load` and `session/request_permission` are not
+implemented; unattended + `--yolo` is how a host that wants tools from the
+first call runs the agent.
+
+## `graff acp`
+
+JSON-RPC 2.0 on stdio. The host is the client; graff is the agent. Protocol
+version is **1** (Zed; we speak [v1 session/update](https://agentclientprotocol.com/protocol/v1/tool-calls)
+shapes, not v2 upserts). Handshake, then one prompt:
+
+```
+initialize → { protocolVersion, agentCapabilities, agentImplementation }
+session/new → { sessionId } then a session/update (available_commands_update)
+session/prompt → session/update* then { stopReason }
+```
+
+`initialize` params: `{ protocolVersion: 1, clientCapabilities: { fs: {} } }`.
+Negotiated version is `min(client, 1)`. Capabilities today:
+`loadSession: false`, `promptCapabilities: { image: false, audio: false,
+embeddedContext: true }`.
+
+`session/new` params may include `cwd`. After the result, the agent advertises
+`/never` and `/constraint` via `available_commands_update`.
+
+`session/prompt` params: `{ sessionId, prompt: [{ type: "text", text }] }`.
+`flattenPrompt` also lifts `resource_link` blocks. Mid-turn stdout is
+`session/update` notifications, then the prompt result:
+
+| `update.sessionUpdate` | Content |
+|---|---|
+| `agent_thought_chunk` | `{ content: { type: "text", text } }` |
+| `agent_message_chunk` | same |
+| `tool_call` | `{ toolCallId, title, kind, status, rawInput }` |
+| `tool_call_update` | `{ toolCallId, status, content }` |
+| `available_commands_update` | `{ availableCommands }` (after `session/new`) |
+
+`stopReason` is `end_turn`, `cancelled` (Esc / `session/cancel`), or
+`max_turn_requests` (run budget). A stub turn that emitted no events still
+writes one final `agent_message_chunk` (the v0 contract). A live turn that
+already streamed text does not duplicate it.
+
+`session/cancel` sets the Esc latch. It may be a request or a notification.
+`set_model` is not an ACP method; a model change respawns the child.
+
+### Node recipe
+
+About twenty lines: spawn, write one JSON-RPC object per stdin line, read
+stdout the same way. Notifications (`session/update`) arrive before the
+`session/prompt` result.
+
+```js
+import { spawn } from "node:child_process";
+import { createInterface } from "node:readline";
+
+const child = spawn("graff", ["acp", "--yolo"], { stdio: ["pipe", "pipe", "inherit"] });
+const pending = new Map();
+let id = 1;
+createInterface({ input: child.stdout }).on("line", (line) => {
+ const msg = JSON.parse(line);
+ if (msg.method === "session/update") return console.log(msg.params.update);
+ const wait = pending.get(msg.id);
+ if (wait) { pending.delete(msg.id); msg.error ? wait.reject(msg.error) : wait.resolve(msg.result); }
+});
+const rpc = (method, params) => new Promise((resolve, reject) => {
+ pending.set(id, { resolve, reject });
+ child.stdin.write(JSON.stringify({ jsonrpc: "2.0", id, method, params }) + "\n");
+ id += 1;
+});
+
+await rpc("initialize", { protocolVersion: 1, clientCapabilities: { fs: {} } });
+const { sessionId } = await rpc("session/new", { cwd: process.cwd() });
+await rpc("session/prompt", { sessionId, prompt: [{ type: "text", text: "hello" }] });
+```
+
+`@codegraff/sdk/acp` is that spawn plus `request` / `notify` / `prompt`
+(`spawnAcp()`, or `acp()` which also runs the handshake).
+
+## `@codegraff/sdk` — `graff --json`
+
+When the host wants graff's JSONL events instead of ACP, spawn through
+`Harness` (local) or `RemoteHarness` (`graff serve` over HTTP). Same agent
+loop; different framing. See [`sdk/ts/README.md`](../sdk/ts/README.md).
+
+```ts
+import { Harness } from "@codegraff/sdk";
+
+const session = Harness.init({ yolo: true, model: "gpt-5.5" }).session();
+console.log(await session.ask("what files are here?"));
+await session.close();
+```
+
+## Embedder mode
+
+A hosted product that must not exec on the host machine already has a gate:
+`--no-local-tools` / `GRAFF_NO_LOCAL_TOOLS=1`. That hard-disables `bash`,
+`read_file` / `edit_file` / `write_file`, and `codedb` for the process
+(advertised off, dispatch refuses a hallucination). MCP tools are untouched,
+so a trusted host maps exec/read/write onto its own sandbox. Works with both
+`graff acp` and `graff --json`. `--yolo` does not lift the gate. Full
+write-up: [README — Embedder mode](../README.md#embedder-mode-run-the-harness-outside-the-sandbox).
+
+```bash
+graff acp --yolo --no-local-tools --model gpt-5.5
+graff --json --no-local-tools --model gpt-5.5
+```
+
+## License
+
+codegraff is **Modified AGPLv3** ([`LICENSE`](../LICENSE)): a hosted or SaaS
+embed is a legal event (AGPL §13) unless both authors grant a separate
+written permission.
+
+## Not this
+
+No `libgraff`, no WASM module, no Node addon, no in-process Zig. Those would
+be a different product. This page is the host recipe that already exists.
diff --git a/docs/releases/v0.0.279.md b/docs/releases/v0.0.279.md
index 339180ca..6d317a72 100644
--- a/docs/releases/v0.0.279.md
+++ b/docs/releases/v0.0.279.md
@@ -46,6 +46,16 @@ cd apps/native && npm install && npm run dev
The existing Tauri app in `gui/` is unchanged.
+## Embedding graff
+
+A host embeds graff by spawning the binary, not by linking a library.
+[docs/embedding.md](../embedding.md) names the two APIs: `graff acp`
+(ACP v1 JSON-RPC; thought / tool / text `session/update`) and
+`@codegraff/sdk` `Harness` (`graff --json`). `@codegraff/sdk/acp` is the
+spawn plus write/read. `--no-local-tools` still gates local bash/file
+tools on a trusted host. Modified AGPLv3: a hosted/SaaS embed is a
+legal event.
+
## Standing constraints (#638)
`/never` is an ACP slash command (`available_commands_update` after
diff --git a/sdk/README.md b/sdk/README.md
index 893bdb76..4cfac6d0 100644
--- a/sdk/README.md
+++ b/sdk/README.md
@@ -130,4 +130,6 @@ for ev in h.reconnect():
JSONL events: `text` (assistant delta), `tool_call`, `ask_user`, `tool_result`,
`turn` (final text + `context_tokens` + `cost_usd`), and `error`. Answer an
`ask_user` event with `{"type":"answer","text":"...","cancelled":false,"call_id":"..."}`.
-See the `protocol` key of `graff --schema`.
+See the `protocol` key of `graff --schema`. A host that wants ACP v1
+`session/update`s instead should spawn `graff acp` — [Embedding graff](../docs/embedding.md)
+and `@codegraff/sdk/acp`.
diff --git a/sdk/ts/README.md b/sdk/ts/README.md
index d986326b..6d06d353 100644
--- a/sdk/ts/README.md
+++ b/sdk/ts/README.md
@@ -153,9 +153,29 @@ See `orchestrate.ts`'s file header for the exact journal format and the
concurrency/determinism guarantees (and their documented edges) for
`parallel()`/`pipeline()`.
+## ACP (`graff acp`)
+
+A host that wants ACP v1 `session/update`s (thought / tool_call / text), not
+`--json` events, should spawn `graff acp` instead of `Harness`.
+`@codegraff/sdk/acp` is the spawn plus JSON-RPC write/read:
+
+```ts
+import { acp } from "@codegraff/sdk/acp";
+
+const session = await acp({ model: "gpt-5.5" });
+session.onUpdate((update) => console.log(update.sessionUpdate));
+const { stopReason, updates } = await session.prompt("hello");
+console.log(stopReason, updates.length);
+await session.close();
+```
+
+`spawnAcp()` skips the `initialize` → `session/new` handshake. Recipe, method
+names, `--no-local-tools`, and license: [Embedding graff](../../docs/embedding.md).
+
## Links
- Repository: <https://github.com/justrach/codegraff>
+- Embedding graff: <https://github.com/justrach/codegraff/blob/main/docs/embedding.md>
- This package (npm): <https://www.npmjs.com/package/@codegraff/sdk>
- Python sibling (PyPI): <https://pypi.org/project/codegraff/>
diff --git a/sdk/ts/acp.test.ts b/sdk/ts/acp.test.ts
new file mode 100644
index 00000000..e2e61813
--- /dev/null
+++ b/sdk/ts/acp.test.ts
@@ -0,0 +1,84 @@
+import { afterEach, describe, expect, test } from "bun:test";
+import { join } from "node:path";
+import { acp, ACP_PROTOCOL_VERSION, spawnAcp, type AcpConn, type AcpUpdate } from "./acp.ts";
+
+const fixture = join(import.meta.dir, "test-fixtures", "fake-acp.mjs");
+const live: AcpConn[] = [];
+const command = [process.execPath, fixture];
+
+const deadline = <T>(promise: Promise<T>, ms = 2_000): Promise<T> =>
+ Promise.race([
+ promise,
+ new Promise<T>((_, reject) => setTimeout(() => reject(new Error("test timed out")), ms)),
+ ]);
+
+afterEach(async () => {
+ await Promise.all(live.splice(0).map((c) => c.close()));
+});
+
+describe("spawnAcp / acp", () => {
+ test("handshake is initialize → session/new, then prompt streams session/update", async () => {
+ const conn = spawnAcp({ command });
+ live.push(conn);
+ const commands = new Promise<AcpUpdate>((resolve) => {
+ const off = conn.onUpdate((update) => {
+ if (update.sessionUpdate === "available_commands_update") {
+ off();
+ resolve(update);
+ }
+ });
+ });
+ await deadline(
+ conn.request("initialize", {
+ protocolVersion: ACP_PROTOCOL_VERSION,
+ clientCapabilities: { fs: {} },
+ }),
+ );
+ const created = (await deadline(conn.request("session/new", { cwd: "/tmp" }))) as { sessionId: string };
+ expect(created.sessionId).toBe("acp-test-1");
+ conn.sessionId = created.sessionId;
+ expect((await deadline(commands)).sessionUpdate).toBe("available_commands_update");
+
+ const { stopReason, updates } = await deadline(conn.prompt("hello"));
+ expect(stopReason).toBe("end_turn");
+ expect(updates.map((u) => u.sessionUpdate)).toEqual([
+ "agent_thought_chunk",
+ "tool_call",
+ "tool_call_update",
+ "agent_message_chunk",
+ ]);
+ const text = updates.find((u) => u.sessionUpdate === "agent_message_chunk");
+ expect((text?.content as { text?: string } | undefined)?.text).toBe("echo:hello");
+ });
+
+ test("acp() runs the handshake and fills sessionId", async () => {
+ const conn = await deadline(acp({ command }));
+ live.push(conn);
+ expect(conn.sessionId).toBe("acp-test-1");
+ });
+
+ test("request sends real ACP method names and surfaces JSON-RPC errors", async () => {
+ const conn = spawnAcp({ command });
+ live.push(conn);
+ const init = (await deadline(
+ conn.request("initialize", { protocolVersion: ACP_PROTOCOL_VERSION, clientCapabilities: { fs: {} } }),
+ )) as { protocolVersion: number; agentImplementation: { name: string } };
+ expect(init.protocolVersion).toBe(1);
+ expect(init.agentImplementation.name).toBe("graff");
+
+ await expect(deadline(conn.request("session/load", { sessionId: "nope" }))).rejects.toThrow(
+ "method not found: session/load",
+ );
+ await expect(deadline(conn.request("session/prompt", { prompt: [{ type: "text", text: "die" }] }))).rejects.toThrow(
+ "boom",
+ );
+ });
+
+ test("session/cancel is a notify", async () => {
+ const conn = spawnAcp({ command });
+ live.push(conn);
+ conn.notify("session/cancel", { sessionId: "acp-test-1" });
+ const created = (await deadline(conn.request("session/new", { cwd: "/tmp" }))) as { sessionId: string };
+ expect(created.sessionId).toBe("acp-test-1");
+ });
+});
diff --git a/sdk/ts/acp.ts b/sdk/ts/acp.ts
new file mode 100644
index 00000000..f905f860
--- /dev/null
+++ b/sdk/ts/acp.ts
@@ -0,0 +1,200 @@
+// SDK ACP host helper — hand-written, NOT auto-generated
+// (contrast harness.ts/remote.ts's "Do not edit" header).
+// Spawn `graff acp` and speak ACP v1 JSON-RPC on stdio. See docs/embedding.md.
+
+import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process";
+
+export const ACP_PROTOCOL_VERSION = 1;
+
+export type AcpUpdate = { sessionUpdate: string; [key: string]: unknown };
+
+export type AcpPromptResult = { stopReason: string };
+
+export interface SpawnAcpOptions {
+ /** graff binary. Defaults to `GRAFF_BIN` or `graff` on PATH. */
+ binary?: string;
+ cwd?: string;
+ env?: NodeJS.ProcessEnv;
+ /** Extra flags after `acp` (e.g. `--no-local-tools`). */
+ args?: string[];
+ /** Default true — ACP has no `session/request_permission` yet. */
+ yolo?: boolean;
+ model?: string;
+ /** Full argv for tests (`[process.execPath, fixture]`). */
+ command?: string[];
+}
+
+export interface AcpConn {
+ readonly child: ChildProcessWithoutNullStreams;
+ sessionId: string | null;
+ request(method: string, params?: unknown): Promise<unknown>;
+ notify(method: string, params?: unknown): void;
+ onUpdate(fn: (update: AcpUpdate, sessionId?: string) => void): () => void;
+ prompt(text: string): Promise<{ stopReason: string; updates: AcpUpdate[] }>;
+ close(): Promise<void>;
+}
+
+type Pending = {
+ resolve: (value: unknown) => void;
+ reject: (err: Error) => void;
+};
+
+function writeLine(child: ChildProcessWithoutNullStreams, obj: unknown): void {
+ child.stdin.write(`${JSON.stringify(obj)}\n`);
+}
+
+function spawnChild(opts: SpawnAcpOptions): ChildProcessWithoutNullStreams {
+ if (opts.command) {
+ const [bin, ...argv] = opts.command;
+ if (!bin) throw new Error("spawnAcp: command is empty");
+ return spawn(bin, argv, {
+ stdio: ["pipe", "pipe", "inherit"],
+ cwd: opts.cwd,
+ env: opts.env ?? process.env,
+ });
+ }
+ const binary = opts.binary ?? process.env.GRAFF_BIN ?? "graff";
+ const args = ["acp"];
+ if (opts.yolo !== false) args.push("--yolo");
+ if (opts.model) args.push("--model", opts.model);
+ if (opts.args) args.push(...opts.args);
+ return spawn(binary, args, {
+ stdio: ["pipe", "pipe", "inherit"],
+ cwd: opts.cwd,
+ env: opts.env ?? process.env,
+ });
+}
+
+/** Spawn `graff acp`. No handshake — call `request("initialize")` yourself. */
+export function spawnAcp(opts: SpawnAcpOptions = {}): AcpConn {
+ const child = spawnChild(opts);
+ const pending = new Map<number, Pending>();
+ const listeners = new Set<(update: AcpUpdate, sessionId?: string) => void>();
+ let nextId = 1;
+ let buf = "";
+ let sessionId: string | null = null;
+ let closed = false;
+
+ const failAll = (err: Error) => {
+ for (const wait of pending.values()) wait.reject(err);
+ pending.clear();
+ };
+
+ const dispatch = (line: string) => {
+ const trimmed = line.trim();
+ if (!trimmed) return;
+ let msg: {
+ id?: number | string;
+ method?: string;
+ params?: { sessionId?: string; update?: AcpUpdate };
+ result?: unknown;
+ error?: { code?: number; message?: string };
+ };
+ try {
+ msg = JSON.parse(trimmed) as typeof msg;
+ } catch {
+ return;
+ }
+ if (msg.method === "session/update") {
+ const update = msg.params?.update;
+ if (update) {
+ for (const fn of listeners) fn(update, msg.params?.sessionId);
+ }
+ return;
+ }
+ if (msg.id === undefined) return;
+ const wait = pending.get(Number(msg.id));
+ if (!wait) return;
+ pending.delete(Number(msg.id));
+ if (msg.error) wait.reject(new Error(msg.error.message ?? "ACP error"));
+ else wait.resolve(msg.result);
+ };
+
+ child.stdout.on("data", (chunk: Buffer | string) => {
+ buf += typeof chunk === "string" ? chunk : chunk.toString("utf8");
+ let nl: number;
+ while ((nl = buf.indexOf("\n")) >= 0) {
+ const line = buf.slice(0, nl);
+ buf = buf.slice(nl + 1);
+ dispatch(line);
+ }
+ });
+ child.on("error", (err) => failAll(err instanceof Error ? err : new Error(String(err))));
+ child.on("exit", (code, signal) => {
+ if (closed && pending.size === 0) return;
+ failAll(new Error(signal ? `graff acp killed (${signal})` : `graff acp exited ${code ?? "?"}`));
+ });
+
+ const conn: AcpConn = {
+ child,
+ get sessionId() {
+ return sessionId;
+ },
+ set sessionId(value) {
+ sessionId = value;
+ },
+ request(method, params) {
+ const id = nextId++;
+ return new Promise((resolve, reject) => {
+ pending.set(id, { resolve, reject });
+ writeLine(child, { jsonrpc: "2.0", id, method, params });
+ });
+ },
+ notify(method, params) {
+ writeLine(child, { jsonrpc: "2.0", method, params });
+ },
+ onUpdate(fn) {
+ listeners.add(fn);
+ return () => {
+ listeners.delete(fn);
+ };
+ },
+ async prompt(text) {
+ const updates: AcpUpdate[] = [];
+ const off = conn.onUpdate((update) => {
+ updates.push(update);
+ });
+ try {
+ const result = (await conn.request("session/prompt", {
+ sessionId: sessionId ?? "",
+ prompt: [{ type: "text", text }],
+ })) as AcpPromptResult;
+ return { stopReason: result.stopReason, updates };
+ } finally {
+ off();
+ }
+ },
+ close() {
+ if (closed) return Promise.resolve();
+ closed = true;
+ child.stdin.end();
+ child.kill("SIGTERM");
+ return new Promise((resolve) => {
+ const done = () => resolve();
+ child.once("exit", done);
+ setTimeout(done, 1_000);
+ });
+ },
+ };
+ return conn;
+}
+
+/** Spawn `graff acp`, then `initialize` + `session/new`. */
+export async function acp(opts: SpawnAcpOptions = {}): Promise<AcpConn> {
+ const conn = spawnAcp(opts);
+ try {
+ await conn.request("initialize", {
+ protocolVersion: ACP_PROTOCOL_VERSION,
+ clientCapabilities: { fs: {} },
+ });
+ const created = (await conn.request("session/new", {
+ cwd: opts.cwd ?? process.cwd(),
+ })) as { sessionId?: string };
+ if (!created?.sessionId) throw new Error("session/new returned no sessionId");
+ conn.sessionId = created.sessionId;
+ return conn;
+ } catch (err) {
+ await conn.close();
+ throw err;
+ }
+}
diff --git a/sdk/ts/package.json b/sdk/ts/package.json
index 480e0458..fd79309d 100644
--- a/sdk/ts/package.json
+++ b/sdk/ts/package.json
@@ -21,6 +21,11 @@
"import": "./dist/orchestrate.js",
"default": "./dist/orchestrate.js"
},
+ "./acp": {
+ "types": "./dist/acp.d.ts",
+ "import": "./dist/acp.js",
+ "default": "./dist/acp.js"
+ },
"./package.json": "./package.json"
},
"repository": {
diff --git a/sdk/ts/test-fixtures/fake-acp.mjs b/sdk/ts/test-fixtures/fake-acp.mjs
new file mode 100644
index 00000000..ceb8f586
--- /dev/null
+++ b/sdk/ts/test-fixtures/fake-acp.mjs
@@ -0,0 +1,75 @@
+#!/usr/bin/env node
+// Fake `graff acp`: JSON-RPC 2.0 on stdio, one message per line.
+import { createInterface } from "node:readline";
+
+const write = (obj) => process.stdout.write(`${JSON.stringify(obj)}\n`);
+const result = (id, value) => write({ jsonrpc: "2.0", id, result: value });
+const fail = (id, code, message) => write({ jsonrpc: "2.0", id, error: { code, message } });
+const update = (sessionId, payload) =>
+ write({ jsonrpc: "2.0", method: "session/update", params: { sessionId, update: payload } });
+
+let sessionId = null;
+
+createInterface({ input: process.stdin }).on("line", (line) => {
+ let msg;
+ try {
+ msg = JSON.parse(line);
+ } catch {
+ return;
+ }
+ const { id, method, params } = msg;
+ if (method === "initialize") {
+ const requested = params?.protocolVersion ?? 1;
+ result(id, {
+ protocolVersion: Math.min(Number(requested) || 1, 1),
+ agentCapabilities: {
+ loadSession: false,
+ promptCapabilities: { image: false, audio: false, embeddedContext: true },
+ },
+ agentImplementation: { name: "graff", title: "graff", version: "test" },
+ });
+ return;
+ }
+ if (method === "session/new") {
+ sessionId = "acp-test-1";
+ result(id, { sessionId });
+ update(sessionId, {
+ sessionUpdate: "available_commands_update",
+ availableCommands: [{ name: "never", description: "List standing constraints.", input: { hint: "" } }],
+ });
+ return;
+ }
+ if (method === "session/cancel") {
+ if (id !== undefined) result(id, {});
+ return;
+ }
+ if (method === "session/prompt") {
+ const sid = params?.sessionId ?? sessionId ?? "";
+ const text = Array.isArray(params?.prompt)
+ ? params.prompt.map((b) => b.text ?? "").join("\n")
+ : "";
+ if (text === "die") {
+ fail(id, -32603, "boom");
+ return;
+ }
+ update(sid, { sessionUpdate: "agent_thought_chunk", content: { type: "text", text: "thinking" } });
+ update(sid, {
+ sessionUpdate: "tool_call",
+ toolCallId: "call-1",
+ title: "ls",
+ kind: "execute",
+ status: "pending",
+ rawInput: { command: "ls" },
+ });
+ update(sid, {
+ sessionUpdate: "tool_call_update",
+ toolCallId: "call-1",
+ status: "completed",
+ content: [{ type: "content", content: { type: "text", text: "ok" } }],
+ });
+ update(sid, { sessionUpdate: "agent_message_chunk", content: { type: "text", text: `echo:${text}` } });
+ result(id, { stopReason: "end_turn" });
+ return;
+ }
+ if (id !== undefined) fail(id, -32601, `method not found: ${method}`);
+});
diff --git a/sdk/ts/tsconfig.build.json b/sdk/ts/tsconfig.build.json
index c859eb75..186ddaf5 100644
--- a/sdk/ts/tsconfig.build.json
+++ b/sdk/ts/tsconfig.build.json
@@ -9,6 +9,6 @@
"rootDir": ".",
"rewriteRelativeImportExtensions": true
},
- "include": ["harness.ts", "remote.ts", "orchestrate.ts"],
+ "include": ["harness.ts", "remote.ts", "orchestrate.ts", "acp.ts"],
"exclude": ["*.test.ts"]
}
diff --git a/src/cli.zig b/src/cli.zig
index 293982e7..985fbe0c 100644
--- a/src/cli.zig
+++ b/src/cli.zig
@@ -26,6 +26,7 @@ pub const changelog_text =
\\ • graff acp emits thought / tool_call / text session/update; /never is an ACP slash command
\\ • /never on a TTY is a searchable picker with two confirms; rm and ACP list still work (#638)
\\ • bash_output wait_ms>0 always waits for exit — mid-range values are not a timeout (#640)
+ \\ • host recipe: docs/embedding.md; @codegraff/sdk/acp spawns graff acp
\\
\\0.0.278
\\ • deleted composer screenshots are not sent: submit keeps [Image #N] / @[path] only (#634)