rho-coding-agent 3.10.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
//! The background work a daemon session's served tools start (see
//! `acp_tools`), delivered to the agent of another runtime that runs the
//! session: a subagent's result or notice, a process's exit, a workflow
//! run's end, and what a client did on a surface no `ui` call waited on.
//!
//! The work outlives the turn that started it, as a Rho session's does, and
//! its results reach the agent by the same rules a Rho session's turns
//! follow (see [`crate::app::background_delivery`]), rendered by the same
//! renderer:
//!
//! - As a turn starts, what waits rides ahead of its prompt, as a content
//!   block of its own ([`TurnMailbox`]), the children's informational
//!   notices with it.
//! - While the turn runs, each result is sent into it as it arrives, through
//!   the run's message inbox, which steers it into the turn in flight, or
//!   sends it as the agent's next turn once the turn ends (see
//!   `acp_runtime::driver`). A child's informational notice alone waits for
//!   a result, a request for the parent to act, or the next turn's prompt.
//! - Between turns, what arrives wakes the session where its client takes
//!   the turns the daemon starts (`idle_wake: turn`, see `idle_wake`), as a
//!   Rho session's does: the daemon starts a turn of its own whose prompt
//!   carries it (see `acp_turns/daemon_turn.rs`). Elsewhere it waits for
//!   the next prompt. No prompt waits for running work either way.
//!
//! A delivery is committed only once the run delivered it: its prompt sent,
//! its steer injected, or its follow-up turn sent. One the run never
//! delivered, as when the turn ended first, is put back for the next turn.
//! The run records the delivery's cards as it delivers it, so clients see
//! them once, where the agent got the results, and a reopen replays them
//! from the agent's journal. A card loses the typed side a Rho session's
//! card keeps (the subagent's session to open), which the journal does not
//! record. Nothing is sent into a turn while a served call runs, a parked
//! one included, or while one of the agent's requests to the served tools
//! has yet to get its answer
//! ([`super::agent_activity::Activity::served_tools_busy`]): `process`
//! `poll` or `agents` `status` may hand the agent the result itself, which a
//! delivery would then send again, and a delivery sent while a call's
//! answer waits to go back, as for a slot in the agent budget, would reach
//! the agent ahead of it.
//!
//! How the session waits follows from whether the daemon wakes it
//! ([`IdleDelivery`], decided as it opens; see [`idle_delivery`]):
//!
//! - Woken ([`IdleDelivery::WakeTurn`]), its `SessionBackground` waits as a
//!   Rho session whose client takes the daemon's turns does
//!   ([`BackgroundWait::HostTurns`]): the work it waits on keeps it active
//!   (see `settle`), its finished results keep it loaded and a daemon
//!   upgrade waiting, as a wake will deliver them
//!   ([`CountedWork::Results`]) until the wake gives up on them (then only
//!   [`CountedWork::Live`], see `unload`), and it takes the news of the pull
//!   requests it watches and the notices of the turns it started in other
//!   sessions too.
//! - Otherwise it waits as [`BackgroundWait::HoldPrompt`], which no daemon
//!   waker wakes: it settles as its turn ends, whatever runs, and its live
//!   work keeps it loaded, but no result does ([`CountedWork::Live`]).

use std::future::Future;

use crate::{
    app::{
        background_delivery::{
            self, BackgroundDelivery, BackgroundSources, Batch, CountedWork, HeldNotices, Notices,
        },
        notification_delivery,
        peer_sessions::PeerInbox,
        session_runtime::BackgroundWait,
    },
    cli_runtime::parent_messages::{
        message_channel, DeliveryReceipt, ParentMessage, ParentMessageHandle, ParentMessageInbox,
    },
    display_transcript::{DisplayRow, DisplayTranscript},
    run_artifacts::AttachmentEvent,
    tools::{
        sdk_registry::{AppToolSet, IdleDelivery},
        workflow_tracker::WorkflowRunTracker,
    },
};

use super::{
    acp_tools::ServedTools,
    agent_activity::AgentActivity,
    background::{SessionBackground, Sources},
};

/// Whether the daemon wakes the idle session a client opens so that a Rho
/// session opened alike would wait as `rho_wait` ([`BackgroundWait::of`]),
/// for its results: only where the daemon starts a Rho session's turns for
/// them. A host that runs a session's children as its own threads wakes a
/// Rho session through itself (`t3_wake`), which no session an agent of
/// another runtime runs has.
pub(super) fn idle_delivery(rho_wait: BackgroundWait) -> IdleDelivery {
    match rho_wait {
        BackgroundWait::HostTurns => IdleDelivery::WakeTurn,
        // T3 Code's own wake is no daemon wake.
        BackgroundWait::HostWakes | BackgroundWait::HoldPrompt => IdleDelivery::NextPrompt,
    }
}

/// How the background work of a session woken as `idle` says waits: for a
/// turn the daemon starts (see `awaited`), or for the next prompt, which no
/// daemon waker wakes. Rho's boundaries never run the session's turns, so
/// neither holds a prompt open. Not the Rho session's wait it came from: a
/// T3 Code client's `HostWakes` names a waker no such session has.
fn wait(idle: IdleDelivery) -> BackgroundWait {
    match idle {
        IdleDelivery::WakeTurn => BackgroundWait::HostTurns,
        IdleDelivery::NextPrompt => BackgroundWait::HoldPrompt,
    }
}

/// The work the session delivers, from the tools it is `served`.
fn sources(served: &ServedTools) -> BackgroundSources<'_> {
    sources_of(served.set(), served.idle(), served.peers())
}

/// The work a session woken as `idle` says delivers, from its tools `set`
/// and the inbox of the turns it starts in other sessions, `peers`. Pull
/// request news and those notices only where the daemon wakes it: only a
/// wake could deliver them, and only then is `watch_pull_request` served.
pub(super) fn sources_of<'a>(
    set: &'a AppToolSet,
    idle: IdleDelivery,
    peers: Option<&'a PeerInbox>,
) -> BackgroundSources<'a> {
    let of = BackgroundSources::of(set);
    match idle {
        IdleDelivery::WakeTurn => BackgroundSources {
            peer_sessions: peers,
            ..of
        },
        IdleDelivery::NextPrompt => BackgroundSources {
            pull_requests: None,
            ..of
        },
    }
}

/// The background work of session `session_id`, from the tools it is
/// `served`: none without them.
pub(super) fn background(session_id: String, served: Option<&ServedTools>) -> SessionBackground {
    match served {
        Some(served) => of_sources(session_id, served.idle(), sources(served)),
        None => SessionBackground::of_sources(
            session_id,
            wait(IdleDelivery::NextPrompt),
            Sources::default(),
            WorkflowRunTracker::new(),
        ),
    }
}

/// The background work of session `session_id`, woken as `idle` says, from
/// `sources`.
fn of_sources(
    session_id: String,
    idle: IdleDelivery,
    sources: BackgroundSources<'_>,
) -> SessionBackground {
    SessionBackground::of_sources(
        session_id,
        wait(idle),
        Sources {
            processes: sources.processes.cloned(),
            subagents: sources.subagents.cloned(),
            surfaces: sources.surfaces.cloned(),
            pull_requests: sources.pull_requests.cloned(),
            peers: sources.peer_sessions.cloned(),
        },
        sources.workflows.clone(),
    )
}

/// Whether work of the tools session `session_id` is `served`, counted as
/// the session's host says (`counted`), keeps it loaded and a daemon
/// upgrade waiting: what a teardown would stop or drop. Where the daemon
/// wakes the session, as for a Rho session, a result counts as the host
/// says, since a wake will deliver it. Otherwise only what still runs: a
/// result there waits for a turn nothing starts, so counting it would keep
/// the session loaded, and a daemon upgrade waiting, for good.
pub(super) fn has_work(session_id: &str, served: &ServedTools, counted: CountedWork) -> bool {
    let counted = match served.idle() {
        IdleDelivery::WakeTurn => counted,
        IdleDelivery::NextPrompt => CountedWork::Live,
    };
    background_delivery::has_work(session_id, &sources(served), served.held_notices(), counted)
}

/// Binds the delivery of session `session_id`'s work, from the tools it is
/// `served`, resuming the children's notices `held` the last turn kept.
pub(super) fn bind(
    session_id: String,
    served: &ServedTools,
    held: Option<HeldNotices>,
) -> BackgroundDelivery {
    BackgroundDelivery::bind(session_id, sources(served), held)
}

/// When a delivery is due.
#[derive(Clone, Copy)]
enum Moment {
    /// As the turn starts: its prompt goes anyway, so the children's
    /// informational notices ride along.
    TurnStart,
    /// While the turn runs: a result, or a child's request that the parent
    /// act.
    MidTurn,
}

/// What one turn's run takes for the session's background results: the
/// inbox the run reads them from, and those its first prompt carries.
pub(super) struct TurnMailbox {
    inbox: ParentMessageInbox,
    prompt_results: Option<ParentMessage>,
}

impl TurnMailbox {
    /// The results that wait, which the turn's prompt carries, if any.
    pub(super) fn prompt_results(&self) -> Option<&ParentMessage> {
        self.prompt_results.as_ref()
    }

    /// Gives `launch` the inbox, and its prompt the results that wait.
    pub(super) fn install(self, launch: &mut crate::app::agent_binding::ExternalLaunch) {
        let Self {
            inbox,
            prompt_results,
        } = self;
        *launch.parent_messages_mut() = Some(inbox);
        launch.overrides_mut().prompt_results = prompt_results;
    }
}

/// A delivery the run was given and has yet to confirm.
struct InFlight {
    batch: Batch,
    delivered: DeliveryReceipt,
}

/// The session's background delivery for one turn.
pub(super) struct TurnDelivery {
    delivery: BackgroundDelivery,
    messages: ParentMessageHandle,
    in_flight: Option<InFlight>,
    /// What the agent does with the served tools, which holds back what is
    /// sent mid-turn.
    activity: AgentActivity,
}

impl TurnDelivery {
    /// Starts delivering `delivery` into a turn whose agent's use of the
    /// served tools `activity` tells: the turn's side, and what its run
    /// takes, with what waits rendered for its prompt.
    pub(super) fn start(
        delivery: BackgroundDelivery,
        activity: AgentActivity,
    ) -> (Self, TurnMailbox) {
        let (messages, inbox) = message_channel();
        let mut turn = Self {
            delivery,
            messages,
            in_flight: None,
            activity,
        };
        let prompt_results = turn.due(Moment::TurnStart).map(|(message, in_flight)| {
            turn.in_flight = Some(in_flight);
            message
        });
        (
            turn,
            TurnMailbox {
                inbox,
                prompt_results,
            },
        )
    }

    /// Sends each result into the turn as it arrives, one at a time, each
    /// committed once the run delivered it, and none while the served tools
    /// are busy. Returns once the run takes no more; cancel-safe, since a
    /// delivery in flight stays for [`Self::finish`].
    async fn deliver(&mut self) {
        loop {
            if let Some(in_flight) = &mut self.in_flight {
                let delivered = (&mut in_flight.delivered).await.is_ok();
                match (delivered, self.in_flight.take()) {
                    (true, Some(in_flight)) => self.commit(in_flight),
                    // The run ended without it, so it takes no more: the
                    // batch goes back for the next turn.
                    (false, _) | (true, None) => return,
                }
                continue;
            }
            // A call that hands the agent a result runs first; what it left
            // is looked at once it, and every other call, ended, and every
            // answer went back.
            self.activity
                .until(|activity| !activity.served_tools_busy())
                .await;
            // Subscribed before the look, so a result in between still
            // wakes the wait.
            let arrived = self.delivery.arrivals();
            if let Some((message, in_flight)) = self.due(Moment::MidTurn) {
                match self.messages.send_message(message) {
                    Ok(()) => self.in_flight = Some(in_flight),
                    // The run closed its inbox as it ends: the batch goes
                    // back for the next turn.
                    Err(_) => return,
                }
                continue;
            }
            self.delivery.changed(arrived).await;
        }
    }

    /// The turn's run ended: a delivery it made is committed, one it did
    /// not is put back, and the children's notice binding is kept for the
    /// next turn.
    pub(super) fn finish(mut self) -> Option<HeldNotices> {
        if let Some(mut in_flight) = self.in_flight.take() {
            if in_flight.delivered.try_recv().is_ok() {
                self.commit(in_flight);
            }
        }
        let Self { delivery, .. } = self;
        delivery.hold()
    }

    /// The results due at `moment`, reserved and rendered as the message
    /// that delivers them; `None`, reserving nothing, when none are.
    fn due(&mut self, moment: Moment) -> Option<(ParentMessage, InFlight)> {
        let lock = notification_delivery::lock();
        let batch = self.delivery.collect(&lock);
        let due = batch.has_results()
            || match moment {
                Moment::TurnStart => self.delivery.has_notices(),
                Moment::MidTurn => self.delivery.action_requested(),
            };
        if !due {
            return None;
        }
        let (model, display) = self.delivery.render(&batch)?;
        let (message, delivered) =
            ParentMessage::hosted(framed(&model), shown(display), UNDELIVERED.to_owned());
        Some((message, InFlight { batch, delivered }))
    }

    /// The run delivered `in_flight`, with every notice that waited, since
    /// each delivery offers them all.
    fn commit(&mut self, in_flight: InFlight) {
        self.delivery.commit(in_flight.batch, Notices::Offered);
    }
}

/// Runs `run`, a turn's run, delivering `delivery` into it meanwhile, if
/// the turn has one; returns how the run ended, and the children's notice
/// binding for the next turn. Once the delivery returns, as the run takes
/// no more, the run goes on alone to its end.
pub(super) async fn alongside<T>(
    delivery: Option<TurnDelivery>,
    run: impl Future<Output = T>,
) -> (T, Option<HeldNotices>) {
    let Some(mut delivery) = delivery else {
        return (run.await, None);
    };
    tokio::pin!(run);
    let ended = tokio::select! {
        biased;
        ended = &mut run => ended,
        () = delivery.deliver() => run.await,
    };
    (ended, delivery.finish())
}

/// The results `model` rendered, as the agent reads them: what work it
/// started finished, not a request from anyone.
fn framed(model: &str) -> String {
    format!("rho delivered results of background work you started earlier with its tools (not a new task from the user - use them in your current work):\n\n{model}")
}

/// What the run says of results it never delivered.
const UNDELIVERED: &str = "acp: background results were not delivered: the run ended before its next turn; the session's next turn gets them";

/// What the run records of a delivery as it delivers it: the rows the
/// renderer gave its transcript, as the agent's journal holds them.
fn shown(display: DisplayTranscript) -> Vec<AttachmentEvent> {
    let DisplayTranscript(rows) = display;
    rows.into_iter()
        .filter_map(|row| match row {
            DisplayRow::Notification(row) => Some(AttachmentEvent::Message(Box::new(row.card))),
            DisplayRow::Notice(text) => Some(AttachmentEvent::Notice(text)),
            // A delivery renders none.
            DisplayRow::Compaction(_) => None,
        })
        .collect()
}

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