Skip to main content

agentmux_srv_core/backend/attachments/
prompt.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Turning a message's attachments into what the agent receives
5//! (docs/specs/SPEC_AGENT_PANE_IMAGE_ATTACHMENTS_2026_09_26.md §6.6,
6//! SPEC_AGENT_PANE_FILE_ATTACHMENTS_2026_09_26.md §7):
7//!
8//! - every provider gets a numbered list appended to the text, in an
9//!   `<attached_files>` block: each image's send-copy, each other file as a
10//!   copy under its real name, plus notes (type, pages, text version), so
11//!   any agent that can open a local file can reach every attachment;
12//! - Claude (stream-json) additionally gets images inline as `image` blocks
13//!   and PDFs of up to 100 pages as `document` blocks, within a count and
14//!   size budget.
15//!
16//! The block is also how the pane rebuilds the tiles on reload: each line
17//! names the attachment and ends with a path that carries the attachment id
18//! (a `<sha256>.` file name or a `named/<sha256>/` folder).
19
20use std::path::PathBuf;
21
22use base64::Engine;
23
24use super::Service;
25use crate::backend::rpc_types::AttachmentRef;
26
27/// Inline at most this many base64 bytes in one Claude message. The API
28/// caps a request at 32 MB, and the whole conversation is resent each turn.
29pub const INLINE_MAX_B64_BYTES: usize = 20 * 1024 * 1024;
30pub const DEFAULT_INLINE_MAX_COUNT: usize = 20;
31/// Inline at most this much base64 across one Claude session. Claude Code
32/// keeps every inline image in its own session transcript.
33pub const DEFAULT_SESSION_INLINE_MB: u64 = 50;
34/// Claude's PDF support takes at most 100 pages per request on models with
35/// less than a 1M-token context; longer PDFs go by path and text version.
36pub const INLINE_PDF_MAX_PAGES: u32 = 100;
37
38pub const BLOCK_OPEN: &str = "<attached_files>";
39pub const BLOCK_CLOSE: &str = "</attached_files>";
40
41/// One attachment resolved to the file the agent gets.
42#[derive(Debug, Clone, PartialEq, Eq)]
43pub struct Resolved {
44    /// 1-based, matching the composer's tile badges.
45    pub number: usize,
46    pub name: String,
47    pub path: PathBuf,
48    pub mime: String,
49    pub page_count: Option<u32>,
50    /// Shown in square brackets after the name.
51    pub note: Option<String>,
52}
53
54impl Resolved {
55    fn is_image(&self) -> bool {
56        self.mime.starts_with("image/") && self.mime != "image/svg+xml"
57    }
58
59    /// Whether Claude can take this inline: a decoded image, or a PDF short
60    /// enough for its document support.
61    fn inlineable(&self) -> bool {
62        self.is_image()
63            || (self.mime == "application/pdf"
64                && self.page_count.is_some_and(|n| n <= INLINE_PDF_MAX_PAGES))
65    }
66}
67
68/// Everything a turn needs from its attachments.
69#[derive(Debug, Clone, Default)]
70pub struct Prepared {
71    /// Appended to the message text.
72    pub list: String,
73    /// Anthropic `image` / `document` content blocks, in order. Empty unless
74    /// asked for.
75    pub inline: Vec<serde_json::Value>,
76}
77
78/// Resolve refs to what the agent gets. Refs whose files are gone (swept, or
79/// never finished processing) come back as names in the second list.
80/// Blocking.
81pub fn resolve(svc: &Service, refs: &[AttachmentRef]) -> (Vec<Resolved>, Vec<String>) {
82    let mut found = Vec::new();
83    let mut missing = Vec::new();
84    for (i, r) in refs.iter().enumerate() {
85        let name = clean_name(&r.name);
86        match svc.send_target(&r.id, &name) {
87            Some(t) => found.push(Resolved {
88                number: i + 1,
89                name,
90                path: t.path,
91                mime: t.mime,
92                page_count: t.page_count,
93                note: t.note,
94            }),
95            None => missing.push(name),
96        }
97    }
98    (found, missing)
99}
100
101/// Build the list and (when `inline_max_count > 0`) the inline blocks, using
102/// at most `inline_budget` base64 bytes (further capped at
103/// [`INLINE_MAX_B64_BYTES`] per message). Reads the inlined files from disk.
104/// Blocking.
105pub fn prepare(
106    items: &[Resolved],
107    missing: &[String],
108    inline_max_count: usize,
109    inline_budget: u64,
110) -> Prepared {
111    prepare_from(None, items, missing, inline_max_count, inline_budget)
112}
113
114/// [`prepare`] for files another agent sent with a jekt: the list's lead
115/// names `sender` (`jekt_list_block`).
116pub fn prepare_from(
117    sender: Option<&str>,
118    items: &[Resolved],
119    missing: &[String],
120    inline_max_count: usize,
121    inline_budget: u64,
122) -> Prepared {
123    let mut inline = Vec::new();
124    let mut inlined: Vec<usize> = Vec::new();
125    let mut budget = (INLINE_MAX_B64_BYTES as u64).min(inline_budget) as usize;
126    for item in items.iter().filter(|i| i.inlineable()) {
127        if inline.len() >= inline_max_count {
128            break;
129        }
130        let Ok(bytes) = std::fs::read(&item.path) else {
131            continue;
132        };
133        let encoded = base64::engine::general_purpose::STANDARD.encode(&bytes);
134        if encoded.len() > budget {
135            // A smaller one further down may still fit.
136            continue;
137        }
138        budget -= encoded.len();
139        inline.push(if item.is_image() {
140            serde_json::json!({
141                "type": "image",
142                "source": { "type": "base64", "media_type": item.mime, "data": encoded },
143            })
144        } else {
145            serde_json::json!({
146                "type": "document",
147                "source": { "type": "base64", "media_type": "application/pdf", "data": encoded },
148                "title": item.name,
149            })
150        });
151        inlined.push(item.number);
152    }
153    Prepared {
154        list: list_block_from(sender, items, missing, &inlined),
155        inline,
156    }
157}
158
159/// The decoded pictures among `items`, as the paths of their send-copies, in the order of the tray: what a
160/// provider that takes a picture by path (Codex's `localImage`) is given, besides the list in the text.
161pub fn image_paths(items: &[Resolved]) -> Vec<String> {
162    items.iter().filter(|i| i.is_image()).map(|i| i.path.to_string_lossy().into_owned()).collect()
163}
164
165/// Base64 bytes carried by inline blocks, for the session budget.
166pub fn inline_bytes(blocks: &[serde_json::Value]) -> u64 {
167    blocks
168        .iter()
169        .filter_map(|b| b.pointer("/source/data").and_then(|d| d.as_str()))
170        .map(|d| d.len() as u64)
171        .sum()
172}
173
174/// The `<attached_files>` block. `inlined` holds the numbers of the items
175/// Claude was also given inline.
176pub fn list_block(items: &[Resolved], missing: &[String], inlined: &[usize]) -> String {
177    list_block_from(None, items, missing, inlined)
178}
179
180/// The `<attached_files>` block for files another agent sent with a jekt
181/// (SPEC_JEKT_FILE_TRANSFER_2026_10_05.md §6.2): the same list, with a lead
182/// naming the sender instead of the user.
183pub fn jekt_list_block(sender: &str, items: &[Resolved], missing: &[String], inlined: &[usize]) -> String {
184    list_block_from(Some(sender), items, missing, inlined)
185}
186
187fn list_block_from(sender: Option<&str>, items: &[Resolved], missing: &[String], inlined: &[usize]) -> String {
188    let total = items.len() + missing.len();
189    let all_images = missing.is_empty() && items.iter().all(|i| i.is_image());
190    let (one, many) = if all_images {
191        ("image", "images")
192    } else {
193        ("file", "files")
194    };
195    let mut out = String::new();
196    out.push_str(BLOCK_OPEN);
197    out.push('\n');
198    let noun = if total == 1 { one } else { many };
199    out.push_str(&match sender {
200        None => format!("The user attached {total} {noun}. The numbers match how the user refers to them."),
201        Some(sender) => format!("{sender} sent {total} {noun} with this message."),
202    });
203    if !inlined.is_empty() && inlined.len() == items.len() {
204        out.push_str(" They are shown above; the files are listed here too.");
205    } else if !inlined.is_empty() {
206        // Name the inlined ones by their real numbers: a missing or
207        // non-inlined attachment shifts them off 1..=n.
208        let (one, many) = if all_images {
209            ("Image", "Images")
210        } else {
211            ("File", "Files")
212        };
213        let noun = if inlined.len() == 1 { one } else { many };
214        let verb = if inlined.len() == 1 { "is" } else { "are" };
215        out.push_str(&format!(
216            " {noun} {} {verb} shown above. Open the others from these paths with your file or image viewing tool when you need them.",
217            number_list(inlined)
218        ));
219    } else if !items.is_empty() {
220        out.push_str(
221            " Open them from these paths with your file or image viewing tool when you need them.",
222        );
223    }
224    out.push('\n');
225    for item in items {
226        let note = item
227            .note
228            .as_deref()
229            .map(|n| format!(" [{n}]"))
230            .unwrap_or_default();
231        out.push_str(&format!(
232            "{}. {}{note} — {}\n",
233            item.number,
234            item.name,
235            item.path.display()
236        ));
237    }
238    for name in missing {
239        out.push_str(&format!("- {name} — (no longer available)\n"));
240    }
241    out.push_str(BLOCK_CLOSE);
242    out
243}
244
245/// "1–3", "2, 4 and 5", "1 and 2": runs of three or more consecutive
246/// numbers collapse to a range.
247fn number_list(nums: &[usize]) -> String {
248    let mut parts: Vec<String> = Vec::new();
249    let mut i = 0;
250    while i < nums.len() {
251        let mut j = i;
252        while j + 1 < nums.len() && nums[j + 1] == nums[j] + 1 {
253            j += 1;
254        }
255        if j - i >= 2 {
256            parts.push(format!("{}–{}", nums[i], nums[j]));
257        } else {
258            parts.extend(nums[i..=j].iter().map(|n| n.to_string()));
259        }
260        i = j + 1;
261    }
262    match parts.len() {
263        0 => String::new(),
264        1 => parts.remove(0),
265        n => format!("{} and {}", parts[..n - 1].join(", "), parts[n - 1]),
266    }
267}
268
269/// The user's text with the attachment list after it.
270pub fn append(message: &str, list: &str) -> String {
271    if list.is_empty() {
272        return message.to_string();
273    }
274    let trimmed = message.trim_end();
275    if trimmed.is_empty() {
276        list.to_string()
277    } else {
278        format!("{trimmed}\n\n{list}")
279    }
280}
281
282/// Names go into a one-line list entry; keep them on one line and short.
283fn clean_name(name: &str) -> String {
284    let one_line: String = name
285        .chars()
286        .map(|c| if c.is_control() { ' ' } else { c })
287        .collect();
288    let trimmed = one_line.trim();
289    let short: String = trimmed.chars().take(120).collect();
290    if short.is_empty() {
291        "image".to_string()
292    } else {
293        short
294    }
295}
296
297/// A Claude stream-json user line. With no images, `content` is the plain
298/// string it always was; with images, the image blocks come first and the
299/// text last, as the Messages API recommends.
300pub fn claude_user_line(message: String, images: Vec<serde_json::Value>) -> String {
301    let content = if images.is_empty() {
302        serde_json::Value::String(message)
303    } else {
304        let mut blocks = images;
305        blocks.push(serde_json::json!({ "type": "text", "text": message }));
306        serde_json::Value::Array(blocks)
307    };
308    serde_json::json!({
309        "type": "user",
310        "message": { "role": "user", "content": content }
311    })
312    .to_string()
313}
314
315/// The form of a Claude stdin line that AgentMux stores for replay: image
316/// blocks dropped and the content collapsed back to its text, which still
317/// holds the `<attached_images>` list. Every reader of stored user lines
318/// expects `content` to be a string, and a stored line should never carry
319/// megabytes of base64. Lines without an array `content` pass through.
320pub fn persisted_line(json_str: &str) -> std::borrow::Cow<'_, str> {
321    let Ok(mut v) = serde_json::from_str::<serde_json::Value>(json_str) else {
322        return json_str.into();
323    };
324    let Some(content) = v.pointer_mut("/message/content") else {
325        return json_str.into();
326    };
327    let Some(blocks) = content.as_array() else {
328        return json_str.into();
329    };
330    let text: Vec<&str> = blocks
331        .iter()
332        .filter(|b| b.get("type").and_then(|t| t.as_str()) == Some("text"))
333        .filter_map(|b| b.get("text").and_then(|t| t.as_str()))
334        .collect();
335    *content = serde_json::Value::String(text.join("\n\n"));
336    v.to_string().into()
337}
338
339#[cfg(test)]
340mod tests {
341    use super::*;
342
343    fn item(n: usize, name: &str, path: &str) -> Resolved {
344        Resolved {
345            number: n,
346            name: name.into(),
347            path: path.into(),
348            mime: "image/png".into(),
349            page_count: None,
350            note: None,
351        }
352    }
353
354    fn file(
355        n: usize,
356        name: &str,
357        path: &str,
358        mime: &str,
359        pages: Option<u32>,
360        note: Option<&str>,
361    ) -> Resolved {
362        Resolved {
363            number: n,
364            name: name.into(),
365            path: path.into(),
366            mime: mime.into(),
367            page_count: pages,
368            note: note.map(str::to_string),
369        }
370    }
371
372    #[test]
373    fn the_pictures_a_provider_takes_by_path_are_the_decoded_images_in_tray_order() {
374        let items = vec![
375            item(1, "a.png", "/s/aa.send.png"),
376            file(2, "notes.pdf", "/s/named/bb/notes.pdf", "application/pdf", Some(3), None),
377            file(3, "logo.svg", "/s/named/cc/logo.svg", "image/svg+xml", None, None),
378            item(4, "b.jpg", "/s/dd.send.jpg"),
379        ];
380        assert_eq!(image_paths(&items), vec!["/s/aa.send.png".to_string(), "/s/dd.send.jpg".to_string()]);
381        assert!(image_paths(&[]).is_empty());
382    }
383
384    #[test]
385    fn list_numbers_items_and_names_missing_ones() {
386        let items = vec![
387            item(1, "a.png", "/s/aa.v1-e2000.send.png"),
388            item(3, "c.png", "/s/cc.v1-e2000.send.png"),
389        ];
390        let list = list_block(&items, &["b.png".into()], &[]);
391        assert!(list.starts_with(BLOCK_OPEN));
392        assert!(list.ends_with(BLOCK_CLOSE));
393        assert!(
394            list.contains("The user attached 3 files."),
395            "a missing one isn't known to be an image"
396        );
397        assert!(list.contains("\n1. a.png — /s/aa.v1-e2000.send.png\n"));
398        assert!(list.contains("\n3. c.png — /s/cc.v1-e2000.send.png\n"));
399        assert!(list.contains("- b.png — (no longer available)"));
400    }
401
402    #[test]
403    fn list_says_which_images_are_inline() {
404        let items = vec![item(1, "a", "/a"), item(2, "b", "/b")];
405        assert!(list_block(&items, &[], &[1, 2]).contains("They are shown above"));
406        assert!(list_block(&items, &[], &[1]).contains("Image 1 is shown above"));
407        assert!(list_block(&items, &[], &[]).contains("Open them from these paths"));
408        assert!(list_block(&items, &[], &[]).contains("The user attached 2 images."));
409    }
410
411    #[test]
412    fn prepare_from_names_the_sender_and_says_what_is_inline() {
413        let d = tempfile::tempdir().unwrap();
414        let png = d.path().join("a.png");
415        std::fs::write(&png, b"not really a png").unwrap();
416        let items = vec![item(1, "a.png", png.to_str().unwrap())];
417        let p = prepare_from(Some("agentx"), &items, &[], 5, u64::MAX);
418        assert_eq!(p.inline.len(), 1);
419        assert!(p.list.contains("agentx sent 1 image with this message. They are shown above"), "{}", p.list);
420        let none = prepare_from(Some("agentx"), &items, &[], 0, u64::MAX);
421        assert!(none.inline.is_empty() && !none.list.contains("shown above"), "{}", none.list);
422    }
423
424    #[test]
425    fn a_jekt_list_names_its_sender_and_keeps_the_item_lines() {
426        let items = vec![item(1, "a.png", "/s/aa.v1-e2000.send.png")];
427        let list = jekt_list_block("agentx", &items, &[], &[]);
428        assert!(list.contains("agentx sent 1 image with this message. Open them"), "{list}");
429        assert!(!list.contains("The user"));
430        assert!(list.contains("\n1. a.png — /s/aa.v1-e2000.send.png\n"));
431    }
432
433    #[test]
434    fn inline_text_uses_real_numbers_when_an_earlier_image_is_missing() {
435        // refs = [missing, #2, #3]; one inlined.
436        let items = vec![item(2, "b", "/b"), item(3, "c", "/c")];
437        let list = list_block(&items, &["a".into()], &[2]);
438        assert!(list.contains("File 2 is shown above"), "{list}");
439        assert!(!list.contains("File 1 "));
440    }
441
442    #[test]
443    fn files_carry_notes_and_mixed_lists_say_files() {
444        let items = vec![
445            item(1, "shot.png", "/s/aa.v1-e2000.send.png"),
446            file(
447                2,
448                "spec.pdf",
449                "/s/named/cc/spec.pdf",
450                "application/pdf",
451                Some(12),
452                Some("PDF, 12 pages; text version: /t.txt"),
453            ),
454            file(
455                3,
456                "notes.md",
457                "/s/named/dd/notes.md",
458                "text/plain; charset=utf-8",
459                None,
460                None,
461            ),
462        ];
463        let list = list_block(&items, &[], &[1, 2]);
464        assert!(list.contains("The user attached 3 files."), "{list}");
465        assert!(list.contains("Files 1 and 2 are shown above"), "{list}");
466        assert!(
467            list.contains(
468                "\n2. spec.pdf [PDF, 12 pages; text version: /t.txt] — /s/named/cc/spec.pdf\n"
469            ),
470            "{list}"
471        );
472        assert!(
473            list.contains("\n3. notes.md — /s/named/dd/notes.md\n"),
474            "{list}"
475        );
476    }
477
478    #[test]
479    fn short_pdfs_go_inline_as_documents_long_ones_and_text_do_not() {
480        let d = tempfile::tempdir().unwrap();
481        let write = |name: &str| {
482            let p = d.path().join(name);
483            std::fs::write(&p, b"%PDF-1.4 tiny").unwrap();
484            p
485        };
486        let items = vec![
487            file(
488                1,
489                "short.pdf",
490                write("s.pdf").to_str().unwrap(),
491                "application/pdf",
492                Some(3),
493                None,
494            ),
495            file(
496                2,
497                "long.pdf",
498                write("l.pdf").to_str().unwrap(),
499                "application/pdf",
500                Some(250),
501                None,
502            ),
503            file(
504                3,
505                "unknown.pdf",
506                write("u.pdf").to_str().unwrap(),
507                "application/pdf",
508                None,
509                None,
510            ),
511            file(
512                4,
513                "notes.md",
514                write("n.md").to_str().unwrap(),
515                "text/plain; charset=utf-8",
516                None,
517                None,
518            ),
519        ];
520        let p = prepare(&items, &[], 20, u64::MAX);
521        assert_eq!(p.inline.len(), 1);
522        assert_eq!(p.inline[0]["type"], "document");
523        assert_eq!(p.inline[0]["source"]["media_type"], "application/pdf");
524        assert_eq!(p.inline[0]["title"], "short.pdf");
525        assert!(p.list.contains("File 1 is shown above"), "{}", p.list);
526        // The stored line drops document blocks like image blocks.
527        let line = claude_user_line("see".into(), p.inline.clone());
528        assert_eq!(
529            serde_json::from_str::<serde_json::Value>(&persisted_line(&line)).unwrap()["message"]
530                ["content"],
531            "see"
532        );
533    }
534
535    #[test]
536    fn number_lists_read_naturally() {
537        assert_eq!(number_list(&[1]), "1");
538        assert_eq!(number_list(&[1, 2]), "1 and 2");
539        assert_eq!(number_list(&[1, 2, 3]), "1–3");
540        assert_eq!(number_list(&[2, 4, 5]), "2, 4 and 5");
541        assert_eq!(number_list(&[1, 2, 3, 7]), "1–3 and 7");
542    }
543
544    #[test]
545    fn append_puts_the_list_after_the_text() {
546        assert_eq!(append("look\n", "<L>"), "look\n\n<L>");
547        assert_eq!(append("   ", "<L>"), "<L>");
548        assert_eq!(append("hi", ""), "hi");
549    }
550
551    #[test]
552    fn names_stay_on_one_line() {
553        assert_eq!(clean_name("a\nb\tc.png"), "a b c.png");
554        assert_eq!(clean_name("  "), "image");
555        assert_eq!(clean_name(&"x".repeat(500)).chars().count(), 120);
556    }
557
558    #[test]
559    fn prepare_inlines_within_count_and_reads_files() {
560        let d = tempfile::tempdir().unwrap();
561        let paths: Vec<_> = (0..3)
562            .map(|i| {
563                let p = d.path().join(format!("{i}.png"));
564                std::fs::write(&p, [0x89, b'P', b'N', b'G', i]).unwrap();
565                p
566            })
567            .collect();
568        let items: Vec<_> = paths
569            .iter()
570            .enumerate()
571            .map(|(i, p)| Resolved {
572                number: i + 1,
573                name: format!("{i}.png"),
574                path: p.clone(),
575                mime: "image/png".into(),
576                page_count: None,
577                note: None,
578            })
579            .collect();
580        let p = prepare(&items, &[], 2, u64::MAX);
581        assert_eq!(p.inline.len(), 2);
582        assert_eq!(p.inline[0]["source"]["media_type"], "image/png");
583        assert!(p.list.contains("Images 1 and 2 are shown above"));
584        assert_eq!(
585            inline_bytes(&p.inline),
586            16,
587            "two 5-byte files are 8 base64 chars each"
588        );
589        assert!(prepare(&items, &[], 0, u64::MAX).inline.is_empty());
590        // A spent session budget means paths only.
591        let spent = prepare(&items, &[], 20, 10);
592        assert_eq!(spent.inline.len(), 1);
593        assert!(prepare(&items, &[], 20, 0).inline.is_empty());
594    }
595
596    #[test]
597    fn claude_line_without_images_is_unchanged_and_with_images_puts_text_last() {
598        // Exactly the expression `send_message_from` used before images existed.
599        let before = serde_json::json!({
600            "type": "user",
601            "message": { "role": "user", "content": "hi" }
602        })
603        .to_string();
604        assert_eq!(claude_user_line("hi".into(), vec![]), before);
605        let img = serde_json::json!({ "type": "image", "source": { "type": "base64", "media_type": "image/png", "data": "AA" } });
606        let line = claude_user_line("look".into(), vec![img.clone()]);
607        let v: serde_json::Value = serde_json::from_str(&line).unwrap();
608        assert_eq!(v["message"]["content"][0], img);
609        assert_eq!(
610            v["message"]["content"][1],
611            serde_json::json!({ "type": "text", "text": "look" })
612        );
613        // What gets stored is the text alone.
614        let stored: serde_json::Value = serde_json::from_str(&persisted_line(&line)).unwrap();
615        assert_eq!(stored["message"]["content"], "look");
616    }
617
618    #[test]
619    fn persisted_line_drops_images_and_keeps_text_as_a_string() {
620        let line = serde_json::json!({
621            "type": "user",
622            "message": { "role": "user", "content": [
623                { "type": "image", "source": { "type": "base64", "media_type": "image/png", "data": "AAAA" } },
624                { "type": "text", "text": "hello\n\n<attached_images>\n1. a — /p\n</attached_images>" }
625            ]}
626        })
627        .to_string();
628        let stored = persisted_line(&line);
629        let v: serde_json::Value = serde_json::from_str(&stored).unwrap();
630        assert_eq!(
631            v["message"]["content"],
632            "hello\n\n<attached_images>\n1. a — /p\n</attached_images>"
633        );
634        assert!(!stored.contains("AAAA"));
635        // Plain string content is untouched, byte for byte.
636        let plain = r#"{"type":"user","message":{"role":"user","content":"hi"}}"#;
637        assert_eq!(persisted_line(plain), plain);
638    }
639}