rho-coding-agent 3.11.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
//! Steps every ACP connection takes the same way, whichever protocol it
//! speaks ([`super::driver`] for v1, [`super::v2`] for v2): serving rho's
//! tools, a refused resume, the first prompt and a queued next turn, and how
//! a connection's end settles.

use super::{
    agent_tools::Served,
    driver::{render, DriverOutcome},
    handshake::error,
};
use crate::cli_runtime::{
    agent_event::{render::EventRenderer, AgentEvent},
    parent_messages::{Delivered, ParentMessage},
    status_sink::StatusSink,
    stream_effect::{StatusPatch, StreamEffect},
    CliPrompt, PromptBlock,
};
use agent_client_protocol::{v1::schema as v1, v2::schema as v2, Error, ErrorCode};
use rho_tools::cancellation::RunCancellation;

/// The tools the run serves its agent, declared over the connection when
/// the agent takes them there (`takes_over_connection`, the capability
/// `capability` names), else over a stdio bridge. One no bridge opens for is
/// told nothing of the tools, and the run says so.
pub(super) fn serve<'s>(
    served: Option<&'s Served>,
    takes_over_connection: bool,
    capability: &str,
    renderer: &mut EventRenderer,
    sink: &mut StatusSink,
) -> Option<&'s Served> {
    let served = served?;
    if takes_over_connection {
        return Some(served);
    }
    match served.open_bridge() {
        Ok(()) => Some(served),
        Err(why) => {
            render(renderer, sink, AgentEvent::Notice(format!("acp: the agent takes no MCP server over its connection ({capability}), and rho could not serve it one over stdio, so it gets none of rho's tools: {why}")));
            None
        }
    }
}

/// The run's error for a `session/resume` the agent refused. Its own
/// refusal, not a sign-in it wants, says the conversation is not there to
/// resume.
pub(super) fn resume_refused(sink: &mut StatusSink, refused: Error) -> Error {
    if refused.code != ErrorCode::AUTH_REQUIRED {
        sink.conversation_not_restored();
    }
    error(format!("acp: session/resume: {refused}"))
}

/// The blocks of the run's first prompt, in order: the background results
/// it carries as a text block of their own, ahead of the prompt's blocks,
/// so the agent reads where they end and the person's content begins.
pub(super) fn first_prompt(
    prompt: &CliPrompt,
    results: Option<&ParentMessage>,
) -> Vec<PromptBlock> {
    results
        .map(|results| PromptBlock::Text {
            text: results.framed(),
        })
        .into_iter()
        .chain(prompt.blocks().iter().cloned())
        .collect()
}

/// Converts `blocks` into ACP v1 prompt content blocks.
pub(super) fn v1_blocks(blocks: Vec<PromptBlock>) -> Vec<v1::ContentBlock> {
    blocks
        .into_iter()
        .map(|block| match block {
            PromptBlock::Text { text } => text.into(),
            PromptBlock::Image { mime_type, data } => {
                v1::ContentBlock::Image(v1::ImageContent::new(data, mime_type))
            }
        })
        .collect()
}

/// Converts `blocks` into ACP v2 prompt content blocks.
pub(super) fn v2_blocks(blocks: Vec<PromptBlock>) -> Vec<v2::ContentBlock> {
    blocks
        .into_iter()
        .map(|block| match block {
            PromptBlock::Text { text } => text.into(),
            PromptBlock::Image { mime_type, data } => {
                v2::ContentBlock::Image(v2::ImageContent::new(data, mime_type))
            }
        })
        .collect()
}

/// The first prompt is out: the results it carried are delivered, and the
/// run names the agent's `session`. Recorded only now: a later turn resumes
/// the session this names, and one that never took a prompt holds no
/// conversation to resume.
pub(super) fn prompt_sent(sink: &mut StatusSink, results: Option<ParentMessage>, session: &str) {
    if let Some(results) = results {
        delivered(sink, results, Delivered::NextTurn);
    }
    sink.apply_effect(StreamEffect::Status(StatusPatch {
        runtime_session_id: Some(session.to_owned()),
        ..StatusPatch::default()
    }));
}

/// A parent message reached the agent, `how` says.
pub(super) fn delivered(sink: &mut StatusSink, message: ParentMessage, how: Delivered) {
    for event in message.settle(how) {
        sink.apply_effect(StreamEffect::Attachment(event));
    }
}

/// How a connection that ended settles. Local cancellation is
/// authoritative on every path, not only when a stop reason arrives: an
/// agent that closes stdio, or a failed `session/cancel` send, still
/// settles as stopped (`stopped`), with the diagnostic kept.
pub(super) fn ended<T>(
    outcome: Result<T, Error>,
    cancellation: &RunCancellation,
    renderer: &mut EventRenderer,
    sink: &mut StatusSink,
    stopped: impl FnOnce(DriverOutcome) -> T,
) -> Result<T, String> {
    match outcome {
        Ok(outcome) => Ok(outcome),
        Err(source) if cancellation.is_cancelled() => {
            render(
                renderer,
                sink,
                AgentEvent::Notice(format!("acp: after cancellation: {source}")),
            );
            Ok(stopped(DriverOutcome::stopped(renderer, None)))
        }
        Err(source) => Err(format!("acp: {source}")),
    }
}