rho-coding-agent 3.13.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
//! The kinds of a session's background work whose finished results a turn
//! boundary delivers to its model, behind one seam: a subagent's result, a
//! workflow run's, a background process's, an action on an A2UI surface,
//! news of a watched pull request, the end of a turn the session started
//! in another session, and the answer to a question it asked without
//! waiting.
//!
//! A boundary [reserves](BoundarySource::reserve) what each source holds,
//! offers it to the run, and [commits](Reserved::commit) it once the run
//! applied it. A reservation dropped uncommitted puts its results back,
//! and each source orders them again as it always does, so a boundary the
//! run rejected loses nothing. Which work holds a prompt open,
//! or keeps an idle session's wake armed, stays each host's policy.

use std::{future::Future, pin::Pin};

use crate::{
    app::{
        peer_sessions::{PeerBatch, PeerInbox},
        pull_requests::{NewsBatch, PullRequestInbox},
        self_questions::{AnswerBatch, AnswerInbox},
        subagent_manager::{SubagentManager, SubagentNotification},
    },
    tools::{
        process::{ProcessManager, ProcessNotification},
        ui::{SurfaceAction, SurfaceHost},
        workflow_tracker::{WorkflowNotification, WorkflowRunTracker},
    },
};

/// A future that resolves once a source's result may have arrived.
pub(crate) type Arrival = Pin<Box<dyn Future<Output = ()> + Send + 'static>>;

/// One kind of a session's background work, as a boundary takes it. Cheap
/// to clone; clones share the work.
#[derive(Clone)]
pub(crate) enum BoundarySource {
    /// The subagents of session `session`. Boxed: the manager is far larger
    /// than any other source.
    Subagents {
        manager: Box<SubagentManager>,
        session: String,
    },
    /// The workflow runs of session `session`.
    Workflows {
        tracker: WorkflowRunTracker,
        session: String,
    },
    Processes(ProcessManager),
    Surfaces(SurfaceHost),
    PullRequests(PullRequestInbox),
    /// Notices of turns the session started in other sessions.
    Peers(PeerInbox),
    /// Answers to the questions the session asked without waiting.
    Answers(AnswerInbox),
}

impl BoundarySource {
    /// Resolves once a result may have arrived from now on, subscribed
    /// when called, not at the first poll. A subagent's notice and a
    /// service's exit resolve it too, though neither is a result: callers
    /// look again.
    pub(crate) fn arrived(&self) -> Arrival {
        match self {
            Self::Subagents { manager, .. } => Box::pin(manager.parent_wake()),
            Self::Workflows { tracker, .. } => Box::pin(tracker.notified_owned()),
            Self::Processes(processes) => Box::pin(processes.notified_owned()),
            Self::Surfaces(surfaces) => Box::pin(surfaces.acted_owned()),
            Self::PullRequests(inbox) => Box::pin(inbox.news_owned()),
            Self::Peers(inbox) => Box::pin(inbox.arrived_owned()),
            Self::Answers(inbox) => Box::pin(inbox.arrived_owned()),
        }
    }

    /// Takes every result the source holds for a boundary to offer. Call
    /// under the delivery lock (`notification_delivery::lock`).
    pub(crate) fn reserve(&self) -> Reserved {
        match self {
            Self::Subagents { manager, session } => {
                Reserved::Subagents(manager.clone(), manager.take_notifications(session))
            }
            Self::Workflows { tracker, session } => {
                Reserved::Workflows(tracker.clone(), tracker.take_notifications(session))
            }
            Self::Processes(processes) => {
                Reserved::Processes(processes.clone(), processes.take_notifications())
            }
            Self::Surfaces(surfaces) => {
                Reserved::Surfaces(surfaces.clone(), surfaces.take_actions())
            }
            Self::PullRequests(inbox) => Reserved::PullRequests(inbox.clone(), inbox.take_news()),
            Self::Peers(inbox) => Reserved::Peers(inbox.clone(), inbox.take()),
            Self::Answers(inbox) => Reserved::Answers(inbox.clone(), inbox.take()),
        }
    }
}

/// Resolves once any of `sources` may have a result, or never without one.
pub(crate) fn any_arrived(sources: impl IntoIterator<Item = Arrival>) -> Arrival {
    let arrivals: Vec<Arrival> = sources.into_iter().collect();
    if arrivals.is_empty() {
        return Box::pin(std::future::pending());
    }
    Box::pin(async move {
        futures_util::future::select_all(arrivals).await;
    })
}

/// The results one boundary took from one source, beside that source.
/// Dropped uncommitted, it puts them back.
pub(crate) enum Reserved {
    Subagents(Box<SubagentManager>, Vec<SubagentNotification>),
    Workflows(WorkflowRunTracker, Vec<WorkflowNotification>),
    Processes(ProcessManager, Vec<ProcessNotification>),
    Surfaces(SurfaceHost, Vec<SurfaceAction>),
    PullRequests(PullRequestInbox, NewsBatch),
    Peers(PeerInbox, PeerBatch),
    Answers(AnswerInbox, AnswerBatch),
}

impl Reserved {
    /// Whether it holds no result.
    pub(crate) fn is_empty(&self) -> bool {
        match self {
            Self::Subagents(_, results) => results.is_empty(),
            Self::Workflows(_, results) => results.is_empty(),
            Self::Processes(_, results) => results.is_empty(),
            Self::Surfaces(_, actions) => actions.is_empty(),
            Self::PullRequests(_, news) => news.is_empty(),
            Self::Peers(_, notices) => notices.is_empty(),
            Self::Answers(_, answers) => answers.is_empty(),
        }
    }

    /// The run applied the input that offered the results: they are
    /// delivered. Pull request news is also removed from disk now, and only
    /// now, so a crash before this delivers it again rather than never.
    pub(crate) fn commit(&mut self) {
        match self {
            Self::Subagents(_, results) => results.clear(),
            Self::Workflows(_, results) => results.clear(),
            Self::Processes(_, results) => results.clear(),
            Self::Surfaces(_, actions) => actions.clear(),
            Self::PullRequests(inbox, news) => {
                inbox.acknowledge(news);
                *news = NewsBatch::default();
            }
            Self::Peers(_, notices) => notices.commit(),
            Self::Answers(_, answers) => answers.commit(),
        }
    }
}

impl Drop for Reserved {
    fn drop(&mut self) {
        match self {
            Self::Subagents(manager, results) => manager.restore_notifications(results),
            Self::Workflows(tracker, results) => tracker.restore_notifications(results),
            Self::Processes(processes, results) => processes.restore_notifications(results),
            Self::Surfaces(surfaces, actions) => surfaces.restore_actions(actions),
            Self::PullRequests(inbox, news) => inbox.restore_news(news),
            Self::Peers(inbox, notices) => inbox.restore(notices),
            Self::Answers(inbox, answers) => inbox.restore(answers),
        }
    }
}