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, 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, } impl Config { /// CLI flags win over environment variables, which win over defaults. pub fn resolve( model: Option, base_url: Option, yolo: bool, ) -> Result { let config = Self::resolve_lenient(model, base_url, yolo); 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, base_url: Option, yolo: bool) -> Config { Config { api_key: api_key().unwrap_or_default(), 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: String::new(), yolo, } } pub fn endpoint(&self) -> String { format!("{}/chat/completions", self.base_url.trim_end_matches('/')) } } fn env_nonempty(key: &str) -> Option { 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 { 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 { let home = std::env::var_os("HOME")?; Some(PathBuf::from(home).join(".config/agent686/key")) }