From 2310ad3e626c64c2c5e8228bb9b64b34cfa169f4 Mon Sep 17 00:00:00 2001 From: timeance <30307526+timeance@users.noreply.github.com> Date: Thu, 19 Nov 2026 11:50:48 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E5=BC=80=E6=94=BE=E7=BE=A4=E8=81=8A?= =?UTF-8?q?=E4=BA=92=E5=8A=A8=E8=AF=84=E4=BC=B0=E5=85=A5=E5=8F=A3=E5=B9=B6?= =?UTF-8?q?=E6=8E=A5=E6=94=B6=E5=8F=8D=E6=B3=A8=E5=85=A5=E9=98=B2=E6=8A=A4?= =?UTF-8?q?=E7=BB=93=E6=9E=9C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- CHANGELOG.md | 9 ++-- README.md | 6 ++- _conf_schema.json | 13 ++++++ api/facade.py | 42 ++++++++++++++++++- api/listeners.py | 60 +++++++++++++++++++++++++-- core/settings.py | 2 + docs/PLUGIN_API.md | 19 +++++++++ main.py | 4 +- metadata.yaml | 2 +- pages/dashboard/app.js | 2 +- services/favor_service.py | 26 ++++++++++++ services/runtime_service.py | 82 ++++++++++++++++++++++++++++++++++--- storage/sqlite_backend.py | 17 +++++++- tests/test_runtime_scope.py | 74 +++++++++++++++++++++++++++++++++ tests/test_settings.py | 2 + 15 files changed, 339 insertions(+), 21 deletions(-) create mode 100644 docs/PLUGIN_API.md diff --git a/CHANGELOG.md b/CHANGELOG.md index 0f2500d..0dba6d7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,7 +1,8 @@ # 更新说明 -## 0.7.3 — 2026-11-18 +## 0.8.0 — 2026-11-19 -- **给群聊留更多发挥空间**:回复模型只看到本轮有内容的印象和经历。熟人可以少些客套,新人也能一起接梗;多人聊天时,关系资料明确指向对应成员。 -- **全局预览说清了为什么看不到**:成员印象和群内经历都会标明「全局空间不展示」,不再让人误以为资料丢了。 -- **少写一个参数不会清空全群**:`/好感重置` 只显示用法。重置一人填 QQ 号;按群保存关系时,清空本群要明确输入 `/好感重置 全群`。 +- 其他插件现在可以请 Bond 评估一条发给机器人的群消息。需要在「基础设置」同时开启「自动评估」和「允许其他插件提交群聊互动评估」。沿用已有评估模型和额度,可能产生模型费用;提交不等于改分。 +- 「信任度变化」新增反注入联动,默认关闭。要使用它,请在 AntiPromptInjector 开启「向 Bond 报告群聊防护结果」,再在 Bond 开启「根据反注入复核结果调整信任度」,保存并重载 Bond。 +- 在 OneBot 群聊中,只有反注入模型确认风险、插件已采取防护,且内容确实来自该成员时,Bond 才会降低信任度。每条消息最多扣 1 点,仍受每日下降额度限制;熟悉度和亲近度不变。 +- 关系流水会标注「反注入复核」,不会保存聊天原文。同一条消息重复送达不重复扣分;私聊、仅规则命中、观察和复核失败不扣分。 diff --git a/README.md b/README.md index 5af0e73..b7094b3 100755 --- a/README.md +++ b/README.md @@ -18,7 +18,7 @@
- v0.7.0 · AstrBot ≥4.28 · OneBot aiocqhttp · AGPL-3.0 + v0.8.0 · AstrBot ≥4.28 · OneBot aiocqhttp · AGPL-3.0
--- @@ -27,6 +27,10 @@ Bond 是面向 **长期多人群聊** 的关系记忆插件。它分别记录 Bo 关系可以随群聊互动更新,也可以在管理面板里查看、调整、撤销或设置限时覆盖。每份关系资料都属于对应的 Bot 账号与数据空间;群内公开查询只显示关系称谓,不展示具体分值。 +可选联动:在「信任度变化」开启「根据反注入复核结果调整信任度」,保存并重载 Bond,再开启 AntiPromptInjector 4.2.0 的群聊防护报告。模型确认且能归责于发言人的防护事件只影响信任度,沿用当前 Bot 的关系空间和每日下降额度。联动默认关闭,不需要开启 Bond 的自动评估,也不额外调用模型。见[本版更新](CHANGELOG.md)。 + +其他插件可以使用[进程内接口](docs/PLUGIN_API.md)查询关系称谓、排行,或提交群聊互动供 Bond 评估。 + > **初次安装默认在回复中体现关系,自动评估、动态称谓和诊断记录默认关闭。** 启用自动评估前,先在管理面板选择日常评估模型。已有配置中明确关闭的回复参考会继续保留。可先试用查询和管理功能,再按需开启自动评估。 ## ✨ Bond 能带来什么 diff --git a/_conf_schema.json b/_conf_schema.json index f4cc958..f3ec0f0 100644 --- a/_conf_schema.json +++ b/_conf_schema.json @@ -1,4 +1,17 @@ { + "external_assessment_enabled": { + "description": "允许其他插件提交群聊互动评估", + "type": "bool", + "default": false, + "hint": "须同时开启自动评估。评估可能调用已配置的模型。" + }, + "antipromptinjector_trust_enabled": { + "description": "根据反注入复核结果调整信任度", + "type": "bool", + "default": false, + "invisible": true, + "hint": "仅用于 OneBot 群聊,同时开启 AntiPromptInjector 的群聊防护报告后生效。" + }, "assessment": { "type": "object", "description": "自动评估", diff --git a/api/facade.py b/api/facade.py index bde87ec..c2c5c78 100755 --- a/api/facade.py +++ b/api/facade.py @@ -1,12 +1,50 @@ -"""Bond 跨插件只读查询;调用者必须明确 Bot 与作用域。""" +"""Bond 进程内接口:只读关系查询及可选的群聊防护通知。""" from __future__ import annotations from ..core.scope import account_id, scope_mode class BondFacade: - def __init__(self, runtime): + def __init__(self, runtime, context=None): self._runtime = runtime + self._context = context + + async def receive_protection_fact_v1(self, ticket): + if type(ticket) is not object or self._context is None: + return "invalid" + source = self._context.get_registered_star("antipromptinjector") + take = getattr( + getattr(source, "star_cls", None), "take_protection_fact_v1", None + ) + if not getattr(source, "activated", False) or not callable(take): + return "unavailable" + return await self._runtime.receive_protection_fact(take(ticket)) + + async def submit_assessment_event_v1(self, event): + """请 Bond 评估本次平台互动,返回处理状态;不能指定分值或目标成员。""" + from astrbot.api.event import AstrMessageEvent + from .listeners import submit_group_candidate + + if not isinstance(event, AstrMessageEvent): + return "invalid" + if not self._runtime.external_assessment_enabled: + return "disabled" + plugins = event.plugins_name + if plugins is not None and "astrbot_plugin_bond" not in plugins: + return "disabled" + if event.get_platform_name() != "aiocqhttp": + return "ignored" + try: + bot, group, user = ( + account_id(event.get_self_id()), + account_id(event.get_group_id()), + account_id(event.get_sender_id()), + ) + except ValueError: + return "ignored" + if not self._runtime.allows_member(bot, group, user): + return "ignored" + return await submit_group_candidate(self._runtime, event) async def get_profile(self, bot_id, mode, group_id, user_id): account_id(group_id) diff --git a/api/listeners.py b/api/listeners.py index f21a500..e55f227 100644 --- a/api/listeners.py +++ b/api/listeners.py @@ -15,7 +15,7 @@ from astrbot.api.event import AstrMessageEvent from astrbot.api.provider import ProviderRequest -from ..core.assessment import Interaction +from ..core.assessment import Interaction, locally_relevant from ..core.taskregistry import TaskRegistry from ..services.diagnostic_capture import CURRENT, event_capture, request_content from ..services.favor_service import FavorService @@ -226,6 +226,62 @@ def _reply_metadata(event): ) +async def submit_group_candidate(runtime, event): + # Platform notices can have adapter-generated IDs; only ordinary messages qualify. + raw = getattr(event.message_obj, "raw_message", None) + read = getattr(raw, "get", None) + if ( + not callable(read) + or read("post_type") != "message" + or read("message_type") != "group" + ): + return "invalid" + bot, group, member, platform, message_id = _message_identity(event) + if ( + message_id in ("", "0") + or len(message_id) > 200 + or any( + str(read(k)) != v + for k, v in ( + ("self_id", bot), + ("group_id", group), + ("user_id", member), + ("message_id", message_id), + ) + ) + ): + return "invalid" + text = event.message_str + if ( + type(text) is not str + or len(text) > 2000 + or text != event.message_obj.message_str + or not locally_relevant(text, any(_chain_flags(event))) + ): + return "filtered" + interaction = Interaction( + bot, group, member, platform, message_id, text, **_reply_metadata(event) + ) + deps = await runtime.select(bot) + if ( + not deps.assessment + or not deps.assessment.config.enabled + or deps.registry.closed + ): + return "disabled" + # Share the native listener's pre-assessment snapshot and persistent claim ID. + deps, _ = await _freeze_relation(deps, event) + if deps.registry.closed: + return "disabled" + state = await deps.favor.temporary_state(group, member) + if state["active"]: + return "temporary" + return await deps.registry.spawn( + deps.assessment.assess(interaction, directed=True, admission_state=state), + name=f"external-assessment:{group}/{member}", + ) + + async def on_llm_response(deps: Deps, event: AstrMessageEvent, response) -> None: """使用入场时冻结的服务与身份,不按回复完成时的配置重新选择空间。""" capture = event_capture(deps, event) @@ -325,8 +381,6 @@ async def on_group_message( and (has_at_bot or is_reply_bot) and not admission_state["active"] ): - from ..core.assessment import locally_relevant - if locally_relevant(text, True): try: admitted_interaction = Interaction( diff --git a/core/settings.py b/core/settings.py index a1a8a4c..55f4184 100644 --- a/core/settings.py +++ b/core/settings.py @@ -21,6 +21,7 @@ class SettingsRevisionError(ValueError): "基础设置", [ "assessment.enabled", + "external_assessment_enabled", "assessment.small_provider_id", "assessment.large_provider_id", "assessment.assessment_mode", @@ -65,6 +66,7 @@ class SettingsRevisionError(ValueError): "trust": ( "信任度变化", [ + "antipromptinjector_trust_enabled", "relation_daily_caps.trust_up", "relation_daily_caps.trust_down", "decay.trust_enabled", diff --git a/docs/PLUGIN_API.md b/docs/PLUGIN_API.md new file mode 100644 index 0000000..072c425 --- /dev/null +++ b/docs/PLUGIN_API.md @@ -0,0 +1,19 @@ +# 插件间调用 + +这些接口只供同一 AstrBot 进程中已安装的插件使用,不是 HTTP 接口、聊天命令或模型工具。调用方仍须遵守自己的访问权限,不要把接口直接转发给聊天用户。 + +```python +star = context.get_registered_star("astrbot_plugin_bond") +if star and star.activated: + api = star.star_cls.api + profile = await api.get_profile(bot_id, mode, group_id, user_id) + ranking = await api.get_ranking(bot_id, mode, group_id, limit=5) + submit = getattr(api, "submit_assessment_event_v1", None) + if submit: + status = await submit(event) +``` + +- 查询必须指定真实 Bot 账号和关系空间(`per_group` 或 `global`)。返回公开关系称谓,不返回分值、印象或聊天记录。 +- `submit_assessment_event_v1(event)` 接收当前 AstrBot 平台事件,不接收自填的成员、文本、关系类别或分值。首版只接受 OneBot 群聊里明确提及或回复机器人的消息。普通插件不能提交脱离平台消息的自定义事实。 +- 管理员须在「基础设置」开启「允许其他插件提交群聊互动评估」和「自动评估」,保存并重载。调用会等待 Bond 处理;它不是持久待办队列。与原生评估共用消息标识、并发限制、模型和额度。`accepted` 表示评估已产生变动;`disabled`、`filtered`、`busy`、`duplicate_or_cooldown`、`abstained` 等均不能视为已改分。 +- 反注入联动独立开启,不使用这个通用评估入口。Bond 只从宿主注册的 AntiPromptInjector 领取本轮防护事实,其他调用方传入自写的「已确认」结论不会改分。此校验用于区分正常调用路径,不提供同进程恶意插件隔离。 diff --git a/main.py b/main.py index 55911cd..999a373 100644 --- a/main.py +++ b/main.py @@ -84,7 +84,7 @@ def _group_entry_id(event) -> str | None: "astrbot_plugin_bond", "yiwuerxin, Timeance", "Bond 关系好感系统:三维关系与成员印象", - "0.7.3", + "0.8.0", "https://github.com/timeance/Astrbot_plugin_bond", ) class BondPlugin(Star): @@ -163,7 +163,7 @@ def __init__(self, context: Context, config: AstrBotConfig) -> None: self._render_rows = int(render_cfg.get("rows_per_col", 12)) # 跨插件 API:context.get_registered_star("astrbot_plugin_bond").star_cls.api - self.api = BondFacade(self._runtime) + self.api = BondFacade(self._runtime, context) # 原生 dashboard 页面 API(框架支持时注册,内嵌于主面板,无独立端口/鉴权) from .api.page_api import PageApi diff --git a/metadata.yaml b/metadata.yaml index fd1d8ef..9906564 100644 --- a/metadata.yaml +++ b/metadata.yaml @@ -2,7 +2,7 @@ name: astrbot_plugin_bond display_name: Bond 关系好感系统 short_desc: 按 Bot 隔离的三维关系与成员印象 desc: 保存熟悉度、亲近度、信任度与成员印象,支持分级评估、人格适配及管理面板。 -version: 0.7.3 +version: 0.8.0 author: yiwuerxin, Timeance repo: https://github.com/timeance/Astrbot_plugin_bond tags: diff --git a/pages/dashboard/app.js b/pages/dashboard/app.js index 52e652f..009f460 100644 --- a/pages/dashboard/app.js +++ b/pages/dashboard/app.js @@ -559,7 +559,7 @@ createApp({ } return `${out} (${id})`; }; - const SOURCE_LABEL = { rule: "规则", judge: "评估", passive_familiarity: "群聊活跃", admin: "管理员", admin_profile: "管理员资料", tool: "工具", api: "API", set: "设定", undo: "撤销" }; + const SOURCE_LABEL = { rule: "规则", judge: "评估", passive_familiarity: "群聊活跃", anti_injection: "反注入复核", admin: "管理员", admin_profile: "管理员资料", tool: "工具", api: "API", set: "设定", undo: "撤销" }; const sourceLabel = (s) => SOURCE_LABEL[s] || s || "-"; const isPassiveLog = (row) => row.source === "passive_familiarity"; diff --git a/services/favor_service.py b/services/favor_service.py index ecef9e7..32af6b1 100644 --- a/services/favor_service.py +++ b/services/favor_service.py @@ -740,6 +740,32 @@ def transform(before, positive_today): ) return result + async def apply_protection_fact(self, group_id, user_id, event_id): + state = await self.temporary_state(group_id, user_id) + if state["active"]: + return "temporary" + now = time.time() + result = await self._storage.apply_relation_change( + self.group_key(group_id), + user_id, + dict(familiarity=0.0, affinity=0.0, trust=-1.0), + event_id=event_id, + source="anti_injection", + reason="反注入模型确认本轮消息存在注入", + caps=self._relation_caps, + cooldown_sec=0, + expected_revision=state["revision"], + effective=self._effective_affinity_raw, + effective_trust=self._effective_trust, + effective_familiarity=self._effective_familiarity, + default_favor=self.default_favor, + day=self._today(now).isoformat(), + day_start=self._day_start(now), + day_end=self._day_end(now), + origin_group_id=group_id, + ) + return result.get("skipped") or "processed" + async def apply_passive_familiarity( self, group_id, user_id, *, trigger_id, observed_at=None, triggered_at=None ): diff --git a/services/runtime_service.py b/services/runtime_service.py index 4797f5b..66d87f9 100644 --- a/services/runtime_service.py +++ b/services/runtime_service.py @@ -4,8 +4,9 @@ import asyncio import json +import re -from ..core.scope import account_id, scope_mode +from ..core.scope import account_id, group_key, is_account_id, scope_mode from ..core.settings import SettingsRevisionError @@ -28,6 +29,13 @@ def __init__( self._names_lock = asyncio.Lock() self._names_refreshed = {} self._default_mode = scope_mode(config.get("default_scope_mode", "per_group")) + self._protection_enabled = ( + config.get("antipromptinjector_trust_enabled") is True + ) + self.external_assessment_enabled = ( + config.get("external_assessment_enabled") is True + and (config.get("assessment") or {}).get("enabled") is True + ) whitelist = config.get("group_whitelist", []) if not isinstance(whitelist, list): raise ValueError("群白名单必须是群号列表") @@ -50,11 +58,65 @@ async def select(self, bot_id: str, mode: str | None = None): bot_id = account_id(bot_id) mode = scope_mode(mode or self.current_mode(bot_id)) async with self._lock: - key = (bot_id, mode) - if key not in self._bundles: - backend = await self.storage.get(bot_id, mode) - self._bundles[key] = self._factory(backend, mode) - return self._bundles[key] + return await self._select_locked(bot_id, mode) + + async def _select_locked(self, bot_id, mode): + key = (bot_id, mode) + if key not in self._bundles: + backend = await self.storage.get(bot_id, mode) + self._bundles[key] = self._factory(backend, mode) + return self._bundles[key] + + async def receive_protection_fact(self, fact): + if not self._protection_enabled: + return "disabled" + fields = { + "event_id", + "platform", + "instance_id", + "bot_id", + "group_id", + "user_id", + "source", + "attributable", + "action", + "evidence", + } + if ( + type(fact) is not dict + or fact.keys() != fields + or any(type(fact[key]) is not str for key in fields - {"attributable"}) + or type(fact["attributable"]) is not bool + or fact["platform"] != "aiocqhttp" + or not 0 < len(fact["instance_id"]) <= 200 + or not re.fullmatch(r"api:v1:[0-9a-f]{64}", fact["event_id"]) + or not all( + is_account_id(fact[k]) for k in ("bot_id", "group_id", "user_id") + ) + or fact["action"] not in ("harden", "replace", "block") + or fact["source"] not in ("prompt", "extra_user_content_parts", "mixed") + or fact["evidence"] not in ("rule", "confirmed") + ): + return "invalid" + bot, group, user = fact["bot_id"], fact["group_id"], fact["user_id"] + if ( + fact["evidence"] != "confirmed" + or not fact["attributable"] + or fact["source"] != "prompt" + or not self.allows_member(bot, group, user) + ): + return "ignored" + # Mode switches and duplicate deliveries share the same critical section. + async with self._lock: + mode = self.current_mode(bot) + other = "global" if mode == "per_group" else "per_group" + backend = await self.storage.get(bot, other) + if await backend.has_relation_event( + group_key(other, group), user, fact["event_id"] + ): + return "duplicate" + deps = await self._select_locked(bot, mode) + return await deps.favor.apply_protection_fact(group, user, fact["event_id"]) def peek(self, bot_id, mode): """只返回已装配空间;预览不初始化数据库、迁移或称谓观察基线。""" @@ -68,6 +130,14 @@ def group_enabled(self, group_id): group_id = account_id(group_id) return not self._group_whitelist or group_id in self._group_whitelist + def allows_member(self, bot, group, user): + return ( + self.group_enabled(group) + and user != bot + and user not in self.known_bot_ids() + and user not in {str(x) for x in self._config.get("ignored_bot_ids") or []} + ) + async def for_event(self, event): self.observe_bot(event) group_id = str(event.get_group_id() or "") diff --git a/storage/sqlite_backend.py b/storage/sqlite_backend.py index 344482a..745be7a 100755 --- a/storage/sqlite_backend.py +++ b/storage/sqlite_backend.py @@ -1072,6 +1072,18 @@ async def boundary_evidence_context(self, group_id, user_id, *, origin_group_id) for row in rows ] + async def has_relation_event(self, group_id, user_id, event_id): + with self._lock: + return ( + self._c() + .execute( + "SELECT 1 FROM favor_log WHERE group_id=? AND user_id=? AND event_id=?", + (group_id, user_id, event_id), + ) + .fetchone() + is not None + ) + async def apply_relation_change( self, group_id, @@ -1271,7 +1283,9 @@ async def apply_relation_change( ) maintained = ( {"familiarity", "affinity"} | (qualified & {"trust"}) - if self._maintenance_strategy == "legacy" and values is None + if self._maintenance_strategy == "legacy" + and values is None + and source != "anti_injection" else qualified ) # 无关维度保留原始数值、结算锚、托底参考和巩固状态。 @@ -1296,6 +1310,7 @@ async def apply_relation_change( add_usage( conn, group_id, user_id, day, real, judge=source == "judge" ) + if values is None and source != "anti_injection": conn.execute( "INSERT INTO cooldown(group_id,user_id,key,last_ts) VALUES(?,?,'relation',?) " "ON CONFLICT(group_id,user_id,key) DO UPDATE SET last_ts=excluded.last_ts", diff --git a/tests/test_runtime_scope.py b/tests/test_runtime_scope.py index 2beabb9..fc13cfd 100644 --- a/tests/test_runtime_scope.py +++ b/tests/test_runtime_scope.py @@ -29,6 +29,80 @@ def factory(storage, mode): ) +def test_protection_policy_limits_and_retry_after_scope_change(tmp_path): + async def run(): + config = Config(antipromptinjector_trust_enabled=True, group_whitelist=["333"]) + storage = BotScopeStorageRouter(tmp_path) + runtime = RuntimeService(storage, config, factory) + fact = dict( + event_id="api:v1:" + "2" * 64, + platform="aiocqhttp", + instance_id="adapter", + bot_id="111", + group_id="333", + user_id="222", + source="prompt", + attributable=True, + action="block", + evidence="confirmed", + ) + assert ( + await RuntimeService(storage, {}, factory).receive_protection_fact(fact) + == "disabled" + ) + for change in ( + dict(evidence="rule"), + dict(attributable=False), + dict(source="mixed"), + dict(group_id="444"), + dict(user_id="111"), + ): + assert ( + await runtime.receive_protection_fact(dict(fact, **change)) == "ignored" + ) + for change in ( + dict(group_id=""), + dict(score=-10), + dict(attributable="true"), + dict(event_id=""), + ): + assert ( + await runtime.receive_protection_fact(dict(fact, **change)) == "invalid" + ) + assert not storage.known_bot_ids() + outcomes = await asyncio.gather( + *(runtime.receive_protection_fact(fact) for _ in range(3)) + ) + assert sorted(outcomes) == ["duplicate", "duplicate", "processed"] + deps = await runtime.select("111") + rec = await deps.favor.get_relation("333", "222") + assert (rec.familiarity, rec.affinity, rec.trust) == (0, 0, -1) + for n in range(1, 12): + await runtime.receive_protection_fact( + dict(fact, event_id=f"api:v1:{n:064x}") + ) + assert (await deps.favor.get_relation("333", "222")).trust == -8 + await runtime.switch_mode("111", "global") + await storage.close() + storage = BotScopeStorageRouter(tmp_path) + runtime = RuntimeService(storage, config, factory) + try: + assert await runtime.receive_protection_fact(fact) == "duplicate" + current = await runtime.select("111") + assert (await current.favor.get_relation("333", "222")).trust == 0 + assert ( + await runtime.receive_protection_fact( + dict(fact, event_id="api:v1:" + "f" * 64) + ) + == "processed" + ) + assert (await current.favor.get_relation("444", "222")).trust == -1 + finally: + await storage.close() + + asyncio.run(run()) + + def test_switch_keeps_old_task_target_and_restarts(tmp_path): async def run(): config = Config() diff --git a/tests/test_settings.py b/tests/test_settings.py index 5c700aa..2841fe4 100644 --- a/tests/test_settings.py +++ b/tests/test_settings.py @@ -112,6 +112,7 @@ def test_quickstart_field_order_unique_groups_and_provider_metadata(): definitions = fields() assert [f["path"] for f in definitions if f["group"] == "basic"] == [ "assessment.enabled", + "external_assessment_enabled", "assessment.small_provider_id", "assessment.large_provider_id", "assessment.assessment_mode", @@ -226,6 +227,7 @@ def collect(path, node): ): collect(key, schema[key]) expected -= {"economy.preset", "decay.grace_days", "decay.maintenance_strategy"} + expected.add("antipromptinjector_trust_enabled") assert set(paths) == expected assert groups["familiarity"][:7] == [ "relation_daily_caps.familiarity_up",