Skip to main content

agentmux_srv_core/backend/
agent_env_scope.rs

1//! Which of the variables srv puts in an agent's environment reach a container agent, and how.
2//!
3//! One table, with a reason on each line, in place of the denylist `container_exec_env` used to apply
4//! to a list written apart from the code that sets the variables (task #13666, step 2). A name srv sets
5//! on an agent turn needs an entry here; `every_name_srv_sets_on_a_turn_has_a_scope` runs the code that
6//! sets them and fails on one that has none, so a new variable is placed when it is added, not found
7//! later when it turns up inside a container. It covers the identity, workspace, auth, tool-path and
8//! build-label steps. The GitHub broker, the publish guard's `GIT_CONFIG_*` and the AWS broker are gated
9//! out under `cfg(test)`, so they are covered by `FAMILIES` and the entries above, not by that test.
10//!
11//! What a name the agent's own `cmd:env` carries gets is not decided here: it passes through unchanged,
12//! as it did.
13
14/// Where a variable goes.
15#[derive(Debug, Clone, Copy, PartialEq, Eq)]
16pub enum EnvScope {
17    /// Native and container agents get it as it is.
18    Everywhere,
19    /// A native agent only: it names the host (a path, a user, a temp folder) and means nothing in an image.
20    HostOnly,
21    /// A container agent gets srv's own value for the container (a token, a URL it can reach, a build label);
22    /// `container_exec_env` sets it, and it replaces any the agent's environment carried.
23    Rewrite,
24}
25
26pub struct EnvSpec {
27    pub name: &'static str,
28    pub scope: EnvScope,
29    pub why: &'static str,
30}
31
32const fn spec(name: &'static str, scope: EnvScope, why: &'static str) -> EnvSpec {
33    EnvSpec { name, scope, why }
34}
35
36use EnvScope::{Everywhere, HostOnly, Rewrite};
37
38/// The variables srv sets or decides on an agent's turn, by name.
39pub const AGENT_ENV: &[EnvSpec] = &[
40    // The agent's identity: the same in or out of a container.
41    spec("AGENTMUX_AGENT_ID", Everywhere, "who the agent is, for MCP routing, memory and jekts"),
42    spec("MUXBUS_AGENT_ID", Everywhere, "AGENTMUX_AGENT_ID under the prefix muxbus-client checks first"),
43    spec("AGENTMUX_AGENT_DISPLAY", Everywhere, "the agent's display name"),
44    spec("AGENTMUX_AGENT_SLUG", Everywhere, "the agent's slug"),
45    spec("AGENTMUX_AGENT_UID", Everywhere, "the agent's row id"),
46    spec("AGENTMUX_AGENT_TOKEN", Everywhere, "the agent's own token; a container's exec token is minted from it"),
47    spec("AGENTMUX_AGENT_FORMER_NAMES", Everywhere, "the names the agent had before a rename"),
48    spec("AGENTMUX_AGENT_FORMER_SLUGS", Everywhere, "the slugs the agent had before a rename"),
49    spec("AGENTMUX_BLOCKID", Everywhere, "the pane the agent's tools speak for"),
50    spec("GIT_AUTHOR_NAME", Everywhere, "git identity: the agent's id"),
51    spec("GIT_AUTHOR_EMAIL", Everywhere, "git identity: the agent's id"),
52    spec("GIT_COMMITTER_NAME", Everywhere, "git identity: the agent's id"),
53    spec("GIT_COMMITTER_EMAIL", Everywhere, "git identity: the agent's id"),
54    // Switches the agent CLI reads.
55    spec("CLAUDE_CODE_HARBOR_KITE", Everywhere, "cli_messaging's gate for the CLI"),
56    spec("ENABLE_CLAUDEAI_MCP_SERVERS", Everywhere, "claudeai_connectors' switch for the CLI"),
57    spec("CLAUDE_CODE_SUBAGENT_MODEL", Everywhere, "the model the CLI's subagents use"),
58    // An agent on a model route (backend::model_gateway): its harness is pointed at srv, never at a key.
59    spec("ANTHROPIC_BASE_URL", Rewrite, "the gateway on srv; a container is given the address it can reach, as for AGENTMUX_LOCAL_URL"),
60    spec("ANTHROPIC_AUTH_TOKEN", Everywhere, "the agent's gateway token, the harness's only credential on a model route"),
61    spec("ANTHROPIC_API_KEY", Everywhere, "emptied on a model route so no other key is used"),
62    spec("ANTHROPIC_DEFAULT_OPUS_MODEL", Everywhere, "the route's model for the harness's largest tier"),
63    spec("ANTHROPIC_DEFAULT_SONNET_MODEL", Everywhere, "the route's model for the harness's middle tier"),
64    spec("ANTHROPIC_DEFAULT_HAIKU_MODEL", Everywhere, "the route's model for the harness's small tier"),
65    // GitHub through the broker: the same hand-off in a container, where the image finds the hooks.
66    spec("AGENTMUX_GITHUB_BROKER", Everywhere, "tells the shell wrappers to ask srv for a GitHub token"),
67    spec("AGENTMUX_GIT_HOST", Everywhere, "the git host the broker serves"),
68    spec("GIT_TERMINAL_PROMPT", Everywhere, "git never asks the terminal for a password"),
69    // What a container is given in place of the host's.
70    spec("AGENTMUX_AUTH_KEY", Rewrite, "the instance key is replaced by this block's container token"),
71    spec("AGENTMUX_LOCAL_URL", Rewrite, "a container reaches srv at host.docker.internal or the agents network's gateway, not loopback"),
72    spec("AGENTMUX_VERSION", Rewrite, "which AgentMux this is: a container exec does not go through pane_env, so srv adds it"),
73    spec("AGENTMUX_BUILD", Rewrite, "which AgentMux this is: a container exec does not go through pane_env, so srv adds it"),
74    spec("AGENTMUX_INSTANCE_CHANNEL", Rewrite, "which AgentMux this is: set only when srv runs in a named channel; as AGENTMUX_VERSION"),
75    spec("AGENTMUX_IN_CONTAINER", Rewrite, "a hint for the in-container MCP and bashwrap, which are not given signing keys"),
76    spec("AGENTMUX_PUBLISH_GUARD", Rewrite, "set to 1 where this machine's gh-agent can judge a container's push, older-gh-agent where it cannot, 0 where there is no gh-agent, for the container's pre-push hook; any value the agent carried is replaced"),
77    spec("CHOKIDAR_USEPOLLING", Rewrite, "file watchers poll where the workspace is a file-sharing mount that sends no change events (Docker Desktop)"),
78    spec("CHOKIDAR_INTERVAL", Rewrite, "as CHOKIDAR_USEPOLLING"),
79    spec("WATCHPACK_POLLING", Rewrite, "as CHOKIDAR_USEPOLLING"),
80    // Host paths and host users: the image has its own.
81    spec("CLAUDE_CONFIG_DIR", HostOnly, "a host path: the image supplies its own, and the bound account is mounted instead"),
82    spec("GH_CONFIG_DIR", HostOnly, "the gh guard's folder is a host path; the image controls its own gh state"),
83    spec("PATH", HostOnly, "a host path list: the image has its own tools"),
84    spec("HOME", HostOnly, "a host path: the image has its own home"),
85    spec("USERPROFILE", HostOnly, "a host path: the image has its own home"),
86    spec("HOMEDRIVE", HostOnly, "a host path: the image has its own home"),
87    spec("HOMEPATH", HostOnly, "a host path: the image has its own home"),
88    spec("TMPDIR", HostOnly, "a host temp folder"),
89    spec("TEMP", HostOnly, "a host temp folder"),
90    spec("TMP", HostOnly, "a host temp folder"),
91    spec("AGENTMUX_AGENT_WORKDIR", HostOnly, "the host path of the agent's workspace; srv sets it for host agents only"),
92    spec("AGENTMUX_MCP_CONFIG", HostOnly, "the host path of the agent's MCP config; a container doctor uses the bind-mounted copy"),
93    spec("CLAUDE_CODE_SHELL_PREFIX", HostOnly, "a host path; the image's own wrapper may predate prefix mode"),
94    spec("CLAUDE_CODE_DISABLE_CRON", HostOnly, "set for a host agent in a folder a container agent can write, whose CLI's scheduler is off there"),
95    spec("CLAUDE_CODE_ADDITIONAL_DIRECTORIES_CLAUDE_MD", HostOnly, "set for a host agent in a folder a container agent can write, with the host path of its startup instructions"),
96];
97
98/// Names that come in numbered or generated families.
99const FAMILIES: &[(&str, EnvScope, &str)] = &[
100    ("GIT_CONFIG_", Rewrite, "git settings: the publish guard's hooks path is a host path and is dropped, the container gets its own hooks"),
101    ("AWS_", Rewrite, "the AWS SDK asks srv for credentials through the mounted config, where the host shares AWS with containers"),
102    ("BASH_FUNC_", Everywhere, "the broker's gh and git shell functions"),
103];
104
105/// How `name` goes into a container, or `None` if srv has not placed it.
106pub fn scope_of(name: &str) -> Option<EnvScope> {
107    AGENT_ENV
108        .iter()
109        .find(|s| s.name == name)
110        .map(|s| s.scope)
111        .or_else(|| FAMILIES.iter().find(|(prefix, ..)| name.starts_with(prefix)).map(|(_, scope, _)| *scope))
112}
113
114/// Whether a container agent is not given `name` from the host's environment.
115pub fn host_only(name: &str) -> bool {
116    scope_of(name) == Some(HostOnly)
117}
118
119#[cfg(test)]
120mod tests {
121    use super::*;
122    use std::collections::{BTreeSet, HashMap};
123
124    #[test]
125    fn every_entry_has_a_reason_and_no_name_twice() {
126        let mut seen = BTreeSet::new();
127        for s in AGENT_ENV {
128            assert!(!s.why.trim().is_empty(), "{} needs a reason", s.name);
129            assert!(seen.insert(s.name), "{} is listed twice", s.name);
130        }
131    }
132
133    /// What srv sets on a turn's environment, from the code that sets it. The agent's own `cmd:env` is the
134    /// `base` and is not counted.
135    fn names_srv_sets(base: &HashMap<String, String>) -> BTreeSet<String> {
136        use crate::backend::spawn_env::{block_identity as input, identity as identity_env};
137        let mut env = base.clone();
138        let identity = input::PersistedAgentIdentity {
139            uid: "11111111-2222-3333-4444-555555555555".into(),
140            slug: Some("fixture-agent".into()),
141            token: Some("tok".into()),
142            former: Default::default(),
143        };
144        input::carry_agent_uid_env(&mut env, Some(&identity));
145        identity_env::carry_slug_identity_env(&mut env, "fixture-agent");
146        let mut meta = crate::backend::obj::MetaMapType::default();
147        meta.insert("cmd:cwd".into(), serde_json::json!(std::env::temp_dir().to_string_lossy()));
148        input::carry_agent_workdir_env(&mut env, &meta);
149        env.insert("AGENTMUX_AUTH_KEY".into(), "k".into());
150        env.insert("AGENTMUX_BLOCKID".into(), "b".into());
151        crate::backend::tool_store::prepend_agent_tools_path(&mut env);
152        crate::backend::gh_guard::apply_gh_guard(&mut env);
153        crate::backend::account_login_guard::strip_account_login(&mut env);
154        // What the container side adds to or does with the same map.
155        let out: HashMap<String, String> = crate::backend::container::credential::container_exec_env("scope-block", &env)
156            .into_iter()
157            .collect();
158        let mut names: BTreeSet<String> = env.keys().chain(out.keys()).filter(|k| !base.contains_key(*k)).cloned().collect();
159        // Set only in some processes (`pane_env::build_info` adds it when the process has a channel), so the test
160        // places it whether or not this one does.
161        names.insert("AGENTMUX_INSTANCE_CHANNEL".to_string());
162        names
163    }
164
165    #[test]
166    fn every_name_srv_sets_on_a_turn_has_a_scope() {
167        let base: HashMap<String, String> = [("MY_OWN_SETTING".to_string(), "1".to_string())].into();
168        let unplaced: Vec<_> = names_srv_sets(&base).into_iter().filter(|n| scope_of(n).is_none()).collect();
169        assert!(unplaced.is_empty(), "add these to AGENT_ENV in backend/agent_env_scope.rs, with a scope and a reason: {unplaced:?}");
170    }
171
172    #[test]
173    fn a_host_only_name_is_not_given_to_a_container() {
174        let env: HashMap<String, String> =
175            AGENT_ENV.iter().filter(|s| s.scope == HostOnly).map(|s| (s.name.to_string(), "host".to_string())).collect();
176        let out: HashMap<String, String> = crate::backend::container::credential::container_exec_env("scope-block", &env)
177            .into_iter()
178            .collect();
179        let leaked: Vec<_> = env.keys().filter(|k| out.contains_key(*k)).collect();
180        assert!(leaked.is_empty(), "host-only names reached a container: {leaked:?}");
181    }
182}