Skip to main content

subspace_agent_tools/
help_image.rs

1//! Bounded, compile-time help assets. This interface never reads files or URLs.
2
3use base64::Engine as _;
4use serde::{Deserialize, Serialize};
5use serde_json::Value;
6
7const MAX_IMAGES: usize = 3;
8const MAX_BYTES: usize = 512 * 1024;
9const MAX_ENCODED: usize = MAX_BYTES.div_ceil(3) * 4;
10const MAX_ID_BYTES: usize = 64;
11const MAX_CAPTION_BYTES: usize = 512;
12const WEBP_FORMAT_OFFSET: usize = 8;
13const WEBP_HEADER_BYTES: usize = 12;
14
15/// A board-owned image compiled into the binary with `include_bytes!`.
16#[derive(Clone, Copy, Debug, PartialEq, Eq)]
17#[non_exhaustive]
18pub struct HelpImage {
19    pub id: &'static str,
20    pub caption: &'static str,
21    pub media_type: &'static str,
22    pub bytes: &'static [u8],
23}
24
25impl HelpImage {
26    pub const fn new(
27        id: &'static str,
28        caption: &'static str,
29        media_type: &'static str,
30        bytes: &'static [u8],
31    ) -> Self {
32        Self {
33            id,
34            caption,
35            media_type,
36            bytes,
37        }
38    }
39
40    /// The selected image's typed transport reply, never part of the guide text.
41    pub fn reply(&self, board_id: &str) -> Result<Value, String> {
42        validate_images(&[*self])?;
43        super::encoded(HelpImageReply {
44            kind: ReplyKind::SubspaceBundledHelpImage,
45            board_id: board_id.into(),
46            image_id: self.id.into(),
47            caption: self.caption.into(),
48            media_type: self.media_type.into(),
49            data: base64::engine::general_purpose::STANDARD.encode(self.bytes),
50        })
51    }
52}
53
54#[derive(Debug, Serialize, Deserialize)]
55#[serde(rename_all = "snake_case")]
56enum ReplyKind {
57    SubspaceBundledHelpImage,
58}
59
60/// Validated image reply shared by the SDK and MCP adapters.
61#[derive(Debug, Serialize, Deserialize)]
62#[serde(deny_unknown_fields)]
63#[non_exhaustive]
64pub struct HelpImageReply {
65    kind: ReplyKind,
66    pub board_id: String,
67    pub image_id: String,
68    pub caption: String,
69    pub media_type: String,
70    pub data: String,
71}
72
73/// Decode only the reserved help tool's typed envelope. Ordinary JSON stays text.
74pub fn help_image_reply(tool_name: &str, value: &Value) -> Option<HelpImageReply> {
75    if tool_name != super::HELP_TOOL || value.get("data")?.as_str()?.len() > MAX_ENCODED {
76        return None;
77    }
78    let reply: HelpImageReply = serde_json::from_value(value.clone()).ok()?;
79    valid_reply(reply)
80}
81
82fn valid_reply(reply: HelpImageReply) -> Option<HelpImageReply> {
83    let bytes = base64::engine::general_purpose::STANDARD
84        .decode(&reply.data)
85        .ok()?;
86    (valid_id(&reply.board_id)
87        && valid_id(&reply.image_id)
88        && valid_caption(&reply.caption)
89        && valid_bytes(&reply.media_type, &bytes))
90    .then_some(reply)
91}
92
93/// Reject invalid catalogs as a whole, rather than silently exposing a subset.
94pub fn validate_images(images: &[HelpImage]) -> Result<(), String> {
95    if images.len() > MAX_IMAGES {
96        return Err("A board may bundle at most 3 help images.".into());
97    }
98    for (index, image) in images.iter().enumerate() {
99        if !valid_id(image.id)
100            || !valid_caption(image.caption)
101            || !valid_bytes(image.media_type, image.bytes)
102            || images[..index].iter().any(|earlier| earlier.id == image.id)
103        {
104            return Err(format!("Invalid bundled help image: {}.", image.id));
105        }
106    }
107    Ok(())
108}
109
110fn valid_id(id: &str) -> bool {
111    !id.is_empty()
112        && id.len() <= MAX_ID_BYTES
113        && id
114            .bytes()
115            .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'-')
116}
117
118fn valid_caption(caption: &str) -> bool {
119    !caption.trim().is_empty() && caption.len() <= MAX_CAPTION_BYTES
120}
121
122fn valid_bytes(media_type: &str, bytes: &[u8]) -> bool {
123    if bytes.len() > MAX_BYTES {
124        return false;
125    }
126    match media_type {
127        "image/png" => bytes.starts_with(b"\x89PNG\r\n\x1a\n"),
128        "image/webp" => {
129            bytes.starts_with(b"RIFF")
130                && bytes.get(WEBP_FORMAT_OFFSET..WEBP_HEADER_BYTES) == Some(b"WEBP")
131        }
132        _ => false,
133    }
134}
135
136#[cfg(test)]
137mod tests {
138    use super::{HelpImage, help_image_reply};
139
140    #[test]
141    fn image_replies_require_the_reserved_tool_exact_tag_and_valid_bounded_raster() {
142        let image = HelpImage::new("dashboard", "Test", "image/png", b"\x89PNG\r\n\x1a\ntest");
143        let mut value = image.reply("lab").unwrap();
144        assert!(help_image_reply("board_help", &value).is_some());
145        assert!(help_image_reply("ordinary_read", &value).is_none());
146        value["kind"] = "arbitrary_image".into();
147        assert!(help_image_reply("board_help", &value).is_none());
148        value["kind"] = "subspace_bundled_help_image".into();
149        value["media_type"] = "image/svg+xml".into();
150        assert!(help_image_reply("board_help", &value).is_none());
151        value["media_type"] = "image/png".into();
152        value["data"] = "x".repeat(700_000).into();
153        assert!(help_image_reply("board_help", &value).is_none());
154    }
155}