scheduler_delivery_room.py 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121
  1. """Cron delivery into a Bot Mode Group Chat (``deliver: room:<room_id>[@<profile>]``).
  2. The job's output becomes one message in the room's log, labelled with the job's name. It starts a round
  3. only for the members it @mentions (``@all`` addresses everyone); without a mention it is only a message in
  4. the room, so a feed of scheduled results never makes every Bot answer it. Failure notices never start a
  5. round. The post is appended to the hosting gateway's room store directly; the room worker picks it up on
  6. its next poll, so delivery does not need the Desktop open.
  7. """
  8. from __future__ import annotations
  9. import logging
  10. import re
  11. import sqlite3
  12. import uuid
  13. from pathlib import Path
  14. from typing import Optional
  15. logger = logging.getLogger(__name__)
  16. ROOM_PLATFORM = "room"
  17. _PREFIX = ROOM_PLATFORM + ":"
  18. _ROOM_TOKEN_RE = re.compile(r"^(?P<room>[A-Za-z0-9][A-Za-z0-9._:-]*)(?:@(?P<profile>[A-Za-z0-9_-]+))?$")
  19. def parse_room_deliver_token(part: str) -> Optional[str]:
  20. """``room:<id>[@<profile>]`` → ``"<id>[@<profile>]"``, ``""`` for a malformed room token, or None
  21. when ``part`` is not a room token at all."""
  22. raw = (part or "").strip()
  23. if not raw.lower().startswith(_PREFIX):
  24. return None
  25. rest = raw[len(_PREFIX):].strip()
  26. return rest if _ROOM_TOKEN_RE.fullmatch(rest) else ""
  27. def resolve_room_target(job: dict, address: str) -> Optional[dict]:
  28. if not address:
  29. logger.warning("Job '%s': malformed room delivery target (expected room:<room_id>[@<profile>])",
  30. job.get("id", "?"))
  31. return None
  32. return {"platform": ROOM_PLATFORM, "chat_id": address, "thread_id": None}
  33. def _room_stores(profile: Optional[str]) -> list[Path]:
  34. """Where a room can live: the hosting profile's session store (rooms its gateway owns), then the
  35. install's shared room store (rooms the dashboard backend owns)."""
  36. from gateway.hosted_rooms import default_db_path
  37. from hermes_constants import get_hermes_home
  38. if profile:
  39. from hermes_cli.profiles import get_profile_dir
  40. home = get_profile_dir(profile)
  41. else:
  42. home = get_hermes_home()
  43. return [home / "state.db", default_db_path()]
  44. def _find_room_store(room_id: str, profile: Optional[str]) -> Optional[Path]:
  45. """The store whose worker serves ``room_id``. The session store counts only when its gateway holds
  46. the room's owner entry: the shared-store import copies rooms out of ``state.db`` without deleting
  47. them, and nothing serves that leftover copy, so a post there would never reach the visible room."""
  48. from gateway.hosted_rooms import probe_hosted_room
  49. session_store, shared_store = _room_stores(profile)
  50. if _serves(session_store, room_id):
  51. return session_store
  52. if not probe_hosted_room(shared_store, room_id=room_id):
  53. return None
  54. # A shared room the root gateway imported is fenced here and lives on in the ROOT home's state.db
  55. # (only that gateway imports), whichever profile's view advertised the target.
  56. from gateway.hosted_rooms_gateway_import import handed_room_ids
  57. root_store = shared_store.with_name("state.db")
  58. if room_id in handed_room_ids(shared_store) and _serves(root_store, room_id):
  59. return root_store
  60. return shared_store
  61. def _serves(store: Path, room_id: str) -> bool:
  62. from gateway.hosted_rooms import probe_hosted_room
  63. from gateway.session_hosted_service import probe_native_room_owner
  64. return probe_hosted_room(store, room_id=room_id) and probe_native_room_owner(store, room_id=room_id)
  65. def deliver_to_room(job: dict, content: str, address: str, *, for_failure: bool = False) -> Optional[str]:
  66. """Post one cron output into a hosted room. None on success, else an error string."""
  67. from cron.scheduler_delivery import _redact_cron_payload
  68. from gateway.hosted_room_context import post_scheduled_message
  69. from gateway.hosted_rooms import AuthorityConflictError
  70. target = f"room:{address}"
  71. match = _ROOM_TOKEN_RE.fullmatch(address)
  72. if match is None:
  73. return f"{target}: malformed room delivery target"
  74. room_id, profile = match.group("room"), match.group("profile")
  75. from hermes_cli.profiles import profile_exists
  76. if profile and not profile_exists(profile):
  77. return f"{target}: no profile named {profile!r} on this machine (Room settings shows the exact target)"
  78. try:
  79. store = _find_room_store(room_id, profile)
  80. if store is None:
  81. return f"{target}: no live Group Chat with that id on this machine"
  82. job_id = str(job.get("id") or "job")
  83. # The durable execution id makes a re-delivered run idempotent; direct helper calls get a fresh key.
  84. run_key = str(job.get("execution_id") or job.setdefault("_room_run_key", uuid.uuid4().hex))
  85. event = post_scheduled_message(
  86. store, room_id=room_id, job_id=job_id,
  87. job_name=_redact_cron_payload(str(job.get("name") or job_id), "job name"),
  88. run_key=run_key, text=_redact_cron_payload(content, "room payload"), notice=for_failure)
  89. logger.info("Job '%s': %s Group Chat %s (seq %s)", job_id,
  90. "already posted this run to" if event.get("idempotent") else "posted to", room_id, event.get("seq"))
  91. return None
  92. except AuthorityConflictError as exc:
  93. return f"{target} delivery failed: {exc} {_profile_hint(room_id, profile)}"
  94. except (ValueError, OSError, sqlite3.Error) as exc: # room/validation errors are ValueErrors
  95. return f"{target} delivery failed: {exc}"
  96. def _profile_hint(room_id: str, profile: Optional[str]) -> str:
  97. """A room a profile's own gateway took over leaves only a fenced shared copy here, which answers "managed
  98. by another gateway"; the remedy is naming the hosting profile so its session store is the one posted to."""
  99. lead = f"@{profile} does not host it. " if profile else ""
  100. return (f"{lead}If a profile's gateway hosts this room, deliver to room:{room_id}@<that profile> "
  101. "(Room settings shows the exact target).")