Skip to content

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

Python
15.2 KB
Raw Blame
//! The single source of truth for the REPL slash-command catalog, shared by
//! its three consumers so they never drift (600-line goal, issue #123):
//!   - the bare "/" fuzzy menu   (pickers.command_menu -> mainloop)
//!   - the /help dump            (commands_misc.handleRest)
//!   - tab completion            (main.repl_commands -> input_util)
//! Each entry's `name` is the runnable command — the bare "/" menu passes it
//! straight to handleCommand, so it must be the plain "/foo" form, never a
//! usage string. `usage` is the fuller "/foo <arg>" form shown only in the
//! /help dump (it falls back to `name` when empty). `desc` is the one-liner.

const std = @import("std");
const slash_suggest = @import("slash_suggest");

/// One catalog entry. `name`/`desc` are the same two fields the generic
/// listPicker items carry (pickers.PickItem = this type), so both are always
/// set there; `usage` is catalog-only and defaults to the bare name.
pub const Item = struct {
    name: []const u8,
    desc: []const u8 = "",
    usage: []const u8 = "",
};

/// 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;
}

/// Spellings the handlers accept that are not catalog entries (each runs the
/// entry named in its comment). suggest() offers them like any name.
pub const aliases = [_][]const u8{
    "/constraint", // /never
    "/ws", // /workspace
    "/adopt", // /import-claude
};

/// The first word of `line` when it is command-shaped: `/` then letters,
/// digits, `-` or `_`, ended by whitespace or the end of the line. A path
/// (`/usr/bin/foo`, `/tmp/x.png`), `/**`, or text that merely contains a
/// `/word` later on is not a command and stays an ordinary prompt.
pub fn commandWord(line: []const u8) ?[]const u8 {
    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\r\n") orelse t.len];
    for (word[1..]) |c| if (!(std.ascii.isAlphanumeric(c) or c == '-' or c == '_')) return null;
    return word;
}

/// The command `word` most likely misspells (#1275): the nearest catalog
/// name or alias by edit distance, or null when nothing is close. Shared by
/// the terminal refusal (commands_misc.handleRest) and, through it, ACP.
pub fn suggest(word: []const u8) ?[]const u8 {
    const candidates = comptime names ++ aliases;
    return slash_suggest.nearest(word, &candidates);
}

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" },
    .{ .name = "/clear", .desc = "wipe the conversation and start fresh" },
    .{ .name = "/new", .desc = "start a fresh autosaved session" },
    .{ .name = "/rename", .usage = "/rename <title>", .desc = "set the current session title" },
    .{ .name = "/goal", .usage = "/goal [30m] [text|pause|resume|status|clear]", .desc = "set a standing objective and work it autonomously; an optional 30s/30m/2h budget paces the run; pause/resume steering, status shows state, clear removes it" },
    .{ .name = "/goals", .desc = "show the current goal without changing it (alias for /goal status)" },
    .{ .name = "/schedule", .usage = "/schedule <30s|5m|2h> <prompt>", .desc = "fire a prompt later after a 30s/5m/2h delay (not a standing goal)" },
    .{ .name = "/adapter", .usage = "/adapter send <text>|inbox", .desc = "channel-worker outbox / inbox (JSONL protocol; Discord/Slack fronts later)" },
    .{ .name = "/review", .usage = "/review <target or instructions>", .desc = "run one isolated read-only review pass; no edits, delegation, or workflows" },
    .{ .name = "/never", .usage = "/never [<text>|rm <id-or-text>]", .desc = "standing constraints that ride every brief; bare opens a searchable picker (TTY) or lists them, rm <id-or-text> retires one (alias /constraint)" },
    .{ .name = "/tell", .usage = "/tell <session|all> <text>", .desc = "message a running graff: <session> is a DM (only it hears, any folder); all broadcasts to every graff on this device; /sessions lists who's around" },
    .{ .name = "/daddy", .usage = "/daddy <session> <text>", .desc = "direct one live graff as the supervisor — control, not ambient room mail; /sessions lists who's around" },
    .{ .name = "/peek", .usage = "/peek <session>", .desc = "see what a live co-resident session is doing right now (its transcript tail)" },
    .{ .name = "/routes", .usage = "/routes [<set>|add <set> <frontier|mid|small> <provider/model>]", .desc = "your own priced model lanes across providers — view the set and which seat wins each lane now" },
    .{ .name = "/plan", .desc = "toggle plan mode: read-only explore + propose; writes/edits denied" },
    .{ .name = "/ultracode", .desc = "toggle persistent workflow mode; bare opens an on/off picker, or /ultracode on|off" },
    .{ .name = "/fallback", .usage = "/fallback [allow|remove|off]", .desc = "opt-in cross-provider fallback for this workspace (same-provider rollout stays on)" },
    .{ .name = "/key", .usage = "/key [provider secret]", .desc = "show API-key status; /key <provider> <secret> adds one live (+ Keychain)" },
    .{ .name = "/login", .usage = "/login [codegraff|chatgpt|kimi|xai|zai]", .desc = "OAuth sign-in (no key to paste); bare opens a picker (chatgpt aliases: codex, openai, oai; zai aliases: glm, z.ai; kimi sites: kimi.ai, kimi.com)" },
    .{ .name = "/keepcontext", .desc = "toggle keeping the conversation when /model switches wire format (default on)" },
    .{ .name = "/effort", .desc = "reasoning depth: low|medium|high|... (codex, deepseek, codegraff; persists)" },
    .{ .name = "/reasoning", .desc = "alias for /effort" },
    .{ .name = "/compact-at", .usage = "/compact-at [10-95|default]", .desc = "where automatic compaction starts, as % of the context window (default 80; persists)" },
    .{ .name = "/fast", .desc = "codex only: priority service tier for lower latency (toggle, persists)" },
    .{ .name = "/thinking", .desc = "stream reasoning live vs spinner only (toggle, persists)" },
    .{ .name = "/title", .desc = "name the tab from your first prompt (AI session title; toggle, persists)" },
    .{ .name = "/strict", .desc = "toggle \"every message is a tool\" mode" },
    .{ .name = "/yolo", .desc = "toggle bash auto-approval (skip permission prompts)" },
    .{ .name = "/trace", .desc = "toggle this run's JSONL event trace (and show its path)" },
    .{ .name = "/privacy", .usage = "/privacy [local|aggregate|templates|examples]", .desc = "control prompt-learning data egress for this session" },
    .{ .name = "/trajectory", .desc = "show this session's agent tree — turns + spawned subagents" },
    .{ .name = "/issue", .usage = "/issue <what went wrong>", .desc = "file one sanitized public tracker issue from this session" },
    .{ .name = "/agents", .desc = "list agent types — builtin personas + .harness/agents" },
    .{ .name = "/workers", .usage = "/workers [child-id]", .desc = "inspect this session's subagents: click/Enter for live activity and reports, Esc to return" },
    .{ .name = "/skills", .usage = "/skills [add|remove <name>]", .desc = "list SKILL.md playbooks + companion tools; add/remove enables or disables one" },
    .{ .name = "/plugins", .usage = "/plugins [list|load <name>]", .desc = "list Claude/Cursor/Grok/Codex plugin trees graff is reading in place; load names one" },
    .{ .name = "/hooks", .desc = "list lifecycle hooks and the built-in codedb guard" },
    .{ .name = "/doctor", .desc = "read-only health check: goal/todo, live jobs, model-call budget" },
    .{ .name = "/btw", .usage = "/btw <question>", .desc = "ask one side question about this conversation — billed, never added, rides the parent cache prefix" },
    .{ .name = "/compact", .desc = "compact history into a fresh context (OpenAI server-side when available)" },
    .{ .name = "/rewind", .usage = "/rewind [n|<snapshot>]", .desc = "list past prompts; /rewind <n> drops prompt n+after & reverts its file edits; /rewind <snapshot id> restores a sandbox filesystem instead, never the conversation" },
    .{ .name = "/edit", .usage = "/edit <n> <text>", .desc = "replace prompt n, drop n+after, keep the prefix so the next turn can still hit cache" },
    .{ .name = "/snapshot", .usage = "/snapshot [attach [image]|detach|list|gc [n]]", .desc = "capture the attached sandbox's filesystem under .graff/sessions/<session>/snapshots; attach puts this session in a Docker sandbox, list shows what it has captured, gc keeps the newest n (default 1)" },
    .{ .name = "/teleport", .usage = "/teleport <id> [docker|container]", .desc = "restore a docker_image_tar snapshot onto a different CLI backend (Apple Container by default); filesystem only, never the conversation" },
    .{ .name = "/image", .usage = "/image <path>", .desc = "attach an image to your next message (vision models only)" },
    .{ .name = "/images", .desc = "open image URLs from the last response (e.g. issue attachments) in your browser" },
    .{ .name = "/paste", .desc = "attach the clipboard image — macOS; also Ctrl-V (⌘V can't be captured)" },
    .{ .name = "/bash", .usage = "/bash <command>", .desc = "run a shell command directly" },
    .{ .name = "/save", .usage = "/save [name]", .desc = "write the conversation to <name>.session.json (default: current)" },
    .{ .name = "/resume", .usage = "/resume [source] [--branch destination]", .desc = "restore a saved conversation, optionally cloning it into an independent branch" },
    .{ .name = "/fork", .usage = "/fork [name]", .desc = "branch this conversation into a new session and continue there; the original stays saved for /resume" },
    .{ .name = "/sessions", .desc = "list saved sessions here and under ~/.graff/sessions" },
    .{ .name = "/workspace", .usage = "/workspace [list|use <name>|create <name>|gc]", .desc = "list git worktrees, switch, create a task workspace, or gc unused trees (free space)" },
    .{ .name = "/experiment", .usage = "/experiment [N|off|status]", .desc = "pre-mint N child worktrees (1-16) and seat the next spawns in them; off clears the pool" },
    .{ .name = "/todo", .desc = "show the current task list" },
    .{ .name = "/jobs", .usage = "/jobs [keep|unkeep|stop|restart <id>]", .desc = "list background jobs (age, port, idle stop); keep pins a server, restart reruns one" },
    .{ .name = "/cost", .desc = "session token usage and cost" },
    .{ .name = "/usage", .desc = "session cost plus remaining Codex/xAI plan percent" },
    .{ .name = "/version", .desc = "show the version in this process and compare it with the latest release" },
    .{ .name = "/update", .usage = "/update [install]", .desc = "check for a release and install it for the next launch (this session keeps running)" },
    .{ .name = "/debug", .desc = "live content-free observability HUD (turns, tokens, tools, last events)" },
    .{ .name = "/cache", .desc = "prompt-cache posture: prefix hash, hit rate, last bust, remaining max levers" },
    .{ .name = "/tools", .desc = "session tool balance: codedb-pro vs zigrep vs native usage, gate refusals, skew" },
    .{ .name = "/animation", .desc = "pick the thinking animation; persists to settings" },
    .{ .name = "/theme", .usage = "/theme [name]", .desc = "pick a color theme; /theme off resets to your terminal default; persists" },
    .{ .name = "/fleet", .usage = "/fleet [on|off]", .desc = "federated DGM contribution (propose/submit/elite_pull)" },
    .{ .name = "/mcp", .usage = "/mcp [add … | reconnect <name>]", .desc = "list MCP servers/tools; /mcp add <name> <cmd> [args...] connects one live; /mcp reconnect <name> starts one again" },
    .{ .name = "/computer", .usage = "/computer [status | stop | off … | allow … | grant … | open]", .desc = "nanocua's switches: what's on, stop it, ask to turn things on (macOS)" },
    .{ .name = "/import-claude", .desc = "copy Claude/Cursor setup and import this project's Claude conversations for /resume" },
    .{ .name = "/help", .desc = "list every command" },
};

/// Bare command names for tab completion (re-exported as main.repl_commands),
/// derived from `commands` so completion never drifts from the menu.
pub const names = blk: {
    var arr: [commands.len][]const u8 = undefined;
    for (&arr, commands) |*slot, command| slot.* = command.name;
    break :blk arr;
};

// /doctor is dispatched from commands_misc.tryHandle now, so doctor.zig is
// reached through the production import graph and needs no hook here.

test "catalog is well-formed and names track commands" {
    try std.testing.expectEqual(commands.len, names.len);
    for (commands, names) |command, name| {
        try std.testing.expect(command.name.len > 1 and command.name[0] == '/');
        try std.testing.expect(command.desc.len > 0);
        try std.testing.expectEqualStrings(command.name, name);
    }
}

test "suggest (#1275): typos find the command, unrelated words do not" {
    try std.testing.expectEqualStrings("/resume", suggest("/resuem").?); // transposition
    try std.testing.expectEqualStrings("/help", suggest("/hlep").?);
    try std.testing.expectEqualStrings("/model", suggest("/modle").?);
    try std.testing.expectEqualStrings("/compact", suggest("/compcat").?);
    try std.testing.expectEqualStrings("/sessions", suggest("/sesions").?); // deletion
    try std.testing.expectEqualStrings("/resume", suggest("/Resume").?); // case only
    try std.testing.expectEqualStrings("/constraint", suggest("/constrant").?); // aliases count
    // Too far from every name, or too short to guess at.
    try std.testing.expect(suggest("/banana") == null);
    try std.testing.expect(suggest("/xyzzy") == null);
    try std.testing.expect(suggest("/zz") == null);
    try std.testing.expect(suggest("/") == null);
    var long: [81]u8 = undefined;
    @memset(&long, 'a');
    long[0] = '/';
    try std.testing.expect(suggest(&long) == null); // past the speller's length cap
}

test "commandWord (#1275): paths and prose are not commands" {
    try std.testing.expectEqualStrings("/resuem", commandWord("/resuem").?);
    try std.testing.expectEqualStrings("/resuem", commandWord("  /resuem last  ").?);
    try std.testing.expectEqualStrings("/import-claude", commandWord("/import-claude now").?);
    try std.testing.expectEqualStrings("/foo", commandWord("/foo\nsecond line").?);
    try std.testing.expect(commandWord("/usr/bin/foo") == null);
    try std.testing.expect(commandWord("/usr/bin/foo explain this") == null);
    try std.testing.expect(commandWord("/tmp/x.png") == null);
    try std.testing.expect(commandWord("/x.png what is this") == null);
    try std.testing.expect(commandWord("/**\n * doc comment\n */") == null);
    try std.testing.expect(commandWord("please /resuem") == null);
    try std.testing.expect(commandWord("/") == null);
    try std.testing.expect(commandWord("") == null);
}