session_completion_notes.py 4.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. """A completion for a local session no viewer is watching is written into it as a note (#134889 LC-7).
  2. Main's CLI and TUI hosted async delegations and background processes in their own process, so once
  3. the user left nothing started a turn for them. Under the gateway the owner outlives its viewers. The
  4. completion is admitted like any producer input. Producers still coalesce a batch into one admission
  5. under its primary identity, the siblings' identities in its descriptor: a lookup by any of them finds
  6. it (``completion_admission``), results already admitted are left out of a new batch, and the one
  7. outcome, note or turn, covers the whole batch. When that admission comes up for execution with no
  8. viewer attached (the authority's own subscriber records) the executor records it in the session's
  9. history, where the next turn sees it, and settles the admission without a model call. Queue order, restart survival and
  10. exactly-once are the admission contract's. With a viewer attached it runs as the turn it always was,
  11. except a local cron result, which is always a note; messaging, Kanban, ``/loop`` and heartbeat wakes
  12. never reach here.
  13. """
  14. import json
  15. from functools import partial
  16. # ``_completion_delivery_identity`` kinds: an async delegation's result, a background process's exit
  17. # and its watch-pattern notices.
  18. _NOTED_PRODUCERS = frozenset({'async_delegation', 'completion', 'watch_match', 'watch_disabled'})
  19. # A cron result for a local chat (``session_cron.deliver_to_local_chat``) is finished text: a note
  20. # with or without a viewer, since a turn over it would only spend a model call (#143547 CRON-11).
  21. _ALWAYS_NOTED = frozenset({'cron'})
  22. def _producer(identity):
  23. try:
  24. return json.loads(identity)[0]
  25. except (ValueError, TypeError, IndexError, KeyError):
  26. return None
  27. def noted_completion(row):
  28. """*row* is a local completion admission: a note when it runs with no viewer attached."""
  29. descriptor = (row or {}).get('payload', {}).get('local_automation_v1')
  30. return descriptor is not None and _producer(descriptor['identity']) in _NOTED_PRODUCERS | _ALWAYS_NOTED
  31. async def reopen_for_turn(authority, ref):
  32. """A turn (never a note) makes *ref*'s finalized row live again: a local session's receipt tip, or
  33. the row of a conversation its chat moved past (gateway/session_detached.py), which the chat's /new
  34. ended."""
  35. from gateway.session_runtime_workers import tracked_write
  36. live = authority.sessions.get(ref.session_id)
  37. if live is not None and live.detached:
  38. from gateway.session_api import reopen_api_session as reopen
  39. else:
  40. from gateway.session_local_recovery import reopen_local_session as reopen
  41. await tracked_write(authority, partial(reopen, authority, ref))
  42. async def note_if_unviewed(authority, ref, row):
  43. """The claimed *row*'s response when it was written as a note instead of running, else None.
  44. It is the FIFO head, so the note lands after every input committed before it and before every
  45. input committed after; the viewer check and the decision share one loop step."""
  46. if not noted_completion(row):
  47. return None
  48. from gateway.session_runtime_workers import tracked_write
  49. live = authority.sessions.get(ref.session_id)
  50. descriptor = row['payload']['local_automation_v1']
  51. if live is None or (live.subscribers and _producer(descriptor['identity']) not in _ALWAYS_NOTED):
  52. # The claim left a closed row closed for a note; the turn reopens it as any first turn does.
  53. await reopen_for_turn(authority, ref)
  54. return None
  55. from gateway.session_viewer_close import _physical_target
  56. metadata = {'completion_note': sorted(set(descriptor.get('identities') or ()) | {descriptor['identity']})}
  57. metadata.update({key: descriptor[key] for key in ('display_text', 'notification_category') if key in descriptor})
  58. target = _physical_target(authority, ref.session_id)
  59. # Keyed by its admission: a claim is never replayed, and this keeps a write retry exact.
  60. await tracked_write(authority, partial(
  61. authority.db.append_completion_note, target, row['admission_id'], row['payload']['text'],
  62. descriptor.get('display_kind', 'internal_notification'), metadata))
  63. refresh = getattr(authority.runner, '_refresh_agent_cache_message_count', None)
  64. if refresh is not None: # the owner's own row: a cached agent stays, as after a turn's writes
  65. await refresh(live.route, target)
  66. authority.pending_results[row['admission_id']] = {'result': {'final_response': '', 'messages': []}, 'usage': {}}
  67. return ''