summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
Diffstat (limited to '')
-rw-r--r--CHANGELOG.md18
-rw-r--r--Cargo.lock109
-rw-r--r--Cargo.toml5
-rw-r--r--README.md31
-rw-r--r--src/config.rs195
-rw-r--r--src/main.rs46
-rw-r--r--src/provider.rs37
-rw-r--r--tests/cli.rs2
-rw-r--r--tests/config.rs128
-rw-r--r--tests/loop.rs21
-rw-r--r--tests/mock.rs3
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.
7file, and the tool schemas the model sees. Anything a script or a resumed session 7file, and the tool schemas the model sees. Anything a script or a resumed session
8could depend on counts as API. 8could depend on counts as API.
9 9
10## 0.12.0
11
12### Changed (breaking)
13- `--provider` now takes a *type* instead of a preset name: `opencode` (the
14 default, sends the required `x-opencode-session` header) or
15 `openai-compatible` (any OpenAI-style endpoint, no session header). The base
16 URL comes from `--base-url`, `AGENT686_BASE_URL`, or the config file; an
17 openai-compatible provider with no URL is rejected.
18
19### Added
20- Config file at `~/.config/agent686/config.toml` (or `AGENT686_CONFIG`):
21 `provider`, `url`, `model`, `lenient`, `system_ca`, `yolo`, `allow_home`,
22 `allow_nogit`. Precedence is CLI flag > environment variable > config file >
23 default.
24
25### Fixed
26- `--provider --help` printed a doubled-dash suggestion (`----provider=`).
27
10## 0.11.0 28## 0.11.0
11 29
12### Added 30### Added
diff --git a/Cargo.lock b/Cargo.lock
index e206be7..48f449c 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -17,6 +17,7 @@ dependencies = [
17 "regex", 17 "regex",
18 "serde", 18 "serde",
19 "serde_json", 19 "serde_json",
20 "toml",
20 "unicode-width", 21 "unicode-width",
21 "ureq", 22 "ureq",
22] 23]
@@ -44,9 +45,9 @@ checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"
44 45
45[[package]] 46[[package]]
46name = "bytes" 47name = "bytes"
47version = "1.12.1" 48version = "1.12.2"
48source = "registry+https://github.com/rust-lang/crates.io-index" 49source = "registry+https://github.com/rust-lang/crates.io-index"
49checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" 50checksum = "776dfebd015e2d8732c684a2c71003674ccb49457b539b9e82151ba38e96dd7c"
50 51
51[[package]] 52[[package]]
52name = "cc" 53name = "cc"
@@ -167,6 +168,12 @@ dependencies = [
167] 168]
168 169
169[[package]] 170[[package]]
171name = "equivalent"
172version = "1.0.3"
173source = "registry+https://github.com/rust-lang/crates.io-index"
174checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826"
175
176[[package]]
170name = "errno" 177name = "errno"
171version = "0.3.15" 178version = "0.3.15"
172source = "registry+https://github.com/rust-lang/crates.io-index" 179source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -205,6 +212,12 @@ dependencies = [
205] 212]
206 213
207[[package]] 214[[package]]
215name = "hashbrown"
216version = "0.17.1"
217source = "registry+https://github.com/rust-lang/crates.io-index"
218checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a"
219
220[[package]]
208name = "http" 221name = "http"
209version = "1.5.0" 222version = "1.5.0"
210source = "registry+https://github.com/rust-lang/crates.io-index" 223source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -221,6 +234,16 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
221checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" 234checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87"
222 235
223[[package]] 236[[package]]
237name = "indexmap"
238version = "2.14.2"
239source = "registry+https://github.com/rust-lang/crates.io-index"
240checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855"
241dependencies = [
242 "equivalent",
243 "hashbrown",
244]
245
246[[package]]
224name = "itoa" 247name = "itoa"
225version = "1.0.19" 248version = "1.0.19"
226source = "registry+https://github.com/rust-lang/crates.io-index" 249source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -406,9 +429,9 @@ dependencies = [
406 429
407[[package]] 430[[package]]
408name = "regex" 431name = "regex"
409version = "1.13.1" 432version = "1.13.2"
410source = "registry+https://github.com/rust-lang/crates.io-index" 433source = "registry+https://github.com/rust-lang/crates.io-index"
411checksum = "f020237b6c8eed93db2e2cb53c00c60a8e1bc73da7d073199a1180401450218d" 434checksum = "9807af0e638c12e753aa1b4e601791bf2a8f71274023c8bbeec12fc149950857"
412dependencies = [ 435dependencies = [
413 "aho-corasick", 436 "aho-corasick",
414 "memchr", 437 "memchr",
@@ -418,9 +441,9 @@ dependencies = [
418 441
419[[package]] 442[[package]]
420name = "regex-automata" 443name = "regex-automata"
421version = "0.4.18" 444version = "0.4.19"
422source = "registry+https://github.com/rust-lang/crates.io-index" 445source = "registry+https://github.com/rust-lang/crates.io-index"
423checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2" 446checksum = "41d60ef07df457506a0a1a2073112eb4aae5733dbd2813c3da77d1b0fd441158"
424dependencies = [ 447dependencies = [
425 "aho-corasick", 448 "aho-corasick",
426 "memchr", 449 "memchr",
@@ -429,9 +452,9 @@ dependencies = [
429 452
430[[package]] 453[[package]]
431name = "regex-syntax" 454name = "regex-syntax"
432version = "0.8.11" 455version = "0.8.12"
433source = "registry+https://github.com/rust-lang/crates.io-index" 456source = "registry+https://github.com/rust-lang/crates.io-index"
434checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" 457checksum = "d902046e6a28a1e4c3cab97258a0ce11e994903f01c2d97a9447a0b3df85f4f6"
435 458
436[[package]] 459[[package]]
437name = "ring" 460name = "ring"
@@ -523,7 +546,7 @@ dependencies = [
523 "security-framework", 546 "security-framework",
524 "security-framework-sys", 547 "security-framework-sys",
525 "webpki-root-certs", 548 "webpki-root-certs",
526 "windows-sys 0.52.0", 549 "windows-sys 0.61.2",
527] 550]
528 551
529[[package]] 552[[package]]
@@ -640,6 +663,15 @@ dependencies = [
640] 663]
641 664
642[[package]] 665[[package]]
666name = "serde_spanned"
667version = "1.1.3"
668source = "registry+https://github.com/rust-lang/crates.io-index"
669checksum = "9c187e0a369471c550af028cba56d4f4fa2a489ad28151ae95a4d340a2a8b782"
670dependencies = [
671 "serde_core",
672]
673
674[[package]]
643name = "shlex" 675name = "shlex"
644version = "2.0.1" 676version = "2.0.1"
645source = "registry+https://github.com/rust-lang/crates.io-index" 677source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -700,9 +732,9 @@ checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e"
700 732
701[[package]] 733[[package]]
702name = "smallvec" 734name = "smallvec"
703version = "1.16.5" 735version = "1.16.6"
704source = "registry+https://github.com/rust-lang/crates.io-index" 736source = "registry+https://github.com/rust-lang/crates.io-index"
705checksum = "149309498a5f7334b12ddae0cad8aba81ce785fe91755068867e017cf98fee46" 737checksum = "3244542535d5de959d90ec55d1b5ff0fd2bb7b1310223907d5f11932847f7b59"
706 738
707[[package]] 739[[package]]
708name = "subtle" 740name = "subtle"
@@ -753,6 +785,45 @@ dependencies = [
753] 785]
754 786
755[[package]] 787[[package]]
788name = "toml"
789version = "1.2.1+spec-1.1.0"
790source = "registry+https://github.com/rust-lang/crates.io-index"
791checksum = "d5755c51863cdac711f1956baf8eb9588e060755f7d3c4c979e70ea1e1f32cd7"
792dependencies = [
793 "indexmap",
794 "serde_core",
795 "serde_spanned",
796 "toml_datetime",
797 "toml_parser",
798 "toml_writer",
799 "winnow",
800]
801
802[[package]]
803name = "toml_datetime"
804version = "1.1.3+spec-1.1.0"
805source = "registry+https://github.com/rust-lang/crates.io-index"
806checksum = "173f25c883cd2176a2d8212155638c0a60d484a9d84546d270866f40f56b6e49"
807dependencies = [
808 "serde_core",
809]
810
811[[package]]
812name = "toml_parser"
813version = "1.1.5+spec-1.1.0"
814source = "registry+https://github.com/rust-lang/crates.io-index"
815checksum = "baa693a8032d7e1cada7d0041e96126df243179ff061456783ac7f12bda4744c"
816dependencies = [
817 "winnow",
818]
819
820[[package]]
821name = "toml_writer"
822version = "1.2.0+spec-1.1.0"
823source = "registry+https://github.com/rust-lang/crates.io-index"
824checksum = "009dbb7700f11c55ef83aebbe4c0e9cf1f1ac0844bd8d6f00dc38f302026e13a"
825
826[[package]]
756name = "unicode-ident" 827name = "unicode-ident"
757version = "1.0.27" 828version = "1.0.27"
758source = "registry+https://github.com/rust-lang/crates.io-index" 829source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -830,9 +901,9 @@ checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b"
830 901
831[[package]] 902[[package]]
832name = "webpki-root-certs" 903name = "webpki-root-certs"
833version = "1.0.11" 904version = "1.0.12"
834source = "registry+https://github.com/rust-lang/crates.io-index" 905source = "registry+https://github.com/rust-lang/crates.io-index"
835checksum = "e49d0e65abc00c142e8f9428da991da9f1a250c39be97459901eb12b9b49f62a" 906checksum = "293198dcebfb821155b5092ab94b5a82ff180eddd7241df3bd6e66a4ffd1a585"
836dependencies = [ 907dependencies = [
837 "rustls-pki-types", 908 "rustls-pki-types",
838] 909]
@@ -868,7 +939,7 @@ version = "0.1.11"
868source = "registry+https://github.com/rust-lang/crates.io-index" 939source = "registry+https://github.com/rust-lang/crates.io-index"
869checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" 940checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"
870dependencies = [ 941dependencies = [
871 "windows-sys 0.52.0", 942 "windows-sys 0.61.2",
872] 943]
873 944
874[[package]] 945[[package]]
@@ -966,10 +1037,16 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
966checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" 1037checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"
967 1038
968[[package]] 1039[[package]]
1040name = "winnow"
1041version = "1.0.5"
1042source = "registry+https://github.com/rust-lang/crates.io-index"
1043checksum = "8c3b93199df0ab874cdf0c6a94f0a0dc3423fe41f1cafb62b8bd7b1deb277aef"
1044
1045[[package]]
969name = "zeroize" 1046name = "zeroize"
970version = "1.9.1" 1047version = "1.9.2"
971source = "registry+https://github.com/rust-lang/crates.io-index" 1048source = "registry+https://github.com/rust-lang/crates.io-index"
972checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879" 1049checksum = "85ccff8a4805aba1eaa4cd4afcd49f7557dd2cf5fd79ffc37f8959466effc5aa"
973 1050
974[[package]] 1051[[package]]
975name = "zlib-rs" 1052name = "zlib-rs"
diff --git a/Cargo.toml b/Cargo.toml
index 44d2fee..465673f 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -1,6 +1,6 @@
1[package] 1[package]
2name = "agent686" 2name = "agent686"
3version = "0.11.0" 3version = "0.12.0"
4edition = "2021" 4edition = "2021"
5description = "A small coding agent for Debian-class Linux" 5description = "A small coding agent for Debian-class Linux"
6publish = false 6publish = false
@@ -11,8 +11,9 @@ serde_json = "1"
11ureq = { version = "3", features = ["rustls", "platform-verifier"] } 11ureq = { version = "3", features = ["rustls", "platform-verifier"] }
12libc = "0.2" 12libc = "0.2"
13crossterm = "0.29.0" 13crossterm = "0.29.0"
14regex = "1.13.1" 14regex = "1.13.2"
15unicode-width = "0.2.3" 15unicode-width = "0.2.3"
16toml = "1.2.1"
16 17
17[profile.release] 18[profile.release]
18strip = true 19strip = 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
55./agent686 --yolo "..." # approve every tool call 55./agent686 --yolo "..." # approve every tool call
56``` 56```
57 57
58Provider is OpenCode Go, `chat/completions`, model `deepseek-v4.1-flash` by 58The provider is a *type* plus a URL, both speaking OpenAI-compatible chat
59default; `--provider ollama|openai|openrouter|vllm|llamacpp` switches to another 59completions:
60OpenAI-compatible endpoint, with `--lenient` for servers that omit `[DONE]`. 60
61`HTTPS_PROXY`/`NO_PROXY` are honoured. Every request carries a stable 61- `opencode` (default) — `https://opencode.ai/inference/go/openai/v1`, and it
62`x-opencode-session` header, which the service uses for routing and prompt caching. 62 requires a stable `x-opencode-session` header per conversation.
63- `openai-compatible` — any endpoint (Ollama, llama.cpp, vLLM, OpenRouter, …),
64 given via `--base-url`/`AGENT686_BASE_URL`/config `url`; no session header.
65
66`--lenient` tolerates servers that omit `[DONE]`/`usage`; `HTTPS_PROXY`/`NO_PROXY`
67are honoured.
68
69## Config file
70
71`~/.config/agent686/config.toml` (override with `AGENT686_CONFIG`) sets defaults
72the CLI and environment can then override:
73
74```toml
75provider = "opencode" # or "openai-compatible"
76url = "http://localhost:11434/v1" # for openai-compatible
77model = "deepseek-v4.1-flash"
78lenient = false
79system_ca = false
80yolo = false
81allow_home = false # permit --yolo in $HOME or /
82allow_nogit = false # permit --yolo outside a git repository
83```
63 84
64In a terminal: up/down walks history, bracketed paste arrives as one block 85In a terminal: up/down walks history, bracketed paste arrives as one block
65(multi-line is fine), ctrl-c abandons the line, ctrl-d exits. `/undo` reverts the 86(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 @@
1use std::path::PathBuf; 1use std::path::PathBuf;
2 2
3pub const DEFAULT_BASE_URL: &str = "https://opencode.ai/inference/go/openai/v1"; 3use serde::Deserialize;
4
4pub const DEFAULT_MODEL: &str = "deepseek-v4.1-flash"; 5pub const DEFAULT_MODEL: &str = "deepseek-v4.1-flash";
5 6
6/// (name, base_url, default_model, lenient). Local gateways that omit `[DONE]` 7/// What kind of provider this is. Both speak OpenAI-compatible chat
7/// or `usage` are marked lenient so a truncated-looking stream is not an error. 8/// completions; OpenCode additionally requires the `x-opencode-session` header.
8const PRESETS: &[(&str, &str, &str, bool)] = &[ 9#[derive(Debug, Clone, Copy, PartialEq, Eq)]
9 ("opencode-go", DEFAULT_BASE_URL, DEFAULT_MODEL, false), 10pub enum Provider {
10 ("openai", "https://api.openai.com/v1", "gpt-4o-mini", false), 11 OpenCode,
11 ("openrouter", "https://openrouter.ai/api/v1", "", false), 12 OpenAICompatible,
12 ("ollama", "http://localhost:11434/v1", "", true), 13}
13 ("llamacpp", "http://localhost:8080/v1", "", true), 14
14 ("vllm", "http://localhost:8000/v1", "", true), 15impl Provider {
15]; 16 pub fn from_name(name: &str) -> Option<Provider> {
17 match name {
18 "opencode" | "opencode-go" => Some(Provider::OpenCode),
19 "openai" | "openai-compatible" | "openai_compatible" => {
20 Some(Provider::OpenAICompatible)
21 }
22 _ => None,
23 }
24 }
25
26 pub fn name(self) -> &'static str {
27 match self {
28 Provider::OpenCode => "opencode",
29 Provider::OpenAICompatible => "openai-compatible",
30 }
31 }
32
33 pub fn default_url(self) -> &'static str {
34 match self {
35 Provider::OpenCode => "https://opencode.ai/inference/go/openai/v1",
36 Provider::OpenAICompatible => "",
37 }
38 }
39
40 pub fn needs_session_header(self) -> bool {
41 self == Provider::OpenCode
42 }
43}
44
45/// The command-line values that override config and environment.
46#[derive(Debug, Default)]
47pub struct Cli {
48 pub model: Option<String>,
49 pub base_url: Option<String>,
50 pub provider: Option<String>,
51 pub yolo: bool,
52 pub lenient: bool,
53 pub system_ca: bool,
54}
16 55
17#[derive(Debug, Clone, PartialEq, Eq)] 56#[derive(Debug, Clone, PartialEq, Eq)]
18pub enum KeySource { 57pub enum KeySource {
@@ -26,28 +65,24 @@ pub struct Config {
26 pub base_url: String, 65 pub base_url: String,
27 pub api_key: String, 66 pub api_key: String,
28 pub model: String, 67 pub model: String,
29 /// Session id, sent to the provider as `x-opencode-session`. Filled in once 68 /// Session id, sent to the provider as `x-opencode-session` when it is
30 /// the session exists. 69 /// OpenCode. Filled in once the session exists.
31 pub session: String, 70 pub session: String,
71 pub provider: Provider,
32 pub yolo: bool, 72 pub yolo: bool,
33 /// Tolerate providers that omit `[DONE]`/`usage`/`finish_reason`. 73 /// Tolerate providers that omit `[DONE]`/`usage`/`finish_reason`.
34 pub lenient: bool, 74 pub lenient: bool,
35 /// Verify TLS against the system trust store instead of bundled roots. 75 /// Verify TLS against the system trust store instead of bundled roots.
36 pub system_ca: bool, 76 pub system_ca: bool,
77 /// Permit `--yolo` in `$HOME` or `/`.
78 pub allow_home: bool,
79 /// Permit `--yolo` outside a git repository.
80 pub allow_nogit: bool,
37} 81}
38 82
39impl Config { 83impl Config {
40 /// CLI flags win over environment variables, which win over defaults. 84 pub fn resolve(cli: &Cli) -> Result<Config, String> {
41 #[allow(clippy::too_many_arguments)] 85 let config = Self::resolve_lenient(cli);
42 pub fn resolve(
43 model: Option<String>,
44 base_url: Option<String>,
45 yolo: bool,
46 provider: Option<String>,
47 lenient: bool,
48 system_ca: bool,
49 ) -> Result<Config, String> {
50 let config = Self::resolve_lenient(model, base_url, yolo, provider, lenient, system_ca);
51 if config.api_key.is_empty() { 86 if config.api_key.is_empty() {
52 return Err(format!( 87 return Err(format!(
53 "no API key: set OPENCODE_API_KEY or write one to {}", 88 "no API key: set OPENCODE_API_KEY or write one to {}",
@@ -56,34 +91,55 @@ impl Config {
56 .unwrap_or_else(|| "~/.config/agent686/key".into()) 91 .unwrap_or_else(|| "~/.config/agent686/key".into())
57 )); 92 ));
58 } 93 }
94 if config.provider == Provider::OpenAICompatible && config.base_url.is_empty() {
95 return Err(
96 "the openai-compatible provider needs a base URL: set --base-url, \
97 AGENT686_BASE_URL, or `url` in the config file"
98 .to_string(),
99 );
100 }
59 Ok(config) 101 Ok(config)
60 } 102 }
61 103
62 /// Same as `resolve`, but tolerates a missing key so `--doctor` can report 104 /// Same as `resolve`, but tolerates a missing key and URL so `--doctor` can
63 /// the missing key instead of failing to start. 105 /// report them instead of failing to start.
64 pub fn resolve_lenient( 106 pub fn resolve_lenient(cli: &Cli) -> Config {
65 model: Option<String>, 107 let file = load_file();
66 base_url: Option<String>, 108
67 yolo: bool, 109 let provider = cli
68 provider: Option<String>, 110 .provider
69 lenient: bool, 111 .clone()
70 system_ca: bool, 112 .or_else(|| env_nonempty("AGENT686_PROVIDER"))
71 ) -> Config { 113 .or(file.provider.clone())
72 // Presets fill the base URL and a default model; explicit values win. 114 .and_then(|name| Provider::from_name(&name))
73 let provider = provider.or_else(|| env_nonempty("AGENT686_PROVIDER")); 115 .unwrap_or_else(|| {
74 let (preset_url, preset_model, preset_lenient) = provider 116 // Unknown names fall back to OpenCode, with a note.
75 .as_deref() 117 if let Some(bad) = cli
76 .and_then(|name| PRESETS.iter().find(|(n, ..)| *n == name)) 118 .provider
77 .map(|(_, url, model, lenient)| (*url, *model, *lenient)) 119 .clone()
78 .unwrap_or((DEFAULT_BASE_URL, "", false)); 120 .or_else(|| env_nonempty("AGENT686_PROVIDER"))
79 121 .or(file.provider.clone())
80 let base_url = base_url 122 {
123 eprintln!(
124 "agent686: unknown provider type `{bad}` (expected opencode or \
125 openai-compatible); using opencode"
126 );
127 }
128 Provider::OpenCode
129 });
130
131 let base_url = cli
132 .base_url
133 .clone()
81 .or_else(|| env_nonempty("AGENT686_BASE_URL")) 134 .or_else(|| env_nonempty("AGENT686_BASE_URL"))
82 .unwrap_or_else(|| preset_url.to_string()); 135 .or(file.url.clone())
136 .unwrap_or_else(|| provider.default_url().to_string());
83 137
84 let model = model 138 let model = cli
139 .model
140 .clone()
85 .or_else(|| env_nonempty("AGENT686_MODEL")) 141 .or_else(|| env_nonempty("AGENT686_MODEL"))
86 .or_else(|| (!preset_model.is_empty()).then(|| preset_model.to_string())) 142 .or(file.model.clone())
87 .unwrap_or_else(|| DEFAULT_MODEL.to_string()); 143 .unwrap_or_else(|| DEFAULT_MODEL.to_string());
88 144
89 Config { 145 Config {
@@ -91,9 +147,16 @@ impl Config {
91 base_url, 147 base_url,
92 model, 148 model,
93 session: String::new(), 149 session: String::new(),
94 yolo, 150 provider,
95 lenient: lenient || preset_lenient, 151 yolo: cli.yolo || file.yolo.unwrap_or(false),
96 system_ca: system_ca || env_nonempty("AGENT686_SYSTEM_CA").is_some(), 152 lenient: cli.lenient || file.lenient.unwrap_or(false),
153 system_ca: cli.system_ca
154 || env_nonempty("AGENT686_SYSTEM_CA").is_some()
155 || file.system_ca.unwrap_or(false),
156 allow_home: env_nonempty("AGENT686_ALLOW_HOME").is_some()
157 || file.allow_home.unwrap_or(false),
158 allow_nogit: env_nonempty("AGENT686_ALLOW_NOGIT").is_some()
159 || file.allow_nogit.unwrap_or(false),
97 } 160 }
98 } 161 }
99 162
@@ -102,8 +165,38 @@ impl Config {
102 } 165 }
103} 166}
104 167
105pub fn provider_names() -> Vec<&'static str> { 168/// The `~/.config/agent686/config.toml` shape. Every key is optional.
106 PRESETS.iter().map(|(name, ..)| *name).collect() 169#[derive(Debug, Default, Deserialize)]
170struct FileConfig {
171 provider: Option<String>,
172 url: Option<String>,
173 model: Option<String>,
174 lenient: Option<bool>,
175 system_ca: Option<bool>,
176 yolo: Option<bool>,
177 allow_home: Option<bool>,
178 allow_nogit: Option<bool>,
179}
180
181fn config_path() -> Option<PathBuf> {
182 if let Some(path) = std::env::var_os("AGENT686_CONFIG") {
183 return Some(PathBuf::from(path));
184 }
185 let home = std::env::var_os("HOME")?;
186 Some(PathBuf::from(home).join(".config/agent686/config.toml"))
187}
188
189fn load_file() -> FileConfig {
190 let Some(path) = config_path() else {
191 return FileConfig::default();
192 };
193 match std::fs::read_to_string(&path) {
194 Ok(text) => toml::from_str(&text).unwrap_or_else(|error| {
195 eprintln!("agent686: {}: {error}", path.display());
196 FileConfig::default()
197 }),
198 Err(_) => FileConfig::default(),
199 }
107} 200}
108 201
109fn env_nonempty(key: &str) -> Option<String> { 202fn env_nonempty(key: &str) -> Option<String> {
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:
38 --show [ID] print a transcript (most recent if no ID) and exit 38 --show [ID] print a transcript (most recent if no ID) and exit
39 --doctor check key, directories, provider and model, then exit 39 --doctor check key, directories, provider and model, then exit
40 --yolo approve every tool call without asking 40 --yolo approve every tool call without asking
41 --provider <NAME> preset: opencode-go, openai, openrouter, ollama, 41 --provider <TYPE> opencode (requires the session header, default) or
42 llamacpp, vllm 42 openai-compatible (any OpenAI-style endpoint; pair with
43 --base-url, e.g. Ollama http://localhost:11434/v1)
43 --lenient tolerate providers that omit [DONE]/usage 44 --lenient tolerate providers that omit [DONE]/usage
44 --system-ca verify TLS with the system trust store 45 --system-ca verify TLS with the system trust store
45 -V, --version print the version and exit 46 -V, --version print the version and exit
@@ -201,7 +202,9 @@ fn take_value(iter: &mut impl Iterator<Item = String>, flag: &str) -> Result<Str
201 { 202 {
202 Ok(value) 203 Ok(value)
203 } 204 }
204 _ => Err(format!("{flag} needs a value (use --{flag}=… for a value starting with -)")), 205 _ => Err(format!(
206 "{flag} needs a value (use {flag}=… for a value starting with -)"
207 )),
205 } 208 }
206} 209}
207 210
@@ -233,28 +236,23 @@ fn run(args: Args) {
233 return; 236 return;
234 } 237 }
235 238
239 let cli = agent686::config::Cli {
240 model: args.model.clone(),
241 base_url: args.base_url.clone(),
242 provider: args.provider.clone(),
243 yolo: args.yolo,
244 lenient: args.lenient,
245 system_ca: args.system_ca,
246 };
247
236 if args.doctor { 248 if args.doctor {
237 let mut config = Config::resolve_lenient( 249 let mut config = Config::resolve_lenient(&cli);
238 args.model,
239 args.base_url,
240 args.yolo,
241 args.provider,
242 args.lenient,
243 args.system_ca,
244 );
245 // `/models` needs the session header too, even though this is not a turn. 250 // `/models` needs the session header too, even though this is not a turn.
246 config.session = session::new_id(); 251 config.session = session::new_id();
247 std::process::exit(doctor::run(&config, args.json)); 252 std::process::exit(doctor::run(&config, args.json));
248 } 253 }
249 254
250 let mut cfg = match Config::resolve( 255 let mut cfg = match Config::resolve(&cli) {
251 args.model,
252 args.base_url,
253 args.yolo,
254 args.provider,
255 args.lenient,
256 args.system_ca,
257 ) {
258 Ok(cfg) => cfg, 256 Ok(cfg) => cfg,
259 Err(message) => { 257 Err(message) => {
260 eprintln!("agent686: {message}"); 258 eprintln!("agent686: {message}");
@@ -708,7 +706,7 @@ fn ago(modified: SystemTime) -> String {
708 706
709/// `--yolo` with no approval and no undo is how a transcript ends up deleting a 707/// `--yolo` with no approval and no undo is how a transcript ends up deleting a
710/// checkout. Git is the documented undo, so `--yolo` needs a repository unless 708/// checkout. Git is the documented undo, so `--yolo` needs a repository unless
711/// asked twice. `$HOME` and `/` are refused outright. 709/// allowed. `$HOME` and `/` are refused outright.
712fn refuse_yolo(cfg: &Config) { 710fn refuse_yolo(cfg: &Config) {
713 if !cfg.yolo { 711 if !cfg.yolo {
714 return; 712 return;
@@ -720,19 +718,19 @@ fn refuse_yolo(cfg: &Config) {
720 let home = std::env::var_os("HOME").map(PathBuf::from); 718 let home = std::env::var_os("HOME").map(PathBuf::from);
721 let at_home = home.as_deref() == Some(cwd.as_path()); 719 let at_home = home.as_deref() == Some(cwd.as_path());
722 let at_root = cwd.parent().is_none(); 720 let at_root = cwd.parent().is_none();
723 if (at_home || at_root) && std::env::var_os("AGENT686_ALLOW_HOME").is_none() { 721 if (at_home || at_root) && !cfg.allow_home {
724 eprintln!( 722 eprintln!(
725 "agent686: refusing --yolo in {} — the model can overwrite anything here. \ 723 "agent686: refusing --yolo in {} — the model can overwrite anything here. \
726 Run inside a project, or set AGENT686_ALLOW_HOME=1.", 724 Run inside a project, or set allow_home in the config.",
727 cwd.display() 725 cwd.display()
728 ); 726 );
729 std::process::exit(2); 727 std::process::exit(2);
730 } 728 }
731 729
732 if !in_git_repo(&cwd) && std::env::var_os("AGENT686_ALLOW_NOGIT").is_none() { 730 if !in_git_repo(&cwd) && !cfg.allow_nogit {
733 eprintln!( 731 eprintln!(
734 "agent686: refusing --yolo outside a git repository ({} has no .git), so \ 732 "agent686: refusing --yolo outside a git repository ({} has no .git), so \
735 there is no undo. Run git init, or set AGENT686_ALLOW_NOGIT=1.", 733 there is no undo. Run git init, or set allow_nogit in the config.",
736 cwd.display() 734 cwd.display()
737 ); 735 );
738 std::process::exit(2); 736 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(
256 return Err(Error::Aborted); 256 return Err(Error::Aborted);
257 } 257 }
258 258
259 let sent = agent 259 let mut request = agent
260 .post(&cfg.endpoint()) 260 .post(&cfg.endpoint())
261 .header("Content-Type", "application/json") 261 .header("Content-Type", "application/json")
262 .header("Accept", "text/event-stream") 262 .header("Accept", "text/event-stream")
263 .header("Authorization", format!("Bearer {}", cfg.api_key)) 263 .header("Authorization", format!("Bearer {}", cfg.api_key))
264 .header("User-Agent", concat!("agent686/", env!("CARGO_PKG_VERSION"))) 264 .header("User-Agent", concat!("agent686/", env!("CARGO_PKG_VERSION")));
265 // Required by OpenCode Go: stable per conversation, used for 265 // OpenCode requires a stable per-conversation id for routing and
266 // routing and prompt caching. Without it the gateway answers 266 // prompt caching; a plain OpenAI-compatible endpoint must not get it.
267 // 400 MissingSessionID. 267 if cfg.provider.needs_session_header() {
268 .header("x-opencode-session", &cfg.session) 268 request = request.header("x-opencode-session", &cfg.session);
269 .send(bytes.clone()); 269 }
270 let sent = request.send(bytes.clone());
270 271
271 let mut response = match sent { 272 let mut response = match sent {
272 Ok(response) => response, 273 Ok(response) => response,
@@ -570,14 +571,15 @@ struct FunctionDelta {
570pub fn summarize(cfg: &Config, messages: &[Value]) -> Result<String, Error> { 571pub fn summarize(cfg: &Config, messages: &[Value]) -> Result<String, Error> {
571 let body = serde_json::json!({ "model": cfg.model, "messages": messages, "stream": false }); 572 let body = serde_json::json!({ "model": cfg.model, "messages": messages, "stream": false });
572 let bytes = serde_json::to_vec(&body).map_err(|e| Error::Transport(e.to_string()))?; 573 let bytes = serde_json::to_vec(&body).map_err(|e| Error::Transport(e.to_string()))?;
573 let mut response = agent(cfg.system_ca) 574 let mut request = agent(cfg.system_ca)
574 .post(&cfg.endpoint()) 575 .post(&cfg.endpoint())
575 .header("Content-Type", "application/json") 576 .header("Content-Type", "application/json")
576 .header("Authorization", format!("Bearer {}", cfg.api_key)) 577 .header("Authorization", format!("Bearer {}", cfg.api_key))
577 .header("User-Agent", concat!("agent686/", env!("CARGO_PKG_VERSION"))) 578 .header("User-Agent", concat!("agent686/", env!("CARGO_PKG_VERSION")));
578 .header("x-opencode-session", &cfg.session) 579 if cfg.provider.needs_session_header() {
579 .send(bytes) 580 request = request.header("x-opencode-session", &cfg.session);
580 .map_err(|e| Error::Transport(e.to_string()))?; 581 }
582 let mut response = request.send(bytes).map_err(|e| Error::Transport(e.to_string()))?;
581 583
582 let status = response.status().as_u16(); 584 let status = response.status().as_u16();
583 let text = response 585 let text = response
@@ -605,13 +607,14 @@ pub fn models(cfg: &Config) -> Result<Vec<String>, Error> {
605 let agent = agent(cfg.system_ca); 607 let agent = agent(cfg.system_ca);
606 608
607 let url = format!("{}/models", cfg.base_url.trim_end_matches('/')); 609 let url = format!("{}/models", cfg.base_url.trim_end_matches('/'));
608 let mut response = agent 610 let mut request = agent
609 .get(&url) 611 .get(&url)
610 .header("Authorization", format!("Bearer {}", cfg.api_key)) 612 .header("Authorization", format!("Bearer {}", cfg.api_key))
611 .header("User-Agent", concat!("agent686/", env!("CARGO_PKG_VERSION"))) 613 .header("User-Agent", concat!("agent686/", env!("CARGO_PKG_VERSION")));
612 .header("x-opencode-session", &cfg.session) 614 if cfg.provider.needs_session_header() {
613 .call() 615 request = request.header("x-opencode-session", &cfg.session);
614 .map_err(|e| Error::Transport(e.to_string()))?; 616 }
617 let mut response = request.call().map_err(|e| Error::Transport(e.to_string()))?;
615 618
616 let status = response.status().as_u16(); 619 let status = response.status().as_u16();
617 let body = response 620 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() {
92 assert_eq!(output.status.code(), Some(2), "{output:?}"); 92 assert_eq!(output.status.code(), Some(2), "{output:?}");
93 let stderr = String::from_utf8_lossy(&output.stderr); 93 let stderr = String::from_utf8_lossy(&output.stderr);
94 assert!(stderr.contains("refusing --yolo"), "{stderr}"); 94 assert!(stderr.contains("refusing --yolo"), "{stderr}");
95 assert!(stderr.contains("AGENT686_ALLOW_HOME"), "{stderr}"); 95 assert!(stderr.contains("allow_home"), "{stderr}");
96} 96}
97 97
98#[test] 98#[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 @@
1use agent686::config::Config; 1use std::fs;
2
3use agent686::config::{Cli, Config, Provider};
4
5static ENV_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
6
7fn clear_env() {
8 for key in [
9 "AGENT686_CONFIG",
10 "AGENT686_PROVIDER",
11 "AGENT686_BASE_URL",
12 "AGENT686_MODEL",
13 "AGENT686_ALLOW_HOME",
14 "AGENT686_ALLOW_NOGIT",
15 "AGENT686_SYSTEM_CA",
16 ] {
17 std::env::remove_var(key);
18 }
19}
20
21fn cli(provider: Option<&str>, base_url: Option<&str>) -> Cli {
22 Cli {
23 model: None,
24 base_url: base_url.map(String::from),
25 provider: provider.map(String::from),
26 yolo: false,
27 lenient: false,
28 system_ca: false,
29 }
30}
31
32fn temp_dir(tag: &str) -> std::path::PathBuf {
33 let dir = std::env::temp_dir().join(format!("agent686-config-{tag}-{}", std::process::id()));
34 let _ = fs::remove_dir_all(&dir);
35 fs::create_dir_all(&dir).unwrap();
36 dir
37}
38
39#[test]
40fn provider_type_selects_url_and_session_header() {
41 let _env = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
42 clear_env();
43
44 let opencode = Config::resolve_lenient(&cli(Some("opencode"), None));
45 assert_eq!(opencode.provider, Provider::OpenCode);
46 assert!(opencode.base_url.contains("opencode.ai"), "{}", opencode.base_url);
47 assert!(opencode.provider.needs_session_header());
48
49 let compatible = Config::resolve_lenient(&cli(
50 Some("openai-compatible"),
51 Some("http://localhost:11434/v1"),
52 ));
53 assert_eq!(compatible.provider, Provider::OpenAICompatible);
54 assert_eq!(compatible.base_url, "http://localhost:11434/v1");
55 assert!(!compatible.provider.needs_session_header());
56}
57
58#[test]
59fn openai_compatible_without_a_url_is_rejected() {
60 let _env = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
61 clear_env();
62 std::env::set_var("OPENCODE_API_KEY", "test");
63
64 let error = Config::resolve(&cli(Some("openai-compatible"), None))
65 .err()
66 .expect("openai-compatible needs a URL");
67 assert!(error.contains("base URL"), "{error}");
68}
69
70#[test]
71fn config_file_supplies_provider_model_and_flags() {
72 let _env = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
73 clear_env();
74
75 let dir = temp_dir("file");
76 let path = dir.join("config.toml");
77 fs::write(
78 &path,
79 "provider = \"openai-compatible\"\nurl = \"http://localhost:8080/v1\"\nmodel = \"local\"\nallow_nogit = true\n",
80 )
81 .unwrap();
82 std::env::set_var("AGENT686_CONFIG", &path);
83
84 let cfg = Config::resolve_lenient(&Cli::default());
85 assert_eq!(cfg.provider, Provider::OpenAICompatible);
86 assert_eq!(cfg.base_url, "http://localhost:8080/v1");
87 assert_eq!(cfg.model, "local");
88 assert!(cfg.allow_nogit);
89}
2 90
3#[test] 91#[test]
4fn presets_fill_base_url_model_and_leniency() { 92fn cli_beats_the_config_file() {
5 let ollama = Config::resolve_lenient(None, None, false, Some("ollama".into()), false, false); 93 let _env = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
6 assert_eq!(ollama.base_url, "http://localhost:11434/v1"); 94 clear_env();
7 assert!(ollama.lenient, "local gateways default to lenient"); 95
8 96 let dir = temp_dir("precedence");
9 let opencode = 97 let path = dir.join("config.toml");
10 Config::resolve_lenient(None, None, false, Some("opencode-go".into()), false, false); 98 fs::write(&path, "model = \"from-file\"\n").unwrap();
11 assert!(!opencode.lenient); 99 std::env::set_var("AGENT686_CONFIG", &path);
12 assert!(opencode.base_url.contains("opencode.ai")); 100
13 101 let cfg = Config::resolve_lenient(&Cli {
14 // An explicit --base-url beats the preset. 102 model: Some("from-cli".into()),
15 let explicit = Config::resolve_lenient( 103 ..Cli::default()
16 None, 104 });
17 Some("http://127.0.0.1:9/v1".into()), 105 assert_eq!(cfg.model, "from-cli");
18 false,
19 Some("ollama".into()),
20 false,
21 false,
22 );
23 assert_eq!(explicit.base_url, "http://127.0.0.1:9/v1");
24
25 // Unknown preset falls back to the default endpoint.
26 let unknown = Config::resolve_lenient(None, None, false, Some("nope".into()), false, false);
27 assert!(unknown.base_url.contains("opencode.ai"));
28} 106}
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() {
101 yolo: true, 101 yolo: true,
102 lenient: false, 102 lenient: false,
103 system_ca: false, 103 system_ca: false,
104 provider: agent686::config::Provider::OpenCode,
105 allow_home: false,
106 allow_nogit: false,
104 }; 107 };
105 let mut history = agent::new_history(system); 108 let mut history = agent::new_history(system);
106 let mut approver = Approver::new(true); 109 let mut approver = Approver::new(true);
@@ -174,6 +177,9 @@ fn a_denied_tool_call_is_returned_as_data() {
174 yolo: false, 177 yolo: false,
175 lenient: false, 178 lenient: false,
176 system_ca: false, 179 system_ca: false,
180 provider: agent686::config::Provider::OpenCode,
181 allow_home: false,
182 allow_nogit: false,
177 }; 183 };
178 let mut history = agent::new_history(system); 184 let mut history = agent::new_history(system);
179 // Not a terminal, so the approver must deny rather than block. 185 // Not a terminal, so the approver must deny rather than block.
@@ -244,6 +250,9 @@ fn aborting_between_tool_calls_answers_every_call() {
244 yolo: true, 250 yolo: true,
245 lenient: false, 251 lenient: false,
246 system_ca: false, 252 system_ca: false,
253 provider: agent686::config::Provider::OpenCode,
254 allow_home: false,
255 allow_nogit: false,
247 }; 256 };
248 let mut history = agent::new_history(system); 257 let mut history = agent::new_history(system);
249 let mut approver = Approver::new(true); 258 let mut approver = Approver::new(true);
@@ -321,6 +330,9 @@ fn opening_a_session_with_unanswered_calls_repairs_it() {
321 yolo: true, 330 yolo: true,
322 lenient: false, 331 lenient: false,
323 system_ca: false, 332 system_ca: false,
333 provider: agent686::config::Provider::OpenCode,
334 allow_home: false,
335 allow_nogit: false,
324 }; 336 };
325 let mut approver = Approver::new(true); 337 let mut approver = Approver::new(true);
326 agent::run_turn( 338 agent::run_turn(
@@ -377,6 +389,9 @@ fn an_empty_bash_call_is_never_approved() {
377 yolo: false, 389 yolo: false,
378 lenient: false, 390 lenient: false,
379 system_ca: false, 391 system_ca: false,
392 provider: agent686::config::Provider::OpenCode,
393 allow_home: false,
394 allow_nogit: false,
380 }; 395 };
381 let mut history = agent::new_history(system); 396 let mut history = agent::new_history(system);
382 // Not a terminal: if this reaches the approval path it is denied, which the 397 // 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() {
433 yolo: false, 448 yolo: false,
434 lenient: false, 449 lenient: false,
435 system_ca: false, 450 system_ca: false,
451 provider: agent686::config::Provider::OpenCode,
452 allow_home: false,
453 allow_nogit: false,
436 }; 454 };
437 let mut history = agent::new_history(system); 455 let mut history = agent::new_history(system);
438 let mut approver = Approver::new(false); 456 let mut approver = Approver::new(false);
@@ -489,6 +507,9 @@ fn a_wrong_argument_key_names_both_keys() {
489 yolo: false, 507 yolo: false,
490 lenient: false, 508 lenient: false,
491 system_ca: false, 509 system_ca: false,
510 provider: agent686::config::Provider::OpenCode,
511 allow_home: false,
512 allow_nogit: false,
492 }; 513 };
493 let mut history = agent::new_history(system); 514 let mut history = agent::new_history(system);
494 let mut approver = Approver::new(false); 515 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 {
76 yolo: true, 76 yolo: true,
77 lenient: false, 77 lenient: false,
78 system_ca: false, 78 system_ca: false,
79 provider: agent686::config::Provider::OpenCode,
80 allow_home: false,
81 allow_nogit: false,
79 } 82 }
80} 83}
81 84