rho-coding-agent 3.12.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
//! The session tree as `/tree` lists it.

use std::collections::HashSet;

use super::{
    DisplayRowOrigin, MessageKey, NodeId, RestoredNode, SessionNodeKind, SessionTree,
    StoredCompactionFacts, StoredDisplayMessage, TurnEnd,
};

/// What a [`SessionTreeItem`] row is.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) enum SessionTreeItemContent {
    /// An empty durable root before any conversation turn.
    SessionStart,
    Turn {
        /// `None` for a turn saved without a user message.
        prompt: Option<RowPrompt>,
        /// How the turn ended: the latest end its nodes record, a node
        /// after a compaction it made part way included.
        end: Option<TurnEnd>,
    },
    Compaction(StoredCompactionFacts),
}

/// The prompt a turn row starts with: the first user message its first
/// node shows.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct RowPrompt {
    /// Where it was saved, which with `key` names the message a replay
    /// shows it as.
    pub(crate) origin: DisplayRowOrigin,
    pub(crate) key: Option<MessageKey>,
    /// Its text; `None` for a prompt with none, such as an image alone.
    pub(crate) text: Option<String>,
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct SessionTreeItem {
    /// The last node of the row's run (see [`SessionTree::turn_items`]).
    pub(crate) id: NodeId,
    /// The row before it: the one whose last node its first node follows.
    pub(crate) parent: Option<NodeId>,
    /// The row's nodes, first to last.
    pub(crate) run: Vec<NodeId>,
    pub(crate) depth: usize,
    pub(crate) content: SessionTreeItemContent,
    /// When the row's last node was saved, in unix milliseconds, to the
    /// second.
    pub(crate) saved_at: Option<u64>,
    pub(crate) active: bool,
    pub(crate) on_active_path: bool,
    pub(crate) ancestor_has_next_sibling: Vec<bool>,
    pub(crate) is_last_sibling: bool,
}

impl SessionTree {
    /// The node after `node`, when exactly one follows it.
    fn only_child(&self, node: &RestoredNode) -> Option<&RestoredNode> {
        match self.children.get(node.id()).map(Vec::as_slice) {
            Some([only]) => self.node(only),
            _ => None,
        }
    }

    /// The node after `node` that carries its turn on: the one child that
    /// shows no prompt, whatever prompts branch beside it.
    fn turn_child(&self, node: &RestoredNode) -> Option<&RestoredNode> {
        let mut carried = self
            .children
            .get(node.id())
            .into_iter()
            .flatten()
            .filter_map(|child| self.node(child))
            .filter(|child| Self::first_prompt(child).is_none());
        match (carried.next(), carried.next()) {
            (Some(only), None) => Some(only),
            _ => None,
        }
    }

    /// The first user message `node` shows, any prompt, an image alone
    /// included, with its row.
    fn first_prompt(node: &RestoredNode) -> Option<(usize, &StoredDisplayMessage)> {
        node.display_messages()
            .iter()
            .enumerate()
            .find(|(_, stored)| {
                matches!(
                    stored.message.semantic(),
                    rho_sdk::model::SemanticMessage::User(_)
                )
            })
    }

    /// Whether `node` carries on the turn of the node before it: a commit
    /// that shows no user message.
    fn continues_turn(node: &RestoredNode) -> bool {
        node.kind() == SessionNodeKind::Commit && Self::first_prompt(node).is_none()
    }

    /// The prompt of the turn `node` belongs to: the text of the first
    /// user message at `node` or before it, whatever the turn saved after
    /// its prompt. `None` for a prompt with no text, such as an image
    /// alone, rather than an earlier turn's.
    pub(crate) fn turn_prompt(&self, node: &NodeId) -> Option<String> {
        let mut at = self.node(node);
        while let Some(node) = at {
            if let Some((_, prompt)) = Self::first_prompt(node) {
                return super::super::persistence::user_message_text(&prompt.message);
            }
            at = node.parent_id().and_then(|parent| self.node(parent));
        }
        None
    }

    /// The first node a turn saved, which began at `before` and ended at
    /// `last`: the node after `before` on the way to `last`. `None` when
    /// `before` does not lead to `last`.
    pub(crate) fn turn_start(&self, before: &NodeId, last: &NodeId) -> Option<&NodeId> {
        let mut at = self.node(last)?;
        loop {
            let parent = at.parent_id()?;
            if parent == before {
                return Some(at.id());
            }
            at = self.node(parent)?;
        }
    }

    /// The facts of compaction `node` read from its state and its
    /// parent's, for a node saved before compactions recorded their own.
    fn derived_compaction_facts(&self, node: &RestoredNode) -> StoredCompactionFacts {
        let compaction = &node.facts().compaction;
        StoredCompactionFacts {
            previous_messages: node
                .parent_id()
                .and_then(|id| self.node(id))
                .map_or(0, |parent| parent.facts().model_len),
            current_messages: node.facts().model_len,
            previous_tokens: compaction.last_previous_tokens().unwrap_or_default(),
            current_tokens: compaction.last_current_tokens().unwrap_or_default(),
            cost_usd_micros: None,
        }
    }

    /// The tree as `/tree` lists it: one row for each prompt and all that
    /// followed it. A node that adds no user message joins the row of the
    /// node before it when nothing branches between them, and the row
    /// names the last node of its run, the conversation once the turn
    /// ended, since some hosts save a turn as several nodes, one for each
    /// step.
    pub(crate) fn turn_items(&self) -> anyhow::Result<Vec<SessionTreeItem>> {
        let active_path: HashSet<_> = self
            .active_path()?
            .into_iter()
            .map(|node| node.id().clone())
            .collect();
        let mut traversal = Vec::new();
        let roots = self
            .order
            .iter()
            .filter(|id| self.node(id).is_some_and(|node| node.parent_id().is_none()))
            .cloned()
            .collect::<Vec<_>>();
        let mut stack = roots
            .iter()
            .enumerate()
            .rev()
            .map(|(index, id)| Pending {
                id: id.clone(),
                parent: None,
                depth: 0,
                ancestor_has_next_sibling: Vec::new(),
                is_last_sibling: index + 1 == roots.len(),
            })
            .collect::<Vec<_>>();
        while let Some(Pending {
            id,
            parent,
            depth,
            ancestor_has_next_sibling,
            is_last_sibling,
        }) = stack.pop()
        {
            let node = self
                .node(&id)
                .ok_or_else(|| anyhow::anyhow!("session tree is missing node '{id}'"))?;
            // The row's run, and whether it holds the active leaf.
            let mut run = vec![node];
            let mut last = node;
            while let Some(next) = self
                .only_child(last)
                .filter(|next| Self::continues_turn(next))
            {
                run.push(next);
                last = next;
            }
            let content = match node.kind() {
                // Classify from durable state, not missing user text: a root
                // that shows nothing is the session start.
                SessionNodeKind::Commit
                    if node.parent_id().is_none()
                        // Whatever the model holds: a host that saves the
                        // session before its first prompt saves the system
                        // prompt with it.
                        && node.display_messages().is_empty() =>
                {
                    SessionTreeItemContent::SessionStart
                }
                SessionNodeKind::Commit => SessionTreeItemContent::Turn {
                    prompt: Self::first_prompt(node).map(|(row, stored)| RowPrompt {
                        origin: DisplayRowOrigin {
                            node: node.id().clone(),
                            row,
                        },
                        key: stored.key.clone(),
                        text: super::super::persistence::user_message_text(&stored.message),
                    }),
                    // A turn that compacts part way saves its later steps
                    // after the compaction's node, on its row, which a
                    // prompt that branched from the row may sit beside.
                    end: run
                        .iter()
                        .copied()
                        .chain(std::iter::successors(self.turn_child(last), |at| {
                            self.turn_child(at)
                        }))
                        .filter_map(RestoredNode::turn_end)
                        .last(),
                },
                SessionNodeKind::Compaction => SessionTreeItemContent::Compaction(
                    node.compaction_facts()
                        .cloned()
                        .unwrap_or_else(|| self.derived_compaction_facts(node)),
                ),
            };
            let id = last.id().clone();
            traversal.push(SessionTreeItem {
                id: id.clone(),
                parent,
                run: run.iter().map(|node| node.id().clone()).collect(),
                depth,
                content,
                saved_at: super::super::layout::parse_timestamp(last.timestamp())
                    .map(|secs| secs.saturating_mul(1000)),
                active: run
                    .iter()
                    .any(|node| self.active_leaf_id() == Some(node.id())),
                on_active_path: active_path.contains(node.id()),
                ancestor_has_next_sibling: ancestor_has_next_sibling.clone(),
                is_last_sibling,
            });
            let children = self.children.get(&id).map_or(&[][..], Vec::as_slice);
            for (index, child_id) in children.iter().enumerate().rev() {
                let mut child_ancestors = ancestor_has_next_sibling.clone();
                if depth > 0 {
                    child_ancestors.push(!is_last_sibling);
                }
                stack.push(Pending {
                    id: child_id.clone(),
                    parent: Some(id.clone()),
                    depth: depth + 1,
                    ancestor_has_next_sibling: child_ancestors,
                    is_last_sibling: index + 1 == children.len(),
                });
            }
        }
        Ok(traversal)
    }
}

/// A row [`SessionTree::turn_items`] has yet to visit, from its first node.
struct Pending {
    id: NodeId,
    parent: Option<NodeId>,
    depth: usize,
    ancestor_has_next_sibling: Vec<bool>,
    is_last_sibling: bool,
}