lean-ctx 3.12.4

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
// SPDX-License-Identifier: Apache-2.0
//! `lean-ctx cockpit` for a person on a terminal: reuse this data dir's
//! running Cockpit server or start one in the background, wait until it is
//! healthy (bounded), let it start the Cockpit runtime, open the browser at
//! the requested view and return the prompt. `lean-ctx cockpit stop` ends
//! the background server by its recorded PID.
//!
//! The bearer token travels only to the browser (in the URL handed to the
//! opener) — it is never printed, and a pinned `--auth-token` reaches the
//! server child through its environment, not its argv.

use std::io::{Read, Write};
use std::net::TcpStream;
use std::time::{Duration, Instant};

use crate::dashboard::cockpit::CockpitUnavailable;
use crate::dashboard::{self, launch};

/// How long a fresh server may take until it answers healthy.
const START_TIMEOUT: Duration = Duration::from_secs(20);
/// How long the first page may take: it starts the Cockpit runtime, whose
/// own handshake is bounded at 10 s.
const WARM_TIMEOUT: Duration = Duration::from_secs(15);

/// What opening the Cockpit came to.
#[derive(Debug)]
pub(crate) enum Outcome {
    /// The browser was sent to the Cockpit served on `port`.
    Opened { port: u16, base_path: String },
    /// The Cockpit runtime cannot be served; nothing was opened.
    Unavailable(CockpitUnavailable),
    /// The server could not be reused or started; one line why.
    Failed(String),
}

/// A person on a terminal: stdout and stderr are terminals and no CI runs.
pub(crate) fn interactive() -> bool {
    use std::io::IsTerminal as _;
    std::io::stdout().is_terminal()
        && std::io::stderr().is_terminal()
        && !lean_ctx::core::telemetry_consent::ci_detected(lean_ctx::core::host_env::var)
}

fn flag_value<'a>(rest: &'a [String], names: &[&str]) -> Option<&'a str> {
    rest.iter().find_map(|arg| {
        let (flag, value) = arg.split_once('=')?;
        names.contains(&flag).then_some(value)
    })
}

/// The server child's arguments: always foreground, never opening a
/// browser, on the planned port; the user's host, subpath, auth mode and
/// project carried over. The token is not among them (a token file's path
/// is: the child reads the file itself).
pub(crate) fn child_args(rest: &[String], port: u16) -> Vec<String> {
    let mut args = vec![
        "cockpit".to_string(),
        "--foreground".to_string(),
        "--no-open".to_string(),
        format!("--port={port}"),
    ];
    let mut iter = rest.iter();
    while let Some(arg) = iter.next() {
        let flag = arg.split_once('=').map_or(arg.as_str(), |(flag, _)| flag);
        match flag {
            "--host" | "-H" | "--base-path" | "--prefix" | "--auth" if arg.contains('=') => {
                args.push(arg.clone());
            }
            "--no-auth" => args.push(arg.clone()),
            "--project" | "--auth-token-file" if arg.contains('=') => args.push(arg.clone()),
            "--project" | "--auth-token-file" => {
                if let Some(value) = iter.next() {
                    args.push(format!("{flag}={value}"));
                }
            }
            _ => {}
        }
    }
    args
}

/// The normalized subpath a new server will serve under.
fn base_path_of(rest: &[String]) -> String {
    flag_value(rest, &["--base-path", "--prefix"])
        .map(str::to_string)
        .or_else(|| std::env::var("LEAN_CTX_DASHBOARD_BASE_PATH").ok())
        .map(|b| dashboard::base_path::normalize(&b))
        .unwrap_or_default()
}

/// Open the Cockpit at `view` (a hash route; `None` = start page).
pub(crate) fn open(view: Option<&str>, rest: &[String]) -> Outcome {
    if let Err(reason) = lean_ctx::core::intelligence_runtime::cockpit::available_or_installed() {
        return Outcome::Unavailable(reason);
    }
    lean_ctx::core::layout_pin::heal();
    let requested = super::port_flag(rest).or_else(|| {
        std::env::var("LEAN_CTX_PORT")
            .ok()
            .and_then(|p| p.trim().parse().ok())
    });
    let (plan, record) = launch::plan_now(requested);
    let started = matches!(
        plan,
        launch::Plan::Replace { .. } | launch::Plan::Start { .. }
    );
    let (port, base_path) = match plan {
        launch::Plan::Reuse {
            port,
            other_version,
        } => {
            if let Some(version) = other_version {
                eprintln!(
                    "\x1b[33m⚠\x1b[0m The running Cockpit server is version {version} (this is {}); \
                     restart it to update: lean-ctx cockpit stop, then lean-ctx cockpit",
                    env!("CARGO_PKG_VERSION")
                );
            }
            let base = record
                .filter(|r| r.port == port)
                .map_or_else(|| base_path_of(rest), |r| r.base_path);
            (port, base)
        }
        launch::Plan::Replace { port, .. } => {
            if let Some(record) = record
                && !launch::stop_instance(&record)
            {
                return Outcome::Failed(format!(
                    "The previous Cockpit server (PID {}) did not stop; stop it, then retry.",
                    record.pid
                ));
            }
            if let Err(message) = start_server(rest, port) {
                return Outcome::Failed(message);
            }
            (port, base_path_of(rest))
        }
        launch::Plan::Start { port, skipped } => {
            if let Some(skipped) = skipped {
                eprintln!(
                    "\x1b[2mPort {skipped} is taken (another program or LeanCTX data dir) — the Cockpit uses {port}.\x1b[0m"
                );
            }
            if let Err(message) = start_server(rest, port) {
                return Outcome::Failed(message);
            }
            (port, base_path_of(rest))
        }
        launch::Plan::PortTaken { port, by } => {
            return Outcome::Failed(launch::port_taken_message(port, &by));
        }
    };
    if let Some(reason) = warm(port, &base_path) {
        // Nothing is opened, so a server started for this request is not
        // left behind: hidden, it would retry the Cockpit on every later
        // request it receives (#2203).
        if started
            && let Some(record) = launch::read_record().filter(|r| r.port == port && r.detached)
        {
            launch::stop_instance(&record);
        }
        return Outcome::Unavailable(reason);
    }
    let token = dashboard::load_saved_token();
    let url = dashboard::launch_url(port, &base_path, token.as_deref(), view);
    dashboard::open_dashboard_url(&url, dashboard::resolve_open_mode(None));
    Outcome::Opened { port, base_path }
}

/// Start the server in the background on `port` and wait until it answers
/// healthy. `Err` is the one line to show.
fn start_server(rest: &[String], port: u16) -> Result<(), String> {
    let exe = std::env::current_exe()
        .map_err(|e| format!("Cannot locate the lean-ctx binary to start the Cockpit: {e}"))?;
    let mut command = std::process::Command::new(exe);
    command
        .args(child_args(rest, port))
        .env(launch::DETACHED_ENV, "1");
    if let Some(token) = flag_value(rest, &["--auth-token", "--token"]) {
        command.env("LEAN_CTX_HTTP_TOKEN", token);
    }
    // Its own process group: closing this terminal (or the shell's job
    // control hanging up its jobs) does not take the server down.
    #[cfg(unix)]
    {
        use std::os::unix::process::CommandExt as _;
        command.process_group(0);
    }
    let mut child = lean_ctx::ipc::process::spawn_detached(
        &mut command,
        lean_ctx::ipc::process::DetachedStderr::Null,
    )
    .map_err(|e| format!("Could not start the Cockpit server: {e}"))?;
    let healthy = || {
        matches!(
            launch::probe("127.0.0.1", port, dashboard::load_saved_token().as_deref()),
            launch::Health::Healthy { .. }
        )
    };
    let deadline = Instant::now() + START_TIMEOUT;
    loop {
        if healthy() {
            return Ok(());
        }
        if let Ok(Some(status)) = child.try_wait() {
            // It may have found an instance that started meanwhile.
            return if healthy() {
                Ok(())
            } else {
                Err(format!(
                    "The Cockpit server ended at start ({status}). See why: lean-ctx cockpit --foreground"
                ))
            };
        }
        if Instant::now() >= deadline {
            return Err(format!(
                "The Cockpit server (PID {}) did not answer within {} s. See why: lean-ctx cockpit stop, then lean-ctx cockpit --foreground",
                child.id(),
                START_TIMEOUT.as_secs()
            ));
        }
        std::thread::sleep(Duration::from_millis(150));
    }
}

/// The reason code in the server's Cockpit-unavailable page, if `page` is one.
pub(crate) fn unavailable_reason(page: &str) -> Option<CockpitUnavailable> {
    let code = page.split("data-reason=\"").nth(1)?.split('"').next()?;
    [
        CockpitUnavailable::NotInstalled,
        CockpitUnavailable::VerificationFailed,
        CockpitUnavailable::StartFailed,
        CockpitUnavailable::Disabled,
        CockpitUnavailable::SourceBuild,
    ]
    .into_iter()
    .find(|reason| reason.as_str() == code)
}

/// Load the start page once, so the server starts the Cockpit runtime
/// before the browser arrives; the reason when it shows the unavailable
/// page instead. A slow or failed load is left to the browser.
fn warm(port: u16, base_path: &str) -> Option<CockpitUnavailable> {
    let address = launch::probe_address("127.0.0.1", port);
    let mut stream = TcpStream::connect_timeout(&address, Duration::from_secs(2)).ok()?;
    let _ = stream.set_read_timeout(Some(WARM_TIMEOUT));
    let _ = stream.set_write_timeout(Some(Duration::from_secs(2)));
    let request = format!(
        "GET {base_path}/ HTTP/1.1\r\nHost: localhost:{port}\r\nAccept: text/html\r\nConnection: close\r\n\r\n"
    );
    stream.write_all(request.as_bytes()).ok()?;
    let mut page = Vec::new();
    let mut buf = [0u8; 8192];
    while page.len() < 64 * 1024 {
        match stream.read(&mut buf) {
            Ok(0) | Err(_) => break,
            Ok(n) => page.extend_from_slice(&buf[..n]),
        }
    }
    unavailable_reason(&String::from_utf8_lossy(&page))
}

/// The one line after a successful open; never the token.
pub(crate) fn opened_line(view: Option<&str>, port: u16, base_path: &str) -> String {
    match view.filter(|v| !v.is_empty()) {
        Some(view) => format!("Opened the Cockpit \u{2192} #{view}"),
        None => format!("Opened the Cockpit \u{2192} http://localhost:{port}{base_path}/"),
    }
}

/// The one line when the Cockpit runtime cannot be served: the reason and
/// the action for it. The terminal alternative is [`TERMINAL_HINT`], added
/// once by the caller.
pub(crate) fn unavailable_line(reason: CockpitUnavailable) -> &'static str {
    match reason {
        CockpitUnavailable::NotInstalled => {
            "Cockpit not installed \u{2014} lean-ctx cockpit install"
        }
        other => other.message(),
    }
}

/// The terminal alternative after a Cockpit that could not be opened. Plain
/// `lean-ctx gain` would try to open the Cockpit again first.
pub(crate) const TERMINAL_HINT: &str = "In the terminal: lean-ctx gain --terminal";

/// `lean-ctx cockpit stop`: end this data dir's background server by its
/// recorded PID. The exit code.
pub(crate) fn stop() -> i32 {
    let Some(record) = launch::read_record() else {
        println!("No Cockpit server is recorded for this data dir.");
        return 0;
    };
    if !record.process_alive() {
        launch::remove_record_of(record.pid);
        println!(
            "The recorded Cockpit server (PID {}) is no longer running.",
            record.pid
        );
        return 0;
    }
    if !record.detached {
        eprintln!(
            "The Cockpit server on port {} runs in a terminal (PID {}) — stop it there with Ctrl+C.",
            record.port, record.pid
        );
        return 1;
    }
    if launch::stop_instance(&record) {
        println!(
            "Stopped the Cockpit server (PID {}, port {}).",
            record.pid, record.port
        );
        0
    } else {
        eprintln!(
            "Could not stop the Cockpit server (PID {}); it is still running.",
            record.pid
        );
        1
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn args(list: &[&str]) -> Vec<String> {
        list.iter().map(|s| (*s).to_string()).collect()
    }

    #[test]
    fn the_child_runs_in_the_foreground_on_the_planned_port_without_the_token() {
        let child = child_args(
            &args(&[
                "--host=127.0.0.1",
                "--base-path=/c",
                "--auth-token=secret-value",
                "--token=other",
                "--no-auth",
                "--project",
                "/work/repo",
                "--port",
                "9999",
                "--vscode",
                "--auth-token-file",
                "/run/token",
            ]),
            4100,
        );
        assert_eq!(
            child,
            args(&[
                "cockpit",
                "--foreground",
                "--no-open",
                "--port=4100",
                "--host=127.0.0.1",
                "--base-path=/c",
                "--no-auth",
                "--project=/work/repo",
                "--auth-token-file=/run/token",
            ])
        );
        assert!(!child.iter().any(|a| a.contains("secret")));
    }

    #[test]
    fn the_unavailable_page_reason_is_read_back() {
        for reason in [
            CockpitUnavailable::NotInstalled,
            CockpitUnavailable::StartFailed,
            CockpitUnavailable::SourceBuild,
        ] {
            let page = crate::dashboard::cockpit::unavailable_page(reason);
            assert_eq!(unavailable_reason(&page), Some(reason));
        }
        assert_eq!(unavailable_reason("<html>the Cockpit app</html>"), None);
    }

    #[test]
    fn lines_name_the_route_or_the_fix_and_never_a_token() {
        assert_eq!(
            opened_line(Some("savings"), 3333, ""),
            "Opened the Cockpit \u{2192} #savings"
        );
        assert_eq!(
            opened_line(None, 3334, "/c"),
            "Opened the Cockpit \u{2192} http://localhost:3334/c/"
        );
        assert_eq!(
            unavailable_line(CockpitUnavailable::NotInstalled),
            "Cockpit not installed \u{2014} lean-ctx cockpit install"
        );
        assert!(unavailable_line(CockpitUnavailable::Disabled).contains("cockpit install"));
    }

    const ALL: [CockpitUnavailable; 5] = [
        CockpitUnavailable::NotInstalled,
        CockpitUnavailable::VerificationFailed,
        CockpitUnavailable::StartFailed,
        CockpitUnavailable::Disabled,
        CockpitUnavailable::SourceBuild,
    ];

    /// #2203: `lean-ctx cockpit` printed "…; in the terminal: lean-ctx gain"
    /// and then "In the terminal: lean-ctx gain --terminal". The reason line
    /// names no terminal command; the hint follows exactly once.
    #[test]
    fn the_terminal_alternative_is_named_once() {
        for reason in ALL {
            let line = unavailable_line(reason);
            assert!(!line.contains("lean-ctx gain"), "{reason:?}: {line}");
            let output = format!("{line}\n{TERMINAL_HINT}");
            assert_eq!(output.matches("lean-ctx gain").count(), 1, "{output}");
        }
        assert_eq!(TERMINAL_HINT, "In the terminal: lean-ctx gain --terminal");
    }

    /// #2203: a Cockpit that did not start was reported as "retried
    /// automatically" with no way to see why. The line says what happened
    /// and names a command that shows the cause; a source build is not told
    /// to run an install it cannot do.
    #[test]
    fn each_reason_names_what_happened_and_an_action_that_works() {
        let start = unavailable_line(CockpitUnavailable::StartFailed);
        assert!(start.contains("installed but did not start"), "{start}");
        assert!(start.contains("lean-ctx cockpit --foreground"), "{start}");
        assert!(!start.contains("retried"), "{start}");
        let source = unavailable_line(CockpitUnavailable::SourceBuild);
        assert!(source.starts_with("Source build"), "{source}");
        assert!(!source.contains("cockpit install"), "{source}");
        for reason in ALL {
            let line = unavailable_line(reason);
            assert!(line.contains("lean-ctx ") || reason == CockpitUnavailable::SourceBuild);
        }
    }
}