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/// Removes stale proxy URLs from Claude Code / Codex settings when the proxy is not enabled.
169/// Returns the number of stale URLs cleaned up.
170pub fn cleanup_stale_proxy_env(home: &Path) -> usize {
171    let cfg = lean_ctx::core::config::Config::load();
172    if cfg.proxy_enabled == Some(true) {
173        return 0;
174    }
175
176    let mut cleaned = 0;
177
178    let settings_dir = lean_ctx::core::editor_registry::claude_state_dir(home);
179    let settings_path = settings_dir.join("settings.json");
180    if let Ok(content) = std::fs::read_to_string(&settings_path)
181        && let Ok(mut doc) = lean_ctx::core::jsonc::parse_jsonc(&content)
182        && let Some(base_url) = doc
183            .get("env")
184            .and_then(|e| e.get("ANTHROPIC_BASE_URL"))
185            .and_then(|v| v.as_str())
186            .map(String::from)
187        && is_local_lean_ctx_url(&base_url)
188        && let Some(env_obj) = doc.get_mut("env").and_then(|e| e.as_object_mut())
189    {
190        if let Some(ref upstream) = cfg.proxy.anthropic_upstream {
191            env_obj.insert(
192                "ANTHROPIC_BASE_URL".to_string(),
193                serde_json::Value::String(upstream.clone()),
194            );
195            println!("  ✓ Restored ANTHROPIC_BASE_URL → {upstream} in Claude Code settings");
196        } else {
197            env_obj.remove("ANTHROPIC_BASE_URL");
198            if env_obj.is_empty() {
199                doc.as_object_mut().map(|o| o.remove("env"));
200            }
201            println!("  ✓ Removed stale ANTHROPIC_BASE_URL from Claude Code settings");
202        }
203        let out = serde_json::to_string_pretty(&doc).unwrap_or_default();
204        let _ = std::fs::write(&settings_path, out + "\n");
205        cleaned += 1;
206    }
207
208    let codex_path = lean_ctx::core::home::resolve_codex_config_path()
209        .unwrap_or_else(|| home.join(".codex/config.toml"));
210    if let Ok(content) = std::fs::read_to_string(&codex_path)
211        && codex_config_has_local_proxy_entry(&content)
212    {
213        let filtered = strip_codex_proxy_entries(&content);
214        let _ = std::fs::write(&codex_path, &filtered);
215        println!("  ✓ Removed stale Codex proxy URL from config.toml");
216        cleaned += 1;
217    }
218
219    let grok_path = home.join(".grok/config.toml");
220    if let Ok(content) = std::fs::read_to_string(&grok_path)
221        && grok_config_has_local_proxy_entry(&content)
222    {
223        let cleaned_toml = strip_grok_proxy_entries(&content);
224        let _ = std::fs::write(&grok_path, &cleaned_toml);
225        println!("  ✓ Removed stale Grok proxy models_base_url from config.toml");
226        cleaned += 1;
227    }
228
229    cleaned
230}
231
232pub fn has_stale_proxy_url(home: &Path) -> bool {
233    let cfg = lean_ctx::core::config::Config::load();
234    if cfg.proxy_enabled == Some(true) {
235        return false;
236    }
237
238    let settings_dir = lean_ctx::core::editor_registry::claude_state_dir(home);
239    let settings_path = settings_dir.join("settings.json");
240    let Ok(content) = std::fs::read_to_string(&settings_path) else {
241        return false;
242    };
243    let Ok(doc) = lean_ctx::core::jsonc::parse_jsonc(&content) else {
244        return false;
245    };
246
247    let base_url = doc
248        .get("env")
249        .and_then(|e| e.get("ANTHROPIC_BASE_URL"))
250        .and_then(|v| v.as_str())
251        .unwrap_or("");
252
253    is_local_lean_ctx_url(base_url)
254}
255
256pub fn uninstall_proxy_env(home: &Path, quiet: bool) {
257    for rc in &[home.join(".zshrc"), home.join(".bashrc")] {
258        let label = format!(
259            "proxy env from ~/{}",
260            rc.file_name().unwrap_or_default().to_string_lossy()
261        );
262        marked_block::remove_from_file(rc, PROXY_ENV_START, PROXY_ENV_END, quiet, &label);
263    }
264
265    let fish_config = home.join(".config/fish/config.fish");
266    if fish_config.exists() {
267        marked_block::remove_from_file(
268            &fish_config,
269            PROXY_ENV_START,
270            PROXY_ENV_END,
271            quiet,
272            "proxy env from ~/.config/fish/config.fish",
273        );
274    }
275
276    let ps_profile =
277        dirs::home_dir().map(|h| lean_ctx::shell::platform::resolve_powershell_profile_path(&h));
278    if let Some(ref ps) = ps_profile
279        && ps.exists()
280    {
281        marked_block::remove_from_file(
282            ps,
283            PROXY_ENV_START,
284            PROXY_ENV_END,
285            quiet,
286            "proxy env from PowerShell profile",
287        );
288    }
289
290    uninstall_claude_env(home, quiet);
291    uninstall_codex_env(home, quiet);
292    uninstall_pi_env(home, quiet);
293    uninstall_grok_env(home, quiet);
294    uninstall_commandcode_env(home, quiet);
295}