Skip to main content

agentmux_srv_core/backend/remote/
wsl.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! WSL terminals (P1 of SPEC_REMOTE_TERMINALS_AND_DURABLE_SESSIONS_2026_10_02.md).
5//!
6//! A WSL pane is `wsl.exe -d <distro>` in a ConPTY: no network, no helper, no
7//! durability (the distro's shell lives as long as its VM, spec §3.3 and §5.5).
8
9/// What `wsl.exe` needs to start a pane's process in a distro.
10#[derive(Debug, Clone, PartialEq, Eq)]
11pub struct WslLaunch {
12    /// Arguments for `wsl.exe`.
13    pub args: Vec<String>,
14}
15
16/// Environment variables a WSL shell should see from the Windows side. WSL does
17/// not pass the Windows environment through; `WSLENV` lists what crosses. Never
18/// the local URL or auth key: those name this machine's srv, which a shell in
19/// the distro has no business calling without the user knowing.
20pub const FORWARDED_ENV: &[&str] = &[
21    "TERM",
22    "COLORTERM",
23    "TERM_PROGRAM",
24    "AGENTMUX_BLOCKID",
25    "AGENTMUX_TABID",
26    "AGENTMUX_VERSION",
27    "AGENTMUX_BUILD",
28    "AGENTMUX_INSTANCE_CHANNEL",
29];
30
31/// The `wsl.exe` arguments for a pane: an interactive login shell, or the
32/// pane's command run by the distro's `sh`. `cwd` is a path inside the distro;
33/// empty means the user's home.
34pub fn launch(distro: &str, cmd: &str, cmd_args: &[String], cwd: &str) -> WslLaunch {
35    let mut args = vec!["-d".to_string(), distro.to_string(), "--cd".to_string()];
36    args.push(if cwd.trim().is_empty() {
37        "~".to_string()
38    } else {
39        cwd.to_string()
40    });
41    if !cmd.is_empty() {
42        // `--exec`, not `--`: after `--` wsl.exe hands the rest to the user's
43        // login shell, which expands `$VAR`, `$(...)` and backticks once more
44        // before `sh -c` sees them (`echo '$HOME'` printed the home dir), and a
45        // non-POSIX login shell (fish) misreads the quoting. `--exec` runs the
46        // argv as given.
47        args.push("--exec".to_string());
48        if cmd_args.is_empty() {
49            // A command line, as a local pane runs it through `sh -c`.
50            args.extend(["sh".to_string(), "-c".to_string(), cmd.to_string()]);
51        } else {
52            args.push(cmd.to_string());
53            args.extend(cmd_args.iter().cloned());
54        }
55    }
56    WslLaunch { args }
57}
58
59/// `WSLENV` with [`FORWARDED_ENV`] added to whatever the user already set,
60/// without duplicates.
61pub fn wslenv(existing: &str) -> String {
62    // An `AGENTMUX_*` entry the user's own WSLENV already lists is dropped
63    // unless it is one of ours: the pane sets AGENTMUX_AUTH_KEY and
64    // AGENTMUX_LOCAL_URL on wsl.exe, and a listed name would carry them in.
65    let mut parts: Vec<String> = existing
66        .split(':')
67        .filter(|p| !p.is_empty())
68        .filter(|p| {
69            let name = p.split('/').next().unwrap_or_default();
70            !name.starts_with("AGENTMUX_") || FORWARDED_ENV.contains(&name)
71        })
72        .map(str::to_string)
73        .collect();
74    for name in FORWARDED_ENV {
75        if !parts.iter().any(|p| p.split('/').next() == Some(*name)) {
76            parts.push((*name).to_string());
77        }
78    }
79    parts.join(":")
80}
81
82/// The agent identity a process started for an agent carries, set by the
83/// server from the agent's definition (`spawn_env::identity`), not
84/// by its caller. Listed in `WSLENV` when present, so a command run in a
85/// distro for an agent names it as one run on Windows does.
86/// `GH_CONFIG_DIR` crosses too, path-translated, as [`wslenv_with`] adds it.
87pub const AGENT_IDENTITY_ENV: [&str; 7] = [
88    "AGENTMUX_AGENT_ID",
89    "AGENTMUX_AGENT_SLUG",
90    "MUXBUS_AGENT_ID",
91    "GIT_AUTHOR_NAME",
92    "GIT_AUTHOR_EMAIL",
93    "GIT_COMMITTER_NAME",
94    "GIT_COMMITTER_EMAIL",
95];
96
97/// `WSLENV` for a process in a distro: the terminal variables, the names its
98/// caller set (an agent `Shell` call's `env`, or a pane's configured
99/// `cmd:env`), and `GH_CONFIG_DIR` translated to a distro path (`/p`), so an
100/// agent's plain-`gh` guard holds inside the distro too and `gh` there cannot
101/// act as the user. Never an `AGENTMUX_*` variable beyond the terminal ones
102/// and the agent id and slug: the auth key, the local URL and the jekt key
103/// stay on Windows.
104pub fn wslenv_with<'a>(existing: &str, caller_keys: impl IntoIterator<Item = &'a str>) -> String {
105    let guard = crate::backend::gh_guard::GH_CONFIG_DIR;
106    // Whatever flag the user's own WSLENV gives GH_CONFIG_DIR (`/u` would keep
107    // it from crossing), the guard's own `/p` entry replaces it.
108    let mut env = wslenv(existing)
109        .split(':')
110        .filter(|p| p.split('/').next() != Some(guard))
111        .collect::<Vec<_>>()
112        .join(":");
113    let mut push = |entry: String| {
114        let name = entry.split('/').next().unwrap_or_default().to_string();
115        let listed = env
116            .split(':')
117            .any(|p| p.split('/').next() == Some(name.as_str()));
118        if !listed {
119            if !env.is_empty() {
120                env.push(':');
121            }
122            env.push_str(&entry);
123        }
124    };
125    for key in caller_keys {
126        let forwardable = !key.is_empty()
127            && !key.contains([':', '/', '='])
128            && (!key.starts_with("AGENTMUX_")
129                || FORWARDED_ENV.contains(&key)
130                || key == "AGENTMUX_AGENT_ID"
131                || key == "AGENTMUX_AGENT_SLUG")
132            && key != guard
133            && key != "WSLENV";
134        if forwardable {
135            push(key.to_string());
136        }
137    }
138    push(format!("{guard}/p"));
139    env
140}
141
142/// Parse `wsl.exe --list --quiet`. It writes UTF-16LE (with or without a BOM),
143/// one distribution per line; with none installed it prints a sentence and
144/// exits non-zero, which the caller treats as "none".
145#[cfg(any(windows, test))]
146pub fn parse_list(stdout: &[u8]) -> Vec<String> {
147    // UTF-16LE when it starts with its BOM, or when every second byte is zero
148    // (ASCII names in UTF-16LE); otherwise UTF-8.
149    let body = stdout.strip_prefix(&[0xff, 0xfe]).unwrap_or(stdout);
150    let utf16 = body.len() != stdout.len()
151        || (stdout.len() >= 2
152            && stdout.len() % 2 == 0
153            && stdout.iter().skip(1).step_by(2).all(|b| *b == 0));
154    let text = if utf16 && body.len() % 2 == 0 {
155        let units: Vec<u16> = body
156            .chunks_exact(2)
157            .map(|c| u16::from_le_bytes([c[0], c[1]]))
158            .collect();
159        String::from_utf16_lossy(&units)
160    } else {
161        String::from_utf8_lossy(stdout).into_owned()
162    };
163    text.trim_start_matches('\u{feff}')
164        .lines()
165        .map(|l| l.trim_matches(|c: char| c.is_whitespace() || c == '\0'))
166        .filter(|l| !l.is_empty())
167        // Docker Desktop's own utility VMs: a root shell with no home and
168        // nothing a user works in. Listing them only invites a confusing pane.
169        .filter(|l| {
170            !l.eq_ignore_ascii_case("docker-desktop")
171                && !l.eq_ignore_ascii_case("docker-desktop-data")
172        })
173        .filter(|l| {
174            super::conn::ConnTarget::parse(&format!("{}{l}", super::conn::WSL_PREFIX)).is_ok()
175        })
176        .map(str::to_string)
177        .collect()
178}
179
180/// How long [`list_cached`] keeps an answer.
181const LIST_CACHE_TTL: std::time::Duration = std::time::Duration::from_secs(30);
182
183/// [`list`], kept for [`LIST_CACHE_TTL`]: for the places in the Files pane and the editor
184/// tree show each time they open, so a slow `wsl.exe` costs at most one wait
185/// per half minute. A connection check uses [`list`], so a distro installed a
186/// moment ago is found there.
187pub async fn list_cached() -> Vec<String> {
188    use std::sync::{Mutex, OnceLock};
189    use std::time::Instant;
190    static CACHE: OnceLock<Mutex<Option<(Instant, Vec<String>)>>> = OnceLock::new();
191    let cache = CACHE.get_or_init(|| Mutex::new(None));
192    if let Some((at, distros)) = cache.lock().unwrap().as_ref() {
193        if at.elapsed() < LIST_CACHE_TTL {
194            return distros.clone();
195        }
196    }
197    let distros = list().await;
198    *cache.lock().unwrap() = Some((Instant::now(), distros.clone()));
199    distros
200}
201
202/// The installed distributions, or none (not Windows, no WSL, or no distro).
203pub async fn list() -> Vec<String> {
204    #[cfg(windows)]
205    {
206        use agentmux_common::win32::NoWindow;
207        let mut cmd = tokio::process::Command::new("wsl.exe");
208        cmd.args(["--list", "--quiet"]).no_window();
209        match tokio::time::timeout(std::time::Duration::from_secs(5), cmd.output()).await {
210            Ok(Ok(out)) if out.status.success() => parse_list(&out.stdout),
211            _ => Vec::new(),
212        }
213    }
214    #[cfg(not(windows))]
215    {
216        Vec::new()
217    }
218}
219
220#[cfg(test)]
221mod tests {
222    use super::*;
223
224    fn utf16(s: &str, bom: bool) -> Vec<u8> {
225        let mut out = Vec::new();
226        if bom {
227            out.extend_from_slice(&0xfeffu16.to_le_bytes());
228        }
229        for u in s.encode_utf16() {
230            out.extend_from_slice(&u.to_le_bytes());
231        }
232        out
233    }
234
235    #[test]
236    fn the_list_is_read_in_utf16_with_or_without_a_bom() {
237        for bom in [false, true] {
238            let out = utf16("Ubuntu\r\ndocker-desktop\r\n\r\nUbuntu-24.04\r\n", bom);
239            assert_eq!(
240                parse_list(&out),
241                ["Ubuntu", "Ubuntu-24.04"],
242                "docker-desktop is Docker's utility VM, not the user's"
243            );
244        }
245        // Some builds print UTF-8.
246        assert_eq!(
247            parse_list(b"Debian\nkali-linux\n"),
248            ["Debian", "kali-linux"]
249        );
250        assert!(parse_list(b"").is_empty());
251    }
252
253    #[test]
254    fn a_line_that_is_not_a_distro_name_is_dropped() {
255        // The "no installed distributions" sentence, if it ever arrives on stdout.
256        let out = utf16(
257            "Windows Subsystem for Linux has no installed distributions.\r\n",
258            false,
259        );
260        assert!(parse_list(&out).is_empty());
261    }
262
263    #[test]
264    fn an_interactive_pane_is_a_login_shell_at_home_or_its_cwd() {
265        assert_eq!(
266            launch("Ubuntu", "", &[], "").args,
267            ["-d", "Ubuntu", "--cd", "~"]
268        );
269        assert_eq!(
270            launch("Ubuntu", "", &[], "/srv/app").args,
271            ["-d", "Ubuntu", "--cd", "/srv/app"]
272        );
273    }
274
275    #[test]
276    /// Run with `--exec`, so only `sh -c` parses the command line, not the
277    /// user's login shell first (#4253).
278    fn a_command_runs_in_the_distro_not_on_windows() {
279        assert_eq!(
280            launch("Ubuntu", "echo '$HOME' && echo ok", &[], "").args,
281            [
282                "-d",
283                "Ubuntu",
284                "--cd",
285                "~",
286                "--exec",
287                "sh",
288                "-c",
289                "echo '$HOME' && echo ok"
290            ]
291        );
292        assert_eq!(
293            launch("Ubuntu", "htop", &["-d".to_string(), "10".to_string()], "").args,
294            ["-d", "Ubuntu", "--cd", "~", "--exec", "htop", "-d", "10"]
295        );
296    }
297
298    #[test]
299    fn wslenv_adds_the_terminal_variables_once_and_keeps_the_users() {
300        let env = wslenv("");
301        assert_eq!(env, FORWARDED_ENV.join(":"));
302        // The user's own WSLENV cannot carry the instance's credentials in.
303        let env = wslenv("AGENTMUX_AUTH_KEY:AGENTMUX_LOCAL_URL/u:PATH/l:AGENTMUX_TABID");
304        assert!(
305            !env.contains("AGENTMUX_AUTH_KEY") && !env.contains("AGENTMUX_LOCAL_URL"),
306            "{env}"
307        );
308        assert!(env.starts_with("PATH/l:AGENTMUX_TABID:"), "{env}");
309        assert!(!wslenv_with("AGENTMUX_AUTH_KEY/p", []).contains("AGENTMUX_AUTH_KEY"));
310        let env = wslenv("USERPROFILE/p:TERM/u");
311        assert!(env.starts_with("USERPROFILE/p:TERM/u:"), "{env}");
312        let names: Vec<&str> = env
313            .split(':')
314            .map(|p| p.split('/').next().unwrap())
315            .collect();
316        assert_eq!(
317            names.iter().filter(|n| **n == "TERM").count(),
318            1,
319            "TERM once: {env}"
320        );
321        assert!(!env.contains("AGENTMUX_AUTH_KEY") && !env.contains("AGENTMUX_LOCAL_URL"));
322    }
323
324    #[test]
325    fn an_agent_command_carries_its_own_env_and_the_gh_guard_but_no_agentmux_secret() {
326        let env = wslenv_with(
327            "GH_CONFIG_DIR/u:USERPROFILE/p",
328            [
329                "RUST_LOG",
330                "AGENTMUX_AUTH_KEY",
331                "AGENTMUX_LOCAL_URL",
332                "AGENTMUX_JEKT_KEY",
333                "AGENTMUX_BLOCKID",
334                "AGENTMUX_AGENT_ID",
335                "GH_CONFIG_DIR",
336                "WSLENV",
337                "BAD:NAME",
338                "",
339            ],
340        );
341        let entries: Vec<&str> = env.split(':').collect();
342        assert!(entries.contains(&"RUST_LOG"), "{env}");
343        assert!(
344            entries.contains(&"AGENTMUX_AGENT_ID"),
345            "a pane's configured identity crosses: {env}"
346        );
347        assert!(
348            entries.contains(&"USERPROFILE/p"),
349            "the user's own entries stay: {env}"
350        );
351        assert_eq!(
352            entries
353                .iter()
354                .filter(|e| e.starts_with("GH_CONFIG_DIR"))
355                .collect::<Vec<_>>(),
356            [&"GH_CONFIG_DIR/p"],
357            "the guard crosses as a distro path, whatever the user's flag was: {env}"
358        );
359        assert_eq!(
360            entries
361                .iter()
362                .filter(|e| e.starts_with("AGENTMUX_BLOCKID"))
363                .count(),
364            1
365        );
366        for secret in [
367            "AGENTMUX_AUTH_KEY",
368            "AGENTMUX_LOCAL_URL",
369            "AGENTMUX_JEKT_KEY",
370            "WSLENV",
371            "BAD",
372        ] {
373            assert!(
374                !entries.iter().any(|e| e.starts_with(secret)),
375                "{secret} in {env}"
376            );
377        }
378    }
379}