rho-coding-agent 3.6.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::{
        peer_sessions::PeerBatch,
        pull_requests::NewsBatch,
        subagent_messaging::{NoticeDelivery, SubagentNotice},
    },
    display_transcript::{DisplayRow, DisplayTranscript, NotificationRow},
    subagent::RunState,
    tools::{
        agent::{SubagentManager, SubagentNotification},
        process::ProcessNotification,
        ui::SurfaceAction,
        workflow_tracker::WorkflowNotification,
    },
};
use rho_protocol::{
    display::{
        NotificationCard, NotificationDelivery, NotificationOutcome, NotificationPreview,
        NotificationSubject, NotificationTone, NotificationVisibility,
    },
    SessionId,
};

/// Finished background work drained for one boundary.
pub(crate) struct BoundaryResults<'a> {
    pub(crate) notices: &'a [SubagentNotice],
    pub(crate) subagents: &'a [SubagentNotification],
    pub(crate) workflows: &'a [WorkflowNotification],
    pub(crate) processes: &'a [ProcessNotification],
    /// What the user did on A2UI surfaces while no `ui` call waited.
    pub(crate) surface_actions: &'a [SurfaceAction],
    /// What changed on the session's watched pull requests.
    pub(crate) pull_requests: &'a NewsBatch,
    /// How turns the session started in other sessions ended, or the
    /// questions they ask.
    pub(crate) peer_sessions: &'a PeerBatch,
}

/// 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(),
                ))));
            }
        }
        if !self.subagents.is_empty() {
            model.push(crate::tools::agent::notification_prompt(self.subagents));
            for notification in self.subagents {
                rows.push(DisplayRow::Notification(Box::new(subagent_result_row(
                    manager,
                    notification,
                ))));
            }
        }
        if !self.workflows.is_empty() {
            let (input, display) =
                crate::tools::workflow_tracker::notification_prompts(self.workflows);
            model.push(input);
            rows.push(DisplayRow::Notice(display));
        }
        if !self.processes.is_empty() {
            model.push(crate::tools::process::notification_prompt(self.processes));
            rows.extend(
                self.processes
                    .iter()
                    .map(|notification| DisplayRow::Notification(Box::new(notification.row()))),
            );
        }
        for SurfaceAction { surface, action } in self.surface_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")
            )));
        }
        if !self.pull_requests.is_empty() {
            model.push(self.pull_requests.prompt());
            rows.extend(
                self.pull_requests
                    .news
                    .iter()
                    .map(|news| DisplayRow::Notification(Box::new(news.row()))),
            );
        }
        if !self.peer_sessions.is_empty() {
            model.push(self.peer_sessions.prompt());
            rows.extend(
                self.peer_sessions
                    .rows()
                    .into_iter()
                    .map(|row| DisplayRow::Notification(Box::new(row))),
            );
        }
        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;