rho-coding-agent 3.11.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
//! A session's finished background work, delivered to its model as one
//! [`Batch`]: collected under the delivery lock (`notification_delivery`),
//! rendered once for the model and the transcript ([`BoundaryResults`]),
//! and committed only once the model took it. A batch dropped uncommitted
//! puts its results back, so a delivery the model never took loses nothing.
//!
//! Rho's own boundaries (`session_runtime::delegation`) and the turns of a
//! daemon session an agent on another runtime runs
//! (`daemon_host::sessions::acp_background`) share these mechanics. When a
//! batch is due, and what holds a prompt open, stays each host's policy.

use tokio::sync::mpsc;

use crate::{
    app::{
        boundary_results::BoundaryResults,
        boundary_sources::{any_arrived, Arrival, BoundarySource, Reserved},
        notification_delivery::DeliveryLock,
        peer_sessions::PeerInbox,
        pull_requests::PullRequestInbox,
        subagent_manager::SubagentManager,
        subagent_messaging::{NoticePermits, SubagentNotice},
    },
    display_transcript::DisplayTranscript,
    tools::{
        process::ProcessManager, sdk_registry::AppToolSet, ui::SurfaceHost,
        workflow_tracker::WorkflowRunTracker,
    },
};

/// The background work a session delivers.
pub(crate) struct BackgroundSources<'a> {
    pub(crate) subagents: Option<&'a SubagentManager>,
    pub(crate) processes: Option<&'a ProcessManager>,
    pub(crate) workflows: &'a WorkflowRunTracker,
    pub(crate) surfaces: Option<&'a SurfaceHost>,
    pub(crate) pull_requests: Option<&'a PullRequestInbox>,
    pub(crate) peer_sessions: Option<&'a PeerInbox>,
}

impl<'a> BackgroundSources<'a> {
    /// The work of the session's `tools`; a turn adds its host's notices of
    /// the turns it started in other sessions.
    pub(crate) fn of(tools: &'a AppToolSet) -> Self {
        Self {
            subagents: tools.subagents(),
            processes: tools.processes(),
            workflows: tools.workflow_tracker(),
            surfaces: tools.surfaces(),
            pull_requests: tools.pull_requests(),
            peer_sessions: None,
        }
    }

    /// Whether work of session `session_id`'s still runs or holds a result
    /// no prompt delivered, whichever prompt started it: a subagent, a
    /// workflow run, a live background process, task or service, or a
    /// finished task's result. A finished service's result does not count:
    /// it waits only for a next prompt, so it must not keep an idle
    /// session loaded or a daemon upgrade waiting. Neither does pull request
    /// news: it is saved, so an unloaded session or a restarted daemon still
    /// delivers it.
    pub(crate) fn has_work(&self, session_id: &str) -> bool {
        self.subagents
            .is_some_and(|manager| manager.has_active_or_pending_notification(session_id))
            || self
                .workflows
                .has_active_or_pending_notification(session_id)
            || self
                .processes
                .is_some_and(|processes| processes.has_live() || processes.has_task_result())
            || self.surfaces.is_some_and(SurfaceHost::has_action)
    }

    /// Whether work of session `session_id`'s still runs: a live background
    /// process, task or service, or a subagent or workflow run that has not
    /// finished. A subagent that waits on a person's answer to its question
    /// still runs. Unlike [`Self::has_work`], no result counts: not a
    /// finished task's, child's or workflow run's, nor a surface action.
    ///
    /// For a host with no waker of its idle sessions, as for a daemon
    /// session an agent of another runtime runs whose client takes no turns
    /// the daemon starts: a result there waits for a turn nothing will
    /// start, so counting it would keep the session loaded, and a daemon
    /// upgrade waiting, forever. Such a host loses a result an unload
    /// drops, which [`Self::has_work`] keeps. A session the daemon wakes
    /// takes [`Self::has_work`] instead.
    pub(crate) fn has_live_work(&self, session_id: &str) -> bool {
        self.subagents
            .is_some_and(|manager| manager.has_running(session_id))
            || self.workflows.has_live(session_id)
            || self.processes.is_some_and(ProcessManager::has_live)
    }
}

/// What of a session's background work keeps it loaded and a daemon
/// upgrade waiting, as its host says.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum CountedWork {
    /// What still runs, or holds a result or a child's notice no prompt
    /// took: something may still deliver that result, so a teardown would
    /// drop it.
    Results,
    /// Only what still runs ([`BackgroundSources::has_live_work`]): nothing
    /// will deliver a result, as for a session no waker wakes, or one whose
    /// waker gave up on the result it holds.
    Live,
}

/// Whether work of session `session_id` from `sources`, or a child's
/// notice `held` keeps for the next prompt, is work a teardown would stop
/// or drop, counted as `counted` says.
pub(crate) fn has_work(
    session_id: &str,
    sources: &BackgroundSources<'_>,
    held: Option<&HeldNotices>,
    counted: CountedWork,
) -> bool {
    match counted {
        CountedWork::Results => {
            sources.has_work(session_id) || held.is_some_and(HeldNotices::has_undelivered)
        }
        CountedWork::Live => sources.has_live_work(session_id),
    }
}

/// The session's subagent notice binding: what its children told it before
/// they finished (`message_parent`, action requests).
struct NoticeBinding {
    manager: SubagentManager,
    notices: mpsc::Receiver<SubagentNotice>,
    permits: NoticePermits,
    /// Notices received and not yet delivered, in send order.
    pending: Vec<SubagentNotice>,
    /// Whether `notices` may still bring one.
    open: bool,
}

/// A notice binding kept between prompts. The binding stays installed, so a
/// child can still queue `message_parent` text or an action request while no
/// prompt runs, and notices a cancelled prompt never delivered reach the next.
pub(crate) struct HeldNotices(NoticeBinding);

impl HeldNotices {
    /// Whether a child's notice waits for the next prompt.
    pub(crate) fn has_undelivered(&self) -> bool {
        let Self(binding) = self;
        !binding.pending.is_empty() || !binding.notices.is_empty()
    }
}

/// Finished work a delivery reserved from its sources, in their order.
/// Dropping it uncommitted puts it back.
pub(crate) struct Batch(Vec<Reserved>);

impl Batch {
    /// Whether a source gave it a result.
    pub(crate) fn has_results(&self) -> bool {
        let Self(reserved) = self;
        reserved.iter().any(|reserved| !reserved.is_empty())
    }

    /// Whether each source gave it a result, in their order.
    #[cfg(test)]
    pub(crate) fn results_by_source(&self) -> Vec<bool> {
        let Self(reserved) = self;
        reserved
            .iter()
            .map(|reserved| !reserved.is_empty())
            .collect()
    }
}

/// Whether a delivery gave the model the children's pending notices too.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Notices {
    /// They went with it: committing it acknowledges them.
    Offered,
    /// They wait for a later delivery.
    Kept,
}

/// Delivery of one session's background work, from its sources, for as
/// long as one prompt (or one agent's turn) runs. Dropping it retires the
/// children's notice binding; [`Self::hold`] keeps it for the next.
pub(crate) struct BackgroundDelivery {
    session_id: String,
    subagents: Option<NoticeBinding>,
    /// The work a delivery takes, in the order the model reads it: the
    /// subagents' results, the workflows', the processes', what the user
    /// did on A2UI surfaces that no `ui` call waited for, news of watched
    /// pull requests, and notices of turns the session started in other
    /// sessions.
    sources: Vec<BoundarySource>,
}

impl BackgroundDelivery {
    /// Delivers session `session_id`'s work from `sources`. A binding in
    /// `held` resumes the last prompt's children's notices; without one the
    /// delivery binds afresh, retiring any earlier binding. The session's
    /// workflow runs report to it from now on.
    pub(crate) fn bind(
        session_id: String,
        sources: BackgroundSources<'_>,
        held: Option<HeldNotices>,
    ) -> Self {
        let mut held = held.map(|HeldNotices(binding)| binding);
        let subagents = sources.subagents.map(|manager| {
            held.take().unwrap_or_else(|| {
                let binding = manager.rebind_notices(None);
                NoticeBinding {
                    manager: manager.clone(),
                    notices: binding.receiver,
                    permits: binding.permits,
                    pending: binding.retained,
                    open: true,
                }
            })
        });
        sources.workflows.bind_parent_session(session_id.clone());
        let sources = [
            // Results come from the manager the notices are bound to, even a
            // binding held over from the last prompt.
            subagents.as_ref().map(|binding| BoundarySource::Subagents {
                manager: Box::new(binding.manager.clone()),
                session: session_id.clone(),
            }),
            Some(BoundarySource::Workflows {
                tracker: sources.workflows.clone(),
                session: session_id.clone(),
            }),
            sources.processes.cloned().map(BoundarySource::Processes),
            sources.surfaces.cloned().map(BoundarySource::Surfaces),
            sources
                .pull_requests
                .cloned()
                .map(BoundarySource::PullRequests),
            sources.peer_sessions.cloned().map(BoundarySource::Peers),
        ]
        .into_iter()
        .flatten()
        .collect();
        Self {
            session_id,
            subagents,
            sources,
        }
    }

    /// Ends the delivery but keeps its notice binding, with every notice not
    /// yet delivered, for the next [`Self::bind`].
    pub(crate) fn hold(mut self) -> Option<HeldNotices> {
        self.subagents.take().map(HeldNotices)
    }

    /// The sources a delivery takes from, for a host's policy on what is
    /// due and what holds a prompt open.
    pub(crate) fn sources(&self) -> &[BoundarySource] {
        &self.sources
    }

    /// Resolves once a result of any source but the subagents may have
    /// arrived from now on, subscribed when called: the children reach
    /// [`Self::changed`] through the notice binding. Subscribe before
    /// [`Self::collect`], so a finish in between still wakes the wait.
    pub(crate) fn arrivals(&self) -> Arrival {
        any_arrived(self.sources.iter().filter_map(|source| match source {
            BoundarySource::Subagents { .. } => None,
            BoundarySource::Workflows { .. }
            | BoundarySource::Processes(_)
            | BoundarySource::Surfaces(_)
            | BoundarySource::PullRequests(_)
            | BoundarySource::Peers(_) => Some(source.arrived()),
        }))
    }

    /// Resolves once `arrived`, from [`Self::arrivals`], does, a child ends,
    /// or a child's notice arrives, which it keeps for the next delivery.
    pub(crate) async fn changed(&mut self, arrived: Arrival) {
        match &mut self.subagents {
            Some(subagents) => tokio::select! {
                notice = subagents.notices.recv(), if subagents.open => match notice {
                    Some(notice) => subagents.pending.push(notice),
                    None => subagents.open = false,
                },
                () = subagents.manager.wait_for_notification(&self.session_id) => {}
                () = arrived => {}
            },
            None => arrived.await,
        }
    }

    /// Drains the children's notices, then reserves finished work from every
    /// source, under the delivery lock `_delivery` holds.
    pub(crate) fn collect(&mut self, _delivery: &DeliveryLock) -> Batch {
        if let Some(subagents) = &mut self.subagents {
            while let Ok(notice) = subagents.notices.try_recv() {
                subagents.pending.push(notice);
            }
            let permits = &subagents.permits;
            subagents.pending.retain(|notice| {
                if notice.is_acknowledged() {
                    permits.release_notice(notice);
                    false
                } else {
                    true
                }
            });
        }
        Batch(self.sources.iter().map(BoundarySource::reserve).collect())
    }

    /// Whether a child's notice waits for delivery.
    pub(crate) fn has_notices(&self) -> bool {
        self.subagents
            .as_ref()
            .is_some_and(|subagents| !subagents.pending.is_empty())
    }

    /// Whether a child's notice that waits asks the parent to act.
    pub(crate) fn action_requested(&self) -> bool {
        self.subagents.as_ref().is_some_and(|subagents| {
            subagents
                .pending
                .iter()
                .any(|notice| notice.delivery.requires_parent_action())
        })
    }

    /// Model input and display rows for `batch` and the notices that wait,
    /// rendered as the TUI renders them; `None` when there is nothing.
    pub(crate) fn render(&self, batch: &Batch) -> Option<(String, DisplayTranscript)> {
        let Batch(batch) = batch;
        BoundaryResults {
            notices: self
                .subagents
                .as_ref()
                .map(|subagents| subagents.pending.as_slice())
                .unwrap_or_default(),
            reserved: batch.as_slice(),
        }
        .render(self.subagents.as_ref().map(|subagents| &subagents.manager))
        .finish()
    }

    /// The model took `batch`, and the notices that wait as `notices` says:
    /// they are delivered.
    pub(crate) fn commit(&mut self, batch: Batch, notices: Notices) {
        let Batch(mut batch) = batch;
        batch.iter_mut().for_each(Reserved::commit);
        if let (Notices::Offered, Some(subagents)) = (notices, &mut self.subagents) {
            for notice in subagents.pending.drain(..) {
                notice.acknowledge();
                subagents.permits.release_notice(&notice);
            }
        }
    }
}

impl Drop for BackgroundDelivery {
    fn drop(&mut self) {
        let Some(subagents) = &mut self.subagents else {
            return;
        };
        let _delivery = crate::app::notification_delivery::lock();
        subagents.manager.unbind_notices();
        // Cancellation can leave queued notices behind. A host that drops the
        // binding instead of holding it retires their receipts with it.
        while let Ok(notice) = subagents.notices.try_recv() {
            subagents.pending.push(notice);
        }
        for notice in subagents.pending.drain(..) {
            subagents.permits.release_notice(&notice);
        }
    }
}

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