graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
feat: in-process ACP core (libgraff + graff-core.wasm)
Cursor Agente38783461bce
diff --git a/build.zig b/build.zigindex ae4ded6e..72ea869f 100644--- a/build.zig+++ b/build.zig@@ -212,4 +212,38 @@ pub fn build(b: *std.Build) void {const tui_test_step = b.step("tui-test", "Run fullscreen TUI unit tests");tui_test_step.dependOn(&b.addRunArtifact(tui_tests).step);++ // In-process ACP (fx-shaped embed). Off the default install so the+ // tagged CLI cut does not grow a .so / .wasm. `zig build libgraff`+ // and `zig build -Dwasm-surface=core`.+ const libgraff = b.addLibrary(.{+ .linkage = .dynamic,+ .name = "graff",+ .root_module = b.createModule(.{+ .root_source_file = b.path("src/libgraff.zig"),+ .target = target,+ .optimize = optimize,+ .strip = lean_release,+ }),+ });+ const libgraff_step = b.step("libgraff", "Build the in-process ACP shared library");+ libgraff_step.dependOn(&b.addInstallArtifact(libgraff, .{}).step);++ _ = b.option([]const u8, "wasm-surface", "wasm surface: core (use `zig build wasm-core`)");+ const wasm = b.addExecutable(.{+ .name = "graff-core",+ .root_module = b.createModule(.{+ .root_source_file = b.path("src/wasm_core_main.zig"),+ .target = b.resolveTargetQuery(.{+ .cpu_arch = .wasm32,+ .os_tag = .freestanding,+ }),+ .optimize = optimize,+ .strip = true,+ }),+ });+ wasm.entry = .disabled;+ wasm.rdynamic = true;+ const wasm_step = b.step("wasm-core", "Build graff-core.wasm (in-process ACP)");+ wasm_step.dependOn(&b.addInstallArtifact(wasm, .{}).step);}diff --git a/docs/adr/0038-in-process-acp-core.md b/docs/adr/0038-in-process-acp-core.mdnew file mode 100644index 00000000..d0b1c731--- /dev/null+++ b/docs/adr/0038-in-process-acp-core.md@@ -0,0 +1,39 @@+# 0038. In-process ACP core is the fx-shaped embed++Status: accepted 2026-08-26++## Context++v0.0.279 parked WASM / `libgraff` / in-process Zig. The host recipe that+shipped is subprocess (`graff acp`, `@codegraff/sdk/acp`) — OpenCode's+shape. fx's embed is same-process: `libfx` + `fx-core.wasm` ++`createFxAgent()`. That is the frontier the 279 continuation was asked+to enable.++Compiling the full agent loop (HTTP, bash, git, Zig `Io.Threaded`) to+wasm32 is a different product. The ACP loop is already a `TurnFn` plus+JSON-RPC writers.++## Decision++Same-process embed is an ACP **core**, not the full CLI:++- `src/acp_engine.zig` is the initialize / session/new / prompt / cancel+ loop. It does not import `main.zig` or `Agent`.+- `libgraff` (shared library) and `graff-core.wasm` export the same C ABI+ (`graff_acp_create` / `graff_acp_feed` / in-out slots).+- `@codegraff/sdk/embed` `createGraffAgent()` instantiates the wasm in+ the host isolate. No child process.+- First-slice turn is `echo:` (protocol proof). Live tools, TLS, and+ bash stay on `graff acp` until a host-imported turn exists.+- Subprocess ACP remains the hosted coding agent (ADR 0032).++This record lives on `release/v0.0.279` after the v0.0.279 tag. It is+**not** on `main` until a later cut.++## Consequences++A JS host can run the ACP handshake in-process the way fx does. It+cannot yet run a model turn inside the wasm. Do not replace `graff acp`+with the core for Zed or `apps/native`. Revisit when a host `turn`+import (JSPI or native addon) is wired.diff --git a/docs/adr/README.md b/docs/adr/README.mdindex bb00a849..fcc12358 100644--- a/docs/adr/README.md+++ b/docs/adr/README.md@@ -48,6 +48,7 @@ record only when you need the evidence or the edge cases.| [0035](0035-first-turn-skips-deferred-mcp-join.md) | First model call after a deferred MCP boot does not wait for the handshake; native tools run now, MCP catalogs merge on the next request. || [0036](0036-computer-use-keeps-the-signed-codex-bridge.md) | Codex Computer Use keeps its authenticated node_repl process chain: Graff launches it through the signed Codex sandbox wrapper, never embeds V8 or spoofs the service. || [0037](0037-experiment-pool-is-opt-in.md) | `--experiment N` / `/experiment N` pre-mints a child worktree pool; default isolation stays `shared_cwd`. 279 continuation — not on main until a later cut. |+| [0038](0038-in-process-acp-core.md) | Same-process embed is `libgraff` + `graff-core.wasm` + `createGraffAgent()` (ACP core, echo turn). Live coding stays `graff acp`. 279 continuation — not on main until a later cut. |## When to write onediff --git a/docs/embedding.md b/docs/embedding.mdindex e904b9df..5bf16315 100644--- a/docs/embedding.md+++ b/docs/embedding.md@@ -140,8 +140,41 @@ codegraff is **Modified AGPLv3** ([`LICENSE`](../LICENSE)): a hosted or SaaSembed is a legal event (AGPL §13) unless both authors grant a separatewritten permission.+## In-process (`createGraffAgent`)++fx-shaped same-process embed (ADR [0038](adr/0038-in-process-acp-core.md)).+The host loads `graff-core.wasm` (or links `libgraff`) and speaks ACP over+in-memory slots — no child process.++```ts+import { graffAgent } from "@codegraff/sdk/embed";++const agent = await graffAgent({ wasm: "./graff-core.wasm", cwd: process.cwd() });+const { stopReason, updates } = await agent.prompt("hello");+```++Build the artifacts on this branch:++```+zig build wasm-core # zig-out/bin/graff-core.wasm+zig build libgraff # zig-out/lib/libgraff.so (C ABI)+```++`createGraffAgent()` is the JS host. The first-slice turn is `echo:` —+protocol + handshake in-process. Live tools / TLS / bash still go through+`graff acp` (above). A host-imported model turn is the next slice.++C ABI (wasm exports and the shared library):++| export | role |+|---|---|+| `graff_acp_create(seed)` | reset session |+| `graff_acp_in_ptr` / `in_cap` | write one JSON-RPC line |+| `graff_acp_feed(len)` | dispatch |+| `graff_acp_out_ptr` / `out_len` / `out_consume` | read newline-framed replies |+## Not this-No `libgraff`, no WASM module (`fx-core.wasm` included), no Node addon, no-in-process Zig. Those would be a different product. The 279 continuation-does not start them. This page is the host recipe that already exists.+No full-agent `fx-core.wasm` (HTTP + bash + git inside the isolate). No+Node-API addon yet — `libgraff` is a C ABI, not a `.node`. Those stay a+later slice on this continuation branch.diff --git a/docs/releases/v0.0.279-continuation.md b/docs/releases/v0.0.279-continuation.mdindex f55eec9b..b6bc04c7 100644--- a/docs/releases/v0.0.279-continuation.md+++ b/docs/releases/v0.0.279-continuation.md@@ -9,4 +9,5 @@ This branch is **not** a retag and is **not** merged back.| #629 experiment worktree pool | **Started.** `--experiment N`, `/experiment [N\|off\|status]`, children `claim()` a seat and set `agent_cwd` before `git worktree add` (ADR 0037). `/help` and `graff --help` list it. Mint/reuse of real trees, forced fan-out, and deliver-back are still open — do not close #629 yet. || #613 ACP Registry | **Docs only.** Submit recipe in [acp-registry.md](../acp-registry.md). Listing + auth check live in `agentclientprotocol/registry`. #612 streaming already shipped. Blocker: `initialize` has no `authMethods`. No registry client here. || yxlyx doctor / cube / governed / localhost | **Inventory.** [yxlyx-leftovers.md](../yxlyx-leftovers.md). `/doctor` goal/todo slice and `--max-model-calls` already exist. Lease/job/listener doctor, idle localhost supervisor, cube NDJSON ingress, protected verifiers, review-cycle caps: parked. No new product mode. |-| WASM / libgraff / in-process embed | **Parked.** Host recipe stays subprocess (`graff acp`, `@codegraff/sdk`) — [embedding.md](../embedding.md). No `fx-core.wasm`, no `libgraff`. |+| WASM / libgraff / in-process embed | **Started (ADR 0038).** `graff-core.wasm` + `libgraff` + `@codegraff/sdk/embed` `createGraffAgent()`. ACP handshake in-process; first-slice turn is `echo:`. Live tools stay `graff acp`. |+| Tab title on grok-4.6 | **Fixed.** AI title uses the session model on chat when the catalog has it (xAI / Codegraff). Failures stay off the `thinking…` row. Responses-kind errors name the provider, not "codex". |diff --git a/sdk/ts/README.md b/sdk/ts/README.mdindex af741100..079f7246 100644--- a/sdk/ts/README.md+++ b/sdk/ts/README.md@@ -183,6 +183,9 @@ await session.close();`spawnAcp()` skips the `initialize` → `session/new` handshake. Recipe, methodnames, `--no-local-tools`, and license: [Embedding graff](../../docs/embedding.md).+Same-process (no child): `@codegraff/sdk/embed` `createGraffAgent()` loads+`graff-core.wasm` (`zig build wasm-core`). First-slice turn is `echo:`.+## Links- Repository: <https://github.com/justrach/codegraff>diff --git a/sdk/ts/embed.test.ts b/sdk/ts/embed.test.tsnew file mode 100644index 00000000..72b03d29--- /dev/null+++ b/sdk/ts/embed.test.ts@@ -0,0 +1,34 @@+import { describe, expect, test } from "bun:test";+import { existsSync } from "node:fs";+import { join } from "node:path";+import { ACP_PROTOCOL_VERSION } from "./acp.ts";+import { createGraffAgent, graffAgent } from "./embed.ts";++const wasmPath = process.env.GRAFF_CORE_WASM ?? join(import.meta.dir, "../../zig-out/bin/graff-core.wasm");+const haveWasm = existsSync(wasmPath);++describe("createGraffAgent", () => {+ test.skipIf(!haveWasm)("handshake and echo prompt run in-process", async () => {+ const agent = await createGraffAgent({ wasm: wasmPath, seed: 0xabc });+ const init = (await agent.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");++ const created = (await agent.request("session/new", { cwd: "/tmp" })) as { sessionId: string };+ expect(created.sessionId).toBe("acp-abc-1");+ agent.sessionId = created.sessionId;++ const { stopReason, updates } = await agent.prompt("ping");+ expect(stopReason).toBe("end_turn");+ const text = updates.find((u) => u.sessionUpdate === "agent_message_chunk");+ expect((text?.content as { text?: string } | undefined)?.text).toBe("echo:ping");+ });++ test.skipIf(!haveWasm)("graffAgent() fills sessionId", async () => {+ const agent = await graffAgent({ wasm: wasmPath, seed: 0xabc, cwd: "/tmp" });+ expect(agent.sessionId).toBe("acp-abc-1");+ });+});diff --git a/sdk/ts/embed.ts b/sdk/ts/embed.tsnew file mode 100644index 00000000..954c794d--- /dev/null+++ b/sdk/ts/embed.ts@@ -0,0 +1,172 @@+// In-process ACP host — `graff-core.wasm` / createGraffAgent().+// Hand-written (same as acp.ts). No child process.++import { readFile } from "node:fs/promises";+import { ACP_PROTOCOL_VERSION, type AcpPromptResult, type AcpUpdate } from "./acp.ts";++export type GraffCoreExports = {+ memory: WebAssembly.Memory;+ graff_acp_in_ptr(): number;+ graff_acp_in_cap(): number;+ graff_acp_out_ptr(): number;+ graff_acp_out_len(): number;+ graff_acp_out_consume(): void;+ graff_acp_create(seed: bigint | number): void;+ graff_acp_feed(len: number): number;+};++export interface CreateGraffAgentOptions {+ /** Path, URL, or bytes of `graff-core.wasm`. */+ wasm: string | URL | Uint8Array | ArrayBuffer | WebAssembly.Module;+ seed?: number;+}++export interface GraffAgent {+ 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>;+}++const textEncoder = new TextEncoder();+const textDecoder = new TextDecoder();++function asExports(instance: WebAssembly.Instance): GraffCoreExports {+ return instance.exports as unknown as GraffCoreExports;+}++function writeIn(core: GraffCoreExports, line: string): void {+ const bytes = textEncoder.encode(line.endsWith("\n") ? line : `${line}\n`);+ const cap = core.graff_acp_in_cap();+ if (bytes.length > cap) throw new Error(`ACP line exceeds ${cap} bytes`);+ const ptr = core.graff_acp_in_ptr();+ new Uint8Array(core.memory.buffer, ptr, bytes.length).set(bytes);+ if (core.graff_acp_feed(bytes.length) !== 0) throw new Error("graff_acp_feed failed");+}++function takeOut(core: GraffCoreExports): string {+ const len = core.graff_acp_out_len();+ if (len === 0) return "";+ const ptr = core.graff_acp_out_ptr();+ const text = textDecoder.decode(new Uint8Array(core.memory.buffer, ptr, len));+ core.graff_acp_out_consume();+ return text;+}++async function compileWasm(+ wasm: CreateGraffAgentOptions["wasm"],+): Promise<WebAssembly.Module> {+ if (wasm instanceof WebAssembly.Module) return wasm;+ if (wasm instanceof Uint8Array) return WebAssembly.compile(wasm);+ if (wasm instanceof ArrayBuffer) return WebAssembly.compile(wasm);+ if (wasm instanceof URL) {+ const res = await fetch(wasm);+ return WebAssembly.compile(await res.arrayBuffer());+ }+ const bytes = await readFile(wasm);+ return WebAssembly.compile(bytes);+}++export async function createGraffAgent(opts: CreateGraffAgentOptions): Promise<GraffAgent> {+ const mod = await compileWasm(opts.wasm);+ const instance = await WebAssembly.instantiate(mod, {});+ const core = asExports(instance);+ if (typeof core.graff_acp_create !== "function") {+ throw new Error("wasm is missing graff_acp_create — rebuild with `zig build wasm-core`");+ }+ core.graff_acp_create(opts.seed ?? 1);++ const listeners = new Set<(update: AcpUpdate, sessionId?: string) => void>();+ let nextId = 1;+ let sessionId: string | null = null;++ const dispatchLines = (raw: string): unknown | undefined => {+ let lastResult: unknown;+ for (const line of raw.split("\n")) {+ const trimmed = line.trim();+ if (!trimmed) continue;+ 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 {+ continue;+ }+ if (msg.method === "session/update") {+ const update = msg.params?.update;+ if (update) {+ for (const fn of listeners) fn(update, msg.params?.sessionId);+ }+ continue;+ }+ if (msg.error) throw new Error(msg.error.message ?? "ACP error");+ if (msg.id !== undefined) lastResult = msg.result;+ }+ return lastResult;+ };++ const agent: GraffAgent = {+ get sessionId() {+ return sessionId;+ },+ set sessionId(value) {+ sessionId = value;+ },+ async request(method, params) {+ const id = nextId++;+ writeIn(core, JSON.stringify({ jsonrpc: "2.0", id, method, params }));+ return dispatchLines(takeOut(core));+ },+ notify(method, params) {+ writeIn(core, JSON.stringify({ jsonrpc: "2.0", method, params }));+ dispatchLines(takeOut(core));+ },+ onUpdate(fn) {+ listeners.add(fn);+ return () => {+ listeners.delete(fn);+ };+ },+ async prompt(text) {+ const updates: AcpUpdate[] = [];+ const off = agent.onUpdate((update) => {+ updates.push(update);+ });+ try {+ const result = (await agent.request("session/prompt", {+ sessionId: sessionId ?? "",+ prompt: [{ type: "text", text }],+ })) as AcpPromptResult;+ return { stopReason: result.stopReason, updates };+ } finally {+ off();+ }+ },+ close() {+ return Promise.resolve();+ },+ };+ return agent;+}++/** createGraffAgent + initialize + session/new. */+export async function graffAgent(opts: CreateGraffAgentOptions & { cwd?: string }): Promise<GraffAgent> {+ const agent = await createGraffAgent(opts);+ await agent.request("initialize", {+ protocolVersion: ACP_PROTOCOL_VERSION,+ clientCapabilities: { fs: {} },+ });+ const created = (await agent.request("session/new", {+ cwd: opts.cwd ?? "",+ })) as { sessionId?: string };+ if (!created?.sessionId) throw new Error("session/new returned no sessionId");+ agent.sessionId = created.sessionId;+ return agent;+}diff --git a/sdk/ts/package.json b/sdk/ts/package.jsonindex fd79309d..9078f6ad 100644--- a/sdk/ts/package.json+++ b/sdk/ts/package.json@@ -26,6 +26,11 @@"import": "./dist/acp.js","default": "./dist/acp.js"},+ "./embed": {+ "types": "./dist/embed.d.ts",+ "import": "./dist/embed.js",+ "default": "./dist/embed.js"+ },"./package.json": "./package.json"},"repository": {diff --git a/sdk/ts/tsconfig.build.json b/sdk/ts/tsconfig.build.jsonindex 186ddaf5..9e6590f8 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", "acp.ts"],+ "include": ["harness.ts", "remote.ts", "orchestrate.ts", "acp.ts", "embed.ts"],"exclude": ["*.test.ts"]}diff --git a/src/acp.zig b/src/acp.zigindex 1b688443..97fa02fc 100644--- a/src/acp.zig+++ b/src/acp.zig@@ -28,6 +28,7 @@ const session = @import("session.zig");const telemetry = @import("telemetry.zig");const util = @import("util.zig");const proto = @import("acp_protocol.zig");+const engine = @import("acp_engine.zig");const stream = @import("acp_stream.zig");const playbook_glue = @import("playbook_glue.zig");@@ -41,6 +42,8 @@ pub const flattenPrompt = proto.flattenPrompt;pub const writeResult = proto.writeResult;pub const writeError = proto.writeError;pub const writeSessionUpdate = proto.writeSessionUpdate;+pub const TurnFn = engine.TurnFn;+pub const Dispatch = engine.Dispatch;pub fn isAcpSubcommand(positional: []const u8) bool {if (!std.mem.eql(u8, positional, "acp")) return false;@@ -48,101 +51,37 @@ pub fn isAcpSubcommand(positional: []const u8) bool {return true;}-pub const TurnFn = *const fn (ctx: *anyopaque, arena: Allocator, text: []const u8) anyerror![]const u8;--pub const Dispatch = struct {- turn: TurnFn,- ctx: *anyopaque,- session_id: ?[]const u8 = null,- seed: u64 = 0,- 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,-};+fn syncEscCancel() void {+ agent_mod.Agent.esc_cancel.store(true, .release);+}-fn respond(w: *Io.Writer, req: Request, result: anytype) !void {- if (req.id == null) return;- try writeResult(w, req.id, result);+fn liveCancelled() bool {+ return agent_mod.Agent.esc_cancel.load(.acquire);}-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);+fn liveSlash(ctx: *anyopaque, arena: Allocator, text: []const u8) anyerror!?[]const u8 {+ const live: *LiveTurn = @ptrCast(@alignCast(ctx));+ if (!playbook_glue.isCommand(text)) return null;+ var aw: Io.Writer.Allocating = .init(arena);+ _ = try playbook_glue.command(live.root, arena, text, &aw.writer);+ return try engine.stripSgr(arena, aw.writer.buffered());}-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);- if (playbook_glue.isCommand(text)) {- if (d.live) |live| {- var aw: Io.Writer.Allocating = .init(arena);- _ = try playbook_glue.command(live.root, arena, text, &aw.writer);- const plain = try stripSgr(arena, aw.writer.buffered());- if (plain.len > 0) try writeSessionUpdate(w, sid, plain);- return respond(w, req, .{ .stopReason = "end_turn" });- }- }- if (d.live) |live| _ = playbook_glue.applyUserOverride(live.root, arena, text);- 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));- };- // 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);- const stop: []const u8 = if (agent_mod.Agent.esc_cancel.load(.acquire)) "cancelled" else "end_turn";- try respond(w, req, .{ .stopReason = stop });+fn liveAfter(ctx: *anyopaque, arena: Allocator, text: []const u8) void {+ const live: *LiveTurn = @ptrCast(@alignCast(ctx));+ _ = playbook_glue.applyUserOverride(live.root, arena, text);}-fn stripSgr(arena: Allocator, s: []const u8) ![]const u8 {- var buf: std.array_list.Managed(u8) = .init(arena);- var i: usize = 0;- while (i < s.len) {- if (s[i] == 0x1b and i + 1 < s.len and s[i + 1] == '[') {- i += 2;- while (i < s.len and (s[i] < '@' or s[i] > '~')) i += 1;- if (i < s.len) i += 1;- continue;- }- try buf.append(s[i]);- i += 1;- }- return buf.items;+fn liveBind(ctx: *anyopaque, session_id: []const u8) void {+ const live: *LiveTurn = @ptrCast(@alignCast(ctx));+ live.session_id = session_id;}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 = proto.PromptCapabilities{},- },- .agentImplementation = proto.AgentImplementation{ .version = main_mod.harness_version },- });- 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 });- try respond(w, req, .{ .sessionId = d.session_id.? });- try proto.writeAvailableCommands(w, d.session_id.?, proto.slashCommands());- return;- }- 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);- 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}));+ engine.implementation_version = main_mod.harness_version;+ engine.on_cancel = syncEscCancel;+ engine.extra_cancelled = liveCancelled;+ return engine.handleLine(d, arena, w, line);}const LiveTurn = struct {@@ -182,8 +121,18 @@ pub fn runAcpCommand(gpa: Allocator, io: Io, environ_map: anytype, root: *agent_root.out = null;root.stream_quiet = true;main_mod.g_out = null;+ engine.implementation_version = main_mod.harness_version;+ engine.cancel_flag.store(false, .release);+ engine.on_cancel = syncEscCancel;var live: LiveTurn = .{ .root = root, .keys = keys, .out = out };- var d: Dispatch = .{ .turn = LiveTurn.run, .ctx = &live, .live = &live, .seed = @bitCast(util.unixMs(io)) };+ var d: Dispatch = .{+ .turn = LiveTurn.run,+ .ctx = &live,+ .seed = @bitCast(util.unixMs(io)),+ .slash = liveSlash,+ .after_user = liveAfter,+ .bind_session = liveBind,+ };while (true) {const line = (in.takeDelimiter('\n') catch break) orelse break;handleLine(&d, arena, out, line) catch |err| {diff --git a/src/acp_engine.zig b/src/acp_engine.zignew file mode 100644index 00000000..e656c638--- /dev/null+++ b/src/acp_engine.zig@@ -0,0 +1,159 @@+//! In-process ACP loop: initialize / session/new / prompt / cancel.+//! No HTTP, no Agent, no `main.zig` — this is what `libgraff` and+//! `graff-core.wasm` compile (fx-shaped same-process embed).++const std = @import("std");+const Io = std.Io;+const Allocator = std.mem.Allocator;++const proto = @import("acp_protocol.zig");+const util = @import("util.zig");++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;+pub const err_method_not_found = proto.err_method_not_found;+pub const err_internal = proto.err_internal;++/// Stamped by the CLI (`harness_version`) or the embed create() call.+pub var implementation_version: []const u8 = "0.0.0-embed";++pub var cancel_flag = std.atomic.Value(bool).init(false);+pub var on_cancel: ?*const fn () void = null;+/// CLI live ACP also watches `Agent.esc_cancel` (Esc / session/cancel).+pub var extra_cancelled: ?*const fn () bool = null;++pub const TurnFn = *const fn (ctx: *anyopaque, arena: Allocator, text: []const u8) anyerror![]const u8;+pub const SlashFn = *const fn (ctx: *anyopaque, arena: Allocator, text: []const u8) anyerror!?[]const u8;+pub const AfterUserFn = *const fn (ctx: *anyopaque, arena: Allocator, text: []const u8) void;+pub const BindSessionFn = *const fn (ctx: *anyopaque, session_id: []const u8) void;++pub const Dispatch = struct {+ turn: TurnFn,+ ctx: *anyopaque,+ session_id: ?[]const u8 = null,+ seed: u64 = 0,+ created: u32 = 0,+ slash: ?SlashFn = null,+ after_user: ?AfterUserFn = null,+ bind_session: ?BindSessionFn = null,+};++fn respond(w: *Io.Writer, req: proto.Request, result: anytype) !void {+ if (req.id == null) return;+ try writeResult(w, req.id, result);+}++fn respondError(w: *Io.Writer, req: proto.Request, code: i32, message: []const u8) !void {+ if (req.id == null) return;+ try writeError(w, req.id, code, message);+}++pub fn stripSgr(arena: Allocator, s: []const u8) ![]const u8 {+ var buf: std.array_list.Managed(u8) = .init(arena);+ var i: usize = 0;+ while (i < s.len) {+ if (s[i] == 0x1b and i + 1 < s.len and s[i + 1] == '[') {+ i += 2;+ while (i < s.len and (s[i] < '@' or s[i] > '~')) i += 1;+ if (i < s.len) i += 1;+ continue;+ }+ try buf.append(s[i]);+ i += 1;+ }+ return buf.items;+}++fn promptTurn(d: *Dispatch, arena: Allocator, w: *Io.Writer, req: proto.Request) !void {+ const obj: ?std.json.ObjectMap = if (req.params) |p| (if (p == .object) p.object else null) else null;+ const sid = blk: {+ if (obj) |o| if (util.strFieldObj(o, "sessionId")) |s| break :blk s;+ break :blk d.session_id orelse "";+ };+ if (d.bind_session) |bind| bind(d.ctx, sid);+ const text = try flattenPrompt(arena, if (obj) |o| o.get("prompt") else null);+ if (d.slash) |slash| {+ if (try slash(d.ctx, arena, text)) |plain| {+ if (plain.len > 0) try writeSessionUpdate(w, sid, plain);+ return respond(w, req, .{ .stopReason = "end_turn" });+ }+ }+ if (d.after_user) |after| after(d.ctx, arena, text);+ 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));+ };+ if (final.len > 0) try writeSessionUpdate(w, sid, final);+ const extra = if (extra_cancelled) |f| f() else false;+ const stop: []const u8 = if (cancel_flag.load(.acquire) or extra) "cancelled" else "end_turn";+ try respond(w, req, .{ .stopReason = stop });+}++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 = proto.PromptCapabilities{},+ },+ .agentImplementation = proto.AgentImplementation{ .version = implementation_version },+ });+ 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 });+ try respond(w, req, .{ .sessionId = d.session_id.? });+ try proto.writeAvailableCommands(w, d.session_id.?, proto.slashCommands());+ return;+ }+ if (std.mem.eql(u8, req.method, "session/cancel")) {+ cancel_flag.store(true, .release);+ if (on_cancel) |hook| hook();+ if (req.id != null) return respond(w, req, .{});+ return;+ }+ if (std.mem.eql(u8, req.method, "session/prompt")) return promptTurn(d, arena, w, req);+ 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}));+}++fn echoTurn(_: *anyopaque, arena: Allocator, text: []const u8) anyerror![]const u8 {+ return std.fmt.allocPrint(arena, "echo:{s}", .{text});+}++test "in-process handleLine speaks the same initialize / new / prompt envelopes" {+ implementation_version = "embed-test";+ cancel_flag.store(false, .release);+ var state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer state.deinit();+ const a = state.allocator();+ var buf: [2048]u8 = undefined;+ var w: Io.Writer = .fixed(&buf);+ var d: Dispatch = .{ .turn = echoTurn, .ctx = undefined, .seed = 0xabc };++ try handleLine(&d, a, &w, "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"initialize\",\"params\":{\"protocolVersion\":9}}");+ try std.testing.expect(std.mem.indexOf(u8, w.buffered(), "\"protocolVersion\":1") != null);+ try std.testing.expect(std.mem.indexOf(u8, w.buffered(), "\"name\":\"graff\"") != null);+ try std.testing.expect(std.mem.indexOf(u8, w.buffered(), "embed-test") != null);++ w = .fixed(&buf);+ try handleLine(&d, a, &w, "{\"jsonrpc\":\"2.0\",\"id\":2,\"method\":\"session/new\"}");+ try std.testing.expectEqualStrings("acp-abc-1", d.session_id.?);+ try std.testing.expect(std.mem.indexOf(u8, w.buffered(), "available_commands_update") != null);++ w = .fixed(&buf);+ try handleLine(&d, a, &w, "{\"id\":3,\"method\":\"session/prompt\",\"params\":{\"prompt\":[{\"type\":\"text\",\"text\":\"ping\"}]}}");+ try std.testing.expect(std.mem.indexOf(u8, w.buffered(), "\"text\":\"echo:ping\"") != null);+ try std.testing.expect(std.mem.indexOf(u8, w.buffered(), "\"stopReason\":\"end_turn\"") != null);+}++test "stripSgr drops CSI sequences" {+ var state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer state.deinit();+ try std.testing.expectEqualStrings("ok", try stripSgr(state.allocator(), "\x1b[2mok\x1b[0m"));+}diff --git a/src/libgraff.zig b/src/libgraff.zignew file mode 100644index 00000000..0abc696b--- /dev/null+++ b/src/libgraff.zig@@ -0,0 +1,117 @@+//! C ABI for in-process ACP (`libgraff` + `graff-core.wasm`).+//! Same-process: the host writes a JSON-RPC line into the input slot,+//! calls `graff_acp_feed`, then reads the output slot. No child process.++const std = @import("std");+const Io = std.Io;+const Allocator = std.mem.Allocator;++const engine = @import("acp_engine.zig");++const in_cap: usize = 64 * 1024;+const out_cap: usize = 256 * 1024;+const heap_cap: usize = 1024 * 1024;++var in_buf: [in_cap]u8 = undefined;+var out_buf: [out_cap]u8 = undefined;+var out_len: usize = 0;+var heap: [heap_cap]u8 = undefined;+var fba = std.heap.FixedBufferAllocator.init(&heap);+var seed: u32 = 1;+var created: u32 = 0;+var session_id_buf: [64]u8 = undefined;+var session_id: ?[]const u8 = null;++fn echoTurn(_: *anyopaque, arena: Allocator, text: []const u8) anyerror![]const u8 {+ return std.fmt.allocPrint(arena, "echo:{s}", .{text});+}++fn dispatch() engine.Dispatch {+ return .{+ .turn = echoTurn,+ .ctx = undefined,+ .session_id = session_id,+ .seed = seed,+ .created = created,+ };+}++fn persistSession(d: *engine.Dispatch) void {+ created = d.created;+ if (d.session_id) |sid| {+ const n = @min(sid.len, session_id_buf.len);+ if (sid.ptr != &session_id_buf) {+ var tmp: [session_id_buf.len]u8 = undefined;+ @memcpy(tmp[0..n], sid[0..n]);+ @memcpy(session_id_buf[0..n], tmp[0..n]);+ }+ session_id = session_id_buf[0..n];+ }+}++export fn graff_acp_in_ptr() [*]u8 {+ return &in_buf;+}++export fn graff_acp_in_cap() usize {+ return in_cap;+}++export fn graff_acp_out_ptr() [*]const u8 {+ return &out_buf;+}++export fn graff_acp_out_len() usize {+ return out_len;+}++export fn graff_acp_out_consume() void {+ out_len = 0;+}++export fn graff_acp_create(new_seed: u32) void {+ fba.reset();+ out_len = 0;+ created = 0;+ session_id = null;+ seed = if (new_seed == 0) 1 else new_seed;+ engine.cancel_flag.store(false, .release);+ engine.implementation_version = "0.0.279-core";+}++export fn graff_acp_feed(len: usize) i32 {+ const n = @min(len, in_cap);+ var arena_state = std.heap.ArenaAllocator.init(fba.allocator());+ defer arena_state.deinit();+ var d = dispatch();+ var w: Io.Writer = .fixed(out_buf[out_len..]);+ engine.handleLine(&d, arena_state.allocator(), &w, in_buf[0..n]) catch return -1;+ out_len += w.buffered().len;+ persistSession(&d);+ return 0;+}++test "C ABI create / feed speaks ACP without a child process" {+ graff_acp_create(0xabc);+ const init_line = "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"initialize\",\"params\":{\"protocolVersion\":1}}";+ @memcpy(in_buf[0..init_line.len], init_line);+ try std.testing.expectEqual(@as(i32, 0), graff_acp_feed(init_line.len));+ const init_out = graff_acp_out_ptr()[0..graff_acp_out_len()];+ try std.testing.expect(std.mem.indexOf(u8, init_out, "\"protocolVersion\":1") != null);+ try std.testing.expect(std.mem.indexOf(u8, init_out, "\"name\":\"graff\"") != null);+ graff_acp_out_consume();++ const new_line = "{\"jsonrpc\":\"2.0\",\"id\":2,\"method\":\"session/new\"}";+ @memcpy(in_buf[0..new_line.len], new_line);+ try std.testing.expectEqual(@as(i32, 0), graff_acp_feed(new_line.len));+ const new_out = graff_acp_out_ptr()[0..graff_acp_out_len()];+ try std.testing.expect(std.mem.indexOf(u8, new_out, "acp-abc-1") != null);+ graff_acp_out_consume();++ const prompt = "{\"id\":3,\"method\":\"session/prompt\",\"params\":{\"prompt\":[{\"type\":\"text\",\"text\":\"hi\"}]}}";+ @memcpy(in_buf[0..prompt.len], prompt);+ try std.testing.expectEqual(@as(i32, 0), graff_acp_feed(prompt.len));+ const prompt_out = graff_acp_out_ptr()[0..graff_acp_out_len()];+ try std.testing.expect(std.mem.indexOf(u8, prompt_out, "echo:hi") != null);+ try std.testing.expect(std.mem.indexOf(u8, prompt_out, "end_turn") != null);+}diff --git a/src/test_hooks.zig b/src/test_hooks.zigindex 23437453..a112a9e1 100644--- a/src/test_hooks.zig+++ b/src/test_hooks.zig@@ -332,4 +332,6 @@ test {_ = session_connect_tests;_ = @import("experiment_pool.zig");_ = @import("commands_experiment.zig");+ _ = @import("acp_engine.zig");+ _ = @import("libgraff.zig");}diff --git a/src/wasm_core_main.zig b/src/wasm_core_main.zignew file mode 100644index 00000000..7f423933--- /dev/null+++ b/src/wasm_core_main.zig@@ -0,0 +1,13 @@+//! `graff-core.wasm` entry: export the libgraff C ABI, no `_start`.+//! Build: `zig build -Dwasm-surface=core`++const std = @import("std");++pub fn panic(msg: []const u8, _: ?*std.builtin.StackTrace, _: ?usize) noreturn {+ _ = msg;+ @trap();+}++comptime {+ _ = @import("libgraff.zig");+}