"""笔记工具:把重要信息写进本地文件,或读回来。这就是最朴素的"记忆"。 ## ★ 笔记存哪儿(改过一次,很重要) 以前是 `工具文件/../data/notes` —— **相对工具自己算的**。 在安卓上工具落在 `/storage/emulated/0/Android/data/<包名>/files/tools/`, 于是笔记写到 `.../files/data/notes`:**App 的外部私有目录**。 那个地方用户用文件管理器根本翻不到(Android 11+ 直接隐藏), 而且**卸载 App 就一起删了**。 用户的原话是"notes 用户要能查看",所以现在: 1. 优先用内核给的路径(`paths.get().notes_dir` = `<数据目录>/notes`), 和 conversations / screens 那些放一起,位置统一、持久 2. **自动把老位置的文件搬过来**(只搬一次,搬完留个 `.migrated` 标记), 不然用户以前记的笔记就"不见了" 3. 电脑端没有内核的 paths 模块时,退回老算法(那边本来就是 repo 里的 tools/ 下) """ import json import os import re import shutil import sys from datetime import datetime sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) from _protocol import serve # noqa: E402 # 老位置:工具文件旁边的 ../data/notes(安卓上会落到 App 外部私有目录) _LEGACY_DIR = os.path.abspath( os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "data", "notes") ) def notes_dir() -> str: """ 笔记目录。 ★ 每次调用现算,不在模块顶层算成常量 —— 内核的 paths 是运行时初始化的, 顶层算会拿到还没配置好的默认值(那个默认值在安卓上是相对路径)。 """ try: import paths # noqa: PLC0415 - 电脑端没有这个模块 d = paths.get().notes_dir if d: return d except Exception: # noqa: BLE001 pass return _LEGACY_DIR def _migrate_once(target: str) -> None: """ 把老位置的笔记搬到新位置(只做一次)。 ★ 为什么必须搬:用户在老版本里记的笔记是真实数据 —— 换了目录之后那些文件还在老地方躺着,但 list/read 都看不到了, 表现就是"我记的笔记全没了"。这类"改路径把用户数据弄丢"的事最不该发生。 """ if os.path.abspath(target) == _LEGACY_DIR: return # 本来就是老位置(电脑端),不用搬 marker = os.path.join(target, ".migrated") if os.path.exists(marker): return try: os.makedirs(target, exist_ok=True) if os.path.isdir(_LEGACY_DIR): moved = 0 for name in os.listdir(_LEGACY_DIR): if not name.endswith(".md"): continue src = os.path.join(_LEGACY_DIR, name) dst = os.path.join(target, name) if os.path.exists(dst): continue # 不覆盖同名的(新位置已有) try: shutil.move(src, dst) moved += 1 except Exception: # noqa: BLE001 # 跨设备 move 可能失败,退回复制 try: shutil.copy2(src, dst) os.remove(src) moved += 1 except Exception: # noqa: BLE001 pass if moved: print(f'[notes] 已把 {moved} 条老笔记搬到新目录', file=sys.stderr, flush=True) with open(marker, "w", encoding="utf-8") as fh: fh.write("ok\n") except Exception as exc: # noqa: BLE001 print(f'[notes] 迁移失败:{exc}', file=sys.stderr, flush=True) TOOL = { "name": "notes", "description": ( "本地笔记:action=save 写笔记,action=list 列出全部,action=read 读某一条," "action=search 关键词搜索。适合记录用户偏好、待办、结论。" "\n★ 用户能在 App 里「笔记」页面看到、也能删,所以别往里写不该让他看到的内部草稿。" ), "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(): d = notes_dir() os.makedirs(d, exist_ok=True) _migrate_once(d) return d def slug(title): safe = re.sub(r'[\\/:*?"<>|\s]+', "-", title.strip())[:40] return safe or "note" def run(args): d = 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(d, 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(d), reverse=True) items = [] for name in files[:50]: if not name.endswith(".md"): continue full = os.path.join(d, 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([f for f in files if f.endswith(".md")]), "notes": items} if action == "read": name = str(args.get("title") or args.get("query") or "").strip() files = [f for f in sorted(os.listdir(d), reverse=True) if f.endswith(".md")] 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(d, 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(d), reverse=True): if not name.endswith(".md"): continue with open(os.path.join(d, 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)