rho-coding-agent 3.7.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
//! A session's open input requests, put to the host.
//!
//! The daemon asks every attached client (`SessionEvent::InputRequested`);
//! the first answer wins and every client hears `InputResolved`. Each open
//! request is one task here that asks the host and sends its answer back;
//! a resolution, from this host or another client, aborts the task, which
//! drops the host request (the connection then cancels it).
//!
//! - An approval is `session/request_permission` on the call's card, or on
//!   a placeholder card for a call the host never saw.
//! - A plan approval is `session/request_permission` offering the modes,
//!   with the plan shown while it is asked ([`AcpClientPort::plan_proposed`]).
//! - A question is a form-mode `elicitation/create` on hosts that draw
//!   forms. A host without forms leaves it to the other clients: sessions
//!   it opens ask none (the daemon declines an MCP server's question
//!   itself), but a session another client opened may.
//!
//! Closing a session on ACP v2 withdraws its open requests from the host
//! before it answers ([`Asks::withdrawn`]).

use std::{
    collections::HashMap,
    future::Future,
    sync::{
        atomic::{AtomicU64, Ordering},
        Arc,
    },
};

use agent_client_protocol::{v1::schema::SessionId as AcpSessionId, Error as AcpError};
use rho_protocol::{
    methods::{SessionAnswer, SessionHold},
    Ask, ClientError, ErrorCode, InputAnswer, InputAsker, InputRequest, InputRequestId,
    SessionAnswerParams, SessionHoldParams, SessionId,
};
use tokio::{sync::watch, task::JoinHandle};

use super::{
    elicitation,
    host_features::{Forms, HostFeatures},
    permission::{self, Card},
    AcpClientPort,
};
use crate::app::daemon_client::Daemon;

/// What every input task of a session shares.
#[derive(Clone)]
pub(super) struct InputContext {
    pub(super) daemon: Arc<Daemon>,
    pub(super) session: SessionId,
    pub(super) acp_id: AcpSessionId,
    pub(super) port: Arc<dyn AcpClientPort>,
    pub(super) features: HostFeatures,
    /// Numbers the placeholder cards of calls the host never saw, across
    /// this process's sessions.
    pub(super) placeholders: Arc<AtomicU64>,
    /// The session's input tasks, each of which may have a request open on
    /// the host.
    pub(super) asks: Asks,
    pub(super) cancels: TurnCancels,
}

/// Counts a session's input tasks until each is gone. A task that is
/// aborted drops its host request, which withdraws the request from the
/// host with `$/cancel_request` as it drops, so once none is left, none of
/// the session's requests is open on the host.
#[derive(Clone, Default)]
pub(super) struct Asks(Arc<watch::Sender<usize>>);

impl Asks {
    fn spawn(&self, ask: impl Future<Output = ()> + Send + 'static) -> JoinHandle<()> {
        self.0.send_modify(|tasks| *tasks += 1);
        // Moved into the task, so it drops with the task's future, even one
        // aborted before it first ran.
        let counted = Counted(Arc::clone(&self.0));
        tokio::spawn(async move {
            let _counted = counted;
            ask.await;
        })
    }

    /// Waits until every input task is gone: answered, or aborted, as when
    /// the session's pump stops.
    pub(super) async fn withdrawn(&self) {
        // The sender lives as long as `self`.
        let _ = self.0.subscribe().wait_for(|tasks| *tasks == 0).await;
    }
}

/// One input task, counted in its session's [`Asks`] while it lives.
struct Counted(Arc<watch::Sender<usize>>);

impl Drop for Counted {
    fn drop(&mut self) {
        self.0.send_modify(|tasks| *tasks -= 1);
    }
}

/// Counts the host's `session/cancel`s of one session. A cancel withdraws
/// the turn's open requests, so an answer the host gives after one is not
/// sent: it would race the cancel, and could land first. ACP v2 hosts
/// answer `cancelled` to the prompts a cancel leaves open, which would
/// otherwise reject the call before the cancel stops it.
#[derive(Clone, Default)]
pub(super) struct TurnCancels(Arc<AtomicU64>);

impl TurnCancels {
    pub(super) fn cancel(&self) {
        self.0.fetch_add(1, Ordering::AcqRel);
    }

    /// The point a request was opened at, to tell later cancels by.
    fn mark(&self) -> CancelMark {
        CancelMark(self.0.load(Ordering::Acquire))
    }

    /// Whether the host cancelled since `mark`.
    fn cancelled_since(&self, mark: CancelMark) -> bool {
        self.0.load(Ordering::Acquire) != mark.0
    }
}

/// A point in a session's [`TurnCancels`].
#[derive(Clone, Copy)]
struct CancelMark(u64);

/// The input requests one session has open on the host.
#[derive(Default)]
pub(super) struct Inputs {
    open: HashMap<InputRequestId, JoinHandle<()>>,
}

impl Inputs {
    /// Puts `request` to the host, unless it is already open: an attach
    /// lists the open requests, and its replay may repeat them.
    pub(super) fn open(&mut self, request: InputRequest, context: &InputContext) {
        if self
            .open
            .get(&request.id)
            .is_some_and(|task| !task.is_finished())
        {
            return;
        }
        let id = request.id;
        // Marked here, not in the task, which first runs later: a cancel
        // that comes in between still withdraws the request.
        let asked = context.cancels.mark();
        let task = context.asks.spawn(ask(request, context.clone(), asked));
        self.open.insert(id, task);
    }

    /// Withdraws every open request but those of `requests`.
    pub(super) fn retain(&mut self, requests: &[InputRequest]) {
        self.open.retain(|id, task| {
            let open = requests.iter().any(|request| request.id == *id);
            if !open {
                task.abort();
            }
            open
        });
    }

    /// Withdraws request `id` from the host: answered, here or elsewhere,
    /// withdrawn, or timed out.
    pub(super) fn resolve(&mut self, id: InputRequestId) {
        if let Some(task) = self.open.remove(&id) {
            task.abort();
        }
    }

    /// Withdraws every request, as when the attachment ends.
    pub(super) fn abort_all(&mut self) {
        for (_, task) in self.open.drain() {
            task.abort();
        }
    }
}

impl Drop for Inputs {
    fn drop(&mut self) {
        self.abort_all();
    }
}

/// Puts `request`, opened at `asked`, to the host and sends its answer.
async fn ask(request: InputRequest, context: InputContext, asked: CancelMark) {
    let mut shown = match &request.ask {
        Ask::PlanApproval(ask) => Some(ShownPlan::new(
            context.port.as_ref(),
            &context.acp_id,
            &ask.plan,
        )),
        _ => None,
    };
    let answer = match host_answer(&request, &context).await {
        Ok(Some(answer)) => answer,
        // The host cannot answer, or cancelled: another client may answer,
        // or the turn's cancel withdraws the request.
        Ok(None) => return,
        Err(error) => {
            tracing::warn!(%error, "could not ask the ACP host for input");
            return;
        }
    };
    if request.asker == InputAsker::Turn && context.cancels.cancelled_since(asked) {
        return;
    }
    let retry = matches!(answer, InputAnswer::Answers { .. });
    if let Some(shown) = &mut shown {
        shown.approved = matches!(answer, InputAnswer::ApprovePlan { .. });
    }
    let sent = send(&context, request.id, answer).await;
    if let (Some(shown), false) = (&mut shown, matches!(sent, Ok(Sent::Taken))) {
        shown.approved = false;
    }
    match sent {
        // An answer the daemon finds invalid, such as a choice the question
        // does not offer, declines instead so the tool is not left waiting.
        Err(Unsent::Failed(error))
            if retry && error.error_code() == Some(ErrorCode::InvalidParams) =>
        {
            if let Err(unsent) = send(&context, request.id, InputAnswer::Decline).await {
                tracing::warn!(?unsent, "could not decline an input request");
            }
        }
        Ok(_) => {}
        Err(unsent) => tracing::warn!(?unsent, "could not answer an input request"),
    }
}

/// What the host answered, or `None` when it cannot answer or cancelled
/// the prompt.
async fn host_answer(
    request: &InputRequest,
    context: &InputContext,
) -> Result<Option<InputAnswer>, AcpError> {
    let InputContext {
        port,
        features,
        placeholders,
        ..
    } = context;
    // A subagent's question goes to the child session the host was told
    // of; it is still answered on this session.
    let child = request
        .subagent
        .as_ref()
        .and_then(|child| port.child_session(&context.acp_id, child));
    let acp_id = child.as_ref().unwrap_or(&context.acp_id);
    match &request.ask {
        Ask::Approval(ask) => {
            let card = Card::of(request.tool_call.as_ref(), placeholders);
            let prompt = permission::permission_request(acp_id, ask, &card);
            let response = port.request_permission(prompt).await?;
            Ok(permission::approval_answer(&response.outcome))
        }
        Ask::PlanApproval(ask) => {
            let card = Card::of(request.tool_call.as_ref(), placeholders);
            let prompt = permission::plan_approval_request(acp_id, ask, &card);
            let response = port.request_permission(prompt).await?;
            Ok(permission::plan_answer(&response.outcome))
        }
        Ask::Question(ask) => {
            let Forms::Available(dialect) = features.forms else {
                return Ok(None);
            };
            // A person may take longer to fill a form than the request's
            // timeout allows; holding it waits for them.
            if request.timeout.is_some() {
                if let Err(unsent) = hold(context, request.id).await {
                    tracing::debug!(?unsent, "could not hold an input request");
                }
            }
            let form =
                elicitation::elicitation_request(ask, acp_id, request.tool_call.as_ref(), dialect);
            let response = port.create_elicitation(form).await?;
            Ok(Some(elicitation::host_answer(ask, response, dialect)))
        }
        // `Unknown`, or an ask a newer daemon sends: the host cannot answer
        // it, and another client may.
        _ => Ok(None),
    }
}

/// A plan shown to the host while its approval is asked. Dropped without
/// this host's approval on its way to the daemon, it is withdrawn: the host
/// kept planning, the request failed or a cancel withdrew it, or another
/// client resolved it first, when this host cannot tell whether it
/// approved. An approval counts once sent, since the resolution it causes
/// aborts the task before the send returns, unless the daemon answers that
/// the request was already resolved.
struct ShownPlan<'a> {
    port: &'a dyn AcpClientPort,
    session: &'a AcpSessionId,
    approved: bool,
}

impl<'a> ShownPlan<'a> {
    fn new(port: &'a dyn AcpClientPort, session: &'a AcpSessionId, plan: &str) -> Self {
        port.plan_proposed(session, plan);
        Self {
            port,
            session,
            approved: false,
        }
    }
}

impl Drop for ShownPlan<'_> {
    fn drop(&mut self) {
        if !self.approved {
            self.port.plan_withdrawn(self.session);
        }
    }
}

/// Why an answer or hold did not reach the daemon.
#[derive(Debug)]
enum Unsent {
    /// The connection the request came over is gone; a new daemon would
    /// not have it.
    Disconnected,
    /// The daemon refused it, or the connection failed under it.
    Failed(ClientError),
}

/// What became of an answer the daemon received.
enum Sent {
    /// It resolved the request.
    Taken,
    /// The request was already resolved elsewhere: the first answer wins.
    Resolved,
}

/// Answers request `id`. A request already resolved elsewhere is not an
/// error.
async fn send(
    context: &InputContext,
    id: InputRequestId,
    answer: InputAnswer,
) -> Result<Sent, Unsent> {
    let params = SessionAnswerParams {
        session: context.session.clone(),
        request: id,
        answer,
    };
    let link = context.daemon.current().await.ok_or(Unsent::Disconnected)?;
    match link.request::<SessionAnswer>(&params).await {
        Ok(_) => Ok(Sent::Taken),
        Err(error) if error.error_code() == Some(ErrorCode::InputNotOpen) => Ok(Sent::Resolved),
        Err(error) => Err(Unsent::Failed(error)),
    }
}

async fn hold(context: &InputContext, id: InputRequestId) -> Result<(), Unsent> {
    let params = SessionHoldParams {
        session: context.session.clone(),
        request: id,
    };
    let link = context.daemon.current().await.ok_or(Unsent::Disconnected)?;
    link.request::<SessionHold>(&params)
        .await
        .map(drop)
        .map_err(Unsent::Failed)
}