rho-coding-agent 3.11.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
//! Antigravity's answers to the generic ACP runtime (`agy acp`).
//!
//! The fence is per run (see `fence`): the run's agy agent with the kept
//! tools, the agy session mode, and one-shot permission answers. The model is
//! a session config option, not argv.
//!
//! A run that serves the agent rho's tools (a daemon session's) lists rho's
//! MCP server in its agent, over the stdio bridge
//! (`acp_runtime::agent_tools::bridge`). agy asks permission before each
//! MCP call, kind `other`, in both its modes: the driver approves an ask for
//! one of rho's tools ([`AcpAgentPolicy::agent_tool`]), since rho's own
//! policy decides the call as it runs, in the session's mode.

use std::path::{Path, PathBuf};

use agent_client_protocol::v1::schema::{
    AuthMethod, AuthMethodId, RequestPermissionRequest, SessionConfigOption, SessionModeId,
    ToolKind,
};
use serde_json::{json, Value};

use crate::{
    acp_runtime::{
        agent_tools::{McpToolNaming, SERVER_NAME},
        permission::PermissionDecision,
        AcpAgentPolicy, AcpSpawnPlan, AgentToolCallRef, ExtensionAnswer, SessionConfigChoice,
    },
    agent::{AntigravityTool, PromptPolicy},
    cli_runtime::{status_sink::RuntimeLabel, CliExecutable},
    permission::PermissionMode,
};

use super::{
    agent_file, executable,
    fence::AntigravityFence,
    models::{self, MODEL_CONFIG_ID},
    ANTIGRAVITY_LABEL,
};

/// How agy 1.5.21 names an MCP server's tools: `mcp_rho_<tool>`.
pub(crate) const MCP_TOOL_NAMING: McpToolNaming = McpToolNaming::separated_by("_");

/// Bound Antigravity run policy. `prepare` must run before the session
/// starts: it gates the mode, fixes the fence, and writes the run's agent.
pub(crate) struct AntigravityAcpPolicy {
    model: Option<String>,
    tools: Vec<AntigravityTool>,
    permission_mode: PermissionMode,
    cwd: PathBuf,
    /// Travels as `_meta.antigravity.systemPrompt.append`, which agy adds
    /// to its own system prompt on `session/new` and again on each
    /// `session/resume`, so a resumed session takes the current text.
    /// Recorded against agy 1.5.16 (ACP server 1.5.21).
    system_prompt: PromptPolicy,
    /// Whether the run serves its agent rho's tools, whose server its
    /// agent file then lists.
    rho_tools: RhoTools,
    /// Set by `prepare`; permission requests before it fail closed.
    prepared: Option<Prepared>,
}

/// Whether a run serves its agent rho's tools.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum RhoTools {
    Unserved,
    Served,
}

impl RhoTools {
    /// The MCP servers the run's agent file lists.
    fn mcp_servers(self) -> &'static [&'static str] {
        match self {
            Self::Unserved => &[],
            Self::Served => &[SERVER_NAME],
        }
    }
}

struct Prepared {
    fence: AntigravityFence,
    agent: agent_file::RunAgent,
}

impl AntigravityAcpPolicy {
    pub(crate) fn new(
        model: Option<String>,
        tools: Vec<AntigravityTool>,
        permission_mode: PermissionMode,
        cwd: PathBuf,
        system_prompt: PromptPolicy,
    ) -> Self {
        Self {
            model,
            tools,
            permission_mode,
            cwd,
            system_prompt,
            rho_tools: RhoTools::Unserved,
            prepared: None,
        }
    }

    /// The policy, for a run that serves its agent rho's tools: its agent
    /// sees rho's MCP server.
    pub(crate) fn serving_rho_tools(self) -> Self {
        Self {
            rho_tools: RhoTools::Served,
            ..self
        }
    }
}

impl AcpAgentPolicy for AntigravityAcpPolicy {
    fn label(&self) -> RuntimeLabel {
        ANTIGRAVITY_LABEL
    }

    fn resolve_executable(
        &self,
        environment: &crate::session_environment::Ambient,
    ) -> Result<CliExecutable, String> {
        executable::resolve(environment).map_err(|error| error.to_string())
    }

    fn spawn_plan(&self) -> Result<AcpSpawnPlan, String> {
        let prepared = self
            .prepared
            .as_ref()
            .ok_or("antigravity: run was not prepared")?;
        Ok(AcpSpawnPlan {
            argv: executable::server_args(&prepared.agent),
            cwd: self.cwd.clone(),
            env: Vec::new(),
        })
    }

    fn prepare(&mut self, run_dir: &Path) -> Result<(), String> {
        if let PromptPolicy::Replace(_) = self.system_prompt {
            return Err(
                "antigravity: `prompt: replace` is unsupported: agy only appends to its system prompt"
                    .into(),
            );
        }
        // Binding refuses these first; checking again keeps a run that skipped
        // binding closed, and fails through the terminal artifact.
        let fence = AntigravityFence::new(self.permission_mode, &self.tools)
            .map_err(|error| error.to_string())?;
        let agent = agent_file::write(run_dir, fence.tools(), self.rho_tools.mcp_servers())
            .map_err(|error| {
                format!("antigravity: could not write the run's agy agent: {error}")
            })?;
        self.prepared = Some(Prepared { fence, agent });
        Ok(())
    }

    fn log_path(&self, output_file: &Path) -> PathBuf {
        output_file.with_file_name(crate::subagent::LOG_FILE_NAME)
    }

    /// Never authenticate in a run: sign-in is interactive and belongs to
    /// `/login antigravity`. A signed-out agy fails `session/new` with
    /// "Authentication required".
    fn auth_method(&self, _advertised: &[AuthMethod]) -> Option<AuthMethodId> {
        None
    }

    fn session_meta(&self) -> Option<agent_client_protocol::v1::schema::Meta> {
        match &self.system_prompt {
            PromptPolicy::Extend(text) if !text.trim().is_empty() => {
                json!({"antigravity": {"systemPrompt": {"append": text}}})
                    .as_object()
                    .cloned()
            }
            PromptPolicy::Extend(_) | PromptPolicy::Replace(_) => None,
        }
    }

    fn session_mode(&self) -> Option<SessionModeId> {
        self.prepared
            .as_ref()
            .map(|prepared| SessionModeId::new(prepared.fence.session_mode()))
    }

    fn session_config(&self) -> Vec<SessionConfigChoice> {
        self.model
            .iter()
            .map(|model| SessionConfigChoice {
                id: MODEL_CONFIG_ID.into(),
                value: model.clone().into(),
            })
            .collect()
    }

    /// Keeps the models agy offered, for `rho/runtime/list`.
    fn config_seen(&self, options: &[SessionConfigOption]) {
        models::record(options);
    }

    fn decide_permission(&self, request: &RequestPermissionRequest) -> PermissionDecision {
        self.prepared
            .as_ref()
            .map_or(PermissionDecision::Reject, |prepared| {
                prepared.fence.decide(request)
            })
    }

    /// agy 1.5.21 names an MCP tool's call as [`MCP_TOOL_NAMING`] says,
    /// kind `other`, in its `tool_call`, its updates and its permission
    /// ask, and puts no tool name in `_meta`. Its `_` is ambiguous: a
    /// server `rho_watch`'s tool `pull_request` would read as rho's
    /// `watch_pull_request`. That is safe only because the run's agent file
    /// lists no server but `rho` ([`RhoTools::mcp_servers`]), so every MCP
    /// call agy makes is to the run's.
    fn agent_tool<'a>(&self, call: AgentToolCallRef<'a>) -> Option<&'a str> {
        if call.kind != Some(ToolKind::Other) {
            return None;
        }
        MCP_TOOL_NAMING.tool_of(call.name?)
    }

    /// agy 1.5.0 sends no extension requests that Rho can answer.
    fn answer_extension(&self, _method: &str, _params: &Value) -> Option<ExtensionAnswer> {
        None
    }
}

#[cfg(test)]
#[path = "policy_tests.rs"]
mod tests;