diff --git a/core/bridge.py b/core/bridge.py index 69a7692..6340cf2 100644 --- a/core/bridge.py +++ b/core/bridge.py @@ -592,22 +592,22 @@ class MemoryCompanionBridge: read_only=False, ) except Exception: - return self._degraded_personal_capability_probe("contract_descriptor_exception") + return self._negative_personal_capability_probe("contract_descriptor_exception") if not isinstance(descriptor, dict): - return self._degraded_personal_capability_probe("contract_descriptor_invalid") + return self._negative_personal_capability_probe("contract_descriptor_invalid") result = dict(descriptor) try: problems = bot_personal_contract.contract_self_check() except Exception: - return self._degraded_personal_capability_probe( + return self._negative_personal_capability_probe( "contract_self_check_exception", base=result, ) if not isinstance(problems, list): - return self._degraded_personal_capability_probe( + return self._negative_personal_capability_probe( "contract_self_check_invalid", base=result, ) @@ -624,7 +624,7 @@ class MemoryCompanionBridge: code = str(problem).split(":", 1)[0] if code in known_codes and code not in warnings: warnings.append(code) - return self._degraded_personal_capability_probe( + return self._negative_personal_capability_probe( "contract_self_check_failed", base=result, warnings=warnings, @@ -729,6 +729,34 @@ class MemoryCompanionBridge: result.setdefault("schema_version", str(result.get("capability_schema_version", ""))) return result + def _negative_personal_capability_probe( + self, + reason: str, + *, + base: dict[str, Any] | None = None, + warnings: list[str] | None = None, + ) -> dict[str, Any]: + """Return a bounded failure and suppress repeated probes for the TTL.""" + + safe_reason = clean_text(reason, 120) or "capability_negative" + result = self._degraded_personal_capability_probe( + safe_reason, + base=base, + warnings=warnings, + ) + cached = self._capability_cache.mark_negative(safe_reason) + for key in ("available", "state", "degraded", "pending", "error_code"): + if key in cached: + result[key] = cached[key] + result["available"] = False + result["state"] = "negative" + result["capability_state"] = "negative" + result["degraded"] = True + result["pending"] = False + result["error_code"] = safe_reason + result["p5"] = {"state": "degraded", "error_code": safe_reason} + return result + @staticmethod def _degraded_personal_capability_probe( reason: str, diff --git a/core/service.py b/core/service.py index b022fcd..e96554b 100644 --- a/core/service.py +++ b/core/service.py @@ -63,6 +63,9 @@ from .turn_signal import analyze_turn_signal, message_terms from .visibility import VisibilityPolicy +LOCAL_TZ = ZoneInfo("Asia/Shanghai") + + _RECENT_FACT_PATTERNS: tuple[tuple[str, re.Pattern[str]], ...] = ( ("meal", re.compile(r"吃过|吃完|吃了|没吃|还没吃|正在吃|吃饭|早饭|早餐|午饭|午餐|晚饭|晚餐|夜宵")), ("bath", re.compile(r"洗澡|洗完澡|冲澡|沐浴")), @@ -2278,7 +2281,7 @@ class MemoryCompanionService: error: str = "", ) -> None: usage = self._extract_token_usage(resp, prompt, completion) - now_dt = datetime.now() + now_dt = datetime.now(LOCAL_TZ) now_ts = time.time() day = now_dt.strftime("%Y-%m-%d") hour = now_dt.strftime("%Y-%m-%dT%H:00") @@ -7183,7 +7186,7 @@ class MemoryCompanionService: if not check_like: return False try: - hour = datetime.now().hour + hour = datetime.now(LOCAL_TZ).hour except Exception: return True return hour >= 23 or hour < 7 @@ -7688,7 +7691,7 @@ class MemoryCompanionService: def _compute_time_of_day(self) -> str: """Compute time-of-day category for atmosphere hints.""" try: - hour = datetime.now().hour + hour = datetime.now(LOCAL_TZ).hour except Exception: return "" if 23 <= hour or hour < 4: diff --git a/core/store.py b/core/store.py index 5cd98e8..dafd828 100644 --- a/core/store.py +++ b/core/store.py @@ -1814,8 +1814,8 @@ class MemoryStore: params.append(clean_text(group_id, 120)) node = clean_text(node, 160) if node: - where += " AND (s.label LIKE ? OR t.label LIKE ?)" - like = f"%{node}%" + where += " AND (s.label LIKE ? ESCAPE '\\' OR t.label LIKE ? ESCAPE '\\')" + like = self._like_pattern(node) params.extend([like, like]) with self._lock: rows = self._conn.execute( @@ -1880,8 +1880,8 @@ class MemoryStore: if group_id: scope_filter += " AND (n.group_id='' OR n.group_id=?)" params.append(group_id) - like_sql = " OR ".join(["lower(n.label) LIKE ?" for _ in cleaned_terms]) - like_params = [f"%{term}%" for term in cleaned_terms] + like_sql = " OR ".join(["lower(n.label) LIKE ? ESCAPE '\\'" for _ in cleaned_terms]) + like_params = [self._like_pattern(term) for term in cleaned_terms] with self._lock: matched = self._conn.execute( f""" @@ -3705,11 +3705,11 @@ class MemoryStore: if not include_pending: where += " AND review_status != 'pending'" if query: - like = f"%{clean_text(query, 500)}%" + like = self._like_pattern(query) where += ( - " AND (id LIKE ? OR content LIKE ? OR evidence LIKE ? OR subject_id LIKE ?" - " OR subject_name LIKE ? OR object_id LIKE ? OR object_name LIKE ?" - " OR session_id LIKE ? OR group_id LIKE ?)" + " AND (id LIKE ? ESCAPE '\\' OR content LIKE ? ESCAPE '\\' OR evidence LIKE ? ESCAPE '\\' OR subject_id LIKE ? ESCAPE '\\'" + " OR subject_name LIKE ? ESCAPE '\\' OR object_id LIKE ? ESCAPE '\\' OR object_name LIKE ? ESCAPE '\\'" + " OR session_id LIKE ? ESCAPE '\\' OR group_id LIKE ? ESCAPE '\\')" ) params.extend([like] * 9) if memory_type: @@ -3735,8 +3735,8 @@ class MemoryStore: params.append(clean_text(group_id, 120)) if entity_id: entity = clean_text(entity_id, 120) - where += " AND (subject_id=? OR object_id=? OR group_id=? OR session_id LIKE ?)" - params.extend([entity, entity, entity, f"%{entity}%"]) + where += " AND (subject_id=? OR object_id=? OR group_id=? OR session_id LIKE ? ESCAPE '\\')" + params.extend([entity, entity, entity, self._like_pattern(entity)]) with self._lock: rows = self._conn.execute( f""" @@ -3778,12 +3778,12 @@ class MemoryStore: MAX(COALESCE(NULLIF(occurred_at, ''), created_at)) AS latest_at FROM memories WHERE scope='private' AND session_id!='' - AND (subject_id=? OR object_id=? OR session_id LIKE ?) + AND (subject_id=? OR object_id=? OR session_id LIKE ? ESCAPE '\\') GROUP BY session_id ORDER BY native_count DESC, total_count DESC, latest_at DESC LIMIT 64 """, - (user_id, user_id, f"%{user_id}%"), + (user_id, user_id, self._like_pattern(user_id)), ).fetchall() for row in rows: parsed_scope, parsed_target = parse_scope_from_session(clean_text(row["session_id"], 200)) diff --git a/page_api.py b/page_api.py index 4293dae..9da5afd 100644 --- a/page_api.py +++ b/page_api.py @@ -717,7 +717,7 @@ class PluginPageApi: return self._ok({"items": rows}) except Exception as exc: logger.warning("[MemoryCompanion] timeline 端点异常: %s", exc, exc_info=True) - return self._ok({"items": []}) + return self._err("timeline_unavailable", 500) async def relations(self): try: @@ -731,7 +731,7 @@ class PluginPageApi: return self._ok({"items": rows}) except Exception as exc: logger.warning("[MemoryCompanion] relations 端点异常: %s", exc, exc_info=True) - return self._ok({"items": []}) + return self._err("relations_unavailable", 500) async def graph(self): try: @@ -745,7 +745,7 @@ class PluginPageApi: return self._ok({"items": rows}) except Exception as exc: logger.warning("[MemoryCompanion] graph 端点异常: %s", exc, exc_info=True) - return self._ok({"items": []}) + return self._err("graph_unavailable", 500) async def threads(self): try: @@ -757,7 +757,7 @@ class PluginPageApi: return self._ok({"items": rows}) except Exception as exc: logger.warning("[MemoryCompanion] threads 端点异常: %s", exc, exc_info=True) - return self._ok({"items": []}) + return self._err("threads_unavailable", 500) async def thread_status(self): payload = await self._json() @@ -788,7 +788,7 @@ class PluginPageApi: return self._ok({"items": rows}) except Exception as exc: logger.warning("[MemoryCompanion] logs 端点异常: %s", exc, exc_info=True) - return self._ok({"items": []}) + return self._err("logs_unavailable", 500) async def context_config(self): config = self.plugin.service.config diff --git a/pages/记忆面板/app.js b/pages/记忆面板/app.js index 950140e..cc97d3e 100644 --- a/pages/记忆面板/app.js +++ b/pages/记忆面板/app.js @@ -493,7 +493,21 @@ async function httpRequest(path, method, body) { headers: body ? { "Content-Type": "application/json" } : undefined, body: body ? JSON.stringify(body) : undefined, }); - return response.json(); + let data = null; + try { + data = await response.json(); + } catch (error) { + if (!response.ok) { + throw new Error(`请求失败(HTTP ${response.status})`); + } + throw new Error("页面 API 返回了无效 JSON"); + } + if (!response.ok || data?.success === false) { + const error = new Error(data?.error || `请求失败(HTTP ${response.status})`); + error.status = response.status; + throw error; + } + return data; } function sleep(ms) { @@ -2074,20 +2088,34 @@ async function loadContextPanel() { apiGet(`/timeline?${params.toString()}`), apiGet(`/logs?${params.toString()}`), ]); - const settled = (idx) => results[idx].status === "fulfilled" ? (results[idx].value?.items || []) : []; - const failures = results.filter(r => r.status === "rejected"); + const settled = (idx) => { + const result = results[idx]; + if (result.status === "fulfilled") { + return { items: Array.isArray(result.value?.items) ? result.value.items : [], error: "" }; + } + return { items: [], error: result.reason?.message || "读取失败,请稍后重试" }; + }; + const sections = results.map((_, idx) => settled(idx)); + const failures = sections.filter((item) => item.error); if (failures.length === results.length) { throw results[0].reason || new Error("所有知识图谱 API 请求失败"); } target.innerHTML = renderKnowledgeOverview({ - graph: settled(0), - relations: settled(1), - threads: settled(2), - timeline: settled(3), - logs: settled(4), + graph: sections[0].items, + relations: sections[1].items, + threads: sections[2].items, + timeline: sections[3].items, + logs: sections[4].items, + errors: { + graph: sections[0].error, + relations: sections[1].error, + threads: sections[2].error, + timeline: sections[3].error, + logs: sections[4].error, + }, }); if (failures.length > 0) { - const failedNames = ["图谱边", "身份关系", "跨窗口线程", "时间线", "注入日志"].filter((_, i) => results[i].status === "rejected"); + const failedNames = ["图谱边", "身份关系", "跨窗口线程", "时间线", "注入日志"].filter((_, i) => sections[i].error); showToast(`${failedNames.join("、")}加载失败,已显示可用数据`, "error"); } } @@ -2107,7 +2135,16 @@ function rawAttr(value) { return escapeHtml(JSON.stringify(value || {})); } -function renderKnowledgeOverview({ graph = [], relations = [], threads = [], timeline = [], logs = [] } = {}) { +function renderContextPanelErrors(errors = {}) { + const labels = { graph: "图谱边", relations: "身份关系", threads: "跨窗口线程", timeline: "时间线", logs: "注入日志" }; + const rows = Object.entries(errors) + .filter(([, message]) => message) + .map(([key, message]) => `