rho-coding-agent 3.9.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
//! A loaded session's conversation tree (`rho/session/tree`) and what
//! rewinding one of its workspace checkpoints would do
//! (`rho/session/rewind/preview`), so a client can offer
//! [`rho_protocol::SessionChange::SelectNode`] and
//! [`rho_protocol::SESSION_REWIND`] without reading the
//! session's files. Both read between the session's turns and change
//! nothing.

use rho_protocol::{
    self as wire, ErrorCode, RpcError, SessionRewindPreviewParams, SessionRewindPreviewResponse,
    SessionTreeParams, SessionTreeResponse, TreeNodeId,
};

use super::Sessions;
use crate::{
    app::{
        session_events::row_user_message_id,
        session_runtime::{
            RewindError, RewindPreview, RewoundConversation, TreeRow, WorkspaceRewind,
        },
    },
    session::{
        tree::{NodeId, RowPrompt, SessionTreeItemContent, TurnEnd},
        workspace_checkpoint::{
            AuditResult, CheckpointFileBudgetExceeded, RestoreClassification, RestorePlanEntry,
            UntrackedEffect, UntrackedEffectKind, WorkspaceCheckpointSummary,
        },
    },
};

// Sizing receipt: prompts saved on one machine ran p50 2,186 and p99 16,018
// characters, and its largest tree 879 rows: whole prompts would make its
// tree ~7 MB of the protocol's 16 MiB line. 200 characters, a row's worth
// in a picker, keep it near 0.3 MB.
/// How much of a prompt a tree row carries.
const PROMPT_CHARS: usize = 200;

impl Sessions {
    pub(in crate::app::daemon_host) async fn tree(
        &self,
        params: SessionTreeParams,
    ) -> Result<SessionTreeResponse, RpcError> {
        let session = self.between_turns(&params.session).await?;
        let runtime = session.runtime.lock().await;
        let runtime = runtime.as_ref().ok_or_else(super::inspect::not_loaded)?;
        let rows = runtime.tree_rows().map_err(|error| {
            RpcError::new(
                ErrorCode::InternalError,
                format!("could not read the session's tree: {error:#}"),
            )
        })?;
        let current = rows
            .iter()
            .find(|row| row.item.active)
            .map(|row| node_to_wire(&row.item.id));
        Ok(SessionTreeResponse::new(
            rows.into_iter().map(row_to_wire).collect(),
            current,
        ))
    }

    pub(in crate::app::daemon_host) async fn rewind_preview(
        &self,
        params: SessionRewindPreviewParams,
    ) -> Result<SessionRewindPreviewResponse, RpcError> {
        let target = node_from_wire(&params.checkpoint)?;
        let session = self.between_turns(&params.session).await?;
        let runtime = session.runtime.lock().await;
        let runtime = runtime.as_ref().ok_or_else(super::inspect::not_loaded)?;
        let RewindPreview {
            tip,
            turns,
            plan,
            returns_to,
        } = runtime
            .preview_rewind(&target)
            .map_err(|error| rewind_error(error, "plan the workspace rewind"))?;
        Ok(SessionRewindPreviewResponse::new(
            turns.iter().map(node_to_wire).collect(),
            node_to_wire(&tip),
            u32::try_from(plan.uncaptured_turns).unwrap_or(u32::MAX),
            plan.entries.into_iter().map(file_to_wire).collect(),
            plan.limitations.iter().map(untracked_to_wire).collect(),
            match returns_to {
                Some(row) => wire::RewindConversation::Moves {
                    to: node_to_wire(&row),
                },
                None => wire::RewindConversation::Stays,
            },
        ))
    }
}

/// The wire error for a rewind, or its preview, that changed nothing:
/// `doing` names what failed, as "rewind the workspace".
pub(super) fn rewind_error(error: RewindError, doing: &str) -> RpcError {
    match error {
        RewindError::Refused(error) => {
            RpcError::new(ErrorCode::InvalidParams, format!("{error:#}"))
        }
        RewindError::Failed(error) => RpcError::new(
            ErrorCode::InternalError,
            format!("could not {doing}: {error:#}"),
        ),
        moved @ RewindError::Moved { .. } => {
            RpcError::new(ErrorCode::ConversationMoved, moved.to_string())
        }
    }
}

/// What a rewind did, as `rho/session/rewind` answers it.
pub(super) fn rewind_to_wire(rewind: WorkspaceRewind) -> wire::SessionRewindResponse {
    let WorkspaceRewind {
        turns,
        audit,
        conversation,
    } = rewind;
    let files = audit
        .entries
        .into_iter()
        .map(|entry| {
            let result = match entry.result() {
                AuditResult::Written => wire::RewoundFileResult::Written,
                AuditResult::Left => wire::RewoundFileResult::Left,
                AuditResult::Failed(error) => wire::RewoundFileResult::Failed {
                    error: error.to_owned(),
                },
            };
            wire::RewoundFile::new(entry.path, action_to_wire(entry.classification), result)
        })
        .collect();
    let conversation = match conversation {
        RewoundConversation::Moved { row } => wire::RewoundConversation::Moved {
            to: node_to_wire(&row),
        },
        RewoundConversation::Stayed => wire::RewoundConversation::Stayed,
        RewoundConversation::MoveFailed(error) => wire::RewoundConversation::MoveFailed {
            error: error.to_string(),
        },
    };
    wire::SessionRewindResponse::new(
        turns.iter().map(node_to_wire).collect(),
        files,
        audit.limitations.iter().map(untracked_to_wire).collect(),
        u32::try_from(audit.uncaptured_turns).unwrap_or(u32::MAX),
        conversation,
    )
}

/// The node a client names, or `InvalidParams` for an id no node can have.
pub(super) fn node_from_wire(id: &TreeNodeId) -> Result<NodeId, RpcError> {
    NodeId::from_string(id.as_str())
        .map_err(|error| RpcError::new(ErrorCode::InvalidParams, format!("{error:#}")))
}

fn node_to_wire(node: &NodeId) -> TreeNodeId {
    TreeNodeId::new(node.as_str())
}

fn row_to_wire(TreeRow { item, checkpoints }: TreeRow) -> wire::SessionTreeRow {
    let content = match &item.content {
        SessionTreeItemContent::SessionStart => wire::TreeRowContent::SessionStart,
        SessionTreeItemContent::Turn { prompt, end } => {
            wire::TreeRowContent::Turn(wire::TreeTurn::new(
                prompt.as_ref().map(prompt_to_wire),
                end.map(turn_end_to_wire),
            ))
        }
        SessionTreeItemContent::Compaction(facts) => {
            wire::TreeRowContent::Compaction(facts.counts())
        }
    };
    wire::SessionTreeRow::new(
        node_to_wire(&item.id),
        item.parent.as_ref().map(node_to_wire),
        item.saved_at,
        content,
        checkpoints.iter().map(checkpoint_to_wire).collect(),
    )
}

/// The prompt as a replay shows it, cut to [`PROMPT_CHARS`].
fn prompt_to_wire(prompt: &RowPrompt) -> wire::TreePrompt {
    let text = prompt.text.as_deref().unwrap_or_default();
    let text = match text.char_indices().nth(PROMPT_CHARS) {
        Some((cut, _)) => format!("{}…", &text[..cut]),
        None => text.to_owned(),
    };
    wire::TreePrompt::new(
        row_user_message_id(&prompt.origin, prompt.key.as_ref()),
        text,
    )
}

fn turn_end_to_wire(end: TurnEnd) -> wire::TreeTurnEnd {
    match end {
        TurnEnd::Completed => wire::TreeTurnEnd::Completed,
        TurnEnd::Cancelled => wire::TreeTurnEnd::Cancelled,
        TurnEnd::Failed => wire::TreeTurnEnd::Failed,
        TurnEnd::Unknown => wire::TreeTurnEnd::Unknown,
    }
}

fn checkpoint_to_wire(checkpoint: &WorkspaceCheckpointSummary) -> wire::TurnCheckpoint {
    wire::TurnCheckpoint::new(
        node_to_wire(&checkpoint.node_id),
        u32::try_from(checkpoint.file_count).unwrap_or(u32::MAX),
        checkpoint
            .limitations
            .iter()
            .map(untracked_to_wire)
            .collect(),
    )
}

fn untracked_to_wire(effect: &UntrackedEffect) -> wire::UntrackedEffect {
    let kind = match effect.kind {
        UntrackedEffectKind::ShellCommand => wire::UntrackedEffectKind::Shell,
        UntrackedEffectKind::UntrackedMutatingTool | UntrackedEffectKind::ExternalEffect => {
            wire::UntrackedEffectKind::Tool
        }
    };
    wire::UntrackedEffect::new(kind, effect.source.clone())
}

fn file_to_wire(entry: RestorePlanEntry) -> wire::RewindFile {
    wire::RewindFile::new(
        entry.path,
        action_to_wire(entry.classification),
        entry
            .over_budget
            .map(|CheckpointFileBudgetExceeded { asked, limit }| {
                wire::CaptureBudget::new(asked, limit)
            }),
    )
}

fn action_to_wire(classification: RestoreClassification) -> wire::RewindAction {
    match classification {
        RestoreClassification::Modify => wire::RewindAction::Restore,
        RestoreClassification::Create => wire::RewindAction::Recreate,
        RestoreClassification::Delete => wire::RewindAction::Delete,
        RestoreClassification::Conflict => wire::RewindAction::Conflict,
        RestoreClassification::Unsupported => wire::RewindAction::Unsupported,
        RestoreClassification::Skipped => wire::RewindAction::Unchanged,
    }
}

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