mixtape-tools 0.4.0

Ready-to-use tool implementations for the mixtape agent framework
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
use crate::prelude::*;
use schemars::JsonSchema;
use serde::Deserialize;
use sysinfo::{ProcessesToUpdate, System};

/// Input for listing processes (no parameters needed)
#[derive(Debug, Deserialize, JsonSchema)]
pub struct ListProcessesInput {}

/// Tool for listing running processes
pub struct ListProcessesTool;

impl Tool for ListProcessesTool {
    type Input = ListProcessesInput;

    fn name(&self) -> &str {
        "list_processes"
    }

    fn description(&self) -> &str {
        "List all running processes on the system with their PID, name, CPU and memory usage."
    }

    async fn execute(&self, _input: Self::Input) -> std::result::Result<ToolResult, ToolError> {
        let mut sys = System::new();
        sys.refresh_processes(ProcessesToUpdate::All);

        let mut processes: Vec<_> = sys.processes().iter().collect();
        processes.sort_by_key(|(pid, _)| pid.as_u32());

        let mut output = String::from("PID     | NAME                          | CPU%  | MEMORY\n");
        output.push_str("--------|-------------------------------|-------|----------\n");

        for (pid, process) in processes.iter().take(50) {
            let name = process.name().to_string_lossy();
            let cpu = process.cpu_usage();
            let memory = process.memory();

            let memory_str = if memory < 1024 * 1024 {
                format!("{:.1} KB", memory as f64 / 1024.0)
            } else if memory < 1024 * 1024 * 1024 {
                format!("{:.1} MB", memory as f64 / (1024.0 * 1024.0))
            } else {
                format!("{:.1} GB", memory as f64 / (1024.0 * 1024.0 * 1024.0))
            };

            output.push_str(&format!(
                "{:<7} | {:<29} | {:>5.1} | {:>8}\n",
                pid.as_u32(),
                if name.len() > 29 {
                    format!("{}...", &name[..26])
                } else {
                    name.to_string()
                },
                cpu,
                memory_str
            ));
        }

        if processes.len() > 50 {
            output.push_str(&format!(
                "\n... and {} more processes\n",
                processes.len() - 50
            ));
        }

        Ok(output.into())
    }

    fn format_output_plain(&self, result: &ToolResult) -> String {
        result.as_text().to_string()
    }

    fn format_output_ansi(&self, result: &ToolResult) -> String {
        let output = result.as_text();
        let lines: Vec<&str> = output.lines().collect();
        if lines.len() < 3 {
            return output.to_string();
        }

        let mut out = String::new();
        out.push_str(&format!(
            "\x1b[1m{:>7}  {:<25}  {:>6}  {:>10}  {}\x1b[0m\n",
            "PID", "NAME", "CPU%", "MEMORY", "CPU"
        ));
        out.push_str(&format!("{}\n", "─".repeat(70)));

        for line in lines.iter().skip(2) {
            if line.starts_with("...") {
                out.push_str(&format!("\x1b[2m{}\x1b[0m\n", line));
                continue;
            }

            let parts: Vec<&str> = line.split('|').collect();
            if parts.len() >= 4 {
                let pid = parts[0].trim();
                let name = parts[1].trim();
                let cpu_str = parts[2].trim();
                let memory = parts[3].trim();
                let cpu: f32 = cpu_str.parse().unwrap_or(0.0);
                let color = resource_color(cpu);
                let bar = resource_bar(cpu.min(100.0), 10);

                out.push_str(&format!(
                    "\x1b[36m{:>7}\x1b[0m  {:<25}  {}{:>5.1}%\x1b[0m  {:>10}  {}{}\x1b[0m\n",
                    pid,
                    if name.len() > 25 { &name[..22] } else { name },
                    color,
                    cpu,
                    memory,
                    color,
                    bar
                ));
            }
        }
        out
    }

    fn format_output_markdown(&self, result: &ToolResult) -> String {
        let output = result.as_text();
        let lines: Vec<&str> = output.lines().collect();
        if lines.len() < 3 {
            return format!("```\n{}\n```", output);
        }

        let mut out =
            String::from("| PID | Name | CPU% | Memory |\n|-----|------|------|--------|\n");
        for line in lines.iter().skip(2) {
            if line.starts_with("...") {
                out.push_str(&format!("\n*{}*\n", line));
                continue;
            }
            let parts: Vec<&str> = line.split('|').collect();
            if parts.len() >= 4 {
                out.push_str(&format!(
                    "| {} | `{}` | {} | {} |\n",
                    parts[0].trim(),
                    parts[1].trim(),
                    parts[2].trim(),
                    parts[3].trim()
                ));
            }
        }
        out
    }
}

/// Create a visual bar for resource usage
fn resource_bar(percent: f32, width: usize) -> String {
    let filled = ((percent / 100.0) * width as f32).round() as usize;
    let empty = width.saturating_sub(filled);
    format!("[{}{}]", "â–ˆ".repeat(filled), "â–‘".repeat(empty))
}

/// Color code for resource usage (green → yellow → red)
fn resource_color(percent: f32) -> &'static str {
    if percent < 25.0 {
        "\x1b[32m"
    } else if percent < 50.0 {
        "\x1b[33m"
    } else if percent < 75.0 {
        "\x1b[38;5;208m"
    } else {
        "\x1b[31m"
    }
}

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

    #[tokio::test]
    async fn test_list_processes_basic() {
        let tool = ListProcessesTool;
        let input = ListProcessesInput {};

        let result = tool.execute(input).await;
        assert!(result.is_ok());

        let output = result.unwrap().as_text();
        // Should have headers
        assert!(output.contains("PID"));
        assert!(output.contains("NAME"));
        assert!(output.contains("CPU"));
        assert!(output.contains("MEMORY"));
    }

    #[tokio::test]
    async fn test_list_processes_contains_processes() {
        let tool = ListProcessesTool;
        let input = ListProcessesInput {};

        let result = tool.execute(input).await;
        assert!(result.is_ok());

        let output = result.unwrap().as_text();
        // Should have at least one process (this test process)
        let line_count = output.lines().count();
        assert!(line_count > 2); // More than just headers
    }

    #[tokio::test]
    async fn test_list_processes_memory_formatting() {
        let tool = ListProcessesTool;
        let input = ListProcessesInput {};

        let result = tool.execute(input).await;
        assert!(result.is_ok());

        let output = result.unwrap().as_text();
        // Should show memory units (KB, MB, or GB)
        assert!(
            output.contains("KB") || output.contains("MB") || output.contains("GB"),
            "Expected memory units in output"
        );
    }

    // ==================== resource_bar tests ====================

    #[test]
    fn test_resource_bar_zero() {
        let bar = resource_bar(0.0, 10);
        assert_eq!(bar, "[â–‘â–‘â–‘â–‘â–‘â–‘â–‘â–‘â–‘â–‘]");
    }

    #[test]
    fn test_resource_bar_half() {
        let bar = resource_bar(50.0, 10);
        assert_eq!(bar, "[█████░░░░░]");
    }

    #[test]
    fn test_resource_bar_full() {
        let bar = resource_bar(100.0, 10);
        assert_eq!(bar, "[██████████]");
    }

    #[test]
    fn test_resource_bar_quarter() {
        let bar = resource_bar(25.0, 10);
        // 25% of 10 = 2.5, rounded = 3 (or 2 depending on rounding)
        let filled_count = bar.chars().filter(|c| *c == 'â–ˆ').count();
        assert!((2..=3).contains(&filled_count));
    }

    #[test]
    fn test_resource_bar_different_width() {
        let bar = resource_bar(50.0, 20);
        let filled_count = bar.chars().filter(|c| *c == 'â–ˆ').count();
        assert_eq!(filled_count, 10); // 50% of 20
    }

    #[test]
    fn test_resource_bar_overflow() {
        // Values over 100 are NOT capped internally - caller is responsible for capping
        // (format_output_ansi calls resource_bar(cpu.min(100.0), 10))
        let bar = resource_bar(150.0, 10);
        let filled_count = bar.chars().filter(|c| *c == 'â–ˆ').count();
        assert_eq!(filled_count, 15); // 150% of 10 = 15
    }

    // ==================== resource_color tests ====================

    #[test]
    fn test_resource_color_low() {
        let color = resource_color(10.0);
        assert_eq!(color, "\x1b[32m"); // green
    }

    #[test]
    fn test_resource_color_medium_low() {
        let color = resource_color(30.0);
        assert_eq!(color, "\x1b[33m"); // yellow
    }

    #[test]
    fn test_resource_color_medium_high() {
        let color = resource_color(60.0);
        assert_eq!(color, "\x1b[38;5;208m"); // orange
    }

    #[test]
    fn test_resource_color_high() {
        let color = resource_color(80.0);
        assert_eq!(color, "\x1b[31m"); // red
    }

    #[test]
    fn test_resource_color_boundaries() {
        // Test boundary values
        assert_eq!(resource_color(0.0), "\x1b[32m"); // green at 0
        assert_eq!(resource_color(24.9), "\x1b[32m"); // green just under 25
        assert_eq!(resource_color(25.0), "\x1b[33m"); // yellow at 25
        assert_eq!(resource_color(49.9), "\x1b[33m"); // yellow just under 50
        assert_eq!(resource_color(50.0), "\x1b[38;5;208m"); // orange at 50
        assert_eq!(resource_color(74.9), "\x1b[38;5;208m"); // orange just under 75
        assert_eq!(resource_color(75.0), "\x1b[31m"); // red at 75
        assert_eq!(resource_color(100.0), "\x1b[31m"); // red at 100
    }

    // ==================== format_output tests ====================

    #[test]
    fn test_format_output_plain() {
        let tool = ListProcessesTool;
        let result: ToolResult = "PID     | NAME                          | CPU%  | MEMORY\n--------|-------------------------------|-------|----------\n1       | init                          |   0.0 |   10.0 MB".into();

        let formatted = tool.format_output_plain(&result);

        // Plain format should return the raw text
        assert!(formatted.contains("PID"));
        assert!(formatted.contains("init"));
    }

    #[test]
    fn test_format_output_ansi_basic() {
        let tool = ListProcessesTool;
        let result: ToolResult = "PID     | NAME                          | CPU%  | MEMORY\n--------|-------------------------------|-------|----------\n1       | init                          |   0.0 |   10.0 MB".into();

        let formatted = tool.format_output_ansi(&result);

        // Should have ANSI codes
        assert!(formatted.contains("\x1b["));
        assert!(formatted.contains("\x1b[1m")); // bold header
        assert!(formatted.contains("\x1b[36m")); // cyan for PID
    }

    #[test]
    fn test_format_output_ansi_cpu_colors() {
        let tool = ListProcessesTool;

        // Low CPU (green)
        let low_cpu: ToolResult = "PID     | NAME                          | CPU%  | MEMORY\n--------|-------------------------------|-------|----------\n1       | proc                          |   5.0 |   10.0 MB".into();
        let formatted = tool.format_output_ansi(&low_cpu);
        assert!(formatted.contains("\x1b[32m")); // green

        // High CPU (red)
        let high_cpu: ToolResult = "PID     | NAME                          | CPU%  | MEMORY\n--------|-------------------------------|-------|----------\n1       | proc                          |  80.0 |   10.0 MB".into();
        let formatted = tool.format_output_ansi(&high_cpu);
        assert!(formatted.contains("\x1b[31m")); // red
    }

    #[test]
    fn test_format_output_ansi_with_overflow_indicator() {
        let tool = ListProcessesTool;
        let result: ToolResult = "PID     | NAME                          | CPU%  | MEMORY\n--------|-------------------------------|-------|----------\n1       | proc                          |   5.0 |   10.0 MB\n... and 100 more processes".into();

        let formatted = tool.format_output_ansi(&result);

        // Overflow indicator should be dimmed
        assert!(formatted.contains("\x1b[2m")); // dim
        assert!(formatted.contains("more processes"));
    }

    #[test]
    fn test_format_output_markdown_basic() {
        let tool = ListProcessesTool;
        let result: ToolResult = "PID     | NAME                          | CPU%  | MEMORY\n--------|-------------------------------|-------|----------\n1       | init                          |   0.0 |   10.0 MB".into();

        let formatted = tool.format_output_markdown(&result);

        // Should have markdown table
        assert!(formatted.contains("| PID |"));
        assert!(formatted.contains("|-----|"));
        assert!(formatted.contains("`init`")); // name in code style
    }

    #[test]
    fn test_format_output_markdown_with_overflow() {
        let tool = ListProcessesTool;
        let result: ToolResult = "PID     | NAME                          | CPU%  | MEMORY\n--------|-------------------------------|-------|----------\n1       | proc                          |   5.0 |   10.0 MB\n... and 50 more processes".into();

        let formatted = tool.format_output_markdown(&result);

        // Overflow should be italicized
        assert!(formatted.contains("*... and 50 more processes*"));
    }

    #[test]
    fn test_format_output_markdown_short_input() {
        let tool = ListProcessesTool;
        let result: ToolResult = "short".into();

        let formatted = tool.format_output_markdown(&result);

        // Short input should be wrapped in code block
        assert!(formatted.contains("```"));
    }

    // ==================== Tool metadata tests ====================

    #[test]
    fn test_tool_name() {
        let tool = ListProcessesTool;
        assert_eq!(tool.name(), "list_processes");
    }

    #[test]
    fn test_tool_description() {
        let tool = ListProcessesTool;
        assert!(!tool.description().is_empty());
        assert!(tool.description().contains("process"));
    }
}