summaryrefslogtreecommitdiffstats
path: root/src/config.rs
blob: b781637700e9a57181be886248f72438e4862e5b (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
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";

#[derive(Debug, Clone)]
pub struct Config {
    pub base_url: String,
    pub api_key: String,
    pub model: String,
    pub session: String,
}

impl Config {
    /// CLI flags win over environment variables, which win over defaults.
    pub fn resolve(
        model: Option<String>,
        base_url: Option<String>,
        session: Option<String>,
    ) -> Result<Config, String> {
        Ok(Config {
            api_key: api_key()?,
            base_url: base_url
                .or_else(|| env_nonempty("AGENT686_BASE_URL"))
                .unwrap_or_else(|| DEFAULT_BASE_URL.to_string()),
            model: model
                .or_else(|| env_nonempty("AGENT686_MODEL"))
                .unwrap_or_else(|| DEFAULT_MODEL.to_string()),
            session: session.unwrap_or_else(crate::session::new_id),
        })
    }

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

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

/// The key comes from the environment first, then from a file, so a key never
/// has to live in shell history or in a process listing.
fn api_key() -> Result<String, String> {
    if let Some(k) = env_nonempty("OPENCODE_API_KEY") {
        return Ok(k.trim().to_string());
    }
    if let Some(path) = key_file() {
        if let Ok(k) = std::fs::read_to_string(&path) {
            let k = k.trim().to_string();
            if !k.is_empty() {
                return Ok(k);
            }
        }
    }
    Err(format!(
        "no API key: set OPENCODE_API_KEY or write one to {}",
        key_file()
            .map(|p| p.display().to_string())
            .unwrap_or_else(|| "~/.config/agent686/key".into())
    ))
}

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