oxi-agent 0.19.0

Agent runtime with tool-calling loop for AI coding assistants
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
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
use super::path_security::PathGuard;
/// Ls tool - list directory contents
use super::{AgentTool, AgentToolResult, ToolContext, ToolError};
use crate::tools::truncate::{format_bytes, truncate_head, TruncationOptions};
use async_trait::async_trait;
use serde_json::{json, Value};
use std::path::{Path, PathBuf};
use tokio::fs;
use tokio::sync::oneshot;

/// Default max entries to show (use truncate for more)
const DEFAULT_ENTRY_LIMIT: usize = 100;
/// Default max output lines (for truncation)
const DEFAULT_MAX_LINES: usize = 2000;
/// Default max output bytes (for truncation)
const DEFAULT_MAX_BYTES: usize = 50 * 1024;

/// LsTool.
pub struct LsTool {
    root_dir: Option<PathBuf>,
}

impl LsTool {
    /// Create with no explicit root (uses ToolContext.workspace_dir at runtime).
    pub fn new() -> Self {
        Self { root_dir: None }
    }

    /// Create with a specific working directory (overrides ToolContext).
    pub fn with_cwd(cwd: PathBuf) -> Self {
        Self {
            root_dir: Some(cwd),
        }
    }

    /// Format file size in human-readable format
    fn format_size(size: u64) -> String {
        format_bytes(size as usize)
    }

    /// Get file type indicator: / for dirs, @ for symlinks, * for executables
    fn get_type_indicator(metadata: &std::fs::Metadata) -> &'static str {
        if metadata.is_dir() {
            "/"
        } else if metadata.file_type().is_symlink() {
            "@"
        } else {
            // Check if executable
            #[cfg(unix)]
            {
                use std::os::unix::fs::PermissionsExt;
                if metadata.permissions().mode() & 0o111 != 0 {
                    return "*";
                }
            }
            ""
        }
    }

    async fn ls_impl(
        root_dir: &Path,
        path: &str,
        all: bool,
        long_format: bool,
        entry_limit: Option<usize>,
    ) -> Result<String, ToolError> {
        // Security: validate path with PathGuard
        let guard = PathGuard::new(root_dir);
        let dir_path = guard
            .validate_traversal(Path::new(path))
            .map_err(|e| e.to_string())?;

        if !dir_path.exists() {
            return Err(format!("Path not found: {}", path));
        }

        if !dir_path.is_dir() {
            // If it's a file, just return its info
            let meta = fs::metadata(&dir_path)
                .await
                .map_err(|e| format!("Cannot read metadata: {}", e))?;
            let size = meta.len();
            let name = dir_path
                .file_name()
                .map(|n| n.to_string_lossy().to_string())
                .unwrap_or_default();

            let type_indicator = Self::get_type_indicator(&meta);

            return Ok(if long_format {
                format!("{:<10} {}{}", Self::format_size(size), name, type_indicator)
            } else {
                format!("{}{}", name, type_indicator)
            });
        }

        // Read all entries first
        let mut entries: Vec<(String, bool, u64, std::fs::Metadata)> = Vec::new();
        let mut dir = fs::read_dir(&dir_path)
            .await
            .map_err(|e| format!("Cannot read directory: {}", e))?;

        while let Some(entry) = dir
            .next_entry()
            .await
            .map_err(|e| format!("Error reading entry: {}", e))?
        {
            let file_name = entry.file_name().to_string_lossy().to_string();

            // Skip hidden files unless --all
            if !all && file_name.starts_with('.') {
                continue;
            }

            let metadata = entry.metadata().await.map_err(|e| e.to_string())?;
            let is_dir = metadata.is_dir();
            let size = metadata.len();

            entries.push((file_name, is_dir, size, metadata));
        }

        // Sort: directories first, then alphabetically (case-insensitive)
        entries.sort_by(|a, b| match (a.1, b.1) {
            (true, false) => std::cmp::Ordering::Less,
            (false, true) => std::cmp::Ordering::Greater,
            _ => a.0.to_lowercase().cmp(&b.0.to_lowercase()),
        });

        // Apply entry limit if specified
        let limit = entry_limit.unwrap_or(DEFAULT_ENTRY_LIMIT);
        let limited = if entries.len() > limit {
            entries.truncate(limit);
            true
        } else {
            false
        };

        let total_entries = entries.len();
        let dir_count = entries.iter().filter(|e| e.1).count();
        let file_count = total_entries - dir_count;

        // Build output based on format
        let output = if long_format {
            let mut lines: Vec<String> = entries
                .iter()
                .map(|(name, _is_dir, size, meta)| {
                    let type_indicator = Self::get_type_indicator(meta);
                    format!(
                        "{:<10} {}{}",
                        Self::format_size(*size),
                        name,
                        type_indicator
                    )
                })
                .collect();

            // Add entry count summary
            lines.push(format!(
                "\n{} director{}, {} file{}",
                dir_count,
                if dir_count == 1 { "y" } else { "ies" },
                file_count,
                if file_count == 1 { "" } else { "s" }
            ));

            lines.join("\n")
        } else {
            let lines: Vec<String> = entries
                .iter()
                .map(|(name, _, _, meta)| {
                    let type_indicator = Self::get_type_indicator(meta);
                    format!("{}{}", name, type_indicator)
                })
                .collect();

            lines.join("\n")
        };

        // Add entry limit notice if truncated
        let output = if limited {
            format!(
                "{}\n\n... [limit reached: {} entries total, use limit=N to see more]",
                output, total_entries
            )
        } else {
            output
        };

        // Apply output truncation (for very large directories)
        let truncation_options = TruncationOptions {
            max_lines: Some(DEFAULT_MAX_LINES),
            max_bytes: Some(DEFAULT_MAX_BYTES),
        };
        let result = truncate_head(&output, &truncation_options);

        Ok(result.content)
    }
}

impl Default for LsTool {
    fn default() -> Self {
        Self::new()
    }
}

#[async_trait]
impl AgentTool for LsTool {
    fn name(&self) -> &str {
        "ls"
    }

    fn label(&self) -> &str {
        "Ls"
    }

    fn essential(&self) -> bool {
        true
    }
    fn description(&self) -> &str {
        "List directory contents. Shows files and subdirectories with optional details."
    }

    fn parameters_schema(&self) -> Value {
        json!({
            "type": "object",
            "properties": {
                "path": {
                    "type": "string",
                    "description": "The directory to list",
                    "default": "."
                },
                "all": {
                    "type": "boolean",
                    "description": "If true, show hidden files (starting with .)",
                    "default": false
                },
                "long": {
                    "type": "boolean",
                    "description": "If true, show detailed listing with file sizes",
                    "default": false
                },
                "limit": {
                    "type": "integer",
                    "description": "Maximum number of entries to display (truncation notice shown if exceeded)",
                    "default": 100
                }
            },
            "required": ["path"]
        })
    }

    async fn execute(
        &self,
        _tool_call_id: &str,
        params: Value,
        _signal: Option<oneshot::Receiver<()>>,
        ctx: &ToolContext,
    ) -> Result<AgentToolResult, ToolError> {
        let path = params
            .get("path")
            .and_then(|v: &Value| v.as_str())
            .unwrap_or(".");

        let all = params
            .get("all")
            .and_then(|v: &Value| v.as_bool())
            .unwrap_or(false);

        let long_format = params
            .get("long")
            .and_then(|v: &Value| v.as_bool())
            .unwrap_or(false);

        let entry_limit = params
            .get("limit")
            .and_then(|v: &Value| v.as_u64())
            .map(|l| l as usize);

        // Use root_dir if set, else ctx.root()
        let root = self.root_dir.as_deref().unwrap_or(ctx.root());

        match Self::ls_impl(root, path, all, long_format, entry_limit).await {
            Ok(output) => Ok(AgentToolResult::success(output)),
            Err(e) => Ok(AgentToolResult::error(e)),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;
    use tempfile::TempDir;

    fn create_test_dir() -> TempDir {
        let temp_dir = TempDir::new().unwrap();

        // Create test files and directories
        let test_files = vec![
            ("alpha.txt", false),
            ("beta.txt", false),
            ("gamma.rs", false),
            ("subdir", true),
            ("another_dir", true),
        ];

        for (name, is_dir) in test_files {
            let path = temp_dir.path().join(name);
            if is_dir {
                fs::create_dir(&path).unwrap();
            } else {
                fs::write(&path, "test content").unwrap();
            }
        }

        // Create hidden file
        fs::write(temp_dir.path().join(".hidden"), "hidden").unwrap();

        temp_dir
    }

    #[test]
    fn test_basic_ls() {
        let temp_dir = create_test_dir();
        let rt = tokio::runtime::Runtime::new().unwrap();

        let result = rt
            .block_on(async {
                LsTool::ls_impl(
                    Path::new("."),
                    temp_dir.path().to_str().unwrap(),
                    false,
                    false,
                    None,
                )
                .await
            })
            .unwrap();

        // Should include visible files and directories
        assert!(result.contains("alpha.txt"));
        assert!(result.contains("beta.txt"));
        assert!(result.contains("gamma.rs"));
        // Should not show hidden file by default
        assert!(!result.contains(".hidden"));
    }

    #[test]
    fn test_ls_all() {
        let temp_dir = create_test_dir();
        let rt = tokio::runtime::Runtime::new().unwrap();

        let result = rt
            .block_on(async {
                LsTool::ls_impl(
                    Path::new("."),
                    temp_dir.path().to_str().unwrap(),
                    true,
                    false,
                    None,
                )
                .await
            })
            .unwrap();

        // Should show hidden file with all flag
        assert!(result.contains(".hidden"));
    }

    #[test]
    fn test_ls_long_format() {
        let temp_dir = create_test_dir();
        let rt = tokio::runtime::Runtime::new().unwrap();

        let result = rt
            .block_on(async {
                LsTool::ls_impl(
                    Path::new("."),
                    temp_dir.path().to_str().unwrap(),
                    false,
                    true,
                    None,
                )
                .await
            })
            .unwrap();

        // Long format should have sizes
        assert!(result.contains("B") || result.contains("KB") || result.contains("MB"));
    }

    #[test]
    fn test_entry_count_summary() {
        let temp_dir = create_test_dir();
        let rt = tokio::runtime::Runtime::new().unwrap();

        let result = rt
            .block_on(async {
                LsTool::ls_impl(
                    Path::new("."),
                    temp_dir.path().to_str().unwrap(),
                    false,
                    true,
                    None,
                )
                .await
            })
            .unwrap();

        // Should have entry count summary in long format
        assert!(result.contains("directories") || result.contains("directory"));
        assert!(result.contains("files") || result.contains("file"));
    }

    #[test]
    fn test_entry_limit() {
        let temp_dir = create_test_dir();
        let rt = tokio::runtime::Runtime::new().unwrap();

        // Set limit to 2
        let result = rt
            .block_on(async {
                LsTool::ls_impl(
                    Path::new("."),
                    temp_dir.path().to_str().unwrap(),
                    false,
                    false,
                    Some(2),
                )
                .await
            })
            .unwrap();

        // Should show limit reached notice
        assert!(result.contains("limit reached") || result.contains("limit=N"));
    }

    #[test]
    fn test_case_insensitive_sort() {
        let temp_dir = TempDir::new().unwrap();

        // Create files with various cases
        fs::write(temp_dir.path().join("Zebra.rs"), "").unwrap();
        fs::write(temp_dir.path().join("apple.rs"), "").unwrap();
        fs::write(temp_dir.path().join("Banana.rs"), "").unwrap();

        let rt = tokio::runtime::Runtime::new().unwrap();
        let result = rt
            .block_on(async {
                LsTool::ls_impl(
                    Path::new("."),
                    temp_dir.path().to_str().unwrap(),
                    false,
                    false,
                    None,
                )
                .await
            })
            .unwrap();

        let _lines: Vec<&str> = result.lines().collect();
        // Should be sorted case-insensitely: apple, Banana, Zebra
        assert!(result.contains("apple.rs"));
        assert!(result.contains("Banana.rs"));
        assert!(result.contains("Zebra.rs"));
    }

    #[test]
    fn test_type_indicators() {
        let temp_dir = TempDir::new().unwrap();

        // Create directory
        fs::create_dir(temp_dir.path().join("test_dir")).unwrap();
        // Create regular file
        fs::write(temp_dir.path().join("test_file.txt"), "").unwrap();

        let rt = tokio::runtime::Runtime::new().unwrap();
        let result = rt
            .block_on(async {
                LsTool::ls_impl(
                    Path::new("."),
                    temp_dir.path().to_str().unwrap(),
                    false,
                    false,
                    None,
                )
                .await
            })
            .unwrap();

        // Directories should have / indicator
        assert!(result.contains("test_dir/"));
        // Regular files should not have indicator
        assert!(result.contains("test_file.txt"));
        assert!(!result.contains("test_file.txt/"));
    }

    #[test]
    fn test_path_traversal_prevention() {
        let rt = tokio::runtime::Runtime::new().unwrap();
        let result = rt.block_on(async {
            LsTool::ls_impl(Path::new("."), "../etc", false, false, None).await
        });

        assert!(result.is_err());
        assert!(result.unwrap_err().contains("traversal"));
    }

    #[test]
    fn test_nonexistent_path() {
        let rt = tokio::runtime::Runtime::new().unwrap();
        let result = rt.block_on(async {
            LsTool::ls_impl(
                Path::new("."),
                "/nonexistent/path/12345",
                false,
                false,
                None,
            )
            .await
        });

        assert!(result.is_err());
        assert!(result.unwrap_err().contains("not found"));
    }

    #[test]
    fn test_single_file() {
        let temp_dir = TempDir::new().unwrap();
        let file_path = temp_dir.path().join("single_file.txt");
        fs::write(&file_path, "content").unwrap();

        let rt = tokio::runtime::Runtime::new().unwrap();
        let result = rt
            .block_on(async {
                LsTool::ls_impl(
                    Path::new("."),
                    file_path.to_str().unwrap(),
                    false,
                    false,
                    None,
                )
                .await
            })
            .unwrap();

        assert!(result.contains("single_file.txt"));
    }

    #[test]
    fn test_format_size() {
        assert!(LsTool::format_size(500).contains("B"));
        assert!(LsTool::format_size(1024).contains("KB"));
        assert!(LsTool::format_size(1024 * 1024).contains("MB"));
    }
}