session_busy_controls.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218
  1. """Session-scoped busy preferences and controls of the existing execution only."""
  2. import asyncio
  3. from functools import partial
  4. from pathlib import Path
  5. from hermes_state_runtime import RuntimeStoreError
  6. def handlers(connection):
  7. return {
  8. 'config.get': partial(busy_config, connection),
  9. 'config.set': partial(busy_config, connection, write=True),
  10. 'session.steer': partial(correct, connection, verb='steer'),
  11. 'session.redirect': partial(correct, connection, verb='redirect'),
  12. }
  13. def authorize(connection, ref, params, capability):
  14. connection.authority.authorize(connection.actor, ref, capability)
  15. # The contract's ``profile`` is nullable; null means this owner, as an omitted key does.
  16. if params.get('profile') is not None:
  17. from hermes_cli.profiles import profile_matches_home
  18. profile = params['profile']
  19. if not isinstance(profile, str):
  20. raise RuntimeStoreError('invalid_params')
  21. if profile and not profile_matches_home(profile, Path(connection.authority.profile_id)):
  22. raise RuntimeStoreError('profile_mismatch')
  23. async def busy_config(connection, ref, params, *, write=False):
  24. if write and params.get('key') == 'model':
  25. # The legacy picker verb. On the owner a model pick is ``session.mutate`` operation=model
  26. # (revision-fenced, retry-idempotent, selection-guarded); a config write would bypass all
  27. # three. Refused before authorization or any read: nothing is written or deferred.
  28. raise RuntimeStoreError('use_session_mutation_model')
  29. allowed = {'session_id', 'profile', 'key'} | ({'value'} if write else set())
  30. if params.get('key') == 'verbose' and not set(params) - allowed and ref.session_id:
  31. return verbose_config(connection, ref, params, write)
  32. if params.get('key') == 'show_reasoning' and not set(params) - allowed and ref.session_id:
  33. return show_reasoning_config(connection, ref, params, write)
  34. if params.get('key') == 'service_tier' and write and not set(params) - allowed and ref.session_id:
  35. return service_tier_config(connection, ref, params)
  36. if params.get('key') == 'yolo' and not set(params) - allowed and ref.session_id:
  37. return await yolo_config(connection, ref, params, write)
  38. if (set(params) - allowed or not ref.session_id or params.get('key') != 'busy'
  39. or (write and params.get('value') not in ('interrupt', 'steer', 'queue'))):
  40. raise RuntimeStoreError('invalid_params')
  41. authorize(connection, ref, params, 'session:control' if write else 'session:read')
  42. authority = connection.authority
  43. live = authority.sessions[ref.session_id]
  44. if write:
  45. # UI negotiation is not a settings write and must not rebuild frozen
  46. # launch policy, toolsets, history, or the retained AIAgent.
  47. live.busy_input_mode = params['value']
  48. value = getattr(live, 'busy_input_mode', None)
  49. if value is None:
  50. from gateway.session_policy import policy_for_source
  51. policy = policy_for_source(authority.runner, live.source)
  52. # Main's TUI defaulted to ``queue`` (``ui-tui/src/app/useConfigSync.ts`` TUI_BUSY_DEFAULT): in a
  53. # full-screen composer the next prompt is authored while the agent streams, and an unintended
  54. # interrupt loses work. Only an explicit ``display.busy_input_mode`` overrides it; every other
  55. # surface keeps the framework default ``interrupt``.
  56. fallback = 'queue' if policy is not None and getattr(policy, 'source', None) == 'tui' else 'interrupt'
  57. display = (policy.config().get('display') or {}) if policy else {}
  58. value = (display.get('busy_input_mode') or fallback if policy else
  59. authority.runner._effective_busy_input_mode(live.source))
  60. if value not in ('interrupt', 'steer', 'queue'):
  61. value = fallback
  62. return {'key': 'busy', 'value': value, 'scope': 'session'}
  63. _VERBOSE_CYCLE = ('off', 'new', 'all', 'verbose')
  64. def verbose_config(connection, ref, params, write):
  65. """Session-scoped /verbose: the tool-progress mode the next tool events of
  66. this session render with (read by TurnRunner), like busy never a settings write."""
  67. value = params.get('value')
  68. if write and value not in (*_VERBOSE_CYCLE, 'cycle'):
  69. raise RuntimeStoreError('invalid_params')
  70. authorize(connection, ref, params, 'session:control' if write else 'session:read')
  71. live = connection.authority.sessions[ref.session_id]
  72. current = getattr(live, 'tool_progress_mode', None) or 'all'
  73. if write:
  74. live.tool_progress_mode = current = (
  75. _VERBOSE_CYCLE[(_VERBOSE_CYCLE.index(current) + 1) % 4] if value == 'cycle' else value)
  76. return {'key': 'verbose', 'value': current, 'scope': 'session'}
  77. def show_reasoning_config(connection, ref, params, write):
  78. """Session-scoped reasoning display (the classic CLI's ``/reasoning show|hide`` and verbose
  79. reasoning): whether a local-viewer turn of this session streams ``reasoning.delta``. Unset, it
  80. reports the launch default the turn uses. Never a settings write."""
  81. value = params.get('value')
  82. word = str(value).strip().lower()
  83. if write and word not in _YOLO_WORDS:
  84. raise RuntimeStoreError('invalid_params')
  85. authorize(connection, ref, params, 'session:control' if write else 'session:read')
  86. live = connection.authority.sessions[ref.session_id]
  87. if write:
  88. live.show_reasoning = _YOLO_WORDS[word]
  89. shown = getattr(live, 'show_reasoning', None)
  90. if shown is None:
  91. from gateway.local_viewer_events import launch_shows_reasoning
  92. from gateway.session_policy import policy_for_source
  93. shown = launch_shows_reasoning(policy_for_source(connection.authority.runner, live.source),
  94. connection.authority)
  95. return {'key': 'show_reasoning', 'value': '1' if shown is True else '0', 'scope': 'session'}
  96. def service_tier_config(connection, ref, params):
  97. """Session-scoped ``/fast`` (the classic CLI's tier pick, ``normal`` clears to normal): the
  98. session's service-tier override the next turn's agent reads (``current_service_tier``), never a
  99. settings write. ``--global`` persistence stays the client's own config.yaml write."""
  100. from agent.fast_mode import parse_exact_service_tier
  101. try:
  102. tier = parse_exact_service_tier(params.get('value')) if isinstance(params.get('value'), str) else None
  103. except ValueError:
  104. tier = None
  105. if tier is None:
  106. raise RuntimeStoreError('invalid_params')
  107. authorize(connection, ref, params, 'session:control')
  108. live = connection.authority.sessions[ref.session_id]
  109. connection.authority.runner._set_session_service_tier_override(live.route, tier or None)
  110. live.event_stream.publish(ref.session_id, {'service_tier': tier or ''}, event_type='session.info')
  111. return {'key': 'service_tier', 'value': tier or 'normal', 'scope': 'session'}
  112. _YOLO_WORDS = {'1': True, 'on': True, 'true': True, '0': False, 'off': False, 'false': False}
  113. async def yolo_config(connection, ref, params, write):
  114. """Session-scoped /yolo (TUI slash + Shift+Tab, Desktop toggle): this session's approval bypass,
  115. never HERMES_YOLO_MODE or approvals.mode. A ``--yolo`` launch is seeded first, so revoking it
  116. here is not re-enabled by the next turn's launch seeding. The write goes through the shared
  117. ``tools.approval_yolo.toggle_session_yolo`` contract on the route's persisted copy
  118. (``SessionEntry.yolo``, restored by ``restore_gateway_yolo``), like the messaging
  119. ``/yolo``: persisted before the live flip, so an OFF here is not revived by the next turn."""
  120. value = params.get('value')
  121. if write and value is not None and str(value).strip().lower() not in _YOLO_WORDS:
  122. raise RuntimeStoreError('invalid_params')
  123. authorize(connection, ref, params, 'session:control' if write else 'session:read')
  124. from gateway.session_policy import policy_for_source
  125. from tools.approval import is_session_yolo_enabled
  126. from tools.approval_yolo import restore_gateway_yolo, toggle_session_yolo
  127. live = connection.authority.sessions[ref.session_id]
  128. runner = connection.authority.runner
  129. policy = policy_for_source(runner, live.source)
  130. store = getattr(runner, 'session_store', None)
  131. entry = await runner.async_session_store.lookup_by_session_key(live.route) if store is not None else None
  132. restore_gateway_yolo(live.route, getattr(entry, 'yolo', None), launch=bool(policy is not None and policy.yolo))
  133. # After a restart only the persisted copy is set until the next turn re-arms it: still ON.
  134. persisted = getattr(entry, 'yolo', False) is True
  135. enabled = is_session_yolo_enabled(live.route) or persisted
  136. if write:
  137. persist = (lambda on: store.set_session_yolo(live.route, on)) if store is not None else None
  138. # Off the loop: the persist is a routing-store write (thread-safe), as in the messaging /yolo.
  139. enabled = await asyncio.to_thread(
  140. toggle_session_yolo, live.route, None if value is None else _YOLO_WORDS[str(value).strip().lower()],
  141. persisted=persisted, persist=persist)
  142. return {'key': 'yolo', 'value': '1' if enabled else '0', 'scope': 'session'}
  143. def adopts_owner_agent(authority, ref):
  144. """The claimed turn runs an in-process owner agent, which adopt_agent hands latched steers to;
  145. a cron job or a managed worker has no steer seam, so a latch there would be acknowledged and lost."""
  146. from gateway.session_managed_worker import managed_policy
  147. from gateway.session_policy import policy_for_source
  148. try:
  149. policy = policy_for_source(authority.runner, authority.sessions[ref.session_id].source)
  150. return not (policy is not None and policy.source == 'cron') and managed_policy(authority, ref) is None
  151. except RuntimeStoreError:
  152. return False
  153. async def correct(connection, ref, params, *, verb):
  154. if (set(params) - {'session_id', 'profile', 'text', 'execution_generation'}
  155. or not isinstance(params.get('text'), str) or not params['text'].strip()
  156. or type(params.get('execution_generation')) is not int):
  157. raise RuntimeStoreError('invalid_params')
  158. authorize(connection, ref, params, 'session:control')
  159. # TUI-26: text typed during a running turn in Ink's interrupt/steer busy modes arrives here, not
  160. # at prompt.submit. A bare stop phrase in a LOCAL voice chat ends the chat and reaches no agent,
  161. # whatever generation is running.
  162. voice_stop = getattr(connection, '_typed_voice_stop', None)
  163. if voice_stop is not None and await voice_stop(ref, params):
  164. return {'voice_stopped': True}
  165. authority = connection.authority
  166. generation = params['execution_generation']
  167. live = authority.sessions[ref.session_id]
  168. with live.event_stream.lock:
  169. authority.check_approval_generation(ref.session_id, generation)
  170. # Managed workers have a separate control channel, not a cached owner
  171. # agent. Refuse explicitly instead of acknowledging undeliverable text.
  172. if ref.session_id in getattr(authority, '_managed_workers', {}):
  173. raise RuntimeStoreError('unsupported_control')
  174. # Accepted for this exact claim before its turn built an agent: steer_agent latches it for
  175. # the agent this generation adopts, never a later one.
  176. agent, latched = authority.steer_agent(ref, generation, params['text'] if verb == 'steer' else None)
  177. if latched:
  178. return {'status': 'queued', 'text': params['text'], 'execution_generation': generation,
  179. 'authority_epoch': authority.epoch}
  180. # A claim can outlive the agent that carried it (a reaped turn the client still believes is
  181. # running), and a redirect in the build window has no agent to queue behind. Nothing live can
  182. # take the text, so answer 'rejected' — the wire contract's "not corrected, queue it as the
  183. # next prompt" (desktop SessionRedirectResponse, tui_gateway's idle-steer reply). Raising here
  184. # made clients discard the message (#141644). ``delivered: False`` is the confirmation a
  185. # client may re-admit on: the live-agent 'rejected' below can follow delivery.
  186. if agent is None:
  187. return {'status': 'rejected', 'text': params['text'], 'execution_generation': generation,
  188. 'authority_epoch': authority.epoch, 'delivered': False}
  189. method = getattr(agent, verb, None)
  190. if not callable(method):
  191. raise RuntimeStoreError('execution_not_ready')
  192. accepted = method(params['text'])
  193. return {'status': ({'steer': 'queued', 'redirect': 'redirected'}[verb] if accepted else 'rejected'),
  194. 'text': params['text'], 'execution_generation': generation,
  195. 'authority_epoch': authority.epoch}