task_queue_tools.py 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137
  1. # app/services/agent/tools/builtin/task_queue_tools.py
  2. from typing import Optional, Dict, Any, List
  3. from sqlalchemy.ext.asyncio import AsyncSession
  4. from sqlalchemy import select, desc
  5. from app.models.user import VasUser
  6. from app.models.vas_task import VasTask
  7. from app.services.agent.tools.registry import agent_tool
  8. from app.core.logger import logger
  9. ADMIN_CHECK_MSG = "Permission denied: This operation is restricted to system administrators (admin)"
  10. @agent_tool(
  11. name="list_automation_tasks",
  12. description="查询后台自动化任务执行队列(vas_tasks),支持按任务状态(pending-待执行, running-执行中, grabbed-已抢位, completed-已完成, pause-已暂停, cancelled-已取消)、关联订单号、routing_key 筛选",
  13. )
  14. async def list_automation_tasks(
  15. status: Optional[str] = None,
  16. order_id: Optional[str] = None,
  17. routing_key: Optional[str] = None,
  18. limit: int = 15,
  19. offset: int = 0,
  20. *,
  21. db: AsyncSession,
  22. current_user: VasUser,
  23. ) -> Dict[str, Any]:
  24. """查询自动化任务队列"""
  25. if current_user.role != "admin":
  26. return {"error": ADMIN_CHECK_MSG}
  27. limit = max(1, min(limit, 50))
  28. offset = max(0, offset)
  29. stmt = select(VasTask)
  30. if status and status.strip():
  31. stmt = stmt.where(VasTask.status == status.strip().lower())
  32. if order_id and order_id.strip():
  33. stmt = stmt.where(VasTask.order_id == order_id.strip())
  34. if routing_key and routing_key.strip():
  35. stmt = stmt.where(VasTask.routing_key.ilike(f"%{routing_key.strip()}%"))
  36. stmt = stmt.order_by(desc(VasTask.created_at)).offset(offset).limit(limit)
  37. res = await db.execute(stmt)
  38. tasks = res.scalars().all()
  39. items = []
  40. for t in tasks:
  41. items.append({
  42. "task_id": t.id,
  43. "order_id": t.order_id,
  44. "routing_key": t.routing_key,
  45. "status": t.status,
  46. "priority": t.priority,
  47. "attempt_count": t.attempt_count,
  48. "created_at": t.created_at.strftime("%Y-%m-%d %H:%M:%S") if t.created_at else None,
  49. "updated_at": t.updated_at.strftime("%Y-%m-%d %H:%M:%S") if t.updated_at else None,
  50. })
  51. return {
  52. "count": len(items),
  53. "tasks": items,
  54. }
  55. @agent_tool(
  56. name="get_automation_task_detail",
  57. description="获取指定自动化任务ID的完整执行状态、重试次数、抢位结果与上下文参数",
  58. )
  59. async def get_automation_task_detail(
  60. task_id: int,
  61. *,
  62. db: AsyncSession,
  63. current_user: VasUser,
  64. ) -> Dict[str, Any]:
  65. """查询自动化任务详情"""
  66. if current_user.role != "admin":
  67. return {"error": ADMIN_CHECK_MSG}
  68. t = await db.get(VasTask, task_id)
  69. if not t:
  70. return {"error": f"Automation task #{task_id} does not exist"}
  71. return {
  72. "task_id": t.id,
  73. "order_id": t.order_id,
  74. "routing_key": t.routing_key,
  75. "status": t.status,
  76. "priority": t.priority,
  77. "attempt_count": t.attempt_count,
  78. "grabbed_history": t.grabbed_history,
  79. "meta": t.meta,
  80. "created_at": t.created_at.strftime("%Y-%m-%d %H:%M:%S") if t.created_at else None,
  81. "updated_at": t.updated_at.strftime("%Y-%m-%d %H:%M:%S") if t.updated_at else None,
  82. }
  83. @agent_tool(
  84. name="admin_update_task_status",
  85. description="修改自动化任务状态(如将任务重置为 pending 进行重试,或设为 pause / cancelled 终止执行)",
  86. is_dangerous=True,
  87. )
  88. async def admin_update_task_status(
  89. task_id: int,
  90. new_status: str,
  91. *,
  92. db: AsyncSession,
  93. current_user: VasUser,
  94. ) -> Dict[str, Any]:
  95. """管理员更新自动化任务状态"""
  96. if current_user.role != "admin":
  97. return {"error": ADMIN_CHECK_MSG}
  98. clean_status = new_status.strip().lower()
  99. valid_statuses = {"pending", "running", "grabbed", "completed", "pause", "cancelled"}
  100. if clean_status not in valid_statuses:
  101. return {"error": f"Invalid task status '{clean_status}'. Valid: {sorted(list(valid_statuses))}"}
  102. t = await db.get(VasTask, task_id)
  103. if not t:
  104. return {"error": f"Automation task #{task_id} does not exist"}
  105. old_status = t.status
  106. t.status = clean_status
  107. if clean_status == "pending":
  108. t.attempt_count = 0 # 重置重试次数
  109. await db.commit()
  110. await db.refresh(t)
  111. logger.info(f"🔄 [AI_AGENT] Updated task #{task_id}: {old_status} -> {clean_status} by admin={current_user.id}")
  112. return {
  113. "success": True,
  114. "task_id": t.id,
  115. "previous_status": old_status,
  116. "new_status": t.status,
  117. }