rho-coding-agent 3.10.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
//! The agent's calls of the tools the run serves it, whose cards the served
//! calls draw ([`super::AgentEvent::Served`]) in place of the agent's own.
//!
//! The agent announces a call (`tool_call`) before it sends the call to the
//! run (`tools/call`), and ends its card once the call's result came back.
//! Its card is held from the announcement on, so nothing generic shows
//! while the call starts; once the served call draws a card, the agent's
//! updates of the call are dropped. A call the agent ends before a served
//! call drew anything, as one the run cancelled or refused before it ran,
//! shows the agent's card after all, closed as the agent closed it, and a
//! served card that comes for it later is dropped, so the closed card is
//! not opened again. A call still held as the turn or the run ends shows
//! interrupted. So no attempt goes unshown and none stays open.
//!
//! A served call may draw before the agent's announcement is rendered, as
//! the two arrive on different paths: a call drawn first is never held.
//!
//! The renderer counts these calls against its budget of tool calls in
//! flight ([`super::render::MAX_ACTIVE_TOOLS`]).
//!
//! A served call's own card stays open from its start to its end, which
//! may come after the agent ended its call, as for a call the stdio bridge
//! parked ([`OpenCards`]); the call stays tracked, in its slot of the
//! budget, until then ([`ServedState::AgentEnded`]), so its later cards
//! update and end the card it drew. The run's end stops every call still
//! running, but such a call draws its end only once the run stopped
//! rendering, so the run's end closes the cards still open, interrupted.

use std::collections::HashMap;

use agent_client_protocol::v1::schema::ToolCallId;
use rho_protocol::display::ToolCard;

use super::tool_cards::StartedTool;

/// Where the agent's card of one call of a served tool stands.
#[derive(Debug)]
pub(super) enum ServedState {
    /// Announced, and not drawn by a served call yet: the agent's card as
    /// it stands, which shows should the agent end the call first.
    Held(StartedTool),
    /// Drawn by a served call, until the agent ends its own card.
    Drawn,
    /// Drawn, and ended by the agent while the served call's own card is
    /// still open, as for a call the stdio bridge parked: tracked, in its
    /// slot of the budget, until the served call's last card.
    AgentEnded,
    /// Ended by the agent before a served call drew it, its card shown as
    /// the agent's: the served call's cards are dropped until its last.
    Released,
}

/// The run's served calls, as far as the agent's cards of them go.
#[derive(Debug, Default)]
pub(super) struct ServedCalls {
    calls: HashMap<ToolCallId, ServedState>,
}

impl ServedCalls {
    /// How many calls are tracked, which count against the renderer's
    /// budget.
    pub(super) fn len(&self) -> usize {
        self.calls.len()
    }

    /// Where call `id` stands, if it is a tracked served call.
    pub(super) fn state(&self, id: &ToolCallId) -> Option<&ServedState> {
        self.calls.get(id)
    }

    /// Call `id`'s held card, to bring up to date.
    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
            }
        }
    }

    /// Puts call `id` in `state`, returning where it stood.
    pub(super) fn set(&mut self, id: ToolCallId, state: ServedState) -> Option<ServedState> {
        self.calls.insert(id, state)
    }

    /// Forgets call `id`: its last card, the agent's or the served call's,
    /// was drawn.
    pub(super) fn forget(&mut self, id: &ToolCallId) -> Option<ServedState> {
        self.calls.remove(id)
    }

    /// Forgets one released call, to make room in the budget; false when
    /// there is none. A served card that comes for it later shows.
    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())
    }

    /// Releases call `id`, if held: its card, as it stands, shows as the
    /// agent's, and the served call's cards are dropped from now on.
    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
            }
        }
    }

    /// Releases every held call, in id order, with its card as it stands.
    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()
    }
}

/// The served calls' own cards drawn and not yet ended, with the card each
/// last showed. An entry lasts only while its call runs, so these are
/// bounded by the calls running in the run, parked ones included.
#[derive(Debug, Default)]
pub(super) struct OpenCards {
    cards: HashMap<ToolCallId, ToolCard>,
}

impl OpenCards {
    /// Call `id`'s card shows `card`, still running.
    pub(super) fn drew(&mut self, id: &ToolCallId, card: &ToolCard) {
        self.cards.insert(id.clone(), card.clone());
    }

    /// Whether call `id`'s card is drawn and not yet ended.
    pub(super) fn is_open(&self, id: &ToolCallId) -> bool {
        self.cards.contains_key(id)
    }

    /// Call `id`'s card ended.
    pub(super) fn ended(&mut self, id: &ToolCallId) {
        self.cards.remove(id);
    }

    /// The cards still open, in id order, which no call will end now.
    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
    }
}