rho-coding-agent 3.11.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
//! Background delivery at SDK input boundaries for hosts without an interactive
//! inbox (the daemon and `rho run`). Finished subagents, workflows, and
//! background processes reach the model at the next boundary. Natural
//! completion waits for every undelivered child of the session, whichever
//! prompt started it, and for workflows and process tasks started during
//! this prompt, standing in for the TUI's idle wake, unless the host wakes
//! the idle session (see below). Workflows and tasks from an earlier prompt,
//! such as a `/workflow:<name>` start, only deliver; a later prompt does not
//! wait for them. A process service (`kind: service`, such as a dev server)
//! never holds completion, whichever prompt started it; its exit result
//! still delivers at the next boundary of any prompt. The wait stays inside
//! the original run, so cancellation and the SDK step budget still govern
//! parent continuations.
//! Notices of turns the session started in other sessions through session
//! control (see `app::peer_sessions`) deliver like finished work and never
//! hold completion; only a session whose host starts its turns has them.
//! Hosts that show a transcript take [`Delegation::offered_displays`] to
//! render what the model was given. Children the host runs as its own threads
//! ([`super::ChildAgents::HostThreads`]) are not registered here: they
//! outlive the prompt and report through the host's next prompt instead.
//!
//! Children also outlive a cancelled prompt, so the session keeps their
//! notice binding between prompts with [`Delegation::hold_notices`]. `rho run`
//! drops it with the run.
//!
//! A session whose host runs its children as its own threads (T3 Code) is
//! woken through that host for background work too (see the daemon's
//! `sessions::t3_wake`), so it gets [`BackgroundWait::HostWakes`]: running
//! workflows and process tasks then never hold natural completion, and
//! finished ones still deliver at every boundary. So it is for a session
//! whose host starts a turn of its own when the work finishes, as the daemon
//! does for the TUI ([`BackgroundWait::HostTurns`], `sessions::idle_wake`).
//! There a prompt does not wait for its running subagents either, and a
//! child's informational notices alone buy no provider request: they wait
//! for the next one, in this prompt or a later turn.

use std::time::Instant;

use rho_sdk::{BoundaryInputRequest, InputBoundary, Session, UserInput};
use tokio::sync::mpsc;

use crate::{
    app::{
        background_delivery::{BackgroundDelivery, BackgroundSources, HeldNotices, Notices},
        boundary_sources::BoundarySource,
    },
    display_transcript::DisplayTranscript,
    session::SessionPersistence,
};

pub(super) struct Delegation {
    requests: mpsc::Receiver<BoundaryInputRequest>,
    /// The session's work a boundary delivers (see
    /// [`crate::app::background_delivery`]).
    delivery: BackgroundDelivery,
    /// Workflows and process tasks started from here on hold natural
    /// completion; older ones, and services, only deliver.
    prompt_started: Instant,
    background_wait: BackgroundWait,
    /// Display rows for each delivery offered to the runtime, when a host asked.
    displays: Option<mpsc::UnboundedSender<(UserInput, DisplayTranscript)>>,
}

/// Whether running workflows and processes hold a prompt's natural completion.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum BackgroundWait {
    /// The prompt waits for the work it started, standing in for an idle wake.
    HoldPrompt,
    /// The host wakes the idle session when the work finishes.
    HostWakes,
    /// The host starts a turn on the idle session when the work finishes,
    /// a subagent included, or a child asks the parent to act. The turn
    /// delivers the result at its first boundary.
    HostTurns,
}

impl BackgroundWait {
    /// How a session whose children `children` runs waits: a host that runs
    /// them as its own threads wakes the session itself, whatever
    /// `idle_turns` says. The daemon decides from it, as a session opens,
    /// what it serves the session and whether it wakes it, whatever runs
    /// the session's turns.
    pub(crate) fn of(children: super::ChildAgents, idle_turns: super::IdleTurns) -> Self {
        match (children, idle_turns) {
            (super::ChildAgents::HostThreads, _) => Self::HostWakes,
            (super::ChildAgents::InProcess, super::IdleTurns::Host) => Self::HostTurns,
            (super::ChildAgents::InProcess, super::IdleTurns::Never) => Self::HoldPrompt,
        }
    }
}

impl Delegation {
    /// Installs boundary delivery for one prompt on an idle session. A binding
    /// in `held` resumes the previous prompt's notices; without one the prompt
    /// binds afresh, retiring any earlier binding. `held` is taken only once
    /// attach succeeds, so a failed attach keeps it for the next prompt.
    /// Subagents keep their artifacts in `storage`'s folder when it has one,
    /// and save their sessions as `persistence` says the session does.
    /// Running workflows and processes hold natural completion as `wait`
    /// says.
    pub(super) fn attach(
        session: &Session,
        sources: BackgroundSources<'_>,
        wait: BackgroundWait,
        storage: Option<&crate::session::Session>,
        persistence: SessionPersistence,
        held: &mut Option<HeldNotices>,
    ) -> Result<Self, rho_sdk::Error> {
        let (source, requests) = rho_sdk::boundary_input_channel();
        session.set_boundary_inputs(Some(source))?;
        let session_id = session.id().to_string();
        if let Some(manager) = sources.subagents {
            manager.bind_parent_session(session_id.clone(), storage, persistence);
        }
        Ok(Self {
            requests,
            delivery: BackgroundDelivery::bind(session_id, sources, held.take()),
            prompt_started: Instant::now(),
            background_wait: wait,
            displays: None,
        })
    }

    /// Display rows for every delivery offered from now on. The host claims
    /// them as the run reports each input applied.
    pub(super) fn offered_displays(&mut self) -> OfferedDisplays {
        let (sender, receiver) = mpsc::unbounded_channel();
        self.displays = Some(sender);
        OfferedDisplays { receiver }
    }

    pub(super) async fn drive<T>(host: &mut Self, run: impl std::future::Future<Output = T>) -> T {
        let service = host.serve();
        tokio::pin!(service);
        let result = tokio::select! {
            biased;
            () = &mut service => unreachable!(),
            result = run => result,
        };
        // The SDK checkpoints input before acknowledging it. Reap any ready
        // acknowledgement before dropping reservations, including when the
        // event pump notices cancellation in that same scheduling turn.
        let _ = futures_util::poll!(&mut service);
        result
    }

    /// Ends this prompt but keeps its notice binding, with every notice not yet
    /// delivered, for the next [`Self::attach`].
    pub(super) fn hold_notices(self) -> Option<HeldNotices> {
        self.delivery.hold()
    }

    async fn serve(&mut self) {
        while let Some(request) = self.requests.recv().await {
            self.respond(request).await;
        }
        std::future::pending().await
    }

    async fn respond(&mut self, request: BoundaryInputRequest) {
        let boundary = request.boundary();
        let (receipt, reservation, notices) = loop {
            // Subscribe before collecting so a finish between the snapshot
            // and the wait below still wakes it.
            let arrived = self.delivery.arrivals();
            {
                let delivery = crate::app::notification_delivery::lock();
                let batch = self.delivery.collect(&delivery);
                let due = batch.has_results()
                    || self.delivery.action_requested()
                    || boundary == InputBoundary::BeforeProvider;
                if due || !self.has_outstanding_work() {
                    // With nothing due, the prompt is about to end. Where the
                    // host starts later turns, notices wait for one of them.
                    let notices = match (due, self.background_wait) {
                        (true, _)
                        | (false, BackgroundWait::HoldPrompt | BackgroundWait::HostWakes) => {
                            Notices::Offered
                        }
                        (false, BackgroundWait::HostTurns) => Notices::Kept,
                    };
                    let rendered = match notices {
                        Notices::Offered => self.delivery.render(&batch),
                        Notices::Kept => None,
                    };
                    let input = rendered.map(|(model, display)| {
                        let input = UserInput::text(model);
                        if let Some(sink) = &self.displays {
                            // Queued before the reply, so its rows wait for
                            // the applied event. A closed host shows nothing.
                            let _ = sink.send((input.clone(), display));
                        }
                        input
                    });
                    break (request.respond(input), batch, notices);
                }
            }
            self.delivery.changed(arrived).await;
        };
        if receipt.await {
            self.delivery.commit(reservation, notices);
        }
    }

    /// Work whose result could still arrive and should hold natural
    /// completion: a finished result no boundary took, a subagent still
    /// running unless the host starts the turn that takes its result, and,
    /// where the prompt waits for its work, a workflow or process task it
    /// started.
    fn has_outstanding_work(&self) -> bool {
        let holds = match self.background_wait {
            BackgroundWait::HoldPrompt => true,
            BackgroundWait::HostWakes | BackgroundWait::HostTurns => false,
        };
        let started = self.prompt_started;
        self.delivery.sources().iter().any(|source| match source {
            BoundarySource::Subagents { manager, session } => match self.background_wait {
                BackgroundWait::HoldPrompt | BackgroundWait::HostWakes => {
                    manager.has_active_or_pending_notification(session)
                }
                BackgroundWait::HostTurns => false,
            },
            BoundarySource::Workflows { tracker, session } => {
                tracker.has_pending_notification(session)
                    || (holds && tracker.has_live_started_since(session, started))
            }
            BoundarySource::Processes(processes) => {
                processes.has_pending_notification()
                    || (holds && processes.has_live_task_started_since(started))
            }
            BoundarySource::Surfaces(surfaces) => surfaces.has_action(),
            BoundarySource::PullRequests(inbox) => inbox.has_news(),
            BoundarySource::Peers(inbox) => inbox.has_notices(),
        })
    }
}

/// Display rows for deliveries offered to the runtime. Each waits for the
/// [`rho_sdk::RunEvent::BoundaryInputApplied`] that confirms it, so a host
/// shows a result exactly where it entered the run and never shows one the
/// runtime rejected.
pub(super) struct OfferedDisplays {
    receiver: mpsc::UnboundedReceiver<(UserInput, DisplayTranscript)>,
}

impl OfferedDisplays {
    /// Rows for the `input` a run applied. A rejected offer can only precede
    /// it, so older offers that do not match are discarded.
    pub(super) fn applied(&mut self, input: &UserInput) -> Option<DisplayTranscript> {
        while let Ok((offered, display)) = self.receiver.try_recv() {
            if offered == *input {
                return Some(display);
            }
        }
        None
    }
}

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