rho-coding-agent 3.13.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
//! The questions a session that reports to its starter asks (see
//! `app::starter_report`), asked without waiting and answered in a later
//! turn.
//!
//! Such a session works on its own, its starter, or the session its
//! question was passed up to, answering when it can: nothing below the top
//! of a tree holds a turn open waiting on a person. So its `questionnaire`
//! call hands the form to its host ([`SelfQuestions::ask`]) and returns at
//! once, and its turn ends. The host opens the question as the session's
//! own request, which outlives the turn, and saves it with the session's
//! job, so a restart keeps it (see `daemon_host::sessions::self_questions`).
//! The answer arrives in the session's [`AnswerInbox`], whose answers a
//! turn boundary delivers as a background result: the host wakes the idle
//! session for it, as for a finished process.
//!
//! An answer stays saved until a turn took it ([`Receipt`]), so a restart
//! before then delivers it again.

use std::{
    future::Future,
    sync::{Arc, Mutex, MutexGuard, PoisonError},
};

use serde::{Deserialize, Serialize};
use tokio::sync::{mpsc, Notify};

use super::peer_sessions::Receipt;

/// Names one question a session asked of itself, across daemons.
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(transparent)]
pub(crate) struct QuestionId(String);

impl QuestionId {
    fn generate() -> Self {
        Self(uuid::Uuid::new_v4().to_string())
    }
}

/// A form a session asks: the `questionnaire` call's arguments, which open
/// it again after a restart, the request they make, and what it asks in a
/// line. Parsed once, where the call comes in.
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct Form {
    pub(crate) arguments: serde_json::Value,
    pub(crate) request: rho_sdk::HostInputRequest,
    pub(crate) ask: String,
}

/// A question the session asked, which its host opens as a request.
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct Asked {
    pub(crate) id: QuestionId,
    pub(crate) form: Form,
}

/// Where a session that reports to its starter asks, and its answers
/// arrive. Cheap to clone; clones share the queue and the inbox.
#[derive(Clone)]
pub(crate) struct SelfQuestions {
    asks: mpsc::UnboundedSender<Asked>,
    /// The queue's far end, until the host takes it.
    asked: Arc<Mutex<Option<mpsc::UnboundedReceiver<Asked>>>>,
    answers: AnswerInbox,
}

impl SelfQuestions {
    pub(crate) fn new() -> Self {
        let (asks, asked) = mpsc::unbounded_channel();
        Self {
            asks,
            asked: Arc::new(Mutex::new(Some(asked))),
            answers: AnswerInbox::default(),
        }
    }

    /// The queue the session's questions arrive on, for its host to take
    /// once; `None` after.
    pub(crate) fn take_asked(&self) -> Option<mpsc::UnboundedReceiver<Asked>> {
        self.asked
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .take()
    }

    /// Asks the session's host `form`; its answer arrives in
    /// [`Self::answers`]. `None` once the host stopped taking questions.
    /// The question counts as open from before its host can see it, so the
    /// session never settles as if nothing could wake it, and an answer
    /// never comes before its question counts.
    pub(crate) fn ask(&self, form: Form) -> Option<QuestionId> {
        let id = QuestionId::generate();
        self.answers.opened();
        let asked = Asked {
            id: id.clone(),
            form,
        };
        if self.asks.send(asked).is_err() {
            self.answers.state().open -= 1;
            return None;
        }
        Some(id)
    }

    pub(crate) fn answers(&self) -> &AnswerInbox {
        &self.answers
    }
}

impl std::fmt::Debug for SelfQuestions {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter.write_str("SelfQuestions")
    }
}

/// The answers to a session's own questions, until a turn takes them.
/// Cheap to clone; clones share the answers.
#[derive(Clone, Default)]
pub(crate) struct AnswerInbox {
    shared: Arc<Shared>,
}

#[derive(Default)]
struct Shared {
    state: Mutex<State>,
    /// Told when an answer arrives or is put back.
    arrived: Arc<Notify>,
}

#[derive(Default)]
struct State {
    /// Each answer waiting, with what runs once it is delivered.
    answers: Vec<(Answer, Receipt)>,
    /// How many questions are open, their answers still to come.
    open: usize,
}

/// One answer, as the model reads it.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct Answer {
    /// The question's title.
    pub(crate) title: String,
    /// The answer, as the `questionnaire` tool reads one back.
    pub(crate) content: String,
}

impl AnswerInbox {
    fn state(&self) -> MutexGuard<'_, State> {
        // Each change is one push, take, or count.
        self.shared
            .state
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
    }

    /// A question opened, whose answer is to come.
    pub(crate) fn opened(&self) {
        self.state().open += 1;
    }

    /// An open question was answered with `answer`; `receipt` runs once a
    /// turn took it.
    pub(crate) fn answered(&self, answer: Answer, receipt: Receipt) {
        {
            let mut state = self.state();
            state.open = state.open.saturating_sub(1);
            state.answers.push((answer, receipt));
        }
        self.shared.arrived.notify_waiters();
    }

    /// An answer a turn has yet to take, as a restart found it saved;
    /// `receipt` runs once a turn took it.
    pub(crate) fn restore_answer(&self, answer: Answer, receipt: Receipt) {
        self.state().open += 1;
        self.answered(answer, receipt);
    }

    /// Whether an answer waits.
    pub(crate) fn has_answers(&self) -> bool {
        !self.state().answers.is_empty()
    }

    /// Whether a question is open, its answer still to come.
    pub(crate) fn expecting(&self) -> bool {
        self.state().open > 0
    }

    /// Completes when an answer arrives or is put back. Subscribe before
    /// checking [`Self::has_answers`], so an answer in between is not
    /// missed.
    pub(crate) fn arrived_owned(&self) -> impl Future<Output = ()> + Send + 'static {
        Arc::clone(&self.shared.arrived).notified_owned()
    }

    /// Takes every answer that waits, oldest first.
    pub(crate) fn take(&self) -> AnswerBatch {
        AnswerBatch(std::mem::take(&mut self.state().answers))
    }

    /// Puts back, ahead of the rest, answers a turn took and did not
    /// deliver.
    pub(crate) fn restore(&self, batch: &mut AnswerBatch) {
        if batch.is_empty() {
            return;
        }
        self.state().answers.splice(0..0, batch.0.drain(..));
        self.shared.arrived.notify_waiters();
    }
}

/// The answers one turn boundary took, oldest first, each with what runs
/// once it is delivered.
#[derive(Default)]
pub(crate) struct AnswerBatch(Vec<(Answer, Receipt)>);

impl AnswerBatch {
    pub(crate) fn is_empty(&self) -> bool {
        self.0.is_empty()
    }

    /// The run applied the batch: its answers are delivered.
    pub(crate) fn commit(&mut self) {
        for (_, receipt) in std::mem::take(&mut self.0) {
            receipt.run();
        }
    }

    /// What the model reads of the answers.
    pub(crate) fn prompt(&self) -> String {
        self.answers()
            .map(|Answer { title, content }| {
                format!("The answer to the question you asked, \"{title}\":\n\n{content}")
            })
            .collect::<Vec<_>>()
            .join("\n\n")
    }

    /// The answers, oldest first.
    pub(crate) fn answers(&self) -> impl Iterator<Item = &Answer> {
        self.0.iter().map(|(answer, _)| answer)
    }
}

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