558 lines
18 KiB
Rust
558 lines
18 KiB
Rust
use std::collections::HashSet;
|
|
use std::path::Path;
|
|
use std::process::Stdio;
|
|
use std::time::Duration;
|
|
|
|
use serde::Serialize;
|
|
use tokio::process::Command;
|
|
|
|
use crate::config::{Config, McpTransport, expand_path};
|
|
|
|
pub const SUPPORTED_AGENT_BROWSER_VERSION: &str = "0.33.0";
|
|
|
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
|
|
#[serde(rename_all = "snake_case")]
|
|
pub enum HealthStatus {
|
|
Pass,
|
|
Warning,
|
|
Fail,
|
|
}
|
|
|
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
|
|
#[serde(rename_all = "snake_case")]
|
|
pub enum HealthOverall {
|
|
Healthy,
|
|
Degraded,
|
|
Unhealthy,
|
|
}
|
|
|
|
#[derive(Debug, Clone, Serialize)]
|
|
pub struct HealthCheck {
|
|
pub name: String,
|
|
pub category: String,
|
|
pub required: bool,
|
|
pub status: HealthStatus,
|
|
pub detail: String,
|
|
#[serde(skip_serializing_if = "Option::is_none")]
|
|
pub remediation: Option<String>,
|
|
}
|
|
|
|
#[derive(Debug, Clone, Serialize)]
|
|
pub struct HealthReport {
|
|
pub version: &'static str,
|
|
pub overall: HealthOverall,
|
|
pub checks: Vec<HealthCheck>,
|
|
}
|
|
|
|
impl HealthReport {
|
|
pub fn configuration_error(error: impl Into<String>) -> Self {
|
|
Self::from_checks(vec![HealthCheck {
|
|
name: "configuration".to_string(),
|
|
category: "core".to_string(),
|
|
required: true,
|
|
status: HealthStatus::Fail,
|
|
detail: error.into(),
|
|
remediation: Some(
|
|
"Fix ~/.picobot/config.json (or ./config.json) and run picobot health again."
|
|
.to_string(),
|
|
),
|
|
}])
|
|
}
|
|
|
|
fn from_checks(checks: Vec<HealthCheck>) -> Self {
|
|
let overall = if checks
|
|
.iter()
|
|
.any(|check| check.required && check.status == HealthStatus::Fail)
|
|
{
|
|
HealthOverall::Unhealthy
|
|
} else if checks
|
|
.iter()
|
|
.any(|check| check.status != HealthStatus::Pass)
|
|
{
|
|
HealthOverall::Degraded
|
|
} else {
|
|
HealthOverall::Healthy
|
|
};
|
|
Self {
|
|
version: env!("CARGO_PKG_VERSION"),
|
|
overall,
|
|
checks,
|
|
}
|
|
}
|
|
|
|
pub fn is_usable(&self) -> bool {
|
|
self.overall != HealthOverall::Unhealthy
|
|
}
|
|
|
|
pub fn render_text(&self) -> String {
|
|
let overall = match self.overall {
|
|
HealthOverall::Healthy => "HEALTHY",
|
|
HealthOverall::Degraded => "DEGRADED",
|
|
HealthOverall::Unhealthy => "UNHEALTHY",
|
|
};
|
|
let mut lines = vec![format!("PicoBot {} health: {overall}", self.version)];
|
|
for check in &self.checks {
|
|
let icon = match check.status {
|
|
HealthStatus::Pass => "✓",
|
|
HealthStatus::Warning => "!",
|
|
HealthStatus::Fail => "✗",
|
|
};
|
|
let requirement = if check.required {
|
|
"required"
|
|
} else {
|
|
"optional"
|
|
};
|
|
lines.push(format!(
|
|
"{icon} [{} / {requirement}] {} — {}",
|
|
check.category, check.name, check.detail
|
|
));
|
|
if let Some(remediation) = &check.remediation {
|
|
lines.push(format!(" Fix: {remediation}"));
|
|
}
|
|
}
|
|
lines.join("\n")
|
|
}
|
|
}
|
|
|
|
#[derive(Clone)]
|
|
pub struct HealthService {
|
|
config: Config,
|
|
}
|
|
|
|
impl HealthService {
|
|
pub fn new(config: Config) -> Self {
|
|
Self { config }
|
|
}
|
|
|
|
pub async fn check(&self) -> HealthReport {
|
|
let mut checks = vec![
|
|
check_workspace(&self.config),
|
|
check_required_binary(
|
|
"bash",
|
|
"core",
|
|
"Install Bash and make it available on PATH.",
|
|
),
|
|
check_search_backend("content search", &["rg", "grep"], "rg"),
|
|
check_search_backend("file search", &["fd", "fdfind", "find"], "fd"),
|
|
check_optional_binary("systemd service management", "systemctl", "service"),
|
|
];
|
|
checks.extend(self.check_mcp_commands());
|
|
checks.extend(self.check_browser().await);
|
|
HealthReport::from_checks(checks)
|
|
}
|
|
|
|
fn check_mcp_commands(&self) -> Vec<HealthCheck> {
|
|
let mut seen = HashSet::new();
|
|
let mut checks = Vec::new();
|
|
for server in &self.config.mcp.servers {
|
|
if !matches!(server.transport, McpTransport::Stdio) {
|
|
continue;
|
|
}
|
|
let Some(command) = server.command.as_deref() else {
|
|
checks.push(HealthCheck {
|
|
name: format!("MCP server {}", server.name),
|
|
category: "configured".to_string(),
|
|
required: true,
|
|
status: HealthStatus::Fail,
|
|
detail: "stdio server has no command".to_string(),
|
|
remediation: Some("Set mcp.servers[].command.".to_string()),
|
|
});
|
|
continue;
|
|
};
|
|
if !seen.insert(command.to_string()) {
|
|
continue;
|
|
}
|
|
let installed = command_exists(command);
|
|
checks.push(HealthCheck {
|
|
name: format!("MCP command {command}"),
|
|
category: "configured".to_string(),
|
|
required: true,
|
|
status: if installed {
|
|
HealthStatus::Pass
|
|
} else {
|
|
HealthStatus::Fail
|
|
},
|
|
detail: if installed {
|
|
"installed".to_string()
|
|
} else {
|
|
"not found on PATH".to_string()
|
|
},
|
|
remediation: (!installed).then(|| {
|
|
format!("Install '{command}' or set an absolute mcp.servers[].command path.")
|
|
}),
|
|
});
|
|
}
|
|
if checks.is_empty() {
|
|
checks.push(HealthCheck {
|
|
name: "MCP stdio commands".to_string(),
|
|
category: "configured".to_string(),
|
|
required: false,
|
|
status: HealthStatus::Pass,
|
|
detail: "no stdio MCP servers configured".to_string(),
|
|
remediation: None,
|
|
});
|
|
}
|
|
checks
|
|
}
|
|
|
|
async fn check_browser(&self) -> Vec<HealthCheck> {
|
|
let browser = &self.config.browser;
|
|
if !browser.enabled {
|
|
return vec![HealthCheck {
|
|
name: "agent-browser".to_string(),
|
|
category: "configured".to_string(),
|
|
required: false,
|
|
status: HealthStatus::Pass,
|
|
detail: "browser tool disabled; dependency not required".to_string(),
|
|
remediation: None,
|
|
}];
|
|
}
|
|
|
|
let mut checks = Vec::new();
|
|
if !browser.allowed_domains.is_empty() {
|
|
checks.push(HealthCheck {
|
|
name: "persistent browser availability".to_string(),
|
|
category: "configured".to_string(),
|
|
required: false,
|
|
status: HealthStatus::Warning,
|
|
detail: "ordinary transient browsing is available, but persistent Chrome profiles are unavailable while allowed_domains is configured".to_string(),
|
|
remediation: Some(
|
|
"Keep allowed_domains for contained transient browsing, or clear it only if reusable persistent profiles are required; agent-browser 0.33.0 cannot combine both guarantees.".to_string(),
|
|
),
|
|
});
|
|
}
|
|
if !command_exists(&browser.command) {
|
|
checks.push(HealthCheck {
|
|
name: "agent-browser CLI".to_string(),
|
|
category: "configured".to_string(),
|
|
required: true,
|
|
status: HealthStatus::Fail,
|
|
detail: format!("'{}' was not found", browser.command),
|
|
remediation: Some(format!(
|
|
"Run `npm install -g agent-browser@{SUPPORTED_AGENT_BROWSER_VERSION}` (or `cargo install agent-browser --version {SUPPORTED_AGENT_BROWSER_VERSION} --locked`), then `agent-browser install`."
|
|
)),
|
|
});
|
|
return checks;
|
|
}
|
|
|
|
let version = command_output(
|
|
&browser.command,
|
|
&["--version"],
|
|
None,
|
|
Duration::from_secs(5),
|
|
)
|
|
.await;
|
|
match version {
|
|
Ok(version_output) => {
|
|
let version_number = extract_version(&version_output);
|
|
let exact = version_number.as_deref() == Some(SUPPORTED_AGENT_BROWSER_VERSION);
|
|
checks.push(HealthCheck {
|
|
name: "agent-browser CLI".to_string(),
|
|
category: "configured".to_string(),
|
|
required: true,
|
|
status: if exact {
|
|
HealthStatus::Pass
|
|
} else {
|
|
HealthStatus::Warning
|
|
},
|
|
detail: format!(
|
|
"installed version {}; PicoBot is validated with {}",
|
|
version_number.unwrap_or_else(|| version_output.trim().to_string()),
|
|
SUPPORTED_AGENT_BROWSER_VERSION
|
|
),
|
|
remediation: (!exact).then(|| {
|
|
format!(
|
|
"Install agent-browser@{SUPPORTED_AGENT_BROWSER_VERSION} for the validated CLI contract."
|
|
)
|
|
}),
|
|
});
|
|
}
|
|
Err(error) => checks.push(HealthCheck {
|
|
name: "agent-browser CLI".to_string(),
|
|
category: "configured".to_string(),
|
|
required: true,
|
|
status: HealthStatus::Fail,
|
|
detail: error,
|
|
remediation: Some("Reinstall agent-browser and verify it can execute.".to_string()),
|
|
}),
|
|
}
|
|
|
|
if let Some(path) = browser.browser_executable_path.as_deref() {
|
|
let path = expand_path(path);
|
|
let path = if path.is_absolute() {
|
|
path
|
|
} else {
|
|
expand_path(&self.config.workspace_dir).join(path)
|
|
};
|
|
let installed = path.is_file();
|
|
checks.push(HealthCheck {
|
|
name: "configured browser executable".to_string(),
|
|
category: "configured".to_string(),
|
|
required: true,
|
|
status: if installed {
|
|
HealthStatus::Pass
|
|
} else {
|
|
HealthStatus::Fail
|
|
},
|
|
detail: if installed {
|
|
format!("found at {}", path.display())
|
|
} else {
|
|
format!("not found at {}", path.display())
|
|
},
|
|
remediation: (!installed).then(|| {
|
|
"Fix browser.browser_executable_path or run `agent-browser install`."
|
|
.to_string()
|
|
}),
|
|
});
|
|
}
|
|
|
|
let doctor_executable = browser
|
|
.browser_executable_path
|
|
.as_deref()
|
|
.map(expand_path)
|
|
.map(|path| {
|
|
if path.is_absolute() {
|
|
path
|
|
} else {
|
|
expand_path(&self.config.workspace_dir).join(path)
|
|
}
|
|
})
|
|
.map(|path| path.to_string_lossy().into_owned());
|
|
let doctor_env = doctor_executable
|
|
.as_deref()
|
|
.map(|path| ("AGENT_BROWSER_EXECUTABLE_PATH", path));
|
|
let doctor = command_output(
|
|
&browser.command,
|
|
&["doctor", "--offline", "--quick", "--json"],
|
|
doctor_env,
|
|
Duration::from_secs(15),
|
|
)
|
|
.await;
|
|
checks.push(match doctor {
|
|
Ok(output) => HealthCheck {
|
|
name: "agent-browser runtime".to_string(),
|
|
category: "configured".to_string(),
|
|
required: true,
|
|
status: HealthStatus::Pass,
|
|
detail: summarize_output(&output),
|
|
remediation: None,
|
|
},
|
|
Err(error) => HealthCheck {
|
|
name: "agent-browser runtime".to_string(),
|
|
category: "configured".to_string(),
|
|
required: true,
|
|
status: HealthStatus::Fail,
|
|
detail: error,
|
|
remediation: Some(
|
|
"Run `agent-browser doctor`, then `agent-browser install --with-deps` on Linux or `agent-browser install` on other platforms."
|
|
.to_string(),
|
|
),
|
|
},
|
|
});
|
|
checks
|
|
}
|
|
}
|
|
|
|
fn check_workspace(config: &Config) -> HealthCheck {
|
|
let workspace = expand_path(&config.workspace_dir);
|
|
let exists = workspace.is_dir();
|
|
HealthCheck {
|
|
name: "workspace".to_string(),
|
|
category: "core".to_string(),
|
|
required: true,
|
|
status: if exists {
|
|
HealthStatus::Pass
|
|
} else {
|
|
HealthStatus::Fail
|
|
},
|
|
detail: if exists {
|
|
format!("{} is available", workspace.display())
|
|
} else {
|
|
format!("{} does not exist", workspace.display())
|
|
},
|
|
remediation: (!exists)
|
|
.then(|| "Create the configured workspace directory or fix workspace_dir.".to_string()),
|
|
}
|
|
}
|
|
|
|
fn check_required_binary(name: &str, category: &str, remediation: &str) -> HealthCheck {
|
|
let installed = command_exists(name);
|
|
HealthCheck {
|
|
name: name.to_string(),
|
|
category: category.to_string(),
|
|
required: true,
|
|
status: if installed {
|
|
HealthStatus::Pass
|
|
} else {
|
|
HealthStatus::Fail
|
|
},
|
|
detail: if installed {
|
|
"installed".to_string()
|
|
} else {
|
|
"not found on PATH".to_string()
|
|
},
|
|
remediation: (!installed).then(|| remediation.to_string()),
|
|
}
|
|
}
|
|
|
|
fn check_search_backend(name: &str, candidates: &[&str], preferred: &str) -> HealthCheck {
|
|
let found = candidates.iter().copied().find(|name| command_exists(name));
|
|
let (status, detail, remediation) = match found {
|
|
Some(found) if found == preferred => (
|
|
HealthStatus::Pass,
|
|
format!("using preferred backend {found}"),
|
|
None,
|
|
),
|
|
Some(found) => (
|
|
HealthStatus::Warning,
|
|
format!("using fallback backend {found}"),
|
|
Some(format!("Install {preferred} for faster searches.")),
|
|
),
|
|
None => (
|
|
HealthStatus::Fail,
|
|
"no supported backend found".to_string(),
|
|
Some(format!("Install one of: {}.", candidates.join(", "))),
|
|
),
|
|
};
|
|
HealthCheck {
|
|
name: name.to_string(),
|
|
category: "core".to_string(),
|
|
required: true,
|
|
status,
|
|
detail,
|
|
remediation,
|
|
}
|
|
}
|
|
|
|
fn check_optional_binary(name: &str, binary: &str, category: &str) -> HealthCheck {
|
|
let installed = command_exists(binary);
|
|
HealthCheck {
|
|
name: name.to_string(),
|
|
category: category.to_string(),
|
|
required: false,
|
|
status: HealthStatus::Pass,
|
|
detail: if installed {
|
|
format!("{binary} installed")
|
|
} else {
|
|
format!("{binary} not installed; feature remains unavailable")
|
|
},
|
|
remediation: None,
|
|
}
|
|
}
|
|
|
|
fn command_exists(command: &str) -> bool {
|
|
if command.contains(std::path::MAIN_SEPARATOR) {
|
|
Path::new(command).is_file()
|
|
} else {
|
|
which::which(command).is_ok()
|
|
}
|
|
}
|
|
|
|
async fn command_output(
|
|
command: &str,
|
|
args: &[&str],
|
|
env: Option<(&str, &str)>,
|
|
timeout: Duration,
|
|
) -> Result<String, String> {
|
|
let mut process = Command::new(command);
|
|
process
|
|
.args(args)
|
|
.stdin(Stdio::null())
|
|
.stdout(Stdio::piped())
|
|
.stderr(Stdio::piped())
|
|
.kill_on_drop(true);
|
|
if let Some((key, value)) = env {
|
|
process.env(key, value);
|
|
}
|
|
let output = tokio::time::timeout(timeout, process.output())
|
|
.await
|
|
.map_err(|_| format!("command timed out after {} seconds", timeout.as_secs()))?
|
|
.map_err(|error| format!("failed to start: {error}"))?;
|
|
let stdout = String::from_utf8_lossy(&output.stdout);
|
|
let stderr = String::from_utf8_lossy(&output.stderr);
|
|
if !output.status.success() {
|
|
let detail = if stderr.trim().is_empty() {
|
|
stdout.trim()
|
|
} else {
|
|
stderr.trim()
|
|
};
|
|
return Err(format!(
|
|
"exited with {}: {}",
|
|
output.status,
|
|
truncate(detail, 1_000)
|
|
));
|
|
}
|
|
let combined = if stdout.trim().is_empty() {
|
|
stderr.trim()
|
|
} else {
|
|
stdout.trim()
|
|
};
|
|
Ok(truncate(combined, 4_000))
|
|
}
|
|
|
|
fn extract_version(output: &str) -> Option<String> {
|
|
output
|
|
.split_whitespace()
|
|
.map(|token| {
|
|
token
|
|
.trim_start_matches('v')
|
|
.trim_matches(|c: char| c == ',' || c == ';')
|
|
})
|
|
.find(|token| {
|
|
let mut parts = token.split('.');
|
|
parts.clone().count() >= 3 && parts.all(|part| part.chars().all(|c| c.is_ascii_digit()))
|
|
})
|
|
.map(str::to_string)
|
|
}
|
|
|
|
fn summarize_output(output: &str) -> String {
|
|
if let Ok(json) = serde_json::from_str::<serde_json::Value>(output)
|
|
&& let Some(summary) = json
|
|
.get("summary")
|
|
.and_then(serde_json::Value::as_str)
|
|
.or_else(|| json.get("message").and_then(serde_json::Value::as_str))
|
|
{
|
|
return truncate(summary, 500);
|
|
}
|
|
let first_line = output
|
|
.lines()
|
|
.find(|line| !line.trim().is_empty())
|
|
.unwrap_or("ok");
|
|
truncate(first_line, 500)
|
|
}
|
|
|
|
fn truncate(value: &str, max: usize) -> String {
|
|
if value.len() <= max {
|
|
value.to_string()
|
|
} else {
|
|
format!("{}…", &value[..value.floor_char_boundary(max)])
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
#[test]
|
|
fn required_failure_makes_report_unhealthy() {
|
|
let report = HealthReport::from_checks(vec![HealthCheck {
|
|
name: "x".into(),
|
|
category: "core".into(),
|
|
required: true,
|
|
status: HealthStatus::Fail,
|
|
detail: "missing".into(),
|
|
remediation: None,
|
|
}]);
|
|
assert_eq!(report.overall, HealthOverall::Unhealthy);
|
|
assert!(!report.is_usable());
|
|
}
|
|
|
|
#[test]
|
|
fn extracts_agent_browser_version() {
|
|
assert_eq!(
|
|
extract_version("agent-browser 0.33.0"),
|
|
Some("0.33.0".to_string())
|
|
);
|
|
}
|
|
}
|