1use serde_json::{json, Value};
2use anyhow::{Result, Context as _};
3use std::process::Command;
4use sysinfo::System;
5
6pub struct SilentModule {
7 system: System,
8}
9
10impl SilentModule {
11 pub fn new() -> Self {
12 Self {
13 system: System::new_all(),
14 }
15 }
16
17 pub fn get_tools(&self) -> Vec<Value> {
18 vec![
19 json!({
20 "name": "silent_script",
21 "description": "Execute bash scripts (silent scripting language)",
22 "inputSchema": {
23 "type": "object",
24 "properties": {
25 "script": {
26 "type": "string",
27 "description": "Bash script content to execute"
28 },
29 "args": {
30 "type": "array",
31 "items": {
32 "type": "string"
33 },
34 "description": "Arguments to pass to the script"
35 },
36 "cwd": {
37 "type": "string",
38 "description": "Working directory for script execution"
39 },
40 "env": {
41 "type": "object",
42 "description": "Environment variables to set"
43 },
44 "timeout": {
45 "type": "number",
46 "description": "Timeout in seconds (default: 300)"
47 }
48 },
49 "required": ["script"]
50 }
51 }),
52 json!({
53 "name": "silent_resources",
54 "description": "Monitor system resources (GPU/RAM/CPU usage)",
55 "inputSchema": {
56 "type": "object",
57 "properties": {
58 "detailed": {
59 "type": "boolean",
60 "description": "Include detailed per-process information"
61 },
62 "process_filter": {
63 "type": "string",
64 "description": "Filter processes by name"
65 }
66 }
67 }
68 }),
69 ]
70 }
71
72 pub async fn script(&self, args: Value) -> Result<Value> {
73 let script = args["script"].as_str().context("Missing 'script' parameter")?;
74 let script_args = args["args"].as_array().map(|arr| {
75 arr.iter()
76 .filter_map(|v| v.as_str())
77 .map(|s| s.to_string())
78 .collect::<Vec<_>>()
79 }).unwrap_or_default();
80
81 let cwd = args["cwd"].as_str();
82 let timeout_secs = args["timeout"].as_u64().unwrap_or(300);
83
84 let temp_dir = std::env::temp_dir();
86 let script_id = uuid::Uuid::new_v4();
87 let script_path = temp_dir.join(format!("silent_script_{}.sh", script_id));
88
89 std::fs::write(&script_path, script)
90 .context("Failed to write script to temp file")?;
91
92 #[cfg(unix)]
94 {
95 use std::os::unix::fs::PermissionsExt;
96 let mut perms = std::fs::metadata(&script_path)?.permissions();
97 perms.set_mode(0o755);
98 std::fs::set_permissions(&script_path, perms)?;
99 }
100
101 let mut cmd = tokio::process::Command::new("bash");
103 cmd.arg(&script_path);
104
105 for arg in script_args {
106 cmd.arg(arg);
107 }
108
109 if let Some(dir) = cwd {
110 cmd.current_dir(dir);
111 }
112
113 if let Some(env_obj) = args["env"].as_object() {
114 for (key, value) in env_obj {
115 if let Some(val_str) = value.as_str() {
116 cmd.env(key, val_str);
117 }
118 }
119 }
120
121 let start = std::time::Instant::now();
123 let timeout_dur = tokio::time::Duration::from_secs(timeout_secs);
124
125 let result = tokio::time::timeout(timeout_dur, cmd.output()).await;
126 let duration = start.elapsed();
127
128 let _ = std::fs::remove_file(&script_path);
130
131 match result {
132 Ok(Ok(output)) => {
133 let stdout = String::from_utf8_lossy(&output.stdout).to_string();
134 let stderr = String::from_utf8_lossy(&output.stderr).to_string();
135
136 Ok(json!({
137 "success": output.status.success(),
138 "exit_code": output.status.code(),
139 "stdout": stdout,
140 "stderr": stderr,
141 "duration_ms": duration.as_millis(),
142 "timed_out": false
143 }))
144 }
145 Ok(Err(e)) => {
146 Err(anyhow::anyhow!("Failed to execute script: {}", e))
147 }
148 Err(_) => {
149 Ok(json!({
150 "success": false,
151 "exit_code": null,
152 "stdout": "",
153 "stderr": format!("Script timed out after {} seconds", timeout_secs),
154 "duration_ms": duration.as_millis(),
155 "timed_out": true
156 }))
157 }
158 }
159 }
160
161 pub async fn resources(&mut self, args: Value) -> Result<Value> {
162 let detailed = args["detailed"].as_bool().unwrap_or(false);
163 let process_filter = args["process_filter"].as_str();
164
165 self.system.refresh_all();
167
168 let mut cpu_usage = Vec::new();
170 for cpu in self.system.cpus() {
171 cpu_usage.push(json!({
172 "name": cpu.name(),
173 "usage": cpu.cpu_usage(),
174 "frequency": cpu.frequency()
175 }));
176 }
177
178 let global_cpu_usage = self.system.global_cpu_info().cpu_usage();
179
180 let total_memory = self.system.total_memory();
182 let used_memory = self.system.used_memory();
183 let available_memory = self.system.available_memory();
184 let memory_usage_percent = (used_memory as f64 / total_memory as f64) * 100.0;
185
186 let total_swap = self.system.total_swap();
188 let used_swap = self.system.used_swap();
189 let swap_usage_percent = if total_swap > 0 {
190 (used_swap as f64 / total_swap as f64) * 100.0
191 } else {
192 0.0
193 };
194
195 let gpu_info = self.get_gpu_info();
197
198 let mut result = json!({
199 "cpu": {
200 "global_usage": global_cpu_usage,
201 "cores": cpu_usage,
202 "core_count": self.system.cpus().len()
203 },
204 "memory": {
205 "total_bytes": total_memory,
206 "used_bytes": used_memory,
207 "available_bytes": available_memory,
208 "usage_percent": memory_usage_percent,
209 "total_gb": total_memory as f64 / 1024.0 / 1024.0 / 1024.0,
210 "used_gb": used_memory as f64 / 1024.0 / 1024.0 / 1024.0
211 },
212 "swap": {
213 "total_bytes": total_swap,
214 "used_bytes": used_swap,
215 "usage_percent": swap_usage_percent
216 },
217 "gpu": gpu_info
218 });
219
220 if detailed {
222 let mut processes = Vec::new();
223
224 for (pid, process) in self.system.processes() {
225 let name = process.name();
226
227 if let Some(filter) = process_filter {
229 if !name.contains(filter) {
230 continue;
231 }
232 }
233
234 processes.push(json!({
235 "pid": pid.as_u32(),
236 "name": name,
237 "cpu_usage": process.cpu_usage(),
238 "memory_bytes": process.memory(),
239 "memory_mb": process.memory() as f64 / 1024.0 / 1024.0,
240 "disk_usage": {
241 "read_bytes": process.disk_usage().read_bytes,
242 "written_bytes": process.disk_usage().written_bytes
243 }
244 }));
245 }
246
247 processes.sort_by(|a, b| {
249 b["cpu_usage"].as_f64().unwrap_or(0.0)
250 .partial_cmp(&a["cpu_usage"].as_f64().unwrap_or(0.0))
251 .unwrap_or(std::cmp::Ordering::Equal)
252 });
253
254 result["processes"] = json!(processes);
255 result["process_count"] = json!(processes.len());
256 }
257
258 Ok(result)
259 }
260
261 fn get_gpu_info(&self) -> Value {
262 if let Ok(output) = Command::new("nvidia-smi")
264 .args(&[
265 "--query-gpu=index,name,temperature.gpu,utilization.gpu,utilization.memory,memory.total,memory.used,memory.free",
266 "--format=csv,noheader,nounits"
267 ])
268 .output()
269 {
270 if output.status.success() {
271 let stdout = String::from_utf8_lossy(&output.stdout);
272 let mut gpus = Vec::new();
273
274 for line in stdout.lines() {
275 let parts: Vec<&str> = line.split(',').map(|s| s.trim()).collect();
276 if parts.len() >= 8 {
277 gpus.push(json!({
278 "index": parts[0].parse::<u32>().ok(),
279 "name": parts[1],
280 "temperature": parts[2].parse::<f64>().ok(),
281 "utilization_gpu": parts[3].parse::<f64>().ok(),
282 "utilization_memory": parts[4].parse::<f64>().ok(),
283 "memory_total_mb": parts[5].parse::<u64>().ok(),
284 "memory_used_mb": parts[6].parse::<u64>().ok(),
285 "memory_free_mb": parts[7].parse::<u64>().ok()
286 }));
287 }
288 }
289
290 if !gpus.is_empty() {
291 return json!({
292 "available": true,
293 "count": gpus.len(),
294 "devices": gpus
295 });
296 }
297 }
298 }
299
300 json!({
302 "available": false,
303 "message": "No GPU information available (nvidia-smi not found or failed)"
304 })
305 }
306}