bot_chat_legacy.py 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123
  1. """``cron/bot_chat_pending``: Bot Chat outputs whose target owner was not running yet.
  2. ``defer`` parks one (a cross-profile target whose gateway is down or still starting), and
  3. the retired CLI lane left records of the same shape behind. Each still-``queued`` record is handed,
  4. under its own id, to the target profile's live owner through the canonical
  5. ``tools.bot_live_delivery.deliver_to_live_owner`` door (idempotent per id). Records are
  6. never deleted: they keep their final status as evidence, exactly as the old drain did.
  7. A ``claimed`` record was an uncertain CLI turn and is never resent.
  8. """
  9. from __future__ import annotations
  10. import json
  11. import logging
  12. from pathlib import Path
  13. from hermes_dir_acl import make_user_dir
  14. from hermes_constants import get_hermes_home
  15. from utils import atomic_json_write
  16. logger = logging.getLogger(__name__)
  17. _warned: set[Path] = set()
  18. def defer(key: str, job: dict, content: str, home: Path, *, for_failure: bool) -> None:
  19. """Park one never-admitted output under its delivery id; a later tick hands it to the owner."""
  20. import time
  21. root = get_hermes_home().resolve() / "cron" / "bot_chat_pending"
  22. make_user_dir(root, parents=True, exist_ok=True, mode=0o700)
  23. path = root / f"{key}.json"
  24. if not path.exists(): # an existing record (queued or already transferred) keeps its status
  25. atomic_json_write(path, dict(
  26. id=key, status="queued", job={k: job[k] for k in ("id", "name") if k in job}, content=content,
  27. home=str(home), for_failure=for_failure, sequence=time.time_ns()), fsync_dir=True, mode=0o600)
  28. def _queued(root: Path) -> list[tuple[Path, dict]]:
  29. found = []
  30. for path in root.glob("*.json"):
  31. try:
  32. record = json.loads(path.read_text(encoding="utf-8-sig"))
  33. if not isinstance(record, dict):
  34. raise ValueError(f"expected a JSON object, got {type(record).__name__}")
  35. except (OSError, ValueError) as exc:
  36. if path not in _warned:
  37. _warned.add(path)
  38. logger.error("Unreadable legacy Bot Chat pending record %s kept as evidence: %s", path, exc)
  39. continue
  40. if record.get("status") == "queued":
  41. found.append((path, record))
  42. return sorted(found, key=lambda item: (item[1].get("sequence", 0), item[0].name))
  43. def _malformed(record: dict) -> str:
  44. """Why *record* can never be handed off (empty when its required fields are usable)."""
  45. missing = [key for key in ("id", "home", "content")
  46. if not isinstance(record.get(key), str) or not record.get(key)]
  47. if missing:
  48. return f"malformed legacy bot-chat record (missing {', '.join(missing)}); not delivered"
  49. if not isinstance(record.get("job") or {}, dict):
  50. return "malformed legacy bot-chat record (job is not an object); not delivered"
  51. return ""
  52. def _dispose(path: Path, record: dict) -> bool:
  53. """Decide one queued record in place; False leaves it queued for a later tick."""
  54. from cron.scheduler_delivery import BOT_CHAT_POLICY_PLATFORM, bot_chat_message
  55. from gateway.warning_notifications import warning_notifications_enabled
  56. from hermes_cli.config_effective import load_user_config_effective
  57. from tools.bot_live_delivery import deliver_to_live_owner, find_canonical_live_owner
  58. if reason := _malformed(record):
  59. record.update(status="ambiguous", error=reason)
  60. return True
  61. home = Path(record["home"]).resolve()
  62. for_failure = bool(record.get("for_failure"))
  63. if not (home / "state.db").is_file():
  64. record.update(status="ambiguous", error=f"bot-chat delivery target no longer exists: {home}")
  65. elif for_failure and not warning_notifications_enabled(
  66. BOT_CHAT_POLICY_PLATFORM, load_user_config_effective(home / "config.yaml")):
  67. record.update(status="suppressed", error=None)
  68. else:
  69. try:
  70. owner = find_canonical_live_owner(home)
  71. except ValueError:
  72. return False # Owner not ready: discovery uncertainty is not a disposition.
  73. if owner is None:
  74. return False
  75. try:
  76. receipt = deliver_to_live_owner(
  77. home, owner, bot_chat_message(record.get("job") or {}, record["content"]),
  78. delivery_id=record["id"], notification_category="diagnostic" if for_failure else "result")
  79. except Exception as exc:
  80. # The door is idempotent per id (a replay returns the existing receipt), so the
  81. # record stays queued for the next tick; log loudly once, quietly after.
  82. logger.log(logging.DEBUG if path in _warned else logging.WARNING,
  83. "Legacy Bot Chat pending record %s not handed off yet: %s", path, exc, exc_info=True)
  84. _warned.add(path)
  85. return False
  86. receipt_status = receipt.get("status") if isinstance(receipt, dict) else None
  87. record.update(status="transferred", error=None, receipt_status=receipt_status)
  88. return True
  89. def drain_legacy_pending() -> None:
  90. """Admit queued legacy records to their live owner; an absent owner leaves them for a later tick.
  91. Each record is isolated: a malformed one is kept as ``ambiguous`` evidence and an
  92. unexpected failure leaves only that record queued, so one bad file never stops cron.
  93. """
  94. root = get_hermes_home().resolve() / "cron" / "bot_chat_pending"
  95. if not root.is_dir():
  96. return
  97. for path, record in _queued(root):
  98. try:
  99. if not _dispose(path, record):
  100. continue
  101. atomic_json_write(path, record, fsync_dir=True, mode=0o600)
  102. except Exception as exc:
  103. logger.log(logging.DEBUG if path in _warned else logging.WARNING,
  104. "Legacy Bot Chat pending record %s left queued: %s", path, exc, exc_info=True)
  105. _warned.add(path)
  106. continue
  107. logger.info("Legacy Bot Chat pending record %s -> %s", path.name, record["status"])