summaryrefslogtreecommitdiffstats
path: root/src/doctor.rs
blob: 8baf1f71e8db5b6bc1df6225b3bfadb09be351ee (plain) (blame)
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
use std::path::Path;

use serde_json::json;

use crate::config::{self, Config, KeySource};
use crate::provider;
use crate::session;

/// Checks the things that are cheap to check but expensive to discover mid-turn.
/// Returns the process exit code; with `json` it prints one JSON object instead
/// of the human-readable rows.
pub fn run(cfg: &Config, json: bool) -> i32 {
    let mut checks: Vec<(String, bool, String)> = Vec::new();
    let mut failed = false;
    let mut record = |label: &str, ok: bool, detail: String| {
        if !ok {
            failed = true;
        }
        checks.push((label.to_string(), ok, detail));
    };

    match config::key_source() {
        KeySource::Env => record("key", true, "present in OPENCODE_API_KEY".into()),
        KeySource::File(path) => {
            let mut detail = format!("present in {}", path.display());
            use std::os::unix::fs::PermissionsExt;
            if std::fs::metadata(&path)
                .map(|m| m.permissions().mode() & 0o077 != 0)
                .unwrap_or(false)
            {
                detail.push_str(" (readable by other users; chmod 600 it)");
            }
            record("key", true, detail);
        }
        KeySource::Missing => record("key",
            false,
            "missing — set OPENCODE_API_KEY or write ~/.config/agent686/key".into(),
        ),
    }

    let sessions = session::sessions_dir();
    match probe_dir(&sessions) {
        Ok(()) => record("sessions", true, sessions.display().to_string()),
        Err(error) => record(
            "sessions",
            false,
            format!("{}: {error}", sessions.display()),
        ),
    }

    let history = session::data_root().join("history");
    match std::fs::read_to_string(&history) {
        Ok(text) => record(
            "history",
            true,
            format!("{} ({} entries)", history.display(), text.lines().count()),
        ),
        Err(_) => record(
            "history",
            true,
            format!("{} (new)", history.display()),
        ),
    }

    record("provider", true, cfg.base_url.clone());
    record("model", true, cfg.model.clone());

    if cfg.api_key.is_empty() {
        record("auth", false, "skipped: no key".into());
    } else {
        match provider::models(cfg) {
            Ok(models) => {
                record("auth", true, format!("ok — {} models visible", models.len()));
                if models.iter().any(|id| id == &cfg.model) {
                    record("model known", true, "yes".into());
                } else {
                    record(
                        "model known",
                        false,
                        "no — the provider does not list this id; pick another with --model".into(),
                    );
                }
            }
            Err(error) => record("auth", false, error.to_string()),
        }
    }

    if json {
        let checks_json: serde_json::Map<String, serde_json::Value> = checks
            .iter()
            .map(|(label, ok, detail)| (label.clone(), json!({ "ok": ok, "detail": detail })))
            .collect();
        let doc = json!({
            "version": env!("CARGO_PKG_VERSION"),
            "arch": std::env::consts::ARCH,
            "os": std::env::consts::OS,
            "ok": !failed,
            "checks": checks_json,
        });
        println!("{}", serde_json::to_string(&doc).unwrap_or_default());
    } else {
        println!(
            "agent686 {} · {} · {}",
            env!("CARGO_PKG_VERSION"),
            std::env::consts::ARCH,
            std::env::consts::OS
        );
        println!();
        for (label, ok, detail) in &checks {
            println!("{:<13} {:<4} {detail}", label, if *ok { "ok" } else { "FAIL" });
        }
        println!();
        if failed {
            println!("some checks failed");
        } else {
            println!("all checks passed");
        }
    }

    if failed {
        1
    } else {
        0
    }
}

fn probe_dir(dir: &Path) -> std::io::Result<()> {
    std::fs::create_dir_all(dir)?;
    let probe = dir.join(".doctor-probe");
    std::fs::write(&probe, b"ok")?;
    std::fs::remove_file(probe)
}