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;
pub(super) const ANNOUNCEMENT_WAIT: Duration = Duration::from_secs(1);
struct Announcement {
tool: String,
id: ToolCallId,
input: Option<Value>,
}
#[derive(Default)]
pub(super) struct Announced {
calls: Mutex<VecDeque<Announcement>>,
heard: Notify,
}
impl Announced {
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);
}
_ => {}
}
}
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();
}
fn ended(&self, id: &ToolCallId) {
self.calls
.lock()
.expect("announced calls")
.retain(|announced| announced.id != *id);
}
pub(super) async fn claim(
&self,
tool: &str,
arguments: &Map<String, Value>,
) -> Option<ToolCallId> {
tokio::time::timeout(ANNOUNCEMENT_WAIT, async {
loop {
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)
}
}
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;