diff --git a/app/agent/policy/registry.py b/app/agent/policy/registry.py index 561932546..830656b05 100644 --- a/app/agent/policy/registry.py +++ b/app/agent/policy/registry.py @@ -60,6 +60,7 @@ BUILTIN_LEGACY_SHADOW_INVENTORY = frozenset( "execute_code", "query_doctor_report", "read_file", + "read_log", "recognize_captcha", "search_web", "send_local_file", diff --git a/app/agent/tools/factory.py b/app/agent/tools/factory.py index a2f3fecb0..84d0c14f1 100644 --- a/app/agent/tools/factory.py +++ b/app/agent/tools/factory.py @@ -30,6 +30,7 @@ from app.agent.tools.impl.knowledge import KnowledgeReadTool, KnowledgeSearchToo from app.agent.tools.impl.persona import PersonaTool from app.agent.tools.impl.query_doctor_report import QueryDoctorReportTool from app.agent.tools.impl.read_file import ReadFileTool +from app.agent.tools.impl.read_log import ReadLogTool from app.agent.tools.impl.recognize_captcha import RecognizeCaptchaTool from app.agent.tools.impl.search_web import SearchWebTool from app.agent.tools.impl.send_local_file import SendLocalFileTool @@ -127,6 +128,7 @@ class MoviePilotToolFactory: ApplyPatchTool, WriteFileTool, ReadFileTool, + ReadLogTool, BrowseWebpageTool, ViewImageTool, QueryDoctorReportTool, diff --git a/app/agent/tools/impl/read_log.py b/app/agent/tools/impl/read_log.py new file mode 100644 index 000000000..965b03fc2 --- /dev/null +++ b/app/agent/tools/impl/read_log.py @@ -0,0 +1,283 @@ +""" +只读日志读取工具。 +""" + +import json +import os +import re +from pathlib import Path +from typing import Any, Optional, Type + +from pydantic import BaseModel, Field + +from app.agent.tools.base import MoviePilotTool +from app.agent.tools.tags import ToolTag +from app.application.security.url import SecurityUtils +from app.runtime.log import logger +from app.runtime.settings import get_runtime_setting + +# 单次最多返回的记录条数与扫描范围,避免把整份日志灌进模型上下文。 +DEFAULT_LOG_TAIL = 200 +MAX_LOG_TAIL = 1000 +MAX_LOG_SCAN_BYTES = 1024 * 1024 +MAX_LOG_RESULT_CHARS = 48 * 1024 +# 日志记录以【LEVEL】开头,后续不带级别前缀的行(如堆栈)归属上一条记录。 +_LOG_RECORD_PATTERN = re.compile(r"^【(?P[A-Z]+)】") +_LOG_LEVEL_ALIASES = {"WARN": "WARNING", "FATAL": "CRITICAL", "CRIT": "CRITICAL"} + + +class ReadLogInput(BaseModel): + """ + 只读日志读取工具的输入参数模型。 + """ + + logfile: str = Field( + ..., + description=( + "相对于日志目录的日志文件名,例如 moviepilot.log、plugins/插件名.log、" + "subscriptions/订阅ID.log;不接受绝对路径" + ), + ) + tail: Optional[int] = Field( + DEFAULT_LOG_TAIL, + description=f"返回最近多少条日志记录,默认 {DEFAULT_LOG_TAIL},最大 {MAX_LOG_TAIL}", + ) + level: Optional[str] = Field( + None, + description="仅保留指定日志级别,多个级别用逗号分隔,例如 ERROR 或 ERROR,WARNING;省略时返回全部级别", + ) + keyword: Optional[str] = Field( + None, + description="仅保留包含该关键字(不区分大小写)的日志记录;省略时不按关键字过滤", + ) + + +class ReadLogTool(MoviePilotTool): + """ + MoviePilot 日志只读读取工具。 + """ + + name: str = Field( + default="read_log", + description="供模型调用的稳定工具名称", + ) + tags: list[str] = Field( + default=[ToolTag.Read, ToolTag.System, ToolTag.Admin], + description="工具的能力和权限分类标签,初始化时会统一归一化", + ) + description: str = Field( + default=( + "以只读方式读取 MoviePilot 主日志、插件日志或订阅日志,按级别和关键字筛选后返回最近的日志记录," + "多行堆栈会随所属记录一并返回。仅允许读取日志目录内的 .log 文件,仅系统管理员可用。" + "本工具不执行修复,也不会修改任何文件。" + ), + description="供模型理解工具用途、输入约束和调用边界的说明", + ) + require_admin: bool = Field( + default=True, + description="是否仅允许系统管理员调用", + ) + args_schema: Type[BaseModel] = Field( + default=ReadLogInput, + description="工具输入参数的验证模型或 JSON Schema", + ) + + def get_tool_message(self, **kwargs: object) -> Optional[str]: + """ + 根据读取参数生成友好的提示消息。 + """ + logfile = str(kwargs.get("logfile") or "日志").strip() or "日志" + return f"读取日志: {Path(logfile).name}" + + @staticmethod + def _normalize_levels(level: Optional[str]) -> tuple[str, ...]: + """ + 归一化级别筛选条件,兼容 WARN 等常见简写。 + + :param level: 用户提供的级别表达式,多个级别用逗号、斜杠或空格分隔 + :return: 去重后的级别名称元组;未提供时为空元组 + """ + if not level or not str(level).strip(): + return () + levels: list[str] = [] + for item in re.split(r"[,/\s]+", str(level).upper()): + if not item: + continue + normalized = _LOG_LEVEL_ALIASES.get(item, item) + if normalized not in levels: + levels.append(normalized) + return tuple(levels) + + @staticmethod + def _normalize_logfile(logfile: str) -> str: + """ + 校验并归一化日志相对路径。 + + :param logfile: 用户提供的日志路径 + :return: 使用正斜杠的日志相对路径 + :raises ValueError: 路径为空、为绝对路径或试图跳出日志目录时抛出 + """ + normalized = str(logfile or "").strip().replace("\\", "/") + if not normalized: + raise ValueError("日志文件名不能为空") + if Path(normalized).is_absolute(): + raise ValueError("请提供相对于日志目录的日志文件名,例如 moviepilot.log 或 plugins/插件名.log") + return normalized + + @staticmethod + def _split_records(lines: list[str]) -> list[tuple[Optional[str], str]]: + """ + 把日志行切分为以级别前缀起始的完整记录。 + + :param lines: 按行切分的日志文本 + :return: 由级别和整条记录文本组成的列表,级别未知时为 None + """ + records: list[list[Any]] = [] + for line in lines: + match = _LOG_RECORD_PATTERN.match(line) + if match or not records: + records.append([match.group("level") if match else None, [line]]) + else: + records[-1][1].append(line) + return [(level, "\n".join(parts)) for level, parts in records] + + @classmethod + def _select_records( + cls, + records: list[tuple[Optional[str], str]], + tail: int, + ) -> tuple[list[tuple[Optional[str], str]], bool]: + """ + 从最新记录向前收集结果,保证总长度不超出输出上限。 + + :param records: 已过滤的日志记录 + :param tail: 需要保留的最大记录条数 + :return: 选中的记录列表和是否发生截断 + """ + candidates = records[-tail:] + selected: list[tuple[Optional[str], str]] = [] + total = 0 + for level, text in reversed(candidates): + cost = len(text) + (1 if selected else 0) + if total + cost > MAX_LOG_RESULT_CHARS: + break + selected.append((level, text)) + total += cost + selected.reverse() + if candidates and not selected: + # 单条记录本身超限时只保留尾部,截断状态同样需要上报。 + level, text = candidates[-1] + return [(level, text[-MAX_LOG_RESULT_CHARS:])], True + return selected, len(selected) < len(candidates) + + @classmethod + def _read_log_records( + cls, + root_path: str, + logfile: str, + tail: int, + levels: tuple[str, ...], + keyword: Optional[str], + ) -> dict[str, Any]: + """ + 在线程池中校验路径并读取日志尾部记录。 + + :param root_path: 允许读取的日志根目录 + :param logfile: 归一化后的日志相对路径 + :param tail: 需要保留的最大记录条数 + :param levels: 需要保留的日志级别 + :param keyword: 需要匹配的关键字 + :return: 结构化读取结果 + :raises FileNotFoundError: 目标不是日志目录内的现存 .log 文件时抛出 + """ + root = Path(root_path) + path = root / logfile + if not SecurityUtils.is_safe_path(base_path=root, user_path=path, allowed_suffixes={".log"}): + raise FileNotFoundError(logfile) + if not path.is_file(): + raise FileNotFoundError(logfile) + + with path.open("rb") as file: + stat = os.fstat(file.fileno()) + scan_start = max(0, stat.st_size - MAX_LOG_SCAN_BYTES) + file.seek(scan_start) + raw = file.read() + + scan_truncated = scan_start > 0 + # 从文件中部开始扫描时丢弃首行残片,避免返回不完整记录。 + if scan_truncated: + raw = raw.partition(b"\n")[2] + + records = cls._split_records(raw.decode("utf-8", errors="replace").splitlines()) + if levels: + records = [item for item in records if item[0] in levels] + needle = str(keyword or "").strip().lower() + if needle: + records = [item for item in records if needle in item[1].lower()] + + selected, result_truncated = cls._select_records(records, tail) + return { + "success": True, + "logfile": logfile, + "levels": list(levels), + "keyword": needle or None, + "tail": tail, + "scanned_bytes": len(raw), + "scan_truncated": scan_truncated, + "matched_records": len(records), + "returned_records": len(selected), + "result_truncated": result_truncated, + "content": "\n".join(text for _, text in selected), + } + + async def run( # type: ignore[override] + self, + logfile: str, + tail: Optional[int] = DEFAULT_LOG_TAIL, + level: Optional[str] = None, + keyword: Optional[str] = None, + **kwargs: object, + ) -> str: + """ + 读取日志尾部记录并返回 JSON 字符串。 + """ + logger.info( + f"执行工具: {self.name}, logfile={logfile}, tail={tail}, level={level}, keyword={keyword}" + ) + try: + normalized = self._normalize_logfile(logfile) + try: + tail_count = int(tail) if tail is not None else DEFAULT_LOG_TAIL + except (TypeError, ValueError): + return self._error_result("tail 必须是大于 0 的整数") + if tail_count < 1: + return self._error_result("tail 必须是大于 0 的整数") + tail_count = min(tail_count, MAX_LOG_TAIL) + + payload = await self.run_blocking( + "default", + self._read_log_records, + str(get_runtime_setting("LOG_PATH")), + normalized, + tail_count, + self._normalize_levels(level), + keyword, + ) + return json.dumps(payload, ensure_ascii=False, indent=2) + except ValueError as err: + return self._error_result(str(err)) + except FileNotFoundError: + return self._error_result(f"未找到日志 {logfile},请确认文件名后重试") + except Exception as err: + logger.error(f"读取日志 {logfile} 失败: {err}", exc_info=True) + return self._error_result(f"读取日志时发生错误: {str(err)}") + + @staticmethod + def _error_result(message: str) -> str: + """ + 生成失败结果 JSON。 + + :param message: 展示给模型的失败原因 + :return: JSON 字符串 + """ + return json.dumps({"success": False, "message": message}, ensure_ascii=False) diff --git a/docs/architecture-overview.md b/docs/architecture-overview.md index 031beb2df..a92e759e3 100644 --- a/docs/architecture-overview.md +++ b/docs/architecture-overview.md @@ -845,13 +845,13 @@ flowchart LR ### 10.2 当前架构快照 -以下是 2026-11-20 核对的 `tests/fixtures/architecture/` 数据;这是源码合同快照, +以下是 2026-11-23 核对的 `tests/fixtures/architecture/` 数据;这是源码合同快照, 不代表某个已发布镜像或正在运行的实例已经验证。 | 指标 | 当前值 | |---|---:| -| Python 模块 | 1198 | -| 内部导入边 | 10,576 | +| Python 模块 | 1199 | +| 内部导入边 | 10,587 | | 非平凡 SCC | 1(29 个模块的 TMDB vendor 精确 containment) | | Application / Chain 具体 Adapter 直连 | 0 / 0 | | Direct egress | 52(精确 policy 准入,Application / Chain 均为 0;本知识 Adapter 仍复用宿主 HTTP 层) | diff --git a/docs/cli.md b/docs/cli.md index be1ab5cf7..733db3d28 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -628,9 +628,11 @@ moviepilot tool run moviepilot_api operation_id=media.search 'query={"title":" - REST 请求失败时显示服务端错误原因并返回非零退出码,不输出整个工具目录响应。 - MoviePilot 业务能力统一通过 `moviepilot_api` 的固定 `operation_id` 调用;不接受任意 URL、method、认证头或 Token,也不兼容旧业务工具名 - 涉及精确媒体身份的 operation 统一使用 `media_source` + `media_id`,两个字段必须成对传递并复用搜索结果 -- `read_skill`、`read_file`、`write_file`、`edit_file` 和 `execute_command` +- `read_skill`、`read_file`、`read_log`、`write_file`、`edit_file` 和 `execute_command` 属于内置 Agent 的本地敏感能力,不通过 MCP/`moviepilot tool` 暴露;插件开发时 由 Agent 按当前用户权限直接调用这些工具。 +- `read_log` 只能读取日志目录内的 `.log` 文件,单次扫描最近 1MB 并按级别、关键字 + 筛选后返回有限条数的记录;该工具不修改任何文件。 - `read_skill` 会一次性返回最多 512 KiB 的 `SKILL.md` 和技能目录内其它文件的完整相对路径列表, 不应用普通工具结果的 64 KiB 全局大小裁剪;超出时会明确标记截断,Agent 不应再用 `read_file` 读取或绕过 `SKILL.md` 限制。 diff --git a/tests/fixtures/architecture/dependency-baseline.json b/tests/fixtures/architecture/dependency-baseline.json index 5e034bb21..5cd40e91c 100644 --- a/tests/fixtures/architecture/dependency-baseline.json +++ b/tests/fixtures/architecture/dependency-baseline.json @@ -978,8 +978,8 @@ "runtime_only": true } }, - "edge_count": 10576, - "edge_sha256": "547154edca338850436a1d46f4917f8588ea2927b28f2cfa48acef4f58b370c4", + "edge_count": 10587, + "edge_sha256": "56f720b09f77ac3ec847c28871320e07ed095adf11df0da815864aa4a2872901", "edges": [ "app -> app.foundation", "app -> app.foundation.environment", @@ -2008,6 +2008,7 @@ "app.agent.tools.factory -> app.agent.tools.impl.persona", "app.agent.tools.factory -> app.agent.tools.impl.query_doctor_report", "app.agent.tools.factory -> app.agent.tools.impl.read_file", + "app.agent.tools.factory -> app.agent.tools.impl.read_log", "app.agent.tools.factory -> app.agent.tools.impl.recognize_captcha", "app.agent.tools.factory -> app.agent.tools.impl.search_web", "app.agent.tools.factory -> app.agent.tools.impl.send_local_file", @@ -2168,6 +2169,16 @@ "app.agent.tools.impl.read_file -> app.agent.tools.tags", "app.agent.tools.impl.read_file -> app.runtime", "app.agent.tools.impl.read_file -> app.runtime.log", + "app.agent.tools.impl.read_log -> app.agent", + "app.agent.tools.impl.read_log -> app.agent.tools", + "app.agent.tools.impl.read_log -> app.agent.tools.base", + "app.agent.tools.impl.read_log -> app.agent.tools.tags", + "app.agent.tools.impl.read_log -> app.application", + "app.agent.tools.impl.read_log -> app.application.security", + "app.agent.tools.impl.read_log -> app.application.security.url", + "app.agent.tools.impl.read_log -> app.runtime", + "app.agent.tools.impl.read_log -> app.runtime.log", + "app.agent.tools.impl.read_log -> app.runtime.settings", "app.agent.tools.impl.recognize_captcha -> app.adapters", "app.agent.tools.impl.recognize_captcha -> app.adapters.external", "app.agent.tools.impl.recognize_captcha -> app.adapters.external.ocr", @@ -11558,7 +11569,7 @@ "app.workflow.actions.transfer_file -> app.workflow", "app.workflow.actions.transfer_file -> app.workflow.actions" ], - "module_count": 1198, + "module_count": 1199, "modules": [ "app", "app.adapters", @@ -11749,6 +11760,7 @@ "app.agent.tools.impl.persona", "app.agent.tools.impl.query_doctor_report", "app.agent.tools.impl.read_file", + "app.agent.tools.impl.read_log", "app.agent.tools.impl.recognize_captcha", "app.agent.tools.impl.search_web", "app.agent.tools.impl.send_local_file", diff --git a/tests/fixtures/architecture/mypy-policy.json b/tests/fixtures/architecture/mypy-policy.json index 5864aa547..539b40840 100644 --- a/tests/fixtures/architecture/mypy-policy.json +++ b/tests/fixtures/architecture/mypy-policy.json @@ -299,6 +299,16 @@ "reason": "async-tool-run" }, { +"path": "app/agent/tools/impl/read_log.py", + "owner": "ReadLogTool.run", + "codes": [ + "override" + ], + "fingerprint": "1a3f5f74c120c3e5e7983e4dfc750377144ea683eac03eaebe22055554150792", + "statement": "async def run(self, logfile: str, tail: Optional[int]=DEFAULT_LOG_TAIL, level: Optional[str]=None, keyword: Optional[str]=None, **kwargs: object) -> str:", + "reason": "async-tool-run" + }, + { "path": "app/agent/tools/impl/search_web.py", "owner": "SearchWebTool.run", "codes": [ diff --git a/tests/test_agent_read_log_tool.py b/tests/test_agent_read_log_tool.py new file mode 100644 index 000000000..d8d573ff5 --- /dev/null +++ b/tests/test_agent_read_log_tool.py @@ -0,0 +1,208 @@ +""" +只读日志读取工具测试。 +""" + +import asyncio +import json +from pathlib import Path + +import pytest + +from app.agent.tools.impl import read_log as read_log_module +from app.agent.tools.impl.read_log import MAX_LOG_RESULT_CHARS, MAX_LOG_TAIL, ReadLogTool + + +def _record(level: str, message: str) -> str: + """ + 生成带级别前缀的日志记录行。 + """ + return f"【{level}】2026-10-30 10:00:00 [abc123] - {message}" + + +def _write_log(root: Path, relative: str, lines: list[str]) -> Path: + """ + 在日志根目录下写入测试日志文件。 + """ + path = root / relative + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text("\n".join(lines) + "\n", encoding="utf-8") + return path + + +@pytest.fixture() +def log_root(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path: + """ + 将只读日志工具指向临时日志目录。 + """ + root = tmp_path / "logs" + root.mkdir() + monkeypatch.setattr(read_log_module, "get_runtime_setting", lambda *_args, **_kwargs: str(root)) + return root + + +def _run(logfile: str, **kwargs: object) -> dict: + """ + 以管理员身份执行日志工具并解析 JSON 结果。 + """ + tool = ReadLogTool(session_id="session-log", user_id="admin") + tool.set_agent_context({"is_admin": True}) + return json.loads(asyncio.run(tool.run(logfile=logfile, **kwargs))) + + +def test_read_log_returns_recent_records(log_root: Path) -> None: + """ + 默认应返回最近日志记录并保留级别信息。 + """ + _write_log(log_root, "moviepilot.log", [ + _record("INFO", "ready"), + _record("ERROR", "boom"), + _record("WARNING", "slow"), + ]) + + payload = _run("moviepilot.log") + + assert payload["success"] is True + assert payload["returned_records"] == 3 + assert "【ERROR】" in payload["content"] + assert "【WARNING】" in payload["content"] + + +def test_read_log_filters_level_and_keyword(log_root: Path) -> None: + """ + 级别与关键字过滤应同时生效,且级别名不区分大小写。 + """ + _write_log(log_root, "moviepilot.log", [ + _record("ERROR", "request timeout"), + _record("ERROR", "disk full"), + _record("INFO", "request timeout"), + ]) + + payload = _run("moviepilot.log", level="error", keyword="TIMEOUT") + + assert payload["success"] is True + assert payload["matched_records"] == 1 + assert "request timeout" in payload["content"] + assert "disk full" not in payload["content"] + + +def test_read_log_keeps_traceback_with_parent_record(log_root: Path) -> None: + """ + 多行堆栈应归属上一条记录,不会在级别过滤时被拆散。 + """ + _write_log(log_root, "moviepilot.log", [ + _record("ERROR", "plugin crashed"), + "Traceback (most recent call last):", + ' File "plugin.py", line 1, in run', + _record("INFO", "recovered"), + ]) + + payload = _run("moviepilot.log", level="ERROR") + + assert payload["returned_records"] == 1 + assert "Traceback (most recent call last)" in payload["content"] + assert "recovered" not in payload["content"] + + +def test_read_log_reads_plugin_log_directory(log_root: Path) -> None: + """ + 插件日志位于日志目录的子目录中,也应能按相对路径读取。 + """ + _write_log(log_root, "plugins/demo.log", [_record("ERROR", "plugin failed")]) + + payload = _run("plugins/demo.log") + + assert payload["success"] is True + assert "plugin failed" in payload["content"] + assert payload["logfile"] == "plugins/demo.log" + + +@pytest.mark.parametrize( + "logfile", + ["", "../outside.log", "moviepilot.txt", "missing.log"], +) +def test_read_log_rejects_invalid_targets(log_root: Path, tmp_path: Path, logfile: str) -> None: + """ + 空路径、越界路径、非 .log 文件和缺失文件都应返回结构化失败。 + """ + (tmp_path / "outside.log").write_text(_record("ERROR", "outside"), encoding="utf-8") + _write_log(log_root, "moviepilot.log", [_record("INFO", "ready")]) + _write_log(log_root, "moviepilot.txt", [_record("INFO", "ready")]) + + payload = _run(logfile) + + assert payload["success"] is False + assert payload["message"] + + +def test_read_log_rejects_absolute_path(log_root: Path) -> None: + """ + 绝对路径即使在日志目录内部也不接受,调用方必须使用相对路径。 + """ + path = _write_log(log_root, "moviepilot.log", [_record("INFO", "ready")]) + + payload = _run(str(path)) + + assert payload["success"] is False + assert "相对" in payload["message"] + + +def test_read_log_rejects_symlink_escape(log_root: Path, tmp_path: Path) -> None: + """ + 指向日志目录外的符号链接不能绕过路径校验。 + """ + outside = tmp_path / "secret.log" + outside.write_text(_record("ERROR", "secret"), encoding="utf-8") + (log_root / "linked.log").symlink_to(outside) + + payload = _run("linked.log") + + assert payload["success"] is False + + +def test_read_log_clamps_tail_and_rejects_non_positive(log_root: Path) -> None: + """ + 超过上限的 tail 会被收敛,非正数则直接拒绝。 + """ + _write_log(log_root, "moviepilot.log", [_record("INFO", f"line {index}") for index in range(3)]) + + invalid = _run("moviepilot.log", tail=0) + clamped = _run("moviepilot.log", tail=MAX_LOG_TAIL * 10) + + assert invalid["success"] is False + assert clamped["success"] is True + assert clamped["tail"] == MAX_LOG_TAIL + + +def test_read_log_truncates_oversized_record(log_root: Path) -> None: + """ + 单条记录超过输出上限时只保留尾部并标记截断。 + """ + _write_log(log_root, "moviepilot.log", [_record("ERROR", "x" * (MAX_LOG_RESULT_CHARS * 2))]) + + payload = _run("moviepilot.log") + + assert payload["success"] is True + assert payload["returned_records"] == 1 + assert payload["result_truncated"] is True + assert len(payload["content"]) == MAX_LOG_RESULT_CHARS + + +def test_read_log_drops_partial_first_line_of_partial_scan(log_root: Path) -> None: + """ + 从文件中段开始扫描时应丢弃首行残片,避免返回不完整记录。 + """ + filler = "f" * 4096 + lines = [_record("INFO", f"{filler} {index}") for index in range(400)] + _write_log(log_root, "moviepilot.log", lines) + + payload = _run("moviepilot.log", tail=1) + + assert payload["scan_truncated"] is True + assert payload["content"].startswith("【INFO】") + + +def test_read_log_requires_admin() -> None: + """ + 日志可能包含敏感信息,工具必须保持管理员可用限制。 + """ + assert ReadLogTool.model_fields["require_admin"].default is True