rho-coding-agent 3.11.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
//! Reading the tool output a client's events left out
//! (`rho/session/tool_output`), by the refs they carried.
//!
//! A ref is the hash of its item (`session_events::deferred`), so the
//! daemon finds it wherever the session still shows the item: a loaded
//! session's buffered live events, then its saved transcript, newest turn
//! first; a run's stream for a session a subagent run under way writes;
//! else the session's file, read as history reads it, without loading it.
//! A ref the session no longer holds renders every turn before the call
//! fails: on a session whose whole replay is 11.9 MB, measured end to end
//! on the daemon's socket, about 18 ms loaded and 75 ms unloaded, against
//! 20 ms and 80 to 97 ms for one it holds.

use rho_protocol::{
    self as wire, ErrorCode, RpcError, SessionToolOutputParams, SessionToolOutputResponse,
    ToolOutputItem,
};

use super::{locate::Located, reopen::parse_session, unloaded::Unloaded, Sessions, ANSWER_LIMIT};
use crate::app::session_events::{encoded_len, NewestTurns, Wanted};

impl Sessions {
    /// The items `params.items` names, as the events that deferred them
    /// would have carried them, in the order asked and as many as fit in
    /// one message.
    pub(in crate::app::daemon_host) async fn tool_output(
        &self,
        params: SessionToolOutputParams,
    ) -> Result<SessionToolOutputResponse, RpcError> {
        self.refuse_when_stopping()?;
        if params.items.is_empty() {
            return Err(RpcError::new(
                ErrorCode::InvalidParams,
                "name at least one item to read",
            ));
        }
        let id = parse_session(&params.session)?;
        let mut wanted = Wanted::new(params.items);
        let turns = match self.locate(&id).await {
            Located::Loaded(session) => session.feed.find_tool_output(&mut wanted),
            Located::Unloaded { run, reopening } => {
                // A subagent run under way writes it: its stream's buffered
                // events hold what the run showed lately. What they no
                // longer hold, the session's file may, which a run still
                // writing it refuses to have read, as `SessionBusy`: a
                // client asks again once it ends.
                if let Some(run) = run {
                    run.find_tool_output(&mut wanted);
                }
                if wanted.complete() {
                    None
                } else {
                    match self.read_unloaded(&reopening).await? {
                        // An agent runtime's session defers nothing.
                        Unloaded::Engine { .. } => None,
                        Unloaded::Saved { feed, .. } => feed.find_tool_output(&mut wanted),
                    }
                }
            }
        };
        let wanted = tokio::task::spawn_blocking(move || {
            search(turns, &mut wanted);
            wanted
        })
        .await
        .map_err(|error| {
            RpcError::new(
                ErrorCode::InternalError,
                format!("could not search the session for tool output: {error}"),
            )
        })?;
        answer(&wanted)
    }
}

/// Takes the items `wanted` still misses from `turns`, rendering them
/// newest first only until none is missing.
fn search(turns: Option<NewestTurns>, wanted: &mut Wanted) {
    for event in turns.into_iter().flat_map(NewestTurns::events) {
        if wanted.complete() {
            return;
        }
        wanted.find_in(&event.event);
    }
}

/// The answer to a call that found `wanted`: `ToolOutputGone` naming each
/// ref not found, else the items in the order asked that fit in one
/// message, at least one.
fn answer(wanted: &Wanted) -> Result<SessionToolOutputResponse, RpcError> {
    let gone = wanted.gone();
    if !gone.is_empty() {
        // The refs go in the data alone: a call may name many.
        let message = format!(
            "the session no longer holds {} of the tool output items asked",
            gone.len()
        );
        let data = serde_json::to_value(wire::ToolOutputGone::new(gone)).expect("refs are JSON");
        return Err(RpcError::new(ErrorCode::ToolOutputGone, message).with_data(data));
    }
    let mut items = Vec::new();
    let mut taken = 0_usize;
    for (item, content) in wanted.answers() {
        // Every ref asked was found.
        let Some(content) = content else { continue };
        let item = ToolOutputItem::new(item.clone(), content.clone());
        // With a comma between two.
        let bytes = encoded_len(&item).unwrap_or(usize::MAX).saturating_add(1);
        if taken.saturating_add(bytes) > ANSWER_LIMIT {
            if items.is_empty() {
                return Err(RpcError::new(
                    ErrorCode::InternalError,
                    format!(
                        "tool output {} takes {bytes} bytes, past what one answer holds \
                         ({ANSWER_LIMIT} bytes, ANSWER_LIMIT); ask for the others",
                        item.item
                    ),
                ));
            }
            break;
        }
        taken += bytes;
        items.push(item);
    }
    Ok(SessionToolOutputResponse::new(items))
}

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