feat(p5): gate multimodal provider and tool sinks

这个提交存在于:
YokiiroBW 2026-07-30 02:30:07 +08:00
父节点 424be44d5e
当前提交 670a956f3d
共有 7 个文件被更改,包括 327 次插入 和 4 次删除

查看文件

@ -9141,6 +9141,33 @@
}
}
},
"p5c_safety_config": {
"description": "P5-C 多模态与输出安全门",
"type": "object",
"hint": "四项均默认关闭。当前仓内没有可验证的宿主 principal 或 opaque invocation 合同;任一项开启后会在对应已确认 sink 处拒绝,直至后续集成提供可验证授权。不要把页面、会话、事件或 JSON 当作授权凭据。",
"items": {
"enable_p5c_raw_image_provider_gate": {
"description": "拒绝私聊原图主模型挂载",
"type": "bool",
"default": false
},
"enable_p5c_group_image_vision_gate": {
"description": "拒绝群图视觉任务与摘要注入",
"type": "bool",
"default": false
},
"enable_p5c_context_image_caption_gate": {
"description": "拒绝上下文图片转写与回填",
"type": "bool",
"default": false
},
"enable_p5c_tool_parameter_gate": {
"description": "拒绝工具参数跨会话发送",
"type": "bool",
"default": false
}
}
},
"legacy_compat_config": {
"description": "旧版兼容项",
"type": "object",

查看文件

@ -19,6 +19,7 @@ except ImportError:
from astrbot.api.provider import ProviderRequest
from .helpers import _group_link_message_context, _safe_float, _safe_int, _single_line, _strip_internal_message_blocks
from .p5c_gate import RAW_IMAGE_PROVIDER_SINK, p5c_gate_allows
class ForwardMessageMixin:
"""Forward-message parsing and prompt-context helpers."""
@ -953,6 +954,8 @@ class ForwardMessageMixin:
return context
async def _transcribe_forward_message_images(self, event: AstrMessageEvent, image_sources: list[str]) -> str:
if not p5c_gate_allows(self, RAW_IMAGE_PROVIDER_SINK):
return ""
if not self.forward_message_image_vision:
logger.info("[PrivateCompanion] 合并/引用图片视觉跳过: forward_message_image_vision=false")
return ""
@ -2174,4 +2177,3 @@ class ForwardMessageMixin:
)
elif should_log_probe:
logger.info("[PrivateCompanion] 合并消息请求未生成上下文: text=%s", message_text or "(empty)")

查看文件

@ -30,6 +30,7 @@ from .helpers import (
_strip_internal_message_blocks,
)
from .memo_notes import apply_memo_note_action, memo_note_sort_key, normalize_memo_note
from .p5c_gate import P5C_CONTROLLED_DENY_REASON, TOOL_PARAMETER_SINK, p5c_gate_allows
PHOTO_TOOL_SILENT_SENTINEL = "[[PC_PHOTO_SENT_NO_FOLLOWUP]]"
@ -2796,6 +2797,8 @@ class LlmToolActionsMixin:
target_id: str,
chain: list[Any],
) -> tuple[bool, str, str]:
if not p5c_gate_allows(self, TOOL_PARAMETER_SINK):
return False, P5C_CONTROLLED_DENY_REASON, ""
errors: list[str] = []
candidates = self._atrelay_target_umo_candidates(event, message_type, target_id)
if not candidates:
@ -2838,6 +2841,8 @@ class LlmToolActionsMixin:
return False, ";".join(errors[-5:]) or "所有发送链路都失败", candidates[0]
async def _pc_relay_message_impl(self, event: AstrMessageEvent, **kwargs) -> str:
if not p5c_gate_allows(self, TOOL_PARAMETER_SINK):
return json.dumps({"status": "denied", "reason": P5C_CONTROLLED_DENY_REASON}, ensure_ascii=False)
if not self.enable_atrelay_tools:
return json.dumps({"status": "disabled", "message": "跨会话转述工具未启用"}, ensure_ascii=False)
# 统一入口也要先鉴权,否则非主人调用会先跑一次改写 LLM 才在底层被拒。
@ -3081,6 +3086,8 @@ class LlmToolActionsMixin:
)
async def _pc_send_to_group_impl(self, event: AstrMessageEvent, **kwargs) -> str:
if not p5c_gate_allows(self, TOOL_PARAMETER_SINK):
return P5C_CONTROLLED_DENY_REASON
if not self.enable_atrelay_tools:
return "发送失败:跨群转述工具未启用"
allowed, _requester_id = self._atrelay_tool_authorization(event)
@ -3160,6 +3167,8 @@ class LlmToolActionsMixin:
return f"消息已发送到群 {target_group}" + (f", 已 @ {at_label or at_qq}" if at_qq else "")
async def _pc_send_to_private_user_impl(self, event: AstrMessageEvent, **kwargs) -> str:
if not p5c_gate_allows(self, TOOL_PARAMETER_SINK):
return P5C_CONTROLLED_DENY_REASON
if not self.enable_atrelay_tools:
return "发送失败:跨群转述工具未启用"
allowed, _requester_id = self._atrelay_tool_authorization(event)
@ -3231,6 +3240,8 @@ class LlmToolActionsMixin:
return f"已向 {target_user} 发送私聊消息" + (",会等待对方回复后带回回执" if need_receipt else "")
async def _pc_send_to_groups_impl(self, event: AstrMessageEvent, **kwargs) -> str:
if not p5c_gate_allows(self, TOOL_PARAMETER_SINK):
return P5C_CONTROLLED_DENY_REASON
group_ids = kwargs.get("group_ids") or kwargs.get("groups") or kwargs.get("group_id") or kwargs.get("targets") or ""
message = kwargs.get("message") or kwargs.get("text") or kwargs.get("content") or kwargs.get("msg") or ""
at_user = kwargs.get("at_user") or kwargs.get("at") or kwargs.get("target_user") or kwargs.get("user_id") or ""
@ -3253,6 +3264,8 @@ class LlmToolActionsMixin:
return "多群通知完成:\n" + "\n".join(results[: self.atrelay_multi_target_limit])
async def _pc_send_to_private_users_impl(self, event: AstrMessageEvent, **kwargs) -> str:
if not p5c_gate_allows(self, TOOL_PARAMETER_SINK):
return P5C_CONTROLLED_DENY_REASON
user_ids = kwargs.get("user_ids") or kwargs.get("users") or kwargs.get("user_id") or kwargs.get("targets") or ""
message = kwargs.get("message") or kwargs.get("text") or kwargs.get("content") or kwargs.get("msg") or ""
relay_mode = kwargs.get("relay_mode") or kwargs.get("mode") or ""
@ -3277,6 +3290,8 @@ class LlmToolActionsMixin:
return "多人转述完成:\n" + "\n".join(results[: self.atrelay_multi_target_limit])
async def _pc_schedule_group_relay_impl(self, event: AstrMessageEvent, **kwargs) -> str:
if not p5c_gate_allows(self, TOOL_PARAMETER_SINK):
return P5C_CONTROLLED_DENY_REASON
if not self.enable_atrelay_tools:
return "挂起失败:跨群转述工具未启用"
allowed, _requester_id = self._atrelay_tool_authorization(event)

26
main.py
查看文件

@ -139,6 +139,7 @@ from .context_orchestration import (
)
from .p5_ingress_firewall import evaluate_ingress_segments
from .p5_provenance_attestation import FIREWALL_STATUSES, P5AttestationRegistry
from .p5c_gate import RAW_IMAGE_PROVIDER_SINK, p5c_gate_allows
from .segmented_message import flatten_component_chunks, split_plain_component_chain_detailed
from .token_budget import TokenBudgetMixin
from .balance_awareness import BalanceAwarenessMixin
@ -1951,6 +1952,13 @@ class PrivateCompanionPlugin(
self.enable_p5_b1_private_reply_vision_gate = self._cfg_bool(
c, "enable_p5_b1_private_reply_vision_gate", False
)
# P5-C confirms these real sinks but the host currently exposes no
# opaque invocation contract for them. Each is therefore default-off
# and deny-only while enabled; no mutable carrier can authorize it.
self.enable_p5c_raw_image_provider_gate = self._cfg_bool(c, "enable_p5c_raw_image_provider_gate", False)
self.enable_p5c_group_image_vision_gate = self._cfg_bool(c, "enable_p5c_group_image_vision_gate", False)
self.enable_p5c_context_image_caption_gate = self._cfg_bool(c, "enable_p5c_context_image_caption_gate", False)
self.enable_p5c_tool_parameter_gate = self._cfg_bool(c, "enable_p5c_tool_parameter_gate", False)
self.memory_companion_context_timeout_seconds = self._cfg_float(c, "memory_companion_context_timeout_seconds", 1.2, 0.2)
self.enable_memory_companion_emotional_drift = self._cfg_bool(c, "enable_memory_companion_emotional_drift", True)
self.enable_memory_companion_cross_window_emotion = self._cfg_bool(c, "enable_memory_companion_cross_window_emotion", True)
@ -9302,7 +9310,15 @@ wakeup_type={_single_line(wakeup.get('type'), 40)} score={_single_line(wakeup.ge
buffered_image_vision = contextual_vision
if buffered_images:
direct_image_mounted = False
if buffered_image_mode == "direct" and self._event_main_provider_supports_image(event) and not buffered_images_include_gif:
# The same gate protects every path that could put an original
# image source into the ProviderRequest, including text fallback.
raw_image_provider_allowed = self._p5c_gate_allows(RAW_IMAGE_PROVIDER_SINK)
if (
buffered_image_mode == "direct"
and self._event_main_provider_supports_image(event)
and not buffered_images_include_gif
and raw_image_provider_allowed
):
image_refs: list[str] = []
for image_ref in buffered_images[:5]:
for request_ref in self._private_image_sources_for_astrbot_request([image_ref]):
@ -9405,8 +9421,8 @@ wakeup_type={_single_line(wakeup.get('type'), 40)} score={_single_line(wakeup.ge
"image.fallback",
"【本轮延迟图片】\n"
f"{image_context_intro}图片已暂存,但暂无可靠视觉摘要;"
"如果用户问图片内容,请自然说暂时没看清,不要编造画面。\n"
+ "\n".join(f"- {path}" for path in buffered_images),
"如果用户问图片内容,请自然说暂时没看清,不要编造画面。"
+ ("\n" + "\n".join(f"- {path}" for path in buffered_images) if raw_image_provider_allowed else ""),
priority=55,
source="private_image",
)
@ -9856,6 +9872,10 @@ wakeup_type={_single_line(wakeup.get('type'), 40)} score={_single_line(wakeup.ge
return bool(getattr(self, "enable_p5_b1_private_reply_vision_gate", False))
return False
def _p5c_gate_allows(self, sink: str) -> bool:
"""Deny an enabled P5-C sink without treating carriers as authority."""
return p5c_gate_allows(self, sink)
def _p5_b1c_runtime_attestation_inputs(
self,
event: AstrMessageEvent,

77
p5c_gate.py 普通文件
查看文件

@ -0,0 +1,77 @@
"""P5-C default-off, deny-only guards for confirmed Companion sinks.
This plugin does not receive a host-issued opaque invocation for raw media,
background group vision, context-image captioning, or LLM tool parameters.
Consequently an enabled P5-C flag can only deny its matching sink. No event,
P3 carrier, session, dict, JSON payload, or P5-B handle is ever inspected as
an allow credential.
"""
from __future__ import annotations
import hashlib
import logging
from typing import Any
logger = logging.getLogger("PrivateCompanion.P5C")
RAW_IMAGE_PROVIDER_SINK = "raw_image_provider"
GROUP_IMAGE_VISION_SINK = "group_image_vision"
CONTEXT_IMAGE_CAPTION_SINK = "context_image_caption"
TOOL_PARAMETER_SINK = "tool_parameter"
P5C_CONTROLLED_DENY_REASON = "p5c_host_opaque_invocation_unavailable"
P5C_SINK_FLAGS = {
RAW_IMAGE_PROVIDER_SINK: "enable_p5c_raw_image_provider_gate",
GROUP_IMAGE_VISION_SINK: "enable_p5c_group_image_vision_gate",
CONTEXT_IMAGE_CAPTION_SINK: "enable_p5c_context_image_caption_gate",
TOOL_PARAMETER_SINK: "enable_p5c_tool_parameter_gate",
}
def p5c_gate_allows(host: Any, sink: str) -> bool:
"""Return false only for an enabled, confirmed P5-C sink.
The audit projection is derived solely from the static sink name. It
deliberately avoids reading any event, request, source, media, tool
parameter, provider payload, or caller-provided identity object.
"""
flag = P5C_SINK_FLAGS.get(sink)
if not flag:
raise ValueError("p5c_unknown_sink")
try:
enabled = bool(getattr(host, flag, False))
except Exception:
enabled = True
if not enabled:
return True
audit = {
"sink": sink,
"outcome": "denied",
"reason_code": P5C_CONTROLLED_DENY_REASON,
"ref_hash": hashlib.sha256(f"p5c:{sink}".encode("utf-8")).hexdigest(),
}
try:
entries = getattr(host, "_p5c_denial_audit", None)
if not isinstance(entries, list):
entries = []
setattr(host, "_p5c_denial_audit", entries)
entries.append(audit)
del entries[:-64]
except Exception:
pass
logger.warning("[PrivateCompanion][P5-C] gate=%s", audit)
return False
__all__ = [
"CONTEXT_IMAGE_CAPTION_SINK",
"GROUP_IMAGE_VISION_SINK",
"P5C_CONTROLLED_DENY_REASON",
"P5C_SINK_FLAGS",
"RAW_IMAGE_PROVIDER_SINK",
"TOOL_PARAMETER_SINK",
"p5c_gate_allows",
]

查看文件

@ -30,6 +30,7 @@ from astrbot.core.astr_main_agent import MainAgentBuildConfig, build_main_agent
from astrbot.core.utils.astrbot_path import get_astrbot_data_path
from .helpers import _missing_optional_model_dependency, _now_ts, _safe_float, _safe_int, _single_line, _strip_internal_message_blocks, _today_key, _url_host_is_public
from .p5c_gate import CONTEXT_IMAGE_CAPTION_SINK, GROUP_IMAGE_VISION_SINK, RAW_IMAGE_PROVIDER_SINK, p5c_gate_allows
from .segmented_message import split_plain_component_chain
# 识图临时文件的存活上限。单次识图(含重试与多 provider 回退)远低于这个数量级,
@ -2336,6 +2337,9 @@ class PrivateImageMixin:
namespace: str = "private_vision",
) -> str:
clean_cache_scope = _single_line(cache_scope, 40)
p5c_sink = GROUP_IMAGE_VISION_SINK if clean_cache_scope == "group_image" else RAW_IMAGE_PROVIDER_SINK
if not p5c_gate_allows(self, p5c_sink):
return ""
clean_task_name = _single_line(task_name, 80) or "private_image_vision"
clean_log_subject = _single_line(log_subject, 40) or "图片"
clean_namespace = _single_line(namespace, 60) or "vision"
@ -2813,6 +2817,8 @@ class PrivateImageMixin:
sender_id: str = "",
text: str = "",
) -> asyncio.Task | None:
if not p5c_gate_allows(self, GROUP_IMAGE_VISION_SINK):
return None
if not bool(getattr(self, "enable_group_image_understanding", False)):
return None
group_id = _single_line(group_id, 80)
@ -2976,6 +2982,10 @@ class PrivateImageMixin:
event: AstrMessageEvent,
req: ProviderRequest,
) -> bool:
# A completed background task has no host-issued invocation grant.
# Enforce again before it can be copied into the ProviderRequest.
if not p5c_gate_allows(self, GROUP_IMAGE_VISION_SINK):
return False
summary = await self._await_group_image_understanding_for_request(event)
if not summary:
return False
@ -3266,6 +3276,10 @@ class PrivateImageMixin:
return None
async def _caption_context_image_sources(self, sources: list[str], *, umo: str = "") -> str:
# Keep the provider boundary protected if a future caller bypasses
# `_enrich_request_context_image_placeholders`.
if not p5c_gate_allows(self, CONTEXT_IMAGE_CAPTION_SINK):
return ""
clean_sources = [str(item).strip() for item in sources if str(item or "").strip()][:5]
if not clean_sources:
return ""
@ -3283,6 +3297,8 @@ class PrivateImageMixin:
return ""
async def _enrich_request_context_image_placeholders(self, event: AstrMessageEvent, req: ProviderRequest) -> dict[str, int]:
if not p5c_gate_allows(self, CONTEXT_IMAGE_CAPTION_SINK):
return {"contexts": 0, "replaced": 0, "missed": 0}
if not bool(getattr(self, "enable_context_image_captioning", True)):
return {"contexts": 0, "replaced": 0, "missed": 0}
contexts = getattr(req, "contexts", None)
@ -4316,6 +4332,8 @@ class PrivateImageMixin:
user_id: str,
buffer: dict[str, Any],
) -> None:
if not p5c_gate_allows(self, RAW_IMAGE_PROVIDER_SINK):
return
feature_checker = getattr(self, "_feature_enabled_or_temp_unlocked", None)
feature_enabled = (
feature_checker("enable_private_image_self_recognition")

164
tests/test_p5c_gates.py 普通文件
查看文件

@ -0,0 +1,164 @@
# -*- coding: utf-8 -*-
"""Focused proof that enabled P5-C Companion sinks deny before egress."""
from __future__ import annotations
import importlib
import inspect
import json
from pathlib import Path
import sys
from types import SimpleNamespace
import types
import unittest
sys.path.insert(0, str(Path(__file__).resolve().parent))
import _host_stub # noqa: E402
_host_stub.install()
event_module = importlib.import_module("astrbot.api.event")
event_module.filter.EventMessageType = SimpleNamespace(
ALL="ALL", PRIVATE_MESSAGE="PRIVATE_MESSAGE", GROUP_MESSAGE="GROUP_MESSAGE"
)
PACKAGE = "_p5c_gate_companion"
if PACKAGE not in sys.modules:
package = types.ModuleType(PACKAGE)
package.__path__ = [str(Path(__file__).resolve().parents[1])]
sys.modules[PACKAGE] = package
gate = importlib.import_module(f"{PACKAGE}.p5c_gate")
main = importlib.import_module(f"{PACKAGE}.main")
private_image = importlib.import_module(f"{PACKAGE}.private_image")
forward = importlib.import_module(f"{PACKAGE}.forward_message")
tool_actions = importlib.import_module(f"{PACKAGE}.llm_tool_actions")
class _Host:
enable_p5c_raw_image_provider_gate = True
enable_p5c_group_image_vision_gate = True
enable_p5c_context_image_caption_gate = True
enable_p5c_tool_parameter_gate = True
class _ImageHost(_Host):
async def _prepare_private_image_sources_for_model(self, *_args, **_kwargs):
raise AssertionError("enabled raw-image gate must stop before image preparation")
class _ForwardHost(_Host):
forward_message_image_vision = True
async def _prepare_private_image_sources_for_model(self, *_args, **_kwargs):
raise AssertionError("enabled forward-image gate must stop before image preparation")
class _ToolHost(_Host):
def _atrelay_target_umo_candidates(self, *_args, **_kwargs):
raise AssertionError("enabled tool gate must stop before target resolution")
class P5CCompanionGateTests(unittest.IsolatedAsyncioTestCase):
async def test_default_off_does_not_change_paths_and_audit_has_no_carrier_values(self) -> None:
off = SimpleNamespace()
self.assertTrue(gate.p5c_gate_allows(off, gate.RAW_IMAGE_PROVIDER_SINK))
host = _Host()
host.event = "event-secret"
self.assertFalse(gate.p5c_gate_allows(host, gate.RAW_IMAGE_PROVIDER_SINK))
audit = host._p5c_denial_audit[-1]
self.assertEqual(
{"sink", "outcome", "reason_code", "ref_hash"},
set(audit),
)
self.assertNotIn("event-secret", repr(audit))
bound = _Host()
bound._p5c_gate_allows = main.PrivateCompanionPlugin._p5c_gate_allows.__get__(bound, _Host)
self.assertFalse(bound._p5c_gate_allows(gate.TOOL_PARAMETER_SINK))
async def test_enabled_media_sinks_stop_before_prepare_task_and_context_mutation(self) -> None:
image_host = _ImageHost()
result = await private_image.PrivateImageMixin._transcribe_private_inbound_images(
image_host, ["https://example.invalid/raw.png"]
)
self.assertEqual("", result)
group_host = _Host()
group_request = SimpleNamespace(system_prompt="unchanged", prompt="")
appended = await private_image.PrivateImageMixin._append_group_image_understanding_to_request(
group_host, SimpleNamespace(), group_request
)
self.assertFalse(appended)
self.assertEqual("unchanged", group_request.system_prompt)
context_host = _Host()
caption = await private_image.PrivateImageMixin._caption_context_image_sources(
context_host, ["https://example.invalid/context.png"]
)
self.assertEqual("", caption)
task = private_image.PrivateImageMixin._start_group_image_understanding(
group_host, SimpleNamespace()
)
self.assertIsNone(task)
request = SimpleNamespace(contexts=["[image placeholder]"])
result = await private_image.PrivateImageMixin._enrich_request_context_image_placeholders(
context_host, SimpleNamespace(), request
)
self.assertEqual({"contexts": 0, "replaced": 0, "missed": 0}, result)
self.assertEqual(["[image placeholder]"], request.contexts)
forward_host = _ForwardHost()
result = await forward.ForwardMessageMixin._transcribe_forward_message_images(
forward_host, SimpleNamespace(), ["https://example.invalid/forward.png"]
)
self.assertEqual("", result)
async def test_enabled_tool_gate_stops_before_target_resolution_and_final_send(self) -> None:
host = _ToolHost()
result = await tool_actions.LlmToolActionsMixin._pc_send_to_group_impl(
host, SimpleNamespace(), message="secret", group_id="123"
)
self.assertEqual(gate.P5C_CONTROLLED_DENY_REASON, result)
ok, reason, used_umo = await tool_actions.LlmToolActionsMixin._send_atrelay_chain_to_target(
host,
SimpleNamespace(),
message_type="group",
target_id="123",
chain=[],
)
self.assertFalse(ok)
self.assertEqual(gate.P5C_CONTROLLED_DENY_REASON, reason)
self.assertEqual("", used_umo)
scheduled = await tool_actions.LlmToolActionsMixin._pc_schedule_group_relay_impl(
host, SimpleNamespace(), message="secret", group_id="123"
)
self.assertEqual(gate.P5C_CONTROLLED_DENY_REASON, scheduled)
async def test_direct_raw_mount_is_gated_before_source_preparation_and_schema_is_default_off(self) -> None:
source = inspect.getsource(main.PrivateCompanionPlugin.inject_humanized_state)
buffered_start = source.index("direct_image_mounted = False")
direct_start = source.index('buffered_image_mode == "direct"', buffered_start)
gate_at = source.index("raw_image_provider_allowed = self._p5c_gate_allows(RAW_IMAGE_PROVIDER_SINK)", buffered_start)
prepare_at = source.index("self._private_image_sources_for_astrbot_request", direct_start)
self.assertLess(gate_at, direct_start)
self.assertLess(gate_at, prepare_at)
fallback_start = source.index('"image.fallback"', direct_start)
fallback_end = source.index('elif bool(getattr(event, "private_companion_deferred_private_image_only_ready"', fallback_start)
fallback = source[fallback_start:fallback_end]
self.assertIn("if raw_image_provider_allowed else \"\"", fallback)
self.assertNotIn('"\\n".join(f"- {path}" for path in buffered_images),', fallback)
schema = json.loads((Path(__file__).resolve().parents[1] / "_conf_schema.json").read_text(encoding="utf-8"))
items = schema["p5c_safety_config"]["items"]
self.assertEqual(set(gate.P5C_SINK_FLAGS.values()), set(items))
self.assertTrue(all(entry["default"] is False for entry in items.values()))
if __name__ == "__main__":
unittest.main()