rho-coding-agent 3.13.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
//! The bridge's calls that outlast one MCP call, and [`AWAIT_TOOL`], which
//! waits for them.
//!
//! agy cuts an MCP call off at three minutes, whatever the call reports:
//! `MCP tool call to server "rho" timed out after 3m0s: context deadline
//! exceeded`, recorded against Antigravity's ACP server 1.5.21, which
//! neither progress notifications nor `_meta.timeout*` moved. A rho call
//! can run longer, as one waiting on a person or a subagent does. So each
//! bridge call runs on a task of its own; the MCP call waits for it up to
//! [`CALL_WAIT`], then answers that it is still running, with an id, while
//! the call runs on, parked. `await` with that id waits up to [`CALL_WAIT`]
//! more, and answers with the call's result or the same continuation.
//!
//! A parked call lasts only as long as the run: the run's end stops it, as
//! it stops every call. One run may hold several of agy's turns, as when
//! rho sends background results as a follow-up prompt, and the run ends
//! only after the last, so the answers do not promise the call stops with
//! the turn: they tell agy to `await` it before ending its turn, since a
//! call still running then may be stopped. A call that ended stays
//! awaitable until the run ends, but only running calls count toward
//! [`MAX_PARKED_CALLS`]. The call keeps the one card it drew from its
//! start, which its end finishes, or the run's end shows interrupted (see
//! `super::CallCards` and the renderer's `run_ended`); an `await` draws
//! none of its own
//! ([`crate::cli_runtime::agent_event::AgentEvent::ServedHidden`]).
//!
//! agy is blocked only while an MCP call of its own is outstanding, the
//! call's or an `await`: once it has the still-running answer, it is free
//! to go on while the parked call runs, so the call no longer counts as
//! blocking it (the bridge's `call`, [`super::AgentTools::request`]). Each
//! answer goes back by [`ANSWER_BY`] after its call arrived, readied or
//! not, so that readying it never costs agy the answer.

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

use futures_util::future::BoxFuture;
use rmcp::model::{CallToolResult, ContentBlock, Tool};
use schemars::JsonSchema;
use serde::Deserialize;
use serde_json::{json, Map, Value};
use tokio::sync::watch;

use super::announced::ANNOUNCEMENT_WAIT;

/// The tool that waits for a parked call, as the bridge lists it.
pub(crate) const AWAIT_TOOL: &str = "await";

/// agy's cut-off on one MCP call, 3 minutes from when it sends the call
/// (recorded in the module docs).
pub(super) const AGENT_CALL_LIMIT: Duration = Duration::from_secs(180);

/// What an MCP call over the bridge keeps clear of [`AGENT_CALL_LIMIT`]:
/// what agy's clock counts and the call's wait ([`CALL_WAIT`]) does not, up
/// to [`ANNOUNCEMENT_WAIT`] (1 s) for the call's announcement before the call
/// starts, and the answer's trip back through the relay and agy, both
/// pipes on one machine. 30 s leaves that room many times over, since an
/// answer past agy's cut-off is lost for good, while a shorter wait only
/// costs one more `await`.
const CALL_MARGIN: Duration = Duration::from_secs(30);

/// How long one MCP call over the bridge waits for its rho call: 150 s,
/// [`CALL_MARGIN`] short of agy's cut-off.
pub(super) const CALL_WAIT: Duration =
    Duration::from_secs(AGENT_CALL_LIMIT.as_secs() - CALL_MARGIN.as_secs());

/// How long after an MCP call over the bridge arrives its answer goes back,
/// whether or not the tools readied it (`super::AgentRequest::answer_by`):
/// 165 s, half of [`CALL_MARGIN`] short of agy's cut-off. The call's own
/// wait ends by [`ANNOUNCEMENT_WAIT`] and [`CALL_WAIT`] after it arrives
/// (151 s), so readying gets at least the 14 s between, while the other
/// half of the margin, 15 s, still covers the answer's trip back over the
/// pipes many times over.
pub(super) const ANSWER_BY: Duration =
    Duration::from_secs(AGENT_CALL_LIMIT.as_secs() - CALL_MARGIN.as_secs() / 2);

// [`ANSWER_BY`] falls between the end of the call's own wait and agy's
// cut-off, with a third of [`CALL_MARGIN`] (10 s) to spare on each side:
// readying, which takes the turn's slot back, gets that long at least, and
// the answer's trip back, milliseconds on one machine, that long many times
// over. Changing one of the waits so that either side shrinks fails the
// build rather than costing agy its answers.
const _: () = {
    let call_ends = CALL_WAIT.as_secs() + ANNOUNCEMENT_WAIT.as_secs();
    let room = CALL_MARGIN.as_secs() / 3;
    assert!(
        ANSWER_BY.as_secs() >= call_ends + room,
        "ANSWER_BY leaves readying too little room past CALL_WAIT and ANNOUNCEMENT_WAIT"
    );
    assert!(
        AGENT_CALL_LIMIT.as_secs() >= ANSWER_BY.as_secs() + room,
        "ANSWER_BY leaves the answer too little room before agy's cut-off"
    );
};

/// How many parked calls may still be running at once. Not measured: a
/// tripwire sized well past what one turn needs, since a call parks only
/// after running [`CALL_WAIT`] and the answer asks agy to await it before
/// it ends its turn; a run with this many running unawaited has lost track
/// of them. Each costs one entry and the call's own task, which runs
/// either way; past it, the call's answer names the limit. A call that
/// ended no longer counts: its entry is only its result, kept for `await`
/// until the run ends.
const MAX_PARKED_CALLS: usize = 16;

/// [`AWAIT_TOOL`]'s arguments.
#[derive(Deserialize, JsonSchema)]
struct AwaitArgs {
    /// The id a still-running answer gave.
    id: String,
}

/// A call's result, once it ended.
type Done = watch::Receiver<Option<CallToolResult>>;

/// A parked call.
struct ParkedCall {
    tool: String,
    done: Done,
}

impl ParkedCall {
    /// Whether the call still runs: its task holds the sender until it
    /// ends, with its result or by a panic.
    fn running(&self) -> bool {
        self.done.has_changed().is_ok()
    }
}

/// The run's parked calls, by id.
#[derive(Default)]
pub(super) struct Parked {
    calls: Mutex<HashMap<String, ParkedCall>>,
}

impl Parked {
    /// The answer to the MCP call of `call`, a call of `tool`: its result
    /// once it ends within [`CALL_WAIT`], or the continuation that parks
    /// it.
    pub(super) async fn run(
        &self,
        tool: &str,
        call: BoxFuture<'static, CallToolResult>,
    ) -> CallToolResult {
        let (ended, done) = watch::channel(None);
        // On a task of its own: it runs on past this MCP call, and agy
        // drops the request it cut off.
        tokio::spawn(async move {
            let _ = ended.send(Some(call.await));
        });
        let done = match waited(done).await {
            Waited::Ended(result) => return result,
            Waited::Running(done) => done,
        };
        let mut calls = self.calls.lock().expect("parked calls");
        let running = calls.values().filter(|call| call.running()).count();
        if running >= MAX_PARKED_CALLS {
            return failed(format!(
                "rho's `{tool}` call is still running after {} s, but rho keeps at most \
                 {MAX_PARKED_CALLS} running calls waiting for `{AWAIT_TOOL}` (MAX_PARKED_CALLS) \
                 and {running} run already, so this one cannot: rho shows its end, but its \
                 result will not reach you. Call `{AWAIT_TOOL}` on the waiting calls first.",
                CALL_WAIT.as_secs(),
            ));
        }
        let id = format!("call-{}", uuid::Uuid::new_v4().simple());
        calls.insert(
            id.clone(),
            ParkedCall {
                tool: tool.to_owned(),
                done,
            },
        );
        still_running(tool, &id)
    }

    /// The answer to an [`AWAIT_TOOL`] call with `arguments`.
    pub(super) async fn wait(&self, arguments: Map<String, Value>) -> CallToolResult {
        let id = match serde_json::from_value::<AwaitArgs>(Value::Object(arguments)) {
            Ok(AwaitArgs { id }) => id,
            Err(error) => {
                return failed(format!(
                    "`{AWAIT_TOOL}` needs the `id` a still-running call gave: {error}"
                ))
            }
        };
        let id = id.as_str();
        let parked = {
            let calls = self.calls.lock().expect("parked calls");
            calls
                .get(id)
                .map(|call| (call.tool.clone(), call.done.clone()))
        };
        let Some((tool, done)) = parked else {
            return failed(format!(
                "no call `{id}` waits: it was awaited to its end already, or never parked"
            ));
        };
        match waited(done).await {
            Waited::Ended(result) => {
                self.calls.lock().expect("parked calls").remove(id);
                result
            }
            Waited::Running(_) => still_running(&tool, id),
        }
    }
}

/// How a wait for a call ended.
enum Waited {
    Ended(CallToolResult),
    /// Still running after [`CALL_WAIT`].
    Running(Done),
}

/// Waits up to [`CALL_WAIT`] for the call `done` tells the end of.
async fn waited(mut done: Done) -> Waited {
    let ended = tokio::time::timeout(CALL_WAIT, async {
        done.wait_for(Option::is_some)
            .await
            .map(|result| (*result).clone())
    })
    .await;
    match ended {
        Ok(Ok(Some(result))) => Waited::Ended(result),
        // The call's task ended without a result: it panicked.
        Ok(Ok(None) | Err(_)) => {
            Waited::Ended(failed("the call ended without a result".to_owned()))
        }
        Err(_elapsed) => Waited::Running(done),
    }
}

/// The continuation for call `id` of `tool`, still running, with the id
/// in its structured content too.
fn still_running(tool: &str, id: &str) -> CallToolResult {
    let mut result = CallToolResult::success(vec![ContentBlock::text(format!(
        "rho's `{tool}` call is still running after {} s, the longest one call of rho's tools \
         waits here. Call `{AWAIT_TOOL}` with {} until it returns the call's result before \
         ending your turn: a call left running when your turn ends may be stopped. Each \
         `{AWAIT_TOOL}` waits up to {} s more.",
        CALL_WAIT.as_secs(),
        json!({"id": id}),
        CALL_WAIT.as_secs(),
    ))]);
    result.structured_content = Some(json!({"id": id}));
    result
}

/// [`AWAIT_TOOL`] as the bridge lists it.
pub(super) fn await_tool() -> Tool {
    let Ok(Value::Object(schema)) = serde_json::to_value(schemars::schema_for!(AwaitArgs)) else {
        unreachable!("a derived schema is a JSON object");
    };
    Tool::new(
        AWAIT_TOOL,
        format!(
            "Waits for a call of rho's tools that is still running. One call of rho's tools \
             waits at most {} s for its result, short of the agent's own limit on an MCP call; \
             a call that runs longer, such as one waiting on the person or a subagent, answers \
             that it is still running, with an `id`. Call this with that `id` to wait up to {} \
             s more: it returns the call's result once the call ends, or the same \
             still-running answer. Call this until it returns the result before ending your \
             turn: a call left running when your turn ends may be stopped.",
            CALL_WAIT.as_secs(),
            CALL_WAIT.as_secs(),
        ),
        schema,
    )
}

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

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