aboutsummaryrefslogtreecommitdiffstats
path: root/src/config.rs
blob: 1d259c7b07233d86ed3973ddf69cb1c783c32b99 (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
133
134
135
136
137
138
139
140
141
142
use std::path::PathBuf;

pub const DEFAULT_BASE_URL: &str = "https://opencode.ai/inference/go/openai/v1";
pub const DEFAULT_MODEL: &str = "deepseek-v4.1-flash";

/// (name, base_url, default_model, lenient). Local gateways that omit `[DONE]`
/// or `usage` are marked lenient so a truncated-looking stream is not an error.
const PRESETS: &[(&str, &str, &str, bool)] = &[
    ("opencode-go", DEFAULT_BASE_URL, DEFAULT_MODEL, false),
    ("openai", "https://api.openai.com/v1", "gpt-4o-mini", false),
    ("openrouter", "https://openrouter.ai/api/v1", "", false),
    ("ollama", "http://localhost:11434/v1", "", true),
    ("llamacpp", "http://localhost:8080/v1", "", true),
    ("vllm", "http://localhost:8000/v1", "", true),
];

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum KeySource {
    Env,
    File(PathBuf),
    Missing,
}

#[derive(Debug, Clone)]
pub struct Config {
    pub base_url: String,
    pub api_key: String,
    pub model: String,
    /// Session id, sent to the provider as `x-opencode-session`. Filled in once
    /// the session exists.
    pub session: String,
    pub yolo: bool,
    /// Tolerate providers that omit `[DONE]`/`usage`/`finish_reason`.
    pub lenient: bool,
    /// Verify TLS against the system trust store instead of bundled roots.
    pub system_ca: bool,
}

impl Config {
    /// CLI flags win over environment variables, which win over defaults.
    #[allow(clippy::too_many_arguments)]
    pub fn resolve(
        model: Option<String>,
        base_url: Option<String>,
        yolo: bool,
        provider: Option<String>,
        lenient: bool,
        system_ca: bool,
    ) -> Result<Config, String> {
        let config = Self::resolve_lenient(model, base_url, yolo, provider, lenient, system_ca);
        if config.api_key.is_empty() {
            return Err(format!(
                "no API key: set OPENCODE_API_KEY or write one to {}",
                key_file()
                    .map(|path| path.display().to_string())
                    .unwrap_or_else(|| "~/.config/agent686/key".into())
            ));
        }
        Ok(config)
    }

    /// Same as `resolve`, but tolerates a missing key so `--doctor` can report
    /// the missing key instead of failing to start.
    pub fn resolve_lenient(
        model: Option<String>,
        base_url: Option<String>,
        yolo: bool,
        provider: Option<String>,
        lenient: bool,
        system_ca: bool,
    ) -> Config {
        // Presets fill the base URL and a default model; explicit values win.
        let provider = provider.or_else(|| env_nonempty("AGENT686_PROVIDER"));
        let (preset_url, preset_model, preset_lenient) = provider
            .as_deref()
            .and_then(|name| PRESETS.iter().find(|(n, ..)| *n == name))
            .map(|(_, url, model, lenient)| (*url, *model, *lenient))
            .unwrap_or((DEFAULT_BASE_URL, "", false));

        let base_url = base_url
            .or_else(|| env_nonempty("AGENT686_BASE_URL"))
            .unwrap_or_else(|| preset_url.to_string());

        let model = model
            .or_else(|| env_nonempty("AGENT686_MODEL"))
            .or_else(|| (!preset_model.is_empty()).then(|| preset_model.to_string()))
            .unwrap_or_else(|| DEFAULT_MODEL.to_string());

        Config {
            api_key: api_key().unwrap_or_default(),
            base_url,
            model,
            session: String::new(),
            yolo,
            lenient: lenient || preset_lenient,
            system_ca: system_ca || env_nonempty("AGENT686_SYSTEM_CA").is_some(),
        }
    }

    pub fn endpoint(&self) -> String {
        format!("{}/chat/completions", self.base_url.trim_end_matches('/'))
    }
}

pub fn provider_names() -> Vec<&'static str> {
    PRESETS.iter().map(|(name, ..)| *name).collect()
}

fn env_nonempty(key: &str) -> Option<String> {
    std::env::var(key).ok().filter(|v| !v.trim().is_empty())
}

pub fn key_source() -> KeySource {
    if env_nonempty("OPENCODE_API_KEY").is_some() {
        return KeySource::Env;
    }
    if let Some(path) = key_file() {
        if let Ok(key) = std::fs::read_to_string(&path) {
            if !key.trim().is_empty() {
                return KeySource::File(path);
            }
        }
    }
    KeySource::Missing
}

/// The key comes from the environment first, then from a file, so a key never
/// has to live in shell history.
fn api_key() -> Result<String, String> {
    match key_source() {
        KeySource::Env => Ok(env_nonempty("OPENCODE_API_KEY").unwrap_or_default()),
        KeySource::File(path) => Ok(std::fs::read_to_string(path)
            .map(|key| key.trim().to_string())
            .unwrap_or_default()),
        KeySource::Missing => Err("no API key".into()),
    }
}

fn key_file() -> Option<PathBuf> {
    let home = std::env::var_os("HOME")?;
    Some(PathBuf::from(home).join(".config/agent686/key"))
}