rho-coding-agent 3.13.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
//! Steering the running turn of a session an agent of another runtime runs.
//!
//! On ACP v2 a steer goes into the turn as another `session/prompt`, which
//! the agent inserts into the work it is busy with (see
//! `acp_runtime::v2::turns`). The session's turn opens a port into its run's
//! message inbox, the one background deliveries go through, and closes it
//! as the run ends; a steer outside a turn finds none. The steer shows as a
//! user message carrying its id once the agent took it, as a Rho session's
//! shows once it applies, and its person may withdraw it until the run sends
//! it. Whether the session steers at all is its capability table's say
//! ([`super::capabilities`]): its adapter must have answered ACP v2.

use std::{collections::HashMap, sync::Mutex};

use rho_protocol::{self as wire, SteerId, UnsteerOutcome};

use crate::{
    cli_runtime::{
        parent_messages::{
            ParentMessage, ParentMessageHandle, ParentMessageSendError, SteerProgress, SteerTicket,
            PARENT_MESSAGE_QUEUE_CAPACITY,
        },
        CliPrompt,
    },
    run_artifacts::AttachmentEvent,
};

/// How many steers a turn's run holds that it has not taken, withdrawn ones
/// included until it skips them: all but one place of its queue
/// ([`PARENT_MESSAGE_QUEUE_CAPACITY`]), which background results share and
/// which they never hold more than one place of, sending one at a time
/// ([`super::acp_background`]). So a steer never finds the queue full of
/// results, nor do results find it full of steers.
pub(super) const STEER_SLOTS: usize = PARENT_MESSAGE_QUEUE_CAPACITY - 1;

/// What a steer says if its turn ends before the agent took it.
const UNDELIVERED: &str =
    "a steer was not delivered: the turn ended before the agent took it; send it again";

/// The session's steer port, open while one of its turns runs.
#[derive(Default)]
pub(super) struct AcpSteers(Mutex<Option<TurnPort>>);

/// One turn's port: its run's inbox, and the steers sent into it.
struct TurnPort {
    messages: ParentMessageHandle,
    steers: HashMap<SteerId, SteerTicket>,
}

/// Why a steer reached no turn.
#[derive(Debug, PartialEq, Eq)]
pub(super) enum AcpSteerError {
    /// No turn runs, or its run takes no more messages.
    NoTurn,
    /// The run holds [`STEER_SLOTS`] steers it has not taken.
    QueueFull,
}

impl AcpSteers {
    /// A turn starts: steers reach its run through `messages` until it
    /// ends.
    pub(super) fn open(&self, messages: ParentMessageHandle) {
        *self.lock() = Some(TurnPort {
            messages,
            steers: HashMap::new(),
        });
    }

    /// The turn ended: no later steer reaches it.
    pub(super) fn close(&self) {
        *self.lock() = None;
    }

    /// Sends a steer, `content`, into the running turn, and returns its id;
    /// clients see `shown`, the steer as sent before rho named its sender
    /// in `content`, once the agent took it.
    pub(super) fn steer(
        &self,
        content: CliPrompt,
        shown: Vec<wire::ContentBlock>,
    ) -> Result<SteerId, AcpSteerError> {
        let mut port = self.lock();
        let port = port.as_mut().ok_or(AcpSteerError::NoTurn)?;
        if port
            .steers
            .values()
            .filter(|ticket| ticket.queued())
            .count()
            >= STEER_SLOTS
        {
            return Err(AcpSteerError::QueueFull);
        }
        let id = SteerId::new(format!("acp-steer-{}", uuid::Uuid::new_v4()));
        let shown = AttachmentEvent::Steered {
            steer: id.clone(),
            content: shown,
        };
        let (message, ticket) =
            ParentMessage::steer(content.into_blocks(), vec![shown], UNDELIVERED.to_owned());
        port.messages
            .send_message(message)
            .map_err(|refused| match refused {
                ParentMessageSendError::Closed => AcpSteerError::NoTurn,
                ParentMessageSendError::QueueFull => AcpSteerError::QueueFull,
            })?;
        port.steers.insert(id.clone(), ticket);
        Ok(id)
    }

    /// Withdraws steer `id` if the run has yet to send it, and says what
    /// became of it.
    pub(super) fn unsteer(&self, id: &SteerId) -> Result<UnsteerOutcome, AcpSteerError> {
        let port = self.lock();
        let port = port.as_ref().ok_or(AcpSteerError::NoTurn)?;
        let Some(ticket) = port.steers.get(id) else {
            return Ok(UnsteerOutcome::NotFound);
        };
        Ok(match ticket.withdraw() {
            SteerProgress::Queued | SteerProgress::Withdrawn | SteerProgress::Dropped => {
                UnsteerOutcome::Withdrawn
            }
            SteerProgress::Sent => UnsteerOutcome::Delivered,
            SteerProgress::Applied => UnsteerOutcome::Applied,
        })
    }

    fn lock(&self) -> std::sync::MutexGuard<'_, Option<TurnPort>> {
        self.0.lock().expect("ACP steers")
    }
}

#[cfg(test)]
#[path = "acp_steer_tests.rs"]
mod tests;