use std::{
collections::HashSet,
future::Future,
pin::Pin,
sync::{Arc, Mutex},
};
use agent_client_protocol::{v1::schema as v1, v2::schema as v2};
use agent_client_protocol::{v2::ConnectionTo as V2ConnectionTo, Client, Error as AcpError};
use rho_protocol::{BackgroundWork, SubagentRef};
use super::{
background, bridge, elicitation, requests,
subagents::{child_id, ChildReplay, Subagents},
terminals, updates,
};
use crate::app::acp::{AcpClientPort, BackgroundChanged, Foreground, TurnEnd};
pub(super) struct V2Port {
cx: V2ConnectionTo<Client>,
subagents: Option<Arc<Subagents>>,
replayed: Option<Mutex<HashSet<v2::MessageId>>>,
}
impl V2Port {
pub(super) fn new(cx: V2ConnectionTo<Client>, subagents: Arc<Subagents>) -> Self {
Self {
cx,
subagents: Some(subagents),
replayed: None,
}
}
pub(super) fn replaying(cx: V2ConnectionTo<Client>, subagents: Arc<Subagents>) -> Self {
Self {
cx,
subagents: Some(subagents),
replayed: Some(Mutex::default()),
}
}
pub(super) fn child(cx: V2ConnectionTo<Client>, replay: ChildReplay) -> Self {
Self {
cx,
subagents: None,
replayed: match replay {
ChildReplay::History => Some(Mutex::default()),
ChildReplay::Live => None,
},
}
}
pub(super) fn cx(&self) -> &V2ConnectionTo<Client> {
&self.cx
}
pub(super) fn send_update(
&self,
session_id: &v2::SessionId,
update: v2::SessionUpdate,
) -> Result<(), AcpError> {
if let (v2::SessionUpdate::SubagentUpdate(child), Some(subagents)) =
(&update, &self.subagents)
{
subagents.announced(session_id, &child.session_id);
}
self.cx
.send_notification(v2::UpdateSessionNotification::new(
session_id.clone(),
update,
))
}
pub(super) fn forward(&self, notification: v1::SessionNotification) {
if let Err(error) = self.deliver(notification) {
tracing::warn!(%error, "could not send session update over ACP v2");
}
}
fn deliver(&self, notification: v1::SessionNotification) -> Result<(), AcpError> {
let linked = updates::linked_children(¬ification.update);
match updates::notification(notification) {
Ok(Some(notification))
if self.replayed.is_some() && !is_history(¬ification.update) =>
{
Ok(())
}
Ok(Some(notification)) => self.send_converted(notification, &linked),
Ok(None) => Ok(()),
Err(error) => {
tracing::warn!(%error, "could not convert a session update to ACP v2");
Ok(())
}
}
}
fn send_converted(
&self,
notification: v2::UpdateSessionNotification,
linked: &[SubagentRef],
) -> Result<(), AcpError> {
let parent = ¬ification.session_id;
for child in linked {
let id = child_id(&child.run, child.session.as_ref());
let known = self
.subagents
.as_ref()
.is_some_and(|subagents| subagents.is_child_of(&parent.0, &id));
if !known {
let announced = v2::SubagentUpdate::new(id.clone());
self.send_update(parent, v2::SessionUpdate::SubagentUpdate(announced))?;
}
if let (Some(subagents), Some(session), None) =
(&self.subagents, &child.session, &self.replayed)
{
subagents.linked(&self.cx, parent, id, session.clone());
}
}
if let (Some(replayed), Some(message)) =
(&self.replayed, updates::chunk_message_id(¬ification))
{
let first = replayed
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.insert(message.clone());
if first {
if let Some(reset) = updates::reset(¬ification) {
self.cx.send_notification(reset)?;
}
}
}
self.cx.send_notification(notification)
}
}
fn is_history(update: &v2::SessionUpdate) -> bool {
use v2::SessionUpdate as U;
match update {
U::UserMessageChunk(_)
| U::UserMessage(_)
| U::AgentMessageChunk(_)
| U::AgentMessage(_)
| U::AgentThoughtChunk(_)
| U::AgentThought(_)
| U::ToolCallContentChunk(_)
| U::ToolCallUpdate(_)
| U::TerminalUpdate(_)
| U::TerminalOutputChunk(_)
| U::PlanUpdate(_)
| U::PlanRemoved(_)
| U::CompactionUpdate(_)
| U::CompactionSummaryChunk(_)
| U::SubagentUpdate(_)
| U::SessionMessage(_)
| U::SessionMessageChunk(_) => true,
U::StateUpdate(_)
| U::AvailableCommandsUpdate(_)
| U::ConfigOptionUpdate(_)
| U::SessionInfoUpdate(_)
| U::UsageUpdate(_)
| U::Notice(_)
| U::ReplayComplete(_) => false,
_ => true,
}
}
impl AcpClientPort for V2Port {
fn send_session_notification(
&self,
notification: v1::SessionNotification,
) -> Pin<Box<dyn Future<Output = Result<(), AcpError>> + Send + '_>> {
Box::pin(async move { self.deliver(notification) })
}
fn request_permission(
&self,
request: v1::RequestPermissionRequest,
) -> Pin<Box<dyn Future<Output = Result<v1::RequestPermissionResponse, AcpError>> + Send + '_>>
{
Box::pin(async move {
let request = requests::permission_request(request)?;
let offered = request.options.clone();
let response = self.cx.send_request(request).block_task().await?;
Ok(requests::permission_response(response, &offered))
})
}
fn create_elicitation(
&self,
request: v1::CreateElicitationRequest,
) -> Pin<Box<dyn Future<Output = Result<v1::CreateElicitationResponse, AcpError>> + Send + '_>>
{
Box::pin(async move {
let request = elicitation::request(&request)?;
let response = self.cx.send_request(request).block_task().await?;
elicitation::response(response)
})
}
fn plan_proposed(&self, session_id: &v1::SessionId, plan: &str) {
let sent = bridge::<_, v2::SessionId>(session_id)
.and_then(|session_id| self.send_update(&session_id, updates::proposed_plan(plan)));
if let Err(error) = sent {
tracing::warn!(%error, "could not show a proposed plan over ACP v2");
}
}
fn plan_withdrawn(&self, session_id: &v1::SessionId) {
let sent = bridge::<_, v2::SessionId>(session_id)
.and_then(|session_id| self.send_update(&session_id, updates::withdrawn_plan()));
if let Err(error) = sent {
tracing::warn!(%error, "could not withdraw a proposed plan over ACP v2");
}
}
fn complete_elicitation(
&self,
notification: v1::CompleteElicitationNotification,
) -> Pin<Box<dyn Future<Output = Result<(), AcpError>> + Send + '_>> {
Box::pin(async move {
let notification: v2::CompleteElicitationNotification = bridge(¬ification)?;
self.cx.send_notification(notification)
})
}
fn turn_ended(&self, session_id: &v1::SessionId, end: TurnEnd, background: &[BackgroundWork]) {
let sent = bridge::<_, v2::SessionId>(session_id)
.and_then(|session_id| self.send_update(&session_id, requests::idle(&end, background)));
if let Err(error) = sent {
tracing::warn!(%error, "could not report the end of an attached turn over ACP v2");
}
}
fn foreground_changed(
&self,
session_id: &v1::SessionId,
foreground: Foreground,
background: &[BackgroundWork],
) {
let sent = bridge::<_, v2::SessionId>(session_id).and_then(|session_id| {
self.send_update(&session_id, background::state(foreground, background))
});
if let Err(error) = sent {
tracing::warn!(%error, "could not report a turn's state over ACP v2");
}
}
fn background_changed(&self, session_id: &v1::SessionId, change: BackgroundChanged<'_>) {
let background::Changes {
updates,
children_ended,
} = background::changes(change.previous, change.current, change.workspace);
if updates.is_empty() {
return;
}
let sent = bridge::<_, v2::SessionId>(session_id).and_then(|session_id| {
for update in updates {
self.send_update(&session_id, update)?;
}
if let Some(subagents) = &self.subagents {
subagents.follow(&self.cx, &session_id, change.current);
for (child, status) in children_ended {
subagents.ended(&self.cx, &session_id, &child, status);
}
}
match change.foreground {
Some(foreground) => {
self.send_update(&session_id, background::state(foreground, change.current))
}
None => Ok(()),
}
});
if let Err(error) = sent {
tracing::warn!(%error, "could not report background work over ACP v2");
}
}
fn terminal_output(&self, session_id: &v1::SessionId, process: &str, text: &str) {
let sent = bridge::<_, v2::SessionId>(session_id)
.and_then(|session_id| self.send_update(&session_id, terminals::output(process, text)));
if let Err(error) = sent {
tracing::warn!(%error, "could not send a terminal's output over ACP v2");
}
}
fn child_session(
&self,
session_id: &v1::SessionId,
child: &SubagentRef,
) -> Option<v1::SessionId> {
let child = child_id(&child.run, child.session.as_ref());
self.subagents
.as_ref()?
.is_child_of(&session_id.0, &child)
.then(|| v1::SessionId::new(child))
}
fn released(&self, session_id: &v1::SessionId) {
if let Some(subagents) = &self.subagents {
subagents.release(&session_id.0);
}
}
fn unobservable(&self, session_id: &v1::SessionId) {
let unknown =
v2::SessionUpdate::StateUpdate(v2::StateUpdate::Unknown(v2::UnknownStateUpdate::new()));
let sent = bridge::<_, v2::SessionId>(session_id)
.and_then(|session_id| self.send_update(&session_id, unknown));
if let Err(error) = sent {
tracing::warn!(%error, "could not report a session's lost state over ACP v2");
}
}
}