use rho_protocol::display::{ToolCard, ToolCardStatus, ToolFact, ToolFamily, ToolHeader};
use serde::Deserialize;
use serde_json::Value;
use super::{body, counted, plural, result, short_id, string_arg, Verb};
use crate::tools::sessions::HistoryAction as Action;
fn verb(action: Action) -> Verb {
match action {
Action::Search => Verb::new("searching", "searched"),
Action::Read => Verb::new("reading", "read"),
Action::Recall => Verb::new("recalling", "recalled"),
}
}
pub(super) fn preview_header(
action: Action,
arguments: &Value,
status: ToolCardStatus,
) -> ToolHeader {
let target = match action {
Action::Search => string_arg(arguments, "query").map(|query| format!("{query:?}")),
Action::Read => None,
Action::Recall => string_arg(arguments, "recall_id"),
};
verb(action).header(status, target.unwrap_or_else(|| "history".to_owned()))
}
pub(super) fn finished_card(action: Action, arguments: &Value, content: &str) -> Option<ToolCard> {
let status = ToolCardStatus::Ok;
let mut lines = Vec::new();
let (header, summary, index) = match action {
Action::Search => {
let (summary, index) = search_receipt(result(content)?, &mut lines);
(preview_header(action, arguments, status), summary, index)
}
Action::Read => {
let read: ReadResult = result(content)?;
let target = read.id.as_deref().map_or_else(
|| "history".to_owned(),
|id| format!("history {}", short_id(id)),
);
let header = verb(action).header(status, target);
let excerpt = read.excerpt;
let mut summary = format!(
"{} · chars {}–{} of {}",
excerpt.role, excerpt.start, excerpt.end, excerpt.total_chars
);
if read.next_start.is_some() {
summary.push_str(" · more available");
}
if excerpt.omitted_blocks > 0 {
summary.push_str(&format!(" · {} blocks omitted", excerpt.omitted_blocks));
}
lines.push(match &read.id {
Some(id) => format!("session: {id}"),
None => format!("handle: {}", read.session),
});
lines.push(format!("anchor: {}", excerpt.anchor));
lines.push(String::new());
lines.extend(excerpt.text.lines().map(str::to_owned));
if let Some(start) = read.next_start {
lines.push(format!("passage continues at char {start}"));
}
if let Some(anchor) = read.next_anchor {
lines.push(format!("next anchor: {anchor}"));
}
if let Some(anchor) = read.previous_anchor {
lines.push(format!("previous anchor: {anchor}"));
}
(header, summary, Some(read.index))
}
Action::Recall => {
let recall: RecallResult = result(content)?;
let header = verb(action).header(status, recall.recall_id);
let mut summary = format!(
"chars {}–{} of {}",
recall.start, recall.end, recall.total_chars
);
if recall.next_start.is_some() {
summary.push_str(" · more available");
}
if !recall.ok {
summary.push_str(" · the original call failed");
}
lines.extend(recall.text.lines().map(str::to_owned));
(header, summary, None)
}
};
let mut card = ToolCard::new(status, ToolFamily::Default, header);
card.push_fact(ToolFact::Meta { text: summary });
if let Some(index) = index.filter(|index| index.skipped_files > 0 || index.omitted_records > 0)
{
card.push_fact(ToolFact::Meta {
text: format!(
"index omissions: {} files skipped · {} records omitted",
index.skipped_files, index.omitted_records
),
});
}
card.body = body(lines);
Some(card)
}
fn search_receipt(page: SearchResult, lines: &mut Vec<String>) -> (String, Option<IndexReport>) {
let mut body = Vec::new();
let (count, total, noun) = match page.listing {
SearchListing::Sessions {
total_sessions,
sessions,
} => {
let count = sessions.len();
for group in sessions {
body.push(String::new());
body.push(format!("session {} · {}", group.id, group.workspace));
body.push(format!("handle: {}", group.session));
body.push(format!(
"{} matching",
counted(group.matching_messages, "message")
));
for excerpt in group.excerpts {
push_excerpt(&mut body, excerpt);
}
if group.omitted_matches > 0 {
body.push(format!(
"{} more matching messages not included",
group.omitted_matches
));
}
}
(count, total_sessions, "session")
}
SearchListing::Matches {
session,
total_matches,
matches,
} => {
let count = matches.len();
if let Some(session) = session {
body.push(String::new());
body.push(format!("handle: {session}"));
}
for excerpt in matches {
push_excerpt(&mut body, excerpt);
}
(count, total_matches, "message")
}
};
let noun = plural(total, noun);
let mut summary = if total == 0 {
format!("no matching {noun} · {}", page.scope)
} else if count == total {
format!("{count} matching {noun} · {}", page.scope)
} else {
format!("{count} of {total} matching {noun} · {}", page.scope)
};
if let Some(offset) = page.next_offset {
summary.push_str(" · more results available");
lines.push(format!("next search offset: {offset}"));
}
if let Some(budget) = page.output_budget_bytes {
summary.push_str(&format!(" · output limited to {budget} bytes"));
}
let skip = usize::from(lines.is_empty() && body.first().is_some_and(String::is_empty));
lines.extend(body.into_iter().skip(skip));
(summary, Some(page.index))
}
fn push_excerpt(lines: &mut Vec<String>, excerpt: Excerpt) {
lines.push(String::new());
lines.push(format!(
"{} · {} · chars {}–{} of {}",
excerpt.role, excerpt.anchor, excerpt.start, excerpt.end, excerpt.total_chars
));
lines.extend(excerpt.text.lines().map(str::to_owned));
if excerpt.omitted_blocks > 0 {
lines.push(format!("{} blocks omitted", excerpt.omitted_blocks));
}
}
#[derive(Deserialize)]
struct SearchResult {
index: IndexReport,
scope: String,
next_offset: Option<usize>,
output_budget_bytes: Option<usize>,
#[serde(flatten)]
listing: SearchListing,
}
#[derive(Deserialize)]
#[serde(untagged)]
enum SearchListing {
Sessions {
total_sessions: usize,
sessions: Vec<SessionGroup>,
},
Matches {
session: Option<String>,
total_matches: usize,
matches: Vec<Excerpt>,
},
}
#[derive(Deserialize)]
struct SessionGroup {
session: String,
id: String,
workspace: String,
matching_messages: usize,
excerpts: Vec<Excerpt>,
omitted_matches: usize,
}
#[derive(Deserialize)]
struct Excerpt {
anchor: String,
role: String,
start: usize,
end: usize,
total_chars: usize,
text: String,
omitted_blocks: usize,
}
#[derive(Deserialize)]
struct ReadResult {
index: IndexReport,
session: String,
#[serde(default)]
id: Option<String>,
#[serde(flatten)]
excerpt: Excerpt,
next_start: Option<usize>,
next_anchor: Option<String>,
previous_anchor: Option<String>,
}
#[derive(Deserialize)]
struct RecallResult {
recall_id: String,
ok: bool,
text: String,
start: usize,
end: usize,
total_chars: usize,
next_start: Option<usize>,
}
#[derive(Deserialize)]
struct IndexReport {
skipped_files: usize,
omitted_records: usize,
}