-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmbs_watcher.py
More file actions
99 lines (88 loc) · 2.95 KB
/
Copy pathmbs_watcher.py
File metadata and controls
99 lines (88 loc) · 2.95 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
#!/usr/bin/env python3
"""
MBS auto-watcher — 自动捕获 Hermes 会话记忆
被 cron 定时调用,检查新会话,提取关键信息存入 MBS
"""
import json
import os
import sqlite3
import subprocess
import time
from datetime import datetime, timedelta
SESSIONS_DIR = os.path.expanduser("~/.hermes/sessions")
MEMORY_DB = os.path.expanduser("~/.memory-bridge/memory.db")
STATE_FILE = os.path.expanduser("~/.memory-bridge/last_check.txt")
def get_latest_sessions(minutes_back=60):
"""获取最近N分钟内的会话文件"""
now = time.time()
cutoff = now - (minutes_back * 60)
sessions = []
if not os.path.exists(SESSIONS_DIR):
return sessions
for f in sorted(os.listdir(SESSIONS_DIR), reverse=True):
fpath = os.path.join(SESSIONS_DIR, f)
if not f.endswith(".json"):
continue
mtime = os.path.getmtime(fpath)
if mtime < cutoff:
break # 文件按修改时间倒序,超时了就不用继续
sessions.append(fpath)
return sessions
def extract_text_from_session(path):
"""从会话JSON中提取用户和AI的对话文本"""
try:
with open(path) as f:
data = json.load(f)
except (json.JSONDecodeError, FileNotFoundError):
return ""
texts = []
messages = data if isinstance(data, list) else data.get("messages", [])
for msg in messages:
role = msg.get("role", "")
content = msg.get("content", "")
if isinstance(content, list):
content = " ".join(c.get("text", "") for c in content if isinstance(c, dict))
if role in ("user", "assistant") and content:
texts.append(f"{role}: {content[:500]}")
return "\n".join(texts[-20:]) # 取最近20条消息
def already_processed(path):
"""检查会话是否已处理过"""
if not os.path.exists(MEMORY_DB):
return False
try:
db = sqlite3.connect(MEMORY_DB)
name = os.path.basename(path)
count = db.execute(
"SELECT COUNT(*) FROM observations WHERE narrative LIKE ?",
(f"%{name}%",)
).fetchone()[0]
db.close()
return count > 0
except:
return False
def main():
sessions = get_latest_sessions(180) # 查最近3小时
new_count = 0
for s in sessions[:5]: # 最多处理5个
if already_processed(s):
continue
text = extract_text_from_session(s)
if len(text) < 50:
continue
# 通过管道传给 mbs auto
result = subprocess.run(
["mbs", "auto"],
input=text,
capture_output=True,
text=True,
timeout=30
)
if result.returncode == 0 and "✔" in result.stdout:
new_count += 1
print(f" ✔ {os.path.basename(s)}")
if new_count == 0:
print("无新会话需要处理")
else:
print(f"处理了 {new_count} 个新会话")
if __name__ == "__main__":
main()