summaryrefslogtreecommitdiffstats
path: root/src
diff options
context:
space:
mode:
authorsalmonik <salmonik@tuta.io>2026-11-15 15:26:21 +0100
committersalmonik <salmonik@tuta.io>2026-11-15 15:26:21 +0100
commitfa5894ea5740852c37eba3937c6ad255574ccfd3 (patch)
tree82d09308bbe8afe3ce92c4df31a03b77d3add110 /src
parent0.2.0: streaming line-range reads (diff)
downloadagent686-fa5894ea5740852c37eba3937c6ad255574ccfd3.tar.gz
agent686-fa5894ea5740852c37eba3937c6ad255574ccfd3.zip
0.3.0: --version and --doctor
doctor reports key source, writable dirs, provider, model, then checks the key against GET /models and confirms the model id is listed. Non-zero exit on failure, so it can gate a deployment.
Diffstat (limited to 'src')
-rw-r--r--src/config.rs62
-rw-r--r--src/doctor.rs99
-rw-r--r--src/lib.rs1
-rw-r--r--src/main.rs13
-rw-r--r--src/provider.rs49
5 files changed, 206 insertions, 18 deletions
diff --git a/src/config.rs b/src/config.rs
index a1d7c42..77bdc52 100644
--- a/src/config.rs
+++ b/src/config.rs
@@ -3,6 +3,13 @@ use std::path::PathBuf;
3pub const DEFAULT_BASE_URL: &str = "https://opencode.ai/inference/go/openai/v1"; 3pub const DEFAULT_BASE_URL: &str = "https://opencode.ai/inference/go/openai/v1";
4pub const DEFAULT_MODEL: &str = "deepseek-v4.1-flash"; 4pub const DEFAULT_MODEL: &str = "deepseek-v4.1-flash";
5 5
6#[derive(Debug, Clone, PartialEq, Eq)]
7pub enum KeySource {
8 Env,
9 File(PathBuf),
10 Missing,
11}
12
6#[derive(Debug, Clone)] 13#[derive(Debug, Clone)]
7pub struct Config { 14pub struct Config {
8 pub base_url: String, 15 pub base_url: String,
@@ -21,8 +28,23 @@ impl Config {
21 base_url: Option<String>, 28 base_url: Option<String>,
22 yolo: bool, 29 yolo: bool,
23 ) -> Result<Config, String> { 30 ) -> Result<Config, String> {
24 Ok(Config { 31 let config = Self::resolve_lenient(model, base_url, yolo);
25 api_key: api_key()?, 32 if config.api_key.is_empty() {
33 return Err(format!(
34 "no API key: set OPENCODE_API_KEY or write one to {}",
35 key_file()
36 .map(|path| path.display().to_string())
37 .unwrap_or_else(|| "~/.config/agent686/key".into())
38 ));
39 }
40 Ok(config)
41 }
42
43 /// Same as `resolve`, but tolerates a missing key so `--doctor` can report
44 /// the missing key instead of failing to start.
45 pub fn resolve_lenient(model: Option<String>, base_url: Option<String>, yolo: bool) -> Config {
46 Config {
47 api_key: api_key().unwrap_or_default(),
26 base_url: base_url 48 base_url: base_url
27 .or_else(|| env_nonempty("AGENT686_BASE_URL")) 49 .or_else(|| env_nonempty("AGENT686_BASE_URL"))
28 .unwrap_or_else(|| DEFAULT_BASE_URL.to_string()), 50 .unwrap_or_else(|| DEFAULT_BASE_URL.to_string()),
@@ -31,7 +53,7 @@ impl Config {
31 .unwrap_or_else(|| DEFAULT_MODEL.to_string()), 53 .unwrap_or_else(|| DEFAULT_MODEL.to_string()),
32 session: String::new(), 54 session: String::new(),
33 yolo, 55 yolo,
34 }) 56 }
35 } 57 }
36 58
37 pub fn endpoint(&self) -> String { 59 pub fn endpoint(&self) -> String {
@@ -43,26 +65,30 @@ fn env_nonempty(key: &str) -> Option<String> {
43 std::env::var(key).ok().filter(|v| !v.trim().is_empty()) 65 std::env::var(key).ok().filter(|v| !v.trim().is_empty())
44} 66}
45 67
46/// The key comes from the environment first, then from a file, so a key never 68pub fn key_source() -> KeySource {
47/// has to live in shell history. 69 if env_nonempty("OPENCODE_API_KEY").is_some() {
48fn api_key() -> Result<String, String> { 70 return KeySource::Env;
49 if let Some(k) = env_nonempty("OPENCODE_API_KEY") {
50 return Ok(k.trim().to_string());
51 } 71 }
52 if let Some(path) = key_file() { 72 if let Some(path) = key_file() {
53 if let Ok(k) = std::fs::read_to_string(&path) { 73 if let Ok(key) = std::fs::read_to_string(&path) {
54 let k = k.trim().to_string(); 74 if !key.trim().is_empty() {
55 if !k.is_empty() { 75 return KeySource::File(path);
56 return Ok(k);
57 } 76 }
58 } 77 }
59 } 78 }
60 Err(format!( 79 KeySource::Missing
61 "no API key: set OPENCODE_API_KEY or write one to {}", 80}
62 key_file() 81
63 .map(|p| p.display().to_string()) 82/// The key comes from the environment first, then from a file, so a key never
64 .unwrap_or_else(|| "~/.config/agent686/key".into()) 83/// has to live in shell history.
65 )) 84fn api_key() -> Result<String, String> {
85 match key_source() {
86 KeySource::Env => Ok(env_nonempty("OPENCODE_API_KEY").unwrap_or_default()),
87 KeySource::File(path) => Ok(std::fs::read_to_string(path)
88 .map(|key| key.trim().to_string())
89 .unwrap_or_default()),
90 KeySource::Missing => Err("no API key".into()),
91 }
66} 92}
67 93
68fn key_file() -> Option<PathBuf> { 94fn key_file() -> Option<PathBuf> {
diff --git a/src/doctor.rs b/src/doctor.rs
new file mode 100644
index 0000000..42d24a8
--- /dev/null
+++ b/src/doctor.rs
@@ -0,0 +1,99 @@
1use std::path::Path;
2
3use crate::config::{self, Config, KeySource};
4use crate::provider;
5use crate::session;
6
7/// Prints the state of everything the harness needs, and checks the things that
8/// are cheap to check but expensive to discover mid-turn.
9pub fn run(cfg: &Config) -> i32 {
10 let mut failed = false;
11
12 println!(
13 "agent686 {} · {} · {}",
14 env!("CARGO_PKG_VERSION"),
15 std::env::consts::ARCH,
16 std::env::consts::OS
17 );
18 println!();
19
20 match config::key_source() {
21 KeySource::Env => row(true, "key", "present in OPENCODE_API_KEY"),
22 KeySource::File(path) => row(true, "key", &format!("present in {}", path.display())),
23 KeySource::Missing => {
24 row(
25 false,
26 "key",
27 "missing — set OPENCODE_API_KEY or write ~/.config/agent686/key",
28 );
29 failed = true;
30 }
31 }
32
33 let sessions = session::sessions_dir();
34 match probe_dir(&sessions) {
35 Ok(()) => row(true, "sessions", &sessions.display().to_string()),
36 Err(error) => {
37 row(false, "sessions", &format!("{}: {error}", sessions.display()));
38 failed = true;
39 }
40 }
41
42 let history = session::data_root().join("history");
43 match std::fs::read_to_string(&history) {
44 Ok(text) => row(
45 true,
46 "history",
47 &format!("{} ({} entries)", history.display(), text.lines().count()),
48 ),
49 Err(_) => row(true, "history", &format!("{} (new)", history.display())),
50 }
51
52 row(true, "provider", &cfg.base_url);
53 row(true, "model", &cfg.model);
54
55 if cfg.api_key.is_empty() {
56 row(false, "auth", "skipped: no key");
57 failed = true;
58 } else {
59 match provider::models(cfg) {
60 Ok(models) => {
61 row(true, "auth", &format!("ok — {} models visible", models.len()));
62 if models.iter().any(|id| id == &cfg.model) {
63 row(true, "model known", "yes");
64 } else {
65 row(
66 false,
67 "model known",
68 "no — the provider does not list this id; pick another with --model",
69 );
70 failed = true;
71 }
72 }
73 Err(error) => {
74 row(false, "auth", &error.to_string());
75 failed = true;
76 }
77 }
78 }
79
80 println!();
81 if failed {
82 println!("some checks failed");
83 1
84 } else {
85 println!("all checks passed");
86 0
87 }
88}
89
90fn row(ok: bool, label: &str, detail: &str) {
91 println!("{:<13} {:<4} {detail}", label, if ok { "ok" } else { "FAIL" });
92}
93
94fn probe_dir(dir: &Path) -> std::io::Result<()> {
95 std::fs::create_dir_all(dir)?;
96 let probe = dir.join(".doctor-probe");
97 std::fs::write(&probe, b"ok")?;
98 std::fs::remove_file(probe)
99}
diff --git a/src/lib.rs b/src/lib.rs
index e978f83..c5c02b1 100644
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -1,5 +1,6 @@
1pub mod agent; 1pub mod agent;
2pub mod config; 2pub mod config;
3pub mod doctor;
3pub mod line; 4pub mod line;
4pub mod provider; 5pub mod provider;
5pub mod session; 6pub mod session;
diff --git a/src/main.rs b/src/main.rs
index 29b4280..ccd4e37 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -30,6 +30,8 @@ OPTIONS:
30 --session <ID> resume a session, creating it if the id is new 30 --session <ID> resume a session, creating it if the id is new
31 -c, --continue resume the most recent session 31 -c, --continue resume the most recent session
32 --list list sessions and exit 32 --list list sessions and exit
33 --doctor check key, directories, provider and model, then exit
34 -V, --version print the version and exit
33 --yolo approve every tool call without asking 35 --yolo approve every tool call without asking
34 -h, --help this text 36 -h, --help this text
35 37
@@ -47,6 +49,7 @@ fn main() {
47 let mut resume = None; 49 let mut resume = None;
48 let mut continue_last = false; 50 let mut continue_last = false;
49 let mut list = false; 51 let mut list = false;
52 let mut doctor = false;
50 let mut yolo = false; 53 let mut yolo = false;
51 54
52 let mut args = std::env::args().skip(1); 55 let mut args = std::env::args().skip(1);
@@ -57,6 +60,11 @@ fn main() {
57 "--session" | "--resume" => resume = args.next(), 60 "--session" | "--resume" => resume = args.next(),
58 "-c" | "--continue" => continue_last = true, 61 "-c" | "--continue" => continue_last = true,
59 "--list" => list = true, 62 "--list" => list = true,
63 "--doctor" => doctor = true,
64 "-V" | "--version" => {
65 println!("agent686 {}", env!("CARGO_PKG_VERSION"));
66 return;
67 }
60 "--yolo" => yolo = true, 68 "--yolo" => yolo = true,
61 "-h" | "--help" => { 69 "-h" | "--help" => {
62 print!("{HELP}"); 70 print!("{HELP}");
@@ -78,6 +86,11 @@ fn main() {
78 return; 86 return;
79 } 87 }
80 88
89 if doctor {
90 let config = Config::resolve_lenient(model, base_url, yolo);
91 std::process::exit(agent686::doctor::run(&config));
92 }
93
81 let mut cfg = match Config::resolve(model, base_url, yolo) { 94 let mut cfg = match Config::resolve(model, base_url, yolo) {
82 Ok(cfg) => cfg, 95 Ok(cfg) => cfg,
83 Err(message) => { 96 Err(message) => {
diff --git a/src/provider.rs b/src/provider.rs
index ba36b70..16c9013 100644
--- a/src/provider.rs
+++ b/src/provider.rs
@@ -448,3 +448,52 @@ struct FunctionDelta {
448 #[serde(default)] 448 #[serde(default)]
449 arguments: Option<String>, 449 arguments: Option<String>,
450} 450}
451
452/// Lists the models the provider offers for this key, for `--doctor`.
453pub fn models(cfg: &Config) -> Result<Vec<String>, Error> {
454 let agent: ureq::Agent = ureq::Agent::config_builder()
455 .http_status_as_error(false)
456 .timeout_connect(Some(Duration::from_secs(10)))
457 .timeout_recv_response(Some(Duration::from_secs(20)))
458 .timeout_per_read(Some(Duration::from_secs(20)))
459 .build()
460 .into();
461
462 let url = format!("{}/models", cfg.base_url.trim_end_matches('/'));
463 let mut response = agent
464 .get(&url)
465 .header("Authorization", format!("Bearer {}", cfg.api_key))
466 .header("User-Agent", concat!("agent686/", env!("CARGO_PKG_VERSION")))
467 .header("x-opencode-session", &cfg.session)
468 .call()
469 .map_err(|e| Error::Transport(e.to_string()))?;
470
471 let status = response.status().as_u16();
472 let body = response
473 .body_mut()
474 .with_config()
475 .limit(8 * 1024 * 1024)
476 .read_to_string()
477 .unwrap_or_default();
478
479 if !(200..300).contains(&status) {
480 return Err(Error::Status {
481 code: status,
482 message: explain(status, &error_message(&body)),
483 });
484 }
485
486 let value: Value = serde_json::from_str(&body)
487 .map_err(|e| Error::Transport(format!("could not parse the model list: {e}")))?;
488 Ok(value
489 .get("data")
490 .and_then(|data| data.as_array())
491 .map(|models| {
492 models
493 .iter()
494 .filter_map(|model| model.get("id").and_then(|id| id.as_str()))
495 .map(|id| id.to_string())
496 .collect()
497 })
498 .unwrap_or_default())
499}