Skip to main content

lean_ctx/
proxy_setup.rs

1use std::path::Path;
2
3use crate::marked_block;
4
5const PROXY_ENV_START: &str = "# >>> lean-ctx proxy env >>>";
6const PROXY_ENV_END: &str = "# <<< lean-ctx proxy env <<<";
7
8const DEFAULT_PROXY_PORT: u16 = 4444;
9
10/// Comment written in place of the `ANTHROPIC_BASE_URL` export when no Anthropic API
11/// key is detectable. A Claude Pro/Max subscription authenticates via OAuth against
12/// `api.anthropic.com` directly and is rejected by any custom base URL, so we must not
13/// route it through the proxy.
14const ANTHROPIC_OMITTED_NOTE: &str = "ANTHROPIC_BASE_URL omitted: Claude Pro/Max subscription authenticates against api.anthropic.com directly (set ANTHROPIC_API_KEY to route Claude through the proxy)";
15
16pub fn install_proxy_env(home: &Path, port: u16, quiet: bool) {
17    let cfg = crate::core::config::Config::load();
18    if cfg.proxy_enabled != Some(true) {
19        if !quiet {
20            println!("  Proxy env skipped (not enabled in config)");
21        }
22        return;
23    }
24    install_shell_exports(home, port, quiet);
25    install_claude_env(home, port, quiet);
26    install_codex_env(home, port, quiet);
27    install_pi_env(home, port, quiet, false);
28}
29
30/// Install proxy env without config guard (used by `lean-ctx proxy enable` which has already set the flag).
31/// `force_endpoint`: if true, overrides even non-local custom endpoints.
32pub fn install_proxy_env_unchecked(home: &Path, port: u16, quiet: bool, force_endpoint: bool) {
33    install_shell_exports(home, port, quiet);
34    if force_endpoint {
35        install_claude_env_inner(home, port, quiet, true);
36    } else {
37        install_claude_env(home, port, quiet);
38    }
39    install_codex_env(home, port, quiet);
40    install_pi_env(home, port, quiet, force_endpoint);
41}
42
43pub fn preview_proxy_cleanup(home: &Path) {
44    let settings_dir = crate::core::editor_registry::claude_state_dir(home);
45    let settings_path = settings_dir.join("settings.json");
46    if let Ok(content) = std::fs::read_to_string(&settings_path)
47        && content.contains("ANTHROPIC_BASE_URL")
48    {
49        let cfg = crate::core::config::Config::load();
50        if let Some(ref upstream) = cfg.proxy.anthropic_upstream {
51            println!("  Would restore ANTHROPIC_BASE_URL → {upstream} in Claude Code settings");
52        } else {
53            println!("  Would remove ANTHROPIC_BASE_URL from Claude Code settings");
54        }
55    }
56
57    let codex_dir = crate::core::home::resolve_codex_dir().unwrap_or_else(|| home.join(".codex"));
58    let codex_path = codex_dir.join("config.toml");
59    if let Ok(content) = std::fs::read_to_string(codex_path)
60        && codex_config_has_local_proxy_entry(&content)
61    {
62        println!("  Would remove Codex proxy URL from config.toml");
63    }
64}
65
66/// Removes stale proxy URLs from Claude Code / Codex settings when the proxy is not enabled.
67/// Returns the number of stale URLs cleaned up.
68pub fn cleanup_stale_proxy_env(home: &Path) -> usize {
69    let cfg = crate::core::config::Config::load();
70    if cfg.proxy_enabled == Some(true) {
71        return 0;
72    }
73
74    let mut cleaned = 0;
75
76    let settings_dir = crate::core::editor_registry::claude_state_dir(home);
77    let settings_path = settings_dir.join("settings.json");
78    if let Ok(content) = std::fs::read_to_string(&settings_path)
79        && let Ok(mut doc) = crate::core::jsonc::parse_jsonc(&content)
80        && let Some(base_url) = doc
81            .get("env")
82            .and_then(|e| e.get("ANTHROPIC_BASE_URL"))
83            .and_then(|v| v.as_str())
84            .map(String::from)
85        && is_local_lean_ctx_url(&base_url)
86        && let Some(env_obj) = doc.get_mut("env").and_then(|e| e.as_object_mut())
87    {
88        if let Some(ref upstream) = cfg.proxy.anthropic_upstream {
89            env_obj.insert(
90                "ANTHROPIC_BASE_URL".to_string(),
91                serde_json::Value::String(upstream.clone()),
92            );
93            println!("  ✓ Restored ANTHROPIC_BASE_URL → {upstream} in Claude Code settings");
94        } else {
95            env_obj.remove("ANTHROPIC_BASE_URL");
96            if env_obj.is_empty() {
97                doc.as_object_mut().map(|o| o.remove("env"));
98            }
99            println!("  ✓ Removed stale ANTHROPIC_BASE_URL from Claude Code settings");
100        }
101        let out = serde_json::to_string_pretty(&doc).unwrap_or_default();
102        let _ = std::fs::write(&settings_path, out + "\n");
103        cleaned += 1;
104    }
105
106    let codex_dir = crate::core::home::resolve_codex_dir().unwrap_or_else(|| home.join(".codex"));
107    let codex_path = codex_dir.join("config.toml");
108    if let Ok(content) = std::fs::read_to_string(&codex_path)
109        && codex_config_has_local_proxy_entry(&content)
110    {
111        let filtered = strip_codex_proxy_entries(&content);
112        let _ = std::fs::write(&codex_path, &filtered);
113        println!("  ✓ Removed stale Codex proxy URL from config.toml");
114        cleaned += 1;
115    }
116
117    cleaned
118}
119
120pub fn is_local_lean_ctx_url(url: &str) -> bool {
121    url.starts_with("http://127.0.0.1:") || url.starts_with("http://localhost:")
122}
123
124/// Returns true if Claude Code settings contain a local ANTHROPIC_BASE_URL
125/// while the proxy is not enabled (stale configuration).
126pub fn has_stale_proxy_url(home: &Path) -> bool {
127    let cfg = crate::core::config::Config::load();
128    if cfg.proxy_enabled == Some(true) {
129        return false;
130    }
131
132    let settings_dir = crate::core::editor_registry::claude_state_dir(home);
133    let settings_path = settings_dir.join("settings.json");
134    let Ok(content) = std::fs::read_to_string(&settings_path) else {
135        return false;
136    };
137    let Ok(doc) = crate::core::jsonc::parse_jsonc(&content) else {
138        return false;
139    };
140
141    let base_url = doc
142        .get("env")
143        .and_then(|e| e.get("ANTHROPIC_BASE_URL"))
144        .and_then(|v| v.as_str())
145        .unwrap_or("");
146
147    is_local_lean_ctx_url(base_url)
148}
149
150/// Returns true when an Anthropic **API key** is available for the proxy to forward
151/// upstream.
152///
153/// The proxy never injects credentials (see `proxy/forward.rs` — only
154/// `ALLOWED_REQUEST_HEADERS` are forwarded), so it can only help Claude Code when the
155/// user runs in API-key (pay-as-you-go) mode. A Claude **Pro/Max subscription**
156/// authenticates via OAuth directly against `api.anthropic.com`; that token is rejected
157/// by any custom `ANTHROPIC_BASE_URL`, so redirecting subscription traffic through the
158/// proxy only breaks auth (login loop / 401). When this returns `false`, callers must
159/// NOT point Claude Code at the proxy.
160pub fn anthropic_api_key_available(home: &Path) -> bool {
161    // 1) Process environment — covers shells and Claude Code launched from them.
162    for var in ["ANTHROPIC_API_KEY", "ANTHROPIC_AUTH_TOKEN"] {
163        if std::env::var(var).is_ok_and(|v| !v.trim().is_empty()) {
164            return true;
165        }
166    }
167
168    // 2) Claude Code settings.json — an explicit key, an auth token, or a dynamic
169    //    key helper all indicate API-key mode.
170    let settings_path = crate::core::editor_registry::claude_state_dir(home).join("settings.json");
171    let Ok(content) = std::fs::read_to_string(&settings_path) else {
172        return false;
173    };
174    let Ok(doc) = crate::core::jsonc::parse_jsonc(&content) else {
175        return false;
176    };
177
178    if doc
179        .get("apiKeyHelper")
180        .and_then(|v| v.as_str())
181        .is_some_and(|v| !v.trim().is_empty())
182    {
183        return true;
184    }
185
186    let env = doc.get("env");
187    ["ANTHROPIC_API_KEY", "ANTHROPIC_AUTH_TOKEN"]
188        .iter()
189        .any(|key| {
190            env.and_then(|e| e.get(*key))
191                .and_then(|v| v.as_str())
192                .is_some_and(|v| !v.trim().is_empty())
193        })
194}
195
196/// Explains why Claude Code was left pointing at `api.anthropic.com` instead of the
197/// proxy: a Pro/Max subscription (OAuth) cannot authenticate through a custom base URL.
198fn warn_claude_subscription_skip() {
199    eprintln!("  \u{26a0} Claude Code: no ANTHROPIC_API_KEY detected (Pro/Max subscription?).");
200    eprintln!("    The proxy forwards your credential upstream but never injects one, and a");
201    eprintln!("    subscription token only authenticates against api.anthropic.com directly.");
202    eprintln!("    Leaving ANTHROPIC_BASE_URL untouched so Claude Code keeps working.");
203    eprintln!("    Savings on a subscription: use the lean-ctx MCP tools (ctx_read /");
204    eprintln!("    ctx_search / ctx_shell). Pay-as-you-go? Set ANTHROPIC_API_KEY, then run:");
205    eprintln!("      lean-ctx proxy enable");
206}
207
208pub fn uninstall_proxy_env(home: &Path, quiet: bool) {
209    for rc in &[home.join(".zshrc"), home.join(".bashrc")] {
210        let label = format!(
211            "proxy env from ~/{}",
212            rc.file_name().unwrap_or_default().to_string_lossy()
213        );
214        marked_block::remove_from_file(rc, PROXY_ENV_START, PROXY_ENV_END, quiet, &label);
215    }
216
217    let fish_config = home.join(".config/fish/config.fish");
218    if fish_config.exists() {
219        marked_block::remove_from_file(
220            &fish_config,
221            PROXY_ENV_START,
222            PROXY_ENV_END,
223            quiet,
224            "proxy env from ~/.config/fish/config.fish",
225        );
226    }
227
228    let ps_profile =
229        dirs::home_dir().map(|h| crate::shell::platform::resolve_powershell_profile_path(&h));
230    if let Some(ref ps) = ps_profile
231        && ps.exists()
232    {
233        marked_block::remove_from_file(
234            ps,
235            PROXY_ENV_START,
236            PROXY_ENV_END,
237            quiet,
238            "proxy env from PowerShell profile",
239        );
240    }
241
242    uninstall_claude_env(home, quiet);
243    uninstall_codex_env(home, quiet);
244    uninstall_pi_env(home, quiet);
245}
246
247fn install_shell_exports(home: &Path, port: u16, quiet: bool) {
248    if !is_proxy_reachable(port) {
249        if !quiet {
250            println!("  Skipping shell proxy exports (proxy not running on port {port})");
251        }
252        return;
253    }
254
255    let base = format!("http://127.0.0.1:{port}");
256    // OpenAI SDK convention: the base URL INCLUDES the `/v1` prefix (default is
257    // `https://api.openai.com/v1`); clients append bare endpoints like `/responses`.
258    // Without `/v1`, OpenCode's ChatGPT-OAuth plugin fails to recognize Responses-API
259    // requests (it matches on `/v1/responses`) and OAuth traffic leaks to the platform
260    // API with the wrong credential ("Missing scopes: api.responses.write", #366).
261    // Anthropic and Gemini SDKs expect a bare origin instead — they append `/v1/...`
262    // / `/v1beta/...` themselves.
263    let openai_base = format!("{base}/v1");
264
265    // Only route Claude through the proxy when an API key is available; a Pro/Max
266    // subscription must keep talking to api.anthropic.com directly (see
267    // `anthropic_api_key_available`).
268    let include_anthropic = anthropic_api_key_available(home);
269
270    let posix_anthropic = if include_anthropic {
271        format!(r#"export ANTHROPIC_BASE_URL="{base}""#)
272    } else {
273        format!("# {ANTHROPIC_OMITTED_NOTE}")
274    };
275    let posix_block = format!(
276        r#"{PROXY_ENV_START}
277{posix_anthropic}
278export OPENAI_BASE_URL="{openai_base}"
279export GEMINI_API_BASE_URL="{base}"
280{PROXY_ENV_END}"#
281    );
282
283    for rc in &[home.join(".zshrc"), home.join(".bashrc")] {
284        if rc.exists() {
285            let label = format!(
286                "proxy env in ~/{}",
287                rc.file_name().unwrap_or_default().to_string_lossy()
288            );
289            marked_block::upsert(
290                rc,
291                PROXY_ENV_START,
292                PROXY_ENV_END,
293                &posix_block,
294                quiet,
295                &label,
296            );
297        }
298    }
299
300    let fish_config = home.join(".config/fish/config.fish");
301    if fish_config.exists() {
302        let fish_anthropic = if include_anthropic {
303            format!(r#"set -gx ANTHROPIC_BASE_URL "{base}""#)
304        } else {
305            format!("# {ANTHROPIC_OMITTED_NOTE}")
306        };
307        let fish_block = format!(
308            r#"{PROXY_ENV_START}
309{fish_anthropic}
310set -gx OPENAI_BASE_URL "{openai_base}"
311set -gx GEMINI_API_BASE_URL "{base}"
312{PROXY_ENV_END}"#
313        );
314        marked_block::upsert(
315            &fish_config,
316            PROXY_ENV_START,
317            PROXY_ENV_END,
318            &fish_block,
319            quiet,
320            "proxy env in ~/.config/fish/config.fish",
321        );
322    }
323
324    let ps_profile =
325        dirs::home_dir().map(|h| crate::shell::platform::resolve_powershell_profile_path(&h));
326    if let Some(ref ps) = ps_profile
327        && ps.exists()
328    {
329        let ps_anthropic = if include_anthropic {
330            format!(r#"$env:ANTHROPIC_BASE_URL = "{base}""#)
331        } else {
332            format!("# {ANTHROPIC_OMITTED_NOTE}")
333        };
334        let ps_block = format!(
335            r#"{PROXY_ENV_START}
336{ps_anthropic}
337$env:OPENAI_BASE_URL = "{openai_base}"
338$env:GEMINI_API_BASE_URL = "{base}"
339{PROXY_ENV_END}"#
340        );
341        marked_block::upsert(
342            ps,
343            PROXY_ENV_START,
344            PROXY_ENV_END,
345            &ps_block,
346            quiet,
347            "proxy env in PowerShell profile",
348        );
349    }
350}
351
352fn uninstall_claude_env(home: &Path, quiet: bool) {
353    use crate::core::config::Config;
354
355    let settings_dir = crate::core::editor_registry::claude_state_dir(home);
356    let settings_path = settings_dir.join("settings.json");
357    let existing = match std::fs::read_to_string(&settings_path) {
358        Ok(s) if !s.trim().is_empty() => s,
359        _ => return,
360    };
361    let mut doc: serde_json::Value = match crate::core::jsonc::parse_jsonc(&existing) {
362        Ok(v) => v,
363        Err(_) => return,
364    };
365
366    let Some(env_obj) = doc.get_mut("env").and_then(|e| e.as_object_mut()) else {
367        return;
368    };
369
370    if !env_obj.contains_key("ANTHROPIC_BASE_URL") {
371        return;
372    }
373
374    let cfg = Config::load();
375    if let Some(ref upstream) = cfg.proxy.anthropic_upstream {
376        env_obj.insert(
377            "ANTHROPIC_BASE_URL".to_string(),
378            serde_json::Value::String(upstream.clone()),
379        );
380        if !quiet {
381            println!("  ✓ Restored ANTHROPIC_BASE_URL → {upstream} in Claude Code settings");
382        }
383    } else {
384        env_obj.remove("ANTHROPIC_BASE_URL");
385        if env_obj.is_empty() {
386            doc.as_object_mut().map(|o| o.remove("env"));
387        }
388        if !quiet {
389            println!("  ✓ Removed ANTHROPIC_BASE_URL from Claude Code settings");
390        }
391    }
392
393    let content = serde_json::to_string_pretty(&doc).unwrap_or_default();
394    let _ = std::fs::write(&settings_path, content + "\n");
395}
396
397fn uninstall_codex_env(home: &Path, quiet: bool) {
398    let codex_dir = crate::core::home::resolve_codex_dir().unwrap_or_else(|| home.join(".codex"));
399    let config_path = codex_dir.join("config.toml");
400    let existing = match std::fs::read_to_string(&config_path) {
401        Ok(s) if !s.trim().is_empty() => s,
402        _ => return,
403    };
404
405    let has_local = codex_config_has_local_proxy_entry(&existing);
406    if !has_local {
407        return;
408    }
409
410    let cleaned = strip_codex_proxy_entries(&existing);
411    let _ = std::fs::write(&config_path, &cleaned);
412    if !quiet {
413        println!("  ✓ Removed Codex proxy URL(s) from Codex CLI config");
414    }
415}
416
417/// Pi / forge resolve their provider endpoint from `~/.pi/agent/models.json`
418/// (`providers.<name>.baseUrl`) + OAuth, *not* from `ANTHROPIC_BASE_URL` /
419/// `OPENAI_BASE_URL`, so the shell and Claude/Codex wiring never reaches them
420/// (an independent benchmark found `proxy enable` silently bypassed for forge,
421/// #361). Point Pi's providers at the proxy directly instead. Unlike a Claude
422/// Code Pro/Max subscription — which a custom base URL breaks — Pi's OAuth works
423/// through the proxy, because the proxy forwards the credential verbatim to the
424/// real upstream (verified field-for-field in #361), so no API-key guard applies.
425fn install_pi_env(home: &Path, port: u16, quiet: bool, force: bool) {
426    install_pi_env_at(&home.join(".pi/agent"), port, quiet, force);
427}
428
429fn uninstall_pi_env(home: &Path, quiet: bool) {
430    uninstall_pi_env_at(&home.join(".pi/agent"), quiet);
431}
432
433/// Testable core of [`install_pi_env`]: operates on an explicit `~/.pi/agent`
434/// directory. Wires both providers using the same per-SDK conventions as the
435/// shell exports — Anthropic gets the bare origin (it appends `/v1` itself),
436/// OpenAI gets the `/v1`-suffixed URL (#366). A custom *remote* endpoint is
437/// preserved unless `force`, and only the providers we actually rewrite are
438/// touched, so the file round-trips cleanly on `disable`.
439fn install_pi_env_at(agent_dir: &Path, port: u16, quiet: bool, force: bool) {
440    use crate::core::config::{is_local_proxy_url, normalize_url_opt};
441
442    // Only wire Pi when it is actually configured on this machine.
443    if !agent_dir.exists() {
444        return;
445    }
446    if !is_proxy_reachable(port) {
447        if !quiet {
448            println!("  Skipping Pi proxy env (proxy not running on port {port})");
449        }
450        return;
451    }
452
453    let base = format!("http://127.0.0.1:{port}");
454    let models_path = agent_dir.join("models.json");
455    let existing = std::fs::read_to_string(&models_path).unwrap_or_default();
456    let mut doc: serde_json::Value = if existing.trim().is_empty() {
457        serde_json::json!({})
458    } else {
459        match crate::core::jsonc::parse_jsonc(&existing) {
460            Ok(v) => v,
461            Err(_) => return,
462        }
463    };
464
465    let mut changed = false;
466    let mut kept_custom: Vec<String> = Vec::new();
467    for (provider, proxy_url) in [
468        ("anthropic", base.clone()),
469        ("openai", format!("{base}/v1")),
470    ] {
471        let current = pi_provider_base_url(&doc, provider).to_string();
472        if current == proxy_url {
473            continue;
474        }
475        // Never silently clobber a user's custom remote gateway; --force overrides.
476        if !force
477            && let Some(custom) = normalize_url_opt(&current)
478            && !is_local_proxy_url(&custom)
479        {
480            kept_custom.push(format!("{provider} → {custom}"));
481            continue;
482        }
483        set_pi_provider_base_url(&mut doc, provider, &proxy_url);
484        changed = true;
485    }
486
487    if changed {
488        let out = serde_json::to_string_pretty(&doc).unwrap_or_default();
489        let _ = std::fs::write(&models_path, out + "\n");
490        if !quiet {
491            println!(
492                "  Configured Pi providers (anthropic/openai) → proxy in ~/.pi/agent/models.json"
493            );
494        }
495    }
496    if !quiet && !kept_custom.is_empty() {
497        eprintln!(
498            "  \u{26a0} Pi: kept custom endpoint(s) {}; use `lean-ctx proxy enable --force` to override.",
499            kept_custom.join(", ")
500        );
501    }
502}
503
504/// Testable core of [`uninstall_pi_env`]. Reverts only the providers whose
505/// `baseUrl` still points at the local proxy (i.e. the ones we set), so a custom
506/// remote endpoint the user configured themselves is never removed.
507fn uninstall_pi_env_at(agent_dir: &Path, quiet: bool) {
508    use crate::core::config::is_local_proxy_url;
509
510    let models_path = agent_dir.join("models.json");
511    let existing = match std::fs::read_to_string(&models_path) {
512        Ok(s) if !s.trim().is_empty() => s,
513        _ => return,
514    };
515    let mut doc: serde_json::Value = match crate::core::jsonc::parse_jsonc(&existing) {
516        Ok(v) => v,
517        Err(_) => return,
518    };
519
520    let mut changed = false;
521    for provider in ["anthropic", "openai"] {
522        if is_local_proxy_url(pi_provider_base_url(&doc, provider))
523            && remove_pi_provider_base_url(&mut doc, provider)
524        {
525            changed = true;
526        }
527    }
528
529    if changed {
530        let out = serde_json::to_string_pretty(&doc).unwrap_or_default();
531        let _ = std::fs::write(&models_path, out + "\n");
532        if !quiet {
533            println!("  \u{2713} Removed Pi proxy endpoints from ~/.pi/agent/models.json");
534        }
535    }
536}
537
538/// `providers.<name>.baseUrl` from a Pi `models.json` document (`""` if absent).
539fn pi_provider_base_url<'a>(doc: &'a serde_json::Value, provider: &str) -> &'a str {
540    doc.get("providers")
541        .and_then(|p| p.get(provider))
542        .and_then(|p| p.get("baseUrl"))
543        .and_then(serde_json::Value::as_str)
544        .unwrap_or("")
545}
546
547/// Sets `providers.<name>.baseUrl`, creating the nested objects as needed.
548fn set_pi_provider_base_url(doc: &mut serde_json::Value, provider: &str, url: &str) {
549    let Some(root) = doc.as_object_mut() else {
550        return;
551    };
552    let providers = root
553        .entry("providers")
554        .or_insert_with(|| serde_json::json!({}));
555    let Some(providers) = providers.as_object_mut() else {
556        return;
557    };
558    let entry = providers
559        .entry(provider.to_string())
560        .or_insert_with(|| serde_json::json!({}));
561    if let Some(entry) = entry.as_object_mut() {
562        entry.insert(
563            "baseUrl".to_string(),
564            serde_json::Value::String(url.to_string()),
565        );
566    }
567}
568
569/// Removes `providers.<name>.baseUrl` and prunes now-empty parent objects.
570/// Returns whether anything was removed.
571fn remove_pi_provider_base_url(doc: &mut serde_json::Value, provider: &str) -> bool {
572    let Some(root) = doc.as_object_mut() else {
573        return false;
574    };
575    let Some(providers) = root.get_mut("providers").and_then(|p| p.as_object_mut()) else {
576        return false;
577    };
578    let Some(entry) = providers.get_mut(provider).and_then(|p| p.as_object_mut()) else {
579        return false;
580    };
581    if entry.remove("baseUrl").is_none() {
582        return false;
583    }
584    if entry.is_empty() {
585        providers.remove(provider);
586    }
587    if providers.is_empty() {
588        root.remove("providers");
589    }
590    true
591}
592
593fn install_claude_env(home: &Path, port: u16, quiet: bool) {
594    install_claude_env_inner(home, port, quiet, false);
595}
596
597fn install_claude_env_inner(home: &Path, port: u16, quiet: bool, force: bool) {
598    use crate::core::config::{Config, is_local_proxy_url, normalize_url_opt};
599
600    let base = format!("http://127.0.0.1:{port}");
601
602    let settings_dir = crate::core::editor_registry::claude_state_dir(home);
603    let settings_path = settings_dir.join("settings.json");
604    let existing = std::fs::read_to_string(&settings_path).unwrap_or_default();
605    let mut doc: serde_json::Value = if existing.trim().is_empty() {
606        serde_json::json!({})
607    } else {
608        match crate::core::jsonc::parse_jsonc(&existing) {
609            Ok(v) => v,
610            Err(_) => return,
611        }
612    };
613
614    let current_url = doc
615        .get("env")
616        .and_then(|e| e.get("ANTHROPIC_BASE_URL"))
617        .and_then(|v| v.as_str())
618        .unwrap_or("")
619        .to_string();
620
621    // SUBSCRIPTION GUARD: the proxy never injects credentials, so redirecting Claude
622    // Code only works in API-key mode. A Claude Pro/Max subscription (OAuth) is rejected
623    // by a custom ANTHROPIC_BASE_URL → login loop / 401. When no API key is detectable we
624    // must not point Claude Code at the proxy. `--force` overrides for power users whose
625    // key lives somewhere we cannot probe (e.g. a keychain or apiKeyHelper we missed).
626    if !force && !anthropic_api_key_available(home) {
627        // Repair an existing stale local redirect so Claude Code reaches Anthropic again.
628        if is_local_lean_ctx_url(&current_url) {
629            let cfg = Config::load();
630            if let Some(env_obj) = doc.get_mut("env").and_then(|e| e.as_object_mut()) {
631                if let Some(ref upstream) = cfg.proxy.anthropic_upstream {
632                    env_obj.insert(
633                        "ANTHROPIC_BASE_URL".to_string(),
634                        serde_json::Value::String(upstream.clone()),
635                    );
636                } else {
637                    env_obj.remove("ANTHROPIC_BASE_URL");
638                    if env_obj.is_empty() {
639                        doc.as_object_mut().map(|o| o.remove("env"));
640                    }
641                }
642                let out = serde_json::to_string_pretty(&doc).unwrap_or_default();
643                let _ = std::fs::write(&settings_path, out + "\n");
644            }
645        }
646        if !quiet {
647            warn_claude_subscription_skip();
648        }
649        return;
650    }
651
652    if current_url == base {
653        if !quiet {
654            println!("  Claude Code proxy env already configured");
655        }
656        return;
657    }
658
659    // HARD GUARD: never overwrite non-local endpoints unless --force
660    if let Some(upstream) = normalize_url_opt(&current_url)
661        && !is_local_proxy_url(&upstream)
662    {
663        if Config::load_global().proxy.anthropic_upstream.is_none()
664            && let Err(e) =
665                Config::update_global(|c| c.proxy.anthropic_upstream = Some(upstream.clone()))
666        {
667            tracing::warn!("could not persist proxy upstream: {e}");
668        }
669
670        if !force {
671            if !quiet {
672                eprintln!("  \u{26a0} Custom endpoint detected: {upstream}");
673                eprintln!(
674                    "    Skipping proxy URL write. Use `lean-ctx proxy enable --force` to override."
675                );
676            }
677            return;
678        }
679        if !quiet {
680            println!("  Overriding custom endpoint (--force): {upstream}");
681        }
682    }
683
684    if !is_proxy_reachable(port) {
685        if !quiet {
686            println!("  Skipping Claude Code proxy env (proxy not running on port {port})");
687        }
688        return;
689    }
690
691    if let Some(env_obj) = doc.as_object_mut().and_then(|o| {
692        o.entry("env")
693            .or_insert(serde_json::json!({}))
694            .as_object_mut()
695    }) {
696        env_obj.insert(
697            "ANTHROPIC_BASE_URL".to_string(),
698            serde_json::Value::String(base),
699        );
700    }
701
702    let _ = std::fs::create_dir_all(&settings_dir);
703    let content = serde_json::to_string_pretty(&doc).unwrap_or_default();
704    let _ = std::fs::write(&settings_path, content + "\n");
705    if !quiet {
706        println!("  Configured ANTHROPIC_BASE_URL in Claude Code settings");
707    }
708}
709
710/// Proxy reachability timeout. Priority: env var > config.toml > 200ms default.
711pub fn proxy_timeout() -> std::time::Duration {
712    if let Ok(val) = std::env::var("LEAN_CTX_PROXY_TIMEOUT_MS")
713        && let Ok(ms) = val.parse::<u64>()
714    {
715        return std::time::Duration::from_millis(ms);
716    }
717    if let Some(ms) = crate::core::config::Config::load().proxy_timeout_ms {
718        return std::time::Duration::from_millis(ms);
719    }
720    std::time::Duration::from_millis(200)
721}
722
723fn is_proxy_reachable(port: u16) -> bool {
724    use std::net::{IpAddr, Ipv4Addr, SocketAddr, TcpStream};
725    let addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), port);
726    TcpStream::connect_timeout(&addr, proxy_timeout()).is_ok()
727}
728
729fn install_codex_env(home: &Path, port: u16, quiet: bool) {
730    let config_dir = crate::core::home::resolve_codex_dir().unwrap_or_else(|| home.join(".codex"));
731    let mode = if codex_uses_chatgpt_login(home) {
732        CodexProxyMode::ChatGpt
733    } else {
734        CodexProxyMode::ApiKey
735    };
736    install_codex_env_at_mode(&config_dir, port, quiet, mode);
737}
738
739#[derive(Debug, Clone, Copy, PartialEq, Eq)]
740enum CodexProxyMode {
741    ApiKey,
742    ChatGpt,
743}
744
745const CODEX_CHATGPT_PROVIDER_ID: &str = "leanctx-chatgpt";
746
747/// Testable core of `install_codex_env`: operates on an explicit Codex config
748/// directory instead of resolving it from `CODEX_HOME` / the real home.
749#[cfg(test)]
750fn install_codex_env_at(config_dir: &Path, port: u16, quiet: bool) {
751    install_codex_env_at_mode(config_dir, port, quiet, CodexProxyMode::ApiKey);
752}
753
754fn install_codex_env_at_mode(config_dir: &Path, port: u16, quiet: bool, mode: CodexProxyMode) {
755    // Codex reads the built-in OpenAI provider's base URL from the top-level
756    // `openai_base_url` key (openai/codex#12031). API-key mode uses `/v1`;
757    // ChatGPT subscription auth uses Codex's backend rail under
758    // `/backend-api/codex`, plus `chatgpt_base_url` for aux `/backend-api/*`
759    // calls such as the codex_apps streamable HTTP MCP endpoint.
760    let base = format!("http://127.0.0.1:{port}");
761    let entries: Vec<(&str, String)> = match mode {
762        CodexProxyMode::ApiKey => vec![("openai_base_url", format!("{base}/v1"))],
763        CodexProxyMode::ChatGpt => vec![
764            ("model_provider", CODEX_CHATGPT_PROVIDER_ID.to_string()),
765            ("openai_base_url", format!("{base}/backend-api/codex")),
766            ("chatgpt_base_url", format!("{base}/backend-api")),
767        ],
768    };
769    let provider_block = match mode {
770        CodexProxyMode::ApiKey => None,
771        CodexProxyMode::ChatGpt => Some(render_codex_chatgpt_provider_block(&base)),
772    };
773
774    if !is_proxy_reachable(port) {
775        if !quiet {
776            println!("  Skipping Codex CLI proxy env (proxy not running on port {port})");
777        }
778        return;
779    }
780
781    if !config_dir.exists() {
782        return;
783    }
784
785    let config_path = config_dir.join("config.toml");
786    let existing = std::fs::read_to_string(&config_path).unwrap_or_default();
787    let updated =
788        render_codex_config_with_extra_block(&existing, &entries, provider_block.as_deref());
789
790    if updated == existing {
791        if !quiet {
792            println!("  Codex CLI proxy env already configured");
793        }
794        return;
795    }
796
797    let _ = std::fs::write(&config_path, &updated);
798    if !quiet {
799        match mode {
800            CodexProxyMode::ApiKey => println!("  Configured openai_base_url in Codex CLI config"),
801            CodexProxyMode::ChatGpt => {
802                println!("  Configured ChatGPT Codex proxy URLs in Codex CLI config");
803            }
804        }
805    }
806}
807
808/// Point Codex's built-in OpenAI provider at `value` via the documented top-level
809/// `openai_base_url` key. Removes lean-ctx's legacy local `[env] OPENAI_BASE_URL`
810/// (dead config Codex never read, #554) and migrates a stale local `openai_base_url`
811/// to the canonical `/v1` value. A custom *remote* endpoint the user configured is
812/// preserved and never overwritten (#366). The key is emitted as a top-level key
813/// (before the first `[table]`) so Codex actually reads it.
814#[cfg(test)]
815fn render_codex_config(existing: &str, entries: &[(&str, String)]) -> String {
816    render_codex_config_with_extra_block(existing, entries, None)
817}
818
819fn render_codex_config_with_extra_block(
820    existing: &str,
821    entries: &[(&str, String)],
822    extra_block: Option<&str>,
823) -> String {
824    let cleaned = strip_codex_proxy_entries(existing);
825
826    let mut prefix = String::new();
827    for (key, value) in entries {
828        if *key == "model_provider" {
829            let has_model_provider =
830                has_top_level_codex_config_key(&cleaned, "model_provider", |_| true);
831            if !has_model_provider {
832                prefix.push_str(&format!("{key} = \"{value}\"\n"));
833            }
834            continue;
835        }
836
837        let has_remote_key = has_top_level_codex_config_key(&cleaned, key, |t| {
838            !(t.contains("127.0.0.1") || t.contains("localhost"))
839        });
840        if !has_remote_key {
841            prefix.push_str(&format!("{key} = \"{value}\"\n"));
842        }
843    }
844    if prefix.is_empty() && extra_block.is_none() {
845        return cleaned;
846    }
847    // `strip_codex_proxy_entries` already dropped local keys, so prepend fresh
848    // top-level keys ahead of every existing line.
849    let mut out = format!("{prefix}{cleaned}");
850    if let Some(extra_block) = extra_block {
851        if !out.is_empty() && !out.ends_with('\n') {
852            out.push('\n');
853        }
854        if !out.is_empty() && !out.ends_with("\n\n") {
855            out.push('\n');
856        }
857        out.push_str(extra_block);
858    }
859    out
860}
861
862fn render_codex_chatgpt_provider_block(base: &str) -> String {
863    format!(
864        "[model_providers.{CODEX_CHATGPT_PROVIDER_ID}]\n\
865         name = \"OpenAI\"\n\
866         base_url = \"{base}/backend-api/codex\"\n\
867         requires_openai_auth = true\n\
868         supports_websockets = false\n\n"
869    )
870}
871
872/// Remove lean-ctx's own Codex proxy entries from a `config.toml` body: local
873/// top-level proxy URLs, older dead `[env]` URL lines (#554), and the generated
874/// ChatGPT provider block. Custom remote endpoints and profile tables are preserved.
875fn strip_codex_proxy_entries(body: &str) -> String {
876    let lines: Vec<&str> = body.lines().collect();
877    let mut kept: Vec<&str> = Vec::with_capacity(lines.len());
878    let mut current_table: Option<&str> = None;
879    let mut i = 0;
880    while i < lines.len() {
881        let trimmed = lines[i].trim();
882        if is_generated_codex_chatgpt_provider_header(trimmed) {
883            i += 1;
884            while i < lines.len() && !lines[i].trim_start().starts_with('[') {
885                i += 1;
886            }
887            continue;
888        }
889
890        if lines[i].trim_start().starts_with('[') {
891            current_table = Some(trimmed);
892            kept.push(lines[i]);
893            i += 1;
894            continue;
895        }
896
897        if should_strip_codex_proxy_entry(lines[i].trim_start(), current_table) {
898            i += 1;
899            continue;
900        }
901
902        kept.push(lines[i]);
903        i += 1;
904    }
905
906    // Drop an `[env]` header left without any keys after the removal.
907    let mut out: Vec<&str> = Vec::with_capacity(kept.len());
908    let mut i = 0;
909    while i < kept.len() {
910        let trimmed = kept[i].trim();
911        if trimmed == "[env]" {
912            let mut j = i + 1;
913            while j < kept.len() && kept[j].trim().is_empty() {
914                j += 1;
915            }
916            if j >= kept.len() || kept[j].trim_start().starts_with('[') {
917                i = j;
918                continue;
919            }
920        }
921        out.push(kept[i]);
922        i += 1;
923    }
924
925    let mut s = out.join("\n");
926    while s.contains("\n\n\n") {
927        s = s.replace("\n\n\n", "\n\n");
928    }
929    let s = s.trim_end_matches('\n');
930    if s.is_empty() {
931        String::new()
932    } else {
933        format!("{s}\n")
934    }
935}
936
937fn has_top_level_codex_config_key(body: &str, key: &str, predicate: impl Fn(&str) -> bool) -> bool {
938    for line in body.lines() {
939        let t = line.trim_start();
940        if t.starts_with('[') {
941            break;
942        }
943        if toml_assignment_key(t) == Some(key) && predicate(t) {
944            return true;
945        }
946    }
947    false
948}
949
950fn should_strip_codex_proxy_entry(t: &str, current_table: Option<&str>) -> bool {
951    match current_table {
952        None => {
953            is_local_codex_base_url_entry(t, &["openai_base_url", "chatgpt_base_url"])
954                || is_codex_proxy_model_provider_entry(t)
955        }
956        Some("[env]") => is_local_codex_base_url_entry(t, &["OPENAI_BASE_URL", "CHATGPT_BASE_URL"]),
957        _ => false,
958    }
959}
960
961fn is_local_codex_base_url_entry(t: &str, keys: &[&str]) -> bool {
962    toml_assignment_key(t).is_some_and(|key| keys.contains(&key))
963        && (t.contains("127.0.0.1") || t.contains("localhost"))
964}
965
966fn toml_assignment_key(t: &str) -> Option<&str> {
967    let key = t.split_once('=')?.0.trim();
968    if key.is_empty() || key.starts_with('#') {
969        None
970    } else {
971        Some(key)
972    }
973}
974
975fn is_codex_proxy_model_provider_entry(t: &str) -> bool {
976    is_toml_string_assignment(t, "model_provider", CODEX_CHATGPT_PROVIDER_ID)
977        || is_toml_string_assignment(t, "model_provider", "openai")
978}
979
980fn is_toml_string_assignment(t: &str, key: &str, value: &str) -> bool {
981    let Some((lhs, rhs)) = t.split_once('=') else {
982        return false;
983    };
984    if lhs.trim() != key {
985        return false;
986    }
987    let rhs = rhs.split('#').next().unwrap_or(rhs);
988    let normalized: String = rhs.chars().filter(|c| !c.is_whitespace()).collect();
989    normalized == format!("\"{value}\"")
990}
991
992fn is_generated_codex_chatgpt_provider_header(t: &str) -> bool {
993    t == format!("[model_providers.{CODEX_CHATGPT_PROVIDER_ID}]")
994}
995
996fn codex_config_has_local_proxy_entry(body: &str) -> bool {
997    let mut current_table: Option<&str> = None;
998    for line in body.lines() {
999        let t = line.trim_start();
1000        if is_generated_codex_chatgpt_provider_header(line.trim()) {
1001            return true;
1002        }
1003        if t.starts_with('[') {
1004            current_table = Some(line.trim());
1005            continue;
1006        }
1007        match current_table {
1008            None => {
1009                if is_local_codex_base_url_entry(t, &["openai_base_url", "chatgpt_base_url"])
1010                    || is_toml_string_assignment(t, "model_provider", CODEX_CHATGPT_PROVIDER_ID)
1011                {
1012                    return true;
1013                }
1014            }
1015            Some("[env]")
1016                if is_local_codex_base_url_entry(t, &["OPENAI_BASE_URL", "CHATGPT_BASE_URL"]) =>
1017            {
1018                return true;
1019            }
1020            _ => {}
1021        }
1022    }
1023    false
1024}
1025
1026/// True when Codex will authenticate via a **ChatGPT login** (OAuth) rather than
1027/// an API key. An explicit `OPENAI_API_KEY` in the environment opts into API-key
1028/// mode and overrides the stored login.
1029fn codex_uses_chatgpt_login(home: &Path) -> bool {
1030    if std::env::var("OPENAI_API_KEY").is_ok_and(|v| !v.trim().is_empty()) {
1031        return false;
1032    }
1033    let codex_dir = crate::core::home::resolve_codex_dir().unwrap_or_else(|| home.join(".codex"));
1034    auth_is_chatgpt(&codex_dir)
1035}
1036
1037/// True when `<codex_dir>/auth.json` records a ChatGPT/backend auth mode.
1038/// False when the file is missing, unreadable, or in API-key mode.
1039fn auth_is_chatgpt(codex_dir: &Path) -> bool {
1040    let Ok(content) = std::fs::read_to_string(codex_dir.join("auth.json")) else {
1041        return false;
1042    };
1043    let Ok(doc) = serde_json::from_str::<serde_json::Value>(&content) else {
1044        return false;
1045    };
1046    let Some(mode) = doc.get("auth_mode").and_then(|v| v.as_str()) else {
1047        return false;
1048    };
1049    let normalized = mode
1050        .chars()
1051        .filter(char::is_ascii_alphanumeric)
1052        .collect::<String>()
1053        .to_ascii_lowercase();
1054    matches!(
1055        normalized.as_str(),
1056        "chatgpt" | "chatgptauthtokens" | "personalaccesstoken" | "agentidentity"
1057    )
1058}
1059
1060pub fn default_port() -> u16 {
1061    if let Ok(val) = std::env::var("LEAN_CTX_PROXY_PORT")
1062        && let Ok(port) = val.parse::<u16>()
1063    {
1064        return port;
1065    }
1066    let cfg = crate::core::config::Config::load();
1067    if let Some(port) = cfg.proxy_port {
1068        return port;
1069    }
1070    uid_based_port()
1071}
1072
1073/// Derives a deterministic port from the user's UID to avoid collisions
1074/// on multi-user systems. uid 1000 → 4444, uid 1001 → 4445, etc.
1075/// System accounts (uid < 1000) and root always get the base port 4444.
1076fn uid_based_port() -> u16 {
1077    #[cfg(unix)]
1078    {
1079        // SAFETY: `getuid` takes no arguments, always succeeds, and only reads
1080        // the calling process's real UID — no preconditions, no UB.
1081        let uid = unsafe { libc::getuid() } as u16;
1082        let offset = uid.saturating_sub(1000) % 1000;
1083        DEFAULT_PROXY_PORT + offset
1084    }
1085    #[cfg(not(unix))]
1086    {
1087        DEFAULT_PROXY_PORT
1088    }
1089}
1090
1091#[cfg(test)]
1092mod tests {
1093    use super::*;
1094
1095    #[test]
1096    fn uid_port_first_regular_user() {
1097        // uid 1000 (first regular user on most Linux) → base port
1098        assert_eq!(DEFAULT_PROXY_PORT, 4444);
1099    }
1100
1101    #[test]
1102    fn uid_port_no_overflow() {
1103        // Ensure port stays in valid range even with high UIDs
1104        // uid 2999 → offset (2999-1000) % 1000 = 999 → port 5443
1105        let port = DEFAULT_PROXY_PORT + 999;
1106        assert_eq!(port, 5443);
1107        assert!(port < u16::MAX);
1108    }
1109
1110    #[test]
1111    fn uid_port_system_accounts_get_base() {
1112        // uid < 1000 → saturating_sub gives 0 → base port
1113        let uid: u16 = 500;
1114        let offset = uid.saturating_sub(1000) % 1000;
1115        assert_eq!(DEFAULT_PROXY_PORT + offset, DEFAULT_PROXY_PORT);
1116    }
1117
1118    #[test]
1119    fn proxy_timeout_default_200ms() {
1120        if std::env::var("LEAN_CTX_PROXY_TIMEOUT_MS").is_ok() {
1121            return;
1122        }
1123        assert_eq!(proxy_timeout(), std::time::Duration::from_millis(200));
1124    }
1125
1126    #[test]
1127    fn proxy_timeout_is_non_zero() {
1128        let t = proxy_timeout();
1129        assert!(t.as_millis() > 0);
1130    }
1131
1132    #[test]
1133    fn is_proxy_reachable_returns_false_on_unused_port() {
1134        assert!(!is_proxy_reachable(19999));
1135    }
1136
1137    #[test]
1138    fn posix_block_contains_all_provider_env_vars() {
1139        let base = "http://127.0.0.1:4444";
1140        let block = format!(
1141            r#"{PROXY_ENV_START}
1142export ANTHROPIC_BASE_URL="{base}"
1143export OPENAI_BASE_URL="{base}/v1"
1144export GEMINI_API_BASE_URL="{base}"
1145{PROXY_ENV_END}"#
1146        );
1147        assert!(
1148            block.contains("ANTHROPIC_BASE_URL"),
1149            "shell exports must include ANTHROPIC_BASE_URL"
1150        );
1151        assert!(
1152            block.contains("OPENAI_BASE_URL"),
1153            "shell exports must include OPENAI_BASE_URL"
1154        );
1155        assert!(
1156            block.contains("GEMINI_API_BASE_URL"),
1157            "shell exports must include GEMINI_API_BASE_URL"
1158        );
1159    }
1160
1161    #[test]
1162    fn fish_block_contains_all_provider_env_vars() {
1163        let base = "http://127.0.0.1:4444";
1164        let block = format!(
1165            r#"{PROXY_ENV_START}
1166set -gx ANTHROPIC_BASE_URL "{base}"
1167set -gx OPENAI_BASE_URL "{base}/v1"
1168set -gx GEMINI_API_BASE_URL "{base}"
1169{PROXY_ENV_END}"#
1170        );
1171        assert!(block.contains("ANTHROPIC_BASE_URL"));
1172        assert!(block.contains("OPENAI_BASE_URL"));
1173        assert!(block.contains("GEMINI_API_BASE_URL"));
1174    }
1175
1176    #[test]
1177    fn powershell_block_contains_all_provider_env_vars() {
1178        let base = "http://127.0.0.1:4444";
1179        let block = format!(
1180            r#"{PROXY_ENV_START}
1181$env:ANTHROPIC_BASE_URL = "{base}"
1182$env:OPENAI_BASE_URL = "{base}/v1"
1183$env:GEMINI_API_BASE_URL = "{base}"
1184{PROXY_ENV_END}"#
1185        );
1186        assert!(block.contains("ANTHROPIC_BASE_URL"));
1187        assert!(block.contains("OPENAI_BASE_URL"));
1188        assert!(block.contains("GEMINI_API_BASE_URL"));
1189    }
1190
1191    /// The subscription guard reads the process environment; these tests are only
1192    /// meaningful when the test runner itself does not provide an Anthropic key.
1193    fn env_provides_anthropic_key() -> bool {
1194        std::env::var("ANTHROPIC_API_KEY").is_ok_and(|v| !v.trim().is_empty())
1195            || std::env::var("ANTHROPIC_AUTH_TOKEN").is_ok_and(|v| !v.trim().is_empty())
1196    }
1197
1198    /// `claude_state_dir` honours `CLAUDE_CONFIG_DIR`; when set it would escape the
1199    /// temp HOME and read the real settings file, so skip in that case.
1200    fn claude_dir_overridden() -> bool {
1201        std::env::var("CLAUDE_CONFIG_DIR").is_ok_and(|v| !v.trim().is_empty())
1202    }
1203
1204    fn write_claude_settings(home: &Path, json: &str) -> std::path::PathBuf {
1205        let dir = home.join(".claude");
1206        std::fs::create_dir_all(&dir).unwrap();
1207        let path = dir.join("settings.json");
1208        std::fs::write(&path, json).unwrap();
1209        path
1210    }
1211
1212    #[test]
1213    fn api_key_available_true_with_api_key_helper() {
1214        if claude_dir_overridden() {
1215            return;
1216        }
1217        let home = tempfile::tempdir().unwrap();
1218        write_claude_settings(home.path(), r#"{"apiKeyHelper": "echo sk-test"}"#);
1219        assert!(anthropic_api_key_available(home.path()));
1220    }
1221
1222    #[test]
1223    fn api_key_available_true_with_settings_env_key() {
1224        if claude_dir_overridden() {
1225            return;
1226        }
1227        let home = tempfile::tempdir().unwrap();
1228        write_claude_settings(home.path(), r#"{"env": {"ANTHROPIC_API_KEY": "sk-test"}}"#);
1229        assert!(anthropic_api_key_available(home.path()));
1230    }
1231
1232    #[test]
1233    fn api_key_available_false_without_key() {
1234        if env_provides_anthropic_key() || claude_dir_overridden() {
1235            return;
1236        }
1237        let home = tempfile::tempdir().unwrap();
1238        write_claude_settings(home.path(), r#"{"env": {}}"#);
1239        assert!(!anthropic_api_key_available(home.path()));
1240    }
1241
1242    #[test]
1243    fn api_key_available_false_when_no_settings_file() {
1244        if env_provides_anthropic_key() || claude_dir_overridden() {
1245            return;
1246        }
1247        let home = tempfile::tempdir().unwrap();
1248        assert!(!anthropic_api_key_available(home.path()));
1249    }
1250
1251    #[test]
1252    fn subscription_guard_skips_redirect_without_key() {
1253        if env_provides_anthropic_key() || claude_dir_overridden() {
1254            return;
1255        }
1256        let home = tempfile::tempdir().unwrap();
1257        // No settings file → subscription mode, empty current URL → nothing to repair.
1258        install_claude_env_inner(home.path(), 4444, true, false);
1259        let settings = home.path().join(".claude/settings.json");
1260        assert!(
1261            !settings.exists(),
1262            "subscription mode must not write a proxy redirect"
1263        );
1264    }
1265
1266    #[test]
1267    fn subscription_guard_repairs_stale_local_redirect() {
1268        if env_provides_anthropic_key() || claude_dir_overridden() {
1269            return;
1270        }
1271        let home = tempfile::tempdir().unwrap();
1272        let path = write_claude_settings(
1273            home.path(),
1274            r#"{"env": {"ANTHROPIC_BASE_URL": "http://127.0.0.1:4444"}}"#,
1275        );
1276        install_claude_env_inner(home.path(), 4444, true, false);
1277        let after = std::fs::read_to_string(&path).unwrap();
1278        let doc: serde_json::Value = crate::core::jsonc::parse_jsonc(&after).unwrap();
1279        let base = doc
1280            .get("env")
1281            .and_then(|e| e.get("ANTHROPIC_BASE_URL"))
1282            .and_then(|v| v.as_str())
1283            .unwrap_or("");
1284        assert!(
1285            !is_local_lean_ctx_url(base),
1286            "stale local redirect must be repaired in subscription mode, got {base:?}"
1287        );
1288    }
1289
1290    /// API-key mode must STILL route Claude through the proxy (we only protect
1291    /// subscriptions; pay-as-you-go users keep their compression). Uses a real bound
1292    /// port so `is_proxy_reachable` passes, exercising the full production path.
1293    #[test]
1294    fn install_redirects_claude_when_api_key_present() {
1295        if claude_dir_overridden() {
1296            return;
1297        }
1298        let home = tempfile::tempdir().unwrap();
1299        // API-key mode declared in settings.json → deterministic regardless of env.
1300        write_claude_settings(home.path(), r#"{"env": {"ANTHROPIC_API_KEY": "sk-test"}}"#);
1301        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
1302        let port = listener.local_addr().unwrap().port();
1303
1304        install_claude_env_inner(home.path(), port, true, false);
1305
1306        let after = std::fs::read_to_string(home.path().join(".claude/settings.json")).unwrap();
1307        let doc: serde_json::Value = crate::core::jsonc::parse_jsonc(&after).unwrap();
1308        let base = doc
1309            .get("env")
1310            .and_then(|e| e.get("ANTHROPIC_BASE_URL"))
1311            .and_then(|v| v.as_str())
1312            .unwrap_or("");
1313        assert_eq!(
1314            base,
1315            format!("http://127.0.0.1:{port}"),
1316            "API-key mode must route Claude through the proxy"
1317        );
1318    }
1319
1320    /// Shell export: subscription mode keeps OpenAI/Gemini but omits the ANTHROPIC line
1321    /// (replaced by an explanatory comment), so a shell-launched Claude stays on
1322    /// api.anthropic.com.
1323    #[test]
1324    fn shell_export_omits_anthropic_without_key() {
1325        if env_provides_anthropic_key() || claude_dir_overridden() {
1326            return;
1327        }
1328        let home = tempfile::tempdir().unwrap();
1329        std::fs::write(home.path().join(".zshrc"), "# user rc\n").unwrap();
1330        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
1331        let port = listener.local_addr().unwrap().port();
1332
1333        install_shell_exports(home.path(), port, true);
1334
1335        let rc = std::fs::read_to_string(home.path().join(".zshrc")).unwrap();
1336        assert!(
1337            rc.contains(&format!(
1338                "export OPENAI_BASE_URL=\"http://127.0.0.1:{port}/v1\""
1339            )),
1340            "OpenAI export must remain and carry the /v1 suffix (#366)"
1341        );
1342        assert!(
1343            rc.contains(&format!(
1344                "export GEMINI_API_BASE_URL=\"http://127.0.0.1:{port}\""
1345            )),
1346            "Gemini export must remain WITHOUT /v1 (SDK appends /v1beta itself)"
1347        );
1348        assert!(
1349            !rc.contains("export ANTHROPIC_BASE_URL="),
1350            "ANTHROPIC export must be omitted in subscription mode"
1351        );
1352        assert!(
1353            rc.contains(ANTHROPIC_OMITTED_NOTE),
1354            "omission must be explained in the RC block"
1355        );
1356    }
1357
1358    /// Codex CLI config: a fresh install writes the `/v1`-suffixed proxy URL (#366).
1359    #[test]
1360    fn codex_env_writes_v1_suffixed_url() {
1361        let dir = tempfile::tempdir().unwrap();
1362        let codex_dir = dir.path().join(".codex");
1363        std::fs::create_dir_all(&codex_dir).unwrap();
1364        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
1365        let port = listener.local_addr().unwrap().port();
1366
1367        install_codex_env_at(&codex_dir, port, true);
1368
1369        let cfg = std::fs::read_to_string(codex_dir.join("config.toml")).unwrap();
1370        assert!(
1371            cfg.contains(&format!("openai_base_url = \"http://127.0.0.1:{port}/v1\"")),
1372            "Codex config must set top-level openai_base_url with the /v1 suffix, got:\n{cfg}"
1373        );
1374        assert!(
1375            !cfg.contains("[env]") && !cfg.contains("OPENAI_BASE_URL"),
1376            "must not write the dead [env] OPENAI_BASE_URL form (#554), got:\n{cfg}"
1377        );
1378        assert!(
1379            !cfg.contains(CODEX_CHATGPT_PROVIDER_ID),
1380            "API-key mode must not install the ChatGPT-only provider, got:\n{cfg}"
1381        );
1382    }
1383
1384    /// Codex CLI config: a legacy `[env] OPENAI_BASE_URL` line (which Codex never
1385    /// read, #554) is removed and replaced by a top-level `openai_base_url`, even
1386    /// when stale (missing `/v1`). The dead `[env]` table is collapsed.
1387    #[test]
1388    fn codex_env_migrates_legacy_env_entry() {
1389        let dir = tempfile::tempdir().unwrap();
1390        let codex_dir = dir.path().join(".codex");
1391        std::fs::create_dir_all(&codex_dir).unwrap();
1392        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
1393        let port = listener.local_addr().unwrap().port();
1394        std::fs::write(
1395            codex_dir.join("config.toml"),
1396            format!(
1397                "model = \"gpt-5.2\"\n\n[env]\nOPENAI_BASE_URL = \"http://127.0.0.1:{port}\"\n"
1398            ),
1399        )
1400        .unwrap();
1401
1402        install_codex_env_at(&codex_dir, port, true);
1403
1404        let cfg = std::fs::read_to_string(codex_dir.join("config.toml")).unwrap();
1405        assert!(
1406            cfg.contains(&format!("openai_base_url = \"http://127.0.0.1:{port}/v1\"")),
1407            "legacy entry must become a top-level openai_base_url (/v1), got:\n{cfg}"
1408        );
1409        assert!(
1410            cfg.contains("model = \"gpt-5.2\""),
1411            "unrelated config must be preserved"
1412        );
1413        assert!(
1414            !cfg.contains("OPENAI_BASE_URL"),
1415            "dead legacy [env] OPENAI_BASE_URL must be removed, got:\n{cfg}"
1416        );
1417        assert!(
1418            !cfg.contains("[env]"),
1419            "empty [env] table must be collapsed, got:\n{cfg}"
1420        );
1421    }
1422
1423    /// Codex CLI config: a custom non-local `openai_base_url` is never rewritten.
1424    #[test]
1425    fn codex_env_preserves_custom_remote_endpoint() {
1426        let dir = tempfile::tempdir().unwrap();
1427        let codex_dir = dir.path().join(".codex");
1428        std::fs::create_dir_all(&codex_dir).unwrap();
1429        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
1430        let port = listener.local_addr().unwrap().port();
1431        let original = "openai_base_url = \"https://my-gateway.example.com/v1\"\n";
1432        std::fs::write(codex_dir.join("config.toml"), original).unwrap();
1433
1434        install_codex_env_at(&codex_dir, port, true);
1435
1436        let cfg = std::fs::read_to_string(codex_dir.join("config.toml")).unwrap();
1437        assert!(
1438            cfg.contains("https://my-gateway.example.com/v1"),
1439            "custom remote endpoint must be preserved, got:\n{cfg}"
1440        );
1441        assert!(
1442            !cfg.contains("127.0.0.1"),
1443            "proxy URL must not be injected over a custom endpoint"
1444        );
1445    }
1446
1447    #[test]
1448    fn codex_env_chatgpt_mode_writes_backend_urls() {
1449        let dir = tempfile::tempdir().unwrap();
1450        let codex_dir = dir.path().join(".codex");
1451        std::fs::create_dir_all(&codex_dir).unwrap();
1452        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
1453        let port = listener.local_addr().unwrap().port();
1454        std::fs::write(codex_dir.join("config.toml"), "model = \"gpt-5.5\"\n").unwrap();
1455
1456        install_codex_env_at_mode(&codex_dir, port, true, CodexProxyMode::ChatGpt);
1457
1458        let cfg = std::fs::read_to_string(codex_dir.join("config.toml")).unwrap();
1459        assert!(cfg.contains(&format!(
1460            "openai_base_url = \"http://127.0.0.1:{port}/backend-api/codex\""
1461        )));
1462        assert!(cfg.contains(&format!(
1463            "chatgpt_base_url = \"http://127.0.0.1:{port}/backend-api\""
1464        )));
1465        assert!(cfg.contains(&format!("model_provider = \"{CODEX_CHATGPT_PROVIDER_ID}\"")));
1466        assert!(cfg.contains(&format!("[model_providers.{CODEX_CHATGPT_PROVIDER_ID}]")));
1467        assert!(cfg.contains(&format!(
1468            "base_url = \"http://127.0.0.1:{port}/backend-api/codex\""
1469        )));
1470        assert!(cfg.contains("requires_openai_auth = true"));
1471        assert!(cfg.contains("supports_websockets = false"));
1472        assert!(cfg.contains("model = \"gpt-5.5\""));
1473    }
1474
1475    /// `render_codex_config` is idempotent: applying it to an already-configured
1476    /// body yields the identical body (so `install` reports "already configured").
1477    #[test]
1478    fn render_codex_config_is_idempotent() {
1479        let entries = vec![("openai_base_url", "http://127.0.0.1:4444/v1".to_string())];
1480        let once = render_codex_config("model = \"gpt-5.5\"\n", &entries);
1481        let twice = render_codex_config(&once, &entries);
1482        assert_eq!(once, twice, "render must be idempotent");
1483        assert!(once.starts_with("openai_base_url = \"http://127.0.0.1:4444/v1\"\n"));
1484        assert!(once.contains("model = \"gpt-5.5\""));
1485    }
1486
1487    #[test]
1488    fn render_codex_chatgpt_provider_config_is_idempotent() {
1489        let base = "http://127.0.0.1:4444";
1490        let entries = vec![
1491            ("model_provider", CODEX_CHATGPT_PROVIDER_ID.to_string()),
1492            ("openai_base_url", format!("{base}/backend-api/codex")),
1493            ("chatgpt_base_url", format!("{base}/backend-api")),
1494        ];
1495        let block = render_codex_chatgpt_provider_block(base);
1496        let once =
1497            render_codex_config_with_extra_block("model = \"gpt-5.5\"\n", &entries, Some(&block));
1498        let twice = render_codex_config_with_extra_block(&once, &entries, Some(&block));
1499
1500        assert_eq!(once, twice, "ChatGPT provider render must be idempotent");
1501        assert_eq!(once.matches(CODEX_CHATGPT_PROVIDER_ID).count(), 2);
1502        assert!(once.contains("supports_websockets = false"));
1503    }
1504
1505    #[test]
1506    fn render_codex_chatgpt_provider_ignores_nested_model_provider() {
1507        let base = "http://127.0.0.1:4444";
1508        let entries = vec![
1509            ("model_provider", CODEX_CHATGPT_PROVIDER_ID.to_string()),
1510            ("openai_base_url", format!("{base}/backend-api/codex")),
1511            ("chatgpt_base_url", format!("{base}/backend-api")),
1512        ];
1513        let block = render_codex_chatgpt_provider_block(base);
1514        let body = "[profiles.work]\nmodel_provider = \"openai\"\nmodel = \"gpt-5.5\"\n";
1515
1516        let out = render_codex_config_with_extra_block(body, &entries, Some(&block));
1517
1518        let top_level_idx = out
1519            .find(&format!("model_provider = \"{CODEX_CHATGPT_PROVIDER_ID}\""))
1520            .expect("top-level ChatGPT provider present");
1521        let profile_idx = out.find("[profiles.work]").expect("profile table present");
1522        assert!(
1523            top_level_idx < profile_idx,
1524            "ChatGPT model_provider must be top-level, got:\n{out}"
1525        );
1526        assert!(
1527            out.contains("[profiles.work]\nmodel_provider = \"openai\""),
1528            "profile model_provider must be preserved, got:\n{out}"
1529        );
1530    }
1531
1532    #[test]
1533    fn strip_codex_proxy_entries_preserves_nested_model_provider() {
1534        let body = format!(
1535            "model_provider = \"{CODEX_CHATGPT_PROVIDER_ID}\"\n\
1536             openai_base_url = \"http://127.0.0.1:4444/backend-api/codex\"\n\
1537             chatgpt_base_url = \"http://127.0.0.1:4444/backend-api\"\n\n\
1538             {}\n\
1539             [profiles.work]\n\
1540             model_provider = \"openai\"\n\
1541             openai_base_url = \"http://127.0.0.1:9999/v1\"\n",
1542            render_codex_chatgpt_provider_block("http://127.0.0.1:4444")
1543        );
1544
1545        let out = strip_codex_proxy_entries(&body);
1546
1547        assert!(
1548            !out.contains(&format!("[model_providers.{CODEX_CHATGPT_PROVIDER_ID}]")),
1549            "generated provider block must be removed, got:\n{out}"
1550        );
1551        assert!(
1552            out.contains(
1553                "[profiles.work]\nmodel_provider = \"openai\"\nopenai_base_url = \"http://127.0.0.1:9999/v1\""
1554            ),
1555            "profile provider config must be preserved, got:\n{out}"
1556        );
1557    }
1558
1559    #[test]
1560    fn codex_proxy_cleanup_detection_ignores_plain_openai_provider() {
1561        assert!(!codex_config_has_local_proxy_entry(
1562            "model_provider = \"openai\"\n"
1563        ));
1564        assert!(codex_config_has_local_proxy_entry(&format!(
1565            "model_provider = \"{CODEX_CHATGPT_PROVIDER_ID}\"\n"
1566        )));
1567    }
1568
1569    /// `render_codex_config` inserts the key as a *top-level* key (before the first
1570    /// `[table]`), otherwise Codex would read it as a sub-key and ignore it.
1571    #[test]
1572    fn render_codex_config_inserts_before_first_table() {
1573        let body = "model = \"gpt-5.5\"\n\n[features]\nhooks = true\n";
1574        let entries = vec![("openai_base_url", "http://127.0.0.1:4444/v1".to_string())];
1575        let out = render_codex_config(body, &entries);
1576        let key_idx = out.find("openai_base_url").expect("key present");
1577        let table_idx = out.find("[features]").expect("table present");
1578        assert!(
1579            key_idx < table_idx,
1580            "openai_base_url must precede the first table, got:\n{out}"
1581        );
1582    }
1583
1584    /// `auth_is_chatgpt` reflects Codex's `auth.json` auth mode.
1585    #[test]
1586    fn auth_is_chatgpt_detects_login_mode() {
1587        let dir = tempfile::tempdir().unwrap();
1588        let codex_dir = dir.path().join(".codex");
1589        std::fs::create_dir_all(&codex_dir).unwrap();
1590
1591        assert!(!auth_is_chatgpt(&codex_dir), "no auth.json => not chatgpt");
1592
1593        std::fs::write(
1594            codex_dir.join("auth.json"),
1595            r#"{"auth_mode":"apikey","OPENAI_API_KEY":"sk-test"}"#,
1596        )
1597        .unwrap();
1598        assert!(!auth_is_chatgpt(&codex_dir), "apikey mode => not chatgpt");
1599
1600        std::fs::write(
1601            codex_dir.join("auth.json"),
1602            r#"{"auth_mode":"chatgpt","tokens":{"access_token":"x"}}"#,
1603        )
1604        .unwrap();
1605        assert!(auth_is_chatgpt(&codex_dir), "chatgpt mode => true");
1606
1607        for mode in ["chatgptAuthTokens", "personalAccessToken", "agentIdentity"] {
1608            std::fs::write(
1609                codex_dir.join("auth.json"),
1610                format!(r#"{{"auth_mode":"{mode}","tokens":{{"access_token":"x"}}}}"#),
1611            )
1612            .unwrap();
1613            assert!(auth_is_chatgpt(&codex_dir), "{mode} => true");
1614        }
1615    }
1616
1617    /// Shell export: API-key mode includes the ANTHROPIC export (symmetry check).
1618    #[test]
1619    fn shell_export_includes_anthropic_with_key() {
1620        if claude_dir_overridden() {
1621            return;
1622        }
1623        let home = tempfile::tempdir().unwrap();
1624        std::fs::write(home.path().join(".zshrc"), "# user rc\n").unwrap();
1625        write_claude_settings(home.path(), r#"{"env": {"ANTHROPIC_API_KEY": "sk-test"}}"#);
1626        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
1627        let port = listener.local_addr().unwrap().port();
1628
1629        install_shell_exports(home.path(), port, true);
1630
1631        let rc = std::fs::read_to_string(home.path().join(".zshrc")).unwrap();
1632        assert!(
1633            rc.contains(&format!(
1634                "export ANTHROPIC_BASE_URL=\"http://127.0.0.1:{port}\""
1635            )),
1636            "API-key mode must export ANTHROPIC_BASE_URL"
1637        );
1638    }
1639
1640    fn read_pi_models(agent_dir: &Path) -> serde_json::Value {
1641        let raw = std::fs::read_to_string(agent_dir.join("models.json")).unwrap();
1642        crate::core::jsonc::parse_jsonc(&raw).unwrap()
1643    }
1644
1645    /// #361: `proxy enable` must reach Pi/forge, which read `providers.*.baseUrl`
1646    /// from models.json (not ANTHROPIC_BASE_URL). Fresh install wires both
1647    /// providers with the per-SDK URL convention (anthropic bare, openai `/v1`).
1648    #[test]
1649    fn pi_env_fresh_install_writes_both_providers() {
1650        let dir = tempfile::tempdir().unwrap();
1651        let agent_dir = dir.path().join(".pi/agent");
1652        std::fs::create_dir_all(&agent_dir).unwrap();
1653        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
1654        let port = listener.local_addr().unwrap().port();
1655
1656        install_pi_env_at(&agent_dir, port, true, false);
1657
1658        let doc = read_pi_models(&agent_dir);
1659        assert_eq!(
1660            pi_provider_base_url(&doc, "anthropic"),
1661            format!("http://127.0.0.1:{port}"),
1662            "Anthropic gets the bare origin (SDK appends /v1 itself)"
1663        );
1664        assert_eq!(
1665            pi_provider_base_url(&doc, "openai"),
1666            format!("http://127.0.0.1:{port}/v1"),
1667            "OpenAI gets the /v1-suffixed URL (#366)"
1668        );
1669    }
1670
1671    /// A user's custom remote gateway must survive `proxy enable` (no --force):
1672    /// only the untouched provider is pointed at the proxy.
1673    #[test]
1674    fn pi_env_preserves_custom_remote_endpoint_without_force() {
1675        let dir = tempfile::tempdir().unwrap();
1676        let agent_dir = dir.path().join(".pi/agent");
1677        std::fs::create_dir_all(&agent_dir).unwrap();
1678        std::fs::write(
1679            agent_dir.join("models.json"),
1680            r#"{"providers":{"anthropic":{"baseUrl":"https://gw.example.com"}}}"#,
1681        )
1682        .unwrap();
1683        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
1684        let port = listener.local_addr().unwrap().port();
1685
1686        install_pi_env_at(&agent_dir, port, true, false);
1687
1688        let doc = read_pi_models(&agent_dir);
1689        assert_eq!(
1690            pi_provider_base_url(&doc, "anthropic"),
1691            "https://gw.example.com",
1692            "custom remote endpoint must be preserved without --force"
1693        );
1694        assert_eq!(
1695            pi_provider_base_url(&doc, "openai"),
1696            format!("http://127.0.0.1:{port}/v1"),
1697            "the untouched provider still gets the proxy"
1698        );
1699    }
1700
1701    /// `--force` (the `proxy enable --force` path) overrides a custom endpoint.
1702    #[test]
1703    fn pi_env_force_overrides_custom_endpoint() {
1704        let dir = tempfile::tempdir().unwrap();
1705        let agent_dir = dir.path().join(".pi/agent");
1706        std::fs::create_dir_all(&agent_dir).unwrap();
1707        std::fs::write(
1708            agent_dir.join("models.json"),
1709            r#"{"providers":{"anthropic":{"baseUrl":"https://gw.example.com"}}}"#,
1710        )
1711        .unwrap();
1712        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
1713        let port = listener.local_addr().unwrap().port();
1714
1715        install_pi_env_at(&agent_dir, port, true, true);
1716
1717        let doc = read_pi_models(&agent_dir);
1718        assert_eq!(
1719            pi_provider_base_url(&doc, "anthropic"),
1720            format!("http://127.0.0.1:{port}"),
1721            "--force must override the custom endpoint"
1722        );
1723    }
1724
1725    /// A user without Pi installed must not get a Pi config materialized.
1726    #[test]
1727    fn pi_env_skips_when_agent_dir_absent() {
1728        let dir = tempfile::tempdir().unwrap();
1729        let agent_dir = dir.path().join(".pi/agent");
1730
1731        install_pi_env_at(&agent_dir, 19999, true, false);
1732
1733        assert!(
1734            !agent_dir.join("models.json").exists(),
1735            "no Pi config must be created when Pi is not configured"
1736        );
1737    }
1738
1739    /// `disable` reverts only the providers pointing at the local proxy; a
1740    /// user-owned custom endpoint is left untouched.
1741    #[test]
1742    fn pi_uninstall_removes_only_local_endpoints() {
1743        let dir = tempfile::tempdir().unwrap();
1744        let agent_dir = dir.path().join(".pi/agent");
1745        std::fs::create_dir_all(&agent_dir).unwrap();
1746        std::fs::write(
1747            agent_dir.join("models.json"),
1748            r#"{"providers":{"anthropic":{"baseUrl":"http://127.0.0.1:4444"},"openai":{"baseUrl":"https://api.openai.com/v1"}}}"#,
1749        )
1750        .unwrap();
1751
1752        uninstall_pi_env_at(&agent_dir, true);
1753
1754        let doc = read_pi_models(&agent_dir);
1755        assert_eq!(
1756            pi_provider_base_url(&doc, "anthropic"),
1757            "",
1758            "the local proxy endpoint we set must be removed"
1759        );
1760        assert_eq!(
1761            pi_provider_base_url(&doc, "openai"),
1762            "https://api.openai.com/v1",
1763            "a custom endpoint must be preserved on disable"
1764        );
1765    }
1766}