rho-coding-agent 3.12.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
//! Prompt content handed to an external agent run: text and images, in order.

use rho_protocol as wire;
use rho_sdk::{
    model::{ContentBlock, ImageContent},
    UserInput,
};
use serde::{Deserialize, Serialize};

use crate::run_artifacts::AttachmentEvent;

/// One block of an external agent run's prompt.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub(crate) enum PromptBlock {
    Text { text: String },
    Image { mime_type: String, data: String },
}

/// The content of one external agent run's prompt: text and images, in order.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub(crate) struct CliPrompt {
    blocks: Vec<PromptBlock>,
}

impl CliPrompt {
    /// A prompt of one text block.
    pub(crate) fn text(text: impl Into<String>) -> Self {
        Self {
            blocks: vec![PromptBlock::Text { text: text.into() }],
        }
    }

    /// A prompt of `blocks`, in order.
    pub(crate) fn from_blocks(blocks: Vec<PromptBlock>) -> Self {
        Self { blocks }
    }

    /// Extracts text and images from `input`. Fails if a tool-call block
    /// appears where only user prompt content is valid.
    pub(crate) fn from_user_input(input: &UserInput) -> Result<Self, &'static str> {
        let blocks = input
            .blocks()
            .iter()
            .map(|block| match block {
                ContentBlock::Text(text) => Ok(PromptBlock::Text { text: text.clone() }),
                ContentBlock::Image(ImageContent { mime_type, data }) => Ok(PromptBlock::Image {
                    mime_type: mime_type.clone(),
                    data: data.clone(),
                }),
                ContentBlock::ToolCall(_) => Err("a prompt cannot carry a tool call"),
            })
            .collect::<Result<Vec<_>, _>>()?;
        Ok(Self { blocks })
    }

    pub(crate) fn blocks(&self) -> &[PromptBlock] {
        &self.blocks
    }

    pub(crate) fn into_blocks(self) -> Vec<PromptBlock> {
        self.blocks
    }

    /// Whether the prompt carries at least one image block.
    pub(crate) fn has_images(&self) -> bool {
        self.blocks
            .iter()
            .any(|block| matches!(block, PromptBlock::Image { .. }))
    }

    /// This prompt with `preamble` ahead of it: prepended onto a leading text
    /// block, or inserted as a text block of its own ahead of an image-first
    /// prompt.
    pub(crate) fn with_preamble(&self, preamble: &str) -> Self {
        let mut blocks = self.blocks.clone();
        match blocks.first_mut() {
            Some(PromptBlock::Text { text }) => {
                *text = format!("{preamble}\n\n{text}");
            }
            Some(PromptBlock::Image { .. }) | None => {
                blocks.insert(
                    0,
                    PromptBlock::Text {
                        text: preamble.to_owned(),
                    },
                );
            }
        }
        Self { blocks }
    }

    /// The prompt's text blocks, as an agent that takes text alone reads it.
    pub(crate) fn text_content(&self) -> String {
        text_of(&self.blocks)
    }

    /// The prompt as daemon wire content blocks. Empty text blocks are omitted
    /// when other blocks are present, matching Rho's own user-message events.
    pub(crate) fn to_wire_blocks(&self) -> Vec<wire::ContentBlock> {
        let non_empty: Vec<wire::ContentBlock> = self
            .blocks
            .iter()
            .filter_map(|block| match block {
                PromptBlock::Text { text } if !text.is_empty() => {
                    Some(wire::ContentBlock::Text { text: text.clone() })
                }
                PromptBlock::Text { .. } => None,
                PromptBlock::Image { mime_type, data } => Some(wire::ContentBlock::Image {
                    mime_type: mime_type.clone(),
                    data: data.clone(),
                }),
            })
            .collect();
        if non_empty.is_empty() {
            vec![wire::ContentBlock::Text {
                text: String::new(),
            }]
        } else {
            non_empty
        }
    }

    /// How the attach journal records this prompt: a plain text prompt stays
    /// [`AttachmentEvent::Prompt`], while a prompt carrying images or multiple
    /// blocks keeps all of them in [`AttachmentEvent::PromptContent`].
    pub(crate) fn to_attachment_event(&self) -> AttachmentEvent {
        match self.blocks.as_slice() {
            [PromptBlock::Text { text }] => AttachmentEvent::Prompt(text.clone()),
            _ => AttachmentEvent::PromptContent(self.to_wire_blocks()),
        }
    }
}

/// The text of `blocks`, without their images: each text block, a blank
/// line between them.
pub(crate) fn text_of(blocks: &[PromptBlock]) -> String {
    blocks
        .iter()
        .filter_map(|block| match block {
            PromptBlock::Text { text } => Some(text.as_str()),
            PromptBlock::Image { .. } => None,
        })
        .collect::<Vec<_>>()
        .join("\n\n")
}

impl From<String> for CliPrompt {
    fn from(text: String) -> Self {
        Self::text(text)
    }
}

impl From<&str> for CliPrompt {
    fn from(text: &str) -> Self {
        Self::text(text)
    }
}

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