merry-runtime 0.1.1

Structured session, task ledger, context compaction, memory, permission, and tool runtime for Merry.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
//! Validated user messages admitted into runtime steps.

use crate::RuntimeError;
use merry_llm::{ModelContent, ModelImage};
use std::{borrow::Cow, sync::Arc};

const PNG_SIGNATURE: &[u8; 8] = b"\x89PNG\r\n\x1a\n";

/// Maximum number of images accepted in one user message.
pub const MAX_USER_IMAGES: usize = 20;
/// Maximum encoded PNG size accepted for one image.
pub const MAX_USER_IMAGE_PNG_BYTES: usize = 10 * 1024 * 1024;
/// Maximum combined encoded PNG size accepted for one user message.
pub const MAX_USER_IMAGE_TOTAL_PNG_BYTES: usize = 20 * 1024 * 1024;
/// Maximum width or height accepted for one image.
pub const MAX_USER_IMAGE_DIMENSION: u32 = 8_000;
/// Maximum decoded pixel count accepted for one image.
pub const MAX_USER_IMAGE_PIXELS: u64 = 32_000_000;

/// Returns the canonical one-based label for a user image.
pub fn user_image_label(index: usize) -> Result<String, RuntimeError> {
    if index == 0 {
        return Err(invalid_image("user image label index must start at one"));
    }
    Ok(format!("[Image #{index}]"))
}

/// A validated normalized PNG attached to one user message.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct UserImageInput {
    label: String,
    png_bytes: Arc<[u8]>,
    width: u32,
    height: u32,
}

impl UserImageInput {
    /// Creates a normalized PNG user image.
    pub fn png(
        label: &str,
        png_bytes: impl Into<Arc<[u8]>>,
        width: u32,
        height: u32,
    ) -> Result<Self, RuntimeError> {
        if label.trim().is_empty() || label.chars().any(char::is_control) {
            return Err(invalid_image(
                "user image label must be non-blank and contain no control characters",
            ));
        }

        let png_bytes = png_bytes.into();
        if !png_bytes.starts_with(PNG_SIGNATURE) {
            return Err(invalid_image(
                "user image bytes must contain normalized PNG data",
            ));
        }
        if png_bytes.len() > MAX_USER_IMAGE_PNG_BYTES {
            return Err(invalid_image(
                "one user image encoded PNG must be at most 10 MiB",
            ));
        }
        if width == 0 || height == 0 {
            return Err(invalid_image(
                "user image dimensions must be greater than zero",
            ));
        }
        if width > MAX_USER_IMAGE_DIMENSION || height > MAX_USER_IMAGE_DIMENSION {
            return Err(invalid_image(
                "user image dimensions must not exceed 8000 pixels per dimension",
            ));
        }
        let pixels = u64::from(width)
            .checked_mul(u64::from(height))
            .ok_or_else(|| invalid_image("user image pixel count overflowed"))?;
        if pixels > MAX_USER_IMAGE_PIXELS {
            return Err(invalid_image(
                "one user image must not exceed 32 million pixels",
            ));
        }

        Ok(Self {
            label: label.to_owned(),
            png_bytes,
            width,
            height,
        })
    }

    /// Canonical user-visible image label.
    #[must_use]
    pub fn label(&self) -> &str {
        &self.label
    }

    /// Normalized PNG bytes.
    #[must_use]
    pub fn png_bytes(&self) -> &[u8] {
        &self.png_bytes
    }

    /// Cheap shared ownership of the normalized PNG bytes.
    #[must_use]
    pub fn shared_png_bytes(&self) -> Arc<[u8]> {
        Arc::clone(&self.png_bytes)
    }

    /// Decoded image width in pixels.
    #[must_use]
    pub fn width(&self) -> u32 {
        self.width
    }

    /// Decoded image height in pixels.
    #[must_use]
    pub fn height(&self) -> u32 {
        self.height
    }

    fn model_image(&self) -> Result<ModelImage, merry_llm::ModelError> {
        ModelImage::png(
            self.label(),
            self.shared_png_bytes(),
            self.width(),
            self.height(),
        )
    }
}

/// One validated user message with zero or more normalized PNG attachments.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct UserMessageInput {
    text: String,
    images: Vec<UserImageInput>,
}

impl UserMessageInput {
    /// Creates a text-only user message.
    pub fn text_only(text: &str) -> Result<Self, RuntimeError> {
        Self::new(text, Vec::new())
    }

    /// Creates a user message with ordered image attachments.
    ///
    /// Windows (`\r\n`) and bare carriage-return (`\r`) line endings are
    /// normalized to `\n`, and other non-whitespace Unicode control characters
    /// (such as NUL, BEL, or ESC) are stripped before validation and storage.
    pub fn new(text: &str, images: Vec<UserImageInput>) -> Result<Self, RuntimeError> {
        let sanitized = sanitize_freeform_text(text);
        let text = sanitized.as_ref();
        validate_user_text(text)?;
        if images.len() > MAX_USER_IMAGES {
            return Err(invalid_image(
                "one user message may contain at most 20 images",
            ));
        }

        let mut total_png_bytes = 0_usize;
        for (offset, image) in images.iter().enumerate() {
            let expected_label = user_image_label(offset + 1)?;
            if image.label() != expected_label {
                return Err(invalid_image(format!(
                    "user image {} label must be {expected_label}",
                    offset + 1
                )));
            }
            if !text.contains(image.label()) {
                return Err(invalid_image(format!(
                    "user message text must contain image label {}",
                    image.label()
                )));
            }
            total_png_bytes = total_png_bytes
                .checked_add(image.png_bytes().len())
                .ok_or_else(|| invalid_image("user image total PNG byte count overflowed"))?;
        }
        if total_png_bytes > MAX_USER_IMAGE_TOTAL_PNG_BYTES {
            return Err(invalid_image(
                "one user message encoded PNG data must total at most 20 MiB",
            ));
        }

        Ok(Self {
            text: sanitized.into_owned(),
            images,
        })
    }

    /// Full user text containing the image labels.
    #[must_use]
    pub fn text(&self) -> &str {
        &self.text
    }

    /// Ordered normalized PNG attachments.
    #[must_use]
    pub fn images(&self) -> &[UserImageInput] {
        &self.images
    }

    pub(crate) fn model_content(&self) -> Result<ModelContent, merry_llm::ModelError> {
        if self.images.is_empty() {
            return ModelContent::text(self.text());
        }

        let images = self
            .images
            .iter()
            .map(UserImageInput::model_image)
            .collect::<Result<Vec<_>, _>>()?;
        ModelContent::user_with_images(self.text(), images)
    }
}

/// Input snapshot for a runtime step.
///
/// Runtime state such as context, artifacts, tool continuations, and ledger
/// facts is read from the owning session rather than passed as raw chat history.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct StepInput {
    user_messages: Vec<UserMessageInput>,
    user_texts: Vec<String>,
    history_message_count: usize,
}

impl StepInput {
    /// Creates a user-text step input.
    pub fn user_text(text: &str) -> Result<Self, RuntimeError> {
        Self::user_texts([text])
    }

    /// Creates a step input with multiple consecutive text-only user messages.
    pub fn user_texts<I, S>(texts: I) -> Result<Self, RuntimeError>
    where
        I: IntoIterator<Item = S>,
        S: AsRef<str>,
    {
        let messages = texts
            .into_iter()
            .map(|text| UserMessageInput::text_only(text.as_ref()))
            .collect::<Result<Vec<_>, _>>()?;
        Self::from_user_messages(messages)
    }

    /// Creates a step input with consecutive validated user messages.
    pub fn from_user_messages<I>(messages: I) -> Result<Self, RuntimeError>
    where
        I: IntoIterator<Item = UserMessageInput>,
    {
        let user_messages = messages.into_iter().collect::<Vec<_>>();
        if user_messages.is_empty() {
            return Err(RuntimeError::InvalidStepInput {
                reason: "user text burst must contain at least one message",
            });
        }
        let user_texts = user_messages
            .iter()
            .map(|message| message.text().to_owned())
            .collect();
        let history_message_count = user_messages.len();

        Ok(Self {
            user_messages,
            user_texts,
            history_message_count,
        })
    }

    pub(crate) fn loop_control_text(text: &str) -> Result<Self, RuntimeError> {
        let message = UserMessageInput::text_only(text)?;
        Ok(Self {
            user_texts: vec![message.text().to_owned()],
            user_messages: vec![message],
            history_message_count: 0,
        })
    }

    pub(crate) fn no_new_user_input() -> Self {
        Self {
            user_messages: Vec::new(),
            user_texts: Vec::new(),
            history_message_count: 0,
        }
    }

    /// Appends a dynamic control steering note sent to the model without recording it as user history.
    pub(crate) fn append_control_note(&mut self, text: &str) -> Result<(), RuntimeError> {
        let message = UserMessageInput::text_only(text)?;
        self.user_texts.push(message.text().to_owned());
        self.user_messages.push(message);
        Ok(())
    }

    /// Borrows the first user text for this step.
    #[must_use]
    pub fn text(&self) -> &str {
        self.user_texts
            .first()
            .map(String::as_str)
            .expect("StepInput::text is available only for user text inputs")
    }

    /// Borrows the user texts for this step.
    #[must_use]
    pub fn texts(&self) -> &[String] {
        &self.user_texts
    }

    /// Borrows the validated user messages for this step.
    #[must_use]
    pub fn user_messages(&self) -> &[UserMessageInput] {
        &self.user_messages
    }

    pub(crate) fn user_messages_for_request(&self) -> &[UserMessageInput] {
        &self.user_messages
    }

    pub(crate) fn user_messages_for_history(&self) -> &[UserMessageInput] {
        &self.user_messages[..self.history_message_count]
    }

    pub(crate) fn memory_activation_query(&self) -> Option<String> {
        (!self.user_texts.is_empty()).then(|| self.user_texts.join("\n\n"))
    }
}

/// Normalizes CRLF (`\r\n`) and bare CR (`\r`) line breaks into `\n`.
///
/// Borrows `text` without allocating when it contains no carriage returns.
#[must_use]
pub fn normalize_line_endings(text: &str) -> Cow<'_, str> {
    if !text.contains('\r') {
        return Cow::Borrowed(text);
    }
    let mut normalized = String::with_capacity(text.len());
    let mut chars = text.chars().peekable();
    while let Some(ch) = chars.next() {
        if ch == '\r' {
            if chars.peek() == Some(&'\n') {
                chars.next();
            }
            normalized.push('\n');
        } else {
            normalized.push(ch);
        }
    }
    Cow::Owned(normalized)
}

pub(crate) fn is_stripped_control_char(ch: char) -> bool {
    ch.is_control() && ch != '\n' && ch != '\t'
}

/// Sanitizes untrusted freeform natural-language text for runtime storage and
/// model requests.
///
/// - Normalizes CRLF (`\r\n`) and bare CR (`\r`) line breaks into `\n`.
/// - Preserves `\n` and `\t`.
/// - Strips all other Unicode control characters (`char::is_control()`),
///   including NUL (`\0`), BEL (`\x07`), ESC (`\x1b`), DEL (`\x7f`), and C1
///   controls, so dirty upstream text never aborts a turn or leaks terminal
///   escape sequences.
/// - Borrows `text` without allocating when it is already clean.
#[must_use]
pub fn sanitize_freeform_text(text: &str) -> Cow<'_, str> {
    if !text.chars().any(is_stripped_control_char) {
        return Cow::Borrowed(text);
    }

    let mut cleaned = String::with_capacity(text.len());
    let mut chars = text.chars().peekable();
    let mut stripped_controls = 0_usize;
    let mut stripped_nuls = 0_usize;
    while let Some(ch) = chars.next() {
        if ch == '\r' {
            if chars.peek() == Some(&'\n') {
                chars.next();
            }
            cleaned.push('\n');
        } else if ch == '\0' {
            stripped_nuls += 1;
            stripped_controls += 1;
        } else if is_stripped_control_char(ch) {
            stripped_controls += 1;
        } else {
            cleaned.push(ch);
        }
    }

    if stripped_nuls > 0 {
        tracing::warn!(
            event = "input.sanitized_control_chars",
            stripped_controls,
            stripped_nuls,
            "stripped NUL and control characters from freeform text"
        );
    } else if stripped_controls > 0 {
        tracing::debug!(
            event = "input.sanitized_control_chars",
            stripped_controls,
            "stripped non-whitespace control characters from freeform text"
        );
    }

    Cow::Owned(cleaned)
}

pub(crate) fn validate_user_text(text: &str) -> Result<(), RuntimeError> {
    if text.trim().is_empty() {
        return Err(RuntimeError::InvalidStepInput {
            reason: "user text must not be blank",
        });
    }

    Ok(())
}

fn invalid_image(reason: impl Into<String>) -> RuntimeError {
    RuntimeError::InvalidUserImageInput {
        reason: reason.into(),
    }
}