embacle 0.29.1

LLM runner library — 12 AI CLI tools, ACP, and HTTP APIs (Gemini, Cohere, Groq, OpenRouter, OpenAI-compatible) as pluggable LLM providers with fallback chains, agent loop, guardrails, and cost tracking
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
// ABOUTME: Auth readiness checking for CLI-based LLM runners
// ABOUTME: Verifies that CLI tools are installed, authenticated, and ready to use
//
// SPDX-License-Identifier: Apache-2.0
// Copyright (c) 2026 dravr.ai

use std::env;
use std::fmt;
use std::path::Path;
use std::time::Duration;

use crate::types::RunnerError;
use serde::{Deserialize, Serialize};
use tokio::process::Command;
use tracing::{debug, warn};

use crate::config::CliRunnerType;
use crate::process::{run_cli_command, CliOutput};

/// Maximum time to wait for an auth-check command
const AUTH_CHECK_TIMEOUT: Duration = Duration::from_secs(15);

/// Maximum output size for auth-check commands (64 KiB)
const AUTH_CHECK_MAX_OUTPUT: usize = 64 * 1024;

/// Provider readiness status
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum ProviderReadiness {
    /// CLI is installed and authenticated
    Ready,
    /// CLI is installed but authentication could not be verified
    ///
    /// The binary exists and runs, but the runner lacks a dedicated auth probe.
    /// Requests may still succeed if the user has configured auth externally.
    InstalledAuthUnverified {
        /// Why authentication could not be verified
        reason: String,
    },
    /// CLI is installed but not authenticated or misconfigured
    NotReady {
        /// Human-readable explanation of why the provider is not ready
        reason: String,
        /// Suggested action to fix the issue
        action: String,
    },
    /// CLI binary was not found at the expected path
    BinaryMissing {
        /// Name of the binary that was expected
        expected_binary: String,
    },
    /// Unable to determine readiness
    Unknown {
        /// Explanation of why readiness could not be determined
        reason: String,
    },
}

impl ProviderReadiness {
    /// Returns `true` when the provider is confirmed authenticated and ready
    #[must_use]
    pub const fn is_ready(&self) -> bool {
        matches!(self, Self::Ready)
    }

    /// Returns `true` when the binary is installed (even if auth is unverified)
    #[must_use]
    pub const fn is_installed(&self) -> bool {
        matches!(self, Self::Ready | Self::InstalledAuthUnverified { .. })
    }
}

impl fmt::Display for ProviderReadiness {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Ready => write!(f, "ready"),
            Self::InstalledAuthUnverified { reason } => {
                write!(f, "installed (auth unverified: {reason})")
            }
            Self::NotReady { reason, action } => {
                write!(f, "not ready: {reason} (action: {action})")
            }
            Self::BinaryMissing { expected_binary } => {
                write!(f, "binary missing: {expected_binary}")
            }
            Self::Unknown { reason } => write!(f, "unknown: {reason}"),
        }
    }
}

/// Check whether a CLI runner is ready to handle requests
///
/// Runs a lightweight probe command appropriate for the runner type and
/// interprets the result to determine authentication and availability status.
///
/// # Errors
///
/// Returns `RunnerError` only on internal failures (e.g. I/O errors when
/// spawning the probe process). A non-ready provider is reported as
/// `ProviderReadiness::NotReady`, not as an error.
pub async fn check_readiness(
    runner_type: &CliRunnerType,
    binary_path: &Path,
) -> Result<ProviderReadiness, RunnerError> {
    if !binary_path.exists() {
        return Ok(ProviderReadiness::BinaryMissing {
            expected_binary: binary_path.display().to_string(),
        });
    }

    match runner_type {
        CliRunnerType::ClaudeCode => check_claude_readiness(binary_path).await,
        CliRunnerType::Copilot => check_copilot_readiness(binary_path).await,
        CliRunnerType::OpenCode => check_opencode_readiness(binary_path).await,
        CliRunnerType::GeminiCli => check_gemini_readiness(binary_path).await,
        CliRunnerType::CodexCli => check_codex_readiness(binary_path).await,
        CliRunnerType::CursorAgent => {
            check_version_probe_unverified(binary_path, "cursor-agent").await
        }
        CliRunnerType::GooseCli => check_version_probe_unverified(binary_path, "goose").await,
        CliRunnerType::ClineCli => check_version_probe_unverified(binary_path, "cline").await,
        CliRunnerType::ContinueCli => check_version_probe_unverified(binary_path, "cn").await,
        CliRunnerType::WarpCli => check_version_probe_unverified(binary_path, "oz").await,
        CliRunnerType::KiroCli => check_version_probe_unverified(binary_path, "kiro-cli").await,
        CliRunnerType::KiloCli => check_version_probe_unverified(binary_path, "kilo").await,
        #[cfg(feature = "copilot-headless")]
        CliRunnerType::CopilotHeadless => check_copilot_readiness(binary_path).await,
        // The SDK runner proves readiness with the runtime's own protocol
        // handshake on first use; the wrapper binary has nothing to probe.
        #[cfg(feature = "copilot-sdk")]
        CliRunnerType::CopilotSdk => Ok(ProviderReadiness::Ready),
        // ClaudeWeb readiness is browser/session-based, not binary-based.
        #[cfg(feature = "web-ui")]
        CliRunnerType::ClaudeWeb => Ok(ProviderReadiness::Ready),
    }
}

/// Check if any of the given environment variables are set and non-empty.
///
/// Returns `Some(var_name)` for the first variable found, or `None`.
#[must_use]
pub fn check_env_var_auth<'a>(var_names: &'a [&'a str]) -> Option<&'a str> {
    var_names
        .iter()
        .find(|name| env::var(name).is_ok_and(|v| !v.is_empty()))
        .copied()
}

/// Claude Code has an explicit `auth status` sub-command
async fn check_claude_readiness(binary_path: &Path) -> Result<ProviderReadiness, RunnerError> {
    let mut cmd = Command::new(binary_path);
    cmd.args(["auth", "status"]);

    let output = run_cli_command(&mut cmd, AUTH_CHECK_TIMEOUT, AUTH_CHECK_MAX_OUTPUT).await;

    match output {
        Ok(CliOutput { exit_code: 0, .. }) => {
            debug!("Claude Code auth status: ready");
            Ok(ProviderReadiness::Ready)
        }
        Ok(cli_output) => {
            let stderr = String::from_utf8_lossy(&cli_output.stderr);
            warn!(exit_code = cli_output.exit_code, %stderr, "Claude Code auth check failed");
            Ok(ProviderReadiness::NotReady {
                reason: format!("Auth check exited with code {}", cli_output.exit_code),
                action: "Run `claude auth login` to authenticate".to_owned(),
            })
        }
        Err(e) => Ok(ProviderReadiness::Unknown {
            reason: format!("Failed to run auth check: {e}"),
        }),
    }
}

/// Check Copilot readiness via `gh auth status` for real auth verification.
///
/// Falls back to a `copilot --version` probe if `gh` is not available.
/// A successful `--version` only confirms the binary exists; `gh auth status`
/// confirms the user is actually authenticated with GitHub.
async fn check_copilot_readiness(binary_path: &Path) -> Result<ProviderReadiness, RunnerError> {
    // Try `gh auth status` for a real authentication check
    if let Some(gh_result) = check_gh_auth_status().await {
        return Ok(gh_result);
    }

    // Fall back to version probe when `gh` is unavailable
    debug!("gh CLI not available, falling back to copilot --version probe");
    let mut cmd = Command::new(binary_path);
    cmd.arg("--version");

    let output = run_cli_command(&mut cmd, AUTH_CHECK_TIMEOUT, AUTH_CHECK_MAX_OUTPUT).await;

    match output {
        Ok(CliOutput { exit_code: 0, .. }) => {
            debug!("Copilot CLI version probe succeeded (auth not verified)");
            Ok(ProviderReadiness::Ready)
        }
        Ok(cli_output) => {
            let stderr = String::from_utf8_lossy(&cli_output.stderr);
            warn!(exit_code = cli_output.exit_code, %stderr, "Copilot CLI version probe failed");
            Ok(ProviderReadiness::NotReady {
                reason: format!(
                    "copilot --version exited with code {}",
                    cli_output.exit_code
                ),
                action: "Run `copilot` to complete GitHub authentication".to_owned(),
            })
        }
        Err(e) => Ok(ProviderReadiness::Unknown {
            reason: format!("Failed to run copilot --version: {e}"),
        }),
    }
}

/// Attempt to verify GitHub authentication via `gh auth status`.
///
/// Returns `Some(ProviderReadiness)` when `gh` is available and produces
/// a definitive result; returns `None` when `gh` cannot be found so the
/// caller can fall back to another probe.
async fn check_gh_auth_status() -> Option<ProviderReadiness> {
    let mut cmd = Command::new("gh");
    cmd.args(["auth", "status"]);

    let output = run_cli_command(&mut cmd, AUTH_CHECK_TIMEOUT, AUTH_CHECK_MAX_OUTPUT)
        .await
        .ok()?;

    if output.exit_code == 0 {
        debug!("gh auth status: authenticated");
        Some(ProviderReadiness::Ready)
    } else {
        let stderr = String::from_utf8_lossy(&output.stderr);
        warn!(%stderr, "gh auth status: not authenticated");
        Some(ProviderReadiness::NotReady {
            reason: "GitHub CLI reports not authenticated".to_owned(),
            action: "Run `gh auth login` to authenticate with GitHub".to_owned(),
        })
    }
}

/// Check Gemini CLI readiness via API key env vars, falling back to version probe.
async fn check_gemini_readiness(binary_path: &Path) -> Result<ProviderReadiness, RunnerError> {
    if let Some(var) = check_env_var_auth(&["GOOGLE_API_KEY", "GEMINI_API_KEY"]) {
        debug!(env_var = var, "Gemini: API key found in environment");
        return Ok(ProviderReadiness::Ready);
    }
    check_version_probe_unverified(binary_path, "gemini").await
}

/// Check Codex CLI readiness via `OPENAI_API_KEY` env var, falling back to version probe.
async fn check_codex_readiness(binary_path: &Path) -> Result<ProviderReadiness, RunnerError> {
    if check_env_var_auth(&["OPENAI_API_KEY"]).is_some() {
        debug!("Codex: OPENAI_API_KEY found in environment");
        return Ok(ProviderReadiness::Ready);
    }
    check_version_probe_unverified(binary_path, "codex").await
}

/// Check `OpenCode` readiness via `gh auth status`, falling back to version probe.
async fn check_opencode_readiness(binary_path: &Path) -> Result<ProviderReadiness, RunnerError> {
    if let Some(gh_result) = check_gh_auth_status().await {
        return Ok(gh_result);
    }
    check_version_probe_unverified(binary_path, "opencode").await
}

/// Version probe that returns `InstalledAuthUnverified` on success.
///
/// Used for runners that lack a dedicated auth sub-command and no env var check.
async fn check_version_probe_unverified(
    binary_path: &Path,
    name: &str,
) -> Result<ProviderReadiness, RunnerError> {
    let mut cmd = Command::new(binary_path);
    cmd.arg("--version");

    let output = run_cli_command(&mut cmd, AUTH_CHECK_TIMEOUT, AUTH_CHECK_MAX_OUTPUT).await;

    match output {
        Ok(CliOutput { exit_code: 0, .. }) => {
            debug!(runner = name, "Version probe succeeded (auth not verified)");
            Ok(ProviderReadiness::InstalledAuthUnverified {
                reason: format!("{name} has no dedicated auth probe"),
            })
        }
        Ok(cli_output) => {
            let stderr = String::from_utf8_lossy(&cli_output.stderr);
            warn!(runner = name, exit_code = cli_output.exit_code, %stderr, "Version probe failed");
            Ok(ProviderReadiness::NotReady {
                reason: format!("{name} --version exited with code {}", cli_output.exit_code),
                action: format!("Verify {name} is properly installed"),
            })
        }
        Err(e) => Ok(ProviderReadiness::Unknown {
            reason: format!("Failed to run {name} --version: {e}"),
        }),
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_provider_readiness_is_ready() {
        assert!(ProviderReadiness::Ready.is_ready());
    }

    #[test]
    fn test_provider_readiness_not_ready() {
        let status = ProviderReadiness::NotReady {
            reason: "not authed".to_owned(),
            action: "login".to_owned(),
        };
        assert!(!status.is_ready());
    }

    #[test]
    fn test_provider_readiness_binary_missing() {
        let status = ProviderReadiness::BinaryMissing {
            expected_binary: "claude".to_owned(),
        };
        assert!(!status.is_ready());
    }

    #[test]
    fn test_provider_readiness_unknown() {
        let status = ProviderReadiness::Unknown {
            reason: "timeout".to_owned(),
        };
        assert!(!status.is_ready());
    }

    #[test]
    fn test_provider_readiness_installed_auth_unverified() {
        let status = ProviderReadiness::InstalledAuthUnverified {
            reason: "no auth probe".to_owned(),
        };
        assert!(!status.is_ready());
        assert!(status.is_installed());
    }

    #[test]
    fn test_is_installed_for_ready() {
        assert!(ProviderReadiness::Ready.is_installed());
    }

    #[test]
    fn test_is_installed_for_not_ready() {
        let status = ProviderReadiness::NotReady {
            reason: "x".to_owned(),
            action: "y".to_owned(),
        };
        assert!(!status.is_installed());
    }

    #[test]
    fn test_provider_readiness_display() {
        assert_eq!(format!("{}", ProviderReadiness::Ready), "ready");

        let unverified = ProviderReadiness::InstalledAuthUnverified {
            reason: "no auth probe".to_owned(),
        };
        let display = format!("{unverified}");
        assert!(display.contains("installed"));
        assert!(display.contains("auth unverified"));

        let not_ready = ProviderReadiness::NotReady {
            reason: "expired token".to_owned(),
            action: "re-login".to_owned(),
        };
        assert!(format!("{not_ready}").contains("expired token"));
        assert!(format!("{not_ready}").contains("re-login"));

        let missing = ProviderReadiness::BinaryMissing {
            expected_binary: "claude".to_owned(),
        };
        assert!(format!("{missing}").contains("claude"));

        let unknown = ProviderReadiness::Unknown {
            reason: "error".to_owned(),
        };
        assert!(format!("{unknown}").contains("error"));
    }

    #[test]
    fn test_check_env_var_auth_found() {
        env::set_var("TEST_EMBACLE_AUTH_KEY", "secret123");
        let result = check_env_var_auth(&["NONEXISTENT_VAR", "TEST_EMBACLE_AUTH_KEY"]);
        assert_eq!(result, Some("TEST_EMBACLE_AUTH_KEY"));
        env::remove_var("TEST_EMBACLE_AUTH_KEY");
    }

    #[test]
    fn test_check_env_var_auth_not_found() {
        let result = check_env_var_auth(&["EMBACLE_TEST_DEFINITELY_NOT_SET_12345"]);
        assert!(result.is_none());
    }

    #[test]
    fn test_check_env_var_auth_empty_value_skipped() {
        env::set_var("TEST_EMBACLE_EMPTY_KEY", "");
        let result = check_env_var_auth(&["TEST_EMBACLE_EMPTY_KEY"]);
        assert!(result.is_none());
        env::remove_var("TEST_EMBACLE_EMPTY_KEY");
    }
}