rho-coding-agent 3.13.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
//! What the agent sent a session, in the order it sent it. Updates arrive
//! through the connection's handler, answers to the client's requests
//! through their own futures; the client reads them as one stream, so it
//! takes an answer after the updates that came before it, as v2 asks:
//! apply responses and `config_option_update`s in the order received, each
//! replacing the whole option list.

use agent_client_protocol::{
    v2::{schema as v2, ActiveSession, SentRequest},
    Agent, Error,
};
use std::collections::VecDeque;
use tokio::sync::{mpsc, oneshot};

use super::error;

/// One item of the stream: an update, or where an answer arrived.
pub(super) enum Inbound {
    Update(Box<v2::UpdateSessionNotification>),
    /// The answer to a `session/prompt`: that the agent took it, or why not.
    Took(Result<v2::PromptResponse, Error>),
    /// A setup request's answer arrived here; [`Updates::ask`] reads it.
    Answered,
}

/// The stream ([`Inbound`]), less what setup already read past.
pub(super) struct Updates {
    tx: mpsc::UnboundedSender<Inbound>,
    rx: mpsc::UnboundedReceiver<Inbound>,
    queued: VecDeque<Inbound>,
}

impl Updates {
    /// The stream, and the sender the connection's update handler feeds.
    pub(super) fn new() -> (Self, mpsc::UnboundedSender<Inbound>) {
        let (tx, rx) = mpsc::unbounded_channel();
        let updates = Self {
            tx: tx.clone(),
            rx,
            queued: VecDeque::new(),
        };
        (updates, tx)
    }

    /// Sends the setup request `sent` and reads up to its answer: a config
    /// update before the answer is replaced by the options the answer
    /// carries (an agent may report options, or the change just asked for,
    /// first); the rest waits for the turn. What follows the answer is read
    /// later ([`Self::latest_options`]).
    pub(super) async fn ask<T: Send + 'static>(
        &mut self,
        sent: SentRequest<T>,
    ) -> Result<T, Error> {
        let (answer_tx, answer_rx) = oneshot::channel();
        let tx = self.tx.clone();
        // Called as the dispatch loop reads the answer, before what follows it.
        sent.on_receiving_result(async move |answer| {
            let _ = answer_tx.send(answer);
            let _ = tx.send(Inbound::Answered);
            Ok(())
        })?;
        self.answer(answer_rx).await
    }

    /// Reads up to where the answer `answer` brings arrived ([`Self::ask`]).
    async fn answer<T>(&mut self, answer: oneshot::Receiver<Result<T, Error>>) -> Result<T, Error> {
        loop {
            let Some(inbound) = self.rx.recv().await else {
                unreachable!("`self` holds a sender");
            };
            match inbound {
                Inbound::Answered => break,
                Inbound::Update(notification) if is_config(&notification) => {}
                other => self.queued.push_back(other),
            }
        }
        answer
            .await
            .unwrap_or_else(|_| Err(error("acp: a setup answer was lost")))
    }

    /// Reads what arrived since the last setup answer: the options of the
    /// latest config update of `session`, which replace the answer's; the
    /// rest waits for the turn.
    pub(super) fn latest_options(&mut self, session: &str) -> Option<Vec<v2::SessionConfigOption>> {
        let mut latest = None;
        while let Ok(inbound) = self.rx.try_recv() {
            match inbound {
                Inbound::Update(notification)
                    if is_config(&notification)
                        && notification.session_id.to_string() == session =>
                {
                    if let v2::SessionUpdate::ConfigOptionUpdate(update) = notification.update {
                        latest = Some(update.config_options);
                    }
                }
                other => self.queued.push_back(other),
            }
        }
        latest
    }

    /// Called before the first prompt goes out: a state the session reported
    /// so far is of work before that prompt, so it is dropped. A config
    /// update since the last setup read is newer than it, and is kept.
    pub(super) fn prompting(&mut self) {
        while let Ok(inbound) = self.rx.try_recv() {
            self.queued.push_back(inbound);
        }
        self.queued.retain(|inbound| {
            !matches!(
                inbound,
                Inbound::Update(notification)
                    if matches!(notification.update, v2::SessionUpdate::StateUpdate(_))
            )
        });
    }

    /// Sends `prompt` on `session`; its answer arrives in order, as
    /// [`Inbound::Took`].
    pub(super) fn prompt(
        &self,
        session: &ActiveSession<Agent>,
        prompt: Vec<v2::ContentBlock>,
    ) -> Result<(), Error> {
        let tx = self.tx.clone();
        // Called as the dispatch loop reads the answer, before what follows it.
        session
            .send_prompt_blocks(prompt)
            .on_receiving_result(async move |took| {
                let _ = tx.send(Inbound::Took(took));
                Ok(())
            })
    }

    pub(super) async fn next(&mut self) -> Option<Inbound> {
        match self.queued.pop_front() {
            Some(inbound) => Some(inbound),
            // Never `None`: `self` holds a sender.
            None => self.rx.recv().await,
        }
    }
}

fn is_config(notification: &v2::UpdateSessionNotification) -> bool {
    matches!(
        notification.update,
        v2::SessionUpdate::ConfigOptionUpdate(_)
    )
}

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