session_control_actions.py 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164
  1. """Desktop's goal / loop / heartbeat / subgoal card buttons (``session.control``) on the owner.
  2. ``session.control.read`` was served, so the cards rendered as controllable, while every button
  3. answered -32601. Each action is the typed slash command the button stands for, run through
  4. ``execute_command`` (the gateway's own /goal /loop /heartbeat /subgoal handlers, with their
  5. capability, local-source, admission and busy rules), answered with the owner's control snapshot.
  6. """
  7. import asyncio
  8. import logging
  9. from hermes_state_runtime import RuntimeStoreError
  10. logger = logging.getLogger(__name__)
  11. _ACTION_COMMANDS = {
  12. 'goal.pause': ('goal', 'pause'), 'goal.resume': ('goal', 'resume'),
  13. 'goal.clear': ('goal', 'clear'), 'goal.unwait': ('goal', 'unwait'),
  14. 'loop.pause': ('loop', 'pause'), 'loop.resume': ('loop', 'resume'), 'loop.stop': ('loop', 'stop'),
  15. 'heartbeat.pause': ('heartbeat', 'pause'), 'heartbeat.resume': ('heartbeat', 'resume'),
  16. 'heartbeat.clear': ('heartbeat', 'clear'),
  17. }
  18. _SUBGOAL_ACTIONS = frozenset({'subgoal.add', 'subgoal.remove', 'subgoal.clear'})
  19. _ENVELOPE = ('type', 'output', 'notice', 'message', 'display')
  20. def _validate(action, args):
  21. if not isinstance(args, dict) or set(args) - {'text', 'index'}:
  22. raise RuntimeStoreError('invalid_params')
  23. if action == 'subgoal.remove' and (type(args.get('index')) is not int or args['index'] < 1):
  24. raise RuntimeStoreError('invalid_params')
  25. if action == 'subgoal.add' and (not isinstance(args.get('text'), str) or not args['text'].strip()):
  26. raise RuntimeStoreError('invalid_params')
  27. if action not in _ACTION_COMMANDS and action not in _SUBGOAL_ACTIONS:
  28. raise RuntimeStoreError('invalid_params')
  29. async def _subgoal(connection, ref, params, action, args):
  30. """A criterion button on the session's goal manager. A goal that is gone or an index that no longer exists is a refusal the card shows; the typed /subgoal command reports the same cases as text."""
  31. from pathlib import Path
  32. from agent.i18n import t
  33. from gateway.platforms.base import MessageEvent
  34. from gateway.run import _profile_runtime_scope
  35. from gateway.session_busy_controls import authorize
  36. from gateway.session_local import authorize_local_source
  37. authority = connection.authority
  38. authorize(connection, ref, params, 'session:control')
  39. live = authority.sessions[ref.session_id]
  40. if authorize_local_source(authority.runner, live.source) is not True:
  41. raise RuntimeStoreError('permission_denied')
  42. authority._require_admission_open()
  43. with _profile_runtime_scope(Path(authority.profile_id)):
  44. mgr, _entry = await authority.runner._get_goal_manager_for_event(
  45. MessageEvent(text='/subgoal', source=live.source))
  46. if mgr is None:
  47. raise RuntimeStoreError('command_unavailable', detail=t('gateway.goal.unavailable'))
  48. if not mgr.has_goal():
  49. raise RuntimeStoreError('goal_not_active', detail=t('gateway.subgoal.no_goal'))
  50. try:
  51. if action == 'subgoal.add':
  52. added = mgr.add_subgoal(args['text'].strip())
  53. output = t('gateway.subgoal.added', index=len(mgr.state.subgoals), text=added)
  54. elif action == 'subgoal.remove':
  55. removed = mgr.remove_subgoal(args['index'])
  56. output = t('gateway.subgoal.removed', index=args['index'], text=removed)
  57. else:
  58. count = mgr.clear_subgoals()
  59. output = (t('gateway.subgoal.cleared_one' if count == 1 else 'gateway.subgoal.cleared_other', count=count)
  60. if count else t('gateway.subgoal.none_to_clear'))
  61. except IndexError as exc:
  62. raise RuntimeStoreError('invalid_params', field='index', detail=str(exc)) from exc
  63. except (RuntimeError, ValueError) as exc:
  64. raise RuntimeStoreError('invalid_params', detail=str(exc)) from exc
  65. return {'type': 'exec', 'output': output}
  66. def publish(authority, session_id, *, only_if_present=False, only_if_changed=False):
  67. """Push one live session's control snapshot to every viewer as ``session.control.update``.
  68. Desktop, Ink and the classic CLI paint the goal/loop/heartbeat cards from this event and run the loop
  69. countdown off its ``next_due_at``, so every place that moves that state on the owner publishes: the
  70. slash commands, a fired or settled loop wakeup, a judged turn, a tool that changed it mid-turn.
  71. ``only_if_present`` skips a session with no automation state (a plain turn's event stream stays
  72. unchanged); ``only_if_changed`` also skips one whose snapshot matches the last one published.
  73. """
  74. live = authority.sessions.get(session_id) if authority is not None else None
  75. if live is None:
  76. return
  77. live.control_seq += 1
  78. ticket = live.control_seq
  79. try:
  80. snapshot = _read_control_snapshot(authority, session_id)
  81. except RuntimeStoreError: # unreadable row: the change itself already landed; the next publish repaints
  82. logger.debug('session.control.update skipped for %s', session_id, exc_info=True)
  83. return
  84. _publish_snapshot(authority, live, session_id, snapshot, ticket,
  85. only_if_present=only_if_present, only_if_changed=only_if_changed)
  86. async def publish_async(authority, session_id, *, only_if_present=False, only_if_changed=False):
  87. """``publish`` with the snapshot read in a worker thread: three state.db meta reads per publish
  88. (after every tool and every turn) were a measured loop stall under load. Publishes keep the order
  89. they were scheduled in: each takes a ticket on the loop, and a snapshot whose read finished after a
  90. later-scheduled one already published is dropped (that one read state at least as new)."""
  91. live = authority.sessions.get(session_id) if authority is not None else None
  92. if live is None:
  93. return
  94. live.control_seq += 1
  95. ticket = live.control_seq
  96. try:
  97. snapshot = await asyncio.to_thread(_read_control_snapshot, authority, session_id, scoped=True)
  98. except RuntimeStoreError:
  99. logger.debug('session.control.update skipped for %s', session_id, exc_info=True)
  100. return
  101. if authority.sessions.get(session_id) is not live: # closed or re-mounted while the read ran
  102. return
  103. _publish_snapshot(authority, live, session_id, snapshot, ticket,
  104. only_if_present=only_if_present, only_if_changed=only_if_changed)
  105. def _read_control_snapshot(authority, session_id, *, scoped=False):
  106. from gateway.session_ancillary import control_snapshot
  107. from gateway.session_contract import SessionRef
  108. ref = SessionRef(authority.profile_id, session_id)
  109. if not scoped:
  110. return control_snapshot(authority, ref)
  111. from gateway.session_authorities import owner_scope
  112. with owner_scope(authority): # a worker thread inherits no profile scope it was not given
  113. return control_snapshot(authority, ref)
  114. def _publish_snapshot(authority, live, session_id, snapshot, ticket, *, only_if_present, only_if_changed):
  115. if live.control_published_seq > ticket: # a later-scheduled publish already painted newer state
  116. return
  117. if (only_if_present and not snapshot['revision']) or (only_if_changed and snapshot['revision'] == live.control_revision):
  118. return
  119. live.control_published_seq = ticket
  120. live.control_revision = snapshot['revision']
  121. live.event_stream.publish(session_id, {'control': snapshot}, event_type='session.control.update')
  122. async def control(connection, ref, params):
  123. if set(params) - {'session_id', 'profile', 'action', 'args'} or not ref.session_id:
  124. raise RuntimeStoreError('invalid_params')
  125. action = params.get('action')
  126. if not isinstance(action, str):
  127. raise RuntimeStoreError('invalid_params')
  128. args = {} if params.get('args') is None else params['args']
  129. action = action.strip()
  130. _validate(action, args)
  131. if ref.session_id not in connection.authority.sessions:
  132. raise RuntimeStoreError('not_found')
  133. scope = {key: params[key] for key in ('session_id', 'profile') if key in params}
  134. # Other viewers (another Desktop window, Ink) repaint their cards from session.control.update, not the
  135. # reply: execute_command publishes it for the automation commands, the criterion buttons here.
  136. if action in _SUBGOAL_ACTIONS:
  137. result = await _subgoal(connection, ref, scope, action, args)
  138. publish(connection.authority, ref.session_id)
  139. else:
  140. from gateway.session_commands import execute_command
  141. name, arg = _ACTION_COMMANDS[action]
  142. result = await execute_command(connection, ref, {**scope, 'name': name, 'arg': arg}, dispatch=True)
  143. from gateway.session_ancillary import read
  144. snapshot = await read(connection, ref, scope, kind='control')
  145. return {**snapshot, 'dispatch': {key: result.get(key) for key in _ENVELOPE}}