Skip to main content

agentmux_srv_core/backend/blockcontroller/shell/
spawn_command.rs

1// Copyright 2025-2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! What a shell pane runs: the command (WSL, SSH, container, a program or the login
5//! shell) and the environment every one of them gets.
6
7use portable_pty::CommandBuilder;
8
9use super::controller::ShellController;
10use super::lifecycle::cmd_env_overrides;
11use crate::backend::obj::{self, MetaMapType};
12use crate::backend::remote::conn::SshDest;
13
14/// Where and what `start` decided to run, before the command is built.
15pub(super) struct SpawnPlan<'a> {
16    pub(super) cmd_str: &'a str,
17    pub(super) cmd_args: &'a [String],
18    pub(super) interactive: bool,
19    pub(super) wsl_distro: Option<&'a str>,
20    pub(super) ssh_plan: Option<&'a (std::path::PathBuf, SshDest)>,
21    pub(super) askpass_secret: Option<&'a str>,
22    pub(super) container: Option<&'a str>,
23    pub(super) pane_cwd: &'a str,
24}
25
26/// The `AGENTMUX_LOG_DIR` a pane gets: the instance's log folder. An instance with no log folder
27/// (srv run without its launcher) gets none: a made-up folder would send `muxlog` to a place no log is in.
28fn log_dir_env(logs_dir: Option<&std::path::Path>) -> Option<(&'static str, &std::ffi::OsStr)> {
29    logs_dir.map(|dir| ("AGENTMUX_LOG_DIR", dir.as_os_str()))
30}
31
32impl ShellController {
33    /// The command for the pane: WSL, SSH, a container, a program, a shell-wrapped
34    /// command or the login shell, in that order.
35    pub(super) fn build_command(
36        &self,
37        block_meta: &MetaMapType,
38        plan: &SpawnPlan,
39    ) -> Result<CommandBuilder, String> {
40        let SpawnPlan {
41            cmd_str,
42            cmd_args,
43            interactive,
44            wsl_distro,
45            ssh_plan,
46            askpass_secret,
47            container,
48            pane_cwd,
49        } = *plan;
50        if let Some(distro) = wsl_distro {
51            return Ok(self.wsl_command(distro, plan, block_meta));
52        }
53        if let Some((ssh_path, dest)) = ssh_plan {
54            let what = (cmd_str, cmd_args, pane_cwd);
55            return Ok(super::ssh_pane::command(
56                ssh_path,
57                dest,
58                what,
59                askpass_secret,
60                &self.auth_key,
61                &self.block_id,
62            ));
63        }
64        if let Some(name) = container {
65            return Ok(super::container_pane::command(
66                name,
67                &self.block_id,
68                &super::super::cmd_env_of(block_meta),
69            ));
70        }
71        if !cmd_str.is_empty() && (!cmd_args.is_empty() || interactive) {
72            // Direct spawn: cmd:args provided or cmd:interactive set.
73            // Spawn the CLI directly (no sh -c wrapper) so args are passed correctly.
74            tracing::info!(block_id = %self.block_id, cmd = %cmd_str, args = ?cmd_args, "direct spawn path");
75            return self.command_process(cmd_str, cmd_args, interactive, block_meta);
76        }
77        if !cmd_str.is_empty() {
78            // "cmd" controller: run a specific command string via shell wrapper
79            tracing::info!(block_id = %self.block_id, cmd = %cmd_str, "shell-wrapped spawn path");
80            return self.command_process(cmd_str, cmd_args, interactive, block_meta);
81        }
82        Ok(self.login_shell_command(block_meta))
83    }
84
85    /// The process a `cmd` pane runs: `cmd` itself when it has `cmd:args` or
86    /// `cmd:interactive`, otherwise `cmd` through the platform shell. Either
87    /// way with the pane's `cmd:env`, as an interactive shell gets it: a pane
88    /// running a provider CLI's login needs the account's config directory.
89    ///
90    /// Spawned directly, an npm `.cmd` shim on Windows is resolved to what it
91    /// runs: the shim itself hangs under ConPTY (`resolve_cli_spawn_target`).
92    /// One that can't be read is refused, rather than started into a pane
93    /// that would never respond.
94    pub(super) fn command_process(
95        &self,
96        cmd_str: &str,
97        cmd_args: &[String],
98        interactive: bool,
99        block_meta: &MetaMapType,
100    ) -> Result<CommandBuilder, String> {
101        let mut c = if !cmd_args.is_empty() || interactive {
102            // Spawned directly (no shell wrapper), so args pass through intact.
103            let (program, prefix) = agentmux_common::resolve_cli_spawn_target(cmd_str).ok_or_else(|| {
104                format!(
105                    "can't run {cmd_str}: it's a command wrapper AgentMux can't read, and run as it is it would hang; \
106                     reinstall the tool, or run its own executable"
107                )
108            })?;
109            let mut c = CommandBuilder::new(&program);
110            c.args(&prefix);
111            c.args(cmd_args);
112            c
113        } else if cfg!(windows) {
114            let mut c = CommandBuilder::new("cmd.exe");
115            c.args(["/C", cmd_str]);
116            c
117        } else {
118            let mut c = CommandBuilder::new("/bin/sh");
119            c.args(["-c", cmd_str]);
120            c
121        };
122        self.apply_cmd_env(&mut c, block_meta);
123        Ok(c)
124    }
125
126    fn wsl_command(
127        &self,
128        distro: &str,
129        plan: &SpawnPlan,
130        block_meta: &MetaMapType,
131    ) -> CommandBuilder {
132        let SpawnPlan {
133            cmd_str,
134            cmd_args,
135            pane_cwd,
136            ..
137        } = *plan;
138        let plan = crate::backend::remote::wsl::launch(distro, cmd_str, cmd_args, pane_cwd);
139        tracing::info!(block_id = %self.block_id, distro = %distro, args = ?plan.args, "wsl spawn path");
140        let mut c = CommandBuilder::new("wsl.exe");
141        c.args(plan.args.iter().map(String::as_str));
142        c.env("TERM", "xterm-256color");
143        c.env("COLORTERM", "truecolor");
144        c.env("TERM_PROGRAM", "agentmux");
145        c.env("AGENTMUX_BLOCKID", &self.block_id);
146        c.env("AGENTMUX_TABID", &self.tab_id);
147        c.env("AGENTMUX_VERSION", env!("CARGO_PKG_VERSION"));
148        // Configured cmd:env (global, then the block's), as a local
149        // interactive shell gets it, and listed in WSLENV so it crosses.
150        let overrides =
151            cmd_env_overrides(&self.live_settings(), &self.with_agent_identity(block_meta));
152        overrides.apply_to(&mut c);
153        c.env(
154            "WSLENV",
155            crate::backend::remote::wsl::wslenv_with(
156                &std::env::var("WSLENV").unwrap_or_default(),
157                overrides.vars.iter().map(|(k, _)| k.as_str()),
158            ),
159        );
160        c
161    }
162
163    /// "shell" controller: the block's or the default shell, with AgentMux integration (backend::shells).
164    fn login_shell_command(&self, block_meta: &MetaMapType) -> CommandBuilder {
165        let (shell_path, shell_opts) =
166            crate::backend::shells::for_block(&self.block_id, block_meta, &self.live_settings());
167        let shell_path = shell_path.display().to_string();
168
169        let shell_type = crate::backend::shellintegration::detect_shell_type(&shell_path);
170
171        // Deploy shell integration scripts under the user's home rather than
172        // AGENTMUX_DATA_HOME.  MSIX packages virtualise writes to %LocalAppData%,
173        // so files written by the packaged backend aren't visible to child
174        // processes (pwsh, bash, etc.) spawned via ConPTY.  The home dir is never
175        // virtualised, so the scripts are always reachable at their literal path.
176        //
177        // The path is keyed per instance: this runs on EVERY shell spawn, so an
178        // unkeyed home-global dir let two concurrently-running versions rewrite
179        // each other's scripts indefinitely (I6).  See `integration_base`.
180        let shell_home = crate::backend::shellintegration::integration_base();
181        crate::backend::shellintegration::deploy_scripts(&shell_home);
182
183        tracing::info!(block_id = %self.block_id, shell = %shell_path, shell_type = ?shell_type, "interactive shell path");
184
185        let mut c = CommandBuilder::new(&shell_path);
186
187        // Apply shell-specific startup args (--rcfile, -File, etc.)
188        let startup = crate::backend::shellintegration::get_shell_startup(shell_type, &shell_home);
189        let integration = startup
190            .as_ref()
191            .map(|s| s.extra_args.as_slice())
192            .unwrap_or_default();
193        c.args(crate::backend::shells::with_user_opts(
194            integration,
195            &shell_opts,
196        ));
197        for (k, v) in startup.iter().flat_map(|s| &s.env_vars) {
198            c.env(k, v);
199        }
200
201        // Inject terminal capability env vars into the PTY environment.
202        // ConPTY on Windows fully supports VT/ANSI sequences, so set TERM
203        // on all platforms. Without this, CLI tools (e.g. Claude Code) use
204        // different Unicode width tables, causing ANSI color offset on Windows.
205        c.env("TERM", "xterm-256color");
206        c.env("COLORTERM", "truecolor");
207        c.env("TERM_PROGRAM", "agentmux");
208        c.env("AGENTMUX_BLOCKID", &self.block_id);
209        c.env("AGENTMUX_TABID", &self.tab_id);
210        c.env("AGENTMUX_VERSION", env!("CARGO_PKG_VERSION"));
211
212        // The log folder, so agents and `muxlog` find the logs without guessing: this instance's,
213        // as the launcher resolved it (per version and channel, under a home override too), the
214        // same folder the host and srv write to and `app.logs.tail` reads.
215        let logs_dir = agentmux_common::DataPaths::from_env().map(|p| p.logs_dir);
216        if let Some((key, value)) = log_dir_env(logs_dir.as_deref()) {
217            c.env(key, value);
218        }
219
220        // AGENTMUX_LOCAL_URL / AGENTMUX_AUTH_KEY are set for every kind of command
221        // in `apply_pane_env`, not here.
222
223        // Wire AgentMux-managed tool dirs into the agent's PATH.
224        //
225        // Two stores, two precedence rules:
226        //
227        //   • Bundled store (`<exe_dir>/tools/bin`) ships the app's OWN
228        //     version-locked binaries — notably `agentmux-bashwrap`, the
229        //     streaming hook that MUST match the running build. It is
230        //     PREPENDED so it wins over any stale copy elsewhere on the
231        //     system PATH. A stale system-PATH `agentmux-bashwrap` (from a
232        //     leftover portable) silently shadowed the fixed one and
233        //     reintroduced the exit-130 bug — see
234        //     docs/retro/RETRO_BASHWRAP_STALE_BUNDLE_2026_06_13.md. The
235        //     bundled jq/rg winning too is intended: agents get the app's
236        //     curated, deterministic tool versions regardless of host.
237        //
238        //   • User-managed store (`~/.agentmux/tools/bin`) holds tools the
239        //     user installed via /tools. APPENDED so the user's own system
240        //     PATH still wins for those.
241        wire_tool_dirs(&mut c);
242
243        // cmd:env: global settings (lowest priority), then the block's
244        // own metadata (highest), then the agent-identity strip. The
245        // settings come from the live config — see `cmd_env_overrides`.
246        self.apply_cmd_env(&mut c, block_meta);
247
248        c
249    }
250
251    /// The pane's endpoint and key, the sanitiser, and the PtyShell's gh and git guards,
252    /// applied to every kind of command.
253    pub(super) fn apply_pane_env(&self, cmd: &mut CommandBuilder, block_meta: &MetaMapType) {
254        // The instance's API endpoint and key, for every kind of command: `muxsh`, `muxspect`,
255        // `muxopen` and `muxlog` run by a human in any pane need both to authenticate. The URL
256        // is read back from this process's env; the key was scrubbed from it at start-up, so it
257        // comes from `self.auth_key`.
258        if let Ok(local_url) = std::env::var("AGENTMUX_LOCAL_URL") {
259            cmd.env("AGENTMUX_LOCAL_URL", &local_url);
260        }
261        if !self.auth_key.is_empty() {
262            cmd.env("AGENTMUX_AUTH_KEY", &self.auth_key);
263        }
264
265        // For every kind of command, not just the interactive shell: a direct-spawn
266        // command launches agent CLIs and a shell-wrapped `cmd` can launch anything,
267        // and both would otherwise inherit the full instance identity.
268        crate::backend::pane_env::sanitize_pty_command(cmd);
269        // An agent's PtyShell carries the agent's plain-`gh` guard (set by
270        // `http_pty_shell.rs`): the agent types into this shell, so `gh` here
271        // must not act as the user. Every kind of command, after the sanitizer; a WSL
272        // shell's WSLENV already lists GH_CONFIG_DIR as a distro path.
273        let gh_guard = obj::meta_get_string(
274            block_meta,
275            crate::backend::gh_guard::META_KEY_PTYSHELL_GH_CONFIG_DIR,
276            "",
277        );
278        if !gh_guard.is_empty() {
279            cmd.env(crate::backend::gh_guard::GH_CONFIG_DIR, &gh_guard);
280        }
281        // Its publish-guard hooks too (`backend::publish_guard`). A host path,
282        // so a WSL shell, whose WSLENV doesn't list these, is unaffected.
283        let hooks = obj::meta_get_string(
284            block_meta,
285            crate::backend::publish_guard::META_KEY_PTYSHELL_GIT_HOOKS_PATH,
286            "",
287        );
288        if !hooks.is_empty() {
289            // On top of the GIT_CONFIG_* entries this shell already has (the
290            // process env plus cmd:env), so none of them is overwritten.
291            let entries = crate::backend::publish_guard::git_config_entries(
292                |k| cmd.get_env(k).and_then(|v| v.to_str()).map(str::to_string),
293                "core.hooksPath",
294                &hooks,
295            );
296            for (key, value) in entries {
297                cmd.env(key, value);
298            }
299        }
300        // And the git settings that keep a shared folder's own configuration from running a program.
301        if obj::meta_get_bool(block_meta, crate::backend::git_program_settings::META_KEY_PTYSHELL_GIT_PROGRAM_SETTINGS, false) {
302            let entries = crate::backend::git_program_settings::entries_over(
303                |k| cmd.get_env(k).and_then(|v| v.to_str()).map(str::to_string),
304                &crate::backend::git_program_settings::persons_values(),
305            );
306            for (key, value) in entries {
307                cmd.env(key, value);
308            }
309        }
310        // Identity M4a: a terminal pane never carries a token. No counter —
311        // most panes are not agents — but an agent CLI that registers from
312        // this block shows in the live gauge.
313        crate::backend::identity_spawn::record_spawn(&self.block_id, false, None);
314    }
315}
316
317/// Puts the bundled and the user's tool directories on the command's PATH.
318fn wire_tool_dirs(c: &mut CommandBuilder) {
319    let current_path = std::env::var("PATH").unwrap_or_default();
320    let mut bundled: Option<std::path::PathBuf> = None;
321
322    // Bundled store — prepended (app-owned, version-locked).
323    if let Some(bundled_bin) = crate::backend::tool_store::bundled_tools_dir() {
324        if bundled_bin.exists() {
325            // Guardrail: log which agentmux-bashwrap the agent will
326            // actually run. A stale system-PATH copy silently
327            // shadowing the bundled one is exactly the exit-130
328            // trap (RETRO_BASHWRAP_STALE_BUNDLE_2026_06_13.md); this
329            // one line makes "which binary?" answerable at a glance
330            // (cross-check the version with `agentmux-bashwrap
331            // --version`).
332            let bashwrap_exe = if cfg!(windows) {
333                "agentmux-bashwrap.exe"
334            } else {
335                "agentmux-bashwrap"
336            };
337            let bw = bundled_bin.join(bashwrap_exe);
338            if bw.exists() {
339                tracing::info!(
340                    target: "agent-tools",
341                    path = %bw.display(),
342                    "agent bashwrap: bundled (version-locked, prepended to PATH)"
343                );
344            } else {
345                tracing::warn!(
346                    target: "agent-tools",
347                    dir = %bundled_bin.display(),
348                    "agent bashwrap: bundled store present but agentmux-bashwrap MISSING — agent will resolve via system PATH (risk of a stale copy; see RETRO_BASHWRAP_STALE_BUNDLE_2026_06_13.md)"
349                );
350            }
351            bundled = Some(bundled_bin.clone());
352        } else {
353            tracing::warn!(
354                target: "agent-tools",
355                "agent bashwrap: no bundled tools dir — agent will resolve agentmux-bashwrap via system PATH (risk of a stale copy; see RETRO_BASHWRAP_STALE_BUNDLE_2026_06_13.md)"
356            );
357        }
358    }
359
360    // User-managed store — after the system PATH, which still wins.
361    let user = crate::backend::tool_store::user_tools_dir().filter(|d| d.exists());
362    if let Some(path) = crate::backend::tool_store::compose_tools_path(
363        &current_path,
364        bundled.as_deref(),
365        user.as_deref(),
366        crate::backend::tool_store::UserToolsPrecedence::AfterExisting,
367    ) {
368        c.env("PATH", path);
369    }
370}
371
372#[cfg(test)]
373mod tests {
374    use super::*;
375    use std::path::Path;
376
377    #[test]
378    fn the_pane_gets_the_instances_log_folder_not_the_launchers_home_folder() {
379        let logs = Path::new("/tmp/am-home/channels/stable/versions/9.9.9/logs");
380        assert_eq!(log_dir_env(Some(logs)), Some(("AGENTMUX_LOG_DIR", logs.as_os_str())));
381    }
382
383    #[test]
384    fn an_instance_with_no_log_folder_gets_none() {
385        assert_eq!(log_dir_env(None), None);
386    }
387}