rho-coding-agent 3.7.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
//! Questionnaire expiry: the model's own answers for a form the user leaves
//! unanswered. Each question may carry an `if_unanswered` answer, in the
//! shape of its `default`, and the form a short `assumption`. A form whose
//! required questions all carry one expires after the session's
//! `[questionnaire] timeout_seconds`, and the turn carries on with those
//! answers; any other form waits for the user. The daemon runs the clock
//! (`daemon_host::sessions::inputs`).
//!
//! Names: the model says `if_unanswered` and `assumption`; the SDK and the
//! wire call them the request's timeout fallback and its reason
//! (`HostInputSource::TimeoutFallback`, `InputTimeout`); the user's setting
//! is `[questionnaire] timeout_seconds` (`QuestionnaireExpiry`). They are one
//! concept: the answers a form expires with.

use std::{collections::BTreeMap, time::Duration};

use rho_sdk::{HostInputResponse, HostQuestion};
use serde::Deserialize;
use serde_json::{json, Value};

use super::{question_id, QuestionnaireRequest, RawQuestionnaireQuestion};

/// The form-level fallback questionnaires took before `if_unanswered`:
/// answers by question id, and why.
// NEXT_MAJOR(rho questionnaire): drop the `on_timeout` argument, which only
// saved sessions and replays still send; per-question `if_unanswered` and
// the form's `assumption` replace it.
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub(super) struct LegacyOnTimeout {
    answers: BTreeMap<String, Value>,
    #[serde(default)]
    reason: Option<String>,
}

impl LegacyOnTimeout {
    /// Moves these answers onto the questions they name, as their
    /// `if_unanswered`, and returns the reason, the form's assumption.
    pub(super) fn apply(
        self,
        questions: &mut [RawQuestionnaireQuestion],
    ) -> Result<Option<String>, String> {
        for (id, answer) in self.answers {
            let question = questions
                .iter_mut()
                .enumerate()
                .find(|(index, question)| question_id(*index, question.id.as_deref()) == id)
                .map(|(_, question)| question)
                .ok_or_else(|| format!("on_timeout.answers names unknown question '{id}'"))?;
            if question.if_unanswered.is_some() {
                return Err(format!(
                    "question '{id}' has both if_unanswered and an on_timeout answer; give only if_unanswered"
                ));
            }
            question.if_unanswered = Some(answer);
        }
        Ok(self.reason)
    }
}

impl QuestionnaireRequest {
    /// The answers the form expires with: each question's `if_unanswered`.
    /// `None` unless every required question has one, and at least one
    /// question does, so the form waits for the user.
    pub fn fallback(&self) -> Option<HostInputResponse> {
        let offered = self
            .questions
            .iter()
            .any(|question| question.if_unanswered.is_some());
        let covered = self
            .questions
            .iter()
            .all(|question| !question.required || question.if_unanswered.is_some());
        (offered && covered).then(|| {
            self.questions
                .iter()
                .filter_map(|question| Some((&question.id, question.if_unanswered.clone()?)))
                .fold(HostInputResponse::new(), |response, (id, values)| {
                    response.answer(id, values)
                })
        })
    }
}

/// A normalized answer, as `normalize_answer` returns it, as answer
/// values: one for a single answer, each label of a multi_select's list.
pub(super) fn answer_values(answer: Value) -> Vec<String> {
    match answer {
        Value::String(value) => vec![value],
        Value::Array(values) => values
            .into_iter()
            .filter_map(|value| match value {
                Value::String(value) => Some(value),
                _ => None,
            })
            .collect(),
        Value::Null | Value::Bool(_) | Value::Number(_) | Value::Object(_) => Vec::new(),
    }
}

/// Fallback `answers` to `questions` as one short line, by choice label:
/// `nextest` when one question has an answer, `Runner: nextest; Suites:
/// unit, pty` when several do, and `no answers` when none does, as an SDK
/// tool may offer for an all-optional form. Stands in for the assumption a
/// model left out, and hosts show it beside the countdown.
pub fn fallback_summary(
    questions: &[HostQuestion],
    answers: &BTreeMap<String, Vec<String>>,
) -> String {
    let labels = |question: &HostQuestion, values: &[String]| {
        if values.is_empty() {
            return "none".to_owned();
        }
        values
            .iter()
            .map(|value| {
                question
                    .choices()
                    .iter()
                    .find(|choice| choice.value() == value)
                    .map_or(value.as_str(), |choice| choice.label())
            })
            .collect::<Vec<_>>()
            .join(", ")
    };
    let answered: Vec<_> = questions
        .iter()
        .filter_map(|question| Some((question, answers.get(question.id())?)))
        .collect();
    match answered.as_slice() {
        [] => "no answers".to_owned(),
        [(question, values)] => labels(question, values),
        _ => answered
            .iter()
            .map(|(question, values)| {
                let name = question.header().unwrap_or(question.id());
                format!("{name}: {}", labels(question, values))
            })
            .collect::<Vec<_>>()
            .join("; "),
    }
}

/// The tool description's guidance for forms that expire after `after`.
pub(super) fn description(after: Duration) -> String {
    let after = human_duration(after);
    format!(
        "Decide each time whether you could carry on without the user. If you could carry on with a sensible answer, give each question an if_unanswered and the form an assumption; the form expires after {after} and you continue with those answers. Leave them out only when you truly can't proceed without the user; the form then waits. Never give if_unanswered for approvals, permissions, destructive actions, purchases, or other authorization."
    )
}

/// The schema of the form's `assumption`, for sessions whose forms expire.
pub(super) fn assumption_schema() -> Value {
    json!({
        "type": "string",
        "description": "With if_unanswered: what you're going with, in one short line the user sees while the form waits, e.g. \"carrying on with nextest; say otherwise anytime\"."
    })
}

/// The schema of a question's `if_unanswered`, for sessions whose forms
/// expire.
pub(super) fn if_unanswered_schema() -> Value {
    json!({
        "description": "Your answer if the user doesn't answer in time, shaped like an answer: a choice label, a list of labels for multi_select, true or false for confirm.",
        "oneOf": [
            { "type": "string" },
            { "type": "boolean" },
            { "type": "array", "items": { "type": "string" } }
        ]
    })
}

/// `after` in the largest whole unit that states it exactly: `5 minutes`,
/// `90 seconds`, `1 hour`.
fn human_duration(after: Duration) -> String {
    let (count, unit) = match after.as_secs() {
        seconds if seconds >= 3600 && seconds.is_multiple_of(3600) => (seconds / 3600, "hour"),
        seconds if seconds >= 60 && seconds.is_multiple_of(60) => (seconds / 60, "minute"),
        seconds => (seconds, "second"),
    };
    let plural = if count == 1 { "" } else { "s" };
    format!("{count} {unit}{plural}")
}