rho-coding-agent 3.10.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
//! What the agent of a run asks the person who attends it (`person.rs`):
//! put to them without holding up the turn's other messages, and answered
//! to the agent once they settle. A run nobody attends, or one being
//! cancelled, asks nobody: its policy's answer, or `cancelled`, goes back.

use std::{collections::HashSet, future::Future, pin::Pin, sync::Mutex};

use agent_client_protocol::{
    v1::schema::{
        CreateElicitationResponse, RequestPermissionOutcome, RequestPermissionRequest,
        RequestPermissionResponse, ToolCallId,
    },
    Error, Responder,
};
use rho_tools::cancellation::RunCancellation;
use serde_json::Value;

use super::{
    elicitation::AgentForm,
    permission::{choose_option, is_allowed, Asking, PermissionDecision},
    person::{Person, PersonAnswer, PersonAsk},
    policy::AcpAgentPolicy,
};

/// The plan of a plan exit whose input carries none, as Claude's may not:
/// what the agent showed before it holds it.
const PLAN_SHOWN_BEFORE: &str =
    "The agent asks to leave plan mode and carry out the plan it drafted above.";

/// Who a session's asks go to while one message is dispatched.
#[derive(Clone, Copy)]
pub(super) struct Asker<'a> {
    pub(super) person: Option<&'a Person>,
    pub(super) cancellation: &'a RunCancellation,
    /// The turn is being cancelled: every ask is answered `cancelled`.
    pub(super) cancelled_by_us: bool,
}

/// An [`Asker`] with a person to ask.
pub(super) struct Attended<'a> {
    person: &'a Person,
    cancellation: &'a RunCancellation,
}

/// An ask put to the person, settled once they answer, the run stops, or
/// the ask is withdrawn.
pub(super) type PendingAsk<'a> = Pin<Box<dyn Future<Output = SettledAsk<'a>> + Send + 'a>>;

/// An ask the person settled, with the request it answers.
pub(super) struct SettledAsk<'a> {
    person: &'a Person,
    reply: AskReply,
    /// `None` when nobody answers any more.
    answer: Option<PersonAnswer>,
}

enum AskReply {
    Permission {
        responder: Responder<RequestPermissionResponse>,
        request: Box<RequestPermissionRequest>,
        asking: Asking,
    },
    Form {
        responder: Responder<CreateElicitationResponse>,
        form: AgentForm,
    },
}

impl<'a> Asker<'a> {
    /// The person to ask; `None` when nobody attends the run, or it is
    /// being cancelled.
    pub(super) fn attended(self) -> Option<Attended<'a>> {
        match (self.person, self.cancelled_by_us) {
            (Some(person), false) => Some(Attended {
                person,
                cancellation: self.cancellation,
            }),
            (Some(_), true) | (None, _) => None,
        }
    }
}

impl<'a> Attended<'a> {
    /// Puts `request` to the person, as `asking` says.
    pub(super) fn permission(
        self,
        request: RequestPermissionRequest,
        responder: Responder<RequestPermissionResponse>,
        asking: Asking,
    ) -> PendingAsk<'a> {
        let ask = person_ask(&request, asking);
        let reply = AskReply::Permission {
            responder,
            request: Box::new(request),
            asking,
        };
        self.put(ask, reply)
    }

    /// Puts the agent's `form`, which the person sees as `ask`, to them.
    pub(super) fn form(
        self,
        form: AgentForm,
        ask: PersonAsk,
        responder: Responder<CreateElicitationResponse>,
    ) -> PendingAsk<'a> {
        self.put(ask, AskReply::Form { responder, form })
    }

    fn put(self, ask: PersonAsk, reply: AskReply) -> PendingAsk<'a> {
        let Self {
            person,
            cancellation,
        } = self;
        let answer = person.ask(ask);
        Box::pin(async move {
            let answer = tokio::select! {
                biased;
                // A stopped run takes no answer; the agent hears `cancelled`.
                _ = cancellation.cancelled() => None,
                answer = answer => answer,
            };
            SettledAsk {
                person,
                reply,
                answer,
            }
        })
    }
}

/// Answers the agent's request the person settled, noting in `rejected`
/// a tool call it may not run. A plan the agent hears approved first moves
/// `policy` to the mode it leaves plan mode for, so the agent's switch to
/// it keeps the run, and then the person hears it left.
pub(super) fn settle<P: AcpAgentPolicy>(
    settled: SettledAsk<'_>,
    policy: &Mutex<P>,
    rejected: &mut HashSet<ToolCallId>,
) -> Result<(), Error> {
    let SettledAsk {
        person,
        reply,
        answer,
    } = settled;
    let (responder, request, asking) = match reply {
        AskReply::Permission {
            responder,
            request,
            asking,
        } => (responder, request, asking),
        AskReply::Form { responder, form } => return responder.respond(form.response(answer)),
    };
    let decision = match answer {
        Some(PersonAnswer::Allow) => PermissionDecision::AllowOnce,
        Some(PersonAnswer::Deny | PersonAnswer::Form(_)) => PermissionDecision::Reject,
        None => {
            rejected.insert(request.tool_call.tool_call_id.clone());
            return responder.respond(RequestPermissionResponse::new(
                RequestPermissionOutcome::Cancelled,
            ));
        }
    };
    let mut outcome = choose_option(decision, &request.options);
    let mut left_plan = None;
    if let (Asking::PlanExit { to }, true) = (asking, is_allowed(&outcome, &request.options)) {
        match policy.lock().expect("ACP policy").leave_plan(to) {
            true => left_plan = Some(to),
            false => outcome = choose_option(PermissionDecision::Reject, &request.options),
        }
    }
    if !is_allowed(&outcome, &request.options) {
        rejected.insert(request.tool_call.tool_call_id.clone());
    }
    responder.respond(RequestPermissionResponse::new(outcome))?;
    if let Some(mode) = left_plan {
        person.left_plan(mode);
    }
    Ok(())
}

/// What the person is asked for `request`, as `asking` says.
fn person_ask(request: &RequestPermissionRequest, asking: Asking) -> PersonAsk {
    let call = &request.tool_call;
    let tool_call = call.tool_call_id.to_string();
    match asking {
        Asking::Tool => PersonAsk::Tool {
            tool_call,
            title: call.fields.title.clone(),
        },
        Asking::PlanExit { to } => PersonAsk::PlanExit {
            tool_call,
            plan: call
                .fields
                .raw_input
                .as_ref()
                .and_then(|input| input.get("plan"))
                .and_then(Value::as_str)
                .filter(|plan| !plan.trim().is_empty())
                .unwrap_or(PLAN_SHOWN_BEFORE)
                .to_owned(),
            to,
        },
    }
}