rho-coding-agent 3.11.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
//! A page of a feed's saved transcript (`rho/session/history`): the newest
//! whole saved entries through one that fit the client's byte budget, at
//! least one, counted as a [`wire::ReplayWindow`] counts them, and each event
//! stamped as a reset replays it.
//!
//! A page is one JSON-RPC message, so it also stops before an entry that
//! would take the answer past [`wire::MAX_LINE_BYTES`]. An entry too large
//! for a message alone goes out as one notice that says so, which carries the
//! stamp of the entry before it, so the client pages on past it.

use rho_protocol::{
    self as wire, EntryId, ErrorCode, HistoryEvent, RpcError, Seq, SessionHistoryResponse,
};

use super::{
    replay::{shifted, Stamped},
    Feed,
};
use crate::app::session_events::{encoded_len, newest_fitting, Boundary, FeedEvent};

/// How many bytes a page's events may take in one message.
const PAGE_LIMIT: usize = super::super::ANSWER_LIMIT;

/// A page of the transcript, taken under the feed's lock, to render after:
/// its events, the boundaries between them, and the newest entry before it.
pub(in crate::app::daemon_host::sessions) struct HistoryPage {
    events: Box<dyn Iterator<Item = FeedEvent> + Send>,
    /// The tool output the page leaves out, if the client asked and the
    /// session defers any.
    deferral: Option<wire::ToolOutputDeferral>,
    stamps: Vec<Boundary>,
    earlier: Option<EntryId>,
}

impl Feed {
    /// The page of the saved transcript that ends with saved entry
    /// `through`'s events: the newest entries that fit in `max_bytes`, and
    /// at most one message, as sent with `deferral`'s tool output left out.
    /// `ConversationMoved` when the transcript no longer holds `through`,
    /// as after a rewind.
    pub(in crate::app::daemon_host::sessions) fn history(
        &self,
        through: &EntryId,
        max_bytes: u64,
        deferral: Option<wire::ToolOutputDeferral>,
    ) -> Result<HistoryPage, RpcError> {
        let state = self.state();
        let deferral = state.deferral(deferral);
        let transcript = &state.transcript;
        let end = transcript.start_of(through).ok_or_else(|| {
            RpcError::new(
                ErrorCode::ConversationMoved,
                format!("the conversation no longer holds entry {through}"),
            )
        })?;
        // An event takes at least its counted bytes in the answer, so what
        // a message holds bounds what the page renders.
        let budget = max_bytes.min(PAGE_LIMIT as u64);
        let (start, earlier) = transcript.fitting_start(end, budget, deferral);
        // The boundary at `end` is on the event after the page.
        let stamps = shifted(transcript, start..end, 0);
        Ok(HistoryPage {
            events: Box::new(transcript.events_from(start).take(end - start)),
            deferral,
            stamps,
            earlier,
        })
    }
}

impl HistoryPage {
    /// The page's events as the answer sends them, each stamped as a reset
    /// stamps it, cut to one message.
    pub(in crate::app::daemon_host::sessions) fn render(self) -> SessionHistoryResponse {
        let cuts = self.stamps.clone();
        let deferral = self.deferral;
        let page = Stamped::new(
            self.events
                .map(move |event| super::deferred(event.into_stream(Seq(0)), deferral)),
            self.stamps,
        )
        .map(|event| {
            let mut page = HistoryEvent::new(event.event);
            page.at = event.at;
            page.notification = event.notification;
            page.after_entry = event.after_entry;
            let bytes = encoded_len(&page).unwrap_or_default();
            (page, bytes)
        })
        .collect();
        fit_message(page, &cuts, self.earlier)
    }
}

/// `page`, each event with the bytes it takes, from the first of `cuts`,
/// the boundaries between its entries, after which it fits one message,
/// and the newest entry it then leaves out; the notice an entry too large
/// alone gets in its place.
fn fit_message(
    page: Vec<(HistoryEvent, usize)>,
    cuts: &[Boundary],
    earlier: Option<EntryId>,
) -> SessionHistoryResponse {
    // What the events from each on take, with a comma between two.
    let mut from = vec![0; page.len() + 1];
    for (index, (_, bytes)) in page.iter().enumerate().rev() {
        from[index] = from[index + 1] + bytes + 1;
    }
    let taken = |start: usize| from[start] as u64;
    let (start, cut) = newest_fitting(cuts, PAGE_LIMIT as u64, taken);
    let earlier = if start == 0 { earlier } else { cut };
    if taken(start) > PAGE_LIMIT as u64 {
        let bytes = page[start..].iter().map(|(_, bytes)| bytes).sum();
        return too_large(bytes, earlier);
    }
    let events = page
        .into_iter()
        .skip(start)
        .map(|(event, _)| event)
        .collect();
    SessionHistoryResponse::new(events, earlier)
}

/// The page for an entry whose events take `bytes`, past what one message
/// holds: a notice that says so, after `earlier`, the entry before it.
fn too_large(bytes: usize, earlier: Option<EntryId>) -> SessionHistoryResponse {
    let mut notice = HistoryEvent::new(wire::SessionEvent::Notice {
        text: format!(
            "an entry of {bytes} bytes is left out: a history page holds at most \
             {PAGE_LIMIT} bytes of events"
        ),
    });
    notice.after_entry = earlier.clone();
    SessionHistoryResponse::new(vec![notice], earlier)
}

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