hosted_room_context.py 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160
  1. """Room purpose, shared notes and scheduled-job posts for hosted Group Chats.
  2. Both live in the append-only room log, never in a side file: the Discussion planner must stay a pure
  3. function of durable room state, because a member turn's task id hashes its prompt. Purpose and notes are
  4. read as of the message that opened a discussion, so editing them mid-discussion never re-plans a turn that
  5. is already admitted; the edit applies from the next message. The same event carries the room's routing:
  6. ``everyone`` (every member gets a turn on an unaddressed message, the default) or ``lead`` (the lead picks
  7. who takes it; ``gateway/hosted_room_lead.py``).
  8. Scheduled posts are ordinary ``message.user`` events whose server-owned actor id names the cron job. Only
  9. this module mints that actor (``groups.send`` hard-codes ``desktop``), so a client cannot impersonate a job.
  10. """
  11. from __future__ import annotations
  12. import hashlib
  13. import json
  14. import re
  15. from collections.abc import Mapping
  16. from contextlib import closing
  17. from typing import Any
  18. from gateway import hosted_rooms
  19. from gateway.hosted_rooms_common import DbPath
  20. MAX_PURPOSE_CHARS = 500
  21. MAX_NOTES_BYTES = 4 * 1024
  22. CONTEXT_EVENT_KIND = "room.context_set"
  23. _CONTEXT_ACTOR = {"kind": "system", "id": "room-control"}
  24. # Actor id prefixes for posts the scheduler makes. A result post can start a round when it @mentions a
  25. # member; a failure notice never does (its text is machine-written, not addressed to anyone).
  26. SCHEDULED_POST_PREFIX = "cron:"
  27. SCHEDULED_NOTICE_PREFIX = "cron-notice:"
  28. ROUTING_MODES = ("everyone", "lead", "auto")
  29. _EMPTY_CONTEXT = {"purpose": "", "notes": "", "routing": "everyone", "lead_member_id": ""}
  30. def validate_context(purpose: Any, notes: Any, routing: Any = "everyone", lead_member_id: Any = "") -> dict[str, str]:
  31. """Normalize one room settings record; purpose and notes may be empty (clears them). ``lead`` routing
  32. needs a lead; ``everyone`` routing never keeps one."""
  33. if not all(isinstance(value, str) for value in (purpose, notes, routing, lead_member_id)):
  34. raise hosted_rooms.HostedRoomError("purpose, notes, routing and lead_member_id must be strings")
  35. purpose = " ".join(purpose.split())
  36. notes = notes.strip()
  37. if len(purpose) > MAX_PURPOSE_CHARS:
  38. raise hosted_rooms.HostedRoomError(f"purpose must be at most {MAX_PURPOSE_CHARS} characters")
  39. if len(notes.encode("utf-8")) > MAX_NOTES_BYTES:
  40. raise hosted_rooms.HostedRoomError(f"notes must be at most {MAX_NOTES_BYTES} bytes")
  41. if routing not in ROUTING_MODES:
  42. raise hosted_rooms.HostedRoomError("routing must be 'everyone', 'lead' or 'auto'")
  43. if routing == "lead" and not lead_member_id.strip():
  44. raise hosted_rooms.HostedRoomError("lead routing needs a lead_member_id")
  45. return {"purpose": purpose, "notes": notes, "routing": routing,
  46. "lead_member_id": lead_member_id.strip() if routing == "lead" else ""}
  47. def _local_authority(db_path: DbPath, room_id: Any) -> dict[str, Any]:
  48. state = hosted_rooms.room_state(db_path, room_id=room_id)
  49. if state["authority_gateway_id"] != hosted_rooms.local_authority_gateway_id():
  50. raise hosted_rooms.AuthorityConflictError("This Group Chat is managed by another gateway.")
  51. return state
  52. def _latest_context(conn: Any, room_id: str, before_seq: int | None) -> dict[str, str]:
  53. sql = "SELECT payload_json FROM hosted_room_events WHERE room_id=? AND kind=?"
  54. params: tuple[Any, ...] = (room_id, CONTEXT_EVENT_KIND)
  55. if before_seq is not None:
  56. sql, params = sql + " AND seq<?", (*params, int(before_seq))
  57. row = conn.execute(sql + " ORDER BY seq DESC LIMIT 1", params).fetchone()
  58. if row is None:
  59. return dict(_EMPTY_CONTEXT)
  60. payload = json.loads(row["payload_json"])
  61. return {key: str(payload.get(key) or default) for key, default in _EMPTY_CONTEXT.items()}
  62. def room_context(db_path: DbPath, *, room_id: Any, before_seq: int | None = None) -> dict[str, str]:
  63. """The latest purpose/notes, or the ones in force before ``before_seq`` when given."""
  64. room_id = hosted_rooms._room_id(room_id)
  65. with closing(hosted_rooms._read_connection(db_path)) as conn:
  66. return _latest_context(conn, room_id, before_seq)
  67. def set_room_context(
  68. db_path: DbPath, *, room_id: Any, event_id: Any, purpose: Any, notes: Any, routing: Any = None,
  69. lead_member_id: Any = None, now: float | None = None,
  70. ) -> dict[str, Any]:
  71. """Record new room settings as one replayable room event. Omitted routing fields keep their current
  72. values, so a client that only edits purpose/notes never switches a lead room back to everyone. Those
  73. values are read under the append's write lock: a concurrent routing change cannot be written back stale.
  74. A retried save (same ``event_id``) fills them from its own first write instead, so it returns that event
  75. even after another client changed the routing meanwhile."""
  76. state = _local_authority(db_path, room_id)
  77. seated = {str(member.get("member_id")) for member in state.get("members") or ()}
  78. saved: dict[str, str] = {}
  79. def settings(conn: Any) -> dict[str, str]:
  80. first = hosted_rooms._load_event(conn, state["room_id"], hosted_rooms._event_id(event_id))
  81. original = json.loads(first["payload_json"]) if first is not None and first["kind"] == CONTEXT_EVENT_KIND else None
  82. current = {**_EMPTY_CONTEXT, **original} if original is not None else _latest_context(conn, state["room_id"], None)
  83. context = validate_context(
  84. purpose, notes, current["routing"] if routing is None else routing,
  85. current["lead_member_id"] if lead_member_id is None else lead_member_id)
  86. if first is None and context["routing"] == "lead" and context["lead_member_id"] not in seated:
  87. raise hosted_rooms.HostedRoomError("the lead must be a member of this Group Chat")
  88. saved.update(context)
  89. if original is None:
  90. return context
  91. # A retry is compared in its first event's own schema: one saved before routing existed has only
  92. # purpose and notes, so a field still at its default is left out rather than read as a different save.
  93. return {key: value for key, value in context.items() if key in original or value != _EMPTY_CONTEXT[key]}
  94. event = hosted_rooms.append_event(
  95. db_path, room_id=room_id, event_id=event_id, kind=CONTEXT_EVENT_KIND, actor=dict(_CONTEXT_ACTOR),
  96. payload=settings, authority_gateway_id=state["authority_gateway_id"],
  97. authority_epoch=state["authority_epoch"], now=now)
  98. return {"context": saved, "event": event}
  99. def scheduled_post_kind(actor: Mapping[str, Any] | None) -> str | None:
  100. """``"post"``/``"notice"`` for a scheduler-authored ``message.user`` actor, else None (the human)."""
  101. if not isinstance(actor, Mapping) or actor.get("kind") != "user":
  102. return None
  103. actor_id = str(actor.get("id") or "")
  104. if actor_id.startswith(SCHEDULED_NOTICE_PREFIX):
  105. return "notice"
  106. return "post" if actor_id.startswith(SCHEDULED_POST_PREFIX) else None
  107. def post_scheduled_message(
  108. db_path: DbPath, *, room_id: Any, job_id: str, job_name: str, run_key: str, text: str, notice: bool = False,
  109. now: float | None = None,
  110. ) -> dict[str, Any]:
  111. """Append one cron output to a room. Idempotent per ``run_key``: a retried delivery of the same run
  112. returns the original event instead of posting twice."""
  113. from gateway.hosted_room_discussion import MAX_USER_TEXT_BYTES, validate_user_payload
  114. state = _local_authority(db_path, room_id)
  115. digest = hashlib.sha256("\0".join((str(state["room_id"]), job_id, run_key, str(notice))).encode()).hexdigest()
  116. suffix = "\n\n[Output truncated to fit the room.]"
  117. if len(text.encode("utf-8")) > MAX_USER_TEXT_BYTES:
  118. text = text.encode("utf-8")[:MAX_USER_TEXT_BYTES - len(suffix.encode())].decode("utf-8", "ignore") + suffix
  119. payload = validate_user_payload({"text": text, "thread_id": f"cron-{digest[:24]}"})
  120. prefix = SCHEDULED_NOTICE_PREFIX if notice else SCHEDULED_POST_PREFIX
  121. job_label = re.sub(r"[^A-Za-z0-9._:-]", "-", job_id)[: hosted_rooms.MAX_ACTOR_ID_CHARS - len(prefix)] or "job"
  122. actor = {"kind": "user", "id": f"{prefix}{job_label}",
  123. "display_name": (job_name or job_id)[: hosted_rooms.MAX_ACTOR_LABEL_CHARS]}
  124. event_id = f"cron-post:{digest[:40]}"
  125. try:
  126. return hosted_rooms.append_event(
  127. db_path, room_id=room_id, event_id=event_id, kind="message.user", actor=actor,
  128. payload=payload, authority_gateway_id=state["authority_gateway_id"],
  129. authority_epoch=state["authority_epoch"], now=now)
  130. except hosted_rooms.EventConflictError:
  131. # A retry of the same run re-rendered different text (a re-run agent, a new timestamp): the first
  132. # post already landed and the run is delivered, so report that post rather than a failure.
  133. with closing(hosted_rooms._read_connection(db_path)) as conn:
  134. row = hosted_rooms._load_event(conn, state["room_id"], event_id)
  135. if row is None:
  136. raise
  137. return hosted_rooms._event_from_row(row, idempotent=True)