agentmux_srv/server/editor_handlers/
agent_config.rs1use std::path::Path;
8use std::sync::Arc;
9
10use crate::backend::base::expand_home_dir_safe;
11use crate::backend::rpc_types::{AgentConfigFile, CommandWriteAgentConfigData, CommandWriteAgentConfigResult, RpcContext};
12use crate::backend::storage::store::Store;
13
14pub(super) struct ConfigStores {
16 pub id_store: Arc<Store>,
17 pub mstore: Arc<Store>,
18 pub identity_store: Arc<Store>,
19}
20
21pub(super) fn write_agent_config(
24 stores: &ConfigStores,
25 ctx: &RpcContext,
26 hands_out_keys: bool,
27 mut cmd: CommandWriteAgentConfigData,
28) -> Result<CommandWriteAgentConfigResult, String> {
29 let ConfigStores { id_store, mstore, identity_store } = stores;
30 crate::server::agent_config_guard::check_agent_config_write(
31 mstore,
32 ctx,
33 cmd.agent_id.as_deref(),
34 &expand_home_dir_safe(&cmd.working_dir),
35 cmd.auto_allocate,
36 )?;
37 tracing::info!(
38 working_dir = %cmd.working_dir,
39 file_count = cmd.files.len(),
40 auto_allocate = cmd.auto_allocate,
41 agent_type = cmd.agent_type.as_deref().unwrap_or("host"),
42 "WriteAgentConfig"
43 );
44 let agent_mode = cmd.agent_type.clone().unwrap_or_else(|| "host".to_string());
45 crate::server::picker_config::check_render_request(mstore, &cmd, hands_out_keys)?;
46 let final_working_dir = resolve_workdir(&cmd)?;
47 cmd.files = crate::server::picker_config::files_to_write(
48 std::mem::take(&mut cmd.files),
49 mstore,
50 id_store,
51 identity_store,
52 &cmd,
53 &agent_mode,
54 hands_out_keys,
55 &final_working_dir,
56 )?;
57 let on_host = !crate::backend::runtime_adapter::RuntimeKind::of_agent_type(&agent_mode).is_container();
58 write_files(&cmd.files, Path::new(&final_working_dir), on_host)?;
59 Ok(CommandWriteAgentConfigResult { working_dir: final_working_dir })
61}
62
63fn resolve_workdir(cmd: &CommandWriteAgentConfigData) -> Result<String, String> {
67 let expanded_working_dir = expand_home_dir_safe(&cmd.working_dir);
68 if cmd.auto_allocate {
69 let desired = expanded_working_dir.to_string_lossy().to_string();
70 return crate::server::app_api::allocate_agent_workdir(&desired);
71 }
72 let p = expanded_working_dir.as_path();
73 if !p.exists() {
74 std::fs::create_dir_all(p) .map_err(|e| format!("failed to create working dir: {e}"))?;
76 }
77 Ok(expanded_working_dir.to_string_lossy().to_string())
78}
79
80fn write_files(files: &[AgentConfigFile], base_path: &Path, on_host: bool) -> Result<(), String> {
81 if on_host && crate::backend::host_agent_files::write(&base_path.to_string_lossy(), files.iter().map(|f| (f.path.as_str(), f.content.as_str())))? {
84 return Ok(());
85 }
86 let canonical_base = base_path
90 .canonicalize()
91 .map_err(|e| format!("failed to canonicalize working dir {}: {e}", base_path.display()))?;
92
93 let wd = crate::backend::workdir_fs::Workdir::open(base_path)
99 .map_err(|e| format!("failed to open working dir {}: {e}", base_path.display()))?;
100 let new_managed_skill_paths = crate::backend::agent_config::managed_skill_file_paths(files.iter().map(|f| f.path.as_str()));
101 crate::backend::agent_config::cleanup_stale_managed_skill_files(base_path, &new_managed_skill_paths);
102
103 for file in files {
104 write_file(&wd, base_path, &canonical_base, file, on_host)?;
105 }
106 crate::backend::agent_config::write_managed_skill_file_manifest(base_path, &new_managed_skill_paths);
107 Ok(())
108}
109
110fn write_file(wd: &crate::backend::workdir_fs::Workdir, base_path: &Path, canonical_base: &Path, file: &AgentConfigFile, on_host: bool) -> Result<(), String> {
113 let file_path = crate::backend::base::safe_join_within_base(base_path, &file.path)
117 .map_err(|e| format!("path traversal denied: {} ({e})", file.path))?;
118 if let Err(e) = crate::backend::base::verify_no_symlink_escape(&file_path, canonical_base) {
122 tracing::warn!(path = %file.path, error = %e, "writeagentconfig: not writing a config file under a folder linking outside the workdir");
123 return Ok(());
124 }
125 if file.path == "CLAUDE.md" {
128 crate::backend::agent_config::write_claude_md_respecting_ownership(base_path, &file.content)
131 .map_err(|e| format!("failed to write CLAUDE.md: {e}"))?;
132 tracing::debug!(path = %file_path.display(), "wrote config file (ownership-aware)");
133 return Ok(());
134 }
135 if crate::backend::providers::is_known_startup_instructions_filename(&file.path) {
140 crate::backend::agent_config::write_startup_instructions_respecting_existing(base_path, &file.path, &file.content)
144 .map_err(|e| format!("failed to write {}: {e}", file.path))?;
145 tracing::debug!(path = %file_path.display(), "wrote config file (exists-guarded)");
146 return Ok(());
147 }
148 if file.path == ".mcp.json" {
152 let expanded = base_path.to_string_lossy();
153 let outside = if on_host {
154 crate::backend::mcp_config_file::host_relocated_path(&expanded)
155 } else {
156 crate::backend::mcp_config_file::relocated_path(&expanded)
157 };
158 if let Some(path) = outside {
159 let content = if on_host { crate::backend::mcp_config_file::host_content(&expanded, file.content.clone()) } else { file.content.clone() };
160 crate::backend::mcp_config_file::write_relocated(&path, &content)
161 .map_err(|e| format!("failed to write the agent's MCP config: {e}"))?;
162 tracing::debug!(path = %path.display(), "wrote config file (relocated, owner-only)");
163 return Ok(());
164 }
165 crate::backend::agent_config::write_mcp_json_respecting_user_servers(base_path, &file.content)
166 .map_err(|e| format!("failed to write .mcp.json: {e}"))?;
167 tracing::debug!(path = %file_path.display(), "wrote config file (merged, owner-only)");
168 return Ok(());
169 }
170 match wd.write(&file.path, file.content.as_bytes(), false) {
174 Err(e) if e.kind() == std::io::ErrorKind::PermissionDenied => {
175 tracing::warn!(path = %file.path, error = %e, "writeagentconfig: not writing a config file");
176 }
177 other => {
178 other.map_err(|e| format!("failed to write {}: {e}", file.path))?;
179 tracing::debug!(path = %file_path.display(), "wrote config file");
180 }
181 }
182 Ok(())
183}
184
185#[cfg(test)]
186mod tests {
187 use super::*;
188
189 fn files() -> Vec<AgentConfigFile> {
190 [("CLAUDE.md", "be kind"), (".claude/settings.json", "{\"hooks\":{}}"), (".claude/skills/review/SKILL.md", "body"), (".mcp.json", "{\"mcpServers\":{}}")]
191 .into_iter()
192 .map(|(path, content)| AgentConfigFile { path: path.to_string(), content: content.to_string() })
193 .collect()
194 }
195
196 #[test]
200 fn a_host_launch_into_a_container_agents_folder_writes_outside_it() {
201 let (data, folder, plain) = (tempfile::tempdir().unwrap(), tempfile::tempdir().unwrap(), tempfile::tempdir().unwrap());
202 let dir = folder.path().to_string_lossy().into_owned();
203 let in_folder = |root: &Path, name: &str| root.join(name).exists();
204 crate::backend::mcp_config_file::with_data_home(data.path(), || {
205 crate::backend::mcp_folder_rule::mark(&dir);
206 write_files(&files(), folder.path(), true).unwrap();
207 assert!(std::fs::read_dir(folder.path()).unwrap().next().is_none(), "nothing is written into the folder");
208 let own = crate::backend::host_agent_files::dir_of(&dir).unwrap();
209 assert!(crate::backend::host_agent_files::settings_path(&own).is_file());
210 assert!(crate::backend::host_agent_files::instructions_path(&own).is_file());
211 assert!(crate::backend::host_agent_files::plugin_dir(&own).join("skills").join("review").join("SKILL.md").is_file());
212
213 write_files(&files(), folder.path(), false).unwrap();
214 assert!(in_folder(folder.path(), "CLAUDE.md") && in_folder(folder.path(), ".claude/settings.json"), "the container agent's own launch writes its folder");
215
216 write_files(&files(), plain.path(), true).unwrap();
217 assert!(in_folder(plain.path(), "CLAUDE.md") && in_folder(plain.path(), ".claude/settings.json") && in_folder(plain.path(), ".claude/skills/review/SKILL.md"), "a folder no container agent has to do with: as before");
218 assert_eq!(crate::backend::host_agent_files::dir_of(&plain.path().to_string_lossy()), None);
219 });
220 }
221}