rho-coding-agent 3.13.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
//! External agent session adapter over the shared run-artifact sink.
//!
//! Shared by every ACP runtime; labels differ per agent. Translates rendered
//! effects into the generic status/attachment contract. Rate-limit
//! persistence is a pluggable [`RateLimitRecorder`]: Claude records
//! subscription windows; other agents leave the recorder unset.

use std::future::Future;
use std::path::PathBuf;
use std::pin::Pin;

use tokio::sync::watch;

use crate::{
    run_artifacts::{AttachmentEvent, RunArtifactIdentity, RunArtifactSink},
    subagent::RunStatus,
};

use super::prompt::CliPrompt;
use super::stream_effect::{RateLimitInfo, StreamEffect, TerminalResult};
use super::stream_format::apply_status_patch;

/// Starting activity, program name, and model-facing copy for a CLI runtime sink.
#[derive(Clone, Copy, Debug)]
pub(crate) struct RuntimeLabel {
    pub(crate) starting_activity: &'static str,
    pub(crate) program: &'static str,
    /// Binary invoked for `--resume <session-id>`. `None` when the recorded
    /// session id cannot be resumed (ACP session ids are not CLI resume ids).
    pub(crate) resume_command: Option<&'static str>,
    /// Prefix for session metadata, e.g. `claude session`.
    pub(crate) session_label: &'static str,
    /// Cost line label, e.g. `claude cost`.
    pub(crate) cost_label: &'static str,
}

/// CLI-specific rate-limit cache updates collected during a run.
///
/// Object-safe so the sink can hold an optional recorder without knowing the
/// owning runtime. `flush` is `'static` after taking pending state.
pub(crate) trait RateLimitRecorder: Send {
    /// Optional transcript notice for this observation.
    fn notice(&self, info: &RateLimitInfo) -> Option<String>;
    fn record(&mut self, info: RateLimitInfo);
    fn flush(&mut self) -> Pin<Box<dyn Future<Output = ()> + Send>>;
}

/// Hears each attach event an external agent run records, in the order it
/// records them, from its prompt to how it ended, so a host can show the
/// run live and record its session.
///
/// Called on the run's own task, before the run's status says it ended, so
/// an implementor that only queues each event (a channel send) has passed
/// on all of them by then.
pub(crate) trait RunObserver: Send {
    /// Called as each event is recorded. Must not block: it runs for every
    /// event the run streams.
    fn recorded(&mut self, event: &AttachmentEvent);

    /// Called as the run sends the agent a follow-up turn, with the reply
    /// of the turn that just ended, which [`Self::ended`] will not give: it
    /// gives the last turn's alone. Must not block. A host that keeps only
    /// the run's answer ignores it.
    fn replied(&mut self, _reply: &str) {}

    /// Called once, as the run sends the agent its prompt, right before it
    /// goes out: from here the agent may act on it, and a run cut short
    /// after this may have. Must not block; may write a file. A host that
    /// does not care whether the prompt went out ignores it.
    fn prompting(&mut self) {}

    /// Called once, right after [`Self::recorded`] heard how the run ended,
    /// with the reply the run gives its parent, if it gave one. May write a
    /// file, as the run's journal is written on the same task.
    fn ended(&mut self, reply: Option<&str>);
}

/// Thin CLI-facing handle around [`RunArtifactSink`].
pub(crate) struct StatusSink {
    inner: RunArtifactSink,
    rate_limits: Option<Box<dyn RateLimitRecorder>>,
    observer: Option<Box<dyn RunObserver>>,
    /// What the journal recorded for the run's prompt as the sink opened,
    /// which an observer hears first.
    opening: Option<AttachmentEvent>,
}

impl StatusSink {
    pub(crate) fn new(
        path: PathBuf,
        identity: &RunArtifactIdentity,
        prompt: &CliPrompt,
        status_tx: Option<watch::Sender<RunStatus>>,
        rate_limits: Option<Box<dyn RateLimitRecorder>>,
        label: RuntimeLabel,
    ) -> anyhow::Result<Self> {
        let opening = prompt.to_attachment_event();
        let mut inner =
            RunArtifactSink::open_with_prompt(path, identity, opening.clone(), status_tx)?;
        inner.status.last_activity = Some(label.starting_activity.into());
        inner.publish();
        Ok(Self {
            inner,
            rate_limits,
            observer: None,
            opening: Some(opening),
        })
    }

    /// Resume after the executor already wrote the Starting boundary, with
    /// the title, journal start and record of the prompt `overrides` set.
    pub(crate) fn continue_from(
        path: PathBuf,
        mut status: RunStatus,
        prompt: &CliPrompt,
        status_tx: Option<watch::Sender<RunStatus>>,
        overrides: &super::CliSessionOverrides,
        rate_limits: Option<Box<dyn RateLimitRecorder>>,
        label: RuntimeLabel,
    ) -> anyhow::Result<Self> {
        status.last_activity = Some(label.starting_activity.into());
        let opening = overrides.prompt_record.event(prompt.to_attachment_event());
        let mut inner = RunArtifactSink::continue_from(
            path,
            status,
            opening.clone(),
            status_tx,
            overrides.live_title.clone(),
            overrides.journal,
        )?;
        inner.publish();
        Ok(Self {
            inner,
            rate_limits,
            observer: None,
            opening,
        })
    }

    /// Lets `observer` hear what the run records from here on, starting
    /// with what the sink recorded for the prompt when it opened.
    pub(crate) fn observed_by(&mut self, mut observer: Box<dyn RunObserver>) {
        if let Some(opening) = &self.opening {
            observer.recorded(opening);
        }
        self.observer = Some(observer);
    }

    /// Records `event`, and tells the observer, if any.
    fn record(&mut self, event: AttachmentEvent) {
        self.tell(&event);
        self.inner.record_attachment(event);
    }

    /// Tells the observer, if any, that the run recorded `event`.
    fn tell(&mut self, event: &AttachmentEvent) {
        if let Some(observer) = self.observer.as_mut() {
            observer.recorded(event);
        }
    }

    /// Tells the observer, if any, that the run ended as `end` says, with
    /// `reply`, before the run's status says so.
    fn tell_end(&mut self, end: &AttachmentEvent, reply: Option<&str>) {
        if let Some(observer) = self.observer.as_mut() {
            observer.recorded(end);
            observer.ended(reply);
        }
    }

    /// Tells the observer, if any, the reply of the turn that just ended,
    /// as the run sends a follow-up turn ([`RunObserver::replied`]): none
    /// for a turn that gave no text.
    pub(crate) fn turn_replied(&mut self, reply: &str) {
        if let (Some(observer), false) = (self.observer.as_mut(), reply.is_empty()) {
            observer.replied(reply);
        }
    }

    /// Names the session the run works for, which its next status carries.
    pub(crate) fn works_for(&mut self, parent_session_id: Option<String>) {
        self.inner.status.parent_session_id = parent_session_id;
    }

    /// Marks the run running as it sends the agent its prompt (the ACP
    /// driver calls this right before the prompt goes out), and tells the
    /// observer, if any ([`RunObserver::prompting`]).
    pub(crate) fn mark_running(&mut self) {
        self.inner.mark_running("running");
        if let Some(observer) = self.observer.as_mut() {
            observer.prompting();
        }
    }

    pub(crate) fn apply_effect(&mut self, effect: StreamEffect) {
        match effect {
            StreamEffect::Attachment(event) => {
                // Answer text reaches `last_text` through its status patch.
                // Reasoning has no text patch, so mirror only that here.
                if let AttachmentEvent::ReasoningDelta(text) = &event {
                    if !text.is_empty() {
                        self.inner.append_last_text(text);
                    }
                }
                self.record(event);
            }
            StreamEffect::Status(patch) => {
                apply_status_patch(&mut self.inner.status, patch);
                self.inner.publish();
            }
            StreamEffect::RateLimit(info) => {
                if let Some(recorder) = self.rate_limits.as_mut() {
                    let notice = recorder.notice(&info);
                    recorder.record(info);
                    match notice {
                        Some(notice) => self.record(AttachmentEvent::Notice(notice)),
                        None => self.inner.publish(),
                    }
                }
            }
        }
    }

    /// Records that the agent could not resume the session the run
    /// continues, which the run's failure then carries.
    pub(crate) fn conversation_not_restored(&mut self) {
        self.inner.status.failure = Some(crate::subagent::RunFailure::ConversationNotRestored);
    }

    pub(crate) async fn fail(&mut self, error: impl Into<String>) {
        let error = error.into();
        self.tell_end(&AttachmentEvent::Failed(error.clone()), /*reply*/ None);
        self.inner.finish_error(error);
        self.flush_rate_limits().await;
    }

    pub(crate) async fn stop(&mut self, reason: &str, terminal: &TerminalResult) {
        apply_terminal_metadata(&mut self.inner.status, terminal);
        self.tell_end(&AttachmentEvent::Cancelled, reply(terminal));
        self.inner.finish_stopped(reason);
        self.flush_rate_limits().await;
    }

    pub(crate) async fn succeed(&mut self, terminal: &TerminalResult) {
        apply_terminal_metadata(&mut self.inner.status, terminal);
        self.tell_end(&AttachmentEvent::Completed, reply(terminal));
        self.inner.finish_ok(Some(terminal.result_text.clone()));
        self.flush_rate_limits().await;
    }

    /// A turn that ended without success; `error` is what the run reports.
    pub(crate) async fn fail_turn(&mut self, terminal: &TerminalResult, error: String) {
        apply_terminal_metadata(&mut self.inner.status, terminal);
        self.tell_end(&AttachmentEvent::Failed(error.clone()), reply(terminal));
        self.inner.finish_error(error);
        self.flush_rate_limits().await;
    }

    async fn flush_rate_limits(&mut self) {
        if let Some(recorder) = self.rate_limits.as_mut() {
            recorder.flush().await;
        }
    }
}

fn apply_terminal_metadata(status: &mut RunStatus, terminal: &TerminalResult) {
    if let Some(session_id) = terminal.session_id.clone() {
        status.runtime_session_id = Some(session_id);
    }
    status.turns = terminal.turns;
    status.result = Some(terminal.result_text.clone());
}

/// The reply a run that ended as `terminal` gives its parent, if it said
/// anything.
fn reply(terminal: &TerminalResult) -> Option<&str> {
    Some(terminal.result_text.as_str()).filter(|text| !text.is_empty())
}

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