rho-coding-agent 3.12.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
//! Takes the questions a session that reports to its starter asks without
//! waiting (see `app::self_questions`), and gives it their answers.
//!
//! The session's `questionnaire` call queues its form and returns, so the
//! session, not a turn, owns the question. One watcher per loaded session,
//! started as the session is added, saves each question on the session's
//! job and opens it as the session's own input request
//! ([`super::inputs::Asker::Session`]). Its starter is told of it and holds
//! it, as of any question a session it started asks (see
//! `LoadedSession::change_inputs`), and it moves on from there as a held
//! question does (see `held_questions`). The answer goes to the session's
//! answer inbox, which wakes the idle session for a turn that takes it, and
//! is saved on the job until that turn took it.
//!
//! Who holds each question is saved as it is given one, explicitly: as
//! its starter is told, or as a holder passes it on. A holder that unloads
//! gives its questions to the person in memory only, so a restart, which
//! unloads every holder, keeps who held each. As the session loads again,
//! its saved questions count as open, and each answer no turn took waits
//! for a turn, before anything reads whether it settled; then each opens
//! again, under the holder it had if that holder is loaded and may act on
//! sessions, else the person's.

use std::{
    sync::{Arc, Weak},
    time::SystemTime,
};

use rho_protocol as wire;
use rho_sdk::{hooks::HookDispatcher, CancellationToken, HostInputId, HostInputRefusal};
use tokio::sync::mpsc;

use super::{
    super::jobs::{HeldBy, QuestionState, SavedQuestion},
    held_questions::Kept,
    peer_wake::ask_of,
    LoadedSession, Sessions,
};
use crate::{
    app::{
        peer_sessions::{PassedUp, Receipt},
        self_questions::{Answer, AnswerInbox, Asked, Form, QuestionId, SelfQuestions},
        session_runtime::{SessionRuntime, TurnControl},
    },
    tools::questionnaire_tool::{answer_content, form},
};

/// A session's side of its watcher.
pub(super) struct OwnQuestions {
    questions: SelfQuestions,
    /// Tells the session's hooks a question waits (#1721).
    hooks: HookDispatcher,
    /// Cancelled when the session is dropped.
    dropped: CancellationToken,
}

impl OwnQuestions {
    /// The questions the session `runtime` runs asks without waiting, when
    /// it reports to its starter.
    pub(super) fn of(runtime: &SessionRuntime) -> Option<Self> {
        Some(Self {
            questions: runtime.self_questions()?.clone(),
            hooks: runtime.hooks(),
            dropped: CancellationToken::new(),
        })
    }

    /// Whether an answer waits for a turn or is still to come: the session
    /// stays loaded meanwhile, so its open questions stay answerable.
    pub(super) fn outstanding(&self) -> bool {
        let answers = self.questions.answers();
        answers.expecting() || answers.has_answers()
    }
}

impl Drop for OwnQuestions {
    fn drop(&mut self) {
        self.dropped.cancel();
    }
}

/// The questions a session's job kept open across a restart, counted open
/// and still to be opened as requests (see [`Sessions::watch_self_questions`]).
#[derive(Default)]
pub(super) struct Reopening(Vec<(QuestionId, Form, Option<HeldBy>)>);

/// The session's questions open in this daemon: the id their requests'
/// answers name, the question, and what it asks.
#[derive(Default)]
struct Opened(Vec<(HostInputId, QuestionId, String)>);

impl Sessions {
    /// Takes back the questions `session` asked without waiting that its
    /// job keeps: hands it each answer no turn took, and counts the rest
    /// open, so the session does not settle as if nothing could wake it.
    /// Call as the session is added, before anything reads whether it
    /// settled; [`Self::watch_self_questions`] opens the rest.
    pub(super) fn reopen_self_questions(&self, session: &LoadedSession) -> Reopening {
        let Some(own) = &session.own_questions else {
            return Reopening::default();
        };
        let answers = own.questions.answers();
        let mut reopening = Reopening::default();
        for SavedQuestion {
            id,
            arguments,
            ask,
            state,
        } in self.jobs.questions_of(&session.job)
        {
            match state {
                QuestionState::Answered { answer } => {
                    let receipt = closes(session, id);
                    let answer = Answer {
                        title: ask,
                        content: answer,
                    };
                    answers.restore_answer(answer, receipt);
                }
                QuestionState::Open { held_by } => match form(arguments) {
                    Ok(form) => {
                        answers.opened();
                        reopening.0.push((id, form, held_by));
                    }
                    // Checked as it was asked; a later daemon may read
                    // forms differently. Nothing could answer it now.
                    Err(_) => {
                        tracing::warn!(session = %session.id, "dropped a saved question that no longer reads as a form");
                        self.jobs.close_question(&session.job, &id);
                    }
                },
            }
        }
        reopening
    }

    /// Opens `reopening`, the questions [`Self::reopen_self_questions`]
    /// took back, each under the holder it had, and starts the watcher that
    /// takes `session`'s questions from now on. Call once, as the session
    /// is added, holding no lock: it reads the loaded sessions.
    pub(super) fn watch_self_questions(&self, session: &Arc<LoadedSession>, reopening: Reopening) {
        let Some(own) = &session.own_questions else {
            return;
        };
        let Some(asked) = own.questions.take_asked() else {
            return;
        };
        // Where the session's input requests send the answers to its
        // questions, as a turn's go to the turn.
        let (control, answers) = mpsc::unbounded_channel();
        let mut opened = Opened::default();
        for (id, form, held_by) in reopening.0 {
            let request = open(session, &control, &mut opened, id, &form);
            self.restore_holder(session, request, held_by);
        }
        let watcher = take_questions(
            Arc::downgrade(session),
            Questions {
                asked,
                answers,
                control,
                opened,
            },
            own.questions.answers().clone(),
            own.hooks.clone(),
        );
        let dropped = own.dropped.clone();
        tokio::spawn(async move {
            tokio::select! {
                () = dropped.cancelled() => {}
                () = watcher => {}
            }
        });
    }

    /// Gives question `request` of `asking`, opened again, back to the
    /// session that held it, `held_by`, when that session is loaded, takes
    /// notices, and may act on sessions; the person holds it otherwise.
    /// Tells the holder of it, as it was told before the restart.
    fn restore_holder(
        &self,
        asking: &Arc<LoadedSession>,
        request: wire::InputRequestId,
        held_by: Option<HeldBy>,
    ) {
        let Some(HeldBy { session, passed_by }) = held_by else {
            return;
        };
        let holder = self.loaded().get(&session).cloned();
        let Some((holder, inbox)) = holder
            .filter(|holder| self.jobs.may_act_on_sessions(&holder.job).is_ok())
            .and_then(|holder| {
                let inbox = holder.peer_wake.inbox()?.clone();
                Some((holder, inbox))
            })
        else {
            return;
        };
        let to = holder.peer_wake.owner();
        let from = asking.feed.holder_of(request);
        if from.as_ref() == Some(to) {
            return;
        }
        // The job already saves this holder.
        let moved = asking.give_held(&[request], from.as_ref(), Some(to), Kept::InMemory);
        for (request, question) in &moved {
            let passed_up = passed_by.as_ref().map(|by| PassedUp {
                by: by.to_string(),
                note: None,
            });
            inbox.tell_held(
                asking.id.as_str(),
                asking.feed.name(),
                *request,
                ask_of(question),
                passed_up,
            );
        }
        holder
            .peer_wake
            .hold_questions(asking, moved.into_iter().map(|(request, _)| request));
    }
}

/// Opens `form` as question `id` of `session`, noting it in `opened`; its
/// answers go to `control`. Returns the request's id.
fn open(
    session: &Arc<LoadedSession>,
    control: &mpsc::UnboundedSender<TurnControl>,
    opened: &mut Opened,
    id: QuestionId,
    form: &Form,
) -> wire::InputRequestId {
    opened
        .0
        .push((form.request.id().clone(), id.clone(), form.ask.clone()));
    session.change_inputs(|inputs| {
        inputs.open_own_question(id, control, &form.request, SystemTime::now())
    })
}

/// What runs once a turn of `session` took the answer to its question
/// `id`: the job no longer keeps it.
fn closes(session: &LoadedSession, id: QuestionId) -> Receipt {
    let jobs = Arc::downgrade(&session.jobs);
    let job = session.job.clone();
    Receipt::new(move || {
        if let Some(jobs) = jobs.upgrade() {
            jobs.close_question(&job, &id);
        }
    })
}

/// A watcher's channels: the questions the session asks, and the answers
/// its requests send, with the end those requests send them on.
struct Questions {
    asked: mpsc::UnboundedReceiver<Asked>,
    answers: mpsc::UnboundedReceiver<TurnControl>,
    control: mpsc::UnboundedSender<TurnControl>,
    opened: Opened,
}

/// Saves and opens each question the session asks, and hands each answer
/// to `inbox`, the session's, until the session is gone.
async fn take_questions(
    session: Weak<LoadedSession>,
    questions: Questions,
    inbox: AnswerInbox,
    hooks: HookDispatcher,
) {
    let Questions {
        mut asked,
        mut answers,
        control,
        mut opened,
    } = questions;
    loop {
        tokio::select! {
            asked = asked.recv() => {
                let (Some(Asked { id, form }), Some(session)) = (asked, session.upgrade()) else {
                    return;
                };
                session.jobs.ask_question(&session.job, SavedQuestion {
                    id: id.clone(),
                    arguments: form.arguments.clone(),
                    ask: form.ask.clone(),
                    state: QuestionState::Open { held_by: None },
                });
                open(&session, &control, &mut opened, id, &form);
                hooks.question_requested(&session.id, &form.request);
            }
            answer = answers.recv() => {
                let (Some(answer), Some(session)) = (answer, session.upgrade()) else {
                    return;
                };
                answered(&session, &inbox, &mut opened, answer);
            }
        }
    }
}

/// Hands `answer`, if it answers one of `opened`, to `inbox`, `session`'s:
/// saved on its job until a turn took it.
fn answered(
    session: &LoadedSession,
    inbox: &AnswerInbox,
    opened: &mut Opened,
    answer: TurnControl,
) {
    let (id, answer) = match answer {
        TurnControl::AnswerQuestion { id, answer } => (id, answer),
        // Only questions are opened on this channel.
        TurnControl::RespondApproval { .. }
        | TurnControl::AnswerPlan { .. }
        | TurnControl::AnswerSecret { .. }
        | TurnControl::HostFailed { .. } => return,
    };
    let Some(at) = opened.0.iter().position(|(open, ..)| *open == id) else {
        return;
    };
    let (_, question, ask) = opened.0.remove(at);
    let content = match answer {
        Ok(response) => answer_content(&response),
        Err(refusal) => refused(refusal).to_owned(),
    };
    session
        .jobs
        .answer_saved_question(&session.job, &question, content.clone());
    inbox.answered(
        Answer {
            title: ask,
            content,
        },
        closes(session, question),
    );
}

/// What the model reads of a question nobody answered.
fn refused(refusal: HostInputRefusal) -> &'static str {
    match refusal {
        HostInputRefusal::Declined => {
            "The question was declined. Go on without its answer, or report what you need."
        }
        // `Dismissed`, and any refusal a newer SDK adds.
        _ => "The question was dismissed unanswered. Go on without its answer, or report what you need.",
    }
}

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