rho-coding-agent 3.10.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
//! The agent's calls of served tools that no MCP call claimed yet, for the
//! bridge's calls to draw their cards under.
//!
//! An MCP call over the stdio bridge names no tool call: agy (Antigravity's
//! ACP server 1.5.21) sends `tools/call` with only its own conversation
//! ids and a progress token in `_meta`. It does announce each call on the
//! connection first (`tool_call`, named `mcp_rho_<tool>`), with the call's
//! arguments in its `rawInput` and keys of agy's own besides, such as
//! `toolSummary`. So the bridge pairs an MCP call with the oldest announced
//! call of the same tool that no MCP call claimed, the agent has not ended,
//! and whose `rawInput` carries the MCP call's arguments; failing that,
//! with the oldest of the tool's unclaimed calls, as the agent runs a
//! tool's calls in the order it announces them.

use std::{collections::VecDeque, sync::Mutex, time::Duration};

use agent_client_protocol::v1::schema::{SessionUpdate, ToolCallId, ToolCallStatus};
use serde_json::{Map, Value};
use tokio::sync::Notify;

/// How long an MCP call waits for the agent's announcement of it. A
/// tripwire, not a wait anyone sees: the agent sends its announcement
/// before its MCP call, and agy 1.5.21 asks permission for every MCP call
/// in both modes rho runs it in, an ask rho answers only once it read the
/// announcement, so the announcement is in by the time the call comes. The
/// wait covers an agy that stops asking, whose announcement and call reach
/// rho on two pipes at once, on one machine: milliseconds apart, so 1 s is
/// room many times over. Past it the call draws under a key of its own,
/// and the agent's card shows beside it: a second card, not a lost call.
pub(super) const ANNOUNCEMENT_WAIT: Duration = Duration::from_secs(1);

/// One announced call: of which tool, its id, and its `rawInput`.
struct Announcement {
    tool: String,
    id: ToolCallId,
    input: Option<Value>,
}

/// The announced calls, oldest first.
#[derive(Default)]
pub(super) struct Announced {
    calls: Mutex<VecDeque<Announcement>>,
    heard: Notify,
}

impl Announced {
    /// The agent's `update`, `tool` being the served tool it announces a
    /// call of, if any: a call announced running is kept for an MCP call
    /// to claim; the agent's end of a call, claimed or not, withdraws it.
    pub(super) fn hear(&self, update: &SessionUpdate, tool: Option<&str>) {
        match (update, tool) {
            (SessionUpdate::ToolCall(call), Some(tool))
                if matches!(
                    call.status,
                    ToolCallStatus::Pending | ToolCallStatus::InProgress
                ) =>
            {
                self.announce(tool, call.tool_call_id.clone(), call.raw_input.clone());
            }
            (SessionUpdate::ToolCallUpdate(update), _)
                if matches!(
                    update.fields.status,
                    Some(ToolCallStatus::Completed | ToolCallStatus::Failed)
                ) =>
            {
                self.ended(&update.tool_call_id);
            }
            // A call of no served tool, one announced as it ended, for
            // which no MCP call is to come, or an update that ends nothing.
            _ => {}
        }
    }

    /// The agent announced its call `id` of tool `tool`, with `input`.
    pub(super) fn announce(&self, tool: &str, id: ToolCallId, input: Option<Value>) {
        self.calls
            .lock()
            .expect("announced calls")
            .push_back(Announcement {
                tool: tool.to_owned(),
                id,
                input,
            });
        self.heard.notify_waiters();
    }

    /// The agent ended its call `id`, claimed or not.
    fn ended(&self, id: &ToolCallId) {
        self.calls
            .lock()
            .expect("announced calls")
            .retain(|announced| announced.id != *id);
    }

    /// The unclaimed call of `tool` with `arguments` (see the module docs),
    /// claimed now, waiting for one up to [`ANNOUNCEMENT_WAIT`]; `None`
    /// past it.
    pub(super) async fn claim(
        &self,
        tool: &str,
        arguments: &Map<String, Value>,
    ) -> Option<ToolCallId> {
        tokio::time::timeout(ANNOUNCEMENT_WAIT, async {
            loop {
                // Listening before looking, so an announcement between the
                // two still wakes it.
                let heard = self.heard.notified();
                tokio::pin!(heard);
                heard.as_mut().enable();
                if let Some(id) = self.take(tool, arguments) {
                    return id;
                }
                heard.await;
            }
        })
        .await
        .ok()
    }

    fn take(&self, tool: &str, arguments: &Map<String, Value>) -> Option<ToolCallId> {
        let mut calls = self.calls.lock().expect("announced calls");
        let of_tool = |announced: &Announcement| announced.tool == tool;
        let at = calls
            .iter()
            .position(|announced| of_tool(announced) && carries(announced, arguments))
            .or_else(|| calls.iter().position(of_tool))?;
        calls.remove(at).map(|announced| announced.id)
    }
}

/// Whether `announced`'s `rawInput` holds every one of `arguments`.
fn carries(announced: &Announcement, arguments: &Map<String, Value>) -> bool {
    let Some(Value::Object(input)) = &announced.input else {
        return false;
    };
    arguments
        .iter()
        .all(|(key, value)| input.get(key) == Some(value))
}

#[cfg(test)]
#[path = "announced_tests.rs"]
mod tests;