sofos 0.1.21

An interactive AI coding agent for your terminal
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
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
pub mod bashexec;
pub mod codesearch;
pub mod filesystem;
pub mod image;
pub mod permissions;
pub mod tool_name;
pub mod types;
mod utils;

use crate::api::MorphClient;
use crate::error::{Result, SofosError};
use crate::mcp::McpManager;
use crate::ui::diff;
use bashexec::BashExecutor;
use codesearch::CodeSearchTool;
use filesystem::FileSystemTool;
use permissions::PermissionManager;
use serde_json::Value;
use tool_name::ToolName;

use crate::tools::types::get_read_only_tools;
use crate::tools::utils::confirm_destructive;
pub use types::{add_code_search_tool, get_all_tools, get_all_tools_with_morph};

// Re-export MCP tool result types for use in response handler
pub use crate::mcp::manager::{ImageData, ToolResult as McpToolResult};

/// Result from tool execution that can contain text and/or images
#[derive(Debug, Clone)]
pub enum ToolExecutionResult {
    /// Simple text result (for most tools)
    Text(String),
    /// Structured result with optional images (for MCP tools)
    Structured(McpToolResult),
}

impl ToolExecutionResult {
    /// Get the text content
    pub fn text(&self) -> &str {
        match self {
            ToolExecutionResult::Text(s) => s,
            ToolExecutionResult::Structured(r) => &r.text,
        }
    }

    /// Check if this result has images
    #[allow(dead_code)]
    pub fn has_images(&self) -> bool {
        match self {
            ToolExecutionResult::Text(_) => false,
            ToolExecutionResult::Structured(r) => !r.images.is_empty(),
        }
    }

    /// Get images if any
    pub fn images(&self) -> &[ImageData] {
        match self {
            ToolExecutionResult::Text(_) => &[],
            ToolExecutionResult::Structured(r) => &r.images,
        }
    }
}

#[cfg(test)]
mod tests;

/// ToolExecutor handles execution of tool calls from AI
#[derive(Clone)]
pub struct ToolExecutor {
    fs_tool: FileSystemTool,
    code_search_tool: Option<CodeSearchTool>,
    bash_executor: BashExecutor,
    morph_client: Option<MorphClient>,
    mcp_manager: Option<McpManager>,
    safe_mode: bool,
}

impl ToolExecutor {
    pub fn new(
        workspace: std::path::PathBuf,
        morph_client: Option<MorphClient>,
        mcp_manager: Option<McpManager>,
        safe_mode: bool,
    ) -> Result<Self> {
        let code_search_tool = match CodeSearchTool::new(workspace.clone()) {
            Ok(tool) => Some(tool),
            Err(_) => {
                crate::ui::UI::print_warning("ripgrep not found. Code search will be unavailable.");
                None
            }
        };

        Ok(Self {
            fs_tool: FileSystemTool::new(workspace.clone())?,
            code_search_tool,
            bash_executor: BashExecutor::new(workspace)?,
            morph_client,
            mcp_manager,
            safe_mode,
        })
    }

    pub fn has_morph(&self) -> bool {
        self.morph_client.is_some()
    }

    pub fn has_code_search(&self) -> bool {
        self.code_search_tool.is_some()
    }

    pub fn set_safe_mode(&mut self, safe_mode: bool) {
        self.safe_mode = safe_mode;
    }

    pub async fn get_available_tools(&self) -> Vec<crate::api::Tool> {
        let mut tools = if self.safe_mode {
            get_read_only_tools()
        } else if self.has_morph() {
            get_all_tools_with_morph()
        } else {
            get_all_tools()
        };

        if self.has_code_search() {
            add_code_search_tool(&mut tools);
        }

        if let Some(mcp_manager) = &self.mcp_manager {
            if let Ok(mcp_tools) = mcp_manager.get_all_tools().await {
                tools.extend(mcp_tools);
            }
        }

        tools
    }

    pub async fn execute(&self, tool_name: &str, input: &Value) -> Result<ToolExecutionResult> {
        // Check if this is an MCP tool first
        if let Some(mcp_manager) = &self.mcp_manager {
            if mcp_manager.is_mcp_tool(tool_name).await {
                let result = mcp_manager.execute_tool(tool_name, input).await?;
                return Ok(ToolExecutionResult::Structured(result));
            }
        }

        let tool = ToolName::from_str(tool_name)?;

        let text_result = match tool {
            ToolName::ReadFile => {
                let path = input["path"].as_str().ok_or_else(|| {
                    SofosError::ToolExecution("Missing 'path' parameter".to_string())
                })?;

                let permission_manager =
                    PermissionManager::new(self.fs_tool._workspace().to_path_buf())?;

                // Canonicalize to resolve symlinks and normalize relative paths
                let full_path = if path.starts_with('/') || path.starts_with('~') {
                    std::path::PathBuf::from(permissions::PermissionManager::expand_tilde_pub(path))
                } else {
                    self.fs_tool._workspace().join(path)
                };

                let canonical = match std::fs::canonicalize(&full_path) {
                    Ok(p) => p,
                    Err(_) => {
                        let parent_dir = std::path::Path::new(path)
                            .parent()
                            .and_then(|p| p.to_str())
                            .unwrap_or(".");
                        return Err(SofosError::ToolExecution(format!(
                            "File not found: '{}'. Suggestion: Use list_directory with path '{}' to see available files.",
                            path, parent_dir
                        )));
                    }
                };

                let is_inside_workspace = canonical.starts_with(self.fs_tool._workspace());
                let canonical_str = canonical.to_str().unwrap_or(path);

                // Check permissions on both original and canonical forms
                let (perm_original, matched_rule_original) =
                    permission_manager.check_read_permission_with_source(path);
                let (perm_canonical, matched_rule_canonical) =
                    permission_manager.check_read_permission_with_source(canonical_str);

                // Use the denied result if either check failed
                let (final_perm, matched_rule) =
                    if perm_original == permissions::CommandPermission::Denied {
                        (perm_original, matched_rule_original)
                    } else if perm_canonical == permissions::CommandPermission::Denied {
                        (perm_canonical, matched_rule_canonical)
                    } else if perm_original == permissions::CommandPermission::Ask {
                        (perm_original, None)
                    } else if perm_canonical == permissions::CommandPermission::Ask {
                        (perm_canonical, None)
                    } else {
                        (permissions::CommandPermission::Allowed, None)
                    };

                match final_perm {
                    permissions::CommandPermission::Denied => {
                        let config_source = if let Some(ref rule) = matched_rule {
                            permission_manager.get_rule_source(rule)
                        } else {
                            ".sofos/config.local.toml or ~/.sofos/config.toml".to_string()
                        };
                        return Err(SofosError::ToolExecution(format!(
                            "Read access denied for path '{}'\n\
                             Hint: Blocked by deny rule in {}",
                            path, config_source
                        )));
                    }
                    permissions::CommandPermission::Ask => {
                        return Err(SofosError::ToolExecution(format!(
                            "Path '{}' is in 'ask' list\n\
                             Hint: 'ask' only works for Bash commands. Use 'allow' or 'deny' for Read permissions.",
                            path
                        )));
                    }
                    permissions::CommandPermission::Allowed => {}
                }

                let is_explicit_allow =
                    permission_manager.is_read_explicit_allow_both_forms(path, canonical_str);

                if !is_inside_workspace && !is_explicit_allow {
                    return Err(SofosError::ToolExecution(format!(
                        "Path '{}' is outside workspace and not explicitly allowed\n\
                         Hint: Add Read({}) to 'allow' list in .sofos/config.local.toml",
                        path, path
                    )));
                }

                if is_inside_workspace {
                    match self.fs_tool.read_file(path) {
                        Ok(content) => Ok(format!("File content of '{}':\n\n{}", path, content)),
                        Err(e) => Err(e),
                    }
                } else {
                    match self.fs_tool.read_file_with_outside_access(canonical_str) {
                        Ok(content) => Ok(format!("File content of '{}':\n\n{}", path, content)),
                        Err(e) => Err(e),
                    }
                }
            }
            ToolName::WriteFile => {
                let path = input["path"].as_str().ok_or_else(|| {
                    SofosError::ToolExecution("Missing 'path' parameter".to_string())
                })?;
                let content = input["content"].as_str().ok_or_else(|| {
                    SofosError::ToolExecution("Missing 'content' parameter".to_string())
                })?;

                // Check if file exists and read original content for diff
                let original_content = self.fs_tool.read_file(path).ok();

                self.fs_tool.write_file(path, content)?;

                // If file existed before, show diff
                if let Some(original) = original_content {
                    let diff_output = diff::generate_compact_diff(&original, content, path);
                    Ok(format!(
                        "Successfully wrote to file '{}'\n\nChanges:\n{}",
                        path, diff_output
                    ))
                } else {
                    Ok(format!("Successfully created file '{}'", path))
                }
            }
            ToolName::ListDirectory => {
                let path = input["path"].as_str().ok_or_else(|| {
                    SofosError::ToolExecution("Missing 'path' parameter".to_string())
                })?;

                let permission_manager =
                    PermissionManager::new(self.fs_tool._workspace().to_path_buf())?;

                // Expand tilde and canonicalize
                let full_path = if path.starts_with('/') || path.starts_with('~') {
                    std::path::PathBuf::from(permissions::PermissionManager::expand_tilde_pub(path))
                } else {
                    self.fs_tool._workspace().join(path)
                };

                let canonical = match std::fs::canonicalize(&full_path) {
                    Ok(p) => p,
                    Err(_) => {
                        return Err(SofosError::FileNotFound(path.to_string()));
                    }
                };

                let is_inside_workspace = canonical.starts_with(self.fs_tool._workspace());
                let canonical_str = canonical.to_str().unwrap_or(path);

                // Check permissions
                let (perm_original, matched_rule_original) =
                    permission_manager.check_read_permission_with_source(path);
                let (perm_canonical, matched_rule_canonical) =
                    permission_manager.check_read_permission_with_source(canonical_str);

                let (final_perm, matched_rule) =
                    if perm_original == permissions::CommandPermission::Denied {
                        (perm_original, matched_rule_original)
                    } else if perm_canonical == permissions::CommandPermission::Denied {
                        (perm_canonical, matched_rule_canonical)
                    } else if perm_original == permissions::CommandPermission::Ask {
                        (perm_original, None)
                    } else if perm_canonical == permissions::CommandPermission::Ask {
                        (perm_canonical, None)
                    } else {
                        (permissions::CommandPermission::Allowed, None)
                    };

                match final_perm {
                    permissions::CommandPermission::Denied => {
                        let config_source = if let Some(ref rule) = matched_rule {
                            permission_manager.get_rule_source(rule)
                        } else {
                            ".sofos/config.local.toml or ~/.sofos/config.toml".to_string()
                        };
                        return Err(SofosError::ToolExecution(format!(
                            "Read access denied for path '{}'\n\
                             Hint: Blocked by deny rule in {}",
                            path, config_source
                        )));
                    }
                    permissions::CommandPermission::Ask => {
                        return Err(SofosError::ToolExecution(format!(
                            "Path '{}' is in 'ask' list\n\
                             Hint: 'ask' only works for Bash commands. Use 'allow' or 'deny' for Read permissions.",
                            path
                        )));
                    }
                    permissions::CommandPermission::Allowed => {}
                }

                let is_explicit_allow =
                    permission_manager.is_read_explicit_allow_both_forms(path, canonical_str);

                if !is_inside_workspace && !is_explicit_allow {
                    return Err(SofosError::ToolExecution(format!(
                        "Path '{}' is outside workspace and not explicitly allowed\n\
                         Hint: Add Read({}) to 'allow' list in .sofos/config.local.toml",
                        path, path
                    )));
                }

                // Use canonical path for the actual operation
                let entries = if is_inside_workspace {
                    self.fs_tool.list_directory(path)?
                } else {
                    // List using canonical path for outside workspace
                    let canonical_entries = std::fs::read_dir(&canonical)?;
                    let mut entries = Vec::new();
                    for entry in canonical_entries {
                        let entry = entry?;
                        let name = entry.file_name().to_string_lossy().to_string();
                        let is_dir = entry.file_type()?.is_dir();
                        entries.push(if is_dir { format!("{}/", name) } else { name });
                    }
                    entries.sort();
                    entries
                };

                Ok(format!("Contents of '{}':\n{}", path, entries.join("\n")))
            }
            ToolName::CreateDirectory => {
                let path = input["path"].as_str().ok_or_else(|| {
                    SofosError::ToolExecution("Missing 'path' parameter".to_string())
                })?;

                self.fs_tool.create_directory(path)?;
                Ok(format!("Successfully created directory '{}'", path))
            }
            ToolName::SearchCode => {
                let code_search = self.code_search_tool.as_ref()
                    .ok_or_else(|| SofosError::ToolExecution(
                        "Code search not available. Please install ripgrep: https://github.com/BurntSushi/ripgrep".to_string()
                    ))?;

                let pattern = input["pattern"].as_str().ok_or_else(|| {
                    SofosError::ToolExecution("Missing 'pattern' parameter".to_string())
                })?;

                let file_type = input["file_type"].as_str();
                let max_results = input["max_results"].as_u64().map(|n| n as usize);

                let results = code_search.search(pattern, file_type, max_results)?;
                Ok(format!("Code search results:\n\n{}", results))
            }
            ToolName::GlobFiles => {
                let pattern = input["pattern"].as_str().ok_or_else(|| {
                    SofosError::ToolExecution("Missing 'pattern' parameter".to_string())
                })?;
                let base = input["path"].as_str().unwrap_or(".");

                let search_dir = self.fs_tool._workspace().join(base);
                if !search_dir.exists() {
                    return Err(SofosError::FileNotFound(base.to_string()));
                }

                let glob = globset::GlobBuilder::new(pattern)
                    .literal_separator(false)
                    .build()
                    .map_err(|e| SofosError::ToolExecution(format!("Invalid glob pattern: {}", e)))?
                    .compile_matcher();

                let mut matches = Vec::new();
                let mut stack = vec![search_dir.clone()];

                while let Some(dir) = stack.pop() {
                    let entries = match std::fs::read_dir(&dir) {
                        Ok(e) => e,
                        Err(_) => continue,
                    };
                    for entry in entries.flatten() {
                        let path = entry.path();
                        if let Ok(rel) = path.strip_prefix(&search_dir) {
                            let rel_str = rel.to_string_lossy();
                            if path.is_dir() {
                                stack.push(path);
                            } else if glob.is_match(rel_str.as_ref()) {
                                matches.push(rel_str.to_string());
                            }
                        }
                    }
                }

                matches.sort();

                if matches.is_empty() {
                    Ok(format!("No files matching '{}' in '{}'", pattern, base))
                } else {
                    Ok(format!(
                        "Found {} file(s) matching '{}':\n{}",
                        matches.len(),
                        pattern,
                        matches.join("\n")
                    ))
                }
            }
            ToolName::EditFile => {
                let path = input["path"].as_str().ok_or_else(|| {
                    SofosError::ToolExecution("Missing 'path' parameter".to_string())
                })?;
                let old_string = input["old_string"].as_str().ok_or_else(|| {
                    SofosError::ToolExecution("Missing 'old_string' parameter".to_string())
                })?;
                let new_string = input["new_string"].as_str().ok_or_else(|| {
                    SofosError::ToolExecution("Missing 'new_string' parameter".to_string())
                })?;
                let replace_all = input["replace_all"].as_bool().unwrap_or(false);

                let original = self.fs_tool.read_file(path)?;

                if !original.contains(old_string) {
                    return Err(SofosError::ToolExecution(format!(
                        "old_string not found in '{}'. Make sure it matches the file content exactly, \
                         including whitespace and indentation.",
                        path
                    )));
                }

                let modified = if replace_all {
                    original.replace(old_string, new_string)
                } else {
                    original.replacen(old_string, new_string, 1)
                };

                self.fs_tool.write_file(path, &modified)?;

                let diff_output = diff::generate_compact_diff(&original, &modified, path);

                Ok(format!(
                    "Successfully edited '{}'\n\nChanges:\n{}",
                    path, diff_output
                ))
            }
            ToolName::MorphEditFile => {
                let morph = self.morph_client.as_ref().ok_or_else(|| {
                    SofosError::ToolExecution(
                        "Morph client not available. Set MORPH_API_KEY to use morph_edit_file"
                            .to_string(),
                    )
                })?;

                let path = input["path"].as_str().ok_or_else(|| {
                    SofosError::ToolExecution("Missing 'path' parameter".to_string())
                })?;
                let instruction = input["instruction"].as_str().ok_or_else(|| {
                    SofosError::ToolExecution("Missing 'instruction' parameter".to_string())
                })?;
                let code_edit = input["code_edit"].as_str().ok_or_else(|| {
                    SofosError::ToolExecution("Missing 'code_edit' parameter".to_string())
                })?;

                let original_code = self.fs_tool.read_file(path)?;

                let merged_code = morph
                    .apply_edit(instruction, &original_code, code_edit)
                    .await?;

                self.fs_tool.write_file(path, &merged_code)?;

                // Generate diff for display
                let diff_output = diff::generate_compact_diff(&original_code, &merged_code, path);

                Ok(format!(
                    "Successfully applied Morph edit to '{}'\n\nChanges:\n{}",
                    path, diff_output
                ))
            }
            ToolName::DeleteFile => {
                let path = input["path"].as_str().ok_or_else(|| {
                    SofosError::ToolExecution("Missing 'path' parameter".to_string())
                })?;

                let confirmed = confirm_destructive(&format!("Delete file '{}'?", path))?;

                if !confirmed {
                    return Ok(ToolExecutionResult::Text(format!(
                        "File deletion cancelled by user. The file '{}' was not deleted.",
                        path
                    )));
                }

                self.fs_tool.delete_file(path)?;
                Ok(format!("Successfully deleted file '{}'", path))
            }
            ToolName::DeleteDirectory => {
                let path = input["path"].as_str().ok_or_else(|| {
                    SofosError::ToolExecution("Missing 'path' parameter".to_string())
                })?;

                let confirmed = confirm_destructive(&format!(
                    "Delete directory '{}' and all its contents?",
                    path
                ))?;

                if !confirmed {
                    return Ok(ToolExecutionResult::Text(format!(
                        "Directory deletion cancelled by user. The directory '{}' and its contents were not deleted. What would you like to do instead?",
                        path
                    )));
                }

                self.fs_tool.delete_directory(path)?;
                Ok(format!("Successfully deleted directory '{}'", path))
            }
            ToolName::MoveFile => {
                let source = input["source"].as_str().ok_or_else(|| {
                    SofosError::ToolExecution("Missing 'source' parameter".to_string())
                })?;
                let destination = input["destination"].as_str().ok_or_else(|| {
                    SofosError::ToolExecution("Missing 'destination' parameter".to_string())
                })?;

                self.fs_tool.move_file(source, destination)?;
                Ok(format!(
                    "Successfully moved '{}' to '{}'",
                    source, destination
                ))
            }
            ToolName::CopyFile => {
                let source = input["source"].as_str().ok_or_else(|| {
                    SofosError::ToolExecution("Missing 'source' parameter".to_string())
                })?;
                let destination = input["destination"].as_str().ok_or_else(|| {
                    SofosError::ToolExecution("Missing 'destination' parameter".to_string())
                })?;

                self.fs_tool.copy_file(source, destination)?;
                Ok(format!(
                    "Successfully copied '{}' to '{}'",
                    source, destination
                ))
            }
            ToolName::ExecuteBash => {
                let command = input["command"].as_str().ok_or_else(|| {
                    SofosError::ToolExecution("Missing 'command' parameter".to_string())
                })?;

                let result = self.bash_executor.execute(command)?;
                Ok(result)
            }
            ToolName::WebFetch => {
                let url = input["url"].as_str().ok_or_else(|| {
                    SofosError::ToolExecution("Missing 'url' parameter".to_string())
                })?;

                if !url.starts_with("http://") && !url.starts_with("https://") {
                    return Err(SofosError::ToolExecution(
                        "URL must start with http:// or https://".to_string(),
                    ));
                }

                let client = reqwest::Client::builder()
                    .timeout(std::time::Duration::from_secs(30))
                    .build()
                    .map_err(|e| SofosError::ToolExecution(format!("HTTP client error: {}", e)))?;

                let response = client
                    .get(url)
                    .header("User-Agent", "Sofos/1.0")
                    .send()
                    .await
                    .map_err(|e| SofosError::ToolExecution(format!("Fetch failed: {}", e)))?;

                let status = response.status();
                if !status.is_success() {
                    return Err(SofosError::ToolExecution(format!(
                        "HTTP {} for {}",
                        status, url
                    )));
                }

                let body = response
                    .text()
                    .await
                    .map_err(|e| SofosError::ToolExecution(format!("Read body failed: {}", e)))?;

                let text = utils::html_to_text(&body);

                let max_chars = 64_000;
                let truncated = if text.len() > max_chars {
                    format!(
                        "{}\n\n[TRUNCATED: showing first ~{} chars of {}]",
                        &text[..max_chars],
                        max_chars,
                        text.len()
                    )
                } else {
                    text
                };

                Ok(format!("Content from {}:\n\n{}", url, truncated))
            }
            ToolName::WebSearch => Err(SofosError::ToolExecution(
                "web_search is handled server-side by the API and should not be executed locally"
                    .to_string(),
            )),
        };

        Ok(ToolExecutionResult::Text(text_result?))
    }
}