limit-cli 0.0.46

AI-powered terminal coding assistant with TUI. Multi-provider LLM support, session persistence, and built-in tools.
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
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
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
use async_trait::async_trait;
use limit_agent::error::AgentError;
use limit_agent::Tool;
use serde_json::Value;
use std::process::Command;

/// Check if git is available in PATH
fn check_git_available() -> Result<(), AgentError> {
    let result = Command::new("git").arg("--version").output();

    match result {
        Ok(output) if output.status.success() => Ok(()),
        Ok(_) => Err(AgentError::ToolError(
            "git command failed to execute".to_string(),
        )),
        Err(_) => Err(AgentError::ToolError(
            "git not found in PATH. Please install git 2.0 or later.".to_string(),
        )),
    }
}

pub struct GitStatusTool;

impl GitStatusTool {
    pub fn new() -> Self {
        GitStatusTool
    }
}

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

#[async_trait]
impl Tool for GitStatusTool {
    fn name(&self) -> &str {
        "git_status"
    }

    async fn execute(&self, _args: Value) -> Result<Value, AgentError> {
        check_git_available()?;

        let output = Command::new("git")
            .args(["status", "--porcelain"])
            .output()
            .map_err(|e| AgentError::ToolError(format!("Failed to execute git status: {}", e)))?;

        if !output.status.success() {
            let stderr = String::from_utf8_lossy(&output.stderr);
            return Err(AgentError::ToolError(format!(
                "git status failed: {}",
                stderr
            )));
        }

        let stdout = String::from_utf8_lossy(&output.stdout);
        let lines: Vec<&str> = stdout.lines().collect();

        Ok(serde_json::json!({
            "changes": lines,
            "count": lines.len()
        }))
    }
}

pub struct GitDiffTool;

impl GitDiffTool {
    pub fn new() -> Self {
        GitDiffTool
    }
}

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

#[async_trait]
impl Tool for GitDiffTool {
    fn name(&self) -> &str {
        "git_diff"
    }

    async fn execute(&self, _args: Value) -> Result<Value, AgentError> {
        check_git_available()?;

        let output = Command::new("git")
            .args(["diff"])
            .output()
            .map_err(|e| AgentError::ToolError(format!("Failed to execute git diff: {}", e)))?;

        if !output.status.success() {
            let stderr = String::from_utf8_lossy(&output.stderr);
            return Err(AgentError::ToolError(format!(
                "git diff failed: {}",
                stderr
            )));
        }

        let stdout = String::from_utf8_lossy(&output.stdout);

        Ok(serde_json::json!({
            "diff": stdout,
            "size": stdout.len()
        }))
    }
}

pub struct GitLogTool;

impl GitLogTool {
    pub fn new() -> Self {
        GitLogTool
    }
}

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

#[async_trait]
impl Tool for GitLogTool {
    fn name(&self) -> &str {
        "git_log"
    }

    async fn execute(&self, args: Value) -> Result<Value, AgentError> {
        check_git_available()?;

        // Get number of commits from args, default to 10
        let count = args.get("count").and_then(|v| v.as_u64()).unwrap_or(10);

        let output = Command::new("git")
            .args(["log", &format!("-{}", count), "--oneline"])
            .output()
            .map_err(|e| AgentError::ToolError(format!("Failed to execute git log: {}", e)))?;

        if !output.status.success() {
            let stderr = String::from_utf8_lossy(&output.stderr);
            return Err(AgentError::ToolError(format!("git log failed: {}", stderr)));
        }

        let stdout = String::from_utf8_lossy(&output.stdout);
        let commits: Vec<&str> = stdout.lines().collect();

        Ok(serde_json::json!({
            "commits": commits,
            "count": commits.len()
        }))
    }
}

pub struct GitAddTool;

impl GitAddTool {
    pub fn new() -> Self {
        GitAddTool
    }
}

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

#[async_trait]
impl Tool for GitAddTool {
    fn name(&self) -> &str {
        "git_add"
    }

    async fn execute(&self, args: Value) -> Result<Value, AgentError> {
        check_git_available()?;

        let files: Vec<String> = serde_json::from_value(args["files"].clone())
            .map_err(|e| AgentError::ToolError(format!("Invalid files argument: {}", e)))?;

        if files.is_empty() {
            return Err(AgentError::ToolError(
                "files argument cannot be empty".to_string(),
            ));
        }

        let mut cmd = Command::new("git");
        cmd.arg("add");
        for file in &files {
            cmd.arg(file);
        }

        let output = cmd
            .output()
            .map_err(|e| AgentError::ToolError(format!("Failed to execute git add: {}", e)))?;

        if !output.status.success() {
            let stderr = String::from_utf8_lossy(&output.stderr);
            return Err(AgentError::ToolError(format!("git add failed: {}", stderr)));
        }

        Ok(serde_json::json!({
            "success": true,
            "files": files,
            "count": files.len()
        }))
    }
}

pub struct GitCommitTool;

impl GitCommitTool {
    pub fn new() -> Self {
        GitCommitTool
    }
}

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

#[async_trait]
impl Tool for GitCommitTool {
    fn name(&self) -> &str {
        "git_commit"
    }

    async fn execute(&self, args: Value) -> Result<Value, AgentError> {
        check_git_available()?;

        let message: String = serde_json::from_value(args["message"].clone())
            .map_err(|e| AgentError::ToolError(format!("Invalid message argument: {}", e)))?;

        if message.trim().is_empty() {
            return Err(AgentError::ToolError(
                "message argument cannot be empty".to_string(),
            ));
        }

        let output = Command::new("git")
            .args(["commit", "-m", &message])
            .output()
            .map_err(|e| AgentError::ToolError(format!("Failed to execute git commit: {}", e)))?;

        if !output.status.success() {
            let stderr = String::from_utf8_lossy(&output.stderr);
            return Err(AgentError::ToolError(format!(
                "git commit failed: {}",
                stderr
            )));
        }

        let stdout = String::from_utf8_lossy(&output.stdout);

        Ok(serde_json::json!({
            "success": true,
            "message": message,
            "output": stdout
        }))
    }
}

pub struct GitPushTool;

impl GitPushTool {
    pub fn new() -> Self {
        GitPushTool
    }
}

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

#[async_trait]
impl Tool for GitPushTool {
    fn name(&self) -> &str {
        "git_push"
    }

    async fn execute(&self, args: Value) -> Result<Value, AgentError> {
        check_git_available()?;

        // Get remote and branch from args, use defaults
        let remote = args
            .get("remote")
            .and_then(|v| v.as_str())
            .unwrap_or("origin");

        let branch = args.get("branch").and_then(|v| v.as_str()).unwrap_or("");

        let output = if branch.is_empty() {
            Command::new("git")
                .args(["push", remote])
                .output()
                .map_err(|e| AgentError::ToolError(format!("Failed to execute git push: {}", e)))?
        } else {
            Command::new("git")
                .args(["push", remote, branch])
                .output()
                .map_err(|e| AgentError::ToolError(format!("Failed to execute git push: {}", e)))?
        };

        if !output.status.success() {
            let stderr = String::from_utf8_lossy(&output.stderr);
            return Err(AgentError::ToolError(format!(
                "git push failed: {}",
                stderr
            )));
        }

        let stdout = String::from_utf8_lossy(&output.stdout);

        Ok(serde_json::json!({
            "success": true,
            "remote": remote,
            "branch": if branch.is_empty() { "(default)" } else { branch },
            "output": stdout
        }))
    }
}

pub struct GitPullTool;

impl GitPullTool {
    pub fn new() -> Self {
        GitPullTool
    }
}

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

#[async_trait]
impl Tool for GitPullTool {
    fn name(&self) -> &str {
        "git_pull"
    }

    async fn execute(&self, args: Value) -> Result<Value, AgentError> {
        check_git_available()?;

        // Get remote and branch from args, use defaults
        let remote = args
            .get("remote")
            .and_then(|v| v.as_str())
            .unwrap_or("origin");

        let branch = args.get("branch").and_then(|v| v.as_str()).unwrap_or("");

        let output = if branch.is_empty() {
            Command::new("git")
                .args(["pull", remote])
                .output()
                .map_err(|e| AgentError::ToolError(format!("Failed to execute git pull: {}", e)))?
        } else {
            Command::new("git")
                .args(["pull", remote, branch])
                .output()
                .map_err(|e| AgentError::ToolError(format!("Failed to execute git pull: {}", e)))?
        };

        if !output.status.success() {
            let stderr = String::from_utf8_lossy(&output.stderr);
            return Err(AgentError::ToolError(format!(
                "git pull failed: {}",
                stderr
            )));
        }

        let stdout = String::from_utf8_lossy(&output.stdout);

        Ok(serde_json::json!({
            "success": true,
            "remote": remote,
            "branch": if branch.is_empty() { "(default)" } else { branch },
            "output": stdout
        }))
    }
}

pub struct GitCloneTool;

impl GitCloneTool {
    pub fn new() -> Self {
        GitCloneTool
    }
}

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

#[async_trait]
impl Tool for GitCloneTool {
    fn name(&self) -> &str {
        "git_clone"
    }

    async fn execute(&self, args: Value) -> Result<Value, AgentError> {
        check_git_available()?;

        let url: String = serde_json::from_value(args["url"].clone())
            .map_err(|e| AgentError::ToolError(format!("Invalid url argument: {}", e)))?;

        if url.trim().is_empty() {
            return Err(AgentError::ToolError(
                "url argument cannot be empty".to_string(),
            ));
        }

        // Get optional directory name
        let directory = args.get("directory").and_then(|v| v.as_str());

        let output = if let Some(dir) = directory {
            Command::new("git")
                .args(["clone", &url, dir])
                .output()
                .map_err(|e| AgentError::ToolError(format!("Failed to execute git clone: {}", e)))?
        } else {
            Command::new("git")
                .args(["clone", &url])
                .output()
                .map_err(|e| AgentError::ToolError(format!("Failed to execute git clone: {}", e)))?
        };

        if !output.status.success() {
            let stderr = String::from_utf8_lossy(&output.stderr);
            return Err(AgentError::ToolError(format!(
                "git clone failed: {}",
                stderr
            )));
        }

        let stdout = String::from_utf8_lossy(&output.stdout);

        Ok(serde_json::json!({
            "success": true,
            "url": url,
            "directory": directory.unwrap_or("(default)"),
            "output": stdout
        }))
    }
}

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

    #[tokio::test]
    async fn test_git_status_tool_name() {
        let tool = GitStatusTool::new();
        assert_eq!(tool.name(), "git_status");
    }

    #[tokio::test]
    async fn test_git_status_tool_default() {
        let tool = GitStatusTool;
        assert_eq!(tool.name(), "git_status");
    }

    #[tokio::test]
    async fn test_git_diff_tool_name() {
        let tool = GitDiffTool::new();
        assert_eq!(tool.name(), "git_diff");
    }

    #[tokio::test]
    async fn test_git_log_tool_name() {
        let tool = GitLogTool::new();
        assert_eq!(tool.name(), "git_log");
    }

    #[tokio::test]
    async fn test_git_log_tool_default_count() {
        let tool = GitLogTool::new();
        let args = serde_json::json!({});

        // This will fail if git is not in a repository, but we test the parsing logic
        // The actual execution requires a git repository context
        let result = tool.execute(args).await;

        // We expect either success (in a git repo) or a git-specific error, not a parsing error
        // If git is not available, we get a different error
        if let Err(e) = result {
            assert!(!e.to_string().contains("Invalid count argument"));
        }
    }

    #[tokio::test]
    async fn test_git_log_tool_custom_count() {
        let tool = GitLogTool::new();
        let args = serde_json::json!({"count": 5});

        let result = tool.execute(args).await;

        // Similar to above, we test parsing, not actual git execution
        if let Err(e) = result {
            assert!(!e.to_string().contains("Invalid count argument"));
        }
    }

    #[tokio::test]
    async fn test_git_add_tool_name() {
        let tool = GitAddTool::new();
        assert_eq!(tool.name(), "git_add");
    }

    #[tokio::test]
    async fn test_git_add_tool_empty_files() {
        let tool = GitAddTool::new();
        let args = serde_json::json!({"files": []});

        let result = tool.execute(args).await;
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("cannot be empty"));
    }

    #[tokio::test]
    async fn test_git_add_tool_invalid_files() {
        let tool = GitAddTool::new();
        let args = serde_json::json!({}); // Missing files

        let result = tool.execute(args).await;
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("Invalid files"));
    }

    #[tokio::test]
    async fn test_git_commit_tool_name() {
        let tool = GitCommitTool::new();
        assert_eq!(tool.name(), "git_commit");
    }

    #[tokio::test]
    async fn test_git_commit_tool_empty_message() {
        let tool = GitCommitTool::new();
        let args = serde_json::json!({"message": "   "});

        let result = tool.execute(args).await;
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("cannot be empty"));
    }

    #[tokio::test]
    async fn test_git_commit_tool_invalid_message() {
        let tool = GitCommitTool::new();
        let args = serde_json::json!({}); // Missing message

        let result = tool.execute(args).await;
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("Invalid message"));
    }

    #[tokio::test]
    async fn test_git_push_tool_name() {
        let tool = GitPushTool::new();
        assert_eq!(tool.name(), "git_push");
    }

    #[tokio::test]
    async fn test_git_push_tool_default_values() {
        let tool = GitPushTool::new();
        let args = serde_json::json!({});

        let result = tool.execute(args).await;

        // Will fail in most cases, but tests parsing
        if let Err(e) = result {
            // Should not be a parsing error
            assert!(!e.to_string().contains("Invalid"));
        }
    }

    #[tokio::test]
    async fn test_git_push_tool_custom_values() {
        let tool = GitPushTool::new();
        let args = serde_json::json!({
            "remote": "upstream",
            "branch": "feature"
        });

        let result = tool.execute(args).await;

        // Tests that custom values are parsed correctly
        if let Err(e) = result {
            assert!(!e.to_string().contains("Invalid"));
        }
    }

    #[tokio::test]
    async fn test_git_pull_tool_name() {
        let tool = GitPullTool::new();
        assert_eq!(tool.name(), "git_pull");
    }

    #[tokio::test]
    async fn test_git_pull_tool_default_values() {
        let tool = GitPullTool::new();
        let args = serde_json::json!({});

        let result = tool.execute(args).await;

        // Will fail in most cases, but tests parsing
        if let Err(e) = result {
            // Should not be a parsing error
            assert!(!e.to_string().contains("Invalid"));
        }
    }

    #[tokio::test]
    async fn test_git_clone_tool_name() {
        let tool = GitCloneTool::new();
        assert_eq!(tool.name(), "git_clone");
    }

    #[tokio::test]
    async fn test_git_clone_tool_empty_url() {
        let tool = GitCloneTool::new();
        let args = serde_json::json!({"url": ""});

        let result = tool.execute(args).await;
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("cannot be empty"));
    }

    #[tokio::test]
    async fn test_git_clone_tool_invalid_url() {
        let tool = GitCloneTool::new();
        let args = serde_json::json!({}); // Missing url

        let result = tool.execute(args).await;
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("Invalid url"));
    }

    #[tokio::test]
    async fn test_git_clone_tool_custom_directory() {
        let tool = GitCloneTool::new();
        let args = serde_json::json!({
            "url": "https://github.com/test/repo.git",
            "directory": "my-repo"
        });

        let result = tool.execute(args).await;

        // Tests that directory argument is parsed correctly
        if let Err(e) = result {
            // Should not be a parsing error
            assert!(!e.to_string().contains("Invalid"));
        }
    }

    #[tokio::test]
    async fn test_all_tools_implement_default() {
        // Verify all tools implement Default trait
        let _status = GitStatusTool;
        let _diff = GitDiffTool;
        let _log = GitLogTool;
        let _add = GitAddTool;
        let _commit = GitCommitTool;
        let _push = GitPushTool;
        let _pull = GitPullTool;
        let _clone = GitCloneTool;
    }
}