Skip to main content

agentmux_srv/server/
picker_config.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! What `writeagentconfig` (the window's Launch) writes for an agent, before it is written: the files the
5//! window built, with what srv adds to them. The catalog's MCP servers go into `.mcp.json`
6//! ([`mcp_launch::add_to_files`]), the launch's agent id and signing keys
7//! ([`mcp_json_identity::finish_launch`]), and Global Memory and the agent's picked bundles into the startup
8//! file ([`inject_global_bundles`]). Pure, so a test can render a launch without a socket or a disk: the
9//! parity test (`agent_config_parity_tests`) compares it with `agent.open`'s.
10
11use std::sync::Arc;
12
13use crate::backend::rpc_types::AgentConfigFile;
14use crate::backend::storage::store::Store;
15
16use super::app_api::agent_config_render::render_agent_config_files;
17use super::editor_handlers::inject_global_bundles;
18
19/// `files` as the window sent them, with what srv adds for `agent_id` launched as `agent_mode`
20/// (`host` or `container`). Keys go only when `hands_out_keys` (the window, proven by its host) and the
21/// agent is not a container agent.
22pub(crate) fn picker_files(
23    mut files: Vec<AgentConfigFile>,
24    mstore: &Arc<Store>,
25    id_store: &Arc<Store>,
26    identity_store: &Arc<Store>,
27    agent_id: Option<&str>,
28    agent_mode: &str,
29    hands_out_keys: bool,
30) -> Vec<AgentConfigFile> {
31    // The bundles picked for the agent go into its startup file after Global Memory. An older frontend
32    // sends no agent id: then there are none.
33    let agent_block = agent_id
34        .filter(|id| !id.is_empty())
35        .map(|id| {
36            crate::backend::storage::format_agent_bundle_block(&crate::backend::storage::agent_picked_bundles(
37                mstore, id_store, id,
38            ))
39        })
40        .unwrap_or_default();
41    // The agent's catalog servers, as `agent.open` gives them.
42    let runtime = crate::backend::runtime_adapter::RuntimeKind::of_agent_mode(agent_mode);
43    let container = runtime.is_container();
44    crate::backend::mcp_launch::add_to_files(&mut files, mstore, identity_store, agent_id, container);
45    // The launch's .mcp.json signs as the definition's agent; the window's launch also carries that
46    // agent's signing keys, never a container agent's.
47    crate::backend::mcp_json_identity::finish_launch(&mut files, mstore, agent_id, hands_out_keys && runtime.adapter().carries_signing_keys());
48    // The startup file gets the same Global Memory `agent.open` puts in it. This RPC carries no provider
49    // id, so a startup-instructions file is recognized by filename against the provider registry.
50    for file in &mut files {
51        if file.path == "CLAUDE.md" || crate::backend::providers::is_known_startup_instructions_filename(&file.path) {
52            file.content = inject_global_bundles(&file.content, id_store, agent_mode, &agent_block);
53        }
54    }
55    files
56}
57
58/// The files the window's Launch writes for `agent_id` into `work_dir`, rendered in Rust exactly as `agent.open`
59/// renders them ([`render_agent_config_files`]), so the window sends no file content of its own. `instance_name`
60/// is the launch's name for the agent (a modal-supplied one), `None` for the agent's own. The launch's folder is
61/// its own (allocated or named by the caller), never the fallback folder every same-name launch shares. Whether
62/// the agent is a container agent is the definition's (`agent_type`), as in `agent.open`.
63pub(crate) fn launch_files(
64    mstore: &Store,
65    id_store: &Store,
66    identity_store: &Store,
67    agent_id: &str,
68    instance_name: Option<&str>,
69    work_dir: &str,
70) -> Result<Vec<AgentConfigFile>, String> {
71    let mut agent = mstore
72        .agent_def_get(agent_id)
73        .map_err(|e| format!("failed to read agent {agent_id}: {e}"))?
74        .ok_or_else(|| format!("unknown agent {agent_id}"))?;
75    // The agent's own provider, or its bundle's when it has none, as `agent.open` settles it (from `id_store`, never
76    // `mstore`): the startup file's name depends on it.
77    agent.provider = id_store.resolve_effective_provider_id(&agent);
78    let display_name = instance_name.map(str::trim).filter(|n| !n.is_empty()).unwrap_or(&agent.name);
79    let slug = if agent.slug.is_empty() { agentmux_common::slug::definition_slug(&agent.name) } else { agent.slug.clone() };
80    let files = render_agent_config_files(mstore, id_store, identity_store, &agent, display_name, &slug, work_dir, false);
81    Ok(files.into_iter().map(|f| AgentConfigFile { path: f.filename, content: f.content }).collect())
82}
83
84/// The files `writeagentconfig` writes into `work_dir`: rendered from the agent's definition when the window asks
85/// (`render_from_agent`; after the folder is allocated, so the files name the folder they are in), otherwise the
86/// ones the caller sent with what srv adds to them ([`picker_files`]).
87pub(crate) fn files_to_write(
88    sent: Vec<AgentConfigFile>,
89    mstore: &Arc<Store>,
90    id_store: &Arc<Store>,
91    identity_store: &Arc<Store>,
92    cmd: &crate::backend::rpc_types::CommandWriteAgentConfigData,
93    agent_mode: &str,
94    hands_out_keys: bool,
95    work_dir: &str,
96) -> Result<Vec<AgentConfigFile>, String> {
97    if !cmd.render_from_agent {
98        return Ok(picker_files(sent, mstore, id_store, identity_store, cmd.agent_id.as_deref(), agent_mode, hands_out_keys));
99    }
100    let agent_id = render_request_agent(mstore, cmd, hands_out_keys)?;
101    launch_files(mstore, id_store, identity_store, &agent_id, cmd.instance_name.as_deref(), work_dir)
102}
103
104/// A request without `render_from_agent` is not checked here. Otherwise, as [`render_request_agent`].
105pub(crate) fn check_render_request(
106    mstore: &Store,
107    cmd: &crate::backend::rpc_types::CommandWriteAgentConfigData,
108    hands_out_keys: bool,
109) -> Result<(), String> {
110    if cmd.render_from_agent {
111        render_request_agent(mstore, cmd, hands_out_keys)?;
112    }
113    Ok(())
114}
115
116/// The agent a `render_from_agent` request names, or why it is refused: only the window may ask, and it must name an
117/// agent that exists. Checked before the working folder is allocated, so a refused request leaves no folder behind.
118pub(crate) fn render_request_agent(
119    mstore: &Store,
120    cmd: &crate::backend::rpc_types::CommandWriteAgentConfigData,
121    hands_out_keys: bool,
122) -> Result<String, String> {
123    if !hands_out_keys {
124        return Err("FORBIDDEN: only the AgentMux window renders an agent's launch files".to_string());
125    }
126    let id = cmd.agent_id.as_deref().map(str::trim).filter(|id| !id.is_empty()).ok_or("render_from_agent needs an agent_id")?;
127    match mstore.agent_def_get(id) {
128        Ok(Some(_)) => Ok(id.to_string()),
129        Ok(None) => Err(format!("unknown agent {id}")),
130        Err(e) => Err(format!("failed to read agent {id}: {e}")),
131    }
132}
133
134#[cfg(test)]
135mod tests {
136    use super::*;
137
138    fn cmd(agent_id: &str) -> crate::backend::rpc_types::CommandWriteAgentConfigData {
139        serde_json::from_value(serde_json::json!({
140            "working_dir": "w", "files": [], "auto_allocate": false, "agent_id": agent_id, "render_from_agent": true
141        }))
142        .unwrap()
143    }
144
145    #[test]
146    fn only_the_window_renders_an_agents_launch_files() {
147        let store = Arc::new(Store::open_in_memory().unwrap());
148        let refused = files_to_write(Vec::new(), &store, &store, &store, &cmd("someone"), "host", false, "w");
149        assert!(refused.unwrap_err().starts_with("FORBIDDEN"), "an agent connection must not render launch files");
150    }
151
152    #[test]
153    fn rendering_without_an_agent_id_fails_instead_of_writing_nothing() {
154        let store = Arc::new(Store::open_in_memory().unwrap());
155        let err = files_to_write(Vec::new(), &store, &store, &store, &cmd(""), "host", true, "w").unwrap_err();
156        assert!(err.contains("needs an agent_id"), "{err}");
157    }
158
159    #[test]
160    fn rendering_an_unknown_agent_fails_instead_of_writing_nothing() {
161        let store = Arc::new(Store::open_in_memory().unwrap());
162        let err = files_to_write(Vec::new(), &store, &store, &store, &cmd("no-such-agent"), "host", true, "w").unwrap_err();
163        assert!(err.contains("unknown agent"), "{err}");
164    }
165
166    #[test]
167    fn without_the_flag_the_sent_files_are_written_as_before() {
168        let store = Arc::new(Store::open_in_memory().unwrap());
169        let mut c = cmd("someone");
170        c.render_from_agent = false;
171        let sent = vec![AgentConfigFile { path: "notes.txt".into(), content: "x".into() }];
172        let files = files_to_write(sent, &store, &store, &store, &c, "host", true, "w").unwrap();
173        assert!(files.iter().any(|f| f.path == "notes.txt" && f.content == "x"));
174    }
175
176    #[test]
177    fn an_agent_with_no_provider_of_its_own_gets_its_bundles_startup_file() {
178        let store = Arc::new(Store::open_in_memory().unwrap());
179        store
180            .bundle_upsert(&crate::backend::storage::bundles::Bundle {
181                id: "b1".into(),
182                name: "b1".into(),
183                description: String::new(),
184                is_blank: false,
185                is_global: false,
186                provider: "gemini".into(),
187                model: String::new(),
188                instructions: String::new(),
189                instructions_by_provider: "{}".into(),
190                context_files: "[]".into(),
191                mcp_servers: "[]".into(),
192                skills: "[]".into(),
193                sort_order: 0,
194                created_at: 0,
195                updated_at: 0,
196                is_system: false,
197            })
198            .unwrap();
199        let mut def = crate::backend::storage::agents::test_agent_def("pf", "Provider Fallback", "", "host", 1, "");
200        def.memory_id = "b1".into();
201        store.agent_def_insert(&mut def).unwrap();
202        let files = launch_files(&store, &store, &store, "pf", None, "w").unwrap();
203        assert!(files.iter().any(|f| f.path == "GEMINI.md"), "the window launched the bundle's provider: {:?}", files.iter().map(|f| &f.path).collect::<Vec<_>>());
204    }
205}