use std::path::PathBuf;
use std::process::{Command, Stdio};
use std::time::{Duration, Instant};
use async_trait::async_trait;
use serde::{Deserialize, Serialize};
use super::{InferenceRequest, InferenceResponse, LocalInferenceClient, ModelInfo};
use crate::error::{IronError, Result};
const DEFAULT_CLI_TIMEOUT: Duration = Duration::from_secs(120);
const POLL_INTERVAL: Duration = Duration::from_millis(25);
const DEFAULT_OLLAMA_MODEL: &str = "llama3.2";
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum CliProvider {
Claude,
Codex,
Gemini,
Ollama,
}
impl CliProvider {
pub const ALL: [CliProvider; 4] = [
CliProvider::Ollama,
CliProvider::Claude,
CliProvider::Codex,
CliProvider::Gemini,
];
pub fn binary(&self) -> &'static str {
match self {
CliProvider::Claude => "claude",
CliProvider::Codex => "codex",
CliProvider::Gemini => "gemini",
CliProvider::Ollama => "ollama",
}
}
pub fn display_name(&self) -> &'static str {
match self {
CliProvider::Claude => "Claude CLI",
CliProvider::Codex => "Codex CLI",
CliProvider::Gemini => "Gemini CLI",
CliProvider::Ollama => "Ollama CLI",
}
}
pub fn runs_on_host(&self) -> bool {
matches!(self, CliProvider::Ollama)
}
pub fn requires_model(&self) -> bool {
matches!(self, CliProvider::Ollama)
}
pub fn detect(&self) -> Option<PathBuf> {
which_on_path(self.binary())
}
fn build_args(&self, prompt: &str, model: Option<&str>) -> Vec<String> {
match self {
CliProvider::Claude => {
let mut args = vec!["-p".to_string(), prompt.to_string()];
if let Some(model) = model {
args.push("--model".to_string());
args.push(model.to_string());
}
args
}
CliProvider::Codex => {
let mut args = vec!["exec".to_string()];
if let Some(model) = model {
args.push("--model".to_string());
args.push(model.to_string());
}
args.push(prompt.to_string());
args
}
CliProvider::Gemini => {
let mut args = vec!["-p".to_string(), prompt.to_string()];
if let Some(model) = model {
args.push("--model".to_string());
args.push(model.to_string());
}
args
}
CliProvider::Ollama => vec![
"run".to_string(),
model.unwrap_or(DEFAULT_OLLAMA_MODEL).to_string(),
prompt.to_string(),
"--hidethinking".to_string(),
],
}
}
}
impl std::fmt::Display for CliProvider {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.display_name())
}
}
pub fn binary_on_path(binary: &str) -> bool {
which_on_path(binary).is_some()
}
fn which_on_path(binary: &str) -> Option<PathBuf> {
let path = std::env::var_os("PATH")?;
#[cfg(target_os = "windows")]
let candidates: Vec<String> = {
let exts = std::env::var("PATHEXT").unwrap_or_else(|_| ".EXE;.CMD;.BAT;.COM".to_string());
let mut names = vec![binary.to_string()];
names.extend(
exts.split(';')
.filter(|e| !e.is_empty())
.map(|ext| format!("{binary}{}", ext.to_lowercase())),
);
names
};
#[cfg(not(target_os = "windows"))]
let candidates: Vec<String> = vec![binary.to_string()];
for dir in std::env::split_paths(&path) {
for name in &candidates {
let candidate = dir.join(name);
if candidate.is_file() {
return Some(candidate);
}
}
}
None
}
#[derive(Debug, Clone)]
pub struct CliClient {
provider: CliProvider,
binary: PathBuf,
timeout: Duration,
}
impl CliClient {
pub fn detect(provider: CliProvider) -> Option<Self> {
provider.detect().map(|binary| Self {
provider,
binary,
timeout: DEFAULT_CLI_TIMEOUT,
})
}
pub fn detect_any() -> Option<Self> {
CliProvider::ALL.iter().copied().find_map(Self::detect)
}
pub fn detect_all() -> Vec<Self> {
CliProvider::ALL
.iter()
.copied()
.filter_map(Self::detect)
.collect()
}
pub fn with_timeout(mut self, timeout: Duration) -> Self {
self.timeout = timeout;
self
}
pub fn provider(&self) -> CliProvider {
self.provider
}
pub fn binary_path(&self) -> &PathBuf {
&self.binary
}
pub fn query_blocking(
&self,
system_prompt: &str,
user_prompt: &str,
model: Option<&str>,
) -> Result<(String, u64)> {
let start = Instant::now();
let prompt = if system_prompt.is_empty() {
user_prompt.to_string()
} else {
format!("{system_prompt}\n\n{user_prompt}")
};
let model = model.filter(|m| !m.is_empty() && *m != "default").or(
if self.provider.requires_model() {
Some(DEFAULT_OLLAMA_MODEL)
} else {
None
},
);
let text = self.run(&self.provider.build_args(&prompt, model))?;
Ok((text, start.elapsed().as_millis() as u64))
}
fn run(&self, args: &[String]) -> Result<String> {
let mut child = Command::new(&self.binary)
.args(args)
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.map_err(|e| {
IronError::Agent(format!("failed to start {}: {e}", self.binary.display()))
})?;
let deadline = Instant::now() + self.timeout;
loop {
match child.try_wait() {
Ok(Some(_)) => break,
Ok(None) => {
if Instant::now() >= deadline {
let _ = child.kill();
let _ = child.wait();
return Err(IronError::Agent(format!(
"{} did not respond within {}s",
self.provider.display_name(),
self.timeout.as_secs()
)));
}
std::thread::sleep(POLL_INTERVAL);
}
Err(e) => {
return Err(IronError::Agent(format!(
"failed while waiting on {}: {e}",
self.provider.display_name()
)))
}
}
}
let output = child.wait_with_output().map_err(|e| {
IronError::Agent(format!(
"failed to read output from {}: {e}",
self.provider.display_name()
))
})?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
return Err(IronError::Agent(format!(
"{} exited with {}: {}",
self.provider.display_name(),
output.status,
stderr.trim()
)));
}
Ok(String::from_utf8_lossy(&output.stdout).trim().to_string())
}
}
#[async_trait]
impl LocalInferenceClient for CliClient {
fn name(&self) -> &str {
self.provider.display_name()
}
async fn is_available(&self) -> bool {
self.binary.is_file()
}
async fn list_models(&self) -> Result<Vec<ModelInfo>> {
if self.provider != CliProvider::Ollama {
return Err(IronError::NotImplemented(format!(
"{} does not expose a model listing; its model is set in the tool's own configuration",
self.provider.display_name()
)));
}
let output = self.run(&["list".to_string()])?;
Ok(output
.lines()
.skip(1) .filter_map(|line| line.split_whitespace().next())
.filter(|name| !name.is_empty())
.map(|name| ModelInfo {
name: name.to_string(),
size: None,
family: None,
parameter_count: None,
quantization: None,
})
.collect())
}
async fn generate(&self, request: InferenceRequest) -> Result<InferenceResponse> {
let (text, duration_ms) = self.query_blocking(
request.system.as_deref().unwrap_or(""),
&request.prompt,
Some(request.model.as_str()),
)?;
Ok(InferenceResponse {
text,
model: request.model,
tokens_generated: None,
duration_ms,
truncated: None,
})
}
async fn model_info(&self, model_name: &str) -> Result<ModelInfo> {
let models = self.list_models().await?;
models
.into_iter()
.find(|m| m.name == model_name)
.ok_or_else(|| {
IronError::Agent(format!(
"{} does not report a model named {model_name}",
self.provider.display_name()
))
})
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn only_ollama_infers_on_host() {
assert!(CliProvider::Ollama.runs_on_host());
assert!(!CliProvider::Claude.runs_on_host());
assert!(!CliProvider::Codex.runs_on_host());
assert!(!CliProvider::Gemini.runs_on_host());
}
#[test]
fn ollama_is_preferred_in_detection_order() {
assert_eq!(CliProvider::ALL[0], CliProvider::Ollama);
assert!(CliProvider::ALL[0].runs_on_host());
}
#[test]
fn non_interactive_flags_are_present() {
let claude = CliProvider::Claude.build_args("hi", None);
assert_eq!(claude.first().map(String::as_str), Some("-p"));
let codex = CliProvider::Codex.build_args("hi", None);
assert_eq!(codex.first().map(String::as_str), Some("exec"));
let gemini = CliProvider::Gemini.build_args("hi", None);
assert_eq!(gemini.first().map(String::as_str), Some("-p"));
let ollama = CliProvider::Ollama.build_args("hi", Some("llama3.2"));
assert_eq!(ollama.first().map(String::as_str), Some("run"));
}
#[test]
fn prompt_is_a_separate_argument_never_shell_interpolated() {
let nasty = "test\"; rm -rf /; echo \"";
for provider in CliProvider::ALL {
let args = provider.build_args(nasty, Some("m"));
assert!(
args.iter().any(|a| a == nasty),
"{provider} must pass the prompt verbatim as one argument"
);
}
}
#[test]
fn ollama_requires_a_model_and_others_do_not() {
assert!(CliProvider::Ollama.requires_model());
assert!(!CliProvider::Claude.requires_model());
let args = CliProvider::Ollama.build_args("prompt", Some("qwen3"));
let model_idx = args.iter().position(|a| a == "qwen3").expect("model");
let prompt_idx = args.iter().position(|a| a == "prompt").expect("prompt");
assert!(model_idx < prompt_idx, "model must precede the prompt");
}
#[test]
fn detection_reports_absent_tools_as_none() {
for provider in CliProvider::ALL {
match CliClient::detect(provider) {
Some(client) => {
eprintln!("detected {provider} -> {}", client.binary_path().display());
assert!(
client.binary_path().is_file(),
"{provider} was detected but its binary does not exist"
);
}
None => {
eprintln!("absent {provider}");
assert!(
provider.detect().is_none(),
"{provider} detection disagreed with itself"
);
}
}
}
}
#[tokio::test]
async fn ollama_subprocess_round_trip() {
if std::env::var_os("IRONMON_TEST_EXTERNAL_CLI").is_none() {
eprintln!("skipping: set IRONMON_TEST_EXTERNAL_CLI=1 to run against a live ollama");
return;
}
let Some(client) = CliClient::detect(CliProvider::Ollama)
.map(|client| client.with_timeout(Duration::from_secs(10)))
else {
eprintln!("skipping: ollama not installed");
return;
};
assert!(client.is_available().await);
let models = client
.list_models()
.await
.expect("`ollama list` should succeed when ollama is installed");
eprintln!("ollama reports {} model(s)", models.len());
for model in &models {
assert!(
!model.name.is_empty(),
"parsed an empty model name from `ollama list` output"
);
assert_ne!(model.name.to_uppercase(), "NAME");
}
}
#[test]
fn timeout_kills_a_hung_child() {
#[cfg(target_os = "windows")]
let (bin, args) = ("cmd", vec!["/c".to_string(), "timeout /t 30".to_string()]);
#[cfg(not(target_os = "windows"))]
let (bin, args) = ("sh", vec!["-c".to_string(), "sleep 30".to_string()]);
let Some(binary) = which_on_path(bin) else {
eprintln!("skipping: {bin} not found");
return;
};
let client = CliClient {
provider: CliProvider::Ollama,
binary,
timeout: Duration::from_millis(300),
};
let started = Instant::now();
let result = client.run(&args);
let elapsed = started.elapsed();
assert!(result.is_err(), "a hung child must produce an error");
assert!(
elapsed < Duration::from_secs(10),
"timeout did not fire; waited {elapsed:?} for a 300ms budget"
);
}
#[test]
fn which_on_path_finds_a_known_binary() {
let found = which_on_path("cargo");
assert!(
found.is_some(),
"PATH lookup failed for a binary known to exist"
);
assert!(found.unwrap().is_file());
}
#[test]
fn which_on_path_rejects_nonexistent_binary() {
assert!(which_on_path("ironmon-definitely-not-a-real-binary-xyzzy").is_none());
}
}