| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187 |
- # app/services/agent/tools/builtin/plugin_tools.py
- from typing import Optional, Dict, Any, List
- from sqlalchemy.ext.asyncio import AsyncSession
- from sqlalchemy import select
- from app.models.user import VasUser
- from app.models.plugin import Plugin
- from app.schemas.plugin import PluginUpdate
- from app.services.plugin_service import PluginService
- 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_plugins",
- description="查询当前系统注册的爬虫插件列表,包含插件名、最新版本号与启用状态(管理员专有)",
- )
- async def list_plugins(
- status: Optional[int] = None,
- page: int = 1,
- page_size: int = 20,
- *,
- db: AsyncSession,
- current_user: VasUser,
- ) -> Dict[str, Any]:
- """查询插件列表"""
- if current_user.role != "admin":
- return {"error": ADMIN_CHECK_MSG}
- try:
- res = await PluginService.get_plugin_list(
- db=db,
- page=page,
- page_size=min(page_size, 50),
- status=status,
- )
- items = []
- for p in res.get("list", []):
- items.append({
- "id": p.id,
- "name": p.name,
- "display_name": p.display_name,
- "filename": p.filename,
- "latest_version": p.latest_version,
- "description": p.description,
- "status": p.status,
- "status_cn": "已启用" if p.status == 1 else "已停用",
- })
- return {
- "total": res.get("total", len(items)),
- "plugins": items,
- }
- except Exception as e:
- return {"error": f"Failed to query plugin list: {str(e)}"}
- @agent_tool(
- name="get_plugin_detail",
- description="获取指定插件的完整信息及所有发布历史版本与更新日志(管理员专有)",
- )
- async def get_plugin_detail(
- plugin_id: Optional[int] = None,
- plugin_name: Optional[str] = None,
- *,
- db: AsyncSession,
- current_user: VasUser,
- ) -> Dict[str, Any]:
- """获取单个插件详情"""
- if current_user.role != "admin":
- return {"error": ADMIN_CHECK_MSG}
- try:
- target_id = plugin_id
- if target_id is None and plugin_name:
- stmt = select(Plugin.id).where(Plugin.name == plugin_name.strip())
- target_id = (await db.execute(stmt)).scalar_one_or_none()
- if not target_id:
- return {"error": f"Plugin not found: id={plugin_id}, name={plugin_name}"}
- detail = await PluginService.get_plugin_detail(db, target_id)
- versions_info = []
- for v in detail.get("versions", []):
- versions_info.append({
- "version": v.version,
- "download_url": v.download_url,
- "sha256": v.sha256[:16] + "..." if v.sha256 else "",
- "changelog": v.changelog,
- "created_at": v.created_at.strftime("%Y-%m-%d %H:%M:%S") if v.created_at else None,
- })
- return {
- "id": detail["id"],
- "name": detail["name"],
- "display_name": detail["display_name"],
- "latest_version": detail["latest_version"],
- "status": detail["status"],
- "description": detail["description"],
- "versions_count": len(versions_info),
- "versions": versions_info,
- }
- except Exception as e:
- return {"error": f"Failed to get plugin details: {str(e)}"}
- @agent_tool(
- name="toggle_plugin_status",
- description="一键启用(status=1)或停用(status=0)指定插件(管理员专有)",
- is_dangerous=True,
- )
- async def toggle_plugin_status(
- plugin_id: Optional[int] = None,
- plugin_name: Optional[str] = None,
- status: int = 1,
- *,
- db: AsyncSession,
- current_user: VasUser,
- ) -> Dict[str, Any]:
- """启停插件"""
- if current_user.role != "admin":
- return {"error": ADMIN_CHECK_MSG}
- try:
- target_id = plugin_id
- if target_id is None and plugin_name:
- stmt = select(Plugin.id).where(Plugin.name == plugin_name.strip())
- target_id = (await db.execute(stmt)).scalar_one_or_none()
- if not target_id:
- return {"error": f"Plugin not found: id={plugin_id}, name={plugin_name}"}
- clean_status = 1 if status == 1 else 0
- updated = await PluginService.update_plugin(
- db=db,
- plugin_id=target_id,
- plugin_in=PluginUpdate(status=clean_status),
- )
- return {
- "success": True,
- "plugin_id": updated.id,
- "name": updated.name,
- "status": updated.status,
- "message": f"Plugin {updated.name} has been successfully {'enabled' if clean_status == 1 else 'disabled'}",
- }
- except Exception as e:
- return {"error": f"Failed to toggle plugin status: {str(e)}"}
- @agent_tool(
- name="switch_plugin_version",
- description="一键切换/回滚插件的当前生效版本号(管理员专有)",
- is_dangerous=True,
- )
- async def switch_plugin_version(
- version: str,
- plugin_id: Optional[int] = None,
- plugin_name: Optional[str] = None,
- *,
- db: AsyncSession,
- current_user: VasUser,
- ) -> Dict[str, Any]:
- """切换插件生效版本"""
- if current_user.role != "admin":
- return {"error": ADMIN_CHECK_MSG}
- try:
- target_id = plugin_id
- if target_id is None and plugin_name:
- stmt = select(Plugin.id).where(Plugin.name == plugin_name.strip())
- target_id = (await db.execute(stmt)).scalar_one_or_none()
- if not target_id:
- return {"error": f"Plugin not found: id={plugin_id}, name={plugin_name}"}
- plugin = await PluginService.switch_version(db, target_id, version.strip())
- return {
- "success": True,
- "plugin_id": plugin.id,
- "name": plugin.name,
- "current_version": plugin.latest_version,
- "message": f"Plugin {plugin.name} active version switched to {version}",
- }
- except Exception as e:
- return {"error": f"Failed to switch plugin version: {str(e)}"}
|