lean_ctx_cli/proxy_setup/
mod.rs1mod 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
70pub fn install_proxy_env_unchecked(home: &Path, port: u16, quiet: bool, force_endpoint: bool) {
73 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#[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
168fn 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
179fn 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
195fn 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
208type 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
221type 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
230fn 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 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
259pub 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
265pub 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}