2.8 KiB
2.8 KiB
P1: 自动注入钩子 — 织忆 Hermes 插件
目标
增强 Hermes 织忆插件的 prefetch/queue_prefetch,实现:
- queue_prefetch 缓存下一轮记忆(异步预取)
- 社交关闭检测(skip trivial messages)
- 新增 [织忆] 标记注入格式,与 hermes 原生记忆区分
- 更好的话题重叠检测(避免同一轮注入重复上下文)
修改文件
~/.hermes/hermes-agent/plugins/memory/zhiyi/__init__.py
1. 新增社交关闭检测(参考 Memory-OS hooks.py:251-268)
_SOCIAL_CLOSERS = frozenset({
"ok", "好的", "👍", "👌", "✅", "谢谢", "感谢", "知道了",
"明白", "嗯", "好", "行", "yes", "yep", "thanks", "thx",
"no", "不用", "没事", "可以", "done", "完成",
})
def _is_social_close(text: str) -> bool:
text = text.strip().lower()
if text in _SOCIAL_CLOSERS:
return True
if len(text) < 6 and not any(c in text for c in "://.@#$_?"):
return True
return False
2. 实现 queue_prefetch(原为 pass)
def queue_prefetch(self, query: str, *, session_id: str = "") -> None:
"""异步预取:本轮对话结束后立即查询织忆,下一轮 prefetch 直接返回缓存。"""
if not self._client or not query or len(query.strip()) < 2:
return
if _is_social_close(query):
return
# 后台线程查询并缓存
def _async_prefetch():
results = self._client.recall(query.strip(), top_k=3)
notes = self._client.search_notes(query.strip(), max_hops=2, max_notes=3)
with self._prefetch_lock:
self._prefetch_cache["queue"] = {
"results": results,
"notes": notes,
"timestamp": time.time()
}
threading.Thread(target=_async_prefetch, daemon=True).start()
3. 增强 prefetch 方法
# 在 prefetch 入口处:
if _is_social_close(query):
return "" # 关闭消息不触发预取
# 优先从 queue_prefetch 缓存取
with self._prefetch_lock:
queued = self._prefetch_cache.pop("queue", None)
if queued and (time.time() - queued["timestamp"]) < 30:
# 用缓存结果
pass
# 输出格式改成带 [织忆] 标记
blocks = ["[织忆 Memory — relevant past context]"]
for r in results:
blocks.append(f" [{score:.2f}][{cat}] {content[:500]}")
验证方法
cd ~/.hermes/hermes-agent && python3 -c "
from plugins.memory.zhiyi import HermesZhiYiMemoryProvider
p = HermesZhiYiMemoryProvider()
# 测试 prefetch
result = p.prefetch('织忆记忆系统架构', session_id='test')
print('prefetch result:', result[:200] if result else 'empty')
# 测试 social closer
result2 = p.prefetch('好的', session_id='test')
print('social closer prefetch:', repr(result2))
"