rho-coding-agent 3.12.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
//! Reading a saved session another engine than Rho's own loop ran
//! ([`SessionEngine`]): a subagent or workflow agent node run on an
//! external agent runtime, whose file holds its prompt and reply, or a
//! daemon session such an agent runs turn by turn, whose file holds every
//! prompt and reply. Its replay is what the agent showed, from the attach
//! journal, mapped as the live stream mapped it ([`ExternalEvents`]), so a
//! client sees it the same whether it followed it live or observes it
//! later, after a restart included.

use std::path::{Path, PathBuf};

use rho_protocol::{
    self as wire, Cursor, DetachReason, ErrorCode, RpcError, SessionAttachAnswer, Subscription,
};
use rho_sdk::SessionId;

use super::{
    acp_turns, attach_response, child_feeds::turn_end, feed::Feed, options, store::store_blocking,
};
use crate::{
    app::{
        daemon_host::{
            jobs::{JobRecord, JobState, TurnEnd},
            subagents::{outcome, run_end},
        },
        session_events::{external_options, ExternalEvents},
    },
    run_artifacts::{AttachmentEvent, AttachmentReader},
    session::{Session as StoredSession, SessionEngine},
    subagent::{self, RunStatus, ATTACHMENT_FILE_NAME, RESULT_FILE_NAME},
};

/// What runs the turns of session `id`, saved in `workspace`: `None` for
/// Rho's own loop.
pub(super) async fn saved_engine(
    workspace: PathBuf,
    id: &SessionId,
) -> Result<Option<SessionEngine>, RpcError> {
    let id = id.clone();
    store_blocking("read the session's engine", move || {
        StoredSession::engine_by_id(&workspace, id.as_str())
    })
    .await
}

/// The replay of session `id`, saved in `workspace`, which `engine` ran, as
/// a client resuming from `after` gets it, then nothing. `run` is the job
/// of the run that wrote it, if the daemon still knows it.
pub(super) async fn read(
    id: &SessionId,
    workspace: &Path,
    engine: SessionEngine,
    after: Option<&Cursor>,
    run: Option<&JobRecord>,
) -> Result<(SessionAttachAnswer, Subscription), RpcError> {
    // A daemon session an agent runs keeps a copy of the choice for the
    // sessions it starts, which a client sees as it would once it loads.
    let (artifacts, permission_mode, keeps_choice) = match engine {
        SessionEngine::Acp {
            artifacts,
            permission_mode,
        } => (artifacts, permission_mode, false),
        SessionEngine::AcpSession {
            artifacts,
            permission_mode,
        } => (artifacts, permission_mode, true),
        SessionEngine::Unknown => {
            return Err(RpcError::new(
                ErrorCode::SessionOpenFailed,
                format!("session {id} ran on an engine this daemon does not know"),
            ));
        }
    };
    let (status, events, started) = store_blocking("read the run's events", move || {
        let directory = artifacts.directory(&crate::paths::rho_dir()?);
        let started = keeps_choice.then(|| acp_turns::started::read(&directory));
        let (status, events) = read_run(&directory)?;
        Ok((status, events, started))
    })
    .await?;
    let ended = run.and_then(|job| match &job.state {
        JobState::Ended(end) => Some(end.clone()),
        JobState::Idle
        | JobState::Queued
        | JobState::Running
        | JobState::Requeued
        | JobState::WaitingForInput => None,
    });
    let feed = replay(&status, &events, permission_mode, ended);
    if let Some(started) = started {
        feed.seed_started_session_defaults(options::started_session_defaults(&started));
    }
    feed.close(DetachReason::NotLoaded);
    Ok(attach_response(
        workspace,
        feed.attach(super::ResumeFrom::cursor(after)),
    ))
}

/// The status of the run whose artifacts are in `directory`, and the events
/// its attach journal recorded.
fn read_run(directory: &Path) -> anyhow::Result<(RunStatus, Vec<AttachmentEvent>)> {
    let status = subagent::read_status(&directory.join(RESULT_FILE_NAME)).ok_or_else(|| {
        anyhow::anyhow!(
            "the run in {} has no status that reads",
            directory.display()
        )
    })?;
    let events = AttachmentReader::new(directory.join(ATTACHMENT_FILE_NAME)).read_new()?;
    Ok((status, events))
}

/// The stream of a run whose `status` and recorded `events` the run left,
/// in permission mode `mode`, as its live stream showed it, framed as one
/// turn, which ended as `ended` says, or as its status does when the daemon
/// no longer knows its job. A daemon session's journal holds every turn,
/// each from its prompt, so its replay shows them all, under that one
/// turn's id, ending as its last turn did. A run whose status never ended
/// was cut short by a daemon that stopped.
fn replay(
    status: &RunStatus,
    events: &[AttachmentEvent],
    mode: wire::PermissionMode,
    ended: Option<TurnEnd>,
) -> Feed {
    let options = external_options(
        status.provider.as_deref().unwrap_or_default(),
        status.model.as_deref(),
        mode,
    );
    let turn = wire::TurnId::new(uuid::Uuid::new_v4().hyphenated().to_string());
    let feed = Feed::new(
        wire::JobState::Running,
        Some(turn.clone()),
        status.title.clone(),
        options,
        status.agent_id.clone().unwrap_or_default(),
    );
    publish_journal(&feed, events);
    let end = ended
        .or_else(|| run_end(status, /*stopping*/ false))
        .unwrap_or(TurnEnd::Interrupted);
    let outcome = outcome(&end, status);
    feed.publish(turn_end(&turn, outcome, (&JobState::Ended(end)).into()));
    // Nothing of it runs or wakes it: it is settled.
    feed.update_activity(|| false);
    feed
}

/// Publishes to `feed` what a journal's `events` showed, as the live
/// stream mapped them, but for the terminals of the processes served
/// `process` starts ran ([`without_terminals`]). A journal a dying daemon
/// cut off leaves its calls running, which this closes.
pub(super) fn publish_journal(feed: &Feed, events: &[AttachmentEvent]) {
    let mut mapped = ExternalEvents::default();
    feed.publish(
        events
            .iter()
            .flat_map(|event| mapped.map(event))
            .map(without_terminals)
            .map(unsteered),
    );
    feed.publish(mapped.cut_short());
}

/// `event` as history: a steer's user message replays as one, carrying no
/// steer id, which marks a steer that just applied.
fn unsteered(mut event: wire::SessionEvent) -> wire::SessionEvent {
    if let wire::SessionEvent::UserMessage { steer, .. } = &mut event {
        *steer = None;
    }
    event
}

/// `event` without the terminals it shows. A journal is read only as the
/// session loads, or while nothing has it loaded, and the processes its
/// served calls started ended with the load that ran them, so none of
/// those terminals has output to send: a Rho session's replay shows a
/// process's terminal only while it runs (`session_events/replay.rs`).
fn without_terminals(mut event: wire::SessionEvent) -> wire::SessionEvent {
    if let wire::SessionEvent::ToolCall(update) = &mut event {
        if let Some(content) = &mut update.content {
            content.retain(|content| !matches!(content, wire::ToolContent::Terminal { .. }));
        }
    }
    event
}

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