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 --- CHANGELOG.md | 18 ++++++ Cargo.lock | 109 ++++++++++++++++++++++++++----- Cargo.toml | 5 +- README.md | 31 +++++++-- src/config.rs | 195 +++++++++++++++++++++++++++++++++++++++++--------------- src/main.rs | 46 +++++++------ src/provider.rs | 37 ++++++----- tests/cli.rs | 2 +- tests/config.rs | 128 +++++++++++++++++++++++++++++-------- tests/loop.rs | 21 ++++++ tests/mock.rs | 3 + 11 files changed, 454 insertions(+), 141 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6d1a673..d3e68e7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,24 @@ break the interface, **PATCH** for bug fixes. file, and the tool schemas the model sees. Anything a script or a resumed session could depend on counts as API. +## 0.12.0 + +### Changed (breaking) +- `--provider` now takes a *type* instead of a preset name: `opencode` (the + default, sends the required `x-opencode-session` header) or + `openai-compatible` (any OpenAI-style endpoint, no session header). The base + URL comes from `--base-url`, `AGENT686_BASE_URL`, or the config file; an + openai-compatible provider with no URL is rejected. + +### Added +- Config file at `~/.config/agent686/config.toml` (or `AGENT686_CONFIG`): + `provider`, `url`, `model`, `lenient`, `system_ca`, `yolo`, `allow_home`, + `allow_nogit`. Precedence is CLI flag > environment variable > config file > + default. + +### Fixed +- `--provider --help` printed a doubled-dash suggestion (`----provider=`). + ## 0.11.0 ### Added diff --git a/Cargo.lock b/Cargo.lock index e206be7..48f449c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -17,6 +17,7 @@ dependencies = [ "regex", "serde", "serde_json", + "toml", "unicode-width", "ureq", ] @@ -44,9 +45,9 @@ checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" [[package]] name = "bytes" -version = "1.12.1" +version = "1.12.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" +checksum = "776dfebd015e2d8732c684a2c71003674ccb49457b539b9e82151ba38e96dd7c" [[package]] name = "cc" @@ -166,6 +167,12 @@ dependencies = [ "litrs", ] +[[package]] +name = "equivalent" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" + [[package]] name = "errno" version = "0.3.15" @@ -204,6 +211,12 @@ dependencies = [ "wasi", ] +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" + [[package]] name = "http" version = "1.5.0" @@ -220,6 +233,16 @@ version = "1.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown", +] + [[package]] name = "itoa" version = "1.0.19" @@ -406,9 +429,9 @@ dependencies = [ [[package]] name = "regex" -version = "1.13.1" +version = "1.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f020237b6c8eed93db2e2cb53c00c60a8e1bc73da7d073199a1180401450218d" +checksum = "9807af0e638c12e753aa1b4e601791bf2a8f71274023c8bbeec12fc149950857" dependencies = [ "aho-corasick", "memchr", @@ -418,9 +441,9 @@ dependencies = [ [[package]] name = "regex-automata" -version = "0.4.18" +version = "0.4.19" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2" +checksum = "41d60ef07df457506a0a1a2073112eb4aae5733dbd2813c3da77d1b0fd441158" dependencies = [ "aho-corasick", "memchr", @@ -429,9 +452,9 @@ dependencies = [ [[package]] name = "regex-syntax" -version = "0.8.11" +version = "0.8.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" +checksum = "d902046e6a28a1e4c3cab97258a0ce11e994903f01c2d97a9447a0b3df85f4f6" [[package]] name = "ring" @@ -523,7 +546,7 @@ dependencies = [ "security-framework", "security-framework-sys", "webpki-root-certs", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -639,6 +662,15 @@ dependencies = [ "zmij", ] +[[package]] +name = "serde_spanned" +version = "1.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c187e0a369471c550af028cba56d4f4fa2a489ad28151ae95a4d340a2a8b782" +dependencies = [ + "serde_core", +] + [[package]] name = "shlex" version = "2.0.1" @@ -700,9 +732,9 @@ checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e" [[package]] name = "smallvec" -version = "1.16.5" +version = "1.16.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "149309498a5f7334b12ddae0cad8aba81ce785fe91755068867e017cf98fee46" +checksum = "3244542535d5de959d90ec55d1b5ff0fd2bb7b1310223907d5f11932847f7b59" [[package]] name = "subtle" @@ -752,6 +784,45 @@ dependencies = [ "syn 3.0.10", ] +[[package]] +name = "toml" +version = "1.2.1+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d5755c51863cdac711f1956baf8eb9588e060755f7d3c4c979e70ea1e1f32cd7" +dependencies = [ + "indexmap", + "serde_core", + "serde_spanned", + "toml_datetime", + "toml_parser", + "toml_writer", + "winnow", +] + +[[package]] +name = "toml_datetime" +version = "1.1.3+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "173f25c883cd2176a2d8212155638c0a60d484a9d84546d270866f40f56b6e49" +dependencies = [ + "serde_core", +] + +[[package]] +name = "toml_parser" +version = "1.1.5+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "baa693a8032d7e1cada7d0041e96126df243179ff061456783ac7f12bda4744c" +dependencies = [ + "winnow", +] + +[[package]] +name = "toml_writer" +version = "1.2.0+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "009dbb7700f11c55ef83aebbe4c0e9cf1f1ac0844bd8d6f00dc38f302026e13a" + [[package]] name = "unicode-ident" version = "1.0.27" @@ -830,9 +901,9 @@ checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" [[package]] name = "webpki-root-certs" -version = "1.0.11" +version = "1.0.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e49d0e65abc00c142e8f9428da991da9f1a250c39be97459901eb12b9b49f62a" +checksum = "293198dcebfb821155b5092ab94b5a82ff180eddd7241df3bd6e66a4ffd1a585" dependencies = [ "rustls-pki-types", ] @@ -868,7 +939,7 @@ version = "0.1.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" dependencies = [ - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -965,11 +1036,17 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" +[[package]] +name = "winnow" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8c3b93199df0ab874cdf0c6a94f0a0dc3423fe41f1cafb62b8bd7b1deb277aef" + [[package]] name = "zeroize" -version = "1.9.1" +version = "1.9.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879" +checksum = "85ccff8a4805aba1eaa4cd4afcd49f7557dd2cf5fd79ffc37f8959466effc5aa" [[package]] name = "zlib-rs" diff --git a/Cargo.toml b/Cargo.toml index 44d2fee..465673f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "agent686" -version = "0.11.0" +version = "0.12.0" edition = "2021" description = "A small coding agent for Debian-class Linux" publish = false @@ -11,8 +11,9 @@ serde_json = "1" ureq = { version = "3", features = ["rustls", "platform-verifier"] } libc = "0.2" crossterm = "0.29.0" -regex = "1.13.1" +regex = "1.13.2" unicode-width = "0.2.3" +toml = "1.2.1" [profile.release] strip = true diff --git a/README.md b/README.md index 58eca18..00c8d1d 100644 --- a/README.md +++ b/README.md @@ -55,11 +55,32 @@ export OPENCODE_API_KEY=... # or write it to ~/.config/agent686/key ./agent686 --yolo "..." # approve every tool call ``` -Provider is OpenCode Go, `chat/completions`, model `deepseek-v4.1-flash` by -default; `--provider ollama|openai|openrouter|vllm|llamacpp` switches to another -OpenAI-compatible endpoint, with `--lenient` for servers that omit `[DONE]`. -`HTTPS_PROXY`/`NO_PROXY` are honoured. Every request carries a stable -`x-opencode-session` header, which the service uses for routing and prompt caching. +The provider is a *type* plus a URL, both speaking OpenAI-compatible chat +completions: + +- `opencode` (default) — `https://opencode.ai/inference/go/openai/v1`, and it + requires a stable `x-opencode-session` header per conversation. +- `openai-compatible` — any endpoint (Ollama, llama.cpp, vLLM, OpenRouter, …), + given via `--base-url`/`AGENT686_BASE_URL`/config `url`; no session header. + +`--lenient` tolerates servers that omit `[DONE]`/`usage`; `HTTPS_PROXY`/`NO_PROXY` +are honoured. + +## Config file + +`~/.config/agent686/config.toml` (override with `AGENT686_CONFIG`) sets defaults +the CLI and environment can then override: + +```toml +provider = "opencode" # or "openai-compatible" +url = "http://localhost:11434/v1" # for openai-compatible +model = "deepseek-v4.1-flash" +lenient = false +system_ca = false +yolo = false +allow_home = false # permit --yolo in $HOME or / +allow_nogit = false # permit --yolo outside a git repository +``` In a terminal: up/down walks history, bracketed paste arrives as one block (multi-line is fine), ctrl-c abandons the line, ctrl-d exits. `/undo` reverts the 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 diff --git a/tests/cli.rs b/tests/cli.rs index 72edbd1..37546b1 100644 --- a/tests/cli.rs +++ b/tests/cli.rs @@ -92,7 +92,7 @@ fn yolo_is_refused_in_the_home_directory() { assert_eq!(output.status.code(), Some(2), "{output:?}"); let stderr = String::from_utf8_lossy(&output.stderr); assert!(stderr.contains("refusing --yolo"), "{stderr}"); - assert!(stderr.contains("AGENT686_ALLOW_HOME"), "{stderr}"); + assert!(stderr.contains("allow_home"), "{stderr}"); } #[test] diff --git a/tests/config.rs b/tests/config.rs index 05361d3..c090fbf 100644 --- a/tests/config.rs +++ b/tests/config.rs @@ -1,28 +1,106 @@ -use agent686::config::Config; +use std::fs; + +use agent686::config::{Cli, Config, Provider}; + +static ENV_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(()); + +fn clear_env() { + for key in [ + "AGENT686_CONFIG", + "AGENT686_PROVIDER", + "AGENT686_BASE_URL", + "AGENT686_MODEL", + "AGENT686_ALLOW_HOME", + "AGENT686_ALLOW_NOGIT", + "AGENT686_SYSTEM_CA", + ] { + std::env::remove_var(key); + } +} + +fn cli(provider: Option<&str>, base_url: Option<&str>) -> Cli { + Cli { + model: None, + base_url: base_url.map(String::from), + provider: provider.map(String::from), + yolo: false, + lenient: false, + system_ca: false, + } +} + +fn temp_dir(tag: &str) -> std::path::PathBuf { + let dir = std::env::temp_dir().join(format!("agent686-config-{tag}-{}", std::process::id())); + let _ = fs::remove_dir_all(&dir); + fs::create_dir_all(&dir).unwrap(); + dir +} + +#[test] +fn provider_type_selects_url_and_session_header() { + let _env = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + clear_env(); + + let opencode = Config::resolve_lenient(&cli(Some("opencode"), None)); + assert_eq!(opencode.provider, Provider::OpenCode); + assert!(opencode.base_url.contains("opencode.ai"), "{}", opencode.base_url); + assert!(opencode.provider.needs_session_header()); + + let compatible = Config::resolve_lenient(&cli( + Some("openai-compatible"), + Some("http://localhost:11434/v1"), + )); + assert_eq!(compatible.provider, Provider::OpenAICompatible); + assert_eq!(compatible.base_url, "http://localhost:11434/v1"); + assert!(!compatible.provider.needs_session_header()); +} + +#[test] +fn openai_compatible_without_a_url_is_rejected() { + let _env = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + clear_env(); + std::env::set_var("OPENCODE_API_KEY", "test"); + + let error = Config::resolve(&cli(Some("openai-compatible"), None)) + .err() + .expect("openai-compatible needs a URL"); + assert!(error.contains("base URL"), "{error}"); +} + +#[test] +fn config_file_supplies_provider_model_and_flags() { + let _env = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + clear_env(); + + let dir = temp_dir("file"); + let path = dir.join("config.toml"); + fs::write( + &path, + "provider = \"openai-compatible\"\nurl = \"http://localhost:8080/v1\"\nmodel = \"local\"\nallow_nogit = true\n", + ) + .unwrap(); + std::env::set_var("AGENT686_CONFIG", &path); + + let cfg = Config::resolve_lenient(&Cli::default()); + assert_eq!(cfg.provider, Provider::OpenAICompatible); + assert_eq!(cfg.base_url, "http://localhost:8080/v1"); + assert_eq!(cfg.model, "local"); + assert!(cfg.allow_nogit); +} #[test] -fn presets_fill_base_url_model_and_leniency() { - let ollama = Config::resolve_lenient(None, None, false, Some("ollama".into()), false, false); - assert_eq!(ollama.base_url, "http://localhost:11434/v1"); - assert!(ollama.lenient, "local gateways default to lenient"); - - let opencode = - Config::resolve_lenient(None, None, false, Some("opencode-go".into()), false, false); - assert!(!opencode.lenient); - assert!(opencode.base_url.contains("opencode.ai")); - - // An explicit --base-url beats the preset. - let explicit = Config::resolve_lenient( - None, - Some("http://127.0.0.1:9/v1".into()), - false, - Some("ollama".into()), - false, - false, - ); - assert_eq!(explicit.base_url, "http://127.0.0.1:9/v1"); - - // Unknown preset falls back to the default endpoint. - let unknown = Config::resolve_lenient(None, None, false, Some("nope".into()), false, false); - assert!(unknown.base_url.contains("opencode.ai")); +fn cli_beats_the_config_file() { + let _env = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + clear_env(); + + let dir = temp_dir("precedence"); + let path = dir.join("config.toml"); + fs::write(&path, "model = \"from-file\"\n").unwrap(); + std::env::set_var("AGENT686_CONFIG", &path); + + let cfg = Config::resolve_lenient(&Cli { + model: Some("from-cli".into()), + ..Cli::default() + }); + assert_eq!(cfg.model, "from-cli"); } diff --git a/tests/loop.rs b/tests/loop.rs index 8c913cd..7e6086f 100644 --- a/tests/loop.rs +++ b/tests/loop.rs @@ -101,6 +101,9 @@ fn runs_a_tool_call_then_finishes_and_records_every_message() { yolo: true, lenient: false, system_ca: false, + provider: agent686::config::Provider::OpenCode, + allow_home: false, + allow_nogit: false, }; let mut history = agent::new_history(system); let mut approver = Approver::new(true); @@ -174,6 +177,9 @@ fn a_denied_tool_call_is_returned_as_data() { yolo: false, lenient: false, system_ca: false, + provider: agent686::config::Provider::OpenCode, + allow_home: false, + allow_nogit: false, }; let mut history = agent::new_history(system); // Not a terminal, so the approver must deny rather than block. @@ -244,6 +250,9 @@ fn aborting_between_tool_calls_answers_every_call() { yolo: true, lenient: false, system_ca: false, + provider: agent686::config::Provider::OpenCode, + allow_home: false, + allow_nogit: false, }; let mut history = agent::new_history(system); let mut approver = Approver::new(true); @@ -321,6 +330,9 @@ fn opening_a_session_with_unanswered_calls_repairs_it() { yolo: true, lenient: false, system_ca: false, + provider: agent686::config::Provider::OpenCode, + allow_home: false, + allow_nogit: false, }; let mut approver = Approver::new(true); agent::run_turn( @@ -377,6 +389,9 @@ fn an_empty_bash_call_is_never_approved() { yolo: false, lenient: false, system_ca: false, + provider: agent686::config::Provider::OpenCode, + allow_home: false, + allow_nogit: false, }; let mut history = agent::new_history(system); // Not a terminal: if this reaches the approval path it is denied, which the @@ -433,6 +448,9 @@ fn a_tool_call_with_no_arguments_is_reported_to_the_model() { yolo: false, lenient: false, system_ca: false, + provider: agent686::config::Provider::OpenCode, + allow_home: false, + allow_nogit: false, }; let mut history = agent::new_history(system); let mut approver = Approver::new(false); @@ -489,6 +507,9 @@ fn a_wrong_argument_key_names_both_keys() { yolo: false, lenient: false, system_ca: false, + provider: agent686::config::Provider::OpenCode, + allow_home: false, + allow_nogit: false, }; let mut history = agent::new_history(system); let mut approver = Approver::new(false); diff --git a/tests/mock.rs b/tests/mock.rs index fdbaca4..3b2abdd 100644 --- a/tests/mock.rs +++ b/tests/mock.rs @@ -76,6 +76,9 @@ fn config(base_url: String) -> Config { yolo: true, lenient: false, system_ca: false, + provider: agent686::config::Provider::OpenCode, + allow_home: false, + allow_nogit: false, } } -- cgit v1.2.3