session_tui_config.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  1. """Owner ``config.set`` for the TUI's profile preferences.
  2. Main served these from the per-TUI sidecar (``tui_gateway/methods_config_set.py``); on the shared
  3. owner they write the OWNING profile's config.yaml (raw round-trip, off-loop, under its runtime
  4. scope) with main's per-key semantics. The session controls (busy/verbose/yolo/show_reasoning/
  5. service_tier, the refused ``model``) stay in ``gateway.session_busy_controls``; any other key is
  6. ``invalid_params``.
  7. """
  8. import asyncio
  9. import copy
  10. from functools import partial
  11. from pathlib import Path
  12. import threading
  13. from hermes_state_runtime import RuntimeStoreError
  14. _SESSION_CONTROL_KEYS = frozenset({'busy', 'verbose', 'yolo', 'show_reasoning', 'service_tier', 'model'})
  15. _DETAIL_SECTIONS = ('thinking', 'tools', 'subagents', 'activity')
  16. _DETAIL_MODES = frozenset({'hidden', 'collapsed', 'expanded'})
  17. _STATUSBAR_MODES = ('off', 'top', 'bottom')
  18. _BOOL_WORDS = {'on': True, 'true': True, 'yes': True, 'off': False, 'false': False, 'no': False}
  19. _WRITE_LOCK = threading.Lock() # one read-modify-write of config.yaml at a time
  20. def handlers(connection):
  21. return {'config.set': partial(config_set, connection)}
  22. def _word(value):
  23. return ('' if value is None else str(value)).strip().lower()
  24. def _statusbar(raw):
  25. return 'off' if raw is False else raw.strip().lower() if (
  26. isinstance(raw, str) and raw.strip().lower() in _STATUSBAR_MODES) else 'top'
  27. def _toggles():
  28. """key -> (display field, word -> value, flipped(display), report(value)); '' / toggle flips."""
  29. from tui_gateway.agent_factory import _MOUSE_TRACKING_ALIASES, _display_mouse_tracking
  30. def on_off(value):
  31. return 'on' if value else 'off'
  32. return {
  33. 'density': ('tui_compact', {'on': True, 'off': False},
  34. lambda d: not bool(d.get('tui_compact', False)), on_off),
  35. 'battery': ('battery', _BOOL_WORDS, lambda d: not bool(d.get('battery', False)), on_off),
  36. # The classic CLI's /timestamps key: [HH:MM] on transcript rows (T10).
  37. 'timestamps': ('timestamps', _BOOL_WORDS, lambda d: not bool(d.get('timestamps', False)), on_off),
  38. 'statusbar': ('tui_statusbar', {'on': 'top', **{m: m for m in _STATUSBAR_MODES}},
  39. lambda d: 'top' if _statusbar(d.get('tui_statusbar', 'top')) == 'off' else 'off', str),
  40. 'mouse': ('mouse_tracking', _MOUSE_TRACKING_ALIASES,
  41. lambda d: 'all' if _display_mouse_tracking(d) == 'off' else 'off', str)}
  42. def _words():
  43. """key -> (display field, accepted words)."""
  44. from hermes_constants import INDICATOR_STYLES
  45. return {'theme': ('tui_theme', frozenset({'auto', 'light', 'dark'})),
  46. 'indicator': ('tui_status_indicator', frozenset(INDICATOR_STYLES))}
  47. def _display(cfg):
  48. if not isinstance(cfg.get('display'), dict):
  49. cfg['display'] = {}
  50. return cfg['display']
  51. def _sections(display):
  52. if not isinstance(display.get('sections'), dict):
  53. display['sections'] = {}
  54. return display['sections']
  55. def _set_display(cfg, key, value):
  56. """One display preference on the raw config, main's semantics; returns the result extras."""
  57. display, raw = _display(cfg), _word(value)
  58. if key in (toggles := _toggles()):
  59. field, aliases, flipped, report = toggles[key]
  60. new = flipped(display) if raw in ('', 'toggle') else aliases.get(raw)
  61. if new is None:
  62. raise RuntimeStoreError('invalid_params')
  63. display[field] = new
  64. return {'value': report(new)}
  65. if key in (words := _words()):
  66. field, allowed = words[key]
  67. if raw not in allowed:
  68. raise RuntimeStoreError('invalid_params')
  69. display[field] = raw
  70. return {'value': raw}
  71. if key == 'details_mode':
  72. if raw not in _DETAIL_MODES:
  73. raise RuntimeStoreError('invalid_params')
  74. display['details_mode'] = raw
  75. _sections(display).update(dict.fromkeys(_DETAIL_SECTIONS, raw))
  76. return {'value': raw}
  77. if key.startswith('details_mode.'):
  78. section = key.split('.', 1)[1]
  79. if section not in _DETAIL_SECTIONS or (raw and raw not in _DETAIL_MODES):
  80. raise RuntimeStoreError('invalid_params')
  81. if raw:
  82. _sections(display)[section] = raw
  83. else: # empty clears the override (the client falls back to its section default)
  84. _sections(display).pop(section, None)
  85. return {'value': raw}
  86. if key == 'focus':
  87. return _set_focus(display, raw)
  88. if key == 'skin':
  89. if not isinstance(value, str) or not value.strip():
  90. raise RuntimeStoreError('invalid_params')
  91. display['skin'] = value.strip()
  92. return {'value': value.strip()}
  93. raise RuntimeStoreError('invalid_params')
  94. def _set_focus(display, raw):
  95. """/focus on stashes the configured tool-progress mode and pins it off; off restores it."""
  96. from hermes_cli.focus_view import FOCUS_TOOL_PROGRESS_MODE, normalize_tool_progress_mode, resolve_focus_arg
  97. current = bool(display.get('focus_view', False))
  98. configured = normalize_tool_progress_mode(display.get('tool_progress', 'all'))
  99. action, target = resolve_focus_arg(raw, current)
  100. if action == 'usage':
  101. raise RuntimeStoreError('invalid_params')
  102. if action == 'status' or target is None:
  103. return {'value': 'on' if current else 'off', 'tool_progress': configured}
  104. if target:
  105. display['focus_saved_tool_progress'] = normalize_tool_progress_mode(
  106. (current and display.get('focus_saved_tool_progress')) or configured)
  107. effective = FOCUS_TOOL_PROGRESS_MODE
  108. else:
  109. effective = normalize_tool_progress_mode(display.get('focus_saved_tool_progress') or 'all')
  110. display['tool_progress'], display['focus_view'] = effective, bool(target)
  111. return {'value': 'on' if target else 'off', 'tool_progress': effective}
  112. def _write_profile_config(connection, edit):
  113. """``edit(raw_cfg)`` on the owning profile's config.yaml EXACTLY as written (no defaults or
  114. overlay persisted); saved only when it changed. Runs off the loop."""
  115. from gateway.run import _profile_runtime_scope
  116. from hermes_cli.config import atomic_config_replace, get_config_path, read_user_config_raw
  117. with _profile_runtime_scope(Path(connection.authority.profile_id)), _WRITE_LOCK:
  118. path = get_config_path()
  119. try:
  120. cfg = read_user_config_raw(path)
  121. except Exception as exc: # unparseable: never overwrite the user's file
  122. raise RuntimeStoreError('storage_unavailable') from exc
  123. before = copy.deepcopy(cfg)
  124. result = edit(cfg)
  125. if cfg != before:
  126. try:
  127. atomic_config_replace(path, cfg)
  128. except Exception as exc:
  129. raise RuntimeStoreError('storage_unavailable') from exc
  130. return result
  131. def _authorize_write(connection, ref, params):
  132. """Profile-level like ``config.get`` (a session is optional), plus the control capability."""
  133. from gateway.session_config import _authorize
  134. policy = _authorize(connection, ref, params)
  135. if 'session:control' not in connection.actor.capabilities:
  136. raise RuntimeStoreError('permission_denied')
  137. return policy
  138. # Profile settings main's sidecar wrote for Desktop's toggles (``tui_gateway/server.py::_DISPLAY_TOGGLE_KEYS``)
  139. # and its voice-engine pick: config.yaml leaves with main's validation.
  140. _DISPLAY_TOGGLE_KEYS = frozenset({'display.message_reactions', 'display.in_app_tips', 'display.in_app_tours'})
  141. _VOICE_CHAT_MODES = frozenset({'chained', 'gpt-live'})
  142. async def config_set(connection, ref, params):
  143. key = params.get('key')
  144. if key == 'reasoning' or (key == 'yolo' and 'scope' in params):
  145. return await _set_command_setting(connection, ref, params)
  146. if key in _SESSION_CONTROL_KEYS or not isinstance(key, str):
  147. from gateway.session_busy_controls import busy_config
  148. return await busy_config(connection, ref, params, write=True)
  149. if set(params) - {'session_id', 'profile', 'key', 'value'}:
  150. raise RuntimeStoreError('invalid_params')
  151. policy = _authorize_write(connection, ref, params)
  152. value = params.get('value')
  153. if key == 'fast':
  154. return await _set_fast(connection, ref, policy, value)
  155. if key == 'personality':
  156. return await asyncio.to_thread(_set_personality, connection, value)
  157. if key in ('approvals.mode', 'approval_mode'):
  158. return await asyncio.to_thread(_set_approval_mode, connection, value)
  159. if key in _DISPLAY_TOGGLE_KEYS or key == 'voice.voice_chat_mode':
  160. return {'key': key, **await asyncio.to_thread(_write_profile_config, connection,
  161. lambda cfg: _set_profile_leaf(cfg, key, value))}
  162. if key == 'daybreak':
  163. # Profile-wide like Codex's own switch; every next turn re-reads it (``_load_daybreak``).
  164. return {'key': key, **await asyncio.to_thread(_write_profile_config, connection,
  165. lambda cfg: _set_profile_leaf(cfg, 'agent.daybreak', value))}
  166. result = await asyncio.to_thread(_write_profile_config, connection,
  167. lambda cfg: _set_display(cfg, key, value))
  168. if key == 'focus' and ref.session_id and 'tool_progress' in result:
  169. # Main's session also took the focus mode at once: this session's /verbose state.
  170. connection.authority.sessions[ref.session_id].tool_progress_mode = result['tool_progress']
  171. if key == 'skin':
  172. await _broadcast_skin(connection)
  173. return {'key': key, **result}
  174. async def _broadcast_skin(connection):
  175. """Main repainted every surface of the profile: ``skin.changed`` on each attached session."""
  176. def resolve():
  177. import sys
  178. from gateway.run import _profile_runtime_scope
  179. from hermes_cli.config import load_config
  180. from tui_gateway.change_watcher import skin_payload
  181. with _profile_runtime_scope(Path(connection.authority.profile_id)):
  182. payload = skin_payload(load_config())
  183. if (server := sys.modules.get('tui_gateway.server')) is not None:
  184. server._note_skin_broadcast() # as main: the config watcher must not repaint it again
  185. return payload
  186. payload = await asyncio.to_thread(resolve)
  187. for session_id, live in list(connection.authority.sessions.items()):
  188. if live.subscribers:
  189. live.event_stream.publish(session_id, payload, event_type='skin.changed')
  190. def current_tier(connection, ref, policy):
  191. """The tier this session's next turn runs: its /fast pin, else its policy's (or the profile's)."""
  192. runner, live = connection.authority.runner, connection.authority.sessions[ref.session_id]
  193. if policy is not None:
  194. return policy.current_service_tier(runner, live.route)
  195. return runner._resolve_session_service_tier(source=live.source, session_key=live.route)
  196. def service_tier_options(connection, ref, policy, *, include_ultrafast=True):
  197. """The session route's speed choices, resolved under its credential scope."""
  198. from agent.codex_service_tiers import ultrafast_offered
  199. from gateway.run import _profile_runtime_scope
  200. from hermes_cli.models import resolve_fast_mode_overrides
  201. with _profile_runtime_scope(Path(connection.authority.profile_id)):
  202. agent = connection.authority.agent(ref)
  203. config, model = policy.effective(connection.authority, secrets=False) if policy else ({}, None)
  204. route = config.get('model') or {}
  205. provider, base_url = route.get('provider'), route.get('base_url')
  206. if policy is not None and policy.follows_profile:
  207. from gateway.session_policy import route_launch_key
  208. access_token = route_launch_key(connection.authority, policy, config) or route.get('api_key')
  209. else:
  210. model = getattr(agent, 'model', None) or model
  211. provider = getattr(agent, 'provider', None) or provider
  212. base_url = getattr(agent, 'base_url', None) or base_url
  213. access_token = getattr(agent, 'api_key', None)
  214. if not model or resolve_fast_mode_overrides(model, provider=provider, base_url=base_url) is None:
  215. return []
  216. options = ['normal', 'fast', 'auto', 'cold']
  217. if include_ultrafast and ultrafast_offered(model, provider=provider, base_url=base_url,
  218. access_token=access_token):
  219. options.append('ultrafast')
  220. return options
  221. async def _set_fast(connection, ref, policy, value):
  222. """Session-scoped /fast like main's: validated against the session's route, never config.yaml.
  223. The words parse through the shared tier table (``parse_exact_service_tier``, as the classic CLI's
  224. ``config.set service_tier`` does); the pin is the same per-session override the next turn reads
  225. (``current_service_tier``). TUI-only on top: ``toggle`` / ``status`` and the route check."""
  226. from agent.fast_mode import STATIC_TIERS, parse_exact_service_tier, service_tier_word
  227. if not ref.session_id:
  228. raise RuntimeStoreError('invalid_params')
  229. raw, current = _word(value), current_tier(connection, ref, policy)
  230. if raw == 'status':
  231. return {'key': 'fast', 'value': service_tier_word(current)}
  232. if raw in ('', 'toggle'):
  233. raw = 'normal' if current in STATIC_TIERS else 'fast'
  234. try:
  235. tier = parse_exact_service_tier(raw) or None
  236. except ValueError:
  237. raise RuntimeStoreError('invalid_params') from None
  238. if tier in STATIC_TIERS:
  239. options = await asyncio.to_thread(service_tier_options, connection, ref, policy,
  240. include_ultrafast=tier == 'ultrafast')
  241. if service_tier_word(tier) not in options:
  242. raise RuntimeStoreError('fast_unavailable')
  243. from gateway.session_busy_controls import service_tier_config
  244. service_tier_config(connection, ref, {'session_id': ref.session_id, 'value': raw})
  245. return {'key': 'fast', 'value': service_tier_word(tier)}
  246. def _set_personality(connection, value):
  247. """Main's /personality: validated against the profile's personalities and persisted through
  248. ``hermes_cli.personality`` (the only sanctioned write). Every next turn of the profile's sessions
  249. resolves its ephemeral prompt from that config, and the changed prompt rebuilds the cached agent."""
  250. from gateway.run import _profile_runtime_scope
  251. from hermes_cli.config import load_config
  252. from hermes_cli.personality import persist_personality, resolve_personality
  253. with _profile_runtime_scope(Path(connection.authority.profile_id)), _WRITE_LOCK:
  254. try:
  255. name, _prompt = resolve_personality(str(value or ''), load_config())
  256. except ValueError as exc:
  257. raise RuntimeStoreError('unknown_personality') from exc
  258. if not persist_personality(name):
  259. raise RuntimeStoreError('storage_unavailable')
  260. return {'key': 'personality', 'value': str(value or 'none'), 'history_reset': False}
  261. def _set_profile_leaf(cfg, key, value):
  262. section, leaf = key.split('.', 1)
  263. if key == 'voice.voice_chat_mode':
  264. new = _word(value)
  265. if new not in _VOICE_CHAT_MODES:
  266. raise RuntimeStoreError('invalid_params')
  267. else:
  268. new = {**_BOOL_WORDS, '1': True, '0': False}.get(_word(value))
  269. if new is None:
  270. raise RuntimeStoreError('invalid_params')
  271. if not isinstance(cfg.get(section), dict):
  272. cfg[section] = {}
  273. cfg[section][leaf] = new
  274. return {'value': new}
  275. def _set_approval_mode(connection, value):
  276. """``/approvals <mode>``'s own write (``hermes_cli.approval_mode``) for this profile."""
  277. from gateway.run import _profile_runtime_scope
  278. from hermes_cli.approval_mode import run_approval_mode_command
  279. with _profile_runtime_scope(Path(connection.authority.profile_id)), _WRITE_LOCK:
  280. result = run_approval_mode_command(_word(value) or None)
  281. if not result.ok:
  282. raise RuntimeStoreError('invalid_params' if _word(value) not in ('manual', 'smart', 'off')
  283. else 'storage_unavailable')
  284. return {'key': 'approvals.mode', 'value': result.mode}
  285. async def _set_command_setting(connection, ref, params):
  286. """``config.set`` for a setting a slash command owns: the same handler code, so the picker, the
  287. keybind and the typed command agree. ``reasoning`` is ``/reasoning`` (``scope=global`` =
  288. ``--global``; show/hide/reset/levels), ``yolo`` with ``scope=global`` is main's Shift+click zap
  289. (``approvals.mode`` off / manual)."""
  290. if (set(params) - {'session_id', 'profile', 'key', 'value', 'scope'} or not ref.session_id
  291. or params.get('scope', 'session') not in ('session', 'global')):
  292. raise RuntimeStoreError('invalid_params')
  293. _authorize_write(connection, ref, params)
  294. connection.authority.authorize(connection.actor, ref, 'session:control')
  295. value, scope = _word(params.get('value')), params.get('scope', 'session')
  296. if params['key'] == 'yolo':
  297. if scope != 'global':
  298. raise RuntimeStoreError('invalid_params')
  299. on = {**_BOOL_WORDS, '1': True, '0': False}.get(value)
  300. if on is None and value not in ('', 'toggle'):
  301. raise RuntimeStoreError('invalid_params')
  302. def flip():
  303. from tools.approval_context import _get_approval_mode
  304. from gateway.run import _profile_runtime_scope
  305. with _profile_runtime_scope(Path(connection.authority.profile_id)):
  306. enable = (_get_approval_mode() != 'off') if on is None else on
  307. return enable, _set_approval_mode(connection, 'off' if enable else 'manual')
  308. enable, _ = await asyncio.to_thread(flip)
  309. return {'key': 'yolo', 'value': '1' if enable else '0', 'scope': 'global'}
  310. if not value:
  311. raise RuntimeStoreError('invalid_params')
  312. from gateway.run import _profile_runtime_scope
  313. from hermes_constants import parse_reasoning_effort
  314. from gateway.slash_commands_model import _REASONING_DISPLAY_TOGGLES
  315. if value not in _REASONING_DISPLAY_TOGGLES and value != 'reset' and parse_reasoning_effort(value) is None:
  316. raise RuntimeStoreError('invalid_params')
  317. live, runner = connection.authority.sessions[ref.session_id], connection.authority.runner
  318. from gateway.session_setting_commands import commit_reasoning_command
  319. await commit_reasoning_command(connection.authority, connection.actor, ref, value, scope == 'global')
  320. def apply():
  321. with _profile_runtime_scope(Path(connection.authority.profile_id)):
  322. return runner._apply_reasoning_selection(live.route, 'cli', value, persist_global=scope == 'global')
  323. await asyncio.to_thread(apply)
  324. show = _REASONING_DISPLAY_TOGGLES.get(value)
  325. reported = ('show' if show else 'hide') if show is not None else value
  326. return {'key': 'reasoning', 'value': reported, 'scope': scope}