rho-coding-agent 3.11.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
//! Setting a v2 session up: `initialize`, `session/new` or `session/resume`,
//! and the policy's required mode and select options, all within the
//! handshake step budget, before the first prompt.
//!
//! On v2 the session mode is no longer `session/set_mode`: it is the select
//! config option whose category is `mode`, and a new session starts in the
//! mode the agent picks itself. claude-agent-acp 0.114.0 picks it from the
//! user's own Claude settings, which can be `bypassPermissions`, so the
//! fence sets the policy's mode and then checks the agent reports it,
//! failing the run before it prompts otherwise.

use super::{bridge, v1_options, Updates};
use crate::acp_runtime::{
    handshake::{self, bounded, error, needs_setting, select_state},
    person::Attendance,
    policy::{AcpAgentPolicy, SessionConfigChoice},
};
use agent_client_protocol::{
    schema::ProtocolVersion,
    v1::schema as v1,
    v2::{schema as v2, ConnectionTo, InitializeOutcome},
    Agent, Error, SelectedInitializeResponse,
};
use std::sync::Mutex;

/// What `initialize` settled.
pub(super) enum Initialized {
    /// The agent speaks v2, at `version` (`info.version`), with these
    /// optional features.
    V2 {
        version: String,
        mcp_over_acp: bool,
        image: bool,
    },
    /// The agent answered v1, at `version` (`agentInfo.version`), taking
    /// images or not: this connection cannot carry it.
    SpeaksV1 {
        version: Option<String>,
        image: bool,
    },
}

/// The `initialize` Rho sends as a v2 client: it names Rho, as the v1 one
/// does. Only a run a person attends advertises forms, which claude-agent-acp
/// needs to offer AskUserQuestion at all: nobody else answers a question.
pub(super) fn initialize_request(attendance: Attendance) -> v2::InitializeRequest {
    let capabilities = match attendance {
        Attendance::Attended => v2::ClientCapabilities::new().elicitation(
            v2::ElicitationCapabilities::new().form(v2::ElicitationFormCapabilities::new()),
        ),
        Attendance::Unattended => v2::ClientCapabilities::new(),
    };
    v2::InitializeRequest::new(
        ProtocolVersion::V2,
        v2::Implementation::new("rho", env!("CARGO_PKG_VERSION")).title("Rho"),
    )
    .capabilities(capabilities)
}

pub(super) async fn initialize(
    cx: &ConnectionTo<Agent>,
    attendance: Attendance,
) -> Result<Initialized, Error> {
    let outcome = bounded(
        "initialize",
        cx.send_initialize(initialize_request(attendance))
            .block_task(),
    )
    .await?;
    match outcome {
        InitializeOutcome::Initialized(response) => Ok(Initialized::V2 {
            version: response.info.version.clone(),
            mcp_over_acp: response
                .capabilities
                .session
                .as_ref()
                .and_then(|session| session.mcp.as_ref())
                .is_some_and(|mcp| mcp.acp.is_some()),
            image: response
                .capabilities
                .session
                .as_ref()
                .and_then(|session| session.prompt.as_ref())
                .is_some_and(|prompt| prompt.image.is_some()),
        }),
        InitializeOutcome::LowerVersion(mismatch) => match mismatch.response {
            SelectedInitializeResponse::V1(response) => Ok(Initialized::SpeaksV1 {
                version: response.agent_info.map(|info| info.version),
                image: response.agent_capabilities.prompt_capabilities.image,
            }),
            // `SelectedInitializeResponse` is non-exhaustive.
            _ => Err(error("acp: initialize: unknown lower protocol version")),
        },
        // `InitializeOutcome` is non-exhaustive.
        _ => Err(error("acp: initialize: unknown negotiation outcome")),
    }
}

/// The v2 form of a server the run declares to the agent.
pub(super) fn mcp_server(server: v1::McpServer) -> Result<v2::McpServer, Error> {
    match server {
        v1::McpServer::Acp(server) => Ok(v2::McpServer::Acp(bridge(&server)?)),
        v1::McpServer::Stdio(server) => Ok(v2::McpServer::Stdio(bridge(&server)?)),
        other => Err(error(format!(
            "acp: no v2 form for MCP server declaration {other:?}"
        ))),
    }
}

/// Sets the policy's required mode, then its select options, on the agent's
/// options `offered` as the session set up with, and checks the agent ends
/// in the required mode. Each answer carries the whole option set, and
/// answers and config updates apply in the order the agent sent them, so
/// each choice and the mode are checked against the latest
/// ([`Updates::ask`], [`Updates::latest_options`]).
pub(super) async fn require_mode_and_config<P: AcpAgentPolicy>(
    session: &agent_client_protocol::v2::ActiveSession<Agent>,
    offered: &[v2::SessionConfigOption],
    policy: &Mutex<P>,
    updates: &mut Updates,
) -> Result<(), Error> {
    let (required, config) = {
        let policy = policy.lock().expect("ACP policy");
        (policy.session_mode(), policy.session_config())
    };
    let mut options = v1_options(offered);
    let mode = match &required {
        Some(mode) => Some(mode_choice(&options, mode)?),
        None => None,
    };
    for choice in mode.into_iter().chain(config) {
        if !needs_setting(&options, &choice)? {
            continue;
        }
        let step = handshake::config_step(&choice);
        let answered = bounded(
            &step,
            updates.ask(session.set_config_option(
                choice.id.to_string(),
                v2::SessionConfigOptionValue::Id {
                    value: choice.value.to_string().into(),
                },
            )),
        )
        .await?;
        options = v1_options(&answered.config_options);
    }
    // An update the agent sent after the last answer moves the options on.
    if let Some(latest) = updates.latest_options(&session.session_id().to_string()) {
        options = v1_options(&latest);
    }
    check_mode(&options, required.as_ref())
}

/// The choice that puts the agent's mode option at `mode`. Fails closed when
/// the agent offers no mode option: the run cannot be fenced.
fn mode_choice(
    options: &[v1::SessionConfigOption],
    mode: &v1::SessionModeId,
) -> Result<SessionConfigChoice, Error> {
    let Some(option) = mode_option(options) else {
        return Err(error(format!(
            "acp: required mode `{mode}`: the agent offers no select option of category `mode`"
        )));
    };
    Ok(SessionConfigChoice {
        id: option.id.clone(),
        value: mode.to_string().into(),
    })
}

/// The select option of category `mode`, which holds the session's mode.
fn mode_option(options: &[v1::SessionConfigOption]) -> Option<&v1::SessionConfigOption> {
    options.iter().find(|option| {
        option.category == Some(v1::SessionConfigOptionCategory::Mode)
            && select_state(option).is_some()
    })
}

/// A policy may rely on its required mode as part of its fence: `options`,
/// the agent's whole option set as set up or as a `config_option_update`
/// replaces it, must hold the mode option at `required`. One that drops the
/// option, or moves it elsewhere, fails the run instead of continuing
/// unfenced.
pub(super) fn check_mode(
    options: &[v1::SessionConfigOption],
    required: Option<&v1::SessionModeId>,
) -> Result<(), Error> {
    let Some(required) = required else {
        return Ok(());
    };
    let current = mode_option(options)
        .and_then(select_state)
        .map(|(current, _)| current);
    match current {
        Some(current) if current.to_string() == required.to_string() => Ok(()),
        Some(current) => Err(error(format!(
            "acp: agent is in mode `{current}`, not required mode `{required}`"
        ))),
        None => Err(error(format!(
            "acp: agent no longer offers a mode option, so required mode `{required}` cannot hold"
        ))),
    }
}