rho-coding-agent 3.10.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
//! Bounded parent → child text queue, independent of the child's wire protocol.
//!
//! A message is a parent's course correction ([`ParentMessage::parent`]),
//! framed and shown as one, or a message its host framed and renders
//! ([`ParentMessage::hosted`]), which tells the host once the run delivered
//! it.

use std::sync::{Arc, Mutex};
use tokio::sync::{mpsc, oneshot};

use rho_protocol::display::NotificationDelivery;

use crate::{presentation::parent_message_card, run_artifacts::AttachmentEvent};

/// Existing Claude receipt: eight course-corrections provide a small backlog
/// without letting a stuck child grow an unbounded queue.
pub(crate) const PARENT_MESSAGE_QUEUE_CAPACITY: usize = 8;

/// One message for the child's running turn.
pub(crate) struct ParentMessage(MessageKind);

enum MessageKind {
    /// A parent's course correction, shown as the parent's card.
    Parent(String),
    /// A message its host framed and renders.
    Hosted {
        /// The message as the agent reads it.
        framed: String,
        /// What the run records as it delivers it.
        shown: Vec<AttachmentEvent>,
        /// What the run says if it never delivers it.
        undelivered: String,
        /// Told once the run delivered it; dropped unsent when it never
        /// did.
        delivered: oneshot::Sender<()>,
    },
}

/// How the run delivered a message.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Delivered {
    /// Injected into the turn in flight.
    Steered,
    /// Sent as the next turn's prompt, or with the run's first prompt.
    NextTurn,
}

/// The host learns here whether the run delivered a message it sent.
pub(crate) type DeliveryReceipt = oneshot::Receiver<()>;

impl ParentMessage {
    /// `text` from the parent.
    pub(crate) fn parent(text: String) -> Self {
        Self(MessageKind::Parent(text))
    }

    /// A message the agent reads as `framed`, which the run records as
    /// `shown` once it delivered it, or tells of with the notice
    /// `undelivered` if it never does; and the receipt that says it did.
    pub(crate) fn hosted(
        framed: String,
        shown: Vec<AttachmentEvent>,
        undelivered: String,
    ) -> (Self, DeliveryReceipt) {
        let (delivered, receipt) = oneshot::channel();
        (
            Self(MessageKind::Hosted {
                framed,
                shown,
                undelivered,
                delivered,
            }),
            receipt,
        )
    }

    /// The message as the agent reads it.
    pub(crate) fn framed(&self) -> String {
        match &self.0 {
            MessageKind::Parent(text) => frame_parent_message(text),
            MessageKind::Hosted { framed, .. } => framed.clone(),
        }
    }

    /// The run delivered the message as `how` says: returns what it records
    /// of it, and tells a host that sent it.
    pub(crate) fn settle(self, how: Delivered) -> Vec<AttachmentEvent> {
        match self.0 {
            MessageKind::Parent(text) => {
                let (delivery, detail) = match how {
                    Delivered::Steered => (
                        NotificationDelivery::Received,
                        "steered into the running turn",
                    ),
                    Delivered::NextTurn => {
                        (NotificationDelivery::Queued, "sent as the next agent turn")
                    }
                };
                vec![AttachmentEvent::Message(Box::new(parent_message_card(
                    text,
                    delivery,
                    detail.into(),
                )))]
            }
            MessageKind::Hosted {
                shown, delivered, ..
            } => {
                // A host that stopped listening keeps nothing to put back.
                let _ = delivered.send(());
                shown
            }
        }
    }

    /// What the run says of a message it will never deliver.
    pub(crate) fn undelivered_notice(&self) -> &str {
        match &self.0 {
            MessageKind::Parent(_) => {
                "acp: a parent message was not delivered: the run ended before its next turn"
            }
            MessageKind::Hosted { undelivered, .. } => undelivered,
        }
    }
}

/// Cloneable port retained by the executor for a live delegated run.
#[derive(Clone, Debug)]
pub(crate) struct ParentMessageHandle {
    gate: Arc<Mutex<Option<mpsc::Sender<ParentMessage>>>>,
}

impl std::fmt::Debug for ParentMessage {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let text = match &self.0 {
            MessageKind::Parent(text) => text,
            MessageKind::Hosted { framed, .. } => framed,
        };
        f.debug_struct("ParentMessage")
            .field("text", text)
            .finish_non_exhaustive()
    }
}

impl ParentMessageHandle {
    /// Accept a parent's body while the port is live (see
    /// [`Self::send_message`]).
    pub(crate) fn send(&self, text: String) -> Result<(), ParentMessageSendError> {
        self.send_message(ParentMessage::parent(text))
    }

    /// Accept `message` while the port is live. Enqueueing happens under the
    /// gate lock, so a successful return means the consumer will see it: no
    /// sender clone outlives the lock to race a seal or a final-empty close.
    pub(crate) fn send_message(
        &self,
        message: ParentMessage,
    ) -> Result<(), ParentMessageSendError> {
        let gate = self.gate.lock().expect("parent message gate");
        let sender = gate.as_ref().ok_or(ParentMessageSendError::Closed)?;
        sender.try_send(message).map_err(|error| match error {
            mpsc::error::TrySendError::Full(_) => ParentMessageSendError::QueueFull,
            mpsc::error::TrySendError::Closed(_) => ParentMessageSendError::Closed,
        })
    }
}

/// Consumer paired with a parent-message port.
pub(crate) struct ParentMessageInbox {
    gate: Arc<Mutex<Option<mpsc::Sender<ParentMessage>>>>,
    receiver: mpsc::Receiver<ParentMessage>,
}

impl ParentMessageInbox {
    /// Reject later sends; bodies already queued remain drainable through recv.
    pub(crate) fn seal(&self) {
        *self.gate.lock().expect("parent message gate") = None;
    }

    /// The next queued message, or close the port when none is queued.
    /// Atomic with [`ParentMessageHandle::send_message`]: a racing send is
    /// either returned here (and the port stays open) or rejected as closed.
    pub(crate) fn take_next_or_close(&mut self) -> Option<ParentMessage> {
        let mut gate = self.gate.lock().expect("parent message gate");
        match self.receiver.try_recv() {
            Ok(message) => Some(message),
            Err(_) => {
                *gate = None;
                None
            }
        }
    }

    pub(crate) async fn recv(&mut self) -> Option<ParentMessage> {
        self.receiver.recv().await
    }
}

impl Drop for ParentMessageInbox {
    fn drop(&mut self) {
        self.seal();
    }
}

#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
pub(crate) enum ParentMessageSendError {
    #[error("delegated run is no longer accepting parent messages")]
    Closed,
    #[error("parent message queue is full: limit {PARENT_MESSAGE_QUEUE_CAPACITY} pending messages; wait for the child to take one")]
    QueueFull,
}

pub(crate) fn message_channel() -> (ParentMessageHandle, ParentMessageInbox) {
    let (sender, receiver) = mpsc::channel(PARENT_MESSAGE_QUEUE_CAPACITY);
    let gate = Arc::new(Mutex::new(Some(sender)));
    (
        ParentMessageHandle {
            gate: Arc::clone(&gate),
        },
        ParentMessageInbox { gate, receiver },
    )
}

/// Same framing as Rho-runtime steering: a correction, not a new task.
pub(crate) fn frame_parent_message(text: &str) -> String {
    format!("Message from the parent session (not a new task - incorporate this into your current work):\n\n{text}")
}

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