Files
memory-gateway/plugins/memory-gateway-agent/memory_gateway_plugin/policy.py

60 lines
2.2 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

from __future__ import annotations
import re
from typing import Any
from .config import PluginConfig, load_config
from .safety import validate_memory_write
REMEMBER_RE = re.compile(r"记住|请保存|remember this|save this|keep in memory", re.I)
STABLE_SIGNAL_RE = re.compile(
r"偏好|长期|约束|架构决策|决策|结论|workflow|工作流|preference|constraint|decision|always|以后都|project fact",
re.I,
)
SMALL_TALK_RE = re.compile(r"^\s*(你好|hi|hello|谢谢|thanks|ok|好的|收到|再见)[。.!\s\w]*$", re.I)
def should_search_memory(user_message: str, context: dict[str, Any] | None = None, config: PluginConfig | None = None) -> bool:
cfg = config or load_config()
if not cfg.auto_search:
return False
return bool(user_message and user_message.strip())
def should_append_episode(
user_message: str,
assistant_response: str = "",
context: dict[str, Any] | None = None,
config: PluginConfig | None = None,
) -> bool:
cfg = config or load_config()
if not cfg.auto_append_episode:
return False
combined = "\n".join(part for part in [user_message, assistant_response] if part)
if not combined.strip() or SMALL_TALK_RE.match(combined.strip()):
return False
if not validate_memory_write(combined)["allowed"]:
return False
return bool(REMEMBER_RE.search(combined) or STABLE_SIGNAL_RE.search(combined))
def build_episode_summary(user_message: str, assistant_response: str = "", context: dict[str, Any] | None = None) -> str:
parts = []
if REMEMBER_RE.search(user_message or ""):
parts.append(f"用户明确要求记住:{user_message.strip()}")
elif user_message:
parts.append(f"用户输入中的可复用信息:{user_message.strip()}")
if assistant_response and STABLE_SIGNAL_RE.search(assistant_response):
parts.append(f"助手结论:{assistant_response.strip()}")
summary = " ".join(parts).strip()
return summary[:1000]
def should_commit_session(context: dict[str, Any] | None = None, config: PluginConfig | None = None) -> bool:
cfg = config or load_config()
if cfg.auto_commit_session:
return True
return bool((context or {}).get("force_commit"))