use std::{
collections::{HashMap, HashSet},
path::{Path, PathBuf},
};
use agent_client_protocol::Error as AcpError;
use agent_client_protocol::{schema::MaybeUndefined, v1::schema as v1, v2::schema as v2};
use rho_protocol::SubagentRef;
use super::{bridge, git_patch::FileContents, subagents::child_id};
use crate::app::acp::markers;
const TODO_PLAN_ID: &str = "rho-todos";
const PROPOSED_PLAN_ID: &str = "rho-plan";
pub(super) fn notification(
notification: v1::SessionNotification,
) -> Result<Option<v2::UpdateSessionNotification>, AcpError> {
let v1::SessionNotification {
session_id,
update,
meta,
..
} = notification;
let Some(update) = session_update(update)? else {
return Ok(None);
};
Ok(Some(
v2::UpdateSessionNotification::new(bridge::<_, v2::SessionId>(&session_id)?, update)
.meta(meta),
))
}
fn session_update(update: v1::SessionUpdate) -> Result<Option<v2::SessionUpdate>, AcpError> {
use v1::SessionUpdate as V1;
use v2::SessionUpdate as V2;
Ok(Some(match update {
V1::UserMessageChunk(chunk) => V2::UserMessageChunk(content_chunk(chunk)?),
V1::AgentMessageChunk(chunk) => V2::AgentMessageChunk(content_chunk(chunk)?),
V1::AgentThoughtChunk(chunk) => V2::AgentThoughtChunk(content_chunk(chunk)?),
V1::ToolCall(call) => V2::ToolCallUpdate(created_tool_call(call)?),
V1::ToolCallUpdate(update) => V2::ToolCallUpdate(tool_call_update(update)?),
V1::Plan(plan) if plan.entries.is_empty() => {
V2::PlanRemoved(v2::PlanRemoved::new(TODO_PLAN_ID).meta(plan.meta))
}
V1::Plan(plan) => V2::PlanUpdate(
v2::PlanUpdate::new(v2::PlanUpdateContent::Items(v2::PlanItems::new(
TODO_PLAN_ID,
bridge(&plan.entries)?,
)))
.meta(plan.meta),
),
V1::AvailableCommandsUpdate(update) => V2::AvailableCommandsUpdate(
v2::AvailableCommandsUpdate::new(available_commands(update.available_commands)?)
.meta(update.meta),
),
V1::CurrentModeUpdate(_) => return Ok(None),
V1::ConfigOptionUpdate(update) => V2::ConfigOptionUpdate(
v2::ConfigOptionUpdate::new(config_options(update.config_options)?).meta(update.meta),
),
V1::SessionInfoUpdate(update) => V2::SessionInfoUpdate(bridge(&update)?),
V1::UsageUpdate(update) => V2::UsageUpdate(bridge(&update)?),
V1::Notice(notice) => V2::Notice(bridge(¬ice)?),
V1::CompactionUpdate(update) => V2::CompactionUpdate(bridge(&update)?),
V1::CompactionSummaryChunk(chunk) => V2::CompactionSummaryChunk(bridge(&chunk)?),
_ => return Err(AcpError::internal_error().data("no ACP v2 form for this session update")),
}))
}
pub(super) fn proposed_plan(markdown: &str) -> v2::SessionUpdate {
v2::SessionUpdate::PlanUpdate(v2::PlanUpdate::new(v2::PlanUpdateContent::Markdown(
v2::PlanMarkdown::new(PROPOSED_PLAN_ID, markdown),
)))
}
pub(super) fn withdrawn_plan() -> v2::SessionUpdate {
v2::SessionUpdate::PlanRemoved(v2::PlanRemoved::new(PROPOSED_PLAN_ID))
}
pub(super) fn chunk_message_id(
notification: &v2::UpdateSessionNotification,
) -> Option<&v2::MessageId> {
use v2::SessionUpdate as V2;
match ¬ification.update {
V2::UserMessageChunk(chunk)
| V2::AgentMessageChunk(chunk)
| V2::AgentThoughtChunk(chunk) => Some(&chunk.message_id),
_ => None,
}
}
pub(super) fn linked_children(update: &v1::SessionUpdate) -> Vec<SubagentRef> {
let contents: &[v1::ToolCallContent] = match update {
v1::SessionUpdate::ToolCall(call) => &call.content,
v1::SessionUpdate::ToolCallUpdate(call) => call.fields.content.as_deref().unwrap_or(&[]),
_ => &[],
};
contents
.iter()
.filter_map(|content| match content {
v1::ToolCallContent::Content(content) => markers::subagent_in(content.meta.as_ref()),
_ => None,
})
.collect()
}
pub(super) fn reset(
notification: &v2::UpdateSessionNotification,
) -> Option<v2::UpdateSessionNotification> {
use v2::SessionUpdate as V2;
let update = match ¬ification.update {
V2::UserMessageChunk(chunk) => {
V2::UserMessage(v2::UserMessage::new(chunk.message_id.clone()).content(Vec::new()))
}
V2::AgentMessageChunk(chunk) => {
V2::AgentMessage(v2::AgentMessage::new(chunk.message_id.clone()).content(Vec::new()))
}
V2::AgentThoughtChunk(chunk) => {
V2::AgentThought(v2::AgentThought::new(chunk.message_id.clone()).content(Vec::new()))
}
_ => return None,
};
Some(
v2::UpdateSessionNotification::new(notification.session_id.clone(), update)
.meta(notification.meta.clone()),
)
}
fn content_chunk(chunk: v1::ContentChunk) -> Result<v2::ContentChunk, AcpError> {
let Some(message_id) = chunk.message_id else {
return Err(AcpError::internal_error().data("ACP v2 message chunk without a message id"));
};
Ok(v2::ContentChunk::new(
bridge(&chunk.content)?,
bridge::<_, v2::MessageId>(&message_id)?,
)
.meta(chunk.meta))
}
fn created_tool_call(call: v1::ToolCall) -> Result<v2::ToolCallUpdate, AcpError> {
let v1::ToolCall {
tool_call_id,
title,
name,
kind,
status,
content,
locations,
raw_input,
raw_output,
meta,
..
} = call;
let fields = v1::ToolCallUpdateFields::new()
.title(title)
.name(name)
.kind(kind)
.status(status)
.content(content)
.locations(locations)
.raw_input(raw_input)
.raw_output(raw_output);
tool_call_update(v1::ToolCallUpdate::new(tool_call_id, fields).meta(meta))
}
pub(super) fn tool_call_update(update: v1::ToolCallUpdate) -> Result<v2::ToolCallUpdate, AcpError> {
let v1::ToolCallUpdate {
tool_call_id,
fields,
mut meta,
..
} = update;
let cancelled = markers::take_flag(&mut meta, markers::TOOL_CANCELLED);
let v1::ToolCallUpdateFields {
kind,
status,
title,
name,
content,
locations,
raw_input,
raw_output,
..
} = fields;
let content = content.map(tool_call_contents).transpose()?;
Ok(
v2::ToolCallUpdate::new(bridge::<_, v2::ToolCallId>(&tool_call_id)?)
.title(unchanged_if_absent(title))
.name(unchanged_if_absent(name))
.kind(unchanged_if_absent(
kind.map(|kind| bridge(&kind)).transpose()?,
))
.status(unchanged_if_absent(match status {
Some(_) if cancelled => Some(v2::ToolCallStatus::Cancelled),
status => status.map(|status| bridge(&status)).transpose()?,
}))
.content(unchanged_if_absent(content))
.locations(unchanged_if_absent(
locations.map(|locations| locations.into_iter().map(location).collect()),
))
.raw_input(unchanged_if_absent(raw_input))
.raw_output(unchanged_if_absent(raw_output))
.meta(unchanged_if_absent(meta)),
)
}
fn location(location: v1::ToolCallLocation) -> v2::ToolCallLocation {
v2::ToolCallLocation::new(location.path)
.line(location.line)
.meta(location.meta)
}
fn unchanged_if_absent<T>(value: Option<T>) -> MaybeUndefined<T> {
match value {
Some(value) => MaybeUndefined::Value(value),
None => MaybeUndefined::Undefined,
}
}
fn tool_call_contents(
content: Vec<v1::ToolCallContent>,
) -> Result<Vec<v2::ToolCallContent>, AcpError> {
let pieces: Vec<Piece> = content.into_iter().map(Piece::of).collect();
let mut deletions: HashMap<&Path, (usize, &MarkedDiff)> = pieces
.iter()
.enumerate()
.filter_map(|(index, piece)| match piece {
Piece::Diff(diff) if diff.deleted => Some((diff.diff.path.as_path(), (index, diff))),
_ => None,
})
.collect();
let sources: Vec<_> = pieces
.iter()
.map(|piece| match piece {
Piece::Diff(MarkedDiff {
moved_from: Some(from),
..
}) => deletions.remove(from.as_path()),
_ => None,
})
.collect();
let covered: HashSet<usize> = sources.iter().flatten().map(|&(index, _)| index).collect();
pieces
.iter()
.zip(sources)
.enumerate()
.filter(|(index, _)| !covered.contains(index))
.map(|(_, (piece, source))| match piece {
Piece::Diff(diff) => Ok(v2::ToolCallContent::from(file_diff(
diff,
source.map(|(_, source)| source),
))),
Piece::Session(child) => Ok(v2::ToolCallContent::Session(v2::SessionReference::new(
child.clone(),
))),
Piece::Other(content) => other_content(content),
})
.collect()
}
enum Piece {
Diff(MarkedDiff),
Session(v2::SessionId),
Other(Box<v1::ToolCallContent>),
}
impl Piece {
fn of(content: v1::ToolCallContent) -> Self {
match content {
v1::ToolCallContent::Diff(mut diff) => {
let deleted = markers::take_flag(&mut diff.meta, markers::DELETED_FILE);
let moved_from = markers::take_path(&mut diff.meta, markers::MOVED_FROM);
Self::Diff(MarkedDiff {
diff,
deleted,
moved_from,
})
}
v1::ToolCallContent::Content(mut content) => {
match markers::take_subagent(&mut content.meta) {
Some(child) => Self::Session(v2::SessionId::new(child_id(
&child.run,
child.session.as_ref(),
))),
None => Self::Other(Box::new(v1::ToolCallContent::Content(content))),
}
}
other => Self::Other(Box::new(other)),
}
}
}
struct MarkedDiff {
diff: v1::Diff,
deleted: bool,
moved_from: Option<PathBuf>,
}
fn other_content(content: &v1::ToolCallContent) -> Result<v2::ToolCallContent, AcpError> {
Ok(match content {
v1::ToolCallContent::Content(content) => v2::ToolCallContent::Content(Box::new(
v2::Content::new(bridge::<_, v2::ContentBlock>(&content.content)?)
.meta(content.meta.clone()),
)),
v1::ToolCallContent::Terminal(terminal) => v2::ToolCallContent::Terminal(bridge(terminal)?),
_ => return Err(AcpError::internal_error().data("no ACP v2 form for this tool content")),
})
}
fn file_diff(diff: &MarkedDiff, source: Option<&MarkedDiff>) -> v2::Diff {
let path = diff.diff.path.as_path();
let new = diff.diff.new_text.as_str();
let (change, contents) = match (source, &diff.diff.old_text, diff.deleted) {
(Some(source), _, _) => {
let from: &Path = &source.diff.path;
(
v2::DiffChange::move_file(from.to_path_buf(), path.to_path_buf()),
FileContents::Moved {
from,
old: source.diff.old_text.as_deref().unwrap_or_default(),
new,
},
)
}
(None, None, _) => (
v2::DiffChange::add(path.to_path_buf()),
FileContents::Created(new),
),
(None, Some(old), true) => (
v2::DiffChange::delete(path.to_path_buf()),
FileContents::Deleted(old),
),
(None, Some(old), false) => (
v2::DiffChange::modify(path.to_path_buf()),
FileContents::Modified { old, new },
),
};
let patch = super::git_patch::file_patch(path, contents);
v2::Diff::new(vec![change.file_type(v2::DiffFileType::Text)])
.with_patch(patch.map(v2::DiffPatch::new))
.meta(diff.diff.meta.clone())
}
pub(super) fn available_commands(
commands: Vec<v1::AvailableCommand>,
) -> Result<Vec<v2::AvailableCommand>, AcpError> {
commands
.into_iter()
.map(|command| {
let input = match command.input {
Some(v1::AvailableCommandInput::Unstructured(input)) => {
Some(v2::AvailableCommandInput::Text(
v2::TextCommandInput::new(input.hint).meta(input.meta),
))
}
None => None,
Some(_) => {
return Err(AcpError::internal_error().data("no ACP v2 form for command input"))
}
};
Ok(v2::AvailableCommand::Command(
v2::Command::new(command.name, command.description)
.input(input)
.meta(command.meta),
))
})
.collect()
}
pub(super) fn config_options(
options: Vec<v1::SessionConfigOption>,
) -> Result<Vec<v2::SessionConfigOption>, AcpError> {
options.into_iter().map(config_option).collect()
}
fn config_option(option: v1::SessionConfigOption) -> Result<v2::SessionConfigOption, AcpError> {
let kind = match option.kind {
v1::SessionConfigKind::Select(select) => {
let options = match select.options {
v1::SessionConfigSelectOptions::Ungrouped(options) => {
v2::SessionConfigSelectOptions::Ungrouped(bridge(&options)?)
}
v1::SessionConfigSelectOptions::Grouped(groups) => {
v2::SessionConfigSelectOptions::Grouped(
groups
.into_iter()
.map(|group| {
Ok(v2::SessionConfigSelectGroup::new(
group.group.0.clone(),
group.name,
bridge(&group.options)?,
)
.meta(group.meta))
})
.collect::<Result<_, AcpError>>()?,
)
}
_ => {
return Err(AcpError::internal_error().data("no ACP v2 form for these options"))
}
};
v2::SessionConfigKind::Select(v2::SessionConfigSelect::new(
select.current_value.0.clone(),
options,
))
}
v1::SessionConfigKind::Boolean(boolean) => {
v2::SessionConfigKind::Boolean(v2::SessionConfigBoolean::new(boolean.current_value))
}
_ => return Err(AcpError::internal_error().data("no ACP v2 form for this config option")),
};
Ok(
v2::SessionConfigOption::new(option.id.0.clone(), option.name, kind)
.description(option.description)
.category(
option
.category
.map(|category| bridge(&category))
.transpose()?,
)
.meta(option.meta),
)
}
#[cfg(test)]
#[path = "updates_tests.rs"]
mod tests;