rho-coding-agent 3.11.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
//! Large tool output a client's events leave out, for it to fetch by ref
//! ([`rho_protocol::ToolOutputDeferral`], `rho/session/tool_output`).
//!
//! A finished call's `text`, `image` and `diff` items of at least the
//! client's size go out as a [`ToolContent::Deferred`] naming the item by a
//! ref: a hash of the item's JSON. The same item has the same ref live and
//! in every replay, after a reload or a restart, so a ref a client keeps
//! finds its item wherever the session still shows it, and never another
//! item.

use std::collections::{HashMap, HashSet};

use rho_protocol::{
    DeferredItem, DeferredKind, SessionEvent, ToolCallUpdate, ToolContent, ToolOutputDeferral,
    ToolOutputRef, ToolStatus,
};
use sha2::{Digest, Sha256};

use super::encoded_len;

/// What every ref starts with, so a later scheme's refs tell apart.
const REF_SCHEME: &str = "t1.";

/// How many bytes of an item's SHA-256 its ref keeps: 128 bits, so two
/// items of the 2^32 a daemon could ever hash share a ref with odds near
/// 2^-64.
const REF_HASH_BYTES: usize = 16;

/// The ref of `item`: [`REF_SCHEME`] and the hash of its JSON; `None` for
/// an item that does not encode, which no event carries.
pub(crate) fn item_ref(item: &ToolContent) -> Option<ToolOutputRef> {
    let json = serde_json::to_vec(item).ok()?;
    let digest = Sha256::digest(&json);
    Some(ToolOutputRef::new(format!(
        "{REF_SCHEME}{}",
        hex::encode(&digest[..REF_HASH_BYTES])
    )))
}

/// Whether `item` is shaped as [`item_ref`] makes refs, so it may name an
/// item: a ref that is not names none, and is gone without a search.
fn well_formed(item: &ToolOutputRef) -> bool {
    item.as_str().strip_prefix(REF_SCHEME).is_some_and(|hash| {
        hash.len() == 2 * REF_HASH_BYTES
            && hash
                .bytes()
                .all(|byte| matches!(byte, b'0'..=b'9' | b'a'..=b'f'))
    })
}

/// What a deferred `item` stands for, if a deferral may leave it out.
fn deferrable_kind(item: &ToolContent) -> Option<DeferredKind> {
    match item {
        ToolContent::Text { .. } => Some(DeferredKind::Text),
        ToolContent::Image { .. } => Some(DeferredKind::Image),
        ToolContent::Diff { .. } => Some(DeferredKind::Diff),
        // Refs a client needs to draw the call, and items a newer protocol
        // adds.
        _ => None,
    }
}

/// A finished call's `event`, which a deferral may thin.
fn finished_call(event: &SessionEvent) -> Option<&ToolCallUpdate> {
    let SessionEvent::ToolCall(update) = event else {
        return None;
    };
    matches!(
        update.status,
        Some(ToolStatus::Completed | ToolStatus::Failed | ToolStatus::Cancelled)
    )
    .then_some(update)
}

/// One item of an event that a deferral may leave out: how many bytes it
/// takes as JSON, and how many fewer its placeholder does.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct Deferrable {
    pub(crate) bytes: u32,
    pub(crate) saved: u32,
}

impl Deferrable {
    /// Whether `deferral` leaves this item out.
    pub(crate) fn deferred_by(self, deferral: ToolOutputDeferral) -> bool {
        u64::from(self.bytes) >= deferral.min_bytes
    }
}

/// The items of `event` a deferral may leave out, each with its place in
/// the call's content and kind: a finished call's `text`, `image` and
/// `diff` items larger than their placeholder.
fn candidates(
    event: &SessionEvent,
) -> impl Iterator<Item = (usize, &ToolContent, DeferredKind, Deferrable)> {
    let content = finished_call(event).and_then(|update| update.content.as_deref());
    content
        .unwrap_or_default()
        .iter()
        .enumerate()
        .filter_map(|(place, item)| {
            let kind = deferrable_kind(item)?;
            let bytes = encoded_len(item)?;
            // A placeholder's ref is as long as any.
            let sample =
                ToolOutputRef::new(format!("{REF_SCHEME}{}", "0".repeat(2 * REF_HASH_BYTES)));
            let placeholder = encoded_len(&placeholder(kind, bytes, sample))?;
            // Far below 4 GiB: an event holds it.
            let bytes = u32::try_from(bytes).unwrap_or(u32::MAX);
            let saved = bytes.saturating_sub(u32::try_from(placeholder).unwrap_or(u32::MAX));
            (saved > 0).then_some((place, item, kind, Deferrable { bytes, saved }))
        })
}

fn placeholder(kind: DeferredKind, bytes: usize, item: ToolOutputRef) -> ToolContent {
    // Far below `u64::MAX`.
    let bytes = u64::try_from(bytes).unwrap_or(u64::MAX);
    ToolContent::Deferred(DeferredItem::new(kind, bytes, item))
}

/// `event` with the items `deferral` leaves out in their places, or `None`
/// when it leaves none out.
pub(crate) fn defer(event: &SessionEvent, deferral: ToolOutputDeferral) -> Option<SessionEvent> {
    Deferrables::of(event).thin(event, deferral)
}

/// The items of an event a deferral may leave out, each with its ref,
/// worked out once for every client that defers, and for each search of
/// the buffer that holds the event.
#[derive(Clone, Debug, Default)]
pub(crate) struct Deferrables(Vec<Placeholder>);

/// One item [`Deferrables`] holds: its place in the call's content, its
/// kind, its size, and its ref.
#[derive(Clone, Debug)]
struct Placeholder {
    place: usize,
    kind: DeferredKind,
    size: Deferrable,
    item: ToolOutputRef,
}

impl Deferrables {
    /// The items of `event` a deferral may leave out; none for any event
    /// but a finished call's.
    pub(crate) fn of(event: &SessionEvent) -> Self {
        Self(
            candidates(event)
                .filter_map(|(place, item, kind, size)| {
                    Some(Placeholder {
                        place,
                        kind,
                        size,
                        item: item_ref(item)?,
                    })
                })
                .collect(),
        )
    }

    /// `event`, which these are of, with the items `deferral` leaves out
    /// in their places, or `None` when it leaves none out.
    pub(crate) fn thin(
        &self,
        event: &SessionEvent,
        deferral: ToolOutputDeferral,
    ) -> Option<SessionEvent> {
        let update = finished_call(event)?;
        let mut content = update.content.clone()?;
        let mut deferred = false;
        for placeholder in self.0.iter().filter(|item| item.size.deferred_by(deferral)) {
            if let Some(item) = content.get_mut(placeholder.place) {
                *item = self::placeholder(
                    placeholder.kind,
                    placeholder.size.bytes as usize,
                    placeholder.item.clone(),
                );
                deferred = true;
            }
        }
        deferred.then(|| {
            SessionEvent::tool_call(ToolCallUpdate {
                content: Some(content),
                ..update.clone()
            })
        })
    }
}

/// The sizes of the items a deferral may leave out of a replay's events,
/// by each event's index among them, ascending: what a window counting the
/// replay as sent takes off.
#[derive(Debug, Default)]
pub(crate) struct DeferrableIndex(Vec<(usize, Deferrable)>);

impl DeferrableIndex {
    /// Records the items event `index`, `event`, may leave out; `index`
    /// is past every index recorded before.
    pub(crate) fn record(&mut self, index: usize, event: &SessionEvent) {
        self.0
            .extend(candidates(event).map(|(_, _, _, size)| (index, size)));
    }

    /// Takes `other`'s items, whose events follow these from `offset` on.
    pub(crate) fn append(&mut self, offset: usize, other: Self) {
        self.0.extend(
            other
                .0
                .into_iter()
                .map(|(index, size)| (offset + index, size)),
        );
    }

    /// What `deferral`, if any, leaves out of the events, to count spans
    /// of them by.
    pub(crate) fn left_out(&self, deferral: Option<ToolOutputDeferral>) -> LeftOut {
        let Some(deferral) = deferral else {
            return LeftOut::default();
        };
        let mut total = 0;
        LeftOut(
            self.0
                .iter()
                .filter(|(_, size)| size.deferred_by(deferral))
                .map(|(index, size)| {
                    total += u64::from(size.saved);
                    (*index, total)
                })
                .collect(),
        )
    }
}

/// How many bytes a deferral leaves out of a replay's events through each
/// event that has an item it leaves out, ascending: so a span's count is
/// two searches, however many spans a window tries.
#[derive(Debug, Default)]
pub(crate) struct LeftOut(Vec<(usize, u64)>);

impl LeftOut {
    /// The bytes left out of the events from the `from`th to before the
    /// `to`th.
    pub(crate) fn between(&self, from: usize, to: usize) -> u64 {
        let before = |end: usize| {
            let items = self.0.partition_point(|(index, _)| *index < end);
            items.checked_sub(1).map_or(0, |last| self.0[last].1)
        };
        before(to) - before(from)
    }
}

/// The deferred items a `rho/session/tool_output` call asks for, as it
/// finds them: each ref in the order asked, and each well-formed one's
/// item once found. A ref [`item_ref`] could not have made is never
/// searched for, so a call naming many costs no search.
#[derive(Debug, Default)]
pub(crate) struct Wanted {
    asked: Vec<ToolOutputRef>,
    found: HashMap<ToolOutputRef, Option<ToolContent>>,
    missing: usize,
}

impl Wanted {
    /// Wants each of `asked`, in order, a ref asked twice answered twice.
    pub(crate) fn new(asked: Vec<ToolOutputRef>) -> Self {
        let found: HashMap<_, _> = asked
            .iter()
            .filter(|item| well_formed(item))
            .map(|item| (item.clone(), None))
            .collect();
        let missing = found.len();
        Self {
            asked,
            found,
            missing,
        }
    }

    /// Whether every ref that could name an item is found.
    pub(crate) fn complete(&self) -> bool {
        self.missing == 0
    }

    /// Takes the items of `event`, a finished call's, that are wanted and
    /// not found yet. Hashes each deferrable item only while one is
    /// missing.
    pub(crate) fn find_in(&mut self, event: &SessionEvent) {
        for (_, item, _, _) in candidates(event) {
            if self.complete() {
                return;
            }
            if let Some(found) = item_ref(item) {
                self.take(&found, item);
            }
        }
    }

    /// [`Self::find_in`] for `event`, whose `deferrables` say its items'
    /// refs, so nothing is hashed.
    pub(crate) fn find_listed(&mut self, event: &SessionEvent, deferrables: &Deferrables) {
        let Some(content) = finished_call(event).and_then(|update| update.content.as_deref())
        else {
            return;
        };
        for placeholder in &deferrables.0 {
            if self.complete() {
                return;
            }
            if let Some(item) = content.get(placeholder.place) {
                self.take(&placeholder.item, item);
            }
        }
    }

    fn take(&mut self, found: &ToolOutputRef, item: &ToolContent) {
        if let Some(slot @ None) = self.found.get_mut(found) {
            *slot = Some(item.clone());
            self.missing -= 1;
        }
    }

    /// The refs asked that no item was found for, each once, in the order
    /// first asked.
    pub(crate) fn gone(&self) -> Vec<ToolOutputRef> {
        let mut named = HashSet::new();
        self.asked
            .iter()
            .filter(|item| !matches!(self.found.get(*item), Some(Some(_))))
            .filter(|item| named.insert(*item))
            .cloned()
            .collect()
    }

    /// Each ref asked, in the order asked, with its item if found.
    pub(crate) fn answers(&self) -> impl Iterator<Item = (&ToolOutputRef, Option<&ToolContent>)> {
        self.asked
            .iter()
            .map(|item| (item, self.found.get(item).and_then(Option::as_ref)))
    }
}

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