Files
zhenxun_bot/zhenxun/services/scheduler/repository.py
922d092650 ♻️ refactor(core): 重构 AI 能力与定时任务调度系统 (#2148)
* ♻️ refactor(core): 重构 AI 能力与定时任务调度系统

- 【AI 能力与工具】重构 Capability 注册与管理机制,引入 CapabilityManager 统一管理
- 移除全局能力注册表,改用声明式装饰器 `@capability` 进行解耦注册
- 重构工具解析器链,使用统一的 BaseToolResolver 代替原有的多个特定解析器
- 增强工具查询过滤,支持通配符匹配、工具箱过滤和排除标签
- 【定时任务调度】重构定时任务管理器,引入 SchedulerRegistry 统一管理任务元数据
- 引入 JobConfig 聚合定时任务配置,支持用户维度的定时任务调度
- 重构执行分发器,支持并发限制、串行间隔和随机延迟打散
- 【运行上下文】引入 ScheduledDeps 以支持后台和定时任务环境下的依赖注入
- 优化 RunContext,支持从定时任务上下文快速构造,并提供 emit 辅助方法
- 【日志与监控】引入 AILoggerProxy,实现 AI 各模块的专属日志输出
- 将各模块的全局 logger 替换为对应的模块专属日志代理
- 【其他优化】修复 Pydantic V1 兼容层中 model_validator 的装饰器兼容性问题
- 在非交互式环境(如定时任务)中自动隐藏 HITL 交互工具以节省 Token

* ♻️ refactor(core): 优化内部导入路径并提升 Pydantic 兼容性

- 【重构】将 `services/ai` 模块内的绝对导入重构为相对导入,优化包结构
- 【重构】移除不必要的 `if TYPE_CHECKING` 保护,通过 `from __future__ import annotations` 直接导入类型
- 【清理】清理 `core/messages/types.py` 中未使用的 `AssistantContentUnion` 等联合类型定义
- 【优化】在 `utils/pydantic_compat.py` 中新增 `model_rebuild` 兼容函数,统一 Pydantic V1/V2 的模型重建逻辑
- 【优化】将部分函数内部的延迟导入提升至模块顶部,规范代码结构

* ♻️ refactor(imports): 优化导入路径为相对导入并清理冗余导入

- 【重构】将 AI 服务相关模块中的绝对导入路径修改为相对导入,提升模块内聚性与可移植性
- 【清理】移除多处函数内部或类方法中未使用的冗余导入,避免循环引用和资源浪费
- 【格式化】微调部分工具装饰器和返回语句的格式与尾随逗号

* 🚨 auto fix by pre-commit hooks

---------

Co-authored-by: webjoin111 <455457521@qq.com>
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
2026-07-10 09:14:06 +08:00

127 lines
4.0 KiB
Python

"""
数据持久层 (Repository)
封装所有对 ScheduledJob 模型的数据库操作,将数据访问逻辑与业务逻辑分离。
"""
from datetime import datetime
from typing import Any
from tortoise.queryset import QuerySet
from zhenxun.models.scheduled_job import ScheduledJob
class ScheduleRepository:
"""封装 ScheduledJob 模型的数据库操作"""
@staticmethod
async def get_by_id(schedule_id: int) -> ScheduledJob | None:
"""
通过ID获取任务
参数:
schedule_id: 任务ID。
返回:
ScheduledJob | None: 任务对象,不存在时返回None。
"""
return await ScheduledJob.get_or_none(id=schedule_id)
@staticmethod
async def get_all_enabled() -> list[ScheduledJob]:
"""
获取所有启用的任务
返回:
list[ScheduledJob]: 所有启用状态的任务列表。
"""
return await ScheduledJob.filter(is_enabled=True).all()
@staticmethod
async def get_all(plugin_name: str | None = None) -> list[ScheduledJob]:
"""获取所有任务,可按插件名过滤"""
if plugin_name:
return await ScheduledJob.filter(plugin_name=plugin_name).all()
return await ScheduledJob.all()
@staticmethod
async def update_run_status(schedule: ScheduledJob, is_success: bool):
"""
统一更新任务的最后运行状态
"""
schedule.last_run_at = datetime.now()
if is_success:
schedule.last_run_status = "SUCCESS"
schedule.consecutive_failures = 0
else:
schedule.last_run_status = "FAILURE"
schedule.consecutive_failures = (schedule.consecutive_failures or 0) + 1
await schedule.save(
update_fields=["last_run_at", "last_run_status", "consecutive_failures"]
)
@staticmethod
async def save(schedule: ScheduledJob, update_fields: list[str] | None = None):
"""
保存任务
参数:
schedule: 要保存的任务对象。
update_fields: 要更新的字段列表,None表示更新所有字段。
"""
await schedule.save(update_fields=update_fields)
@staticmethod
async def exists(**kwargs: Any) -> bool:
"""检查任务是否存在"""
return await ScheduledJob.exists(**kwargs)
@staticmethod
async def get_by_plugin_and_group(
plugin_name: str, group_ids: list[str]
) -> list[ScheduledJob]:
"""[DEPRECATED] 根据插件和群组ID列表获取任务"""
return await ScheduledJob.filter(
plugin_name=plugin_name, target_descriptor__in=group_ids
).all()
@staticmethod
async def update_or_create(
defaults: dict, **kwargs: Any
) -> tuple[ScheduledJob, bool]:
"""更新或创建任务"""
return await ScheduledJob.update_or_create(defaults=defaults, **kwargs)
@staticmethod
async def query_schedules(
page: int | None = None, page_size: int | None = None, **filters: Any
) -> tuple[list[ScheduledJob], int]:
"""
根据任意条件查询任务列表
参数:
page: 页码(从1开始)
page_size: 每页数量
**filters: 过滤条件,如 group_id="123", plugin_name="abc"
返回:
tuple[list[ScheduledJob], int]: (任务列表, 总数)
"""
cleaned_filters = {k: v for k, v in filters.items() if v is not None}
query = ScheduledJob.filter(**cleaned_filters)
total_count = await query.count()
if page is not None and page_size is not None:
offset = (page - 1) * page_size
query = query.offset(offset).limit(page_size)
return await query.all(), total_count
@staticmethod
def filter(**kwargs: Any) -> QuerySet[ScheduledJob]:
"""提供一个通用的过滤查询接口,供Targeter使用"""
return ScheduledJob.filter(**kwargs)