# app/services/agent/tools/builtin/node_config_tools.py from typing import Optional, Dict, Any, List from sqlalchemy.ext.asyncio import AsyncSession from app.models.user import VasUser from app.services.node_configuration_service import NodeConfigurationService from app.services.agent.tools.registry import agent_tool ADMIN_CHECK_MSG = "Permission denied: This operation is restricted to system administrators (admin)" @agent_tool( name="list_node_configurations", description="查询爬虫节点配置列表(booker/sentinel/standalone),支持按 identifier 标识与启用状态筛选(管理员专有)", ) async def list_node_configurations( entry_type: str = "booker", identifier: Optional[str] = None, enable: Optional[bool] = None, page: int = 1, page_size: int = 10, *, db: AsyncSession, current_user: VasUser, ) -> Dict[str, Any]: """查询爬虫节点配置列表""" if current_user.role != "admin": return {"error": ADMIN_CHECK_MSG} clean_type = entry_type.strip().lower() enable_int = 1 if enable is True else (0 if enable is False else None) try: total, entries = await NodeConfigurationService.list_entries( db=db, entry_type=clean_type, page=page, page_size=min(page_size, 30), identifier=identifier.strip() if identifier else None, enable=enable_int, ) items = [] for e in entries: items.append({ "id": e.id, "node_id": e.node_id, "identifier": e.identifier, "enable": bool(e.enable), "debug": bool(e.debug), "proxy_cd": getattr(e, "proxy_cd", None), "session_max_life": getattr(e, "session_max_life", None), "version": e.version, "updated_by": e.updated_by, "updated_at": e.updated_at.strftime("%Y-%m-%d %H:%M:%S") if e.updated_at else None, }) return { "entry_type": clean_type, "total": total, "page": page, "items": items, } except Exception as e: return {"error": f"Failed to query node configurations: {str(e)}"} @agent_tool( name="get_node_configuration_detail", description="获取指定爬虫节点配置的完整详情(含代理池、时间窗、Plugin配置等,管理员专有)", ) async def get_node_configuration_detail( entry_type: str, entry_id: int, *, db: AsyncSession, current_user: VasUser, ) -> Dict[str, Any]: """获取单个节点配置完整详情""" if current_user.role != "admin": return {"error": ADMIN_CHECK_MSG} try: entry = await NodeConfigurationService.get_entry(db, entry_type.strip().lower(), entry_id) snapshot = NodeConfigurationService._to_snapshot(entry) return { "entry_type": entry_type, "entry_id": entry_id, "configuration": snapshot, } except Exception as e: return {"error": f"Failed to get node configuration details: {str(e)}"} @agent_tool( name="toggle_node_configuration", description="一键启用或禁用指定的爬虫节点配置(管理员专有)", is_dangerous=True, ) async def toggle_node_configuration( entry_type: str, entry_id: int, enable: bool, *, db: AsyncSession, current_user: VasUser, ) -> Dict[str, Any]: """启停节点配置""" if current_user.role != "admin": return {"error": ADMIN_CHECK_MSG} operator = current_user.email or current_user.nickname or current_user.id try: updated = await NodeConfigurationService.toggle_enable( db=db, entry_type=entry_type.strip().lower(), entry_id=entry_id, enable=enable, operator=operator, ) return { "success": True, "entry_type": entry_type, "entry_id": entry_id, "identifier": updated.identifier, "enable": bool(updated.enable), "version": updated.version, "message": f"Node {updated.identifier} has been successfully {'enabled' if enable else 'disabled'}", } except Exception as e: return {"error": f"Failed to toggle node configuration: {str(e)}"} @agent_tool( name="update_node_configuration_settings", description="调整指定爬虫节点的关键运维参数,如 proxy_cd(秒), session_max_life(秒), debug模式(管理员专有)", is_dangerous=True, ) async def update_node_configuration_settings( entry_type: str, entry_id: int, proxy_cd: Optional[int] = None, session_max_life: Optional[int] = None, debug: Optional[int] = None, *, db: AsyncSession, current_user: VasUser, ) -> Dict[str, Any]: """修改节点配置关键参数""" if current_user.role != "admin": return {"error": ADMIN_CHECK_MSG} set_data = {} if proxy_cd is not None: set_data["proxy_cd"] = proxy_cd if session_max_life is not None: set_data["session_max_life"] = session_max_life if debug is not None: set_data["debug"] = 1 if debug else 0 if not set_data: return {"message": "No parameters provided to update"} operator = current_user.email or current_user.nickname or current_user.id try: updated = await NodeConfigurationService.sparse_update_entry( db=db, entry_type=entry_type.strip().lower(), entry_id=entry_id, set_data=set_data, operator=operator, ) return { "success": True, "entry_type": entry_type, "entry_id": entry_id, "identifier": updated.identifier, "updated_fields": set_data, "version": updated.version, "message": f"Node {updated.identifier} configuration updated successfully", } except Exception as e: return {"error": f"Failed to update node configuration: {str(e)}"} @agent_tool( name="list_node_configuration_revisions", description="查询指定节点配置的历史版本审计记录,用于排错与回滚(管理员专有)", ) async def list_node_configuration_revisions( entry_type: str, entry_id: int, *, db: AsyncSession, current_user: VasUser, ) -> Dict[str, Any]: """查询节点配置历史版本""" if current_user.role != "admin": return {"error": ADMIN_CHECK_MSG} try: revisions = await NodeConfigurationService.get_revisions( db=db, entry_type=entry_type.strip().lower(), entry_id=entry_id, ) items = [] for r in revisions[:15]: items.append({ "revision_id": r.id, "version": r.version, "action": r.action, "updated_by": r.updated_by, "created_at": r.created_at.strftime("%Y-%m-%d %H:%M:%S") if r.created_at else None, }) return { "entry_type": entry_type, "entry_id": entry_id, "count": len(items), "revisions": items, } except Exception as e: return {"error": f"Failed to query revisions: {str(e)}"} @agent_tool( name="rollback_node_configuration", description="将节点配置紧急回滚到指定的历史版本 revision_id(管理员专有)", is_dangerous=True, ) async def rollback_node_configuration( entry_type: str, entry_id: int, revision_id: int, *, db: AsyncSession, current_user: VasUser, ) -> Dict[str, Any]: """回滚节点配置""" if current_user.role != "admin": return {"error": ADMIN_CHECK_MSG} operator = current_user.email or current_user.nickname or current_user.id try: rolled = await NodeConfigurationService.rollback_revision( db=db, entry_type=entry_type.strip().lower(), entry_id=entry_id, revision_id=revision_id, operator=operator, ) return { "success": True, "entry_type": entry_type, "entry_id": entry_id, "identifier": rolled.identifier, "current_version": rolled.version, "message": f"Node {rolled.identifier} successfully rolled back to revision #{revision_id}", } except Exception as e: return {"error": f"Failed to rollback node configuration: {str(e)}"}