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 { 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, pub base_url: Option, pub provider: Option, 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 { 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, url: Option, model: Option, lenient: Option, system_ca: Option, yolo: Option, allow_home: Option, allow_nogit: Option, } fn config_path() -> Option { 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 { 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")) }