You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 

95 lines
3.4 KiB

#!/usr/bin/env python3
"""
从 session 历史文件中恢复记忆
"""
import json
import os
from datetime import datetime
# Session 文件路径
SESSION_DIR = "/root/.openclaw/agents/main/sessions"
MEMORY_DIR = "/root/.openclaw/workspace/memory"
# 按时间排序的 session 文件(最新的在前)
session_files = [
"fda8a2ae-5b9b-444d-a87d-331519888590.jsonl", # 最大的,1.5MB
"327cadb1-1a83-446b-b1a1-e545c90714fd.jsonl", # 495KB
"af32c214-5ba3-4ac6-a693-53be763407c4.jsonl", # 125KB
"8b3836d3-feff-46d7-977c-02050988a185.jsonl", # 187KB
"26cf4026-2ff9-40b5-b904-886d047bbc93.jsonl", # 51KB
"27db0960-4d43-4074-9df4-1136fdb46d8a.jsonl", # 47KB
"3fa25b26-6943-4b9d-9375-ab2feeb0aab4.jsonl", # 52KB
]
def parse_session_file(filepath):
"""解析单个 session 文件"""
messages = []
try:
with open(filepath, 'r', encoding='utf-8') as f:
for line in f:
line = line.strip()
if not line:
continue
try:
data = json.loads(line)
if data.get('type') == 'message':
msg = data.get('message', {})
role = msg.get('role')
content = msg.get('content', [])
# 提取文本内容
text_content = ""
if isinstance(content, list):
for item in content:
if item.get('type') == 'text':
text_content += item.get('text', '')
elif isinstance(content, str):
text_content = content
if text_content:
messages.append({
'role': role,
'content': text_content,
'timestamp': data.get('timestamp')
})
except json.JSONDecodeError:
continue
except Exception as e:
print(f"Error reading {filepath}: {e}")
return messages
def main():
all_messages = []
# 读取所有 session 文件
for filename in session_files:
filepath = os.path.join(SESSION_DIR, filename)
if os.path.exists(filepath):
print(f"Reading {filename}...")
msgs = parse_session_file(filepath)
all_messages.extend(msgs)
# 按时间排序(从旧到新)
all_messages.sort(key=lambda x: x.get('timestamp', ''))
# 生成恢复的记忆文件
today = datetime.now().strftime('%Y-%m-%d')
output_path = os.path.join(MEMORY_DIR, f"{today}-recovered.md")
with open(output_path, 'w', encoding='utf-8') as f:
f.write(f"# 恢复的记忆 - {today}\n\n")
f.write("## 说明\n")
f.write("这是从 session 历史文件中恢复的对话记录\n\n")
f.write("---\n\n")
for i, msg in enumerate(all_messages, 1):
role = "用户" if msg['role'] == 'user' else "星未"
f.write(f"### {role}\n")
f.write(f"{msg['content']}\n\n")
print(f"\n✅ 记忆已恢复到: {output_path}")
print(f"共恢复 {len(all_messages)} 条消息")
if __name__ == "__main__":
main()