rho-coding-agent 3.12.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
//! What a session's in-process subagents share with the host that runs the
//! session.
//!
//! Most hosts run each session's subagents, and the agent nodes of the
//! workflow runs it starts, on a pool of their own sized by the config's
//! `agent_concurrency`. The daemon shares one pool across every session it
//! hosts, so the budget is daemon-wide, and hears of each subagent and
//! workflow run so it can list the run as a child job of its session's
//! (#1658).

mod external_run_file;

use std::{path::PathBuf, sync::Arc};

use external_run_file::ExternalRunFile;

use rho_protocol::{SessionEvent as WireEvent, SessionOptions};
use tokio::sync::mpsc::{self, UnboundedReceiver, UnboundedSender};

use super::{
    agent_concurrency::{AgentConcurrency, QueueWatch},
    agent_executor::AgentRunHandle,
    session_events::{external_options, ExternalEvents},
};
use crate::{
    cli_runtime::status_sink::RunObserver,
    permission::PermissionMode,
    run_artifacts::{AttachmentEvent, RunArtifactIdentity},
    session::{SessionPersistence, SessionProvenance},
    subagent::RunStatus,
    workflow::RunId,
};

/// Where a session's in-process agent runs take capacity, its subagents and
/// its workflow runs' agent nodes, and who else hears of them.
#[derive(Clone)]
pub(crate) enum SubagentPool {
    /// The session's own pool, sized by its config's `agent_concurrency`;
    /// nobody else hears of its runs.
    Own,
    /// A pool the host shares across its sessions, and the observer of the
    /// runs started here.
    Shared {
        concurrency: AgentConcurrency,
        observer: Arc<dyn ChildObserver>,
    },
}

impl SubagentPool {
    /// What hears of the runs started here, if anyone does.
    pub(crate) fn child_observer(&self) -> Option<Arc<dyn ChildObserver>> {
        match self {
            Self::Own => None,
            Self::Shared { observer, .. } => Some(Arc::clone(observer)),
        }
    }

    /// The pool runs take capacity from, an own one sized to
    /// `agent_concurrency`, and the observer that hears of them, if any.
    pub(crate) fn into_parts(
        self,
        agent_concurrency: usize,
    ) -> (AgentConcurrency, Option<Arc<dyn ChildObserver>>) {
        match self {
            Self::Own => (AgentConcurrency::from_config(agent_concurrency), None),
            Self::Shared {
                concurrency,
                observer,
            } => (concurrency, Some(observer)),
        }
    }

    /// The pool workflow run `run`'s agent nodes take capacity from: this
    /// one, whose observer hears of the run first and returns the observer
    /// of its nodes, and where to report how the run ended, if anyone
    /// follows it.
    pub(crate) fn host_workflow(
        self,
        run: StartedWorkflow,
    ) -> (Self, Option<tokio::sync::oneshot::Sender<WorkflowEnd>>) {
        match self {
            Self::Own => (Self::Own, None),
            Self::Shared {
                concurrency,
                observer,
            } => {
                let HostedWorkflow { observer, end } = observer.workflow_started(run);
                (
                    Self::Shared {
                        concurrency,
                        observer,
                    },
                    Some(end),
                )
            }
        }
    }
}

impl std::fmt::Debug for SubagentPool {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Own => formatter.write_str("Own"),
            Self::Shared { concurrency, .. } => formatter
                .debug_struct("Shared")
                .field("limit", &concurrency.total_limit())
                .finish_non_exhaustive(),
        }
    }
}

/// Hears of the subagent and workflow runs a session starts, and of the
/// agent node runs of those workflow runs. The daemon implements it to
/// record each run as a child job of the job that started it.
///
/// Both methods are called on the task that starts the run and must return
/// promptly; implementors follow the run on a task of their own.
pub(crate) trait ChildObserver: Send + Sync {
    /// Called right after the run is spawned, possibly before it has
    /// capacity and possibly after it already ended.
    fn subagent_started(&self, run: StartedSubagent);

    /// Called before the run is driven. Returns the observer of the run's
    /// agent node runs, and where the run reports how it ended. Workflow
    /// agent nodes start no workflow runs, so the returned observer only
    /// hears [`Self::subagent_started`].
    fn workflow_started(&self, run: StartedWorkflow) -> HostedWorkflow;
}

/// What a child run tells the observer that follows it (#1668): the events
/// of a Rho child's session, or of the one a run on an external agent
/// runtime is recorded under ([`ExternalRun`]), and the children such a
/// run's agent starts on its own.
pub(crate) enum ChildEvent {
    /// The run opened its session, which runs with `options` as the agent
    /// whose id is `agent`, on `runtime`. Sent once, before any
    /// [`Self::Session`].
    Opened {
        options: Box<SessionOptions>,
        agent: String,
        runtime: crate::agent::AgentRuntime,
    },
    /// One event of the run's session, as the daemon protocol's.
    Session(WireEvent),
    /// Not an event of the run's session: the run's agent started a child
    /// on its own, a run of its own the observer lists as the run's child
    /// (see `app::runtime_child_host`).
    RuntimeChild(Box<StartedSubagent>),
}

/// Where a child run sends its [`ChildEvent`]s. Unbounded: the observer
/// drains it on a task of its own into a stream that bounds what it keeps.
pub(crate) type ChildEventSender = UnboundedSender<ChildEvent>;

/// The observer's end of a [`ChildEventSender`].
pub(crate) type ChildEvents = UnboundedReceiver<ChildEvent>;

/// A run on an external agent runtime that a host follows: where it sends
/// its session's events, and where it records that session.
pub(crate) struct ExternalRun {
    pub(crate) events: ChildEventSender,
    /// The session the run is recorded under.
    pub(crate) session: rho_sdk::SessionId,
    /// The workspace the run works in.
    pub(crate) cwd: PathBuf,
    pub(crate) provenance: SessionProvenance,
    /// The run's id.
    pub(crate) run: String,
    /// The run's status file, beside which it keeps its attach journal.
    pub(crate) status: PathBuf,
    pub(crate) prompt: String,
    /// Whether the run's session is saved: not when its parent's is not.
    pub(crate) persistence: SessionPersistence,
}

impl ExternalRun {
    /// What hears the run of the agent bound as `identity`, in permission
    /// mode `mode`: it tells the host the run's session's events, and
    /// records that session in a file, created now, which gets the run's
    /// prompt and reply once it ends, beside the run's attach journal.
    pub(crate) fn observer(
        self,
        identity: &RunArtifactIdentity,
        mode: PermissionMode,
    ) -> Box<dyn RunObserver> {
        let created = match self.persistence {
            SessionPersistence::Saved => Some(ExternalRunFile::create(&self, identity, mode)),
            SessionPersistence::Ephemeral => None,
        };
        let (file, pending) = match created.transpose() {
            Ok(file) => (file, None),
            // The run goes on; its session shows only while it runs.
            Err(error) => {
                tracing::warn!(
                    session = %self.session,
                    run = %self.run,
                    error = format!("{error:#}"),
                    "could not create an external run's session file"
                );
                let notice = "could not save this run's session: it shows only while it runs";
                (None, Some(AttachmentEvent::Notice(notice.into())))
            }
        };
        let mut feed = ExternalRunFeed::new(self.events, identity, mode, file);
        feed.pending = pending;
        Box::new(feed)
    }
}

/// Tells a run's observer what a run on an external agent runtime records,
/// as the events of the session it is recorded under: opens that session
/// with the run's first recorded event, its prompt, once the run has
/// capacity and starts.
struct ExternalRunFeed {
    events: ChildEventSender,
    /// The session's opening, until it is sent.
    opening: Option<ChildEvent>,
    /// What the host is told once the session opens, besides what the run
    /// records.
    pending: Option<AttachmentEvent>,
    mapped: ExternalEvents,
    /// The session's file, until the run ends.
    file: Option<ExternalRunFile>,
}

impl ExternalRunFeed {
    /// Follows a run of the agent bound as `identity`, in permission mode
    /// `mode`, telling the host on `events`, and saving to `file`, if any.
    fn new(
        events: ChildEventSender,
        identity: &RunArtifactIdentity,
        mode: PermissionMode,
        file: Option<ExternalRunFile>,
    ) -> Self {
        Self {
            events,
            opening: Some(ChildEvent::Opened {
                options: Box::new(external_options(
                    &identity.provider,
                    identity.model.as_deref(),
                    mode.into(),
                )),
                agent: identity.agent_id.clone(),
                runtime: identity.runtime,
            }),
            pending: None,
            mapped: ExternalEvents::default(),
            file,
        }
    }
}

impl RunObserver for ExternalRunFeed {
    fn recorded(&mut self, event: &AttachmentEvent) {
        let opening = self.opening.take();
        let pending = opening.as_ref().and_then(|_| self.pending.take());
        let mapped = &mut self.mapped;
        let events = std::iter::once(event)
            .chain(pending.as_ref())
            .flat_map(|event| mapped.map(event))
            .map(ChildEvent::Session);
        for event in opening.into_iter().chain(events) {
            // The observer went away: nobody follows the run any more.
            let _ = self.events.send(event);
        }
    }

    fn ended(&mut self, reply: Option<&str>) {
        if let Some(file) = self.file.take() {
            file.finish(reply);
        }
    }
}

/// The event channel of a run about to start: both ends when `observer`
/// will hear of the run, neither when nobody follows it.
pub(crate) fn child_events(
    observer: Option<&Arc<dyn ChildObserver>>,
) -> (Option<ChildEventSender>, Option<ChildEvents>) {
    observer.map(|_| mpsc::unbounded_channel()).unzip()
}

/// A subagent run that just started, as its observer follows it.
pub(crate) struct StartedSubagent {
    /// The run's id among its parent session's runs.
    pub(crate) run_id: String,
    /// The session the run shows its events under; `None` for a run on an
    /// external runtime launched without the sender of `events`.
    pub(crate) session: Option<RunSession>,
    /// The directory the run works in.
    pub(crate) workspace: PathBuf,
    /// The run's status, from `queued` until it is terminal.
    pub(crate) status: tokio::sync::watch::Receiver<RunStatus>,
    /// Where the run waits for capacity, while it does.
    pub(crate) queue: QueueWatch,
    /// What the run tells of its session, from its opening; `None` for a
    /// run launched without the sender.
    pub(crate) events: Option<ChildEvents>,
    /// What the run shows as until it titles itself, from the moment it
    /// queues: its task's [`crate::title::placeholder`].
    pub(crate) task: Option<String>,
    /// Who started the run: Rho, or its parent's agent runtime.
    pub(crate) started_by: RunStarter,
}

/// What started a subagent run.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "snake_case")]
pub(crate) enum RunStarter {
    /// Rho: the `agent` tool of its parent, or the workflow run it is an
    /// agent node of.
    #[default]
    Rho,
    /// The agent runtime of its parent's session, on its own, as Claude
    /// Code starts a subagent with its Task tool (see
    /// `acp_runtime::runtime_children`). Nobody prompts or resumes it.
    Runtime,
}

impl RunStarter {
    /// Whether Rho started the run: what a job record that does not say
    /// means.
    pub(crate) fn is_rho(&self) -> bool {
        *self == Self::Rho
    }
}

/// The session a child run shows its events under, and what it holds.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) enum RunSession {
    /// The session a Rho child writes: its conversation, which a follow-up
    /// continues.
    Rho(rho_sdk::SessionId),
    /// The session a run on an external agent runtime is recorded under.
    /// The runtime keeps its own conversation; the session's file holds the
    /// run's prompt and reply, and the run's attach journal what it showed
    /// (see [`crate::session::SessionEngine::Acp`]).
    External(rho_sdk::SessionId),
}

impl RunSession {
    pub(crate) fn id(&self) -> &rho_sdk::SessionId {
        match self {
            Self::Rho(id) | Self::External(id) => id,
        }
    }
}

impl StartedSubagent {
    /// The run `handle` follows, started as `run_id` in `workspace` on
    /// `task`, which sends its session's events to `events`.
    pub(crate) fn of(
        run_id: String,
        workspace: PathBuf,
        handle: &AgentRunHandle,
        events: Option<ChildEvents>,
        task: Option<String>,
    ) -> Self {
        Self {
            run_id,
            session: handle.session().cloned(),
            workspace,
            status: handle.clone_status_watch(),
            queue: handle.queue(),
            events,
            task,
            started_by: RunStarter::Rho,
        }
    }
}

/// A workflow run about to be driven in the background.
pub(crate) struct StartedWorkflow {
    pub(crate) run_id: RunId,
    /// The workspace the run was planned in, where its nodes work.
    pub(crate) workspace: PathBuf,
}

/// How the host follows a workflow run it heard of.
pub(crate) struct HostedWorkflow {
    /// Hears of each of the run's agent node runs.
    pub(crate) observer: Arc<dyn ChildObserver>,
    /// Takes how the run ended. Dropped unsent when the drive stops without
    /// an end, such as when the host's runtime shuts down under it.
    pub(crate) end: tokio::sync::oneshot::Sender<WorkflowEnd>,
}

/// How a workflow run's drive ended.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) enum WorkflowEnd {
    /// Every node finished and the run succeeded.
    Completed,
    /// The run was cancelled.
    Cancelled,
    /// The run failed, was denied or blocked, or could not be driven.
    Failed(String),
}

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