microagents-cli 0.1.0

Batteries-included terminal-based agent built on top of the microagents framework
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
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
use microagents_cli::init_env::root_or_cwd;
use microagents_core::types::{AgentError, ToolExecutionContext, ToolFunction};
use microagents_events::types::ToolResult;
use regex::Regex;
use serde_json::{Value, json};
use std::fs;
use std::io::Write;
#[cfg(unix)]
use std::os::unix::fs::PermissionsExt;
use std::path::Path;
use std::process::Stdio;
use std::sync::{Arc, OnceLock};
use std::time::Duration;

use tokio::process::Command;

use crate::init_env::{SUPPORTED_LIT_EXTENSIONS, parser};
use crate::processing::embed_query;
use crate::search::search as vector_search;

static DANGEROUS: OnceLock<Regex> = OnceLock::new();

fn dangerous_regex() -> &'static Regex {
    DANGEROUS.get_or_init(|| {
        Regex::new(
            r#"(?i)(?:
            \brm\s+-[rf]{1,2}
            |\bmkfs
            |\bdd\s+if=
            |\bshred\s+
            |\bwipefs\s+
            |\bchmod\s+[0-7]*7{2,}
            |\bchown\s+-R
            |\bsudo\s+
            |\bsu\s+
            |\bwget\s+\S+\s*\|\s*sh
            |\bcurl\s+\S+\s*\|\s*sh
            |\bnc\s+-e
            |\bbash\s+-i
            |\bpython[23]?\s+-c
            |\bperl\s+-e
            |\bshutdown\b
            |\breboot\b
            |\bhalt\b
            |\binit\s+0
            |\bkill\s+-9\s+-1
            |/etc/(?:passwd|shadow|sudoers)
            |(?:>|>>)\s*/dev/sd[a-z]
            |:\(\)\{.+\}
            |\brd\s+/s
            |\brmdir\s+/s
            |\bdel\s+/[fqs]
            |\bformat\s+[a-z]:
            |\bdiskpart\b
            |\bshutdown\s+/[rfs]
            |\btaskkill\s+/f
            |\bnet\s+(?:stop|user|localgroup)
            |\bsc\s+(?:delete|stop|create)
            |\breg\s+(?:delete|add|import|export)
            |\bwhoami\s+/priv
            |\bicacls\b
            |\battrib\s+[+-][rsah]
            |\bschtasks\s+/create
            |\bbcdedit\b
            |\bbootrec\b
            |[a-z]:\\(?:windows\\system32\\config\\(?:sam|system|security)|windows\\repair\\sam)
            |\bInvoke-Expression\b
            |\bIEX\b
            |\bInvoke-WebRequest\b.*\|\s*I(?:EX|nvoke-Expression)
            |\bDownloadString\b.*\|\s*I(?:EX|nvoke-Expression)
            |\bStart-Process\b
            |\bInvoke-Command\b
            |\bEncodedCommand\b
            |\bFromBase64String\b
            |\b-enc\b
            |\b-ex\s+bypass\b
            |\bExecutionPolicy\s+(?:bypass|unrestricted)
            |\bGet-Credential\b
            |\bDump-(?:Lsass|SAM)\b
            |\bAdd-MpPreference\b
            |\bSet-MpPreference\b
            |\bDisable-WindowsOptionalFeature\b
        )"#
            .replace('\n', "")
            .trim(),
        )
        .unwrap()
    })
}

fn is_dangerous(cmd: &str) -> bool {
    let re = dangerous_regex();

    re.is_match(cmd)
}

fn is_within_root(path: &Path) -> Result<bool, Box<dyn std::error::Error>> {
    let root = root_or_cwd()?;
    let canonical_root = root.canonicalize()?;
    let candidate = if path.is_absolute() {
        path.to_path_buf()
    } else {
        root.join(path)
    };

    // Walk up to the nearest existing ancestor, since `path` itself may not exist yet
    // (e.g., a new file or a directory that will be created by the tool).
    let mut ancestor = candidate.as_path();
    loop {
        if ancestor.exists() {
            let canonical_ancestor = ancestor.canonicalize()?;
            return Ok(canonical_ancestor.starts_with(&canonical_root));
        }
        match ancestor.parent() {
            Some(parent) => ancestor = parent,
            None => return Ok(false),
        }
    }
}

#[derive(Debug)]
pub struct SearchTool;

#[async_trait::async_trait]
impl ToolFunction<()> for SearchTool {
    fn name(&self) -> &'static str {
        "search"
    }

    fn description(&self) -> &'static str {
        "Semantically search across files in the workspace. Returns the most relevant chunks with their document path and similarity score."
    }

    fn input_schema(&self) -> Value {
        json!({
            "type": "object",
            "required": ["query"],
            "properties": {
                "query": {
                    "type": "string",
                    "description": "Natural-language query to search for in the indexed files."
                },
                "document_paths": {
                    "type": "array",
                    "items": { "type": "string" },
                    "description": "Optional list of document paths to restrict the search to."
                },
                "limit": {
                    "type": "integer",
                    "minimum": 1,
                    "description": "Maximum number of results to return (default 10)."
                },
                "score_threshold": {
                    "type": "number",
                    "description": "Optional minimum similarity score for returned results."
                }
            }
        })
    }

    async fn execute(
        &self,
        input: Value,
        _ctx: &Arc<ToolExecutionContext<()>>,
    ) -> Result<ToolResult, AgentError> {
        let query = match input["query"].as_str() {
            Some(q) => q.to_string(),
            None => {
                return Ok(ToolResult::Err(
                    "Missing required field 'query' in tool input".into(),
                ));
            }
        };
        let document_paths: Option<Vec<String>> = input["document_paths"].as_array().map(|arr| {
            arr.iter()
                .filter_map(|v| v.as_str().map(|s| s.to_string()))
                .collect()
        });
        let limit = input["limit"].as_u64().map(|l| l as usize);
        let score_threshold = input["score_threshold"].as_f64().map(|l| l as f32);

        let (embedding, sparse_embedding) = embed_query(&query);
        match vector_search(
            embedding,
            sparse_embedding,
            document_paths,
            limit,
            score_threshold,
        ) {
            Ok(results) => {
                let payload: Vec<Value> = results
                    .into_iter()
                    .map(|r| {
                        json!({
                            "document_path": r.document_path,
                            "content": r.content,
                            "score": r.score,
                        })
                    })
                    .collect();
                Ok(ToolResult::Ok(
                    serde_json::to_string_pretty(&payload).unwrap_or_else(|_| "[]".to_string()),
                ))
            }
            Err(e) => Ok(ToolResult::Err(format!("Search failed: {e}"))),
        }
    }
}

#[derive(Debug)]
pub struct ReadTool;

#[async_trait::async_trait]
impl ToolFunction<()> for ReadTool {
    fn name(&self) -> &'static str {
        "read"
    }

    fn description(&self) -> &'static str {
        "Read the contents of a file from the local filesystem. This tool also allows to extract the text content unstructured files (PDFs, Office documents, scanned images) through LiteParse."
    }

    fn input_schema(&self) -> Value {
        json!({
            "type": "object",
            "required": ["path"],
            "properties": {
                "path": {
                    "type": "string",
                    "description": "Path to the file to read."
                }
            }
        })
    }

    async fn execute(
        &self,
        input: Value,
        _ctx: &Arc<ToolExecutionContext<()>>,
    ) -> Result<ToolResult, AgentError> {
        let path = match input["path"].as_str() {
            Some(p) => p,
            None => {
                return Ok(ToolResult::Err(
                    "Missing required field 'path' in tool input".into(),
                ));
            }
        };
        let p = Path::new(path);
        let within_root =
            is_within_root(p).map_err(|e| AgentError::ToolCallError(e.to_string()))?;
        if !within_root {
            return Ok(ToolResult::Err(
                "Path does not appear to be within the current workspace or its root is non-resolvable".into(),
            ));
        }
        if SUPPORTED_LIT_EXTENSIONS.contains(
            &p.extension()
                .unwrap_or_default()
                .to_str()
                .map(|s| format!(".{}", s.to_lowercase()))
                .unwrap_or_default()
                .as_str(),
        ) {
            let result = parser().parse(path).await;
            match result {
                Ok(content) => return Ok(ToolResult::Ok(content.text)),
                Err(e) => return Ok(ToolResult::Err(format!("Failed to read {path}: {e}"))),
            }
        }
        match fs::read_to_string(path) {
            Ok(content) => Ok(ToolResult::Ok(content)),
            Err(e) => Ok(ToolResult::Err(format!("Failed to read {path}: {e}"))),
        }
    }
}

#[derive(Debug)]
pub struct WriteTool;

#[async_trait::async_trait]
impl ToolFunction<()> for WriteTool {
    fn name(&self) -> &'static str {
        "write"
    }

    fn description(&self) -> &'static str {
        "Write content to a file, creating it (and parent directories) if needed. Overwrites the file if it exists."
    }

    fn input_schema(&self) -> Value {
        json!({
            "type": "object",
            "required": ["path", "content"],
            "properties": {
                "path": {
                    "type": "string",
                    "description": "Path to the file to write."
                },
                "content": {
                    "type": "string",
                    "description": "Content to write to the file."
                }
            }
        })
    }

    async fn execute(
        &self,
        input: Value,
        _ctx: &Arc<ToolExecutionContext<()>>,
    ) -> Result<ToolResult, AgentError> {
        let path = match input["path"].as_str() {
            Some(p) => p,
            None => {
                return Ok(ToolResult::Err(
                    "Missing required field 'path' in tool input".into(),
                ));
            }
        };
        let p = Path::new(path);
        let within_root =
            is_within_root(p).map_err(|e| AgentError::ToolCallError(e.to_string()))?;
        if !within_root {
            return Ok(ToolResult::Err(
                "Path does not appear to be within the current workspace or its root is non-resolvable".into(),
            ));
        }
        let content = match input["content"].as_str() {
            Some(c) => c,
            None => {
                return Ok(ToolResult::Err(
                    "Missing required field 'content' in tool input".into(),
                ));
            }
        };
        if let Some(parent) = Path::new(path).parent()
            && !parent.as_os_str().is_empty()
            && let Err(e) = fs::create_dir_all(parent)
        {
            return Ok(ToolResult::Err(format!(
                "Failed to create parent directories for {path}: {e}"
            )));
        }
        match fs::write(path, content) {
            Ok(_) => Ok(ToolResult::Ok(format!(
                "Wrote {} bytes to {path}",
                content.len()
            ))),
            Err(e) => Ok(ToolResult::Err(format!("Failed to write {path}: {e}"))),
        }
    }
}

#[derive(Debug)]
pub struct EditTool;

#[async_trait::async_trait]
impl ToolFunction<()> for EditTool {
    fn name(&self) -> &'static str {
        "edit"
    }

    fn description(&self) -> &'static str {
        "Edit a file by replacing an exact occurrence of `old_str` with `new_str`. The `old_str` must match exactly once in the file."
    }

    fn input_schema(&self) -> Value {
        json!({
            "type": "object",
            "required": ["path", "old_str", "new_str"],
            "properties": {
                "path": {
                    "type": "string",
                    "description": "Path to the file to edit."
                },
                "old_str": {
                    "type": "string",
                    "description": "Exact string to find and replace. Must occur exactly once."
                },
                "new_str": {
                    "type": "string",
                    "description": "Replacement string."
                }
            }
        })
    }

    async fn execute(
        &self,
        input: Value,
        _ctx: &Arc<ToolExecutionContext<()>>,
    ) -> Result<ToolResult, AgentError> {
        let path = match input["path"].as_str() {
            Some(p) => p,
            None => {
                return Ok(ToolResult::Err("Missing required field 'path'".into()));
            }
        };
        let p = Path::new(path);
        let within_root =
            is_within_root(p).map_err(|e| AgentError::ToolCallError(e.to_string()))?;
        if !within_root {
            return Ok(ToolResult::Err(
                "Path does not appear to be within the current workspace or its root is non-resolvable".into(),
            ));
        }
        let old_str = match input["old_str"].as_str() {
            Some(s) => s,
            None => {
                return Ok(ToolResult::Err("Missing required field 'old_str'".into()));
            }
        };
        let new_str = match input["new_str"].as_str() {
            Some(s) => s,
            None => {
                return Ok(ToolResult::Err("Missing required field 'new_str'".into()));
            }
        };

        let content = match fs::read_to_string(path) {
            Ok(c) => c,
            Err(e) => return Ok(ToolResult::Err(format!("Failed to read {path}: {e}"))),
        };
        let occurrences = content.matches(old_str).count();
        if occurrences == 0 {
            return Ok(ToolResult::Err(format!("`old_str` not found in {path}")));
        }
        if occurrences > 1 {
            return Ok(ToolResult::Err(format!(
                "`old_str` matched {occurrences} times in {path}; it must be unique"
            )));
        }
        // Replace
        let updated = content.replacen(old_str, new_str, 1);

        // Atomic write — temp file in same dir so rename stays on same filesystem
        let parent = p.parent().unwrap_or(Path::new("."));
        let mut tmp = tempfile::NamedTempFile::new_in(parent)
            .map_err(|e| AgentError::ToolCallError(e.to_string()))?;
        tmp.write_all(updated.as_bytes())
            .map_err(|e| AgentError::ToolCallError(e.to_string()))?;

        // Preserve original permissions/metadata before overwriting
        if p.exists() {
            match fs::metadata(p) {
                Ok(meta) => {
                    #[cfg(unix)]
                    {
                        let mode = meta.permissions().mode();
                        let mut perms = fs::metadata(tmp.path())
                            .map(|m| m.permissions())
                            .unwrap_or_else(|_| std::fs::Permissions::from_mode(mode));
                        perms.set_mode(mode);
                        let _ = fs::set_permissions(tmp.path(), perms);
                    }
                    #[cfg(windows)]
                    {
                        let _ = fs::set_permissions(tmp.path(), meta.permissions());
                    }
                }
                Err(_) => { /* ignore metadata read errors */ }
            }
        }

        tmp.persist(p)
            .map_err(|e| AgentError::ToolCallError(e.to_string()))?;

        Ok(ToolResult::Ok(format!("Edited {path}")))
    }
}

#[derive(Debug)]
pub struct ShellExecuteTool;

#[async_trait::async_trait]
impl ToolFunction<()> for ShellExecuteTool {
    fn name(&self) -> &'static str {
        "shell_execute"
    }

    fn description(&self) -> &'static str {
        "Execute a shell command and return its stdout, stderr, and exit status. Supports Bash-compatible shells and Powershell."
    }

    fn input_schema(&self) -> Value {
        json!({
          "type": "object",
          "required": [
            "command"
          ],
          "properties": {
            "command": {
              "type": "string",
              "description": "Shell command to execute (run via `sh -c`)."
            },
            "cwd": {
              "type": "string",
              "description": "Optional working directory for the command."
            },
            "timeout": {
              "type": "integer",
              "description": "Command execution timeout in seconds (only integers allowed). Defaults to 60 seconds."
            }
          }
        })
    }

    async fn execute(
        &self,
        input: Value,
        _ctx: &Arc<ToolExecutionContext<()>>,
    ) -> Result<ToolResult, AgentError> {
        let command = match input["command"].as_str() {
            Some(c) => c,
            None => {
                return Ok(ToolResult::Err(
                    "Missing required field 'command' in tool input".into(),
                ));
            }
        };
        if is_dangerous(command) {
            return Ok(ToolResult::Err(
                "Dangerous command (`{command}`) detected and blocked".into(),
            ));
        }

        let mut cmd = if cfg!(target_os = "windows") {
            let mut c = Command::new("powershell");
            c.arg("-NoProfile").arg("-Command").arg(command);
            c
        } else {
            let mut c = Command::new("sh");
            c.arg("-c").arg(command);
            c
        };

        cmd.stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .kill_on_drop(true);
        if let Some(cwd) = input["cwd"].as_str() {
            cmd.current_dir(cwd);
        }
        let tim = input["timeout"].as_u64().unwrap_or(60);
        let res = tokio::time::timeout(Duration::from_secs(tim), cmd.output()).await;
        let out = match res {
            Ok(r) => r,
            Err(e) => {
                return Ok(ToolResult::Err(format!(
                    "Error while executing {command} with timeout: {e}"
                )));
            }
        };
        match out {
            Ok(output) => {
                let stdout = String::from_utf8_lossy(&output.stdout).to_string();
                let stderr = String::from_utf8_lossy(&output.stderr).to_string();
                let code = output.status.code();
                let payload = json!({
                    "exit_code": code,
                    "stdout": stdout,
                    "stderr": stderr,
                });
                let body =
                    serde_json::to_string_pretty(&payload).unwrap_or_else(|_| "{}".to_string());
                if output.status.success() {
                    Ok(ToolResult::Ok(body))
                } else {
                    Ok(ToolResult::Err(body))
                }
            }
            Err(e) => Ok(ToolResult::Err(format!(
                "Failed to spawn command `{command}`: {e}"
            ))),
        }
    }
}