Skip to main content

merry_runtime/
user_input.rs

1//! Validated user messages admitted into runtime steps.
2
3use crate::RuntimeError;
4use merry_llm::{ModelContent, ModelImage};
5use std::{borrow::Cow, sync::Arc};
6
7const PNG_SIGNATURE: &[u8; 8] = b"\x89PNG\r\n\x1a\n";
8
9/// Maximum number of images accepted in one user message.
10pub const MAX_USER_IMAGES: usize = 20;
11/// Maximum encoded PNG size accepted for one image.
12pub const MAX_USER_IMAGE_PNG_BYTES: usize = 10 * 1024 * 1024;
13/// Maximum combined encoded PNG size accepted for one user message.
14pub const MAX_USER_IMAGE_TOTAL_PNG_BYTES: usize = 20 * 1024 * 1024;
15/// Maximum width or height accepted for one image.
16pub const MAX_USER_IMAGE_DIMENSION: u32 = 8_000;
17/// Maximum decoded pixel count accepted for one image.
18pub const MAX_USER_IMAGE_PIXELS: u64 = 32_000_000;
19
20/// Returns the canonical one-based label for a user image.
21pub fn user_image_label(index: usize) -> Result<String, RuntimeError> {
22    if index == 0 {
23        return Err(invalid_image("user image label index must start at one"));
24    }
25    Ok(format!("[Image #{index}]"))
26}
27
28/// A validated normalized PNG attached to one user message.
29#[derive(Debug, Clone, PartialEq, Eq)]
30pub struct UserImageInput {
31    label: String,
32    png_bytes: Arc<[u8]>,
33    width: u32,
34    height: u32,
35}
36
37impl UserImageInput {
38    /// Creates a normalized PNG user image.
39    pub fn png(
40        label: &str,
41        png_bytes: impl Into<Arc<[u8]>>,
42        width: u32,
43        height: u32,
44    ) -> Result<Self, RuntimeError> {
45        if label.trim().is_empty() || label.chars().any(char::is_control) {
46            return Err(invalid_image(
47                "user image label must be non-blank and contain no control characters",
48            ));
49        }
50
51        let png_bytes = png_bytes.into();
52        if !png_bytes.starts_with(PNG_SIGNATURE) {
53            return Err(invalid_image(
54                "user image bytes must contain normalized PNG data",
55            ));
56        }
57        if png_bytes.len() > MAX_USER_IMAGE_PNG_BYTES {
58            return Err(invalid_image(
59                "one user image encoded PNG must be at most 10 MiB",
60            ));
61        }
62        if width == 0 || height == 0 {
63            return Err(invalid_image(
64                "user image dimensions must be greater than zero",
65            ));
66        }
67        if width > MAX_USER_IMAGE_DIMENSION || height > MAX_USER_IMAGE_DIMENSION {
68            return Err(invalid_image(
69                "user image dimensions must not exceed 8000 pixels per dimension",
70            ));
71        }
72        let pixels = u64::from(width)
73            .checked_mul(u64::from(height))
74            .ok_or_else(|| invalid_image("user image pixel count overflowed"))?;
75        if pixels > MAX_USER_IMAGE_PIXELS {
76            return Err(invalid_image(
77                "one user image must not exceed 32 million pixels",
78            ));
79        }
80
81        Ok(Self {
82            label: label.to_owned(),
83            png_bytes,
84            width,
85            height,
86        })
87    }
88
89    /// Canonical user-visible image label.
90    #[must_use]
91    pub fn label(&self) -> &str {
92        &self.label
93    }
94
95    /// Normalized PNG bytes.
96    #[must_use]
97    pub fn png_bytes(&self) -> &[u8] {
98        &self.png_bytes
99    }
100
101    /// Cheap shared ownership of the normalized PNG bytes.
102    #[must_use]
103    pub fn shared_png_bytes(&self) -> Arc<[u8]> {
104        Arc::clone(&self.png_bytes)
105    }
106
107    /// Decoded image width in pixels.
108    #[must_use]
109    pub fn width(&self) -> u32 {
110        self.width
111    }
112
113    /// Decoded image height in pixels.
114    #[must_use]
115    pub fn height(&self) -> u32 {
116        self.height
117    }
118
119    fn model_image(&self) -> Result<ModelImage, merry_llm::ModelError> {
120        ModelImage::png(
121            self.label(),
122            self.shared_png_bytes(),
123            self.width(),
124            self.height(),
125        )
126    }
127}
128
129/// One validated user message with zero or more normalized PNG attachments.
130#[derive(Debug, Clone, PartialEq, Eq)]
131pub struct UserMessageInput {
132    text: String,
133    images: Vec<UserImageInput>,
134}
135
136impl UserMessageInput {
137    /// Creates a text-only user message.
138    pub fn text_only(text: &str) -> Result<Self, RuntimeError> {
139        Self::new(text, Vec::new())
140    }
141
142    /// Creates a user message with ordered image attachments.
143    ///
144    /// Windows (`\r\n`) and bare carriage-return (`\r`) line endings are
145    /// normalized to `\n`, and other non-whitespace Unicode control characters
146    /// (such as NUL, BEL, or ESC) are stripped before validation and storage.
147    pub fn new(text: &str, images: Vec<UserImageInput>) -> Result<Self, RuntimeError> {
148        let sanitized = sanitize_freeform_text(text);
149        let text = sanitized.as_ref();
150        validate_user_text(text)?;
151        if images.len() > MAX_USER_IMAGES {
152            return Err(invalid_image(
153                "one user message may contain at most 20 images",
154            ));
155        }
156
157        let mut total_png_bytes = 0_usize;
158        for (offset, image) in images.iter().enumerate() {
159            let expected_label = user_image_label(offset + 1)?;
160            if image.label() != expected_label {
161                return Err(invalid_image(format!(
162                    "user image {} label must be {expected_label}",
163                    offset + 1
164                )));
165            }
166            if !text.contains(image.label()) {
167                return Err(invalid_image(format!(
168                    "user message text must contain image label {}",
169                    image.label()
170                )));
171            }
172            total_png_bytes = total_png_bytes
173                .checked_add(image.png_bytes().len())
174                .ok_or_else(|| invalid_image("user image total PNG byte count overflowed"))?;
175        }
176        if total_png_bytes > MAX_USER_IMAGE_TOTAL_PNG_BYTES {
177            return Err(invalid_image(
178                "one user message encoded PNG data must total at most 20 MiB",
179            ));
180        }
181
182        Ok(Self {
183            text: sanitized.into_owned(),
184            images,
185        })
186    }
187
188    /// Full user text containing the image labels.
189    #[must_use]
190    pub fn text(&self) -> &str {
191        &self.text
192    }
193
194    /// Ordered normalized PNG attachments.
195    #[must_use]
196    pub fn images(&self) -> &[UserImageInput] {
197        &self.images
198    }
199
200    pub(crate) fn model_content(&self) -> Result<ModelContent, merry_llm::ModelError> {
201        if self.images.is_empty() {
202            return ModelContent::text(self.text());
203        }
204
205        let images = self
206            .images
207            .iter()
208            .map(UserImageInput::model_image)
209            .collect::<Result<Vec<_>, _>>()?;
210        ModelContent::user_with_images(self.text(), images)
211    }
212}
213
214/// Input snapshot for a runtime step.
215///
216/// Runtime state such as context, artifacts, tool continuations, and ledger
217/// facts is read from the owning session rather than passed as raw chat history.
218#[derive(Debug, Clone, PartialEq, Eq)]
219pub struct StepInput {
220    user_messages: Vec<UserMessageInput>,
221    user_texts: Vec<String>,
222    history_message_count: usize,
223}
224
225impl StepInput {
226    /// Creates a user-text step input.
227    pub fn user_text(text: &str) -> Result<Self, RuntimeError> {
228        Self::user_texts([text])
229    }
230
231    /// Creates a step input with multiple consecutive text-only user messages.
232    pub fn user_texts<I, S>(texts: I) -> Result<Self, RuntimeError>
233    where
234        I: IntoIterator<Item = S>,
235        S: AsRef<str>,
236    {
237        let messages = texts
238            .into_iter()
239            .map(|text| UserMessageInput::text_only(text.as_ref()))
240            .collect::<Result<Vec<_>, _>>()?;
241        Self::from_user_messages(messages)
242    }
243
244    /// Creates a step input with consecutive validated user messages.
245    pub fn from_user_messages<I>(messages: I) -> Result<Self, RuntimeError>
246    where
247        I: IntoIterator<Item = UserMessageInput>,
248    {
249        let user_messages = messages.into_iter().collect::<Vec<_>>();
250        if user_messages.is_empty() {
251            return Err(RuntimeError::InvalidStepInput {
252                reason: "user text burst must contain at least one message",
253            });
254        }
255        let user_texts = user_messages
256            .iter()
257            .map(|message| message.text().to_owned())
258            .collect();
259        let history_message_count = user_messages.len();
260
261        Ok(Self {
262            user_messages,
263            user_texts,
264            history_message_count,
265        })
266    }
267
268    pub(crate) fn loop_control_text(text: &str) -> Result<Self, RuntimeError> {
269        let message = UserMessageInput::text_only(text)?;
270        Ok(Self {
271            user_texts: vec![message.text().to_owned()],
272            user_messages: vec![message],
273            history_message_count: 0,
274        })
275    }
276
277    pub(crate) fn no_new_user_input() -> Self {
278        Self {
279            user_messages: Vec::new(),
280            user_texts: Vec::new(),
281            history_message_count: 0,
282        }
283    }
284
285    /// Appends a dynamic control steering note sent to the model without recording it as user history.
286    pub(crate) fn append_control_note(&mut self, text: &str) -> Result<(), RuntimeError> {
287        let message = UserMessageInput::text_only(text)?;
288        self.user_texts.push(message.text().to_owned());
289        self.user_messages.push(message);
290        Ok(())
291    }
292
293    /// Borrows the first user text for this step.
294    #[must_use]
295    pub fn text(&self) -> &str {
296        self.user_texts
297            .first()
298            .map(String::as_str)
299            .expect("StepInput::text is available only for user text inputs")
300    }
301
302    /// Borrows the user texts for this step.
303    #[must_use]
304    pub fn texts(&self) -> &[String] {
305        &self.user_texts
306    }
307
308    /// Borrows the validated user messages for this step.
309    #[must_use]
310    pub fn user_messages(&self) -> &[UserMessageInput] {
311        &self.user_messages
312    }
313
314    pub(crate) fn user_messages_for_request(&self) -> &[UserMessageInput] {
315        &self.user_messages
316    }
317
318    pub(crate) fn user_messages_for_history(&self) -> &[UserMessageInput] {
319        &self.user_messages[..self.history_message_count]
320    }
321
322    pub(crate) fn memory_activation_query(&self) -> Option<String> {
323        (!self.user_texts.is_empty()).then(|| self.user_texts.join("\n\n"))
324    }
325}
326
327/// Normalizes CRLF (`\r\n`) and bare CR (`\r`) line breaks into `\n`.
328///
329/// Borrows `text` without allocating when it contains no carriage returns.
330#[must_use]
331pub fn normalize_line_endings(text: &str) -> Cow<'_, str> {
332    if !text.contains('\r') {
333        return Cow::Borrowed(text);
334    }
335    let mut normalized = String::with_capacity(text.len());
336    let mut chars = text.chars().peekable();
337    while let Some(ch) = chars.next() {
338        if ch == '\r' {
339            if chars.peek() == Some(&'\n') {
340                chars.next();
341            }
342            normalized.push('\n');
343        } else {
344            normalized.push(ch);
345        }
346    }
347    Cow::Owned(normalized)
348}
349
350pub(crate) fn is_stripped_control_char(ch: char) -> bool {
351    ch.is_control() && ch != '\n' && ch != '\t'
352}
353
354/// Sanitizes untrusted freeform natural-language text for runtime storage and
355/// model requests.
356///
357/// - Normalizes CRLF (`\r\n`) and bare CR (`\r`) line breaks into `\n`.
358/// - Preserves `\n` and `\t`.
359/// - Strips all other Unicode control characters (`char::is_control()`),
360///   including NUL (`\0`), BEL (`\x07`), ESC (`\x1b`), DEL (`\x7f`), and C1
361///   controls, so dirty upstream text never aborts a turn or leaks terminal
362///   escape sequences.
363/// - Borrows `text` without allocating when it is already clean.
364#[must_use]
365pub fn sanitize_freeform_text(text: &str) -> Cow<'_, str> {
366    if !text.chars().any(is_stripped_control_char) {
367        return Cow::Borrowed(text);
368    }
369
370    let mut cleaned = String::with_capacity(text.len());
371    let mut chars = text.chars().peekable();
372    let mut stripped_controls = 0_usize;
373    let mut stripped_nuls = 0_usize;
374    while let Some(ch) = chars.next() {
375        if ch == '\r' {
376            if chars.peek() == Some(&'\n') {
377                chars.next();
378            }
379            cleaned.push('\n');
380        } else if ch == '\0' {
381            stripped_nuls += 1;
382            stripped_controls += 1;
383        } else if is_stripped_control_char(ch) {
384            stripped_controls += 1;
385        } else {
386            cleaned.push(ch);
387        }
388    }
389
390    if stripped_nuls > 0 {
391        tracing::warn!(
392            event = "input.sanitized_control_chars",
393            stripped_controls,
394            stripped_nuls,
395            "stripped NUL and control characters from freeform text"
396        );
397    } else if stripped_controls > 0 {
398        tracing::debug!(
399            event = "input.sanitized_control_chars",
400            stripped_controls,
401            "stripped non-whitespace control characters from freeform text"
402        );
403    }
404
405    Cow::Owned(cleaned)
406}
407
408pub(crate) fn validate_user_text(text: &str) -> Result<(), RuntimeError> {
409    if text.trim().is_empty() {
410        return Err(RuntimeError::InvalidStepInput {
411            reason: "user text must not be blank",
412        });
413    }
414
415    Ok(())
416}
417
418fn invalid_image(reason: impl Into<String>) -> RuntimeError {
419    RuntimeError::InvalidUserImageInput {
420        reason: reason.into(),
421    }
422}