rho-coding-agent 3.7.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
//! Cards for `sessions` calls. A call searches saved history (`history`:
//! `search`, `recall`, and a `read` with an `anchor`) or acts on sessions
//! the daemon has (`control`: every other action). Each half projects its
//! calls' arguments and JSON results into cards; renderers only see cards.
//!
//! Every card reads `<verb>  <target>`, with the verb progressive while the
//! call runs and past once it ended: `waiting on 1a2b3c4d`, then `waited
//! Fix fold jump · completed`.

use rho_protocol::display::{ToolBody, ToolCard, ToolCardStatus, ToolFamily, ToolHeader};
use serde_json::Value;

use super::format::{push_error_output, split_body_lines, string_arg, truncate};
use crate::tools::sessions::{result, Route};

#[path = "interactive_presenter_sessions/control.rs"]
mod control;
#[path = "interactive_presenter_sessions/history.rs"]
mod history;

/// A header verb in both tenses.
#[derive(Clone, Copy)]
struct Verb {
    running: &'static str,
    done: &'static str,
}

impl Verb {
    const fn new(running: &'static str, done: &'static str) -> Self {
        Self { running, done }
    }

    /// The header naming `target`, in the tense of a card with `status`: an
    /// interrupted call never ended, so it keeps the running verb.
    fn header(self, status: ToolCardStatus, target: impl Into<String>) -> ToolHeader {
        let verb = match status {
            ToolCardStatus::Ok | ToolCardStatus::Error => self.done,
            ToolCardStatus::Running | ToolCardStatus::Interrupted | ToolCardStatus::Unknown => {
                self.running
            }
            // A status a newer protocol adds.
            _ => self.running,
        };
        ToolHeader::status_first(verb, target)
    }
}

/// The card of a call with `arguments` before it finished, from its
/// arguments alone.
pub(super) fn preview_card(arguments: &Value, status: ToolCardStatus) -> ToolCard {
    let header = match Route::of(arguments) {
        Some(Route::History(action)) => history::preview_header(action, arguments, status),
        Some(Route::Control(action)) => control::preview_header(action, arguments, status),
        None => ToolHeader::call(crate::session::search::TOOL_NAME, None),
    };
    ToolCard::new(status, ToolFamily::Default, header)
}

/// The card of a finished call. A failure shows its error; a result the
/// card cannot read shows as it came, under the call's header.
pub(super) fn finished_card(arguments: &Value, content: &str, ok: bool) -> ToolCard {
    let status = ToolCardStatus::from_finished(ok);
    if !ok {
        let mut card = preview_card(arguments, status);
        push_error_output(&mut card, content);
        return card;
    }
    let card = match Route::of(arguments) {
        Some(Route::History(action)) => history::finished_card(action, arguments, content),
        Some(Route::Control(action)) => control::finished_card(action, arguments, content),
        None => None,
    };
    card.unwrap_or_else(|| {
        let mut card = preview_card(arguments, status);
        card.body = ToolBody::Lines(split_body_lines(content));
        card
    })
}

/// A body of `lines`, or none to expand when there are none.
fn body(lines: Vec<String>) -> ToolBody {
    if lines.is_empty() {
        ToolBody::None
    } else {
        ToolBody::Lines(lines)
    }
}

/// The short form of a session id or handle, as `rho sessions` shows it.
fn short_id(id: &str) -> String {
    id.chars().take(8).collect()
}

/// `text`'s first non-empty line, quoted and shortened to fit a header or
/// fact, and whether that left any of `text` out.
fn quoted_first_line(text: &str) -> (String, bool) {
    let mut lines = text.lines().map(str::trim).filter(|line| !line.is_empty());
    let first = lines.next().unwrap_or_default();
    let shown = truncate(first, 72);
    let whole = first.split_whitespace().collect::<Vec<_>>().join(" ");
    let cut = shown != whole || lines.next().is_some();
    (format!("\"{shown}\""), cut)
}

/// `count` and `noun`, plural unless `count` is 1.
fn counted(count: usize, noun: &str) -> String {
    format!("{count} {}", plural(count, noun))
}

fn plural(count: usize, noun: &str) -> String {
    if count == 1 {
        noun.to_owned()
    } else {
        format!("{noun}s")
    }
}

/// The `session` argument, shortened, for a card whose result has not
/// named the session yet.
fn session_arg(arguments: &Value) -> String {
    string_arg(arguments, "session").map_or_else(|| "session".to_owned(), |id| short_id(&id))
}

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