Skip to main content

lean_ctx_cli/proxy_setup/
mod.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Install / uninstall LLM-client proxy environment wiring.
3//!
4//! Submodules hold per-client setup (Claude, Codex, Grok, Pi, shell). This
5//! facade keeps the public API stable as `crate::proxy_setup::*`.
6
7mod claude;
8mod codex;
9mod commandcode;
10mod grok;
11mod pi;
12mod shell;
13mod util;
14
15#[cfg(test)]
16#[path = "tests.rs"]
17mod tests;
18
19#[cfg(test)]
20#[path = "tests_codex_rail.rs"]
21mod tests_codex_rail;
22
23#[cfg(test)]
24#[path = "tests_codex_provider.rs"]
25mod tests_codex_provider;
26
27use std::path::Path;
28
29use lean_ctx::marked_block;
30
31use claude::{install_claude_env, install_claude_env_inner, uninstall_claude_env};
32use codex::{codex_config_has_local_proxy_entry, strip_codex_proxy_entries, uninstall_codex_env};
33use commandcode::{install_commandcode_env, uninstall_commandcode_env};
34use grok::{
35    grok_config_has_local_proxy_entry, install_grok_env, strip_grok_proxy_entries,
36    uninstall_grok_env,
37};
38use pi::{install_pi_env, uninstall_pi_env};
39use shell::install_shell_exports;
40use util::{PROXY_ENV_END, PROXY_ENV_START};
41
42pub use claude::anthropic_api_key_available;
43pub(crate) use claude::repair_claude_subscription_env;
44#[cfg(feature = "http-server")]
45pub(crate) use codex::CodexEnvOutcome;
46pub(crate) use codex::install_codex_env;
47pub use grok::{grok_session_auth_available, xai_api_key_available};
48pub use lean_ctx::core::proxy_endpoint::{
49    configured_proxy_live, default_port, lean_ctx_proxy_responding, proxy_timeout,
50};
51pub use util::is_local_lean_ctx_url;
52pub(crate) use util::is_proxy_reachable;
53
54pub fn install_proxy_env(home: &Path, port: u16, quiet: bool) {
55    let cfg = lean_ctx::core::config::Config::load();
56    if cfg.proxy_enabled != Some(true) {
57        if !quiet {
58            println!("  Proxy env skipped (not enabled in config)");
59        }
60        return;
61    }
62    install_shell_exports(home, port, quiet, false);
63    install_claude_env(home, port, quiet);
64    install_codex_env(home, port, quiet);
65    install_pi_env(home, port, quiet, false);
66    install_grok_env(home, port, quiet, false);
67    install_commandcode_env(home, port, quiet, false);
68}
69
70/// Install proxy env without config guard (used by `lean-ctx proxy enable` which has already set the flag).
71/// `force_endpoint`: if true, overrides even non-local custom endpoints.
72pub fn install_proxy_env_unchecked(home: &Path, port: u16, quiet: bool, force_endpoint: bool) {
73    // Shell exports and Grok install share `force_endpoint` so force+no-auth
74    // seeds grok-chat and still emits GROK_CLI_CHAT_PROXY_BASE_URL.
75    install_shell_exports(home, port, quiet, force_endpoint);
76    if force_endpoint {
77        install_claude_env_inner(home, port, quiet, true);
78    } else {
79        install_claude_env(home, port, quiet);
80    }
81    install_codex_env(home, port, quiet);
82    install_pi_env(home, port, quiet, force_endpoint);
83    install_grok_env(home, port, quiet, force_endpoint);
84    install_commandcode_env(home, port, quiet, force_endpoint);
85}
86
87pub fn preview_proxy_cleanup(home: &Path) {
88    let settings_dir = lean_ctx::core::editor_registry::claude_state_dir(home);
89    let settings_path = settings_dir.join("settings.json");
90    if let Ok(content) = std::fs::read_to_string(&settings_path)
91        && let Ok(doc) = lean_ctx::core::jsonc::parse_jsonc(&content)
92        && doc
93            .get("env")
94            .and_then(|e| e.get("ANTHROPIC_BASE_URL"))
95            .and_then(|v| v.as_str())
96            .is_some_and(is_local_lean_ctx_url)
97    {
98        let cfg = lean_ctx::core::config::Config::load();
99        if let Some(ref upstream) = cfg.proxy.anthropic_upstream {
100            println!("  Would restore ANTHROPIC_BASE_URL → {upstream} in Claude Code settings");
101        } else {
102            println!("  Would remove ANTHROPIC_BASE_URL from Claude Code settings");
103        }
104    }
105
106    let codex_path = lean_ctx::core::home::resolve_codex_config_path()
107        .unwrap_or_else(|| home.join(".codex/config.toml"));
108    if let Ok(content) = std::fs::read_to_string(codex_path)
109        && codex_config_has_local_proxy_entry(&content)
110    {
111        println!("  Would remove Codex proxy URL from config.toml");
112    }
113
114    let grok_path = home.join(".grok/config.toml");
115    if let Ok(content) = std::fs::read_to_string(grok_path)
116        && grok_config_has_local_proxy_entry(&content)
117    {
118        println!("  Would remove Grok proxy models_base_url from config.toml");
119    }
120
121    let cc_mcp = home.join(".commandcode/mcp.json");
122    if let Ok(content) = std::fs::read_to_string(cc_mcp)
123        && content.contains("lean-ctx")
124    {
125        println!("  Would remove lean-ctx from Command Code MCP (~/.commandcode/mcp.json)");
126    }
127}
128
129/// Hosts whose model traffic is routed through the local lean-ctx proxy right
130/// now (read-only). Requires the proxy to be enabled; a leftover local URL with
131/// the proxy off routes nothing and is reported as not routed.
132#[must_use]
133pub fn egress_routed_hosts(home: &Path) -> Vec<&'static str> {
134    if lean_ctx::core::config::Config::load().proxy_enabled != Some(true) {
135        return Vec::new();
136    }
137    let mut routed = Vec::new();
138    let settings_path =
139        lean_ctx::core::editor_registry::claude_state_dir(home).join("settings.json");
140    if std::fs::read_to_string(&settings_path)
141        .ok()
142        .and_then(|content| lean_ctx::core::jsonc::parse_jsonc(&content).ok())
143        .and_then(|doc| {
144            doc.get("env")
145                .and_then(|e| e.get("ANTHROPIC_BASE_URL"))
146                .and_then(|v| v.as_str())
147                .map(is_local_lean_ctx_url)
148        })
149        .unwrap_or(false)
150    {
151        routed.push("claude");
152    }
153    let codex_path = lean_ctx::core::home::resolve_codex_config_path()
154        .unwrap_or_else(|| home.join(".codex/config.toml"));
155    if std::fs::read_to_string(codex_path)
156        .is_ok_and(|content| codex_config_has_local_proxy_entry(&content))
157    {
158        routed.push("codex");
159    }
160    if std::fs::read_to_string(home.join(".grok/config.toml"))
161        .is_ok_and(|content| grok_config_has_local_proxy_entry(&content))
162    {
163        routed.push("grok");
164    }
165    routed
166}
167
168/// The [`egress_routed_hosts`] entry and the base-URL variable of an agent
169/// (by its policy agent id) whose routing can be confirmed.
170fn routable_agent(agent: &str) -> Option<(&'static str, Option<&'static str>)> {
171    match agent {
172        "claude-code" => Some(("claude", Some("ANTHROPIC_BASE_URL"))),
173        "codex" => Some(("codex", Some("OPENAI_BASE_URL"))),
174        "grok" => Some(("grok", None)),
175        _ => None,
176    }
177}
178
179/// Whether `agent` (an id from `cloud_agents::agent_id`) sends its model
180/// traffic through the LeanCTX proxy: the proxy is enabled, the agent's own
181/// config points at it ([`egress_routed_hosts`]), and `base_url_env` (the
182/// value of its base-URL variable the agent passed to this process, if any)
183/// does not point elsewhere. An agent whose routing cannot be confirmed is
184/// not routed.
185fn agent_routed(home: &Path, agent: &str, base_url_env: impl Fn(&str) -> Option<String>) -> bool {
186    let Some((host, env)) = routable_agent(agent) else {
187        return false;
188    };
189    let overridden = env
190        .and_then(base_url_env)
191        .is_some_and(|url| !url.trim().is_empty() && !is_local_lean_ctx_url(&url));
192    !overridden && cached_routed_hosts(home).contains(&host)
193}
194
195/// The files [`egress_routed_hosts`] reads for `home`: the LeanCTX config
196/// (proxy enabled) and the Claude Code, Codex and Grok configs.
197fn routing_files(home: &Path) -> Vec<std::path::PathBuf> {
198    let mut files: Vec<_> = lean_ctx::core::config::Config::path().into_iter().collect();
199    files.push(lean_ctx::core::editor_registry::claude_state_dir(home).join("settings.json"));
200    files.push(
201        lean_ctx::core::home::resolve_codex_config_path()
202            .unwrap_or_else(|| home.join(".codex/config.toml")),
203    );
204    files.push(home.join(".grok/config.toml"));
205    files
206}
207
208/// Modification time and length of each file (`None` when absent).
209type FileStamps = Vec<Option<(std::time::SystemTime, u64)>>;
210
211fn stamps(files: &[std::path::PathBuf]) -> FileStamps {
212    files
213        .iter()
214        .map(|file| {
215            let meta = std::fs::metadata(file).ok()?;
216            Some((meta.modified().ok()?, meta.len()))
217        })
218        .collect()
219}
220
221/// The last [`egress_routed_hosts`] answer, by home, files and their stamps.
222type RoutedCache = (
223    std::path::PathBuf,
224    Vec<std::path::PathBuf>,
225    FileStamps,
226    Vec<&'static str>,
227);
228static ROUTED_CACHE: std::sync::Mutex<Option<RoutedCache>> = std::sync::Mutex::new(None);
229
230/// [`egress_routed_hosts`] cached like the Cloud floor: the guarded call path
231/// asks it on every tool call under `security.require_proxy`, so the configs
232/// are read again only when one of [`routing_files`] changes (stamp: mtime
233/// and length) or the home differs.
234fn cached_routed_hosts(home: &Path) -> Vec<&'static str> {
235    let files = routing_files(home);
236    let now = stamps(&files);
237    {
238        let cache = ROUTED_CACHE
239            .lock()
240            .unwrap_or_else(std::sync::PoisonError::into_inner);
241        if let Some((h, f, s, hosts)) = cache.as_ref()
242            && h == home
243            && *f == files
244            && *s == now
245        {
246            return hosts.clone();
247        }
248    }
249    // Read outside the lock: `egress_routed_hosts` loads the config (L4), so
250    // ROUTED_CACHE stays a leaf lock (LOCK_ORDERING.md L152).
251    let hosts = egress_routed_hosts(home);
252    *ROUTED_CACHE
253        .lock()
254        .unwrap_or_else(std::sync::PoisonError::into_inner) =
255        Some((home.to_path_buf(), files, now, hosts.clone()));
256    hosts
257}
258
259/// The `security.require_proxy` probe the binary registers with the Engine
260/// (`cloud_agents::set_proxy_routing_probe`).
261pub fn agent_routed_through_proxy(agent: &str) -> bool {
262    dirs::home_dir().is_some_and(|home| agent_routed(&home, agent, |name| std::env::var(name).ok()))
263}
264
265/// Removes stale proxy URLs from Claude Code / Codex settings when the proxy is not enabled.
266/// Returns the number of stale URLs cleaned up.
267pub fn cleanup_stale_proxy_env(home: &Path) -> usize {
268    let cfg = lean_ctx::core::config::Config::load();
269    if cfg.proxy_enabled == Some(true) {
270        return 0;
271    }
272
273    let mut cleaned = 0;
274
275    let settings_dir = lean_ctx::core::editor_registry::claude_state_dir(home);
276    let settings_path = settings_dir.join("settings.json");
277    if let Ok(content) = std::fs::read_to_string(&settings_path)
278        && let Ok(mut doc) = lean_ctx::core::jsonc::parse_jsonc(&content)
279        && let Some(base_url) = doc
280            .get("env")
281            .and_then(|e| e.get("ANTHROPIC_BASE_URL"))
282            .and_then(|v| v.as_str())
283            .map(String::from)
284        && is_local_lean_ctx_url(&base_url)
285        && let Some(env_obj) = doc.get_mut("env").and_then(|e| e.as_object_mut())
286    {
287        if let Some(ref upstream) = cfg.proxy.anthropic_upstream {
288            env_obj.insert(
289                "ANTHROPIC_BASE_URL".to_string(),
290                serde_json::Value::String(upstream.clone()),
291            );
292            println!("  ✓ Restored ANTHROPIC_BASE_URL → {upstream} in Claude Code settings");
293        } else {
294            env_obj.remove("ANTHROPIC_BASE_URL");
295            if env_obj.is_empty() {
296                doc.as_object_mut().map(|o| o.remove("env"));
297            }
298            println!("  ✓ Removed stale ANTHROPIC_BASE_URL from Claude Code settings");
299        }
300        let out = serde_json::to_string_pretty(&doc).unwrap_or_default();
301        let _ = std::fs::write(&settings_path, out + "\n");
302        cleaned += 1;
303    }
304
305    let codex_path = lean_ctx::core::home::resolve_codex_config_path()
306        .unwrap_or_else(|| home.join(".codex/config.toml"));
307    if let Ok(content) = std::fs::read_to_string(&codex_path)
308        && codex_config_has_local_proxy_entry(&content)
309    {
310        let filtered = strip_codex_proxy_entries(&content);
311        let _ = std::fs::write(&codex_path, &filtered);
312        println!("  ✓ Removed stale Codex proxy URL from config.toml");
313        cleaned += 1;
314    }
315
316    let grok_path = home.join(".grok/config.toml");
317    if let Ok(content) = std::fs::read_to_string(&grok_path)
318        && grok_config_has_local_proxy_entry(&content)
319    {
320        let cleaned_toml = strip_grok_proxy_entries(&content);
321        let _ = std::fs::write(&grok_path, &cleaned_toml);
322        println!("  ✓ Removed stale Grok proxy models_base_url from config.toml");
323        cleaned += 1;
324    }
325
326    cleaned
327}
328
329pub fn has_stale_proxy_url(home: &Path) -> bool {
330    let cfg = lean_ctx::core::config::Config::load();
331    if cfg.proxy_enabled == Some(true) {
332        return false;
333    }
334
335    let settings_dir = lean_ctx::core::editor_registry::claude_state_dir(home);
336    let settings_path = settings_dir.join("settings.json");
337    let Ok(content) = std::fs::read_to_string(&settings_path) else {
338        return false;
339    };
340    let Ok(doc) = lean_ctx::core::jsonc::parse_jsonc(&content) else {
341        return false;
342    };
343
344    let base_url = doc
345        .get("env")
346        .and_then(|e| e.get("ANTHROPIC_BASE_URL"))
347        .and_then(|v| v.as_str())
348        .unwrap_or("");
349
350    is_local_lean_ctx_url(base_url)
351}
352
353pub fn uninstall_proxy_env(home: &Path, quiet: bool) {
354    for rc in &[home.join(".zshrc"), home.join(".bashrc")] {
355        let label = format!(
356            "proxy env from ~/{}",
357            rc.file_name().unwrap_or_default().to_string_lossy()
358        );
359        marked_block::remove_from_file(rc, PROXY_ENV_START, PROXY_ENV_END, quiet, &label);
360    }
361
362    let fish_config = home.join(".config/fish/config.fish");
363    if fish_config.exists() {
364        marked_block::remove_from_file(
365            &fish_config,
366            PROXY_ENV_START,
367            PROXY_ENV_END,
368            quiet,
369            "proxy env from ~/.config/fish/config.fish",
370        );
371    }
372
373    let ps_profile =
374        dirs::home_dir().map(|h| lean_ctx::shell::platform::resolve_powershell_profile_path(&h));
375    if let Some(ref ps) = ps_profile
376        && ps.exists()
377    {
378        marked_block::remove_from_file(
379            ps,
380            PROXY_ENV_START,
381            PROXY_ENV_END,
382            quiet,
383            "proxy env from PowerShell profile",
384        );
385    }
386
387    uninstall_claude_env(home, quiet);
388    uninstall_codex_env(home, quiet);
389    uninstall_pi_env(home, quiet);
390    uninstall_grok_env(home, quiet);
391    uninstall_commandcode_env(home, quiet);
392}