AI coding agents can edit files, run shell commands, and touch infrastructure. One bad rm -rf, force-push, or docker compose down -v can wipe hours of work or production data.
| 1 | # SPDX-License-Identifier: MIT |
| 2 | """Typer CLI for agent-guard.""" |
| 3 | |
| 4 | from __future__ import annotations |
| 5 | |
| 6 | import sys |
| 7 | from pathlib import Path |
| 8 | |
| 9 | import typer |
| 10 | from rich.console import Console |
| 11 | |
| 12 | from agent_guard import __version__ |
| 13 | from agent_guard.commands import run_command |
| 14 | from agent_guard.config import ( |
| 15 | CONFIG_FILENAME, |
| 16 | GuardConfig, |
| 17 | build_init_config, |
| 18 | detect_project_signals, |
| 19 | load_config, |
| 20 | write_config, |
| 21 | ) |
| 22 | from agent_guard.evaluator import evaluate_command, evaluate_file_operation |
| 23 | from agent_guard.models import Decision, PolicyMode |
| 24 | from agent_guard.output import ( |
| 25 | EXIT_ERROR, |
| 26 | decision_exit_code, |
| 27 | format_rules_json, |
| 28 | format_rules_text, |
| 29 | format_scan_json, |
| 30 | format_scan_text, |
| 31 | print_result, |
| 32 | ) |
| 33 | from agent_guard.redactor import redact |
| 34 | from agent_guard.rules import all_rule_definitions |
| 35 | from agent_guard.scanner import scan_project |
| 36 | |
| 37 | app = typer.Typer( |
| 38 | name="agent-guard", |
| 39 | help="Local-first security layer for AI coding agents. Deterministic. Offline. No LLM.", |
| 40 | no_args_is_help=True, |
| 41 | add_completion=False, |
| 42 | ) |
| 43 | |
| 44 | console = Console(highlight=False) |
| 45 | err_console = Console(stderr=True, highlight=False) |
| 46 | |
| 47 | |
| 48 | def _load(config_path: Path | None, project_root: Path | None) -> GuardConfig: |
| 49 | try: |
| 50 | return load_config(config_path, project_root=project_root) |
| 51 | except Exception as exc: |
| 52 | err_console.print(redact(f"Configuration error: {exc}")) |
| 53 | raise typer.Exit(EXIT_ERROR) from exc |
| 54 | |
| 55 | |
| 56 | @app.callback() |
| 57 | def main_callback( |
| 58 | ctx: typer.Context, |
| 59 | debug: bool = typer.Option(False, "--debug", help="Enable debug output (secrets redacted)."), |
| 60 | config: Path | None = typer.Option( |
| 61 | None, |
| 62 | "--config", |
| 63 | "-c", |
| 64 | help="Path to .agent-guard.yml", |
| 65 | exists=False, |
| 66 | dir_okay=False, |
| 67 | ), |
| 68 | ) -> None: |
| 69 | ctx.ensure_object(dict) |
| 70 | ctx.obj["debug"] = debug |
| 71 | ctx.obj["config_path"] = config |
| 72 | if debug: |
| 73 | err_console.print("[dim]debug: agent-guard starting (secrets redacted)[/dim]") |
| 74 | |
| 75 | |
| 76 | @app.command("version") |
| 77 | def version_cmd() -> None: |
| 78 | """Show version.""" |
| 79 | typer.echo(__version__) |
| 80 | |
| 81 | |
| 82 | @app.command("check") |
| 83 | def check_cmd( |
| 84 | ctx: typer.Context, |
| 85 | command: str | None = typer.Argument(None, help="Command string to analyze (not executed)."), |
| 86 | file_operation: str | None = typer.Option( |
| 87 | None, |
| 88 | "--file-operation", |
| 89 | help="File operation type: delete, read, write", |
| 90 | ), |
| 91 | path: str | None = typer.Argument( |
| 92 | None, |
| 93 | help="Path for --file-operation", |
| 94 | ), |
| 95 | json_output: bool = typer.Option(False, "--json", help="Machine-readable JSON output"), |
| 96 | ) -> None: |
| 97 | """Analyze a command or file operation without executing it.""" |
| 98 | cfg = _load(ctx.obj.get("config_path"), None) |
| 99 | |
| 100 | if file_operation: |
| 101 | target = path or command |
| 102 | if not target: |
| 103 | err_console.print("Provide a path for --file-operation") |
| 104 | raise typer.Exit(EXIT_ERROR) |
| 105 | result = evaluate_file_operation(file_operation, target, cfg) |
| 106 | elif command: |
| 107 | result = evaluate_command(command, cfg) |
| 108 | else: |
| 109 | err_console.print('Usage: agent-guard check "command"') |
| 110 | raise typer.Exit(EXIT_ERROR) |
| 111 | |
| 112 | if ctx.obj.get("debug"): |
| 113 | err_console.print(redact(f"debug: score={result.score} findings={len(result.findings)}")) |
| 114 | |
| 115 | print_result(result, json_mode=json_output, console=console) |
| 116 | raise typer.Exit(decision_exit_code(result.decision)) |
| 117 | |
| 118 | |
| 119 | @app.command( |
| 120 | "run", |
| 121 | context_settings={"allow_extra_args": True, "ignore_unknown_options": True}, |
| 122 | ) |
| 123 | def run_cmd( |
| 124 | ctx: typer.Context, |
| 125 | allow_risk: bool = typer.Option( |
| 126 | False, |
| 127 | "--allow-risk", |
| 128 | help="Explicitly allow WARN decisions (never overrides BLOCK).", |
| 129 | ), |
| 130 | yes: bool = typer.Option(False, "--yes", "-y", help="Same as --allow-risk for WARN."), |
| 131 | json_output: bool = typer.Option(False, "--json", help="JSON summary on stderr policy events"), |
| 132 | ) -> None: |
| 133 | """Evaluate then execute a command (shell=False). Use: agent-guard run -- cmd args""" |
| 134 | argv = list(ctx.args) |
| 135 | # Support `--` separator already stripped by typer |
| 136 | if argv and argv[0] == "--": |
| 137 | argv = argv[1:] |
| 138 | |
| 139 | if not argv: |
| 140 | err_console.print("Usage: agent-guard run -- <command> [args...]") |
| 141 | raise typer.Exit(EXIT_ERROR) |
| 142 | |
| 143 | cfg = _load(ctx.obj.get("config_path"), None) |
| 144 | outcome = run_command( |
| 145 | argv, |
| 146 | cfg, |
| 147 | allow_risk=allow_risk or yes, |
| 148 | yes=yes, |
| 149 | json_mode=json_output, |
| 150 | ) |
| 151 | |
| 152 | if outcome.result.decision != Decision.ALLOW or not outcome.executed: |
| 153 | if json_output: |
| 154 | from agent_guard.output import format_result_json |
| 155 | |
| 156 | sys.stderr.write(format_result_json(outcome.result)) |
| 157 | else: |
| 158 | print_result(outcome.result, json_mode=False, console=err_console) |
| 159 | if outcome.message: |
| 160 | err_console.print() |
| 161 | err_console.print(redact(outcome.message)) |
| 162 | |
| 163 | if not outcome.executed: |
| 164 | # Map to decision exit codes for policy denials |
| 165 | if outcome.result.decision == Decision.BLOCK: |
| 166 | raise typer.Exit(20) |
| 167 | if outcome.result.decision == Decision.WARN: |
| 168 | raise typer.Exit(10) |
| 169 | raise typer.Exit(outcome.exit_code) |
| 170 | |
| 171 | raise typer.Exit(outcome.exit_code) |
| 172 | |
| 173 | |
| 174 | @app.command("init") |
| 175 | def init_cmd( |
| 176 | ctx: typer.Context, |
| 177 | force: bool = typer.Option(False, "--force", help="Overwrite existing config"), |
| 178 | mode: str = typer.Option("default", "--mode", help="default | strict | permissive"), |
| 179 | ) -> None: |
| 180 | """Create .agent-guard.yml for the current project.""" |
| 181 | root = Path.cwd().resolve() |
| 182 | dest = root / CONFIG_FILENAME |
| 183 | if dest.exists() and not force: |
| 184 | err_console.print(f"{CONFIG_FILENAME} already exists. Use --force to overwrite.") |
| 185 | raise typer.Exit(EXIT_ERROR) |
| 186 | |
| 187 | try: |
| 188 | policy_mode = PolicyMode(mode.lower()) |
| 189 | except ValueError as exc: |
| 190 | err_console.print(f"Invalid mode: {mode}") |
| 191 | raise typer.Exit(EXIT_ERROR) from exc |
| 192 | |
| 193 | signals = detect_project_signals(root) |
| 194 | labels = { |
| 195 | "git": "Git repository detected", |
| 196 | "node": "Node.js project detected", |
| 197 | "python": "Python project detected", |
| 198 | "docker": "Docker Compose detected", |
| 199 | "mongodb": "MongoDB configuration detected", |
| 200 | "postgres": "PostgreSQL configuration detected", |
| 201 | "mysql": "MySQL configuration detected", |
| 202 | "redis": "Redis configuration detected", |
| 203 | "env_file": ".env file detected (path only; values not read)", |
| 204 | } |
| 205 | for key, label in labels.items(): |
| 206 | if signals.get(key): |
| 207 | console.print(f"[+] {label}") |
| 208 | |
| 209 | cfg = build_init_config(root, mode=policy_mode) |
| 210 | write_config(dest, cfg) |
| 211 | console.print() |
| 212 | console.print("Created:") |
| 213 | console.print(CONFIG_FILENAME) |
| 214 | |
| 215 | |
| 216 | @app.command("scan") |
| 217 | def scan_cmd( |
| 218 | ctx: typer.Context, |
| 219 | json_output: bool = typer.Option(False, "--json", help="JSON output"), |
| 220 | ) -> None: |
| 221 | """Scan the project for risky configuration (never prints secrets).""" |
| 222 | cfg = _load(ctx.obj.get("config_path"), None) |
| 223 | result = scan_project(cfg.project_root, cfg) |
| 224 | if json_output: |
| 225 | sys.stdout.write(format_scan_json(result)) |
| 226 | else: |
| 227 | sys.stdout.write(format_scan_text(result)) |
| 228 | raise typer.Exit(0) |
| 229 | |
| 230 | |
| 231 | @app.command("rules") |
| 232 | def rules_cmd( |
| 233 | json_output: bool = typer.Option(False, "--json", help="JSON output"), |
| 234 | ) -> None: |
| 235 | """List all built-in security rules.""" |
| 236 | rules = list(all_rule_definitions()) |
| 237 | if json_output: |
| 238 | sys.stdout.write(format_rules_json(rules)) |
| 239 | else: |
| 240 | sys.stdout.write(format_rules_text(rules)) |
| 241 | raise typer.Exit(0) |
| 242 | |
| 243 | |
| 244 | @app.command("config") |
| 245 | def config_cmd( |
| 246 | ctx: typer.Context, |
| 247 | json_output: bool = typer.Option(False, "--json", help="JSON output"), |
| 248 | show: bool = typer.Option(True, "--show/--no-show", help="Show effective config"), |
| 249 | ) -> None: |
| 250 | """Show effective configuration.""" |
| 251 | cfg = _load(ctx.obj.get("config_path"), None) |
| 252 | if not show: |
| 253 | raise typer.Exit(0) |
| 254 | data = cfg.to_dict() |
| 255 | if cfg.config_path: |
| 256 | data["config_path"] = str(cfg.config_path) |
| 257 | if json_output: |
| 258 | import json |
| 259 | |
| 260 | from agent_guard.output import _redact_obj |
| 261 | |
| 262 | sys.stdout.write(json.dumps(_redact_obj(data), indent=2, sort_keys=True) + "\n") |
| 263 | else: |
| 264 | import yaml |
| 265 | |
| 266 | console.print(yaml.safe_dump(data, default_flow_style=False, sort_keys=False)) |
| 267 | raise typer.Exit(0) |
| 268 | |
| 269 | |
| 270 | def main() -> None: |
| 271 | """Console script entry point.""" |
| 272 | # Support `agent-guard --version` |
| 273 | if len(sys.argv) == 2 and sys.argv[1] in {"--version", "-V"}: |
| 274 | typer.echo(__version__) |
| 275 | sys.exit(0) |
| 276 | app() |
| 277 | |
| 278 | |
| 279 | if __name__ == "__main__": |
| 280 | main() |