aboutsummaryrefslogtreecommitdiffstats
path: root/src
diff options
context:
space:
mode:
Diffstat (limited to '')
-rw-r--r--src/config.rs195
-rw-r--r--src/main.rs46
-rw-r--r--src/provider.rs37
3 files changed, 186 insertions, 92 deletions
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