|
| 1 | +#!/usr/bin/env python3 |
| 2 | +""" |
| 3 | +atq - Agent Task Queue CLI |
| 4 | +
|
| 5 | +Simple CLI to inspect the task queue. |
| 6 | +""" |
| 7 | + |
| 8 | +import argparse |
| 9 | +import os |
| 10 | +import sqlite3 |
| 11 | +from datetime import datetime |
| 12 | +from pathlib import Path |
| 13 | + |
| 14 | + |
| 15 | +def get_data_dir(args): |
| 16 | + """Get data directory from args or environment.""" |
| 17 | + if args.data_dir: |
| 18 | + return Path(args.data_dir) |
| 19 | + return Path(os.environ.get("TASK_QUEUE_DATA_DIR", "/tmp/agent-task-queue")) |
| 20 | + |
| 21 | + |
| 22 | +def cmd_list(args): |
| 23 | + """List all tasks in the queue.""" |
| 24 | + data_dir = get_data_dir(args) |
| 25 | + db_path = data_dir / "queue.db" |
| 26 | + |
| 27 | + if not db_path.exists(): |
| 28 | + print(f"No queue database found at {db_path}") |
| 29 | + print("Queue is empty (no tasks have been run yet)") |
| 30 | + return |
| 31 | + |
| 32 | + conn = sqlite3.connect(db_path, timeout=5.0) |
| 33 | + conn.row_factory = sqlite3.Row |
| 34 | + |
| 35 | + try: |
| 36 | + rows = conn.execute( |
| 37 | + "SELECT * FROM queue ORDER BY queue_name, id" |
| 38 | + ).fetchall() |
| 39 | + |
| 40 | + if not rows: |
| 41 | + print("Queue is empty") |
| 42 | + return |
| 43 | + |
| 44 | + # Group by queue name |
| 45 | + queues = {} |
| 46 | + for row in rows: |
| 47 | + qname = row["queue_name"] |
| 48 | + if qname not in queues: |
| 49 | + queues[qname] = [] |
| 50 | + queues[qname].append(row) |
| 51 | + |
| 52 | + for qname, tasks in queues.items(): |
| 53 | + print(f"\n[{qname}] ({len(tasks)} task(s))") |
| 54 | + print("-" * 50) |
| 55 | + |
| 56 | + for task in tasks: |
| 57 | + status = task["status"].upper() |
| 58 | + task_id = task["id"] |
| 59 | + pid = task["pid"] or "-" |
| 60 | + child_pid = task["child_pid"] or "-" |
| 61 | + created = task["created_at"] |
| 62 | + |
| 63 | + # Format timestamp |
| 64 | + if created: |
| 65 | + try: |
| 66 | + dt = datetime.fromisoformat(created) |
| 67 | + created = dt.strftime("%H:%M:%S") |
| 68 | + except ValueError: |
| 69 | + pass |
| 70 | + |
| 71 | + status_icon = "🔄" if status == "RUNNING" else "⏳" |
| 72 | + print(f" {status_icon} #{task_id} {status} (pid={pid}, child={child_pid}) @ {created}") |
| 73 | + |
| 74 | + finally: |
| 75 | + conn.close() |
| 76 | + |
| 77 | + |
| 78 | +def cmd_clear(args): |
| 79 | + """Clear all tasks from the queue.""" |
| 80 | + data_dir = get_data_dir(args) |
| 81 | + db_path = data_dir / "queue.db" |
| 82 | + |
| 83 | + if not db_path.exists(): |
| 84 | + print("No queue database found") |
| 85 | + return |
| 86 | + |
| 87 | + conn = sqlite3.connect(db_path, timeout=5.0) |
| 88 | + try: |
| 89 | + # Check how many tasks exist |
| 90 | + count = conn.execute("SELECT COUNT(*) FROM queue").fetchone()[0] |
| 91 | + if count == 0: |
| 92 | + print("Queue is already empty") |
| 93 | + return |
| 94 | + |
| 95 | + response = input(f"Clear {count} task(s) from queue? [y/N] ") |
| 96 | + if response.lower() != 'y': |
| 97 | + print("Cancelled") |
| 98 | + return |
| 99 | + |
| 100 | + cursor = conn.execute("DELETE FROM queue") |
| 101 | + conn.commit() |
| 102 | + print(f"Cleared {cursor.rowcount} task(s) from queue") |
| 103 | + finally: |
| 104 | + conn.close() |
| 105 | + |
| 106 | + |
| 107 | +def cmd_logs(args): |
| 108 | + """Show recent log entries.""" |
| 109 | + data_dir = get_data_dir(args) |
| 110 | + log_path = data_dir / "agent-task-queue-logs.json" |
| 111 | + |
| 112 | + if not log_path.exists(): |
| 113 | + print(f"No log file found at {log_path}") |
| 114 | + return |
| 115 | + |
| 116 | + import json |
| 117 | + |
| 118 | + lines = log_path.read_text().strip().split("\n") |
| 119 | + recent = lines[-args.n:] if len(lines) > args.n else lines |
| 120 | + |
| 121 | + for line in recent: |
| 122 | + try: |
| 123 | + entry = json.loads(line) |
| 124 | + ts = entry.get("timestamp", "")[:19].replace("T", " ") |
| 125 | + event = entry.get("event", "unknown") |
| 126 | + task_id = entry.get("task_id", "") |
| 127 | + queue = entry.get("queue_name", "") |
| 128 | + |
| 129 | + # Format based on event type |
| 130 | + if event == "task_completed": |
| 131 | + exit_code = entry.get("exit_code", "?") |
| 132 | + duration = entry.get("duration_seconds", "?") |
| 133 | + print(f"{ts} [{queue}] #{task_id} completed exit={exit_code} {duration}s") |
| 134 | + elif event == "task_started": |
| 135 | + wait = entry.get("wait_time_seconds", 0) |
| 136 | + print(f"{ts} [{queue}] #{task_id} started (waited {wait}s)") |
| 137 | + elif event == "task_queued": |
| 138 | + print(f"{ts} [{queue}] #{task_id} queued") |
| 139 | + elif event == "task_timeout": |
| 140 | + print(f"{ts} [{queue}] #{task_id} TIMEOUT") |
| 141 | + elif event == "task_error": |
| 142 | + error = entry.get("error", "?") |
| 143 | + print(f"{ts} [{queue}] #{task_id} ERROR: {error}") |
| 144 | + elif event == "zombie_cleared": |
| 145 | + reason = entry.get("reason", "?") |
| 146 | + print(f"{ts} [{queue}] #{task_id} zombie cleared ({reason})") |
| 147 | + else: |
| 148 | + print(f"{ts} {event}") |
| 149 | + except json.JSONDecodeError: |
| 150 | + print(line) |
| 151 | + |
| 152 | + |
| 153 | +def main(): |
| 154 | + parser = argparse.ArgumentParser( |
| 155 | + prog="atq", |
| 156 | + description="Agent Task Queue CLI - inspect and manage the task queue", |
| 157 | + ) |
| 158 | + parser.add_argument( |
| 159 | + "--data-dir", |
| 160 | + help="Data directory (default: $TASK_QUEUE_DATA_DIR or /tmp/agent-task-queue)", |
| 161 | + ) |
| 162 | + |
| 163 | + subparsers = parser.add_subparsers(dest="command", help="Commands") |
| 164 | + |
| 165 | + # list |
| 166 | + subparsers.add_parser("list", help="List tasks in queue") |
| 167 | + |
| 168 | + # clear |
| 169 | + subparsers.add_parser("clear", help="Clear all tasks from queue") |
| 170 | + |
| 171 | + # logs |
| 172 | + logs_parser = subparsers.add_parser("logs", help="Show recent log entries") |
| 173 | + logs_parser.add_argument("-n", type=int, default=20, help="Number of entries (default: 20)") |
| 174 | + |
| 175 | + args = parser.parse_args() |
| 176 | + |
| 177 | + if args.command == "list": |
| 178 | + cmd_list(args) |
| 179 | + elif args.command == "clear": |
| 180 | + cmd_clear(args) |
| 181 | + elif args.command == "logs": |
| 182 | + cmd_logs(args) |
| 183 | + else: |
| 184 | + parser.print_help() |
| 185 | + |
| 186 | + |
| 187 | +if __name__ == "__main__": |
| 188 | + main() |
0 commit comments