Skip to main content

agentmux_srv_core/backend/container/
session_files.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! A container agent's provider session files, reached through its container
5//! (`SPEC_HISTORY_COMPACT_FORM_ONLY_2026_11_23.md` section 5.4).
6//!
7//! The provider's home in a container is the per-agent volume at [`CONTAINER_CLAUDE_DIR`]. A session is two paths in
8//! it, named from the project folder and the session id alone: `projects/<project>/<sid>.jsonl` and
9//! `projects/<project>/<sid>/`. Nothing here lists a folder or names anything else.
10//!
11//! - **Reading** is the archive API (`docker cp`), which works on a running and on a stopped container.
12//! - **Removing** is `rm` through an exec when the container runs; when it is stopped, a short helper container of the
13//!   same image that mounts only the agent's volume, has no network and no capability but the one `rm` needs, and is
14//!   removed when it ends.
15
16use std::collections::HashMap;
17use std::io::{Seek, SeekFrom, Write};
18use std::path::{Component, Path};
19use std::time::Duration;
20
21use bollard::container::{Config, CreateContainerOptions, DownloadFromContainerOptions, RemoveContainerOptions, StartContainerOptions};
22use bollard::models::{HostConfig, Mount, MountTypeEnum};
23use futures_util::StreamExt as _;
24
25use super::mounts::claude_volume_name;
26use super::{ContainerManager, CONTAINER_CLAUDE_DIR};
27use crate::backend::transcript::provider_end::valid_sid;
28
29/// The label every helper container carries, so a leftover can be found.
30pub const HELPER_LABEL: &str = "agentmux.session-end";
31/// How long the removal may take, in a helper or an exec.
32const REMOVE_LIMIT: Duration = Duration::from_secs(60);
33/// The most a staged copy of one session may hold. A session larger than this is not staged, so not removed.
34const STAGE_LIMIT: u64 = 4 << 30;
35
36/// A project folder name: one plain path part, as the provider names it (the working folder with its separators
37/// turned into `-`).
38pub fn valid_project(project: &str) -> bool {
39    !project.is_empty() && project.len() <= 200 && project != "." && project != ".." && project.bytes().all(|b| b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.'))
40}
41
42/// The two paths of one session in the container.
43#[derive(Debug, Clone, PartialEq, Eq)]
44pub struct SessionPaths {
45    pub jsonl: String,
46    pub folder: String,
47}
48
49/// `None` unless both names are plain: nothing is ever named from a string with a separator in it.
50pub fn session_paths(project: &str, sid: &str) -> Option<SessionPaths> {
51    (valid_project(project) && valid_sid(sid)).then(|| {
52        let base = format!("{CONTAINER_CLAUDE_DIR}/projects/{project}");
53        SessionPaths { jsonl: format!("{base}/{sid}.jsonl"), folder: format!("{base}/{sid}") }
54    })
55}
56
57/// The removal as an argv, run directly (no shell): exactly the two paths, the folder with what is under it.
58pub fn remove_argv(paths: &SessionPaths) -> Vec<String> {
59    ["rm", "-rf", "--", paths.jsonl.as_str(), paths.folder.as_str()].map(str::to_string).to_vec()
60}
61
62/// The helper container's configuration. Pure, so the locks are testable without a runtime.
63pub fn helper_config(image: &str, user: Option<&str>, volume: &str, paths: &SessionPaths) -> Config<String> {
64    let argv = remove_argv(paths);
65    Config {
66        image: Some(image.to_string()),
67        entrypoint: Some(vec![argv[0].clone()]),
68        cmd: Some(argv[1..].to_vec()),
69        user: user.filter(|u| !u.is_empty()).map(str::to_string),
70        network_disabled: Some(true),
71        tty: Some(false),
72        open_stdin: Some(false),
73        labels: Some(HashMap::from([(HELPER_LABEL.to_string(), "1".to_string())])),
74        host_config: Some(HostConfig {
75            network_mode: Some("none".to_string()),
76            readonly_rootfs: Some(true),
77            // The one capability `rm` needs to remove what another user's folders hold.
78            cap_drop: Some(vec!["ALL".to_string()]),
79            cap_add: Some(vec!["DAC_OVERRIDE".to_string()]),
80            security_opt: Some(vec!["no-new-privileges".to_string()]),
81            memory: Some(128 * 1024 * 1024),
82            memory_swap: Some(128 * 1024 * 1024),
83            pids_limit: Some(32),
84            init: Some(true),
85            mounts: Some(vec![Mount {
86                target: Some(CONTAINER_CLAUDE_DIR.to_string()),
87                source: Some(volume.to_string()),
88                typ: Some(MountTypeEnum::VOLUME),
89                read_only: Some(false),
90                ..Default::default()
91            }]),
92            ..Default::default()
93        }),
94        ..Default::default()
95    }
96}
97
98/// Unpack the archive of one path of a session (what `docker cp` gives) into `dest`. `top` is the one name the archive
99/// may hold at its root (`<sid>.jsonl` or `<sid>`). Only regular files and folders, only under `top`: a link, a device,
100/// a name that climbs out or a second root is an error and leaves nothing to trust. Returns how many bytes it wrote.
101pub fn extract(archive: impl std::io::Read, top: &str, dest: &Path) -> Result<u64, String> {
102    let mut archive = tar::Archive::new(archive);
103    archive.set_preserve_permissions(false);
104    archive.set_unpack_xattrs(false);
105    let mut written = 0u64;
106    for entry in archive.entries().map_err(|e| format!("the archive: {e}"))? {
107        let mut entry = entry.map_err(|e| format!("the archive: {e}"))?;
108        let kind = entry.header().entry_type();
109        if !(kind.is_file() || kind.is_dir()) {
110            return Err("the session holds a link or a special file".to_string());
111        }
112        let path = entry.path().map_err(|e| format!("the archive: {e}"))?.into_owned();
113        let mut parts = path.components();
114        if !matches!(parts.next(), Some(Component::Normal(first)) if first == top) || !parts.all(|c| matches!(c, Component::Normal(_))) {
115            return Err("the archive names a file outside the session".to_string());
116        }
117        written += entry.header().size().unwrap_or(0);
118        if written > STAGE_LIMIT {
119            return Err("the session is too large to stage".to_string());
120        }
121        if !entry.unpack_in(dest).map_err(|e| format!("the archive: {e}"))? {
122            return Err("the archive names a file outside the session".to_string());
123        }
124    }
125    Ok(written)
126}
127
128fn is_missing(e: &bollard::errors::Error) -> bool {
129    matches!(e, bollard::errors::Error::DockerResponseServerError { status_code: 404, .. })
130}
131
132impl ContainerManager {
133    /// Copy one session's files out of the container into `dest` (a project folder on the host): `<sid>.jsonl` and
134    /// `<sid>/`, as they are. A path the container does not have is not copied; a session with neither leaves `dest`
135    /// empty. Works on a stopped container.
136    pub async fn session_files_stage_out(&self, container_name: &str, project: &str, sid: &str, dest: &Path) -> Result<(), String> {
137        let paths = session_paths(project, sid).ok_or("not a session this can name")?;
138        // The archive API answers 404 for a path the container lacks and for a container that is gone: only the first
139        // is a session that is not there, so the second is told apart here, before any path is asked for.
140        self.inner.docker.inspect_container(container_name, None).await.map_err(|e| format!("couldn't inspect the container: {e}"))?;
141        for (path, top) in [(&paths.jsonl, format!("{sid}.jsonl")), (&paths.folder, sid.to_string())] {
142            let mut stream = self.inner.docker.download_from_container(container_name, Some(DownloadFromContainerOptions { path: path.as_str() }));
143            // The archive goes to an unnamed file that is gone with this call, then is unpacked from there.
144            let mut spool = tempfile::tempfile().map_err(|e| format!("a place to stage: {e}"))?;
145            let mut got = 0u64;
146            while let Some(chunk) = stream.next().await {
147                match chunk {
148                    Ok(bytes) => {
149                        got += bytes.len() as u64;
150                        if got > STAGE_LIMIT + (1 << 20) {
151                            return Err("the session is too large to stage".to_string());
152                        }
153                        spool.write_all(&bytes).map_err(|e| format!("a place to stage: {e}"))?;
154                    }
155                    Err(e) if is_missing(&e) => {
156                        got = 0;
157                        break;
158                    }
159                    Err(e) => return Err(format!("couldn't read the container's files: {e}")),
160                }
161            }
162            if got == 0 {
163                continue;
164            }
165            spool.seek(SeekFrom::Start(0)).map_err(|e| e.to_string())?;
166            extract(std::io::BufReader::new(spool), &top, dest)?;
167        }
168        Ok(())
169    }
170
171    /// Remove one session's files from the container, by session id: through an exec when it runs, through a helper
172    /// container on its volume when it does not. A session that is not there is removed.
173    pub async fn session_files_remove(&self, container_name: &str, project: &str, sid: &str) -> Result<(), String> {
174        let paths = session_paths(project, sid).ok_or("not a session this can name")?;
175        let info = self.inner.docker.inspect_container(container_name, None).await.map_err(|e| format!("couldn't inspect the container: {e}"))?;
176        if info.state.as_ref().and_then(|s| s.running) == Some(true) {
177            let out = self.exec_collect(container_name, &remove_argv(&paths), REMOVE_LIMIT).await.map_err(|e| format!("couldn't remove the files: {e}"))?;
178            return match (out.timed_out, out.exit) {
179                (false, Some(0)) => Ok(()),
180                (true, _) => Err("removing the files took too long".to_string()),
181                (false, code) => Err(format!("removing the files failed ({code:?})")),
182            };
183        }
184        let config = info.config.as_ref();
185        let image = config.and_then(|c| c.image.clone()).filter(|i| !i.is_empty()).ok_or("the container names no image")?;
186        let user = config.and_then(|c| c.user.clone());
187        let name = format!("agentmux-session-end-{}", uuid::Uuid::new_v4().simple());
188        let docker = &self.inner.docker;
189        docker
190            .create_container(Some(CreateContainerOptions { name: name.as_str(), platform: None }), helper_config(&image, user.as_deref(), &claude_volume_name(container_name), &paths))
191            .await
192            .map_err(|e| format!("couldn't create the helper container: {e}"))?;
193        let ran = async {
194            docker.start_container(&name, None::<StartContainerOptions<String>>).await.map_err(|e| format!("couldn't start the helper container: {e}"))?;
195            match tokio::time::timeout(REMOVE_LIMIT, super::oneshot::wait(docker, &name)).await {
196                Ok(Ok(0)) => Ok(()),
197                Ok(Ok(code)) => Err(format!("removing the files failed ({code})")),
198                Ok(Err(e)) => Err(e),
199                Err(_) => Err("removing the files took too long".to_string()),
200            }
201        }
202        .await;
203        let _ = docker.remove_container(&name, Some(RemoveContainerOptions { force: true, v: true, ..Default::default() })).await;
204        ran
205    }
206}
207
208#[cfg(test)]
209#[path = "session_files_tests.rs"]
210mod tests;