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};
pub(in crate::app::daemon_host::sessions) enum ServedAsk {
Approval(PendingApproval),
Question {
call: ToolCallId,
input: PendingToolHostInput,
},
Ended(ToolCallId),
}
pub(in crate::app::daemon_host::sessions) struct ServedApproval {
pub(in crate::app::daemon_host::sessions) call: Option<ToolCallId>,
pub(in crate::app::daemon_host::sessions) approval: PendingApproval,
}
impl ServedApproval {
pub(in crate::app::daemon_host::sessions) fn answer(mut self, decision: ApprovalDecision) {
let _ = self.approval.respond(decision);
}
}
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 {
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");
}
}
}
pub(super) type TurnHost = Result<ToolHost, String>;
pub(super) type ToolsByName = Arc<HashMap<String, Arc<dyn RhoTool>>>;
pub(super) struct TurnCalls {
listed: Arc<[Tool]>,
tools: ToolsByName,
scope: CardScope,
host: watch::Receiver<TurnHost>,
asks: mpsc::UnboundedSender<ServedAsk>,
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> {
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;
let id = ToolCallId::from_string(cards.key().to_string()).unwrap_or_default();
let arguments = Value::Object(arguments);
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,
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);
}
}
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);
}
};
let _ended = EndedCall {
asks: asks.clone(),
call: id.clone(),
};
loop {
tokio::select! {
() = 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),
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)
}
fn failed_output(message: String) -> ToolCompletion {
ToolCompletion::Completed(ToolOutput::text(message).failed())
}
struct EndedCall {
asks: mpsc::UnboundedSender<ServedAsk>,
call: ToolCallId,
}
impl Drop for EndedCall {
fn drop(&mut self) {
let _ = self.asks.send(ServedAsk::Ended(self.call.clone()));
}
}
fn result_of(completion: &ToolCompletion) -> CallToolResult {
let output = match completion {
ToolCompletion::Completed(output) => output,
ToolCompletion::Failure(failure) => return failed(failure.message().to_owned()),
ToolCompletion::Unavailable => return failed("tool is unavailable".to_owned()),
_ => 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)])
}