Skip to main content

agentmux_srv/server/app_api/
agent_config_render.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4use serde_json::json;
5
6use crate::backend::storage::store::Store;
7
8/// The files an agent launch writes into its working directory, whichever way it was started: `agent.open`
9/// ([`super::agent_open::write_agent_config_files`]) and the window's Launch (`writeagentconfig`, `picker_config::launch_files`)
10/// both render them here, so a native and a container agent, and the two entry points, share one builder.
11/// `display_name` is what `{{AGENT}}` and `{{AGENT_DISPLAY}}` expand to (a launch's instance name, or the
12/// agent's name); `workdir_is_shared` is whether other launches of the agent use the same folder.
13pub(crate) fn render_agent_config_files(
14    mstore: &Store,
15    id_store: &Store,
16    identity_store: &Store,
17    agent: &crate::backend::storage::AgentDefinition,
18    display_name: &str,
19    agent_slug: &str,
20    work_dir: &str,
21    workdir_is_shared: bool,
22) -> Vec<crate::backend::agent_config::AgentConfigFile> {
23    // The agent's content, with Global Memory and its picked bundles put
24    // before its own memory (shared with `memory:launchcost`).
25    let mut content_map = crate::server::memory_launch_cost::startup_content_map(mstore, id_store, agent);
26
27    // Disable autonomous memory writes only when using the bare slug-fallback workdir
28    // (~/.agentmux/agents/<slug>) — that path is shared across same-name multi-tab
29    // launches with no collision resolution, risking concurrent MEMORY.md corruption
30    // (upstream issue #29051). Any explicitly set workdir, or one a launch allocated, is isolated and
31    // keeps writes on.
32    if workdir_is_shared {
33        disable_autonomous_memory(&mut content_map, work_dir);
34    }
35
36    // v1 skills: globals are always injected; the agent's OWN ref-bound skills
37    // are authoritative when present, otherwise fall back to legacy
38    // db_agent_skills. See Store::effective_skills for the merge algorithm —
39    // shared with the `listagentskills` RPC handler so the frontend's
40    // pre-launch skill fetch and this materialization path never diverge.
41    let effective_skills = mstore.effective_skills(identity_store, &agent.id);
42
43    let mut config_files = crate::backend::agent_config::build_config_files(
44        &content_map,
45        &effective_skills,
46        display_name,
47        &agent.id,
48        agent_slug,
49        work_dir,
50        &agent.provider,
51    );
52    // The files beside a computer-use skill's SKILL.md (its reference files and approved scripts).
53    config_files.extend(crate::backend::computer_use_skill::sibling_files(&effective_skills, identity_store));
54
55    // v1 MCP: "agentmux" plus the agent's effective servers. The
56    // legacy blob's user servers are merged in ONLY when the agent has no own
57    // ref-bound servers (so a global server never wipes a legacy-only agent's
58    // .mcp.json). When the agent has own refs, those are authoritative.
59    // A bundle carries no MCP servers
60    // (SPEC_BUNDLE_CONTENTS_MEMORY_NOT_MCP_2026_10_07.md §3.1), so bundles
61    // add none.
62    let visible_mcp: Vec<crate::backend::storage::McpServer> = mstore.effective_mcp_servers(identity_store, &agent.id, agent.runtime().is_container());
63    let has_own_mcp_refs = visible_mcp.iter().any(|server| !server.is_global);
64    if !visible_mcp.is_empty() {
65        let blob_for_merge = if has_own_mcp_refs {
66            None
67        } else {
68            content_map.get("mcp").map(|s| s.as_str())
69        };
70        if let Some(mcp_json) = crate::backend::agent_config::build_mcp_config_from_refs(
71            &visible_mcp,
72            blob_for_merge,
73            agent_slug,
74            &agent.agent_bus_id,
75        ) {
76            if let Some(pos) = config_files.iter().position(|f| f.filename == ".mcp.json") {
77                config_files[pos].content = mcp_json;
78            } else {
79                config_files.push(crate::backend::agent_config::AgentConfigFile {
80                    filename: ".mcp.json".to_string(),
81                    content: mcp_json,
82                });
83            }
84        }
85    }
86
87    // Host-tier + LAN-tier jekt sender signing keys
88    // (SPEC_JEKT_TRUST_LAYER_COMPLETION_2026_08_13.md §2.2,
89    // SPEC_JEKT_LAN_TIER_SIGNING_2026_08_15.md §2.1) — inject
90    // ensure the agent's keys in the store and write the rest of the agentmux
91    // MCP server's env, right alongside AGENTMUX_AGENT_ID. No signing value is
92    // written: the MCP fetches its keys from srv (`GET /agentmux/agents/self/keys`)
93    // so the `Message` tool can sign outgoing jekts as this agent.
94    // Best-effort: a failure here must never block agent spawn — the agent
95    // still launches; only without its keys do its jekts go unsigned.
96    // Shared with `WriteAgentConfig`
97    // (server/editor_handlers.rs, the "click Launch" path) via
98    // `agent_config::inject_jekt_signing_keys_into_mcp_json` — see that
99    // function's doc comment for why this must not be duplicated inline
100    // again.
101    if let Some(file) = config_files.iter_mut().find(|f| f.filename == ".mcp.json") {
102        crate::backend::mcp_json_identity::keys_for_agent_open(&mut file.content, &mstore, agent_slug, &agent);
103    }
104    config_files
105}
106
107/// Turn autonomous memory writes off in the agent's settings: the folder is shared by every same-name launch.
108fn disable_autonomous_memory(content_map: &mut std::collections::HashMap<String, String>, work_dir: &str) {
109    let settings_str = content_map
110        .entry("settings".to_string())
111        .or_insert_with(|| "{}".to_string());
112    match serde_json::from_str::<serde_json::Map<String, serde_json::Value>>(settings_str) {
113        Ok(mut obj) => {
114            obj.entry("autoMemoryEnabled".to_string())
115                .or_insert(json!(false));
116            *settings_str =
117                serde_json::to_string(&obj).unwrap_or_else(|_| "{}".to_string());
118        }
119        Err(e) => {
120            tracing::warn!(
121                work_dir = %work_dir,
122                error = %e,
123                "write_agent_config_files: settings JSON unparseable; \
124                 autoMemoryEnabled guard skipped — memory writes may be active on shared workdir"
125            );
126        }
127    }
128}
129
130/// Write one rendered config file into the working directory, the way its kind is written (ownership-aware,
131/// exists-guarded, merged, or plainly); a path the workdir refuses is skipped with a warning.
132pub(super) fn write_config_file(
133    wd: &crate::backend::workdir_fs::Workdir,
134    base_path: &std::path::Path,
135    expanded_dir: &str,
136    file: &crate::backend::agent_config::AgentConfigFile,
137    on_host: bool,
138) -> Result<(), String> {
139    // CLAUDE.md never gets the generic write below — it goes through
140    // ownership-aware materialization instead, which never overwrites
141    // a pre-existing, non-AgentMux-authored file's content. See
142    // docs/specs/SPEC_CLAUDE_MD_OWNERSHIP_PROTECTION_2026_08_22.md.
143    if file.filename == "CLAUDE.md" {
144        if let Err(e) =
145            crate::backend::agent_config::write_claude_md_respecting_ownership(base_path, &file.content)
146        {
147            return Err(format!("failed to write CLAUDE.md: {e}"));
148        }
149        return Ok(());
150    }
151    // Every OTHER provider's startup-instructions filename (AGENTS.md,
152    // GEMINI.md, QWEN.md, .pi/APPEND_SYSTEM.md) never overwrites a
153    // pre-existing file — codex P1, PR #2788: unlike CLAUDE.md's full
154    // ownership-aware materialization above, this is a plain
155    // exists-guard (see write_startup_instructions_respecting_existing's
156    // own doc comment for why a fuller mechanism isn't attempted here).
157    if crate::backend::providers::is_known_startup_instructions_filename(&file.filename) {
158        crate::backend::agent_config::write_startup_instructions_respecting_existing(
159            base_path,
160            &file.filename,
161            &file.content,
162        )
163        .map_err(|e| format!("failed to write {}: {e}", file.filename))?;
164        return Ok(());
165    }
166    // `.mcp.json` never goes into a user's project (#3680): in a folder AgentMux owns it
167    // merges into the agent's own file as before; elsewhere it is written under the data
168    // directory, outside the project, and Claude is pointed at it at spawn. A host agent's
169    // also goes outside a folder a container agent can write, and is not merged with what
170    // that folder's file holds.
171    if file.filename == ".mcp.json" {
172        let outside = if on_host {
173            crate::backend::mcp_config_file::host_relocated_path(expanded_dir)
174        } else {
175            crate::backend::mcp_config_file::relocated_path(expanded_dir)
176        };
177        if let Some(path) = outside {
178            let content = if on_host { crate::backend::mcp_config_file::host_content(expanded_dir, file.content.clone()) } else { file.content.clone() };
179            crate::backend::mcp_config_file::write_relocated(&path, &content)
180                .map_err(|e| format!("failed to write the agent's MCP config: {e}"))?;
181            return Ok(());
182        }
183        crate::backend::agent_config::write_mcp_json_respecting_user_servers(base_path, &file.content)
184            .map_err(|e| format!("failed to write .mcp.json: {e}"))?;
185        return Ok(());
186    }
187    // Through the workdir (SPEC_WORKDIR_SAFE_WRITES_2026_10_01): a path
188    // outside it, under a folder linking out of it, or onto a symlink is
189    // refused and skipped, like an escaping path always was here.
190    match wd.write(&file.filename, file.content.as_bytes(), false) {
191        Err(e) if e.kind() == std::io::ErrorKind::PermissionDenied => {
192            tracing::warn!(
193                work_dir = %expanded_dir,
194                path = %file.filename,
195                error = %e,
196                "write_agent_config_files: refusing to write a config path outside the working directory"
197            );
198        }
199        other => other.map_err(|e| format!("failed to write {}: {e}", file.filename))?,
200    }
201
202    Ok(())
203}
204
205#[cfg(test)]
206mod tests {
207    use super::*;
208    use crate::backend::agent_config::AgentConfigFile;
209
210    fn files_under(dir: &std::path::Path) -> Vec<std::path::PathBuf> {
211        let mut out = Vec::new();
212        let mut stack = vec![dir.to_path_buf()];
213        while let Some(path) = stack.pop() {
214            for entry in std::fs::read_dir(&path).unwrap().flatten() {
215                let path = entry.path();
216                if path.is_dir() {
217                    stack.push(path);
218                } else {
219                    out.push(path);
220                }
221            }
222        }
223        out
224    }
225
226    /// #3680: a launch into the user's own project must leave the project's `.mcp.json` exactly
227    /// as it was and write no signing material anywhere under the project. The agent's config
228    /// goes to AgentMux's data root, where Claude is pointed at it and the other harnesses read it.
229    #[test]
230    fn a_launch_into_a_user_project_leaves_its_mcp_json_alone_and_writes_no_keys_there() {
231        let data = tempfile::tempdir().unwrap();
232        let project = tempfile::tempdir().unwrap();
233        let project_mcp = project.path().join(".mcp.json");
234        let original = "{\n  \"mcpServers\": {\n    \"postgres\": { \"command\": \"pg-mcp\" }\n  },\n  \"kept\": true\n}\n";
235        std::fs::write(&project_mcp, original).unwrap();
236        let project_str = project.path().to_string_lossy().into_owned();
237
238        let relocated = crate::backend::mcp_config_file::with_data_home(data.path(), || {
239            let wd = crate::backend::workdir_fs::Workdir::open(project.path()).unwrap();
240            let file = AgentConfigFile {
241                filename: ".mcp.json".into(),
242                content: r#"{"mcpServers":{"agentmux":{"command":"agentmux-mcp","env":{"AGENTMUX_AGENT_ID":"aria","AGENTMUX_JEKT_KEY":"PRIVATE-JEKT","AGENTMUX_LAN_KEY":"PRIVATE-LAN"}}}}"#.into(),
243            };
244            write_config_file(&wd, project.path(), &project_str, &file, true).unwrap();
245            crate::backend::mcp_config_file::config_path(&project_str)
246        });
247
248        assert_eq!(
249            std::fs::read_to_string(&project_mcp).unwrap(),
250            original,
251            "the user's .mcp.json is byte-for-byte unchanged"
252        );
253        for file in files_under(project.path()) {
254            let body = std::fs::read_to_string(&file).unwrap_or_default();
255            assert!(
256                !body.contains("AGENTMUX_JEKT_KEY") && !body.contains("PRIVATE-JEKT") && !body.contains("PRIVATE-LAN"),
257                "no signing material may appear under the project: {file:?}"
258            );
259        }
260        assert!(!project.path().join(".claude").join(".agentmux-managed-mcp-servers.json").exists());
261        assert!(relocated.starts_with(data.path().join("mcp")), "{relocated:?}");
262        let written = std::fs::read_to_string(&relocated).unwrap();
263        assert!(written.contains("agentmux-mcp"), "{written}");
264        assert!(written.contains("PRIVATE-JEKT"), "the agent's own config may carry its keys: {written}");
265    }
266
267    /// A folder AgentMux owns keeps its own `.mcp.json` (the default agent home), so nothing changes
268    /// there and Claude finds it without a flag.
269    #[test]
270    fn a_launch_into_an_agentmux_folder_keeps_the_file_in_it() {
271        let data = tempfile::tempdir().unwrap();
272        let home = data.path().join("agents").join("aria");
273        std::fs::create_dir_all(&home).unwrap();
274        let home_str = home.to_string_lossy().into_owned();
275        let relocated = crate::backend::mcp_config_file::with_data_home(data.path(), || {
276            let wd = crate::backend::workdir_fs::Workdir::open(&home).unwrap();
277            let file = AgentConfigFile {
278                filename: ".mcp.json".into(),
279                content: r#"{"mcpServers":{"agentmux":{"command":"agentmux-mcp"}}}"#.into(),
280            };
281            write_config_file(&wd, &home, &home_str, &file, true).unwrap();
282            crate::backend::mcp_config_file::relocated_path(&home_str)
283        });
284        assert!(home.join(".mcp.json").is_file());
285        assert!(relocated.is_none());
286    }
287
288    /// A host agent's launch into a folder a container agent ran in: the config goes outside the folder with
289    /// the launch's servers only, and the folder's own file, with whatever it lists, is neither read nor written.
290    #[test]
291    fn a_host_launch_into_a_container_agents_folder_keeps_its_config_outside_and_takes_none_of_the_folders_servers() {
292        let data = tempfile::tempdir().unwrap();
293        let home = data.path().join("agents").join("aria");
294        std::fs::create_dir_all(&home).unwrap();
295        let home_str = home.to_string_lossy().into_owned();
296        let theirs = r#"{"mcpServers":{"agentmux":{"command":"other"},"theirs":{"command":"theirs-mcp"}}}"#;
297        std::fs::write(home.join(".mcp.json"), theirs).unwrap();
298        let file = AgentConfigFile {
299            filename: ".mcp.json".into(),
300            content: r#"{"mcpServers":{"agentmux":{"command":"agentmux-mcp","env":{"AGENTMUX_JEKT_KEY":"PRIVATE-JEKT"}}}}"#.into(),
301        };
302        let outside = crate::backend::mcp_config_file::with_data_home(data.path(), || {
303            crate::backend::mcp_folder_rule::mark(&home_str);
304            let wd = crate::backend::workdir_fs::Workdir::open(&home).unwrap();
305            write_config_file(&wd, &home, &home_str, &file, true).unwrap();
306            crate::backend::mcp_config_file::host_config_path(&home_str)
307        });
308        assert!(outside.starts_with(data.path().join(agentmux_common::mcp_config_path::HOST_ONLY_DIR)) && !outside.starts_with(&home), "{outside:?}");
309        let text = std::fs::read_to_string(&outside).unwrap();
310        let written: serde_json::Value = serde_json::from_str(&text).unwrap();
311        // The command by its path (where an `agentmux-mcp` ships on this computer), never the bare name.
312        assert!(crate::backend::mcp_folder_rule::names_the_command_by_path(&text), "{text}");
313        assert_ne!(written["mcpServers"]["agentmux"]["command"], "agentmux-mcp");
314        assert!(written["mcpServers"].as_object().unwrap().keys().all(|name| name == "agentmux"), "none of the folder's servers: {written}");
315        assert_eq!(std::fs::read_to_string(home.join(".mcp.json")).unwrap(), theirs, "the folder's file is left as it is");
316        for file in files_under(&home) {
317            assert!(!std::fs::read_to_string(&file).unwrap_or_default().contains("PRIVATE-JEKT"), "no signing key in the folder: {file:?}");
318        }
319    }
320
321    /// The container agent's own launch into that folder is as it was: its file is the one in the folder.
322    #[test]
323    fn a_container_agents_own_launch_still_writes_the_file_in_its_folder() {
324        let data = tempfile::tempdir().unwrap();
325        let home = data.path().join("agents").join("aria");
326        std::fs::create_dir_all(&home).unwrap();
327        let home_str = home.to_string_lossy().into_owned();
328        let file = AgentConfigFile { filename: ".mcp.json".into(), content: r#"{"mcpServers":{"agentmux":{"command":"agentmux-mcp"}}}"#.into() };
329        crate::backend::mcp_config_file::with_data_home(data.path(), || {
330            crate::backend::mcp_folder_rule::mark(&home_str);
331            let wd = crate::backend::workdir_fs::Workdir::open(&home).unwrap();
332            write_config_file(&wd, &home, &home_str, &file, false).unwrap();
333            assert!(!crate::backend::mcp_config_file::host_config_path(&home_str).exists(), "nothing is written outside for it");
334        });
335        assert!(std::fs::read_to_string(home.join(".mcp.json")).unwrap().contains("agentmux-mcp"));
336    }
337}