rho-coding-agent 3.12.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
//! The children an agent of another runtime starts on its own, as Claude
//! Code starts a subagent with its Task tool, recorded as runs a host
//! follows as child jobs (`rho_protocol::ChildRole::Runtime`): a daemon
//! session's, whose job hears of them directly, and a delegated run's,
//! which tells the job following it on its event channel.
//!
//! Each child's run is reserved where the session's subagents' runs go, so
//! it is listed, attached to and deleted as theirs are, and clients follow
//! its session's events as a subagent's. A child's own children are
//! recorded the same way, as children of its job, which hears of them on
//! the child's event channel. Rho did not start the child and its
//! conversation is the agent's, so nobody prompts, cancels or resumes it:
//! its session is not saved and shows only while it runs; its status and
//! attach journal stay.

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

use rho_sdk::SessionId;
use tokio::sync::{mpsc, watch};

use super::{
    agent_concurrency::QueueWatch,
    session_runtime::SessionRole,
    subagent_pool::{
        ChildEvent, ChildEventSender, ChildObserver, ExternalRun, RunSession, RunStarter,
        StartedSubagent,
    },
};
use crate::{
    acp_runtime::runtime_children::{ChildRecord, RuntimeChild, RuntimeChildren, StartedChild},
    permission::PermissionMode,
    run_artifacts::RunArtifactIdentity,
    session::SessionPersistence,
    subagent::{self, RunPlacement, RESULT_FILE_NAME},
};

/// Where the children of one run are recorded, before the run's agent is
/// known: the session they work for, where their runs go, and who hears of
/// each.
#[derive(Clone)]
pub(crate) struct RecordedChildren {
    /// The session the children work for, which deleting deletes them.
    pub(crate) works_for: SessionId,
    /// Where that session's subagents' runs go.
    pub(crate) placement: RunPlacement,
    /// Where the run, and its children, work.
    pub(crate) workspace: PathBuf,
    /// The workspace the run index files the children's runs under
    /// ([`subagent::reserve_run_directory`]): the session's own, as for its
    /// subagents', even for a run in a worktree.
    pub(crate) indexed_under: PathBuf,
    /// Who lists each child as a child job.
    pub(crate) announce: Announce,
}

/// Who hears of each child, which lists it as a child job.
#[derive(Clone)]
pub(crate) enum Announce {
    /// The observer of a session's subagents: the child is the session's.
    Observer(Arc<dyn ChildObserver>),
    /// The event channel of a run its host follows: the child is the run's.
    Events(ChildEventSender),
}

impl RecordedChildren {
    /// The host of a run of the agent bound as `identity`, in permission
    /// mode `mode`, which each child runs as too.
    pub(crate) fn host(
        self,
        identity: &RunArtifactIdentity,
        mode: PermissionMode,
    ) -> Arc<dyn RuntimeChildren> {
        Arc::new(Host {
            children: self,
            identity: identity.clone(),
            mode,
        })
    }
}

/// [`RecordedChildren`] of a run whose agent is known.
struct Host {
    children: RecordedChildren,
    identity: RunArtifactIdentity,
    mode: PermissionMode,
}

impl RuntimeChildren for Host {
    fn started(&self, child: RuntimeChild) -> StartedChild<'_> {
        Box::pin(async move {
            let placement = self.children.placement.clone();
            let indexed_under = self.children.indexed_under.clone();
            let (run, directory) = tokio::task::spawn_blocking(move || {
                subagent::reserve_run_directory(&placement, &indexed_under)
            })
            .await
            .map_err(|error| error.to_string())?
            .map_err(|error| format!("{error:#}"))?;
            Ok(self.record(child, run, directory))
        })
    }
}

impl Host {
    /// Child `child`'s run `run`, reserved in `directory`, as its job
    /// follows it.
    fn record(&self, child: RuntimeChild, run: String, directory: PathBuf) -> ChildRecord {
        let RecordedChildren {
            works_for,
            workspace,
            announce,
            ..
        } = &self.children;
        let RuntimeChild {
            title,
            description,
            task,
            ..
        } = child;
        let output_file = directory.join(RESULT_FILE_NAME);
        let shown_as = SessionId::new();
        let (events, followed) = mpsc::unbounded_channel();
        let prompt = task.text_content();
        // The role a saved session would record; a child's is never saved
        // (`Ephemeral`), so its provenance is never persisted.
        let role = SessionRole::Subagent {
            parent: works_for.clone(),
            parent_workspace: Some(workspace.clone()),
        };
        // The child's own children are its job's, which hears of them on
        // the child's event channel.
        let grandchildren = RecordedChildren {
            announce: Announce::Events(events.clone()),
            ..self.children.clone()
        }
        .host(&self.identity, self.mode);
        let observer = ExternalRun {
            events,
            session: shown_as.clone(),
            cwd: workspace.clone(),
            provenance: role.provenance(),
            run: run.clone(),
            status: output_file.clone(),
            prompt: prompt.clone(),
            persistence: SessionPersistence::Ephemeral,
        }
        .observer(&self.identity, self.mode);
        let works_for = Some(works_for.to_string());
        let mut status = self.identity.starting_status();
        status.parent_session_id.clone_from(&works_for);
        let (status_tx, status_rx) = watch::channel(status);
        // Until the run is titled, it shows as what the agent calls it.
        let shown = title
            .or(description)
            .or_else(|| crate::title::placeholder(&prompt));
        let started = StartedSubagent {
            run_id: run,
            session: Some(RunSession::External(shown_as)),
            workspace: workspace.clone(),
            status: status_rx,
            queue: QueueWatch::default(),
            events: Some(followed),
            task: shown,
            started_by: RunStarter::Runtime,
        };
        match announce {
            Announce::Observer(observer) => observer.subagent_started(started),
            // Nobody follows the run any more: its child goes unlisted, as
            // a subagent started then would.
            Announce::Events(events) => {
                let _ = events.send(ChildEvent::RuntimeChild(Box::new(started)));
            }
        }
        ChildRecord {
            output_file,
            works_for,
            identity: self.identity.clone(),
            status_tx: Some(status_tx),
            observer: Some(observer),
            children: Some(grandchildren),
        }
    }
}