rho-coding-agent 3.13.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
//! What an attach replays before a loaded session's live events: a tail
//! from the client's seq cursor while the buffer still holds it, else the
//! saved transcript after the client's saved entry for a resume, or for a
//! reset whole, or its newest entries that fit the client's window
//! ([`rho_protocol::ReplayStart`]), then the turn in progress.
//!
//! A replay of the transcript carries the stamps the protocol promises
//! ([`wire::SessionEventEnvelope::after_entry`]): each of the transcript's
//! boundaries ([`SavedTranscript::boundaries`]) goes on the event after it,
//! so the first event after the state carries the entry a resume started
//! after, or a later one that meets it, and the event after the transcript
//! carries its last entry. A replay with no event after the transcript, as
//! one with no usage, turn in progress, browser or activity to send, has
//! nothing to carry that last one: a client resuming from the entry before
//! it gets one entry more.

use rho_protocol::{self as wire, Cursor, EntryId, Replay, Seq, StreamEvent};

use super::{usage_event, FeedState, ResumeFrom, TURN_START_EVICTED};
use crate::app::session_events::{Boundary, FeedEvent, SavedTranscript};

/// The events an attach replays, oldest first, and how many there are. A
/// transcript renders as its client takes it.
pub(super) struct ReplayEvents {
    pub(super) len: usize,
    pub(super) events: Box<dyn Iterator<Item = StreamEvent> + Send + Sync>,
}

/// Where a replay starts.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(super) enum ReplayedFrom {
    /// After the client's seq cursor.
    Cursor,
    /// After the saved entry the client sent.
    Entry(EntryId),
    /// From the transcript's start, or after `earlier`, the newest saved
    /// entry a window left out.
    Reset { earlier: Option<EntryId> },
}

impl ReplayedFrom {
    /// The replay's kind.
    pub(super) fn replay(&self) -> Replay {
        match self {
            Self::Cursor | Self::Entry(_) => Replay::Tail,
            Self::Reset { .. } => Replay::Reset,
        }
    }

    /// Sets the saved entry `answer`, of this replay's kind, says its
    /// replay starts after.
    pub(super) fn answer(self, answer: &mut wire::SessionAttachAnswer) {
        match self {
            Self::Cursor => {}
            Self::Entry(entry) => answer.resumed_after = Some(entry),
            Self::Reset { earlier } => answer.earlier = earlier,
        }
    }
}

/// What an attach replays.
pub(super) struct Replayed {
    pub(super) from: ReplayedFrom,
    pub(super) events: ReplayEvents,
}

impl FeedState {
    /// What a client resuming from `resume` is sent before the live
    /// events, ending with the session's browser, once its tools ran, and
    /// its activity, once the feed reports it: the buffer after its seq
    /// cursor, else the transcript after its saved entry unless that sends
    /// more than its window's reset would, else that reset.
    pub(super) fn replay_from(&self, resume: ResumeFrom<'_>) -> Replayed {
        // The replay's buffered events are those after `buffered`; the
        // transcript's boundaries go on the replay's events from `state`.
        let (from, events, buffered, stamps) =
            if let Some(cursor) = resume.after.filter(|cursor| self.resumes(cursor)) {
                let tail = self.buffered_after(cursor.seq);
                let events = ReplayEvents {
                    len: tail.len(),
                    events: Box::new(tail.into_iter()),
                };
                (ReplayedFrom::Cursor, events, cursor.seq, Vec::new())
            } else {
                // The newest entries the window holds, at least the newest:
                // a resume that starts no earlier sends no more.
                let (window_start, earlier) = resume.window.map_or((0, None), |window| {
                    self.transcript.fitting_start(
                        self.transcript.len(),
                        window.max_bytes,
                        resume.deferral,
                    )
                });
                let resumed = resume
                    .entry
                    .and_then(|entry| Some((entry, self.transcript.start_of(entry)?)))
                    .filter(|(_, start)| *start >= window_start);
                let (from, start) = match resumed {
                    Some((entry, start)) => (ReplayedFrom::Entry(entry.clone()), start),
                    None => (ReplayedFrom::Reset { earlier }, window_start),
                };
                let (events, stamps) = self.saved_events(start);
                (from, events, self.turn_start, stamps)
            };
        // A replay whose last event is the activity event says the level
        // already; any other gets it again, under the stream's last seq.
        // The buffer's back is the stream's newest event unless that one
        // alone outgrew the buffer and was evicted (an activity event never
        // does), so the back says the level only while its seq is the last.
        // NEXT_MAJOR(rho-protocol): report a session's activity as SessionAttachResponse::activity and stop replaying a trailing synthetic SessionEvent::Activity.
        // A replay that ends with the browser says the activity after it
        // again.
        // NEXT_MAJOR(rho-protocol): report a session's browser as SessionAttachResponse::browser and stop replaying a trailing synthetic SessionEvent::Browser.
        let browser = self.browser.clone().map(|browser| {
            StreamEvent::new(
                self.last,
                wire::SessionEvent::Browser {
                    browser: Box::new(browser),
                },
            )
        });
        let said = browser.is_none()
            && self.buffer.back().is_some_and(|newest| {
                newest.event.seq == self.last
                    && newest.event.seq > buffered
                    && matches!(newest.event.event, wire::SessionEvent::Activity { .. })
            });
        let activity = self
            .activity
            .filter(|_| !said)
            .map(|state| StreamEvent::new(self.last, wire::SessionEvent::Activity { state }));
        let events = ReplayEvents {
            len: events.len + usize::from(browser.is_some()) + usize::from(activity.is_some()),
            events: Box::new(Stamped::new(
                events.events.chain(browser).chain(activity),
                stamps,
            )),
        };
        Replayed { from, events }
    }

    /// Whether `cursor` is a point of this stream the buffer resumes from:
    /// every event after it is still buffered. Seq 0 is not a point: a
    /// client holding it may have stopped partway through a transcript.
    fn resumes(&self, cursor: &Cursor) -> bool {
        let oldest = self
            .buffer
            .front()
            .map_or(Seq(self.last.0 + 1), |buffered| buffered.event.seq);
        cursor.stream == self.stream
            && cursor.seq > Seq(0)
            && cursor.seq <= self.last
            && cursor.seq.0 + 1 >= oldest.0
    }

    fn buffered_after(&self, seq: Seq) -> Vec<StreamEvent> {
        self.buffer
            .iter()
            .filter(|buffered| buffered.event.seq > seq)
            .map(|buffered| buffered.event.clone())
            .collect()
    }

    /// The agent, what the sessions this one starts open with, what runs
    /// the session and what it can do, if the feed knows, the saved
    /// transcript from its `from`th event, and the usage as of the last
    /// save, at seq 0 but the last event, which carries the point the turn
    /// in progress began after, then the turn's buffered events; and the
    /// transcript's boundaries from `from` on, counted from the replay's
    /// first event. No saved row holds the agent, that choice, or usage, so
    /// without them a client that resets would not know the agent or the
    /// choice, and would show no context or spend until the next turn. The
    /// transcript renders as the client takes it, so a replay never holds a
    /// long session's events at once.
    fn saved_events(&self, from: usize) -> (ReplayEvents, Vec<Boundary>) {
        let agent = wire::SessionEvent::Agent {
            id: self.agent.clone(),
        };
        let evicted = self.turn_start_evicted.then(|| wire::SessionEvent::Notice {
            text: TURN_START_EVICTED.to_owned(),
        });
        let started =
            wire::SessionEvent::StartedSessionDefaults(self.started_session_defaults.clone());
        let engine = self.engine.map(super::super::capabilities::engine_event);
        let usage = self.saved_usage.map(usage_event);
        let state = 2 + usize::from(engine.is_some());
        // The boundary at the transcript's end goes on the event after it.
        let stamps = shifted(&self.transcript, from..self.transcript.len() + 1, state);
        let numbered = state
            + (self.transcript.len() - from)
            + usize::from(evicted.is_some())
            + usize::from(usage.is_some());
        let turn_start = self.turn_start;
        let tail = self.buffered_after(turn_start);
        let len = numbered + tail.len();
        let events = [agent, started]
            .into_iter()
            .chain(engine)
            .map(FeedEvent::from)
            .chain(self.transcript.events_from(from))
            .chain(evicted.map(FeedEvent::from))
            .chain(usage.map(FeedEvent::from))
            .enumerate()
            .map(move |(index, event)| {
                let seq = if index + 1 == numbered {
                    turn_start
                } else {
                    Seq(0)
                };
                event.into_stream(seq)
            })
            .chain(tail);
        let events = ReplayEvents {
            len,
            events: Box::new(events),
        };
        (events, stamps)
    }
}

/// `transcript`'s boundaries at its events in `within`, moved to count
/// from a replay that sends the first of them `at` events in.
pub(super) fn shifted(
    transcript: &SavedTranscript,
    within: std::ops::Range<usize>,
    at: usize,
) -> Vec<Boundary> {
    let boundaries = transcript.boundaries();
    let first = boundaries.partition_point(|boundary| boundary.index < within.start);
    let last = boundaries.partition_point(|boundary| boundary.index < within.end);
    boundaries[first..last]
        .iter()
        .map(|boundary| Boundary {
            index: boundary.index - within.start + at,
            entry: boundary.entry.clone(),
        })
        .collect()
}

/// `events`, the first at or after each of `boundaries` stamped with the
/// newest boundary there; the rest keep their own stamps. A boundary out of
/// order lands late, which claims less, never more.
pub(super) struct Stamped<I> {
    events: I,
    /// Ascending by index.
    boundaries: std::iter::Peekable<std::vec::IntoIter<Boundary>>,
    next: usize,
}

impl<I> Stamped<I> {
    pub(super) fn new(events: I, boundaries: Vec<Boundary>) -> Self {
        Self {
            events,
            boundaries: boundaries.into_iter().peekable(),
            next: 0,
        }
    }
}

impl<I: Iterator<Item = StreamEvent>> Iterator for Stamped<I> {
    type Item = StreamEvent;

    fn next(&mut self) -> Option<StreamEvent> {
        let mut event = self.events.next()?;
        let index = self.next;
        self.next += 1;
        while let Some(boundary) = self.boundaries.next_if(|boundary| boundary.index <= index) {
            event.after_entry = Some(boundary.entry);
        }
        Some(event)
    }
}