use std::{collections::HashMap, path::Path};
use rho_protocol::display::ToolHeader;
use rho_protocol::{
CardTone, ContentBlock, Location, PlanEntry, PlanStatus, SessionEvent as WireEvent, SteerId,
ToolCallId, ToolCallUpdate, ToolContent, ToolStatus,
};
use rho_sdk::{model, tool::ToolMetadata};
use serde_json::Value;
use crate::{
app::interactive_presenter::call_header,
display_transcript::{DisplayRow, DisplayTranscript},
tools::{
mcp::exported_name::McpToolNames,
todo::{TodoState, TodoStatus},
},
};
use rho_protocol::display::NotificationTone;
mod live;
pub(crate) mod outcome;
mod replay;
#[cfg(test)]
mod test_support;
mod tools;
pub(crate) use live::{CompactionEnd, LiveEvents};
pub(crate) use replay::{SavedTranscript, SavedTurn};
#[derive(Clone, Debug, Default)]
struct CallIds {
opened: HashMap<String, usize>,
}
impl CallIds {
fn open(&mut self, provider: &str) -> ToolCallId {
let count = self.opened.entry(provider.to_owned()).or_default();
*count += 1;
match (provider.is_empty(), *count) {
(false, 1) => ToolCallId::new(provider),
(false, n) => ToolCallId::new(format!("{provider}#{n}")),
(true, n) => ToolCallId::new(format!("unnamed-call-{n}")),
}
}
fn cover(&mut self, other: &Self) {
for (provider, &count) in &other.opened {
let own = self.opened.entry(provider.clone()).or_default();
*own = (*own).max(count);
}
}
}
pub(crate) fn encoded_len(event: &WireEvent) -> Option<usize> {
struct Counter(usize);
impl std::io::Write for Counter {
fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
self.0 += bytes.len();
Ok(bytes.len())
}
fn flush(&mut self) -> std::io::Result<()> {
Ok(())
}
}
let mut counter = Counter(0);
match serde_json::to_writer(&mut counter, event) {
Ok(()) => Some(counter.0),
Err(error) => {
tracing::warn!(%error, "dropped a session event JSON cannot hold");
None
}
}
}
const UNNAMED_TOOL_TITLE: &str = "tool";
fn opened_call(
id: ToolCallId,
name: &str,
arguments: Option<Value>,
metadata: &ToolMetadata,
cwd: &Path,
mcp_tools: &McpToolNames,
) -> ToolCallUpdate {
let locations = tools::started_locations(name, arguments.as_ref(), metadata, cwd);
ToolCallUpdate {
status: Some(ToolStatus::InProgress),
locations: non_empty(locations),
..named_call(id, name, arguments, metadata, cwd, mcp_tools)
}
}
fn named_call(
id: ToolCallId,
name: &str,
arguments: Option<Value>,
metadata: &ToolMetadata,
cwd: &Path,
mcp_tools: &McpToolNames,
) -> ToolCallUpdate {
ToolCallUpdate {
title: Some(tool_title(
name,
arguments.as_ref(),
metadata,
cwd,
mcp_tools,
)),
kind: Some(tools::kind(name, arguments.as_ref(), metadata)),
raw_input: arguments,
..status_update(id, None)
}
}
fn status_update(id: ToolCallId, status: Option<ToolStatus>) -> ToolCallUpdate {
ToolCallUpdate {
id,
title: None,
kind: None,
status,
raw_input: None,
content: None,
locations: None,
display: None,
}
}
fn tool_title(
name: &str,
arguments: Option<&Value>,
metadata: &ToolMetadata,
cwd: &Path,
mcp_tools: &McpToolNames,
) -> String {
if let Some(command) = metadata.command_line_text().filter(|c| !c.is_empty()) {
return command.to_owned();
}
let title = match call_header(name, arguments, metadata, cwd, mcp_tools) {
ToolHeader::Shell {
command: Some(command),
..
} => command,
ToolHeader::Shell { command: None, .. } => name.to_owned(),
ToolHeader::StatusFirst { identity, .. } => identity,
ToolHeader::Call {
verb,
primary: Some(primary),
} if !primary.is_empty() => format!("{verb}({primary})"),
ToolHeader::Call { verb, .. } => verb,
_ => name.to_owned(),
};
match mcp_tools.identify(name) {
Some(identity) => format!("{}/{title}", identity.server),
None => title,
}
}
pub(crate) fn steer_to_wire(id: &rho_sdk::SteeringId) -> SteerId {
SteerId::new(id.as_str())
}
fn user_content(blocks: &[model::ContentBlock]) -> Vec<ContentBlock> {
blocks
.iter()
.filter_map(|block| match block {
model::ContentBlock::Text(text) if !text.is_empty() => {
Some(ContentBlock::Text { text: text.clone() })
}
model::ContentBlock::Image(image) => Some(ContentBlock::Image {
mime_type: image.mime_type.clone(),
data: image.data.clone(),
}),
model::ContentBlock::Text(_) | model::ContentBlock::ToolCall(_) => None,
})
.collect()
}
fn result_content(text: &str, images: &[model::ImageContent]) -> Vec<ToolContent> {
let text = (!text.is_empty()).then(|| text_content(text));
text.into_iter()
.chain(images.iter().map(|image| ToolContent::Image {
mime_type: image.mime_type.clone(),
data: image.data.clone(),
}))
.collect()
}
fn text_content(text: impl Into<String>) -> ToolContent {
ToolContent::Text { text: text.into() }
}
fn cards(transcript: &DisplayTranscript) -> impl Iterator<Item = WireEvent> + '_ {
transcript.0.iter().map(card)
}
fn card(row: &DisplayRow) -> WireEvent {
let text = row.card_text();
WireEvent::Card {
title: text.title.to_owned(),
markdown: text.markdown,
plain: text.plain,
tone: card_tone(row),
display: match row {
DisplayRow::Notification(card) => Some(card.clone()),
DisplayRow::Notice(_) | DisplayRow::Compaction(_) => None,
},
}
}
fn card_tone(row: &DisplayRow) -> CardTone {
match row {
DisplayRow::Notification(card) => match card.tone {
NotificationTone::Neutral => CardTone::Neutral,
NotificationTone::Accent => CardTone::Accent,
NotificationTone::Success => CardTone::Success,
NotificationTone::Warning => CardTone::Warning,
NotificationTone::Error => CardTone::Error,
_ => CardTone::Neutral,
},
DisplayRow::Notice(_) | DisplayRow::Compaction(_) => CardTone::Neutral,
}
}
fn plan_entries(todo: &TodoState) -> Vec<PlanEntry> {
let Some(list) = todo.list() else {
return Vec::new();
};
list.todos
.iter()
.map(|item| PlanEntry {
content: item.content.clone(),
status: match item.status {
TodoStatus::Pending => PlanStatus::Pending,
TodoStatus::InProgress => PlanStatus::InProgress,
TodoStatus::Completed => PlanStatus::Completed,
},
})
.collect()
}
fn non_empty(locations: Vec<Location>) -> Option<Vec<Location>> {
Some(locations).filter(|locations| !locations.is_empty())
}