rho-coding-agent 3.10.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
//! What the agent of a session a person attends asks them during a turn
//! ([`crate::acp_runtime::person`]), as the session's input requests: a
//! tool approval, a plan approval, or questions, which any client answers
//! with `rho/session/answer` as it would Rho's own. The turn's end
//! withdraws whatever is still open.
//!
//! The tools of rho's the turn serves the agent (see `acp_tools.rs`) ask
//! through the same requests, in the same id space: an approval a call
//! needs, and a question a tool asks, whoever opened the session, as a Rho
//! session's do. A call that ends withdraws what it still asks.
//!
//! The agent is only ever answered `allow_once`, so nothing it would keep
//! (Claude writes `allow_always` into its settings) outlives the session.
//! An approval for the session is kept here instead, by the tool call's
//! title, for the session's later turns while the daemon has it loaded; a
//! tool call the agent gave no title is asked about every time.

use std::{collections::HashSet, sync::Arc, time::SystemTime};

use rho_protocol as wire;
use rho_sdk::{ApprovalDecision, HostInputId, HostInputRefusal, HostInputResponse, ToolCallId};
use tokio::sync::{mpsc, oneshot};

use super::{
    acp_tools::{ServedApproval, ServedAsk, ServedQuestion},
    LoadedSession,
};
use crate::{
    acp_runtime::person::{Asked, PersonAnswer, PersonAsk},
    app::session_runtime::{
        ApprovalId, PlanApprovalId, PlanApprovalRequest, SessionEvent, TurnControl,
    },
    permission::PermissionMode,
    tools::plan_exit::PlanExitDecision,
};

/// The tool calls a person allowed for the session, by title.
#[derive(Default)]
pub(super) struct AllowedForSession(HashSet<String>);

/// What an approval shows of a tool call the agent gave no title.
const UNTITLED: &str = "a tool call";

/// One turn's asks: what is open, and the answers on their way back.
pub(super) struct TurnAsks {
    /// Names the agent's runtime to whoever answers.
    runtime: String,
    control: mpsc::UnboundedSender<TurnControl>,
    answers: mpsc::UnboundedReceiver<TurnControl>,
    open: OpenAsks,
    /// Counts the agent's approvals and the served tools' alike, so their
    /// ids never collide.
    approvals: u64,
    plans: u64,
}

/// The open asks, by kind and by the id their request carries.
#[derive(Default)]
struct OpenAsks {
    approvals: Vec<(ApprovalId, ApprovalWaiter)>,
    /// The agent's alone: a served tool never asks to leave plan mode.
    plans: Vec<(PlanApprovalId, oneshot::Sender<PersonAnswer>)>,
    questions: Vec<(HostInputId, QuestionWaiter)>,
}

enum ApprovalWaiter {
    /// The agent's own.
    Agent {
        reply: oneshot::Sender<PersonAnswer>,
        /// The title an approval for the session keeps: none for a tool
        /// call the agent gave no title.
        title: Option<String>,
    },
    /// A served call's.
    Served(Box<ServedApproval>),
}

enum QuestionWaiter {
    /// The agent's own form.
    Agent(oneshot::Sender<PersonAnswer>),
    /// A served call's.
    Served(Box<ServedQuestion>),
}

/// A person's answer to an open ask, by the id its request carries: a
/// client's [`TurnControl`] as a turn of an agent's session reads it.
enum Answer {
    Approval(ApprovalId, ApprovalDecision),
    Plan(PlanApprovalId, PlanExitDecision),
    Question(HostInputId, Result<HostInputResponse, HostInputRefusal>),
}

impl Answer {
    /// What `control` answers; none for what only Rho's own loop is sent.
    fn of(control: TurnControl) -> Option<Self> {
        match control {
            TurnControl::RespondApproval { id, decision } => Some(Self::Approval(id, decision)),
            TurnControl::AnswerPlan { id, answer } => Some(Self::Plan(id, answer)),
            TurnControl::AnswerQuestion { id, answer } => Some(Self::Question(id, answer)),
            TurnControl::AnswerSecret { .. } | TurnControl::HostFailed { .. } => None,
        }
    }
}

/// Takes the waiter of `open` whose ask `id` names, if it is still open.
fn take<K: PartialEq, W>(open: &mut Vec<(K, W)>, id: &K) -> Option<W> {
    let at = open.iter().position(|(open, _)| open == id)?;
    Some(open.swap_remove(at).1)
}

impl OpenAsks {
    /// Takes out what served call `ended` still asks, and the events that
    /// withdraw it from the session's input requests. Dropping a served
    /// approval denies it, and a dropped question fails the tool's ask, as
    /// the call that asked is gone.
    fn end_call(&mut self, ended: &ToolCallId) -> Vec<SessionEvent> {
        let mut withdrawn = Vec::new();
        self.approvals.retain(|(id, waiter)| {
            let of_call = match waiter {
                ApprovalWaiter::Served(served) => served.call.as_ref() == Some(ended),
                ApprovalWaiter::Agent { .. } => false,
            };
            if of_call {
                withdrawn.push(SessionEvent::ApprovalWithdrawn { id: *id });
            }
            !of_call
        });
        self.questions.retain(|(id, waiter)| {
            let of_call = match waiter {
                QuestionWaiter::Served(served) => served.call == *ended,
                QuestionWaiter::Agent(_) => false,
            };
            if of_call {
                withdrawn.push(SessionEvent::QuestionWithdrawn { id: id.clone() });
            }
            !of_call
        });
        withdrawn
    }
}

impl TurnAsks {
    pub(super) fn new(runtime: &str) -> Self {
        let (control, answers) = mpsc::unbounded_channel();
        Self {
            runtime: runtime.to_owned(),
            control,
            answers,
            open: OpenAsks::default(),
            approvals: 0,
            plans: 0,
        }
    }

    /// The next answer a client gave.
    pub(super) async fn answer(&mut self) -> Option<TurnControl> {
        self.answers.recv().await
    }

    /// Opens `asked` as an input request of `session`, or answers it at
    /// once: a tool call the person allowed for the session runs.
    pub(super) fn put(
        &mut self,
        session: &Arc<LoadedSession>,
        asked: Asked,
        allowed: &AllowedForSession,
    ) {
        let Asked { ask, reply } = asked;
        let now = SystemTime::now();
        match ask {
            PersonAsk::Tool {
                title: Some(title), ..
            } if allowed.0.contains(&title) => {
                let _ = reply.send(PersonAnswer::Allow);
            }
            PersonAsk::Tool { tool_call, title } => {
                let id = ApprovalId::nth(self.approvals);
                self.approvals += 1;
                let ask = wire::ApprovalAsk {
                    source: wire::ApprovalSource::ExternalAgent {
                        runtime: self.runtime.clone(),
                    },
                    operation: wire::Operation::AgentTool {
                        title: title.clone().unwrap_or_else(|| UNTITLED.to_owned()),
                    },
                    reason: "the agent asks before this tool call".to_owned(),
                };
                let control = &self.control;
                session.change_inputs(|inputs| {
                    inputs.open_agent_approval(
                        control,
                        id,
                        ask,
                        wire::ToolCallId::new(&tool_call),
                        now,
                    );
                });
                self.open
                    .approvals
                    .push((id, ApprovalWaiter::Agent { reply, title }));
            }
            PersonAsk::PlanExit {
                tool_call,
                plan,
                to,
            } => {
                let id = PlanApprovalId::nth(self.plans);
                self.plans += 1;
                let Ok(call_id) = ToolCallId::from_string(tool_call) else {
                    // An agent's id Rho cannot name is no plan to approve.
                    let _ = reply.send(PersonAnswer::Deny);
                    return;
                };
                let request = PlanApprovalRequest {
                    call_id,
                    plan,
                    targets: vec![to],
                };
                self.note(
                    session,
                    &SessionEvent::PlanApprovalRequested { id, request },
                    now,
                );
                self.open.plans.push((id, reply));
            }
            PersonAsk::Form { tool_call, request } => {
                let id = request.id().clone();
                let call_id = tool_call.and_then(|id| ToolCallId::from_string(id).ok());
                let event = SessionEvent::QuestionAsked {
                    id: id.clone(),
                    call_id,
                    request,
                };
                self.note(session, &event, now);
                self.open.questions.push((id, QuestionWaiter::Agent(reply)));
            }
        }
    }

    /// Opens what `asked`, of a call of a tool the turn serves the agent,
    /// asks as an input request of `session`, or withdraws what a call that
    /// ended still asks.
    pub(super) fn put_served(&mut self, session: &Arc<LoadedSession>, asked: ServedAsk) {
        let now = SystemTime::now();
        match asked {
            ServedAsk::Approval(approval) => {
                let id = ApprovalId::nth(self.approvals);
                self.approvals += 1;
                let request = approval.request().clone();
                let call = request.tool_call_id().cloned();
                self.note(
                    session,
                    &SessionEvent::ApprovalRequested { id, request },
                    now,
                );
                let waiter = ServedApproval { call, approval };
                self.open
                    .approvals
                    .push((id, ApprovalWaiter::Served(Box::new(waiter))));
            }
            ServedAsk::Question { call, input } => {
                let id = input.request().id().clone();
                let event = SessionEvent::QuestionAsked {
                    id: id.clone(),
                    call_id: Some(call.clone()),
                    request: input.request().clone(),
                };
                self.note(session, &event, now);
                let waiter = ServedQuestion { call, input };
                self.open
                    .questions
                    .push((id, QuestionWaiter::Served(Box::new(waiter))));
            }
            ServedAsk::Ended(call) => {
                for withdrawn in self.open.end_call(&call) {
                    self.note(session, &withdrawn, now);
                }
            }
        }
    }

    fn note(&self, session: &Arc<LoadedSession>, event: &SessionEvent, now: SystemTime) {
        let control = &self.control;
        session
            .change_inputs(|inputs| inputs.note(super::inputs::Asker::Turn, control, event, now));
    }

    /// Hands the agent, or the served call that asked, the person's
    /// answer, `control`, keeping an agent's approval for the session in
    /// `allowed`. An answer to an ask no longer open goes nowhere. A plan
    /// the person approved is the caller's to tell the agent of
    /// ([`ApprovedPlan::tell`]), once the turn runs in its mode.
    #[must_use]
    pub(super) fn answered(
        &mut self,
        control: TurnControl,
        allowed: &mut AllowedForSession,
    ) -> Option<ApprovedPlan> {
        let answer = Answer::of(control)?;
        // A run that stopped asking takes no answer.
        match answer {
            Answer::Approval(id, decision) => match take(&mut self.open.approvals, &id) {
                Some(ApprovalWaiter::Agent { reply, title }) => {
                    let (answer, keep) = match decision {
                        ApprovalDecision::AllowOnce => (PersonAnswer::Allow, false),
                        ApprovalDecision::AllowForSession => (PersonAnswer::Allow, true),
                        // Deny, or a decision a newer SDK adds.
                        _ => (PersonAnswer::Deny, false),
                    };
                    if let (true, Some(title)) = (keep, title) {
                        allowed.0.insert(title);
                    }
                    let _ = reply.send(answer);
                }
                Some(ApprovalWaiter::Served(served)) => served.answer(decision),
                None => {}
            },
            // The plan's one target: the agent tells whether it left.
            Answer::Plan(id, decision) => {
                let reply = take(&mut self.open.plans, &id)?;
                match decision.approved() {
                    Some(mode) => return Some(ApprovedPlan { mode, reply }),
                    None => {
                        let _ = reply.send(PersonAnswer::Deny);
                    }
                }
            }
            Answer::Question(id, answer) => match take(&mut self.open.questions, &id) {
                Some(QuestionWaiter::Agent(reply)) => {
                    let _ = reply.send(PersonAnswer::Form(answer));
                }
                Some(QuestionWaiter::Served(served)) => served.answer(answer),
                None => {}
            },
        }
        None
    }
}

/// A plan the person approved, which the agent has yet to hear of.
pub(super) struct ApprovedPlan {
    mode: PermissionMode,
    reply: oneshot::Sender<PersonAnswer>,
}

impl ApprovedPlan {
    /// The mode the plan is carried out in.
    pub(super) fn mode(&self) -> PermissionMode {
        self.mode
    }

    /// Tells the agent: it leaves plan mode, and the person hears it did
    /// ([`crate::acp_runtime::person::Heard::LeftPlan`]).
    pub(super) fn tell(self) {
        // A run that stopped asking takes no answer.
        let _ = self.reply.send(PersonAnswer::Allow);
    }
}

#[cfg(test)]
#[path = "acp_asks_tests.rs"]
mod tests;