rho-coding-agent 3.10.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
//! How a turn shows itself to the session's clients and its job.

use std::{future::Future, sync::Arc, time::SystemTime};

use rho_protocol as wire;
use rho_sdk::RunEvent;
use tokio::sync::{mpsc, watch};

use super::{
    super::{
        super::jobs::TurnEnd,
        cost,
        inputs::{Asker, Inputs},
        options::available_auths,
        prompt_keys::PromptMessage,
        LoadedSession,
    },
    failed, spawn_title, PromptStart, UNEXPECTED_STOP,
};
use crate::{
    app::{
        session_events::FeedEvent,
        session_runtime::{
            PlanReport, SessionEvent, SessionRuntime, TurnControl, TurnIo, TurnView,
        },
    },
    config::Config,
};

/// Shows a session's turn to its clients and its job: the session's input
/// requests follow the turn's, and the request that sent the prompt learns
/// how the turn began.
///
/// Records the turn's end exactly once: through [`Self::end`], or, when the
/// view drops without it, as the turn task panicking, failed with
/// [`UNEXPECTED_STOP`].
pub(in crate::app::daemon_host::sessions) struct DaemonView {
    pub(in crate::app::daemon_host::sessions) session: Arc<LoadedSession>,
    /// The turn's id, which its end is told under.
    turn: wire::TurnId,
    /// Told `Began` once the turn began (see [`PromptStart::Began`]), or
    /// how the turn ended if it ends first.
    start: watch::Sender<PromptStart>,
    /// The prompt's user message, once the turn showed it.
    message: PromptMessage,
    /// Whether the turn's end is recorded.
    ended: bool,
}

impl DaemonView {
    pub(super) fn new(
        session: Arc<LoadedSession>,
        turn: wire::TurnId,
        start: watch::Sender<PromptStart>,
        message: PromptMessage,
    ) -> Self {
        Self {
            session,
            turn,
            start,
            message,
            ended: false,
        }
    }

    /// Notes the prompt's user message among `shown`, the events the turn
    /// shows as it inserts it, which the prompt's request answers with once
    /// the turn began. A steer is no prompt's.
    pub(in crate::app::daemon_host::sessions) fn inserted<'a>(
        &self,
        shown: impl IntoIterator<Item = &'a wire::SessionEvent>,
    ) {
        let prompt = shown.into_iter().find_map(|event| match event {
            wire::SessionEvent::UserMessage {
                message,
                steer: None,
                ..
            } => Some(message),
            _ => None,
        });
        if let Some(message) = prompt {
            self.message.set(message.clone());
        }
    }

    /// Tells whoever waits for the turn to begin that it began as `start`,
    /// unless they were told already.
    fn tell_start(&self, start: PromptStart) {
        self.start.send_if_modified(|told| {
            let first = *told == PromptStart::Pending;
            if first {
                *told = start;
            }
            first
        });
    }

    /// Records that the turn ended as `end`, telling clients `outcome`
    /// when there are clients to tell (`None` while the daemon stops).
    pub(super) fn end(mut self, outcome: Option<wire::TurnOutcome>, end: TurnEnd) {
        self.finish(outcome, end);
    }

    /// Tells clients the turn ended with `outcome`, if any, records it as
    /// `end`, and tells a request still waiting for the turn to begin.
    fn finish(&mut self, outcome: Option<wire::TurnOutcome>, end: TurnEnd) {
        // How the turn began, if it had not reported beginning yet. A
        // turn that completed began, and is recorded so (see `began`).
        let start = match end {
            TurnEnd::Completed => Some(PromptStart::Began),
            TurnEnd::Interrupted => None,
            TurnEnd::Cancelled | TurnEnd::TimedOut { .. } | TurnEnd::Failed(_) => {
                outcome.clone().map(PromptStart::Ended)
            }
        };
        // A turn that ended waits for nothing, and inserts nothing more.
        self.session.change_inputs(Inputs::withdraw_turn);
        self.message.settle();
        {
            // See `prompt`: the next turn's `running` cannot come before this.
            let _turn = self.session.turn();
            // A turn that ends before it began answers its prompt with that
            // end, so the session whose call sent it hears it there alone.
            if matches!(start, Some(PromptStart::Ended(_)))
                && *self.start.borrow() == PromptStart::Pending
            {
                self.session.peer_wake.forget();
            }
            self.session.end_turn(self.turn.clone(), outcome, end);
        }
        self.ended = true;
        // Here, so a turn whose task panicked frees the watcher too.
        if let Some(wake) = &self.session.idle_wake {
            wake.turn_ended();
        }
        if let Some(keep) = &self.session.cache_warm {
            keep.turn_ended();
        }
        match start {
            Some(PromptStart::Began) => self.began(),
            Some(start @ PromptStart::Ended(_)) => self.tell_start(start),
            Some(PromptStart::Pending) | None => {}
        }
    }

    /// Tells the request that sent the prompt, if it still waits, that the
    /// turn began (see [`PromptStart::Began`]), and records it on the job,
    /// so a later daemon still knows the prompt as one that ran.
    ///
    /// Nothing a turn does before this needs a client: `rho acp` reads none
    /// of the session's events while its prompt waits for this answer.
    pub(in crate::app::daemon_host::sessions) fn began(&mut self) {
        // Recorded before the request is answered, so a daemon killed right
        // after its answer still left the turn recorded as begun. The
        // registry records it once, and only on this turn.
        self.message.settle();
        let message = self.message.get();
        self.session
            .jobs
            .turn_began(&self.session.job, &self.turn, message);
        self.tell_start(PromptStart::Began);
    }

    /// Tells the request that sent the prompt that the turn began, though
    /// it only waits for capacity: it has run nothing, so the job does not
    /// record it begun until it does ([`Self::began`]).
    pub(in crate::app::daemon_host::sessions) fn accepted(&mut self) {
        self.tell_start(PromptStart::Began);
    }

    /// Takes the model turn's events until it drops its sender, opening
    /// and withdrawing input requests whose answers go to `control`. Holds
    /// `control` until then: a turn whose control channel closes fails, and
    /// requests nobody answered yet must stay open.
    pub(super) async fn show(
        &mut self,
        mut events: mpsc::UnboundedReceiver<SessionEvent>,
        control: mpsc::UnboundedSender<TurnControl>,
        mut cost: cost::TurnCost,
    ) {
        loop {
            // A streamed card held back for more arguments goes out when
            // the stream pauses instead.
            let event = if self.session.live().holds_previews() {
                match tokio::time::timeout(PREVIEW_PAUSE, events.recv()).await {
                    Ok(event) => event,
                    Err(_) => {
                        let held = self.session.live().held_previews();
                        self.session.feed.publish(held);
                        continue;
                    }
                }
            } else {
                events.recv().await
            };
            let event = match event {
                Some(SessionEvent::TitleRequested(title)) => {
                    spawn_title(&self.session, *title);
                    continue;
                }
                Some(event) => event,
                None => break,
            };
            let wire = {
                let mut live = self.session.live();
                let mut wire = live.map(&event);
                if matches!(event, SessionEvent::Run(RunEvent::UsageUpdated { .. })) {
                    wire.extend(live.streamed_usage().map(FeedEvent::from));
                }
                wire
            };
            let wire = cost.priced(&event, wire, &self.session.id).await;
            let inserted = matches!(event, SessionEvent::MessageInserted(_));
            if inserted {
                self.inserted(wire.iter().map(|shown| &shown.event));
            }
            self.session.feed.publish(wire);
            if let Some(keep) = &self.session.cache_warm {
                match &event {
                    SessionEvent::RunStarted { .. } => keep.run_started(),
                    SessionEvent::Run(RunEvent::ModelCallCompleted { metrics, .. }) => {
                        keep.model_call_completed(metrics);
                    }
                    SessionEvent::Run(RunEvent::CompactionCompleted { .. }) => {
                        keep.prefix_rewritten();
                    }
                    _ => {}
                }
            }
            if inserted {
                self.began();
            }
            self.session.change_inputs(|inputs| {
                inputs.note(Asker::Turn, &control, &event, SystemTime::now())
            });
        }
    }
}

/// How long a model's stream may pause before the card of what it wrote
/// last is sent though its arguments grew little: long enough that a card
/// per pause stays at four a second for a stream that only trickles, short
/// enough to read as the stream itself.
const PREVIEW_PAUSE: std::time::Duration = std::time::Duration::from_millis(250);

impl Drop for DaemonView {
    fn drop(&mut self) {
        if !self.ended {
            let (outcome, end) = failed(wire::TurnError {
                kind: wire::TurnErrorKind::Other,
                message: UNEXPECTED_STOP.to_owned(),
            });
            self.finish(Some(outcome), end);
        }
    }
}

impl TurnView for DaemonView {
    fn open_turn<'v>(
        &'v mut self,
        runtime: &SessionRuntime,
    ) -> (TurnIo, impl Future<Output = ()> + Send + use<'v>) {
        let (events, event_receiver) = mpsc::unbounded_channel();
        let (control_sender, control) = mpsc::unbounded_channel();
        (
            TurnIo { events, control },
            self.show(
                event_receiver,
                control_sender,
                cost::TurnCost::on(&runtime.current_model()),
            ),
        )
    }

    /// A plan the session kept its mode for reaches clients as a notice
    /// saying why. An approval that switched the permission mode changes
    /// the session's options, which clients see before the implementation
    /// turn.
    fn report_plan(
        &mut self,
        runtime: &SessionRuntime,
        _process_config: &Config,
        report: PlanReport,
    ) -> impl Future<Output = ()> + Send {
        let session = Arc::clone(&self.session);
        let notice = match report {
            PlanReport::Kept { notice } => Some(wire::SessionEvent::Notice { text: notice }),
            PlanReport::Switched => {
                // Before the implementation turn starts, so a change queued
                // during it still applies afterwards.
                session.turn().plan_switches += 1;
                None
            }
        };
        async move {
            session.feed.publish(notice);
            session.refresh_options(runtime, &available_auths(runtime.credentials()).await);
        }
    }
}