Skip to main content

agentmux_srv_core/backend/spawn_env/
endpoint.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! A Claude Code agent pointed at a server of its own: `ANTHROPIC_BASE_URL` in its environment names
5//! something other than Anthropic (a local model, a LAN server, a proxy; set by an agent through
6//! `Agents env_set` or by the person in My Agents).
7//!
8//! The rule, applied to every spawn after the account's credentials were put in the environment:
9//! **the person's Claude sign-in goes only to Anthropic.** Whatever the account injected (its
10//! config directory with the OAuth login, an OAuth token variable, an API key) is taken out, the
11//! CLI is given a private config directory with no sign-in in it, and its credentials are only what
12//! the agent's own environment gave it: a Vault entry the person opened to that agent, a
13//! placeholder for a server that ignores the key, or nothing (then a placeholder, so the CLI does
14//! not fall back to asking for a sign-in). Otherwise the sign-in would go to the other server, over
15//! plain HTTP for a LAN one.
16//!
17//! An agent on a model route (`model_gateway`) is not touched here: the route's own variables are put
18//! in after this step and name srv's gateway, which holds the key.
19
20use crate::backend::agent_env;
21use std::collections::HashMap;
22
23/// The key the CLI is given when the agent's environment gave none: a value, so it never asks for a
24/// sign-in, and one that is no credential.
25pub const NO_KEY_PLACEHOLDER: &str = "agentmux-no-key";
26
27/// The environment variables that carry a Claude login or key that the account puts in.
28const ACCOUNT_VARIABLES: &[&str] = &["CLAUDE_CODE_OAUTH_TOKEN", "ANTHROPIC_AUTH_TOKEN", "ANTHROPIC_API_KEY"];
29
30/// Whether `name` is one of the variables that carry the person's Claude login. The endpoint step leaves
31/// these empty, and `apply_working_dir` removes an empty one from the child command.
32pub(crate) fn is_account_variable(name: &str) -> bool {
33    ACCOUNT_VARIABLES.iter().any(|n| n.eq_ignore_ascii_case(name))
34}
35
36/// What the agent's own environment (`cmd:env`, before the account's variables) asks for.
37#[derive(Debug, Clone, PartialEq, Eq)]
38pub struct Endpoint {
39    pub base_url: String,
40    /// `ANTHROPIC_AUTH_TOKEN` as written: a `vault:<id>` reference or a placeholder.
41    pub auth_token: Option<String>,
42    /// `ANTHROPIC_API_KEY` as written.
43    pub api_key: Option<String>,
44}
45
46/// Every non-empty value written for `name`, in any spelling (a launch on Windows reads names without
47/// regard to case, so `anthropic_base_url` is the same setting), ordered by spelling so the choice is stable.
48fn values_of(env: &HashMap<String, String>, name: &str) -> Vec<String> {
49    let mut spellings: Vec<(&String, &String)> = env.iter().filter(|(k, _)| k.eq_ignore_ascii_case(name)).collect();
50    spellings.sort();
51    spellings.into_iter().map(|(_, v)| v.trim()).filter(|v| !v.is_empty()).map(str::to_string).collect()
52}
53
54fn nonempty(env: &HashMap<String, String>, name: &str) -> Option<String> {
55    values_of(env, name).into_iter().next()
56}
57
58/// The custom endpoint `own` (the agent's own environment) asks for, or `None` where it names
59/// none or names Anthropic's own API.
60pub fn requested(own: &HashMap<String, String>) -> Option<Endpoint> {
61    // Two spellings that disagree: the one that is not Anthropic's decides, so the sign-in stays home.
62    let base_url = values_of(own, "ANTHROPIC_BASE_URL").into_iter().find(|u| !agent_env::is_anthropic_url(u))?;
63    Some(Endpoint { base_url, auth_token: nonempty(own, "ANTHROPIC_AUTH_TOKEN"), api_key: nonempty(own, "ANTHROPIC_API_KEY") })
64}
65
66/// Where the CLI's private config directory is for this agent on the server at `base_url`: beside the shared
67/// one, never in it, so no sign-in is ever visible there. The address is part of the name, so a conversation
68/// belongs to the server it was held with: pointing the agent at another server (or back) gives the CLI a
69/// directory that does not hold it, and the next launch cannot resume it there (`--resume` is a lookup in
70/// this directory), where one folder per agent would send A's history to B.
71pub fn private_config_dir(shared_auth_dir: &str, agent_slug: &str, base_url: &str) -> String {
72    let safe: String = agent_slug.chars().map(|c| if c.is_ascii_alphanumeric() || c == '-' || c == '_' { c } else { '_' }).collect();
73    let shared = std::path::Path::new(shared_auth_dir);
74    let base = shared.parent().unwrap_or(shared);
75    let name = if safe.is_empty() { "agent".to_string() } else { safe };
76    base.join("claude-endpoint").join(format!("{name}-{}", address_key(base_url))).to_string_lossy().into_owned()
77}
78
79/// A short, stable key for a server address: the same server written with a different case or a trailing
80/// slash is the same key.
81fn address_key(base_url: &str) -> String {
82    let normal = base_url.trim().trim_end_matches('/').to_ascii_lowercase();
83    crate::backend::memory::record::sha256_hex(normal.as_bytes()).chars().take(8).collect()
84}
85
86/// Takes the account's login out of `env` and gives the CLI the endpoint and the keys the agent's
87/// own environment asked for. `resolve_vault` turns an entry id into its value, or `None` when the
88/// agent may not have it (the key is then left out: never a fallback to another key).
89pub fn apply(env: &mut HashMap<String, String>, endpoint: &Endpoint, config_dir: &str, resolve_vault: &dyn Fn(&str) -> Option<String>) {
90    // Every spelling of the names set below goes first, so the child never sees one name twice.
91    env.retain(|k, _| {
92        !ACCOUNT_VARIABLES.iter().chain(&["CLAUDE_CONFIG_DIR", "ANTHROPIC_BASE_URL"]).any(|n| n.eq_ignore_ascii_case(k))
93    });
94    env.insert("CLAUDE_CONFIG_DIR".to_string(), config_dir.to_string());
95    env.insert("ANTHROPIC_BASE_URL".to_string(), endpoint.base_url.clone());
96    // Left empty, not absent: the child inherits srv's own environment, which may hold the person's token, and
97    // `apply_working_dir` removes an emptied login variable from the child command.
98    env.insert("CLAUDE_CODE_OAUTH_TOKEN".to_string(), String::new());
99    let value_of = |written: &Option<String>| {
100        written.as_deref().and_then(|w| match agent_env::vault_ref(w) {
101            Some(id) => {
102                let value = resolve_vault(id);
103                // A Vault value handed to the agent's process is never written into its transcript.
104                if let Some(value) = &value {
105                    crate::backend::transcript::withhold::register(value);
106                }
107                value
108            }
109            None => Some(w.to_string()),
110        })
111    };
112    let (token, key) = (value_of(&endpoint.auth_token), value_of(&endpoint.api_key));
113    match (token, &key) {
114        (Some(token), _) => {
115            env.insert("ANTHROPIC_AUTH_TOKEN".to_string(), token);
116        }
117        // A key and no token: the CLI sends the key; a token would take its place, so it is emptied.
118        (None, Some(_)) => {
119            env.insert("ANTHROPIC_AUTH_TOKEN".to_string(), String::new());
120        }
121        (None, None) => {
122            env.insert("ANTHROPIC_AUTH_TOKEN".to_string(), NO_KEY_PLACEHOLDER.to_string());
123        }
124    }
125    // Always set, empty when the agent gave none, so no other key the account held is used.
126    env.insert("ANTHROPIC_API_KEY".to_string(), key.unwrap_or_default());
127}
128
129/// The agent a spawn is for, as the endpoint step needs it.
130struct Who {
131    id: String,
132    slug: String,
133}
134
135fn who_of(mstore: &crate::backend::storage::store::Store, block_id: &str, env: &HashMap<String, String>) -> Option<Who> {
136    let instance = mstore.instance_get_active_for_block(block_id).ok().flatten()?;
137    let def = mstore.agent_def_get(&instance.definition_id).ok().flatten()?;
138    let slug = if def.slug.is_empty() { env.get("AGENTMUX_AGENT_SLUG").cloned().unwrap_or_default() } else { def.slug };
139    Some(Who { id: def.id, slug })
140}
141
142/// Whether the pane runs the Claude Code CLI. `agentProvider` is written from the definition verbatim, so it can
143/// be a legacy alias (`claude-code`, `claude_code`): it is resolved, as the model rule does, or a Claude agent on
144/// an alias would keep the person's sign-in on a custom server. Nothing written (or only blanks) is Claude, the
145/// default a launch assumes; any other provider is not.
146fn is_claude(block_meta: &crate::backend::obj::MetaMapType) -> bool {
147    let written = crate::backend::obj::meta_get_string(block_meta, "agentProvider", "");
148    written.trim().is_empty() || crate::backend::providers::resolve_provider_alias(written.trim()) == "claude"
149}
150
151/// Whether a spawn brings its own Claude endpoint: the pane runs Claude Code and `own` (its own environment,
152/// `cmd:env`) names a model server other than Anthropic's. The spawn and the quiet recheck of a held message's
153/// gate (`server/jekt_held.rs`) both ask this, so a held message is released exactly when the spawn would pass.
154pub fn own_claude_endpoint(block_meta: &crate::backend::obj::MetaMapType, own: &HashMap<String, String>) -> bool {
155    is_claude(block_meta) && requested(own).is_some()
156}
157
158/// [`own_claude_endpoint`] for a block's own `cmd:env`, as a spawn reads it.
159pub fn own_claude_endpoint_of(block_meta: &crate::backend::obj::MetaMapType) -> bool {
160    own_claude_endpoint(block_meta, &crate::backend::blockcontroller::cmd_env_of(block_meta))
161}
162
163/// The identity step of a spawn (the account's variables over the agent's own), then this step, then the
164/// note of which account the run uses. `base_env_vars` is the agent's own environment.
165pub(crate) async fn inject_identity(
166    mstore: std::sync::Arc<crate::backend::storage::store::Store>,
167    id_store: std::sync::Arc<crate::backend::storage::store::Store>,
168    identity_store: std::sync::Arc<crate::backend::storage::store::Store>,
169    broker: Option<std::sync::Arc<crate::backend::mps::Broker>>,
170    block_meta: &crate::backend::obj::MetaMapType,
171    block_id: &str,
172    base_env_vars: HashMap<String, String>,
173) -> Result<HashMap<String, String>, crate::identity::resolver::SpawnGateError> {
174    let (own, mstore_after) = (base_env_vars.clone(), mstore.clone());
175    // The account's login is discarded for this agent below, so the identity step neither injects nor requires it.
176    let own_claude_endpoint = own_claude_endpoint(block_meta, &own);
177    let mut env_vars = crate::identity::token_warmup::inject_after_warmup(
178        mstore,
179        id_store,
180        identity_store.clone(),
181        broker,
182        block_id.to_string(),
183        base_env_vars,
184        own_claude_endpoint,
185    )
186    .await?;
187    guard(&mut env_vars, &own, block_meta, block_id, mstore_after.clone(), identity_store.clone()).await;
188    super::run_account::note_run_account(&mstore_after, &identity_store, block_id);
189    Ok(env_vars)
190}
191
192/// The endpoint step of a spawn (`build::build_persistent_spawn_env`): `own` is what the agent's own
193/// environment asked for, `env_vars` the spawn environment after the account's variables went in. A
194/// Claude Code agent that asked for a custom server has the account's login taken out and its own
195/// keys put in (`apply`). Does nothing for another harness or for Anthropic's own address.
196pub(crate) async fn guard(
197    env_vars: &mut HashMap<String, String>,
198    own: &HashMap<String, String>,
199    block_meta: &crate::backend::obj::MetaMapType,
200    block_id: &str,
201    mstore: std::sync::Arc<crate::backend::storage::store::Store>,
202    identity_store: std::sync::Arc<crate::backend::storage::store::Store>,
203) {
204    if !is_claude(block_meta) {
205        return;
206    }
207    let Some(endpoint) = requested(own) else { return };
208    let Some(provider) = crate::backend::providers::get_provider("claude") else { return };
209    let (spawn_env, block) = (env_vars.clone(), block_id.to_string());
210    let done = tokio::task::spawn_blocking(move || {
211        let mut env = spawn_env;
212        let who = who_of(&mstore, &block, &env);
213        let slug = who.as_ref().map(|w| w.slug.clone()).unwrap_or_default();
214        let shared = crate::backend::providers::default_auth_dir(provider).unwrap_or_default();
215        let dir = private_config_dir(&shared, &slug, &endpoint.base_url);
216        if let Err(e) = crate::backend::providers::prepare_provider_auth_dir(provider, &dir) {
217            tracing::warn!(block_id = %block, dir = %dir, error = %e, "endpoint: could not prepare the agent's private config directory");
218        }
219        let resolve = |entry_id: &str| -> Option<String> {
220            let who = who.as_ref()?;
221            match crate::backend::vault::endpoint_key::for_launch(&identity_store, entry_id, &who.id, &who.slug) {
222                Ok(value) => Some(value.to_string()),
223                Err(why) => {
224                    tracing::warn!(agent = %who.slug, error = %why, "endpoint: a Vault key named in the agent's environment was not put in");
225                    None
226                }
227            }
228        };
229        apply(&mut env, &endpoint, &dir, &resolve);
230        env
231    })
232    .await;
233    match done {
234        Ok(env) => *env_vars = env,
235        // The step died: the agent starts with no login at all rather than with the person's.
236        Err(e) => {
237            tracing::error!(block_id = %block_id, error = %e, "endpoint: the step failed; the agent is started without a login");
238            no_login(env_vars);
239        }
240    }
241}
242
243/// No login for the child: the account variables emptied (an absent name would be inherited from srv's
244/// own environment) and the config directory a folder with nothing in it (an absent one is the person's
245/// own `~/.claude`).
246fn no_login(env: &mut HashMap<String, String>) {
247    for name in ACCOUNT_VARIABLES {
248        env.insert((*name).to_string(), String::new());
249    }
250    env.insert("CLAUDE_CONFIG_DIR".to_string(), std::env::temp_dir().join("agentmux-no-login").to_string_lossy().into_owned());
251}
252
253#[cfg(test)]
254mod tests {
255    use super::*;
256
257    fn env(pairs: &[(&str, &str)]) -> HashMap<String, String> {
258        pairs.iter().map(|(k, v)| (k.to_string(), v.to_string())).collect()
259    }
260
261    fn account() -> HashMap<String, String> {
262        env(&[
263            ("CLAUDE_CONFIG_DIR", "C:/shared/providers/claude"),
264            ("CLAUDE_CODE_OAUTH_TOKEN", "sk-ant-oat01-PERSONS-LOGIN"),
265            ("ANTHROPIC_API_KEY", "sk-ant-api03-PERSONS-KEY"),
266            ("ANTHROPIC_AUTH_TOKEN", "persons-bearer"),
267            ("TZ", "UTC"),
268        ])
269    }
270
271    fn none(_: &str) -> Option<String> {
272        None
273    }
274
275    #[test]
276    fn anthropic_and_no_url_are_not_an_endpoint() {
277        assert_eq!(requested(&env(&[])), None);
278        assert_eq!(requested(&env(&[("ANTHROPIC_BASE_URL", "")])), None);
279        assert_eq!(requested(&env(&[("ANTHROPIC_BASE_URL", "https://api.anthropic.com")])), None);
280        assert_eq!(requested(&env(&[("ANTHROPIC_BASE_URL", "https://api.anthropic.com/v1")])), None);
281    }
282
283    #[test]
284    fn a_lan_server_a_proxy_and_a_lookalike_are_endpoints() {
285        for url in ["http://192.0.2.68:11434", "https://proxy.example.com", "https://api.anthropic.com.evil.example", "http://api.anthropic.com"] {
286            let e = requested(&env(&[("ANTHROPIC_BASE_URL", url), ("ANTHROPIC_AUTH_TOKEN", "ollama")])).unwrap();
287            assert_eq!(e.base_url, url);
288            assert_eq!(e.auth_token.as_deref(), Some("ollama"));
289        }
290    }
291
292    #[test]
293    fn the_persons_sign_in_is_not_sent_to_a_custom_server() {
294        let endpoint = requested(&env(&[("ANTHROPIC_BASE_URL", "http://192.0.2.68:11434"), ("ANTHROPIC_AUTH_TOKEN", "ollama")])).unwrap();
295        let mut spawn = account();
296        apply(&mut spawn, &endpoint, "C:/shared/providers/claude-endpoint/lolly", &none);
297        assert_eq!(spawn["CLAUDE_CONFIG_DIR"], "C:/shared/providers/claude-endpoint/lolly");
298        assert_eq!(spawn["ANTHROPIC_BASE_URL"], "http://192.0.2.68:11434");
299        assert_eq!(spawn["ANTHROPIC_AUTH_TOKEN"], "ollama");
300        assert_eq!(spawn["ANTHROPIC_API_KEY"], "", "the account's key is emptied");
301        assert_eq!(spawn["CLAUDE_CODE_OAUTH_TOKEN"], "", "emptied, so a token in srv's own environment does not reach the child");
302        assert!(!spawn.values().any(|v| v.contains("PERSONS") || v.contains("persons-bearer")), "{spawn:?}");
303        assert_eq!(spawn["TZ"], "UTC", "other variables are left alone");
304    }
305
306    #[test]
307    fn the_child_command_loses_an_emptied_login_variable_it_would_inherit() {
308        let endpoint = requested(&env(&[("ANTHROPIC_BASE_URL", "http://localhost:11434"), ("ANTHROPIC_API_KEY", "local")])).unwrap();
309        let mut spawn = account();
310        apply(&mut spawn, &endpoint, "/d", &none);
311        let mut cmd = tokio::process::Command::new("claude");
312        crate::backend::blockcontroller::core::apply_working_dir(&mut cmd, "block-1", "", &spawn);
313        let set: HashMap<String, Option<String>> = cmd
314            .as_std()
315            .get_envs()
316            .map(|(k, v)| (k.to_string_lossy().into_owned(), v.map(|v| v.to_string_lossy().into_owned())))
317            .collect();
318        // Removed from the child (None), not set to an empty string and not left to be inherited.
319        assert_eq!(set.get("CLAUDE_CODE_OAUTH_TOKEN"), Some(&None), "{set:?}");
320        assert_eq!(set.get("ANTHROPIC_AUTH_TOKEN"), Some(&None), "{set:?}");
321        // The key the endpoint gave is set; the address too.
322        assert_eq!(set.get("ANTHROPIC_API_KEY"), Some(&Some("local".to_string())));
323        assert_eq!(set.get("ANTHROPIC_BASE_URL"), Some(&Some("http://localhost:11434".to_string())));
324    }
325
326    #[test]
327    fn a_failed_step_leaves_no_login_and_nothing_to_inherit() {
328        let mut spawn = account();
329        no_login(&mut spawn);
330        for name in ACCOUNT_VARIABLES {
331            assert_eq!(spawn[*name], "", "{name}");
332        }
333        assert!(!spawn["CLAUDE_CONFIG_DIR"].contains("shared"), "{spawn:?}");
334        assert_eq!(spawn["TZ"], "UTC");
335    }
336
337    #[test]
338    fn every_account_variable_is_in_the_overlay_so_none_is_inherited_from_srv() {
339        // Whatever the account put in (or did not), the child gets an entry for each, because a name left out
340        // is inherited from srv's own environment.
341        for endpoint_env in [
342            env(&[("ANTHROPIC_BASE_URL", "http://localhost:11434")]),
343            env(&[("ANTHROPIC_BASE_URL", "http://localhost:11434"), ("ANTHROPIC_API_KEY", "local")]),
344            env(&[("ANTHROPIC_BASE_URL", "http://localhost:11434"), ("ANTHROPIC_AUTH_TOKEN", "ollama")]),
345        ] {
346            let endpoint = requested(&endpoint_env).unwrap();
347            for mut spawn in [env(&[]), account()] {
348                apply(&mut spawn, &endpoint, "/d", &none);
349                for name in ACCOUNT_VARIABLES {
350                    let value = spawn.get(*name).unwrap_or_else(|| panic!("{name} is left to be inherited: {spawn:?}"));
351                    assert!(!value.contains("PERSONS") && value != "persons-bearer", "{name}={value}");
352                }
353            }
354        }
355    }
356
357    #[test]
358    fn with_no_key_given_the_cli_gets_a_placeholder_so_it_does_not_ask_for_a_sign_in() {
359        let endpoint = requested(&env(&[("ANTHROPIC_BASE_URL", "http://localhost:11434")])).unwrap();
360        let mut spawn = account();
361        apply(&mut spawn, &endpoint, "/d", &none);
362        assert_eq!(spawn["ANTHROPIC_AUTH_TOKEN"], NO_KEY_PLACEHOLDER);
363        assert_eq!(spawn["ANTHROPIC_API_KEY"], "");
364    }
365
366    #[test]
367    fn a_name_in_any_case_is_the_same_setting_and_leaves_no_second_copy() {
368        // An environment saved from My Agents keeps the spelling it was typed in, and a Windows
369        // launch reads names without regard to case: the sign-in must stay home either way.
370        let own = env(&[("anthropic_base_url", "http://192.0.2.68:11434"), ("Anthropic_Auth_Token", "ollama")]);
371        let endpoint = requested(&own).unwrap();
372        assert_eq!((endpoint.base_url.as_str(), endpoint.auth_token.as_deref()), ("http://192.0.2.68:11434", Some("ollama")));
373        let mut spawn = account();
374        spawn.extend(own);
375        apply(&mut spawn, &endpoint, "/d", &none);
376        let spellings = |name: &str| spawn.keys().filter(|k| k.eq_ignore_ascii_case(name)).count();
377        assert_eq!((spellings("ANTHROPIC_BASE_URL"), spellings("ANTHROPIC_AUTH_TOKEN")), (1, 1), "{spawn:?}");
378        assert!(!spawn.values().any(|v| v.contains("PERSONS")), "{spawn:?}");
379    }
380
381    #[test]
382    fn a_claude_agent_is_claude_under_any_name_it_was_written_with() {
383        let meta = |provider: Option<&str>| {
384            let mut m = crate::backend::obj::MetaMapType::new();
385            if let Some(p) = provider {
386                m.insert("agentProvider".to_string(), serde_json::json!(p));
387            }
388            m
389        };
390        for claude in [None, Some(""), Some("  "), Some("claude"), Some("claude-code"), Some("claude_code")] {
391            assert!(is_claude(&meta(claude)), "{claude:?} is Claude");
392        }
393        for other in ["codex", "codex-cli", "gemini", "no-such-provider"] {
394            assert!(!is_claude(&meta(Some(other))), "{other} is not Claude");
395        }
396    }
397
398    #[test]
399    fn two_spellings_that_disagree_never_leave_the_sign_in_going_to_anthropic_by_chance() {
400        let own = env(&[("ANTHROPIC_BASE_URL", "https://api.anthropic.com"), ("anthropic_base_url", "http://192.0.2.68:11434")]);
401        for _ in 0..8 {
402            assert_eq!(requested(&own).unwrap().base_url, "http://192.0.2.68:11434");
403        }
404    }
405
406    #[test]
407    fn an_api_key_alone_is_sent_as_the_key_with_no_token_variable() {
408        let endpoint = requested(&env(&[("ANTHROPIC_BASE_URL", "http://localhost:8080"), ("ANTHROPIC_API_KEY", "local")])).unwrap();
409        let mut spawn = account();
410        apply(&mut spawn, &endpoint, "/d", &none);
411        assert_eq!(spawn["ANTHROPIC_API_KEY"], "local");
412        assert_eq!(spawn["ANTHROPIC_AUTH_TOKEN"], "", "emptied, not absent: an inherited bearer token must not override the key");
413    }
414
415    #[test]
416    fn a_vault_reference_is_replaced_by_the_entrys_value_and_a_refused_one_by_nothing() {
417        let endpoint = requested(&env(&[("ANTHROPIC_BASE_URL", "https://llm.example.com"), ("ANTHROPIC_AUTH_TOKEN", "vault:k1")])).unwrap();
418        let mut spawn = account();
419        apply(&mut spawn, &endpoint, "/d", &|id| (id == "k1").then(|| "the-real-key-withhold-canary".to_string()));
420        assert_eq!(spawn["ANTHROPIC_AUTH_TOKEN"], "the-real-key-withhold-canary");
421        // The value handed to the agent's process is never written into its transcript.
422        assert_eq!(crate::backend::transcript::withhold::text("KEY=the-real-key-withhold-canary"), "KEY=[withheld]");
423        let mut refused = account();
424        apply(&mut refused, &endpoint, "/d", &none);
425        assert_eq!(refused["ANTHROPIC_AUTH_TOKEN"], NO_KEY_PLACEHOLDER, "no value, and never the account's");
426        assert!(!refused.values().any(|v| v.contains("vault:") || v.contains("PERSONS")), "{refused:?}");
427    }
428
429    #[test]
430    fn the_private_config_directory_is_beside_the_shared_one_per_agent_and_server() {
431        // Windows joins with a backslash; the layout is what matters.
432        let dir = |shared: &str, slug: &str, url: &str| private_config_dir(shared, slug, url).replace(std::path::MAIN_SEPARATOR, "/");
433        let a = "http://192.0.2.68:11434";
434        let key = address_key(a);
435        assert_eq!(key.len(), 8);
436        assert_eq!(dir("C:/h/shared/providers/claude", "lolly", a), format!("C:/h/shared/providers/claude-endpoint/lolly-{key}"));
437        assert_eq!(dir("/h/shared/providers/claude", "../evil/x", a), format!("/h/shared/providers/claude-endpoint/___evil_x-{key}"));
438        assert_eq!(dir("/h/shared/providers/claude", "", a), format!("/h/shared/providers/claude-endpoint/agent-{key}"));
439        assert!(!dir("/h/shared/providers/claude", "lolly", a).starts_with("/h/shared/providers/claude/"));
440    }
441
442    #[test]
443    fn a_conversation_belongs_to_the_server_it_was_held_with() {
444        let shared = "/h/shared/providers/claude";
445        let (a, b) = ("http://192.0.2.68:11434", "https://proxy.example.com");
446        let dir = |slug: &str, url: &str| private_config_dir(shared, slug, url);
447        assert_ne!(dir("lolly", a), dir("lolly", b), "another server, another directory");
448        assert_eq!(dir("lolly", a), dir("lolly", a), "the same server, the same one, back from B as before");
449        assert_eq!(dir("lolly", a), dir("lolly", "HTTP://192.0.2.68:11434/"), "case and a trailing slash are not another server");
450        assert_ne!(dir("lolly", a), dir("brio", a), "two agents on one server keep their own");
451        assert_ne!(dir("lolly", "http://192.0.2.68:11434"), dir("lolly", "http://192.0.2.68:11435"), "a port is part of the address");
452    }
453
454    /// The next launch resumes by looking the session up in the spawn's config directory
455    /// (`session_backfill::session_is_reachable`): a session taken on A is not there after the agent is pointed at
456    /// B, and is not there for B's own session when it is pointed back.
457    #[test]
458    fn a_session_taken_on_one_server_cannot_be_resumed_on_another() {
459        let tmp = tempfile::tempdir().unwrap();
460        let shared = tmp.path().join("providers").join("claude");
461        let shared = shared.to_string_lossy().into_owned();
462        let (a, b) = ("http://192.0.2.68:11434", "https://proxy.example.com");
463        let work = "/work/lolly";
464        let (dir_a, dir_b) = (private_config_dir(&shared, "lolly", a), private_config_dir(&shared, "lolly", b));
465        let take = |dir: &str, sid: &str| {
466            let file = crate::backend::session_backfill::session_file_path(dir, work, sid).unwrap();
467            std::fs::create_dir_all(file.parent().unwrap()).unwrap();
468            std::fs::write(file, "{\"type\":\"user\"}\n").unwrap();
469        };
470        let reachable = |dir: &str, sid: &str| crate::backend::session_backfill::session_is_reachable(dir, work, sid);
471        take(&dir_a, "sid-a");
472        assert!(reachable(&dir_a, "sid-a"), "resumable where it was taken");
473        assert!(!reachable(&dir_b, "sid-a"), "pointed at B: the next launch does not find it");
474        take(&dir_b, "sid-b");
475        assert!(!reachable(&dir_a, "sid-b"), "and what B took is not A's");
476        assert!(!reachable(&private_config_dir(&shared, "lolly", "https://api.example.org"), "sid-a"), "a third server finds neither");
477    }
478}