use std::collections::HashMap;
use agent_client_protocol::v1::schema::ToolCallId;
use rho_protocol::display::ToolCard;
use super::tool_cards::StartedTool;
#[derive(Debug)]
pub(super) enum ServedState {
Held(StartedTool),
Drawn,
AgentEnded,
Released,
}
#[derive(Debug, Default)]
pub(super) struct ServedCalls {
calls: HashMap<ToolCallId, ServedState>,
}
impl ServedCalls {
pub(super) fn len(&self) -> usize {
self.calls.len()
}
pub(super) fn state(&self, id: &ToolCallId) -> Option<&ServedState> {
self.calls.get(id)
}
pub(super) fn held_mut(&mut self, id: &ToolCallId) -> Option<&mut StartedTool> {
match self.calls.get_mut(id) {
Some(ServedState::Held(tool)) => Some(tool),
Some(ServedState::Drawn | ServedState::AgentEnded | ServedState::Released) | None => {
None
}
}
}
pub(super) fn set(&mut self, id: ToolCallId, state: ServedState) -> Option<ServedState> {
self.calls.insert(id, state)
}
pub(super) fn forget(&mut self, id: &ToolCallId) -> Option<ServedState> {
self.calls.remove(id)
}
pub(super) fn forget_a_released(&mut self) -> bool {
let released = self
.calls
.iter()
.find(|(_, state)| matches!(state, ServedState::Released))
.map(|(id, _)| id.clone());
released.is_some_and(|id| self.calls.remove(&id).is_some())
}
pub(super) fn release(&mut self, id: &ToolCallId) -> Option<StartedTool> {
let state = self.calls.get_mut(id)?;
match std::mem::replace(state, ServedState::Released) {
ServedState::Held(tool) => Some(tool),
other => {
*state = other;
None
}
}
}
pub(super) fn release_held(&mut self) -> Vec<(ToolCallId, StartedTool)> {
let mut held: Vec<ToolCallId> = self
.calls
.iter()
.filter(|(_, state)| matches!(state, ServedState::Held(_)))
.map(|(id, _)| id.clone())
.collect();
held.sort_by_key(|id| id.0.clone());
held.into_iter()
.filter_map(|id| self.release(&id).map(|tool| (id, tool)))
.collect()
}
}
#[derive(Debug, Default)]
pub(super) struct OpenCards {
cards: HashMap<ToolCallId, ToolCard>,
}
impl OpenCards {
pub(super) fn drew(&mut self, id: &ToolCallId, card: &ToolCard) {
self.cards.insert(id.clone(), card.clone());
}
pub(super) fn is_open(&self, id: &ToolCallId) -> bool {
self.cards.contains_key(id)
}
pub(super) fn ended(&mut self, id: &ToolCallId) {
self.cards.remove(id);
}
pub(super) fn take(&mut self) -> Vec<(ToolCallId, ToolCard)> {
let mut open: Vec<_> = std::mem::take(&mut self.cards).into_iter().collect();
open.sort_by(|(left, _), (right, _)| left.0.cmp(&right.0));
open
}
}