diff --git a/_conf_schema.json b/_conf_schema.json index 1ab4448..29e829e 100644 --- a/_conf_schema.json +++ b/_conf_schema.json @@ -83,7 +83,7 @@ "target_user_ids": { "description": "私聊目标用户 ID", "type": "list", - "hint": "填写后启动时会自动预热这些私聊对象。OneBot/aiocqhttp 通常填 QQ 号;QQ 官方机器人请填日志或私聊页显示的 openid/平台用户 ID。误粘贴私聊 UMO 时会自动提取 FriendMessage 后面的用户 ID。只想被动聊天也可以留空。", + "hint": "填写后启动时会自动预热这些用户。OneBot/aiocqhttp 通常填 QQ 号;QQ 官方机器人请填日志或用户页显示的 openid/平台用户 ID。误粘贴私聊 UMO 时会自动提取 FriendMessage 后面的用户 ID。只想被动聊天也可以留空。", "default": [] }, "private_user_aliases": { @@ -179,6 +179,80 @@ "hint": "开启后 target_user_ids 中的用户会自动建立主动私聊来源。首次使用建议开启。", "default": true }, + "enable_auto_user_profile_creation": { + "description": "新用户默认档案", + "type": "bool", + "hint": "首次收到真实私聊时建立最小用户档案。建档与陪伴接管分离,不会自动授予主要用户、跨用户查询、主动触达或 P4 权限。", + "default": true + }, + "auto_enable_companion_for_new_users": { + "description": "自动启用新用户陪伴", + "type": "bool", + "hint": "开启后,新建档案同时进入本插件陪伴链路;默认关闭,关闭时只建档并继续放行 AstrBot 默认主链。", + "default": false, + "condition": "enable_auto_user_profile_creation" + }, + "auto_profile_platforms": { + "description": "自动建档平台", + "type": "list", + "hint": "允许首次私聊自动建档的平台类型。QQ/NapCat 为 onebot,QQ 官方为 qq_official,Telegram 为 telegram,网页聊天为 webchat,其他适配器为 generic。", + "default": ["onebot", "qq_official", "telegram", "webchat", "generic"], + "condition": "enable_auto_user_profile_creation" + }, + "default_nickname_strategy": { + "description": "默认称呼来源", + "type": "string", + "options": ["platform_display_name", "fixed", "user_id"], + "labels": ["优先平台显示名", "固定称呼", "用户 ID"], + "hint": "平台显示名不可用时回退到下方默认称呼;不会改变用户 ID、UMO 或身份归并。", + "default": "platform_display_name", + "condition": "enable_auto_user_profile_creation" + }, + "default_relationship_role": { + "description": "默认关系角色", + "type": "string", + "options": ["friend"], + "labels": ["普通用户 / 朋友"], + "hint": "自动档案固定为普通用户,不能通过此配置成为主要用户。", + "default": "friend", + "condition": "enable_auto_user_profile_creation" + }, + "default_relationship_score": { + "description": "默认亲密度", + "type": "int", + "slider": {"min": -1200, "max": 1200, "step": 1}, + "hint": "只用于之后自动建立的新档案,不重写既有用户。", + "default": 0, + "condition": "enable_auto_user_profile_creation" + }, + "default_proactive_enabled": { + "description": "允许新用户主动关心", + "type": "bool", + "hint": "只有同时开启自动陪伴时才可能生效;默认关闭。", + "default": false, + "condition": "enable_auto_user_profile_creation" + }, + "default_proactive_daily_limit": { + "description": "新用户每日主动上限", + "type": "int", + "slider": {"min": 0, "max": 30, "step": 1}, + "hint": "自动档案的主动上限;关闭主动关心或未自动启用陪伴时强制为 0。", + "default": 0, + "condition": "default_proactive_enabled" + }, + "enable_custom_relationship_stage_policy": { + "description": "亲密度阶段策略", + "type": "bool", + "hint": "关闭时使用内置八阶段策略;开启后使用陪伴面板详情页编辑的自定义标签、语气和软行为。固定阶段键与分数范围不变。", + "default": false + }, + "relationship_stage_policy": { + "description": "亲密度阶段策略数据", + "type": "text", + "hint": "由陪伴面板结构化编辑器维护。阶段策略只能调整表达和软行为,不能授予权限或绕过 P4。", + "default": "", + "invisible": true + }, "default_nickname": { "description": "默认称呼", "type": "string", @@ -1637,7 +1711,7 @@ "invisible": true }, "enable_livingmemory_integration": { - "description": "Legacy flat config: 启用外部记忆插件协同", + "description": "Legacy flat config: 启用记忆插件协同", "type": "bool", "default": true, "invisible": true @@ -2510,7 +2584,7 @@ "invisible": true }, "enable_cross_user_memory_bridge": { - "description": "Legacy flat config: 启用跨用户记忆互通", + "description": "Legacy flat config: 启用跨用户互动摘要查询", "type": "bool", "default": false, "invisible": true @@ -5835,7 +5909,7 @@ "user_habit_max_items": { "description": "习惯条目上限", "type": "int", - "hint": "每个私聊对象最多保留多少条行为习惯模式,超过后优先保留高频和近期条目。", + "hint": "每个用户最多保留多少条行为习惯模式,超过后优先保留高频和近期条目。", "slider": { "min": 8, "max": 80, @@ -6152,7 +6226,7 @@ "max_dialogue_episodes": { "description": "最多保留对话片段数量", "type": "int", - "hint": "每个私聊对象最多保留多少段共同经历摘要;实际回复时只会择要使用少量片段。", + "hint": "每个用户最多保留多少段共同经历摘要;实际回复时只会择要使用少量片段。", "slider": { "min": 3, "max": 40, @@ -6175,14 +6249,14 @@ } }, "external_memory_config": { - "description": "外部记忆插件协同", + "description": "记忆插件协同", "type": "object", "hint": "统一接入已适配的外部长期记忆插件。当前支持“我会牢牢记住你”/MemoryCompanion 与 LivingMemory;检测到不同插件时会展开各自适用的协同配置。", "items": { "enable_livingmemory_integration": { - "description": "启用外部记忆插件协同", + "description": "启用记忆插件协同", "type": "bool", - "hint": "统一控制已适配的外部记忆插件协同,不只对应 LivingMemory。检测到“我会牢牢记住你”/MemoryCompanion 或 LivingMemory 时,在私聊和群聊提示词中按各自能力使用记忆上下文或召回工具;本插件继续负责人格、状态、关系和群聊气氛。", + "hint": "统一控制已适配的记忆插件协同,不只对应 LivingMemory。检测到“我会牢牢记住你”/MemoryCompanion 或 LivingMemory 时,在私聊和群聊提示词中按各自能力使用记忆上下文或召回工具;本插件继续负责人格、状态、关系和群聊气氛。", "default": true }, "enable_memory_companion_bridge": { @@ -7919,9 +7993,9 @@ } }, "enable_cross_user_memory_bridge": { - "description": "启用跨用户记忆互通", + "description": "启用跨用户互动摘要查询", "type": "bool", - "hint": "开启后,主要用户可在私聊中询问 Bot 与某个私聊对象或群聊的近期互动。该功能只读摘要,不会发送消息,默认仅主要用户可用。", + "hint": "开启后,主要用户可在私聊中询问 Bot 与某个用户或群聊的近期互动。该功能只读摘要,不会发送消息,默认仅主要用户可用。", "default": false, "condition": { "enable_worldbook_member_recognition": true @@ -7930,7 +8004,7 @@ "cross_user_memory_owner_only": { "description": "仅主要用户可查询跨用户互动", "type": "bool", - "hint": "开启后,target_user_ids 中配置的用户以及私聊页中关系角色设为主要用户的用户能查询 Bot 与其他用户/群聊的互动;关闭后,AstrBot 全局管理员 admins_id 也可在私聊中查询。手动启用对象和身份别名不会获得该权限。", + "hint": "开启后,target_user_ids 中配置的用户以及用户页中关系角色设为主要用户的用户能查询 Bot 与其他用户/群聊的互动;关闭后,AstrBot 全局管理员 admins_id 也可在私聊中查询。手动启用用户和身份别名不会获得该权限。", "default": true, "condition": { "enable_cross_user_memory_bridge": true diff --git a/constants.py b/constants.py index 749108e..fb5b74c 100644 --- a/constants.py +++ b/constants.py @@ -377,6 +377,10 @@ _SIMULATION_FALLBACK_EVENTS = [ # 默认用户模板(无文本,无需修改) _DEFAULT_USER_TEMPLATE = { "enabled": True, + "auto_enabled": False, + "auto_profile_created": False, + "auto_profile_created_at": 0, + "profile_origin": "", "relationship_role": "", "proactive_daily_limit": -1, "proactive_idle_minutes": -1, diff --git a/core_store.py b/core_store.py index 3ce6206..fed3924 100644 --- a/core_store.py +++ b/core_store.py @@ -114,6 +114,7 @@ from .helpers import ( _strip_persisted_chat_control_tags, _today_key, ) +from .relationship_policy import RELATIONSHIP_SCORE_MAX, RELATIONSHIP_SCORE_MIN 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 @@ -1318,6 +1319,83 @@ class CoreStoreMixin: user["style"] = self.default_style return user + def _auto_profile_platform_set(self) -> set[str]: + raw = getattr(self, "auto_profile_platforms", None) + if isinstance(raw, str): + items = re.split(r"[\s,,、;;]+", raw) + elif isinstance(raw, (list, tuple, set)): + items = list(raw) + else: + items = [] + normalized = { + self._normalize_platform_kind(item) + for item in items + if str(item or "").strip() + } + return normalized or {"onebot", "qq_official", "telegram", "webchat", "generic"} + + def _auto_profile_nickname(self, user_id: str, sender_display_name: str) -> str: + strategy = str(getattr(self, "default_nickname_strategy", "platform_display_name") or "").strip() + fixed = _single_line(getattr(self, "default_nickname", "你"), 24) or "你" + observed = _single_line(sender_display_name, 24) + generic = {"用户", "主人", "主要用户", "默认用户", "unknown", "未知"} + if strategy == "fixed": + return fixed + if strategy == "user_id": + return _single_line(user_id, 24) or fixed + if observed and observed.lower() not in generic: + return observed + return fixed or _single_line(user_id, 24) + + def _ensure_auto_private_user_profile( + self, + event: Any, + *, + user_id: str, + sender_display_name: str = "", + now: float | None = None, + ) -> tuple[dict[str, Any] | None, bool]: + """Create a minimal private profile without granting implicit authority.""" + if not bool(getattr(self, "enable_auto_user_profile_creation", True)): + return None, False + canonical_user_id = self._canonical_private_user_id(str(user_id or "").strip()) + if not canonical_user_id or self._is_bot_self_user_id(canonical_user_id): + return None, False + platform_kind = self._platform_kind_for_event(event) + if platform_kind not in self._auto_profile_platform_set(): + return None, False + users = self.data.setdefault("users", {}) + existing = users.get(canonical_user_id) if isinstance(users, dict) else None + if isinstance(existing, dict): + return existing, False + + user = self._get_user(canonical_user_id) + created_at = float(now if now is not None else _now_ts()) + user["auto_profile_created"] = True + user["auto_profile_created_at"] = created_at + user["profile_origin"] = "private_auto" + user["relationship_role"] = "friend" + user["relationship_score"] = max( + RELATIONSHIP_SCORE_MIN, + min(RELATIONSHIP_SCORE_MAX, _safe_int(getattr(self, "default_relationship_score", 0), 0)), + ) + user["nickname"] = self._auto_profile_nickname(canonical_user_id, sender_display_name) + user["style"] = _single_line(getattr(self, "default_style", "温柔"), 24) or "温柔" + auto_enabled = bool(getattr(self, "auto_enable_companion_for_new_users", False)) + user["auto_enabled"] = auto_enabled + user["manual_enabled"] = False + user["manual_disabled"] = False + user["enabled"] = bool(auto_enabled or canonical_user_id in set(self._configured_target_ids())) + 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 + user["proactive_boundary_note"] = "" if auto_enabled else "自动建档默认不主动触达" + user["last_seen"] = max(_safe_float(user.get("last_seen"), 0), created_at) + user["last_activity_at"] = max(_safe_float(user.get("last_activity_at"), 0), created_at) + self._note_private_user_umo(canonical_user_id, user, getattr(event, "unified_msg_origin", "")) + self._schedule_data_save() + return user, True + def _latest_user_activity_ts(self, user: dict[str, Any] | None) -> float: if not isinstance(user, dict): return 0.0 @@ -1350,8 +1428,11 @@ class CoreStoreMixin: user_id = self._canonical_private_user_id(str(user_id or "").strip()) if self._is_bot_self_user_id(user_id): return False - if isinstance(user, dict) and user.get("manual_enabled"): - return True + if isinstance(user, dict): + if user.get("manual_disabled"): + return False + if user.get("manual_enabled") or user.get("auto_enabled"): + return True if not user_id: return False if user_id in set(self._configured_target_ids()): diff --git a/main.py b/main.py index e8f1db0..12148e0 100644 --- a/main.py +++ b/main.py @@ -148,6 +148,7 @@ from .plugin_identity import ( plugin_identity_snapshot, ) from .runtime_compat import probe_runtime_capabilities +from .relationship_policy import normalize_relationship_stage_policy from .user_rest_gate import UserRestGateMixin from .busy_reply_gate import BusyReplyGateMixin from .memory_companion_adapter import MemoryCompanionAdapterMixin @@ -1426,6 +1427,28 @@ class PrivateCompanionPlugin( self.worldview_adaptation_mode = "auto" self.worldview_adaptation_prompt = self._cfg_str(c, "worldview_adaptation_prompt", "") self.default_nickname = self._cfg_str(c, "default_nickname", "你", "你") + self.enable_auto_user_profile_creation = self._cfg_bool(c, "enable_auto_user_profile_creation", True) + self.auto_enable_companion_for_new_users = self._cfg_bool(c, "auto_enable_companion_for_new_users", False) + self.auto_profile_platforms = self._cfg_raw( + c, + "auto_profile_platforms", + ["onebot", "qq_official", "telegram", "webchat", "generic"], + ) + self.default_nickname_strategy = self._cfg_str(c, "default_nickname_strategy", "platform_display_name") + if self.default_nickname_strategy not in {"platform_display_name", "fixed", "user_id"}: + self.default_nickname_strategy = "platform_display_name" + self.default_relationship_role = "friend" + self.default_relationship_score = self._cfg_int(c, "default_relationship_score", 0, -1200, 1200) + self.default_proactive_enabled = self._cfg_bool(c, "default_proactive_enabled", False) + self.default_proactive_daily_limit = self._cfg_int(c, "default_proactive_daily_limit", 0, 0, 30) + self.enable_custom_relationship_stage_policy = self._cfg_bool( + c, + "enable_custom_relationship_stage_policy", + False, + ) + self.relationship_stage_policy = normalize_relationship_stage_policy( + self._cfg_raw(c, "relationship_stage_policy", []) + ) self.require_private_opt_in = self._cfg_bool(c, "require_private_opt_in", True) self.target_user_ids = self._cfg_raw(c, "target_user_ids", []) self.private_user_aliases = self._parse_private_user_aliases(self._cfg_raw(c, "private_user_aliases", "")) @@ -11865,6 +11888,20 @@ wakeup_type={_single_line(wakeup.get('type'), 40)} score={_single_line(wakeup.ge return if self._message_debounce_command_text(event, text): return + async with self._data_lock: + _, auto_profile_created = self._ensure_auto_private_user_profile( + event, + user_id=user_id, + sender_display_name=sender_display_name, + now=received_ts, + ) + if auto_profile_created: + logger.info( + "[PrivateCompanion] 已建立最小用户档案: user=%s platform=%s auto_enabled=%s", + _single_line(self._canonical_private_user_id(user_id), 80), + _single_line(self._platform_kind_for_event(event), 40), + bool(getattr(self, "auto_enable_companion_for_new_users", False)), + ) existing_reply_preview = self._event_existing_reply_result_preview(event) if existing_reply_preview: preview_user_id = self._canonical_private_user_id(user_id) diff --git a/memory_companion_adapter.py b/memory_companion_adapter.py index eea1474..8922d54 100644 --- a/memory_companion_adapter.py +++ b/memory_companion_adapter.py @@ -23,6 +23,7 @@ from .bot_personal_contract import ( ) from .bot_personal_outbox import BotPersonalOutbox from .helpers import _missing_optional_model_dependency, _path_text, _safe_float, _safe_int, _single_line +from .relationship_policy import relationship_projection_for_bridge def _memory_companion_safe_float(value: Any, default: float, minimum: float = 0.0) -> float: @@ -1462,6 +1463,22 @@ class MemoryCompanionAdapterMixin: text: str, ) -> None: payload = self._memory_companion_build_private_context(user_id=user_id, user=user, text=text, event=event) + policy = ( + getattr(self, "relationship_stage_policy", None) + if bool(getattr(self, "enable_custom_relationship_stage_policy", False)) + else None + ) + projection = relationship_projection_for_bridge(user.get("relationship_score", 0), policy) + bridge = self._memory_companion_bridge() + consumer = getattr(bridge, "consume_relationship_projection", None) if bridge is not None else None + if callable(consumer): + try: + consumed = consumer(projection) + except Exception: + consumed = {} + if isinstance(consumed, dict) and isinstance(consumed.get("projection"), dict): + projection = consumed["projection"] + payload["relationship_projection"] = projection self._memory_companion_attach_context(event, payload) self._memory_companion_attach_person_context(event) diff --git a/page_api.py b/page_api.py index d753960..7689b21 100644 --- a/page_api.py +++ b/page_api.py @@ -30,6 +30,11 @@ 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 .reference_asset_gate import ReferenceAssetGate +from .relationship_policy import ( + normalize_relationship_stage_policy, + relationship_stage_for_score, + relationship_stage_policy_json, +) from .page_api_qzone import PrivateCompanionPageApiQzoneMixin from .page_api_users_groups import PrivateCompanionPageApiUsersGroupsMixin from .planning import evaluate_daily_plan_quality, generate_daily_plan, generate_detail_enhancement @@ -131,34 +136,14 @@ class PrivateCompanionPageApi(PrivateCompanionPageApiQzoneMixin, PrivateCompanio self.plugin = plugin self._schema_key_index_cache: dict[str, Any] | None = None - @staticmethod - def _relationship_intimacy_projection(value: int) -> dict[str, Any]: + def _relationship_intimacy_projection(self, value: int) -> dict[str, Any]: """Return the admin-facing phase for the legacy companion baseline only.""" - score = max(-1200, min(1200, int(value))) - if score <= -801: - phase_key, phase_label = "deeply_distant", "极度疏离" - elif score <= -401: - phase_key, phase_label = "strongly_distant", "强烈疏离" - elif score < 0: - phase_key, phase_label = "distant", "疏离" - elif score <= 199: - phase_key, phase_label = "acquaintance", "初识" - elif score <= 599: - phase_key, phase_label = "familiar", "熟悉" - elif score <= 899: - phase_key, phase_label = "close", "亲近" - elif score < 1200: - phase_key, phase_label = "intimate", "亲密" - else: - phase_key, phase_label = "deeply_bonded", "深度联结" - return { - "value": score, - "band": phase_label, - "phase": {"key": phase_key, "label": phase_label}, - "min": -1200, - "max": 1200, - "trend": "unknown", - } + policy = ( + getattr(self.plugin, "relationship_stage_policy", None) + if bool(getattr(self.plugin, "enable_custom_relationship_stage_policy", False)) + else None + ) + return relationship_stage_for_score(value, policy) @staticmethod def _p4_page_status_projection() -> dict[str, Any]: @@ -2125,8 +2110,8 @@ class PrivateCompanionPageApi(PrivateCompanionPageApiQzoneMixin, PrivateCompanio "TTS 配置已开但 provider 不可用": "tts.provider_unavailable", "TTS 强化已开但会话 TTS 未启用": "tts.provider_unavailable", "TTS 强化开启但合成 provider 不可用": "tts.provider_unavailable", - "暂无启用的私聊对象": "proactive.no_enabled_users", - "主动消息没有私聊对象": "proactive.no_enabled_users", + "暂无启用的用户": "proactive.no_enabled_users", + "主动消息没有用户": "proactive.no_enabled_users", "私聊主动已关闭": "proactive.daily_limit_zero", "私聊主动总额度为 0": "proactive.daily_limit_zero", "Token 软限额正在暂缓后台任务": "token.soft_limit_active", @@ -3574,12 +3559,12 @@ class PrivateCompanionPageApi(PrivateCompanionPageApiQzoneMixin, PrivateCompanio users = deepcopy(self.plugin.data.get("users") if isinstance(self.plugin.data.get("users"), dict) else {}) target_user_id, target_user = self._preferred_proactive_test_user(users, target_user_id) if not target_user_id or not target_user: - add_step("目标会话", "error", "没有找到已启用且带私聊会话的私聊对象") + add_step("目标会话", "error", "没有找到已启用且带私聊会话的用户") return { "ok": False, "title": "主动消息链路测试", "steps": steps, - "error": "没有找到可用于测试的私聊对象", + "error": "没有找到可用于测试的用户", } stored_umo = self._single_line(target_user.get("umo"), 180) route_resolver = getattr(self.plugin, "_private_delivery_umo_for_user_id", None) @@ -3672,14 +3657,14 @@ class PrivateCompanionPageApi(PrivateCompanionPageApiQzoneMixin, PrivateCompanio async with self.plugin._data_lock: current = self.plugin._get_user(target_user_id) if not isinstance(current, dict) or not current.get("enabled", True): - add_step("临时任务", "error", "目标私聊对象未启用") + add_step("临时任务", "error", "目标用户未启用") return { "ok": False, "title": "主动消息链路测试", "user_id": target_user_id, "umo": umo, "steps": steps, - "error": "目标私聊对象未启用", + "error": "目标用户未启用", } if current.get("proactive_sending"): add_step("临时任务", "error", "该用户已有主动发送正在进行") @@ -5348,13 +5333,13 @@ class PrivateCompanionPageApi(PrivateCompanionPageApiQzoneMixin, PrivateCompanio daily_limit = self._int(getattr(self.plugin, "max_daily_messages", 0)) budget = token_stats.get("budget", {}) if not enabled_users: - add("warn", "主动消息没有私聊对象", "当前没有启用的私聊对象,主动消息不会有目标。", "到私聊页新增或启用对象", "private", "proactive.no_enabled_users") + add("warn", "主动消息没有用户", "当前没有启用的用户,主动消息不会有目标。", "到用户页新增或启用用户", "private", "proactive.no_enabled_users") elif daily_limit <= 0: add("warn", "私聊主动总额度为 0", "每日主动上限为 0 时,主动念头、候选、主动行为生成与发送均已停止。", "到模块配置调高每日主动上限", "modules", "proactive.daily_limit_zero") elif not runtime.get("healthy"): add("warn", "主动循环心跳不新鲜", runtime.get("last_tick_error") or "最近没有检测到主动循环心跳。", "查看主动页的循环状态", "proactive", "proactive.loop_stale") else: - add("ok", "主动循环可运行", f"启用对象 {len(enabled_users)} 个,最近心跳 {runtime.get('last_tick_started') or '-'}。", "", "proactive") + add("ok", "主动循环可运行", f"启用用户 {len(enabled_users)} 个,最近心跳 {runtime.get('last_tick_started') or '-'}。", "", "proactive") if budget.get("exceeded"): add("error", "今日 Token 硬限额已耗尽", f"今日已用 {budget.get('used')},硬限额 {budget.get('limit')}。", "调高每日 Token 限额或等待明日重置", "tokens") @@ -9840,7 +9825,15 @@ class PrivateCompanionPageApi(PrivateCompanionPageApiQzoneMixin, PrivateCompanio elif platform_kind == "qq_official": display_name = nickname if nickname and nickname not in generic_names else f"QQ 官方 · {user_id_text[:8]}" else: - display_name = f"临时会话 · {user_id_text[:8]}" + platform_label = self._single_line((platform_profile or {}).get("label"), 40) or "其他平台" + display_name = nickname if nickname and nickname not in generic_names else f"{platform_label} · {user_id_text[:8]}" + platform_group = ( + "qq" + if platform_kind in {"onebot", "qq_official"} + else "telegram" + if platform_kind == "telegram" + else "web_other" + ) relationship_stage = "" rel_state = user.get("relationship_state") if isinstance(user.get("relationship_state"), dict) else {} if isinstance(rel_state, dict): @@ -9880,9 +9873,10 @@ class PrivateCompanionPageApi(PrivateCompanionPageApiQzoneMixin, PrivateCompanio "display_name": display_name, "is_qq_user": is_qq_user, "platform_kind": platform_kind, + "platform_group": platform_group, "platform_label": self._single_line((platform_profile or {}).get("label"), 60), "identity_label": self._single_line((platform_profile or {}).get("identity_label"), 60), - "stable_platform_identity": bool(platform_kind == "qq_official" or is_qq_user), + "stable_platform_identity": bool(platform_kind in {"qq_official", "telegram"} or is_qq_user), "source": source, "enabled": bool(user.get("enabled", True)), "relationship_role": role, @@ -11728,6 +11722,8 @@ class PrivateCompanionPageApi(PrivateCompanionPageApiQzoneMixin, PrivateCompanio def _feature_flags(self) -> dict[str, bool]: keys = [ "enable_proactive_only_mode", + "enable_auto_user_profile_creation", + "enable_custom_relationship_stage_policy", "enable_proactive_chat_integration", "enable_mai_style_integration", "enable_companion_memory", @@ -12315,7 +12311,7 @@ class PrivateCompanionPageApi(PrivateCompanionPageApiQzoneMixin, PrivateCompanio @staticmethod def _migration_section_label(key: str) -> str: return { - "users": "私聊对象资料", + "users": "用户档案资料", "groups": "群聊观测资料", "worldbook_entries": "关系网原始条目", "worldbook_member_profiles": "关系网成员资料", @@ -13041,6 +13037,14 @@ class PrivateCompanionPageApi(PrivateCompanionPageApiQzoneMixin, PrivateCompanio "enable_almanac_perception", "default_nickname", "default_style", + "auto_enable_companion_for_new_users", + "auto_profile_platforms", + "default_nickname_strategy", + "default_relationship_role", + "default_relationship_score", + "default_proactive_enabled", + "default_proactive_daily_limit", + "relationship_stage_policy", "reply_style_prompt", "enable_persona_voice_channels", "persona_conversation_voice_prompt", @@ -13443,6 +13447,9 @@ class PrivateCompanionPageApi(PrivateCompanionPageApiQzoneMixin, PrivateCompanio if key not in keys and key not in provider_keys: keys.append(key) values = {key: getattr(self.plugin, key, self._config_get(key)) for key in keys} + values["relationship_stage_policy"] = normalize_relationship_stage_policy( + getattr(self.plugin, "relationship_stage_policy", None) + ) for key in self._schema_bool_keys(): if key not in values: continue @@ -14153,9 +14160,9 @@ class PrivateCompanionPageApi(PrivateCompanionPageApiQzoneMixin, PrivateCompanio ) if enabled_users: - add("ok", "私聊对象已就绪", f"已启用 {enabled_users} 个私聊对象") + add("ok", "用户已就绪", f"已启用 {enabled_users} 个用户") else: - add("warn", "暂无启用的私聊对象", "私聊主动陪伴没有明确目标", "在私聊页新增对象或配置 target_user_ids", "proactive.no_enabled_users") + add("warn", "暂无启用的用户", "私聊主动陪伴没有明确目标", "在用户页新增用户或配置 target_user_ids", "proactive.no_enabled_users") max_daily = int(getattr(self.plugin, "max_daily_messages", 0) or 0) effective_max_daily = max_daily @@ -14205,7 +14212,7 @@ class PrivateCompanionPageApi(PrivateCompanionPageApiQzoneMixin, PrivateCompanio add("info", "每日 Token 软限额已关闭", "功能全开时后台任务会按各自开关正常运行") if features.get("enable_companion_memory"): - add("ok", "私聊长期画像已启用", "按私聊对象整理偏好、边界、关系线索和重要事实") + add("ok", "私聊长期画像已启用", "按用户整理偏好、边界、关系线索和重要事实") else: add("info", "私聊长期画像已关闭", "不会新增私聊长期画像,已有资料仍可管理") if features.get("enable_expression_learning"): @@ -14800,6 +14807,9 @@ class PrivateCompanionPageApi(PrivateCompanionPageApiQzoneMixin, PrivateCompanio def _apply_config_value(self, key: str, value: Any, overrides: dict[str, Any] | None = None) -> None: self._set_config_value(key, value) + if key == "relationship_stage_policy": + self.plugin.relationship_stage_policy = normalize_relationship_stage_policy(value) + return if key == "external_image_api_endpoints": normalizer = getattr(self.plugin, "_normalize_external_image_api_endpoints", None) endpoints = normalizer(value) if callable(normalizer) else (value if isinstance(value, list) else []) @@ -15389,6 +15399,8 @@ class PrivateCompanionPageApi(PrivateCompanionPageApiQzoneMixin, PrivateCompanio def _allowed_feature_keys(self) -> set[str]: return { "enable_proactive_only_mode", + "enable_auto_user_profile_creation", + "enable_custom_relationship_stage_policy", "enable_mai_style_integration", "enable_companion_memory", "enable_expression_learning", @@ -15588,6 +15600,14 @@ class PrivateCompanionPageApi(PrivateCompanionPageApiQzoneMixin, PrivateCompanio "enable_almanac_perception", "default_nickname", "default_style", + "auto_enable_companion_for_new_users", + "auto_profile_platforms", + "default_nickname_strategy", + "default_relationship_role", + "default_relationship_score", + "default_proactive_enabled", + "default_proactive_daily_limit", + "relationship_stage_policy", "reply_style_prompt", "enable_persona_voice_channels", "persona_conversation_voice_prompt", @@ -15985,8 +16005,44 @@ class PrivateCompanionPageApi(PrivateCompanionPageApiQzoneMixin, PrivateCompanio return keys def _normalize_setting_value(self, key: str, value: Any) -> Any: + if key == "relationship_stage_policy": + return relationship_stage_policy_json(value) if key in self._schema_bool_keys(): return self._normalize_bool_value(value) + if key == "auto_profile_platforms": + if isinstance(value, str): + raw_items = re.split(r"[\s,,、;;]+", value) + elif isinstance(value, (list, tuple, set)): + raw_items = list(value) + else: + raw_items = [] + aliases = { + "aiocqhttp": "onebot", + "napcat": "onebot", + "qq": "onebot", + "qqofficial": "qq_official", + "qqbot": "qq_official", + "telegram_bot": "telegram", + "telegrambot": "telegram", + "tg": "telegram", + } + allowed = {"onebot", "qq_official", "telegram", "webchat", "generic"} + normalized: list[str] = [] + for item in raw_items: + text = str(item or "").strip().lower().replace("-", "_").replace(" ", "") + text = aliases.get(text, text) + if text in allowed and text not in normalized: + normalized.append(text) + return normalized or ["onebot", "qq_official", "telegram", "webchat", "generic"] + if key == "default_nickname_strategy": + text = str(value or "platform_display_name").strip().lower() + return text if text in {"platform_display_name", "fixed", "user_id"} else "platform_display_name" + if key == "default_relationship_role": + return "friend" + if key == "default_relationship_score": + return self._int(value, 0, -1200, 1200) + if key == "default_proactive_daily_limit": + return self._int(value, 0, 0, 30) expression_modes = { "expression_private_learning_source_mode": ({"owner", "selected", "all"}, "owner"), "expression_group_learning_source_mode": ({"disabled", "selected", "all"}, "disabled"), diff --git a/page_api_users_groups.py b/page_api_users_groups.py index baa6e3c..b65388f 100644 --- a/page_api_users_groups.py +++ b/page_api_users_groups.py @@ -116,6 +116,7 @@ class PrivateCompanionPageApiUsersGroupsMixin: user["enabled"] = enabled user["manual_enabled"] = enabled user["manual_disabled"] = not enabled + user["auto_enabled"] = False if enabled: self.plugin._ensure_private_user_umo(user_id, user) if not enabled: diff --git a/pages/陪伴面板/app.css b/pages/陪伴面板/app.css index 5b0f9c7..f493f16 100644 --- a/pages/陪伴面板/app.css +++ b/pages/陪伴面板/app.css @@ -2142,6 +2142,82 @@ input[type="search"] { font-size: 12px; } +.companion-intimacy-head p { + margin: 5px 0 0; + color: var(--muted); + font-size: 12px; +} + +.companion-intimacy-current { + display: grid; + justify-items: end; + gap: 2px; +} + +.companion-intimacy-current strong { + color: var(--accent-strong); + font-size: 20px; +} + +.companion-intimacy-current span { + color: var(--muted); + font: 700 13px ui-monospace, SFMono-Regular, Consolas, monospace; +} + +.relationship-stage-bar { + display: grid; + grid-template-columns: repeat(8, minmax(72px, 1fr)); + gap: 5px; + overflow-x: auto; + padding: 18px 1px 7px; +} + +.relationship-stage-segment { + position: relative; + display: grid; + gap: 5px; + min-width: 72px; + color: var(--muted); + font-size: 11px; + text-align: center; +} + +.relationship-stage-segment i { + display: block; + height: 7px; + border-radius: 999px; + background: color-mix(in srgb, var(--line) 84%, white 16%); +} + +.relationship-stage-segment.is-current { + color: var(--accent-strong); + font-weight: 700; +} + +.relationship-stage-segment.is-current i { + background: linear-gradient(90deg, var(--accent), var(--accent-strong)); + box-shadow: 0 0 0 3px color-mix(in srgb, var(--accent) 16%, transparent); +} + +.relationship-stage-segment b { + position: absolute; + top: -17px; + left: 50%; + transform: translateX(-50%); + border-radius: 999px; + padding: 1px 6px; + background: var(--accent-strong); + color: #fff; + font-size: 10px; +} + +.companion-intimacy-meta { + flex-wrap: wrap; + justify-content: flex-start; + color: var(--text-muted); + font-size: 12px; +} + .stack-form { display: grid; gap: 10px; @@ -18845,6 +18921,103 @@ textarea { color: var(--muted); } +.feature-param-row-policy { + grid-template-columns: 1fr; +} + +.relationship-policy-editor { + display: grid; + gap: 12px; + min-width: 0; +} + +.relationship-policy-notice { + border: 1px solid color-mix(in srgb, var(--accent) 28%, var(--line)); + border-radius: 8px; + padding: 9px 11px; + background: color-mix(in srgb, var(--accent) 7%, var(--surface)); + color: var(--muted); + font-size: 12px; + line-height: 1.55; +} + +.relationship-policy-grid { + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: 10px; +} + +.relationship-policy-stage { + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: 9px; + border: 1px solid var(--line-soft); + border-radius: 10px; + padding: 11px; + background: var(--surface); +} + +.relationship-policy-stage > header, +.relationship-policy-stage > label:nth-of-type(2), +.relationship-policy-stage > label:nth-of-type(3), +.relationship-policy-behaviors { + grid-column: 1 / -1; +} + +.relationship-policy-stage > header { + display: flex; + align-items: center; + justify-content: space-between; + gap: 8px; + color: var(--muted); + font-size: 11px; +} + +.relationship-policy-stage label { + display: grid; + gap: 5px; + color: var(--muted); + font-size: 11px; +} + +.relationship-policy-stage input, +.relationship-policy-stage textarea { + width: 100%; + min-width: 0; + border: 1px solid var(--line); + border-radius: 7px; + padding: 7px 8px; + background: var(--surface); + color: var(--ink); + font: inherit; +} + +.relationship-policy-behaviors { + display: flex; + flex-wrap: wrap; + gap: 6px; +} + +.relationship-policy-behaviors label { + display: inline-flex; + grid-auto-flow: column; + align-items: center; + gap: 5px; + border: 1px solid var(--line-soft); + border-radius: 999px; + padding: 5px 8px; +} + +.relationship-policy-behaviors input { + width: auto; +} + +@media (max-width: 900px) { + .relationship-policy-grid { + grid-template-columns: 1fr; + } +} + .photo-reference-launch { display: flex; align-items: center; @@ -19582,6 +19755,49 @@ table { text-align: right; } +.user-platform-group td { + padding: 9px 10px 7px; + border-bottom: 0; + background: color-mix(in srgb, var(--accent-soft) 52%, var(--surface)); +} + +.user-platform-group button { + display: grid; + grid-template-columns: auto auto minmax(0, 1fr) auto; + align-items: center; + gap: 8px; + width: 100%; + border: 0; + padding: 0; + background: transparent; + color: var(--ink); + text-align: left; + cursor: pointer; +} + +.user-platform-group button > span { + width: 14px; + color: var(--accent-strong); +} + +.user-platform-group button small { + overflow: hidden; + color: var(--muted); + text-overflow: ellipsis; + white-space: nowrap; +} + +.user-platform-group button em { + min-width: 28px; + border-radius: 999px; + padding: 2px 8px; + background: var(--surface); + color: var(--accent-strong); + font-style: normal; + font-weight: 700; + text-align: center; +} + .user-id-line { display: inline-flex; align-items: center; @@ -19681,6 +19897,38 @@ tbody tr.is-selected { text-align: right; } +.relationship-phase-summary { + display: inline-flex; + align-items: baseline; + gap: 7px; + margin-top: 5px; +} + +.relationship-phase-summary b { + color: var(--accent-strong); +} + +.relationship-phase-summary small { + color: var(--muted); +} + +@media (max-width: 720px) { + .user-platform-group button { + grid-template-columns: auto auto 1fr; + } + + .user-platform-group button small { + grid-column: 2 / -1; + grid-row: 2; + } + + .user-platform-group button em { + grid-column: 3; + grid-row: 1; + justify-self: end; + } +} + .mono { font-family: ui-monospace, SFMono-Regular, Consolas, "Liberation Mono", monospace; font-size: 12px; diff --git a/pages/陪伴面板/app.js b/pages/陪伴面板/app.js index 7f9e834..fcfb10b 100644 --- a/pages/陪伴面板/app.js +++ b/pages/陪伴面板/app.js @@ -28,6 +28,7 @@ const state = { memoFilter: "active", memoEditorId: "", selectedUserId: "", + userPlatformCollapsed: {}, learningSection: "expressions", expressionWorkspaceView: "library", selectedExpressionReviewRuleId: "", @@ -1014,6 +1015,8 @@ const providerGroupByKey = providerGroups.reduce((acc, group) => { const featureMeta = { enable_proactive_only_mode: ["仅保留主动能力", "只让本插件负责主动私聊调度、生成和发送;普通私聊/群聊放行给默认主链或其他插件。"], + enable_auto_user_profile_creation: ["新用户默认档案", "首次真实私聊先建立最小用户档案;是否由本插件接管回复、是否允许主动关心分别配置。"], + enable_custom_relationship_stage_policy: ["亲密度阶段策略", "保留固定八阶段和分数范围,配置每一阶段的标签、语气、称呼尺度与软行为上限。"], enable_mai_style_integration: ["私聊互动策略", "把相处分寸、偏好和本轮接话方式注入回复。"], enable_companion_memory: ["长期画像", "沉淀用户偏好、边界、关系线索和可复用事实。"], enable_expression_learning: ["表达方式学习", "从选定私聊或群聊提取抽象表达特征,并按范围用于私聊被动、私聊主动和群聊回复。"], @@ -1094,9 +1097,9 @@ const featureMeta = { enable_group_relationship_graph: ["群友互动图", "记录成员之间近期谁常互相接话、玩梗或争论。"], enable_group_privacy_guard: ["群隐私保护", "保护私聊信息。"], enable_worldbook_member_recognition: ["群聊关系网", "以 QQ 号确认稳定身份,关系备注和重要记忆都放在这里。"], - enable_cross_user_memory_bridge: ["跨用户记忆", "主要用户可查询 Bot 与其他用户/群聊的近期互动摘要;只读,不发送消息。"], + enable_cross_user_memory_bridge: ["跨用户互动摘要查询", "主要用户可查询 Bot 与其他用户/群聊的近期互动摘要;只读,不发送消息。"], enable_atrelay_tools: ["跨群转述", "查询群成员、按关系网解析 @ 对象,并转述到群聊或私聊。"], - enable_livingmemory_integration: ["外部记忆插件协同", "统一接入已适配的外部长期记忆插件;当前支持“我会牢牢记住你”/MemoryCompanion 与 LivingMemory。"], + enable_livingmemory_integration: ["记忆插件协同", "统一接入已适配的外部长期记忆插件;当前支持“我会牢牢记住你”/MemoryCompanion 与 LivingMemory。"], enable_bilibili_integration: ["B站 AI Bot 联动", "读取 B站 AI Bot 观看日志,并在合适节点私聊分享。"], enable_bilibili_boredom_watch: ["无聊刷 B 站", "空档看视频。"], enable_news_integration: ["新闻阅读", "低频读取 RSS/Atom 新闻源,形成近期见闻和主动分享素材。"], @@ -1138,6 +1141,14 @@ const featurePublicKeyAliases = { }; const featureGroups = [ + { + title: "用户与关系", + note: "新用户建档默认值与唯一可见的陪伴亲密度阶段策略。", + keys: [ + "enable_auto_user_profile_creation", + "enable_custom_relationship_stage_policy", + ], + }, { title: "通用能力", note: "私聊、群聊和主动链路都会参考的状态、媒介、表达学习、收口与发送能力。", @@ -1179,7 +1190,7 @@ const featureGroups = [ }, { title: "群聊功能", - note: "按要解决的问题找开关:启用范围、续话、读空气、合并、理解、安全、唤醒、学习、复读、转述和跨用户记忆。", + note: "按要解决的问题找开关:启用范围、续话、读空气、合并、理解、安全、唤醒、学习、复读、转述和跨用户互动摘要。", keys: [ "enable_group_companion", "enable_group_member_safety", @@ -1438,9 +1449,18 @@ const safeFeatureKeys = [ ]; const configLabels = { - enabled_user_count: "启用私聊对象", - user_count: "私聊对象总数", - require_opt_in: "是否需要私聊确认", + enabled_user_count: "启用用户", + user_count: "用户总数", + require_opt_in: "是否需要用户确认", + auto_enable_companion_for_new_users: "自动启用新用户陪伴", + auto_profile_platforms: "自动建档平台", + default_nickname_strategy: "默认称呼来源", + default_nickname: "默认称呼", + default_relationship_role: "默认关系角色", + default_relationship_score: "默认亲密度", + default_proactive_enabled: "允许新用户主动关心", + default_proactive_daily_limit: "新用户每日主动上限", + relationship_stage_policy: "八阶段策略", default_style: "默认语气", reply_style_prompt: "回复风格提示词", enable_persona_voice_channels: "启用分通道人格风格", @@ -1980,6 +2000,16 @@ const configLabels = { }; const configDescriptions = { + auto_enable_companion_for_new_users: "建档与接管分离。关闭时仍建立可见档案,但继续放行 AstrBot 默认主链;开启后才由本插件接管普通回复。", + auto_profile_platforms: "每行一个规范平台类型:onebot、qq_official、telegram、webchat、generic。未知平台不会被猜成 QQ。", + default_nickname_strategy: "优先使用平台显示名、固定称呼或用户 ID;平台显示名不可用时回退到默认称呼。", + default_nickname: "平台显示名不可用或选择固定称呼时使用;不改变用户身份。", + default_style: "新用户基础语气。单用户设置和当前亲密度阶段策略优先于此默认值。", + default_relationship_role: "自动档案固定为普通用户 / 朋友,不允许由默认配置成为主要用户。", + default_relationship_score: "只影响之后自动创建的档案,不重写既有用户,范围 -1200 到 1200。", + default_proactive_enabled: "默认关闭。只有自动启用陪伴时才可能允许主动关心。", + default_proactive_daily_limit: "新用户每天最多主动关心次数;未自动启用陪伴时强制为 0。", + relationship_stage_policy: "固定八阶段键与阈值,只编辑显示、语气、称呼尺度和软行为,不能授予权限或绕过 P4。", enable_proactive_only_mode: "开启后,本插件只保留主动私聊的日程、主动生成和发送链路;普通私聊、群聊消息不会再被本插件做状态/TTS/图片/转发/群聊上下文注入,也不会触发本插件的被动回复增强,但不会阻止 AstrBot 默认回复或其他插件处理。用户回复主动消息时仍会被轻量记为已回应。适合只想使用主动陪伴、或担心本插件被动链路误接管/误识别的场景。", enable_llm_proactive_message: "开启后,主动调度只负责挑选动机和时机,真正文本会调用 AstrBot 人格生成;关闭时回退为本地模板,更省但更机械。", enable_proactive_chat_integration: "检测到 Proactive Chat 时自动建立深度运行时联动:生成前检查两套调度是否撞车,并注入当前关系、状态、时机和已审核表达;生成后统一复核;平台发送无异常返回后才结算成功。不会修改对方插件文件或配置,也不会新建第二套定时任务。版本不兼容时自动降级为发送前装饰联动。", @@ -2132,12 +2162,12 @@ const configDescriptions = { TROUBLESHOOTING_PROVIDER_ID: "用于“陪伴 答疑”的插件专家问答和排障中心模型复核。建议使用能阅读长上下文、理解代码和配置关系的模型;留空时快速配置使用复杂推理模型。", proactive_intensity_preset: "默认关闭,完全沿用手动参数。开启后只在运行态调整私聊主动、群聊唤醒和插话的有效频率,并会在排障页显示当前预设;最高档不限制每日主动次数和每日群聊插话次数,不再替用户节省主动成本,会忽略 Token 软限额降载,但不会绕过免打扰、休息、用户拒绝、隐私和每日 Token 硬限额。", idle_minutes: "用户多久没有活跃后,才被视为适合主动触达或分享的空闲状态。", - min_interval_minutes: "同一私聊对象两次主动消息之间的最小间隔,避免频繁打扰。", + min_interval_minutes: "同一用户两次主动消息之间的最小间隔,避免频繁打扰。", proactive_unanswered_slowdown_start: "用户连续几次不回应 Bot 主动消息后,开始自动降低主动频率。", proactive_unanswered_max_interval_multiplier: "连续未回应时,最小主动间隔最多放大到多少倍。", friend_unanswered_max_cooldown_hours: "次要用户持续未回应时,主动消息最长可延后到多少小时内再尝试。", timer_pre_silence_minutes: "已有聊天临时预约时,距离预约时间不足该分钟数会暂停普通主动、链式追问和未回复补一句,避免抢在官方定时计划前打扰。若预约文本带有休息/睡觉/起床语义,会从预约创建起静默到到点。", - max_daily_messages: "每个私聊对象每天最多收到多少条插件主动消息。", + max_daily_messages: "每个用户每天最多收到多少条插件主动消息。", passive_topic_memory_hours: "记录最近被动回复主题的时间窗口,用来判断短时间内是否又在重复同类话题。", tts_generation_mode: "先决定语音从哪里来。快速标签模式追求低延迟:主模型可写 ,插件发送前轻处理。后处理模式追求稳定:主模型只写普通回复,发送前由 TTS 文本模型判断是否需要语音并完成翻译/改写。", tts_voice_language: "控制真正送入 TTS 的语音正文语种。可让聊天文本保留中文, 内使用日语、中文或英语朗读;日语模式会尽量避免明显非日语文本直接进入 TTS,并会给缺少说明的外语语音块补中文释义。", @@ -2236,7 +2266,7 @@ const configDescriptions = { segmented_proactive_interval_max: "两段消息之间的最大等待秒数;普通 LLM 回复只影响后台补发片段。", segmented_proactive_log_base: "对数间隔的底数。数值越小,长句间隔增长越明显。", group_access_mode: "决定群聊功能按白名单还是黑名单生效。白名单模式只处理白名单里的群;黑名单模式默认处理所有群,但会跳过黑名单里的群。初次使用建议白名单模式。", - group_whitelist_ids: "白名单模式下允许插件参与的群号列表。可填写数组,也可在输入框里一行一个或用逗号分隔;只影响群聊功能,不影响私聊对象。", + group_whitelist_ids: "白名单模式下允许插件参与的群号列表。可填写数组,也可在输入框里一行一个或用逗号分隔;只影响群聊功能,不影响用户档案。", group_blacklist_ids: "黑名单模式下禁止插件参与的群号列表。可填写数组,也可在输入框里一行一个或用逗号分隔;适合临时屏蔽机器人多、话题敏感或不想观察的群。", group_conversation_followup_seconds: "群里用户叫过 Bot 后,后续未 @ 的消息在多久内可能被判断为仍在对 Bot 说。", group_conversation_followup_max_turns: "一次群聊连续对话最多自动续接几轮,防止 Bot 一直卷进对话。", @@ -2308,20 +2338,20 @@ const configDescriptions = { group_slang_web_search_terms: "黑话释义联网参考开启时,每次最多从多少个候选词里挑选待查词;实际每轮只联网搜索 1 个词,并缓存结果/失败冷却,避免短时间连发搜索。", group_slang_web_search_results: "黑话释义联网参考开启时,每个候选词最多保留多少条网页摘要给模型判断匹配程度。", memory_refresh_interval_minutes: "长期画像整理的最小间隔,越短越容易产生模型调用。", - max_companion_memory_items: "每个私聊对象最多保留多少条长期画像条目。", + max_companion_memory_items: "每个用户最多保留多少条长期画像条目。", expression_learning_mode: "light 更克制;balanced 会按短确认、提问、请求、玩笑和情绪等场景应用重复证据;aggressive 会参考更多通过审核的短句和句尾样本,建议搭配手动审核。", enable_expression_manual_review: "开启后,原始观察素材先进入“学习”页待整理区;模型生成的情境表达和语法习惯无论此项是否开启都必须审核。", enable_expression_style_review: "开启后,回复复核会额外处理表达学习过头、异常逗号/断句、照抄样本等问题。", max_learned_expression_items: "每个私聊或群聊来源最多保留多少条情境表达、语法习惯和观察素材;每轮最多召回 2 条已审核规则。", episode_memory_refresh_messages: "累计多少条私聊消息后尝试整理一次对话片段。", episode_memory_refresh_minutes: "距离上次整理多久后允许再次整理私聊片段。", - max_dialogue_episodes: "每个私聊对象最多保留多少条对话片段;实际回复时只择要使用最近或相关片段。", + max_dialogue_episodes: "每个用户最多保留多少条对话片段;实际回复时只择要使用最近或相关片段。", user_habit_min_count: "同一时段同类行为至少出现多少次,才被视为用户习惯;旧习惯会衰减,被动回复还要求当前时段和话题相关。", enable_food_menu_recommendation: "用户明确纠结吃什么、点什么或夜宵时,从候选菜单里取少量贴合项作回复参考;饭点关心中识别到实际吃过的内容也会自动回填。候选本身在这个功能详情页管理。", enable_meal_care_proactive: "早餐、午饭、晚饭窗口独立安排吃饭关心,仅面向主要用户,并继续遵守免打扰、主动额度和未回应降速。", meal_care_max_daily: "每天最多选择几餐主动询问,默认 2,避免三餐都像打卡。", meal_care_followup_minutes: "没有得到具体饮食信息时,等待多久允许一次低压补问;每餐最多补问一次。", - user_habit_max_items: "每个私聊对象最多保留多少条行为习惯模式。", + user_habit_max_items: "每个用户最多保留多少条行为习惯模式。", skill_growth_rate: "技能经验增长倍率。1 为默认速度,越高升级越快。", skill_growth_custom_skills: "手动补充技能名,可用逗号、换行或 JSON 列表表达。", enable_skill_growth_passive_injection: "开启后普通聊天会注入 Bot 当前能力状态和自我认知。默认关闭;关闭时技能成长仍会结算,并可继续影响日程和能力边界。", @@ -2364,7 +2394,7 @@ const configDescriptions = { qzone_comment_inbox_interval_minutes: "两次评论收件箱自动检查之间的最小间隔。", qzone_comment_inbox_recent_posts: "每次向前扫描多少条自己的最近说说详情。", qzone_comment_inbox_max_replies_per_tick: "每次后台检查最多公开回复多少条新评论,建议保持 1,避免刷屏。", - photo_action_max_daily: "每个私聊对象每天最多生成几张主动图片。真实生成成功就消耗额度,避免失败重试时反复生图。", + photo_action_max_daily: "每个用户每天最多生成几张主动图片。真实生成成功就消耗额度,避免失败重试时反复生图。", proactive_photo_text_probability: "在主动生图可用、额度未用完,且本轮主动有生活画面或视觉切口时,把普通文字主动升级成带图的概率,按百分比填写。", photo_generation_backend: "auto 会在在线图片 API 配置完整时优先尝试在线 API,失败后回退本地 ComfyUI/SDGen;未配置在线 API 时使用本地后端。comfyui/sdgen/external 可指定单一后端。tool_call 会调用其他插件注册的函数工具(需在下方填写工具名)。", COMFYUI_TEXT2IMG_WORKFLOW_NAME: "用于普通随手拍、风景、桌面小物等 photo_text 的 ComfyUI 工作流名。", @@ -2534,6 +2564,8 @@ const advancedCycleSettingKeys = [ ]; 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_proactive_enabled", "default_proactive_daily_limit"], + enable_custom_relationship_stage_policy: ["relationship_stage_policy"], enable_mai_style_integration: [ "default_style", "reply_style_prompt", @@ -3313,6 +3345,13 @@ const featureSettingSections = { }; const featureSettingTypes = { + auto_enable_companion_for_new_users: { type: "checkbox" }, + auto_profile_platforms: { type: "textarea", rows: 5 }, + default_nickname_strategy: { type: "select", options: [["platform_display_name", "优先平台显示名"], ["fixed", "固定称呼"], ["user_id", "用户 ID"]] }, + default_relationship_role: { type: "select", options: [["friend", "普通用户 / 朋友"]] }, + default_relationship_score: { type: "number", min: -1200, max: 1200, step: 1 }, + default_proactive_enabled: { type: "checkbox" }, + default_proactive_daily_limit: { type: "number", min: 0, max: 30, step: 1 }, forward_message_mode: { type: "select", options: [["inject", "注入"], ["transcribe", "转述"]] }, tts_generation_mode: { type: "select", options: [["fast_tag", "快速标签:主模型写私有标签"], ["postprocess", "后处理:判断+翻译模型"]] }, tts_fishaudio_model: { type: "select", options: [["auto", "自动识别(官方接口默认 S2.1 Free)"], ["s2.1-pro-free", "S2.1 Pro Free"], ["s2.1-pro", "S2.1 Pro"], ["s2-pro", "S2 Pro"], ["s1", "S1 旧版"]] }, @@ -5568,7 +5607,7 @@ const setupGuideAdvancedItems = { key: "enable_companion_memory", title: "私聊长期画像", ask: "是否让 Bot 从长期私聊中整理稳定偏好、边界、关系线索和重要事实?", - description: "长期画像服务于对应私聊对象,不承担跨私聊或群聊的表达学习。", + description: "长期画像服务于对应用户档案,不承担跨用户或群聊的表达学习。", caution: "画像越多越需要定期清理;整理间隔太短会增加后台模型调用。", kind: "feature", settings: [ @@ -5875,7 +5914,7 @@ const setupGuideAdvancedItems = { }, { key: "enable_cross_user_memory_bridge", - title: "跨用户记忆", + title: "跨用户互动摘要查询", ask: "是否允许主要用户查询 Bot 与其他用户/群聊的互动线索?", description: "只读查询跨用户互动摘要,不负责发送消息。", caution: "涉及跨会话信息,建议保持仅主要用户可查。", @@ -8925,7 +8964,7 @@ function renderHealthPanel() { level: overview.livingmemory?.conflict ? "warn" : features.enable_livingmemory_integration && (overview.livingmemory?.compatible_available || overview.livingmemory?.available || overview.livingmemory?.memory_companion_active) ? "ok" : "info", - title: "外部记忆插件协同", + title: "记忆插件协同", text: livingMemoryHealthText(overview.livingmemory), }, { @@ -9121,7 +9160,7 @@ function renderSetupProgress() { } function livingMemoryHealthText(livingmemory) { - if (!livingmemory) return "未读取到外部记忆插件协同状态"; + if (!livingmemory) return "未读取到记忆插件协同状态"; if (livingmemory.conflict_warning) return livingmemory.conflict_warning; const pluginName = livingmemory.selected_plugin_name || livingmemory.selected_plugin?.display_name || ""; if (!livingmemory.compatible_available && !livingmemory.available && !livingmemory.memory_companion_active) return "未检测到可协同记忆插件"; @@ -9133,7 +9172,7 @@ function livingMemoryHealthText(livingmemory) { } function livingMemoryStatusText(livingmemory) { - if (!livingmemory) return "未读取到外部记忆插件协同状态"; + if (!livingmemory) return "未读取到记忆插件协同状态"; const lines = [livingMemoryHealthText(livingmemory)]; const activePlugins = Array.isArray(livingmemory.active_plugins) ? livingmemory.active_plugins : []; if (activePlugins.length) { @@ -9201,7 +9240,7 @@ function renderUxReviewPanel() { const imageEnhanceEnabled = Boolean(settings.enable_private_image_self_recognition || features.enable_private_image_self_recognition); const items = [ { level: personaReady && worldReady && userReady ? "ok" : "warn", title: "世界知识", text: personaReady && worldReady && userReady ? (roleFilled >= 6 ? `角色资料 ${roleFilled}/8 项,世界观和用户关系已补齐` : "旧版文案已完整;标准化字段可按需补齐") : `角色资料 ${roleFilled}/8 项;补齐外貌识别点、爱好、禁忌和用户关系`, tab: "roleplay" }, - { level: Number(settings.max_daily_messages || 0) <= 0 || hasPrivateTargets ? "ok" : "warn", title: "私聊主动目标", text: Number(settings.max_daily_messages || 0) <= 0 ? "私聊主动关闭,无需目标列表" : (hasPrivateTargets ? `已识别 ${targetUsers.length || state.users.length} 个私聊对象` : "主动已开启,但目标列表为空"), tab: "config" }, + { level: Number(settings.max_daily_messages || 0) <= 0 || hasPrivateTargets ? "ok" : "warn", title: "用户主动目标", text: Number(settings.max_daily_messages || 0) <= 0 ? "私聊主动关闭,无需目标列表" : (hasPrivateTargets ? `已识别 ${targetUsers.length || state.users.length} 个用户` : "主动已开启,但目标列表为空"), tab: "config" }, { level: features.enable_group_companion ? (Number(group.enabled_group_count || 0) > 0 ? "ok" : "warn") : "info", title: "群聊入口", text: features.enable_group_companion ? `${group.enabled_group_count || 0}/${group.group_count || 0} 个群正在观测` : "群聊观察关闭,相关页仅保留管理视图", tab: "group" }, { level: imageEnhanceEnabled ? (settings.enable_private_image_vision_cache ? "ok" : "warn") : "info", title: "图片转述增强", text: imageEnhanceEnabled ? `缓存 ${imageCache.items || 0}/${imageCache.max_items || "不限"} 条;${settings.enable_private_image_vision_cache ? "重复图会复用摘要" : "缓存关闭,重复图会重复调用"}` : "图片转述增强关闭", tab: "image-cache" }, { level: featureKeys.length ? "ok" : "info", title: "功能开关", text: featureKeys.length ? `${enabledFeatureCount}/${featureKeys.length} 个主开关开启,归入 ${activeFeatureGroupCount}/${featureGroups.length} 个分类` : "等待功能开关数据", tab: "config" }, @@ -9636,13 +9675,13 @@ function troubleshootingFaqMarkup(data = {}, category = "all") { title: "为什么没有主动消息?", meta: proactiveMeta, body: [ - "先确认私聊对象已启用,并且没有处在静默、休息、冷却、每日上限、未回复降频或主动人格判定拦截中。", + "先确认用户档案已启用,并且没有处在静默、休息、冷却、每日上限、未回复降频或主动人格判定拦截中。", "再看上方“最近问题”和主动审计记录:如果显示“已放弃/已延后”,通常是时间窗、关系压力、内容重复或链路依赖不可用。", "最直接的验证方式是点“测试主动消息”,它会预约一次临时主动,检查生成、复核、发送和归档是否完整。", ], actions: [ { label: "看主动页", tab: "proactive" }, - { label: "看私聊对象", tab: "private" }, + { label: "看用户", tab: "private" }, { label: "测试主动消息", test: "proactive_message" }, ], }, @@ -10650,7 +10689,7 @@ function renderQuotaChart() { `; }); - $("#quotaChart").innerHTML = rows.length ? rows.join("") : `
暂无私聊对象
`; + $("#quotaChart").innerHTML = rows.length ? rows.join("") : `
暂无用户档案
`; } function userQuotaLabel(user) { @@ -10668,6 +10707,9 @@ function userPlatformBadge(user) { return `QQ 官方`; } if (user?.is_qq_user || user?.platform_kind === "onebot") return ""; + if (user?.platform_kind === "telegram") { + return `Telegram`; + } const label = String(user?.platform_label || "其他平台").trim() || "其他平台"; return `${escapeHtml(label)}`; } @@ -11980,7 +12022,7 @@ function expressionScopeItems(kind, selectedIds = []) { : state.users.map((user) => ({ id: String(user.user_id || "").trim(), label: user.display_name || user.nickname || user.user_id, - meta: user.relationship_role_label || "私聊对象", + meta: user.relationship_role_label || "用户", })); const knownIds = new Set(known.map((item) => item.id)); selected.forEach((id) => { @@ -11993,7 +12035,7 @@ function renderExpressionScopeChecklist(definition, selectedIds) { const selected = new Set((selectedIds || []).map((item) => String(item || ""))); const items = expressionScopeItems(definition.itemKind, selectedIds); if (!items.length) { - return `

暂无可选${definition.itemKind === "group" ? "群聊" : "私聊对象"},产生会话记录后会出现在这里。

`; + return `

暂无可选${definition.itemKind === "group" ? "群聊" : "用户"},产生会话记录后会出现在这里。

`; } return `
@@ -12309,18 +12351,40 @@ function renderUsers() { const text = `${user.user_id} ${user.nickname} ${user.umo}`.toLowerCase(); return !keyword || text.includes(keyword); }); - $("#userRows").innerHTML = rows.length - ? rows.map((user) => ` + const groupSpecs = [ + ["qq", "QQ", "NapCat / OneBot 与 QQ 官方"], + ["telegram", "Telegram", "Telegram 适配器"], + ["web_other", "网页 / 其他", "AstrBot WebChat 与其他适配器"], + ]; + const groupedRows = groupSpecs.map(([groupKey, label, note]) => { + const users = rows + .filter((user) => (user.platform_group || (user.platform_kind === "telegram" ? "telegram" : ["onebot", "qq_official"].includes(user.platform_kind) || user.is_qq_user ? "qq" : "web_other")) === groupKey) + .sort((a, b) => Number(b.last_seen_ts || 0) - Number(a.last_seen_ts || 0)); + if (!users.length) return ""; + const collapsed = Boolean(state.userPlatformCollapsed[groupKey]); + return ` + + + + ${collapsed ? "" : users.map((user) => ` ${escapeHtml(user.display_name || user.nickname || user.user_id)} ${userPlatformBadge(user)}${Array.isArray(user.alias_user_ids) && user.alias_user_ids.length ? ` 已合并 ${escapeHtml(user.alias_user_ids.length)} 个身份` : ""}
${escapeHtml(user.user_id)} - ${escapeHtml(user.enabled ? "启用" : "停用")} ${escapeHtml(user.relationship_role_label || "次要用户")} ${escapeHtml(user.relationship_stage || "未分层")}
陪伴亲密度 ${escapeHtml(user.relationship_intimacy?.value ?? 0)} · ${escapeHtml(user.relationship_intimacy?.phase?.label || user.relationship_intimacy?.band || "初识")} + ${escapeHtml(user.enabled ? "启用" : "停用")} ${escapeHtml(user.relationship_role_label || "次要用户")} ${escapeHtml(user.relationship_stage || "未分层")}
${escapeHtml(user.relationship_intimacy?.phase?.label || user.relationship_intimacy?.band || "初识")}亲密度 ${escapeHtml(user.relationship_intimacy?.value ?? 0)} 入站 ${escapeHtml(user.inbound_count)} · 回复 ${escapeHtml(user.reply_count)}
记忆 ${escapeHtml(user.memory_items)} 条 今日 ${escapeHtml(user.sent_today)} · 总计 ${escapeHtml(user.proactive_sent_count)}
${escapeHtml(user.next_proactive)} ${escapeHtml(user.last_seen)}
上次主动 ${escapeHtml(user.last_sent)} - `).join("") - : `暂无私聊对象`; + `).join("")}`; + }).join(""); + $("#userRows").innerHTML = rows.length ? groupedRows : `暂无用户档案`; + document.querySelectorAll("[data-user-platform-toggle]").forEach((button) => { + button.addEventListener("click", () => { + const key = button.dataset.userPlatformToggle || "web_other"; + state.userPlatformCollapsed[key] = !state.userPlatformCollapsed[key]; + renderUsers(); + }); + }); document.querySelectorAll("[data-user-toggle]").forEach((button) => { button.addEventListener("click", async (event) => { event.stopPropagation(); @@ -12329,7 +12393,7 @@ function renderUsers() { await runAction(() => postJson("/user/update", { user_id: user.user_id, enabled: !user.enabled, - }), !user.enabled ? "已启用私聊对象" : "已停用私聊对象", button); + }), !user.enabled ? "已启用用户" : "已停用用户", button); }); }); document.querySelectorAll("[data-copy-user-id]").forEach((button) => { @@ -12365,11 +12429,11 @@ async function renderUserDetail(forceFetch = false) { } box.innerHTML = `
- + - +
@@ -12385,7 +12449,6 @@ async function renderUserDetail(forceFetch = false) {
${renderCompanionIntimacyEditor(detail)}
- ${scoreGauge("陪伴亲密度", detail.relationship_intimacy?.value ?? 0, -1200, 1200)} ${scoreGauge("今日主动", detail.sent_today || 0, 0, proactiveGaugeMax(detail.sent_today, detail.effective_daily_limit, detail.effective_daily_limit_unlimited, state.overview?.private?.max_daily_messages || 8))} ${miniStat("片段", detail.dialogue_episode_count || (detail.dialogue_episodes || []).length)} ${miniStat("未完话头", Array.isArray(detail.open_loops) ? activeOpenLoopItems(detail.open_loops).length : (detail.open_loop_count || 0))} @@ -12417,11 +12480,13 @@ function renderCompanionIntimacyEditor(detail) { const value = Number.isInteger(rawValue) ? Math.max(min, Math.min(max, rawValue)) : 0; const phase = intimacy.phase && typeof intimacy.phase === "object" ? intimacy.phase : {}; const phaseLabel = String(phase.label || intimacy.band || "初识"); + const stages = Array.isArray(intimacy.stages) ? intimacy.stages : []; const trend = String(intimacy.trend || "unknown"); const trendLabel = trend === "rising" ? "正在升温" : trend === "cooling" ? "正在降温" : "变化轨迹暂未记录"; return `
-
COMPANION BASELINE

陪伴亲密度

${value}
-
当前亲密阶段${escapeHtml(phaseLabel)}范围 ${min} 到 ${max} · ${escapeHtml(trendLabel)}
+
COMPANION INTIMACY

陪伴亲密度阶段

${escapeHtml(phase.description || "以阶段展示长期关系位置;数字仅用于精确管理。")}

${escapeHtml(phaseLabel)}${value}
+ ${relationshipStageBar(stages, phase.key, value)} +
基础语气:${escapeHtml(phase.tone || detail.style || "自然")}称呼尺度:${escapeHtml(phase.address_level || "沿用已确认称呼")}${escapeHtml(trendLabel)}
仅调整陪伴关系基础;不影响 P4 好感、黑屋、审核或安全权限。 @@ -12430,6 +12495,17 @@ function renderCompanionIntimacyEditor(detail) {
`; } +function relationshipStageBar(stages, currentKey, value) { + const items = Array.isArray(stages) ? stages : []; + if (!items.length) return ""; + return ``; +} + function renderRelationshipPanel(panel) { const data = panel && typeof panel === "object" ? panel : {}; const intimacy = data.relationship_intimacy && typeof data.relationship_intimacy === "object" ? data.relationship_intimacy : {}; @@ -12437,13 +12513,9 @@ function renderRelationshipPanel(panel) { const memory = data.memory_phase && typeof data.memory_phase === "object" ? data.memory_phase : {}; const network = data.network && typeof data.network === "object" ? data.network : {}; const momentumLabels = { rising: "正在升温", cooling: "正在降温", steady: "保持稳定", unknown: "暂不可确认" }; - return detailBlock("关系面板", "好感、当前状态和上下文会在真实聊天中合成为本轮最终回复温度。", [ - ["陪伴亲密度", `${Number.isInteger(Number(intimacy.value)) ? Number(intimacy.value) : 0} / ${Number.isInteger(Number(intimacy.min)) ? Number(intimacy.min) : -1200} 到 ${Number.isInteger(Number(intimacy.max)) ? Number(intimacy.max) : 1200}`], - ["当前亲密阶段", intimacy.phase?.label || intimacy.band || "初识"], - ["变化轨迹", intimacy.trend === "rising" ? "正在升温" : intimacy.trend === "cooling" ? "正在降温" : "暂未记录变化轨迹"], - ["陪伴阶段", data.relationship_stage || "未分层"], + return detailBlock("互动与记忆协同", "陪伴亲密度由上方八阶段条统一展示;这里仅保留短期互动距离、记忆趋势和安全温度状态。", [ ["互动回应", `${interaction.reply_band || "暂无样本"} · 入站 ${Number(interaction.inbound_count || 0)} / 回复 ${Number(interaction.reply_count || 0)}`], - ["记忆关系阶段", `${memory.phase || "暂不可用"} · ${momentumLabels[memory.momentum_band] || "暂不可确认"}`], + ["记忆触动趋势", `${momentumLabels[memory.momentum_band] || "暂不可确认"} · 不独立决定称呼或基础语气`], ["关系网", `${network.status || "未登记节点"} · 待观察 ${Number(network.pending_observation_count || 0)}`], ["回复温度", data.reply_temperature?.status === "live_chat_only" ? "仅在真实聊天中合成" : (data.reply_temperature?.status || "仅在真实聊天中合成")], ]); @@ -13674,7 +13746,7 @@ function bindUserActions(detail) { style: form.get("style"), relationship_role: selectedRole, proactive_daily_limit: Number(form.get("proactive_daily_limit") || -1), - }), "已保存私聊对象", event.submitter); + }), "已保存用户档案", event.submitter); await refreshSelectedUserDetail(); }); document.querySelectorAll("[data-user-action]").forEach((button) => { @@ -13689,15 +13761,15 @@ function bindUserActions(detail) { body.clear_emotion_state = true; } if (action === "delete") { - if (!requireSecondClick(button, `user-delete:${detail.user_id}`, "再次点击删除该私聊用户、目标名单和相关映射", "再次点击删除")) return; + if (!requireSecondClick(button, `user-delete:${detail.user_id}`, "再次点击删除该用户档案、目标名单和相关映射", "再次点击删除")) return; await runAction(async () => { await postJson("/user/delete", body); state.selectedUserId = ""; await loadAll(); - }, "已删除私聊用户", button); + }, "已删除用户档案", button); return; } - await runAction(() => postJson("/user/update", body), "已更新私聊对象", button); + await runAction(() => postJson("/user/update", body), "已更新用户档案", button); await refreshSelectedUserDetail(); }); }); @@ -17906,7 +17978,7 @@ function renderProactiveCandidateFilters(users, selected, allTotal, selectedTota const userItems = Array.isArray(users) ? users : []; const selectedUser = userItems.find((user) => String(user.user_id || "") === selected); const title = selected === "all" - ? "全部私聊用户" + ? "全部用户" : (selectedUser?.label || selected || "未知用户"); const note = selected === "all" ? `${formatNumber(userItems.length)} 个用户 · ${formatNumber(visibleCount || 0)} 条记录` @@ -18646,7 +18718,7 @@ function renderModuleWorkbench(settings) { ], actions: [ ["proactive", "看主动候选"], - ["private", "管理私聊对象"], + ["private", "管理用户"], ], }, { @@ -20589,7 +20661,16 @@ function featureSwitchItem(key) { const tempUnlocked = featureTemporarilyUnlockedByProactiveOnly(key); const displayOn = checked || tempUnlocked; const related = proactiveOnlyRelatedUnlocks(key); - const stateText = locked ? (tempUnlocked ? "临时放行" : "已锁定") : checked ? "开启" : "关闭"; + let stateText = locked ? (tempUnlocked ? "临时放行" : "已锁定") : checked ? "开启" : "关闭"; + if (!locked && key === "enable_custom_relationship_stage_policy") { + const count = normalizeRelationshipPolicy(state.overview?.settings?.relationship_stage_policy).length || 8; + stateText = checked ? `自定义 · ${count} 阶段` : `内置 · ${count} 阶段`; + } + if (!locked && key === "enable_auto_user_profile_creation") { + stateText = checked + ? (toBool(state.overview?.settings?.auto_enable_companion_for_new_users) ? "建档并启用" : "只建档") + : "关闭"; + } const lockNote = tempUnlocked ? "已临时放行,关闭仅保留主动能力后清空" : "仅保留主动能力中,原配置保留"; const relatedText = related.length ? `建议同步:${related.map((item) => item.label || item.key).join("、")}` : ""; return ` @@ -21051,6 +21132,106 @@ function featureSettingInputType(key, value) { return { type: "text" }; } +const DEFAULT_RELATIONSHIP_POLICY = [ + ["deeply_distant", "极度疏离", -1200, -801, "明显保持距离,只做必要、克制且尊重边界的回应。", "克制、礼貌、低压力,不主动拉近关系", "仅使用姓名、固定称呼或“你”", 0, false, false, false, false], + ["strongly_distant", "强烈疏离", -800, -401, "关系处于明显降温期,优先稳住边界和基本礼貌。", "平静、简短、不过度解释", "只使用中性称呼", 0, false, false, false, false], + ["distant", "疏离", -400, -1, "保持自然但不过分熟络,避免擅自使用亲昵称呼。", "自然、客气、留有空间", "中性称呼", 0, false, false, false, false], + ["acquaintance", "初识", 0, 199, "刚开始相处,友好回应并逐步观察偏好。", "友好、自然、不自来熟", "优先固定称呼、姓名或“你”", 0, false, true, false, false], + ["familiar", "熟悉", 200, 599, "已有稳定互动,可以更轻松地接话和续话。", "轻松、友好、带一点熟悉感", "可自然使用昵称", 1, true, true, true, true], + ["close", "亲近", 600, 899, "关系稳定亲近,可更自然地关心近况和提及共同经历。", "温暖、亲近、尊重当前节奏", "可使用已确认的亲昵称呼", 2, true, true, true, true], + ["intimate", "亲密", 900, 1199, "关系亲密,表达可以柔软、有默契,但仍服从用户边界。", "亲密、柔软、不过度黏人", "可使用双方已接受的亲昵称呼", 3, true, true, true, true], + ["deeply_bonded", "深度联结", 1200, 1200, "长期关系达到当前上限,以稳定默契为主,不继续扩大权限。", "默契、温柔、稳定", "使用双方明确认可的专属称呼", 4, true, true, true, true], +].map(([key, label, min, max, description, tone, address_level, proactive_care_limit, allow_playful_jokes, allow_followup, allow_memory_mention, allow_daily_care]) => ({ + key, label, min, max, description, tone, address_level, proactive_care_limit, + allow_playful_jokes, allow_followup, allow_memory_mention, allow_daily_care, +})); + +const RELATIONSHIP_POLICY_BOOL_FIELDS = [ + ["allow_playful_jokes", "轻量玩笑"], + ["allow_followup", "自然续话"], + ["allow_memory_mention", "回忆提及"], + ["allow_daily_care", "日常关心"], +]; + +function normalizeRelationshipPolicy(value) { + let raw = value; + if (typeof raw === "string") { + try { raw = JSON.parse(raw); } catch { raw = []; } + } + if (raw && !Array.isArray(raw) && Array.isArray(raw.stages)) raw = raw.stages; + const byKey = new Map((Array.isArray(raw) ? raw : []) + .filter((item) => item && typeof item === "object" && item.key) + .map((item) => [String(item.key), item])); + return DEFAULT_RELATIONSHIP_POLICY.map((defaults) => { + const item = byKey.get(defaults.key) || {}; + const careLimit = Number(item.proactive_care_limit); + return { + ...defaults, + label: String(item.label || defaults.label).slice(0, 20), + description: String(item.description || defaults.description).slice(0, 160), + tone: String(item.tone || defaults.tone).slice(0, 120), + address_level: String(item.address_level || defaults.address_level).slice(0, 100), + proactive_care_limit: Number.isFinite(careLimit) ? Math.max(0, Math.min(30, Math.trunc(careLimit))) : defaults.proactive_care_limit, + ...Object.fromEntries(RELATIONSHIP_POLICY_BOOL_FIELDS.map(([field]) => [field, typeof item[field] === "boolean" ? item[field] : defaults[field]])), + }; + }); +} + +function relationshipPolicyEditor(value) { + const stages = normalizeRelationshipPolicy(value); + return ` +
+ +
阶段键与分数范围固定;这里只能调整表达和软行为,不能授予主要用户、跨用户查询、现实/平台动作或 P4 权限。
+
+ ${stages.map((stage, index) => ` +
+
${escapeHtml(`${stage.min}..${stage.max}`)}${escapeHtml(stage.key)}
+ + + + + +
+ ${RELATIONSHIP_POLICY_BOOL_FIELDS.map(([field, label]) => ``).join("")} +
+
+ `).join("")} +
+
+ `; +} + +function bindRelationshipPolicyEditor(root = document) { + const editor = root.querySelector?.("[data-relationship-policy-editor]"); + if (!editor) return; + const hidden = editor.querySelector('[data-feature-param="relationship_stage_policy"]'); + const sync = () => { + const stages = [...editor.querySelectorAll("[data-stage-key]")].map((card) => { + const base = normalizeRelationshipPolicy(hidden?.value)[Number(card.dataset.stageIndex || 0)] || {}; + const item = { ...base, key: card.dataset.stageKey || base.key || "" }; + card.querySelectorAll("[data-stage-field]").forEach((input) => { + const field = input.dataset.stageField || ""; + if (!field) return; + item[field] = input.type === "checkbox" + ? input.checked + : input.type === "number" + ? Math.max(0, Math.min(30, Number(input.value || 0))) + : input.value; + }); + return item; + }); + if (hidden) { + hidden.value = JSON.stringify(stages); + rememberFeatureParamDraft(hidden); + } + markFeatureDetailDirty(); + }; + editor.querySelectorAll("[data-stage-field]").forEach((input) => { + input.addEventListener(input.type === "checkbox" ? "change" : "input", sync); + }); +} + function featureTextareaValue(key, value) { if (!Array.isArray(value)) return String(value ?? ""); return value.map((item) => { @@ -21307,6 +21488,18 @@ function featureDependencyLines(key) { } const featureDetailGuides = { + enable_auto_user_profile_creation: { + summary: "首次真实私聊建立最小用户档案,并把默认称呼、语气、角色、亲密度和主动边界集中到一处。", + trigger: "收到非 Bot 回流的真实私聊事件,且平台在允许列表中、当前身份尚无档案时。", + enabled: "先建档,再按自动启用或人工设置决定是否接管;首条正文不会因此直接升级为长期记忆。", + disabled: "陌生用户不会自动建档,仍沿用目标用户或人工启用流程。", + }, + enable_custom_relationship_stage_policy: { + summary: "用固定八阶段呈现陪伴亲密度,并配置每个阶段的表达与软行为上限。", + trigger: "用户详情展示、私聊互动策略注入和 Memory 只读关系投影时。", + enabled: "使用下方自定义标签、说明、语气、称呼尺度和软行为;分数阈值保持固定。", + disabled: "使用内置八阶段策略;既有用户分数、P4、安全与权限均不改变。", + }, enable_proactive_only_mode: { summary: "让本插件只负责主动来找用户的链路,并可与 Proactive Chat 共享发送出口和主动状态,普通聊天继续放行给 AstrBot 默认主链或其他插件。", trigger: "普通私聊、群聊事件和非主动框架 LLM 请求到达时生效。", @@ -22339,7 +22532,12 @@ function featureDetailPage(key) { const guideRows = featureDetailGuideRows(key) .map(([name, value]) => `
${escapeHtml(name)}
${escapeHtml(value)}
`) .join(""); - const settingRow = ({ key: name, value, description }) => ` + const settingRow = ({ key: name, value, description }) => name === "relationship_stage_policy" ? ` +
+
${escapeHtml(configLabel(name))}${escapeHtml(name)}

${escapeHtml(description)}

+ ${relationshipPolicyEditor(value)} +
+ ` : `
@@ -22697,6 +22895,9 @@ function bindFeatureDetailActions() { if (state.selectedFeatureKey === "enable_photo_text_action") { bindPhotoReferenceManagerActions(); } + if (state.selectedFeatureKey === "enable_custom_relationship_stage_policy") { + bindRelationshipPolicyEditor(detailPage || document); + } bindProactiveOnlyTempUnlockActions(); } @@ -23729,7 +23930,7 @@ const experimentalFeatureMeta = { { trigger: "开启 QQ 空间心情动态", behavior: "高情绪强度时可能发布心情说说", result: "Bot 在社交平台表达当前心情,形成生活连续感" }, ], caution: "这是扮演状态,不是真实心理判断。阈值过低会让 Bot 太容易受伤,建议先温和开启并观察。", - runtimeHint: "私聊用户详情页的「情绪余波」卡片可查看四维状态、基本/复合情绪、调节策略和策略候选。", + runtimeHint: "用户详情页的「情绪余波」卡片可查看四维状态、基本/复合情绪、调节策略和策略候选。", }, enable_maslow_motivation_experiment: { label: "需求强化功能", @@ -23804,7 +24005,7 @@ function experimentalVisualSpec(key) { ["Plutchik 八情绪", "喜悦、信任、恐惧、惊讶、悲伤、厌恶、愤怒、期待", "决定主导情绪和复合情绪,例如期待/乐观、反感、亲近。"], ["Gross 调节", "避开高压、换低压问法、转移注意、重新理解、短答降压", "把内部情绪余波映射到更自然的外显回复策略。"], ], - verify: [["私聊对象", "private"], ["排障页", "troubleshooting"]], + verify: [["用户", "private"], ["排障页", "troubleshooting"]], }, enable_maslow_motivation_experiment: { mark: "需", @@ -26261,7 +26462,7 @@ if (key === "enable_emotion_simulation") { extraHtml = `
-
私聊用户${escapeHtml(String(userCount))}
+
用户${escapeHtml(String(userCount))}
已有样本${escapeHtml(String(emotionInfos.length))}
情绪波动${escapeHtml(String(emotionalCount))}
平稳样本${escapeHtml(String(calmCount))}
@@ -28240,7 +28441,7 @@ $("#addUserForm").addEventListener("submit", async (event) => { user_id: userId, enabled: true, nickname: form.get("nickname") || "", - }), "已添加私聊对象", event.submitter); + }), "已添加用户档案", event.submitter); if (saved) event.currentTarget.reset(); }); diff --git a/pages/陪伴面板/index.html b/pages/陪伴面板/index.html index c48b3f1..33c15b3 100644 --- a/pages/陪伴面板/index.html +++ b/pages/陪伴面板/index.html @@ -109,7 +109,7 @@ - + @@ -463,7 +463,7 @@ QQ空间 = 公开札记
-

私聊对象

+

用户档案

管理关系角色、主动额度、行为习惯、陪伴状态和已整理的对话片段。

@@ -471,7 +471,7 @@ QQ空间 = 公开札记 - +
@@ -737,7 +737,7 @@ QQ空间 = 公开札记
-

外部记忆插件协同

+

记忆插件协同

加载中...
diff --git a/platform_compat.py b/platform_compat.py index 07948b2..81ac22f 100644 --- a/platform_compat.py +++ b/platform_compat.py @@ -20,6 +20,10 @@ _PLATFORM_KIND_ALIASES = { "qq官方": "qq_official", "官方qq": "qq_official", "webchat": "webchat", + "telegram": "telegram", + "telegram_bot": "telegram", + "telegrambot": "telegram", + "tg": "telegram", "weixin_official_account": "wechat_official", "wechat_official": "wechat_official", "dingtalk": "dingtalk", @@ -95,6 +99,23 @@ _PLATFORM_PROFILES: dict[str, dict[str, Any]] = { "capabilities": {**_BASE_CAPABILITIES}, "limits": [], }, + "telegram": { + "label": "Telegram", + "identity_label": "Telegram 用户ID", + "delivery_policy": "adapter_managed", + "capabilities": { + **_BASE_CAPABILITIES, + "opaque_identity": True, + "onebot_actions": False, + "poke": False, + "input_status": False, + "message_recall": False, + "merged_forward": False, + "group_member_query": False, + "qzone": False, + }, + "limits": ["平台特有发送限制由 Telegram 适配器决定"], + }, "wechat_official": { "label": "微信公众号", "identity_label": "平台用户ID", diff --git a/relationship_policy.py b/relationship_policy.py new file mode 100644 index 0000000..ffb458f --- /dev/null +++ b/relationship_policy.py @@ -0,0 +1,258 @@ +from __future__ import annotations + +import json +from copy import deepcopy +from typing import Any + + +RELATIONSHIP_SCORE_MIN = -1200 +RELATIONSHIP_SCORE_MAX = 1200 + +_DEFAULT_STAGES: tuple[dict[str, Any], ...] = ( + { + "key": "deeply_distant", + "label": "极度疏离", + "min": -1200, + "max": -801, + "description": "明显保持距离,只做必要、克制且尊重边界的回应。", + "tone": "克制、礼貌、低压力,不主动拉近关系", + "address_level": "仅使用姓名、固定称呼或“你”", + "proactive_care_limit": 0, + "allow_playful_jokes": False, + "allow_followup": False, + "allow_memory_mention": False, + "allow_daily_care": False, + }, + { + "key": "strongly_distant", + "label": "强烈疏离", + "min": -800, + "max": -401, + "description": "关系处于明显降温期,优先稳住边界和基本礼貌。", + "tone": "平静、简短、不过度解释", + "address_level": "只使用中性称呼", + "proactive_care_limit": 0, + "allow_playful_jokes": False, + "allow_followup": False, + "allow_memory_mention": False, + "allow_daily_care": False, + }, + { + "key": "distant", + "label": "疏离", + "min": -400, + "max": -1, + "description": "保持自然但不过分熟络,避免擅自使用亲昵称呼。", + "tone": "自然、客气、留有空间", + "address_level": "中性称呼", + "proactive_care_limit": 0, + "allow_playful_jokes": False, + "allow_followup": False, + "allow_memory_mention": False, + "allow_daily_care": False, + }, + { + "key": "acquaintance", + "label": "初识", + "min": 0, + "max": 199, + "description": "刚开始相处,友好回应并逐步观察偏好。", + "tone": "友好、自然、不自来熟", + "address_level": "优先固定称呼、姓名或“你”", + "proactive_care_limit": 0, + "allow_playful_jokes": False, + "allow_followup": True, + "allow_memory_mention": False, + "allow_daily_care": False, + }, + { + "key": "familiar", + "label": "熟悉", + "min": 200, + "max": 599, + "description": "已有稳定互动,可以更轻松地接话和续话。", + "tone": "轻松、友好、带一点熟悉感", + "address_level": "可自然使用昵称", + "proactive_care_limit": 1, + "allow_playful_jokes": True, + "allow_followup": True, + "allow_memory_mention": True, + "allow_daily_care": True, + }, + { + "key": "close", + "label": "亲近", + "min": 600, + "max": 899, + "description": "关系稳定亲近,可更自然地关心近况和提及共同经历。", + "tone": "温暖、亲近、尊重当前节奏", + "address_level": "可使用已确认的亲昵称呼", + "proactive_care_limit": 2, + "allow_playful_jokes": True, + "allow_followup": True, + "allow_memory_mention": True, + "allow_daily_care": True, + }, + { + "key": "intimate", + "label": "亲密", + "min": 900, + "max": 1199, + "description": "关系亲密,表达可以柔软、有默契,但仍服从用户边界。", + "tone": "亲密、柔软、不过度黏人", + "address_level": "可使用双方已接受的亲昵称呼", + "proactive_care_limit": 3, + "allow_playful_jokes": True, + "allow_followup": True, + "allow_memory_mention": True, + "allow_daily_care": True, + }, + { + "key": "deeply_bonded", + "label": "深度联结", + "min": 1200, + "max": 1200, + "description": "长期关系达到当前上限,以稳定默契为主,不继续扩大权限。", + "tone": "默契、温柔、稳定", + "address_level": "使用双方明确认可的专属称呼", + "proactive_care_limit": 4, + "allow_playful_jokes": True, + "allow_followup": True, + "allow_memory_mention": True, + "allow_daily_care": True, + }, +) + +_TEXT_LIMITS = { + "label": 20, + "description": 160, + "tone": 120, + "address_level": 100, +} +_BOOL_FIELDS = ( + "allow_playful_jokes", + "allow_followup", + "allow_memory_mention", + "allow_daily_care", +) + + +def default_relationship_stage_policy() -> list[dict[str, Any]]: + return deepcopy(list(_DEFAULT_STAGES)) + + +def _single_line(value: Any, limit: int) -> str: + return " ".join(str(value or "").replace("\r", " ").replace("\n", " ").split())[:limit] + + +def _decode_policy(value: Any) -> Any: + if isinstance(value, str): + text = value.strip() + if not text: + return [] + try: + return json.loads(text) + except (TypeError, ValueError): + return [] + return value + + +def normalize_relationship_stage_policy(value: Any) -> list[dict[str, Any]]: + raw = _decode_policy(value) + if isinstance(raw, dict): + raw = raw.get("stages") + if not isinstance(raw, list): + raw = [] + raw_by_key = { + str(item.get("key") or "").strip(): item + for item in raw + if isinstance(item, dict) and item.get("key") + } + normalized: list[dict[str, Any]] = [] + for default in _DEFAULT_STAGES: + item = raw_by_key.get(default["key"], {}) + stage = deepcopy(default) + for field, limit in _TEXT_LIMITS.items(): + text = _single_line(item.get(field), limit) + if text: + stage[field] = text + try: + stage["proactive_care_limit"] = max(0, min(30, int(item.get("proactive_care_limit")))) + except (TypeError, ValueError): + pass + for field in _BOOL_FIELDS: + if type(item.get(field)) is bool: + stage[field] = item[field] + normalized.append(stage) + return normalized + + +def relationship_stage_for_score(value: Any, policy: Any = None) -> dict[str, Any]: + try: + score = int(value) + except (TypeError, ValueError): + score = 0 + score = max(RELATIONSHIP_SCORE_MIN, min(RELATIONSHIP_SCORE_MAX, score)) + stages = normalize_relationship_stage_policy(policy) + stage_index = 0 + for index, stage in enumerate(stages): + if stage["min"] <= score <= stage["max"]: + stage_index = index + break + stage = deepcopy(stages[stage_index]) + span = max(0, int(stage["max"]) - int(stage["min"])) + within = 1.0 if span == 0 else (score - int(stage["min"])) / span + return { + "value": score, + "band": stage["label"], + "phase": stage, + "stages": stages, + "stage_index": stage_index, + "stage_progress": round(max(0.0, min(1.0, within)), 4), + "min": RELATIONSHIP_SCORE_MIN, + "max": RELATIONSHIP_SCORE_MAX, + "trend": "unknown", + "authority": "private_companion.relationship_score", + "read_only": True, + "schema_version": "chat.relationship_projection.v1", + } + + +def relationship_projection_for_bridge(value: Any, policy: Any = None) -> dict[str, Any]: + projection = relationship_stage_for_score(value, policy) + phase = projection["phase"] + return { + "schema_version": projection["schema_version"], + "authority": projection["authority"], + "read_only": True, + "score": projection["value"], + "phase_key": phase["key"], + "phase_label": phase["label"], + "tone": phase["tone"], + "address_level": phase["address_level"], + "proactive_care_limit": phase["proactive_care_limit"], + "soft_behaviors": {field: bool(phase[field]) for field in _BOOL_FIELDS}, + } + + +def relationship_stage_prompt(value: Any, policy: Any = None) -> str: + phase = relationship_stage_for_score(value, policy)["phase"] + behaviors = [] + labels = { + "allow_playful_jokes": "轻量玩笑", + "allow_followup": "自然续话", + "allow_memory_mention": "回忆提及", + "allow_daily_care": "日常关心", + } + for key, label in labels.items(): + behaviors.append(f"{label}{'可用' if phase[key] else '关闭'}") + return ( + f"当前陪伴亲密阶段:{phase['label']}(固定分数范围 {phase['min']}..{phase['max']})。" + f"基础语气:{phase['tone']};称呼尺度:{phase['address_level']};" + f"主动关心上限:{phase['proactive_care_limit']};{'、'.join(behaviors)}。" + "这些只限制表达和软行为,不能授予主要用户、跨用户查询、平台动作、现实动作或任何 P4 安全权限。" + ) + + +def relationship_stage_policy_json(value: Any = None) -> str: + return json.dumps(normalize_relationship_stage_policy(value), ensure_ascii=False, separators=(",", ":")) diff --git a/tests/test_chat_companion_intimacy_controls.py b/tests/test_chat_companion_intimacy_controls.py index 8f23d01..bc8dca6 100644 --- a/tests/test_chat_companion_intimacy_controls.py +++ b/tests/test_chat_companion_intimacy_controls.py @@ -2,6 +2,7 @@ from __future__ import annotations import ast from copy import deepcopy +import importlib.util from pathlib import Path import re import unittest @@ -10,6 +11,14 @@ import unittest ROOT = Path(__file__).resolve().parents[1] +def _load_relationship_policy_module(): + spec = importlib.util.spec_from_file_location("chat_relationship_policy_test", ROOT / "relationship_policy.py") + module = importlib.util.module_from_spec(spec) + assert spec and spec.loader + spec.loader.exec_module(module) + return module + + def _class_method(path: Path, class_name: str, method_name: str) -> ast.FunctionDef | ast.AsyncFunctionDef: tree = ast.parse(path.read_text(encoding="utf-8")) owner = next( @@ -38,11 +47,7 @@ def _compile_static_method(path: Path, class_name: str, method_name: str) -> obj class ChatCompanionIntimacyControlTests(unittest.TestCase): def test_projection_is_bounded_and_has_the_public_contract(self) -> None: - projection = _compile_static_method( - ROOT / "page_api.py", - "PrivateCompanionPageApi", - "_relationship_intimacy_projection", - ) + projection = _load_relationship_policy_module().relationship_stage_for_score cases = { -1200: ("deeply_distant", "极度疏离"), -801: ("deeply_distant", "极度疏离"), @@ -58,15 +63,20 @@ class ChatCompanionIntimacyControlTests(unittest.TestCase): with self.subTest(value=value): result = projection(value) self.assertEqual( - {"value", "band", "phase", "min", "max", "trend"}, + {"value", "band", "phase", "stages", "stage_index", "stage_progress", "min", "max", "trend", "authority", "read_only", "schema_version"}, set(result), ) self.assertEqual(value, result["value"]) self.assertEqual(phase_label, result["band"]) - self.assertEqual({"key": phase_key, "label": phase_label}, result["phase"]) + self.assertEqual(phase_key, result["phase"]["key"]) + self.assertEqual(phase_label, result["phase"]["label"]) + self.assertEqual(8, len(result["stages"])) self.assertEqual(-1200, result["min"]) self.assertEqual(1200, result["max"]) self.assertEqual("unknown", result["trend"]) + self.assertEqual("private_companion.relationship_score", result["authority"]) + self.assertTrue(result["read_only"]) + self.assertEqual("chat.relationship_projection.v1", result["schema_version"]) self.assertEqual(-1200, projection(-99999)["value"]) self.assertEqual(1200, projection(99999)["value"]) @@ -146,10 +156,10 @@ class ChatCompanionIntimacyControlTests(unittest.TestCase): bindings = source[bind_start:bind_end] self.assertIn('type="number"', editor) self.assertIn('name="companion_intimacy"', editor) - self.assertIn("当前亲密阶段", editor) + self.assertIn("当前亲密度阶段", editor) self.assertIn("不影响 P4 好感、黑屋、审核或安全权限", editor) self.assertNotIn('type="range"', editor) - self.assertNotIn("relationship_score", source) + self.assertNotIn('name="relationship_score"', editor) self.assertIn('postJson("/user/update", { user_id: detail.user_id, companion_intimacy: value })', bindings) self.assertIn("Number.isInteger(value)", bindings) self.assertIn("value < -1200 || value > 1200", bindings) diff --git a/tests/test_req027_user_profiles_relationship_policy.py b/tests/test_req027_user_profiles_relationship_policy.py new file mode 100644 index 0000000..e5ba8e1 --- /dev/null +++ b/tests/test_req027_user_profiles_relationship_policy.py @@ -0,0 +1,289 @@ +from __future__ import annotations + +import ast +import copy +import importlib.util +from pathlib import Path +import re +import sys +from types import ModuleType, SimpleNamespace +from typing import Any +import unittest + + +ROOT = Path(__file__).resolve().parents[1] + + +def _single_line(value: Any, limit: int = 1000) -> str: + return re.sub(r"\s+", " ", str(value or "")).strip()[:limit] + + +def _load_relationship_policy(): + spec = importlib.util.spec_from_file_location("req027_relationship_policy", ROOT / "relationship_policy.py") + module = importlib.util.module_from_spec(spec) + assert spec and spec.loader + spec.loader.exec_module(module) + return module + + +def _load_platform_compat(): + package_name = "req027_platform_package" + package = ModuleType(package_name) + package.__path__ = [str(ROOT)] + helpers = ModuleType(f"{package_name}.helpers") + helpers._single_line = _single_line + sys.modules[package_name] = package + sys.modules[helpers.__name__] = helpers + spec = importlib.util.spec_from_file_location( + f"{package_name}.platform_compat", + ROOT / "platform_compat.py", + submodule_search_locations=[], + ) + module = importlib.util.module_from_spec(spec) + assert spec and spec.loader + sys.modules[spec.name] = module + spec.loader.exec_module(module) + return module + + +def _load_class_methods(filename: str, class_name: str, names: set[str], namespace: dict[str, Any]) -> dict[str, Any]: + path = ROOT / filename + tree = ast.parse(path.read_text(encoding="utf-8")) + owner = next(node for node in tree.body if isinstance(node, ast.ClassDef) and node.name == class_name) + scope = dict(namespace) + for node in owner.body: + if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) and node.name in names: + module = ast.Module(body=[copy.deepcopy(node)], type_ignores=[]) + ast.fix_missing_locations(module) + exec(compile(module, str(path), "exec"), scope) + return {name: scope[name] for name in names} + + +CORE_METHODS = _load_class_methods( + "core_store.py", + "CoreStoreMixin", + { + "_auto_profile_platform_set", + "_auto_profile_nickname", + "_ensure_auto_private_user_profile", + "_is_target_private_user", + }, + { + "Any": Any, + "re": re, + "_single_line": _single_line, + "_safe_int": lambda value, default=0, minimum=None, maximum=None: max( + minimum if minimum is not None else int(float(value)), + min(maximum if maximum is not None else int(float(value)), int(float(value))), + ) if str(value).strip() else default, + "_safe_float": lambda value, default=0.0: float(value or default), + "_now_ts": lambda: 123.0, + "RELATIONSHIP_SCORE_MIN": -1200, + "RELATIONSHIP_SCORE_MAX": 1200, + }, +) + + +class _AutoProfileHost: + enable_auto_user_profile_creation = True + auto_enable_companion_for_new_users = False + auto_profile_platforms = ["onebot", "qq_official", "telegram", "webchat", "generic"] + default_nickname_strategy = "platform_display_name" + default_nickname = "你" + default_style = "温柔" + default_relationship_score = 0 + default_proactive_enabled = False + default_proactive_daily_limit = 0 + + def __init__(self) -> None: + self.data = {"users": {}} + self.saved = 0 + self.platform_kind = "telegram" + self.bot_ids: set[str] = set() + self.targets: list[str] = [] + + def _canonical_private_user_id(self, value: str) -> str: + return str(value or "").strip() + + def _is_bot_self_user_id(self, value: str) -> bool: + return value in self.bot_ids + + def _platform_kind_for_event(self, _event: Any) -> str: + return self.platform_kind + + def _normalize_platform_kind(self, value: Any) -> str: + return _load_platform_compat().PlatformCompatibilityMixin._normalize_platform_kind(value) + + def _configured_target_ids(self) -> list[str]: + return list(self.targets) + + def _get_user(self, user_id: str) -> dict[str, Any]: + return self.data["users"].setdefault(user_id, {"enabled": False}) + + def _note_private_user_umo(self, _user_id: str, user: dict[str, Any], umo: str) -> None: + user["umo"] = umo + + def _schedule_data_save(self) -> None: + self.saved += 1 + + +for _name, _method in CORE_METHODS.items(): + setattr(_AutoProfileHost, _name, _method) + + +class Req027UserProfileRelationshipPolicyTests(unittest.TestCase): + def test_telegram_aliases_and_profile_are_first_class(self) -> None: + module = _load_platform_compat() + mixin = module.PlatformCompatibilityMixin + for alias in ("telegram", "telegram_bot", "telegrambot", "tg"): + with self.subTest(alias=alias): + self.assertEqual("telegram", mixin._normalize_platform_kind(alias)) + profile = mixin()._platform_profile(kind="telegram") + self.assertEqual("Telegram", profile["label"]) + self.assertEqual("Telegram 用户ID", profile["identity_label"]) + self.assertTrue(profile["capabilities"]["private_proactive"]) + self.assertFalse(profile["capabilities"]["onebot_actions"]) + + def test_relationship_policy_boundaries_and_security_whitelist(self) -> None: + policy = _load_relationship_policy() + boundaries = [ + (-1200, "deeply_distant"), (-801, "deeply_distant"), + (-800, "strongly_distant"), (-401, "strongly_distant"), + (-400, "distant"), (-1, "distant"), + (0, "acquaintance"), (199, "acquaintance"), + (200, "familiar"), (599, "familiar"), + (600, "close"), (899, "close"), + (900, "intimate"), (1199, "intimate"), + (1200, "deeply_bonded"), + ] + for score, key in boundaries: + with self.subTest(score=score): + self.assertEqual(key, policy.relationship_stage_for_score(score)["phase"]["key"]) + + hostile = [{ + "key": "acquaintance", + "min": -999999, + "max": 999999, + "label": "自定义初识", + "tone": "自然", + "owner": True, + "cross_user_query": True, + "p4_bypass": True, + "allow_followup": "false", + }, {"key": "forged_stage", "label": "伪造阶段"}] + normalized = policy.normalize_relationship_stage_policy(hostile) + self.assertEqual(8, len(normalized)) + acquaintance = next(item for item in normalized if item["key"] == "acquaintance") + self.assertEqual((0, 199), (acquaintance["min"], acquaintance["max"])) + self.assertEqual("自定义初识", acquaintance["label"]) + self.assertTrue(acquaintance["allow_followup"]) + for forbidden in ("owner", "cross_user_query", "p4_bypass"): + self.assertNotIn(forbidden, acquaintance) + self.assertNotIn("forged_stage", {item["key"] for item in normalized}) + + def test_auto_profile_is_minimal_idempotent_and_not_authoritative(self) -> None: + host = _AutoProfileHost() + event = SimpleNamespace(unified_msg_origin="telegram:FriendMessage:10001") + user, created = host._ensure_auto_private_user_profile( + event, user_id="10001", sender_display_name="小雪", now=456.0 + ) + self.assertTrue(created) + self.assertEqual("小雪", user["nickname"]) + self.assertEqual("friend", user["relationship_role"]) + self.assertFalse(user["enabled"]) + self.assertFalse(user["auto_enabled"]) + self.assertFalse(user["manual_enabled"]) + self.assertFalse(user["manual_disabled"]) + self.assertEqual(0, user["proactive_daily_limit"]) + self.assertEqual("private_auto", user["profile_origin"]) + self.assertNotIn("owner", user) + self.assertEqual(1, host.saved) + + same, duplicate_created = host._ensure_auto_private_user_profile( + event, user_id="10001", sender_display_name="另一个名字", now=999.0 + ) + self.assertIs(user, same) + self.assertFalse(duplicate_created) + self.assertEqual("小雪", same["nickname"]) + self.assertEqual(1, host.saved) + + def test_auto_profile_gates_and_manual_disable_precedence(self) -> None: + event = SimpleNamespace(unified_msg_origin="telegram:FriendMessage:10001") + host = _AutoProfileHost() + host.enable_auto_user_profile_creation = False + self.assertEqual((None, False), host._ensure_auto_private_user_profile(event, user_id="10001")) + + host = _AutoProfileHost() + host.bot_ids.add("10001") + self.assertEqual((None, False), host._ensure_auto_private_user_profile(event, user_id="10001")) + + host = _AutoProfileHost() + host.auto_profile_platforms = ["onebot"] + self.assertEqual((None, False), host._ensure_auto_private_user_profile(event, user_id="10001")) + + self.assertFalse(host._is_target_private_user("10001", {"auto_enabled": True, "manual_disabled": True})) + self.assertTrue(host._is_target_private_user("10001", {"auto_enabled": True, "manual_disabled": False})) + + def test_page_api_normalizes_new_profile_settings(self) -> None: + method = _load_class_methods( + "page_api.py", + "PrivateCompanionPageApi", + {"_normalize_setting_value"}, + {"Any": Any, "re": re, "relationship_stage_policy_json": lambda value: "normalized"}, + )["_normalize_setting_value"] + + class Host: + _normalize_setting_value = method + + @staticmethod + def _schema_bool_keys() -> set[str]: + return set() + + @staticmethod + def _int(value: Any, default: int = 0, minimum: int | None = None, maximum: int | None = None) -> int: + try: + result = int(value) + except (TypeError, ValueError): + result = default + if minimum is not None: + result = max(minimum, result) + if maximum is not None: + result = min(maximum, result) + return result + + host = Host() + self.assertEqual(["onebot", "telegram"], host._normalize_setting_value("auto_profile_platforms", ["napcat", "TG", "unknown", "telegram"])) + self.assertEqual("platform_display_name", host._normalize_setting_value("default_nickname_strategy", "owner")) + self.assertEqual("friend", host._normalize_setting_value("default_relationship_role", "owner")) + self.assertEqual(1200, host._normalize_setting_value("default_relationship_score", 99999)) + self.assertEqual(0, host._normalize_setting_value("default_proactive_daily_limit", -8)) + + def test_page_source_contains_grouped_users_cards_and_stage_fallback(self) -> None: + source = (ROOT / "pages" / "陪伴面板" / "app.js").read_text(encoding="utf-8") + css = (ROOT / "pages" / "陪伴面板" / "app.css").read_text(encoding="utf-8") + html = (ROOT / "pages" / "陪伴面板" / "index.html").read_text(encoding="utf-8") + self.assertIn('["qq", "QQ"', source) + self.assertIn('["telegram", "Telegram"', source) + self.assertIn('["web_other", "网页 / 其他"', source) + self.assertIn("user-platform-group", source) + self.assertIn(".user-platform-group button", css) + self.assertIn("DEFAULT_RELATIONSHIP_POLICY", source) + self.assertIn("relationship-stage-bar", source) + self.assertIn("relationship-phase-summary", source) + self.assertIn('data-feature-open="${escapeHtml(key)}"', source) + self.assertIn("新用户默认档案", source) + self.assertIn("亲密度阶段策略", source) + self.assertIn("用户档案", html) + self.assertIn("记忆插件协同", html) + self.assertNotIn("外部记忆插件协同", source) + self.assertNotIn("私聊对象", source) + self.assertNotIn("陪伴亲密度仪表", source) + + editor_start = source.index("function renderCompanionIntimacyEditor") + panel_start = source.index("function renderRelationshipPanel", editor_start) + self.assertNotIn("scoreGauge(", source[editor_start:panel_start]) + self.assertNotIn('type="range"', source[editor_start:panel_start]) + + +if __name__ == "__main__": + unittest.main() diff --git a/user_memory.py b/user_memory.py index 001b00d..dbb7dbe 100644 --- a/user_memory.py +++ b/user_memory.py @@ -104,6 +104,7 @@ from .dreaming import ( weighted_unique_fragment_sample, ) from .helpers import _date_key, _normalize_photo_subject_owner, _now_ts, _photo_subject_owner_prompt_label, _safe_float, _safe_int, _single_line, _strip_internal_message_blocks, _today_key +from .relationship_policy import relationship_stage_for_score, relationship_stage_prompt from .planning import ( build_daily_plan_prompt, build_detail_enhancement_prompt, @@ -6744,6 +6745,12 @@ bot_promises 只记录 Bot 明确承诺要提醒、记住、转述、发送或 return "" profile = self._relationship_profile(user) sections = ["【私聊互动策略】"] + policy = ( + getattr(self, "relationship_stage_policy", None) + if bool(getattr(self, "enable_custom_relationship_stage_policy", False)) + else None + ) + sections.append(relationship_stage_prompt(user.get("relationship_score", 0), policy)) preference = _single_line(profile.get("preference"), 40) intent_injection = self._format_intent_relationship_injection(user) if preference and preference != "普通": @@ -7670,8 +7677,14 @@ Bot 主动后用户回复次数:{reply_count} def _format_relationship_summary(self, user: dict[str, Any]) -> str: profile = self._relationship_profile(user) + policy = ( + getattr(self, "relationship_stage_policy", None) + if bool(getattr(self, "enable_custom_relationship_stage_policy", False)) + else None + ) + stage = relationship_stage_for_score(user.get("relationship_score", 0), policy)["phase"] return ( - f"{profile['level']}|回复率 {profile['reply_rate_label']}|" + f"亲密度 {stage['label']}|互动距离 {profile['level']}|回复率 {profile['reply_rate_label']}|" f"偏好 {profile['preference']}" )