diff --git a/core/bridge.py b/core/bridge.py index f120882..3470fc8 100644 --- a/core/bridge.py +++ b/core/bridge.py @@ -25,6 +25,98 @@ _COMPANION_RELATIONSHIP_PHASES = { "intimate", "deeply_bonded", } +_COMPANION_INTERACTION_BANDS = { + "avoidant", + "hurt", + "relaxed", + "lively", + "warm", + "close", + "affectionate", +} +_COMPANION_EXPRESSION_CONTRACT = "companion_interaction_expression.v1" +_COMPANION_EXPRESSION_BEHAVIORS = { + "acknowledge", + "brief_reply", + "give_space", + "reply", + "clarify", + "light_humor", + "followup", + "support", + "shared_ritual", + "affectionate_expression", +} +_COMPANION_EXPRESSION_SAFETY_MODES = { + "normal", + "contact_boundary_passive", + "contact_boundary", + "p4_blocked", +} +_COMPANION_EXPRESSION_BLOCKERS = {"contact_boundary", "p4_safety"} +_COMPANION_EXPRESSION_REASON_CODES = { + "relationship_baseline_retained", + "interaction_band_applied", + "administrator_override_applied", + "owner_role_required", + "contact_boundary_passive_reengagement", + "p4_warmth_cap_applied", + "relationship_tone_applied", + "relationship_address_applied", + "relationship_followup_cap", + "intent_followup_suppressed", + "low_energy_expression_cap", + "down_mood_expression_cap", + "up_mood_expression_lift", + "relationship_proactive_cap", + "interaction_proactive_suppressed", + "schedule_proactive_suppressed", + "p4_blocked", + "contact_boundary", +} + + +def sanitize_companion_expression_decision(value: Any) -> dict[str, Any]: + """Accept only the bounded, request-scoped Companion expression contract.""" + + fallback = {"status": "invalid", "read_only": True, "decision": {}} + if type(value) is not dict or value.get("contract") != _COMPANION_EXPRESSION_CONTRACT: + return fallback + expression_band = value.get("expression_band") + if type(expression_band) is not str or expression_band not in _COMPANION_INTERACTION_BANDS: + return fallback + allowed_behaviors = value.get("allowed_behaviors") + if type(allowed_behaviors) not in {list, tuple} or len(allowed_behaviors) > 12: + return fallback + if any(type(item) is not str or item not in _COMPANION_EXPRESSION_BEHAVIORS for item in allowed_behaviors): + return fallback + if len(set(allowed_behaviors)) != len(allowed_behaviors): + return fallback + safety_mode = value.get("safety_mode") + if type(safety_mode) is not str or safety_mode not in _COMPANION_EXPRESSION_SAFETY_MODES: + return fallback + blocker = value.get("blocker") + if blocker is not None and (type(blocker) is not str or blocker not in _COMPANION_EXPRESSION_BLOCKERS): + return fallback + reason_codes = value.get("reason_codes") + if type(reason_codes) not in {list, tuple} or len(reason_codes) > 24: + return fallback + if any(type(item) is not str or item not in _COMPANION_EXPRESSION_REASON_CODES for item in reason_codes): + return fallback + if type(value.get("followup")) is not bool: + return fallback + return { + "status": "accepted", + "read_only": True, + "decision": { + "contract": _COMPANION_EXPRESSION_CONTRACT, + "expression_band": expression_band, + "allowed_behaviors": list(allowed_behaviors), + "safety_mode": safety_mode, + "blocker": blocker, + "reason_codes": list(reason_codes), + }, + } def sanitize_companion_relationship_projection(value: Any) -> dict[str, Any]: @@ -68,6 +160,20 @@ def sanitize_companion_relationship_projection(value: Any) -> dict[str, Any]: ) }, } + relationship_mode = value.get("relationship_mode") + if relationship_mode in {"normal", "owner_exclusive"}: + projection["relationship_mode"] = relationship_mode + current_interaction = value.get("current_interaction") + if type(current_interaction) is dict: + expression_band = current_interaction.get("expression_band") + if type(expression_band) is str and expression_band in _COMPANION_INTERACTION_BANDS: + projection["current_interaction"] = { + "expression_band": expression_band, + "label": clean_text(current_interaction.get("label"), 40), + "source": clean_text(current_interaction.get("source"), 40), + "reason": clean_text(current_interaction.get("reason"), 120), + "manual_override": current_interaction.get("manual_override") is True, + } return {"status": "accepted", "read_only": True, "projection": projection} diff --git a/core/injection.py b/core/injection.py index 99be507..52f8569 100644 --- a/core/injection.py +++ b/core/injection.py @@ -642,7 +642,7 @@ class InjectionComposer: scar = 0.0 hints: list[str] = [] if phase and phase != "neutral": - hints.append(f"关系阶段={phase}") + hints.append(f"当时关系情境={phase}") if scar >= 0.45: hints.append("伤痕感=高") try: diff --git a/core/models.py b/core/models.py index 9194db9..f74ef52 100644 --- a/core/models.py +++ b/core/models.py @@ -84,6 +84,12 @@ class SessionContext: companion_relationship_phase_label: str = "" companion_relationship_tone: str = "" companion_relationship_address_level: str = "" + companion_expression_contract: str = "" + companion_expression_band: str = "" + companion_expression_allowed_behaviors: tuple[str, ...] = () + companion_expression_safety_mode: str = "" + companion_expression_blocker: str = "" + companion_expression_reason_codes: tuple[str, ...] = () @property def current_target_id(self) -> str: diff --git a/core/service.py b/core/service.py index b7fc6de..b92fc29 100644 --- a/core/service.py +++ b/core/service.py @@ -23,7 +23,11 @@ from .astrbot_compat import ( remove_temp_text, sanitize_request_history, ) -from .bridge import sanitize_companion_relationship_projection, serialize_memory +from .bridge import ( + sanitize_companion_expression_decision, + sanitize_companion_relationship_projection, + serialize_memory, +) from .bot_personal_dto import ( BotPersonalArchiveDTO, BotPersonalValidationError, @@ -388,6 +392,7 @@ class MemoryCompanionService: ctx = await self.identity.resolve_event_context(event) self._sanitize_session_context_message_text(ctx) self._apply_companion_relationship_projection(ctx, event=event, req=req) + self._apply_companion_expression_decision(ctx, event=event, req=req) self._apply_private_companion_preferred_address(ctx, req=req, event=event) if self._private_companion_internal_generation_event(event): return @@ -733,6 +738,34 @@ class MemoryCompanionService: or getattr(event, "_private_companion_preferred_address_locked", False) ) + @staticmethod + def _apply_companion_expression_decision( + ctx: SessionContext, + *, + event: Any = None, + req: Any = None, + ) -> None: + if ctx.scope != "private": + return + raw_decision: Any = None + for target in (req, event): + if target is None: + continue + candidate = getattr(target, "_private_companion_expression_decision", None) + if candidate is not None: + raw_decision = candidate + break + consumed = sanitize_companion_expression_decision(raw_decision) + decision = consumed.get("decision") if isinstance(consumed, dict) else None + if not isinstance(decision, dict): + return + ctx.companion_expression_contract = clean_text(decision.get("contract"), 80) + ctx.companion_expression_band = clean_text(decision.get("expression_band"), 40) + ctx.companion_expression_allowed_behaviors = tuple(decision.get("allowed_behaviors") or ()) + ctx.companion_expression_safety_mode = clean_text(decision.get("safety_mode"), 60) + ctx.companion_expression_blocker = clean_text(decision.get("blocker"), 60) + ctx.companion_expression_reason_codes = tuple(decision.get("reason_codes") or ()) + def _sanitize_visible_timeline_text(self, text: Any) -> str: cleaned = clean_text(text, 1200) if not cleaned: @@ -7117,6 +7150,9 @@ class MemoryCompanionService: return "uncertain", "low_confidence" text = clean_text(query_text or ctx.message_text, 800) explicit_memory = self._message_is_contextual_memory_request(text) or self._message_requests_temporal_aggregate(text) + companion_cap_reason = self._companion_memory_mention_cap(ctx, explicit_memory=explicit_memory) + if companion_cap_reason: + return "tone", companion_cap_reason short_rest_check = self._message_is_short_rest_check(text) metadata = memory.metadata if isinstance(memory.metadata, dict) else {} mention_policy = clean_text(metadata.get("mention_policy"), 60) @@ -7185,6 +7221,23 @@ class MemoryCompanionService: return "tone", "indirect_memory" return "mention", "direct_relevance" + @staticmethod + def _companion_memory_mention_cap(ctx: SessionContext, *, explicit_memory: bool) -> str: + """Return a reason when Companion limits unsolicited memory expression.""" + + if explicit_memory or ctx.scope != "private" or not ctx.companion_expression_contract: + return "" + if ctx.companion_expression_blocker: + return "companion_expression:blocker" + if ctx.companion_expression_safety_mode != "normal": + return f"companion_expression:safety_{ctx.companion_expression_safety_mode}" + if ctx.companion_expression_band in {"avoidant", "hurt"}: + return f"companion_expression:band_{ctx.companion_expression_band}" + mention_capable = {"support", "followup", "shared_ritual"} + if not mention_capable.intersection(ctx.companion_expression_allowed_behaviors): + return "companion_expression:behavior_cap" + return "" + def _memory_age_days(self, memory: MemoryRecord) -> float | None: timestamp = clean_text(memory.occurred_at or memory.updated_at or memory.created_at, 80) parsed = self._parse_utc_datetime(timestamp) @@ -7930,6 +7983,11 @@ class MemoryCompanionService: message_id = clean_text(message_id or ctx.message_id, 160) if not message_id: return False + if ( + ctx.relationship_authority_source == "private_companion.relationship_score" + or ctx.companion_expression_contract + ): + return False state = self._get_relationship_phase(ctx) recent_ids = state.get("recent_touch_message_ids") if not isinstance(recent_ids, list): @@ -7954,12 +8012,7 @@ class MemoryCompanionService: recent_ids.append(message_id) state["recent_touch_message_ids"] = recent_ids[-self._RELATIONSHIP_TOUCH_HISTORY_LIMIT :] state["updated_at"] = utc_now() - if ctx.relationship_authority_source == "private_companion.relationship_score": - state["companion_phase_key"] = clean_text(ctx.companion_relationship_phase_key, 40) - state["companion_phase_label"] = clean_text(ctx.companion_relationship_phase_label, 40) - state["phase_authority"] = "private_companion.relationship_score" - else: - self._maybe_transition_phase(ctx, state) + self._maybe_transition_phase(ctx, state) self._save_relationship_phase_state() return True @@ -8034,6 +8087,11 @@ class MemoryCompanionService: def _update_address_evolution(self, ctx: SessionContext, text: str) -> None: """Track address evolution in the relationship phase state.""" + if ( + ctx.relationship_authority_source == "private_companion.relationship_score" + or ctx.companion_expression_contract + ): + return phase = self._detect_address_phase(text) if not phase: return @@ -8068,6 +8126,8 @@ class MemoryCompanionService: "不必每句都带称呼;关系阶段建议、历史称呼、显示名和旧记忆只作识别资料," "不能另造或追加亲昵称呼。若对方本轮明确要求改称呼,以本轮最新要求为准。" ) + if ctx.companion_expression_contract: + return "" if ctx.relationship_authority_source == "private_companion.relationship_score": label = clean_text(ctx.companion_relationship_phase_label, 40) or clean_text( ctx.companion_relationship_phase_key, diff --git a/page_api.py b/page_api.py index 2f48435..24e5ffe 100644 --- a/page_api.py +++ b/page_api.py @@ -339,10 +339,10 @@ class PluginPageApi: return self._err(f"历史对话导入回滚失败: {exc}", 500) async def persona_state(self): - """Return persona state: relationship phases, emotional events, address evolution, cross-window state.""" + """Return read-only expression coordination and memory-touch diagnostics.""" try: service = self.plugin.service - phases: list[dict[str, Any]] = [] + touch_trends: list[dict[str, Any]] = [] phase_state = getattr(service, "_relationship_phase_state", None) if isinstance(phase_state, dict): for key, state in phase_state.items(): @@ -358,19 +358,19 @@ class PluginPageApi: member_id = clean_text(identity.get("member_id"), 120) if member_id: identity_parts.append(f"member={member_id}") - phases.append({ + raw_momentum = state.get("momentum", 0.0) + momentum = float(raw_momentum) if type(raw_momentum) in {int, float} else 0.0 + trend_band = "rising" if momentum >= 0.08 else "cooling" if momentum <= -0.08 else "steady" + touch_trends.append({ "session_key": key, "session_label": " / ".join(part for part in identity_parts if part) or key, - "phase": state.get("phase", "acquaintance"), - "momentum": round(state.get("momentum", 0.0), 3), + "trend_band": trend_band, "touch_count": state.get("touch_count", 0), - "last_transition_at": state.get("last_transition_at", ""), + "legacy_context": clean_text(state.get("phase"), 40), "updated_at": state.get("updated_at", ""), - "current_address_phase": state.get("current_address_phase", ""), - "address_log": (state.get("address_log") or [])[-5:], }) - phases.sort(key=lambda p: p.get("updated_at", ""), reverse=True) - pending_emotional_events: list[dict[str, Any]] = [] + touch_trends.sort(key=lambda item: item.get("updated_at", ""), reverse=True) + memory_touch_events: list[dict[str, Any]] = [] event_queue = getattr(service, "_emotional_event_queue", None) if isinstance(event_queue, dict): for session_id, queue in event_queue.items(): @@ -379,7 +379,7 @@ class PluginPageApi: for event in queue[-3:]: if not isinstance(event, dict): continue - pending_emotional_events.append({ + memory_touch_events.append({ "session_id": session_id, "event_type": event.get("event_type"), "energy_delta": event.get("energy_delta"), @@ -393,24 +393,18 @@ class PluginPageApi: cross_window_state: dict[str, Any] = {"total": 0, "scar_count": 0, "warm_count": 0, "vulnerable_count": 0} if hasattr(service, "_get_cross_window_emotional_state"): cross_window_state = service._get_cross_window_emotional_state() - phases_list = getattr(service, "_PHASES", ["acquaintance", "familiar", "close", "intimate", "deeply_bonded"]) - thresholds = getattr(service, "_PHASE_THRESHOLDS", [0.0, 0.20, 0.45, 0.65, 0.85]) - bot_suggestions = getattr(service, "_BOT_ADDRESS_SUGGESTIONS", {}) return self._ok({ - "phases": phases[:20], - "pending_emotional_events": pending_emotional_events[:15], + "expression_coordination": { + "contract": "companion_interaction_expression.v1", + "mode": "request_scoped_read_only", + "expression_authority": "private_companion", + "memory_role": "recall_visibility_and_mention_cap", + "persistent": False, + }, + "memory_touch_trends": touch_trends[:20], + "memory_touch_events": memory_touch_events[:15], "time_of_day": time_of_day, - "phase_definitions": { - "phases": phases_list, - "thresholds": thresholds, - }, "cross_window_emotional_state": cross_window_state, - "address_phase_labels": { - "formal": "正式", - "casual": "随意", - "intimate": "亲密", - "playful": "玩笑", - }, "time_of_day_labels": { "late_night": "深夜", "dawn": "凌晨", @@ -419,8 +413,7 @@ class PluginPageApi: "evening": "傍晚", "night": "夜间", }, - "bot_address_suggestions": bot_suggestions, - "phase_labels": { + "legacy_context_labels": { "acquaintance": "初识", "familiar": "熟悉", "close": "亲近", @@ -429,7 +422,7 @@ class PluginPageApi: }, }) except Exception as exc: - return self._err(f"拟人维度数据读取失败: {exc}", 500) + return self._err(f"互动协同数据读取失败: {exc}", 500) async def acl_matrix(self): """Return all windows, ACL rules and policies in one shot for topology visualization.""" diff --git a/pages/记忆面板/app.js b/pages/记忆面板/app.js index 35b5506..632c4e8 100644 --- a/pages/记忆面板/app.js +++ b/pages/记忆面板/app.js @@ -3,7 +3,7 @@ const PAGE_ENDPOINT_PREFIX = "page"; const TRANSPARENT_IMAGE = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw=="; const VIEWS = { - objects: { title: "知识图谱", hint: "查看关系边、跨窗口线程、时间线、记忆节点和拟人维度概览。" }, + objects: { title: "知识图谱", hint: "查看关系边、跨窗口线程、时间线、记忆节点和互动协同概览。" }, film: { title: "群聊记忆", hint: "查看群聊范围内可召回、可管理的结构化记忆。" }, microscope: { title: "记忆显微镜", hint: "对比全库管理检索与指定会话中的实际召回和过滤。" }, relations: { title: "用户记忆", hint: "聚焦用户画像、偏好、称呼和关系声明。" }, @@ -36,7 +36,7 @@ const SECONDARY_NAV = { { id: "relations", label: "图谱边", sublabel: "人物、话题、事实与记忆关联", badge: "图谱" }, { id: "threads", label: "跨窗口线程", sublabel: "不同私聊/群聊之间的待办线索", badge: "线程" }, { id: "timeline", label: "时间线", sublabel: "最近记录的事件节点", badge: "时间" }, - { id: "persona", label: "拟人维度", sublabel: "关系阶段 · 情绪连续性 · 称呼演进", badge: "拟人" }, + { id: "persona", label: "互动协同", sublabel: "表达权威 · 记忆触动 · 情绪连续性", badge: "协同" }, ], microscope: [ { id: "query", label: "召回测试", sublabel: "输入一句话模拟检索", badge: "测试" }, @@ -4445,7 +4445,7 @@ function renderMemoryStructuredMetadata(memory) {
还没有足够的关系互动数据。随着对话积累,关系阶段会自然演进。
+暂无历史记忆触动记录。该区域只反映记忆被触动的趋势,不代表当前好感度或互动状态。