rho-coding-agent 3.12.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
//! The session a run on an external agent runtime (Claude Code,
//! Antigravity) is recorded under: the wire events of what the run records
//! ([`AttachmentEvent`]), so clients observe it as they observe a Rho
//! child's session, live or replayed from the run's attach journal, and the
//! options that session shows.
//!
//! The run keeps its runtime's own conversation; the session's file holds
//! only its prompt and reply (see [`crate::session::SessionEngine::Acp`]).
//! How the run ended comes from its status, as a Rho child's does.

use rho_protocol::{
    display::{Presentation, ToolCard, ToolCardStatus},
    ContentBlock, ModelChoice, ModelOptions, ModelRef, PermissionModeOptions,
    SessionEvent as WireEvent, SessionOptions, ToolCallId, ToolCallUpdate, ToolStatus,
};

use super::{
    card, header_title,
    message_ids::{fresh_message_id, ChunkKind, MessageStream},
    status_update, CallIds,
};
use crate::{
    cli_runtime::agent_event::render::MAX_ACTIVE_TOOLS,
    display_transcript::{DisplayRow, NotificationRow},
    presentation::checklist::{plan_card, EXTERNAL_PLAN_KEY},
    run_artifacts::AttachmentEvent,
};

/// The model an external run shows when its agent pins none: the runtime
/// chooses, and reports which only as the run goes.
const RUNTIME_DEFAULT_MODEL: &str = "default";

/// The model an external run whose agent pins `model`, if any, runs on, as
/// its session shows it.
pub(crate) fn runtime_model(model: Option<&str>) -> &str {
    model.unwrap_or(RUNTIME_DEFAULT_MODEL)
}

/// Maps one external run's recorded events, in order, to its session's.
#[derive(Default)]
pub(crate) struct ExternalEvents {
    messages: MessageStream,
    /// Ids for calls recorded without a key.
    calls: CallIds,
    /// The calls started and not finished, in the order they started, with
    /// the card each last showed: the run's end closes them, as an agent's
    /// plan, which it never finishes.
    open: Vec<(ToolCallId, ToolCard)>,
}

impl ExternalEvents {
    /// The wire events of `event`; none for what clients are told another
    /// way, or not at all.
    pub(crate) fn map(&mut self, event: &AttachmentEvent) -> Vec<WireEvent> {
        let events = self.wire_events(event);
        if events.iter().any(|event| {
            !matches!(
                event,
                WireEvent::AgentMessageChunk { .. } | WireEvent::ThoughtChunk { .. }
            )
        }) {
            // Text after anything else starts a message.
            self.messages.interrupt();
        }
        events
    }

    fn wire_events(&mut self, event: &AttachmentEvent) -> Vec<WireEvent> {
        match event {
            AttachmentEvent::Prompt(text) => vec![WireEvent::UserMessage {
                message: fresh_message_id(),
                content: vec![ContentBlock::Text { text: text.clone() }],
                steer: None,
            }],
            AttachmentEvent::PromptContent(content) => vec![WireEvent::UserMessage {
                message: fresh_message_id(),
                content: content.clone(),
                steer: None,
            }],
            AttachmentEvent::Steered { steer, content } => vec![WireEvent::UserMessage {
                message: fresh_message_id(),
                content: content.clone(),
                steer: Some(steer.clone()),
            }],
            AttachmentEvent::Message(message) => {
                let row = DisplayRow::Notification(Box::new(NotificationRow {
                    card: (**message).clone(),
                    info: None,
                }));
                vec![card(&row).event]
            }
            AttachmentEvent::AssistantTextDelta(text) => vec![WireEvent::AgentMessageChunk {
                message: self.messages.chunk(ChunkKind::Agent),
                text: text.clone(),
            }],
            AttachmentEvent::ReasoningDelta(text) => vec![WireEvent::ThoughtChunk {
                message: self.messages.chunk(ChunkKind::Thought),
                text: text.clone(),
            }],
            AttachmentEvent::ToolStarted { key, card } => {
                let id = self.call_id(key.as_deref());
                self.shown(&id, card);
                vec![WireEvent::tool_call(ToolCallUpdate {
                    title: header_title(card.header.clone()),
                    display: Some(Presentation::Card(card.clone())),
                    ..status_update(id, tool_status(card.status))
                })]
            }
            AttachmentEvent::ToolUpdated { key, card } => {
                let id = self.call_id(key.as_deref());
                self.shown(&id, card);
                vec![WireEvent::tool_call(ToolCallUpdate {
                    display: Some(Presentation::Card(card.clone())),
                    ..status_update(id, tool_status(card.status))
                })]
            }
            AttachmentEvent::ToolFinished { key, presentation } => {
                let status = match presentation {
                    Presentation::Card(card) | Presentation::SummaryCard(card) => {
                        tool_status(card.status)
                    }
                    Presentation::Notification(_) => Some(ToolStatus::Completed),
                };
                let id = self.call_id(key.as_deref());
                self.open.retain(|(open, _)| *open != id);
                vec![WireEvent::tool_call(ToolCallUpdate {
                    display: Some(presentation.clone()),
                    ..status_update(id, status)
                })]
            }
            // Absent fields are unchanged: the call keeps its card and
            // status, and shows `content` until a later update replaces it.
            AttachmentEvent::ToolContent { key, content } => {
                vec![WireEvent::tool_call(ToolCallUpdate {
                    content: Some(content.clone()),
                    ..status_update(ToolCallId::new(key), /*status*/ None)
                })]
            }
            AttachmentEvent::Notice(text) => vec![WireEvent::Notice { text: text.clone() }],
            // The session's plan, and the card that shows it among the
            // run's calls, as a Rho session's todo shows both.
            AttachmentEvent::Plan(entries) => {
                let card = AttachmentEvent::ToolStarted {
                    key: Some(EXTERNAL_PLAN_KEY.to_owned()),
                    card: plan_card(entries),
                };
                let mut events = vec![WireEvent::Plan {
                    entries: entries.clone(),
                }];
                events.extend(self.wire_events(&card));
                events
            }
            AttachmentEvent::ContextUsage(usage) => usage
                .tokens
                .map(|used_tokens| WireEvent::Usage {
                    used_tokens,
                    window_tokens: usage.context_window,
                    cost_usd_micros: None,
                })
                .into_iter()
                .collect(),
            // The run's end closes its open calls as it ended; how it ended
            // comes from its status, which the run's follower reports.
            AttachmentEvent::Completed => self.close_open(ToolCardStatus::Ok),
            AttachmentEvent::Cancelled => self.close_open(ToolCardStatus::Interrupted),
            AttachmentEvent::Failed(_) => self.close_open(ToolCardStatus::Error),
            // Argument previews are a Rho child's alone; a model call's
            // usage and a step's start show in the run's status.
            AttachmentEvent::ToolPreview { .. }
            | AttachmentEvent::Usage(_)
            | AttachmentEvent::ModelCallCompleted { .. }
            | AttachmentEvent::StepStarted
            | AttachmentEvent::ProviderStreamReset => Vec::new(),
        }
    }

    /// Closes the calls still open as interrupted, for a run whose journal
    /// ends without its end, as when the daemon running it died: none once
    /// the run's end closed them.
    pub(crate) fn cut_short(&mut self) -> Vec<WireEvent> {
        self.close_open(ToolCardStatus::Interrupted)
    }

    /// Keeps call `id` open with `card`, while the card shows it running.
    /// Past as many open calls as the run's renderer keeps in flight, which
    /// announces its own overflow, a call is shown but not kept open: the
    /// first, as the plan, are the ones the run's end must close.
    fn shown(&mut self, id: &ToolCallId, card: &ToolCard) {
        self.open.retain(|(open, _)| open != id);
        if card.status == ToolCardStatus::Running && self.open.len() < MAX_ACTIVE_TOOLS {
            self.open.push((id.clone(), card.clone()));
        }
    }

    /// Closes the calls still open, their last cards showing `status`: a
    /// completed run's as completed, since what an agent leaves open when
    /// it ends, as its plan, ended with it.
    fn close_open(&mut self, status: ToolCardStatus) -> Vec<WireEvent> {
        std::mem::take(&mut self.open)
            .into_iter()
            .map(|(id, mut card)| {
                card.status = status;
                WireEvent::tool_call(ToolCallUpdate {
                    display: Some(Presentation::Card(card)),
                    ..status_update(id, tool_status(status))
                })
            })
            .collect()
    }

    /// Call `key`'s id; for a call recorded without a key, which no later
    /// event names, a numbered one.
    fn call_id(&mut self, key: Option<&str>) -> ToolCallId {
        match key {
            Some(key) => ToolCallId::new(key),
            None => self.calls.open(""),
        }
    }
}

/// The options the session of an external run shows: the `provider`,
/// `model` (if its agent pins one) and `mode` it was bound with, which
/// nobody changes while it runs.
pub(crate) fn external_options(
    provider: &str,
    model: Option<&str>,
    mode: rho_protocol::PermissionMode,
) -> SessionOptions {
    let model = runtime_model(model).to_owned();
    let current = ModelRef {
        provider: provider.to_owned(),
        model: model.clone(),
    };
    SessionOptions {
        model: ModelOptions {
            available: vec![ModelChoice {
                model: current.clone(),
                label: model,
            }],
            current,
            // The runtime signs in itself; its sign-in is its provider's.
            auth: provider.to_owned(),
        },
        reasoning: None,
        fast_mode: None,
        permission_mode: PermissionModeOptions {
            current: mode,
            available: vec![mode],
        },
        commands: Vec::new(),
        added_dirs: Vec::new(),
    }
}

fn tool_status(status: ToolCardStatus) -> Option<ToolStatus> {
    match status {
        ToolCardStatus::Running => Some(ToolStatus::InProgress),
        ToolCardStatus::Ok => Some(ToolStatus::Completed),
        ToolCardStatus::Error => Some(ToolStatus::Failed),
        ToolCardStatus::Interrupted => Some(ToolStatus::Cancelled),
        // `Unknown`, or a status a newer protocol adds.
        _ => None,
    }
}

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