rho-coding-agent 3.11.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
//! Sessions whose turns another engine than Rho's own loop runs: an agent
//! on an external runtime over ACP, which keeps its own conversation. That
//! is a subagent or workflow agent node's one run, or a daemon session the
//! agent runs turn by turn. The file records each prompt and final reply,
//! for listings, search and reading, and its header names the artifacts,
//! whose attach journal holds what the agent showed, for clients that
//! replay it.
//!
//! The file records the run's agent, which no Rho runtime runs: a build
//! that predates the engine exports the file but refuses to open it, to
//! continue or to read it, as it cannot bind its agent; a subagent's it
//! also refuses to continue for its origin, as only its parent does.

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

use rho_sdk::{
    model::{Message, ModelIdentity},
    CompactionState, Revision, SessionId, SessionSnapshot,
};
use serde::{Deserialize, Serialize};

use super::{
    agent_identity, resolve_saved, session_root, unix_timestamp_secs, Session, SessionProvenance,
    SessionStore,
};

/// What runs a session's turns, as its header records it. A header with
/// none is a session of Rho's own loop.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub(crate) enum SessionEngine {
    /// A subagent or workflow agent node run on an external agent runtime
    /// over ACP, in `permission_mode`. What it showed is the attach journal
    /// among the run's `artifacts`, whose status names the runtime. Nothing
    /// continues, forks or resumes it.
    ///
    /// A later Rho must not change these fields: a header whose `acp`
    /// engine does not read does not read at all.
    Acp {
        artifacts: RunArtifacts,
        permission_mode: rho_protocol::PermissionMode,
    },
    /// A daemon session whose turns an agent on an external runtime runs
    /// over ACP, in `permission_mode`, one agent process per turn: each
    /// turn after the first resumes the agent's own session, which the
    /// status among the session's `artifacts` names. Its attach journal
    /// holds every turn, each from its prompt. Nothing forks it.
    ///
    /// A later Rho must not change these fields, as for [`Self::Acp`].
    AcpSession {
        artifacts: RunArtifacts,
        permission_mode: rho_protocol::PermissionMode,
    },
    /// An engine a later Rho records that this one does not know.
    #[serde(other)]
    Unknown,
}

/// The directory of a run's artifacts, its status and attach journal, as a
/// path under the rho home, which holds every run's: a subagent run's under
/// `subagents` or its parent session's folder, a workflow node attempt's
/// under `workflows`. Only plain components, so it never leaves the home.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(try_from = "PathBuf", into = "PathBuf")]
pub(crate) struct RunArtifacts(PathBuf);

impl RunArtifacts {
    /// The artifacts in `directory`, which must be under `rho_home`.
    pub(crate) fn of(directory: &Path, rho_home: &Path) -> anyhow::Result<Self> {
        let relative = directory.strip_prefix(rho_home).map_err(|_| {
            anyhow::anyhow!(
                "the run's artifacts at {} are outside the rho home {}",
                directory.display(),
                rho_home.display()
            )
        })?;
        Self::try_from(relative.to_path_buf())
    }

    /// The artifacts' directory under `rho_home`.
    pub(crate) fn directory(&self, rho_home: &Path) -> PathBuf {
        rho_home.join(&self.0)
    }
}

impl TryFrom<PathBuf> for RunArtifacts {
    type Error = anyhow::Error;

    fn try_from(path: PathBuf) -> anyhow::Result<Self> {
        let plain = path
            .components()
            .all(|component| matches!(component, Component::Normal(_)));
        anyhow::ensure!(
            plain && path.components().next().is_some(),
            "{} is not a path under the rho home",
            path.display()
        );
        Ok(Self(path))
    }
}

impl From<RunArtifacts> for PathBuf {
    fn from(artifacts: RunArtifacts) -> Self {
        artifacts.0
    }
}

impl Session {
    /// Creates the file of session `id` in `cwd`'s workspace, which came
    /// from `provenance` as agent `agent` (its id and fingerprint) and runs
    /// on `engine`.
    pub(crate) fn create_on_engine(
        cwd: &Path,
        id: &str,
        agent: (&str, &str),
        provenance: SessionProvenance,
        engine: &SessionEngine,
    ) -> anyhow::Result<Self> {
        Self::create_on_engine_in_root(&session_root()?, cwd, id, agent, provenance, engine)
    }

    fn create_on_engine_in_root(
        session_root: &Path,
        cwd: &Path,
        id: &str,
        agent: (&str, &str),
        provenance: SessionProvenance,
        engine: &SessionEngine,
    ) -> anyhow::Result<Self> {
        let created_at = unix_timestamp_secs();
        let path = SessionStore::new(session_root, cwd).create_path(id, created_at)?;
        let session = Self::from_parts(session_root, cwd, id.to_owned(), path)?;
        session.append_session_metadata(
            id.to_owned(),
            created_at,
            Some(agent),
            provenance,
            Some(engine),
        )?;
        Ok(session)
    }

    /// Creates the file of session `id` in `cwd`'s workspace, which came
    /// from `provenance` and whose turns agent `agent` (its id and
    /// fingerprint), on an external runtime, runs in `permission_mode`
    /// ([`SessionEngine::AcpSession`]). Its artifacts are in the session's
    /// own folder, which its delete removes; returns their directory too.
    pub(crate) fn create_on_agent(
        cwd: &Path,
        id: &str,
        agent: (&str, &str),
        provenance: SessionProvenance,
        permission_mode: rho_protocol::PermissionMode,
    ) -> anyhow::Result<(Self, PathBuf)> {
        let rho_home = crate::paths::rho_dir()?;
        let session_root = super::layout::session_root_in(&rho_home);
        let created_at = unix_timestamp_secs();
        let path = SessionStore::new(&session_root, cwd).create_path(id, created_at)?;
        let artifacts = path.with_file_name(super::layout::SESSION_AGENT_DIR_NAME);
        let engine = SessionEngine::AcpSession {
            artifacts: RunArtifacts::of(&artifacts, &rho_home)?,
            permission_mode,
        };
        let session = Self::from_parts(&session_root, cwd, id.to_owned(), path)?;
        session.append_session_metadata(
            id.to_owned(),
            created_at,
            Some(agent),
            provenance,
            Some(&engine),
        )?;
        Ok((session, artifacts))
    }

    /// Saves `history`, the conversation of a session another engine runs
    /// on `model`, whose last rows, `shown`, it adds. `history` only ever
    /// grows, so its length orders the saves.
    pub(crate) fn save_engine_history(
        &self,
        history: &[Message],
        shown: &[Message],
        model: ModelIdentity,
    ) -> anyhow::Result<()> {
        self.save_snapshot(&self.engine_snapshot(history, model)?, shown)
    }

    /// What runs the turns of the session saved under exactly `id` in
    /// `cwd`'s workspace, read without opening it, which another process may
    /// hold: `None` for Rho's own loop; an error when nothing is saved
    /// under `id` there.
    pub(crate) fn engine_by_id(cwd: &Path, id: &str) -> anyhow::Result<Option<SessionEngine>> {
        agent_identity::read_engine(&resolve_saved(cwd, id)?.path)
    }

    /// What runs this session's turns: `None` for Rho's own loop.
    pub(crate) fn engine(&self) -> anyhow::Result<Option<SessionEngine>> {
        agent_identity::read_engine(&self.path)
    }

    /// The session that started this one through session control, by id;
    /// `None` for one a person or an agent outside any session opened.
    pub(crate) fn started_by(&self) -> anyhow::Result<Option<String>> {
        agent_identity::read_started_by(&self.path)
    }

    /// Saves `prompt` as the first message of a session another engine
    /// runs on `model`, as the run starts.
    pub(crate) fn save_engine_prompt(
        &self,
        prompt: &str,
        model: ModelIdentity,
    ) -> anyhow::Result<()> {
        let history = vec![Message::user_text(prompt)];
        self.save_snapshot(&self.engine_snapshot(&history, model)?, &history)
    }

    /// Saves the `reply` a run another engine ran on `model` gave to
    /// `prompt`, once it ended. `prompt_row` says whether
    /// [`Self::save_engine_prompt`] saved the prompt's row; when it did not,
    /// the prompt's row is saved here, before the reply's, so the session
    /// never shows a reply without its prompt.
    pub(crate) fn save_engine_reply(
        &self,
        prompt: &str,
        reply: &str,
        model: ModelIdentity,
        prompt_row: PromptRow,
    ) -> anyhow::Result<()> {
        let history = vec![Message::user_text(prompt), Message::assistant_text(reply)];
        let shown = match prompt_row {
            PromptRow::Saved => &history[1..],
            PromptRow::Unsaved => &history[..],
        };
        self.save_snapshot(&self.engine_snapshot(&history, model)?, shown)
    }

    fn engine_snapshot(
        &self,
        history: &[Message],
        model: ModelIdentity,
    ) -> anyhow::Result<SessionSnapshot> {
        Ok(SessionSnapshot::new(
            SessionId::from_string(self.id.clone())?,
            // Each save must advance the revision, or the file does not
            // reopen: each saves one more message, so its count does.
            Revision::from_u64(history.len() as u64),
            history.to_vec(),
            model,
            CompactionState::default(),
        ))
    }
}

/// Whether an engine session's prompt row was saved as its run started.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum PromptRow {
    Saved,
    Unsaved,
}

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