Skip to main content

agentmux_srv/server/editor_handlers/
agent_config.rs

1// Copyright 2025-2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! `writeagentconfig`, moved out of `register_editor_handlers` unchanged as named steps: write an agent's
5//! config files atomically into its working directory.
6
7use 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
14/// The stores a config write reads (the agent's picked bundles, its identity links, the pane store).
15pub(super) struct ConfigStores {
16    pub id_store: Arc<Store>,
17    pub mstore: Arc<Store>,
18    pub identity_store: Arc<Store>,
19}
20
21/// Only the window, proven by its host, gets an agent's keys (`hands_out_keys`); an agent writes only its own
22/// (`agent_config_guard`).
23pub(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    // The final path goes back so the caller can patch `cmd:cwd` if collision resolution changed it.
60    Ok(CommandWriteAgentConfigResult { working_dir: final_working_dir })
61}
62
63/// The final on-disk path. An auto-generated instance path (`auto_allocate: true`) uses the atomic `<base>-N`
64/// allocator so concurrent same-hour launches don't share a workdir. A user-specified path is mkdir -p'd and
65/// never rewritten.
66fn 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) // workdir-fs: creates the workdir itself
75            .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    // A host agent in a folder a container agent can write is given its files from outside the folder
82    // (`host_agent_files`), as `agent.open` gives them: nothing is written into the folder.
83    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    // The base is canonicalized ONCE (it exists: allocate_agent_workdir or the explicit-path mkdir -p created
87    // it). The per-file symlink-escape verifier uses it to catch a symlinked ancestor like
88    // `<base>/.claude -> /tmp/outside` before fs::write follows it.
89    let canonical_base = base_path
90        .canonicalize()
91        .map_err(|e| format!("failed to canonicalize working dir {}: {e}", base_path.display()))?;
92
93    // Remove skill-derived files (.claude/commands/*.md, .claude/skills/*/SKILL.md) that WE wrote on a
94    // previous materialization but aren't part of this run's output, e.g. a skill's format switched between
95    // "prompt" and "agent-skill", or a skill was renamed/removed. This is the "click Launch" path used on every
96    // normal agent launch (`launchAgentDefinition`/`WriteAgentConfigCommand`), shared with `agent.open`'s
97    // `write_agent_config_files` (agent_open.rs) via `agent_config.rs` so the two can't drift apart (#2322).
98    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
110/// One config file, written the way its kind needs: CLAUDE.md and the other providers' startup files keep an
111/// existing file's content, `.mcp.json` merges into the user's own, anything else is an atomic workdir write.
112fn write_file(wd: &crate::backend::workdir_fs::Workdir, base_path: &Path, canonical_base: &Path, file: &AgentConfigFile, on_host: bool) -> Result<(), String> {
113    // A lexical join plus traversal check works on Windows where canonicalize() adds the `\\?\` UNC prefix and
114    // breaks starts_with against not-yet-created files. It catches `..`, absolute paths and drive-letter
115    // prefixes (root and inner).
116    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    // The symlink-escape guard: if any EXISTING ancestor is a symlink that resolves outside the workdir, reject.
119    // A no-op for fully fresh agent dirs. Like a refused write below, this skips that one file rather than
120    // failing the launch, as agent.open does (#4141).
121    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    // Global Memory is already in `file.content` (`picker_config`), so launching from the picker gives the same
126    // workspace rules as the agent.open RPC path.
127    if file.path == "CLAUDE.md" {
128        // Ownership-aware materialization instead of the generic write below: never overwrites a pre-existing,
129        // non-AgentMux-authored file's content. See docs/specs/SPEC_CLAUDE_MD_OWNERSHIP_PROTECTION_2026_08_22.md.
130        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    // This RPC command carries no provider ID (`CommandWriteAgentConfigData` is just `{working_dir, files}`:
136    // the frontend already resolved everything), so a non-Claude provider's startup-instructions file
137    // (AGENTS.md, GEMINI.md, QWEN.md, .pi/APPEND_SYSTEM.md, ...) is recognized by filename membership against
138    // the provider registry, not a literal string match.
139    if crate::backend::providers::is_known_startup_instructions_filename(&file.path) {
140        // Never overwrites a pre-existing file (#2788): a simpler exists-guard than CLAUDE.md's full
141        // ownership-aware materialization. See write_startup_instructions_respecting_existing for why a fuller
142        // mechanism (the @import-based side-file fallback) isn't attempted here.
143        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    // `.mcp.json` never goes into a user's project (#3680): in a folder AgentMux owns it merges into the
149    // agent's own file; elsewhere it is written under the data directory, outside the project. A host
150    // agent's also goes outside a folder a container agent can write, with nothing of that folder's file.
151    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    // Atomic, parents created inside the workdir, never through a symlinked file
171    // (SPEC_WORKDIR_SAFE_WRITES_2026_10_01). A refusal skips that one file, as agent.open does (#4141); any
172    // other failure fails the launch.
173    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    /// The window's Launch, for a host agent in a folder a container agent has run in: every file goes to the
197    /// agent's own folder outside it, as `agent.open` writes them, and nothing into the folder. The container
198    /// agent's own launch there, and a host launch into any other folder, write into the folder as before.
199    #[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}