Skip to main content

aidaemon_tools/
check_environment.rs

1use async_trait::async_trait;
2use serde_json::{Value, json};
3
4use crate::OutcomeTool as Tool;
5use crate::backend::SharedExecutionBackend;
6use crate::semantics::{ToolCapabilities, ToolRole};
7use crate::{BackendPath, ExecutionRequest};
8
9/// Where the daemon's process says its config file is.
10pub const RUNTIME_CONFIG_PATH_ENV_KEY: &str = "AIDAEMON_RUNTIME_CONFIG_PATH";
11/// Where the daemon's process says its env file is.
12pub const RUNTIME_ENV_FILE_ENV_KEY: &str = "AIDAEMON_RUNTIME_ENV_FILE";
13/// The daemon's working directory.
14pub const RUNTIME_WORKDIR_ENV_KEY: &str = "AIDAEMON_RUNTIME_WORKDIR";
15
16pub struct CheckEnvironmentTool {
17    backend: SharedExecutionBackend,
18}
19
20impl CheckEnvironmentTool {
21    pub fn new(backend: SharedExecutionBackend) -> Self {
22        Self { backend }
23    }
24}
25
26/// Runtimes/tools to check with their version flags.
27const TOOLS_TO_CHECK: &[(&str, &str)] = &[
28    ("rustc", "--version"),
29    ("cargo", "--version"),
30    ("node", "--version"),
31    ("npm", "--version"),
32    ("npx", "--version"),
33    ("bun", "--version"),
34    ("deno", "--version"),
35    ("python3", "--version"),
36    ("python", "--version"),
37    ("pip3", "--version"),
38    ("pip", "--version"),
39    ("go", "version"),
40    ("java", "-version"),
41    ("javac", "-version"),
42    ("ruby", "--version"),
43    ("php", "--version"),
44    ("docker", "--version"),
45    ("docker-compose", "--version"),
46    ("git", "--version"),
47    ("make", "--version"),
48    ("cmake", "--version"),
49    ("gcc", "--version"),
50    ("g++", "--version"),
51    ("clang", "--version"),
52];
53
54/// Config files to look for.
55const CONFIG_FILES: &[(&str, &str)] = &[
56    (".nvmrc", "Node version"),
57    (".node-version", "Node version"),
58    (".python-version", "Python version"),
59    (".ruby-version", "Ruby version"),
60    (".tool-versions", "asdf versions"),
61    ("Dockerfile", "Docker"),
62    ("docker-compose.yml", "Docker Compose"),
63    ("docker-compose.yaml", "Docker Compose"),
64    (".env", "Environment variables"),
65    (".env.local", "Local environment"),
66    ("rust-toolchain.toml", "Rust toolchain"),
67    ("rust-toolchain", "Rust toolchain"),
68    (".editorconfig", "Editor config"),
69    (".prettierrc", "Prettier"),
70    (".eslintrc.json", "ESLint"),
71    ("tsconfig.json", "TypeScript"),
72];
73
74#[async_trait]
75impl Tool for CheckEnvironmentTool {
76    fn name(&self) -> &str {
77        "check_environment"
78    }
79
80    fn description(&self) -> &str {
81        "Check which development tools and runtimes are available, their versions, and what config files exist. Use this instead of running multiple 'which' and '--version' commands."
82    }
83
84    fn schema(&self) -> Value {
85        json!({
86            "name": "check_environment",
87            "description": self.description(),
88            "parameters": {
89                "type": "object",
90                "properties": {
91                    "path": {
92                        "type": "string",
93                        "description": "Directory to check for config files (default: current directory)"
94                    }
95                },
96                "additionalProperties": false
97            }
98        })
99    }
100
101    async fn execute(
102        &self,
103        arguments: &str,
104        _facts: &crate::semantics::ToolCallContext,
105    ) -> anyhow::Result<crate::semantics::ToolCallOutcome> {
106        let output: anyhow::Result<String> = async move {
107            let args: Value = serde_json::from_str(arguments)?;
108            let path_str = args["path"].as_str().unwrap_or(".");
109            let backend = self.backend.clone();
110            let check_dir = backend.resolve_path(path_str).await?;
111
112            let mut output = String::new();
113            output.push_str("## Execution Environment\n\n");
114            output.push_str(&format!(
115                "  Backend             {} ({})\n  Workspace           {}\n\n",
116                backend.kind().as_str(),
117                backend.id(),
118                backend.workspace_root()
119            ));
120
121            if let Some(runtime_context) = format_daemon_runtime_context(std::env::var) {
122                output.push_str("## Local Daemon Control Plane\n\n");
123                output.push_str(&runtime_context);
124                output.push('\n');
125            }
126
127            // Check tools in parallel
128            output.push_str("## Available Tools\n\n");
129
130            let mut handles = Vec::new();
131            for (tool, flag) in TOOLS_TO_CHECK {
132                let tool = tool.to_string();
133                let flag = flag.to_string();
134                let backend = backend.clone();
135                handles.push(tokio::spawn(async move {
136                    check_tool(backend, &tool, &flag).await
137                }));
138            }
139
140            let results = futures::future::join_all(handles).await;
141            let mut found = Vec::new();
142            let mut not_found = Vec::new();
143
144            for (i, result) in results.into_iter().enumerate() {
145                let (tool_name, _) = TOOLS_TO_CHECK[i];
146                match result {
147                    Ok(Some((path, version))) => found.push((tool_name, path, version)),
148                    Ok(None) => not_found.push(tool_name),
149                    Err(_) => not_found.push(tool_name),
150                }
151            }
152
153            for (name, path, version) in &found {
154                output.push_str(&format!(
155                    "  {} {}\n    path: {}\n",
156                    pad_right(name, 18),
157                    version,
158                    path
159                ));
160            }
161
162            if !not_found.is_empty() {
163                output.push_str(&format!("\nNot found: {}\n", not_found.join(", ")));
164            }
165
166            // Check config files
167            let configs = check_config_files(backend, &check_dir).await;
168            if !configs.is_empty() {
169                output.push_str("\n## Config Files\n\n");
170                for (file, desc, content) in &configs {
171                    output.push_str(&format!("  {} ({})", file, desc));
172                    if let Some(c) = content {
173                        output.push_str(&format!(" → {}", c));
174                    }
175                    output.push('\n');
176                }
177            }
178
179            Ok(output)
180        }
181        .await;
182        output.map(crate::semantics::ToolCallOutcome::from_output)
183    }
184}
185
186impl crate::semantics::ToolSemantics for CheckEnvironmentTool {
187    fn dispatch_facts(&self) -> crate::semantics::ToolDispatchFacts {
188        crate::semantics::ToolDispatchFacts {
189            same_tool_streak: crate::semantics::SameToolStreak::Versatile,
190            project_dir_argument: crate::semantics::ProjectDirArgument::SearchRoot,
191            evidence: crate::semantics::EvidenceSource::HostInfo,
192            semantic_scope: Some(crate::semantics::ToolSemanticScope::HostLocal),
193            low_signal_result: true,
194            ..Default::default()
195        }
196    }
197
198    fn tool_role(&self) -> ToolRole {
199        ToolRole::Universal
200    }
201
202    fn capabilities(&self) -> ToolCapabilities {
203        ToolCapabilities::READ_ONLY
204    }
205}
206
207fn pad_right(s: &str, width: usize) -> String {
208    if s.len() >= width {
209        s.to_string()
210    } else {
211        format!("{}{}", s, " ".repeat(width - s.len()))
212    }
213}
214
215fn format_daemon_runtime_context<F>(mut lookup: F) -> Option<String>
216where
217    F: FnMut(&'static str) -> Result<String, std::env::VarError>,
218{
219    let mut lines = Vec::new();
220
221    if let Ok(workdir) = lookup(RUNTIME_WORKDIR_ENV_KEY)
222        && !workdir.trim().is_empty()
223    {
224        lines.push(format!("  Working dir         {}", workdir));
225    }
226
227    if let Ok(config_path) = lookup(RUNTIME_CONFIG_PATH_ENV_KEY)
228        && !config_path.trim().is_empty()
229    {
230        lines.push(format!("  Config path         {}", config_path));
231    }
232
233    if let Ok(env_path) = lookup(RUNTIME_ENV_FILE_ENV_KEY)
234        && !env_path.trim().is_empty()
235    {
236        lines.push(format!("  Env file            {}", env_path));
237    }
238
239    let secret_backend = match lookup("AIDAEMON_NO_KEYCHAIN") {
240        Ok(v) if v == "1" || v.eq_ignore_ascii_case("true") => Some("env-file / environment"),
241        _ => Some("OS keychain"),
242    };
243    if let Some(backend) = secret_backend {
244        lines.push(format!("  Secret backend      {}", backend));
245    }
246
247    if lines.is_empty() {
248        None
249    } else {
250        Some(format!("{}\n", lines.join("\n")))
251    }
252}
253
254async fn check_tool(
255    backend: SharedExecutionBackend,
256    name: &str,
257    flag: &str,
258) -> Option<(String, String)> {
259    let executable = backend.resolve_executable(name).await.ok()??;
260    let request = ExecutionRequest::argv(executable.as_str(), vec![flag.to_string()]);
261    match backend
262        .execute(request, std::time::Duration::from_secs(5))
263        .await
264    {
265        Ok(out) => {
266            if out.exit_code == 0 {
267                // Some tools output to stderr (java -version)
268                let stdout = out.stdout_lossy();
269                let stderr = out.stderr_lossy();
270                let version_str = if stdout.trim().is_empty() {
271                    stderr.trim().to_string()
272                } else {
273                    stdout.trim().to_string()
274                };
275                // Take first line only
276                Some((
277                    executable.to_string(),
278                    version_str
279                        .lines()
280                        .next()
281                        .unwrap_or(&version_str)
282                        .to_string(),
283                ))
284            } else {
285                Some((
286                    executable.to_string(),
287                    "(installed, version unknown)".to_string(),
288                ))
289            }
290        }
291        Err(_) => Some((
292            executable.to_string(),
293            "(installed, version check timed out)".to_string(),
294        )),
295    }
296}
297
298async fn check_config_files(
299    backend: SharedExecutionBackend,
300    dir: &BackendPath,
301) -> Vec<(String, String, Option<String>)> {
302    let mut configs = Vec::new();
303
304    for (file, desc) in CONFIG_FILES {
305        let path = dir.join(file);
306        if backend.metadata(&path).await.is_ok() {
307            // Read small config files for their content
308            let content = if *file == ".nvmrc"
309                || *file == ".node-version"
310                || *file == ".python-version"
311                || *file == ".ruby-version"
312                || *file == "rust-toolchain"
313            {
314                backend
315                    .read(&path)
316                    .await
317                    .ok()
318                    .and_then(|bytes| String::from_utf8(bytes).ok())
319                    .map(|content| content.trim().to_string())
320            } else {
321                None
322            };
323            configs.push((file.to_string(), desc.to_string(), content));
324        }
325    }
326
327    configs
328}
329
330#[cfg(test)]
331mod tests {
332    use super::*;
333    use crate::testing::ToolCalls as _;
334
335    #[test]
336    fn test_format_daemon_runtime_context() {
337        let vars = std::collections::HashMap::from([
338            (
339                RUNTIME_WORKDIR_ENV_KEY.to_string(),
340                "/daemon/root".to_string(),
341            ),
342            (
343                RUNTIME_CONFIG_PATH_ENV_KEY.to_string(),
344                "/daemon/root/config.toml".to_string(),
345            ),
346            (
347                RUNTIME_ENV_FILE_ENV_KEY.to_string(),
348                "/daemon/root/.env".to_string(),
349            ),
350            ("AIDAEMON_NO_KEYCHAIN".to_string(), "1".to_string()),
351        ]);
352
353        let rendered = format_daemon_runtime_context(|key| {
354            vars.get(key).cloned().ok_or(std::env::VarError::NotPresent)
355        })
356        .expect("runtime context");
357
358        assert!(rendered.contains("/daemon/root"));
359        assert!(rendered.contains("/daemon/root/config.toml"));
360        assert!(rendered.contains("/daemon/root/.env"));
361        assert!(rendered.contains("env-file / environment"));
362    }
363
364    #[test]
365    fn test_pad_right() {
366        assert_eq!(pad_right("git", 10), "git       ");
367        assert_eq!(pad_right("docker-compose", 10), "docker-compose");
368    }
369
370    #[test]
371    fn test_schema_has_required_fields() {
372        let tool = CheckEnvironmentTool::new(crate::testing::active_execution_backend());
373        let schema = tool.schema();
374        assert_eq!(schema["name"], "check_environment");
375        assert!(!schema["description"].as_str().unwrap().is_empty());
376    }
377
378    #[tokio::test]
379    async fn test_check_environment_runs() {
380        let args = json!({}).to_string();
381        let result = CheckEnvironmentTool::new(crate::testing::active_execution_backend())
382            .call(&args)
383            .await
384            .unwrap();
385        // Should at least find git (we're in a git repo)
386        assert!(result.contains("Available Tools"));
387    }
388
389    #[tokio::test]
390    async fn test_check_environment_with_config_files() {
391        let dir = tempfile::tempdir().unwrap();
392        std::fs::write(dir.path().join(".nvmrc"), "18.17.0").unwrap();
393        std::fs::write(dir.path().join("Dockerfile"), "FROM node:18").unwrap();
394
395        let args = json!({"path": dir.path().to_str().unwrap()}).to_string();
396        let result = CheckEnvironmentTool::new(crate::testing::active_execution_backend())
397            .call(&args)
398            .await
399            .unwrap();
400        assert!(result.contains(".nvmrc"));
401        assert!(result.contains("18.17.0"));
402        assert!(result.contains("Dockerfile"));
403    }
404
405    #[tokio::test]
406    async fn test_check_tool_git() {
407        let result = check_tool(
408            crate::testing::active_execution_backend(),
409            "git",
410            "--version",
411        )
412        .await;
413        assert!(result.is_some());
414        let (path, version) = result.unwrap();
415        assert!(path.contains("git"));
416        assert!(version.contains("git"));
417    }
418
419    #[tokio::test]
420    async fn test_check_tool_nonexistent() {
421        let result = check_tool(
422            crate::testing::active_execution_backend(),
423            "nonexistent_tool_xyz_12345",
424            "--version",
425        )
426        .await;
427        assert!(result.is_none());
428    }
429}