Skip to main content

agentmux_srv_core/backend/transcript/
images.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! How many images an agent's conversation holds, read from its transcript. A model that cannot read images
5//! (`catalog::Model::images`) must not be picked for a conversation that still holds one, and the pane's own count
6//! only sees the part of the feed it has loaded, so srv counts in the transcript store, which keeps all of it.
7//!
8//! An image reaches the harness as the `<attached_files>` list srv appends to the user's message (`attachments::prompt`):
9//! a found one as `N. name — <path>.send.<image extension>`, a missing one as `- name.png — (no longer available)`.
10//! Only user lines are read, so an agent's own text that quotes such a list counts for nothing.
11
12use std::collections::{HashMap, HashSet};
13use std::sync::{Arc, Mutex, OnceLock};
14
15use serde_json::Value;
16
17use crate::backend::storage::filestore::FileStore;
18
19const FILE: &str = "output";
20/// How much of the transcript is read at a time; a line longer than this widens the read.
21const CHUNK: i64 = 4 * 1024 * 1024;
22const IMAGE_EXTENSIONS: &[&str] = &["png", "jpg", "jpeg", "gif", "webp", "bmp", "tif", "tiff"];
23
24/// What was counted in a zone, and where the count stopped: a transcript only grows, so the next count reads on from there.
25/// `created` is when the file was made: an archive deletes the file and a new conversation makes it again, and its count
26/// starts at the top.
27#[derive(Clone, Copy, Default)]
28struct Counted {
29    created: i64,
30    pos: i64,
31    images: u32,
32}
33
34fn cache() -> &'static Mutex<HashMap<String, Counted>> {
35    static CACHE: OnceLock<Mutex<HashMap<String, Counted>>> = OnceLock::new();
36    CACHE.get_or_init(Default::default)
37}
38
39/// Drops what was counted in `zone`, for a transcript rewritten in place (history repair): the file keeps its creation
40/// time and may not be shorter, so nothing else tells the next count that its bytes are not the ones it read.
41pub fn forget(zone: &str) {
42    cache().lock().unwrap_or_else(|e| e.into_inner()).remove(zone);
43}
44
45/// What the last finished count of `zone` found: a floor for the transcript as it is now, and `None` before the first
46/// count. It reads nothing, so a caller with a deadline can ask it where [`count_in_zone`] would first read the whole file
47/// (a big agent's transcript is gigabytes).
48pub fn counted(zone: &str) -> Option<u32> {
49    cache().lock().unwrap_or_else(|e| e.into_inner()).get(zone).map(|c| c.images)
50}
51
52/// Counts `zone` in the background, so [`counted`] has an answer once it finishes and the next count reads only what was
53/// added since. Nothing starts while a count of the zone is already running.
54pub fn warm(gfs: &Arc<FileStore>, zone: &str) {
55    static RUNNING: OnceLock<Mutex<HashSet<String>>> = OnceLock::new();
56    let running = RUNNING.get_or_init(Default::default);
57    if !running.lock().unwrap_or_else(|e| e.into_inner()).insert(zone.to_string()) {
58        return;
59    }
60    let (gfs, zone) = (gfs.clone(), zone.to_string());
61    std::thread::spawn(move || {
62        if let Err(e) = count_in_zone(&gfs, &zone) {
63            tracing::warn!(zone = %zone, error = %e, "the images in the conversation were not counted");
64        }
65        running.lock().unwrap_or_else(|e| e.into_inner()).remove(&zone);
66    });
67}
68
69/// The images in the user messages of `zone`'s transcript; 0 when there is none.
70pub fn count_in_zone(gfs: &FileStore, zone: &str) -> Result<u32, String> {
71    let Some(stat) = gfs.stat(zone, FILE).map_err(|e| format!("stat transcript: {e}"))? else {
72        cache().lock().unwrap_or_else(|e| e.into_inner()).remove(zone);
73        return Ok(0);
74    };
75    let mut done = cache().lock().unwrap_or_else(|e| e.into_inner()).get(zone).copied().unwrap_or_default();
76    // Made again since the last count, or shorter than where it stopped (trimmed): count it again from the start.
77    if stat.createdts != done.created || stat.size < done.pos {
78        done = Counted { created: stat.createdts, ..Counted::default() };
79    }
80    let mut window = CHUNK;
81    while done.pos < stat.size {
82        let (at, data) = gfs.read_at(zone, FILE, done.pos, window).map_err(|e| format!("read transcript: {e}"))?;
83        if data.is_empty() {
84            break;
85        }
86        // Whole lines only; the last one is cut by the window unless the file ends there.
87        let end = if at + data.len() as i64 >= stat.size { data.len() } else { data.iter().rposition(|b| *b == b'\n').map_or(0, |i| i + 1) };
88        if end == 0 {
89            window = window.saturating_mul(2);
90            continue;
91        }
92        window = CHUNK;
93        done.images += data[..end].split(|b| *b == b'\n').map(images_in_line).sum::<u32>();
94        done.pos = at + end as i64;
95    }
96    cache().lock().unwrap_or_else(|e| e.into_inner()).insert(zone.to_string(), done);
97    Ok(done.images)
98}
99
100/// The images one transcript line lists, if it is a user message.
101pub fn images_in_line(line: &[u8]) -> u32 {
102    // Most lines name no attachment: skip parsing them.
103    if !contains(line, b"<attached_") {
104        return 0;
105    }
106    let Ok(v) = serde_json::from_slice::<Value>(line) else { return 0 };
107    if v.get("type").and_then(Value::as_str) != Some("user") {
108        return 0;
109    }
110    let mut texts = Vec::new();
111    match v.pointer("/message/content") {
112        Some(Value::String(s)) => texts.push(s.as_str()),
113        Some(Value::Array(items)) => texts.extend(items.iter().filter_map(|i| i.get("text").and_then(Value::as_str))),
114        _ => {}
115    }
116    texts.into_iter().map(images_in_text).sum()
117}
118
119fn contains(hay: &[u8], needle: &[u8]) -> bool {
120    hay.windows(needle.len()).any(|w| w == needle)
121}
122
123fn has_image_extension(name: &str) -> bool {
124    name.rsplit_once('.').is_some_and(|(_, ext)| IMAGE_EXTENSIONS.contains(&ext.to_ascii_lowercase().as_str()))
125}
126
127/// The images in the `<attached_files>` (or `<attached_images>`) block at the end of a message.
128fn images_in_text(text: &str) -> u32 {
129    let mut in_block = false;
130    let mut n = 0;
131    for line in text.lines() {
132        let line = line.trim();
133        if line == "<attached_files>" || line == "<attached_images>" {
134            in_block = true;
135        } else if line == "</attached_files>" || line == "</attached_images>" {
136            in_block = false;
137        } else if in_block {
138            if let Some(name) = line.strip_prefix("- ").and_then(|l| l.strip_suffix(" — (no longer available)")) {
139                n += u32::from(has_image_extension(name));
140            } else if let Some((_, path)) = line.rsplit_once(" — ") {
141                // A found image is sent as its derived file: `<sha256>.<version>.send.<extension>`.
142                n += u32::from(path.contains(".send.") && has_image_extension(path.trim()));
143            }
144        }
145    }
146    n
147}
148
149#[cfg(test)]
150#[path = "images_tests.rs"]
151mod tests;