rho-coding-agent 3.11.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
//! What an agent's sessions offer before any runs: the select options a
//! fresh `session/new` advertises, such as its models, shown to the policy's
//! [`AcpAgentPolicy::config_seen`] as a run's are, for a cache a runtime
//! keeps without a run.
//!
//! The probe spawns the policy's agent, initializes, opens one session, then
//! ends the process; it prompts nothing. The agent may keep that session,
//! empty, among its own.

use std::process::Stdio;

use agent_client_protocol::{v1::schema::NewSessionRequest, Client, ConnectTo};

use super::{
    handshake, person::Attendance, policy::AcpAgentPolicy, session::spawn_agent,
    transport::child_transport,
};
use crate::{cli_runtime::StderrTail, session_environment::Ambient};

/// Opens a new session of `policy`'s agent, spawned in `environment` as its
/// runs are, so that `policy` sees the select options it offers. `policy`
/// must be ready to spawn: one that needs `prepare` is prepared by its
/// caller.
pub(crate) async fn probe_session_config<P: AcpAgentPolicy>(
    policy: P,
    environment: &Ambient,
) -> Result<(), String> {
    let program = policy.label().program;
    let executable = policy.resolve_executable(environment)?;
    let plan = policy.spawn_plan()?;
    let cwd = plan.cwd.clone();
    let (mut child, stdin, stdout) = spawn_agent(
        program,
        &executable,
        plan,
        Stdio::piped(),
        /*before_spawn*/ None,
        environment,
    )?;
    let stderr = tokio::spawn(StderrTail::capture(child.stderr()));
    let opened = open_session(child_transport(stdin, stdout, program), policy, &cwd).await;
    child.terminate().await;
    let tail = stderr.await.map(StderrTail::finish).unwrap_or_default();
    opened.map_err(|detail| match tail.trim() {
        "" => detail,
        tail => format!("{detail}: {tail}"),
    })
}

/// The protocol half of [`probe_session_config`], over any transport.
async fn open_session<P: AcpAgentPolicy>(
    transport: impl ConnectTo<Client> + 'static,
    policy: P,
    cwd: &std::path::Path,
) -> Result<(), String> {
    let policy = std::sync::Mutex::new(policy);
    Client
        .v1()
        .name("rho")
        .connect_with(transport, async |cx| {
            handshake::initialize(&cx, &policy, Attendance::Unattended, /*adapter*/ None).await?;
            let meta = policy.lock().expect("ACP policy").session_meta();
            handshake::new_session(
                &cx,
                NewSessionRequest::new(cwd.to_path_buf()).meta(meta),
                &policy,
            )
            .await?;
            Ok(())
        })
        .await
        .map_err(|error| error.to_string())
}