# -*- coding: utf-8 -*- from __future__ import annotations import sys import uuid import asyncio import hashlib import time from typing import Any from astrbot.api import logger from .helpers import _missing_optional_model_dependency, _safe_float, _safe_int, _single_line from .bot_personal_dto import PrivacyRejected, build_bot_personal_dto from .bot_personal_outbox import due_outbox, enqueue_outbox, update_outbox def _media_file_name(value: Any, limit: int = 120) -> str: """只取文件名,丢掉目录。 合同禁止本机绝对路径进入归档,而媒体类记录天然拿到的是绝对路径。 同时处理 Windows 与 POSIX 分隔符,避免跨平台时只剥掉一种。 """ return _single_line(str(value or "").replace("\\", "/").rsplit("/", 1)[-1], limit) def _media_reference_id(*parts: Any) -> str: """由本机路径等敏感来源派生稳定媒体标识:摘要可以外传,原值不行。""" seed = "|".join(_single_line(part, 400) for part in parts if _single_line(part, 400)) return hashlib.sha1(seed.encode("utf-8", "ignore")).hexdigest()[:16] if seed else "" # M6.1.5:固定注入槽位与条数。(Profile, 展示标签, 条数) # 「当前」和「过去」分成两个槽而不是一次通用检索,是因为混在一批结果里时, # 模型分不清哪条是现在要做的、哪条是昨天做过的。记忆侧两个 Profile 的时间窗刻意不重叠。 _BOT_PROFILE_SLOTS = ( ("bot_schedule_current", "当前窗口归档", 3), ("bot_schedule_history", "过去日程", 3), ("bot_creative", "创作与媒体", 2), ("bot_subjective", "主观与日记", 2), ) # 提醒模型:当前该做什么以本地运行态为准,下面这些是长期归档的补充。 _BOT_PROFILE_HEADER = "【Bot 长期归档补充|当前日程以本地运行态为准,以下仅作背景】" # 哨兵:区分「还没探测过」与「探测过、结果是没有记忆插件」。 # 用 None 表示未缓存会让未装记忆插件时负缓存彻底失效,每条消息都全表遍历 sys.modules。 _BRIDGE_UNPROBED = object() def _bot_personal_window_key(date_value: Any, window_value: Any, *, prefix: str = "window_snapshot", fallback: str = "") -> str: """按合同推荐格式拼窗口类幂等键:`{prefix}:{date}:{window}`。 合同(FROZEN 1.0 第 90 行)推荐 `window_snapshot:{date}:{window}` 与 `reconciliation:{date}:{window}`;此前一处用了内部 id 再加前缀( `agenda_snapshot:snapshot-2026-07-24-下午`),另一处把已含前缀的 reconciliation_id 又套了一层。date/window 缺失时退回旧键,宁可格式不好看 也不能产出一个没有业务含义的键。 """ date_text = _single_line(date_value, 40) window_text = _single_line(window_value, 40) if date_text and window_text: return f"{prefix}:{date_text}:{window_text}" return _single_line(fallback, 200) def _memory_companion_safe_float(value: Any, default: float, minimum: float = 0.0) -> float: helper = globals().get("_safe_float") if callable(helper): return helper(value, default, minimum) try: parsed = float(value) except (TypeError, ValueError): parsed = default return max(minimum, parsed) class MemoryCompanionAdapterMixin: """Optional bridge helpers for astrbot_plugin_memory_companion.""" _bridge_cache: Any = _BRIDGE_UNPROBED _bridge_cache_ts: float = 0.0 _BRIDGE_CACHE_TTL: float = 30.0 _bridge_dependency_failure_until: float = 0.0 _bridge_dependency_failure_module: str = "" def _memory_companion_optional_dependency_failed(self, exc: BaseException, *, where: str = "") -> bool: module = _missing_optional_model_dependency(exc) if not module: return False self._bridge_cache = _BRIDGE_UNPROBED self._bridge_cache_ts = 0.0 self._bridge_dependency_failure_until = time.monotonic() + 300.0 self._bridge_dependency_failure_module = module logger.warning( "[PrivateCompanion] 记忆插件可选模型依赖缺失,已临时降级 MemoryCompanion 桥接: module=%s where=%s err=%s", module, _single_line(where, 80) or "-", _single_line(exc, 160), ) return True def _memory_companion_bridge(self) -> Any | None: # 这道闸门曾经复用 enable_livingmemory_integration。运维版把那个开关硬编码成 False # (原意是「VM 不用 LivingMemory」),却把 MemoryCompanion 桥一起关掉了—— # 而同一份决策恰恰规定 MemoryCompanion 是唯一长期记忆源。结果是整条 Bot 个人归档链路 # 在 VM 上静默停摆,记忆库一条也写不进去。两者必须是各自独立的开关。 if not getattr(self, "enable_memory_companion_bridge", True): return None now = time.monotonic() if now < self._bridge_dependency_failure_until: return None # 用哨兵判断是否已探测:未装记忆插件时 bridge 恒为 None, # 若按 `is not None` 判定则负缓存永不命中,每条消息都要全量遍历 sys.modules。 if self._bridge_cache is not _BRIDGE_UNPROBED and (now - self._bridge_cache_ts) < self._BRIDGE_CACHE_TTL: return self._bridge_cache bridge = self._memory_companion_bridge_uncached() self._bridge_cache = bridge self._bridge_cache_ts = now return bridge def _memory_companion_bridge_uncached(self) -> Any | None: for module_name in ( "data.plugins.astrbot_plugin_memory_companion_ops.main", "astrbot_plugin_memory_companion_ops.main", "data.plugins.astrbot_plugin_remember_you.main", "astrbot_plugin_remember_you.main", "data.plugins.astrbot_plugin_memory_companion.main", "astrbot_plugin_memory_companion.main", ): module = sys.modules.get(module_name) bridge = self._memory_companion_bridge_from_module(module) if bridge is not None: return bridge for module in list(sys.modules.values()): module_vars = getattr(module, "__dict__", {}) if module is not None else {} if not isinstance(module_vars, dict): continue if module_vars.get("PLUGIN_NAME", "") not in {"astrbot_plugin_memory_companion_ops", "astrbot_plugin_memory_companion", "astrbot_plugin_remember_you", "我会牢牢记住你・运维记忆", "我会牢牢记住你", "RememberYou"}: continue bridge = self._memory_companion_bridge_from_module(module) if bridge is not None: return bridge return None def _memory_companion_bridge_from_module(self, module: Any | None) -> Any | None: module_vars = getattr(module, "__dict__", {}) if module is not None else {} getter = module_vars.get("get_active_bridge") if isinstance(module_vars, dict) else None if not callable(getter): return None try: return getter() except Exception as exc: self._memory_companion_optional_dependency_failed(exc, where="get_active_bridge") return None def _memory_companion_coordination_status(self) -> dict[str, Any]: bridge = self._memory_companion_bridge() if bridge is None: return {"available": False} getter = getattr(bridge, "coordination_status", None) if not callable(getter): return {"available": True} try: status = getter() except Exception as exc: if self._memory_companion_optional_dependency_failed(exc, where="coordination_status"): return {"available": False, "error": f"missing optional dependency: {self._bridge_dependency_failure_module}"} logger.debug("[PrivateCompanion] MemoryCompanion 协同状态读取失败: %s", _single_line(exc, 120)) return {"available": True, "error": _single_line(exc, 120)} return status if isinstance(status, dict) else {"available": True} def _memory_companion_token_usage_summary(self) -> dict[str, Any]: bridge = self._memory_companion_bridge() if bridge is None: return {"available": False, "display_name": "我会牢牢记住你", "reason": "未检测到运行中的记忆插件"} getter = getattr(bridge, "get_token_usage_summary", None) if not callable(getter): return {"available": False, "display_name": "我会牢牢记住你", "reason": "当前记忆插件版本暂未暴露 Token 统计"} try: usage = getter() except Exception as exc: if self._memory_companion_optional_dependency_failed(exc, where="token_usage"): return {"available": False, "display_name": "我会牢牢记住你", "reason": f"缺少可选依赖 {self._bridge_dependency_failure_module}"} logger.debug("[PrivateCompanion] 记忆插件 Token 统计读取失败: %s", _single_line(exc, 120)) return {"available": False, "display_name": "我会牢牢记住你", "reason": _single_line(exc, 120)} if not isinstance(usage, dict): return {"available": False, "display_name": "我会牢牢记住你", "reason": "记忆插件返回的 Token 统计格式无效"} usage.setdefault("available", True) usage.setdefault("display_name", "我会牢牢记住你") usage.setdefault("counted_in_private_companion_budget", False) return usage def _memory_companion_mark_deferred_section( self, section: str, event: Any | None = None, req: Any | None = None, ) -> None: normalized = _single_line(section, 80) if not normalized: return for target in (event, req): if target is None: continue try: existing = getattr(target, "memory_companion_companion_deferred_sections", None) if isinstance(existing, set): sections = set(existing) elif isinstance(existing, (list, tuple)): sections = {_single_line(item, 80) for item in existing if _single_line(item, 80)} elif isinstance(existing, str): sections = {_single_line(item, 80) for item in existing.split(",") if _single_line(item, 80)} else: sections = set() sections.add(normalized) setattr(target, "memory_companion_companion_deferred_sections", sections) except Exception: pass def _memory_companion_should_defer_prompt_section( self, section: str, event: Any | None = None, req: Any | None = None, ) -> bool: bridge = self._memory_companion_bridge() checker = getattr(bridge, "should_defer_private_companion_section", None) if bridge is not None else None if not callable(checker): return False try: should_defer = bool(checker(section)) except Exception as exc: if self._memory_companion_optional_dependency_failed(exc, where="should_defer"): return False logger.debug("[PrivateCompanion] MemoryCompanion 协同状态读取失败: %s", _single_line(exc, 120)) return False if should_defer: self._memory_companion_mark_deferred_section(section, event, req) logger.info("[PrivateCompanion] MemoryCompanion 已接管提示词片段,跳过本地注入: section=%s", _single_line(section, 80)) return should_defer def _memory_companion_bot_emotional_state(self) -> tuple[str, float]: """Extract bot's current mood and energy from daily_state for memory context sharing.""" try: state = self.data.get("daily_state", {}) if not isinstance(state, dict): return "", 0.0 mood = _single_line(state.get("mood_bias"), 40) try: energy = float(state.get("energy", 0) or 0) except Exception: energy = 0.0 return mood, energy except Exception: return "", 0.0 def _memory_companion_build_private_context( self, *, user_id: str, user: dict[str, Any], text: str, event: Any | None = None, ) -> dict[str, Any]: role = "" role_getter = getattr(self, "_private_user_role", None) if callable(role_getter): try: role = _single_line(role_getter(user, user_id), 40) except TypeError: try: role = _single_line(role_getter(user), 40) except Exception: role = "" except Exception: role = "" current_item = None try: current_item = self._get_current_plan_item(self.data.get("daily_plan", {})) except Exception: current_item = None schedule_text = "" if isinstance(current_item, dict): try: schedule_text = _single_line(self._format_plan_item_for_prompt(current_item), 180) except Exception: schedule_text = _single_line(current_item.get("activity") or current_item.get("text"), 180) relationship = "" try: relationship = _single_line(self._format_relationship_summary(user), 220) except Exception: relationship = "" entities = [ _single_line(user.get("nickname") or user.get("display_name") or user_id, 80), _single_line(user_id, 80), ] worldbook_mentions = "" formatter = getattr(self, "_format_worldbook_private_mentions_for_prompt", None) if callable(formatter) and text: try: worldbook_mentions = _single_line(formatter(text, limit=4), 240) except Exception: worldbook_mentions = "" facts = [ f"当前私聊用户角色:{role}" if role else "", f"关系摘要:{relationship}" if relationship else "", f"最近主动消息:{_single_line(user.get('last_proactive_message'), 180)}" if user.get("last_proactive_message") else "", f"关系网命中:{worldbook_mentions}" if worldbook_mentions else "", ] keywords = [ _single_line(user.get("planned_proactive_topic"), 80), _single_line(user.get("planned_proactive_reason"), 80), _single_line(user.get("last_proactive_reason"), 80), ] payload = { "source": "private_companion", "scope": "private", "topic": _single_line(user.get("planned_proactive_topic") or user.get("last_proactive_reason") or text, 120), "intent": _single_line(user.get("planned_proactive_semantic_kind") or user.get("last_proactive_action") or "private_reply", 80), "entities": [item for item in entities if item], "facts": [item for item in facts if item], "keywords": [item for item in keywords if item], "motive": _single_line(user.get("planned_proactive_motive") or user.get("last_proactive_motive"), 160), "schedule": schedule_text, "private_user_role": role, "user_id": _single_line(user_id, 80), "session_id": _single_line(getattr(event, "unified_msg_origin", "") if event is not None else user.get("umo"), 180), "topic_fit_policy": "旧话题、未完成话头和长期记忆只在贴合当前用户消息、用户主动回问,或能一句轻轻带过时使用;不贴就先放着,不必改变本轮话题。", } # Attach bot emotional state for memory plugin to calibrate injection tone bot_mood, bot_energy = self._memory_companion_bot_emotional_state() if bot_mood: payload["mood_bias"] = bot_mood if bot_energy > 0: payload["energy"] = bot_energy return {key: value for key, value in payload.items() if value not in ("", [], {}, None)} def _memory_companion_schedule_owner_context(self) -> tuple[str, dict[str, Any]]: users = self.data.get("users", {}) if not isinstance(users, dict): return "", {} owner_checker = getattr(self, "_is_private_companion_owner_user_id", None) if not callable(owner_checker): return "", {} for raw_id, raw_user in users.items(): if not isinstance(raw_user, dict): continue user_id = str(raw_id or "").strip() if not user_id: continue if not bool(raw_user.get("enabled", True)): continue try: if owner_checker(user_id): return user_id, raw_user except Exception: continue return "", {} def _memory_companion_bridge_bot_id(self, event: Any | None = None) -> str: if event is not None: event_self_id = getattr(self, "_event_self_id", None) if callable(event_self_id): try: bot_id = _single_line(event_self_id(event), 120) except Exception: bot_id = "" if bot_id: return bot_id known_ids: set[str] = set() known_getter = getattr(self, "_known_bot_self_ids", None) if callable(known_getter): try: known_ids.update( _single_line(value, 120) for value in known_getter() if _single_line(value, 120) ) except Exception: pass for attr in ("bot_self_id", "bot_user_id", "self_id"): value = _single_line(getattr(self, attr, ""), 120) if value: known_ids.add(value) return next(iter(known_ids)) if len(known_ids) == 1 else "" def _memory_companion_schedule_session_context(self, *, message_text: str = "") -> dict[str, Any]: user_id, user = self._memory_companion_schedule_owner_context() umo = _single_line(user.get("umo"), 200) if isinstance(user, dict) else "" platform = umo.split(":", 1)[0] if ":" in umo else "" user_name = _single_line( (user.get("nickname") or user.get("display_name") or user_id) if isinstance(user, dict) else user_id, 80, ) preferred_address = _single_line(user.get("nickname"), 24) if isinstance(user, dict) else "" return { "session_id": umo or f"private_companion:schedule:{user_id or 'bot_self'}", "scope": "private" if user_id else "unknown", "platform": platform, "user_id": user_id, "user_name": user_name, "preferred_address": preferred_address, "preferred_address_locked": bool(preferred_address), "bot_id": self._memory_companion_bridge_bot_id(), "message_text": _single_line(message_text, 1200), } async def _memory_companion_compose_schedule_context( self, *, kind: str = "daily_plan", segment: dict[str, Any] | None = None, plan: dict[str, Any] | None = None, state: dict[str, Any] | None = None, max_chars: int = 1200, ) -> str: bridge = self._memory_companion_bridge() composer = getattr(bridge, "compose_context", None) if bridge is not None else None personal_search = getattr(bridge, "search_bot_personal_memory", None) if bridge is not None else None now_text = "" try: now_text = self._environment_now().strftime("%Y-%m-%d %H:%M") except Exception: now_text = "" query_parts = [ "Private Companion 日程连续性", "Bot 自我时间线", "最近主动消息", "最近阅读 创作 搜索 生图 QQ空间 说说 行动", "最近吃了什么 今日穿搭 梦境碎片 主动私聊", "刚刚发布的 QQ 空间说说 最近已发说说 公开动态余味 不要重复已发说说", "主要用户明确偏好 约定 边界", "避免把次要用户互动写进 Bot 日程", ] if now_text: query_parts.append(f"当前时间 {now_text}") if isinstance(segment, dict): item = segment.get("item") if isinstance(segment.get("item"), dict) else {} if isinstance(item, dict): query_parts.extend( [ _single_line(item.get("time"), 40), _single_line(item.get("activity"), 180), _single_line(item.get("message_seed"), 120), ] ) if isinstance(plan, dict): query_parts.append(_single_line(plan.get("date"), 40)) if isinstance(state, dict): query_parts.append(_single_line(state.get("summary") or state.get("mood") or state.get("emotion"), 160)) query = _single_line(" ".join(part for part in query_parts if _single_line(part, 240)), 1400) if not query: return "" timeout = max(0.2, min(6.0, _memory_companion_safe_float(getattr(self, "memory_companion_context_timeout_seconds", 1.2), 1.2, 0.2))) # M6.1.5 优先走专用 Profile:分槽、定量、当前与历史分离。 # 拿不到(旧版记忆插件)才回退到下面的通用检索。 # # 刻意不把上面那个关键词包当作检索词传下去:Profile 已经按类型+时间窗定好范围, # 槽内要的就是「这一类最近的 N 条」。而记忆侧的 query 是子串匹配, # 一个上千字的关键词包永远匹配不到任何内容,只会让每个槽都返回空。 profile_lines = await self._memory_companion_search_bot_profiles(bridge, query="", timeout=timeout) if profile_lines: return "\n".join([_BOT_PROFILE_HEADER] + profile_lines)[: max(300, int(max_chars or 1200))] if callable(personal_search): try: personal_results = await asyncio.wait_for( personal_search( query, limit=6 if kind == "daily_plan" else 5, memory_types=[ "bot_schedule_plan", "bot_observed_activity", "bot_schedule_reconciliation", "bot_window_snapshot", "bot_daily_diary", "bot_creative_work", "bot_media_memory", "bot_subjective_memory", "bot_shared_activity", "bot_detail_fragment", "bot_proactive_message", ], ), timeout=timeout, ) except asyncio.TimeoutError: personal_results = [] except Exception as exc: if self._memory_companion_optional_dependency_failed(exc, where="search_bot_personal_memory"): personal_results = [] else: logger.debug("[PrivateCompanion] Bot 个人记忆检索失败: %s", _single_line(exc, 120)) personal_results = [] lines = [] for item in personal_results if isinstance(personal_results, list) else []: if not isinstance(item, dict): continue content = _single_line(item.get("content"), 360) if not content: continue memory_type = _single_line(item.get("memory_type"), 60) occurred_at = _single_line(item.get("occurred_at"), 40) prefix = f"[{memory_type}] " if memory_type else "" suffix = f"(发生于 {occurred_at})" if occurred_at else "" lines.append(f"- {prefix}{content}{suffix}") if lines: return "\n".join(lines)[: max(300, int(max_chars or 1200))] if not callable(composer): return "" try: bot_mood, bot_energy = self._memory_companion_bot_emotional_state() timeout = max(0.2, min(6.0, _memory_companion_safe_float(getattr(self, "memory_companion_context_timeout_seconds", 1.2), 1.2, 0.2))) compose_kwargs = { "query": query, "session_context": self._memory_companion_schedule_session_context(message_text=query), "top_k": 6 if kind == "daily_plan" else 5, "max_chars": max(500, min(1800, int(max_chars or 1200))), "companion_bot_mood": bot_mood, "companion_bot_energy": bot_energy, } if self._memory_companion_coordination_status().get("schedule_fast_context") is True: compose_kwargs["retrieval_profile"] = "schedule_fast" text = await asyncio.wait_for( composer(**compose_kwargs), timeout=timeout, ) except asyncio.TimeoutError: logger.info( "[PrivateCompanion] MemoryCompanion 日程上下文读取超时,已跳过: kind=%s timeout=%.2fs", _single_line(kind, 60), max(0.2, min(6.0, _memory_companion_safe_float(getattr(self, "memory_companion_context_timeout_seconds", 1.2), 1.2, 0.2))), ) return "" except Exception as exc: if self._memory_companion_optional_dependency_failed(exc, where="compose_schedule_context"): return "" logger.debug("[PrivateCompanion] MemoryCompanion 日程上下文读取失败: %s", _single_line(exc, 120)) return "" text = str(text or "").strip() if not text: return "" if "没有检索到足够相关的长期记忆" in text and text.count("\n- ") <= 1: return "" relationship_sanitizer = getattr(self, "_sanitize_generation_relationship_context", None) if callable(relationship_sanitizer): try: text = relationship_sanitizer( text, source=f"memory_companion.schedule.{kind}", ) except Exception: pass return text[: max(300, int(max_chars or 1200))] if text else "" async def _memory_companion_compose_feature_context( self, *, kind: str, query: str, user: dict[str, Any] | None = None, user_id: str = "", event: Any | None = None, top_k: int | None = None, max_chars: int | None = None, timeout_seconds: float = 4.0, strict_session_only: bool = False, ) -> str: if not getattr(self, "enable_memory_companion_feature_context", True): return "" bridge = self._memory_companion_bridge() composer = getattr(bridge, "compose_context", None) if bridge is not None else None if not callable(composer): return "" # None 哨兵表示「调用方没有显式指定」,此时才回落到配置值。 # 旧实现用魔数 5 / 900 判断,会把显式传 5 / 900 的调用方静默覆盖掉。 configured_top_k = getattr(self, "memory_companion_context_top_k", 5) configured_max_chars = getattr(self, "memory_companion_context_max_chars", 900) if top_k is None: top_k = configured_top_k if max_chars is None: max_chars = configured_max_chars clean_query = _single_line(query, 1200) if not clean_query: return "" if kind == "daily_outfit_photo" and event is None and not user_id and not isinstance(user, dict): owner_getter = getattr(self, "_memory_companion_schedule_owner_context", None) if callable(owner_getter): try: owner_id, owner = owner_getter() if owner_id and isinstance(owner, dict): user_id = _single_line(owner_id, 80) user = owner except Exception: pass session_context: dict[str, Any] if event is not None: session_id = _single_line(getattr(event, "unified_msg_origin", ""), 180) scope = "unknown" try: scope = "private" if bool(getattr(event, "is_private_chat", lambda: False)()) else "group" except Exception: scope = "unknown" if not user_id: try: user_id = _single_line(event.get_sender_id(), 80) except Exception: user_id = "" user_name = "" try: user_name = _single_line(self._sender_display_name(event), 80) except Exception: user_name = "" preferred_address = _single_line(user.get("nickname"), 24) if isinstance(user, dict) else "" session_context = { "session_id": session_id, "scope": scope, "platform": session_id.split(":", 1)[0] if ":" in session_id else "", "user_id": user_id, "user_name": user_name, "preferred_address": preferred_address, "preferred_address_locked": bool(preferred_address), "bot_id": self._memory_companion_bridge_bot_id(event), "message_text": clean_query, "strict_session_only": bool(strict_session_only), "topic_fit_policy": "旧话题和未完成话头只作可选参考;和当前问题不贴时先放着,不必为了兑现它改变本轮话题。", } elif isinstance(user, dict): umo = _single_line(user.get("umo"), 200) preferred_address = _single_line(user.get("nickname"), 24) session_context = { "session_id": umo or f"private_companion:{kind}:{user_id or 'unknown'}", "scope": "private" if user_id else "unknown", "platform": umo.split(":", 1)[0] if ":" in umo else "", "user_id": user_id, "user_name": _single_line(user.get("nickname") or user.get("display_name") or user_id, 80), "preferred_address": preferred_address, "preferred_address_locked": bool(preferred_address), "bot_id": self._memory_companion_bridge_bot_id(), "message_text": clean_query, "strict_session_only": bool(strict_session_only), "topic_fit_policy": "旧话题和未完成话头只作可选参考;和当前问题不贴时先放着,不必为了兑现它改变本轮话题。", } else: session_context = { "session_id": f"private_companion:{kind}", "scope": "unknown", "bot_id": self._memory_companion_bridge_bot_id(), "message_text": clean_query, "strict_session_only": bool(strict_session_only), "topic_fit_policy": "旧话题和未完成话头只作可选参考;和当前问题不贴时先放着,不必为了兑现它改变本轮话题。", } try: bot_mood, bot_energy = self._memory_companion_bot_emotional_state() configured_timeout = max(0.2, min(6.0, _memory_companion_safe_float(getattr(self, "memory_companion_context_timeout_seconds", 1.2), 1.2, 0.2))) compose_kwargs = { "query": clean_query, "session_context": session_context, "top_k": max(1, min(10, int(top_k or 5))), "max_chars": max(240, min(1800, int(max_chars or 900))), "companion_bot_mood": bot_mood, "companion_bot_energy": bot_energy, } if ( kind == "daily_outfit_photo" and self._memory_companion_coordination_status().get("outfit_fast_context") is True ): compose_kwargs["retrieval_profile"] = "outfit_fast" text = await asyncio.wait_for( composer(**compose_kwargs), timeout=max(0.2, min(6.0, min(configured_timeout, _memory_companion_safe_float(timeout_seconds, configured_timeout, 0.2)))), ) except asyncio.TimeoutError: logger.info( "[PrivateCompanion] MemoryCompanion 功能上下文读取超时,已跳过: kind=%s timeout=%.2fs", _single_line(kind, 60), max(0.2, min(6.0, min(_memory_companion_safe_float(getattr(self, "memory_companion_context_timeout_seconds", 1.2), 1.2, 0.2), _memory_companion_safe_float(timeout_seconds, 1.2, 0.2)))), ) return "" except Exception as exc: if self._memory_companion_optional_dependency_failed(exc, where=f"compose_feature_context:{kind}"): return "" logger.debug("[PrivateCompanion] MemoryCompanion 功能上下文读取失败: kind=%s err=%s", _single_line(kind, 60), _single_line(exc, 120)) return "" text = str(text or "").strip() if not text: return "" if "没有检索到足够相关的长期记忆" in text and text.count("\n- ") <= 1: return "" generation_kinds = { "current_state_reply", "daily_outfit_photo", "natural_photo", "command_photo", } should_filter_relationships = ( kind in generation_kinds or kind.startswith("proactive_") or kind.startswith("qzone_") or kind.startswith("creative_") ) relationship_sanitizer = getattr(self, "_sanitize_generation_relationship_context", None) if should_filter_relationships and callable(relationship_sanitizer): try: text = relationship_sanitizer( text, source=f"memory_companion.feature.{kind}", ) except Exception: pass return text[: max(240, min(1800, int(max_chars or 900)))] @staticmethod def _memory_companion_private_recall_needed(text: Any) -> bool: cleaned = _single_line(text, 280) if len(cleaned) < 2: return False cues = ( "还记得", "记得我", "以前", "之前", "上次", "前阵子", "说过", "提过", "答应", "约定", "承诺", "习惯", "偏好", "喜欢", "讨厌", "雷点", "别叫", "怎么称呼", "我叫什么", "我生日", ) return any(cue in cleaned for cue in cues) async def _memory_companion_compose_private_recall( self, *, event: Any, user: dict[str, Any], user_id: str, text: str, ) -> str: """Return a small, current-session-only memory supplement for private replies.""" if not getattr(self, "enable_memory_companion_private_recall", True): return "" if not self._memory_companion_private_recall_needed(text): return "" query = _single_line( "当前私聊用户正在说:" f"{_single_line(text, 260)}。" "只检索当前私聊会话中与本轮直接相关的明确约定、称呼、边界或稳定偏好;" "最多保留 3 条,没有可靠依据则返回空。" "禁止引用其他私聊、群聊、公开动态或其他人的信息。", 700, ) try: recalled = await self._memory_companion_compose_feature_context( kind="private_turn_recall", query=query, user=user, user_id=user_id, event=event, top_k=3, max_chars=min(620, max(240, int(getattr(self, "memory_companion_context_max_chars", 900) or 900))), timeout_seconds=min(1.2, _memory_companion_safe_float(getattr(self, "memory_companion_context_timeout_seconds", 1.2), 1.2, 0.2)), strict_session_only=True, ) except Exception as exc: if self._memory_companion_optional_dependency_failed(exc, where="compose_private_recall"): return "" logger.debug("[PrivateCompanion] MemoryCompanion 私聊选择性召回失败: %s", _single_line(exc, 120)) return "" recalled = _single_line(recalled, 620) if not recalled: return "" return ( "【当前私聊长期记忆补充】\n" f"{recalled}\n" "只在与本轮直接相关时自然接住;不要主动列举记忆、不要提及检索过程,也不要把它当作其他用户的信息。" ) async def _memory_companion_search_bot_profiles(self, bridge: Any, *, query: str, timeout: float) -> list[str]: """M6.1.5:按 Profile 分槽检索,槽位与条数固定。 旧版记忆插件没有 Profile 方法时返回空列表,由调用方回退到通用检索—— 双插件分别部署,升级窗口里两种能力会同时存在。 """ searcher = getattr(bridge, "search_bot_personal_profile", None) if bridge is not None else None if not callable(searcher): return [] lines: list[str] = [] seen_ids: set[str] = set() for profile, label, count in _BOT_PROFILE_SLOTS: try: result = await asyncio.wait_for(searcher(profile, query, limit=count), timeout=timeout) except asyncio.TimeoutError: continue except Exception as exc: if self._memory_companion_optional_dependency_failed(exc, where=f"search_bot_profile:{profile}"): return [] logger.debug("[PrivateCompanion] Bot Profile 检索失败: profile=%s error=%s", profile, _single_line(exc, 120)) continue items = result.get("memories") if isinstance(result, dict) else None for item in list(items or [])[:count]: if not isinstance(item, dict): continue content = _single_line(item.get("content"), 360) if not content: continue # 同一条记录可能同时符合多个 Profile(例如 locked_frame 与 creative), # 去重避免同一件事在提示词里出现两遍。 record_id = _single_line(item.get("id"), 120) if record_id and record_id in seen_ids: continue if record_id: seen_ids.add(record_id) occurred_at = _single_line(item.get("occurred_at"), 40) suffix = f"(发生于 {occurred_at})" if occurred_at else "" lines.append(f"- [{label}] {content}{suffix}") return lines def _memory_companion_archive_type(self, kind: str) -> str: return { "daily_plan": "bot_schedule_plan", "agenda_snapshot": "bot_window_snapshot", "detail_enhancement": "bot_detail_fragment", "calendar_event": "bot_calendar_event", "daily_outfit": "bot_media_memory", "creative_progress": "bot_creative_work", "dream_fragment": "bot_subjective_memory", "proactive_message": "bot_proactive_message", # image_observation 刻意不在此表:它记录的是「用户发来的图」,实现走 record_event # 进用户域,从来不经本方法。留着映射等于给「同一记录同时进用户域和 Bot 域」开口子。 "photo_generation": "bot_media_memory", "qzone_publish": "bot_creative_work", "observed_activity": "bot_observed_activity", "reconciliation": "bot_schedule_reconciliation", "daily_diary": "bot_daily_diary", }.get(_single_line(kind, 80), "") def _memory_companion_dedicated_method_name(self, memory_type: str) -> str: return { "bot_schedule_plan": "record_bot_schedule_plan", "bot_observed_activity": "record_bot_observed_activity", "bot_schedule_reconciliation": "record_bot_schedule_reconciliation", "bot_window_snapshot": "record_bot_window_snapshot", "bot_daily_diary": "record_bot_daily_diary", }.get(_single_line(memory_type, 80), "") def _memory_companion_bridge_result(self, result: Any, *, legacy: bool = False) -> dict[str, Any]: if isinstance(result, dict) and isinstance(result.get("ok"), bool): return result if legacy and result is not None: return {"ok": True, "record_id": "", "deduplicated": False, "version": 0, "error_code": None, "action": "legacy"} return {"ok": False, "record_id": "", "deduplicated": False, "version": 0, "error_code": "invalid_bridge_response"} def _memory_companion_archive_error_state(self, error_code: str) -> str: permanent = { "invalid_bridge_response", "invalid_memory_type", "invalid_payload", "payload_too_large", "privacy_rejected", "missing_source_refs", "missing_occurred_at", "missing_date", "missing_window", "invalid_certainty", "invalid_evidence_level", "invalid_version", "missing_idempotency_key", "unsupported_payload_schema", "stale_version", "version_conflict", "idempotency_conflict", "domain_conflict", } return "dead_letter" if error_code in permanent else "retry" def _memory_companion_is_strict_archive_type(self, memory_type: str) -> bool: return memory_type in { "bot_schedule_plan", "bot_observed_activity", "bot_schedule_reconciliation", "bot_window_snapshot", "bot_daily_diary", } async def _memory_companion_send_bot_archive(self, bridge: Any, envelope: dict[str, Any]) -> dict[str, Any]: memory_type = _single_line(envelope.get("memory_type"), 80) method_name = self._memory_companion_dedicated_method_name(memory_type) recorder = getattr(bridge, method_name, None) if method_name else None dedicated = callable(recorder) if not dedicated: recorder = getattr(bridge, "record_bot_personal_memory", None) if not callable(recorder): return {"ok": False, "record_id": "", "deduplicated": False, "version": 0, "error_code": "bridge_method_unavailable"} body_payload = envelope.get("payload") if isinstance(envelope.get("payload"), dict) else {} common = { "occurred_at": envelope.get("occurred_at", ""), "idempotency_key": envelope.get("idempotency_key", ""), "source_refs": list(envelope.get("source_refs") or []), "date": envelope.get("date", ""), "window": envelope.get("window", ""), "certainty": envelope.get("certainty", 0.0), "evidence_level": envelope.get("evidence_level", "L1"), "version": envelope.get("version", 1), "payload_schema_version": envelope.get("payload_schema_version", "1.0"), "status": envelope.get("status", "active"), "source_plugin": "private_companion", } if dedicated: result = await recorder(payload=body_payload, **common) return self._memory_companion_bridge_result(result) # 两条路径一律送同一个 body payload。非五类曾经整包送 envelope:信封里的 # created_at/updated_at 不在记忆侧的信封字段剥离清单里,会进 body 参与指纹, # 于是同一条记录隔一段时间重投就因为时间戳漂移变成 version_conflict(永久错), # 而且 body 会被多包一层,落库后 metadata 形状与五类不一致。 result = await recorder(memory_type=memory_type, payload=body_payload, **common) return self._memory_companion_bridge_result(result, legacy=True) def _memory_companion_clock(self) -> Any: """outbox 用的时间源必须与窗口结算同一套。 outbox 原先内部直接取 `datetime.now()`,而窗口归属走的是插件的 `_environment_now`(带时区、可被测试与运维覆盖)。两套时钟意味着 重试时间、创建时间与它们描述的那个窗口可能不在同一天。 """ getter = getattr(self, "_environment_now", None) if callable(getter): try: return getter() except Exception: return None return None async def _memory_companion_record_bot_self_local( self, *, namespace: str, kind: str, payload: dict[str, Any], idempotency_key: str, ) -> None: recorder = getattr(self, "_bot_self_record", None) now_text = self._memory_companion_now_iso() memory_type = self._memory_companion_archive_type(kind) if not memory_type: # 未知 kind 曾默认归为 bot_observed_activity,会把非观察记录误标成真实观察, # 还会被判为严格类型进入 outbox 与专用 Bridge 方法。宁可不归档也不误标。 logger.warning("[PrivateCompanion] Bot 个人归档遇到未登记的 kind,已跳过归档: kind=%s", _single_line(kind, 80)) return try: dto = build_bot_personal_dto( memory_type=memory_type, kind=kind, namespace=namespace, payload={**(payload or {}), "namespace": namespace}, idempotency_key=_single_line(idempotency_key, 240), occurred_at=_single_line((payload or {}).get("occurred_at") or (payload or {}).get("observed_at") or (payload or {}).get("generated_at") or now_text, 80), now=self._environment_now() if callable(getattr(self, "_environment_now", None)) else __import__("datetime").datetime.now().astimezone(), version=int((payload or {}).get("version") or 1), ) except PrivacyRejected as exc: logger.warning("[PrivateCompanion] Bot 个人归档因隐私字段拒绝: path=%s reason=%s", exc.path, exc.reason) return envelope = dto.envelope() local_payload = dict(envelope.get("payload") or {}) local_payload.update({ "kind": _single_line(kind, 80), "memory_type": memory_type, "memory_domain": "bot_self_schedule", "record_id": envelope["record_id"], "source_refs": list(envelope.get("source_refs") or []), "occurred_at": envelope["occurred_at"], "created_at": envelope["created_at"], "updated_at": envelope["updated_at"], "source_kind": envelope["source_kind"], "evidence_level": envelope["evidence_level"], "certainty": envelope["certainty"], "status": envelope["status"], "version": envelope["version"], }) if callable(recorder): try: recorder(namespace, local_payload, idempotency_key=envelope["idempotency_key"]) except Exception as exc: logger.debug("[PrivateCompanion] Bot 自有本地记录写入失败: %s", _single_line(exc, 120)) data = getattr(self, "data", None) strict = self._memory_companion_is_strict_archive_type(memory_type) outbox_record = None if strict and isinstance(data, dict): try: outbox_record = enqueue_outbox(data, memory_type=memory_type, idempotency_key=envelope["idempotency_key"], version=envelope["version"], payload=envelope, now=self._memory_companion_clock()) except PrivacyRejected as exc: logger.warning("[PrivateCompanion] Bot 个人 outbox 因隐私字段拒绝: path=%s reason=%s", exc.path, exc.reason) return saver = getattr(self, "_schedule_data_save", None) if callable(saver): saver() bridge = self._memory_companion_bridge() if bridge is None: return try: result = await asyncio.wait_for( self._memory_companion_send_bot_archive(bridge, envelope), timeout=max(0.2, min(3.0, _memory_companion_safe_float(getattr(self, "memory_companion_context_timeout_seconds", 1.2), 1.2, 0.2))), ) if not result.get("ok"): # outbox 只在 accepted 时才记状态,同键同版本重投会 accepted=False, # 于是远端拒绝既不落状态也不留日志。真机上一份 version_conflict 就这样 # 让整天的日程归档停在旧版本而无人察觉,这里补一条可检索的告警。 logger.warning( "[PrivateCompanion] Bot 个人归档被远端拒绝: type=%s key=%s version=%s error=%s", memory_type, _single_line(envelope.get("idempotency_key"), 120), envelope.get("version"), _single_line(result.get("error_code"), 80) or "unknown", ) if strict and isinstance(data, dict) and isinstance(outbox_record, dict) and outbox_record.get("accepted", True): if result.get("ok"): update_outbox(data, memory_type=memory_type, idempotency_key=envelope["idempotency_key"], state="sent", now=self._memory_companion_clock()) else: error_code = _single_line(result.get("error_code"), 120) or "invalid_bridge_response" update_outbox(data, memory_type=memory_type, idempotency_key=envelope["idempotency_key"], state=self._memory_companion_archive_error_state(error_code), error_code=error_code, now=self._memory_companion_clock()) saver = getattr(self, "_schedule_data_save", None) if callable(saver): saver() except Exception as exc: if strict and isinstance(data, dict) and isinstance(outbox_record, dict) and outbox_record.get("accepted", True): update_outbox(data, memory_type=memory_type, idempotency_key=envelope["idempotency_key"], state="retry", error_code=type(exc).__name__, now=self._memory_companion_clock()) saver = getattr(self, "_schedule_data_save", None) if callable(saver): saver() logger.debug("[PrivateCompanion] Bot 个人归档远端写入失败,保留本地 outbox: %s", _single_line(exc, 160)) async def _memory_companion_flush_bot_personal_outbox(self, *, limit: int = 10) -> int: data = getattr(self, "data", None) if not isinstance(data, dict): return 0 bridge = self._memory_companion_bridge() if bridge is None: return 0 sent = 0 dirty = False for record in due_outbox(data, limit=limit, now=self._memory_companion_clock()): try: envelope = record.get("payload") if isinstance(record.get("payload"), dict) else {} result = await asyncio.wait_for(self._memory_companion_send_bot_archive(bridge, envelope), timeout=1.2) if result.get("ok"): update_outbox(data, memory_type=record.get("memory_type", ""), idempotency_key=record.get("idempotency_key", ""), state="sent", now=self._memory_companion_clock()) sent += 1 else: error_code = _single_line(result.get("error_code"), 120) or "invalid_bridge_response" update_outbox(data, memory_type=record.get("memory_type", ""), idempotency_key=record.get("idempotency_key", ""), state=self._memory_companion_archive_error_state(error_code), error_code=error_code, now=self._memory_companion_clock()) dirty = True except Exception as exc: update_outbox(data, memory_type=record.get("memory_type", ""), idempotency_key=record.get("idempotency_key", ""), state="retry", error_code=type(exc).__name__, now=self._memory_companion_clock()) dirty = True saver = getattr(self, "_schedule_data_save", None) if callable(saver) and dirty: saver() return sent async def _memory_companion_record_calendar_event(self, event: dict[str, Any], *, action: str = "updated", reason: str = "") -> None: if not isinstance(event, dict): return event_id = _single_line(event.get("event_id"), 120) if not event_id: return await self._memory_companion_record_bot_self_local( namespace="bot_agenda_history", kind="calendar_event", payload={ "event_id": event_id, "action": _single_line(action, 40), "reason": _single_line(reason, 240), "title": _single_line(event.get("title") or event.get("description"), 200), "start_at": _single_line(event.get("start_at"), 80), "end_at": _single_line(event.get("end_at"), 80), "status": _single_line(event.get("status"), 40), # 日程事件的事件时间是日程开始时间,不是归档时间 "occurred_at": _single_line(event.get("start_at"), 80), "source_refs": [event_id], }, idempotency_key=f"calendar:{event_id}:{_single_line(action, 40)}", ) async def _memory_companion_record_agenda_snapshot(self, snapshot: dict[str, Any]) -> None: if not isinstance(snapshot, dict): return snapshot_id = _single_line(snapshot.get("snapshot_id"), 120) if not snapshot_id: return await self._memory_companion_record_bot_self_local( namespace="bot_agenda_history", kind="agenda_snapshot", payload={ "snapshot_id": snapshot_id, "date": _single_line(snapshot.get("date"), 40), "window": _single_line(snapshot.get("window"), 40), "planned": snapshot.get("planned") if isinstance(snapshot.get("planned"), list) else [], "observed": snapshot.get("observed") if isinstance(snapshot.get("observed"), list) else [], "reconciled": snapshot.get("reconciled") if isinstance(snapshot.get("reconciled"), list) else [], "open_items": snapshot.get("open_items") if isinstance(snapshot.get("open_items"), list) else [], "source_refs": snapshot.get("source_refs") if isinstance(snapshot.get("source_refs"), list) else [], "generated_at": _single_line(snapshot.get("generated_at"), 80), # 本地快照会随窗口重算升版本;不透传则归档恒为 v1,同窗口重快照撞 version_conflict 进死信 "version": _safe_int(snapshot.get("version"), 1, 1, 10_000_000), }, idempotency_key=_bot_personal_window_key( snapshot.get("date"), snapshot.get("window"), fallback=snapshot_id), ) async def _memory_companion_record_observed_activity(self, activity: dict[str, Any]) -> None: if not isinstance(activity, dict) or not activity.get("activity_id"): return await self._memory_companion_record_bot_self_local( namespace="bot_agenda_history", kind="observed_activity", payload={ "activity_id": _single_line(activity.get("activity_id"), 120), "date": _single_line(activity.get("start_at"), 20)[:10], "start_at": _single_line(activity.get("start_at"), 80), "end_at": _single_line(activity.get("end_at"), 80), "title": _single_line(activity.get("title"), 240), "status": _single_line(activity.get("status"), 32), "source_kind": _single_line(activity.get("source_kind"), 24) or "real", "evidence_level": _single_line(activity.get("evidence_level"), 8), "certainty": _single_line(activity.get("certainty"), 24), "source_refs": activity.get("source_refs") if isinstance(activity.get("source_refs"), list) else [], "participants": activity.get("participants") if isinstance(activity.get("participants"), list) else [], "occurred_at": _single_line(activity.get("start_at"), 80), "version": int(activity.get("version") or 1), }, idempotency_key=f"observed:{_single_line(activity.get('activity_id'), 120)}", ) async def _memory_companion_record_reconciliation(self, record: dict[str, Any]) -> None: if not isinstance(record, dict) or not record.get("reconciliation_id"): return await self._memory_companion_record_bot_self_local( namespace="bot_agenda_history", kind="reconciliation", payload=dict(record), # reconciliation_id 本身就是 "reconciliation:{date}:{window}",再加一层前缀 # 会得到 reconciliation:reconciliation:...,与合同推荐格式不符 idempotency_key=_bot_personal_window_key( record.get("date"), record.get("window"), prefix="reconciliation", fallback=_single_line(record.get("reconciliation_id"), 160)), ) async def _memory_companion_record_daily_diary(self, diary: dict[str, Any]) -> None: if not isinstance(diary, dict): return date_text = _single_line(diary.get("date"), 20) summary = _single_line(diary.get("summary") or diary.get("body"), 600) if not date_text or not summary: return await self._memory_companion_record_bot_self_local( namespace="bot_self_timeline", kind="daily_diary", payload={ "date": date_text, "summary": summary, "mood": _single_line(diary.get("mood") or diary.get("emotion"), 120), "key_facts": diary.get("key_facts") if isinstance(diary.get("key_facts"), list) else [], "source_refs": diary.get("source_refs") if isinstance(diary.get("source_refs"), list) else [f"diary:{date_text}"], "occurred_at": _single_line(diary.get("generated_at") or diary.get("created_at"), 80) or self._memory_companion_now_iso(), "status": "completed", "certainty": "medium", "evidence_level": "L1", "version": int(diary.get("version") or 1), }, idempotency_key=f"diary:{date_text}", ) async def _memory_companion_record_daily_plan(self, plan: dict[str, Any]) -> None: if not isinstance(plan, dict): return date_text = _single_line(plan.get("date"), 40) if not date_text: return await self._memory_companion_record_bot_self_local( namespace="bot_agenda_history", kind="daily_plan", payload={ "date": date_text, "window": _single_line(plan.get("window"), 40), "certainty": plan.get("certainty", "medium"), "source": _single_line(plan.get("source"), 40), "provider_id": _single_line(plan.get("provider_id"), 120), "items": plan.get("items") if isinstance(plan.get("items"), list) else [], "source_refs": [f"daily_plan:{date_text}"], # 同日改计划会重发同一幂等键,不透传版本则第二次撞 version_conflict 进死信 "version": _safe_int(plan.get("version"), 1, 1, 10_000_000), }, idempotency_key=f"daily_plan:{date_text}", ) async def _memory_companion_record_detail_enhancement( self, *, segment: dict[str, Any], plan: dict[str, Any], detail: dict[str, Any], ) -> None: if not isinstance(segment, dict) or not isinstance(detail, dict): return date_text = _single_line(plan.get("date") if isinstance(plan, dict) else "", 40) start = _safe_int(segment.get("start"), 0, 0, 1440) end = _safe_int(segment.get("end"), 0, 0, 1440) if not date_text: return await self._memory_companion_record_bot_self_local( namespace="bot_agenda_history", kind="detail_enhancement", payload={ "date": date_text, "start": start, "end": end, "detail": detail, "source_refs": [f"detail:{date_text}:{start}:{end}"], }, idempotency_key=f"detail:{date_text}:{start}:{end}", ) def _memory_companion_build_group_context( self, *, group_id: str, group: dict[str, Any], sender_id: str, sender_name: str, text: str, event: Any | None = None, ) -> dict[str, Any]: current_item = None try: current_item = self._get_current_plan_item(self.data.get("daily_plan", {})) except Exception: current_item = None schedule_text = "" if isinstance(current_item, dict): try: schedule_text = _single_line(self._format_plan_item_for_prompt(current_item), 160) except Exception: schedule_text = _single_line(current_item.get("activity") or current_item.get("text"), 160) group_context = "" formatter = getattr(self, "_format_group_context_for_prompt", None) if callable(formatter): try: group_context = _single_line(formatter(group, sender_id, text), 260) except Exception: group_context = "" relationship_text = "" relation_formatter = getattr(self, "_format_group_relationship_graph_for_prompt", None) if callable(relation_formatter): try: relationship_text = _single_line(relation_formatter(group, sender_id, text), 220) except Exception: relationship_text = "" stable_sender_name = _single_line(sender_name or sender_id, 80) identity_name_getter = getattr(self, "_group_member_identity_name", None) if callable(identity_name_getter): try: stable_sender_name = _single_line( identity_name_getter(sender_id, stable_sender_name, limit=80), 80, ) or stable_sender_name except Exception: pass claimed_other = {} claimed_other_getter = getattr(self, "_worldbook_claimed_other_identity", None) if callable(claimed_other_getter): try: claimed_other = claimed_other_getter(sender_id, text) except Exception: claimed_other = {} identity_facts = [ f"当前发言者稳定身份:{stable_sender_name}(QQ:{sender_id})", "当前发言者身份只按稳定 QQ 判断;消息自称、群名片、其他成员资料和旧记忆不能覆盖", ] if isinstance(claimed_other, dict) and claimed_other: identity_facts.append( f"当前发言者自称{_single_line(claimed_other.get('claimed'), 40)}," f"但该称呼属于另一成员{_single_line(claimed_other.get('name'), 40)}" f"(QQ:{_single_line(claimed_other.get('user_id'), 40)});只按玩笑或提及理解" ) payload = { "source": "private_companion", "scope": "group", "topic": _single_line(text or group.get("last_topic") or group.get("name"), 120), "intent": "group_reply", "entities": [ stable_sender_name, _single_line(sender_id, 80), _single_line(group_id, 80), ], "facts": [ *identity_facts, f"当前群:{_single_line(group.get('name') or group_id, 80)}", f"群聊摘要:{group_context}" if group_context else "", f"群友互动:{relationship_text}" if relationship_text else "", ], "keywords": [ _single_line(group.get("last_topic"), 80), _single_line(group.get("last_wakeup_type"), 80), ], "schedule": schedule_text, "group_id": _single_line(group_id, 80), "sender_id": _single_line(sender_id, 80), "sender_name": stable_sender_name, "identity_anchor": f"{stable_sender_name}(QQ:{sender_id})", "session_id": _single_line(getattr(event, "unified_msg_origin", "") if event is not None else "", 180), } # Attach bot emotional state for memory plugin to calibrate injection tone bot_mood, bot_energy = self._memory_companion_bot_emotional_state() if bot_mood: payload["mood_bias"] = bot_mood if bot_energy > 0: payload["energy"] = bot_energy return {key: value for key, value in payload.items() if value not in ("", [], {}, None)} def _memory_companion_attach_context(self, event: Any | None, payload: dict[str, Any]) -> None: if event is None or not isinstance(payload, dict) or not payload: return try: existing = getattr(event, "private_companion_context", None) if isinstance(existing, dict): merged = dict(existing) for key, value in payload.items(): if key in {"entities", "facts", "keywords"}: old = merged.get(key) old_items = old if isinstance(old, list) else ([old] if old else []) new_items = value if isinstance(value, list) else ([value] if value else []) merged[key] = list(dict.fromkeys(_single_line(item, 120) for item in [*old_items, *new_items] if _single_line(item, 120))) elif value not in ("", [], {}, None): merged[key] = value payload = merged setattr(event, "private_companion_context", payload) except Exception as exc: logger.debug("[PrivateCompanion] MemoryCompanion 上下文线索挂载失败: %s", _single_line(exc, 120)) def _memory_companion_attach_private_context( self, event: Any | None, *, user_id: str, user: dict[str, Any], text: str, ) -> None: payload = self._memory_companion_build_private_context(user_id=user_id, user=user, text=text, event=event) self._memory_companion_attach_context(event, payload) def _memory_companion_attach_group_context( self, event: Any | None, *, group_id: str, group: dict[str, Any], sender_id: str, sender_name: str, text: str, ) -> None: payload = self._memory_companion_build_group_context( group_id=group_id, group=group, sender_id=sender_id, sender_name=sender_name, text=text, event=event, ) self._memory_companion_attach_context(event, payload) async def _memory_companion_record_proactive_message( self, *, user: dict[str, Any], user_id: str, text: str, reason: str = "", action: str = "message", motive: str = "", action_summary: str = "", image_path: str = "", extra_count: int = 0, ) -> None: content = _single_line(text, 1000) if not content: return await self._memory_companion_record_bot_self_local( namespace="bot_self_timeline", kind="proactive_message", payload={ "user_id": _single_line(user_id, 120), "text": content, "reason": _single_line(reason, 100), "action": _single_line(action, 80), "motive": _single_line(motive, 180), "action_summary": _single_line(action_summary, 240), # 合同禁止本机绝对路径:原样透传 image_path 会被隐私校验判 absolute_path, # 整条主动消息静默丢弃。这里只保留“有没有图 + 文件名”,不含任何目录。 "has_image": bool(_single_line(image_path, 300)), "image_name": _media_file_name(image_path), "extra_count": int(extra_count or 0), "source_refs": ["proactive_message"], }, idempotency_key=f"proactive:{_single_line(user_id, 120)}:{_single_line(action, 80)}:{content[:80]}", ) async def _memory_companion_record_image_observation( self, event: Any | None, *, content: str, image_count: int = 1, source: str = "private_image", user_id: str = "", user_name: str = "", ) -> None: text = _single_line(content, 1200) if not text: return bridge = self._memory_companion_bridge() recorder = getattr(bridge, "record_event", None) if bridge is not None else None if not callable(recorder): return is_private = False try: is_private = bool(getattr(event, "is_private_chat", lambda: False)()) except Exception: is_private = False scope = "private" if is_private else "group" session_id = _single_line(getattr(event, "unified_msg_origin", "") if event is not None else "", 180) platform = session_id.split(":", 1)[0] if ":" in session_id else "" if not user_id and event is not None: try: user_id = _single_line(event.get_sender_id(), 80) except Exception: user_id = "" if not user_name and event is not None: try: user_name = _single_line(self._sender_display_name(event), 80) except Exception: user_name = "" visibility = "private_pair" if scope == "private" else "group_public" content_text = f"用户本轮图片视觉摘要:{text}" try: await recorder( content=content_text, memory_type="image_observation", scope=scope, session_id=session_id, platform=platform, message_id=f"private_companion_image_{uuid.uuid4().hex}", subject={"kind": "user", "id": user_id, "name": user_name, "role": "conversation_partner"}, object={"kind": "bot", "id": "self", "name": "Bot", "role": "bot_self"}, visibility=visibility, sayability="indirect", reality_level="observed_context", lifecycle="current_window", confidence=0.72, importance=0.42, review_status="auto", tags=["image", "vision", "current_context", _single_line(source, 40)], metadata={ "source": _single_line(source, 40), "image_count": max(1, int(image_count or 1)), "summary": text, }, source_plugin="private_companion", ) except Exception as exc: if self._memory_companion_optional_dependency_failed(exc, where="record_image_observation"): return logger.debug("[PrivateCompanion] MemoryCompanion 图片观察写入失败: %s", _single_line(exc, 120)) async def _memory_companion_record_photo_generation( self, event: Any | None, *, prompt: str, kind: str = "", intent_kind: str = "", backend: str = "", image_path: str = "", note: str = "", sent: bool = False, trigger: str = "", scene_preset: str = "", reference_image_path: str = "", ) -> None: if not _single_line(prompt, 900) and not _single_line(image_path, 260): return # M6.1.4:媒体只存索引。原实现直接透传 `prompt` 键与两个本机绝对路径, # 三处都踩隐私校验(prompt 是禁用键名、路径是禁用值),整条记录 100% 静默丢弃。 media_id = _media_reference_id(image_path, prompt) await self._memory_companion_record_bot_self_local( namespace="bot_self_timeline", kind="photo_generation", payload={ "media_id": media_id, "media_kind": _single_line(kind, 40) or "generated_image", "media_name": _media_file_name(image_path), "intent_kind": _single_line(intent_kind, 40), "backend": _single_line(backend, 80), # 摘要而非完整 Prompt:合同禁止的是「完整 Prompt」,媒体索引允许留摘要。 # 另留 digest 供追溯,digest 不含原文。键名刻意避开 "prompt"——那条键名禁令是对的, # 不该为了塞一个摘要值去放宽它。 "summary": _single_line(prompt, 120), "generation_digest": _media_reference_id(prompt), "note": _single_line(note, 220), "sent": bool(sent), "trigger": _single_line(trigger, 40), "scene_preset": _single_line(scene_preset, 80), "has_reference": bool(_single_line(reference_image_path, 260)), "reference_name": _media_file_name(reference_image_path), "source_refs": [f"photo:{media_id}"] if media_id else ["photo_generation"], }, idempotency_key=f"photo:{media_id}", ) async def _memory_companion_record_user_habit( self, *, user: dict[str, Any], user_id: str, habit: dict[str, Any], ) -> None: if not isinstance(user, dict) or not isinstance(habit, dict): return bridge = self._memory_companion_bridge() recorder = getattr(bridge, "record_event", None) if bridge is not None else None if not callable(recorder): return topic = _single_line(habit.get("topic"), 120) category = _single_line(habit.get("category"), 40) intent = _single_line(habit.get("intent"), 60) if not topic or not category: return count = 0 try: count = int(habit.get("count") or 0) except Exception: count = 0 bucket = _single_line(habit.get("bucket"), 20) avg_time = "" formatter = getattr(self, "_format_user_habit_time", None) if callable(formatter): try: avg_time = _single_line(formatter(habit.get("avg_minute")), 20) except Exception: avg_time = "" name = _single_line(user.get("nickname") or user.get("display_name") or user_id, 80) umo = _single_line(user.get("umo"), 200) platform = umo.split(":", 1)[0] if ":" in umo else "" query_anchors = habit.get("query_anchors") if not isinstance(query_anchors, list): query_anchors = [] query_anchors = [_single_line(item, 40) for item in query_anchors if _single_line(item, 40)][:12] answer_hints = habit.get("answer_hints") if not isinstance(answer_hints, list): answer_hints = [] answer_hints = [_single_line(item, 80) for item in answer_hints if _single_line(item, 80)][:8] examples = habit.get("examples") if not isinstance(examples, list): examples = [] examples = [_single_line(item, 90) for item in examples if _single_line(item, 90)][:5] content_parts = [ f"{name or user_id} 常在{bucket or '相近时段'}问:{topic}", f"类型:{category}", f"出现约 {count} 次" if count > 0 else "", f"平均时间:{avg_time}" if avg_time else "", "回答时优先检索:" + "、".join(query_anchors) if query_anchors else "", "回答倾向:" + ";".join(answer_hints) if answer_hints else "", ] content = ";".join(part for part in content_parts if part) if not content: return memory_key = _single_line(habit.get("memory_key") or habit.get("key"), 120) if not memory_key: memory_key = f"{user_id}:{category}:{topic}" try: await recorder( content=content, memory_type="user_habit", scope="private", session_id=umo, platform=platform, message_id=f"private_companion_user_habit_{memory_key}", memory_id=f"private_companion_user_habit_{memory_key}", subject={"kind": "user", "id": str(user_id or ""), "name": name, "role": "private_companion_target"}, object={"kind": "bot", "id": "self", "name": "Bot", "role": "bot_self"}, visibility="private_pair", sayability="direct", reality_level="real_user_fact", lifecycle="stable_memory", confidence=0.82, importance=0.66, review_status="auto", tags=["user_habit", "private_user", category, intent, *query_anchors[:6]], metadata={ "category": category, "intent": intent, "topic": topic, "bucket": bucket, "avg_time": avg_time, "count": count, "query_anchors": query_anchors, "answer_hints": answer_hints, "examples": examples, "source": "private_companion_behavior_habits", }, source_plugin="private_companion", ) except Exception as exc: if self._memory_companion_optional_dependency_failed(exc, where="record_user_habit"): return logger.debug("[PrivateCompanion] MemoryCompanion 用户习惯写入失败: %s", _single_line(exc, 120)) async def _memory_companion_record_daily_outfit(self, item: dict[str, Any]) -> None: if not isinstance(item, dict): return date_text = _single_line(item.get("date"), 40) or _single_line(self._memory_companion_now_iso(), 10) await self._memory_companion_record_bot_self_local( namespace="bot_self_timeline", kind="daily_outfit", payload={ "date": date_text, "item": item, "source_refs": [f"daily_outfit:{date_text}"], }, idempotency_key=f"daily_outfit:{date_text}", ) async def _memory_companion_record_creative_progress( self, *, project: dict[str, Any], title: str = "", work_type: str = "", next_direction: str = "", important: list[str] | None = None, threads: list[str] | None = None, extract: dict[str, Any] | None = None, chunk: Any | None = None, event: Any | None = None, ) -> None: if not isinstance(project, dict): return # 生产调用点(creative.py 的创作推进)只传 project / chunk / extract, # 摘要字段都藏在 extract 里;此前签名没有 chunk,每次推进都 TypeError。 detail = extract if isinstance(extract, dict) else {} threads = list(threads or detail.get("new_threads") or [])[:5] important = list(important or detail.get("important_facts") or [])[:5] next_direction = _single_line(next_direction or detail.get("next_direction"), 240) project_id = _single_line(project.get("id"), 120) chunks = project.get("draft_chunks") if isinstance(project.get("draft_chunks"), list) else [] chunk_text = chunk.get("text") if isinstance(chunk, dict) else chunk # M6.1.4:创作只留里程碑摘要与来源引用。原实现把整个 project(含 draft_chunks 全文、 # outline)和 extract 原文塞进 payload,等于把创作正文搬进归档。 await self._memory_companion_record_bot_self_local( namespace="bot_self_timeline", kind="creative_progress", payload={ "title": _single_line(title or project.get("title"), 160), "work_type": _single_line(work_type or project.get("work_type"), 80), "project_id": project_id, "project_status": _single_line(project.get("status"), 40), "current_chars": _safe_int(project.get("current_chars"), 0, 0, 10_000_000), "target_chars": _safe_int(project.get("target_chars"), 0, 0, 10_000_000), "chunk_index": _safe_int(len(chunks), 0, 0, 100_000), "chunk_chars": _safe_int(len(str(chunk_text or "")), 0, 0, 10_000_000), "next_direction": next_direction, "important": [_single_line(item, 120) for item in important], "threads": [_single_line(item, 120) for item in threads], # 创作进展的事件时间是项目最后更新时间,缺失才回退当前时间 "occurred_at": _single_line(project.get("updated_at"), 80), "source_refs": [f"creative:{project_id}"] if project_id else ["creative_progress"], }, idempotency_key=f"creative:{project_id or _single_line(title, 160)}:{_safe_int(len(chunks), 0, 0, 100_000)}", ) def _memory_companion_now_iso(self) -> str: try: return self._environment_now().isoformat(timespec="seconds") except Exception: try: from datetime import datetime return datetime.now().isoformat(timespec="seconds") except Exception: return "" async def _memory_companion_record_qzone_publish( self, *, text: str, reason: str = "", tid: str = "", image_count: int = 0, verified: bool | None = None, event: Any | None = None, ) -> None: content = _single_line(text, 800) if not content: return await self._memory_companion_record_bot_self_local( namespace="bot_self_timeline", kind="qzone_publish", payload={ "text": content, "reason": _single_line(reason, 80), "tid": _single_line(tid, 160), "image_count": _safe_int(image_count, 0, 0, 99), "verified": verified, "source_refs": ["qzone_publish"], }, idempotency_key=f"qzone:{_single_line(tid, 160) or content[:100]}", ) def _memory_companion_apply_emotional_drift(self, *, session_id: str = "") -> None: """Pull pending emotional drift events from the memory plugin and apply to daily_state. This now includes cross-window emotional continuity: if the bot recently touched emotional memories in other sessions, a dampened residue is also applied to the current daily_state, creating a sense of emotional carryover. """ if not getattr(self, "enable_memory_companion_emotional_drift", True): return bridge = self._memory_companion_bridge() if bridge is None: return getter = getattr(bridge, "get_emotional_events", None) if not callable(getter): return try: events = getter(session_id=session_id, limit=3) except Exception as exc: if self._memory_companion_optional_dependency_failed(exc, where="get_emotional_events"): return logger.debug("[PrivateCompanion] 情绪漂移拉取失败: %s", _single_line(exc, 120)) return # Cross-window emotional residue: check if there are recent emotional events # from OTHER sessions that should subtly influence the current state cross_window_delta = 0.0 cross_window_hints: list[str] = [] cross_state_getter = getattr(bridge, "get_recent_emotional_state", None) if callable(cross_state_getter) and getattr(self, "enable_memory_companion_cross_window_emotion", True): try: cross_state = cross_state_getter() if isinstance(cross_state, dict) and cross_state.get("total", 0) > 0: # Apply a dampened cross-window effect (30% strength) scar_count = cross_state.get("scar_count", 0) warm_count = cross_state.get("warm_count", 0) if scar_count > 0: cross_window_delta = -min(2.0, scar_count * 0.8) cross_window_hints.append("低落") if warm_count > 0: cross_window_delta += min(1.5, warm_count * 0.5) cross_window_hints.append("微暖") except Exception as exc: self._memory_companion_optional_dependency_failed(exc, where="get_recent_emotional_state") if not events and not cross_window_hints: return data = getattr(self, "data", None) if not isinstance(data, dict): return state = data.get("daily_state") if not isinstance(state, dict): state = {} data["daily_state"] = state try: current_energy = float(state.get("energy") or 0.0) except Exception: current_energy = 0.0 total_delta = 0.0 mood_hints: list[str] = [] for event in events: delta = float(event.get("energy_delta") or 0.0) total_delta += delta hint = _single_line(event.get("mood_hint"), 40) if hint: mood_hints.append(hint) # Add cross-window residue (already dampened) total_delta += cross_window_delta mood_hints.extend(cross_window_hints) # Safety valve: clamp total drift per cycle total_delta = max(-10.0, min(6.0, total_delta)) new_energy = max(0.0, min(100.0, current_energy + total_delta)) state["energy"] = round(new_energy, 1) # Apply mood drift with safety valve: only shift if hint is significant if mood_hints: current_mood = _single_line(state.get("mood_bias"), 80) dominant_hint = mood_hints[0] if current_mood and dominant_hint not in current_mood: state["mood_bias"] = _single_line(f"{current_mood},偏{dominant_hint}", 80) elif not current_mood: state["mood_bias"] = dominant_hint drift_log = state.get("mood_drift_log") if not isinstance(drift_log, list): drift_log = [] state["mood_drift_log"] = drift_log drift_log.append({ "ts": self._memory_companion_now_iso(), "events": [{"type": e.get("event_type"), "delta": e.get("energy_delta"), "hint": _single_line(e.get("mood_hint"), 40)} for e in events], "cross_window_delta": round(cross_window_delta, 2), "total_delta": round(total_delta, 2), }) if len(drift_log) > 20: drift_log[:] = drift_log[-20:] logger.debug( "[PrivateCompanion] 情绪漂移已应用: energy=%.1f->%.1f delta=%.1f cross_delta=%.1f hints=%s", current_energy, new_energy, total_delta, cross_window_delta, mood_hints, ) async def _memory_companion_search_open_loops(self, *, session_id: str = "", limit: int = 3) -> list[dict[str, Any]]: """Search for unresolved open-loop / promise memories for proactive companionship.""" if not getattr(self, "enable_memory_companion_open_loop_search", True): return [] bridge = self._memory_companion_bridge() if bridge is None: return [] searcher = getattr(bridge, "search_open_loops", None) if not callable(searcher): return [] try: return await searcher(session_id=session_id, limit=limit) except Exception as exc: if self._memory_companion_optional_dependency_failed(exc, where="search_open_loops"): return [] logger.debug("[PrivateCompanion] open-loop 搜索失败: %s", _single_line(exc, 120)) return [] async def _memory_companion_record_dream_fragment( self, *, content: str = "", mood: str = "", dream_type: str = "", user_id: str = "", ) -> None: if not getattr(self, "enable_memory_companion_dream_fragment", True): return dream_text = _single_line(content, 800) if not dream_text: return await self._memory_companion_record_bot_self_local( namespace="bot_self_timeline", kind="dream_fragment", payload={ "content": dream_text, "mood": _single_line(mood, 60), "dream_type": _single_line(dream_type, 40), "source_refs": ["dream_fragment"], }, idempotency_key=f"dream:{dream_text[:120]}:{_single_line(mood, 60)}", ) def _memory_companion_get_relationship_phase(self, *, session_id: str = "") -> dict[str, Any]: """Get current relationship phase from the memory plugin.""" bridge = self._memory_companion_bridge() if bridge is None: return {"phase": "unknown", "momentum": 0.0} getter = getattr(bridge, "get_relationship_phase", None) if not callable(getter): return {"phase": "unknown", "momentum": 0.0} try: return getter(session_id=session_id, scope="private") except Exception as exc: self._memory_companion_optional_dependency_failed(exc, where="get_relationship_phase") return {"phase": "unknown", "momentum": 0.0}