lean-ctx 3.12.13

LeanCTX | OSS: the open-source runtime for the Context Gateway for AI agents. CLI, MCP server, and supported proxy integrations.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
// SPDX-License-Identifier: Apache-2.0
//! LLM proxy plane: liveness, auth, upstream config, env drift, the
//! Claude-subscription conflict.

#[allow(clippy::wildcard_imports)]
use crate::doctor::common::*;
use crate::doctor::{Advice, BOLD, DIM, FixAction, GREEN, Outcome, RED, RST, Severity, YELLOW};

pub(crate) fn proxy_health_outcome() -> Outcome {
    use lean_ctx::core::config::Config;

    let cfg = Config::load();
    let port = crate::proxy_setup::default_port();

    match cfg.proxy_enabled {
        Some(true) => {
            let reachable = {
                use std::net::{IpAddr, Ipv4Addr, SocketAddr, TcpStream};
                let addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), port);
                TcpStream::connect_timeout(&addr, crate::proxy_setup::proxy_timeout()).is_ok()
            };
            // Autostart has no backend on Windows/other platforms, so a missing
            // autostart must never be a hard failure there (#416).
            let supported = lean_ctx::proxy_autostart::is_supported();

            if reachable {
                // Something listens — it only counts when it answers as the
                // lean-ctx proxy (same probe as `gain`/`status`).
                if !crate::proxy_setup::lean_ctx_proxy_responding(port) {
                    return Outcome {
                        ok: false,
                        line: format!(
                            "{BOLD}Proxy{RST}  {RED}port {port} is answered by another process, not the lean-ctx proxy{RST}  {DIM}fix: lean-ctx proxy restart (or set proxy_port){RST}"
                        ),
                    };
                }
                if supported && !lean_ctx::proxy_autostart::is_installed() {
                    // Running, but it won't survive a reboot without autostart.
                    Outcome {
                        ok: true,
                        line: format!(
                            "{BOLD}Proxy{RST}  {GREEN}running on port {port}{RST}  {YELLOW}autostart not installed — persist: lean-ctx proxy enable{RST}"
                        ),
                    }
                } else {
                    Outcome {
                        ok: true,
                        line: format!(
                            "{BOLD}Proxy{RST}  {GREEN}enabled, running on port {port}{RST}"
                        ),
                    }
                }
            } else if supported {
                Outcome {
                    ok: false,
                    line: format!(
                        "{BOLD}Proxy{RST}  {RED}enabled but not reachable on port {port}{RST}  {YELLOW}fix: lean-ctx proxy start{RST}"
                    ),
                }
            } else {
                // Windows/other: no autostart backend, so a stopped proxy is a
                // setup note (start it manually), not a doctor failure (#416).
                Outcome {
                    ok: true,
                    line: format!(
                        "{BOLD}Proxy{RST}  {YELLOW}enabled but not running{RST}  {DIM}autostart unavailable on this platform — start: lean-ctx proxy start{RST}"
                    ),
                }
            }
        }
        Some(false) => Outcome {
            ok: true,
            line: format!(
                "{BOLD}Proxy{RST}  {DIM}disabled (optional feature){RST}  {DIM}enable: lean-ctx proxy enable{RST}"
            ),
        },
        None => Outcome {
            ok: true,
            line: format!(
                "{BOLD}Proxy{RST}  {DIM}not configured{RST}  {DIM}enable: lean-ctx proxy enable{RST}"
            ),
        },
    }
}
/// Detects stale `ANTHROPIC_BASE_URL` in Claude Code settings pointing to the local
/// lean-ctx proxy when the proxy is not enabled. Returns `None` when no mismatch exists
/// (no check needed), `Some(Outcome)` when a stale URL is found.
pub(crate) fn stale_proxy_env_outcome() -> Option<Outcome> {
    use lean_ctx::core::config::Config;

    let home = dirs::home_dir()?;
    let cfg = Config::load();

    if cfg.proxy_enabled == Some(true) {
        return None;
    }

    let settings_dir = lean_ctx::core::editor_registry::claude_state_dir(&home);
    let settings_path = settings_dir.join("settings.json");
    let content = std::fs::read_to_string(&settings_path).ok()?;
    let doc: serde_json::Value = lean_ctx::core::jsonc::parse_jsonc(&content).ok()?;

    let base_url = doc
        .get("env")
        .and_then(|e| e.get("ANTHROPIC_BASE_URL"))
        .and_then(|v| v.as_str())
        .unwrap_or("");

    if base_url.is_empty() {
        return None;
    }

    // #1972: only lean-ctx's own proxy URL is stale. Another local gateway is
    // the user's — flagging it sent them to `proxy cleanup`, which deleted it.
    if !crate::proxy_setup::is_local_lean_ctx_url(base_url) {
        return None;
    }

    let state = if cfg.proxy_enabled == Some(false) {
        "disabled"
    } else {
        "not configured"
    };

    Some(Outcome {
        ok: false,
        line: format!(
            "{BOLD}Proxy env{RST}  {RED}ANTHROPIC_BASE_URL → {base_url} but proxy is {state}{RST}\n\
             {DIM}         Claude Code routes API traffic to lean-ctx, but lean-ctx proxy is {state}.{RST}\n\
             {DIM}         This causes 401 auth failures. Fix:{RST}\n\
             {YELLOW}           lean-ctx proxy cleanup    {DIM}(remove stale URL){RST}\n\
             {YELLOW}           lean-ctx proxy enable     {DIM}(enable the proxy){RST}"
        ),
    })
}
/// Detects the Claude Pro/Max subscription + proxy conflict: the proxy is enabled and
/// Claude Code's `ANTHROPIC_BASE_URL` points at the local proxy, but no Anthropic API
/// key is available. Anthropic does not permit third-party tools to route requests
/// through a subscription login, so that traffic must stay on `api.anthropic.com`.
/// Returns `None` when not applicable, `Some(Outcome)` when the conflict is present.
/// v4 removed automatic model selection. A leftover `[proxy.routing.tiers]`
/// table is still parsed but never routes, so tell the operator once instead
/// of letting them believe requests are being downgraded.
pub(crate) fn removed_routing_tiers_outcome() -> Option<Outcome> {
    let cfg = lean_ctx::core::config::Config::load();
    removed_routing_tiers_line(&cfg.proxy.routing).map(|line| Outcome { ok: false, line })
}

fn removed_routing_tiers_line(rules: &lean_ctx::core::config::RoutingRules) -> Option<String> {
    if rules.tiers.is_empty() {
        return None;
    }
    Some(format!(
        "{BOLD}Proxy routing{RST}  {YELLOW}[proxy.routing.tiers] is ignored{RST}\n\
         {DIM}         LeanCTX no longer picks models automatically; these {} tier entries route nothing.{RST}\n\
         {DIM}         Remove the table, or map exact model names under [proxy.routing.aliases].{RST}",
        rules.tiers.len()
    ))
}

pub(crate) fn proxy_subscription_conflict_outcome() -> Option<(Outcome, Advice)> {
    use lean_ctx::core::config::Config;

    let home = dirs::home_dir()?;
    let cfg = Config::load();

    // Only relevant when the proxy is actively enabled.
    if cfg.proxy_enabled != Some(true) {
        return None;
    }

    let settings_path =
        lean_ctx::core::editor_registry::claude_state_dir(&home).join("settings.json");
    let content = std::fs::read_to_string(&settings_path).ok()?;
    let doc: serde_json::Value = lean_ctx::core::jsonc::parse_jsonc(&content).ok()?;

    let base_url = doc
        .get("env")
        .and_then(|e| e.get("ANTHROPIC_BASE_URL"))
        .and_then(|v| v.as_str())
        .unwrap_or("");

    // No local redirect → nothing to warn about.
    if !crate::proxy_setup::is_local_lean_ctx_url(base_url) {
        return None;
    }

    // API key present → the proxy can forward it, redirect is fine.
    if crate::proxy_setup::anthropic_api_key_available(&home) {
        return None;
    }

    Some(subscription_conflict())
}

/// The Claude auth finding: a Pro/Max login routed to the local proxy
/// without an API key (rc4-220: title, one sentence, named fixes).
pub(crate) fn subscription_conflict() -> (Outcome, Advice) {
    let advice = Advice {
        id: "claude_subscription_via_proxy",
        title: "Claude subscription goes through the proxy".to_string(),
        severity: Severity::Error,
        detail: "Claude Code sends its requests to the LeanCTX proxy without an \
                 ANTHROPIC_API_KEY, so it uses your Pro/Max login, and Anthropic does \
                 not allow third-party tools to route a subscription login."
            .to_string(),
        actions: vec![
            FixAction {
                label: "Turn off the proxy".to_string(),
                changes: "The proxy goes off for every client on this computer (Claude Code, \
                          Codex, shell exports and autostart): Claude Code talks to \
                          api.anthropic.com again, your subscription keeps working and the \
                          ctx_* tools still save tokens."
                    .to_string(),
                commands: vec!["lean-ctx proxy disable".to_string()],
            },
            FixAction {
                label: "Use an API key".to_string(),
                changes: "Set ANTHROPIC_API_KEY where Claude Code starts (your shell profile \
                          or Claude Code's settings.json), then turn the proxy on again. \
                          Requests keep going through the proxy and are billed pay-as-you-go \
                          to your API key."
                    .to_string(),
                commands: vec!["lean-ctx proxy enable".to_string()],
            },
        ],
    };
    let outcome = Outcome {
        ok: false,
        line: format!("{BOLD}Claude auth{RST}  {RED}{}{RST}", advice.title),
    };
    (outcome, advice)
}
pub(crate) fn proxy_upstream_outcome() -> Outcome {
    use lean_ctx::core::config::{Config, ProxyProvider, is_local_proxy_url};

    let cfg = Config::load();
    let checks = [
        (
            "Anthropic",
            "proxy.anthropic_upstream",
            cfg.proxy.resolve_upstream(ProxyProvider::Anthropic),
        ),
        (
            "OpenAI",
            "proxy.openai_upstream",
            cfg.proxy.resolve_upstream(ProxyProvider::OpenAi),
        ),
        (
            "ChatGPT",
            "proxy.chatgpt_upstream",
            cfg.proxy.resolve_upstream(ProxyProvider::ChatGpt),
        ),
        (
            "Gemini",
            "proxy.gemini_upstream",
            cfg.proxy.resolve_upstream(ProxyProvider::Gemini),
        ),
    ];

    let mut custom = Vec::new();
    let mut plaintext = Vec::new();
    for (label, key, resolved) in &checks {
        if is_local_proxy_url(resolved) {
            return Outcome {
                ok: false,
                line: format!(
                    "{BOLD}Proxy upstream{RST}  {RED}{label} upstream points back to local proxy{RST}  {YELLOW}run: lean-ctx config set {key} <url>{RST}"
                ),
            };
        }
        if !resolved.starts_with("http://") && !resolved.starts_with("https://") {
            return Outcome {
                ok: false,
                line: format!(
                    "{BOLD}Proxy upstream{RST}  {RED}invalid {label} upstream{RST}  {YELLOW}set {key} to an http(s) URL{RST}"
                ),
            };
        }
        let is_default = matches!(
            *label,
            "Anthropic" if resolved == "https://api.anthropic.com"
        ) || matches!(
            *label,
            "OpenAI" if resolved == "https://api.openai.com"
        ) || matches!(
            *label,
            "ChatGPT" if resolved == "https://chatgpt.com"
        ) || matches!(
            *label,
            "Gemini" if resolved == "https://generativelanguage.googleapis.com"
        );
        if !is_default {
            custom.push(format!("{label}={resolved}"));
            // Past the loopback guard above, any `http://` is a non-loopback
            // plaintext upstream that only resolved because the user opted in
            // (allow_insecure_http_upstream, #440). Valid config, but worth a
            // standing security reminder.
            if resolved.starts_with("http://") {
                plaintext.push(*label);
            }
        }
    }

    if custom.is_empty() {
        Outcome {
            ok: true,
            line: format!("{BOLD}Proxy upstream{RST}  {GREEN}provider defaults{RST}"),
        }
    } else {
        let mut line = format!(
            "{BOLD}Proxy upstream{RST}  {GREEN}custom: {}{RST}",
            custom.join(", ")
        );
        if !plaintext.is_empty() {
            line.push_str(&format!(
                "  {YELLOW}⚠ plaintext HTTP ({}) — trusted local network only{RST}",
                plaintext.join(", ")
            ));
        }
        Outcome { ok: true, line }
    }
}
/// #449 drift check: warns when the running proxy forwards to a different
/// upstream than the operator expects. Covers both traps — a shell-exported
/// `LEAN_CTX_*_UPSTREAM` that never reached the MCP/service-spawned proxy, and a
/// proxy started with an env override that now masks a later config.toml edit.
/// Returns `None` when the proxy is down or in sync, so the board stays quiet
/// unless there is something actionable.
pub(crate) fn proxy_upstream_drift_outcome() -> Option<Outcome> {
    use lean_ctx::core::config::{
        Config, ProxyProvider, UpstreamDrift, diagnose_drift, env_upstream_override,
    };

    let cfg = Config::load();
    if cfg.proxy_enabled != Some(true) {
        return None;
    }
    let port = crate::proxy_setup::default_port();
    let (live_anthropic, live_openai, live_chatgpt, live_gemini) = proxy_live_upstreams(port)?;
    let disk = cfg.proxy.resolve_all_disk();

    let mut env_not_applied = Vec::new();
    let mut config_not_applied = Vec::new();
    for (label, key, provider, disk_val, live) in [
        (
            "Anthropic",
            "anthropic",
            ProxyProvider::Anthropic,
            &disk.anthropic,
            &live_anthropic,
        ),
        (
            "OpenAI",
            "openai",
            ProxyProvider::OpenAi,
            &disk.openai,
            &live_openai,
        ),
        (
            "ChatGPT",
            "chatgpt",
            ProxyProvider::ChatGpt,
            &disk.chatgpt,
            &live_chatgpt,
        ),
        (
            "Gemini",
            "gemini",
            ProxyProvider::Gemini,
            &disk.gemini,
            &live_gemini,
        ),
    ] {
        let env = env_upstream_override(provider);
        match diagnose_drift(env.as_deref(), disk_val, live) {
            Some(UpstreamDrift::EnvNotApplied) => {
                env_not_applied.push(format!(
                    "{label} → `lean-ctx config set proxy.{key}_upstream`"
                ));
            }
            Some(UpstreamDrift::ConfigNotApplied) => {
                config_not_applied.push(format!("{label} live {live} ≠ config {disk_val}"));
            }
            None => {}
        }
    }

    if env_not_applied.is_empty() && config_not_applied.is_empty() {
        return None;
    }
    let mut line = format!("{BOLD}Proxy upstream drift{RST}");
    if !env_not_applied.is_empty() {
        line.push_str(&format!(
            "  {YELLOW}LEAN_CTX_*_UPSTREAM set in this shell but not reaching the proxy — env never reaches an MCP/service-spawned proxy (#449); persist it (applies live): {}{RST}",
            env_not_applied.join(", ")
        ));
    }
    if !config_not_applied.is_empty() {
        line.push_str(&format!(
            "  {YELLOW}{} — apply: lean-ctx proxy restart{RST}",
            config_not_applied.join("; ")
        ));
    }
    Some(Outcome { ok: false, line })
}

#[cfg(test)]
mod removed_routing_tests {
    #[test]
    fn a_leftover_tier_table_is_reported_and_an_empty_one_is_not() {
        let mut rules = lean_ctx::core::config::RoutingRules::default();
        assert!(super::removed_routing_tiers_line(&rules).is_none());
        rules.tiers.insert("fast".into(), "foundry:phi-4".into());
        let line = super::removed_routing_tiers_line(&rules).expect("reported");
        assert!(line.contains("[proxy.routing.tiers] is ignored"));
    }
}