"""笔记工具:把重要信息写进本地文件,或读回来。这就是最朴素的"记忆"。""" import json import os import re import sys from datetime import datetime sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) from _protocol import serve # noqa: E402 NOTES_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "data", "notes") TOOL = { "name": "notes", "description": "本地笔记:action=save 写笔记,action=list 列出全部,action=read 读某一条,action=search 关键词搜索。适合记录用户偏好、待办、结论。", "parameters": { "type": "object", "properties": { "action": {"type": "string", "enum": ["save", "list", "read", "search"], "description": "要做的操作"}, "title": {"type": "string", "description": "save 时的标题"}, "content": {"type": "string", "description": "save 时的正文"}, "query": {"type": "string", "description": "search 时的关键词"}, }, "required": ["action"], }, } def ensure_dir(): os.makedirs(NOTES_DIR, exist_ok=True) def slug(title): safe = re.sub(r'[\\/:*?"<>|\s]+', "-", title.strip())[:40] return safe or "note" def run(args): ensure_dir() action = str(args.get("action", "list")).lower() if action == "save": title = str(args.get("title", "")).strip() or "未命名" content = str(args.get("content", "")) stamp = datetime.now().strftime("%Y%m%d-%H%M%S") path = os.path.join(NOTES_DIR, f"{stamp}-{slug(title)}.md") with open(path, "w", encoding="utf-8") as fh: fh.write(f"# {title}\n\n{content}\n") return {"saved": os.path.basename(path), "title": title, "chars": len(content)} if action == "list": files = sorted(os.listdir(NOTES_DIR), reverse=True) items = [] for name in files[:50]: full = os.path.join(NOTES_DIR, name) with open(full, encoding="utf-8") as fh: first = fh.readline().strip().lstrip("# ") items.append({"file": name, "title": first, "bytes": os.path.getsize(full)}) return {"count": len(files), "notes": items} if action == "read": name = str(args.get("title") or args.get("query") or "").strip() files = sorted(os.listdir(NOTES_DIR), reverse=True) hit = next((f for f in files if name and name in f), None) if not hit: return {"ok": False, "error": f"没找到匹配 {name} 的笔记"} with open(os.path.join(NOTES_DIR, hit), encoding="utf-8") as fh: return {"file": hit, "content": fh.read()[:4000]} if action == "search": query = str(args.get("query", "")).strip() if not query: raise ValueError("search 需要 query") hits = [] for name in sorted(os.listdir(NOTES_DIR), reverse=True): with open(os.path.join(NOTES_DIR, name), encoding="utf-8") as fh: text = fh.read() if query in text: idx = text.index(query) hits.append({"file": name, "excerpt": text[max(0, idx - 60): idx + 120]}) if len(hits) >= 20: break return {"query": query, "hits": hits} raise ValueError(f"不支持的 action: {action}") if __name__ == "__main__": serve(TOOL, run)