From 79bd39432505d8b285e7f2863c618602a2cffbf8 Mon Sep 17 00:00:00 2001 From: jxxghp Date: Thu, 19 Nov 2026 17:57:38 +0800 Subject: [PATCH] feat(agent): enable central knowledge through laboratory switch --- app/adapters/external/knowledge.py | 19 +- app/agent/orchestrator.py | 3 +- app/agent/tools/impl/knowledge.py | 6 +- app/application/agent.py | 2 +- app/application/knowledge.py | 40 +-- app/application/settings/contract.py | 4 - .../resources/system_settings_catalog.json | 10 +- app/application/settings/service.py | 6 +- app/runtime/config.py | 1 + app/schemas/knowledge.py | 35 +-- app/schemas/types.py | 2 - app/startup/composition/agent.py | 16 +- app/startup/composition/configuration.py | 2 - app/startup/composition/system.py | 23 +- docs/mcp-api.md | 48 ++-- docs/rules/05-architecture.md | 8 +- tests/test_agent_knowledge_tool.py | 18 +- tests/test_knowledge_client.py | 263 ++++++------------ 18 files changed, 171 insertions(+), 335 deletions(-) diff --git a/app/adapters/external/knowledge.py b/app/adapters/external/knowledge.py index 628d6e7ed..a21cc3777 100644 --- a/app/adapters/external/knowledge.py +++ b/app/adapters/external/knowledge.py @@ -28,7 +28,7 @@ _HTTP_FAILURES: dict[int, KnowledgeFailure] = { class KnowledgeClient: """ - 复用宿主网络层,只向配置中的中心源发送独立读取令牌。 + 复用宿主网络层,只向 MoviePilot Server 发送有界只读请求。 """ def __init__(self, transport: Optional["KnowledgeHttpTransport"] = None) -> None: @@ -43,25 +43,28 @@ class KnowledgeClient: self, config: AgentKnowledgeConfig, request: Union[KnowledgeSearch, KnowledgeRead], ) -> KnowledgeOutcome: """ - 固定路径、校验证书并关闭跳转;缓冲后执行响应字节和协议预算检查。 + 固定路径、校验证书并关闭跳转;不携带 Cookie 或用户身份令牌。 - :param config: 当前显式中心源及该源的独立读取凭据 + :param config: 当前 Server 源和本地工具开关 :param request: 宿主验证的检索或补读请求,不接受任意路径 :return: 不含外部异常详情的结果或受控失败 """ if not config.enabled: return KnowledgeOutcome("disabled") - path = "search" if isinstance(request, KnowledgeSearch) else "read" + path = "agent/search" if isinstance(request, KnowledgeSearch) else "agent/read" + origin = config.origin.rstrip("/") + if not origin: + return KnowledgeOutcome("unavailable") transport = self._transport or AsyncRequestUtils( proxies=get_runtime_setting("PROXY"), http2=False, timeout=QUERY_SECONDS, verify=True, follow_redirects=False, trust_env=False, ) try: response = await transport.post_res( - f"{config.origin}/knowledge/v1/{path}", json=request.model_dump(mode="json"), + f"{origin}/knowledge/v1/{path}", json=request.model_dump(mode="json"), allow_redirects=False, raise_exception=True, - headers={"Authorization": "Bearer " + config.token, "Accept": "application/json", - "Content-Type": "application/json", "Accept-Encoding": "identity"}, + headers={"Accept": "application/json", "Content-Type": "application/json", + "Accept-Encoding": "identity"}, ) except (AsyncHttpRequestError, OSError, ValueError): return KnowledgeOutcome("unavailable") @@ -132,7 +135,7 @@ class KnowledgeHttpTransport(Protocol): :param json: 已验证的协议 DTO :param allow_redirects: 必须为 False :param raise_exception: 必须为 True,不将传输错误伪装成空结果 - :param headers: 含中心独立令牌的单次请求头 + :param headers: 不含 Cookie 或身份令牌的单次请求头 :return: 已缓冲的 HTTP 响应;无响应时为 None """ ... diff --git a/app/agent/orchestrator.py b/app/agent/orchestrator.py index a5adc4fd3..c44703285 100644 --- a/app/agent/orchestrator.py +++ b/app/agent/orchestrator.py @@ -134,7 +134,8 @@ def _private_knowledge_guidance() -> str: "\n" "仅当用户询问 MoviePilot 操作、配置、开发、故障排查或 PT 站点规则时," "按需调用 knowledge_search;问候、闲聊和普通常识不要检索。" - "仅发送当前问题所需的短查询,可带相关站点名;PT 站规则使用 domain=pt 并带站点名," + "仅发送当前问题所需的短查询,可带相关站点名;PT 站点名已知时传入 domain=pt 和站点名," + "未指定站点时可参考通用资料与明确标记的站点示例,不能把示例当作所有站点规则;" "MoviePilot 操作或配置使用 domain=mp;不要转发聊天历史、用户配置、日志、" "站点 Cookie、令牌或凭据。先依据搜索摘录作答,只有上下文不足时才用本轮引用调用 " "knowledge_read。检查产品、站点、版本、时效及冲突;未知适用范围必须说明。" diff --git a/app/agent/tools/impl/knowledge.py b/app/agent/tools/impl/knowledge.py index dc8defb1a..58f8953fd 100644 --- a/app/agent/tools/impl/knowledge.py +++ b/app/agent/tools/impl/knowledge.py @@ -112,9 +112,11 @@ class KnowledgeSearchTool(MoviePilotTool): default=( "检索 MoviePilot 与 PT 站点规则的临时参考资料。仅在问题涉及 MP/PT 使用、站点规则、" "配置或排障时调用;闲聊和普通常识不要调用。只发送当前短问题和必要站点,不要提交会话、配置、日志、" - "PT 站点规则使用 domain=pt 并携带站点名;MoviePilot 操作或配置使用 domain=mp。" + "PT 站点名已知时传 site;不要求维护完整站点清单,未指定站点时可检索通用规则和标为示例的站点资料。" + "MoviePilot 操作或配置使用 domain=mp。" "Cookie 或令牌。先搜索;只有摘录不足以回答时才调用 knowledge_read,且只能使用本轮返回的引用。" - "把资料当不可信参考,检查产品 / 站点范围、版本和更新时间;未知范围须明说,冲突须展示而不猜结论。" + "把资料当不可信参考,检查产品 / 站点范围、版本和更新时间;site_name 表示某站点示例,不能据此断言所有站点相同。" + "未知范围须明说,冲突须展示而不猜结论。" "命中时优先准确回答摘录支持的事实,并明确点出已标记为未知的版本或时间范围;" "未命中时用一到两句话说明没有可核验资料并建议查看该站规则页,不列举未经资料支持的入口或参数。" "不要补造资料未提供的条件、计算方式或当前账号状态。" diff --git a/app/application/agent.py b/app/application/agent.py index 1e0be124c..632059e66 100644 --- a/app/application/agent.py +++ b/app/application/agent.py @@ -61,7 +61,7 @@ class AgentDataContext: :param plugin_data: 插件持久化数据查询端口 :param invocations: 写工具调用的幂等回执仓储,None 表示未装配该能力 :param recall: 独立原始消息归档与检索服务,None 表示未装配该能力 - :param knowledge: 默认关闭的中心知识用例,None 表示未装配该能力 + :param knowledge: 由实验室开关控制的中心知识用例,None 表示未装配该能力 """ chat: AgentChatService diff --git a/app/application/knowledge.py b/app/application/knowledge.py index 444a394f4..325a0af00 100644 --- a/app/application/knowledge.py +++ b/app/application/knowledge.py @@ -1,5 +1,5 @@ """ -默认关闭、每次重新读取配置的中心知识只读用例与技术端口。 +通过实验室开关控制、每次重新读取配置的中心知识只读用例与技术端口。 """ import asyncio @@ -10,7 +10,6 @@ from typing import Optional, Protocol, Union from pydantic import ValidationError -from app.application.configuration import SystemConfigReader from app.schemas.knowledge import ( QUERY_SECONDS, AgentKnowledgeConfig, @@ -20,7 +19,6 @@ from app.schemas.knowledge import ( KnowledgeRead, KnowledgeSearch, ) -from app.schemas.types import SystemConfigKey # 只拦截已知高风险形态,不声称识别任意秘密;工具仍须提炼短问题而非转发会话。 _SENSITIVE_QUERY = re.compile( @@ -42,22 +40,6 @@ def contains_knowledge_secret(value: str, site: Optional[str] = None) -> bool: return bool(_SENSITIVE_QUERY.search(value + "\n" + (site or ""))) -def normalize_knowledge_config(key: object, value: object) -> object: - """ - 在所有配置服务写入路径上规范化中心地址并校验完整令牌绑定。 - - :param key: 系统配置枚举或持久化键名 - :param value: 候选 JSON 设置值 - :return: 非目标设置原样返回;中心配置返回不包含默认字段的规范字典 - """ - if key not in (SystemConfigKey.AIAgentKnowledge, SystemConfigKey.AIAgentKnowledge.value): - return value - if value is None: - return None - config = AgentKnowledgeConfig.model_validate(value) - return config.model_dump(mode="json", exclude_unset=True) - - class KnowledgePort(Protocol): """ 宿主注入的有界只读技术端口,不提供采集、列表或写知识能力。 @@ -69,7 +51,7 @@ class KnowledgePort(Protocol): """ 以当前配置完成一次检索或补读,不缓存正文或回显传输异常。 - :param config: 当前显式绑定的中心源与独立读取凭据 + :param config: 当前 MoviePilot Server 地址与本地工具开关 :param request: 宿主已验证的短查询或短期补读身份 :return: 受控的成功响应或失败状态 """ @@ -78,14 +60,16 @@ class KnowledgePort(Protocol): class KnowledgeService: """ - 管理默认开关、当前配置、宿主版本和单次请求预算,不保留响应正文。 + 管理当前开关、Server 配置、宿主版本和单次请求预算,不保留响应正文。 """ - def __init__(self, config: SystemConfigReader, port: KnowledgePort, version: Callable[[], Optional[str]]) -> None: + def __init__( + self, config: Callable[[], AgentKnowledgeConfig], port: KnowledgePort, version: Callable[[], Optional[str]], + ) -> None: """ 注入快照配置、外部技术端口和宿主版本读取器。 - :param config: 仅从内存快照读取系统配置的端口 + :param config: 由宿主组合根提供的 Server 地址与本地开关快照读取器 :param port: 由组合根提供的只读中心适配器 :param version: 返回宿主当前版本,不能取自模型参数 """ @@ -95,19 +79,19 @@ class KnowledgeService: def current_config(self) -> Optional[AgentKnowledgeConfig]: """ - 每次读取并验证完整配置,旧格式、未配置和停用均失败关闭。 + 每次读取并验证当前 Server 地址和本地开关,损坏配置保持关闭。 :return: 已启用配置;不可用时为 None """ try: - value = AgentKnowledgeConfig.model_validate(self._config.get(SystemConfigKey.AIAgentKnowledge) or {}) + value = AgentKnowledgeConfig.model_validate(self._config()) except (ValueError, TypeError): return None - return value if value.enabled else None + return value if value.enabled and value.origin else None def signature(self) -> str: """ - 给工具目录提供不含地址和凭据原文的变更身份。 + 给工具目录提供不暴露 Server 地址的变更身份。 :return: 当前完整配置摘要;未启用时为 disabled """ @@ -116,7 +100,7 @@ class KnowledgeService: async def _query(self, request: Union[KnowledgeSearch, KnowledgeRead]) -> KnowledgeOutcome: """ - 在请求前后核对配置,停用或换凭据后的迟到正文不再交给调用方。 + 在请求前后核对配置,停用或 Server 地址变化后的迟到正文不再交给调用方。 :param request: 仅包含当前问题及已验证范围的协议输入 :return: 当前配置下的结果;请求中配置变化时丢弃响应 diff --git a/app/application/settings/contract.py b/app/application/settings/contract.py index 7ccd46fda..680c49fd0 100644 --- a/app/application/settings/contract.py +++ b/app/application/settings/contract.py @@ -20,7 +20,6 @@ from app.runtime.config import Settings from app.schemas.agent import AgentMcpServerConfig from app.schemas.category import ClassificationPolicyState from app.schemas.common import JsonData -from app.schemas.knowledge import AgentKnowledgeConfig from app.schemas.plugin import PluginFoldersData from app.schemas.rule import CustomRule, FilterRuleGroup from app.schemas.site import SiteAuth @@ -472,9 +471,6 @@ SYSTEMCONFIG_CONTRACTS: dict[SystemConfigKey, _SystemConfigContract] = { SystemConfigKey.AIAgentConfig: _internal_contract( "ai_agent", Optional[dict[str, JsonData]], sensitive=True ), - SystemConfigKey.AIAgentKnowledge: _contract( - "ai_agent", Optional[AgentKnowledgeConfig], sensitive=True - ), SystemConfigKey.GithubAuth: _internal_contract( "dependencies", Optional[dict[str, JsonData]], sensitive=True ), diff --git a/app/application/settings/resources/system_settings_catalog.json b/app/application/settings/resources/system_settings_catalog.json index db9cd80e9..fd40d3f4d 100644 --- a/app/application/settings/resources/system_settings_catalog.json +++ b/app/application/settings/resources/system_settings_catalog.json @@ -46,6 +46,11 @@ "group": "ai_agent", "source_file": "app/runtime/config.py" }, + "AI_AGENT_KNOWLEDGE_ENABLE": { + "description": "是否允许 Agent 使用 MoviePilot Server 的中心知识工具", + "group": "ai_agent", + "source_file": "app/runtime/config.py" + }, "AI_AGENT_OUTPUT_LANGUAGE": { "description": "内置智能助手输出语言,默认使用简体中文", "group": "ai_agent", @@ -1378,11 +1383,6 @@ "enum_name": "AIAgentConfig", "source_file": "app/schemas/types.py" }, - "AIAgentKnowledge": { - "description": "AI智能体私有中心知识配置;显式绑定 HTTPS 源与独立读取令牌,默认关闭", - "enum_name": "AIAgentKnowledge", - "source_file": "app/schemas/types.py" - }, "AIAgentMcpServers": { "description": "AI智能体外部MCP服务器配置", "enum_name": "AIAgentMcpServers", diff --git a/app/application/settings/service.py b/app/application/settings/service.py index 39f3c9ba6..6953f2ed0 100644 --- a/app/application/settings/service.py +++ b/app/application/settings/service.py @@ -443,8 +443,7 @@ class SystemSettingsService: raise ValueError(f"系统设置项 '{setting_key}' 不存在") value = self._load(spec) sensitive = should_redact_setting(spec, value) - never_reveal = spec.systemconfig_key == SystemConfigKey.AIAgentKnowledge - redacted = sensitive and (never_reveal or not show_secrets) + redacted = sensitive and not show_secrets response_value = ( redact_setting_value(spec, value) if redacted @@ -501,8 +500,7 @@ class SystemSettingsService: for spec in specs: value = self._load(spec) sensitive = should_redact_setting(spec, value) - never_reveal = spec.systemconfig_key == SystemConfigKey.AIAgentKnowledge - redacted = sensitive and (never_reveal or not show_secrets) + redacted = sensitive and not show_secrets response_value = ( redact_setting_value(spec, value) if redacted diff --git a/app/runtime/config.py b/app/runtime/config.py index a88e2228b..0145ab9d3 100644 --- a/app/runtime/config.py +++ b/app/runtime/config.py @@ -754,6 +754,7 @@ class ConfigModel(BaseModel): # AI智能体配置 AI_AGENT_ENABLE: bool = Field(default=False, description='AI智能体开关') + AI_AGENT_KNOWLEDGE_ENABLE: bool = Field(default=True, description='是否允许 Agent 使用 MoviePilot Server 的中心知识工具') AGENT_INTERACTIVE_PRIORITY: bool = Field(default=True, description='为交互式智能助手隔离执行容量,并让新启动的非关键后台服务有限避让') AGENT_BACKGROUND_DEFER_SECONDS: int = Field(default=30, ge=0, description='交互活跃时非关键后台服务最多避让的秒数,0为不避让;不暂停已开始的任务') AGENT_LLM_TIMEOUT: int = Field(default=180, ge=0, description='Agent单次模型请求的总超时秒数,包含供应商重试;0为不限制') diff --git a/app/schemas/knowledge.py b/app/schemas/knowledge.py index 42e6bccf7..eb8fc57db 100644 --- a/app/schemas/knowledge.py +++ b/app/schemas/knowledge.py @@ -2,7 +2,6 @@ 中心知识的受保护配置与有界只读协议,不包含知识落盘或采集能力。 """ -import re from dataclasses import dataclass, field from datetime import datetime from typing import Annotated, Literal, Optional, Union @@ -23,14 +22,13 @@ EvidenceIdentifier = Annotated[str, Field(pattern=r"^ke_[A-Za-z0-9_-]{43}$")] class AgentKnowledgeConfig(BaseModel): """ - 保存显式绑定的中心地址和独立读取凭据;仅允许完整替换。 + 保存宿主当前 Server 地址和实验室工具开关,不包含实例令牌。 """ model_config = ConfigDict(extra="forbid", strict=True, hide_input_in_errors=True) - enabled: bool = Field(default=False, description="是否启用主 Agent 的只读中心知识工具") - origin: str = Field(default="", max_length=512, repr=False, description="读取令牌所属的 HTTPS 源,不含路径或查询") - token: str = Field(default="", repr=False, description="该中心签发的独立 mpk_ 读取令牌;不能填写脱敏占位符") + enabled: bool = Field(default=True, description="是否启用主 Agent 的只读中心知识工具") + origin: str = Field(default="", max_length=512, repr=False, description="MoviePilot Server 的 HTTPS 源,不含路径或查询") @field_validator("origin") @classmethod @@ -38,7 +36,7 @@ class AgentKnowledgeConfig(BaseModel): """ 仅接受明确的 HTTPS 源,阻止凭据、额外路径或控制字符。 - :param value: 管理员提供的中心源地址 + :param value: 来自 MoviePilot Server 连接设置的服务地址 :return: 去除末尾斜线的规范源地址,或停用配置的空值 """ if not value: @@ -53,30 +51,6 @@ class AgentKnowledgeConfig(BaseModel): _ = parsed.port return value.rstrip("/") - @field_validator("token") - @classmethod - def validate_token(cls, value: str) -> str: - """ - 拒绝管理登录凭据、星号回填和换行注入,只接受当前独立令牌格式。 - - :param value: 管理员重新提供的原始读取令牌 - :return: 独立令牌,或用于清除配置的空值 - """ - if value and not re.fullmatch(r"mpk_[A-Za-z0-9_-]{43}", value): - raise ValueError("必须重新提供中心签发的独立知识读取令牌") - return value - - @model_validator(mode="after") - def require_enabled_credentials(self) -> "AgentKnowledgeConfig": - """ - 启用时必须同时明确地址和凭据,不从其他服务配置补全。 - - :return: 完整配置,或有效的停用配置 - """ - if self.enabled and (not self.origin or not self.token): - raise ValueError("启用知识工具前必须配置中心源地址和读取令牌") - return self - class KnowledgeSearch(BaseModel): """ @@ -136,6 +110,7 @@ class KnowledgeEvidence(BaseModel): domain: KnowledgeDomain = Field(description="证据所属领域") product: str = Field(max_length=64, description="证据所属产品") site_id: Optional[str] = Field(max_length=64, description="证据关联的中心站点身份;通用知识为 null") + site_name: Optional[str] = Field(default=None, max_length=120, description="PT 站点级资料对应的示例站点名称") applicable_versions: KnowledgeVersions = Field(description="版本适用性及上下界") fetched_at: Optional[datetime] = Field(description="实际采集时间;未知时为 null") valid_until: Optional[datetime] = Field(description="明确维护的有效期;未知时为 null") diff --git a/app/schemas/types.py b/app/schemas/types.py index cbea7d95a..8b7f153d3 100644 --- a/app/schemas/types.py +++ b/app/schemas/types.py @@ -493,8 +493,6 @@ class SystemConfigKey(Enum): NotificationSendTime = "NotificationSendTime" # AI智能体配置 AIAgentConfig = "AIAgentConfig" - # AI智能体私有中心知识配置;显式绑定 HTTPS 源与独立读取令牌,默认关闭 - AIAgentKnowledge = "AIAgentKnowledge" # GitHub OAuth 设备授权元数据 GithubAuth = "GithubAuth" # AI智能体外部MCP服务器配置 diff --git a/app/startup/composition/agent.py b/app/startup/composition/agent.py index f20bd8173..d8352e5eb 100644 --- a/app/startup/composition/agent.py +++ b/app/startup/composition/agent.py @@ -37,7 +37,9 @@ from app.db.adapters.recall import LegacyRecallRepository from app.db.oper.agentchat import AgentChatOper from app.db.oper.systemconfig import SystemConfigOper from app.db.session import SessionFactory, async_session_scope +from app.runtime.settings import get_runtime_setting from app.runtime.tasks import TaskRegistry +from app.schemas.knowledge import AgentKnowledgeConfig from app.startup.composition.context import ( AgentChatRepositoryFactory, ) @@ -75,6 +77,18 @@ class AgentComposition: execution: AgentTaskExecutionService +def _agent_knowledge_config() -> AgentKnowledgeConfig: + """ + 从宿主实验室开关与既有 Server 地址生成每次检索使用的配置快照。 + + :return: 未配置独立用户凭据的中心知识读取设置 + """ + return AgentKnowledgeConfig( + enabled=get_runtime_setting("AI_AGENT_KNOWLEDGE_ENABLE", True) is True, + origin=get_runtime_setting("MP_SERVER_HOST", "") or "", + ) + + def _history_retention_cutoff() -> float | None: """ 独立 Agent 库复用已配置的清理开关和会话保留期,零天表示不自动删除。 @@ -107,7 +121,7 @@ def compose_agent( from app.adapters.external.knowledge import KnowledgeClient from app.runtime.version import get_app_version - knowledge = KnowledgeService(system_config, KnowledgeClient(), get_app_version) + knowledge = KnowledgeService(_agent_knowledge_config, KnowledgeClient(), get_app_version) persistence = AgentChatPersistenceService( repository=AgentChatOper, diff --git a/app/startup/composition/configuration.py b/app/startup/composition/configuration.py index cd7e3c396..71350aeb4 100644 --- a/app/startup/composition/configuration.py +++ b/app/startup/composition/configuration.py @@ -26,7 +26,6 @@ from app.application.directory import ( DirectoryConfigurationMutationService, normalize_directory_configurations_for_policy, ) -from app.application.knowledge import normalize_knowledge_config from app.application.security.userconfig import ( UserConfigurationService, configure_user_configuration, @@ -90,7 +89,6 @@ async def compose_configuration( repository=system_config, async_executor=executor, directory_mutation=directory_mutation, - value_normalizer=normalize_knowledge_config, ) user_service = UserConfigurationService( repository=user_config, diff --git a/app/startup/composition/system.py b/app/startup/composition/system.py index 6a5476a56..711d23263 100644 --- a/app/startup/composition/system.py +++ b/app/startup/composition/system.py @@ -242,31 +242,12 @@ class _ConfigurationEventAdapter(ConfigurationEventPort): async def publish(self, key: Any, value: Any = None) -> None: """ - 同步失效派生缓存并等待全部配置重载处理器完成;中心知识凭据不随事件广播。 + 同步失效派生缓存并等待全部配置重载处理器完成。 :param key: 已提交设置键或同一事务提交的键集合 :param value: 单键设置的新值;批量变化默认不广播值 """ - single_key = isinstance(key, (str, SystemConfigKey)) - if single_key: - key_items = (key,) - else: - try: - key_items = tuple(key) - except TypeError: - key_items = (key,) - normalized_keys = { - item.value if isinstance(item, SystemConfigKey) else str(item) - for item in key_items - } - event_value = value - if SystemConfigKey.AIAgentKnowledge.value in normalized_keys: - event_value = ( - {"enabled": value.get("enabled") is True} - if single_key and isinstance(value, dict) - else None - ) - payload = ConfigChangeEventData(key=key, value=event_value, change_type="update") + payload = ConfigChangeEventData(key=key, value=value, change_type="update") if payload.key.intersection(_RUST_METAINFO_OPTION_SETTING_KEYS): # 必须在写入入口返回前失效缓存,避免下一次识别读取旧配置。 clear_rust_parse_options_cache() diff --git a/docs/mcp-api.md b/docs/mcp-api.md index bce249e99..7b955431b 100644 --- a/docs/mcp-api.md +++ b/docs/mcp-api.md @@ -677,38 +677,30 @@ Emby、Jellyfin、Plex、Navidrome 的目录、条目、搜索、季集和活动 (如调用时指定),不要依赖空闲回收及时释放资源。宿主关停或启动失败回滚时,TaskRegistry 只停止扫描并等待已投递的关闭,不提前全关活动会话;最终全关仍由模块关闭阶段负责。 -### 4.5 私有知识配置基础 +### 4.5 中心知识工具 -`SystemConfigKey.AIAgentKnowledge` 保存独立知识中心的 `enabled`、`origin`、`token`,默认关闭。 -`origin` 必须是显式 HTTPS 源,不能带路径、查询、片段或 URL 凭据;`token` 使用该源签发的独立 -`mpk_` 读取令牌。该配置不使用 `MP_SERVER_HOST` 回退,也不使用本地 API Key、后台 Cookie 或站点 Cookie。 +Agent 使用既有 `MP_SERVER_HOST` 连接 MoviePilot Server,不需要填写知识中心地址、令牌或站点权限。 +「高级设置 → 实验室」中的 `AI_AGENT_KNOWLEDGE_ENABLE` 总开关默认开启;关闭后主 Agent 不会收到 +`knowledge_search` / `knowledge_read` 工具。Server 侧 `KNOWLEDGE_ENABLED` 决定公共知识检索和采集是否启用; +发布后的知识只读,后台来源凭据不会随检索响应返回。 -管理员通过受保护的系统设置入口整体替换该配置;不支持合并字段。普通查询、Agent 即使使用 -`show_secrets=true`、批量明文查询以及更新回执均只显示脱敏值并保留开关状态;不能将 `***` 当原值保存。 -更换中心时须重新提供该中心的完整配置,不把旧中心令牌带去试探。 -配置持久化沿用系统凭据存储,备份和数据库权限也须按凭据保护。不要在对话中粘贴令牌让模型代填。 - -只读基础每次请求重新验证配置,固定 `/knowledge/v1/search` 与 `/knowledge/v1/read`,校验 TLS、 -不跟随重定向、不自动重放 POST;总预算 3 秒,无跨请求正文缓存。搜索最多 3 条、每条 1600 字符, -补读最多 1 条 4000 字符;中心总正文预算 6000 字符。96 KiB 响应检查发生在宿主 HTTP 层缓冲之后, -不代表传输前的硬内存上限。已知凭据形态在发送查询前拒绝,这不替代提炼短问题和秘密保护。 - -未命中、不适用、冲突与鉴权失败、引用失效、限流、暂不可用分别处理;请求途中配置改变会丢弃迟到结果。 -本阶段只提供默认关闭的配置及协议基础,尚未把知识工具注册到 Agent、MCP 或代码执行环境;工具启用另行验收。 - -### 4.6 主 Agent 私有知识工具 - -启用并正确配置上述绑定后,只有主 Agent 的本地工具目录会出现 knowledge_search / knowledge_read; -默认配置、子代理、HTTP/MCP 管理器、插件目录和执行代码 RPC 均不会获得这两个工具。 -设置开关或地址 / 令牌变化会改变 Agent 图签名,已缓存图不能跨凭据复用。 +Agent 使用固定 `/knowledge/v1/agent/search` 与 `/knowledge/v1/agent/read` 路径,校验 TLS、关闭重定向、 +不自动重放 POST,也不发送站点 Cookie、登录 Cookie、API Key 或用户 UID。单次查询总预算 3 秒、 +搜索最多 3 条且每条最多 1600 字符、补读最多 1 条 4000 字符;总正文预算 6000 字符。96 KiB 响应检查 +发生在宿主 HTTP 层缓冲之后,不代表传输前的硬内存上限。请求途中开关或 Server 地址变化会丢弃迟到结果。 Agent 仅在回答 MoviePilot 使用、配置、开发、故障或 PT 站点规则时检索;问候、闲聊和普通常识不触发。 -检索提交当前问题的短语及可选站点;PT 站规则使用 `domain=pt` 并带站点名,MoviePilot 操作或配置使用 `domain=mp`。不上传对话历史、站点 Cookie、用户配置或运行日志。 -返回内容只在本轮主模型中作为不可信参考,模型须核对产品 / 站点 / 版本、有效期和冲突;未知范围须明确说明。 -命中时优先回答摘录明确支持的事实;如果摘录明确标注版本或采集时间未知,须明确写出这些未知项,例如“适用版本和采集时间均未知”,不能因此略去匹配到的事实,也不能只用“来源不确定”带过。具体站规和 MoviePilot 配置不得补造未检索到的阈值、豁免、计算方式、保证、建议下限或当前实例状态;未命中时用简短说明告知知识集没有该站可核验规则,建议以站点规则页为准,随后停止回答,不扩展未经资料支持的 FAQ、用户面板、豁免、计算方式或其他规则。一般建议须明确标为通用建议,并说明未由该站资料核验;只有本轮可用工具确实支持并已完成查询时,才能承诺或陈述当前状态。人格只改变表达方式,不扩大事实或工具能力边界。 -中心 ke_ 引用只在本轮宿主内存里映射到随机 ref_ 别名,read 请求只接受该别名、当前执行轮最多两次, -中心每次重新核验当前令牌与发布状态。历史 / 摘要 / 恢复不会保留中心引用,跨轮使用提示重新搜索。 -工具返回的回执隐藏来源 URL、内部文档 ID 和凭据;补读结果不得回传新的中心引用。 +只发送当前问题的短语和必要站点,不上传对话历史、Cookie、用户配置或运行日志。PT 查询可包含通用规则与 +带 `site_name` 的站点示例;示例站点不能自动代表目标站点,回答应明确区分资料中的例子和通用规则。 +返回内容只在本轮主模型中作为不可信参考,模型须核对产品、站点、版本、有效期和冲突;未知范围须明确说明。 +未命中时简短告知知识集没有可核验资料;不能补造未检索到的阈值、豁免、计算方式或当前实例状态。 +中心短期引用只在本轮宿主内存里映射到随机 `ref_` 别名;历史、摘要和恢复不会保留引用。 +工具回执隐藏来源 URL、内部文档 ID 和中心引用;补读结果不能签发新的 Agent 可见引用。 + +### 4.6 主 Agent 人格与知识边界 + +人格只调整表达风格,不扩大事实或工具能力边界。默认人格也应保持自然、鲜活;回答中心知识时仍以 +当前检索证据为准,对站点示例、未知版本和资料冲突作出清晰说明。 ## 5. 组合业务调用 diff --git a/docs/rules/05-architecture.md b/docs/rules/05-architecture.md index dc59bda67..92863211f 100644 --- a/docs/rules/05-architecture.md +++ b/docs/rules/05-architecture.md @@ -155,11 +155,13 @@ Entrypoints (app/api, app/command, app/monitor, app/scheduler, app/agent, app/wo temporary content. Summarization inputs and state commands redact it at their producer boundary, while history and recovery remove local references. Evidence never grants tool authority or becomes a cross-turn result cache. -- `app/application/knowledge.py` owns the default-off read-only knowledge use +- `app/application/knowledge.py` owns the locally switchable read-only knowledge use case and technical Port. `app/adapters/external/knowledge.py` implements the protocol through the host HTTP layer; shared configuration and response DTOs - live in `app/schemas/knowledge.py`. Explicit center credentials never fall back - to `MP_SERVER_HOST`, and no response body is cached by this capability. + live in `app/schemas/knowledge.py`. The public read-only endpoint uses the + existing `MP_SERVER_HOST` connection and carries no per-install access token. + Knowledge tools are controlled by `AI_AGENT_KNOWLEDGE_ENABLE` and response + bodies are not cached by this capability. ### DB, Repository, Outbox and Durable Transfer Layer diff --git a/tests/test_agent_knowledge_tool.py b/tests/test_agent_knowledge_tool.py index 0bf5ae589..2e4ee39c5 100644 --- a/tests/test_agent_knowledge_tool.py +++ b/tests/test_agent_knowledge_tool.py @@ -29,7 +29,6 @@ from app.application.knowledge import KnowledgeOutcome, KnowledgeService from app.schemas.knowledge import AgentKnowledgeConfig, KnowledgeEvidence, KnowledgeResponse, KnowledgeVersions ORIGIN = "https://knowledge.example.invalid" -TOKEN = "mpk_" + "t" * 43 CENTER_REFERENCE = "ke_" + "k" * 43 HIDDEN_SOURCE = "https://private.example.invalid/manual?passkey=not-for-agent" SECRET_FRAGMENT = "mpk_" + "z" * 43 @@ -282,7 +281,7 @@ def test_factory_exposes_knowledge_only_when_main_agent_explicitly_requests_it(m monkeypatch.setattr("app.agent.tools.factory._get_plugin_agent_tools", lambda: []) monkeypatch.setattr("app.agent.tools.factory.AgentCapabilityManager.supports_audio_output", lambda: False) service = MagicMock() - service.current_config.return_value = AgentKnowledgeConfig(enabled=True, origin=ORIGIN, token=TOKEN) + service.current_config.return_value = AgentKnowledgeConfig(enabled=True, origin=ORIGIN) data = _tool_data(service) ordinary = MoviePilotToolFactory.create_tools(session_id="ordinary", user_id="user", data=data) @@ -353,7 +352,7 @@ def test_private_knowledge_guidance_does_not_allow_unsupported_site_rule_claims( assert "不得用常识填补未命中的事实" in guidance assert "随后停止回答" in guidance assert "不得再扩展 FAQ" in guidance - assert "PT 站规则使用 domain=pt" in guidance + assert "PT 站点名已知时传 site" in KnowledgeSearchTool.model_fields["description"].default assert "MoviePilot 操作或配置使用 domain=mp" in guidance assert "不可信的参考资料" in guidance @@ -361,11 +360,10 @@ def test_private_knowledge_guidance_does_not_allow_unsupported_site_rule_claims( @pytest.mark.asyncio async def test_agent_graph_signature_changes_when_knowledge_binding_changes(monkeypatch): """ - 中心地址、令牌或开关变化都会使会话内编译图签名失效。 + 中心地址或本地开关变化都会使会话内编译图签名失效。 """ - config = MagicMock() - config.get.return_value = {"enabled": True, "origin": ORIGIN, "token": TOKEN} - knowledge = KnowledgeService(config, MagicMock(), lambda: "v3.2.8") + config = {"enabled": True, "origin": ORIGIN} + knowledge = KnowledgeService(lambda: AgentKnowledgeConfig(**config), MagicMock(), lambda: "v3.2.8") from app.agent.graph import ToolCatalogSnapshot from app.agent.orchestrator import MoviePilotAgent @@ -377,10 +375,10 @@ async def test_agent_graph_signature_changes_when_knowledge_binding_changes(monk monkeypatch.setattr("app.agent.orchestrator.agent_mcp_manager.config_signature", lambda: "mcp-v1") initial = await agent._agent_bundle_signature(False, empty_catalog, empty_catalog) - config.get.return_value = {"enabled": True, "origin": "https://new.example.invalid", "token": "mpk_" + "u" * 43} + config.update(enabled=True, origin="https://new.example.invalid") rotated = await agent._agent_bundle_signature(False, empty_catalog, empty_catalog) - config.get.return_value = {"enabled": False} + config.update(enabled=False) disabled = await agent._agent_bundle_signature(False, empty_catalog, empty_catalog) assert initial != rotated and rotated != disabled and initial != disabled - assert ORIGIN not in repr(initial) and TOKEN not in repr(initial) + assert ORIGIN not in repr(initial) diff --git a/tests/test_knowledge_client.py b/tests/test_knowledge_client.py index bf78a277c..c308d9de6 100644 --- a/tests/test_knowledge_client.py +++ b/tests/test_knowledge_client.py @@ -4,8 +4,6 @@ import asyncio import json -from contextlib import nullcontext -from copy import deepcopy from unittest.mock import AsyncMock, MagicMock import httpx2 @@ -14,16 +12,11 @@ from pydantic import ValidationError from app.adapters.external.knowledge import MAX_RESPONSE_BYTES, KnowledgeClient from app.adapters.network.http import AsyncRequestUtils -from app.application.configuration import SystemConfigWriteResult -from app.application.knowledge import KnowledgeService, normalize_knowledge_config -from app.application.security.secrets import is_secret_setting_key -from app.application.settings.contract import ALL_SETTING_SPECS, validate_setting_value -from app.application.settings.service import SystemSettingsService, redact_setting_value +from app.application.knowledge import KnowledgeService +from app.runtime.config import Settings from app.schemas.knowledge import AgentKnowledgeConfig, KnowledgeOutcome, KnowledgeRead, KnowledgeSearch -from app.schemas.types import SystemConfigKey ORIGIN = "https://knowledge.example.invalid" -TOKEN = "mpk_" + "s" * 43 REFERENCE = "ke_" + "r" * 43 SENTINEL = "本轮合成知识正文,不得输出到默认对象展示" @@ -35,7 +28,7 @@ def _config(**changes): :param changes: 本用例需要替换的配置字段 :return: 可供服务快照读取的合成字典 """ - return {"enabled": True, "origin": ORIGIN, "token": TOKEN, **changes} + return {"enabled": True, "origin": ORIGIN, **changes} def _reply(status="matched"): @@ -48,7 +41,8 @@ def _reply(status="matched"): item = { "document_id": "a" * 32, "revision": 2, "title": "合成配置规则", "excerpt": SENTINEL, "source_label": "合成来源", "collection_label": "合成集合", "source_url": None, - "source_commit": None, "domain": "mp", "product": "moviepilot", "site_id": None, + "source_commit": None, "domain": "pt", "product": "moviepilot", "site_id": None, + "site_name": "合成示例站", "applicable_versions": {"scope": "unknown", "min": None, "max": None}, "fetched_at": "2026-11-19T00:00:00+00:00", "valid_until": None, "freshness": "dated", "stale": None, "kind": "document", "section": "chunk:1", @@ -70,133 +64,69 @@ def _requester(client): """ return AsyncRequestUtils(client=client, http2=False, timeout=3, verify=True, follow_redirects=False, trust_env=False) + + +def test_runtime_setting_declares_lab_default_enabled(): + """ + 运行时设置目录默认允许 Agent 注入知识工具。 + """ + assert Settings.model_fields["AI_AGENT_KNOWLEDGE_ENABLE"].default is True + + +@pytest.mark.asyncio +async def test_runtime_toggle_is_read_each_time_and_disables_service(monkeypatch): + """ + 实验室开关变化立即改变工具目录签名,关闭后不请求 Server。 + """ + from app.startup.composition import agent as composition + + state = {"AI_AGENT_KNOWLEDGE_ENABLE": True, "MP_SERVER_HOST": ORIGIN} + monkeypatch.setattr(composition, "get_runtime_setting", lambda key, default=None: state.get(key, default)) + port = MagicMock(query=AsyncMock(return_value=KnowledgeOutcome("no_match"))) + service = KnowledgeService(composition._agent_knowledge_config, port, lambda: "v3.2.5") + enabled_signature = service.signature() + assert service.current_config() is not None + state["AI_AGENT_KNOWLEDGE_ENABLE"] = False + assert service.signature() == "disabled" + assert await service.search("合成规则") == KnowledgeOutcome("disabled") + port.query.assert_not_awaited() + state["AI_AGENT_KNOWLEDGE_ENABLE"] = True + state["MP_SERVER_HOST"] = "" + assert service.current_config() is None + assert service.signature() != enabled_signature + + @pytest.mark.parametrize("origin", [ "http://knowledge.example.invalid", "https://user:password@knowledge.example.invalid", ORIGIN + "/path", ORIGIN + "?token=x", ORIGIN + "#fragment", ORIGIN + "?", ORIGIN + ":bad", ORIGIN + "\n", "https://knowledge.example.invalid\\@other.invalid", ]) -def test_config_rejects_ambiguous_credential_targets(origin): +def test_config_rejects_ambiguous_server_targets(origin): """ - 凭据不能发给模型自由指定的路径、非 TLS 源或解析含糊的目标。 + Server 地址不能包含路径、凭据、查询或含糊的解析形式。 """ with pytest.raises(ValidationError) as error: AgentKnowledgeConfig.model_validate(_config(origin=origin)) - assert TOKEN not in str(error.value) + assert ORIGIN not in str(error.value) -@pytest.mark.parametrize("changes", [{"token": "***"}, {"token": "Bearer x"}, {"token": TOKEN + "\r\n"}, - {"token": ""}, {"origin": ""}, {"enabled": "true"}, {"extra": "x"}]) -def test_config_is_complete_strict_and_default_off(changes): +@pytest.mark.parametrize("changes", [{"token": "not-accepted"}, {"enabled": "true"}, {"extra": "x"}]) +def test_config_defaults_on_and_has_no_per_instance_credential(changes): """ - 启用需要完整独立凭据,拒绝回填脱敏值及隐式类型转换。 + 默认打开工具开关,但配置结构不接受用户填写服务端地址以外的访问凭据。 """ - assert AgentKnowledgeConfig().enabled is False + assert AgentKnowledgeConfig().enabled is True assert AgentKnowledgeConfig(origin=ORIGIN + "/").origin == ORIGIN with pytest.raises(ValidationError) as error: AgentKnowledgeConfig.model_validate(_config(**changes)) - assert TOKEN not in str(error.value) - - -def test_setting_contract_replaces_and_redacts_the_whole_binding(): - """ - 设置发现保留 Schema,但当前值整体受保护且不允许局部修改中心地址。 - """ - spec = ALL_SETTING_SPECS[SystemConfigKey.AIAgentKnowledge.value] - assert spec.update_operations == ("replace",) - assert spec.sensitive and is_secret_setting_key(spec.key) - parsed = validate_setting_value(spec, _config()) - assert parsed.token == TOKEN and TOKEN not in repr(parsed) and ORIGIN not in repr(parsed) - assert redact_setting_value(spec, _config()) == {"enabled": True, "origin": "***", "token": "***"} - with pytest.raises(ValidationError): - validate_setting_value(spec, {"enabled": True, "origin": ORIGIN, "token": "***"}) - - -@pytest.mark.parametrize("show_secrets", [False, True]) -def test_system_settings_apis_never_reveal_center_binding(show_secrets): - """ - 即使其他设置允许明文读取,Agent 专用中心绑定也只能更新、不能回读。 - """ - system = MagicMock() - system.get.side_effect = lambda key: _config() if key == SystemConfigKey.AIAgentKnowledge else None - runtime_settings = MagicMock() - runtime_settings.get.return_value = None - service = SystemSettingsService(runtime_settings, system, AsyncMock()) - result = service.describe(setting_key="AIAgentKnowledge", show_secrets=show_secrets) - assert result["redacted"] is True - assert result["value"] == {"enabled": True, "origin": "***", "token": "***"} - assert TOKEN not in json.dumps(result) and ORIGIN not in json.dumps(result) - batch_result = service.query(group="ai_agent", include_values=True, show_secrets=True) - batch_value = next(item["value"] for item in batch_result["settings"] - if item["setting_key"] == "AIAgentKnowledge") - assert batch_value == {"enabled": True, "origin": "***", "token": "***"} - assert TOKEN not in json.dumps(batch_result) and ORIGIN not in json.dumps(batch_result) - query_result = service.query(setting_key="AIAgentKnowledge", include_values=True, show_secrets=True) - assert query_result["settings"][0]["value"] == {"enabled": True, "origin": "***", "token": "***"} - - -@pytest.mark.parametrize("key", [SystemConfigKey.AIAgentKnowledge, "AIAgentKnowledge"]) -def test_all_configuration_write_paths_normalize_or_fail_closed(key): - """ - 绕过设置目录的原始配置写入仍执行同一地址和令牌合同。 - """ - assert normalize_knowledge_config(key, _config(origin=ORIGIN + "/")) == _config() - assert normalize_knowledge_config(key, None) is None - assert normalize_knowledge_config(SystemConfigKey.AIAgentConfig, {"token": "ordinary"}) == {"token": "ordinary"} - with pytest.raises(ValidationError) as error: - normalize_knowledge_config(key, _config(token="***")) - assert TOKEN not in str(error.value) - - -@pytest.mark.asyncio -async def test_system_setting_update_validates_normalizes_and_redacts_saved_binding(monkeypatch): - """ - 设置 API 只接受完整中心绑定,系统写端规范化后回执仍不回显秘密。 - """ - import app.application.settings as settings_module - - saved: dict[str, object] = {"enabled": False} - system = MagicMock() - - def get_value(_key): - """ - 读取本用例的隔离配置副本。 - - :param _key: 待读取的合成设置键 - :return: 当前持久化合成值 - """ - return deepcopy(saved) - - async def save_value(key, value): - """ - 模拟 SystemConfigService 对候选值执行的最终规范化写入。 - - :param key: 已登记的系统配置键 - :param value: 已由设置合同验证的完整候选值 - :return: 规范化值和成功写入结果 - """ - normalized = normalize_knowledge_config(key, value) - saved.clear() - saved.update(normalized) - return SystemConfigWriteResult(changed=True, normalized_value=normalized) - - system.get.side_effect = get_value - system.async_set_with_normalized_value = AsyncMock(side_effect=save_value) - publish = AsyncMock() - service = SystemSettingsService(MagicMock(), system, publish) - monkeypatch.setattr(settings_module, "plugin_system_config_mutation", lambda _key: nullcontext()) - result = await service.update(setting_key="AIAgentKnowledge", value=_config(origin=ORIGIN + "/")) - assert saved == _config() - assert result["changed"] is True and result["values_redacted"] is True - assert result["saved_value"] == {"enabled": True, "origin": "***", "token": "***"} - assert TOKEN not in json.dumps(result) and ORIGIN not in json.dumps(result) - publish.assert_awaited_once() + assert "not-accepted" not in str(error.value) @pytest.mark.asyncio @pytest.mark.parametrize("operation", ["search", "read"]) -async def test_real_transport_uses_fixed_origin_independent_auth_and_no_replay(operation): +async def test_real_transport_uses_server_path_without_user_authorization(operation): """ - 真实 AsyncRequestUtils 只向固定 HTTPS 路径发一个 POST,中心引用不在 URL 中。 + 真实 AsyncRequestUtils 只向固定 HTTPS 路径发一个 POST,不携带用户令牌。 """ observed = [] @@ -218,13 +148,13 @@ async def test_real_transport_uses_fixed_origin_independent_auth_and_no_replay(o assert SENTINEL not in repr(result) and REFERENCE not in repr(result) assert len(observed) == 1 request = observed[0] - assert str(request.url) == ORIGIN + "/knowledge/v1/" + operation - assert request.method == "POST" and request.headers["authorization"] == "Bearer " + TOKEN + assert str(request.url) == ORIGIN + "/knowledge/v1/agent/" + operation + assert request.method == "POST" and "authorization" not in request.headers assert "cookie" not in request.headers and "x-api-key" not in request.headers + assert "x-moviepilot-user-uid" not in request.headers assert request.headers["accept-encoding"] == "identity" body = json.loads(request.content) assert "token" not in body and "origin" not in body and body["protocol_version"] == 1 - assert TOKEN.encode() not in request.content @pytest.mark.asyncio @@ -273,7 +203,7 @@ async def test_untrusted_response_must_satisfy_protocol_and_budgets(mutation): """ 协议漂移、状态矛盾、引用损坏和超预算均失败关闭,不静默删减资料。 """ - data = deepcopy(_reply()) + data = json.loads(json.dumps(_reply())) if mutation == "retention": data["retention"] = "persistent" elif mutation == "trust": @@ -330,12 +260,12 @@ async def test_transport_failures_are_sanitized_and_not_retried(kind): """ calls.append(request) error = httpx2.ReadTimeout if kind == "timeout" else httpx2.ConnectError - raise error(TOKEN + SENTINEL, request=request) + raise error(SENTINEL, request=request) async with httpx2.AsyncClient(transport=httpx2.MockTransport(handle)) as http: result = await KnowledgeClient(_requester(http)).query(AgentKnowledgeConfig(**_config()), KnowledgeSearch(query="规则")) assert result == KnowledgeOutcome("unavailable") - assert len(calls) == 1 and TOKEN not in repr(result) and SENTINEL not in repr(result) + assert len(calls) == 1 and SENTINEL not in repr(result) @pytest.mark.asyncio @@ -356,14 +286,13 @@ async def test_read_accepts_only_the_requested_reference_and_one_context(): @pytest.mark.asyncio -@pytest.mark.parametrize("value", [None, {}, {"enabled": False}, _config(token="***"), _config(enabled=False)]) +@pytest.mark.parametrize("value", [None, {}, {"enabled": False, "origin": ORIGIN}, _config(origin="")]) async def test_unconfigured_or_disabled_service_never_calls_transport(value): """ - 默认关闭、脱敏占位或损坏的旧配置都不能触发访问。 + 缺少 Server 地址或关闭本地开关时服务保持关闭。 """ - config, port = MagicMock(), MagicMock(query=AsyncMock()) - config.get.return_value = value - service = KnowledgeService(config, port, lambda: "v3.2.5") + port = MagicMock(query=AsyncMock()) + service = KnowledgeService(lambda: AgentKnowledgeConfig.model_validate(value or {}), port, lambda: "v3.2.5") assert service.signature() == "disabled" assert await service.search("规则") == KnowledgeOutcome("disabled") assert await service.read(REFERENCE) == KnowledgeOutcome("disabled") @@ -377,17 +306,15 @@ async def test_service_sends_only_short_query_host_version_and_fixed_budget(host """ 产品版本只能来自宿主,开发分支不冒充稳定版,条数不是模型参数。 """ - config, port = MagicMock(), MagicMock(query=AsyncMock(return_value=KnowledgeOutcome("no_match"))) - config.get.return_value = _config() - service = KnowledgeService(config, port, lambda: host_version) + port = MagicMock(query=AsyncMock(return_value=KnowledgeOutcome("no_match"))) + service = KnowledgeService(lambda: AgentKnowledgeConfig(**_config()), port, lambda: host_version) result = await service.search(" 合成规则 ", domain="pt", site="合成站", purpose="troubleshooting") assert result.status == "no_match" binding, request = port.query.await_args.args - assert binding.origin == ORIGIN and binding.token == TOKEN + assert binding.origin == ORIGIN and not hasattr(binding, "token") assert request.query == "合成规则" and request.product == "moviepilot" assert request.product_version == wire_version and request.limit == 3 and request.site == "合成站" assert request.domain == "pt" and request.purpose == "troubleshooting" - config.get.assert_called_with(SystemConfigKey.AIAgentKnowledge) @pytest.mark.asyncio @@ -395,9 +322,9 @@ async def test_revocation_during_request_drops_late_evidence_and_changes_signatu """ 请求在途时停用、换地址或换令牌都丢弃迟到正文,下一调用重新读取配置。 """ - config = MagicMock() - for changes in ({"enabled": False}, {"token": "mpk_" + "x" * 43}, {"origin": "https://new.example.invalid"}): - config.get.return_value = _config() + state = _config() + for changes in ({"enabled": False}, {"origin": "https://new.example.invalid"}): + state.update(_config()) async def query(_binding, _request): """ @@ -407,13 +334,13 @@ async def test_revocation_during_request_drops_late_evidence_and_changes_signatu :param _request: 当前短查询 :return: 必须被上层丢弃的合成证据 """ - config.get.return_value = _config(**changes) + state.update(changes) return KnowledgeOutcome("matched", None) port = MagicMock(query=AsyncMock(side_effect=query)) - service = KnowledgeService(config, port, lambda: "3.2.5") + service = KnowledgeService(lambda: AgentKnowledgeConfig(**state), port, lambda: "3.2.5") previous = service.signature() - assert TOKEN not in previous and ORIGIN not in previous + assert ORIGIN not in previous assert await service.search("规则") == KnowledgeOutcome("configuration_changed") assert service.signature() != previous @@ -423,8 +350,7 @@ async def test_service_total_deadline_cancels_port_and_invalid_inputs_never_disp """ 用例总预算包括端口的全部等待,超时取消;无效输入不消耗网络请求。 """ - config = MagicMock() - config.get.return_value = _config() + state = _config() cancelled = asyncio.Event() async def query(_binding, _request): @@ -441,7 +367,7 @@ async def test_service_total_deadline_cancels_port_and_invalid_inputs_never_disp cancelled.set() port = MagicMock(query=AsyncMock(side_effect=query)) - service = KnowledgeService(config, port, lambda: None) + service = KnowledgeService(lambda: AgentKnowledgeConfig(**state), port, lambda: None) assert await service.search("x" * 301) == KnowledgeOutcome("invalid_request") assert await service.search(" ") == KnowledgeOutcome("invalid_request") assert await service.read("../path") == KnowledgeOutcome("invalid_request") @@ -452,67 +378,34 @@ async def test_service_total_deadline_cancels_port_and_invalid_inputs_never_disp @pytest.mark.asyncio -async def test_configuration_change_event_never_broadcasts_center_credentials(monkeypatch): - """ - 系统配置事件只通知启用状态,不把中心地址和令牌送入插件监听器。 - """ - from app.startup.composition import system as composition - - observed = [] - - async def capture(**kwargs): - """ - 保存合成事件供断言,不发出真实广播。 - - :param kwargs: EventManager 的类型和数据参数 - :return: 已完成的空结果 - """ - observed.append(kwargs) - - monkeypatch.setattr(composition.eventmanager, "async_send_event_strict", capture) - await composition._ConfigurationEventAdapter().publish(SystemConfigKey.AIAgentKnowledge, _config()) - payload = observed[0]["data"] - assert payload.value == {"enabled": True} - assert TOKEN not in repr(payload) and ORIGIN not in repr(payload) - observed.clear() - await composition._ConfigurationEventAdapter().publish( - {SystemConfigKey.AIAgentKnowledge.value: None}.keys(), _config() - ) - payload = observed[0]["data"] - assert payload.value is None - assert TOKEN not in repr(payload) and ORIGIN not in repr(payload) - - -@pytest.mark.asyncio -@pytest.mark.parametrize("secret", [TOKEN, REFERENCE, "Cookie: uid=123; pass=secret", "Authorization: Bearer abc", +@pytest.mark.parametrize("secret", ["mpk_" + "s" * 43, REFERENCE, "Cookie: uid=123; pass=secret", "Authorization: Bearer abc", "https://site.invalid/?passkey=syntheticsecret", "sk-" + "z" * 24]) async def test_known_credential_shapes_are_rejected_before_transport(secret): """ 已知凭据形态在实例侧拒绝,不能依赖中心收到后再过滤。 """ - config, port = MagicMock(), MagicMock(query=AsyncMock()) - config.get.return_value = _config() - service = KnowledgeService(config, port, lambda: "3.2.5") + port = MagicMock(query=AsyncMock()) + service = KnowledgeService(lambda: AgentKnowledgeConfig(**_config()), port, lambda: "3.2.5") assert await service.search(secret) == KnowledgeOutcome("invalid_request") assert await service.search("规则", site=secret) == KnowledgeOutcome("invalid_request") port.query.assert_not_awaited() @pytest.mark.asyncio -async def test_search_and_read_do_not_reuse_cached_evidence_or_prior_credential(): +async def test_search_and_read_do_not_reuse_cached_evidence_or_old_server_address(): """ - 连续检索与补读都访问当前端口,令牌轮换后不复用旧授权或正文。 + 连续检索与补读都访问当前端口,Server 地址变化后不复用旧配置或正文。 """ - config, port = MagicMock(), MagicMock(query=AsyncMock(return_value=KnowledgeOutcome("no_match"))) - config.get.return_value = _config() - service = KnowledgeService(config, port, lambda: "3.2.5") + state = _config() + port = MagicMock(query=AsyncMock(return_value=KnowledgeOutcome("no_match"))) + service = KnowledgeService(lambda: AgentKnowledgeConfig(**state), port, lambda: "3.2.5") await service.search("规则") await service.search("规则") - config.get.return_value = _config(token="mpk_" + "x" * 43) + state["origin"] = "https://new.example.invalid" await service.read(REFERENCE) assert port.query.await_count == 3 binding, request = port.query.await_args.args - assert binding.token == "mpk_" + "x" * 43 and request.evidence_id == REFERENCE + assert binding.origin == state["origin"] and request.evidence_id == REFERENCE @pytest.mark.asyncio