mirror of
https://github.com/jxxghp/MoviePilot.git
synced 2026-12-01 00:15:56 +08:00
refactor(agent): unify tools behind API gateway and provider skills
This commit is contained in:
@@ -1,465 +0,0 @@
|
||||
"""过滤规则 Agent 工具共用的校验、查询和引用处理逻辑。"""
|
||||
|
||||
import copy
|
||||
import re
|
||||
from typing import Any, Dict, Iterable, Optional
|
||||
|
||||
from app.application.configuration import get_configured_system_config
|
||||
from app.application.rules import (
|
||||
BUILTIN_RULE_SET,
|
||||
RuleHelper,
|
||||
RuleParser,
|
||||
)
|
||||
from app.application.subscription.contract import SubscriptionRepository
|
||||
from app.runtime.events import eventmanager
|
||||
from app.schemas.event import ConfigChangeEventData
|
||||
from app.schemas.rule import CustomRule
|
||||
from app.schemas.system import FilterRuleGroup
|
||||
from app.schemas.types import EventType, SystemConfigKey
|
||||
|
||||
RULE_ID_PATTERN = re.compile(r"^[A-Za-z0-9]+$")
|
||||
RULE_TOKEN_PATTERN = re.compile(r"[A-Za-z][A-Za-z0-9]*|[0-9][A-Za-z0-9]+")
|
||||
NUMERIC_RANGE_PATTERN = re.compile(
|
||||
r"^\d+(?:\.\d+)?(?:\s*-\s*\d+(?:\.\d+)?)?$"
|
||||
)
|
||||
|
||||
MEDIA_TYPE_ALIASES = {
|
||||
"movie": "电影",
|
||||
"film": "电影",
|
||||
"tv": "电视剧",
|
||||
"series": "电视剧",
|
||||
"show": "电视剧",
|
||||
"music": "音乐",
|
||||
"电影": "电影",
|
||||
"电视剧": "电视剧",
|
||||
"音乐": "音乐",
|
||||
}
|
||||
|
||||
RULE_STRING_SYNTAX = {
|
||||
"level_separator": ">",
|
||||
"and_operator": "&",
|
||||
"not_operator": "!",
|
||||
"supported_grouping": "Parentheses are supported inside a single level.",
|
||||
"spacing_note": "Prefer spaces around '&', and '>' for readability; use '!RULE' for negation.",
|
||||
"match_order": "Levels are evaluated from left to right. The first matched level wins and stops further matching.",
|
||||
"match_result": "If no level matches, the torrent is filtered out. If a level matches, the torrent is kept.",
|
||||
"writing_workflow": [
|
||||
"First query built-in rules and custom rules to learn valid rule IDs.",
|
||||
"Compose one priority level with '&', '!' and optional parentheses.",
|
||||
"Join multiple priority levels with '>' from highest priority to lowest priority.",
|
||||
"Use spaces around '&', and '>' for readability.",
|
||||
],
|
||||
"examples": [
|
||||
{
|
||||
"description": "Prefer torrents with special subtitles and Chinese dubbing at 4K, otherwise fall back to Chinese subtitles and Chinese dubbing at 4K.",
|
||||
"rule_string": "SPECSUB & CNVOI & 4K & !BLU & !REMUX & !WEBDL > CNSUB & CNVOI & 4K & !BLU & !REMUX & !WEBDL",
|
||||
},
|
||||
{
|
||||
"description": "Inside one level, require 4K and reject Blu-ray source.",
|
||||
"rule_string": "4K & !BLU",
|
||||
},
|
||||
{
|
||||
"description": "Inside one level, accept either special subtitles or Chinese subtitles, then also require 1080P.",
|
||||
"rule_string": "(SPECSUB | CNSUB) & 1080P",
|
||||
},
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
def normalize_optional_text(value: Optional[str]) -> Optional[str]:
|
||||
"""把空白字符串折叠为 None,避免保存无意义的空值。"""
|
||||
if value is None:
|
||||
return None
|
||||
value = str(value).strip()
|
||||
return value or None
|
||||
|
||||
|
||||
def normalize_media_type(value: Optional[str]) -> Optional[str]:
|
||||
"""兼容英中文媒体类型输入,最终统一为后端实际使用的中文值。"""
|
||||
value = normalize_optional_text(value)
|
||||
if not value:
|
||||
return None
|
||||
normalized = MEDIA_TYPE_ALIASES.get(value.lower(), value)
|
||||
if normalized not in {"电影", "电视剧", "音乐"}:
|
||||
raise ValueError(
|
||||
"media_type 仅支持 '电影'、'电视剧'、'音乐'、'movie'、'tv' 或 'music'"
|
||||
)
|
||||
return normalized
|
||||
|
||||
|
||||
def validate_numeric_range(
|
||||
field_name: str, value: Optional[str]
|
||||
) -> Optional[str]:
|
||||
"""校验 size_range / publish_time 这类单值或区间值。"""
|
||||
value = normalize_optional_text(value)
|
||||
if not value:
|
||||
return None
|
||||
if not NUMERIC_RANGE_PATTERN.match(value):
|
||||
raise ValueError(
|
||||
f"{field_name} 格式无效,支持 '1000' 或 '1000-5000' 这类数字区间格式"
|
||||
)
|
||||
|
||||
parts = [float(item.strip()) for item in value.split("-")]
|
||||
if len(parts) == 2 and parts[0] > parts[1]:
|
||||
raise ValueError(f"{field_name} 区间起始值不能大于结束值")
|
||||
return value
|
||||
|
||||
|
||||
def validate_seeders(value: Optional[str]) -> Optional[str]:
|
||||
"""做种人数最终会被 int() 解析,这里提前拦住非法值。"""
|
||||
value = normalize_optional_text(value)
|
||||
if not value:
|
||||
return None
|
||||
if not value.isdigit():
|
||||
raise ValueError("seeders 必须是非负整数")
|
||||
return value
|
||||
|
||||
|
||||
def get_builtin_rules() -> Dict[str, dict]:
|
||||
"""返回内置规则的深拷贝,避免调用方误改共享常量。"""
|
||||
return copy.deepcopy(BUILTIN_RULE_SET)
|
||||
|
||||
|
||||
def get_custom_rules() -> list[CustomRule]:
|
||||
return RuleHelper().get_custom_rules()
|
||||
|
||||
|
||||
def get_rule_groups() -> list[FilterRuleGroup]:
|
||||
return RuleHelper().get_rule_groups()
|
||||
|
||||
|
||||
def build_custom_rule_map(rules: Optional[Iterable[CustomRule]] = None) -> Dict[str, CustomRule]:
|
||||
return {
|
||||
rule.id: rule
|
||||
for rule in (rules or get_custom_rules())
|
||||
if rule.id
|
||||
}
|
||||
|
||||
|
||||
def build_rule_group_map(
|
||||
groups: Optional[Iterable[FilterRuleGroup]] = None,
|
||||
) -> Dict[str, FilterRuleGroup]:
|
||||
return {
|
||||
group.name: group
|
||||
for group in (groups or get_rule_groups())
|
||||
if group.name
|
||||
}
|
||||
|
||||
|
||||
def extract_rule_tokens(rule_string: Optional[str]) -> list[str]:
|
||||
"""从规则串里提取规则 ID,用于引用分析和未知规则校验。"""
|
||||
if not rule_string:
|
||||
return []
|
||||
# dict.fromkeys 用来在保留顺序的同时去重,便于展示和报错。
|
||||
return list(dict.fromkeys(RULE_TOKEN_PATTERN.findall(rule_string)))
|
||||
|
||||
|
||||
def parse_rule_string(rule_string: str) -> dict:
|
||||
"""使用后端同款 RuleParser 解析规则串,并拆出每一层的元数据。"""
|
||||
normalized = normalize_optional_text(rule_string)
|
||||
if not normalized:
|
||||
raise ValueError("rule_string 不能为空")
|
||||
|
||||
parser = RuleParser()
|
||||
levels = [level.strip() for level in normalized.split(">")]
|
||||
if any(not level for level in levels):
|
||||
raise ValueError("rule_string 不能包含空层级,请检查 '>' 两侧内容")
|
||||
|
||||
parsed_levels = []
|
||||
for index, level in enumerate(levels, start=1):
|
||||
try:
|
||||
parser.parse(level)
|
||||
except Exception as exc: # pragma: no cover - 依赖 pyparsing 的具体异常
|
||||
raise ValueError(f"规则串第 {index} 层语法错误: {exc}") from exc
|
||||
|
||||
parsed_levels.append(
|
||||
{
|
||||
"priority": index,
|
||||
"expression": level,
|
||||
"referenced_rules": extract_rule_tokens(level),
|
||||
}
|
||||
)
|
||||
|
||||
return {
|
||||
"rule_string": " > ".join(levels),
|
||||
"levels": parsed_levels,
|
||||
"referenced_rules": extract_rule_tokens(normalized),
|
||||
}
|
||||
|
||||
|
||||
def validate_rule_string(rule_string: str, available_rule_ids: Iterable[str]) -> dict:
|
||||
"""校验规则串语法和引用规则是否都存在。"""
|
||||
parsed = parse_rule_string(rule_string)
|
||||
available_ids = set(available_rule_ids)
|
||||
unknown_rules = sorted(
|
||||
{
|
||||
rule_id
|
||||
for rule_id in parsed["referenced_rules"]
|
||||
if rule_id not in available_ids
|
||||
}
|
||||
)
|
||||
if unknown_rules:
|
||||
raise ValueError(
|
||||
f"rule_string 引用了不存在的规则: {', '.join(unknown_rules)}"
|
||||
)
|
||||
return parsed
|
||||
|
||||
|
||||
def serialize_builtin_rule(rule_id: str, payload: dict) -> dict:
|
||||
"""把内置规则整理成适合 Agent 阅读的结构。"""
|
||||
data = copy.deepcopy(payload)
|
||||
data["id"] = rule_id
|
||||
data["source"] = "builtin"
|
||||
return data
|
||||
|
||||
|
||||
def serialize_custom_rule(rule: CustomRule, group_refs: Optional[list[str]] = None) -> dict:
|
||||
data = rule.model_dump(exclude_none=True)
|
||||
data["source"] = "custom"
|
||||
data["referenced_by_rule_groups"] = group_refs or []
|
||||
return data
|
||||
|
||||
|
||||
def serialize_rule_group(group: FilterRuleGroup, usage: Optional[dict] = None) -> dict:
|
||||
"""查询时尽量附带解析结果,便于 Agent 理解优先级层级。"""
|
||||
data = group.model_dump(exclude_none=True)
|
||||
if group.rule_string:
|
||||
try:
|
||||
parsed = parse_rule_string(group.rule_string)
|
||||
data["levels"] = parsed["levels"]
|
||||
data["referenced_rules"] = parsed["referenced_rules"]
|
||||
data["syntax_valid"] = True
|
||||
except ValueError as exc:
|
||||
data["syntax_valid"] = False
|
||||
data["syntax_error"] = str(exc)
|
||||
data["referenced_rules"] = extract_rule_tokens(group.rule_string)
|
||||
else:
|
||||
data["syntax_valid"] = False
|
||||
data["syntax_error"] = "rule_string 为空"
|
||||
data["referenced_rules"] = []
|
||||
data["usage"] = usage or default_rule_group_usage()
|
||||
return data
|
||||
|
||||
|
||||
def default_rule_group_usage() -> dict:
|
||||
return {
|
||||
"used_in_global_search": False,
|
||||
"used_in_global_subscribe": False,
|
||||
"used_in_global_best_version": False,
|
||||
"subscribes": [],
|
||||
}
|
||||
|
||||
|
||||
async def collect_rule_group_usages(
|
||||
repository: SubscriptionRepository,
|
||||
group_names: Optional[Iterable[str]] = None,
|
||||
) -> Dict[str, dict]:
|
||||
"""收集规则组在全局配置和订阅上的引用情况。"""
|
||||
target_names = set(group_names or [])
|
||||
search_groups = set(
|
||||
get_configured_system_config().get(SystemConfigKey.SearchFilterRuleGroups) or []
|
||||
)
|
||||
subscribe_groups = set(
|
||||
get_configured_system_config().get(SystemConfigKey.SubscribeFilterRuleGroups) or []
|
||||
)
|
||||
best_version_groups = set(
|
||||
get_configured_system_config().get(SystemConfigKey.BestVersionFilterRuleGroups) or []
|
||||
)
|
||||
|
||||
usage_map = {
|
||||
name: default_rule_group_usage()
|
||||
for name in target_names
|
||||
}
|
||||
|
||||
def ensure_usage(name: str) -> dict:
|
||||
if name not in usage_map:
|
||||
usage_map[name] = default_rule_group_usage()
|
||||
return usage_map[name]
|
||||
|
||||
for name in search_groups:
|
||||
if target_names and name not in target_names:
|
||||
continue
|
||||
ensure_usage(name)["used_in_global_search"] = True
|
||||
for name in subscribe_groups:
|
||||
if target_names and name not in target_names:
|
||||
continue
|
||||
ensure_usage(name)["used_in_global_subscribe"] = True
|
||||
for name in best_version_groups:
|
||||
if target_names and name not in target_names:
|
||||
continue
|
||||
ensure_usage(name)["used_in_global_best_version"] = True
|
||||
|
||||
subscribes = await repository.async_list()
|
||||
for subscribe in subscribes:
|
||||
filter_groups = [str(name) for name in subscribe.filter_groups] \
|
||||
if isinstance(subscribe.filter_groups, list) else []
|
||||
for name in filter_groups:
|
||||
if target_names and name not in target_names:
|
||||
continue
|
||||
ensure_usage(name)["subscribes"].append(
|
||||
{
|
||||
"subscribe_id": subscribe.id,
|
||||
"name": subscribe.name,
|
||||
"season": subscribe.season,
|
||||
"type": subscribe.type,
|
||||
"username": subscribe.username,
|
||||
"best_version": bool(subscribe.best_version),
|
||||
}
|
||||
)
|
||||
|
||||
return usage_map
|
||||
|
||||
|
||||
def collect_custom_rule_group_refs(
|
||||
rule_groups: Iterable[FilterRuleGroup],
|
||||
rule_ids: Optional[Iterable[str]] = None,
|
||||
) -> Dict[str, list[str]]:
|
||||
"""收集自定义规则被哪些规则组引用。"""
|
||||
target_rule_ids = set(rule_ids or [])
|
||||
refs: Dict[str, list[str]] = {
|
||||
rule_id: []
|
||||
for rule_id in target_rule_ids
|
||||
}
|
||||
|
||||
for group in rule_groups:
|
||||
if not group.name or not group.rule_string:
|
||||
continue
|
||||
referenced = set(extract_rule_tokens(group.rule_string))
|
||||
for rule_id in referenced:
|
||||
if target_rule_ids and rule_id not in target_rule_ids:
|
||||
continue
|
||||
refs.setdefault(rule_id, []).append(group.name)
|
||||
|
||||
for names in refs.values():
|
||||
names.sort()
|
||||
return refs
|
||||
|
||||
|
||||
def normalize_custom_rule(
|
||||
rule_id: str,
|
||||
name: str,
|
||||
include: Optional[str],
|
||||
exclude: Optional[str],
|
||||
size_range: Optional[str],
|
||||
seeders: Optional[str],
|
||||
publish_time: Optional[str],
|
||||
existing_rules: Iterable[CustomRule],
|
||||
original_rule_id: Optional[str] = None,
|
||||
) -> CustomRule:
|
||||
"""新增/更新自定义规则时统一走这里,避免多处散落校验逻辑。"""
|
||||
normalized_rule_id = normalize_optional_text(rule_id)
|
||||
normalized_name = normalize_optional_text(name)
|
||||
if not normalized_rule_id:
|
||||
raise ValueError("rule_id 不能为空")
|
||||
if not normalized_name:
|
||||
raise ValueError("name 不能为空")
|
||||
if not RULE_ID_PATTERN.match(normalized_rule_id):
|
||||
raise ValueError("rule_id 仅支持英文字母和数字")
|
||||
if (
|
||||
normalized_rule_id in BUILTIN_RULE_SET
|
||||
and normalized_rule_id != original_rule_id
|
||||
):
|
||||
raise ValueError(
|
||||
f"rule_id '{normalized_rule_id}' 与内置规则冲突,不能覆盖内置规则"
|
||||
)
|
||||
|
||||
for existing_rule in existing_rules:
|
||||
if (
|
||||
existing_rule.id == normalized_rule_id
|
||||
and existing_rule.id != original_rule_id
|
||||
):
|
||||
raise ValueError(f"rule_id '{normalized_rule_id}' 已存在")
|
||||
if (
|
||||
existing_rule.name == normalized_name
|
||||
and existing_rule.id != original_rule_id
|
||||
):
|
||||
raise ValueError(f"规则名称 '{normalized_name}' 已存在")
|
||||
|
||||
return CustomRule(
|
||||
id=normalized_rule_id,
|
||||
name=normalized_name,
|
||||
include=normalize_optional_text(include),
|
||||
exclude=normalize_optional_text(exclude),
|
||||
size_range=validate_numeric_range("size_range", size_range),
|
||||
seeders=validate_seeders(seeders),
|
||||
publish_time=validate_numeric_range("publish_time", publish_time),
|
||||
)
|
||||
|
||||
|
||||
def normalize_rule_group(
|
||||
name: str,
|
||||
rule_string: str,
|
||||
media_type: Optional[str],
|
||||
category: Optional[str],
|
||||
existing_groups: Iterable[FilterRuleGroup],
|
||||
available_rule_ids: Iterable[str],
|
||||
original_name: Optional[str] = None,
|
||||
) -> tuple[FilterRuleGroup, dict]:
|
||||
"""新增/更新规则组时统一校验名字、适用范围和规则串。"""
|
||||
normalized_name = normalize_optional_text(name)
|
||||
if not normalized_name:
|
||||
raise ValueError("规则组名称不能为空")
|
||||
|
||||
for group in existing_groups:
|
||||
if group.name == normalized_name and group.name != original_name:
|
||||
raise ValueError(f"规则组名称 '{normalized_name}' 已存在")
|
||||
|
||||
normalized_media_type = normalize_media_type(media_type)
|
||||
normalized_category = normalize_optional_text(category)
|
||||
if normalized_category and not normalized_media_type:
|
||||
raise ValueError("设置 category 时必须同时设置 media_type")
|
||||
|
||||
parsed = validate_rule_string(rule_string, available_rule_ids)
|
||||
return (
|
||||
FilterRuleGroup(
|
||||
name=normalized_name,
|
||||
rule_string=parsed["rule_string"],
|
||||
media_type=normalized_media_type,
|
||||
category=normalized_category,
|
||||
),
|
||||
parsed,
|
||||
)
|
||||
|
||||
|
||||
async def save_system_config(
|
||||
key: SystemConfigKey, value: Any
|
||||
) -> Optional[bool]:
|
||||
"""通过统一入口保存配置并补发 ConfigChanged 事件。"""
|
||||
normalized_value = value
|
||||
if isinstance(normalized_value, list):
|
||||
normalized_value = [
|
||||
item
|
||||
for item in normalized_value
|
||||
if item is not None and item != ""
|
||||
]
|
||||
normalized_value = normalized_value or None
|
||||
|
||||
success = await get_configured_system_config().async_set(key, normalized_value)
|
||||
if success:
|
||||
await publish_rule_config_changed(key, normalized_value)
|
||||
return success
|
||||
|
||||
|
||||
async def publish_rule_config_changed(
|
||||
key: SystemConfigKey,
|
||||
value: Any,
|
||||
) -> None:
|
||||
"""广播一项已经提交的规则配置变更。"""
|
||||
await eventmanager.async_send_event(
|
||||
etype=EventType.ConfigChanged,
|
||||
data=ConfigChangeEventData(
|
||||
key=key,
|
||||
value=value,
|
||||
change_type="update",
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def replace_rule_id_in_rule_string(
|
||||
rule_string: str, old_rule_id: str, new_rule_id: str
|
||||
) -> str:
|
||||
"""只替换完整 token,避免误伤其他规则名。"""
|
||||
pattern = re.compile(
|
||||
rf"(?<![A-Za-z0-9]){re.escape(old_rule_id)}(?![A-Za-z0-9])"
|
||||
)
|
||||
return pattern.sub(new_rule_id, rule_string)
|
||||
@@ -1,87 +0,0 @@
|
||||
"""Agent 音乐工具共享的实体校验与结果精简函数。"""
|
||||
|
||||
from typing import Any
|
||||
|
||||
from app.domain.context import (
|
||||
MusicAlbumInfo,
|
||||
MusicArtistInfo,
|
||||
MusicInfo,
|
||||
)
|
||||
from app.schemas.types import media_type_to_agent
|
||||
|
||||
|
||||
MUSIC_TRACK_PREVIEW_LIMIT = 100
|
||||
MUSIC_RELEASE_PREVIEW_LIMIT = 20
|
||||
|
||||
|
||||
def simplify_music_info(info: MusicInfo) -> dict[str, Any]:
|
||||
"""精简音乐列表项,同时保留订阅和下载所需的稳定身份。"""
|
||||
payload = {
|
||||
"title": info.title,
|
||||
"year": info.year,
|
||||
"type": media_type_to_agent(info.type),
|
||||
"music_type": info.music_type,
|
||||
"artists": list(info.artists or []),
|
||||
"artist_ids": list(info.artist_ids or []),
|
||||
"artist": info.artist,
|
||||
"album": info.album,
|
||||
"album_id": info.album_id,
|
||||
"album_type": info.album_type,
|
||||
"release_date": info.release_date,
|
||||
"disc_number": info.disc_number,
|
||||
"track_number": info.track_number,
|
||||
"total_tracks": info.total_tracks,
|
||||
"duration": info.duration,
|
||||
"isrc": info.isrc,
|
||||
"version": info.version,
|
||||
"genres": list(info.genres or []),
|
||||
"category": info.category,
|
||||
"listen_count": info.listen_count,
|
||||
"media_source": info.media_source,
|
||||
"media_id": info.media_id,
|
||||
"poster_path": info.poster_path,
|
||||
"detail_link": info.detail_link,
|
||||
"overview": info.overview,
|
||||
}
|
||||
return {key: value for key, value in payload.items() if value not in (None, "", [])}
|
||||
|
||||
|
||||
def simplify_music_album(
|
||||
info: MusicAlbumInfo,
|
||||
*,
|
||||
track_limit: int = MUSIC_TRACK_PREVIEW_LIMIT,
|
||||
) -> dict[str, Any]:
|
||||
"""精简专辑详情并限制曲目和发行版本预览,避免撑大 Agent 上下文。"""
|
||||
normalized_track_limit = max(1, min(track_limit, MUSIC_TRACK_PREVIEW_LIMIT))
|
||||
tracks = list(info.tracks or [])
|
||||
releases = list(info.releases or [])
|
||||
payload = simplify_music_info(info.to_music_info())
|
||||
payload.update({
|
||||
"release_date": info.release_date,
|
||||
"secondary_types": list(info.secondary_types or []),
|
||||
"tags": list(info.tags or []),
|
||||
"rating": info.rating,
|
||||
"rating_votes": info.rating_votes,
|
||||
"tracks": [
|
||||
simplify_music_info(track)
|
||||
for track in tracks[:normalized_track_limit]
|
||||
],
|
||||
"tracks_total": len(tracks),
|
||||
"tracks_truncated": len(tracks) > normalized_track_limit,
|
||||
"releases": [release.to_dict() for release in releases[:MUSIC_RELEASE_PREVIEW_LIMIT]],
|
||||
"releases_total": len(releases),
|
||||
"releases_truncated": len(releases) > MUSIC_RELEASE_PREVIEW_LIMIT,
|
||||
})
|
||||
return payload
|
||||
|
||||
|
||||
def simplify_music_artist(info: MusicArtistInfo) -> dict[str, Any]:
|
||||
"""精简艺术家详情,明确其仅用于浏览而非订阅或下载。"""
|
||||
payload = info.to_dict()
|
||||
payload.pop("raw_data", None)
|
||||
payload.pop("mediaid_prefix", None)
|
||||
payload["type"] = media_type_to_agent(info.type)
|
||||
payload["media_source"] = info.media_source
|
||||
payload["media_id"] = info.media_id
|
||||
payload["subscribable"] = False
|
||||
return {key: value for key, value in payload.items() if value not in (None, "", [])}
|
||||
@@ -1,400 +0,0 @@
|
||||
"""插件 Agent 工具共享辅助方法"""
|
||||
|
||||
import json
|
||||
from typing import Any, Optional
|
||||
|
||||
from app.adapters.external.plugin.client import is_local_repo_url
|
||||
from app.application.configuration import get_configured_system_config
|
||||
from app.application.plugin.gateway import get_plugin_install_service
|
||||
from app.application.plugin.runtime import get_plugin_manager
|
||||
from app.schemas.plugin import PluginRuntimeStatus
|
||||
from app.schemas.types import SystemConfigKey
|
||||
|
||||
|
||||
# 默认只向智能体返回一个可读预览,避免超大插件数据挤爆上下文窗口。
|
||||
DEFAULT_PLUGIN_DATA_PREVIEW_CHARS = 12_000
|
||||
MAX_PLUGIN_DATA_PREVIEW_CHARS = 50_000
|
||||
PLUGIN_DATA_KEY_PREVIEW_LIMIT = 50
|
||||
PLUGIN_DATA_TRUNCATION_SUFFIX = "\n...(插件数据内容过长,已截断)"
|
||||
DEFAULT_PLUGIN_CANDIDATE_LIMIT = 50
|
||||
MAX_PLUGIN_CANDIDATE_LIMIT = 200
|
||||
|
||||
|
||||
def get_plugin_snapshot(plugin_id: str) -> Optional[dict[str, Any]]:
|
||||
"""
|
||||
获取已安装插件的基础信息快照。
|
||||
"""
|
||||
plugin_manager = get_plugin_manager()
|
||||
for plugin in plugin_manager.get_local_plugins():
|
||||
if plugin.id == plugin_id:
|
||||
return {
|
||||
"plugin_id": plugin.id,
|
||||
"plugin_name": plugin.plugin_name,
|
||||
"plugin_version": plugin.plugin_version,
|
||||
"state": plugin.state,
|
||||
}
|
||||
return None
|
||||
|
||||
|
||||
def clamp_preview_chars(max_chars: Optional[int]) -> int:
|
||||
"""
|
||||
约束插件数据预览长度,避免工具结果无限膨胀。
|
||||
"""
|
||||
if max_chars is None:
|
||||
return DEFAULT_PLUGIN_DATA_PREVIEW_CHARS
|
||||
return max(512, min(int(max_chars), MAX_PLUGIN_DATA_PREVIEW_CHARS))
|
||||
|
||||
|
||||
def serialize_for_agent(value: Any) -> str:
|
||||
"""
|
||||
将结果稳定序列化为 JSON 字符串,无法原生序列化的对象退化为字符串。
|
||||
"""
|
||||
return json.dumps(value, ensure_ascii=False, indent=2, default=str)
|
||||
|
||||
|
||||
def build_preview_payload(value: Any, max_chars: Optional[int]) -> tuple[bool, int, int, str]:
|
||||
"""
|
||||
为可能很大的插件数据生成预览结果。
|
||||
"""
|
||||
serialized = serialize_for_agent(value)
|
||||
if len(serialized) <= clamp_preview_chars(max_chars):
|
||||
return False, len(serialized), len(serialized), serialized
|
||||
|
||||
preview_limit = clamp_preview_chars(max_chars)
|
||||
preview = serialized[:preview_limit] + PLUGIN_DATA_TRUNCATION_SUFFIX
|
||||
return True, len(serialized), len(preview), preview
|
||||
|
||||
|
||||
def refresh_plugin_registrations(plugin_id: str) -> None:
|
||||
"""重新注册插件的定时任务、命令和动态 API 路由。"""
|
||||
# 这些依赖只在真正执行重载时才导入,避免普通查询工具引入不必要的初始化开销。
|
||||
from app.application.plugin.routes import register_plugin_api
|
||||
from app.application.commands import init_commands
|
||||
from app.application.scheduling import update_plugin_job
|
||||
|
||||
update_plugin_job(plugin_id)
|
||||
init_commands(plugin_id)
|
||||
register_plugin_api(plugin_id)
|
||||
|
||||
|
||||
def reload_plugin_runtime(plugin_id: str) -> PluginRuntimeStatus:
|
||||
"""重载插件实例并重新注册其命令、定时任务和 API。"""
|
||||
plugin_manager = get_plugin_manager()
|
||||
with plugin_manager.mutation(f"重载插件 {plugin_id}"):
|
||||
runtime_status = plugin_manager.reload_plugin(plugin_id)
|
||||
refresh_plugin_registrations(plugin_id)
|
||||
return runtime_status
|
||||
|
||||
|
||||
def summarize_plugin(plugin: Any) -> dict[str, Any]:
|
||||
"""
|
||||
提取插件对象中对 Agent 有价值的摘要字段。
|
||||
"""
|
||||
repo_url = getattr(plugin, "repo_url", None)
|
||||
return {
|
||||
"id": getattr(plugin, "id", None),
|
||||
"plugin_name": getattr(plugin, "plugin_name", None),
|
||||
"plugin_desc": getattr(plugin, "plugin_desc", None),
|
||||
"plugin_version": getattr(plugin, "plugin_version", None),
|
||||
"plugin_author": getattr(plugin, "plugin_author", None),
|
||||
"installed": bool(getattr(plugin, "installed", False)),
|
||||
"has_update": bool(getattr(plugin, "has_update", False)),
|
||||
"system_version_compatible": getattr(plugin, "system_version_compatible", True) is not False,
|
||||
"system_version": getattr(plugin, "system_version", None),
|
||||
"system_version_message": getattr(plugin, "system_version_message", None),
|
||||
"state": bool(getattr(plugin, "state", False)),
|
||||
"repo_url": repo_url,
|
||||
"source": "local_repo" if is_local_repo_url(repo_url) else "market",
|
||||
}
|
||||
|
||||
|
||||
def _merge_plugin_source_metadata(plugin: Any, source_plugin: Any) -> Any:
|
||||
"""
|
||||
将插件市场或本地仓库中的来源元数据合并到已安装插件对象。
|
||||
"""
|
||||
repo_url = getattr(source_plugin, "repo_url", None)
|
||||
if repo_url:
|
||||
setattr(plugin, "repo_url", repo_url)
|
||||
|
||||
for attr in (
|
||||
"has_update",
|
||||
"release",
|
||||
"system_version",
|
||||
"system_version_compatible",
|
||||
"system_version_message",
|
||||
):
|
||||
value = getattr(source_plugin, attr, None)
|
||||
if value is not None:
|
||||
setattr(plugin, attr, value)
|
||||
|
||||
return plugin
|
||||
|
||||
|
||||
def _map_plugins_by_id(plugins: list[Any]) -> dict[str, Any]:
|
||||
"""
|
||||
按插件 ID 建立稳定映射,保留同 ID 首个候选来源。
|
||||
"""
|
||||
plugin_map: dict[str, Any] = {}
|
||||
for plugin in plugins:
|
||||
plugin_id = getattr(plugin, "id", None)
|
||||
if plugin_id and plugin_id not in plugin_map:
|
||||
plugin_map[plugin_id] = plugin
|
||||
return plugin_map
|
||||
|
||||
|
||||
async def enrich_installed_plugin_sources(
|
||||
installed_plugins: list[Any],
|
||||
force_refresh: bool = False,
|
||||
) -> list[Any]:
|
||||
"""
|
||||
为已安装插件补齐安装来源仓库地址。
|
||||
|
||||
本地插件对象只包含运行目录中的静态元数据,通常没有 repo_url。这里按需从
|
||||
本地插件仓库和插件市场补齐来源,保证 Agent 后续安装、升级判断可以拿到仓库地址。
|
||||
"""
|
||||
missing_source_plugins = [
|
||||
plugin for plugin in installed_plugins if not getattr(plugin, "repo_url", None)
|
||||
]
|
||||
if not missing_source_plugins:
|
||||
return installed_plugins
|
||||
|
||||
plugin_manager = get_plugin_manager()
|
||||
local_repo_map = _map_plugins_by_id(plugin_manager.get_local_repo_plugins())
|
||||
for plugin in missing_source_plugins:
|
||||
source_plugin = local_repo_map.get(getattr(plugin, "id", None))
|
||||
if source_plugin:
|
||||
_merge_plugin_source_metadata(plugin, source_plugin)
|
||||
|
||||
missing_source_plugins = [
|
||||
plugin for plugin in installed_plugins if not getattr(plugin, "repo_url", None)
|
||||
]
|
||||
if not missing_source_plugins:
|
||||
return installed_plugins
|
||||
|
||||
market_plugins = await plugin_manager.async_get_online_plugins(force=force_refresh)
|
||||
market_map = _map_plugins_by_id(market_plugins or [])
|
||||
for plugin in missing_source_plugins:
|
||||
source_plugin = market_map.get(getattr(plugin, "id", None))
|
||||
if source_plugin:
|
||||
_merge_plugin_source_metadata(plugin, source_plugin)
|
||||
|
||||
return installed_plugins
|
||||
|
||||
|
||||
async def load_market_plugins(force_refresh: bool = False) -> list[Any]:
|
||||
"""
|
||||
聚合插件市场与本地插件仓库中的候选插件。
|
||||
"""
|
||||
plugin_manager = get_plugin_manager()
|
||||
online_plugins = await plugin_manager.async_get_online_plugins(force=force_refresh)
|
||||
local_repo_plugins = plugin_manager.get_local_repo_plugins()
|
||||
if not online_plugins and not local_repo_plugins:
|
||||
return []
|
||||
return plugin_manager.process_plugins_list(online_plugins + local_repo_plugins, [])
|
||||
|
||||
|
||||
def list_installed_plugins() -> list[Any]:
|
||||
"""
|
||||
返回当前已安装插件列表。
|
||||
"""
|
||||
plugin_manager = get_plugin_manager()
|
||||
return [plugin for plugin in plugin_manager.get_local_plugins() if plugin.installed]
|
||||
|
||||
|
||||
def _normalize_text(value: Optional[str]) -> str:
|
||||
return (value or "").strip().lower()
|
||||
|
||||
|
||||
def is_exact_plugin_match(plugin: Any, query: str) -> bool:
|
||||
"""
|
||||
精确匹配插件 ID 或插件名称,用于安全地自动选择候选。
|
||||
"""
|
||||
normalized_query = _normalize_text(query)
|
||||
return normalized_query in {
|
||||
_normalize_text(getattr(plugin, "id", None)),
|
||||
_normalize_text(getattr(plugin, "plugin_name", None)),
|
||||
}
|
||||
|
||||
|
||||
def search_plugin_candidates(query: str, plugins: list[Any]) -> list[dict[str, Any]]:
|
||||
"""
|
||||
按插件 ID、名称、描述和作者搜索候选,并返回打分结果。
|
||||
"""
|
||||
normalized_query = _normalize_text(query)
|
||||
if not normalized_query:
|
||||
return []
|
||||
|
||||
tokens = [token for token in normalized_query.replace("-", " ").split() if token]
|
||||
matches: list[dict[str, Any]] = []
|
||||
|
||||
for plugin in plugins:
|
||||
plugin_id = _normalize_text(getattr(plugin, "id", None))
|
||||
plugin_name = _normalize_text(getattr(plugin, "plugin_name", None))
|
||||
plugin_desc = _normalize_text(getattr(plugin, "plugin_desc", None))
|
||||
plugin_author = _normalize_text(getattr(plugin, "plugin_author", None))
|
||||
haystack = "\n".join([plugin_id, plugin_name, plugin_desc, plugin_author])
|
||||
|
||||
score = 0
|
||||
if normalized_query == plugin_id:
|
||||
score = 100
|
||||
elif normalized_query == plugin_name:
|
||||
score = 95
|
||||
elif plugin_id.startswith(normalized_query):
|
||||
score = 85
|
||||
elif plugin_name.startswith(normalized_query):
|
||||
score = 80
|
||||
elif normalized_query in plugin_id:
|
||||
score = 75
|
||||
elif normalized_query in plugin_name:
|
||||
score = 70
|
||||
elif tokens and all(token in plugin_name for token in tokens):
|
||||
score = 68
|
||||
elif tokens and all(token in plugin_id for token in tokens):
|
||||
score = 66
|
||||
elif normalized_query in plugin_desc:
|
||||
score = 45
|
||||
elif normalized_query in plugin_author:
|
||||
score = 40
|
||||
elif tokens and all(token in haystack for token in tokens):
|
||||
score = 35
|
||||
|
||||
if score <= 0:
|
||||
continue
|
||||
|
||||
matches.append(
|
||||
{
|
||||
"plugin": plugin,
|
||||
"score": score,
|
||||
"exact": is_exact_plugin_match(plugin, normalized_query),
|
||||
}
|
||||
)
|
||||
|
||||
return sorted(
|
||||
matches,
|
||||
key=lambda item: (
|
||||
-item["score"],
|
||||
not item["exact"],
|
||||
-int(bool(getattr(item["plugin"], "has_update", False))),
|
||||
-int(bool(getattr(item["plugin"], "installed", False))),
|
||||
-int(getattr(item["plugin"], "add_time", 0) or 0),
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def summarize_candidates(matches: list[dict[str, Any]], limit: int = DEFAULT_PLUGIN_CANDIDATE_LIMIT) -> list[dict[str, Any]]:
|
||||
"""
|
||||
压缩候选列表,避免一次性把完整市场数据返回给 Agent。
|
||||
"""
|
||||
return [
|
||||
{
|
||||
**summarize_plugin(item["plugin"]),
|
||||
"score": item["score"],
|
||||
"exact": item["exact"],
|
||||
}
|
||||
for item in matches[:limit]
|
||||
]
|
||||
|
||||
|
||||
async def install_plugin_runtime(
|
||||
plugin_id: str,
|
||||
repo_url: Optional[str],
|
||||
force: bool = False,
|
||||
*,
|
||||
explicit_source: bool = False,
|
||||
) -> tuple[bool, str, bool]:
|
||||
"""
|
||||
按现有插件接口的行为安装插件,并刷新运行态注册信息。
|
||||
"""
|
||||
result = await get_plugin_install_service().install(
|
||||
plugin_id=plugin_id,
|
||||
repo_url=repo_url or None,
|
||||
force=force,
|
||||
explicit_source=explicit_source,
|
||||
)
|
||||
return result.success, result.message, result.refreshed_only
|
||||
|
||||
|
||||
async def inspect_plugin_sources(
|
||||
plugin_id: str,
|
||||
*,
|
||||
force: bool = False,
|
||||
) -> dict[str, Any]:
|
||||
"""返回 Agent 可展示的脱敏来源候选与当前准入状态。"""
|
||||
inspection = await get_plugin_install_service().inspect_source(
|
||||
plugin_id=plugin_id,
|
||||
force=force,
|
||||
)
|
||||
candidates = [
|
||||
candidate.public_dict()
|
||||
for candidate in inspection.online_candidates
|
||||
]
|
||||
if inspection.local_candidate is not None:
|
||||
candidates.append(inspection.local_candidate.public_dict())
|
||||
return {
|
||||
"selection_status": inspection.selection.status.value,
|
||||
"selection_reason": inspection.selection.reason,
|
||||
"inventory_complete": inspection.inventory_complete,
|
||||
"candidates": candidates,
|
||||
}
|
||||
|
||||
|
||||
async def uninstall_plugin_runtime(plugin_id: str) -> dict[str, Any]:
|
||||
"""
|
||||
按现有卸载逻辑移除插件,并清理运行态注册与分组信息。
|
||||
"""
|
||||
from app.application.plugin.folders import remove_plugin_from_folders
|
||||
from app.application.plugin.routes import remove_plugin_api
|
||||
from app.application.scheduling import remove_plugin_job
|
||||
from app.agent.tools.base import run_agent_blocking
|
||||
|
||||
plugin_manager = get_plugin_manager()
|
||||
with plugin_manager.mutation(f"卸载插件 {plugin_id}"):
|
||||
virtual_instance = plugin_manager.get_plugin_instance(plugin_id)
|
||||
source_instances = plugin_manager.get_plugin_source_instances(plugin_id)
|
||||
if not virtual_instance and source_instances:
|
||||
instance_ids = "、".join(item.instance_id for item in source_instances)
|
||||
raise ValueError(f"请先卸载该插件的分身:{instance_ids}")
|
||||
|
||||
config_oper = get_configured_system_config()
|
||||
install_plugins = config_oper.get(SystemConfigKey.UserInstalledPlugins) or []
|
||||
if plugin_id in install_plugins:
|
||||
install_plugins = [
|
||||
plugin for plugin in install_plugins if plugin != plugin_id
|
||||
]
|
||||
await config_oper.async_set(
|
||||
SystemConfigKey.UserInstalledPlugins,
|
||||
install_plugins,
|
||||
)
|
||||
|
||||
remove_plugin_api(plugin_id)
|
||||
remove_plugin_job(plugin_id)
|
||||
|
||||
plugin_class = plugin_manager.plugins.get(plugin_id)
|
||||
was_clone = bool(getattr(plugin_class, "is_clone", False))
|
||||
clone_files_removed = False
|
||||
|
||||
if virtual_instance:
|
||||
plugin_manager.delete_plugin_config(plugin_id, force=True)
|
||||
plugin_manager.delete_plugin_data(plugin_id, force=True)
|
||||
plugin_manager.delete_plugin_instance(plugin_id)
|
||||
elif was_clone:
|
||||
plugin_manager.delete_plugin_config(plugin_id)
|
||||
plugin_manager.delete_plugin_data(plugin_id)
|
||||
try:
|
||||
clone_files_removed = await run_agent_blocking(
|
||||
"plugin",
|
||||
plugin_manager.remove_plugin_package,
|
||||
plugin_id,
|
||||
)
|
||||
if clone_files_removed:
|
||||
plugin_manager.plugins.pop(plugin_id, None)
|
||||
except Exception:
|
||||
clone_files_removed = False
|
||||
|
||||
remove_plugin_from_folders(plugin_id)
|
||||
plugin_manager.remove_plugin(plugin_id)
|
||||
|
||||
return {
|
||||
"was_clone": was_clone,
|
||||
"clone_files_removed": clone_files_removed,
|
||||
}
|
||||
@@ -1,403 +0,0 @@
|
||||
"""系统设置工具共用的键解析与分组元数据。"""
|
||||
|
||||
from dataclasses import dataclass
|
||||
from typing import Any, Optional
|
||||
|
||||
from app.agent.policy.secrets import is_secret_setting_key
|
||||
from app.runtime.config import Settings
|
||||
from app.schemas.types import SystemConfigKey
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class SettingSpec:
|
||||
"""描述一个可被 Agent 读写的系统设置项。"""
|
||||
|
||||
key: str
|
||||
source: str
|
||||
group: str
|
||||
label: str
|
||||
systemconfig_key: Optional[SystemConfigKey] = None
|
||||
|
||||
|
||||
SYSTEMCONFIG_SETTING_METADATA = {
|
||||
SystemConfigKey.Downloaders.value: {
|
||||
"group": "downloaders",
|
||||
"label": "下载器配置",
|
||||
},
|
||||
SystemConfigKey.MediaServers.value: {
|
||||
"group": "media_servers",
|
||||
"label": "媒体服务器配置",
|
||||
},
|
||||
SystemConfigKey.Notifications.value: {
|
||||
"group": "notifications",
|
||||
"label": "消息通知配置",
|
||||
},
|
||||
SystemConfigKey.NotificationSwitchs.value: {
|
||||
"group": "notification_switches",
|
||||
"label": "通知场景开关",
|
||||
},
|
||||
SystemConfigKey.Directories.value: {
|
||||
"group": "directories",
|
||||
"label": "目录配置",
|
||||
},
|
||||
SystemConfigKey.Storages.value: {
|
||||
"group": "storages",
|
||||
"label": "存储配置",
|
||||
},
|
||||
SystemConfigKey.IndexerSites.value: {
|
||||
"group": "search_sites",
|
||||
"label": "搜索站点范围",
|
||||
},
|
||||
SystemConfigKey.RssSites.value: {
|
||||
"group": "subscribe_sites",
|
||||
"label": "订阅站点范围",
|
||||
},
|
||||
SystemConfigKey.UserSiteAuthParams.value: {
|
||||
"group": "site_auth",
|
||||
"label": "站点认证参数",
|
||||
},
|
||||
SystemConfigKey.AIAgentConfig.value: {
|
||||
"group": "ai_agent",
|
||||
"label": "AI 智能体配置",
|
||||
},
|
||||
SystemConfigKey.AIAgentMcpServers.value: {
|
||||
"group": "ai_agent",
|
||||
"label": "AI 智能体外部 MCP 服务器",
|
||||
},
|
||||
SystemConfigKey.CustomIdentifiers.value: {
|
||||
"group": "custom_identifiers",
|
||||
"label": "自定义识别词",
|
||||
},
|
||||
SystemConfigKey.EpisodeFormatRuleTable.value: {
|
||||
"group": "transfer",
|
||||
"label": "集数定位规则词表",
|
||||
},
|
||||
SystemConfigKey.CustomReleaseGroups.value: {
|
||||
"group": "customization",
|
||||
"label": "自定义制作组/字幕组",
|
||||
},
|
||||
SystemConfigKey.Customization.value: {
|
||||
"group": "customization",
|
||||
"label": "自定义占位符",
|
||||
},
|
||||
SystemConfigKey.TransferExcludeWords.value: {
|
||||
"group": "transfer",
|
||||
"label": "整理屏蔽词",
|
||||
},
|
||||
SystemConfigKey.TorrentsPriority.value: {
|
||||
"group": "filter_rules",
|
||||
"label": "种子优先级规则",
|
||||
},
|
||||
SystemConfigKey.CustomFilterRules.value: {
|
||||
"group": "filter_rules",
|
||||
"label": "用户自定义规则",
|
||||
},
|
||||
SystemConfigKey.UserFilterRuleGroups.value: {
|
||||
"group": "filter_rules",
|
||||
"label": "用户规则组",
|
||||
},
|
||||
SystemConfigKey.SearchFilterRuleGroups.value: {
|
||||
"group": "filter_rules",
|
||||
"label": "搜索默认过滤规则组",
|
||||
},
|
||||
SystemConfigKey.SubscribeFilterRuleGroups.value: {
|
||||
"group": "filter_rules",
|
||||
"label": "订阅默认过滤规则组",
|
||||
},
|
||||
SystemConfigKey.BestVersionFilterRuleGroups.value: {
|
||||
"group": "filter_rules",
|
||||
"label": "洗版默认过滤规则组",
|
||||
},
|
||||
SystemConfigKey.SubscribeDefaultParams.value: {
|
||||
"group": "subscribe_defaults",
|
||||
"label": "订阅默认参数",
|
||||
},
|
||||
SystemConfigKey.DefaultMovieSubscribeConfig.value: {
|
||||
"group": "subscribe_defaults",
|
||||
"label": "默认电影订阅规则",
|
||||
},
|
||||
SystemConfigKey.DefaultTvSubscribeConfig.value: {
|
||||
"group": "subscribe_defaults",
|
||||
"label": "默认电视剧订阅规则",
|
||||
},
|
||||
SystemConfigKey.DefaultMusicSubscribeConfig.value: {
|
||||
"group": "subscribe_defaults",
|
||||
"label": "默认音乐订阅规则",
|
||||
},
|
||||
SystemConfigKey.UserInstalledPlugins.value: {
|
||||
"group": "plugins",
|
||||
"label": "已安装插件列表",
|
||||
},
|
||||
SystemConfigKey.PluginFolders.value: {
|
||||
"group": "plugins",
|
||||
"label": "插件文件夹分组配置",
|
||||
},
|
||||
SystemConfigKey.PluginInstallReport.value: {
|
||||
"group": "plugins",
|
||||
"label": "插件安装统计",
|
||||
},
|
||||
SystemConfigKey.NotificationSendTime.value: {
|
||||
"group": "notifications",
|
||||
"label": "通知发送时间",
|
||||
},
|
||||
SystemConfigKey.NotificationTemplates.value: {
|
||||
"group": "notifications",
|
||||
"label": "通知模板",
|
||||
},
|
||||
SystemConfigKey.ScrapingSwitchs.value: {
|
||||
"group": "scraping",
|
||||
"label": "刮削开关设置",
|
||||
},
|
||||
SystemConfigKey.FollowSubscribers.value: {
|
||||
"group": "subscribe_sites",
|
||||
"label": "Follow 订阅分享者",
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
LIST_ITEM_MATCH_FIELD_DEFAULTS = {
|
||||
SystemConfigKey.Downloaders.value: "name",
|
||||
SystemConfigKey.MediaServers.value: "name",
|
||||
SystemConfigKey.Notifications.value: "name",
|
||||
SystemConfigKey.NotificationSwitchs.value: "type",
|
||||
SystemConfigKey.Directories.value: "name",
|
||||
SystemConfigKey.Storages.value: "name",
|
||||
}
|
||||
|
||||
|
||||
GROUP_ALIASES = {
|
||||
"all": "all",
|
||||
"全部": "all",
|
||||
"settings": "settings",
|
||||
"basic": "settings",
|
||||
"基础设置": "settings",
|
||||
"基础配置": "settings",
|
||||
"systemconfig": "systemconfig",
|
||||
"system_config": "systemconfig",
|
||||
"系统设置": "systemconfig",
|
||||
"系统配置": "systemconfig",
|
||||
"downloaders": "downloaders",
|
||||
"downloader": "downloaders",
|
||||
"下载器": "downloaders",
|
||||
"media_servers": "media_servers",
|
||||
"mediaservers": "media_servers",
|
||||
"media-servers": "media_servers",
|
||||
"媒体服务器": "media_servers",
|
||||
"notifications": "notifications",
|
||||
"notification": "notifications",
|
||||
"消息通知": "notifications",
|
||||
"通知": "notifications",
|
||||
"notification_switches": "notification_switches",
|
||||
"notification_switchs": "notification_switches",
|
||||
"通知开关": "notification_switches",
|
||||
"storages": "storages",
|
||||
"storage": "storages",
|
||||
"存储": "storages",
|
||||
"directories": "directories",
|
||||
"directory": "directories",
|
||||
"目录": "directories",
|
||||
"search_sites": "search_sites",
|
||||
"indexer_sites": "search_sites",
|
||||
"搜索站点": "search_sites",
|
||||
"subscribe_sites": "subscribe_sites",
|
||||
"rss_sites": "subscribe_sites",
|
||||
"订阅站点": "subscribe_sites",
|
||||
"site_auth": "site_auth",
|
||||
"site_auth_params": "site_auth",
|
||||
"站点认证": "site_auth",
|
||||
"ai_agent": "ai_agent",
|
||||
"agent": "ai_agent",
|
||||
"智能体": "ai_agent",
|
||||
"custom_identifiers": "custom_identifiers",
|
||||
"自定义识别词": "custom_identifiers",
|
||||
"filter_rules": "filter_rules",
|
||||
"过滤规则": "filter_rules",
|
||||
"subscribe_defaults": "subscribe_defaults",
|
||||
"订阅默认": "subscribe_defaults",
|
||||
"plugins": "plugins",
|
||||
"插件": "plugins",
|
||||
"customization": "customization",
|
||||
"自定义": "customization",
|
||||
"transfer": "transfer",
|
||||
"整理": "transfer",
|
||||
"scraping": "scraping",
|
||||
"刮削": "scraping",
|
||||
"misc": "misc",
|
||||
"其他": "misc",
|
||||
}
|
||||
|
||||
|
||||
# 这些前缀共同组成可启动、推理和扩展 AI Agent 的同一业务配置域。
|
||||
AI_AGENT_CORE_SETTING_PREFIXES = (
|
||||
"AI_AGENT_",
|
||||
"LLM_",
|
||||
"AUDIO_INPUT_",
|
||||
"AUDIO_OUTPUT_",
|
||||
"AI_RECOMMEND_",
|
||||
)
|
||||
|
||||
|
||||
def _normalize_token(value: str) -> str:
|
||||
return str(value).strip().lower().replace("-", "_")
|
||||
|
||||
|
||||
def _resolve_core_setting_group(key: str) -> str:
|
||||
"""根据基础设置的业务归属返回 Agent 可查询的分类。"""
|
||||
|
||||
if key.startswith(AI_AGENT_CORE_SETTING_PREFIXES):
|
||||
return "ai_agent"
|
||||
return "settings"
|
||||
|
||||
|
||||
def _build_specs() -> tuple[dict[str, SettingSpec], dict[str, SettingSpec]]:
|
||||
core_specs = {
|
||||
key: SettingSpec(
|
||||
key=key,
|
||||
source="settings",
|
||||
group=_resolve_core_setting_group(key),
|
||||
label=key,
|
||||
)
|
||||
for key in Settings.model_fields.keys()
|
||||
}
|
||||
system_specs = {}
|
||||
for item in SystemConfigKey:
|
||||
metadata = SYSTEMCONFIG_SETTING_METADATA.get(item.value, {})
|
||||
system_specs[item.value] = SettingSpec(
|
||||
key=item.value,
|
||||
source="systemconfig",
|
||||
group=metadata.get("group", "misc"),
|
||||
label=metadata.get("label", item.value),
|
||||
systemconfig_key=item,
|
||||
)
|
||||
return core_specs, system_specs
|
||||
|
||||
|
||||
CORE_SETTING_SPECS, SYSTEMCONFIG_SETTING_SPECS = _build_specs()
|
||||
ALL_SETTING_SPECS = {**CORE_SETTING_SPECS, **SYSTEMCONFIG_SETTING_SPECS}
|
||||
|
||||
|
||||
SETTING_KEY_ALIASES = {}
|
||||
for key in CORE_SETTING_SPECS:
|
||||
SETTING_KEY_ALIASES[_normalize_token(key)] = key
|
||||
for item in SystemConfigKey:
|
||||
SETTING_KEY_ALIASES[_normalize_token(item.value)] = item.value
|
||||
SETTING_KEY_ALIASES[_normalize_token(item.name)] = item.value
|
||||
|
||||
SINGLE_KEY_GROUP_ALIASES = {
|
||||
_normalize_token(alias): next(
|
||||
(
|
||||
spec.key
|
||||
for spec in ALL_SETTING_SPECS.values()
|
||||
if spec.group == canonical_group
|
||||
),
|
||||
None,
|
||||
)
|
||||
for alias, canonical_group in GROUP_ALIASES.items()
|
||||
if canonical_group not in {"all", "settings", "systemconfig"}
|
||||
and len(
|
||||
[
|
||||
spec.key
|
||||
for spec in ALL_SETTING_SPECS.values()
|
||||
if spec.group == canonical_group
|
||||
]
|
||||
)
|
||||
== 1
|
||||
}
|
||||
|
||||
|
||||
def normalize_group(group: Optional[str]) -> str:
|
||||
if not group:
|
||||
return "all"
|
||||
normalized = GROUP_ALIASES.get(_normalize_token(group))
|
||||
if not normalized:
|
||||
raise ValueError(
|
||||
"group 不支持,支持值包括 all/settings/systemconfig 以及"
|
||||
" downloaders、media_servers、notifications、storages、directories、"
|
||||
"search_sites、subscribe_sites、site_auth、ai_agent 等分类别名"
|
||||
)
|
||||
return normalized
|
||||
|
||||
|
||||
def resolve_setting_spec(setting_key: Optional[str]) -> Optional[SettingSpec]:
|
||||
"""把精确键名、枚举名或单键分组别名解析为统一的设置定义。"""
|
||||
|
||||
if not setting_key:
|
||||
return None
|
||||
|
||||
normalized = _normalize_token(setting_key)
|
||||
resolved_key = SETTING_KEY_ALIASES.get(normalized) or SINGLE_KEY_GROUP_ALIASES.get(
|
||||
normalized
|
||||
)
|
||||
if not resolved_key:
|
||||
return None
|
||||
return ALL_SETTING_SPECS.get(resolved_key)
|
||||
|
||||
|
||||
def list_setting_specs(
|
||||
group: Optional[str] = "all", keyword: Optional[str] = None
|
||||
) -> list[SettingSpec]:
|
||||
"""按分组和关键字筛选可查询的设置项。"""
|
||||
|
||||
normalized_group = normalize_group(group)
|
||||
if normalized_group == "all":
|
||||
specs = list(ALL_SETTING_SPECS.values())
|
||||
elif normalized_group == "settings":
|
||||
specs = list(CORE_SETTING_SPECS.values())
|
||||
elif normalized_group == "systemconfig":
|
||||
specs = list(SYSTEMCONFIG_SETTING_SPECS.values())
|
||||
else:
|
||||
specs = [
|
||||
spec
|
||||
for spec in ALL_SETTING_SPECS.values()
|
||||
if spec.group == normalized_group
|
||||
]
|
||||
|
||||
if keyword:
|
||||
normalized_keyword = _normalize_token(keyword)
|
||||
specs = [
|
||||
spec
|
||||
for spec in specs
|
||||
if normalized_keyword in _normalize_token(spec.key)
|
||||
or normalized_keyword in _normalize_token(spec.group)
|
||||
or normalized_keyword in _normalize_token(spec.label)
|
||||
]
|
||||
|
||||
return sorted(specs, key=lambda spec: (spec.source, spec.group, spec.key))
|
||||
|
||||
|
||||
def get_default_list_match_field(setting_key: str) -> Optional[str]:
|
||||
return LIST_ITEM_MATCH_FIELD_DEFAULTS.get(setting_key)
|
||||
|
||||
|
||||
def redact_secret_value(value: Any, *, redact_scalar: bool = False) -> Any:
|
||||
"""递归脱敏配置值中的密钥、Cookie、Token 等敏感字段。"""
|
||||
if isinstance(value, dict):
|
||||
return {
|
||||
key: "***"
|
||||
if is_secret_setting_key(str(key))
|
||||
else redact_secret_value(item, redact_scalar=redact_scalar)
|
||||
for key, item in value.items()
|
||||
}
|
||||
if isinstance(value, list):
|
||||
return [
|
||||
redact_secret_value(item, redact_scalar=redact_scalar)
|
||||
for item in value
|
||||
]
|
||||
if isinstance(value, str):
|
||||
return "***" if value and redact_scalar else value
|
||||
return value
|
||||
|
||||
|
||||
def should_redact_setting(spec: SettingSpec, value: Any) -> bool:
|
||||
"""判断某项设置在默认查询响应中是否需要脱敏。"""
|
||||
if is_secret_setting_key(spec.key):
|
||||
return True
|
||||
if isinstance(value, dict):
|
||||
return any(is_secret_setting_key(str(key)) for key in value.keys())
|
||||
if isinstance(value, list):
|
||||
return any(
|
||||
should_redact_setting(spec, item)
|
||||
for item in value
|
||||
if isinstance(item, dict)
|
||||
)
|
||||
return False
|
||||
@@ -1,211 +0,0 @@
|
||||
"""种子搜索工具辅助函数"""
|
||||
|
||||
import re
|
||||
from typing import List, Optional
|
||||
|
||||
from app.domain.context import Context
|
||||
from app.schemas.types import MediaType, media_type_to_agent
|
||||
from app.foundation.crypto import HashUtils
|
||||
from app.foundation import size as size_tools
|
||||
from ._music_utils import simplify_music_info
|
||||
|
||||
SEARCH_RESULT_CACHE_FILE = "__search_result__"
|
||||
TORRENT_RESULT_LIMIT = 50
|
||||
|
||||
|
||||
def build_torrent_ref(context: Optional[Context]) -> str:
|
||||
"""生成用于下载校验的短引用"""
|
||||
if not context or not context.torrent_info:
|
||||
return ""
|
||||
return HashUtils.sha1(context.torrent_info.enclosure or "")[:7]
|
||||
|
||||
|
||||
def sort_season_options(options: List[str]) -> List[str]:
|
||||
"""按前端逻辑排序季集选项"""
|
||||
if len(options) <= 1:
|
||||
return options
|
||||
|
||||
parsed_options = []
|
||||
for index, option in enumerate(options):
|
||||
match = re.match(r"^S(\d+)(?:-S(\d+))?\s*(?:E(\d+)(?:-E(\d+))?)?$", option or "")
|
||||
if not match:
|
||||
parsed_options.append({
|
||||
"original": option,
|
||||
"season_num": 0,
|
||||
"episode_num": 0,
|
||||
"max_episode_num": 0,
|
||||
"is_whole_season": False,
|
||||
"index": index,
|
||||
})
|
||||
continue
|
||||
|
||||
episode_num = int(match.group(3)) if match.group(3) else 0
|
||||
max_episode_num = int(match.group(4)) if match.group(4) else episode_num
|
||||
parsed_options.append({
|
||||
"original": option,
|
||||
"season_num": int(match.group(1)),
|
||||
"episode_num": episode_num,
|
||||
"max_episode_num": max_episode_num,
|
||||
"is_whole_season": not match.group(3),
|
||||
"index": index,
|
||||
})
|
||||
|
||||
whole_seasons = [item for item in parsed_options if item["is_whole_season"]]
|
||||
episodes = [item for item in parsed_options if not item["is_whole_season"]]
|
||||
|
||||
whole_seasons.sort(key=lambda item: (-item["season_num"], item["index"]))
|
||||
episodes.sort(
|
||||
key=lambda item: (
|
||||
-item["season_num"],
|
||||
-(item["max_episode_num"] or item["episode_num"]),
|
||||
-item["episode_num"],
|
||||
item["index"],
|
||||
)
|
||||
)
|
||||
return [item["original"] for item in whole_seasons + episodes]
|
||||
|
||||
|
||||
def append_option(options: List[str], value: Optional[str]) -> None:
|
||||
"""按前端逻辑收集去重后的筛选项"""
|
||||
if value and value not in options:
|
||||
options.append(value)
|
||||
|
||||
|
||||
def build_filter_options(items: List[Context]) -> dict:
|
||||
"""从搜索结果中构建筛选项汇总"""
|
||||
filter_options = {
|
||||
"site": [],
|
||||
"season": [],
|
||||
"freeState": [],
|
||||
"edition": [],
|
||||
"resolution": [],
|
||||
"videoCode": [],
|
||||
"releaseGroup": [],
|
||||
}
|
||||
|
||||
for item in items:
|
||||
torrent_info = item.torrent_info
|
||||
meta_info = item.meta_info
|
||||
append_option(filter_options["site"], getattr(torrent_info, "site_name", None))
|
||||
append_option(filter_options["season"], getattr(meta_info, "season_episode", None))
|
||||
append_option(filter_options["freeState"], getattr(torrent_info, "volume_factor", None))
|
||||
append_option(filter_options["edition"], getattr(meta_info, "edition", None))
|
||||
append_option(filter_options["resolution"], getattr(meta_info, "resource_pix", None))
|
||||
append_option(filter_options["videoCode"], getattr(meta_info, "video_encode", None))
|
||||
append_option(filter_options["releaseGroup"], getattr(meta_info, "resource_team", None))
|
||||
|
||||
filter_options["season"] = sort_season_options(filter_options["season"])
|
||||
return filter_options
|
||||
|
||||
|
||||
def match_filter(filter_values: Optional[List[str]], value: Optional[str]) -> bool:
|
||||
"""匹配前端同款多选筛选规则"""
|
||||
return not filter_values or bool(value and value in filter_values)
|
||||
|
||||
|
||||
def filter_contexts(items: List[Context],
|
||||
site: Optional[List[str]] = None,
|
||||
season: Optional[List[str]] = None,
|
||||
free_state: Optional[List[str]] = None,
|
||||
video_code: Optional[List[str]] = None,
|
||||
edition: Optional[List[str]] = None,
|
||||
resolution: Optional[List[str]] = None,
|
||||
release_group: Optional[List[str]] = None) -> List[Context]:
|
||||
"""按前端同款维度筛选结果"""
|
||||
filtered_items = []
|
||||
for item in items:
|
||||
torrent_info = item.torrent_info
|
||||
meta_info = item.meta_info
|
||||
if (
|
||||
match_filter(site, getattr(torrent_info, "site_name", None))
|
||||
and match_filter(free_state, getattr(torrent_info, "volume_factor", None))
|
||||
and match_filter(season, getattr(meta_info, "season_episode", None))
|
||||
and match_filter(release_group, getattr(meta_info, "resource_team", None))
|
||||
and match_filter(video_code, getattr(meta_info, "video_encode", None))
|
||||
and match_filter(resolution, getattr(meta_info, "resource_pix", None))
|
||||
and match_filter(edition, getattr(meta_info, "edition", None))
|
||||
):
|
||||
filtered_items.append(item)
|
||||
return filtered_items
|
||||
|
||||
|
||||
def simplify_search_result(
|
||||
context: Context,
|
||||
index: int,
|
||||
include_description: bool = False,
|
||||
include_labels: bool = False,
|
||||
) -> dict:
|
||||
"""
|
||||
精简单条搜索结果
|
||||
|
||||
:param context: 搜索结果上下文
|
||||
:param index: 搜索结果在原始缓存中的序号
|
||||
:param include_description: 是否返回种子简介
|
||||
:param include_labels: 是否返回种子标签
|
||||
:return: 精简后的搜索结果
|
||||
"""
|
||||
simplified = {}
|
||||
torrent_info = context.torrent_info
|
||||
meta_info = context.meta_info
|
||||
media_info = context.media_info
|
||||
|
||||
if torrent_info:
|
||||
simplified["torrent_info"] = {
|
||||
"title": torrent_info.title,
|
||||
"size": size_tools.format_size(torrent_info.size),
|
||||
"seeders": torrent_info.seeders,
|
||||
"peers": torrent_info.peers,
|
||||
"site_name": torrent_info.site_name,
|
||||
"torrent_url": f"{build_torrent_ref(context)}:{index}",
|
||||
"page_url": torrent_info.page_url,
|
||||
"volume_factor": torrent_info.volume_factor,
|
||||
"freedate_diff": torrent_info.freedate_diff,
|
||||
"pubdate": torrent_info.pubdate,
|
||||
}
|
||||
if include_description:
|
||||
simplified["torrent_info"]["description"] = torrent_info.description
|
||||
if include_labels:
|
||||
simplified["torrent_info"]["labels"] = torrent_info.labels or []
|
||||
|
||||
if media_info:
|
||||
if getattr(media_info, "type", None) == MediaType.MUSIC:
|
||||
simplified["media_info"] = simplify_music_info(media_info)
|
||||
else:
|
||||
simplified["media_info"] = {
|
||||
"title": getattr(media_info, "title", None),
|
||||
"en_title": getattr(media_info, "en_title", None),
|
||||
"year": getattr(media_info, "year", None),
|
||||
"type": media_type_to_agent(getattr(media_info, "type", None)),
|
||||
"season": getattr(media_info, "season", None),
|
||||
"tmdb_id": getattr(media_info, "tmdb_id", None),
|
||||
}
|
||||
|
||||
if meta_info:
|
||||
if getattr(meta_info, "type", None) == MediaType.MUSIC:
|
||||
simplified["meta_info"] = {
|
||||
key: getattr(meta_info, key, None)
|
||||
for key in (
|
||||
"title", "artists", "album", "album_artist", "year",
|
||||
"disc_number", "track_number", "total_tracks", "version",
|
||||
"audio_format", "bit_depth", "sample_rate", "bitrate",
|
||||
"duration", "isrc", "media_source", "media_id",
|
||||
)
|
||||
if getattr(meta_info, key, None) not in (None, "", [])
|
||||
}
|
||||
simplified["meta_info"]["type"] = "music"
|
||||
else:
|
||||
simplified["meta_info"] = {
|
||||
"name": getattr(meta_info, "name", None),
|
||||
"cn_name": getattr(meta_info, "cn_name", None),
|
||||
"en_name": getattr(meta_info, "en_name", None),
|
||||
"year": getattr(meta_info, "year", None),
|
||||
"type": media_type_to_agent(getattr(meta_info, "type", None)),
|
||||
"begin_season": getattr(meta_info, "begin_season", None),
|
||||
"season_episode": getattr(meta_info, "season_episode", None),
|
||||
"resource_team": getattr(meta_info, "resource_team", None),
|
||||
"video_encode": getattr(meta_info, "video_encode", None),
|
||||
"edition": getattr(meta_info, "edition", None),
|
||||
"resource_pix": getattr(meta_info, "resource_pix", None),
|
||||
}
|
||||
|
||||
return simplified
|
||||
@@ -1,113 +0,0 @@
|
||||
"""新增自定义过滤规则工具。"""
|
||||
|
||||
import json
|
||||
from typing import Optional, Type
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from app.agent.tools.base import MoviePilotTool
|
||||
from app.agent.tools.tags import ToolTag
|
||||
from app.agent.tools.impl._filter_rule_utils import (
|
||||
get_custom_rules,
|
||||
normalize_custom_rule,
|
||||
save_system_config,
|
||||
serialize_custom_rule,
|
||||
)
|
||||
from app.runtime.log import logger
|
||||
from app.schemas.types import SystemConfigKey
|
||||
|
||||
|
||||
class AddCustomFilterRuleInput(BaseModel):
|
||||
"""新增自定义过滤规则工具的输入参数模型"""
|
||||
|
||||
rule_id: str = Field(
|
||||
...,
|
||||
description="Unique custom rule ID. Only letters and numbers are allowed.",
|
||||
)
|
||||
name: str = Field(..., description="Display name of the custom rule.")
|
||||
include: Optional[str] = Field(
|
||||
None, description="Optional include regex for the rule."
|
||||
)
|
||||
exclude: Optional[str] = Field(
|
||||
None, description="Optional exclude regex for the rule."
|
||||
)
|
||||
size_range: Optional[str] = Field(
|
||||
None, description="Optional size range in MB, for example '1000-5000'."
|
||||
)
|
||||
seeders: Optional[str] = Field(
|
||||
None, description="Optional minimum seeder count as a non-negative integer."
|
||||
)
|
||||
publish_time: Optional[str] = Field(
|
||||
None,
|
||||
description="Optional publish-time filter in minutes, for example '60' or '60-1440'.",
|
||||
)
|
||||
|
||||
|
||||
class AddCustomFilterRuleTool(MoviePilotTool):
|
||||
name: str = "add_custom_filter_rule"
|
||||
tags: list[str] = [
|
||||
ToolTag.Write,
|
||||
ToolTag.FilterRule,
|
||||
ToolTag.Admin,
|
||||
]
|
||||
description: str = (
|
||||
"Add a custom filter rule to CustomFilterRules. "
|
||||
"The new rule can then be referenced by rule ID inside filter rule groups."
|
||||
)
|
||||
args_schema: Type[BaseModel] = AddCustomFilterRuleInput
|
||||
require_admin: bool = True
|
||||
|
||||
def get_tool_message(self, **kwargs) -> Optional[str]:
|
||||
return f"新增自定义过滤规则 {kwargs.get('rule_id', '')}"
|
||||
|
||||
async def run(
|
||||
self,
|
||||
rule_id: str,
|
||||
name: str,
|
||||
include: Optional[str] = None,
|
||||
exclude: Optional[str] = None,
|
||||
size_range: Optional[str] = None,
|
||||
seeders: Optional[str] = None,
|
||||
publish_time: Optional[str] = None,
|
||||
**kwargs,
|
||||
) -> str:
|
||||
logger.info(f"执行工具: {self.name}, rule_id={rule_id}")
|
||||
|
||||
try:
|
||||
custom_rules = get_custom_rules()
|
||||
new_rule = normalize_custom_rule(
|
||||
rule_id=rule_id,
|
||||
name=name,
|
||||
include=include,
|
||||
exclude=exclude,
|
||||
size_range=size_range,
|
||||
seeders=seeders,
|
||||
publish_time=publish_time,
|
||||
existing_rules=custom_rules,
|
||||
)
|
||||
|
||||
custom_rules.append(new_rule)
|
||||
await save_system_config(
|
||||
SystemConfigKey.CustomFilterRules,
|
||||
[rule.model_dump(exclude_none=True) for rule in custom_rules],
|
||||
)
|
||||
|
||||
return json.dumps(
|
||||
{
|
||||
"success": True,
|
||||
"message": f"已新增自定义过滤规则 {new_rule.id}",
|
||||
"custom_rule": serialize_custom_rule(new_rule),
|
||||
"count": len(custom_rules),
|
||||
},
|
||||
ensure_ascii=False,
|
||||
indent=2,
|
||||
)
|
||||
except Exception as exc:
|
||||
logger.error(f"新增自定义过滤规则失败: {exc}", exc_info=True)
|
||||
return json.dumps(
|
||||
{
|
||||
"success": False,
|
||||
"message": f"新增自定义过滤规则失败: {exc}",
|
||||
},
|
||||
ensure_ascii=False,
|
||||
)
|
||||
@@ -1,368 +0,0 @@
|
||||
"""添加下载任务工具"""
|
||||
|
||||
import copy
|
||||
import re
|
||||
from pathlib import Path
|
||||
from typing import List, Optional, Type, Union, cast
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from app.agent.tools.base import MoviePilotTool
|
||||
from app.agent.tools.tags import ToolTag
|
||||
from app.application.directory import DirectoryHelper, validate_download_save_path
|
||||
from app.chain.download import DownloadChain
|
||||
from app.chain.media import MediaChain
|
||||
|
||||
# SearchChain 由包根惰性公开,Pylint 无法静态解析 __getattr__ 映射。
|
||||
from app.chain.search.facade import SearchChain
|
||||
from app.domain.context import Context
|
||||
from app.domain.metainfo import MetaInfo
|
||||
from app.foundation.crypto import HashUtils
|
||||
from app.runtime.log import logger
|
||||
from app.runtime.settings import get_runtime_setting
|
||||
from app.schemas.file import FileURI
|
||||
|
||||
|
||||
class AddDownloadTasksInput(BaseModel):
|
||||
"""添加下载任务工具的输入参数模型"""
|
||||
|
||||
torrent_url: List[str] = Field(
|
||||
...,
|
||||
description="One or more torrent_url values. Supports refs from get_search_results (`hash:id`) and magnet links."
|
||||
)
|
||||
downloader: Optional[str] = Field(None,
|
||||
description="Name of the downloader to use (optional, uses default if not specified)")
|
||||
save_path: Optional[str] = Field(None,
|
||||
description="Directory path where the downloaded files should be saved. Using `<storage>:<path>` for remote storage. e.g. rclone:/MP, smb:/server/share/Movies. (optional, uses default path if not specified)")
|
||||
labels: Optional[str] = Field(None,
|
||||
description="Comma-separated list of labels/tags to assign to the download (optional, e.g., 'movie,hd,bluray')")
|
||||
|
||||
|
||||
class AddDownloadTasksTool(MoviePilotTool):
|
||||
"""添加下载任务工具"""
|
||||
|
||||
name: str = "add_download_tasks"
|
||||
tags: list[str] = [
|
||||
ToolTag.Write,
|
||||
ToolTag.Download,
|
||||
ToolTag.Resource,
|
||||
]
|
||||
description: str = "Add torrent download tasks using refs from get_search_results or magnet links."
|
||||
args_schema: Type[BaseModel] = AddDownloadTasksInput
|
||||
|
||||
def get_tool_message(self, **kwargs) -> Optional[str]:
|
||||
"""根据下载参数生成友好的提示消息"""
|
||||
torrent_urls = self._normalize_torrent_urls(kwargs.get("torrent_url"))
|
||||
downloader = kwargs.get("downloader")
|
||||
|
||||
if torrent_urls:
|
||||
if len(torrent_urls) == 1:
|
||||
if self._is_torrent_ref(torrent_urls[0]):
|
||||
message = f"添加下载任务: 资源 {torrent_urls[0]}"
|
||||
else:
|
||||
message = "添加下载任务: 磁力链接"
|
||||
else:
|
||||
message = f"批量添加下载任务: 共 {len(torrent_urls)} 个资源"
|
||||
else:
|
||||
message = "添加下载任务"
|
||||
if downloader:
|
||||
message += f" [下载器: {downloader}]"
|
||||
|
||||
return message
|
||||
|
||||
@staticmethod
|
||||
def _build_torrent_ref(context: Context) -> str:
|
||||
"""生成用于校验缓存项的短引用"""
|
||||
if not context or not context.torrent_info:
|
||||
return ""
|
||||
return HashUtils.sha1(context.torrent_info.enclosure or "")[:7]
|
||||
|
||||
@staticmethod
|
||||
def _is_torrent_ref(torrent_ref: Optional[str]) -> bool:
|
||||
"""判断是否为内部搜索结果引用"""
|
||||
if not torrent_ref:
|
||||
return False
|
||||
return bool(re.fullmatch(r"[0-9a-f]{7}:\d+", str(torrent_ref).strip()))
|
||||
|
||||
@staticmethod
|
||||
def _is_magnet_link_input(torrent_url: Optional[str]) -> bool:
|
||||
"""判断输入是否为允许直接添加的磁力链接"""
|
||||
if not torrent_url:
|
||||
return False
|
||||
value = str(torrent_url).strip()
|
||||
return value.startswith("magnet:")
|
||||
|
||||
@classmethod
|
||||
def _resolve_cached_context(cls, torrent_ref: str) -> Optional[Context]:
|
||||
"""从最近一次搜索缓存中解析种子上下文,仅支持 hash:id 格式"""
|
||||
ref = str(torrent_ref).strip()
|
||||
if ":" not in ref:
|
||||
return None
|
||||
try:
|
||||
ref_hash, ref_index = ref.split(":", 1)
|
||||
index = int(ref_index)
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
|
||||
if index < 1:
|
||||
return None
|
||||
|
||||
results = cast(List[Context], SearchChain().last_search_results() or [])
|
||||
if index > len(results):
|
||||
return None
|
||||
context = results[index - 1]
|
||||
if not ref_hash or cls._build_torrent_ref(context) != ref_hash:
|
||||
return None
|
||||
return context
|
||||
|
||||
@classmethod
|
||||
async def _async_resolve_cached_context(cls, torrent_ref: str) -> Optional[Context]:
|
||||
"""异步读取最近搜索缓存,避免在协程里直接访问同步文件缓存。"""
|
||||
ref = str(torrent_ref).strip()
|
||||
if ":" not in ref:
|
||||
return None
|
||||
try:
|
||||
ref_hash, ref_index = ref.split(":", 1)
|
||||
index = int(ref_index)
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
|
||||
if index < 1:
|
||||
return None
|
||||
|
||||
results = cast(
|
||||
List[Context],
|
||||
await SearchChain().async_last_search_results() or [],
|
||||
)
|
||||
if index > len(results):
|
||||
return None
|
||||
context = results[index - 1]
|
||||
if not ref_hash or cls._build_torrent_ref(context) != ref_hash:
|
||||
return None
|
||||
return context
|
||||
|
||||
@staticmethod
|
||||
def _merge_labels_with_system_tag(labels: Optional[str]) -> Optional[str]:
|
||||
"""合并用户标签与系统默认标签,确保任务可被系统管理"""
|
||||
system_tag = (get_runtime_setting('TORRENT_TAG') or "").strip()
|
||||
user_labels = [item.strip() for item in (labels or "").split(",") if item.strip()]
|
||||
|
||||
if system_tag and system_tag not in user_labels:
|
||||
user_labels.append(system_tag)
|
||||
|
||||
return ",".join(user_labels) if user_labels else None
|
||||
|
||||
@staticmethod
|
||||
def _format_failed_result(failed_messages: List[str]) -> str:
|
||||
"""统一格式化失败结果"""
|
||||
return ", ".join([message for message in failed_messages if message])
|
||||
|
||||
@staticmethod
|
||||
def _build_failure_message(torrent_ref: str, error_msg: Optional[str] = None) -> str:
|
||||
"""构造失败提示"""
|
||||
normalized_error = (error_msg or "").strip()
|
||||
prefix = "添加种子任务失败:"
|
||||
if normalized_error.startswith(prefix):
|
||||
normalized_error = normalized_error[len(prefix):].lstrip()
|
||||
if AddDownloadTasksTool._is_magnet_link_input(normalized_error):
|
||||
normalized_error = ""
|
||||
if normalized_error:
|
||||
return f"{torrent_ref} {normalized_error}"
|
||||
if AddDownloadTasksTool._is_torrent_ref(torrent_ref):
|
||||
return torrent_ref
|
||||
return ""
|
||||
|
||||
@classmethod
|
||||
def _normalize_torrent_urls(cls, torrent_url: Optional[Union[List[str], str]]) -> List[str]:
|
||||
"""统一规范 torrent_url 输入,保留所有非空值"""
|
||||
if torrent_url is None:
|
||||
return []
|
||||
|
||||
if isinstance(torrent_url, str):
|
||||
candidates = torrent_url.split(",")
|
||||
else:
|
||||
candidates = torrent_url
|
||||
|
||||
return [str(item).strip() for item in candidates if item and str(item).strip()]
|
||||
|
||||
@staticmethod
|
||||
def _resolve_direct_download_dir(save_path: Optional[str]) -> Optional[Path]:
|
||||
"""解析直接下载使用的目录,优先使用 save_path,其次使用默认下载目录"""
|
||||
if save_path is not None:
|
||||
return Path(validate_download_save_path(save_path))
|
||||
|
||||
download_dirs = DirectoryHelper().get_download_dirs()
|
||||
if not download_dirs:
|
||||
return None
|
||||
|
||||
dir_conf = download_dirs[0]
|
||||
if not dir_conf.download_path:
|
||||
return None
|
||||
|
||||
return Path(FileURI(storage=dir_conf.storage or "local", path=dir_conf.download_path).uri)
|
||||
|
||||
@staticmethod
|
||||
def _download_direct_sync(
|
||||
torrent_input: str,
|
||||
download_dir: Path,
|
||||
merged_labels: Optional[str],
|
||||
downloader: Optional[str],
|
||||
) -> tuple[Optional[str], Optional[str]]:
|
||||
"""同步添加磁力下载任务,避免下载器调用阻塞事件循环。"""
|
||||
result = DownloadChain().download(
|
||||
content=torrent_input,
|
||||
download_dir=download_dir,
|
||||
cookie=None,
|
||||
label=merged_labels,
|
||||
downloader=downloader,
|
||||
)
|
||||
if result:
|
||||
_, did, _, error_msg = result
|
||||
else:
|
||||
did, error_msg = None, "未找到下载器"
|
||||
return did, error_msg
|
||||
|
||||
@staticmethod
|
||||
def _download_single_sync(
|
||||
context: Context,
|
||||
downloader: Optional[str],
|
||||
save_path: Optional[str],
|
||||
merged_labels: Optional[str],
|
||||
) -> tuple[Optional[str], Optional[str]]:
|
||||
"""同步提交带上下文的下载任务,避免站点下载与下载器调用阻塞事件循环。"""
|
||||
if save_path is not None:
|
||||
save_path = validate_download_save_path(save_path)
|
||||
return cast(
|
||||
tuple[Optional[str], Optional[str]],
|
||||
DownloadChain().download_single(
|
||||
context=context,
|
||||
downloader=downloader,
|
||||
save_path=save_path,
|
||||
label=merged_labels,
|
||||
return_detail=True,
|
||||
),
|
||||
)
|
||||
|
||||
async def run(self, torrent_url: Optional[List[str]] = None,
|
||||
downloader: Optional[str] = None, save_path: Optional[str] = None,
|
||||
labels: Optional[str] = None, **kwargs) -> str:
|
||||
"""执行添加下载任务。"""
|
||||
logger.info(
|
||||
f"执行工具: {self.name}, 参数: torrent_url={torrent_url}, downloader={downloader}, save_path={save_path}, labels={labels}")
|
||||
|
||||
try:
|
||||
torrent_inputs = self._normalize_torrent_urls(torrent_url)
|
||||
if not torrent_inputs:
|
||||
return "错误:torrent_url 不能为空。"
|
||||
|
||||
if save_path is not None:
|
||||
try:
|
||||
save_path = validate_download_save_path(save_path)
|
||||
except ValueError as err:
|
||||
return f"参数错误:save_path {str(err)}"
|
||||
|
||||
merged_labels = self._merge_labels_with_system_tag(labels)
|
||||
success_count = 0
|
||||
failed_messages = []
|
||||
|
||||
for torrent_input in torrent_inputs:
|
||||
if self._is_torrent_ref(torrent_input):
|
||||
cached_context = await self._async_resolve_cached_context(torrent_input)
|
||||
if not cached_context or not cached_context.torrent_info:
|
||||
failed_messages.append(f"{torrent_input} 引用无效,请重新使用 get_search_results 查看搜索结果")
|
||||
continue
|
||||
|
||||
cached_torrent = cached_context.torrent_info
|
||||
site_name = cached_torrent.site_name
|
||||
torrent_title = cached_torrent.title or torrent_input
|
||||
torrent_description = cached_torrent.description
|
||||
enclosure = cached_torrent.enclosure
|
||||
|
||||
if not site_name:
|
||||
failed_messages.append(f"{torrent_input} 缺少站点名称")
|
||||
continue
|
||||
|
||||
siteinfo = await self.data.sites.async_get_by_name(site_name)
|
||||
if not siteinfo:
|
||||
failed_messages.append(f"{torrent_input} 未找到站点信息 {site_name}")
|
||||
continue
|
||||
|
||||
# 复制完整搜索上下文,只刷新可能变化的站点凭据。音乐上下文中的
|
||||
# MetaMusic、专辑总曲目数和完整覆盖状态必须保留到下载校验层。
|
||||
context = copy.copy(cached_context)
|
||||
torrent_info = copy.copy(cached_torrent)
|
||||
torrent_info.title = torrent_title
|
||||
torrent_info.description = torrent_description
|
||||
torrent_info.enclosure = enclosure
|
||||
torrent_info.site_name = site_name
|
||||
torrent_info.site_ua = siteinfo.ua or ""
|
||||
torrent_info.site_cookie = siteinfo.cookie or ""
|
||||
torrent_info.site_proxy = bool(siteinfo.proxy)
|
||||
torrent_info.site_order = siteinfo.pri or 0
|
||||
torrent_info.site_downloader = siteinfo.downloader or ""
|
||||
context.torrent_info = torrent_info
|
||||
|
||||
meta_info = cached_context.meta_info or MetaInfo(
|
||||
title=torrent_title,
|
||||
subtitle=torrent_description,
|
||||
)
|
||||
media_info = cached_context.media_info if cached_context.media_info else None
|
||||
if not media_info:
|
||||
media_info = await MediaChain().async_recognize_by_meta(
|
||||
meta_info,
|
||||
obtain_images=False,
|
||||
)
|
||||
if not media_info:
|
||||
failed_messages.append(f"{torrent_input} 无法识别媒体信息")
|
||||
continue
|
||||
context.meta_info = meta_info
|
||||
context.media_info = media_info
|
||||
else:
|
||||
if not self._is_magnet_link_input(torrent_input):
|
||||
failed_messages.append(
|
||||
f"{torrent_input} 不是有效的下载内容,非 hash:id 时仅支持 magnet: 开头"
|
||||
)
|
||||
continue
|
||||
download_dir = await self.run_blocking(
|
||||
"storage", self._resolve_direct_download_dir, save_path
|
||||
)
|
||||
if not download_dir:
|
||||
failed_messages.append(f"{torrent_input} 缺少保存路径,且系统未配置可用下载目录")
|
||||
continue
|
||||
did, error_msg = await self.run_blocking(
|
||||
"downloader",
|
||||
self._download_direct_sync,
|
||||
torrent_input,
|
||||
download_dir,
|
||||
merged_labels,
|
||||
downloader,
|
||||
)
|
||||
if did:
|
||||
success_count += 1
|
||||
else:
|
||||
failed_messages.append(self._build_failure_message(torrent_input, error_msg))
|
||||
continue
|
||||
|
||||
did, error_msg = await self.run_blocking(
|
||||
"downloader",
|
||||
self._download_single_sync,
|
||||
context,
|
||||
downloader,
|
||||
save_path,
|
||||
merged_labels,
|
||||
)
|
||||
if did:
|
||||
success_count += 1
|
||||
else:
|
||||
failed_messages.append(self._build_failure_message(torrent_input, error_msg))
|
||||
|
||||
if success_count and not failed_messages:
|
||||
return "任务添加成功"
|
||||
|
||||
if success_count:
|
||||
return f"部分任务添加失败:{self._format_failed_result(failed_messages)}"
|
||||
|
||||
return f"任务添加失败:{self._format_failed_result(failed_messages)}"
|
||||
except Exception as e:
|
||||
logger.error(f"添加下载任务失败: {e}", exc_info=True)
|
||||
return f"添加下载任务时发生错误: {str(e)}"
|
||||
@@ -1,131 +0,0 @@
|
||||
"""新增过滤规则组工具。"""
|
||||
|
||||
import json
|
||||
from typing import Optional, Type
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from app.agent.tools.base import MoviePilotTool
|
||||
from app.agent.tools.impl._filter_rule_utils import (
|
||||
build_custom_rule_map,
|
||||
collect_rule_group_usages,
|
||||
get_builtin_rules,
|
||||
get_custom_rules,
|
||||
get_rule_groups,
|
||||
normalize_rule_group,
|
||||
publish_rule_config_changed,
|
||||
serialize_rule_group,
|
||||
)
|
||||
from app.agent.tools.tags import ToolTag
|
||||
from app.runtime.log import logger
|
||||
from app.schemas.types import SystemConfigKey
|
||||
|
||||
|
||||
class AddRuleGroupInput(BaseModel):
|
||||
"""新增过滤规则组工具的输入参数模型"""
|
||||
|
||||
name: str = Field(..., description="New rule group name.")
|
||||
rule_string: str = Field(
|
||||
...,
|
||||
description=(
|
||||
"Rule expression using built-in/custom rule IDs. "
|
||||
"Use '&', '!' inside one level, and use '>' between priority levels. "
|
||||
"Example: 'SPECSUB & CNVOI & 4K & !BLU > CNSUB & CNVOI & 4K & !BLU'."
|
||||
),
|
||||
)
|
||||
media_type: Optional[str] = Field(
|
||||
None,
|
||||
description="Optional media type scope: '电影', '电视剧', '音乐', 'movie', 'tv', or 'music'.",
|
||||
)
|
||||
category: Optional[str] = Field(
|
||||
None,
|
||||
description="Optional media category. Only valid when media_type is set.",
|
||||
)
|
||||
|
||||
|
||||
class AddRuleGroupTool(MoviePilotTool):
|
||||
name: str = "add_rule_group"
|
||||
tags: list[str] = [
|
||||
ToolTag.Write,
|
||||
ToolTag.FilterRule,
|
||||
ToolTag.Admin,
|
||||
]
|
||||
description: str = (
|
||||
"Add a new filter rule group to UserFilterRuleGroups. "
|
||||
"Rule groups are matched level by level from left to right and can be linked to search/subscription flows. "
|
||||
"Before calling this tool, first use query_builtin_filter_rules and query_custom_filter_rules to confirm valid rule IDs, "
|
||||
"and optionally use query_rule_groups to imitate existing rule_string patterns."
|
||||
)
|
||||
args_schema: Type[BaseModel] = AddRuleGroupInput
|
||||
require_admin: bool = True
|
||||
|
||||
def get_tool_message(self, **kwargs) -> Optional[str]:
|
||||
return f"新增规则组 {kwargs.get('name', '')}"
|
||||
|
||||
async def run(
|
||||
self,
|
||||
name: str,
|
||||
rule_string: str,
|
||||
media_type: Optional[str] = None,
|
||||
category: Optional[str] = None,
|
||||
**kwargs,
|
||||
) -> str:
|
||||
logger.info(f"执行工具: {self.name}, name={name}")
|
||||
|
||||
try:
|
||||
custom_rules = get_custom_rules()
|
||||
available_rule_ids = set(get_builtin_rules().keys()) | set(
|
||||
build_custom_rule_map(custom_rules).keys()
|
||||
)
|
||||
rule_groups = get_rule_groups()
|
||||
expected_definitions = [
|
||||
group.model_dump(exclude_none=True) for group in rule_groups
|
||||
]
|
||||
new_group, _ = normalize_rule_group(
|
||||
name=name,
|
||||
rule_string=rule_string,
|
||||
media_type=media_type,
|
||||
category=category,
|
||||
existing_groups=rule_groups,
|
||||
available_rule_ids=available_rule_ids,
|
||||
)
|
||||
|
||||
rule_groups.append(new_group)
|
||||
definitions = [
|
||||
group.model_dump(exclude_none=True) for group in rule_groups
|
||||
]
|
||||
async with self.data.async_rule_group_mutation_scope() as mutation:
|
||||
await mutation.apply(
|
||||
definitions,
|
||||
expected_rule_groups=expected_definitions,
|
||||
)
|
||||
await publish_rule_config_changed(
|
||||
SystemConfigKey.UserFilterRuleGroups,
|
||||
definitions,
|
||||
)
|
||||
usage = await collect_rule_group_usages(
|
||||
self.data.subscriptions,
|
||||
[new_group.name],
|
||||
)
|
||||
|
||||
return json.dumps(
|
||||
{
|
||||
"success": True,
|
||||
"message": f"已新增规则组 {new_group.name}",
|
||||
"rule_group": serialize_rule_group(
|
||||
new_group, usage.get(new_group.name)
|
||||
),
|
||||
"count": len(rule_groups),
|
||||
},
|
||||
ensure_ascii=False,
|
||||
indent=2,
|
||||
)
|
||||
except Exception as exc:
|
||||
logger.error(f"新增规则组失败: {exc}", exc_info=True)
|
||||
return json.dumps(
|
||||
{
|
||||
"success": False,
|
||||
"message": f"新增规则组失败: {exc}",
|
||||
},
|
||||
ensure_ascii=False,
|
||||
)
|
||||
@@ -1,348 +0,0 @@
|
||||
"""添加订阅工具"""
|
||||
|
||||
from typing import List, Optional, Type, TypedDict
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from app.agent.tools.base import MoviePilotTool
|
||||
from app.agent.tools.tags import ToolTag
|
||||
from app.chain.subscribe.facade import SubscribeChain
|
||||
from app.domain.media import normalize_music_type
|
||||
from app.runtime.log import logger
|
||||
from app.schemas.types import MUSIC_ENTITY_ALBUM, MediaSource, MediaType, NotificationChannel
|
||||
|
||||
|
||||
class _SubscribeOptions(TypedDict, total=False):
|
||||
"""声明 Agent 工具允许透传给订阅链的可选配置。"""
|
||||
|
||||
music_type: str
|
||||
start_episode: int
|
||||
total_episode: int
|
||||
quality: str
|
||||
resolution: str
|
||||
effect: str
|
||||
audio_quality: str
|
||||
audio_format: str
|
||||
min_bitrate: int
|
||||
min_bit_depth: int
|
||||
min_sample_rate: int
|
||||
best_version: int
|
||||
filter_groups: List[str]
|
||||
sites: List[int]
|
||||
|
||||
|
||||
class AddSubscribeInput(BaseModel):
|
||||
"""添加订阅工具的输入参数模型"""
|
||||
|
||||
title: str = Field(
|
||||
...,
|
||||
description="The title of the media to subscribe to (e.g., 'The Matrix', 'Breaking Bad')",
|
||||
)
|
||||
year: Optional[str] = Field(
|
||||
None,
|
||||
description="Release year. Recommended for video; optional when a stable music ID is provided",
|
||||
)
|
||||
media_type: str = Field(..., description="Allowed values: movie, tv, music")
|
||||
music_type: Optional[str] = Field(
|
||||
None,
|
||||
description="Required for music subscriptions: recording for one track or album for the complete album. Artists cannot be subscribed",
|
||||
)
|
||||
season: Optional[int] = Field(
|
||||
None,
|
||||
description=(
|
||||
"Season number for TV shows (optional). If omitted, the subscription defaults to season 1 only. "
|
||||
"To subscribe multiple seasons or the full series, call this tool separately for each season."
|
||||
),
|
||||
)
|
||||
media_source: Optional[MediaSource] = Field(
|
||||
None,
|
||||
description="Media metadata source returned by search_media",
|
||||
)
|
||||
media_id: Optional[str] = Field(None, description="Native ID for media_source")
|
||||
start_episode: Optional[int] = Field(
|
||||
None,
|
||||
description="Starting episode number for TV shows (optional, defaults to 1 if not specified)",
|
||||
)
|
||||
total_episode: Optional[int] = Field(
|
||||
None,
|
||||
description="Total number of episodes for TV shows (optional, will be auto-detected from TMDB if not specified)",
|
||||
)
|
||||
quality: Optional[str] = Field(
|
||||
None,
|
||||
description="Quality filter as regular expression (optional, e.g., 'BluRay|WEB-DL|HDTV')",
|
||||
)
|
||||
resolution: Optional[str] = Field(
|
||||
None,
|
||||
description="Resolution filter as regular expression (optional, e.g., '1080p|720p|2160p')",
|
||||
)
|
||||
effect: Optional[str] = Field(
|
||||
None,
|
||||
description="Effect filter as regular expression (optional, e.g., 'HDR|DV|SDR')",
|
||||
)
|
||||
audio_quality: Optional[str] = Field(
|
||||
None,
|
||||
description="Music quality tier filter: hires, lossless, lossy, or a regular-expression combination",
|
||||
)
|
||||
audio_format: Optional[str] = Field(
|
||||
None,
|
||||
description="Music audio-format filter as a regular expression, e.g. FLAC|ALAC|DSD",
|
||||
)
|
||||
min_bitrate: Optional[int] = Field(None, description="Minimum music bitrate in bits per second")
|
||||
min_bit_depth: Optional[int] = Field(None, description="Minimum music bit depth")
|
||||
min_sample_rate: Optional[int] = Field(None, description="Minimum music sample rate in Hz")
|
||||
best_version: Optional[int] = Field(
|
||||
None,
|
||||
description="Enable quality upgrades: 0 for no, 1 for yes. Music upgrades use normalized audio quality",
|
||||
)
|
||||
filter_groups: Optional[List[str]] = Field(
|
||||
None,
|
||||
description="List of filter rule group names to apply (optional, can be obtained from query_rule_groups tool)",
|
||||
)
|
||||
sites: Optional[List[int]] = Field(
|
||||
None,
|
||||
description="List of site IDs to search from (optional, can be obtained from query_sites tool)",
|
||||
)
|
||||
|
||||
|
||||
class AddSubscribeTool(MoviePilotTool):
|
||||
"""添加电影、电视剧、单曲或整张专辑订阅。"""
|
||||
|
||||
name: str = "add_subscribe"
|
||||
tags: list[str] = [
|
||||
ToolTag.Write,
|
||||
ToolTag.Subscription,
|
||||
ToolTag.Media,
|
||||
]
|
||||
description: str = (
|
||||
"Add automated subscriptions for movies, TV shows, one music recording, or one complete album. "
|
||||
"Music requires the source-native ID and music_type='recording' or 'album'; artists are browse-only. "
|
||||
"Album subscriptions only complete after a resource is confirmed to cover the album's expected track count. "
|
||||
"For TV shows, omitting `season` subscribes season 1 only by default; to subscribe multiple seasons or "
|
||||
"the full series, call this tool once per season. Supports advanced filtering options like quality, "
|
||||
"resolution, and effect filters using regular expressions."
|
||||
)
|
||||
args_schema: Type[BaseModel] = AddSubscribeInput
|
||||
|
||||
def get_tool_message(self, **kwargs) -> Optional[str]:
|
||||
"""根据订阅参数生成友好的提示消息"""
|
||||
title = kwargs.get("title", "")
|
||||
year = kwargs.get("year", "")
|
||||
media_type = kwargs.get("media_type", "")
|
||||
music_type = kwargs.get("music_type")
|
||||
season = kwargs.get("season")
|
||||
|
||||
message = f"添加订阅: {title}"
|
||||
if year:
|
||||
message += f" ({year})"
|
||||
if media_type:
|
||||
message += f" [{media_type}]"
|
||||
if music_type:
|
||||
message += f" [{music_type}]"
|
||||
if season is not None:
|
||||
message += f" 第{season}季"
|
||||
elif media_type == "tv":
|
||||
message += " 第1季(默认)"
|
||||
|
||||
return message
|
||||
|
||||
async def _resolve_subscribe_username(self) -> Optional[str]:
|
||||
"""优先映射为系统用户名,未绑定时回退当前渠道用户名。"""
|
||||
resolved_username = self._username
|
||||
if not self._channel or not self._user_id:
|
||||
return resolved_username
|
||||
|
||||
try:
|
||||
channel = NotificationChannel(self._channel)
|
||||
except ValueError:
|
||||
return resolved_username
|
||||
|
||||
binding_keys = {
|
||||
NotificationChannel.Telegram: ("telegram_userid",),
|
||||
NotificationChannel.Discord: ("discord_userid",),
|
||||
NotificationChannel.Wechat: ("wechat_userid",),
|
||||
NotificationChannel.Feishu: ("feishu_userid", "feishu_openid"),
|
||||
NotificationChannel.WechatClawBot: ("wechatclawbot_userid",),
|
||||
NotificationChannel.Slack: ("slack_userid",),
|
||||
NotificationChannel.VoceChat: ("vocechat_userid",),
|
||||
NotificationChannel.SynologyChat: ("synologychat_userid",),
|
||||
NotificationChannel.QQ: ("qq_userid", "qq_openid"),
|
||||
}.get(channel)
|
||||
if not binding_keys:
|
||||
return resolved_username
|
||||
|
||||
mapped_username = await self.run_blocking(
|
||||
"db",
|
||||
self.data.users.find_name_by_bindings,
|
||||
{key: self._user_id for key in binding_keys},
|
||||
)
|
||||
return mapped_username or resolved_username
|
||||
|
||||
async def run(
|
||||
self,
|
||||
title: str,
|
||||
media_type: str,
|
||||
year: Optional[str] = None,
|
||||
music_type: Optional[str] = None,
|
||||
season: Optional[int] = None,
|
||||
media_source: Optional[MediaSource] = None,
|
||||
media_id: Optional[str] = None,
|
||||
start_episode: Optional[int] = None,
|
||||
total_episode: Optional[int] = None,
|
||||
quality: Optional[str] = None,
|
||||
resolution: Optional[str] = None,
|
||||
effect: Optional[str] = None,
|
||||
audio_quality: Optional[str] = None,
|
||||
audio_format: Optional[str] = None,
|
||||
min_bitrate: Optional[int] = None,
|
||||
min_bit_depth: Optional[int] = None,
|
||||
min_sample_rate: Optional[int] = None,
|
||||
best_version: Optional[int] = None,
|
||||
filter_groups: Optional[List[str]] = None,
|
||||
sites: Optional[List[int]] = None,
|
||||
**kwargs,
|
||||
) -> str:
|
||||
"""校验实体语义后调用订阅链添加精确订阅。"""
|
||||
logger.info(
|
||||
f"执行工具: {self.name}, 参数: title={title}, year={year}, media_type={media_type}, "
|
||||
f"music_type={music_type}, season={season}, media_source={media_source}, "
|
||||
f"media_id={media_id}, "
|
||||
f"start_episode={start_episode}, "
|
||||
f"total_episode={total_episode}, quality={quality}, resolution={resolution}, "
|
||||
f"effect={effect}, filter_groups={filter_groups}, sites={sites}"
|
||||
)
|
||||
|
||||
try:
|
||||
subscribe_chain = SubscribeChain()
|
||||
media_type_enum = MediaType.from_agent(media_type)
|
||||
if not media_type_enum:
|
||||
return f"错误:无效的媒体类型 '{media_type}',支持的类型:'movie', 'tv', 'music'"
|
||||
|
||||
normalized_music_type = None
|
||||
if media_type_enum == MediaType.MUSIC:
|
||||
normalized_music_type = normalize_music_type(
|
||||
music_type,
|
||||
allow_artist=False,
|
||||
)
|
||||
if not normalized_music_type:
|
||||
return (
|
||||
"错误:音乐订阅必须提供 music_type='recording'(单曲)"
|
||||
"或 music_type='album'(整张专辑),艺术家不能订阅"
|
||||
)
|
||||
if not media_source or not media_id:
|
||||
return "错误:音乐订阅必须同时提供 search_media 返回的 media_source 和 media_id"
|
||||
if any(value is not None for value in (season, start_episode, total_episode)):
|
||||
return "错误:音乐订阅没有季集参数,不能传入 season、start_episode 或 total_episode"
|
||||
elif music_type:
|
||||
return "错误:music_type 仅能与 media_type='music' 一起使用"
|
||||
if (media_source is None) != (media_id is None):
|
||||
return "错误:media_source 和 media_id 必须同时提供"
|
||||
audio_filter_values = (
|
||||
audio_quality, audio_format, min_bitrate, min_bit_depth, min_sample_rate
|
||||
)
|
||||
if media_type_enum != MediaType.MUSIC and any(
|
||||
value is not None for value in audio_filter_values
|
||||
):
|
||||
return "错误:audio_quality、audio_format 和音频技术参数仅用于音乐订阅"
|
||||
effective_season = (
|
||||
season
|
||||
if season is not None
|
||||
else 1
|
||||
if media_type_enum == MediaType.TV
|
||||
else None
|
||||
)
|
||||
subscribe_username = await self._resolve_subscribe_username()
|
||||
|
||||
# 构建额外的订阅参数
|
||||
subscribe_kwargs: _SubscribeOptions = {}
|
||||
if normalized_music_type:
|
||||
subscribe_kwargs["music_type"] = normalized_music_type
|
||||
if start_episode is not None:
|
||||
subscribe_kwargs["start_episode"] = start_episode
|
||||
if total_episode is not None:
|
||||
subscribe_kwargs["total_episode"] = total_episode
|
||||
if quality:
|
||||
subscribe_kwargs["quality"] = quality
|
||||
if resolution:
|
||||
subscribe_kwargs["resolution"] = resolution
|
||||
if effect:
|
||||
subscribe_kwargs["effect"] = effect
|
||||
if audio_quality:
|
||||
subscribe_kwargs["audio_quality"] = audio_quality
|
||||
if audio_format:
|
||||
subscribe_kwargs["audio_format"] = audio_format
|
||||
if min_bitrate is not None:
|
||||
subscribe_kwargs["min_bitrate"] = min_bitrate
|
||||
if min_bit_depth is not None:
|
||||
subscribe_kwargs["min_bit_depth"] = min_bit_depth
|
||||
if min_sample_rate is not None:
|
||||
subscribe_kwargs["min_sample_rate"] = min_sample_rate
|
||||
if best_version is not None:
|
||||
subscribe_kwargs["best_version"] = best_version
|
||||
if filter_groups:
|
||||
subscribe_kwargs["filter_groups"] = filter_groups
|
||||
if sites:
|
||||
subscribe_kwargs["sites"] = sites
|
||||
|
||||
sid, message = await subscribe_chain.async_add(
|
||||
mtype=media_type_enum,
|
||||
title=title,
|
||||
year=year or "",
|
||||
media_source=media_source,
|
||||
media_id=media_id,
|
||||
season=season,
|
||||
username=subscribe_username,
|
||||
**subscribe_kwargs,
|
||||
)
|
||||
if sid:
|
||||
display_year = f" ({year})" if year else ""
|
||||
music_label = (
|
||||
"专辑" if normalized_music_type == MUSIC_ENTITY_ALBUM else "单曲"
|
||||
) if normalized_music_type else ""
|
||||
if message and "已存在" in message:
|
||||
result_msg = f"{music_label}订阅已存在:{title}{display_year}"
|
||||
if effective_season is not None:
|
||||
result_msg += f" 第{effective_season}季"
|
||||
result_msg += "。如需修改参数请先删除旧订阅。"
|
||||
return result_msg
|
||||
|
||||
result_msg = f"成功添加{music_label}订阅:{title}{display_year}"
|
||||
if effective_season is not None:
|
||||
result_msg += f" 第{effective_season}季"
|
||||
if season is None:
|
||||
result_msg += "(未指定季号,默认按第一季订阅)"
|
||||
if subscribe_kwargs:
|
||||
params = []
|
||||
if start_episode is not None:
|
||||
params.append(f"开始集数: {start_episode}")
|
||||
if total_episode is not None:
|
||||
params.append(f"总集数: {total_episode}")
|
||||
if quality:
|
||||
params.append(f"质量过滤: {quality}")
|
||||
if resolution:
|
||||
params.append(f"分辨率过滤: {resolution}")
|
||||
if effect:
|
||||
params.append(f"特效过滤: {effect}")
|
||||
if audio_quality:
|
||||
params.append(f"音质等级: {audio_quality}")
|
||||
if audio_format:
|
||||
params.append(f"音频格式: {audio_format}")
|
||||
if min_bitrate is not None:
|
||||
params.append(f"最低码率: {round(min_bitrate / 1000)}kbps")
|
||||
if min_bit_depth is not None:
|
||||
params.append(f"最低位深: {min_bit_depth}bit")
|
||||
if min_sample_rate is not None:
|
||||
params.append(f"最低采样率: {min_sample_rate / 1000:g}kHz")
|
||||
if best_version is not None:
|
||||
params.append(f"音质洗版: {'开启' if best_version else '关闭'}")
|
||||
if filter_groups:
|
||||
params.append(f"规则组: {', '.join(filter_groups)}")
|
||||
if sites:
|
||||
params.append(f"站点: {', '.join(map(str, sites))}")
|
||||
if params:
|
||||
result_msg += f"\n配置参数: {', '.join(params)}"
|
||||
return result_msg
|
||||
else:
|
||||
return f"添加订阅失败:{message}"
|
||||
except Exception as e:
|
||||
logger.error(f"添加订阅失败: {e}", exc_info=True)
|
||||
return f"添加订阅时发生错误: {str(e)}"
|
||||
440
app/agent/tools/impl/agent_task.py
Normal file
440
app/agent/tools/impl/agent_task.py
Normal file
@@ -0,0 +1,440 @@
|
||||
"""Agent 自主定时任务统一工具。"""
|
||||
|
||||
import json
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Literal, Optional, Type
|
||||
|
||||
import pytz
|
||||
from pydantic import BaseModel, Field, model_validator
|
||||
|
||||
from app.agent.tools.base import MoviePilotTool
|
||||
from app.agent.tools.tags import ToolTag
|
||||
from app.application.agenttask import agent_task_run_to_dict, agent_task_to_dict
|
||||
from app.runtime.scheduling import TimerUtils
|
||||
from app.runtime.settings import get_runtime_setting
|
||||
|
||||
AgentTaskAction = Literal["create", "list", "update", "run", "delete"]
|
||||
AgentTaskTriggerType = Literal["date", "cron"]
|
||||
|
||||
|
||||
class AgentTaskInput(BaseModel):
|
||||
"""统一管理 Agent 自主定时任务的输入参数。"""
|
||||
|
||||
action: AgentTaskAction = Field(
|
||||
...,
|
||||
description=(
|
||||
"Action to perform: create, list, update, run, or delete. "
|
||||
"Use list before changing a task when its integer task_id is unknown."
|
||||
),
|
||||
)
|
||||
task_id: Optional[int] = Field(
|
||||
None,
|
||||
ge=1,
|
||||
description="Task ID for list, update, run, or delete.",
|
||||
)
|
||||
name: Optional[str] = Field(
|
||||
None,
|
||||
min_length=1,
|
||||
max_length=100,
|
||||
description="Task name for create or update.",
|
||||
)
|
||||
content: Optional[str] = Field(
|
||||
None,
|
||||
min_length=1,
|
||||
max_length=10000,
|
||||
description="Complete instructions for create or update.",
|
||||
)
|
||||
trigger_type: Optional[AgentTaskTriggerType] = Field(
|
||||
None,
|
||||
description="Use date for one future run or cron for recurring work.",
|
||||
)
|
||||
trigger: Optional[str] = Field(
|
||||
None,
|
||||
min_length=1,
|
||||
max_length=200,
|
||||
description="ISO 8601 date or standard five-field cron expression.",
|
||||
)
|
||||
delay_minutes: Optional[int] = Field(
|
||||
None,
|
||||
ge=1,
|
||||
le=525600,
|
||||
description=("Relative delay for a one-time date task. Use instead of trigger with trigger_type=date."),
|
||||
)
|
||||
enabled: Optional[bool] = Field(
|
||||
None,
|
||||
description=("For list, optionally filter by enabled state. For update, set false to pause or true to resume."),
|
||||
)
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_action(self) -> "AgentTaskInput":
|
||||
"""按动作校验必填字段和触发参数组合。"""
|
||||
if self.name is not None:
|
||||
self.name = self.name.strip()
|
||||
if not self.name:
|
||||
raise ValueError("name 不能只包含空白字符")
|
||||
if self.content is not None:
|
||||
self.content = self.content.strip()
|
||||
if not self.content:
|
||||
raise ValueError("content 不能只包含空白字符")
|
||||
|
||||
if self.action == "create":
|
||||
if self.name is None or self.content is None or self.trigger_type is None:
|
||||
raise ValueError("create 必须提供 name、content 和 trigger_type")
|
||||
self._validate_schedule(require_schedule=True, normalize_exact=True)
|
||||
elif self.action == "update":
|
||||
if self.task_id is None:
|
||||
raise ValueError("update 必须提供 task_id")
|
||||
has_schedule_update = any(
|
||||
value is not None for value in (self.trigger_type, self.trigger, self.delay_minutes)
|
||||
)
|
||||
if has_schedule_update:
|
||||
self._validate_schedule(require_schedule=True, normalize_exact=False)
|
||||
if all(
|
||||
value is None
|
||||
for value in (
|
||||
self.name,
|
||||
self.content,
|
||||
self.trigger_type,
|
||||
self.enabled,
|
||||
)
|
||||
):
|
||||
raise ValueError("update 至少需要提供一个要更新的字段")
|
||||
elif self.action in {"run", "delete"} and self.task_id is None:
|
||||
raise ValueError(f"{self.action} 必须提供 task_id")
|
||||
return self
|
||||
|
||||
def _validate_schedule(
|
||||
self,
|
||||
*,
|
||||
require_schedule: bool,
|
||||
normalize_exact: bool,
|
||||
) -> None:
|
||||
"""校验 date/cron 触发组合,并按需规范化绝对触发值。"""
|
||||
if require_schedule and self.trigger_type is None:
|
||||
raise ValueError("修改触发配置时必须提供 trigger_type")
|
||||
if self.trigger_type == "date":
|
||||
if self.delay_minutes is not None:
|
||||
self.trigger = None
|
||||
return
|
||||
if self.trigger is None:
|
||||
raise ValueError("date 任务必须提供 trigger 或 delay_minutes")
|
||||
elif self.trigger_type == "cron":
|
||||
if self.trigger is None or self.delay_minutes is not None:
|
||||
raise ValueError("cron 任务必须提供 trigger,且不能提供 delay_minutes")
|
||||
if normalize_exact and self.trigger_type is not None:
|
||||
self.trigger_type, self.trigger = TimerUtils.normalize_schedule_trigger(
|
||||
trigger_type=self.trigger_type,
|
||||
trigger_value=self.trigger,
|
||||
timezone_name=get_runtime_setting("TZ"),
|
||||
require_future=True,
|
||||
)
|
||||
|
||||
|
||||
class AgentTaskTool(MoviePilotTool):
|
||||
"""通过一个动作式接口管理当前用户的自主定时任务。"""
|
||||
|
||||
name: str = "agent_task"
|
||||
tags: list[str] = [
|
||||
ToolTag.Read,
|
||||
ToolTag.Write,
|
||||
ToolTag.AgentTask,
|
||||
ToolTag.Admin,
|
||||
]
|
||||
description: str = (
|
||||
"Manage persistent autonomous agent tasks with one structured action. Use create "
|
||||
"for explicitly requested delayed or recurring work, list to inspect current-user "
|
||||
"tasks, update to change or pause one, run to queue one immediately, and delete "
|
||||
"to permanently remove it. Task IDs are integers and are not scheduler job IDs."
|
||||
)
|
||||
args_schema: Type[BaseModel] = AgentTaskInput
|
||||
require_admin: bool = True
|
||||
|
||||
def get_tool_message(self, **kwargs: object) -> Optional[str]:
|
||||
"""生成统一任务操作的用户可见提示。"""
|
||||
action = str(kwargs.get("action") or "list")
|
||||
action_name = {
|
||||
"create": "创建",
|
||||
"list": "查询",
|
||||
"update": "更新",
|
||||
"run": "立即执行",
|
||||
"delete": "删除",
|
||||
}.get(action, action)
|
||||
target = kwargs.get("task_id") or kwargs.get("name") or ""
|
||||
return f"{action_name}自主定时任务:{target}".rstrip(":")
|
||||
|
||||
@staticmethod
|
||||
def _absolute_trigger(payload: AgentTaskInput) -> str:
|
||||
"""将相对分钟或绝对表达式转换为规范化触发值。"""
|
||||
trigger_value = payload.trigger
|
||||
if payload.trigger_type == "date" and payload.delay_minutes is not None:
|
||||
timezone = pytz.timezone(get_runtime_setting("TZ"))
|
||||
trigger_value = (datetime.now(timezone) + timedelta(minutes=payload.delay_minutes)).isoformat(
|
||||
timespec="seconds"
|
||||
)
|
||||
if payload.trigger_type is None:
|
||||
raise ValueError("Agent 定时任务缺少 trigger_type")
|
||||
_, normalized = TimerUtils.normalize_schedule_trigger(
|
||||
trigger_type=payload.trigger_type,
|
||||
trigger_value=trigger_value,
|
||||
timezone_name=get_runtime_setting("TZ"),
|
||||
require_future=True,
|
||||
)
|
||||
return normalized
|
||||
|
||||
def _create_task(self, payload: AgentTaskInput) -> dict[str, object]:
|
||||
"""持久化任务并立即注册到运行时调度器。"""
|
||||
from app.application.scheduling import update_agent_task_job
|
||||
|
||||
trigger_value = self._absolute_trigger(payload)
|
||||
if payload.name is None or payload.content is None or payload.trigger_type is None:
|
||||
raise ValueError("create 缺少必要参数")
|
||||
chat = self.data.chat.get_sync(
|
||||
session_id=self._session_id,
|
||||
user_id=self._user_id,
|
||||
)
|
||||
task = self.data.tasks.add(
|
||||
name=payload.name,
|
||||
content=payload.content,
|
||||
trigger_type=payload.trigger_type,
|
||||
cron_expression=(trigger_value if payload.trigger_type == "cron" else None),
|
||||
run_at=trigger_value if payload.trigger_type == "date" else None,
|
||||
user_id=str(self._user_id),
|
||||
username=self._username or (chat.username if chat else None),
|
||||
session_id=str(self._session_id),
|
||||
channel=self._channel or (chat.channel if chat else None),
|
||||
source=self._source or (chat.source if chat else None),
|
||||
original_chat_id=chat.original_chat_id if chat else None,
|
||||
)
|
||||
if task is None:
|
||||
raise RuntimeError("Agent 定时任务创建后无法读取")
|
||||
return agent_task_to_dict(
|
||||
task,
|
||||
next_run_at=update_agent_task_job(task.id),
|
||||
timezone=get_runtime_setting("TZ"),
|
||||
)
|
||||
|
||||
def _list_tasks(
|
||||
self,
|
||||
task_id: Optional[int],
|
||||
enabled: Optional[bool],
|
||||
) -> list[dict[str, object]]:
|
||||
"""读取当前用户任务及运行时下一次触发时间。"""
|
||||
from app.application.scheduling import get_agent_task_next_run
|
||||
|
||||
oper = self.data.tasks
|
||||
if task_id is not None:
|
||||
task = oper.get(task_id=task_id, user_id=str(self._user_id))
|
||||
tasks = [task] if task else []
|
||||
else:
|
||||
tasks = oper.list(user_id=str(self._user_id), enabled=enabled)
|
||||
result: list[dict[str, object]] = []
|
||||
for task in tasks:
|
||||
data = agent_task_to_dict(
|
||||
task,
|
||||
next_run_at=get_agent_task_next_run(task.id),
|
||||
timezone=get_runtime_setting("TZ"),
|
||||
)
|
||||
if task_id is not None:
|
||||
data["recent_runs"] = [
|
||||
agent_task_run_to_dict(run)
|
||||
for run in oper.list_runs(
|
||||
task_id=task.id,
|
||||
user_id=str(self._user_id),
|
||||
limit=10,
|
||||
)
|
||||
]
|
||||
result.append(data)
|
||||
return result
|
||||
|
||||
def _update_task(
|
||||
self,
|
||||
payload: AgentTaskInput,
|
||||
) -> Optional[dict[str, object]]:
|
||||
"""更新当前用户任务并刷新运行时调度。"""
|
||||
from app.application.scheduling import update_agent_task_job
|
||||
|
||||
if payload.task_id is None:
|
||||
raise ValueError("update 缺少 task_id")
|
||||
oper = self.data.tasks
|
||||
task = oper.get(task_id=payload.task_id, user_id=str(self._user_id))
|
||||
if not task:
|
||||
return None
|
||||
if task.last_status == "running":
|
||||
return {"error": f"Agent 定时任务 {payload.task_id} 正在执行,请稍后再修改"}
|
||||
|
||||
has_schedule_update = payload.trigger_type is not None
|
||||
trigger_type = payload.trigger_type or task.trigger_type
|
||||
trigger_value = payload.trigger
|
||||
if trigger_type == "date" and payload.delay_minutes is not None:
|
||||
timezone = pytz.timezone(get_runtime_setting("TZ"))
|
||||
trigger_value = (datetime.now(timezone) + timedelta(minutes=payload.delay_minutes)).isoformat(
|
||||
timespec="seconds"
|
||||
)
|
||||
if trigger_value is None:
|
||||
trigger_value = task.cron_expression if trigger_type == "cron" else task.run_at
|
||||
normalized_type = trigger_type
|
||||
normalized_trigger = trigger_value
|
||||
validates_existing_date_schedule = bool(
|
||||
payload.enabled and task.last_status != "interrupted" and trigger_type == "date"
|
||||
)
|
||||
if has_schedule_update or validates_existing_date_schedule:
|
||||
if trigger_value is None:
|
||||
raise ValueError("Agent 定时任务缺少触发配置")
|
||||
normalized_type, normalized_trigger = TimerUtils.normalize_schedule_trigger(
|
||||
trigger_type=trigger_type,
|
||||
trigger_value=trigger_value,
|
||||
timezone_name=get_runtime_setting("TZ"),
|
||||
require_future=bool(
|
||||
trigger_type == "date"
|
||||
and (
|
||||
task.last_status == "interrupted"
|
||||
or (task.enabled if payload.enabled is None else payload.enabled)
|
||||
)
|
||||
),
|
||||
)
|
||||
|
||||
update_payload: dict[str, object] = {}
|
||||
if payload.name is not None:
|
||||
update_payload["name"] = payload.name
|
||||
if payload.content is not None:
|
||||
update_payload["content"] = payload.content
|
||||
if has_schedule_update:
|
||||
update_payload.update(
|
||||
{
|
||||
"trigger_type": normalized_type,
|
||||
"cron_expression": (normalized_trigger if normalized_type == "cron" else None),
|
||||
"run_at": (normalized_trigger if normalized_type == "date" else None),
|
||||
"last_status": "waiting",
|
||||
"last_result": None,
|
||||
}
|
||||
)
|
||||
if payload.enabled is not None:
|
||||
update_payload["enabled"] = payload.enabled
|
||||
if payload.enabled and task.last_status != "interrupted":
|
||||
update_payload["last_status"] = "waiting"
|
||||
|
||||
updated = oper.update(
|
||||
task_id=payload.task_id,
|
||||
payload=update_payload,
|
||||
user_id=str(self._user_id),
|
||||
)
|
||||
if not updated:
|
||||
current = oper.get(task_id=payload.task_id, user_id=str(self._user_id))
|
||||
if current and current.last_status == "running":
|
||||
return {"error": (f"Agent 定时任务 {payload.task_id} 正在执行,请稍后再修改")}
|
||||
return None
|
||||
updated_task = oper.get(
|
||||
task_id=payload.task_id,
|
||||
user_id=str(self._user_id),
|
||||
)
|
||||
if updated_task is None:
|
||||
return None
|
||||
return agent_task_to_dict(
|
||||
updated_task,
|
||||
next_run_at=update_agent_task_job(payload.task_id),
|
||||
timezone=get_runtime_setting("TZ"),
|
||||
)
|
||||
|
||||
def _get_task_state(self, task_id: int) -> tuple[str, Optional[str]]:
|
||||
"""校验任务归属和状态,返回可执行性及任务名称。"""
|
||||
task = self.data.tasks.get(task_id=task_id, user_id=str(self._user_id))
|
||||
if not task:
|
||||
return "not_found", None
|
||||
if not task.enabled:
|
||||
return "disabled", task.name
|
||||
if task.last_status == "running":
|
||||
return "running", task.name
|
||||
return "ready", task.name
|
||||
|
||||
def _delete_task(self, task_id: int) -> bool:
|
||||
"""删除当前用户任务并移除运行时调度。"""
|
||||
from app.application.scheduling import remove_agent_task_job
|
||||
|
||||
deleted = self.data.tasks.delete(
|
||||
task_id=task_id,
|
||||
user_id=str(self._user_id),
|
||||
)
|
||||
if deleted:
|
||||
remove_agent_task_job(task_id)
|
||||
return deleted
|
||||
|
||||
async def run(
|
||||
self,
|
||||
action: AgentTaskAction,
|
||||
task_id: Optional[int] = None,
|
||||
name: Optional[str] = None,
|
||||
content: Optional[str] = None,
|
||||
trigger_type: Optional[AgentTaskTriggerType] = None,
|
||||
trigger: Optional[str] = None,
|
||||
delay_minutes: Optional[int] = None,
|
||||
enabled: Optional[bool] = None,
|
||||
**kwargs: object,
|
||||
) -> str:
|
||||
"""执行一项任务创建、查询、更新、立即运行或删除操作。"""
|
||||
payload = AgentTaskInput(
|
||||
action=action,
|
||||
task_id=task_id,
|
||||
name=name,
|
||||
content=content,
|
||||
trigger_type=trigger_type,
|
||||
trigger=trigger,
|
||||
delay_minutes=delay_minutes,
|
||||
enabled=enabled,
|
||||
)
|
||||
if payload.action == "create":
|
||||
if not get_runtime_setting("AI_AGENT_ENABLE"):
|
||||
return "AI Agent 未启用,无法创建自主定时任务"
|
||||
task = await self.run_blocking("db", self._create_task, payload)
|
||||
return json.dumps(task, ensure_ascii=False, indent=2)
|
||||
if payload.action == "list":
|
||||
tasks = await self.run_blocking(
|
||||
"db",
|
||||
self._list_tasks,
|
||||
payload.task_id,
|
||||
payload.enabled,
|
||||
)
|
||||
return json.dumps(
|
||||
{"total": len(tasks), "tasks": tasks},
|
||||
ensure_ascii=False,
|
||||
indent=2,
|
||||
)
|
||||
if payload.action == "update":
|
||||
task = await self.run_blocking("db", self._update_task, payload)
|
||||
if not task:
|
||||
return f"Agent 定时任务 {payload.task_id} 不存在或不属于当前用户"
|
||||
if error := task.get("error"):
|
||||
return str(error)
|
||||
return json.dumps(task, ensure_ascii=False, indent=2)
|
||||
if payload.action == "run":
|
||||
return await self._run_now(payload.task_id)
|
||||
return await self._delete(payload.task_id)
|
||||
|
||||
async def _run_now(self, task_id: Optional[int]) -> str:
|
||||
"""立即提交一项已启用且属于当前用户的任务。"""
|
||||
from app.application.scheduling import start_agent_task
|
||||
|
||||
if task_id is None:
|
||||
raise ValueError("run 缺少 task_id")
|
||||
status, task_name = await self.run_blocking(
|
||||
"db",
|
||||
self._get_task_state,
|
||||
task_id,
|
||||
)
|
||||
if status == "not_found":
|
||||
return f"Agent 定时任务 {task_id} 不存在或不属于当前用户"
|
||||
if status == "disabled":
|
||||
return f"Agent 定时任务 {task_id} 已暂停,请先恢复后再执行"
|
||||
if status == "running":
|
||||
return f"Agent 定时任务 {task_id} 正在执行,请勿重复触发"
|
||||
if not start_agent_task(task_id):
|
||||
return f"Agent 定时任务 {task_id} 尚未注册到运行时调度器,无法立即执行"
|
||||
return f"Agent 定时任务 {task_id} 已提交立即执行:{task_name}。执行完成后将通过已配置的通知渠道广播结果"
|
||||
|
||||
async def _delete(self, task_id: Optional[int]) -> str:
|
||||
"""永久删除一项属于当前用户的自主定时任务。"""
|
||||
if task_id is None:
|
||||
raise ValueError("delete 缺少 task_id")
|
||||
deleted = await self.run_blocking("db", self._delete_task, task_id)
|
||||
if not deleted:
|
||||
return f"Agent 定时任务 {task_id} 不存在或不属于当前用户"
|
||||
return f"Agent 定时任务 {task_id} 已删除"
|
||||
199
app/agent/tools/impl/api.py
Normal file
199
app/agent/tools/impl/api.py
Normal file
@@ -0,0 +1,199 @@
|
||||
"""MoviePilot 结构化 API 网关工具。"""
|
||||
|
||||
import json
|
||||
from typing import Any, Dict, Optional, Type
|
||||
|
||||
from pydantic import BaseModel, Field, PrivateAttr
|
||||
|
||||
from app.agent.api.executor import ApiExecutionContext, ApiExecutionError, MoviePilotApiExecutor
|
||||
from app.agent.policy.api import resolve_api_operation
|
||||
from app.agent.tools.base import MoviePilotTool
|
||||
from app.agent.tools.tags import ToolTag
|
||||
from app.schemas.types import NotificationChannel
|
||||
|
||||
|
||||
class MoviePilotApiInput(BaseModel):
|
||||
"""MoviePilot API 网关的结构化输入参数。"""
|
||||
|
||||
operation_id: str = Field(
|
||||
...,
|
||||
description=(
|
||||
"稳定的 MoviePilot API operation ID。先根据领域 Skill 选择操作,不要传入 URL、认证头或 API Token。"
|
||||
),
|
||||
)
|
||||
path_params: Dict[str, Any] = Field(
|
||||
default_factory=dict,
|
||||
description="路径参数;仅填当前 operation 声明的参数。",
|
||||
)
|
||||
query: Dict[str, Any] = Field(
|
||||
default_factory=dict,
|
||||
description="查询参数;仅填当前 operation 声明的参数。",
|
||||
)
|
||||
body: Dict[str, Any] = Field(
|
||||
default_factory=dict,
|
||||
description="JSON 请求体;字段由当前 operation 的 Skill 合同定义。",
|
||||
)
|
||||
|
||||
|
||||
class MoviePilotApiTool(MoviePilotTool):
|
||||
"""
|
||||
MoviePilot 结构化 API 网关。
|
||||
|
||||
网关只接受固定 operation ID 和结构化参数,由宿主注册表解析为固定 API
|
||||
方法与路径;模型不能提供 URL、认证头、令牌或任意 HTTP 方法。
|
||||
"""
|
||||
|
||||
name: str = "moviepilot_api"
|
||||
tags: list[str] = [
|
||||
ToolTag.Read,
|
||||
ToolTag.Media,
|
||||
ToolTag.Subscription,
|
||||
ToolTag.Download,
|
||||
ToolTag.Site,
|
||||
ToolTag.Plugin,
|
||||
]
|
||||
description: str = (
|
||||
"调用经过白名单审核的 MoviePilot 业务 API。使用领域 Skill 获取 operation_id、"
|
||||
"参数和失败处理;不能调用任意 URL、命令或认证接口。"
|
||||
)
|
||||
require_admin: bool = False
|
||||
args_schema: Type[BaseModel] = MoviePilotApiInput
|
||||
|
||||
_executor: Optional[MoviePilotApiExecutor] = PrivateAttr(default=None)
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
session_id: str,
|
||||
user_id: str,
|
||||
*,
|
||||
executor: Optional[MoviePilotApiExecutor] = None,
|
||||
**kwargs: Any,
|
||||
) -> None:
|
||||
"""注入可测试的固定 API 执行器。"""
|
||||
super().__init__(session_id=session_id, user_id=user_id, **kwargs)
|
||||
self._executor = executor
|
||||
|
||||
def get_tool_message(self, **kwargs) -> Optional[str]:
|
||||
"""生成结构化 API 调用提示。"""
|
||||
operation_id = kwargs.get("operation_id") or "未知操作"
|
||||
return f"调用 MoviePilot API:{operation_id}"
|
||||
|
||||
async def _resolve_api_identity(self) -> tuple[str, Optional[str], bool]:
|
||||
"""把 Web 或渠道身份解析为真实 MoviePilot 用户身份。"""
|
||||
raw_user_id = str(self._user_id or "")
|
||||
if self._source == "api" and bool(self._agent_context.get("is_admin")):
|
||||
from app.application.security.auth import build_superuser_token_payload
|
||||
|
||||
payload = await self.run_blocking(
|
||||
"db",
|
||||
build_superuser_token_payload,
|
||||
)
|
||||
if payload.sub is None:
|
||||
raise ApiExecutionError("管理员集成身份没有持久化用户 ID")
|
||||
return str(payload.sub), payload.username, bool(payload.super_user)
|
||||
direct_user_channels = {
|
||||
NotificationChannel.Web.value,
|
||||
NotificationChannel.WebAgent.value,
|
||||
}
|
||||
is_direct_user_channel = self._channel in direct_user_channels
|
||||
if self._data is None:
|
||||
if is_direct_user_channel and raw_user_id.isdigit():
|
||||
return raw_user_id, self._username, bool(self._agent_context.get("is_admin"))
|
||||
raise ApiExecutionError("Agent 数据上下文未装配,无法解析 API 用户身份")
|
||||
|
||||
username = self._username
|
||||
user = await self._data.users.async_get_by_name(username) if username else None
|
||||
if user is None and not is_direct_user_channel and self._channel and raw_user_id:
|
||||
try:
|
||||
channel = NotificationChannel(self._channel)
|
||||
except ValueError:
|
||||
channel = None
|
||||
binding_keys = {
|
||||
NotificationChannel.Telegram: ("telegram_userid",),
|
||||
NotificationChannel.Discord: ("discord_userid",),
|
||||
NotificationChannel.Wechat: ("wechat_userid",),
|
||||
NotificationChannel.Feishu: ("feishu_userid", "feishu_openid"),
|
||||
NotificationChannel.WechatClawBot: ("wechatclawbot_userid",),
|
||||
NotificationChannel.Slack: ("slack_userid",),
|
||||
NotificationChannel.VoceChat: ("vocechat_userid",),
|
||||
NotificationChannel.SynologyChat: ("synologychat_userid",),
|
||||
NotificationChannel.QQ: ("qq_userid", "qq_openid"),
|
||||
}.get(channel)
|
||||
if binding_keys:
|
||||
username = await self.run_blocking(
|
||||
"db",
|
||||
self._data.users.find_name_by_bindings,
|
||||
{key: raw_user_id for key in binding_keys},
|
||||
)
|
||||
user = await self._data.users.async_get_by_name(username) if username else None
|
||||
if user is None and is_direct_user_channel and raw_user_id.isdigit():
|
||||
return raw_user_id, self._username, bool(self._agent_context.get("is_admin"))
|
||||
if user is None or not user.is_active:
|
||||
raise ApiExecutionError("当前 Agent 身份未绑定有效的 MoviePilot 用户")
|
||||
return str(user.id), user.name, bool(user.is_superuser)
|
||||
|
||||
async def _get_executor(self) -> MoviePilotApiExecutor:
|
||||
"""返回注入执行器,未注入时按当前可信 Agent 身份创建。"""
|
||||
if self._executor is None:
|
||||
user_id, username, is_admin = await self._resolve_api_identity()
|
||||
self._executor = MoviePilotApiExecutor(
|
||||
context=ApiExecutionContext(
|
||||
user_id=user_id,
|
||||
username=username,
|
||||
is_admin=is_admin,
|
||||
session_id=self._session_id,
|
||||
channel=self._channel,
|
||||
source=self._source,
|
||||
)
|
||||
)
|
||||
return self._executor
|
||||
|
||||
async def run(
|
||||
self,
|
||||
operation_id: str,
|
||||
path_params: Optional[Dict[str, Any]] = None,
|
||||
query: Optional[Dict[str, Any]] = None,
|
||||
body: Optional[Dict[str, Any]] = None,
|
||||
**kwargs: Any,
|
||||
) -> str:
|
||||
"""
|
||||
执行一个白名单 MoviePilot API 操作。
|
||||
|
||||
:param operation_id: 稳定 API 操作标识
|
||||
:param path_params: 路径参数
|
||||
:param query: 查询参数
|
||||
:param body: JSON 请求体
|
||||
:return: 结构化业务结果或安全错误消息
|
||||
"""
|
||||
del kwargs
|
||||
spec = resolve_api_operation(operation_id)
|
||||
if spec is None:
|
||||
return json.dumps(
|
||||
{
|
||||
"success": False,
|
||||
"error": "unknown_operation",
|
||||
"message": f"未允许的 MoviePilot API 操作:{operation_id}",
|
||||
},
|
||||
ensure_ascii=False,
|
||||
)
|
||||
|
||||
try:
|
||||
executor = await self._get_executor()
|
||||
return await executor.execute(
|
||||
operation_id,
|
||||
path_params=path_params,
|
||||
query=query,
|
||||
body=body,
|
||||
)
|
||||
except ApiExecutionError as error:
|
||||
return json.dumps(
|
||||
{
|
||||
"success": False,
|
||||
"error": "operation_unavailable",
|
||||
"message": str(error),
|
||||
},
|
||||
ensure_ascii=False,
|
||||
)
|
||||
|
||||
|
||||
__all__ = ["MoviePilotApiInput", "MoviePilotApiTool"]
|
||||
@@ -1,161 +0,0 @@
|
||||
import json
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Literal, Optional, Type
|
||||
|
||||
import pytz
|
||||
from pydantic import BaseModel, Field, model_validator
|
||||
|
||||
from app.agent.tools.base import MoviePilotTool
|
||||
from app.agent.tools.tags import ToolTag
|
||||
from app.application.agenttask import agent_task_to_dict
|
||||
from app.runtime.scheduling import TimerUtils
|
||||
from app.runtime.settings import get_runtime_setting
|
||||
|
||||
|
||||
class CreateAgentTaskInput(BaseModel):
|
||||
"""创建 Agent 自主定时任务的输入参数。"""
|
||||
|
||||
name: str = Field(
|
||||
...,
|
||||
min_length=1,
|
||||
max_length=100,
|
||||
description="Short task name shown in task management and execution reports.",
|
||||
)
|
||||
content: str = Field(
|
||||
...,
|
||||
min_length=1,
|
||||
max_length=10000,
|
||||
description="Complete instructions that the agent must execute when the task fires.",
|
||||
)
|
||||
trigger_type: Literal["date", "cron"] = Field(
|
||||
...,
|
||||
description="Use 'date' for one exact future run or 'cron' for recurring work.",
|
||||
)
|
||||
trigger: Optional[str] = Field(
|
||||
None,
|
||||
min_length=1,
|
||||
max_length=200,
|
||||
description=(
|
||||
"For date, an ISO 8601 local or timezone-aware time such as "
|
||||
"2026-07-19 20:30:00; for cron, a standard five-field expression "
|
||||
"(minute hour day month weekday). The MoviePilot system timezone is used."
|
||||
),
|
||||
)
|
||||
delay_minutes: Optional[int] = Field(
|
||||
None,
|
||||
ge=1,
|
||||
le=525600,
|
||||
description=(
|
||||
"For a one-time date task expressed as 'in N minutes', provide this instead "
|
||||
"of trigger. MoviePilot calculates and persists the exact future run time."
|
||||
),
|
||||
)
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_trigger(self) -> "CreateAgentTaskInput":
|
||||
"""校验任务触发配置并统一格式。"""
|
||||
self.name = self.name.strip()
|
||||
self.content = self.content.strip()
|
||||
if not self.name or not self.content:
|
||||
raise ValueError("name 和 content 不能只包含空白字符")
|
||||
if self.trigger_type == "date":
|
||||
if self.delay_minutes is not None:
|
||||
# LangChain 会在 run() 前后各校验一次,延迟时间在持久化前统一计算。
|
||||
self.trigger = None
|
||||
return self
|
||||
if self.trigger is None:
|
||||
raise ValueError("date 任务必须提供 trigger 或 delay_minutes")
|
||||
elif self.trigger is None or self.delay_minutes is not None:
|
||||
raise ValueError("cron 任务必须提供 trigger,且不能提供 delay_minutes")
|
||||
self.trigger_type, self.trigger = TimerUtils.normalize_schedule_trigger(
|
||||
trigger_type=self.trigger_type,
|
||||
trigger_value=self.trigger,
|
||||
timezone_name=get_runtime_setting('TZ'),
|
||||
require_future=True,
|
||||
)
|
||||
return self
|
||||
|
||||
|
||||
class CreateAgentTaskTool(MoviePilotTool):
|
||||
"""创建可精确唤醒当前 Agent 会话的自主定时任务。"""
|
||||
|
||||
name: str = "create_agent_task"
|
||||
tags: list[str] = [ToolTag.Write, ToolTag.AgentTask, ToolTag.Admin]
|
||||
description: str = (
|
||||
"Create a persistent autonomous agent task only when the user explicitly asks "
|
||||
"for delayed, scheduled, recurring, reminder, or monitoring work. Use trigger_type "
|
||||
"'date' with delay_minutes for requests such as 'check in 30 minutes', an exact "
|
||||
"trigger time for other one-time work, and 'cron' for recurring schedules. When "
|
||||
"fired, MoviePilot wakes the agent in this conversation, executes content, and "
|
||||
"broadcasts user-facing messages through the configured notification channels."
|
||||
)
|
||||
args_schema: Type[BaseModel] = CreateAgentTaskInput
|
||||
require_admin: bool = True
|
||||
|
||||
def get_tool_message(self, **kwargs: object) -> Optional[str]:
|
||||
"""生成创建定时任务的提示消息。"""
|
||||
return f"创建自主定时任务:{kwargs.get('name', '')}"
|
||||
|
||||
def _create_task(self, payload: CreateAgentTaskInput) -> dict:
|
||||
"""持久化任务并立即注册到运行时调度器。"""
|
||||
from app.application.scheduling import update_agent_task_job
|
||||
|
||||
trigger_value = payload.trigger
|
||||
if payload.trigger_type == "date" and payload.delay_minutes is not None:
|
||||
timezone = pytz.timezone(get_runtime_setting('TZ'))
|
||||
trigger_value = (
|
||||
datetime.now(timezone) + timedelta(minutes=payload.delay_minutes)
|
||||
).isoformat(timespec="seconds")
|
||||
_, trigger_value = TimerUtils.normalize_schedule_trigger(
|
||||
trigger_type=payload.trigger_type,
|
||||
trigger_value=trigger_value,
|
||||
timezone_name=get_runtime_setting('TZ'),
|
||||
require_future=True,
|
||||
)
|
||||
chat = self.data.chat.get_sync(
|
||||
session_id=self._session_id,
|
||||
user_id=self._user_id,
|
||||
)
|
||||
task = self.data.tasks.add(
|
||||
name=payload.name.strip(),
|
||||
content=payload.content.strip(),
|
||||
trigger_type=payload.trigger_type,
|
||||
cron_expression=trigger_value if payload.trigger_type == "cron" else None,
|
||||
run_at=trigger_value if payload.trigger_type == "date" else None,
|
||||
user_id=str(self._user_id),
|
||||
username=self._username or (chat.username if chat else None),
|
||||
session_id=str(self._session_id),
|
||||
channel=self._channel or (chat.channel if chat else None),
|
||||
source=self._source or (chat.source if chat else None),
|
||||
original_chat_id=chat.original_chat_id if chat else None,
|
||||
)
|
||||
if task is None:
|
||||
raise RuntimeError("Agent 定时任务创建后无法读取")
|
||||
next_run_at = update_agent_task_job(task.id)
|
||||
return agent_task_to_dict(
|
||||
task,
|
||||
next_run_at=next_run_at,
|
||||
timezone=get_runtime_setting('TZ'),
|
||||
)
|
||||
|
||||
async def run(
|
||||
self,
|
||||
name: str,
|
||||
content: str,
|
||||
trigger_type: str,
|
||||
trigger: Optional[str] = None,
|
||||
delay_minutes: Optional[int] = None,
|
||||
**kwargs: object,
|
||||
) -> str:
|
||||
"""创建 Agent 自主定时任务。"""
|
||||
if not get_runtime_setting('AI_AGENT_ENABLE'):
|
||||
return "AI Agent 未启用,无法创建自主定时任务"
|
||||
payload = CreateAgentTaskInput(
|
||||
name=name,
|
||||
content=content,
|
||||
trigger_type=trigger_type,
|
||||
trigger=trigger,
|
||||
delay_minutes=delay_minutes,
|
||||
)
|
||||
task = await self.run_blocking("db", self._create_task, payload)
|
||||
return json.dumps(task, ensure_ascii=False, indent=2)
|
||||
@@ -1,49 +0,0 @@
|
||||
from typing import Optional, Type
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from app.agent.tools.base import MoviePilotTool
|
||||
from app.agent.tools.tags import ToolTag
|
||||
|
||||
|
||||
class DeleteAgentTaskInput(BaseModel):
|
||||
"""删除 Agent 自主定时任务的输入参数。"""
|
||||
|
||||
task_id: int = Field(..., ge=1, description="ID of the task to permanently delete.")
|
||||
|
||||
|
||||
class DeleteAgentTaskTool(MoviePilotTool):
|
||||
"""永久删除 Agent 自主定时任务。"""
|
||||
|
||||
name: str = "delete_agent_task"
|
||||
tags: list[str] = [ToolTag.Write, ToolTag.AgentTask, ToolTag.Admin]
|
||||
description: str = (
|
||||
"Permanently delete an autonomous agent task and remove its runtime schedule. "
|
||||
"Use update_agent_task with enabled=false when the user only wants to pause it."
|
||||
)
|
||||
args_schema: Type[BaseModel] = DeleteAgentTaskInput
|
||||
require_admin: bool = True
|
||||
|
||||
def get_tool_message(self, **kwargs: object) -> Optional[str]:
|
||||
"""生成删除定时任务的提示消息。"""
|
||||
return f"删除自主定时任务:{kwargs.get('task_id', '')}"
|
||||
|
||||
def _delete_task(self, task_id: int) -> bool:
|
||||
"""删除当前用户的任务并移除运行时调度。"""
|
||||
from app.application.scheduling import remove_agent_task_job
|
||||
|
||||
deleted = self.data.tasks.delete(
|
||||
task_id=task_id,
|
||||
user_id=str(self._user_id),
|
||||
)
|
||||
if deleted:
|
||||
remove_agent_task_job(task_id)
|
||||
return deleted
|
||||
|
||||
async def run(self, task_id: int, **kwargs: object) -> str:
|
||||
"""删除 Agent 自主定时任务。"""
|
||||
payload = DeleteAgentTaskInput(task_id=task_id)
|
||||
deleted = await self.run_blocking("db", self._delete_task, payload.task_id)
|
||||
if not deleted:
|
||||
return f"Agent 定时任务 {task_id} 不存在或不属于当前用户"
|
||||
return f"Agent 定时任务 {task_id} 已删除"
|
||||
@@ -1,99 +0,0 @@
|
||||
"""删除自定义过滤规则工具。"""
|
||||
|
||||
import json
|
||||
from typing import Optional, Type
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from app.agent.tools.base import MoviePilotTool
|
||||
from app.agent.tools.tags import ToolTag
|
||||
from app.agent.tools.impl._filter_rule_utils import (
|
||||
collect_custom_rule_group_refs,
|
||||
get_custom_rules,
|
||||
get_rule_groups,
|
||||
save_system_config,
|
||||
)
|
||||
from app.runtime.log import logger
|
||||
from app.schemas.types import SystemConfigKey
|
||||
|
||||
|
||||
class DeleteCustomFilterRuleInput(BaseModel):
|
||||
"""删除自定义过滤规则工具的输入参数模型"""
|
||||
|
||||
rule_id: str = Field(..., description="Custom rule ID to delete.")
|
||||
|
||||
|
||||
class DeleteCustomFilterRuleTool(MoviePilotTool):
|
||||
name: str = "delete_custom_filter_rule"
|
||||
tags: list[str] = [
|
||||
ToolTag.Write,
|
||||
ToolTag.FilterRule,
|
||||
ToolTag.Admin,
|
||||
]
|
||||
description: str = (
|
||||
"Delete a custom filter rule from CustomFilterRules. "
|
||||
"If the rule is still referenced by rule groups, the deletion is blocked to avoid breaking rule_string expressions."
|
||||
)
|
||||
args_schema: Type[BaseModel] = DeleteCustomFilterRuleInput
|
||||
require_admin: bool = True
|
||||
|
||||
def get_tool_message(self, **kwargs) -> Optional[str]:
|
||||
return f"删除自定义过滤规则 {kwargs.get('rule_id', '')}"
|
||||
|
||||
async def run(self, rule_id: str, **kwargs) -> str:
|
||||
logger.info(f"执行工具: {self.name}, rule_id={rule_id}")
|
||||
|
||||
try:
|
||||
custom_rules = get_custom_rules()
|
||||
target_rule = next((rule for rule in custom_rules if rule.id == rule_id), None)
|
||||
if not target_rule:
|
||||
return json.dumps(
|
||||
{
|
||||
"success": False,
|
||||
"message": f"自定义过滤规则 '{rule_id}' 不存在",
|
||||
},
|
||||
ensure_ascii=False,
|
||||
)
|
||||
|
||||
refs = collect_custom_rule_group_refs(get_rule_groups(), [rule_id]).get(
|
||||
rule_id, []
|
||||
)
|
||||
if refs:
|
||||
return json.dumps(
|
||||
{
|
||||
"success": False,
|
||||
"message": (
|
||||
f"自定义过滤规则 '{rule_id}' 仍被规则组引用,无法删除。"
|
||||
),
|
||||
"referenced_by_rule_groups": refs,
|
||||
},
|
||||
ensure_ascii=False,
|
||||
indent=2,
|
||||
)
|
||||
|
||||
remaining_rules = [
|
||||
rule for rule in custom_rules if rule.id != rule_id
|
||||
]
|
||||
await save_system_config(
|
||||
SystemConfigKey.CustomFilterRules,
|
||||
[rule.model_dump(exclude_none=True) for rule in remaining_rules],
|
||||
)
|
||||
|
||||
return json.dumps(
|
||||
{
|
||||
"success": True,
|
||||
"message": f"已删除自定义过滤规则 {rule_id}",
|
||||
"count": len(remaining_rules),
|
||||
},
|
||||
ensure_ascii=False,
|
||||
indent=2,
|
||||
)
|
||||
except Exception as exc:
|
||||
logger.error(f"删除自定义过滤规则失败: {exc}", exc_info=True)
|
||||
return json.dumps(
|
||||
{
|
||||
"success": False,
|
||||
"message": f"删除自定义过滤规则失败: {exc}",
|
||||
},
|
||||
ensure_ascii=False,
|
||||
)
|
||||
@@ -1,43 +0,0 @@
|
||||
"""删除下载历史记录工具"""
|
||||
|
||||
from typing import Optional, Type
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from app.agent.tools.base import MoviePilotTool
|
||||
from app.agent.tools.tags import ToolTag
|
||||
from app.runtime.log import logger
|
||||
|
||||
|
||||
class DeleteDownloadHistoryInput(BaseModel):
|
||||
"""删除下载历史记录工具的输入参数模型"""
|
||||
|
||||
history_id: int = Field(
|
||||
..., description="The ID of the download history record to delete"
|
||||
)
|
||||
|
||||
|
||||
class DeleteDownloadHistoryTool(MoviePilotTool):
|
||||
name: str = "delete_download_history"
|
||||
tags: list[str] = [
|
||||
ToolTag.Write,
|
||||
ToolTag.Download,
|
||||
ToolTag.Admin,
|
||||
]
|
||||
description: str = "Delete a download history record by ID. This only removes the record from the database, does not delete any actual files."
|
||||
args_schema: Type[BaseModel] = DeleteDownloadHistoryInput
|
||||
require_admin: bool = True
|
||||
|
||||
def get_tool_message(self, **kwargs) -> Optional[str]:
|
||||
history_id = kwargs.get("history_id")
|
||||
return f"删除下载历史记录 ID: {history_id}"
|
||||
|
||||
async def run(self, history_id: int, **kwargs) -> str:
|
||||
logger.info(f"执行工具: {self.name}, 参数: history_id={history_id}")
|
||||
|
||||
try:
|
||||
await self.data.download_history.async_delete(history_id)
|
||||
return f"下载历史记录 ID: {history_id} 已成功删除"
|
||||
except Exception as e:
|
||||
logger.error(f"删除下载历史记录失败: {e}", exc_info=True)
|
||||
return f"删除下载历史记录时发生错误: {str(e)}"
|
||||
@@ -1,102 +0,0 @@
|
||||
"""删除下载任务工具"""
|
||||
|
||||
from typing import Optional, Type, cast
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from app.agent.tools.base import MoviePilotTool
|
||||
from app.agent.tools.tags import ToolTag
|
||||
from app.chain.download import DownloadChain
|
||||
from app.runtime.log import logger
|
||||
|
||||
|
||||
class DeleteDownloadTasksInput(BaseModel):
|
||||
"""删除下载任务工具的输入参数模型"""
|
||||
|
||||
hash: str = Field(
|
||||
..., description="Task hash (can be obtained from query_download_tasks tool)"
|
||||
)
|
||||
downloader: Optional[str] = Field(
|
||||
None,
|
||||
description="Name of specific downloader (optional, if not provided will search all downloaders)",
|
||||
)
|
||||
delete_files: Optional[bool] = Field(
|
||||
False,
|
||||
description="Whether to delete downloaded files along with the task (default: False, only removes the task from downloader)",
|
||||
)
|
||||
|
||||
|
||||
class DeleteDownloadTasksTool(MoviePilotTool):
|
||||
"""删除下载任务工具"""
|
||||
|
||||
name: str = "delete_download_tasks"
|
||||
tags: list[str] = [
|
||||
ToolTag.Write,
|
||||
ToolTag.Download,
|
||||
ToolTag.Admin,
|
||||
]
|
||||
description: str = "Delete a download task from the downloader by task hash only. Optionally specify the downloader name and whether to delete downloaded files."
|
||||
args_schema: Type[BaseModel] = DeleteDownloadTasksInput
|
||||
require_admin: bool = True
|
||||
|
||||
def get_tool_message(self, **kwargs) -> Optional[str]:
|
||||
"""根据删除参数生成友好的提示消息"""
|
||||
hash_value = kwargs.get("hash", "")
|
||||
downloader = kwargs.get("downloader")
|
||||
delete_files = kwargs.get("delete_files", False)
|
||||
|
||||
message = f"删除下载任务: {hash_value}"
|
||||
if downloader:
|
||||
message += f" [下载器: {downloader}]"
|
||||
if delete_files:
|
||||
message += " (包含文件)"
|
||||
|
||||
return message
|
||||
|
||||
@staticmethod
|
||||
def _delete_download_sync(
|
||||
hash_value: str, downloader: Optional[str] = None, delete_files: bool = False
|
||||
) -> bool:
|
||||
"""同步删除下载任务,避免下载器客户端阻塞事件循环。"""
|
||||
return cast(
|
||||
bool,
|
||||
DownloadChain().remove_torrents(
|
||||
hashs=[hash_value], downloader=downloader, delete_file=delete_files
|
||||
),
|
||||
)
|
||||
|
||||
async def run(
|
||||
self,
|
||||
hash: str,
|
||||
downloader: Optional[str] = None,
|
||||
delete_files: Optional[bool] = False,
|
||||
**kwargs,
|
||||
) -> str:
|
||||
"""执行删除下载任务。"""
|
||||
logger.info(
|
||||
f"执行工具: {self.name}, 参数: hash={hash}, downloader={downloader}, delete_files={delete_files}"
|
||||
)
|
||||
|
||||
try:
|
||||
# 仅支持通过hash删除任务
|
||||
if len(hash) != 40 or not all(c in "0123456789abcdefABCDEF" for c in hash):
|
||||
return "参数错误:hash 格式无效,请先使用 query_download_tasks 工具获取正确的 hash。"
|
||||
|
||||
# 删除下载任务
|
||||
# remove_torrents 支持 delete_file 参数,可以控制是否删除文件
|
||||
result = await self.run_blocking(
|
||||
"downloader",
|
||||
self._delete_download_sync,
|
||||
hash,
|
||||
downloader,
|
||||
bool(delete_files),
|
||||
)
|
||||
|
||||
if result:
|
||||
files_info = "(包含文件)" if delete_files else "(不包含文件)"
|
||||
return f"成功删除下载任务:{hash} {files_info}"
|
||||
else:
|
||||
return f"删除下载任务失败:{hash},请检查任务是否存在或下载器是否可用"
|
||||
except Exception as e:
|
||||
logger.error(f"删除下载任务失败: {e}", exc_info=True)
|
||||
return f"删除下载任务时发生错误: {str(e)}"
|
||||
@@ -1,94 +0,0 @@
|
||||
"""删除过滤规则组工具。"""
|
||||
|
||||
import json
|
||||
from typing import Optional, Type
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from app.agent.tools.base import MoviePilotTool
|
||||
from app.agent.tools.impl._filter_rule_utils import (
|
||||
get_rule_groups,
|
||||
publish_rule_config_changed,
|
||||
)
|
||||
from app.agent.tools.tags import ToolTag
|
||||
from app.runtime.log import logger
|
||||
from app.schemas.types import SystemConfigKey
|
||||
|
||||
|
||||
class DeleteRuleGroupInput(BaseModel):
|
||||
"""删除过滤规则组工具的输入参数模型"""
|
||||
|
||||
name: str = Field(..., description="Rule group name to delete.")
|
||||
|
||||
|
||||
class DeleteRuleGroupTool(MoviePilotTool):
|
||||
name: str = "delete_rule_group"
|
||||
tags: list[str] = [
|
||||
ToolTag.Write,
|
||||
ToolTag.FilterRule,
|
||||
ToolTag.Admin,
|
||||
]
|
||||
description: str = (
|
||||
"Delete a filter rule group from UserFilterRuleGroups. "
|
||||
"The tool also removes dangling references from global settings and subscriptions."
|
||||
)
|
||||
args_schema: Type[BaseModel] = DeleteRuleGroupInput
|
||||
require_admin: bool = True
|
||||
|
||||
def get_tool_message(self, **kwargs) -> Optional[str]:
|
||||
return f"删除规则组 {kwargs.get('name', '')}"
|
||||
|
||||
async def run(self, name: str, **kwargs) -> str:
|
||||
logger.info(f"执行工具: {self.name}, name={name}")
|
||||
|
||||
try:
|
||||
rule_groups = get_rule_groups()
|
||||
expected_definitions = [
|
||||
group.model_dump(exclude_none=True) for group in rule_groups
|
||||
]
|
||||
if not any(group.name == name for group in rule_groups):
|
||||
return json.dumps(
|
||||
{
|
||||
"success": False,
|
||||
"message": f"规则组 '{name}' 不存在",
|
||||
},
|
||||
ensure_ascii=False,
|
||||
)
|
||||
|
||||
remaining_groups = [
|
||||
group for group in rule_groups if group.name != name
|
||||
]
|
||||
definitions = [
|
||||
group.model_dump(exclude_none=True) for group in remaining_groups
|
||||
]
|
||||
async with self.data.async_rule_group_mutation_scope() as mutation:
|
||||
result = await mutation.apply(
|
||||
definitions,
|
||||
expected_rule_groups=expected_definitions,
|
||||
previous_name=name,
|
||||
)
|
||||
await publish_rule_config_changed(
|
||||
SystemConfigKey.UserFilterRuleGroups,
|
||||
definitions,
|
||||
)
|
||||
reference_changes = result.to_dict()
|
||||
|
||||
return json.dumps(
|
||||
{
|
||||
"success": True,
|
||||
"message": f"已删除规则组 {name}",
|
||||
"count": len(remaining_groups),
|
||||
"reference_updates": reference_changes,
|
||||
},
|
||||
ensure_ascii=False,
|
||||
indent=2,
|
||||
)
|
||||
except Exception as exc:
|
||||
logger.error(f"删除规则组失败: {exc}", exc_info=True)
|
||||
return json.dumps(
|
||||
{
|
||||
"success": False,
|
||||
"message": f"删除规则组失败: {exc}",
|
||||
},
|
||||
ensure_ascii=False,
|
||||
)
|
||||
@@ -1,67 +0,0 @@
|
||||
"""删除订阅工具"""
|
||||
|
||||
from typing import Optional, Type
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from app.agent.tools.base import MoviePilotTool
|
||||
from app.agent.tools.tags import ToolTag
|
||||
from app.application.subscription.delete import (
|
||||
SubscribeDeletionActor,
|
||||
)
|
||||
from app.application.subscription.mutation import SubscriptionActor
|
||||
from app.runtime.log import logger
|
||||
|
||||
|
||||
class DeleteSubscribeInput(BaseModel):
|
||||
"""删除订阅工具的输入参数模型"""
|
||||
|
||||
subscribe_id: int = Field(
|
||||
...,
|
||||
description="The ID of the subscription to delete (can be obtained from query_subscribes tool)",
|
||||
)
|
||||
|
||||
|
||||
class DeleteSubscribeTool(MoviePilotTool):
|
||||
"""按订阅 ID 删除影视、单曲或专辑订阅。"""
|
||||
|
||||
name: str = "delete_subscribe"
|
||||
tags: list[str] = [
|
||||
ToolTag.Write,
|
||||
ToolTag.Subscription,
|
||||
ToolTag.Admin,
|
||||
]
|
||||
description: str = "Delete a media subscription by its ID. This will remove the subscription and stop automatic downloads for that media."
|
||||
args_schema: Type[BaseModel] = DeleteSubscribeInput
|
||||
require_admin: bool = True
|
||||
|
||||
def get_tool_message(self, **kwargs) -> Optional[str]:
|
||||
"""根据删除参数生成友好的提示消息"""
|
||||
subscribe_id = kwargs.get("subscribe_id")
|
||||
return f"删除订阅 (ID: {subscribe_id})"
|
||||
|
||||
async def run(self, subscribe_id: int, **kwargs) -> str:
|
||||
"""删除订阅并同步刷新带音乐实体维度的共享统计。"""
|
||||
logger.info(f"执行工具: {self.name}, 参数: subscribe_id={subscribe_id}")
|
||||
|
||||
try:
|
||||
async with self.data.subscription_mutation_scope() as mutation:
|
||||
subscribe = await mutation.get_accessible(
|
||||
subscribe_id,
|
||||
SubscriptionActor(name="agent", is_superuser=True),
|
||||
)
|
||||
if not subscribe:
|
||||
return f"订阅 ID {subscribe_id} 不存在"
|
||||
|
||||
async with self.data.subscription_delete_scope() as command:
|
||||
deleted = await command.execute(
|
||||
subscribe_id,
|
||||
SubscribeDeletionActor(username="agent", is_superuser=True),
|
||||
)
|
||||
if not deleted:
|
||||
return f"订阅 ID {subscribe_id} 不存在"
|
||||
|
||||
return f"成功删除订阅:{subscribe.name} ({subscribe.year})"
|
||||
except Exception as e:
|
||||
logger.error(f"删除订阅失败: {e}", exc_info=True)
|
||||
return f"删除订阅时发生错误: {str(e)}"
|
||||
@@ -1,134 +0,0 @@
|
||||
"""删除整理历史记录工具"""
|
||||
|
||||
import asyncio
|
||||
from typing import Optional, Type
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from app.agent.tools.base import MoviePilotTool
|
||||
from app.agent.tools.tags import ToolTag
|
||||
from app.application.transfer.execution import (
|
||||
TransferExecutionCommand,
|
||||
TransferExecutionRepository,
|
||||
TransferRetryRequestResult,
|
||||
)
|
||||
from app.chain.storage import StorageChain
|
||||
from app.runtime.log import logger
|
||||
from app.schemas.workflow import FileItem
|
||||
|
||||
|
||||
class DeleteTransferHistoryInput(BaseModel):
|
||||
"""删除整理历史记录工具的输入参数模型"""
|
||||
|
||||
history_id: int = Field(
|
||||
..., description="The ID of the transfer history record to delete"
|
||||
)
|
||||
|
||||
|
||||
def _delete_history_destination_file(fileitem: FileItem) -> tuple[bool, bool]:
|
||||
"""在存储 worker 内完成旧目标检查和删除,保持历史删除前的顺序。"""
|
||||
storage_chain = StorageChain()
|
||||
if not storage_chain.exists(fileitem):
|
||||
return False, False
|
||||
return True, bool(storage_chain.delete_media_file(fileitem))
|
||||
|
||||
|
||||
def _request_transfer_retry(
|
||||
repository: TransferExecutionRepository,
|
||||
*,
|
||||
history_id: int,
|
||||
task_id: str,
|
||||
user_id: str,
|
||||
) -> TransferRetryRequestResult:
|
||||
"""在线程池中登记 durable 重试,避免 Agent 事件循环执行同步数据库 I/O。"""
|
||||
return TransferExecutionCommand(
|
||||
repository
|
||||
).request_retry(
|
||||
task_id=task_id,
|
||||
reason=f"Agent 请求重试整理历史 #{history_id}",
|
||||
requested_by=f"agent:{user_id or 'unknown'}",
|
||||
)
|
||||
|
||||
|
||||
class DeleteTransferHistoryTool(MoviePilotTool):
|
||||
name: str = "delete_transfer_history"
|
||||
tags: list[str] = [
|
||||
ToolTag.Write,
|
||||
ToolTag.Transfer,
|
||||
ToolTag.Admin,
|
||||
]
|
||||
description: str = (
|
||||
"Request a safe retry for durable transfer history, or delete a legacy transfer history record by its ID. "
|
||||
"Durable records keep their files and history and are retried only by the persistent scheduler. For legacy "
|
||||
"non-successful-move records, the tool removes the old destination before deleting the history. If a durable "
|
||||
"retry is accepted or rejected, stop and report that result; do not call transfer_file for the same record."
|
||||
)
|
||||
args_schema: Type[BaseModel] = DeleteTransferHistoryInput
|
||||
require_admin: bool = True
|
||||
|
||||
def get_tool_message(self, **kwargs) -> Optional[str]:
|
||||
"""根据参数生成友好的提示消息"""
|
||||
history_id = kwargs.get("history_id")
|
||||
return f"删除整理历史记录: ID={history_id}"
|
||||
|
||||
async def run(self, history_id: int, **kwargs) -> str:
|
||||
logger.info(f"执行工具: {self.name}, 参数: history_id={history_id}")
|
||||
|
||||
try:
|
||||
transferhis = self.data.transfer_history
|
||||
history = await transferhis.async_get(history_id)
|
||||
if not history:
|
||||
return f"错误:整理历史记录不存在,ID={history_id}"
|
||||
|
||||
task_id = getattr(history, "transfer_task_id", None)
|
||||
if task_id:
|
||||
retry = await self.run_blocking(
|
||||
"db",
|
||||
_request_transfer_retry,
|
||||
self.data.transfer_execution,
|
||||
history_id=history_id,
|
||||
task_id=task_id,
|
||||
user_id=self._user_id,
|
||||
)
|
||||
outcome = "已登记" if retry.accepted else "未登记"
|
||||
return (
|
||||
f"durable 整理任务{outcome}重试:ID={history_id},"
|
||||
f"task_id={task_id},state={retry.state.value},{retry.message}。"
|
||||
"已保留目标文件、历史记录和失败计数;不要调用 transfer_file。"
|
||||
)
|
||||
|
||||
title = history.title or "未知"
|
||||
src = history.src or "未知"
|
||||
status = "成功" if history.status else "失败"
|
||||
deleted_dest = False
|
||||
if history.dest_fileitem and not (history.status and history.mode == "move"):
|
||||
if not isinstance(history.dest_fileitem, dict):
|
||||
return "删除失败:目标文件历史数据无效,已保留历史记录"
|
||||
dest_fileitem = FileItem(**history.dest_fileitem)
|
||||
try:
|
||||
destination_exists, destination_deleted = await self.run_blocking(
|
||||
"storage",
|
||||
_delete_history_destination_file,
|
||||
dest_fileitem,
|
||||
)
|
||||
except asyncio.CancelledError:
|
||||
logger.warning(
|
||||
"删除整理历史的旧媒体文件等待已取消,底层文件操作可能仍在继续,"
|
||||
"请确认实际状态后再重试,历史记录尚未删除,path=%s",
|
||||
dest_fileitem.path,
|
||||
)
|
||||
raise
|
||||
if destination_exists:
|
||||
if not destination_deleted:
|
||||
return f"错误:旧媒体库文件删除失败,路径={dest_fileitem.path}"
|
||||
deleted_dest = True
|
||||
await transferhis.async_delete(history_id)
|
||||
message = (
|
||||
f"已删除整理历史记录:ID={history_id},标题={title},源路径={src},状态={status}"
|
||||
)
|
||||
if deleted_dest:
|
||||
message += ",已删除旧媒体库文件"
|
||||
return message
|
||||
except Exception as e:
|
||||
logger.error(f"删除整理历史记录失败: {e}", exc_info=True)
|
||||
return f"删除整理历史记录时发生错误: {str(e)}"
|
||||
@@ -1,347 +0,0 @@
|
||||
"""获取推荐工具"""
|
||||
|
||||
import json
|
||||
from typing import Optional, Type
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from app.agent.tools.base import MoviePilotTool
|
||||
from app.agent.tools.tags import ToolTag
|
||||
from app.chain.recommend import RecommendChain
|
||||
from app.runtime.log import logger
|
||||
from app.chain.listenbrainz import (
|
||||
LISTENBRAINZ_CHART_RANGES,
|
||||
LISTENBRAINZ_FRESH_MAX_DAYS,
|
||||
LISTENBRAINZ_FRESH_SORTS,
|
||||
)
|
||||
from app.schemas.types import (
|
||||
MUSIC_ENTITY_ALBUM,
|
||||
MUSIC_ENTITY_RECORDING,
|
||||
MediaType,
|
||||
media_type_to_agent,
|
||||
)
|
||||
from app.domain.media import normalize_music_type
|
||||
from ._music_utils import simplify_music_info
|
||||
|
||||
|
||||
class GetRecommendationsInput(BaseModel):
|
||||
"""获取推荐工具的输入参数模型"""
|
||||
|
||||
source: Optional[str] = Field(
|
||||
"tmdb_trending",
|
||||
description="Recommendation source: "
|
||||
"'tmdb_trending' for TMDB trending content, "
|
||||
"'tmdb_movies' for TMDB popular movies, "
|
||||
"'tmdb_tvs' for TMDB popular TV shows, "
|
||||
"'douban_hot' for Douban popular content, "
|
||||
"'douban_movie_hot' for Douban hot movies, "
|
||||
"'douban_tv_hot' for Douban hot TV shows, "
|
||||
"'douban_movie_showing' for Douban movies currently showing, "
|
||||
"'douban_movies' for Douban latest movies, "
|
||||
"'douban_tvs' for Douban latest TV shows, "
|
||||
"'douban_movie_top250' for Douban movie TOP250, "
|
||||
"'douban_tv_weekly_chinese' for Douban Chinese TV weekly chart, "
|
||||
"'douban_tv_weekly_global' for Douban global TV weekly chart, "
|
||||
"'douban_tv_animation' for Douban popular animation, "
|
||||
"'bangumi_calendar' for Bangumi anime calendar, "
|
||||
"'listenbrainz_chart' for popular recordings/albums, "
|
||||
"'listenbrainz_fresh' for fresh album releases",
|
||||
)
|
||||
media_type: Optional[str] = Field(
|
||||
"all", description="Allowed values: movie, tv, music, all"
|
||||
)
|
||||
page: Optional[int] = Field(
|
||||
1, description="Page number for pagination (default: 1, 20 items per page)"
|
||||
)
|
||||
music_type: Optional[str] = Field(
|
||||
None,
|
||||
description="For listenbrainz_chart: recording or album. Fresh releases are always albums",
|
||||
)
|
||||
range_name: Optional[str] = Field(
|
||||
"this_month",
|
||||
description="ListenBrainz chart range such as this_week, this_month, this_year, or all_time",
|
||||
)
|
||||
sort_by: Optional[str] = Field(
|
||||
"listen_count.desc",
|
||||
description="ListenBrainz chart sort: listen_count.desc or listen_count.asc",
|
||||
)
|
||||
days: Optional[int] = Field(14, description="Fresh release window in days, max 90")
|
||||
fresh_sort: Optional[str] = Field(
|
||||
"release_date",
|
||||
description="Fresh release sort: release_date, artist_credit_name, or release_name",
|
||||
)
|
||||
past: Optional[bool] = Field(True, description="Include already released albums")
|
||||
future: Optional[bool] = Field(True, description="Include upcoming albums")
|
||||
min_listen_count: Optional[int] = Field(0, description="Minimum chart listen count")
|
||||
with_cover: Optional[bool] = Field(False, description="Only return music results with cover art")
|
||||
|
||||
|
||||
class GetRecommendationsTool(MoviePilotTool):
|
||||
"""获取影视推荐或 ListenBrainz 音乐探索结果。"""
|
||||
|
||||
name: str = "get_recommendations"
|
||||
tags: list[str] = [
|
||||
ToolTag.Read,
|
||||
ToolTag.Media,
|
||||
ToolTag.Recommendation,
|
||||
]
|
||||
description: str = (
|
||||
"Get movie, TV, anime, or music discovery results. Music supports ListenBrainz chart periods, "
|
||||
"recording/album modes, listen-count sorting, and fresh album releases. Returned music IDs can be "
|
||||
"passed directly to detail, library, subscription, and torrent tools."
|
||||
)
|
||||
args_schema: Type[BaseModel] = GetRecommendationsInput
|
||||
|
||||
def get_tool_message(self, **kwargs) -> Optional[str]:
|
||||
"""根据推荐参数生成友好的提示消息"""
|
||||
source = kwargs.get("source", "tmdb_trending")
|
||||
media_type = kwargs.get("media_type", "all")
|
||||
page = kwargs.get("page", 1)
|
||||
|
||||
source_map = {
|
||||
"tmdb_trending": "TMDB流行趋势",
|
||||
"tmdb_movies": "TMDB热门电影",
|
||||
"tmdb_tvs": "TMDB热门电视剧",
|
||||
"douban_hot": "豆瓣热门",
|
||||
"douban_movie_hot": "豆瓣热门电影",
|
||||
"douban_tv_hot": "豆瓣热门电视剧",
|
||||
"douban_movie_showing": "豆瓣热映",
|
||||
"douban_movies": "豆瓣最新电影",
|
||||
"douban_tvs": "豆瓣最新电视剧",
|
||||
"douban_movie_top250": "豆瓣电影TOP250",
|
||||
"douban_tv_weekly_chinese": "豆瓣国产剧集榜",
|
||||
"douban_tv_weekly_global": "豆瓣全球剧集榜",
|
||||
"douban_tv_animation": "豆瓣热门动漫",
|
||||
"bangumi_calendar": "番组计划",
|
||||
"listenbrainz_chart": "ListenBrainz 音乐榜单",
|
||||
"listenbrainz_fresh": "ListenBrainz 新发行专辑",
|
||||
}
|
||||
source_desc = source_map.get(source, source)
|
||||
|
||||
message = f"获取推荐: {source_desc}"
|
||||
if media_type != "all":
|
||||
message += f" [{media_type}]"
|
||||
message += f" (第{page}页)"
|
||||
|
||||
return message
|
||||
|
||||
async def run(
|
||||
self,
|
||||
source: Optional[str] = "tmdb_trending",
|
||||
media_type: Optional[str] = "all",
|
||||
page: Optional[int] = 1,
|
||||
music_type: Optional[str] = None,
|
||||
range_name: Optional[str] = "this_month",
|
||||
sort_by: Optional[str] = "listen_count.desc",
|
||||
days: Optional[int] = 14,
|
||||
fresh_sort: Optional[str] = "release_date",
|
||||
past: Optional[bool] = True,
|
||||
future: Optional[bool] = True,
|
||||
min_listen_count: Optional[int] = 0,
|
||||
with_cover: Optional[bool] = False,
|
||||
**kwargs,
|
||||
) -> str:
|
||||
"""按来源校验参数并返回有界推荐列表。"""
|
||||
page = max(1, page or 1)
|
||||
page_size = 20
|
||||
logger.info(
|
||||
f"执行工具: {self.name}, 参数: source={source}, media_type={media_type}, page={page}"
|
||||
)
|
||||
try:
|
||||
if media_type != "all":
|
||||
media_type_enum = MediaType.from_agent(media_type)
|
||||
if not media_type_enum:
|
||||
return f"错误:无效的媒体类型 '{media_type}',支持的类型:'movie', 'tv', 'music', 'all'"
|
||||
media_type = media_type_enum.to_agent()
|
||||
|
||||
if source in {"listenbrainz_chart", "listenbrainz_fresh"}:
|
||||
if media_type not in {"all", "music"}:
|
||||
return "错误:ListenBrainz 来源只能与 media_type='music' 或 'all' 一起使用"
|
||||
normalized_music_type = None
|
||||
if music_type:
|
||||
normalized_music_type = normalize_music_type(
|
||||
music_type,
|
||||
allow_artist=False,
|
||||
)
|
||||
if not normalized_music_type:
|
||||
return (
|
||||
f"错误:无效的音乐实体类型 '{music_type}',"
|
||||
"支持的类型:'recording', 'album'"
|
||||
)
|
||||
recommend_chain = RecommendChain()
|
||||
if source == "listenbrainz_chart":
|
||||
if range_name not in LISTENBRAINZ_CHART_RANGES:
|
||||
return f"错误:无效的榜单周期 '{range_name}'"
|
||||
if sort_by not in {"listen_count.desc", "listen_count.asc"}:
|
||||
return f"错误:无效的榜单排序 '{sort_by}'"
|
||||
results = await recommend_chain.async_music_chart(
|
||||
range_name=range_name,
|
||||
page=page,
|
||||
count=page_size,
|
||||
sort_by=sort_by,
|
||||
min_listen_count=max(0, min_listen_count or 0),
|
||||
with_cover=bool(with_cover),
|
||||
entity=normalized_music_type or MUSIC_ENTITY_RECORDING,
|
||||
)
|
||||
else:
|
||||
if normalized_music_type and normalized_music_type != MUSIC_ENTITY_ALBUM:
|
||||
return "错误:ListenBrainz 新发行结果只支持 music_type='album'"
|
||||
if fresh_sort not in LISTENBRAINZ_FRESH_SORTS:
|
||||
return f"错误:无效的新发行排序 '{fresh_sort}'"
|
||||
if not past and not future:
|
||||
return "错误:past 和 future 不能同时为 false"
|
||||
normalized_days = max(1, min(days or 14, LISTENBRAINZ_FRESH_MAX_DAYS))
|
||||
results = await recommend_chain.async_music_fresh_releases(
|
||||
days=normalized_days,
|
||||
sort=fresh_sort,
|
||||
past=bool(past),
|
||||
future=bool(future),
|
||||
page=page,
|
||||
count=page_size,
|
||||
with_cover=bool(with_cover),
|
||||
)
|
||||
if not results:
|
||||
return "未找到音乐推荐内容。"
|
||||
return json.dumps(
|
||||
[simplify_music_info(item) for item in results],
|
||||
ensure_ascii=False,
|
||||
indent=2,
|
||||
)
|
||||
|
||||
if media_type == "music":
|
||||
return "错误:音乐推荐请使用 listenbrainz_chart 或 listenbrainz_fresh 来源"
|
||||
|
||||
recommend_chain = RecommendChain()
|
||||
results = []
|
||||
if source == "tmdb_trending":
|
||||
results = await recommend_chain.async_tmdb_trending(page=page)
|
||||
elif source == "tmdb_movies":
|
||||
results = await recommend_chain.async_tmdb_movies(page=page)
|
||||
elif source == "tmdb_tvs":
|
||||
results = await recommend_chain.async_tmdb_tvs(page=page)
|
||||
elif source == "douban_hot":
|
||||
if media_type == "movie":
|
||||
results = await recommend_chain.async_douban_movie_hot(
|
||||
page=page, count=page_size
|
||||
)
|
||||
elif media_type == "tv":
|
||||
results = await recommend_chain.async_douban_tv_hot(
|
||||
page=page, count=page_size
|
||||
)
|
||||
else: # all
|
||||
results.extend(
|
||||
await recommend_chain.async_douban_movie_hot(
|
||||
page=page, count=page_size
|
||||
)
|
||||
)
|
||||
results.extend(
|
||||
await recommend_chain.async_douban_tv_hot(
|
||||
page=page, count=page_size
|
||||
)
|
||||
)
|
||||
elif source == "douban_movie_hot":
|
||||
results = await recommend_chain.async_douban_movie_hot(
|
||||
page=page, count=page_size
|
||||
)
|
||||
elif source == "douban_tv_hot":
|
||||
results = await recommend_chain.async_douban_tv_hot(
|
||||
page=page, count=page_size
|
||||
)
|
||||
elif source == "douban_movie_showing":
|
||||
results = await recommend_chain.async_douban_movie_showing(
|
||||
page=page, count=page_size
|
||||
)
|
||||
elif source == "douban_movies":
|
||||
results = await recommend_chain.async_douban_movies(
|
||||
page=page, count=page_size
|
||||
)
|
||||
elif source == "douban_tvs":
|
||||
results = await recommend_chain.async_douban_tvs(
|
||||
page=page, count=page_size
|
||||
)
|
||||
elif source == "douban_movie_top250":
|
||||
results = await recommend_chain.async_douban_movie_top250(
|
||||
page=page, count=page_size
|
||||
)
|
||||
elif source == "douban_tv_weekly_chinese":
|
||||
results = await recommend_chain.async_douban_tv_weekly_chinese(
|
||||
page=page, count=page_size
|
||||
)
|
||||
elif source == "douban_tv_weekly_global":
|
||||
results = await recommend_chain.async_douban_tv_weekly_global(
|
||||
page=page, count=page_size
|
||||
)
|
||||
elif source == "douban_tv_animation":
|
||||
results = await recommend_chain.async_douban_tv_animation(
|
||||
page=page, count=page_size
|
||||
)
|
||||
elif source == "bangumi_calendar":
|
||||
results = await recommend_chain.async_bangumi_calendar(
|
||||
page=page, count=page_size
|
||||
)
|
||||
else:
|
||||
# 不支持的推荐来源
|
||||
supported_sources = [
|
||||
"tmdb_trending",
|
||||
"tmdb_movies",
|
||||
"tmdb_tvs",
|
||||
"douban_hot",
|
||||
"douban_movie_hot",
|
||||
"douban_tv_hot",
|
||||
"douban_movie_showing",
|
||||
"douban_movies",
|
||||
"douban_tvs",
|
||||
"douban_movie_top250",
|
||||
"douban_tv_weekly_chinese",
|
||||
"douban_tv_weekly_global",
|
||||
"douban_tv_animation",
|
||||
"bangumi_calendar",
|
||||
"listenbrainz_chart",
|
||||
"listenbrainz_fresh",
|
||||
]
|
||||
return f"不支持的推荐来源: {source}。支持的来源包括: {', '.join(supported_sources)}"
|
||||
|
||||
if results:
|
||||
# 对于TMDB来源,API自身按页返回,取前page_size条
|
||||
total_count = len(results)
|
||||
page_results = results[:page_size]
|
||||
# 精简字段,只保留关键信息
|
||||
simplified_results = []
|
||||
for r in page_results:
|
||||
# r 应该是字典格式(to_dict的结果),但为了安全起见进行检查
|
||||
if not isinstance(r, dict):
|
||||
logger.warning(f"推荐结果格式异常,跳过: {type(r)}")
|
||||
continue
|
||||
|
||||
simplified = {
|
||||
"title": r.get("title"),
|
||||
"en_title": r.get("en_title"),
|
||||
"year": r.get("year"),
|
||||
"type": media_type_to_agent(r.get("type")),
|
||||
"season": r.get("season"),
|
||||
"tmdb_id": r.get("tmdb_id"),
|
||||
"imdb_id": r.get("imdb_id"),
|
||||
"douban_id": r.get("douban_id"),
|
||||
"bangumi_id": r.get("bangumi_id"),
|
||||
"anilist_id": r.get("anilist_id"),
|
||||
"media_source": r.get("media_source"),
|
||||
"media_id": r.get("media_id"),
|
||||
"vote_average": r.get("vote_average"),
|
||||
"poster_path": r.get("poster_path"),
|
||||
"detail_link": r.get("detail_link"),
|
||||
}
|
||||
simplified_results.append(simplified)
|
||||
result_json = json.dumps(
|
||||
simplified_results, ensure_ascii=False, indent=2
|
||||
)
|
||||
has_more = total_count > page_size
|
||||
payload_msg = f"第 {page} 页,当前页 {len(simplified_results)} 条结果。"
|
||||
if has_more:
|
||||
payload_msg += (
|
||||
f" 可能有更多数据,可使用 page={page + 1} 获取下一页。"
|
||||
)
|
||||
return f"{payload_msg}\n\n{result_json}"
|
||||
return "未找到推荐内容。"
|
||||
except Exception as e:
|
||||
logger.error(f"获取推荐失败: {e}", exc_info=True)
|
||||
return f"获取推荐时发生错误: {str(e)}"
|
||||
@@ -1,221 +0,0 @@
|
||||
"""获取搜索结果工具"""
|
||||
|
||||
import json
|
||||
import re
|
||||
from typing import List, Optional, Type
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from app.agent.tools.base import MoviePilotTool
|
||||
from app.agent.tools.tags import ToolTag
|
||||
from app.chain.search.facade import SearchChain
|
||||
from app.runtime.log import logger
|
||||
from ._torrent_search_utils import (
|
||||
TORRENT_RESULT_LIMIT,
|
||||
build_filter_options,
|
||||
filter_contexts,
|
||||
simplify_search_result,
|
||||
)
|
||||
|
||||
|
||||
class GetSearchResultsInput(BaseModel):
|
||||
"""获取搜索结果工具的输入参数模型"""
|
||||
|
||||
site: Optional[List[str]] = Field(None, description="Site name filters")
|
||||
season: Optional[List[str]] = Field(None, description="Season or episode filters")
|
||||
free_state: Optional[List[str]] = Field(None, description="Promotion state filters")
|
||||
video_code: Optional[List[str]] = Field(None, description="Video codec filters")
|
||||
edition: Optional[List[str]] = Field(None, description="Edition filters")
|
||||
resolution: Optional[List[str]] = Field(None, description="Resolution filters")
|
||||
release_group: Optional[List[str]] = Field(
|
||||
None, description="Release group filters"
|
||||
)
|
||||
title_pattern: Optional[str] = Field(
|
||||
None,
|
||||
description="Regular expression pattern to filter torrent titles (e.g., '4K|2160p|UHD', '1080p.*BluRay')",
|
||||
)
|
||||
content_pattern: Optional[str] = Field(
|
||||
None,
|
||||
description="Regular expression pattern to filter torrent titles, descriptions, and labels (e.g., '特效字幕|国语|DIY')",
|
||||
)
|
||||
include_description: Optional[bool] = Field(
|
||||
False,
|
||||
description="Whether to include torrent descriptions in returned results",
|
||||
)
|
||||
include_labels: Optional[bool] = Field(
|
||||
False,
|
||||
description="Whether to include torrent labels in returned results",
|
||||
)
|
||||
show_filter_options: Optional[bool] = Field(
|
||||
False,
|
||||
description="Whether to return only optional filter options for re-checking available conditions",
|
||||
)
|
||||
page: Optional[int] = Field(
|
||||
1,
|
||||
description="Page number for pagination (default: 1, each page returns up to 50 results)",
|
||||
)
|
||||
|
||||
|
||||
class GetSearchResultsTool(MoviePilotTool):
|
||||
"""获取并筛选最近一次种子搜索结果"""
|
||||
|
||||
name: str = "get_search_results"
|
||||
tags: list[str] = [
|
||||
ToolTag.Read,
|
||||
ToolTag.Resource,
|
||||
]
|
||||
description: str = "Get cached torrent search results from search_torrents with optional filters. Supports pagination with up to 50 results per page."
|
||||
args_schema: Type[BaseModel] = GetSearchResultsInput
|
||||
|
||||
def get_tool_message(self, **kwargs) -> Optional[str]:
|
||||
"""返回工具执行提示"""
|
||||
return "获取搜索结果"
|
||||
|
||||
async def run(
|
||||
self,
|
||||
site: Optional[List[str]] = None,
|
||||
season: Optional[List[str]] = None,
|
||||
free_state: Optional[List[str]] = None,
|
||||
video_code: Optional[List[str]] = None,
|
||||
edition: Optional[List[str]] = None,
|
||||
resolution: Optional[List[str]] = None,
|
||||
release_group: Optional[List[str]] = None,
|
||||
title_pattern: Optional[str] = None,
|
||||
content_pattern: Optional[str] = None,
|
||||
include_description: bool = False,
|
||||
include_labels: bool = False,
|
||||
show_filter_options: bool = False,
|
||||
page: Optional[int] = 1,
|
||||
**kwargs,
|
||||
) -> str:
|
||||
"""
|
||||
获取并筛选最近一次种子搜索结果
|
||||
|
||||
:param site: 站点名称筛选项
|
||||
:param season: 季集筛选项
|
||||
:param free_state: 促销状态筛选项
|
||||
:param video_code: 视频编码筛选项
|
||||
:param edition: 制作版本筛选项
|
||||
:param resolution: 分辨率筛选项
|
||||
:param release_group: 发布组筛选项
|
||||
:param title_pattern: 仅匹配种子标题的正则表达式
|
||||
:param content_pattern: 匹配种子标题、简介和标签的正则表达式
|
||||
:param include_description: 是否在结果中返回种子简介
|
||||
:param include_labels: 是否在结果中返回种子标签
|
||||
:param show_filter_options: 是否只返回可用筛选项
|
||||
:param page: 分页页码
|
||||
:param kwargs: 工具框架附加参数
|
||||
:return: JSON 格式的搜索结果或错误提示
|
||||
"""
|
||||
page = max(1, page or 1)
|
||||
logger.info(
|
||||
f"执行工具: {self.name}, 参数: site={site}, season={season}, free_state={free_state}, video_code={video_code}, edition={edition}, resolution={resolution}, release_group={release_group}, title_pattern={title_pattern}, content_pattern={content_pattern}, include_description={include_description}, include_labels={include_labels}, show_filter_options={show_filter_options}, page={page}"
|
||||
)
|
||||
|
||||
try:
|
||||
items = await SearchChain().async_last_search_results() or []
|
||||
if not items:
|
||||
return "没有可用的搜索结果,请先使用 search_torrents 搜索"
|
||||
|
||||
if show_filter_options:
|
||||
payload = {
|
||||
"total_count": len(items),
|
||||
"filter_options": build_filter_options(items),
|
||||
}
|
||||
return json.dumps(payload, ensure_ascii=False, indent=2)
|
||||
|
||||
title_regex_pattern = None
|
||||
if title_pattern:
|
||||
try:
|
||||
title_regex_pattern = re.compile(title_pattern, re.IGNORECASE)
|
||||
except re.error as e:
|
||||
logger.warning(f"正则表达式编译失败: {title_pattern}, 错误: {e}")
|
||||
return f"正则表达式格式错误: {str(e)}"
|
||||
|
||||
content_regex_pattern = None
|
||||
if content_pattern:
|
||||
try:
|
||||
content_regex_pattern = re.compile(content_pattern, re.IGNORECASE)
|
||||
except re.error as e:
|
||||
logger.warning(f"正则表达式编译失败: {content_pattern}, 错误: {e}")
|
||||
return f"正则表达式格式错误: {str(e)}"
|
||||
|
||||
filtered_items = filter_contexts(
|
||||
items=items,
|
||||
site=site,
|
||||
season=season,
|
||||
free_state=free_state,
|
||||
video_code=video_code,
|
||||
edition=edition,
|
||||
resolution=resolution,
|
||||
release_group=release_group,
|
||||
)
|
||||
if title_regex_pattern:
|
||||
filtered_items = [
|
||||
item
|
||||
for item in filtered_items
|
||||
if item.torrent_info
|
||||
and item.torrent_info.title
|
||||
and title_regex_pattern.search(item.torrent_info.title)
|
||||
]
|
||||
if content_regex_pattern:
|
||||
content_filtered_items = []
|
||||
for item in filtered_items:
|
||||
torrent_info = item.torrent_info
|
||||
if not torrent_info:
|
||||
continue
|
||||
content_values = [torrent_info.title, torrent_info.description]
|
||||
content_values.extend(torrent_info.labels or [])
|
||||
if any(
|
||||
content_regex_pattern.search(str(value))
|
||||
for value in content_values
|
||||
if value
|
||||
):
|
||||
content_filtered_items.append(item)
|
||||
filtered_items = content_filtered_items
|
||||
if not filtered_items:
|
||||
return "没有符合筛选条件的搜索结果,请调整筛选条件"
|
||||
|
||||
total_count = len(filtered_items)
|
||||
filtered_ids = {id(item) for item in filtered_items}
|
||||
matched_indices = [
|
||||
index
|
||||
for index, item in enumerate(items, start=1)
|
||||
if id(item) in filtered_ids
|
||||
]
|
||||
|
||||
# 分页
|
||||
page_size = TORRENT_RESULT_LIMIT
|
||||
start = (page - 1) * page_size
|
||||
end = start + page_size
|
||||
page_items = filtered_items[start:end]
|
||||
page_indices = matched_indices[start:end]
|
||||
|
||||
if not page_items:
|
||||
return f"第 {page} 页没有数据,共 {total_count} 条结果,共 {(total_count + page_size - 1) // page_size} 页。"
|
||||
|
||||
results = [
|
||||
simplify_search_result(
|
||||
item,
|
||||
index,
|
||||
include_description=include_description,
|
||||
include_labels=include_labels,
|
||||
)
|
||||
for item, index in zip(page_items, page_indices)
|
||||
]
|
||||
total_pages = (total_count + page_size - 1) // page_size
|
||||
payload = {
|
||||
"total_count": total_count,
|
||||
"page": page,
|
||||
"total_pages": total_pages,
|
||||
"results": results,
|
||||
}
|
||||
if page < total_pages:
|
||||
payload["message"] = (
|
||||
f"搜索结果共 {total_count} 条,当前第 {page}/{total_pages} 页,可使用 page={page + 1} 获取下一页。"
|
||||
)
|
||||
return json.dumps(payload, ensure_ascii=False, indent=2)
|
||||
except Exception as e:
|
||||
error_message = f"获取搜索结果失败: {str(e)}"
|
||||
logger.error(f"获取搜索结果失败: {e}", exc_info=True)
|
||||
return error_message
|
||||
@@ -1,165 +0,0 @@
|
||||
"""安装插件工具"""
|
||||
|
||||
import json
|
||||
from typing import Optional, Type
|
||||
|
||||
from pydantic import BaseModel, Field, field_validator
|
||||
|
||||
from app.agent.tools.base import MoviePilotTool
|
||||
from app.agent.tools.tags import ToolTag
|
||||
from app.agent.tools.impl._plugin_tool_utils import (
|
||||
get_plugin_snapshot,
|
||||
inspect_plugin_sources,
|
||||
install_plugin_runtime,
|
||||
load_market_plugins,
|
||||
summarize_plugin,
|
||||
)
|
||||
from app.runtime.log import logger
|
||||
|
||||
|
||||
class InstallPluginInput(BaseModel):
|
||||
"""安装插件工具的输入参数模型"""
|
||||
|
||||
plugin_id: str = Field(
|
||||
...,
|
||||
description="Exact plugin ID to install. Use query_market_plugins first to find the correct plugin_id.",
|
||||
)
|
||||
force: bool = Field(
|
||||
False,
|
||||
description="Whether to force reinstall or upgrade the specified plugin.",
|
||||
)
|
||||
force_refresh_market: bool = Field(
|
||||
False,
|
||||
description="Whether to refresh plugin market caches before reading the market list.",
|
||||
)
|
||||
repo_url: Optional[str] = Field(
|
||||
None,
|
||||
description=(
|
||||
"Exact repository URL explicitly selected by the administrator. "
|
||||
"Only set it after a source conflict is shown to the user."
|
||||
),
|
||||
)
|
||||
|
||||
@field_validator("repo_url")
|
||||
@classmethod
|
||||
def normalize_repo_url(cls, value: Optional[str]) -> Optional[str]:
|
||||
"""显式来源必须是非空在线仓库地址。"""
|
||||
if value is None:
|
||||
return None
|
||||
normalized = value.strip()
|
||||
if not normalized:
|
||||
raise ValueError("Explicit source repository URL cannot be empty.")
|
||||
if normalized.startswith("local://"):
|
||||
raise ValueError("Explicit source selection only accepts online repositories.")
|
||||
return normalized
|
||||
|
||||
|
||||
class InstallPluginTool(MoviePilotTool):
|
||||
name: str = "install_plugin"
|
||||
tags: list[str] = [
|
||||
ToolTag.Write,
|
||||
ToolTag.Plugin,
|
||||
ToolTag.Admin,
|
||||
]
|
||||
description: str = (
|
||||
"Install a plugin by exact plugin_id from the plugin market or local plugin repositories. "
|
||||
"Use query_market_plugins first when you need filtering or discovery."
|
||||
)
|
||||
require_admin: bool = True
|
||||
args_schema: Type[BaseModel] = InstallPluginInput
|
||||
|
||||
def get_tool_message(self, **kwargs) -> Optional[str]:
|
||||
plugin_id = kwargs.get("plugin_id")
|
||||
return f"安装插件: {plugin_id or '未知插件'}"
|
||||
|
||||
async def run(
|
||||
self,
|
||||
plugin_id: str,
|
||||
force: bool = False,
|
||||
force_refresh_market: bool = False,
|
||||
repo_url: Optional[str] = None,
|
||||
**kwargs,
|
||||
) -> str:
|
||||
logger.info(
|
||||
f"执行工具: {self.name}, 参数: plugin_id={plugin_id}, force={force}"
|
||||
)
|
||||
|
||||
try:
|
||||
plugins = await load_market_plugins(force_refresh=force_refresh_market)
|
||||
if not plugins:
|
||||
return json.dumps(
|
||||
{"success": False, "message": "当前插件市场没有可用插件"},
|
||||
ensure_ascii=False,
|
||||
)
|
||||
|
||||
candidate = next((plugin for plugin in plugins if plugin.id == plugin_id), None)
|
||||
if not candidate:
|
||||
return json.dumps(
|
||||
{
|
||||
"success": False,
|
||||
"message": f"未在插件市场中找到插件: {plugin_id}。请先调用 query_market_plugins 确认 plugin_id。",
|
||||
},
|
||||
ensure_ascii=False,
|
||||
)
|
||||
|
||||
success, message, refreshed_only = await install_plugin_runtime(
|
||||
candidate.id,
|
||||
repo_url,
|
||||
force=force,
|
||||
explicit_source=repo_url is not None,
|
||||
)
|
||||
if not success:
|
||||
source_options = await inspect_plugin_sources(
|
||||
candidate.id,
|
||||
force=False,
|
||||
)
|
||||
if (
|
||||
repo_url is None
|
||||
and source_options["selection_status"] in {
|
||||
"conflict",
|
||||
"incomplete",
|
||||
}
|
||||
):
|
||||
return json.dumps(
|
||||
{
|
||||
"success": False,
|
||||
"plugin": summarize_plugin(candidate),
|
||||
"message": source_options["selection_reason"],
|
||||
"requires_explicit_source": True,
|
||||
"source_candidates": source_options["candidates"],
|
||||
},
|
||||
ensure_ascii=False,
|
||||
indent=2,
|
||||
)
|
||||
return json.dumps(
|
||||
{
|
||||
"success": False,
|
||||
"plugin": summarize_plugin(candidate),
|
||||
"message": message,
|
||||
},
|
||||
ensure_ascii=False,
|
||||
indent=2,
|
||||
)
|
||||
|
||||
plugin_snapshot = get_plugin_snapshot(candidate.id)
|
||||
if refreshed_only and getattr(candidate, "has_update", False) and not force:
|
||||
message = "插件已安装,当前仅刷新加载;如需升级到市场新版本,请设置 force=true"
|
||||
|
||||
return json.dumps(
|
||||
{
|
||||
"success": True,
|
||||
"message": message,
|
||||
"force": force,
|
||||
"refreshed_only": refreshed_only,
|
||||
"plugin": summarize_plugin(candidate),
|
||||
"runtime": plugin_snapshot,
|
||||
},
|
||||
ensure_ascii=False,
|
||||
indent=2,
|
||||
)
|
||||
except Exception as e:
|
||||
logger.error(f"安装插件失败: {e}", exc_info=True)
|
||||
return json.dumps(
|
||||
{"success": False, "message": f"安装插件时发生错误: {str(e)}"},
|
||||
ensure_ascii=False,
|
||||
)
|
||||
@@ -1,194 +0,0 @@
|
||||
"""查询文件系统目录内容工具"""
|
||||
|
||||
import json
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
from typing import Optional, Type
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from app.agent.tools.base import MoviePilotTool
|
||||
from app.agent.tools.tags import ToolTag
|
||||
from app.chain.storage import StorageChain
|
||||
from app.runtime.log import logger
|
||||
from app.schemas.file import FileItem
|
||||
from app.foundation import size as size_tools
|
||||
from app.foundation import text as text_tools
|
||||
|
||||
|
||||
DEFAULT_DIRECTORY_PAGE_SIZE = 50
|
||||
MAX_DIRECTORY_PAGE_SIZE = 200
|
||||
|
||||
|
||||
class ListDirectoryInput(BaseModel):
|
||||
"""查询文件系统目录内容工具的输入参数模型"""
|
||||
path: str = Field(..., description="Directory path to list contents (e.g., '/home/user/downloads' or 'C:/Downloads')")
|
||||
storage: Optional[str] = Field("local", description="Storage type (default: 'local' for local file system, can be 'smb', 'alist', etc.)")
|
||||
sort_by: Optional[str] = Field("name", description="Sort order: 'name' for alphabetical sorting, 'time' for modification time sorting (default: 'name')")
|
||||
limit: Optional[int] = Field(
|
||||
DEFAULT_DIRECTORY_PAGE_SIZE,
|
||||
ge=1,
|
||||
le=MAX_DIRECTORY_PAGE_SIZE,
|
||||
description=(
|
||||
f"Maximum items to return in this page (default: {DEFAULT_DIRECTORY_PAGE_SIZE}, "
|
||||
f"maximum: {MAX_DIRECTORY_PAGE_SIZE})"
|
||||
),
|
||||
)
|
||||
offset: Optional[int] = Field(
|
||||
0,
|
||||
ge=0,
|
||||
description="Number of sorted directory items to skip before this page",
|
||||
)
|
||||
|
||||
|
||||
class ListDirectoryTool(MoviePilotTool):
|
||||
"""分页查询本地或远程存储目录中的文件和子目录。"""
|
||||
|
||||
name: str = "list_directory"
|
||||
tags: list[str] = [
|
||||
ToolTag.Read,
|
||||
ToolTag.Directory,
|
||||
ToolTag.File,
|
||||
]
|
||||
description: str = (
|
||||
"List actual files and folders in a file system directory (NOT configuration). "
|
||||
"Shows files and subdirectories with their names, types, sizes, and modification "
|
||||
f"times. Returns a page of up to {DEFAULT_DIRECTORY_PAGE_SIZE} items with total "
|
||||
f"count and next offset; limit is capped at {MAX_DIRECTORY_PAGE_SIZE}. "
|
||||
"Use 'query_directory_settings' to query directory configuration settings."
|
||||
)
|
||||
args_schema: Type[BaseModel] = ListDirectoryInput
|
||||
|
||||
def get_tool_message(self, **kwargs) -> Optional[str]:
|
||||
"""根据目录参数生成友好的提示消息"""
|
||||
path = kwargs.get("path", "")
|
||||
storage = kwargs.get("storage", "local")
|
||||
|
||||
message = f"查询目录: {path}"
|
||||
if storage != "local":
|
||||
message += f" [存储: {storage}]"
|
||||
|
||||
return message
|
||||
|
||||
@staticmethod
|
||||
def _list_directory_sync(
|
||||
path: str,
|
||||
storage: Optional[str] = "local",
|
||||
sort_by: Optional[str] = "name",
|
||||
limit: Optional[int] = DEFAULT_DIRECTORY_PAGE_SIZE,
|
||||
offset: Optional[int] = 0,
|
||||
) -> str:
|
||||
"""
|
||||
目录遍历可能触发本地磁盘或远程存储请求,统一放到线程池中执行并分页返回。
|
||||
"""
|
||||
if not path:
|
||||
return "错误:路径不能为空"
|
||||
|
||||
if storage == "local":
|
||||
if not path.startswith("/") and not (len(path) > 1 and path[1] == ":"):
|
||||
path = str(Path(path).resolve())
|
||||
elif not path.startswith("/"):
|
||||
path = "/" + path
|
||||
|
||||
fileitem = FileItem(storage=storage or "local", path=path, type="dir")
|
||||
file_list = StorageChain().list_files(fileitem, recursion=False)
|
||||
|
||||
if file_list is None:
|
||||
return f"无法访问目录:{path},请检查路径是否正确或存储是否可用"
|
||||
if sort_by == "time":
|
||||
file_list.sort(key=lambda x: x.modify_time or 0, reverse=True)
|
||||
else:
|
||||
file_list.sort(
|
||||
key=lambda x: (
|
||||
0 if x.type == "dir" else 1,
|
||||
text_tools.natural_sort_key(x.name or ""),
|
||||
)
|
||||
)
|
||||
|
||||
total_count = len(file_list)
|
||||
normalized_limit = max(
|
||||
1,
|
||||
min(int(limit or DEFAULT_DIRECTORY_PAGE_SIZE), MAX_DIRECTORY_PAGE_SIZE),
|
||||
)
|
||||
normalized_offset = max(0, int(offset or 0))
|
||||
limited_list = file_list[
|
||||
normalized_offset : normalized_offset + normalized_limit
|
||||
]
|
||||
simplified_items = []
|
||||
for item in limited_list:
|
||||
size_str = size_tools.format_compact_size(item.size) if item.size else None
|
||||
modify_time_str = None
|
||||
if item.modify_time:
|
||||
try:
|
||||
modify_time_str = datetime.fromtimestamp(item.modify_time).strftime(
|
||||
"%Y-%m-%d %H:%M:%S"
|
||||
)
|
||||
except (ValueError, OSError):
|
||||
modify_time_str = str(item.modify_time)
|
||||
|
||||
simplified = {
|
||||
"name": item.name,
|
||||
"type": item.type,
|
||||
"path": item.path,
|
||||
"size": size_str,
|
||||
"modify_time": modify_time_str,
|
||||
}
|
||||
if item.type == "file" and item.extension:
|
||||
simplified["extension"] = item.extension
|
||||
simplified_items.append(simplified)
|
||||
|
||||
returned_count = len(simplified_items)
|
||||
has_more = normalized_offset + returned_count < total_count
|
||||
return json.dumps(
|
||||
{
|
||||
"items": simplified_items,
|
||||
"total_count": total_count,
|
||||
"returned_count": returned_count,
|
||||
"limit": normalized_limit,
|
||||
"offset": normalized_offset,
|
||||
"has_more": has_more,
|
||||
"next_offset": (
|
||||
normalized_offset + returned_count if has_more else None
|
||||
),
|
||||
},
|
||||
ensure_ascii=False,
|
||||
indent=2,
|
||||
)
|
||||
|
||||
async def run(self, path: str, storage: Optional[str] = "local",
|
||||
sort_by: Optional[str] = "name",
|
||||
limit: Optional[int] = DEFAULT_DIRECTORY_PAGE_SIZE,
|
||||
offset: Optional[int] = 0,
|
||||
**kwargs) -> str:
|
||||
"""
|
||||
分页查询指定目录的文件和子目录。
|
||||
|
||||
:param path: 要查询的目录路径
|
||||
:param storage: 存储类型,默认为本地存储
|
||||
:param sort_by: 排序方式,支持名称或修改时间
|
||||
:param limit: 当前页最大条数,最高不超过工具上限
|
||||
:param offset: 当前页起始偏移量
|
||||
:return: 包含项目列表和分页元数据的 JSON 字符串
|
||||
"""
|
||||
logger.info(f"执行工具: {self.name}, 参数: path={path}, storage={storage}, sort_by={sort_by}")
|
||||
|
||||
try:
|
||||
resolved_path, access_error = await self._check_local_storage_access(
|
||||
path=path, storage=storage, operation="列出"
|
||||
)
|
||||
if access_error:
|
||||
return access_error
|
||||
if resolved_path:
|
||||
path = str(resolved_path)
|
||||
return await self.run_blocking(
|
||||
"storage",
|
||||
self._list_directory_sync,
|
||||
path,
|
||||
storage,
|
||||
sort_by,
|
||||
limit,
|
||||
offset,
|
||||
)
|
||||
except Exception as e:
|
||||
logger.error(f"查询目录内容失败: {e}", exc_info=True)
|
||||
return f"查询目录内容时发生错误: {str(e)}"
|
||||
@@ -1,79 +0,0 @@
|
||||
"""查询所有可用斜杠命令工具(系统命令 + 插件命令)"""
|
||||
|
||||
import json
|
||||
from typing import Optional, Type
|
||||
|
||||
from pydantic import BaseModel
|
||||
|
||||
from app.agent.tools.base import MoviePilotTool
|
||||
from app.agent.tools.tags import ToolTag
|
||||
from app.runtime.log import logger
|
||||
|
||||
|
||||
class ListSlashCommandsInput(BaseModel):
|
||||
"""查询所有可用斜杠命令工具的输入参数模型"""
|
||||
|
||||
|
||||
class ListSlashCommandsTool(MoviePilotTool):
|
||||
name: str = "list_slash_commands"
|
||||
tags: list[str] = [
|
||||
ToolTag.Read,
|
||||
ToolTag.SlashCommand,
|
||||
ToolTag.Admin,
|
||||
]
|
||||
description: str = (
|
||||
"List all available slash commands in the system, including system preset commands "
|
||||
"(e.g. /cookiecloud, /sites, /subscribes, /downloading, /transfer, /restart, etc.) "
|
||||
"and plugin-registered commands. "
|
||||
"Use this tool to discover what slash commands are available before executing them with run_slash_command. "
|
||||
"This is especially useful when the user describes an action in natural language and you need to "
|
||||
"find the matching command to fulfill their request."
|
||||
)
|
||||
args_schema: Type[BaseModel] = ListSlashCommandsInput
|
||||
require_admin: bool = True
|
||||
|
||||
def get_tool_message(self, **kwargs) -> Optional[str]:
|
||||
"""生成友好的提示消息"""
|
||||
return "查询所有可用命令"
|
||||
|
||||
async def run(self, **kwargs) -> str:
|
||||
logger.info(f"执行工具: {self.name}")
|
||||
|
||||
try:
|
||||
from app.application.commands import get_commands
|
||||
|
||||
all_commands = get_commands()
|
||||
|
||||
if not all_commands:
|
||||
return "当前没有可用的命令"
|
||||
|
||||
commands_list = []
|
||||
for cmd, info in all_commands.items():
|
||||
cmd_info = {
|
||||
"command": cmd,
|
||||
"description": info.get("description", ""),
|
||||
}
|
||||
if info.get("category"):
|
||||
cmd_info["category"] = info["category"]
|
||||
# 标识命令类型
|
||||
if info.get("type") == "scheduler":
|
||||
cmd_info["type"] = "scheduler"
|
||||
elif info.get("pid"):
|
||||
cmd_info["type"] = "plugin"
|
||||
cmd_info["plugin_id"] = info["pid"]
|
||||
else:
|
||||
cmd_info["type"] = "system"
|
||||
commands_list.append(cmd_info)
|
||||
|
||||
result = {
|
||||
"total": len(commands_list),
|
||||
"commands": commands_list,
|
||||
}
|
||||
return json.dumps(result, ensure_ascii=False, indent=2)
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"查询可用命令失败: {e}", exc_info=True)
|
||||
return json.dumps(
|
||||
{"success": False, "message": f"查询可用命令时发生错误: {str(e)}"},
|
||||
ensure_ascii=False,
|
||||
)
|
||||
@@ -30,8 +30,7 @@ class McpExternalTool(MoviePilotTool):
|
||||
session_id=session_id,
|
||||
user_id=user_id,
|
||||
name=spec.agent_tool_name,
|
||||
description=spec.description
|
||||
or f"Call external MCP tool {spec.name} on {spec.server.name}.",
|
||||
description=spec.description or f"Call external MCP tool {spec.name} on {spec.server.name}.",
|
||||
args_schema=spec.input_schema,
|
||||
require_admin=spec.server.require_admin,
|
||||
)
|
||||
@@ -127,17 +126,3 @@ async def create_external_mcp_tools(
|
||||
)
|
||||
tools.append(tool)
|
||||
return tools
|
||||
|
||||
|
||||
def select_legacy_mcp_tools(
|
||||
tools: list[McpExternalTool],
|
||||
) -> list[McpExternalTool]:
|
||||
"""保留跨服务器同名工具历史上的 first-wins 执行顺序。"""
|
||||
selected = []
|
||||
seen_names = set()
|
||||
for tool in tools:
|
||||
if tool.name in seen_names:
|
||||
continue
|
||||
selected.append(tool)
|
||||
seen_names.add(tool.name)
|
||||
return selected
|
||||
|
||||
232
app/agent/tools/impl/persona.py
Normal file
232
app/agent/tools/impl/persona.py
Normal file
@@ -0,0 +1,232 @@
|
||||
"""Agent 人格统一管理工具。"""
|
||||
|
||||
import json
|
||||
from typing import Literal, Optional, Type
|
||||
|
||||
from pydantic import BaseModel, Field, model_validator
|
||||
|
||||
from app.agent.runtime import agent_runtime_manager
|
||||
from app.agent.tools.base import MoviePilotTool
|
||||
from app.agent.tools.tags import ToolTag
|
||||
from app.runtime.log import logger
|
||||
|
||||
PersonaAction = Literal["list", "switch", "update"]
|
||||
|
||||
|
||||
class PersonaInput(BaseModel):
|
||||
"""查询、切换或更新 Agent 人格的统一输入参数。"""
|
||||
|
||||
action: PersonaAction = Field(
|
||||
...,
|
||||
description="Action to perform: list, switch, or update.",
|
||||
)
|
||||
query: Optional[str] = Field(
|
||||
None,
|
||||
description=("Optional list filter for persona_id, label, description, or aliases."),
|
||||
)
|
||||
persona_id: Optional[str] = Field(
|
||||
None,
|
||||
description=(
|
||||
"Target persona for switch or update. Existing labels and aliases are "
|
||||
"accepted; new personas require a lowercase persona_id."
|
||||
),
|
||||
)
|
||||
label: Optional[str] = Field(None, description="Replacement display label.")
|
||||
description: Optional[str] = Field(
|
||||
None,
|
||||
description="Replacement description of the intended persona style.",
|
||||
)
|
||||
aliases: Optional[list[str]] = Field(
|
||||
None,
|
||||
description="Full replacement list of persona aliases.",
|
||||
)
|
||||
instructions: Optional[str] = Field(
|
||||
None,
|
||||
description="Full replacement PERSONA.md body without YAML frontmatter.",
|
||||
)
|
||||
append_instructions: Optional[list[str]] = Field(
|
||||
None,
|
||||
description="Additional persona rules appended to the existing body.",
|
||||
)
|
||||
create_if_missing: bool = Field(
|
||||
False,
|
||||
description="Create a new runtime persona when update cannot resolve one.",
|
||||
)
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_action(self) -> "PersonaInput":
|
||||
"""按动作校验目标人格和更新字段。"""
|
||||
if self.query is not None:
|
||||
self.query = self.query.strip() or None
|
||||
if self.persona_id is not None:
|
||||
self.persona_id = self.persona_id.strip()
|
||||
if self.action in {"switch", "update"} and not self.persona_id:
|
||||
raise ValueError(f"{self.action} 必须提供 persona_id")
|
||||
if self.action == "update" and not any(
|
||||
value is not None
|
||||
for value in (
|
||||
self.label,
|
||||
self.description,
|
||||
self.aliases,
|
||||
self.instructions,
|
||||
self.append_instructions,
|
||||
)
|
||||
):
|
||||
raise ValueError("update 必须提供至少一个人格定义字段")
|
||||
return self
|
||||
|
||||
|
||||
class PersonaTool(MoviePilotTool):
|
||||
"""通过一个动作式接口查询、切换或管理 Agent 人格。"""
|
||||
|
||||
name: str = "persona"
|
||||
tags: list[str] = [ToolTag.Read, ToolTag.Write, ToolTag.Persona]
|
||||
description: str = (
|
||||
"Manage agent personas with one structured action. Use list to discover personas "
|
||||
"and the active state, switch when the user explicitly requests a speaking style, "
|
||||
"and update only for an explicit administrator request to create or rewrite a "
|
||||
"persona definition."
|
||||
)
|
||||
args_schema: Type[BaseModel] = PersonaInput
|
||||
|
||||
def get_tool_message(self, **kwargs: object) -> str:
|
||||
"""生成统一人格操作的用户可见提示。"""
|
||||
action = str(kwargs.get("action") or "list")
|
||||
action_name = {
|
||||
"list": "查询人格",
|
||||
"switch": "切换人格",
|
||||
"update": "更新人格定义",
|
||||
}.get(action, action)
|
||||
target = kwargs.get("persona_id") or kwargs.get("query")
|
||||
return f"{action_name}: {target}" if target else action_name
|
||||
|
||||
async def run(
|
||||
self,
|
||||
action: PersonaAction,
|
||||
query: Optional[str] = None,
|
||||
persona_id: Optional[str] = None,
|
||||
label: Optional[str] = None,
|
||||
description: Optional[str] = None,
|
||||
aliases: Optional[list[str]] = None,
|
||||
instructions: Optional[str] = None,
|
||||
append_instructions: Optional[list[str]] = None,
|
||||
create_if_missing: bool = False,
|
||||
**kwargs: object,
|
||||
) -> str:
|
||||
"""执行查询、切换或更新人格定义。"""
|
||||
payload = PersonaInput(
|
||||
action=action,
|
||||
query=query,
|
||||
persona_id=persona_id,
|
||||
label=label,
|
||||
description=description,
|
||||
aliases=aliases,
|
||||
instructions=instructions,
|
||||
append_instructions=append_instructions,
|
||||
create_if_missing=create_if_missing,
|
||||
)
|
||||
logger.info(
|
||||
"执行工具: %s, 参数: action=%s, persona_id=%s",
|
||||
self.name,
|
||||
payload.action,
|
||||
payload.persona_id,
|
||||
)
|
||||
try:
|
||||
if payload.action == "list":
|
||||
return self._list_personas(payload.query)
|
||||
if payload.action == "switch":
|
||||
return self._switch_persona(payload.persona_id)
|
||||
if not await self.is_admin_user():
|
||||
return json.dumps(
|
||||
{
|
||||
"success": False,
|
||||
"message": "只有系统管理员才能更新人格定义。",
|
||||
},
|
||||
ensure_ascii=False,
|
||||
)
|
||||
return self._update_persona(payload)
|
||||
except Exception as error: # noqa: BLE001
|
||||
logger.error(
|
||||
"人格操作失败: action=%s, error=%s",
|
||||
payload.action,
|
||||
error,
|
||||
exc_info=True,
|
||||
)
|
||||
return json.dumps(
|
||||
{
|
||||
"success": False,
|
||||
"message": f"人格操作失败: {str(error)}",
|
||||
},
|
||||
ensure_ascii=False,
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def _list_personas(query: Optional[str]) -> str:
|
||||
"""列出可用人格并按可选关键词过滤。"""
|
||||
runtime_config = agent_runtime_manager.load_runtime_config()
|
||||
personas = runtime_config.list_personas()
|
||||
if query:
|
||||
normalized = query.casefold()
|
||||
personas = [
|
||||
persona
|
||||
for persona in personas
|
||||
if normalized in persona["persona_id"].casefold()
|
||||
or normalized in persona["label"].casefold()
|
||||
or normalized in persona["description"].casefold()
|
||||
or any(normalized in alias.casefold() for alias in persona["aliases"])
|
||||
]
|
||||
return json.dumps(
|
||||
{
|
||||
"active_persona": runtime_config.active_persona,
|
||||
"count": len(personas),
|
||||
"personas": personas,
|
||||
},
|
||||
ensure_ascii=False,
|
||||
indent=2,
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def _switch_persona(persona_id: Optional[str]) -> str:
|
||||
"""切换当前持久化激活人格。"""
|
||||
if persona_id is None:
|
||||
raise ValueError("switch 缺少 persona_id")
|
||||
runtime_config = agent_runtime_manager.set_active_persona(persona_id)
|
||||
return json.dumps(
|
||||
{
|
||||
"success": True,
|
||||
"active_persona": runtime_config.active_persona,
|
||||
"persona": runtime_config.persona.to_dict(is_active=True),
|
||||
"message": f"已切换为人格 `{runtime_config.active_persona}`",
|
||||
},
|
||||
ensure_ascii=False,
|
||||
indent=2,
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def _update_persona(payload: PersonaInput) -> str:
|
||||
"""创建或更新一项运行时人格定义。"""
|
||||
if payload.persona_id is None:
|
||||
raise ValueError("update 缺少 persona_id")
|
||||
persona, created = agent_runtime_manager.update_persona_definition(
|
||||
payload.persona_id,
|
||||
label=payload.label,
|
||||
description=payload.description,
|
||||
aliases=payload.aliases,
|
||||
instructions=payload.instructions,
|
||||
append_instructions=payload.append_instructions,
|
||||
create_if_missing=payload.create_if_missing,
|
||||
)
|
||||
runtime_config = agent_runtime_manager.load_runtime_config()
|
||||
return json.dumps(
|
||||
{
|
||||
"success": True,
|
||||
"created": created,
|
||||
"active_persona": runtime_config.active_persona,
|
||||
"persona": persona.to_dict(is_active=persona.persona_id == runtime_config.active_persona),
|
||||
"message": (
|
||||
f"已创建人格 `{persona.persona_id}`" if created else f"已更新人格 `{persona.persona_id}` 的定义"
|
||||
),
|
||||
},
|
||||
ensure_ascii=False,
|
||||
indent=2,
|
||||
)
|
||||
@@ -1,96 +0,0 @@
|
||||
import json
|
||||
from typing import Optional, Type
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from app.agent.tools.base import MoviePilotTool
|
||||
from app.agent.tools.tags import ToolTag
|
||||
from app.application.agenttask import agent_task_run_to_dict, agent_task_to_dict
|
||||
from app.runtime.settings import get_runtime_setting
|
||||
|
||||
|
||||
class QueryAgentTasksInput(BaseModel):
|
||||
"""查询 Agent 自主定时任务的输入参数。"""
|
||||
|
||||
task_id: Optional[int] = Field(
|
||||
None,
|
||||
ge=1,
|
||||
description="Optional task ID. Omit it to list tasks owned by the current user.",
|
||||
)
|
||||
enabled: Optional[bool] = Field(
|
||||
None,
|
||||
description="Optional enabled-state filter used when listing tasks.",
|
||||
)
|
||||
|
||||
|
||||
class QueryAgentTasksTool(MoviePilotTool):
|
||||
"""查询当前用户创建的 Agent 自主定时任务。"""
|
||||
|
||||
name: str = "query_agent_tasks"
|
||||
tags: list[str] = [ToolTag.Read, ToolTag.AgentTask, ToolTag.Admin]
|
||||
description: str = (
|
||||
"Query persistent autonomous agent tasks owned by the current user, including "
|
||||
"reminders, monitoring tasks, and recurring agent work. Returns the integer "
|
||||
"task_id, instructions, trigger, enabled state, next run time, and latest result. "
|
||||
"Do not use this for MoviePilot system, plugin, or workflow scheduler services."
|
||||
)
|
||||
args_schema: Type[BaseModel] = QueryAgentTasksInput
|
||||
require_admin: bool = True
|
||||
|
||||
def get_tool_message(self, **kwargs: object) -> Optional[str]:
|
||||
"""生成查询定时任务的提示消息。"""
|
||||
task_id = kwargs.get("task_id")
|
||||
return f"查询自主定时任务:{task_id}" if task_id else "查询自主定时任务"
|
||||
|
||||
def _query_tasks(
|
||||
self,
|
||||
task_id: Optional[int],
|
||||
enabled: Optional[bool],
|
||||
) -> list[dict[str, object]]:
|
||||
"""读取当前用户的任务及运行时下一次触发时间。"""
|
||||
from app.application.scheduling import get_agent_task_next_run
|
||||
|
||||
oper = self.data.tasks
|
||||
if task_id:
|
||||
task = oper.get(task_id=task_id, user_id=str(self._user_id))
|
||||
tasks = [task] if task else []
|
||||
else:
|
||||
tasks = oper.list(user_id=str(self._user_id), enabled=enabled)
|
||||
result: list[dict[str, object]] = []
|
||||
for task in tasks:
|
||||
data = agent_task_to_dict(
|
||||
task,
|
||||
next_run_at=get_agent_task_next_run(task.id),
|
||||
timezone=get_runtime_setting('TZ'),
|
||||
)
|
||||
if task_id:
|
||||
data["recent_runs"] = [
|
||||
agent_task_run_to_dict(run)
|
||||
for run in oper.list_runs(
|
||||
task_id=task.id,
|
||||
user_id=str(self._user_id),
|
||||
limit=10,
|
||||
)
|
||||
]
|
||||
result.append(data)
|
||||
return result
|
||||
|
||||
async def run(
|
||||
self,
|
||||
task_id: Optional[int] = None,
|
||||
enabled: Optional[bool] = None,
|
||||
**kwargs: object,
|
||||
) -> str:
|
||||
"""查询 Agent 自主定时任务。"""
|
||||
payload = QueryAgentTasksInput(task_id=task_id, enabled=enabled)
|
||||
tasks = await self.run_blocking(
|
||||
"db",
|
||||
self._query_tasks,
|
||||
payload.task_id,
|
||||
payload.enabled,
|
||||
)
|
||||
return json.dumps(
|
||||
{"total": len(tasks), "tasks": tasks},
|
||||
ensure_ascii=False,
|
||||
indent=2,
|
||||
)
|
||||
@@ -1,86 +0,0 @@
|
||||
"""查询内置过滤规则工具。"""
|
||||
|
||||
import json
|
||||
from typing import Optional, Type, List
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from app.agent.tools.base import MoviePilotTool
|
||||
from app.agent.tools.tags import ToolTag
|
||||
from app.agent.tools.impl._filter_rule_utils import (
|
||||
get_builtin_rules,
|
||||
serialize_builtin_rule,
|
||||
RULE_STRING_SYNTAX,
|
||||
)
|
||||
from app.runtime.log import logger
|
||||
|
||||
|
||||
class QueryBuiltinFilterRulesInput(BaseModel):
|
||||
"""查询内置过滤规则工具的输入参数模型"""
|
||||
|
||||
rule_ids: Optional[List[str]] = Field(
|
||||
None,
|
||||
description="Optional list of built-in rule IDs to query. If omitted, return all built-in rules.",
|
||||
)
|
||||
|
||||
|
||||
class QueryBuiltinFilterRulesTool(MoviePilotTool):
|
||||
name: str = "query_builtin_filter_rules"
|
||||
tags: list[str] = [
|
||||
ToolTag.Read,
|
||||
ToolTag.FilterRule,
|
||||
]
|
||||
description: str = (
|
||||
"Query built-in filter rules defined by the backend filter module. "
|
||||
"These rule IDs can be used directly inside rule_string expressions for filter rule groups. "
|
||||
"Use this tool before add_rule_group or update_rule_group to learn valid built-in rule IDs."
|
||||
)
|
||||
args_schema: Type[BaseModel] = QueryBuiltinFilterRulesInput
|
||||
|
||||
def get_tool_message(self, **kwargs) -> Optional[str]:
|
||||
rule_ids = kwargs.get("rule_ids") or []
|
||||
if rule_ids:
|
||||
return f"查询内置过滤规则: {', '.join(rule_ids)}"
|
||||
return "查询所有内置过滤规则"
|
||||
|
||||
async def run(
|
||||
self,
|
||||
rule_ids: Optional[List[str]] = None,
|
||||
**kwargs,
|
||||
) -> str:
|
||||
logger.info(f"执行工具: {self.name}")
|
||||
|
||||
try:
|
||||
builtin_rules = get_builtin_rules()
|
||||
if rule_ids:
|
||||
target_ids = set(rule_ids)
|
||||
builtin_rules = {
|
||||
rule_id: payload
|
||||
for rule_id, payload in builtin_rules.items()
|
||||
if rule_id in target_ids
|
||||
}
|
||||
|
||||
serialized = [
|
||||
serialize_builtin_rule(rule_id, payload)
|
||||
for rule_id, payload in builtin_rules.items()
|
||||
]
|
||||
return json.dumps(
|
||||
{
|
||||
"success": True,
|
||||
"count": len(serialized),
|
||||
"rule_string_syntax": RULE_STRING_SYNTAX,
|
||||
"rules": serialized,
|
||||
},
|
||||
ensure_ascii=False,
|
||||
indent=2,
|
||||
)
|
||||
except Exception as exc:
|
||||
logger.error(f"查询内置过滤规则失败: {exc}", exc_info=True)
|
||||
return json.dumps(
|
||||
{
|
||||
"success": False,
|
||||
"message": f"查询内置过滤规则失败: {exc}",
|
||||
"rules": [],
|
||||
},
|
||||
ensure_ascii=False,
|
||||
)
|
||||
@@ -1,96 +0,0 @@
|
||||
"""查询自定义过滤规则工具。"""
|
||||
|
||||
import json
|
||||
from typing import Optional, Type, List
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from app.agent.tools.base import MoviePilotTool
|
||||
from app.agent.tools.tags import ToolTag
|
||||
from app.agent.tools.impl._filter_rule_utils import (
|
||||
collect_custom_rule_group_refs,
|
||||
get_custom_rules,
|
||||
get_rule_groups,
|
||||
serialize_custom_rule,
|
||||
)
|
||||
from app.runtime.log import logger
|
||||
|
||||
|
||||
class QueryCustomFilterRulesInput(BaseModel):
|
||||
"""查询自定义过滤规则工具的输入参数模型"""
|
||||
|
||||
rule_ids: Optional[List[str]] = Field(
|
||||
None,
|
||||
description="Optional list of custom rule IDs to query. If omitted, return all custom rules.",
|
||||
)
|
||||
include_group_refs: bool = Field(
|
||||
True,
|
||||
description="Whether to include which rule groups reference each custom rule.",
|
||||
)
|
||||
|
||||
|
||||
class QueryCustomFilterRulesTool(MoviePilotTool):
|
||||
name: str = "query_custom_filter_rules"
|
||||
tags: list[str] = [
|
||||
ToolTag.Read,
|
||||
ToolTag.FilterRule,
|
||||
]
|
||||
description: str = (
|
||||
"Query custom filter rules stored in CustomFilterRules. "
|
||||
"Custom rules can be referenced from rule_string expressions in filter rule groups. "
|
||||
"Use this tool before add_rule_group or update_rule_group to learn valid custom rule IDs."
|
||||
)
|
||||
args_schema: Type[BaseModel] = QueryCustomFilterRulesInput
|
||||
|
||||
def get_tool_message(self, **kwargs) -> Optional[str]:
|
||||
rule_ids = kwargs.get("rule_ids") or []
|
||||
if rule_ids:
|
||||
return f"查询自定义过滤规则: {', '.join(rule_ids)}"
|
||||
return "查询所有自定义过滤规则"
|
||||
|
||||
async def run(
|
||||
self,
|
||||
rule_ids: Optional[List[str]] = None,
|
||||
include_group_refs: bool = True,
|
||||
**kwargs,
|
||||
) -> str:
|
||||
logger.info(f"执行工具: {self.name}")
|
||||
|
||||
try:
|
||||
custom_rules = get_custom_rules()
|
||||
if rule_ids:
|
||||
target_ids = set(rule_ids)
|
||||
custom_rules = [
|
||||
rule for rule in custom_rules if rule.id in target_ids
|
||||
]
|
||||
|
||||
refs = {}
|
||||
if include_group_refs:
|
||||
refs = collect_custom_rule_group_refs(
|
||||
get_rule_groups(),
|
||||
[rule.id for rule in custom_rules if rule.id],
|
||||
)
|
||||
|
||||
serialized = [
|
||||
serialize_custom_rule(rule, refs.get(rule.id))
|
||||
for rule in custom_rules
|
||||
]
|
||||
return json.dumps(
|
||||
{
|
||||
"success": True,
|
||||
"count": len(serialized),
|
||||
"rules": serialized,
|
||||
},
|
||||
ensure_ascii=False,
|
||||
indent=2,
|
||||
)
|
||||
except Exception as exc:
|
||||
logger.error(f"查询自定义过滤规则失败: {exc}", exc_info=True)
|
||||
return json.dumps(
|
||||
{
|
||||
"success": False,
|
||||
"message": f"查询自定义过滤规则失败: {exc}",
|
||||
"rules": [],
|
||||
},
|
||||
ensure_ascii=False,
|
||||
)
|
||||
@@ -1,73 +0,0 @@
|
||||
"""查询自定义识别词工具"""
|
||||
|
||||
import json
|
||||
from typing import Optional, Type
|
||||
|
||||
from pydantic import BaseModel
|
||||
|
||||
from app.agent.tools.base import MoviePilotTool
|
||||
from app.agent.tools.tags import ToolTag
|
||||
from app.application.configuration import get_configured_system_config
|
||||
from app.runtime.log import logger
|
||||
from app.schemas.types import SystemConfigKey
|
||||
|
||||
|
||||
class QueryCustomIdentifiersInput(BaseModel):
|
||||
"""查询自定义识别词工具的输入参数模型"""
|
||||
|
||||
|
||||
|
||||
class QueryCustomIdentifiersTool(MoviePilotTool):
|
||||
name: str = "query_custom_identifiers"
|
||||
tags: list[str] = [
|
||||
ToolTag.Read,
|
||||
ToolTag.FilterRule,
|
||||
ToolTag.Admin,
|
||||
]
|
||||
description: str = (
|
||||
"Query all currently configured custom identifiers (自定义识别词). "
|
||||
"Returns the list of identifier rules used for preprocessing torrent/file names before media recognition. "
|
||||
"Use this tool to check existing rules before adding new ones to avoid duplicates."
|
||||
)
|
||||
require_admin: bool = True
|
||||
args_schema: Type[BaseModel] = QueryCustomIdentifiersInput
|
||||
|
||||
def get_tool_message(self, **kwargs) -> Optional[str]:
|
||||
"""生成友好的提示消息"""
|
||||
return "查询自定义识别词"
|
||||
|
||||
@staticmethod
|
||||
def _load_custom_identifiers():
|
||||
"""从内存配置缓存中读取自定义识别词。"""
|
||||
return get_configured_system_config().get(SystemConfigKey.CustomIdentifiers)
|
||||
|
||||
async def run(self, **kwargs) -> str:
|
||||
logger.info(f"执行工具: {self.name}")
|
||||
try:
|
||||
identifiers = self._load_custom_identifiers()
|
||||
if identifiers:
|
||||
return json.dumps(
|
||||
{
|
||||
"success": True,
|
||||
"count": len(identifiers),
|
||||
"identifiers": identifiers,
|
||||
},
|
||||
ensure_ascii=False,
|
||||
indent=2,
|
||||
)
|
||||
return json.dumps(
|
||||
{
|
||||
"success": True,
|
||||
"count": 0,
|
||||
"identifiers": [],
|
||||
"message": "当前没有配置自定义识别词",
|
||||
},
|
||||
ensure_ascii=False,
|
||||
indent=2,
|
||||
)
|
||||
except Exception as e:
|
||||
logger.error(f"查询自定义识别词失败: {e}")
|
||||
return json.dumps(
|
||||
{"success": False, "message": f"查询自定义识别词时发生错误: {str(e)}"},
|
||||
ensure_ascii=False,
|
||||
)
|
||||
@@ -1,146 +0,0 @@
|
||||
"""查询系统目录设置工具"""
|
||||
|
||||
import json
|
||||
from typing import Optional, Type
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from app.agent.tools.base import MoviePilotTool
|
||||
from app.agent.tools.tags import ToolTag
|
||||
from app.application.directory import DirectoryHelper
|
||||
from app.runtime.log import logger
|
||||
|
||||
|
||||
class QueryDirectorySettingsInput(BaseModel):
|
||||
"""查询系统目录设置工具的输入参数模型"""
|
||||
directory_type: Optional[str] = Field("all",
|
||||
description="Filter directories by type: 'download' for download directories, 'library' for media library directories, 'all' for all directories")
|
||||
storage_type: Optional[str] = Field("all",
|
||||
description="Filter directories by storage type: 'local' for local storage, 'remote' for remote storage, 'all' for all storage types")
|
||||
name: Optional[str] = Field(None,
|
||||
description="Filter directories by name (partial match, optional)")
|
||||
|
||||
|
||||
class QueryDirectorySettingsTool(MoviePilotTool):
|
||||
name: str = "query_directory_settings"
|
||||
tags: list[str] = [
|
||||
ToolTag.Read,
|
||||
ToolTag.Directory,
|
||||
ToolTag.Settings,
|
||||
ToolTag.Admin,
|
||||
]
|
||||
description: str = "Query system directory configuration settings (NOT file listings). Returns configured directory paths, storage types, transfer modes, and other directory-related settings. Use 'list_directory' to list actual files and folders in a directory."
|
||||
require_admin: bool = True
|
||||
args_schema: Type[BaseModel] = QueryDirectorySettingsInput
|
||||
|
||||
def get_tool_message(self, **kwargs) -> Optional[str]:
|
||||
"""根据查询参数生成友好的提示消息"""
|
||||
directory_type = kwargs.get("directory_type", "all")
|
||||
storage_type = kwargs.get("storage_type", "all")
|
||||
name = kwargs.get("name")
|
||||
|
||||
parts = ["查询目录配置"]
|
||||
|
||||
if directory_type != "all":
|
||||
type_map = {"download": "下载目录", "library": "媒体库目录"}
|
||||
parts.append(f"类型: {type_map.get(directory_type, directory_type)}")
|
||||
|
||||
if storage_type != "all":
|
||||
storage_map = {"local": "本地存储", "remote": "远程存储"}
|
||||
parts.append(f"存储: {storage_map.get(storage_type, storage_type)}")
|
||||
|
||||
if name:
|
||||
parts.append(f"名称: {name}")
|
||||
|
||||
return " | ".join(parts) if len(parts) > 1 else parts[0]
|
||||
|
||||
@staticmethod
|
||||
def _query_directory_settings(
|
||||
directory_type: Optional[str] = "all",
|
||||
storage_type: Optional[str] = "all",
|
||||
name: Optional[str] = None,
|
||||
) -> str:
|
||||
"""
|
||||
目录配置完全来自内存配置缓存,这里只做本地过滤和序列化。
|
||||
"""
|
||||
directory_helper = DirectoryHelper()
|
||||
|
||||
if directory_type == "download":
|
||||
dirs = directory_helper.get_download_dirs()
|
||||
elif directory_type == "library":
|
||||
dirs = directory_helper.get_library_dirs()
|
||||
else:
|
||||
dirs = directory_helper.get_dirs()
|
||||
|
||||
filtered_dirs = []
|
||||
for d in dirs:
|
||||
if storage_type == "local":
|
||||
if directory_type == "download" and d.storage != "local":
|
||||
continue
|
||||
if directory_type == "library" and d.library_storage != "local":
|
||||
continue
|
||||
if directory_type == "all":
|
||||
if d.download_path and d.storage != "local":
|
||||
continue
|
||||
if d.library_path and d.library_storage != "local":
|
||||
continue
|
||||
elif storage_type == "remote":
|
||||
if directory_type == "download" and d.storage == "local":
|
||||
continue
|
||||
if directory_type == "library" and d.library_storage == "local":
|
||||
continue
|
||||
if directory_type == "all":
|
||||
if d.download_path and d.storage == "local":
|
||||
continue
|
||||
if d.library_path and d.library_storage == "local":
|
||||
continue
|
||||
|
||||
if name and d.name and name.lower() not in d.name.lower():
|
||||
continue
|
||||
filtered_dirs.append(d)
|
||||
|
||||
if not filtered_dirs:
|
||||
return "未找到相关目录配置"
|
||||
|
||||
simplified_dirs = []
|
||||
for d in filtered_dirs:
|
||||
simplified_dirs.append(
|
||||
{
|
||||
"name": d.name,
|
||||
"priority": d.priority,
|
||||
"storage": d.storage,
|
||||
"download_path": d.download_path,
|
||||
"library_path": d.library_path,
|
||||
"library_storage": d.library_storage,
|
||||
"media_type": d.media_type,
|
||||
"media_category": d.media_category,
|
||||
"monitor_type": d.monitor_type,
|
||||
"monitor_mode": d.monitor_mode,
|
||||
"transfer_type": d.transfer_type,
|
||||
"overwrite_mode": d.overwrite_mode,
|
||||
"renaming": d.renaming,
|
||||
"scraping": d.scraping,
|
||||
"notify": d.notify,
|
||||
"download_type_folder": d.download_type_folder,
|
||||
"download_category_folder": d.download_category_folder,
|
||||
"library_type_folder": d.library_type_folder,
|
||||
"library_category_folder": d.library_category_folder,
|
||||
}
|
||||
)
|
||||
|
||||
return json.dumps(simplified_dirs, ensure_ascii=False, indent=2)
|
||||
|
||||
async def run(self, directory_type: Optional[str] = "all",
|
||||
storage_type: Optional[str] = "all",
|
||||
name: Optional[str] = None, **kwargs) -> str:
|
||||
logger.info(f"执行工具: {self.name}, 参数: directory_type={directory_type}, storage_type={storage_type}, name={name}")
|
||||
|
||||
try:
|
||||
return self._query_directory_settings(
|
||||
directory_type=directory_type,
|
||||
storage_type=storage_type,
|
||||
name=name,
|
||||
)
|
||||
except Exception as e:
|
||||
logger.error(f"查询系统目录设置失败: {e}", exc_info=True)
|
||||
return f"查询系统目录设置时发生错误: {str(e)}"
|
||||
@@ -1,415 +0,0 @@
|
||||
"""查询下载工具"""
|
||||
|
||||
import json
|
||||
from typing import Any, Dict, List, Optional, Type
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from app.agent.tools.base import MoviePilotTool
|
||||
from app.agent.tools.tags import ToolTag
|
||||
from app.application.history import DownloadHistorySnapshot
|
||||
from app.chain.download import DownloadChain
|
||||
from app.runtime.log import logger
|
||||
from app.schemas.common import JsonData
|
||||
from app.schemas.transfer import DownloaderTorrent, DownloadTaskMedia
|
||||
from app.schemas.types import MUSIC_ENTITY_RECORDING, TorrentQueryStatus, media_type_to_agent
|
||||
|
||||
|
||||
class QueryDownloadTasksInput(BaseModel):
|
||||
"""查询下载工具的输入参数模型"""
|
||||
downloader: Optional[str] = Field(None,
|
||||
description="Name of specific downloader to query (optional, if not provided queries all configured downloaders)")
|
||||
status: Optional[str] = Field("all",
|
||||
description="Filter downloads by status: 'downloading' for active downloads, 'completed' for finished downloads, 'paused' for paused downloads, 'all' for all downloads")
|
||||
include_all_tags: Optional[bool] = Field(
|
||||
False,
|
||||
description="Include tasks without the MoviePilot built-in tag. Default false keeps the normal MoviePilot task scope.",
|
||||
)
|
||||
include_trackers: Optional[bool] = Field(
|
||||
False,
|
||||
description="Include tracker URLs when supported. Hash queries always include trackers.",
|
||||
)
|
||||
hash: Optional[str] = Field(None, description="Query specific download task by hash (optional, if provided will search for this specific task regardless of status)")
|
||||
title: Optional[str] = Field(None, description="Query download tasks by title/name (optional, supports partial match, searches all tasks if provided)")
|
||||
tag: Optional[str] = Field(None, description="Filter download tasks by tag (optional, supports partial match, e.g. 'movie' will match tasks with tag 'movie' or 'movie_2024')")
|
||||
|
||||
|
||||
class QueryDownloadTasksTool(MoviePilotTool):
|
||||
"""查询下载器任务并用下载历史补全影视或音乐身份。"""
|
||||
|
||||
name: str = "query_download_tasks"
|
||||
tags: list[str] = [
|
||||
ToolTag.Read,
|
||||
ToolTag.Download,
|
||||
]
|
||||
description: str = "Query download status and list download tasks. Can query all active downloads, or search for specific tasks by hash, title, or tag. Shows download progress, completion status, tags, and task details from configured downloaders."
|
||||
args_schema: Type[BaseModel] = QueryDownloadTasksInput
|
||||
|
||||
@staticmethod
|
||||
def _normalize_query_status(status: Optional[str]) -> TorrentQueryStatus:
|
||||
"""
|
||||
归一下载任务查询状态。
|
||||
"""
|
||||
status_value = str(status or "").strip().lower()
|
||||
if not status_value or status_value == TorrentQueryStatus.ALL.value:
|
||||
return TorrentQueryStatus.ALL
|
||||
if status_value in {"completed", "complete", "seeding"}:
|
||||
return TorrentQueryStatus.COMPLETED
|
||||
if status_value in {"paused", "pause"}:
|
||||
return TorrentQueryStatus.PAUSED
|
||||
if status_value == TorrentQueryStatus.DOWNLOADING.value:
|
||||
return TorrentQueryStatus.DOWNLOADING
|
||||
return TorrentQueryStatus.ALL
|
||||
|
||||
@staticmethod
|
||||
def _normalize_include_all_tags(include_all_tags: Any) -> bool:
|
||||
"""
|
||||
归一全部标签查询开关。
|
||||
"""
|
||||
if isinstance(include_all_tags, bool):
|
||||
return include_all_tags
|
||||
if isinstance(include_all_tags, str):
|
||||
return include_all_tags.strip().lower() in {"1", "true", "yes", "on", "是"}
|
||||
return bool(include_all_tags)
|
||||
|
||||
@staticmethod
|
||||
def _get_all_torrents(
|
||||
download_chain: DownloadChain,
|
||||
downloader: Optional[str] = None,
|
||||
include_all_tags: bool = False,
|
||||
) -> List[DownloaderTorrent]:
|
||||
"""
|
||||
查询所有状态的任务(包括下载中和已完成的任务)
|
||||
"""
|
||||
return download_chain.list_torrents(
|
||||
downloader=downloader,
|
||||
include_all_tags=include_all_tags,
|
||||
) or []
|
||||
|
||||
@staticmethod
|
||||
def _format_progress(progress: Optional[float]) -> Optional[str]:
|
||||
"""
|
||||
将下载进度格式化为保留一位小数的百分比字符串
|
||||
"""
|
||||
try:
|
||||
if progress is None:
|
||||
return None
|
||||
return f"{float(progress):.1f}%"
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
|
||||
@staticmethod
|
||||
def _apply_download_history(
|
||||
torrent: DownloaderTorrent, history: Optional[DownloadHistorySnapshot]
|
||||
) -> None:
|
||||
"""将下载历史中的补充信息回填到下载任务结果中。"""
|
||||
if not history:
|
||||
return
|
||||
if hasattr(torrent, "media"):
|
||||
media = DownloadTaskMedia(
|
||||
type=history.type,
|
||||
title=history.title,
|
||||
season=history.seasons,
|
||||
episode=history.episodes,
|
||||
image=history.image,
|
||||
poster=history.poster,
|
||||
media_source=history.media_source,
|
||||
media_id=history.media_id,
|
||||
)
|
||||
music_media = QueryDownloadTasksTool._history_music_media(history)
|
||||
if media_type_to_agent(history.type) == "music":
|
||||
music_type = music_media.get("music_type")
|
||||
artists = music_media.get("artists")
|
||||
album = music_media.get("album")
|
||||
album_id = music_media.get("album_id")
|
||||
total_tracks = music_media.get("total_tracks")
|
||||
track_number = music_media.get("track_number")
|
||||
media.music_type = (
|
||||
music_type if isinstance(music_type, str) else MUSIC_ENTITY_RECORDING
|
||||
)
|
||||
media.artists = (
|
||||
[artist for artist in artists if isinstance(artist, str)]
|
||||
if isinstance(artists, list)
|
||||
else []
|
||||
)
|
||||
media.album = album if isinstance(album, str) else None
|
||||
media.album_id = album_id if isinstance(album_id, str) else None
|
||||
media.total_tracks = (
|
||||
total_tracks
|
||||
if isinstance(total_tracks, int) and not isinstance(total_tracks, bool)
|
||||
else None
|
||||
)
|
||||
media.track_number = (
|
||||
track_number
|
||||
if isinstance(track_number, int) and not isinstance(track_number, bool)
|
||||
else None
|
||||
)
|
||||
torrent.media = media
|
||||
if hasattr(torrent, "username"):
|
||||
torrent.username = history.username
|
||||
torrent.userid = history.userid
|
||||
|
||||
@staticmethod
|
||||
def _history_music_media(
|
||||
history: DownloadHistorySnapshot,
|
||||
) -> dict[str, JsonData]:
|
||||
"""从冻结历史备注中读取经过结构校验的音乐媒体字段。"""
|
||||
note = history.note
|
||||
if not isinstance(note, dict):
|
||||
return {}
|
||||
music = note.get("music")
|
||||
if not isinstance(music, dict):
|
||||
return {}
|
||||
media = music.get("media")
|
||||
return media if isinstance(media, dict) else {}
|
||||
|
||||
def _load_history_map(
|
||||
self,
|
||||
torrents: List[DownloaderTorrent],
|
||||
) -> Dict[str, DownloadHistorySnapshot]:
|
||||
"""批量加载下载历史,避免逐条查询形成 N+1。"""
|
||||
hashes = [torrent.hash for torrent in torrents if torrent.hash]
|
||||
if not hashes:
|
||||
return {}
|
||||
return self.data.download_history.get_by_hashes(hashes)
|
||||
|
||||
def _query_downloads_sync(
|
||||
self,
|
||||
downloader: Optional[str] = None,
|
||||
status: Optional[str] = "all",
|
||||
hash_value: Optional[str] = None,
|
||||
title: Optional[str] = None,
|
||||
tag: Optional[str] = None,
|
||||
include_all_tags: bool = False,
|
||||
include_trackers: bool = False,
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
同步查询下载器和下载历史,整个链路放在线程池中执行。
|
||||
"""
|
||||
download_chain = DownloadChain()
|
||||
query_status = self._normalize_query_status(status)
|
||||
include_all_tags = self._normalize_include_all_tags(include_all_tags)
|
||||
|
||||
if hash_value:
|
||||
torrents = (
|
||||
download_chain.list_torrents(
|
||||
downloader=downloader,
|
||||
hashs=[hash_value],
|
||||
include_all_tags=include_all_tags,
|
||||
)
|
||||
or []
|
||||
)
|
||||
if not torrents:
|
||||
return {
|
||||
"message": f"未找到hash为 {hash_value} 的下载任务(该任务可能已完成、已删除或不存在)"
|
||||
}
|
||||
|
||||
history_map = self._load_history_map(torrents)
|
||||
for torrent in torrents:
|
||||
self._apply_download_history(torrent, history_map.get(torrent.hash))
|
||||
filtered_downloads = list(torrents)
|
||||
elif title:
|
||||
all_torrents = self._get_all_torrents(
|
||||
download_chain,
|
||||
downloader,
|
||||
include_all_tags=include_all_tags,
|
||||
)
|
||||
history_map = self._load_history_map(all_torrents)
|
||||
filtered_downloads = []
|
||||
title_lower = title.lower()
|
||||
|
||||
for torrent in all_torrents:
|
||||
history = history_map.get(torrent.hash)
|
||||
matched = title_lower in (torrent.title or "").lower() or title_lower in (
|
||||
getattr(torrent, "name", None) or ""
|
||||
).lower()
|
||||
if not matched and history and history.title:
|
||||
matched = title_lower in history.title.lower()
|
||||
|
||||
if not matched:
|
||||
continue
|
||||
|
||||
self._apply_download_history(torrent, history)
|
||||
filtered_downloads.append(torrent)
|
||||
|
||||
if not filtered_downloads:
|
||||
return {"message": f"未找到标题包含 '{title}' 的下载任务"}
|
||||
else:
|
||||
if query_status == TorrentQueryStatus.DOWNLOADING and not include_all_tags:
|
||||
downloads = download_chain.downloading(name=downloader) or []
|
||||
filtered_downloads = [
|
||||
dl
|
||||
for dl in downloads
|
||||
if not downloader or dl.downloader == downloader
|
||||
]
|
||||
else:
|
||||
list_status = None if query_status == TorrentQueryStatus.ALL else query_status.value
|
||||
filtered_downloads = download_chain.list_torrents(
|
||||
downloader=downloader,
|
||||
status=list_status,
|
||||
include_all_tags=include_all_tags,
|
||||
) or []
|
||||
|
||||
history_map = self._load_history_map(filtered_downloads)
|
||||
for torrent in filtered_downloads:
|
||||
self._apply_download_history(
|
||||
torrent,
|
||||
history_map.get(torrent.hash),
|
||||
)
|
||||
|
||||
if tag and filtered_downloads:
|
||||
tag_lower = tag.lower()
|
||||
filtered_downloads = [
|
||||
d for d in filtered_downloads if d.tags and tag_lower in d.tags.lower()
|
||||
]
|
||||
if not filtered_downloads:
|
||||
return {"message": f"未找到标签包含 '{tag}' 的下载任务"}
|
||||
|
||||
if not filtered_downloads:
|
||||
return {"message": "未找到相关下载任务"}
|
||||
|
||||
if hash_value or include_trackers:
|
||||
for torrent in filtered_downloads:
|
||||
if not getattr(torrent, "hash", None):
|
||||
continue
|
||||
tracker_map = download_chain.get_torrent_trackers(
|
||||
hash_string=torrent.hash,
|
||||
downloader=getattr(torrent, "downloader", None) or downloader,
|
||||
) or {}
|
||||
torrent.trackers = tracker_map.get(getattr(torrent, "downloader", None)) or []
|
||||
|
||||
return {"downloads": filtered_downloads}
|
||||
|
||||
def get_tool_message(self, **kwargs) -> Optional[str]:
|
||||
"""根据查询参数生成友好的提示消息"""
|
||||
downloader = kwargs.get("downloader")
|
||||
status = kwargs.get("status", "all")
|
||||
hash_value = kwargs.get("hash")
|
||||
title = kwargs.get("title")
|
||||
include_all_tags = self._normalize_include_all_tags(
|
||||
kwargs.get("include_all_tags", False)
|
||||
)
|
||||
|
||||
parts = ["查询下载任务"]
|
||||
|
||||
if downloader:
|
||||
parts.append(f"下载器: {downloader}")
|
||||
|
||||
if status != "all":
|
||||
status_map = {"downloading": "下载中", "completed": "已完成", "paused": "已暂停"}
|
||||
parts.append(f"状态: {status_map.get(status, status)}")
|
||||
|
||||
if hash_value:
|
||||
parts.append(f"Hash: {hash_value[:8]}...")
|
||||
elif title:
|
||||
parts.append(f"标题: {title}")
|
||||
|
||||
tag = kwargs.get("tag")
|
||||
if tag:
|
||||
parts.append(f"标签: {tag}")
|
||||
if include_all_tags:
|
||||
parts.append("范围: 全部标签")
|
||||
if kwargs.get("include_trackers"):
|
||||
parts.append("包含Tracker")
|
||||
|
||||
return " | ".join(parts) if len(parts) > 1 else parts[0]
|
||||
|
||||
async def run(self, downloader: Optional[str] = None,
|
||||
status: Optional[str] = "all",
|
||||
hash: Optional[str] = None,
|
||||
title: Optional[str] = None,
|
||||
tag: Optional[str] = None,
|
||||
include_all_tags: Optional[bool] = False,
|
||||
include_trackers: Optional[bool] = False,
|
||||
**kwargs) -> str:
|
||||
"""执行下载任务查询并输出有界的状态摘要。"""
|
||||
logger.info(
|
||||
f"执行工具: {self.name}, 参数: downloader={downloader}, status={status}, "
|
||||
f"hash={hash}, title={title}, tag={tag}, include_all_tags={include_all_tags}, "
|
||||
f"include_trackers={include_trackers}"
|
||||
)
|
||||
try:
|
||||
payload = await self.run_blocking(
|
||||
"downloader",
|
||||
self._query_downloads_sync,
|
||||
downloader,
|
||||
status,
|
||||
hash,
|
||||
title,
|
||||
tag,
|
||||
self._normalize_include_all_tags(include_all_tags),
|
||||
self._normalize_include_all_tags(include_trackers),
|
||||
)
|
||||
if payload.get("message"):
|
||||
return payload["message"]
|
||||
|
||||
filtered_downloads = payload.get("downloads") or []
|
||||
if filtered_downloads:
|
||||
# 限制最多20条结果
|
||||
total_count = len(filtered_downloads)
|
||||
limited_downloads = filtered_downloads[:20]
|
||||
# 精简字段,只保留关键信息
|
||||
simplified_downloads = []
|
||||
for d in limited_downloads:
|
||||
simplified = {
|
||||
"downloader": d.downloader,
|
||||
"hash": d.hash,
|
||||
"title": d.title,
|
||||
"name": getattr(d, "name", None),
|
||||
"year": getattr(d, "year", None),
|
||||
"season_episode": getattr(d, "season_episode", None),
|
||||
"size": d.size,
|
||||
"progress": self._format_progress(d.progress),
|
||||
"state": d.state,
|
||||
"upspeed": getattr(d, "upspeed", None),
|
||||
"dlspeed": getattr(d, "dlspeed", None),
|
||||
"tags": d.tags,
|
||||
"save_path": getattr(d, "save_path", None),
|
||||
"content_path": getattr(d, "content_path", None) or (
|
||||
d.path.as_posix() if getattr(d, "path", None) else None
|
||||
),
|
||||
"category": getattr(d, "category", None),
|
||||
"download_limit": getattr(d, "download_limit", None),
|
||||
"upload_limit": getattr(d, "upload_limit", None),
|
||||
"ratio_limit": getattr(d, "ratio_limit", None),
|
||||
"seeding_time_limit": getattr(d, "seeding_time_limit", None),
|
||||
"trackers": getattr(d, "trackers", None) or [],
|
||||
"left_time": getattr(d, "left_time", None)
|
||||
}
|
||||
# 精简 media 字段
|
||||
media = getattr(d, "media", None)
|
||||
if media:
|
||||
media_data = (
|
||||
media.model_dump() if isinstance(media, BaseModel) else media
|
||||
)
|
||||
simplified["media"] = {
|
||||
"type": media_type_to_agent(media_data.get("type")),
|
||||
"title": media_data.get("title"),
|
||||
"season": media_data.get("season"),
|
||||
"episode": media_data.get("episode"),
|
||||
"media_source": media_data.get("media_source"),
|
||||
"media_id": media_data.get("media_id"),
|
||||
"music_type": media_data.get("music_type"),
|
||||
"artists": media_data.get("artists"),
|
||||
"album": media_data.get("album"),
|
||||
"album_id": media_data.get("album_id"),
|
||||
"total_tracks": media_data.get("total_tracks"),
|
||||
"track_number": media_data.get("track_number"),
|
||||
}
|
||||
simplified_downloads.append(simplified)
|
||||
result_json = json.dumps(simplified_downloads, ensure_ascii=False, indent=2)
|
||||
# 如果结果被裁剪,添加提示信息
|
||||
if total_count > 20:
|
||||
return f"注意:查询结果共找到 {total_count} 条,为节省上下文空间,仅显示前 20 条结果。\n\n{result_json}"
|
||||
|
||||
# 如果查询的是特定hash或title,添加明确的状态信息
|
||||
if hash:
|
||||
return f"找到hash为 {hash} 的下载任务:\n\n{result_json}"
|
||||
elif title:
|
||||
return f"找到 {total_count} 个标题包含 '{title}' 的下载任务:\n\n{result_json}"
|
||||
|
||||
return result_json
|
||||
return "未找到相关下载任务"
|
||||
except Exception as e:
|
||||
logger.error(f"查询下载失败: {e}", exc_info=True)
|
||||
return f"查询下载时发生错误: {str(e)}"
|
||||
@@ -1,72 +0,0 @@
|
||||
"""查询下载器工具"""
|
||||
|
||||
import json
|
||||
from typing import Optional, Type
|
||||
|
||||
from pydantic import BaseModel
|
||||
|
||||
from app.agent.tools.base import MoviePilotTool
|
||||
from app.agent.tools.tags import ToolTag
|
||||
from app.application.configuration import get_configured_system_config
|
||||
from app.runtime.log import logger
|
||||
from app.schemas.types import SystemConfigKey
|
||||
|
||||
|
||||
class QueryDownloadersInput(BaseModel):
|
||||
"""查询下载器工具的输入参数模型"""
|
||||
class QueryDownloadersTool(MoviePilotTool):
|
||||
name: str = "query_downloaders"
|
||||
tags: list[str] = [
|
||||
ToolTag.Read,
|
||||
ToolTag.Download,
|
||||
]
|
||||
description: str = (
|
||||
"Query downloader configuration and list available downloaders. Non-admin users receive "
|
||||
"a safe view with only the fields needed to choose a downloader, without host, account, "
|
||||
"password, token or API key values."
|
||||
)
|
||||
args_schema: Type[BaseModel] = QueryDownloadersInput
|
||||
|
||||
def get_tool_message(self, **kwargs) -> Optional[str]:
|
||||
"""生成友好的提示消息"""
|
||||
return "查询下载器配置"
|
||||
|
||||
@staticmethod
|
||||
def _load_downloaders_config():
|
||||
"""从内存配置缓存中读取下载器配置。"""
|
||||
return get_configured_system_config().get(SystemConfigKey.Downloaders)
|
||||
|
||||
@staticmethod
|
||||
def _sanitize_downloaders_config(downloaders_config: list) -> list:
|
||||
"""
|
||||
生成普通用户可见的下载器配置视图。
|
||||
|
||||
:param downloaders_config: 系统下载器完整配置列表
|
||||
:return: 仅包含名称、类型和启用状态的安全配置列表
|
||||
"""
|
||||
safe_fields = ("name", "type", "enabled", "default", "priority")
|
||||
safe_downloaders = []
|
||||
for downloader in downloaders_config:
|
||||
if not isinstance(downloader, dict):
|
||||
continue
|
||||
safe_downloaders.append({
|
||||
key: downloader.get(key)
|
||||
for key in safe_fields
|
||||
if key in downloader
|
||||
})
|
||||
return safe_downloaders
|
||||
|
||||
async def run(self, **kwargs) -> str:
|
||||
logger.info(f"执行工具: {self.name}")
|
||||
try:
|
||||
downloaders_config = self._load_downloaders_config()
|
||||
if downloaders_config:
|
||||
if not await self.is_admin_user():
|
||||
downloaders_config = self._sanitize_downloaders_config(
|
||||
downloaders_config
|
||||
)
|
||||
return json.dumps(downloaders_config, ensure_ascii=False, indent=2)
|
||||
return "未配置下载器。"
|
||||
except Exception as e:
|
||||
logger.error(f"查询下载器失败: {e}")
|
||||
return f"查询下载器时发生错误: {str(e)}"
|
||||
@@ -1,107 +0,0 @@
|
||||
"""查询剧集上映时间工具"""
|
||||
|
||||
import json
|
||||
from typing import Optional, Type
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from app.agent.tools.base import MoviePilotTool
|
||||
from app.agent.tools.tags import ToolTag
|
||||
from app.chain.tmdb import TmdbChain
|
||||
from app.runtime.log import logger
|
||||
|
||||
|
||||
class QueryEpisodeScheduleInput(BaseModel):
|
||||
"""查询剧集上映时间工具的输入参数模型"""
|
||||
tmdb_id: int = Field(..., description="TMDB ID of the TV series (can be obtained from search_media tool)")
|
||||
season: int = Field(..., description="Season number to query")
|
||||
episode_group: Optional[str] = Field(None, description="Episode group ID (optional)")
|
||||
|
||||
|
||||
class QueryEpisodeScheduleTool(MoviePilotTool):
|
||||
name: str = "query_episode_schedule"
|
||||
tags: list[str] = [
|
||||
ToolTag.Read,
|
||||
ToolTag.Media,
|
||||
]
|
||||
description: str = "Query TV series episode air dates and schedule. Returns non-duplicated schedule fields, including episode list, air-date statistics, and per-episode metadata. Filters out episodes without air dates."
|
||||
args_schema: Type[BaseModel] = QueryEpisodeScheduleInput
|
||||
|
||||
def get_tool_message(self, **kwargs) -> Optional[str]:
|
||||
"""根据查询参数生成友好的提示消息"""
|
||||
tmdb_id = kwargs.get("tmdb_id")
|
||||
season = kwargs.get("season")
|
||||
episode_group = kwargs.get("episode_group")
|
||||
|
||||
message = f"查询剧集上映时间: TMDB ID {tmdb_id} 第{season}季"
|
||||
if episode_group:
|
||||
message += f" (剧集组: {episode_group})"
|
||||
|
||||
return message
|
||||
|
||||
async def run(self, tmdb_id: int, season: int, episode_group: Optional[str] = None, **kwargs) -> str:
|
||||
logger.info(f"执行工具: {self.name}, 参数: tmdb_id={tmdb_id}, season={season}, episode_group={episode_group}")
|
||||
|
||||
try:
|
||||
# 获取集列表
|
||||
tmdb_chain = TmdbChain()
|
||||
episodes = await tmdb_chain.async_tmdb_episodes(
|
||||
tmdbid=tmdb_id,
|
||||
season=season,
|
||||
episode_group=episode_group
|
||||
)
|
||||
|
||||
if not episodes:
|
||||
return json.dumps({
|
||||
"success": False,
|
||||
"message": f"未找到 TMDB ID {tmdb_id} 第{season}季的集信息"
|
||||
}, ensure_ascii=False)
|
||||
|
||||
# 过滤掉没有上映日期的集,并构建每集的详细信息
|
||||
episode_list = []
|
||||
for episode in episodes:
|
||||
air_date = episode.air_date
|
||||
|
||||
# 过滤掉没有上映日期的数据
|
||||
if not air_date:
|
||||
continue
|
||||
|
||||
episode_info = {
|
||||
"episode_number": episode.episode_number,
|
||||
"name": episode.name,
|
||||
"air_date": air_date,
|
||||
"runtime": episode.runtime,
|
||||
"vote_average": episode.vote_average,
|
||||
"still_path": episode.still_path,
|
||||
"episode_type": episode.episode_type,
|
||||
"season_number": episode.season_number
|
||||
}
|
||||
episode_list.append(episode_info)
|
||||
|
||||
if not episode_list:
|
||||
return json.dumps({
|
||||
"success": False,
|
||||
"message": f"未找到 TMDB ID {tmdb_id} 第{season}季的播出时间信息(所有集都没有播出日期)"
|
||||
}, ensure_ascii=False)
|
||||
|
||||
# 按播出日期排序
|
||||
episode_list.sort(key=lambda x: (x["air_date"] or "", x["episode_number"] or 0))
|
||||
|
||||
result = {
|
||||
"season": season,
|
||||
"total_episodes": len(episodes),
|
||||
"episodes_with_air_date": len(episode_list),
|
||||
"episodes": episode_list
|
||||
}
|
||||
|
||||
return json.dumps(result, ensure_ascii=False, indent=2)
|
||||
|
||||
except Exception as e:
|
||||
error_message = f"查询剧集上映时间失败: {str(e)}"
|
||||
logger.error(f"查询剧集上映时间失败: {e}", exc_info=True)
|
||||
return json.dumps({
|
||||
"success": False,
|
||||
"message": error_message,
|
||||
"tmdb_id": tmdb_id,
|
||||
"season": season
|
||||
}, ensure_ascii=False)
|
||||
@@ -1,131 +0,0 @@
|
||||
"""查询已安装插件工具"""
|
||||
|
||||
import json
|
||||
from typing import Optional, Type
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from app.agent.tools.base import MoviePilotTool
|
||||
from app.agent.tools.tags import ToolTag
|
||||
from app.agent.tools.impl._plugin_tool_utils import (
|
||||
DEFAULT_PLUGIN_CANDIDATE_LIMIT,
|
||||
MAX_PLUGIN_CANDIDATE_LIMIT,
|
||||
enrich_installed_plugin_sources,
|
||||
list_installed_plugins,
|
||||
search_plugin_candidates,
|
||||
summarize_candidates,
|
||||
summarize_plugin,
|
||||
)
|
||||
from app.runtime.log import logger
|
||||
|
||||
|
||||
class QueryInstalledPluginsInput(BaseModel):
|
||||
"""查询已安装插件工具的输入参数模型"""
|
||||
|
||||
query: Optional[str] = Field(
|
||||
None,
|
||||
description="Optional keyword to filter installed plugins by plugin ID, name, description, or author.",
|
||||
)
|
||||
max_results: Optional[int] = Field(
|
||||
DEFAULT_PLUGIN_CANDIDATE_LIMIT,
|
||||
description="Maximum number of plugins to return. Defaults to 50, capped at 200.",
|
||||
)
|
||||
force_refresh_market: bool = Field(
|
||||
False,
|
||||
description="Whether to refresh plugin market caches before completing missing repo_url values.",
|
||||
)
|
||||
|
||||
|
||||
class QueryInstalledPluginsTool(MoviePilotTool):
|
||||
"""查询已安装插件并返回 Agent 可消费的摘要信息。"""
|
||||
|
||||
name: str = "query_installed_plugins"
|
||||
tags: list[str] = [
|
||||
ToolTag.Read,
|
||||
ToolTag.Plugin,
|
||||
ToolTag.Admin,
|
||||
]
|
||||
description: str = (
|
||||
"Query installed plugins in MoviePilot. Returns all installed plugins or filters them by keywords. "
|
||||
"Use this tool to find the exact plugin_id before uninstall_plugin or other plugin management tools are used."
|
||||
)
|
||||
require_admin: bool = True
|
||||
args_schema: Type[BaseModel] = QueryInstalledPluginsInput
|
||||
|
||||
def get_tool_message(self, **kwargs) -> Optional[str]:
|
||||
"""生成友好的提示消息"""
|
||||
query = kwargs.get("query")
|
||||
if query:
|
||||
return f"查询已安装插件: {query}"
|
||||
return "查询已安装插件"
|
||||
|
||||
@staticmethod
|
||||
def _clamp_results(max_results: Optional[int]) -> int:
|
||||
if max_results is None:
|
||||
return DEFAULT_PLUGIN_CANDIDATE_LIMIT
|
||||
try:
|
||||
return max(1, min(int(max_results), MAX_PLUGIN_CANDIDATE_LIMIT))
|
||||
except (TypeError, ValueError):
|
||||
return DEFAULT_PLUGIN_CANDIDATE_LIMIT
|
||||
|
||||
async def run(
|
||||
self,
|
||||
query: Optional[str] = None,
|
||||
max_results: Optional[int] = DEFAULT_PLUGIN_CANDIDATE_LIMIT,
|
||||
force_refresh_market: bool = False,
|
||||
**kwargs,
|
||||
) -> str:
|
||||
"""
|
||||
查询已安装插件列表,并在可能时补齐插件来源仓库地址。
|
||||
"""
|
||||
logger.info(
|
||||
f"执行工具: {self.name}, 参数: query={query}, force_refresh_market={force_refresh_market}"
|
||||
)
|
||||
try:
|
||||
installed_plugins = list_installed_plugins()
|
||||
if not installed_plugins:
|
||||
return json.dumps(
|
||||
{"success": False, "message": "当前没有已安装的插件"},
|
||||
ensure_ascii=False,
|
||||
)
|
||||
installed_plugins = await enrich_installed_plugin_sources(
|
||||
installed_plugins,
|
||||
force_refresh=force_refresh_market,
|
||||
)
|
||||
|
||||
limit = self._clamp_results(max_results)
|
||||
if query:
|
||||
matches = search_plugin_candidates(query, installed_plugins)
|
||||
return json.dumps(
|
||||
{
|
||||
"success": True,
|
||||
"query": query,
|
||||
"total_installed": len(installed_plugins),
|
||||
"match_count": len(matches),
|
||||
"truncated": len(matches) > limit,
|
||||
"plugins": summarize_candidates(matches, limit=limit),
|
||||
},
|
||||
ensure_ascii=False,
|
||||
indent=2,
|
||||
)
|
||||
|
||||
plugin_summaries = [
|
||||
summarize_plugin(plugin) for plugin in installed_plugins[:limit]
|
||||
]
|
||||
return json.dumps(
|
||||
{
|
||||
"success": True,
|
||||
"total_installed": len(installed_plugins),
|
||||
"returned_count": len(plugin_summaries),
|
||||
"truncated": len(installed_plugins) > limit,
|
||||
"plugins": plugin_summaries,
|
||||
},
|
||||
ensure_ascii=False,
|
||||
indent=2,
|
||||
)
|
||||
except Exception as e:
|
||||
logger.error(f"查询已安装插件失败: {e}", exc_info=True)
|
||||
return json.dumps(
|
||||
{"success": False, "message": f"查询已安装插件时发生错误: {str(e)}"},
|
||||
ensure_ascii=False,
|
||||
)
|
||||
@@ -1,271 +0,0 @@
|
||||
"""查询媒体库工具"""
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
from collections import OrderedDict
|
||||
from typing import Optional, Type, Any
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from app.agent.tools.base import MoviePilotTool
|
||||
from app.agent.tools.tags import ToolTag
|
||||
from app.chain.mediaserver import MediaServerChain
|
||||
from app.application.mediaserver import MediaServerHelper
|
||||
from app.runtime.log import logger
|
||||
from app.schemas.types import (
|
||||
MUSIC_ENTITY_ALBUM,
|
||||
MediaSource,
|
||||
MediaType,
|
||||
media_type_to_agent,
|
||||
)
|
||||
from app.domain.media import normalize_music_type
|
||||
|
||||
|
||||
def _sort_seasons(seasons: Optional[dict]) -> dict:
|
||||
"""按季号、集号升序整理季集信息,保证输出稳定。"""
|
||||
if not seasons:
|
||||
return {}
|
||||
|
||||
def _sort_key(value):
|
||||
try:
|
||||
return int(value)
|
||||
except (TypeError, ValueError):
|
||||
return str(value)
|
||||
|
||||
return OrderedDict(
|
||||
(season, sorted(episodes, key=_sort_key))
|
||||
for season, episodes in sorted(seasons.items(), key=lambda item: _sort_key(item[0]))
|
||||
)
|
||||
|
||||
|
||||
def _filter_regular_seasons(seasons: Optional[dict]) -> OrderedDict:
|
||||
"""仅保留正片季,忽略 season 0 等特殊季。"""
|
||||
sorted_seasons = _sort_seasons(seasons)
|
||||
regular_seasons = OrderedDict()
|
||||
for season, episodes in sorted_seasons.items():
|
||||
try:
|
||||
season_number = int(season)
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
if season_number > 0:
|
||||
regular_seasons[season_number] = episodes
|
||||
return regular_seasons
|
||||
|
||||
|
||||
def _build_tv_server_result(existing_seasons: OrderedDict, total_seasons: OrderedDict) -> dict[str, Any]:
|
||||
"""构建单个服务器的电视剧存在性结果。"""
|
||||
seasons_result = OrderedDict()
|
||||
missing_seasons = []
|
||||
all_seasons = sorted(set(total_seasons.keys()) | set(existing_seasons.keys()))
|
||||
|
||||
for season in all_seasons:
|
||||
existing_episodes = existing_seasons.get(season, [])
|
||||
total_episodes = total_seasons.get(season)
|
||||
if total_episodes is not None:
|
||||
missing_episodes = [episode for episode in total_episodes if episode not in existing_episodes]
|
||||
total_episode_count = len(total_episodes)
|
||||
else:
|
||||
missing_episodes = None
|
||||
total_episode_count = None
|
||||
seasons_result[str(season)] = {
|
||||
"existing_episodes": existing_episodes,
|
||||
"total_episodes": total_episode_count,
|
||||
"missing_episodes": missing_episodes
|
||||
}
|
||||
if total_episodes is not None and not existing_episodes:
|
||||
missing_seasons.append(season)
|
||||
|
||||
return {
|
||||
"seasons": seasons_result,
|
||||
"missing_seasons": missing_seasons
|
||||
}
|
||||
|
||||
|
||||
class QueryLibraryExistsInput(BaseModel):
|
||||
"""查询媒体库工具的输入参数模型"""
|
||||
media_source: MediaSource = Field(..., description="Media metadata source")
|
||||
media_id: str = Field(..., description="Native ID for media_source")
|
||||
media_type: Optional[str] = Field(None, description="Allowed values: movie, tv, music")
|
||||
music_type: Optional[str] = Field(
|
||||
None,
|
||||
description="For music: recording or album. Artists are not library acquisition targets",
|
||||
)
|
||||
|
||||
|
||||
class QueryLibraryExistsTool(MoviePilotTool):
|
||||
"""查询影视、单曲或完整专辑是否已存在于媒体服务器。"""
|
||||
|
||||
name: str = "query_library_exists"
|
||||
tags: list[str] = [
|
||||
ToolTag.Read,
|
||||
ToolTag.Library,
|
||||
ToolTag.Media,
|
||||
]
|
||||
description: str = (
|
||||
"Check whether movies, TV, music recordings, or complete albums exist on configured media servers. "
|
||||
"TV results include episode coverage. Album existence is true only when the server confirms complete "
|
||||
"track coverage for the expected album size; artists cannot be queried as acquisition targets."
|
||||
)
|
||||
args_schema: Type[BaseModel] = QueryLibraryExistsInput
|
||||
|
||||
def get_tool_message(self, **kwargs) -> Optional[str]:
|
||||
"""根据查询参数生成友好的提示消息"""
|
||||
media_type = kwargs.get("media_type")
|
||||
label = kwargs.get("media_source") or "媒体源"
|
||||
identity = kwargs.get("media_id")
|
||||
message = f"查询媒体库: {label}={identity}" if label else "查询媒体库"
|
||||
if media_type:
|
||||
message += f" [{media_type}]"
|
||||
return message
|
||||
|
||||
@staticmethod
|
||||
def _get_media_server_names() -> list[str]:
|
||||
"""同步读取已加载媒体服务器名称。"""
|
||||
return sorted(MediaServerHelper().get_services().keys())
|
||||
|
||||
@staticmethod
|
||||
def _query_media_exists(mediainfo, server: Optional[str] = None):
|
||||
"""同步查询单个媒体服务器的存在性信息。"""
|
||||
return MediaServerChain().media_exists(mediainfo=mediainfo, server=server)
|
||||
|
||||
async def run(self, media_source: MediaSource, media_id: str,
|
||||
media_type: Optional[str] = None,
|
||||
music_type: Optional[str] = None, **kwargs) -> str:
|
||||
"""识别精确媒体身份并按服务器汇总存在性或完整性。"""
|
||||
logger.info(
|
||||
f"执行工具: {self.name}, 参数: media_source={media_source}, "
|
||||
f"media_id={media_id}, media_type={media_type}"
|
||||
)
|
||||
try:
|
||||
if not str(media_id or "").strip():
|
||||
return "参数错误:必须提供 media_id,请先使用 search_media 工具获取媒体信息。"
|
||||
|
||||
media_type_enum = None
|
||||
if media_type:
|
||||
media_type_enum = MediaType.from_agent(media_type)
|
||||
if not media_type_enum:
|
||||
return f"错误:无效的媒体类型 '{media_type}',支持的类型:'movie', 'tv', 'music'"
|
||||
|
||||
normalized_music_type = None
|
||||
if music_type:
|
||||
normalized_music_type = normalize_music_type(
|
||||
music_type,
|
||||
allow_artist=False,
|
||||
)
|
||||
if not normalized_music_type:
|
||||
return (
|
||||
f"错误:无效的音乐实体类型 '{music_type}',"
|
||||
"支持的类型:'recording', 'album'"
|
||||
)
|
||||
if media_type_enum != MediaType.MUSIC:
|
||||
return "错误:music_type 仅能与 media_type='music' 一起使用"
|
||||
if media_type_enum == MediaType.MUSIC and (not media_source or not media_id):
|
||||
return "错误:音乐媒体库查询必须同时提供 media_source 和 media_id"
|
||||
|
||||
media_chain = MediaServerChain()
|
||||
mediainfo = await media_chain.async_recognize_media(
|
||||
media_source=media_source,
|
||||
media_id=media_id,
|
||||
mtype=media_type_enum,
|
||||
)
|
||||
if not mediainfo:
|
||||
return f"未识别到媒体信息: {media_source}:{media_id}"
|
||||
if normalized_music_type and (
|
||||
getattr(mediainfo, "music_type", None) != normalized_music_type
|
||||
):
|
||||
return (
|
||||
f"音乐实体类型不匹配:请求 {normalized_music_type},"
|
||||
f"实际 {getattr(mediainfo, 'music_type', None) or 'unknown'}"
|
||||
)
|
||||
|
||||
# 2. 遍历所有媒体服务器,分别查询存在性信息
|
||||
server_results = OrderedDict()
|
||||
total_seasons = _filter_regular_seasons(
|
||||
mediainfo.seasons if mediainfo.type == MediaType.TV else None
|
||||
)
|
||||
service_names = self._get_media_server_names()
|
||||
|
||||
server_checks = await asyncio.gather(
|
||||
*[
|
||||
self.run_blocking(
|
||||
"mediaserver",
|
||||
self._query_media_exists,
|
||||
mediainfo,
|
||||
service_name,
|
||||
)
|
||||
for service_name in service_names
|
||||
]
|
||||
)
|
||||
|
||||
for service_name, existsinfo in zip(service_names, server_checks):
|
||||
if not existsinfo:
|
||||
continue
|
||||
|
||||
if existsinfo.type == MediaType.TV:
|
||||
existing_seasons = _filter_regular_seasons(existsinfo.seasons)
|
||||
server_results[service_name] = _build_tv_server_result(
|
||||
existing_seasons=existing_seasons,
|
||||
total_seasons=total_seasons
|
||||
)
|
||||
else:
|
||||
server_results[service_name] = {
|
||||
"exists": True,
|
||||
**(
|
||||
{
|
||||
"complete": True,
|
||||
"expected_tracks": mediainfo.total_tracks,
|
||||
}
|
||||
if mediainfo.type == MediaType.MUSIC
|
||||
and getattr(mediainfo, "music_type", None) == MUSIC_ENTITY_ALBUM
|
||||
else {}
|
||||
),
|
||||
}
|
||||
|
||||
if not server_results:
|
||||
global_existsinfo = await self.run_blocking(
|
||||
"mediaserver", self._query_media_exists, mediainfo, None
|
||||
)
|
||||
if not global_existsinfo:
|
||||
return "媒体库中未找到相关媒体"
|
||||
|
||||
fallback_server_name = global_existsinfo.server or "local"
|
||||
if global_existsinfo.type == MediaType.TV:
|
||||
server_results[fallback_server_name] = _build_tv_server_result(
|
||||
existing_seasons=_filter_regular_seasons(global_existsinfo.seasons),
|
||||
total_seasons=total_seasons
|
||||
)
|
||||
else:
|
||||
server_results[fallback_server_name] = {
|
||||
"exists": True,
|
||||
**(
|
||||
{
|
||||
"complete": True,
|
||||
"expected_tracks": mediainfo.total_tracks,
|
||||
}
|
||||
if mediainfo.type == MediaType.MUSIC
|
||||
and getattr(mediainfo, "music_type", None) == MUSIC_ENTITY_ALBUM
|
||||
else {}
|
||||
),
|
||||
}
|
||||
|
||||
# 3. 组装统一的存在性结果,不查询媒体服务器详情
|
||||
result_dict = {
|
||||
"title": mediainfo.title,
|
||||
"year": mediainfo.year,
|
||||
"type": media_type_to_agent(mediainfo.type),
|
||||
"servers": server_results
|
||||
}
|
||||
if mediainfo.type == MediaType.MUSIC:
|
||||
result_dict.update({
|
||||
"music_type": mediainfo.music_type,
|
||||
"artists": list(mediainfo.artists or []),
|
||||
"album": mediainfo.album,
|
||||
"total_tracks": mediainfo.total_tracks,
|
||||
"media_source": mediainfo.media_source,
|
||||
"media_id": mediainfo.media_id,
|
||||
})
|
||||
|
||||
return json.dumps([result_dict], ensure_ascii=False)
|
||||
except Exception as e:
|
||||
logger.error(f"查询媒体库失败: {e}", exc_info=True)
|
||||
return f"查询媒体库时发生错误: {str(e)}"
|
||||
@@ -1,148 +0,0 @@
|
||||
"""查询媒体服务器最近入库条目工具"""
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
from typing import Optional, Type
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from app.agent.tools.base import MoviePilotTool
|
||||
from app.agent.tools.tags import ToolTag
|
||||
from app.chain.mediaserver import MediaServerChain
|
||||
from app.application.mediaserver import get_mediaserver_configs
|
||||
from app.runtime.log import logger
|
||||
|
||||
PAGE_SIZE = 20
|
||||
|
||||
|
||||
class QueryLibraryLatestInput(BaseModel):
|
||||
"""查询媒体服务器最近入库条目工具的输入参数模型"""
|
||||
|
||||
server: Optional[str] = Field(
|
||||
None,
|
||||
description="Media server name (optional, if not specified queries all enabled media servers)",
|
||||
)
|
||||
page: Optional[int] = Field(
|
||||
1, description="Page number for pagination (default: 1, 20 items per page)"
|
||||
)
|
||||
|
||||
|
||||
class QueryLibraryLatestTool(MoviePilotTool):
|
||||
"""查询媒体服务器最近入库的影视或音乐条目。"""
|
||||
|
||||
name: str = "query_library_latest"
|
||||
tags: list[str] = [
|
||||
ToolTag.Read,
|
||||
ToolTag.Library,
|
||||
ToolTag.Media,
|
||||
]
|
||||
description: str = (
|
||||
"Query the latest media items added to configured media servers. Returns any server-supported movies, "
|
||||
"TV, recordings, or albums with titles, images, links, and metadata. Supports 20-item pagination."
|
||||
)
|
||||
args_schema: Type[BaseModel] = QueryLibraryLatestInput
|
||||
|
||||
def get_tool_message(self, **kwargs) -> Optional[str]:
|
||||
"""根据查询参数生成友好的提示消息"""
|
||||
server = kwargs.get("server")
|
||||
page = kwargs.get("page", 1)
|
||||
|
||||
parts = ["查询媒体服务器最近入库条目"]
|
||||
|
||||
if server:
|
||||
parts.append(f"服务器: {server}")
|
||||
else:
|
||||
parts.append("所有服务器")
|
||||
|
||||
parts.append(f"第{page}页")
|
||||
|
||||
return " | ".join(parts)
|
||||
|
||||
@staticmethod
|
||||
def _get_enabled_servers() -> list[str]:
|
||||
"""同步读取启用的媒体服务器列表。"""
|
||||
return [config.name for config in get_mediaserver_configs()]
|
||||
|
||||
@staticmethod
|
||||
def _load_latest_items(
|
||||
server_name: str, count: int, username: Optional[str] = None
|
||||
) -> list[dict]:
|
||||
"""
|
||||
媒体服务器 SDK 和 requests 调用都是同步的,这里在线程池中转换为可序列化结果。
|
||||
"""
|
||||
latest_items = MediaServerChain().latest(
|
||||
server=server_name, count=count, username=username
|
||||
)
|
||||
if not latest_items:
|
||||
return []
|
||||
return [
|
||||
{
|
||||
**item.model_dump(exclude_none=True),
|
||||
"server": server_name,
|
||||
}
|
||||
for item in latest_items
|
||||
]
|
||||
|
||||
async def run(
|
||||
self, server: Optional[str] = None, page: Optional[int] = 1, **kwargs
|
||||
) -> str:
|
||||
"""并行读取媒体服务器最近入库结果并执行统一分页。"""
|
||||
page = max(1, page or 1)
|
||||
# 为了支持分页,需要获取足够多的数据再切片
|
||||
fetch_count = page * PAGE_SIZE
|
||||
logger.info(f"执行工具: {self.name}, 参数: server={server}, page={page}")
|
||||
try:
|
||||
# 如果没有指定服务器,获取所有启用的媒体服务器
|
||||
if not server:
|
||||
enabled_servers = self._get_enabled_servers()
|
||||
if not enabled_servers:
|
||||
return "未找到启用的媒体服务器"
|
||||
server_results = await asyncio.gather(
|
||||
*[
|
||||
self.run_blocking(
|
||||
"mediaserver",
|
||||
self._load_latest_items,
|
||||
server_name,
|
||||
fetch_count,
|
||||
self._username,
|
||||
)
|
||||
for server_name in enabled_servers
|
||||
]
|
||||
)
|
||||
results = [
|
||||
item for items in server_results for item in items if items
|
||||
]
|
||||
else:
|
||||
results = await self.run_blocking(
|
||||
"mediaserver",
|
||||
self._load_latest_items,
|
||||
server,
|
||||
fetch_count,
|
||||
self._username,
|
||||
)
|
||||
|
||||
if not results:
|
||||
server_info = f"服务器 {server}" if server else "所有服务器"
|
||||
return f"未找到 {server_info} 的最近入库条目"
|
||||
|
||||
# 分页
|
||||
total_count = len(results)
|
||||
start = (page - 1) * PAGE_SIZE
|
||||
end = start + PAGE_SIZE
|
||||
page_results = results[start:end]
|
||||
|
||||
if not page_results:
|
||||
total_pages = (total_count + PAGE_SIZE - 1) // PAGE_SIZE
|
||||
return f"第 {page} 页没有数据,共 {total_count} 条结果,共 {total_pages} 页。"
|
||||
|
||||
total_pages = (total_count + PAGE_SIZE - 1) // PAGE_SIZE
|
||||
payload_msg = f"第 {page}/{total_pages} 页,当前页 {len(page_results)} 条结果,共 {total_count} 条。"
|
||||
if page < total_pages:
|
||||
payload_msg += f" 可使用 page={page + 1} 获取下一页。"
|
||||
|
||||
result_json = json.dumps(page_results, ensure_ascii=False, indent=2)
|
||||
return f"{payload_msg}\n\n{result_json}"
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"查询媒体服务器最近入库影片失败: {e}", exc_info=True)
|
||||
return f"查询媒体服务器最近入库影片时发生错误: {str(e)}"
|
||||
@@ -1,119 +0,0 @@
|
||||
"""查询插件市场工具"""
|
||||
|
||||
import json
|
||||
from typing import Optional, Type
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from app.agent.tools.base import MoviePilotTool
|
||||
from app.agent.tools.tags import ToolTag
|
||||
from app.agent.tools.impl._plugin_tool_utils import (
|
||||
DEFAULT_PLUGIN_CANDIDATE_LIMIT,
|
||||
MAX_PLUGIN_CANDIDATE_LIMIT,
|
||||
load_market_plugins,
|
||||
search_plugin_candidates,
|
||||
summarize_candidates,
|
||||
summarize_plugin,
|
||||
)
|
||||
from app.runtime.log import logger
|
||||
|
||||
|
||||
class QueryMarketPluginsInput(BaseModel):
|
||||
"""查询插件市场工具的输入参数模型"""
|
||||
|
||||
query: Optional[str] = Field(
|
||||
None,
|
||||
description="Optional keyword to filter plugin market results by plugin ID, name, description, or author.",
|
||||
)
|
||||
max_results: Optional[int] = Field(
|
||||
DEFAULT_PLUGIN_CANDIDATE_LIMIT,
|
||||
description="Maximum number of plugins to return. Defaults to 50, capped at 200.",
|
||||
)
|
||||
force_refresh: Optional[bool] = Field(
|
||||
False,
|
||||
description="Whether to refresh plugin market caches before querying.",
|
||||
)
|
||||
|
||||
|
||||
class QueryMarketPluginsTool(MoviePilotTool):
|
||||
name: str = "query_market_plugins"
|
||||
tags: list[str] = [
|
||||
ToolTag.Read,
|
||||
ToolTag.Plugin,
|
||||
ToolTag.Admin,
|
||||
]
|
||||
description: str = (
|
||||
"Query available plugins from the plugin market and local plugin repositories. "
|
||||
"Can return the full plugin list or filter by keywords before install_plugin is used."
|
||||
)
|
||||
require_admin: bool = True
|
||||
args_schema: Type[BaseModel] = QueryMarketPluginsInput
|
||||
|
||||
def get_tool_message(self, **kwargs) -> Optional[str]:
|
||||
query = kwargs.get("query")
|
||||
if query:
|
||||
return f"查询插件市场: {query}"
|
||||
return "查询插件市场全部插件"
|
||||
|
||||
@staticmethod
|
||||
def _clamp_results(max_results: Optional[int]) -> int:
|
||||
if max_results is None:
|
||||
return DEFAULT_PLUGIN_CANDIDATE_LIMIT
|
||||
try:
|
||||
return max(1, min(int(max_results), MAX_PLUGIN_CANDIDATE_LIMIT))
|
||||
except (TypeError, ValueError):
|
||||
return DEFAULT_PLUGIN_CANDIDATE_LIMIT
|
||||
|
||||
async def run(
|
||||
self,
|
||||
query: Optional[str] = None,
|
||||
max_results: Optional[int] = DEFAULT_PLUGIN_CANDIDATE_LIMIT,
|
||||
force_refresh: bool = False,
|
||||
**kwargs,
|
||||
) -> str:
|
||||
logger.info(
|
||||
f"执行工具: {self.name}, 参数: query={query}, force_refresh={force_refresh}"
|
||||
)
|
||||
|
||||
try:
|
||||
plugins = await load_market_plugins(force_refresh=force_refresh)
|
||||
if not plugins:
|
||||
return json.dumps(
|
||||
{"success": False, "message": "当前插件市场没有可用插件"},
|
||||
ensure_ascii=False,
|
||||
)
|
||||
|
||||
limit = self._clamp_results(max_results)
|
||||
if query:
|
||||
matches = search_plugin_candidates(query, plugins)
|
||||
return json.dumps(
|
||||
{
|
||||
"success": True,
|
||||
"query": query,
|
||||
"total_available": len(plugins),
|
||||
"match_count": len(matches),
|
||||
"truncated": len(matches) > limit,
|
||||
"plugins": summarize_candidates(matches, limit=limit),
|
||||
},
|
||||
ensure_ascii=False,
|
||||
indent=2,
|
||||
)
|
||||
|
||||
plugin_summaries = [summarize_plugin(plugin) for plugin in plugins[:limit]]
|
||||
return json.dumps(
|
||||
{
|
||||
"success": True,
|
||||
"total_available": len(plugins),
|
||||
"returned_count": len(plugin_summaries),
|
||||
"truncated": len(plugins) > limit,
|
||||
"plugins": plugin_summaries,
|
||||
},
|
||||
ensure_ascii=False,
|
||||
indent=2,
|
||||
)
|
||||
except Exception as e:
|
||||
logger.error(f"查询插件市场失败: {e}", exc_info=True)
|
||||
return json.dumps(
|
||||
{"success": False, "message": f"查询插件市场时发生错误: {str(e)}"},
|
||||
ensure_ascii=False,
|
||||
)
|
||||
@@ -1,293 +0,0 @@
|
||||
"""查询媒体详情工具"""
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
from typing import Optional, Type
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from app.agent.tools.base import MoviePilotTool
|
||||
from app.agent.tools.tags import ToolTag
|
||||
from app.chain.media import MediaChain
|
||||
from app.runtime.log import logger
|
||||
from app.schemas.types import (
|
||||
MUSIC_ENTITY_ALBUM,
|
||||
MUSIC_ENTITY_ARTIST,
|
||||
MUSIC_ENTITY_RECORDING,
|
||||
MediaSource,
|
||||
MediaType,
|
||||
)
|
||||
from app.domain.media import normalize_music_type
|
||||
from ._music_utils import (
|
||||
simplify_music_album,
|
||||
simplify_music_artist,
|
||||
simplify_music_info,
|
||||
)
|
||||
|
||||
DIRECTOR_PREVIEW_LIMIT = 10
|
||||
ACTOR_PREVIEW_LIMIT = 20
|
||||
SEASON_PREVIEW_LIMIT = 100
|
||||
|
||||
|
||||
class QueryMediaDetailInput(BaseModel):
|
||||
"""查询媒体详情工具的输入参数模型"""
|
||||
media_source: MediaSource = Field(..., description="Media metadata source")
|
||||
media_id: str = Field(..., description="Native ID for media_source")
|
||||
media_type: str = Field(..., description="Allowed values: movie, tv, music")
|
||||
music_type: Optional[str] = Field(
|
||||
None,
|
||||
description="Required for music: recording, album, or artist",
|
||||
)
|
||||
include_artist_albums: Optional[bool] = Field(
|
||||
False,
|
||||
description="For artist detail, include a paged album/EP/single catalog preview",
|
||||
)
|
||||
include_related_artists: Optional[bool] = Field(
|
||||
False,
|
||||
description="For artist detail, include related artists",
|
||||
)
|
||||
page: Optional[int] = Field(1, description="Artist album catalog page, default 1")
|
||||
count: Optional[int] = Field(20, description="Artist catalog/related result count, max 30")
|
||||
album_type: Optional[str] = Field(
|
||||
None,
|
||||
description="Optional artist catalog filter: album, single, ep, broadcast, other, compilation, soundtrack, live, or remix",
|
||||
)
|
||||
|
||||
|
||||
class QueryMediaDetailTool(MoviePilotTool):
|
||||
"""按稳定媒体身份查询影视、单曲、专辑或艺术家详情。"""
|
||||
|
||||
name: str = "query_media_detail"
|
||||
tags: list[str] = [
|
||||
ToolTag.Read,
|
||||
ToolTag.Media,
|
||||
]
|
||||
description: str = (
|
||||
"Query details by stable metadata ID for movies, TV, music recordings, albums, or artists. "
|
||||
"Music requires media_source, media_id, and music_type. Album details include a bounded track list; "
|
||||
"artist details may optionally include catalog and related-artist previews. Artists are browse-only."
|
||||
)
|
||||
args_schema: Type[BaseModel] = QueryMediaDetailInput
|
||||
|
||||
def get_tool_message(self, **kwargs) -> Optional[str]:
|
||||
"""根据查询参数生成友好的提示消息"""
|
||||
return (
|
||||
f"查询媒体详情: {kwargs.get('media_source') or '媒体源'} "
|
||||
f"ID {kwargs.get('media_id')}"
|
||||
)
|
||||
|
||||
async def run(
|
||||
self, media_type: str, media_source: MediaSource,
|
||||
media_id: str, music_type: Optional[str] = None,
|
||||
include_artist_albums: Optional[bool] = False,
|
||||
include_related_artists: Optional[bool] = False,
|
||||
page: Optional[int] = 1, count: Optional[int] = 20,
|
||||
album_type: Optional[str] = None, **kwargs,
|
||||
) -> str:
|
||||
"""执行媒体详情查询,并限制音乐目录型结果的上下文大小。"""
|
||||
logger.info(
|
||||
f"执行工具: {self.name}, 参数: media_type={media_type}, "
|
||||
f"music_type={music_type}, media_source={media_source}, "
|
||||
f"media_id={media_id}"
|
||||
)
|
||||
|
||||
if not str(media_id or "").strip():
|
||||
return json.dumps({
|
||||
"success": False,
|
||||
"message": "必须提供 media_id"
|
||||
}, ensure_ascii=False)
|
||||
|
||||
try:
|
||||
media_type_enum = MediaType.from_agent(media_type)
|
||||
if not media_type_enum:
|
||||
return json.dumps({
|
||||
"success": False,
|
||||
"message": (
|
||||
f"无效的媒体类型 '{media_type}',"
|
||||
"支持的类型:'movie', 'tv', 'music'"
|
||||
)
|
||||
}, ensure_ascii=False)
|
||||
|
||||
if media_type_enum == MediaType.MUSIC:
|
||||
normalized_music_type = normalize_music_type(music_type)
|
||||
if not normalized_music_type:
|
||||
return json.dumps({
|
||||
"success": False,
|
||||
"message": (
|
||||
"查询音乐详情必须提供 music_type:"
|
||||
"'recording', 'album' 或 'artist'"
|
||||
),
|
||||
}, ensure_ascii=False)
|
||||
if not media_source or not media_id:
|
||||
return json.dumps({
|
||||
"success": False,
|
||||
"message": "查询音乐详情必须同时提供 media_source 和 media_id",
|
||||
}, ensure_ascii=False)
|
||||
|
||||
media_chain = MediaChain()
|
||||
if normalized_music_type == MUSIC_ENTITY_ALBUM:
|
||||
album_info = await media_chain.async_get_music_album(
|
||||
media_source, media_id
|
||||
)
|
||||
if not album_info:
|
||||
return json.dumps({
|
||||
"success": False,
|
||||
"message": f"未找到专辑 {media_source}:{media_id}",
|
||||
}, ensure_ascii=False)
|
||||
return json.dumps(
|
||||
simplify_music_album(album_info),
|
||||
ensure_ascii=False,
|
||||
indent=2,
|
||||
)
|
||||
|
||||
if normalized_music_type == MUSIC_ENTITY_ARTIST:
|
||||
artist_info = await media_chain.async_get_music_artist(
|
||||
media_source, media_id
|
||||
)
|
||||
if not artist_info:
|
||||
return json.dumps({
|
||||
"success": False,
|
||||
"message": f"未找到艺术家 {media_source}:{media_id}",
|
||||
}, ensure_ascii=False)
|
||||
normalized_page = max(1, page or 1)
|
||||
normalized_count = max(1, min(count or 20, 30))
|
||||
result = simplify_music_artist(artist_info)
|
||||
pending = []
|
||||
if include_artist_albums:
|
||||
pending.append((
|
||||
"albums",
|
||||
media_chain.async_get_music_artist_albums(
|
||||
media_source=media_source,
|
||||
media_id=media_id,
|
||||
page=normalized_page,
|
||||
count=normalized_count,
|
||||
album_type=album_type,
|
||||
),
|
||||
))
|
||||
if include_related_artists:
|
||||
pending.append((
|
||||
"related_artists",
|
||||
media_chain.async_get_music_artist_related(
|
||||
media_source=media_source,
|
||||
media_id=media_id,
|
||||
count=normalized_count,
|
||||
),
|
||||
))
|
||||
if pending:
|
||||
values = await asyncio.gather(*(call for _, call in pending))
|
||||
for (key, _), items in zip(pending, values):
|
||||
result[key] = [
|
||||
simplify_music_info(item)
|
||||
if key == "albums"
|
||||
else simplify_music_artist(item)
|
||||
for item in items
|
||||
]
|
||||
return json.dumps(result, ensure_ascii=False, indent=2)
|
||||
|
||||
mediainfo = await media_chain.async_recognize_media(
|
||||
media_source=media_source,
|
||||
media_id=media_id,
|
||||
mtype=MediaType.MUSIC,
|
||||
music_type=normalized_music_type,
|
||||
)
|
||||
if (
|
||||
not mediainfo
|
||||
or getattr(mediainfo, "music_type", MUSIC_ENTITY_RECORDING)
|
||||
!= MUSIC_ENTITY_RECORDING
|
||||
):
|
||||
return json.dumps({
|
||||
"success": False,
|
||||
"message": f"未找到单曲 {media_source}:{media_id}",
|
||||
}, ensure_ascii=False)
|
||||
return json.dumps(
|
||||
simplify_music_info(mediainfo),
|
||||
ensure_ascii=False,
|
||||
indent=2,
|
||||
)
|
||||
|
||||
media_chain = MediaChain()
|
||||
mediainfo = await media_chain.async_recognize_media(
|
||||
media_source=media_source,
|
||||
media_id=media_id,
|
||||
mtype=media_type_enum,
|
||||
)
|
||||
|
||||
if not mediainfo:
|
||||
return json.dumps({
|
||||
"success": False,
|
||||
"message": f"未找到 {media_source} ID {media_id} 的媒体信息"
|
||||
}, ensure_ascii=False)
|
||||
|
||||
# 精简 genres - 只保留名称
|
||||
genres = [g.get("name") for g in (mediainfo.genres or []) if g.get("name")]
|
||||
|
||||
# 精简 directors - 只保留姓名和职位
|
||||
director_source = [d for d in (mediainfo.directors or []) if d.get("name")]
|
||||
directors = [
|
||||
{
|
||||
"name": d.get("name"),
|
||||
"job": d.get("job")
|
||||
}
|
||||
for d in director_source[:DIRECTOR_PREVIEW_LIMIT]
|
||||
]
|
||||
|
||||
# 精简 actors - 只保留姓名和角色
|
||||
actor_source = [a for a in (mediainfo.actors or []) if a.get("name")]
|
||||
actors = [
|
||||
{
|
||||
"name": a.get("name"),
|
||||
"character": a.get("character")
|
||||
}
|
||||
for a in actor_source[:ACTOR_PREVIEW_LIMIT]
|
||||
]
|
||||
|
||||
# 构建基础媒体详情信息
|
||||
result = {
|
||||
"status": mediainfo.status,
|
||||
"genres": genres,
|
||||
"directors": directors,
|
||||
"directors_total": len(director_source),
|
||||
"directors_truncated": len(director_source) > DIRECTOR_PREVIEW_LIMIT,
|
||||
"actors": actors,
|
||||
"actors_total": len(actor_source),
|
||||
"actors_truncated": len(actor_source) > ACTOR_PREVIEW_LIMIT,
|
||||
}
|
||||
|
||||
# 如果是电视剧,添加电视剧特有信息
|
||||
if mediainfo.type == MediaType.TV:
|
||||
# 精简 season_info - 只保留基础摘要
|
||||
season_source = [
|
||||
s for s in (mediainfo.season_info or [])
|
||||
if s.get("season_number") is not None
|
||||
]
|
||||
season_info = [
|
||||
{
|
||||
"season_number": s.get("season_number"),
|
||||
"name": s.get("name"),
|
||||
"episode_count": s.get("episode_count"),
|
||||
"air_date": s.get("air_date")
|
||||
}
|
||||
for s in season_source[:SEASON_PREVIEW_LIMIT]
|
||||
]
|
||||
|
||||
result.update({
|
||||
"number_of_seasons": mediainfo.number_of_seasons,
|
||||
"number_of_episodes": mediainfo.number_of_episodes,
|
||||
"first_air_date": mediainfo.first_air_date,
|
||||
"last_air_date": mediainfo.last_air_date,
|
||||
"season_info": season_info,
|
||||
"season_info_total": len(season_source),
|
||||
"season_info_truncated": len(season_source) > SEASON_PREVIEW_LIMIT,
|
||||
})
|
||||
|
||||
return json.dumps(result, ensure_ascii=False, indent=2)
|
||||
|
||||
except Exception as e:
|
||||
error_message = f"查询媒体详情失败: {str(e)}"
|
||||
logger.error(f"查询媒体详情失败: {e}", exc_info=True)
|
||||
return json.dumps({
|
||||
"success": False,
|
||||
"message": error_message,
|
||||
"media_source": media_source,
|
||||
"media_id": media_id,
|
||||
}, ensure_ascii=False)
|
||||
@@ -1,76 +0,0 @@
|
||||
"""查询可用人格工具。"""
|
||||
|
||||
import json
|
||||
from typing import Optional, Type
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from app.agent.runtime import agent_runtime_manager
|
||||
from app.agent.tools.base import MoviePilotTool
|
||||
from app.agent.tools.tags import ToolTag
|
||||
from app.runtime.log import logger
|
||||
|
||||
|
||||
class QueryPersonasInput(BaseModel):
|
||||
"""查询人格工具的输入参数模型。"""
|
||||
|
||||
query: Optional[str] = Field(
|
||||
None,
|
||||
description=(
|
||||
"Optional search keyword for persona_id, label, description, or aliases. "
|
||||
"Use this when the user asks for a certain speaking style but the exact persona name is unknown."
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
class QueryPersonasTool(MoviePilotTool):
|
||||
name: str = "query_personas"
|
||||
tags: list[str] = [
|
||||
ToolTag.Read,
|
||||
ToolTag.Persona,
|
||||
]
|
||||
description: str = (
|
||||
"List all available personas (人格) and show which one is currently active. "
|
||||
"Use this before switching persona when the user asks for a different speaking style but does not name "
|
||||
"an exact persona_id. The result includes persona_id, label, description, aliases, and whether it is active."
|
||||
)
|
||||
args_schema: Type[BaseModel] = QueryPersonasInput
|
||||
|
||||
def get_tool_message(self, **kwargs) -> Optional[str]:
|
||||
query = kwargs.get("query")
|
||||
if query:
|
||||
return f"查询人格列表: {query}"
|
||||
return "查询人格列表"
|
||||
|
||||
async def run(self, query: Optional[str] = None, **kwargs) -> str:
|
||||
logger.info("执行工具: %s, 参数: query=%s", self.name, query)
|
||||
try:
|
||||
runtime_config = agent_runtime_manager.load_runtime_config()
|
||||
personas = runtime_config.list_personas()
|
||||
|
||||
if query:
|
||||
normalized = query.strip().casefold()
|
||||
personas = [
|
||||
persona
|
||||
for persona in personas
|
||||
if normalized in persona["persona_id"].casefold()
|
||||
or normalized in persona["label"].casefold()
|
||||
or normalized in persona["description"].casefold()
|
||||
or any(normalized in alias.casefold() for alias in persona["aliases"])
|
||||
]
|
||||
|
||||
payload = {
|
||||
"active_persona": runtime_config.active_persona,
|
||||
"count": len(personas),
|
||||
"personas": personas,
|
||||
}
|
||||
return json.dumps(payload, ensure_ascii=False, indent=2)
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.error("查询人格列表失败: %s", e, exc_info=True)
|
||||
return json.dumps(
|
||||
{
|
||||
"success": False,
|
||||
"message": f"查询人格列表时发生错误: {str(e)}",
|
||||
},
|
||||
ensure_ascii=False,
|
||||
)
|
||||
@@ -1,118 +0,0 @@
|
||||
"""查询插件能力工具"""
|
||||
|
||||
import json
|
||||
from typing import Optional, Type
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from app.agent.tools.base import MoviePilotTool
|
||||
from app.agent.tools.tags import ToolTag
|
||||
from app.application.plugin.runtime import get_plugin_manager
|
||||
from app.runtime.log import logger
|
||||
|
||||
|
||||
class QueryPluginCapabilitiesInput(BaseModel):
|
||||
"""查询插件能力工具的输入参数模型"""
|
||||
|
||||
plugin_id: Optional[str] = Field(
|
||||
None,
|
||||
description="Optional plugin ID to query capabilities for a specific plugin. "
|
||||
"If not provided, returns capabilities of all running plugins. "
|
||||
"Use query_installed_plugins tool to get the plugin IDs first.",
|
||||
)
|
||||
|
||||
|
||||
class QueryPluginCapabilitiesTool(MoviePilotTool):
|
||||
name: str = "query_plugin_capabilities"
|
||||
tags: list[str] = [
|
||||
ToolTag.Read,
|
||||
ToolTag.Plugin,
|
||||
ToolTag.Admin,
|
||||
]
|
||||
description: str = (
|
||||
"Query the capabilities of installed plugins, including supported commands and scheduled services. "
|
||||
"Commands are slash-commands (e.g. /xxx) that can be executed via the run_slash_command tool. "
|
||||
"Scheduled services are periodic tasks that can be triggered via the run_scheduler tool. "
|
||||
"Optionally specify a plugin_id to query a specific plugin, or omit to query all running plugins."
|
||||
)
|
||||
require_admin: bool = True
|
||||
args_schema: Type[BaseModel] = QueryPluginCapabilitiesInput
|
||||
|
||||
def get_tool_message(self, **kwargs) -> Optional[str]:
|
||||
"""生成友好的提示消息"""
|
||||
plugin_id = kwargs.get("plugin_id")
|
||||
if plugin_id:
|
||||
return f"查询插件 {plugin_id} 的能力"
|
||||
return "查询所有插件的能力"
|
||||
|
||||
@staticmethod
|
||||
def _load_plugin_capabilities(plugin_id: Optional[str] = None) -> dict:
|
||||
"""读取运行中插件实例暴露的内存能力信息。"""
|
||||
plugin_manager = get_plugin_manager()
|
||||
result = {}
|
||||
|
||||
commands = plugin_manager.get_plugin_commands(pid=plugin_id)
|
||||
if commands:
|
||||
result["commands"] = [
|
||||
{
|
||||
"cmd": cmd.get("cmd"),
|
||||
"desc": cmd.get("desc"),
|
||||
"plugin_id": cmd.get("pid"),
|
||||
**({"data": cmd.get("data")} if cmd.get("data") else {}),
|
||||
}
|
||||
for cmd in commands
|
||||
]
|
||||
|
||||
actions = plugin_manager.get_plugin_actions(pid=plugin_id)
|
||||
if actions:
|
||||
actions_list = []
|
||||
for action_group in actions:
|
||||
actions_list.append(
|
||||
{
|
||||
"plugin_id": action_group.get("plugin_id"),
|
||||
"plugin_name": action_group.get("plugin_name"),
|
||||
"actions": [
|
||||
{
|
||||
"id": action.get("id"),
|
||||
"name": action.get("name"),
|
||||
}
|
||||
for action in action_group.get("actions", [])
|
||||
],
|
||||
}
|
||||
)
|
||||
result["actions"] = actions_list
|
||||
|
||||
services = plugin_manager.get_plugin_services(pid=plugin_id)
|
||||
if services:
|
||||
services_list = []
|
||||
for svc in services:
|
||||
svc_info = {
|
||||
"id": svc.get("id"),
|
||||
"name": svc.get("name"),
|
||||
}
|
||||
trigger = svc.get("trigger")
|
||||
if trigger:
|
||||
svc_info["trigger"] = str(trigger)
|
||||
svc_kwargs = svc.get("kwargs")
|
||||
if svc_kwargs:
|
||||
svc_info["trigger_kwargs"] = {
|
||||
k: str(v) for k, v in svc_kwargs.items()
|
||||
}
|
||||
services_list.append(svc_info)
|
||||
result["services"] = services_list
|
||||
|
||||
return result
|
||||
|
||||
async def run(self, plugin_id: Optional[str] = None, **kwargs) -> str:
|
||||
logger.info(f"执行工具: {self.name}, 参数: plugin_id={plugin_id}")
|
||||
try:
|
||||
result = self._load_plugin_capabilities(plugin_id)
|
||||
if not result:
|
||||
if plugin_id:
|
||||
return f"插件 {plugin_id} 没有注册任何命令、动作或定时服务"
|
||||
return "当前没有运行中的插件注册了命令、动作或定时服务"
|
||||
|
||||
return json.dumps(result, ensure_ascii=False, indent=2)
|
||||
except Exception as e:
|
||||
logger.error(f"查询插件能力失败: {e}", exc_info=True)
|
||||
return f"查询插件能力时发生错误: {str(e)}"
|
||||
@@ -1,90 +0,0 @@
|
||||
"""查询插件配置工具"""
|
||||
|
||||
import json
|
||||
from typing import Optional, Type
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from app.agent.tools.base import MoviePilotTool
|
||||
from app.agent.tools.tags import ToolTag
|
||||
from app.agent.tools.impl._plugin_tool_utils import get_plugin_snapshot
|
||||
from app.application.plugin.runtime import get_plugin_manager
|
||||
from app.runtime.log import logger
|
||||
|
||||
|
||||
class QueryPluginConfigInput(BaseModel):
|
||||
"""查询插件配置工具的输入参数模型"""
|
||||
|
||||
plugin_id: str = Field(
|
||||
...,
|
||||
description="The plugin ID to query. Use query_installed_plugins first to discover valid plugin IDs.",
|
||||
)
|
||||
|
||||
|
||||
class QueryPluginConfigTool(MoviePilotTool):
|
||||
name: str = "query_plugin_config"
|
||||
tags: list[str] = [
|
||||
ToolTag.Read,
|
||||
ToolTag.Plugin,
|
||||
ToolTag.Admin,
|
||||
]
|
||||
description: str = (
|
||||
"Query the saved configuration of an installed plugin. "
|
||||
"Returns the current saved config and, when available, the plugin's default config model. "
|
||||
"Use this before update_plugin_config so you only change the intended keys."
|
||||
)
|
||||
require_admin: bool = True
|
||||
args_schema: Type[BaseModel] = QueryPluginConfigInput
|
||||
|
||||
def get_tool_message(self, **kwargs) -> Optional[str]:
|
||||
"""生成友好的提示消息"""
|
||||
plugin_id = kwargs.get("plugin_id", "")
|
||||
return f"查询插件配置: {plugin_id}"
|
||||
|
||||
@staticmethod
|
||||
def _query_plugin_config(plugin_id: str) -> str:
|
||||
"""
|
||||
读取插件已保存配置,并尽量补充默认配置模型方便后续精确修改。
|
||||
"""
|
||||
plugin_info = get_plugin_snapshot(plugin_id)
|
||||
if not plugin_info:
|
||||
return json.dumps(
|
||||
{
|
||||
"success": False,
|
||||
"message": f"插件 {plugin_id} 不存在,请先使用 query_installed_plugins 查询有效插件 ID",
|
||||
},
|
||||
ensure_ascii=False,
|
||||
)
|
||||
|
||||
plugin_manager = get_plugin_manager()
|
||||
saved_config = plugin_manager.get_plugin_config(plugin_id) or {}
|
||||
result = {
|
||||
"success": True,
|
||||
**plugin_info,
|
||||
"config": saved_config,
|
||||
}
|
||||
|
||||
# get_form 的 model 通常就是插件期望的配置结构,适合作为修改前的键参考。
|
||||
plugin_instance = plugin_manager.running_plugins.get(plugin_id)
|
||||
if plugin_instance and hasattr(plugin_instance, "get_form"):
|
||||
try:
|
||||
_form_schema, default_model = plugin_instance.get_form()
|
||||
if default_model is not None:
|
||||
result["default_model"] = default_model
|
||||
except Exception as err:
|
||||
logger.warning(f"读取插件 {plugin_id} 默认配置模型失败: {err}")
|
||||
|
||||
return json.dumps(result, ensure_ascii=False, indent=2, default=str)
|
||||
|
||||
async def run(self, plugin_id: str, **kwargs) -> str:
|
||||
logger.info(f"执行工具: {self.name}, 参数: plugin_id={plugin_id}")
|
||||
|
||||
try:
|
||||
# 插件配置来自内存配置缓存和运行态插件实例,直接读取即可。
|
||||
return self._query_plugin_config(plugin_id)
|
||||
except Exception as e:
|
||||
logger.error(f"查询插件配置失败: {e}", exc_info=True)
|
||||
return json.dumps(
|
||||
{"success": False, "message": f"查询插件配置时发生错误: {str(e)}"},
|
||||
ensure_ascii=False,
|
||||
)
|
||||
@@ -1,159 +0,0 @@
|
||||
"""查询插件数据工具"""
|
||||
|
||||
import json
|
||||
from typing import Optional, Type
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from app.agent.tools.base import MoviePilotTool
|
||||
from app.agent.tools.impl._plugin_tool_utils import (
|
||||
PLUGIN_DATA_KEY_PREVIEW_LIMIT,
|
||||
build_preview_payload,
|
||||
get_plugin_snapshot,
|
||||
)
|
||||
from app.agent.tools.tags import ToolTag
|
||||
from app.runtime.log import logger
|
||||
|
||||
|
||||
class QueryPluginDataInput(BaseModel):
|
||||
"""查询插件数据工具的输入参数模型"""
|
||||
|
||||
plugin_id: str = Field(
|
||||
...,
|
||||
description="The plugin ID to query. Use query_installed_plugins first to discover valid plugin IDs.",
|
||||
)
|
||||
key: Optional[str] = Field(
|
||||
None,
|
||||
description="Optional plugin data key. If omitted, returns all plugin data entries for the plugin.",
|
||||
)
|
||||
max_chars: Optional[int] = Field(
|
||||
None,
|
||||
description="Maximum number of preview characters to return when plugin data is too large. Default 12000, capped at 50000.",
|
||||
)
|
||||
|
||||
|
||||
class QueryPluginDataTool(MoviePilotTool):
|
||||
name: str = "query_plugin_data"
|
||||
tags: list[str] = [
|
||||
ToolTag.Read,
|
||||
ToolTag.Plugin,
|
||||
ToolTag.Admin,
|
||||
]
|
||||
description: str = (
|
||||
"Query persisted data of an installed plugin. "
|
||||
"Optionally specify a key to read a single data item; otherwise all plugin data entries are returned. "
|
||||
"When the result is too large, the tool automatically truncates it and returns a preview instead."
|
||||
)
|
||||
require_admin: bool = True
|
||||
args_schema: Type[BaseModel] = QueryPluginDataInput
|
||||
|
||||
def get_tool_message(self, **kwargs) -> Optional[str]:
|
||||
"""生成友好的提示消息"""
|
||||
plugin_id = kwargs.get("plugin_id", "")
|
||||
key = kwargs.get("key")
|
||||
if key:
|
||||
return f"查询插件数据: {plugin_id}.{key}"
|
||||
return f"查询插件全部数据: {plugin_id}"
|
||||
|
||||
async def _query_plugin_data(
|
||||
self,
|
||||
plugin_id: str,
|
||||
key: Optional[str] = None,
|
||||
max_chars: Optional[int] = None,
|
||||
) -> str:
|
||||
"""
|
||||
插件数据改走异步 ORM 查询,避免再套一层线程池。
|
||||
"""
|
||||
plugin_info = get_plugin_snapshot(plugin_id)
|
||||
if not plugin_info:
|
||||
return json.dumps(
|
||||
{
|
||||
"success": False,
|
||||
"message": f"插件 {plugin_id} 不存在,请先使用 query_installed_plugins 查询有效插件 ID",
|
||||
},
|
||||
ensure_ascii=False,
|
||||
)
|
||||
|
||||
if key:
|
||||
value = await self.data.plugin_data.get(plugin_id, key)
|
||||
if value is None:
|
||||
return json.dumps(
|
||||
{
|
||||
"success": True,
|
||||
**plugin_info,
|
||||
"key": key,
|
||||
"found": False,
|
||||
"message": f"插件 {plugin_id} 没有数据项 {key}",
|
||||
},
|
||||
ensure_ascii=False,
|
||||
indent=2,
|
||||
)
|
||||
|
||||
truncated, total_chars, returned_chars, preview = build_preview_payload(
|
||||
value, max_chars
|
||||
)
|
||||
result = {
|
||||
"success": True,
|
||||
**plugin_info,
|
||||
"key": key,
|
||||
"found": True,
|
||||
"truncated": truncated,
|
||||
"total_chars": total_chars,
|
||||
"returned_chars": returned_chars,
|
||||
}
|
||||
if truncated:
|
||||
result["value_preview"] = preview
|
||||
result["message"] = "插件数据内容过大,已截断预览"
|
||||
else:
|
||||
result["value"] = value
|
||||
return json.dumps(result, ensure_ascii=False, indent=2, default=str)
|
||||
|
||||
data_map = await self.data.plugin_data.list(plugin_id)
|
||||
keys = list(data_map.keys())
|
||||
key_preview = keys[:PLUGIN_DATA_KEY_PREVIEW_LIMIT]
|
||||
|
||||
result = {
|
||||
"success": True,
|
||||
**plugin_info,
|
||||
"count": len(data_map),
|
||||
"keys": key_preview,
|
||||
"keys_truncated": len(keys) > PLUGIN_DATA_KEY_PREVIEW_LIMIT,
|
||||
}
|
||||
|
||||
if not data_map:
|
||||
result["data"] = {}
|
||||
result["truncated"] = False
|
||||
return json.dumps(result, ensure_ascii=False, indent=2, default=str)
|
||||
|
||||
truncated, total_chars, returned_chars, preview = build_preview_payload(
|
||||
data_map, max_chars
|
||||
)
|
||||
result["truncated"] = truncated
|
||||
result["total_chars"] = total_chars
|
||||
result["returned_chars"] = returned_chars
|
||||
if truncated:
|
||||
result["data_preview"] = preview
|
||||
result["message"] = "插件数据内容过大,已截断。请传入 key 精确查询单个数据项。"
|
||||
else:
|
||||
result["data"] = data_map
|
||||
return json.dumps(result, ensure_ascii=False, indent=2, default=str)
|
||||
|
||||
async def run(
|
||||
self,
|
||||
plugin_id: str,
|
||||
key: Optional[str] = None,
|
||||
max_chars: Optional[int] = None,
|
||||
**kwargs,
|
||||
) -> str:
|
||||
logger.info(
|
||||
f"执行工具: {self.name}, 参数: plugin_id={plugin_id}, key={key}"
|
||||
)
|
||||
|
||||
try:
|
||||
return await self._query_plugin_data(plugin_id, key, max_chars)
|
||||
except Exception as e:
|
||||
logger.error(f"查询插件数据失败: {e}", exc_info=True)
|
||||
return json.dumps(
|
||||
{"success": False, "message": f"查询插件数据时发生错误: {str(e)}"},
|
||||
ensure_ascii=False,
|
||||
)
|
||||
@@ -1,223 +0,0 @@
|
||||
"""查询热门订阅工具"""
|
||||
|
||||
import json
|
||||
from typing import Optional, Type
|
||||
|
||||
import cn2an
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from app.agent.tools.base import MoviePilotTool
|
||||
from app.agent.tools.tags import ToolTag
|
||||
from app.domain.context import MediaInfo
|
||||
from app.adapters.external.server import MoviePilotServerHelper
|
||||
from app.runtime.log import logger
|
||||
from app.schemas.types import MUSIC_ENTITY_RECORDING, MediaType, media_type_to_agent
|
||||
from app.domain.media import normalize_music_type
|
||||
|
||||
MAX_PAGE_SIZE = 50
|
||||
|
||||
|
||||
class QueryPopularSubscribesInput(BaseModel):
|
||||
"""查询热门订阅工具的输入参数模型"""
|
||||
media_type: str = Field(..., description="Allowed values: movie, tv, music")
|
||||
music_type: Optional[str] = Field(
|
||||
None,
|
||||
description="Optional music entity filter: recording or album",
|
||||
)
|
||||
page: Optional[int] = Field(1, description="Page number for pagination (default: 1)")
|
||||
count: Optional[int] = Field(30, description="Number of items per page (default: 30, max: 50)")
|
||||
min_sub: Optional[int] = Field(None, description="Minimum number of subscribers filter (optional, e.g., 5)")
|
||||
genre_id: Optional[int] = Field(None, description="Filter by genre ID (optional)")
|
||||
min_rating: Optional[float] = Field(None, description="Minimum rating filter (optional, e.g., 7.5)")
|
||||
max_rating: Optional[float] = Field(None, description="Maximum rating filter (optional, e.g., 10.0)")
|
||||
sort_type: Optional[str] = Field(None, description="Sort type (optional, e.g., 'count', 'rating')")
|
||||
|
||||
|
||||
class QueryPopularSubscribesTool(MoviePilotTool):
|
||||
"""查询社区热门的影视、单曲或专辑订阅。"""
|
||||
|
||||
name: str = "query_popular_subscribes"
|
||||
tags: list[str] = [
|
||||
ToolTag.Read,
|
||||
ToolTag.Subscription,
|
||||
ToolTag.Recommendation,
|
||||
]
|
||||
description: str = (
|
||||
"Query popular movie, TV, recording, or album subscriptions from shared statistics. "
|
||||
"Music results can be filtered by recording or album entity type."
|
||||
)
|
||||
args_schema: Type[BaseModel] = QueryPopularSubscribesInput
|
||||
|
||||
def get_tool_message(self, **kwargs) -> Optional[str]:
|
||||
"""根据查询参数生成友好的提示消息"""
|
||||
media_type = kwargs.get("media_type", "")
|
||||
page = kwargs.get("page", 1)
|
||||
min_sub = kwargs.get("min_sub")
|
||||
min_rating = kwargs.get("min_rating")
|
||||
max_rating = kwargs.get("max_rating")
|
||||
|
||||
parts = [f"查询热门订阅 [{media_type}]"]
|
||||
|
||||
if min_sub:
|
||||
parts.append(f"最少订阅: {min_sub}")
|
||||
if min_rating:
|
||||
parts.append(f"最低评分: {min_rating}")
|
||||
if max_rating:
|
||||
parts.append(f"最高评分: {max_rating}")
|
||||
if page > 1:
|
||||
parts.append(f"第{page}页")
|
||||
|
||||
return " | ".join(parts) if len(parts) > 1 else parts[0]
|
||||
|
||||
async def run(self, media_type: str,
|
||||
music_type: Optional[str] = None,
|
||||
page: Optional[int] = 1,
|
||||
count: Optional[int] = 30,
|
||||
min_sub: Optional[int] = None,
|
||||
genre_id: Optional[int] = None,
|
||||
min_rating: Optional[float] = None,
|
||||
max_rating: Optional[float] = None,
|
||||
sort_type: Optional[str] = None, **kwargs) -> str:
|
||||
"""查询有界的订阅统计并保留音乐实体身份。"""
|
||||
logger.info(
|
||||
f"执行工具: {self.name}, 参数: media_type={media_type}, page={page}, count={count}, min_sub={min_sub}, "
|
||||
f"genre_id={genre_id}, min_rating={min_rating}, max_rating={max_rating}, sort_type={sort_type}")
|
||||
|
||||
try:
|
||||
if page is None or page < 1:
|
||||
page = 1
|
||||
if count is None or count < 1:
|
||||
count = 30
|
||||
# 外部统计接口支持传入 count,这里做硬上限,避免 Agent 一次拉取过多结果。
|
||||
count = min(count, MAX_PAGE_SIZE)
|
||||
media_type_enum = MediaType.from_agent(media_type)
|
||||
if not media_type_enum:
|
||||
return f"错误:无效的媒体类型 '{media_type}',支持的类型:'movie', 'tv', 'music'"
|
||||
normalized_music_type = None
|
||||
if music_type:
|
||||
normalized_music_type = normalize_music_type(
|
||||
music_type,
|
||||
allow_artist=False,
|
||||
)
|
||||
if not normalized_music_type:
|
||||
return (
|
||||
f"错误:无效的音乐实体类型 '{music_type}',"
|
||||
"支持的类型:'recording', 'album'"
|
||||
)
|
||||
if media_type_enum != MediaType.MUSIC:
|
||||
return "错误:music_type 仅能与 media_type='music' 一起使用"
|
||||
|
||||
subscribes = await MoviePilotServerHelper.async_get_subscribe_statistic(
|
||||
stype=media_type_enum.to_agent(),
|
||||
page=page,
|
||||
count=count,
|
||||
genre_id=genre_id,
|
||||
min_rating=min_rating,
|
||||
max_rating=max_rating,
|
||||
sort_type=sort_type
|
||||
)
|
||||
|
||||
if not subscribes:
|
||||
return "未找到热门订阅数据(可能订阅统计功能未启用)"
|
||||
|
||||
# 转换为MediaInfo格式并过滤
|
||||
ret_medias = []
|
||||
for sub in subscribes:
|
||||
# 订阅人数
|
||||
subscriber_count = sub.get("count", 0)
|
||||
# 如果设置了最小订阅人数,进行过滤
|
||||
if min_sub and subscriber_count < min_sub:
|
||||
continue
|
||||
|
||||
media = MediaInfo()
|
||||
raw_type = str(sub.get("type") or "").strip().lower()
|
||||
if raw_type in ["music", "音乐"]:
|
||||
sub_music_type = normalize_music_type(
|
||||
sub.get("music_type") or MUSIC_ENTITY_RECORDING,
|
||||
allow_artist=False,
|
||||
)
|
||||
if not sub_music_type:
|
||||
logger.warning(f"跳过未知音乐订阅实体: {sub.get('music_type')}")
|
||||
continue
|
||||
if normalized_music_type and sub_music_type != normalized_music_type:
|
||||
continue
|
||||
artists = sub.get("artists") or []
|
||||
if isinstance(artists, str):
|
||||
artists = [artists]
|
||||
if not artists and sub.get("artist"):
|
||||
artists = [sub.get("artist")]
|
||||
ret_medias.append({
|
||||
"type": "music",
|
||||
"title": sub.get("name"),
|
||||
"year": sub.get("year"),
|
||||
"music_type": sub_music_type,
|
||||
"artists": artists,
|
||||
"album": sub.get("album"),
|
||||
"total_tracks": sub.get("total_tracks"),
|
||||
"media_source": sub.get("media_source"),
|
||||
"media_id": sub.get("media_id"),
|
||||
"poster_path": sub.get("poster"),
|
||||
"backdrop_path": sub.get("backdrop"),
|
||||
"subscriber_count": subscriber_count,
|
||||
"popularity": subscriber_count,
|
||||
})
|
||||
continue
|
||||
if raw_type in ["movie", "电影"]:
|
||||
media.type = MediaType.MOVIE
|
||||
elif raw_type in ["tv", "电视剧"]:
|
||||
media.type = MediaType.TV
|
||||
else:
|
||||
# 跳过无法识别类型的数据,避免单条脏数据导致整批失败
|
||||
logger.warning(f"跳过未知媒体类型: {sub.get('type')}")
|
||||
continue
|
||||
# 处理标题
|
||||
title = sub.get("name")
|
||||
season = sub.get("season")
|
||||
if season not in (None, "") and int(season) != 1:
|
||||
# 小写数据转大写
|
||||
season_str = cn2an.an2cn(season, "low")
|
||||
title = f"{title} 第{season_str}季"
|
||||
media.title = title
|
||||
media.year = sub.get("year")
|
||||
media.media_source = sub.get("media_source")
|
||||
media.media_id = sub.get("media_id")
|
||||
media.season = sub.get("season")
|
||||
media.vote_average = sub.get("vote")
|
||||
media.poster_path = sub.get("poster")
|
||||
media.backdrop_path = sub.get("backdrop")
|
||||
media.popularity = subscriber_count
|
||||
ret_medias.append(media)
|
||||
|
||||
if not ret_medias:
|
||||
return "未找到符合条件的热门订阅"
|
||||
|
||||
# 转换为字典格式,只保留关键信息
|
||||
simplified_medias = []
|
||||
for media in ret_medias:
|
||||
if isinstance(media, dict):
|
||||
simplified_medias.append(media)
|
||||
continue
|
||||
media_dict = media.to_dict()
|
||||
simplified = {
|
||||
"type": media_type_to_agent(media_dict.get("type")),
|
||||
"title": media_dict.get("title"),
|
||||
"year": media_dict.get("year"),
|
||||
"media_source": media_dict.get("media_source"),
|
||||
"media_id": media_dict.get("media_id"),
|
||||
"season": media_dict.get("season"),
|
||||
"vote_average": media_dict.get("vote_average"),
|
||||
"poster_path": media_dict.get("poster_path"),
|
||||
"backdrop_path": media_dict.get("backdrop_path"),
|
||||
"popularity": media_dict.get("popularity"), # 订阅人数
|
||||
"subscriber_count": media_dict.get("popularity") # 明确标注为订阅人数
|
||||
}
|
||||
simplified_medias.append(simplified)
|
||||
|
||||
result_json = json.dumps(simplified_medias, ensure_ascii=False, indent=2)
|
||||
|
||||
pagination_info = f"第 {page} 页,每页 {count} 条,共 {len(simplified_medias)} 条结果"
|
||||
|
||||
return f"{pagination_info}\n\n{result_json}"
|
||||
except Exception as e:
|
||||
logger.error(f"查询热门订阅失败: {e}", exc_info=True)
|
||||
return f"查询热门订阅时发生错误: {str(e)}"
|
||||
@@ -1,106 +0,0 @@
|
||||
"""查询过滤规则组工具。"""
|
||||
|
||||
import json
|
||||
from typing import List, Optional, Type
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from app.agent.tools.base import MoviePilotTool
|
||||
from app.agent.tools.impl._filter_rule_utils import (
|
||||
RULE_STRING_SYNTAX,
|
||||
collect_rule_group_usages,
|
||||
get_rule_groups,
|
||||
serialize_rule_group,
|
||||
)
|
||||
from app.agent.tools.tags import ToolTag
|
||||
from app.runtime.log import logger
|
||||
|
||||
|
||||
class QueryRuleGroupsInput(BaseModel):
|
||||
"""查询规则组工具的输入参数模型"""
|
||||
|
||||
group_names: Optional[List[str]] = Field(
|
||||
None,
|
||||
description="Optional list of rule group names to query. If omitted, return all rule groups.",
|
||||
)
|
||||
include_usage: bool = Field(
|
||||
True,
|
||||
description="Whether to include where each rule group is referenced by global settings or subscriptions.",
|
||||
)
|
||||
|
||||
|
||||
class QueryRuleGroupsTool(MoviePilotTool):
|
||||
name: str = "query_rule_groups"
|
||||
tags: list[str] = [
|
||||
ToolTag.Read,
|
||||
ToolTag.FilterRule,
|
||||
]
|
||||
description: str = (
|
||||
"Query filter rule groups (过滤规则组 / 优先级规则组). "
|
||||
"Each rule group contains a rule_string made of built-in rules and/or custom rules. "
|
||||
"Inside one level use '&', '|', '!' and optional parentheses; use '>' between levels. "
|
||||
"Levels are evaluated from left to right, and the first matched level wins. "
|
||||
"The result includes parsed levels and syntax guidance so the agent can learn existing patterns before writing a new rule group."
|
||||
)
|
||||
args_schema: Type[BaseModel] = QueryRuleGroupsInput
|
||||
|
||||
def get_tool_message(self, **kwargs) -> Optional[str]:
|
||||
group_names = kwargs.get("group_names") or []
|
||||
if group_names:
|
||||
return f"查询规则组: {', '.join(group_names)}"
|
||||
return "查询所有规则组"
|
||||
|
||||
async def run(
|
||||
self,
|
||||
group_names: Optional[List[str]] = None,
|
||||
include_usage: bool = True,
|
||||
**kwargs,
|
||||
) -> str:
|
||||
logger.info(f"执行工具: {self.name}")
|
||||
|
||||
try:
|
||||
rule_groups = get_rule_groups()
|
||||
if group_names:
|
||||
target_names = set(group_names)
|
||||
rule_groups = [
|
||||
group for group in rule_groups if group.name in target_names
|
||||
]
|
||||
|
||||
usage_map = {}
|
||||
if include_usage:
|
||||
usage_map = await collect_rule_group_usages(
|
||||
self.data.subscriptions,
|
||||
[group.name for group in rule_groups if group.name]
|
||||
)
|
||||
|
||||
serialized = [
|
||||
serialize_rule_group(group, usage_map.get(group.name))
|
||||
for group in rule_groups
|
||||
]
|
||||
message = (
|
||||
f"找到 {len(serialized)} 个规则组"
|
||||
if serialized
|
||||
else "未找到任何规则组"
|
||||
)
|
||||
|
||||
return json.dumps(
|
||||
{
|
||||
"success": True,
|
||||
"message": message,
|
||||
"count": len(serialized),
|
||||
"rule_string_syntax": RULE_STRING_SYNTAX,
|
||||
"rule_groups": serialized,
|
||||
},
|
||||
ensure_ascii=False,
|
||||
indent=2,
|
||||
)
|
||||
except Exception as exc:
|
||||
logger.error(f"查询规则组失败: {exc}", exc_info=True)
|
||||
return json.dumps(
|
||||
{
|
||||
"success": False,
|
||||
"message": f"查询规则组失败: {exc}",
|
||||
"rule_groups": [],
|
||||
},
|
||||
ensure_ascii=False,
|
||||
)
|
||||
@@ -1,81 +0,0 @@
|
||||
"""查询定时服务工具"""
|
||||
|
||||
import json
|
||||
from typing import Optional, Type
|
||||
|
||||
from pydantic import BaseModel
|
||||
|
||||
from app.agent.tools.base import MoviePilotTool
|
||||
from app.agent.tools.tags import ToolTag
|
||||
from app.runtime.log import logger
|
||||
|
||||
|
||||
class QuerySchedulersInput(BaseModel):
|
||||
"""查询运行时定时服务的输入参数模型。"""
|
||||
|
||||
|
||||
class QuerySchedulersTool(MoviePilotTool):
|
||||
"""查询系统、插件和工作流注册的运行时定时服务。"""
|
||||
|
||||
name: str = "query_schedulers"
|
||||
tags: list[str] = [
|
||||
ToolTag.Read,
|
||||
ToolTag.Scheduler,
|
||||
ToolTag.Admin,
|
||||
]
|
||||
description: str = (
|
||||
"Query runtime scheduler services registered by MoviePilot system components, "
|
||||
"plugins, and workflows. It excludes user-created autonomous agent tasks; use "
|
||||
"query_agent_tasks for reminders, monitoring tasks, and other agent schedules."
|
||||
)
|
||||
args_schema: Type[BaseModel] = QuerySchedulersInput
|
||||
require_admin: bool = True
|
||||
|
||||
def get_tool_message(self, **kwargs: object) -> Optional[str]:
|
||||
"""生成查询运行时定时服务的提示消息。"""
|
||||
return "查询系统定时服务"
|
||||
|
||||
async def run(self, **kwargs: object) -> str:
|
||||
"""查询非 Agent 自主任务的运行时定时服务。"""
|
||||
logger.info(f"执行工具: {self.name}")
|
||||
try:
|
||||
from app.application.scheduling import (
|
||||
AGENT_TASK_JOB_PREFIX,
|
||||
list_scheduler_jobs,
|
||||
)
|
||||
|
||||
agent_task_prefix = f"{AGENT_TASK_JOB_PREFIX}-"
|
||||
schedulers = [
|
||||
scheduler_item
|
||||
for scheduler_item in list_scheduler_jobs()
|
||||
if not str(scheduler_item.id or "").startswith(agent_task_prefix)
|
||||
]
|
||||
if schedulers:
|
||||
schedulers_list = [
|
||||
{
|
||||
"id": scheduler_item.id,
|
||||
"name": scheduler_item.name,
|
||||
"provider": scheduler_item.provider,
|
||||
"status": scheduler_item.status,
|
||||
"next_run": scheduler_item.next_run,
|
||||
}
|
||||
for scheduler_item in schedulers
|
||||
]
|
||||
result_json = json.dumps(schedulers_list, ensure_ascii=False, indent=2)
|
||||
total_count = len(schedulers_list)
|
||||
if total_count > 30:
|
||||
limited_schedulers = schedulers_list[:30]
|
||||
limited_json = json.dumps(
|
||||
limited_schedulers,
|
||||
ensure_ascii=False,
|
||||
indent=2,
|
||||
)
|
||||
return (
|
||||
f"注意:查询结果共找到 {total_count} 条,为节省上下文空间,"
|
||||
f"仅显示前 30 条结果。\n\n{limited_json}"
|
||||
)
|
||||
return result_json
|
||||
return "未找到系统、插件或工作流定时服务"
|
||||
except Exception as e:
|
||||
logger.error(f"查询定时服务失败: {e}", exc_info=True)
|
||||
return f"查询定时服务时发生错误: {str(e)}"
|
||||
@@ -1,190 +0,0 @@
|
||||
"""查询站点用户数据工具"""
|
||||
|
||||
import json
|
||||
from typing import Optional, Type
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from app.agent.tools.base import MoviePilotTool
|
||||
from app.agent.tools.tags import ToolTag
|
||||
from app.domain import site as site_rules
|
||||
from app.runtime.log import logger
|
||||
from app.schemas.common import JsonData
|
||||
|
||||
SITE_USERDATA_DETAIL_PREVIEW_LIMIT = 10
|
||||
|
||||
|
||||
def _preview_list(value, limit: int = SITE_USERDATA_DETAIL_PREVIEW_LIMIT) -> tuple[list, int, bool]:
|
||||
"""返回列表字段预览,避免做种明细或未读消息一次性撑大工具结果。"""
|
||||
items = list(value) if isinstance(value, (list, tuple)) else []
|
||||
return items[:limit], len(items), len(items) > limit
|
||||
|
||||
|
||||
def _sort_text(value: JsonData) -> str:
|
||||
"""把用户数据排序字段规范为可比较文本。"""
|
||||
return value if isinstance(value, str) else ""
|
||||
|
||||
|
||||
class QuerySiteUserdataInput(BaseModel):
|
||||
"""查询站点用户数据工具的输入参数模型"""
|
||||
|
||||
site_id: int = Field(
|
||||
...,
|
||||
description="The ID of the site to query user data for (can be obtained from query_sites tool)",
|
||||
)
|
||||
workdate: Optional[str] = Field(
|
||||
None,
|
||||
description="Work date to query (optional, format: 'YYYY-MM-DD', if not specified returns latest data)",
|
||||
)
|
||||
|
||||
|
||||
class QuerySiteUserdataTool(MoviePilotTool):
|
||||
name: str = "query_site_userdata"
|
||||
tags: list[str] = [
|
||||
ToolTag.Read,
|
||||
ToolTag.Site,
|
||||
ToolTag.Admin,
|
||||
]
|
||||
description: str = "Query user data for a specific site including username, user level, upload/download statistics, seeding information, bonus points, and other account details. Supports querying data for a specific date or latest data."
|
||||
require_admin: bool = True
|
||||
args_schema: Type[BaseModel] = QuerySiteUserdataInput
|
||||
|
||||
def get_tool_message(self, **kwargs) -> Optional[str]:
|
||||
"""根据查询参数生成友好的提示消息"""
|
||||
site_id = kwargs.get("site_id")
|
||||
workdate = kwargs.get("workdate")
|
||||
|
||||
message = f"查询站点 #{site_id} 的用户数据"
|
||||
if workdate:
|
||||
message += f" (日期: {workdate})"
|
||||
else:
|
||||
message += " (最新数据)"
|
||||
|
||||
return message
|
||||
|
||||
async def run(self, site_id: int, workdate: Optional[str] = None, **kwargs) -> str:
|
||||
logger.info(
|
||||
f"执行工具: {self.name}, 参数: site_id={site_id}, workdate={workdate}"
|
||||
)
|
||||
|
||||
try:
|
||||
repository = self.data.sites
|
||||
site = await repository.async_get(site_id)
|
||||
if not site:
|
||||
return json.dumps(
|
||||
{"success": False, "message": f"站点不存在: {site_id}"},
|
||||
ensure_ascii=False,
|
||||
)
|
||||
|
||||
site_domain = site.domain or site_rules.extract_domain(site.url)
|
||||
user_data_list = await repository.async_get_userdata_by_domain(
|
||||
domain=site_domain, workdate=workdate
|
||||
)
|
||||
|
||||
if not user_data_list:
|
||||
return json.dumps(
|
||||
{
|
||||
"success": False,
|
||||
"message": f"站点 {site.name} ({site_domain}) 暂无用户数据",
|
||||
"site_id": site_id,
|
||||
"site_name": site.name,
|
||||
"site_domain": site_domain,
|
||||
"workdate": workdate,
|
||||
},
|
||||
ensure_ascii=False,
|
||||
)
|
||||
|
||||
formatted_user_data: list[dict[str, JsonData]] = []
|
||||
|
||||
for user_data in user_data_list:
|
||||
# 格式化上传/下载量(转换为可读格式)
|
||||
upload_gb = user_data.upload / (1024**3) if user_data.upload else 0
|
||||
download_gb = (
|
||||
user_data.download / (1024**3) if user_data.download else 0
|
||||
)
|
||||
seeding_size_gb = (
|
||||
user_data.seeding_size / (1024**3)
|
||||
if user_data.seeding_size
|
||||
else 0
|
||||
)
|
||||
leeching_size_gb = (
|
||||
user_data.leeching_size / (1024**3)
|
||||
if user_data.leeching_size
|
||||
else 0
|
||||
)
|
||||
|
||||
seeding_preview, seeding_count, seeding_truncated = _preview_list(
|
||||
user_data.seeding_info
|
||||
)
|
||||
unread_preview, unread_count, unread_truncated = _preview_list(
|
||||
user_data.message_unread_contents
|
||||
)
|
||||
|
||||
user_data_dict: dict[str, JsonData] = {
|
||||
"domain": user_data.domain,
|
||||
"name": user_data.name,
|
||||
"username": user_data.username,
|
||||
"userid": user_data.userid,
|
||||
"user_level": user_data.user_level,
|
||||
"join_at": user_data.join_at,
|
||||
"bonus": user_data.bonus,
|
||||
"upload": user_data.upload,
|
||||
"upload_gb": round(upload_gb, 2),
|
||||
"download": user_data.download,
|
||||
"download_gb": round(download_gb, 2),
|
||||
"ratio": round(user_data.ratio, 2) if user_data.ratio else 0,
|
||||
"seeding": int(user_data.seeding) if user_data.seeding else 0,
|
||||
"leeching": int(user_data.leeching)
|
||||
if user_data.leeching
|
||||
else 0,
|
||||
"seeding_size": user_data.seeding_size,
|
||||
"seeding_size_gb": round(seeding_size_gb, 2),
|
||||
"leeching_size": user_data.leeching_size,
|
||||
"leeching_size_gb": round(leeching_size_gb, 2),
|
||||
"seeding_info_count": seeding_count,
|
||||
"seeding_info": seeding_preview,
|
||||
"seeding_info_truncated": seeding_truncated,
|
||||
"message_unread": user_data.message_unread,
|
||||
"message_unread_contents_count": unread_count,
|
||||
"message_unread_contents": unread_preview,
|
||||
"message_unread_contents_truncated": unread_truncated,
|
||||
"err_msg": user_data.err_msg,
|
||||
"updated_day": user_data.updated_day,
|
||||
"updated_time": user_data.updated_time,
|
||||
}
|
||||
formatted_user_data.append(user_data_dict)
|
||||
|
||||
# 如果有多条数据,只返回最新的(按更新时间排序)
|
||||
message: Optional[str] = None
|
||||
if len(formatted_user_data) > 1:
|
||||
formatted_user_data.sort(
|
||||
key=lambda item: (
|
||||
_sort_text(item.get("updated_day")),
|
||||
_sort_text(item.get("updated_time")),
|
||||
),
|
||||
reverse=True,
|
||||
)
|
||||
message = f"找到 {len(formatted_user_data)} 条数据,显示最新的一条"
|
||||
formatted_user_data = [formatted_user_data[0]]
|
||||
|
||||
result: dict[str, JsonData] = {
|
||||
"success": True,
|
||||
"site_id": site_id,
|
||||
"site_name": site.name,
|
||||
"site_domain": site_domain,
|
||||
"workdate": workdate,
|
||||
"data_count": len(user_data_list),
|
||||
"user_data": formatted_user_data,
|
||||
}
|
||||
if message:
|
||||
result["message"] = message
|
||||
|
||||
return json.dumps(result, ensure_ascii=False, indent=2)
|
||||
|
||||
except Exception as e:
|
||||
error_message = f"查询站点用户数据失败: {str(e)}"
|
||||
logger.error(f"查询站点用户数据失败: {e}", exc_info=True)
|
||||
return json.dumps(
|
||||
{"success": False, "message": error_message, "site_id": site_id},
|
||||
ensure_ascii=False,
|
||||
)
|
||||
@@ -1,110 +0,0 @@
|
||||
"""查询站点工具"""
|
||||
|
||||
import json
|
||||
from typing import Optional, Type
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from app.agent.tools.base import MoviePilotTool
|
||||
from app.agent.tools.tags import ToolTag
|
||||
from app.runtime.log import logger
|
||||
|
||||
|
||||
class QuerySitesInput(BaseModel):
|
||||
"""查询站点工具的输入参数模型"""
|
||||
|
||||
status: Optional[str] = Field(
|
||||
"all",
|
||||
description="Filter sites by status: 'active' for enabled sites, 'inactive' for disabled sites, 'all' for all sites",
|
||||
)
|
||||
name: Optional[str] = Field(
|
||||
None, description="Filter sites by name (partial match, optional)"
|
||||
)
|
||||
|
||||
|
||||
class QuerySitesTool(MoviePilotTool):
|
||||
name: str = "query_sites"
|
||||
tags: list[str] = [
|
||||
ToolTag.Read,
|
||||
ToolTag.Site,
|
||||
]
|
||||
description: str = (
|
||||
"Query site status and list configured sites. Non-admin users receive a safe view "
|
||||
"that omits sensitive fields: cookie, token, API key and RSS URL. "
|
||||
"Site priority (pri): smaller values have higher priority (e.g., pri=1 has higher priority than pri=10)."
|
||||
)
|
||||
args_schema: Type[BaseModel] = QuerySitesInput
|
||||
|
||||
def get_tool_message(self, **kwargs) -> Optional[str]:
|
||||
"""根据查询参数生成友好的提示消息"""
|
||||
status = kwargs.get("status", "all")
|
||||
name = kwargs.get("name")
|
||||
|
||||
parts = ["查询站点"]
|
||||
|
||||
if status != "all":
|
||||
status_map = {"active": "已启用", "inactive": "已禁用"}
|
||||
parts.append(f"状态: {status_map.get(status, status)}")
|
||||
|
||||
if name:
|
||||
parts.append(f"名称: {name}")
|
||||
|
||||
return " | ".join(parts) if len(parts) > 1 else parts[0]
|
||||
|
||||
async def run(
|
||||
self, status: Optional[str] = "all", name: Optional[str] = None, **kwargs
|
||||
) -> str:
|
||||
logger.info(f"执行工具: {self.name}, 参数: status={status}, name={name}")
|
||||
try:
|
||||
is_admin = await self.is_admin_user()
|
||||
repository = self.data.sites
|
||||
# 获取所有站点(按优先级排序)
|
||||
sites = await repository.async_list()
|
||||
filtered_sites = []
|
||||
for site in sites:
|
||||
# 按状态过滤
|
||||
if status == "active" and not site.is_active:
|
||||
continue
|
||||
if status == "inactive" and site.is_active:
|
||||
continue
|
||||
# 按名称过滤(部分匹配)
|
||||
if name and name.lower() not in (site.name or "").lower():
|
||||
continue
|
||||
filtered_sites.append(site)
|
||||
if filtered_sites:
|
||||
# 精简字段,只保留关键信息
|
||||
simplified_sites = []
|
||||
for s in filtered_sites:
|
||||
simplified = {
|
||||
"id": s.id,
|
||||
"name": s.name,
|
||||
"domain": s.domain,
|
||||
"url": s.url,
|
||||
"pri": s.pri,
|
||||
"is_active": s.is_active,
|
||||
"downloader": s.downloader,
|
||||
"ua": s.ua,
|
||||
"proxy": s.proxy,
|
||||
"filter": s.filter,
|
||||
"render": s.render,
|
||||
"public": s.public,
|
||||
"note": s.note,
|
||||
"limit_interval": s.limit_interval,
|
||||
"limit_count": s.limit_count,
|
||||
"limit_seconds": s.limit_seconds,
|
||||
"timeout": s.timeout,
|
||||
}
|
||||
if is_admin:
|
||||
simplified.update({
|
||||
"rss": s.rss,
|
||||
"cookie": s.cookie,
|
||||
"apikey": s.apikey,
|
||||
"token": s.token,
|
||||
})
|
||||
simplified_sites.append(simplified)
|
||||
result_json = json.dumps(simplified_sites, ensure_ascii=False, indent=2)
|
||||
return result_json
|
||||
return "未找到相关站点"
|
||||
except Exception as e:
|
||||
logger.error(f"查询站点失败: {e}", exc_info=True)
|
||||
return f"查询站点时发生错误: {str(e)}"
|
||||
@@ -1,231 +0,0 @@
|
||||
"""查询订阅历史工具"""
|
||||
|
||||
import json
|
||||
from typing import Optional, Type
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from app.agent.tools.base import MoviePilotTool
|
||||
from app.agent.tools.tags import ToolTag
|
||||
from app.domain.media import normalize_music_type
|
||||
from app.runtime.log import logger
|
||||
from app.schemas.types import MUSIC_ENTITY_RECORDING, MediaType, media_type_to_agent
|
||||
|
||||
PAGE_SIZE = 20
|
||||
|
||||
|
||||
class QuerySubscribeHistoryInput(BaseModel):
|
||||
"""查询订阅历史工具的输入参数模型"""
|
||||
|
||||
media_type: Optional[str] = Field(
|
||||
"all", description="Allowed values: movie, tv, music, all"
|
||||
)
|
||||
music_type: Optional[str] = Field(
|
||||
None,
|
||||
description="Optional music history filter: recording or album",
|
||||
)
|
||||
name: Optional[str] = Field(
|
||||
None, description="Filter by media name (partial match, optional)"
|
||||
)
|
||||
page: Optional[int] = Field(
|
||||
1,
|
||||
description="Page number for pagination (default: 1, 20 items per page). Ignored when name filter is provided.",
|
||||
)
|
||||
|
||||
|
||||
class QuerySubscribeHistoryTool(MoviePilotTool):
|
||||
"""查询已完成的影视、单曲与整张专辑订阅历史。"""
|
||||
|
||||
name: str = "query_subscribe_history"
|
||||
tags: list[str] = [
|
||||
ToolTag.Read,
|
||||
ToolTag.Subscription,
|
||||
]
|
||||
description: str = "Query subscription history records. Shows completed subscriptions with their details including name, type, rating, completion date, and other subscription information. Supports filtering by media type and name. Supports pagination with 20 records per page."
|
||||
args_schema: Type[BaseModel] = QuerySubscribeHistoryInput
|
||||
|
||||
def get_tool_message(self, **kwargs) -> Optional[str]:
|
||||
"""根据查询参数生成友好的提示消息"""
|
||||
media_type = kwargs.get("media_type", "all")
|
||||
name = kwargs.get("name")
|
||||
page = kwargs.get("page", 1)
|
||||
|
||||
parts = ["查询订阅历史"]
|
||||
|
||||
if media_type != "all":
|
||||
parts.append(f"类型: {media_type}")
|
||||
if name:
|
||||
parts.append(f"名称: {name}")
|
||||
else:
|
||||
parts.append(f"第{page}页")
|
||||
|
||||
return " | ".join(parts)
|
||||
|
||||
async def run(
|
||||
self,
|
||||
media_type: Optional[str] = "all",
|
||||
music_type: Optional[str] = None,
|
||||
name: Optional[str] = None,
|
||||
page: Optional[int] = 1,
|
||||
**kwargs,
|
||||
) -> str:
|
||||
"""按规范化数据库类型查询并合并订阅历史。"""
|
||||
page = max(1, page or 1)
|
||||
logger.info(
|
||||
f"执行工具: {self.name}, 参数: media_type={media_type}, name={name}, page={page}"
|
||||
)
|
||||
|
||||
try:
|
||||
if media_type == "all":
|
||||
requested_types = [
|
||||
MediaType.MOVIE.value,
|
||||
MediaType.TV.value,
|
||||
MediaType.MUSIC.value,
|
||||
]
|
||||
else:
|
||||
media_type_enum = MediaType.from_agent(media_type)
|
||||
if not media_type_enum:
|
||||
return (
|
||||
f"错误:无效的媒体类型 '{media_type}',"
|
||||
"支持的类型:'movie', 'tv', 'music', 'all'"
|
||||
)
|
||||
requested_types = [media_type_enum.value]
|
||||
|
||||
normalized_music_type = None
|
||||
if music_type:
|
||||
normalized_music_type = normalize_music_type(
|
||||
music_type,
|
||||
allow_artist=False,
|
||||
)
|
||||
if not normalized_music_type:
|
||||
return (
|
||||
f"错误:无效的音乐实体类型 '{music_type}',"
|
||||
"支持的类型:'recording', 'album'"
|
||||
)
|
||||
if MediaType.MUSIC.value not in requested_types:
|
||||
return "错误:music_type 仅能与 media_type='music' 或 'all' 一起使用"
|
||||
|
||||
repository = self.data.subscription_history
|
||||
if name:
|
||||
# 有名称过滤时,获取足够多的记录在内存中过滤,不分页
|
||||
fetch_count = 500
|
||||
history_groups = [
|
||||
await repository.async_list_by_type(
|
||||
mtype=requested_type,
|
||||
page=1,
|
||||
count=fetch_count,
|
||||
)
|
||||
for requested_type in requested_types
|
||||
]
|
||||
all_history = [
|
||||
record for group in history_groups for record in group
|
||||
]
|
||||
all_history.sort(key=lambda x: x.date or "", reverse=True)
|
||||
|
||||
# 按名称过滤
|
||||
name_lower = name.lower()
|
||||
filtered_history = [
|
||||
record
|
||||
for record in all_history
|
||||
if record.name and name_lower in record.name.lower()
|
||||
and self._matches_music_type(record, normalized_music_type)
|
||||
]
|
||||
|
||||
if not filtered_history:
|
||||
return "未找到相关订阅历史记录"
|
||||
|
||||
# 名称过滤时直接返回所有匹配结果,不分页
|
||||
simplified_records = self._simplify_records(filtered_history)
|
||||
result_json = json.dumps(
|
||||
simplified_records, ensure_ascii=False, indent=2
|
||||
)
|
||||
return result_json
|
||||
else:
|
||||
# 无名称过滤时,直接利用数据库分页
|
||||
history_groups = [
|
||||
await repository.async_list_by_type(
|
||||
mtype=requested_type,
|
||||
page=1,
|
||||
count=page * PAGE_SIZE,
|
||||
)
|
||||
for requested_type in requested_types
|
||||
]
|
||||
all_history = [
|
||||
record for group in history_groups for record in group
|
||||
]
|
||||
all_history.sort(key=lambda x: x.date or "", reverse=True)
|
||||
filtered_history = [
|
||||
record
|
||||
for record in all_history
|
||||
if self._matches_music_type(record, normalized_music_type)
|
||||
]
|
||||
|
||||
if not filtered_history:
|
||||
return "未找到相关订阅历史记录"
|
||||
|
||||
# 分页切片
|
||||
total_count = len(filtered_history)
|
||||
start = (page - 1) * PAGE_SIZE
|
||||
end = start + PAGE_SIZE
|
||||
page_records = filtered_history[start:end]
|
||||
|
||||
if not page_records:
|
||||
return f"第 {page} 页没有数据。"
|
||||
|
||||
simplified_records = self._simplify_records(page_records)
|
||||
result_json = json.dumps(
|
||||
simplified_records, ensure_ascii=False, indent=2
|
||||
)
|
||||
|
||||
has_more = total_count > end
|
||||
payload_msg = f"第 {page} 页,当前页 {len(simplified_records)} 条结果。"
|
||||
if has_more:
|
||||
payload_msg += (
|
||||
f" 可能有更多数据,可使用 page={page + 1} 获取下一页。"
|
||||
)
|
||||
|
||||
return f"{payload_msg}\n\n{result_json}"
|
||||
except Exception as e:
|
||||
logger.error(f"查询订阅历史失败: {e}", exc_info=True)
|
||||
return f"查询订阅历史时发生错误: {str(e)}"
|
||||
|
||||
@staticmethod
|
||||
def _matches_music_type(record, music_type: Optional[str]) -> bool:
|
||||
"""匹配音乐实体类型,旧空值历史按单曲兼容。"""
|
||||
if not music_type:
|
||||
return True
|
||||
if media_type_to_agent(getattr(record, "type", None)) != "music":
|
||||
return False
|
||||
return (getattr(record, "music_type", None) or MUSIC_ENTITY_RECORDING) == music_type
|
||||
|
||||
@staticmethod
|
||||
def _simplify_records(records) -> list:
|
||||
"""转换为字典格式,只保留关键信息"""
|
||||
simplified_records = []
|
||||
for record in records:
|
||||
simplified = {
|
||||
"id": record.id,
|
||||
"name": record.name,
|
||||
"year": record.year,
|
||||
"type": media_type_to_agent(record.type),
|
||||
"season": record.season,
|
||||
"media_source": record.media_source,
|
||||
"media_id": record.media_id,
|
||||
"music_type": getattr(record, "music_type", None) or (
|
||||
MUSIC_ENTITY_RECORDING if media_type_to_agent(record.type) == "music" else None
|
||||
),
|
||||
"total_tracks": getattr(record, "total_tracks", None),
|
||||
"poster": record.poster,
|
||||
"vote": record.vote,
|
||||
"total_episode": record.total_episode,
|
||||
"date": record.date,
|
||||
"username": record.username,
|
||||
}
|
||||
if record.filter:
|
||||
simplified["filter"] = record.filter
|
||||
if record.quality:
|
||||
simplified["quality"] = record.quality
|
||||
if record.resolution:
|
||||
simplified["resolution"] = record.resolution
|
||||
simplified_records.append(simplified)
|
||||
return simplified_records
|
||||
@@ -1,138 +0,0 @@
|
||||
"""查询订阅分享工具"""
|
||||
|
||||
import json
|
||||
from typing import Optional, Type
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from app.agent.tools.base import MoviePilotTool
|
||||
from app.agent.tools.tags import ToolTag
|
||||
from app.adapters.external.server import MoviePilotServerHelper
|
||||
from app.runtime.log import logger
|
||||
from app.schemas.types import MUSIC_ENTITY_RECORDING, media_type_to_agent
|
||||
from app.domain.media import normalize_music_type
|
||||
|
||||
MAX_PAGE_SIZE = 50
|
||||
|
||||
|
||||
class QuerySubscribeSharesInput(BaseModel):
|
||||
"""查询订阅分享工具的输入参数模型"""
|
||||
name: Optional[str] = Field(None, description="Filter shares by media name (partial match, optional)")
|
||||
page: Optional[int] = Field(1, description="Page number for pagination (default: 1)")
|
||||
count: Optional[int] = Field(30, description="Number of items per page (default: 30, max: 50)")
|
||||
genre_id: Optional[int] = Field(None, description="Filter by genre ID (optional)")
|
||||
min_rating: Optional[float] = Field(None, description="Minimum rating filter (optional, e.g., 7.5)")
|
||||
max_rating: Optional[float] = Field(None, description="Maximum rating filter (optional, e.g., 10.0)")
|
||||
sort_type: Optional[str] = Field(None, description="Sort type (optional, e.g., 'count', 'rating')")
|
||||
|
||||
|
||||
class QuerySubscribeSharesTool(MoviePilotTool):
|
||||
"""查询社区共享的影视、单曲与专辑订阅。"""
|
||||
|
||||
name: str = "query_subscribe_shares"
|
||||
tags: list[str] = [
|
||||
ToolTag.Read,
|
||||
ToolTag.Subscription,
|
||||
]
|
||||
description: str = "Query shared subscriptions from other users. Shows popular subscriptions shared by the community with filtering and pagination support."
|
||||
args_schema: Type[BaseModel] = QuerySubscribeSharesInput
|
||||
|
||||
def get_tool_message(self, **kwargs) -> Optional[str]:
|
||||
"""根据查询参数生成友好的提示消息"""
|
||||
name = kwargs.get("name")
|
||||
page = kwargs.get("page", 1)
|
||||
min_rating = kwargs.get("min_rating")
|
||||
max_rating = kwargs.get("max_rating")
|
||||
|
||||
parts = ["查询订阅分享"]
|
||||
|
||||
if name:
|
||||
parts.append(f"名称: {name}")
|
||||
if min_rating:
|
||||
parts.append(f"最低评分: {min_rating}")
|
||||
if max_rating:
|
||||
parts.append(f"最高评分: {max_rating}")
|
||||
if page > 1:
|
||||
parts.append(f"第{page}页")
|
||||
|
||||
return " | ".join(parts) if len(parts) > 1 else parts[0]
|
||||
|
||||
async def run(self, name: Optional[str] = None,
|
||||
page: Optional[int] = 1,
|
||||
count: Optional[int] = 30,
|
||||
genre_id: Optional[int] = None,
|
||||
min_rating: Optional[float] = None,
|
||||
max_rating: Optional[float] = None,
|
||||
sort_type: Optional[str] = None, **kwargs) -> str:
|
||||
"""查询订阅分享并保留音乐实体及整专曲目字段。"""
|
||||
logger.info(
|
||||
f"执行工具: {self.name}, 参数: name={name}, page={page}, count={count}, genre_id={genre_id}, "
|
||||
f"min_rating={min_rating}, max_rating={max_rating}, sort_type={sort_type}")
|
||||
|
||||
try:
|
||||
if page is None or page < 1:
|
||||
page = 1
|
||||
if count is None or count < 1:
|
||||
count = 30
|
||||
# 订阅分享是外部列表型结果,限制单页大小能降低工具上下文占用。
|
||||
count = min(count, MAX_PAGE_SIZE)
|
||||
|
||||
shares = await MoviePilotServerHelper.async_get_subscribe_shares(
|
||||
name=name,
|
||||
page=page,
|
||||
count=count,
|
||||
genre_id=genre_id,
|
||||
min_rating=min_rating,
|
||||
max_rating=max_rating,
|
||||
sort_type=sort_type
|
||||
)
|
||||
|
||||
if not shares:
|
||||
return "未找到订阅分享数据(可能订阅分享功能未启用)"
|
||||
|
||||
# 简化字段,只保留关键信息
|
||||
simplified_shares = []
|
||||
for share in shares:
|
||||
normalized_type = media_type_to_agent(share.get("type"))
|
||||
normalized_music_type = None
|
||||
if normalized_type == "music":
|
||||
normalized_music_type = normalize_music_type(
|
||||
share.get("music_type") or MUSIC_ENTITY_RECORDING,
|
||||
allow_artist=False,
|
||||
)
|
||||
if not normalized_music_type:
|
||||
logger.warning(
|
||||
f"跳过未知音乐订阅分享实体: {share.get('music_type')}"
|
||||
)
|
||||
continue
|
||||
simplified = {
|
||||
"id": share.get("id"),
|
||||
"name": share.get("name"),
|
||||
"year": share.get("year"),
|
||||
"type": normalized_type,
|
||||
"season": share.get("season"),
|
||||
"media_source": share.get("media_source"),
|
||||
"media_id": share.get("media_id"),
|
||||
"music_type": normalized_music_type,
|
||||
"total_tracks": share.get("total_tracks"),
|
||||
"description": share.get("description"),
|
||||
"poster": share.get("poster"),
|
||||
"vote": share.get("vote"),
|
||||
"share_title": share.get("share_title"),
|
||||
"share_comment": share.get("share_comment"),
|
||||
"share_user": share.get("share_user"),
|
||||
"fork_count": share.get("fork_count", 0)
|
||||
}
|
||||
# 截断过长的描述
|
||||
if simplified.get("description") and len(simplified["description"]) > 200:
|
||||
simplified["description"] = simplified["description"][:200] + "..."
|
||||
simplified_shares.append(simplified)
|
||||
|
||||
result_json = json.dumps(simplified_shares, ensure_ascii=False, indent=2)
|
||||
|
||||
pagination_info = f"第 {page} 页,每页 {count} 条,共 {len(simplified_shares)} 条结果"
|
||||
|
||||
return f"{pagination_info}\n\n{result_json}"
|
||||
except Exception as e:
|
||||
logger.error(f"查询订阅分享失败: {e}", exc_info=True)
|
||||
return f"查询订阅分享时发生错误: {str(e)}"
|
||||
@@ -1,215 +0,0 @@
|
||||
"""查询订阅工具"""
|
||||
|
||||
import json
|
||||
from typing import Optional, Type
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from app.agent.tools.base import MoviePilotTool
|
||||
from app.agent.tools.tags import ToolTag
|
||||
from app.domain.media import normalize_music_type
|
||||
from app.runtime.log import logger
|
||||
from app.schemas.subscribe import Subscribe as SubscribeSchema
|
||||
from app.schemas.types import (
|
||||
MUSIC_ENTITY_RECORDING,
|
||||
MediaSource,
|
||||
MediaType,
|
||||
media_type_to_agent,
|
||||
)
|
||||
|
||||
PAGE_SIZE = 100
|
||||
|
||||
QUERY_SUBSCRIBE_OUTPUT_FIELDS = [
|
||||
"id",
|
||||
"name",
|
||||
"year",
|
||||
"type",
|
||||
"media_source",
|
||||
"media_id",
|
||||
"music_type",
|
||||
"total_tracks",
|
||||
"season",
|
||||
"total_episode",
|
||||
"start_episode",
|
||||
"lack_episode",
|
||||
"filter",
|
||||
"include",
|
||||
"exclude",
|
||||
"quality",
|
||||
"resolution",
|
||||
"effect",
|
||||
"audio_quality",
|
||||
"audio_format",
|
||||
"min_bitrate",
|
||||
"min_bit_depth",
|
||||
"min_sample_rate",
|
||||
"state",
|
||||
"last_update",
|
||||
"sites",
|
||||
"downloader",
|
||||
"best_version",
|
||||
"best_version_full",
|
||||
"current_priority",
|
||||
"current_audio_format",
|
||||
"current_bitrate",
|
||||
"current_bit_depth",
|
||||
"current_sample_rate",
|
||||
"episode_priority",
|
||||
"save_path",
|
||||
"custom_words",
|
||||
"media_category",
|
||||
"filter_groups",
|
||||
"episode_group",
|
||||
"poster",
|
||||
"backdrop",
|
||||
"description",
|
||||
"username",
|
||||
]
|
||||
|
||||
|
||||
class QuerySubscribesInput(BaseModel):
|
||||
"""查询订阅工具的输入参数模型"""
|
||||
|
||||
status: Optional[str] = Field(
|
||||
"all",
|
||||
description="Filter subscriptions by status: 'R' for enabled subscriptions, 'S' for paused ones, 'all' for all subscriptions",
|
||||
)
|
||||
media_type: Optional[str] = Field(
|
||||
"all", description="Allowed values: movie, tv, music, all"
|
||||
)
|
||||
music_type: Optional[str] = Field(
|
||||
None,
|
||||
description="Optional music subscription filter: recording or album",
|
||||
)
|
||||
media_source: Optional[MediaSource] = Field(
|
||||
None, description="Filter by media source"
|
||||
)
|
||||
media_id: Optional[str] = Field(None, description="Filter by source-native media ID")
|
||||
page: Optional[int] = Field(
|
||||
1, description="Page number for pagination (default: 1, 100 items per page)"
|
||||
)
|
||||
|
||||
|
||||
class QuerySubscribesTool(MoviePilotTool):
|
||||
"""查询电影、电视剧、单曲与专辑订阅。"""
|
||||
|
||||
name: str = "query_subscribes"
|
||||
tags: list[str] = [
|
||||
ToolTag.Read,
|
||||
ToolTag.Subscription,
|
||||
]
|
||||
description: str = "Query subscription status and list user subscriptions. Returns full subscription parameters for each matched subscription. Supports pagination with 100 items per page."
|
||||
args_schema: Type[BaseModel] = QuerySubscribesInput
|
||||
|
||||
def get_tool_message(self, **kwargs) -> Optional[str]:
|
||||
"""根据查询参数生成友好的提示消息"""
|
||||
status = kwargs.get("status", "all")
|
||||
media_type = kwargs.get("media_type", "all")
|
||||
page = kwargs.get("page", 1)
|
||||
|
||||
parts = ["查询订阅"]
|
||||
|
||||
# 根据状态过滤条件生成提示
|
||||
if status != "all":
|
||||
status_map = {"R": "已启用", "S": "已暂停"}
|
||||
parts.append(f"状态: {status_map.get(status, status)}")
|
||||
|
||||
# 根据媒体类型过滤条件生成提示
|
||||
if media_type != "all":
|
||||
parts.append(f"类型: {media_type}")
|
||||
|
||||
parts.append(f"第{page}页")
|
||||
|
||||
return " | ".join(parts)
|
||||
|
||||
async def run(
|
||||
self,
|
||||
status: Optional[str] = "all",
|
||||
media_type: Optional[str] = "all",
|
||||
music_type: Optional[str] = None,
|
||||
media_source: Optional[MediaSource] = None,
|
||||
media_id: Optional[str] = None,
|
||||
page: Optional[int] = 1,
|
||||
**kwargs,
|
||||
) -> str:
|
||||
"""按状态、媒体身份及音乐实体类型筛选订阅。"""
|
||||
page = max(1, page or 1)
|
||||
logger.info(
|
||||
f"执行工具: {self.name}, 参数: status={status}, "
|
||||
f"media_type={media_type}, media_source={media_source}, "
|
||||
f"media_id={media_id}, page={page}"
|
||||
)
|
||||
try:
|
||||
if media_type != "all" and not MediaType.from_agent(media_type):
|
||||
return f"错误:无效的媒体类型 '{media_type}',支持的类型:'movie', 'tv', 'music', 'all'"
|
||||
normalized_music_type = None
|
||||
if music_type:
|
||||
normalized_music_type = normalize_music_type(
|
||||
music_type,
|
||||
allow_artist=False,
|
||||
)
|
||||
if not normalized_music_type:
|
||||
return (
|
||||
f"错误:无效的音乐实体类型 '{music_type}',"
|
||||
"支持的类型:'recording', 'album'"
|
||||
)
|
||||
if media_type not in ("all", "music"):
|
||||
return "错误:music_type 仅能与 media_type='music' 或 'all' 一起使用"
|
||||
|
||||
repository = self.data.subscriptions
|
||||
subscribes = await repository.async_list()
|
||||
filtered_subscribes = []
|
||||
for sub in subscribes:
|
||||
if status != "all" and sub.state != status:
|
||||
continue
|
||||
if (
|
||||
media_type != "all"
|
||||
and sub.type != MediaType.from_agent(media_type).value
|
||||
):
|
||||
continue
|
||||
if media_source is not None and sub.media_source != str(media_source):
|
||||
continue
|
||||
if media_id is not None and sub.media_id != media_id:
|
||||
continue
|
||||
if normalized_music_type:
|
||||
sub_music_type = sub.music_type or MUSIC_ENTITY_RECORDING
|
||||
if sub_music_type != normalized_music_type:
|
||||
continue
|
||||
filtered_subscribes.append(sub)
|
||||
if filtered_subscribes:
|
||||
total_count = len(filtered_subscribes)
|
||||
# 分页
|
||||
start = (page - 1) * PAGE_SIZE
|
||||
end = start + PAGE_SIZE
|
||||
page_subscribes = filtered_subscribes[start:end]
|
||||
|
||||
if not page_subscribes:
|
||||
total_pages = (total_count + PAGE_SIZE - 1) // PAGE_SIZE
|
||||
return f"第 {page} 页没有数据,共 {total_count} 条结果,共 {total_pages} 页。"
|
||||
|
||||
full_subscribes = []
|
||||
for subscribe in page_subscribes:
|
||||
payload = SubscribeSchema.model_validate(
|
||||
subscribe,
|
||||
from_attributes=True,
|
||||
).model_dump(
|
||||
include=set(QUERY_SUBSCRIBE_OUTPUT_FIELDS), exclude_none=True
|
||||
)
|
||||
# 手动总集数是运行锁状态,不属于公共订阅写入 Schema,查询时直接从实体读取。
|
||||
payload["manual_total_episode"] = subscribe.manual_total_episode or 0
|
||||
payload["type"] = media_type_to_agent(payload.get("type"))
|
||||
if payload["type"] == "music" and not payload.get("music_type"):
|
||||
payload["music_type"] = MUSIC_ENTITY_RECORDING
|
||||
full_subscribes.append(payload)
|
||||
result_json = json.dumps(full_subscribes, ensure_ascii=False, indent=2)
|
||||
|
||||
total_pages = (total_count + PAGE_SIZE - 1) // PAGE_SIZE
|
||||
payload_msg = f"第 {page}/{total_pages} 页,当前页 {len(page_subscribes)} 条结果,共 {total_count} 条。"
|
||||
if page < total_pages:
|
||||
payload_msg += f" 可使用 page={page + 1} 获取下一页。"
|
||||
|
||||
return f"{payload_msg}\n\n{result_json}"
|
||||
return "未找到相关订阅"
|
||||
except Exception as e:
|
||||
logger.error(f"查询订阅失败: {e}", exc_info=True)
|
||||
return f"查询订阅时发生错误: {str(e)}"
|
||||
@@ -1,259 +0,0 @@
|
||||
"""统一查询系统设置工具。"""
|
||||
|
||||
import json
|
||||
from typing import Optional, Type
|
||||
|
||||
from pydantic import BaseModel, Field, PrivateAttr
|
||||
|
||||
from app.agent.tools.base import MoviePilotTool
|
||||
from app.agent.tools.tags import ToolTag
|
||||
from app.agent.tools.impl._system_setting_utils import (
|
||||
SettingSpec,
|
||||
is_secret_setting_key,
|
||||
list_setting_specs,
|
||||
redact_secret_value,
|
||||
resolve_setting_spec,
|
||||
should_redact_setting,
|
||||
)
|
||||
from app.application.configuration import (
|
||||
SystemConfigReader,
|
||||
get_configured_system_config,
|
||||
get_runtime_settings,
|
||||
)
|
||||
from app.runtime.log import logger
|
||||
|
||||
|
||||
class QuerySystemSettingsInput(BaseModel):
|
||||
"""查询系统设置工具的输入参数模型。"""
|
||||
|
||||
setting_key: Optional[str] = Field(
|
||||
None,
|
||||
description=(
|
||||
"Exact setting key to query. Supports Settings field names like 'APP_DOMAIN' or 'TMDB_API_KEY', "
|
||||
"SystemConfigKey values like 'Downloaders' or 'MediaServers', enum names, and some single-key aliases "
|
||||
"such as 'downloaders', 'directories', 'search_sites', 'subscribe_sites', 'site_auth', "
|
||||
"and 'custom_identifiers'."
|
||||
),
|
||||
)
|
||||
group: Optional[str] = Field(
|
||||
"all",
|
||||
description=(
|
||||
"Optional group filter when setting_key is not provided. Supports 'all', 'settings', 'systemconfig', "
|
||||
"and category aliases such as 'downloaders', 'media_servers', 'notifications', 'notification_switches', "
|
||||
"'storages', 'directories', 'search_sites', 'subscribe_sites', 'site_auth', 'ai_agent', 'filter_rules', "
|
||||
"'subscribe_defaults', 'plugins', and 'custom_identifiers'. Chinese aliases are also accepted."
|
||||
),
|
||||
)
|
||||
keyword: Optional[str] = Field(
|
||||
None,
|
||||
description=(
|
||||
"Optional keyword used to fuzzy match setting keys, group names, or labels when listing settings."
|
||||
),
|
||||
)
|
||||
include_values: Optional[bool] = Field(
|
||||
None,
|
||||
description=(
|
||||
"Whether to include full setting values. Default behavior: when a single setting is matched it returns the full value; "
|
||||
"when multiple settings are matched it returns summaries only unless this is explicitly set to true."
|
||||
),
|
||||
)
|
||||
show_secrets: Optional[bool] = Field(
|
||||
False,
|
||||
description=(
|
||||
"Whether to return raw secret values such as API keys, tokens, cookies, and passwords. "
|
||||
"Defaults to false; secret-like fields are redacted in returned values and previews. "
|
||||
"Set this to true when the user explicitly asks for an unredacted secret; the host verifies "
|
||||
"administrator authority, requests confirmation, and delivers the result outside the ordinary "
|
||||
"model response. Do not refuse the tool call solely because the requested value is sensitive."
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
class QuerySystemSettingsTool(MoviePilotTool):
|
||||
"""查询系统设置,并隔离 Agent 确认后的密钥读取入口。"""
|
||||
|
||||
name: str = "query_system_settings"
|
||||
tags: list[str] = [
|
||||
ToolTag.Read,
|
||||
ToolTag.System,
|
||||
ToolTag.Settings,
|
||||
ToolTag.Admin,
|
||||
]
|
||||
description: str = (
|
||||
"Query system settings across both the basic Settings module and all SystemConfig-backed categories. "
|
||||
"Use this tool to inspect downloaders, media servers, notification channels, storages, directories, search-site ranges, "
|
||||
"subscribe-site ranges, site auth params, AI agent config, and any other system setting before making changes."
|
||||
)
|
||||
require_admin: bool = True
|
||||
args_schema: Type[BaseModel] = QuerySystemSettingsInput
|
||||
_secret_read_confirmed: bool = PrivateAttr(default=False)
|
||||
_system_config: Optional[SystemConfigReader] = PrivateAttr(default=None)
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
session_id: str,
|
||||
user_id: str,
|
||||
*,
|
||||
system_config: Optional[SystemConfigReader] = None,
|
||||
**kwargs,
|
||||
) -> None:
|
||||
"""注入授权范围内的配置读取端口,并兼容组合根默认服务。"""
|
||||
super().__init__(session_id=session_id, user_id=user_id, **kwargs)
|
||||
self._system_config = system_config
|
||||
|
||||
def _get_system_config(self) -> SystemConfigReader:
|
||||
"""返回显式注入端口,旧构造形态则延迟读取组合根服务。"""
|
||||
return self._system_config or get_configured_system_config()
|
||||
|
||||
async def _run_confirmed(self, **kwargs) -> str:
|
||||
"""仅供宿主在消费有效确认后执行一次未脱敏读取。"""
|
||||
self._secret_read_confirmed = True
|
||||
try:
|
||||
return await self.run(**kwargs)
|
||||
finally:
|
||||
self._secret_read_confirmed = False
|
||||
|
||||
def get_tool_message(self, **kwargs) -> Optional[str]:
|
||||
"""根据查询参数生成友好的提示消息。"""
|
||||
|
||||
setting_key = kwargs.get("setting_key")
|
||||
group = kwargs.get("group", "all")
|
||||
keyword = kwargs.get("keyword")
|
||||
if setting_key:
|
||||
return f"查询系统设置: {setting_key}"
|
||||
if keyword:
|
||||
return f"筛选系统设置: {group} / {keyword}"
|
||||
return f"查询系统设置分组: {group}"
|
||||
|
||||
def _load_setting_value(self, spec: SettingSpec):
|
||||
"""读取指定设置项的当前值。"""
|
||||
if spec.source == "settings":
|
||||
return get_runtime_settings().get(spec.key)
|
||||
return self._get_system_config().get(spec.systemconfig_key)
|
||||
|
||||
@staticmethod
|
||||
def _summarize_value(value, *, redacted: bool = False) -> dict:
|
||||
"""生成设置值摘要,避免列表和字典默认输出过长。"""
|
||||
summary = {
|
||||
"has_value": value is not None,
|
||||
"value_type": type(value).__name__,
|
||||
"redacted": redacted,
|
||||
}
|
||||
if isinstance(value, list):
|
||||
summary["item_count"] = len(value)
|
||||
if value:
|
||||
summary["item_type"] = type(value[0]).__name__
|
||||
elif isinstance(value, dict):
|
||||
keys = list(value.keys())
|
||||
summary["item_count"] = len(keys)
|
||||
summary["keys_preview"] = keys[:10]
|
||||
if len(keys) > 10:
|
||||
summary["keys_truncated"] = True
|
||||
elif isinstance(value, str):
|
||||
summary["length"] = len(value)
|
||||
preview = value[:200]
|
||||
if preview:
|
||||
summary["value_preview"] = preview
|
||||
if len(value) > len(preview):
|
||||
summary["value_truncated"] = True
|
||||
elif value is not None:
|
||||
summary["value_preview"] = value
|
||||
return summary
|
||||
|
||||
async def run(
|
||||
self,
|
||||
setting_key: Optional[str] = None,
|
||||
group: Optional[str] = "all",
|
||||
keyword: Optional[str] = None,
|
||||
include_values: Optional[bool] = None,
|
||||
show_secrets: Optional[bool] = False,
|
||||
**kwargs,
|
||||
) -> str:
|
||||
"""查询系统设置,并在 Agent 场景中阻止未经确认的密钥明文读取。"""
|
||||
logger.info(
|
||||
f"执行工具: {self.name}, setting_key={setting_key}, "
|
||||
f"group={group}, keyword={keyword}"
|
||||
)
|
||||
|
||||
try:
|
||||
if (
|
||||
show_secrets is True
|
||||
and self._agent_context.get("require_secret_confirmation")
|
||||
and not self._secret_read_confirmed
|
||||
):
|
||||
return json.dumps(
|
||||
{
|
||||
"success": False,
|
||||
"message": "读取敏感设置前需要用户确认,本次未执行。",
|
||||
},
|
||||
ensure_ascii=False,
|
||||
)
|
||||
if setting_key:
|
||||
spec = resolve_setting_spec(setting_key)
|
||||
if not spec:
|
||||
return json.dumps(
|
||||
{
|
||||
"success": False,
|
||||
"message": f"系统设置项 '{setting_key}' 不存在",
|
||||
},
|
||||
ensure_ascii=False,
|
||||
)
|
||||
specs = [spec]
|
||||
else:
|
||||
specs = list_setting_specs(group=group, keyword=keyword)
|
||||
if not specs:
|
||||
return json.dumps(
|
||||
{
|
||||
"success": False,
|
||||
"message": "没有找到匹配的系统设置项",
|
||||
},
|
||||
ensure_ascii=False,
|
||||
)
|
||||
|
||||
should_include_values = (
|
||||
include_values if include_values is not None else len(specs) == 1
|
||||
)
|
||||
allow_secret_values = bool(show_secrets) and await self.is_admin_user()
|
||||
settings_payload = []
|
||||
for spec in specs:
|
||||
value = self._load_setting_value(spec)
|
||||
should_redact = (
|
||||
should_redact_setting(spec, value) and not allow_secret_values
|
||||
)
|
||||
response_value = (
|
||||
redact_secret_value(
|
||||
value,
|
||||
redact_scalar=is_secret_setting_key(spec.key),
|
||||
)
|
||||
if should_redact
|
||||
else value
|
||||
)
|
||||
item = {
|
||||
"setting_key": spec.key,
|
||||
"source": spec.source,
|
||||
"group": spec.group,
|
||||
"label": spec.label,
|
||||
}
|
||||
item.update(self._summarize_value(response_value, redacted=should_redact))
|
||||
if should_include_values:
|
||||
item["value"] = response_value
|
||||
settings_payload.append(item)
|
||||
|
||||
return json.dumps(
|
||||
{
|
||||
"success": True,
|
||||
"matched_count": len(settings_payload),
|
||||
"include_values": should_include_values,
|
||||
"show_secrets": allow_secret_values,
|
||||
"settings": settings_payload,
|
||||
},
|
||||
ensure_ascii=False,
|
||||
indent=2,
|
||||
default=str,
|
||||
)
|
||||
except Exception as e:
|
||||
logger.error(f"查询系统设置失败: {e}", exc_info=True)
|
||||
return json.dumps(
|
||||
{"success": False, "message": f"查询系统设置时发生错误: {str(e)}"},
|
||||
ensure_ascii=False,
|
||||
)
|
||||
@@ -1,143 +0,0 @@
|
||||
"""查询整理历史记录工具"""
|
||||
|
||||
import json
|
||||
from typing import Optional, Type
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from app.agent.tools.base import MoviePilotTool
|
||||
from app.agent.tools.tags import ToolTag
|
||||
from app.foundation.text import cut as jieba_cut
|
||||
from app.runtime.log import logger
|
||||
from app.schemas.types import media_type_to_agent
|
||||
|
||||
|
||||
class QueryTransferHistoryInput(BaseModel):
|
||||
"""查询整理历史记录工具的输入参数模型"""
|
||||
title: Optional[str] = Field(None, description="Search by title (optional, supports partial match)")
|
||||
status: Optional[str] = Field("all",
|
||||
description="Filter by status: 'success' for successful transfers, 'failed' for failed transfers, 'all' for all records (default: 'all')")
|
||||
page: Optional[int] = Field(1, description="Page number for pagination (default: 1, each page contains 30 records)")
|
||||
|
||||
|
||||
class QueryTransferHistoryTool(MoviePilotTool):
|
||||
"""查询影视与音乐整理历史及可复用的媒体身份。"""
|
||||
|
||||
name: str = "query_transfer_history"
|
||||
tags: list[str] = [
|
||||
ToolTag.Read,
|
||||
ToolTag.Transfer,
|
||||
]
|
||||
description: str = (
|
||||
"Query movie, TV, and music transfer history. Returns source/destination paths, status, errors, and "
|
||||
"stable media_source/media_id values that can be reused for retries. Music album retries should group "
|
||||
"tracks by the shared album directory/identity instead of treating every track as unrelated media."
|
||||
)
|
||||
args_schema: Type[BaseModel] = QueryTransferHistoryInput
|
||||
|
||||
def get_tool_message(self, **kwargs) -> Optional[str]:
|
||||
"""根据查询参数生成友好的提示消息"""
|
||||
title = kwargs.get("title")
|
||||
status = kwargs.get("status", "all")
|
||||
page = kwargs.get("page", 1)
|
||||
|
||||
parts = ["查询整理历史"]
|
||||
|
||||
if title:
|
||||
parts.append(f"标题: {title}")
|
||||
if status != "all":
|
||||
status_map = {"success": "成功", "failed": "失败"}
|
||||
parts.append(f"状态: {status_map.get(status, status)}")
|
||||
if page > 1:
|
||||
parts.append(f"第{page}页")
|
||||
|
||||
return " | ".join(parts) if len(parts) > 1 else parts[0]
|
||||
|
||||
async def run(self, title: Optional[str] = None,
|
||||
status: Optional[str] = "all",
|
||||
page: Optional[int] = 1, **kwargs) -> str:
|
||||
"""执行整理历史筛选并返回有界分页结果。"""
|
||||
logger.info(f"执行工具: {self.name}, 参数: title={title}, status={status}, page={page}")
|
||||
|
||||
try:
|
||||
# 处理状态参数
|
||||
status_bool = None
|
||||
if status == "success":
|
||||
status_bool = True
|
||||
elif status == "failed":
|
||||
status_bool = False
|
||||
|
||||
# 处理页码参数
|
||||
if page is None or page < 1:
|
||||
page = 1
|
||||
|
||||
# 每页固定 30 条,与工具说明保持一致,避免整理路径等字段撑大上下文。
|
||||
count = 30
|
||||
|
||||
transferhis = self.data.transfer_history
|
||||
# 处理标题搜索
|
||||
if title:
|
||||
# 使用统一分词封装处理标题,便于替换底层实现。
|
||||
words = jieba_cut(title, HMM=False)
|
||||
title_search = "%".join(words)
|
||||
# 查询记录
|
||||
result = await transferhis.async_list_by_title(
|
||||
title=title_search, page=page, count=count, status=status_bool
|
||||
)
|
||||
total = await transferhis.async_count_by_title(
|
||||
title=title_search, status=status_bool
|
||||
)
|
||||
else:
|
||||
# 查询所有记录
|
||||
result = await transferhis.async_list_by_page(
|
||||
page=page, count=count, status=status_bool
|
||||
)
|
||||
total = await transferhis.async_count(status=status_bool)
|
||||
|
||||
if not result:
|
||||
return "未找到相关整理历史记录"
|
||||
|
||||
# 转换为字典格式,只保留关键信息
|
||||
simplified_records = []
|
||||
for record in result:
|
||||
simplified = {
|
||||
"id": record.id,
|
||||
"title": record.title,
|
||||
"year": record.year,
|
||||
"type": media_type_to_agent(record.type),
|
||||
"category": record.category,
|
||||
"seasons": record.seasons,
|
||||
"episodes": record.episodes,
|
||||
"src": record.src,
|
||||
"dest": record.dest,
|
||||
"mode": record.mode,
|
||||
"status": "成功" if record.status else "失败",
|
||||
"date": record.date,
|
||||
"downloader": record.downloader,
|
||||
"download_hash": record.download_hash
|
||||
}
|
||||
# 如果失败,添加错误信息
|
||||
if not record.status and record.errmsg:
|
||||
simplified["errmsg"] = record.errmsg
|
||||
if record.media_source:
|
||||
simplified["media_source"] = record.media_source
|
||||
if record.media_id:
|
||||
simplified["media_id"] = record.media_id
|
||||
if getattr(record, "music_type", None):
|
||||
simplified["music_type"] = record.music_type
|
||||
if getattr(record, "total_tracks", None):
|
||||
simplified["total_tracks"] = record.total_tracks
|
||||
simplified_records.append(simplified)
|
||||
|
||||
result_json = json.dumps(simplified_records, ensure_ascii=False, indent=2)
|
||||
|
||||
# 计算总页数
|
||||
total_pages = (total + count - 1) // count if total > 0 else 1
|
||||
|
||||
# 构建分页信息
|
||||
pagination_info = f"第 {page}/{total_pages} 页,共 {total} 条记录(每页 {count} 条)"
|
||||
|
||||
return f"{pagination_info}\n\n{result_json}"
|
||||
except Exception as e:
|
||||
logger.error(f"查询整理历史记录失败: {e}", exc_info=True)
|
||||
return f"查询整理历史记录时发生错误: {str(e)}"
|
||||
@@ -1,129 +0,0 @@
|
||||
"""查询工作流工具"""
|
||||
|
||||
import json
|
||||
from typing import Optional, Type
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from app.agent.tools.base import MoviePilotTool
|
||||
from app.agent.tools.tags import ToolTag
|
||||
from app.application.workflow import get_configured_workflow_query
|
||||
from app.runtime.log import logger
|
||||
|
||||
|
||||
class QueryWorkflowsInput(BaseModel):
|
||||
"""查询工作流工具的输入参数模型"""
|
||||
state: Optional[str] = Field("all", description="Filter workflows by state: 'W' for waiting, 'R' for running, 'P' for paused, 'S' for success, 'F' for failed, 'all' for all workflows (default: 'all')")
|
||||
name: Optional[str] = Field(None, description="Filter workflows by name (partial match, optional)")
|
||||
trigger_type: Optional[str] = Field("all", description="Filter workflows by trigger type: 'timer' for scheduled, 'event' for event-triggered, 'manual' for manual, 'all' for all types (default: 'all')")
|
||||
|
||||
|
||||
class QueryWorkflowsTool(MoviePilotTool):
|
||||
name: str = "query_workflows"
|
||||
tags: list[str] = [
|
||||
ToolTag.Read,
|
||||
ToolTag.Workflow,
|
||||
]
|
||||
description: str = "Query workflow list and status. Shows workflow name, description, trigger type, state, execution count, and other workflow details. Supports filtering by state, name, and trigger type."
|
||||
args_schema: Type[BaseModel] = QueryWorkflowsInput
|
||||
|
||||
def get_tool_message(self, **kwargs) -> Optional[str]:
|
||||
"""根据查询参数生成友好的提示消息"""
|
||||
state = kwargs.get("state", "all")
|
||||
name = kwargs.get("name")
|
||||
trigger_type = kwargs.get("trigger_type", "all")
|
||||
|
||||
parts = ["查询工作流"]
|
||||
|
||||
if state != "all":
|
||||
state_map = {"W": "等待", "R": "运行中", "P": "暂停", "S": "成功", "F": "失败"}
|
||||
parts.append(f"状态: {state_map.get(state, state)}")
|
||||
|
||||
if trigger_type != "all":
|
||||
trigger_map = {"timer": "定时触发", "event": "事件触发", "manual": "手动触发"}
|
||||
parts.append(f"触发类型: {trigger_map.get(trigger_type, trigger_type)}")
|
||||
|
||||
if name:
|
||||
parts.append(f"名称: {name}")
|
||||
|
||||
return " | ".join(parts) if len(parts) > 1 else parts[0]
|
||||
|
||||
async def run(self, state: Optional[str] = "all",
|
||||
name: Optional[str] = None,
|
||||
trigger_type: Optional[str] = "all", **kwargs) -> str:
|
||||
logger.info(f"执行工具: {self.name}, 参数: state={state}, name={name}, trigger_type={trigger_type}")
|
||||
|
||||
try:
|
||||
workflows = await get_configured_workflow_query().list()
|
||||
|
||||
# 过滤工作流
|
||||
filtered_workflows = []
|
||||
for wf in workflows:
|
||||
# 按状态过滤
|
||||
if state != "all" and wf.state != state:
|
||||
continue
|
||||
|
||||
# 按触发类型过滤
|
||||
if trigger_type != "all":
|
||||
if trigger_type == "timer" and wf.trigger_type not in ["timer", None]:
|
||||
continue
|
||||
elif trigger_type == "event" and wf.trigger_type != "event":
|
||||
continue
|
||||
elif trigger_type == "manual" and wf.trigger_type != "manual":
|
||||
continue
|
||||
|
||||
# 按名称过滤(部分匹配)
|
||||
if name and wf.name and name.lower() not in wf.name.lower():
|
||||
continue
|
||||
|
||||
filtered_workflows.append(wf)
|
||||
|
||||
if not filtered_workflows:
|
||||
return "未找到相关工作流"
|
||||
|
||||
# 转换为字典格式,只保留关键信息
|
||||
simplified_workflows = []
|
||||
for wf in filtered_workflows:
|
||||
# 状态说明
|
||||
state_map = {
|
||||
"W": "等待",
|
||||
"R": "运行中",
|
||||
"P": "暂停",
|
||||
"S": "成功",
|
||||
"F": "失败"
|
||||
}
|
||||
state_desc = state_map.get(wf.state, wf.state)
|
||||
|
||||
# 触发类型说明
|
||||
trigger_type_map = {
|
||||
"timer": "定时触发",
|
||||
"event": "事件触发",
|
||||
"manual": "手动触发"
|
||||
}
|
||||
trigger_type_key = wf.trigger_type or "timer"
|
||||
trigger_type_desc = trigger_type_map.get(
|
||||
trigger_type_key,
|
||||
trigger_type_key,
|
||||
)
|
||||
|
||||
simplified = {
|
||||
"id": wf.id,
|
||||
"name": wf.name,
|
||||
"description": wf.description,
|
||||
"trigger_type": trigger_type_desc,
|
||||
"state": state_desc,
|
||||
"run_count": wf.run_count,
|
||||
"timer": wf.timer,
|
||||
"event_type": wf.event_type,
|
||||
"add_time": wf.add_time,
|
||||
"last_time": wf.last_time,
|
||||
"current_action": wf.current_action
|
||||
}
|
||||
# wf.result 往往是执行日志或上下文快照,不适合作为列表查询结果返回。
|
||||
simplified_workflows.append(simplified)
|
||||
|
||||
result_json = json.dumps(simplified_workflows, ensure_ascii=False, indent=2)
|
||||
return result_json
|
||||
except Exception as e:
|
||||
logger.error(f"查询工作流失败: {e}", exc_info=True)
|
||||
return f"查询工作流时发生错误: {str(e)}"
|
||||
@@ -1,282 +0,0 @@
|
||||
"""识别媒体信息工具"""
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
from typing import Optional, Type
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from app.agent.tools.base import MoviePilotTool
|
||||
from app.agent.tools.tags import ToolTag
|
||||
from app.chain.media import MediaChain
|
||||
from app.runtime.settings import get_runtime_setting
|
||||
|
||||
from app.domain.context import Context
|
||||
from app.domain.meta.metamusic import MetaMusic
|
||||
from app.domain.metainfo import MetaInfo
|
||||
from app.runtime.log import logger
|
||||
from app.schemas.types import MediaType, media_type_to_agent
|
||||
from ._music_utils import simplify_music_info
|
||||
|
||||
|
||||
class RecognizeMediaInput(BaseModel):
|
||||
"""识别媒体信息工具的输入参数模型"""
|
||||
title: Optional[str] = Field(None, description="The title of the torrent/media to recognize (required for torrent recognition)")
|
||||
subtitle: Optional[str] = Field(None, description="The subtitle or description of the torrent (optional, helps improve recognition accuracy)")
|
||||
path: Optional[str] = Field(None, description="The file path to recognize (required for file recognition, mutually exclusive with title)")
|
||||
media_type: Optional[str] = Field(
|
||||
None,
|
||||
description="Allowed values: movie, tv, music. Audio file paths are automatically treated as music",
|
||||
)
|
||||
artist: Optional[str] = Field(
|
||||
None,
|
||||
description="Artist name for music title recognition. Only valid with media_type='music'",
|
||||
)
|
||||
album: Optional[str] = Field(
|
||||
None,
|
||||
description="Album name for music title recognition. Only valid with media_type='music'",
|
||||
)
|
||||
|
||||
|
||||
class RecognizeMediaTool(MoviePilotTool):
|
||||
"""从标题或文件路径识别影视与单曲信息。"""
|
||||
|
||||
name: str = "recognize_media"
|
||||
tags: list[str] = [
|
||||
ToolTag.Read,
|
||||
ToolTag.Media,
|
||||
ToolTag.Metadata,
|
||||
]
|
||||
description: str = (
|
||||
"Extract media information from torrent titles or file paths. Supports movies, TV, and individual "
|
||||
"audio files. For music title recognition set media_type='music' and provide artist when known. "
|
||||
"Album and artist browsing by stable ID belongs to query_media_detail; use scrape_metadata for directories."
|
||||
)
|
||||
args_schema: Type[BaseModel] = RecognizeMediaInput
|
||||
|
||||
def get_tool_message(self, **kwargs) -> Optional[str]:
|
||||
"""根据识别参数生成友好的提示消息"""
|
||||
title = kwargs.get("title")
|
||||
subtitle = kwargs.get("subtitle")
|
||||
path = kwargs.get("path")
|
||||
media_type = kwargs.get("media_type")
|
||||
|
||||
if path:
|
||||
message = f"识别文件媒体信息: {path}"
|
||||
elif title:
|
||||
message = f"识别种子媒体信息: {title}"
|
||||
if subtitle:
|
||||
message += f" ({subtitle})"
|
||||
else:
|
||||
message = "识别媒体信息"
|
||||
if media_type:
|
||||
message += f" [{media_type}]"
|
||||
|
||||
return message
|
||||
|
||||
async def run(self, title: Optional[str] = None, subtitle: Optional[str] = None,
|
||||
path: Optional[str] = None, media_type: Optional[str] = None,
|
||||
artist: Optional[str] = None, album: Optional[str] = None,
|
||||
**kwargs) -> str:
|
||||
"""执行路径或标题识别,并按媒体类型选择正确的元数据链。"""
|
||||
logger.info(
|
||||
f"执行工具: {self.name}, 参数: title={title}, subtitle={subtitle}, "
|
||||
f"path={path}, media_type={media_type}, artist={artist}, album={album}"
|
||||
)
|
||||
|
||||
try:
|
||||
media_type_enum = None
|
||||
if media_type:
|
||||
media_type_enum = MediaType.from_agent(media_type)
|
||||
if not media_type_enum:
|
||||
return json.dumps({
|
||||
"success": False,
|
||||
"message": (
|
||||
f"无效的媒体类型 '{media_type}',"
|
||||
"支持的类型:'movie', 'tv', 'music'"
|
||||
),
|
||||
}, ensure_ascii=False)
|
||||
if (artist or album) and media_type_enum != MediaType.MUSIC:
|
||||
return json.dumps({
|
||||
"success": False,
|
||||
"message": "artist 和 album 仅能与 media_type='music' 一起使用",
|
||||
}, ensure_ascii=False)
|
||||
|
||||
is_audio_path = bool(
|
||||
path and Path(path).suffix.lower() in get_runtime_setting('RMT_AUDIOEXT')
|
||||
)
|
||||
recognize_music = media_type_enum == MediaType.MUSIC or (
|
||||
media_type_enum is None and is_audio_path
|
||||
)
|
||||
if recognize_music:
|
||||
if path:
|
||||
if not is_audio_path:
|
||||
return json.dumps({
|
||||
"success": False,
|
||||
"message": (
|
||||
"音乐路径识别只支持单个音频文件;目录请使用 "
|
||||
"scrape_metadata(media_type='music')"
|
||||
),
|
||||
"path": path,
|
||||
}, ensure_ascii=False)
|
||||
# 影视与音乐共用统一路径识别入口,音频后缀自动路由到音乐识别链
|
||||
context = await MediaChain().async_recognize_by_path(path)
|
||||
if context:
|
||||
return self._format_context_result(context, "音频文件")
|
||||
return json.dumps({
|
||||
"success": False,
|
||||
"message": f"无法识别音乐信息: {path}",
|
||||
"path": path,
|
||||
}, ensure_ascii=False)
|
||||
if title:
|
||||
metainfo = MetaMusic.parse_query(title)
|
||||
if artist:
|
||||
metainfo.artists = [artist]
|
||||
if album:
|
||||
metainfo.album = album
|
||||
mediainfo = await MediaChain().async_recognize_by_meta(metainfo)
|
||||
if mediainfo:
|
||||
context = Context(meta_info=metainfo, media_info=mediainfo)
|
||||
return self._format_context_result(context, "音乐标题")
|
||||
return json.dumps({
|
||||
"success": False,
|
||||
"message": f"无法识别音乐信息: {title}",
|
||||
"title": title,
|
||||
"artist": artist,
|
||||
"album": album,
|
||||
}, ensure_ascii=False)
|
||||
return json.dumps({
|
||||
"success": False,
|
||||
"message": "音乐识别必须提供 title 或单个音频文件 path",
|
||||
}, ensure_ascii=False)
|
||||
|
||||
media_chain = MediaChain()
|
||||
|
||||
# 根据提供的参数选择识别方式
|
||||
if path:
|
||||
# 文件路径识别
|
||||
if not path:
|
||||
return json.dumps({
|
||||
"success": False,
|
||||
"message": "文件路径不能为空"
|
||||
}, ensure_ascii=False)
|
||||
|
||||
context = await media_chain.async_recognize_by_path(
|
||||
path,
|
||||
obtain_images=False,
|
||||
)
|
||||
if context:
|
||||
return self._format_context_result(context, "文件")
|
||||
else:
|
||||
return json.dumps({
|
||||
"success": False,
|
||||
"message": f"无法识别文件媒体信息: {path}",
|
||||
"path": path
|
||||
}, ensure_ascii=False)
|
||||
|
||||
elif title:
|
||||
# 种子标题识别
|
||||
metainfo = MetaInfo(title, subtitle)
|
||||
mediainfo = await media_chain.async_recognize_by_meta(
|
||||
metainfo,
|
||||
obtain_images=False,
|
||||
)
|
||||
if mediainfo:
|
||||
context = Context(meta_info=metainfo, media_info=mediainfo)
|
||||
return self._format_context_result(context, "种子")
|
||||
else:
|
||||
return json.dumps({
|
||||
"success": False,
|
||||
"message": f"无法识别种子媒体信息: {title}",
|
||||
"title": title,
|
||||
"subtitle": subtitle
|
||||
}, ensure_ascii=False)
|
||||
|
||||
else:
|
||||
return json.dumps({
|
||||
"success": False,
|
||||
"message": "必须提供 title(标题)或 path(文件路径)参数之一"
|
||||
}, ensure_ascii=False)
|
||||
|
||||
except Exception as e:
|
||||
error_message = f"识别媒体信息失败: {str(e)}"
|
||||
logger.error(f"识别媒体信息失败: {e}", exc_info=True)
|
||||
return json.dumps({
|
||||
"success": False,
|
||||
"message": error_message
|
||||
}, ensure_ascii=False)
|
||||
|
||||
@staticmethod
|
||||
def _format_context_result(context: Context, source_type: str) -> str:
|
||||
"""格式化识别结果为JSON字符串"""
|
||||
if not context:
|
||||
return json.dumps({
|
||||
"success": False,
|
||||
"message": "识别结果为空"
|
||||
}, ensure_ascii=False)
|
||||
|
||||
context_dict = context.to_dict()
|
||||
media_info = context_dict.get("media_info")
|
||||
meta_info = context_dict.get("meta_info")
|
||||
|
||||
# 构建简化的结果
|
||||
result = {
|
||||
"success": True,
|
||||
"source_type": source_type,
|
||||
"media_info": None,
|
||||
"meta_info": None
|
||||
}
|
||||
|
||||
# 处理媒体信息
|
||||
if media_info:
|
||||
if getattr(context.media_info, "type", None) == MediaType.MUSIC:
|
||||
result["media_info"] = simplify_music_info(context.media_info)
|
||||
else:
|
||||
result["media_info"] = {
|
||||
"title": media_info.get("title"),
|
||||
"en_title": media_info.get("en_title"),
|
||||
"year": media_info.get("year"),
|
||||
"type": media_type_to_agent(media_info.get("type")),
|
||||
"season": media_info.get("season"),
|
||||
"media_source": media_info.get("media_source"),
|
||||
"media_id": media_info.get("media_id"),
|
||||
"overview": media_info.get("overview"),
|
||||
"vote_average": media_info.get("vote_average"),
|
||||
"poster_path": media_info.get("poster_path"),
|
||||
"backdrop_path": media_info.get("backdrop_path"),
|
||||
"detail_link": media_info.get("detail_link"),
|
||||
"title_year": media_info.get("title_year"),
|
||||
}
|
||||
|
||||
# 处理元数据信息
|
||||
if meta_info:
|
||||
if getattr(context.media_info, "type", None) == MediaType.MUSIC:
|
||||
result["meta_info"] = {
|
||||
key: meta_info.get(key)
|
||||
for key in (
|
||||
"title", "artists", "album", "album_artist", "year",
|
||||
"disc_number", "track_number", "total_discs", "total_tracks",
|
||||
"version", "audio_format", "bit_depth", "sample_rate", "bitrate",
|
||||
"duration", "isrc", "media_source", "media_id",
|
||||
)
|
||||
if meta_info.get(key) not in (None, "", [])
|
||||
}
|
||||
else:
|
||||
result["meta_info"] = {
|
||||
"name": meta_info.get("name"),
|
||||
"title": meta_info.get("title"),
|
||||
"year": meta_info.get("year"),
|
||||
"type": media_type_to_agent(meta_info.get("type")),
|
||||
"begin_season": meta_info.get("begin_season"),
|
||||
"end_season": meta_info.get("end_season"),
|
||||
"begin_episode": meta_info.get("begin_episode"),
|
||||
"end_episode": meta_info.get("end_episode"),
|
||||
"total_episode": meta_info.get("total_episode"),
|
||||
"part": meta_info.get("part"),
|
||||
"season_episode": meta_info.get("season_episode"),
|
||||
"episode_list": meta_info.get("episode_list"),
|
||||
"media_source": meta_info.get("media_source"),
|
||||
"media_id": meta_info.get("media_id"),
|
||||
}
|
||||
|
||||
return json.dumps(result, ensure_ascii=False, indent=2)
|
||||
@@ -1,104 +0,0 @@
|
||||
"""重载插件工具"""
|
||||
|
||||
import json
|
||||
from typing import Optional, Type
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from app.agent.tools.base import MoviePilotTool
|
||||
from app.agent.tools.tags import ToolTag
|
||||
from app.agent.tools.impl._plugin_tool_utils import (
|
||||
get_plugin_snapshot,
|
||||
reload_plugin_runtime,
|
||||
)
|
||||
from app.runtime.log import logger
|
||||
from app.schemas.plugin import PluginRuntimeStatus
|
||||
|
||||
|
||||
class ReloadPluginInput(BaseModel):
|
||||
"""重载插件工具的输入参数模型"""
|
||||
|
||||
plugin_id: str = Field(
|
||||
...,
|
||||
description="The plugin ID to reload so the latest saved config takes effect.",
|
||||
)
|
||||
|
||||
|
||||
class ReloadPluginTool(MoviePilotTool):
|
||||
name: str = "reload_plugin"
|
||||
tags: list[str] = [
|
||||
ToolTag.Write,
|
||||
ToolTag.Plugin,
|
||||
ToolTag.Admin,
|
||||
]
|
||||
description: str = (
|
||||
"Reload an installed plugin so its latest saved configuration takes effect. "
|
||||
"This also refreshes the plugin's registered commands, scheduled services, and API routes."
|
||||
)
|
||||
require_admin: bool = True
|
||||
args_schema: Type[BaseModel] = ReloadPluginInput
|
||||
|
||||
def get_tool_message(self, **kwargs) -> Optional[str]:
|
||||
"""生成友好的提示消息"""
|
||||
plugin_id = kwargs.get("plugin_id", "")
|
||||
return f"重载插件: {plugin_id}"
|
||||
|
||||
@staticmethod
|
||||
def _reload_plugin_sync(plugin_id: str) -> str:
|
||||
"""
|
||||
按后台接口同样的流程重载插件,确保最新配置和注册信息一起刷新。
|
||||
"""
|
||||
plugin_info = get_plugin_snapshot(plugin_id)
|
||||
if not plugin_info:
|
||||
return json.dumps(
|
||||
{
|
||||
"success": False,
|
||||
"message": f"插件 {plugin_id} 不存在,请先使用 query_installed_plugins 查询有效插件 ID",
|
||||
},
|
||||
ensure_ascii=False,
|
||||
)
|
||||
|
||||
runtime_status = reload_plugin_runtime(plugin_id)
|
||||
refreshed_plugin = get_plugin_snapshot(plugin_id) or plugin_info
|
||||
|
||||
if runtime_status is not PluginRuntimeStatus.ACTIVE:
|
||||
return json.dumps(
|
||||
{
|
||||
"success": False,
|
||||
**refreshed_plugin,
|
||||
"runtime_status": runtime_status,
|
||||
"message": (
|
||||
"未通过用户认证,请查看日志"
|
||||
if runtime_status is PluginRuntimeStatus.BLOCKED_BY_POLICY
|
||||
else "插件加载失败,请查看插件日志"
|
||||
),
|
||||
},
|
||||
ensure_ascii=False,
|
||||
indent=2,
|
||||
default=str,
|
||||
)
|
||||
|
||||
return json.dumps(
|
||||
{
|
||||
"success": True,
|
||||
**refreshed_plugin,
|
||||
"message": "插件已重载,最新配置已生效",
|
||||
},
|
||||
ensure_ascii=False,
|
||||
indent=2,
|
||||
default=str,
|
||||
)
|
||||
|
||||
async def run(self, plugin_id: str, **kwargs) -> str:
|
||||
logger.info(f"执行工具: {self.name}, 参数: plugin_id={plugin_id}")
|
||||
|
||||
try:
|
||||
return await self.run_blocking(
|
||||
"plugin", self._reload_plugin_sync, plugin_id
|
||||
)
|
||||
except Exception as e:
|
||||
logger.error(f"重载插件失败: {e}", exc_info=True)
|
||||
return json.dumps(
|
||||
{"success": False, "message": f"重载插件时发生错误: {str(e)}"},
|
||||
ensure_ascii=False,
|
||||
)
|
||||
@@ -1,77 +0,0 @@
|
||||
"""立即执行 Agent 自主定时任务工具。"""
|
||||
|
||||
from typing import Optional, Type
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from app.agent.tools.base import MoviePilotTool
|
||||
from app.agent.tools.tags import ToolTag
|
||||
|
||||
|
||||
class RunAgentTaskInput(BaseModel):
|
||||
"""立即执行 Agent 自主定时任务的输入参数。"""
|
||||
|
||||
task_id: int = Field(
|
||||
...,
|
||||
ge=1,
|
||||
description=(
|
||||
"Integer autonomous task ID returned by query_agent_tasks. Do not pass a "
|
||||
"runtime scheduler job_id such as agent-task-12."
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
class RunAgentTaskTool(MoviePilotTool):
|
||||
"""将当前用户的 Agent 自主定时任务提交为立即执行。"""
|
||||
|
||||
name: str = "run_agent_task"
|
||||
tags: list[str] = [ToolTag.Write, ToolTag.AgentTask, ToolTag.Admin]
|
||||
description: str = (
|
||||
"Queue an enabled autonomous agent task owned by the current user for immediate "
|
||||
"execution. Use the integer task_id returned by query_agent_tasks. The task runs "
|
||||
"after the current agent turn can finish and broadcasts its result through the "
|
||||
"configured notification channels."
|
||||
)
|
||||
args_schema: Type[BaseModel] = RunAgentTaskInput
|
||||
require_admin: bool = True
|
||||
|
||||
def get_tool_message(self, **kwargs: object) -> Optional[str]:
|
||||
"""生成立即执行 Agent 任务的提示消息。"""
|
||||
return f"立即执行自主定时任务:{kwargs.get('task_id', '')}"
|
||||
|
||||
def _get_task_state(self, task_id: int) -> tuple[str, Optional[str]]:
|
||||
"""校验任务归属和状态,返回可执行性及任务名称。"""
|
||||
task = self.data.tasks.get(
|
||||
task_id=task_id,
|
||||
user_id=str(self._user_id),
|
||||
)
|
||||
if not task:
|
||||
return "not_found", None
|
||||
if not task.enabled:
|
||||
return "disabled", task.name
|
||||
if task.last_status == "running":
|
||||
return "running", task.name
|
||||
return "ready", task.name
|
||||
|
||||
async def run(self, task_id: int, **kwargs: object) -> str:
|
||||
"""立即执行当前用户拥有且已启用的 Agent 自主定时任务。"""
|
||||
from app.application.scheduling import start_agent_task
|
||||
|
||||
payload = RunAgentTaskInput(task_id=task_id)
|
||||
status, task_name = await self.run_blocking(
|
||||
"db",
|
||||
self._get_task_state,
|
||||
payload.task_id,
|
||||
)
|
||||
if status == "not_found":
|
||||
return f"Agent 定时任务 {task_id} 不存在或不属于当前用户"
|
||||
if status == "disabled":
|
||||
return f"Agent 定时任务 {task_id} 已暂停,请先恢复后再执行"
|
||||
if status == "running":
|
||||
return f"Agent 定时任务 {task_id} 正在执行,请勿重复触发"
|
||||
if not start_agent_task(payload.task_id):
|
||||
return f"Agent 定时任务 {task_id} 尚未注册到运行时调度器,无法立即执行"
|
||||
return (
|
||||
f"Agent 定时任务 {task_id} 已提交立即执行:{task_name}。"
|
||||
"执行完成后将通过已配置的通知渠道广播结果"
|
||||
)
|
||||
@@ -1,81 +0,0 @@
|
||||
"""运行定时服务工具"""
|
||||
|
||||
from typing import Optional, Type
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from app.agent.tools.base import MoviePilotTool
|
||||
from app.agent.tools.tags import ToolTag
|
||||
from app.runtime.log import logger
|
||||
|
||||
|
||||
class RunSchedulerInput(BaseModel):
|
||||
"""运行定时服务工具的输入参数模型"""
|
||||
|
||||
job_id: str = Field(
|
||||
...,
|
||||
description=(
|
||||
"Runtime scheduler job ID returned by query_schedulers. Do not pass an "
|
||||
"autonomous agent task ID or an agent-task-* runtime ID."
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
class RunSchedulerTool(MoviePilotTool):
|
||||
"""立即运行系统、插件或工作流注册的定时服务。"""
|
||||
|
||||
name: str = "run_scheduler"
|
||||
tags: list[str] = [
|
||||
ToolTag.Write,
|
||||
ToolTag.Scheduler,
|
||||
ToolTag.Admin,
|
||||
]
|
||||
description: str = (
|
||||
"Manually trigger a MoviePilot system, plugin, or workflow scheduler service by "
|
||||
"the runtime job_id returned from query_schedulers. This tool does not run "
|
||||
"user-created autonomous agent tasks; use run_agent_task with an integer task_id."
|
||||
)
|
||||
args_schema: Type[BaseModel] = RunSchedulerInput
|
||||
require_admin: bool = True
|
||||
|
||||
def get_tool_message(self, **kwargs: object) -> Optional[str]:
|
||||
"""根据运行参数生成友好的提示消息。"""
|
||||
job_id = kwargs.get("job_id", "")
|
||||
return f"运行定时服务 (ID: {job_id})"
|
||||
|
||||
@staticmethod
|
||||
def _run_scheduler_sync(job_id: str) -> tuple[bool, str]:
|
||||
"""同步触发定时服务,避免调度器扫描阻塞事件循环。"""
|
||||
from app.application.scheduling import (
|
||||
list_scheduler_jobs,
|
||||
start_scheduler_job,
|
||||
)
|
||||
|
||||
for scheduler_item in list_scheduler_jobs():
|
||||
if scheduler_item.id == job_id:
|
||||
start_scheduler_job(job_id)
|
||||
return True, scheduler_item.name
|
||||
return False, ""
|
||||
|
||||
async def run(self, job_id: str, **kwargs: object) -> str:
|
||||
"""立即运行非 Agent 自主任务的运行时定时服务。"""
|
||||
logger.info(f"执行工具: {self.name}, 参数: job_id={job_id}")
|
||||
|
||||
try:
|
||||
from app.application.scheduling import AGENT_TASK_JOB_PREFIX
|
||||
|
||||
if job_id.startswith(f"{AGENT_TASK_JOB_PREFIX}-"):
|
||||
return (
|
||||
"Agent 自主定时任务不能通过 run_scheduler 运行,"
|
||||
"请使用 query_agent_tasks 查询整数 task_id 后调用 run_agent_task"
|
||||
)
|
||||
job_exists, job_name = await self.run_blocking(
|
||||
"workflow", self._run_scheduler_sync, job_id
|
||||
)
|
||||
if not job_exists:
|
||||
return f"定时服务 ID {job_id} 不存在,请使用 query_schedulers 工具查询可用的定时服务"
|
||||
|
||||
return f"成功触发定时服务:{job_name} (ID: {job_id})"
|
||||
except Exception as e:
|
||||
logger.error(f"运行定时服务失败: {e}", exc_info=True)
|
||||
return f"运行定时服务时发生错误: {str(e)}"
|
||||
@@ -1,116 +0,0 @@
|
||||
"""运行斜杠命令工具(系统命令 + 插件命令)"""
|
||||
|
||||
import json
|
||||
from typing import Optional, Type
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from app.agent.tools.base import MoviePilotTool
|
||||
from app.agent.tools.tags import ToolTag
|
||||
from app.runtime.events import eventmanager
|
||||
from app.runtime.log import logger
|
||||
from app.schemas.types import EventType, NotificationChannel
|
||||
|
||||
|
||||
class RunSlashCommandInput(BaseModel):
|
||||
"""运行斜杠命令工具的输入参数模型"""
|
||||
|
||||
command: str = Field(
|
||||
...,
|
||||
description="The slash command to execute, e.g. '/cookiecloud'. "
|
||||
"Must start with '/'. Can include arguments after the command, e.g. '/command arg1 arg2'. "
|
||||
"Use query_plugin_capabilities tool to discover available plugin commands, "
|
||||
"or list_slash_commands tool to discover all available commands (including system commands).",
|
||||
)
|
||||
|
||||
|
||||
class RunSlashCommandTool(MoviePilotTool):
|
||||
name: str = "run_slash_command"
|
||||
tags: list[str] = [
|
||||
ToolTag.Write,
|
||||
ToolTag.SlashCommand,
|
||||
ToolTag.Admin,
|
||||
]
|
||||
description: str = (
|
||||
"Execute a slash command (system or plugin) by sending a CommandExcute event. "
|
||||
"This tool supports ALL registered slash commands, including: "
|
||||
"1) System preset commands (e.g. /cookiecloud, /sites, /subscribes, /downloading, /transfer, /restart, etc.) "
|
||||
"2) Plugin commands registered by installed plugins. "
|
||||
"Use the query_plugin_capabilities tool to discover plugin commands, "
|
||||
"or the list_slash_commands tool to discover all available commands. "
|
||||
"The command will be executed asynchronously. "
|
||||
"Note: This tool triggers the command execution but the actual processing happens in the background."
|
||||
)
|
||||
args_schema: Type[BaseModel] = RunSlashCommandInput
|
||||
require_admin: bool = True
|
||||
|
||||
def get_tool_message(self, **kwargs) -> Optional[str]:
|
||||
"""生成友好的提示消息"""
|
||||
command = kwargs.get("command", "")
|
||||
return f"执行命令: {command}"
|
||||
|
||||
async def run(self, command: str, **kwargs) -> str:
|
||||
logger.info(f"执行工具: {self.name}, 参数: command={command}")
|
||||
|
||||
try:
|
||||
# 确保命令以 / 开头
|
||||
if not command.startswith("/"):
|
||||
command = f"/{command}"
|
||||
|
||||
# 从命令注册表中验证命令是否存在(包含系统预设命令 + 插件命令 + 其他命令)
|
||||
from app.application.commands import get_command, get_commands
|
||||
|
||||
cmd_name = command.split()[0]
|
||||
matched_command = get_command(cmd_name)
|
||||
|
||||
if not matched_command:
|
||||
# 列出所有可用命令帮助用户
|
||||
all_commands = get_commands()
|
||||
available_cmds = [
|
||||
f"{cmd} - {info.get('description', '无描述')}"
|
||||
for cmd, info in all_commands.items()
|
||||
]
|
||||
result = {
|
||||
"success": False,
|
||||
"message": f"命令 {cmd_name} 不存在",
|
||||
}
|
||||
if available_cmds:
|
||||
result["available_commands"] = available_cmds
|
||||
return json.dumps(result, ensure_ascii=False, indent=2)
|
||||
|
||||
# 构建消息渠道,优先使用当前会话的渠道信息
|
||||
channel = None
|
||||
if self._channel:
|
||||
try:
|
||||
channel = NotificationChannel(self._channel)
|
||||
except (ValueError, KeyError):
|
||||
channel = None
|
||||
|
||||
# 发送命令执行事件,与 message.py 中的方式一致
|
||||
eventmanager.send_event(
|
||||
EventType.CommandExcute,
|
||||
{
|
||||
"cmd": command,
|
||||
"user": self._user_id,
|
||||
"channel": channel,
|
||||
"source": self._source,
|
||||
},
|
||||
)
|
||||
|
||||
result = {
|
||||
"success": True,
|
||||
"message": f"命令 {cmd_name} 已触发执行",
|
||||
"command": command,
|
||||
"command_desc": matched_command.get("description", ""),
|
||||
}
|
||||
# 如果是插件命令,附加插件ID
|
||||
if matched_command.get("pid"):
|
||||
result["plugin_id"] = matched_command["pid"]
|
||||
return json.dumps(result, ensure_ascii=False, indent=2)
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"执行命令失败: {e}", exc_info=True)
|
||||
return json.dumps(
|
||||
{"success": False, "message": f"执行命令时发生错误: {str(e)}"},
|
||||
ensure_ascii=False,
|
||||
)
|
||||
@@ -1,84 +0,0 @@
|
||||
"""执行工作流工具"""
|
||||
|
||||
from typing import Optional, Type
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from app.agent.tools.base import MoviePilotTool
|
||||
from app.agent.tools.tags import ToolTag
|
||||
from app.chain.workflow import WorkflowChain
|
||||
from app.application.workflow import get_configured_workflow_query
|
||||
from app.runtime.log import logger
|
||||
|
||||
|
||||
class RunWorkflowInput(BaseModel):
|
||||
"""执行工作流工具的输入参数模型"""
|
||||
|
||||
workflow_id: int = Field(
|
||||
..., description="Workflow ID (can be obtained from query_workflows tool)"
|
||||
)
|
||||
from_begin: Optional[bool] = Field(
|
||||
True,
|
||||
description="Whether to run workflow from the beginning (default: True, if False will continue from last executed action)",
|
||||
)
|
||||
|
||||
|
||||
class RunWorkflowTool(MoviePilotTool):
|
||||
name: str = "run_workflow"
|
||||
tags: list[str] = [
|
||||
ToolTag.Write,
|
||||
ToolTag.Workflow,
|
||||
ToolTag.Admin,
|
||||
]
|
||||
description: str = "Execute a specific workflow manually by workflow ID. Supports running from the beginning or continuing from the last executed action."
|
||||
args_schema: Type[BaseModel] = RunWorkflowInput
|
||||
require_admin: bool = True
|
||||
|
||||
def get_tool_message(self, **kwargs) -> Optional[str]:
|
||||
"""根据工作流参数生成友好的提示消息"""
|
||||
workflow_id = kwargs.get("workflow_id")
|
||||
from_begin = kwargs.get("from_begin", True)
|
||||
|
||||
message = f"执行工作流: {workflow_id}"
|
||||
if not from_begin:
|
||||
message += " (从上次位置继续)"
|
||||
else:
|
||||
message += " (从头开始)"
|
||||
|
||||
return message
|
||||
|
||||
@staticmethod
|
||||
def _run_workflow_sync(
|
||||
workflow_id: int, from_begin: Optional[bool] = True
|
||||
) -> tuple[bool, str]:
|
||||
"""同步执行工作流,放到专用线程池避免长流程阻塞 API 响应。"""
|
||||
return WorkflowChain().process(workflow_id, from_begin=from_begin)
|
||||
|
||||
async def run(
|
||||
self, workflow_id: int, from_begin: Optional[bool] = True, **kwargs
|
||||
) -> str:
|
||||
logger.info(
|
||||
f"执行工具: {self.name}, 参数: workflow_id={workflow_id}, from_begin={from_begin}"
|
||||
)
|
||||
|
||||
try:
|
||||
workflow = await get_configured_workflow_query().get(workflow_id)
|
||||
|
||||
if not workflow:
|
||||
return f"未找到工作流:{workflow_id},请使用 query_workflows 工具查询可用的工作流"
|
||||
|
||||
# 工作流执行链路包含大量同步步骤,统一放到 workflow 线程池。
|
||||
state, errmsg = await self.run_blocking(
|
||||
"workflow",
|
||||
self._run_workflow_sync,
|
||||
workflow.id,
|
||||
from_begin,
|
||||
)
|
||||
|
||||
if not state:
|
||||
return f"执行工作流失败:{workflow.name} (ID: {workflow.id})\n错误原因:{errmsg}"
|
||||
else:
|
||||
return f"工作流执行成功:{workflow.name} (ID: {workflow.id})"
|
||||
except Exception as e:
|
||||
logger.error(f"执行工作流失败: {e}", exc_info=True)
|
||||
return f"执行工作流时发生错误: {str(e)}"
|
||||
@@ -1,310 +0,0 @@
|
||||
"""刮削媒体元数据工具"""
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
from typing import Optional, Type
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from app.agent.tools.base import MoviePilotTool
|
||||
from app.agent.tools.tags import ToolTag
|
||||
from app.chain.media import MediaChain
|
||||
from app.chain.scraping import ScrapingChain
|
||||
from app.runtime.settings import get_runtime_setting
|
||||
|
||||
from app.runtime.log import logger
|
||||
from app.schemas.workflow import FileItem
|
||||
from app.schemas.types import (
|
||||
MUSIC_ENTITY_ARTIST,
|
||||
MediaSource,
|
||||
MediaType,
|
||||
media_type_to_agent,
|
||||
)
|
||||
from app.schemas.media import normalize_media_source
|
||||
from app.domain.media import normalize_music_type
|
||||
from ._music_utils import simplify_music_info
|
||||
|
||||
|
||||
def _inspect_local_path(path: Path) -> tuple[bool, bool]:
|
||||
"""返回本地路径是否存在及是否为目录。"""
|
||||
exists = path.exists()
|
||||
return exists and path.is_dir(), exists
|
||||
|
||||
|
||||
class ScrapeMetadataInput(BaseModel):
|
||||
"""刮削媒体元数据工具的输入参数模型"""
|
||||
|
||||
path: str = Field(
|
||||
...,
|
||||
description="Path to the file or directory to scrape metadata for (e.g., '/path/to/file.mkv' or '/path/to/directory')",
|
||||
)
|
||||
storage: Optional[str] = Field(
|
||||
"local",
|
||||
description="Storage type: 'local' for local storage, 'smb', 'alist', etc. for remote storage (default: 'local')",
|
||||
)
|
||||
overwrite: Optional[bool] = Field(
|
||||
False,
|
||||
description="Whether to overwrite existing metadata files (default: False)",
|
||||
)
|
||||
media_type: Optional[str] = Field(
|
||||
None,
|
||||
description="Allowed values: movie, tv, music. Audio files are auto-detected; music directories should set music explicitly",
|
||||
)
|
||||
music_type: Optional[str] = Field(
|
||||
None,
|
||||
description="For an explicit music ID: recording for one file or album for a complete album directory",
|
||||
)
|
||||
media_source: Optional[MediaSource] = Field(
|
||||
None,
|
||||
description=(
|
||||
"Music metadata source: musicbrainz, theaudiodb, or doubanmusic. "
|
||||
"When omitted, automatic music recognition compares all sources. "
|
||||
"Must be paired with media_id when an ID is supplied"
|
||||
),
|
||||
)
|
||||
media_id: Optional[str] = Field(
|
||||
None,
|
||||
description="Source-native recording or album ID. Must be paired with media_source",
|
||||
)
|
||||
|
||||
|
||||
class ScrapeMetadataTool(MoviePilotTool):
|
||||
"""刮削影视 NFO/图片或音乐标签、封面与旁挂歌词。"""
|
||||
|
||||
name: str = "scrape_metadata"
|
||||
tags: list[str] = [
|
||||
ToolTag.Write,
|
||||
ToolTag.Media,
|
||||
ToolTag.Metadata,
|
||||
ToolTag.File,
|
||||
ToolTag.Admin,
|
||||
]
|
||||
description: str = (
|
||||
"Scrape existing movie, TV, or music files on local/remote storage. Video generates configured NFO and "
|
||||
"images. Music applies configured audio-tag and cover policies and can automatically download LRCLIB "
|
||||
"lyrics as same-name .lrc/.txt sidecars. A directory with an album ID is treated as one complete album; "
|
||||
"without an ID, each audio file is recognized independently."
|
||||
)
|
||||
require_admin: bool = True
|
||||
args_schema: Type[BaseModel] = ScrapeMetadataInput
|
||||
|
||||
def get_tool_message(self, **kwargs) -> Optional[str]:
|
||||
"""根据刮削参数生成友好的提示消息"""
|
||||
path = kwargs.get("path", "")
|
||||
storage = kwargs.get("storage", "local")
|
||||
overwrite = kwargs.get("overwrite", False)
|
||||
media_type = kwargs.get("media_type")
|
||||
|
||||
message = f"刮削媒体元数据: {path}"
|
||||
if storage != "local":
|
||||
message += f" [存储: {storage}]"
|
||||
if overwrite:
|
||||
message += " [覆盖模式]"
|
||||
if media_type:
|
||||
message += f" [{media_type}]"
|
||||
|
||||
return message
|
||||
|
||||
async def run(
|
||||
self,
|
||||
path: str,
|
||||
storage: Optional[str] = "local",
|
||||
overwrite: Optional[bool] = False,
|
||||
media_type: Optional[str] = None,
|
||||
music_type: Optional[str] = None,
|
||||
media_source: Optional[MediaSource] = None,
|
||||
media_id: Optional[str] = None,
|
||||
**kwargs,
|
||||
) -> str:
|
||||
"""识别刮削类型并将同步文件及外部元数据操作放入线程池。"""
|
||||
logger.info(
|
||||
f"执行工具: {self.name}, 参数: path={path}, storage={storage}, "
|
||||
f"overwrite={overwrite}, media_type={media_type}, music_type={music_type}, "
|
||||
f"media_source={media_source}, media_id={media_id}"
|
||||
)
|
||||
|
||||
try:
|
||||
# 验证路径
|
||||
if not path:
|
||||
return json.dumps(
|
||||
{"success": False, "message": "刮削路径不能为空"},
|
||||
ensure_ascii=False,
|
||||
)
|
||||
|
||||
media_type_enum = None
|
||||
if media_type:
|
||||
media_type_enum = MediaType.from_agent(media_type)
|
||||
if not media_type_enum:
|
||||
return json.dumps({
|
||||
"success": False,
|
||||
"message": (
|
||||
f"无效的媒体类型 '{media_type}',"
|
||||
"支持的类型:'movie', 'tv', 'music'"
|
||||
),
|
||||
}, ensure_ascii=False)
|
||||
explicit_identity = media_source is not None or media_id is not None
|
||||
normalized_source = normalize_media_source(media_source)
|
||||
normalized_media_id = str(media_id).strip() if media_id is not None else ""
|
||||
if explicit_identity and (
|
||||
not normalized_source or not normalized_media_id
|
||||
):
|
||||
return json.dumps({
|
||||
"success": False,
|
||||
"message": "必须同时提供有效的 media_source 和 media_id",
|
||||
}, ensure_ascii=False)
|
||||
media_source = normalized_source
|
||||
media_id = normalized_media_id or None
|
||||
|
||||
local_path = Path(path)
|
||||
is_local_directory = False
|
||||
path_exists = True
|
||||
if (storage or "local") == "local":
|
||||
is_local_directory, path_exists = await self.run_blocking(
|
||||
"storage",
|
||||
_inspect_local_path,
|
||||
local_path,
|
||||
)
|
||||
file_type = "dir" if is_local_directory or not local_path.suffix else "file"
|
||||
fileitem = FileItem(
|
||||
storage=storage or "local",
|
||||
path=path,
|
||||
type=file_type,
|
||||
)
|
||||
|
||||
# 检查本地存储路径是否存在
|
||||
if storage == "local":
|
||||
if not path_exists:
|
||||
return json.dumps(
|
||||
{"success": False, "message": f"刮削路径不存在: {path}"},
|
||||
ensure_ascii=False,
|
||||
)
|
||||
|
||||
media_chain = MediaChain()
|
||||
scraping_chain = ScrapingChain()
|
||||
is_audio_file = (
|
||||
fileitem.type == "file"
|
||||
and Path(path).suffix.lower() in get_runtime_setting('RMT_AUDIOEXT')
|
||||
)
|
||||
scrape_music = media_type_enum == MediaType.MUSIC or (
|
||||
media_type_enum is None and is_audio_file
|
||||
)
|
||||
if scrape_music:
|
||||
normalized_music_type = None
|
||||
if music_type:
|
||||
normalized_music_type = normalize_music_type(music_type)
|
||||
if not normalized_music_type:
|
||||
return json.dumps({
|
||||
"success": False,
|
||||
"message": (
|
||||
f"无效的音乐实体类型 '{music_type}',"
|
||||
"支持的类型:'recording', 'album'"
|
||||
),
|
||||
}, ensure_ascii=False)
|
||||
if normalized_music_type == MUSIC_ENTITY_ARTIST:
|
||||
return json.dumps({
|
||||
"success": False,
|
||||
"message": "艺术家是浏览实体,不能用于文件刮削",
|
||||
}, ensure_ascii=False)
|
||||
|
||||
mediainfo = None
|
||||
if media_source and media_id:
|
||||
recognize_kwargs = {
|
||||
"media_source": media_source,
|
||||
"media_id": media_id,
|
||||
"mtype": MediaType.MUSIC,
|
||||
}
|
||||
if normalized_music_type:
|
||||
recognize_kwargs["music_type"] = normalized_music_type
|
||||
mediainfo = await media_chain.async_recognize_media(
|
||||
**recognize_kwargs
|
||||
)
|
||||
if not mediainfo:
|
||||
return json.dumps({
|
||||
"success": False,
|
||||
"message": f"未识别到音乐信息: {media_source}:{media_id}",
|
||||
}, ensure_ascii=False)
|
||||
actual_music_type = getattr(mediainfo, "music_type", None)
|
||||
if normalized_music_type and actual_music_type != normalized_music_type:
|
||||
return json.dumps({
|
||||
"success": False,
|
||||
"message": (
|
||||
f"音乐实体类型不匹配:请求 {normalized_music_type},"
|
||||
f"实际 {actual_music_type or 'unknown'}"
|
||||
),
|
||||
}, ensure_ascii=False)
|
||||
|
||||
success, message = await self.run_blocking(
|
||||
"storage",
|
||||
scraping_chain.scrape_music_metadata,
|
||||
fileitem=fileitem,
|
||||
mediainfo=mediainfo,
|
||||
overwrite=bool(overwrite),
|
||||
media_source=media_source,
|
||||
)
|
||||
result = {
|
||||
"success": success,
|
||||
"message": message,
|
||||
"path": path,
|
||||
"type": "music",
|
||||
}
|
||||
if mediainfo:
|
||||
result["media_info"] = simplify_music_info(mediainfo)
|
||||
return json.dumps(result, ensure_ascii=False, indent=2)
|
||||
|
||||
if music_type or media_source or media_id:
|
||||
return json.dumps({
|
||||
"success": False,
|
||||
"message": "music_type、media_source 和 media_id 仅能用于音乐刮削",
|
||||
}, ensure_ascii=False)
|
||||
|
||||
# 影视沿用路径识别与 NFO/图片刮削链路。
|
||||
context = await media_chain.async_recognize_by_path(
|
||||
path,
|
||||
obtain_images=True,
|
||||
)
|
||||
|
||||
if not context or not context.media_info:
|
||||
return json.dumps(
|
||||
{
|
||||
"success": False,
|
||||
"message": f"刮削失败,无法识别媒体信息: {path}",
|
||||
"path": path,
|
||||
},
|
||||
ensure_ascii=False,
|
||||
)
|
||||
|
||||
# 刮削会包含磁盘写入和外部图片/元数据访问,统一放到 storage 线程池。
|
||||
await self.run_blocking(
|
||||
"storage",
|
||||
scraping_chain.scrape_metadata,
|
||||
fileitem=fileitem,
|
||||
meta=context.meta_info,
|
||||
mediainfo=context.media_info,
|
||||
overwrite=overwrite,
|
||||
)
|
||||
|
||||
return json.dumps(
|
||||
{
|
||||
"success": True,
|
||||
"message": f"{path} 刮削完成",
|
||||
"path": path,
|
||||
"media_info": {
|
||||
"title": context.media_info.title,
|
||||
"year": context.media_info.year,
|
||||
"type": media_type_to_agent(context.media_info.type),
|
||||
"media_source": context.media_info.media_source,
|
||||
"media_id": context.media_info.media_id,
|
||||
"season": context.media_info.season,
|
||||
},
|
||||
},
|
||||
ensure_ascii=False,
|
||||
indent=2,
|
||||
)
|
||||
|
||||
except Exception as e:
|
||||
error_message = f"刮削媒体元数据失败: {str(e)}"
|
||||
logger.error(f"刮削媒体元数据失败: {e}", exc_info=True)
|
||||
return json.dumps(
|
||||
{"success": False, "message": error_message, "path": path},
|
||||
ensure_ascii=False,
|
||||
)
|
||||
@@ -1,176 +0,0 @@
|
||||
"""搜索媒体工具"""
|
||||
|
||||
import json
|
||||
from typing import Optional, Type
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from app.agent.tools.base import MoviePilotTool
|
||||
from app.agent.tools.tags import ToolTag
|
||||
from app.chain.media import MediaChain
|
||||
from app.runtime.log import logger
|
||||
from app.schemas.types import MediaType, media_type_to_agent
|
||||
from app.schemas.media import resolve_media_identity
|
||||
from app.domain.media import normalize_music_type
|
||||
from ._music_utils import simplify_music_info
|
||||
|
||||
|
||||
class SearchMediaInput(BaseModel):
|
||||
"""搜索媒体工具的输入参数模型"""
|
||||
title: str = Field(..., description="The title of the media to search for (e.g., 'The Matrix', 'Breaking Bad')")
|
||||
year: Optional[str] = Field(None, description="Release year of the media (optional, helps narrow down results)")
|
||||
media_type: Optional[str] = Field(None,
|
||||
description="Allowed values: movie, tv, music")
|
||||
music_type: Optional[str] = Field(
|
||||
None,
|
||||
description="Music entity filter: recording, album, or artist. Only valid when media_type='music'",
|
||||
)
|
||||
season: Optional[int] = Field(None,
|
||||
description="Season number for TV shows and anime (optional, only applicable for series)")
|
||||
|
||||
|
||||
class SearchMediaTool(MoviePilotTool):
|
||||
"""按标题搜索影视或音乐元数据候选。"""
|
||||
|
||||
name: str = "search_media"
|
||||
tags: list[str] = [
|
||||
ToolTag.Read,
|
||||
ToolTag.Media,
|
||||
]
|
||||
description: str = (
|
||||
"Search metadata databases for movies, TV shows, music recordings, albums, or artists. "
|
||||
"For music, set media_type='music' and optionally filter music_type as recording, album, or artist. "
|
||||
"Returns source-native IDs that must be reused for detail, subscription, torrent, and library operations."
|
||||
)
|
||||
args_schema: Type[BaseModel] = SearchMediaInput
|
||||
|
||||
def get_tool_message(self, **kwargs) -> Optional[str]:
|
||||
"""根据搜索参数生成友好的提示消息"""
|
||||
title = kwargs.get("title", "")
|
||||
year = kwargs.get("year")
|
||||
media_type = kwargs.get("media_type")
|
||||
music_type = kwargs.get("music_type")
|
||||
season = kwargs.get("season")
|
||||
|
||||
message = f"搜索媒体: {title}"
|
||||
if year:
|
||||
message += f" ({year})"
|
||||
if media_type:
|
||||
message += f" [{media_type}]"
|
||||
if music_type:
|
||||
message += f" [{music_type}]"
|
||||
if season is not None:
|
||||
message += f" 第{season}季"
|
||||
|
||||
return message
|
||||
|
||||
async def run(self, title: str, year: Optional[str] = None,
|
||||
media_type: Optional[str] = None, season: Optional[int] = None,
|
||||
music_type: Optional[str] = None, **kwargs) -> str:
|
||||
"""执行元数据搜索并返回可复用的精简媒体身份。"""
|
||||
logger.info(
|
||||
f"执行工具: {self.name}, 参数: title={title}, year={year}, "
|
||||
f"media_type={media_type}, season={season}, music_type={music_type}")
|
||||
|
||||
try:
|
||||
media_type_enum = None
|
||||
if media_type:
|
||||
media_type_enum = MediaType.from_agent(media_type)
|
||||
if not media_type_enum:
|
||||
return f"错误:无效的媒体类型 '{media_type}',支持的类型:'movie', 'tv', 'music'"
|
||||
|
||||
if music_type and media_type_enum != MediaType.MUSIC:
|
||||
return "错误:music_type 仅能与 media_type='music' 一起使用"
|
||||
|
||||
if media_type_enum == MediaType.MUSIC:
|
||||
if season is not None:
|
||||
return "错误:音乐没有季号,搜索音乐时不能传入 season"
|
||||
normalized_music_type = None
|
||||
if music_type:
|
||||
normalized_music_type = normalize_music_type(music_type)
|
||||
if not normalized_music_type:
|
||||
return (
|
||||
f"错误:无效的音乐实体类型 '{music_type}',"
|
||||
"支持的类型:'recording', 'album', 'artist'"
|
||||
)
|
||||
results = await MediaChain().async_search_music(query=title, limit=100)
|
||||
filtered_music = [
|
||||
item
|
||||
for item in results or []
|
||||
if (not year or str(item.year or "") == str(year))
|
||||
and (
|
||||
not normalized_music_type
|
||||
or item.music_type == normalized_music_type
|
||||
)
|
||||
]
|
||||
if not filtered_music:
|
||||
return f"未找到符合条件的音乐资源: {title}"
|
||||
total_count = len(filtered_music)
|
||||
limited_results = filtered_music[:30]
|
||||
result_json = json.dumps(
|
||||
[simplify_music_info(item) for item in limited_results],
|
||||
ensure_ascii=False,
|
||||
indent=2,
|
||||
)
|
||||
if total_count > len(limited_results):
|
||||
return (
|
||||
f"注意:搜索结果共找到 {total_count} 条,为节省上下文空间,"
|
||||
f"仅显示前 {len(limited_results)} 条结果。\n\n{result_json}"
|
||||
)
|
||||
return result_json
|
||||
|
||||
media_chain = MediaChain()
|
||||
_, results = await media_chain.async_search(title=title)
|
||||
|
||||
# 过滤结果
|
||||
if results:
|
||||
filtered_results = []
|
||||
for result in results:
|
||||
if year and str(result.year or "") != str(year):
|
||||
continue
|
||||
if media_type_enum and result.type != media_type_enum:
|
||||
continue
|
||||
if season is not None and result.season != season:
|
||||
continue
|
||||
filtered_results.append(result)
|
||||
|
||||
if filtered_results:
|
||||
# 搜索结果只返回前 30 条,后续可通过更精确的年份/类型条件缩小范围。
|
||||
total_count = len(filtered_results)
|
||||
limited_results = filtered_results[:30]
|
||||
# 精简字段,只保留关键信息
|
||||
simplified_results = []
|
||||
for r in limited_results:
|
||||
media_source, media_id = resolve_media_identity(media=r)
|
||||
simplified = {
|
||||
"title": r.title,
|
||||
"en_title": r.en_title,
|
||||
"year": r.year,
|
||||
"type": media_type_to_agent(r.type),
|
||||
"season": r.season,
|
||||
"tmdb_id": r.tmdb_id,
|
||||
"imdb_id": r.imdb_id,
|
||||
"douban_id": r.douban_id,
|
||||
"bangumi_id": r.bangumi_id,
|
||||
"anilist_id": r.anilist_id,
|
||||
"media_source": media_source,
|
||||
"media_id": media_id,
|
||||
"overview": r.overview[:200] + "..." if r.overview and len(r.overview) > 200 else r.overview,
|
||||
"vote_average": r.vote_average,
|
||||
"poster_path": r.poster_path,
|
||||
"detail_link": r.detail_link
|
||||
}
|
||||
simplified_results.append(simplified)
|
||||
result_json = json.dumps(simplified_results, ensure_ascii=False, indent=2)
|
||||
# 如果结果被裁剪,添加提示信息
|
||||
if total_count > len(limited_results):
|
||||
return f"注意:搜索结果共找到 {total_count} 条,为节省上下文空间,仅显示前 {len(limited_results)} 条结果。\n\n{result_json}"
|
||||
return result_json
|
||||
else:
|
||||
return f"未找到符合条件的媒体资源: {title}"
|
||||
else:
|
||||
return f"未找到相关媒体资源: {title}"
|
||||
except Exception as e:
|
||||
error_message = f"搜索媒体失败: {str(e)}"
|
||||
logger.error(f"搜索媒体失败: {e}", exc_info=True)
|
||||
return error_message
|
||||
@@ -1,87 +0,0 @@
|
||||
"""搜索人物工具"""
|
||||
|
||||
import json
|
||||
from typing import Optional, Type
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from app.agent.tools.base import MoviePilotTool
|
||||
from app.agent.tools.tags import ToolTag
|
||||
from app.chain.media import MediaChain
|
||||
from app.runtime.log import logger
|
||||
|
||||
|
||||
class SearchPersonInput(BaseModel):
|
||||
"""搜索人物工具的输入参数模型"""
|
||||
name: str = Field(..., description="The name of the person to search for (e.g., 'Tom Hanks', '周杰伦')")
|
||||
|
||||
|
||||
class SearchPersonTool(MoviePilotTool):
|
||||
name: str = "search_person"
|
||||
tags: list[str] = [
|
||||
ToolTag.Read,
|
||||
ToolTag.Media,
|
||||
]
|
||||
description: str = "Search for person information including actors, directors, etc. Supports searching by name. Returns detailed person information from TMDB, Douban, or Bangumi database."
|
||||
args_schema: Type[BaseModel] = SearchPersonInput
|
||||
|
||||
def get_tool_message(self, **kwargs) -> Optional[str]:
|
||||
"""根据搜索参数生成友好的提示消息"""
|
||||
name = kwargs.get("name", "")
|
||||
return f"搜索人物: {name}"
|
||||
|
||||
async def run(self, name: str, **kwargs) -> str:
|
||||
logger.info(f"执行工具: {self.name}, 参数: name={name}")
|
||||
|
||||
try:
|
||||
media_chain = MediaChain()
|
||||
# 使用 MediaChain.async_search_persons 方法搜索人物
|
||||
persons = await media_chain.async_search_persons(name=name)
|
||||
|
||||
if persons:
|
||||
# 人物搜索结果只返回前 30 条,避免 biography/别名等字段挤占上下文。
|
||||
total_count = len(persons)
|
||||
limited_persons = persons[:30]
|
||||
# 精简字段,只保留关键信息
|
||||
simplified_results = []
|
||||
for person in limited_persons:
|
||||
simplified = {
|
||||
"name": person.name,
|
||||
"id": person.id,
|
||||
"source": person.source,
|
||||
"profile_path": person.profile_path,
|
||||
"original_name": person.original_name,
|
||||
"known_for_department": person.known_for_department,
|
||||
"popularity": person.popularity,
|
||||
"biography": person.biography[:200] + "..." if person.biography and len(person.biography) > 200 else person.biography,
|
||||
"birthday": person.birthday,
|
||||
"deathday": person.deathday,
|
||||
"place_of_birth": person.place_of_birth,
|
||||
"gender": person.gender,
|
||||
"imdb_id": person.imdb_id,
|
||||
"also_known_as": person.also_known_as[:5] if person.also_known_as else [], # 限制别名数量
|
||||
}
|
||||
# 添加豆瓣特有字段
|
||||
if person.source == "douban":
|
||||
simplified["url"] = person.url
|
||||
simplified["avatar"] = person.avatar
|
||||
simplified["latin_name"] = person.latin_name
|
||||
simplified["roles"] = person.roles[:5] if person.roles else [] # 限制角色数量
|
||||
# 添加Bangumi特有字段
|
||||
if person.source == "bangumi":
|
||||
simplified["career"] = person.career
|
||||
simplified["relation"] = person.relation
|
||||
|
||||
simplified_results.append(simplified)
|
||||
|
||||
result_json = json.dumps(simplified_results, ensure_ascii=False, indent=2)
|
||||
# 如果结果被裁剪,添加提示信息
|
||||
if total_count > len(limited_persons):
|
||||
return f"注意:搜索结果共找到 {total_count} 条,为节省上下文空间,仅显示前 {len(limited_persons)} 条结果。\n\n{result_json}"
|
||||
return result_json
|
||||
else:
|
||||
return f"未找到相关人物信息: {name}"
|
||||
except Exception as e:
|
||||
error_message = f"搜索人物失败: {str(e)}"
|
||||
logger.error(f"搜索人物失败: {e}", exc_info=True)
|
||||
return error_message
|
||||
@@ -1,95 +0,0 @@
|
||||
"""搜索演员参演作品工具"""
|
||||
|
||||
import json
|
||||
from typing import Optional, Type
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from app.agent.tools.base import MoviePilotTool
|
||||
from app.agent.tools.tags import ToolTag
|
||||
from app.chain.douban import DoubanChain
|
||||
from app.chain.tmdb import TmdbChain
|
||||
from app.chain.bangumi import BangumiChain
|
||||
from app.runtime.log import logger
|
||||
from app.schemas.media import resolve_media_identity
|
||||
|
||||
|
||||
class SearchPersonCreditsInput(BaseModel):
|
||||
"""搜索演员参演作品工具的输入参数模型"""
|
||||
person_id: int = Field(..., description="The ID of the person/actor to search for credits (e.g., 31 for Tom Hanks in TMDB)")
|
||||
source: str = Field(..., description="The data source: 'tmdb' for TheMovieDB, 'douban' for Douban, 'bangumi' for Bangumi")
|
||||
page: Optional[int] = Field(1, description="Page number for pagination (default: 1)")
|
||||
|
||||
|
||||
class SearchPersonCreditsTool(MoviePilotTool):
|
||||
name: str = "search_person_credits"
|
||||
tags: list[str] = [
|
||||
ToolTag.Read,
|
||||
ToolTag.Media,
|
||||
]
|
||||
description: str = "Search for films and TV shows that a person/actor has appeared in (filmography). Supports searching by person ID from TMDB, Douban, or Bangumi database. Returns a list of media works the person has participated in."
|
||||
args_schema: Type[BaseModel] = SearchPersonCreditsInput
|
||||
|
||||
def get_tool_message(self, **kwargs) -> Optional[str]:
|
||||
"""根据搜索参数生成友好的提示消息"""
|
||||
person_id = kwargs.get("person_id", "")
|
||||
source = kwargs.get("source", "")
|
||||
return f"搜索人物参演作品: {source} ID {person_id}"
|
||||
|
||||
async def run(self, person_id: int, source: str, page: Optional[int] = 1, **kwargs) -> str:
|
||||
logger.info(f"执行工具: {self.name}, 参数: person_id={person_id}, source={source}, page={page}")
|
||||
|
||||
try:
|
||||
# 根据source选择相应的chain
|
||||
if source.lower() == "tmdb":
|
||||
tmdb_chain = TmdbChain()
|
||||
medias = await tmdb_chain.async_person_credits(person_id=person_id, page=page)
|
||||
elif source.lower() == "douban":
|
||||
douban_chain = DoubanChain()
|
||||
medias = await douban_chain.async_person_credits(person_id=person_id, page=page)
|
||||
elif source.lower() == "bangumi":
|
||||
bangumi_chain = BangumiChain()
|
||||
medias = await bangumi_chain.async_person_credits(person_id=person_id)
|
||||
else:
|
||||
return f"不支持的数据源: {source}。支持的数据源: tmdb, douban, bangumi"
|
||||
|
||||
if medias:
|
||||
# 限制最多30条结果
|
||||
total_count = len(medias)
|
||||
limited_medias = medias[:30]
|
||||
# 精简字段,只保留关键信息
|
||||
simplified_results = []
|
||||
for media in limited_medias:
|
||||
media_source, media_id = resolve_media_identity(media=media)
|
||||
simplified = {
|
||||
"title": media.title,
|
||||
"en_title": media.en_title,
|
||||
"year": media.year,
|
||||
"type": media.type.value if media.type else None,
|
||||
"season": media.season,
|
||||
"tmdb_id": media.tmdb_id,
|
||||
"imdb_id": media.imdb_id,
|
||||
"douban_id": media.douban_id,
|
||||
"bangumi_id": media.bangumi_id,
|
||||
"anilist_id": media.anilist_id,
|
||||
"media_source": media_source,
|
||||
"media_id": media_id,
|
||||
"overview": media.overview[:200] + "..." if media.overview and len(media.overview) > 200 else media.overview,
|
||||
"vote_average": media.vote_average,
|
||||
"poster_path": media.poster_path,
|
||||
"backdrop_path": media.backdrop_path,
|
||||
"detail_link": media.detail_link
|
||||
}
|
||||
simplified_results.append(simplified)
|
||||
|
||||
result_json = json.dumps(simplified_results, ensure_ascii=False, indent=2)
|
||||
# 如果结果被裁剪,添加提示信息
|
||||
if total_count > 30:
|
||||
return f"注意:搜索结果共找到 {total_count} 条,为节省上下文空间,仅显示前 30 条结果。\n\n{result_json}"
|
||||
return result_json
|
||||
else:
|
||||
return f"未找到人物 ID {person_id} ({source}) 的参演作品"
|
||||
except Exception as e:
|
||||
error_message = f"搜索演员参演作品失败: {str(e)}"
|
||||
logger.error(f"搜索演员参演作品失败: {e}", exc_info=True)
|
||||
return error_message
|
||||
@@ -1,144 +0,0 @@
|
||||
"""搜索订阅缺失资源工具"""
|
||||
|
||||
import json
|
||||
from typing import List, Optional, Type
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from app.agent.tools.base import MoviePilotTool
|
||||
from app.agent.tools.tags import ToolTag
|
||||
from app.application.subscription.mutation import SubscriptionActor
|
||||
from app.chain.subscribe.facade import SubscribeChain
|
||||
from app.runtime.log import logger
|
||||
from app.schemas.types import media_type_to_agent
|
||||
|
||||
|
||||
class SearchSubscribeInput(BaseModel):
|
||||
"""搜索订阅缺失资源工具的输入参数模型"""
|
||||
subscribe_id: int = Field(..., description="The subscription ID to search for missing resources (from query_subscribes)")
|
||||
manual: Optional[bool] = Field(False, description="Whether this is a manual search (default: False)")
|
||||
filter_groups: Optional[List[str]] = Field(None,
|
||||
description="List of filter rule group names to apply for this search (optional, can be obtained from query_rule_groups tool. If provided, will temporarily update the subscription's filter groups before searching)")
|
||||
|
||||
|
||||
class SearchSubscribeTool(MoviePilotTool):
|
||||
"""立即搜索电影、剧集、单曲或专辑订阅的缺失资源。"""
|
||||
|
||||
name: str = "search_subscribe"
|
||||
tags: list[str] = [
|
||||
ToolTag.Read,
|
||||
ToolTag.Write,
|
||||
ToolTag.Subscription,
|
||||
ToolTag.Resource,
|
||||
]
|
||||
description: str = (
|
||||
"Search and automatically download missing resources for one subscription. Supports movies, TV episodes, "
|
||||
"single recordings, and complete albums. Album search keeps the subscription active unless downloaded "
|
||||
"files are confirmed to cover the expected track count."
|
||||
)
|
||||
args_schema: Type[BaseModel] = SearchSubscribeInput
|
||||
|
||||
def get_tool_message(self, **kwargs) -> Optional[str]:
|
||||
"""根据搜索参数生成友好的提示消息"""
|
||||
subscribe_id = kwargs.get("subscribe_id")
|
||||
manual = kwargs.get("manual", False)
|
||||
|
||||
message = f"搜索订阅 #{subscribe_id} 的缺失资源"
|
||||
if manual:
|
||||
message += "(手动搜索)"
|
||||
|
||||
return message
|
||||
|
||||
async def run(self, subscribe_id: int, manual: Optional[bool] = False,
|
||||
filter_groups: Optional[List[str]] = None, **kwargs) -> str:
|
||||
"""验证订阅状态并触发一次订阅资源搜索。"""
|
||||
logger.info(
|
||||
f"执行工具: {self.name}, 参数: subscribe_id={subscribe_id}, manual={manual}, filter_groups={filter_groups}")
|
||||
|
||||
try:
|
||||
# 先验证订阅是否存在
|
||||
repository = self.data.subscriptions
|
||||
subscribe = await repository.async_get(subscribe_id)
|
||||
|
||||
if not subscribe:
|
||||
return json.dumps({
|
||||
"success": False,
|
||||
"message": f"订阅不存在: {subscribe_id}"
|
||||
}, ensure_ascii=False)
|
||||
|
||||
# 获取订阅信息用于返回
|
||||
subscribe_info = {
|
||||
"id": subscribe.id,
|
||||
"name": subscribe.name,
|
||||
"year": subscribe.year,
|
||||
"type": media_type_to_agent(subscribe.type),
|
||||
"season": subscribe.season,
|
||||
"state": subscribe.state,
|
||||
"total_episode": subscribe.total_episode,
|
||||
"lack_episode": subscribe.lack_episode,
|
||||
"media_source": subscribe.media_source,
|
||||
"media_id": subscribe.media_id,
|
||||
"music_type": subscribe.music_type,
|
||||
"total_tracks": subscribe.total_tracks,
|
||||
"description": subscribe.description,
|
||||
}
|
||||
|
||||
# 检查订阅状态
|
||||
if subscribe.state == "S":
|
||||
return json.dumps({
|
||||
"success": False,
|
||||
"message": f"订阅 #{subscribe_id} ({subscribe.name}) 已暂停,无法搜索",
|
||||
"subscribe": subscribe_info
|
||||
}, ensure_ascii=False)
|
||||
|
||||
# 如果提供了 filter_groups 参数,先更新订阅的规则组
|
||||
if filter_groups is not None:
|
||||
async with self.data.subscription_mutation_scope() as mutation:
|
||||
await mutation.update(
|
||||
subscribe_id,
|
||||
{"filter_groups": filter_groups},
|
||||
SubscriptionActor(name="agent", is_superuser=True),
|
||||
existing=subscribe,
|
||||
scene="agent_search",
|
||||
)
|
||||
logger.info(f"更新订阅 #{subscribe_id} 的规则组为: {filter_groups}")
|
||||
|
||||
# 订阅搜索会触发大量同步站点访问,统一走 subscribe 线程池。
|
||||
await self.run_blocking(
|
||||
"subscribe",
|
||||
SubscribeChain().search,
|
||||
sid=subscribe_id,
|
||||
state="R", # 当 sid 有值时此参数会被忽略
|
||||
manual=manual,
|
||||
)
|
||||
|
||||
# 重新获取订阅信息以获取更新后的状态
|
||||
updated_subscribe = await repository.async_get(subscribe_id)
|
||||
if updated_subscribe:
|
||||
subscribe_info.update({
|
||||
"state": updated_subscribe.state,
|
||||
"lack_episode": updated_subscribe.lack_episode,
|
||||
"last_update": updated_subscribe.last_update,
|
||||
"filter_groups": updated_subscribe.filter_groups
|
||||
})
|
||||
|
||||
# 如果提供了规则组,会在返回信息中显示
|
||||
result = {
|
||||
"success": True,
|
||||
"message": f"订阅 #{subscribe_id} ({subscribe.name}) 搜索完成",
|
||||
"subscribe": subscribe_info
|
||||
}
|
||||
|
||||
if filter_groups is not None:
|
||||
result["message"] += f"(已应用规则组: {', '.join(filter_groups)})"
|
||||
|
||||
return json.dumps(result, ensure_ascii=False, indent=2)
|
||||
|
||||
except Exception as e:
|
||||
error_message = f"搜索订阅缺失资源失败: {str(e)}"
|
||||
logger.error(f"搜索订阅缺失资源失败: {e}", exc_info=True)
|
||||
return json.dumps({
|
||||
"success": False,
|
||||
"message": error_message,
|
||||
"subscribe_id": subscribe_id
|
||||
}, ensure_ascii=False)
|
||||
@@ -1,144 +0,0 @@
|
||||
"""搜索种子工具"""
|
||||
|
||||
import json
|
||||
from typing import List, Optional, Type
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from app.agent.tools.base import MoviePilotTool
|
||||
from app.agent.tools.tags import ToolTag
|
||||
from app.chain.search.facade import SearchChain
|
||||
from app.application.configuration import get_configured_system_config
|
||||
from app.application.site.sites import SitesHelper # pylint: disable=import-error,no-name-in-module
|
||||
from app.runtime.log import logger
|
||||
from app.schemas.types import MediaSource, MediaType, SystemConfigKey
|
||||
from app.domain.media import normalize_music_type
|
||||
from ._torrent_search_utils import (
|
||||
SEARCH_RESULT_CACHE_FILE,
|
||||
build_filter_options,
|
||||
)
|
||||
|
||||
|
||||
class SearchTorrentsInput(BaseModel):
|
||||
"""搜索种子工具的输入参数模型"""
|
||||
media_source: MediaSource = Field(..., description="Media metadata source")
|
||||
media_id: str = Field(..., description="Native ID for media_source")
|
||||
media_type: Optional[str] = Field(None, description="Allowed values: movie, tv, music")
|
||||
music_type: Optional[str] = Field(
|
||||
None,
|
||||
description="Music target entity: recording or album. Artists cannot be searched as torrent targets",
|
||||
)
|
||||
area: Optional[str] = Field(None, description="Search scope: 'title' (default) or 'imdbid'")
|
||||
sites: Optional[List[int]] = Field(None,
|
||||
description="Array of specific site IDs to search on (optional, if not provided searches all configured sites)")
|
||||
|
||||
|
||||
class SearchTorrentsTool(MoviePilotTool):
|
||||
"""按稳定媒体身份搜索影视、单曲或整张专辑资源。"""
|
||||
|
||||
name: str = "search_torrents"
|
||||
tags: list[str] = [
|
||||
ToolTag.Read,
|
||||
ToolTag.Resource,
|
||||
ToolTag.Site,
|
||||
ToolTag.Media,
|
||||
]
|
||||
description: str = (
|
||||
"Search for torrent files by media ID across configured indexer sites, cache the matched results, "
|
||||
"and return available filter options for follow-up selection. "
|
||||
"Accepts one MediaSource enum value and its source-native media ID. "
|
||||
"Music targets are one recording or one complete album; artists are browse-only.")
|
||||
args_schema: Type[BaseModel] = SearchTorrentsInput
|
||||
|
||||
def get_tool_message(self, **kwargs) -> Optional[str]:
|
||||
"""根据搜索参数生成友好的提示消息"""
|
||||
media_type = kwargs.get("media_type")
|
||||
source = kwargs.get("media_source")
|
||||
media_id = kwargs.get("media_id")
|
||||
message = f"搜索种子: {source}={media_id}" if source and media_id else "搜索种子"
|
||||
if media_type:
|
||||
message += f" [{media_type}]"
|
||||
return message
|
||||
|
||||
@staticmethod
|
||||
def _load_configured_sites() -> List[int]:
|
||||
"""同步读取默认搜索站点列表。"""
|
||||
return get_configured_system_config().get(SystemConfigKey.IndexerSites) or []
|
||||
|
||||
async def run(self, media_source: MediaSource, media_id: str,
|
||||
media_type: Optional[str] = None, area: Optional[str] = None,
|
||||
sites: Optional[List[int]] = None,
|
||||
music_type: Optional[str] = None, **kwargs) -> str:
|
||||
"""执行精确资源搜索并缓存带完整音乐上下文的候选。"""
|
||||
logger.info(
|
||||
f"执行工具: {self.name}, 参数: media_source={media_source}, "
|
||||
f"media_id={media_id}, media_type={media_type}, area={area}, sites={sites}"
|
||||
)
|
||||
|
||||
if not media_source or not str(media_id or "").strip():
|
||||
return "参数错误:media_source 和 media_id 必须同时提供。"
|
||||
|
||||
try:
|
||||
search_chain = SearchChain()
|
||||
media_type_enum = None
|
||||
if media_type:
|
||||
media_type_enum = MediaType.from_agent(media_type)
|
||||
if not media_type_enum:
|
||||
return f"错误:无效的媒体类型 '{media_type}',支持的类型:'movie', 'tv', 'music'"
|
||||
|
||||
normalized_music_type = None
|
||||
if music_type:
|
||||
normalized_music_type = normalize_music_type(
|
||||
music_type,
|
||||
allow_artist=False,
|
||||
)
|
||||
if not normalized_music_type:
|
||||
return (
|
||||
f"错误:无效的音乐实体类型 '{music_type}',"
|
||||
"支持的类型:'recording', 'album'"
|
||||
)
|
||||
if media_type_enum != MediaType.MUSIC:
|
||||
return "错误:music_type 仅能与 media_type='music' 一起使用"
|
||||
if media_type_enum == MediaType.MUSIC:
|
||||
if area == "imdbid":
|
||||
return "错误:音乐不支持按 IMDb ID 搜索"
|
||||
|
||||
filtered_torrents = await search_chain.async_search_by_id(
|
||||
media_source=media_source,
|
||||
media_id=media_id,
|
||||
mtype=media_type_enum,
|
||||
music_type=normalized_music_type,
|
||||
area=area or "title",
|
||||
sites=sites,
|
||||
cache_local=False,
|
||||
)
|
||||
# 获取站点信息
|
||||
all_indexers = await SitesHelper().async_get_indexers()
|
||||
all_sites = [{"id": indexer.get("id"), "name": indexer.get("name")} for indexer in (all_indexers or [])]
|
||||
|
||||
if sites:
|
||||
search_site_ids = sites
|
||||
else:
|
||||
search_site_ids = self._load_configured_sites()
|
||||
|
||||
if filtered_torrents:
|
||||
await search_chain.async_save_cache(filtered_torrents, SEARCH_RESULT_CACHE_FILE)
|
||||
result_json = json.dumps({
|
||||
"total_count": len(filtered_torrents),
|
||||
"message": "搜索完成。请使用 get_search_results 工具获取搜索结果。",
|
||||
"all_sites": all_sites,
|
||||
"search_site_ids": search_site_ids,
|
||||
"filter_options": build_filter_options(filtered_torrents),
|
||||
}, ensure_ascii=False, indent=2)
|
||||
return result_json
|
||||
else:
|
||||
result_json = json.dumps({
|
||||
"message": f"未找到相关种子资源: {media_source}:{media_id}",
|
||||
"all_sites": all_sites,
|
||||
"search_site_ids": search_site_ids,
|
||||
}, ensure_ascii=False, indent=2)
|
||||
return result_json
|
||||
except Exception as e:
|
||||
error_message = f"搜索种子时发生错误: {str(e)}"
|
||||
logger.error(f"搜索种子失败: {e}", exc_info=True)
|
||||
return error_message
|
||||
@@ -1,63 +0,0 @@
|
||||
"""切换当前激活人格工具。"""
|
||||
|
||||
import json
|
||||
from typing import Type
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from app.agent.runtime import agent_runtime_manager
|
||||
from app.agent.tools.base import MoviePilotTool
|
||||
from app.agent.tools.tags import ToolTag
|
||||
from app.runtime.log import logger
|
||||
|
||||
|
||||
class SwitchPersonaInput(BaseModel):
|
||||
"""切换人格工具的输入参数模型。"""
|
||||
|
||||
persona_id: str = Field(
|
||||
...,
|
||||
description=(
|
||||
"The target persona to activate. This can be the exact persona_id, label, or one of the persona aliases. "
|
||||
"If the exact persona is unclear, call query_personas first."
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
class SwitchPersonaTool(MoviePilotTool):
|
||||
name: str = "switch_persona"
|
||||
tags: list[str] = [
|
||||
ToolTag.Write,
|
||||
ToolTag.Persona,
|
||||
]
|
||||
description: str = (
|
||||
"Switch the active persona (人格) used by the agent runtime. "
|
||||
"This change is persistent for future turns. "
|
||||
"Use this when the user explicitly asks to change the speaking style, tone, or response persona. "
|
||||
"If the user asks for a vague style and you are not sure which persona matches best, call query_personas first."
|
||||
)
|
||||
args_schema: Type[BaseModel] = SwitchPersonaInput
|
||||
|
||||
def get_tool_message(self, **kwargs) -> str:
|
||||
persona_id = kwargs.get("persona_id") or "未知人格"
|
||||
return f"切换人格: {persona_id}"
|
||||
|
||||
async def run(self, persona_id: str, **kwargs) -> str:
|
||||
logger.info("执行工具: %s, 参数: persona_id=%s", self.name, persona_id)
|
||||
try:
|
||||
runtime_config = agent_runtime_manager.set_active_persona(persona_id)
|
||||
payload = {
|
||||
"success": True,
|
||||
"active_persona": runtime_config.active_persona,
|
||||
"persona": runtime_config.persona.to_dict(is_active=True),
|
||||
"message": f"已切换为人格 `{runtime_config.active_persona}`",
|
||||
}
|
||||
return json.dumps(payload, ensure_ascii=False, indent=2)
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.error("切换人格失败: %s", e, exc_info=True)
|
||||
return json.dumps(
|
||||
{
|
||||
"success": False,
|
||||
"message": f"切换人格时发生错误: {str(e)}",
|
||||
},
|
||||
ensure_ascii=False,
|
||||
)
|
||||
@@ -1,61 +0,0 @@
|
||||
"""测试站点连通性工具"""
|
||||
|
||||
from typing import Optional, Type
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from app.agent.tools.base import MoviePilotTool
|
||||
from app.agent.tools.tags import ToolTag
|
||||
from app.chain.site import SiteChain
|
||||
from app.domain import site as site_rules
|
||||
from app.runtime.log import logger
|
||||
|
||||
|
||||
class TestSiteInput(BaseModel):
|
||||
"""测试站点连通性工具的输入参数模型"""
|
||||
site_identifier: int = Field(..., description="Site ID to test (can be obtained from query_sites tool)")
|
||||
|
||||
|
||||
class TestSiteTool(MoviePilotTool):
|
||||
name: str = "test_site"
|
||||
tags: list[str] = [
|
||||
ToolTag.Read,
|
||||
ToolTag.Site,
|
||||
]
|
||||
description: str = "Test site connectivity and availability. This will check if a site is accessible and can be logged in. Accepts site ID only."
|
||||
args_schema: Type[BaseModel] = TestSiteInput
|
||||
|
||||
def get_tool_message(self, **kwargs) -> Optional[str]:
|
||||
"""根据测试参数生成友好的提示消息"""
|
||||
site_identifier = kwargs.get("site_identifier")
|
||||
return f"测试站点连通性: {site_identifier}"
|
||||
|
||||
def _test_site_sync(
|
||||
self,
|
||||
site_identifier: int,
|
||||
) -> tuple[Optional[str], Optional[str], bool, str]:
|
||||
"""在同步线程里执行站点联通测试,避免网络请求卡住事件循环。"""
|
||||
site = self.data.sites.get(site_identifier)
|
||||
if not site:
|
||||
return None, None, False, f"未找到站点:{site_identifier},请使用 query_sites 工具查询可用的站点"
|
||||
|
||||
domain = site.domain or site_rules.extract_domain(site.url)
|
||||
status, message = SiteChain().test(domain)
|
||||
return site.name, domain, status, message
|
||||
|
||||
async def run(self, site_identifier: int, **kwargs) -> str:
|
||||
logger.info(f"执行工具: {self.name}, 参数: site_identifier={site_identifier}")
|
||||
|
||||
try:
|
||||
site_name, site_domain, status, message = await self.run_blocking(
|
||||
"site", self._test_site_sync, site_identifier
|
||||
)
|
||||
if not site_name:
|
||||
return message
|
||||
if status:
|
||||
return f"站点连通性测试成功:{site_name} ({site_domain})\n{message}"
|
||||
else:
|
||||
return f"站点连通性测试失败:{site_name} ({site_domain})\n{message}"
|
||||
except Exception as e:
|
||||
logger.error(f"测试站点连通性失败: {e}", exc_info=True)
|
||||
return f"测试站点连通性时发生错误: {str(e)}"
|
||||
@@ -1,267 +0,0 @@
|
||||
"""整理文件或目录工具"""
|
||||
|
||||
from pathlib import Path
|
||||
from typing import Optional, Type
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from app.agent.tools.base import MoviePilotTool
|
||||
from app.agent.tools.tags import ToolTag
|
||||
from app.domain.media import normalize_music_type
|
||||
from app.runtime.log import logger
|
||||
from app.schemas.types import MUSIC_ENTITY_ALBUM, MUSIC_ENTITY_RECORDING, MediaSource, MediaType
|
||||
from app.schemas.workflow import FileItem
|
||||
|
||||
|
||||
class TransferFileInput(BaseModel):
|
||||
"""整理文件或目录工具的输入参数模型"""
|
||||
|
||||
file_path: str = Field(
|
||||
...,
|
||||
description="Path to the file or directory to transfer (e.g., '/path/to/file.mkv' or '/path/to/directory')",
|
||||
)
|
||||
storage: Optional[str] = Field(
|
||||
"local",
|
||||
description="Storage type of the source file (default: 'local', can be 'smb', 'alist', etc.)",
|
||||
)
|
||||
target_path: Optional[str] = Field(
|
||||
None,
|
||||
description="Target path for the transferred file/directory (optional, uses default library path if not specified)",
|
||||
)
|
||||
target_storage: Optional[str] = Field(
|
||||
None,
|
||||
description="Target storage type (optional, uses default storage if not specified)",
|
||||
)
|
||||
media_type: Optional[str] = Field(None, description="Allowed values: movie, tv, music")
|
||||
music_type: Optional[str] = Field(
|
||||
None,
|
||||
description="For music: recording for one audio file or album for one album directory. Artists cannot be transferred",
|
||||
)
|
||||
media_source: Optional[MediaSource] = Field(
|
||||
None,
|
||||
description="Media metadata source; for music use the MusicBrainz recording or album source from search_media",
|
||||
)
|
||||
media_id: Optional[str] = Field(
|
||||
None,
|
||||
description="Native ID for media_source; an album ID organizes the directory as one album",
|
||||
)
|
||||
season: Optional[int] = Field(
|
||||
None, description="Season number for TV shows (optional)"
|
||||
)
|
||||
transfer_type: Optional[str] = Field(
|
||||
None,
|
||||
description="Transfer mode: 'move' to move files, 'copy' to copy files, 'link' for hard link, 'softlink' for symbolic link (optional, uses default mode if not specified)",
|
||||
)
|
||||
background: Optional[bool] = Field(
|
||||
False,
|
||||
description="Whether to run transfer in background (default: False, runs synchronously)",
|
||||
)
|
||||
|
||||
|
||||
class TransferFileTool(MoviePilotTool):
|
||||
"""通过统一整理链将影视或音乐文件写入媒体库。"""
|
||||
|
||||
name: str = "transfer_file"
|
||||
tags: list[str] = [
|
||||
ToolTag.Write,
|
||||
ToolTag.Transfer,
|
||||
ToolTag.Library,
|
||||
ToolTag.File,
|
||||
ToolTag.Admin,
|
||||
]
|
||||
description: str = (
|
||||
"Transfer/organize movie, TV, or music files through MoviePilot's configured library pipeline. "
|
||||
"For a complete album, pass the album directory once with media_type='music', music_type='album', "
|
||||
"and its source-native ID; for one recording, pass one audio file with music_type='recording'."
|
||||
)
|
||||
args_schema: Type[BaseModel] = TransferFileInput
|
||||
require_admin: bool = True
|
||||
|
||||
@staticmethod
|
||||
def _get_fileitem_type(
|
||||
file_path: str,
|
||||
storage: Optional[str] = "local",
|
||||
music_type: Optional[str] = None,
|
||||
) -> str:
|
||||
"""
|
||||
判断待整理路径的文件类型。
|
||||
|
||||
:param file_path: 已规范化的源文件或目录路径
|
||||
:param storage: 源存储类型
|
||||
:return: ``dir`` 或 ``file``
|
||||
"""
|
||||
if (storage or "local") == "local" and Path(file_path).is_dir():
|
||||
return "dir"
|
||||
if (storage or "local") != "local" and music_type == MUSIC_ENTITY_ALBUM:
|
||||
# 远程存储无法 stat,显式专辑语义比路径尾斜杠更可靠。
|
||||
return "dir"
|
||||
return "dir" if file_path.endswith("/") else "file"
|
||||
|
||||
def get_tool_message(self, **kwargs) -> Optional[str]:
|
||||
"""根据整理参数生成友好的提示消息"""
|
||||
file_path = kwargs.get("file_path", "")
|
||||
media_type = kwargs.get("media_type")
|
||||
transfer_type = kwargs.get("transfer_type")
|
||||
background = kwargs.get("background", False)
|
||||
|
||||
message = f"整理文件: {file_path}"
|
||||
if media_type:
|
||||
message += f" [{media_type}]"
|
||||
if transfer_type:
|
||||
transfer_map = {
|
||||
"move": "移动",
|
||||
"copy": "复制",
|
||||
"link": "硬链接",
|
||||
"softlink": "软链接",
|
||||
}
|
||||
message += f" 模式: {transfer_map.get(transfer_type, transfer_type)}"
|
||||
if background:
|
||||
message += " [后台运行]"
|
||||
|
||||
return message
|
||||
|
||||
@staticmethod
|
||||
def _transfer_file_sync(
|
||||
file_path: str,
|
||||
storage: Optional[str] = "local",
|
||||
target_path: Optional[str] = None,
|
||||
target_storage: Optional[str] = None,
|
||||
media_type: Optional[str] = None,
|
||||
music_type: Optional[str] = None,
|
||||
media_source: Optional[MediaSource] = None,
|
||||
media_id: Optional[str] = None,
|
||||
season: Optional[int] = None,
|
||||
transfer_type: Optional[str] = None,
|
||||
background: Optional[bool] = False,
|
||||
) -> str:
|
||||
"""
|
||||
文件整理链路包含大量同步磁盘与外部服务调用,需要在线程池中运行。
|
||||
"""
|
||||
if not file_path:
|
||||
return "错误:必须提供文件或目录路径"
|
||||
|
||||
if storage == "local":
|
||||
if not file_path.startswith("/") and not (
|
||||
len(file_path) > 1 and file_path[1] == ":"
|
||||
):
|
||||
file_path = str(Path(file_path).resolve())
|
||||
elif not file_path.startswith("/"):
|
||||
file_path = "/" + file_path
|
||||
|
||||
media_type_enum = None
|
||||
if media_type:
|
||||
media_type_enum = MediaType.from_agent(media_type)
|
||||
if not media_type_enum:
|
||||
return f"错误:无效的媒体类型 '{media_type}',支持的类型:'movie', 'tv', 'music'"
|
||||
normalized_music_type = None
|
||||
if music_type:
|
||||
normalized_music_type = normalize_music_type(
|
||||
music_type,
|
||||
allow_artist=False,
|
||||
)
|
||||
if not normalized_music_type:
|
||||
return (
|
||||
f"错误:无效的音乐实体类型 '{music_type}',"
|
||||
"支持的类型:'recording', 'album'"
|
||||
)
|
||||
if media_type_enum != MediaType.MUSIC:
|
||||
return "错误:music_type 仅能与 media_type='music' 一起使用"
|
||||
if bool(media_source) != bool(media_id):
|
||||
return "错误:media_source 和 media_id 必须同时提供"
|
||||
if media_type_enum == MediaType.MUSIC and season is not None:
|
||||
return "错误:音乐没有季号,整理音乐时不能传入 season"
|
||||
|
||||
fileitem = FileItem(
|
||||
storage=storage or "local",
|
||||
path=file_path,
|
||||
type=TransferFileTool._get_fileitem_type(
|
||||
file_path,
|
||||
storage,
|
||||
normalized_music_type,
|
||||
),
|
||||
)
|
||||
if (
|
||||
media_type_enum == MediaType.MUSIC
|
||||
and normalized_music_type == MUSIC_ENTITY_ALBUM
|
||||
and fileitem.type != "dir"
|
||||
):
|
||||
return "错误:专辑必须按一个目录整理,不能把单个音频文件作为整张专辑"
|
||||
if (
|
||||
media_type_enum == MediaType.MUSIC
|
||||
and normalized_music_type == MUSIC_ENTITY_RECORDING
|
||||
and fileitem.type != "file"
|
||||
):
|
||||
return "错误:单曲必须按一个音频文件整理,不能把目录作为一首单曲"
|
||||
target_path_obj = Path(target_path) if target_path else None
|
||||
|
||||
from app.chain.transfer.facade import TransferChain
|
||||
|
||||
state, errormsg = TransferChain().manual_transfer(
|
||||
fileitem=fileitem,
|
||||
target_storage=target_storage,
|
||||
target_path=target_path_obj,
|
||||
media_source=media_source,
|
||||
media_id=media_id,
|
||||
mtype=media_type_enum,
|
||||
season=season,
|
||||
transfer_type=transfer_type,
|
||||
background=background,
|
||||
)
|
||||
|
||||
if state:
|
||||
if background:
|
||||
return f"整理任务已提交到后台运行:{file_path}"
|
||||
return f"整理成功:{file_path}"
|
||||
|
||||
if isinstance(errormsg, list):
|
||||
error_text = f"整理完成,{len(errormsg)} 个文件转移失败"
|
||||
if errormsg:
|
||||
error_text += ":\n" + "\n".join(str(e) for e in errormsg[:5])
|
||||
if len(errormsg) > 5:
|
||||
error_text += f"\n... 还有 {len(errormsg) - 5} 个错误"
|
||||
else:
|
||||
error_text = str(errormsg)
|
||||
return f"整理失败:{error_text}"
|
||||
|
||||
async def run(
|
||||
self,
|
||||
file_path: str,
|
||||
storage: Optional[str] = "local",
|
||||
target_path: Optional[str] = None,
|
||||
target_storage: Optional[str] = None,
|
||||
media_type: Optional[str] = None,
|
||||
music_type: Optional[str] = None,
|
||||
media_source: Optional[MediaSource] = None,
|
||||
media_id: Optional[str] = None,
|
||||
season: Optional[int] = None,
|
||||
transfer_type: Optional[str] = None,
|
||||
background: Optional[bool] = False,
|
||||
**kwargs,
|
||||
) -> str:
|
||||
"""在线程池中执行文件整理并返回最终状态。"""
|
||||
logger.info(
|
||||
f"执行工具: {self.name}, 参数: file_path={file_path}, storage={storage}, target_path={target_path}, "
|
||||
f"target_storage={target_storage}, media_type={media_type}, music_type={music_type}, "
|
||||
f"media_source={media_source}, media_id={media_id}, "
|
||||
f"season={season}, transfer_type={transfer_type}, background={background}"
|
||||
)
|
||||
|
||||
try:
|
||||
return await self.run_blocking(
|
||||
"storage",
|
||||
self._transfer_file_sync,
|
||||
file_path,
|
||||
storage,
|
||||
target_path,
|
||||
target_storage,
|
||||
media_type,
|
||||
music_type,
|
||||
media_source,
|
||||
media_id,
|
||||
season,
|
||||
transfer_type,
|
||||
background,
|
||||
)
|
||||
except Exception as e:
|
||||
logger.error(f"整理文件失败: {e}", exc_info=True)
|
||||
return f"整理文件时发生错误: {str(e)}"
|
||||
@@ -1,86 +0,0 @@
|
||||
"""卸载插件工具"""
|
||||
|
||||
import json
|
||||
from typing import Optional, Type
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from app.agent.tools.base import MoviePilotTool
|
||||
from app.agent.tools.tags import ToolTag
|
||||
from app.agent.tools.impl._plugin_tool_utils import (
|
||||
list_installed_plugins,
|
||||
summarize_plugin,
|
||||
uninstall_plugin_runtime,
|
||||
)
|
||||
from app.runtime.log import logger
|
||||
|
||||
|
||||
class UninstallPluginInput(BaseModel):
|
||||
"""卸载插件工具的输入参数模型"""
|
||||
|
||||
plugin_id: str = Field(
|
||||
...,
|
||||
description="Exact plugin ID to uninstall. Use query_installed_plugins first to find the correct plugin_id.",
|
||||
)
|
||||
|
||||
|
||||
class UninstallPluginTool(MoviePilotTool):
|
||||
name: str = "uninstall_plugin"
|
||||
tags: list[str] = [
|
||||
ToolTag.Write,
|
||||
ToolTag.Plugin,
|
||||
ToolTag.Admin,
|
||||
]
|
||||
description: str = (
|
||||
"Uninstall an installed plugin by exact plugin_id. "
|
||||
"Use query_installed_plugins first when you need filtering or discovery."
|
||||
)
|
||||
require_admin: bool = True
|
||||
args_schema: Type[BaseModel] = UninstallPluginInput
|
||||
|
||||
def get_tool_message(self, **kwargs) -> Optional[str]:
|
||||
plugin_id = kwargs.get("plugin_id")
|
||||
return f"卸载插件: {plugin_id or '未知插件'}"
|
||||
|
||||
async def run(
|
||||
self,
|
||||
plugin_id: str,
|
||||
**kwargs,
|
||||
) -> str:
|
||||
logger.info(f"执行工具: {self.name}, 参数: plugin_id={plugin_id}")
|
||||
|
||||
try:
|
||||
plugins = list_installed_plugins()
|
||||
if not plugins:
|
||||
return json.dumps(
|
||||
{"success": False, "message": "当前没有已安装的插件"},
|
||||
ensure_ascii=False,
|
||||
)
|
||||
|
||||
candidate = next((plugin for plugin in plugins if plugin.id == plugin_id), None)
|
||||
if not candidate:
|
||||
return json.dumps(
|
||||
{
|
||||
"success": False,
|
||||
"message": f"未找到已安装插件: {plugin_id}。请先调用 query_installed_plugins 确认 plugin_id。",
|
||||
},
|
||||
ensure_ascii=False,
|
||||
)
|
||||
|
||||
cleanup_result = await uninstall_plugin_runtime(candidate.id)
|
||||
return json.dumps(
|
||||
{
|
||||
"success": True,
|
||||
"message": f"插件 {candidate.id} 已卸载",
|
||||
"plugin": summarize_plugin(candidate),
|
||||
**cleanup_result,
|
||||
},
|
||||
ensure_ascii=False,
|
||||
indent=2,
|
||||
)
|
||||
except Exception as e:
|
||||
logger.error(f"卸载插件失败: {e}", exc_info=True)
|
||||
return json.dumps(
|
||||
{"success": False, "message": f"卸载插件时发生错误: {str(e)}"},
|
||||
ensure_ascii=False,
|
||||
)
|
||||
@@ -1,219 +0,0 @@
|
||||
import json
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Literal, Optional, Type
|
||||
|
||||
import pytz
|
||||
from pydantic import BaseModel, Field, model_validator
|
||||
|
||||
from app.agent.tools.base import MoviePilotTool
|
||||
from app.agent.tools.tags import ToolTag
|
||||
from app.application.agenttask import agent_task_to_dict
|
||||
from app.runtime.scheduling import TimerUtils
|
||||
from app.runtime.settings import get_runtime_setting
|
||||
|
||||
|
||||
class UpdateAgentTaskInput(BaseModel):
|
||||
"""更新 Agent 自主定时任务的输入参数。"""
|
||||
|
||||
task_id: int = Field(..., ge=1, description="ID of the task to update.")
|
||||
name: Optional[str] = Field(None, min_length=1, max_length=100)
|
||||
content: Optional[str] = Field(None, min_length=1, max_length=10000)
|
||||
trigger_type: Optional[Literal["date", "cron"]] = Field(
|
||||
None,
|
||||
description="New trigger type. Must be provided together with trigger.",
|
||||
)
|
||||
trigger: Optional[str] = Field(
|
||||
None,
|
||||
min_length=1,
|
||||
max_length=200,
|
||||
description="New ISO 8601 date or five-field cron expression.",
|
||||
)
|
||||
delay_minutes: Optional[int] = Field(
|
||||
None,
|
||||
ge=1,
|
||||
le=525600,
|
||||
description=(
|
||||
"For a one-time date task expressed as 'in N minutes', provide this instead "
|
||||
"of trigger together with trigger_type='date'."
|
||||
),
|
||||
)
|
||||
enabled: Optional[bool] = Field(
|
||||
None,
|
||||
description="Set false to pause the task or true to resume it.",
|
||||
)
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_update(self) -> "UpdateAgentTaskInput":
|
||||
"""校验更新内容和触发参数组合。"""
|
||||
if self.name is not None:
|
||||
self.name = self.name.strip()
|
||||
if not self.name:
|
||||
raise ValueError("name 不能只包含空白字符")
|
||||
if self.content is not None:
|
||||
self.content = self.content.strip()
|
||||
if not self.content:
|
||||
raise ValueError("content 不能只包含空白字符")
|
||||
has_schedule_update = any(
|
||||
value is not None
|
||||
for value in (self.trigger_type, self.trigger, self.delay_minutes)
|
||||
)
|
||||
if has_schedule_update:
|
||||
if self.trigger_type is None:
|
||||
raise ValueError("修改触发配置时必须提供 trigger_type")
|
||||
if self.trigger_type == "date":
|
||||
if self.delay_minutes is not None:
|
||||
# 保持校验幂等,具体绝对时间在更新调度前只计算一次。
|
||||
self.trigger = None
|
||||
elif self.trigger is None:
|
||||
raise ValueError("date 任务必须提供 trigger 或 delay_minutes")
|
||||
elif self.trigger is None or self.delay_minutes is not None:
|
||||
raise ValueError("cron 任务必须提供 trigger,且不能提供 delay_minutes")
|
||||
if all(
|
||||
value is None
|
||||
for value in (
|
||||
self.name,
|
||||
self.content,
|
||||
self.trigger_type,
|
||||
self.enabled,
|
||||
)
|
||||
):
|
||||
raise ValueError("至少需要提供一个要更新的字段")
|
||||
return self
|
||||
|
||||
|
||||
class UpdateAgentTaskTool(MoviePilotTool):
|
||||
"""修改、暂停或恢复 Agent 自主定时任务。"""
|
||||
|
||||
name: str = "update_agent_task"
|
||||
tags: list[str] = [ToolTag.Write, ToolTag.AgentTask, ToolTag.Admin]
|
||||
description: str = (
|
||||
"Update an autonomous agent task's name, instructions, exact date or cron "
|
||||
"trigger, relative delay_minutes, or enabled state. Use enabled=false to pause "
|
||||
"and enabled=true to resume."
|
||||
)
|
||||
args_schema: Type[BaseModel] = UpdateAgentTaskInput
|
||||
require_admin: bool = True
|
||||
|
||||
def get_tool_message(self, **kwargs: object) -> Optional[str]:
|
||||
"""生成更新定时任务的提示消息。"""
|
||||
return f"更新自主定时任务:{kwargs.get('task_id', '')}"
|
||||
|
||||
def _update_task(
|
||||
self,
|
||||
payload: UpdateAgentTaskInput,
|
||||
) -> Optional[dict[str, object]]:
|
||||
"""更新当前用户的任务并刷新运行时调度。"""
|
||||
from app.application.scheduling import update_agent_task_job
|
||||
|
||||
oper = self.data.tasks
|
||||
task = oper.get(task_id=payload.task_id, user_id=str(self._user_id))
|
||||
if not task:
|
||||
return None
|
||||
if task.last_status == "running":
|
||||
return {"error": f"Agent 定时任务 {payload.task_id} 正在执行,请稍后再修改"}
|
||||
|
||||
has_schedule_update = payload.trigger_type is not None
|
||||
trigger_type = payload.trigger_type or task.trigger_type
|
||||
trigger_value = payload.trigger
|
||||
if trigger_type == "date" and payload.delay_minutes is not None:
|
||||
timezone = pytz.timezone(get_runtime_setting('TZ'))
|
||||
trigger_value = (
|
||||
datetime.now(timezone) + timedelta(minutes=payload.delay_minutes)
|
||||
).isoformat(timespec="seconds")
|
||||
if trigger_value is None:
|
||||
trigger_value = (
|
||||
task.cron_expression if trigger_type == "cron" else task.run_at
|
||||
)
|
||||
normalized_type = trigger_type
|
||||
normalized_trigger = trigger_value
|
||||
validates_existing_date_schedule = bool(
|
||||
payload.enabled
|
||||
and task.last_status != "interrupted"
|
||||
and trigger_type == "date"
|
||||
)
|
||||
if has_schedule_update or validates_existing_date_schedule:
|
||||
if trigger_value is None:
|
||||
raise ValueError("Agent 定时任务缺少触发配置")
|
||||
normalized_type, normalized_trigger = TimerUtils.normalize_schedule_trigger(
|
||||
trigger_type=trigger_type,
|
||||
trigger_value=trigger_value,
|
||||
timezone_name=get_runtime_setting('TZ'),
|
||||
require_future=bool(
|
||||
trigger_type == "date"
|
||||
and (
|
||||
task.last_status == "interrupted"
|
||||
or (task.enabled if payload.enabled is None else payload.enabled)
|
||||
)
|
||||
),
|
||||
)
|
||||
|
||||
update_payload: dict[str, object] = {}
|
||||
if payload.name is not None:
|
||||
update_payload["name"] = payload.name.strip()
|
||||
if payload.content is not None:
|
||||
update_payload["content"] = payload.content.strip()
|
||||
if has_schedule_update:
|
||||
update_payload.update(
|
||||
{
|
||||
"trigger_type": normalized_type,
|
||||
"cron_expression": (
|
||||
normalized_trigger if normalized_type == "cron" else None
|
||||
),
|
||||
"run_at": normalized_trigger if normalized_type == "date" else None,
|
||||
"last_status": "waiting",
|
||||
"last_result": None,
|
||||
}
|
||||
)
|
||||
if payload.enabled is not None:
|
||||
update_payload["enabled"] = payload.enabled
|
||||
if payload.enabled and task.last_status != "interrupted":
|
||||
update_payload["last_status"] = "waiting"
|
||||
|
||||
updated = oper.update(
|
||||
task_id=payload.task_id,
|
||||
payload=update_payload,
|
||||
user_id=str(self._user_id),
|
||||
)
|
||||
if not updated:
|
||||
current = oper.get(task_id=payload.task_id, user_id=str(self._user_id))
|
||||
if current and current.last_status == "running":
|
||||
return {"error": f"Agent 定时任务 {payload.task_id} 正在执行,请稍后再修改"}
|
||||
return None
|
||||
next_run_at = update_agent_task_job(payload.task_id)
|
||||
updated_task = oper.get(task_id=payload.task_id, user_id=str(self._user_id))
|
||||
if updated_task is None:
|
||||
return None
|
||||
return agent_task_to_dict(
|
||||
updated_task,
|
||||
next_run_at=next_run_at,
|
||||
timezone=get_runtime_setting('TZ'),
|
||||
)
|
||||
|
||||
async def run(
|
||||
self,
|
||||
task_id: int,
|
||||
name: Optional[str] = None,
|
||||
content: Optional[str] = None,
|
||||
trigger_type: Optional[str] = None,
|
||||
trigger: Optional[str] = None,
|
||||
delay_minutes: Optional[int] = None,
|
||||
enabled: Optional[bool] = None,
|
||||
**kwargs: object,
|
||||
) -> str:
|
||||
"""更新 Agent 自主定时任务。"""
|
||||
payload = UpdateAgentTaskInput(
|
||||
task_id=task_id,
|
||||
name=name,
|
||||
content=content,
|
||||
trigger_type=trigger_type,
|
||||
trigger=trigger,
|
||||
delay_minutes=delay_minutes,
|
||||
enabled=enabled,
|
||||
)
|
||||
task = await self.run_blocking("db", self._update_task, payload)
|
||||
if not task:
|
||||
return f"Agent 定时任务 {task_id} 不存在或不属于当前用户"
|
||||
error = task.get("error")
|
||||
if error:
|
||||
return str(error)
|
||||
return json.dumps(task, ensure_ascii=False, indent=2)
|
||||
@@ -1,211 +0,0 @@
|
||||
"""更新自定义过滤规则工具。"""
|
||||
|
||||
import json
|
||||
from typing import Optional, Type
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from app.agent.tools.base import MoviePilotTool
|
||||
from app.agent.tools.impl._filter_rule_utils import (
|
||||
collect_custom_rule_group_refs,
|
||||
get_custom_rules,
|
||||
get_rule_groups,
|
||||
normalize_custom_rule,
|
||||
publish_rule_config_changed,
|
||||
replace_rule_id_in_rule_string,
|
||||
save_system_config,
|
||||
serialize_custom_rule,
|
||||
)
|
||||
from app.agent.tools.tags import ToolTag
|
||||
from app.runtime.log import logger
|
||||
from app.schemas.types import SystemConfigKey
|
||||
|
||||
|
||||
class UpdateCustomFilterRuleInput(BaseModel):
|
||||
"""更新自定义过滤规则工具的输入参数模型"""
|
||||
|
||||
current_rule_id: str = Field(
|
||||
..., description="Existing custom rule ID to update."
|
||||
)
|
||||
new_rule_id: Optional[str] = Field(
|
||||
None,
|
||||
description="New rule ID. If omitted, keep the original rule ID.",
|
||||
)
|
||||
name: Optional[str] = Field(
|
||||
None, description="New display name. If omitted, keep the original name."
|
||||
)
|
||||
include: Optional[str] = Field(
|
||||
None,
|
||||
description="New include regex. Pass an empty string to clear it.",
|
||||
)
|
||||
exclude: Optional[str] = Field(
|
||||
None,
|
||||
description="New exclude regex. Pass an empty string to clear it.",
|
||||
)
|
||||
size_range: Optional[str] = Field(
|
||||
None,
|
||||
description="New size range in MB. Pass an empty string to clear it.",
|
||||
)
|
||||
seeders: Optional[str] = Field(
|
||||
None,
|
||||
description="New minimum seeder count. Pass an empty string to clear it.",
|
||||
)
|
||||
publish_time: Optional[str] = Field(
|
||||
None,
|
||||
description="New publish-time filter in minutes. Pass an empty string to clear it.",
|
||||
)
|
||||
|
||||
|
||||
class UpdateCustomFilterRuleTool(MoviePilotTool):
|
||||
name: str = "update_custom_filter_rule"
|
||||
tags: list[str] = [
|
||||
ToolTag.Write,
|
||||
ToolTag.FilterRule,
|
||||
ToolTag.Admin,
|
||||
]
|
||||
description: str = (
|
||||
"Update an existing custom filter rule. "
|
||||
"If the rule ID is renamed, all rule groups that reference the old ID are updated automatically."
|
||||
)
|
||||
args_schema: Type[BaseModel] = UpdateCustomFilterRuleInput
|
||||
require_admin: bool = True
|
||||
|
||||
def get_tool_message(self, **kwargs) -> Optional[str]:
|
||||
current_rule_id = kwargs.get("current_rule_id", "")
|
||||
new_rule_id = kwargs.get("new_rule_id")
|
||||
if new_rule_id and new_rule_id != current_rule_id:
|
||||
return f"更新自定义过滤规则 {current_rule_id} -> {new_rule_id}"
|
||||
return f"更新自定义过滤规则 {current_rule_id}"
|
||||
|
||||
async def run(
|
||||
self,
|
||||
current_rule_id: str,
|
||||
new_rule_id: Optional[str] = None,
|
||||
name: Optional[str] = None,
|
||||
include: Optional[str] = None,
|
||||
exclude: Optional[str] = None,
|
||||
size_range: Optional[str] = None,
|
||||
seeders: Optional[str] = None,
|
||||
publish_time: Optional[str] = None,
|
||||
**kwargs,
|
||||
) -> str:
|
||||
logger.info(f"执行工具: {self.name}, current_rule_id={current_rule_id}")
|
||||
|
||||
try:
|
||||
custom_rules = get_custom_rules()
|
||||
rule_map = {rule.id: rule for rule in custom_rules if rule.id}
|
||||
current_rule = rule_map.get(current_rule_id)
|
||||
if not current_rule:
|
||||
return json.dumps(
|
||||
{
|
||||
"success": False,
|
||||
"message": f"自定义过滤规则 '{current_rule_id}' 不存在",
|
||||
},
|
||||
ensure_ascii=False,
|
||||
)
|
||||
|
||||
updated_rule = normalize_custom_rule(
|
||||
rule_id=new_rule_id or current_rule.id,
|
||||
name=name if name is not None else current_rule.name,
|
||||
include=include if include is not None else current_rule.include,
|
||||
exclude=exclude if exclude is not None else current_rule.exclude,
|
||||
size_range=(
|
||||
size_range if size_range is not None else current_rule.size_range
|
||||
),
|
||||
seeders=seeders if seeders is not None else current_rule.seeders,
|
||||
publish_time=(
|
||||
publish_time
|
||||
if publish_time is not None
|
||||
else current_rule.publish_time
|
||||
),
|
||||
existing_rules=custom_rules,
|
||||
original_rule_id=current_rule.id,
|
||||
)
|
||||
|
||||
expected_custom_rules = [
|
||||
rule.model_dump(exclude_none=True) for rule in custom_rules
|
||||
]
|
||||
final_rules = [
|
||||
updated_rule if rule.id == current_rule.id else rule
|
||||
for rule in custom_rules
|
||||
]
|
||||
custom_rule_definitions = [
|
||||
rule.model_dump(exclude_none=True) for rule in final_rules
|
||||
]
|
||||
|
||||
rule_groups = get_rule_groups()
|
||||
expected_rule_groups = [
|
||||
group.model_dump(exclude_none=True) for group in rule_groups
|
||||
]
|
||||
updated_rule_groups = rule_groups
|
||||
renamed_group_refs = []
|
||||
if updated_rule.id != current_rule.id:
|
||||
updated_rule_groups = []
|
||||
for group in rule_groups:
|
||||
if not group.rule_string:
|
||||
updated_rule_groups.append(group)
|
||||
continue
|
||||
new_rule_string = replace_rule_id_in_rule_string(
|
||||
group.rule_string,
|
||||
current_rule.id,
|
||||
updated_rule.id,
|
||||
)
|
||||
if new_rule_string == group.rule_string:
|
||||
updated_rule_groups.append(group)
|
||||
continue
|
||||
renamed_group_refs.append(group.name)
|
||||
updated_rule_groups.append(
|
||||
group.model_copy(update={"rule_string": new_rule_string})
|
||||
)
|
||||
|
||||
rule_group_definitions = [
|
||||
group.model_dump(exclude_none=True)
|
||||
for group in updated_rule_groups
|
||||
]
|
||||
async with self.data.async_rule_group_mutation_scope() as mutation:
|
||||
await mutation.apply(
|
||||
rule_group_definitions,
|
||||
expected_rule_groups=expected_rule_groups,
|
||||
custom_rules=custom_rule_definitions,
|
||||
expected_custom_rules=expected_custom_rules,
|
||||
)
|
||||
await publish_rule_config_changed(
|
||||
SystemConfigKey.CustomFilterRules,
|
||||
custom_rule_definitions,
|
||||
)
|
||||
await publish_rule_config_changed(
|
||||
SystemConfigKey.UserFilterRuleGroups,
|
||||
rule_group_definitions,
|
||||
)
|
||||
else:
|
||||
await save_system_config(
|
||||
SystemConfigKey.CustomFilterRules,
|
||||
custom_rule_definitions,
|
||||
)
|
||||
|
||||
updated_refs = collect_custom_rule_group_refs(
|
||||
updated_rule_groups,
|
||||
[updated_rule.id],
|
||||
)
|
||||
return json.dumps(
|
||||
{
|
||||
"success": True,
|
||||
"message": f"已更新自定义过滤规则 {updated_rule.id}",
|
||||
"custom_rule": serialize_custom_rule(
|
||||
updated_rule,
|
||||
updated_refs.get(updated_rule.id),
|
||||
),
|
||||
"rule_groups_updated_for_rule_id_rename": renamed_group_refs,
|
||||
},
|
||||
ensure_ascii=False,
|
||||
indent=2,
|
||||
)
|
||||
except Exception as exc:
|
||||
logger.error(f"更新自定义过滤规则失败: {exc}", exc_info=True)
|
||||
return json.dumps(
|
||||
{
|
||||
"success": False,
|
||||
"message": f"更新自定义过滤规则失败: {exc}",
|
||||
},
|
||||
ensure_ascii=False,
|
||||
)
|
||||
@@ -1,112 +0,0 @@
|
||||
"""更新自定义识别词工具"""
|
||||
|
||||
import json
|
||||
from typing import List, Optional, Type
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from app.agent.tools.base import MoviePilotTool
|
||||
from app.agent.tools.tags import ToolTag
|
||||
from app.domain.metainfo import clear_rust_parse_options_cache
|
||||
from app.application.configuration import get_configured_system_config
|
||||
from app.runtime.log import logger
|
||||
from app.schemas.types import SystemConfigKey
|
||||
|
||||
|
||||
class UpdateCustomIdentifiersInput(BaseModel):
|
||||
"""更新自定义识别词工具的输入参数模型"""
|
||||
|
||||
identifiers: List[str] = Field(
|
||||
...,
|
||||
description=(
|
||||
"The complete list of custom identifier rules to save. "
|
||||
"This REPLACES the entire existing list. "
|
||||
"Always query existing identifiers first, merge new rules, then pass the full list. "
|
||||
"These rules are global and affect future recognition for all torrents/files. "
|
||||
"When adding a rule for a user-provided sample, prefer narrow regex patterns that include "
|
||||
"sample-specific anchors such as the title alias, year, season/episode marker, group tag, "
|
||||
"resolution, or other distinctive fragments. Avoid overly broad patterns like bare generic "
|
||||
"tags, pure episode numbers, or common release words unless the user explicitly wants a global rule."
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
class UpdateCustomIdentifiersTool(MoviePilotTool):
|
||||
name: str = "update_custom_identifiers"
|
||||
tags: list[str] = [
|
||||
ToolTag.Write,
|
||||
ToolTag.FilterRule,
|
||||
ToolTag.Admin,
|
||||
]
|
||||
description: str = (
|
||||
"Update the full list of custom identifiers (自定义识别词) used for preprocessing torrent/file names. "
|
||||
"This tool REPLACES all existing identifier rules with the provided list. "
|
||||
"IMPORTANT: Always use 'query_custom_identifiers' first to get existing rules, "
|
||||
"then merge new rules into the list before calling this tool to avoid accidentally deleting existing rules. "
|
||||
"IMPORTANT: New identifier rules are global. When the rule is created from a specific torrent/file name, "
|
||||
"make the regex as narrow as possible and include distinctive elements from that sample so unrelated titles "
|
||||
"are not affected. Prefer contextual replacements with capture groups/backreferences over bare block words "
|
||||
"when a generic word like REPACK, WEB-DL, 1080p, 字幕, or a simple episode marker would otherwise match too broadly. "
|
||||
"Supported rule formats (spaces around operators are required): "
|
||||
"1) Block word: just the word/regex to remove; "
|
||||
"2) Replacement: '被替换词 => 替换词'; "
|
||||
"3) Episode offset: '前定位词 <> 后定位词 >> EP±N'; "
|
||||
"4) Combined: '被替换词 => 替换词 && 前定位词 <> 后定位词 >> EP±N'; "
|
||||
"Lines starting with '#' are comments. "
|
||||
"The replacement target supports: "
|
||||
"{[tmdbid=xxx;type=movie/tv;g=xxx;s=xxx;e=xxx]}; "
|
||||
"tmdbid may be replaced with doubanid, bangumiid, or anilistid; "
|
||||
"g is an optional episode group ID for TV recognition."
|
||||
)
|
||||
require_admin: bool = True
|
||||
args_schema: Type[BaseModel] = UpdateCustomIdentifiersInput
|
||||
|
||||
def get_tool_message(self, **kwargs) -> Optional[str]:
|
||||
"""生成友好的提示消息"""
|
||||
identifiers = kwargs.get("identifiers", [])
|
||||
return f"更新自定义识别词(共 {len(identifiers)} 条规则)"
|
||||
|
||||
async def run(self, identifiers: List[str] = None, **kwargs) -> str:
|
||||
logger.info(
|
||||
f"执行工具: {self.name}, 规则数量: {len(identifiers) if identifiers else 0}"
|
||||
)
|
||||
try:
|
||||
if identifiers is None:
|
||||
return json.dumps(
|
||||
{"success": False, "message": "必须提供 identifiers 参数"},
|
||||
ensure_ascii=False,
|
||||
)
|
||||
|
||||
# 过滤空字符串
|
||||
identifiers = [i for i in identifiers if i is not None]
|
||||
|
||||
system_config_oper = get_configured_system_config()
|
||||
|
||||
# 保存
|
||||
value = identifiers if identifiers else None
|
||||
success = await system_config_oper.async_set(
|
||||
SystemConfigKey.CustomIdentifiers, value
|
||||
)
|
||||
if success:
|
||||
clear_rust_parse_options_cache()
|
||||
return json.dumps(
|
||||
{
|
||||
"success": True,
|
||||
"message": f"自定义识别词已更新,共 {len(identifiers)} 条规则",
|
||||
"count": len(identifiers),
|
||||
"identifiers": identifiers,
|
||||
},
|
||||
ensure_ascii=False,
|
||||
indent=2,
|
||||
)
|
||||
else:
|
||||
return json.dumps(
|
||||
{"success": False, "message": "保存自定义识别词失败"},
|
||||
ensure_ascii=False,
|
||||
)
|
||||
except Exception as e:
|
||||
logger.error(f"更新自定义识别词失败: {e}")
|
||||
return json.dumps(
|
||||
{"success": False, "message": f"更新自定义识别词时发生错误: {str(e)}"},
|
||||
ensure_ascii=False,
|
||||
)
|
||||
@@ -1,319 +0,0 @@
|
||||
"""更新下载任务工具"""
|
||||
|
||||
import json
|
||||
from typing import Any, Dict, List, Optional, Type
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from app.agent.tools.base import MoviePilotTool
|
||||
from app.agent.tools.tags import ToolTag
|
||||
from app.chain.download import DownloadChain
|
||||
from app.application.directory import validate_download_save_path
|
||||
from app.runtime.log import logger
|
||||
|
||||
|
||||
class UpdateDownloadTasksInput(BaseModel):
|
||||
"""更新下载任务工具的输入参数模型"""
|
||||
|
||||
hash: str = Field(
|
||||
..., description="Task hash (can be obtained from query_download_tasks tool)"
|
||||
)
|
||||
action: Optional[str] = Field(
|
||||
None,
|
||||
description="Action to perform on the task: 'start' to resume downloading, 'stop' to pause downloading.",
|
||||
)
|
||||
tags: Optional[List[str]] = Field(
|
||||
None,
|
||||
description="List of tags to add to the download task. Example: ['movie', 'hd']",
|
||||
)
|
||||
downloader: Optional[str] = Field(
|
||||
None,
|
||||
description="Name of specific downloader. If omitted, the tool resolves it from the task hash.",
|
||||
)
|
||||
download_limit: Optional[float] = Field(
|
||||
None,
|
||||
description="Per-task download speed limit in KB/s. Use 0 to disable the limit when supported.",
|
||||
)
|
||||
upload_limit: Optional[float] = Field(
|
||||
None,
|
||||
description="Per-task upload speed limit in KB/s. Use 0 to disable the limit when supported.",
|
||||
)
|
||||
trackers: Optional[List[str]] = Field(
|
||||
None,
|
||||
description="Tracker URL list to add or set, depending on downloader support.",
|
||||
)
|
||||
save_path: Optional[str] = Field(
|
||||
None,
|
||||
description="New save/download directory for the task, when supported.",
|
||||
)
|
||||
category: Optional[str] = Field(
|
||||
None,
|
||||
description="Downloader category to set, when supported.",
|
||||
)
|
||||
ratio_limit: Optional[float] = Field(
|
||||
None,
|
||||
description="Per-task share ratio limit, when supported.",
|
||||
)
|
||||
seeding_time_limit: Optional[int] = Field(
|
||||
None,
|
||||
description="Per-task seeding time limit in minutes, when supported.",
|
||||
)
|
||||
|
||||
|
||||
class UpdateDownloadTasksTool(MoviePilotTool):
|
||||
"""更新下载任务工具"""
|
||||
|
||||
name: str = "update_download_tasks"
|
||||
tags: list[str] = [
|
||||
ToolTag.Write,
|
||||
ToolTag.Download,
|
||||
ToolTag.Admin,
|
||||
]
|
||||
description: str = (
|
||||
"Update a download task by hash. Supports start/stop, adding tags, per-task "
|
||||
"upload/download speed limits, trackers, save directory, category, share ratio, "
|
||||
"and seeding time where the configured downloader supports them. "
|
||||
"Use query_download_tasks first to get the hash and current downloader."
|
||||
)
|
||||
args_schema: Type[BaseModel] = UpdateDownloadTasksInput
|
||||
require_admin: bool = True
|
||||
|
||||
@staticmethod
|
||||
def _is_valid_hash(hash_value: str) -> bool:
|
||||
"""校验下载任务Hash格式。"""
|
||||
return len(hash_value) == 40 and all(c in "0123456789abcdefABCDEF" for c in hash_value)
|
||||
|
||||
@staticmethod
|
||||
def _normalize_non_empty_list(values: Optional[List[str]]) -> Optional[List[str]]:
|
||||
"""清理字符串列表中的空值。"""
|
||||
if values is None:
|
||||
return None
|
||||
return [str(value).strip() for value in values if str(value).strip()]
|
||||
|
||||
@staticmethod
|
||||
def _has_update_params(**kwargs) -> bool:
|
||||
"""判断是否传入至少一个修改参数。"""
|
||||
return any(value is not None and value != [] for value in kwargs.values())
|
||||
|
||||
@staticmethod
|
||||
def _build_result(operation: str, success: bool, message: str) -> Dict[str, Any]:
|
||||
"""构造单项操作结果。"""
|
||||
return {
|
||||
"operation": operation,
|
||||
"success": success,
|
||||
"message": message,
|
||||
}
|
||||
|
||||
@classmethod
|
||||
def _resolve_downloader(
|
||||
cls,
|
||||
download_chain: DownloadChain,
|
||||
hash_value: str,
|
||||
downloader: Optional[str],
|
||||
) -> Optional[str]:
|
||||
"""根据Hash解析下载任务所在下载器。"""
|
||||
if downloader:
|
||||
return downloader
|
||||
torrents = download_chain.list_torrents(
|
||||
hashs=[hash_value],
|
||||
include_all_tags=True,
|
||||
) or []
|
||||
return getattr(torrents[0], "downloader", None) if torrents else None
|
||||
|
||||
@classmethod
|
||||
def _update_download_sync(
|
||||
cls,
|
||||
hash_value: str,
|
||||
action: Optional[str] = None,
|
||||
tags: Optional[List[str]] = None,
|
||||
downloader: Optional[str] = None,
|
||||
download_limit: Optional[float] = None,
|
||||
upload_limit: Optional[float] = None,
|
||||
trackers: Optional[List[str]] = None,
|
||||
save_path: Optional[str] = None,
|
||||
category: Optional[str] = None,
|
||||
ratio_limit: Optional[float] = None,
|
||||
seeding_time_limit: Optional[int] = None,
|
||||
) -> Dict[str, Any]:
|
||||
"""同步更新下载任务,避免下载器 SDK 阻塞事件循环。"""
|
||||
download_chain = DownloadChain()
|
||||
resolved_downloader = cls._resolve_downloader(
|
||||
download_chain=download_chain,
|
||||
hash_value=hash_value,
|
||||
downloader=downloader,
|
||||
)
|
||||
if not resolved_downloader:
|
||||
return {
|
||||
"hash": hash_value,
|
||||
"downloader": downloader,
|
||||
"results": [
|
||||
cls._build_result("resolve_downloader", False, "未找到下载任务或下载器不可用")
|
||||
],
|
||||
}
|
||||
|
||||
if save_path is not None:
|
||||
try:
|
||||
save_path = validate_download_save_path(save_path)
|
||||
except ValueError:
|
||||
return {
|
||||
"hash": hash_value,
|
||||
"downloader": resolved_downloader,
|
||||
"results": [
|
||||
cls._build_result("save_path", False, "保存目录不在允许的下载目录范围内")
|
||||
],
|
||||
}
|
||||
|
||||
results = []
|
||||
if tags:
|
||||
tag_result = download_chain.set_torrents_tag(
|
||||
hashs=[hash_value], tags=tags, downloader=resolved_downloader
|
||||
)
|
||||
results.append(
|
||||
cls._build_result(
|
||||
"tags",
|
||||
bool(tag_result),
|
||||
f"成功设置标签:{', '.join(tags)}" if tag_result else "设置标签失败",
|
||||
)
|
||||
)
|
||||
|
||||
if action:
|
||||
action_result = download_chain.set_downloading(
|
||||
hash_str=hash_value, oper=action, name=resolved_downloader
|
||||
)
|
||||
action_desc = "开始" if action == "start" else "暂停"
|
||||
results.append(
|
||||
cls._build_result(
|
||||
action,
|
||||
bool(action_result),
|
||||
f"成功{action_desc}下载任务" if action_result else f"{action_desc}下载任务失败",
|
||||
)
|
||||
)
|
||||
|
||||
update_result = {}
|
||||
if cls._has_update_params(
|
||||
download_limit=download_limit,
|
||||
upload_limit=upload_limit,
|
||||
trackers=trackers,
|
||||
save_path=save_path,
|
||||
category=category,
|
||||
ratio_limit=ratio_limit,
|
||||
seeding_time_limit=seeding_time_limit,
|
||||
):
|
||||
update_result = download_chain.update_torrent(
|
||||
hash_string=hash_value,
|
||||
downloader=resolved_downloader,
|
||||
download_limit=download_limit,
|
||||
upload_limit=upload_limit,
|
||||
tracker_list=trackers,
|
||||
save_path=save_path,
|
||||
category=category,
|
||||
ratio_limit=ratio_limit,
|
||||
seeding_time_limit=seeding_time_limit,
|
||||
)
|
||||
operation_messages = {
|
||||
"limits": "限速/做种策略",
|
||||
"trackers": "Tracker",
|
||||
"save_path": "保存目录",
|
||||
"category": "分类",
|
||||
}
|
||||
for operation, success in (update_result or {}).items():
|
||||
label = operation_messages.get(operation, operation)
|
||||
results.append(
|
||||
cls._build_result(
|
||||
operation,
|
||||
bool(success),
|
||||
f"{label}修改成功" if success else f"{label}修改失败或下载器不支持",
|
||||
)
|
||||
)
|
||||
|
||||
return {
|
||||
"hash": hash_value,
|
||||
"downloader": resolved_downloader,
|
||||
"results": results,
|
||||
}
|
||||
|
||||
def get_tool_message(self, **kwargs) -> Optional[str]:
|
||||
"""根据更新参数生成友好的提示消息。"""
|
||||
hash_value = kwargs.get("hash", "")
|
||||
parts = [f"更新下载任务: {hash_value}"]
|
||||
action = kwargs.get("action")
|
||||
if action == "start":
|
||||
parts.append("操作: 开始下载")
|
||||
elif action == "stop":
|
||||
parts.append("操作: 暂停下载")
|
||||
if kwargs.get("tags"):
|
||||
parts.append(f"标签: {', '.join(kwargs.get('tags'))}")
|
||||
if kwargs.get("download_limit") is not None or kwargs.get("upload_limit") is not None:
|
||||
parts.append("限速")
|
||||
if kwargs.get("trackers") is not None:
|
||||
parts.append("Tracker")
|
||||
if kwargs.get("save_path"):
|
||||
parts.append("保存目录")
|
||||
if kwargs.get("category") is not None:
|
||||
parts.append("分类")
|
||||
if kwargs.get("downloader"):
|
||||
parts.append(f"下载器: {kwargs.get('downloader')}")
|
||||
return " | ".join(parts)
|
||||
|
||||
async def run(
|
||||
self,
|
||||
hash: str,
|
||||
action: Optional[str] = None,
|
||||
tags: Optional[List[str]] = None,
|
||||
downloader: Optional[str] = None,
|
||||
download_limit: Optional[float] = None,
|
||||
upload_limit: Optional[float] = None,
|
||||
trackers: Optional[List[str]] = None,
|
||||
save_path: Optional[str] = None,
|
||||
category: Optional[str] = None,
|
||||
ratio_limit: Optional[float] = None,
|
||||
seeding_time_limit: Optional[int] = None,
|
||||
**kwargs,
|
||||
) -> str:
|
||||
"""执行下载任务更新。"""
|
||||
logger.info(
|
||||
f"执行工具: {self.name}, 参数: hash={hash}, action={action}, tags={tags}, "
|
||||
f"downloader={downloader}, download_limit={download_limit}, upload_limit={upload_limit}, "
|
||||
f"trackers={trackers}, save_path={save_path}, category={category}, "
|
||||
f"ratio_limit={ratio_limit}, seeding_time_limit={seeding_time_limit}"
|
||||
)
|
||||
try:
|
||||
if not self._is_valid_hash(hash):
|
||||
return "参数错误:hash 格式无效,请先使用 query_download_tasks 工具获取正确的 hash。"
|
||||
|
||||
tags = self._normalize_non_empty_list(tags)
|
||||
trackers = self._normalize_non_empty_list(trackers)
|
||||
if action and action not in ("start", "stop"):
|
||||
return f"参数错误:action 只支持 'start'(开始下载)或 'stop'(暂停下载),收到: '{action}'。"
|
||||
if not self._has_update_params(
|
||||
action=action,
|
||||
tags=tags,
|
||||
download_limit=download_limit,
|
||||
upload_limit=upload_limit,
|
||||
trackers=trackers,
|
||||
save_path=save_path,
|
||||
category=category,
|
||||
ratio_limit=ratio_limit,
|
||||
seeding_time_limit=seeding_time_limit,
|
||||
):
|
||||
return "参数错误:至少需要指定一个要更新的字段。"
|
||||
|
||||
result = await self.run_blocking(
|
||||
"downloader",
|
||||
self._update_download_sync,
|
||||
hash,
|
||||
action,
|
||||
tags,
|
||||
downloader,
|
||||
download_limit,
|
||||
upload_limit,
|
||||
trackers,
|
||||
save_path,
|
||||
category,
|
||||
ratio_limit,
|
||||
seeding_time_limit,
|
||||
)
|
||||
return json.dumps(result, ensure_ascii=False, indent=2)
|
||||
except Exception as e:
|
||||
logger.error(f"更新下载任务失败: {e}", exc_info=True)
|
||||
return f"更新下载任务时发生错误: {str(e)}"
|
||||
@@ -1,133 +0,0 @@
|
||||
"""更新人格定义工具。"""
|
||||
|
||||
import json
|
||||
from typing import Optional, Type
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from app.agent.runtime import agent_runtime_manager
|
||||
from app.agent.tools.base import MoviePilotTool
|
||||
from app.agent.tools.tags import ToolTag
|
||||
from app.runtime.log import logger
|
||||
|
||||
|
||||
class UpdatePersonaDefinitionInput(BaseModel):
|
||||
"""更新人格定义工具的输入参数模型。"""
|
||||
|
||||
persona_id: str = Field(
|
||||
...,
|
||||
description=(
|
||||
"Target persona to update. For existing personas this can be persona_id, label, or alias. "
|
||||
"For new personas, provide the new lowercase persona_id."
|
||||
),
|
||||
)
|
||||
label: Optional[str] = Field(
|
||||
None,
|
||||
description="Optional new label shown to users, such as 默认 or 说明型.",
|
||||
)
|
||||
description: Optional[str] = Field(
|
||||
None,
|
||||
description="Optional short description of the persona's intended style.",
|
||||
)
|
||||
aliases: Optional[list[str]] = Field(
|
||||
None,
|
||||
description="Optional full replacement list of aliases for this persona.",
|
||||
)
|
||||
instructions: Optional[str] = Field(
|
||||
None,
|
||||
description=(
|
||||
"Optional full replacement body for PERSONA.md, excluding YAML frontmatter. "
|
||||
"Use this when the persona definition should be rewritten completely."
|
||||
),
|
||||
)
|
||||
append_instructions: Optional[list[str]] = Field(
|
||||
None,
|
||||
description=(
|
||||
"Optional extra persona rules to append to the existing PERSONA body. "
|
||||
"Use this for small adjustments such as '回答更短' or '复杂问题给两步解释'."
|
||||
),
|
||||
)
|
||||
create_if_missing: bool = Field(
|
||||
False,
|
||||
description="Whether to create a new runtime persona if the target persona does not already exist.",
|
||||
)
|
||||
|
||||
|
||||
class UpdatePersonaDefinitionTool(MoviePilotTool):
|
||||
name: str = "update_persona_definition"
|
||||
tags: list[str] = [
|
||||
ToolTag.Write,
|
||||
ToolTag.Persona,
|
||||
ToolTag.Admin,
|
||||
]
|
||||
description: str = (
|
||||
"Create or update a runtime persona definition (人格定义) without manually editing PERSONA.md files. "
|
||||
"Use this when the user explicitly asks to modify how a persona is defined, such as changing tone rules, "
|
||||
"rewriting the persona body, adjusting aliases, or creating a new persona."
|
||||
)
|
||||
args_schema: Type[BaseModel] = UpdatePersonaDefinitionInput
|
||||
require_admin: bool = True
|
||||
|
||||
def get_tool_message(self, **kwargs) -> str:
|
||||
persona_id = kwargs.get("persona_id") or "未知人格"
|
||||
action = "创建/更新人格定义"
|
||||
return f"{action}: {persona_id}"
|
||||
|
||||
async def run(
|
||||
self,
|
||||
persona_id: str,
|
||||
label: Optional[str] = None,
|
||||
description: Optional[str] = None,
|
||||
aliases: Optional[list[str]] = None,
|
||||
instructions: Optional[str] = None,
|
||||
append_instructions: Optional[list[str]] = None,
|
||||
create_if_missing: bool = False,
|
||||
**kwargs,
|
||||
) -> str:
|
||||
logger.info("执行工具: %s, 参数: persona_id=%s", self.name, persona_id)
|
||||
if not any(
|
||||
value is not None
|
||||
for value in (label, description, aliases, instructions, append_instructions)
|
||||
):
|
||||
return json.dumps(
|
||||
{
|
||||
"success": False,
|
||||
"message": "未提供任何要更新的人格定义字段。",
|
||||
},
|
||||
ensure_ascii=False,
|
||||
)
|
||||
|
||||
try:
|
||||
persona, created = agent_runtime_manager.update_persona_definition(
|
||||
persona_id,
|
||||
label=label,
|
||||
description=description,
|
||||
aliases=aliases,
|
||||
instructions=instructions,
|
||||
append_instructions=append_instructions,
|
||||
create_if_missing=create_if_missing,
|
||||
)
|
||||
runtime_config = agent_runtime_manager.load_runtime_config()
|
||||
payload = {
|
||||
"success": True,
|
||||
"created": created,
|
||||
"active_persona": runtime_config.active_persona,
|
||||
"persona": persona.to_dict(
|
||||
is_active=persona.persona_id == runtime_config.active_persona
|
||||
),
|
||||
"message": (
|
||||
f"已创建人格 `{persona.persona_id}`"
|
||||
if created
|
||||
else f"已更新人格 `{persona.persona_id}` 的定义"
|
||||
),
|
||||
}
|
||||
return json.dumps(payload, ensure_ascii=False, indent=2)
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.error("更新人格定义失败: %s", e, exc_info=True)
|
||||
return json.dumps(
|
||||
{
|
||||
"success": False,
|
||||
"message": f"更新人格定义时发生错误: {str(e)}",
|
||||
},
|
||||
ensure_ascii=False,
|
||||
)
|
||||
@@ -1,159 +0,0 @@
|
||||
"""修改插件配置工具"""
|
||||
|
||||
import json
|
||||
from typing import Any, Dict, List, Optional, Type
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from app.agent.tools.base import MoviePilotTool
|
||||
from app.agent.tools.tags import ToolTag
|
||||
from app.agent.tools.impl._plugin_tool_utils import get_plugin_snapshot
|
||||
from app.application.plugin.runtime import get_plugin_manager
|
||||
from app.runtime.log import logger
|
||||
|
||||
|
||||
class UpdatePluginConfigInput(BaseModel):
|
||||
"""修改插件配置工具的输入参数模型"""
|
||||
|
||||
plugin_id: str = Field(
|
||||
...,
|
||||
description="The plugin ID to update. Use query_plugin_config first to inspect the current config.",
|
||||
)
|
||||
updates: Optional[Dict[str, Any]] = Field(
|
||||
None,
|
||||
description=(
|
||||
"Config items to save. By default this tool merges these keys into the existing config "
|
||||
"instead of replacing the whole config."
|
||||
),
|
||||
)
|
||||
remove_keys: Optional[List[str]] = Field(
|
||||
None,
|
||||
description="Optional config keys to remove from the saved plugin config.",
|
||||
)
|
||||
replace: Optional[bool] = Field(
|
||||
False,
|
||||
description=(
|
||||
"Whether to replace the entire saved config with 'updates'. "
|
||||
"Default false, which performs a partial merge update."
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
class UpdatePluginConfigTool(MoviePilotTool):
|
||||
name: str = "update_plugin_config"
|
||||
tags: list[str] = [
|
||||
ToolTag.Write,
|
||||
ToolTag.Plugin,
|
||||
ToolTag.Admin,
|
||||
]
|
||||
description: str = (
|
||||
"Update the saved configuration of an installed plugin. "
|
||||
"By default this performs a partial merge update and does NOT reload the plugin automatically. "
|
||||
"Call reload_plugin afterwards to apply the latest saved config to the running plugin."
|
||||
)
|
||||
require_admin: bool = True
|
||||
args_schema: Type[BaseModel] = UpdatePluginConfigInput
|
||||
|
||||
def get_tool_message(self, **kwargs) -> Optional[str]:
|
||||
"""生成友好的提示消息"""
|
||||
plugin_id = kwargs.get("plugin_id", "")
|
||||
replace = kwargs.get("replace", False)
|
||||
action = "覆盖插件配置" if replace else "修改插件配置"
|
||||
return f"{action}: {plugin_id}"
|
||||
|
||||
@staticmethod
|
||||
async def _update_plugin_config(
|
||||
plugin_id: str,
|
||||
updates: Optional[Dict[str, Any]] = None,
|
||||
remove_keys: Optional[List[str]] = None,
|
||||
replace: bool = False,
|
||||
) -> str:
|
||||
"""
|
||||
仅异步保存插件配置,不主动生效,让 Agent 可以先批量改完再显式重载插件。
|
||||
"""
|
||||
plugin_info = get_plugin_snapshot(plugin_id)
|
||||
if not plugin_info:
|
||||
return json.dumps(
|
||||
{
|
||||
"success": False,
|
||||
"message": f"插件 {plugin_id} 不存在,请先使用 query_installed_plugins 查询有效插件 ID",
|
||||
},
|
||||
ensure_ascii=False,
|
||||
)
|
||||
|
||||
remove_keys = remove_keys or []
|
||||
if not replace and not updates and not remove_keys:
|
||||
return json.dumps(
|
||||
{"success": False, "message": "没有提供任何需要修改的配置项"},
|
||||
ensure_ascii=False,
|
||||
)
|
||||
|
||||
plugin_manager = get_plugin_manager()
|
||||
with plugin_manager.mutation(f"更新插件 {plugin_id} 配置"):
|
||||
current_config = dict(plugin_manager.get_plugin_config(plugin_id) or {})
|
||||
|
||||
# merge 模式以当前保存值为基准,replace 模式则从空配置开始重建。
|
||||
next_config = {} if replace else dict(current_config)
|
||||
if updates:
|
||||
next_config.update(updates)
|
||||
for key in remove_keys:
|
||||
next_config.pop(key, None)
|
||||
|
||||
changed_keys = sorted(
|
||||
key
|
||||
for key in set(current_config.keys()) | set(next_config.keys())
|
||||
if current_config.get(key) != next_config.get(key)
|
||||
or (key in current_config) != (key in next_config)
|
||||
)
|
||||
|
||||
if not await plugin_manager.async_save_plugin_config(
|
||||
plugin_id,
|
||||
next_config,
|
||||
):
|
||||
return json.dumps(
|
||||
{
|
||||
"success": False,
|
||||
"message": f"保存插件 {plugin_id} 配置失败",
|
||||
},
|
||||
ensure_ascii=False,
|
||||
)
|
||||
|
||||
return json.dumps(
|
||||
{
|
||||
"success": True,
|
||||
**plugin_info,
|
||||
"message": "插件配置已保存,请调用 reload_plugin 使最新配置生效",
|
||||
"replace": replace,
|
||||
"changed_keys": changed_keys,
|
||||
"removed_keys": remove_keys,
|
||||
"config_requires_reload": True,
|
||||
"previous_config": current_config,
|
||||
"saved_config": next_config,
|
||||
},
|
||||
ensure_ascii=False,
|
||||
indent=2,
|
||||
default=str,
|
||||
)
|
||||
|
||||
async def run(
|
||||
self,
|
||||
plugin_id: str,
|
||||
updates: Optional[Dict[str, Any]] = None,
|
||||
remove_keys: Optional[List[str]] = None,
|
||||
replace: bool = False,
|
||||
**kwargs,
|
||||
) -> str:
|
||||
logger.info(
|
||||
f"执行工具: {self.name}, 参数: plugin_id={plugin_id}, replace={replace}"
|
||||
)
|
||||
|
||||
try:
|
||||
return await self._update_plugin_config(
|
||||
plugin_id, updates, remove_keys, replace
|
||||
)
|
||||
except Exception as e:
|
||||
logger.error(f"修改插件配置失败: {e}", exc_info=True)
|
||||
return json.dumps(
|
||||
{"success": False, "message": f"修改插件配置时发生错误: {str(e)}"},
|
||||
ensure_ascii=False,
|
||||
)
|
||||
@@ -1,168 +0,0 @@
|
||||
"""更新过滤规则组工具。"""
|
||||
|
||||
import json
|
||||
from typing import Optional, Type
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from app.agent.tools.base import MoviePilotTool
|
||||
from app.agent.tools.impl._filter_rule_utils import (
|
||||
build_custom_rule_map,
|
||||
collect_rule_group_usages,
|
||||
get_builtin_rules,
|
||||
get_custom_rules,
|
||||
get_rule_groups,
|
||||
normalize_rule_group,
|
||||
publish_rule_config_changed,
|
||||
serialize_rule_group,
|
||||
)
|
||||
from app.agent.tools.tags import ToolTag
|
||||
from app.runtime.log import logger
|
||||
from app.schemas.types import SystemConfigKey
|
||||
|
||||
|
||||
class UpdateRuleGroupInput(BaseModel):
|
||||
"""更新过滤规则组工具的输入参数模型"""
|
||||
|
||||
current_name: str = Field(..., description="Existing rule group name to update.")
|
||||
new_name: Optional[str] = Field(
|
||||
None,
|
||||
description="New rule group name. If omitted, keep the original name.",
|
||||
)
|
||||
rule_string: Optional[str] = Field(
|
||||
None,
|
||||
description=(
|
||||
"New rule_string. If omitted, keep the original rule_string. "
|
||||
"Example: 'SPECSUB & CNVOI & 4K & !BLU > CNSUB & CNVOI & 4K & !BLU'."
|
||||
),
|
||||
)
|
||||
media_type: Optional[str] = Field(
|
||||
None,
|
||||
description="New media type scope. Pass an empty string to clear it.",
|
||||
)
|
||||
category: Optional[str] = Field(
|
||||
None,
|
||||
description="New category. Pass an empty string to clear it.",
|
||||
)
|
||||
|
||||
|
||||
class UpdateRuleGroupTool(MoviePilotTool):
|
||||
name: str = "update_rule_group"
|
||||
tags: list[str] = [
|
||||
ToolTag.Write,
|
||||
ToolTag.FilterRule,
|
||||
ToolTag.Admin,
|
||||
]
|
||||
description: str = (
|
||||
"Update a filter rule group. "
|
||||
"If the rule group name changes, its references in global search/subscription settings and per-subscription bindings are updated automatically. "
|
||||
"Before changing rule_string, first use query_builtin_filter_rules and query_custom_filter_rules to confirm valid rule IDs."
|
||||
)
|
||||
args_schema: Type[BaseModel] = UpdateRuleGroupInput
|
||||
require_admin: bool = True
|
||||
|
||||
def get_tool_message(self, **kwargs) -> Optional[str]:
|
||||
current_name = kwargs.get("current_name", "")
|
||||
new_name = kwargs.get("new_name")
|
||||
if new_name and new_name != current_name:
|
||||
return f"更新规则组 {current_name} -> {new_name}"
|
||||
return f"更新规则组 {current_name}"
|
||||
|
||||
async def run(
|
||||
self,
|
||||
current_name: str,
|
||||
new_name: Optional[str] = None,
|
||||
rule_string: Optional[str] = None,
|
||||
media_type: Optional[str] = None,
|
||||
category: Optional[str] = None,
|
||||
**kwargs,
|
||||
) -> str:
|
||||
logger.info(f"执行工具: {self.name}, current_name={current_name}")
|
||||
|
||||
try:
|
||||
rule_groups = get_rule_groups()
|
||||
expected_definitions = [
|
||||
group.model_dump(exclude_none=True) for group in rule_groups
|
||||
]
|
||||
group_map = {group.name: group for group in rule_groups if group.name}
|
||||
current_group = group_map.get(current_name)
|
||||
if not current_group:
|
||||
return json.dumps(
|
||||
{
|
||||
"success": False,
|
||||
"message": f"规则组 '{current_name}' 不存在",
|
||||
},
|
||||
ensure_ascii=False,
|
||||
)
|
||||
|
||||
available_rule_ids = set(get_builtin_rules().keys()) | set(
|
||||
build_custom_rule_map(get_custom_rules()).keys()
|
||||
)
|
||||
updated_group, _ = normalize_rule_group(
|
||||
name=new_name or current_group.name,
|
||||
rule_string=(
|
||||
rule_string
|
||||
if rule_string is not None
|
||||
else current_group.rule_string
|
||||
),
|
||||
media_type=(
|
||||
media_type
|
||||
if media_type is not None
|
||||
else current_group.media_type
|
||||
),
|
||||
category=(
|
||||
category if category is not None else current_group.category
|
||||
),
|
||||
existing_groups=rule_groups,
|
||||
available_rule_ids=available_rule_ids,
|
||||
original_name=current_group.name,
|
||||
)
|
||||
|
||||
final_groups = []
|
||||
for group in rule_groups:
|
||||
if group.name == current_group.name:
|
||||
final_groups.append(updated_group)
|
||||
else:
|
||||
final_groups.append(group)
|
||||
|
||||
definitions = [
|
||||
group.model_dump(exclude_none=True) for group in final_groups
|
||||
]
|
||||
async with self.data.async_rule_group_mutation_scope() as mutation:
|
||||
result = await mutation.apply(
|
||||
definitions,
|
||||
expected_rule_groups=expected_definitions,
|
||||
previous_name=current_group.name,
|
||||
current_name=updated_group.name,
|
||||
)
|
||||
await publish_rule_config_changed(
|
||||
SystemConfigKey.UserFilterRuleGroups,
|
||||
definitions,
|
||||
)
|
||||
reference_changes = result.to_dict()
|
||||
|
||||
usage = await collect_rule_group_usages(
|
||||
self.data.subscriptions,
|
||||
[updated_group.name],
|
||||
)
|
||||
return json.dumps(
|
||||
{
|
||||
"success": True,
|
||||
"message": f"已更新规则组 {updated_group.name}",
|
||||
"rule_group": serialize_rule_group(
|
||||
updated_group, usage.get(updated_group.name)
|
||||
),
|
||||
"reference_updates": reference_changes,
|
||||
},
|
||||
ensure_ascii=False,
|
||||
indent=2,
|
||||
)
|
||||
except Exception as exc:
|
||||
logger.error(f"更新规则组失败: {exc}", exc_info=True)
|
||||
return json.dumps(
|
||||
{
|
||||
"success": False,
|
||||
"message": f"更新规则组失败: {exc}",
|
||||
},
|
||||
ensure_ascii=False,
|
||||
)
|
||||
@@ -1,234 +0,0 @@
|
||||
"""更新站点工具"""
|
||||
|
||||
import json
|
||||
from typing import Optional, Type
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from app.agent.tools.base import MoviePilotTool
|
||||
from app.agent.tools.tags import ToolTag
|
||||
from app.application.site.contract import SiteMutation
|
||||
from app.foundation import url as url_tools
|
||||
from app.runtime.events import eventmanager
|
||||
from app.runtime.log import logger
|
||||
from app.schemas.types import EventType
|
||||
|
||||
|
||||
class UpdateSiteInput(BaseModel):
|
||||
"""更新站点工具的输入参数模型"""
|
||||
|
||||
site_id: int = Field(
|
||||
...,
|
||||
description="The ID of the site to update (can be obtained from query_sites tool)",
|
||||
)
|
||||
name: Optional[str] = Field(None, description="Site name (optional)")
|
||||
url: Optional[str] = Field(
|
||||
None, description="Site URL (optional, will be automatically formatted)"
|
||||
)
|
||||
pri: Optional[int] = Field(
|
||||
None,
|
||||
description="Site priority (optional, smaller value = higher priority, e.g., pri=1 has higher priority than pri=10)",
|
||||
)
|
||||
rss: Optional[str] = Field(None, description="RSS feed URL (optional)")
|
||||
cookie: Optional[str] = Field(None, description="Site cookie (optional)")
|
||||
ua: Optional[str] = Field(None, description="User-Agent string (optional)")
|
||||
apikey: Optional[str] = Field(None, description="API key (optional)")
|
||||
token: Optional[str] = Field(None, description="API token (optional)")
|
||||
proxy: Optional[int] = Field(
|
||||
None, description="Whether to use proxy: 0 for no, 1 for yes (optional)"
|
||||
)
|
||||
filter: Optional[str] = Field(
|
||||
None, description="Filter rule as regular expression (optional)"
|
||||
)
|
||||
note: Optional[str] = Field(None, description="Site notes/remarks (optional)")
|
||||
timeout: Optional[int] = Field(
|
||||
None, description="Request timeout in seconds (optional, default: 15)"
|
||||
)
|
||||
limit_interval: Optional[int] = Field(
|
||||
None, description="Rate limit interval in seconds (optional)"
|
||||
)
|
||||
limit_count: Optional[int] = Field(
|
||||
None, description="Rate limit count per interval (optional)"
|
||||
)
|
||||
limit_seconds: Optional[int] = Field(
|
||||
None, description="Rate limit seconds between requests (optional)"
|
||||
)
|
||||
is_active: Optional[bool] = Field(
|
||||
None,
|
||||
description="Whether site is active: True for enabled, False for disabled (optional)",
|
||||
)
|
||||
downloader: Optional[str] = Field(
|
||||
None, description="Downloader name for this site (optional)"
|
||||
)
|
||||
|
||||
|
||||
class UpdateSiteTool(MoviePilotTool):
|
||||
name: str = "update_site"
|
||||
tags: list[str] = [
|
||||
ToolTag.Write,
|
||||
ToolTag.Site,
|
||||
ToolTag.Admin,
|
||||
]
|
||||
description: str = "Update site configuration including URL, priority, authentication credentials (cookie, UA, API key), proxy settings, rate limits, and other site properties. Supports updating multiple site attributes at once. Site priority (pri): smaller values have higher priority (e.g., pri=1 has higher priority than pri=10)."
|
||||
args_schema: Type[BaseModel] = UpdateSiteInput
|
||||
require_admin: bool = True
|
||||
|
||||
def get_tool_message(self, **kwargs) -> Optional[str]:
|
||||
"""根据更新参数生成友好的提示消息"""
|
||||
site_id = kwargs.get("site_id")
|
||||
fields_updated = []
|
||||
|
||||
if kwargs.get("name"):
|
||||
fields_updated.append("名称")
|
||||
if kwargs.get("url"):
|
||||
fields_updated.append("URL")
|
||||
if kwargs.get("pri") is not None:
|
||||
fields_updated.append("优先级")
|
||||
if kwargs.get("cookie"):
|
||||
fields_updated.append("Cookie")
|
||||
if kwargs.get("ua"):
|
||||
fields_updated.append("User-Agent")
|
||||
if kwargs.get("proxy") is not None:
|
||||
fields_updated.append("代理设置")
|
||||
if kwargs.get("is_active") is not None:
|
||||
fields_updated.append("启用状态")
|
||||
if kwargs.get("downloader"):
|
||||
fields_updated.append("下载器")
|
||||
|
||||
if fields_updated:
|
||||
return f"更新站点 #{site_id}: {', '.join(fields_updated)}"
|
||||
return f"更新站点 #{site_id}"
|
||||
|
||||
async def run(
|
||||
self,
|
||||
site_id: int,
|
||||
name: Optional[str] = None,
|
||||
url: Optional[str] = None,
|
||||
pri: Optional[int] = None,
|
||||
rss: Optional[str] = None,
|
||||
cookie: Optional[str] = None,
|
||||
ua: Optional[str] = None,
|
||||
apikey: Optional[str] = None,
|
||||
token: Optional[str] = None,
|
||||
proxy: Optional[int] = None,
|
||||
filter: Optional[str] = None,
|
||||
note: Optional[str] = None,
|
||||
timeout: Optional[int] = None,
|
||||
limit_interval: Optional[int] = None,
|
||||
limit_count: Optional[int] = None,
|
||||
limit_seconds: Optional[int] = None,
|
||||
is_active: Optional[bool] = None,
|
||||
downloader: Optional[str] = None,
|
||||
**kwargs,
|
||||
) -> str:
|
||||
logger.info(f"执行工具: {self.name}, 参数: site_id={site_id}")
|
||||
|
||||
try:
|
||||
repository = self.data.sites
|
||||
site = await repository.async_get(site_id)
|
||||
if not site:
|
||||
return json.dumps(
|
||||
{"success": False, "message": f"站点不存在: {site_id}"},
|
||||
ensure_ascii=False,
|
||||
)
|
||||
|
||||
# 构建更新字典
|
||||
site_dict = {}
|
||||
|
||||
# 基本信息
|
||||
if name is not None:
|
||||
site_dict["name"] = name
|
||||
|
||||
# URL处理(需要校正格式)
|
||||
if url is not None:
|
||||
_scheme, _netloc = url_tools.split_netloc(url)
|
||||
site_dict["url"] = f"{_scheme}://{_netloc}/"
|
||||
|
||||
if pri is not None:
|
||||
site_dict["pri"] = pri
|
||||
if rss is not None:
|
||||
site_dict["rss"] = rss
|
||||
|
||||
# 认证信息
|
||||
if cookie is not None:
|
||||
site_dict["cookie"] = cookie
|
||||
if ua is not None:
|
||||
site_dict["ua"] = ua
|
||||
if apikey is not None:
|
||||
site_dict["apikey"] = apikey
|
||||
if token is not None:
|
||||
site_dict["token"] = token
|
||||
|
||||
# 配置选项
|
||||
if proxy is not None:
|
||||
site_dict["proxy"] = proxy
|
||||
if filter is not None:
|
||||
site_dict["filter"] = filter
|
||||
if note is not None:
|
||||
site_dict["note"] = note
|
||||
if timeout is not None:
|
||||
site_dict["timeout"] = timeout
|
||||
|
||||
# 流控设置
|
||||
if limit_interval is not None:
|
||||
site_dict["limit_interval"] = limit_interval
|
||||
if limit_count is not None:
|
||||
site_dict["limit_count"] = limit_count
|
||||
if limit_seconds is not None:
|
||||
site_dict["limit_seconds"] = limit_seconds
|
||||
|
||||
# 状态和下载器
|
||||
if is_active is not None:
|
||||
site_dict["is_active"] = is_active
|
||||
if downloader is not None:
|
||||
site_dict["downloader"] = downloader
|
||||
|
||||
# 如果没有要更新的字段
|
||||
if not site_dict:
|
||||
return json.dumps(
|
||||
{"success": False, "message": "没有提供要更新的字段"},
|
||||
ensure_ascii=False,
|
||||
)
|
||||
|
||||
# 更新站点
|
||||
await repository.async_update(site_id, SiteMutation(site_dict))
|
||||
|
||||
# 重新获取更新后的站点数据
|
||||
updated_site = await repository.async_get(site_id)
|
||||
|
||||
# 发送站点更新事件
|
||||
await eventmanager.async_send_event(
|
||||
EventType.SiteUpdated,
|
||||
{"domain": updated_site.domain if updated_site else site.domain},
|
||||
)
|
||||
|
||||
# 构建返回结果
|
||||
result = {
|
||||
"success": True,
|
||||
"message": f"站点 #{site_id} 更新成功",
|
||||
"site_id": site_id,
|
||||
"updated_fields": list(site_dict.keys()),
|
||||
}
|
||||
|
||||
if updated_site:
|
||||
result["site"] = {
|
||||
"id": updated_site.id,
|
||||
"name": updated_site.name,
|
||||
"domain": updated_site.domain,
|
||||
"url": updated_site.url,
|
||||
"pri": updated_site.pri,
|
||||
"is_active": updated_site.is_active,
|
||||
"downloader": updated_site.downloader,
|
||||
"proxy": updated_site.proxy,
|
||||
"timeout": updated_site.timeout,
|
||||
}
|
||||
|
||||
return json.dumps(result, ensure_ascii=False, indent=2)
|
||||
|
||||
except Exception as e:
|
||||
error_message = f"更新站点失败: {str(e)}"
|
||||
logger.error(f"更新站点失败: {e}", exc_info=True)
|
||||
return json.dumps(
|
||||
{"success": False, "message": error_message, "site_id": site_id},
|
||||
ensure_ascii=False,
|
||||
)
|
||||
@@ -1,103 +0,0 @@
|
||||
"""更新站点Cookie和UA工具"""
|
||||
|
||||
from typing import Optional, Type
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from app.agent.tools.base import MoviePilotTool
|
||||
from app.agent.tools.tags import ToolTag
|
||||
from app.chain.site import SiteChain
|
||||
from app.runtime.log import logger
|
||||
|
||||
|
||||
class UpdateSiteCookieInput(BaseModel):
|
||||
"""更新站点Cookie和UA工具的输入参数模型"""
|
||||
|
||||
site_identifier: int = Field(
|
||||
...,
|
||||
description="Site ID to update Cookie and User-Agent for (can be obtained from query_sites tool)",
|
||||
)
|
||||
username: str = Field(..., description="Site login username")
|
||||
password: str = Field(..., description="Site login password")
|
||||
two_step_code: Optional[str] = Field(
|
||||
None,
|
||||
description="Two-step verification code or secret key (optional, required for sites with 2FA enabled)",
|
||||
)
|
||||
|
||||
|
||||
class UpdateSiteCookieTool(MoviePilotTool):
|
||||
name: str = "update_site_cookie"
|
||||
tags: list[str] = [
|
||||
ToolTag.Write,
|
||||
ToolTag.Site,
|
||||
ToolTag.Admin,
|
||||
]
|
||||
description: str = "Update site Cookie and User-Agent by logging in with username and password. This tool can automatically obtain and update the site's authentication credentials. Supports two-step verification for sites that require it. Accepts site ID only."
|
||||
args_schema: Type[BaseModel] = UpdateSiteCookieInput
|
||||
require_admin: bool = True
|
||||
|
||||
def get_tool_message(self, **kwargs) -> Optional[str]:
|
||||
"""根据更新参数生成友好的提示消息"""
|
||||
site_identifier = kwargs.get("site_identifier")
|
||||
username = kwargs.get("username", "")
|
||||
two_step_code = kwargs.get("two_step_code")
|
||||
|
||||
message = f"更新站点Cookie: {site_identifier} (用户: {username})"
|
||||
if two_step_code:
|
||||
message += " [需要两步验证]"
|
||||
|
||||
return message
|
||||
|
||||
def _update_site_cookie_sync(
|
||||
self,
|
||||
site_identifier: int,
|
||||
username: str,
|
||||
password: str,
|
||||
two_step_code: Optional[str] = None,
|
||||
) -> tuple[Optional[str], bool, str]:
|
||||
"""
|
||||
在同步线程里执行站点登录和 Cookie 更新,避免网络登录阻塞协程。
|
||||
"""
|
||||
site = self.data.sites.get(site_identifier)
|
||||
if not site:
|
||||
return None, False, f"未找到站点:{site_identifier},请使用 query_sites 工具查询可用的站点"
|
||||
|
||||
status, message = SiteChain().update_cookie(
|
||||
site_info=site,
|
||||
username=username,
|
||||
password=password,
|
||||
two_step_code=two_step_code,
|
||||
)
|
||||
return site.name, status, message
|
||||
|
||||
async def run(
|
||||
self,
|
||||
site_identifier: int,
|
||||
username: str,
|
||||
password: str,
|
||||
two_step_code: Optional[str] = None,
|
||||
**kwargs,
|
||||
) -> str:
|
||||
logger.info(
|
||||
f"执行工具: {self.name}, 参数: site_identifier={site_identifier}, username={username}"
|
||||
)
|
||||
|
||||
try:
|
||||
site_name, status, message = await self.run_blocking(
|
||||
"site",
|
||||
self._update_site_cookie_sync,
|
||||
site_identifier,
|
||||
username,
|
||||
password,
|
||||
two_step_code,
|
||||
)
|
||||
if not site_name:
|
||||
return message
|
||||
|
||||
if status:
|
||||
return f"站点【{site_name}】Cookie和UA更新成功\n{message}"
|
||||
else:
|
||||
return f"站点【{site_name}】Cookie和UA更新失败\n错误原因:{message}"
|
||||
except Exception as e:
|
||||
logger.error(f"更新站点Cookie和UA失败: {e}", exc_info=True)
|
||||
return f"更新站点Cookie和UA时发生错误: {str(e)}"
|
||||
@@ -1,363 +0,0 @@
|
||||
"""更新订阅工具"""
|
||||
|
||||
import json
|
||||
from typing import List, Optional, Type
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from app.agent.tools.base import MoviePilotTool
|
||||
from app.agent.tools.tags import ToolTag
|
||||
from app.application.subscription.mutation import SubscriptionActor
|
||||
from app.runtime.log import logger
|
||||
from app.schemas.common import JsonData
|
||||
from app.schemas.types import media_type_to_agent
|
||||
|
||||
|
||||
class UpdateSubscribeInput(BaseModel):
|
||||
"""更新订阅工具的输入参数模型"""
|
||||
|
||||
subscribe_id: int = Field(
|
||||
...,
|
||||
description="The ID of the subscription to update (can be obtained from query_subscribes tool)",
|
||||
)
|
||||
name: Optional[str] = Field(None, description="Subscription name/title (optional)")
|
||||
year: Optional[str] = Field(None, description="Release year (optional)")
|
||||
season: Optional[int] = Field(
|
||||
None, description="Season number for TV shows (optional)"
|
||||
)
|
||||
total_episode: Optional[int] = Field(
|
||||
None, description="Total number of episodes (optional)"
|
||||
)
|
||||
lack_episode: Optional[int] = Field(
|
||||
None, description="Number of missing episodes (optional)"
|
||||
)
|
||||
start_episode: Optional[int] = Field(
|
||||
None, description="Starting episode number (optional)"
|
||||
)
|
||||
quality: Optional[str] = Field(
|
||||
None,
|
||||
description="Quality filter as regular expression (optional, e.g., 'BluRay|WEB-DL|HDTV')",
|
||||
)
|
||||
resolution: Optional[str] = Field(
|
||||
None,
|
||||
description="Resolution filter as regular expression (optional, e.g., '1080p|720p|2160p')",
|
||||
)
|
||||
effect: Optional[str] = Field(
|
||||
None,
|
||||
description="Effect filter as regular expression (optional, e.g., 'HDR|DV|SDR')",
|
||||
)
|
||||
audio_quality: Optional[str] = Field(None, description="Music quality tier filter")
|
||||
audio_format: Optional[str] = Field(None, description="Music audio-format regular expression")
|
||||
min_bitrate: Optional[int] = Field(None, description="Minimum music bitrate in bits per second")
|
||||
min_bit_depth: Optional[int] = Field(None, description="Minimum music bit depth")
|
||||
min_sample_rate: Optional[int] = Field(None, description="Minimum music sample rate in Hz")
|
||||
include: Optional[str] = Field(
|
||||
None, description="Include filter as regular expression (optional)"
|
||||
)
|
||||
exclude: Optional[str] = Field(
|
||||
None, description="Exclude filter as regular expression (optional)"
|
||||
)
|
||||
filter: Optional[str] = Field(
|
||||
None, description="Filter rule as regular expression (optional)"
|
||||
)
|
||||
state: Optional[str] = Field(
|
||||
None,
|
||||
description="Subscription state: 'R' for enabled, 'P' for pending, 'S' for paused (optional)",
|
||||
)
|
||||
sites: Optional[List[int]] = Field(
|
||||
None, description="List of site IDs to search from (optional)"
|
||||
)
|
||||
downloader: Optional[str] = Field(None, description="Downloader name (optional)")
|
||||
save_path: Optional[str] = Field(
|
||||
None, description="Save path for downloaded files (optional)"
|
||||
)
|
||||
best_version: Optional[int] = Field(
|
||||
None,
|
||||
description="Whether to upgrade to best version: 0 for no, 1 for yes (optional)",
|
||||
)
|
||||
best_version_full: Optional[int] = Field(
|
||||
None,
|
||||
description="For TV best-version subscriptions, only download full-season packs: 0 for no, 1 for yes (optional)",
|
||||
)
|
||||
custom_words: Optional[str] = Field(
|
||||
None, description="Custom recognition words (optional)"
|
||||
)
|
||||
media_category: Optional[str] = Field(
|
||||
None, description="Custom media category (optional)"
|
||||
)
|
||||
episode_group: Optional[str] = Field(
|
||||
None, description="Episode group ID (optional)"
|
||||
)
|
||||
|
||||
|
||||
class UpdateSubscribeTool(MoviePilotTool):
|
||||
"""更新影视、单曲或专辑订阅的运行参数。"""
|
||||
|
||||
name: str = "update_subscribe"
|
||||
tags: list[str] = [
|
||||
ToolTag.Write,
|
||||
ToolTag.Subscription,
|
||||
ToolTag.Admin,
|
||||
]
|
||||
description: str = (
|
||||
"Update subscription filters, state, sites, downloader, save path, and other runtime settings. "
|
||||
"Episode fields are TV-only; music recording/album identity and expected album track count are metadata "
|
||||
"facts and are not changed by this tool."
|
||||
)
|
||||
args_schema: Type[BaseModel] = UpdateSubscribeInput
|
||||
require_admin: bool = True
|
||||
|
||||
def get_tool_message(self, **kwargs) -> Optional[str]:
|
||||
"""根据更新参数生成友好的提示消息"""
|
||||
subscribe_id = kwargs.get("subscribe_id")
|
||||
fields_updated = []
|
||||
|
||||
if kwargs.get("name"):
|
||||
fields_updated.append("名称")
|
||||
if kwargs.get("total_episode") is not None:
|
||||
fields_updated.append("总集数")
|
||||
if kwargs.get("lack_episode") is not None:
|
||||
fields_updated.append("缺失集数")
|
||||
if kwargs.get("quality"):
|
||||
fields_updated.append("质量过滤")
|
||||
if kwargs.get("resolution"):
|
||||
fields_updated.append("分辨率过滤")
|
||||
if kwargs.get("state"):
|
||||
state_map = {"R": "启用", "P": "禁用", "S": "暂停"}
|
||||
fields_updated.append(
|
||||
f"状态({state_map.get(kwargs.get('state'), kwargs.get('state'))})"
|
||||
)
|
||||
if kwargs.get("sites"):
|
||||
fields_updated.append("站点")
|
||||
if kwargs.get("downloader"):
|
||||
fields_updated.append("下载器")
|
||||
|
||||
if fields_updated:
|
||||
return f"更新订阅 #{subscribe_id}: {', '.join(fields_updated)}"
|
||||
return f"更新订阅 #{subscribe_id}"
|
||||
|
||||
async def run(
|
||||
self,
|
||||
subscribe_id: int,
|
||||
name: Optional[str] = None,
|
||||
year: Optional[str] = None,
|
||||
season: Optional[int] = None,
|
||||
total_episode: Optional[int] = None,
|
||||
lack_episode: Optional[int] = None,
|
||||
start_episode: Optional[int] = None,
|
||||
quality: Optional[str] = None,
|
||||
resolution: Optional[str] = None,
|
||||
effect: Optional[str] = None,
|
||||
audio_quality: Optional[str] = None,
|
||||
audio_format: Optional[str] = None,
|
||||
min_bitrate: Optional[int] = None,
|
||||
min_bit_depth: Optional[int] = None,
|
||||
min_sample_rate: Optional[int] = None,
|
||||
include: Optional[str] = None,
|
||||
exclude: Optional[str] = None,
|
||||
filter: Optional[str] = None,
|
||||
state: Optional[str] = None,
|
||||
sites: Optional[List[int]] = None,
|
||||
downloader: Optional[str] = None,
|
||||
save_path: Optional[str] = None,
|
||||
best_version: Optional[int] = None,
|
||||
best_version_full: Optional[int] = None,
|
||||
custom_words: Optional[str] = None,
|
||||
media_category: Optional[str] = None,
|
||||
episode_group: Optional[str] = None,
|
||||
**kwargs,
|
||||
) -> str:
|
||||
"""更新可变订阅字段并发送订阅调整事件。"""
|
||||
logger.info(f"执行工具: {self.name}, 参数: subscribe_id={subscribe_id}")
|
||||
|
||||
try:
|
||||
actor = SubscriptionActor(name="agent", is_superuser=True)
|
||||
async with self.data.subscription_mutation_scope() as mutation:
|
||||
subscribe = await mutation.get_accessible(subscribe_id, actor)
|
||||
if not subscribe:
|
||||
return json.dumps(
|
||||
{"success": False, "message": f"订阅不存在: {subscribe_id}"},
|
||||
ensure_ascii=False,
|
||||
)
|
||||
if media_type_to_agent(subscribe.type) == "music" and any(
|
||||
value is not None
|
||||
for value in (
|
||||
season,
|
||||
total_episode,
|
||||
lack_episode,
|
||||
start_episode,
|
||||
best_version_full,
|
||||
episode_group,
|
||||
)
|
||||
):
|
||||
return json.dumps(
|
||||
{
|
||||
"success": False,
|
||||
"message": "音乐订阅不能更新季集、整季洗版或剧集组字段",
|
||||
},
|
||||
ensure_ascii=False,
|
||||
)
|
||||
if media_type_to_agent(subscribe.type) != "music" and any(
|
||||
value is not None
|
||||
for value in (audio_quality, audio_format, min_bitrate, min_bit_depth, min_sample_rate)
|
||||
):
|
||||
return json.dumps(
|
||||
{"success": False, "message": "音质等级、音频格式和音频技术参数仅用于音乐订阅"},
|
||||
ensure_ascii=False,
|
||||
)
|
||||
|
||||
# 构建更新字典
|
||||
subscribe_dict: dict[str, JsonData] = {}
|
||||
|
||||
# 基本信息
|
||||
if name is not None:
|
||||
subscribe_dict["name"] = name
|
||||
if year is not None:
|
||||
subscribe_dict["year"] = year
|
||||
if season is not None:
|
||||
subscribe_dict["season"] = season
|
||||
|
||||
# 集数相关
|
||||
if total_episode is not None and total_episode != subscribe.total_episode:
|
||||
subscribe_dict["total_episode"] = total_episode
|
||||
# 如果总集数增加,缺失集数也要相应增加
|
||||
if total_episode > (subscribe.total_episode or 0):
|
||||
old_lack = subscribe.lack_episode or 0
|
||||
subscribe_dict["lack_episode"] = old_lack + (
|
||||
total_episode - (subscribe.total_episode or 0)
|
||||
)
|
||||
# 标记为手动修改过总集数
|
||||
subscribe_dict["manual_total_episode"] = 1
|
||||
|
||||
# 缺失集数处理(只有在没有提供总集数时才单独处理)
|
||||
# 注意:如果 lack_episode 为 0,不更新(避免更新为0)
|
||||
if lack_episode is not None and total_episode is None:
|
||||
if lack_episode > 0:
|
||||
subscribe_dict["lack_episode"] = lack_episode
|
||||
# 如果 lack_episode 为 0,不添加到更新字典中(保持原值或由总集数逻辑处理)
|
||||
|
||||
if start_episode is not None:
|
||||
subscribe_dict["start_episode"] = start_episode
|
||||
|
||||
# 过滤规则
|
||||
if quality is not None:
|
||||
subscribe_dict["quality"] = quality
|
||||
if resolution is not None:
|
||||
subscribe_dict["resolution"] = resolution
|
||||
if effect is not None:
|
||||
subscribe_dict["effect"] = effect
|
||||
if audio_quality is not None:
|
||||
subscribe_dict["audio_quality"] = audio_quality
|
||||
if audio_format is not None:
|
||||
subscribe_dict["audio_format"] = audio_format
|
||||
if min_bitrate is not None:
|
||||
subscribe_dict["min_bitrate"] = min_bitrate
|
||||
if min_bit_depth is not None:
|
||||
subscribe_dict["min_bit_depth"] = min_bit_depth
|
||||
if min_sample_rate is not None:
|
||||
subscribe_dict["min_sample_rate"] = min_sample_rate
|
||||
if include is not None:
|
||||
subscribe_dict["include"] = include
|
||||
if exclude is not None:
|
||||
subscribe_dict["exclude"] = exclude
|
||||
if filter is not None:
|
||||
subscribe_dict["filter"] = filter
|
||||
|
||||
# 状态
|
||||
if state is not None:
|
||||
valid_states = ["R", "P", "S", "N"]
|
||||
if state not in valid_states:
|
||||
return json.dumps(
|
||||
{
|
||||
"success": False,
|
||||
"message": f"无效的订阅状态: {state},有效状态: {', '.join(valid_states)}",
|
||||
},
|
||||
ensure_ascii=False,
|
||||
)
|
||||
subscribe_dict["state"] = state
|
||||
|
||||
# 下载配置
|
||||
if sites is not None:
|
||||
subscribe_dict["sites"] = sites
|
||||
if downloader is not None:
|
||||
subscribe_dict["downloader"] = downloader
|
||||
if save_path is not None:
|
||||
subscribe_dict["save_path"] = save_path
|
||||
if best_version is not None:
|
||||
subscribe_dict["best_version"] = best_version
|
||||
if best_version_full is not None:
|
||||
subscribe_dict["best_version_full"] = best_version_full
|
||||
|
||||
# 其他配置
|
||||
if custom_words is not None:
|
||||
subscribe_dict["custom_words"] = custom_words
|
||||
if media_category is not None:
|
||||
subscribe_dict["media_category"] = media_category
|
||||
if episode_group is not None:
|
||||
subscribe_dict["episode_group"] = episode_group
|
||||
|
||||
# 如果没有要更新的字段
|
||||
if not subscribe_dict:
|
||||
return json.dumps(
|
||||
{"success": False, "message": "没有提供要更新的字段"},
|
||||
ensure_ascii=False,
|
||||
)
|
||||
|
||||
# Agent 工具没有 FastAPI 请求会话,由组合根提供一次独占事务作用域;
|
||||
# 更新和 durable intent 必须共享同一 AsyncSession。
|
||||
async with self.data.subscription_mutation_scope() as mutation:
|
||||
change = await mutation.update(
|
||||
subscribe_id,
|
||||
subscribe_dict,
|
||||
actor,
|
||||
scene="agent_update",
|
||||
)
|
||||
if not change:
|
||||
return json.dumps(
|
||||
{"success": False, "message": f"订阅不存在: {subscribe_id}"},
|
||||
ensure_ascii=False,
|
||||
)
|
||||
updated_subscribe = change.new
|
||||
|
||||
# 构建返回结果
|
||||
result = {
|
||||
"success": True,
|
||||
"message": f"订阅 #{subscribe_id} 更新成功",
|
||||
"subscribe_id": subscribe_id,
|
||||
"updated_fields": list(subscribe_dict.keys()),
|
||||
}
|
||||
|
||||
if updated_subscribe:
|
||||
result["subscribe"] = {
|
||||
"id": updated_subscribe.get("id"),
|
||||
"name": updated_subscribe.get("name"),
|
||||
"year": updated_subscribe.get("year"),
|
||||
"type": media_type_to_agent(updated_subscribe.get("type")),
|
||||
"music_type": updated_subscribe.get("music_type"),
|
||||
"total_tracks": updated_subscribe.get("total_tracks"),
|
||||
"media_source": updated_subscribe.get("media_source"),
|
||||
"media_id": updated_subscribe.get("media_id"),
|
||||
"season": updated_subscribe.get("season"),
|
||||
"state": updated_subscribe.get("state"),
|
||||
"total_episode": updated_subscribe.get("total_episode"),
|
||||
"manual_total_episode": updated_subscribe.get("manual_total_episode"),
|
||||
"lack_episode": updated_subscribe.get("lack_episode"),
|
||||
"start_episode": updated_subscribe.get("start_episode"),
|
||||
"quality": updated_subscribe.get("quality"),
|
||||
"resolution": updated_subscribe.get("resolution"),
|
||||
"effect": updated_subscribe.get("effect"),
|
||||
}
|
||||
|
||||
return json.dumps(result, ensure_ascii=False, indent=2)
|
||||
|
||||
except Exception as e:
|
||||
error_message = f"更新订阅失败: {str(e)}"
|
||||
logger.error(f"更新订阅失败: {e}", exc_info=True)
|
||||
return json.dumps(
|
||||
{
|
||||
"success": False,
|
||||
"message": error_message,
|
||||
"subscribe_id": subscribe_id,
|
||||
},
|
||||
ensure_ascii=False,
|
||||
)
|
||||
@@ -1,363 +0,0 @@
|
||||
"""统一更新系统设置工具。"""
|
||||
|
||||
import copy
|
||||
import json
|
||||
from typing import Any, Literal, Optional, Type, Union
|
||||
|
||||
from pydantic import BaseModel, Field, PrivateAttr
|
||||
|
||||
from app.agent.tools.base import MoviePilotTool
|
||||
from app.agent.tools.tags import ToolTag
|
||||
from app.agent.tools.impl._system_setting_utils import (
|
||||
SettingSpec,
|
||||
get_default_list_match_field,
|
||||
is_secret_setting_key,
|
||||
redact_secret_value,
|
||||
resolve_setting_spec,
|
||||
should_redact_setting,
|
||||
)
|
||||
from app.runtime.events import eventmanager
|
||||
from app.application.configuration import (
|
||||
SystemConfigService,
|
||||
get_configured_system_config,
|
||||
get_runtime_settings,
|
||||
)
|
||||
from app.application.plugin.runtime import plugin_system_config_mutation
|
||||
from app.runtime.log import logger
|
||||
from app.schemas.event import ConfigChangeEventData
|
||||
from app.schemas.types import EventType
|
||||
|
||||
SettingValue = Optional[Union[list, dict, bool, int, float, str]]
|
||||
|
||||
|
||||
class UpdateSystemSettingsInput(BaseModel):
|
||||
"""更新系统设置工具的输入参数模型。"""
|
||||
|
||||
setting_key: str = Field(
|
||||
...,
|
||||
description=(
|
||||
"Exact setting key to update. Supports Settings field names, SystemConfigKey values, enum names, and common aliases "
|
||||
"such as 'downloaders', 'directories', 'search_sites', 'subscribe_sites', 'site_auth', 'ai_agent', and 'custom_identifiers'."
|
||||
),
|
||||
)
|
||||
value: SettingValue = Field(
|
||||
None,
|
||||
description=(
|
||||
"The new value or list item payload. For replace: this becomes the entire setting value. For merge_dict: this should be a dict of keys to merge. "
|
||||
"For upsert_list_item/remove_list_item: this can be a dict item or a scalar list item."
|
||||
),
|
||||
)
|
||||
operation: Literal[
|
||||
"replace",
|
||||
"merge_dict",
|
||||
"upsert_list_item",
|
||||
"remove_list_item",
|
||||
] = Field(
|
||||
"replace",
|
||||
description=(
|
||||
"Update operation. replace replaces the whole value; merge_dict merges dict keys (optionally with remove_keys); "
|
||||
"upsert_list_item inserts or replaces one item inside a list; remove_list_item removes one item from a list."
|
||||
),
|
||||
)
|
||||
remove_keys: Optional[list[str]] = Field(
|
||||
None,
|
||||
description="Optional dict keys to delete when operation is merge_dict.",
|
||||
)
|
||||
match_field: Optional[str] = Field(
|
||||
None,
|
||||
description=(
|
||||
"Optional match field for list item upsert/remove. If omitted, common SystemConfig categories use built-in defaults such as 'name' or 'type'."
|
||||
),
|
||||
)
|
||||
match_value: SettingValue = Field(
|
||||
None,
|
||||
description=(
|
||||
"Optional explicit value used to locate a list item when operation is upsert_list_item or remove_list_item."
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
class UpdateSystemSettingsTool(MoviePilotTool):
|
||||
"""通过授权配置服务修改可登记系统设置。"""
|
||||
|
||||
name: str = "update_system_settings"
|
||||
tags: list[str] = [
|
||||
ToolTag.Write,
|
||||
ToolTag.System,
|
||||
ToolTag.Settings,
|
||||
ToolTag.Admin,
|
||||
]
|
||||
description: str = (
|
||||
"Update system settings across both the basic Settings module and all SystemConfig-backed categories. "
|
||||
"Supports full replacement, shallow dict merge, and generic list item upsert/remove so the agent can manage downloaders, media servers, notification channels, storages, directories, search-site ranges, subscribe-site ranges, site auth params, AI agent config, and other system settings through one tool."
|
||||
)
|
||||
require_admin: bool = True
|
||||
args_schema: Type[BaseModel] = UpdateSystemSettingsInput
|
||||
_system_config: Optional[SystemConfigService] = PrivateAttr(default=None)
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
session_id: str,
|
||||
user_id: str,
|
||||
*,
|
||||
system_config: Optional[SystemConfigService] = None,
|
||||
**kwargs,
|
||||
) -> None:
|
||||
"""注入配置读写服务,并兼容组合根默认装配。"""
|
||||
super().__init__(session_id=session_id, user_id=user_id, **kwargs)
|
||||
self._system_config = system_config
|
||||
|
||||
def _get_system_config(self) -> SystemConfigService:
|
||||
"""返回显式注入服务,旧构造形态则延迟读取组合根服务。"""
|
||||
return self._system_config or get_configured_system_config()
|
||||
|
||||
def get_tool_message(self, **kwargs) -> Optional[str]:
|
||||
"""根据更新参数生成友好的提示消息。"""
|
||||
|
||||
setting_key = kwargs.get("setting_key", "")
|
||||
operation = kwargs.get("operation", "replace")
|
||||
action_map = {
|
||||
"replace": "覆盖系统设置",
|
||||
"merge_dict": "合并系统设置",
|
||||
"upsert_list_item": "更新列表项",
|
||||
"remove_list_item": "移除列表项",
|
||||
}
|
||||
return f"{action_map.get(operation, '更新系统设置')}: {setting_key}"
|
||||
|
||||
def _load_setting_value(self, spec: SettingSpec):
|
||||
"""读取指定设置项的当前值。"""
|
||||
if spec.source == "settings":
|
||||
return get_runtime_settings().get(spec.key)
|
||||
return self._get_system_config().get(spec.systemconfig_key)
|
||||
|
||||
@staticmethod
|
||||
def _normalize_systemconfig_value(value: Any):
|
||||
"""规范化写入 SystemConfig 的空列表值。"""
|
||||
if isinstance(value, list):
|
||||
filtered = [item for item in value if item is not None]
|
||||
return filtered or None
|
||||
return value
|
||||
|
||||
@staticmethod
|
||||
def _resolve_list_match(
|
||||
spec: SettingSpec,
|
||||
operation: str,
|
||||
value: Any,
|
||||
match_field: Optional[str],
|
||||
match_value: Any,
|
||||
) -> tuple[Optional[str], Any]:
|
||||
resolved_field = match_field or get_default_list_match_field(spec.key)
|
||||
resolved_value = match_value
|
||||
|
||||
if isinstance(value, dict):
|
||||
if not resolved_field:
|
||||
raise ValueError(
|
||||
f"{operation} 需要提供 match_field,或使用带默认匹配字段的系统配置项"
|
||||
)
|
||||
if resolved_value is None:
|
||||
resolved_value = value.get(resolved_field)
|
||||
if resolved_value is None:
|
||||
raise ValueError(
|
||||
f"{operation} 缺少匹配值,请在 value.{resolved_field} 或 match_value 中提供"
|
||||
)
|
||||
else:
|
||||
if resolved_value is None:
|
||||
resolved_value = value
|
||||
|
||||
return resolved_field, resolved_value
|
||||
|
||||
@classmethod
|
||||
def _prepare_next_value(
|
||||
cls,
|
||||
spec: SettingSpec,
|
||||
current_value: Any,
|
||||
value: Any,
|
||||
operation: str,
|
||||
remove_keys: Optional[list[str]] = None,
|
||||
match_field: Optional[str] = None,
|
||||
match_value: Any = None,
|
||||
) -> Any:
|
||||
remove_keys = remove_keys or []
|
||||
if operation == "replace":
|
||||
return value
|
||||
|
||||
if operation == "merge_dict":
|
||||
if remove_keys and not isinstance(remove_keys, list):
|
||||
raise ValueError("remove_keys 必须是字符串列表")
|
||||
if current_value is not None and not isinstance(current_value, dict):
|
||||
raise ValueError("merge_dict 仅支持当前值为 dict 的设置项")
|
||||
if value is not None and not isinstance(value, dict):
|
||||
raise ValueError("merge_dict 的 value 必须是 dict 或 null")
|
||||
next_value = dict(current_value or {})
|
||||
if value:
|
||||
next_value.update(value)
|
||||
for key in remove_keys:
|
||||
next_value.pop(key, None)
|
||||
return next_value
|
||||
|
||||
if operation not in {"upsert_list_item", "remove_list_item"}:
|
||||
raise ValueError(f"不支持的操作: {operation}")
|
||||
|
||||
if current_value is not None and not isinstance(current_value, list):
|
||||
raise ValueError(f"{operation} 仅支持当前值为 list 的设置项")
|
||||
|
||||
next_items = list(copy.deepcopy(current_value or []))
|
||||
resolved_field, resolved_match_value = cls._resolve_list_match(
|
||||
spec, operation, value, match_field, match_value
|
||||
)
|
||||
|
||||
if operation == "upsert_list_item":
|
||||
if value is None:
|
||||
raise ValueError("upsert_list_item 必须提供 value")
|
||||
replaced = False
|
||||
for index, item in enumerate(next_items):
|
||||
if resolved_field:
|
||||
if isinstance(item, dict) and item.get(resolved_field) == resolved_match_value:
|
||||
next_items[index] = value
|
||||
replaced = True
|
||||
break
|
||||
elif item == resolved_match_value:
|
||||
next_items[index] = value
|
||||
replaced = True
|
||||
break
|
||||
if not replaced:
|
||||
next_items.append(value)
|
||||
return next_items
|
||||
|
||||
return [
|
||||
item
|
||||
for item in next_items
|
||||
if not (
|
||||
isinstance(item, dict)
|
||||
and resolved_field
|
||||
and item.get(resolved_field) == resolved_match_value
|
||||
)
|
||||
and not (not resolved_field and item == resolved_match_value)
|
||||
]
|
||||
|
||||
async def run(
|
||||
self,
|
||||
setting_key: str,
|
||||
value: SettingValue = None,
|
||||
operation: str = "replace",
|
||||
remove_keys: Optional[list[str]] = None,
|
||||
match_field: Optional[str] = None,
|
||||
match_value: SettingValue = None,
|
||||
**kwargs,
|
||||
) -> str:
|
||||
logger.info(
|
||||
f"执行工具: {self.name}, setting_key={setting_key}, operation={operation}"
|
||||
)
|
||||
|
||||
try:
|
||||
spec = resolve_setting_spec(setting_key)
|
||||
if not spec:
|
||||
return json.dumps(
|
||||
{
|
||||
"success": False,
|
||||
"message": f"系统设置项 '{setting_key}' 不存在",
|
||||
},
|
||||
ensure_ascii=False,
|
||||
)
|
||||
|
||||
mutation_key = (
|
||||
spec.systemconfig_key if spec.source == "systemconfig" else None
|
||||
)
|
||||
with plugin_system_config_mutation(mutation_key):
|
||||
current_value = self._load_setting_value(spec)
|
||||
next_value = self._prepare_next_value(
|
||||
spec=spec,
|
||||
current_value=current_value,
|
||||
value=value,
|
||||
operation=operation,
|
||||
remove_keys=remove_keys,
|
||||
match_field=match_field,
|
||||
match_value=match_value,
|
||||
)
|
||||
|
||||
event_value = next_value
|
||||
changed = False
|
||||
message = ""
|
||||
if spec.source == "settings":
|
||||
success, message = get_runtime_settings().update(
|
||||
spec.key,
|
||||
next_value,
|
||||
)
|
||||
if success is False:
|
||||
return json.dumps(
|
||||
{
|
||||
"success": False,
|
||||
"message": message or f"更新设置 {spec.key} 失败",
|
||||
},
|
||||
ensure_ascii=False,
|
||||
)
|
||||
changed = success is True
|
||||
else:
|
||||
normalized_value = self._normalize_systemconfig_value(next_value)
|
||||
event_value = normalized_value
|
||||
success = await self._get_system_config().async_set(
|
||||
spec.systemconfig_key,
|
||||
normalized_value,
|
||||
)
|
||||
changed = success is True
|
||||
|
||||
if changed:
|
||||
await eventmanager.async_send_event(
|
||||
etype=EventType.ConfigChanged,
|
||||
data=ConfigChangeEventData(
|
||||
key=spec.key,
|
||||
value=event_value,
|
||||
change_type="update",
|
||||
),
|
||||
)
|
||||
|
||||
saved_value = self._load_setting_value(spec)
|
||||
redact_values = (
|
||||
should_redact_setting(spec, saved_value)
|
||||
or should_redact_setting(spec, current_value)
|
||||
)
|
||||
response_previous_value = (
|
||||
redact_secret_value(
|
||||
current_value,
|
||||
redact_scalar=is_secret_setting_key(spec.key),
|
||||
)
|
||||
if redact_values
|
||||
else current_value
|
||||
)
|
||||
response_saved_value = (
|
||||
redact_secret_value(
|
||||
saved_value,
|
||||
redact_scalar=is_secret_setting_key(spec.key),
|
||||
)
|
||||
if redact_values
|
||||
else saved_value
|
||||
)
|
||||
if not changed and not message:
|
||||
message = "配置值未发生变化"
|
||||
|
||||
return json.dumps(
|
||||
{
|
||||
"success": True,
|
||||
"message": message or f"系统设置 {spec.key} 已更新",
|
||||
"changed": changed,
|
||||
"operation": operation,
|
||||
"setting": {
|
||||
"setting_key": spec.key,
|
||||
"source": spec.source,
|
||||
"group": spec.group,
|
||||
"label": spec.label,
|
||||
},
|
||||
"values_redacted": redact_values,
|
||||
"previous_value": response_previous_value,
|
||||
"saved_value": response_saved_value,
|
||||
},
|
||||
ensure_ascii=False,
|
||||
indent=2,
|
||||
default=str,
|
||||
)
|
||||
except Exception as e:
|
||||
logger.error(f"更新系统设置失败: {e}", exc_info=True)
|
||||
return json.dumps(
|
||||
{"success": False, "message": f"更新系统设置时发生错误: {str(e)}"},
|
||||
ensure_ascii=False,
|
||||
)
|
||||
Reference in New Issue
Block a user