Skip to main content

agentmux_srv_core/backend/
agent_env.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The extra environment variables a definition launches with: the `env`
5//! content blob (`agent_content`, `content_type = "env"`), one `KEY=VALUE` per
6//! line, `#` comments and blank lines allowed. The launch reads it the way
7//! [`classify`] does (`frontend/app/view/agent/agent-model.ts`): a line that
8//! isn't a comment and has no valid `KEY=` is skipped.
9//!
10//! The operator edits the blob freely in My Agents. An agent edits it through
11//! `Agents env_set` (`server/app_api/agent_env.rs`), and these rules bound
12//! what it may write: no name AgentMux itself sets or that points a provider
13//! at another home or credential, no value that looks like a secret, and a
14//! small size. The one exception is the model endpoint of a Claude Code agent
15//! ([`ENDPOINT_NAMES`]): an agent may point another agent at a server of its own
16//! (a local model), on the terms in [`endpoint_value_problem`] and with the
17//! notice and undo window of `server/app_api/agent_env.rs`. Everything an agent reads back has the values of
18//! names it may not set hidden.
19
20use std::collections::BTreeMap;
21
22/// The `content_type` of the blob.
23pub const CONTENT_TYPE: &str = "env";
24/// The most lines (comments and blanks included) an agent may write.
25pub const MAX_LINES: usize = 64;
26/// The most bytes an agent may write.
27pub const MAX_BYTES: usize = 4096;
28/// What stands for a value an agent isn't shown.
29pub const HIDDEN: &str = "[hidden]";
30
31/// Names AgentMux sets for every agent, or that decide where its files and
32/// tools are looked up, which proxy it uses or which libraries load.
33const RESERVED_NAMES: &[&str] = &[
34    "PATH",
35    "PATHEXT",
36    "HOME",
37    "USERPROFILE",
38    "HOMEDRIVE",
39    "HOMEPATH",
40    "TMPDIR",
41    "TEMP",
42    "TMP",
43    "SHELL",
44    "COMSPEC",
45    "GH_CONFIG_DIR",
46    "CLAUDE_CONFIG_DIR",
47    "CLAUDE_CODE_SHELL_PREFIX",
48    "CODEX_HOME",
49    "NODE_OPTIONS",
50    "LD_PRELOAD",
51    "LD_LIBRARY_PATH",
52    "DYLD_INSERT_LIBRARIES",
53    "DYLD_LIBRARY_PATH",
54    "HTTP_PROXY",
55    "HTTPS_PROXY",
56    "ALL_PROXY",
57    "NO_PROXY",
58    "ANTHROPIC_API_KEY",
59    "ANTHROPIC_AUTH_TOKEN",
60    "OPENAI_API_KEY",
61    "GEMINI_API_KEY",
62    "GOOGLE_API_KEY",
63    "GITHUB_TOKEN",
64    "GH_TOKEN",
65];
66
67/// Names that run a program or load code in a tool the agent starts, or that
68/// point one at another config home, certificate store or server.
69const RESERVED_PREFIXES: &[&str] = &[
70    "LD_", "DYLD_", "PYTHON", "NODE_EXTRA", "NODE_TLS", "NODE_PATH", "NODE_REPL", "NPM_CONFIG_", "RUBY", "PERL", "BASH_", "SSH_", "SSL_",
71    "XDG_", "CARGO_", "RUSTUP_", "RUSTC", "GIT_CONFIG", "GIT_SSH", "GIT_ASKPASS", "GIT_EXEC", "GIT_PROXY", "GIT_EXTERNAL", "GIT_TEMPLATE",
72    "GIT_DIR", "GIT_WORK", "_JAVA", "JAVA_TOOL", "JDK_JAVA",
73];
74
75/// Names a shell reads and runs, whatever their prefix.
76const RESERVED_SHELL_NAMES: &[&str] = &["ENV", "BASH_ENV", "PROMPT_COMMAND", "IFS", "ZDOTDIR", "CDPATH", "PS4"];
77
78/// Name endings that point a tool at a server, proxy, certificate store or
79/// home of its own.
80const RESERVED_SUFFIXES: &[&str] =
81    &["_BASE_URL", "_API_BASE", "_URL", "_ENDPOINT", "_HOST", "_PROXY", "_CA_BUNDLE", "_CA_CERTS", "_CERT_FILE", "_CONFIG_DIR", "_HOME", "_COMMAND", "_HELPER", "_PREFIX", "_EDITOR", "_PAGER"];
82
83/// The Claude Code variables that choose the server and the model an agent talks to. An agent
84/// may set them, which is why they are spelled out here and not left to the reserved patterns
85/// (`_BASE_URL`, a credential ending): the notice, the undo window and the launch rules of
86/// `spawn_env/endpoint.rs` stand where the refusal stood. Other harnesses have no verified endpoint
87/// variable (`providers`: `base_url_env_var` is Claude's alone), so nothing else is in the list.
88pub const ENDPOINT_NAMES: &[&str] = &[
89    "ANTHROPIC_BASE_URL",
90    "ANTHROPIC_AUTH_TOKEN",
91    "ANTHROPIC_API_KEY",
92    "API_TIMEOUT_MS",
93    "ANTHROPIC_DEFAULT_OPUS_MODEL",
94    "ANTHROPIC_DEFAULT_SONNET_MODEL",
95    "ANTHROPIC_DEFAULT_HAIKU_MODEL",
96    "CLAUDE_CODE_SUBAGENT_MODEL",
97];
98
99/// Whether `name` is one of [`ENDPOINT_NAMES`] (any case).
100pub fn is_endpoint_name(name: &str) -> bool {
101    ENDPOINT_NAMES.iter().any(|n| n.eq_ignore_ascii_case(name))
102}
103
104/// The prefix of a value that names a Vault entry: `vault:<entry id>`.
105pub const VAULT_REF_PREFIX: &str = "vault:";
106
107/// The Vault entry id in `value`, if it is a reference to one.
108pub fn vault_ref(value: &str) -> Option<&str> {
109    value.strip_prefix(VAULT_REF_PREFIX).map(str::trim).filter(|id| !id.is_empty())
110}
111
112/// What an agent may write for a key a server ignores. A fixed list, not a shape: any shape that fits
113/// a placeholder also fits a short real key.
114const PLACEHOLDERS: &[&str] =
115    &["ollama", "lm-studio", "lmstudio", "llamacpp", "vllm", "local", "none", "dummy", "placeholder", "unused", "not-needed", "no-key"];
116
117pub fn is_placeholder(value: &str) -> bool {
118    PLACEHOLDERS.iter().any(|p| p.eq_ignore_ascii_case(value))
119}
120
121/// Why `value` is not acceptable for the endpoint variable `name`, if it is not. A server address is
122/// plain `http(s)://host[:port][/path]`: no sign-in in it, no query, no fragment. A key is a reference
123/// to a Vault entry (`vault:<id>`; whether the agent may use that entry is the caller's to check) or
124/// one of a few placeholder words for a server that ignores it (Ollama's "ollama"); a real secret is never
125/// stored in the environment, where every agent that can read it would see it. The rest are
126/// numbers and model names.
127pub fn endpoint_value_problem(name: &str, value: &str) -> Option<String> {
128    let upper = name.to_ascii_uppercase();
129    match upper.as_str() {
130        "ANTHROPIC_BASE_URL" => endpoint_url_problem(value).map(|why| format!("{name}: {why}")),
131        "ANTHROPIC_AUTH_TOKEN" | "ANTHROPIC_API_KEY" => {
132            if vault_ref(value).is_some() || is_placeholder(value) {
133                None
134            } else if value.starts_with(VAULT_REF_PREFIX) {
135                Some(format!("{name}: vault: needs the entry's id after it"))
136            } else {
137                Some(format!(
138                    "{name}: give vault:<entry id> for a key kept in the Vault, or one of {} for a server that ignores it; a key is never written here",
139                    PLACEHOLDERS.join(", ")
140                ))
141            }
142        }
143        "API_TIMEOUT_MS" => (!value.chars().all(|c| c.is_ascii_digit()) || value.is_empty() || value.len() > 9)
144            .then(|| format!("{name}: a number of milliseconds")),
145        _ => (value.trim().is_empty() || value.len() > 200 || value.chars().any(char::is_whitespace))
146            .then(|| format!("{name}: a model name, with no spaces")),
147    }
148}
149
150/// Why `value` is not a server address an agent may point another agent at.
151fn endpoint_url_problem(value: &str) -> Option<String> {
152    let rest = value.strip_prefix("https://").or_else(|| value.strip_prefix("http://"));
153    let Some(rest) = rest else {
154        return Some("an address is http:// or https://, then the host".to_string());
155    };
156    let authority = rest.split(['/', '?', '#']).next().unwrap_or("");
157    if authority.is_empty() || authority.contains('@') {
158        return Some("an address has a host and no sign-in in it (no user:password@)".to_string());
159    }
160    if rest.contains('?') || rest.contains('#') {
161        return Some("an address has no query or fragment".to_string());
162    }
163    if !authority.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '-' | ':' | '[' | ']')) {
164        return Some("the host is letters, digits, dots and dashes, with an optional :port".to_string());
165    }
166    None
167}
168
169/// Whether `url` (a `ANTHROPIC_BASE_URL` value) is Anthropic's own API: the one place a person's Claude
170/// sign-in may go. Anything else, a LAN server, a proxy or another vendor, is not.
171pub fn is_anthropic_url(url: &str) -> bool {
172    let Some(rest) = url.trim().strip_prefix("https://") else { return false };
173    // Sign-in, query or fragment: not the address Anthropic gives, so not trusted with the person's sign-in.
174    if rest.contains(['@', '?', '#']) {
175        return false;
176    }
177    let authority = rest.split('/').next().unwrap_or("");
178    let (host, port) = authority.split_once(':').map_or((authority, None), |(h, p)| (h, Some(p)));
179    host.eq_ignore_ascii_case("api.anthropic.com") && port.is_none_or(|p| p == "443")
180}
181
182/// What an agent may set, each name spelled out: the settings that tune a
183/// provider CLI's context, output, timeouts and telemetry, and a few ordinary
184/// ones. A prefix would let through names that choose which program runs or
185/// which provider is used, so there is none. Any other name is the operator's
186/// to set in My Agents, because an agent's variables apply to another agent's
187/// launches and a list of what is dangerous is never complete. The reserved
188/// rules above still apply to these.
189const ALLOWED_NAMES: &[&str] = &[
190    "CLAUDE_CODE_AUTO_COMPACT_WINDOW",
191    "CLAUDE_AUTOCOMPACT_PCT_OVERRIDE",
192    "CLAUDE_CODE_MAX_OUTPUT_TOKENS",
193    "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC",
194    "DISABLE_TELEMETRY",
195    "DISABLE_ERROR_REPORTING",
196    "DISABLE_AUTOUPDATER",
197    "DISABLE_COST_WARNINGS",
198    "MAX_THINKING_TOKENS",
199    "MAX_MCP_OUTPUT_TOKENS",
200    "MCP_TIMEOUT",
201    "MCP_TOOL_TIMEOUT",
202    "ANTHROPIC_MODEL",
203    "ANTHROPIC_SMALL_FAST_MODEL",
204    "RUST_LOG",
205    "RUST_BACKTRACE",
206    "NO_COLOR",
207    "FORCE_COLOR",
208    "TZ",
209    "LANG",
210    "LC_ALL",
211];
212
213/// Name endings that mark a credential. An ending, not a substring: a
214/// setting such as `CLAUDE_CODE_MAX_OUTPUT_TOKENS` is not one.
215const CREDENTIAL_SUFFIXES: &[&str] = &["_KEY", "_TOKEN", "_SECRET", "_PASSWORD", "_PASSWD", "_CREDENTIAL", "_CREDENTIALS"];
216
217/// How one line reads at launch.
218#[derive(Debug, PartialEq, Eq)]
219pub enum Line<'a> {
220    Blank,
221    Comment,
222    Pair { key: &'a str, value: &'a str },
223    /// Not blank, not a comment, and no valid `KEY=`: skipped at launch.
224    Ignored,
225}
226
227/// How the launch reads `raw`: trimmed, `#` starts a comment, the key is
228/// everything before the first `=` and must be a valid name (not trimmed, so
229/// `KEY = v` is skipped), the value everything after it.
230pub fn classify(raw: &str) -> Line<'_> {
231    let line = raw.trim();
232    if line.is_empty() {
233        return Line::Blank;
234    }
235    if line.starts_with('#') {
236        return Line::Comment;
237    }
238    match line.find('=') {
239        Some(at) if at >= 1 && is_valid_name(&line[..at]) => Line::Pair { key: &line[..at], value: &line[at + 1..] },
240        _ => Line::Ignored,
241    }
242}
243
244/// `^[a-zA-Z_][a-zA-Z0-9_]*$`.
245pub fn is_valid_name(name: &str) -> bool {
246    let mut chars = name.chars();
247    chars.next().is_some_and(|c| c.is_ascii_alphabetic() || c == '_') && chars.all(|c| c.is_ascii_alphanumeric() || c == '_')
248}
249
250/// The variables the launch ends up with: a name given twice has its last value.
251pub fn effective(text: &str) -> BTreeMap<String, String> {
252    text.lines()
253        .filter_map(|l| match classify(l) {
254            Line::Pair { key, value } => Some((key.to_string(), value.to_string())),
255            _ => None,
256        })
257        .collect()
258}
259
260/// Whether `name` looks like it holds a credential.
261pub fn is_credential_name(name: &str) -> bool {
262    let upper = name.to_ascii_uppercase();
263    matches!(upper.as_str(), "TOKEN" | "SECRET" | "PASSWORD" | "APIKEY") || CREDENTIAL_SUFFIXES.iter().any(|s| upper.ends_with(s))
264}
265
266/// Names the providers use for their config homes, endpoints and the
267/// variables they are launched without, which an agent mustn't change.
268fn provider_names() -> impl Iterator<Item = String> {
269    crate::backend::providers::all_providers().flat_map(|p| {
270        std::iter::once(p.auth_config_dir_env_var.to_string())
271            .chain(p.base_url_env_var.map(str::to_string))
272            .chain(p.auth_extra_env.iter().map(|(k, _)| k.to_string()))
273            .chain(p.unset_env.iter().map(|k| k.to_string()))
274    })
275}
276
277/// Why an agent may not set or remove `name`, if it may not. A pattern, not
278/// a list of names: a variable that runs code or redirects traffic in the
279/// tools another agent launches is refused whatever it is called.
280pub fn name_problem(name: &str) -> Option<String> {
281    if !is_valid_name(name) {
282        return Some(format!("{name}: a name is letters, digits and underscores, not starting with a digit"));
283    }
284    let upper = name.to_ascii_uppercase();
285    if upper.starts_with("AGENTMUX_") {
286        return Some(format!("{name}: names starting AGENTMUX_ are reserved for AgentMux"));
287    }
288    if is_endpoint_name(&upper) {
289        // One spelling: a launch on Windows reads names without regard to case, and a second spelling would be a second way to write the same setting.
290        return (name != upper).then(|| format!("{name}: write this one as {upper}"));
291    }
292    let reserved = RESERVED_NAMES.contains(&upper.as_str())
293        || RESERVED_SHELL_NAMES.contains(&upper.as_str())
294        || RESERVED_PREFIXES.iter().any(|p| upper.starts_with(p))
295        || RESERVED_SUFFIXES.iter().any(|x| upper.ends_with(x));
296    if reserved || provider_names().any(|n| n.eq_ignore_ascii_case(name)) {
297        return Some(format!("{name}: AgentMux sets this one itself, or it decides where an agent's tools, credentials or traffic go"));
298    }
299    if is_credential_name(name) {
300        return Some(format!("{name}: looks like a credential; the operator sets those in My Agents"));
301    }
302    if !ALLOWED_NAMES.contains(&upper.as_str()) {
303        return Some(format!("{name}: an agent may set only {}; the operator sets any other in My Agents", ALLOWED_NAMES.join(", ")));
304    }
305    None
306}
307
308/// Whether `value` has the shape of a secret (a token with a known prefix, a
309/// private key, a JWT, ...).
310pub fn looks_like_secret(value: &str) -> bool {
311    agentmux_common::redact::redact_secrets(value) != value
312}
313
314/// Why an agent may not give a variable `value`, if it may not.
315pub fn value_problem(name: &str, value: &str) -> Option<String> {
316    if value == HIDDEN {
317        return Some(format!("{name}: {HIDDEN} stands for a value you aren't shown; use set and unset to change other variables"));
318    }
319    if value.chars().any(|c| c.is_control() && c != '\t') {
320        return Some(format!("{name}: a value is one line of plain text"));
321    }
322    if is_endpoint_name(name) {
323        return endpoint_value_problem(name, value);
324    }
325    if looks_like_secret(value) {
326        return Some(format!("{name}: the value looks like a secret; values here are plain text, so keep secrets in the Vault"));
327    }
328    None
329}
330
331/// `text` within the size an agent may write.
332pub fn check_size(text: &str) -> Result<(), String> {
333    if text.len() > MAX_BYTES {
334        return Err(format!("the environment is {} bytes; at most {MAX_BYTES}", text.len()));
335    }
336    let lines = text.lines().count();
337    if lines > MAX_LINES {
338        return Err(format!("the environment is {lines} lines; at most {MAX_LINES}"));
339    }
340    Ok(())
341}
342
343/// What an agent is shown for a line it may not read: a comment or a skipped
344/// line standing where it can't be told apart from a secret.
345const HIDDEN_LINE: &str = "# [hidden]";
346
347/// Whether an agent is shown `raw` as `[hidden]`: a value it may not read, a
348/// skipped line (a mistyped `NAME = value`), or a comment that holds a `=` or
349/// `:` or a secret, since a commented-out credential is still one.
350fn is_hidden_line(raw: &str) -> bool {
351    match classify(raw) {
352        Line::Blank => false,
353        Line::Comment => raw.contains('=') || raw.contains(':') || looks_like_secret(raw),
354        Line::Ignored => true,
355        Line::Pair { key, value } => shown(key, value) == HIDDEN,
356    }
357}
358
359/// The name of a line an agent can neither read nor write: its name is one an
360/// agent may not set, or it is shown to an agent as hidden. A hidden comment
361/// or skipped line has the name "".
362fn is_kept_line(raw: &str) -> Option<&str> {
363    match classify(raw) {
364        Line::Pair { key, .. } if name_problem(key).is_some() || is_hidden_line(raw) => Some(key),
365        Line::Comment | Line::Ignored if is_hidden_line(raw) => Some(""),
366        _ => None,
367    }
368}
369
370/// The text an agent proposes as the whole environment (`lines`), with the
371/// lines it can't write kept. It is within the size, and every line is a
372/// comment, a blank or a `KEY=VALUE` it may write; a line that would be
373/// skipped at launch is refused rather than kept silently. A name in
374/// `current` that the agent may not write (a credential, a reserved name, a
375/// hidden value) stays as the operator wrote it: where the agent kept
376/// the line as `env_get` showed it (`NAME=[hidden]`, or unchanged), the
377/// operator's line goes back in that place, and one the agent left out goes at the end.
378pub fn resolve_lines(current: &str, text: &str) -> Result<String, String> {
379    check_size(text)?;
380    let mut kept: Vec<(&str, &str, bool)> = current.lines().filter_map(|raw| is_kept_line(raw).map(|key| (key, raw, false))).collect();
381    let mut out: Vec<&str> = Vec::new();
382    for (i, raw) in text.lines().enumerate() {
383        match classify(raw) {
384            Line::Blank => out.push(raw),
385            Line::Comment => {
386                let operators = if raw.trim() == HIDDEN_LINE { kept.iter_mut().find(|(k, _, used)| k.is_empty() && !*used) } else { None };
387                if let Some((_, original, used)) = operators {
388                    *used = true;
389                    out.push(original);
390                } else {
391                    out.push(raw);
392                }
393            }
394            Line::Ignored => return Err(format!("line {}: not a comment and not KEY=VALUE, so it would be ignored", i + 1)),
395            Line::Pair { key, value } => {
396                let operators = kept.iter_mut().find(|(k, original, used)| *k == key && !*used && (value == HIDDEN || original.trim() == raw.trim()));
397                if let Some((_, original, used)) = operators {
398                    *used = true;
399                    out.push(original);
400                } else if let Some(why) = name_problem(key).or_else(|| value_problem(key, value)) {
401                    return Err(format!("line {}: {why}", i + 1));
402                } else {
403                    // A value of its own for a name the operator's line also holds (one shown
404                    // as `[hidden]` because it looks like a secret): the agent's value
405                    // replaces it, so it is the last and not shadowed by a line kept at the end.
406                    if let Some((_, _, used)) = kept.iter_mut().find(|(k, _, used)| *k == key && !*used) {
407                        *used = true;
408                    }
409                    out.push(raw);
410                }
411            }
412        }
413    }
414    out.extend(kept.iter().filter(|(_, _, used)| !used).map(|(_, raw, _)| *raw));
415    let mut joined = out.join("\n");
416    if !joined.is_empty() && text.ends_with('\n') {
417        joined.push('\n');
418    }
419    Ok(joined)
420}
421
422/// `current` with `set` applied and `unset` removed, every other line (and
423/// comment) as it was. A name already there has its value replaced where it
424/// stands, a new one goes at the end.
425pub fn edit(current: &str, set: &BTreeMap<String, String>, unset: &[String]) -> Result<String, String> {
426    for (name, value) in set {
427        if let Some(why) = name_problem(name).or_else(|| value_problem(name, value)) {
428            return Err(why);
429        }
430    }
431    for name in unset {
432        if let Some(why) = name_problem(name) {
433            return Err(why);
434        }
435    }
436    let trailing_newline = current.is_empty() || current.ends_with('\n');
437    let mut seen: Vec<&str> = Vec::new();
438    let mut out: Vec<String> = Vec::new();
439    for raw in current.lines() {
440        match classify(raw) {
441            Line::Pair { key, .. } if unset.iter().any(|n| n == key) => {}
442            Line::Pair { key, .. } if set.contains_key(key) => {
443                seen.push(key);
444                out.push(format!("{key}={}", set[key]));
445            }
446            _ => out.push(raw.to_string()),
447        }
448    }
449    for (name, value) in set {
450        if !seen.contains(&name.as_str()) {
451            out.push(format!("{name}={value}"));
452        }
453    }
454    let mut text = out.join("\n");
455    if !text.is_empty() && trailing_newline {
456        text.push('\n');
457    }
458    Ok(text)
459}
460
461/// What an edit did, by name. Values of credential-looking names are `HIDDEN`.
462#[derive(Debug, Default, PartialEq, Eq, serde::Serialize)]
463pub struct Change {
464    pub added: BTreeMap<String, String>,
465    pub changed: BTreeMap<String, ValueChange>,
466    pub removed: Vec<String>,
467}
468
469#[derive(Debug, PartialEq, Eq, serde::Serialize)]
470pub struct ValueChange {
471    pub from: String,
472    pub to: String,
473}
474
475impl Change {
476    /// Whether the change adds, changes or removes one of [`ENDPOINT_NAMES`], `ANTHROPIC_MODEL` or
477    /// `ANTHROPIC_SMALL_FAST_MODEL`: where the agent's traffic goes, or what it asks for there.
478    pub fn touches_endpoint(&self) -> bool {
479        let named = |n: &String| is_endpoint_name(n) || n.eq_ignore_ascii_case("ANTHROPIC_MODEL") || n.eq_ignore_ascii_case("ANTHROPIC_SMALL_FAST_MODEL");
480        self.added.keys().chain(self.changed.keys()).chain(self.removed.iter()).any(named)
481    }
482
483    /// Whether the change adds or changes one of [`ENDPOINT_NAMES`]: the settings that need a server
484    /// the agent can reach. Removing one, or any change to `ANTHROPIC_MODEL`, is not.
485    pub fn sets_endpoint(&self) -> bool {
486        self.added.keys().chain(self.changed.keys()).any(|n| is_endpoint_name(n))
487    }
488
489    /// Whether the change adds or changes `ANTHROPIC_MODEL`.
490    pub fn sets_model_name(&self) -> bool {
491        self.added.keys().chain(self.changed.keys()).any(|n| n.eq_ignore_ascii_case("ANTHROPIC_MODEL"))
492    }
493
494    pub fn is_empty(&self) -> bool {
495        self.added.is_empty() && self.changed.is_empty() && self.removed.is_empty()
496    }
497
498    /// The names and what happened to each, never a value: for the audit entry.
499    pub fn summary(&self) -> String {
500        let names = |keys: Vec<&String>| keys.into_iter().cloned().collect::<Vec<_>>().join(",");
501        format!(
502            "added [{}] changed [{}] removed [{}]",
503            names(self.added.keys().collect()),
504            names(self.changed.keys().collect()),
505            self.removed.join(",")
506        )
507    }
508}
509
510/// What a value is shown as to an agent: only the value of a name an agent may
511/// set, and not one that looks like a secret. Anything else is the operator's,
512/// and a secret can sit under a name no pattern recognises (`PGPASSWORD`,
513/// `DB_PASS`), so the name decides, not a guess at what the value is.
514fn shown(name: &str, value: &str) -> String {
515    let upper = name.to_ascii_uppercase();
516    let readable = (ALLOWED_NAMES.contains(&upper.as_str()) || is_endpoint_name(&upper)) && !is_credential_name(name) && !looks_like_secret(value);
517    if readable { value.to_string() } else { HIDDEN.to_string() }
518}
519
520/// What changed in the variables the launch gets from `old` to `new`.
521pub fn diff(old: &str, new: &str) -> Change {
522    let (old, new) = (effective(old), effective(new));
523    let mut change = Change::default();
524    for (name, value) in &new {
525        match old.get(name) {
526            None => {
527                change.added.insert(name.clone(), shown(name, value));
528            }
529            Some(before) if before != value => {
530                change.changed.insert(name.clone(), ValueChange { from: shown(name, before), to: shown(name, value) });
531            }
532            Some(_) => {}
533        }
534    }
535    change.removed = old.keys().filter(|n| !new.contains_key(*n)).cloned().collect();
536    change
537}
538
539/// Whether the environment in `text` points the agent at a server of its own: an `ANTHROPIC_BASE_URL` that is not
540/// Anthropic's. Only then does the launch ask for the model `ANTHROPIC_MODEL` names (`endpoint_model`); anywhere else it
541/// passes the model its pane's runtime chose, which that variable cannot change.
542pub fn points_at_own_server(text: &str) -> bool {
543    effective(text).iter().any(|(k, v)| k.eq_ignore_ascii_case("ANTHROPIC_BASE_URL") && !v.trim().is_empty() && !is_anthropic_url(v.trim()))
544}
545
546/// [`points_at_own_server`] for an agent with a definition: the launch puts its structured `model_vendor_base_url`
547/// into the environment first, and it wins over an `ANTHROPIC_BASE_URL` line of the text, so a set one decides alone.
548pub fn points_at_own_server_with(text: &str, structured_base_url: &str) -> bool {
549    match structured_base_url.trim() {
550        "" => points_at_own_server(text),
551        url => !is_anthropic_url(url),
552    }
553}
554
555/// `text` as an agent is shown it: the values of names it may not set hidden,
556/// a comment that may hold a secret and a skipped line as `# [hidden]`, every
557/// other line as written.
558pub fn redacted(text: &str) -> String {
559    let mut out: Vec<String> = text
560        .lines()
561        .map(|raw| match classify(raw) {
562            Line::Pair { key, .. } if is_hidden_line(raw) => format!("{key}={HIDDEN}"),
563            Line::Comment | Line::Ignored if is_hidden_line(raw) => HIDDEN_LINE.to_string(),
564            _ => raw.to_string(),
565        })
566        .collect();
567    if text.ends_with('\n') {
568        out.push(String::new());
569    }
570    out.join("\n")
571}
572
573#[cfg(test)]
574#[path = "agent_env_tests.rs"]
575mod tests;