rho-coding-agent 3.11.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
//! A Rho agent run that a session or a workflow started: a subagent the
//! `agent` tool delegated, or a workflow agent node. Its session is saved
//! like any other, tagged with its role, unless its parent's is never saved,
//! and the parent watches its status file. The child sends its prompt as
//! given, decides its approvals alone or as the parent passed down, and
//! stops when the parent cancels it. A workflow node an earlier process left
//! running reopens its saved session and continues it instead, or reports
//! the final reply that session already holds without asking the model again.
//! A follow-up of a finished subagent reopens the session that subagent
//! saved and sends its prompt there as the next turn.

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

use rho_sdk::UserInput;
use rho_tools::cancellation::RunCancellation;

use super::{run_prompt, HeadlessView, ParentQuestions, PromptEnd, RunReporter, Stops};
use crate::{
    app::{
        agent_binding::{narrower_permission_mode, BoundAgent},
        agent_concurrency::RunSlot,
        cli_config::{settle_bound_config, ProviderRefreshStatus, SettledConfig},
        session_runtime::{
            subagent_session, HostCapabilities, LeftOut, NodeSession, QuestionSupport, RunShape,
            SessionBuild, SessionLaunch, SessionOpening, SessionRole, SessionRuntime, Turn,
            TurnStart, UnattendedApprovals,
        },
        shutdown_signal::ShutdownSignals,
        subagent_messaging::{NoticePoster, SteeringSlot, CHILD_COMMUNICATION_CONTRACT},
        subagent_pool::ChildEventSender,
    },
    session::SessionPersistence,
    subagent::RunStatus,
};

/// The session a child runs in.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) enum ChildSession {
    /// A new session under this id: a subagent's, or a workflow node
    /// attempt's first run.
    New(rho_sdk::SessionId),
    /// The session saved under exactly this id in the child's workspace,
    /// which must be a session of the agent the child is bound to: a
    /// workflow node attempt that an earlier process left running. The child
    /// continues the conversation saved there, sends its prompt when none was
    /// saved yet, or reports the final reply saved there.
    Reopen(rho_sdk::SessionId),
    /// The session a finished subagent run of the agent the child is bound
    /// to saved under exactly `id`, in the child's workspace. The child sends
    /// its prompt there as the conversation's next turn, in the mode its
    /// first run ran in (or one a host saved on its session) or `ceiling`,
    /// the parent's now, whichever is narrower.
    FollowUp {
        id: rho_sdk::SessionId,
        ceiling: crate::permission::PermissionMode,
    },
}

impl ChildSession {
    pub(crate) fn id(&self) -> &rho_sdk::SessionId {
        match self {
            Self::New(id) | Self::Reopen(id) | Self::FollowUp { id, .. } => id,
        }
    }

    /// Where the run's attach journal starts: a follow-up's continues the
    /// one the run it follows up wrote.
    fn journal(&self) -> crate::run_artifacts::JournalStart {
        match self {
            Self::New(_) | Self::Reopen(_) => crate::run_artifacts::JournalStart::New,
            Self::FollowUp { .. } => crate::run_artifacts::JournalStart::Continue,
        }
    }

    /// How the child's first turn starts once its session is open.
    fn first_turn(&self) -> FirstTurn {
        match self {
            Self::New(_) | Self::Reopen(_) => FirstTurn::PromptUnlessConversation,
            Self::FollowUp { .. } => FirstTurn::Prompt,
        }
    }

    /// The mode the child may run in at most, whatever it was launched or
    /// saved with: a follow-up's parent may have narrowed its own since the
    /// run began.
    fn permission_ceiling(&self) -> Option<crate::permission::PermissionMode> {
        match self {
            Self::New(_) | Self::Reopen(_) => None,
            Self::FollowUp { ceiling, .. } => Some(*ceiling),
        }
    }
}

/// How a child's first turn starts once its session is open.
#[derive(Clone, Copy)]
enum FirstTurn {
    /// Its prompt, unless the session holds a conversation already, as a
    /// reopened workflow node's may, which the turn continues instead.
    PromptUnlessConversation,
    /// Its prompt, as the next turn of whatever conversation the session
    /// holds.
    Prompt,
}

/// One child run on the Rho runtime, after binding and permit acquisition.
pub(crate) struct ChildRun {
    /// A Rho agent, whose binding carries the config the child settles.
    pub(crate) bound: BoundAgent,
    pub(crate) config_path: PathBuf,
    pub(crate) cwd: PathBuf,
    pub(crate) prompt: String,
    pub(crate) output_file: PathBuf,
    /// A subagent with its parent, or a workflow node.
    pub(crate) role: SessionRole,
    /// Whether a new session is saved: as its parent's is, for a subagent;
    /// always, for a workflow node. Ignored for a reopened session, which is
    /// saved already.
    pub(crate) persistence: SessionPersistence,
    /// The parent that answers the child's questions, when one listens.
    pub(crate) questions: Option<ParentQuestions>,
    /// The child's slot, its runtime's model request gate.
    pub(crate) slot: Arc<RunSlot>,
    /// The parent the child posts notices to, when one listens.
    pub(crate) notices: Option<Arc<dyn NoticePoster>>,
    pub(crate) steering_slot: Option<SteeringSlot>,
    pub(crate) cancellation: RunCancellation,
    pub(crate) status_tx: tokio::sync::watch::Sender<RunStatus>,
    pub(crate) live_title: crate::run_artifacts::LiveRunTitle,
    pub(crate) hook_host_labels: rho_sdk::hooks::HookHostLabels,
    pub(crate) approvals: UnattendedApprovals,
    pub(crate) session: ChildSession,
    pub(crate) added_dirs: crate::added_dirs::AddedDirs,
    pub(crate) environment: crate::session_environment::SessionEnvironment,
    /// Where the session's events go, when the host follows them.
    pub(crate) events: Option<ChildEventSender>,
}

/// Runs `run` to its end, reporting it in its status file. Fails only when
/// the run could not be reported or failed; a stop ends it as stopped.
pub(crate) async fn run_child(run: ChildRun) -> anyhow::Result<()> {
    let ChildRun {
        bound,
        config_path,
        cwd,
        prompt,
        output_file,
        role,
        persistence,
        questions,
        slot,
        notices,
        steering_slot,
        cancellation,
        status_tx,
        live_title,
        hook_host_labels,
        approvals,
        session,
        added_dirs,
        environment,
        events,
    } = run;

    let bound_config = bound
        .rho_config()
        .ok_or_else(|| anyhow::anyhow!("agent {} does not run on rho", bound.id()))?
        .clone();
    let SettledConfig {
        config,
        diagnostics,
    } = settle_bound_config(
        bound_config,
        &bound,
        environment.credentials(),
        &ProviderRefreshStatus::NotAttempted,
        rho_providers::model::ReasoningRequestSource::PersistedOrDefault,
    )
    .await?;
    let started_status = status_tx.borrow().clone();
    let sink = crate::run_artifacts::RunArtifactSink::continue_from(
        output_file,
        started_status,
        Some(crate::run_artifacts::AttachmentEvent::Prompt(
            prompt.clone(),
        )),
        Some(status_tx),
        Some(live_title),
        session.journal(),
    )?;
    let mut reporter = RunReporter::continue_into(sink, cwd.clone(), steering_slot.clone());
    let first_turn = session.first_turn();
    let ceiling = session.permission_ceiling();
    let max_steps = std::num::NonZeroUsize::new(
        bound
            .step_limit()
            .try_into()
            .map_err(|_| anyhow::anyhow!("agent step limit does not fit this platform"))?,
    )
    .ok_or_else(|| anyhow::anyhow!("agent step limit must be positive"))?;
    let mut stops = Stops::on_signals(ShutdownSignals::install()?).or_cancelled(cancellation);
    // A reopened session is found before anything opens, so one that already
    // holds the agent's final reply ends the run with it, as a finished turn
    // would, without asking the model again.
    let (id, saved) = match session {
        ChildSession::New(id) => (id, None),
        ChildSession::Reopen(id) => match NodeSession::find(&cwd, &id, &bound) {
            Ok(NodeSession::Unsaved) => (id, None),
            Ok(NodeSession::Saved(stored)) => (id, Some(stored)),
            Ok(NodeSession::Answered(reply)) => {
                reporter.finish_answered(reply);
                return Ok(());
            }
            Err(error) => {
                reporter.finish_error(&error);
                return Err(error);
            }
        },
        ChildSession::FollowUp { id, .. } => match subagent_session(&cwd, &id, &bound) {
            Ok(stored) => (id, Some(stored)),
            Err(error) => {
                reporter.finish_error(&error);
                return Err(error);
            }
        },
    };
    let build = SessionBuild {
        launch: SessionLaunch {
            config_path,
            left_out: LeftOut {
                subagents: true,
                ..LeftOut::default()
            },
            diagnostics,
            agent: bound,
            prompt_suffix: Some(CHILD_COMMUNICATION_CONTRACT),
            host_prompt: None,
        },
        host: HostCapabilities {
            // A child shows its parent's user nothing in this version.
            surfaces: None,
            pull_requests: None,
            browser: None,
            questions: match &questions {
                Some(_) => QuestionSupport::Available,
                None => QuestionSupport::Unavailable,
            },
            environment,
            parent_notices: notices,
            // The child takes its slot again before a request it makes
            // after giving it back for a question.
            model_requests: Some(slot),
            ..HostCapabilities::unattended(approvals)
        },
        run: RunShape {
            role,
            max_steps: Some(max_steps),
            hook_labels: hook_host_labels,
        },
    };
    let opening = SessionOpening {
        build,
        process_config: &config,
        host_mcp: Default::default(),
        cwd: &cwd,
        added_dirs,
    };
    let open = async {
        // `NodeSession::find` and `subagent_session` held a saved session to
        // the agent the child is bound to, as its root session, which opens
        // as the launch agent.
        let mut runtime = match saved {
            None => {
                SessionRuntime::open_new(opening, id, persistence, /*started_by*/ None).await?
            }
            Some(stored) => SessionRuntime::open_saved(opening, stored).await?,
        };
        // After any saved settings were restored, so they cannot loosen it.
        if let Some(ceiling) = ceiling {
            let mode = narrower_permission_mode(runtime.permission_mode(), ceiling);
            runtime
                .set_permission_mode(mode, &config)
                .await
                .map_err(|error| {
                    anyhow::anyhow!(
                        "could not hold the follow-up to permission mode {}: {error}",
                        mode.as_str()
                    )
                })?;
        }
        // The parent steers the child's model turns through its handle.
        if let Some(slot) = &steering_slot {
            slot.publish(runtime.handle());
        }
        anyhow::Ok(runtime)
    };
    let mut view = HeadlessView::new()
        .reporting_to(&mut reporter)
        .with_parent_questions(questions);
    if let Some(events) = events {
        view = view.streaming_to(events);
    }
    // The child's status file keeps the title its prompt was given; the
    // view drops the session's own title request.
    let end = run_prompt(
        &mut stops,
        &mut view,
        &config,
        open,
        |runtime, view, scope, process_config| {
            // A reopened session saved before its prompt reached the model,
            // or not at all, holds no conversation and still needs it.
            let start = match (first_turn, runtime.has_conversation()) {
                (FirstTurn::PromptUnlessConversation, true) => TurnStart::Continue,
                (FirstTurn::PromptUnlessConversation, false) | (FirstTurn::Prompt, _) => {
                    let input = UserInput::text(prompt);
                    view.prompt(&input);
                    TurnStart::Prompt(Turn {
                        display: input.clone(),
                        model: input,
                        calls: Vec::new(),
                    })
                }
            };
            Box::pin(runtime.run_prompt_turn(view, scope, start, process_config))
        },
    )
    .await;
    drop(view);
    match end {
        PromptEnd::Finished(outcome) => reporter.finish_ok(&outcome),
        PromptEnd::Stopped(_) => reporter.finish_stopped(),
        PromptEnd::Failed(error) => {
            reporter.finish_error(&error);
            return Err(error);
        }
    }
    Ok(())
}