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
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
// SPDX-License-Identifier: Apache-2.0
//! Codex CLI config.toml proxy wiring.

use std::borrow::Cow;
use std::path::Path;

use super::util::is_proxy_reachable;

pub(crate) fn uninstall_codex_env(home: &Path, quiet: bool) {
    let codex_dir =
        lean_ctx::core::home::resolve_codex_dir().unwrap_or_else(|| home.join(".codex"));
    let config_path = lean_ctx::core::home::resolve_codex_config_path()
        .unwrap_or_else(|| codex_dir.join("config.toml"));
    let existing = match std::fs::read_to_string(&config_path) {
        Ok(s) if !s.trim().is_empty() => s,
        _ => return,
    };

    let has_local = codex_config_has_local_proxy_entry(&existing);
    if !has_local {
        return;
    }

    let cleaned = strip_codex_proxy_entries(&existing);
    let _ = std::fs::write(&config_path, &cleaned);
    if !quiet {
        println!("  ✓ Removed Codex proxy URL(s) from Codex CLI config");
    }
}
/// (Re)apply ONLY the Codex CLI proxy env from the current config — used by
/// `proxy codex-chatgpt on|off` to write/strip Codex's `chatgpt_base_url`
/// immediately after persisting the `[proxy] codex_chatgpt_proxy` opt-in, without
/// touching Claude/Pi/shell exports. The opt-in is resolved from `config.toml`
/// (env-independent), so this works for the env-less managed proxy and every
/// later setup pass too (#603/#616).
pub(crate) fn install_codex_env(home: &Path, port: u16, quiet: bool) -> CodexEnvOutcome {
    let config_dir =
        lean_ctx::core::home::resolve_codex_dir().unwrap_or_else(|| home.join(".codex"));
    let mode = if codex_uses_chatgpt_login(home) {
        CodexProxyMode::ChatGpt
    } else {
        CodexProxyMode::ApiKey
    };
    // The ChatGPT-subscription rail is opt-in (default off): routing it pins a
    // `model_provider`, which scopes Codex history to that provider (#597), so we
    // only write it when the user enabled `[proxy] codex_chatgpt_proxy`. Resolved
    // from config.toml (env-independent) so the env-less managed proxy honors it.
    let chatgpt_proxy = lean_ctx::core::config::Config::load()
        .proxy
        .codex_chatgpt_proxy_enabled();
    let config_path = lean_ctx::core::home::resolve_codex_config_path()
        .unwrap_or_else(|| config_dir.join("config.toml"));
    install_codex_env_at_path(&config_path, port, quiet, mode, chatgpt_proxy)
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum CodexProxyMode {
    ApiKey,
    ChatGpt,
}

pub(crate) const CODEX_CHATGPT_PROVIDER_ID: &str = "leanctx-chatgpt";

/// Testable core of `install_codex_env`: operates on an explicit Codex config
/// directory instead of resolving it from `CODEX_HOME` / the real home.
#[cfg(test)]
pub(crate) fn install_codex_env_at(config_dir: &Path, port: u16, quiet: bool) {
    install_codex_env_at_mode(config_dir, port, quiet, CodexProxyMode::ApiKey, false);
}
#[cfg_attr(not(test), allow(dead_code))] // test helper entrypoint
pub(crate) fn install_codex_env_at_mode(
    config_dir: &Path,
    port: u16,
    quiet: bool,
    mode: CodexProxyMode,
    chatgpt_proxy: bool,
) -> CodexEnvOutcome {
    install_codex_env_at_path(
        &config_dir.join("config.toml"),
        port,
        quiet,
        mode,
        chatgpt_proxy,
    )
}

/// What a Codex-env install pass actually did (#1775).
///
/// `codex chatgpt on` printed its green "enabled" line *before* calling the
/// installer, so a write that was skipped because the proxy was down still read
/// as success. Returning the outcome lets the caller report what happened rather
/// than what it intended.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum CodexEnvOutcome {
    /// Codex's config was rewritten on disk.
    Written,
    /// The desired entries were already present.
    AlreadyConfigured,
    /// ChatGPT login without the opt-in — staying native is the intended state.
    LeftNative,
    /// Nothing written: the proxy was not reachable.
    SkippedProxyDown,
    /// Nothing written: no Codex config directory exists.
    NoConfigDir,
}

fn install_codex_env_at_path(
    config_path: &Path,
    port: u16,
    quiet: bool,
    mode: CodexProxyMode,
    chatgpt_proxy: bool,
) -> CodexEnvOutcome {
    // API-key Codex is billed per token, so routing it through the proxy's `/v1`
    // rail is where compression actually saves money. Codex reads the built-in
    // OpenAI provider's base URL from the top-level `openai_base_url` key
    // (openai/codex#12031).
    //
    // A ChatGPT *subscription* login is flat-rate, so the safe default writes
    // NOTHING and leaves Codex talking directly to chatgpt.com (#597) — an empty
    // `entries` still lets `render_codex_config` auto-heal stale lean-ctx entries.
    //
    // The opt-in `[proxy] codex_chatgpt_proxy` routes only ChatGPT subscription
    // model turns through the generated `leanctx-chatgpt` provider
    // (`/backend-api/codex/responses`, where the proxy strips the responses-lite
    // marker so every model incl. gpt-5.5 works). Keep `chatgpt_base_url` native:
    // Codex Apps MCP and other ChatGPT aux rails require first-party ChatGPT
    // request cookies/headers (otherwise upstream returns
    // `no_biscuit_no_service`), and model-turn compression does not need those
    // rails. Pinning a provider scopes Codex history (#597), so it stays opt-in;
    // flipping it back off strips the entries and restores native history.
    let base = format!("http://127.0.0.1:{port}");
    let entries: Vec<(&str, String)> = match mode {
        CodexProxyMode::ApiKey => vec![("openai_base_url", format!("{base}/v1"))],
        CodexProxyMode::ChatGpt if chatgpt_proxy => {
            vec![("model_provider", CODEX_CHATGPT_PROVIDER_ID.to_string())]
        }
        CodexProxyMode::ChatGpt => Vec::new(),
    };
    let provider_block = match mode {
        CodexProxyMode::ChatGpt if chatgpt_proxy => {
            Some(render_codex_chatgpt_provider_block(&base))
        }
        _ => None,
    };

    // Writing a proxy URL only makes sense against a live proxy.
    if !entries.is_empty() && !is_proxy_reachable(port) {
        if !quiet {
            println!("  Skipping Codex CLI proxy env (proxy not running on port {port})");
        }
        return CodexEnvOutcome::SkippedProxyDown;
    }

    if !config_path.parent().is_some_and(std::path::Path::exists) {
        return CodexEnvOutcome::NoConfigDir;
    }

    let existing = std::fs::read_to_string(config_path).unwrap_or_default();
    let updated = render_codex_config(&existing, &entries, provider_block.as_deref(), port);

    if updated == existing {
        if !quiet {
            // `entries` is empty only for the safe ChatGPT-native default; any
            // written rail (API-key `/v1` or the opt-in ChatGPT provider) means
            // the proxy env is already in place.
            if entries.is_empty() {
                println!("  Codex ChatGPT login — config left native (no lean-ctx proxy entries)");
            } else {
                println!("  Codex CLI proxy env already configured");
            }
        }
        return if entries.is_empty() {
            CodexEnvOutcome::LeftNative
        } else {
            CodexEnvOutcome::AlreadyConfigured
        };
    }

    let _ = std::fs::write(config_path, &updated);
    if !quiet {
        match mode {
            CodexProxyMode::ApiKey => {
                println!("  Configured openai_base_url in Codex CLI config");
            }
            CodexProxyMode::ChatGpt if chatgpt_proxy => println!(
                "  Configured ChatGPT subscription provider in Codex CLI config (model turns compressed; history scoped to lean-ctx provider while enabled)"
            ),
            CodexProxyMode::ChatGpt => println!(
                "  Codex ChatGPT login — removed stale lean-ctx proxy entries (Codex now talks directly to ChatGPT)"
            ),
        }
    }
    // Reaching here means the file changed — including the `entries.is_empty()`
    // case, which strips stale lean-ctx entries. That is a write, not a no-op.
    CodexEnvOutcome::Written
}

/// Point Codex's built-in OpenAI provider at `value` via the documented top-level
/// `openai_base_url`/`chatgpt_base_url` keys. Removes lean-ctx's legacy local proxy
/// entries — the dead `[env] OPENAI_BASE_URL` (#554) and the pre-#597
/// `model_provider = leanctx-chatgpt` + `[model_providers.leanctx-chatgpt]` block
/// (which hid Codex history) — and migrates a stale local value to the canonical
/// one. An `openai_base_url` lean-ctx did not write — remote (#366) or a gateway
/// on another localhost port (#1972) — is preserved and never overwritten.
/// `port` is the proxy port this pass wires; a value on it is lean-ctx's own. Keys are emitted as top-level keys
/// (before the first `[table]`) so Codex actually reads them.
pub(crate) fn render_codex_config(
    existing: &str,
    entries: &[(&str, String)],
    append_block: Option<&str>,
    port: u16,
) -> String {
    // The appended block is the provider itself: any existing copy must go, or
    // the table is declared twice and config.toml stops parsing.
    let provider_block = if append_block.is_some() {
        ProviderBlock::Drop
    } else {
        ProviderBlock::Repoint
    };
    let mut cleaned = strip_owned_codex_entries(existing, Some(port), provider_block);
    if entries.iter().any(|(key, _)| *key == "model_provider") {
        cleaned = strip_top_level_codex_config_key(&cleaned, "model_provider");
        cleaned = strip_top_level_codex_config_key(&cleaned, "chatgpt_base_url");
    }

    let mut prefix = String::new();
    for (key, value) in entries {
        // Whatever survived the strip is not lean-ctx's (remote, or a gateway on
        // another localhost port, #1972): keep it, and never add a second copy —
        // a duplicate key makes the whole config.toml unparseable.
        if !has_top_level_codex_config_key(&cleaned, key, |_| true) {
            prefix.push_str(&format!("{key} = \"{value}\"\n"));
        }
    }
    let mut rendered = if prefix.is_empty() {
        cleaned
    } else {
        // The strip already dropped lean-ctx's own keys, so prepend fresh
        // top-level keys ahead of every existing line.
        format!("{prefix}{cleaned}")
    };
    if let Some(block) = append_block {
        if !rendered.is_empty() && !rendered.ends_with("\n\n") {
            rendered.push('\n');
        }
        rendered.push_str(block);
    }
    rendered
}

pub(crate) fn render_codex_chatgpt_provider_block(base: &str) -> String {
    format!(
        "[model_providers.{CODEX_CHATGPT_PROVIDER_ID}]\n\
         name = \"OpenAI\"\n\
         base_url = \"{base}/backend-api/codex\"\n\
         requires_openai_auth = true\n\
         supports_websockets = false\n"
    )
}

pub(crate) fn strip_top_level_codex_config_key(body: &str, key: &str) -> String {
    let mut out = Vec::new();
    let mut in_top_level = true;
    for line in body.lines() {
        let t = line.trim_start();
        if t.starts_with('[') {
            in_top_level = false;
        }
        if in_top_level && toml_assignment_key(t) == Some(key) {
            continue;
        }
        out.push(line);
    }
    let s = out.join("\n");
    if s.is_empty() { s } else { format!("{s}\n") }
}

/// Remove lean-ctx's own Codex proxy entries from a `config.toml` body: local
/// top-level proxy URLs, older dead `[env]` URL lines (#554), and the generated
/// ChatGPT provider block. Endpoints lean-ctx did not write — remote or on
/// another localhost port (#1972) — and profile tables are preserved.
pub(crate) fn strip_codex_proxy_entries(body: &str) -> String {
    strip_owned_codex_entries(body, None, ProviderBlock::Repoint)
}

/// Where the generated provider points once nothing routes through the proxy.
/// Codex stamps `model_provider = "leanctx-chatgpt"` into every rollout recorded
/// while routing was on and refuses to resume such a thread once that provider
/// id is gone ("Model provider 'leanctx-chatgpt' not found"). Cleanup therefore
/// repoints the block straight at ChatGPT instead of deleting it.
pub(crate) const CODEX_CHATGPT_DIRECT_BASE: &str = "https://chatgpt.com";

/// What a strip pass does with a `[model_providers.leanctx-chatgpt]` block that
/// targets lean-ctx's local proxy. A block aimed anywhere else is the user's
/// (typically the direct one that keeps old threads resumable) and is kept.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum ProviderBlock {
    /// Routing is being (re)installed and appends a fresh block.
    Drop,
    /// Routing is off: keep the provider id, aim it at ChatGPT directly.
    Repoint,
}

/// [`strip_codex_proxy_entries`] that also owns `install_port`, the port an
/// install pass is about to write, so its own previous value is replaced.
fn strip_owned_codex_entries(
    body: &str,
    install_port: Option<u16>,
    provider_block: ProviderBlock,
) -> String {
    let lines: Vec<&str> = body.lines().collect();
    let mut kept: Vec<Cow<'_, str>> = Vec::with_capacity(lines.len());
    let mut current_table: Option<&str> = None;
    let mut i = 0;
    while i < lines.len() {
        let trimmed = lines[i].trim();
        if is_generated_codex_chatgpt_provider_header(trimmed) {
            let end = lines[i + 1..]
                .iter()
                .position(|l| l.trim_start().starts_with('['))
                .map_or(lines.len(), |n| i + 1 + n);
            let block = &lines[i..end];
            let local = block.iter().any(|l| {
                is_local_codex_base_url_entry(l.trim_start(), &["base_url"], install_port)
            });
            match (provider_block, local) {
                (ProviderBlock::Drop, _) => {}
                (ProviderBlock::Repoint, true) => {
                    kept.extend(block.iter().map(|l| {
                        if is_local_codex_base_url_entry(
                            l.trim_start(),
                            &["base_url"],
                            install_port,
                        ) {
                            Cow::Owned(format!(
                                "base_url = \"{CODEX_CHATGPT_DIRECT_BASE}/backend-api/codex\""
                            ))
                        } else {
                            Cow::Borrowed(*l)
                        }
                    }));
                }
                (ProviderBlock::Repoint, false) => {
                    kept.extend(block.iter().map(|l| Cow::Borrowed(*l)));
                }
            }
            i = end;
            continue;
        }

        if lines[i].trim_start().starts_with('[') {
            current_table = Some(trimmed);
            kept.push(Cow::Borrowed(lines[i]));
            i += 1;
            continue;
        }

        if should_strip_codex_proxy_entry(lines[i].trim_start(), current_table, install_port) {
            i += 1;
            continue;
        }

        kept.push(Cow::Borrowed(lines[i]));
        i += 1;
    }
    let kept: Vec<&str> = kept.iter().map(AsRef::as_ref).collect();

    // Drop an `[env]` header left without any keys after the removal.
    let mut out: Vec<&str> = Vec::with_capacity(kept.len());
    let mut i = 0;
    while i < kept.len() {
        let trimmed = kept[i].trim();
        if trimmed == "[env]" {
            let mut j = i + 1;
            while j < kept.len() && kept[j].trim().is_empty() {
                j += 1;
            }
            if j >= kept.len() || kept[j].trim_start().starts_with('[') {
                i = j;
                continue;
            }
        }
        out.push(kept[i]);
        i += 1;
    }

    let mut s = out.join("\n");
    while s.contains("\n\n\n") {
        s = s.replace("\n\n\n", "\n\n");
    }
    let s = s.trim_end_matches('\n');
    if s.is_empty() {
        String::new()
    } else {
        format!("{s}\n")
    }
}

pub(crate) fn has_top_level_codex_config_key(
    body: &str,
    key: &str,
    predicate: impl Fn(&str) -> bool,
) -> bool {
    for line in body.lines() {
        let t = line.trim_start();
        if t.starts_with('[') {
            break;
        }
        if toml_assignment_key(t) == Some(key) && predicate(t) {
            return true;
        }
    }
    false
}

pub(crate) fn should_strip_codex_proxy_entry(
    t: &str,
    current_table: Option<&str>,
    install_port: Option<u16>,
) -> bool {
    match current_table {
        None => {
            is_local_codex_base_url_entry(t, &["openai_base_url", "chatgpt_base_url"], install_port)
                || is_codex_proxy_model_provider_entry(t)
        }
        Some("[env]") => {
            is_local_codex_base_url_entry(t, &["OPENAI_BASE_URL", "CHATGPT_BASE_URL"], install_port)
        }
        _ => false,
    }
}

/// A `key = "url"` line whose URL is lean-ctx's own proxy. A gateway on another
/// localhost port is the user's and must survive cleanup (#1972).
pub(crate) fn is_local_codex_base_url_entry(
    t: &str,
    keys: &[&str],
    install_port: Option<u16>,
) -> bool {
    toml_assignment_key(t).is_some_and(|key| keys.contains(&key))
        && t.split_once('=')
            .and_then(|(_, rhs)| rhs.split('"').nth(1))
            .is_some_and(|url| super::util::is_lean_ctx_url_on(url, install_port))
}

pub(crate) fn toml_assignment_key(t: &str) -> Option<&str> {
    let key = t.split_once('=')?.0.trim();
    if key.is_empty() || key.starts_with('#') {
        None
    } else {
        Some(key)
    }
}

/// True for a `model_provider` pin that lean-ctx itself wrote.
///
/// Only the generated `leanctx-chatgpt` provider qualifies. `model_provider =
/// "openai"` used to be matched here too, but lean-ctx never wrote that value —
/// it writes [`CODEX_CHATGPT_PROVIDER_ID`] — so the branch could only ever
/// delete a pin the user had set themselves, silently, on every setup pass.
pub(crate) fn is_codex_proxy_model_provider_entry(t: &str) -> bool {
    is_toml_string_assignment(t, "model_provider", CODEX_CHATGPT_PROVIDER_ID)
}

pub(crate) fn is_toml_string_assignment(t: &str, key: &str, value: &str) -> bool {
    let Some((lhs, rhs)) = t.split_once('=') else {
        return false;
    };
    if lhs.trim() != key {
        return false;
    }
    let rhs = rhs.split('#').next().unwrap_or(rhs);
    let normalized: String = rhs.chars().filter(|c| !c.is_whitespace()).collect();
    normalized == format!("\"{value}\"")
}

pub(crate) fn is_generated_codex_chatgpt_provider_header(t: &str) -> bool {
    t == format!("[model_providers.{CODEX_CHATGPT_PROVIDER_ID}]")
}

pub(crate) fn codex_config_has_local_proxy_entry(body: &str) -> bool {
    let mut current_table: Option<&str> = None;
    for line in body.lines() {
        let t = line.trim_start();
        if t.starts_with('[') {
            current_table = Some(line.trim());
            continue;
        }
        match current_table {
            None => {
                if is_local_codex_base_url_entry(t, &["openai_base_url", "chatgpt_base_url"], None)
                    || is_toml_string_assignment(t, "model_provider", CODEX_CHATGPT_PROVIDER_ID)
                {
                    return true;
                }
            }
            Some("[env]")
                if is_local_codex_base_url_entry(
                    t,
                    &["OPENAI_BASE_URL", "CHATGPT_BASE_URL"],
                    None,
                ) =>
            {
                return true;
            }
            // The generated provider counts only while it targets the proxy;
            // the direct ChatGPT one routes nothing and must survive cleanup.
            Some(table)
                if is_generated_codex_chatgpt_provider_header(table)
                    && is_local_codex_base_url_entry(t, &["base_url"], None) =>
            {
                return true;
            }
            _ => {}
        }
    }
    false
}

/// True when Codex will authenticate via a **ChatGPT login** (OAuth) rather than
/// an API key. An explicit `OPENAI_API_KEY` in the environment opts into API-key
/// mode and overrides the stored login.
pub(crate) fn codex_uses_chatgpt_login(home: &Path) -> bool {
    if std::env::var("OPENAI_API_KEY").is_ok_and(|v| !v.trim().is_empty()) {
        return false;
    }
    let codex_dir =
        lean_ctx::core::home::resolve_codex_dir().unwrap_or_else(|| home.join(".codex"));
    auth_is_chatgpt(&codex_dir)
}

/// True when Codex should remain on its native/Codex-backend auth rail.
///
/// Codex treats a legacy file without `auth_mode` as ChatGPT auth unless it
/// contains `OPENAI_API_KEY`. Mirror that fallback: otherwise browser OAuth
/// tokens get sent to the API-key `/v1` rail and OpenAI rejects them with a
/// misleading `api.responses.write` scope error (#1685). Missing, unreadable,
/// malformed, or unknown auth state also stays native; only positive API-key
/// evidence may select the `/v1` rail.
pub(crate) fn auth_is_chatgpt(codex_dir: &Path) -> bool {
    let Ok(content) = std::fs::read_to_string(codex_dir.join("auth.json")) else {
        return true;
    };
    let Ok(doc) = serde_json::from_str::<serde_json::Value>(&content) else {
        return true;
    };
    match doc.get("auth_mode").and_then(|v| v.as_str()) {
        Some(mode) => {
            let normalized = mode
                .chars()
                .filter(char::is_ascii_alphanumeric)
                .collect::<String>()
                .to_ascii_lowercase();
            !matches!(
                normalized.as_str(),
                "apikey" | "bedrockapikey" | "bedrockaccesskeys"
            )
        }
        None => doc
            .get("OPENAI_API_KEY")
            .and_then(|v| v.as_str())
            .is_none_or(|v| v.trim().is_empty()),
    }
}