rho-coding-agent 3.10.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
//! `answer`: the caller answers a question a session asks. Approvals and
//! plan approvals are never answered here: they wait for a person, and the
//! daemon refuses them on this path whatever the caller.
//!
//! Who answers is the [`Answerer`] the check found. A calling session, as
//! the native `sessions` tool's is, answers through
//! `rho/session/answer_question`, naming itself, and the daemon alone
//! decides whether it may (#1714): it refuses a session that did not start
//! the asker, or whose grant may not act on sessions, and its refusal is
//! the call's error. An agent outside any session, as an MCP client of
//! `rho mcp serve` is, answers through `rho/session/answer_question_by_agent`
//! any session its grant may drive, which the check already held it to, as
//! it does for a prompt or a steer. The daemon checks that the answers fit
//! the questions either way.

use rho_protocol::{
    methods::{SessionAnswerQuestion, SessionAnswerQuestionByAgent},
    ClientError, ErrorCode, InputRequestId, QuestionAnswer, QuestionAsk,
    SessionAnswerQuestionByAgentParams, SessionAnswerQuestionParams, SessionId,
};

use super::{AnswerResult, Caller, ControlError, DaemonError, SessionControl};
use crate::app::question_choices::choice_value;

/// Who answers a question through the core.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(super) enum Answerer {
    /// The calling session, which the daemon holds to answering only the
    /// sessions it started.
    Session(SessionId),
    /// An agent outside any session, as an MCP client of `rho mcp serve`
    /// is: it answers any session its grant may drive.
    Outside,
}

impl Answerer {
    /// Who `caller` answers as: its session when the front end knows it,
    /// else the caller itself. A caller that declares a session depth, as
    /// a nested rho session's MCP client does when it calls `rho mcp
    /// serve`, is refused: a session answers only the sessions it started,
    /// through the `sessions` tool, which knows it. A session at depth 0,
    /// one a person opened, declares nothing, so it answers as an outside
    /// agent, as it prompts and steers through `rho mcp serve` with its
    /// own grant. The depth is the caller's word, not a sandbox
    /// (`crate::caller_context`).
    pub(super) fn of(caller: &Caller) -> Result<Self, ControlError> {
        match (&caller.session, caller.depth) {
            (Some(session), _) => Ok(Self::Session(session.clone())),
            (None, 0) => Ok(Self::Outside),
            (None, depth) => Err(ControlError::Invalid(format!(
                "`answer` from a session at depth {depth} answers only the questions of sessions it started, through the `sessions` tool's `answer`"
            ))),
        }
    }
}

/// `answer` with each answer that names a choice of `question` by its
/// label, rather than its value, naming its value, which is what the daemon
/// matches (`crate::app::question_choices`). Answers to a question the ask
/// lacks, and text that names no choice, go as they are, for the daemon to
/// check against the questions.
pub(super) fn by_choice_values(answer: QuestionAnswer, question: &QuestionAsk) -> QuestionAnswer {
    let QuestionAnswer::Answers { answers } = answer else {
        return answer;
    };
    let answers = answers
        .into_iter()
        .map(|(id, values)| {
            let values = match question.questions.iter().find(|asked| asked.id == id) {
                Some(asked) => values
                    .into_iter()
                    .map(|value| choice_value(asked, value))
                    .collect(),
                None => values,
            };
            (id, values)
        })
        .collect();
    QuestionAnswer::Answers { answers }
}

impl SessionControl {
    /// Hands `answer` to question `request` of `session`, as `by`'s. An
    /// answer that lost, to a person's or the timeout's, or to a request
    /// the turn withdrew, says the question is not open.
    pub(super) async fn answer(
        &self,
        session: SessionId,
        request: InputRequestId,
        answer: QuestionAnswer,
        by: Answerer,
    ) -> Result<AnswerResult, ControlError> {
        let answered = match by {
            Answerer::Session(by) => self
                .daemon
                .request::<SessionAnswerQuestion>(&SessionAnswerQuestionParams {
                    session: session.clone(),
                    request,
                    answer,
                    by,
                })
                .await
                .map(drop),
            Answerer::Outside => {
                self.daemon
                    .request::<SessionAnswerQuestionByAgent>(
                        &SessionAnswerQuestionByAgentParams::new(session.clone(), request, answer),
                    )
                    .await
                    .map(drop)
            }
        };
        let code = match &answered {
            Err(DaemonError::Request(ClientError::Rpc { error, .. })) => error.error_code(),
            _ => None,
        };
        match (answered, code) {
            (Ok(()), _) => Ok(AnswerResult { session }),
            (Err(_), Some(ErrorCode::InputNotOpen)) => Err(not_open(&session, request)),
            (Err(_), Some(ErrorCode::MethodNotFound)) => Err(ControlError::Invalid(
                "the rho daemon on this machine predates answering a question here; upgrade rho and restart its daemon".into(),
            )),
            (Err(error), _) => Err(error.into()),
        }
    }
}

/// The refusal of an answer to request `request` of `session`, which is not
/// open: from the daemon, or from the check, which reads the open requests
/// first and also sees an id that never opened.
pub(super) fn not_open(session: &SessionId, request: InputRequestId) -> ControlError {
    ControlError::Invalid(format!(
        "input request {request} of session {session} is not open: it was already answered, it timed out, or its turn withdrew it"
    ))
}

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