Skip to main content

lean_ctx/proxy_setup/
mod.rs

1//! Install / uninstall LLM-client proxy environment wiring.
2//!
3//! Submodules hold per-client setup (Claude, Codex, Grok, Pi, shell). This
4//! facade keeps the public API stable as `crate::proxy_setup::*`.
5
6mod claude;
7mod codex;
8mod commandcode;
9mod grok;
10mod pi;
11mod shell;
12mod util;
13
14#[cfg(test)]
15#[path = "tests.rs"]
16mod tests;
17
18#[cfg(test)]
19#[path = "tests_codex_rail.rs"]
20mod tests_codex_rail;
21
22#[cfg(test)]
23#[path = "tests_codex_provider.rs"]
24mod tests_codex_provider;
25
26use std::path::Path;
27
28use crate::marked_block;
29
30use claude::{install_claude_env, install_claude_env_inner, uninstall_claude_env};
31use codex::{codex_config_has_local_proxy_entry, strip_codex_proxy_entries, uninstall_codex_env};
32use commandcode::{install_commandcode_env, uninstall_commandcode_env};
33use grok::{
34    grok_config_has_local_proxy_entry, install_grok_env, strip_grok_proxy_entries,
35    uninstall_grok_env,
36};
37use pi::{install_pi_env, uninstall_pi_env};
38use shell::install_shell_exports;
39use util::{PROXY_ENV_END, PROXY_ENV_START};
40
41pub use claude::anthropic_api_key_available;
42pub(crate) use claude::repair_claude_subscription_env;
43pub(crate) use codex::{CodexEnvOutcome, install_codex_env};
44pub(crate) use commandcode::COMMANDCODE_MCP_INSTRUCTIONS;
45pub use grok::{grok_session_auth_available, xai_api_key_available};
46pub(crate) use util::is_proxy_reachable;
47pub use util::{default_port, is_local_lean_ctx_url, proxy_timeout};
48
49pub fn install_proxy_env(home: &Path, port: u16, quiet: bool) {
50    let cfg = crate::core::config::Config::load();
51    if cfg.proxy_enabled != Some(true) {
52        if !quiet {
53            println!("  Proxy env skipped (not enabled in config)");
54        }
55        return;
56    }
57    install_shell_exports(home, port, quiet, false);
58    install_claude_env(home, port, quiet);
59    install_codex_env(home, port, quiet);
60    install_pi_env(home, port, quiet, false);
61    install_grok_env(home, port, quiet, false);
62    install_commandcode_env(home, port, quiet, false);
63}
64
65/// Install proxy env without config guard (used by `lean-ctx proxy enable` which has already set the flag).
66/// `force_endpoint`: if true, overrides even non-local custom endpoints.
67pub fn install_proxy_env_unchecked(home: &Path, port: u16, quiet: bool, force_endpoint: bool) {
68    // Shell exports and Grok install share `force_endpoint` so force+no-auth
69    // seeds grok-chat and still emits GROK_CLI_CHAT_PROXY_BASE_URL.
70    install_shell_exports(home, port, quiet, force_endpoint);
71    if force_endpoint {
72        install_claude_env_inner(home, port, quiet, true);
73    } else {
74        install_claude_env(home, port, quiet);
75    }
76    install_codex_env(home, port, quiet);
77    install_pi_env(home, port, quiet, force_endpoint);
78    install_grok_env(home, port, quiet, force_endpoint);
79    install_commandcode_env(home, port, quiet, force_endpoint);
80}
81
82pub fn preview_proxy_cleanup(home: &Path) {
83    let settings_dir = crate::core::editor_registry::claude_state_dir(home);
84    let settings_path = settings_dir.join("settings.json");
85    if let Ok(content) = std::fs::read_to_string(&settings_path)
86        && let Ok(doc) = crate::core::jsonc::parse_jsonc(&content)
87        && doc
88            .get("env")
89            .and_then(|e| e.get("ANTHROPIC_BASE_URL"))
90            .and_then(|v| v.as_str())
91            .is_some_and(is_local_lean_ctx_url)
92    {
93        let cfg = crate::core::config::Config::load();
94        if let Some(ref upstream) = cfg.proxy.anthropic_upstream {
95            println!("  Would restore ANTHROPIC_BASE_URL → {upstream} in Claude Code settings");
96        } else {
97            println!("  Would remove ANTHROPIC_BASE_URL from Claude Code settings");
98        }
99    }
100
101    let codex_path = crate::core::home::resolve_codex_config_path()
102        .unwrap_or_else(|| home.join(".codex/config.toml"));
103    if let Ok(content) = std::fs::read_to_string(codex_path)
104        && codex_config_has_local_proxy_entry(&content)
105    {
106        println!("  Would remove Codex proxy URL from config.toml");
107    }
108
109    let grok_path = home.join(".grok/config.toml");
110    if let Ok(content) = std::fs::read_to_string(grok_path)
111        && grok_config_has_local_proxy_entry(&content)
112    {
113        println!("  Would remove Grok proxy models_base_url from config.toml");
114    }
115
116    let cc_mcp = home.join(".commandcode/mcp.json");
117    if let Ok(content) = std::fs::read_to_string(cc_mcp)
118        && content.contains("lean-ctx")
119    {
120        println!("  Would remove lean-ctx from Command Code MCP (~/.commandcode/mcp.json)");
121    }
122}
123
124/// Hosts whose model traffic is routed through the local lean-ctx proxy right
125/// now (read-only). Requires the proxy to be enabled; a leftover local URL with
126/// the proxy off routes nothing and is reported as not routed.
127#[must_use]
128pub fn egress_routed_hosts(home: &Path) -> Vec<&'static str> {
129    if crate::core::config::Config::load().proxy_enabled != Some(true) {
130        return Vec::new();
131    }
132    let mut routed = Vec::new();
133    let settings_path = crate::core::editor_registry::claude_state_dir(home).join("settings.json");
134    if std::fs::read_to_string(&settings_path)
135        .ok()
136        .and_then(|content| crate::core::jsonc::parse_jsonc(&content).ok())
137        .and_then(|doc| {
138            doc.get("env")
139                .and_then(|e| e.get("ANTHROPIC_BASE_URL"))
140                .and_then(|v| v.as_str())
141                .map(is_local_lean_ctx_url)
142        })
143        .unwrap_or(false)
144    {
145        routed.push("claude");
146    }
147    let codex_path = crate::core::home::resolve_codex_config_path()
148        .unwrap_or_else(|| home.join(".codex/config.toml"));
149    if std::fs::read_to_string(codex_path)
150        .is_ok_and(|content| codex_config_has_local_proxy_entry(&content))
151    {
152        routed.push("codex");
153    }
154    if std::fs::read_to_string(home.join(".grok/config.toml"))
155        .is_ok_and(|content| grok_config_has_local_proxy_entry(&content))
156    {
157        routed.push("grok");
158    }
159    routed
160}
161
162/// Removes stale proxy URLs from Claude Code / Codex settings when the proxy is not enabled.
163/// Returns the number of stale URLs cleaned up.
164pub fn cleanup_stale_proxy_env(home: &Path) -> usize {
165    let cfg = crate::core::config::Config::load();
166    if cfg.proxy_enabled == Some(true) {
167        return 0;
168    }
169
170    let mut cleaned = 0;
171
172    let settings_dir = crate::core::editor_registry::claude_state_dir(home);
173    let settings_path = settings_dir.join("settings.json");
174    if let Ok(content) = std::fs::read_to_string(&settings_path)
175        && let Ok(mut doc) = crate::core::jsonc::parse_jsonc(&content)
176        && let Some(base_url) = doc
177            .get("env")
178            .and_then(|e| e.get("ANTHROPIC_BASE_URL"))
179            .and_then(|v| v.as_str())
180            .map(String::from)
181        && is_local_lean_ctx_url(&base_url)
182        && let Some(env_obj) = doc.get_mut("env").and_then(|e| e.as_object_mut())
183    {
184        if let Some(ref upstream) = cfg.proxy.anthropic_upstream {
185            env_obj.insert(
186                "ANTHROPIC_BASE_URL".to_string(),
187                serde_json::Value::String(upstream.clone()),
188            );
189            println!("  ✓ Restored ANTHROPIC_BASE_URL → {upstream} in Claude Code settings");
190        } else {
191            env_obj.remove("ANTHROPIC_BASE_URL");
192            if env_obj.is_empty() {
193                doc.as_object_mut().map(|o| o.remove("env"));
194            }
195            println!("  ✓ Removed stale ANTHROPIC_BASE_URL from Claude Code settings");
196        }
197        let out = serde_json::to_string_pretty(&doc).unwrap_or_default();
198        let _ = std::fs::write(&settings_path, out + "\n");
199        cleaned += 1;
200    }
201
202    let codex_path = crate::core::home::resolve_codex_config_path()
203        .unwrap_or_else(|| home.join(".codex/config.toml"));
204    if let Ok(content) = std::fs::read_to_string(&codex_path)
205        && codex_config_has_local_proxy_entry(&content)
206    {
207        let filtered = strip_codex_proxy_entries(&content);
208        let _ = std::fs::write(&codex_path, &filtered);
209        println!("  ✓ Removed stale Codex proxy URL from config.toml");
210        cleaned += 1;
211    }
212
213    let grok_path = home.join(".grok/config.toml");
214    if let Ok(content) = std::fs::read_to_string(&grok_path)
215        && grok_config_has_local_proxy_entry(&content)
216    {
217        let cleaned_toml = strip_grok_proxy_entries(&content);
218        let _ = std::fs::write(&grok_path, &cleaned_toml);
219        println!("  ✓ Removed stale Grok proxy models_base_url from config.toml");
220        cleaned += 1;
221    }
222
223    cleaned
224}
225
226pub fn has_stale_proxy_url(home: &Path) -> bool {
227    let cfg = crate::core::config::Config::load();
228    if cfg.proxy_enabled == Some(true) {
229        return false;
230    }
231
232    let settings_dir = crate::core::editor_registry::claude_state_dir(home);
233    let settings_path = settings_dir.join("settings.json");
234    let Ok(content) = std::fs::read_to_string(&settings_path) else {
235        return false;
236    };
237    let Ok(doc) = crate::core::jsonc::parse_jsonc(&content) else {
238        return false;
239    };
240
241    let base_url = doc
242        .get("env")
243        .and_then(|e| e.get("ANTHROPIC_BASE_URL"))
244        .and_then(|v| v.as_str())
245        .unwrap_or("");
246
247    is_local_lean_ctx_url(base_url)
248}
249
250pub fn uninstall_proxy_env(home: &Path, quiet: bool) {
251    for rc in &[home.join(".zshrc"), home.join(".bashrc")] {
252        let label = format!(
253            "proxy env from ~/{}",
254            rc.file_name().unwrap_or_default().to_string_lossy()
255        );
256        marked_block::remove_from_file(rc, PROXY_ENV_START, PROXY_ENV_END, quiet, &label);
257    }
258
259    let fish_config = home.join(".config/fish/config.fish");
260    if fish_config.exists() {
261        marked_block::remove_from_file(
262            &fish_config,
263            PROXY_ENV_START,
264            PROXY_ENV_END,
265            quiet,
266            "proxy env from ~/.config/fish/config.fish",
267        );
268    }
269
270    let ps_profile =
271        dirs::home_dir().map(|h| crate::shell::platform::resolve_powershell_profile_path(&h));
272    if let Some(ref ps) = ps_profile
273        && ps.exists()
274    {
275        marked_block::remove_from_file(
276            ps,
277            PROXY_ENV_START,
278            PROXY_ENV_END,
279            quiet,
280            "proxy env from PowerShell profile",
281        );
282    }
283
284    uninstall_claude_env(home, quiet);
285    uninstall_codex_env(home, quiet);
286    uninstall_pi_env(home, quiet);
287    uninstall_grok_env(home, quiet);
288    uninstall_commandcode_env(home, quiet);
289}