# -*- coding: utf-8 -*- """Stable, read-only payloads for the operations companion page API.""" from __future__ import annotations from copy import deepcopy from datetime import datetime from typing import Any try: from .bot_self_store import BOT_SELF_LIST_NAMESPACES, build_bot_self_migration_preview, ensure_bot_self_store except ImportError: from bot_self_store import BOT_SELF_LIST_NAMESPACES, build_bot_self_migration_preview, ensure_bot_self_store AGENDA_STATUS_KEYS = ( "planned", "active", "completed", "partially_completed", "deferred", "cancelled", "overridden", "unknown", ) def _list_tail(value: Any, limit: int) -> list[Any]: if not isinstance(value, list): return [] return [deepcopy(item) for item in value[-max(0, int(limit)) :] if isinstance(item, dict)] def _iso_now() -> str: return datetime.now().astimezone().isoformat(timespec="seconds") def _latest_timestamp(items: list[dict[str, Any]], *keys: str) -> str: values = [] for item in items: for key in keys: value = str(item.get(key) or "").strip() if value: values.append(value) break return max(values) if values else "" def build_bot_self_summary(data: dict[str, Any]) -> dict[str, Any]: ensure_bot_self_store(data) store = data.get("bot_self_store") if isinstance(data.get("bot_self_store"), dict) else {} namespaces: dict[str, dict[str, Any]] = {} all_records: list[dict[str, Any]] = [] for namespace in (*BOT_SELF_LIST_NAMESPACES, "bot_persona_state"): raw = store.get(namespace) records = raw if isinstance(raw, list) else ([raw] if isinstance(raw, dict) and raw else []) safe_records = [deepcopy(item) for item in records if isinstance(item, dict)] all_records.extend(safe_records) namespaces[namespace] = { "count": len(safe_records), "latest_at": _latest_timestamp(safe_records, "updated_at", "created_at", "occurred_at", "generated_at"), } outbox = data.get("bot_personal_outbox") if isinstance(data.get("bot_personal_outbox"), list) else [] outbox_states = {"pending": 0, "sent": 0, "retry": 0, "dead_letter": 0} for item in outbox: state = str(item.get("state") or "pending") if isinstance(item, dict) else "pending" outbox_states[state if state in outbox_states else "pending"] += 1 return { "version": int(store.get("version") or 1), "storage_domain": "bot_self", "owner": "bot", "status": "ready", "namespaces": namespaces, "total_records": len(all_records), "latest_at": _latest_timestamp(all_records, "updated_at", "created_at", "occurred_at", "generated_at"), "archive_outbox": {"version": int(data.get("bot_personal_outbox_version") or 1), "states": outbox_states, "total": len(outbox)}, "migration": build_bot_self_migration_preview(data), } def build_bot_self_detail(data: dict[str, Any], namespace: str, *, limit: int = 50) -> dict[str, Any]: ensure_bot_self_store(data) store = data.get("bot_self_store") if isinstance(data.get("bot_self_store"), dict) else {} allowed = set(BOT_SELF_LIST_NAMESPACES) | {"bot_persona_state"} if namespace not in allowed: raise ValueError("unsupported Bot self namespace") raw = store.get(namespace) records = raw if isinstance(raw, list) else ([raw] if isinstance(raw, dict) and raw else []) return { "namespace": namespace, "owner": "bot", "storage_domain": "bot_self", "items": [deepcopy(item) for item in records[-max(1, min(int(limit), 200)) :] if isinstance(item, dict)], } def build_agenda_summary(data: dict[str, Any]) -> dict[str, Any]: plan = data.get("daily_plan") if isinstance(data.get("daily_plan"), dict) else {} plan_items = [item for item in plan.get("items", []) if isinstance(item, dict)] observed = data.get("observed_activities") if isinstance(data.get("observed_activities"), list) else [] history = data.get("agenda_reconciliation_history") if isinstance(data.get("agenda_reconciliation_history"), list) else [] status_counts = {key: 0 for key in AGENDA_STATUS_KEYS} for item in plan_items: status = str(item.get("status") or item.get("lifecycle_status") or "planned").strip() status_counts[status if status in status_counts else "unknown"] += 1 return { "plan_date": str(plan.get("date") or ""), "plan_version": int(plan.get("version") or 1), "plan_item_count": len(plan_items), "observed_activity_count": len([item for item in observed if isinstance(item, dict)]), "reconciliation_count": len([item for item in history if isinstance(item, dict)]), "status_counts": status_counts, "current_time": _iso_now(), "timezone": datetime.now().astimezone().tzname() or "local", "latest_reconciliation_at": _latest_timestamp( [item for item in history if isinstance(item, dict)], "reconciled_at", "updated_at", "generated_at", ), } def build_agenda_detail(data: dict[str, Any], *, limit: int = 100) -> dict[str, Any]: plan = data.get("daily_plan") if isinstance(data.get("daily_plan"), dict) else {} plan_items = [deepcopy(item) for item in plan.get("items", []) if isinstance(item, dict)] observed = _list_tail(data.get("observed_activities"), limit) snapshots = _list_tail(data.get("window_snapshots"), limit) history = _list_tail(data.get("agenda_reconciliation_history"), limit) return { "plan_date": str(plan.get("date") or ""), "plan": plan_items[-max(1, min(int(limit), 200)) :], "observed": observed, "window_snapshots": snapshots, "reconciliation_history": history, "source_policy": { "plan": "planned", "observed": "real_or_projected_activity", "world": "world_context_only_until_enabled", }, } def _outbox_sync_status(data: dict[str, Any]) -> dict[str, Any]: """本地 outbox 的同步态。页面据此显示 local_only / dual_write / pending / degraded。""" items = [item for item in (data.get("bot_personal_outbox") or []) if isinstance(item, dict)] counts = {"pending": 0, "retry": 0, "sent": 0, "dead_letter": 0} for item in items: state = str(item.get("state") or "pending").strip() counts[state if state in counts else "pending"] += 1 return { "total": len(items), "counts": counts, "oldest_pending_at": min( (str(item.get("created_at") or "") for item in items if str(item.get("state") or "pending") in {"pending", "retry"} and item.get("created_at")), default="", ), "last_error_code": next( (str(item.get("error_code") or "") for item in reversed(items) if item.get("error_code")), "" ), } def build_agenda_runtime_view(plugin: Any, data: dict[str, Any]) -> dict[str, Any]: """M6.1.6:陪伴侧运行态只读视图。 这里是「现在」的唯一权威来源:当前时间、时区、当前窗口、当日日程、下一项、 当前活动、对账摘要、同步状态。长期归档由记忆侧另一个端点提供,页面必须分别标注来源, 不能把归档当成运行态。 记忆插件停用时本视图照常返回,只把 `archive_available` 标 false —— 一侧停用, 另一侧继续显示并明确降级。 """ now = None getter = getattr(plugin, "_calendar_now", None) or getattr(plugin, "_environment_now", None) if callable(getter): try: now = getter() except Exception: now = None if now is None: now = datetime.now().astimezone() timezone_name = "" tz_getter = getattr(plugin, "_agenda_timezone_name", None) if callable(tz_getter): try: timezone_name = str(tz_getter() or "") except Exception: timezone_name = "" if not timezone_name: timezone_name = now.tzname() or "local" current_window = "" window_getter = getattr(plugin, "_agenda_window_for_now", None) if callable(window_getter): try: current_window = str(window_getter(now)[0] or "") except Exception: current_window = "" plan = data.get("daily_plan") if isinstance(data.get("daily_plan"), dict) else {} plan_items = [deepcopy(item) for item in plan.get("items", []) if isinstance(item, dict)] # 「下一项」与「当前活动」按分钟数定位,不依赖 LLM 判断 minutes_now = now.hour * 60 + now.minute current_item = None next_item = None for item in plan_items: start = _minutes_of(item.get("start") or item.get("time")) end = _minutes_of(item.get("end")) if start is None: continue if end is not None and start <= minutes_now < end: current_item = item elif start > minutes_now and (next_item is None or start < _minutes_of(next_item.get("start") or next_item.get("time"), 10 ** 6)): next_item = item observed = [item for item in (data.get("observed_activities") or []) if isinstance(item, dict)] active_observed = [item for item in observed if str(item.get("status") or "") == "active"] bridge_available = False bridge_getter = getattr(plugin, "_memory_companion_bridge", None) if callable(bridge_getter): try: bridge_available = bridge_getter() is not None except Exception: bridge_available = False return { "data_source": "companion_runtime", "source_plugin": "private_companion", "current_time": now.isoformat(timespec="seconds"), "timezone": timezone_name, "current_window": current_window, "plan_date": str(plan.get("date") or ""), "plan_items": plan_items, "next_item": deepcopy(next_item) if next_item else None, "current_item": deepcopy(current_item) if current_item else None, "current_activities": [deepcopy(item) for item in active_observed[-5:]], "reconciliation": build_agenda_summary(data), "sync_status": _outbox_sync_status(data), # 记忆插件不可用时页面仍然要能显示运行态,只是长期归档一栏降级 "archive_available": bool(bridge_available), "degraded": not bridge_available, } def _minutes_of(value: Any, default: int | None = None) -> int | None: text = str(value or "").strip() if not text: return default if text.isdigit(): return int(text) parts = text.split(":") if len(parts) >= 2 and parts[0].strip().isdigit() and parts[1].strip().isdigit(): return int(parts[0]) * 60 + int(parts[1]) return default def build_memory_boundary_summary(plugin: Any, data: dict[str, Any]) -> dict[str, Any]: bridge = None bridge_status: dict[str, Any] = {} getter = getattr(plugin, "_memory_companion_bridge", None) if callable(getter): try: bridge = getter() except Exception: bridge = None status_getter = getattr(plugin, "_memory_companion_coordination_status", None) if callable(status_getter): try: value = status_getter() if isinstance(value, dict): bridge_status = deepcopy(value) except Exception: bridge_status = {} runtime = data.get("runtime_settings") if isinstance(data.get("runtime_settings"), dict) else {} return { "policy": "user_only", "status": "ready" if bridge is not None else "unavailable", "bridge_available": bridge is not None, "bridge_name": str(getattr(bridge, "display_name", "") or "") if bridge is not None else "", "coordination": bridge_status, "bot_self_external_write": False, "bot_self_store_migrated": bool(runtime.get("bot_self_store_migrated", False)), "checked_at": _iso_now(), "boundary_note": "Bot 当前运行态保存在陪伴插件自有空间;长期归档只通过 Bot 专属域 Bridge 写入,不进入 user_memory。", }