//! Generic tool for running arbitrary git subcommands. use std::process::Command; use serde_json::{json, Value}; use anyhow::{Result, anyhow}; use super::Tool; use super::ToolCtx; /// Tool that runs `git [args...]` and returns combined stdout/stderr. pub struct GitOperator; impl Tool for GitOperator { fn name(&self) -> &'static str { "git_operator" } fn description(&self) -> &'static str { "Execute git operations" } fn parameters(&self) -> Value { json!({ "type": "object", "properties": { "operation": { "type": "string", "description": "Git subcommand to execute (e.g. 'add', 'commit', 'status')" }, "args": { "type": "array", "items": {"type": "string"}, "description": "Arguments for the git subcommand" } }, "required": ["operation", "args"] }) } /// Run `git [args...]` and return its combined output. /// /// Flow: extract `operation` + `args` → gate through `shell_filter::git` /// to block destructive operations → spawn `git ` → /// trim and join stdout/stderr. /// /// Why: reconstructing the command string for the shell filter prevents /// the model (or a subagent) from running destructive git operations /// that would otherwise bypass the filter by going through this tool /// instead of the `bash` tool. /// /// Return: trimmed combined output on success; error including exit code and /// stderr on failure. fn run(&self, _ctx: &ToolCtx, args: &Value) -> Result { let operation = args.get("operation") .and_then(|v| v.as_str()) .ok_or_else(|| anyhow!("missing required argument: operation"))? .to_string(); let arg_list: Vec = args.get("args") .and_then(|v| v.as_array()) .map(|arr| { arr.iter() .filter_map(|v| v.as_str().map(|s| s.to_string())) .collect() }) .ok_or_else(|| anyhow!("missing required argument: args"))?; // Gate through the destructive git filter — same filter used by // the `bash` tool, so destructive operations are blocked regardless // of which tool the model uses. let cmd_for_filter = format!("git {} {}", operation, arg_list.join(" ")); crate::tool::shell_filter::git::check_git_destructive(&cmd_for_filter) .map_err(|e| anyhow!("blocked: {}", e))?; let output = Command::new("git") .arg(&operation) .args(&arg_list) .output() .map_err(|e| anyhow!("git {} failed: {}", operation, e))?; let stdout = String::from_utf8_lossy(&output.stdout).to_string(); let stderr = String::from_utf8_lossy(&output.stderr).to_string(); let combined = if stderr.is_empty() { stdout.trim().to_string() } else { format!("{}\n{}", stdout.trim(), stderr.trim()) }; if output.status.success() { Ok(combined) } else { anyhow::bail!("git {} failed (exit {}): {}", operation, output.status.code().unwrap_or(-1), stderr.trim()) } } }