54 lines
2.0 KiB
Python
54 lines
2.0 KiB
Python
import json, os, sys
|
|
|
|
src = os.environ.get("PI_SESSION_FILE")
|
|
if not src:
|
|
sys.exit("PI_SESSION_FILE 未设置")
|
|
|
|
dst = sys.argv[1] if len(sys.argv) > 1 else "session.md"
|
|
|
|
out = []
|
|
with open(src, encoding="utf-8") as fh:
|
|
for line in fh:
|
|
line = line.strip()
|
|
if not line:
|
|
continue
|
|
o = json.loads(line)
|
|
if o.get("type") != "message":
|
|
continue
|
|
m = o.get("message", {})
|
|
role = m.get("role")
|
|
content = m.get("content", []) or []
|
|
|
|
if role == "user":
|
|
texts = [p.get("text", "") for p in content if p.get("type") == "text"]
|
|
out.append("## User\n")
|
|
out.append("\n".join(texts).rstrip())
|
|
out.append("\n")
|
|
elif role == "assistant":
|
|
out.append("## Assistant\n")
|
|
for p in content:
|
|
pt = p.get("type")
|
|
if pt == "thinking":
|
|
out.append("\n<thinking>\n" + p.get("thinking", "") + "\n</thinking>\n")
|
|
elif pt == "text":
|
|
out.append("\n" + p.get("text", "").rstrip() + "\n")
|
|
elif pt == "toolCall":
|
|
name = p.get("name", "")
|
|
args = p.get("arguments", {})
|
|
try:
|
|
args_s = json.dumps(args, ensure_ascii=False, indent=2)
|
|
except Exception:
|
|
args_s = str(args)
|
|
out.append("\n**Tool Call: " + name + "**\n```json\n" + args_s + "\n```\n")
|
|
elif role == "toolResult":
|
|
tool = m.get("toolName", "")
|
|
err = m.get("isError", False)
|
|
texts = [p.get("text", "") for p in content if p.get("type") == "text"]
|
|
body = "\n".join(texts).rstrip()
|
|
out.append("**Tool Result: " + tool + (" (error)" if err else "") + "**\n\n" + body + "\n")
|
|
|
|
text = "\n".join(out)
|
|
with open(dst, "w", encoding="utf-8") as fh:
|
|
fh.write(text)
|
|
print("wrote", dst, len(text), "chars")
|