rho-coding-agent 2.33.0

A fast Rust agent harness with a small footprint and opinionated defaults
//! 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, LiveRunTitle, RunArtifactIdentity, RunArtifactSink},
    subagent::RunStatus,
};

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>>;
}

/// Thin CLI-facing handle around [`RunArtifactSink`].
pub(crate) struct StatusSink {
    inner: RunArtifactSink,
    rate_limits: Option<Box<dyn RateLimitRecorder>>,
}

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

    /// Resume after the executor already wrote the Starting boundary.
    pub(crate) fn continue_from(
        path: PathBuf,
        mut status: RunStatus,
        prompt: &str,
        status_tx: Option<watch::Sender<RunStatus>>,
        live_title: Option<LiveRunTitle>,
        rate_limits: Option<Box<dyn RateLimitRecorder>>,
        label: RuntimeLabel,
    ) -> anyhow::Result<Self> {
        status.last_activity = Some(label.starting_activity.into());
        let mut inner =
            RunArtifactSink::continue_from(path, status, prompt, status_tx, live_title)?;
        inner.publish();
        Ok(Self { inner, rate_limits })
    }

    pub(crate) fn mark_running(&mut self) {
        self.inner.mark_running("running");
    }

    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.inner.record_attachment(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() {
                    if let Some(notice) = recorder.notice(&info) {
                        self.inner.write_attachment(AttachmentEvent::Notice(notice));
                    }
                    recorder.record(info);
                    self.inner.publish();
                }
            }
        }
    }

    pub(crate) async fn fail(&mut self, error: impl Into<String>) {
        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.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.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.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.claude_session_id = Some(session_id);
    }
    status.turns = terminal.turns;
    status.result = Some(terminal.result_text.clone());
}

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