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;
pub(crate) const AWAIT_TOOL: &str = "await";
pub(super) const AGENT_CALL_LIMIT: Duration = Duration::from_secs(180);
const CALL_MARGIN: Duration = Duration::from_secs(30);
pub(super) const CALL_WAIT: Duration =
Duration::from_secs(AGENT_CALL_LIMIT.as_secs() - CALL_MARGIN.as_secs());
pub(super) const ANSWER_BY: Duration =
Duration::from_secs(AGENT_CALL_LIMIT.as_secs() - CALL_MARGIN.as_secs() / 2);
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"
);
};
const MAX_PARKED_CALLS: usize = 16;
#[derive(Deserialize, JsonSchema)]
struct AwaitArgs {
id: String,
}
type Done = watch::Receiver<Option<CallToolResult>>;
struct ParkedCall {
tool: String,
done: Done,
}
impl ParkedCall {
fn running(&self) -> bool {
self.done.has_changed().is_ok()
}
}
#[derive(Default)]
pub(super) struct Parked {
calls: Mutex<HashMap<String, ParkedCall>>,
}
impl Parked {
pub(super) async fn run(
&self,
tool: &str,
call: BoxFuture<'static, CallToolResult>,
) -> CallToolResult {
let (ended, done) = watch::channel(None);
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)
}
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),
}
}
}
enum Waited {
Ended(CallToolResult),
Running(Done),
}
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),
Ok(Ok(None) | Err(_)) => {
Waited::Ended(failed("the call ended without a result".to_owned()))
}
Err(_elapsed) => Waited::Running(done),
}
}
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
}
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;