Skip to main content

agentmux_mcp/tools/
send_files.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! `SendMessage`'s `files`: each file is put in this agent's own attachment
5//! store first, through srv's upload route, and the jekt then names them by
6//! hash (docs/specs/SPEC_JEKT_FILE_TRANSFER_2026_10_05.md §3.1). This
7//! process runs as the agent, so it sends exactly what the agent can read.
8
9use agentmux_common::jekt_files::{self, JektFile};
10
11use super::*;
12
13/// The most one file, and all of a jekt's files together, may weigh on the
14/// same machine (spec §5).
15pub(super) const MAX_FILE_BYTES: u64 = 100 * 1024 * 1024;
16pub(super) const MAX_TOTAL_BYTES: u64 = 200 * 1024 * 1024;
17/// An upload waits for srv to store and process the file (thumbnails, a
18/// document's text version), well past the client's usual 10 s.
19const UPLOAD_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(300);
20
21/// The `files` argument: `None` when absent or empty.
22pub(super) fn files_arg(arguments: &Value) -> Result<Option<Vec<String>>> {
23    let Some(v) = arguments.get("files").filter(|v| !v.is_null()) else {
24        return Ok(None);
25    };
26    let list = v.as_array().ok_or_else(|| anyhow::anyhow!("files must be a list of file paths"))?;
27    let paths = list
28        .iter()
29        .map(|p| {
30            p.as_str()
31                .map(str::trim)
32                .filter(|s| !s.is_empty())
33                .map(str::to_string)
34                .ok_or_else(|| anyhow::anyhow!("files must be a list of file paths"))
35        })
36        .collect::<Result<Vec<_>>>()?;
37    Ok((!paths.is_empty()).then_some(paths))
38}
39
40/// One file to send: where it is and how big it is.
41#[derive(Debug)]
42pub(super) struct Local {
43    pub path: std::path::PathBuf,
44    pub name: String,
45    pub size: u64,
46}
47
48/// What a call may carry: how many files, and how many bytes in all (one file is at most [`MAX_FILE_BYTES`]).
49#[derive(Debug, Clone, Copy)]
50pub(super) struct Limits {
51    pub max_files: usize,
52    pub max_total: u64,
53    /// What the files go in, for the messages: "message" or "call".
54    pub per: &'static str,
55}
56
57/// A jekt's limits (spec §5).
58const MESSAGE_LIMITS: Limits = Limits { max_files: jekt_files::MAX_FILES, max_total: MAX_TOTAL_BYTES, per: "message" };
59
60/// What to add to a "No such file" for a container agent: its file tools only see its own container, so a path on the
61/// host (a screenshot's older answer, a file in a host folder) is simply not there.
62fn missing_hint(kind: std::io::ErrorKind, in_container: bool) -> &'static str {
63    if in_container && kind == std::io::ErrorKind::NotFound {
64        " (not inside your container: a file on the host cannot be read from here. Put the file under /workspace, or take the screenshot or recording again and use the path it gives)"
65    } else {
66        ""
67    }
68}
69
70/// Check every path before anything is uploaded: each names a readable,
71/// non-empty file within the limits. The error names the file.
72pub(super) fn check(paths: &[String]) -> Result<Vec<Local>> {
73    check_within(paths, MESSAGE_LIMITS)
74}
75
76/// [`check`] against another call's limits (a task's files are not a jekt's).
77pub(super) fn check_within(paths: &[String], limits: Limits) -> Result<Vec<Local>> {
78    let Limits { max_files, max_total, per } = limits;
79    if paths.len() > max_files {
80        anyhow::bail!("{} files is more than the limit of {max_files} per {per}", paths.len());
81    }
82    let mut out = Vec::with_capacity(paths.len());
83    let mut total = 0u64;
84    for given in paths {
85        let path = std::path::PathBuf::from(resolve_workdir_path(given));
86        let meta = std::fs::metadata(&path)
87            .map_err(|e| anyhow::anyhow!("{given}: {e}{}", missing_hint(e.kind(), crate::self_keys::in_container())))?;
88        if meta.is_dir() {
89            anyhow::bail!("{given} is a folder; send the files in it, or an archive of it");
90        }
91        let size = meta.len();
92        if size == 0 {
93            anyhow::bail!("{given} is empty");
94        }
95        if size > MAX_FILE_BYTES {
96            anyhow::bail!("{given} is {} MB, over the {} MB limit per file", size / (1024 * 1024), MAX_FILE_BYTES / (1024 * 1024));
97        }
98        total += size;
99        if total > max_total {
100            anyhow::bail!("these files come to more than the {} MB limit per {per}", max_total / (1024 * 1024));
101        }
102        // Readable now, not only listed.
103        std::fs::File::open(&path).map_err(|e| anyhow::anyhow!("{given}: {e}"))?;
104        let name = jekt_files::clean_name(&path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default());
105        out.push(Local { path, name, size });
106    }
107    Ok(out)
108}
109
110/// Upload each file into this agent's attachment store and return the
111/// manifest, in the order given.
112pub(super) async fn upload(files: Vec<Local>, cx: &ToolCtx<'_>) -> Result<Vec<JektFile>> {
113    let url = format!("{}/api/v1/attachments/upload", cx.local_url.trim_end_matches('/'));
114    let mut manifest = Vec::with_capacity(files.len());
115    for f in files {
116        let file = tokio::fs::File::open(&f.path)
117            .await
118            .map_err(|e| anyhow::anyhow!("{}: {e}", f.path.display()))?;
119        let resp = cx
120            .client
121            .post(&url)
122            .query(&[("name", f.name.as_str())])
123            .header(AUTH_KEY_HEADER, cx.auth_key)
124            .timeout(UPLOAD_TIMEOUT)
125            .body(reqwest::Body::from(file))
126            .send()
127            .await
128            .map_err(|e| anyhow::anyhow!("{}: upload failed: {e}", f.name))?;
129        if !resp.status().is_success() {
130            let status = resp.status();
131            let body: Value = resp.json().await.unwrap_or_default();
132            let why = body.get("error").and_then(Value::as_str).unwrap_or("");
133            anyhow::bail!("{}: upload failed: HTTP {status} {why}", f.name);
134        }
135        let info: Value = resp.json().await.map_err(|e| anyhow::anyhow!("{}: upload answer unreadable: {e}", f.name))?;
136        let sha256 = info.get("id").and_then(Value::as_str).unwrap_or_default().to_string();
137        // What srv stored, not what was on disk a moment ago.
138        let size = info.get("bytes").and_then(Value::as_u64).unwrap_or(f.size);
139        manifest.push(JektFile { sha256, name: f.name, size });
140    }
141    // What srv stored may differ from what was on disk a moment ago: the same limits, compared again.
142    jekt_files::validate_for_tier(&manifest, "host").map_err(|e| anyhow::anyhow!("files refused: {e}"))?;
143    Ok(manifest)
144}
145
146/// What one task call carries: at most 10 files, within a task's 300 MiB (srv enforces the rest: sizes by
147/// kind, and 30 files and 300 MiB per task in all).
148const TASK_LIMITS: Limits = Limits { max_files: 10, max_total: 300 * 1024 * 1024, per: "call" };
149
150/// The `captions` argument, one per file in the same order (missing ones are empty).
151fn captions_for(captions: Option<&Value>, count: usize) -> Result<Vec<String>> {
152    let given: Vec<String> = match captions.filter(|v| !v.is_null()) {
153        None => Vec::new(),
154        Some(v) => v
155            .as_array()
156            .ok_or_else(|| anyhow::anyhow!("captions must be a list of short texts, one per file"))?
157            .iter()
158            .map(|c| c.as_str().map(|s| s.trim().to_string()).ok_or_else(|| anyhow::anyhow!("captions must be a list of short texts, one per file")))
159            .collect::<Result<_>>()?,
160    };
161    if given.len() > count {
162        anyhow::bail!("{} captions for {count} files", given.len());
163    }
164    Ok((0..count).map(|i| given.get(i).cloned().unwrap_or_default()).collect())
165}
166
167/// Check each path, then upload each to srv's task media store; returns what `Tasks` update and submit
168/// carry: `[{sha256, name, caption}]`. Nothing has changed on the task when this fails.
169pub(super) async fn upload_task_media(paths: &[String], captions: Option<&Value>, cx: &ToolCtx<'_>) -> Result<Vec<Value>> {
170    let captions = captions_for(captions, paths.len())?;
171    let files = check_within(paths, TASK_LIMITS)?;
172    let url = format!("{}/agentmux/work/media", cx.local_url.trim_end_matches('/'));
173    let mut out = Vec::with_capacity(files.len());
174    for (f, caption) in files.into_iter().zip(captions) {
175        let file = tokio::fs::File::open(&f.path).await.map_err(|e| anyhow::anyhow!("{}: {e}", f.path.display()))?;
176        let resp = cx
177            .client
178            .post(&url)
179            .query(&[("name", f.name.as_str())])
180            .header(AUTH_KEY_HEADER, cx.auth_key)
181            .timeout(UPLOAD_TIMEOUT)
182            .body(reqwest::Body::from(file))
183            .send()
184            .await
185            .map_err(|e| anyhow::anyhow!("{}: upload failed: {e}", f.name))?;
186        if !resp.status().is_success() {
187            let status = resp.status();
188            let body: Value = resp.json().await.unwrap_or_default();
189            let why = body.get("error").and_then(Value::as_str).unwrap_or("");
190            anyhow::bail!("{}: not attached: {why} (HTTP {status})", f.name);
191        }
192        let info: Value = resp.json().await.map_err(|e| anyhow::anyhow!("{}: upload answer unreadable: {e}", f.name))?;
193        let sha256 = info.get("sha256").and_then(Value::as_str).unwrap_or_default();
194        out.push(serde_json::json!({ "sha256": sha256, "name": f.name, "caption": caption }));
195    }
196    Ok(out)
197}
198
199#[cfg(test)]
200mod tests {
201    use super::*;
202
203    #[test]
204    fn files_arg_reads_a_list_and_ignores_an_empty_one() {
205        assert_eq!(files_arg(&serde_json::json!({})).unwrap(), None);
206        assert_eq!(files_arg(&serde_json::json!({ "files": [] })).unwrap(), None);
207        assert_eq!(files_arg(&serde_json::json!({ "files": null })).unwrap(), None);
208        assert_eq!(
209            files_arg(&serde_json::json!({ "files": [" a.png ", "b.txt"] })).unwrap(),
210            Some(vec!["a.png".to_string(), "b.txt".to_string()])
211        );
212        assert!(files_arg(&serde_json::json!({ "files": "a.png" })).is_err());
213        assert!(files_arg(&serde_json::json!({ "files": [""] })).is_err());
214        assert!(files_arg(&serde_json::json!({ "files": [1] })).is_err());
215    }
216
217    #[test]
218    fn captions_pair_with_files_in_order_and_may_be_fewer() {
219        let c = |v: Value, n| captions_for(Some(&v), n);
220        assert_eq!(captions_for(None, 2).unwrap(), ["", ""]);
221        assert_eq!(c(serde_json::json!(["before", "after"]), 2).unwrap(), ["before", "after"]);
222        assert_eq!(c(serde_json::json!([" before "]), 2).unwrap(), ["before", ""]);
223        assert!(c(serde_json::json!(["a", "b", "c"]), 2).unwrap_err().to_string().contains("3 captions for 2 files"));
224        assert!(c(serde_json::json!("after"), 1).is_err());
225        assert!(c(serde_json::json!([1]), 1).is_err());
226    }
227
228    #[test]
229    fn a_task_call_is_checked_against_a_tasks_limits_not_a_messages() {
230        let dir = tempfile::tempdir().unwrap();
231        let paths: Vec<String> = (0..3)
232            .map(|i| {
233                let p = dir.path().join(format!("f{i}.bin"));
234                std::fs::write(&p, vec![1u8; 4096]).unwrap();
235                p.to_string_lossy().into_owned()
236            })
237            .collect();
238        // Three files together are over a (small) total, one at a time they are not.
239        let tight = Limits { max_files: 10, max_total: 8192, per: "call" };
240        let err = check_within(&paths, tight).unwrap_err().to_string();
241        assert!(err.contains("limit per call"), "{err}");
242        assert!(check_within(&paths[..2], tight).is_ok());
243        // The task limits are wider than a message's in total, and tighter in count.
244        assert!(TASK_LIMITS.max_total > MESSAGE_LIMITS.max_total);
245        assert!(check_within(&paths, TASK_LIMITS).is_ok());
246        let eleven = vec![paths[0].clone(); 11];
247        assert!(check_within(&eleven, TASK_LIMITS).unwrap_err().to_string().contains("limit of 10 per call"));
248        // A message keeps its own.
249        let err = check_within(&eleven, Limits { max_files: 10, ..MESSAGE_LIMITS }).unwrap_err().to_string();
250        assert!(err.contains("per message"), "{err}");
251    }
252
253    #[test]
254    fn check_names_the_file_it_refuses() {
255        let dir = tempfile::tempdir().unwrap();
256        let ok = dir.path().join("shot.png");
257        std::fs::write(&ok, b"png").unwrap();
258        let empty = dir.path().join("empty.txt");
259        std::fs::write(&empty, b"").unwrap();
260        let p = |p: &std::path::Path| p.to_string_lossy().into_owned();
261
262        let got = check(&[p(&ok)]).unwrap();
263        assert_eq!((got[0].name.as_str(), got[0].size), ("shot.png", 3));
264
265        let err = check(&[p(&empty)]).unwrap_err().to_string();
266        assert!(err.contains("empty.txt") && err.contains("empty"), "{err}");
267        let err = check(&[p(dir.path())]).unwrap_err().to_string();
268        assert!(err.contains("is a folder"), "{err}");
269        let missing = p(&dir.path().join("nope.png"));
270        assert!(check(&[missing.clone()]).unwrap_err().to_string().contains(&missing));
271        let many = vec![p(&ok); jekt_files::MAX_FILES + 1];
272        assert!(check(&many).unwrap_err().to_string().contains("limit"));
273    }
274
275    #[test]
276    fn a_container_agent_told_a_host_path_is_missing_is_told_what_to_do() {
277        use std::io::ErrorKind::{NotFound, PermissionDenied};
278        let hint = missing_hint(NotFound, true);
279        assert!(hint.contains("not inside your container") && hint.contains("/workspace"), "{hint}");
280        // Native agents, and other failures, get the plain error.
281        assert_eq!(missing_hint(NotFound, false), "");
282        assert_eq!(missing_hint(PermissionDenied, true), "");
283    }
284}