Skip to main content

agent_base/
image_ops.rs

1//! Image mechanics shared by tools and the wire layer: magic sniffing,
2//! header-only dimension reads, the downscale-to-fit pass, and the
3//! per-image / per-message byte budget that keeps request bodies under the
4//! gateway's limit (the HTTP 413 cure — see [`apply_image_budget`]).
5//!
6//! One source of truth for "is this bytes stream a picture, how big is it,
7//! and does it fit the wire": the `read_image` tool sniffs and labels with
8//! it, and the engine budgets and shrinks with it. Numbers live here as
9//! named constants so a product can argue with them in one place.
10
11use base64::Engine as _;
12use llm_trait::message::{ChatMessage, ImageAttachment};
13
14/// Longest edge any picture may carry on the wire: large enough for a
15/// desktop screenshot's text to stay legible to a vision model, small
16/// enough that two of them never tripped the gateway's body limit (the
17/// HTTP 413 of session 20261030_862ddf5c).
18pub const MAX_WIRE_LONG_EDGE: u32 = 1568;
19
20/// Per-image wire budget, in base64 characters (the on-the-wire size).
21/// ~2.6 MB of raw pixels — after the downscale pass only the most
22/// pathological screenshot can reach it, and such a one is refused with an
23/// inventory instead of silently thinned.
24pub const MAX_IMAGE_BASE64_BYTES: usize = 3_500_000;
25
26/// Per-message wire budget for all of its pictures together, in base64
27/// characters. A message keeps all of its pictures or none — this is the
28/// line where "all" stops being affordable and the send is refused.
29pub const MAX_MESSAGE_IMAGES_BASE64_BYTES: usize = 12_000_000;
30
31/// MIME sniff from magic bytes — the extension and any declared MIME are
32/// advisory at best (a `.jpg` that is really a PNG is a PNG; a `text/html`
33/// wearing `image/png` is not a picture at all).
34pub fn sniff_mime(bytes: &[u8]) -> Option<&'static str> {
35    if bytes.starts_with(&[0x89, b'P', b'N', b'G', 0x0D, 0x0A, 0x1A, 0x0A]) {
36        return Some("image/png");
37    }
38    if bytes.starts_with(&[0xFF, 0xD8, 0xFF]) {
39        return Some("image/jpeg");
40    }
41    None
42}
43
44/// Decode base64 with the standard alphabet.
45pub fn from_base64(data: &str) -> Result<Vec<u8>, String> {
46    base64::engine::general_purpose::STANDARD
47        .decode(data)
48        .map_err(|e| format!("invalid base64 payload: {e}"))
49}
50
51/// Encode to base64 (standard alphabet, padded).
52pub fn to_base64(bytes: &[u8]) -> String {
53    base64::engine::general_purpose::STANDARD.encode(bytes)
54}
55
56/// On-the-wire size of a raw payload once base64-encoded, without doing the
57/// encode: padded standard base64 is `ceil(n / 3) * 4` characters.
58pub fn base64_len(raw_len: usize) -> usize {
59    raw_len.div_ceil(3) * 4
60}
61
62/// How much base64 head to decode for a dimension probe: enough for any
63/// PNG and for all but the most EXIF-bloated JPEG (its SOF marker sits near
64/// the head of the stream, well inside this window).
65const DIMS_PROBE_B64_CHARS: usize = 64 * 1024;
66
67/// Read a picture's pixel size from the HEAD of its base64 payload — a
68/// bounded probe, never a full decode. `None` when the head carries no
69/// decodable PNG/JPEG header: an exotic format, a corrupt payload, or not
70/// an image at all. Non-ASCII characters are skipped (a payload may be
71/// arbitrary text), so the probe never slices mid-character.
72pub fn base64_prefix_dims(data: &str) -> Option<Dims> {
73    let head: String = data
74        .chars()
75        .filter(char::is_ascii)
76        .take(DIMS_PROBE_B64_CHARS)
77        .collect();
78    let usable = head.len() - (head.len() % 4);
79    if usable == 0 {
80        return None;
81    }
82    let raw = from_base64(&head[..usable]).ok()?;
83    header_dimensions(&raw)
84}
85
86/// A picture's pixel size, (width, height).
87pub type Dims = (u32, u32);
88
89/// Header-only dimension read for PNG/JPEG — no pixel decode. `None` for
90/// bytes that are not a decodable PNG/JPEG stream.
91pub fn header_dimensions(bytes: &[u8]) -> Option<Dims> {
92    let format = match sniff_mime(bytes)? {
93        "image/png" => image::ImageFormat::Png,
94        "image/jpeg" => image::ImageFormat::Jpeg,
95        _ => return None,
96    };
97    let reader = image::ImageReader::with_format(std::io::Cursor::new(bytes), format);
98    reader.into_dimensions().ok()
99}
100
101/// Shrink a picture so its longest edge is [`MAX_WIRE_LONG_EDGE`],
102/// re-encoding in the SAME format (a PNG screenshot stays lossless, a JPEG
103/// stays a JPEG). Returns the (possibly unchanged) bytes plus the original
104/// and final pixel sizes.
105///
106/// A picture that already fits is returned byte-identical: no re-encode, no
107/// gratuitous generation loss, and a stable payload across turns. Errors are
108/// honest strings — the caller decides whether an un-shrinkable picture
109/// still travels (it does, subject to the byte budget).
110pub fn downscale_to_fit(bytes: &[u8]) -> Result<(Vec<u8>, Dims, Dims), String> {
111    let format = match sniff_mime(bytes) {
112        Some("image/png") => image::ImageFormat::Png,
113        Some("image/jpeg") => image::ImageFormat::Jpeg,
114        _ => return Err("not a PNG/JPEG image (magic bytes do not match)".to_string()),
115    };
116    let mut reader = image::ImageReader::with_format(std::io::Cursor::new(bytes), format);
117    // Untrusted bytes get a hard allocation ceiling before any decode —
118    // a "small" file can declare a monstrous canvas.
119    let mut limits = image::Limits::default();
120    limits.max_image_width = Some(32_000);
121    limits.max_image_height = Some(32_000);
122    limits.max_alloc = Some(512 * 1024 * 1024);
123    reader.limits(limits);
124    let img = reader
125        .decode()
126        .map_err(|e| format!("image decode failed: {e}"))?;
127    let original = (img.width(), img.height());
128    let long_edge = original.0.max(original.1);
129    if long_edge <= MAX_WIRE_LONG_EDGE {
130        return Ok((bytes.to_vec(), original, original));
131    }
132    let scale = MAX_WIRE_LONG_EDGE as f32 / long_edge as f32;
133    let new_w = ((original.0 as f32 * scale).round() as u32).max(1);
134    let new_h = ((original.1 as f32 * scale).round() as u32).max(1);
135    let resized = img.resize(new_w, new_h, image::imageops::FilterType::Lanczos3);
136    let mut out = Vec::new();
137    match format {
138        image::ImageFormat::Png => resized
139            .write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png)
140            .map_err(|e| format!("PNG re-encode failed: {e}"))?,
141        _ => {
142            let mut encoder = image::codecs::jpeg::JpegEncoder::new_with_quality(&mut out, 85);
143            encoder
144                .encode_image(&resized)
145                .map_err(|e| format!("JPEG re-encode failed: {e}"))?;
146        }
147    }
148    Ok((out, original, (new_w, new_h)))
149}
150
151/// Human byte count for inventories and guidance ("2.1 MB", "350 KB").
152fn pretty_bytes(n: usize) -> String {
153    if n >= 1_000_000 {
154        format!("{:.1} MB", n as f64 / 1_000_000.0)
155    } else if n >= 1_000 {
156        format!("{:.0} KB", n as f64 / 1_000.0)
157    } else {
158        format!("{n} B")
159    }
160}
161
162/// Why the request never left the machine: the full size inventory of every
163/// picture it carried, plus the lines that crossed the budget. Surfaced as
164/// a run error — the request is refused WHOLE, never thinned.
165#[derive(Debug, Clone)]
166pub struct ImageBudgetError {
167    pub inventory: Vec<String>,
168}
169
170impl std::fmt::Display for ImageBudgetError {
171    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
172        writeln!(
173            f,
174            "request NOT sent - image budget exceeded (nothing is silently dropped):"
175        )?;
176        for line in &self.inventory {
177            writeln!(f, "  {line}")?;
178        }
179        write!(
180            f,
181            "guidance: downscale the screenshot before pasting (long edge <= \
182             {MAX_WIRE_LONG_EDGE}px) or split the pictures across fewer messages."
183        )
184    }
185}
186
187impl std::error::Error for ImageBudgetError {}
188
189/// Prepare every picture for the wire and enforce the byte budget.
190///
191/// Per picture: shrink to [`MAX_WIRE_LONG_EDGE`] (same format), then measure
192/// the base64 it now occupies. Per message: the sum of its pictures. Over
193/// either line the WHOLE send is refused with [`ImageBudgetError`] — this is
194/// the one place a picture may leave the wire, and it does so with an
195/// inventory, never a silent drop. Word-only messages pass untouched.
196pub fn apply_image_budget(messages: &mut [ChatMessage]) -> Result<(), ImageBudgetError> {
197    let mut inventory: Vec<String> = Vec::new();
198    let mut over_budget = false;
199
200    for (mi, message) in messages.iter_mut().enumerate() {
201        let images = match message {
202            ChatMessage::Tool { images, .. } | ChatMessage::User { images, .. } => images,
203            _ => continue,
204        };
205        if images.is_empty() {
206            continue;
207        }
208        let mut message_bytes = 0usize;
209        for (ii, image) in images.iter_mut().enumerate() {
210            let ImageAttachment::Base64 {
211                data, media_type, ..
212            } = image
213            else {
214                // A URL reference carries no payload of ours to budget or
215                // shrink — the provider fetches it. It still gets an
216                // inventory line so the sizes listed are complete.
217                inventory.push(format!(
218                    "message {}, image {}: URL reference",
219                    mi + 1,
220                    ii + 1
221                ));
222                continue;
223            };
224            // Shrink first, judge second: a picture must not be refused for
225            // size it would have shed two lines down. Unparseable bytes are
226            // left as they are and judged by their measured size.
227            if let Ok(raw) = from_base64(data)
228                && sniff_mime(&raw).is_some()
229                && let Ok((shrunk, original, final_dims)) = downscale_to_fit(&raw)
230            {
231                *data = to_base64(&shrunk);
232                if original != final_dims {
233                    inventory.push(format!(
234                        "message {}, image {}: downscaled {}x{} -> {}x{}",
235                        mi + 1,
236                        ii + 1,
237                        original.0,
238                        original.1,
239                        final_dims.0,
240                        final_dims.1
241                    ));
242                }
243            }
244            let size = data.len();
245            let flag = if size > MAX_IMAGE_BASE64_BYTES {
246                over_budget = true;
247                " [OVER per-image budget]"
248            } else {
249                ""
250            };
251            inventory.push(format!(
252                "message {}, image {}: {} base64{}",
253                mi + 1,
254                ii + 1,
255                pretty_bytes(size),
256                flag
257            ));
258            if let Some(mime) = media_type {
259                inventory.push(format!("    type: {mime}"));
260            }
261            message_bytes += size;
262        }
263        if message_bytes > MAX_MESSAGE_IMAGES_BASE64_BYTES {
264            over_budget = true;
265            inventory.push(format!(
266                "message {}: {} of pictures total [OVER per-message budget of {}]",
267                mi + 1,
268                pretty_bytes(message_bytes),
269                pretty_bytes(MAX_MESSAGE_IMAGES_BASE64_BYTES)
270            ));
271        }
272    }
273
274    if over_budget {
275        Err(ImageBudgetError { inventory })
276    } else {
277        Ok(())
278    }
279}
280
281#[cfg(test)]
282pub(crate) mod test_fixtures {
283    /// A screenshot-sized PNG of incompressible noise — the payload SCALE of
284    /// a real desktop capture (megabytes of base64 at 1278x1152), which
285    /// solid-color fixtures cannot reproduce (they compress to nothing).
286    /// Grayscale keeps it inside the wire byte budget while still dwarfing
287    /// any token limit. Deterministic LCG pixels: same bytes on every run.
288    pub(crate) fn noisy_png(w: u32, h: u32) -> Vec<u8> {
289        let state = std::cell::Cell::new(0x9E37_79B9_7F4A_7C15u64);
290        let img = image::GrayImage::from_fn(w, h, |_, _| {
291            let mut s = state
292                .get()
293                .wrapping_mul(6364136223846793005)
294                .wrapping_add(1);
295            s ^= s >> 29;
296            state.set(s);
297            image::Luma([(s >> 40) as u8])
298        });
299        let mut out = Vec::new();
300        img.write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png)
301            .expect("encode noise png");
302        out
303    }
304}
305
306#[cfg(test)]
307mod tests {
308    use super::*;
309
310    fn png_bytes(w: u32, h: u32) -> Vec<u8> {
311        let img = image::RgbaImage::from_pixel(w, h, image::Rgba([10, 20, 30, 255]));
312        let mut out = Vec::new();
313        img.write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png)
314            .expect("encode test png");
315        out
316    }
317
318    fn base64_image(w: u32, h: u32) -> ImageAttachment {
319        ImageAttachment::Base64 {
320            data: to_base64(&png_bytes(w, h)),
321            media_type: Some("image/png".to_string()),
322            detail: None,
323        }
324    }
325
326    /// protects: the magic bytes — not the file name, not a declared MIME —
327    /// decide what a payload is (AC2's ".jpg named PNG is accepted, a
328    /// text/html impostor is refused"). fails_when: an extension or a
329    /// content-type header can smuggle non-image bytes past the tool.
330    /// no_claim: what happens to bytes whose type is correctly read.
331    #[test]
332    fn sniff_reads_the_magic_not_the_name() {
333        assert_eq!(sniff_mime(&png_bytes(1, 1)), Some("image/png"));
334        let mut jpg = vec![0xFF, 0xD8, 0xFF, 0xE0];
335        jpg.extend_from_slice(&[0; 8]);
336        assert_eq!(sniff_mime(&jpg), Some("image/jpeg"));
337        assert_eq!(sniff_mime(b"<html><body>not a picture</body></html>"), None);
338        assert_eq!(sniff_mime(b""), None);
339    }
340
341    /// protects: dimensions come from the image header without a pixel
342    /// decode (the metadata face of `read_image`). fails_when: a corrupt
343    /// header yields a made-up size. no_claim: pixel fidelity.
344    #[test]
345    fn header_dimensions_read_png_and_jpeg_headers() {
346        assert_eq!(header_dimensions(&png_bytes(37, 11)), Some((37, 11)));
347        assert_eq!(header_dimensions(b"not an image"), None);
348    }
349
350    /// protects: the bounded base64-head probe reads a picture's size without
351    /// decoding the whole payload (the token estimator's eyes), and survives
352    /// junk payloads and non-ASCII text without panicking. fails_when: the
353    /// probe needs the full decode, guesses a size for non-images, or slices
354    /// mid-character. no_claim: what a full pixel decode would find past the
355    /// probe window.
356    #[test]
357    fn base64_prefix_dims_probe_reads_the_head() {
358        let png = png_bytes(1278, 1152);
359        let b64 = to_base64(&png);
360        assert_eq!(base64_prefix_dims(&b64), Some((1278, 1152)));
361        // A junk tail behind a valid header does not fool the probe...
362        let mut padded = png.clone();
363        padded.extend_from_slice(&[0x55; 200_000]);
364        assert_eq!(base64_prefix_dims(&to_base64(&padded)), Some((1278, 1152)));
365        // ...and non-image or non-ASCII payloads answer None, never a panic.
366        assert_eq!(base64_prefix_dims(&to_base64(b"not an image at all")), None);
367        assert_eq!(base64_prefix_dims("你好世界"), None);
368        assert_eq!(base64_prefix_dims(""), None);
369        // A payload cut mid-quartet still probes fine: the head holds the
370        // header and the probe trims to whole quartets instead of panicking.
371        let cut = &b64[..b64.len() - 2];
372        assert_eq!(base64_prefix_dims(cut), Some((1278, 1152)));
373    }
374
375    /// protects: the downscale pass keeps a fitting picture byte-identical
376    /// (no gratuitous re-encode) and shrinks a too-large one to the
377    /// 1568px long edge in the same format. fails_when: every send re-encodes
378    /// and degrades, or a too-large picture keeps its size. no_claim: the
379    /// exact resampling filter's visual quality.
380    #[test]
381    fn downscale_shrinks_only_what_does_not_fit() {
382        let small = png_bytes(320, 200);
383        let (kept, original, final_dims) = downscale_to_fit(&small).expect("small fits");
384        assert_eq!(kept, small, "a fitting picture is byte-identical");
385        assert_eq!(original, (320, 200));
386        assert_eq!(final_dims, (320, 200));
387
388        let big = png_bytes(3200, 800);
389        let (shrunk, original, final_dims) = downscale_to_fit(&big).expect("big shrinks");
390        assert_eq!(original, (3200, 800));
391        assert_eq!(final_dims, (1568, 392), "long edge lands on the cap");
392        assert!(shrunk.len() < big.len(), "the wire payload is smaller");
393        assert_eq!(sniff_mime(&shrunk), Some("image/png"), "format preserved");
394    }
395
396    /// protects: the base64 size math the budget judges by (padded standard
397    /// alphabet). fails_when: the measured size drifts from the true wire
398    /// size and the budget lies. no_claim: which side of the line a given
399    /// screenshot lands on.
400    #[test]
401    fn base64_size_math_matches_the_wire() {
402        assert_eq!(base64_len(0), 0);
403        assert_eq!(base64_len(1), 4);
404        assert_eq!(base64_len(3), 4);
405        assert_eq!(base64_len(4), 8);
406        for n in [0usize, 1, 2, 3, 57, 58, 1000] {
407            assert_eq!(base64_len(n), to_base64(&vec![0u8; n]).len());
408        }
409    }
410
411    /// protects: every picture of an in-budget message travels — the count
412    /// gate is gone and the budget is measured, not guessed (AC4's "no
413    /// silent drop" path). fails_when: an older picture is quietly thinned
414    /// to make room. no_claim: how a vision model uses the pictures.
415    #[test]
416    fn in_budget_messages_keep_every_picture() {
417        let mut messages = vec![
418            ChatMessage::user("look at the boards"),
419            ChatMessage::tool_with_images(
420                "t1",
421                "shot 1",
422                vec![base64_image(200, 200), base64_image(200, 200)],
423            ),
424            ChatMessage::tool_with_images("t2", "shot 2", vec![base64_image(200, 200)]),
425        ];
426        apply_image_budget(&mut messages).expect("small pictures fit");
427        let count: usize = messages
428            .iter()
429            .map(|m| match m {
430                ChatMessage::Tool { images, .. } | ChatMessage::User { images, .. } => images.len(),
431                _ => 0,
432            })
433            .sum();
434        assert_eq!(count, 3, "all three pictures are still attached");
435    }
436
437    /// protects: a picture over the per-image line refuses the whole send
438    /// with a size inventory naming each item — the refusal is loud and
439    /// complete (AC4). fails_when: the oversized picture is silently dropped
440    /// or silently shrunk further, or the error lacks the sizes. no_claim:
441    /// that 3.5 MB is the right line (a named constant, adjustable).
442    #[test]
443    fn an_oversized_image_refuses_the_send_with_an_inventory() {
444        // Unparseable filler bytes: no downscale pass applies, so the
445        // measured base64 size is what the budget judges.
446        let fat = ImageAttachment::Base64 {
447            data: "x".repeat(MAX_IMAGE_BASE64_BYTES + 1),
448            media_type: Some("image/png".to_string()),
449            detail: None,
450        };
451        let mut messages = vec![ChatMessage::tool_with_images("t1", "a fat one", vec![fat])];
452        let err = apply_image_budget(&mut messages).expect_err("over the per-image line");
453        let text = err.to_string();
454        assert!(
455            text.contains("request NOT sent"),
456            "the refusal is explicit: {text}"
457        );
458        assert!(
459            text.contains("OVER per-image budget"),
460            "the violator is named: {text}"
461        );
462        assert!(
463            text.contains("image 1:"),
464            "the inventory lists the item: {text}"
465        );
466        let ChatMessage::Tool { images, .. } = &messages[0] else {
467            panic!("expected a tool result");
468        };
469        assert_eq!(
470            images.len(),
471            1,
472            "the picture is still attached to the message"
473        );
474    }
475
476    /// protects: the per-message line judges the SUM of a message's
477    /// pictures, each individually under the per-image line. fails_when:
478    /// four mid-size pictures sneak past as a 12 MB+ message. no_claim: the
479    /// per-message number's wisdom (named constant, adjustable).
480    #[test]
481    fn a_message_sum_over_the_cap_refuses_the_send() {
482        let mid = ImageAttachment::Base64 {
483            data: "y".repeat(MAX_IMAGE_BASE64_BYTES - 10),
484            media_type: Some("image/png".to_string()),
485            detail: None,
486        };
487        let mut messages = vec![ChatMessage::tool_with_images(
488            "t1",
489            "four mid-size pictures",
490            vec![mid.clone(), mid.clone(), mid.clone(), mid],
491        )];
492        let err = apply_image_budget(&mut messages).expect_err("sum crosses the line");
493        let text = err.to_string();
494        assert!(
495            text.contains("OVER per-message budget"),
496            "the sum violator is named: {text}"
497        );
498    }
499
500    /// protects: a fitting picture that CAN be parsed is downscaled before
501    /// it is judged — the wire sees the post-shrink size, and the inventory
502    /// says so. fails_when: the budget refuses a picture for size it would
503    /// have shed. no_claim: the shrink's visual quality.
504    #[test]
505    fn the_budget_judges_post_shrink_sizes() {
506        let big = base64_image(3200, 800);
507        let raw_len = match &big {
508            ImageAttachment::Base64 { data, .. } => data.len(),
509            _ => unreachable!(),
510        };
511        assert!(
512            raw_len < MAX_IMAGE_BASE64_BYTES,
513            "fixture: under the line before"
514        );
515        let mut messages = vec![ChatMessage::tool_with_images("t1", "shot", vec![big])];
516        apply_image_budget(&mut messages).expect("shrinks to fit");
517        let ChatMessage::Tool { images, .. } = &messages[0] else {
518            panic!("expected a tool result");
519        };
520        let ImageAttachment::Base64 { data, .. } = &images[0] else {
521            panic!("expected a base64 attachment");
522        };
523        assert!(data.len() < raw_len, "the wire payload was shrunk");
524        assert_eq!(sniff_mime(&from_base64(data).unwrap()), Some("image/png"));
525    }
526}