From 4d5b584e39cf90a4afaab8af46be2f69dcd914b6 Mon Sep 17 00:00:00 2001 From: salmonik Date: Thu, 19 Nov 2026 11:30:47 +0100 Subject: 0.12.0: provider is a type + URL, plus a config file - --provider opencode|openai-compatible; opencode keeps the session header, openai-compatible needs a base URL and sends none - config file at ~/.config/agent686/config.toml (provider, url, model, flags) - fix the doubled-dash --provider help message --- src/config.rs | 195 +++++++++++++++++++++++++++++++++++++++++--------------- src/main.rs | 46 +++++++------ src/provider.rs | 37 ++++++----- 3 files changed, 186 insertions(+), 92 deletions(-) (limited to 'src') diff --git a/src/config.rs b/src/config.rs index 1d259c7..a314f38 100644 --- a/src/config.rs +++ b/src/config.rs @@ -1,18 +1,57 @@ use std::path::PathBuf; -pub const DEFAULT_BASE_URL: &str = "https://opencode.ai/inference/go/openai/v1"; +use serde::Deserialize; + 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), -]; +/// 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 { @@ -26,28 +65,24 @@ 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. + /// 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 { - /// CLI flags win over environment variables, which win over defaults. - #[allow(clippy::too_many_arguments)] - pub fn resolve( - model: Option, - base_url: Option, - yolo: bool, - provider: Option, - lenient: bool, - system_ca: bool, - ) -> Result { - let config = Self::resolve_lenient(model, base_url, yolo, provider, lenient, system_ca); + 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 {}", @@ -56,34 +91,55 @@ impl Config { .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 so `--doctor` can report - /// the missing key instead of failing to start. - pub fn resolve_lenient( - model: Option, - base_url: Option, - yolo: bool, - provider: Option, - 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 + /// 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")) - .unwrap_or_else(|| preset_url.to_string()); + .or(file.url.clone()) + .unwrap_or_else(|| provider.default_url().to_string()); - let model = model + let model = cli + .model + .clone() .or_else(|| env_nonempty("AGENT686_MODEL")) - .or_else(|| (!preset_model.is_empty()).then(|| preset_model.to_string())) + .or(file.model.clone()) .unwrap_or_else(|| DEFAULT_MODEL.to_string()); Config { @@ -91,9 +147,16 @@ impl Config { base_url, model, session: String::new(), - yolo, - lenient: lenient || preset_lenient, - system_ca: system_ca || env_nonempty("AGENT686_SYSTEM_CA").is_some(), + 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), } } @@ -102,8 +165,38 @@ impl Config { } } -pub fn provider_names() -> Vec<&'static str> { - PRESETS.iter().map(|(name, ..)| *name).collect() +/// 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 { diff --git a/src/main.rs b/src/main.rs index 8f53d9e..a591c07 100644 --- a/src/main.rs +++ b/src/main.rs @@ -38,8 +38,9 @@ OPTIONS: --show [ID] print a transcript (most recent if no ID) and exit --doctor check key, directories, provider and model, then exit --yolo approve every tool call without asking - --provider preset: opencode-go, openai, openrouter, ollama, - llamacpp, vllm + --provider opencode (requires the session header, default) or + openai-compatible (any OpenAI-style endpoint; pair with + --base-url, e.g. Ollama http://localhost:11434/v1) --lenient tolerate providers that omit [DONE]/usage --system-ca verify TLS with the system trust store -V, --version print the version and exit @@ -201,7 +202,9 @@ fn take_value(iter: &mut impl Iterator, flag: &str) -> Result Err(format!("{flag} needs a value (use --{flag}=… for a value starting with -)")), + _ => Err(format!( + "{flag} needs a value (use {flag}=… for a value starting with -)" + )), } } @@ -233,28 +236,23 @@ fn run(args: Args) { return; } + let cli = agent686::config::Cli { + model: args.model.clone(), + base_url: args.base_url.clone(), + provider: args.provider.clone(), + yolo: args.yolo, + lenient: args.lenient, + system_ca: args.system_ca, + }; + if args.doctor { - let mut config = Config::resolve_lenient( - args.model, - args.base_url, - args.yolo, - args.provider, - args.lenient, - args.system_ca, - ); + let mut config = Config::resolve_lenient(&cli); // `/models` needs the session header too, even though this is not a turn. config.session = session::new_id(); std::process::exit(doctor::run(&config, args.json)); } - let mut cfg = match Config::resolve( - args.model, - args.base_url, - args.yolo, - args.provider, - args.lenient, - args.system_ca, - ) { + let mut cfg = match Config::resolve(&cli) { Ok(cfg) => cfg, Err(message) => { eprintln!("agent686: {message}"); @@ -708,7 +706,7 @@ fn ago(modified: SystemTime) -> String { /// `--yolo` with no approval and no undo is how a transcript ends up deleting a /// checkout. Git is the documented undo, so `--yolo` needs a repository unless -/// asked twice. `$HOME` and `/` are refused outright. +/// allowed. `$HOME` and `/` are refused outright. fn refuse_yolo(cfg: &Config) { if !cfg.yolo { return; @@ -720,19 +718,19 @@ fn refuse_yolo(cfg: &Config) { let home = std::env::var_os("HOME").map(PathBuf::from); let at_home = home.as_deref() == Some(cwd.as_path()); let at_root = cwd.parent().is_none(); - if (at_home || at_root) && std::env::var_os("AGENT686_ALLOW_HOME").is_none() { + if (at_home || at_root) && !cfg.allow_home { eprintln!( "agent686: refusing --yolo in {} — the model can overwrite anything here. \ - Run inside a project, or set AGENT686_ALLOW_HOME=1.", + Run inside a project, or set allow_home in the config.", cwd.display() ); std::process::exit(2); } - if !in_git_repo(&cwd) && std::env::var_os("AGENT686_ALLOW_NOGIT").is_none() { + if !in_git_repo(&cwd) && !cfg.allow_nogit { eprintln!( "agent686: refusing --yolo outside a git repository ({} has no .git), so \ - there is no undo. Run git init, or set AGENT686_ALLOW_NOGIT=1.", + there is no undo. Run git init, or set allow_nogit in the config.", cwd.display() ); std::process::exit(2); diff --git a/src/provider.rs b/src/provider.rs index c03dea2..b5dca62 100644 --- a/src/provider.rs +++ b/src/provider.rs @@ -256,17 +256,18 @@ pub fn chat_with( return Err(Error::Aborted); } - let sent = agent + let mut request = agent .post(&cfg.endpoint()) .header("Content-Type", "application/json") .header("Accept", "text/event-stream") .header("Authorization", format!("Bearer {}", cfg.api_key)) - .header("User-Agent", concat!("agent686/", env!("CARGO_PKG_VERSION"))) - // Required by OpenCode Go: stable per conversation, used for - // routing and prompt caching. Without it the gateway answers - // 400 MissingSessionID. - .header("x-opencode-session", &cfg.session) - .send(bytes.clone()); + .header("User-Agent", concat!("agent686/", env!("CARGO_PKG_VERSION"))); + // OpenCode requires a stable per-conversation id for routing and + // prompt caching; a plain OpenAI-compatible endpoint must not get it. + if cfg.provider.needs_session_header() { + request = request.header("x-opencode-session", &cfg.session); + } + let sent = request.send(bytes.clone()); let mut response = match sent { Ok(response) => response, @@ -570,14 +571,15 @@ struct FunctionDelta { pub fn summarize(cfg: &Config, messages: &[Value]) -> Result { let body = serde_json::json!({ "model": cfg.model, "messages": messages, "stream": false }); let bytes = serde_json::to_vec(&body).map_err(|e| Error::Transport(e.to_string()))?; - let mut response = agent(cfg.system_ca) + let mut request = agent(cfg.system_ca) .post(&cfg.endpoint()) .header("Content-Type", "application/json") .header("Authorization", format!("Bearer {}", cfg.api_key)) - .header("User-Agent", concat!("agent686/", env!("CARGO_PKG_VERSION"))) - .header("x-opencode-session", &cfg.session) - .send(bytes) - .map_err(|e| Error::Transport(e.to_string()))?; + .header("User-Agent", concat!("agent686/", env!("CARGO_PKG_VERSION"))); + if cfg.provider.needs_session_header() { + request = request.header("x-opencode-session", &cfg.session); + } + let mut response = request.send(bytes).map_err(|e| Error::Transport(e.to_string()))?; let status = response.status().as_u16(); let text = response @@ -605,13 +607,14 @@ pub fn models(cfg: &Config) -> Result, Error> { let agent = agent(cfg.system_ca); let url = format!("{}/models", cfg.base_url.trim_end_matches('/')); - let mut response = agent + let mut request = agent .get(&url) .header("Authorization", format!("Bearer {}", cfg.api_key)) - .header("User-Agent", concat!("agent686/", env!("CARGO_PKG_VERSION"))) - .header("x-opencode-session", &cfg.session) - .call() - .map_err(|e| Error::Transport(e.to_string()))?; + .header("User-Agent", concat!("agent686/", env!("CARGO_PKG_VERSION"))); + if cfg.provider.needs_session_header() { + request = request.header("x-opencode-session", &cfg.session); + } + let mut response = request.call().map_err(|e| Error::Transport(e.to_string()))?; let status = response.status().as_u16(); let body = response -- cgit v1.2.3