diff --git a/_conf_schema.json b/_conf_schema.json index e76be63..31f0e6a 100644 --- a/_conf_schema.json +++ b/_conf_schema.json @@ -262,6 +262,22 @@ "default": "", "invisible": true }, + "relationship_positive_stage_cap_key": { + "description": "普通用户正向亲密度阶段上限", + "type": "string", + "options": ["familiar", "close", "intimate", "deeply_bonded"], + "labels": ["熟悉", "亲近", "亲密", "深度联结"], + "hint": "普通用户的正向亲密度不会超过所选阶段。下调时既有正分会按旧上限与新上限比例仅降档一次;管理员专属关系和负分不受影响。", + "default": "deeply_bonded" + }, + "normal_interaction_band_cap": { + "description": "普通用户互动温度上限", + "type": "string", + "options": ["relaxed", "lively", "warm"], + "labels": ["放松", "活泼", "温暖"], + "hint": "普通用户的当前互动状态最多到这里。管理员账户与专属关系不受此温度上限影响。", + "default": "warm" + }, "owner_exclusive_label": { "description": "管理员专属关系名称", "type": "string", diff --git a/companion_interaction_expression.py b/companion_interaction_expression.py index ef69309..7a5079a 100644 --- a/companion_interaction_expression.py +++ b/companion_interaction_expression.py @@ -56,6 +56,8 @@ EXPRESSION_BAND_LABELS: dict[str, str] = { } COMMON_EXPRESSION_BANDS = tuple(band.value for band in ExpressionBand if band not in _OWNER_ONLY_BANDS) OWNER_EXPRESSION_BANDS = tuple(band.value for band in ExpressionBand) +NORMAL_INTERACTION_BAND_CAPS = ("relaxed", "lively", "warm") +DEFAULT_NORMAL_INTERACTION_BAND_CAP = "warm" @dataclass(frozen=True) @@ -92,6 +94,7 @@ class ExpressionInput: relationship_role: str = "friend" relationship_mode: str = "" relationship_baseline: Mapping[str, Any] | None = None + normal_interaction_band_cap: str = DEFAULT_NORMAL_INTERACTION_BAND_CAP current_interaction: str = "" bot_state: Mapping[str, Any] | None = None schedule: Mapping[str, Any] | None = None @@ -106,6 +109,7 @@ class ExpressionInput: "relationship_role": self.relationship_role, "relationship_mode": self.relationship_mode, "relationship_baseline": self.relationship_baseline, + "normal_interaction_band_cap": self.normal_interaction_band_cap, "current_interaction": self.current_interaction, "bot_state": self.bot_state, "schedule": self.schedule, @@ -183,6 +187,16 @@ def _band_from_interaction(value: Any) -> ExpressionBand | None: return _band(value) +def normalize_normal_interaction_band_cap(value: Any) -> str: + cap = _text(value) + return cap if cap in NORMAL_INTERACTION_BAND_CAPS else DEFAULT_NORMAL_INTERACTION_BAND_CAP + + +def _normal_interaction_cap_applies(*, role: str, score: int) -> bool: + del score + return role != "owner" + + def _baseline_band(score: int, *, owner_exclusive: bool = False) -> ExpressionBand: if owner_exclusive: return ExpressionBand.CLOSE @@ -304,6 +318,10 @@ def build_expression_decision(input_data: ExpressionInput | Mapping[str, Any] | return _blocked_decision("contact_boundary", "contact_boundary", reasons) score = _bounded_int(source.get("relationship_score"), 0, -1200, 1200) + normal_cap = normalize_normal_interaction_band_cap( + source.get("normal_interaction_band_cap") + or _mapping(source.get("current_interaction")).get("normal_interaction_band_cap") + ) relationship_baseline = _mapping(source.get("relationship_baseline")) band = _baseline_band(score, owner_exclusive=owner_exclusive) interaction_band = _band_from_interaction(source.get("current_interaction")) @@ -323,6 +341,10 @@ def build_expression_decision(input_data: ExpressionInput | Mapping[str, Any] | if band in _OWNER_ONLY_BANDS and not owner_account: band = ExpressionBand.WARM reasons.append("owner_role_required") + normal_cap_band = _band(normal_cap) or ExpressionBand.WARM + if _normal_interaction_cap_applies(role=role, score=score) and _BAND_INDEX[band] > _BAND_INDEX[normal_cap_band]: + band = normal_cap_band + reasons.append("normal_interaction_band_cap_applied") if contact_boundary: band = ExpressionBand.AVOIDANT reasons.append("contact_boundary_passive_reengagement") @@ -439,16 +461,27 @@ def current_interaction_projection( *, relationship_role: Any = "friend", relationship_mode: Any = "normal", + normal_interaction_band_cap: Any = None, + relationship_score: Any = 0, now: Any = None, ) -> dict[str, Any]: """Normalize persisted and legacy interaction state for runtime/page use.""" raw = dict(value) if isinstance(value, Mapping) else {} band = _band_from_interaction(raw) or ExpressionBand.RELAXED + role = _text(relationship_role) + score = _bounded_int(raw.get("relationship_score", relationship_score), 0, -1200, 1200) + normal_cap = normalize_normal_interaction_band_cap( + normal_interaction_band_cap if normal_interaction_band_cap is not None else raw.get("normal_interaction_band_cap") + ) allowed = allowed_expression_bands(relationship_role, relationship_mode) reason_codes: list[str] = [] if band.value not in allowed: band = ExpressionBand.WARM reason_codes.append("owner_role_required") + normal_cap_band = _band(normal_cap) or ExpressionBand.WARM + if _normal_interaction_cap_applies(role=role, score=score) and _BAND_INDEX[band] > _BAND_INDEX[normal_cap_band]: + band = normal_cap_band + reason_codes.append("normal_interaction_band_cap_applied") expires_at = _bounded_timestamp(raw.get("expires_at")) current_ts = _bounded_timestamp(now) manual = bool(raw.get("manual_override") or _text(raw.get("source")) == "manual") @@ -467,6 +500,7 @@ def current_interaction_projection( "updated_at": _bounded_timestamp(raw.get("updated_at")), "expires_at": expires_at, "manual_override": manual, + "normal_interaction_band_cap": normal_cap, "allowed_bands": list(allowed), "reason_codes": reason_codes, } @@ -526,10 +560,13 @@ __all__ = [ "ExpressionBand", "ExpressionDecision", "ExpressionInput", + "DEFAULT_NORMAL_INTERACTION_BAND_CAP", + "NORMAL_INTERACTION_BAND_CAPS", "OWNER_EXPRESSION_BANDS", "allowed_expression_bands", "build_expression_decision", "current_interaction_projection", + "normalize_normal_interaction_band_cap", "expression_decision_prompt", "resolve_expression_decision", ] diff --git a/constants.py b/constants.py index 29fa960..8cd0212 100644 --- a/constants.py +++ b/constants.py @@ -377,9 +377,15 @@ _SIMULATION_FALLBACK_EVENTS = [ # 默认用户模板(无文本,无需修改) _DEFAULT_USER_TEMPLATE = { "enabled": True, + "private_companion_enabled": True, + "group_relationship_enabled": False, + "private_memory_enabled": True, + "cross_group_memory_enabled": False, "auto_enabled": False, "auto_profile_created": False, "auto_profile_created_at": 0, + "group_profile_created_at": 0, + "last_group_observed_at": 0, "profile_origin": "", "relationship_role": "", "relationship_mode": "normal", diff --git a/core_store.py b/core_store.py index 7166c86..4003e0c 100644 --- a/core_store.py +++ b/core_store.py @@ -115,7 +115,13 @@ from .helpers import ( _today_key, ) from .relationship_policy import RELATIONSHIP_SCORE_MAX, RELATIONSHIP_SCORE_MIN -from .relationship_ledger import apply_natural_relationship_decay, normalize_relationship_mode +from .relationship_ledger import ( + apply_natural_relationship_decay, + clamp_relationship_positive_stage_cap, + normalize_relationship_mode, + normalize_relationship_positive_stage_cap_key, +) +from .companion_interaction_expression import current_interaction_projection, normalize_normal_interaction_band_cap from .config_migration import _ensure_config_parent_dir from .storage.store_manager import StoreManager from .person_context_contract import empty_person_store, ensure_person_store @@ -1303,6 +1309,30 @@ class CoreStoreMixin: user.get("relationship_mode"), user.get("relationship_role"), ) + positive_cap_key = normalize_relationship_positive_stage_cap_key( + getattr(self, "relationship_positive_stage_cap_key", "deeply_bonded") + ) + interaction_cap = normalize_normal_interaction_band_cap( + getattr(self, "normal_interaction_band_cap", "warm") + ) + cap_configuration_changed = ( + user.get("relationship_positive_stage_cap_key") != positive_cap_key + or user.get("normal_interaction_band_cap") != interaction_cap + ) + user["relationship_positive_stage_cap_key"] = positive_cap_key + user["normal_interaction_band_cap"] = interaction_cap + cap_result = clamp_relationship_positive_stage_cap(user, cap_key=positive_cap_key) + raw_interaction = user.get("current_interaction") + projected_interaction = current_interaction_projection( + raw_interaction, + relationship_role=user.get("relationship_role"), + relationship_mode=user.get("relationship_mode"), + relationship_score=user.get("relationship_score"), + normal_interaction_band_cap=interaction_cap, + now=_now_ts(), + ) + interaction_changed = projected_interaction != raw_interaction + user["current_interaction"] = projected_interaction decay_result = apply_natural_relationship_decay( user, policy=( @@ -1315,7 +1345,7 @@ class CoreStoreMixin: middle_rate=int(getattr(self, "relationship_decay_middle_per_day", 5)), late_rate=int(getattr(self, "relationship_decay_late_per_day", 8)), ) - if decay_result.get("changed"): + if cap_configuration_changed or cap_result.get("changed") or interaction_changed or decay_result.get("changed"): save_scheduler = getattr(self, "_schedule_data_save", None) if callable(save_scheduler): save_scheduler() @@ -1334,12 +1364,113 @@ class CoreStoreMixin: user["enabled"] = False elif not self._is_target_private_user(user_id, user): user["enabled"] = False + user["private_companion_enabled"] = bool(user.get("enabled")) if not user.get("nickname"): user["nickname"] = self.default_nickname if not user.get("style"): user["style"] = self.default_style return user + def _ensure_group_relationship_user_profile( + self, + *, + group_id: str, + sender_id: str, + qq_nickname: str = "", + group_card: str = "", + now: float | None = None, + ) -> tuple[dict[str, Any] | None, bool]: + """Create or refresh the unified relationship profile for a group speaker. + + The profile deliberately grants only group relationship expression. It + does not enable private companionship, proactive delivery, private or + cross-group memory, owner authority, or P4 eligibility. + """ + canonical_user_id = self._canonical_private_user_id(str(sender_id or "").strip()) + clean_group_id = _single_line(group_id, 80) + if not canonical_user_id or not clean_group_id or self._is_bot_self_user_id(canonical_user_id): + return None, False + users = self.data.setdefault("users", {}) + if not isinstance(users, dict): + users = {} + self.data["users"] = users + existing = users.get(canonical_user_id) + created = not isinstance(existing, dict) + user = self._get_user(canonical_user_id) + ts = float(now if now is not None else _now_ts()) + display_name = _single_line(qq_nickname, 24) or _single_line(group_card, 24) or canonical_user_id + + if created: + user["profile_origin"] = "group_observation" + user["group_profile_created_at"] = ts + user["auto_profile_created"] = True + user["auto_profile_created_at"] = ts + user["nickname"] = display_name + user["style"] = _single_line(getattr(self, "default_style", "温柔"), 24) or "温柔" + user["relationship_score"] = max( + RELATIONSHIP_SCORE_MIN, + min(RELATIONSHIP_SCORE_MAX, _safe_int(getattr(self, "default_relationship_score", 0), 0)), + ) + clamp_relationship_positive_stage_cap( + user, + cap_key=getattr(self, "relationship_positive_stage_cap_key", "deeply_bonded"), + reason_code="group_profile_default_positive_stage_cap", + ) + user["relationship_mode"] = normalize_relationship_mode( + user.get("relationship_mode"), + user.get("relationship_role"), + ) + user["current_interaction"] = { + "expression_band": str(getattr(self, "default_interaction_band", "relaxed") or "relaxed"), + "normal_interaction_band_cap": normalize_normal_interaction_band_cap( + getattr(self, "normal_interaction_band_cap", "warm") + ), + "source": "group_relationship_default", + "reason": "group_observation_profile_created", + "updated_at": ts, + "expires_at": 0, + "manual_override": False, + } + user["enabled"] = bool(canonical_user_id in set(self._configured_target_ids())) + user["auto_enabled"] = False + user["manual_enabled"] = False + user["manual_disabled"] = False + user["proactive_daily_limit"] = 0 + user["proactive_boundary_note"] = "群聊关系档案默认不主动触达" + + user["private_companion_enabled"] = bool(user.get("enabled")) + user["group_relationship_enabled"] = True + if created: + user["private_memory_enabled"] = False + user["cross_group_memory_enabled"] = False + user["p4_eligible"] = False + else: + user.setdefault("private_memory_enabled", bool(user.get("enabled"))) + user.setdefault("cross_group_memory_enabled", False) + user["last_group_observed_at"] = max(_safe_float(user.get("last_group_observed_at"), 0), ts) + scopes = user.setdefault("group_observation_scope_ids", []) + if not isinstance(scopes, list): + scopes = [] + user["group_observation_scope_ids"] = scopes + if clean_group_id not in scopes: + scopes.append(clean_group_id) + del scopes[:-32] + names = user.setdefault("group_observation_names", []) + if not isinstance(names, list): + names = [] + user["group_observation_names"] = names + if display_name and display_name != canonical_user_id and display_name not in names: + names.append(display_name) + del names[:-16] + sources = user.setdefault("profile_sources", []) + if not isinstance(sources, list): + sources = [] + user["profile_sources"] = sources + if "group_observation" not in sources: + sources.append("group_observation") + self._schedule_data_save() + return user, created + def _auto_profile_platform_set(self) -> set[str]: raw = getattr(self, "auto_profile_platforms", None) if isinstance(raw, str): @@ -1477,12 +1608,35 @@ class CoreStoreMixin: users = self.data.setdefault("users", {}) existing = users.get(canonical_user_id) if isinstance(users, dict) else None if isinstance(existing, dict): + changed = False observation_merger = getattr(self, "_merge_group_observation_into_private_user", None) if callable(observation_merger) and observation_merger( canonical_user_id, existing, now=float(now if now is not None else _now_ts()), ): + changed = True + if existing.get("profile_origin") == "group_observation" or bool(existing.get("group_relationship_enabled")): + observed_at = float(now if now is not None else _now_ts()) + sources = existing.setdefault("profile_sources", []) + if not isinstance(sources, list): + sources = [] + existing["profile_sources"] = sources + if "private_chat" not in sources: + sources.append("private_chat") + changed = True + if existing.get("private_profile_observed_at") != observed_at: + existing["private_profile_observed_at"] = observed_at + changed = True + if existing.get("profile_origin") == "group_observation": + existing["profile_origin"] = "group_observation_private" + changed = True + if sender_display_name and not _single_line(existing.get("nickname"), 24): + existing["nickname"] = self._auto_profile_nickname(canonical_user_id, sender_display_name) + changed = True + existing["private_companion_enabled"] = bool(existing.get("enabled")) + self._note_private_user_umo(canonical_user_id, existing, getattr(event, "unified_msg_origin", "")) + if changed: self._schedule_data_save() return existing, False if not bool(getattr(self, "enable_auto_user_profile_creation", True)): @@ -1499,6 +1653,11 @@ class CoreStoreMixin: RELATIONSHIP_SCORE_MIN, min(RELATIONSHIP_SCORE_MAX, _safe_int(getattr(self, "default_relationship_score", 0), 0)), ) + clamp_relationship_positive_stage_cap( + user, + cap_key=getattr(self, "relationship_positive_stage_cap_key", "deeply_bonded"), + reason_code="auto_profile_default_positive_stage_cap", + ) user["nickname"] = self._auto_profile_nickname(canonical_user_id, sender_display_name) observation_merger = getattr(self, "_merge_group_observation_into_private_user", None) if callable(observation_merger): @@ -1511,6 +1670,9 @@ class CoreStoreMixin: user["style"] = _single_line(getattr(self, "default_style", "温柔"), 24) or "温柔" user["current_interaction"] = { "expression_band": str(getattr(self, "default_interaction_band", "relaxed") or "relaxed"), + "normal_interaction_band_cap": normalize_normal_interaction_band_cap( + getattr(self, "normal_interaction_band_cap", "warm") + ), "source": "default_profile", "reason": "auto_profile_default", "updated_at": created_at, @@ -1522,6 +1684,10 @@ class CoreStoreMixin: user["manual_enabled"] = False user["manual_disabled"] = False user["enabled"] = bool(auto_enabled or canonical_user_id in set(self._configured_target_ids())) + user["private_companion_enabled"] = bool(user["enabled"]) + user["group_relationship_enabled"] = bool(user.get("group_relationship_enabled", False)) + user["private_memory_enabled"] = bool(user["enabled"]) + user["cross_group_memory_enabled"] = False proactive_enabled = bool(getattr(self, "default_proactive_enabled", False)) proactive_limit = _safe_int(getattr(self, "default_proactive_daily_limit", 0), 0, 0, 30) user["proactive_daily_limit"] = proactive_limit if proactive_enabled and auto_enabled else 0 diff --git a/group_observation.py b/group_observation.py index b8ea39d..91f2429 100644 --- a/group_observation.py +++ b/group_observation.py @@ -126,6 +126,9 @@ from .planning import ( normalize_story_plan, pick_detail_segment, ) +from .companion_interaction_expression import build_expression_decision, current_interaction_projection +from .relationship_ledger import apply_relationship_event, normalize_relationship_mode +from .relationship_policy import relationship_stage_for_score DEFAULT_AI_DAILY_NEWS_SOURCE = "B站 AI早报|bilibili:285286947" @@ -339,6 +342,128 @@ class GroupObservationMixin: stats["last_result_code"] = result_code stats["last_result_at"] = _now_ts() + def _group_sender_relationship_context_for_prompt(self, sender_id: str) -> str: + """Project only the current sender's relationship-expression contract.""" + canonicalizer = getattr(self, "_canonical_private_user_id", None) + canonical_id = canonicalizer(str(sender_id or "").strip()) if callable(canonicalizer) else str(sender_id or "").strip() + if not canonical_id: + return "" + users = self.data.get("users") if isinstance(getattr(self, "data", None), dict) else {} + if not isinstance(users, dict) or not isinstance(users.get(canonical_id), dict): + return "" + user_getter = getattr(self, "_get_user", None) + user = user_getter(canonical_id) if callable(user_getter) else users.get(canonical_id) + if not isinstance(user, dict) or not bool(user.get("group_relationship_enabled")): + return "" + role_getter = getattr(self, "_private_user_role", None) + role = role_getter(user, canonical_id) if callable(role_getter) else str(user.get("relationship_role") or "friend") + mode = normalize_relationship_mode(user.get("relationship_mode"), role) + policy = ( + getattr(self, "relationship_stage_policy", None) + if bool(getattr(self, "enable_custom_relationship_stage_policy", False)) + else None + ) + projection = relationship_stage_for_score(user.get("relationship_score", 0), policy) + phase = projection.get("phase") if isinstance(projection.get("phase"), dict) else {} + stage_label = ( + (_single_line(getattr(self, "owner_exclusive_label", "专属联结"), 20) or "专属联结") + if mode == "owner_exclusive" + else (_single_line(phase.get("label"), 24) or "初识") + ) + interaction = current_interaction_projection( + user.get("current_interaction"), + relationship_role=role, + relationship_mode=mode, + now=_now_ts(), + ) + decision = build_expression_decision( + { + "relationship_score": _safe_int(user.get("relationship_score"), 0), + "relationship_role": role, + "relationship_mode": mode, + "relationship_baseline": phase, + "current_interaction": interaction, + } + ) + interaction_label = _single_line(interaction.get("label"), 24) or _single_line(interaction.get("expression_band"), 24) or "放松" + nickname = _single_line(user.get("nickname"), 24) or canonical_id + return ( + "当前发言者关系表达:" + f"对象 {nickname};长期阶段 {stage_label};当前互动 {interaction_label};" + f"语气 {decision.tone};称呼尺度 {decision.address_style};回复长度 {decision.response_length}。" + "只据此调整对当前发言者的表达,不引用私聊正文、私聊记忆、其他群昵称或其他群内容;" + "也不因此授予主动联系、跨群记忆、owner 或 P4 权限。" + ) + + async def _settle_confirmed_group_relationship(self, event: AstrMessageEvent) -> dict[str, Any]: + """Settle one low-weight event only after a real group reply was sent.""" + if not bool(getattr(self, "enable_group_companion", False)) or not bool(getattr(self, "enable_group_member_profiles", False)): + return {"changed": False, "code": "feature_disabled"} + group_id = self._extract_group_id_from_event(event) + if not group_id or not self._group_enabled_for_event(group_id): + return {"changed": False, "code": "group_not_allowed"} + try: + sender_id = _single_line(event.get_sender_id(), 80) + except Exception: + sender_id = "" + if not sender_id or self._is_bot_self_user_id(sender_id): + return {"changed": False, "code": "invalid_sender"} + inbound_text = _single_line(getattr(event, "message_str", ""), 260) + if not inbound_text: + return {"changed": False, "code": "empty_message"} + guard = self._analyze_group_injection_guard(inbound_text, sender_id=sender_id) + if bool(guard.get("blocked")): + return {"changed": False, "code": "injection_guard_blocked"} + scene = getattr(event, "private_companion_group_scene", None) + trigger = _single_line(scene.get("trigger"), 40).lower() if isinstance(scene, dict) else "" + talking_to = _single_line(scene.get("talking_to"), 40).lower() if isinstance(scene, dict) else "" + directed = talking_to == "bot" or trigger in { + "at_bot", + "reply_bot", + "mention_bot_name", + "bot_conversation_followup", + } or trigger.startswith("group_wakeup_") + async with self._data_lock: + group = self._get_group(group_id) + active = self._group_active_conversation(group) + if not directed and _single_line(active.get("sender_id"), 80) != sender_id: + return {"changed": False, "code": "not_directed_to_sender"} + canonicalizer = getattr(self, "_canonical_private_user_id", None) + canonical_id = canonicalizer(sender_id) if callable(canonicalizer) else sender_id + users = self.data.get("users") if isinstance(self.data.get("users"), dict) else {} + user = users.get(canonical_id) if isinstance(users, dict) else None + if not isinstance(user, dict) or not bool(user.get("group_relationship_enabled")): + return {"changed": False, "code": "group_relationship_unavailable"} + message_id_getter = getattr(self, "_event_message_id", None) + message_id = _single_line(message_id_getter(event) if callable(message_id_getter) else "", 120) + event_source = ( + f"group-reply:{group_id}:{canonical_id}:{message_id}" + if message_id + else f"group-reply:{group_id}:{canonical_id}:{int(_now_ts() // 300)}:{inbound_text}" + ) + event_id = hashlib.sha256(event_source.encode("utf-8", errors="ignore")).hexdigest() + settled_at = _now_ts() + result = apply_relationship_event( + user, + 1, + reason_code="group_effective_interaction", + now=settled_at, + event_id=event_id, + positive_daily_cap=4, + event_window_seconds=6 * 3600, + positive_event_cap=1, + positive_stage_cap_key=getattr( + self, + "relationship_positive_stage_cap_key", + "deeply_bonded", + ), + ) + if result.get("changed"): + user["last_group_relationship_at"] = settled_at + user["group_relationship_event_count"] = _safe_int(user.get("group_relationship_event_count"), 0, 0) + 1 + self._save_data_sync() + return result + def _group_injection_guard_threshold(self) -> int: return _GROUP_INJECTION_GUARD_THRESHOLD @@ -2361,6 +2486,9 @@ class GroupObservationMixin: identity_guard = self._format_group_current_sender_identity_guard(group, sender_id=sender_id, text=text) if identity_guard: lines.append(identity_guard) + relationship_expression = self._group_sender_relationship_context_for_prompt(sender_id) + if relationship_expression: + lines.append(relationship_expression) pace = _single_line(atmosphere.get("pace"), 20) mood = _single_line(atmosphere.get("mood"), 20) if (pace and pace != "未知") or (mood and mood != "平稳"): @@ -2449,6 +2577,9 @@ class GroupObservationMixin: identity_guard = self._format_group_current_sender_identity_guard(group, sender_id=sender_id, text=text) if identity_guard: lines.append(identity_guard) + relationship_expression = self._group_sender_relationship_context_for_prompt(sender_id) + if relationship_expression: + lines.append(relationship_expression) details = [] pace = _single_line(atmosphere.get("pace"), 20) mood = _single_line(atmosphere.get("mood"), 20) diff --git a/main.py b/main.py index 658d220..09eb8b9 100644 --- a/main.py +++ b/main.py @@ -147,7 +147,7 @@ from .plugin_identity import ( ) from .runtime_compat import probe_runtime_capabilities from .relationship_policy import normalize_relationship_stage_policy -from .relationship_ledger import apply_relationship_event +from .relationship_ledger import apply_relationship_event, normalize_relationship_positive_stage_cap_key from .companion_interaction_expression import build_expression_decision, expression_decision_prompt from .user_rest_gate import UserRestGateMixin from .busy_reply_gate import BusyReplyGateMixin @@ -1452,6 +1452,12 @@ class PrivateCompanionPlugin( self.relationship_stage_policy = normalize_relationship_stage_policy( self._cfg_raw(c, "relationship_stage_policy", []) ) + self.relationship_positive_stage_cap_key = normalize_relationship_positive_stage_cap_key( + self._cfg_raw(c, "relationship_positive_stage_cap_key", "deeply_bonded") + ) + self.normal_interaction_band_cap = self._cfg_str(c, "normal_interaction_band_cap", "warm") + if self.normal_interaction_band_cap not in {"relaxed", "lively", "warm"}: + self.normal_interaction_band_cap = "warm" self.owner_exclusive_label = self._cfg_str(c, "owner_exclusive_label", "专属联结", "专属联结") self.owner_exclusive_tone = self._cfg_str(c, "owner_exclusive_tone", "温暖、亲近、稳定", "温暖、亲近、稳定") self.owner_exclusive_address_style = self._cfg_str(c, "owner_exclusive_address_style", "优先使用已确认的专属称呼", "优先使用已确认的专属称呼") @@ -2589,6 +2595,7 @@ class PrivateCompanionPlugin( event_window_seconds=int(getattr(self, "relationship_event_window_minutes", 30)) * 60, positive_event_cap=int(getattr(self, "relationship_positive_event_cap", 4)), negative_event_cap=int(getattr(self, "relationship_negative_event_cap", 12)), + positive_stage_cap_key=getattr(self, "relationship_positive_stage_cap_key", "deeply_bonded"), ) return bool(result.get("changed")) @@ -3720,6 +3727,15 @@ class PrivateCompanionPlugin( if isinstance(candidate, dict): self._confirm_outbound_text_candidate(candidate) await self._refresh_group_conversation_after_confirmed_send(event) + settlement = getattr(self, "_settle_confirmed_group_relationship", None) + if callable(settlement): + try: + await settlement(event) + except Exception as exc: + logger.warning( + "[PrivateCompanion] 群聊关系结算失败: %s", + _single_line(exc, 120), + ) @filter.on_decorating_result() async def suppress_group_llm_reply_block_before_send(self, event: AstrMessageEvent, *args, **kwargs): diff --git a/memory_companion_adapter.py b/memory_companion_adapter.py index bab1cf3..2678096 100644 --- a/memory_companion_adapter.py +++ b/memory_companion_adapter.py @@ -2338,6 +2338,72 @@ class MemoryCompanionAdapterMixin: self._memory_companion_optional_dependency_failed(exc, where="get_relationship_phase") return {"phase": "unknown", "momentum": 0.0} + async def _memory_companion_read_user_memory_summary( + self, + user_id: str, + *, + session_id: str = "", + limit: int = 3, + ) -> dict[str, Any]: + """Read a bounded, redacted Memory summary without affecting the chat path.""" + identity = _single_line(user_id, 120) + if not identity: + return {"available": False, "state": "invalid", "reason_code": "missing_user_identity"} + bridge = self._memory_companion_bridge() + if bridge is None: + reason = _single_line(getattr(self, "_bridge_last_status", {}).get("reason"), 80) + return {"available": False, "state": "degraded", "reason_code": reason or "bridge_unavailable"} + reader = getattr(bridge, "read_user_memory_summary", None) + if not callable(reader): + return {"available": False, "state": "unsupported", "reason_code": "summary_method_unavailable"} + try: + result = reader(user_id=identity, session_id=_single_line(session_id, 200), limit=max(1, min(5, int(limit or 3)))) + if asyncio.iscoroutine(result) or hasattr(result, "__await__"): + result = await result + except Exception as exc: + self._memory_companion_optional_dependency_failed(exc, where="read_user_memory_summary") + return {"available": False, "state": "degraded", "reason_code": "summary_read_failed"} + if ( + not isinstance(result, dict) + or result.get("contract") != "memory.user_memory_summary.v1" + or result.get("ok") is not True + or result.get("state") != "ready" + ): + state = _single_line(result.get("state"), 32) if isinstance(result, dict) else "invalid" + return {"available": False, "state": state or "degraded", "reason_code": "summary_unavailable"} + + raw_counts = result.get("counts") if isinstance(result.get("counts"), dict) else {} + counts: dict[str, int] = {} + for key in ("profile", "preference", "relationship"): + value = raw_counts.get(key, result.get(f"{key}_count", 0)) + counts[key] = _safe_int(value, 0, 0, 1_000_000) + counts["private_chat"] = _safe_int( + raw_counts.get("private_conversation", raw_counts.get("private_chat", 0)), + 0, + 0, + 1_000_000, + ) + + summaries: dict[str, str] = {} + category_alias = {"private_conversation": "private_chat"} + for item in result.get("summaries", []) if isinstance(result.get("summaries"), list) else []: + if not isinstance(item, dict): + continue + key = category_alias.get(_single_line(item.get("category"), 40), _single_line(item.get("category"), 40)) + if key not in {"profile", "preference", "relationship", "private_chat"} or key in summaries: + continue + text = _single_line(item.get("summary"), 160) + if text: + summaries[key] = text + return { + "schema_version": "memory.user_memory_summary.v1", + "available": True, + "state": "ready", + "counts": counts, + "summaries": summaries, + "workspace_path": "", + } + def _memory_companion_peek_relationship_phase(self, *, session_id: str = "") -> dict[str, Any]: """Read an existing Memory relationship phase without creating state.""" bridge = self._memory_companion_bridge() diff --git a/page_api.py b/page_api.py index b7ff8cd..360136a 100644 --- a/page_api.py +++ b/page_api.py @@ -29,9 +29,14 @@ from .constants import DEFAULT_DAILY_PLAN_ITEMS, PAGE_FONT_NAMES, PAGE_THEME_NAM from .config_migration import _ensure_config_parent_dir from .diagnostic_envelope import DIAGNOSTIC_ENVELOPE_VERSION, diagnostic_test_id, normalize_diagnostic_result from .helpers import _flat_get, _normalize_timezone_name, _path_text, _redact_outbound_secrets, _safe_int, _set_into_config, _set_today_key_timezone, _strip_internal_message_blocks, _text_looks_garbled, _text_similarity, _today_key -from .companion_interaction_expression import current_interaction_projection +from .companion_interaction_expression import current_interaction_projection, normalize_normal_interaction_band_cap from .reference_asset_gate import ReferenceAssetGate -from .relationship_ledger import normalize_relationship_mode, relationship_ledger_summary +from .relationship_ledger import ( + migrate_relationship_positive_stage_cap, + normalize_relationship_mode, + normalize_relationship_positive_stage_cap_key, + relationship_ledger_summary, +) from .relationship_policy import ( normalize_relationship_stage_policy, relationship_stage_for_score, @@ -192,6 +197,8 @@ class PrivateCompanionPageApi(PrivateCompanionPageApiQzoneMixin, PrivateCompanio user.get("current_interaction"), relationship_role=role, relationship_mode=relationship_mode, + relationship_score=user.get("relationship_score"), + normal_interaction_band_cap=getattr(self.plugin, "normal_interaction_band_cap", "warm"), now=time.time(), ) expression_projection = { @@ -9859,7 +9866,7 @@ class PrivateCompanionPageApi(PrivateCompanionPageApiQzoneMixin, PrivateCompanio ) def _user_summary(self, user_id: str, user: dict[str, Any]) -> dict[str, Any]: - last_seen = user.get("last_seen", 0) + last_seen = max(self._float(user.get("last_seen")), self._float(user.get("last_group_observed_at"))) last_sent = user.get("last_sent", 0) user_id_text = str(user_id) is_qq_user = user_id_text.isdigit() @@ -9901,8 +9908,39 @@ class PrivateCompanionPageApi(PrivateCompanionPageApiQzoneMixin, PrivateCompanio user.get("current_interaction"), relationship_role=role, relationship_mode=relationship_mode, + relationship_score=user.get("relationship_score"), + normal_interaction_band_cap=getattr(self.plugin, "normal_interaction_band_cap", "warm"), now=time.time(), ) + profile_sources = [ + self._single_line(item, 40) + for item in (user.get("profile_sources") if isinstance(user.get("profile_sources"), list) else []) + if self._single_line(item, 40) + ] + group_relationship_enabled = bool(user.get("group_relationship_enabled")) + private_companion_enabled = bool(user.get("private_companion_enabled", user.get("enabled", True))) + group_observation_profile = bool( + group_relationship_enabled + and ( + str(user.get("profile_origin") or "").startswith("group_observation") + or "group_observation" in profile_sources + ) + ) + created_candidates = [ + value + for value in ( + self._float(user.get("profile_created_at")), + self._float(user.get("group_profile_created_at")), + self._float(user.get("auto_profile_created_at")), + ) + if value > 0 + ] + profile_created_at = min(created_candidates or [0]) + if profile_created_at <= 0: + profile_created_at = min( + [value for value in (self._float(user.get("last_seen")), self._float(user.get("last_group_observed_at"))) if value > 0] + or [0] + ) if relationship_mode == "owner_exclusive": relationship_intimacy["owner_exclusive"] = { "label": self._single_line(getattr(self.plugin, "owner_exclusive_label", "专属联结"), 20) or "专属联结", @@ -9933,7 +9971,32 @@ class PrivateCompanionPageApi(PrivateCompanionPageApiQzoneMixin, PrivateCompanio "identity_label": self._single_line((platform_profile or {}).get("identity_label"), 60), "stable_platform_identity": bool(platform_kind in {"qq_official", "telegram"} or is_qq_user), "source": source, - "enabled": bool(user.get("enabled", True)), + "enabled": private_companion_enabled, + "private_companion_enabled": private_companion_enabled, + "group_relationship_enabled": group_relationship_enabled, + "private_memory_enabled": bool(user.get("private_memory_enabled", private_companion_enabled)), + "cross_group_memory_enabled": bool(user.get("cross_group_memory_enabled", False)), + "p4_eligible": bool(user.get("p4_eligible", not group_observation_profile or private_companion_enabled)), + "proactive_contact_enabled": bool(private_companion_enabled and self._int(user.get("proactive_daily_limit")) != 0), + "group_observation_profile": group_observation_profile, + "profile_kind": "group_relationship" if group_observation_profile and not private_companion_enabled else "private", + "profile_source": "group_observation" if group_observation_profile and "private_chat" not in profile_sources else "private_chat", + "profile_source_label": "群聊关系档案" if group_observation_profile and "private_chat" not in profile_sources else "用户档案", + "profile_origin": self._single_line(user.get("profile_origin"), 40), + "profile_sources": profile_sources, + "observation_only": False, + "group_observation_only": bool(group_observation_profile and not private_companion_enabled), + "profile_created_at": profile_created_at, + "profile_created": self.plugin._format_timestamp_elapsed(profile_created_at), + "observed_group_count": len( + { + self._single_line(item, 80) + for item in (user.get("group_observation_scope_ids") if isinstance(user.get("group_observation_scope_ids"), list) else []) + if self._single_line(item, 80) + } + ), + "group_relationship_event_count": self._int(user.get("group_relationship_event_count")), + "last_group_relationship_at": self._float(user.get("last_group_relationship_at")), "relationship_role": role, "relationship_role_label": role_label, "nickname": user.get("nickname", ""), @@ -13142,6 +13205,8 @@ class PrivateCompanionPageApi(PrivateCompanionPageApiQzoneMixin, PrivateCompanio "default_proactive_enabled", "default_proactive_daily_limit", "relationship_stage_policy", + "relationship_positive_stage_cap_key", + "normal_interaction_band_cap", "owner_exclusive_label", "owner_exclusive_tone", "owner_exclusive_address_style", @@ -14914,7 +14979,113 @@ class PrivateCompanionPageApi(PrivateCompanionPageApiQzoneMixin, PrivateCompanio }, } + def _reconcile_relationship_cap_config( + self, + *, + old_positive_cap: Any = None, + new_positive_cap: Any = None, + old_interaction_cap: Any = None, + new_interaction_cap: Any = None, + ) -> None: + """Apply a cap transition once to ordinary user records and persist its audit.""" + users = self.plugin.data.get("users") if isinstance(getattr(self.plugin, "data", None), dict) else None + if not isinstance(users, dict): + return + previous_positive = normalize_relationship_positive_stage_cap_key(old_positive_cap) + next_positive = normalize_relationship_positive_stage_cap_key(new_positive_cap) + previous_interaction = normalize_normal_interaction_band_cap(old_interaction_cap) + next_interaction = normalize_normal_interaction_band_cap(new_interaction_cap) + interaction_cap_lowered = { + "relaxed": 0, + "lively": 1, + "warm": 2, + }[next_interaction] < { + "relaxed": 0, + "lively": 1, + "warm": 2, + }[previous_interaction] + touched = False + for user_id, user in users.items(): + if not isinstance(user, dict): + continue + resolved_user_id = self._single_line(user.get("user_id") or user_id, 80) + role = self.plugin._private_user_role(user, resolved_user_id) if hasattr(self.plugin, "_private_user_role") else str(user.get("relationship_role") or "friend") + mode = normalize_relationship_mode(user.get("relationship_mode"), role) + touched = touched or user.get("relationship_role") != role or user.get("relationship_mode") != mode + user["relationship_role"] = role + user["relationship_mode"] = mode + if previous_positive != next_positive: + stored_positive = user.get("relationship_positive_stage_cap_key") + result = migrate_relationship_positive_stage_cap( + user, + old_cap_key=previous_positive, + new_cap_key=next_positive, + now=time.time(), + ) + touched = touched or bool(result.get("changed")) or stored_positive != user.get("relationship_positive_stage_cap_key") + else: + touched = touched or user.get("relationship_positive_stage_cap_key") != next_positive + user["relationship_positive_stage_cap_key"] = next_positive + raw_interaction = user.get("current_interaction") + projection = current_interaction_projection( + raw_interaction, + relationship_role=role, + relationship_mode=mode, + relationship_score=user.get("relationship_score"), + normal_interaction_band_cap=next_interaction, + now=time.time(), + ) + raw_for_persistence = dict(raw_interaction) if isinstance(raw_interaction, dict) else {} + projection_for_persistence = dict(projection) + raw_for_persistence.pop("reason_codes", None) + projection_for_persistence.pop("reason_codes", None) + interaction_band_lowered = ( + interaction_cap_lowered + and isinstance(raw_interaction, dict) + and projection.get("expression_band") != raw_interaction.get("expression_band") + and "normal_interaction_band_cap_applied" in projection.get("reason_codes", []) + ) + if interaction_band_lowered: + projection["source"] = "administrator_interaction_cap_migration" + projection["reason"] = "administrator_interaction_cap_migration" + projection["updated_at"] = time.time() + projection_for_persistence = dict(projection) + projection_for_persistence.pop("reason_codes", None) + if projection_for_persistence != raw_for_persistence: + user["current_interaction"] = projection + touched = True + touched = touched or user.get("normal_interaction_band_cap") != next_interaction + user["normal_interaction_band_cap"] = next_interaction + if touched: + saver = getattr(self.plugin, "_save_data_sync", None) + if callable(saver): + saver() + def _apply_config_value(self, key: str, value: Any, overrides: dict[str, Any] | None = None) -> None: + if key == "relationship_positive_stage_cap_key": + old_value = getattr(self.plugin, key, "deeply_bonded") + normalized = normalize_relationship_positive_stage_cap_key(value) + self._set_config_value(key, normalized) + self.plugin.relationship_positive_stage_cap_key = normalized + self._reconcile_relationship_cap_config( + old_positive_cap=old_value, + new_positive_cap=normalized, + old_interaction_cap=getattr(self.plugin, "normal_interaction_band_cap", "warm"), + new_interaction_cap=getattr(self.plugin, "normal_interaction_band_cap", "warm"), + ) + return + if key == "normal_interaction_band_cap": + old_value = getattr(self.plugin, key, "warm") + normalized = normalize_normal_interaction_band_cap(value) + self._set_config_value(key, normalized) + self.plugin.normal_interaction_band_cap = normalized + self._reconcile_relationship_cap_config( + old_positive_cap=getattr(self.plugin, "relationship_positive_stage_cap_key", "deeply_bonded"), + new_positive_cap=getattr(self.plugin, "relationship_positive_stage_cap_key", "deeply_bonded"), + old_interaction_cap=old_value, + new_interaction_cap=normalized, + ) + return self._set_config_value(key, value) if key == "relationship_stage_policy": self.plugin.relationship_stage_policy = normalize_relationship_stage_policy(value) @@ -15718,6 +15889,8 @@ class PrivateCompanionPageApi(PrivateCompanionPageApiQzoneMixin, PrivateCompanio "default_proactive_enabled", "default_proactive_daily_limit", "relationship_stage_policy", + "relationship_positive_stage_cap_key", + "normal_interaction_band_cap", "owner_exclusive_label", "owner_exclusive_tone", "owner_exclusive_address_style", @@ -16129,6 +16302,10 @@ class PrivateCompanionPageApi(PrivateCompanionPageApiQzoneMixin, PrivateCompanio def _normalize_setting_value(self, key: str, value: Any) -> Any: if key == "relationship_stage_policy": return relationship_stage_policy_json(value) + if key == "relationship_positive_stage_cap_key": + return normalize_relationship_positive_stage_cap_key(value) + if key == "normal_interaction_band_cap": + return normalize_normal_interaction_band_cap(value) if key in self._schema_bool_keys(): return self._normalize_bool_value(value) if key == "auto_profile_platforms": diff --git a/page_api_users_groups.py b/page_api_users_groups.py index 0f61dff..b751b6a 100644 --- a/page_api_users_groups.py +++ b/page_api_users_groups.py @@ -12,7 +12,12 @@ from quart import request from .companion_interaction_expression import allowed_expression_bands, current_interaction_projection from .helpers import _safe_int -from .relationship_ledger import normalize_relationship_mode, record_manual_relationship_change +from .relationship_ledger import ( + is_owner_exclusive, + normalize_relationship_mode, + relationship_positive_score_cap, + record_manual_relationship_change, +) class PrivateCompanionPageApiUsersGroupsMixin: @@ -58,71 +63,81 @@ class PrivateCompanionPageApiUsersGroupsMixin: return None def _observation_user_summary(self, profile_id: str, profile: dict[str, Any]) -> dict[str, Any]: - """Build a read-only user-page DTO without manufacturing a private user.""" + """Build a full relationship DTO for a legacy observation-only record.""" identity = self._single_line(profile.get("user_id") or profile_id, 40) name = self._single_line(profile.get("name"), 60) or identity last_seen = profile.get("last_observed_at", profile.get("auto_registered_ts", 0)) scopes = profile.get("group_observation_scope_ids") if isinstance(profile.get("group_observation_scope_ids"), list) else [] - return { + created_at = profile.get("auto_registered_ts", last_seen) + user = { "user_id": identity, - "display_name": name, "nickname": name, - "style": "", - "is_qq_user": True, - "platform_kind": "onebot", - "platform_group": "qq", - "platform_label": "QQ", - "identity_label": "QQ 群聊观察", - "stable_platform_identity": True, - "source": "group_observation", - "profile_source": "group_observation", - "profile_source_label": "群聊观察", - "profile_kind": "observation", - "observation_only": True, - "group_observation_only": True, - "enabled": bool(profile.get("enabled", True)), - "relationship_role": "observer", - "relationship_mode": "observation_only", - "relationship_mode_label": "observation only", - "relationship_role_label": "仅观察对象", - "relationship_score": 0, - "relationship_ledger": {"items": [], "trend": "steady", "recent_delta": 0}, - "current_interaction": { - "expression_band": "relaxed", - "label": "relaxed", - "source": "group_observation", - "reason": "observation_only", - "updated_at": last_seen, - "expires_at": 0, - "manual_override": False, - "allowed_bands": [], - "reason_codes": ["observation_only"], - }, - "relationship_stage": "初识", - "relationship_state": {"mode": "neutral", "source": "group_observation"}, - "proactive_contact_enabled": False, + "style": self._single_line(getattr(self.plugin, "default_style", "温柔"), 24) or "温柔", + "enabled": False, + "private_companion_enabled": False, + "group_relationship_enabled": True, "private_memory_enabled": False, "cross_group_memory_enabled": False, "p4_eligible": False, - "effective_daily_limit": 0, - "effective_daily_limit_text": "不主动触达", - "last_seen_ts": last_seen, - "last_seen": self.plugin._format_timestamp_elapsed(last_seen), - "last_sent_ts": 0, - "last_sent": "", - "observed_group_count": len({self._single_line(item, 80) for item in scopes if self._single_line(item, 80)}), - "profile_origin": self._single_line(profile.get("profile_origin"), 40) or "group_observation", + "profile_origin": "group_observation", + "profile_sources": ["group_observation"], + "group_profile_created_at": created_at, + "auto_profile_created_at": created_at, + "last_group_observed_at": last_seen, + "group_observation_scope_ids": list(scopes), + "relationship_role": "friend", + "relationship_mode": "normal", + "relationship_score": 0, + "relationship_ledger": [], + "current_interaction": { + "expression_band": "relaxed", + "source": "group_relationship_default", + "reason": "legacy_group_observation_projection", + "updated_at": last_seen, + "expires_at": 0, + "manual_override": False, + }, + "proactive_daily_limit": 0, + "proactive_boundary_note": "群聊关系档案默认不主动触达", } + detail = self._user_summary(identity, user) + detail.update( + { + "source": "group_observation", + "profile_source": "group_observation", + "profile_source_label": "群聊关系档案", + "profile_kind": "group_relationship", + "group_observation_profile": True, + "group_observation_only": True, + "legacy_observation_projection": True, + "observed_group_count": len({self._single_line(item, 80) for item in scopes if self._single_line(item, 80)}), + } + ) + return detail def _observation_user_detail(self, profile_id: str, profile: dict[str, Any]) -> dict[str, Any]: detail = self._observation_user_summary(profile_id, profile) member_summary = self._worldbook_member_profile_summary(profile_id, profile) + projected_user = { + "relationship_role": "friend", + "relationship_mode": "normal", + "relationship_score": 0, + "relationship_ledger": [], + "current_interaction": detail.get("current_interaction") or {}, + "enabled": False, + "private_companion_enabled": False, + "group_relationship_enabled": True, + } + relationship_panel = self._relationship_panel( + detail.get("user_id") or profile_id, + projected_user, + relationship_stage=str(detail.get("relationship_stage") or ""), + worldbook_member=member_summary, + ) detail.update( { - "relationship_panel": { - "observation_only": True, - "message": "群聊观察档案不进入私聊亲密度、主动联系或安全权限链路。", - }, + "relationship_panel": relationship_panel, + "expression_decision": relationship_panel.get("expression_decision") if isinstance(relationship_panel, dict) else {}, "memory": {}, "expression_profile": {}, "intent_profile": {}, @@ -132,11 +147,11 @@ class PrivateCompanionPageApiUsersGroupsMixin: "recent_reply_topics": [], "last_user_message": "", "last_companion_message": "", - "delivery_route": {"available": False, "reason": "observation_only"}, + "delivery_route": {"available": False, "reason": "private_companion_disabled"}, "worldbook_member": member_summary, - "p4_runtime": {"available": False, "reason": "observation_only"}, + "p4_runtime": {"available": False, "reason": "group_relationship_profile"}, "formatted": { - "relationship": "仅观察:中性,不进入私聊关系链路", + "relationship": "群聊关系启用;私聊陪伴默认关闭", "action_affinity": "不主动触达", "next_proactive": "不适用", }, @@ -180,7 +195,7 @@ class PrivateCompanionPageApiUsersGroupsMixin: logger.warning("[PrivateCompanionPage] 用户列表接口耗时较高: elapsed=%sms users=%s", elapsed_ms, len(items)) source_counts = { "private_chat": sum(1 for item in items if item.get("profile_kind") == "private"), - "group_observation": sum(1 for item in items if item.get("observation_only")), + "group_observation": sum(1 for item in items if item.get("group_observation_profile")), } platform_counts: dict[str, int] = {} for item in items: @@ -212,7 +227,13 @@ class PrivateCompanionPageApiUsersGroupsMixin: worldbook_member = self._worldbook_member_for_private_user_locked(self.plugin.data, user_id, user if isinstance(user, dict) else {}) if observation is not None: profile_id, profile = observation - return self._ok(self._observation_user_detail(profile_id, deepcopy(profile))) + detail = self._observation_user_detail(profile_id, deepcopy(profile)) + memory_reader = getattr(self.plugin, "_memory_companion_read_user_memory_summary", None) + if callable(memory_reader): + detail["memory_summary"] = await memory_reader(user_id, limit=3) + else: + detail["memory_summary"] = {"available": False, "state": "unsupported", "reason_code": "summary_reader_unavailable"} + return self._ok(detail) if not isinstance(user, dict): return self._error("用户不存在") detail = self._user_summary(user_id, user) @@ -224,9 +245,17 @@ class PrivateCompanionPageApiUsersGroupsMixin: ) detail["current_interaction"] = detail["relationship_panel"]["current_interaction"] detail["expression_decision"] = detail["relationship_panel"]["expression_decision"] - detail["p4_runtime"] = self._p4_page_status_projection() + detail["p4_runtime"] = ( + self._p4_page_status_projection() + if bool(detail.get("p4_eligible")) + else {"available": False, "reason": "group_relationship_profile"} + ) route_status_getter = getattr(self.plugin, "_private_delivery_route_status", None) - delivery_route = route_status_getter(user_id, user) if callable(route_status_getter) else {} + delivery_route = ( + route_status_getter(user_id, user) + if callable(route_status_getter) and bool(detail.get("private_companion_enabled")) + else {"available": False, "reason": "private_companion_disabled"} + ) detail.update( { "memory": user.get("companion_memory") if isinstance(user.get("companion_memory"), dict) else {}, @@ -248,6 +277,11 @@ class PrivateCompanionPageApiUsersGroupsMixin: }, } ) + memory_reader = getattr(self.plugin, "_memory_companion_read_user_memory_summary", None) + if callable(memory_reader): + detail["memory_summary"] = await memory_reader(user_id, limit=3) + else: + detail["memory_summary"] = {"available": False, "state": "unsupported", "reason_code": "summary_reader_unavailable"} return self._ok(detail) except Exception as exc: logger.error(f"[PrivateCompanionPage] 获取用户详情失败: {exc}", exc_info=True) @@ -286,8 +320,23 @@ class PrivateCompanionPageApiUsersGroupsMixin: action_message = "" async with self.plugin._data_lock: users = self.plugin.data.get("users") if isinstance(self.plugin.data.get("users"), dict) else {} - if not isinstance(users.get(user_id), dict) and self._observation_profile_by_user_id_locked(self.plugin.data, user_id): - return self._error("仅观察档案不能通过私聊用户接口修改") + if not isinstance(users.get(user_id), dict): + observed = self._observation_profile_by_user_id_locked(self.plugin.data, user_id) + if observed is not None: + _, profile = observed + scopes = profile.get("group_observation_scope_ids") if isinstance(profile.get("group_observation_scope_ids"), list) else [] + group_id = next((self._single_line(item, 80) for item in scopes if self._single_line(item, 80)), "legacy-observation") + ensurer = getattr(self.plugin, "_ensure_group_relationship_user_profile", None) + if not callable(ensurer): + return self._error("群聊关系档案处理器不可用") + materialized, _ = ensurer( + group_id=group_id, + sender_id=user_id, + qq_nickname=self._single_line(profile.get("name"), 40), + now=time.time(), + ) + if not isinstance(materialized, dict): + return self._error("群聊关系档案创建失败") user = self.plugin._get_user(user_id) expression_voice_needs_refresh = False previous_role = self.plugin._private_user_role(user, user_id) @@ -317,6 +366,7 @@ class PrivateCompanionPageApiUsersGroupsMixin: if "enabled" in payload: enabled = bool(payload.get("enabled")) user["enabled"] = enabled + user["private_companion_enabled"] = enabled user["manual_enabled"] = enabled user["manual_disabled"] = not enabled user["auto_enabled"] = False @@ -336,13 +386,21 @@ class PrivateCompanionPageApiUsersGroupsMixin: expression_voice_needs_refresh = expression_voice_needs_refresh or next_mode != previous_mode if relationship_score is not None: previous_score = user.get("relationship_score", 0) - user["relationship_score"] = relationship_score + effective_score = relationship_score + positive_cap_key = getattr(self.plugin, "relationship_positive_stage_cap_key", "deeply_bonded") + if effective_score > 0 and not is_owner_exclusive(user): + effective_score = min(effective_score, relationship_positive_score_cap(positive_cap_key)) + user["relationship_score"] = effective_score record_manual_relationship_change( user, previous_score, - relationship_score, + effective_score, now=time.time(), - reason_code="administrator_manual_relationship_adjustment", + reason_code=( + "administrator_manual_relationship_adjustment_stage_capped" + if effective_score != relationship_score + else "administrator_manual_relationship_adjustment" + ), ) if requested_interaction_band is not None: changed_at = time.time() @@ -358,6 +416,8 @@ class PrivateCompanionPageApiUsersGroupsMixin: }, relationship_role=role, relationship_mode=next_mode, + relationship_score=user.get("relationship_score"), + normal_interaction_band_cap=getattr(self.plugin, "normal_interaction_band_cap", "warm"), now=changed_at, ) expression_voice_needs_refresh = True @@ -366,6 +426,8 @@ class PrivateCompanionPageApiUsersGroupsMixin: user.get("current_interaction"), relationship_role=role, relationship_mode=next_mode, + relationship_score=user.get("relationship_score"), + normal_interaction_band_cap=getattr(self.plugin, "normal_interaction_band_cap", "warm"), now=time.time(), ) if "proactive_daily_limit" in payload: @@ -411,6 +473,8 @@ class PrivateCompanionPageApiUsersGroupsMixin: None, relationship_role=user.get("relationship_role"), relationship_mode=user.get("relationship_mode"), + relationship_score=user.get("relationship_score"), + normal_interaction_band_cap=getattr(self.plugin, "normal_interaction_band_cap", "warm"), ) if payload.get("clear_behavior_habits"): user["behavior_habits"] = {} diff --git a/pages/陪伴面板/app.css b/pages/陪伴面板/app.css index 36afab9..f58e7a8 100644 --- a/pages/陪伴面板/app.css +++ b/pages/陪伴面板/app.css @@ -4486,6 +4486,97 @@ body.daily-outfit-preview-open { margin: 0; } +.user-memory-summary { + display: grid; + gap: 10px; +} + +.user-memory-summary.is-unavailable { + border-style: dashed; +} + +.user-memory-summary.is-unavailable p, +.user-memory-summary-head p { + margin: 4px 0 0; + color: var(--muted); + font-size: 12px; +} + +.user-memory-summary-head { + display: flex; + align-items: flex-start; + justify-content: space-between; + gap: 10px; +} + +.user-memory-summary-head h2 { + margin: 0; +} + +.user-memory-summary-counts { + display: grid; + grid-template-columns: repeat(4, minmax(0, 1fr)); + gap: 6px; +} + +.user-memory-summary-counts span { + display: grid; + gap: 2px; + min-width: 0; + border-radius: 7px; + padding: 7px; + background: color-mix(in srgb, var(--accent) 7%, var(--surface)); + color: var(--muted); + font-size: 11px; +} + +.user-memory-summary-counts b { + color: var(--accent-strong); + font-size: 15px; +} + +.user-memory-summary-snippets { + display: grid; + gap: 5px; +} + +.user-memory-summary-snippets p { + display: grid; + grid-template-columns: 34px minmax(0, 1fr); + gap: 8px; + margin: 0; + color: var(--text-muted); + font-size: 12px; + line-height: 1.5; +} + +.user-memory-summary-snippets b { + color: var(--accent-strong); +} + +.user-memory-summary-snippets span { + overflow-wrap: anywhere; +} + +.user-memory-summary-actions { + display: flex; + justify-content: flex-end; +} + +.user-memory-summary-actions .button-link { + border: 1px solid color-mix(in srgb, var(--accent) 42%, var(--line)); + border-radius: 7px; + padding: 6px 9px; + color: var(--accent-strong); + font-size: 12px; + font-weight: 700; + text-decoration: none; +} + +.user-memory-summary-actions .button-link:hover { + background: color-mix(in srgb, var(--accent) 8%, var(--surface)); +} + .open-loop-actions { display: flex; flex-wrap: wrap; @@ -27101,3 +27192,73 @@ pre { grid-template-columns: 1fr; } } + +/* REQ-029: user relationship profiles and deterministic list ordering */ +.user-list-controls { + display: flex; + align-items: end; + justify-content: flex-end; + gap: 10px; + flex-wrap: wrap; +} + +.user-list-controls > label { + display: grid; + gap: 4px; + color: var(--muted); + font-size: 12px; +} + +.user-list-controls select, +.user-list-controls input { + min-height: 38px; +} + +.user-platform-group.is-owner-group td { + background: color-mix(in srgb, var(--accent) 12%, var(--surface)); +} + +.user-platform-group.is-owner-group button:disabled { + cursor: default; + opacity: 1; +} + +.group-relationship-profile-banner { + display: flex; + align-items: center; + justify-content: space-between; + gap: 20px; + margin: 0 0 16px; + padding: 18px 20px; + border: 1px solid color-mix(in srgb, var(--accent) 30%, var(--border)); + border-radius: 18px; + background: linear-gradient(135deg, color-mix(in srgb, var(--accent) 10%, var(--surface)), var(--surface)); +} + +.group-relationship-profile-banner h3, +.group-relationship-profile-banner p { + margin: 4px 0 0; +} + +.group-relationship-profile-banner > div:last-child { + display: flex; + gap: 8px; + flex-wrap: wrap; + justify-content: flex-end; +} + +@media (max-width: 760px) { + .user-list-controls, + .group-relationship-profile-banner { + align-items: stretch; + flex-direction: column; + } + + .user-list-controls > * { + width: 100%; + } + + .group-relationship-profile-banner > div:last-child { + justify-content: flex-start; + } +} diff --git a/pages/陪伴面板/app.js b/pages/陪伴面板/app.js index aa6fccd..ee210ff 100644 --- a/pages/陪伴面板/app.js +++ b/pages/陪伴面板/app.js @@ -29,6 +29,8 @@ const state = { memoEditorId: "", selectedUserId: "", userPlatformCollapsed: {}, + userSortKey: "recent", + userSortDirection: "desc", learningSection: "expressions", expressionWorkspaceView: "library", selectedExpressionReviewRuleId: "", @@ -1461,6 +1463,8 @@ const configLabels = { default_proactive_enabled: "允许新用户主动关心", default_proactive_daily_limit: "新用户每日主动上限", relationship_stage_policy: "八阶段策略", + relationship_positive_stage_cap_key: "普通用户长期关系上限阶段", + normal_interaction_band_cap: "普通用户互动状态上限", owner_exclusive_label: "管理员专属关系名称", owner_exclusive_tone: "管理员专属基础表达", owner_exclusive_address_style: "管理员专属称呼尺度", @@ -2024,6 +2028,8 @@ const configDescriptions = { default_proactive_enabled: "默认关闭。只有自动启用陪伴时才可能允许主动关心。", default_proactive_daily_limit: "新用户每天最多主动关心次数;未自动启用陪伴时强制为 0。", relationship_stage_policy: "固定八阶段键与阈值,只编辑显示、语气、称呼尺度和软行为,不能授予权限或绕过 P4。", + relationship_positive_stage_cap_key: "普通用户的自动与管理员手动调整均不能超过该阶段;owner_exclusive 不受影响。默认是深度联结。", + normal_interaction_band_cap: "普通用户自动或手动可达到的最高互动状态;亲近和爱意始终只属于主要用户。默认是温暖。", owner_exclusive_label: "只修改 owner 专属关系的显示名称,不增加管理或安全权限。", owner_exclusive_tone: "专属关系的长期表达基线;当前互动状态仍可使本轮收敛。", owner_exclusive_address_style: "优先沿用双方已确认的专属称呼。", @@ -2594,6 +2600,8 @@ const featureSettingGroups = { enable_auto_user_profile_creation: ["auto_enable_companion_for_new_users", "auto_profile_platforms", "default_nickname_strategy", "default_nickname", "default_style", "default_relationship_role", "default_relationship_score", "default_interaction_band", "default_proactive_enabled", "default_proactive_daily_limit"], enable_custom_relationship_stage_policy: [ "relationship_stage_policy", + "relationship_positive_stage_cap_key", + "normal_interaction_band_cap", "owner_exclusive_label", "owner_exclusive_tone", "owner_exclusive_address_style", @@ -3399,6 +3407,8 @@ const featureSettingTypes = { default_relationship_role: { type: "select", options: [["friend", "普通用户 / 朋友"]] }, default_relationship_score: { type: "number", min: -1200, max: 1200, step: 1 }, default_interaction_band: { type: "select", options: [["avoidant", "回避"], ["hurt", "受伤"], ["relaxed", "放松"], ["lively", "活泼"], ["warm", "温暖"]] }, + relationship_positive_stage_cap_key: { type: "select", options: [["familiar", "熟悉"], ["close", "亲近"], ["intimate", "亲密"], ["deeply_bonded", "深度联结"]] }, + normal_interaction_band_cap: { type: "select", options: [["relaxed", "放松"], ["lively", "活泼"], ["warm", "温暖"]] }, owner_exclusive_proactive_limit: { type: "number", min: 0, max: 30, step: 1 }, default_proactive_enabled: { type: "checkbox" }, default_proactive_daily_limit: { type: "number", min: 0, max: 30, step: 1 }, @@ -5005,7 +5015,10 @@ function applyUserGroupLists(users, groups) { state.users = Array.isArray(users?.items) ? users.items : []; state.groups = Array.isArray(groups?.items) ? groups.items : []; state.userGroupListError = ""; - if (!state.selectedUserId && state.users[0]) state.selectedUserId = state.users[0].user_id; + if (!state.selectedUserId && state.users[0]) { + const owner = state.users.find((item) => item.relationship_role === "owner"); + state.selectedUserId = (owner || state.users[0]).user_id; + } if (!state.selectedGroupId && state.groups[0]) state.selectedGroupId = state.groups[0].group_id; } @@ -12380,38 +12393,104 @@ function renderLearning() { switchLearningSection(state.learningSection); } +const USER_SORT_STORAGE_KEY = "private_companion_user_sort_v1"; + +function loadUserSortPreference() { + try { + const raw = JSON.parse(window.localStorage?.getItem(USER_SORT_STORAGE_KEY) || "{}"); + if (["recent", "intimacy", "nickname", "created"].includes(raw.key)) state.userSortKey = raw.key; + if (["asc", "desc"].includes(raw.direction)) state.userSortDirection = raw.direction; + } catch (error) { + // 嵌入页面可能禁用 localStorage,排序仍在当前页面会话内生效。 + } +} + +function saveUserSortPreference() { + try { + window.localStorage?.setItem(USER_SORT_STORAGE_KEY, JSON.stringify({ key: state.userSortKey, direction: state.userSortDirection })); + } catch (error) {} +} + +function userPlatformGroup(user) { + return user.platform_group || (user.platform_kind === "telegram" ? "telegram" : ["onebot", "qq_official"].includes(user.platform_kind) || user.is_qq_user ? "qq" : "web_other"); +} + +function userCreatedTimestamp(user) { + return Number(user.profile_created_at || user.group_profile_created_at || user.auto_profile_created_at || 0); +} + +function compareUsersForList(a, b) { + const direction = state.userSortDirection === "asc" ? 1 : -1; + let result = 0; + if (state.userSortKey === "intimacy") { + result = Number(a.relationship_intimacy?.value ?? a.relationship_score ?? 0) - Number(b.relationship_intimacy?.value ?? b.relationship_score ?? 0); + } else if (state.userSortKey === "nickname") { + result = String(a.display_name || a.nickname || a.user_id).localeCompare(String(b.display_name || b.nickname || b.user_id), "zh-Hans-CN", { numeric: true, sensitivity: "base" }); + } else if (state.userSortKey === "created") { + result = userCreatedTimestamp(a) - userCreatedTimestamp(b); + } else { + result = Number(a.last_seen_ts || 0) - Number(b.last_seen_ts || 0); + } + if (result === 0) result = String(a.user_id || "").localeCompare(String(b.user_id || ""), "en", { numeric: true }); + return result * direction; +} + +function renderUserTableRow(user) { + const privateEnabled = Boolean(user.private_companion_enabled ?? user.enabled); + const groupRelationshipEnabled = Boolean(user.group_relationship_enabled); + const groupProfile = Boolean(user.group_observation_profile); + const createdText = user.profile_created || (userCreatedTimestamp(user) ? new Date(userCreatedTimestamp(user) * 1000).toLocaleString() : "未知"); + const interactionLabel = user.current_interaction?.label || user.current_interaction?.expression_band || "放松"; + return ` +
${escapeHtml(detail.user_id || "")}
当前不可用;不展示底层错误或原始数据。
仅显示脱敏概览;完整记录仍由记忆插件独立管理。
${escapeHtml(label)}${escapeHtml(text)}
`).join("")}暂无可展示的脱敏摘要。
`} + ${workspaceUrl ? `` : ""} +管理关系角色、主动额度、行为习惯、陪伴状态和已整理的对话片段。