Skip to main content

agentmux_srv_core/backend/
runtime_adapter.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Where an agent runs, behind one trait.
5//!
6//! An agent is a process on this machine (`NativeAdapter`) or a `docker exec` in its container
7//! (`ContainerAdapter`). What differs between the two used to be answered at each place that asked
8//! "is this a container agent?" (the env a turn gets, how a container reaches srv, which controller
9//! may host a provider, whether attachments work, how a turn is launched). Each answer is now a
10//! method here, so a new runtime (WSL, remote) is one more impl and the callers do not change.
11//!
12//! The methods:
13//! - [`credentials`](RuntimeAdapter::credentials): the env a turn's process is given, with the
14//!   instance key replaced by a scoped token where the runtime is not trusted with it.
15//! - [`srv_endpoint`](RuntimeAdapter::srv_endpoint): how the process reaches this srv.
16//! - [`map_mount`](RuntimeAdapter::map_mount): where a folder the host knows by role appears.
17//! - [`tool_path`](RuntimeAdapter::tool_path): how a helper program is named in config files.
18//! - [`materialize`](RuntimeAdapter::materialize): what a turn does before it runs (a container is
19//!   started and the CLI installed in it).
20//! - [`launch`](RuntimeAdapter::launch): start one turn.
21//!
22//! [`RuntimeKind`] is the one place `agentMode` / `agent_type` is read as "host or container".
23
24use std::collections::HashMap;
25use std::sync::Arc;
26
27use super::blockcontroller::subprocess::{StartupStep, SubprocessController, SubprocessSpawnConfig};
28use super::container::{ContainerManager, CONTAINER_CLAUDE_DIR, CONTAINER_WORKSPACE_DIR};
29use super::providers::ControllerType;
30
31/// The value of `agentMode` (a pane) and `agent_type` (a definition) that names a container agent.
32const CONTAINER: &str = "container";
33
34/// Where an agent runs. On the wire it is `"host"` or `"container"`.
35#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize, ts_rs::TS)]
36#[ts(export, export_to = "../../../frontend/types/rpc/")]
37#[serde(rename_all = "snake_case")]
38pub enum RuntimeKind {
39    /// A process on this machine (`"host"`, the legacy `"standalone"`, empty or unknown).
40    #[default]
41    Host,
42    /// A Docker container.
43    Container,
44}
45
46impl RuntimeKind {
47    /// The runtime of a pane's `agentMode`: `"container"` is a container, anything else is the host,
48    /// as srv has always read it.
49    pub fn of_agent_mode(agent_mode: &str) -> Self {
50        if agent_mode == CONTAINER {
51            Self::Container
52        } else {
53            Self::Host
54        }
55    }
56
57    /// The runtime a wire value names, `None` for anything but exactly `"host"` or `"container"`. For a
58    /// value that is validated (a presence record's `kind`); [`of_agent_mode`](Self::of_agent_mode) reads
59    /// the stored value, where anything else means the host.
60    pub fn parse(kind: &str) -> Option<Self> {
61        match kind {
62            "host" => Some(Self::Host),
63            CONTAINER => Some(Self::Container),
64            _ => None,
65        }
66    }
67
68    /// The runtime of a definition's `agent_type`. The same values as `agentMode`.
69    pub fn of_agent_type(agent_type: &str) -> Self {
70        Self::of_agent_mode(agent_type)
71    }
72
73    /// The runtime of a pane, from its block meta.
74    pub fn of_block_meta(meta: &super::obj::MetaMapType) -> Self {
75        Self::of_agent_mode(&super::obj::meta_get_string(meta, "agentMode", "host"))
76    }
77
78    pub fn is_container(self) -> bool {
79        self == Self::Container
80    }
81
82    /// The adapter for the parts that need no per-agent state. A container adapter made here cannot
83    /// [`launch`](RuntimeAdapter::launch); build one with [`ContainerAdapter::with_launch`] for that.
84    pub fn adapter(self) -> Box<dyn RuntimeAdapter> {
85        match self {
86            Self::Host => Box::new(NativeAdapter),
87            Self::Container => Box::new(ContainerAdapter::default()),
88        }
89    }
90}
91
92/// A folder the host knows by what it is for, not by its path.
93#[derive(Debug, Clone, Copy, PartialEq, Eq)]
94pub enum MountRole {
95    /// The agent's working directory.
96    Workspace,
97    /// The folder the CLI keeps the agent's Personal Memory in.
98    PersonalMemory,
99    /// The CLI's own config folder (`CLAUDE_CONFIG_DIR`).
100    CliHome,
101    /// The agent's MCP config when it lives outside its working directory (#3680). A container
102    /// gets its folder as a read-only bind and reads the file inside it; the host uses the path
103    /// as it is.
104    McpConfig,
105}
106
107/// A helper program AgentMux puts beside the agent's CLI.
108#[derive(Debug, Clone, Copy, PartialEq, Eq)]
109pub enum ToolId {
110    /// The MCP server (`.mcp.json`'s `agentmux` entry).
111    Mcp,
112    /// The Bash wrapper the hooks name.
113    Bashwrap,
114}
115
116pub trait RuntimeAdapter: Send + Sync {
117    fn kind(&self) -> RuntimeKind;
118
119    /// The env a turn's process is given, from the env the block resolved. `block_id` names whose
120    /// scoped token a runtime that uses one hands out.
121    fn credentials(&self, block_id: &str, env: &HashMap<String, String>) -> Vec<(String, String)>;
122
123    /// `AGENTMUX_LOCAL_URL` as the process sees it, given how this srv sees itself.
124    fn srv_endpoint(&self, local_url: &str) -> String;
125
126    /// Where `host_path`, the folder of `role`, appears in the runtime.
127    fn map_mount(&self, role: MountRole, host_path: &str) -> String;
128
129    /// How `tool` is named in the config files written for the agent.
130    fn tool_path(&self, tool: ToolId) -> String;
131
132    /// What a turn does before it runs. Call before [`launch`](Self::launch).
133    fn materialize(&self, ctrl: &SubprocessController);
134
135    /// Start one turn. `config` is in the host's shape (`cli_command`, `cli_args`, `working_dir`);
136    /// a runtime that runs the CLI elsewhere turns that into its own.
137    fn launch(&self, ctrl: &SubprocessController, config: SubprocessSpawnConfig) -> Result<(), String>;
138
139    /// Whether the `.mcp.json` written for the agent carries its signing keys. A runtime that mounts
140    /// the file where other code reads it does not.
141    fn carries_signing_keys(&self) -> bool;
142
143    /// Whether an attachment's host path means anything to the agent.
144    fn accepts_attachments(&self) -> bool;
145
146    /// Whether a long-lived (persistent) controller can host the agent.
147    fn accepts_persistent_controller(&self) -> bool;
148
149    /// Whether a provider run by `controller` can run here.
150    fn can_host(&self, controller: ControllerType) -> bool;
151
152    /// The controller type a new pane gets, given the provider's own.
153    fn controller_type_for_open(&self, provider_default: &'static str) -> &'static str;
154}
155
156/// An agent that is a process on this machine.
157#[derive(Debug, Clone, Copy, Default)]
158pub struct NativeAdapter;
159
160impl RuntimeAdapter for NativeAdapter {
161    fn kind(&self) -> RuntimeKind {
162        RuntimeKind::Host
163    }
164
165    fn credentials(&self, _block_id: &str, env: &HashMap<String, String>) -> Vec<(String, String)> {
166        env.iter().map(|(k, v)| (k.clone(), v.clone())).collect()
167    }
168
169    fn srv_endpoint(&self, local_url: &str) -> String {
170        local_url.to_string()
171    }
172
173    fn map_mount(&self, _role: MountRole, host_path: &str) -> String {
174        host_path.to_string()
175    }
176
177    fn tool_path(&self, tool: ToolId) -> String {
178        bare_tool_name(tool).to_string()
179    }
180
181    fn materialize(&self, ctrl: &SubprocessController) {
182        ctrl.remember_adapter(Arc::new(*self));
183    }
184
185    fn launch(&self, ctrl: &SubprocessController, config: SubprocessSpawnConfig) -> Result<(), String> {
186        ctrl.spawn_turn(config)
187    }
188
189    fn carries_signing_keys(&self) -> bool {
190        true
191    }
192
193    fn accepts_attachments(&self) -> bool {
194        true
195    }
196
197    fn accepts_persistent_controller(&self) -> bool {
198        true
199    }
200
201    fn can_host(&self, _controller: ControllerType) -> bool {
202        true
203    }
204
205    fn controller_type_for_open(&self, provider_default: &'static str) -> &'static str {
206        provider_default
207    }
208}
209
210/// Both runtimes name a helper by its bare name today: the image has them on its `PATH`, and a host
211/// pane finds them on its own.
212fn bare_tool_name(tool: ToolId) -> &'static str {
213    match tool {
214        ToolId::Mcp => "agentmux-mcp",
215        ToolId::Bashwrap => "agentmux-bashwrap",
216    }
217}
218
219/// What a container turn needs that the pane's meta and the services give it.
220#[derive(Clone)]
221pub struct ContainerLaunch {
222    pub cm: ContainerManager,
223    pub container_name: String,
224    /// The provider CLI as the image names it (`claude`), not the host's resolved path.
225    pub container_command: String,
226    pub provider_id: String,
227    /// Starts the container and installs the CLI in it, at the start of the turn's own task.
228    pub startup: StartupStep,
229}
230
231/// An agent in a Docker container, one `docker exec` per turn.
232#[derive(Clone, Default)]
233pub struct ContainerAdapter {
234    launch: Option<ContainerLaunch>,
235}
236
237impl ContainerAdapter {
238    pub fn with_launch(launch: ContainerLaunch) -> Self {
239        Self { launch: Some(launch) }
240    }
241}
242
243impl RuntimeAdapter for ContainerAdapter {
244    fn kind(&self) -> RuntimeKind {
245        RuntimeKind::Container
246    }
247
248    fn credentials(&self, block_id: &str, env: &HashMap<String, String>) -> Vec<(String, String)> {
249        super::container::credential::container_exec_env(block_id, env)
250    }
251
252    /// A container can't reach the loopback address srv sees.
253    fn srv_endpoint(&self, local_url: &str) -> String {
254        super::container::rewrite_local_url_for_container(local_url)
255    }
256
257    fn map_mount(&self, role: MountRole, host_path: &str) -> String {
258        let _ = host_path;
259        match role {
260            MountRole::Workspace => CONTAINER_WORKSPACE_DIR.to_string(),
261            MountRole::PersonalMemory => super::container::container_memory_dir(),
262            MountRole::CliHome => CONTAINER_CLAUDE_DIR.to_string(),
263            MountRole::McpConfig => {
264                let name = std::path::Path::new(host_path)
265                    .file_name()
266                    .and_then(|n| n.to_str())
267                    .unwrap_or("mcp.json");
268                format!("{}/{name}", super::container::CONTAINER_MCP_CONFIG_DIR)
269            }
270        }
271    }
272
273    fn tool_path(&self, tool: ToolId) -> String {
274        bare_tool_name(tool).to_string()
275    }
276
277    fn materialize(&self, ctrl: &SubprocessController) {
278        ctrl.remember_adapter(Arc::new(self.clone()));
279        if let Some(launch) = &self.launch {
280            ctrl.set_container_startup(launch.startup.clone());
281            // A container worker's brief can beat the pane's Session Context block: the block goes first.
282            ctrl.expect_session_context();
283        }
284    }
285
286    fn launch(&self, ctrl: &SubprocessController, mut config: SubprocessSpawnConfig) -> Result<(), String> {
287        let launch = self.launch.as_ref().ok_or("this container adapter was made without a container to launch in")?;
288        // The container runs the image's own CLI with its own working directory: the host's resolved
289        // command and path mean nothing there.
290        let mut base_cmd = vec![launch.container_command.clone()];
291        base_cmd.extend(super::container::argv::container_argv(std::mem::take(&mut config.cli_args), &launch.provider_id));
292        config.cli_command = String::new();
293        config.working_dir = String::new();
294        ctrl.spawn_container_turn(launch.cm.clone(), launch.container_name.clone(), base_cmd, config)
295    }
296
297    fn carries_signing_keys(&self) -> bool {
298        false
299    }
300
301    fn accepts_attachments(&self) -> bool {
302        false
303    }
304
305    /// A container turn is one `docker exec`; a long-lived stdin has nothing to attach to.
306    fn accepts_persistent_controller(&self) -> bool {
307        false
308    }
309
310    /// A terminal or an MSP session runs on the host.
311    fn can_host(&self, controller: ControllerType) -> bool {
312        !matches!(controller, ControllerType::Terminal | ControllerType::Msp)
313    }
314
315    /// Per-turn `docker exec` needs the subprocess controller, whatever the provider defaults to (Claude's
316    /// is persistent, which would skip the container exec path).
317    fn controller_type_for_open(&self, _provider_default: &'static str) -> &'static str {
318        "subprocess"
319    }
320}
321
322#[cfg(test)]
323mod tests {
324    use super::*;
325
326    fn env(pairs: &[(&str, &str)]) -> HashMap<String, String> {
327        pairs.iter().map(|(k, v)| (k.to_string(), v.to_string())).collect()
328    }
329
330    fn get(out: &[(String, String)], key: &str) -> Option<String> {
331        out.iter().find(|(k, _)| k == key).map(|(_, v)| v.clone())
332    }
333
334    #[test]
335    fn a_wire_kind_is_exactly_host_or_container() {
336        assert_eq!(RuntimeKind::parse("host"), Some(RuntimeKind::Host));
337        assert_eq!(RuntimeKind::parse("container"), Some(RuntimeKind::Container));
338        for other in ["", "standalone", "Container", "docker", " host"] {
339            assert_eq!(RuntimeKind::parse(other), None, "{other:?}");
340        }
341    }
342
343    #[test]
344    fn only_container_names_a_container() {
345        assert_eq!(RuntimeKind::of_agent_mode("container"), RuntimeKind::Container);
346        assert_eq!(RuntimeKind::of_agent_type("container"), RuntimeKind::Container);
347        for other in ["host", "standalone", "", "Container", "docker"] {
348            assert_eq!(RuntimeKind::of_agent_mode(other), RuntimeKind::Host, "{other:?}");
349        }
350        assert!(RuntimeKind::Container.adapter().kind().is_container());
351        assert!(!RuntimeKind::Host.adapter().kind().is_container());
352    }
353
354    /// The adapter answers what `container_exec_env` answered, so the live tests that go through
355    /// the env see no change.
356    #[test]
357    fn the_container_adapters_credentials_are_the_exec_env() {
358        let vars = env(&[("AGENTMUX_AUTH_KEY", "instance-key"), ("AGENTMUX_AGENT_TOKEN", "agent-tok"), ("FOO", "bar")]);
359        let adapter = RuntimeKind::Container.adapter();
360        let mut got = adapter.credentials("ra-block-a", &vars);
361        let mut want = super::super::container::credential::container_exec_env("ra-block-a", &vars);
362        got.sort();
363        want.sort();
364        assert_eq!(got, want);
365        let token = get(&got, "AGENTMUX_AUTH_KEY").unwrap();
366        assert!(token.starts_with(super::super::container::credential::TOKEN_PREFIX), "the instance key never enters a container");
367        assert_eq!(get(&got, "AGENTMUX_IN_CONTAINER").as_deref(), Some("1"));
368        assert_eq!(get(&got, "FOO").as_deref(), Some("bar"));
369    }
370
371    #[test]
372    fn the_native_adapter_hands_the_env_over_unchanged() {
373        let vars = env(&[("AGENTMUX_AUTH_KEY", "instance-key"), ("CLAUDE_CONFIG_DIR", "/home/u/.claude-a")]);
374        let mut got = RuntimeKind::Host.adapter().credentials("ra-block-b", &vars);
375        got.sort();
376        assert_eq!(
377            got,
378            vec![
379                ("AGENTMUX_AUTH_KEY".to_string(), "instance-key".to_string()),
380                ("CLAUDE_CONFIG_DIR".to_string(), "/home/u/.claude-a".to_string()),
381            ]
382        );
383    }
384
385    #[test]
386    fn a_container_reaches_srv_by_the_docker_host_name_and_a_process_by_loopback() {
387        let url = "http://127.0.0.1:51234";
388        assert_eq!(RuntimeKind::Host.adapter().srv_endpoint(url), url);
389        assert_eq!(RuntimeKind::Container.adapter().srv_endpoint(url), "http://host.docker.internal:51234");
390        // A name that is not loopback passes through.
391        assert_eq!(RuntimeKind::Container.adapter().srv_endpoint("http://srv.example:9"), "http://srv.example:9");
392    }
393
394    #[test]
395    fn mounts_keep_their_host_path_natively_and_appear_at_the_images_paths_in_a_container() {
396        let native = RuntimeKind::Host.adapter();
397        let container = RuntimeKind::Container.adapter();
398        for role in [MountRole::Workspace, MountRole::PersonalMemory, MountRole::CliHome] {
399            assert_eq!(native.map_mount(role, "/home/u/work"), "/home/u/work");
400        }
401        assert_eq!(container.map_mount(MountRole::Workspace, "/home/u/work"), "/workspace");
402        assert_eq!(container.map_mount(MountRole::CliHome, "/home/u/.claude-a"), "/home/agent/.claude");
403        assert_eq!(
404            container.map_mount(MountRole::PersonalMemory, "/home/u/.claude-a/projects/x/memory"),
405            "/home/agent/.claude/projects/-workspace/memory"
406        );
407        let config = "/home/u/.agentmux/mcp/abc/mcp.json";
408        assert_eq!(native.map_mount(MountRole::McpConfig, config), config);
409        assert_eq!(
410            container.map_mount(MountRole::McpConfig, config),
411            "/home/agent/.agentmux/mcp/mcp.json",
412            "the folder is mounted; the file keeps its name inside it"
413        );
414    }
415
416    #[test]
417    fn both_runtimes_name_the_helpers_by_their_bare_names_for_now() {
418        for kind in [RuntimeKind::Host, RuntimeKind::Container] {
419            let adapter = kind.adapter();
420            assert_eq!(adapter.tool_path(ToolId::Mcp), "agentmux-mcp");
421            assert_eq!(adapter.tool_path(ToolId::Bashwrap), "agentmux-bashwrap");
422        }
423    }
424
425    /// What the scattered `if container` branches decided, in one table.
426    #[test]
427    fn the_capabilities_the_branches_used_to_decide() {
428        let (native, container) = (RuntimeKind::Host.adapter(), RuntimeKind::Container.adapter());
429        assert!(native.carries_signing_keys() && !container.carries_signing_keys());
430        assert!(native.accepts_attachments() && !container.accepts_attachments());
431        assert!(native.accepts_persistent_controller() && !container.accepts_persistent_controller());
432        assert!(native.can_host(ControllerType::Terminal) && native.can_host(ControllerType::Msp));
433        assert!(!container.can_host(ControllerType::Terminal) && !container.can_host(ControllerType::Msp));
434        assert!(container.can_host(ControllerType::Persistent));
435        assert_eq!(native.controller_type_for_open("persistent"), "persistent");
436        assert_eq!(container.controller_type_for_open("persistent"), "subprocess");
437    }
438
439    #[test]
440    fn a_container_adapter_without_a_container_refuses_to_launch() {
441        let ctrl = SubprocessController::new("tab".into(), "ra-block-c".into(), None, None, None, None, None, "boot".into());
442        let err = RuntimeKind::Container.adapter().launch(&ctrl, SubprocessSpawnConfig::default()).unwrap_err();
443        assert!(err.contains("without a container"), "{err}");
444    }
445
446    /// "Is this a container agent?" is answered by [`RuntimeKind`]. A new `== "container"` outside the
447    /// files below is a branch the adapter should own; move it behind a method here instead.
448    #[test]
449    fn nothing_but_the_adapter_compares_a_mode_to_container() {
450        // Files that still read the string, and why.
451        let allowed = [
452            "backend/runtime_adapter.rs",                           // the one derivation
453            "migrations/m0043_rotate_container_agent_keys.rs",      // a frozen migration reads the stored value
454        ];
455        fn walk(dir: &std::path::Path, out: &mut Vec<std::path::PathBuf>) {
456            for entry in std::fs::read_dir(dir).unwrap().flatten() {
457                let path = entry.path();
458                if path.is_dir() {
459                    walk(&path, out);
460                } else if path.extension().is_some_and(|e| e == "rs") {
461                    out.push(path);
462                }
463            }
464        }
465        let mut pairs = Vec::new();
466        for src in crate::test_support::server_src_roots() {
467            let mut files = Vec::new();
468            walk(&src, &mut files);
469            pairs.extend(files.into_iter().map(|file| (src.clone(), file)));
470        }
471        let mut offenders = Vec::new();
472        for (src, file) in pairs {
473            let rel = file.strip_prefix(&src).unwrap().to_string_lossy().replace('\\', "/");
474            if allowed.contains(&rel.as_str()) || rel.ends_with("tests.rs") || rel.contains("/tests/") {
475                continue;
476            }
477            let text = std::fs::read_to_string(&file).unwrap();
478            for (n, line) in text.lines().enumerate() {
479                let code = line.split("//").next().unwrap_or("");
480                if code.contains("== \"container\"") || code.contains("!= \"container\"") {
481                    offenders.push(format!("{rel}:{}", n + 1));
482                }
483            }
484        }
485        assert!(offenders.is_empty(), "compare through RuntimeKind, not the string: {offenders:?}");
486    }
487}