rho-coding-agent 3.13.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
//! Joins a replayed call's open and result into one event.
//!
//! A tool call's updates are patches: a field an update leaves out stays as
//! the client has it. So a call's open and result sent as one event leave a
//! client with the card the two left. Where it shows the card stays put too,
//! as long as nothing goes between them and call order holds: some clients
//! show a call at its first event (`rho acp`, rho-ui, `rho attach`'s title
//! line), the TUI where it closes, and `rho attach` prints a failure line
//! there too.

use std::collections::VecDeque;

use rho_protocol::{SessionEvent as WireEvent, ToolCallUpdate, ToolStatus};

use super::FeedEvent;

/// The stage a saved turn's replay goes through last, after the events
/// JSON cannot hold were dropped.
///
/// It holds each call's open, unsent, and sends it with the call's result
/// as one event, timed as the open was. Only the oldest open held goes with
/// its result, so first events keep their order; any other event goes after
/// the opens held, which go first. A failure goes with its open only when
/// no later open is held, since its failure line would pass that call's
/// title. A cancelled call and one a replay closes itself, without a card,
/// are opened, then updated: rho-ui shows `cancelled` only on a call it saw
/// running, and the TUI draws a call closed without a card as its last
/// card, interrupted.
///
/// It tells events apart by the fields [`Replay`](super::Replay) gives them:
/// an open is `in_progress` without content (one that shows a surface has
/// it), a result carries its card, and a close the replay adds has none.
/// It reads only fields capture fixes, never a result's content, which a
/// process's terminal may change when the turn replays: capture counts the
/// events a client is sent through it.
#[derive(Default)]
pub(super) struct FinishedCalls {
    /// Opens not sent yet, oldest first.
    held: VecDeque<Held>,
}

/// An open held, and when its row was saved.
struct Held {
    open: ToolCallUpdate,
    at: Option<u64>,
}

impl FinishedCalls {
    /// Takes `event`, and adds to `sent` what goes out with it.
    pub(super) fn push(&mut self, event: FeedEvent, sent: &mut VecDeque<FeedEvent>) {
        let FeedEvent {
            event: WireEvent::ToolCall(update),
            at,
            notification: None,
            after_entry: None,
            origin: None,
        } = event
        else {
            self.finish(sent);
            sent.push_back(event);
            return;
        };
        if opens(&update) {
            self.held.push_back(Held { open: *update, at });
            return;
        }
        let goes_with_open = self
            .held
            .front()
            .is_some_and(|held| held.open.id == update.id && self.finishes(&update));
        let held = if goes_with_open {
            self.held.pop_front()
        } else {
            None
        };
        if let Some(held) = held {
            sent.push_back(FeedEvent {
                at: held.at,
                ..WireEvent::tool_call(joined(held.open, *update)).into()
            });
            return;
        }
        self.finish(sent);
        sent.push_back(FeedEvent {
            at,
            ..WireEvent::ToolCall(update).into()
        });
    }

    /// Adds the opens still held to `sent`, in order.
    pub(super) fn finish(&mut self, sent: &mut VecDeque<FeedEvent>) {
        sent.extend(self.held.drain(..).map(|Held { open, at }| FeedEvent {
            at,
            ..WireEvent::tool_call(open).into()
        }));
    }

    /// Whether no open waits for its result, so every event taken so far
    /// was sent.
    pub(super) fn is_settled(&self) -> bool {
        self.held.is_empty()
    }

    /// Whether `result` finishes the oldest call held in one event.
    fn finishes(&self, result: &ToolCallUpdate) -> bool {
        let finished = match result.status {
            Some(ToolStatus::Completed) => true,
            Some(ToolStatus::Failed) => self.held.len() == 1,
            // rho-ui shows `cancelled` only on a call it saw running.
            Some(ToolStatus::Cancelled) => false,
            Some(ToolStatus::Pending | ToolStatus::InProgress) | None => false,
            // Daemons never send it; were one replayed, how a client shows
            // it is the client's call, so the call goes as it went.
            Some(ToolStatus::Unknown) => false,
            // `ToolStatus` is `#[non_exhaustive]`, so the compiler needs this
            // arm; a variant added to it later lands here until a case is
            // written for it above.
            Some(_) => false,
        };
        finished && result.display.is_some()
    }
}

/// A saved turn's events, those no client can be sent dropped, as
/// [`FinishedCalls`] sends them.
pub(super) struct JoinedEvents<I> {
    events: I,
    finished_calls: FinishedCalls,
    ready: VecDeque<FeedEvent>,
    /// How many events capture counted a client is sent, and how many were.
    expected: usize,
    sent: usize,
}

impl<I> JoinedEvents<I> {
    /// `events`, of which capture counted `expected` would be sent.
    pub(super) fn new(events: I, expected: usize) -> Self {
        Self {
            events,
            finished_calls: FinishedCalls::default(),
            ready: VecDeque::new(),
            expected,
            sent: 0,
        }
    }
}

impl<I: Iterator<Item = FeedEvent>> Iterator for JoinedEvents<I> {
    type Item = FeedEvent;

    fn next(&mut self) -> Option<FeedEvent> {
        loop {
            if let Some(event) = self.ready.pop_front() {
                self.sent += 1;
                return Some(event);
            }
            match self.events.next() {
                Some(event) => self.finished_calls.push(event, &mut self.ready),
                None if !self.finished_calls.held.is_empty() => {
                    self.finished_calls.finish(&mut self.ready);
                }
                None => {
                    debug_assert_eq!(self.sent, self.expected);
                    return None;
                }
            }
        }
    }
}

/// Whether `update` opens a call that may wait for its result: one with no
/// content yet. One that shows its surface already has content, which a
/// client places at the call's first event.
fn opens(update: &ToolCallUpdate) -> bool {
    update.status == Some(ToolStatus::InProgress) && update.content.is_none()
}

/// `open` and `result` as one update: every field the result sets, else the
/// open's.
fn joined(open: ToolCallUpdate, result: ToolCallUpdate) -> ToolCallUpdate {
    let ToolCallUpdate {
        id,
        title,
        kind,
        status,
        raw_input,
        content,
        locations,
        display,
    } = result;
    ToolCallUpdate {
        id,
        title: title.or(open.title),
        kind: kind.or(open.kind),
        status: status.or(open.status),
        raw_input: raw_input.or(open.raw_input),
        content: content.or(open.content),
        locations: locations.or(open.locations),
        display: display.or(open.display),
    }
}