rho-coding-agent 3.10.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
//! One turn's calls of the tools rho serves the agent. Each runs on the
//! turn's tool host, on a task the ACP driver spawned; what it asks a
//! person it hands the turn ([`ServedAsk`]), which puts it to the person as
//! the session's input request and hands the answer back
//! ([`ServedApproval::answer`], [`ServedQuestion::answer`]). Each draws its
//! card in the run's journal as it runs (see `cards.rs`), and counts as
//! running until it ends, as each of the agent's requests to the tools
//! counts until its answer readies, and the agent's own calls as its run
//! tells them (`agent_activity`, which the session's budget and background
//! delivery read). A budgeted turn may lend its slot while the agent waits
//! on the tools, so each request takes one back for the turn before its
//! answer goes back ([`ModelSlot::request`]).

use std::{collections::HashMap, sync::Arc};

use futures_util::future::BoxFuture;
use rho_sdk::{
    tool::{Tool as RhoTool, ToolOutput},
    ApprovalDecision, HostInputRefusal, HostInputResponse, PendingApproval, PendingToolHostInput,
    ToolCallId, ToolCompletion, ToolHost, ToolHostCall, ToolHostEvent,
};
use rho_tools::cancellation::RunCancellation;
use rmcp::model::{CallToolResult, ContentBlock, Tool};
use serde_json::Value;
use tokio::sync::{mpsc, watch};

use super::{
    super::{agent_activity::CallRunning, budget::ModelSlot},
    cards::{CallCard, CardScope},
};
use crate::acp_runtime::agent_tools::{AgentRequest, AgentToolCall, AgentTools};

/// What a served call hands the turn.
pub(in crate::app::daemon_host::sessions) enum ServedAsk {
    /// An approval a call needs, which names the call.
    Approval(PendingApproval),
    /// A question call `call` asks.
    Question {
        call: ToolCallId,
        input: PendingToolHostInput,
    },
    /// Call `call` ended, however it did: nobody need answer what it still
    /// asks.
    Ended(ToolCallId),
}

/// A served call's approval the person has yet to answer.
pub(in crate::app::daemon_host::sessions) struct ServedApproval {
    /// The call that needs it, when the request names one.
    pub(in crate::app::daemon_host::sessions) call: Option<ToolCallId>,
    pub(in crate::app::daemon_host::sessions) approval: PendingApproval,
}

impl ServedApproval {
    /// Hands the call the person's `decision`. A call that stopped waiting
    /// takes none.
    pub(in crate::app::daemon_host::sessions) fn answer(mut self, decision: ApprovalDecision) {
        let _ = self.approval.respond(decision);
    }
}

/// A served call's question the person has yet to answer.
pub(in crate::app::daemon_host::sessions) struct ServedQuestion {
    pub(in crate::app::daemon_host::sessions) call: ToolCallId,
    pub(in crate::app::daemon_host::sessions) input: PendingToolHostInput,
}

impl ServedQuestion {
    /// Hands the call the person's `answer`, or their refusal. A call that
    /// stopped waiting takes none.
    pub(in crate::app::daemon_host::sessions) fn answer(
        mut self,
        answer: Result<HostInputResponse, HostInputRefusal>,
    ) {
        let delivered = match answer {
            Ok(response) => self.input.respond(response),
            Err(refusal) => self.input.refuse(refusal),
        };
        if let Err(error) = delivered {
            tracing::debug!(%error, "a served tool's question took no answer");
        }
    }
}

/// The host a turn's calls run on, or why the turn has none, which each
/// call then fails with.
pub(super) type TurnHost = Result<ToolHost, String>;

/// The served tools, by name.
pub(super) type ToolsByName = Arc<HashMap<String, Arc<dyn RhoTool>>>;

/// One turn's side of the served tools: what its run serves the agent.
pub(super) struct TurnCalls {
    listed: Arc<[Tool]>,
    /// The tools, whose start metadata draws each call's first card.
    tools: ToolsByName,
    /// What the calls' cards draw with.
    scope: CardScope,
    /// The turn's host as it stands: the turn swaps it when its mode
    /// changes, as when the agent leaves plan mode. A call runs on the one
    /// it started on.
    host: watch::Receiver<TurnHost>,
    asks: mpsc::UnboundedSender<ServedAsk>,
    /// The session's slot in the agent budget, whose activity counts each
    /// call while it runs, and which each of the agent's requests takes
    /// back for a budgeted turn that lent it before its answer goes back.
    slot: Arc<ModelSlot>,
}

impl TurnCalls {
    pub(super) fn new(
        listed: Arc<[Tool]>,
        tools: ToolsByName,
        scope: CardScope,
        host: watch::Receiver<TurnHost>,
        asks: mpsc::UnboundedSender<ServedAsk>,
        slot: Arc<ModelSlot>,
    ) -> Self {
        Self {
            listed,
            tools,
            scope,
            host,
            asks,
            slot,
        }
    }
}

impl AgentTools for TurnCalls {
    fn list(&self) -> Vec<Tool> {
        self.listed.to_vec()
    }

    fn serves(&self, name: &str) -> bool {
        self.tools.contains_key(name)
    }

    fn call(&self, call: AgentToolCall) -> BoxFuture<'static, CallToolResult> {
        // The binding refuses a tool it does not serve before it calls.
        let Some(tool) = self.tools.get(&call.name) else {
            let message = format!("Unknown tool: {}", call.name);
            return Box::pin(std::future::ready(failed(message)));
        };
        let AgentToolCall {
            name,
            arguments,
            cancellation,
            cards,
        } = call;
        // The card's key, the agent's own id for the call, so the input
        // requests it opens name the call's card. The tool runs under it
        // too, so the work it starts names the call the card links.
        let id = ToolCallId::from_string(cards.key().to_string()).unwrap_or_default();
        let arguments = Value::Object(arguments);
        // Drawn before the call can ask anything, which names its card.
        let card = CallCard::start(
            cards,
            self.scope.clone(),
            id.clone(),
            &name,
            &arguments,
            tool.start_metadata(&arguments),
        );
        let started = ToolHostCall::new(name, arguments).with_id(id.clone());
        Box::pin(run_call(
            self.host.borrow().clone(),
            self.asks.clone(),
            id,
            started,
            cancellation,
            card,
            // Running from now until the call's future ends or drops.
            self.slot.activity().call_running(),
        ))
    }

    fn request(&self) -> AgentRequest {
        self.slot.request()
    }

    fn agent_calls(&self, running: usize) {
        self.slot.activity().set_agent_calls(running);
    }
}

/// Runs call `id`, `call`, on `host` until it ends or `cancellation`
/// fires, handing what it asks to the turn through `asks` and drawing its
/// `card` as it goes. It holds `_running` throughout, so the turn's
/// delivery of background results waits for it (see `acp_background`).
async fn run_call(
    host: TurnHost,
    asks: mpsc::UnboundedSender<ServedAsk>,
    id: ToolCallId,
    call: ToolHostCall,
    cancellation: RunCancellation,
    mut card: CallCard,
    _running: CallRunning,
) -> CallToolResult {
    let started = match &host {
        Ok(host) => host.start(call).map_err(|error| error.to_string()),
        Err(why) => Err(why.clone()),
    };
    let mut run = match started {
        Ok(run) => run,
        Err(why) => {
            let failure = failed_output(why);
            card.finished(&failure);
            return result_of(&failure);
        }
    };
    // However the call ends, dropped with its run too, the turn withdraws
    // what it still asks.
    let _ended = EndedCall {
        asks: asks.clone(),
        call: id.clone(),
    };
    loop {
        tokio::select! {
            // The run that served the call ended.
            () = cancellation.cancelled() => {
                run.cancel();
                break;
            }
            event = run.next_event() => match event {
                Some(ToolHostEvent::HostInputRequested(input)) => {
                    let _ = asks.send(ServedAsk::Question { call: id.clone(), input });
                }
                Some(ToolHostEvent::Progress(progress)) => card.progress(&progress),
                // An event a newer SDK adds.
                Some(_) => {}
                None => break,
            },
        }
    }
    let completion = match run.outcome().await {
        Ok(output) => ToolCompletion::Completed(output),
        Err(error) => failed_output(error.to_string()),
    };
    card.finished(&completion);
    result_of(&completion)
}

/// A call's failure with `message`, as its card draws it: the SDK builds a
/// run's failures alone, so as the call's failed output.
fn failed_output(message: String) -> ToolCompletion {
    ToolCompletion::Completed(ToolOutput::text(message).failed())
}

/// Tells the turn its call ended, as it drops.
struct EndedCall {
    asks: mpsc::UnboundedSender<ServedAsk>,
    call: ToolCallId,
}

impl Drop for EndedCall {
    fn drop(&mut self) {
        // A turn that ended withdrew everything already.
        let _ = self.asks.send(ServedAsk::Ended(self.call.clone()));
    }
}

/// The MCP result of a call that ended with `completion`: its text and
/// images, an error for a tool's failure.
fn result_of(completion: &ToolCompletion) -> CallToolResult {
    let output = match completion {
        ToolCompletion::Completed(output) => output,
        ToolCompletion::Failure(failure) => return failed(failure.message().to_owned()),
        // Neither is built for a served call, whose tool is served and
        // whose failures are its output (`failed_output`).
        ToolCompletion::Unavailable => return failed("tool is unavailable".to_owned()),
        // A result a newer SDK adds, which cannot be shown as success.
        _ => return failed("the call ended without a result".to_owned()),
    };
    let mut content = Vec::new();
    if !output.content().is_empty() || output.images().is_empty() {
        content.push(ContentBlock::text(output.content()));
    }
    content.extend(
        output
            .images()
            .iter()
            .map(|image| ContentBlock::image(image.data.clone(), image.mime_type.clone())),
    );
    if output.is_failure() {
        CallToolResult::error(content)
    } else {
        CallToolResult::success(content)
    }
}

fn failed(message: String) -> CallToolResult {
    CallToolResult::error(vec![ContentBlock::text(message)])
}