1use std::io::Read;
9use std::path::{Path, PathBuf};
10use std::process::{Command, Stdio};
11use std::time::{Duration, Instant};
12
13use serde_json::Value;
14
15const UV_TOOL_BIN: &str = ".local/bin/abstractcore";
17const LOCAL_VENV_BIN: &str = ".venv/bin/abstractcore";
19
20#[derive(Clone, Debug, PartialEq)]
21pub enum CliErrorKind {
22 NotFound,
24 Spawn,
26 Timeout,
28 Exit(i32),
30 BadJson,
32}
33
34#[derive(Clone, Debug)]
35pub struct CliError {
36 pub kind: CliErrorKind,
37 pub message: String,
38 pub program: &'static str,
42}
43
44impl CliError {
45 pub fn core(kind: CliErrorKind, message: String) -> CliError {
46 CliError {
47 kind,
48 message,
49 program: "abstractcore",
50 }
51 }
52
53 pub fn chat(kind: CliErrorKind, message: String) -> CliError {
54 CliError {
55 kind,
56 message,
57 program: "abstractcore-chat",
58 }
59 }
60
61 pub fn headline(&self) -> String {
62 let p = self.program;
63 match self.kind {
64 CliErrorKind::NotFound => format!("{p} CLI not found"),
65 CliErrorKind::Spawn => format!("could not start {p}"),
66 CliErrorKind::Timeout => format!("{p} timed out"),
67 CliErrorKind::Exit(code) => format!("{p} exited with {code}"),
68 CliErrorKind::BadJson => format!("{p} answered, but not with JSON"),
69 }
70 }
71
72 pub fn hint(&self) -> &'static str {
74 match self.kind {
75 CliErrorKind::NotFound => {
76 "set $ABSTRACTCORE_CLI, or install abstractcore on PATH — the file mirror still works"
77 }
78 CliErrorKind::Spawn => "check the binary is executable ($ABSTRACTCORE_CLI?)",
79 CliErrorKind::Timeout => "the Python side hung — retry with r",
80 CliErrorKind::Exit(_) => "the message above is the CLI's own error",
81 CliErrorKind::BadJson => "an abstractcore too old for --json? check its version",
82 }
83 }
84}
85
86impl std::fmt::Display for CliError {
87 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
88 write!(f, "{}: {}", self.headline(), self.message)
89 }
90}
91
92#[derive(Clone, Debug)]
95pub struct CliInfo {
96 pub bin: PathBuf,
97 pub source: &'static str,
98}
99
100pub fn resolve_bin(
113 env: &dyn Fn(&str) -> Option<String>,
114 home: &Path,
115 cwd: &Path,
116 exists: &dyn Fn(&Path) -> bool,
117) -> Option<CliInfo> {
118 for (var, source) in [
119 ("ABSTRACTCORE_CLI", "$ABSTRACTCORE_CLI"),
120 ("ABSTRACTCORE_BIN", "$ABSTRACTCORE_BIN (legacy alias)"),
121 ] {
122 if let Some(explicit) = env(var).filter(|v| !v.trim().is_empty()) {
123 return Some(CliInfo {
124 bin: PathBuf::from(explicit.trim()),
125 source,
126 });
127 }
128 }
129 if let Some(paths) = env("PATH") {
130 for dir in std::env::split_paths(&paths) {
131 let candidate = dir.join("abstractcore");
132 if exists(&candidate) {
133 return Some(CliInfo {
134 bin: candidate,
135 source: "PATH",
136 });
137 }
138 }
139 }
140 if !home.as_os_str().is_empty() {
141 let shim = home.join(UV_TOOL_BIN);
142 if exists(&shim) {
143 return Some(CliInfo {
144 bin: shim,
145 source: "~/.local/bin (uv tool)",
146 });
147 }
148 }
149 let venv = cwd.join(LOCAL_VENV_BIN);
150 if exists(&venv) {
151 return Some(CliInfo {
152 bin: venv,
153 source: "./.venv",
154 });
155 }
156 None
157}
158
159pub fn resolve_bin_from_env() -> Option<CliInfo> {
160 let home = std::env::var("HOME").map(PathBuf::from).unwrap_or_default();
161 let cwd = std::env::current_dir().unwrap_or_default();
162 resolve_bin(&|k| std::env::var(k).ok(), &home, &cwd, &|p| p.is_file())
163}
164
165pub struct CoreCli {
166 pub bin: PathBuf,
167 pub chat_bin: Option<PathBuf>,
171 pub chat_from_path: bool,
176}
177
178pub fn resolve_chat_bin(
183 core_bin: &Path,
184 exists: &dyn Fn(&Path) -> bool,
185) -> Option<(PathBuf, bool)> {
186 let sibling = core_bin.with_file_name("abstractcore-chat");
187 if exists(&sibling) {
188 return Some((sibling, false));
189 }
190 if let Some(paths) = std::env::var_os("PATH") {
191 for dir in std::env::split_paths(&paths) {
192 let candidate = dir.join("abstractcore-chat");
193 if exists(&candidate) {
194 return Some((candidate, true));
195 }
196 }
197 }
198 None
199}
200
201#[derive(Clone, Debug)]
209pub struct CliOutput {
210 pub value: Value,
211 pub fallback_warnings: Vec<String>,
212}
213
214impl CoreCli {
215 pub fn new(bin: PathBuf) -> CoreCli {
216 let resolved = resolve_chat_bin(&bin, &|p| p.is_file());
217 let chat_from_path = resolved.as_ref().is_some_and(|(_, from_path)| *from_path);
218 CoreCli {
219 bin,
220 chat_bin: resolved.map(|(p, _)| p),
221 chat_from_path,
222 }
223 }
224
225 #[cfg(test)]
227 pub fn bare(bin: PathBuf) -> CoreCli {
228 CoreCli {
229 bin,
230 chat_bin: None,
231 chat_from_path: false,
232 }
233 }
234
235 pub fn run_chat(
241 &self,
242 args: &[&str],
243 timeout: Duration,
244 ) -> Result<(String, Vec<String>), CliError> {
245 let chat = self.chat_bin.as_ref().ok_or_else(|| {
246 CliError::chat(
247 CliErrorKind::NotFound,
248 "abstractcore-chat not found beside abstractcore or on PATH".into(),
249 )
250 })?;
251 let label = format!("abstractcore-chat {}", args.join(" "));
252 let (status, stdout, stderr) =
253 run_raw_at(chat, args, &label, timeout).map_err(|mut e| {
254 e.program = "abstractcore-chat";
255 e
256 })?;
257 if !status.success() {
258 return Err(CliError::chat(
259 CliErrorKind::Exit(status.code().unwrap_or(-1)),
260 error_line(&stdout, &stderr),
261 ));
262 }
263 Ok((stdout, fallback_lines(&stderr)))
264 }
265
266 pub fn run_setter(
275 &self,
276 args: &[&str],
277 redacted_label: &str,
278 timeout: Duration,
279 ) -> Result<Vec<String>, CliError> {
280 let (status, stdout, stderr) = self.run_raw(args, redacted_label, timeout)?;
281 if !status.success() {
282 return Err(CliError::core(
283 CliErrorKind::Exit(status.code().unwrap_or(-1)),
284 error_line(&stdout, &stderr),
285 ));
286 }
287 if let Some(l) = stdout
288 .lines()
289 .find(|l| l.contains("❌") || l.contains("Error:"))
290 {
291 return Err(CliError::core(
292 CliErrorKind::Exit(0),
293 format!("{} (the CLI still exited 0)", l.trim()),
294 ));
295 }
296 Ok(fallback_lines(&stderr))
297 }
298
299 pub fn run_json(&self, args: &[&str], timeout: Duration) -> Result<CliOutput, CliError> {
306 let label = format!("abstractcore {}", args.join(" "));
309 let (status, stdout, stderr) = self.run_raw(args, &label, timeout)?;
310 if !status.success() {
311 let code = status.code().unwrap_or(-1);
312 return Err(CliError::core(
313 CliErrorKind::Exit(code),
314 error_line(&stdout, &stderr),
315 ));
316 }
317 let value = serde_json::from_str(&stdout).map_err(|e| {
318 CliError::core(
319 CliErrorKind::BadJson,
320 format!("{e} — first bytes: {}", head(&stdout, 120)),
321 )
322 })?;
323 Ok(CliOutput {
324 value,
325 fallback_warnings: fallback_lines(&stderr),
326 })
327 }
328
329 pub fn run_json_last(&self, args: &[&str], timeout: Duration) -> Result<CliOutput, CliError> {
340 let label = format!("abstractcore {}", args.join(" "));
341 let (status, stdout, stderr) = self.run_raw(args, &label, timeout)?;
342 let last = last_json_object(&stdout);
343 if !status.success() {
344 let code = status.code().unwrap_or(-1);
345 let msg = last
346 .as_ref()
347 .and_then(job_error_text)
348 .unwrap_or_else(|| error_line(&stdout, &stderr));
349 return Err(CliError::core(CliErrorKind::Exit(code), msg));
350 }
351 let value = last.ok_or_else(|| {
352 CliError::core(
353 CliErrorKind::BadJson,
354 format!(
355 "no JSON object on stdout — first bytes: {}",
356 head(&stdout, 120)
357 ),
358 )
359 })?;
360 Ok(CliOutput {
361 value,
362 fallback_warnings: fallback_lines(&stderr),
363 })
364 }
365
366 fn run_raw(
370 &self,
371 args: &[&str],
372 redacted_label: &str,
373 timeout: Duration,
374 ) -> Result<(std::process::ExitStatus, String, String), CliError> {
375 run_raw_at(&self.bin, args, redacted_label, timeout)
376 }
377}
378
379pub(crate) fn run_raw_at(
380 bin: &Path,
381 args: &[&str],
382 redacted_label: &str,
383 timeout: Duration,
384) -> Result<(std::process::ExitStatus, String, String), CliError> {
385 let mut child = Command::new(bin)
386 .args(args)
387 .stdin(Stdio::null())
388 .stdout(Stdio::piped())
389 .stderr(Stdio::piped())
390 .spawn()
391 .map_err(|e| CliError::core(CliErrorKind::Spawn, format!("{}: {e}", bin.display())))?;
392
393 let stdout = child.stdout.take().expect("piped");
394 let stderr = child.stderr.take().expect("piped");
395 let out_h = std::thread::spawn(move || read_all(stdout));
396 let err_h = std::thread::spawn(move || read_all(stderr));
397
398 let deadline = Instant::now() + timeout;
399 let status = loop {
400 match child.try_wait() {
401 Ok(Some(status)) => break status,
402 Ok(None) => {
403 if Instant::now() >= deadline {
404 let _ = child.kill();
405 let _ = child.wait();
406 let _ = out_h.join();
408 let _ = err_h.join();
409 return Err(CliError::core(
410 CliErrorKind::Timeout,
411 format!("no answer within {}s: {redacted_label}", timeout.as_secs()),
412 ));
413 }
414 std::thread::sleep(Duration::from_millis(25));
415 }
416 Err(e) => return Err(CliError::core(CliErrorKind::Spawn, e.to_string())),
417 }
418 };
419 let stdout = out_h.join().unwrap_or_default();
420 let stderr = err_h.join().unwrap_or_default();
421 Ok((status, stdout, stderr))
422}
423
424fn fallback_lines(stderr: &str) -> Vec<String> {
428 stderr
429 .lines()
430 .filter(|l| l.contains("#FALLBACK"))
431 .map(|l| l.trim().to_string())
432 .collect()
433}
434
435fn read_all(mut r: impl Read) -> String {
436 let mut buf = Vec::new();
437 let _ = r.read_to_end(&mut buf);
438 String::from_utf8_lossy(&buf).into_owned()
439}
440
441pub(crate) fn error_line(stdout: &str, stderr: &str) -> String {
445 if let Some(l) = stdout.lines().find(|l| l.contains("Error:")) {
446 return l.trim().to_string();
447 }
448 if let Some(l) = stderr.lines().rev().find(|l| !l.trim().is_empty()) {
449 return l.trim().to_string();
450 }
451 if let Some(l) = stdout.lines().find(|l| !l.trim().is_empty()) {
452 return l.trim().to_string();
453 }
454 "(no output)".into()
455}
456
457pub(crate) fn last_json_object(stdout: &str) -> Option<Value> {
460 let trimmed = stdout.trim();
461 if trimmed.is_empty() {
462 return None;
463 }
464 if let Ok(v) = serde_json::from_str::<Value>(trimmed) {
465 return v.is_object().then_some(v);
466 }
467 trimmed
468 .lines()
469 .rev()
470 .find_map(|l| serde_json::from_str::<Value>(l.trim()).ok())
471 .filter(Value::is_object)
472}
473
474fn job_error_text(v: &Value) -> Option<String> {
477 let err = v.get("error");
478 let text = err
479 .and_then(Value::as_str)
480 .or_else(|| err.and_then(|e| e.get("message")).and_then(Value::as_str))
481 .or_else(|| v.get("message").and_then(Value::as_str))?;
482 let text = text.trim();
483 (!text.is_empty()).then(|| text.to_string())
484}
485
486pub(crate) fn head(s: &str, n: usize) -> String {
487 let t: String = s.chars().take(n).collect();
488 t.replace('\n', " ")
489}
490
491#[cfg(test)]
492mod tests {
493 use super::*;
494
495 #[test]
496 fn bin_resolution_order() {
497 let home = Path::new("/home/u");
498 let cwd = Path::new("/work/proj");
499 let info = resolve_bin(
502 &|k| match k {
503 "ABSTRACTCORE_CLI" => Some("/opt/ac".to_string()),
504 "ABSTRACTCORE_BIN" => Some("/opt/legacy".to_string()),
505 _ => None,
506 },
507 home,
508 cwd,
509 &|_| false,
510 )
511 .unwrap();
512 assert_eq!(info.bin, PathBuf::from("/opt/ac"));
513 assert_eq!(info.source, "$ABSTRACTCORE_CLI");
514 let info = resolve_bin(
515 &|k| (k == "ABSTRACTCORE_BIN").then(|| "/opt/legacy".to_string()),
516 home,
517 cwd,
518 &|_| false,
519 )
520 .unwrap();
521 assert_eq!(info.bin, PathBuf::from("/opt/legacy"));
522
523 let info = resolve_bin(
525 &|k| (k == "PATH").then(|| "/a:/b".to_string()),
526 home,
527 cwd,
528 &|p| {
529 p == Path::new("/b/abstractcore")
530 || p.starts_with("/home")
531 || p.starts_with("/work")
532 },
533 )
534 .unwrap();
535 assert_eq!(info.bin, PathBuf::from("/b/abstractcore"));
536 assert_eq!(info.source, "PATH");
537
538 let info = resolve_bin(&|_| None, home, cwd, &|p| {
540 p == Path::new("/home/u/.local/bin/abstractcore")
541 || p == Path::new("/work/proj/.venv/bin/abstractcore")
542 })
543 .unwrap();
544 assert_eq!(info.bin, PathBuf::from("/home/u/.local/bin/abstractcore"));
545 let info = resolve_bin(&|_| None, home, cwd, &|p| {
546 p == Path::new("/work/proj/.venv/bin/abstractcore")
547 })
548 .unwrap();
549 assert_eq!(info.bin, PathBuf::from("/work/proj/.venv/bin/abstractcore"));
550 assert_eq!(info.source, "./.venv");
551
552 assert!(resolve_bin(&|_| None, home, cwd, &|p| {
554 p == Path::new("/home/u/tmp/abstractframework/.venv/bin/abstractcore")
555 })
556 .is_none());
557
558 assert!(resolve_bin(&|_| None, home, cwd, &|_| false).is_none());
560 }
561
562 #[test]
563 fn error_line_prefers_the_cli_error() {
564 let out = "some noise\n❌ Error: Unknown provider 'x'\nmore";
565 assert_eq!(error_line(out, ""), "❌ Error: Unknown provider 'x'");
566 assert_eq!(
567 error_line("", "Traceback...\nValueError: boom"),
568 "ValueError: boom"
569 );
570 assert_eq!(error_line("", ""), "(no output)");
571 }
572
573 #[test]
577 fn run_json_parses_and_times_out() {
578 let echo = CoreCli::new(PathBuf::from("/bin/echo"));
579 let out = echo
580 .run_json(&["{\"ok\": true}"], Duration::from_secs(5))
581 .unwrap();
582 assert_eq!(out.value.get("ok").and_then(Value::as_bool), Some(true));
583 assert!(out.fallback_warnings.is_empty());
584
585 let sleep = CoreCli::new(PathBuf::from("/bin/sleep"));
586 let err = sleep
587 .run_json(&["5"], Duration::from_millis(200))
588 .unwrap_err();
589 assert_eq!(err.kind, CliErrorKind::Timeout);
590
591 let missing = CoreCli::new(PathBuf::from("/nonexistent/bin"));
592 let err = missing.run_json(&[], Duration::from_secs(1)).unwrap_err();
593 assert_eq!(err.kind, CliErrorKind::Spawn);
594 }
595
596 #[test]
600 fn run_json_last_takes_the_final_ndjson_line() {
601 let sh = CoreCli::new(PathBuf::from("/bin/sh"));
602 let ok = sh
603 .run_json_last(
604 &[
605 "-c",
606 r#"echo '{"schema":"host_job_v1","status":"running","percent":10.0}'
607echo '{"schema":"host_job_v1","status":"running","percent":90.0}'
608echo '{"schema":"host_job_v1","status":"completed","ok":true,"results":[{"status":"downloaded","message":"done"}]}'"#,
609 ],
610 Duration::from_secs(5),
611 )
612 .unwrap();
613 assert_eq!(ok.value["status"], "completed");
614 assert_eq!(ok.value["results"][0]["status"], "downloaded");
615
616 assert_eq!(
618 sh.run_json(
619 &["-c", "echo '{\"a\":1}'; echo '{\"a\":2}'"],
620 Duration::from_secs(5)
621 )
622 .unwrap_err()
623 .kind,
624 CliErrorKind::BadJson
625 );
626
627 let failed = sh
628 .run_json_last(
629 &[
630 "-c",
631 r#"echo '{"schema":"host_job_v1","status":"running"}'
632echo '{"schema":"host_job_v1","status":"failed","error":"pull failed: manifest unknown"}'
633exit 1"#,
634 ],
635 Duration::from_secs(5),
636 )
637 .unwrap_err();
638 assert_eq!(failed.kind, CliErrorKind::Exit(1));
639 assert!(failed.to_string().contains("manifest unknown"), "{failed}");
640
641 let empty = sh
642 .run_json_last(&["-c", "echo not json"], Duration::from_secs(5))
643 .unwrap_err();
644 assert_eq!(empty.kind, CliErrorKind::BadJson);
645 }
646
647 #[test]
651 fn exit_zero_stderr_fallback_is_surfaced() {
652 let sh = CoreCli::new(PathBuf::from("/bin/sh"));
653 let out = sh
654 .run_json(
655 &[
656 "-c",
657 "echo '#FALLBACK abstractcore config could not be parsed; \
658 falling back to DEFAULTS' >&2; echo '{\"ok\": true}'",
659 ],
660 Duration::from_secs(5),
661 )
662 .unwrap();
663 assert_eq!(out.value.get("ok").and_then(Value::as_bool), Some(true));
664 assert_eq!(out.fallback_warnings.len(), 1);
665 assert!(out.fallback_warnings[0].contains("falling back to DEFAULTS"));
666 }
667}