rho-coding-agent 3.12.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
//! Routes structured host questionnaires from delegated agents to the parent session.

use std::{
    collections::BTreeMap,
    sync::{Arc, Mutex, MutexGuard, PoisonError},
};

use rho_sdk::{
    CancellationToken, Error, HostInputId, HostInputRefusal, HostInputRequest, HostInputResponse,
};
use tokio::sync::{mpsc, oneshot};

/// The delegated run that asks a questionnaire.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct ChildAsker {
    pub(crate) run_id: String,
    pub(crate) agent_id: String,
    /// The run's own session, when its runtime keeps one.
    pub(crate) session: Option<rho_sdk::SessionId>,
}

impl ChildAsker {
    /// The run as the wire names a subagent.
    pub(crate) fn wire(&self) -> rho_protocol::SubagentRef {
        rho_protocol::SubagentRef::new(
            self.run_id.clone(),
            self.session
                .as_ref()
                .map(|session| rho_protocol::SessionId::new(session.as_str())),
        )
    }
}

/// Questionnaires block the child until the parent answers, so this only needs
/// to absorb a burst of parallel children before back-pressuring.
const HOST_INPUT_QUEUE_CAPACITY: usize = 32;

/// One questionnaire raised by a delegated run and awaiting a parent answer.
pub(crate) struct SubagentHostInputRequest {
    pub(crate) asker: ChildAsker,
    pub(crate) request: HostInputRequest,
    pub(crate) response: oneshot::Sender<Result<HostInputResponse, Error>>,
}

/// The questionnaires a host took from subagents and has not answered,
/// with what it tells the person about each. Dropping one tells its
/// subagent nobody will answer.
#[derive(Default)]
pub(crate) struct OpenChildQuestions(BTreeMap<HostInputId, OpenChildQuestion>);

struct OpenChildQuestion {
    /// The asking run as notices name it: `<run id> (<agent id>)`.
    asker: String,
    reply: oneshot::Sender<Result<HostInputResponse, Error>>,
}

impl OpenChildQuestions {
    /// Takes `asked`. Returns the notice that says who asks, and the
    /// questionnaire to put to the person.
    pub(crate) fn open(&mut self, asked: SubagentHostInputRequest) -> (String, HostInputRequest) {
        let SubagentHostInputRequest {
            asker: ChildAsker {
                run_id, agent_id, ..
            },
            request,
            response,
        } = asked;
        let asker = format!("{run_id} ({agent_id})");
        let notice = format!("agent {asker} asks: {}", request.title());
        self.0.insert(
            request.id().clone(),
            OpenChildQuestion {
                asker,
                reply: response,
            },
        );
        (notice, request)
    }

    /// Gives questionnaire `id`'s subagent the person's `answer`. Returns
    /// the notice that says so, or `None` when no such questionnaire is
    /// open.
    pub(crate) fn answer(
        &mut self,
        id: &HostInputId,
        answer: Result<HostInputResponse, HostInputRefusal>,
    ) -> Option<String> {
        let OpenChildQuestion { asker, reply } = self.0.remove(id)?;
        let verb = match &answer {
            Ok(_) => "answered",
            Err(_) => "cancelled",
        };
        let _ = reply.send(answer.map_err(|refusal| {
            Error::Interrupted {
                message: match refusal {
                    HostInputRefusal::Declined => "delegated questionnaire declined by user",
                    // `Dismissed`, or a refusal added later.
                    _ => "delegated questionnaire cancelled by user",
                }
                .into(),
                source: None,
            }
        }));
        Some(format!("{verb} questionnaire for agent {asker}"))
    }

    /// Takes out the next questionnaire whose subagent no longer waits for
    /// an answer; never resolves while every subagent waits.
    pub(crate) async fn abandoned(&mut self) -> HostInputId {
        let id = std::future::poll_fn(|context| {
            for (id, question) in &mut self.0 {
                if question.reply.poll_closed(context).is_ready() {
                    return std::task::Poll::Ready(id.clone());
                }
            }
            std::task::Poll::Pending
        })
        .await;
        self.0.remove(&id);
        id
    }
}

/// Where delegated children send their questionnaires: the parent's queue
/// once a host takes them, for the session's life; until then children
/// ask nobody, and get no questionnaire tool. Clones share the binding.
#[derive(Clone, Default)]
pub(crate) struct SubagentHostInputBridge {
    parent: Arc<Mutex<Option<mpsc::Sender<SubagentHostInputRequest>>>>,
}

impl SubagentHostInputBridge {
    pub(crate) fn new() -> Self {
        Self::default()
    }

    /// Installs a queue of its own as the parent's side, and returns it.
    #[cfg(test)]
    pub(crate) fn bind_parent(&self) -> mpsc::Receiver<SubagentHostInputRequest> {
        let (sender, receiver) = Self::queue();
        self.bind_parent_to(sender);
        receiver
    }

    /// Installs `sender` as the parent's side, for a parent that keeps one
    /// queue across the bridges of every subagent manager it has had.
    /// Replaces any previous binding.
    pub(crate) fn bind_parent_to(&self, sender: mpsc::Sender<SubagentHostInputRequest>) {
        *self.parent() = Some(sender);
    }

    /// How many questionnaires a parent's queue holds before a child's
    /// request waits for room.
    const QUEUE_CAPACITY: usize = HOST_INPUT_QUEUE_CAPACITY;

    /// A parent's queue of the questionnaires: the side a manager sends
    /// them to (`SubagentManager::bind_host_input_to`), and the side its
    /// host takes them from.
    pub(crate) fn queue() -> (
        mpsc::Sender<SubagentHostInputRequest>,
        mpsc::Receiver<SubagentHostInputRequest>,
    ) {
        mpsc::channel(Self::QUEUE_CAPACITY)
    }

    /// True once a host takes the questionnaires.
    pub(crate) fn is_bound(&self) -> bool {
        self.parent().is_some()
    }

    /// Forwards a child questionnaire to the parent and waits for its answer.
    pub(crate) async fn request(
        &self,
        asker: ChildAsker,
        request: HostInputRequest,
        cancellation: &CancellationToken,
    ) -> Result<HostInputResponse, Error> {
        let sender = self
            .parent()
            .clone()
            .ok_or_else(|| Error::InvalidConfiguration {
                message: "delegated agent questionnaires require an interactive parent session"
                    .into(),
                source: None,
            })?;
        let (response_tx, response_rx) = oneshot::channel();
        let pending = SubagentHostInputRequest {
            asker,
            request,
            response: response_tx,
        };
        tokio::select! {
            result = sender.send(pending) => result.map_err(|_| Error::Interrupted {
                message: "parent session stopped accepting delegated questionnaires".into(),
                source: None,
            })?,
            () = cancellation.cancelled() => return Err(Error::Cancelled),
        }
        tokio::select! {
            result = response_rx => result.map_err(|_| Error::Interrupted {
                message: "delegated questionnaire was dropped without a response".into(),
                source: None,
            })?,
            () = cancellation.cancelled() => Err(Error::Cancelled),
        }
    }

    fn parent(&self) -> MutexGuard<'_, Option<mpsc::Sender<SubagentHostInputRequest>>> {
        self.parent.lock().unwrap_or_else(PoisonError::into_inner)
    }
}

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