Skip to content

armgit / agtx

Public Imported from GitHub
0

πŸ„πŸΌβ€β™‚οΈ The blackboard for coding agents - agentic development environment for claude code, codex, cursor, opencode, grok and more.

51.5 KB
Raw Blame
//! One declarative record per coding agent.
//!
//! Everything agtx knows about an agent that is *data* lives here; everything
//! that is *behaviour* is selected by a small closed enum stored in the record
//! rather than by re-matching the agent's name in each function. The short
//! version is that a name-match ending in `_ => {}` cannot tell you an agent was
//! only half added, and a kind-match over a closed enum can.
//!
//! The record is deliberately pure data (no closures, no `String`) so that it
//! can later be deserialized from a `[[agents]]` block in `config.toml`, which
//! is what makes user-defined agents possible.
//!
//! Adding an agent is one entry in [`AGENT_SPECS`]. If a field cannot express
//! it, the right move is one new enum variant plus one new match arm in the one
//! function that reads that enum β€” not a new match on the agent's name.

/// How a non-empty prompt is appended to the agent's launch command.
///
/// This is the *shape of the CLI*, not a statement about whether agtx trusts it
/// β€” see [`AgentSpec::launch_prompt_verified`] for that.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PromptForm {
    /// Positional argument: `claude '<text>'`.
    Argv,
    /// Prompt flag: `gemini -i '<text>'`.
    Flag(&'static str),
}

/// How the resume flags combine with [`AgentSpec::base_args`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ResumeArgs {
    /// Appended after the launch flags: `claude --dangerously-skip-permissions --continue`.
    Append(&'static [&'static str]),
    /// Replaces the launch flags entirely: `codex resume --last` takes no `--sandbox`.
    Replace(&'static [&'static str]),
}

/// How skill files are laid out in the agent's native discovery directory, and
/// therefore also how existing skills are found when scanning a project.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SkillLayout {
    /// `{base}/{namespace}/{short-name}.md` β€” Claude, Copilot.
    CommandFile,
    /// `{base}/{namespace}/{short-name}.toml` β€” Gemini's TOML command format.
    GeminiToml,
    /// `{base}/{full-name}/SKILL.md` β€” Codex, Cursor, Grok, Antigravity.
    SkillDir,
    /// `{base}/{full-name}.md`, flat, no namespace subdir β€” OpenCode.
    OpenCodeFlat,
}

/// Slash-command syntax the agent's TUI accepts for an invocable skill.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CommandSyntax {
    /// `/ns:command` β€” the canonical form, unchanged.
    Colon,
    /// `/ns-command` β€” colon becomes a hyphen, the slash is kept.
    Hyphen,
    /// `$ns-command` β€” Codex's inline skill reference.
    Dollar,
    /// `/skill:ns-command` β€” pi's skill commands live in one `skill:` namespace
    /// of their own, so the plugin's namespace collapses into the skill *name*
    /// (`/agtx:plan` β†’ `/skill:agtx-plan`) rather than staying a prefix.
    /// Verified against pi 0.84.3.
    PiSkill,
    /// No interactive skill invocation; callers fall back to a file-path
    /// reference. Copilot, and any agent agtx has not been taught.
    None,
}

/// When an agent's dialog appears, which decides how it is matched.
///
/// The distinction is forced by what each call site knows. `wait_for_agent_ready`
/// is handed only a tmux target, so it matches `Launch` dialogs against any pane
/// regardless of agent β€” a false positive is possible in principle. The
/// session-refresh loop *does* know which agent runs in the pane, so `Session`
/// dialogs are matched only against their own agent.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DialogScope {
    /// Shown once when the agent opens in a directory it has not seen.
    Launch,
    /// Shown mid-session, e.g. the first time the agent calls an MCP tool.
    Session,
}

/// An interactive prompt that blocks the agent until it is answered.
#[derive(Debug, Clone, Copy)]
pub struct AgentDialog {
    /// Text to look for in the pane. Combined per [`require_all`](Self::require_all).
    pub patterns: &'static [&'static str],
    /// Whether answering this is a **security decision** rather than a nuisance.
    ///
    /// A trust prompt asks the user to vouch for a directory's contents; a
    /// permission-bypass warning asks them to accept unattended tool execution.
    /// Those are the user's to make, and `auto_trust = false` (the default) stops
    /// agtx answering them β€” the task is surfaced as `Blocked` instead. Prompts
    /// that decide nothing about safety (codex's "an update is available") stay
    /// answered either way, because leaving them up only wedges the pane.
    pub security: bool,
    /// When false the patterns are **alternatives**: any one matching is enough,
    /// which is how a dialog whose wording varies between versions is caught.
    /// When true they are a **conjunction**: all must be present, for a prompt
    /// identified by a combination of phrases rather than one distinctive string.
    pub require_all: bool,
    /// The keys that answer it, in order, sent through tmux's key-name lookup.
    ///
    /// A sequence rather than a single key because menus differ in kind: a
    /// numbered menu needs the digit *and* an Enter to confirm it, while an
    /// arrow-navigated menu whose safe option is already highlighted needs only
    /// the Enter β€” antigravity's trust prompt is the latter, and sending it a
    /// digit first would type a stray character into the composer it opens.
    pub answer: &'static [&'static str],
    pub scope: DialogScope,
}

impl AgentDialog {
    /// Whether this dialog is visible in `content`.
    pub fn matches(&self, content: &str) -> bool {
        if self.require_all {
            self.patterns.iter().all(|p| content.contains(p))
        } else {
            self.patterns.iter().any(|p| content.contains(p))
        }
    }
}

/// How a mid-session message (a phase advance into a running agent) is delivered.
///
/// The plan that introduced this sketched a fourth variant, `CombinedThenPicker`,
/// for Codex's second Enter. Bracketed paste removed the need for it: Codex's
/// `$skill` picker opens on typing, not on a paste, so there is nothing to
/// dismiss. Three variants, not four.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SendStrategy {
    /// Send the command, optionally wait on a `prompt_trigger`, then the prompt.
    Generic,
    /// Combine skill and prompt into one bracketed paste, then a single Enter.
    /// Ink-class TUIs need this: they lose a separately-sent prompt, and a typed
    /// newline submits the message half-written.
    Combined,
    /// OpenCode's command picker strips arguments when the whole string is typed
    /// at once, so the text must arrive in two pieces by design.
    OpenCodePicker,
}

/// Where and how an agent's project-scoped MCP server config is written.
///
/// Seven variants for seven agents, which looks untidy and is: the formats
/// genuinely differ (JSON vs TOML, `mcpServers` vs `mcp_servers` vs `mcp`). What
/// the enum buys is that the mess lives in one function instead of a 170-line
/// match inside `write_skills_to_worktree`, and that the names now say *why* the
/// arms differ.
///
/// The `…Merge` variants must not overwrite: their file is vendor-neutral or
/// otherwise likely to be tracked in the repo already, so clobbering it destroys
/// the user's own settings.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum McpConfigKind {
    /// `.mcp.json`. Also writes `.claude/settings.local.json`
    /// (`enableAllProjectMcpServers`, the bypass preflight, and agtx's hooks).
    ClaudeJson,
    /// `.codex/config.toml`. Also appends a trust entry for the worktree to the
    /// user's global `~/.codex/config.toml`, without which Codex prompts on open.
    CodexToml,
    /// `.gemini/settings.json`, which additionally needs `trust: true`.
    GeminiJson,
    /// `.cursor/mcp.json`.
    CursorJson,
    /// `.grok/config.toml` β€” appended if the agtx table is absent.
    GrokTomlMerge,
    /// `.agents/mcp_config.json` β€” parsed, agtx inserted, written back, so other
    /// servers and sibling top-level keys survive.
    AntigravityJsonMerge,
    /// `opencode.json`, whose key is `mcp` and whose entry shape differs.
    OpenCode,
    /// `.pi/mcp.json` β€” parsed, agtx inserted, written back, so other servers
    /// survive. pi has no MCP client of its own; the `pi-mcp-adapter` package
    /// reads this path as its highest-precedence project layer, and without the
    /// adapter installed the file is inert rather than harmful.
    PiJsonMerge,
}

/// Where and how an agent's lifecycle-hook config is written, and which event
/// vocabulary its payloads speak.
///
/// One kind per agent, like [`McpConfigKind`], because the formats differ. The
/// location does not: every variant is **project-local**, so agtx writes into
/// the worktree and never into the user's global agent config. Removing the
/// worktree removes the registration.
///
/// `hook_config: None` β€” opencode, copilot β€” keeps the pane-hash heuristic,
/// which is a supported state, not a degraded one.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum HookConfigKind {
    /// `.claude/settings.local.json`, `hooks` key. Shared with the MCP preflight
    /// keys, so the writer merges.
    ClaudeSettings,
    /// `.codex/hooks.json`, auto-discovered: `{description, hooks: {…}}` with
    /// PascalCase event keys. The `hooks` key in `.codex/config.toml` is a table,
    /// not a path, and pointing it at a file makes codex reject the whole config.
    CodexHooksJson,
    /// `.gemini/settings.json`, `hooks` key. Shared with gemini's MCP config, so
    /// the writer merges.
    GeminiSettings,
    /// `.cursor/hooks.json`, `{version, hooks: {…}}`, camelCase event names.
    CursorHooksJson,
    /// `.grok/hooks/agtx.json`. Grok scans the whole directory, so agtx owns one
    /// file in it and never merges.
    GrokHooksJson,
    /// `.agents/hooks.json`, keyed by hook *name* first and event second. The
    /// payload carries no event name, so the event is passed in argv.
    AntigravityHooksJson,
}

/// How the firing event reaches `agtx hook`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum HookEventSource {
    /// The payload names the event, so one command serves every event.
    Payload,
    /// The payload has no event field, so each event registers its own command
    /// with `--event <Name>`. Antigravity only.
    Argv,
}

/// Everything agtx knows about one coding agent.
#[derive(Debug, Clone, Copy)]
pub struct AgentSpec {
    // ── identity ─────────────────────────────────────────────────────────
    pub name: &'static str,
    /// Executable name, which is not always the agent's name: `cursor` ships
    /// `agent`, `antigravity` ships `agy`.
    pub binary: &'static str,
    pub description: &'static str,
    pub co_author: &'static str,
    /// Environment variables that carry a provider API key for this agent, most
    /// preferred first.
    ///
    /// This is the **headless** credential: the auth mode that works with no
    /// browser and no keychain, which is the only kind a CI runner can use. It is
    /// not how agtx authenticates anything β€” agtx never reads these β€” it is the
    /// per-agent fact that the smoke harness and the CI workflow both need, kept
    /// here so there is one copy rather than three. The trust stores went the
    /// other way and ended up duplicated in `trust.rs`, `agent_smoke.py` and
    /// `benchmark.py`; this is that lesson applied.
    ///
    /// Empty means *no verified headless credential*, which is a real answer:
    /// such an agent cannot run unattended in CI at all. It must not be confused
    /// with "not looked into yet" β€” see each entry's comment.
    pub api_key_env: &'static [&'static str],

    // ── launching ────────────────────────────────────────────────────────
    /// Environment assignments prefixed to the interactive launch command.
    /// Not applied to the headless invocation, which never touches the workspace.
    pub env: &'static [(&'static str, &'static str)],
    /// Flags that make the agent run unattended (permission bypass, sandbox mode).
    pub base_args: &'static [&'static str],
    pub prompt_form: PromptForm,
    /// Whether [`prompt_form`](Self::prompt_form) has been checked against the
    /// real binary and may be used to hand the agent its opening message at
    /// launch.
    ///
    /// Deliberately conservative. Getting this wrong swallows the task text
    /// silently rather than failing loudly: OpenCode's `-p`, like Copilot's used
    /// to be, is print mode β€” it answers once and exits, killing the window.
    /// Flip this only after verifying against the installed CLI.
    pub launch_prompt_verified: bool,
    pub resume: ResumeArgs,
    /// Flags for the one-shot print invocation used to generate PR descriptions.
    pub headless_args: &'static [&'static str],

    // ── skills & commands ────────────────────────────────────────────────
    /// `(base_dir, namespace_subdir)` relative to the worktree, or `None` for an
    /// agent with no native skill discovery. The namespace is empty for layouts
    /// that carry the prefix in the file or directory name instead.
    pub skill_dir: Option<(&'static str, &'static str)>,
    pub skill_layout: SkillLayout,
    /// Directory scanned for the agent's *pre-existing* skills. Normally the
    /// same as `skill_dir`'s base; OpenCode is the exception.
    pub skill_scan_dir: Option<&'static str>,
    pub command_syntax: CommandSyntax,

    // ── integration ──────────────────────────────────────────────────────
    /// How this agent's project-scoped MCP config is written, or `None` for an
    /// agent agtx does not wire up to the MCP server.
    pub mcp_config: Option<McpConfigKind>,
    /// How this agent's lifecycle-hook config is written, or `None` for an agent
    /// that reports nothing and falls back to the pane-hash heuristic.
    pub hook_config: Option<HookConfigKind>,
    /// Where `agtx hook` learns which event fired. Ignored when `hook_config` is
    /// `None`.
    pub hook_event_source: HookEventSource,

    // ── process / liveness ───────────────────────────────────────────────
    /// Process names this agent may appear as in `pane_current_command`.
    ///
    /// Node/Ink agents often report `node` or `bash` instead of their own name,
    /// which is what `active_indicators` is for.
    pub process_names: &'static [&'static str],
    /// Strings in pane content that mean this agent's TUI is up and ready.
    ///
    /// Needed for agents that run inside bash/node and so never show their own
    /// name in `pane_current_command`.
    pub active_indicators: &'static [&'static str],
    /// Readiness needles that count **only in this agent's own pane**.
    ///
    /// [`active_indicators`](Self::active_indicators) is also matched against
    /// panes whose agent is unknown, flattened across every spec, so a needle
    /// that occurs in ordinary output would report an exited agent as still
    /// running. pi has no startup banner β€” the one unconditional part of its
    /// footer is the context display (`0.0%/1.0M`), giving `%/`, which also
    /// occurs in text like `Coverage: 85%/90%`. Such a needle goes here: used
    /// when agtx knows the pane runs this agent, ignored otherwise.
    pub scoped_indicators: &'static [&'static str],
    /// Command that makes the agent exit cleanly, or `None` when Ctrl+C is the
    /// only way out.
    pub exit_command: Option<&'static str>,

    // ── display ──────────────────────────────────────────────────────────
    /// Foreground colour of the agent label on a task card.
    pub label_fg: (u8, u8, u8),
    /// Background colour, for the agents whose branding is a filled chip.
    pub label_bg: Option<(u8, u8, u8)>,

    // ── sending ──────────────────────────────────────────────────────────
    pub send_strategy: SendStrategy,
    /// Command that clears the agent's context, for `clear_context_on_advance`.
    /// `None` where no such command is known β€” the phase advance then just sends
    /// normally. Tracked in issue #46.
    pub clear_context_command: Option<&'static str>,

    // ── dialogs ──────────────────────────────────────────────────────────
    /// Interactive prompts this agent shows that agtx answers on the user's
    /// behalf. Missing one is silent and total: the task's prompt is delivered
    /// but never read, because the agent never reaches its composer.
    pub dialogs: &'static [AgentDialog],
}

/// Every agent agtx ships with.
///
/// Ordered by preference β€” [`crate::agent::known_agents`] and the agent pickers
/// present them in this order.
pub const AGENT_SPECS: &[AgentSpec] = &[
    AgentSpec {
        name: "claude",
        binary: "claude",
        description: "Anthropic's Claude Code CLI",
        co_author: "Claude <[email protected]>",
        // `claude --help`: API-key users authenticate "strictly
        // ANTHROPIC_API_KEY or apiKeyHelper". Verified 2.1.246.
        api_key_env: &["ANTHROPIC_API_KEY"],
        env: &[],
        base_args: &["--dangerously-skip-permissions"],
        prompt_form: PromptForm::Argv,
        // Verified against claude 2.1.241: `claude [prompt]` starts an
        // interactive session with the prompt submitted, and a leading
        // `/agtx:plan …` still expands as a slash command.
        launch_prompt_verified: true,
        resume: ResumeArgs::Append(&["--continue"]),
        headless_args: &["--print"],
        skill_dir: Some((".claude/commands", "agtx")),
        skill_layout: SkillLayout::CommandFile,
        skill_scan_dir: Some(".claude/commands"),
        command_syntax: CommandSyntax::Colon,
        mcp_config: Some(McpConfigKind::ClaudeJson),
        // Verified against claude 2.1.247.
        hook_config: Some(HookConfigKind::ClaudeSettings),
        hook_event_source: HookEventSource::Payload,
        process_names: &["claude"],
        active_indicators: &["Claude Code"],
        scoped_indicators: &[],
        exit_command: Some("/exit"),
        label_fg: (227, 148, 62), // orange
        label_bg: None,
        send_strategy: SendStrategy::Generic,
        clear_context_command: Some("/clear"),
        dialogs: &[
            // Workspace trust, shown before the bypass warning in a directory
            // with no trusted ancestor. Recorded as
            // `projects."<dir>".hasTrustDialogAccepted` in ~/.claude.json.
            //
            // Trust is **inherited from a parent directory**. Verified against
            // claude 2.1.246: a fresh `git worktree add` under an already-trusted
            // project opened straight at the composer β€” no dialog, and no new
            // `projects` entry for the worktree path β€” while a fresh `git init`
            // repo with no trusted ancestor showed the dialog under the same
            // launch flags and the same timing. So with the default
            // `worktree_dir` (`.agtx/worktrees`, inside the project root) this
            // does *not* fire once the user has trusted the project once.
            //
            // It still fires wherever a worktree has no trusted ancestor: a
            // `worktree_dir` pointing outside the project, the smoke runner's
            // temp repos, and the swebench containers (~/.claude.json is copied
            // in, but the repo lands at a different path). Treat it as a
            // container/edge-case handler, not the common path.
            //
            // Contrast antigravity, where trust is per-directory and is *not*
            // inherited (also verified). Do not generalise one agent's rule to
            // another: they differ, and the difference is measured.
            AgentDialog {
                patterns: &["Yes, I trust this folder"],
                security: true,
                require_all: false,
                answer: &["1", "Enter"],
                scope: DialogScope::Launch,
            },
            // `--dangerously-skip-permissions` acceptance, shown right after the
            // trust dialog. Not covered by `hasTrustDialogAccepted` β€” verified
            // against claude 2.1.246 by pre-seeding that record for the exact
            // directory: the trust dialog was skipped and this one still
            // rendered. So copying ~/.claude.json (as the swebench harness does)
            // cannot suppress it.
            //
            // What does suppress it is the `skipDangerousModePermissionPrompt`
            // *settings* key, which `write_skills_to_worktree` now writes into
            // each worktree's `.claude/settings.local.json`. This arm stays as
            // the backstop for wherever that file does not reach the agent.
            //
            // Note the option order is inverted relative to the trust dialog:
            // `1. No, exit` / `2. Yes, I accept`. A bare Enter on the default
            // quits the agent β€” which is exactly what happened when a stray
            // Enter reached it during testing. Hence `2` then `Enter`, never a
            // lone Enter.
            AgentDialog {
                // Alternatives: the wording has varied across Claude versions.
                patterns: &["Yes, I accept", "I accept the risk"],
                security: true,
                require_all: false,
                answer: &["2", "Enter"],
                scope: DialogScope::Launch,
            },
        ],
    },
    AgentSpec {
        name: "codex",
        binary: "codex",
        description: "OpenAI's Codex CLI",
        co_author: "Codex <[email protected]>",
        // Both names are present in the 0.144.5 binary; OPENAI_API_KEY is the
        // documented one. Note codex otherwise authenticates from
        // ~/.codex/auth.json, which a runner has no way to produce β€” the env var
        // is the only headless path.
        api_key_env: &["OPENAI_API_KEY", "CODEX_API_KEY"],
        env: &[],
        base_args: &["--sandbox", "workspace-write"],
        prompt_form: PromptForm::Argv,
        // Verified against codex-cli 0.144.5: `codex --sandbox workspace-write
        // '$agtx-plan <id>\n\n<task>'` starts interactively with the prompt
        // submitted, and the `$skill` mention resolves and runs.
        launch_prompt_verified: true,
        // `codex resume` is its own subcommand and rejects the launch flags.
        resume: ResumeArgs::Replace(&["resume", "--last"]),
        headless_args: &["exec", "--sandbox", "workspace-write"],
        skill_dir: Some((".codex/skills", "")),
        skill_layout: SkillLayout::SkillDir,
        skill_scan_dir: Some(".codex/skills"),
        command_syntax: CommandSyntax::Dollar,
        mcp_config: Some(McpConfigKind::CodexToml),
        // Off: codex gates project hooks behind a startup trust review whose only
        // enabling answers ("Trust all and continue", or
        // `--dangerously-bypass-hook-trust`) trust *every* hook the repo ships,
        // not just agtx's. That is the user's decision. The vocabulary is mapped
        // and the writer exists, so enabling it is one field once codex offers
        // per-hook trust. codex-cli 0.144.5.
        hook_config: None,
        hook_event_source: HookEventSource::Payload,
        process_names: &["codex"],
        active_indicators: &["OpenAI Codex"],
        scoped_indicators: &[],
        exit_command: None,
        label_fg: (255, 255, 255), // white on black
        label_bg: Some((20, 20, 20)),
        send_strategy: SendStrategy::Combined,
        clear_context_command: None,
        dialogs: &[
            // Directory trust, per directory, so it fires on the first launch of
            // every codex task. Worded differently from both Claude's ("Yes, I
            // trust this folder") and Gemini's ("files in this folder"), so
            // neither of their patterns catches it. Verified against
            // codex-cli 0.144.5.
            AgentDialog {
                patterns: &["Do you trust the contents of this directory?"],
                security: true,
                require_all: false,
                answer: &["1", "Enter"],
                scope: DialogScope::Launch,
            },
            // Update prompt, shown whenever a newer codex is published. "Skip"
            // rather than "Update now": agtx must never upgrade a user's agent
            // binary behind their back, but leaving the pane blocked is worse.
            AgentDialog {
                patterns: &["Update now (runs"],
                security: false,
                require_all: false,
                answer: &["2", "Enter"],
                scope: DialogScope::Launch,
            },
            // Hook review, shown at launch when the project ships a
            // `.codex/hooks.json` codex has not seen. Options are `1. Review
            // hooks` / `2. Trust all and continue` / `3. Continue without
            // trusting`.
            //
            // `3` and `security: false`, for the same reason as the update prompt
            // above: declining grants nothing and decides nothing about safety,
            // where `2` would trust every hook the repo ships. Fires whether or
            // not agtx writes hooks for codex β€” the project's own file is enough.
            // codex-cli 0.144.5.
            AgentDialog {
                patterns: &["Hooks need review"],
                security: false,
                require_all: false,
                answer: &["3", "Enter"],
                scope: DialogScope::Launch,
            },
            // MCP tool approval, shown mid-session the first time the agent calls
            // an agtx tool β€” not at launch, so it is matched only against a pane
            // known to be running codex.
            AgentDialog {
                // A conjunction: none of these three is distinctive alone.
                patterns: &["Allow the", "MCP server to run tool", "Always allow"],
                security: false,
                require_all: true,
                answer: &["3", "Enter"],
                scope: DialogScope::Session,
            },
        ],
    },
    AgentSpec {
        name: "copilot",
        binary: "copilot",
        description: "GitHub Copilot CLI",
        co_author: "GitHub Copilot <[email protected]>",
        // Unverified: copilot is not installed on any machine this has been
        // measured on. Empty here means "unknown", not "none" β€” the only entry
        // where those differ, and the reason not to guess at a plausible
        // GH_TOKEN. Fill it in from the real binary, not from documentation.
        api_key_env: &[],
        env: &[],
        base_args: &["--allow-all-tools"],
        // `-i` keeps the session interactive; `-p` is print mode and exits on
        // completion, which killed every copilot task until it was fixed.
        prompt_form: PromptForm::Flag("-i"),
        launch_prompt_verified: false,
        resume: ResumeArgs::Append(&["--continue"]),
        headless_args: &["-p"],
        skill_dir: Some((".github/agents", "agtx")),
        skill_layout: SkillLayout::CommandFile,
        skill_scan_dir: Some(".github/agents"),
        // Copilot has no interactive slash-command invocation, so skills reach
        // it as a file-path reference in the prompt instead. Its skills are
        // still discovered and listed by the `/` picker.
        command_syntax: CommandSyntax::None,
        // Copilot is not wired to the MCP server.
        mcp_config: None,
        // Unknown, not absent β€” copilot has never been measured. Same rule as
        // `api_key_env` above: fill this in from the real binary, not from docs.
        hook_config: None,
        hook_event_source: HookEventSource::Payload,
        process_names: &["copilot"],
        active_indicators: &[],
        scoped_indicators: &[],
        exit_command: Some("/exit"),
        label_fg: (255, 255, 255), // default white
        label_bg: None,
        send_strategy: SendStrategy::Generic,
        clear_context_command: None,
        dialogs: &[],
    },
    AgentSpec {
        name: "gemini",
        binary: "gemini",
        description: "Google Gemini CLI",
        co_author: "Gemini <[email protected]>",
        // Both documented in the gemini-cli README, 0.46.0.
        api_key_env: &["GEMINI_API_KEY", "GOOGLE_API_KEY"],
        // Kept, but it does **not** suppress the folder-trust dialog β€” verified
        // against gemini 0.46.0: the dialog rendered with this set. Gemini's real
        // trust store is `~/.gemini/trustedFolders.json`, a map of
        // path -> "TRUST_FOLDER" with **lowercased** paths and ancestor
        // semantics (`/users/fynn` covers everything beneath), which is why gemini
        // inherits a trusted project root and why its dialog offers "Trust parent
        // folder". The variable is kept because it is untested for the *other*
        // things it may gate, but it is not what grants the inheritance.
        env: &[("GEMINI_TRUST_WORKSPACE", "true")],
        base_args: &["--approval-mode", "yolo"],
        prompt_form: PromptForm::Flag("-i"),
        // Verified against gemini 0.46.0: `gemini … -i '<prompt>'` delivers the
        // prompt and continues interactively. It also survives the process restart
        // that answering the folder-trust dialog triggers β€” the prompt still
        // reached the model afterwards.
        launch_prompt_verified: true,
        resume: ResumeArgs::Append(&["--resume"]),
        headless_args: &["-p"],
        skill_dir: Some((".gemini/commands", "agtx")),
        skill_layout: SkillLayout::GeminiToml,
        skill_scan_dir: Some(".gemini/commands"),
        command_syntax: CommandSyntax::Colon,
        mcp_config: Some(McpConfigKind::GeminiJson),
        hook_config: Some(HookConfigKind::GeminiSettings),
        hook_event_source: HookEventSource::Payload,
        process_names: &["gemini"],
        active_indicators: &["Type your message"],
        scoped_indicators: &[],
        exit_command: Some("/quit"),
        label_fg: (234, 130, 180), // pink
        label_bg: None,
        send_strategy: SendStrategy::Combined,
        clear_context_command: None,
        dialogs: &[
            // Answering this restarts the process.
            AgentDialog {
                patterns: &["Do you trust the files in this folder?"],
                security: true,
                require_all: false,
                answer: &["1", "Enter"],
                scope: DialogScope::Launch,
            },
        ],
    },
    AgentSpec {
        name: "opencode",
        binary: "opencode",
        description: "AI-powered coding assistant",
        co_author: "OpenCode <[email protected]>",
        // Multi-provider: the variable that matters is whichever provider the
        // user's opencode config selects, so all four it knows about are listed.
        // Present in the 1.18.20 binary.
        api_key_env: &[
            "ANTHROPIC_API_KEY",
            "OPENAI_API_KEY",
            "GEMINI_API_KEY",
            "GOOGLE_GENERATIVE_AI_API_KEY",
        ],
        env: &[],
        base_args: &[],
        // `--prompt`, not `-p`: opencode has no `-p` short form at all, so the
        // previous value would have failed the moment it was used. Verified
        // against opencode 1.18.20: `opencode --prompt '<prompt>'` submits the
        // prompt as a user message and stays interactive.
        prompt_form: PromptForm::Flag("--prompt"),
        launch_prompt_verified: true,
        resume: ResumeArgs::Append(&["--continue"]),
        headless_args: &[],
        skill_dir: Some((".opencode/command", "")),
        skill_layout: SkillLayout::OpenCodeFlat,
        // Deliberately not `.opencode/command`: agtx deploys into the worktree
        // tree, but OpenCode's own project commands live under `.config/`.
        skill_scan_dir: Some(".config/opencode/command"),
        command_syntax: CommandSyntax::Hyphen,
        mcp_config: Some(McpConfigKind::OpenCode),
        // OpenCode's lifecycle callbacks are a TypeScript plugin API
        // (`.opencode/plugin/*.ts`), not shell commands in a config file β€” there
        // is no `hooks` key to write. opencode 1.18.20.
        hook_config: None,
        hook_event_source: HookEventSource::Payload,
        process_names: &["opencode"],
        active_indicators: &["Ask anything"],
        scoped_indicators: &[],
        exit_command: Some("/exit"),
        label_fg: (255, 255, 255), // white on grey
        label_bg: Some((80, 80, 80)),
        send_strategy: SendStrategy::OpenCodePicker,
        clear_context_command: None,
        dialogs: &[],
    },
    AgentSpec {
        name: "cursor",
        binary: "agent",
        description: "Cursor Agent CLI",
        co_author: "Cursor Agent <[email protected]>",
        // `agent --help`: "--api-key <key> ... (can also use CURSOR_API_KEY env
        // var)". Verified 2026.08.11.
        api_key_env: &["CURSOR_API_KEY"],
        env: &[],
        // `--trust` is "trust the current workspace without prompting". It is not
        // an escalation on top of `--yolo`, which already auto-runs every tool β€”
        // refusing the narrower flag while passing the broader one would be
        // incoherent. Verified against cursor-agent 2026.08.11: no
        // `Workspace Trust Required` dialog, prompt delivered, session usable.
        base_args: &["--yolo", "--trust"],
        prompt_form: PromptForm::Argv,
        // Verified against cursor-agent 2026.08.11 together with `--trust`:
        // `agent --yolo --trust '<prompt>'` submitted the prompt and answered it.
        launch_prompt_verified: true,
        resume: ResumeArgs::Append(&["--continue"]),
        headless_args: &["--print", "--yolo"],
        skill_dir: Some((".cursor/skills", "")),
        skill_layout: SkillLayout::SkillDir,
        skill_scan_dir: Some(".cursor/skills"),
        command_syntax: CommandSyntax::Hyphen,
        mcp_config: Some(McpConfigKind::CursorJson),
        hook_config: Some(HookConfigKind::CursorHooksJson),
        hook_event_source: HookEventSource::Payload,
        process_names: &["agent"],
        active_indicators: &["Cursor Agent"],
        scoped_indicators: &[],
        exit_command: None,
        label_fg: (255, 255, 255), // default white
        label_bg: None,
        send_strategy: SendStrategy::Combined,
        clear_context_command: None,
        dialogs: &[
            // Workspace trust, per directory, so it fires on the first launch of
            // every cursor task. Its question line is *identical* to codex's
            // ("Do you trust the contents of this directory?"), which is why it
            // is matched on the heading instead β€” and why per-agent scoping is
            // what makes declaring it safe.
            //
            // Answered with the access key the dialog itself advertises ("or
            // press the key shown") rather than an Enter on the highlighted row:
            // explicit, and it survives an option being added above it. Verified
            // against cursor-agent 2026.08.11 β€” "a" trusts the workspace without
            // restarting the process, and a paste lands immediately after.
            AgentDialog {
                patterns: &["Workspace Trust Required"],
                security: true,
                require_all: false,
                answer: &["a"],
                scope: DialogScope::Launch,
            },
        ],
    },
    AgentSpec {
        name: "grok",
        binary: "grok",
        description: "xAI's Grok Build CLI",
        co_author: "Grok <[email protected]>",
        // The grok README names this one for exactly this purpose: "For CI or
        // headless environments, use an API key from console.x.ai:
        // export XAI_API_KEY=...". The clearest headless story of any agent here.
        api_key_env: &["XAI_API_KEY"],
        env: &[],
        // `--trust` also ungates the repo-local `.grok/config.toml` MCP server
        // and suppresses the directory-trust dialog.
        base_args: &["--yolo", "--trust"],
        prompt_form: PromptForm::Argv,
        // Verified against Grok 4.6: `grok --yolo --trust '/agtx-plan <id>\n\n<task>'`
        // delivered the prompt at launch, the skill ran, and `--trust` meant no
        // dialog appeared at all.
        launch_prompt_verified: true,
        resume: ResumeArgs::Append(&["--continue"]),
        headless_args: &["-p"],
        skill_dir: Some((".grok/skills", "")),
        skill_layout: SkillLayout::SkillDir,
        skill_scan_dir: Some(".grok/skills"),
        command_syntax: CommandSyntax::Hyphen,
        mcp_config: Some(McpConfigKind::GrokTomlMerge),
        hook_config: Some(HookConfigKind::GrokHooksJson),
        hook_event_source: HookEventSource::Payload,
        process_names: &["grok"],
        active_indicators: &["Grok Build", "Shift+Tab:mode"],
        scoped_indicators: &[],
        exit_command: Some("/quit"),
        label_fg: (20, 20, 20), // black on white
        label_bg: Some((255, 255, 255)),
        send_strategy: SendStrategy::Generic,
        clear_context_command: None,
        dialogs: &[],
    },
    AgentSpec {
        name: "antigravity",
        binary: "agy",
        description: "Google's Antigravity CLI",
        co_author: "Antigravity <[email protected]>",
        // Empty on purpose. `GEMINI_API_KEY` / `GOOGLE_API_KEY` appear as
        // strings in the 1.1.21 binary, but `agy --help` documents no auth flag
        // at all and the CLI signs in through a browser with the token cached in
        // the OS keychain β€” which is why the benchmark has never been able to
        // carry antigravity into a container. Strings in a binary are not a
        // supported auth path; treat this as "no verified headless credential"
        // until someone authenticates a fresh `agy` with the variable alone.
        api_key_env: &[],
        env: &[],
        // Two orthogonal controls: the flag governs shell/MCP/URL approvals,
        // `--mode` governs the file-edit diff review. Both are needed to run
        // unattended.
        base_args: &["--dangerously-skip-permissions", "--mode", "accept-edits"],
        prompt_form: PromptForm::Flag("-i"),
        // The ordering question is settled. Measured against agy 1.1.21 in an
        // untrusted repo: `agy … -i '<prompt>'` launched
        // with the project-trust dialog up, and once the dialog was answered the
        // prompt was submitted and answered normally. An argv prompt is *queued*
        // behind a dialog, not handed to the menu β€” the dialog delays it, it does
        // not eat it. Same result for claude, cursor and gemini.
        launch_prompt_verified: true,
        resume: ResumeArgs::Append(&["--continue"]),
        headless_args: &["-p"],
        // Antigravity reads workspace skills from the vendor-neutral `.agents/`
        // tree, not from an agent-specific dotdir.
        skill_dir: Some((".agents/skills", "")),
        skill_layout: SkillLayout::SkillDir,
        skill_scan_dir: Some(".agents/skills"),
        command_syntax: CommandSyntax::Hyphen,
        mcp_config: Some(McpConfigKind::AntigravityJsonMerge),
        // Its payload is protojson camelCase (`conversationId`, `stepIdx`) with
        // no event key, so each event registers its own `--event`. agy 1.1.21.
        hook_config: Some(HookConfigKind::AntigravityHooksJson),
        hook_event_source: HookEventSource::Argv,
        process_names: &["agy"],
        // Shown only once the session is interactive: the trust dialog's own
        // footer reads "↑/↓ Navigate Β· enter Confirm" instead, so this cannot
        // fire while the pane is still blocked. Without it antigravity had no
        // readiness signal at all β€” `pane_current_command` reports `bash` for its
        // npm wrapper, and the content-stabilisation fallback needs three pane
        // changes where its splash produces two.
        active_indicators: &["? for shortcuts"],
        scoped_indicators: &[],
        exit_command: Some("/exit"),
        label_fg: (120, 190, 255), // light blue
        label_bg: None,
        send_strategy: SendStrategy::Combined,
        clear_context_command: None,
        dialogs: &[
            // Project trust, shown on the first launch in any directory β€” which
            // is every task, because every task gets a new worktree. It was
            // deliberately left unanswered while dialogs were matched flat, when
            // answering it meant Claude's identical "Yes, I trust this folder"
            // pattern firing in any pane. Per-agent scoping removed that risk,
            // and leaving it stood the session up blocked: the paste went into a
            // menu that ignores text and agtx's follow-up Enter confirmed the
            // dialog, so every antigravity task reached its composer empty.
            //
            // Answered with a bare Enter: this menu is arrow-navigated with
            // "Yes, I trust this folder" preselected, so a digit would be typed
            // into the composer the Enter then opens. Verified against
            // antigravity 1.1.20 β€” the process does not restart, and a paste
            // lands immediately afterwards.
            AgentDialog {
                // Its own wording, not Claude's. Codex's differs by one word
                // ("directory"), which is why each is matched separately.
                patterns: &["Do you trust the contents of this project?"],
                security: true,
                require_all: false,
                answer: &["Enter"],
                scope: DialogScope::Launch,
            },
        ],
    },
    AgentSpec {
        name: "pi",
        binary: "pi",
        description: "Earendil's pi coding agent",
        co_author: "Pi <[email protected]>",
        // pi is provider-agnostic: the variable that matters is the one for the
        // provider `settings.json` selects, and its shipped default is google.
        // Listed default-first, then the two providers whose keys a runner is
        // most likely to already hold. `pi auth` otherwise reads
        // ~/.pi/agent/auth.json, which a runner has no way to produce.
        // Verified against pi 0.84.3 (docs/providers.md).
        api_key_env: &["GEMINI_API_KEY", "ANTHROPIC_API_KEY", "OPENAI_API_KEY"],
        env: &[],
        // pi ships no permission system, so there is no --yolo equivalent and
        // none is needed. What does block an unattended start is the project
        // trust prompt, which fires in any directory carrying project-local
        // settings, skills or extensions β€” i.e. every worktree agtx writes a
        // skill into. `--approve` answers it for this run only and, unlike the
        // codex arm, writes nothing to the user's global config.
        base_args: &["--approve"],
        prompt_form: PromptForm::Argv,
        // Verified against pi 0.84.3 in tmux: `pi --approve '<prompt>'` starts
        // interactively with the prompt submitted, and a leading
        // `/skill:agtx-plan` still resolves as a skill command.
        launch_prompt_verified: true,
        resume: ResumeArgs::Append(&["--continue"]),
        // `--no-approve` for the headless lane: a one-shot PR description has no
        // need of the repo's own skills or extensions, so it declines them.
        headless_args: &["--no-approve", "-p"],
        // Project skills live in `.pi/skills/<name>/SKILL.md`, loaded only once
        // the project is trusted β€” which is what `--approve` above buys.
        skill_dir: Some((".pi/skills", "")),
        skill_layout: SkillLayout::SkillDir,
        skill_scan_dir: Some(".pi/skills"),
        command_syntax: CommandSyntax::PiSkill,
        mcp_config: Some(McpConfigKind::PiJsonMerge),
        // pi has no lifecycle-hook mechanism, so phase status falls back to the
        // pane-hash heuristic, as it does for opencode and copilot.
        hook_config: None,
        hook_event_source: HookEventSource::Payload,
        // macOS fixes `p_comm` at exec, so the pane reports `node` however pi
        // sets `process.title` β€” `scoped_indicators` is what actually detects it
        // there. Kept because Linux does pick the rewrite up. Note `node` must
        // NOT be added: it is every Ink agent's pane name and would make any
        // node process read as a live agent.
        process_names: &["pi"],
        // Nothing distinctive enough to match in any pane: pi's last lines are
        // editor borders, the cwd and a stats line. See `scoped_indicators`.
        active_indicators: &[],
        // The context display is the only unconditional part of the footer:
        // `0.0%/1.0M (auto)` on a fresh session, `1.0%/1.0M` after a turn.
        // Reads `?/` for a moment after a compaction, until the next response.
        // Verified against pi 0.84.3.
        scoped_indicators: &["%/"],
        exit_command: Some("/quit"),
        label_fg: (120, 220, 200), // teal
        label_bg: None,
        // Ink-class composer: a bracketed paste lands as literal text and a
        // single Enter submits the whole multi-line message. Verified against pi
        // 0.84.3 β€” a combined text+Enter `send-keys` leaves it unsent instead.
        send_strategy: SendStrategy::Combined,
        // `/new` starts a fresh session with no confirmation step; verified
        // against pi 0.84.3 by watching the context display return to 0.0%.
        clear_context_command: Some("/new"),
        // None: `--approve` suppresses the only launch dialog pi has, and it is
        // the same flag whose absence would leave the worktree's skills
        // unloaded β€” so a pane that reaches the dialog is already misconfigured.
        dialogs: &[],
    },
    // TODO: investigate CLI usage before enabling
    // aider  β€” "AI pair programming in your terminal", Aider <[email protected]>
    // cline  β€” "AI coding assistant for VS Code",      Cline <[email protected]>
];

/// Look up an agent's spec by name. `None` for agents agtx has not been taught,
/// which fall back to generic behaviour throughout.
pub fn spec(name: &str) -> Option<&'static AgentSpec> {
    AGENT_SPECS.iter().find(|s| s.name == name)
}

/// Build a shell command for `spec`: env prefix, binary, the given args, then
/// the prompt in the agent's own form.
///
/// The prompt is single-quoted with the POSIX `'"'"'` idiom because the result
/// is wrapped in `sh -c '…'` by `create_window`; a bare quote would close that
/// outer quote and let the shell mangle the text.
/// Largest prompt agtx will hand to a process in argv.
///
/// `ARG_MAX` is ~1 MB on macOS and Linux and task descriptions are far below
/// that, but the limit should be explicit rather than incidental: past this the
/// caller falls back to the mid-session lane, which has no such ceiling. Counted
/// in bytes, not chars, because that is what `execve` counts.
pub const MAX_LAUNCH_PROMPT_BYTES: usize = 128 * 1024;

/// Strip characters that cannot survive the trip through argv intact.
///
/// The command string is handed to tmux, which runs it through a shell, so the
/// prompt is embedded in a single-quoted word. Single quotes are escaped by
/// [`compose_command`]; this handles the rest:
///
/// - **NUL** would truncate the argument at the C-string boundary, silently
///   discarding the rest of the task.
/// - **`\r`** renders as a carriage return, moving the agent's cursor to column
///   zero and corrupting the echoed prompt. It is almost always a paste artifact
///   from a CRLF source.
/// - **Other control characters** (ESC in particular) let pasted text move the
///   cursor or set colours in the agent's TUI.
///
/// `\n` and `\t` are kept: they are ordinary structure in a task description,
/// and inside a single-quoted argv word they are just bytes.
pub fn normalize_prompt(prompt: &str) -> String {
    prompt
        .chars()
        .filter(|c| *c == '\n' || *c == '\t' || !c.is_control())
        .collect()
}

/// Whether `text` can be delivered as a launch argument for this injection mode.
///
/// False sends the caller down the mid-session lane instead β€” either because the
/// agent's launch form is unverified, or because the text is too large for argv.
pub fn can_launch_with_prompt(injection: crate::agent::PromptInjection, text: &str) -> bool {
    !text.is_empty()
        && !matches!(injection, crate::agent::PromptInjection::Unknown)
        && text.len() <= MAX_LAUNCH_PROMPT_BYTES
}

pub fn compose_command(spec: &AgentSpec, args: &[&str], prompt: Option<&str>) -> String {
    let mut out = String::new();
    for (key, value) in spec.env {
        out.push_str(key);
        out.push('=');
        out.push_str(value);
        out.push(' ');
    }
    out.push_str(spec.binary);
    for arg in args {
        out.push(' ');
        out.push_str(arg);
    }
    if let Some(prompt) = prompt.filter(|p| !p.is_empty()) {
        if let PromptForm::Flag(flag) = spec.prompt_form {
            out.push(' ');
            out.push_str(flag);
        }
        // POSIX single-quote escaping: close, emit a literal quote, reopen. The
        // whole command is itself wrapped in `sh -c '…'` by create_window, so a
        // bare quote here would end that outer word and let the shell interpret
        // the rest of the task as code.
        let prompt = normalize_prompt(prompt);
        out.push_str(&format!(" '{}'", prompt.replace('\'', "'\"'\"'")));
    }
    out
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn every_known_agent_has_exactly_one_spec() {
        let names: Vec<&str> = AGENT_SPECS.iter().map(|s| s.name).collect();
        let mut sorted = names.clone();
        sorted.sort_unstable();
        sorted.dedup();
        assert_eq!(sorted.len(), names.len(), "duplicate agent name in table");

        let known: Vec<String> = crate::agent::known_agents()
            .into_iter()
            .map(|a| a.name)
            .collect();
        assert_eq!(
            known, names,
            "known_agents() must be derived from the table"
        );
    }

    #[test]
    fn spec_lookup_is_exhaustive_and_exclusive() {
        for entry in AGENT_SPECS {
            assert_eq!(spec(entry.name).map(|s| s.name), Some(entry.name));
        }
        assert!(spec("mistral").is_none());
        assert!(spec("").is_none());
    }

    #[test]
    fn skill_dirs_stay_inside_the_worktree() {
        for entry in AGENT_SPECS {
            for dir in entry
                .skill_dir
                .map(|(b, _)| b)
                .into_iter()
                .chain(entry.skill_scan_dir)
            {
                assert!(
                    !dir.starts_with('/'),
                    "{}: {dir} must be relative",
                    entry.name
                );
                assert!(
                    !dir.contains(".."),
                    "{}: {dir} must stay in-worktree",
                    entry.name
                );
            }
        }
    }

    #[test]
    fn a_verified_launch_prompt_is_never_a_print_flag() {
        // `-p` is print mode for every agent that has it: it answers once and
        // exits, killing the task window. Marking such an agent verified is the
        // bug this guard exists for.
        for entry in AGENT_SPECS.iter().filter(|s| s.launch_prompt_verified) {
            assert_ne!(
                entry.prompt_form,
                PromptForm::Flag("-p"),
                "{} cannot deliver its prompt at launch through print mode",
                entry.name
            );
        }
    }
}