| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137 |
- # app/services/agent/tools/builtin/task_queue_tools.py
- from typing import Optional, Dict, Any, List
- from sqlalchemy.ext.asyncio import AsyncSession
- from sqlalchemy import select, desc
- from app.models.user import VasUser
- from app.models.vas_task import VasTask
- from app.services.agent.tools.registry import agent_tool
- from app.core.logger import logger
- ADMIN_CHECK_MSG = "Permission denied: This operation is restricted to system administrators (admin)"
- @agent_tool(
- name="list_automation_tasks",
- description="查询后台自动化任务执行队列(vas_tasks),支持按任务状态(pending-待执行, running-执行中, grabbed-已抢位, completed-已完成, pause-已暂停, cancelled-已取消)、关联订单号、routing_key 筛选",
- )
- async def list_automation_tasks(
- status: Optional[str] = None,
- order_id: Optional[str] = None,
- routing_key: Optional[str] = None,
- limit: int = 15,
- offset: int = 0,
- *,
- db: AsyncSession,
- current_user: VasUser,
- ) -> Dict[str, Any]:
- """查询自动化任务队列"""
- if current_user.role != "admin":
- return {"error": ADMIN_CHECK_MSG}
- limit = max(1, min(limit, 50))
- offset = max(0, offset)
- stmt = select(VasTask)
- if status and status.strip():
- stmt = stmt.where(VasTask.status == status.strip().lower())
- if order_id and order_id.strip():
- stmt = stmt.where(VasTask.order_id == order_id.strip())
- if routing_key and routing_key.strip():
- stmt = stmt.where(VasTask.routing_key.ilike(f"%{routing_key.strip()}%"))
- stmt = stmt.order_by(desc(VasTask.created_at)).offset(offset).limit(limit)
- res = await db.execute(stmt)
- tasks = res.scalars().all()
- items = []
- for t in tasks:
- items.append({
- "task_id": t.id,
- "order_id": t.order_id,
- "routing_key": t.routing_key,
- "status": t.status,
- "priority": t.priority,
- "attempt_count": t.attempt_count,
- "created_at": t.created_at.strftime("%Y-%m-%d %H:%M:%S") if t.created_at else None,
- "updated_at": t.updated_at.strftime("%Y-%m-%d %H:%M:%S") if t.updated_at else None,
- })
- return {
- "count": len(items),
- "tasks": items,
- }
- @agent_tool(
- name="get_automation_task_detail",
- description="获取指定自动化任务ID的完整执行状态、重试次数、抢位结果与上下文参数",
- )
- async def get_automation_task_detail(
- task_id: int,
- *,
- db: AsyncSession,
- current_user: VasUser,
- ) -> Dict[str, Any]:
- """查询自动化任务详情"""
- if current_user.role != "admin":
- return {"error": ADMIN_CHECK_MSG}
- t = await db.get(VasTask, task_id)
- if not t:
- return {"error": f"Automation task #{task_id} does not exist"}
- return {
- "task_id": t.id,
- "order_id": t.order_id,
- "routing_key": t.routing_key,
- "status": t.status,
- "priority": t.priority,
- "attempt_count": t.attempt_count,
- "grabbed_history": t.grabbed_history,
- "meta": t.meta,
- "created_at": t.created_at.strftime("%Y-%m-%d %H:%M:%S") if t.created_at else None,
- "updated_at": t.updated_at.strftime("%Y-%m-%d %H:%M:%S") if t.updated_at else None,
- }
- @agent_tool(
- name="admin_update_task_status",
- description="修改自动化任务状态(如将任务重置为 pending 进行重试,或设为 pause / cancelled 终止执行)",
- is_dangerous=True,
- )
- async def admin_update_task_status(
- task_id: int,
- new_status: str,
- *,
- db: AsyncSession,
- current_user: VasUser,
- ) -> Dict[str, Any]:
- """管理员更新自动化任务状态"""
- if current_user.role != "admin":
- return {"error": ADMIN_CHECK_MSG}
- clean_status = new_status.strip().lower()
- valid_statuses = {"pending", "running", "grabbed", "completed", "pause", "cancelled"}
- if clean_status not in valid_statuses:
- return {"error": f"Invalid task status '{clean_status}'. Valid: {sorted(list(valid_statuses))}"}
- t = await db.get(VasTask, task_id)
- if not t:
- return {"error": f"Automation task #{task_id} does not exist"}
- old_status = t.status
- t.status = clean_status
- if clean_status == "pending":
- t.attempt_count = 0 # 重置重试次数
- await db.commit()
- await db.refresh(t)
- logger.info(f"🔄 [AI_AGENT] Updated task #{task_id}: {old_status} -> {clean_status} by admin={current_user.id}")
- return {
- "success": True,
- "task_id": t.id,
- "previous_status": old_status,
- "new_status": t.status,
- }
|