Skip to main content

agentmux_srv_core/backend/
host_agent_files.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! What a host Claude Code agent is given from outside its folder, where a container agent can write the folder.
5//!
6//! In a folder the rule of [`mcp_folder_rule`](crate::backend::mcp_folder_rule) holds for, a host agent's CLI
7//! takes nothing of the folder's own configuration: it is started with the setting sources limited to the
8//! person's own (`agent_mcp_flag`), so the folder's settings, hooks, instruction files, skills, commands,
9//! subagents, output styles, workflows and plugins are not loaded, and with its scheduler off
10//! ([`apply_for_spawn`]), because a scheduled prompt can be kept in the folder. What AgentMux itself gives the
11//! agent is written beside its MCP config, in the folder kept for host agents alone, and named to the CLI:
12//!
13//! - `settings.json`: AgentMux's hooks, each named by the path of the wrapper that ships with this install, and
14//!   the agent's own settings ([`settings_with_hooks_by_path`]);
15//! - `instructions/CLAUDE.md`: the agent's startup instructions;
16//! - `plugin/`: the agent's skills and commands, which the CLI lists as `agentmux:<name>`.
17//!
18//! A host launch writes none of these into the folder there ([`write`]), and the pane is told what of the
19//! folder was not loaded, by kind and count ([`left_out`]).
20//!
21//! What each flag and variable keeps out was checked against a live CLI, per kind of file, with the version
22//! named by [`CHECKED_WITH_CLAUDE_CODE`]. The check is repeated when the pinned version moves.
23
24use std::path::{Path, PathBuf};
25
26use serde_json::Value;
27
28use agentmux_common::mcp_config_path as shared;
29
30/// The Claude Code version the flags and variables of this module were last checked against, kind by kind.
31/// It follows the pinned version: a test fails when the pin moves until the check has been run again.
32pub const CHECKED_WITH_CLAUDE_CODE: &str = "2.1.321";
33
34/// The plugin AgentMux's own skills and commands are given as: the CLI lists them as `agentmux:<name>`.
35pub 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";
42/// The names of the agent's own MCP servers that the last launch left out of its config: their command is a
43/// bare name with no path outside the folder on this computer.
44const SERVERS_WITH_NO_PATH: &str = "servers-with-no-path.json";
45
46/// The most entries one folder walk counts: a row says "200+" beyond it.
47const MOST_COUNTED: usize = 200;
48/// How deep a walk goes under a `.claude` folder of the folder.
49const DEEPEST: usize = 4;
50
51/// The variable that turns the CLI's scheduler off: nothing scheduled fires, and `/loop` and `CronCreate` are
52/// not offered.
53const SCHEDULER_OFF: &str = "CLAUDE_CODE_DISABLE_CRON";
54/// The variable that has the CLI read the `CLAUDE.md` of a folder it is given with `--add-dir`.
55const READ_ADDED_INSTRUCTIONS: &str = "CLAUDE_CODE_ADDITIONAL_DIRECTORIES_CLAUDE_MD";
56
57/// Where a host agent of `work_dir` is given its own files, when the rule holds for the folder. Reads the disk
58/// and the store.
59pub 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
67/// AgentMux's settings for the agent, in `dir` ([`dir_of`]).
68pub fn settings_path(dir: &Path) -> PathBuf {
69    dir.join(SETTINGS_FILE)
70}
71
72/// The folder that holds the agent's startup instructions and nothing else, in `dir`.
73pub fn instructions_dir(dir: &Path) -> PathBuf {
74    dir.join(INSTRUCTIONS_DIR)
75}
76
77/// The agent's startup instructions, in `dir`.
78pub fn instructions_path(dir: &Path) -> PathBuf {
79    instructions_dir(dir).join(INSTRUCTIONS_FILE)
80}
81
82/// The plugin folder that holds the agent's skills and commands, in `dir`.
83pub fn plugin_dir(dir: &Path) -> PathBuf {
84    dir.join(PLUGIN_DIR)
85}
86
87/// Where the launch file `name` (as a launch names it, relative to the working folder) goes under the agent's
88/// own folder, or `None` for a file that is not given to a host Claude Code agent from outside.
89fn 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
105/// Write a host launch's files for `work_dir`, a folder the rule holds for: each goes to the agent's own folder
106/// outside it, and nothing is written into the folder. `files` are (name, content) as the launch rendered them.
107/// The skills and instructions of an earlier launch are removed first. A file with no place outside (another
108/// harness's startup file) is not written: no other harness is started there. `Ok(false)` when the rule does
109/// not hold and the caller writes into the folder as before.
110pub 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
147/// The agent's skills and commands for `work_dir` again, as a controller start refreshes them: only the plugin
148/// folder outside is rewritten, and nothing is written into the folder. `Ok(false)` when the rule does not hold.
149pub 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
174/// The agent's own MCP servers the last launch left out of its config in `dir` ([`dir_of`]), by name: each is
175/// set with a bare command that has no path outside the folder on this computer.
176pub 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
183/// Write the agent's startup instructions for `work_dir` again (a refresh while it runs). `Ok(false)` when the
184/// rule does not hold for the folder, or no launch has written them yet.
185pub 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
194/// The startup instructions as the file holds them: under the line that says AgentMux wrote the file, as the
195/// startup file in an agent's own folder is, so what reads it back knows it for AgentMux's.
196fn 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
204/// The hook command `command` with AgentMux's wrapper named by `wrapper`'s path; `None` for a command that is
205/// not the wrapper's. A path is quoted, with forward slashes, so one shell word names it on every platform.
206fn 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
215/// Whether `path` can stand in a quoted shell word as it is.
216fn plain_in_quotes(path: &Path) -> bool {
217    !path.to_string_lossy().chars().any(|c| matches!(c, '"' | '$' | '`' | '\n'))
218}
219
220/// `settings` (the text of the settings AgentMux renders for an agent) as it is given to a host agent of
221/// `work_dir`: each of AgentMux's own hooks names the wrapper by the absolute path of the one that ships with
222/// this install, never by a bare name. Where none ships outside the folder, those hooks are taken out: no hook
223/// rather than a command found by name. Text that is not a JSON object is returned as it is.
224pub 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/// What of a folder's own files a host agent there is not given, by kind: how many of each. Counted, never
260/// read as configuration.
261#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, serde::Serialize)]
262pub struct LeftOut {
263    /// `.claude/settings.json` and `.claude/settings.local.json`.
264    pub settings: usize,
265    /// `CLAUDE.md`, `.claude/CLAUDE.md`, `CLAUDE.local.md` and the rules under `.claude/rules`.
266    pub instructions: usize,
267    pub skills: usize,
268    pub commands: usize,
269    pub agents: usize,
270    /// Output styles, workflows and the file of scheduled prompts.
271    pub other: usize,
272}
273
274impl LeftOut {
275    pub fn is_empty(&self) -> bool {
276        *self == Self::default()
277    }
278}
279
280/// The files under `dir` (to [`DEEPEST`]) that `counts` says yes to, at most [`MOST_COUNTED`]. Links are not
281/// followed.
282fn 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
308/// What of `folder`'s own files a host agent there is not given, every one counted: the agent is given
309/// AgentMux's own settings, instructions, skills and commands from outside, so none of these is read, a file
310/// AgentMux wrote there at an earlier launch included. A file can't be told for AgentMux's by what it says,
311/// since a container agent can write that too. Only looks at names.
312pub 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
330/// The environment of a host Claude Code agent's CLI in a folder the rule holds for: its scheduler is off (a
331/// scheduled prompt can be kept in the folder, and would run as a turn of this agent), and it reads the
332/// startup instructions of the folder AgentMux adds for it. Set over whatever the agent's own environment
333/// says. Every other agent's environment is left as it is.
334pub 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;