rho-coding-agent 3.12.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
//! What a loaded session opens with, from its engine: the watchers and
//! views Rho's own loop has, and the feed, which for Rho's loop holds the
//! conversation its file saved and how its job's last turn ended.

use std::path::Path;

use super::{
    acp_background,
    acp_tools::ServedTools,
    acp_turns::AcpTurns,
    background::SessionBackground,
    cache_warm::KeepWarm,
    child_questions::ChildQuestions,
    engine::Engine,
    feed::Feed,
    idle_wake::IdleWatch,
    options,
    peer_wake::PeerWake,
    prompt_keys::PromptKeys,
    self_questions::OwnQuestions,
    t3_wake::{T3Wake, WakeDir},
    JobId, JobRecord,
};
use crate::{
    app::{
        daemon_host::wire::state_event,
        session_events::{LiveEvents, SavedTurn},
        session_mcp::SessionMcp,
        session_runtime::{SavedHistory, SessionHandle, SessionRuntime},
    },
    config::Config,
    session::tree::ProjectedMessage,
};

/// The rows `runtime` has saved that `live` has not replayed yet, as a turn
/// of the feed's transcript, or `None` when it has saved none since or they
/// could not be read.
pub(super) fn saved_replay(
    live: &mut LiveEvents,
    runtime: &SessionRuntime,
    job: &JobId,
) -> Option<SavedTurn> {
    let saved = runtime.saved_history()?;
    let rows = saved_rows(&saved, job)?;
    live.replay(&rows, saved.cwd(), saved.tools())
}

/// The rows of `saved` along the session's branch, or `None` when they
/// could not be read.
fn saved_rows(saved: &SavedHistory<'_>, job: &JobId) -> Option<Vec<ProjectedMessage>> {
    saved
        .display_rows()
        .inspect_err(|error| {
            tracing::warn!(
                %job,
                error = format!("{error:#}"),
                "could not read the session's saved rows; a reset replays only the turns since, live, until a later turn saves"
            );
        })
        .ok()
}

/// The feed of a session opened as `runtime` with `config`, whose turns are
/// recorded on `job`, the mapper that replayed it, and the keyed prompts its
/// saved rows and job name: the feed begins with the conversation the
/// session has saved and how the job's last turn ended, which a new session
/// has neither of, so a client attaching to a reopened session learns that
/// end (#1661).
pub(super) fn opening_feed(
    job: &JobRecord,
    runtime: &SessionRuntime,
    config: &Config,
    auths: &[String],
) -> (Feed, LiveEvents, PromptKeys) {
    let mut live = LiveEvents::new(
        runtime.workspace_root(),
        runtime.tools(),
        runtime.configured_context_window(),
    );
    // Titles are not saved with the transcript, so the feed starts with the
    // one the session's file has.
    let last = job.moved();
    let feed = Feed::new(
        (&last.state).into(),
        last.turn.clone(),
        runtime.stored_title(),
        options::daemon_options(runtime, config, auths),
        runtime.agent_id().to_string(),
    );
    feed.seed_started_session_defaults(options::started_session_defaults(
        runtime.started_session_defaults(),
    ));
    let saved = runtime.saved_history();
    let rows = saved.as_ref().and_then(|saved| saved_rows(saved, &job.id));
    let saved_keys = saved.as_ref().map_or_else(Vec::new, |saved| {
        saved.message_keys().unwrap_or_else(|error| {
            tracing::warn!(
                job = %job.id,
                error = format!("{error:#}"),
                "could not read the session's saved message keys; a prompt sent again with the key of a saved message starts a turn"
            );
            Vec::new()
        })
    });
    let keys = PromptKeys::loaded(job, &saved_keys);
    if let Some(turn) = saved
        .zip(rows)
        .and_then(|(saved, rows)| live.replay(&rows, saved.cwd(), saved.tools()))
    {
        feed.end_turn(turn);
        feed.seed_usage(&live.context_usage(runtime.context_estimate()));
    }
    // An outcome is recorded with the turn it is of.
    if let (Some(outcome), Some(turn)) = (job.outcome.clone(), last.turn.clone()) {
        feed.publish([
            rho_protocol::SessionEvent::TurnEnded { turn, outcome },
            state_event(&last),
        ]);
    }
    (feed, live, keys)
}

/// What a loaded session takes from its engine as it opens: the watchers
/// and views Rho's loop has, which a session an agent runs has none of,
/// and its opening feed.
pub(super) struct EngineParts {
    pub(super) wake: Option<tokio::sync::Mutex<T3Wake>>,
    pub(super) idle_wake: Option<IdleWatch>,
    pub(super) cache_warm: Option<KeepWarm>,
    pub(super) peer_wake: PeerWake,
    pub(super) child_questions: Option<ChildQuestions>,
    pub(super) own_questions: Option<OwnQuestions>,
    pub(super) handle: SessionHandle,
    pub(super) live: LiveEvents,
    pub(super) mcp: SessionMcp,
    pub(super) background: SessionBackground,
    pub(super) feed: Feed,
    pub(super) keys: PromptKeys,
    pub(super) engine: Engine,
}

impl EngineParts {
    /// Rho's loop running the session: its watchers and views, and its
    /// opening feed, its turns recorded on `job`.
    pub(super) fn rho(
        mut runtime: Box<SessionRuntime>,
        job: &JobRecord,
        config: &Config,
        auths: &[String],
        wakes: &WakeDir,
    ) -> Self {
        let (feed, live, keys) = opening_feed(job, &runtime, config, auths);
        Self {
            wake: T3Wake::of(&runtime, wakes).map(tokio::sync::Mutex::new),
            idle_wake: IdleWatch::of(&runtime),
            cache_warm: KeepWarm::of(&runtime),
            peer_wake: PeerWake::of(runtime.session_id(), &runtime),
            child_questions: ChildQuestions::of(&mut runtime),
            own_questions: OwnQuestions::of(&runtime),
            handle: runtime.handle(),
            live,
            mcp: SessionMcp::of(&runtime),
            background: SessionBackground::of(&runtime),
            feed,
            keys,
            engine: Engine::Rho(runtime),
        }
    }

    /// An agent of another runtime running the session's turns, recorded on
    /// `job`, under the config at `config_path`: its opening feed, the
    /// background work and subagents' questions of the tools it is served,
    /// the idle watcher and the notices of the turns it starts in other
    /// sessions where the daemon wakes it (see `acp_background`), and none
    /// of the other watchers and views of Rho's own loop.
    pub(super) fn acp(mut turns: Box<AcpTurns>, job: &JobRecord, config_path: &Path) -> Self {
        let background = acp_background::background(turns.session_id().to_string(), turns.served());
        let peers = turns.served().and_then(ServedTools::peers).cloned();
        Self {
            wake: None,
            idle_wake: IdleWatch::for_wait(background.wait()),
            cache_warm: None,
            // Only Rho's loop reports to a starter: the parser refuses
            // `starter_hears: reports` on another runtime.
            peer_wake: PeerWake::new(turns.session_id(), peers, /*report*/ None),
            child_questions: turns
                .served_mut()
                .and_then(ServedTools::take_child_questions)
                .map(ChildQuestions::served),
            // Only Rho's loop reports to a starter.
            own_questions: None,
            handle: SessionHandle::without_runtime(),
            live: LiveEvents::without_tools(turns.workspace()),
            mcp: SessionMcp::none(config_path.to_path_buf()),
            background,
            feed: turns.opening_feed(job),
            keys: PromptKeys::loaded(job, /*saved*/ &[]),
            engine: Engine::Acp(turns),
        }
    }
}