apollo-agent 0.6.0

Local-first Rust AI agent runtime — Telegram-first, trait-driven, SurrealDB + RocksDB state layer.
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
//! Shared diagnostics and security audit helpers.

use crate::config::Config;
use serde::Serialize;
use std::path::Path;

#[derive(Debug, Clone, Copy, Serialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum Severity {
    Info,
    Warn,
    Critical,
}

#[derive(Debug, Clone, Serialize)]
pub struct Finding {
    pub code: &'static str,
    pub severity: Severity,
    pub title: &'static str,
    pub detail: String,
    pub remediation: Option<String>,
}

#[derive(Debug, Clone, Serialize)]
pub struct Check {
    pub name: String,
    pub ok: bool,
    pub detail: String,
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub soft_warn: bool,
}

#[derive(Debug, Clone, Serialize)]
pub struct DoctorReport {
    pub findings: Vec<Finding>,
    pub checks: Vec<Check>,
}

pub fn audit_config(cfg: &Config) -> Vec<Finding> {
    let mut findings = Vec::new();

    if cfg.policy.allow_shell {
        findings.push(Finding {
            code: "policy_shell_enabled",
            severity: Severity::Info,
            title: "Shell execution is enabled",
            detail: "The exec tool can run host commands when invoked by the agent.".into(),
            remediation: Some(
                "Leave enabled only if this deployment is intended to be a full-computer agent."
                    .into(),
            ),
        });
    }

    if cfg.policy.allow_dynamic_tools {
        findings.push(Finding {
            code: "policy_dynamic_tools_enabled",
            severity: Severity::Warn,
            title: "Dynamic tool creation/execution is enabled",
            detail: "The agent can create and execute custom tools at runtime.".into(),
            remediation: Some("Disable policy.allow_dynamic_tools for deployments that do not need self-extending tools.".into()),
        });
    }

    if cfg.policy.allow_plugin_shell {
        findings.push(Finding {
            code: "policy_plugin_shell_enabled",
            severity: Severity::Warn,
            title: "Plugin shell execution is enabled",
            detail: "Plugins are allowed to spawn shell commands.".into(),
            remediation: Some(
                "Disable policy.allow_plugin_shell unless plugins are trusted.".into(),
            ),
        });
    }

    if cfg.policy.allow_plugin_git {
        findings.push(Finding {
            code: "policy_plugin_git_enabled",
            severity: Severity::Warn,
            title: "Plugin git execution is enabled",
            detail: "Plugins are allowed to run git operations directly.".into(),
            remediation: Some("Disable policy.allow_plugin_git unless plugins are trusted.".into()),
        });
    }

    if !Path::new(&cfg.workspace).exists() {
        findings.push(Finding {
            code: "workspace_missing",
            severity: Severity::Warn,
            title: "Configured workspace does not exist",
            detail: format!(
                "workspace=\"{}\" does not exist on disk.",
                cfg.workspace.display()
            ),
            remediation: Some(
                "Set workspace to an existing directory before starting the agent.".into(),
            ),
        });
    }

    if cfg.provider.api_key.is_none() && std::env::var("OPENAI_API_KEY").is_err() {
        findings.push(Finding {
            code: "provider_credentials_missing",
            severity: Severity::Warn,
            title: "No provider credentials detected",
            detail: "No API key is configured in the config or common environment variables."
                .into(),
            remediation: Some(
                "Set provider.api_key or export a provider API key before starting chat.".into(),
            ),
        });
    }

    findings
}

pub async fn collect_doctor_report(
    cfg: Option<&Config>,
    config_path: Option<&str>,
    verbose: bool,
) -> DoctorReport {
    let mut checks = Vec::new();
    if let Some(path) = config_path {
        checks.push(check_config_file(path));
    }
    let cfg = cfg.cloned().unwrap_or_else(|| {
        config_path
            .and_then(|path| Config::load(path).ok())
            .unwrap_or_else(Config::default_config)
    });

    for (bin, label) in [
        ("git", "Git"),
        ("cargo", "Rust toolchain"),
        ("ffmpeg", "FFmpeg"),
        ("docker", "Docker"),
        ("node", "Node.js"),
    ] {
        let found = check_cmd(bin).await;
        if found || verbose {
            checks.push(Check {
                name: label.to_string(),
                ok: found,
                detail: if found {
                    format!("{bin} is available")
                } else {
                    format!("{bin} is not on PATH")
                },
                soft_warn: false,
            });
        }
    }

    let workspace_exists = cfg.workspace.exists();
    checks.push(Check {
        name: "Workspace".into(),
        ok: workspace_exists,
        detail: cfg.workspace.display().to_string(),
        soft_warn: false,
    });

    let workspace_writable = workspace_exists && is_workspace_writable(&cfg.workspace);
    checks.push(Check {
        name: "Workspace writable".into(),
        ok: workspace_writable,
        detail: if !workspace_exists {
            "workspace does not exist".into()
        } else if workspace_writable {
            "workspace is writable".into()
        } else {
            "workspace is not writable".into()
        },
        soft_warn: false,
    });

    checks.push(local_bin_path_check());
    checks.push(shared_login_check());

    let provider_key_present =
        cfg.provider.api_key.is_some() || std::env::var("OPENAI_API_KEY").is_ok();
    checks.push(Check {
        name: "Provider credentials".into(),
        ok: provider_key_present,
        detail: if provider_key_present {
            "API credentials detected".into()
        } else {
            "No provider credentials detected".into()
        },
        soft_warn: false,
    });

    DoctorReport {
        findings: audit_config(&cfg),
        checks,
    }
}

pub fn render_findings(findings: &[Finding]) -> String {
    if findings.is_empty() {
        return "No audit findings.".into();
    }

    findings
        .iter()
        .map(|finding| {
            let severity = match finding.severity {
                Severity::Info => "INFO",
                Severity::Warn => "WARN",
                Severity::Critical => "CRITICAL",
            };
            match &finding.remediation {
                Some(remediation) => format!(
                    "[{severity}] {} ({})\n{}\nRemediation: {}",
                    finding.title, finding.code, finding.detail, remediation
                ),
                None => format!(
                    "[{severity}] {} ({})\n{}",
                    finding.title, finding.code, finding.detail
                ),
            }
        })
        .collect::<Vec<_>>()
        .join("\n\n")
}

pub fn render_doctor_report(report: &DoctorReport) -> String {
    let mut out = vec![
        "apollo doctor".to_string(),
        String::new(),
        "Checks:".to_string(),
    ];
    for check in &report.checks {
        let icon = if check.ok {
            "OK"
        } else if check.soft_warn {
            "WARN"
        } else {
            "FAIL"
        };
        out.push(format!("- [{icon}] {}: {}", check.name, check.detail));
    }
    out.push(String::new());
    out.push("Audit:".to_string());
    out.push(render_findings(&report.findings));
    out.join("\n")
}

pub(crate) fn check_config_file(path: &str) -> Check {
    let file = Path::new(path);
    if !file.exists() {
        return Check {
            name: "Config file".into(),
            ok: false,
            detail: format!("{path} not found"),
            soft_warn: false,
        };
    }
    match Config::load(path) {
        Ok(_) => Check {
            name: "Config file".into(),
            ok: true,
            detail: format!("{path} parses OK"),
            soft_warn: false,
        },
        Err(err) => Check {
            name: "Config file".into(),
            ok: false,
            detail: format!("{path} invalid: {err}"),
            soft_warn: false,
        },
    }
}

fn is_workspace_writable(path: &Path) -> bool {
    let probe = path.join(format!(".apollo-write-test-{}", std::process::id()));
    match std::fs::File::create(&probe) {
        Ok(_) => {
            let _ = std::fs::remove_file(probe);
            true
        }
        Err(_) => false,
    }
}

/// Which providers have a usable credential in the store shared with
/// telekinesis, so "am I logged in?" is answerable without guessing.
///
/// Reports provider names and expiry only — never a token.
#[cfg(feature = "rs-ai")]
fn shared_login_check() -> Check {
    let logins = crate::providers::shared_credentials::logins();
    if logins.is_empty() {
        return Check {
            name: "Shared login (rs_ai)".into(),
            ok: false,
            detail: "no provider logged in to the shared credential store".into(),
            soft_warn: true,
        };
    }

    let detail = logins
        .iter()
        .map(|login| match (login.expired, login.refreshable) {
            (false, _) => login.provider.to_string(),
            (true, true) => format!("{} (expired, refreshable)", login.provider),
            (true, false) => format!("{} (expired)", login.provider),
        })
        .collect::<Vec<_>>()
        .join(", ");

    // Expired-but-refreshable is a working login: the provider refreshes it on
    // first use. Only a dead, unrefreshable token means the user must log in
    // again.
    let usable = logins.iter().any(|l| !l.expired || l.refreshable);
    Check {
        name: "Shared login (rs_ai)".into(),
        ok: usable,
        detail,
        soft_warn: !usable,
    }
}

#[cfg(not(feature = "rs-ai"))]
fn shared_login_check() -> Check {
    Check {
        name: "Shared login (rs_ai)".into(),
        ok: false,
        detail: "built without the rs-ai feature".into(),
        soft_warn: true,
    }
}

fn local_bin_path_check() -> Check {
    let on_path = local_bin_on_path();
    Check {
        name: "~/.local/bin on PATH".into(),
        ok: on_path,
        detail: if on_path {
            "~/.local/bin is on PATH".into()
        } else {
            "~/.local/bin is not on PATH (optional)".into()
        },
        soft_warn: true,
    }
}

fn local_bin_on_path() -> bool {
    let Ok(home) = std::env::var("HOME") else {
        return false;
    };
    let local_bin = Path::new(&home).join(".local/bin");
    let Ok(path_env) = std::env::var("PATH") else {
        return false;
    };
    path_env
        .split(':')
        .any(|entry| Path::new(entry) == local_bin.as_path())
}

async fn check_cmd(cmd: &str) -> bool {
    tokio::process::Command::new("which")
        .arg(cmd)
        .output()
        .await
        .map(|output| output.status.success())
        .unwrap_or(false)
}

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

    #[test]
    fn render_doctor_report_marks_soft_warn_and_fail() {
        let report = DoctorReport {
            findings: vec![],
            checks: vec![
                Check {
                    name: "passing".into(),
                    ok: true,
                    detail: "all good".into(),
                    soft_warn: false,
                },
                Check {
                    name: "optional missing".into(),
                    ok: false,
                    detail: "not on PATH (optional)".into(),
                    soft_warn: true,
                },
                Check {
                    name: "required missing".into(),
                    ok: false,
                    detail: "not found".into(),
                    soft_warn: false,
                },
            ],
        };
        let rendered = render_doctor_report(&report);
        assert!(rendered.contains("- [OK] passing: all good"));
        assert!(rendered.contains("- [WARN] optional missing: not on PATH (optional)"));
        assert!(rendered.contains("- [FAIL] required missing: not found"));
    }

    #[test]
    fn check_config_file_reports_missing_path() {
        let path = "/tmp/apollo-doctor-missing-config-test-xyz123.json";
        let check = check_config_file(path);
        assert!(!check.ok);
        assert!(!check.soft_warn);
        assert_eq!(check.name, "Config file");
        assert!(check.detail.contains("not found"));
    }

    #[test]
    fn check_config_file_reports_valid_config() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("apollo.json");
        std::fs::write(&path, "{}").unwrap();
        let check = check_config_file(path.to_str().unwrap());
        assert!(check.ok);
        assert!(!check.soft_warn);
        assert!(check.detail.contains("parses OK"));
    }
}