summaryrefslogtreecommitdiffstats
path: root/src/config.rs
blob: a314f38726e10d942816364023d6d4326f140bf3 (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
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
use std::path::PathBuf;

use serde::Deserialize;

pub const DEFAULT_MODEL: &str = "deepseek-v4.1-flash";

/// What kind of provider this is. Both speak OpenAI-compatible chat
/// completions; OpenCode additionally requires the `x-opencode-session` header.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Provider {
    OpenCode,
    OpenAICompatible,
}

impl Provider {
    pub fn from_name(name: &str) -> Option<Provider> {
        match name {
            "opencode" | "opencode-go" => Some(Provider::OpenCode),
            "openai" | "openai-compatible" | "openai_compatible" => {
                Some(Provider::OpenAICompatible)
            }
            _ => None,
        }
    }

    pub fn name(self) -> &'static str {
        match self {
            Provider::OpenCode => "opencode",
            Provider::OpenAICompatible => "openai-compatible",
        }
    }

    pub fn default_url(self) -> &'static str {
        match self {
            Provider::OpenCode => "https://opencode.ai/inference/go/openai/v1",
            Provider::OpenAICompatible => "",
        }
    }

    pub fn needs_session_header(self) -> bool {
        self == Provider::OpenCode
    }
}

/// The command-line values that override config and environment.
#[derive(Debug, Default)]
pub struct Cli {
    pub model: Option<String>,
    pub base_url: Option<String>,
    pub provider: Option<String>,
    pub yolo: bool,
    pub lenient: bool,
    pub system_ca: bool,
}

#[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` when it is
    /// OpenCode. Filled in once the session exists.
    pub session: String,
    pub provider: Provider,
    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,
    /// Permit `--yolo` in `$HOME` or `/`.
    pub allow_home: bool,
    /// Permit `--yolo` outside a git repository.
    pub allow_nogit: bool,
}

impl Config {
    pub fn resolve(cli: &Cli) -> Result<Config, String> {
        let config = Self::resolve_lenient(cli);
        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())
            ));
        }
        if config.provider == Provider::OpenAICompatible && config.base_url.is_empty() {
            return Err(
                "the openai-compatible provider needs a base URL: set --base-url, \
                 AGENT686_BASE_URL, or `url` in the config file"
                    .to_string(),
            );
        }
        Ok(config)
    }

    /// Same as `resolve`, but tolerates a missing key and URL so `--doctor` can
    /// report them instead of failing to start.
    pub fn resolve_lenient(cli: &Cli) -> Config {
        let file = load_file();

        let provider = cli
            .provider
            .clone()
            .or_else(|| env_nonempty("AGENT686_PROVIDER"))
            .or(file.provider.clone())
            .and_then(|name| Provider::from_name(&name))
            .unwrap_or_else(|| {
                // Unknown names fall back to OpenCode, with a note.
                if let Some(bad) = cli
                    .provider
                    .clone()
                    .or_else(|| env_nonempty("AGENT686_PROVIDER"))
                    .or(file.provider.clone())
                {
                    eprintln!(
                        "agent686: unknown provider type `{bad}` (expected opencode or \
                         openai-compatible); using opencode"
                    );
                }
                Provider::OpenCode
            });

        let base_url = cli
            .base_url
            .clone()
            .or_else(|| env_nonempty("AGENT686_BASE_URL"))
            .or(file.url.clone())
            .unwrap_or_else(|| provider.default_url().to_string());

        let model = cli
            .model
            .clone()
            .or_else(|| env_nonempty("AGENT686_MODEL"))
            .or(file.model.clone())
            .unwrap_or_else(|| DEFAULT_MODEL.to_string());

        Config {
            api_key: api_key().unwrap_or_default(),
            base_url,
            model,
            session: String::new(),
            provider,
            yolo: cli.yolo || file.yolo.unwrap_or(false),
            lenient: cli.lenient || file.lenient.unwrap_or(false),
            system_ca: cli.system_ca
                || env_nonempty("AGENT686_SYSTEM_CA").is_some()
                || file.system_ca.unwrap_or(false),
            allow_home: env_nonempty("AGENT686_ALLOW_HOME").is_some()
                || file.allow_home.unwrap_or(false),
            allow_nogit: env_nonempty("AGENT686_ALLOW_NOGIT").is_some()
                || file.allow_nogit.unwrap_or(false),
        }
    }

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

/// The `~/.config/agent686/config.toml` shape. Every key is optional.
#[derive(Debug, Default, Deserialize)]
struct FileConfig {
    provider: Option<String>,
    url: Option<String>,
    model: Option<String>,
    lenient: Option<bool>,
    system_ca: Option<bool>,
    yolo: Option<bool>,
    allow_home: Option<bool>,
    allow_nogit: Option<bool>,
}

fn config_path() -> Option<PathBuf> {
    if let Some(path) = std::env::var_os("AGENT686_CONFIG") {
        return Some(PathBuf::from(path));
    }
    let home = std::env::var_os("HOME")?;
    Some(PathBuf::from(home).join(".config/agent686/config.toml"))
}

fn load_file() -> FileConfig {
    let Some(path) = config_path() else {
        return FileConfig::default();
    };
    match std::fs::read_to_string(&path) {
        Ok(text) => toml::from_str(&text).unwrap_or_else(|error| {
            eprintln!("agent686: {}: {error}", path.display());
            FileConfig::default()
        }),
        Err(_) => FileConfig::default(),
    }
}

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"))
}