rho-coding-agent 3.13.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
use std::sync::Arc;

use pretty_assertions::assert_eq;

use super::{
    super::acp_background, antigravity_reach, claude_reach, listed, served_capabilities, Reach,
    SurfaceSupport, CLAUDE_MCP_DESCRIPTION_LIMIT, SERVED,
};
use crate::{
    agent::{AgentCapabilities, AntigravityTool, ToolCapability},
    app::{
        peer_sessions::PeerInbox,
        pull_requests::{PullRequests, ScriptedForge},
        session_runtime::QuestionSupport,
        subagent_pool::SubagentPool,
        workflow_cli::workflow_tool_service,
    },
    browser::Browsers,
    config::Config,
    diagnostics::RuntimeDiagnostics,
    tools::{
        sdk_registry::{AppToolSet, DelegationConfig, IdleDelivery, ToolCaller, ToolSetOptions},
        ui::SurfaceHost,
        workflow_tracker::WorkflowRunTracker,
    },
};

/// Every capability rho may serve an agent.
fn every_served() -> AgentCapabilities {
    AgentCapabilities::new(
        SERVED
            .into_iter()
            .map(|(capability, _)| capability)
            .collect(),
    )
}

/// The reach of a Claude definition with `tools`.
fn claude(tools: &[&str]) -> Vec<Reach> {
    let tools: Vec<String> = tools.iter().map(|tool| (*tool).to_owned()).collect();
    claude_reach(&tools)
}

// Covers: a definition's `tools:` bound what rho serves its agent: a bare
// `Bash`, or agy's `run_command`, brings the tools that run commands or
// start agents and sessions, a bare `WebFetch`, or agy's `search_web`, the
// one that reads stored web content, and both together the web fetch that
// also reads GitHub signed in; a scoped `Bash(git *)`, or agy's file tools
// alone, bring none of them; clients that show no questions get no
// questionnaire, and clients that draw no surfaces no `ui`; the rest are
// served either way.
// Owner: daemon sessions on an external runtime (served tools' grant).
#[test]
fn a_definitions_tools_bound_what_its_agent_is_served() {
    use AntigravityTool::{EditFile, ReadFile, RunCommand, SearchWeb};
    use ToolCapability::*;

    let available = every_served();
    let always = [Questionnaire, Ui, Rho, Skill, PullRequests];
    let commands = [Process, Agent, Agents, Sessions, Workflow, Browser];
    let shown = (QuestionSupport::Available, SurfaceSupport::Available);
    let cases: [(&str, Vec<Reach>, _, Vec<ToolCapability>); 11] = [
        (
            "Bash WebFetch",
            claude(&["Bash", "WebFetch"]),
            shown,
            [&always[..], &commands, &[GetSearchContent, FetchContent]].concat(),
        ),
        (
            "Read Bash Edit",
            claude(&["Read", "Bash", "Edit"]),
            shown,
            [&always[..], &commands].concat(),
        ),
        (
            "Bash(git *)",
            claude(&["Bash(git *)"]),
            shown,
            always.to_vec(),
        ),
        (
            "WebFetch",
            claude(&["WebFetch"]),
            shown,
            [&always[..], &[GetSearchContent]].concat(),
        ),
        ("Read", claude(&["Read"]), shown, always.to_vec()),
        (
            "Read, no questions",
            claude(&["Read"]),
            (QuestionSupport::Unavailable, SurfaceSupport::Available),
            vec![Ui, Rho, Skill, PullRequests],
        ),
        (
            "Read, no surfaces",
            claude(&["Read"]),
            (QuestionSupport::Available, SurfaceSupport::Unavailable),
            vec![Questionnaire, Rho, Skill, PullRequests],
        ),
        (
            "agy run_command search_web",
            antigravity_reach(&[ReadFile, RunCommand, SearchWeb]),
            shown,
            [&always[..], &commands, &[GetSearchContent, FetchContent]].concat(),
        ),
        (
            "agy run_command",
            antigravity_reach(&[RunCommand]),
            shown,
            [&always[..], &commands].concat(),
        ),
        (
            "agy search_web",
            antigravity_reach(&[SearchWeb]),
            shown,
            [&always[..], &[GetSearchContent]].concat(),
        ),
        (
            "agy read_file edit_file",
            antigravity_reach(&[ReadFile, EditFile]),
            shown,
            always.to_vec(),
        ),
    ];
    for (case, reach, (questions, surfaces), expected) in cases {
        assert_eq!(
            served_capabilities(&available, questions, surfaces, &reach),
            AgentCapabilities::new(expected.into_iter().collect()),
            "{case}"
        );
    }
}

/// The tools a session serves an agent granted `Bash` and `WebFetch`, on
/// clients that show questions and draw surfaces, woken as `idle` says,
/// with the built-in agents alone.
fn served_set(root: &std::path::Path, idle: IdleDelivery) -> AppToolSet {
    let config = Config::default();
    let session = rho_sdk::SessionId::new();
    let capabilities = served_capabilities(
        &every_served(),
        QuestionSupport::Available,
        SurfaceSupport::Available,
        &[Reach::Commands, Reach::WebReads],
    );
    let pull_requests = PullRequests::open(root, Arc::new(ScriptedForge::default()));
    let tracker = WorkflowRunTracker::new();
    let options = ToolSetOptions::new(capabilities)
        .caller(ToolCaller::ExternalAgent(idle))
        .surfaces(Some(SurfaceHost::default()))
        .pull_requests(Some(pull_requests.inbox(&session, root)))
        // A daemon's browser, which starts nothing until a tool runs.
        .browser(Browsers::session(
            Browsers::for_daemon(root, Box::new(|| Box::pin(async { Default::default() })))
                .as_ref(),
            &session,
        ))
        .workflow_tracker(tracker.clone())
        // The built-in agents alone, not the ones this machine's user
        // defined, which the `agent` tool's description lists too.
        .delegation(DelegationConfig::new(
            root.to_owned(),
            root.join("config.toml"),
            Some(Arc::new(
                crate::agent::AgentCatalog::from_sources(Default::default()).unwrap(),
            )),
            SubagentPool::Own,
        ))
        .workflow(workflow_tool_service(
            root.to_owned(),
            Some(root.join("config.toml")),
            tracker,
            SubagentPool::Own,
            Default::default(),
        ));
    AppToolSet::new(&config, RuntimeDiagnostics::new(&config), options)
}

// Covers: every tool rho serves an agent, as listed to it, fits the
// description Claude Code keeps whole, so none reaches the agent cut short,
// whether or not the daemon wakes the session (each says how results reach
// the agent, which differs): `ui`'s Express notation, some 15,000
// characters, goes in the agent's instructions instead. agy kept a 20,000
// character description whole (`ANTIGRAVITY_MCP_DESCRIPTION_KEPT`), so
// what fits Claude Code fits agy too.
// Owner: daemon sessions on an external runtime (served tools' listing).
#[test]
fn every_served_tool_fits_the_description_claude_code_keeps() {
    let mut seen = Vec::new();
    for idle in [IdleDelivery::WakeTurn, IdleDelivery::NextPrompt] {
        let root = tempfile::tempdir().unwrap();
        let set = served_set(root.path(), idle);
        let too_long: Vec<(String, usize)> = set
            .tools()
            .iter()
            .map(listed)
            .map(|tool| {
                let chars = tool
                    .description
                    .as_deref()
                    .unwrap_or_default()
                    .chars()
                    .count();
                (tool.name.to_string(), chars)
            })
            .filter(|(_, chars)| *chars > CLAUDE_MCP_DESCRIPTION_LIMIT)
            .collect();
        let lists_ui = set.tools().iter().any(|tool| tool.spec().name == "ui");
        seen.push((idle, lists_ui, too_long));
    }

    assert_eq!(
        seen,
        vec![
            (IdleDelivery::WakeTurn, true, Vec::new()),
            (IdleDelivery::NextPrompt, true, Vec::new()),
        ],
        "(woken, the served set lists `ui`, served tools (name, description \
         characters) over Claude Code's {CLAUDE_MCP_DESCRIPTION_LIMIT}-character \
         description limit)"
    );
}

// Covers: `watch_pull_request` (and its `unwatch_pull_request`) is served
// only to an agent whose session the daemon wakes, whose news a turn the
// daemon starts delivers; the pull request links are served either way.
// Kills: the watch served where nothing would deliver its news (the agent
// waits on news that never comes while idle), or withheld where a wake
// would deliver it.
// Owner: daemon sessions on an external runtime (served tools' wake gate).
#[test]
fn watch_pull_request_is_served_only_where_the_daemon_wakes_the_session() {
    let links = [
        "link_pull_request",
        "list_session_pull_requests",
        "unlink_pull_request",
    ];
    let watches = ["unwatch_pull_request", "watch_pull_request"];
    let mut seen = Vec::new();
    for idle in [IdleDelivery::WakeTurn, IdleDelivery::NextPrompt] {
        let root = tempfile::tempdir().unwrap();
        let set = served_set(root.path(), idle);
        let mut pull_request_tools: Vec<String> = set
            .tools()
            .iter()
            .map(|tool| tool.spec().name)
            .filter(|name| name.contains("pull_request"))
            .collect();
        pull_request_tools.sort();
        seen.push((idle, pull_request_tools));
    }

    let names = |names: &[&str]| -> Vec<String> {
        let mut names: Vec<String> = names.iter().map(|name| (*name).to_owned()).collect();
        names.sort();
        names
    };
    assert_eq!(
        seen,
        vec![
            (
                IdleDelivery::WakeTurn,
                names(&[&links[..], &watches].concat())
            ),
            (IdleDelivery::NextPrompt, names(&links)),
        ]
    );
}

// Covers: the background work a served session delivers takes the news of
// its watched pull requests and the notices of the turns it starts in
// other sessions only where the daemon wakes it, though its tools hold the
// pull request inbox either way (for the link tools). Kills: pull request
// news kept for a session nothing wakes (it would wait on news only a wake
// delivers), and the peer inbox dropped from a woken session (a turn it
// started ends unheard).
// Owner: daemon ACP background delivery (sources per wake).
#[test]
fn only_a_woken_session_delivers_pull_request_news_and_peer_notices() {
    let mut seen = Vec::new();
    for idle in [IdleDelivery::WakeTurn, IdleDelivery::NextPrompt] {
        let root = tempfile::tempdir().unwrap();
        let set = served_set(root.path(), idle);
        let peers = PeerInbox::default();
        let sources = acp_background::sources_of(&set, idle, Some(&peers));
        seen.push((
            idle,
            set.pull_requests().is_some(),
            sources.pull_requests.is_some(),
            sources.peer_sessions.is_some(),
        ));
    }

    // (woken, the tools hold the inbox, delivers pull request news, delivers
    // peer notices)
    assert_eq!(
        seen,
        vec![
            (IdleDelivery::WakeTurn, true, true, true),
            (IdleDelivery::NextPrompt, true, false, false),
        ]
    );
}