_jsonfile.py 1.1 KB

1234567891011121314151617181920212223242526272829303132
  1. """Tiny JSON file helpers shared by the bot, process manager, node registry and node server."""
  2. from __future__ import annotations
  3. import json
  4. import threading
  5. from contextlib import contextmanager
  6. from pathlib import Path
  7. from typing import Any, Iterator, Optional
  8. _say_queue_lock_holder = threading.local()
  9. def read_json(path: Path) -> Optional[Any]:
  10. """Parsed JSON from *path*, or None when missing/unreadable/malformed."""
  11. if not path.is_file():
  12. return None
  13. try:
  14. return json.loads(path.read_text(encoding="utf-8-sig"))
  15. except (OSError, ValueError):
  16. return None
  17. @contextmanager
  18. def say_queue_lock(queue_path: Path) -> Iterator[None]:
  19. """Cross-process lock around ``say_queue.jsonl`` edits. The bot's speaker re-reads and rewrites the
  20. queue to drop what it spoke; an agent-side append landing in between would be wiped by the rewrite."""
  21. from hermes_cli.auth import _file_lock
  22. lock_path = queue_path.with_name(queue_path.name + ".lock")
  23. with _file_lock(lock_path, _say_queue_lock_holder, 10.0, f"Timed out waiting for say queue lock ({lock_path})"):
  24. yield