-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmbs_daemon.py
More file actions
113 lines (97 loc) · 3.21 KB
/
Copy pathmbs_daemon.py
File metadata and controls
113 lines (97 loc) · 3.21 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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
#!/usr/bin/env python3
"""
MBS 守护进程 — 系统持续运行版
替代cron,保持MBS在后台持续监视会话变化
开机自启(通过launchd)
"""
import json
import os
import sqlite3
import subprocess
import time
import sys
from datetime import datetime
MEMORY_DIR = os.path.expanduser("~/.memory-bridge")
SESSIONS_DIR = os.path.expanduser("~/.hermes/sessions")
PID_FILE = os.path.join(MEMORY_DIR, "mbsd.pid")
LOG_FILE = os.path.join(MEMORY_DIR, "mbsd.log")
INTERVAL = 180 # 每3分钟扫描一次
def log(msg):
ts = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
with open(LOG_FILE, "a") as f:
f.write(f"[{ts}] {msg}\n")
print(f"[{ts}] {msg}")
def process_new_sessions():
"""扫描并处理新会话"""
if not os.path.exists(SESSIONS_DIR):
return 0
now = time.time()
cutoff = now - 3600 # 过去1小时
count = 0
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
try:
# 检查是否已处理过
db = sqlite3.connect(os.path.join(MEMORY_DIR, "memory.db"))
already = db.execute(
"SELECT COUNT(*) FROM observations WHERE narrative LIKE ?",
(f"%{f}%",)
).fetchone()[0]
db.close()
if already > 0:
continue
# 读取会话内容
with open(fpath) as fh:
data = json.load(fh)
texts = []
msgs = data if isinstance(data, list) else data.get("messages", [])
for msg in msgs[-30:]: # 取最近30条
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[:300]}")
full_text = "\n".join(texts)
if len(full_text) < 50:
continue
# 传给 mbs auto
result = subprocess.run(
["mbs", "auto"],
input=full_text,
capture_output=True,
text=True,
timeout=30
)
if result.returncode == 0:
log(f" ✔ 处理会话: {f}")
count += 1
except Exception as e:
log(f" ✗ 处理失败 {f}: {e}")
return count
def main():
# 写PID
os.makedirs(MEMORY_DIR, exist_ok=True)
with open(PID_FILE, "w") as f:
f.write(str(os.getpid()))
log("MBS 守护进程启动")
# 启动时先处理一次
n = process_new_sessions()
if n > 0:
log(f"启动时处理了 {n} 个新会话")
# 持续循环
while True:
time.sleep(INTERVAL)
try:
n = process_new_sessions()
if n > 0:
log(f"扫描完成: 处理了 {n} 个新会话")
except Exception as e:
log(f"扫描异常: {e}")
if __name__ == "__main__":
main()