rho-coding-agent 3.13.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
//! Bounded setup steps. Prompt turns themselves have no runtime time limit.

use super::{
    person::Attendance,
    policy::{AcpAgentPolicy, AcpProtocol, SessionConfigChoice},
};
use agent_client_protocol::{
    schema::ProtocolVersion,
    v1::schema::{
        AuthenticateRequest, ClientCapabilities, ElicitationCapabilities,
        ElicitationFormCapabilities, Implementation, InitializeRequest, NewSessionRequest,
        NewSessionResponse, ResumeSessionResponse, SessionConfigKind, SessionConfigOption,
        SessionConfigSelectOptions, SessionConfigValueId, SessionModeId, SessionModeState,
        SessionUpdate, SetSessionConfigOptionRequest, SetSessionModeRequest,
    },
    v1::{ActiveSession, ConnectionTo, SessionSetup},
    Agent, Error,
};
use std::{future::Future, sync::Mutex, time::Duration};

// Receipt: a recorded ACP agent (Cursor, n=14) took 420–503 ms to
// `initialize` and 2411–3381 ms for `session/new`; ten seconds is about 3x the
// worst cold handshake. The recordings are in the history of the commit that
// removed the cursor runtime.
pub(super) const HANDSHAKE_STEP_BUDGET: Duration = Duration::from_secs(10);

pub(super) fn error(message: impl Into<String>) -> Error {
    let mut error = Error::internal_error();
    error.message = message.into();
    error
}

pub(super) async fn bounded<T>(
    step: &str,
    future: impl Future<Output = Result<T, Error>>,
) -> Result<T, Error> {
    tokio::time::timeout(HANDSHAKE_STEP_BUDGET, future)
        .await
        .map_err(|_| error(format!("acp: {step} exceeded handshake step budget 10 s")))?
        .map_err(|source| error(format!("acp: {step}: {source}")))
}

/// The `initialize` Rho sends as a client: it names Rho, with the version
/// `rho --version` prints, and keeps the constructor's capability defaults,
/// which advertise no filesystem, terminal, or subagent support. Do not
/// enable capabilities we cannot fulfill: only a run a person attends
/// advertises form elicitation, so an agent nobody attends never waits on
/// a question.
pub(super) fn initialize_request(attendance: Attendance) -> InitializeRequest {
    let request = InitializeRequest::new(ProtocolVersion::V1)
        .client_info(Implementation::new("rho", env!("CARGO_PKG_VERSION")).title("Rho"));
    match attendance {
        Attendance::Attended => {
            request.client_capabilities(ClientCapabilities::new().elicitation(
                ElicitationCapabilities::new().form(ElicitationFormCapabilities::new()),
            ))
        }
        Attendance::Unattended => request,
    }
}

/// Optional agent extensions the driver uses, read from `initialize`.
#[derive(Clone, Copy, Debug, Default)]
pub(super) struct AgentFeatures {
    pub(super) steering: bool,
    /// The agent resumes a session it set up earlier, in another process
    /// too (`sessionCapabilities.resume`).
    pub(super) resume: bool,
    /// The agent takes an MCP server carried over this connection
    /// (`mcpCapabilities.acp`).
    pub(super) mcp_over_acp: bool,
    /// The agent takes image content blocks in `session/prompt`
    /// (`promptCapabilities.image`).
    pub(super) image: bool,
}

/// What a session set up with, new or resumed: the modes and config
/// options the policy's requirements are checked against.
#[derive(Clone, Copy)]
pub(super) struct SetUp<'a> {
    modes: Option<&'a SessionModeState>,
    config_options: Option<&'a Vec<SessionConfigOption>>,
}

impl<'a> From<&'a NewSessionResponse> for SetUp<'a> {
    fn from(response: &'a NewSessionResponse) -> Self {
        Self {
            modes: response.modes.as_ref(),
            config_options: response.config_options.as_ref(),
        }
    }
}

impl<'a> From<&'a ResumeSessionResponse> for SetUp<'a> {
    fn from(response: &'a ResumeSessionResponse) -> Self {
        Self {
            modes: response.modes.as_ref(),
            config_options: response.config_options.as_ref(),
        }
    }
}

/// Open a new session with `request`, within the step budget, and show the
/// policy the select options it offered ([`AcpAgentPolicy::config_seen`])
/// before anything sets one. Every `session/new` goes through here.
pub(super) async fn new_session<P: AcpAgentPolicy>(
    cx: &ConnectionTo<Agent>,
    request: NewSessionRequest,
    policy: &Mutex<P>,
) -> Result<SessionSetup<'static, Agent, NewSessionResponse>, Error> {
    let setup = bounded(
        "session/new",
        cx.build_session_from(request).block_task().start_session(),
    )
    .await?;
    let offered = setup.response.config_options.as_deref().unwrap_or_default();
    policy.lock().expect("ACP policy").config_seen(offered);
    Ok(setup)
}

/// Initializes the agent on v1 (and signs in if its policy says how),
/// telling `adapter`, when set, what it said.
pub(super) async fn initialize<P: AcpAgentPolicy>(
    cx: &ConnectionTo<Agent>,
    policy: &Mutex<P>,
    attendance: Attendance,
    adapter: Option<super::adapters::Adapter<'_>>,
) -> Result<AgentFeatures, Error> {
    let response = bounded(
        "initialize",
        cx.send_request(initialize_request(attendance)).block_task(),
    )
    .await
    .and_then(|response| match response.protocol_version {
        ProtocolVersion::V1 => Ok(response),
        other => Err(error(format!(
            "acp: initialize: unsupported protocol version {other}"
        ))),
    });
    let response = match response {
        Ok(response) => response,
        Err(failed) => {
            if let Some(adapter) = adapter {
                adapter.v1_failed();
            }
            return Err(failed);
        }
    };
    let image = response.agent_capabilities.prompt_capabilities.image;
    if let Some(adapter) = adapter {
        let version = response
            .agent_info
            .as_ref()
            .map(|info| info.version.clone());
        adapter.initialized(AcpProtocol::V1, AcpProtocol::V1, version, image);
    }
    let method = policy
        .lock()
        .expect("ACP policy")
        .auth_method(&response.auth_methods);
    if let Some(method) = method {
        bounded(
            "authenticate",
            cx.send_request(AuthenticateRequest::new(method))
                .block_task(),
        )
        .await?;
    }
    Ok(AgentFeatures {
        steering: super::steering::supported(response.meta.as_ref()),
        resume: response
            .agent_capabilities
            .session_capabilities
            .resume
            .is_some(),
        mcp_over_acp: response.agent_capabilities.mcp_capabilities.acp,
        image,
    })
}

/// A policy may rely on its required mode as part of its fence: an agent that
/// leaves it fails the run instead of continuing unfenced.
pub(super) fn check_mode_update(
    update: &SessionUpdate,
    required: Option<&SessionModeId>,
) -> Result<(), Error> {
    if let (SessionUpdate::CurrentModeUpdate(mode), Some(required)) = (update, required) {
        if mode.current_mode_id != *required {
            return Err(error(format!(
                "acp: agent switched to mode `{}`, leaving required mode `{required}`",
                mode.current_mode_id
            )));
        }
    }
    Ok(())
}

pub(super) async fn require_mode<P: AcpAgentPolicy>(
    session: &ActiveSession<'_, Agent>,
    created: SetUp<'_>,
    policy: &Mutex<P>,
) -> Result<(), Error> {
    let mode = policy.lock().expect("ACP policy").session_mode();
    if let Some(mode) = mode {
        if !created.modes.is_some_and(|modes| {
            modes
                .available_modes
                .iter()
                .any(|available| available.id == mode)
        }) {
            return Err(error(format!(
                "acp: session/set_mode: required mode `{mode}` is not advertised"
            )));
        }
        bounded(
            &format!("session/set_mode `{mode}`"),
            session
                .connection()
                .send_request(SetSessionModeRequest::new(
                    session.session_id().clone(),
                    mode,
                ))
                .block_task(),
        )
        .await?;
    }
    Ok(())
}

/// Set each policy-required select option, after checking the agent
/// advertised it with that value. Already-current values are not re-sent.
/// Each response carries the full option set (one change can move others),
/// so later choices are checked against the latest one.
pub(super) async fn require_config<P: AcpAgentPolicy>(
    session: &ActiveSession<'_, Agent>,
    created: SetUp<'_>,
    policy: &Mutex<P>,
) -> Result<(), Error> {
    let choices = policy.lock().expect("ACP policy").session_config();
    let mut options = created.config_options.cloned().unwrap_or_default();
    for choice in choices {
        if !needs_setting(&options, &choice)? {
            continue;
        }
        options = bounded(
            &config_step(&choice),
            session
                .connection()
                .send_request(SetSessionConfigOptionRequest::new(
                    session.session_id().clone(),
                    choice.id,
                    choice.value,
                ))
                .block_task(),
        )
        .await?
        .config_options;
    }
    Ok(())
}

/// The setup step that sets `choice`, as errors name it.
pub(super) fn config_step(choice: &SessionConfigChoice) -> String {
    format!("session/set_config_option `{}`", choice.id)
}

/// Whether `choice` must be set: `false` when it is already current. Fails
/// when `options`, the agent's current select options, do not offer it.
pub(super) fn needs_setting(
    options: &[SessionConfigOption],
    choice: &SessionConfigChoice,
) -> Result<bool, Error> {
    let step = config_step(choice);
    let Some((current, values)) = options
        .iter()
        .find(|option| option.id == choice.id)
        .and_then(select_state)
    else {
        return Err(error(format!(
            "acp: {step}: the agent does not advertise select option `{}`",
            choice.id
        )));
    };
    if !values.contains(&&choice.value) {
        let available = values
            .iter()
            .map(ToString::to_string)
            .collect::<Vec<_>>()
            .join(", ");
        return Err(error(format!(
            "acp: {step}: value `{}` is not advertised (available: {available})",
            choice.value
        )));
    }
    Ok(*current != choice.value)
}

/// Current value and every offered value of a select option; `None` for
/// other (including future) option kinds.
pub(super) fn select_state(
    option: &SessionConfigOption,
) -> Option<(&SessionConfigValueId, Vec<&SessionConfigValueId>)> {
    let SessionConfigKind::Select(select) = &option.kind else {
        return None;
    };
    let values = match &select.options {
        SessionConfigSelectOptions::Ungrouped(options) => {
            options.iter().map(|option| &option.value).collect()
        }
        SessionConfigSelectOptions::Grouped(groups) => groups
            .iter()
            .flat_map(|group| &group.options)
            .map(|option| &option.value)
            .collect(),
        _ => return None,
    };
    Some((&select.current_value, values))
}