rho-coding-agent 3.13.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
//! Background results delivered at one turn boundary, rendered once for both
//! the model and the transcript.
//!
//! The TUI and the headless hosts (ACP, `rho run`) deliver the same finished
//! work: subagent messages and results, workflows, and background processes.
//! Rendering both views here keeps the saved display rows describing exactly
//! the input the model received, whichever host delivered it.

use crate::{
    app::{
        boundary_sources::Reserved,
        subagent_messaging::{NoticeDelivery, SubagentNotice},
    },
    display_transcript::{DisplayRow, DisplayTranscript, NotificationRow},
    subagent::RunState,
    tools::agent::{SubagentManager, SubagentNotification},
};
use rho_protocol::{
    display::{
        NotificationCard, NotificationDelivery, NotificationOutcome, NotificationPreview,
        NotificationSubject, NotificationTone, NotificationVisibility,
    },
    SessionId,
};

/// Finished background work drained for one boundary.
pub(crate) struct BoundaryResults<'a> {
    /// What the session's subagents told it before they finished.
    pub(crate) notices: &'a [SubagentNotice],
    /// The results the boundary took, one batch per source, in the order
    /// the model reads them.
    pub(crate) reserved: &'a [Reserved],
}

/// Model input sections and display rows for one boundary, in delivery order.
/// Hosts may append their own sections before joining them.
pub(crate) struct BoundaryMessage {
    pub(crate) model: Vec<String>,
    pub(crate) rows: Vec<DisplayRow>,
}

impl BoundaryMessage {
    /// `None` when nothing was delivered.
    pub(crate) fn finish(self) -> Option<(String, DisplayTranscript)> {
        (!self.model.is_empty()).then(|| (self.model.join("\n\n"), DisplayTranscript(self.rows)))
    }
}

impl BoundaryResults<'_> {
    /// Renders every result. `manager` resolves subagent task titles so saved
    /// and live cards name the same task.
    pub(crate) fn render(&self, manager: Option<&SubagentManager>) -> BoundaryMessage {
        let mut model = Vec::new();
        let mut rows = Vec::new();
        if !self.notices.is_empty() {
            model.push(format!(
                "Earlier child messages in send order. Any terminal result below supersedes that child's planning and progress; preserve substantive findings.\n\n{}",
                crate::app::subagent_messaging::notice_prompt(self.notices),
            ));
            for notice in self.notices {
                let event = match notice.delivery {
                    NoticeDelivery::NextTurn => AgentEvent::Update,
                    NoticeDelivery::ParentActionRequired => AgentEvent::ActionRequired,
                };
                rows.push(DisplayRow::Notification(Box::new(agent_row(
                    manager,
                    &notice.run_id,
                    &notice.agent_id,
                    /*title*/ None,
                    event,
                    notice.message.clone(),
                ))));
            }
        }
        for reserved in self.reserved.iter().filter(|reserved| !reserved.is_empty()) {
            match reserved {
                Reserved::Subagents(_, notifications) => {
                    model.push(crate::tools::agent::notification_prompt(notifications));
                    for notification in notifications {
                        rows.push(DisplayRow::Notification(Box::new(subagent_result_row(
                            manager,
                            notification,
                        ))));
                    }
                }
                Reserved::Workflows(_, notifications) => {
                    let (input, display) =
                        crate::tools::workflow_tracker::notification_prompts(notifications);
                    model.push(input);
                    rows.push(DisplayRow::Notice(display));
                }
                Reserved::Processes(_, notifications) => {
                    model.push(crate::tools::process::notification_prompt(notifications));
                    rows.extend(notifications.iter().map(|notification| {
                        DisplayRow::Notification(Box::new(notification.row()))
                    }));
                }
                Reserved::Surfaces(_, actions) => {
                    for crate::tools::ui::SurfaceAction { surface, action } in actions {
                        model.push(format!(
                            "The user acted on surface `{surface}`, which the `ui` tool showed. The A2UI action:\n\n{action}"
                        ));
                        let name = action.get("name").and_then(serde_json::Value::as_str);
                        rows.push(DisplayRow::Notice(format!(
                            "surface action\n{} on surface {surface}",
                            name.unwrap_or("action")
                        )));
                    }
                }
                Reserved::PullRequests(_, news) => {
                    model.push(news.prompt());
                    rows.extend(
                        news.news
                            .iter()
                            .map(|news| DisplayRow::Notification(Box::new(news.row()))),
                    );
                }
                Reserved::Peers(_, notices) => {
                    model.push(notices.prompt());
                    rows.extend(
                        notices
                            .rows()
                            .into_iter()
                            .map(|row| DisplayRow::Notification(Box::new(row))),
                    );
                }
                Reserved::Answers(_, answers) => {
                    model.push(answers.prompt());
                    rows.extend(answers.answers().map(|answer| {
                        DisplayRow::Notice(format!(
                            "answer to \"{}\"\n{}",
                            answer.title, answer.content
                        ))
                    }));
                }
            }
        }
        BoundaryMessage { model, rows }
    }
}

fn subagent_result_row(
    manager: Option<&SubagentManager>,
    notification: &SubagentNotification,
) -> NotificationRow {
    let snapshot = &notification.snapshot;
    let event = match snapshot.status.state {
        RunState::Queued | RunState::Starting | RunState::Running => AgentEvent::Update,
        RunState::Ok => AgentEvent::Completed,
        RunState::Error => AgentEvent::Failed,
        RunState::Stopped => AgentEvent::Stopped,
    };
    let body = snapshot
        .status
        .error
        .iter()
        .chain(snapshot.status.result.iter())
        .cloned()
        .collect::<Vec<_>>()
        .join("\n\n");
    let mut row = agent_row(
        manager,
        &snapshot.id,
        &snapshot.agent_id,
        snapshot.title.as_deref(),
        event,
        body,
    );
    row.card.details.push(format!(
        "elapsed: {:.1}s · turns: {}",
        snapshot.elapsed.as_secs_f64(),
        snapshot.status.turns
    ));
    if let Some(model) = crate::model_identity::PromptModel::from_run_status(&snapshot.status) {
        row.card
            .details
            .push(format!("model: {}", model.describe()));
    }
    row
}

/// Agent-specific policy becomes explicit, generic display data at this boundary.
enum AgentEvent {
    Update,
    ActionRequired,
    Completed,
    Failed,
    Stopped,
}

/// A subagent's card, typed as one item about its run: the run's own
/// session, when the manager knows it, lets a client open it.
fn agent_row(
    manager: Option<&SubagentManager>,
    run_id: &str,
    sender: &str,
    title: Option<&str>,
    event: AgentEvent,
    body: String,
) -> NotificationRow {
    let identity = manager.and_then(|manager| manager.task_identity(run_id));
    let task = title
        .filter(|title| !title.trim().is_empty())
        .map(str::to_owned)
        .or_else(|| identity.as_ref().map(|identity| identity.task.clone()))
        .unwrap_or_else(|| "Delegated task".into());
    let (label, tone, preview, outcome) = match event {
        AgentEvent::Update => (
            "Update",
            NotificationTone::Accent,
            NotificationPreview::Truncated,
            NotificationOutcome::Update,
        ),
        AgentEvent::ActionRequired => (
            "Action requested",
            NotificationTone::Warning,
            NotificationPreview::Full,
            NotificationOutcome::ActionRequested,
        ),
        AgentEvent::Completed => (
            "Completed",
            NotificationTone::Success,
            NotificationPreview::Truncated,
            NotificationOutcome::Completed,
        ),
        AgentEvent::Failed => (
            "Failed",
            NotificationTone::Error,
            NotificationPreview::Full,
            NotificationOutcome::Failed,
        ),
        AgentEvent::Stopped => (
            "Stopped",
            NotificationTone::Accent,
            NotificationPreview::Truncated,
            NotificationOutcome::Stopped,
        ),
    };
    let title = format!("{label} · {task}");
    let subject = NotificationSubject::Subagent {
        run: run_id.to_owned(),
        session: identity
            .and_then(|identity| identity.session)
            .map(|session| SessionId::new(session.to_string())),
    };
    let card = NotificationCard {
        title,
        sender: sender.into(),
        recipient: "parent".into(),
        delivery: NotificationDelivery::Received,
        tone,
        preview,
        visibility: NotificationVisibility::Conversation,
        reference: Some(run_id.into()),
        subtitle: None,
        body,
        output: None,
        details: vec![format!("task: {task}")],
    };
    NotificationRow::single(card, subject, outcome)
}

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