Skip to main content

agentmux_srv_core/backend/spawn_env/
bash_prefix.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The Claude agent's Bash settings at launch: `agentmux-bashwrap` as the CLI's
5//! `CLAUDE_CODE_SHELL_PREFIX`, which streams Bash output without the hook
6//! rewriting the call (docs/specs/SPEC_BASH_STREAMING_VIA_SHELL_PREFIX_2026_10_10.md).
7
8/// Set the prefix in an agent's spawn environment
9/// (`spawn_env::build::build_persistent_spawn_env`). Not for a pane in the MCP
10/// self-heal's safe profile: its MCP server failed to start and reconnecting
11/// didn't help, so its CLI runs without the prefix, as with
12/// `AGENTMUX_BASHWRAP_MODE=rewrite` (`backend::mcp_health`).
13pub(crate) fn apply_for_spawn(
14    env_vars: &mut std::collections::HashMap<String, String>,
15    block_id: &str,
16    block_meta: &crate::backend::obj::MetaMapType,
17) {
18    let mode = mode_for(block_id);
19    apply_bash_shell_prefix(env_vars, crate::backend::tool_store::bashwrap_path(), mode.as_deref());
20    // The agentmux MCP server, started through that prefix once per agent per build (in the background).
21    crate::backend::mcp_selftest::launch(env_vars, block_id, block_meta);
22    // A Bash call still running after 30 s goes to the background and gives the turn back (Claude Code's own timeout).
23    crate::backend::bash_background::apply_for_spawn(env_vars, block_meta);
24}
25
26/// `rewrite` for a pane in the safe profile, else srv's own setting.
27fn mode_for(block_id: &str) -> Option<String> {
28    if crate::backend::mcp_health::is_safe_profile(block_id) {
29        tracing::info!(block_id, "MCP self-heal safe profile: starting the agent without the shell prefix");
30        return Some("rewrite".to_string());
31    }
32    std::env::var(BASHWRAP_MODE_ENV).ok()
33}
34
35/// srv's own environment variable that turns the shell prefix off:
36/// `rewrite` keeps the hook rewriting commands, as before the prefix.
37const BASHWRAP_MODE_ENV: &str = "AGENTMUX_BASHWRAP_MODE";
38
39/// Claude Code runs every Bash tool command through `CLAUDE_CODE_SHELL_PREFIX`
40/// when it is set: pointed at `agentmux-bashwrap`, that streams the command
41/// without the hook rewriting the call, so the CLI's permission rules and
42/// labels see the model's own command
43/// (docs/specs/SPEC_BASH_STREAMING_VIA_SHELL_PREFIX_2026_10_10.md ยง2.4).
44/// Only Claude Code reads the variable. A prefix the agent's own `cmd:env`
45/// sets is kept (the hook then rewrites, as it does without a prefix); no
46/// prefix is set without the wrapper, or when srv runs with
47/// `AGENTMUX_BASHWRAP_MODE=rewrite`.
48fn apply_bash_shell_prefix(
49    env_vars: &mut std::collections::HashMap<String, String>,
50    bashwrap: Option<std::path::PathBuf>,
51    mode: Option<&str>,
52) {
53    const PREFIX_ENV: &str = "CLAUDE_CODE_SHELL_PREFIX";
54    if env_vars.contains_key(PREFIX_ENV) || mode.is_some_and(|m| m.eq_ignore_ascii_case("rewrite")) {
55        return;
56    }
57    if let Some(path) = bashwrap {
58        env_vars.insert(PREFIX_ENV.to_string(), path.to_string_lossy().into_owned());
59    }
60}
61
62#[cfg(test)]
63mod tests {
64    use super::apply_bash_shell_prefix;
65
66    const PREFIX: &str = "CLAUDE_CODE_SHELL_PREFIX";
67
68    #[test]
69    fn the_shell_prefix_names_the_bundled_wrapper() {
70        let mut env = std::collections::HashMap::new();
71        let wrapper = std::path::PathBuf::from("/opt/agentmux/tools/bin/agentmux-bashwrap");
72        apply_bash_shell_prefix(&mut env, Some(wrapper.clone()), None);
73        assert_eq!(env.get(PREFIX).map(String::as_str), Some(wrapper.to_str().unwrap()));
74    }
75
76    #[test]
77    fn no_shell_prefix_without_the_wrapper_or_when_switched_off() {
78        let mut env = std::collections::HashMap::new();
79        apply_bash_shell_prefix(&mut env, None, None);
80        assert!(!env.contains_key(PREFIX));
81        let wrapper = Some(std::path::PathBuf::from("/x/agentmux-bashwrap"));
82        apply_bash_shell_prefix(&mut env, wrapper.clone(), Some("rewrite"));
83        apply_bash_shell_prefix(&mut env, wrapper, Some("REWRITE"));
84        assert!(!env.contains_key(PREFIX));
85    }
86
87    #[test]
88    fn an_agents_own_shell_prefix_is_kept() {
89        let mut env = std::collections::HashMap::from([(PREFIX.to_string(), "/home/me/log-commands.sh".to_string())]);
90        apply_bash_shell_prefix(&mut env, Some("/x/agentmux-bashwrap".into()), None);
91        assert_eq!(env[PREFIX], "/home/me/log-commands.sh");
92    }
93
94    /// A pane whose MCP server failed and wouldn't reconnect starts without
95    /// the prefix; other panes are unaffected.
96    #[test]
97    fn a_pane_in_the_safe_profile_gets_no_prefix() {
98        use crate::backend::mcp_health::{on_reconnect, on_rewrite, on_status, Status};
99        let block = format!("safe-profile-test-{}", uuid::Uuid::new_v4());
100        on_status(&block, "p1", Status::Failed, None, true, 0);
101        on_reconnect(&block, "p1", Err("Connection closed".into()), 1);
102        on_reconnect(&block, "p1", Err("Connection closed".into()), 2);
103        // The two rewrites of the entry changed nothing, so the safe profile is next.
104        on_rewrite(&block, "p1", Ok(false), 3);
105        on_rewrite(&block, "p1", Ok(false), 4);
106        assert_eq!(super::mode_for(&block).as_deref(), Some("rewrite"));
107        if std::env::var("AGENTMUX_BASHWRAP_MODE").is_err() {
108            assert_eq!(super::mode_for("another-pane"), None);
109        }
110    }
111}