Skip to main content

agentmux_srv_core/backend/
dev_relay.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! A relay into the agents network, for a dev server srv cannot reach by the container's IP.
5//!
6//! The dev proxy (`dev_proxy`) forwards to the address a container agent's dev server listens on.
7//! On Linux that is the container's address on the agents network. On Docker Desktop (Windows and
8//! macOS) the daemon runs in a VM and container addresses are not routable from the host, so the
9//! same connection times out. There, one small container per host sits on the agents network with a
10//! single port published on `127.0.0.1`; srv opens a connection to that port, names the container
11//! and port it wants, and the relay joins the two. One relay serves every agent and every project,
12//! it needs nothing published per dev server, and a WebSocket is just another connection.
13//!
14//! The relay runs the agent image's own `node` (nothing to pull), and takes a request line
15//! `<token> <container> <port>`, where the token is generated here and only the loopback caller
16//! that knows it is served. It only reaches containers named `agentmux-*`. srv adopts a running relay
17//! after a restart (the token is in its environment) and replaces one that is gone.
18
19use std::collections::HashMap;
20use std::net::SocketAddr;
21use std::sync::OnceLock;
22use std::time::Duration;
23
24use bollard::container::{Config, CreateContainerOptions, StartContainerOptions};
25use bollard::models::{HostConfig, PortBinding, RestartPolicy, RestartPolicyNameEnum};
26use tokio::io::{AsyncReadExt, AsyncWriteExt};
27use tokio::net::TcpStream;
28
29use crate::backend::container::{ContainerManager, AGENTMUX_DOCKER_NETWORK};
30
31/// The relay container's name. Not under `agentmux-`: that is the namespace of agent containers
32/// (`container_name_for_slug`), and an agent called `dev-relay` must not be the relay's neighbour.
33pub const RELAY_NAME: &str = "amx-dev-relay";
34/// Marks the relay container, so nothing else is taken for it.
35const LABEL: &str = "ai.agentmux.dev-relay";
36/// The port the relay listens on inside its container.
37const RELAY_PORT: u16 = 9100;
38/// How long a connection through the relay may take to be set up.
39const SETUP: Duration = Duration::from_secs(8);
40
41/// What the relay does, as one `node -e` program. A request line, then bytes both ways.
42const PROGRAM: &str = r#"const net=require('net');const T=process.env.AMX_RELAY_TOKEN;
43net.createServer(c=>{let b=Buffer.alloc(0);c.on('error',()=>{});
44const on=d=>{b=Buffer.concat([b,d]);const i=b.indexOf(10);if(i<0){if(b.length>256)c.destroy();return}
45c.off('data',on);c.pause();const [t,h,p]=b.subarray(0,i).toString().trim().split(' ');
46if(!T||t!==T||!/^agentmux-[A-Za-z0-9_.-]+$/.test(h)||!(+p>0&&+p<65536)){c.end('ERR refused\n');return}
47const s=net.connect(+p,h);s.on('error',e=>{c.end('ERR '+(e.code||'failed')+'\n')});
48s.on('connect',()=>{c.write('OK\n');const r=b.subarray(i+1);if(r.length)s.write(r);c.pipe(s);s.pipe(c);c.resume()});
49s.on('close',()=>c.destroy());c.on('close',()=>s.destroy())};
50c.on('data',on)}).listen(9100,'0.0.0.0')"#;
51
52/// Where the relay can be reached and the token that opens it.
53#[derive(Debug, Clone, PartialEq, Eq)]
54pub struct RelayEndpoint {
55    pub addr: SocketAddr,
56    pub token: String,
57}
58
59/// Whether this Docker keeps container addresses to itself: Docker Desktop, and any macOS or Windows
60/// host. `AGENTMUX_DEV_PROXY_RELAY=1` (or `0`) overrides it.
61pub async fn needed(manager: &ContainerManager) -> bool {
62    if let Ok(v) = std::env::var("AGENTMUX_DEV_PROXY_RELAY") {
63        return v == "1";
64    }
65    if cfg!(any(windows, target_os = "macos")) {
66        return true;
67    }
68    manager
69        .docker()
70        .info()
71        .await
72        .ok()
73        .and_then(|i| i.operating_system)
74        .is_some_and(|os| os.contains("Docker Desktop"))
75}
76
77fn token() -> String {
78    format!("{}{}", uuid::Uuid::new_v4().simple(), uuid::Uuid::new_v4().simple())
79}
80
81fn published_port(details: &bollard::models::ContainerInspectResponse) -> Option<u16> {
82    let ports = details.network_settings.as_ref()?.ports.as_ref()?;
83    let binding = ports.get(&format!("{RELAY_PORT}/tcp"))?.as_ref()?.first()?;
84    binding.host_port.as_deref()?.parse().ok()
85}
86
87fn env_token(details: &bollard::models::ContainerInspectResponse) -> Option<String> {
88    let env = details.config.as_ref()?.env.as_ref()?;
89    env.iter().find_map(|e| e.strip_prefix("AMX_RELAY_TOKEN=").map(str::to_string))
90}
91
92/// The running relay, created if there is none. `image` is an image already on this machine (the
93/// one an agent container runs from).
94pub async fn ensure(manager: &ContainerManager, image: &str) -> Result<RelayEndpoint, String> {
95    ensure_named(manager, image, RELAY_NAME).await
96}
97
98async fn ensure_named(manager: &ContainerManager, image: &str, name: &str) -> Result<RelayEndpoint, String> {
99    static LOCK: OnceLock<tokio::sync::Mutex<()>> = OnceLock::new();
100    let _one_at_a_time = LOCK.get_or_init(Default::default).lock().await;
101    let docker = manager.docker();
102
103    if let Ok(details) = docker.inspect_container(name, None).await {
104        let ours = details.config.as_ref().and_then(|c| c.labels.as_ref()).is_some_and(|l| l.contains_key(LABEL));
105        if ours {
106            let running = details.state.as_ref().and_then(|s| s.running).unwrap_or(false);
107            if !running {
108                let _ = docker.start_container(name, None::<StartContainerOptions<String>>).await;
109            }
110            let details = docker.inspect_container(name, None).await.map_err(|e| e.to_string())?;
111            if let (Some(port), Some(token)) = (published_port(&details), env_token(&details)) {
112                if details.state.as_ref().and_then(|s| s.running).unwrap_or(false) {
113                    let addr = SocketAddr::from(([127, 0, 0, 1], port));
114                    wait_until_listening(addr).await?;
115                    crate::backend::transcript::withhold_sources::relay_token(&token);
116                    return Ok(RelayEndpoint { addr, token });
117                }
118            }
119        }
120        if !ours {
121            return Err(format!("a container called {name} exists and is not the dev relay; not touching it"));
122        }
123        // Ours but broken: replace it.
124        let _ = docker
125            .remove_container(name, Some(bollard::container::RemoveContainerOptions { force: true, ..Default::default() }))
126            .await;
127    }
128
129    let token = token();
130    crate::backend::transcript::withhold_sources::relay_token(&token);
131    let mut ports = HashMap::new();
132    ports.insert(format!("{RELAY_PORT}/tcp"), Some(vec![PortBinding { host_ip: Some("127.0.0.1".into()), host_port: Some(String::new()) }]));
133    let config = Config {
134        image: Some(image.to_string()),
135        entrypoint: Some(vec!["node".into(), "-e".into(), PROGRAM.into()]),
136        cmd: Some(vec![]),
137        env: Some(vec![format!("AMX_RELAY_TOKEN={token}")]),
138        labels: Some(HashMap::from([(LABEL.to_string(), "1".to_string())])),
139        exposed_ports: Some(HashMap::from([(format!("{RELAY_PORT}/tcp"), HashMap::new())])),
140        host_config: Some(HostConfig {
141            network_mode: Some(AGENTMUX_DOCKER_NETWORK.to_string()),
142            port_bindings: Some(ports),
143            init: Some(true),
144            restart_policy: Some(RestartPolicy { name: Some(RestartPolicyNameEnum::UNLESS_STOPPED), maximum_retry_count: None }),
145            ..Default::default()
146        }),
147        ..Default::default()
148    };
149    docker
150        .create_container(Some(CreateContainerOptions { name, platform: None }), config)
151        .await
152        .map_err(|e| format!("couldn't create the dev relay: {e}"))?;
153    docker
154        .start_container(name, None::<StartContainerOptions<String>>)
155        .await
156        .map_err(|e| format!("couldn't start the dev relay: {e}"))?;
157    let details = docker.inspect_container(name, None).await.map_err(|e| e.to_string())?;
158    let port = published_port(&details).ok_or("the dev relay has no published port")?;
159    let addr = SocketAddr::from(([127, 0, 0, 1], port));
160    wait_until_listening(addr).await?;
161    Ok(RelayEndpoint { addr, token })
162}
163
164/// Waits until the relay answers: Docker publishes the port the moment the container starts, before
165/// node is listening in it, and a connection in that gap is reset.
166async fn wait_until_listening(addr: SocketAddr) -> Result<(), String> {
167    for _ in 0..50 {
168        if let Ok(mut s) = TcpStream::connect(addr).await {
169            // A request the relay refuses by design; any answer at all means it is up.
170            if s.write_all(b"ready\n").await.is_ok() {
171                let mut buf = [0u8; 16];
172                if matches!(s.read(&mut buf).await, Ok(n) if n > 0) {
173                    return Ok(());
174                }
175            }
176        }
177        tokio::time::sleep(Duration::from_millis(200)).await;
178    }
179    Err("the dev relay did not start listening".to_string())
180}
181
182/// A connection to `container:port` through the relay at `via`.
183pub async fn connect(via: &RelayEndpoint, container: &str, port: u16) -> std::io::Result<TcpStream> {
184    let attempt = async {
185        let mut stream = TcpStream::connect(via.addr).await?;
186        stream.write_all(format!("{} {container} {port}\n", via.token).as_bytes()).await?;
187        // The answer is one short line; read it a byte at a time so nothing of the stream is consumed.
188        let mut line = Vec::with_capacity(32);
189        loop {
190            let mut b = [0u8; 1];
191            if stream.read(&mut b).await? == 0 {
192                return Err(std::io::Error::new(std::io::ErrorKind::UnexpectedEof, "the dev relay closed the connection"));
193            }
194            if b[0] == b'\n' {
195                break;
196            }
197            line.push(b[0]);
198            if line.len() > 64 {
199                return Err(std::io::Error::other("the dev relay answered with something else"));
200            }
201        }
202        match line.as_slice() {
203            b"OK" => Ok(stream),
204            other => Err(std::io::Error::new(std::io::ErrorKind::ConnectionRefused, String::from_utf8_lossy(other).into_owned())),
205        }
206    };
207    tokio::time::timeout(SETUP, attempt).await.unwrap_or_else(|_| Err(std::io::ErrorKind::TimedOut.into()))
208}
209
210#[cfg(test)]
211mod tests {
212    use super::*;
213    use tokio::net::TcpListener;
214
215    /// A stand-in relay speaking the same line protocol: answers `OK` to the right token and then echoes.
216    async fn fake_relay(token: &'static str) -> RelayEndpoint {
217        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
218        let addr = listener.local_addr().unwrap();
219        tokio::spawn(async move {
220            loop {
221                let Ok((mut s, _)) = listener.accept().await else { return };
222                tokio::spawn(async move {
223                    let mut line = Vec::new();
224                    loop {
225                        let mut b = [0u8; 1];
226                        if s.read(&mut b).await.unwrap_or(0) == 0 {
227                            return;
228                        }
229                        if b[0] == b'\n' {
230                            break;
231                        }
232                        line.push(b[0]);
233                    }
234                    let line = String::from_utf8_lossy(&line).into_owned();
235                    if line.split(' ').next() != Some(token) {
236                        let _ = s.write_all(b"ERR refused\n").await;
237                        return;
238                    }
239                    let _ = s.write_all(b"OK\n").await;
240                    let mut buf = [0u8; 256];
241                    while let Ok(n) = s.read(&mut buf).await {
242                        if n == 0 || s.write_all(&buf[..n]).await.is_err() {
243                            return;
244                        }
245                    }
246                });
247            }
248        });
249        RelayEndpoint { addr, token: token.to_string() }
250    }
251
252    #[tokio::test]
253    async fn a_connection_through_the_relay_carries_bytes_after_the_ok() {
254        let relay = fake_relay("secret").await;
255        let mut s = connect(&relay, "agentmux-korp", 7000).await.expect("connected");
256        s.write_all(b"ping").await.unwrap();
257        let mut buf = [0u8; 4];
258        s.read_exact(&mut buf).await.unwrap();
259        assert_eq!(&buf, b"ping");
260    }
261
262    #[tokio::test]
263    async fn the_wrong_token_is_refused_with_the_relays_reason() {
264        let relay = RelayEndpoint { token: "wrong".into(), ..fake_relay("secret").await };
265        let err = connect(&relay, "agentmux-korp", 7000).await.expect_err("refused");
266        assert_eq!(err.kind(), std::io::ErrorKind::ConnectionRefused);
267        assert!(err.to_string().contains("refused"), "{err}");
268    }
269
270    #[tokio::test]
271    async fn a_relay_that_is_not_there_is_an_error_not_a_hang() {
272        let gone = TcpListener::bind("127.0.0.1:0").await.unwrap().local_addr().unwrap();
273        let relay = RelayEndpoint { addr: gone, token: "t".into() };
274        assert!(connect(&relay, "agentmux-korp", 7000).await.is_err());
275    }
276
277    #[test]
278    fn the_relay_program_only_reaches_agent_containers_and_needs_the_token() {
279        assert!(PROGRAM.contains("agentmux-[A-Za-z0-9_.-]+"));
280        assert!(PROGRAM.contains("t!==T"));
281        assert!(PROGRAM.contains(&RELAY_PORT.to_string()));
282    }
283
284    /// Against a real daemon: the relay is created, reached, adopted again and replaced.
285    ///   cargo test -p agentmux-srv-core --lib -- --ignored --nocapture itest_dev_relay
286    #[tokio::test]
287    #[ignore]
288    async fn itest_dev_relay_reaches_a_container_by_name_and_is_adopted() {
289        use bollard::network::CreateNetworkOptions;
290        use bollard::container::RemoveContainerOptions;
291        let cm = ContainerManager::connect().expect("connect to docker (set DOCKER_HOST)");
292        cm.check_available().await.expect("docker daemon must be reachable");
293        let docker = cm.docker();
294        let image = "ghcr.io/agentmuxai/agent-base:0.60.3";
295        let relay_name = "amx-itest-dev-relay";
296        let target = "agentmux-itest-relay-target";
297        async fn rm(docker: &bollard::Docker, name: &str) {
298            let _ = docker.remove_container(name, Some(RemoveContainerOptions { force: true, ..Default::default() })).await;
299        }
300        rm(docker, relay_name).await;
301        rm(docker, target).await;
302        let _ = docker.create_network(CreateNetworkOptions { name: AGENTMUX_DOCKER_NETWORK, driver: "bridge", ..Default::default() }).await;
303
304        let server = "require('http').createServer((q,r)=>r.end('hello from '+q.headers.host)).listen(7000,'0.0.0.0')";
305        docker
306            .create_container(
307                Some(CreateContainerOptions { name: target, platform: None }),
308                Config {
309                    image: Some(image.to_string()),
310                    cmd: Some(vec!["node".into(), "-e".into(), server.into()]),
311                    host_config: Some(HostConfig { network_mode: Some(AGENTMUX_DOCKER_NETWORK.to_string()), ..Default::default() }),
312                    ..Default::default()
313                },
314            )
315            .await
316            .expect("create target");
317        docker.start_container(target, None::<StartContainerOptions<String>>).await.expect("start target");
318        tokio::time::sleep(Duration::from_secs(2)).await;
319
320        // A container that is not the relay, under the relay's name, is left alone and reported.
321        let foreign = "amx-itest-foreign";
322        rm(docker, foreign).await;
323        docker
324            .create_container(Some(CreateContainerOptions { name: foreign, platform: None }), Config { image: Some(image.to_string()), cmd: Some(vec!["sleep".into(), "60".into()]), ..Default::default() })
325            .await
326            .expect("create foreign");
327        let refused = ensure_named(&cm, image, foreign).await.expect_err("not the relay's to replace");
328        let still_there = docker.inspect_container(foreign, None).await.is_ok();
329        rm(docker, foreign).await;
330        assert!(refused.contains("not touching it") && still_there, "{refused}");
331
332        let first = ensure_named(&cm, image, relay_name).await.expect("relay");
333        let again = ensure_named(&cm, image, relay_name).await.expect("adopted");
334        let mut s = connect(&first, target, 7000).await.expect("through the relay to the target");
335        s.write_all(b"GET / HTTP/1.1\r\nHost: localhost:7000\r\nConnection: close\r\n\r\n").await.unwrap();
336        let mut answer = String::new();
337        s.read_to_string(&mut answer).await.unwrap();
338        let refused_name = connect(&first, "not-an-agent", 7000).await.expect_err("only agent containers");
339        let refused_token = connect(&RelayEndpoint { token: "wrong".into(), ..first.clone() }, target, 7000).await.expect_err("token");
340        let no_such = connect(&first, "agentmux-nobody-here", 7000).await.expect_err("no such container");
341
342        rm(docker, relay_name).await;
343        rm(docker, target).await;
344
345        assert_eq!(first, again, "the running relay is adopted, not replaced");
346        assert!(first.addr.ip().is_loopback(), "published on loopback only: {first:?}");
347        assert!(answer.contains("200 OK") && answer.contains("hello from localhost:7000"), "{answer}");
348        assert!(refused_name.to_string().contains("refused"), "{refused_name}");
349        assert!(refused_token.to_string().contains("refused"), "{refused_token}");
350        assert!(no_such.to_string().to_uppercase().contains("ERR"), "{no_such}");
351    }
352}