plugin_storage.py 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. """Per-plugin persistent storage: ``<hermes home>/plugin-data/<name>/``.
  2. Plugins must NOT park state in ``<hermes home>/plugins/<name>/`` (the install dir, deleted by
  3. ``remove`` and git-pulled by ``update``). Secrets are deliberately NOT part of this convention —
  4. credential reads go through ``agent.secret_scope`` / ``.env``.
  5. Usage: ``plugin_data_dir("my-plugin") / "state.json"``; ``plugin_db("my-plugin")`` → ``data.db``.
  6. """
  7. from __future__ import annotations
  8. import re
  9. import sqlite3
  10. from pathlib import Path
  11. __all__ = ["plugin_data_dir", "plugin_db"]
  12. # Mirrors the plugin-name shape `hermes plugins install` accepts (no separators/traversal).
  13. _NAME_RE = re.compile(r"^[a-zA-Z0-9][a-zA-Z0-9._-]{0,63}$")
  14. def _validate_name(name: str) -> str:
  15. if not _NAME_RE.fullmatch(name) or ".." in name:
  16. raise ValueError(f"invalid plugin name for storage: {name!r}")
  17. return name
  18. def plugin_data_dir(name: str) -> Path:
  19. """Return (and create) ``<hermes home>/plugin-data/<name>/``; resolves ``get_hermes_home()`` on
  20. every call so it follows the active profile — don't cache across profile switches."""
  21. from hermes_constants import get_hermes_home
  22. root = get_hermes_home() / "plugin-data" / _validate_name(name)
  23. root.mkdir(parents=True, exist_ok=True)
  24. return root
  25. def plugin_db(name: str, filename: str = "data.db") -> sqlite3.Connection:
  26. """Open ``<data dir>/<filename>``. WAL so a dashboard reader and a tool writer coexist;
  27. ``check_same_thread=False`` for the threaded FastAPI/tool env — caller owns transactions."""
  28. if Path(filename).name != filename or not filename:
  29. raise ValueError(f"invalid plugin db filename: {filename!r}")
  30. from hermes_cli.sqlite_util import open_db
  31. # WAL via the shared fallback helper: network filesystems degrade to DELETE and WAL-reset-bug
  32. # builds never enable it, instead of every plugin DB bypassing those rules with a raw PRAGMA.
  33. return open_db(plugin_data_dir(name) / filename, db_label=f"plugin-data/{name}/{filename}",
  34. foreign_keys=True, row_factory=None, check_same_thread=False)