hosted_room_lead.py 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167
  1. """Opt-in lead routing for hosted Group Chats.
  2. A room whose settings say ``routing: lead`` sends an unaddressed human message to its lead first. The lead
  3. runs one routing turn on its own member session and answers with the handles that should take the message;
  4. the gateway records that as a ``room.assignment`` event (the Desktop renders "Ada gave this to Linus") and
  5. only the chosen members take the normal round. Anything the lead answers that names no roster member wakes
  6. the lead alone: a routing answer can never broadcast.
  7. Everything else keeps the room's normal resolution: an @mention or @all/@everyone, a scheduled post, a
  8. reply inside an existing thread, and every message in an ``everyone`` room (the default).
  9. The routing turn is an ordinary driver task whose payload carries ``lead_routing: true``. Only the planner's
  10. lead round sets it; the driver accepts it only as exactly true, and it is hashed into the task id (the prompt
  11. is not: it names the room, and a rename must not orphan the receipt the planner looks up by that id), so a
  12. persisted task without it (every task admitted before lead routing existed, and every member turn, including
  13. batch-bounded ones whose ``seen_through_seq`` sits below their source message) is an ordinary member turn.
  14. Its ``seen_through_seq`` is the message's seq minus one, so its terminal receipt never advances the lead's
  15. watermark past the message the lead still has to answer.
  16. """
  17. from __future__ import annotations
  18. import json
  19. from collections.abc import Mapping, Sequence
  20. from typing import TYPE_CHECKING, Any
  21. if TYPE_CHECKING:
  22. from gateway.hosted_room_discussion import (
  23. DiscussionMember, DiscussionRoom, DiscussionTaskPlan, EventPlan, _ValidatedEvent)
  24. ASSIGNMENT_EVENT_KIND = "room.assignment"
  25. ASSIGNMENT_FIELDS = frozenset(
  26. {"discussion_event_id", "thread_id", "task_id", "lead_member_id", "member_ids", "fallback"})
  27. _ROUTING_INSTRUCTIONS = (
  28. "You are the lead of this room. A message arrived that names nobody, so you decide who takes it: pick the "
  29. "member(s) whose role the request touches (yourself included when it is yours). Do not answer the message "
  30. "itself here; whoever you pick answers it next.",
  31. 'Reply with only a JSON object and nothing else, for example {"assign": ["handle"]}.')
  32. def lead_member(room: DiscussionRoom, context: Mapping[str, str]) -> DiscussionMember | None:
  33. """The room's lead when lead routing is on and the lead is still seated, else None (everyone mode)."""
  34. if context.get("routing") != "lead":
  35. return None
  36. return next((member for member in room.members if member.member_id == context.get("lead_member_id")), None)
  37. def routes_through_lead(discussion: _ValidatedEvent, room: DiscussionRoom, events: Sequence[_ValidatedEvent]) -> bool:
  38. """A human message that opens a new thread and addresses nobody goes to the lead first."""
  39. from gateway.hosted_room_context import scheduled_post_kind
  40. from gateway.hosted_room_discussion import _MENTION_RE
  41. if scheduled_post_kind(discussion.actor) is not None:
  42. return False
  43. handles = {member.handle.casefold() for member in room.members} | {"all", "everyone"}
  44. if any(match.group(1).casefold() in handles for match in _MENTION_RE.finditer(str(discussion.payload["text"]))):
  45. return False
  46. thread_id = discussion.payload["thread_id"]
  47. return not any(
  48. event.seq < discussion.seq and event.kind in {"message.user", "message.member"}
  49. and event.payload.get("thread_id") == thread_id for event in events)
  50. def is_routing_task(task: DiscussionTaskPlan) -> bool:
  51. return task.payload.get("lead_routing") is True
  52. def routing_prompt(
  53. *, room: DiscussionRoom, lead: DiscussionMember, discussion: _ValidatedEvent, context_lines: Sequence[str]
  54. ) -> str:
  55. roster = [f"- @{member.handle}" + (f" ({member.display_name})" if member.display_name else "")
  56. + (" (you)" if member.member_id == lead.member_id else "") for member in room.members]
  57. return "\n".join([
  58. f'[Discussion: "{room.name}"] You are @{lead.handle}, the lead of this room.', "",
  59. *context_lines, "Members:", *roster, "",
  60. "The message (from the user):", f" {discussion.payload['text']}", *_attachment_lines(discussion), "",
  61. *_ROUTING_INSTRUCTIONS])
  62. def _attachment_lines(discussion: _ValidatedEvent) -> list[str]:
  63. """Name and kind of each attached file: the lead routes on them (an attachment-only message has no text);
  64. the files themselves reach only the member who takes the message."""
  65. files = discussion.payload.get("attachments") or ()
  66. return ["Attached files:", *(f" - {' '.join(str(item.get('name') or 'file').split())} ({item.get('kind')}"
  67. + (f", {item['mime']}" if item.get("mime") else "") + ")" for item in files)] if files else []
  68. def _first_assign_object(text: str) -> Mapping[str, Any] | None:
  69. """The first balanced JSON object in ``text`` carrying an ``assign`` key. A lead often wraps its answer
  70. in prose that has braces of its own (``see {notes}``), so a greedy outer match is not the answer."""
  71. decoder = json.JSONDecoder()
  72. start = text.find("{")
  73. while start != -1:
  74. try:
  75. value, _end = decoder.raw_decode(text, start)
  76. except ValueError:
  77. value = None
  78. if isinstance(value, Mapping) and "assign" in value:
  79. return value
  80. start = text.find("{", start + 1)
  81. return None
  82. def parse_assignment(text: Any, room: DiscussionRoom) -> tuple[str, ...]:
  83. """Member ids the lead's answer names, in roster order; empty when it names none (or is not JSON)."""
  84. answer = _first_assign_object(str(text or ""))
  85. picked = answer.get("assign") if answer is not None else None
  86. if not isinstance(picked, list):
  87. return ()
  88. handles = {str(item).strip().lstrip("@").casefold() for item in picked if isinstance(item, str)}
  89. return tuple(member.member_id for member in room.members if member.handle.casefold() in handles)
  90. def assignment(events: Sequence[_ValidatedEvent], discussion_event_id: str) -> _ValidatedEvent | None:
  91. return next((event for event in events if event.kind == ASSIGNMENT_EVENT_KIND
  92. and event.payload.get("discussion_event_id") == discussion_event_id), None)
  93. def first_round_members(
  94. room: DiscussionRoom, lead: DiscussionMember, events: Sequence[_ValidatedEvent], discussion_event_id: str,
  95. routing_task_id: str,
  96. ) -> tuple[DiscussionMember, ...] | None:
  97. """Who the lead gave the message to; ``(lead,)`` when its routing turn reached a terminal receipt
  98. without an assignment (cancelled: discarded or superseded); None while the routing turn has not
  99. finished (``turn.deferred`` is not terminal: it awaits Retry or Discard)."""
  100. if (event := assignment(events, discussion_event_id)) is not None:
  101. chosen = set(event.payload["member_ids"])
  102. return tuple(member for member in room.members if member.member_id in chosen)
  103. if any(event.payload.get("task_id") == routing_task_id for event in events if event.kind.startswith("turn.")
  104. and event.kind != "turn.deferred"):
  105. return (lead,)
  106. return None
  107. def validate_assignment_event(kind: str, payload: Mapping[str, Any], actor: Mapping[str, Any],
  108. room: DiscussionRoom) -> Mapping[str, Any]:
  109. from gateway.hosted_room_discussion import DiscussionValidationError, _exact_fields, _require_gateway_actor
  110. _exact_fields(payload, label=f"{kind} payload", required=ASSIGNMENT_FIELDS)
  111. _require_gateway_actor(actor, room, f"{kind} requires the room gateway")
  112. roster = {member.member_id for member in room.members}
  113. member_ids = payload.get("member_ids")
  114. if (not isinstance(member_ids, list) or not member_ids or not set(member_ids) <= roster
  115. or payload.get("lead_member_id") not in roster or not isinstance(payload.get("fallback"), bool)):
  116. raise DiscussionValidationError(f"{kind} must name seated members and a seated lead")
  117. return payload
  118. def assignment_effect(result: Any, *, task: DiscussionTaskPlan, room: DiscussionRoom, status: str) -> list[EventPlan]:
  119. """The ``room.assignment`` a finished routing turn publishes ahead of its terminal receipt. A settled
  120. answer naming no member, or a failed routing turn, records a fallback to the lead alone. A cancelled
  121. (discarded or superseded) or deferred routing turn records no assignment; once it is terminal,
  122. ``first_round_members`` still gives the message to the lead, because Discard gives up one attempt, never
  123. the user's message (a discarded member turn in an everyone room leaves the rest of the round running).
  124. Stop ends the whole round through the stop fence instead."""
  125. from gateway.hosted_room_discussion import EventPlan, _terminal_text
  126. if status not in {"settled", "failed"}:
  127. return []
  128. chosen = parse_assignment(_terminal_text(result, field="text", fallback=""), room) if status == "settled" else ()
  129. digest = task.identity.task_id.removeprefix("dtask:")
  130. return [EventPlan(
  131. event_id=f"dassign:{digest}", kind=ASSIGNMENT_EVENT_KIND, actor={"kind": "gateway", "id": room.gateway_id},
  132. payload={"discussion_event_id": task.discussion_event_id, "thread_id": task.identity.thread_id,
  133. "task_id": task.identity.task_id, "lead_member_id": task.member.member_id,
  134. "member_ids": list(chosen or (task.member.member_id,)), "fallback": not chosen},
  135. authority_gateway_id=room.gateway_id, authority_epoch=room.authority_epoch)]