persisted_turn_receipt.py 3.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. """``message.complete.persisted_turn``: the committed row addresses of the agent's current turn.
  2. Shared by every host that publishes a turn's completion (the TUI gateway's in-process turn and
  3. the session authority's TurnRunner turn), so a client sees one receipt contract whichever host
  4. ran the turn. Clients key on it to bind a streamed reply to its stored row (``SessionMessage.row_id``)
  5. instead of comparing words.
  6. """
  7. from __future__ import annotations
  8. from typing import Any, Callable
  9. from agent.context_compressor import _DB_PERSISTED_MARKER
  10. def committed_row_id(message: Any) -> int | None:
  11. row_id = message.get("_row_id") if isinstance(message, dict) else None
  12. return row_id if message.get(_DB_PERSISTED_MARKER) and type(row_id) is int and row_id > 0 else None
  13. def persisted_turn_receipt(
  14. messages: Any, start: Any, history: list, raw: Any, status: str, *,
  15. compression_unchanged: bool, prefix_row_matches: Callable[[Any, Any], bool],
  16. ) -> dict | None:
  17. """Report committed row addresses, never a text/timestamp search for a matching turn.
  18. ``start`` is the agent's persistence cursor (``_persist_user_message_idx``), re-anchored during
  19. compaction. A partial receipt can address its surviving rows, but cannot retire a client's
  20. entire streamed turn. Full coverage additionally requires the unchanged pre-turn prefix
  21. (``prefix_row_matches(history_row, turn_row)`` for every row before ``start``), no compaction
  22. and no redirected user boundary.
  23. """
  24. if (not isinstance(messages, list) or type(start) is not int or not 0 <= start < len(messages)
  25. or not isinstance(messages[start], dict) or messages[start].get("role") != "user"):
  26. return None
  27. tail = messages[start:]
  28. anchor_id = committed_row_id(tail[0])
  29. if any(before is tail[0] or (anchor_id is not None and anchor_id == committed_row_id(before))
  30. for before in history):
  31. return None # preflight returned the old transcript, not a new turn
  32. row_ids = [rid for message in tail if (rid := committed_row_id(message)) is not None]
  33. if not row_ids:
  34. return None
  35. receipt: dict = {"row_ids": row_ids, "complete": False}
  36. if (user_row_id := committed_row_id(tail[0])) is not None:
  37. receipt["user_row_id"] = user_row_id
  38. # Every rendered user row of the turn in order (the prompt, then each steer/redirect row), so a
  39. # client binds its optimistic bubbles even when the turn holds more than one prompt row. Only a
  40. # fully committed list is published: a gap would shift every later pairing.
  41. users = [message for message in tail if message.get("role") == "user" and message.get("display_kind") != "hidden"]
  42. user_row_ids = [committed_row_id(message) for message in users]
  43. if users and None not in user_row_ids:
  44. receipt["user_row_ids"] = user_row_ids
  45. last = tail[-1]
  46. # Equality only verifies the structurally selected final row's body: it never selects an identity.
  47. if (status == "complete" and last.get("role") == "assistant" and not last.get("tool_calls")
  48. and last.get("content") == raw and (final_id := committed_row_id(last)) is not None):
  49. receipt["final_assistant_row_id"] = final_id
  50. prefix_unchanged = start == len(history) and all(
  51. prefix_row_matches(before, after) for before, after in zip(history, messages[:start]))
  52. receipt["complete"] = bool(
  53. prefix_unchanged and compression_unchanged
  54. and len(row_ids) == len(tail)
  55. and sum(message.get("role") == "user" for message in tail) == 1
  56. and "final_assistant_row_id" in receipt)
  57. return receipt