Your own team of AI bots in one self-hosted binary: spaces, every account you have, handoffs, approvals and routines. Open-source, self-hosted alternative to Grok Bot, Claude Duet and OpenAI dots. Rust + React.
Rust ai-agentsai-assistantai-botautomationbotbots-teamchatbotclaude-duetgrokgrok-botgrok-bot-alternativeharnessllmmulti-agentopenai-dotsopenbotpersonal-agentrustself-hostedselfhosted-ai
Engines: real access checks, skip engines that can't run, no fake fallback
Lin (kwant bot)aed7e53c1465
diff --git a/src/drivers/engines.rs b/src/drivers/engines.rsnew file mode 100644index 00000000..b2ff29eb--- /dev/null+++ b/src/drivers/engines.rs@@ -0,0 +1,881 @@+//! Which engines can actually run on this host, and the models each one offers: every CLI's+//! own sign-in check, every API key against its provider's free model list, and Ollama's pulled+//! models. Checks run in the background (at startup and on Re-check) and are cached; turns only+//! read the cache, and a turn the provider refuses marks its engine at once.++use crate::profiles::{classify::redact_detail, Engine, FailClass, ProviderFailure};+use chrono::{DateTime, Utc};+use serde::Serialize;+use serde_json::Value;+use std::collections::HashMap;+use std::process::Stdio;+use std::sync::RwLock;+use std::time::Duration;++/// Longest one engine's check may take, all its commands and requests included.+pub const PROBE_TIMEOUT: Duration = Duration::from_secs(10);++/// What a turn gets when no engine at all can run.+pub const NO_ENGINE_MESSAGE: &str = "No engine is available — check Settings → Engines.";++#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize)]+#[serde(rename_all = "snake_case")]+pub enum EngineId {+ Claude,+ Codex,+ Grok,+ AnthropicApi,+ OpenaiApi,+ XaiApi,+ Ollama,+}++#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]+#[serde(rename_all = "snake_case")]+pub enum EngineKind {+ Cli,+ Api,+ Local,+}++#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]+#[serde(rename_all = "snake_case")]+pub enum EngineStatus {+ Ready,+ SignedOut,+ NotInstalled,+ Error,+ /// Not checked yet (startup).+ Checking,+}++impl EngineId {+ /// Every engine, in the order the API lists them.+ pub const ALL: [EngineId; 7] = [+ EngineId::Claude,+ EngineId::Codex,+ EngineId::Grok,+ EngineId::AnthropicApi,+ EngineId::OpenaiApi,+ EngineId::XaiApi,+ EngineId::Ollama,+ ];++ pub fn name(self) -> &'static str {+ match self {+ EngineId::Claude => "Claude Code CLI",+ EngineId::Codex => "OpenAI Codex CLI",+ EngineId::Grok => "Grok CLI",+ EngineId::AnthropicApi => "Anthropic API",+ EngineId::OpenaiApi => "OpenAI API",+ EngineId::XaiApi => "xAI API",+ EngineId::Ollama => "Ollama",+ }+ }++ pub fn kind(self) -> EngineKind {+ match self {+ EngineId::Claude | EngineId::Codex | EngineId::Grok => EngineKind::Cli,+ EngineId::AnthropicApi | EngineId::OpenaiApi | EngineId::XaiApi => EngineKind::Api,+ EngineId::Ollama => EngineKind::Local,+ }+ }++ /// The CLI and the API that run a model family.+ pub fn of_family(engine: Engine) -> (EngineId, EngineId) {+ match engine {+ Engine::Claude => (EngineId::Claude, EngineId::AnthropicApi),+ Engine::Codex => (EngineId::Codex, EngineId::OpenaiApi),+ Engine::Grok => (EngineId::Grok, EngineId::XaiApi),+ }+ }+}++#[derive(Debug, Clone, PartialEq, Serialize)]+pub struct EngineModel {+ pub id: String,+ pub label: String,+ pub default: bool,+}++/// One engine as `GET /api/engines` shows it.+#[derive(Debug, Clone, PartialEq, Serialize)]+pub struct EngineReport {+ pub id: EngineId,+ pub name: String,+ pub kind: EngineKind,+ pub status: EngineStatus,+ pub detail: Option<String>,+ pub version: Option<String>,+ pub models: Vec<EngineModel>,+ pub checked_at: Option<DateTime<Utc>>,+}++impl EngineReport {+ fn checking(id: EngineId) -> Self {+ Self::from_probe(id, Probe::new(EngineStatus::Checking, None), None)+ }++ fn from_probe(id: EngineId, p: Probe, checked_at: Option<DateTime<Utc>>) -> Self {+ Self {+ id,+ name: id.name().into(),+ kind: id.kind(),+ status: p.status,+ detail: p.detail,+ version: p.version,+ models: if p.status == EngineStatus::Ready { p.models } else { Vec::new() },+ checked_at,+ }+ }++ /// The model a turn uses when none is picked.+ pub fn default_model(&self) -> Option<&EngineModel> {+ self.models.iter().find(|m| m.default).or(self.models.first())+ }+}++/// The result of one check, before it gets a time stamp.+#[derive(Debug, Clone, PartialEq)]+pub struct Probe {+ pub status: EngineStatus,+ pub detail: Option<String>,+ pub version: Option<String>,+ pub models: Vec<EngineModel>,+}++impl Probe {+ fn new(status: EngineStatus, detail: Option<String>) -> Self {+ Self { status, detail, version: None, models: Vec::new() }+ }+ fn ready(detail: impl Into<String>, models: Vec<EngineModel>) -> Self {+ Self { models, ..Self::new(EngineStatus::Ready, Some(detail.into())) }+ }+ fn signed_out(detail: impl Into<String>) -> Self {+ Self::new(EngineStatus::SignedOut, Some(detail.into()))+ }+ fn not_installed(detail: impl Into<String>) -> Self {+ Self::new(EngineStatus::NotInstalled, Some(detail.into()))+ }+ fn error(detail: impl Into<String>) -> Self {+ Self::new(EngineStatus::Error, Some(detail.into()))+ }+ fn with_version(mut self, version: Option<String>) -> Self {+ self.version = version;+ self+ }+}++/// Everything the checks need, read once from Settings and the environment.+#[derive(Debug, Clone, Default)]+pub struct ProbeEnv {+ pub claude_bin: Option<String>,+ pub codex_bin: Option<String>,+ pub grok_bin: Option<String>,+ pub anthropic_key: Option<String>,+ pub openai_key: Option<String>,+ pub xai_key: Option<String>,+ /// Ollama server root (no `/v1`).+ pub ollama_root: String,+ pub ollama_installed: bool,+ pub anthropic_base: String,+ pub openai_base: String,+ pub xai_base: String,+}++impl ProbeEnv {+ /// This host: CLIs on PATH, keys from Settings or else the env (as turns use them).+ pub async fn from_settings(db: &crate::db::Database) -> Self {+ async fn key(db: &crate::db::Database, setting: &str, var: &str) -> Option<String> {+ db.get_setting(setting)+ .await+ .ok()+ .flatten()+ .or_else(|| std::env::var(var).ok())+ .filter(|k| !k.trim().is_empty())+ }+ let ollama_url = db.get_setting("ollama_url").await.ok().flatten();+ Self {+ claude_bin: super::find_cli_binary("claude"),+ codex_bin: super::find_cli_binary("codex"),+ grok_bin: super::find_cli_binary("grok"),+ anthropic_key: key(db, "anthropic_api_key", "ANTHROPIC_API_KEY").await,+ openai_key: key(db, "openai_api_key", "OPENAI_API_KEY").await,+ xai_key: key(db, "xai_api_key", "XAI_API_KEY").await,+ ollama_root: super::ollama_root(ollama_url.as_deref()),+ ollama_installed: super::find_cli_binary("ollama").is_some(),+ anthropic_base: "https://api.anthropic.com".into(),+ openai_base: "https://api.openai.com".into(),+ xai_base: "https://api.x.ai".into(),+ }+ }+}++/// Checks one engine, never taking longer than [`PROBE_TIMEOUT`].+pub async fn probe(id: EngineId, env: &ProbeEnv) -> Probe {+ probe_within(id, env, PROBE_TIMEOUT).await+}++pub async fn probe_within(id: EngineId, env: &ProbeEnv, limit: Duration) -> Probe {+ let check = async {+ match id {+ EngineId::Claude => probe_claude(env.claude_bin.as_deref()).await,+ EngineId::Codex => probe_codex(env.codex_bin.as_deref()).await,+ EngineId::Grok => probe_grok(env.grok_bin.as_deref()).await,+ EngineId::AnthropicApi | EngineId::OpenaiApi | EngineId::XaiApi => probe_api(id, env).await,+ EngineId::Ollama => probe_ollama(env).await,+ }+ };+ // Dropping the check kills its commands (kill_on_drop) and aborts its requests.+ tokio::time::timeout(limit, check)+ .await+ .unwrap_or_else(|_| Probe::error(format!("Check timed out after {}s", limit.as_secs())))+}++struct CmdOut {+ success: bool,+ stdout: String,+ stderr: String,+}++async fn run(bin: &str, args: &[&str]) -> Result<CmdOut, String> {+ let out = tokio::process::Command::new(bin)+ .args(args)+ .env("NO_COLOR", "1")+ .stdin(Stdio::null())+ .stdout(Stdio::piped())+ .stderr(Stdio::piped())+ .kill_on_drop(true)+ .output()+ .await+ .map_err(|e| format!("Couldn't run {bin}: {e}"))?;+ Ok(CmdOut {+ success: out.status.success(),+ stdout: String::from_utf8_lossy(&out.stdout).into_owned(),+ stderr: String::from_utf8_lossy(&out.stderr).into_owned(),+ })+}++/// The version number in `--version` output: "2.1.296 (Claude Code)", "codex-cli 0.162.1",+/// "grok 1.0.62 (1474f9cb)".+pub fn parse_version(text: &str) -> Option<String> {+ let line = text.lines().map(str::trim).find(|l| !l.is_empty())?;+ line.split_whitespace()+ .map(|w| w.trim_start_matches('v'))+ .find(|w| w.chars().next().is_some_and(|c| c.is_ascii_digit()) && w.contains('.'))+ .map(|w| w.chars().take(40).collect())+}++async fn version_of(bin: &str) -> Option<String> {+ run(bin, &["--version"]).await.ok().and_then(|o| parse_version(&o.stdout))+}++/// First non-empty line of a failed command, redacted, for the reason shown.+fn failure_line(out: &CmdOut) -> String {+ let text = format!("{}\n{}", out.stderr, out.stdout);+ let line = text+ .lines()+ .map(|l| crate::profiles::login::strip_ansi(l).trim().to_string())+ .find(|l| !l.is_empty())+ .unwrap_or_else(|| "no output".into());+ redact_detail(&line, 120)+}++/// Claude Code has no command that lists models; these aliases always point at the latest.+pub fn claude_cli_models() -> Vec<EngineModel> {+ [+ ("opus", "Claude Opus (latest)", true),+ ("sonnet", "Claude Sonnet (latest)", false),+ ("haiku", "Claude Haiku (latest)", false),+ ("fable", "Claude Fable (latest)", false),+ ]+ .into_iter()+ .map(|(id, label, default)| EngineModel { id: id.into(), label: label.into(), default })+ .collect()+}++async fn probe_claude(bin: Option<&str>) -> Probe {+ let Some(bin) = bin else {+ return Probe::not_installed("Claude Code isn't installed");+ };+ let version = version_of(bin).await;+ // `auth status` asks Claude Code itself, so a login kept in the macOS Keychain counts.+ let out = match run(bin, &["auth", "status", "--json"]).await {+ Ok(o) => o,+ Err(e) => return Probe::error(e).with_version(version),+ };+ let parsed: Option<Value> = serde_json::from_str(out.stdout.trim()).ok();+ let probe = match parsed.as_ref().and_then(|v| v["loggedIn"].as_bool()) {+ Some(true) => {+ let v = parsed.as_ref().unwrap();+ let how = ["authMethod", "apiProvider"]+ .iter()+ .find_map(|k| v[*k].as_str().filter(|s| !s.is_empty()))+ .map(|s| format!("Signed in ({})", redact_detail(s, 40)))+ .unwrap_or_else(|| "Signed in".into());+ Probe::ready(how, claude_cli_models())+ }+ Some(false) => Probe::signed_out("Not signed in: run `claude auth login`"),+ None => Probe::error(format!("Couldn't read the sign-in status: {}", failure_line(&out))),+ };+ probe.with_version(version)+}++/// Models in `codex debug models` JSON that codex lists, best first.+pub fn parse_codex_models(json: &str) -> Vec<EngineModel> {+ let Ok(v) = serde_json::from_str::<Value>(json.trim()) else {+ return Vec::new();+ };+ let mut listed: Vec<(i64, String, String)> = v["models"]+ .as_array()+ .into_iter()+ .flatten()+ .filter(|m| m["visibility"].as_str().is_none_or(|s| s == "list"))+ .filter_map(|m| {+ let id = m["slug"].as_str()?.to_string();+ let label = m["display_name"].as_str().unwrap_or(&id).to_string();+ Some((m["priority"].as_i64().unwrap_or(i64::MAX), id, label))+ })+ .collect();+ listed.sort();+ listed+ .into_iter()+ .enumerate()+ .map(|(i, (_, id, label))| EngineModel { id, label, default: i == 0 })+ .collect()+}++/// Used when a CLI's model list can't be read: run it without `--model`.+fn cli_default_model(engine: &str) -> Vec<EngineModel> {+ vec![EngineModel { id: "default".into(), label: format!("{engine} default"), default: true }]+}++async fn probe_codex(bin: Option<&str>) -> Probe {+ let Some(bin) = bin else {+ return Probe::not_installed("Codex isn't installed");+ };+ let version = version_of(bin).await;+ let out = match run(bin, &["login", "status"]).await {+ Ok(o) => o,+ Err(e) => return Probe::error(e).with_version(version),+ };+ let status = crate::profiles::status::codex_status(out.success, &out.stdout, &out.stderr);+ let probe = if status.signed_in == Some(true) {+ let models = match run(bin, &["debug", "models"]).await {+ Ok(o) if o.success => parse_codex_models(&o.stdout),+ _ => Vec::new(),+ };+ let models = if models.is_empty() { cli_default_model("Codex") } else { models };+ Probe::ready(status.account_label.unwrap_or_else(|| "Signed in".into()), models)+ } else if !out.success && !format!("{}{}", out.stdout, out.stderr).to_lowercase().contains("not logged in") {+ Probe::error(format!("Couldn't read the sign-in status: {}", failure_line(&out)))+ } else {+ Probe::signed_out("Not signed in: run `codex login`")+ };+ probe.with_version(version)+}++/// `grok models` output: whether it's signed in, and the models it lists.+pub fn parse_grok_models(text: &str) -> (bool, Vec<EngineModel>) {+ let lower = text.to_lowercase();+ let signed_out = ["not authenticated", "not logged in", "not signed in", "please log in", "grok login"]+ .iter()+ .any(|p| lower.contains(p));+ let default_line = text+ .lines()+ .find_map(|l| l.trim().strip_prefix("Default model:").map(|m| m.trim().to_string()));+ let mut models: Vec<EngineModel> = text+ .lines()+ .skip_while(|l| !l.trim().starts_with("Available models"))+ .skip(1)+ .filter_map(|l| {+ let l = l.trim();+ let rest = l.strip_prefix('*').or_else(|| l.strip_prefix('-'))?.trim();+ let id = rest.split_whitespace().next()?.to_string();+ let default = rest.contains("(default)") || default_line.as_deref() == Some(id.as_str());+ Some(EngineModel { label: id.clone(), id, default })+ })+ .collect();+ if !models.is_empty() && !models.iter().any(|m| m.default) {+ models[0].default = true;+ }+ (!signed_out, models)+}++async fn probe_grok(bin: Option<&str>) -> Probe {+ let Some(bin) = bin else {+ return Probe::not_installed("Grok CLI isn't installed");+ };+ let version = version_of(bin).await;+ // grok has no status command; `grok models` says whether it's authenticated, for free.+ let out = match run(bin, &["models"]).await {+ Ok(o) => o,+ Err(e) => return Probe::error(e).with_version(version),+ };+ let (signed_in, models) = parse_grok_models(&format!("{}\n{}", out.stdout, out.stderr));+ let probe = if !signed_in {+ Probe::signed_out("Not signed in: run `grok login`")+ } else if !out.success {+ Probe::error(format!("Couldn't check: {}", failure_line(&out)))+ } else {+ let models = if models.is_empty() { cli_default_model("Grok") } else { models };+ Probe::ready("Signed in", models)+ };+ probe.with_version(version)+}++/// Chat models in a provider's `GET /v1/models` reply, newest first, default marked.+pub fn parse_api_models(id: EngineId, body: &Value) -> Vec<EngineModel> {+ let chat = |m: &str| match id {+ EngineId::AnthropicApi => m.starts_with("claude"),+ EngineId::XaiApi => m.contains("grok") && !m.contains("image") && !m.contains("imagine"),+ _ => {+ let family = m.starts_with("gpt-")+ || m.starts_with("chatgpt")+ || (m.starts_with('o') && m[1..].starts_with(|c: char| c.is_ascii_digit()));+ let other = ["audio", "realtime", "tts", "transcribe", "image", "search", "embedding", "moderation", "instruct"];+ family && !other.iter().any(|o| m.contains(o))+ }+ };+ let mut models: Vec<(i64, String, String)> = body["data"]+ .as_array()+ .into_iter()+ .flatten()+ .filter_map(|m| {+ let mid = m["id"].as_str()?;+ chat(mid).then(|| {+ let label = m["display_name"].as_str().unwrap_or(mid).to_string();+ let created = m["created"]+ .as_i64()+ .or_else(|| m["created_at"].as_str().and_then(|s| DateTime::parse_from_rfc3339(s).ok()).map(|t| t.timestamp()))+ .unwrap_or(0);+ (created, mid.to_string(), label)+ })+ })+ .collect();+ // Newest first; the provider's own order breaks ties (Anthropic already lists newest first).+ models.sort_by_key(|m| std::cmp::Reverse(m.0));+ let preferred = (id == EngineId::AnthropicApi)+ .then_some(super::api::DEFAULT_CLAUDE_MODEL)+ .filter(|d| models.iter().any(|m| m.1 == *d));+ models+ .into_iter()+ .enumerate()+ .map(|(i, (_, mid, label))| EngineModel {+ default: preferred.map_or(i == 0, |d| d == mid),+ id: mid,+ label,+ })+ .collect()+}++async fn probe_api(id: EngineId, env: &ProbeEnv) -> Probe {+ let (key, base) = match id {+ EngineId::AnthropicApi => (&env.anthropic_key, &env.anthropic_base),+ EngineId::OpenaiApi => (&env.openai_key, &env.openai_base),+ _ => (&env.xai_key, &env.xai_base),+ };+ let Some(key) = key else {+ return Probe::not_installed("No API key: add one in Settings");+ };+ let client = match reqwest::Client::builder().timeout(PROBE_TIMEOUT).build() {+ Ok(c) => c,+ Err(e) => return Probe::error(format!("Couldn't start the check: {e}")),+ };+ // Listing models is free on every provider and needs a valid key.+ let mut req = client.get(format!("{}/v1/models", base.trim_end_matches('/')));+ req = if id == EngineId::AnthropicApi {+ req.header("x-api-key", key).header("anthropic-version", "2023-06-01")+ } else {+ req.bearer_auth(key)+ };+ let resp = match req.send().await {+ Ok(r) => r,+ Err(e) => {+ let why = if e.is_timeout() { "timed out" } else { "network error" };+ return Probe::error(format!("Couldn't reach {} ({why})", id.name()));+ }+ };+ let status = resp.status().as_u16();+ let text = resp.text().await.unwrap_or_default();+ if (200..300).contains(&status) {+ let body: Value = serde_json::from_str(&text).unwrap_or(Value::Null);+ return Probe::ready("API key accepted", parse_api_models(id, &body));+ }+ api_refusal(status, &text)+}++/// A refused key check as a status and reason; the key itself never appears in it.+pub fn api_refusal(status: u16, body: &str) -> Probe {+ match crate::profiles::classify(Some(status), body, Utc::now()) {+ Some((FailClass::Auth, _)) => Probe::signed_out(format!("API key rejected ({status})")),+ Some((FailClass::Quota, _)) => Probe::error(format!("Quota exceeded ({status})")),+ _ => Probe::error(format!("The provider answered HTTP {status}")),+ }+}++/// Model names in Ollama's `/api/tags` reply; `OLLAMA_MODEL` (or else the first) is the default.+pub fn parse_ollama_models(body: &Value, preferred: Option<&str>) -> Vec<EngineModel> {+ let names: Vec<String> = body["models"]+ .as_array()+ .into_iter()+ .flatten()+ .filter_map(|m| m["name"].as_str().map(str::to_string))+ .collect();+ let preferred = preferred.filter(|p| names.iter().any(|n| n == p));+ names+ .iter()+ .enumerate()+ .map(|(i, n)| EngineModel {+ id: n.clone(),+ label: n.clone(),+ default: preferred.map_or(i == 0, |p| p == n),+ })+ .collect()+}++async fn probe_ollama(env: &ProbeEnv) -> Probe {+ let Ok(client) = reqwest::Client::builder().timeout(Duration::from_secs(3)).build() else {+ return Probe::error("Couldn't start the check");+ };+ let root = env.ollama_root.trim_end_matches('/');+ let tags = match client.get(format!("{root}/api/tags")).send().await {+ Ok(r) if r.status().is_success() => r.json::<Value>().await.unwrap_or(Value::Null),+ Ok(r) => return Probe::error(format!("Ollama answered HTTP {}", r.status().as_u16())),+ Err(_) if env.ollama_installed => {+ return Probe::error(format!("Ollama isn't running at {root}: run `ollama serve`"))+ }+ Err(_) => return Probe::not_installed(format!("Ollama isn't running at {root}")),+ };+ let version = match client.get(format!("{root}/api/version")).send().await {+ Ok(r) => r.json::<Value>().await.ok().and_then(|v| v["version"].as_str().map(str::to_string)),+ Err(_) => None,+ };+ let preferred = std::env::var("OLLAMA_MODEL").ok();+ let models = parse_ollama_models(&tags, preferred.as_deref().map(str::trim));+ let probe = if models.is_empty() {+ Probe::error("No models pulled: run `ollama pull llama3.2`")+ } else {+ Probe::ready(format!("{} model(s) pulled", models.len()), models)+ };+ probe.with_version(version)+}++/// A refusal seen during a turn, shown over the last check until it expires or the next check.+#[derive(Debug, Clone)]+struct Mark {+ status: EngineStatus,+ detail: String,+ at: DateTime<Utc>,+ until: Option<DateTime<Utc>>,+}++/// Cached engine checks, shared by the API and turn routing.+#[derive(Default)]+pub struct EngineRegistry {+ checked: RwLock<HashMap<EngineId, EngineReport>>,+ marks: RwLock<HashMap<EngineId, Mark>>,+ running: tokio::sync::Mutex<()>,+}++impl EngineRegistry {+ /// Every engine as it stands: last check, with any newer refusal from a turn on top.+ pub fn snapshot(&self) -> Vec<EngineReport> {+ EngineId::ALL.iter().map(|id| self.report(*id)).collect()+ }++ pub fn report(&self, id: EngineId) -> EngineReport {+ let mut report = self+ .checked+ .read()+ .unwrap()+ .get(&id)+ .cloned()+ .unwrap_or_else(|| EngineReport::checking(id));+ let now = Utc::now();+ if let Some(mark) = self.marks.read().unwrap().get(&id) {+ if mark.until.is_none_or(|u| u > now) {+ report.status = mark.status;+ report.detail = Some(mark.detail.clone());+ report.models.clear();+ report.checked_at = Some(mark.at);+ }+ }+ report+ }++ pub fn status(&self, id: EngineId) -> EngineStatus {+ self.report(id).status+ }++ /// Whether a turn may use the engine. Before the first check finishes, `present` (binary+ /// found, key set) decides, as before checks existed.+ pub fn usable(&self, id: EngineId, present: bool) -> bool {+ match self.status(id) {+ EngineStatus::Ready => true,+ EngineStatus::Checking => present,+ _ => false,+ }+ }++ /// Stores check results; a fresh check replaces any refusal a turn saw.+ pub fn store(&self, results: Vec<(EngineId, Probe)>) {+ let now = Utc::now();+ let mut checked = self.checked.write().unwrap();+ let mut marks = self.marks.write().unwrap();+ for (id, probe) in results {+ marks.remove(&id);+ checked.insert(id, EngineReport::from_probe(id, probe, Some(now)));+ }+ }++ /// Checks every engine at once and returns the result. A call while a check is already+ /// running waits for it and returns its result instead of checking twice.+ pub async fn recheck(&self, env: &ProbeEnv) -> Vec<EngineReport> {+ let _guard = match self.running.try_lock() {+ Ok(g) => g,+ Err(_) => {+ let _wait = self.running.lock().await;+ return self.snapshot();+ }+ };+ let results = futures::future::join_all(+ EngineId::ALL.iter().map(|id| async move { (*id, probe(*id, env).await) }),+ )+ .await;+ self.store(results);+ self.snapshot()+ }++ /// A turn on this engine was refused: auth marks it signed out until the next check, quota+ /// marks it unavailable until the quota resets. Transient failures change nothing.+ pub fn record_failure(&self, id: EngineId, failure: &ProviderFailure) {+ let now = Utc::now();+ let (status, detail, until) = match failure.class {+ FailClass::Auth => (+ EngineStatus::SignedOut,+ match id.kind() {+ EngineKind::Api => "API key rejected during a turn".to_string(),+ _ => "Signed out during a turn: sign in again, then Re-check".to_string(),+ },+ None,+ ),+ FailClass::Quota => {+ let until = failure.retry_at.unwrap_or_else(|| {+ now + chrono::Duration::minutes(crate::profiles::classify::DEFAULT_QUOTA_COOLDOWN_MINS)+ });+ (EngineStatus::Error, format!("Quota exceeded until {} UTC", until.format("%H:%M")), Some(until))+ }+ FailClass::Transient => return,+ };+ tracing::info!(engine = ?id, status = ?status, "engine marked unavailable after a refused turn");+ self.marks.write().unwrap().insert(id, Mark { status, detail, at: now, until });+ }+}++/// Which engine a turn on `target_model` runs on without a profile, and why not when none can.+#[derive(Debug, Clone, PartialEq)]+pub enum SystemRoute {+ Api { engine: EngineId, key: String },+ Cli { engine: EngineId, bin: String },+ Ollama,+}++fn is_ollama_model(model: &str) -> bool {+ model == "local_ollama" || model.starts_with("ollama/")+}++/// The provider key a turn would use: the Settings key, else the provider's env var.+pub fn key_for(api: EngineId, configured_key: Option<String>) -> Option<String> {+ let var = match api {+ EngineId::AnthropicApi => "ANTHROPIC_API_KEY",+ EngineId::XaiApi => "XAI_API_KEY",+ _ => "OPENAI_API_KEY",+ };+ configured_key.or_else(|| std::env::var(var).ok()).filter(|k| !k.trim().is_empty())+}++/// Picks the API (when its key works) or else the CLI (when signed in); never another family's+/// engine. `Err` says why nothing can run it.+pub fn system_route(+ engines: &EngineRegistry,+ target_model: &str,+ configured_key: Option<String>,+ find_bin: impl Fn(&str) -> Option<String>,+) -> Result<SystemRoute, String> {+ if is_ollama_model(target_model) {+ return if engines.usable(EngineId::Ollama, true) {+ Ok(SystemRoute::Ollama)+ } else {+ Err(unavailable(target_model, &[engines.report(EngineId::Ollama)]))+ };+ }+ let Some(family) = Engine::from_model(target_model) else {+ return Err(format!("No engine runs the model '{target_model}'. Pick another in the bot's settings."));+ };+ let (cli, api) = EngineId::of_family(family);+ if let Some(key) = key_for(api, configured_key) {+ if engines.usable(api, true) {+ return Ok(SystemRoute::Api { engine: api, key });+ }+ }+ if let Some(bin) = find_bin(family.as_str()) {+ if engines.usable(cli, true) {+ return Ok(SystemRoute::Cli { engine: cli, bin });+ }+ }+ Err(unavailable(target_model, &[engines.report(cli), engines.report(api)]))+}++/// "claude can't run right now (Claude Code CLI: Not signed in: run `claude auth login`; …)".+fn unavailable(target_model: &str, reports: &[EngineReport]) -> String {+ let why: Vec<String> = reports+ .iter()+ .map(|r| match (&r.detail, r.status) {+ (Some(d), _) => format!("{}: {d}", r.name),+ (None, EngineStatus::Checking) => format!("{}: not checked yet", r.name),+ (None, _) => format!("{}: not available", r.name),+ })+ .collect();+ format!(+ "'{target_model}' can't run right now ({}). Fix it in Settings → Engines, or pick another engine for this bot.",+ why.join("; ")+ )+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn versions_parse_from_each_cli() {+ assert_eq!(parse_version("2.1.296 (Claude Code)\n").as_deref(), Some("2.1.296"));+ assert_eq!(parse_version("codex-cli 0.162.1").as_deref(), Some("0.162.1"));+ assert_eq!(parse_version("grok 1.0.62 (1474f9cbdd91)").as_deref(), Some("1.0.62"));+ assert_eq!(parse_version("no version here"), None);+ }++ #[test]+ fn grok_models_output_parses_signed_in_and_out() {+ let out = "You are not authenticated.\n\nDefault model: grok-4.6\n\nAvailable models:\n * grok-4.6 (default)\n - grok-4.5\n";+ let (signed_in, models) = parse_grok_models(out);+ assert!(!signed_in);+ assert_eq!(models.iter().map(|m| m.id.as_str()).collect::<Vec<_>>(), ["grok-4.6", "grok-4.5"]);+ assert!(models[0].default && !models[1].default);+ let (signed_in, _) = parse_grok_models("Default model: grok-4.6\n\nAvailable models:\n * grok-4.6 (default)\n");+ assert!(signed_in);+ }++ #[test]+ fn codex_models_keep_listed_ones_by_priority() {+ let json = r#"{"models":[+ {"slug":"b","display_name":"B","visibility":"list","priority":2},+ {"slug":"hidden","display_name":"H","visibility":"hide","priority":0},+ {"slug":"a","display_name":"A","visibility":"list","priority":1}]}"#;+ let models = parse_codex_models(json);+ assert_eq!(models.iter().map(|m| m.id.as_str()).collect::<Vec<_>>(), ["a", "b"]);+ assert!(models[0].default && !models[1].default);+ assert!(parse_codex_models("not json").is_empty());+ }++ #[test]+ fn api_model_lists_keep_chat_models_newest_first() {+ let openai = serde_json::json!({"data":[+ {"id":"gpt-5.5","created":10},{"id":"text-embedding-3-large","created":20},+ {"id":"gpt-6-sol","created":30},{"id":"gpt-4o-realtime-preview","created":40},{"id":"o4-mini","created":5}]});+ let m = parse_api_models(EngineId::OpenaiApi, &openai);+ assert_eq!(m.iter().map(|m| m.id.as_str()).collect::<Vec<_>>(), ["gpt-6-sol", "gpt-5.5", "o4-mini"]);+ assert!(m[0].default);++ let anthropic = serde_json::json!({"data":[+ {"id":"claude-fable-5-1","display_name":"Claude Fable 5.1","created_at":"2026-09-01T00:00:00Z"},+ {"id":"claude-opus-5-5","display_name":"Claude Opus 5.5","created_at":"2026-08-01T00:00:00Z"}]});+ let m = parse_api_models(EngineId::AnthropicApi, &anthropic);+ assert_eq!(m[0].label, "Claude Fable 5.1");+ assert!(m.iter().find(|x| x.id == super::super::api::DEFAULT_CLAUDE_MODEL).unwrap().default);+ assert_eq!(m.iter().filter(|x| x.default).count(), 1);++ let xai = serde_json::json!({"data":[{"id":"grok-4.6","created":2},{"id":"grok-imagine-image","created":3}]});+ assert_eq!(parse_api_models(EngineId::XaiApi, &xai).len(), 1);+ }++ #[test]+ fn api_refusals_map_to_status_without_the_key() {+ assert_eq!(api_refusal(401, "{\"error\":\"invalid x-api-key\"}").status, EngineStatus::SignedOut);+ let quota = api_refusal(429, "You exceeded your current quota");+ assert_eq!(quota.status, EngineStatus::Error);+ assert_eq!(quota.detail.as_deref(), Some("Quota exceeded (429)"));+ assert_eq!(api_refusal(500, "boom").detail.as_deref(), Some("The provider answered HTTP 500"));+ }++ #[test]+ fn ollama_default_is_the_configured_model() {+ let tags = serde_json::json!({"models":[{"name":"llama3.2"},{"name":"qwen3"}]});+ let m = parse_ollama_models(&tags, Some("qwen3"));+ assert!(!m[0].default && m[1].default);+ assert!(parse_ollama_models(&tags, Some("missing"))[0].default);+ }++ #[test]+ fn unchecked_engines_fall_back_to_presence_then_follow_checks() {+ let reg = EngineRegistry::default();+ assert_eq!(reg.status(EngineId::Claude), EngineStatus::Checking);+ assert!(reg.usable(EngineId::Claude, true));+ assert!(!reg.usable(EngineId::Claude, false));+ reg.store(vec![(EngineId::Claude, Probe::signed_out("Not signed in"))]);+ assert!(!reg.usable(EngineId::Claude, true));+ reg.store(vec![(EngineId::Claude, Probe::ready("Signed in", claude_cli_models()))]);+ assert!(reg.usable(EngineId::Claude, false));+ assert_eq!(reg.report(EngineId::Claude).default_model().unwrap().id, "opus");+ }++ #[test]+ fn refused_turns_mark_the_engine_until_the_next_check() {+ let reg = EngineRegistry::default();+ reg.store(vec![(EngineId::Codex, Probe::ready("Signed in", Vec::new()))]);+ let auth = ProviderFailure { class: FailClass::Auth, retry_at: None, detail: String::new() };+ reg.record_failure(EngineId::Codex, &auth);+ assert_eq!(reg.status(EngineId::Codex), EngineStatus::SignedOut);+ reg.store(vec![(EngineId::Codex, Probe::ready("Signed in", Vec::new()))]);+ assert_eq!(reg.status(EngineId::Codex), EngineStatus::Ready);++ // A quota mark lifts by itself once the reset time passes+ let past = ProviderFailure { class: FailClass::Quota, retry_at: Some(Utc::now() - chrono::Duration::minutes(1)), detail: String::new() };+ reg.record_failure(EngineId::Codex, &past);+ assert_eq!(reg.status(EngineId::Codex), EngineStatus::Ready);+ let future = ProviderFailure { class: FailClass::Quota, retry_at: Some(Utc::now() + chrono::Duration::hours(1)), detail: String::new() };+ reg.record_failure(EngineId::Codex, &future);+ let r = reg.report(EngineId::Codex);+ assert_eq!(r.status, EngineStatus::Error);+ assert!(r.detail.unwrap().starts_with("Quota exceeded until"));++ let transient = ProviderFailure { class: FailClass::Transient, retry_at: None, detail: String::new() };+ reg.record_failure(EngineId::Claude, &transient);+ assert_eq!(reg.status(EngineId::Claude), EngineStatus::Checking);+ }++ #[test]+ fn routing_skips_engines_that_are_not_ready() {+ let reg = EngineRegistry::default();+ let bin = |_: &str| Some("/usr/bin/fake".to_string());+ reg.store(vec![+ (EngineId::AnthropicApi, Probe::signed_out("API key rejected (401)")),+ (EngineId::Claude, Probe::ready("Signed in", claude_cli_models())),+ ]);+ // The rejected key is skipped for the signed-in CLI+ assert!(matches!(+ system_route(®, "claude", Some("sk-bad".into()), bin),+ Ok(SystemRoute::Cli { engine: EngineId::Claude, .. })+ ));+ reg.store(vec![(EngineId::Claude, Probe::signed_out("Not signed in: run `claude auth login`"))]);+ let err = system_route(®, "claude", Some("sk-bad".into()), bin).unwrap_err();+ assert!(err.contains("claude auth login") && err.contains("API key rejected"), "{err}");+ assert!(!err.contains("sk-bad"));+ // Never another family's engine, even when it is ready+ reg.store(vec![(EngineId::Codex, Probe::ready("Signed in", Vec::new()))]);+ assert!(system_route(®, "claude", None, bin).is_err());+ assert!(system_route(®, "mystery-model", None, bin).is_err());+ reg.store(vec![(EngineId::Ollama, Probe::not_installed("Ollama isn't running"))]);+ assert!(system_route(®, "local_ollama", None, bin).is_err());+ }+}diff --git a/src/drivers/mod.rs b/src/drivers/mod.rsindex 71850921..01c07ae6 100644--- a/src/drivers/mod.rs+++ b/src/drivers/mod.rs@@ -1,5 +1,6 @@pub mod api;pub mod cli;+pub mod engines;pub mod events;pub mod grok;@@ -200,64 +201,71 @@ pub async fn first_ollama_model(root: &str) -> Option<String> {tags["models"].as_array()?.first()?["name"].as_str().map(str::to_string)}-/// Automatically detects all currently available and functional models on the host-pub async fn detect_available_models(db: &crate::db::Database) -> Vec<ModelDescriptor> {+/// The model families a turn can run on right now, for routing: a family counts when its API key+/// or CLI passed its check (see [`engines`]), or when `profile_engines` has a usable profile for+/// it. Empty when nothing can run; there is no made-up fallback.+pub async fn detect_available_models(+ db: &crate::db::Database,+ engines: &engines::EngineRegistry,+ profile_engines: &std::collections::HashSet<crate::profiles::Engine>,+) -> Vec<ModelDescriptor> {+ use crate::profiles::Engine;+ use engines::{EngineId, SystemRoute};let mut available = Vec::new();-- // 1. Claude- let claude_cli = find_cli_binary("claude");- let claude_key = db.get_setting("anthropic_api_key").await.ok().flatten()- .or_else(|| std::env::var("ANTHROPIC_API_KEY").ok());- if claude_cli.is_some() || claude_key.is_some() {- available.push(ModelDescriptor {- id: "claude".into(),- display_name: "Claude 3.5 Sonnet".into(),- capability_desc: if claude_key.is_none() {- "fastest local replies (~3s): everyday questions, quick answers, plus deep architecture and complex analysis"- } else {- "deep architecture, multi-file refactoring, long complex analysis"- }- .into(),- is_cli: claude_key.is_none() && claude_cli.is_some(),- });- }-- // 2. Grok- let grok_cli = find_cli_binary("grok");- let grok_key = db.get_setting("xai_api_key").await.ok().flatten()- .or_else(|| std::env::var("XAI_API_KEY").ok());- if grok_cli.is_some() || grok_key.is_some() {- available.push(ModelDescriptor {- id: "grok".into(),- display_name: "xAI Grok-2".into(),- capability_desc: if grok_key.is_none() {- "witty banter and technical reasoning; slow local CLI (10s+ per reply), avoid for quick questions"- } else {- "fast technical reasoning, witty banter, quick coding solutions"- }- .into(),- is_cli: grok_key.is_none() && grok_cli.is_some(),- });- }-- // 3. Codex- let codex_cli = find_cli_binary("codex");- let codex_key = db.get_setting("openai_api_key").await.ok().flatten()- .or_else(|| std::env::var("OPENAI_API_KEY").ok());- if codex_cli.is_some() || codex_key.is_some() {+ let families = [+ (+ Engine::Claude,+ "deep architecture, multi-file refactoring, long complex analysis",+ "fastest local replies (~3s): everyday questions, quick answers, plus deep architecture and complex analysis",+ ),+ (+ Engine::Grok,+ "fast technical reasoning, witty banter, quick coding solutions",+ "witty banter and technical reasoning; slow local CLI (10s+ per reply), avoid for quick questions",+ ),+ (+ Engine::Codex,+ "direct code generation, standard algorithms, regex, JSON transforms",+ "direct code generation, standard algorithms, regex, JSON transforms",+ ),+ ];+ for (family, api_desc, cli_desc) in families {+ let key = db.get_setting(family.key_setting()).await.ok().flatten();+ let route = engines::system_route(engines, family.as_str(), key, find_cli_binary);+ let engine = match &route {+ Ok(SystemRoute::Api { engine, .. }) | Ok(SystemRoute::Cli { engine, .. }) => Some(*engine),+ _ => None,+ };+ if engine.is_none() && !profile_engines.contains(&family) {+ continue;+ }+ let (cli, api) = EngineId::of_family(family);+ let report = engines.report(engine.unwrap_or(cli));+ let model = report.default_model().map(|m| m.label.clone());+ let fallback_name = match family {+ Engine::Claude => "Claude",+ Engine::Grok => "Grok",+ Engine::Codex => "OpenAI Codex",+ };available.push(ModelDescriptor {- id: "codex".into(),- display_name: "OpenAI Codex".into(),- capability_desc: "direct code generation, standard algorithms, regex, JSON transforms".into(),- is_cli: codex_key.is_none() && codex_cli.is_some(),+ id: family.as_str().into(),+ display_name: model.unwrap_or_else(|| fallback_name.into()),+ capability_desc: if engine == Some(api) { api_desc } else { cli_desc }.into(),+ is_cli: engine != Some(api),});}- // 4. Local Ollama- let ollama_url = db.get_setting("ollama_url").await.ok().flatten()- .or_else(|| std::env::var("OLLAMA_URL").ok());- // Having the binary isn't enough: routing here only works with the server up and a model pulled.- if let Some(model) = first_ollama_model(&ollama_root(ollama_url.as_deref())).await {+ // Local Ollama: before its first check, the old quick look at the server decides.+ let ollama = engines.report(EngineId::Ollama);+ let model = match ollama.status {+ engines::EngineStatus::Ready => ollama.default_model().map(|m| m.id.clone()),+ engines::EngineStatus::Checking => {+ let ollama_url = db.get_setting("ollama_url").await.ok().flatten();+ first_ollama_model(&ollama_root(ollama_url.as_deref())).await+ }+ _ => None,+ };+ if let Some(model) = model {available.push(ModelDescriptor {id: "local_ollama".into(),display_name: format!("Ollama ({model})"),@@ -266,16 +274,6 @@ pub async fn detect_available_models(db: &crate::db::Database) -> Vec<ModelDescr});}- // Fallback: If host has zero configured, provide default fleet so system functions- if available.is_empty() {- available.push(ModelDescriptor {- id: "grok".into(),- display_name: "Grok (Arcade Default)".into(),- capability_desc: "fast technical reasoning, witty banter, quick coding solutions".into(),- is_cli: false,- });- }-available}@@ -306,64 +304,31 @@ pub trait Driver: Send + Sync {) -> Result<TurnOutput, DriverError>;}-/// Creates a driver for a Kwant based on target model, configured API keys, and locally installed CLIs+/// The driver for a turn on `target_model` without a profile, and the engine it runs on: the+/// family's API when its key works, else its CLI when signed in. Engines whose check failed are+/// skipped, and another family is never used instead. `Err` explains why nothing can run it.pub fn resolve_driver_for_model(target_model: &str,configured_key: Option<String>,endpoint: Option<String>,-) -> Box<dyn Driver> {- // 1. If an explicit API key is provided, use ApiDriver directly- if let Some(key) = configured_key {- return Box::new(ApiDriver::new(Some(key), endpoint));- }-- // 2. Check environment variable for direct API key- let env_key = if target_model.contains("claude") {- std::env::var("ANTHROPIC_API_KEY").ok()- } else if target_model.contains("grok") {- std::env::var("XAI_API_KEY").ok()- } else if target_model.contains("codex") || target_model.contains("gpt") {- std::env::var("OPENAI_API_KEY").ok()- } else {- None- };-- if let Some(key) = env_key {- return Box::new(ApiDriver::new(Some(key), endpoint));- }-- // 3. Bring-Your-Own-Agent CLI auto-discovery (Claude, Grok, Codex)- if target_model.contains("claude") {- if let Some(bin) = find_cli_binary("claude") {- return Box::new(CliDriver::new(Some(bin), Some("claude".into())));+ engines: &engines::EngineRegistry,+) -> Result<(Box<dyn Driver>, engines::EngineId), String> {+ use engines::{EngineId, SystemRoute};+ Ok(match engines::system_route(engines, target_model, configured_key, find_cli_binary)? {+ SystemRoute::Ollama => (Box::new(ApiDriver::new(None, endpoint)), EngineId::Ollama),+ SystemRoute::Api { engine, key } => (Box::new(ApiDriver::new(Some(key), endpoint)), engine),+ SystemRoute::Cli { engine, bin } => {+ let name = crate::profiles::Engine::from_model(target_model).map(|e| e.as_str().to_string());+ (Box::new(CliDriver::new(Some(bin), name)), engine)}- } else if target_model.contains("grok") {- if let Some(bin) = find_cli_binary("grok") {- return Box::new(CliDriver::new(Some(bin), Some("grok".into())));- }- } else if target_model.contains("codex") || target_model.contains("gpt") {- if let Some(bin) = find_cli_binary("codex") {- return Box::new(CliDriver::new(Some(bin), Some("codex".into())));- }- } else if target_model == "local_ollama" {- return Box::new(ApiDriver::new(None, endpoint));- }-- // 4. Fallback: check if ANY local agent CLI is installed on this host- if let Some(bin) = find_cli_binary("claude") {- return Box::new(CliDriver::new(Some(bin), Some("claude".into())));- }- if let Some(bin) = find_cli_binary("grok") {- return Box::new(CliDriver::new(Some(bin), Some("grok".into())));- }- if let Some(bin) = find_cli_binary("codex") {- return Box::new(CliDriver::new(Some(bin), Some("codex".into())));- }-- // 5. Default to ApiDriver (which will prompt user to set an API key in Settings)- Box::new(ApiDriver::new(None, endpoint))+ })}+/// A driver for the kwant's pinned model, as before engine checks ran (nothing checked yet).+/// Without any way to run it, the API driver explains how to set one up.pub fn create_driver_for_kwant(kwant: &Kwant) -> Box<dyn Driver> {- resolve_driver_for_model(&kwant.preferred_model, None, None)+ match resolve_driver_for_model(&kwant.preferred_model, None, None, &engines::EngineRegistry::default()) {+ Ok((driver, _)) => driver,+ Err(_) => Box::new(ApiDriver::new(None, None)),+ }}diff --git a/src/main.rs b/src/main.rsindex 13e54858..5534cfd7 100644--- a/src/main.rs+++ b/src/main.rs@@ -148,6 +148,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {let state = AppState::new(config.clone(), db, tools, broker, router);kwnt::server::scheduler::spawn_background(state.clone(), shutdown.clone());+ kwnt::server::engine_routes::spawn_startup_check(state.clone());let app = create_router(state);let addr = format!("{}:{}", config.host, config.port);diff --git a/src/profiles/status.rs b/src/profiles/status.rsindex eacd1541..6366f396 100644--- a/src/profiles/status.rs+++ b/src/profiles/status.rs@@ -170,7 +170,7 @@ pub async fn probe(engine: Engine, home: Option<&Path>) -> ProfileStatus {}}-fn claude_status(stdout: &str) -> ProfileStatus {+pub(crate) fn claude_status(stdout: &str) -> ProfileStatus {let Ok(v) = serde_json::from_str::<serde_json::Value>(stdout.trim()) else {return ProfileStatus::default();};@@ -185,7 +185,7 @@ fn claude_status(stdout: &str) -> ProfileStatus {}}-fn codex_status(success: bool, stdout: &str, stderr: &str) -> ProfileStatus {+pub(crate) fn codex_status(success: bool, stdout: &str, stderr: &str) -> ProfileStatus {let text = format!("{stdout}\n{stderr}");let line = text.lines()diff --git a/src/server/engine_routes.rs b/src/server/engine_routes.rsnew file mode 100644index 00000000..218fe10f--- /dev/null+++ b/src/server/engine_routes.rs@@ -0,0 +1,40 @@+//! `GET /api/engines` and `POST /api/engines/recheck`: whether each engine can run, why not,+//! and the models it offers.++use super::AppState;+use crate::drivers::engines::{EngineReport, ProbeEnv};+use axum::{extract::State, Json};+use serde::Serialize;++#[derive(Serialize)]+pub struct EnginesResponse {+ pub engines: Vec<EngineReport>,+}++/// The cached checks; never waits on one. Engines not checked yet show as "checking".+pub async fn list(State(state): State<AppState>) -> Json<EnginesResponse> {+ Json(EnginesResponse { engines: state.engines.snapshot() })+}++/// Checks every engine again and answers once done (each check is capped at 10s).+pub async fn recheck(State(state): State<AppState>) -> Json<EnginesResponse> {+ Json(EnginesResponse { engines: recheck_all(&state).await })+}++pub async fn recheck_all(state: &AppState) -> Vec<EngineReport> {+ let env = ProbeEnv::from_settings(&state.db).await;+ state.engines.recheck(&env).await+}++/// Checks every engine in the background, so the first turns after startup see real status.+pub fn spawn_startup_check(state: AppState) {+ tokio::spawn(async move {+ let engines = recheck_all(&state).await;+ let ready: Vec<_> = engines+ .iter()+ .filter(|e| e.status == crate::drivers::engines::EngineStatus::Ready)+ .map(|e| e.name.as_str())+ .collect();+ tracing::info!(ready = ?ready, "engine checks finished");+ });+}diff --git a/src/server/mod.rs b/src/server/mod.rsindex de12b8bd..9bb0d586 100644--- a/src/server/mod.rs+++ b/src/server/mod.rs@@ -7,6 +7,7 @@ pub mod mcp_routes;pub mod mcp_runtime;pub mod profile_routes;pub mod profile_turn;+pub mod engine_routes;pub mod auth;pub mod continuity;pub mod scheduler;@@ -51,6 +52,8 @@ pub struct AppState {pub mcp_oauth: Arc<mcp_oauth::OAuthState>,/// LLM profiles: sign-in checks and in-app logins.pub profiles: Arc<crate::profiles::ProfileManager>,+ /// Which engines can run and their models: checked at startup and on Re-check.+ pub engines: Arc<crate::drivers::engines::EngineRegistry>,/// API token for requests from other machines (see `auth`).pub api_token: Arc<auth::ApiToken>,/// Live turns that have the agents' own tools, by bearer token.@@ -91,6 +94,7 @@ impl AppState {mcp_sessions: Arc::new(Mutex::new(HashMap::new())),mcp_oauth: Arc::new(mcp_oauth::OAuthState::default()),profiles,+ engines: Default::default(),api_token,self_tools: Default::default(),running_routines: Default::default(),@@ -121,6 +125,8 @@ pub fn create_router(state: AppState) -> Router {).route("/api/profiles/:id/login/:flow_id/code", post(profile_routes::submit_login_code)).route("/api/profiles/:id/logout", post(profile_routes::logout))+ .route("/api/engines", get(engine_routes::list))+ .route("/api/engines/recheck", post(engine_routes::recheck)).route("/api/laya/status", get(routes::laya_status)).route("/api/kwants", get(routes::list_kwants).post(routes::create_kwant)).route("/api/kwants/:id", put(routes::update_kwant))diff --git a/src/server/profile_turn.rs b/src/server/profile_turn.rsindex f5d13b72..cc93083b 100644--- a/src/server/profile_turn.rs+++ b/src/server/profile_turn.rs@@ -3,7 +3,9 @@use super::AppState;use crate::db::models::LlmProfile;+use crate::drivers::engines::EngineId;use crate::drivers::{find_cli_binary, resolve_driver_for_model, ApiDriver, CliDriver, Driver};+use std::collections::HashSet;use crate::profiles::{failover_order, Availability, Engine, FailClass, ProfileStatus, ProviderFailure,};@@ -39,16 +41,18 @@ pub async fn plan(state: &AppState, engine: Option<Engine>, kwant_id: &str) -> V)}-/// The driver for one attempt. `None` or the system profile: exactly the pre-profiles choice.+/// The driver for one attempt, and the engine it runs on when it's the host's own (no profile+/// or the system profile; see [`resolve_driver_for_model`]). `Err` when that engine can't run.pub async fn driver_for(state: &AppState,profile: Option<&LlmProfile>,target_model: &str,configured_key: Option<String>,endpoint: Option<String>,-) -> Box<dyn Driver> {+) -> Result<(Box<dyn Driver>, Option<EngineId>), String> {let Some(p) = profile.filter(|p| p.kind != "system") else {- return resolve_driver_for_model(target_model, configured_key, endpoint);+ return resolve_driver_for_model(target_model, configured_key, endpoint, &state.engines)+ .map(|(d, e)| (d, Some(e)));};let engine = Engine::parse(&p.engine).unwrap_or(Engine::Claude);if p.kind == "api_key" {@@ -59,16 +63,47 @@ pub async fn driver_for(.ok().flatten().map(|k| k.0);- return Box::new(ApiDriver::for_profile(key));+ return Ok((Box::new(ApiDriver::for_profile(key)), None));}let home = state.profiles.home_of(p).unwrap_or_default();- Box::new(- CliDriver::new(- find_cli_binary(engine.as_str()),- Some(engine.as_str().into()),- )- .with_profile_home(engine, home),- )+ Ok((+ Box::new(+ CliDriver::new(+ find_cli_binary(engine.as_str()),+ Some(engine.as_str().into()),+ )+ .with_profile_home(engine, home),+ ),+ None,+ ))+}++/// Engines with an enabled account of their own (not the system profile) that failover+/// would use: these engines can run even when the host's own CLI or key can't.+pub async fn profile_engines(state: &AppState) -> HashSet<Engine> {+ let db = &state.db;+ let (Ok(profiles), Ok(states), Ok(with_key)) = (+ db.list_profiles().await,+ db.list_profile_states().await,+ db.profile_ids_with_key().await,+ ) else {+ return HashSet::new();+ };+ let signed_out = state.profiles.signed_out();+ let now = chrono::Utc::now();+ profiles+ .iter()+ .filter(|p| p.enabled && p.kind != "system")+ .filter(|p| p.kind != "api_key" || with_key.contains(&p.id))+ .filter(|p| !signed_out.contains(&p.id))+ .filter(|p| {+ !states+ .get(&p.id)+ .and_then(|s| s.limited_until)+ .is_some_and(|t| t > now)+ })+ .filter_map(|p| Engine::parse(&p.engine))+ .collect()}/// Remembers a refusal so failover skips the profile: until its quota resets, or until it isdiff --git a/src/server/routes.rs b/src/server/routes.rsindex 9861520b..0504013b 100644--- a/src/server/routes.rs+++ b/src/server/routes.rs@@ -931,7 +931,25 @@ async fn run_kwant_turn_inner(let cancel_token = &scope.cancel_token;{- let available_models = crate::drivers::detect_available_models(&db).await;+ let profile_engines = super::profile_turn::profile_engines(state).await;+ let available_models =+ crate::drivers::detect_available_models(&db, &state.engines, &profile_engines).await;+ if available_models.is_empty() {+ let text = format!("⚠️ [{}] {}", target_kwant.name, crate::drivers::engines::NO_ENGINE_MESSAGE);+ event_broadcast.send(RuntimeEvent::TextDelta(text.clone()));+ event_broadcast.send(RuntimeEvent::TurnComplete {+ tokens: 0,+ duration_ms: 0,+ kwant_id: Some(target_kwant.id.clone()),+ profile_id: None,+ });+ let msg = NewMessage {+ reasoning_content: opts.label.clone(),+ ..scope.message("kwant", &target_kwant.name, text.clone())+ };+ scope.save(&msg, None).await;+ return Err(text);+ }let route = match router.route_prompt_with_models(&prompt, "chat", &available_models).await {Ok(r) => r,Err(_) => crate::router::RouteDecision {@@ -1133,14 +1151,34 @@ async fn run_kwant_turn_inner(let mut driver_result = None;let mut gave_up: Option<String> = None;for (i, profile) in attempts.iter().enumerate() {- let driver = super::profile_turn::driver_for(+ let (driver, host_engine) = match super::profile_turn::driver_for(state,profile.as_ref(),&target_model,configured_key.clone(),endpoint.clone(),)- .await;+ .await+ {+ Ok(d) => d,+ // The host's own CLI or key can't run it: try the next profile, else say why+ Err(why) if i + 1 < attempts.len() => {+ tracing::info!(kwant = %target_kwant.id, reason = %why, "skipping an engine that can't run");+ continue;+ }+ Err(why) => {+ let text = format!("⚠️ [{}] {why}", target_kwant.name);+ event_broadcast.send(RuntimeEvent::TextDelta(text.clone()));+ event_broadcast.send(RuntimeEvent::TurnComplete {+ tokens: 0,+ duration_ms: turn_start.elapsed().as_millis() as u64,+ kwant_id: Some(target_kwant.id.clone()),+ profile_id: profile.as_ref().map(|p| p.id.clone()),+ });+ gave_up = Some(text);+ break;+ }+ };let input = turn_input.clone();let (driver_tx, mut driver_rx) = mpsc::channel(32);let driver_task =@@ -1188,6 +1226,9 @@ async fn run_kwant_turn_inner(if let Some(p) = profile {super::profile_turn::record_failure(state, p, &failure).await;}+ if let Some(engine) = host_engine {+ state.engines.record_failure(engine, &failure);+ }let next = attempts.get(i + 1).and_then(|n| n.as_ref());if let (Some(from), Some(to), false) = (profile, next, side_effects) {let notice = super::profile_turn::switch_notice(from, to, &failure);@@ -1935,26 +1976,38 @@ pub async fn save_settings({return Err((StatusCode::BAD_REQUEST, Json(json!({ "error": e }))));}+ // A new key or Ollama URL is checked right away, in the background+ let mut engines_changed = false;if let Some(key) = payload.anthropic_api_key {if !key.starts_with('•') && !key.is_empty() {let _ = state.db.set_setting("anthropic_api_key", &key).await;+ engines_changed = true;}}if let Some(key) = payload.xai_api_key {if !key.starts_with('•') && !key.is_empty() {let _ = state.db.set_setting("xai_api_key", &key).await;+ engines_changed = true;}}if let Some(key) = payload.openai_api_key {if !key.starts_with('•') && !key.is_empty() {let _ = state.db.set_setting("openai_api_key", &key).await;+ engines_changed = true;}}if let Some(url) = payload.ollama_url {if !url.is_empty() {let _ = state.db.set_setting("ollama_url", &url).await;+ engines_changed = true;}}+ if engines_changed {+ let state = state.clone();+ tokio::spawn(async move {+ super::engine_routes::recheck_all(&state).await;+ });+ }if payload.max_turns_per_agent.is_some() || payload.max_turns_global.is_some() {let (per_agent, global) = state.turns.limiter.limits();let per_agent = payload.max_turns_per_agent.unwrap_or(per_agent);diff --git a/tests/engine_probe_test.rs b/tests/engine_probe_test.rsnew file mode 100644index 00000000..d0baeb01--- /dev/null+++ b/tests/engine_probe_test.rs@@ -0,0 +1,202 @@+//! Each engine check against fake CLIs (signed in, signed out, broken, hanging) and a fake+//! provider API, so every status and reason is pinned without touching real accounts.++use axum::{+ extract::State,+ http::{HeaderMap, StatusCode},+ routing::get,+ Json, Router,+};+use kwnt::drivers::engines::{probe, probe_within, EngineId, EngineStatus, ProbeEnv};+use serde_json::{json, Value};+use std::path::Path;+use std::time::{Duration, Instant};++fn script(dir: &Path, name: &str, body: &str) -> Option<String> {+ let path = dir.join(name);+ std::fs::write(&path, format!("#!/bin/sh\n{body}\n")).unwrap();+ #[cfg(unix)]+ {+ use std::os::unix::fs::PermissionsExt;+ std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).unwrap();+ }+ Some(path.to_string_lossy().into_owned())+}++#[tokio::test]+async fn cli_checks_report_each_status_with_a_reason() {+ let tmp = tempfile::tempdir().unwrap();+ let d = tmp.path();+ let claude_in = script(d, "claude-in", r#"case "$1" in+ --version) echo "9.9.9 (Claude Code)" ;;+ auth) echo '{"loggedIn":true,"authMethod":"claude.ai","email":"[email protected]"}' ;;+esac"#);+ let claude_out = script(d, "claude-out", r#"case "$1" in+ --version) echo "9.9.9 (Claude Code)" ;;+ auth) echo '{"loggedIn":false,"authMethod":"none"}'; exit 1 ;;+esac"#);+ let claude_broken = script(d, "claude-broken", r#"case "$1" in+ auth) echo "error: unknown command 'auth' sk-ant-api03-abcdefghijklmnopqrstuvwxyz" >&2; exit 2 ;;+esac"#);+ let claude_hang = script(d, "claude-hang", "sleep 30");+ let codex_in = script(d, "codex-in", r#"case "$1" in+ --version) echo "codex-cli 1.2.3" ;;+ login) echo "Logged in using ChatGPT" ;;+ debug) echo '{"models":[{"slug":"gpt-b","display_name":"GPT B","visibility":"list","priority":2},{"slug":"gpt-a","display_name":"GPT A","visibility":"list","priority":1},{"slug":"secret","visibility":"hide","priority":0}]}' ;;+esac"#);+ // Real codex prints this and still exits 0+ let codex_out = script(d, "codex-out", r#"case "$1" in+ login) echo "Not logged in" ;;+esac"#);+ let grok_out = script(d, "grok-out", r#"case "$1" in+ --version) echo "grok 1.0.62 (1474f9cbdd91)" ;;+ models) printf 'You are not authenticated.\n\nDefault model: grok-4.6\n\nAvailable models:\n * grok-4.6 (default)\n - grok-4.5\n' ;;+esac"#);+ let grok_in = script(d, "grok-in", r#"case "$1" in+ models) printf 'Default model: grok-4.6\n\nAvailable models:\n * grok-4.6 (default)\n - grok-4.5\n' ;;+esac"#);++ let env = |claude: &Option<String>, codex: &Option<String>, grok: &Option<String>| ProbeEnv {+ claude_bin: claude.clone(),+ codex_bin: codex.clone(),+ grok_bin: grok.clone(),+ ..ProbeEnv::default()+ };++ // Claude+ let p = probe(EngineId::Claude, &env(&claude_in, &None, &None)).await;+ assert_eq!(p.status, EngineStatus::Ready);+ assert_eq!(p.version.as_deref(), Some("9.9.9"));+ assert_eq!(p.detail.as_deref(), Some("Signed in (claude.ai)"));+ assert!(p.models.iter().any(|m| m.id == "opus" && m.default));+ let p = probe(EngineId::Claude, &env(&claude_out, &None, &None)).await;+ assert_eq!(p.status, EngineStatus::SignedOut);+ assert_eq!(p.detail.as_deref(), Some("Not signed in: run `claude auth login`"));+ assert!(p.models.is_empty());+ let p = probe(EngineId::Claude, &env(&claude_broken, &None, &None)).await;+ assert_eq!(p.status, EngineStatus::Error);+ let detail = p.detail.unwrap();+ assert!(detail.contains("unknown command"), "{detail}");+ assert!(!detail.contains("abcdefghijklmnop"), "a secret reached the reason: {detail}");+ let p = probe(EngineId::Claude, &env(&None, &None, &None)).await;+ assert_eq!(p.status, EngineStatus::NotInstalled);++ // A hanging CLI is cut off at the limit, not waited on+ let start = Instant::now();+ let p = probe_within(EngineId::Claude, &env(&claude_hang, &None, &None), Duration::from_secs(1)).await;+ assert!(start.elapsed() < Duration::from_secs(5), "took {:?}", start.elapsed());+ assert_eq!(p.status, EngineStatus::Error);+ assert_eq!(p.detail.as_deref(), Some("Check timed out after 1s"));++ // Codex+ let p = probe(EngineId::Codex, &env(&None, &codex_in, &None)).await;+ assert_eq!(p.status, EngineStatus::Ready);+ assert_eq!(p.version.as_deref(), Some("1.2.3"));+ let ids: Vec<_> = p.models.iter().map(|m| m.id.as_str()).collect();+ assert_eq!(ids, ["gpt-a", "gpt-b"]);+ assert!(p.models[0].default);+ let p = probe(EngineId::Codex, &env(&None, &codex_out, &None)).await;+ assert_eq!(p.status, EngineStatus::SignedOut);+ assert_eq!(p.detail.as_deref(), Some("Not signed in: run `codex login`"));++ // Grok+ let p = probe(EngineId::Grok, &env(&None, &None, &grok_out)).await;+ assert_eq!(p.status, EngineStatus::SignedOut);+ assert_eq!(p.version.as_deref(), Some("1.0.62"));+ assert_eq!(p.detail.as_deref(), Some("Not signed in: run `grok login`"));+ let p = probe(EngineId::Grok, &env(&None, &None, &grok_in)).await;+ assert_eq!(p.status, EngineStatus::Ready);+ assert_eq!(p.models.iter().find(|m| m.default).unwrap().id, "grok-4.6");+ assert_eq!(p.models.len(), 2);+}++async fn models(State(()): State<()>, headers: HeaderMap) -> (StatusCode, Json<Value>) {+ let key = headers+ .get("x-api-key")+ .or(headers.get("authorization"))+ .and_then(|v| v.to_str().ok())+ .unwrap_or_default()+ .trim_start_matches("Bearer ")+ .to_string();+ match key.as_str() {+ "good" => (+ StatusCode::OK,+ Json(json!({"data": [+ {"id": "claude-opus-5-5", "display_name": "Claude Opus 5.5", "created": 2},+ {"id": "gpt-6-sol", "created": 3},+ {"id": "grok-4.6", "created": 4},+ {"id": "text-embedding-3-large", "created": 9}+ ]})),+ ),+ "broke" => (+ StatusCode::TOO_MANY_REQUESTS,+ Json(json!({"error": {"message": "You exceeded your current quota"}})),+ ),+ _ => (+ StatusCode::UNAUTHORIZED,+ Json(json!({"error": {"type": "authentication_error", "message": "invalid x-api-key"}})),+ ),+ }+}++async fn serve(app: Router) -> String {+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let url = format!("http://{}", listener.local_addr().unwrap());+ tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });+ url+}++#[tokio::test]+async fn api_keys_are_checked_against_the_free_model_list() {+ let base = serve(+ Router::new()+ .route("/v1/models", get(models))+ .route("/api/tags", get(|| async { Json(json!({"models": [{"name": "llama3.2"}, {"name": "qwen3"}]})) }))+ .route("/api/version", get(|| async { Json(json!({"version": "0.9.1"})) }))+ .with_state(()),+ )+ .await;+ let env = |key: &str| ProbeEnv {+ anthropic_key: Some(key.into()),+ openai_key: Some(key.into()),+ xai_key: Some(key.into()),+ anthropic_base: base.clone(),+ openai_base: base.clone(),+ xai_base: base.clone(),+ ollama_root: base.clone(),+ ..ProbeEnv::default()+ };++ let p = probe(EngineId::AnthropicApi, &env("good")).await;+ assert_eq!(p.status, EngineStatus::Ready);+ assert_eq!(p.models.len(), 1);+ assert_eq!(p.models[0].label, "Claude Opus 5.5");+ let p = probe(EngineId::OpenaiApi, &env("good")).await;+ assert_eq!(p.models.iter().map(|m| m.id.as_str()).collect::<Vec<_>>(), ["gpt-6-sol"]);+ let p = probe(EngineId::XaiApi, &env("good")).await;+ assert_eq!(p.models[0].id, "grok-4.6");++ for id in [EngineId::AnthropicApi, EngineId::OpenaiApi, EngineId::XaiApi] {+ let p = probe(id, &env("sk-wrong-key-123")).await;+ assert_eq!(p.status, EngineStatus::SignedOut, "{id:?}");+ assert_eq!(p.detail.as_deref(), Some("API key rejected (401)"));+ let p = probe(id, &env("broke")).await;+ assert_eq!(p.status, EngineStatus::Error);+ assert_eq!(p.detail.as_deref(), Some("Quota exceeded (429)"));+ }+ let p = probe(EngineId::OpenaiApi, &ProbeEnv::default()).await;+ assert_eq!(p.status, EngineStatus::NotInstalled);+ assert_eq!(p.detail.as_deref(), Some("No API key: add one in Settings"));++ // Ollama: up with models, then down+ let p = probe(EngineId::Ollama, &env("good")).await;+ assert_eq!(p.status, EngineStatus::Ready);+ assert_eq!(p.version.as_deref(), Some("0.9.1"));+ assert_eq!(p.models.len(), 2);+ let down = ProbeEnv { ollama_root: "http://127.0.0.1:9".into(), ..ProbeEnv::default() };+ let p = probe(EngineId::Ollama, &down).await;+ assert_eq!(p.status, EngineStatus::NotInstalled);+ let p = probe(EngineId::Ollama, &ProbeEnv { ollama_installed: true, ..down }).await;+ assert_eq!(p.status, EngineStatus::Error);+ assert!(p.detail.unwrap().contains("ollama serve"));+}diff --git a/tests/engine_routing_test.rs b/tests/engine_routing_test.rsnew file mode 100644index 00000000..63e3f41a--- /dev/null+++ b/tests/engine_routing_test.rs@@ -0,0 +1,210 @@+//! Turns run only on engines that passed their check, a refused turn marks its engine at once,+//! and with nothing usable the turn says so instead of using another engine. A fake claude CLI+//! is the only engine on PATH. Its own test binary: it changes PATH, HOME and the process env.++use axum::{+ body::{to_bytes, Body},+ http::{Request, StatusCode},+ Router,+};+use kwnt::{+ broker::PermissionBroker,+ config::Config,+ db::Database,+ drivers::{engines::EngineId, engines::EngineStatus, RuntimeEvent},+ router::LayaRouter,+ server::{create_router, AppState},+ tools::ToolRunner,+};+use serde_json::{json, Value};+use std::path::Path;+use std::time::Duration;+use tower::ServiceExt;++/// Signed in; a turn fails as signed out while `$FAKE_DIR/refuse` exists. Every turn is logged.+const FAKE_CLAUDE: &str = r#"#!/bin/sh+case "$1" in+ --version) echo "7.0.1 (Claude Code)"; exit 0 ;;+ auth) echo '{"loggedIn":true,"authMethod":"claude.ai"}'; exit 0 ;;+esac+echo turn >> "$FAKE_DIR/turns.log"+if [ -f "$FAKE_DIR/refuse" ]; then+ echo '{"type":"result","is_error":true,"num_turns":1,"result":"Not logged in · Please run /login"}'+ exit 1+fi+echo '{"type":"result","is_error":false,"num_turns":1,"result":"hello from fake claude","usage":{"input_tokens":3,"output_tokens":4}}'+"#;++async fn call(app: &Router, method: &str, uri: &str, body: Option<Value>) -> (StatusCode, Value) {+ let resp = app+ .clone()+ .oneshot(+ Request::builder()+ .method(method)+ .uri(uri)+ .header("content-type", "application/json")+ .body(body.map(|v| Body::from(v.to_string())).unwrap_or_else(Body::empty))+ .unwrap(),+ )+ .await+ .unwrap();+ let s = resp.status();+ let bytes = to_bytes(resp.into_body(), usize::MAX).await.unwrap();+ (s, serde_json::from_slice(&bytes).unwrap_or(Value::Null))+}++/// Sends a prompt and returns the text the turn streamed.+async fn turn_text(app: &Router, state: &AppState, kwant_id: &str) -> String {+ let mut rx = state.event_sender.subscribe();+ let (s, v) = call(+ app,+ "POST",+ "/api/chat/send",+ Some(json!({"kwant_id": kwant_id, "prompt": "hi", "sender_id": "user"})),+ )+ .await;+ assert_eq!(s, StatusCode::OK, "{v}");+ let mut text = String::new();+ tokio::time::timeout(Duration::from_secs(60), async {+ while let Ok(e) = rx.recv().await {+ match e.unscoped() {+ RuntimeEvent::TextDelta(t) => text.push_str(t),+ RuntimeEvent::TurnEnded { kwant_id: k, .. } if k == kwant_id => break,+ _ => {}+ }+ }+ })+ .await+ .expect("turn did not end");+ text+}++fn turns_run(dir: &Path) -> usize {+ std::fs::read_to_string(dir.join("turns.log")).map(|s| s.lines().count()).unwrap_or(0)+}++#[tokio::test]+async fn turns_skip_engines_that_cannot_run() {+ let tmp = tempfile::tempdir().unwrap();+ let bin = tmp.path().join("bin");+ std::fs::create_dir_all(&bin).unwrap();+ let fake = bin.join("claude");+ std::fs::write(&fake, FAKE_CLAUDE).unwrap();+ #[cfg(unix)]+ {+ use std::os::unix::fs::PermissionsExt;+ std::fs::set_permissions(&fake, std::fs::Permissions::from_mode(0o755)).unwrap();+ }+ // Only the fake claude: no real CLIs from PATH or ~/.local/bin, no host keys+ std::env::set_var("PATH", format!("{}:/usr/bin:/bin", bin.display()));+ std::env::set_var("HOME", tmp.path());+ std::env::set_var("FAKE_DIR", tmp.path());+ for var in ["ANTHROPIC_API_KEY", "OPENAI_API_KEY", "XAI_API_KEY", "OLLAMA_MODEL", "CLAUDE_CONFIG_DIR"] {+ std::env::remove_var(var);+ }+ std::env::set_var("OLLAMA_URL", "http://127.0.0.1:9");++ let data = tmp.path().join("data");+ let db = Database::init(&data).await.unwrap();+ let config = Config {+ data_dir: data.clone(),+ laya_url: "http://127.0.0.1:9".into(),+ browser_cdp_url: Some("http://127.0.0.1:9".into()),+ ..Config::default()+ };+ let state = AppState::new(+ config.clone(),+ db,+ ToolRunner::new(data.join("workspace")),+ PermissionBroker::new(),+ LayaRouter::new(config.laya_url.clone()),+ );+ let app = create_router(state.clone());++ // Before any check every engine is "checking"+ let (s, v) = call(&app, "GET", "/api/engines", None).await;+ assert_eq!(s, StatusCode::OK);+ let engines = v["engines"].as_array().unwrap();+ assert_eq!(engines.len(), 7);+ assert!(engines.iter().all(|e| e["status"] == "checking" && e["checked_at"].is_null()));++ // 1. Re-check: only the fake claude is ready; the shape is the agreed contract+ let (s, v) = call(&app, "POST", "/api/engines/recheck", None).await;+ assert_eq!(s, StatusCode::OK, "{v}");+ let by_id = |v: &Value, id: &str| v["engines"].as_array().unwrap().iter().find(|e| e["id"] == id).cloned().unwrap();+ let claude = by_id(&v, "claude");+ assert_eq!(claude["status"], "ready", "{claude}");+ assert_eq!(claude["name"], "Claude Code CLI");+ assert_eq!(claude["kind"], "cli");+ assert_eq!(claude["version"], "7.0.1");+ assert!(claude["checked_at"].as_str().unwrap().contains('T'));+ assert!(claude["models"].as_array().unwrap().iter().any(|m| m["id"] == "opus" && m["default"] == true && m["label"].is_string()));+ for (id, kind) in [("codex", "cli"), ("grok", "cli"), ("anthropic_api", "api"), ("openai_api", "api"), ("xai_api", "api"), ("ollama", "local")] {+ let e = by_id(&v, id);+ assert_eq!(e["status"], "not_installed", "{e}");+ assert_eq!(e["kind"], kind);+ assert!(e["detail"].is_string());+ assert_eq!(e["models"], json!([]));+ }+ let (_, listed) = call(&app, "GET", "/api/engines", None).await;+ assert_eq!(listed, v);+ // The old Settings fields stay+ let (_, settings) = call(&app, "GET", "/api/settings", None).await;+ assert_eq!(settings["claude_cli_found"], true);+ assert_eq!(settings["codex_cli_found"], false);++ // 2. A turn pinned to claude runs on the ready CLI+ let (_, kwants) = call(&app, "GET", "/api/kwants", None).await;+ let k = kwants[0].clone();+ let kid = k["id"].as_str().unwrap().to_string();+ let mut body = k.clone();+ body.as_object_mut()+ .unwrap()+ .retain(|key, _| ["name", "title", "persona_prompt", "soul", "avatar_sprite"].contains(&key.as_str()));+ body["preferred_model"] = json!("claude");+ let (s, r) = call(&app, "PUT", &format!("/api/kwants/{kid}"), Some(body.clone())).await;+ assert_eq!(s, StatusCode::OK, "{r}");+ let text = turn_text(&app, &state, &kid).await;+ assert!(text.contains("hello from fake claude"), "{text}");+ assert_eq!(turns_run(tmp.path()), 1);++ // 3. Signed out mid-turn: the engine is marked at once, without a re-check+ std::fs::write(tmp.path().join("refuse"), "").unwrap();+ let text = turn_text(&app, &state, &kid).await;+ assert!(text.contains("signed out") || text.contains("refused"), "{text}");+ assert_eq!(turns_run(tmp.path()), 2);+ assert_eq!(state.engines.status(EngineId::Claude), EngineStatus::SignedOut);+ let (_, v) = call(&app, "GET", "/api/engines", None).await;+ assert_eq!(by_id(&v, "claude")["status"], "signed_out");+ assert_eq!(by_id(&v, "claude")["models"], json!([]));++ // 4. Nothing can run now: a clear message, and no CLI is started+ let text = turn_text(&app, &state, &kid).await;+ assert!(text.contains("No engine is available — check Settings"), "{text}");+ assert_eq!(turns_run(tmp.path()), 2);++ // 5. Signed in again and re-checked: claude is back. A kwant pinned to codex (not installed)+ // is told why, and never quietly runs on claude instead (the old fallback did).+ std::fs::remove_file(tmp.path().join("refuse")).unwrap();+ call(&app, "POST", "/api/engines/recheck", None).await;+ assert_eq!(state.engines.status(EngineId::Claude), EngineStatus::Ready);+ body["preferred_model"] = json!("codex");+ let (s, _) = call(&app, "PUT", &format!("/api/kwants/{kid}"), Some(body.clone())).await;+ assert_eq!(s, StatusCode::OK);+ let text = turn_text(&app, &state, &kid).await;+ assert!(text.contains("'codex' can't run right now"), "{text}");+ assert!(text.contains("Codex isn't installed") && text.contains("No API key"), "{text}");+ assert_eq!(turns_run(tmp.path()), 2);++ // 6. A rejected Settings key is skipped for the signed-in CLI+ state.db.set_setting("anthropic_api_key", "sk-ant-rejected").await.unwrap();+ body["preferred_model"] = json!("claude");+ call(&app, "PUT", &format!("/api/kwants/{kid}"), Some(body)).await;+ state.engines.store(vec![(+ EngineId::AnthropicApi,+ kwnt::drivers::engines::api_refusal(401, "invalid x-api-key"),+ )]);+ let text = turn_text(&app, &state, &kid).await;+ assert!(text.contains("hello from fake claude"), "{text}");+ assert_eq!(turns_run(tmp.path()), 3);+}diff --git a/tests/routine_failure_test.rs b/tests/routine_failure_test.rsindex db294cf7..2a9a0e92 100644--- a/tests/routine_failure_test.rs+++ b/tests/routine_failure_test.rs@@ -123,6 +123,14 @@ async fn failed_routine_run_records_the_engine_error() {assert!(error.contains("is signed out"), "{error}");assert!(error.chars().count() <= 600, "{error}");+ // The refusal marked claude signed out, so turns stop starting it until it's signed in again+ use kwnt::drivers::engines::{EngineId, EngineStatus, Probe};+ assert_eq!(state.engines.status(EngineId::Claude), EngineStatus::SignedOut);+ state.engines.store(vec![(+ EngineId::Claude,+ Probe { status: EngineStatus::Ready, detail: None, version: None, models: Vec::new() },+ )]);+// A CLI that dies silently used to be recorded as an ok run with an empty replystd::fs::write(&crash, "").unwrap();let error = run_once(&app, &id).await;