sh-layer3 1.0.0

Continuum Layer 3: Capabilities
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
//! # Git Tools
//!
//! Git 版本控制工具集。

use crate::builtin_tools::BuiltinTool;
use crate::types::{Layer3Result, ToolCategory};
use async_trait::async_trait;
use std::process::Command;

/// Execute a git command and return the output
fn run_git(args: &[&str], cwd: Option<&str>) -> Layer3Result<String> {
    let mut cmd = Command::new("git");
    cmd.args(args);

    if let Some(dir) = cwd {
        cmd.current_dir(dir);
    }

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

    if output.status.success() {
        String::from_utf8(output.stdout).map_err(|e| anyhow::anyhow!("Invalid UTF-8 output: {}", e))
    } else {
        let stderr = String::from_utf8_lossy(&output.stderr);
        Err(anyhow::anyhow!("Git command failed: {}", stderr))
    }
}

// ============================================================================
// Git Status Tool
// ============================================================================

/// Git 状态工具
pub struct GitStatusTool;

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

    fn description(&self) -> &str {
        "Show the working tree status. Lists modified, staged, and untracked files."
    }

    fn parameters_schema(&self) -> serde_json::Value {
        serde_json::json!({
            "type": "object",
            "properties": {
                "path": {
                    "type": "string",
                    "description": "Repository path (default: current directory)"
                },
                "short": {
                    "type": "boolean",
                    "description": "Use short format (default: false)"
                }
            }
        })
    }

    fn category(&self) -> ToolCategory {
        ToolCategory::VersionControl
    }

    async fn execute(&self, args: serde_json::Value) -> Layer3Result<String> {
        let path = args["path"].as_str();
        let short = args["short"].as_bool().unwrap_or(false);

        let mut git_args = vec!["status"];
        if short {
            git_args.push("--short");
        }

        run_git(&git_args, path)
    }
}

// ============================================================================
// Git Log Tool
// ============================================================================

/// Git 日志工具
pub struct GitLogTool;

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

    fn description(&self) -> &str {
        "Show commit logs. Supports various format options."
    }

    fn parameters_schema(&self) -> serde_json::Value {
        serde_json::json!({
            "type": "object",
            "properties": {
                "path": {
                    "type": "string",
                    "description": "Repository path (default: current directory)"
                },
                "count": {
                    "type": "integer",
                    "description": "Number of commits to show (default: 10)"
                },
                "oneline": {
                    "type": "boolean",
                    "description": "Use one-line format (default: true)"
                },
                "branch": {
                    "type": "string",
                    "description": "Branch name (default: current branch)"
                }
            }
        })
    }

    fn category(&self) -> ToolCategory {
        ToolCategory::VersionControl
    }

    async fn execute(&self, args: serde_json::Value) -> Layer3Result<String> {
        let path = args["path"].as_str();
        let count = args["count"].as_u64().unwrap_or(10);
        let oneline = args["oneline"].as_bool().unwrap_or(true);
        let branch = args["branch"].as_str();

        let count_arg = format!("-{}", count);
        let mut git_args = vec!["log", &count_arg];
        if oneline {
            git_args.push("--oneline");
        }
        if let Some(b) = branch {
            git_args.push(b);
        }

        run_git(&git_args, path)
    }
}

// ============================================================================
// Git Diff Tool
// ============================================================================

/// Git Diff 工具
pub struct GitDiffTool;

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

    fn description(&self) -> &str {
        "Show changes between commits, commit and working tree, etc."
    }

    fn parameters_schema(&self) -> serde_json::Value {
        serde_json::json!({
            "type": "object",
            "properties": {
                "path": {
                    "type": "string",
                    "description": "Repository path (default: current directory)"
                },
                "file": {
                    "type": "string",
                    "description": "Specific file to diff"
                },
                "staged": {
                    "type": "boolean",
                    "description": "Show staged changes (--cached)"
                },
                "commit": {
                    "type": "string",
                    "description": "Commit hash or branch to compare"
                }
            }
        })
    }

    fn category(&self) -> ToolCategory {
        ToolCategory::VersionControl
    }

    async fn execute(&self, args: serde_json::Value) -> Layer3Result<String> {
        let path = args["path"].as_str();
        let file = args["file"].as_str();
        let staged = args["staged"].as_bool().unwrap_or(false);
        let commit = args["commit"].as_str();

        let mut git_args = vec!["diff"];
        if staged {
            git_args.push("--cached");
        }
        if let Some(c) = commit {
            git_args.push(c);
        }
        if let Some(f) = file {
            git_args.push("--");
            git_args.push(f);
        }

        run_git(&git_args, path)
    }
}

// ============================================================================
// Git Branch Tool
// ============================================================================

/// Git 分支工具
pub struct GitBranchTool;

#[async_trait]
impl BuiltinTool for GitBranchTool {
    fn name(&self) -> &str {
        "git_branch"
    }

    fn description(&self) -> &str {
        "List, create, or delete branches."
    }

    fn parameters_schema(&self) -> serde_json::Value {
        serde_json::json!({
            "type": "object",
            "properties": {
                "path": {
                    "type": "string",
                    "description": "Repository path (default: current directory)"
                },
                "action": {
                    "type": "string",
                    "enum": ["list", "create", "delete"],
                    "description": "Action to perform (default: list)"
                },
                "branch_name": {
                    "type": "string",
                    "description": "Branch name for create/delete"
                },
                "all": {
                    "type": "boolean",
                    "description": "List all branches including remote (default: false)"
                }
            }
        })
    }

    fn category(&self) -> ToolCategory {
        ToolCategory::VersionControl
    }

    fn requires_confirmation(&self) -> bool {
        true // Creating/deleting branches is a significant action
    }

    async fn execute(&self, args: serde_json::Value) -> Layer3Result<String> {
        let path = args["path"].as_str();
        let action = args["action"].as_str().unwrap_or("list");
        let branch_name = args["branch_name"].as_str();
        let all = args["all"].as_bool().unwrap_or(false);

        let git_args = match action {
            "list" => {
                let mut args = vec!["branch"];
                if all {
                    args.push("-a");
                }
                args
            }
            "create" => {
                let name = branch_name
                    .ok_or_else(|| anyhow::anyhow!("branch_name required for create"))?;
                vec!["branch", name]
            }
            "delete" => {
                let name = branch_name
                    .ok_or_else(|| anyhow::anyhow!("branch_name required for delete"))?;
                vec!["branch", "-D", name]
            }
            _ => return Err(anyhow::anyhow!("Invalid action: {}", action)),
        };

        run_git(&git_args, path)
    }
}

// ============================================================================
// Git Add Tool
// ============================================================================

/// Git Add 工具
pub struct GitAddTool;

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

    fn description(&self) -> &str {
        "Add file contents to the index."
    }

    fn parameters_schema(&self) -> serde_json::Value {
        serde_json::json!({
            "type": "object",
            "properties": {
                "path": {
                    "type": "string",
                    "description": "Repository path (default: current directory)"
                },
                "files": {
                    "type": "array",
                    "items": {"type": "string"},
                    "description": "Files to add (default: ['.'])"
                }
            }
        })
    }

    fn category(&self) -> ToolCategory {
        ToolCategory::VersionControl
    }

    fn requires_confirmation(&self) -> bool {
        true
    }

    async fn execute(&self, args: serde_json::Value) -> Layer3Result<String> {
        let path = args["path"].as_str();
        let files: Vec<&str> = if let Some(arr) = args["files"].as_array() {
            arr.iter().filter_map(|v| v.as_str()).collect()
        } else {
            vec!["."]
        };

        let mut git_args = vec!["add", "--"];
        git_args.extend(files);

        run_git(&git_args, path)
    }
}

// ============================================================================
// Git Commit Tool
// ============================================================================

/// Git Commit 工具
pub struct GitCommitTool;

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

    fn description(&self) -> &str {
        "Record changes to the repository."
    }

    fn parameters_schema(&self) -> serde_json::Value {
        serde_json::json!({
            "type": "object",
            "properties": {
                "path": {
                    "type": "string",
                    "description": "Repository path (default: current directory)"
                },
                "message": {
                    "type": "string",
                    "description": "Commit message"
                }
            },
            "required": ["message"]
        })
    }

    fn category(&self) -> ToolCategory {
        ToolCategory::VersionControl
    }

    fn requires_confirmation(&self) -> bool {
        true
    }

    fn is_dangerous(&self) -> bool {
        true
    }

    async fn execute(&self, args: serde_json::Value) -> Layer3Result<String> {
        let path = args["path"].as_str();
        let message = args["message"]
            .as_str()
            .ok_or_else(|| anyhow::anyhow!("Missing message parameter"))?;

        run_git(&["commit", "-m", message], path)
    }
}

// ============================================================================
// Git Show Tool
// ============================================================================

/// Git Show 工具
pub struct GitShowTool;

#[async_trait]
impl BuiltinTool for GitShowTool {
    fn name(&self) -> &str {
        "git_show"
    }

    fn description(&self) -> &str {
        "Show various types of objects (commits, tags, trees)."
    }

    fn parameters_schema(&self) -> serde_json::Value {
        serde_json::json!({
            "type": "object",
            "properties": {
                "path": {
                    "type": "string",
                    "description": "Repository path (default: current directory)"
                },
                "object": {
                    "type": "string",
                    "description": "Object to show (commit hash, tag, etc.)"
                },
                "stat": {
                    "type": "boolean",
                    "description": "Show diffstat instead of full diff (default: true)"
                }
            },
            "required": ["object"]
        })
    }

    fn category(&self) -> ToolCategory {
        ToolCategory::VersionControl
    }

    async fn execute(&self, args: serde_json::Value) -> Layer3Result<String> {
        let path = args["path"].as_str();
        let object = args["object"]
            .as_str()
            .ok_or_else(|| anyhow::anyhow!("Missing object parameter"))?;
        let stat = args["stat"].as_bool().unwrap_or(true);

        let mut git_args = vec!["show"];
        if stat {
            git_args.push("--stat");
        }
        git_args.push(object);

        run_git(&git_args, path)
    }
}

// ============================================================================
// Git Stash Tool
// ============================================================================

/// Git Stash 工具
pub struct GitStashTool;

#[async_trait]
impl BuiltinTool for GitStashTool {
    fn name(&self) -> &str {
        "git_stash"
    }

    fn description(&self) -> &str {
        "Stash the changes in a dirty working directory."
    }

    fn parameters_schema(&self) -> serde_json::Value {
        serde_json::json!({
            "type": "object",
            "properties": {
                "path": {
                    "type": "string",
                    "description": "Repository path (default: current directory)"
                },
                "action": {
                    "type": "string",
                    "enum": ["push", "pop", "list", "drop"],
                    "description": "Action to perform (default: list)"
                },
                "message": {
                    "type": "string",
                    "description": "Stash message (for push)"
                }
            }
        })
    }

    fn category(&self) -> ToolCategory {
        ToolCategory::VersionControl
    }

    fn requires_confirmation(&self) -> bool {
        true
    }

    async fn execute(&self, args: serde_json::Value) -> Layer3Result<String> {
        let path = args["path"].as_str();
        let action = args["action"].as_str().unwrap_or("list");
        let message = args["message"].as_str();

        let git_args = match action {
            "push" => {
                let mut args = vec!["stash", "push"];
                if let Some(msg) = message {
                    args.push("-m");
                    args.push(msg);
                }
                args
            }
            "pop" => vec!["stash", "pop"],
            "list" => vec!["stash", "list"],
            "drop" => vec!["stash", "drop"],
            _ => return Err(anyhow::anyhow!("Invalid action: {}", action)),
        };

        run_git(&git_args, path)
    }
}

// ============================================================================
// Tests
// ============================================================================

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

    #[test]
    fn test_git_status_category() {
        let tool = GitStatusTool;
        assert_eq!(tool.category(), ToolCategory::VersionControl);
    }

    #[test]
    fn test_git_commit_is_dangerous() {
        let tool = GitCommitTool;
        assert!(tool.is_dangerous());
        assert!(tool.requires_confirmation());
    }

    #[test]
    fn test_git_add_requires_confirmation() {
        let tool = GitAddTool;
        assert!(tool.requires_confirmation());
    }
}