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