agent-code-lib 0.16.1

Agent engine library: LLM providers, tools, query loop, memory
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
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
//! Environment diagnostics.
//!
//! Comprehensive checks for the agent's runtime environment:
//! tools, configuration, connectivity, and permissions.

use std::path::Path;

/// Result of a single diagnostic check.
#[derive(Debug)]
pub struct Check {
    pub name: String,
    pub status: CheckStatus,
    pub detail: String,
}

#[derive(Debug, PartialEq, Eq)]
pub enum CheckStatus {
    Pass,
    Warn,
    Fail,
}

impl Check {
    fn pass(name: &str, detail: &str) -> Self {
        Self {
            name: name.to_string(),
            status: CheckStatus::Pass,
            detail: detail.to_string(),
        }
    }
    fn warn(name: &str, detail: &str) -> Self {
        Self {
            name: name.to_string(),
            status: CheckStatus::Warn,
            detail: detail.to_string(),
        }
    }
    fn fail(name: &str, detail: &str) -> Self {
        Self {
            name: name.to_string(),
            status: CheckStatus::Fail,
            detail: detail.to_string(),
        }
    }

    pub fn symbol(&self) -> &str {
        match self.status {
            CheckStatus::Pass => "ok",
            CheckStatus::Warn => "!?",
            CheckStatus::Fail => "xx",
        }
    }
}

/// Run all diagnostic checks and return results.
pub async fn run_all(cwd: &Path, config: &crate::config::Config) -> Vec<Check> {
    let mut checks = Vec::new();

    // 1. Required CLI tools.
    for (tool, purpose) in &[
        ("git", "version control"),
        ("rg", "content search (ripgrep)"),
        ("bash", "shell execution"),
    ] {
        let available = tokio::process::Command::new("which")
            .arg(tool)
            .output()
            .await
            .map(|o| o.status.success())
            .unwrap_or(false);

        if available {
            checks.push(Check::pass(
                &format!("tool:{tool}"),
                &format!("{tool} found ({purpose})"),
            ));
        } else {
            checks.push(Check::fail(
                &format!("tool:{tool}"),
                &format!("{tool} not found — needed for {purpose}"),
            ));
        }
    }

    // 2. Optional tools.
    for (tool, purpose) in &[
        ("node", "JavaScript execution"),
        ("python3", "Python execution"),
        ("cargo", "Rust toolchain"),
    ] {
        let available = tokio::process::Command::new("which")
            .arg(tool)
            .output()
            .await
            .map(|o| o.status.success())
            .unwrap_or(false);

        if available {
            checks.push(Check::pass(
                &format!("tool:{tool}"),
                &format!("{tool} available ({purpose})"),
            ));
        } else {
            checks.push(Check::warn(
                &format!("tool:{tool}"),
                &format!("{tool} not found — optional, for {purpose}"),
            ));
        }
    }

    // 3. API configuration.
    if config.api.api_key.is_some() {
        checks.push(Check::pass("config:api_key", "API key configured"));
    } else {
        checks.push(Check::fail(
            "config:api_key",
            "No API key set (AGENT_CODE_API_KEY or --api-key)",
        ));
    }

    checks.push(Check::pass(
        "config:model",
        &format!("Model: {}", config.api.model),
    ));

    checks.push(Check::pass(
        "config:base_url",
        &format!("API endpoint: {}", config.api.base_url),
    ));

    // 4. Git repository.
    if crate::services::git::is_git_repo(cwd).await {
        let branch = crate::services::git::current_branch(cwd)
            .await
            .unwrap_or_else(|| "(detached HEAD)".to_string());
        checks.push(Check::pass(
            "git:repo",
            &format!("Git repository on branch '{branch}'"),
        ));
    } else {
        checks.push(Check::warn("git:repo", "Not inside a git repository"));
    }

    // 5. Config file locations.
    let user_config = dirs::config_dir().map(|d| d.join("agent-code").join("config.toml"));
    if let Some(ref path) = user_config {
        if path.exists() {
            checks.push(Check::pass(
                "config:user_file",
                &format!("User config: {}", path.display()),
            ));
        } else {
            checks.push(Check::warn(
                "config:user_file",
                &format!("No user config at {}", path.display()),
            ));
        }
    }

    let project_config = cwd.join(".agent").join("settings.toml");
    if project_config.exists() {
        checks.push(Check::pass(
            "config:project_file",
            &format!("Project config: {}", project_config.display()),
        ));
    }

    // 6. MCP servers.
    let mcp_count = config.mcp_servers.len();
    if mcp_count > 0 {
        checks.push(Check::pass(
            "mcp:servers",
            &format!("{mcp_count} MCP server(s) configured"),
        ));
    }

    // 7. Provider detection and health check.
    let provider_kind =
        crate::llm::provider::detect_provider(&config.api.model, &config.api.base_url);
    checks.push(Check::pass(
        "provider:detected",
        &format!("Provider: {provider_kind:?}"),
    ));

    if let Some(expected_env) = match provider_kind {
        crate::llm::provider::ProviderKind::AzureOpenAi => Some("AZURE_OPENAI_API_KEY"),
        crate::llm::provider::ProviderKind::Bedrock => Some("AWS_REGION"),
        crate::llm::provider::ProviderKind::Vertex => Some("GOOGLE_CLOUD_PROJECT"),
        _ => None,
    } {
        if std::env::var(expected_env).is_ok() {
            checks.push(Check::pass(
                "provider:env",
                &format!("{expected_env} is set"),
            ));
        } else {
            checks.push(Check::warn(
                "provider:env",
                &format!("{expected_env} not set (may be needed for {provider_kind:?})"),
            ));
        }
    }

    // 8. API connectivity test (provider-aware auth).
    if config.api.api_key.is_some() {
        let api_key = config.api.api_key.as_deref().unwrap_or("");
        let url = format!("{}/models", config.api.base_url);

        let client = reqwest::Client::new();
        let mut request = client.get(&url).timeout(std::time::Duration::from_secs(5));

        // Use provider-specific auth headers.
        match provider_kind {
            crate::llm::provider::ProviderKind::AzureOpenAi => {
                request = request.header("api-key", api_key);
            }
            crate::llm::provider::ProviderKind::Anthropic
            | crate::llm::provider::ProviderKind::Bedrock
            | crate::llm::provider::ProviderKind::Vertex => {
                request = request
                    .header("x-api-key", api_key)
                    .header("anthropic-version", "2023-06-01");
            }
            _ => {
                request = request.header("Authorization", format!("Bearer {api_key}"));
            }
        }

        match request.send().await {
            Ok(resp) => {
                let status = resp.status();
                if status.is_success() || status.as_u16() == 200 {
                    checks.push(Check::pass(
                        "api:connectivity",
                        &format!(
                            "API reachable ({:?} at {})",
                            provider_kind, config.api.base_url
                        ),
                    ));
                } else if status.as_u16() == 401 || status.as_u16() == 403 {
                    checks.push(Check::fail(
                        "api:connectivity",
                        &format!(
                            "API key rejected by {:?} (HTTP {})",
                            provider_kind,
                            status.as_u16()
                        ),
                    ));
                } else {
                    checks.push(Check::warn(
                        "api:connectivity",
                        &format!(
                            "{:?} responded with HTTP {}",
                            provider_kind,
                            status.as_u16()
                        ),
                    ));
                }
            }
            Err(e) => {
                let msg = if e.is_timeout() {
                    format!("{:?} unreachable (timeout after 5s)", provider_kind)
                } else if e.is_connect() {
                    format!(
                        "Cannot connect to {:?} at {}",
                        provider_kind, config.api.base_url
                    )
                } else {
                    format!("{:?} error: {e}", provider_kind)
                };
                checks.push(Check::fail("api:connectivity", &msg));
            }
        }
    }

    // 9. MCP server health check.
    for (name, entry) in &config.mcp_servers {
        if let Some(ref cmd) = entry.command {
            // Check if the command binary exists.
            let binary = cmd.split_whitespace().next().unwrap_or(cmd);
            if let Ok(output) = tokio::process::Command::new("which")
                .arg(binary)
                .output()
                .await
            {
                if output.status.success() {
                    checks.push(Check::pass(
                        &format!("mcp:{name}"),
                        &format!("MCP server '{name}' binary found: {binary}"),
                    ));
                } else {
                    checks.push(Check::fail(
                        &format!("mcp:{name}"),
                        &format!("MCP server '{name}' binary not found: {binary}"),
                    ));
                }
            }
        } else if let Some(ref url) = entry.url {
            // Check if the SSE endpoint is reachable.
            match reqwest::Client::new()
                .get(url)
                .timeout(std::time::Duration::from_secs(3))
                .send()
                .await
            {
                Ok(_) => {
                    checks.push(Check::pass(
                        &format!("mcp:{name}"),
                        &format!("MCP server '{name}' reachable at {url}"),
                    ));
                }
                Err(_) => {
                    checks.push(Check::fail(
                        &format!("mcp:{name}"),
                        &format!("MCP server '{name}' unreachable at {url}"),
                    ));
                }
            }
        }
    }

    // 10. Disk space (warn if < 1GB free).
    // Simple check via df.
    if let Ok(output) = tokio::process::Command::new("df")
        .args(["-BG", "."])
        .current_dir(cwd)
        .output()
        .await
    {
        let text = String::from_utf8_lossy(&output.stdout);
        // Parse the "Available" column from df output.
        if let Some(line) = text.lines().nth(1) {
            let parts: Vec<&str> = line.split_whitespace().collect();
            if let Some(avail) = parts.get(3) {
                let gb: f64 = avail.trim_end_matches('G').parse().unwrap_or(999.0);
                if gb < 1.0 {
                    checks.push(Check::warn(
                        "disk:space",
                        &format!("Low disk space: {avail} available"),
                    ));
                }
            }
        }
    }

    checks
}

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

    #[test]
    fn test_check_constructors() {
        let p = Check::pass("test", "ok");
        assert_eq!(p.status, CheckStatus::Pass);
        assert_eq!(p.symbol(), "ok");

        let w = Check::warn("test", "warning");
        assert_eq!(w.status, CheckStatus::Warn);
        assert_eq!(w.symbol(), "!?");

        let f = Check::fail("test", "failed");
        assert_eq!(f.status, CheckStatus::Fail);
        assert_eq!(f.symbol(), "xx");
    }

    #[test]
    fn test_check_fields() {
        let c = Check::pass("git:repo", "Git repository on branch 'main'");
        assert_eq!(c.name, "git:repo");
        assert!(c.detail.contains("main"));
    }

    #[tokio::test]
    async fn test_run_all_returns_checks() {
        let dir = tempfile::tempdir().unwrap();
        let config = crate::config::Config::default();
        let checks = run_all(dir.path(), &config).await;

        // Should always return at least a few checks.
        assert!(checks.len() >= 3);

        // Should always check for git.
        assert!(checks.iter().any(|c| c.name.starts_with("tool:")));
    }

    #[tokio::test]
    async fn test_run_all_in_git_repo() {
        let dir = tempfile::tempdir().unwrap();
        tokio::process::Command::new("git")
            .args(["init", "-q"])
            .current_dir(dir.path())
            .output()
            .await
            .unwrap();

        let config = crate::config::Config::default();
        let checks = run_all(dir.path(), &config).await;

        let git_check = checks.iter().find(|c| c.name == "git:repo");
        assert!(git_check.is_some());
        assert_eq!(git_check.unwrap().status, CheckStatus::Pass);
    }

    #[tokio::test]
    async fn test_run_all_no_api_key() {
        let dir = tempfile::tempdir().unwrap();
        let mut config = crate::config::Config::default();
        config.api.api_key = None;

        let checks = run_all(dir.path(), &config).await;

        let api_check = checks.iter().find(|c| c.name == "config:api_key");
        assert!(api_check.is_some());
        assert_eq!(api_check.unwrap().status, CheckStatus::Fail);
    }

    #[tokio::test]
    async fn test_run_all_with_api_key() {
        let dir = tempfile::tempdir().unwrap();
        let mut config = crate::config::Config::default();
        config.api.api_key = Some("test-key".to_string());

        let checks = run_all(dir.path(), &config).await;

        let api_check = checks.iter().find(|c| c.name == "config:api_key");
        assert!(api_check.is_some());
        assert_eq!(api_check.unwrap().status, CheckStatus::Pass);
    }

    #[tokio::test]
    async fn test_run_all_includes_provider_check() {
        let dir = tempfile::tempdir().unwrap();
        let mut config = crate::config::Config::default();
        config.api.base_url = "https://api.openai.com/v1".to_string();
        config.api.model = "gpt-5.4".to_string();

        let checks = run_all(dir.path(), &config).await;

        let provider_check = checks.iter().find(|c| c.name == "provider:detected");
        assert!(provider_check.is_some());
        assert_eq!(provider_check.unwrap().status, CheckStatus::Pass);
        assert!(provider_check.unwrap().detail.contains("OpenAi"));
    }

    #[tokio::test]
    async fn test_run_all_azure_provider_env_check() {
        let dir = tempfile::tempdir().unwrap();
        let mut config = crate::config::Config::default();
        config.api.base_url =
            "https://myresource.openai.azure.com/openai/deployments/gpt-4".to_string();

        let checks = run_all(dir.path(), &config).await;

        let provider_check = checks.iter().find(|c| c.name == "provider:detected");
        assert!(provider_check.is_some());
        assert!(provider_check.unwrap().detail.contains("AzureOpenAi"));

        // Should have a provider:env check for AZURE_OPENAI_API_KEY.
        let env_check = checks.iter().find(|c| c.name == "provider:env");
        assert!(env_check.is_some());
    }

    #[tokio::test]
    async fn test_run_all_mcp_servers() {
        let dir = tempfile::tempdir().unwrap();
        let mut config = crate::config::Config::default();
        config.mcp_servers.insert(
            "test-server".to_string(),
            crate::config::McpServerEntry {
                command: Some("nonexistent-binary-xyz".to_string()),
                args: vec![],
                url: None,
                env: std::collections::HashMap::new(),
            },
        );

        let checks = run_all(dir.path(), &config).await;

        // Should have a check for the MCP server.
        let mcp_check = checks.iter().find(|c| c.name == "mcp:test-server");
        assert!(mcp_check.is_some());
        // The binary won't exist, so it should fail.
        assert_eq!(mcp_check.unwrap().status, CheckStatus::Fail);
    }
}