|
| 1 | +"""Agents command for the Codegen CLI.""" |
| 2 | + |
| 3 | +import requests |
| 4 | +import typer |
| 5 | +from rich.console import Console |
| 6 | +from rich.table import Table |
| 7 | + |
| 8 | +from codegen.cli.api.endpoints import API_ENDPOINT |
| 9 | +from codegen.cli.auth.token_manager import get_current_token |
| 10 | +from codegen.cli.rich.spinners import create_spinner |
| 11 | +from codegen.cli.utils.org import resolve_org_id |
| 12 | + |
| 13 | +console = Console() |
| 14 | + |
| 15 | +# Create the agents app |
| 16 | +agents_app = typer.Typer(help="Manage Codegen agents") |
| 17 | + |
| 18 | + |
| 19 | +@agents_app.command("list") |
| 20 | +def list_agents(org_id: int | None = typer.Option(None, help="Organization ID (defaults to CODEGEN_ORG_ID/REPOSITORY_ORG_ID or auto-detect)")): |
| 21 | + """List agent runs from the Codegen API.""" |
| 22 | + # Get the current token |
| 23 | + token = get_current_token() |
| 24 | + if not token: |
| 25 | + console.print("[red]Error:[/red] Not authenticated. Please run 'codegen login' first.") |
| 26 | + raise typer.Exit(1) |
| 27 | + |
| 28 | + try: |
| 29 | + # Resolve org id |
| 30 | + resolved_org_id = resolve_org_id(org_id) |
| 31 | + if resolved_org_id is None: |
| 32 | + console.print("[red]Error:[/red] Organization ID not provided. Pass --org-id, set CODEGEN_ORG_ID, or REPOSITORY_ORG_ID.") |
| 33 | + raise typer.Exit(1) |
| 34 | + |
| 35 | + # Make API request to list agent runs with spinner |
| 36 | + spinner = create_spinner("Fetching agent runs...") |
| 37 | + spinner.start() |
| 38 | + |
| 39 | + try: |
| 40 | + headers = {"Authorization": f"Bearer {token}"} |
| 41 | + url = f"{API_ENDPOINT.rstrip('/')}/v1/organizations/{resolved_org_id}/agent/runs" |
| 42 | + response = requests.get(url, headers=headers) |
| 43 | + response.raise_for_status() |
| 44 | + response_data = response.json() |
| 45 | + finally: |
| 46 | + spinner.stop() |
| 47 | + |
| 48 | + # Extract agent runs from the response structure |
| 49 | + agent_runs = response_data.get("items", []) |
| 50 | + total = response_data.get("total", 0) |
| 51 | + page = response_data.get("page", 1) |
| 52 | + page_size = response_data.get("page_size", 10) |
| 53 | + |
| 54 | + if not agent_runs: |
| 55 | + console.print("[yellow]No agent runs found.[/yellow]") |
| 56 | + return |
| 57 | + |
| 58 | + # Create a table to display agent runs |
| 59 | + table = Table( |
| 60 | + title=f"Agent Runs (Page {page}, Total: {total})", |
| 61 | + border_style="blue", |
| 62 | + show_header=True, |
| 63 | + title_justify="center", |
| 64 | + ) |
| 65 | + table.add_column("ID", style="cyan", no_wrap=True) |
| 66 | + table.add_column("Status", style="white", justify="center") |
| 67 | + table.add_column("Source", style="magenta") |
| 68 | + table.add_column("Created", style="dim") |
| 69 | + table.add_column("Result", style="green") |
| 70 | + |
| 71 | + # Add agent runs to table |
| 72 | + for agent_run in agent_runs: |
| 73 | + run_id = str(agent_run.get("id", "Unknown")) |
| 74 | + status = agent_run.get("status", "Unknown") |
| 75 | + source_type = agent_run.get("source_type", "Unknown") |
| 76 | + created_at = agent_run.get("created_at", "Unknown") |
| 77 | + result = agent_run.get("result", "") |
| 78 | + |
| 79 | + # Status with emoji |
| 80 | + status_display = status |
| 81 | + if status == "COMPLETE": |
| 82 | + status_display = "✅ Complete" |
| 83 | + elif status == "RUNNING": |
| 84 | + status_display = "🏃 Running" |
| 85 | + elif status == "FAILED": |
| 86 | + status_display = "❌ Failed" |
| 87 | + elif status == "STOPPED": |
| 88 | + status_display = "⏹️ Stopped" |
| 89 | + elif status == "PENDING": |
| 90 | + status_display = "⏳ Pending" |
| 91 | + |
| 92 | + # Format created date (just show date and time, not full timestamp) |
| 93 | + if created_at and created_at != "Unknown": |
| 94 | + try: |
| 95 | + # Parse and format the timestamp to be more readable |
| 96 | + from datetime import datetime |
| 97 | + |
| 98 | + dt = datetime.fromisoformat(created_at.replace("Z", "+00:00")) |
| 99 | + created_display = dt.strftime("%m/%d %H:%M") |
| 100 | + except (ValueError, TypeError): |
| 101 | + created_display = created_at[:16] if len(created_at) > 16 else created_at |
| 102 | + else: |
| 103 | + created_display = created_at |
| 104 | + |
| 105 | + # Truncate result if too long |
| 106 | + result_display = result[:50] + "..." if result and len(result) > 50 else result or "No result" |
| 107 | + |
| 108 | + table.add_row(run_id, status_display, source_type, created_display, result_display) |
| 109 | + |
| 110 | + console.print(table) |
| 111 | + console.print(f"\n[green]Showing {len(agent_runs)} of {total} agent runs[/green]") |
| 112 | + |
| 113 | + except requests.RequestException as e: |
| 114 | + console.print(f"[red]Error fetching agent runs:[/red] {e}", style="bold red") |
| 115 | + raise typer.Exit(1) |
| 116 | + except Exception as e: |
| 117 | + console.print(f"[red]Unexpected error:[/red] {e}", style="bold red") |
| 118 | + raise typer.Exit(1) |
| 119 | + |
| 120 | + |
| 121 | +# Default callback for the agents app |
| 122 | +@agents_app.callback(invoke_without_command=True) |
| 123 | +def agents_callback(ctx: typer.Context): |
| 124 | + """Manage Codegen agents.""" |
| 125 | + if ctx.invoked_subcommand is None: |
| 126 | + # If no subcommand is provided, run list by default |
| 127 | + list_agents(org_id=None) |
0 commit comments