rho-coding-agent 3.13.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
//! The launch for a bound agent: a Rho child, or the session request for a
//! CLI runtime (Claude Code, Antigravity) built from the bound agent
//! plus what one run launches with, including the environment it runs in
//! (#1659).

use super::{BoundAgent, BoundRuntime};
use crate::{
    acp_runtime::person::Attendance,
    agent::PromptPolicy,
    antigravity_runtime::fence::AntigravityFence,
    claude_runtime::fence::ClaudeFence,
    permission::PermissionMode,
    prompt::agent_session::{
        agent_session_instructions, ProjectInstructionFiles, ServedToolGuide, SkillFiles,
    },
};

/// Only [`BoundAgent::into_external`] makes an [`ExternalAgent`].
const NEVER_RHO: &str = "an external agent is bound to an external runtime";

/// What one launch of a bound agent starts with besides the agent itself.
/// A CLI runtime's session request takes all of it; a Rho agent ignores it,
/// since its child run takes the same values from its launch request.
pub(crate) struct CliRunInputs {
    pub(crate) prompt: crate::cli_runtime::CliPrompt,
    pub(crate) output_file: std::path::PathBuf,
    pub(crate) cwd: std::path::PathBuf,
    pub(crate) cancellation: rho_tools::cancellation::RunCancellation,
    pub(crate) status_tx: Option<tokio::sync::watch::Sender<crate::subagent::RunStatus>>,
    pub(crate) started_status: Option<crate::subagent::RunStatus>,
    /// The environment a CLI agent runs in and is found on: its session's
    /// when the run launched (#1659).
    pub(crate) environment: crate::session_environment::Ambient,
}

/// Exhaustive launch target after bind. The session task matches this instead
/// of probing Claude-then-Rho.
pub(in crate::app) enum Launch {
    Rho(BoundAgent),
    ClaudeCli(crate::claude_runtime::session::ClaudeSessionRequest),
    Antigravity(crate::antigravity_runtime::session::AntigravitySessionRequest),
}

impl BoundAgent {
    /// The launch for this agent: a CLI runtime's session request built
    /// from `run`, or the agent itself for a Rho child, which leaves `run`
    /// unused.
    pub(in crate::app) fn into_launch(self, run: CliRunInputs) -> Launch {
        let CliRunInputs {
            prompt,
            output_file,
            cwd,
            cancellation,
            status_tx,
            started_status,
            environment,
        } = run;
        let identity = self.artifact_identity();
        match self.runtime {
            BoundRuntime::Rho { .. } => Launch::Rho(self),
            BoundRuntime::ClaudeCli {
                tools,
                inherit_claude_config,
                permission_mode,
                max_turns,
                // Both are already in `identity`.
                model: _,
                reasoning: _,
            } => Launch::ClaudeCli(crate::claude_runtime::session::ClaudeSessionRequest {
                system_prompt: self.definition.prompt.clone(),
                identity,
                tools,
                inherit_claude_config,
                permission_mode,
                max_turns,
                prompt,
                output_file,
                cwd,
                cancellation,
                status_tx,
                started_status,
                parent_messages: None,
                rate_limit_state_path: None,
                overrides: Default::default(),
                // A saved parent's; the executor sets the parent's own.
                persistence: crate::session::SessionPersistence::Saved,
                environment,
            }),
            BoundRuntime::Antigravity {
                tools,
                permission_mode,
                // Already in `identity`.
                model: _,
            } => Launch::Antigravity(
                crate::antigravity_runtime::session::AntigravitySessionRequest {
                    system_prompt: self.definition.prompt.clone(),
                    identity,
                    tools,
                    prompt,
                    output_file,
                    cwd,
                    permission_mode,
                    cancellation,
                    status_tx,
                    started_status,
                    parent_messages: None,
                    overrides: Default::default(),
                    environment,
                },
            ),
        }
    }
}

/// A bound agent on an external runtime (Claude Code, Antigravity), which
/// runs its turns itself over ACP, and whether a person attends its runs.
/// Only [`BoundAgent::into_external`] makes one, so it never holds a Rho
/// agent.
#[derive(Clone)]
pub(crate) struct ExternalAgent {
    agent: BoundAgent,
    attendance: Attendance,
}

/// One run of an [`ExternalAgent`]: its runtime's session request.
pub(in crate::app) enum ExternalLaunch {
    ClaudeCli(crate::claude_runtime::session::ClaudeSessionRequest),
    Antigravity(crate::antigravity_runtime::session::AntigravitySessionRequest),
}

impl BoundAgent {
    /// This agent as one on an external runtime, whose runs nobody attends
    /// until [`ExternalAgent::attended_as`] says otherwise, or itself back
    /// when Rho's own loop runs it.
    pub(crate) fn into_external(self) -> Result<ExternalAgent, BoundAgent> {
        match &self.runtime {
            BoundRuntime::Rho { .. } => Err(self),
            BoundRuntime::ClaudeCli { .. } | BoundRuntime::Antigravity { .. } => {
                Ok(ExternalAgent {
                    agent: self,
                    // The safe default; a daemon session's open sets it.
                    attendance: Attendance::Unattended,
                })
            }
        }
    }
}

impl ExternalAgent {
    pub(crate) fn agent(&self) -> &BoundAgent {
        &self.agent
    }

    /// The agent, whose runs `attendance` describes.
    pub(crate) fn attended_as(self, attendance: Attendance) -> Self {
        Self { attendance, ..self }
    }

    pub(crate) fn attendance(&self) -> Attendance {
        self.attendance
    }

    /// The permission mode the agent's runs take: the one it was bound in,
    /// until [`Self::set_permission_mode`] changes it.
    pub(crate) fn permission_mode(&self) -> PermissionMode {
        match &self.agent.runtime {
            BoundRuntime::ClaudeCli {
                permission_mode, ..
            }
            | BoundRuntime::Antigravity {
                permission_mode, ..
            } => *permission_mode,
            BoundRuntime::Rho { .. } => unreachable!("{NEVER_RHO}"),
        }
    }

    /// Whether the agent's runtime fences a run in `mode`, as the agent's
    /// runs are attended; why not when it refuses.
    pub(crate) fn admits(&self, mode: PermissionMode) -> anyhow::Result<()> {
        match &self.agent.runtime {
            BoundRuntime::ClaudeCli {
                tools,
                inherit_claude_config,
                ..
            } => {
                ClaudeFence::new(mode, tools, *inherit_claude_config, self.attendance)?;
            }
            BoundRuntime::Antigravity { tools, .. } => {
                AntigravityFence::new(mode, tools)?;
            }
            BoundRuntime::Rho { .. } => unreachable!("{NEVER_RHO}"),
        }
        Ok(())
    }

    /// Runs the agent's later runs in `mode`; one its runtime's fence
    /// refuses is refused, and the mode stays as it was.
    pub(crate) fn set_permission_mode(&mut self, mode: PermissionMode) -> anyhow::Result<()> {
        self.admits(mode)?;
        match &mut self.agent.runtime {
            BoundRuntime::ClaudeCli {
                permission_mode, ..
            }
            | BoundRuntime::Antigravity {
                permission_mode, ..
            } => *permission_mode = mode,
            BoundRuntime::Rho { .. } => unreachable!("{NEVER_RHO}"),
        }
        Ok(())
    }

    /// The permission modes [`Self::admits`].
    pub(crate) fn permission_modes(&self) -> Vec<PermissionMode> {
        PermissionMode::ALL
            .into_iter()
            .filter(|&mode| self.admits(mode).is_ok())
            .collect()
    }

    /// Runs the agent's later runs on `model`: each run is a process of its
    /// own, which takes its model as it starts (Claude Code's
    /// `ANTHROPIC_MODEL`, Antigravity's `model` option). The agent refuses
    /// a model it does not offer as that run starts.
    pub(crate) fn set_model(&mut self, model: String) {
        match &mut self.agent.runtime {
            BoundRuntime::ClaudeCli { model: pinned, .. }
            | BoundRuntime::Antigravity { model: pinned, .. } => *pinned = Some(model),
            BoundRuntime::Rho { .. } => unreachable!("{NEVER_RHO}"),
        }
    }

    /// The session request of one run of the agent, built from `run`.
    pub(in crate::app) fn launch(&self, run: CliRunInputs) -> ExternalLaunch {
        match self.agent.clone().into_launch(run) {
            Launch::ClaudeCli(request) => ExternalLaunch::ClaudeCli(request),
            Launch::Antigravity(request) => ExternalLaunch::Antigravity(request),
            Launch::Rho(_) => unreachable!("{NEVER_RHO}"),
        }
    }
}

/// What an agent's session keeps of the system prompt it started with
/// when a later run resumes it.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(in crate::app) enum ResumedInstructions {
    /// It takes the run's: agy appends `_meta.antigravity.systemPrompt` on
    /// `session/resume` too.
    Refreshed,
    /// It keeps the first run's: claude-agent-acp 0.114.0 ignores a system
    /// prompt on `session/resume`.
    KeptFromStart,
}

/// The instructions a run gives its agent, and what a resumed session
/// keeps of them.
pub(in crate::app) struct SessionInstructions {
    pub(in crate::app) text: String,
    pub(in crate::app) resumed: ResumedInstructions,
}

impl ExternalLaunch {
    /// Gives the run rho's instructions for a daemon session's agent
    /// ([`agent_session_instructions`]) in place of its definition's text,
    /// with how to use `served`, the tools of rho's the run serves the
    /// agent, if any. Reads the run's attendance from its overrides, so
    /// call it once they are set.
    pub(in crate::app) fn give_session_instructions(
        &mut self,
        home: Option<&std::path::Path>,
        served: Option<&ServedToolGuide>,
    ) -> SessionInstructions {
        let (system_prompt, cwd, project, skills, resumed) = match self {
            Self::ClaudeCli(request) => {
                let project = match request.reads_project_instructions() {
                    true => ProjectInstructionFiles::ReadByAgent,
                    false => ProjectInstructionFiles::FromRho,
                };
                let prompt = &mut request.system_prompt;
                (
                    prompt,
                    &request.cwd,
                    project,
                    SkillFiles::FromRho,
                    ResumedInstructions::KeptFromStart,
                )
            }
            // agy reads the project's AGENTS.md itself, and the
            // `.agents/skills` folders.
            Self::Antigravity(request) => (
                &mut request.system_prompt,
                &request.cwd,
                ProjectInstructionFiles::ReadByAgent,
                SkillFiles::LooseReadByAgent,
                ResumedInstructions::Refreshed,
            ),
        };
        let text = match system_prompt {
            PromptPolicy::Extend(text) => {
                *text = agent_session_instructions(text, cwd, home, project, served, skills);
                text.clone()
            }
            // A definition that replaces the agent's system prompt owns all
            // of it. The session definitions extend.
            PromptPolicy::Replace(text) => text.clone(),
        };
        SessionInstructions { text, resumed }
    }

    /// Whether the run resumes the agent's session.
    pub(in crate::app) fn resumes(&mut self) -> bool {
        self.overrides_mut().resume.is_some()
    }

    /// The seams the run's caller may replace.
    pub(in crate::app) fn overrides_mut(&mut self) -> &mut crate::cli_runtime::CliSessionOverrides {
        match self {
            Self::ClaudeCli(request) => &mut request.overrides,
            Self::Antigravity(request) => &mut request.overrides,
        }
    }

    /// Where the run takes messages for its turn in flight: none unless its
    /// caller sets an inbox, as a daemon session does for the results of
    /// its agent's background work.
    pub(in crate::app) fn parent_messages_mut(
        &mut self,
    ) -> &mut Option<crate::cli_runtime::parent_messages::ParentMessageInbox> {
        match self {
            Self::ClaudeCli(request) => &mut request.parent_messages,
            Self::Antigravity(request) => &mut request.parent_messages,
        }
    }

    /// Runs the agent once, to the run's end.
    pub(in crate::app) async fn run(self) -> anyhow::Result<()> {
        match self {
            Self::ClaudeCli(request) => crate::claude_runtime::session::run_session(request).await,
            Self::Antigravity(request) => {
                crate::antigravity_runtime::session::run_session(request).await
            }
        }
    }
}