rho-coding-agent 3.12.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
//! A parent's messages to its runs: to a run's live turn while it runs, or,
//! once a Rho run that saved its session ended and its result reached the
//! parent, to a follow-up of it, a new run under the same id that continues
//! that session with the message as its next turn.

use std::time::Instant;

use super::{AgentEntry, SubagentManager, ValidatedMessage};
use crate::{
    app::{
        agent_executor::{AgentRunHandle, ChildConversation, LaunchWorkspace},
        subagent_pool::{child_events, RunSession, StartedSubagent},
    },
    session::SessionPersistence,
};

/// Where a parent's message to a run goes.
enum Delivery {
    /// To the run's live turn.
    Live(AgentRunHandle),
    /// To a follow-up of the run, which ended: the run that follows it up,
    /// already started, and what its observer is told of it.
    FollowedUp(AgentRunHandle, StartedSubagent),
}

impl SubagentManager {
    /// Sends `message` to run `id`: to its live turn while it runs, or, once
    /// it ended, as a follow-up of it (see [`Self::follow_up`]).
    pub(crate) async fn message(&self, id: &str, message: &ValidatedMessage) -> anyhow::Result<()> {
        let id = crate::subagent::normalize_id(id)?;
        // Decided under the registry lock, which no await may hold.
        let delivery = {
            let mut entries = self.inner.lock().expect("delegated registry lock");
            let entry = entries
                .get_mut(&id)
                .ok_or_else(|| anyhow::anyhow!("unknown delegated run '{id}'"))?;
            if entry.handle.is_complete() {
                let (handle, started) = self.follow_up(&id, entry, message)?;
                Delivery::FollowedUp(handle, started)
            } else {
                Delivery::Live(entry.handle.clone())
            }
        };
        match delivery {
            Delivery::Live(handle) => handle.message_from_parent(message).await,
            Delivery::FollowedUp(handle, started) => {
                if let Some(observer) = &self.observer {
                    observer.subagent_started(started);
                }
                self.registered(handle);
                Ok(())
            }
        }
    }

    /// Follows up `entry`, run `id`, which ended: launches it again in its
    /// own session, under the same id and with the same agent, workspace and
    /// title, with `message` as the session's next turn, and makes the new
    /// run the entry's, whose result is delivered when it ends. Refused for a
    /// run whose session cannot be continued (one on another runtime, one
    /// never saved, or one whose directory is gone), while a person's turns
    /// in the daemon hold its session (see `session::lease`), and while the
    /// run's result has not reached the parent, since the new run would
    /// replace it. Runs under the registry lock, so two follow-ups of a run never
    /// both launch; the lock is held through the run's status write.
    fn follow_up(
        &self,
        id: &str,
        entry: &mut AgentEntry,
        message: &ValidatedMessage,
    ) -> anyhow::Result<(AgentRunHandle, StartedSubagent)> {
        let cannot = |why: &str| {
            anyhow::anyhow!("delegated run '{id}' has finished and cannot be followed up: {why}")
        };
        // What can never change first, so the model is not sent to read a
        // result only to be refused for a reason that held all along.
        // A run on another runtime is recorded under a session too, which
        // holds no conversation Rho can continue.
        let Some(RunSession::Rho(session)) = entry.handle.session().cloned() else {
            return Err(cannot(
                "only a Rho-runtime run keeps a session to continue; start a new run instead",
            ));
        };
        let launch = entry
            .launch
            .clone()
            .ok_or_else(|| cannot("it was never launched"))?;
        anyhow::ensure!(
            launch.persistence == SessionPersistence::Saved,
            cannot("its session was not saved; start a new run instead")
        );
        // Where the run worked and saved its session: the executor's own
        // directory, which may be spelled otherwise than the workspace the
        // run is listed in, or its worktree.
        let cwd = match &launch.workspace {
            LaunchWorkspace::Executor => self.executor.cwd(),
            LaunchWorkspace::Worktree { cwd, .. } => cwd,
        };
        anyhow::ensure!(
            cwd.is_dir(),
            cannot(&format!(
                "the directory it worked in, {}, is gone",
                cwd.display()
            ))
        );
        anyhow::ensure!(
            crate::session::Session::is_saved_in_workspace(cwd, session.as_str())?,
            cannot("it ended before it saved its session; start a new run instead")
        );
        // Its open would be refused; the run's own open is what guards it.
        anyhow::ensure!(
            !crate::session::is_held_alone(cwd, session.as_str())?,
            cannot("a person has its session open; follow it up once the daemon unloads it")
        );
        anyhow::ensure!(
            entry.observed,
            cannot(
                "its result has not reached you yet; read it with action=status, then follow up"
            )
        );
        let works_in = launch.works_in.clone();
        let conversation = ChildConversation::FollowUp {
            session,
            title: entry.handle.status().title,
        };
        let (events, followed) = child_events(self.observer.as_ref());
        let request = launch.request(id, message.as_str(), events, conversation);
        let handle = self.executor.spawn(request)?;
        entry.handle = handle.clone();
        entry.started = Instant::now();
        entry.observed = false;
        entry.explicitly_observed = false;
        let started = StartedSubagent::of(
            id.to_owned(),
            works_in,
            &handle,
            followed,
            entry.task_fallback.clone(),
        );
        Ok((handle, started))
    }
}