session_config.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  1. """Owner-bound native settings and model inventory, never legacy execution."""
  2. import asyncio
  3. from functools import partial
  4. import hashlib
  5. import json
  6. from pathlib import Path
  7. from hermes_state_runtime import RuntimeStoreError
  8. def handlers(connection):
  9. return {'config.get': partial(config_get, connection),
  10. 'model.options': partial(model_options, connection)}
  11. def _authorize(connection, ref, params):
  12. authority, actor = connection.authority, connection.actor
  13. if actor.profile_id != authority.profile_id:
  14. raise RuntimeStoreError('profile_mismatch')
  15. if 'session:read' not in actor.capabilities:
  16. raise RuntimeStoreError('permission_denied')
  17. for name in ('profile', 'session_id'):
  18. if name in params and not isinstance(params[name], str):
  19. raise RuntimeStoreError('invalid_params')
  20. if params.get('profile'):
  21. from hermes_cli.profiles import profile_matches_home
  22. if not profile_matches_home(params['profile'], Path(authority.profile_id)):
  23. raise RuntimeStoreError('profile_mismatch')
  24. if ref.session_id:
  25. authority.authorize(actor, ref, 'session:read')
  26. from gateway.session_policy import policy_for_source
  27. return policy_for_source(authority.runner, authority.sessions[ref.session_id].source)
  28. return None
  29. def mcp_revision(policy, cfg) -> str:
  30. """``mcp_rev``: the MCP-relevant sections a client polls (``config.get mtime``) and names back on
  31. ``reload.mcp``. Read from the session's frozen policy when it has one — a live config edit is not an
  32. MCP reload request, it reaches a chat as a committed generation — so the value a client is told to load
  33. is the value the session already holds."""
  34. return hashlib.sha256(json.dumps({k: (policy.config() if policy else cfg).get(k)
  35. for k in ('mcp', 'mcp_servers', 'tools')},
  36. sort_keys=True).encode()).hexdigest()[:12]
  37. def _client_config(cfg):
  38. # Native full-config consumers are presentation-only. Do not export provider,
  39. # MCP, plugin or terminal configuration (which can contain arbitrary secrets).
  40. from hermes_cli.config import redact_config_value
  41. result = redact_config_value({key: cfg[key] for key in (
  42. 'display', 'approvals', 'paste_collapse_threshold', 'paste_collapse_char_threshold') if key in cfg})
  43. if 'display' in result:
  44. # Its readers are local surfaces (Ink, Desktop): the local key a local /reasoning show|hide or
  45. # /footer saved wins over the global one (T7).
  46. from gateway.display_config import local_display_config
  47. result['display'] = local_display_config(result['display'])
  48. # Allowlisted after redaction: ``record_key`` is a keybinding, not a credential, but the
  49. # structural masker treats every ``*_key`` leaf as one. The voice section's real secrets
  50. # (``api_key``) never enter the projection.
  51. result['voice'] = {key: cfg.get('voice', {}).get(key) for key in ('record_key', 'submit_mode')
  52. if key in cfg.get('voice', {})}
  53. return result
  54. async def config_get(connection, ref, params):
  55. if set(params) - {'session_id', 'profile', 'key', 'cwd'}:
  56. raise RuntimeStoreError('invalid_params')
  57. key = params.get('key')
  58. if not isinstance(key, str):
  59. raise RuntimeStoreError('invalid_params')
  60. if key in ('busy', 'verbose', 'yolo', 'show_reasoning'):
  61. from gateway.session_busy_controls import busy_config
  62. return await busy_config(connection, ref, params)
  63. policy = _authorize(connection, ref, params)
  64. if 'cwd' in params and (key != 'project' or not isinstance(params['cwd'], str)):
  65. raise RuntimeStoreError('invalid_params')
  66. if key == 'voice':
  67. return _voice(connection, ref)
  68. agent = connection.authority.agent(ref) if ref.session_id else None
  69. def read():
  70. from gateway.run import _profile_runtime_scope
  71. from hermes_cli.config import load_config
  72. from hermes_cli.config_backend import config_version_or_none, version_token
  73. from hermes_cli.config_effective import load_user_config_effective
  74. from hermes_constants import DEFAULT_INDICATOR_STYLE
  75. from tools.approval_context import _get_approval_mode
  76. home = Path(connection.authority.profile_id)
  77. with _profile_runtime_scope(home):
  78. cfg = load_config()
  79. display = cfg.get('display') or {}
  80. getters = {
  81. # The user's own settings, not DEFAULT_CONFIG: clients read an absent key as their
  82. # own default (the TUI streams unless display.streaming is explicitly false).
  83. 'full': lambda: {'config': _client_config(load_user_config_effective(home / 'config.yaml'))},
  84. 'mtime': lambda: {'mtime': version_token(config_version_or_none(home / 'config.yaml')),
  85. # Frozen tool policy is not a live MCP reload request.
  86. 'mcp_rev': mcp_revision(policy, cfg)},
  87. 'reasoning': lambda: _reasoning(agent, policy, cfg, connection, ref),
  88. 'fast': lambda: _fast(connection, ref, policy, agent, cfg),
  89. 'service_tier': lambda: _service_tier(connection, ref, policy),
  90. 'daybreak': lambda: {'value': (cfg.get('agent') or {}).get('daybreak') is True},
  91. 'skin': lambda: {'value': display.get('skin', 'default')},
  92. 'theme': lambda: {'value': display.get('tui_theme', 'auto')},
  93. 'indicator': lambda: {'value': display.get('tui_status_indicator', DEFAULT_INDICATOR_STYLE)},
  94. 'details_mode': lambda: {'value': display.get('details_mode', 'collapsed')},
  95. 'approvals.mode': lambda: {'value': _get_approval_mode()},
  96. 'approval_mode': lambda: {'value': _get_approval_mode()},
  97. 'project': lambda: _project(params, policy, cfg),
  98. 'profile': lambda: {'home': str(home), 'display': str(home)},
  99. }
  100. if key not in getters:
  101. raise RuntimeStoreError('invalid_params')
  102. return getters[key]()
  103. return await asyncio.to_thread(read)
  104. def session_voice_mode(connection, ref):
  105. """``off`` / ``voice_only`` / ``all``: the session's ``/voice`` mode as the messaging handler stored it."""
  106. runner, live = connection.authority.runner, connection.authority.sessions[ref.session_id]
  107. if live.source is None: # a history mount: no chat for a voice mode to belong to
  108. return 'off'
  109. modes = getattr(runner, '_voice_mode', None) or {}
  110. return modes.get(runner._voice_key_for_source(live.source), 'off')
  111. def local_voice_enabled(session_id):
  112. """True/False for a local session the running owner holds (its gateway ``/voice`` mode), else
  113. None (no owner in this process, or not one of its sessions: the sidecar's env flag applies)."""
  114. from gateway.run_api import _ACTIVE_RUNNER
  115. from gateway.session_authorities import all_authorities
  116. if _ACTIVE_RUNNER is None or not isinstance(session_id, str) or not session_id:
  117. return None
  118. for authority in all_authorities(_ACTIVE_RUNNER):
  119. live = getattr(authority, 'sessions', {}).get(session_id)
  120. if live is not None:
  121. if live.source is None: # a history mount: no chat for a voice mode to belong to
  122. return False
  123. modes = getattr(_ACTIVE_RUNNER, '_voice_mode', None) or {}
  124. return modes.get(_ACTIVE_RUNNER._voice_key_for_source(live.source), 'off') != 'off'
  125. return None
  126. def set_local_voice_mode(session_id, mode):
  127. """The one writer for a local session's voice mode outside ``/voice`` (wake, spoken stop): sets
  128. and persists the owner's per-session mode. True when the running owner holds the session, else
  129. None (the sidecar's env flag applies)."""
  130. from gateway.run_api import _ACTIVE_RUNNER
  131. from gateway.session_authorities import all_authorities
  132. if _ACTIVE_RUNNER is None or not isinstance(session_id, str) or not session_id:
  133. return None
  134. for authority in all_authorities(_ACTIVE_RUNNER):
  135. live = getattr(authority, 'sessions', {}).get(session_id)
  136. if live is not None:
  137. _ACTIVE_RUNNER._voice_mode[_ACTIVE_RUNNER._voice_key_for_source(live.source)] = mode
  138. _ACTIVE_RUNNER._save_voice_modes()
  139. local_voice_transition(live.source, mode)
  140. return True
  141. return None
  142. def local_voice_transition(source, mode):
  143. """A local session's voice mode went ``off``: end the push-to-talk capture it started in this
  144. process (and drop its late callbacks), as the sidecar's ``voice.toggle off`` did. Another
  145. session's capture is left alone."""
  146. import sys
  147. from gateway.config import Platform
  148. server = sys.modules.get('tui_gateway.server')
  149. if mode == 'off' and server is not None and getattr(source, 'platform', None) == Platform.LOCAL:
  150. server._stop_session_voice_capture(source.chat_id)
  151. def _voice(connection, ref):
  152. """The session's own ``/voice`` mode, so Ink mirrors the gateway's per-session state instead of
  153. the sidecar's process-global ``HERMES_VOICE`` (T9)."""
  154. if not ref.session_id:
  155. raise RuntimeStoreError('invalid_params')
  156. return {'value': session_voice_mode(connection, ref)}
  157. def _fast(connection, ref, policy, agent, cfg):
  158. from agent.fast_mode import parse_service_tier
  159. if ref.session_id: # the session's next-turn tier: its /fast pin, else its policy's
  160. from gateway.session_tui_config import current_tier
  161. tier = current_tier(connection, ref, policy)
  162. else:
  163. tier = getattr(agent, 'service_tier', None) or parse_service_tier(cfg.get('agent', {}).get('service_tier'))
  164. return {'value': {'priority': 'fast', 'ultrafast': 'ultrafast'}.get(tier, 'normal')}
  165. def _service_tier(connection, ref, policy):
  166. from agent.fast_mode import service_tier_word
  167. from gateway.session_tui_config import current_tier, service_tier_options
  168. if not ref.session_id:
  169. raise RuntimeStoreError('invalid_params')
  170. return {'value': service_tier_word(current_tier(connection, ref, policy)),
  171. 'options': service_tier_options(connection, ref, policy)}
  172. def _reasoning(agent, policy, cfg, connection=None, ref=None):
  173. from hermes_constants import resolve_reasoning_config
  174. value = getattr(agent, 'reasoning_config', None)
  175. if not isinstance(value, dict) and policy is not None:
  176. # The next turn's level: a typed session /reasoning, else the frozen (or followed) one.
  177. runner = connection.authority.runner
  178. value = policy.current_reasoning_config(runner, connection.authority.sessions[ref.session_id].route)
  179. elif not isinstance(value, dict):
  180. value = resolve_reasoning_config(cfg, '')
  181. effort = 'none' if value and value.get('enabled') is False else (value or {}).get('effort', 'medium')
  182. from gateway.display_config import local_display_config
  183. shown = local_display_config(cfg.get('display')).get('show_reasoning', True)
  184. return {'value': effort, 'display': 'show' if shown else 'hide'}
  185. def _project(params, policy, cfg):
  186. from tui_gateway import git_probe
  187. cwd = params.get('cwd') or (policy.cwd if policy else cfg.get('terminal', {}).get('cwd'))
  188. if not cwd:
  189. from agent.runtime_cwd import resolve_agent_cwd
  190. cwd = str(resolve_agent_cwd())
  191. return {'cwd': cwd, 'branch': git_probe.branch(cwd)}
  192. async def model_options(connection, ref, params):
  193. flags = {'explicit_only', 'include_unconfigured', 'refresh'}
  194. if (set(params) - flags - {'profile', 'session_id'}
  195. or any(type(params[k]) is not bool for k in flags & params.keys())):
  196. raise RuntimeStoreError('invalid_params')
  197. policy = _authorize(connection, ref, params)
  198. agent = connection.authority.agent(ref) if ref.session_id else None
  199. provider = getattr(agent, 'provider', None) or (policy.provider if policy else None)
  200. model = getattr(agent, 'model', None) or (policy.model if policy else None)
  201. base_url = getattr(agent, 'base_url', None) or (policy.base_url if policy else None)
  202. def discover():
  203. from gateway.run import _profile_runtime_scope
  204. from hermes_cli.inventory import load_picker_context, build_model_options_payload
  205. with _profile_runtime_scope(Path(connection.authority.profile_id)):
  206. ctx = load_picker_context()
  207. selected = provider
  208. if selected == 'custom':
  209. from hermes_cli.runtime_provider import canonical_custom_identity
  210. selected = canonical_custom_identity(base_url=base_url, config_provider=ctx.current_provider, model=model,
  211. requested=getattr(agent, 'requested_provider', None)) or selected
  212. return build_model_options_payload(ctx.with_overrides(current_provider=selected,
  213. current_model=model, current_base_url=base_url), **{k: params[k] for k in flags & params.keys()})
  214. return await asyncio.to_thread(discover)