rho-coding-agent 3.13.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
//! Where a replay's events pass each saved entry, so a client can resume
//! after one once the stream that sent it is gone
//! ([`rho_protocol::SessionEventEnvelope::after_entry`]).
//!
//! An entry is a saved display row, named by where it was saved: the same on
//! every load. A boundary sits between two of a replay's events where the
//! events before it show the rows up to and including one entry and nothing
//! of a later row. Capture records them as it renders a turn
//! ([`TurnEntries`]): after each saved row once no call open of it or an
//! earlier row is held for its result, since a held open goes out later, and
//! after the turn's last saved row at the turn's end, once the replay closed
//! what it left open. A row the load added, which was never saved, names no
//! entry: the next saved row's boundary covers it, or, when it is what
//! settles a held call, as the interrupted result a load adds for a call
//! that never got one, the boundary after it is the saved row's before it.
//!
//! A replay stamps a boundary on the event after it, the newest entry where
//! several meet. A boundary at a turn's end falls on the next turn's first
//! event, and one at the transcript's end on whatever the feed sends next.

use std::sync::Arc;

use rho_protocol::{EntryId, ToolOutputDeferral};

use super::{turn_events, FeedEvent, SavedTranscript};
use crate::app::session_events::deferred::LeftOut;
use crate::session::tree::DisplayRowOrigin;

/// The entry naming the row saved at `origin`.
pub(super) fn entry_id(DisplayRowOrigin { node, row }: &DisplayRowOrigin) -> EntryId {
    EntryId::new(format!("{node}/{row}"))
}

/// One boundary of a replay: the events before its `index`th sent event
/// show the rows through `entry`, and nothing of a later row.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct Boundary {
    pub(crate) index: usize,
    pub(crate) entry: EntryId,
}

/// The boundaries of one turn's replay, in row order, so ascending by
/// index.
#[derive(Clone, Debug, Default)]
pub(super) struct TurnEntries {
    boundaries: Vec<Boundary>,
    /// The turn's last saved row, whose boundary [`Self::end`] places.
    last: Option<EntryId>,
    /// Whether `last`'s boundary is placed.
    placed: bool,
}

impl TurnEntries {
    /// Records that a row, saved at `origin` or added by the load, was the
    /// last rendered, with `settled_at` events sent so far when nothing of
    /// it or an earlier row is held back: the last saved row's boundary
    /// then, if not placed yet.
    pub(super) fn row(&mut self, origin: Option<&DisplayRowOrigin>, settled_at: Option<usize>) {
        if let Some(origin) = origin {
            self.last = Some(entry_id(origin));
            self.placed = false;
        }
        if let (Some(index), Some(entry), false) = (settled_at, &self.last, self.placed) {
            self.boundaries.push(Boundary {
                index,
                entry: entry.clone(),
            });
            self.placed = true;
        }
    }

    /// Places the last saved row's boundary at the turn's end, `sent`
    /// events in, after what the replay closed at its finish.
    pub(super) fn end(&mut self, sent: usize) {
        let Some(last) = self.last.take() else {
            return;
        };
        self.boundaries.retain(|boundary| boundary.entry != last);
        self.boundaries.push(Boundary {
            index: sent,
            entry: last,
        });
    }

    pub(super) fn boundaries(&self) -> &[Boundary] {
        &self.boundaries
    }
}

impl SavedTranscript {
    /// Where the transcript's replay ([`Self::events_from`]) passes each
    /// saved entry, counted from its first event, ascending.
    /// One at the transcript's end, [`Self::len`], is for the event that
    /// follows them.
    pub(crate) fn boundaries(&self) -> &[Boundary] {
        &self.boundaries
    }

    /// The entry the transcript ends on: the last saved row's, which the
    /// event after the transcript carries.
    pub(crate) fn final_entry(&self) -> Option<EntryId> {
        self.boundaries
            .last()
            .filter(|boundary| boundary.index == self.sent)
            .map(|boundary| boundary.entry.clone())
    }

    /// How many of the replay's events come before saved entry `entry`'s
    /// boundary, so a resume after it starts there. `None` when no boundary
    /// names `entry`, as for a row a rewind moved off the conversation.
    pub(crate) fn start_of(&self, entry: &EntryId) -> Option<usize> {
        self.boundaries
            .iter()
            .find(|boundary| boundary.entry == *entry)
            .map(|boundary| boundary.index)
    }

    /// How many bytes the replay's events from the `from`th to before the
    /// `to`th take as JSON, event and notification, as a
    /// [`rho_protocol::ReplayWindow`] counts them: as sent with `deferral`'s
    /// items left out.
    #[cfg(test)]
    pub(crate) fn bytes(
        &self,
        from: usize,
        to: usize,
        deferral: Option<ToolOutputDeferral>,
    ) -> u64 {
        self.bytes_sent(from, to, &self.deferrable.left_out(deferral))
    }

    /// How many bytes the events from the `from`th to before the `to`th
    /// take as a window counts them, less what `left_out` says a deferral
    /// leaves out of them.
    fn bytes_sent(&self, from: usize, to: usize, left_out: &LeftOut) -> u64 {
        let through = |index: usize| index.checked_sub(1).map_or(0, |last| self.totals[last]);
        through(to) - through(from) - left_out.between(from, to)
    }

    /// Where the newest whole saved entries before the `end`th event that
    /// fit in `max_bytes` start ([`newest_fitting`]), counted as sent with
    /// `deferral`'s items left out.
    pub(crate) fn fitting_start(
        &self,
        end: usize,
        max_bytes: u64,
        deferral: Option<ToolOutputDeferral>,
    ) -> (usize, Option<EntryId>) {
        let before = self
            .boundaries
            .partition_point(|boundary| boundary.index < end);
        let left_out = self.deferrable.left_out(deferral);
        newest_fitting(&self.boundaries[..before], max_bytes, |start| {
            self.bytes_sent(start, end, &left_out)
        })
    }

    /// The wire events that replay every turn, in order, the same each
    /// time, from the `from`th on, each with when its row was saved if the
    /// session file says. They render a row at a time as the replay is
    /// taken, so a replay never holds a long session's events at once. The
    /// turns before the one `from` falls in go unrendered; that one renders
    /// from its start, its events before `from` dropped.
    pub(crate) fn events_from(
        &self,
        from: usize,
    ) -> impl Iterator<Item = FeedEvent> + Send + Sync + 'static {
        let mut offset = 0;
        let mut turns = Vec::new();
        let mut skip = 0;
        for turn in &self.turns {
            let end = offset + turn.sent;
            if end > from {
                if turns.is_empty() {
                    skip = from - offset;
                }
                turns.push(Arc::clone(turn));
            }
            offset = end;
        }
        turns.into_iter().flat_map(turn_events).skip(skip)
    }
}

/// Where the newest whole entries of some events that fit in `max_bytes`
/// start, and at least the newest one: that event's index, and the entry
/// before it, which the events from there leave out; `None` at the first
/// event. `boundaries` are those between the events, ascending, and
/// `bytes(start)` what the events from `start` on take. Where several
/// entries meet, the newest, as a replay stamps it.
pub(crate) fn newest_fitting(
    boundaries: &[Boundary],
    max_bytes: u64,
    bytes: impl Fn(usize) -> u64,
) -> (usize, Option<EntryId>) {
    let mut newest = (0, None);
    for boundary in boundaries
        .iter()
        .rev()
        .filter(|boundary| boundary.index > 0)
    {
        if boundary.index == newest.0 {
            continue;
        }
        if newest.1.is_some() && bytes(boundary.index) > max_bytes {
            return newest;
        }
        newest = (boundary.index, Some(boundary.entry.clone()));
    }
    if newest.1.is_some() && bytes(0) > max_bytes {
        return newest;
    }
    (0, None)
}