Skip to main content

agentmux_srv_core/backend/
cli_messaging.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! AgentMux agents message each other through jekt, so the Claude CLI's own
5//! separate cross-session messaging is turned off by default.
6//!
7//! The switch is an environment variable the CLI reads at launch. Its name is an
8//! internal of the CLI, not a documented setting, so it can change from one CLI
9//! version to the next: when the pinned CLI version moves, the tests below (the
10//! canary) and this note must be rechecked against the new CLI.
11//!
12//! Setting `agent:climessaging`: `false` (the default) launches Claude agents
13//! with the variable set to `0`; `true` leaves it unset, so the CLI behaves as it
14//! does outside AgentMux.
15
16use std::collections::HashMap;
17use std::sync::{Arc, OnceLock};
18
19use super::obj::{meta_get_string, MetaMapType};
20use super::wconfig::ConfigState;
21
22/// The setting. Off by default.
23pub const SETTING_CLI_MESSAGING: &str = "agent:climessaging";
24
25/// The CLI's own gate for its cross-session messaging (set to `0` to turn it
26/// off). An undocumented name: recheck on every CLI upgrade.
27pub const ENV_GATE: &str = "CLAUDE_CODE_HARBOR_KITE";
28
29static CONFIG: OnceLock<Arc<ConfigState>> = OnceLock::new();
30
31/// Attach the live settings (bootstrap), so [`SETTING_CLI_MESSAGING`] is read at each launch.
32pub fn install_config(config: Arc<ConfigState>) {
33    super::claudeai_connectors::install_config(Arc::clone(&config));
34    let _ = CONFIG.set(config);
35}
36
37/// Whether the CLI's own messaging stays on: only a boolean `true` turns it on.
38pub fn enabled(extra: &HashMap<String, serde_json::Value>) -> bool {
39    extra.get(SETTING_CLI_MESSAGING).and_then(|v| v.as_bool()).unwrap_or(false)
40}
41
42/// Turn the CLI's messaging off in a launch environment: a Claude agent's, when the setting is off.
43/// It overwrites what the environment already carries (a persisted `cmd:env`), as the setting is the
44/// only way to turn it back on. Any other provider's launch is left alone.
45pub fn apply(env_vars: &mut HashMap<String, String>, provider: &str, messaging_on: bool) {
46    if provider == "claude" && !messaging_on {
47        env_vars.insert(ENV_GATE.to_string(), "0".to_string());
48    }
49}
50
51/// [`apply`] for a block's launch, reading the provider from its meta and the setting now.
52pub fn apply_for_spawn(env_vars: &mut HashMap<String, String>, block_meta: &MetaMapType) {
53    // The block keeps the definition's provider as written, which may be a legacy alias (`claude-code`).
54    // A block with no provider is a Claude one, as elsewhere in the launch code.
55    let provider = super::providers::resolve_provider_alias(&meta_get_string(block_meta, "agentProvider", "claude"));
56    let provider = if provider.is_empty() { "claude" } else { provider };
57    let on = CONFIG.get().is_some_and(|c| enabled(&c.get_settings().extra));
58    apply(env_vars, provider, on);
59    // The other switch the CLI reads at launch (the claude.ai connectors) is set at the same point.
60    super::claudeai_connectors::apply_for_spawn(env_vars, provider);
61}
62
63/// Whether a volume source is a host folder the CLI keeps its sessions' sockets in, or inside one:
64/// `/tmp/cc-socks`, the user's runtime folder (`$XDG_RUNTIME_DIR`, `/run/user/*`).
65pub fn is_cli_session_dir(source: &str) -> bool {
66    let xdg = std::env::var("XDG_RUNTIME_DIR").ok().map(|d| normalized(&d)).filter(|d| !d.is_empty());
67    let guarded = |p: &str| {
68        let inside = |dir: &str| p == dir || p.starts_with(&format!("{dir}/"));
69        inside("/tmp/cc-socks") || inside("/run/user") || xdg.as_deref().is_some_and(inside)
70    };
71    // A link to the folder resolves to it, where the path exists on this host.
72    guarded(&normalized(source)) || std::fs::canonicalize(source.trim()).is_ok_and(|c| guarded(&normalized(&c.to_string_lossy())))
73}
74
75/// `source` with `\` as `/`, repeated separators, `.` and `..` resolved, and no trailing separator.
76pub(crate) fn normalized(source: &str) -> String {
77    let unified = source.trim().replace('\\', "/");
78    let mut parts: Vec<&str> = Vec::new();
79    for part in unified.split('/') {
80        match part {
81            "" | "." => {}
82            ".." => {
83                parts.pop();
84            }
85            p => parts.push(p),
86        }
87    }
88    format!("{}{}", if unified.starts_with('/') { "/" } else { "" }, parts.join("/"))
89}
90
91/// The first of a container's volume sources that is such a folder, which the container may not mount.
92pub fn refused_volume_source<'a>(mut sources: impl Iterator<Item = &'a str>) -> Option<String> {
93    sources.find(|s| is_cli_session_dir(s)).map(str::to_string)
94}
95
96#[cfg(test)]
97mod tests {
98    use super::*;
99
100    #[test]
101    fn a_volume_from_the_cli_session_folders_is_refused_and_an_ordinary_one_is_not() {
102        for source in ["/tmp/cc-socks", "/tmp/cc-socks/abc", "/run/user/1000", "/run/user/1000/cc", "/run/user"] {
103            assert!(is_cli_session_dir(source), "{source}");
104        }
105        for source in ["/tmp/cc-socks-other", "/home/me/repo", "/tmp", "data", "C:\\Users\\me\\repo"] {
106            assert!(!is_cli_session_dir(source), "{source}");
107        }
108        assert_eq!(refused_volume_source(["data", "/run/user/1000"].into_iter()).as_deref(), Some("/run/user/1000"));
109        assert_eq!(refused_volume_source(["data", "/home/me"].into_iter()), None);
110    }
111
112    fn extra(value: Option<serde_json::Value>) -> HashMap<String, serde_json::Value> {
113        value.into_iter().map(|v| (SETTING_CLI_MESSAGING.to_string(), v)).collect()
114    }
115
116    #[test]
117    fn the_cli_messaging_is_off_unless_the_setting_is_true() {
118        assert!(!enabled(&extra(None)));
119        assert!(!enabled(&extra(Some(serde_json::json!("yes")))));
120        assert!(!enabled(&extra(Some(serde_json::json!(false)))));
121        assert!(enabled(&extra(Some(serde_json::json!(true)))));
122    }
123
124    /// The canary: the gate is present, as `0`, for a Claude agent while the setting is off, and absent
125    /// once it is on. If the CLI renames its gate, this is where the new name goes.
126    #[test]
127    fn a_claude_launch_carries_the_gate_with_the_setting_off_and_not_with_it_on() {
128        let mut off = HashMap::new();
129        apply(&mut off, "claude", false);
130        assert_eq!(off.get(ENV_GATE).map(String::as_str), Some("0"));
131
132        let mut on = HashMap::new();
133        apply(&mut on, "claude", true);
134        assert!(!on.contains_key(ENV_GATE));
135    }
136
137    #[test]
138    fn the_gate_overwrites_a_persisted_value_and_other_providers_are_left_alone() {
139        let mut persisted = HashMap::from([(ENV_GATE.to_string(), "1".to_string())]);
140        apply(&mut persisted, "claude", false);
141        assert_eq!(persisted.get(ENV_GATE).map(String::as_str), Some("0"));
142
143        let mut codex = HashMap::new();
144        apply(&mut codex, "codex", false);
145        assert!(codex.is_empty());
146    }
147
148    #[test]
149    fn a_block_with_no_provider_is_a_claude_launch() {
150        for meta in [MetaMapType::new(), MetaMapType::from_iter([("agentProvider".to_string(), serde_json::json!(""))])] {
151            let mut env = HashMap::new();
152            apply_for_spawn(&mut env, &meta);
153            assert_eq!(env.get(ENV_GATE).map(String::as_str), Some("0"));
154        }
155    }
156
157    #[test]
158    fn a_legacy_provider_alias_is_still_claude() {
159        for alias in ["claude-code", "claude_code", "claude"] {
160            let mut meta = MetaMapType::new();
161            meta.insert("agentProvider".to_string(), serde_json::json!(alias));
162            let mut env = HashMap::new();
163            apply_for_spawn(&mut env, &meta);
164            assert_eq!(env.get(ENV_GATE).map(String::as_str), Some("0"), "{alias}");
165        }
166    }
167
168    #[test]
169    fn a_volume_source_is_compared_after_dots_and_repeated_separators_are_resolved() {
170        for source in ["/tmp//cc-socks", "/tmp/cc-socks/../cc-socks", "/run/user/../user/1000", "/tmp/./cc-socks/", "\\tmp\\cc-socks"] {
171            assert!(is_cli_session_dir(source), "{source}");
172        }
173        assert!(!is_cli_session_dir("/tmp/cc-socks/.."), "the parent is not the folder");
174    }
175
176    #[test]
177    fn a_block_meta_names_the_provider() {
178        let mut meta = MetaMapType::new();
179        meta.insert("agentProvider".to_string(), serde_json::json!("claude"));
180        let mut env = HashMap::new();
181        apply_for_spawn(&mut env, &meta);
182        assert_eq!(env.get(ENV_GATE).map(String::as_str), Some("0"), "no settings installed: the default, off");
183    }
184}