diff --git a/constants.py b/constants.py index 404c2a5..bb7eeaa 100644 --- a/constants.py +++ b/constants.py @@ -3,7 +3,7 @@ from __future__ import annotations import re PLUGIN_NAME = "astrbot_plugin_private_companion_ops" -PLUGIN_DISPLAY_NAME = "我会永远陪着你・运维人格" +PLUGIN_DISPLAY_NAME = "雪色的我会永远陪着你-运维版" PLUGIN_VERSION = "5.10.4-ops.1" PLUGIN_REPO = "https://forgejo.yokiirobw.top:55443/YokiiroBW/astrbot_plugin_private_companion_ops" DATA_VERSION = 1 diff --git a/metadata.yaml b/metadata.yaml index 2fb2116..de3c2a7 100644 --- a/metadata.yaml +++ b/metadata.yaml @@ -1,5 +1,5 @@ name: astrbot_plugin_private_companion_ops -display_name: 我会永远陪着你・运维人格 +display_name: 雪色的我会永远陪着你-运维版 author: menglimi author_url: https://github.com/menglimi description: astrbot_plugin_private_companion_ops 是面向专用 AstrBot VM 运维平台的人格与陪伴编排插件。它把人格连续性、生活状态、日程细化、私聊关系、群聊观察、QQ 关系网、主动消息、图片/语音/转发理解、长期创作、模型 Provider 和扩展页排障组织到同一套体验里,让 Bot 不只是临时回复,而是有状态、有记忆、有边界地生活和互动。 diff --git a/ops_status_projection.py b/ops_status_projection.py new file mode 100644 index 0000000..0aa73f8 --- /dev/null +++ b/ops_status_projection.py @@ -0,0 +1,204 @@ +"""Safe, versioned status DTOs for the Companion management page. + +These projections deliberately expose only fixed labels, switches and bounded +counts. They must not become another path to P4 ledgers, P5 source material, +P3 carriers, review records or unified-person identities. +""" +from __future__ import annotations + +from typing import Any + +try: # Package import for the plugin; direct import for focused tests. + from .context_orchestration import CONTRACT_VERSION as P3_CONTRACT_VERSION + from .p4_live_runtime import project_warmth_band + from .p6_readonly_projection import build_p6_readonly_status +except ImportError: # pragma: no cover - exercised by unittest discovery. + from context_orchestration import CONTRACT_VERSION as P3_CONTRACT_VERSION # type: ignore + from p4_live_runtime import project_warmth_band # type: ignore + from p6_readonly_projection import build_p6_readonly_status # type: ignore + + +OPS_STATUS_SCHEMA_VERSION = "ops.page_status.v1" +P4_USER_STATUS_SCHEMA_VERSION = "ops.page_user_p4_status.v1" + +_MAX_REVIEW_COUNT = 10_000_000 +_P5_GROUP_FLAGS = { + "b": ( + "enable_p5_b1_recall_gate", + "enable_p5_b1_bridge_gate", + "enable_p5_b1_forward_quote_prompt_gate", + "enable_p5_b1_private_reply_vision_gate", + ), + "c": ( + "enable_p5c_raw_image_provider_gate", + "enable_p5c_group_image_vision_gate", + "enable_p5c_context_image_caption_gate", + "enable_p5c_tool_parameter_gate", + ), + "d": ( + "enable_p5d_cross_turn_correlation", + "enable_p5d_manual_recovery", + ), +} +_WARMTH_BANDS = ("unknown", "confinement", "guarded", "reserved", "neutral", "warm", "close", "very_warm") + + +def build_ops_status_projection( + *, + p4_runtime_enabled: Any, + p4_manual_review_enabled: Any, + p4_review_container: Any, + p4_effect_container: Any, + p5_source_observer_enabled: Any, + p5_protection_flags: Any, + p6_registry_status: Any, +) -> dict[str, Any]: + """Return the exact, page-safe cross-stage status DTO. + + Callers may pass the internal P4 review container and registry status, but + this function reads neither candidate records nor any ledger/audit body. + The returned structure is allowlist-only and contains no identifiers, + scores, source content, capabilities, attestations or credentials. + """ + runtime_enabled = bool(p4_runtime_enabled) + review_enabled = bool(p4_manual_review_enabled) + review = _review_queue_summary(p4_review_container, enabled=review_enabled) + runtime = _p4_runtime_aggregate(p4_effect_container, enabled=runtime_enabled) + p5_group_counts = _p5_group_counts(p5_protection_flags) + protected_sink_count = sum(p5_group_counts.values()) + observer_enabled = bool(p5_source_observer_enabled) + if protected_sink_count: + p5_status = "protected" + elif observer_enabled: + p5_status = "observing" + else: + p5_status = "disabled" + p6 = build_p6_readonly_status(p6_registry_status) + return { + "schema_version": OPS_STATUS_SCHEMA_VERSION, + "p3": { + "contract_version": P3_CONTRACT_VERSION, + "status": "available", + }, + "p4": { + "runtime_enabled": runtime_enabled, + "protection_status": "protected" if runtime_enabled else "disabled", + "review_enabled": review_enabled, + "review_candidate_count": review["candidate_count"], + "review_status": review["status"], + "runtime_status": runtime["status"], + "warmth_band_counts": dict(runtime["warmth_band_counts"]), + "active_confinement_count": runtime["active_confinement_count"], + }, + "p5": { + "source_observer_enabled": observer_enabled, + "b_gate_count": p5_group_counts["b"], + "c_gate_count": p5_group_counts["c"], + "d_gate_count": p5_group_counts["d"], + "protected_sink_count": protected_sink_count, + "protection_status": p5_status, + }, + "p6": { + "health": p6["health"], + "reason_code": p6["reason_code"], + "counts": dict(p6["counts"]), + }, + } + + +def build_user_p4_status_projection(*, runtime_enabled: Any) -> dict[str, Any]: + """Return a user-page P4 status without attempting identity resolution. + + A web page has no authenticated AstrBot event principal. It therefore + cannot safely bind a stored user record to a P4 person or issue a review + decision. The explicit unavailable state is safer than guessing from an + ID, alias, nickname, ledger, or configured owner list. + """ + return { + "schema_version": P4_USER_STATUS_SCHEMA_VERSION, + "runtime_enabled": bool(runtime_enabled), + "warmth_band": "unknown", + "confinement_state": "unknown", + "confinement_until": "", + "review_candidate_count": 0, + "review_status": "identity_not_verifiably_linked", + "action_available": False, + "action_unavailable_reason": "host_principal_unavailable", + } + + +def _review_queue_summary(container: Any, *, enabled: bool) -> dict[str, Any]: + if not enabled: + return {"candidate_count": 0, "status": "disabled"} + if container is None: + return {"candidate_count": 0, "status": "no_pending"} + if type(container) is not dict or container.get("version") != 1: + return {"candidate_count": 0, "status": "unverifiable"} + candidates = container.get("candidates") + decisions = container.get("decisions") + event_index = container.get("event_index") + if type(candidates) is not dict or type(decisions) is not dict or type(event_index) is not dict: + return {"candidate_count": 0, "status": "unverifiable"} + if len(candidates) > _MAX_REVIEW_COUNT or len(decisions) > _MAX_REVIEW_COUNT: + return {"candidate_count": 0, "status": "unverifiable"} + pending_count = sum(1 for candidate_id in candidates if candidate_id not in decisions) + return { + "candidate_count": pending_count, + "status": "pending" if pending_count else "no_pending", + } + + +def _p5_group_counts(value: Any) -> dict[str, int]: + if type(value) is not dict: + return {group: 0 for group in _P5_GROUP_FLAGS} + return { + group: sum(bool(value.get(key)) for key in flags) + for group, flags in _P5_GROUP_FLAGS.items() + } + + +def _p4_runtime_aggregate(container: Any, *, enabled: bool) -> dict[str, Any]: + counts = {band: 0 for band in _WARMTH_BANDS} + if not enabled: + return {"status": "disabled", "warmth_band_counts": counts, "active_confinement_count": 0} + if container is None: + return {"status": "no_runtime_data", "warmth_band_counts": counts, "active_confinement_count": 0} + if type(container) is not dict or type(container.get("people")) is not dict: + return {"status": "unverifiable", "warmth_band_counts": counts, "active_confinement_count": 0} + people = container["people"] + if len(people) > _MAX_REVIEW_COUNT: + return {"status": "unverifiable", "warmth_band_counts": counts, "active_confinement_count": 0} + active_confinement_count = 0 + invalid_count = 0 + for entry in people.values(): + state = entry.get("state") if type(entry) is dict else None + if type(state) is not dict: + invalid_count += 1 + continue + working = dict(state) + if working.get("mode") == "effect_preparation": + working["mode"] = "shadow" + try: + band = project_warmth_band(working).get("warmth_band") + except Exception: + band = "unknown" + if band not in counts: + band = "unknown" + counts[band] += 1 + if band == "confinement": + active_confinement_count += 1 + if invalid_count: + counts["unknown"] += invalid_count + return { + "status": "degraded" if invalid_count else "ready", + "warmth_band_counts": counts, + "active_confinement_count": active_confinement_count, + } + + +__all__ = [ + "OPS_STATUS_SCHEMA_VERSION", + "P4_USER_STATUS_SCHEMA_VERSION", + "build_ops_status_projection", + "build_user_p4_status_projection", +] diff --git a/page_api.py b/page_api.py index 64ea2c3..cf6dd4b 100644 --- a/page_api.py +++ b/page_api.py @@ -30,6 +30,7 @@ from .config_migration import _ensure_config_parent_dir from .agenda_contracts import WINDOW_SLUGS, window_for_plan_minutes from .helpers import _flat_get, _normalize_timezone_name, _redact_outbound_secrets, _safe_int, _set_into_config, _set_today_key_timezone, _strip_internal_message_blocks, _text_looks_garbled, _text_similarity, _today_key from .page_api_users_groups import PrivateCompanionPageApiUsersGroupsMixin +from .ops_status_projection import build_ops_status_projection, build_user_p4_status_projection from .planning import evaluate_daily_plan_quality, generate_daily_plan, generate_detail_enhancement from .memo_notes import ( apply_memo_note_action, @@ -208,6 +209,7 @@ class PrivateCompanionPageApi(PrivateCompanionPageApiUsersGroupsMixin): register = self.plugin.context.register_web_api routes = [ ("/overview", self.get_overview, ["GET"], "Private Companion Page overview"), + ("/ops/status", self.get_ops_status, ["GET"], "Private Companion Page safe operations status"), ("/bot-self/summary", self.get_bot_self_summary, ["GET"], "Private Companion Bot self storage summary"), ("/bot-self/timeline", self.get_bot_self_timeline, ["GET"], "Private Companion Bot self timeline"), ("/bot-self/agenda", self.get_bot_self_agenda, ["GET"], "Private Companion Bot self agenda history"), @@ -504,6 +506,64 @@ class PrivateCompanionPageApi(PrivateCompanionPageApiUsersGroupsMixin): logger.error(f"[PrivateCompanionPage] 获取总览失败: {exc}", exc_info=True) return self._error(str(exc)) + async def get_ops_status(self) -> dict[str, Any]: + """Return the page-safe P3--P6 operational status projection only.""" + try: + async with self.plugin._data_lock: + data = self.plugin.data if isinstance(self.plugin.data, dict) else {} + projection = self._ops_status_projection_locked(data) + return self._ok(projection) + except Exception as exc: + logger.error("[PrivateCompanionPage] safe ops status failed: %s", exc, exc_info=True) + # A status error must not turn this projection into an incidental + # recovery path for internal data or exception detail. + return self._error("安全状态暂不可用") + + def _ops_status_projection_locked(self, data: dict[str, Any]) -> dict[str, Any]: + """Build the only P3--P6 status shape that may leave the page API.""" + root_available = type(data.get("unified_person")) is dict + root = data.get("unified_person") if root_available else {} + p4_review = root.get("p4_review") if type(root) is dict else None + p4_effect = root.get("p4_effect") if type(root) is dict else None + p6_status = None + if root_available: + p6_status = { + "profiles": len(root.get("profiles") or {}) if type(root.get("profiles")) is dict else 0, + "identity_links": len(root.get("identity_links") or {}) if type(root.get("identity_links")) is dict else 0, + "audit_events": len(root.get("audit_events") or []) if type(root.get("audit_events")) is list else 0, + "operations": len(root.get("operations") or {}) if type(root.get("operations")) is dict else 0, + } + p5_flags = { + key: bool(getattr(self.plugin, key, False)) + for key in ( + "enable_p5_b1_recall_gate", + "enable_p5_b1_bridge_gate", + "enable_p5_b1_forward_quote_prompt_gate", + "enable_p5_b1_private_reply_vision_gate", + "enable_p5c_raw_image_provider_gate", + "enable_p5c_group_image_vision_gate", + "enable_p5c_context_image_caption_gate", + "enable_p5c_tool_parameter_gate", + "enable_p5d_cross_turn_correlation", + "enable_p5d_manual_recovery", + ) + } + return build_ops_status_projection( + p4_runtime_enabled=getattr(self.plugin, "enable_p4_live_runtime", False), + p4_manual_review_enabled=getattr(self.plugin, "enable_p4_manual_review", False), + p4_review_container=p4_review, + p4_effect_container=p4_effect, + p5_source_observer_enabled=getattr(self.plugin, "enable_p5_source_observer", False), + p5_protection_flags=p5_flags, + p6_registry_status=p6_status, + ) + + def _user_p4_status_projection(self) -> dict[str, Any]: + """Never resolve a page user to a P4 principal without a host event.""" + return build_user_p4_status_projection( + runtime_enabled=getattr(self.plugin, "enable_p4_live_runtime", False), + ) + def _token_overview_payload(self, usage: Any, balance_state: Any = None) -> dict[str, Any]: if not isinstance(usage, dict): usage = {} diff --git a/page_api_users_groups.py b/page_api_users_groups.py index 67e9a33..3d86f94 100644 --- a/page_api_users_groups.py +++ b/page_api_users_groups.py @@ -58,6 +58,7 @@ class PrivateCompanionPageApiUsersGroupsMixin: "last_user_message": self._display_message_text(user.get("last_user_message"), 500), "last_companion_message": self._display_message_text(user.get("last_companion_message"), 500), "delivery_route": delivery_route if isinstance(delivery_route, dict) else {}, + "p4_runtime": self._user_p4_status_projection(), "worldbook_member": worldbook_member, "formatted": { "relationship": self.plugin._format_relationship_summary(user), diff --git a/pages/陪伴面板/app.js b/pages/陪伴面板/app.js index 8cdcc2b..235874d 100644 --- a/pages/陪伴面板/app.js +++ b/pages/陪伴面板/app.js @@ -130,7 +130,7 @@ const state = { pageFontFamily: "original", pageTheme: "classic", overviewRefreshedAt: 0, - opsCenter: { loaded: false, loading: false, error: "", summary: null, timeline: null, agenda: null, persona: null, boundary: null }, + opsCenter: { loaded: false, loading: false, error: "", summary: null, timeline: null, agenda: null, persona: null, boundary: null, protection: null }, uxReviewShowAll: false, selectedFoodMenuIds: new Set(), }; @@ -1052,7 +1052,7 @@ const featureGroups = [ ], }, { - title: "私聊陪伴", + title: "用户陪伴", note: "关系、记忆、回复策略、主动终审和自然表达。", keys: [ "enable_mai_style_integration", @@ -1329,8 +1329,8 @@ const safeFeatureKeys = [ ]; const configLabels = { - enabled_user_count: "启用私聊对象", - user_count: "私聊对象总数", + enabled_user_count: "启用用户", + user_count: "用户总数", require_opt_in: "是否需要私聊确认", default_style: "默认语气", reply_style_prompt: "回复风格提示词", @@ -4855,9 +4855,10 @@ async function loadOpsCenter(force = false) { fetchJson("/agenda/reconciliation").catch((error) => ({ __error: error.message })), fetchJson("/bot-self/persona").catch((error) => ({ __error: error.message })), fetchJson("/memory-boundary/status").catch((error) => ({ __error: error.message })), + fetchJson("/ops/status").catch((error) => ({ __error: error.message })), ]); const clean = (value) => value && !value.__error ? value : null; - [state.opsCenter.summary, state.opsCenter.timeline, state.opsCenter.agenda, state.opsCenter.persona, state.opsCenter.boundary] = requests.map(clean); + [state.opsCenter.summary, state.opsCenter.timeline, state.opsCenter.agenda, state.opsCenter.persona, state.opsCenter.boundary, state.opsCenter.protection] = requests.map(clean); const errors = requests.filter((item) => item?.__error).map((item) => item.__error); state.opsCenter.error = errors.length ? errors.join(";") : ""; state.opsCenter.loaded = true; @@ -4873,6 +4874,7 @@ function renderOpsCenter() { const boundary = center.boundary || {}; const persona = center.persona || {}; const timeline = center.timeline || {}; + const protection = center.protection || {}; const overview = state.overview || {}; const put = (id, html) => { const node = document.getElementById(id); if (node) node.innerHTML = html; }; const text = (id, value) => { const node = document.getElementById(id); if (node) node.textContent = value; }; @@ -4897,6 +4899,35 @@ function renderOpsCenter() { put("opsBoundarySummary", `
${escapeHtml(opsSafe(boundary.boundary_note, "Bot 的日程、人格、创作和自我时间线不会写入用户记忆。"))}
`); const recordCount = summary.namespaces && typeof summary.namespaces === "object" ? Object.values(summary.namespaces).reduce((total, item) => total + Number(item?.count || 0), 0) : Number(summary.total_records || 0); put("opsSelfSummary", `这里只读展示 Bot 的人格、日程、创作和自我时间线摘要,不提供直接改库入口。
`); + const p3 = protection.p3 || {}; + const p4 = protection.p4 || {}; + const p5 = protection.p5 || {}; + const p6 = protection.p6 || {}; + const p6Counts = p6.counts && typeof p6.counts === "object" ? p6.counts : {}; + const warmthCounts = p4.warmth_band_counts && typeof p4.warmth_band_counts === "object" ? p4.warmth_band_counts : {}; + const reviewStatusLabels = { + disabled: "未开启", + no_pending: "暂无候选", + pending: "有待处理候选", + unverifiable: "暂不可核验", + }; + const p5StatusLabels = { + protected: "保护已启用", + observing: "仅观察", + disabled: "未启用", + }; + const p6HealthLabels = { + ready: "健康", + degraded: "降级", + unverifiable: "暂不可核验", + }; + const protectionReady = Boolean(p4.runtime_enabled) && p6.health === "ready"; + const protectionBadge = document.getElementById("opsProtectionBadge"); + if (protectionBadge) { + protectionBadge.textContent = protectionReady ? "保护运行中" : "需要关注"; + protectionBadge.dataset.state = protectionReady ? "ok" : "warn"; + } + put("opsProtectionSummary", `只展示版本、开关和受控数量;不会展示用户身份、消息、分数、账本、审核内容或访问凭据。
`); const personaItems = Array.isArray(persona.items) ? persona.items : []; put("opsPersonaSummary", personaItems.length ? `管理关系角色、主动额度、行为习惯、陪伴状态和已整理的对话片段。
+管理用户关系角色、主动额度、行为习惯、陪伴状态和已整理的对话片段。