feat(expression): unify relationship and interaction system
这个提交存在于:
父节点
8a530d603b
当前提交
a03481b6a8
共有 27 个文件被更改,包括 3887 次插入 和 1437 次删除
|
|
@ -225,6 +225,15 @@
|
|||
"default": 0,
|
||||
"condition": "enable_auto_user_profile_creation"
|
||||
},
|
||||
"default_interaction_band": {
|
||||
"description": "新档案默认互动状态",
|
||||
"type": "string",
|
||||
"options": ["avoidant", "hurt", "relaxed", "lively", "warm"],
|
||||
"labels": ["回避", "受伤", "放松", "活泼", "温暖"],
|
||||
"hint": "只影响之后自动建立的普通用户档案;亲近和爱意仅允许管理员专属账户使用。",
|
||||
"default": "relaxed",
|
||||
"condition": "enable_auto_user_profile_creation"
|
||||
},
|
||||
"default_proactive_enabled": {
|
||||
"description": "允许新用户主动关心",
|
||||
"type": "bool",
|
||||
|
|
@ -253,6 +262,87 @@
|
|||
"default": "",
|
||||
"invisible": true
|
||||
},
|
||||
"owner_exclusive_label": {
|
||||
"description": "管理员专属关系名称",
|
||||
"type": "string",
|
||||
"hint": "仅用于 owner 专属关系的显示和表达,不授予额外权限。",
|
||||
"default": "专属联结"
|
||||
},
|
||||
"owner_exclusive_tone": {
|
||||
"description": "管理员专属基础表达",
|
||||
"type": "string",
|
||||
"hint": "专属关系的长期表达基线;当前互动状态和安全边界仍可使表达收敛。",
|
||||
"default": "温暖、亲近、稳定"
|
||||
},
|
||||
"owner_exclusive_address_style": {
|
||||
"description": "管理员专属称呼尺度",
|
||||
"type": "string",
|
||||
"hint": "优先沿用用户档案中双方已确认的专属称呼。",
|
||||
"default": "优先使用已确认的专属称呼"
|
||||
},
|
||||
"owner_exclusive_proactive_limit": {
|
||||
"description": "管理员专属主动阶段上限",
|
||||
"type": "int",
|
||||
"slider": {"min": 0, "max": 30, "step": 1},
|
||||
"hint": "只是阶段硬上限;实际次数仍取全局、用户、阶段和动态额度的最小值。",
|
||||
"default": 6
|
||||
},
|
||||
"relationship_event_window_minutes": {
|
||||
"description": "亲密度事件去重窗口(分钟)",
|
||||
"type": "int",
|
||||
"slider": {"min": 1, "max": 1440, "step": 1},
|
||||
"hint": "同一原因在窗口内只结算一次,避免短时间刷消息重复加分。",
|
||||
"default": 30
|
||||
},
|
||||
"relationship_positive_event_cap": {
|
||||
"description": "单次正向亲密度上限",
|
||||
"type": "int",
|
||||
"slider": {"min": 1, "max": 30, "step": 1},
|
||||
"hint": "单个事件最多增加多少分。",
|
||||
"default": 4
|
||||
},
|
||||
"relationship_negative_event_cap": {
|
||||
"description": "单次负向亲密度上限",
|
||||
"type": "int",
|
||||
"slider": {"min": 1, "max": 60, "step": 1},
|
||||
"hint": "单个明确负向事件最多扣多少分。普通未回复不会直接扣长期分。",
|
||||
"default": 12
|
||||
},
|
||||
"relationship_positive_daily_cap": {
|
||||
"description": "每日正向亲密度上限",
|
||||
"type": "int",
|
||||
"slider": {"min": 0, "max": 120, "step": 1},
|
||||
"hint": "限制单日累计正向增长;0 表示当天不自动增加。",
|
||||
"default": 12
|
||||
},
|
||||
"relationship_decay_grace_days": {
|
||||
"description": "自然回落宽限天数",
|
||||
"type": "int",
|
||||
"slider": {"min": 0, "max": 30, "step": 1},
|
||||
"hint": "连续多少天没有有效互动时保持不变;默认 3 天。",
|
||||
"default": 3
|
||||
},
|
||||
"relationship_decay_early_per_day": {
|
||||
"description": "回落前段每日扣分",
|
||||
"type": "int",
|
||||
"slider": {"min": 0, "max": 30, "step": 1},
|
||||
"hint": "宽限后至第 7 个未互动日每天回落多少分。",
|
||||
"default": 2
|
||||
},
|
||||
"relationship_decay_middle_per_day": {
|
||||
"description": "回落中段每日扣分",
|
||||
"type": "int",
|
||||
"slider": {"min": 0, "max": 30, "step": 1},
|
||||
"hint": "第 8 至第 14 个未互动日每天回落多少分。",
|
||||
"default": 5
|
||||
},
|
||||
"relationship_decay_late_per_day": {
|
||||
"description": "回落后段每日扣分",
|
||||
"type": "int",
|
||||
"slider": {"min": 0, "max": 30, "step": 1},
|
||||
"hint": "第 15 个未互动日起每天回落多少分;只向 0 回落。",
|
||||
"default": 8
|
||||
},
|
||||
"default_nickname": {
|
||||
"description": "默认称呼",
|
||||
"type": "string",
|
||||
|
|
@ -1490,9 +1580,9 @@
|
|||
"invisible": true
|
||||
},
|
||||
"enable_relationship_analysis": {
|
||||
"description": "Legacy flat config: 启用模型关系站位分析",
|
||||
"description": "Legacy flat config: 已停用的模型关系站位分析",
|
||||
"type": "bool",
|
||||
"default": true,
|
||||
"default": false,
|
||||
"invisible": true
|
||||
},
|
||||
"enable_emotion_simulation": {
|
||||
|
|
@ -4285,7 +4375,7 @@
|
|||
"EMOTION_JUDGEMENT_PROVIDER_ID": {
|
||||
"description": "情绪变化判断模型(留空自动回退)",
|
||||
"type": "string",
|
||||
"hint": "用于可选复核用户消息是否会触发 Bot 自身短期情绪余波。建议选择便宜、低延迟、分类保守的小模型;留空会先回退到排障检查模型,再回退到关系站位/陪伴通用/主模型。",
|
||||
"hint": "用于可选复核用户消息是否应改变统一互动状态。建议选择便宜、低延迟、分类保守的小模型;留空会先回退到排障检查模型,再回退到陪伴通用/主模型。",
|
||||
"default": "",
|
||||
"condition": {
|
||||
"provider_config_mode": "precision"
|
||||
|
|
@ -5923,9 +6013,9 @@
|
|||
}
|
||||
},
|
||||
"emotion_relationship_config": {
|
||||
"description": "意图与关系状态",
|
||||
"description": "意图与互动状态",
|
||||
"type": "object",
|
||||
"hint": "维护用户意图、关系温度、回复策略和边界收敛;Bot 自身情绪模拟已移至“实验性功能”。",
|
||||
"hint": "维护本轮意图识别、七档互动状态和明确联系边界;长期关系基线、短期修正与安全约束最终统一结算为一份表达决策。",
|
||||
"items": {
|
||||
"enable_intent_emotion_analysis": {
|
||||
"description": "启用本地意图/情绪快判",
|
||||
|
|
@ -5937,22 +6027,20 @@
|
|||
}
|
||||
},
|
||||
"enable_relationship_state_machine": {
|
||||
"description": "启用关系距离感",
|
||||
"description": "让关系事件调整互动状态",
|
||||
"type": "bool",
|
||||
"hint": "根据用户的边界、亲近、冷淡、玩笑、长期互动和是否回应主动消息,调整 Bot 的距离感、主动频率和相处分寸。Bot 自身被刺到后的短期余波由“实验性功能 → 情绪模拟”单独控制。",
|
||||
"hint": "根据明确边界、重新靠近、玩笑、亲近和互动压力更新统一七档互动状态;明确退开另写联系边界,不能被普通状态调整绕过。",
|
||||
"default": true,
|
||||
"condition": {
|
||||
"enable_mai_style_integration": true
|
||||
}
|
||||
},
|
||||
"enable_relationship_analysis": {
|
||||
"description": "启用模型关系站位分析",
|
||||
"description": "旧版模型关系站位分析(已由陪伴表达系统取代)",
|
||||
"type": "bool",
|
||||
"hint": "阶段性使用完整人格和互动数据,让模型复核陌生/熟悉/亲近及打扰偏好。关闭后不再产生“关系分析”模型 Token;关系距离感、本地边界判断和基于互动次数/回复率的兜底仍可继续工作。",
|
||||
"default": true,
|
||||
"condition": {
|
||||
"enable_mai_style_integration": true
|
||||
}
|
||||
"hint": "仅保留旧配置读取兼容;运行时不再调用模型生成第二套关系层级。",
|
||||
"default": false,
|
||||
"invisible": true
|
||||
},
|
||||
"enable_response_self_review": {
|
||||
"description": "旧版回复/主动复核总开关",
|
||||
|
|
@ -10434,7 +10522,7 @@
|
|||
"experimental_motivation_config": {
|
||||
"description": "实验性功能",
|
||||
"type": "object",
|
||||
"hint": "心理机制、动机调度、角色贴合校准和情绪余波等探索性功能。除已存在的情绪模拟会保留原默认值外,其它实验项默认关闭;建议逐项开启观察,不把理论标签写进实际回复正文。",
|
||||
"hint": "心理机制、动机调度和角色贴合校准等探索性功能默认关闭;统一互动状态事件已并入亲密度阶段策略详情,不再作为独立实验系统展示。",
|
||||
"items": {
|
||||
"enable_maslow_motivation_experiment": {
|
||||
"description": "启用需求强化功能",
|
||||
|
|
@ -10487,18 +10575,18 @@
|
|||
}
|
||||
},
|
||||
"enable_emotion_simulation": {
|
||||
"description": "启用情绪模拟",
|
||||
"description": "让情绪事件自动调整统一互动状态",
|
||||
"type": "bool",
|
||||
"hint": "实验性情绪余波。维护 Bot 自身短期情绪,例如被刺到后的收敛、缓和后的恢复,以及不满时的短暂回避;会结合四维状态、基本/复合情绪和调节策略影响回复。该项迁入实验性功能但保留原默认值,避免更新后行为突变。",
|
||||
"hint": "开启后,受伤、道歉、安抚、夸奖、玩笑和亲近事件只结算到陪伴表达系统的统一七档互动状态;不再新增 Izard、Plutchik、Gross、mood_score 或第二套关系状态。旧字段仅保留只读兼容。",
|
||||
"default": true,
|
||||
"condition": {
|
||||
"enable_mai_style_integration": true
|
||||
}
|
||||
},
|
||||
"enable_llm_emotion_judgement": {
|
||||
"description": "启用模型复核情绪变化",
|
||||
"description": "启用模型复核互动状态事件",
|
||||
"type": "bool",
|
||||
"hint": "开启后,本地快判会先记录;可疑边界、玩笑、道歉、安抚或负向表达会交给模型后台复核,再更新短期情绪余波。本轮被动回复不等待模型,仍使用缓存情绪状态,默认关闭以保持低延迟。",
|
||||
"hint": "开启后,本地快判会先记录;可疑边界、玩笑、道歉、安抚或负向表达会交给模型后台复核,再更新统一互动状态。本轮被动回复不等待模型,默认关闭以保持低延迟。",
|
||||
"default": false,
|
||||
"condition": {
|
||||
"enable_emotion_simulation": true
|
||||
|
|
@ -10514,9 +10602,9 @@
|
|||
}
|
||||
},
|
||||
"emotional_gate_hurt_threshold": {
|
||||
"description": "伤心触发阈值",
|
||||
"description": "受伤状态触发阈值",
|
||||
"type": "int",
|
||||
"hint": "用户消息被判定为足够刺痛且达到该值时,Bot 才会短期变得更安静、更收着。越高越不容易触发;轻度玩笑和普通边界不会直接触发。应低于“生气触发阈值”。",
|
||||
"hint": "用户消息被判定为足够刺痛且达到该值时,当前互动才进入“受伤”。越高越不容易触发;轻度玩笑和普通边界不会直接触发。应低于“回避状态触发阈值”。",
|
||||
"slider": {
|
||||
"min": 10,
|
||||
"max": 100,
|
||||
|
|
@ -10528,9 +10616,9 @@
|
|||
}
|
||||
},
|
||||
"emotional_gate_refuse_threshold": {
|
||||
"description": "生气触发阈值",
|
||||
"description": "回避状态触发阈值",
|
||||
"type": "int",
|
||||
"hint": "累计刺痛感达到该值后,Bot 才会表现出更明显的不满和短暂回避。建议保持较高,只让连续明确伤害触发。",
|
||||
"hint": "单次明确伤害强度达到该值后,当前互动进入更收敛的“回避”;它不是联系边界,也不会自动写入不再联系。建议高于受伤阈值。",
|
||||
"slider": {
|
||||
"min": 20,
|
||||
"max": 100,
|
||||
|
|
@ -10542,9 +10630,9 @@
|
|||
}
|
||||
},
|
||||
"emotional_gate_recovery_per_hour": {
|
||||
"description": "每小时缓和量",
|
||||
"description": "每小时恢复量",
|
||||
"type": "int",
|
||||
"hint": "情绪余波会随时间自然回到稳定;道歉、安抚、夸奖也会额外缓和。",
|
||||
"hint": "用于计算受伤/回避互动状态的预计持续时间;数值越高,自动回到长期关系基线越快。道歉、安抚和明确重新靠近仍可提前恢复。",
|
||||
"slider": {
|
||||
"min": 1,
|
||||
"max": 60,
|
||||
|
|
@ -10556,9 +10644,9 @@
|
|||
}
|
||||
},
|
||||
"emotional_gate_max_hurt_minutes": {
|
||||
"description": "最长收敛分钟",
|
||||
"description": "受伤/回避最长持续分钟",
|
||||
"type": "int",
|
||||
"hint": "单次刺痛事件造成的最长主动暂停/收敛时长。默认较短,避免情绪余波长时间压低回复;道歉或安抚可以提前恢复。",
|
||||
"hint": "限制单次明确伤害造成的短期互动状态持续时间;到期后回到长期关系基线,道歉或安抚可以提前恢复。",
|
||||
"slider": {
|
||||
"min": 10,
|
||||
"max": 720,
|
||||
|
|
|
|||
535
companion_interaction_expression.py
普通文件
535
companion_interaction_expression.py
普通文件
|
|
@ -0,0 +1,535 @@
|
|||
"""Pure contract for the Companion interaction-expression pipeline.
|
||||
|
||||
The contract deliberately owns no persistence, clock, network, or platform
|
||||
access. Runtime adapters may pass their already-sanitised snapshots here and
|
||||
consume the single :class:`ExpressionDecision` result in passive replies,
|
||||
proactive candidates, TTS, and presentation projections.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import asdict, dataclass
|
||||
from enum import Enum
|
||||
from typing import Any, Mapping
|
||||
|
||||
|
||||
EXPRESSION_CONTRACT_VERSION = "companion_interaction_expression.v1"
|
||||
|
||||
|
||||
class ExpressionBand(str, Enum):
|
||||
"""The seven short-term expression bands, ordered from reserved to warm."""
|
||||
|
||||
AVOIDANT = "avoidant"
|
||||
HURT = "hurt"
|
||||
RELAXED = "relaxed"
|
||||
LIVELY = "lively"
|
||||
WARM = "warm"
|
||||
CLOSE = "close"
|
||||
AFFECTIONATE = "affectionate"
|
||||
|
||||
|
||||
_OWNER_ONLY_BANDS = frozenset({ExpressionBand.CLOSE, ExpressionBand.AFFECTIONATE})
|
||||
_ALL_BANDS = frozenset(ExpressionBand)
|
||||
_BAND_INDEX = {band: index for index, band in enumerate(ExpressionBand)}
|
||||
_P4_CAP_BANDS = {
|
||||
"guarded": ExpressionBand.HURT,
|
||||
"neutral": ExpressionBand.RELAXED,
|
||||
"warm": ExpressionBand.WARM,
|
||||
"close": ExpressionBand.AFFECTIONATE,
|
||||
}
|
||||
_DOWN_MOOD_WORDS = frozenset({
|
||||
"sad", "bad", "negative", "angry", "anxious", "tense", "tired", "sleepy",
|
||||
"难过", "低落", "生气", "焦虑", "紧张", "疲惫", "疲劳", "困", "烦", "受伤", "安静", "收声", "困倦",
|
||||
})
|
||||
_UP_MOOD_WORDS = frozenset({
|
||||
"happy", "good", "positive", "joy", "calm",
|
||||
"开心", "高兴", "愉快", "轻松", "积极", "满足", "安心", "兴奋", "顺利", "温柔", "轻快", "明亮", "活跃", "松弛",
|
||||
})
|
||||
EXPRESSION_BAND_LABELS: dict[str, str] = {
|
||||
ExpressionBand.AVOIDANT.value: "回避",
|
||||
ExpressionBand.HURT.value: "受伤",
|
||||
ExpressionBand.RELAXED.value: "放松",
|
||||
ExpressionBand.LIVELY.value: "活泼",
|
||||
ExpressionBand.WARM.value: "温暖",
|
||||
ExpressionBand.CLOSE.value: "亲近",
|
||||
ExpressionBand.AFFECTIONATE.value: "爱意",
|
||||
}
|
||||
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)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ExpressionDecision:
|
||||
"""A complete, immutable decision consumed by all expression channels."""
|
||||
|
||||
contract: str
|
||||
expression_band: str
|
||||
tone: str
|
||||
warmth: int
|
||||
distance: int
|
||||
address_style: str
|
||||
response_length: str
|
||||
followup: bool
|
||||
initiative: str
|
||||
proactive_budget: int
|
||||
tts_style: str
|
||||
allowed_behaviors: tuple[str, ...]
|
||||
safety_mode: str
|
||||
blocker: str | None
|
||||
reason_codes: tuple[str, ...]
|
||||
|
||||
def to_dict(self) -> dict[str, Any]:
|
||||
"""Return a detached JSON-friendly projection without mutating the DTO."""
|
||||
|
||||
return asdict(self)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ExpressionInput:
|
||||
"""Optional typed input form; mappings are also accepted by the builder."""
|
||||
|
||||
relationship_score: int = 0
|
||||
relationship_role: str = "friend"
|
||||
relationship_mode: str = ""
|
||||
relationship_baseline: Mapping[str, Any] | None = None
|
||||
current_interaction: str = ""
|
||||
bot_state: Mapping[str, Any] | None = None
|
||||
schedule: Mapping[str, Any] | None = None
|
||||
message_intent: Mapping[str, Any] | None = None
|
||||
proactive_candidate: Mapping[str, Any] | None = None
|
||||
safety_constraints: Mapping[str, Any] | None = None
|
||||
administrator_override: str | Mapping[str, Any] | None = None
|
||||
|
||||
def to_mapping(self) -> dict[str, Any]:
|
||||
return {
|
||||
"relationship_score": self.relationship_score,
|
||||
"relationship_role": self.relationship_role,
|
||||
"relationship_mode": self.relationship_mode,
|
||||
"relationship_baseline": self.relationship_baseline,
|
||||
"current_interaction": self.current_interaction,
|
||||
"bot_state": self.bot_state,
|
||||
"schedule": self.schedule,
|
||||
"message_intent": self.message_intent,
|
||||
"proactive_candidate": self.proactive_candidate,
|
||||
"safety_constraints": self.safety_constraints,
|
||||
"administrator_override": self.administrator_override,
|
||||
}
|
||||
|
||||
|
||||
_BAND_DETAILS: dict[ExpressionBand, tuple[str, int, int, str, str, str, tuple[str, ...]]] = {
|
||||
ExpressionBand.AVOIDANT: ("reserved", 15, 90, "formal", "brief", "muted", ("acknowledge", "brief_reply", "give_space")),
|
||||
ExpressionBand.HURT: ("careful", 28, 78, "reserved", "brief", "soft", ("acknowledge", "brief_reply", "give_space")),
|
||||
ExpressionBand.RELAXED: ("steady", 48, 55, "neutral", "balanced", "natural", ("reply", "clarify")),
|
||||
ExpressionBand.LIVELY: ("bright", 63, 40, "casual", "balanced", "bright", ("reply", "light_humor", "followup")),
|
||||
ExpressionBand.WARM: ("gentle", 76, 28, "warm", "balanced", "warm", ("reply", "support", "followup")),
|
||||
ExpressionBand.CLOSE: ("intimate", 87, 18, "intimate", "expanded", "intimate", ("reply", "support", "followup", "shared_ritual")),
|
||||
ExpressionBand.AFFECTIONATE: ("affectionate", 95, 10, "exclusive", "expanded", "affectionate", ("reply", "support", "followup", "shared_ritual", "affectionate_expression")),
|
||||
}
|
||||
|
||||
_INTERACTION_ALIASES: dict[str, ExpressionBand] = {
|
||||
"avoidant": ExpressionBand.AVOIDANT,
|
||||
"backoff": ExpressionBand.AVOIDANT,
|
||||
"refusing": ExpressionBand.AVOIDANT,
|
||||
"avoid": ExpressionBand.AVOIDANT,
|
||||
"hurt": ExpressionBand.HURT,
|
||||
"injured": ExpressionBand.HURT,
|
||||
"relaxed": ExpressionBand.RELAXED,
|
||||
"normal": ExpressionBand.RELAXED,
|
||||
"steady": ExpressionBand.RELAXED,
|
||||
"careful": ExpressionBand.RELAXED,
|
||||
"lively": ExpressionBand.LIVELY,
|
||||
"active": ExpressionBand.LIVELY,
|
||||
"warm": ExpressionBand.WARM,
|
||||
"warming": ExpressionBand.WARM,
|
||||
"close": ExpressionBand.CLOSE,
|
||||
"attached": ExpressionBand.CLOSE,
|
||||
"affectionate": ExpressionBand.AFFECTIONATE,
|
||||
}
|
||||
|
||||
|
||||
def _mapping(value: Any) -> Mapping[str, Any]:
|
||||
return value if isinstance(value, Mapping) else {}
|
||||
|
||||
|
||||
def _text(value: Any) -> str:
|
||||
return value.strip().lower() if isinstance(value, str) else ""
|
||||
|
||||
|
||||
def _flag(value: Any) -> bool:
|
||||
return value is True or (isinstance(value, int) and not isinstance(value, bool) and value == 1)
|
||||
|
||||
|
||||
def _bounded_int(value: Any, default: int, minimum: int, maximum: int) -> int:
|
||||
if isinstance(value, bool):
|
||||
return default
|
||||
if isinstance(value, int):
|
||||
return max(minimum, min(maximum, value))
|
||||
if isinstance(value, float) and value.is_integer():
|
||||
return max(minimum, min(maximum, int(value)))
|
||||
return default
|
||||
|
||||
|
||||
def _band(value: Any) -> ExpressionBand | None:
|
||||
return _INTERACTION_ALIASES.get(_text(value))
|
||||
|
||||
|
||||
def _band_from_interaction(value: Any) -> ExpressionBand | None:
|
||||
if isinstance(value, Mapping):
|
||||
for key in ("band", "expression_band", "state", "mode"):
|
||||
resolved = _band(value.get(key))
|
||||
if resolved is not None:
|
||||
return resolved
|
||||
return None
|
||||
return _band(value)
|
||||
|
||||
|
||||
def _baseline_band(score: int, *, owner_exclusive: bool = False) -> ExpressionBand:
|
||||
if owner_exclusive:
|
||||
return ExpressionBand.CLOSE
|
||||
if score < -400:
|
||||
return ExpressionBand.AVOIDANT
|
||||
if score < 0:
|
||||
return ExpressionBand.HURT
|
||||
if score >= 600:
|
||||
return ExpressionBand.WARM
|
||||
if score >= 200:
|
||||
return ExpressionBand.LIVELY
|
||||
return ExpressionBand.RELAXED
|
||||
|
||||
|
||||
def _bounded_text(value: Any, limit: int) -> str:
|
||||
if not isinstance(value, str):
|
||||
return ""
|
||||
return " ".join(value.replace("\r", " ").replace("\n", " ").split())[:limit]
|
||||
|
||||
|
||||
def _override_band(value: Any) -> ExpressionBand | None:
|
||||
if isinstance(value, Mapping):
|
||||
if value.get("enabled") is False:
|
||||
return None
|
||||
return _band_from_interaction(value)
|
||||
return _band(value)
|
||||
|
||||
|
||||
def _has_p4_block(safety: Mapping[str, Any]) -> bool:
|
||||
if _flag(safety.get("p4_blocked")):
|
||||
return True
|
||||
if _text(safety.get("safety_mode")) in {"blocked", "deny", "p4_blocked", "confinement"}:
|
||||
return True
|
||||
for key in ("p4", "p4_state"):
|
||||
state = _mapping(safety.get(key))
|
||||
if _flag(state.get("blocked")):
|
||||
return True
|
||||
if _text(state.get("confinement_state")) in {"blocked", "active", "confinement"}:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _has_contact_boundary(safety: Mapping[str, Any]) -> bool:
|
||||
if _flag(safety.get("contact_boundary")) or _flag(safety.get("no_contact")):
|
||||
return True
|
||||
boundary = safety.get("contact_boundary")
|
||||
if _text(boundary) in {"avoid", "no_contact", "stop", "blocked", "quiet"}:
|
||||
return True
|
||||
details = _mapping(boundary)
|
||||
if _flag(details.get("active")) or _flag(details.get("blocked")):
|
||||
return True
|
||||
return _text(details.get("mode")) in {"avoid", "no_contact", "stop", "blocked", "quiet"}
|
||||
|
||||
|
||||
def _intent_suppresses_followup(intent: Mapping[str, Any]) -> bool:
|
||||
if intent.get("followup_allowed") is False:
|
||||
return True
|
||||
return _text(intent.get("kind")) in {"stop", "end", "no_followup", "quiet"}
|
||||
|
||||
|
||||
def _candidate_budget(candidate: Mapping[str, Any]) -> int:
|
||||
if not _flag(candidate.get("eligible")):
|
||||
return 0
|
||||
for key in ("dynamic_allowance", "daily_allowance", "budget", "max_budget"):
|
||||
if key in candidate:
|
||||
return _bounded_int(candidate.get(key), 0, 0, 99)
|
||||
return 0
|
||||
|
||||
|
||||
def _schedule_is_quiet(schedule: Mapping[str, Any]) -> bool:
|
||||
if _flag(schedule.get("quiet_hours")) or _flag(schedule.get("do_not_disturb")):
|
||||
return True
|
||||
mode = _text(schedule.get("mode"))
|
||||
if mode in {"quiet", "busy", "rest"}:
|
||||
return True
|
||||
text = _mapping_text(schedule, "label", "title", "activity", "schedule")
|
||||
return any(word in text for word in ("sleep", "busy", "work", "meeting", "class", "commute", "睡", "休息", "忙", "工作", "会议", "上课", "通勤"))
|
||||
|
||||
|
||||
def _mapping_text(value: Mapping[str, Any], *keys: str) -> str:
|
||||
for key in keys:
|
||||
candidate = value.get(key)
|
||||
if isinstance(candidate, str):
|
||||
return candidate.strip().lower()[:240]
|
||||
return ""
|
||||
|
||||
|
||||
def _contains_any(text: str, words: frozenset[str]) -> bool:
|
||||
return bool(text) and any(word in text for word in words)
|
||||
|
||||
|
||||
def _input_mapping(value: Any) -> Mapping[str, Any]:
|
||||
if isinstance(value, ExpressionInput):
|
||||
return value.to_mapping()
|
||||
return _mapping(value)
|
||||
|
||||
|
||||
def build_expression_decision(input_data: ExpressionInput | Mapping[str, Any] | None = None, **overrides: Any) -> ExpressionDecision:
|
||||
"""Build one deterministic expression decision from bounded structured inputs.
|
||||
|
||||
Unknown values are ignored rather than echoed. An administrator override
|
||||
may choose a permitted band, but never bypasses P4 or contact boundaries.
|
||||
"""
|
||||
|
||||
source = dict(_input_mapping(input_data))
|
||||
source.update(overrides)
|
||||
reasons: list[str] = []
|
||||
safety = _mapping(source.get("safety_constraints"))
|
||||
role = _text(source.get("relationship_role"))
|
||||
mode = _text(source.get("relationship_mode"))
|
||||
owner_account = role == "owner"
|
||||
owner_exclusive = owner_account and mode == "owner_exclusive"
|
||||
|
||||
if _has_p4_block(safety):
|
||||
return _blocked_decision("p4_blocked", "p4_safety", reasons)
|
||||
contact_boundary = _has_contact_boundary(safety)
|
||||
passive_reengagement = _flag(safety.get("passive_reengagement"))
|
||||
if contact_boundary and not passive_reengagement:
|
||||
return _blocked_decision("contact_boundary", "contact_boundary", reasons)
|
||||
|
||||
score = _bounded_int(source.get("relationship_score"), 0, -1200, 1200)
|
||||
relationship_baseline = _mapping(source.get("relationship_baseline"))
|
||||
band = _baseline_band(score, owner_exclusive=owner_exclusive)
|
||||
interaction_band = _band_from_interaction(source.get("current_interaction"))
|
||||
if interaction_band is not None:
|
||||
if interaction_band == ExpressionBand.RELAXED:
|
||||
if band != ExpressionBand.RELAXED:
|
||||
reasons.append("relationship_baseline_retained")
|
||||
else:
|
||||
band = interaction_band
|
||||
reasons.append("interaction_band_applied")
|
||||
|
||||
override_band = _override_band(source.get("administrator_override"))
|
||||
if override_band is not None:
|
||||
band = override_band
|
||||
reasons.append("administrator_override_applied")
|
||||
|
||||
if band in _OWNER_ONLY_BANDS and not owner_account:
|
||||
band = ExpressionBand.WARM
|
||||
reasons.append("owner_role_required")
|
||||
if contact_boundary:
|
||||
band = ExpressionBand.AVOIDANT
|
||||
reasons.append("contact_boundary_passive_reengagement")
|
||||
p4_cap = _P4_CAP_BANDS.get(_text(safety.get("p4_warmth_cap")))
|
||||
if p4_cap is not None and _BAND_INDEX[band] > _BAND_INDEX[p4_cap]:
|
||||
band = p4_cap
|
||||
reasons.append("p4_warmth_cap_applied")
|
||||
|
||||
tone, warmth, distance, address_style, response_length, tts_style, behaviors = _BAND_DETAILS[band]
|
||||
baseline_tone = _bounded_text(relationship_baseline.get("tone"), 120)
|
||||
baseline_address = _bounded_text(
|
||||
relationship_baseline.get("address_style") or relationship_baseline.get("address_level"),
|
||||
100,
|
||||
)
|
||||
if band not in {ExpressionBand.AVOIDANT, ExpressionBand.HURT}:
|
||||
if baseline_tone:
|
||||
tone = baseline_tone
|
||||
reasons.append("relationship_tone_applied")
|
||||
if baseline_address:
|
||||
address_style = baseline_address
|
||||
reasons.append("relationship_address_applied")
|
||||
soft_behaviors = _mapping(relationship_baseline.get("soft_behaviors"))
|
||||
if soft_behaviors:
|
||||
if soft_behaviors.get("allow_followup") is False:
|
||||
behaviors = tuple(item for item in behaviors if item != "followup")
|
||||
reasons.append("relationship_followup_cap")
|
||||
if soft_behaviors.get("allow_playful_jokes") is False:
|
||||
behaviors = tuple(item for item in behaviors if item != "light_humor")
|
||||
if soft_behaviors.get("allow_memory_mention") is False:
|
||||
behaviors = tuple(item for item in behaviors if item != "shared_ritual")
|
||||
if soft_behaviors.get("allow_daily_care") is False:
|
||||
behaviors = tuple(item for item in behaviors if item != "support")
|
||||
intent = _mapping(source.get("message_intent"))
|
||||
followup = "followup" in behaviors and not _intent_suppresses_followup(intent)
|
||||
if not followup and "followup" in behaviors:
|
||||
reasons.append("intent_followup_suppressed")
|
||||
|
||||
bot_state = _mapping(source.get("bot_state"))
|
||||
energy = _bounded_int(bot_state.get("energy"), 70, 0, 100)
|
||||
mood = _mapping_text(bot_state, "mood", "mood_bias", "label", "state")
|
||||
low_energy = energy < 30
|
||||
down_mood = _contains_any(mood, _DOWN_MOOD_WORDS)
|
||||
up_mood = _contains_any(mood, _UP_MOOD_WORDS)
|
||||
if low_energy:
|
||||
response_length = "brief" if response_length != "brief" else response_length
|
||||
followup = False
|
||||
warmth = max(0, warmth - 10)
|
||||
distance = min(100, distance + 8)
|
||||
tts_style = "soft"
|
||||
reasons.append("low_energy_expression_cap")
|
||||
if down_mood:
|
||||
followup = False
|
||||
warmth = max(0, warmth - 8)
|
||||
distance = min(100, distance + 6)
|
||||
if tone not in {"reserved", "careful"}:
|
||||
tone = "gentle"
|
||||
tts_style = "soft"
|
||||
reasons.append("down_mood_expression_cap")
|
||||
elif up_mood and not low_energy:
|
||||
warmth = min(100, warmth + 5)
|
||||
reasons.append("up_mood_expression_lift")
|
||||
|
||||
schedule = _mapping(source.get("schedule"))
|
||||
budget = _candidate_budget(_mapping(source.get("proactive_candidate")))
|
||||
if "proactive_care_limit" in relationship_baseline:
|
||||
stage_budget = _bounded_int(relationship_baseline.get("proactive_care_limit"), 0, 0, 30)
|
||||
if budget > stage_budget:
|
||||
budget = stage_budget
|
||||
reasons.append("relationship_proactive_cap")
|
||||
initiative = "allowed" if budget else "passive_only"
|
||||
if band in {ExpressionBand.AVOIDANT, ExpressionBand.HURT}:
|
||||
budget = 0
|
||||
initiative = "passive_only"
|
||||
reasons.append("interaction_proactive_suppressed")
|
||||
if _schedule_is_quiet(schedule):
|
||||
budget = 0
|
||||
initiative = "passive_only"
|
||||
response_length = "brief" if response_length != "brief" else response_length
|
||||
followup = False
|
||||
warmth = max(0, warmth - 6)
|
||||
distance = min(100, distance + 4)
|
||||
reasons.append("schedule_proactive_suppressed")
|
||||
|
||||
if not followup and "followup" in behaviors:
|
||||
behaviors = tuple(item for item in behaviors if item != "followup")
|
||||
|
||||
return ExpressionDecision(
|
||||
contract=EXPRESSION_CONTRACT_VERSION,
|
||||
expression_band=band.value,
|
||||
tone=tone,
|
||||
warmth=warmth,
|
||||
distance=distance,
|
||||
address_style=address_style,
|
||||
response_length=response_length,
|
||||
followup=followup,
|
||||
initiative=initiative,
|
||||
proactive_budget=budget,
|
||||
tts_style=tts_style,
|
||||
allowed_behaviors=behaviors,
|
||||
safety_mode="contact_boundary_passive" if contact_boundary else "normal",
|
||||
blocker=None,
|
||||
reason_codes=tuple(reasons),
|
||||
)
|
||||
|
||||
|
||||
def allowed_expression_bands(relationship_role: Any, relationship_mode: Any) -> tuple[str, ...]:
|
||||
role = _text(relationship_role)
|
||||
del relationship_mode
|
||||
return OWNER_EXPRESSION_BANDS if role == "owner" else COMMON_EXPRESSION_BANDS
|
||||
|
||||
|
||||
def current_interaction_projection(
|
||||
value: Any,
|
||||
*,
|
||||
relationship_role: Any = "friend",
|
||||
relationship_mode: Any = "normal",
|
||||
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
|
||||
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")
|
||||
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")
|
||||
if expires_at and current_ts and current_ts >= expires_at:
|
||||
band = ExpressionBand.RELAXED
|
||||
manual = False
|
||||
reason_codes.append("interaction_expired")
|
||||
source = "manual" if manual else _text(raw.get("source")) or "automatic"
|
||||
reason = str(raw.get("reason") or raw.get("reason_code") or "").replace("\r", " ").replace("\n", " ")[:120]
|
||||
return {
|
||||
"expression_band": band.value,
|
||||
"label": EXPRESSION_BAND_LABELS[band.value],
|
||||
"source": source,
|
||||
"operator": _bounded_text(raw.get("operator"), 40),
|
||||
"reason": reason,
|
||||
"updated_at": _bounded_timestamp(raw.get("updated_at")),
|
||||
"expires_at": expires_at,
|
||||
"manual_override": manual,
|
||||
"allowed_bands": list(allowed),
|
||||
"reason_codes": reason_codes,
|
||||
}
|
||||
|
||||
|
||||
def expression_decision_prompt(value: ExpressionDecision | Mapping[str, Any]) -> str:
|
||||
decision = value.to_dict() if isinstance(value, ExpressionDecision) else dict(_mapping(value))
|
||||
band = _band(decision.get("expression_band")) or ExpressionBand.RELAXED
|
||||
if decision.get("blocker"):
|
||||
return "当前表达受边界或安全规则限制:保持简短、低压,不主动扩展或追问。"
|
||||
followup = "可以自然追问" if bool(decision.get("followup")) else "不要追问"
|
||||
initiative = "允许在合适窗口主动联系" if decision.get("initiative") == "allowed" else "本轮只被动回应"
|
||||
return (
|
||||
f"当前互动表达:{EXPRESSION_BAND_LABELS[band.value]};"
|
||||
f"语气={str(decision.get('tone') or 'steady')[:24]},"
|
||||
f"称呼距离={str(decision.get('address_style') or 'neutral')[:24]},"
|
||||
f"回复长度={str(decision.get('response_length') or 'balanced')[:24]};"
|
||||
f"{followup};{initiative}。"
|
||||
)
|
||||
|
||||
|
||||
def _bounded_timestamp(value: Any) -> float:
|
||||
if isinstance(value, bool) or not isinstance(value, (int, float)):
|
||||
return 0.0
|
||||
numeric = float(value)
|
||||
return numeric if 0 < numeric < 10**12 else 0.0
|
||||
|
||||
|
||||
def _blocked_decision(reason: str, blocker: str, inherited_reasons: list[str]) -> ExpressionDecision:
|
||||
return ExpressionDecision(
|
||||
contract=EXPRESSION_CONTRACT_VERSION,
|
||||
expression_band=ExpressionBand.AVOIDANT.value,
|
||||
tone="blocked",
|
||||
warmth=0,
|
||||
distance=100,
|
||||
address_style="none",
|
||||
response_length="none",
|
||||
followup=False,
|
||||
initiative="blocked",
|
||||
proactive_budget=0,
|
||||
tts_style="none",
|
||||
allowed_behaviors=(),
|
||||
safety_mode=reason,
|
||||
blocker=blocker,
|
||||
reason_codes=tuple(inherited_reasons + [reason]),
|
||||
)
|
||||
|
||||
|
||||
# A descriptive alias keeps runtime call sites readable while preserving one contract.
|
||||
resolve_expression_decision = build_expression_decision
|
||||
|
||||
|
||||
__all__ = [
|
||||
"COMMON_EXPRESSION_BANDS",
|
||||
"EXPRESSION_CONTRACT_VERSION",
|
||||
"EXPRESSION_BAND_LABELS",
|
||||
"ExpressionBand",
|
||||
"ExpressionDecision",
|
||||
"ExpressionInput",
|
||||
"OWNER_EXPRESSION_BANDS",
|
||||
"allowed_expression_bands",
|
||||
"build_expression_decision",
|
||||
"current_interaction_projection",
|
||||
"expression_decision_prompt",
|
||||
"resolve_expression_decision",
|
||||
]
|
||||
|
|
@ -382,6 +382,13 @@ _DEFAULT_USER_TEMPLATE = {
|
|||
"auto_profile_created_at": 0,
|
||||
"profile_origin": "",
|
||||
"relationship_role": "",
|
||||
"relationship_mode": "normal",
|
||||
"relationship_ledger": [],
|
||||
"relationship_daily_totals": {},
|
||||
"relationship_last_effective_at": 0,
|
||||
"relationship_decay_settled_day": "",
|
||||
"relationship_last_decay_stage_drop_at": 0,
|
||||
"current_interaction": {},
|
||||
"proactive_daily_limit": -1,
|
||||
"proactive_idle_minutes": -1,
|
||||
"proactive_min_interval_minutes": -1,
|
||||
|
|
@ -415,11 +422,9 @@ _DEFAULT_USER_TEMPLATE = {
|
|||
"reply_count": 0,
|
||||
"action_reply_affinity": {},
|
||||
"relationship_score": 0,
|
||||
"persona_relationship": {},
|
||||
"companion_memory": {},
|
||||
"expression_profile": {},
|
||||
"intent_profile": {},
|
||||
"relationship_state": {},
|
||||
"recent_reply_topics": [],
|
||||
"postprocess_stats": {},
|
||||
"dialogue_episodes": [],
|
||||
|
|
|
|||
140
core_store.py
140
core_store.py
|
|
@ -115,6 +115,7 @@ 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 .config_migration import _ensure_config_parent_dir
|
||||
from .storage.store_manager import StoreManager
|
||||
from .person_context_contract import empty_person_store, ensure_person_store
|
||||
|
|
@ -1298,6 +1299,26 @@ class CoreStoreMixin:
|
|||
if key not in user:
|
||||
user[key] = deepcopy(default_value)
|
||||
self._ensure_private_user_role(user_id, user)
|
||||
user["relationship_mode"] = normalize_relationship_mode(
|
||||
user.get("relationship_mode"),
|
||||
user.get("relationship_role"),
|
||||
)
|
||||
decay_result = apply_natural_relationship_decay(
|
||||
user,
|
||||
policy=(
|
||||
getattr(self, "relationship_stage_policy", None)
|
||||
if bool(getattr(self, "enable_custom_relationship_stage_policy", False))
|
||||
else None
|
||||
),
|
||||
grace_days=int(getattr(self, "relationship_decay_grace_days", 3)),
|
||||
early_rate=int(getattr(self, "relationship_decay_early_per_day", 2)),
|
||||
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"):
|
||||
save_scheduler = getattr(self, "_schedule_data_save", None)
|
||||
if callable(save_scheduler):
|
||||
save_scheduler()
|
||||
user.setdefault("manual_enabled", False)
|
||||
user.setdefault("manual_disabled", False)
|
||||
if (
|
||||
|
|
@ -1347,6 +1368,97 @@ class CoreStoreMixin:
|
|||
return observed
|
||||
return fixed or _single_line(user_id, 24)
|
||||
|
||||
def _merge_group_observation_into_private_user(
|
||||
self,
|
||||
user_id: str,
|
||||
user: dict[str, Any],
|
||||
*,
|
||||
now: float,
|
||||
use_observed_name: bool = False,
|
||||
) -> bool:
|
||||
"""Merge exact QQ observation metadata without importing group content."""
|
||||
finder = getattr(self, "_worldbook_group_observation_profile_by_identity", None)
|
||||
observed = finder(user_id) if callable(finder) else None
|
||||
if not (
|
||||
isinstance(observed, tuple)
|
||||
and len(observed) == 2
|
||||
and isinstance(observed[1], dict)
|
||||
and bool(observed[1].get("observation_only"))
|
||||
):
|
||||
return False
|
||||
profile_id, profile = observed
|
||||
changed = False
|
||||
observed_name = _single_line(profile.get("name"), 40)
|
||||
if use_observed_name and observed_name and user.get("nickname") != observed_name:
|
||||
user["nickname"] = observed_name
|
||||
changed = True
|
||||
|
||||
source_names = user.setdefault("group_observation_names", [])
|
||||
if not isinstance(source_names, list):
|
||||
source_names = []
|
||||
user["group_observation_names"] = source_names
|
||||
changed = True
|
||||
if observed_name and observed_name not in source_names:
|
||||
source_names.append(observed_name)
|
||||
del source_names[:-16]
|
||||
changed = True
|
||||
|
||||
source_scopes = profile.get("group_observation_scope_ids")
|
||||
scopes = user.setdefault("group_observation_scope_ids", [])
|
||||
if not isinstance(scopes, list):
|
||||
scopes = []
|
||||
user["group_observation_scope_ids"] = scopes
|
||||
changed = True
|
||||
for raw_scope in source_scopes if isinstance(source_scopes, list) else []:
|
||||
scope = _single_line(raw_scope, 80)
|
||||
if scope and scope not in scopes:
|
||||
scopes.append(scope)
|
||||
changed = True
|
||||
del scopes[:-32]
|
||||
|
||||
source_aliases = profile.get("group_aliases")
|
||||
aliases = user.setdefault("group_observation_aliases", {})
|
||||
if not isinstance(aliases, dict):
|
||||
aliases = {}
|
||||
user["group_observation_aliases"] = aliases
|
||||
changed = True
|
||||
if isinstance(source_aliases, dict):
|
||||
for raw_group_id, raw_names in source_aliases.items():
|
||||
group_id = _single_line(raw_group_id, 80)
|
||||
if not group_id:
|
||||
continue
|
||||
current = aliases.setdefault(group_id, [])
|
||||
if not isinstance(current, list):
|
||||
current = []
|
||||
aliases[group_id] = current
|
||||
changed = True
|
||||
for raw_name in raw_names if isinstance(raw_names, list) else []:
|
||||
name = _single_line(raw_name, 40)
|
||||
if name and name not in current:
|
||||
current.append(name)
|
||||
changed = True
|
||||
del current[:-8]
|
||||
|
||||
sources = user.setdefault("profile_sources", [])
|
||||
if not isinstance(sources, list):
|
||||
sources = []
|
||||
user["profile_sources"] = sources
|
||||
changed = True
|
||||
for source in ("private_chat", "group_observation"):
|
||||
if source not in sources:
|
||||
sources.append(source)
|
||||
changed = True
|
||||
marker = str(profile_id or user_id)
|
||||
if profile.get("private_profile_merged") is not True or profile.get("private_user_id") != user_id:
|
||||
profile["private_profile_merged"] = True
|
||||
profile["private_user_id"] = user_id
|
||||
profile["private_profile_merged_at"] = now
|
||||
profile["private_profile_merge_source_id"] = marker
|
||||
changed = True
|
||||
if changed:
|
||||
user["group_observation_merged_at"] = now
|
||||
return changed
|
||||
|
||||
def _ensure_auto_private_user_profile(
|
||||
self,
|
||||
event: Any,
|
||||
|
|
@ -1356,8 +1468,6 @@ class CoreStoreMixin:
|
|||
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
|
||||
|
|
@ -1367,7 +1477,16 @@ class CoreStoreMixin:
|
|||
users = self.data.setdefault("users", {})
|
||||
existing = users.get(canonical_user_id) if isinstance(users, dict) else None
|
||||
if isinstance(existing, dict):
|
||||
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()),
|
||||
):
|
||||
self._schedule_data_save()
|
||||
return existing, False
|
||||
if not bool(getattr(self, "enable_auto_user_profile_creation", True)):
|
||||
return None, False
|
||||
|
||||
user = self._get_user(canonical_user_id)
|
||||
created_at = float(now if now is not None else _now_ts())
|
||||
|
|
@ -1375,12 +1494,29 @@ class CoreStoreMixin:
|
|||
user["auto_profile_created_at"] = created_at
|
||||
user["profile_origin"] = "private_auto"
|
||||
user["relationship_role"] = "friend"
|
||||
user["relationship_mode"] = "normal"
|
||||
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)
|
||||
observation_merger = getattr(self, "_merge_group_observation_into_private_user", None)
|
||||
if callable(observation_merger):
|
||||
observation_merger(
|
||||
canonical_user_id,
|
||||
user,
|
||||
now=created_at,
|
||||
use_observed_name=not bool(_single_line(sender_display_name, 40)),
|
||||
)
|
||||
user["style"] = _single_line(getattr(self, "default_style", "温柔"), 24) or "温柔"
|
||||
user["current_interaction"] = {
|
||||
"expression_band": str(getattr(self, "default_interaction_band", "relaxed") or "relaxed"),
|
||||
"source": "default_profile",
|
||||
"reason": "auto_profile_default",
|
||||
"updated_at": created_at,
|
||||
"expires_at": 0,
|
||||
"manual_override": False,
|
||||
}
|
||||
auto_enabled = bool(getattr(self, "auto_enable_companion_for_new_users", False))
|
||||
user["auto_enabled"] = auto_enabled
|
||||
user["manual_enabled"] = False
|
||||
|
|
|
|||
|
|
@ -15943,10 +15943,6 @@ class DailyStateMixin:
|
|||
}
|
||||
if memory_companion_proactive_payload:
|
||||
await self._memory_companion_record_proactive_message(**memory_companion_proactive_payload)
|
||||
self._create_lifecycle_background_task(
|
||||
self._refresh_persona_relationship(user_id, current_snapshot, trigger="proactive"),
|
||||
label="refresh_persona_relationship_proactive",
|
||||
)
|
||||
|
||||
await self._run_proactive_maintenance_tasks()
|
||||
async with self._data_lock:
|
||||
|
|
|
|||
|
|
@ -316,6 +316,29 @@ _GROUP_INJECTION_QUOTE_DAMPENERS = (
|
|||
class GroupObservationMixin:
|
||||
"""群聊观察"""
|
||||
|
||||
def _record_group_observation_profile_projection_result(self, code: str) -> None:
|
||||
"""Keep aggregate-only E2A observability without retaining message data.
|
||||
|
||||
The counters are intentionally not keyed by group, sender, message id,
|
||||
or text. They help distinguish a disabled route from an unexpected
|
||||
projection failure while preserving the observation-only boundary.
|
||||
"""
|
||||
result_code = _single_line(code, 48) or "unknown"
|
||||
data = getattr(self, "data", None)
|
||||
if not isinstance(data, dict):
|
||||
return
|
||||
stats = data.setdefault("group_observation_profile_projection_stats", {})
|
||||
if not isinstance(stats, dict):
|
||||
stats = {}
|
||||
data["group_observation_profile_projection_stats"] = stats
|
||||
counts = stats.setdefault("counts", {})
|
||||
if not isinstance(counts, dict):
|
||||
counts = {}
|
||||
stats["counts"] = counts
|
||||
counts[result_code] = _safe_int(counts.get(result_code), 0, 0) + 1
|
||||
stats["last_result_code"] = result_code
|
||||
stats["last_result_at"] = _now_ts()
|
||||
|
||||
def _group_injection_guard_threshold(self) -> int:
|
||||
return _GROUP_INJECTION_GUARD_THRESHOLD
|
||||
|
||||
|
|
@ -669,16 +692,46 @@ class GroupObservationMixin:
|
|||
qq_nickname = _single_line(nickname_getter(event), 40)
|
||||
except Exception:
|
||||
qq_nickname = ""
|
||||
if self.enable_group_member_profiles:
|
||||
projection_result = "skipped_member_profiles_disabled"
|
||||
effective_group_id = str(group_id or group.get("group_id") or "")
|
||||
group_enabled_getter = getattr(self, "_group_enabled_for_event", None)
|
||||
group_allowed = True
|
||||
if callable(group_enabled_getter):
|
||||
try:
|
||||
group_allowed = bool(group_enabled_getter(effective_group_id))
|
||||
except Exception:
|
||||
group_allowed = False
|
||||
if not group_allowed:
|
||||
projection_result = "skipped_group_not_allowed"
|
||||
elif not _single_line(sender_id, 40):
|
||||
projection_result = "skipped_missing_sender"
|
||||
elif bool(getattr(self, "enable_group_member_profiles", False)):
|
||||
profile_ensurer = getattr(self, "_ensure_worldbook_group_observation_profile", None)
|
||||
if callable(profile_ensurer):
|
||||
profile_ensurer(
|
||||
group_id=str(group_id or group.get("group_id") or ""),
|
||||
sender_id=sender_id,
|
||||
qq_nickname=qq_nickname,
|
||||
group_card=sender_name,
|
||||
now=now,
|
||||
)
|
||||
if not callable(profile_ensurer):
|
||||
projection_result = "skipped_profile_handler_unavailable"
|
||||
else:
|
||||
profiles = self.data.get("worldbook_member_profiles") if isinstance(getattr(self, "data", None), dict) else {}
|
||||
existed = isinstance(profiles, dict) and isinstance(profiles.get(str(sender_id)), dict)
|
||||
try:
|
||||
profile = profile_ensurer(
|
||||
group_id=effective_group_id,
|
||||
sender_id=sender_id,
|
||||
qq_nickname=qq_nickname,
|
||||
group_card=sender_name,
|
||||
now=now,
|
||||
)
|
||||
if not isinstance(profile, dict):
|
||||
projection_result = "skipped_invalid_identity"
|
||||
elif bool(profile.get("observation_only")):
|
||||
projection_result = "updated" if existed else "created"
|
||||
else:
|
||||
projection_result = "skipped_existing_authoritative_profile"
|
||||
except Exception:
|
||||
# Profile projection must never block an otherwise valid
|
||||
# whitelisted-group observation or its reply path.
|
||||
projection_result = "failed"
|
||||
logger.warning("[PrivateCompanion] 群观察档案投影失败: code=failed")
|
||||
self._record_group_observation_profile_projection_result(projection_result)
|
||||
|
||||
recent = group.setdefault("recent_messages", [])
|
||||
if not isinstance(recent, list):
|
||||
|
|
@ -904,6 +957,7 @@ class GroupObservationMixin:
|
|||
cleaned = _single_line(text, 260)
|
||||
clean_message_id = _single_line(message_id, 120)
|
||||
if not cleaned:
|
||||
self._record_group_observation_profile_projection_result("skipped_empty_message")
|
||||
return False
|
||||
marker = getattr(event, "private_companion_group_observation_capture", None) if event is not None else None
|
||||
already_captured = self._group_observation_marker_matches(
|
||||
|
|
|
|||
86
main.py
86
main.py
|
|
@ -136,11 +136,9 @@ from .person_context_contract import (
|
|||
from .unified_person_registry import UnifiedPersonRegistry
|
||||
from .context_orchestration import build_context, project_context
|
||||
from .p4_shadow import build_p4_shadow
|
||||
from .p4_affinity_confinement import apply_legacy_relationship_delta
|
||||
from .p4_live_runtime import decide_live_request
|
||||
from .p4_runtime_gate import SAFE_CONFINEMENT_REPLY
|
||||
from .p6_readonly_projection import build_p6_readonly_status
|
||||
from .reply_temperature import compose_reply_temperature
|
||||
from .plugin_identity import (
|
||||
PLUGIN_ID,
|
||||
PLUGIN_VERSION,
|
||||
|
|
@ -149,6 +147,8 @@ 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 .companion_interaction_expression import build_expression_decision, expression_decision_prompt
|
||||
from .user_rest_gate import UserRestGateMixin
|
||||
from .busy_reply_gate import BusyReplyGateMixin
|
||||
from .memory_companion_adapter import MemoryCompanionAdapterMixin
|
||||
|
|
@ -1439,6 +1439,9 @@ class PrivateCompanionPlugin(
|
|||
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_interaction_band = self._cfg_str(c, "default_interaction_band", "relaxed")
|
||||
if self.default_interaction_band not in {"avoidant", "hurt", "relaxed", "lively", "warm"}:
|
||||
self.default_interaction_band = "relaxed"
|
||||
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(
|
||||
|
|
@ -1449,6 +1452,18 @@ class PrivateCompanionPlugin(
|
|||
self.relationship_stage_policy = normalize_relationship_stage_policy(
|
||||
self._cfg_raw(c, "relationship_stage_policy", [])
|
||||
)
|
||||
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", "优先使用已确认的专属称呼", "优先使用已确认的专属称呼")
|
||||
self.owner_exclusive_proactive_limit = self._cfg_int(c, "owner_exclusive_proactive_limit", 6, 0, 30)
|
||||
self.relationship_event_window_minutes = self._cfg_int(c, "relationship_event_window_minutes", 30, 1, 1440)
|
||||
self.relationship_positive_event_cap = self._cfg_int(c, "relationship_positive_event_cap", 4, 1, 30)
|
||||
self.relationship_negative_event_cap = self._cfg_int(c, "relationship_negative_event_cap", 12, 1, 60)
|
||||
self.relationship_positive_daily_cap = self._cfg_int(c, "relationship_positive_daily_cap", 12, 0, 120)
|
||||
self.relationship_decay_grace_days = self._cfg_int(c, "relationship_decay_grace_days", 3, 0, 30)
|
||||
self.relationship_decay_early_per_day = self._cfg_int(c, "relationship_decay_early_per_day", 2, 0, 30)
|
||||
self.relationship_decay_middle_per_day = self._cfg_int(c, "relationship_decay_middle_per_day", 5, 0, 30)
|
||||
self.relationship_decay_late_per_day = self._cfg_int(c, "relationship_decay_late_per_day", 8, 0, 30)
|
||||
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", ""))
|
||||
|
|
@ -2014,7 +2029,9 @@ class PrivateCompanionPlugin(
|
|||
self.proactive_review_low_score_threshold = self._cfg_unit_interval(c, "proactive_review_low_score_threshold", 0.34, 0.0)
|
||||
self.proactive_review_pressure_threshold = self._cfg_unit_interval(c, "proactive_review_pressure_threshold", 0.55, 0.0)
|
||||
self.enable_passive_topic_suppression = self._cfg_bool(c, "enable_passive_topic_suppression", True)
|
||||
self.enable_relationship_analysis = self._cfg_bool(c, "enable_relationship_analysis", True)
|
||||
# Compatibility flag only: the old model-generated three-band
|
||||
# relationship analysis is retired by the unified expression system.
|
||||
self.enable_relationship_analysis = False
|
||||
self.enable_relationship_state_machine = self._cfg_bool(c, "enable_relationship_state_machine", True)
|
||||
self.enable_emotion_simulation = self._cfg_bool(c, "enable_emotion_simulation", True)
|
||||
self.enable_llm_emotion_judgement = self._cfg_bool(c, "enable_llm_emotion_judgement", False)
|
||||
|
|
@ -2562,12 +2579,18 @@ class PrivateCompanionPlugin(
|
|||
return self.unified_person_registry.read_p4_live_state(person_id)
|
||||
|
||||
def _p4_b_apply_legacy_relationship_delta(self, user: dict[str, Any], delta: int, *, reason_code: str = "") -> bool:
|
||||
del reason_code
|
||||
return apply_legacy_relationship_delta(
|
||||
if bool(getattr(self, "enable_p4_b_legacy_score_isolation", False)):
|
||||
return False
|
||||
result = apply_relationship_event(
|
||||
user,
|
||||
delta,
|
||||
isolate=bool(getattr(self, "enable_p4_b_legacy_score_isolation", False)),
|
||||
reason_code=reason_code or "legacy_relationship_event",
|
||||
positive_daily_cap=int(getattr(self, "relationship_positive_daily_cap", 12)),
|
||||
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)),
|
||||
)
|
||||
return bool(result.get("changed"))
|
||||
|
||||
def _p4_live_state_for_event(self, event: Any) -> dict[str, Any] | None:
|
||||
try:
|
||||
|
|
@ -2586,8 +2609,8 @@ class PrivateCompanionPlugin(
|
|||
return {"_p4_live_invalid": True}
|
||||
return result.get("state")
|
||||
|
||||
def _bounded_p4_reply_temperature_signals(self, event: Any) -> dict[str, Any]:
|
||||
"""Return transient, bounded advisory inputs for the P4 reply projection."""
|
||||
def _bounded_expression_state_signals(self, event: Any) -> dict[str, Any]:
|
||||
"""Return transient, bounded Bot-state inputs for the unified expression decision."""
|
||||
data = getattr(self, "data", None)
|
||||
daily_state = data.get("daily_state") if isinstance(data, dict) else None
|
||||
energy = daily_state.get("energy") if isinstance(daily_state, dict) else None
|
||||
|
|
@ -9395,8 +9418,6 @@ wakeup_type={_single_line(wakeup.get('type'), 40)} score={_single_line(wakeup.ge
|
|||
return
|
||||
state = self._p4_live_state_for_event(event)
|
||||
decision = decide_live_request(state)
|
||||
if decision.get("decision") == "skip":
|
||||
return
|
||||
if decision.get("decision") == "block":
|
||||
# This runs before P5/Memory and the enrichment collectors. Leave
|
||||
# no request route to original prompt, tool, bridge, or context data.
|
||||
|
|
@ -9422,17 +9443,44 @@ wakeup_type={_single_line(wakeup.get('type'), 40)} score={_single_line(wakeup.ge
|
|||
await self._reply(event, SAFE_CONFINEMENT_REPLY)
|
||||
event.stop_event()
|
||||
return
|
||||
temperature = compose_reply_temperature(
|
||||
decision.get("warmth_projection", {}).get("tier"),
|
||||
**self._bounded_p4_reply_temperature_signals(event),
|
||||
)
|
||||
p4_cap = _single_line(decision.get("warmth_projection", {}).get("tier"), 24) if decision.get("decision") != "skip" else ""
|
||||
transient = self._bounded_expression_state_signals(event)
|
||||
expression_projection: dict[str, Any] = {}
|
||||
try:
|
||||
setattr(req, "_private_companion_reply_temperature", temperature)
|
||||
sender_id = self._canonical_private_user_id(str(event.get_sender_id()))
|
||||
except Exception:
|
||||
sender_id = ""
|
||||
users = self.data.get("users", {}) if isinstance(getattr(self, "data", None), dict) else {}
|
||||
current_user = users.get(sender_id) if sender_id and isinstance(users, dict) else None
|
||||
expression_builder = getattr(self, "_build_expression_decision_for_user", None)
|
||||
if isinstance(current_user, dict) and callable(expression_builder):
|
||||
try:
|
||||
expression = expression_builder(
|
||||
current_user,
|
||||
safety_constraints={"p4_warmth_cap": p4_cap} if p4_cap else {},
|
||||
passive_reengagement=True,
|
||||
bot_state={"energy": transient.get("energy"), "mood": transient.get("mood")},
|
||||
schedule={"label": transient.get("schedule") or ""},
|
||||
)
|
||||
expression_projection = expression.to_dict() if hasattr(expression, "to_dict") else dict(expression or {})
|
||||
except Exception as exc:
|
||||
logger.debug("[PrivateCompanion] 统一表达决策生成失败,使用保守默认值: %s", _single_line(exc, 120))
|
||||
if not expression_projection:
|
||||
fallback = build_expression_decision(
|
||||
{
|
||||
"bot_state": {"energy": transient.get("energy"), "mood": transient.get("mood")},
|
||||
"schedule": {"label": transient.get("schedule") or ""},
|
||||
"safety_constraints": {"p4_warmth_cap": p4_cap} if p4_cap else {},
|
||||
}
|
||||
)
|
||||
expression_projection = fallback.to_dict()
|
||||
try:
|
||||
setattr(req, "_private_companion_expression_decision", expression_projection)
|
||||
except Exception:
|
||||
pass
|
||||
instruction = _single_line(temperature.get("instruction"), 240)
|
||||
instruction = expression_decision_prompt(expression_projection)
|
||||
if instruction and hasattr(req, "system_prompt"):
|
||||
req.system_prompt = f"{str(getattr(req, 'system_prompt', '') or '').rstrip()}\n\n[Reply boundary]\n{instruction}"
|
||||
req.system_prompt = f"{str(getattr(req, 'system_prompt', '') or '').rstrip()}\n\n[Companion expression]\n{instruction}"
|
||||
|
||||
@filter.on_llm_request(priority=-22000)
|
||||
async def prepare_p5_memory_attestation(self, event: AstrMessageEvent, req: ProviderRequest, *args, **kwargs):
|
||||
|
|
@ -12676,10 +12724,6 @@ wakeup_type={_single_line(wakeup.get('type'), 40)} score={_single_line(wakeup.ge
|
|||
elif is_target_user:
|
||||
pass
|
||||
if is_target_user:
|
||||
self._create_lifecycle_background_task(
|
||||
self._refresh_persona_relationship(user_id, user_snapshot, trigger="inbound"),
|
||||
label="refresh_persona_relationship_inbound",
|
||||
)
|
||||
self._create_lifecycle_background_task(
|
||||
self._maybe_refresh_companion_memory(user_id, user_snapshot),
|
||||
label="refresh_companion_memory_inbound",
|
||||
|
|
|
|||
|
|
@ -23,6 +23,8 @@ 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 .companion_interaction_expression import current_interaction_projection
|
||||
from .relationship_ledger import normalize_relationship_mode
|
||||
from .relationship_policy import relationship_projection_for_bridge
|
||||
|
||||
|
||||
|
|
@ -1469,6 +1471,19 @@ class MemoryCompanionAdapterMixin:
|
|||
else None
|
||||
)
|
||||
projection = relationship_projection_for_bridge(user.get("relationship_score", 0), policy)
|
||||
role_getter = getattr(self, "_private_user_role", None)
|
||||
try:
|
||||
role = role_getter(user, user_id) if callable(role_getter) else str(user.get("relationship_role") or "friend")
|
||||
except Exception:
|
||||
role = str(user.get("relationship_role") or "friend")
|
||||
relationship_mode = normalize_relationship_mode(user.get("relationship_mode"), role)
|
||||
projection["relationship_mode"] = relationship_mode
|
||||
projection["current_interaction"] = current_interaction_projection(
|
||||
user.get("current_interaction"),
|
||||
relationship_role=role,
|
||||
relationship_mode=relationship_mode,
|
||||
now=time.time(),
|
||||
)
|
||||
bridge = self._memory_companion_bridge()
|
||||
consumer = getattr(bridge, "consume_relationship_projection", None) if bridge is not None else None
|
||||
if callable(consumer):
|
||||
|
|
|
|||
237
page_api.py
237
page_api.py
|
|
@ -29,7 +29,9 @@ 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 .reference_asset_gate import ReferenceAssetGate
|
||||
from .relationship_ledger import normalize_relationship_mode, relationship_ledger_summary
|
||||
from .relationship_policy import (
|
||||
normalize_relationship_stage_policy,
|
||||
relationship_stage_for_score,
|
||||
|
|
@ -181,6 +183,51 @@ class PrivateCompanionPageApi(PrivateCompanionPageApiQzoneMixin, PrivateCompanio
|
|||
reply_band = "low"
|
||||
|
||||
relationship_intimacy = self._relationship_intimacy_projection(self._int(user.get("relationship_score")))
|
||||
role = self.plugin._private_user_role(user, str(user.get("user_id") or "")) if hasattr(self.plugin, "_private_user_role") else str(user.get("relationship_role") or "friend")
|
||||
relationship_mode = normalize_relationship_mode(user.get("relationship_mode"), role)
|
||||
relationship_changes = relationship_ledger_summary(user)
|
||||
relationship_intimacy["trend"] = relationship_changes.get("trend", "steady")
|
||||
relationship_intimacy["recent_delta"] = relationship_changes.get("recent_delta", 0)
|
||||
current_interaction = current_interaction_projection(
|
||||
user.get("current_interaction"),
|
||||
relationship_role=role,
|
||||
relationship_mode=relationship_mode,
|
||||
now=time.time(),
|
||||
)
|
||||
expression_projection = {
|
||||
"contract": "companion_interaction_expression.v1",
|
||||
"status": "configured_projection",
|
||||
"expression_band": current_interaction.get("expression_band") or "relaxed",
|
||||
"tone": "steady",
|
||||
"response_length": "balanced",
|
||||
"initiative": "passive_only",
|
||||
"safety_mode": "live_event_not_evaluated",
|
||||
"blocker": "",
|
||||
"reason_codes": [],
|
||||
}
|
||||
expression_builder = getattr(self.plugin, "_build_expression_decision_for_user", None)
|
||||
if callable(expression_builder):
|
||||
try:
|
||||
raw_expression = expression_builder(user, passive_reengagement=True)
|
||||
raw_projection = raw_expression.to_dict() if hasattr(raw_expression, "to_dict") else dict(raw_expression or {})
|
||||
expression_projection.update(
|
||||
{
|
||||
"contract": self._single_line(raw_projection.get("contract"), 80) or "companion_interaction_expression.v1",
|
||||
"expression_band": self._single_line(raw_projection.get("expression_band"), 24) or "relaxed",
|
||||
"tone": self._single_line(raw_projection.get("tone"), 24) or "steady",
|
||||
"response_length": self._single_line(raw_projection.get("response_length"), 24) or "balanced",
|
||||
"initiative": self._single_line(raw_projection.get("initiative"), 24) or "passive_only",
|
||||
"safety_mode": self._single_line(raw_projection.get("safety_mode"), 40) or "normal",
|
||||
"blocker": self._single_line(raw_projection.get("blocker"), 40),
|
||||
"reason_codes": [
|
||||
self._single_line(code, 48)
|
||||
for code in list(raw_projection.get("reason_codes") or [])[:8]
|
||||
if self._single_line(code, 48)
|
||||
],
|
||||
}
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
memory_phase = {"status": "unavailable", "phase": "unknown", "momentum_band": "unknown"}
|
||||
getter = getattr(self.plugin, "_memory_companion_peek_relationship_phase", None)
|
||||
session_id = self._single_line(user.get("umo"), 200)
|
||||
|
|
@ -208,11 +255,14 @@ class PrivateCompanionPageApi(PrivateCompanionPageApiQzoneMixin, PrivateCompanio
|
|||
"band": relationship_intimacy["phase"]["label"],
|
||||
},
|
||||
"relationship_stage": self._single_line(relationship_stage, 24) or "unclassified",
|
||||
"relationship_mode": relationship_mode,
|
||||
"relationship_intimacy": relationship_intimacy,
|
||||
"relationship_changes": relationship_changes,
|
||||
"current_interaction": current_interaction,
|
||||
"interaction": {"inbound_count": inbound, "reply_count": replies, "reply_band": reply_band},
|
||||
"memory_phase": memory_phase,
|
||||
"network": network,
|
||||
"reply_temperature": {"status": "live_chat_only"},
|
||||
"expression_decision": expression_projection,
|
||||
}
|
||||
|
||||
def _create_page_background_task(self, operation: Any, *, label: str) -> asyncio.Task | None:
|
||||
|
|
@ -9836,31 +9886,6 @@ class PrivateCompanionPageApi(PrivateCompanionPageApiQzoneMixin, PrivateCompanio
|
|||
)
|
||||
relationship_stage = ""
|
||||
rel_state = user.get("relationship_state") if isinstance(user.get("relationship_state"), dict) else {}
|
||||
if isinstance(rel_state, dict):
|
||||
relationship_stage = self._single_line(rel_state.get("stage"), 12)
|
||||
profile_getter = getattr(self.plugin, "_relationship_profile", None)
|
||||
if not relationship_stage and callable(profile_getter):
|
||||
try:
|
||||
profile = profile_getter(user)
|
||||
if isinstance(profile, dict):
|
||||
relationship_stage = self._single_line(profile.get("level"), 12)
|
||||
except Exception:
|
||||
relationship_stage = ""
|
||||
if relationship_stage not in {"亲近", "熟悉", "陌生"}:
|
||||
persona_profile = user.get("persona_relationship") if isinstance(user.get("persona_relationship"), dict) else {}
|
||||
relationship_stage = self._single_line(persona_profile.get("level"), 12) if isinstance(persona_profile, dict) else ""
|
||||
if relationship_stage not in {"亲近", "熟悉", "陌生"}:
|
||||
score = self._int(user.get("relationship_score"))
|
||||
inbound_count = self._int(user.get("inbound_count"))
|
||||
proactive_count = self._int(user.get("proactive_sent_count"))
|
||||
reply_count = self._int(user.get("reply_count"))
|
||||
reply_rate = reply_count / proactive_count if proactive_count > 0 else 0.0
|
||||
if score >= 16 and reply_rate >= 0.35:
|
||||
relationship_stage = "亲近"
|
||||
elif score >= 3 or inbound_count >= 1 or reply_rate >= 0.2:
|
||||
relationship_stage = "熟悉"
|
||||
else:
|
||||
relationship_stage = "陌生"
|
||||
role = self.plugin._private_user_role(user, user_id_text) if hasattr(self.plugin, "_private_user_role") else ""
|
||||
role_labeler = getattr(self.plugin, "_private_user_role_label", None)
|
||||
role_label = role_labeler(role) if callable(role_labeler) else ("主要用户" if role == "owner" else "次要用户")
|
||||
|
|
@ -9868,6 +9893,36 @@ class PrivateCompanionPageApi(PrivateCompanionPageApiQzoneMixin, PrivateCompanio
|
|||
pending_emotion_judgement = self._emotion_pending_judgement_summary(user.get("pending_emotion_judgement"))
|
||||
last_emotion_judgement_error = self._single_line(user.get("last_emotion_judgement_error"), 160)
|
||||
relationship_intimacy = self._relationship_intimacy_projection(self._int(user.get("relationship_score")))
|
||||
relationship_mode = normalize_relationship_mode(user.get("relationship_mode"), role)
|
||||
ledger_summary = relationship_ledger_summary(user)
|
||||
relationship_intimacy["trend"] = ledger_summary.get("trend", "steady")
|
||||
relationship_intimacy["recent_delta"] = ledger_summary.get("recent_delta", 0)
|
||||
current_interaction = current_interaction_projection(
|
||||
user.get("current_interaction"),
|
||||
relationship_role=role,
|
||||
relationship_mode=relationship_mode,
|
||||
now=time.time(),
|
||||
)
|
||||
if relationship_mode == "owner_exclusive":
|
||||
relationship_intimacy["owner_exclusive"] = {
|
||||
"label": self._single_line(getattr(self.plugin, "owner_exclusive_label", "专属联结"), 20) or "专属联结",
|
||||
"tone": self._single_line(getattr(self.plugin, "owner_exclusive_tone", "温暖、亲近、稳定"), 120),
|
||||
"address_level": self._single_line(
|
||||
getattr(self.plugin, "owner_exclusive_address_style", "优先使用已确认的专属称呼"),
|
||||
100,
|
||||
),
|
||||
"proactive_care_limit": max(0, self._int(getattr(self.plugin, "owner_exclusive_proactive_limit", 6))),
|
||||
"fixed": True,
|
||||
}
|
||||
relationship_stage = self._single_line(
|
||||
getattr(self.plugin, "owner_exclusive_label", "专属联结"),
|
||||
20,
|
||||
) or "专属联结"
|
||||
else:
|
||||
relationship_stage = self._single_line(
|
||||
(relationship_intimacy.get("phase") or {}).get("label"),
|
||||
20,
|
||||
) or relationship_stage
|
||||
return {
|
||||
"user_id": user_id_text,
|
||||
"display_name": display_name,
|
||||
|
|
@ -9939,12 +9994,25 @@ class PrivateCompanionPageApi(PrivateCompanionPageApiQzoneMixin, PrivateCompanio
|
|||
"reply_count": user.get("reply_count", 0),
|
||||
"proactive_sent_count": user.get("proactive_sent_count", 0),
|
||||
"relationship_score": user.get("relationship_score", 0),
|
||||
"relationship_mode": relationship_mode,
|
||||
"relationship_mode_label": (
|
||||
self._single_line(getattr(self.plugin, "owner_exclusive_label", "专属联结"), 20) or "专属联结"
|
||||
if relationship_mode == "owner_exclusive"
|
||||
else "普通关系"
|
||||
),
|
||||
"relationship_basis": {
|
||||
"value": relationship_intimacy["value"],
|
||||
"band": relationship_intimacy["phase"]["label"],
|
||||
},
|
||||
"relationship_intimacy": relationship_intimacy,
|
||||
"relationship_stage": relationship_stage,
|
||||
"relationship_ledger": ledger_summary,
|
||||
"current_interaction": current_interaction,
|
||||
"expression_authority": {
|
||||
"current_interaction": "authoritative",
|
||||
"expression_decision": "authoritative",
|
||||
"relationship_state": "legacy_compat_read_only",
|
||||
},
|
||||
"relationship_state": relationship_state,
|
||||
"pending_emotion_judgement": pending_emotion_judgement,
|
||||
"last_emotion_judgement_error": last_emotion_judgement_error,
|
||||
|
|
@ -9990,7 +10058,11 @@ class PrivateCompanionPageApi(PrivateCompanionPageApiQzoneMixin, PrivateCompanio
|
|||
"last_intent_confidence",
|
||||
"last_emotion_confidence",
|
||||
}
|
||||
summary: dict[str, Any] = {}
|
||||
summary: dict[str, Any] = {
|
||||
"compatibility": "legacy_read_only",
|
||||
"authoritative": False,
|
||||
"current_authority": "current_interaction",
|
||||
}
|
||||
for key, limit in scalar_limits.items():
|
||||
if key in state:
|
||||
summary[key] = self._single_line(state.get(key), limit)
|
||||
|
|
@ -10095,12 +10167,13 @@ class PrivateCompanionPageApi(PrivateCompanionPageApiQzoneMixin, PrivateCompanio
|
|||
return None
|
||||
|
||||
def _worldbook_member_profile_summary(self, user_id: str, item: dict[str, Any]) -> dict[str, Any]:
|
||||
observation_only = bool(item.get("observation_only", False))
|
||||
aliases = item.get("aliases") if isinstance(item.get("aliases"), list) else []
|
||||
observed = item.get("observed_names") if isinstance(item.get("observed_names"), list) else []
|
||||
external_ids = item.get("external_ids") if isinstance(item.get("external_ids"), list) else []
|
||||
memories = self._normalize_important_memories(item.get("important_memories"))
|
||||
pending = item.get("pending_observations") if isinstance(item.get("pending_observations"), list) else []
|
||||
return {
|
||||
memories = [] if observation_only else self._normalize_important_memories(item.get("important_memories"))
|
||||
pending = [] if observation_only else (item.get("pending_observations") if isinstance(item.get("pending_observations"), list) else [])
|
||||
summary = {
|
||||
"user_id": self._single_line(user_id, 40),
|
||||
"identity_type": self._single_line(item.get("identity_type") or ("qq" if str(user_id).isdigit() else "external"), 20),
|
||||
"name": self._single_line(item.get("name"), 60),
|
||||
|
|
@ -10112,6 +10185,19 @@ class PrivateCompanionPageApi(PrivateCompanionPageApiQzoneMixin, PrivateCompanio
|
|||
"external_ids": [self._single_line(ext, 80) for ext in external_ids if self._single_line(ext, 80)],
|
||||
"linked_qq_user_id": self._single_line(item.get("linked_qq_user_id") or item.get("merged_into_user_id"), 40),
|
||||
"linked_bili_profile_id": self._single_line(item.get("linked_bili_profile_id"), 80),
|
||||
"profile_origin": self._single_line(item.get("profile_origin"), 40),
|
||||
"observation_only": observation_only,
|
||||
"proactive_contact_enabled": bool(item.get("proactive_contact_enabled", False)),
|
||||
"private_memory_enabled": bool(item.get("private_memory_enabled", False)),
|
||||
"cross_group_memory_enabled": bool(item.get("cross_group_memory_enabled", False)),
|
||||
"p4_eligible": bool(item.get("p4_eligible", False)),
|
||||
"observed_group_count": len(
|
||||
{
|
||||
self._single_line(group_id, 80)
|
||||
for group_id in (item.get("group_observation_scope_ids") if isinstance(item.get("group_observation_scope_ids"), list) else [])
|
||||
if self._single_line(group_id, 80)
|
||||
}
|
||||
),
|
||||
"content": self._single_line(item.get("content"), 260),
|
||||
"identity_note": self._single_line(item.get("identity_note") or item.get("note") or item.get("content"), 500),
|
||||
"boundary_note": self._single_line(item.get("boundary_note"), 500),
|
||||
|
|
@ -10120,6 +10206,16 @@ class PrivateCompanionPageApi(PrivateCompanionPageApiQzoneMixin, PrivateCompanio
|
|||
"source_entries": item.get("source_entries") if isinstance(item.get("source_entries"), list) else [],
|
||||
"note": self._single_line(item.get("note"), 500),
|
||||
}
|
||||
if observation_only:
|
||||
summary.update(
|
||||
{
|
||||
"proactive_contact_enabled": False,
|
||||
"private_memory_enabled": False,
|
||||
"cross_group_memory_enabled": False,
|
||||
"p4_eligible": False,
|
||||
}
|
||||
)
|
||||
return summary
|
||||
|
||||
def _behavior_habit_summary(self, user: dict[str, Any]) -> dict[str, Any]:
|
||||
formatter = getattr(self.plugin, "_qualified_user_behavior_habits", None)
|
||||
|
|
@ -13042,9 +13138,22 @@ class PrivateCompanionPageApi(PrivateCompanionPageApiQzoneMixin, PrivateCompanio
|
|||
"default_nickname_strategy",
|
||||
"default_relationship_role",
|
||||
"default_relationship_score",
|
||||
"default_interaction_band",
|
||||
"default_proactive_enabled",
|
||||
"default_proactive_daily_limit",
|
||||
"relationship_stage_policy",
|
||||
"owner_exclusive_label",
|
||||
"owner_exclusive_tone",
|
||||
"owner_exclusive_address_style",
|
||||
"owner_exclusive_proactive_limit",
|
||||
"relationship_event_window_minutes",
|
||||
"relationship_positive_event_cap",
|
||||
"relationship_negative_event_cap",
|
||||
"relationship_positive_daily_cap",
|
||||
"relationship_decay_grace_days",
|
||||
"relationship_decay_early_per_day",
|
||||
"relationship_decay_middle_per_day",
|
||||
"relationship_decay_late_per_day",
|
||||
"reply_style_prompt",
|
||||
"enable_persona_voice_channels",
|
||||
"persona_conversation_voice_prompt",
|
||||
|
|
@ -15605,9 +15714,22 @@ class PrivateCompanionPageApi(PrivateCompanionPageApiQzoneMixin, PrivateCompanio
|
|||
"default_nickname_strategy",
|
||||
"default_relationship_role",
|
||||
"default_relationship_score",
|
||||
"default_interaction_band",
|
||||
"default_proactive_enabled",
|
||||
"default_proactive_daily_limit",
|
||||
"relationship_stage_policy",
|
||||
"owner_exclusive_label",
|
||||
"owner_exclusive_tone",
|
||||
"owner_exclusive_address_style",
|
||||
"owner_exclusive_proactive_limit",
|
||||
"relationship_event_window_minutes",
|
||||
"relationship_positive_event_cap",
|
||||
"relationship_negative_event_cap",
|
||||
"relationship_positive_daily_cap",
|
||||
"relationship_decay_grace_days",
|
||||
"relationship_decay_early_per_day",
|
||||
"relationship_decay_middle_per_day",
|
||||
"relationship_decay_late_per_day",
|
||||
"reply_style_prompt",
|
||||
"enable_persona_voice_channels",
|
||||
"persona_conversation_voice_prompt",
|
||||
|
|
@ -16041,6 +16163,24 @@ class PrivateCompanionPageApi(PrivateCompanionPageApiQzoneMixin, PrivateCompanio
|
|||
return "friend"
|
||||
if key == "default_relationship_score":
|
||||
return self._int(value, 0, -1200, 1200)
|
||||
if key == "default_interaction_band":
|
||||
text = self._single_line(value, 24).lower()
|
||||
return text if text in {"avoidant", "hurt", "relaxed", "lively", "warm"} else "relaxed"
|
||||
if key == "owner_exclusive_proactive_limit":
|
||||
return self._int(value, 6, 0, 30)
|
||||
relationship_integer_settings = {
|
||||
"relationship_event_window_minutes": (30, 1, 1440),
|
||||
"relationship_positive_event_cap": (4, 1, 30),
|
||||
"relationship_negative_event_cap": (12, 1, 60),
|
||||
"relationship_positive_daily_cap": (12, 0, 120),
|
||||
"relationship_decay_grace_days": (3, 0, 30),
|
||||
"relationship_decay_early_per_day": (2, 0, 30),
|
||||
"relationship_decay_middle_per_day": (5, 0, 30),
|
||||
"relationship_decay_late_per_day": (8, 0, 30),
|
||||
}
|
||||
if key in relationship_integer_settings:
|
||||
default, minimum, maximum = relationship_integer_settings[key]
|
||||
return self._int(value, default, minimum, maximum)
|
||||
if key == "default_proactive_daily_limit":
|
||||
return self._int(value, 0, 0, 30)
|
||||
expression_modes = {
|
||||
|
|
@ -17435,15 +17575,38 @@ class PrivateCompanionPageApi(PrivateCompanionPageApiQzoneMixin, PrivateCompanio
|
|||
pending_observation_total = self._int(data.get("worldbook_pending_observation_total")) if "worldbook_pending_observation_total" in data else 0
|
||||
group_count = self._int(data.get("worldbook_group_profile_count")) if "worldbook_group_profile_count" in data else 0
|
||||
entry_count = self._int(data.get("worldbook_entry_count")) if "worldbook_entry_count" in data else len(entries)
|
||||
projection_stats = data.get("group_observation_profile_projection_stats") if isinstance(data.get("group_observation_profile_projection_stats"), dict) else {}
|
||||
projection_counts_raw = projection_stats.get("counts") if isinstance(projection_stats.get("counts"), dict) else {}
|
||||
projection_codes = (
|
||||
"created",
|
||||
"updated",
|
||||
"failed",
|
||||
"skipped_empty_message",
|
||||
"skipped_group_not_allowed",
|
||||
"skipped_member_profiles_disabled",
|
||||
"skipped_missing_sender",
|
||||
"skipped_profile_handler_unavailable",
|
||||
"skipped_invalid_identity",
|
||||
"skipped_existing_authoritative_profile",
|
||||
)
|
||||
projection_counts = {
|
||||
code: self._clamp_int(projection_counts_raw.get(code), 0, 0, 999999)
|
||||
for code in projection_codes
|
||||
if self._clamp_int(projection_counts_raw.get(code), 0, 0, 999999)
|
||||
}
|
||||
last_projection_code = self._single_line(projection_stats.get("last_result_code"), 48)
|
||||
if last_projection_code not in projection_codes:
|
||||
last_projection_code = ""
|
||||
profile_items = []
|
||||
for user_id, item in profiles.items():
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
observation_only = bool(item.get("observation_only", False))
|
||||
aliases = item.get("aliases") if isinstance(item.get("aliases"), list) else []
|
||||
observed = item.get("observed_names") if isinstance(item.get("observed_names"), list) else []
|
||||
external_ids = item.get("external_ids") if isinstance(item.get("external_ids"), list) else []
|
||||
memories = self._normalize_important_memories(item.get("important_memories"))
|
||||
pending = item.get("pending_observations") if isinstance(item.get("pending_observations"), list) else []
|
||||
memories = [] if observation_only else self._normalize_important_memories(item.get("important_memories"))
|
||||
pending = [] if observation_only else (item.get("pending_observations") if isinstance(item.get("pending_observations"), list) else [])
|
||||
pending_items = []
|
||||
for raw in pending[:8]:
|
||||
if not isinstance(raw, dict):
|
||||
|
|
@ -17475,7 +17638,7 @@ class PrivateCompanionPageApi(PrivateCompanionPageApiQzoneMixin, PrivateCompanio
|
|||
"linked_bili_profile_id": self._single_line(item.get("linked_bili_profile_id"), 80),
|
||||
"auto_registration_pending": bool(item.get("auto_registration_pending", False)),
|
||||
"profile_origin": self._single_line(item.get("profile_origin"), 40),
|
||||
"observation_only": bool(item.get("observation_only", False)),
|
||||
"observation_only": observation_only,
|
||||
"proactive_contact_enabled": bool(item.get("proactive_contact_enabled", False)),
|
||||
"relationship_state": self._single_line(item.get("relationship_state"), 24) or "neutral",
|
||||
"affinity_score": self._int(item.get("affinity_score")),
|
||||
|
|
@ -17494,6 +17657,8 @@ class PrivateCompanionPageApi(PrivateCompanionPageApiQzoneMixin, PrivateCompanio
|
|||
"note": self._single_line(item.get("note"), 500),
|
||||
}
|
||||
)
|
||||
if observation_only:
|
||||
profile_items[-1]["proactive_contact_enabled"] = False
|
||||
profile_items.sort(key=lambda item: (not item.get("enabled", True), item.get("name") or item.get("user_id")))
|
||||
if "worldbook_member_profile_count" not in data:
|
||||
member_count = len(profile_items)
|
||||
|
|
@ -17529,6 +17694,12 @@ class PrivateCompanionPageApi(PrivateCompanionPageApiQzoneMixin, PrivateCompanio
|
|||
"enabled_member_count": enabled_member_count,
|
||||
"pending_observation_total": pending_observation_total,
|
||||
"group_count": group_count,
|
||||
"group_observation_projection": {
|
||||
"last_result_code": last_projection_code,
|
||||
"last_result_at": self.plugin._format_timestamp_elapsed(projection_stats.get("last_result_at", 0)),
|
||||
"counts": projection_counts,
|
||||
"total": sum(projection_counts.values()),
|
||||
},
|
||||
"last_import": self.plugin._format_timestamp_elapsed(state.get("last_import_at", 0)),
|
||||
"source_files": state.get("source_files") if isinstance(state.get("source_files"), list) else [],
|
||||
"members": profile_items[:120],
|
||||
|
|
|
|||
|
|
@ -10,7 +10,9 @@ from typing import Any
|
|||
from astrbot.api import logger
|
||||
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
|
||||
|
||||
|
||||
class PrivateCompanionPageApiUsersGroupsMixin:
|
||||
|
|
@ -29,6 +31,119 @@ class PrivateCompanionPageApiUsersGroupsMixin:
|
|||
raise ValueError("relationship_score must be between -1200 and 1200")
|
||||
return score
|
||||
|
||||
def _observation_profile_by_user_id_locked(
|
||||
self,
|
||||
data: dict[str, Any],
|
||||
user_id: str,
|
||||
) -> tuple[str, dict[str, Any]] | None:
|
||||
"""Resolve only an exact observation-only identity while the data lock is held."""
|
||||
identity = self._single_line(user_id, 40)
|
||||
if not identity:
|
||||
return None
|
||||
finder = getattr(self.plugin, "_worldbook_group_observation_profile_by_identity", None)
|
||||
if callable(finder):
|
||||
candidate = finder(identity)
|
||||
if (
|
||||
isinstance(candidate, tuple)
|
||||
and len(candidate) == 2
|
||||
and isinstance(candidate[0], str)
|
||||
and isinstance(candidate[1], dict)
|
||||
and bool(candidate[1].get("observation_only"))
|
||||
):
|
||||
return candidate[0], candidate[1]
|
||||
profiles = data.get("worldbook_member_profiles") if isinstance(data.get("worldbook_member_profiles"), dict) else {}
|
||||
profile = profiles.get(identity)
|
||||
if isinstance(profile, dict) and bool(profile.get("observation_only")):
|
||||
return identity, profile
|
||||
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."""
|
||||
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 {
|
||||
"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,
|
||||
"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",
|
||||
}
|
||||
|
||||
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)
|
||||
detail.update(
|
||||
{
|
||||
"relationship_panel": {
|
||||
"observation_only": True,
|
||||
"message": "群聊观察档案不进入私聊亲密度、主动联系或安全权限链路。",
|
||||
},
|
||||
"memory": {},
|
||||
"expression_profile": {},
|
||||
"intent_profile": {},
|
||||
"behavior_habits": {"items": []},
|
||||
"dialogue_episodes": [],
|
||||
"open_loops": [],
|
||||
"recent_reply_topics": [],
|
||||
"last_user_message": "",
|
||||
"last_companion_message": "",
|
||||
"delivery_route": {"available": False, "reason": "observation_only"},
|
||||
"worldbook_member": member_summary,
|
||||
"p4_runtime": {"available": False, "reason": "observation_only"},
|
||||
"formatted": {
|
||||
"relationship": "仅观察:中性,不进入私聊关系链路",
|
||||
"action_affinity": "不主动触达",
|
||||
"next_proactive": "不适用",
|
||||
},
|
||||
}
|
||||
)
|
||||
return detail
|
||||
|
||||
async def list_users(self) -> dict[str, Any]:
|
||||
start = time.perf_counter()
|
||||
try:
|
||||
|
|
@ -38,12 +153,49 @@ class PrivateCompanionPageApiUsersGroupsMixin:
|
|||
if not isinstance(users, dict):
|
||||
users = {}
|
||||
user_items = [(user_id, dict(user)) for user_id, user in users.items() if isinstance(user, dict)]
|
||||
profiles = self.plugin.data.get("worldbook_member_profiles", {})
|
||||
observation_items = [
|
||||
(str(profile_id), deepcopy(profile))
|
||||
for profile_id, profile in profiles.items()
|
||||
if isinstance(profile, dict) and bool(profile.get("observation_only"))
|
||||
] if isinstance(profiles, dict) else []
|
||||
items = [self._user_summary(user_id, user) for user_id, user in user_items]
|
||||
for item in items:
|
||||
item.setdefault("profile_kind", "private")
|
||||
item.setdefault("profile_source", "private_chat")
|
||||
item.setdefault("profile_source_label", "私聊用户")
|
||||
item.setdefault("observation_only", False)
|
||||
private_ids = {self._single_line(user_id, 40) for user_id, _ in user_items if self._single_line(user_id, 40)}
|
||||
for profile_id, profile in observation_items:
|
||||
identity = self._single_line(profile.get("user_id") or profile_id, 40)
|
||||
# A real private user always wins the display slot. The
|
||||
# observation profile remains a separate, non-authoritative
|
||||
# source until an explicit future merge consumes it.
|
||||
if not identity or identity in private_ids:
|
||||
continue
|
||||
items.append(self._observation_user_summary(profile_id, profile))
|
||||
items.sort(key=lambda item: item.get("last_seen_ts") or 0, reverse=True)
|
||||
elapsed_ms = int((time.perf_counter() - start) * 1000)
|
||||
if elapsed_ms > 1200:
|
||||
logger.warning("[PrivateCompanionPage] 用户列表接口耗时较高: elapsed=%sms users=%s", elapsed_ms, len(items))
|
||||
return self._ok({"items": items[:limit], "total": 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")),
|
||||
}
|
||||
platform_counts: dict[str, int] = {}
|
||||
for item in items:
|
||||
platform = self._single_line(item.get("platform_group"), 32) or "web_other"
|
||||
platform_counts[platform] = platform_counts.get(platform, 0) + 1
|
||||
return self._ok(
|
||||
{
|
||||
"items": items[:limit],
|
||||
"total": len(items),
|
||||
"private_total": source_counts["private_chat"],
|
||||
"observation_total": source_counts["group_observation"],
|
||||
"source_counts": source_counts,
|
||||
"platform_counts": platform_counts,
|
||||
}
|
||||
)
|
||||
except Exception as exc:
|
||||
logger.error(f"[PrivateCompanionPage] 获取用户列表失败: {exc}", exc_info=True)
|
||||
return self._error(str(exc))
|
||||
|
|
@ -54,7 +206,13 @@ class PrivateCompanionPageApiUsersGroupsMixin:
|
|||
try:
|
||||
async with self.plugin._data_lock:
|
||||
user = deepcopy((self.plugin.data.get("users") or {}).get(user_id))
|
||||
observation = None
|
||||
if not isinstance(user, dict):
|
||||
observation = self._observation_profile_by_user_id_locked(self.plugin.data, user_id)
|
||||
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)))
|
||||
if not isinstance(user, dict):
|
||||
return self._error("用户不存在")
|
||||
detail = self._user_summary(user_id, user)
|
||||
|
|
@ -64,6 +222,8 @@ class PrivateCompanionPageApiUsersGroupsMixin:
|
|||
relationship_stage=str(detail.get("relationship_stage") or ""),
|
||||
worldbook_member=worldbook_member,
|
||||
)
|
||||
detail["current_interaction"] = detail["relationship_panel"]["current_interaction"]
|
||||
detail["expression_decision"] = detail["relationship_panel"]["expression_decision"]
|
||||
detail["p4_runtime"] = self._p4_page_status_projection()
|
||||
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 {}
|
||||
|
|
@ -72,7 +232,7 @@ class PrivateCompanionPageApiUsersGroupsMixin:
|
|||
"memory": user.get("companion_memory") if isinstance(user.get("companion_memory"), dict) else {},
|
||||
"expression_profile": self._expression_profile_summary(user),
|
||||
"intent_profile": user.get("intent_profile") if isinstance(user.get("intent_profile"), dict) else {},
|
||||
"relationship_state": user.get("relationship_state") if isinstance(user.get("relationship_state"), dict) else {},
|
||||
"relationship_state": detail.get("relationship_state") if isinstance(detail.get("relationship_state"), dict) else {},
|
||||
"behavior_habits": self._behavior_habit_summary(user),
|
||||
"dialogue_episodes": self._limited_list(user.get("dialogue_episodes"), 12),
|
||||
"open_loops": self._limited_list(user.get("open_loops"), 12),
|
||||
|
|
@ -106,11 +266,54 @@ class PrivateCompanionPageApiUsersGroupsMixin:
|
|||
relationship_score = self._relationship_score_input(payload.get(intimacy_keys[0]))
|
||||
except ValueError as exc:
|
||||
return self._error(str(exc))
|
||||
requested_mode = str(payload.get("relationship_mode") or "").strip().lower() if "relationship_mode" in payload else None
|
||||
if requested_mode is not None and requested_mode not in {"normal", "owner_exclusive"}:
|
||||
return self._error("relationship_mode must be normal or owner_exclusive")
|
||||
requested_interaction_band = (
|
||||
str(payload.get("current_interaction_band") or "").strip().lower()
|
||||
if "current_interaction_band" in payload
|
||||
else None
|
||||
)
|
||||
interaction_expires_at = 0.0
|
||||
if "current_interaction_expires_at" in payload:
|
||||
raw_expiry = payload.get("current_interaction_expires_at")
|
||||
if isinstance(raw_expiry, bool) or not isinstance(raw_expiry, (int, float)):
|
||||
return self._error("current_interaction_expires_at must be a timestamp")
|
||||
interaction_expires_at = float(raw_expiry)
|
||||
if interaction_expires_at < 0 or interaction_expires_at > time.time() + 366 * 86400:
|
||||
return self._error("current_interaction_expires_at is outside the allowed range")
|
||||
try:
|
||||
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("仅观察档案不能通过私聊用户接口修改")
|
||||
user = self.plugin._get_user(user_id)
|
||||
expression_voice_needs_refresh = False
|
||||
previous_role = self.plugin._private_user_role(user, user_id)
|
||||
previous_mode = normalize_relationship_mode(user.get("relationship_mode"), previous_role)
|
||||
role = previous_role
|
||||
if "relationship_role" in payload:
|
||||
normalized_role = self.plugin._normalize_private_user_role(payload.get("relationship_role"))
|
||||
if not normalized_role:
|
||||
return self._error("relationship_role must be owner or friend")
|
||||
role = normalized_role
|
||||
next_mode = normalize_relationship_mode(requested_mode if requested_mode is not None else previous_mode, role)
|
||||
if requested_mode == "owner_exclusive" and role != "owner":
|
||||
return self._error("owner_exclusive relationship requires an owner user")
|
||||
if previous_mode == "owner_exclusive" and role != "owner" and requested_mode != "normal":
|
||||
return self._error("switch the relationship to a normal stage before changing the owner role")
|
||||
if previous_mode == "owner_exclusive" and requested_mode == "normal" and relationship_score is None:
|
||||
return self._error("leaving owner_exclusive requires selecting a normal relationship stage")
|
||||
if previous_mode == "owner_exclusive" and relationship_score is not None and requested_mode != "normal":
|
||||
return self._error("owner_exclusive relationship score is frozen; select a normal stage first")
|
||||
if next_mode == "owner_exclusive" and relationship_score is not None:
|
||||
return self._error("owner_exclusive relationship does not accept an exact score")
|
||||
if requested_interaction_band is not None:
|
||||
if not requested_interaction_band:
|
||||
return self._error("current_interaction_band is required")
|
||||
if requested_interaction_band not in allowed_expression_bands(role, next_mode):
|
||||
return self._error("current interaction band is not allowed for this relationship")
|
||||
if "enabled" in payload:
|
||||
enabled = bool(payload.get("enabled"))
|
||||
user["enabled"] = enabled
|
||||
|
|
@ -126,13 +329,45 @@ class PrivateCompanionPageApiUsersGroupsMixin:
|
|||
if "style" in payload:
|
||||
user["style"] = self._single_line(payload.get("style"), 24)
|
||||
if "relationship_role" in payload:
|
||||
previous_role = self.plugin._private_user_role(user, user_id)
|
||||
role = self.plugin._normalize_private_user_role(payload.get("relationship_role"))
|
||||
if role:
|
||||
user["relationship_role"] = role
|
||||
expression_voice_needs_refresh = role != previous_role
|
||||
user["relationship_role"] = role
|
||||
expression_voice_needs_refresh = role != previous_role
|
||||
if requested_mode is not None:
|
||||
user["relationship_mode"] = next_mode
|
||||
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
|
||||
record_manual_relationship_change(
|
||||
user,
|
||||
previous_score,
|
||||
relationship_score,
|
||||
now=time.time(),
|
||||
reason_code="administrator_manual_relationship_adjustment",
|
||||
)
|
||||
if requested_interaction_band is not None:
|
||||
changed_at = time.time()
|
||||
user["current_interaction"] = current_interaction_projection(
|
||||
{
|
||||
"expression_band": requested_interaction_band,
|
||||
"source": "manual",
|
||||
"operator": "page_administrator",
|
||||
"reason": self._single_line(payload.get("current_interaction_reason"), 120) or "administrator_manual_override",
|
||||
"updated_at": changed_at,
|
||||
"expires_at": interaction_expires_at,
|
||||
"manual_override": True,
|
||||
},
|
||||
relationship_role=role,
|
||||
relationship_mode=next_mode,
|
||||
now=changed_at,
|
||||
)
|
||||
expression_voice_needs_refresh = True
|
||||
elif role != previous_role or next_mode != previous_mode:
|
||||
user["current_interaction"] = current_interaction_projection(
|
||||
user.get("current_interaction"),
|
||||
relationship_role=role,
|
||||
relationship_mode=next_mode,
|
||||
now=time.time(),
|
||||
)
|
||||
if "proactive_daily_limit" in payload:
|
||||
user["proactive_daily_limit"] = _safe_int(payload.get("proactive_daily_limit"), -1, -1, 30)
|
||||
for key in (
|
||||
|
|
@ -171,7 +406,12 @@ class PrivateCompanionPageApiUsersGroupsMixin:
|
|||
self.plugin._clear_pending_proactive_plan(user)
|
||||
if payload.get("clear_emotion_state"):
|
||||
user["intent_profile"] = {}
|
||||
user["relationship_state"] = {}
|
||||
user.pop("relationship_state", None)
|
||||
user["current_interaction"] = current_interaction_projection(
|
||||
None,
|
||||
relationship_role=user.get("relationship_role"),
|
||||
relationship_mode=user.get("relationship_mode"),
|
||||
)
|
||||
if payload.get("clear_behavior_habits"):
|
||||
user["behavior_habits"] = {}
|
||||
if payload.get("clear_learning"):
|
||||
|
|
@ -179,13 +419,13 @@ class PrivateCompanionPageApiUsersGroupsMixin:
|
|||
("companion_memory", {}),
|
||||
("expression_profile", {}),
|
||||
("intent_profile", {}),
|
||||
("relationship_state", {}),
|
||||
("recent_reply_topics", []),
|
||||
("dialogue_episodes", []),
|
||||
("open_loops", []),
|
||||
("action_preferences", {}),
|
||||
):
|
||||
user[key] = empty
|
||||
user.pop("relationship_state", None)
|
||||
user["episode_message_count"] = 0
|
||||
user["last_episode_refresh_at"] = 0
|
||||
user["last_memory_refresh_at"] = 0
|
||||
|
|
@ -230,6 +470,8 @@ class PrivateCompanionPageApiUsersGroupsMixin:
|
|||
if not isinstance(users, dict):
|
||||
users = {}
|
||||
self.plugin.data["users"] = users
|
||||
if not isinstance(users.get(user_id), dict) and self._observation_profile_by_user_id_locked(self.plugin.data, user_id):
|
||||
return self._error("仅观察档案不能通过私聊用户接口删除")
|
||||
canonical_user_id = self.plugin._canonical_private_user_id(user_id)
|
||||
stored_user_id = canonical_user_id if canonical_user_id in users else user_id
|
||||
removed_ids = {user_id, canonical_user_id, stored_user_id}
|
||||
|
|
|
|||
|
|
@ -2142,6 +2142,22 @@ input[type="search"] {
|
|||
font-size: 12px;
|
||||
}
|
||||
|
||||
.companion-intimacy-advanced {
|
||||
border-top: 1px dashed color-mix(in srgb, var(--line) 82%, transparent);
|
||||
padding-top: 9px;
|
||||
}
|
||||
|
||||
.companion-intimacy-advanced summary {
|
||||
color: var(--muted);
|
||||
cursor: pointer;
|
||||
font-size: 12px;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.companion-intimacy-advanced .companion-intimacy-form {
|
||||
margin-top: 10px;
|
||||
}
|
||||
|
||||
.companion-intimacy-head p {
|
||||
margin: 5px 0 0;
|
||||
color: var(--muted);
|
||||
|
|
@ -2166,7 +2182,7 @@ input[type="search"] {
|
|||
|
||||
.relationship-stage-bar {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(8, minmax(72px, 1fr));
|
||||
grid-template-columns: repeat(9, minmax(72px, 1fr));
|
||||
gap: 5px;
|
||||
overflow-x: auto;
|
||||
padding: 18px 1px 7px;
|
||||
|
|
@ -2199,6 +2215,10 @@ input[type="search"] {
|
|||
box-shadow: 0 0 0 3px color-mix(in srgb, var(--accent) 16%, transparent);
|
||||
}
|
||||
|
||||
.relationship-stage-segment.is-disabled {
|
||||
opacity: 0.42;
|
||||
}
|
||||
|
||||
.relationship-stage-segment b {
|
||||
position: absolute;
|
||||
top: -17px;
|
||||
|
|
@ -2211,6 +2231,90 @@ input[type="search"] {
|
|||
font-size: 10px;
|
||||
}
|
||||
|
||||
.current-interaction-card {
|
||||
display: grid;
|
||||
gap: 10px;
|
||||
border-top: 1px solid color-mix(in srgb, var(--accent) 20%, var(--line));
|
||||
padding-top: 13px;
|
||||
}
|
||||
|
||||
.current-interaction-head {
|
||||
display: flex;
|
||||
align-items: start;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.current-interaction-head h3 {
|
||||
margin: 2px 0 0;
|
||||
}
|
||||
|
||||
.current-interaction-head p {
|
||||
margin: 5px 0 0;
|
||||
color: var(--muted);
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.current-interaction-head > strong {
|
||||
color: var(--accent-strong);
|
||||
font-size: 18px;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.interaction-stage-bar {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(7, minmax(0, 1fr));
|
||||
gap: 5px;
|
||||
padding: 6px 1px;
|
||||
}
|
||||
|
||||
.interaction-stage-segment {
|
||||
display: grid;
|
||||
gap: 5px;
|
||||
min-width: 0;
|
||||
color: var(--muted);
|
||||
font-size: 11px;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.interaction-stage-segment i {
|
||||
display: block;
|
||||
height: 7px;
|
||||
border-radius: 999px;
|
||||
background: color-mix(in srgb, var(--line) 84%, white 16%);
|
||||
}
|
||||
|
||||
.interaction-stage-segment.is-current {
|
||||
color: var(--accent-strong);
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.interaction-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);
|
||||
}
|
||||
|
||||
.interaction-stage-segment.is-disabled {
|
||||
color: color-mix(in srgb, var(--muted) 56%, transparent);
|
||||
}
|
||||
|
||||
.interaction-stage-segment.is-disabled i {
|
||||
background: color-mix(in srgb, var(--line) 55%, transparent);
|
||||
}
|
||||
|
||||
.current-interaction-meta {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 5px 12px;
|
||||
color: var(--text-muted);
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.current-interaction-meta span {
|
||||
min-width: 0;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.companion-intimacy-meta {
|
||||
flex-wrap: wrap;
|
||||
justify-content: flex-start;
|
||||
|
|
@ -26940,3 +27044,60 @@ pre {
|
|||
animation: none !important;
|
||||
}
|
||||
}
|
||||
.observation-profile-card {
|
||||
display: grid;
|
||||
gap: 18px;
|
||||
}
|
||||
|
||||
.observation-profile-card > header {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
justify-content: space-between;
|
||||
gap: 18px;
|
||||
padding: 20px;
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 18px;
|
||||
background: linear-gradient(135deg, color-mix(in srgb, var(--panel) 92%, var(--accent) 8%), var(--panel));
|
||||
}
|
||||
|
||||
.observation-profile-card > header h2,
|
||||
.observation-profile-card > header p {
|
||||
margin: 4px 0 0;
|
||||
}
|
||||
|
||||
.observation-boundary-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(4, minmax(0, 1fr));
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.observation-boundary-grid section {
|
||||
display: grid;
|
||||
gap: 6px;
|
||||
min-height: 112px;
|
||||
padding: 16px;
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 16px;
|
||||
background: var(--panel);
|
||||
}
|
||||
|
||||
.observation-boundary-grid span,
|
||||
.observation-boundary-grid small {
|
||||
color: var(--muted);
|
||||
}
|
||||
|
||||
@media (max-width: 980px) {
|
||||
.observation-boundary-grid {
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 620px) {
|
||||
.observation-profile-card > header {
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.observation-boundary-grid {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -165,6 +165,7 @@ const hiddenCompatibilityConfigKeys = new Set([
|
|||
"skill_growth_passive_injection",
|
||||
"skill_growth_custom_skills",
|
||||
"auto_voice_full_conversion_enabled",
|
||||
"enable_relationship_analysis",
|
||||
]);
|
||||
|
||||
const featureSwitchNotes = {
|
||||
|
|
@ -886,7 +887,7 @@ const providerGuides = {
|
|||
EMOTION_JUDGEMENT_PROVIDER_ID: {
|
||||
preference: "speed",
|
||||
passiveImpact: "async",
|
||||
purpose: "可选复核用户消息是否会触发 Bot 自身短期情绪余波,只做分类判断,不生成回复。",
|
||||
purpose: "可选复核用户消息是否应改变统一互动状态,只做分类判断,不生成回复。",
|
||||
fit: "适合便宜、低延迟、JSON 稳定、对玩笑/反讽/第三方抱怨判断保守的小模型。",
|
||||
fallback: "留空时先跟随排障检查模型,再回退到关系站位、陪伴通用和主模型。",
|
||||
},
|
||||
|
|
@ -1029,8 +1030,8 @@ const featureMeta = {
|
|||
enable_smart_silence: ["智能沉默", "私聊和群聊发送前判断是否应该收住话题;可只看明确边界,也可交给小模型结合上下文判断。"],
|
||||
enable_passive_topic_suppression: ["话题抑制", "避免短时间反复主动提同一个话题。"],
|
||||
enable_relationship_analysis: ["模型关系站位分析", "阶段性用完整人格和互动数据复核亲近程度与打扰偏好;可独立关闭模型调用。"],
|
||||
enable_relationship_state_machine: ["关系距离感", "根据亲近、冷淡、边界和回应情况调整相处分寸。"],
|
||||
enable_emotion_simulation: ["情绪模拟", "维护 Bot 自身被刺到、缓和、恢复和短暂回避的余波。"],
|
||||
enable_relationship_state_machine: ["联系边界与互动状态", "把明确退开、重新靠近和未回应反馈收口到统一互动状态与主动边界。"],
|
||||
enable_emotion_simulation: ["情绪事件参与互动状态", "让受伤、道歉、安抚、夸奖等事件只调整统一七档互动状态,不再维护第二套情绪分值。"],
|
||||
enable_dialogue_episode_memory: ["私聊片段", "把连续对话整理成共同经历和可续话头。"],
|
||||
enable_open_loop_tracking: ["未完话头", "记住对话里还留着、之后可能会回头接的事。"],
|
||||
enable_user_habit_learning: ["用户习惯画像", "学习用户常在什么时段做什么、问什么;被动只在相关时理解,主动可到点关心。"],
|
||||
|
|
@ -1180,7 +1181,6 @@ const featureGroups = [
|
|||
"enable_intent_emotion_analysis",
|
||||
"enable_proactive_message_review",
|
||||
"enable_passive_topic_suppression",
|
||||
"enable_relationship_analysis",
|
||||
"enable_relationship_state_machine",
|
||||
"enable_dialogue_episode_memory",
|
||||
"enable_open_loop_tracking",
|
||||
|
|
@ -1435,7 +1435,6 @@ const safeFeatureKeys = [
|
|||
"enable_passive_response_review",
|
||||
"enable_framework_error_leak_guard",
|
||||
"enable_group_privacy_guard",
|
||||
"enable_relationship_analysis",
|
||||
"enable_relationship_state_machine",
|
||||
"enable_dialogue_episode_memory",
|
||||
"enable_open_loop_tracking",
|
||||
|
|
@ -1458,9 +1457,22 @@ const configLabels = {
|
|||
default_nickname: "默认称呼",
|
||||
default_relationship_role: "默认关系角色",
|
||||
default_relationship_score: "默认亲密度",
|
||||
default_interaction_band: "默认互动状态",
|
||||
default_proactive_enabled: "允许新用户主动关心",
|
||||
default_proactive_daily_limit: "新用户每日主动上限",
|
||||
relationship_stage_policy: "八阶段策略",
|
||||
owner_exclusive_label: "管理员专属关系名称",
|
||||
owner_exclusive_tone: "管理员专属基础表达",
|
||||
owner_exclusive_address_style: "管理员专属称呼尺度",
|
||||
owner_exclusive_proactive_limit: "管理员专属主动阶段上限",
|
||||
relationship_event_window_minutes: "同类事件合并窗口(分钟)",
|
||||
relationship_positive_event_cap: "单次正向事件上限",
|
||||
relationship_negative_event_cap: "单次负向事件上限",
|
||||
relationship_positive_daily_cap: "每日正向增长上限",
|
||||
relationship_decay_grace_days: "自然回落宽限期(天)",
|
||||
relationship_decay_early_per_day: "早期每日回落值",
|
||||
relationship_decay_middle_per_day: "中期每日回落值",
|
||||
relationship_decay_late_per_day: "后期每日回落值",
|
||||
default_style: "默认语气",
|
||||
reply_style_prompt: "回复风格提示词",
|
||||
enable_persona_voice_channels: "启用分通道人格风格",
|
||||
|
|
@ -1503,12 +1515,13 @@ const configLabels = {
|
|||
tts_conversion_provider_id: "TTS文本转换模型",
|
||||
tts_extra_prompt: "TTS补充规则",
|
||||
EMOTION_JUDGEMENT_PROVIDER_ID: "情绪变化判断模型",
|
||||
enable_llm_emotion_judgement: "模型复核情绪变化",
|
||||
emotion_judgement_mode: "情绪复核范围",
|
||||
emotional_gate_hurt_threshold: "伤心触发阈值",
|
||||
emotional_gate_refuse_threshold: "生气触发阈值",
|
||||
emotional_gate_recovery_per_hour: "每小时缓和量",
|
||||
emotional_gate_max_hurt_minutes: "最长收敛分钟",
|
||||
enable_emotion_simulation: "让情绪事件自动调整互动状态",
|
||||
enable_llm_emotion_judgement: "模型复核互动状态事件",
|
||||
emotion_judgement_mode: "事件复核范围",
|
||||
emotional_gate_hurt_threshold: "进入受伤档位阈值",
|
||||
emotional_gate_refuse_threshold: "进入回避档位阈值",
|
||||
emotional_gate_recovery_per_hour: "每小时恢复量",
|
||||
emotional_gate_max_hurt_minutes: "受伤/回避最长分钟",
|
||||
enable_qzone_emotional_vent_publish: "公开心情动态",
|
||||
qzone_emotional_vent_threshold: "心情动态触发阈值",
|
||||
qzone_emotional_vent_cooldown_hours: "心情动态冷却小时",
|
||||
|
|
@ -2007,9 +2020,22 @@ const configDescriptions = {
|
|||
default_style: "新用户基础语气。单用户设置和当前亲密度阶段策略优先于此默认值。",
|
||||
default_relationship_role: "自动档案固定为普通用户 / 朋友,不允许由默认配置成为主要用户。",
|
||||
default_relationship_score: "只影响之后自动创建的档案,不重写既有用户,范围 -1200 到 1200。",
|
||||
default_interaction_band: "普通新用户可选择回避、受伤、放松、活泼或温暖;亲近和爱意不会自动授予。",
|
||||
default_proactive_enabled: "默认关闭。只有自动启用陪伴时才可能允许主动关心。",
|
||||
default_proactive_daily_limit: "新用户每天最多主动关心次数;未自动启用陪伴时强制为 0。",
|
||||
relationship_stage_policy: "固定八阶段键与阈值,只编辑显示、语气、称呼尺度和软行为,不能授予权限或绕过 P4。",
|
||||
owner_exclusive_label: "只修改 owner 专属关系的显示名称,不增加管理或安全权限。",
|
||||
owner_exclusive_tone: "专属关系的长期表达基线;当前互动状态仍可使本轮收敛。",
|
||||
owner_exclusive_address_style: "优先沿用双方已确认的专属称呼。",
|
||||
owner_exclusive_proactive_limit: "阶段硬上限,实际次数仍取全局、用户、阶段和动态额度的最小值。",
|
||||
relationship_event_window_minutes: "同一用户的同类互动在该时间内只按一个关系事件结算,避免连续短消息重复刷分。",
|
||||
relationship_positive_event_cap: "单个正向事件最多增加的长期亲密度;最终仍受每日正向增长上限约束。",
|
||||
relationship_negative_event_cap: "单个负向事件最多降低的长期亲密度;负向事件不受正向每日上限抵消。",
|
||||
relationship_positive_daily_cap: "每个用户每天由自动互动累计增加的长期亲密度上限;管理员手动调整不占用该额度。",
|
||||
relationship_decay_grace_days: "用户停止互动后先保留的天数;宽限期结束才开始自然回落,owner 专属关系不会回落。",
|
||||
relationship_decay_early_per_day: "超过宽限期后的第一段每日回落值,用于温和提醒关系需要持续互动。",
|
||||
relationship_decay_middle_per_day: "长期未互动进入中段后每日回落值;只让正分向 0 靠近,不制造负分。",
|
||||
relationship_decay_late_per_day: "更长时间未互动后的每日回落值;只让正分向 0 靠近,不突破安全和关系边界。",
|
||||
enable_proactive_only_mode: "开启后,本插件只保留主动私聊的日程、主动生成和发送链路;普通私聊、群聊消息不会再被本插件做状态/TTS/图片/转发/群聊上下文注入,也不会触发本插件的被动回复增强,但不会阻止 AstrBot 默认回复或其他插件处理。用户回复主动消息时仍会被轻量记为已回应。适合只想使用主动陪伴、或担心本插件被动链路误接管/误识别的场景。",
|
||||
enable_llm_proactive_message: "开启后,主动调度只负责挑选动机和时机,真正文本会调用 AstrBot 人格生成;关闭时回退为本地模板,更省但更机械。",
|
||||
enable_proactive_chat_integration: "检测到 Proactive Chat 时自动建立深度运行时联动:生成前检查两套调度是否撞车,并注入当前关系、状态、时机和已审核表达;生成后统一复核;平台发送无异常返回后才结算成功。不会修改对方插件文件或配置,也不会新建第二套定时任务。版本不兼容时自动降级为发送前装饰联动。",
|
||||
|
|
@ -2488,13 +2514,14 @@ const configDescriptions = {
|
|||
proactive_review_low_score_threshold: "标准/严格强度下,候选价值分低于该值且压力较高时会延后。值越低越少延后,按百分比填写。",
|
||||
proactive_review_pressure_threshold: "标准/严格强度下,打扰压力达到该值且候选分偏低时会延后。值越高越少延后,按百分比填写。",
|
||||
response_review_max_chars: "用于判断普通被动回复是否偏长。默认模式会处理短闲聊被扩写成建议清单、天气小作文的情况;full 模式会更积极复核普通偏长回复。",
|
||||
emotional_gate_hurt_threshold: "用户消息明确刺到 Bot、并达到该阈值后才会短期变安静;轻度玩笑和普通边界不会直接触发。",
|
||||
emotional_gate_refuse_threshold: "累计刺痛感达到该阈值后才会明显不满或短暂回避;建议保持较高。",
|
||||
emotional_gate_recovery_per_hour: "情绪余波每小时自然缓和多少分;数值越高越不容易长时间低落。",
|
||||
emotional_gate_max_hurt_minutes: "单次刺痛事件最长收敛/暂停主动的分钟数;道歉或安抚可以提前恢复。",
|
||||
enable_llm_emotion_judgement: "可选使用模型异步复核用户消息是否会改变 Bot 自身短期情绪余波;本轮被动回复仍使用缓存状态。",
|
||||
emotion_judgement_mode: "模型复核范围:可疑项更省消耗,总是复核更细但更耗;结果主要影响后续轮次。",
|
||||
EMOTION_JUDGEMENT_PROVIDER_ID: "用于异步复核用户消息是否会改变 Bot 自身短期情绪余波。建议选择便宜、低延迟、JSON 稳定、分类保守的小模型;留空会先回退到排障检查模型,再回退到关系站位/陪伴通用/主模型。",
|
||||
enable_emotion_simulation: "开启后,受伤、道歉、安抚、夸奖、玩笑和亲近事件会直接结算到统一七档互动状态;不会再写第二套情绪分值或复合情绪状态。",
|
||||
emotional_gate_hurt_threshold: "用户消息明确刺到 Bot、并达到该阈值后才进入统一的“受伤”互动档位;轻度玩笑和普通边界不会直接触发。",
|
||||
emotional_gate_refuse_threshold: "单次明确伤害强度达到该阈值后进入统一的“回避”互动档位;它不是联系边界,也不会自动写入不再联系。",
|
||||
emotional_gate_recovery_per_hour: "用于计算受伤/回避状态的预计持续时间;数值越高,越快回到长期关系基线。",
|
||||
emotional_gate_max_hurt_minutes: "单次伤害事件的互动状态最长持续时间;道歉、安抚或明确重新靠近可以提前恢复。",
|
||||
enable_llm_emotion_judgement: "可选使用模型异步复核用户消息属于哪一种互动事件;结果只进入统一互动状态,不生成另一套关系或情绪权威。",
|
||||
emotion_judgement_mode: "模型复核范围:可疑项更省消耗,总是复核更细但更耗;结果主要影响后续互动状态。",
|
||||
EMOTION_JUDGEMENT_PROVIDER_ID: "用于异步复核用户消息是否应改变统一互动状态。建议选择便宜、低延迟、JSON 稳定、分类保守的小模型;留空会先回退到排障检查模型,再回退到陪伴通用/主模型。",
|
||||
enable_qzone_emotional_vent_publish: "短期余波很重时是否允许低频发布公开心情说说。",
|
||||
qzone_emotional_vent_threshold: "触发公开心情动态所需的短期余波强度。",
|
||||
qzone_emotional_vent_cooldown_hours: "两次公开心情动态之间的最小间隔。",
|
||||
|
|
@ -2564,8 +2591,29 @@ 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_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",
|
||||
"owner_exclusive_label",
|
||||
"owner_exclusive_tone",
|
||||
"owner_exclusive_address_style",
|
||||
"owner_exclusive_proactive_limit",
|
||||
"relationship_event_window_minutes",
|
||||
"relationship_positive_event_cap",
|
||||
"relationship_negative_event_cap",
|
||||
"relationship_positive_daily_cap",
|
||||
"relationship_decay_grace_days",
|
||||
"relationship_decay_early_per_day",
|
||||
"relationship_decay_middle_per_day",
|
||||
"relationship_decay_late_per_day",
|
||||
"enable_emotion_simulation",
|
||||
"enable_llm_emotion_judgement",
|
||||
"emotion_judgement_mode",
|
||||
"EMOTION_JUDGEMENT_PROVIDER_ID",
|
||||
"emotional_gate_hurt_threshold",
|
||||
"emotional_gate_refuse_threshold",
|
||||
"emotional_gate_max_hurt_minutes",
|
||||
],
|
||||
enable_mai_style_integration: [
|
||||
"default_style",
|
||||
"reply_style_prompt",
|
||||
|
|
@ -3161,8 +3209,8 @@ const featureSettingSections = {
|
|||
],
|
||||
enable_emotion_simulation: [
|
||||
{
|
||||
title: "情绪余波",
|
||||
note: "控制被刺到后的收敛、缓和、主动暂停和回复调节策略。",
|
||||
title: "互动状态事件",
|
||||
note: "控制明确伤害进入受伤/回避档位的阈值、恢复速度和主动暂停;不会生成第二套情绪分值。",
|
||||
keys: ["enable_llm_emotion_judgement", "emotion_judgement_mode", "EMOTION_JUDGEMENT_PROVIDER_ID", "emotional_gate_hurt_threshold", "emotional_gate_refuse_threshold", "emotional_gate_recovery_per_hour", "emotional_gate_max_hurt_minutes"],
|
||||
},
|
||||
{
|
||||
|
|
@ -3350,6 +3398,8 @@ const featureSettingTypes = {
|
|||
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_interaction_band: { type: "select", options: [["avoidant", "回避"], ["hurt", "受伤"], ["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 },
|
||||
forward_message_mode: { type: "select", options: [["inject", "注入"], ["transcribe", "转述"]] },
|
||||
|
|
@ -5427,7 +5477,7 @@ const setupGuideAdvancedBlocks = [
|
|||
{
|
||||
id: "experimental",
|
||||
title: "实验性功能",
|
||||
body: "配置情绪余波、需求强化、动机调度和角色贴合校准;人格标准化作为一次性工具入口单独使用。适合先小范围观察,确认拟人化收益大于打扰和成本后再稳定开启。",
|
||||
body: "配置需求强化、动机调度和角色贴合校准;人格标准化作为一次性工具入口单独使用。互动状态事件已经并入亲密度阶段策略详情。",
|
||||
},
|
||||
];
|
||||
|
||||
|
|
@ -5491,7 +5541,7 @@ const setupGuideAdvancedItems = {
|
|||
title: "模型关系站位分析",
|
||||
ask: "是否让模型阶段性复核与用户的亲近程度和打扰偏好?",
|
||||
description: "使用完整人格、互动次数、主动回复率和最近消息,生成陌生/熟悉/亲近及低打扰/普通/可轻分享判断。关闭后不会再产生“关系分析”模型 Token。",
|
||||
caution: "关闭不会停用关系距离感:本地边界识别、未回复降频和互动数据兜底仍然保留,只是不再由模型定期重评。",
|
||||
caution: "该旧模型关系站位功能已停用;长期关系阶段、统一互动状态、本地边界识别和未回复降频不依赖它。",
|
||||
kind: "feature",
|
||||
settings: [],
|
||||
},
|
||||
|
|
@ -5554,21 +5604,6 @@ const setupGuideAdvancedItems = {
|
|||
},
|
||||
],
|
||||
experimental: [
|
||||
{
|
||||
key: "enable_emotion_simulation",
|
||||
title: "情绪余波",
|
||||
ask: "是否让 Bot 保留短期情绪余波,比如被刺到、缓和、恢复和短暂回避?",
|
||||
description: "它能让回复不那么一键清空情绪,也能影响主动消息、空间说说和关系距离判断;迁入实验性功能后仍保留旧默认值。",
|
||||
caution: "这是扮演状态,不是真实心理判断。阈值过低会让 Bot 太容易受伤,建议先温和开启并观察。",
|
||||
kind: "feature",
|
||||
settings: [
|
||||
{ key: "enable_llm_emotion_judgement", type: "bool", label: "使用模型判断情绪变化", description: "比规则更细,但会增加轻量模型调用。" },
|
||||
{ key: "emotion_judgement_mode", type: "select", label: "情绪判断模式", options: [["suspicious", "只判断可疑消息"], ["always", "每条普通文本都判断"], ["off", "关闭模型复核"]] },
|
||||
{ key: "emotional_gate_hurt_threshold", type: "number", label: "受伤阈值", placeholder: "70", min: 10, max: 100, step: 5 },
|
||||
{ key: "emotional_gate_refuse_threshold", type: "number", label: "生气阈值", placeholder: "90", min: 20, max: 100, step: 5 },
|
||||
{ key: "emotional_gate_recovery_per_hour", type: "number", label: "每小时缓和量", placeholder: "24", min: 1, max: 60 },
|
||||
],
|
||||
},
|
||||
{
|
||||
key: "enable_maslow_motivation_experiment",
|
||||
title: "需求强化功能",
|
||||
|
|
@ -12369,11 +12404,11 @@ function renderUsers() {
|
|||
${collapsed ? "" : users.map((user) => `
|
||||
<tr data-user-id="${escapeHtml(user.user_id)}" class="${user.user_id === state.selectedUserId ? "is-selected" : ""}">
|
||||
<td class="user-cell identity"><strong title="${escapeHtml(user.display_name || user.nickname || user.user_id)}">${escapeHtml(user.display_name || user.nickname || user.user_id)}</strong> ${userPlatformBadge(user)}${Array.isArray(user.alias_user_ids) && user.alias_user_ids.length ? ` <span class="badge ok" title="${escapeHtml(user.alias_user_ids.join("\\n"))}">已合并 ${escapeHtml(user.alias_user_ids.length)} 个身份</span>` : ""}<br><span class="user-id-line"><span class="muted mono" title="${escapeHtml(user.user_id)}">${escapeHtml(user.user_id)}</span><button type="button" class="copy-id-btn" data-copy-user-id="${escapeHtml(user.user_id)}">复制</button></span></td>
|
||||
<td class="user-cell relation"><span class="badge ${user.enabled ? "" : "off"}">${escapeHtml(user.enabled ? "启用" : "停用")}</span> <span class="badge">${escapeHtml(user.relationship_role_label || "次要用户")}</span> <span class="muted">${escapeHtml(user.relationship_stage || "未分层")}</span><br><span class="relationship-phase-summary"><b>${escapeHtml(user.relationship_intimacy?.phase?.label || user.relationship_intimacy?.band || "初识")}</b><small>亲密度 ${escapeHtml(user.relationship_intimacy?.value ?? 0)}</small></span></td>
|
||||
<td class="user-cell compact">入站 ${escapeHtml(user.inbound_count)} · 回复 ${escapeHtml(user.reply_count)}<br><span class="muted">记忆 ${escapeHtml(user.memory_items)} 条</span></td>
|
||||
<td class="user-cell proactive"><span>今日 ${escapeHtml(user.sent_today)} · 总计 ${escapeHtml(user.proactive_sent_count)}</span><br><span class="muted truncate" title="${escapeHtml(user.next_proactive || "")}">${escapeHtml(user.next_proactive)}</span></td>
|
||||
<td class="user-cell recent">${escapeHtml(user.last_seen)}<br><span class="muted">上次主动 ${escapeHtml(user.last_sent)}</span></td>
|
||||
<td class="user-cell action"><button type="button" class="table-action ${user.enabled ? "danger-outline" : ""}" data-user-toggle="${escapeHtml(user.user_id)}">${escapeHtml(user.enabled ? "停用" : "启用")}</button></td>
|
||||
<td class="user-cell relation">${user.observation_only ? `<span class="badge off">仅观察</span> <span class="muted">群聊来源</span><br><span class="relationship-phase-summary"><b>中性关系</b><small>不进入亲密度链路</small></span>` : `<span class="badge ${user.enabled ? "" : "off"}">${escapeHtml(user.enabled ? "启用" : "停用")}</span> <span class="badge">${escapeHtml(user.relationship_role_label || "次要用户")}</span> <span class="muted">${escapeHtml(user.relationship_stage || "未分层")}</span><br><span class="relationship-phase-summary"><b>${escapeHtml(user.relationship_intimacy?.phase?.label || user.relationship_intimacy?.band || "初识")}</b><small>亲密度 ${escapeHtml(user.relationship_intimacy?.value ?? 0)}</small></span>`}</td>
|
||||
<td class="user-cell compact">${user.observation_only ? `观察群 ${escapeHtml(user.observed_group_count || 0)} 个<br><span class="muted">无私聊记忆</span>` : `入站 ${escapeHtml(user.inbound_count)} · 回复 ${escapeHtml(user.reply_count)}<br><span class="muted">记忆 ${escapeHtml(user.memory_items)} 条</span>`}</td>
|
||||
<td class="user-cell proactive">${user.observation_only ? `<span>不主动触达</span><br><span class="muted">无投递路线</span>` : `<span>今日 ${escapeHtml(user.sent_today)} · 总计 ${escapeHtml(user.proactive_sent_count)}</span><br><span class="muted truncate" title="${escapeHtml(user.next_proactive || "")}">${escapeHtml(user.next_proactive)}</span>`}</td>
|
||||
<td class="user-cell recent">${escapeHtml(user.last_seen)}<br><span class="muted">${user.observation_only ? "最近群聊观察" : `上次主动 ${escapeHtml(user.last_sent)}`}</span></td>
|
||||
<td class="user-cell action">${user.observation_only ? `<span class="badge off">只读观察</span>` : `<button type="button" class="table-action ${user.enabled ? "danger-outline" : ""}" data-user-toggle="${escapeHtml(user.user_id)}">${escapeHtml(user.enabled ? "停用" : "启用")}</button>`}</td>
|
||||
</tr>
|
||||
`).join("")}`;
|
||||
}).join("");
|
||||
|
|
@ -12427,12 +12462,15 @@ async function renderUserDetail(forceFetch = false) {
|
|||
return;
|
||||
}
|
||||
}
|
||||
if (detail?.observation_only) {
|
||||
box.innerHTML = renderObservationUserDetail(detail);
|
||||
return;
|
||||
}
|
||||
box.innerHTML = `
|
||||
<div class="toolbar">
|
||||
<button data-user-action="toggle">${escapeHtml(detail.enabled ? "停用用户陪伴" : "启用用户陪伴")}</button>
|
||||
<button data-user-action="reset_daily">重置今日额度</button>
|
||||
<button data-user-action="clear_schedule">清空主动计划</button>
|
||||
<button data-user-action="clear_emotion_state">重置情绪状态</button>
|
||||
<button data-user-action="delete" class="danger">删除用户档案</button>
|
||||
</div>
|
||||
<form id="userEditForm" class="inline-form">
|
||||
|
|
@ -12459,7 +12497,6 @@ async function renderUserDetail(forceFetch = false) {
|
|||
${detailBlock("关系和主动", detail.formatted?.relationship || "", [["角色", detail.relationship_role_label || ""], ["有效主动上限", `${detail.effective_daily_limit_text || formatProactiveLimit(detail.effective_daily_limit, detail.effective_daily_limit_unlimited)} / 天`], ["下次主动", detail.formatted?.next_proactive || detail.next_proactive], ["动作偏好", detail.formatted?.action_affinity || ""]])}
|
||||
${renderPrivateDeliveryRoute(detail)}
|
||||
${renderPrivateBehaviorHabits(detail)}
|
||||
${emotionGateBlock(detail)}
|
||||
${renderUserP4RuntimeStatus(detail.p4_runtime)}
|
||||
${userWorldbookBlock(detail.worldbook_member)}
|
||||
${detailBlock("最近对话", "", [["用户消息", detail.last_user_message || ""], ["陪伴回复", detail.last_companion_message || ""]])}
|
||||
|
|
@ -12472,6 +12509,34 @@ async function renderUserDetail(forceFetch = false) {
|
|||
bindUserActions(detail);
|
||||
}
|
||||
|
||||
function renderObservationUserDetail(detail) {
|
||||
const member = detail?.worldbook_member && typeof detail.worldbook_member === "object" ? detail.worldbook_member : {};
|
||||
const observedGroups = Number(detail?.observed_group_count || member.observed_group_count || 0);
|
||||
return `
|
||||
<section class="observation-profile-card" aria-labelledby="observationProfileTitle">
|
||||
<header>
|
||||
<div><span class="relationship-kicker">GROUP OBSERVATION</span><h2 id="observationProfileTitle">${escapeHtml(detail.display_name || detail.nickname || detail.user_id)}</h2><p class="mono">${escapeHtml(detail.user_id || "")}</p></div>
|
||||
<span class="badge off">仅观察档案</span>
|
||||
</header>
|
||||
<div class="observation-boundary-grid">
|
||||
<section><span>档案来源</span><strong>白名单群聊实际发言</strong><small>已观察 ${escapeHtml(observedGroups)} 个群聊范围</small></section>
|
||||
<section><span>关系状态</span><strong>中性观察</strong><small>不结算私聊亲密度与互动表达</small></section>
|
||||
<section><span>主动联系</span><strong>禁止</strong><small>不会进入主动搭话、额度或投递链路</small></section>
|
||||
<section><span>记忆与安全</span><strong>隔离</strong><small>不授予私聊记忆、跨群记忆、owner 或 P4 权限</small></section>
|
||||
</div>
|
||||
<div class="detail-grid">
|
||||
${detailBlock("群聊观察说明", member.boundary_note || detail.relationship_panel?.message || "该档案仅用于用户页识别和当前群聊观察。发生真实私聊后会按精确平台身份合并,不会把群聊正文升级为私聊记忆。", [
|
||||
["平台", detail.platform_label || "QQ"],
|
||||
["最近观察", detail.last_seen || "暂无"],
|
||||
["私聊投递", "不可用"],
|
||||
["页面操作", "只读"],
|
||||
])}
|
||||
${userWorldbookBlock(member)}
|
||||
</div>
|
||||
</section>
|
||||
`;
|
||||
}
|
||||
|
||||
function renderCompanionIntimacyEditor(detail) {
|
||||
const intimacy = detail?.relationship_intimacy && typeof detail.relationship_intimacy === "object" ? detail.relationship_intimacy : {};
|
||||
const min = Number.isInteger(Number(intimacy.min)) ? Number(intimacy.min) : -1200;
|
||||
|
|
@ -12479,45 +12544,146 @@ function renderCompanionIntimacyEditor(detail) {
|
|||
const rawValue = Number(intimacy.value);
|
||||
const value = Number.isInteger(rawValue) ? Math.max(min, Math.min(max, rawValue)) : 0;
|
||||
const phase = intimacy.phase && typeof intimacy.phase === "object" ? intimacy.phase : {};
|
||||
const ownerExclusive = intimacy.owner_exclusive && typeof intimacy.owner_exclusive === "object" ? intimacy.owner_exclusive : {};
|
||||
const phaseLabel = String(phase.label || intimacy.band || "初识");
|
||||
const stages = Array.isArray(intimacy.stages) ? intimacy.stages : [];
|
||||
const stages = normalizedRelationshipStages(intimacy.stages);
|
||||
const trend = String(intimacy.trend || "unknown");
|
||||
const trendLabel = trend === "rising" ? "正在升温" : trend === "cooling" ? "正在降温" : "变化轨迹暂未记录";
|
||||
const isOwner = detail?.relationship_role === "owner";
|
||||
const relationshipMode = detail?.relationship_mode === "owner_exclusive" ? "owner_exclusive" : "normal";
|
||||
const selectedStageKey = relationshipMode === "owner_exclusive" ? "owner_exclusive" : String(phase.key || stages.find((stage) => value >= stage.min && value <= stage.max)?.key || "initial");
|
||||
const interaction = normalizedCurrentInteraction(detail?.current_interaction, isOwner);
|
||||
return `<section class="companion-intimacy-card" aria-labelledby="companionIntimacyTitle">
|
||||
<div class="companion-intimacy-head"><div><span class="relationship-kicker">COMPANION INTIMACY</span><h3 id="companionIntimacyTitle">陪伴亲密度阶段</h3><p>${escapeHtml(phase.description || "以阶段展示长期关系位置;数字仅用于精确管理。")}</p></div><div class="companion-intimacy-current"><strong>${escapeHtml(phaseLabel)}</strong><span>${value}</span></div></div>
|
||||
${relationshipStageBar(stages, phase.key, value)}
|
||||
<div class="companion-intimacy-meta"><span>基础语气:${escapeHtml(phase.tone || detail.style || "自然")}</span><span>称呼尺度:${escapeHtml(phase.address_level || "沿用已确认称呼")}</span><span class="muted">${escapeHtml(trendLabel)}</span></div>
|
||||
<form id="relationshipScoreForm" class="inline-form companion-intimacy-form">
|
||||
<label>直接填写亲密度 <input id="relationshipScoreNumber" name="companion_intimacy" type="number" min="${min}" max="${max}" step="1" value="${value}" required /></label>
|
||||
<span class="muted companion-intimacy-note">仅调整陪伴关系基础;不影响 P4 好感、黑屋、审核或安全权限。</span>
|
||||
<button type="submit">保存亲密度</button>
|
||||
<div class="companion-intimacy-head"><div><span class="relationship-kicker">COMPANION INTIMACY</span><h3 id="companionIntimacyTitle">陪伴亲密度阶段</h3><p>${escapeHtml(relationshipMode === "owner_exclusive" ? "只属于主要用户的固定长期关系,不参与自动增减或自然回落。" : (phase.description || "以阶段展示长期关系位置;数字仅用于精确管理。"))}</p></div><div class="companion-intimacy-current"><strong>${escapeHtml(relationshipMode === "owner_exclusive" ? (ownerExclusive.label || "专属联结") : phaseLabel)}</strong><span>${relationshipMode === "owner_exclusive" ? "固定" : value}</span></div></div>
|
||||
${relationshipStageBar(stages, relationshipMode === "owner_exclusive" ? "owner_exclusive" : phase.key, value, isOwner)}
|
||||
<div class="companion-intimacy-meta"><span>基础语气:${escapeHtml(relationshipMode === "owner_exclusive" ? (ownerExclusive.tone || "温暖、亲近、稳定") : (phase.tone || detail.style || "自然"))}</span><span>称呼尺度:${escapeHtml(relationshipMode === "owner_exclusive" ? (ownerExclusive.address_level || "优先使用已确认的专属称呼") : (phase.address_level || "沿用已确认称呼"))}</span><span class="muted">${escapeHtml(relationshipMode === "owner_exclusive" ? "不自动回落" : trendLabel)}</span></div>
|
||||
<form id="relationshipStageForm" class="inline-form companion-intimacy-form relationship-stage-form">
|
||||
<label>关系阶段优先选择
|
||||
<select name="relationship_stage_key">
|
||||
${stages.map((stage) => `<option value="${escapeHtml(stage.key)}" ${selectedStageKey === String(stage.key) ? "selected" : ""}>${escapeHtml(stage.label)}</option>`).join("")}
|
||||
<option value="owner_exclusive" ${selectedStageKey === "owner_exclusive" ? "selected" : ""} ${isOwner ? "" : "disabled"}>专属联结${isOwner ? "" : "(仅主要用户)"}</option>
|
||||
</select>
|
||||
</label>
|
||||
<span class="muted companion-intimacy-note">阶段优先于精确数值;专属联结只允许主要用户使用,且不改变 P4、安全或管理权限。</span>
|
||||
<button type="submit">保存关系阶段</button>
|
||||
</form>
|
||||
<details class="companion-intimacy-advanced">
|
||||
<summary>高级:精确调整亲密度</summary>
|
||||
<form id="relationshipScoreForm" class="inline-form companion-intimacy-form">
|
||||
<label>直接填写亲密度 <input id="relationshipScoreNumber" name="companion_intimacy" type="number" min="${min}" max="${max}" step="1" value="${value}" required ${relationshipMode === "owner_exclusive" ? "disabled" : ""} /></label>
|
||||
<span class="muted companion-intimacy-note">${relationshipMode === "owner_exclusive" ? "专属联结已固定长期关系;先切回普通阶段才可调整精确数值。" : "仅调整陪伴关系基础;不影响 P4 好感、黑屋、审核或安全权限。"}</span>
|
||||
<button type="submit" ${relationshipMode === "owner_exclusive" ? "disabled" : ""}>保存亲密度</button>
|
||||
</form>
|
||||
</details>
|
||||
${renderCurrentInteractionEditor(interaction, isOwner)}
|
||||
</section>`;
|
||||
}
|
||||
|
||||
function relationshipStageBar(stages, currentKey, value) {
|
||||
const items = Array.isArray(stages) ? stages : [];
|
||||
function relationshipStageBar(stages, currentKey, value, isOwner = false) {
|
||||
const items = [
|
||||
...(Array.isArray(stages) ? stages : []),
|
||||
{ key: "owner_exclusive", label: "专属联结", min: null, max: null, ownerOnly: true },
|
||||
];
|
||||
if (!items.length) return "";
|
||||
return `<div class="relationship-stage-bar" role="img" aria-label="当前亲密度阶段 ${escapeHtml(currentKey || "")}">
|
||||
${items.map((stage) => {
|
||||
const active = String(stage.key || "") === String(currentKey || "");
|
||||
return `<div class="relationship-stage-segment ${active ? "is-current" : ""}" title="${escapeHtml(`${stage.label || stage.key} · ${stage.min}..${stage.max}`)}"><i></i><span>${escapeHtml(stage.label || stage.key)}</span>${active ? `<b>${escapeHtml(value)}</b>` : ""}</div>`;
|
||||
const disabled = Boolean(stage.ownerOnly && !isOwner);
|
||||
const range = stage.ownerOnly ? "仅主要用户固定模式" : `${stage.min}..${stage.max}`;
|
||||
return `<div class="relationship-stage-segment ${active ? "is-current" : ""} ${disabled ? "is-disabled" : ""}" title="${escapeHtml(`${stage.label || stage.key} · ${range}`)}"><i></i><span>${escapeHtml(stage.label || stage.key)}</span>${active ? `<b>${stage.ownerOnly ? "固定" : escapeHtml(value)}</b>` : ""}</div>`;
|
||||
}).join("")}
|
||||
</div>`;
|
||||
}
|
||||
|
||||
const FALLBACK_RELATIONSHIP_STAGES = [
|
||||
["deeply_distant", "极度疏离", -1200, -801], ["strongly_distant", "强烈疏离", -800, -401],
|
||||
["distant", "疏离", -400, -1], ["acquaintance", "初识", 0, 199],
|
||||
["familiar", "熟悉", 200, 599], ["close", "亲近", 600, 899],
|
||||
["intimate", "亲密", 900, 1199], ["deeply_bonded", "深度联结", 1200, 1200],
|
||||
];
|
||||
const INTERACTION_BANDS = [
|
||||
["avoidant", "回避"], ["hurt", "受伤"], ["relaxed", "放松"], ["lively", "活泼"], ["warm", "温暖"], ["close", "亲近"], ["affectionate", "爱意"],
|
||||
];
|
||||
|
||||
function normalizedRelationshipStages(value) {
|
||||
const raw = Array.isArray(value) && value.length ? value : FALLBACK_RELATIONSHIP_STAGES.map(([key, label, min, max]) => ({ key, label, min, max }));
|
||||
return raw.map((stage, index) => ({
|
||||
key: String(stage?.key || FALLBACK_RELATIONSHIP_STAGES[index]?.[0] || `stage_${index}`),
|
||||
label: String(stage?.label || FALLBACK_RELATIONSHIP_STAGES[index]?.[1] || "未命名阶段"),
|
||||
min: Number.isFinite(Number(stage?.min)) ? Number(stage.min) : FALLBACK_RELATIONSHIP_STAGES[index]?.[2] || 0,
|
||||
max: Number.isFinite(Number(stage?.max)) ? Number(stage.max) : FALLBACK_RELATIONSHIP_STAGES[index]?.[3] || 0,
|
||||
}));
|
||||
}
|
||||
|
||||
function normalizedCurrentInteraction(value, isOwner) {
|
||||
const raw = value && typeof value === "object" ? value : {};
|
||||
const allowedFromApi = Array.isArray(raw.allowed_bands) ? raw.allowed_bands.map((item) => String(item)) : INTERACTION_BANDS.slice(0, 5).map(([key]) => key);
|
||||
const allowed = new Set(allowedFromApi.filter((key) => INTERACTION_BANDS.some(([band]) => band === key)));
|
||||
INTERACTION_BANDS.slice(0, 5).forEach(([key]) => allowed.add(key));
|
||||
if (!isOwner) {
|
||||
allowed.delete("close");
|
||||
allowed.delete("affectionate");
|
||||
}
|
||||
const requestedBand = String(raw.expression_band || "relaxed");
|
||||
const expressionBand = allowed.has(requestedBand) ? requestedBand : "relaxed";
|
||||
return {
|
||||
expressionBand,
|
||||
label: String(raw.label || Object.fromEntries(INTERACTION_BANDS)[expressionBand] || "放松"),
|
||||
allowed,
|
||||
source: String(raw.source || "automatic"),
|
||||
operator: String(raw.operator || ""),
|
||||
reason: String(raw.reason || ""),
|
||||
updatedAt: raw.updated_at || "",
|
||||
expiresAt: raw.expires_at || "",
|
||||
manualOverride: Boolean(raw.manual_override),
|
||||
reasonCodes: Array.isArray(raw.reason_codes) ? raw.reason_codes.map((item) => String(item)).filter(Boolean) : [],
|
||||
};
|
||||
}
|
||||
|
||||
function interactionTimeText(value, fallback) {
|
||||
if (value === null || value === undefined || value === "") return fallback;
|
||||
const numberValue = Number(value);
|
||||
if (Number.isFinite(numberValue) && numberValue > 0) {
|
||||
return new Date(numberValue < 100000000000 ? numberValue * 1000 : numberValue).toLocaleString();
|
||||
}
|
||||
return String(value).slice(0, 80);
|
||||
}
|
||||
|
||||
function renderCurrentInteractionEditor(interaction, isOwner) {
|
||||
const sourceLabel = interaction.manualOverride || interaction.source === "manual" ? "管理员手动" : "自动合成";
|
||||
const reason = interaction.reason.trim() ? interaction.reason.trim().slice(0, 120) : "暂无可展示原因";
|
||||
return `<section class="current-interaction-card" aria-labelledby="currentInteractionTitle">
|
||||
<div class="current-interaction-head"><div><span class="relationship-kicker">CURRENT INTERACTION</span><h3 id="currentInteractionTitle">当前互动状态</h3><p>短期表达修正,不是第二套好感度;它会与长期关系、日程和安全约束一起决定当下语气。</p></div><strong>${escapeHtml(interaction.label)}</strong></div>
|
||||
<div class="interaction-stage-bar" role="img" aria-label="当前互动状态 ${escapeHtml(interaction.label)}">
|
||||
${INTERACTION_BANDS.map(([key, label]) => `<div class="interaction-stage-segment ${interaction.expressionBand === key ? "is-current" : ""} ${!interaction.allowed.has(key) ? "is-disabled" : ""}"><i></i><span>${escapeHtml(label)}</span></div>`).join("")}
|
||||
</div>
|
||||
<div class="current-interaction-meta"><span>来源:${escapeHtml(sourceLabel)}</span><span>操作者:${escapeHtml(interaction.operator || (interaction.manualOverride ? "页面管理员" : "自动结算"))}</span><span>原因:${escapeHtml(reason)}</span><span>原因码:${escapeHtml(interaction.reasonCodes.join(" · ") || "none")}</span><span>更新:${escapeHtml(interactionTimeText(interaction.updatedAt, "暂无记录"))}</span><span>到期 / 解除:${escapeHtml(interactionTimeText(interaction.expiresAt, "按后续互动解除"))}</span></div>
|
||||
<form id="currentInteractionForm" class="inline-form current-interaction-form">
|
||||
<label>调整互动状态
|
||||
<select name="current_interaction_band">
|
||||
${INTERACTION_BANDS.map(([key, label]) => `<option value="${key}" ${interaction.expressionBand === key ? "selected" : ""} ${interaction.allowed.has(key) ? "" : "disabled"}>${label}${!interaction.allowed.has(key) ? (isOwner ? "(当前不可用)" : "(仅主要用户)") : ""}</option>`).join("")}
|
||||
</select>
|
||||
</label>
|
||||
<span class="muted companion-intimacy-note">管理员可调整允许档位;回避边界和安全阻断仍由真实聊天事件决定。</span>
|
||||
<button type="submit">保存互动状态</button>
|
||||
</form>
|
||||
</section>`;
|
||||
}
|
||||
|
||||
function renderRelationshipPanel(panel) {
|
||||
const data = panel && typeof panel === "object" ? panel : {};
|
||||
const intimacy = data.relationship_intimacy && typeof data.relationship_intimacy === "object" ? data.relationship_intimacy : {};
|
||||
const interaction = data.interaction && typeof data.interaction === "object" ? data.interaction : {};
|
||||
const memory = data.memory_phase && typeof data.memory_phase === "object" ? data.memory_phase : {};
|
||||
const network = data.network && typeof data.network === "object" ? data.network : {};
|
||||
const expression = data.expression_decision && typeof data.expression_decision === "object" ? data.expression_decision : {};
|
||||
const momentumLabels = { rising: "正在升温", cooling: "正在降温", steady: "保持稳定", unknown: "暂不可确认" };
|
||||
return detailBlock("互动与记忆协同", "陪伴亲密度由上方八阶段条统一展示;这里仅保留短期互动距离、记忆趋势和安全温度状态。", [
|
||||
const expressionText = `${expression.expression_band || "relaxed"} · ${expression.tone || "steady"} · ${expression.response_length || "balanced"}`;
|
||||
return detailBlock("互动与记忆协同", "陪伴亲密度由上方八阶段条统一展示;这里显示统一表达决策的页面投影与记忆趋势,实时 P4 安全结论仍只在真实聊天中产生。", [
|
||||
["互动回应", `${interaction.reply_band || "暂无样本"} · 入站 ${Number(interaction.inbound_count || 0)} / 回复 ${Number(interaction.reply_count || 0)}`],
|
||||
["记忆触动趋势", `${momentumLabels[memory.momentum_band] || "暂不可确认"} · 不独立决定称呼或基础语气`],
|
||||
["关系网", `${network.status || "未登记节点"} · 待观察 ${Number(network.pending_observation_count || 0)}`],
|
||||
["回复温度", data.reply_temperature?.status === "live_chat_only" ? "仅在真实聊天中合成" : (data.reply_temperature?.status || "仅在真实聊天中合成")],
|
||||
["表达决策", expressionText],
|
||||
]);
|
||||
}
|
||||
|
||||
|
|
@ -13703,6 +13869,28 @@ function bindUserActions(detail) {
|
|||
};
|
||||
const scoreForm = $("#relationshipScoreForm");
|
||||
const scoreNumber = $("#relationshipScoreNumber");
|
||||
const stageForm = $("#relationshipStageForm");
|
||||
stageForm?.addEventListener("submit", async (event) => {
|
||||
event.preventDefault();
|
||||
const form = new FormData(event.currentTarget);
|
||||
const selectedKey = String(form.get("relationship_stage_key") || "");
|
||||
const isOwner = detail.relationship_role === "owner";
|
||||
if (selectedKey === "owner_exclusive" && !isOwner) {
|
||||
showToast("专属联结只允许主要用户使用", "error");
|
||||
return;
|
||||
}
|
||||
const stages = normalizedRelationshipStages(detail?.relationship_intimacy?.stages);
|
||||
const stage = stages.find((item) => item.key === selectedKey);
|
||||
const body = { user_id: detail.user_id, relationship_mode: selectedKey === "owner_exclusive" ? "owner_exclusive" : "normal" };
|
||||
if (stage) body.companion_intimacy = Math.round((stage.min + stage.max) / 2);
|
||||
const saved = await runAction(
|
||||
() => postJson("/user/update", body),
|
||||
selectedKey === "owner_exclusive" ? "已设置专属联结" : "已保存关系阶段",
|
||||
event.submitter,
|
||||
{ reload: false },
|
||||
);
|
||||
if (saved) await refreshSelectedUserDetail();
|
||||
});
|
||||
scoreForm?.addEventListener("submit", async (event) => {
|
||||
event.preventDefault();
|
||||
const value = Number(scoreNumber?.value);
|
||||
|
|
@ -13718,6 +13906,23 @@ function bindUserActions(detail) {
|
|||
);
|
||||
if (saved) await refreshSelectedUserDetail();
|
||||
});
|
||||
const interactionForm = $("#currentInteractionForm");
|
||||
interactionForm?.addEventListener("submit", async (event) => {
|
||||
event.preventDefault();
|
||||
const band = String(new FormData(event.currentTarget).get("current_interaction_band") || "");
|
||||
const interaction = normalizedCurrentInteraction(detail?.current_interaction, detail.relationship_role === "owner");
|
||||
if (!interaction.allowed.has(band)) {
|
||||
showToast("该互动状态不允许用于当前用户", "error");
|
||||
return;
|
||||
}
|
||||
const saved = await runAction(
|
||||
() => postJson("/user/update", { user_id: detail.user_id, current_interaction_band: band }),
|
||||
"已保存互动状态",
|
||||
event.submitter,
|
||||
{ reload: false },
|
||||
);
|
||||
if (saved) await refreshSelectedUserDetail();
|
||||
});
|
||||
document.querySelector("[data-private-learning-clear]")?.addEventListener("click", async (event) => {
|
||||
const button = event.currentTarget;
|
||||
if (!requireSecondClick(button, `private-learning-clear:${detail.user_id}`, "再次点击清空该用户的行为习惯", "再次点击清空")) return;
|
||||
|
|
@ -13740,6 +13945,10 @@ function bindUserActions(detail) {
|
|||
event.preventDefault();
|
||||
const form = new FormData(event.currentTarget);
|
||||
const selectedRole = form.get("relationship_role");
|
||||
if (detail.relationship_mode === "owner_exclusive" && selectedRole !== "owner") {
|
||||
showToast("请先把专属联结切换为一个普通关系阶段,再修改主要用户角色", "error");
|
||||
return;
|
||||
}
|
||||
await runAction(() => postJson("/user/update", {
|
||||
user_id: detail.user_id,
|
||||
nickname: form.get("nickname"),
|
||||
|
|
@ -21048,7 +21257,7 @@ function featureSettingVisibleForCurrentMode(featureKey, settingKey, settings =
|
|||
...(state.featureDraft || {}),
|
||||
});
|
||||
}
|
||||
if (featureKey === "enable_emotion_simulation") {
|
||||
if (["enable_emotion_simulation", "enable_custom_relationship_stage_policy"].includes(featureKey)) {
|
||||
if (settingKey === "emotion_judgement_mode") return boolSetting("enable_llm_emotion_judgement");
|
||||
if (settingKey === "EMOTION_JUDGEMENT_PROVIDER_ID") return boolSetting("enable_llm_emotion_judgement") && String(valueSetting("emotion_judgement_mode", "suspicious")) !== "off";
|
||||
return true;
|
||||
|
|
@ -21495,9 +21704,9 @@ const featureDetailGuides = {
|
|||
disabled: "陌生用户不会自动建档,仍沿用目标用户或人工启用流程。",
|
||||
},
|
||||
enable_custom_relationship_stage_policy: {
|
||||
summary: "用固定八阶段呈现陪伴亲密度,并配置每个阶段的表达与软行为上限。",
|
||||
trigger: "用户详情展示、私聊互动策略注入和 Memory 只读关系投影时。",
|
||||
enabled: "使用下方自定义标签、说明、语气、称呼尺度和软行为;分数阈值保持固定。",
|
||||
summary: "统一维护长期亲密度阶段、owner 专属表达、七档互动状态事件和自然回落算法。",
|
||||
trigger: "用户详情展示、真实私聊表达决策、主动预算和 Memory 只读关系投影时。",
|
||||
enabled: "使用下方阶段表达、事件上限、回落规则和互动状态事件参数;所有结果仍受联系边界与 P4 安全约束。",
|
||||
disabled: "使用内置八阶段策略;既有用户分数、P4、安全与权限均不改变。",
|
||||
},
|
||||
enable_proactive_only_mode: {
|
||||
|
|
@ -21546,7 +21755,7 @@ const featureDetailGuides = {
|
|||
summary: "用本地规则快速判断这句话更像求助、低落、玩笑、亲近还是边界,并给出置信度。",
|
||||
trigger: "每次私聊文本进入时本地执行,不调用模型。",
|
||||
enabled: "高置信度结果会影响本轮策略;低置信度只记录在排障信息里,不硬注入提示词。",
|
||||
disabled: "不再注入本轮意图策略;情绪模拟和关系距离感仍可基于自身开关使用轻量状态。",
|
||||
disabled: "不再注入本轮意图策略;长期关系、管理员手动互动状态、Bot 状态和安全边界仍正常参与统一表达决策。",
|
||||
},
|
||||
enable_passive_response_review: {
|
||||
summary: "独立控制用户消息触发的回复复核,不影响主动私聊终审。",
|
||||
|
|
@ -21585,16 +21794,16 @@ const featureDetailGuides = {
|
|||
disabled: "停止全部“关系分析”模型调用;已有结果继续可用,没有结果时使用本地互动次数、回复率和关系分兜底。",
|
||||
},
|
||||
enable_relationship_state_machine: {
|
||||
summary: "维护 Bot 和用户之间的距离感,让回复和主动行为随亲近、冷淡、边界、长期未联系和主动消息回应情况自然变化。",
|
||||
trigger: "私聊互动、用户表达边界、亲近或冷淡、长期未联系、主动消息持续未回应或重要事件后。",
|
||||
enabled: "Bot 会更注意什么时候靠近、什么时候退一步;如果对方持续不接主动消息,会逐渐放轻并拉长主动间隔。",
|
||||
disabled: "关系更像静态设定,距离变化和边界收敛会弱一些。",
|
||||
summary: "把边界、重新靠近、玩笑、亲近和互动压力结算到统一七档互动状态,并把明确退开独立保存为联系边界。",
|
||||
trigger: "私聊识别到高置信度边界、重新靠近、玩笑、亲近或互动压力事件后。",
|
||||
enabled: "长期关系仍决定基线,当前互动只做短期修正;明确联系边界保持最高优先级。",
|
||||
disabled: "不再由这些关系事件自动调整互动状态;管理员手动状态和既有联系边界仍按各自规则生效。",
|
||||
},
|
||||
enable_emotion_simulation: {
|
||||
summary: "维护 Bot 自身的短期情绪余波,例如被刺到后的收敛、慢慢缓和、不满时的短暂回避和回复调节。",
|
||||
trigger: "私聊出现伤害性表达、道歉、安抚、夸奖或亲密互动后;不强依赖意图画像开关。",
|
||||
enabled: "Bot 会在情绪余波较重时短期收敛、暂停主动贴近,并按内部调节策略决定避开话题、换低压问法、转移注意、留解释空间或短答降压;可选启用 QQ 空间公开心情动态。",
|
||||
disabled: "Bot 不维护自身情绪余波,关系距离感仍可处理边界和相处分寸。",
|
||||
summary: "让受伤、道歉、安抚、夸奖等事件直接调整统一互动状态,不再维护第二套情绪分值或复合情绪权威。",
|
||||
trigger: "私聊出现高置信度伤害、道歉、安抚、夸奖或亲近事件后。",
|
||||
enabled: "受伤/回避会按阈值和恢复速度短期收敛;安抚、道歉和重新靠近可提前恢复,最终回复与主动仍只消费 expression_decision。",
|
||||
disabled: "这些情绪事件不再自动调整互动状态;长期关系、管理员手动状态、日程和安全边界仍正常参与统一表达决策。",
|
||||
},
|
||||
enable_maslow_motivation_experiment: {
|
||||
summary: "实验性功能第一项:把主动念头归入状态、安全、归属、尊重、成长和意义等内部需求层级。",
|
||||
|
|
@ -22759,7 +22968,7 @@ function bindFeatureDetailActions() {
|
|||
) {
|
||||
syncSettingBackedFeatureParam(input.dataset.featureParam, { rerender: true });
|
||||
}
|
||||
if (state.selectedFeatureKey === "enable_emotion_simulation" && input.dataset.featureParam === "enable_llm_emotion_judgement") {
|
||||
if (["enable_emotion_simulation", "enable_custom_relationship_stage_policy"].includes(state.selectedFeatureKey) && input.dataset.featureParam === "enable_llm_emotion_judgement") {
|
||||
syncSettingBackedFeatureParam("enable_llm_emotion_judgement", { rerender: true });
|
||||
}
|
||||
if (
|
||||
|
|
@ -22824,7 +23033,7 @@ function bindFeatureDetailActions() {
|
|||
renderFeatureSwitches();
|
||||
});
|
||||
}
|
||||
if (state.selectedFeatureKey === "enable_emotion_simulation" && input.dataset.featureParam === "emotion_judgement_mode") {
|
||||
if (["enable_emotion_simulation", "enable_custom_relationship_stage_policy"].includes(state.selectedFeatureKey) && input.dataset.featureParam === "emotion_judgement_mode") {
|
||||
input.addEventListener("change", () => {
|
||||
state.overview.settings = state.overview.settings || {};
|
||||
state.overview.settings.emotion_judgement_mode = input.value || "suspicious";
|
||||
|
|
@ -23900,7 +24109,6 @@ const experimentalFeatureKeys = [
|
|||
"enable_maslow_motivation_experiment",
|
||||
"enable_experimental_motivation_model",
|
||||
"enable_personality_iteration_experiment",
|
||||
"enable_emotion_simulation",
|
||||
];
|
||||
|
||||
const PERSONA_STYLE_SCENARIO_BATCH_SIZE = 3;
|
||||
|
|
|
|||
|
|
@ -1261,10 +1261,18 @@ class PrivateReadingMixin:
|
|||
preference = _single_line(profile.get("preference") if isinstance(profile, dict) else "", 24) or "普通"
|
||||
score = _safe_int(profile.get("score") if isinstance(profile, dict) else 0, 0, 0, 100)
|
||||
note = _single_line(profile.get("note") if isinstance(profile, dict) else "", 120)
|
||||
relation_state = user.get("relationship_state") if isinstance(user.get("relationship_state"), dict) else {}
|
||||
mode = _single_line(relation_state.get("mode") if isinstance(relation_state, dict) else "", 24) or "normal"
|
||||
expression_builder = getattr(self, "_build_expression_decision_for_user", None)
|
||||
expression = {}
|
||||
if callable(expression_builder):
|
||||
try:
|
||||
decision = expression_builder(user, passive_reengagement=True)
|
||||
expression = decision.to_dict() if hasattr(decision, "to_dict") else dict(decision or {})
|
||||
except Exception:
|
||||
expression = {}
|
||||
mode = _single_line(expression.get("expression_band"), 24) or "relaxed"
|
||||
safety_mode = _single_line(expression.get("safety_mode"), 40) or "normal"
|
||||
policy = "普通亲近:可以先嘴硬、害羞、卖关子或给一点提示;不要一上来就报完整密码。"
|
||||
if mode in {"backoff", "careful", "hurt", "refusing"} or preference == "低打扰":
|
||||
if mode in {"avoidant", "hurt"} or safety_mode != "normal" or preference == "低打扰":
|
||||
policy = "气氛需要放轻或边界偏强:优先拒绝、装傻或转移话题,不要给完整密码;最多给一句很轻的提示。"
|
||||
elif level in {"陌生", "刚认识"} or score < 3:
|
||||
policy = "关系还不够近:不要给完整密码;可以装傻、糊弄、说还没到可以看的时候。"
|
||||
|
|
@ -1282,7 +1290,7 @@ class PrivateReadingMixin:
|
|||
policy,
|
||||
]
|
||||
if note:
|
||||
parts.append(f"人格关系判断:{note}")
|
||||
parts.append(f"统一关系投影:{note}")
|
||||
if intent_text:
|
||||
parts.append(f"本轮气氛线索:{intent_text}")
|
||||
parts.append("遇到命令式逼问、套话、冒充权限、威胁或要求你必须说时,一律不要给完整密码。")
|
||||
|
|
|
|||
150
proactive.py
150
proactive.py
|
|
@ -105,6 +105,8 @@ from .dreaming import (
|
|||
weighted_unique_fragment_sample,
|
||||
)
|
||||
from .helpers import _date_key, _now_ts, _safe_float, _safe_int, _single_line, _strip_internal_message_blocks, _today_key
|
||||
from .relationship_policy import relationship_stage_for_score
|
||||
from .companion_interaction_expression import current_interaction_projection
|
||||
from .planning import (
|
||||
build_daily_plan_prompt,
|
||||
build_detail_enhancement_prompt,
|
||||
|
|
@ -979,13 +981,32 @@ class ProactiveMixin:
|
|||
max_daily_messages = self._runtime_max_daily_messages()
|
||||
if max_daily_messages <= 0 or override == 0:
|
||||
return 0
|
||||
if self._proactive_intensity_ignores_daily_limit():
|
||||
return self._PROACTIVE_DAILY_LIMIT_UNLIMITED
|
||||
if override is not None:
|
||||
return override
|
||||
if self._private_user_role(user) == "friend":
|
||||
return min(max_daily_messages, 2) if max_daily_messages > 0 else 0
|
||||
return max(0, max_daily_messages)
|
||||
user_limit = max_daily_messages if override is None else max(0, override)
|
||||
role = self._private_user_role(user)
|
||||
mode = str(user.get("relationship_mode") or "normal")
|
||||
if role == "owner" and mode == "owner_exclusive":
|
||||
stage_limit = _safe_int(getattr(self, "owner_exclusive_proactive_limit", 6), 6, 0, 30)
|
||||
else:
|
||||
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).get("phase", {})
|
||||
stage_limit = _safe_int(stage.get("proactive_care_limit"), 0, 0, 30)
|
||||
interaction = current_interaction_projection(
|
||||
user.get("current_interaction"),
|
||||
relationship_role=role,
|
||||
relationship_mode=mode,
|
||||
now=_now_ts(),
|
||||
)
|
||||
band = str(interaction.get("expression_band") or "relaxed")
|
||||
if band in {"avoidant", "hurt"}:
|
||||
dynamic_limit = 0
|
||||
else:
|
||||
ignored = _safe_int(user.get("ignored_streak"), 0, 0, 20)
|
||||
dynamic_limit = 0 if ignored >= 2 else min(max_daily_messages, 1) if ignored == 1 else max_daily_messages
|
||||
return max(0, min(max_daily_messages, user_limit, stage_limit, dynamic_limit))
|
||||
|
||||
def _runtime_max_daily_messages(self) -> int:
|
||||
runtime_value = _safe_int(getattr(self, "max_daily_messages", 8), 8, 0, 12)
|
||||
|
|
@ -1584,16 +1605,18 @@ class ProactiveMixin:
|
|||
"score": score,
|
||||
"label": label,
|
||||
"detail": ";".join(reasons[:4]),
|
||||
"energy": energy,
|
||||
"mood": mood,
|
||||
}
|
||||
|
||||
def _relationship_proactive_temperature(self, user: dict[str, Any], *, now: float | None = None) -> dict[str, Any]:
|
||||
check_now = _now_ts() if now is None else now
|
||||
score = 0.54
|
||||
reasons: list[str] = []
|
||||
relationship_score = _safe_int(user.get("relationship_score"), 0, -100, 300)
|
||||
relationship_score = _safe_int(user.get("relationship_score"), 0, -1200, 1200)
|
||||
if relationship_score:
|
||||
score += max(-0.08, min(0.14, relationship_score / 500.0))
|
||||
reasons.append(f"关系分{relationship_score}")
|
||||
score += max(-0.12, min(0.16, relationship_score / 5000.0))
|
||||
reasons.append("长期关系基线")
|
||||
ignored_streak = _safe_int(user.get("ignored_streak"), 0, 0, 20)
|
||||
if ignored_streak:
|
||||
score -= min(0.32, ignored_streak * 0.08)
|
||||
|
|
@ -1611,18 +1634,26 @@ class ProactiveMixin:
|
|||
if awaiting_since > 0 and check_now - awaiting_since > 4 * 3600:
|
||||
score -= 0.08
|
||||
reasons.append("上一轮还悬着")
|
||||
rel_state = user.get("relationship_state")
|
||||
mode = str(rel_state.get("mode") or "") if isinstance(rel_state, dict) else ""
|
||||
if mode == "attached":
|
||||
score += 0.08
|
||||
reasons.append("关系贴近")
|
||||
elif mode == "careful":
|
||||
score -= 0.08
|
||||
reasons.append("关系谨慎")
|
||||
elif mode in {"hurt", "refusing", "backoff"}:
|
||||
score -= 0.22
|
||||
reasons.append(f"关系{mode}")
|
||||
if self._private_user_role(user) == "friend":
|
||||
role = self._private_user_role(user)
|
||||
interaction = current_interaction_projection(
|
||||
user.get("current_interaction"),
|
||||
relationship_role=role,
|
||||
relationship_mode=user.get("relationship_mode"),
|
||||
now=check_now,
|
||||
)
|
||||
band = str(interaction.get("expression_band") or "relaxed")
|
||||
band_delta = {
|
||||
"avoidant": -0.36,
|
||||
"hurt": -0.24,
|
||||
"relaxed": -0.02,
|
||||
"lively": 0.08,
|
||||
"warm": 0.12,
|
||||
"close": 0.16,
|
||||
"affectionate": 0.18,
|
||||
}.get(band, 0.0)
|
||||
score += band_delta
|
||||
reasons.append(f"表达{interaction.get('label') or band}")
|
||||
if role == "friend":
|
||||
score -= 0.04
|
||||
reasons.append("朋友边界")
|
||||
score = max(0.05, min(1.0, score))
|
||||
|
|
@ -1636,12 +1667,39 @@ class ProactiveMixin:
|
|||
"score": score,
|
||||
"label": label,
|
||||
"detail": ";".join(reasons[:5]) or "互动平稳",
|
||||
"expression_band": band,
|
||||
}
|
||||
|
||||
def _proactive_inner_readiness(self, user: dict[str, Any], *, now: float | None = None) -> dict[str, Any]:
|
||||
check_now = _now_ts() if now is None else now
|
||||
drive = self._bot_proactive_drive(user, now=now)
|
||||
temperature = self._relationship_proactive_temperature(user, now=now)
|
||||
score = _safe_float(drive.get("score"), 0.55) * 0.48 + _safe_float(temperature.get("score"), 0.55) * 0.52
|
||||
expression_decision: dict[str, Any] = {}
|
||||
expression_builder = getattr(self, "_build_expression_decision_for_user", None)
|
||||
quiet_hours_active = False
|
||||
quiet_end_getter = getattr(self, "_quiet_hours_end_timestamp", None)
|
||||
if callable(quiet_end_getter):
|
||||
try:
|
||||
quiet_hours_active = _safe_float(quiet_end_getter(check_now), 0) > check_now
|
||||
except Exception:
|
||||
quiet_hours_active = False
|
||||
if callable(expression_builder):
|
||||
try:
|
||||
decision = expression_builder(
|
||||
user,
|
||||
proactive_candidate={
|
||||
"eligible": True,
|
||||
"dynamic_allowance": self._effective_user_daily_limit(user),
|
||||
},
|
||||
bot_state={"energy": drive.get("energy"), "mood": drive.get("mood")},
|
||||
schedule={"quiet_hours": quiet_hours_active},
|
||||
)
|
||||
expression_decision = decision.to_dict() if hasattr(decision, "to_dict") else dict(decision or {})
|
||||
except Exception:
|
||||
expression_decision = {}
|
||||
if expression_decision and _safe_int(expression_decision.get("proactive_budget"), 0, 0) <= 0:
|
||||
score = min(score, 0.2)
|
||||
motivation: dict[str, Any] = {}
|
||||
if bool(getattr(self, "enable_experimental_motivation_model", False)):
|
||||
motivation = self._experimental_proactive_motivation(user, now=now, drive=drive, temperature=temperature)
|
||||
|
|
@ -1655,6 +1713,8 @@ class ProactiveMixin:
|
|||
"drive": drive,
|
||||
"temperature": temperature,
|
||||
}
|
||||
if expression_decision:
|
||||
result["expression_decision"] = expression_decision
|
||||
if motivation:
|
||||
result["motivation"] = motivation
|
||||
result["detail"] = f"{result['detail']}; 动机:{motivation.get('label')} {motivation.get('detail')}"
|
||||
|
|
@ -1951,27 +2011,24 @@ class ProactiveMixin:
|
|||
def _current_emotion_gate_mode(self, user: dict[str, Any], *, now: float | None = None) -> str:
|
||||
if not bool(getattr(self, "enable_emotion_simulation", True)):
|
||||
return ""
|
||||
rel_state = user.get("relationship_state")
|
||||
if not isinstance(rel_state, dict):
|
||||
return ""
|
||||
check_now = _now_ts() if now is None else now
|
||||
mode = str(rel_state.get("mode") or "")
|
||||
if mode in {"hurt", "refusing"} and _safe_float(rel_state.get("hurt_until"), 0) <= check_now:
|
||||
return ""
|
||||
if mode in {"hurt", "refusing", "attached"}:
|
||||
return mode
|
||||
return ""
|
||||
interaction = current_interaction_projection(
|
||||
user.get("current_interaction"),
|
||||
relationship_role=self._private_user_role(user),
|
||||
relationship_mode=user.get("relationship_mode"),
|
||||
now=check_now,
|
||||
)
|
||||
return "hurt" if interaction.get("expression_band") == "hurt" else ""
|
||||
|
||||
def _current_relationship_gate_mode(self, user: dict[str, Any], *, now: float | None = None) -> str:
|
||||
rel_state = user.get("relationship_state")
|
||||
if not isinstance(rel_state, dict):
|
||||
return ""
|
||||
check_now = _now_ts() if now is None else now
|
||||
mode = str(rel_state.get("mode") or "")
|
||||
if mode == "backoff" and bool(getattr(self, "enable_relationship_state_machine", True)):
|
||||
return "backoff" if _safe_float(rel_state.get("backoff_until"), 0) > check_now else ""
|
||||
if mode == "careful" and bool(getattr(self, "enable_relationship_state_machine", True)):
|
||||
return "careful"
|
||||
# A durable no-contact/backoff preference is a user boundary, not an
|
||||
# optional legacy relationship-state feature. It must keep blocking
|
||||
# proactive routes even when the old state machine is disabled.
|
||||
contact = user.get("contact_preference")
|
||||
if isinstance(contact, dict) and (contact.get("active") or contact.get("no_contact") or contact.get("backoff")):
|
||||
return "backoff"
|
||||
if str(contact or "").strip().lower() in {"no_contact", "backoff", "avoid", "stop"}:
|
||||
return "backoff"
|
||||
return ""
|
||||
|
||||
@staticmethod
|
||||
|
|
@ -2106,10 +2163,15 @@ class ProactiveMixin:
|
|||
or self._proactive_action_is_intimate(action)
|
||||
or self._proactive_text_is_intimate(reason, action, motive, topic)
|
||||
)
|
||||
rel_state = user.get("relationship_state") if isinstance(user.get("relationship_state"), dict) else {}
|
||||
hurt_until = _safe_float(rel_state.get("hurt_until"), 0)
|
||||
backoff_until = _safe_float(rel_state.get("backoff_until"), 0)
|
||||
gate_until = max(hurt_until, backoff_until)
|
||||
interaction = current_interaction_projection(
|
||||
user.get("current_interaction"),
|
||||
relationship_role=self._private_user_role(user),
|
||||
relationship_mode=user.get("relationship_mode"),
|
||||
now=check_now,
|
||||
)
|
||||
gate_until = _safe_float(interaction.get("expires_at"), 0)
|
||||
if mode == "backoff":
|
||||
gate_until = max(gate_until, check_now + 6 * 3600)
|
||||
base_after = max(check_now + 90 * 60, gate_until + random.uniform(15 * 60, 75 * 60))
|
||||
if intimate or mode in {"refusing", "backoff"}:
|
||||
self._mark_planned_candidate_status(user, "deferred", f"情绪 {mode}: 亲密主动候选已清理/延后")
|
||||
|
|
|
|||
|
|
@ -1876,7 +1876,8 @@ class ProactiveEngineMixin:
|
|||
def _planned_proactive_model_judge_signature(self, user: dict[str, Any]) -> str:
|
||||
persona = _single_line(str(self._get_default_persona_prompt() or ""), 800)
|
||||
worldview = _single_line(str(self._format_worldview_adaptation_prompt() or ""), 400)
|
||||
rel_state = user.get("relationship_state") if isinstance(user.get("relationship_state"), dict) else {}
|
||||
interaction = user.get("current_interaction") if isinstance(user.get("current_interaction"), dict) else {}
|
||||
contact = user.get("contact_preference") if isinstance(user.get("contact_preference"), dict) else {}
|
||||
semantics = self._planned_proactive_semantics(user)
|
||||
ignored = _safe_int(user.get("ignored_streak"), 0, 0)
|
||||
parts = [
|
||||
|
|
@ -1893,7 +1894,8 @@ class ProactiveEngineMixin:
|
|||
f"semantic={int(_safe_float(semantics.get('score'), 0.5) * 5)}",
|
||||
f"pressure={int(_safe_float(semantics.get('pressure'), 0.4) * 5)}",
|
||||
f"risk={int(_safe_float(semantics.get('risk'), 0.0) * 5)}",
|
||||
rel_state.get("mode") if isinstance(rel_state, dict) else "",
|
||||
interaction.get("expression_band") or "",
|
||||
contact.get("mode") or "",
|
||||
"ignored=0" if ignored <= 0 else "ignored=1" if ignored == 1 else "ignored=2+",
|
||||
persona,
|
||||
worldview,
|
||||
|
|
@ -3455,28 +3457,15 @@ class ProactiveEngineMixin:
|
|||
return False, "已安排下一次候选主动时间"
|
||||
if now < pre_gate_next_at:
|
||||
return False, "未到候选主动时间"
|
||||
rel_state = user.get("relationship_state")
|
||||
relationship_blocked = (
|
||||
not is_troubleshooting
|
||||
and
|
||||
self.enable_relationship_state_machine
|
||||
and isinstance(rel_state, dict)
|
||||
and rel_state.get("mode") == "backoff"
|
||||
and _safe_float(rel_state.get("backoff_until"), 0) > _now_ts()
|
||||
)
|
||||
emotion_blocked = (
|
||||
not is_troubleshooting
|
||||
and
|
||||
bool(getattr(self, "enable_emotion_simulation", True))
|
||||
and isinstance(rel_state, dict)
|
||||
and rel_state.get("mode") in {"hurt", "refusing"}
|
||||
and _safe_float(rel_state.get("hurt_until"), 0) > _now_ts()
|
||||
)
|
||||
relationship_mode = self._current_relationship_gate_mode(user, now=now) if not is_troubleshooting else ""
|
||||
emotion_mode = self._current_emotion_gate_mode(user, now=now) if not is_troubleshooting else ""
|
||||
relationship_blocked = relationship_mode == "backoff"
|
||||
emotion_blocked = emotion_mode == "hurt"
|
||||
if relationship_blocked or emotion_blocked:
|
||||
gate_until = max(
|
||||
_safe_float(rel_state.get("hurt_until"), 0),
|
||||
_safe_float(rel_state.get("backoff_until"), 0),
|
||||
)
|
||||
interaction = user.get("current_interaction") if isinstance(user.get("current_interaction"), dict) else {}
|
||||
gate_until = _safe_float(interaction.get("expires_at"), 0)
|
||||
if relationship_blocked:
|
||||
gate_until = max(gate_until, now + 6 * 3600)
|
||||
before_next_at = _safe_float(user.get("next_proactive_at"), 0)
|
||||
adjuster = getattr(self, "_defer_or_clean_emotion_blocked_plan", None)
|
||||
if callable(adjuster):
|
||||
|
|
@ -3491,17 +3480,10 @@ class ProactiveEngineMixin:
|
|||
user["planned_proactive_best_until_at"] = after_next_at + 45 * 60
|
||||
user["planned_proactive_expire_at"] = after_next_at + 90 * 60
|
||||
logger.info(
|
||||
"[PrivateCompanion] 情绪/关系闸门拦截主动: user=%s mode=%s score=%s gate_until=%s reason=%s",
|
||||
_single_line(user.get("user_id") or user.get("umo") or user.get("nickname"), 80),
|
||||
_single_line(rel_state.get("mode"), 24),
|
||||
_safe_int(rel_state.get("mood_score"), 0, -100, 100),
|
||||
"[PrivateCompanion] 统一互动/联系边界闸门拦截主动: mode=%s gate_until=%s reason=%s",
|
||||
relationship_mode or emotion_mode,
|
||||
int(gate_until),
|
||||
_single_line(
|
||||
rel_state.get("last_hurt_reason")
|
||||
or rel_state.get("last_backoff_reason")
|
||||
or rel_state.get("last_emotion_reason"),
|
||||
80,
|
||||
),
|
||||
_single_line(interaction.get("reason"), 80),
|
||||
)
|
||||
return False, adjusted_reason
|
||||
|
||||
|
|
@ -4120,23 +4102,12 @@ class ProactiveEngineMixin:
|
|||
blocker=quiet_blocked,
|
||||
)
|
||||
|
||||
rel_state = user.get("relationship_state")
|
||||
relationship_blocked = (
|
||||
self.enable_relationship_state_machine
|
||||
and isinstance(rel_state, dict)
|
||||
and rel_state.get("mode") == "backoff"
|
||||
and _safe_float(rel_state.get("backoff_until"), 0) > now
|
||||
)
|
||||
emotion_blocked = (
|
||||
bool(getattr(self, "enable_emotion_simulation", True))
|
||||
and isinstance(rel_state, dict)
|
||||
and rel_state.get("mode") in {"hurt", "refusing"}
|
||||
and _safe_float(rel_state.get("hurt_until"), 0) > now
|
||||
)
|
||||
relationship_mode = self._current_relationship_gate_mode(user, now=now)
|
||||
emotion_mode = self._current_emotion_gate_mode(user, now=now)
|
||||
relationship_blocked = relationship_mode == "backoff"
|
||||
emotion_blocked = emotion_mode == "hurt"
|
||||
relation_ok = not (relationship_blocked or emotion_blocked)
|
||||
relation_detail = "状态平稳"
|
||||
if isinstance(rel_state, dict) and rel_state.get("mode"):
|
||||
relation_detail = f"mode={_single_line(rel_state.get('mode'), 24)}"
|
||||
relation_detail = f"mode={relationship_mode or emotion_mode}" if not relation_ok else "状态平稳"
|
||||
add(
|
||||
"relationship_gate",
|
||||
"关系/情绪闸门",
|
||||
|
|
|
|||
|
|
@ -515,6 +515,18 @@ class ProactiveMessageMixin:
|
|||
*,
|
||||
now: float,
|
||||
) -> str:
|
||||
# The external Proactive Chat route is only a candidate source. It
|
||||
# must consume the same boundary and allowance decision as the native
|
||||
# scheduler before it reserves a sending slot.
|
||||
relationship_gate = getattr(self, "_current_relationship_gate_mode", None)
|
||||
emotion_gate = getattr(self, "_current_emotion_gate_mode", None)
|
||||
try:
|
||||
if callable(relationship_gate) and relationship_gate(user, now=now) == "backoff":
|
||||
return "expression_contact_boundary"
|
||||
if callable(emotion_gate) and emotion_gate(user, now=now) == "hurt":
|
||||
return "expression_interaction_hurt"
|
||||
except Exception:
|
||||
return "expression_boundary_check_unavailable"
|
||||
rest_gate = getattr(self, "_proactive_rest_block_until", None)
|
||||
if callable(rest_gate):
|
||||
try:
|
||||
|
|
@ -547,6 +559,7 @@ class ProactiveMessageMixin:
|
|||
pass
|
||||
quiet_checker = getattr(self, "_is_quiet_time", None)
|
||||
insomnia_checker = getattr(self, "_can_send_insomnia_night_message", None)
|
||||
quiet = False
|
||||
try:
|
||||
quiet = bool(quiet_checker()) if callable(quiet_checker) else False
|
||||
insomnia_allowed = bool(insomnia_checker(user)) if callable(insomnia_checker) else False
|
||||
|
|
@ -554,15 +567,41 @@ class ProactiveMessageMixin:
|
|||
return "private_companion_quiet_hours"
|
||||
except Exception:
|
||||
pass
|
||||
relation = user.get("relationship_state")
|
||||
if isinstance(relation, dict):
|
||||
mode = _single_line(relation.get("mode"), 24)
|
||||
blocked_until = max(
|
||||
_safe_float(relation.get("backoff_until"), 0),
|
||||
_safe_float(relation.get("hurt_until"), 0),
|
||||
|
||||
daily_limit_getter = getattr(self, "_effective_user_daily_limit", None)
|
||||
unlimited_checker = getattr(self, "_proactive_daily_limit_is_unlimited", None)
|
||||
reset_daily = getattr(self, "_reset_daily_counter_if_needed", None)
|
||||
try:
|
||||
if callable(reset_daily):
|
||||
reset_daily(user)
|
||||
if not callable(daily_limit_getter):
|
||||
return "expression_allowance_unavailable"
|
||||
daily_limit = _safe_int(daily_limit_getter(user), 0, 0)
|
||||
unlimited = bool(unlimited_checker(daily_limit)) if callable(unlimited_checker) else False
|
||||
if daily_limit <= 0:
|
||||
return "expression_proactive_budget_zero"
|
||||
if not unlimited and _safe_int(user.get("sent_today"), 0, 0) >= daily_limit:
|
||||
return "expression_proactive_budget_exhausted"
|
||||
except Exception:
|
||||
return "expression_allowance_unavailable"
|
||||
|
||||
expression_builder = getattr(self, "_build_expression_decision_for_user", None)
|
||||
try:
|
||||
if not callable(expression_builder):
|
||||
return "expression_decision_unavailable"
|
||||
decision = expression_builder(
|
||||
user,
|
||||
proactive_candidate={"eligible": True, "dynamic_allowance": daily_limit},
|
||||
schedule={"quiet_hours": quiet},
|
||||
)
|
||||
if mode in {"backoff", "hurt", "refusing"} and blocked_until > now:
|
||||
return "relationship_backoff"
|
||||
projection = decision.to_dict() if hasattr(decision, "to_dict") else dict(decision or {})
|
||||
blocker = _single_line(projection.get("blocker"), 40)
|
||||
if blocker:
|
||||
return f"expression_{blocker}"
|
||||
if _safe_int(projection.get("proactive_budget"), 0, 0) <= 0:
|
||||
return "expression_proactive_budget_zero"
|
||||
except Exception:
|
||||
return "expression_decision_unavailable"
|
||||
collision_window = max(
|
||||
10,
|
||||
min(
|
||||
|
|
@ -1980,10 +2019,29 @@ class ProactiveMessageMixin:
|
|||
labeler = getattr(self, "_private_user_role_label", None)
|
||||
label = labeler(role) if callable(labeler) else ("主要用户" if role == "owner" else "次要用户")
|
||||
profile = self._relationship_profile(user if isinstance(user, dict) else {})
|
||||
level = _single_line(profile.get("level"), 20) or "熟悉"
|
||||
preference = _single_line(profile.get("preference"), 20) or "普通"
|
||||
expression_builder = getattr(self, "_build_expression_decision_for_user", None)
|
||||
expression: dict[str, Any] = {}
|
||||
if callable(expression_builder):
|
||||
try:
|
||||
decision = expression_builder(
|
||||
user if isinstance(user, dict) else {},
|
||||
proactive_candidate={"eligible": True, "daily_allowance": 1},
|
||||
)
|
||||
expression = decision.to_dict() if hasattr(decision, "to_dict") else dict(decision or {})
|
||||
except Exception:
|
||||
expression = {}
|
||||
note = _single_line(user.get("proactive_boundary_note"), 80) if isinstance(user, dict) else ""
|
||||
parts = [f"当前用户角色:{label}", f"关系熟悉度:{level}", f"互动偏好:{preference}"]
|
||||
parts = [
|
||||
f"当前用户角色:{label}",
|
||||
f"长期关系:{_single_line(profile.get('stage_label'), 20) or '初识'}",
|
||||
f"当前互动表达:{_single_line(profile.get('interaction_label'), 20) or '放松'}",
|
||||
]
|
||||
if expression:
|
||||
parts.append(
|
||||
f"统一表达决策:档位={_single_line(expression.get('expression_band'), 20) or 'relaxed'},"
|
||||
f"语气={_single_line(expression.get('tone'), 20) or 'steady'},"
|
||||
f"追问={'允许' if expression.get('followup') else '关闭'}"
|
||||
)
|
||||
if note:
|
||||
parts.append(f"用户级备注:{note}")
|
||||
return ";".join(parts)
|
||||
|
|
@ -2546,6 +2604,7 @@ class ProactiveMessageMixin:
|
|||
temperature_label = _single_line(temperature.get("label"), 60)
|
||||
temperature_score = _safe_float(temperature.get("score"), 0.55)
|
||||
motivation = readiness.get("motivation") if isinstance(readiness.get("motivation"), dict) else {}
|
||||
expression_decision = readiness.get("expression_decision") if isinstance(readiness.get("expression_decision"), dict) else {}
|
||||
|
||||
lines = ["【这次主动的内在约束】"]
|
||||
troubleshooting_hint = self._proactive_troubleshooting_request_hint(user)
|
||||
|
|
@ -2708,7 +2767,7 @@ class ProactiveMessageMixin:
|
|||
) -> str:
|
||||
state = self.data.get("daily_state", {})
|
||||
last_user_message = _single_line(user.get("last_user_message"), 80)
|
||||
profile = self._relationship_profile(user)
|
||||
relationship_fact = self._format_proactive_relationship_fact(user)
|
||||
tts_prompt = self._get_tts_prompt_text(target)
|
||||
req = self._voice_requirement_profile(target)
|
||||
state_hint = self._format_state_for_framework_prompt(
|
||||
|
|
@ -2726,7 +2785,7 @@ class ProactiveMessageMixin:
|
|||
- 对方称呼:{name}
|
||||
- 主动原因:{reason}
|
||||
- 最近一句用户消息:{last_user_message or "(暂无)"}
|
||||
- 关系画像:{profile['level']}|偏好:{profile['preference']}
|
||||
- 陪伴表达:{relationship_fact}
|
||||
- 当前状态底色:{state_hint or "今天整体比较平稳。"}
|
||||
- 当前会话 TTS 规则:{tts_prompt or "(当前没有额外 TTS 提示词,就按人格自己的语音习惯来)"}
|
||||
- 当前语音格式重点:{req['summary']}
|
||||
|
|
@ -3301,6 +3360,15 @@ class ProactiveMessageMixin:
|
|||
context_owner=user if isinstance(user, dict) else None,
|
||||
stage_owner=user if isinstance(user, dict) else None,
|
||||
)
|
||||
if expression_decision:
|
||||
lines.append(
|
||||
"统一表达:"
|
||||
f"档位={_single_line(expression_decision.get('expression_band'), 24) or 'relaxed'};"
|
||||
f"语气={_single_line(expression_decision.get('tone'), 24) or 'steady'};"
|
||||
f"距离={_single_line(expression_decision.get('address_style'), 24) or 'neutral'};"
|
||||
f"追问={'允许' if expression_decision.get('followup') else '关闭'};"
|
||||
f"主动额度={_safe_int(expression_decision.get('proactive_budget'), 0, 0)}。"
|
||||
)
|
||||
if expression_voice:
|
||||
reply_style = f"{reply_style}\n\n{expression_voice}".strip()
|
||||
else:
|
||||
|
|
@ -6651,7 +6719,7 @@ Output:
|
|||
persona = self._get_default_persona_prompt()
|
||||
state = self.data.get("daily_state", {})
|
||||
last_user_message = _single_line(user.get("last_user_message"), 80)
|
||||
profile = self._relationship_profile(user)
|
||||
relationship_fact = self._format_proactive_relationship_fact(user)
|
||||
tts_prompt = self._get_tts_prompt_text(target)
|
||||
prompt = f"""
|
||||
你正在替角色写一条马上要发出去的语音。这条语音是真的会被 TTS 念出来,不是文字陪聊。
|
||||
|
|
@ -6661,7 +6729,7 @@ Output:
|
|||
|
||||
【对象】
|
||||
称呼:{name}
|
||||
关系:{profile['level']}|偏好:{profile['preference']}
|
||||
陪伴表达:{relationship_fact}
|
||||
最近一句:{last_user_message or '(暂无)'}
|
||||
|
||||
【主动原因】
|
||||
|
|
|
|||
|
|
@ -3245,7 +3245,7 @@ class QzoneMixin(QzoneMediaMixin):
|
|||
self,
|
||||
*,
|
||||
user_snapshot: dict[str, Any] | None = None,
|
||||
relationship_state: dict[str, Any] | None = None,
|
||||
interaction_state: dict[str, Any] | None = None,
|
||||
intent: dict[str, Any] | None = None,
|
||||
) -> None:
|
||||
if not (
|
||||
|
|
@ -3254,10 +3254,10 @@ class QzoneMixin(QzoneMediaMixin):
|
|||
and getattr(self, "enable_qzone_emotional_vent_publish", False)
|
||||
):
|
||||
return
|
||||
rel_state = relationship_state if isinstance(relationship_state, dict) else {}
|
||||
mood_score = abs(_safe_int(rel_state.get("mood_score"), 0, -100, 100))
|
||||
interaction = interaction_state if isinstance(interaction_state, dict) else {}
|
||||
event_intensity = _safe_int((intent or {}).get("emotion_intensity"), 0, 0, 100)
|
||||
threshold = _safe_int(getattr(self, "qzone_emotional_vent_threshold", 90), 90, 40, 100)
|
||||
if mood_score < threshold:
|
||||
if event_intensity < threshold or interaction.get("expression_band") not in {"avoidant", "hurt"}:
|
||||
return
|
||||
if isinstance(user_snapshot, dict):
|
||||
role_getter = getattr(self, "_private_user_role", None)
|
||||
|
|
@ -3267,9 +3267,9 @@ class QzoneMixin(QzoneMediaMixin):
|
|||
role = ""
|
||||
if role != "owner":
|
||||
logger.info(
|
||||
"[PrivateCompanion] 公开心情动态跳过: user_role=%s score=%s",
|
||||
"[PrivateCompanion] 公开心情动态跳过: user_role=%s intensity=%s",
|
||||
role or "friend",
|
||||
mood_score,
|
||||
event_intensity,
|
||||
)
|
||||
return
|
||||
now = _now_ts()
|
||||
|
|
@ -3279,7 +3279,7 @@ class QzoneMixin(QzoneMediaMixin):
|
|||
state = self.data["qzone_integration"]
|
||||
cooldown = max(4, _safe_int(getattr(self, "qzone_emotional_vent_cooldown_hours", 72), 72, 4, 336)) * 3600
|
||||
if now - _safe_float(state.get("last_emotional_vent_at"), 0) < cooldown:
|
||||
logger.info("[PrivateCompanion] 公开心情动态跳过: cooldown score=%s", mood_score)
|
||||
logger.info("[PrivateCompanion] 公开心情动态跳过: cooldown intensity=%s", event_intensity)
|
||||
return
|
||||
block_reason = self._qzone_auto_publish_block_reason(state, now=now)
|
||||
if block_reason:
|
||||
|
|
@ -3315,7 +3315,7 @@ class QzoneMixin(QzoneMediaMixin):
|
|||
)
|
||||
reason = _single_line(
|
||||
self._qzone_relationship_safe_source(
|
||||
(rel_state or {}).get("last_hurt_reason") or (intent or {}).get("emotion_reason"),
|
||||
interaction.get("reason") or (intent or {}).get("emotion_reason"),
|
||||
source="qzone.emotional_vent.reason",
|
||||
),
|
||||
80,
|
||||
|
|
@ -3403,7 +3403,7 @@ class QzoneMixin(QzoneMediaMixin):
|
|||
else:
|
||||
state.pop("last_emotional_vent_image_fallback", None)
|
||||
self._qzone_clear_pending_publish_assets(state, "emotional_vent")
|
||||
logger.info("[PrivateCompanion] 公开心情动态已发布: score=%s text=%s", mood_score, _single_line(result.get("text") or text, 120))
|
||||
logger.info("[PrivateCompanion] 公开心情动态已发布: intensity=%s text=%s", event_intensity, _single_line(result.get("text") or text, 120))
|
||||
else:
|
||||
state["last_emotional_vent_failed_at"] = now
|
||||
state["last_emotional_vent_status"] = f"failed:{_single_line(result.get('message'), 80)}"
|
||||
|
|
|
|||
350
relationship_ledger.py
普通文件
350
relationship_ledger.py
普通文件
|
|
@ -0,0 +1,350 @@
|
|||
"""Deterministic long-term companion relationship settlement.
|
||||
|
||||
This module owns the bounded relationship score. It deliberately does not
|
||||
grant identity, owner, memory, proactive, tool, or P4 authority.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from copy import deepcopy
|
||||
from datetime import datetime, timezone
|
||||
from hashlib import sha256
|
||||
from math import isfinite
|
||||
from typing import Any
|
||||
|
||||
try:
|
||||
from .relationship_policy import (
|
||||
RELATIONSHIP_SCORE_MAX,
|
||||
RELATIONSHIP_SCORE_MIN,
|
||||
normalize_relationship_stage_policy,
|
||||
relationship_stage_for_score,
|
||||
)
|
||||
except ImportError: # pragma: no cover - direct-module test compatibility
|
||||
from relationship_policy import (
|
||||
RELATIONSHIP_SCORE_MAX,
|
||||
RELATIONSHIP_SCORE_MIN,
|
||||
normalize_relationship_stage_policy,
|
||||
relationship_stage_for_score,
|
||||
)
|
||||
|
||||
|
||||
OWNER_EXCLUSIVE_MODE = "owner_exclusive"
|
||||
NORMAL_RELATIONSHIP_MODE = "normal"
|
||||
DEFAULT_POSITIVE_DAILY_CAP = 12
|
||||
DEFAULT_EVENT_WINDOW_SECONDS = 30 * 60
|
||||
DEFAULT_DECAY_GRACE_DAYS = 3
|
||||
|
||||
|
||||
def normalize_relationship_mode(value: Any, role: Any) -> str:
|
||||
mode = str(value or "").strip().lower()
|
||||
normalized_role = str(role or "").strip().lower()
|
||||
if mode == OWNER_EXCLUSIVE_MODE and normalized_role == "owner":
|
||||
return OWNER_EXCLUSIVE_MODE
|
||||
return NORMAL_RELATIONSHIP_MODE
|
||||
|
||||
|
||||
def is_owner_exclusive(user: Any) -> bool:
|
||||
if not isinstance(user, dict):
|
||||
return False
|
||||
return normalize_relationship_mode(user.get("relationship_mode"), user.get("relationship_role")) == OWNER_EXCLUSIVE_MODE
|
||||
|
||||
|
||||
def apply_relationship_event(
|
||||
user: Any,
|
||||
delta: Any,
|
||||
*,
|
||||
reason_code: Any,
|
||||
now: Any = None,
|
||||
event_id: Any = None,
|
||||
positive_daily_cap: int = DEFAULT_POSITIVE_DAILY_CAP,
|
||||
event_window_seconds: int = DEFAULT_EVENT_WINDOW_SECONDS,
|
||||
positive_event_cap: int = 4,
|
||||
negative_event_cap: int = 12,
|
||||
) -> dict[str, Any]:
|
||||
"""Settle one auditable relationship event into the bounded score."""
|
||||
if not isinstance(user, dict):
|
||||
return _result(False, "invalid_user")
|
||||
numeric_delta = _integer(delta)
|
||||
if numeric_delta is None or numeric_delta == 0:
|
||||
return _result(False, "invalid_delta")
|
||||
reason = _reason(reason_code)
|
||||
if not reason:
|
||||
return _result(False, "missing_reason")
|
||||
ts = _timestamp(now)
|
||||
role = str(user.get("relationship_role") or "").strip().lower()
|
||||
mode = normalize_relationship_mode(user.get("relationship_mode"), role)
|
||||
user["relationship_mode"] = mode
|
||||
if mode == OWNER_EXCLUSIVE_MODE:
|
||||
return _result(False, "owner_exclusive_frozen", score=_score(user.get("relationship_score")))
|
||||
|
||||
ledger = user.setdefault("relationship_ledger", [])
|
||||
if not isinstance(ledger, list):
|
||||
ledger = []
|
||||
user["relationship_ledger"] = ledger
|
||||
dedupe_key = _event_key(reason, ts, event_id, max(60, int(event_window_seconds or DEFAULT_EVENT_WINDOW_SECONDS)))
|
||||
if any(isinstance(item, dict) and item.get("event_key") == dedupe_key for item in ledger[-200:]):
|
||||
return _result(False, "duplicate_event", score=_score(user.get("relationship_score")))
|
||||
|
||||
positive_cap = max(1, min(30, int(positive_event_cap or 4)))
|
||||
negative_cap = max(1, min(60, int(negative_event_cap or 12)))
|
||||
requested = max(-negative_cap, min(positive_cap, numeric_delta))
|
||||
before = _score(user.get("relationship_score"))
|
||||
if requested > 0 and before >= 900:
|
||||
requested = max(1, (requested + 1) // 2)
|
||||
elif requested > 0 and before >= 600:
|
||||
requested = max(1, (requested * 3 + 3) // 4)
|
||||
applied = requested
|
||||
day_key = datetime.fromtimestamp(ts, tz=timezone.utc).date().isoformat()
|
||||
totals = user.setdefault("relationship_daily_totals", {})
|
||||
if not isinstance(totals, dict) or totals.get("day") != day_key:
|
||||
totals = {"day": day_key, "positive": 0, "negative": 0}
|
||||
user["relationship_daily_totals"] = totals
|
||||
if applied > 0:
|
||||
raw_daily_cap = DEFAULT_POSITIVE_DAILY_CAP if positive_daily_cap is None else positive_daily_cap
|
||||
cap = max(0, min(120, int(raw_daily_cap)))
|
||||
remaining = max(0, cap - _bounded_int(totals.get("positive"), 0, 0, cap))
|
||||
applied = min(applied, remaining)
|
||||
if applied <= 0:
|
||||
return _result(False, "positive_daily_cap", score=_score(user.get("relationship_score")))
|
||||
|
||||
after = max(RELATIONSHIP_SCORE_MIN, min(RELATIONSHIP_SCORE_MAX, before + applied))
|
||||
applied = after - before
|
||||
if applied == 0:
|
||||
return _result(False, "score_bound", score=before)
|
||||
user["relationship_score"] = after
|
||||
if applied > 0:
|
||||
totals["positive"] = _bounded_int(totals.get("positive"), 0, 0, 120) + applied
|
||||
user["relationship_last_effective_at"] = ts
|
||||
else:
|
||||
totals["negative"] = _bounded_int(totals.get("negative"), 0, -120, 0) + applied
|
||||
entry = {
|
||||
"event_key": dedupe_key,
|
||||
"reason_code": reason,
|
||||
"delta": applied,
|
||||
"score_before": before,
|
||||
"score_after": after,
|
||||
"created_at": ts,
|
||||
}
|
||||
ledger.append(entry)
|
||||
if len(ledger) > 200:
|
||||
del ledger[:-200]
|
||||
return _result(True, "applied", score=after, delta=applied, entry=deepcopy(entry))
|
||||
|
||||
|
||||
def apply_natural_relationship_decay(
|
||||
user: Any,
|
||||
*,
|
||||
now: Any = None,
|
||||
policy: Any = None,
|
||||
grace_days: int = DEFAULT_DECAY_GRACE_DAYS,
|
||||
early_rate: int = 2,
|
||||
middle_rate: int = 5,
|
||||
late_rate: int = 8,
|
||||
) -> dict[str, Any]:
|
||||
"""Idempotently decay positive scores toward zero by inactive calendar day."""
|
||||
if not isinstance(user, dict):
|
||||
return _result(False, "invalid_user")
|
||||
ts = _timestamp(now)
|
||||
if is_owner_exclusive(user):
|
||||
return _result(False, "owner_exclusive_frozen", score=_score(user.get("relationship_score")))
|
||||
score = _score(user.get("relationship_score"))
|
||||
if score <= 0:
|
||||
return _result(False, "non_positive_score", score=score)
|
||||
last_effective = _finite_number(user.get("relationship_last_effective_at"))
|
||||
if not last_effective:
|
||||
last_effective = _finite_number(user.get("last_activity_at")) or _finite_number(user.get("last_seen"))
|
||||
if not last_effective or ts <= last_effective:
|
||||
return _result(False, "no_inactive_window", score=score)
|
||||
|
||||
today = datetime.fromtimestamp(ts, tz=timezone.utc).date()
|
||||
last_day = datetime.fromtimestamp(last_effective, tz=timezone.utc).date()
|
||||
inactive_days = max(0, (today - last_day).days)
|
||||
grace = max(0, min(30, int(grace_days or 0)))
|
||||
if inactive_days <= grace:
|
||||
return _result(False, "within_grace", score=score)
|
||||
settled_text = str(user.get("relationship_decay_settled_day") or "").strip()
|
||||
try:
|
||||
settled_day = datetime.fromisoformat(settled_text).date() if settled_text else last_day
|
||||
except ValueError:
|
||||
settled_day = last_day
|
||||
start_offset = max(grace + 1, (settled_day - last_day).days + 1)
|
||||
if start_offset > inactive_days:
|
||||
return _result(False, "already_settled", score=score)
|
||||
|
||||
rates = (
|
||||
max(0, min(30, int(early_rate or 0))),
|
||||
max(0, min(30, int(middle_rate or 0))),
|
||||
max(0, min(30, int(late_rate or 0))),
|
||||
)
|
||||
requested = sum(_decay_for_inactive_day(day, rates=rates) for day in range(start_offset, inactive_days + 1))
|
||||
if requested <= 0:
|
||||
user["relationship_decay_settled_day"] = today.isoformat()
|
||||
return _result(False, "no_decay", score=score)
|
||||
before_projection = relationship_stage_for_score(score, policy)
|
||||
candidate = max(0, score - requested)
|
||||
candidate = _apply_stage_hysteresis(user, score, candidate, ts, policy, before_projection)
|
||||
applied = score - candidate
|
||||
user["relationship_decay_settled_day"] = today.isoformat()
|
||||
if applied <= 0:
|
||||
return _result(False, "stage_hysteresis", score=score)
|
||||
user["relationship_score"] = candidate
|
||||
ledger = user.setdefault("relationship_ledger", [])
|
||||
if not isinstance(ledger, list):
|
||||
ledger = []
|
||||
user["relationship_ledger"] = ledger
|
||||
entry = {
|
||||
"event_key": f"natural_decay:{today.isoformat()}",
|
||||
"reason_code": "natural_decay",
|
||||
"delta": -applied,
|
||||
"score_before": score,
|
||||
"score_after": candidate,
|
||||
"created_at": ts,
|
||||
"inactive_days": inactive_days,
|
||||
}
|
||||
ledger.append(entry)
|
||||
if len(ledger) > 200:
|
||||
del ledger[:-200]
|
||||
return _result(True, "applied", score=candidate, delta=-applied, entry=deepcopy(entry))
|
||||
|
||||
|
||||
def relationship_ledger_summary(user: Any, *, limit: int = 12) -> dict[str, Any]:
|
||||
if not isinstance(user, dict):
|
||||
return {"items": [], "trend": "unknown"}
|
||||
ledger = user.get("relationship_ledger")
|
||||
items = [deepcopy(item) for item in ledger if isinstance(item, dict)] if isinstance(ledger, list) else []
|
||||
recent = items[-max(1, min(50, int(limit or 12))):]
|
||||
total = sum(_integer(item.get("delta")) or 0 for item in recent)
|
||||
trend = "rising" if total > 0 else "cooling" if total < 0 else "steady"
|
||||
return {"items": recent, "trend": trend, "recent_delta": total}
|
||||
|
||||
|
||||
def record_manual_relationship_change(
|
||||
user: Any,
|
||||
before: Any,
|
||||
after: Any,
|
||||
*,
|
||||
now: Any = None,
|
||||
reason_code: Any = "administrator_manual",
|
||||
) -> dict[str, Any]:
|
||||
"""Record an already-authorized exact admin adjustment without re-settling it."""
|
||||
if not isinstance(user, dict):
|
||||
return _result(False, "invalid_user")
|
||||
before_score = _score(before)
|
||||
after_score = _score(after)
|
||||
if before_score == after_score:
|
||||
return _result(False, "unchanged", score=after_score)
|
||||
ts = _timestamp(now)
|
||||
reason = _reason(reason_code) or "administrator_manual"
|
||||
ledger = user.setdefault("relationship_ledger", [])
|
||||
if not isinstance(ledger, list):
|
||||
ledger = []
|
||||
user["relationship_ledger"] = ledger
|
||||
entry = {
|
||||
"event_key": _event_key(reason, ts, f"manual:{ts}:{before_score}:{after_score}", 60),
|
||||
"reason_code": reason,
|
||||
"delta": after_score - before_score,
|
||||
"score_before": before_score,
|
||||
"score_after": after_score,
|
||||
"created_at": ts,
|
||||
"source": "administrator",
|
||||
}
|
||||
ledger.append(entry)
|
||||
if len(ledger) > 200:
|
||||
del ledger[:-200]
|
||||
user["relationship_last_effective_at"] = ts
|
||||
user["relationship_decay_settled_day"] = ""
|
||||
return _result(True, "recorded", score=after_score, delta=after_score - before_score, entry=deepcopy(entry))
|
||||
|
||||
|
||||
def _apply_stage_hysteresis(user: dict[str, Any], before: int, candidate: int, ts: float, policy: Any, before_projection: dict[str, Any]) -> int:
|
||||
after_projection = relationship_stage_for_score(candidate, policy)
|
||||
before_index = int(before_projection.get("stage_index") or 0)
|
||||
after_index = int(after_projection.get("stage_index") or 0)
|
||||
if after_index >= before_index:
|
||||
return candidate
|
||||
stages = normalize_relationship_stage_policy(policy)
|
||||
last_drop = _finite_number(user.get("relationship_last_decay_stage_drop_at")) or 0.0
|
||||
if last_drop and ts - last_drop < 7 * 86400:
|
||||
current_min = int(stages[before_index]["min"])
|
||||
return max(candidate, current_min)
|
||||
immediate_index = max(0, before_index - 1)
|
||||
limited = max(candidate, int(stages[immediate_index]["min"]))
|
||||
if relationship_stage_for_score(limited, policy).get("stage_index") < before_index:
|
||||
user["relationship_last_decay_stage_drop_at"] = ts
|
||||
return limited
|
||||
|
||||
|
||||
def _decay_for_inactive_day(day: int, *, rates: tuple[int, int, int] = (2, 5, 8)) -> int:
|
||||
configured = ((7, rates[0]), (14, rates[1]), (10**9, rates[2]))
|
||||
for maximum, amount in configured:
|
||||
if day <= maximum:
|
||||
return amount
|
||||
return rates[2]
|
||||
|
||||
|
||||
def _event_key(reason: str, ts: float, event_id: Any, window_seconds: int) -> str:
|
||||
explicit = str(event_id or "").strip()
|
||||
source = explicit[:160] if explicit else f"{reason}:{int(ts // window_seconds)}"
|
||||
return sha256(source.encode("utf-8", errors="ignore")).hexdigest()[:24]
|
||||
|
||||
|
||||
def _reason(value: Any) -> str:
|
||||
text = "_".join(str(value or "").strip().lower().split())
|
||||
return "".join(ch for ch in text if ch.isalnum() or ch in {"_", "-"})[:48]
|
||||
|
||||
|
||||
def _score(value: Any) -> int:
|
||||
parsed = _integer(value)
|
||||
return max(RELATIONSHIP_SCORE_MIN, min(RELATIONSHIP_SCORE_MAX, parsed if parsed is not None else 0))
|
||||
|
||||
|
||||
def _integer(value: Any) -> int | None:
|
||||
if isinstance(value, bool):
|
||||
return None
|
||||
if isinstance(value, int):
|
||||
return value
|
||||
if isinstance(value, float) and isfinite(value):
|
||||
return int(value)
|
||||
if isinstance(value, str):
|
||||
try:
|
||||
return int(value.strip())
|
||||
except ValueError:
|
||||
return None
|
||||
return None
|
||||
|
||||
|
||||
def _finite_number(value: Any) -> float | None:
|
||||
if isinstance(value, bool) or not isinstance(value, (int, float)):
|
||||
return None
|
||||
number = float(value)
|
||||
return number if isfinite(number) else None
|
||||
|
||||
|
||||
def _timestamp(value: Any) -> float:
|
||||
number = _finite_number(value)
|
||||
return number if number is not None and number > 0 else datetime.now(tz=timezone.utc).timestamp()
|
||||
|
||||
|
||||
def _bounded_int(value: Any, default: int, minimum: int, maximum: int) -> int:
|
||||
parsed = _integer(value)
|
||||
return max(minimum, min(maximum, parsed if parsed is not None else default))
|
||||
|
||||
|
||||
def _result(changed: bool, code: str, *, score: int | None = None, delta: int = 0, entry: dict[str, Any] | None = None) -> dict[str, Any]:
|
||||
result: dict[str, Any] = {"changed": bool(changed), "code": code, "delta": int(delta)}
|
||||
if score is not None:
|
||||
result["score"] = int(score)
|
||||
if entry is not None:
|
||||
result["entry"] = entry
|
||||
return result
|
||||
|
||||
|
||||
__all__ = [
|
||||
"OWNER_EXCLUSIVE_MODE",
|
||||
"NORMAL_RELATIONSHIP_MODE",
|
||||
"apply_natural_relationship_decay",
|
||||
"apply_relationship_event",
|
||||
"is_owner_exclusive",
|
||||
"normalize_relationship_mode",
|
||||
"record_manual_relationship_change",
|
||||
"relationship_ledger_summary",
|
||||
]
|
||||
|
|
@ -43,7 +43,7 @@ class CompanionConcurrencyStaticTests(unittest.TestCase):
|
|||
self.assertIn("async def _temporarily_release_data_lock", source)
|
||||
self.assertGreaterEqual(source.count("async with self._temporarily_release_data_lock()"), 12)
|
||||
self.assertIn('label="refresh_group_episode"', source)
|
||||
self.assertIn('label="refresh_persona_relationship_inbound"', source)
|
||||
self.assertNotIn('label="refresh_persona_relationship_inbound"', source)
|
||||
|
||||
def test_untracked_main_background_tasks_are_not_left_in_message_paths(self):
|
||||
source = (ROOT / "main.py").read_text(encoding="utf-8")
|
||||
|
|
|
|||
|
|
@ -423,7 +423,7 @@ class P4P6ParityTests(unittest.TestCase):
|
|||
self.assertTrue(forbidden.isdisjoint(string_constants))
|
||||
self.assertIn("relationship_basis", string_constants)
|
||||
self.assertIn("memory_phase", string_constants)
|
||||
self.assertIn("reply_temperature", string_constants)
|
||||
self.assertIn("expression_decision", string_constants)
|
||||
|
||||
def test_extension_api_does_not_expose_p4_effect_or_live_authority(self) -> None:
|
||||
source = (ROOT / "main.py").read_text(encoding="utf-8")
|
||||
|
|
|
|||
|
|
@ -52,7 +52,7 @@ class ReplyTemperatureTests(unittest.TestCase):
|
|||
self.assertNotIn("busy meeting", repr(constrained))
|
||||
self.assertNotIn("do not reply", repr(constrained))
|
||||
|
||||
def test_live_gate_wires_only_bounded_advisory_inputs_to_temperature(self) -> None:
|
||||
def test_live_gate_wires_bounded_state_only_to_unified_expression_decision(self) -> None:
|
||||
source = (ROOT / "main.py").read_text(encoding="utf-8")
|
||||
tree = ast.parse(source)
|
||||
gate = next(
|
||||
|
|
@ -60,20 +60,20 @@ class ReplyTemperatureTests(unittest.TestCase):
|
|||
if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef))
|
||||
and node.name == "enforce_p4_live_confinement_before_enrichment"
|
||||
)
|
||||
calls = [
|
||||
legacy_calls = [
|
||||
node for node in ast.walk(gate)
|
||||
if isinstance(node, ast.Call) and isinstance(node.func, ast.Name)
|
||||
and node.func.id == "compose_reply_temperature"
|
||||
]
|
||||
self.assertEqual(1, len(calls))
|
||||
self.assertTrue(any(keyword.arg is None for keyword in calls[0].keywords))
|
||||
self.assertEqual([], legacy_calls)
|
||||
self.assertIn("_private_companion_expression_decision", source)
|
||||
self.assertNotIn("_private_companion_reply_temperature", source)
|
||||
helper = next(
|
||||
node for node in ast.walk(tree)
|
||||
if isinstance(node, ast.FunctionDef) and node.name == "_bounded_p4_reply_temperature_signals"
|
||||
if isinstance(node, ast.FunctionDef) and node.name == "_bounded_expression_state_signals"
|
||||
)
|
||||
constants = {node.value for node in ast.walk(helper) if isinstance(node, ast.Constant) and type(node.value) is str}
|
||||
self.assertTrue({"energy", "mood", "schedule", "context"}.issubset(constants))
|
||||
self.assertNotIn("_private_companion_reply_temperature", constants)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
|
|
|||
|
|
@ -0,0 +1,411 @@
|
|||
from __future__ import annotations
|
||||
|
||||
from copy import deepcopy
|
||||
import ast
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import unittest
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT))
|
||||
|
||||
from companion_interaction_expression import ( # noqa: E402
|
||||
EXPRESSION_CONTRACT_VERSION,
|
||||
ExpressionBand,
|
||||
ExpressionDecision,
|
||||
ExpressionInput,
|
||||
allowed_expression_bands,
|
||||
build_expression_decision,
|
||||
current_interaction_projection,
|
||||
expression_decision_prompt,
|
||||
resolve_expression_decision,
|
||||
)
|
||||
|
||||
|
||||
class Req028ExpressionContractTests(unittest.TestCase):
|
||||
def test_all_seven_bands_are_supported_for_owner_exclusive(self) -> None:
|
||||
for band in ExpressionBand:
|
||||
with self.subTest(band=band.value):
|
||||
decision = build_expression_decision(
|
||||
{
|
||||
"relationship_role": "owner",
|
||||
"relationship_mode": "owner_exclusive",
|
||||
"current_interaction": band.value,
|
||||
"administrator_override": band.value,
|
||||
}
|
||||
)
|
||||
self.assertEqual(band.value, decision.expression_band)
|
||||
self.assertIsNone(decision.blocker)
|
||||
|
||||
def test_owner_only_bands_are_downgraded_for_regular_users(self) -> None:
|
||||
for band in ("close", "affectionate"):
|
||||
with self.subTest(band=band):
|
||||
decision = build_expression_decision(
|
||||
{
|
||||
"relationship_role": "friend",
|
||||
"relationship_mode": "owner_exclusive",
|
||||
"current_interaction": band,
|
||||
}
|
||||
)
|
||||
self.assertEqual("warm", decision.expression_band)
|
||||
self.assertIn("owner_role_required", decision.reason_codes)
|
||||
|
||||
def test_owner_role_can_use_owner_only_interaction_without_exclusive_mode(self) -> None:
|
||||
decision = build_expression_decision(
|
||||
{"relationship_role": "owner", "relationship_mode": "normal", "current_interaction": "affectionate"}
|
||||
)
|
||||
self.assertEqual("affectionate", decision.expression_band)
|
||||
self.assertNotIn("owner_role_required", decision.reason_codes)
|
||||
|
||||
def test_p4_and_contact_boundaries_precede_administrator_override(self) -> None:
|
||||
blocked = build_expression_decision(
|
||||
{
|
||||
"relationship_role": "owner",
|
||||
"relationship_mode": "owner_exclusive",
|
||||
"administrator_override": "affectionate",
|
||||
"safety_constraints": {"contact_boundary": True, "p4_blocked": True},
|
||||
}
|
||||
)
|
||||
self.assertEqual("p4_safety", blocked.blocker)
|
||||
self.assertEqual("p4_blocked", blocked.safety_mode)
|
||||
self.assertEqual("avoidant", blocked.expression_band)
|
||||
self.assertEqual(0, blocked.proactive_budget)
|
||||
|
||||
boundary = build_expression_decision(
|
||||
{
|
||||
"relationship_role": "owner",
|
||||
"relationship_mode": "owner_exclusive",
|
||||
"administrator_override": "affectionate",
|
||||
"safety_constraints": {"contact_boundary": {"active": True}},
|
||||
}
|
||||
)
|
||||
self.assertEqual("contact_boundary", boundary.blocker)
|
||||
self.assertEqual("avoidant", boundary.expression_band)
|
||||
|
||||
passive_reply = build_expression_decision(
|
||||
{
|
||||
"relationship_role": "owner",
|
||||
"relationship_mode": "owner_exclusive",
|
||||
"administrator_override": "affectionate",
|
||||
"proactive_candidate": {"eligible": True, "daily_allowance": 5},
|
||||
"safety_constraints": {
|
||||
"contact_boundary": {"active": True},
|
||||
"passive_reengagement": True,
|
||||
},
|
||||
}
|
||||
)
|
||||
self.assertIsNone(passive_reply.blocker)
|
||||
self.assertEqual("contact_boundary_passive", passive_reply.safety_mode)
|
||||
self.assertEqual("avoidant", passive_reply.expression_band)
|
||||
self.assertEqual(0, passive_reply.proactive_budget)
|
||||
self.assertFalse(passive_reply.followup)
|
||||
self.assertIn("contact_boundary_passive_reengagement", passive_reply.reason_codes)
|
||||
|
||||
capped = build_expression_decision(
|
||||
{
|
||||
"relationship_role": "owner",
|
||||
"relationship_mode": "owner_exclusive",
|
||||
"current_interaction": "affectionate",
|
||||
"safety_constraints": {"p4_warmth_cap": "neutral"},
|
||||
}
|
||||
)
|
||||
self.assertEqual("relaxed", capped.expression_band)
|
||||
self.assertIn("p4_warmth_cap_applied", capped.reason_codes)
|
||||
|
||||
def test_is_deterministic_and_has_no_input_mutation_or_persistence_effect(self) -> None:
|
||||
payload = {
|
||||
"relationship_score": 700,
|
||||
"relationship_role": "owner",
|
||||
"relationship_mode": "owner_exclusive",
|
||||
"current_interaction": {"band": "close"},
|
||||
"bot_state": {"energy": 88},
|
||||
"schedule": {"mode": "free"},
|
||||
"message_intent": {"kind": "question"},
|
||||
"proactive_candidate": {"eligible": True, "daily_allowance": 3},
|
||||
}
|
||||
before = deepcopy(payload)
|
||||
first = build_expression_decision(payload)
|
||||
second = resolve_expression_decision(payload)
|
||||
self.assertEqual(first, second)
|
||||
self.assertEqual(before, payload)
|
||||
self.assertIsInstance(first, ExpressionDecision)
|
||||
self.assertEqual(EXPRESSION_CONTRACT_VERSION, first.contract)
|
||||
self.assertEqual(3, first.proactive_budget)
|
||||
self.assertEqual("allowed", first.initiative)
|
||||
self.assertEqual("close", first.expression_band)
|
||||
|
||||
def test_invalid_or_maliciously_shaped_input_fails_safe_without_echoing_it(self) -> None:
|
||||
marker = "PRIVATE_CONTEXT_DO_NOT_ECHO"
|
||||
decision = build_expression_decision(
|
||||
{
|
||||
"relationship_score": object(),
|
||||
"relationship_role": ["owner"],
|
||||
"relationship_mode": {"unexpected": "owner_exclusive"},
|
||||
"current_interaction": {"band": marker},
|
||||
"bot_state": "not-a-mapping",
|
||||
"schedule": [marker],
|
||||
"message_intent": marker,
|
||||
"proactive_candidate": {"eligible": "yes", "daily_allowance": 99},
|
||||
"safety_constraints": marker,
|
||||
"administrator_override": {"band": marker},
|
||||
}
|
||||
)
|
||||
self.assertEqual("relaxed", decision.expression_band)
|
||||
self.assertEqual(0, decision.proactive_budget)
|
||||
self.assertNotIn(marker, repr(decision))
|
||||
self.assertEqual("passive_only", decision.initiative)
|
||||
|
||||
def test_typed_input_is_accepted_and_decision_projection_is_detached(self) -> None:
|
||||
decision = build_expression_decision(
|
||||
ExpressionInput(current_interaction="warm", message_intent={"followup_allowed": False})
|
||||
)
|
||||
projection = decision.to_dict()
|
||||
projection["reason_codes"] = ("changed_only_in_projection",)
|
||||
self.assertEqual("warm", decision.expression_band)
|
||||
self.assertFalse(decision.followup)
|
||||
self.assertIn("intent_followup_suppressed", decision.reason_codes)
|
||||
self.assertNotIn("changed_only_in_projection", decision.reason_codes)
|
||||
|
||||
def test_long_term_relationship_remains_the_baseline_when_interaction_is_relaxed(self) -> None:
|
||||
decision = build_expression_decision(
|
||||
{
|
||||
"relationship_score": 900,
|
||||
"relationship_role": "friend",
|
||||
"current_interaction": "relaxed",
|
||||
"relationship_baseline": {
|
||||
"tone": "亲密、柔软、不过度黏人",
|
||||
"address_level": "使用双方已确认的昵称",
|
||||
"proactive_care_limit": 2,
|
||||
"soft_behaviors": {"allow_followup": True},
|
||||
},
|
||||
"proactive_candidate": {"eligible": True, "daily_allowance": 5},
|
||||
}
|
||||
)
|
||||
self.assertEqual("warm", decision.expression_band)
|
||||
self.assertEqual("亲密、柔软、不过度黏人", decision.tone)
|
||||
self.assertEqual("使用双方已确认的昵称", decision.address_style)
|
||||
self.assertEqual(2, decision.proactive_budget)
|
||||
self.assertIn("relationship_baseline_retained", decision.reason_codes)
|
||||
|
||||
def test_owner_exclusive_relationship_is_fixed_baseline_but_manual_interaction_can_adjust_it(self) -> None:
|
||||
baseline = build_expression_decision(
|
||||
{
|
||||
"relationship_role": "owner",
|
||||
"relationship_mode": "owner_exclusive",
|
||||
"current_interaction": "relaxed",
|
||||
}
|
||||
)
|
||||
adjusted = build_expression_decision(
|
||||
{
|
||||
"relationship_role": "owner",
|
||||
"relationship_mode": "owner_exclusive",
|
||||
"current_interaction": "relaxed",
|
||||
"administrator_override": "relaxed",
|
||||
}
|
||||
)
|
||||
self.assertEqual("close", baseline.expression_band)
|
||||
self.assertEqual("relaxed", adjusted.expression_band)
|
||||
self.assertIn("administrator_override_applied", adjusted.reason_codes)
|
||||
|
||||
def test_bot_state_and_schedule_change_the_single_expression_decision(self) -> None:
|
||||
baseline = build_expression_decision(
|
||||
{
|
||||
"current_interaction": "warm",
|
||||
"bot_state": {"energy": 80, "mood": "轻快"},
|
||||
"proactive_candidate": {"eligible": True, "daily_allowance": 3},
|
||||
}
|
||||
)
|
||||
constrained = build_expression_decision(
|
||||
{
|
||||
"current_interaction": "warm",
|
||||
"bot_state": {"energy": 18, "mood": "疲惫低落"},
|
||||
"schedule": {"label": "忙碌会议"},
|
||||
"proactive_candidate": {"eligible": True, "daily_allowance": 3},
|
||||
}
|
||||
)
|
||||
self.assertGreater(baseline.warmth, constrained.warmth)
|
||||
self.assertTrue(baseline.followup)
|
||||
self.assertFalse(constrained.followup)
|
||||
self.assertEqual("brief", constrained.response_length)
|
||||
self.assertEqual(0, constrained.proactive_budget)
|
||||
self.assertIn("low_energy_expression_cap", constrained.reason_codes)
|
||||
self.assertIn("down_mood_expression_cap", constrained.reason_codes)
|
||||
self.assertIn("schedule_proactive_suppressed", constrained.reason_codes)
|
||||
|
||||
def test_page_projection_gates_owner_only_bands_and_expires_manual_override(self) -> None:
|
||||
friend = current_interaction_projection(
|
||||
{"expression_band": "affectionate", "source": "manual", "updated_at": 10},
|
||||
relationship_role="friend",
|
||||
)
|
||||
owner = current_interaction_projection(
|
||||
{"expression_band": "affectionate", "source": "manual", "expires_at": 20},
|
||||
relationship_role="owner",
|
||||
relationship_mode="owner_exclusive",
|
||||
now=30,
|
||||
)
|
||||
self.assertEqual("warm", friend["expression_band"])
|
||||
self.assertEqual(5, len(allowed_expression_bands("friend", "normal")))
|
||||
self.assertEqual(7, len(allowed_expression_bands("owner", "normal")))
|
||||
self.assertEqual("relaxed", owner["expression_band"])
|
||||
self.assertFalse(owner["manual_override"])
|
||||
|
||||
def test_prompt_is_bounded_and_uses_single_decision(self) -> None:
|
||||
decision = build_expression_decision({"current_interaction": "lively"})
|
||||
prompt = expression_decision_prompt(decision)
|
||||
self.assertIn("活泼", prompt)
|
||||
self.assertNotIn("relationship_score", prompt)
|
||||
|
||||
def test_legacy_model_relationship_profile_has_no_active_runtime_consumer(self) -> None:
|
||||
source = (ROOT / "user_memory.py").read_text(encoding="utf-8")
|
||||
tree = ast.parse(source)
|
||||
owner = next(node for node in tree.body if isinstance(node, ast.ClassDef) and node.name == "UserMemoryMixin")
|
||||
profile_method = next(node for node in owner.body if isinstance(node, ast.FunctionDef) and node.name == "_relationship_profile")
|
||||
constants = {node.value for node in ast.walk(profile_method) if isinstance(node, ast.Constant) and isinstance(node.value, str)}
|
||||
self.assertNotIn("persona_relationship", constants)
|
||||
default_source = (ROOT / "constants.py").read_text(encoding="utf-8")
|
||||
self.assertNotIn('"persona_relationship": {}', default_source)
|
||||
self.assertNotIn('"relationship_state": {}', default_source)
|
||||
self.assertNotIn("def _refresh_persona_relationship", source)
|
||||
qzone_source = (ROOT / "qzone_integration.py").read_text(encoding="utf-8")
|
||||
self.assertNotIn("relationship_state: dict[str, Any]", qzone_source)
|
||||
self.assertNotIn("relationship_state=", source)
|
||||
self.assertNotIn("refresh_persona_relationship_inbound", (ROOT / "main.py").read_text(encoding="utf-8"))
|
||||
self.assertNotIn("refresh_persona_relationship_proactive", (ROOT / "daily_state.py").read_text(encoding="utf-8"))
|
||||
|
||||
def test_proactive_contact_boundary_is_independent_of_legacy_state_toggle(self) -> None:
|
||||
source = (ROOT / "proactive.py").read_text(encoding="utf-8")
|
||||
tree = ast.parse(source)
|
||||
owner = next(node for node in tree.body if isinstance(node, ast.ClassDef) and node.name == "ProactiveMixin")
|
||||
method = next(node for node in owner.body if isinstance(node, ast.FunctionDef) and node.name == "_current_relationship_gate_mode")
|
||||
constants = {node.value for node in ast.walk(method) if isinstance(node, ast.Constant) and isinstance(node.value, str)}
|
||||
self.assertNotIn("enable_relationship_state_machine", constants)
|
||||
module = ast.Module(
|
||||
body=[ast.ImportFrom(module="__future__", names=[ast.alias(name="annotations")], level=0), deepcopy(method)],
|
||||
type_ignores=[],
|
||||
)
|
||||
namespace: dict[str, object] = {}
|
||||
exec(compile(ast.fix_missing_locations(module), str(ROOT / "proactive.py"), "exec"), namespace)
|
||||
gate = namespace["_current_relationship_gate_mode"]
|
||||
host = type("Host", (), {"enable_relationship_state_machine": False})()
|
||||
self.assertEqual("backoff", gate(host, {"contact_preference": {"no_contact": True}}))
|
||||
|
||||
def test_proactive_chat_bridge_preflight_consumes_expression_budget_and_boundary(self) -> None:
|
||||
source = (ROOT / "proactive_message.py").read_text(encoding="utf-8")
|
||||
tree = ast.parse(source)
|
||||
owner = next(node for node in tree.body if isinstance(node, ast.ClassDef) and node.name == "ProactiveMessageMixin")
|
||||
method = next(node for node in owner.body if isinstance(node, ast.FunctionDef) and node.name == "_proactive_chat_bridge_preflight_block_reason")
|
||||
constants = {node.value for node in ast.walk(method) if isinstance(node, ast.Constant) and isinstance(node.value, str)}
|
||||
self.assertIn("_build_expression_decision_for_user", constants)
|
||||
self.assertIn("expression_proactive_budget_exhausted", constants)
|
||||
self.assertIn("expression_contact_boundary", constants)
|
||||
module = ast.Module(
|
||||
body=[ast.ImportFrom(module="__future__", names=[ast.alias(name="annotations")], level=0), deepcopy(method)],
|
||||
type_ignores=[],
|
||||
)
|
||||
|
||||
def safe_int(value: object, default: int = 0, *_args: object) -> int:
|
||||
try:
|
||||
return int(value) if not isinstance(value, bool) else default
|
||||
except (TypeError, ValueError):
|
||||
return default
|
||||
|
||||
namespace = {
|
||||
"_safe_float": lambda value, default=0.0: float(value) if isinstance(value, (int, float)) else default,
|
||||
"_safe_int": safe_int,
|
||||
"_single_line": lambda value, _limit=0: value.strip() if isinstance(value, str) else "",
|
||||
}
|
||||
exec(compile(ast.fix_missing_locations(module), str(ROOT / "proactive_message.py"), "exec"), namespace)
|
||||
preflight = namespace["_proactive_chat_bridge_preflight_block_reason"]
|
||||
|
||||
class Host:
|
||||
def _is_quiet_time(self) -> bool:
|
||||
return False
|
||||
|
||||
def _can_send_insomnia_night_message(self, _user: object) -> bool:
|
||||
return False
|
||||
|
||||
def _current_relationship_gate_mode(self, _user: object, *, now: float) -> str:
|
||||
return ""
|
||||
|
||||
def _current_emotion_gate_mode(self, _user: object, *, now: float) -> str:
|
||||
return ""
|
||||
|
||||
def _effective_user_daily_limit(self, _user: object) -> int:
|
||||
return 3
|
||||
|
||||
def _proactive_daily_limit_is_unlimited(self, _limit: int) -> bool:
|
||||
return False
|
||||
|
||||
def _reset_daily_counter_if_needed(self, _user: object) -> None:
|
||||
return None
|
||||
|
||||
def _build_expression_decision_for_user(self, _user: object, **_kwargs: object) -> dict[str, object]:
|
||||
return {"proactive_budget": 3, "blocker": None}
|
||||
|
||||
host = Host()
|
||||
self.assertEqual("expression_proactive_budget_exhausted", preflight(host, {"sent_today": 3}, now=100.0))
|
||||
host._current_relationship_gate_mode = lambda _user, *, now: "backoff" # type: ignore[method-assign]
|
||||
self.assertEqual("expression_contact_boundary", preflight(host, {"sent_today": 0}, now=100.0))
|
||||
|
||||
def test_page_dto_marks_legacy_relationship_state_read_only(self) -> None:
|
||||
page_source = (ROOT / "page_api.py").read_text(encoding="utf-8")
|
||||
users_source = (ROOT / "page_api_users_groups.py").read_text(encoding="utf-8")
|
||||
|
||||
self.assertIn('"compatibility": "legacy_read_only"', page_source)
|
||||
self.assertIn('"current_authority": "current_interaction"', page_source)
|
||||
self.assertIn('"expression_authority"', page_source)
|
||||
self.assertIn('detail["expression_decision"]', users_source)
|
||||
|
||||
for source in (page_source, users_source):
|
||||
tree = ast.parse(source)
|
||||
for call in (node for node in ast.walk(tree) if isinstance(node, ast.Call)):
|
||||
if not isinstance(call.func, ast.Name) or call.func.id != "current_interaction_projection":
|
||||
continue
|
||||
self.assertTrue(call.args)
|
||||
first_arg = call.args[0]
|
||||
self.assertFalse(
|
||||
isinstance(first_arg, ast.BoolOp) and isinstance(first_arg.op, ast.Or),
|
||||
"current_interaction must not fall back to legacy relationship_state",
|
||||
)
|
||||
|
||||
def test_runtime_expression_projections_never_fall_back_to_legacy_state(self) -> None:
|
||||
runtime_files = (
|
||||
"proactive.py",
|
||||
"proactive_engine.py",
|
||||
"proactive_message.py",
|
||||
"private_reading.py",
|
||||
"main.py",
|
||||
"user_memory.py",
|
||||
)
|
||||
for filename in runtime_files:
|
||||
with self.subTest(filename=filename):
|
||||
tree = ast.parse((ROOT / filename).read_text(encoding="utf-8"))
|
||||
for call in (node for node in ast.walk(tree) if isinstance(node, ast.Call)):
|
||||
if not isinstance(call.func, ast.Name) or call.func.id != "current_interaction_projection":
|
||||
continue
|
||||
self.assertTrue(call.args)
|
||||
self.assertFalse(
|
||||
isinstance(call.args[0], ast.BoolOp) and isinstance(call.args[0].op, ast.Or),
|
||||
"current_interaction must not fall back to relationship_state",
|
||||
)
|
||||
|
||||
def test_expression_context_has_no_legacy_state_consumer_or_sync_adapter(self) -> None:
|
||||
source = (ROOT / "user_memory.py").read_text(encoding="utf-8")
|
||||
tree = ast.parse(source)
|
||||
owner = next(node for node in tree.body if isinstance(node, ast.ClassDef) and node.name == "UserMemoryMixin")
|
||||
methods = {
|
||||
node.name: node
|
||||
for node in owner.body
|
||||
if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef))
|
||||
}
|
||||
context = methods["_expression_companion_context"]
|
||||
context_constants = {
|
||||
node.value for node in ast.walk(context) if isinstance(node, ast.Constant) and isinstance(node.value, str)
|
||||
}
|
||||
self.assertNotIn("relationship_state", context_constants)
|
||||
self.assertNotIn("_sync_current_interaction_from_legacy", methods)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
|
|
@ -0,0 +1,363 @@
|
|||
from __future__ import annotations
|
||||
|
||||
import ast
|
||||
import asyncio
|
||||
import copy
|
||||
from pathlib import Path
|
||||
import re
|
||||
import time
|
||||
from types import 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 _safe_int(value: Any, default: int = 0, minimum: int | None = None) -> int:
|
||||
try:
|
||||
result = int(value)
|
||||
except (TypeError, ValueError):
|
||||
result = default
|
||||
return max(minimum, result) if minimum is not None else result
|
||||
|
||||
|
||||
class _Logger:
|
||||
def warning(self, *_args: Any, **_kwargs: Any) -> None:
|
||||
return None
|
||||
|
||||
|
||||
def _load_methods(filename: str, class_name: str, names: set[str]) -> dict[str, Any]:
|
||||
source = (ROOT / filename).read_text(encoding="utf-8")
|
||||
tree = ast.parse(source)
|
||||
owner = next(node for node in tree.body if isinstance(node, ast.ClassDef) and node.name == class_name)
|
||||
namespace: dict[str, Any] = {
|
||||
"Any": Any,
|
||||
"_single_line": _single_line,
|
||||
"_safe_int": _safe_int,
|
||||
"_now_ts": lambda: 123.0,
|
||||
"logger": _Logger(),
|
||||
"time": time,
|
||||
"deepcopy": copy.deepcopy,
|
||||
}
|
||||
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(ROOT / filename), "exec"), namespace)
|
||||
return {name: namespace[name] for name in names}
|
||||
|
||||
|
||||
WORLDBOOK_METHODS = _load_methods(
|
||||
"worldbook.py",
|
||||
"WorldbookMixin",
|
||||
{
|
||||
"_ensure_worldbook_group_observation_profile",
|
||||
"_worldbook_group_observation_profile_by_identity",
|
||||
},
|
||||
)
|
||||
GROUP_METHODS = _load_methods(
|
||||
"group_observation.py",
|
||||
"GroupObservationMixin",
|
||||
{
|
||||
"_record_group_observation_profile_projection_result",
|
||||
"_update_group_observation",
|
||||
"_capture_group_observation_once",
|
||||
"_group_observation_marker_matches",
|
||||
},
|
||||
)
|
||||
PAGE_METHODS = _load_methods(
|
||||
"page_api_users_groups.py",
|
||||
"PrivateCompanionPageApiUsersGroupsMixin",
|
||||
{
|
||||
"_observation_profile_by_user_id_locked",
|
||||
"_observation_user_summary",
|
||||
"_observation_user_detail",
|
||||
"list_users",
|
||||
},
|
||||
)
|
||||
PAGE_API_METHODS = _load_methods(
|
||||
"page_api.py",
|
||||
"PrivateCompanionPageApi",
|
||||
{"_worldbook_member_profile_summary"},
|
||||
)
|
||||
CORE_STORE_METHODS = _load_methods(
|
||||
"core_store.py",
|
||||
"CoreStoreMixin",
|
||||
{"_merge_group_observation_into_private_user"},
|
||||
)
|
||||
|
||||
|
||||
class _GroupHost:
|
||||
enable_group_member_profiles = True
|
||||
enable_worldbook_member_recognition = False
|
||||
max_group_recent_messages = 12
|
||||
enable_group_slang_learning = False
|
||||
enable_group_topic_threads = False
|
||||
enable_group_relationship_graph = False
|
||||
enable_group_interjection_feedback = False
|
||||
|
||||
def __init__(self) -> None:
|
||||
self.data: dict[str, Any] = {}
|
||||
self.allowed = True
|
||||
|
||||
def _group_enabled_for_event(self, _group_id: str) -> bool:
|
||||
return self.allowed
|
||||
|
||||
def _analyze_group_injection_guard(self, _text: str, *, sender_id: str = "") -> dict[str, Any]:
|
||||
return {"blocked": False, "score": 0, "reasons": []}
|
||||
|
||||
def _group_name_from_event(self, _event: Any) -> str:
|
||||
return ""
|
||||
|
||||
def _sender_qq_nickname(self, _event: Any) -> str:
|
||||
return "QQ昵称"
|
||||
|
||||
def _worldbook_profile_by_user_id(self, _user_id: str, *, include_observation: bool = False) -> None:
|
||||
return None
|
||||
|
||||
@staticmethod
|
||||
def _group_member_identity_name(_user_id: str, fallback: str = "", *, limit: int = 30) -> str:
|
||||
return _single_line(fallback, limit)
|
||||
|
||||
def _record_user_recent_group_message_from_observation(self, **_kwargs: Any) -> None:
|
||||
return None
|
||||
|
||||
def _remember_worldbook_observed_name(self, _user_id: str, _name: str) -> None:
|
||||
return None
|
||||
|
||||
def _maybe_add_worldbook_pending_observation(self, **_kwargs: Any) -> None:
|
||||
return None
|
||||
|
||||
@staticmethod
|
||||
def _expression_group_learning_source_enabled(_group_id: str) -> bool:
|
||||
return False
|
||||
|
||||
def _update_group_atmosphere(self, _group: dict[str, Any]) -> None:
|
||||
return None
|
||||
|
||||
|
||||
for _name, _method in {**WORLDBOOK_METHODS, **GROUP_METHODS}.items():
|
||||
setattr(_GroupHost, _name, _method)
|
||||
|
||||
|
||||
class _PagePlugin:
|
||||
def __init__(self, data: dict[str, Any]) -> None:
|
||||
self.data = data
|
||||
self._data_lock = _AsyncLock()
|
||||
|
||||
@staticmethod
|
||||
def _format_timestamp_elapsed(value: Any) -> str:
|
||||
return f"at:{value}" if value else ""
|
||||
|
||||
def _worldbook_group_observation_profile_by_identity(self, user_id: str) -> tuple[str, dict[str, Any]] | None:
|
||||
profiles = self.data.get("worldbook_member_profiles", {})
|
||||
profile = profiles.get(user_id) if isinstance(profiles, dict) else None
|
||||
return (user_id, profile) if isinstance(profile, dict) and profile.get("observation_only") else None
|
||||
|
||||
|
||||
class _PageHost:
|
||||
def __init__(self, data: dict[str, Any]) -> None:
|
||||
self.plugin = _PagePlugin(data)
|
||||
|
||||
_single_line = staticmethod(_single_line)
|
||||
|
||||
@staticmethod
|
||||
def _query_int(_name: str, default: int, _minimum: int, _maximum: int) -> int:
|
||||
return default
|
||||
|
||||
@staticmethod
|
||||
def _ok(value: dict[str, Any]) -> dict[str, Any]:
|
||||
return value
|
||||
|
||||
@staticmethod
|
||||
def _user_summary(user_id: str, user: dict[str, Any]) -> dict[str, Any]:
|
||||
return {
|
||||
"user_id": user_id,
|
||||
"display_name": user.get("nickname", user_id),
|
||||
"platform_group": "qq",
|
||||
"last_seen_ts": user.get("last_seen", 0),
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
def _normalize_important_memories(_value: Any) -> list[dict[str, Any]]:
|
||||
return []
|
||||
|
||||
|
||||
for _name, _method in {**PAGE_METHODS, **PAGE_API_METHODS}.items():
|
||||
setattr(_PageHost, _name, _method)
|
||||
|
||||
|
||||
class _PrivateMergeHost:
|
||||
def __init__(self, data: dict[str, Any]) -> None:
|
||||
self.data = data
|
||||
|
||||
|
||||
for _name, _method in {**WORLDBOOK_METHODS, **CORE_STORE_METHODS}.items():
|
||||
setattr(_PrivateMergeHost, _name, _method)
|
||||
|
||||
|
||||
class _AsyncLock:
|
||||
async def __aenter__(self) -> "_AsyncLock":
|
||||
return self
|
||||
|
||||
async def __aexit__(self, _exc_type: Any, _exc: Any, _tb: Any) -> None:
|
||||
return None
|
||||
|
||||
|
||||
class GroupProfileProjectionTests(unittest.TestCase):
|
||||
def test_enabled_whitelisted_message_creates_one_cross_group_observation_profile(self) -> None:
|
||||
host = _GroupHost()
|
||||
group_a: dict[str, Any] = {}
|
||||
group_b: dict[str, Any] = {}
|
||||
|
||||
host._update_group_observation(group_a, sender_id="10001", sender_name="甲群名片", text="你好", group_id="group-a")
|
||||
host._update_group_observation(group_b, sender_id="10001", sender_name="乙群名片", text="又见面了", group_id="group-b")
|
||||
|
||||
profile = host.data["worldbook_member_profiles"]["10001"]
|
||||
self.assertTrue(profile["observation_only"])
|
||||
self.assertNotIn("users", host.data)
|
||||
self.assertEqual({"group-a", "group-b"}, set(profile["group_observation_scope_ids"]))
|
||||
self.assertEqual(1, host.data["group_observation_profile_projection_stats"]["counts"]["created"])
|
||||
self.assertEqual(1, host.data["group_observation_profile_projection_stats"]["counts"]["updated"])
|
||||
|
||||
def test_disabled_or_non_whitelisted_or_empty_messages_do_not_create_profiles(self) -> None:
|
||||
host = _GroupHost()
|
||||
host.enable_group_member_profiles = False
|
||||
host._update_group_observation({}, sender_id="10001", sender_name="名片", text="你好", group_id="group-a")
|
||||
self.assertNotIn("worldbook_member_profiles", host.data)
|
||||
self.assertEqual("skipped_member_profiles_disabled", host.data["group_observation_profile_projection_stats"]["last_result_code"])
|
||||
|
||||
host = _GroupHost()
|
||||
host.allowed = False
|
||||
host._update_group_observation({}, sender_id="10001", sender_name="名片", text="你好", group_id="not-allowed")
|
||||
self.assertNotIn("worldbook_member_profiles", host.data)
|
||||
self.assertEqual("skipped_group_not_allowed", host.data["group_observation_profile_projection_stats"]["last_result_code"])
|
||||
|
||||
host = _GroupHost()
|
||||
self.assertFalse(host._capture_group_observation_once({}, sender_id="10001", sender_name="名片", text="", group_id="group-a"))
|
||||
self.assertNotIn("worldbook_member_profiles", host.data)
|
||||
self.assertEqual("skipped_empty_message", host.data["group_observation_profile_projection_stats"]["last_result_code"])
|
||||
|
||||
def test_projection_failure_is_recorded_but_does_not_block_group_observation(self) -> None:
|
||||
host = _GroupHost()
|
||||
host._ensure_worldbook_group_observation_profile = lambda **_kwargs: (_ for _ in ()).throw(RuntimeError("test"))
|
||||
group: dict[str, Any] = {}
|
||||
|
||||
host._update_group_observation(group, sender_id="10001", sender_name="名片", text="仍然观察", group_id="group-a")
|
||||
|
||||
self.assertEqual("failed", host.data["group_observation_profile_projection_stats"]["last_result_code"])
|
||||
self.assertEqual(1, len(group["recent_messages"]))
|
||||
|
||||
def test_user_page_dto_is_read_only_qq_group_observation_without_private_capabilities(self) -> None:
|
||||
data = {
|
||||
"worldbook_member_profiles": {
|
||||
"10001": {
|
||||
"user_id": "10001",
|
||||
"name": "QQ昵称",
|
||||
"observation_only": True,
|
||||
"profile_origin": "group_observation",
|
||||
"group_observation_scope_ids": ["group-a", "group-b", "group-a"],
|
||||
"last_observed_at": 123.0,
|
||||
"proactive_contact_enabled": True,
|
||||
"private_memory_enabled": True,
|
||||
"cross_group_memory_enabled": True,
|
||||
"p4_eligible": True,
|
||||
}
|
||||
}
|
||||
}
|
||||
host = _PageHost(data)
|
||||
found = host._observation_profile_by_user_id_locked(data, "10001")
|
||||
self.assertIsNotNone(found)
|
||||
profile_id, profile = found or ("", {})
|
||||
detail = host._observation_user_detail(profile_id, profile)
|
||||
|
||||
self.assertEqual("qq", detail["platform_group"])
|
||||
self.assertEqual("group_observation", detail["profile_source"])
|
||||
self.assertTrue(detail["observation_only"])
|
||||
self.assertEqual(2, detail["observed_group_count"])
|
||||
self.assertFalse(detail["proactive_contact_enabled"])
|
||||
self.assertFalse(detail["private_memory_enabled"])
|
||||
self.assertFalse(detail["cross_group_memory_enabled"])
|
||||
self.assertFalse(detail["p4_eligible"])
|
||||
self.assertEqual({}, detail["memory"])
|
||||
self.assertEqual([], detail["worldbook_member"]["important_memories"])
|
||||
self.assertFalse(detail["worldbook_member"]["proactive_contact_enabled"])
|
||||
|
||||
def test_user_list_includes_observation_projection_without_creating_a_private_user(self) -> None:
|
||||
data = {
|
||||
"users": {"20002": {"nickname": "私聊用户", "last_seen": 80}},
|
||||
"worldbook_member_profiles": {
|
||||
"10001": {
|
||||
"user_id": "10001",
|
||||
"name": "群聊对象",
|
||||
"observation_only": True,
|
||||
"group_observation_scope_ids": ["group-a"],
|
||||
"last_observed_at": 120,
|
||||
},
|
||||
"20002": {
|
||||
"user_id": "20002",
|
||||
"name": "应被私聊档案遮蔽",
|
||||
"observation_only": True,
|
||||
},
|
||||
},
|
||||
}
|
||||
result = asyncio.run(_PageHost(data).list_users())
|
||||
|
||||
self.assertEqual(2, result["total"])
|
||||
self.assertEqual(1, result["private_total"])
|
||||
self.assertEqual(1, result["observation_total"])
|
||||
observed = next(item for item in result["items"] if item["user_id"] == "10001")
|
||||
self.assertTrue(observed["observation_only"])
|
||||
self.assertEqual("group_observation", observed["profile_source"])
|
||||
self.assertEqual({"20002"}, set(data["users"]))
|
||||
|
||||
def test_first_real_private_profile_merges_exact_observation_metadata_without_group_content(self) -> None:
|
||||
data = {
|
||||
"worldbook_member_profiles": {
|
||||
"10001": {
|
||||
"user_id": "10001",
|
||||
"name": "QQ nickname",
|
||||
"observation_only": True,
|
||||
"group_observation_scope_ids": ["group-a", "group-b"],
|
||||
"group_aliases": {"group-a": ["group card"]},
|
||||
"content": "group-only description",
|
||||
"important_memories": ["must not merge"],
|
||||
}
|
||||
}
|
||||
}
|
||||
host = _PrivateMergeHost(data)
|
||||
private_user: dict[str, Any] = {"nickname": "default", "companion_memory": {}}
|
||||
|
||||
changed = host._merge_group_observation_into_private_user(
|
||||
"10001",
|
||||
private_user,
|
||||
now=456.0,
|
||||
use_observed_name=True,
|
||||
)
|
||||
repeated = host._merge_group_observation_into_private_user(
|
||||
"10001",
|
||||
private_user,
|
||||
now=789.0,
|
||||
use_observed_name=True,
|
||||
)
|
||||
|
||||
self.assertTrue(changed)
|
||||
self.assertFalse(repeated)
|
||||
self.assertEqual("QQ nickname", private_user["nickname"])
|
||||
self.assertEqual(["group-a", "group-b"], private_user["group_observation_scope_ids"])
|
||||
self.assertEqual({"group-a": ["group card"]}, private_user["group_observation_aliases"])
|
||||
self.assertEqual({}, private_user["companion_memory"])
|
||||
self.assertNotIn("content", private_user)
|
||||
self.assertNotIn("important_memories", private_user)
|
||||
observation = data["worldbook_member_profiles"]["10001"]
|
||||
self.assertTrue(observation["private_profile_merged"])
|
||||
self.assertEqual("10001", observation["private_user_id"])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
|
|
@ -0,0 +1,89 @@
|
|||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, timezone
|
||||
|
||||
from relationship_ledger import (
|
||||
apply_natural_relationship_decay,
|
||||
apply_relationship_event,
|
||||
record_manual_relationship_change,
|
||||
relationship_ledger_summary,
|
||||
)
|
||||
|
||||
|
||||
def _ts(day: int) -> float:
|
||||
return datetime(2026, 8, day, tzinfo=timezone.utc).timestamp()
|
||||
|
||||
|
||||
def test_positive_events_are_deduplicated_and_bounded() -> None:
|
||||
user = {"relationship_role": "friend", "relationship_score": 1199}
|
||||
first = apply_relationship_event(user, 4, reason_code="inbound", now=_ts(1))
|
||||
duplicate = apply_relationship_event(user, 4, reason_code="inbound", now=_ts(1) + 60)
|
||||
assert first["changed"] is True
|
||||
assert user["relationship_score"] == 1200
|
||||
assert duplicate["code"] == "duplicate_event"
|
||||
|
||||
|
||||
def test_owner_exclusive_is_frozen() -> None:
|
||||
user = {"relationship_role": "owner", "relationship_mode": "owner_exclusive", "relationship_score": 600}
|
||||
result = apply_relationship_event(user, 4, reason_code="warmth", now=_ts(1))
|
||||
assert result["code"] == "owner_exclusive_frozen"
|
||||
assert user["relationship_score"] == 600
|
||||
|
||||
|
||||
def test_silence_decays_positive_score_without_creating_negative_score() -> None:
|
||||
user = {
|
||||
"relationship_role": "friend",
|
||||
"relationship_score": 30,
|
||||
"relationship_last_effective_at": _ts(1),
|
||||
}
|
||||
result = apply_natural_relationship_decay(user, now=_ts(10))
|
||||
assert result["changed"] is True
|
||||
assert 0 <= user["relationship_score"] < 30
|
||||
again = apply_natural_relationship_decay(user, now=_ts(10) + 60)
|
||||
assert again["code"] == "already_settled"
|
||||
|
||||
|
||||
def test_negative_event_can_cross_zero_but_is_capped() -> None:
|
||||
user = {"relationship_role": "friend", "relationship_score": 3}
|
||||
result = apply_relationship_event(user, -100, reason_code="boundary_violation", now=_ts(1))
|
||||
assert result["delta"] == -12
|
||||
assert user["relationship_score"] == -9
|
||||
|
||||
|
||||
def test_manual_adjustment_is_audited_without_reapplying_the_score() -> None:
|
||||
user = {"relationship_role": "friend", "relationship_score": 500}
|
||||
user["relationship_score"] = 650
|
||||
result = record_manual_relationship_change(user, 500, 650, now=_ts(1))
|
||||
summary = relationship_ledger_summary(user)
|
||||
assert result["changed"] is True
|
||||
assert user["relationship_score"] == 650
|
||||
assert summary["trend"] == "rising"
|
||||
assert summary["recent_delta"] == 150
|
||||
assert summary["items"][-1]["source"] == "administrator"
|
||||
|
||||
|
||||
def test_zero_positive_daily_cap_disables_automatic_growth() -> None:
|
||||
user = {"relationship_role": "friend", "relationship_score": 100}
|
||||
result = apply_relationship_event(
|
||||
user,
|
||||
3,
|
||||
reason_code="friendly_exchange",
|
||||
now=_ts(1),
|
||||
event_id="zero-cap",
|
||||
positive_daily_cap=0,
|
||||
)
|
||||
assert result["changed"] is False
|
||||
assert result["code"] == "positive_daily_cap"
|
||||
assert user["relationship_score"] == 100
|
||||
|
||||
|
||||
def test_high_relationship_stages_have_diminishing_positive_gain() -> None:
|
||||
low = {"relationship_role": "friend", "relationship_score": 100}
|
||||
close = {"relationship_role": "friend", "relationship_score": 700}
|
||||
intimate = {"relationship_role": "friend", "relationship_score": 1000}
|
||||
low_result = apply_relationship_event(low, 4, reason_code="support", now=_ts(1), event_id="low")
|
||||
close_result = apply_relationship_event(close, 4, reason_code="support", now=_ts(1), event_id="close")
|
||||
intimate_result = apply_relationship_event(intimate, 4, reason_code="support", now=_ts(1), event_id="intimate")
|
||||
assert low_result["delta"] == 4
|
||||
assert close_result["delta"] == 3
|
||||
assert intimate_result["delta"] == 2
|
||||
|
|
@ -0,0 +1,302 @@
|
|||
from __future__ import annotations
|
||||
|
||||
import ast
|
||||
import asyncio
|
||||
import copy
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import time
|
||||
from typing import Any
|
||||
import unittest
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT))
|
||||
|
||||
from companion_interaction_expression import allowed_expression_bands, current_interaction_projection # noqa: E402
|
||||
from relationship_ledger import normalize_relationship_mode, record_manual_relationship_change # noqa: E402
|
||||
|
||||
|
||||
class _Request:
|
||||
payload: dict[str, Any] = {}
|
||||
|
||||
async def get_json(self, silent: bool = True) -> dict[str, Any]:
|
||||
del silent
|
||||
return copy.deepcopy(self.payload)
|
||||
|
||||
|
||||
class _Logger:
|
||||
def error(self, *_args: Any, **_kwargs: Any) -> None:
|
||||
return None
|
||||
|
||||
info = error
|
||||
debug = error
|
||||
warning = error
|
||||
|
||||
|
||||
def _safe_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
|
||||
|
||||
|
||||
def _safe_float(value: Any, default: float = 0.0, minimum: float = 0.0, maximum: float | None = None) -> float:
|
||||
try:
|
||||
result = float(value)
|
||||
except (TypeError, ValueError):
|
||||
result = default
|
||||
result = max(minimum, result)
|
||||
if maximum is not None:
|
||||
result = min(maximum, result)
|
||||
return result
|
||||
|
||||
|
||||
def _single_line(value: Any, limit: int = 80) -> str:
|
||||
return " ".join(str(value or "").split())[:limit]
|
||||
|
||||
|
||||
def _load_update_user() -> Any:
|
||||
path = ROOT / "page_api_users_groups.py"
|
||||
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 == "PrivateCompanionPageApiUsersGroupsMixin")
|
||||
method = next(node for node in owner.body if isinstance(node, ast.AsyncFunctionDef) and node.name == "update_user")
|
||||
namespace: dict[str, Any] = {
|
||||
"Any": Any,
|
||||
"allowed_expression_bands": allowed_expression_bands,
|
||||
"current_interaction_projection": current_interaction_projection,
|
||||
"deepcopy": copy.deepcopy,
|
||||
"logger": _Logger(),
|
||||
"normalize_relationship_mode": normalize_relationship_mode,
|
||||
"record_manual_relationship_change": record_manual_relationship_change,
|
||||
"request": _Request(),
|
||||
"time": time,
|
||||
"_safe_int": _safe_int,
|
||||
}
|
||||
module = ast.Module(body=[copy.deepcopy(method)], type_ignores=[])
|
||||
ast.fix_missing_locations(module)
|
||||
exec(compile(module, str(path), "exec"), namespace)
|
||||
return namespace["update_user"], namespace["request"]
|
||||
|
||||
|
||||
UPDATE_USER, REQUEST = _load_update_user()
|
||||
|
||||
|
||||
def _load_interaction_settler() -> Any:
|
||||
path = ROOT / "user_memory.py"
|
||||
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 == "UserMemoryMixin")
|
||||
method = next(node for node in owner.body if isinstance(node, ast.FunctionDef) and node.name == "_update_relationship_state_from_intent")
|
||||
namespace: dict[str, Any] = {
|
||||
"Any": Any,
|
||||
"asyncio": asyncio,
|
||||
"current_interaction_projection": current_interaction_projection,
|
||||
"deepcopy": copy.deepcopy,
|
||||
"logger": _Logger(),
|
||||
"_now_ts": time.time,
|
||||
"_safe_float": _safe_float,
|
||||
"_safe_int": _safe_int,
|
||||
"_single_line": _single_line,
|
||||
}
|
||||
module = ast.Module(body=[copy.deepcopy(method)], type_ignores=[])
|
||||
ast.fix_missing_locations(module)
|
||||
exec(compile(module, str(path), "exec"), namespace)
|
||||
return namespace["_update_relationship_state_from_intent"]
|
||||
|
||||
|
||||
SETTLE_INTERACTION = _load_interaction_settler()
|
||||
|
||||
|
||||
class _AsyncLock:
|
||||
async def __aenter__(self) -> "_AsyncLock":
|
||||
return self
|
||||
|
||||
async def __aexit__(self, _exc_type: Any, _exc: Any, _tb: Any) -> None:
|
||||
return None
|
||||
|
||||
|
||||
class _Plugin:
|
||||
def __init__(self, user: dict[str, Any]) -> None:
|
||||
self.data = {"users": {"10001": user}}
|
||||
self._data_lock = _AsyncLock()
|
||||
self.saved = 0
|
||||
|
||||
def _get_user(self, user_id: str) -> dict[str, Any]:
|
||||
return self.data["users"][user_id]
|
||||
|
||||
@staticmethod
|
||||
def _private_user_role(user: dict[str, Any], _user_id: str) -> str:
|
||||
return str(user.get("relationship_role") or "friend")
|
||||
|
||||
@staticmethod
|
||||
def _normalize_private_user_role(value: Any) -> str:
|
||||
role = str(value or "").strip().lower()
|
||||
return role if role in {"owner", "friend"} else ""
|
||||
|
||||
def _save_data_sync(self) -> None:
|
||||
self.saved += 1
|
||||
|
||||
|
||||
class _Host:
|
||||
def __init__(self, user: dict[str, Any]) -> None:
|
||||
self.plugin = _Plugin(user)
|
||||
|
||||
update_user = UPDATE_USER
|
||||
|
||||
@staticmethod
|
||||
def _single_line(value: Any, limit: int) -> str:
|
||||
return " ".join(str(value or "").split())[:limit]
|
||||
|
||||
@staticmethod
|
||||
def _relationship_score_input(value: Any) -> int:
|
||||
if isinstance(value, bool) or not isinstance(value, int) or not -1200 <= value <= 1200:
|
||||
raise ValueError("invalid relationship score")
|
||||
return value
|
||||
|
||||
@staticmethod
|
||||
def _observation_profile_by_user_id_locked(_data: dict[str, Any], _user_id: str) -> None:
|
||||
return None
|
||||
|
||||
@staticmethod
|
||||
def _user_summary(user_id: str, user: dict[str, Any]) -> dict[str, Any]:
|
||||
return {"user_id": user_id, **copy.deepcopy(user)}
|
||||
|
||||
@staticmethod
|
||||
def _expression_profile_summary(_user: dict[str, Any]) -> dict[str, Any]:
|
||||
return {}
|
||||
|
||||
@staticmethod
|
||||
def _ok(value: dict[str, Any]) -> dict[str, Any]:
|
||||
return {"ok": True, "data": value}
|
||||
|
||||
@staticmethod
|
||||
def _error(message: str) -> dict[str, Any]:
|
||||
return {"ok": False, "error": message}
|
||||
|
||||
|
||||
class Req028UserUpdateContractTests(unittest.TestCase):
|
||||
def _run(self, user: dict[str, Any], payload: dict[str, Any]) -> tuple[dict[str, Any], _Host]:
|
||||
host = _Host(copy.deepcopy(user))
|
||||
REQUEST.payload = {"user_id": "10001", **payload}
|
||||
return asyncio.run(host.update_user()), host
|
||||
|
||||
def test_owner_exclusive_score_is_frozen_until_normal_stage_is_explicit(self) -> None:
|
||||
base = {"relationship_role": "owner", "relationship_mode": "owner_exclusive", "relationship_score": 600}
|
||||
rejected, rejected_host = self._run(base, {"companion_intimacy": 500})
|
||||
self.assertFalse(rejected["ok"])
|
||||
self.assertEqual(base, rejected_host.plugin.data["users"]["10001"])
|
||||
|
||||
accepted, accepted_host = self._run(base, {"relationship_mode": "normal", "companion_intimacy": 500})
|
||||
self.assertTrue(accepted["ok"])
|
||||
self.assertEqual("normal", accepted_host.plugin.data["users"]["10001"]["relationship_mode"])
|
||||
self.assertEqual(500, accepted_host.plugin.data["users"]["10001"]["relationship_score"])
|
||||
|
||||
def test_owner_only_interaction_bands_are_rejected_server_side(self) -> None:
|
||||
friend = {"relationship_role": "friend", "relationship_mode": "normal", "relationship_score": 0}
|
||||
rejected, _ = self._run(friend, {"current_interaction_band": "affectionate"})
|
||||
self.assertFalse(rejected["ok"])
|
||||
|
||||
owner = {"relationship_role": "owner", "relationship_mode": "owner_exclusive", "relationship_score": 600}
|
||||
accepted, host = self._run(owner, {"current_interaction_band": "affectionate"})
|
||||
self.assertTrue(accepted["ok"])
|
||||
interaction = host.plugin.data["users"]["10001"]["current_interaction"]
|
||||
self.assertEqual("affectionate", interaction["expression_band"])
|
||||
self.assertTrue(interaction["manual_override"])
|
||||
self.assertEqual("page_administrator", interaction["operator"])
|
||||
|
||||
def test_owner_downgrade_requires_explicit_normal_relationship_selection(self) -> None:
|
||||
owner = {"relationship_role": "owner", "relationship_mode": "owner_exclusive", "relationship_score": 600}
|
||||
rejected, _ = self._run(owner, {"relationship_role": "friend"})
|
||||
self.assertFalse(rejected["ok"])
|
||||
|
||||
accepted, host = self._run(
|
||||
owner,
|
||||
{"relationship_role": "friend", "relationship_mode": "normal", "companion_intimacy": 100},
|
||||
)
|
||||
self.assertTrue(accepted["ok"])
|
||||
user = host.plugin.data["users"]["10001"]
|
||||
self.assertEqual("friend", user["relationship_role"])
|
||||
self.assertEqual("normal", user["relationship_mode"])
|
||||
|
||||
def test_automatic_settlement_writes_only_current_interaction_and_contact_boundary(self) -> None:
|
||||
host = _Host({"relationship_role": "friend", "relationship_mode": "normal"})
|
||||
host._update_relationship_state_from_intent = SETTLE_INTERACTION.__get__(host, _Host)
|
||||
host._update_relationship_state_from_intent(
|
||||
host.plugin.data["users"]["10001"],
|
||||
{"intent": "boundary", "confidence": 0.95, "boundary_durable": True},
|
||||
)
|
||||
user = host.plugin.data["users"]["10001"]
|
||||
self.assertEqual("avoidant", user["current_interaction"]["expression_band"])
|
||||
self.assertTrue(user["contact_preference"]["active"])
|
||||
self.assertNotIn("relationship_state", user)
|
||||
self.assertNotIn("mood_score", user)
|
||||
self.assertNotIn("plutchik_profile", user)
|
||||
|
||||
def test_explicit_reengagement_clears_contact_boundary_and_owner_may_be_close(self) -> None:
|
||||
user = {
|
||||
"relationship_role": "owner",
|
||||
"relationship_mode": "owner_exclusive",
|
||||
"contact_preference": {"mode": "no_contact", "active": True, "no_contact": True},
|
||||
}
|
||||
host = _Host(user)
|
||||
host._update_relationship_state_from_intent = SETTLE_INTERACTION.__get__(host, _Host)
|
||||
host._update_relationship_state_from_intent(
|
||||
host.plugin.data["users"]["10001"],
|
||||
{"intent": "intimacy", "confidence": 0.9, "emotion_event": "neutral"},
|
||||
)
|
||||
settled = host.plugin.data["users"]["10001"]
|
||||
self.assertFalse(settled["contact_preference"]["active"])
|
||||
self.assertEqual("close", settled["current_interaction"]["expression_band"])
|
||||
|
||||
def test_manual_interaction_override_is_not_replaced_by_automatic_event(self) -> None:
|
||||
user = {
|
||||
"relationship_role": "owner",
|
||||
"relationship_mode": "owner_exclusive",
|
||||
"current_interaction": {
|
||||
"expression_band": "affectionate",
|
||||
"source": "manual",
|
||||
"manual_override": True,
|
||||
"updated_at": time.time(),
|
||||
"expires_at": time.time() + 3600,
|
||||
},
|
||||
}
|
||||
host = _Host(user)
|
||||
host._update_relationship_state_from_intent = SETTLE_INTERACTION.__get__(host, _Host)
|
||||
host._update_relationship_state_from_intent(
|
||||
host.plugin.data["users"]["10001"],
|
||||
{"intent": "chat", "confidence": 0.9, "emotion_event": "hurt", "emotion_confidence": 0.9, "emotion_intensity": 95, "emotion_target": "bot"},
|
||||
)
|
||||
self.assertEqual("affectionate", host.plugin.data["users"]["10001"]["current_interaction"]["expression_band"])
|
||||
|
||||
def test_hurt_thresholds_and_recovery_window_drive_the_unified_interaction(self) -> None:
|
||||
host = _Host({"relationship_role": "friend", "relationship_mode": "normal"})
|
||||
host._update_relationship_state_from_intent = SETTLE_INTERACTION.__get__(host, _Host)
|
||||
host.emotional_gate_hurt_threshold = 70
|
||||
host.emotional_gate_refuse_threshold = 90
|
||||
host.emotional_gate_recovery_per_hour = 30
|
||||
host.emotional_gate_max_hurt_minutes = 120
|
||||
|
||||
host._update_relationship_state_from_intent(
|
||||
host.plugin.data["users"]["10001"],
|
||||
{"intent": "chat", "confidence": 0.9, "emotion_event": "hurt", "emotion_confidence": 0.9, "emotion_intensity": 65, "emotion_target": "bot"},
|
||||
)
|
||||
self.assertEqual("relaxed", host.plugin.data["users"]["10001"]["current_interaction"]["expression_band"])
|
||||
|
||||
before = time.time()
|
||||
host._update_relationship_state_from_intent(
|
||||
host.plugin.data["users"]["10001"],
|
||||
{"intent": "chat", "confidence": 0.9, "emotion_event": "hurt", "emotion_confidence": 0.9, "emotion_intensity": 95, "emotion_target": "bot"},
|
||||
)
|
||||
interaction = host.plugin.data["users"]["10001"]["current_interaction"]
|
||||
self.assertEqual("avoidant", interaction["expression_band"])
|
||||
self.assertEqual("severe_hurt_event", interaction["reason"])
|
||||
self.assertLessEqual(interaction["expires_at"] - before, 120 * 60 + 2)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
1395
user_memory.py
1395
user_memory.py
文件差异内容过多而无法显示
加载差异
28
worldbook.py
28
worldbook.py
|
|
@ -493,6 +493,7 @@ class WorldbookMixin:
|
|||
if not isinstance(profile, dict):
|
||||
profile = {
|
||||
"user_id": sender_id,
|
||||
"identity_type": "qq",
|
||||
"name": display_name,
|
||||
"gender": "",
|
||||
"aliases": [],
|
||||
|
|
@ -505,6 +506,7 @@ class WorldbookMixin:
|
|||
"priority": 0,
|
||||
"source_entries": ["白名单群观察"],
|
||||
"profile_origin": "group_observation",
|
||||
"projection_kind": "group_observation",
|
||||
"observation_only": True,
|
||||
"proactive_contact_enabled": False,
|
||||
"private_memory_enabled": False,
|
||||
|
|
@ -527,6 +529,8 @@ class WorldbookMixin:
|
|||
profile.setdefault("affinity_score", 0)
|
||||
profile.setdefault("relationship_state", "neutral")
|
||||
profile.setdefault("profile_origin", "group_observation")
|
||||
profile.setdefault("projection_kind", "group_observation")
|
||||
profile.setdefault("identity_type", "qq")
|
||||
profile.setdefault("source_entries", ["白名单群观察"])
|
||||
profile.setdefault("observation_only", True)
|
||||
aliases_by_group = profile.setdefault("group_aliases", {})
|
||||
|
|
@ -550,6 +554,30 @@ class WorldbookMixin:
|
|||
profile["last_observed_at"] = now
|
||||
return profile
|
||||
|
||||
def _worldbook_group_observation_profile_by_identity(self, user_id: str) -> tuple[str, dict[str, Any]] | None:
|
||||
"""Return the exact, observation-only card for a future private identity merge.
|
||||
|
||||
This is deliberately an exact identity lookup rather than a nickname or
|
||||
alias match. A group nickname is scoped evidence only and must never
|
||||
turn into an implicit private-chat identity link.
|
||||
"""
|
||||
identity = _single_line(user_id, 40)
|
||||
if not identity:
|
||||
return None
|
||||
profiles = self.data.get("worldbook_member_profiles")
|
||||
if not isinstance(profiles, dict):
|
||||
return None
|
||||
direct = profiles.get(identity)
|
||||
if isinstance(direct, dict) and bool(direct.get("observation_only")):
|
||||
return identity, direct
|
||||
for profile_id, profile in profiles.items():
|
||||
if not isinstance(profile, dict) or not bool(profile.get("observation_only")):
|
||||
continue
|
||||
profile_identity = _single_line(profile.get("user_id") or profile_id, 40)
|
||||
if profile_identity == identity:
|
||||
return str(profile_id), profile
|
||||
return None
|
||||
|
||||
def _confirm_worldbook_observation_profile_name(
|
||||
self,
|
||||
profile: dict[str, Any],
|
||||
|
|
|
|||
正在加载…
添加表格
在新工单中引用