use std::io::Read;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::time::{Duration, Instant};
use serde_json::Value;
const UV_TOOL_BIN: &str = ".local/bin/abstractcore";
const LOCAL_VENV_BIN: &str = ".venv/bin/abstractcore";
#[derive(Clone, Debug, PartialEq)]
pub enum CliErrorKind {
NotFound,
Spawn,
Timeout,
Exit(i32),
BadJson,
}
#[derive(Clone, Debug)]
pub struct CliError {
pub kind: CliErrorKind,
pub message: String,
pub program: &'static str,
}
impl CliError {
pub fn core(kind: CliErrorKind, message: String) -> CliError {
CliError {
kind,
message,
program: "abstractcore",
}
}
pub fn chat(kind: CliErrorKind, message: String) -> CliError {
CliError {
kind,
message,
program: "abstractcore-chat",
}
}
pub fn headline(&self) -> String {
let p = self.program;
match self.kind {
CliErrorKind::NotFound => format!("{p} CLI not found"),
CliErrorKind::Spawn => format!("could not start {p}"),
CliErrorKind::Timeout => format!("{p} timed out"),
CliErrorKind::Exit(code) => format!("{p} exited with {code}"),
CliErrorKind::BadJson => format!("{p} answered, but not with JSON"),
}
}
pub fn hint(&self) -> &'static str {
match self.kind {
CliErrorKind::NotFound => {
"set $ABSTRACTCORE_CLI, or install abstractcore on PATH — the file mirror still works"
}
CliErrorKind::Spawn => "check the binary is executable ($ABSTRACTCORE_CLI?)",
CliErrorKind::Timeout => "the Python side hung — retry with r",
CliErrorKind::Exit(_) => "the message above is the CLI's own error",
CliErrorKind::BadJson => "an abstractcore too old for --json? check its version",
}
}
}
impl std::fmt::Display for CliError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}: {}", self.headline(), self.message)
}
}
#[derive(Clone, Debug)]
pub struct CliInfo {
pub bin: PathBuf,
pub source: &'static str,
}
pub fn resolve_bin(
env: &dyn Fn(&str) -> Option<String>,
home: &Path,
cwd: &Path,
exists: &dyn Fn(&Path) -> bool,
) -> Option<CliInfo> {
for (var, source) in [
("ABSTRACTCORE_CLI", "$ABSTRACTCORE_CLI"),
("ABSTRACTCORE_BIN", "$ABSTRACTCORE_BIN (legacy alias)"),
] {
if let Some(explicit) = env(var).filter(|v| !v.trim().is_empty()) {
return Some(CliInfo {
bin: PathBuf::from(explicit.trim()),
source,
});
}
}
if let Some(paths) = env("PATH") {
for dir in std::env::split_paths(&paths) {
let candidate = dir.join("abstractcore");
if exists(&candidate) {
return Some(CliInfo {
bin: candidate,
source: "PATH",
});
}
}
}
if !home.as_os_str().is_empty() {
let shim = home.join(UV_TOOL_BIN);
if exists(&shim) {
return Some(CliInfo {
bin: shim,
source: "~/.local/bin (uv tool)",
});
}
}
let venv = cwd.join(LOCAL_VENV_BIN);
if exists(&venv) {
return Some(CliInfo {
bin: venv,
source: "./.venv",
});
}
None
}
pub fn resolve_bin_from_env() -> Option<CliInfo> {
let home = std::env::var("HOME").map(PathBuf::from).unwrap_or_default();
let cwd = std::env::current_dir().unwrap_or_default();
resolve_bin(&|k| std::env::var(k).ok(), &home, &cwd, &|p| p.is_file())
}
pub struct CoreCli {
pub bin: PathBuf,
pub chat_bin: Option<PathBuf>,
pub chat_from_path: bool,
}
pub fn resolve_chat_bin(
core_bin: &Path,
exists: &dyn Fn(&Path) -> bool,
) -> Option<(PathBuf, bool)> {
let sibling = core_bin.with_file_name("abstractcore-chat");
if exists(&sibling) {
return Some((sibling, false));
}
if let Some(paths) = std::env::var_os("PATH") {
for dir in std::env::split_paths(&paths) {
let candidate = dir.join("abstractcore-chat");
if exists(&candidate) {
return Some((candidate, true));
}
}
}
None
}
#[derive(Clone, Debug)]
pub struct CliOutput {
pub value: Value,
pub fallback_warnings: Vec<String>,
}
impl CoreCli {
pub fn new(bin: PathBuf) -> CoreCli {
let resolved = resolve_chat_bin(&bin, &|p| p.is_file());
let chat_from_path = resolved.as_ref().is_some_and(|(_, from_path)| *from_path);
CoreCli {
bin,
chat_bin: resolved.map(|(p, _)| p),
chat_from_path,
}
}
#[cfg(test)]
pub fn bare(bin: PathBuf) -> CoreCli {
CoreCli {
bin,
chat_bin: None,
chat_from_path: false,
}
}
pub fn run_chat(
&self,
args: &[&str],
timeout: Duration,
) -> Result<(String, Vec<String>), CliError> {
let chat = self.chat_bin.as_ref().ok_or_else(|| {
CliError::chat(
CliErrorKind::NotFound,
"abstractcore-chat not found beside abstractcore or on PATH".into(),
)
})?;
let label = format!("abstractcore-chat {}", args.join(" "));
let (status, stdout, stderr) =
run_raw_at(chat, args, &label, timeout).map_err(|mut e| {
e.program = "abstractcore-chat";
e
})?;
if !status.success() {
return Err(CliError::chat(
CliErrorKind::Exit(status.code().unwrap_or(-1)),
error_line(&stdout, &stderr),
));
}
Ok((stdout, fallback_lines(&stderr)))
}
pub fn run_setter(
&self,
args: &[&str],
redacted_label: &str,
timeout: Duration,
) -> Result<Vec<String>, CliError> {
let (status, stdout, stderr) = self.run_raw(args, redacted_label, timeout)?;
if !status.success() {
return Err(CliError::core(
CliErrorKind::Exit(status.code().unwrap_or(-1)),
error_line(&stdout, &stderr),
));
}
if let Some(l) = stdout
.lines()
.find(|l| l.contains("❌") || l.contains("Error:"))
{
return Err(CliError::core(
CliErrorKind::Exit(0),
format!("{} (the CLI still exited 0)", l.trim()),
));
}
Ok(fallback_lines(&stderr))
}
pub fn run_json(&self, args: &[&str], timeout: Duration) -> Result<CliOutput, CliError> {
let label = format!("abstractcore {}", args.join(" "));
let (status, stdout, stderr) = self.run_raw(args, &label, timeout)?;
if !status.success() {
let code = status.code().unwrap_or(-1);
return Err(CliError::core(
CliErrorKind::Exit(code),
error_line(&stdout, &stderr),
));
}
let value = serde_json::from_str(&stdout).map_err(|e| {
CliError::core(
CliErrorKind::BadJson,
format!("{e} — first bytes: {}", head(&stdout, 120)),
)
})?;
Ok(CliOutput {
value,
fallback_warnings: fallback_lines(&stderr),
})
}
pub fn run_json_last(&self, args: &[&str], timeout: Duration) -> Result<CliOutput, CliError> {
let label = format!("abstractcore {}", args.join(" "));
let (status, stdout, stderr) = self.run_raw(args, &label, timeout)?;
let last = last_json_object(&stdout);
if !status.success() {
let code = status.code().unwrap_or(-1);
let msg = last
.as_ref()
.and_then(job_error_text)
.unwrap_or_else(|| error_line(&stdout, &stderr));
return Err(CliError::core(CliErrorKind::Exit(code), msg));
}
let value = last.ok_or_else(|| {
CliError::core(
CliErrorKind::BadJson,
format!(
"no JSON object on stdout — first bytes: {}",
head(&stdout, 120)
),
)
})?;
Ok(CliOutput {
value,
fallback_warnings: fallback_lines(&stderr),
})
}
fn run_raw(
&self,
args: &[&str],
redacted_label: &str,
timeout: Duration,
) -> Result<(std::process::ExitStatus, String, String), CliError> {
run_raw_at(&self.bin, args, redacted_label, timeout)
}
}
pub(crate) fn run_raw_at(
bin: &Path,
args: &[&str],
redacted_label: &str,
timeout: Duration,
) -> Result<(std::process::ExitStatus, String, String), CliError> {
let mut child = Command::new(bin)
.args(args)
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.map_err(|e| CliError::core(CliErrorKind::Spawn, format!("{}: {e}", bin.display())))?;
let stdout = child.stdout.take().expect("piped");
let stderr = child.stderr.take().expect("piped");
let out_h = std::thread::spawn(move || read_all(stdout));
let err_h = std::thread::spawn(move || read_all(stderr));
let deadline = Instant::now() + timeout;
let status = loop {
match child.try_wait() {
Ok(Some(status)) => break status,
Ok(None) => {
if Instant::now() >= deadline {
let _ = child.kill();
let _ = child.wait();
let _ = out_h.join();
let _ = err_h.join();
return Err(CliError::core(
CliErrorKind::Timeout,
format!("no answer within {}s: {redacted_label}", timeout.as_secs()),
));
}
std::thread::sleep(Duration::from_millis(25));
}
Err(e) => return Err(CliError::core(CliErrorKind::Spawn, e.to_string())),
}
};
let stdout = out_h.join().unwrap_or_default();
let stderr = err_h.join().unwrap_or_default();
Ok((status, stdout, stderr))
}
fn fallback_lines(stderr: &str) -> Vec<String> {
stderr
.lines()
.filter(|l| l.contains("#FALLBACK"))
.map(|l| l.trim().to_string())
.collect()
}
fn read_all(mut r: impl Read) -> String {
let mut buf = Vec::new();
let _ = r.read_to_end(&mut buf);
String::from_utf8_lossy(&buf).into_owned()
}
pub(crate) fn error_line(stdout: &str, stderr: &str) -> String {
if let Some(l) = stdout.lines().find(|l| l.contains("Error:")) {
return l.trim().to_string();
}
if let Some(l) = stderr.lines().rev().find(|l| !l.trim().is_empty()) {
return l.trim().to_string();
}
if let Some(l) = stdout.lines().find(|l| !l.trim().is_empty()) {
return l.trim().to_string();
}
"(no output)".into()
}
pub(crate) fn last_json_object(stdout: &str) -> Option<Value> {
let trimmed = stdout.trim();
if trimmed.is_empty() {
return None;
}
if let Ok(v) = serde_json::from_str::<Value>(trimmed) {
return v.is_object().then_some(v);
}
trimmed
.lines()
.rev()
.find_map(|l| serde_json::from_str::<Value>(l.trim()).ok())
.filter(Value::is_object)
}
fn job_error_text(v: &Value) -> Option<String> {
let err = v.get("error");
let text = err
.and_then(Value::as_str)
.or_else(|| err.and_then(|e| e.get("message")).and_then(Value::as_str))
.or_else(|| v.get("message").and_then(Value::as_str))?;
let text = text.trim();
(!text.is_empty()).then(|| text.to_string())
}
pub(crate) fn head(s: &str, n: usize) -> String {
let t: String = s.chars().take(n).collect();
t.replace('\n', " ")
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn bin_resolution_order() {
let home = Path::new("/home/u");
let cwd = Path::new("/work/proj");
let info = resolve_bin(
&|k| match k {
"ABSTRACTCORE_CLI" => Some("/opt/ac".to_string()),
"ABSTRACTCORE_BIN" => Some("/opt/legacy".to_string()),
_ => None,
},
home,
cwd,
&|_| false,
)
.unwrap();
assert_eq!(info.bin, PathBuf::from("/opt/ac"));
assert_eq!(info.source, "$ABSTRACTCORE_CLI");
let info = resolve_bin(
&|k| (k == "ABSTRACTCORE_BIN").then(|| "/opt/legacy".to_string()),
home,
cwd,
&|_| false,
)
.unwrap();
assert_eq!(info.bin, PathBuf::from("/opt/legacy"));
let info = resolve_bin(
&|k| (k == "PATH").then(|| "/a:/b".to_string()),
home,
cwd,
&|p| {
p == Path::new("/b/abstractcore")
|| p.starts_with("/home")
|| p.starts_with("/work")
},
)
.unwrap();
assert_eq!(info.bin, PathBuf::from("/b/abstractcore"));
assert_eq!(info.source, "PATH");
let info = resolve_bin(&|_| None, home, cwd, &|p| {
p == Path::new("/home/u/.local/bin/abstractcore")
|| p == Path::new("/work/proj/.venv/bin/abstractcore")
})
.unwrap();
assert_eq!(info.bin, PathBuf::from("/home/u/.local/bin/abstractcore"));
let info = resolve_bin(&|_| None, home, cwd, &|p| {
p == Path::new("/work/proj/.venv/bin/abstractcore")
})
.unwrap();
assert_eq!(info.bin, PathBuf::from("/work/proj/.venv/bin/abstractcore"));
assert_eq!(info.source, "./.venv");
assert!(resolve_bin(&|_| None, home, cwd, &|p| {
p == Path::new("/home/u/tmp/abstractframework/.venv/bin/abstractcore")
})
.is_none());
assert!(resolve_bin(&|_| None, home, cwd, &|_| false).is_none());
}
#[test]
fn error_line_prefers_the_cli_error() {
let out = "some noise\n❌ Error: Unknown provider 'x'\nmore";
assert_eq!(error_line(out, ""), "❌ Error: Unknown provider 'x'");
assert_eq!(
error_line("", "Traceback...\nValueError: boom"),
"ValueError: boom"
);
assert_eq!(error_line("", ""), "(no output)");
}
#[test]
fn run_json_parses_and_times_out() {
let echo = CoreCli::new(PathBuf::from("/bin/echo"));
let out = echo
.run_json(&["{\"ok\": true}"], Duration::from_secs(5))
.unwrap();
assert_eq!(out.value.get("ok").and_then(Value::as_bool), Some(true));
assert!(out.fallback_warnings.is_empty());
let sleep = CoreCli::new(PathBuf::from("/bin/sleep"));
let err = sleep
.run_json(&["5"], Duration::from_millis(200))
.unwrap_err();
assert_eq!(err.kind, CliErrorKind::Timeout);
let missing = CoreCli::new(PathBuf::from("/nonexistent/bin"));
let err = missing.run_json(&[], Duration::from_secs(1)).unwrap_err();
assert_eq!(err.kind, CliErrorKind::Spawn);
}
#[test]
fn run_json_last_takes_the_final_ndjson_line() {
let sh = CoreCli::new(PathBuf::from("/bin/sh"));
let ok = sh
.run_json_last(
&[
"-c",
r#"echo '{"schema":"host_job_v1","status":"running","percent":10.0}'
echo '{"schema":"host_job_v1","status":"running","percent":90.0}'
echo '{"schema":"host_job_v1","status":"completed","ok":true,"results":[{"status":"downloaded","message":"done"}]}'"#,
],
Duration::from_secs(5),
)
.unwrap();
assert_eq!(ok.value["status"], "completed");
assert_eq!(ok.value["results"][0]["status"], "downloaded");
assert_eq!(
sh.run_json(
&["-c", "echo '{\"a\":1}'; echo '{\"a\":2}'"],
Duration::from_secs(5)
)
.unwrap_err()
.kind,
CliErrorKind::BadJson
);
let failed = sh
.run_json_last(
&[
"-c",
r#"echo '{"schema":"host_job_v1","status":"running"}'
echo '{"schema":"host_job_v1","status":"failed","error":"pull failed: manifest unknown"}'
exit 1"#,
],
Duration::from_secs(5),
)
.unwrap_err();
assert_eq!(failed.kind, CliErrorKind::Exit(1));
assert!(failed.to_string().contains("manifest unknown"), "{failed}");
let empty = sh
.run_json_last(&["-c", "echo not json"], Duration::from_secs(5))
.unwrap_err();
assert_eq!(empty.kind, CliErrorKind::BadJson);
}
#[test]
fn exit_zero_stderr_fallback_is_surfaced() {
let sh = CoreCli::new(PathBuf::from("/bin/sh"));
let out = sh
.run_json(
&[
"-c",
"echo '#FALLBACK abstractcore config could not be parsed; \
falling back to DEFAULTS' >&2; echo '{\"ok\": true}'",
],
Duration::from_secs(5),
)
.unwrap();
assert_eq!(out.value.get("ok").and_then(Value::as_bool), Some(true));
assert_eq!(out.fallback_warnings.len(), 1);
assert!(out.fallback_warnings[0].contains("falling back to DEFAULTS"));
}
}