rho-coding-agent 3.13.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::{
        CreateElicitationRequest, CreateElicitationResponse, ElicitationAction,
        RequestPermissionOutcome, RequestPermissionRequest, RequestPermissionResponse, ToolCallId,
    },
    Error,
};
use rho_tools::cancellation::RunCancellation;
use serde_json::Value;

use super::{
    deciders::Deciders,
    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.";

/// Where the answer to one of the agent's requests goes, in v1 form: the
/// v1 client responds with it, and the v2 client responds with its v2 form.
pub(super) type Reply<T> = Box<dyn FnOnce(T) -> Result<(), Error> + Send>;

/// 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: Reply<RequestPermissionResponse>,
        request: Box<RequestPermissionRequest>,
        asking: Asking,
    },
    Form {
        responder: Reply<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: Reply<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: Reply<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,
            }
        })
    }
}

/// The agent's permission ask `request`, decided by `deciders`: put to the
/// person when they say to ask and one attends, else answered now, failing
/// closed. A tool call it may not run is noted in `rejected`.
pub(super) fn permission<'a, P: AcpAgentPolicy>(
    request: RequestPermissionRequest,
    reply: Reply<RequestPermissionResponse>,
    deciders: &Deciders<'_, P>,
    asker: Asker<'a>,
    rejected: &mut HashSet<ToolCallId>,
) -> Result<Option<PendingAsk<'a>>, Error> {
    let decision = deciders.decide(&request);
    let outcome = match (decision, asker.attended()) {
        _ if asker.cancelled_by_us => RequestPermissionOutcome::Cancelled,
        (PermissionDecision::AskPerson(asking), Some(attended)) => {
            return Ok(Some(attended.permission(request, reply, asking)));
        }
        // Nobody attends to ask: it fails closed.
        (
            PermissionDecision::AskPerson(_)
            | PermissionDecision::AllowOnce
            | PermissionDecision::Reject,
            _,
        ) => choose_option(decision, &request.options),
    };
    if !is_allowed(&outcome, &request.options) {
        rejected.insert(request.tool_call.tool_call_id.clone());
    }
    reply(RequestPermissionResponse::new(outcome))?;
    Ok(None)
}

/// The agent's form `request`: put to the person, or declined when Rho
/// cannot show it. Only a run a person attends advertised forms; any other
/// is cancelled.
pub(super) fn form<'a>(
    request: &CreateElicitationRequest,
    reply: Reply<CreateElicitationResponse>,
    asker: Asker<'a>,
) -> Result<Option<PendingAsk<'a>>, Error> {
    let Some(attended) = asker.attended() else {
        reply(CreateElicitationResponse::new(ElicitationAction::Cancel))?;
        return Ok(None);
    };
    match AgentForm::of(request) {
        Ok((form, ask)) => Ok(Some(attended.form(form, ask, reply))),
        Err(declined) => {
            reply(declined)?;
            Ok(None)
        }
    }
}

/// 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(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(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(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,
        },
    }
}