Skip to main content

agentmux_srv_core/backend/
container_sessions.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The end of a container agent's provider session (`SPEC_HISTORY_COMPACT_FORM_ONLY_2026_11_23.md` section 5.4).
5//!
6//! A container agent's session files are in its container's volume, not on the host. The end of a session is the host
7//! path's (`transcript::provider_end::end_session`: prove against the store, import what it lacks, verify, remove), run
8//! on a **staged copy** of the session's two paths, with the removal done in the container by session id:
9//!
10//! 1. the session's files are copied out of the container into an owner-only folder of the host's temp area;
11//! 2. the proof and the import run on that copy, as for a host agent;
12//! 3. when the proof has passed, the caller's admission is taken (the agent's lease: a running agent holds it, so its
13//!    session is never touched), the container's files are copied out a second time and must equal the first copy,
14//!    and only then is `<sid>.jsonl` and `<sid>/` removed in the container: through an exec when it runs, through a
15//!    short helper container on the volume when it is stopped (`ContainerManager::session_files_remove`);
16//! 4. the staged copy is overwritten and removed, and its folder with it, whatever the outcome.
17//!
18//! Nothing here decides *when* a session ends or *which* ids AgentMux started: the caller names one session of one
19//! container. Like the host path it removes by exact session id and never lists or sweeps a folder.
20
21use std::path::Path;
22
23use crate::backend::container::session_files::{session_paths, valid_project};
24use crate::backend::container::ContainerManager;
25use crate::backend::transcript::provider_end::{end_session, fingerprint, Hold, Outcome, SessionFiles, Zone};
26
27/// Where a container's session files can be reached. Blocking, and called from a blocking thread: [`DockerHome`] is
28/// the container; a test's is a folder.
29pub trait ContainerHome {
30    /// Copy the session's files (`<sid>.jsonl` and `<sid>/`, those that exist) into `dest`.
31    fn stage_out(&self, project: &str, sid: &str, dest: &Path) -> Result<(), String>;
32    /// Remove the session's files, by session id.
33    fn remove(&self, project: &str, sid: &str) -> Result<(), String>;
34}
35
36/// A container reached through the container runtime.
37pub struct DockerHome {
38    manager: ContainerManager,
39    container: String,
40    runtime: tokio::runtime::Handle,
41}
42
43impl DockerHome {
44    /// For use on a blocking thread of the runtime `runtime` is the handle of (`spawn_blocking`).
45    pub fn new(manager: ContainerManager, container: impl Into<String>, runtime: tokio::runtime::Handle) -> Self {
46        Self { manager, container: container.into(), runtime }
47    }
48}
49
50impl ContainerHome for DockerHome {
51    fn stage_out(&self, project: &str, sid: &str, dest: &Path) -> Result<(), String> {
52        self.runtime.block_on(self.manager.session_files_stage_out(&self.container, project, sid, dest))
53    }
54
55    fn remove(&self, project: &str, sid: &str) -> Result<(), String> {
56        self.runtime.block_on(self.manager.session_files_remove(&self.container, project, sid))
57    }
58}
59
60/// Copy the session out into a fresh `<root>/<n>/<project>` and say where, `None` when the container has no file of it.
61fn stage(home: &dyn ContainerHome, root: &Path, n: u32, project: &str, sid: &str) -> Result<Option<SessionFiles>, String> {
62    let dir = root.join(n.to_string()).join(project);
63    std::fs::create_dir_all(&dir).map_err(|e| format!("a place to stage: {e}"))?;
64    home.stage_out(project, sid, &dir)?;
65    let files = SessionFiles::at(&dir, sid).ok_or("not a session this can name")?;
66    Ok((files.jsonl.exists() || files.folder.exists()).then_some(files))
67}
68
69/// Prove, import and remove one session of a container agent: see the module's text. `read` are the zones that may hold
70/// the conversation and `zone` is where what the store lacks is imported, as for [`end_session`]; `admit` is the
71/// caller's last word, run after the proof and before anything is removed (an `Err` stops with nothing removed; what it
72/// returns is held until the removal is done). A session the container no longer holds is already ended: `Ok` with
73/// nothing counted. Every failure removes nothing, in the container or here.
74pub fn end_container_session(
75    home: &dyn ContainerHome,
76    project: &str,
77    sid: &str,
78    read: &[&dyn Zone],
79    zone: &dyn Zone,
80    admit: &mut dyn FnMut() -> Result<Box<dyn Hold>, String>,
81) -> Result<Outcome, String> {
82    if !valid_project(project) || session_paths(project, sid).is_none() {
83        return Err("not a session this can name".to_string());
84    }
85    // Owner-only, and gone when this returns whatever happens.
86    let staged = tempfile::Builder::new().prefix("agentmux-session-end-").tempdir().map_err(|e| format!("a place to stage: {e}"))?;
87    let Some(files) = stage(home, staged.path(), 0, project, sid)? else { return Ok(Outcome::default()) };
88    let proved = fingerprint(&files)?;
89    let mut remove_in_container = || -> Result<Box<dyn Hold>, String> {
90        let held = admit()?;
91        // The agent cannot start now. Look once more at what the container holds: it must be what was proved.
92        let again = stage(home, staged.path(), 1, project, sid)?.ok_or("the session's files are gone from the container")?;
93        if fingerprint(&again)? != proved {
94            return Err("the session's files changed in the container after they were proved".to_string());
95        }
96        home.remove(project, sid)?;
97        Ok(held)
98    };
99    end_session(&files, read, zone, &mut remove_in_container, &mut |_, _| {})
100}
101
102#[cfg(test)]
103#[path = "container_sessions_tests.rs"]
104mod tests;