rho-coding-agent 3.12.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
//! Reading a saved session the daemon has not loaded, without loading it:
//! opened only to be read, starting none of its MCP servers, OpenAPI
//! sources, or hooks, its worktree restored for the read and removed again,
//! and shut down again. An observe replays what the read found
//! (`observe.rs`), and history pages through it (`history.rs`).

use std::path::PathBuf;

use rho_protocol::{DetachReason, ErrorCode, RpcError};
use rho_sdk::SessionId;

use super::{
    engine::Engine,
    engine_replay::saved_engine,
    open::open_to_read,
    opening::opening_feed,
    options::available_auths,
    reopen::{saved_to_read, saved_workspace, ReopenGuard},
    worktree::{Restore, Restored},
    writing, Feed, Sessions,
};
use crate::{
    app::daemon_host::jobs::{JobId, JobRecord, SessionJob},
    session::SessionEngine,
};

impl Sessions {
    /// The saved session whose reopen lock `reopening` holds through the
    /// read, which the daemon has not loaded, read from what its run left:
    /// opened only to be read (see [`open_to_read`]) and shut down again,
    /// its worktree restored for the read and removed again.
    pub(super) async fn read_unloaded(
        &self,
        reopening: &ReopenGuard<'_>,
    ) -> Result<Unloaded, RpcError> {
        let id = reopening.id();
        let mut last = match self.jobs.session_job(id) {
            SessionJob::Busy(job) => return Err(writing(&job, id)),
            SessionJob::Last(record) => Some(*record),
            SessionJob::New => None,
        };
        // Read from what its run left, with no worktree to restore.
        let workspace = saved_workspace(id).await?;
        if let Some(engine) = saved_engine(workspace.clone(), id).await? {
            let run = self.jobs.last_writer(id).map(Box::new);
            return Ok(Unloaded::Engine {
                workspace,
                engine: Box::new(engine),
                run,
            });
        }
        let restored = match &mut last {
            Some(record) => self.restore_worktree(record, Restore::Reading).await?,
            None => Restored::Nothing,
        };
        let read = self.read_saved(id, last.clone()).await;
        // Removed again however the read went.
        if let (Restored::ForReading, Some(record)) = (restored, &last) {
            Self::end_read_checkout(record).await;
        }
        read
    }

    /// Saved session `id` whose last job is `last`, as
    /// [`Self::read_unloaded`] reads it once its worktree is on disk.
    async fn read_saved(
        &self,
        id: &SessionId,
        last: Option<JobRecord>,
    ) -> Result<Unloaded, RpcError> {
        let stored = saved_to_read(id).await?;
        // A session no daemon has run is idle, with no last turn. Its job
        // is not registered: reading it records nothing.
        let job = last.unwrap_or_else(|| {
            JobRecord::new_session(JobId::generate(), stored.cwd().to_path_buf(), id.clone())
        });
        let opened = open_to_read(stored, &self.subagents, &self.settings, &job.id).await?;
        // Read through `engine_replay` before this when an agent ran it.
        let Engine::Rho(runtime) = opened.engine else {
            return Err(RpcError::new(
                ErrorCode::SessionOpenFailed,
                format!("session {id} is run by an agent, whose journal shows it"),
            ));
        };
        let (feed, _, _) = opening_feed(
            &job,
            &runtime,
            &opened.config,
            &available_auths(runtime.credentials()).await,
        );
        // Unloaded, so nothing of it runs or wakes it: it is settled.
        feed.update_activity(|| false);
        feed.close(DetachReason::NotLoaded);
        let workspace = runtime.workspace_root().to_path_buf();
        runtime.shutdown().await;
        Ok(Unloaded::Saved {
            workspace,
            feed: Box::new(feed),
        })
    }
}

/// A saved session the daemon has not loaded, as [`Sessions::read_unloaded`]
/// read it.
pub(super) enum Unloaded {
    /// An agent runtime ran it, and its journal shows it.
    Engine {
        workspace: PathBuf,
        engine: Box<SessionEngine>,
        /// The job that last wrote it.
        run: Option<Box<JobRecord>>,
    },
    /// Rho ran it: its feed, closed, which replays it as a reopen would.
    Saved { workspace: PathBuf, feed: Box<Feed> },
}