graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
fix(native): the command menu lists what the agent actually runs
justrachbc42fdd008f8
diff --git a/apps/native/app/api/acp/route.ts b/apps/native/app/api/acp/route.tsindex b4d93e7c..2c51a24e 100644--- a/apps/native/app/api/acp/route.ts+++ b/apps/native/app/api/acp/route.ts@@ -4,6 +4,7 @@ import os from "node:os";import path from "node:path";import type { Readable, Writable } from "node:stream";import { NextRequest } from "next/server";+import type { AcpCommand } from "@/lib/acp";import { defaultRoot, resolveRoot } from "@/lib/server-root";export const runtime = "nodejs";@@ -24,6 +25,8 @@ type Slot = {yolo: boolean;/** Whether the configured MCP servers were started with it. */mcp: boolean;+ /** What the agent said it services, from `available_commands_update`. */+ commands: AcpCommand[];};type SpawnOpts = { model?: string; resume?: string; cwd: string; yolo: boolean; mcp: boolean };@@ -123,6 +126,7 @@ function spawnAgent(chat: string, opts: SpawnOpts): Slot {cwd: opts.cwd,yolo: opts.yolo,mcp: opts.mcp,+ commands: [],};child.on("exit", () => {if (slots.get(chat) === slot) slots.delete(chat);@@ -159,18 +163,50 @@ function readLine(slot: Slot, timeoutMs: number): Promise<string> {});}+/** The agent advertises its command set once, unprompted, right after+ * session/new — so it has to be picked off the stream rather than asked for. */+function noteCommands(slot: Slot, msg: { params?: unknown }): void {+ const update = (msg.params as { update?: { sessionUpdate?: string; availableCommands?: AcpCommand[] } } | undefined)+ ?.update;+ if (update?.sessionUpdate !== "available_commands_update") return;+ if (Array.isArray(update.availableCommands)) slot.commands = update.availableCommands;+}++/** The advertisement follows the session/new result on the same stream, so+ * the reply to that call returns before it has been read. Wait briefly for+ * it rather than leaving the menu empty until the first prompt. */+async function drainCommands(slot: Slot): Promise<void> {+ const deadline = Date.now() + 2_000;+ while (slot.commands.length === 0 && Date.now() < deadline) {+ let line: string;+ try {+ line = await readLine(slot, Math.max(50, deadline - Date.now()));+ } catch {+ return;+ }+ try {+ noteCommands(slot, JSON.parse(line) as { params?: unknown });+ } catch {+ // not JSON: a diagnostic line, keep waiting+ }+ }+}+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 };+ let msg: { id?: unknown; result?: unknown; error?: { message?: string }; method?: string; params?: unknown };try {msg = JSON.parse(line) as typeof msg;} catch {continue;}- if (msg.method) continue;+ if (msg.method) {+ noteCommands(slot, msg);+ continue;+ }if (msg.id !== id) continue;if (msg.error) throw new Error(msg.error.message ?? "ACP error");return msg.result;@@ -204,6 +240,7 @@ async function bootstrap(chat: string, opts: BootstrapOpts): Promise<Slot> {};if (!created?.sessionId) throw new Error("session/new returned no sessionId");slot.sessionId = created.sessionId;+ await drainCommands(slot);return slot;}@@ -261,7 +298,7 @@ export async function POST(req: NextRequest) {yolo,mcp,});- return Response.json({ sessionId: slot.sessionId, cwd: slot.cwd });+ return Response.json({ sessionId: slot.sessionId, cwd: slot.cwd, commands: slot.commands });}const slot = await bootstrap(chat, { model });if (method === "session/cancel") {diff --git a/apps/native/components/primitives/PromptBar.tsx b/apps/native/components/primitives/PromptBar.tsxindex 25feefe0..880e26a8 100644--- a/apps/native/components/primitives/PromptBar.tsx+++ b/apps/native/components/primitives/PromptBar.tsx@@ -1,7 +1,8 @@"use client";-import { useEffect, useLayoutEffect, useRef, useState } from "react";+import { useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";import { createShader, playSweep, accentChain, ACCENTS } from "glimm";+import type { AcpCommand } from "@/lib/acp";import { entryAt, historyKeyIntent, stepHistory } from "@/lib/prompt-history";/* The built-in "prism" palette is only cyan→indigo→magenta, so a sweep@@ -89,12 +90,16 @@ const SOURCES: Source[] = [{ key: "gmail", name: "Gmail", desc: "Read and manage Gmail", brand: "gmail", connect: true },];-const COMMANDS = [- { key: "compare", name: "/compare", desc: "Flavor vs. last summer" },- { key: "churn-plan", name: "/churn-plan", desc: "Draft a churn schedule" },- { key: "restock", name: "/restock", desc: "Build a reorder list" },- { key: "draft-email", name: "/draft-email", desc: "Write a supplier email" },- { key: "summarize", name: "/summarize", desc: "Digest the thread so far" },+/* The self-running walkthrough types "/" and glides through rows, so it+ * needs something to show. A live surface is handed the agent's real set and+ * never falls back to these — an invented command must not reach a console+ * where someone could run it. */+const DEMO_COMMANDS: AcpCommand[] = [+ { name: "compare", description: "Flavor vs. last summer" },+ { name: "churn-plan", description: "Draft a churn schedule" },+ { name: "restock", description: "Build a reorder list" },+ { name: "draft-email", description: "Write a supplier email" },+ { name: "summarize", description: "Digest the thread so far" },];const MODELS = [@@ -153,6 +158,7 @@ export default function PromptBar({placeholder,onSend,models,+ commands,modelKey,onModelChange,disabled,@@ -168,6 +174,9 @@ export default function PromptBar({placeholder?: string;onSend?: (text: string) => void;models?: PromptModel[];+ /** The slash commands the agent advertised. Empty until it answers —+ * an empty menu beats inventing commands this build may not service. */+ commands?: AcpCommand[];modelKey?: string;onModelChange?: (key: string) => void;disabled?: boolean;@@ -235,6 +244,12 @@ export default function PromptBar({if (auto && event.target === inputRef.current) setDraft("");};+ /* ACP names commands bare; the menu shows and inserts the typed form. */+ const slashRows = useMemo(() => {+ const live = commands ?? (demo ? DEMO_COMMANDS : []);+ return live.map((c) => ({ key: c.name, name: `/${c.name}`, desc: c.description }));+ }, [commands, demo]);+const token = dismissed ? null : parseToken(draft);const menu: "at" | "slash" | null = plusOpen ? "at" : token?.kind ?? null;const query = plusOpen ? "" : token?.query ?? "";@@ -243,7 +258,7 @@ export default function PromptBar({menu === "at"? SOURCES.filter((s) => s.name.toLowerCase().includes(query)): menu === "slash"- ? COMMANDS.filter((c) => c.name.slice(1).startsWith(query))+ ? slashRows.filter((c) => c.name.slice(1).startsWith(query)): [];useEffect(() => {diff --git a/apps/native/components/site/GraffHarness.tsx b/apps/native/components/site/GraffHarness.tsxindex 061edc64..18ef0cf8 100644--- a/apps/native/components/site/GraffHarness.tsx+++ b/apps/native/components/site/GraffHarness.tsx@@ -25,7 +25,7 @@ import {prompt,type Health,} from "@/lib/acp-client";-import { applyAcpUpdate, emptyTurn, finishAcpTurn, type AssistantTurn } from "@/lib/acp";+import { applyAcpUpdate, emptyTurn, finishAcpTurn, type AcpCommand, type AssistantTurn } from "@/lib/acp";import { isFollowingTail, pinScrollerTail } from "@/lib/follow-scroll";import { dropQueuedPrompt, enqueuePrompt, shiftQueuedPrompt, type QueuedPrompt } from "@/lib/prompt-queue";import { dateGroup, listSessionsPage, loadSession, relativeTime, removeSession, toSidebarRecent, type StoredSession } from "@/lib/sessions";@@ -87,6 +87,8 @@ export default function GraffHarness() {// chat id → graff session name (the `--resume` target / sidebar identity).const sessionNamesRef = useRef(new Map<number, string>());const [sessionIds, setSessionIds] = useState<Record<number, string>>({});+ /** Per tab, the slash commands its agent advertised at session/new. */+ const [commands, setCommands] = useState<Record<number, AcpCommand[]>>({});const [stored, setStored] = useState<StoredSession[]>([]);const [storedTotal, setStoredTotal] = useState(0);const [busyIds, setBusyIds] = useState<ReadonlySet<number>>(() => new Set());@@ -247,7 +249,7 @@ export default function GraffHarness() {const cwd = chat?.cwd ?? activePathRef.current ?? undefined;const ws = findWorkspace(workspacesRef.current, cwd);const spawnModel = key ?? chat?.model ?? ws?.model ?? model ?? undefined;- const id = await ensureSession(handleOf(chatId), {+ const { sessionId: id, commands } = await ensureSession(handleOf(chatId), {model: spawnModel,reset,resume: sessionNamesRef.current.get(chatId),@@ -257,6 +259,9 @@ export default function GraffHarness() {});sessionsRef.current.set(chatId, id);setSessionIds((current) => ({ ...current, [chatId]: id }));+ // The command menu is whatever this agent says it services — a build+ // with different commands must not be described by a stale list here.+ if (commands.length > 0) setCommands((current) => ({ ...current, [chatId]: commands }));setHealth({ ok: true });return id;};@@ -867,6 +872,7 @@ export default function GraffHarness() {tallplaceholder={threadBusy ? "Queue a follow-up…" : "Follow up"}models={models}+ commands={commands[thread.id] ?? []}modelKey={threadModel}onModelChange={(key: string) => changeModel(key, thread.id)}onSend={(text: string) => void send(text, thread.id)}diff --git a/apps/native/lib/acp-client.ts b/apps/native/lib/acp-client.tsindex f894e3c3..2c8bcbe5 100644--- a/apps/native/lib/acp-client.ts+++ b/apps/native/lib/acp-client.ts@@ -1,4 +1,4 @@-import { parseRpcLine, type AcpUpdate, type JsonRpcLine } from "./acp";+import { parseRpcLine, type AcpCommand, type AcpUpdate, type JsonRpcLine } from "./acp";const BASE = "/api/acp";@@ -89,11 +89,14 @@ export type SessionOpts = {/** The tab's agent, spawned on first use and reused while it still matches* the options; a changed model, workspace or approval mode respawns it. */-export async function ensureSession(chat: ChatHandle, opts: SessionOpts = {}): Promise<string> {+export async function ensureSession(+ chat: ChatHandle,+ opts: SessionOpts = {},+): Promise<{ sessionId: string; commands: AcpCommand[] }> {const res = await rpc(chat, "bootstrap", opts);- const body = (await res.json()) as { sessionId?: string; error?: string };+ const body = (await res.json()) as { sessionId?: string; error?: string; commands?: AcpCommand[] };if (!body.sessionId) throw new Error(body.error ?? "ACP session/new failed");- return body.sessionId;+ return { sessionId: body.sessionId, commands: body.commands ?? [] };}export async function* prompt(diff --git a/apps/native/lib/acp.ts b/apps/native/lib/acp.tsindex e43b8411..04d25962 100644--- a/apps/native/lib/acp.ts+++ b/apps/native/lib/acp.ts@@ -2,6 +2,10 @@export type AcpContent = { type: "text"; text: string };+/** One entry of the agent's `available_commands_update`: the slash commands+ * this build actually services, named without the leading slash. */+export type AcpCommand = { name: string; description: string; input?: { hint?: string } | null };+export type AcpToolKind = "read" | "edit" | "delete" | "move" | "search" | "execute" | "think" | "fetch" | "other";export type AcpToolStatus = "pending" | "in_progress" | "completed" | "failed";diff --git a/src/acp.zig b/src/acp.zigindex 7df0d06e..49ead453 100644--- a/src/acp.zig+++ b/src/acp.zig@@ -31,6 +31,7 @@ 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");+const command_catalog = @import("command_catalog.zig");const vision = @import("vision.zig");const vision_queue = @import("vision_queue.zig");const pricing = @import("pricing.zig");@@ -64,11 +65,21 @@ fn liveCancelled() bool {return agent_mod.Agent.esc_cancel.load(.acquire);}+/// A slash command typed in a client runs the same handler the REPL runs,+/// so the menu the agent advertises is not a menu of things that then get+/// sent to the model as prose. Anything outside the catalog returns null+/// and stays an ordinary prompt. Pickers here find no TTY and fall back to+/// printing their list, so nothing waits on a keypress that cannot come.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);+ // /never is the playbook's own, and handleCommand does not know it.+ if (playbook_glue.isCommand(text)) {+ _ = try playbook_glue.command(live.root, arena, text, &aw.writer);+ return try engine.stripSgr(arena, aw.writer.buffered());+ }+ if (command_catalog.match(text) == null) return null;+ try main_mod.handleCommand(live.root, live.keys, arena, text, &aw.writer);return try engine.stripSgr(arena, aw.writer.buffered());}@@ -378,7 +389,7 @@ test "handleLine: initialize, session/new, then a prompt turn" {var state = std.heap.ArenaAllocator.init(testing.allocator);defer state.deinit();const a = state.allocator();- var buf: [4096]u8 = undefined;+ var buf: [16384]u8 = undefined; // session/new advertises the whole command catalogvar w: Io.Writer = .fixed(&buf);var d: Dispatch = .{ .turn = echoTurn, .ctx = undefined, .seed = 0xabc };@@ -415,7 +426,7 @@ test "handleLine: a prompt with no sessionId falls back to the live session" {var state = std.heap.ArenaAllocator.init(testing.allocator);defer state.deinit();const a = state.allocator();- var buf: [2048]u8 = undefined;+ var buf: [16384]u8 = undefined; // session/new advertises the whole command catalogvar w: Io.Writer = .fixed(&buf);var d: Dispatch = .{ .turn = echoTurn, .ctx = undefined, .seed = 1 };try handleLine(&d, a, &w, "{\"id\":1,\"method\":\"session/new\"}");diff --git a/src/acp_engine.zig b/src/acp_engine.zigindex 6c6b129c..a3277801 100644--- a/src/acp_engine.zig+++ b/src/acp_engine.zig@@ -154,7 +154,7 @@ test "in-process handleLine speaks the same initialize / new / prompt envelopes"var state = std.heap.ArenaAllocator.init(std.testing.allocator);defer state.deinit();const a = state.allocator();- var buf: [2048]u8 = undefined;+ var buf: [16384]u8 = undefined; // session/new advertises the whole command catalogvar w: Io.Writer = .fixed(&buf);var d: Dispatch = .{ .turn = echoTurn, .ctx = undefined, .seed = 0xabc };diff --git a/src/acp_protocol.zig b/src/acp_protocol.zigindex 38a5f160..3bcb92e8 100644--- a/src/acp_protocol.zig+++ b/src/acp_protocol.zig@@ -7,6 +7,7 @@ const Io = std.Io;const Allocator = std.mem.Allocator;const Value = std.json.Value;const util = @import("util.zig");+const command_catalog = @import("command_catalog.zig");/// Highest ACP protocol version this agent implements (v1 shapes).pub const protocol_version: i64 = 1;@@ -154,17 +155,42 @@ pub fn writeAvailableCommands(w: *Io.Writer, session_id: []const u8, commands: [});}+/// Commands the menu does not offer. Each one needs a terminal the client+/// does not have: a full-screen HUD, the raw-mode key loop a picker drives,+/// or the browser hand-off an OAuth flow waits on. Typing one still works —+/// it degrades to a text dump — but a menu entry that lands somewhere the+/// client cannot show is worse than no entry.+const terminal_only = [_][]const u8{+ "/theme",+ "/animation",+ "/debug",+ "/login",+ "/paste",+ "/image",+ "/images",+};++/// The advertised set, built from the one catalog the REPL and tab+/// completion already read, so a command cannot exist in one surface and be+/// missing from the other. Names go out bare: ACP owns the leading slash.pub fn slashCommands() []const AvailableCommand {- return &.{- .{- .name = "never",- .description = "List, add, or retire a standing constraint. Bare lists them; `rm <id-or-text>` retires one.",- .input = .{ .hint = "[<text>|rm <id-or-text>]" },- },- .{- .name = "constraint",- .description = "Alias for never.",- .input = .{ .hint = "[<text>|rm <id-or-text>]" },- },+ const built = comptime blk: {+ var out: [command_catalog.commands.len]AvailableCommand = undefined;+ var n: usize = 0;+ for (command_catalog.commands) |c| {+ for (terminal_only) |skip| {+ if (std.mem.eql(u8, c.name, skip)) break;+ } else {+ out[n] = .{+ .name = c.name[1..],+ .description = c.desc,+ .input = .{ .hint = c.usage },+ };+ n += 1;+ }+ }+ const frozen = out[0..n].*;+ break :blk frozen;};+ return &built;}diff --git a/src/command_catalog.zig b/src/command_catalog.zigindex 4f9234ef..13a2d4cb 100644--- a/src/command_catalog.zig+++ b/src/command_catalog.zig@@ -20,6 +20,16 @@ pub const Item = struct {};/// The canonical command list, in menu / help display order.+/// The catalog entry `line` invokes, or null when its first word is not one+/// of ours — callers hand anything else to the model as ordinary text.+pub fn match(line: []const u8) ?Item {+ const t = std.mem.trim(u8, line, " \t\r\n");+ if (t.len < 2 or t[0] != '/') return null;+ const word = t[0 .. std.mem.indexOfAny(u8, t, " \t") orelse t.len];+ for (commands) |c| if (std.mem.eql(u8, c.name, word)) return c;+ return null;+}+pub const commands = [_]Item{.{ .name = "/model", .usage = "/model [<provider>] <name>", .desc = "switch model/provider, fuzzy match (e.g. \"sonnet\", \"opus\"); name a provider to pin the seat" },.{ .name = "/models", .usage = "/models [health]", .desc = "list known models: context window, compaction point, provider and what that seat costs (plan/credits/api/local); health shows live state" },