rho-coding-agent 3.13.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
//! The event streams of the subagent and workflow agent node runs the
//! daemon's sessions start (#1668), so a client follows a run as it
//! follows a session: by observing the session the run writes, or for a run
//! on an external agent runtime, the one it is recorded under.
//!
//! A run's stream is a [`Feed`] like a loaded session's, with one turn: the
//! run. It opens when the run opens its session, which may be long after
//! the run started, while it waits for capacity; an observe meanwhile is
//! refused as any other of a session a job writes, and the client asks
//! again. The stream carries the run's events as its child sends them,
//! the run's job states, and how the run ended, then closes. Nobody
//! attaches to it to prompt, steer, or answer: a run's questions go to its
//! parent session.

use std::{
    collections::HashMap,
    path::PathBuf,
    sync::{Arc, Mutex, MutexGuard, PoisonError},
};

use rho_protocol::{self as wire, DetachReason, SessionAttachAnswer, Subscription, TurnOutcome};
use rho_sdk::SessionId;
use tokio::sync::watch;

use super::{attach_response, feed::Feed};
use crate::app::daemon_host::jobs::{JobState, Moved, TransitionError};
use crate::app::session_events::Wanted;

/// The streams of the runs under way, by the session each writes.
#[derive(Clone, Default)]
pub(in crate::app::daemon_host) struct ChildFeeds {
    runs: Arc<Mutex<HashMap<SessionId, Listed>>>,
}

/// One run's stream as an observe finds it.
#[derive(Clone)]
struct Listed {
    workspace: PathBuf,
    /// The run's feed, once the run opened its session.
    feed: watch::Receiver<Option<Arc<Feed>>>,
}

impl ChildFeeds {
    /// Lists the stream of a run about to write `session` in `workspace`,
    /// whose job is in `state`. The stream is listed until the returned
    /// [`ChildStream`] drops.
    pub(in crate::app::daemon_host) fn list(
        &self,
        session: SessionId,
        workspace: PathBuf,
        state: &JobState,
    ) -> ChildStream {
        let (feed, listed) = watch::channel(None);
        self.runs().insert(
            session.clone(),
            Listed {
                workspace,
                feed: listed,
            },
        );
        ChildStream {
            feeds: self.clone(),
            session,
            turn: wire::TurnId::new(uuid::Uuid::new_v4().hyphenated().to_string()),
            state: state.into(),
            feed,
        }
    }

    /// The stream of the run writing `session`; `None` when no run under
    /// way writes it, or the run has not opened it yet: a request never
    /// waits on a run, which may be queued for long.
    pub(super) fn run(&self, session: &SessionId) -> Option<RunStream> {
        let listed = self.runs().get(session)?.clone();
        let feed = listed.feed.borrow().clone()?;
        Some(RunStream {
            workspace: listed.workspace,
            feed,
        })
    }

    /// What `rho/job/list` reports of the run writing `session` from its
    /// stream; `None` when no run under way writes it, or the run has not
    /// opened it yet.
    pub(in crate::app::daemon_host) fn live(&self, session: &SessionId) -> Option<wire::JobLive> {
        let listed = self.runs().get(session)?.clone();
        let feed = listed.feed.borrow().clone()?;
        Some(feed.live())
    }

    fn runs(&self) -> MutexGuard<'_, HashMap<SessionId, Listed>> {
        // Entries are only inserted and removed whole.
        self.runs.lock().unwrap_or_else(PoisonError::into_inner)
    }
}

/// The stream of a run under way, once it opened the session it writes.
pub(super) struct RunStream {
    workspace: PathBuf,
    feed: Arc<Feed>,
}

impl RunStream {
    /// Subscribes a client to the run's stream, resuming after its seq
    /// cursor when the stream still can, its events leaving the tool output
    /// it asks out: a run's stream has no saved entries or window to resume
    /// by.
    pub(super) fn attach(
        &self,
        from: super::ResumeFrom<'_>,
    ) -> (SessionAttachAnswer, Subscription) {
        let from = super::ResumeFrom {
            deferral: from.deferral,
            ..super::ResumeFrom::cursor(from.after)
        };
        attach_response(&self.workspace, self.feed.attach(from))
    }

    /// Takes the wanted items the run's buffered events carry: what the
    /// run showed lately.
    pub(super) fn find_tool_output(&self, wanted: &mut Wanted) {
        // A run's stream saves no turns of its own: its session's file
        // holds them.
        let _ = self.feed.find_tool_output(wanted);
    }
}

/// One run's stream, as the task that follows the run writes it. Dropping
/// it closes the stream and takes it off the list.
pub(in crate::app::daemon_host) struct ChildStream {
    feeds: ChildFeeds,
    session: SessionId,
    /// The stream's one turn: the run.
    turn: wire::TurnId,
    /// Where the run's job is, which the feed opens in.
    state: wire::JobState,
    feed: watch::Sender<Option<Arc<Feed>>>,
}

impl ChildStream {
    /// Opens the stream: the run opened its session, which runs with
    /// `options` as agent `agent`, on `runtime`.
    pub(in crate::app::daemon_host) fn open(
        &self,
        options: wire::SessionOptions,
        agent: String,
        runtime: crate::agent::AgentRuntime,
    ) {
        self.feed.send_if_modified(|feed| {
            if feed.is_some() {
                return false;
            }
            let opened = Feed::new(
                self.state,
                Some(self.turn.clone()),
                /*title*/ None,
                options,
                agent,
            );
            // A run on an agent runtime defers no tool output, and its
            // replay says the runtime, as a loaded session of it does; a
            // rho run's stream stays as a loaded rho session's.
            if runtime != crate::agent::AgentRuntime::Rho {
                opened.seed_engine(runtime.into());
            }
            *feed = Some(Arc::new(opened));
            true
        });
    }

    /// Sends `events` to the clients following the run. A run sends none
    /// before it opens its session.
    pub(in crate::app::daemon_host) fn publish(
        &self,
        events: impl IntoIterator<Item = wire::SessionEvent>,
    ) {
        if let Some(feed) = self.feed.borrow().as_ref() {
            feed.publish(events);
        }
    }

    /// Moves the run's job with `change`, and tells the clients following
    /// the run where it left the job: a job that ended ends the run's turn
    /// as `outcome`, if any, in one publish, as a session's turn ends.
    /// Holds the run's feed meanwhile (see [`Feed::publish_change`]), so an
    /// observe that found the move in the job list sees it too.
    pub(in crate::app::daemon_host) fn record(
        &mut self,
        change: impl FnOnce() -> Result<Moved, TransitionError>,
        outcome: Option<TurnOutcome>,
    ) -> Result<Moved, TransitionError> {
        let feed = self.feed.borrow().clone();
        let tell = || {
            let moved = change();
            let events = match &moved {
                Ok(moved) => self.moved_to(&moved.state, outcome),
                Err(_) => Vec::new(),
            };
            (moved, events)
        };
        match feed {
            Some(feed) => feed.publish_change(tell),
            None => tell().0,
        }
    }

    /// Notes the run's job is in `state`, and returns the events that tell
    /// its clients so.
    fn moved_to(
        &mut self,
        state: &JobState,
        outcome: Option<TurnOutcome>,
    ) -> Vec<wire::SessionEvent> {
        self.state = state.into();
        match state {
            JobState::Ended(_) => turn_end(&self.turn, outcome, self.state).collect(),
            JobState::Idle
            | JobState::Queued
            | JobState::Running
            | JobState::Requeued
            | JobState::WaitingForInput => vec![self.state_event()],
        }
    }

    /// Tells the clients following the run its title is `title`, unless
    /// they know.
    pub(in crate::app::daemon_host) fn titled(&self, title: &str) {
        if let Some(feed) = self.feed.borrow().as_ref() {
            if feed.title().as_deref() != Some(title) {
                feed.publish([wire::SessionEvent::TitleChanged {
                    title: title.to_owned(),
                }]);
            }
        }
    }

    /// Detaches the clients following the run with `reason`, instead of
    /// the [`DetachReason::NotLoaded`] a dropped stream closes with.
    pub(in crate::app::daemon_host) fn close(&self, reason: DetachReason) {
        if let Some(feed) = self.feed.borrow().as_ref() {
            feed.close(reason);
        }
    }

    fn state_event(&self) -> wire::SessionEvent {
        wire::SessionEvent::State {
            state: self.state,
            turn: Some(self.turn.clone()),
        }
    }
}

/// What ends a run's turn `turn` as `outcome`, if it has one to tell, with
/// its job in `state`, for one publish, as a session's turn ends.
pub(super) fn turn_end(
    turn: &wire::TurnId,
    outcome: Option<TurnOutcome>,
    state: wire::JobState,
) -> impl Iterator<Item = wire::SessionEvent> {
    let ended = outcome.map(|outcome| wire::SessionEvent::TurnEnded {
        turn: turn.clone(),
        outcome,
    });
    ended.into_iter().chain([wire::SessionEvent::State {
        state,
        turn: Some(turn.clone()),
    }])
}

impl Drop for ChildStream {
    fn drop(&mut self) {
        // The run's session is saved and no longer written: an observe
        // reads it from its file from here on, or for an external run,
        // from the run's attach journal its file names.
        self.close(DetachReason::NotLoaded);
        let mut runs = self.feeds.runs();
        // A workflow node that runs again writes the same session, and may
        // have listed its stream already.
        if runs
            .get(&self.session)
            .is_some_and(|listed| listed.feed.same_channel(&self.feed.subscribe()))
        {
            runs.remove(&self.session);
        }
    }
}