feat(companion): unify sleep replies and content tiers

这个提交存在于:
YokiiroBW 2026-08-02 22:08:25 +08:00
父节点 e6d506e2f3
当前提交 05a200be8e
共有 13 个文件被更改,包括 997 次插入 和 47 次删除

查看文件

@ -278,6 +278,48 @@
"hint": "普通用户的当前互动状态最多到这里。管理员账户与专属关系不受此温度上限影响。",
"default": "warm"
},
"enable_relationship_content_tiers": {
"description": "关系内容尺度",
"type": "bool",
"hint": "把日常、含蓄暧昧和成人私密内容纳入统一表达决策。默认关闭;开启也不会仅凭亲密度自动放宽内容。",
"default": false
},
"enable_flirt_content_tier": {
"description": "允许含蓄暧昧档",
"type": "bool",
"hint": "仅在私聊、长期关系至少达到亲密且当前互动不是回避/受伤时允许;始终保持非露骨。",
"default": true,
"condition": "enable_relationship_content_tiers"
},
"enable_adult_content_tier": {
"description": "允许成人私密档",
"type": "bool",
"hint": "高风险总开关。还必须同时满足主要用户、专属关系、爱意互动、私聊、成年确认、当轮明确同意和指定 Provider 精确匹配。",
"default": false,
"condition": "enable_relationship_content_tiers"
},
"adult_content_owner_confirmed": {
"description": "确认主要用户已成年",
"type": "bool",
"hint": "这是管理员后台确认,不会从关系分数、用户话术或模型输出自动推断。",
"default": false,
"condition": "enable_adult_content_tier"
},
"adult_content_require_turn_consent": {
"description": "每轮要求明确同意",
"type": "bool",
"hint": "建议保持开启。开启后只有当轮消息同时明确请求成人尺度并表达同意时才允许。",
"default": true,
"condition": "enable_adult_content_tier"
},
"ADULT_CONTENT_PROVIDER_ID": {
"description": "成人私密档指定 Provider",
"type": "string",
"hint": "只能选择本地或由管理员确认可承载该内容的 Provider。当前会话 Provider 必须与此 ID 精确一致;不可用时直接降级,不回退其他 Provider。",
"default": "",
"condition": "enable_adult_content_tier",
"_special": "select_provider"
},
"owner_exclusive_label": {
"description": "管理员专属关系名称",
"type": "string",

查看文件

@ -14,6 +14,19 @@ from typing import Any, Mapping
EXPRESSION_CONTRACT_VERSION = "companion_interaction_expression.v1"
CONTENT_TIERS = ("normal", "flirt", "adult")
CONTENT_TIER_LABELS = {"normal": "日常", "flirt": "含蓄暧昧", "adult": "成人私密"}
_CONTENT_STAGE_INDEX = {
"deeply_distant": 0,
"strongly_distant": 1,
"distant": 2,
"acquaintance": 3,
"familiar": 4,
"close": 5,
"intimate": 6,
"deeply_bonded": 7,
"owner_exclusive": 8,
}
class ExpressionBand(str, Enum):
@ -66,6 +79,8 @@ class ExpressionDecision:
contract: str
expression_band: str
content_tier: str
content_provider_policy: str
tone: str
warmth: int
distance: int
@ -94,6 +109,7 @@ class ExpressionInput:
relationship_role: str = "friend"
relationship_mode: str = ""
relationship_baseline: Mapping[str, Any] | None = None
relationship_stage: str = ""
normal_interaction_band_cap: str = DEFAULT_NORMAL_INTERACTION_BAND_CAP
current_interaction: str = ""
bot_state: Mapping[str, Any] | None = None
@ -101,6 +117,7 @@ class ExpressionInput:
message_intent: Mapping[str, Any] | None = None
proactive_candidate: Mapping[str, Any] | None = None
safety_constraints: Mapping[str, Any] | None = None
content_policy: Mapping[str, Any] | None = None
administrator_override: str | Mapping[str, Any] | None = None
def to_mapping(self) -> dict[str, Any]:
@ -109,6 +126,7 @@ class ExpressionInput:
"relationship_role": self.relationship_role,
"relationship_mode": self.relationship_mode,
"relationship_baseline": self.relationship_baseline,
"relationship_stage": self.relationship_stage,
"normal_interaction_band_cap": self.normal_interaction_band_cap,
"current_interaction": self.current_interaction,
"bot_state": self.bot_state,
@ -116,6 +134,7 @@ class ExpressionInput:
"message_intent": self.message_intent,
"proactive_candidate": self.proactive_candidate,
"safety_constraints": self.safety_constraints,
"content_policy": self.content_policy,
"administrator_override": self.administrator_override,
}
@ -294,6 +313,91 @@ def _input_mapping(value: Any) -> Mapping[str, Any]:
return _mapping(value)
def content_intent_from_text(value: Any) -> dict[str, Any]:
"""Return a bounded, non-persistent content request classification."""
text = _bounded_text(value, 500).lower()
compact = "".join(text.split())
adult_requested = any(
token in compact
for token in ("nsfw", "成人内容", "成人模式", "露骨", "性爱", "做爱", "色情", "性描写")
)
flirt_requested = adult_requested or any(
token in compact
for token in ("暧昧", "调情", "撩我", "亲密一点", "亲密点", "更亲密", "甜一点")
)
consent = adult_requested and any(
token in compact
for token in ("我同意", "我允许", "可以继续", "想要", "请继续", "进入成人", "开启成人")
)
return {
"requested_content_tier": "adult" if adult_requested else ("flirt" if flirt_requested else "normal"),
"turn_consent": consent,
}
def _resolve_content_tier(
source: Mapping[str, Any],
*,
band: ExpressionBand,
owner_account: bool,
owner_exclusive: bool,
reasons: list[str],
) -> tuple[str, str]:
policy = _mapping(source.get("content_policy"))
intent = _mapping(source.get("message_intent"))
requested = _text(intent.get("requested_content_tier") or intent.get("content_tier"))
if requested not in CONTENT_TIERS:
requested = "normal"
if not _flag(policy.get("enabled")) or requested == "normal":
return "normal", "current_provider"
private_chat = _flag(policy.get("private_chat"))
stage = _text(source.get("relationship_stage"))
stage_rank = _CONTENT_STAGE_INDEX.get(stage, -1)
flirt_allowed = (
_flag(policy.get("flirt_enabled"))
and private_chat
and stage_rank >= _CONTENT_STAGE_INDEX["intimate"]
and band not in {ExpressionBand.AVOIDANT, ExpressionBand.HURT}
)
if requested == "adult":
adult_checks = {
"adult_disabled": _flag(policy.get("adult_enabled")),
"adult_owner_required": owner_account and owner_exclusive,
"adult_affectionate_required": band == ExpressionBand.AFFECTIONATE,
"adult_private_required": private_chat,
"adult_age_confirmation_required": _flag(policy.get("adult_owner_confirmed")),
"adult_turn_consent_required": (
not _flag(policy.get("require_turn_consent")) or _flag(intent.get("turn_consent"))
),
"adult_local_provider_required": (
_flag(policy.get("local_provider_configured")) and _flag(policy.get("local_provider_match"))
),
}
failures = [code for code, passed in adult_checks.items() if not passed]
if not failures:
reasons.append("adult_content_tier_allowed")
return "adult", "configured_local_only"
reasons.extend(failures)
if flirt_allowed:
reasons.append("adult_downgraded_to_flirt")
return "flirt", "current_provider"
reasons.append("adult_downgraded_to_normal")
return "normal", "current_provider"
if flirt_allowed:
reasons.append("flirt_content_tier_allowed")
return "flirt", "current_provider"
if not private_chat:
reasons.append("flirt_private_required")
if stage_rank < _CONTENT_STAGE_INDEX["intimate"]:
reasons.append("flirt_intimate_stage_required")
if band in {ExpressionBand.AVOIDANT, ExpressionBand.HURT}:
reasons.append("flirt_interaction_boundary")
if not _flag(policy.get("flirt_enabled")):
reasons.append("flirt_disabled")
return "normal", "current_provider"
def build_expression_decision(input_data: ExpressionInput | Mapping[str, Any] | None = None, **overrides: Any) -> ExpressionDecision:
"""Build one deterministic expression decision from bounded structured inputs.
@ -431,9 +535,18 @@ def build_expression_decision(input_data: ExpressionInput | Mapping[str, Any] |
if not followup and "followup" in behaviors:
behaviors = tuple(item for item in behaviors if item != "followup")
content_tier, content_provider_policy = _resolve_content_tier(
source,
band=band,
owner_account=owner_account,
owner_exclusive=owner_exclusive,
reasons=reasons,
)
return ExpressionDecision(
contract=EXPRESSION_CONTRACT_VERSION,
expression_band=band.value,
content_tier=content_tier,
content_provider_policy=content_provider_policy,
tone=tone,
warmth=warmth,
distance=distance,
@ -513,12 +626,19 @@ def expression_decision_prompt(value: ExpressionDecision | Mapping[str, Any]) ->
return "当前表达受边界或安全规则限制:保持简短、低压,不主动扩展或追问。"
followup = "可以自然追问" if bool(decision.get("followup")) else "不要追问"
initiative = "允许在合适窗口主动联系" if decision.get("initiative") == "allowed" else "本轮只被动回应"
content_tier = _text(decision.get("content_tier"))
if content_tier == "adult":
content_instruction = "内容尺度=成人私密;只承接本轮明确同意的合法成年人私聊,不扩大同意,不转入群聊、主动消息或其他 Provider"
elif content_tier == "flirt":
content_instruction = "内容尺度=含蓄暧昧;可以亲密和调情,但保持非露骨,不描写成人性行为"
else:
content_instruction = "内容尺度=日常;不要主动升级为暧昧或成人内容"
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}。"
f"{followup};{initiative};{content_instruction}。"
)
@ -533,6 +653,8 @@ def _blocked_decision(reason: str, blocker: str, inherited_reasons: list[str]) -
return ExpressionDecision(
contract=EXPRESSION_CONTRACT_VERSION,
expression_band=ExpressionBand.AVOIDANT.value,
content_tier="normal",
content_provider_policy="current_provider",
tone="blocked",
warmth=0,
distance=100,
@ -555,6 +677,8 @@ resolve_expression_decision = build_expression_decision
__all__ = [
"COMMON_EXPRESSION_BANDS",
"CONTENT_TIERS",
"CONTENT_TIER_LABELS",
"EXPRESSION_CONTRACT_VERSION",
"EXPRESSION_BAND_LABELS",
"ExpressionBand",
@ -566,6 +690,7 @@ __all__ = [
"allowed_expression_bands",
"build_expression_decision",
"current_interaction_projection",
"content_intent_from_text",
"normalize_normal_interaction_band_cap",
"expression_decision_prompt",
"resolve_expression_decision",

查看文件

@ -6828,7 +6828,13 @@ class DailyStateMixin:
)
if not text:
return False
if re.search(r"睡醒|醒来|醒后|刚醒|起床|不睡|没睡|未睡|还没睡|睡不着|失眠", text):
if re.search(r"继续睡|睡回去|重新入睡|再次入睡|回笼觉", text):
return True
if re.search(
r"自然醒|睡醒|醒来|醒后|刚醒|醒了|已醒|醒着|清醒|睁眼|起床|起身|洗漱|"
r"不睡|没睡|未睡|还没睡|睡不着|失眠",
text,
):
return False
return bool(
re.search(

145
main.py
查看文件

@ -148,7 +148,7 @@ from .plugin_identity import (
from .runtime_compat import probe_runtime_capabilities
from .relationship_policy import normalize_relationship_stage_policy
from .relationship_ledger import apply_relationship_event, normalize_relationship_positive_stage_cap_key
from .companion_interaction_expression import build_expression_decision, expression_decision_prompt
from .companion_interaction_expression import build_expression_decision, content_intent_from_text, expression_decision_prompt
from .user_rest_gate import UserRestGateMixin
from .busy_reply_gate import BusyReplyGateMixin
from .memory_companion_adapter import MemoryCompanionAdapterMixin
@ -1458,6 +1458,12 @@ class PrivateCompanionPlugin(
self.normal_interaction_band_cap = self._cfg_str(c, "normal_interaction_band_cap", "warm")
if self.normal_interaction_band_cap not in {"relaxed", "lively", "warm"}:
self.normal_interaction_band_cap = "warm"
self.enable_relationship_content_tiers = self._cfg_bool(c, "enable_relationship_content_tiers", False)
self.enable_flirt_content_tier = self._cfg_bool(c, "enable_flirt_content_tier", True)
self.enable_adult_content_tier = self._cfg_bool(c, "enable_adult_content_tier", False)
self.adult_content_owner_confirmed = self._cfg_bool(c, "adult_content_owner_confirmed", False)
self.adult_content_require_turn_consent = self._cfg_bool(c, "adult_content_require_turn_consent", True)
self.adult_content_provider_id = self._cfg_str(c, "ADULT_CONTENT_PROVIDER_ID", "")
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", "优先使用已确认的专属称呼", "优先使用已确认的专属称呼")
@ -3370,9 +3376,11 @@ class PrivateCompanionPlugin(
return
self._note_inbound_activity_for_scope(event)
self._busy_reply_note_inbound_event(event)
raw = self._event_raw_payload(event)
if raw.get("post_type") not in {"notice", "request", "meta_event"}:
self._record_passive_reply_lifecycle(event, "received", reason_code="inbound_message")
if not self.enable_recall_enhancement:
return
raw = self._event_raw_payload(event)
if raw.get("post_type") == "notice":
notice_type = str(raw.get("notice_type") or "").strip()
if notice_type not in {"friend_recall", "group_recall"}:
@ -3723,6 +3731,7 @@ class PrivateCompanionPlugin(
return
if not bool(getattr(event, "_has_send_oper", False)):
return
self._record_passive_reply_lifecycle(event, "sent", reason_code="platform_send_confirmed")
candidate = getattr(event, "_private_companion_outbound_text_candidate", None)
if isinstance(candidate, dict):
self._confirm_outbound_text_candidate(candidate)
@ -8865,6 +8874,114 @@ wakeup_type={_single_line(wakeup.get('type'), 40)} score={_single_line(wakeup.ge
after=reply_text,
detail=detail_text,
)
self._record_passive_reply_lifecycle(
event,
"cancelled",
reason_code=f"{source_text}:{reason_text}",
)
def _passive_reply_trace_id(self, event: AstrMessageEvent | None) -> str:
if event is None:
return ""
existing = _single_line(getattr(event, "_private_companion_passive_reply_trace_id", ""), 32)
if existing:
return existing
try:
source = _single_line(self._event_message_id(event), 160)
except Exception:
source = ""
if not source:
source = "|".join(
(
_single_line(getattr(event, "unified_msg_origin", ""), 160),
_single_line(getattr(event, "timestamp", ""), 40),
str(id(event)),
)
)
trace_id = hashlib.sha256(source.encode("utf-8", errors="ignore")).hexdigest()[:20]
try:
setattr(event, "_private_companion_passive_reply_trace_id", trace_id)
except Exception:
pass
return trace_id
def _record_passive_reply_lifecycle(
self,
event: AstrMessageEvent | None,
stage: str,
*,
reason_code: str = "",
) -> None:
if event is None or bool(getattr(event, "private_companion_proactive_framework", False)):
return
stage_text = _single_line(stage, 32)
allowed_stages = {
"received", "gate_decided", "request_started", "generated",
"send_attempted", "sent", "failed", "cancelled",
}
if stage_text not in allowed_stages:
return
trace_id = self._passive_reply_trace_id(event)
if not trace_id:
return
now = _now_ts()
root = self.data.setdefault("passive_reply_lifecycle", {})
if not isinstance(root, dict):
root = {}
self.data["passive_reply_lifecycle"] = root
items = root.setdefault("items", [])
if not isinstance(items, list):
items = []
root["items"] = items
item = next(
(entry for entry in items if isinstance(entry, dict) and entry.get("trace_id") == trace_id),
None,
)
if item is None:
item = {"trace_id": trace_id, "created_at": now, "stages": []}
items.insert(0, item)
stages = item.setdefault("stages", [])
if not isinstance(stages, list):
stages = []
item["stages"] = stages
if stages and isinstance(stages[-1], dict) and stages[-1].get("stage") == stage_text:
return
stages.append(
{
"stage": stage_text,
"ts": now,
"reason_code": _single_line(reason_code, 140),
}
)
del stages[:-12]
item["last_stage"] = stage_text
item["last_ts"] = now
item["elapsed_ms"] = max(0, int((now - _safe_float(item.get("created_at"), now)) * 1000))
items.sort(
key=lambda entry: _safe_float(entry.get("last_ts"), 0) if isinstance(entry, dict) else 0,
reverse=True,
)
del items[60:]
root["last_ts"] = now
try:
self._schedule_data_save()
except Exception:
pass
@filter.on_llm_response(priority=-30000)
async def record_passive_reply_generated(self, event: AstrMessageEvent, resp, *args, **kwargs):
if self is None or not bool(getattr(self, "enabled", False)):
return
self._record_passive_reply_lifecycle(event, "generated", reason_code="llm_response_received")
@filter.on_decorating_result(priority=-30000)
async def record_passive_reply_send_attempt(self, event: AstrMessageEvent, *args, **kwargs):
if self is None or not bool(getattr(self, "enabled", False)):
return
result = event.get_result()
chain = list(getattr(result, "chain", []) or []) if result is not None else []
if chain:
self._record_passive_reply_lifecycle(event, "send_attempted", reason_code="outbound_chain_ready")
def _schedule_reply_interception_forward(
self,
@ -9275,6 +9392,12 @@ wakeup_type={_single_line(wakeup.get('type'), 40)} score={_single_line(wakeup.ge
)
)
def _adult_content_provider_matches(self, event: AstrMessageEvent | None, req: ProviderRequest | None) -> bool:
configured = _single_line(getattr(self, "adult_content_provider_id", ""), 160).casefold()
if not configured:
return False
return any(part.casefold() == configured for part in self._llm_request_provider_identity_parts(event, req))
def _llm_request_uses_deepseek_openai_compatible_provider(
self,
event: AstrMessageEvent | None,
@ -9477,6 +9600,17 @@ wakeup_type={_single_line(wakeup.get('type'), 40)} score={_single_line(wakeup.ge
passive_reengagement=True,
bot_state={"energy": transient.get("energy"), "mood": transient.get("mood")},
schedule={"label": transient.get("schedule") or ""},
message_intent=content_intent_from_text(getattr(event, "message_str", "")),
content_policy={
"enabled": bool(getattr(self, "enable_relationship_content_tiers", False)),
"flirt_enabled": bool(getattr(self, "enable_flirt_content_tier", True)),
"adult_enabled": bool(getattr(self, "enable_adult_content_tier", False)),
"adult_owner_confirmed": bool(getattr(self, "adult_content_owner_confirmed", False)),
"require_turn_consent": bool(getattr(self, "adult_content_require_turn_consent", True)),
"private_chat": self._safe_event_is_private(event),
"local_provider_configured": bool(getattr(self, "adult_content_provider_id", "")),
"local_provider_match": self._adult_content_provider_matches(event, req),
},
)
expression_projection = expression.to_dict() if hasattr(expression, "to_dict") else dict(expression or {})
except Exception as exc:
@ -9492,6 +9626,7 @@ wakeup_type={_single_line(wakeup.get('type'), 40)} score={_single_line(wakeup.ge
expression_projection = fallback.to_dict()
try:
setattr(req, "_private_companion_expression_decision", expression_projection)
setattr(event, "_private_companion_expression_decision", expression_projection)
except Exception:
pass
instruction = expression_decision_prompt(expression_projection)
@ -9705,10 +9840,16 @@ wakeup_type={_single_line(wakeup.get('type'), 40)} score={_single_line(wakeup.ge
reason,
)
rest_allowed, rest_reason = await self._should_reply_during_rest(event, is_private_chat=is_private_chat)
self._record_passive_reply_lifecycle(
event,
"gate_decided",
reason_code=("rest_allowed:" if rest_allowed else "rest_blocked:") + _single_line(rest_reason, 100),
)
if not rest_allowed:
log_bookshelf_secret_skip(f"rest_reply_gate:{_single_line(rest_reason, 60)}")
self._stop_reply_for_rest_gate(event, rest_reason)
return
self._record_passive_reply_lifecycle(event, "request_started", reason_code="llm_request_enrichment")
if rest_reason not in {"disabled", "not_sleeping"}:
try:
setattr(event, "private_companion_rest_reply_gate_reason", rest_reason)

查看文件

@ -2363,6 +2363,7 @@ class PrivateCompanionPageApi(PrivateCompanionPageApiQzoneMixin, PrivateCompanio
all_sqlite_items.append(item)
sqlite_status = {**sqlite_status, "items": all_sqlite_items}
passive_no_reply = self._passive_no_reply_summary(data)
passive_reply_lifecycle = self._passive_reply_lifecycle_summary(data)
screen_companion = self._screen_companion_summary(data)
qzone = self._qzone_summary(data)
all_recent_events = self._troubleshooting_recent_events(
@ -2431,6 +2432,7 @@ class PrivateCompanionPageApi(PrivateCompanionPageApiQzoneMixin, PrivateCompanio
"image_api_endpoints": self._troubleshooting_image_api_endpoints(),
"recent_photo_generations": self._recent_photo_generation_summary(data),
"passive_no_reply": passive_no_reply,
"passive_reply_lifecycle": passive_reply_lifecycle,
"prompt_injections": self._prompt_injection_summary(data),
"screen_companion": screen_companion,
"qzone": qzone,
@ -5216,6 +5218,37 @@ class PrivateCompanionPageApi(PrivateCompanionPageApiQzoneMixin, PrivateCompanio
"max_age_seconds": max_age_seconds,
}
def _passive_reply_lifecycle_summary(self, data: dict[str, Any]) -> dict[str, Any]:
raw = data.get("passive_reply_lifecycle")
if not isinstance(raw, dict):
return {"items": [], "last_ts": 0.0}
items: list[dict[str, Any]] = []
for raw_item in raw.get("items", []) if isinstance(raw.get("items"), list) else []:
if not isinstance(raw_item, dict):
continue
stages: list[dict[str, Any]] = []
for raw_stage in raw_item.get("stages", []) if isinstance(raw_item.get("stages"), list) else []:
if not isinstance(raw_stage, dict):
continue
stages.append(
{
"stage": self._single_line(raw_stage.get("stage"), 32),
"ts": self._float(raw_stage.get("ts")),
"reason_code": self._single_line(raw_stage.get("reason_code"), 140),
}
)
items.append(
{
"trace_id": self._single_line(raw_item.get("trace_id"), 24),
"last_stage": self._single_line(raw_item.get("last_stage"), 32),
"last_ts": self._float(raw_item.get("last_ts")),
"elapsed_ms": max(0, self._int(raw_item.get("elapsed_ms"))),
"stages": stages[-12:],
}
)
items.sort(key=lambda item: self._float(item.get("last_ts")), reverse=True)
return {"items": items[:60], "last_ts": self._float(raw.get("last_ts"))}
def _active_token_failures(
self,
recent: Any,
@ -11883,6 +11916,7 @@ class PrivateCompanionPageApi(PrivateCompanionPageApiQzoneMixin, PrivateCompanio
"enable_proactive_only_mode",
"enable_auto_user_profile_creation",
"enable_custom_relationship_stage_policy",
"enable_relationship_content_tiers",
"enable_proactive_chat_integration",
"enable_mai_style_integration",
"enable_companion_memory",
@ -13207,6 +13241,11 @@ class PrivateCompanionPageApi(PrivateCompanionPageApiQzoneMixin, PrivateCompanio
"relationship_stage_policy",
"relationship_positive_stage_cap_key",
"normal_interaction_band_cap",
"enable_relationship_content_tiers",
"enable_flirt_content_tier",
"enable_adult_content_tier",
"adult_content_owner_confirmed",
"adult_content_require_turn_consent",
"owner_exclusive_label",
"owner_exclusive_tone",
"owner_exclusive_address_style",
@ -15181,6 +15220,7 @@ class PrivateCompanionPageApi(PrivateCompanionPageApiQzoneMixin, PrivateCompanio
"NARRATION_PROVIDER_ID": "narration_provider_id",
"HISTORY_SUMMARY_PROVIDER_ID": "history_summary_provider_id",
"RESPONSE_REVIEW_PROVIDER_ID": "response_review_provider_id",
"ADULT_CONTENT_PROVIDER_ID": "adult_content_provider_id",
"SMART_SILENCE_PROVIDER_ID": "smart_silence_provider_id",
"PROACTIVE_PERSONA_JUDGE_PROVIDER_ID": "proactive_persona_judge_provider_id",
"TROUBLESHOOTING_PROVIDER_ID": "troubleshooting_provider_id",
@ -15681,6 +15721,7 @@ class PrivateCompanionPageApi(PrivateCompanionPageApiQzoneMixin, PrivateCompanio
"enable_proactive_only_mode",
"enable_auto_user_profile_creation",
"enable_custom_relationship_stage_policy",
"enable_relationship_content_tiers",
"enable_mai_style_integration",
"enable_companion_memory",
"enable_expression_learning",
@ -15891,6 +15932,11 @@ class PrivateCompanionPageApi(PrivateCompanionPageApiQzoneMixin, PrivateCompanio
"relationship_stage_policy",
"relationship_positive_stage_cap_key",
"normal_interaction_band_cap",
"enable_relationship_content_tiers",
"enable_flirt_content_tier",
"enable_adult_content_tier",
"adult_content_owner_confirmed",
"adult_content_require_turn_consent",
"owner_exclusive_label",
"owner_exclusive_tone",
"owner_exclusive_address_style",

查看文件

@ -19916,37 +19916,27 @@ table {
.private-user-table {
table-layout: fixed;
min-width: 980px;
min-width: 820px;
}
.private-user-table th:nth-child(1),
.private-user-table td:nth-child(1) {
width: 19%;
width: 24%;
}
.private-user-table th:nth-child(2),
.private-user-table td:nth-child(2) {
width: 12%;
width: 25%;
}
.private-user-table th:nth-child(3),
.private-user-table td:nth-child(3) {
width: 14%;
width: 41%;
}
.private-user-table th:nth-child(4),
.private-user-table td:nth-child(4) {
width: 34%;
}
.private-user-table th:nth-child(5),
.private-user-table td:nth-child(5) {
width: 13%;
}
.private-user-table th:nth-child(6),
.private-user-table td:nth-child(6) {
width: 8%;
width: 10%;
text-align: right;
}
@ -20107,6 +20097,99 @@ tbody tr.is-selected {
color: var(--muted);
}
.user-owner-table-wrap {
margin-bottom: 12px;
border-color: color-mix(in srgb, var(--accent) 34%, var(--line-soft));
}
.user-profile-scroll {
max-height: 570px;
overflow: auto;
overscroll-behavior: contain;
}
.user-profile-scroll .user-platform-group td {
position: sticky;
top: 41px;
z-index: 2;
}
.user-role-badges {
display: flex;
gap: 5px;
flex-wrap: wrap;
}
.user-relationship-compact {
display: grid;
gap: 4px;
margin-top: 7px;
}
.user-relationship-line,
.user-status-meta {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
min-width: 0;
}
.user-relationship-line b {
color: var(--accent-strong);
}
.user-relationship-line small,
.user-status-secondary,
.user-status-meta {
color: var(--muted);
font-size: 12px;
}
.user-mini-stage-track {
display: grid;
grid-template-columns: repeat(8, minmax(8px, 1fr));
gap: 3px;
height: 5px;
}
.user-mini-stage-track.interaction {
grid-template-columns: repeat(7, minmax(8px, 1fr));
}
.user-mini-stage-track i {
border-radius: 2px;
background: var(--line-soft);
}
.user-mini-stage-track i.is-current {
background: var(--accent-strong);
box-shadow: 0 0 0 1px color-mix(in srgb, var(--accent-strong) 30%, transparent);
}
.user-mini-stage-track.interaction i.is-current {
background: var(--success, #2fa36b);
}
.user-cell.status {
line-height: 1.45;
}
.user-status-primary,
.user-status-secondary {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.user-status-secondary {
margin-top: 5px;
}
.user-status-meta {
margin-top: 7px;
}
@media (max-width: 720px) {
.user-platform-group button {
grid-template-columns: auto auto 1fr;

查看文件

@ -1020,6 +1020,7 @@ const featureMeta = {
enable_proactive_only_mode: ["仅保留主动能力", "只让本插件负责主动私聊调度、生成和发送;普通私聊/群聊放行给默认主链或其他插件。"],
enable_auto_user_profile_creation: ["新用户默认档案", "首次真实私聊先建立最小用户档案;是否由本插件接管回复、是否允许主动关心分别配置。"],
enable_custom_relationship_stage_policy: ["亲密度阶段策略", "保留固定八阶段和分数范围,配置每一阶段的标签、语气、称呼尺度与软行为上限。"],
enable_relationship_content_tiers: ["关系内容尺度", "把日常、含蓄暧昧和成人私密内容纳入同一表达决策;关系阶段只是必要条件,不会自动授权。"],
enable_mai_style_integration: ["私聊互动策略", "把相处分寸、偏好和本轮接话方式注入回复。"],
enable_companion_memory: ["长期画像", "沉淀用户偏好、边界、关系线索和可复用事实。"],
enable_expression_learning: ["表达方式学习", "从选定私聊或群聊提取抽象表达特征,并按范围用于私聊被动、私聊主动和群聊回复。"],
@ -1150,6 +1151,7 @@ const featureGroups = [
keys: [
"enable_auto_user_profile_creation",
"enable_custom_relationship_stage_policy",
"enable_relationship_content_tiers",
],
},
{
@ -1465,6 +1467,11 @@ const configLabels = {
relationship_stage_policy: "八阶段策略",
relationship_positive_stage_cap_key: "普通用户长期关系上限阶段",
normal_interaction_band_cap: "普通用户互动状态上限",
enable_flirt_content_tier: "允许含蓄暧昧档",
enable_adult_content_tier: "允许成人私密档",
adult_content_owner_confirmed: "确认主要用户已成年",
adult_content_require_turn_consent: "每轮要求明确同意",
ADULT_CONTENT_PROVIDER_ID: "成人私密档指定 Provider",
owner_exclusive_label: "管理员专属关系名称",
owner_exclusive_tone: "管理员专属基础表达",
owner_exclusive_address_style: "管理员专属称呼尺度",
@ -2030,6 +2037,11 @@ const configDescriptions = {
relationship_stage_policy: "固定八阶段键与阈值,只编辑显示、语气、称呼尺度和软行为,不能授予权限或绕过 P4。",
relationship_positive_stage_cap_key: "普通用户的自动与管理员手动调整均不能超过该阶段;owner_exclusive 不受影响。默认是深度联结。",
normal_interaction_band_cap: "普通用户自动或手动可达到的最高互动状态;亲近和爱意始终只属于主要用户。默认是温暖。",
enable_flirt_content_tier: "只允许亲密及以上、私聊且当前互动不是回避或受伤时使用非露骨暧昧表达。",
enable_adult_content_tier: "只打开成人档资格检查,不代表自动授权;主要用户、专属关系、爱意、私聊、成年确认、当轮同意和指定 Provider 必须同时成立。",
adult_content_owner_confirmed: "仅由管理员在后台确认主要用户已成年;插件不会从亲密度、聊天内容或模型结果推断年龄。",
adult_content_require_turn_consent: "开启后每轮都必须在用户当轮消息中识别到明确请求和同意;建议保持开启。",
ADULT_CONTENT_PROVIDER_ID: "当前会话必须已经使用此 Provider 才能进入成人档。未配置、不匹配或调用失败时不得回退其他 Provider。",
owner_exclusive_label: "只修改 owner 专属关系的显示名称,不增加管理或安全权限。",
owner_exclusive_tone: "专属关系的长期表达基线;当前互动状态仍可使本轮收敛。",
owner_exclusive_address_style: "优先沿用双方已确认的专属称呼。",
@ -2622,6 +2634,13 @@ const featureSettingGroups = {
"emotional_gate_refuse_threshold",
"emotional_gate_max_hurt_minutes",
],
enable_relationship_content_tiers: [
"enable_flirt_content_tier",
"enable_adult_content_tier",
"adult_content_owner_confirmed",
"adult_content_require_turn_consent",
"ADULT_CONTENT_PROVIDER_ID",
],
enable_mai_style_integration: [
"default_style",
"reply_style_prompt",
@ -2735,6 +2754,18 @@ const featureSettingGroups = {
};
const featureSettingSections = {
enable_relationship_content_tiers: [
{
title: "普通暧昧",
note: "只在亲密及以上的普通私聊中允许非露骨表达;回避或受伤时自动收敛。",
keys: ["enable_flirt_content_tier"],
},
{
title: "成人私密边界",
note: "成人档不会由关系自动开启;缺少任一条件都会降级,并且绝不回退到其他 Provider。",
keys: ["enable_adult_content_tier", "adult_content_owner_confirmed", "adult_content_require_turn_consent", "ADULT_CONTENT_PROVIDER_ID"],
},
],
enable_reply_interception_forward: [
{
title: "转发目标与范围",
@ -3409,6 +3440,11 @@ const featureSettingTypes = {
default_interaction_band: { type: "select", options: [["avoidant", "回避"], ["hurt", "受伤"], ["relaxed", "放松"], ["lively", "活泼"], ["warm", "温暖"]] },
relationship_positive_stage_cap_key: { type: "select", options: [["familiar", "熟悉"], ["close", "亲近"], ["intimate", "亲密"], ["deeply_bonded", "深度联结"]] },
normal_interaction_band_cap: { type: "select", options: [["relaxed", "放松"], ["lively", "活泼"], ["warm", "温暖"]] },
enable_flirt_content_tier: { type: "checkbox" },
enable_adult_content_tier: { type: "checkbox" },
adult_content_owner_confirmed: { type: "checkbox" },
adult_content_require_turn_consent: { type: "checkbox" },
ADULT_CONTENT_PROVIDER_ID: { type: "provider" },
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 },
@ -12435,19 +12471,36 @@ function compareUsersForList(a, b) {
return result * direction;
}
function renderCompactRelationshipTracks(user) {
const intimacy = user.relationship_intimacy || {};
const stages = normalizedRelationshipStages(intimacy.stages);
const currentStage = String(intimacy.phase?.key || "");
const interaction = String(user.current_interaction?.expression_band || "relaxed");
const interactionLabel = user.current_interaction?.label || interaction || "放松";
const intimacyLabel = intimacy.phase?.label || intimacy.band || "初识";
return `
<div class="user-relationship-compact">
<div class="user-relationship-line"><b>${escapeHtml(intimacyLabel)}</b><span>${escapeHtml(intimacy.value ?? 0)}</span></div>
<div class="user-mini-stage-track" aria-label="亲密度阶段 ${escapeHtml(intimacyLabel)}">
${stages.map((stage) => `<i class="${String(stage.key) === currentStage ? "is-current" : ""}" title="${escapeHtml(stage.label)}"></i>`).join("")}
</div>
<div class="user-relationship-line"><small>互动状态</small><span>${escapeHtml(interactionLabel)}</span></div>
<div class="user-mini-stage-track interaction" aria-label="互动状态 ${escapeHtml(interactionLabel)}">
${INTERACTION_BANDS.map(([key, label]) => `<i class="${key === interaction ? "is-current" : ""}" title="${escapeHtml(label)}"></i>`).join("")}
</div>
</div>`;
}
function renderUserTableRow(user) {
const privateEnabled = Boolean(user.private_companion_enabled ?? user.enabled);
const groupRelationshipEnabled = Boolean(user.group_relationship_enabled);
const groupProfile = Boolean(user.group_observation_profile);
const createdText = user.profile_created || (userCreatedTimestamp(user) ? new Date(userCreatedTimestamp(user) * 1000).toLocaleString() : "未知");
const interactionLabel = user.current_interaction?.label || user.current_interaction?.expression_band || "放松";
return `
<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)}${user.relationship_role === "owner" ? ` <span class="badge ok">主人</span>` : ""}${groupProfile ? ` <span class="badge">群聊建档</span>` : ""}${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 ${privateEnabled ? "ok" : "off"}">${escapeHtml(privateEnabled ? "私聊启用" : "私聊仅观测")}</span> ${groupRelationshipEnabled ? `<span class="badge ok">群关系启用</span>` : ""} <span class="badge">${escapeHtml(user.relationship_role_label || "次要用户")}</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)} · 互动 ${escapeHtml(interactionLabel)}</small></span></td>
<td class="user-cell compact">${groupProfile ? `观察群 ${escapeHtml(user.observed_group_count || 0)} 个 · 群关系事件 ${escapeHtml(user.group_relationship_event_count || 0)}<br><span class="muted">${escapeHtml(user.private_memory_enabled ? "私聊记忆启用" : "私聊记忆关闭")}</span>` : `入站 ${escapeHtml(user.inbound_count || 0)} · 回复 ${escapeHtml(user.reply_count || 0)}<br><span class="muted">记忆 ${escapeHtml(user.memory_items || 0)} 条</span>`}</td>
<td class="user-cell proactive">${privateEnabled ? `<span>今日 ${escapeHtml(user.sent_today || 0)} · 总计 ${escapeHtml(user.proactive_sent_count || 0)}</span><br><span class="muted truncate" title="${escapeHtml(user.next_proactive || "")}">${escapeHtml(user.next_proactive || "暂无主动计划")}</span>` : `<span>不主动触达</span><br><span class="muted">私聊陪伴关闭</span>`}</td>
<td class="user-cell recent">${escapeHtml(user.last_seen || "暂无活动")}<br><span class="muted" title="${escapeHtml(createdText)}">建档 ${escapeHtml(createdText)}</span></td>
<td class="user-cell relation"><div class="user-role-badges"><span class="badge ${privateEnabled ? "ok" : "off"}">${escapeHtml(privateEnabled ? "私聊启用" : "私聊仅观测")}</span>${groupRelationshipEnabled ? `<span class="badge ok">群关系启用</span>` : ""}<span class="badge">${escapeHtml(user.relationship_role_label || "次要用户")}</span></div>${renderCompactRelationshipTracks(user)}</td>
<td class="user-cell status"><div class="user-status-primary">${groupProfile ? `观察群 ${escapeHtml(user.observed_group_count || 0)} 个 · 关系事件 ${escapeHtml(user.group_relationship_event_count || 0)}` : `入站 ${escapeHtml(user.inbound_count || 0)} · 回复 ${escapeHtml(user.reply_count || 0)} · 记忆 ${escapeHtml(user.memory_items || 0)}`}</div><div class="user-status-secondary">${privateEnabled ? `主动 ${escapeHtml(user.sent_today || 0)} / ${escapeHtml(user.proactive_sent_count || 0)} · <span title="${escapeHtml(user.next_proactive || "")}">${escapeHtml(user.next_proactive || "暂无下次主动计划")}</span>` : "不主动触达 · 私聊陪伴关闭"}</div><div class="user-status-meta"><span>${escapeHtml(user.last_seen || "暂无活动")}</span><span title="${escapeHtml(createdText)}">建档 ${escapeHtml(createdText)}</span></div></td>
<td class="user-cell action"><button type="button" class="table-action ${privateEnabled ? "danger-outline" : ""}" data-user-toggle="${escapeHtml(user.user_id)}">${escapeHtml(privateEnabled ? "关闭私聊" : "开启私聊")}</button></td>
</tr>`;
}
@ -12457,7 +12510,7 @@ function renderUserGroupRows(groupKey, label, note, users, options = {}) {
const collapsed = options.fixedOpen ? false : Boolean(state.userPlatformCollapsed[groupKey]);
return `
<tr class="user-platform-group ${options.owner ? "is-owner-group" : ""}" data-user-platform-group="${escapeHtml(groupKey)}">
<td colspan="6"><button type="button" ${options.fixedOpen ? "disabled" : `data-user-platform-toggle="${escapeHtml(groupKey)}"`} aria-expanded="${collapsed ? "false" : "true"}"><span>${options.fixedOpen ? "★" : collapsed ? "▸" : "▾"}</span><b>${escapeHtml(label)}</b><small>${escapeHtml(note)}</small><em>${users.length}</em></button></td>
<td colspan="4"><button type="button" ${options.fixedOpen ? "disabled" : `data-user-platform-toggle="${escapeHtml(groupKey)}"`} aria-expanded="${collapsed ? "false" : "true"}"><span>${options.fixedOpen ? "★" : collapsed ? "▸" : "▾"}</span><b>${escapeHtml(label)}</b><small>${escapeHtml(note)}</small><em>${users.length}</em></button></td>
</tr>
${collapsed ? "" : users.map(renderUserTableRow).join("")}`;
}
@ -12482,16 +12535,19 @@ function renderUsers() {
["telegram", "Telegram", "Telegram 适配器"],
["web_other", "网页 / 其他", "AstrBot WebChat 与其他适配器"],
];
const groupedRows = [
renderUserGroupRows("owner", "主要用户", "主人始终置顶,不受排序字段影响", owners, { fixedOpen: true, owner: true }),
...groupSpecs.map(([groupKey, label, note]) => renderUserGroupRows(
const ownerWrap = $("#userOwnerTableWrap");
const ownerRows = $("#userOwnerRows");
if (ownerWrap && ownerRows) {
ownerWrap.hidden = owners.length === 0;
ownerRows.innerHTML = owners.map(renderUserTableRow).join("");
}
const groupedRows = groupSpecs.map(([groupKey, label, note]) => renderUserGroupRows(
groupKey,
label,
note,
regularRows.filter((user) => userPlatformGroup(user) === groupKey).sort(compareUsersForList),
)),
].join("");
$("#userRows").innerHTML = rows.length ? groupedRows : `<tr><td class="empty" colspan="6">暂无用户档案</td></tr>`;
)).join("");
$("#userRows").innerHTML = regularRows.length ? groupedRows : `<tr><td class="empty" colspan="4">暂无普通用户档案</td></tr>`;
document.querySelectorAll("[data-user-platform-toggle]").forEach((button) => {
button.addEventListener("click", () => {
const key = button.dataset.userPlatformToggle || "web_other";
@ -21095,6 +21151,11 @@ function featureRelatedSettings(key) {
main_user_mention_voice_prompt: "",
relationship_positive_stage_cap_key: "deeply_bonded",
normal_interaction_band_cap: "warm",
enable_flirt_content_tier: true,
enable_adult_content_tier: false,
adult_content_owner_confirmed: false,
adult_content_require_turn_consent: true,
ADULT_CONTENT_PROVIDER_ID: "",
};
return Object.prototype.hasOwnProperty.call(defaults, name) ? defaults[name] : undefined;
};
@ -21196,6 +21257,15 @@ function featureSettingVisibleForCurrentMode(featureKey, settingKey, settings =
if (Object.prototype.hasOwnProperty.call(state.featureDraft || {}, name)) return state.featureDraft[name];
return Object.prototype.hasOwnProperty.call(settings, name) ? settings[name] : fallback;
};
if (featureKey === "enable_relationship_content_tiers") {
const adultOnly = new Set([
"adult_content_owner_confirmed",
"adult_content_require_turn_consent",
"ADULT_CONTENT_PROVIDER_ID",
]);
if (adultOnly.has(settingKey)) return boolSetting("enable_adult_content_tier");
return true;
}
if (featureKey === "enable_livingmemory_integration") {
const livingmemory = state.overview?.livingmemory || {};
const memoryCompanionActive = Boolean(livingmemory.memory_companion_active);
@ -21639,7 +21709,7 @@ function featureProviderSelect(key, value) {
const known = state.availableProviders.some((item) => item.id === current);
const customValue = current && !known ? current : "";
const options = [
`<option value="">留空自动回退</option>`,
`<option value="">${key === "ADULT_CONTENT_PROVIDER_ID" ? "未配置(成人档不可用)" : "留空自动回退"}</option>`,
...state.availableProviders.map((item) => {
const label = `${item.name || item.id}${item.model ? ` · ${item.model}` : ""}${item.is_default ? " · 默认" : ""}`;
return `<option value="${escapeHtml(item.id)}" ${item.id === current ? "selected" : ""}>${escapeHtml(label)}</option>`;
@ -21790,6 +21860,10 @@ function featureDependencyLines(key) {
else if (proactiveChat.installed) dependencies.push(["Proactive Chat", "已检测到插件;开启联动后会优先建立深度运行时桥接"]);
else dependencies.push(["Proactive Chat", "未检测到;安装后无需修改对方插件,本页联动开关会自动生效"]);
}
if (key === "enable_relationship_content_tiers") {
dependencies.push(["关系条件", "长期亲密度阶段 + 当前互动状态"]);
dependencies.push(["成人档", "主要用户专属关系 + 成年确认 + 当轮同意 + 指定 Provider"]);
}
if (key !== "enable_group_companion" && key.startsWith("enable_group_")) dependencies.push(["依赖", "群聊总开关"]);
if (key === "enable_group_conversation_followup") dependencies.push(["依赖", "群聊场景感知"]);
if (["enable_companion_memory", "enable_expression_learning", "enable_intent_emotion_analysis", "enable_passive_response_review", "enable_proactive_message_review", "enable_smart_silence", "enable_passive_topic_suppression", "enable_relationship_analysis", "enable_relationship_state_machine", "enable_emotion_simulation", "enable_dialogue_episode_memory", "enable_open_loop_tracking", "enable_food_menu_recommendation"].includes(key)) {
@ -21822,6 +21896,12 @@ function featureDependencyLines(key) {
}
const featureDetailGuides = {
enable_relationship_content_tiers: {
summary: "在统一表达决策里选择日常、含蓄暧昧或成人私密尺度;它不新增关系状态,也不改变既有权限。",
trigger: "目标私聊进入主模型请求前,根据当轮明确意图、长期关系、当前互动状态和 Provider 身份共同判定。",
enabled: "普通暧昧仍受亲密阶段和互动状态约束;成人档只对已确认的主要用户专属私聊开放,缺条件自动降级。",
disabled: "所有请求保持日常档;主动消息、群聊、普通用户和记忆插件上下文始终不获得成人内容授权。",
},
enable_auto_user_profile_creation: {
summary: "首次真实私聊建立最小用户档案,并把默认称呼、语气、角色、亲密度和主动边界集中到一处。",
trigger: "收到非 Bot 回流的真实私聊事件,且平台在允许列表中、当前身份尚无档案时。",
@ -23054,6 +23134,12 @@ function bindFeatureDetailActions() {
) {
syncSettingBackedFeatureParam(input.dataset.featureParam, { rerender: true });
}
if (
state.selectedFeatureKey === "enable_relationship_content_tiers"
&& input.dataset.featureParam === "enable_adult_content_tier"
) {
syncSettingBackedFeatureParam(input.dataset.featureParam, { rerender: true });
}
if (
state.selectedFeatureKey === "enable_humanized_states"
&& [

查看文件

@ -4,7 +4,7 @@
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>陪伴面板</title>
<link rel="stylesheet" href="./app.css?v=20260802-user-profile-memory-caps-v1" />
<link rel="stylesheet" href="./app.css?v=20260802-req030-v1" />
<link rel="stylesheet" href="./css/header-tools.css?v=20260713-font-options" />
<link rel="stylesheet" href="./css/qzone-mobile.css?v=20260711-qzone-image-preview" />
<link rel="stylesheet" href="./css/polish.css?v=20260715-learning-nav-merged-v1" />
@ -488,15 +488,26 @@ QQ空间 = 公开札记
<label>身份别名归并 <textarea name="private_user_aliases" rows="3" placeholder="临时ID=主用户ID&#10;机器人侧ID=主用户ID"></textarea></label>
<button type="submit">保存归并规则</button>
</form>
<div class="table-wrap">
<div id="userOwnerTableWrap" class="table-wrap user-owner-table-wrap" hidden>
<table class="private-user-table private-user-owner-table">
<thead>
<tr>
<th>主要用户</th>
<th>关系</th>
<th>状态</th>
<th>操作</th>
</tr>
</thead>
<tbody id="userOwnerRows"></tbody>
</table>
</div>
<div class="table-wrap user-profile-scroll">
<table class="private-user-table">
<thead>
<tr>
<th>用户</th>
<th>关系</th>
<th>互动</th>
<th>主动</th>
<th>最近</th>
<th>状态</th>
<th>操作</th>
</tr>
</thead>
@ -1602,6 +1613,6 @@ QQ空间 = 公开札记
<script src="./js/ui/appearance.js?v=20260713-font-options"></script>
<script src="./js/panels/provider-tree.js?v=20260723-provider-filter-immediate"></script>
<script src="./js/panels/qzone-panel.js?v=20260711-qzone-preview-context"></script>
<script src="./app.js?v=20260802-user-profile-memory-caps-v1"></script>
<script src="./app.js?v=20260802-req030-v1"></script>
</body>
</html>

查看文件

@ -274,7 +274,8 @@ class Req027UserProfileRelationshipPolicyTests(unittest.TestCase):
self.assertIn(".user-platform-group button", css)
self.assertIn("DEFAULT_RELATIONSHIP_POLICY", source)
self.assertIn("relationship-stage-bar", source)
self.assertIn("relationship-phase-summary", source)
self.assertIn("user-relationship-compact", source)
self.assertIn("renderCompactRelationshipTracks", source)
self.assertIn('data-feature-open="${escapeHtml(key)}"', source)
self.assertIn("新用户默认档案", source)
self.assertIn("亲密度阶段策略", source)

查看文件

@ -324,7 +324,9 @@ class Req029GroupRelationshipProfileTests(unittest.TestCase):
app = (ROOT / "pages" / "陪伴面板" / "app.js").read_text(encoding="utf-8")
html = (ROOT / "pages" / "陪伴面板" / "index.html").read_text(encoding="utf-8")
api = (ROOT / "page_api_users_groups.py").read_text(encoding="utf-8")
self.assertIn('renderUserGroupRows("owner"', app)
self.assertIn('const ownerWrap = $("#userOwnerTableWrap")', app)
self.assertIn('ownerRows.innerHTML = owners.map(renderUserTableRow).join("")', app)
self.assertIn('id="userOwnerRows"', html)
self.assertIn('localeCompare(String(b.display_name', app)
self.assertIn('state.userSortKey === "intimacy"', app)
self.assertIn('state.userSortKey === "created"', app)

查看文件

@ -0,0 +1,357 @@
from __future__ import annotations
import ast
import asyncio
import hashlib
import json
from pathlib import Path
import re
import sys
import time
from types import SimpleNamespace
from typing import Any
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT))
from companion_interaction_expression import ( # noqa: E402
EXPRESSION_CONTRACT_VERSION,
build_expression_decision,
content_intent_from_text,
)
def _class_method(filename: str, class_name: str, method_name: str, namespace: 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)
method = next(
node
for node in owner.body
if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) and node.name == method_name
)
module = ast.Module(
body=[ast.ImportFrom(module="__future__", names=[ast.alias(name="annotations")], level=0), method],
type_ignores=[],
)
ast.fix_missing_locations(module)
exec(compile(module, str(ROOT / filename), "exec"), namespace)
return namespace[method_name]
def _single_line(value: Any, limit: int = 0) -> str:
text = " ".join(str(value or "").split())
return text[:limit] if limit else text
def _safe_float(value: Any, default: float = 0.0) -> float:
try:
return float(value)
except (TypeError, ValueError):
return default
def test_natural_wake_schedule_wins_over_bedding_and_retrospective_sleep_words() -> None:
namespace = {"Any": Any, "re": re, "_single_line": _single_line}
sleepy = _class_method("daily_state.py", "DailyStateMixin", "_is_sleepy_plan_item", namespace)
host = SimpleNamespace()
item = {
"activity": "自然醒后赖在被窝里看看消息",
"mood": "清醒,慢慢起身",
"message_seed": "想起昨晚睡前聊到的事",
}
assert sleepy(host, item) is False
assert sleepy(host, {"activity": "醒了一下又继续睡,睡回去补个回笼觉"}) is True
assert sleepy(host, {"activity": "洗漱后准备早餐", "message_seed": "早上好"}) is False
def test_0824_rest_gate_returns_not_sleeping_for_natural_wake_schedule() -> None:
namespace = {
"Any": Any,
"re": re,
"_single_line": _single_line,
"_safe_float": _safe_float,
"_now_ts": lambda: 1_700_000_000.0,
}
sleepy = _class_method("daily_state.py", "DailyStateMixin", "_is_sleepy_plan_item", namespace)
refresh = _class_method("daily_state.py", "DailyStateMixin", "_refresh_sleep_runtime_state", namespace)
rest_context = _class_method("main.py", "PrivateCompanionPlugin", "_rest_reply_sleep_context", namespace)
should_reply = _class_method("main.py", "PrivateCompanionPlugin", "_should_reply_during_rest", namespace)
class Host:
enable_rest_reply_simulation = True
rest_reply_llm_threshold = 65
def __init__(self) -> None:
self.item = {
"activity": "自然醒后还窝在被窝里",
"mood": "已经清醒",
"message_seed": "昨晚睡前的话题还记得",
}
self.runtime = {"phase": "falling_asleep", "updated_at": 100.0}
self.data = {"daily_plan": {"items": [self.item]}}
def _get_current_plan_item(self, _plan: dict[str, Any]) -> dict[str, Any]:
return self.item
def _sleep_runtime_state(self) -> dict[str, Any]:
return self.runtime
def _sleep_rest_window_active(self) -> bool:
return True
def _rest_reply_window_active(self) -> bool:
return True
def _sleep_delay_override_state(self, *_args: Any, **_kwargs: Any) -> None:
return None
def _sleep_awake_grace_seconds(self) -> int:
return 1800
def _set_sleep_phase(self, phase: str, **_kwargs: Any) -> dict[str, Any]:
self.runtime.update({"phase": phase, "updated_at": 1_700_000_000.0})
return self.runtime
def _format_plan_item_for_prompt(self, item: dict[str, Any]) -> str:
return str(item.get("activity") or "")
Host._is_sleepy_plan_item = sleepy
Host._refresh_sleep_runtime_state = refresh
Host._rest_reply_sleep_context = rest_context
Host._should_reply_during_rest = should_reply
host = Host()
sleeping, runtime, _, _ = host._rest_reply_sleep_context()
assert sleeping is False
assert runtime["phase"] == "natural_wake"
allowed, reason = asyncio.run(host._should_reply_during_rest(SimpleNamespace(), is_private_chat=True))
assert allowed is True
assert reason == "not_sleeping"
def _content_payload(**overrides: Any) -> dict[str, Any]:
payload: dict[str, Any] = {
"relationship_role": "owner",
"relationship_mode": "owner_exclusive",
"relationship_stage": "owner_exclusive",
"current_interaction": "affectionate",
"message_intent": {"requested_content_tier": "adult", "turn_consent": True},
"content_policy": {
"enabled": True,
"flirt_enabled": True,
"adult_enabled": True,
"adult_owner_confirmed": True,
"require_turn_consent": True,
"private_chat": True,
"local_provider_configured": True,
"local_provider_match": True,
},
}
for key, value in overrides.items():
if key.startswith("policy_"):
payload["content_policy"][key.removeprefix("policy_")] = value
else:
payload[key] = value
return payload
def test_content_tier_matrix_and_intent_are_deterministic() -> None:
assert EXPRESSION_CONTRACT_VERSION == "companion_interaction_expression.v1"
assert content_intent_from_text("我同意,开启成人模式并继续") == {
"requested_content_tier": "adult",
"turn_consent": True,
}
assert content_intent_from_text("说得暧昧一点")["requested_content_tier"] == "flirt"
assert build_expression_decision({}).content_tier == "normal"
flirt = build_expression_decision(
{
"relationship_role": "friend",
"relationship_stage": "intimate",
"current_interaction": "warm",
"message_intent": {"requested_content_tier": "flirt"},
"content_policy": {"enabled": True, "flirt_enabled": True, "private_chat": True},
}
)
assert flirt.content_tier == "flirt"
assert flirt.content_provider_policy == "current_provider"
adult = build_expression_decision(_content_payload())
assert adult.content_tier == "adult"
assert adult.content_provider_policy == "configured_local_only"
def test_adult_tier_fails_closed_when_any_required_condition_is_missing() -> None:
cases = {
"total switch": {"policy_enabled": False},
"adult switch": {"policy_adult_enabled": False},
"owner": {"relationship_role": "friend"},
"exclusive": {"relationship_mode": "normal"},
"affectionate": {"current_interaction": "warm"},
"private": {"policy_private_chat": False},
"age": {"policy_adult_owner_confirmed": False},
"consent": {"message_intent": {"requested_content_tier": "adult", "turn_consent": False}},
"provider configured": {"policy_local_provider_configured": False},
"provider match": {"policy_local_provider_match": False},
}
for label, override in cases.items():
decision = build_expression_decision(_content_payload(**override))
assert decision.content_tier != "adult", label
assert decision.content_provider_policy == "current_provider", label
def test_group_proactive_and_unconfigured_paths_remain_normal() -> None:
group = build_expression_decision(_content_payload(policy_private_chat=False))
proactive = build_expression_decision(
{
"relationship_role": "owner",
"relationship_mode": "owner_exclusive",
"current_interaction": "affectionate",
"message_intent": {"requested_content_tier": "adult", "turn_consent": True},
"proactive_candidate": {"eligible": True, "daily_allowance": 3},
}
)
assert group.content_tier != "adult"
assert proactive.content_tier == "normal"
def test_strict_llm_provider_skips_peak_replacement_and_fallback() -> None:
namespace = {
"Any": Any,
"asyncio": asyncio,
"time": time,
"_single_line": _single_line,
"logger": SimpleNamespace(info=lambda *_a, **_k: None, warning=lambda *_a, **_k: None),
}
llm_call = _class_method("token_budget.py", "TokenBudgetMixin", "_llm_call", namespace)
class Host:
llm_provider_id = "cloud-default"
model_timeout_overrides: dict[str, Any] = {}
def __init__(self) -> None:
self.called_provider = ""
self.peak_calls = 0
self.fallback_calls = 0
self.context = SimpleNamespace(llm_generate=self._generate)
async def _generate(self, **kwargs: Any):
self.called_provider = kwargs["chat_provider_id"]
return SimpleNamespace(completion_text="ok")
def _resolve_chat_provider_id(self, provider_id: str | None) -> str:
return str(provider_id or self.llm_provider_id)
def _apply_deepseek_peak_replacement(self, provider_id: str) -> str:
self.peak_calls += 1
return "cloud-replacement"
def _classify_llm_prompt(self, _prompt: str) -> str:
return "response_review"
def _is_llm_budget_exempt_task(self, _task: str) -> bool:
return True
def _daily_token_soft_limit_should_defer(self, _task: str) -> bool:
return False
def _llm_daily_budget_remaining(self) -> int:
return 1
def _model_fallback_provider_for_call(self, **_kwargs: Any):
self.fallback_calls += 1
return "response_review", "cloud-fallback"
def _model_timeout_seconds_for_call(self, **_kwargs: Any) -> None:
return None
def _record_llm_usage(self, **_kwargs: Any) -> None:
return None
Host._llm_call = llm_call
host = Host()
result = asyncio.run(
host._llm_call(
"review",
provider_id="local-adult",
task="response_review",
strict_provider=True,
)
)
assert result == "ok"
assert host.called_provider == "local-adult"
assert host.peak_calls == 0
assert host.fallback_calls == 0
def test_passive_reply_lifecycle_is_hash_only_and_redacted() -> None:
namespace = {
"Any": Any,
"hashlib": hashlib,
"_single_line": _single_line,
"_now_ts": lambda: 1_700_000_000.0,
"_safe_float": _safe_float,
}
trace_method = _class_method("main.py", "PrivateCompanionPlugin", "_passive_reply_trace_id", namespace)
record_method = _class_method("main.py", "PrivateCompanionPlugin", "_record_passive_reply_lifecycle", namespace)
class Event:
unified_msg_origin = "sensitive-session-id"
message_str = "sensitive-message-body"
timestamp = 1_700_000_000
class Host:
def __init__(self) -> None:
self.data: dict[str, Any] = {}
def _event_message_id(self, _event: Any) -> str:
return "platform-message-id"
def _schedule_data_save(self) -> None:
return None
Host._passive_reply_trace_id = trace_method
Host._record_passive_reply_lifecycle = record_method
host = Host()
event = Event()
host._record_passive_reply_lifecycle(event, "received", reason_code="inbound_message")
host._record_passive_reply_lifecycle(event, "gate_decided", reason_code="rest_allowed:not_sleeping")
stored = json.dumps(host.data, ensure_ascii=False)
assert "sensitive-session-id" not in stored
assert "sensitive-message-body" not in stored
assert "platform-message-id" not in stored
item = host.data["passive_reply_lifecycle"]["items"][0]
assert re.fullmatch(r"[0-9a-f]{20}", item["trace_id"])
assert [stage["stage"] for stage in item["stages"]] == ["received", "gate_decided"]
def test_schema_and_settings_page_expose_fail_closed_content_controls() -> None:
schema = json.loads((ROOT / "_conf_schema.json").read_text(encoding="utf-8-sig"))
items = schema["basic_config"]["items"]
assert items["enable_relationship_content_tiers"]["default"] is False
assert items["enable_adult_content_tier"]["default"] is False
assert items["adult_content_owner_confirmed"]["default"] is False
assert items["adult_content_require_turn_consent"]["default"] is True
assert items["ADULT_CONTENT_PROVIDER_ID"]["_special"] == "select_provider"
source = (ROOT / "pages" / "陪伴面板" / "app.js").read_text(encoding="utf-8")
assert 'enable_relationship_content_tiers: ["关系内容尺度"' in source
assert 'data-feature-open="${escapeHtml(key)}"' in source
assert 'key === "ADULT_CONTENT_PROVIDER_ID" ? "未配置(成人档不可用)"' in source
assert "绝不回退到其他 Provider" in source
def test_profile_table_keeps_owner_separate_and_regular_rows_scroll() -> None:
source = (ROOT / "pages" / "陪伴面板" / "app.js").read_text(encoding="utf-8")
html = (ROOT / "pages" / "陪伴面板" / "index.html").read_text(encoding="utf-8")
css = (ROOT / "pages" / "陪伴面板" / "app.css").read_text(encoding="utf-8")
assert 'const ownerWrap = $("#userOwnerTableWrap")' in source
assert 'ownerRows.innerHTML = owners.map(renderUserTableRow).join("")' in source
assert 'id="userOwnerRows"' in html
assert 'class="table-wrap user-profile-scroll"' in html
assert html.count("<th>") >= 8
assert ".user-profile-scroll" in css
assert "max-height: 570px" in css
assert "renderCompactRelationshipTracks(user)" in source
assert 'colspan="4"' in source

查看文件

@ -943,10 +943,11 @@ class TokenBudgetMixin:
system_prompt: str | None = None,
timeout_key: str | None = None,
timeout_seconds: float | None = None,
strict_provider: bool = False,
) -> str | None:
selected_provider = self._resolve_chat_provider_id(provider_id)
peak_router = getattr(self, "_apply_deepseek_peak_replacement", None)
if callable(peak_router) and (str(provider_id or "").strip() or str(getattr(self, "llm_provider_id", "") or "").strip()):
if not strict_provider and callable(peak_router) and (str(provider_id or "").strip() or str(getattr(self, "llm_provider_id", "") or "").strip()):
selected_provider = peak_router(selected_provider)
task_key = _single_line(task, 40) or self._classify_llm_prompt(prompt)
budget_exempt = self._is_llm_budget_exempt_task(task_key)
@ -961,11 +962,14 @@ class TokenBudgetMixin:
if not budget_exempt and self._llm_daily_budget_remaining() == 0:
self._record_llm_budget_skip(provider_id=selected_provider, task=task_key, prompt=prompt)
return None
provider_key, fallback_provider = self._model_fallback_provider_for_call(
task=task_key,
primary_provider_id=selected_provider,
provider_key=str(timeout_key or ""),
)
if strict_provider:
provider_key, fallback_provider = str(timeout_key or task_key), ""
else:
provider_key, fallback_provider = self._model_fallback_provider_for_call(
task=task_key,
primary_provider_id=selected_provider,
provider_key=str(timeout_key or ""),
)
if fallback_provider and callable(peak_router):
fallback_provider = peak_router(fallback_provider)
candidates = [selected_provider]

查看文件

@ -5277,6 +5277,30 @@ Local classifier result:
)
return any(re.search(pattern, response, re.IGNORECASE) for pattern in denial_patterns)
@staticmethod
def _response_content_tier(review_event: Any | None) -> str:
decision = getattr(review_event, "_private_companion_expression_decision", None) if review_event is not None else None
tier = str(decision.get("content_tier") or "normal").strip().lower() if isinstance(decision, dict) else "normal"
return tier if tier in {"normal", "flirt", "adult"} else "normal"
@staticmethod
def _response_contains_explicit_adult_content(value: Any) -> bool:
text = _single_line(value, 1200).lower()
if not text:
return False
return bool(
re.search(
r"nsfw|色情|露骨|性行为|性交|做爱|口交|肛交|阴茎|阴道|射精|高潮|"
r"裸体|全裸|性器官|乳房",
text,
re.IGNORECASE,
)
)
@staticmethod
def _content_tier_boundary_reply() -> str:
return "这个尺度我先不往露骨方向展开,我们换成更含蓄一点的说法吧。"
async def _review_and_rewrite_response(
self,
user: dict[str, Any],
@ -5309,6 +5333,13 @@ Local classifier result:
_single_line(fallback, 160),
)
return fallback
content_tier = self._response_content_tier(review_event)
if content_tier != "adult" and self._response_contains_explicit_adult_content(response_text):
logger.warning(
"[PrivateCompanion] 回复超出统一内容尺度,已本地收敛: tier=%s",
content_tier,
)
return self._content_tier_boundary_reply()
if not self._passive_response_review_enabled():
return self._fallback_temporal_or_continuity_confused_reply(inbound_text, response_text, user=user) or response_text
flags = self._response_review_flags(response_text, user, inbound_text=inbound_text)
@ -5389,6 +5420,9 @@ Local classifier result:
【回复风格】
{reply_style or '(保持当前私聊的自然表达)'}
【统一内容尺度】
{content_tier};normal 不升级暧昧或成人内容,flirt 只允许非露骨暧昧,adult 也只能承接本轮明确同意的合法成年人私聊。
{attribution_guard}
【本轮真实创作记录】
@ -5420,11 +5454,18 @@ Local classifier result:
setattr(review_event, "_private_companion_response_review_fallback_text", response_text)
started = time.perf_counter()
try:
review_provider_id = self._task_provider(self.response_review_provider_id, self.mai_style_provider_id)
if content_tier == "adult":
review_provider_id = _single_line(getattr(self, "adult_content_provider_id", ""), 160)
if not review_provider_id:
logger.warning("[PrivateCompanion] 成人内容复核缺少指定 Provider,跳过二次模型调用")
return response_text
rewritten = await self._llm_call(
prompt,
max_tokens=260,
provider_id=self._task_provider(self.response_review_provider_id, self.mai_style_provider_id),
provider_id=review_provider_id,
task="response_review",
strict_provider=content_tier == "adult",
)
except Exception as exc:
logger.warning(
@ -6153,6 +6194,7 @@ bot_promises 只记录 Bot 明确承诺要提醒、记住、转述、发送或
bot_state: dict[str, Any] | None = None,
schedule: dict[str, Any] | None = None,
message_intent: dict[str, Any] | None = None,
content_policy: dict[str, Any] | None = None,
):
role_getter = getattr(self, "_private_user_role", None)
try:
@ -6162,6 +6204,7 @@ bot_promises 只记录 Bot 明确承诺要提醒、记住、转述、发送或
relationship_mode = str(user.get("relationship_mode") or "normal")
if role == "owner" and relationship_mode == "owner_exclusive":
relationship_baseline = {
"stage_key": "owner_exclusive",
"tone": _single_line(getattr(self, "owner_exclusive_tone", "温暖、亲近、稳定"), 120),
"address_level": _single_line(
getattr(self, "owner_exclusive_address_style", "优先使用已确认的专属称呼"),
@ -6188,6 +6231,7 @@ bot_promises 只记录 Bot 明确承诺要提醒、记住、转述、发送或
)
stage = relationship_stage_for_score(user.get("relationship_score", 0), policy)["phase"]
relationship_baseline = {
"stage_key": stage.get("key"),
"tone": stage.get("tone"),
"address_level": stage.get("address_level"),
"proactive_care_limit": stage.get("proactive_care_limit"),
@ -6223,6 +6267,7 @@ bot_promises 只记录 Bot 明确承诺要提醒、记住、转述、发送或
"relationship_role": role,
"relationship_mode": relationship_mode,
"relationship_baseline": relationship_baseline,
"relationship_stage": relationship_baseline.get("stage_key"),
"normal_interaction_band_cap": getattr(self, "normal_interaction_band_cap", "warm"),
"current_interaction": interaction,
"administrator_override": manual_override,
@ -6231,6 +6276,7 @@ bot_promises 只记录 Bot 明确承诺要提醒、记住、转述、发送或
"message_intent": message_intent if isinstance(message_intent, dict) else (user.get("intent_profile") if isinstance(user.get("intent_profile"), dict) else {}),
"proactive_candidate": proactive_candidate or {},
"safety_constraints": safety,
"content_policy": content_policy or {},
}
)