mirror of
https://github.com/jxxghp/MoviePilot.git
synced 2026-12-01 16:36:28 +08:00
feat(agent): prepare central knowledge client
This commit is contained in:
138
app/adapters/external/knowledge.py
vendored
Normal file
138
app/adapters/external/knowledge.py
vendored
Normal file
@@ -0,0 +1,138 @@
|
||||
"""
|
||||
中心知识协议的只读 HTTPS 适配器,不缓存、不重放、不回显中心错误正文。
|
||||
"""
|
||||
|
||||
from collections.abc import Mapping
|
||||
from typing import Any, Literal, Optional, Protocol, Union
|
||||
|
||||
from pydantic import ValidationError
|
||||
|
||||
from app.adapters.network.http import AsyncHttpRequestError, AsyncRequestUtils
|
||||
from app.runtime.settings import get_runtime_setting
|
||||
from app.schemas.knowledge import (
|
||||
QUERY_SECONDS,
|
||||
AgentKnowledgeConfig,
|
||||
KnowledgeFailure,
|
||||
KnowledgeOutcome,
|
||||
KnowledgeRead,
|
||||
KnowledgeResponse,
|
||||
KnowledgeSearch,
|
||||
)
|
||||
|
||||
MAX_RESPONSE_BYTES = 96 * 1024
|
||||
_HTTP_FAILURES: dict[int, KnowledgeFailure] = {
|
||||
401: "unauthorized", 403: "forbidden", 410: "reference_expired", 413: "invalid_request",
|
||||
415: "invalid_request", 422: "invalid_request", 429: "rate_limited", 503: "unavailable",
|
||||
}
|
||||
|
||||
|
||||
class KnowledgeClient:
|
||||
"""
|
||||
复用宿主网络层,只向配置中的中心源发送独立读取令牌。
|
||||
"""
|
||||
|
||||
def __init__(self, transport: Optional["KnowledgeHttpTransport"] = None) -> None:
|
||||
"""
|
||||
允许测试通过宿主 HTTP 抽象注入合成响应,生产固定创建宿主网络层请求器。
|
||||
|
||||
:param transport: 可选的宿主 HTTP 请求器;其生命周期由注入方管理
|
||||
"""
|
||||
self._transport = transport
|
||||
|
||||
async def query(
|
||||
self, config: AgentKnowledgeConfig, request: Union[KnowledgeSearch, KnowledgeRead],
|
||||
) -> KnowledgeOutcome:
|
||||
"""
|
||||
固定路径、校验证书并关闭跳转;缓冲后执行响应字节和协议预算检查。
|
||||
|
||||
:param config: 当前显式中心源及该源的独立读取凭据
|
||||
:param request: 宿主验证的检索或补读请求,不接受任意路径
|
||||
:return: 不含外部异常详情的结果或受控失败
|
||||
"""
|
||||
if not config.enabled:
|
||||
return KnowledgeOutcome("disabled")
|
||||
path = "search" if isinstance(request, KnowledgeSearch) else "read"
|
||||
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"),
|
||||
allow_redirects=False, raise_exception=True,
|
||||
headers={"Authorization": "Bearer " + config.token, "Accept": "application/json",
|
||||
"Content-Type": "application/json", "Accept-Encoding": "identity"},
|
||||
)
|
||||
except (AsyncHttpRequestError, OSError, ValueError):
|
||||
return KnowledgeOutcome("unavailable")
|
||||
if response is None:
|
||||
return KnowledgeOutcome("unavailable")
|
||||
try:
|
||||
if len(response.content) > MAX_RESPONSE_BYTES:
|
||||
return KnowledgeOutcome("invalid_response")
|
||||
if response.status_code != 200:
|
||||
return KnowledgeOutcome(_HTTP_FAILURES.get(response.status_code, "unavailable"))
|
||||
if response.headers.get("content-type", "").split(";", 1)[0].lower() != "application/json":
|
||||
return KnowledgeOutcome("invalid_response")
|
||||
try:
|
||||
result = KnowledgeResponse.model_validate_json(response.content)
|
||||
except ValidationError:
|
||||
return KnowledgeOutcome("invalid_response")
|
||||
if isinstance(request, KnowledgeSearch):
|
||||
if len(result.evidence) > request.limit or any(len(item.excerpt) > 1600 for item in result.evidence):
|
||||
return KnowledgeOutcome("invalid_response")
|
||||
if any(item.product not in ("", request.product)
|
||||
or (request.domain and item.domain != request.domain) for item in result.evidence):
|
||||
return KnowledgeOutcome("invalid_response")
|
||||
elif len(result.evidence) > 1 or any(item.evidence_id != request.evidence_id for item in result.evidence):
|
||||
return KnowledgeOutcome("invalid_response")
|
||||
return KnowledgeOutcome(result.status, result)
|
||||
finally:
|
||||
await response.aclose()
|
||||
|
||||
|
||||
class KnowledgeHttpResponse(Protocol):
|
||||
"""
|
||||
只暴露协议校验所需的有限 HTTP 响应字段。
|
||||
|
||||
:ivar status_code: HTTP 状态码
|
||||
:ivar headers: 响应头的只读映射
|
||||
:ivar content: HTTP 层缓冲后的响应字节
|
||||
"""
|
||||
|
||||
status_code: int
|
||||
headers: Mapping[str, str]
|
||||
content: bytes
|
||||
|
||||
async def aclose(self) -> None:
|
||||
"""
|
||||
关闭响应资源。
|
||||
"""
|
||||
...
|
||||
|
||||
|
||||
class KnowledgeHttpTransport(Protocol):
|
||||
"""
|
||||
由宿主网络层实现的单次异步 POST 请求器。
|
||||
"""
|
||||
|
||||
async def post_res(
|
||||
self,
|
||||
url: str,
|
||||
*,
|
||||
json: dict[str, Any],
|
||||
allow_redirects: bool,
|
||||
raise_exception: Literal[True],
|
||||
headers: dict[str, str],
|
||||
) -> Optional[KnowledgeHttpResponse]:
|
||||
"""
|
||||
发送一次指定 HTTPS POST 并返回可关闭响应。
|
||||
|
||||
:param url: Adapter 固定构造的中心协议路径
|
||||
:param json: 已验证的协议 DTO
|
||||
:param allow_redirects: 必须为 False
|
||||
:param raise_exception: 必须为 True,不将传输错误伪装成空结果
|
||||
:param headers: 含中心独立令牌的单次请求头
|
||||
:return: 已缓冲的 HTTP 响应;无响应时为 None
|
||||
"""
|
||||
...
|
||||
160
app/application/knowledge.py
Normal file
160
app/application/knowledge.py
Normal file
@@ -0,0 +1,160 @@
|
||||
"""
|
||||
默认关闭、每次重新读取配置的中心知识只读用例与技术端口。
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import hashlib
|
||||
import re
|
||||
from collections.abc import Callable
|
||||
from typing import Optional, Protocol, Union
|
||||
|
||||
from pydantic import ValidationError
|
||||
|
||||
from app.application.configuration import SystemConfigReader
|
||||
from app.schemas.knowledge import (
|
||||
QUERY_SECONDS,
|
||||
AgentKnowledgeConfig,
|
||||
KnowledgeDomain,
|
||||
KnowledgeOutcome,
|
||||
KnowledgePurpose,
|
||||
KnowledgeRead,
|
||||
KnowledgeSearch,
|
||||
)
|
||||
from app.schemas.types import SystemConfigKey
|
||||
|
||||
# 只拦截已知高风险形态,不声称识别任意秘密;工具仍须提炼短问题而非转发会话。
|
||||
_SENSITIVE_QUERY = re.compile(
|
||||
r"mpk_[A-Za-z0-9_-]{43}|ke_[A-Za-z0-9_-]{43}|(?:sk-|ghp_)[A-Za-z0-9_-]{20,}|"
|
||||
r"-----BEGIN (?:RSA |EC |OPENSSH )?PRIVATE KEY-----|"
|
||||
r"(?i:cookie\s*:\s*\S+|authorization\s*:\s*\S+|"
|
||||
r"(?:passkey|password|api_key|access_token|token)[\"']?\s*[:=]\s*[\"']?[A-Za-z0-9_%+/-]{8,})"
|
||||
)
|
||||
|
||||
|
||||
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):
|
||||
"""
|
||||
宿主注入的有界只读技术端口,不提供采集、列表或写知识能力。
|
||||
"""
|
||||
|
||||
async def query(
|
||||
self, config: AgentKnowledgeConfig, request: Union[KnowledgeSearch, KnowledgeRead],
|
||||
) -> KnowledgeOutcome:
|
||||
"""
|
||||
以当前配置完成一次检索或补读,不缓存正文或回显传输异常。
|
||||
|
||||
:param config: 当前显式绑定的中心源与独立读取凭据
|
||||
:param request: 宿主已验证的短查询或短期补读身份
|
||||
:return: 受控的成功响应或失败状态
|
||||
"""
|
||||
...
|
||||
|
||||
|
||||
class KnowledgeService:
|
||||
"""
|
||||
管理默认开关、当前配置、宿主版本和单次请求预算,不保留响应正文。
|
||||
"""
|
||||
|
||||
def __init__(self, config: SystemConfigReader, port: KnowledgePort, version: Callable[[], Optional[str]]) -> None:
|
||||
"""
|
||||
注入快照配置、外部技术端口和宿主版本读取器。
|
||||
|
||||
:param config: 仅从内存快照读取系统配置的端口
|
||||
:param port: 由组合根提供的只读中心适配器
|
||||
:param version: 返回宿主当前版本,不能取自模型参数
|
||||
"""
|
||||
self._config = config
|
||||
self._port = port
|
||||
self._version = version
|
||||
|
||||
def current_config(self) -> Optional[AgentKnowledgeConfig]:
|
||||
"""
|
||||
每次读取并验证完整配置,旧格式、未配置和停用均失败关闭。
|
||||
|
||||
:return: 已启用配置;不可用时为 None
|
||||
"""
|
||||
try:
|
||||
value = AgentKnowledgeConfig.model_validate(self._config.get(SystemConfigKey.AIAgentKnowledge) or {})
|
||||
except (ValueError, TypeError):
|
||||
return None
|
||||
return value if value.enabled else None
|
||||
|
||||
def signature(self) -> str:
|
||||
"""
|
||||
给工具目录提供不含地址和凭据原文的变更身份。
|
||||
|
||||
:return: 当前完整配置摘要;未启用时为 disabled
|
||||
"""
|
||||
config = self.current_config()
|
||||
return hashlib.sha256(config.model_dump_json().encode()).hexdigest() if config else "disabled"
|
||||
|
||||
async def _query(self, request: Union[KnowledgeSearch, KnowledgeRead]) -> KnowledgeOutcome:
|
||||
"""
|
||||
在请求前后核对配置,停用或换凭据后的迟到正文不再交给调用方。
|
||||
|
||||
:param request: 仅包含当前问题及已验证范围的协议输入
|
||||
:return: 当前配置下的结果;请求中配置变化时丢弃响应
|
||||
"""
|
||||
config = self.current_config()
|
||||
if config is None:
|
||||
return KnowledgeOutcome("disabled")
|
||||
try:
|
||||
async with asyncio.timeout(QUERY_SECONDS):
|
||||
result = await self._port.query(config, request)
|
||||
except TimeoutError:
|
||||
result = KnowledgeOutcome("timeout")
|
||||
if config != self.current_config():
|
||||
return KnowledgeOutcome("configuration_changed")
|
||||
return result
|
||||
|
||||
async def search(
|
||||
self, query: str, *, domain: Optional[KnowledgeDomain] = None,
|
||||
site: Optional[str] = None, purpose: KnowledgePurpose = "usage",
|
||||
) -> KnowledgeOutcome:
|
||||
"""
|
||||
只发送当前短问题,以宿主确定的产品、稳定版本和条数检索。
|
||||
|
||||
:param query: 当前问题提取的短检索词,不是整段会话
|
||||
:param domain: MP 或 PT 领域过滤
|
||||
:param site: 可选站点范围,不替代中心授权
|
||||
:param purpose: 本轮查询用途
|
||||
:return: 有限证据或明确失败状态
|
||||
"""
|
||||
if _SENSITIVE_QUERY.search(query + "\n" + (site or "")):
|
||||
return KnowledgeOutcome("invalid_request")
|
||||
version = self._version()
|
||||
stable = re.fullmatch(r"v?(\d+\.\d+\.\d+)", version or "")
|
||||
try:
|
||||
request = KnowledgeSearch(query=query.strip(), domain=domain, site=site, purpose=purpose,
|
||||
product_version=stable.group(1) if stable else None, limit=3)
|
||||
except ValidationError:
|
||||
return KnowledgeOutcome("invalid_request")
|
||||
return await self._query(request)
|
||||
|
||||
async def read(self, evidence_id: str) -> KnowledgeOutcome:
|
||||
"""
|
||||
每次补读重新使用当前凭据,中心再次检查授权与发布状态。
|
||||
|
||||
:param evidence_id: 由本轮宿主管理的中心短期引用
|
||||
:return: 有限上下文或受控失败状态
|
||||
"""
|
||||
try:
|
||||
request = KnowledgeRead(evidence_id=evidence_id)
|
||||
except ValidationError:
|
||||
return KnowledgeOutcome("invalid_request")
|
||||
return await self._query(request)
|
||||
@@ -37,6 +37,8 @@ _SECRET_SETTING_NAMES = frozenset(
|
||||
"cookiecloud_key",
|
||||
# 自动推送接入是内部凭据状态,默认查询应整体脱敏,不能只根据嵌套字段名判断。
|
||||
"app_push_credentials",
|
||||
# 中心知识的源地址与独立令牌整体受保护,Agent 不能通过设置读取凭据。
|
||||
"ai_agent_knowledge",
|
||||
}
|
||||
)
|
||||
_SECRET_SETTING_ENDINGS = ("_encrypt_key",)
|
||||
|
||||
@@ -20,6 +20,7 @@ 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
|
||||
@@ -471,6 +472,9 @@ 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
|
||||
),
|
||||
|
||||
@@ -1378,6 +1378,11 @@
|
||||
"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",
|
||||
|
||||
@@ -443,7 +443,8 @@ class SystemSettingsService:
|
||||
raise ValueError(f"系统设置项 '{setting_key}' 不存在")
|
||||
value = self._load(spec)
|
||||
sensitive = should_redact_setting(spec, value)
|
||||
redacted = sensitive and not show_secrets
|
||||
never_reveal = spec.systemconfig_key == SystemConfigKey.AIAgentKnowledge
|
||||
redacted = sensitive and (never_reveal or not show_secrets)
|
||||
response_value = (
|
||||
redact_setting_value(spec, value)
|
||||
if redacted
|
||||
@@ -500,7 +501,8 @@ class SystemSettingsService:
|
||||
for spec in specs:
|
||||
value = self._load(spec)
|
||||
sensitive = should_redact_setting(spec, value)
|
||||
redacted = sensitive and not show_secrets
|
||||
never_reveal = spec.systemconfig_key == SystemConfigKey.AIAgentKnowledge
|
||||
redacted = sensitive and (never_reveal or not show_secrets)
|
||||
response_value = (
|
||||
redact_setting_value(spec, value)
|
||||
if redacted
|
||||
|
||||
190
app/schemas/knowledge.py
Normal file
190
app/schemas/knowledge.py
Normal file
@@ -0,0 +1,190 @@
|
||||
"""
|
||||
中心知识的受保护配置与有界只读协议,不包含知识落盘或采集能力。
|
||||
"""
|
||||
|
||||
import re
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import datetime
|
||||
from typing import Annotated, Literal, Optional, Union
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator
|
||||
|
||||
KnowledgeDomain = Literal["mp", "pt"]
|
||||
KnowledgePurpose = Literal["usage", "troubleshooting", "development"]
|
||||
KnowledgeStatus = Literal["matched", "no_match", "not_applicable", "conflicting"]
|
||||
KnowledgeFailure = Literal[
|
||||
"disabled", "configuration_changed", "unauthorized", "forbidden", "reference_expired",
|
||||
"rate_limited", "unavailable", "invalid_request", "invalid_response", "timeout",
|
||||
]
|
||||
QUERY_SECONDS = 3.0
|
||||
EvidenceIdentifier = Annotated[str, Field(pattern=r"^ke_[A-Za-z0-9_-]{43}$")]
|
||||
|
||||
|
||||
class AgentKnowledgeConfig(BaseModel):
|
||||
"""
|
||||
保存显式绑定的中心地址和独立读取凭据;仅允许完整替换。
|
||||
"""
|
||||
|
||||
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_ 读取令牌;不能填写脱敏占位符")
|
||||
|
||||
@field_validator("origin")
|
||||
@classmethod
|
||||
def validate_origin(cls, value: str) -> str:
|
||||
"""
|
||||
仅接受明确的 HTTPS 源,阻止凭据、额外路径或控制字符。
|
||||
|
||||
:param value: 管理员提供的中心源地址
|
||||
:return: 去除末尾斜线的规范源地址,或停用配置的空值
|
||||
"""
|
||||
if not value:
|
||||
return value
|
||||
parsed = urlsplit(value)
|
||||
if (any(char.isspace() or ord(char) < 32 for char in value)
|
||||
or parsed.scheme != "https" or not parsed.hostname or parsed.username is not None
|
||||
or parsed.password is not None or parsed.path not in ("", "/")
|
||||
or parsed.query or parsed.fragment or "?" in value or "#" in value or "\\" in value):
|
||||
raise ValueError("知识中心地址必须为不含凭据、路径或查询的 HTTPS 源")
|
||||
# 显式检查非法端口;请求层不负责修复配置。
|
||||
_ = 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):
|
||||
"""
|
||||
由宿主补齐产品与版本的短查询,条数和路径不属于模型输入。
|
||||
"""
|
||||
|
||||
model_config = ConfigDict(extra="forbid", strict=True, hide_input_in_errors=True)
|
||||
|
||||
protocol_version: Literal[1] = Field(default=1, description="中心知识只读协议版本")
|
||||
query: str = Field(min_length=1, max_length=300, description="当前问题的简短检索词,不含历史正文或凭据")
|
||||
product: Literal["moviepilot"] = Field(default="moviepilot", description="宿主确定的产品标识")
|
||||
product_version: Optional[str] = Field(default=None, max_length=32, description="宿主确定的稳定版本;未知或开发版为 null")
|
||||
domain: Optional[KnowledgeDomain] = Field(default=None, description="MP 或 PT 知识领域;未指定则均可")
|
||||
site: Optional[str] = Field(default=None, min_length=1, max_length=253, description="站点名或别名;授权仍由中心核验")
|
||||
purpose: KnowledgePurpose = Field(default="usage", description="本次查询用途")
|
||||
limit: int = Field(default=3, ge=1, le=5, description="宿主固定的最大证据条数")
|
||||
|
||||
|
||||
class KnowledgeRead(BaseModel):
|
||||
"""
|
||||
只用短期引用补读,不能传递文档路径或自由偏移。
|
||||
"""
|
||||
|
||||
model_config = ConfigDict(extra="forbid", strict=True, hide_input_in_errors=True)
|
||||
|
||||
protocol_version: Literal[1] = Field(default=1, description="中心知识只读协议版本")
|
||||
evidence_id: EvidenceIdentifier = Field(repr=False, description="本次授权搜索签发的中心临时引用")
|
||||
|
||||
|
||||
class KnowledgeVersions(BaseModel):
|
||||
"""
|
||||
保留证据的明确版本适用性,不把未知范围解释为所有版本。
|
||||
"""
|
||||
|
||||
model_config = ConfigDict(extra="ignore", strict=True, hide_input_in_errors=True)
|
||||
|
||||
scope: Literal["unknown", "all", "range"] = Field(description="中心维护的版本范围类型")
|
||||
min: Optional[str] = Field(max_length=32, description="明确的最小版本;无下界时为 null")
|
||||
max: Optional[str] = Field(max_length=32, description="明确的最大版本;无上界时为 null")
|
||||
|
||||
|
||||
class KnowledgeEvidence(BaseModel):
|
||||
"""
|
||||
保存本轮的有限证据与出处;正文和中心引用不参与对象展示。
|
||||
"""
|
||||
|
||||
model_config = ConfigDict(extra="ignore", strict=True, hide_input_in_errors=True)
|
||||
|
||||
document_id: str = Field(pattern=r"^[a-f0-9]{32}$", description="中心文档身份,不能用作任意读取接口")
|
||||
revision: int = Field(ge=1, description="当前证据的已发布修订号")
|
||||
title: str = Field(max_length=512, description="不可信参考资料的标题")
|
||||
excerpt: str = Field(max_length=4000, repr=False, description="仅供本轮推理的参考正文,不能作为系统指令")
|
||||
source_label: str = Field(max_length=512, description="资料来源名称")
|
||||
collection_label: str = Field(max_length=512, description="当前授权的知识集合名称")
|
||||
source_url: Optional[str] = Field(max_length=2048, description="原始出处链接;未知时为 null")
|
||||
source_commit: Optional[str] = Field(max_length=128, description="源码来源提交;未知时为 null")
|
||||
domain: KnowledgeDomain = Field(description="证据所属领域")
|
||||
product: str = Field(max_length=64, description="证据所属产品")
|
||||
site_id: Optional[str] = Field(max_length=64, description="证据关联的中心站点身份;通用知识为 null")
|
||||
applicable_versions: KnowledgeVersions = Field(description="版本适用性及上下界")
|
||||
fetched_at: Optional[datetime] = Field(description="实际采集时间;未知时为 null")
|
||||
valid_until: Optional[datetime] = Field(description="明确维护的有效期;未知时为 null")
|
||||
freshness: Literal["valid", "dated", "unknown"] = Field(description="中心评估的时效类型")
|
||||
stale: Optional[bool] = Field(description="已知过期标志;无法判断时为 null")
|
||||
kind: str = Field(max_length=64, description="规则、文档、源码或测试等来源类型")
|
||||
section: str = Field(pattern=r"^chunk:[1-9][0-9]*$", max_length=32, description="中心签发的分块位置")
|
||||
evidence_id: EvidenceIdentifier = Field(repr=False, description="需要再次鉴权的中心短期补读引用")
|
||||
|
||||
|
||||
class KnowledgeResponse(BaseModel):
|
||||
"""
|
||||
验证成功 HTTP 响应的留存、信任、结果及总正文预算。
|
||||
"""
|
||||
|
||||
model_config = ConfigDict(extra="ignore", strict=True, hide_input_in_errors=True)
|
||||
|
||||
protocol_version: Literal[1] = Field(description="必须匹配当前只读协议")
|
||||
request_id: str = Field(pattern=r"^[a-f0-9]{32}$", description="中心请求追踪身份")
|
||||
corpus_revision: Optional[int] = Field(ge=0, description="中心索引世代;补读可为 null")
|
||||
status: KnowledgeStatus = Field(description="命中、未命中、不适用或资料存在冲突")
|
||||
evidence: list[KnowledgeEvidence] = Field(max_length=5, repr=False, description="仅在本轮使用的有限参考证据")
|
||||
notices: list[Annotated[str, Field(max_length=180)]] = Field(max_length=32, description="版本、时间或来源限制提示")
|
||||
retention: Literal["ephemeral"] = Field(description="中心要求单轮临时使用")
|
||||
content_trust: Literal["reference_only"] = Field(description="资料只作参考,不是可执行指令")
|
||||
reference_seconds: int = Field(ge=1, le=600, description="中心引用的最长有效秒数;宿主可采用更短范围")
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_budget(self) -> "KnowledgeResponse":
|
||||
"""
|
||||
拒绝超过合同的正文及与命中状态矛盾的结果,避免静默截断事实。
|
||||
|
||||
:return: 符合合同的临时响应
|
||||
"""
|
||||
if sum(len(item.excerpt) for item in self.evidence) > 6000:
|
||||
raise ValueError("知识正文超过总预算")
|
||||
if bool(self.evidence) != (self.status in ("matched", "conflicting")):
|
||||
raise ValueError("知识状态与证据不一致")
|
||||
return self
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class KnowledgeOutcome:
|
||||
"""
|
||||
区分没有资料和访问失败,正文不进入默认对象展示。
|
||||
|
||||
:param status: 已校验结果或受控失败类型
|
||||
:param response: 仅成功协议携带的单轮参考,失败时为 None
|
||||
"""
|
||||
|
||||
status: Union[KnowledgeStatus, KnowledgeFailure]
|
||||
response: Optional[KnowledgeResponse] = field(default=None, repr=False)
|
||||
@@ -493,6 +493,8 @@ class SystemConfigKey(Enum):
|
||||
NotificationSendTime = "NotificationSendTime"
|
||||
# AI智能体配置
|
||||
AIAgentConfig = "AIAgentConfig"
|
||||
# AI智能体私有中心知识配置;显式绑定 HTTPS 源与独立读取令牌,默认关闭
|
||||
AIAgentKnowledge = "AIAgentKnowledge"
|
||||
# GitHub OAuth 设备授权元数据
|
||||
GithubAuth = "GithubAuth"
|
||||
# AI智能体外部MCP服务器配置
|
||||
|
||||
@@ -26,6 +26,7 @@ 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,
|
||||
@@ -89,6 +90,7 @@ 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,
|
||||
|
||||
@@ -242,9 +242,23 @@ class _ConfigurationEventAdapter(ConfigurationEventPort):
|
||||
|
||||
async def publish(self, key: Any, value: Any = None) -> None:
|
||||
"""
|
||||
同步失效派生缓存并等待全部配置重载处理器完成。
|
||||
同步失效派生缓存并等待全部配置重载处理器完成;中心知识凭据不随事件广播。
|
||||
"""
|
||||
payload = ConfigChangeEventData(key=key, value=value, change_type="update")
|
||||
if isinstance(key, (str, SystemConfigKey)):
|
||||
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 isinstance(value, dict) else None
|
||||
payload = ConfigChangeEventData(key=key, value=event_value, change_type="update")
|
||||
if payload.key.intersection(_RUST_METAINFO_OPTION_SETTING_KEYS):
|
||||
# 必须在写入入口返回前失效缓存,避免下一次识别读取旧配置。
|
||||
clear_rust_parse_options_cache()
|
||||
|
||||
@@ -850,11 +850,11 @@ flowchart LR
|
||||
|
||||
| 指标 | 当前值 |
|
||||
|---|---:|
|
||||
| Python 模块 | 1181 |
|
||||
| 内部导入边 | 10,349 |
|
||||
| Python 模块 | 1184 |
|
||||
| 内部导入边 | 10,363 |
|
||||
| 非平凡 SCC | 1(29 个模块的 TMDB vendor 精确 containment) |
|
||||
| Application / Chain 具体 Adapter 直连 | 0 / 0 |
|
||||
| Direct egress | 51(精确 policy 准入,Application / Chain 均为 0) |
|
||||
| Direct egress | 52(精确 policy 准入,Application / Chain 均为 0;本知识 Adapter 仍复用宿主 HTTP 层) |
|
||||
| Module Contract V2 spec | 237(其中 223 个方法进入 `run_module` 观察面) |
|
||||
| Event Contract | 53 |
|
||||
| Event producer / consumer | 76(74 静态、2 动态)/ 19(18 静态、1 动态) |
|
||||
|
||||
@@ -677,6 +677,25 @@ Emby、Jellyfin、Plex、Navidrome 的目录、条目、搜索、季集和活动
|
||||
(如调用时指定),不要依赖空闲回收及时释放资源。宿主关停或启动失败回滚时,TaskRegistry
|
||||
只停止扫描并等待已投递的关闭,不提前全关活动会话;最终全关仍由模块关闭阶段负责。
|
||||
|
||||
### 4.5 私有知识配置基础
|
||||
|
||||
`SystemConfigKey.AIAgentKnowledge` 保存独立知识中心的 `enabled`、`origin`、`token`,默认关闭。
|
||||
`origin` 必须是显式 HTTPS 源,不能带路径、查询、片段或 URL 凭据;`token` 使用该源签发的独立
|
||||
`mpk_` 读取令牌。该配置不使用 `MP_SERVER_HOST` 回退,也不使用本地 API Key、后台 Cookie 或站点 Cookie。
|
||||
|
||||
管理员通过受保护的系统设置入口整体替换该配置;不支持合并字段。普通查询、Agent 即使使用
|
||||
`show_secrets=true`、批量明文查询以及更新回执均只显示脱敏值并保留开关状态;不能将 `***` 当原值保存。
|
||||
更换中心时须重新提供该中心的完整配置,不把旧中心令牌带去试探。
|
||||
配置持久化沿用系统凭据存储,备份和数据库权限也须按凭据保护。不要在对话中粘贴令牌让模型代填。
|
||||
|
||||
只读基础每次请求重新验证配置,固定 `/knowledge/v1/search` 与 `/knowledge/v1/read`,校验 TLS、
|
||||
不跟随重定向、不自动重放 POST;总预算 3 秒,无跨请求正文缓存。搜索最多 3 条、每条 1600 字符,
|
||||
补读最多 1 条 4000 字符;中心总正文预算 6000 字符。96 KiB 响应检查发生在宿主 HTTP 层缓冲之后,
|
||||
不代表传输前的硬内存上限。已知凭据形态在发送查询前拒绝,这不替代提炼短问题和秘密保护。
|
||||
|
||||
未命中、不适用、冲突与鉴权失败、引用失效、限流、暂不可用分别处理;请求途中配置改变会丢弃迟到结果。
|
||||
本阶段只提供默认关闭的配置及协议基础,尚未把知识工具注册到 Agent、MCP 或代码执行环境;工具启用另行验收。
|
||||
|
||||
## 5. 组合业务调用
|
||||
|
||||
以下是调用顺序指引。具体参数仍按各 operation 的 Schema 构造,不将顺序中的操作全部默认执行。
|
||||
|
||||
@@ -155,6 +155,11 @@ 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
|
||||
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.
|
||||
|
||||
### DB, Repository, Outbox and Durable Transfer Layer
|
||||
|
||||
|
||||
@@ -977,8 +977,8 @@
|
||||
"runtime_only": true
|
||||
}
|
||||
},
|
||||
"edge_count": 10349,
|
||||
"edge_sha256": "7849aa388d0e5e592fe253f9bbbc9ef1a4f9457e0e2f9c3376f6072d4b853ce8",
|
||||
"edge_count": 10363,
|
||||
"edge_sha256": "36f0ff4e5d499e4870c1635e0305cbf7defda5e4414f6dbc38e656f477c12ea6",
|
||||
"edges": [
|
||||
"app -> app.foundation",
|
||||
"app -> app.foundation.environment",
|
||||
@@ -1017,6 +1017,13 @@
|
||||
"app.adapters.external.github -> app.foundation.url",
|
||||
"app.adapters.external.github -> app.runtime",
|
||||
"app.adapters.external.github -> app.runtime.settings",
|
||||
"app.adapters.external.knowledge -> app.adapters",
|
||||
"app.adapters.external.knowledge -> app.adapters.network",
|
||||
"app.adapters.external.knowledge -> app.adapters.network.http",
|
||||
"app.adapters.external.knowledge -> app.runtime",
|
||||
"app.adapters.external.knowledge -> app.runtime.settings",
|
||||
"app.adapters.external.knowledge -> app.schemas",
|
||||
"app.adapters.external.knowledge -> app.schemas.knowledge",
|
||||
"app.adapters.external.location -> app.adapters",
|
||||
"app.adapters.external.location -> app.adapters.network",
|
||||
"app.adapters.external.location -> app.adapters.network.http",
|
||||
@@ -3926,6 +3933,11 @@
|
||||
"app.application.image -> app.runtime",
|
||||
"app.application.image -> app.runtime.cache",
|
||||
"app.application.image -> app.runtime.log",
|
||||
"app.application.knowledge -> app.application",
|
||||
"app.application.knowledge -> app.application.configuration",
|
||||
"app.application.knowledge -> app.schemas",
|
||||
"app.application.knowledge -> app.schemas.knowledge",
|
||||
"app.application.knowledge -> app.schemas.types",
|
||||
"app.application.maintenance -> app.application",
|
||||
"app.application.maintenance -> app.application.configuration",
|
||||
"app.application.maintenance -> app.runtime",
|
||||
@@ -4379,6 +4391,7 @@
|
||||
"app.application.settings.contract -> app.schemas.agent",
|
||||
"app.application.settings.contract -> app.schemas.category",
|
||||
"app.application.settings.contract -> app.schemas.common",
|
||||
"app.application.settings.contract -> app.schemas.knowledge",
|
||||
"app.application.settings.contract -> app.schemas.plugin",
|
||||
"app.application.settings.contract -> app.schemas.rule",
|
||||
"app.application.settings.contract -> app.schemas.site",
|
||||
@@ -10446,6 +10459,7 @@
|
||||
"app.startup.composition.configuration -> app.application.configuration",
|
||||
"app.startup.composition.configuration -> app.application.database",
|
||||
"app.startup.composition.configuration -> app.application.directory",
|
||||
"app.startup.composition.configuration -> app.application.knowledge",
|
||||
"app.startup.composition.configuration -> app.application.security",
|
||||
"app.startup.composition.configuration -> app.application.security.userconfig",
|
||||
"app.startup.composition.configuration -> app.db",
|
||||
@@ -11330,7 +11344,7 @@
|
||||
"app.workflow.actions.transfer_file -> app.workflow",
|
||||
"app.workflow.actions.transfer_file -> app.workflow.actions"
|
||||
],
|
||||
"module_count": 1181,
|
||||
"module_count": 1184,
|
||||
"modules": [
|
||||
"app",
|
||||
"app.adapters",
|
||||
@@ -11340,6 +11354,7 @@
|
||||
"app.adapters.external",
|
||||
"app.adapters.external.cookiecloud",
|
||||
"app.adapters.external.github",
|
||||
"app.adapters.external.knowledge",
|
||||
"app.adapters.external.location",
|
||||
"app.adapters.external.mapping",
|
||||
"app.adapters.external.market",
|
||||
@@ -11653,6 +11668,7 @@
|
||||
"app.application.history.retry",
|
||||
"app.application.image",
|
||||
"app.application.invocation",
|
||||
"app.application.knowledge",
|
||||
"app.application.maintenance",
|
||||
"app.application.mediaserver",
|
||||
"app.application.messaging",
|
||||
@@ -12389,6 +12405,7 @@
|
||||
"app.schemas.github",
|
||||
"app.schemas.history",
|
||||
"app.schemas.initialization",
|
||||
"app.schemas.knowledge",
|
||||
"app.schemas.llm",
|
||||
"app.schemas.mapping",
|
||||
"app.schemas.mcp",
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
"repeat": 3,
|
||||
"targets": {
|
||||
"app.startup.lifecycle": {
|
||||
"loaded_app_module_count": 613,
|
||||
"loaded_app_module_count": 615,
|
||||
"max_ms": 1293.338,
|
||||
"median_ms": 1156.239,
|
||||
"min_ms": 1102.806,
|
||||
@@ -17,7 +17,7 @@
|
||||
]
|
||||
},
|
||||
"app.factory": {
|
||||
"loaded_app_module_count": 627,
|
||||
"loaded_app_module_count": 629,
|
||||
"max_ms": 1127.911,
|
||||
"median_ms": 1122.382,
|
||||
"min_ms": 1119.221,
|
||||
@@ -28,7 +28,7 @@
|
||||
]
|
||||
},
|
||||
"app.main": {
|
||||
"loaded_app_module_count": 629,
|
||||
"loaded_app_module_count": 631,
|
||||
"max_ms": 1188.652,
|
||||
"median_ms": 1183.509,
|
||||
"min_ms": 1174.522,
|
||||
|
||||
528
tests/test_knowledge_client.py
Normal file
528
tests/test_knowledge_client.py
Normal file
@@ -0,0 +1,528 @@
|
||||
"""
|
||||
使用真实宿主 HTTP 适配链和合成传输验证知识协议、默认关闭及配置变化。
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
from contextlib import nullcontext
|
||||
from copy import deepcopy
|
||||
from unittest.mock import AsyncMock, MagicMock
|
||||
|
||||
import httpx2
|
||||
import pytest
|
||||
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.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 = "本轮合成知识正文,不得输出到默认对象展示"
|
||||
|
||||
|
||||
def _config(**changes):
|
||||
"""
|
||||
构造不对应任何真实中心或用户的完整配置。
|
||||
|
||||
:param changes: 本用例需要替换的配置字段
|
||||
:return: 可供服务快照读取的合成字典
|
||||
"""
|
||||
return {"enabled": True, "origin": ORIGIN, "token": TOKEN, **changes}
|
||||
|
||||
|
||||
def _reply(status="matched"):
|
||||
"""
|
||||
对照当前中心实际协议构造完整证据,资料全部为合成值。
|
||||
|
||||
:param status: 需要验证的中心结果状态
|
||||
:return: JSON 可序列化的中心响应
|
||||
"""
|
||||
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,
|
||||
"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",
|
||||
"evidence_id": REFERENCE,
|
||||
}
|
||||
return {
|
||||
"protocol_version": 1, "request_id": "b" * 32, "corpus_revision": 1, "status": status,
|
||||
"evidence": [item] if status in ("matched", "conflicting") else [], "notices": ["applicability_unknown"],
|
||||
"retention": "ephemeral", "content_trust": "reference_only", "reference_seconds": 600,
|
||||
}
|
||||
|
||||
|
||||
def _requester(client):
|
||||
"""
|
||||
装配生产使用的网络层配置到仅服务于本用例的 MockTransport 客户端。
|
||||
|
||||
:param client: 由测试管理的合成传输客户端
|
||||
:return: 不跟随跳转、验证 TLS 且禁用环境代理继承的宿主请求器
|
||||
"""
|
||||
return AsyncRequestUtils(client=client, http2=False, timeout=3, verify=True,
|
||||
follow_redirects=False, trust_env=False)
|
||||
@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):
|
||||
"""
|
||||
凭据不能发给模型自由指定的路径、非 TLS 源或解析含糊的目标。
|
||||
"""
|
||||
with pytest.raises(ValidationError) as error:
|
||||
AgentKnowledgeConfig.model_validate(_config(origin=origin))
|
||||
assert TOKEN 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):
|
||||
"""
|
||||
启用需要完整独立凭据,拒绝回填脱敏值及隐式类型转换。
|
||||
"""
|
||||
assert AgentKnowledgeConfig().enabled is False
|
||||
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()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("operation", ["search", "read"])
|
||||
async def test_real_transport_uses_fixed_origin_independent_auth_and_no_replay(operation):
|
||||
"""
|
||||
真实 AsyncRequestUtils 只向固定 HTTPS 路径发一个 POST,中心引用不在 URL 中。
|
||||
"""
|
||||
observed = []
|
||||
|
||||
def handle(request):
|
||||
"""
|
||||
记录实际进入 MockTransport 的请求,不访问网络。
|
||||
|
||||
:param request: 网络层构造的实际 HTTP 请求
|
||||
:return: 合成中心返回
|
||||
"""
|
||||
observed.append(request)
|
||||
return httpx2.Response(200, json=_reply())
|
||||
|
||||
async with httpx2.AsyncClient(transport=httpx2.MockTransport(handle)) as http:
|
||||
client = KnowledgeClient(_requester(http))
|
||||
payload = KnowledgeSearch(query="合成规则") if operation == "search" else KnowledgeRead(evidence_id=REFERENCE)
|
||||
result = await client.query(AgentKnowledgeConfig(**_config()), payload)
|
||||
assert result.status == "matched" and result.response.evidence[0].excerpt == SENTINEL
|
||||
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 "cookie" not in request.headers and "x-api-key" 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
|
||||
@pytest.mark.parametrize(("code", "status"), [
|
||||
(401, "unauthorized"), (403, "forbidden"), (410, "reference_expired"), (413, "invalid_request"),
|
||||
(415, "invalid_request"), (422, "invalid_request"), (429, "rate_limited"), (503, "unavailable"),
|
||||
(500, "unavailable"), (302, "unavailable"), (307, "unavailable"),
|
||||
])
|
||||
async def test_failures_do_not_become_no_match_or_follow_redirects(code, status):
|
||||
"""
|
||||
外部错误正文和跳转目标不会被执行或作为没查到知识返回。
|
||||
"""
|
||||
observed = []
|
||||
|
||||
def handle(request):
|
||||
"""
|
||||
返回错误或跨源跳转并记录调用数。
|
||||
|
||||
:param request: 实际请求
|
||||
:return: 带不可信错误正文的 HTTP 响应
|
||||
"""
|
||||
observed.append(request)
|
||||
return httpx2.Response(code, text=SENTINEL, headers={"Location": "https://other.invalid/path"})
|
||||
|
||||
async with httpx2.AsyncClient(transport=httpx2.MockTransport(handle), follow_redirects=True) as http:
|
||||
result = await KnowledgeClient(_requester(http)).query(AgentKnowledgeConfig(**_config()), KnowledgeSearch(query="规则"))
|
||||
assert result == KnowledgeOutcome(status) and SENTINEL not in repr(result)
|
||||
assert len(observed) == 1
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("status", ["matched", "no_match", "not_applicable", "conflicting"])
|
||||
async def test_protocol_preserves_authoritative_result_states(status):
|
||||
"""
|
||||
中心命中、不适用和冲突保持原义,未来附加字段不破坏当前投影。
|
||||
"""
|
||||
data = {**_reply(status), "future_optional_field": True}
|
||||
async with httpx2.AsyncClient(transport=httpx2.MockTransport(lambda _request: httpx2.Response(200, json=data))) as http:
|
||||
result = await KnowledgeClient(_requester(http)).query(AgentKnowledgeConfig(**_config()), KnowledgeSearch(query="规则"))
|
||||
assert result.status == status and result.response.notices == ["applicability_unknown"]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("mutation", ["retention", "trust", "protocol", "schema", "status", "snippet", "count", "total", "reference"])
|
||||
async def test_untrusted_response_must_satisfy_protocol_and_budgets(mutation):
|
||||
"""
|
||||
协议漂移、状态矛盾、引用损坏和超预算均失败关闭,不静默删减资料。
|
||||
"""
|
||||
data = deepcopy(_reply())
|
||||
if mutation == "retention":
|
||||
data["retention"] = "persistent"
|
||||
elif mutation == "trust":
|
||||
data["content_trust"] = "instructions"
|
||||
elif mutation == "protocol":
|
||||
data["protocol_version"] = 2
|
||||
elif mutation == "schema":
|
||||
data["evidence"][0]["revision"] = True
|
||||
elif mutation == "status":
|
||||
data["status"] = "no_match"
|
||||
elif mutation == "snippet":
|
||||
data["evidence"][0]["excerpt"] = "长" * 1601
|
||||
elif mutation == "count":
|
||||
data["evidence"] *= 4
|
||||
elif mutation == "total":
|
||||
data["evidence"][0]["excerpt"] = "长" * 3100
|
||||
data["evidence"] *= 2
|
||||
else:
|
||||
data["evidence"][0]["evidence_id"] = "invalid"
|
||||
async with httpx2.AsyncClient(transport=httpx2.MockTransport(lambda _request: httpx2.Response(200, json=data))) as http:
|
||||
result = await KnowledgeClient(_requester(http)).query(AgentKnowledgeConfig(**_config()), KnowledgeSearch(query="规则"))
|
||||
assert result == KnowledgeOutcome("invalid_response")
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("response", [
|
||||
httpx2.Response(200, content=b"not json", headers={"Content-Type": "application/json"}),
|
||||
httpx2.Response(200, json=_reply(), headers={"Content-Type": "text/html"}),
|
||||
httpx2.Response(200, content=b"x" * (MAX_RESPONSE_BYTES + 1), headers={"Content-Type": "application/json"}),
|
||||
])
|
||||
async def test_invalid_encoding_type_or_buffered_size_is_rejected(response):
|
||||
"""
|
||||
完成缓冲后仍检查类型、JSON 和字节上限,不把 HTML 登录页当资料。
|
||||
"""
|
||||
async with httpx2.AsyncClient(transport=httpx2.MockTransport(lambda _request: response)) as http:
|
||||
result = await KnowledgeClient(_requester(http)).query(AgentKnowledgeConfig(**_config()), KnowledgeSearch(query="规则"))
|
||||
assert result == KnowledgeOutcome("invalid_response") and response.is_closed
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("kind", ["connect", "timeout"])
|
||||
async def test_transport_failures_are_sanitized_and_not_retried(kind):
|
||||
"""
|
||||
传输异常不回显可能含凭据的异常文本,POST 失败也不自动重放。
|
||||
"""
|
||||
calls = []
|
||||
|
||||
def handle(request):
|
||||
"""
|
||||
模拟带私有哨兵的网络错误。
|
||||
|
||||
:param request: 当前固定目标的请求
|
||||
:return: 始终抛出合成网络错误
|
||||
"""
|
||||
calls.append(request)
|
||||
error = httpx2.ReadTimeout if kind == "timeout" else httpx2.ConnectError
|
||||
raise error(TOKEN + 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)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_read_accepts_only_the_requested_reference_and_one_context():
|
||||
"""
|
||||
补读不能借中心错误返回另一引用或多个全文窗口。
|
||||
"""
|
||||
data = _reply()
|
||||
data["evidence"][0]["evidence_id"] = "ke_" + "x" * 43
|
||||
async with httpx2.AsyncClient(transport=httpx2.MockTransport(lambda _request: httpx2.Response(200, json=data))) as http:
|
||||
result = await KnowledgeClient(_requester(http)).query(AgentKnowledgeConfig(**_config()), KnowledgeRead(evidence_id=REFERENCE))
|
||||
assert result.status == "invalid_response"
|
||||
data = _reply()
|
||||
data["evidence"] *= 2
|
||||
async with httpx2.AsyncClient(transport=httpx2.MockTransport(lambda _request: httpx2.Response(200, json=data))) as http:
|
||||
result = await KnowledgeClient(_requester(http)).query(AgentKnowledgeConfig(**_config()), KnowledgeRead(evidence_id=REFERENCE))
|
||||
assert result.status == "invalid_response"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("value", [None, {}, {"enabled": False}, _config(token="***"), _config(enabled=False)])
|
||||
async def test_unconfigured_or_disabled_service_never_calls_transport(value):
|
||||
"""
|
||||
默认关闭、脱敏占位或损坏的旧配置都不能触发访问。
|
||||
"""
|
||||
config, port = MagicMock(), MagicMock(query=AsyncMock())
|
||||
config.get.return_value = value
|
||||
service = KnowledgeService(config, port, lambda: "v3.2.5")
|
||||
assert service.signature() == "disabled"
|
||||
assert await service.search("规则") == KnowledgeOutcome("disabled")
|
||||
assert await service.read(REFERENCE) == KnowledgeOutcome("disabled")
|
||||
port.query.assert_not_awaited()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize(("host_version", "wire_version"), [("v3.2.5", "3.2.5"), ("3.2.5", "3.2.5"),
|
||||
("v3", None), ("3.2.5-dev", None), (None, None)])
|
||||
async def test_service_sends_only_short_query_host_version_and_fixed_budget(host_version, wire_version):
|
||||
"""
|
||||
产品版本只能来自宿主,开发分支不冒充稳定版,条数不是模型参数。
|
||||
"""
|
||||
config, port = MagicMock(), MagicMock(query=AsyncMock(return_value=KnowledgeOutcome("no_match")))
|
||||
config.get.return_value = _config()
|
||||
service = KnowledgeService(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 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
|
||||
async def test_revocation_during_request_drops_late_evidence_and_changes_signature():
|
||||
"""
|
||||
请求在途时停用、换地址或换令牌都丢弃迟到正文,下一调用重新读取配置。
|
||||
"""
|
||||
config = MagicMock()
|
||||
for changes in ({"enabled": False}, {"token": "mpk_" + "x" * 43}, {"origin": "https://new.example.invalid"}):
|
||||
config.get.return_value = _config()
|
||||
|
||||
async def query(_binding, _request):
|
||||
"""
|
||||
在返回前模拟一次管理员配置变更。
|
||||
|
||||
:param _binding: 请求开始时的完整配置
|
||||
:param _request: 当前短查询
|
||||
:return: 必须被上层丢弃的合成证据
|
||||
"""
|
||||
config.get.return_value = _config(**changes)
|
||||
return KnowledgeOutcome("matched", None)
|
||||
|
||||
port = MagicMock(query=AsyncMock(side_effect=query))
|
||||
service = KnowledgeService(config, port, lambda: "3.2.5")
|
||||
previous = service.signature()
|
||||
assert TOKEN not in previous and ORIGIN not in previous
|
||||
assert await service.search("规则") == KnowledgeOutcome("configuration_changed")
|
||||
assert service.signature() != previous
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_service_total_deadline_cancels_port_and_invalid_inputs_never_dispatch(monkeypatch):
|
||||
"""
|
||||
用例总预算包括端口的全部等待,超时取消;无效输入不消耗网络请求。
|
||||
"""
|
||||
config = MagicMock()
|
||||
config.get.return_value = _config()
|
||||
cancelled = asyncio.Event()
|
||||
|
||||
async def query(_binding, _request):
|
||||
"""
|
||||
模拟能响应取消的无限外部等待。
|
||||
|
||||
:param _binding: 本轮配置
|
||||
:param _request: 本次协议请求
|
||||
:return: 不会正常返回
|
||||
"""
|
||||
try:
|
||||
await asyncio.Event().wait()
|
||||
finally:
|
||||
cancelled.set()
|
||||
|
||||
port = MagicMock(query=AsyncMock(side_effect=query))
|
||||
service = KnowledgeService(config, 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")
|
||||
port.query.assert_not_awaited()
|
||||
monkeypatch.setattr("app.application.knowledge.QUERY_SECONDS", 0.01)
|
||||
assert await service.search("规则") == KnowledgeOutcome("timeout")
|
||||
assert cancelled.is_set()
|
||||
|
||||
|
||||
@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 == {"enabled": True}
|
||||
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",
|
||||
"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")
|
||||
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():
|
||||
"""
|
||||
连续检索与补读都访问当前端口,令牌轮换后不复用旧授权或正文。
|
||||
"""
|
||||
config, port = MagicMock(), MagicMock(query=AsyncMock(return_value=KnowledgeOutcome("no_match")))
|
||||
config.get.return_value = _config()
|
||||
service = KnowledgeService(config, port, lambda: "3.2.5")
|
||||
await service.search("规则")
|
||||
await service.search("规则")
|
||||
config.get.return_value = _config(token="mpk_" + "x" * 43)
|
||||
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
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("change", [{"domain": "pt"}, {"product": "another-product"}])
|
||||
async def test_search_rejects_response_from_another_declared_scope(change):
|
||||
"""
|
||||
响应的产品与已指定领域必须匹配当前查询,不盲信错误中心返回的范围。
|
||||
"""
|
||||
data = _reply()
|
||||
data["evidence"][0].update(change)
|
||||
async with httpx2.AsyncClient(transport=httpx2.MockTransport(lambda _request: httpx2.Response(200, json=data))) as http:
|
||||
result = await KnowledgeClient(_requester(http)).query(AgentKnowledgeConfig(**_config()), KnowledgeSearch(query="规则", domain="mp"))
|
||||
assert result.status == "invalid_response"
|
||||
Reference in New Issue
Block a user