rho-coding-agent 3.13.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
//! Agent-owned decisions consumed by the generic ACP driver.

use super::permission::PermissionDecision;
use crate::{
    cli_runtime::{
        agent_event::AgentEvent,
        status_sink::{RateLimitRecorder, RuntimeLabel},
        stream_effect::StreamEffect,
        CliExecutable,
    },
    session_environment::Ambient,
};
use agent_client_protocol::v1::schema::{
    AuthMethod, AuthMethodId, Meta, RequestPermissionRequest, SessionConfigId, SessionConfigOption,
    SessionConfigValueId, SessionModeId, SessionUpdate, ToolCall, ToolCallUpdate, ToolKind,
};
use serde_json::Value;
use std::{
    ffi::OsString,
    path::{Path, PathBuf},
};

/// What [`AcpAgentPolicy::agent_tool`] reads one of the agent's tool calls
/// by: the parts of its `tool_call`, or of an update or permission ask
/// for it, that can name the tool it runs.
#[derive(Clone, Copy, Debug)]
pub(crate) struct AgentToolCallRef<'a> {
    pub(crate) meta: Option<&'a Meta>,
    pub(crate) name: Option<&'a str>,
    pub(crate) kind: Option<ToolKind>,
}

impl<'a> From<&'a ToolCall> for AgentToolCallRef<'a> {
    fn from(call: &'a ToolCall) -> Self {
        Self {
            meta: call.meta.as_ref(),
            name: call.name.as_deref(),
            kind: Some(call.kind),
        }
    }
}

impl<'a> From<&'a ToolCallUpdate> for AgentToolCallRef<'a> {
    fn from(update: &'a ToolCallUpdate) -> Self {
        Self {
            meta: update.meta.as_ref(),
            name: update.fields.name.as_deref(),
            kind: update.fields.kind,
        }
    }
}

/// Whether a run's agent may start agents of its own, as Claude Code's Task
/// tool does.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum NestedAgents {
    /// It may not: Rho owns delegation, and nobody would see such a child.
    Off,
    /// It may: the run records each child it starts as a run of its own
    /// (see `runtime_children`).
    Recorded,
}

/// What one ACP agent needs from Rho, and how Rho answers agent requests.
/// Implementors supply synchronous policy; only executable resolution and
/// `prepare` may perform I/O. `prepare` must only write per-run configuration
/// under `run_dir`. Never mutate process environment or await another ACP
/// request while answering a request.
/// The driver owns process supervision, timeout budgets, rendering, and terminal
/// writes. A policy sends the agent's instructions as its runtime takes a
/// system prompt, in [`Self::session_meta`].
pub(crate) trait AcpAgentPolicy: Send + 'static {
    fn label(&self) -> RuntimeLabel;
    /// The agent's program on the `PATH` of `environment`, the one it will
    /// run in (#1659).
    fn resolve_executable(&self, environment: &Ambient) -> Result<CliExecutable, String>;
    /// Argv, cwd, and environment for this run, with permission-sensitive
    /// flags derived from the bound mode.
    fn spawn_plan(&self) -> Result<AcpSpawnPlan, String>;
    /// Per-run setup, done before the agent is spawned.
    fn prepare(&mut self, run_dir: &Path) -> Result<(), String>;
    fn log_path(&self, output_file: &Path) -> PathBuf;
    /// The newest ACP version the run asks the agent for. An agent that
    /// answers v1 to a v2 `initialize` runs on v1, in a new process.
    fn protocol(&self) -> AcpProtocol {
        AcpProtocol::V1
    }
    /// Asked on protocol v1 only: a runtime that asks for v2 signs in
    /// outside its runs, so the driver sends no v2 `auth/login`.
    fn auth_method(&self, advertised: &[AuthMethod]) -> Option<AuthMethodId>;
    /// A required mode must be advertised and successfully set before prompting,
    /// and the agent must stay in it: a `current_mode_update` to another mode
    /// fails the run.
    fn session_mode(&self) -> Option<SessionModeId>;
    /// `_meta` sent with `session/new` and `session/resume`, for vendor
    /// session parameters such as tool filters and the system prompt, in a
    /// run whose agent may start agents of its own as `nested` says.
    fn session_meta(&self, _nested: NestedAgents) -> Option<Meta> {
        None
    }
    /// Select options to set, in order, after `session/new` and the mode.
    /// Each must be advertised with the asked value, or the run fails before
    /// prompting.
    fn session_config(&self) -> Vec<SessionConfigChoice> {
        Vec::new()
    }
    /// The select options a new session of the agent offered, before Rho
    /// set any: what it would run on unasked. Not called for a resumed
    /// session, whose options are what an earlier run left them at. Called
    /// with the policy's lock held. The one place besides `prepare` a
    /// policy may do I/O, to keep a cache of its runtime's own, such as the
    /// models it offers; failing to is the policy's to log, never the
    /// run's.
    fn config_seen(&self, _options: &[SessionConfigOption]) {}
    fn decide_permission(&self, request: &RequestPermissionRequest) -> PermissionDecision;
    /// The tool of the server [`super::agent_tools::SERVER_NAME`], by the
    /// name the server lists, that the agent's tool call `call` runs, on
    /// its permission ask or its `tool_call` update, read the way this
    /// agent names MCP tools: in `_meta` (Claude Code) or in its name and
    /// kind (agy). The driver approves an ask for a tool the run serves
    /// without [`Self::decide_permission`], since the tools' owner decides
    /// each call as it runs, and holds back the agent's card for its call,
    /// which the served call draws. `None` leaves every ask to the policy
    /// and every card to the agent.
    fn agent_tool<'a>(&self, _call: AgentToolCallRef<'a>) -> Option<&'a str> {
        None
    }
    /// The person approved the plan of a [`Asking::PlanExit`] ask into
    /// `to`, the mode it named, and the agent is about to hear so: the
    /// policy now fences `to`, which [`Self::session_mode`] then names.
    /// `false` keeps the policy as it was, for a policy that never asks to
    /// leave plan mode, and the agent hears a rejection instead.
    ///
    /// [`Asking::PlanExit`]: super::permission::Asking::PlanExit
    fn leave_plan(&mut self, _to: crate::permission::PermissionMode) -> bool {
        false
    }
    /// Answer any blocking extension request, including methods without a
    /// session id or underscore prefix. None replies method_not_found.
    fn answer_extension(&self, method: &str, params: &Value) -> Option<ExtensionAnswer>;
    /// Where this agent's subscription rate-limit observations are kept.
    /// `None` records nothing.
    fn rate_limit_recorder(&self) -> Option<Box<dyn RateLimitRecorder>> {
        None
    }
    /// Agent-specific status an update carries in its `_meta`, such as a
    /// rate-limit observation for the recorder or the resolved model.
    fn status_effects(&self, _update: &SessionUpdate) -> Vec<StreamEffect> {
        Vec::new()
    }
}

/// An ACP protocol version the client speaks.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum AcpProtocol {
    V1,
    /// The draft v2 (`unstable_protocol_v2`): the prompt response only
    /// acknowledges the prompt, the turn ends with the session's `idle`
    /// state, and the session mode is the config option of category `mode`.
    V2,
}

/// Fully materialized launch; `env` overrides apply to this child only, on
/// top of the environment the run gives it (see [`Ambient::apply_full`]).
pub(crate) struct AcpSpawnPlan {
    pub(crate) argv: Vec<OsString>,
    pub(crate) cwd: PathBuf,
    pub(crate) env: Vec<(OsString, OsString)>,
}

/// One required `session/set_config_option` select value.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct SessionConfigChoice {
    pub(crate) id: SessionConfigId,
    pub(crate) value: SessionConfigValueId,
}

pub(crate) struct ExtensionAnswer {
    pub(crate) reply: Value,
    pub(crate) events: Vec<AgentEvent>,
}