hermes_state_detached_results.py 3.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. """Results that arrive between turns, recorded once as user rows: a detached API delegation's delivery and
  2. an unviewed local completion's note (#134889 LC-7). Split out of ``hermes_state_messages`` and bound onto
  3. SessionDB through ``SessionMessagesMixin``; built on its _message_row_params/_execute_write primitives."""
  4. from __future__ import annotations
  5. import time
  6. from typing import Any
  7. from agent.message_metadata import stamp_message_uid
  8. # Rows of a session and of the parents it was compressed from; a detached result's match condition follows.
  9. _LINEAGE_MATCH_SQL = """WITH RECURSIVE lineage(id) AS (SELECT ? UNION
  10. SELECT s.parent_session_id FROM sessions s JOIN lineage l ON s.id = l.id
  11. JOIN sessions p ON p.id = s.parent_session_id WHERE p.end_reason = 'compression'
  12. ) SELECT m.id FROM messages m JOIN lineage l ON m.session_id = l.id WHERE """
  13. _DELEGATION_DELIVERY_MATCH = ("m.display_kind IN ('async_delegation_complete', 'hidden') AND json_extract(m.display_metadata, "
  14. "'$.delegation_id') = ? AND coalesce(json_extract(m.display_metadata, '$.delivery_notice'), '') = ?")
  15. class SessionDetachedResultsMixin:
  16. """Detached API delegation deliveries and unviewed completion notes."""
  17. def append_delegation_delivery(self, session_id: str, content: str, metadata: dict[str, Any]) -> int:
  18. """Record a detached API result once, keyed by the event's unit id (not its text or active flag)."""
  19. delegation_id = metadata.get("delegation_id")
  20. if not delegation_id:
  21. raise ValueError("Delegation delivery requires a stable delegation_id")
  22. kind = "hidden" if metadata.get("presentation_suppressed") else "async_delegation_complete"
  23. return self._append_detached_result(session_id, content, kind, metadata, _DELEGATION_DELIVERY_MATCH,
  24. (delegation_id, metadata.get("delivery_notice", "")))
  25. def append_completion_note(self, session_id: str, admission_id: str, content: str, display_kind: str,
  26. metadata: dict[str, Any]) -> int:
  27. """Record an unviewed completion's note once, keyed by its admission (stored as ``completion_admission``)."""
  28. return self._append_detached_result(
  29. session_id, content, display_kind, {**metadata, "completion_admission": admission_id},
  30. "json_extract(m.display_metadata, '$.completion_admission') = ?", (admission_id,))
  31. def _append_detached_result(self, session_id: str, content: str, display_kind: str, metadata: dict[str, Any],
  32. match_sql: str, params: tuple) -> int:
  33. """Record a result that arrived between turns as a user row once, including replay after rotation: a row
  34. ``match_sql`` (a condition on ``m``) finds in the compression lineage is returned instead. Check and insert
  35. share the writer transaction, so independent gateway processes cannot duplicate it; a live turn refuses it."""
  36. from hermes_state_messages import _INSERT_MESSAGE_SQL # that module binds this mixin
  37. msg = {"content": content, "display_kind": display_kind, "display_metadata": metadata}
  38. stamp_message_uid(msg) # a fresh occurrence: mint its durable id
  39. row = self._message_row_params(session_id, "user", msg, None, time.time(), keep_reasoning=True)
  40. def _do(conn):
  41. existing = conn.execute(_LINEAGE_MATCH_SQL + match_sql + " LIMIT 1", (session_id, *params)).fetchone()
  42. if existing is not None:
  43. return existing[0]
  44. self._check_transcript_write_guards(conn, session_id, None, reject_active_turn_lease=True)
  45. msg_id = conn.execute(_INSERT_MESSAGE_SQL, row).lastrowid
  46. self._bump_session_counters(conn, session_id, 1, 0, unit=True)
  47. return msg_id
  48. return self._execute_write(_do, patience_s=self._TRANSCRIPT_WRITE_PATIENCE_S)