agentmux_srv_core/backend/
host_agent_files.rs1use std::path::{Path, PathBuf};
25
26use serde_json::Value;
27
28use agentmux_common::mcp_config_path as shared;
29
30pub const CHECKED_WITH_CLAUDE_CODE: &str = "2.1.321";
33
34pub const PLUGIN_NAME: &str = "agentmux";
36
37const SETTINGS_FILE: &str = "settings.json";
38const INSTRUCTIONS_DIR: &str = "instructions";
39const INSTRUCTIONS_FILE: &str = "CLAUDE.md";
40const PLUGIN_DIR: &str = "plugin";
41const WRAPPER: &str = "agentmux-bashwrap";
42const SERVERS_WITH_NO_PATH: &str = "servers-with-no-path.json";
45
46const MOST_COUNTED: usize = 200;
48const DEEPEST: usize = 4;
50
51const SCHEDULER_OFF: &str = "CLAUDE_CODE_DISABLE_CRON";
54const READ_ADDED_INSTRUCTIONS: &str = "CLAUDE_CODE_ADDITIONAL_DIRECTORIES_CLAUDE_MD";
56
57pub fn dir_of(work_dir: &str) -> Option<PathBuf> {
60 if !crate::backend::mcp_folder_rule::holds_in(work_dir) {
61 return None;
62 }
63 let expanded = crate::backend::blockcontroller::core::expand_home_dir(work_dir);
64 shared::host_only_dir_for(Path::new(&expanded))
65}
66
67pub fn settings_path(dir: &Path) -> PathBuf {
69 dir.join(SETTINGS_FILE)
70}
71
72pub fn instructions_dir(dir: &Path) -> PathBuf {
74 dir.join(INSTRUCTIONS_DIR)
75}
76
77pub fn instructions_path(dir: &Path) -> PathBuf {
79 instructions_dir(dir).join(INSTRUCTIONS_FILE)
80}
81
82pub fn plugin_dir(dir: &Path) -> PathBuf {
84 dir.join(PLUGIN_DIR)
85}
86
87fn place_of(name: &str) -> Option<String> {
90 let name = name.replace('\\', "/");
91 if name == "CLAUDE.md" {
92 return Some(format!("{INSTRUCTIONS_DIR}/{INSTRUCTIONS_FILE}"));
93 }
94 if name == ".claude/settings.json" {
95 return Some(SETTINGS_FILE.to_string());
96 }
97 for (from, to) in [(".claude/skills/", "skills/"), (".claude/commands/", "commands/")] {
98 if let Some(rest) = name.strip_prefix(from).filter(|rest| !rest.is_empty()) {
99 return Some(format!("{PLUGIN_DIR}/{to}{rest}"));
100 }
101 }
102 None
103}
104
105pub fn write<'a>(work_dir: &str, files: impl Iterator<Item = (&'a str, &'a str)>) -> Result<bool, String> {
111 let Some(dir) = dir_of(work_dir) else { return Ok(false) };
112 for stale in [instructions_dir(&dir), plugin_dir(&dir)] {
113 match std::fs::remove_dir_all(&stale) {
114 Ok(()) => {}
115 Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
116 Err(e) => return Err(format!("failed to clear {}: {e}", stale.display())),
117 }
118 }
119 let mut in_plugin = false;
120 for (name, content) in files {
121 if name == shared::MCP_JSON {
122 let (text, no_path) = crate::backend::mcp_folder_rule::with_commands_by_path(content, work_dir);
123 write_one(&dir.join(shared::RELOCATED_MCP_JSON), &text)?;
124 write_one(&dir.join(SERVERS_WITH_NO_PATH), &serde_json::json!(no_path).to_string())?;
125 continue;
126 }
127 let Some(place) = place_of(name) else {
128 tracing::debug!(work_dir, name, "not written: a host agent in a folder a container agent can write is given it from nowhere");
129 continue;
130 };
131 let path = crate::backend::base::safe_join_within_base(&dir, &place).map_err(|e| format!("path traversal denied: {name} ({e})"))?;
132 if place == SETTINGS_FILE {
133 write_one(&path, &settings_with_hooks_by_path(content, work_dir))?;
134 } else if place.starts_with(INSTRUCTIONS_DIR) {
135 write_one(&path, &as_agentmux_wrote_it(content))?;
136 } else {
137 in_plugin = true;
138 write_one(&path, content)?;
139 }
140 }
141 if in_plugin {
142 write_plugin_manifest(&dir)?;
143 }
144 Ok(true)
145}
146
147pub fn refresh_skills<'a>(work_dir: &str, files: impl Iterator<Item = (&'a str, &'a str)>) -> Result<bool, String> {
150 let Some(dir) = dir_of(work_dir) else { return Ok(false) };
151 match std::fs::remove_dir_all(plugin_dir(&dir)) {
152 Ok(()) => {}
153 Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
154 Err(e) => return Err(format!("failed to clear {}: {e}", plugin_dir(&dir).display())),
155 }
156 let mut in_plugin = false;
157 for (name, content) in files {
158 let Some(place) = place_of(name).filter(|place| place.starts_with(PLUGIN_DIR)) else { continue };
159 let path = crate::backend::base::safe_join_within_base(&dir, &place).map_err(|e| format!("path traversal denied: {name} ({e})"))?;
160 in_plugin = true;
161 write_one(&path, content)?;
162 }
163 if in_plugin {
164 write_plugin_manifest(&dir)?;
165 }
166 Ok(true)
167}
168
169fn write_plugin_manifest(dir: &Path) -> Result<(), String> {
170 let manifest = serde_json::json!({ "name": PLUGIN_NAME, "version": "1.0.0", "description": "The skills and commands AgentMux gives this agent" });
171 write_one(&plugin_dir(dir).join(".claude-plugin").join("plugin.json"), &manifest.to_string())
172}
173
174pub fn servers_with_no_path(dir: &Path) -> Vec<String> {
177 std::fs::read_to_string(dir.join(SERVERS_WITH_NO_PATH))
178 .ok()
179 .and_then(|raw| serde_json::from_str::<Vec<String>>(&raw).ok())
180 .unwrap_or_default()
181}
182
183pub fn refresh_instructions(work_dir: &str, content: &str) -> Result<bool, String> {
186 let Some(dir) = dir_of(work_dir) else { return Ok(false) };
187 let path = instructions_path(&dir);
188 if !path.is_file() {
189 return Ok(false);
190 }
191 write_one(&path, &as_agentmux_wrote_it(content)).map(|()| true)
192}
193
194fn as_agentmux_wrote_it(content: &str) -> String {
197 format!("{}\n\n{content}", crate::backend::agent_config::CLAUDE_MD_MANAGED_MARKER)
198}
199
200fn write_one(path: &Path, content: &str) -> Result<(), String> {
201 crate::backend::mcp_config_file::write_relocated(path, content).map_err(|e| format!("failed to write {}: {e}", path.display()))
202}
203
204fn wrapper_by_path(command: &str, wrapper: &Path) -> Option<String> {
207 let rest = command.strip_prefix(WRAPPER)?;
208 if !(rest.is_empty() || rest.starts_with(' ')) {
209 return None;
210 }
211 let path = wrapper.to_string_lossy().replace('\\', "/");
212 Some(format!("\"{path}\"{rest}"))
213}
214
215fn plain_in_quotes(path: &Path) -> bool {
217 !path.to_string_lossy().chars().any(|c| matches!(c, '"' | '$' | '`' | '\n'))
218}
219
220pub fn settings_with_hooks_by_path(settings: &str, work_dir: &str) -> String {
225 let wrapper = crate::backend::tool_store::bashwrap_path()
226 .filter(|path| plain_in_quotes(path) && crate::backend::mcp_folder_rule::is_outside(path, work_dir));
227 if wrapper.is_none() {
228 tracing::warn!(work_dir, "no agentmux-bashwrap ships outside this folder: the agent's settings are written without AgentMux's hooks");
229 }
230 hooks_by_path(settings, wrapper.as_deref())
231}
232
233fn hooks_by_path(settings: &str, wrapper: Option<&Path>) -> String {
234 let Ok(mut doc) = serde_json::from_str::<Value>(settings) else { return settings.to_string() };
235 let Some(events) = doc.get_mut("hooks").and_then(Value::as_object_mut) else { return settings.to_string() };
236 for entries in events.values_mut().filter_map(Value::as_array_mut) {
237 for entry in entries.iter_mut() {
238 let Some(hooks) = entry.get_mut("hooks").and_then(Value::as_array_mut) else { continue };
239 hooks.retain_mut(|hook| {
240 let Some(command) = hook.get("command").and_then(Value::as_str) else { return true };
241 let is_ours = command == WRAPPER || command.starts_with(&format!("{WRAPPER} "));
242 if !is_ours {
243 return true;
244 }
245 match wrapper.and_then(|path| wrapper_by_path(command, path)) {
246 Some(by_path) => {
247 hook["command"] = Value::String(by_path);
248 true
249 }
250 None => false,
251 }
252 });
253 }
254 entries.retain(|entry| entry.get("hooks").and_then(Value::as_array).is_none_or(|hooks| !hooks.is_empty()));
255 }
256 serde_json::to_string_pretty(&doc).unwrap_or_else(|_| settings.to_string())
257}
258
259#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, serde::Serialize)]
262pub struct LeftOut {
263 pub settings: usize,
265 pub instructions: usize,
267 pub skills: usize,
268 pub commands: usize,
269 pub agents: usize,
270 pub other: usize,
272}
273
274impl LeftOut {
275 pub fn is_empty(&self) -> bool {
276 *self == Self::default()
277 }
278}
279
280fn count_under(dir: &Path, counts: &dyn Fn(&Path) -> bool) -> usize {
283 fn walk(dir: &Path, depth: usize, seen: &mut usize, counts: &dyn Fn(&Path) -> bool, total: &mut usize) {
284 let Ok(entries) = std::fs::read_dir(dir) else { return };
285 for entry in entries.flatten() {
286 *seen += 1;
287 if *seen > MOST_COUNTED * 10 || *total >= MOST_COUNTED {
288 return;
289 }
290 let Ok(kind) = entry.file_type() else { continue };
291 let path = entry.path();
292 if kind.is_dir() && depth < DEEPEST {
293 walk(&path, depth + 1, seen, counts, total);
294 } else if kind.is_file() && counts(&path) {
295 *total += 1;
296 }
297 }
298 }
299 let (mut seen, mut total) = (0, 0);
300 walk(dir, 0, &mut seen, counts, &mut total);
301 total
302}
303
304fn is_markdown(path: &Path) -> bool {
305 path.extension().is_some_and(|x| x.eq_ignore_ascii_case("md"))
306}
307
308pub fn left_out(folder: &str) -> LeftOut {
313 let folder = Path::new(folder);
314 let claude = folder.join(".claude");
315 let mut out = LeftOut::default();
316 out.settings = usize::from(claude.join("settings.json").is_file()) + usize::from(claude.join("settings.local.json").is_file());
317 out.instructions = usize::from(folder.join("CLAUDE.md").is_file())
318 + usize::from(claude.join("CLAUDE.md").is_file())
319 + usize::from(folder.join("CLAUDE.local.md").is_file())
320 + count_under(&claude.join("rules"), &is_markdown);
321 out.skills = count_under(&claude.join("skills"), &|path| path.file_name().is_some_and(|n| n == "SKILL.md"));
322 out.commands = count_under(&claude.join("commands"), &is_markdown);
323 out.agents = count_under(&claude.join("agents"), &is_markdown);
324 out.other = count_under(&claude.join("output-styles"), &is_markdown)
325 + count_under(&claude.join("workflows"), &|_| true)
326 + usize::from(claude.join("scheduled_tasks.json").is_file());
327 out
328}
329
330pub fn apply_for_spawn(env_vars: &mut std::collections::HashMap<String, String>, block_meta: &crate::backend::obj::MetaMapType) {
335 let provider = crate::backend::providers::resolve_provider_alias(&crate::backend::obj::meta_get_string(block_meta, "agentProvider", ""));
336 if provider != "claude" || crate::backend::mcp_folder_rule::folder_of(block_meta).is_none() {
337 return;
338 }
339 env_vars.insert(SCHEDULER_OFF.to_string(), "1".to_string());
340 env_vars.insert(READ_ADDED_INSTRUCTIONS.to_string(), "1".to_string());
341}
342
343#[cfg(test)]
344#[path = "host_agent_files_tests.rs"]
345mod tests;