1pub mod caches;
5pub mod credential_mode;
6pub mod dev_exec;
7pub mod host_name;
8pub mod read_exec;
9pub mod writable;
10pub(super) use self::host_name::host_name_for_new_container;
11
12use bollard::exec::{CreateExecOptions, StartExecOptions, StartExecResults};
13use bollard::models::{Mount, MountTypeEnum};
14use futures_util::StreamExt as _;
15
16use super::{
17 normalize_host_path, ContainerManager, ContainerMountSpec, CLAUDE_CREDENTIALS_FILE, CONTAINER_CLAUDE_DIR,
18 CONTAINER_WORKSPACE_DIR,
19};
20
21pub(crate) fn container_memory_dir() -> String {
24 let project = crate::backend::claude_layout::project_dir_name(CONTAINER_WORKSPACE_DIR);
25 format!("{CONTAINER_CLAUDE_DIR}/projects/{project}/memory")
26}
27
28pub(crate) fn personal_memory_host_dir(claude_config_dir: Option<&str>, working_dir: &str) -> Option<String> {
33 if working_dir.is_empty() {
34 return None;
35 }
36 let workspace = crate::backend::base::expand_home_dir_safe(working_dir);
39 let written = |dir: &std::path::Path| {
40 dir.starts_with(&workspace) || crate::backend::fs_ops::container_folders::written_by_a_container_agent(dir)
41 };
42 let dir = crate::backend::memory::native_files::memory_dir_for_cwd_with(claude_config_dir.unwrap_or(""), working_dir, &written);
43 if let Err(e) = std::fs::create_dir_all(&dir) {
44 tracing::warn!(dir = %dir.display(), error = %e, "container agent: can't create the Personal Memory folder; not mounting it");
45 return None;
46 }
47 let dir = if cfg!(windows) { dir } else { dir.canonicalize().unwrap_or(dir) };
48 Some(dir.to_string_lossy().into_owned())
49}
50
51fn on_the_key_route(env_vars: &std::collections::HashMap<String, String>) -> bool {
54 env_vars.get("ANTHROPIC_BASE_URL").is_some_and(|url| super::key_route::names_key_route(url))
55}
56
57impl ContainerMountSpec {
58 pub fn bound_host_dirs(&self) -> Vec<String> {
60 [
61 &self.workspace_host_dir,
62 &self.memory_host_dir,
63 &self.mcp_config_host_dir,
64 &self.github_hooks_host_dir,
65 &self.aws_config_host_dir,
66 &self.aws_tools_host_dir,
67 ]
68 .into_iter()
69 .flatten()
70 .cloned()
71 .collect()
72 }
73
74 pub fn for_agent(env_vars: &std::collections::HashMap<String, String>, working_dir: &str) -> Self {
80 let working_dir = crate::backend::base::expand_home_dir_safe(working_dir).to_string_lossy().into_owned();
81 let working_dir = working_dir.as_str();
82 let config_dir = env_vars.get("CLAUDE_CONFIG_DIR").map(String::as_str).filter(|d| !d.is_empty());
83 let login_dir = config_dir.filter(|_| !on_the_key_route(env_vars));
86 Self {
87 claude_config_host_dir: None,
89 staged_login_config_dir: login_dir
90 .filter(|dir| cfg!(target_os = "macos") || super::credentials_dir_if_file_backed(dir).is_some())
91 .map(str::to_string),
92 workspace_host_dir: Some(working_dir.to_string()).filter(|d| !d.is_empty()),
93 memory_host_dir: config_dir.and_then(|dir| personal_memory_host_dir(Some(dir), working_dir)),
94 mcp_config_host_dir: crate::backend::mcp_config_file::relocated_path(working_dir)
95 .filter(|path| path.is_file())
96 .and_then(|path| path.parent().map(|dir| dir.to_string_lossy().into_owned())),
97 github_hooks_host_dir: crate::identity::github_tokens::container_git_hooks().map(|d| d.to_string_lossy().into_owned()),
98 aws_config_host_dir: crate::identity::aws_broker::container::config_dir(),
99 aws_tools_host_dir: env_vars.get("AGENTMUX_AGENT_ID").and_then(|slug| crate::identity::aws_broker::tools::config_dir_for(slug)),
100 limits: Default::default(),
101 }
102 }
103}
104
105impl ContainerManager {
106 pub(crate) fn docker(&self) -> &bollard::Docker {
108 &self.inner.docker
109 }
110
111 pub(super) async fn own_memory_parents(&self, container_name: &str, spec: &ContainerMountSpec) {
116 if spec.memory_host_dir.as_deref().is_none_or(str::is_empty) {
117 return;
118 }
119 let memory = container_memory_dir();
120 let Some(project) = memory.strip_suffix("/memory") else { return };
121 let Some(projects) = project.rsplit_once('/').map(|(p, _)| p) else { return };
122 let Some((uid, gid)) = self.exec_identity(container_name).await else {
123 tracing::warn!(container = container_name, "container agent: can't tell which user runs turns; the memory folder's parents stay root-owned");
124 return;
125 };
126 let script = format!("chown {uid}:{gid} '{projects}' '{project}'");
127 let outcome = async {
128 let exec = self
129 .inner
130 .docker
131 .create_exec(
132 container_name,
133 CreateExecOptions {
134 user: Some("root"),
135 cmd: Some(vec!["sh", "-c", &script]),
136 attach_stdout: Some(true),
137 attach_stderr: Some(true),
138 ..Default::default()
139 },
140 )
141 .await?;
142 if let StartExecResults::Attached { mut output, .. } = self
143 .inner
144 .docker
145 .start_exec(&exec.id, Some(StartExecOptions { detach: false, ..Default::default() }))
146 .await?
147 {
148 while output.next().await.is_some() {}
149 }
150 self.inspect_exec(&exec.id).await
151 }
152 .await;
153 match outcome {
154 Ok(Some(0)) => {}
155 Ok(code) => tracing::warn!(container = container_name, ?code, "container agent: handing the memory folder's parents to the turn user failed"),
156 Err(e) => tracing::warn!(container = container_name, error = %e, "container agent: couldn't hand the memory folder's parents to the turn user"),
157 }
158 }
159}
160
161pub fn claude_volume_name(container_name: &str) -> String {
163 format!("agentmux-claude-{container_name}")
164}
165
166pub(super) fn agent_home_mounts(container_name: &str, spec: &ContainerMountSpec) -> Vec<Mount> {
212 let mut mounts = vec![Mount {
213 target: Some(CONTAINER_CLAUDE_DIR.to_string()),
214 source: Some(claude_volume_name(container_name)),
215 typ: Some(MountTypeEnum::VOLUME),
216 read_only: Some(false),
217 ..Default::default()
218 }];
219
220 if let Some(host_dir) = spec.claude_config_host_dir.as_deref().filter(|d| !d.is_empty()) {
221 let host_dir = normalize_host_path(host_dir);
222 mounts.push(Mount {
223 target: Some(format!("{CONTAINER_CLAUDE_DIR}/{CLAUDE_CREDENTIALS_FILE}")),
224 source: Some(format!("{}/{CLAUDE_CREDENTIALS_FILE}", host_dir.trim_end_matches('/'))),
225 typ: Some(MountTypeEnum::BIND),
226 read_only: Some(false),
230 ..Default::default()
231 });
232 }
233 if let Some(host_dir) = spec.memory_host_dir.as_deref().filter(|d| !d.is_empty()) {
234 mounts.push(Mount {
235 target: Some(container_memory_dir()),
236 source: Some(normalize_host_path(host_dir)),
237 typ: Some(MountTypeEnum::BIND),
238 read_only: Some(false),
239 ..Default::default()
240 });
241 }
242 if let Some(host_dir) = spec.mcp_config_host_dir.as_deref().filter(|d| !d.is_empty()) {
243 mounts.push(Mount {
246 target: Some(crate::backend::container::CONTAINER_MCP_CONFIG_DIR.to_string()),
247 source: Some(normalize_host_path(host_dir)),
248 typ: Some(MountTypeEnum::BIND),
249 read_only: Some(true),
250 ..Default::default()
251 });
252 }
253 if let Some(host_dir) = spec.github_hooks_host_dir.as_deref().filter(|d| !d.is_empty()) {
254 mounts.push(Mount {
256 target: Some(crate::identity::github_tokens::CONTAINER_HOOKS_DIR.to_string()),
257 source: Some(normalize_host_path(host_dir)),
258 typ: Some(MountTypeEnum::BIND),
259 read_only: Some(true),
260 ..Default::default()
261 });
262 }
263 let aws = [
265 (spec.aws_config_host_dir.as_deref(), crate::identity::aws_broker::container::CONTAINER_AWS_DIR),
266 (spec.aws_tools_host_dir.as_deref(), crate::identity::aws_broker::tools::CONTAINER_TOOLS_DIR),
267 ];
268 for (host_dir, target) in aws.into_iter().filter_map(|(d, t)| Some((d.filter(|d| !d.is_empty())?, t))) {
269 mounts.push(Mount {
270 target: Some(target.to_string()),
271 source: Some(normalize_host_path(host_dir)),
272 typ: Some(MountTypeEnum::BIND),
273 read_only: Some(true),
274 ..Default::default()
275 });
276 }
277 mounts
278}
279
280pub(super) fn owned_mount_targets() -> [String; 7] {
283 [
284 CONTAINER_CLAUDE_DIR.to_string(),
285 format!("{CONTAINER_CLAUDE_DIR}/{CLAUDE_CREDENTIALS_FILE}"),
286 CONTAINER_WORKSPACE_DIR.to_string(),
287 crate::backend::container::CONTAINER_MCP_CONFIG_DIR.to_string(),
288 crate::identity::github_tokens::CONTAINER_HOOKS_DIR.to_string(),
289 crate::identity::aws_broker::container::CONTAINER_AWS_DIR.to_string(),
290 crate::identity::aws_broker::tools::CONTAINER_TOOLS_DIR.to_string(),
291 ]
292}
293
294pub(super) fn is_checked(spec: &ContainerMountSpec, target: &str) -> bool {
297 use crate::identity::aws_broker::{container::CONTAINER_AWS_DIR, tools::CONTAINER_TOOLS_DIR};
298 match target {
299 CONTAINER_AWS_DIR => spec.aws_config_host_dir.is_some(),
300 CONTAINER_TOOLS_DIR => spec.aws_tools_host_dir.is_some(),
301 _ => true,
302 }
303}
304
305#[cfg(test)]
306mod itest;
307
308#[cfg(test)]
309mod tests {
310 use super::*;
311 use std::collections::HashMap;
312
313 fn bind_at<'a>(mounts: &'a [Mount], target: &str) -> Option<&'a Mount> {
314 mounts.iter().find(|m| m.target.as_deref() == Some(target))
315 }
316
317 #[test]
318 fn claude_reads_memory_from_the_folder_it_names_for_the_workspace() {
319 assert_eq!(container_memory_dir(), "/home/agent/.claude/projects/-workspace/memory");
320 }
321
322 #[test]
325 fn the_relocated_mcp_config_is_a_read_only_folder_bind() {
326 let with = ContainerMountSpec { mcp_config_host_dir: Some("/host/.agentmux/mcp/abc".into()), ..Default::default() };
327 let mounts = agent_home_mounts("agentmux-abc", &with);
328 let mount = bind_at(&mounts, crate::backend::container::CONTAINER_MCP_CONFIG_DIR).expect("the config folder is mounted");
329 assert_eq!(mount.source.as_deref(), Some("/host/.agentmux/mcp/abc"));
330 assert_eq!(mount.read_only, Some(true), "the config is srv's to write");
331 let without = ContainerMountSpec::default();
332 assert!(bind_at(&agent_home_mounts("agentmux-abc", &without), crate::backend::container::CONTAINER_MCP_CONFIG_DIR).is_none());
333 }
334
335 #[test]
336 fn the_git_hooks_are_a_read_only_bind_and_only_when_there_are_some() {
337 let with = ContainerMountSpec { github_hooks_host_dir: Some("/host/github-hooks".into()), ..Default::default() };
338 let mounts = agent_home_mounts("agentmux-abc", &with);
339 let hooks = bind_at(&mounts, crate::identity::github_tokens::CONTAINER_HOOKS_DIR).expect("the hooks are mounted");
340 assert_eq!(hooks.source.as_deref(), Some("/host/github-hooks"));
341 assert_eq!(hooks.read_only, Some(true), "the scan is not the agent's to edit");
342 for none in [None, Some(String::new())] {
343 let without = ContainerMountSpec { github_hooks_host_dir: none, ..Default::default() };
344 assert!(bind_at(&agent_home_mounts("agentmux-abc", &without), crate::identity::github_tokens::CONTAINER_HOOKS_DIR).is_none());
345 }
346 }
347
348 #[test]
349 fn an_account_with_a_login_is_given_a_copy_of_it_and_never_its_own_file() {
350 let account = tempfile::tempdir().unwrap();
351 let env = |dir: &std::path::Path| HashMap::from([("CLAUDE_CONFIG_DIR".to_string(), dir.to_string_lossy().into_owned())]);
352 let without = ContainerMountSpec::for_agent(&env(account.path()), "");
353 assert_eq!(without.claude_config_host_dir, None);
354 assert_eq!(without.staged_login_config_dir.is_some(), cfg!(target_os = "macos"), "only macOS keeps a login outside a file");
355 std::fs::write(account.path().join(CLAUDE_CREDENTIALS_FILE), "{}").unwrap();
356 let with = ContainerMountSpec::for_agent(&env(account.path()), "");
357 assert_eq!(with.claude_config_host_dir, None, "the container's own copy is made at its start, so the spec names no file");
358 assert_eq!(with.staged_login_config_dir.as_deref(), Some(account.path().to_str().unwrap()), "the account whose login is copied");
359 assert_eq!(ContainerMountSpec::for_agent(&HashMap::new(), "").staged_login_config_dir, None, "no bound account, nothing to stage");
360 }
361
362 #[test]
363 fn an_agent_on_an_api_key_mounts_no_login_from_the_folder_it_runs_in_and_still_shares_its_memory() {
364 use crate::backend::model_gateway::{catalog::KEY_ROUTE_ID, token, PATH_PREFIX};
365 let default_dir = tempfile::tempdir().unwrap();
367 std::fs::write(default_dir.path().join(CLAUDE_CREDENTIALS_FILE), "{}").unwrap();
368 let work = tempfile::tempdir().unwrap();
369 let mut env = HashMap::from([("CLAUDE_CONFIG_DIR".to_string(), default_dir.path().to_string_lossy().into_owned())]);
370 let plan = ContainerMountSpec::for_agent(&env, work.path().to_str().unwrap());
371 assert!(plan.staged_login_config_dir.is_some(), "a plan account's login is copied for the container");
372 let key_token = token::renew_for_account("km-slug", "km-def", KEY_ROUTE_ID, "km-acct", None);
373 env.insert("ANTHROPIC_AUTH_TOKEN".to_string(), key_token);
374 env.insert("ANTHROPIC_BASE_URL".to_string(), format!("http://127.0.0.1:1{PATH_PREFIX}{KEY_ROUTE_ID}"));
375 let key = ContainerMountSpec::for_agent(&env, work.path().to_str().unwrap());
376 assert_eq!(key.claude_config_host_dir, None, "no credentials file is given to a key agent's container");
377 assert_eq!(key.staged_login_config_dir, None, "and no login is copied for it");
378 assert_eq!(key.memory_host_dir, plan.memory_host_dir, "its Personal Memory folder is shared as before");
379 assert!(key.memory_host_dir.is_some());
380 let mut model = env.clone();
382 model.insert("ANTHROPIC_AUTH_TOKEN".to_string(), token::token_for("km-model-slug", "km-model-def", "openrouter"));
383 model.insert("ANTHROPIC_BASE_URL".to_string(), format!("http://127.0.0.1:1{PATH_PREFIX}openrouter"));
384 assert!(ContainerMountSpec::for_agent(&model, work.path().to_str().unwrap()).staged_login_config_dir.is_some());
385 token::revoke("km-model-def", "openrouter");
386 token::revoke("km-def", KEY_ROUTE_ID);
387 }
388
389 #[test]
390 fn an_agent_on_an_api_key_mounts_no_login_even_when_its_token_has_ended() {
391 use crate::backend::model_gateway::{catalog::KEY_ROUTE_ID, token, PATH_PREFIX};
392 let default_dir = tempfile::tempdir().unwrap();
393 std::fs::write(default_dir.path().join(CLAUDE_CREDENTIALS_FILE), "{}").unwrap();
394 let work = tempfile::tempdir().unwrap();
395 let ended = token::renew_for_account("ke-slug", "ke-def", KEY_ROUTE_ID, "ke-acct", None);
396 token::revoke("ke-def", KEY_ROUTE_ID);
397 assert_eq!(token::grant_for(&ended), None);
398 let base = ("ANTHROPIC_BASE_URL".to_string(), format!("http://127.0.0.1:1{PATH_PREFIX}{KEY_ROUTE_ID}"));
399 let config = ("CLAUDE_CONFIG_DIR".to_string(), default_dir.path().to_string_lossy().into_owned());
400 for token in [Some(ended), None] {
402 let mut env = HashMap::from([base.clone(), config.clone()]);
403 if let Some(t) = token {
404 env.insert("ANTHROPIC_AUTH_TOKEN".to_string(), t);
405 }
406 let plan = ContainerMountSpec::for_agent(&env, work.path().to_str().unwrap());
407 assert_eq!(plan.claude_config_host_dir, None, "the person's own sign-in is never mounted for a key agent");
408 assert_eq!(plan.staged_login_config_dir, None);
409 }
410 }
411
412 #[test]
413 fn the_memory_folder_is_one_bind_and_only_when_there_is_one() {
414 let with = ContainerMountSpec { memory_host_dir: Some("/host/mem".into()), ..Default::default() };
415 let mounts = agent_home_mounts("agentmux-abc", &with);
416 let memory = bind_at(&mounts, &container_memory_dir()).expect("memory is mounted");
417 assert_eq!(memory.source.as_deref(), Some("/host/mem"));
418 assert_eq!(memory.typ, Some(MountTypeEnum::BIND));
419 assert_eq!(memory.read_only, Some(false));
420 assert!(bind_at(&mounts, &format!("{CONTAINER_CLAUDE_DIR}/projects")).is_none());
422 assert_eq!(mounts.len(), 2, "the volume and the memory folder");
423
424 for none in [None, Some(String::new())] {
425 let without = ContainerMountSpec { memory_host_dir: none, ..Default::default() };
426 assert!(bind_at(&agent_home_mounts("agentmux-abc", &without), &container_memory_dir()).is_none());
427 }
428 }
429
430 #[test]
431 fn the_host_folder_is_where_a_native_session_keeps_memory_and_is_created() {
432 let root = std::env::temp_dir().join(format!("agentmux-p5-{}", std::process::id()));
433 let config = root.join("claude");
434 let work = root.join("work");
435 std::fs::create_dir_all(&work).unwrap();
436 let got = personal_memory_host_dir(Some(&config.to_string_lossy()), &work.to_string_lossy()).expect("a folder");
437 let want = crate::backend::memory::native_files::memory_dir_for_cwd(&config.to_string_lossy(), &work.to_string_lossy());
438 assert!(want.is_dir(), "created, so Docker has a source to bind");
439 let expected = if cfg!(windows) { want.clone() } else { want.canonicalize().unwrap() };
442 assert_eq!(std::path::Path::new(&got), expected);
443 assert_eq!(personal_memory_host_dir(Some(&config.to_string_lossy()), ""), None);
444 let _ = std::fs::remove_dir_all(&root);
445 }
446
447 #[test]
450 fn the_memory_folder_is_named_after_the_workspaces_path_whatever_it_holds() {
451 let base = tempfile::tempdir().unwrap();
452 let config = base.path().join("claude");
453 let (repo, worktree) = crate::backend::claude_layout::tests::repo_with_worktree(base.path());
454 let plain = crate::backend::claude_layout::real_path(base.path()).join("plain");
455 std::fs::create_dir_all(&plain).unwrap();
456 let name = |dir: &std::path::Path| crate::backend::claude_layout::project_dir_name(&dir.to_string_lossy());
457 for workspace in [&worktree, &repo, &plain] {
458 let bound = personal_memory_host_dir(Some(&config.to_string_lossy()), &workspace.to_string_lossy()).expect("a folder");
459 let project = std::path::Path::new(&bound).parent().unwrap().file_name().unwrap().to_string_lossy().into_owned();
460 assert_eq!(project, name(workspace), "{}", workspace.display());
461 }
462 assert_ne!(name(&worktree), name(&repo));
463 }
464
465 #[test]
466 fn a_tilde_working_dir_is_mounted_as_the_absolute_folder_it_names() {
467 let _guard = crate::test_support::ISOLATED_AUTH_ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
468 let fake = tempfile::tempdir().unwrap();
469 let prior = std::env::var_os("AGENTMUX_HOME_OVERRIDE");
470 std::env::set_var("AGENTMUX_HOME_OVERRIDE", fake.path());
471 let isolated = ContainerMountSpec::for_agent(&HashMap::new(), "~/.agentmux/agents/aria");
472 std::env::remove_var("AGENTMUX_HOME_OVERRIDE");
473 let normal = ContainerMountSpec::for_agent(&HashMap::new(), "~/.agentmux/agents/aria");
474 if let Some(p) = prior {
475 std::env::set_var("AGENTMUX_HOME_OVERRIDE", p);
476 }
477 assert_eq!(isolated.workspace_host_dir.as_deref().map(std::path::Path::new), Some(fake.path().join("agents").join("aria").as_path()));
478 let normal = normal.workspace_host_dir.unwrap();
479 assert!(std::path::Path::new(&normal).is_absolute() && !normal.contains('~'), "{normal}");
480 }
481
482 #[test]
483 fn an_agent_without_a_claude_config_dir_gets_no_memory_mount() {
484 let spec = ContainerMountSpec::for_agent(&HashMap::new(), "/some/work");
485 assert_eq!(spec.memory_host_dir, None);
486 assert_eq!(spec.workspace_host_dir.as_deref(), Some("/some/work"));
487 }
488}