rho-coding-agent 3.7.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
//! The [`AcpClientPort`] of an ACP v2 connection: Rho's adapter speaks v1,
//! and this port rewrites what it sends into v2.

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>,
    /// The connection's children, which a session port's `subagent_update`s
    /// announce; none on a child's relay, which announces nothing.
    subagents: Option<Arc<Subagents>>,
    /// On a port replaying history, the messages it has reset so far.
    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,
        }
    }

    /// A port for a replay. v2 hosts append chunks to a message they already
    /// hold, so before a replayed message's first chunk this port sends the
    /// message with no content, which resets it; see [`updates::reset`].
    /// It sends history only ([`is_history`]): a v2 resume reports the
    /// session's current info once the replay is through.
    pub(super) fn replaying(cx: V2ConnectionTo<Client>, subagents: Arc<Subagents>) -> Self {
        Self {
            cx,
            subagents: Some(subagents),
            replayed: Some(Mutex::default()),
        }
    }

    /// The port of a child's relay, [`replaying`](Self::replaying) for a
    /// resume's replay of its history: it announces no children, so a
    /// relay neither keeps the registry alive nor writes it.
    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
    }

    /// Sends a v2-only update, such as a `state_update`. A `subagent_update`
    /// announces its child as `session_id`'s.
    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,
            ))
    }

    /// Sends Rho's v1 `notification` in v2 form, as
    /// [`AcpClientPort::send_session_notification`] does. A tool call that
    /// links a child session announces the child first, as the host must
    /// know a session content names.
    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(&notification.update);
        match updates::notification(notification) {
            Ok(Some(notification))
                if self.replayed.is_some() && !is_history(&notification.update) =>
            {
                Ok(())
            }
            Ok(Some(notification)) => self.send_converted(notification, &linked),
            Ok(None) => Ok(()),
            // A card the host cannot draw must not fail the turn that
            // produced it, so it is dropped and logged instead.
            Err(error) => {
                tracing::warn!(%error, "could not convert a session update to ACP v2");
                Ok(())
            }
        }
    }

    /// Sends `notification`, announcing each child it `linked` that the
    /// host was not told of. Live, a linked child with a session of its own
    /// is relayed from here, as one that started and ended between two of
    /// its parent's background reports is never listed.
    fn send_converted(
        &self,
        notification: v2::UpdateSessionNotification,
        linked: &[SubagentRef],
    ) -> Result<(), AcpError> {
        let parent = &notification.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(&notification))
        {
            let first = replayed
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner)
                .insert(message.clone());
            if first {
                if let Some(reset) = updates::reset(&notification) {
                    self.cx.send_notification(reset)?;
                }
            }
        }
        self.cx.send_notification(notification)
    }
}

/// Whether a replay sends `update`. v2 replays the conversation, not the
/// notices, states and session info that were current while it went on:
/// those are live only, and a resume reports what is current now.
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,
        // An update a newer schema adds, which no rho mapping makes yet.
        _ => 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)
        })
    }

    /// Shows the plan as a markdown plan.
    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(&notification)?;
            self.cx.send_notification(notification)
        })
    }

    /// Closes the `running` the host was told with `idle`.
    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");
        }
    }

    /// Reports `requires_action` while the turn waits for a person, and
    /// `running` once it goes on; also the state of a session observed
    /// again after [`AcpClientPort::unobservable`], `idle` included.
    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");
        }
    }

    /// Announces the work that started and finalizes the work that
    /// stopped, then repeats the session's state with the new background
    /// list, unless a prompt's acknowledgement is due to. The list changes
    /// exactly when work starts or stops, so with neither the host hears
    /// nothing.
    /// Children that started are relayed from then on
    /// ([`Subagents::follow`]), and those that stopped are told how
    /// ([`Subagents::ended`]).
    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);
        }
    }

    /// Reports the `unknown` state, with no background list: the host can
    /// tell neither while the session cannot be observed.
    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");
        }
    }
}