From fa5894ea5740852c37eba3937c6ad255574ccfd3 Mon Sep 17 00:00:00 2001 From: salmonik Date: Sun, 15 Nov 2026 15:26:21 +0100 Subject: 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. --- src/config.rs | 62 +++++++++++++++++++++++++----------- src/doctor.rs | 99 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++ src/lib.rs | 1 + src/main.rs | 13 ++++++++ src/provider.rs | 49 ++++++++++++++++++++++++++++ 5 files changed, 206 insertions(+), 18 deletions(-) create mode 100644 src/doctor.rs (limited to 'src') 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; pub const DEFAULT_BASE_URL: &str = "https://opencode.ai/inference/go/openai/v1"; pub const DEFAULT_MODEL: &str = "deepseek-v4.1-flash"; +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum KeySource { + Env, + File(PathBuf), + Missing, +} + #[derive(Debug, Clone)] pub struct Config { pub base_url: String, @@ -21,8 +28,23 @@ impl Config { base_url: Option, yolo: bool, ) -> Result { - Ok(Config { - api_key: api_key()?, + let config = Self::resolve_lenient(model, base_url, yolo); + if config.api_key.is_empty() { + return Err(format!( + "no API key: set OPENCODE_API_KEY or write one to {}", + key_file() + .map(|path| path.display().to_string()) + .unwrap_or_else(|| "~/.config/agent686/key".into()) + )); + } + 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) -> Config { + Config { + api_key: api_key().unwrap_or_default(), base_url: base_url .or_else(|| env_nonempty("AGENT686_BASE_URL")) .unwrap_or_else(|| DEFAULT_BASE_URL.to_string()), @@ -31,7 +53,7 @@ impl Config { .unwrap_or_else(|| DEFAULT_MODEL.to_string()), session: String::new(), yolo, - }) + } } pub fn endpoint(&self) -> String { @@ -43,26 +65,30 @@ fn env_nonempty(key: &str) -> Option { std::env::var(key).ok().filter(|v| !v.trim().is_empty()) } -/// The key comes from the environment first, then from a file, so a key never -/// has to live in shell history. -fn api_key() -> Result { - if let Some(k) = env_nonempty("OPENCODE_API_KEY") { - return Ok(k.trim().to_string()); +pub fn key_source() -> KeySource { + if env_nonempty("OPENCODE_API_KEY").is_some() { + return KeySource::Env; } if let Some(path) = key_file() { - if let Ok(k) = std::fs::read_to_string(&path) { - let k = k.trim().to_string(); - if !k.is_empty() { - return Ok(k); + if let Ok(key) = std::fs::read_to_string(&path) { + if !key.trim().is_empty() { + return KeySource::File(path); } } } - Err(format!( - "no API key: set OPENCODE_API_KEY or write one to {}", - key_file() - .map(|p| p.display().to_string()) - .unwrap_or_else(|| "~/.config/agent686/key".into()) - )) + KeySource::Missing +} + +/// The key comes from the environment first, then from a file, so a key never +/// has to live in shell history. +fn api_key() -> Result { + match key_source() { + KeySource::Env => Ok(env_nonempty("OPENCODE_API_KEY").unwrap_or_default()), + KeySource::File(path) => Ok(std::fs::read_to_string(path) + .map(|key| key.trim().to_string()) + .unwrap_or_default()), + KeySource::Missing => Err("no API key".into()), + } } fn key_file() -> Option { 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 @@ +use std::path::Path; + +use crate::config::{self, Config, KeySource}; +use crate::provider; +use crate::session; + +/// Prints the state of everything the harness needs, and checks the things that +/// are cheap to check but expensive to discover mid-turn. +pub fn run(cfg: &Config) -> i32 { + let mut failed = false; + + println!( + "agent686 {} · {} · {}", + env!("CARGO_PKG_VERSION"), + std::env::consts::ARCH, + std::env::consts::OS + ); + println!(); + + match config::key_source() { + KeySource::Env => row(true, "key", "present in OPENCODE_API_KEY"), + KeySource::File(path) => row(true, "key", &format!("present in {}", path.display())), + KeySource::Missing => { + row( + false, + "key", + "missing — set OPENCODE_API_KEY or write ~/.config/agent686/key", + ); + failed = true; + } + } + + let sessions = session::sessions_dir(); + match probe_dir(&sessions) { + Ok(()) => row(true, "sessions", &sessions.display().to_string()), + Err(error) => { + row(false, "sessions", &format!("{}: {error}", sessions.display())); + failed = true; + } + } + + let history = session::data_root().join("history"); + match std::fs::read_to_string(&history) { + Ok(text) => row( + true, + "history", + &format!("{} ({} entries)", history.display(), text.lines().count()), + ), + Err(_) => row(true, "history", &format!("{} (new)", history.display())), + } + + row(true, "provider", &cfg.base_url); + row(true, "model", &cfg.model); + + if cfg.api_key.is_empty() { + row(false, "auth", "skipped: no key"); + failed = true; + } else { + match provider::models(cfg) { + Ok(models) => { + row(true, "auth", &format!("ok — {} models visible", models.len())); + if models.iter().any(|id| id == &cfg.model) { + row(true, "model known", "yes"); + } else { + row( + false, + "model known", + "no — the provider does not list this id; pick another with --model", + ); + failed = true; + } + } + Err(error) => { + row(false, "auth", &error.to_string()); + failed = true; + } + } + } + + println!(); + if failed { + println!("some checks failed"); + 1 + } else { + println!("all checks passed"); + 0 + } +} + +fn row(ok: bool, label: &str, detail: &str) { + println!("{:<13} {:<4} {detail}", label, if ok { "ok" } else { "FAIL" }); +} + +fn probe_dir(dir: &Path) -> std::io::Result<()> { + std::fs::create_dir_all(dir)?; + let probe = dir.join(".doctor-probe"); + std::fs::write(&probe, b"ok")?; + std::fs::remove_file(probe) +} 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 @@ pub mod agent; pub mod config; +pub mod doctor; pub mod line; pub mod provider; pub 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: --session resume a session, creating it if the id is new -c, --continue resume the most recent session --list list sessions and exit + --doctor check key, directories, provider and model, then exit + -V, --version print the version and exit --yolo approve every tool call without asking -h, --help this text @@ -47,6 +49,7 @@ fn main() { let mut resume = None; let mut continue_last = false; let mut list = false; + let mut doctor = false; let mut yolo = false; let mut args = std::env::args().skip(1); @@ -57,6 +60,11 @@ fn main() { "--session" | "--resume" => resume = args.next(), "-c" | "--continue" => continue_last = true, "--list" => list = true, + "--doctor" => doctor = true, + "-V" | "--version" => { + println!("agent686 {}", env!("CARGO_PKG_VERSION")); + return; + } "--yolo" => yolo = true, "-h" | "--help" => { print!("{HELP}"); @@ -78,6 +86,11 @@ fn main() { return; } + if doctor { + let config = Config::resolve_lenient(model, base_url, yolo); + std::process::exit(agent686::doctor::run(&config)); + } + let mut cfg = match Config::resolve(model, base_url, yolo) { Ok(cfg) => cfg, 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 { #[serde(default)] arguments: Option, } + +/// Lists the models the provider offers for this key, for `--doctor`. +pub fn models(cfg: &Config) -> Result, Error> { + let agent: ureq::Agent = ureq::Agent::config_builder() + .http_status_as_error(false) + .timeout_connect(Some(Duration::from_secs(10))) + .timeout_recv_response(Some(Duration::from_secs(20))) + .timeout_per_read(Some(Duration::from_secs(20))) + .build() + .into(); + + let url = format!("{}/models", cfg.base_url.trim_end_matches('/')); + let mut response = 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()))?; + + let status = response.status().as_u16(); + let body = response + .body_mut() + .with_config() + .limit(8 * 1024 * 1024) + .read_to_string() + .unwrap_or_default(); + + if !(200..300).contains(&status) { + return Err(Error::Status { + code: status, + message: explain(status, &error_message(&body)), + }); + } + + let value: Value = serde_json::from_str(&body) + .map_err(|e| Error::Transport(format!("could not parse the model list: {e}")))?; + Ok(value + .get("data") + .and_then(|data| data.as_array()) + .map(|models| { + models + .iter() + .filter_map(|model| model.get("id").and_then(|id| id.as_str())) + .map(|id| id.to_string()) + .collect() + }) + .unwrap_or_default()) +} -- cgit v1.2.3