The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): per-session setting commands run their messaging handler for a local session
Tekniumd3cd685fb66b
diff --git a/gateway/run_config_loaders.py b/gateway/run_config_loaders.pyindex 296f1748af0..fe8796bb207 100644--- a/gateway/run_config_loaders.py+++ b/gateway/run_config_loaders.py@@ -186,6 +186,10 @@ class GatewayConfigLoadersMixin:_r_state = self._peek_session_state(resolved_session_key)if _r_state is not None and _r_state.conversation.reasoning_override is not None:return _r_state.conversation.reasoning_override+ from gateway.session_setting_commands import local_policy+ if (policy := local_policy(self, source)) is not None:+ # A local session runs its frozen (or followed) level, not the profile's.+ return policy.current_reasoning_config(self, resolved_session_key)return self._load_reasoning_config(model)def _set_session_reasoning_override(self, session_key: str, reasoning_config: Optional[dict]) -> None:@@ -208,6 +212,10 @@ class GatewayConfigLoadersMixin:_t_state = self._peek_session_state(resolved_session_key)if _t_state is not None and _t_state.conversation.service_tier_override is not _SERVICE_TIER_UNSET:return _t_state.conversation.service_tier_override+ from gateway.session_setting_commands import local_live_for_route, local_policy+ live = local_live_for_route(self, resolved_session_key)+ if live is not None and (policy := local_policy(self, live.source)) is not None:+ return policy.current_service_tier(self, resolved_session_key) # its frozen tier, not config.yaml'sreturn self._load_service_tier()def _set_session_service_tier_override(self, session_key: str, service_tier, clear: bool = False) -> None:diff --git a/gateway/run_turn_runner.py b/gateway/run_turn_runner.pyindex 5a42b9745d9..2d56f9e9c9b 100644--- a/gateway/run_turn_runner.py+++ b/gateway/run_turn_runner.py@@ -1210,7 +1210,7 @@ class TurnRunner(GatewayTurnProgressMixin, GatewaySessionAgentMixin):return _unresolved(f"⚠️ {exc}")return _unresolved(t("gateway.errors.no_credentials"))pr = runner._provider_routing- reasoning_config = (policy.current_reasoning_config(runner) if policy else+ reasoning_config = (policy.current_reasoning_config(runner, ctx.session_key) if policy elserunner._resolve_session_reasoning_config(source=ctx.source, session_key=ctx.session_key, model=model))runner._service_tier = (policy.current_service_tier(runner, ctx.session_key) if policy elserunner._resolve_session_service_tier(source=ctx.source, session_key=ctx.session_key))diff --git a/gateway/session_commands.py b/gateway/session_commands.pyindex eb357f044bf..b5b13bf3018 100644--- a/gateway/session_commands.py+++ b/gateway/session_commands.py@@ -27,6 +27,10 @@ _HANDLER_CONTROLS = frozenset({'goal', 'subgoal', 'loop', 'heartbeat', 'review',# Idle-path commands the messaging gateway answers by rewriting the turn (``_hm_cmd_<name>``,# gateway/run_inbound.py): the rewritten text is returned as the client's ``send`` directive._PROMPT_COMMANDS = frozenset({'plan', 'learn', 'init', 'initiate-setup', 'moa', 'blueprint', 'egress'})+# Per-session settings: the messaging handler itself, made session-correct for a local session+# (gateway/session_setting_commands.py). Admission-fenced like any control.+_SETTING_COMMANDS = frozenset({'reasoning', 'voice', 'approvals', 'codex-runtime', 'footer', 'busy', 'verbose',+ 'yolo', 'fast', 'personality'})# Kanban verbs that only read the board. ``create`` would also subscribe the LOCAL chat to# messaging notifications, and every other verb mutates the board.@@ -57,7 +61,8 @@ _READ_ARGUMENTS = {def command_verdict(name, arg=''):"""``read`` / ``control`` / ``refused`` for a canonical registry command on a local session."""- if name in _CONTROL_COMMANDS or name in _HANDLER_CONTROLS or name in _PROMPT_COMMANDS:+ if (name in _CONTROL_COMMANDS or name in _HANDLER_CONTROLS or name in _PROMPT_COMMANDS+ or name in _SETTING_COMMANDS):return 'control'if name in _READ_COMMANDS and _READ_ARGUMENTS.get(name, lambda _arg: True)(arg):return 'read'diff --git a/gateway/session_config.py b/gateway/session_config.pyindex 74ba630d372..83507c60408 100644--- a/gateway/session_config.py+++ b/gateway/session_config.py@@ -82,7 +82,7 @@ async def config_get(connection, ref, params):k: (policy.config() if policy else cfg).get(k)for k in ('mcp', 'mcp_servers', 'tools')},sort_keys=True).encode()).hexdigest()[:12]},- 'reasoning': lambda: _reasoning(agent, policy, cfg),+ 'reasoning': lambda: _reasoning(agent, policy, cfg, connection, ref),'fast': lambda: _fast(connection, ref, policy, agent, cfg),'skin': lambda: {'value': display.get('skin', 'default')},'theme': lambda: {'value': display.get('tui_theme', 'auto')},@@ -109,11 +109,15 @@ def _fast(connection, ref, policy, agent, cfg):return {'value': {'priority': 'fast', 'ultrafast': 'ultrafast'}.get(tier, 'normal')}-def _reasoning(agent, policy, cfg):+def _reasoning(agent, policy, cfg, connection=None, ref=None):from hermes_constants import resolve_reasoning_configvalue = getattr(agent, 'reasoning_config', None)- if not isinstance(value, dict):- value = policy.reasoning_config if policy else resolve_reasoning_config(cfg, '')+ if not isinstance(value, dict) and policy is not None:+ # The next turn's level: a typed session /reasoning, else the frozen (or followed) one.+ runner = connection.authority.runner+ value = policy.current_reasoning_config(runner, connection.authority.sessions[ref.session_id].route)+ elif not isinstance(value, dict):+ value = resolve_reasoning_config(cfg, '')effort = 'none' if value and value.get('enabled') is False else (value or {}).get('effort', 'medium')return {'value': effort, 'display': 'show' if cfg.get('display', {}).get('show_reasoning', True) else 'hide'}diff --git a/gateway/session_local.py b/gateway/session_local.pyindex 74ea1e939a7..a56d2ddc4f7 100644--- a/gateway/session_local.py+++ b/gateway/session_local.py@@ -249,7 +249,7 @@ def _lazy_model(authority, policy):return GUEST_MODEL if free_tier_route() else model-def _reasoning_fields(agent, policy, model, authority=None):+def _reasoning_fields(agent, policy, model, authority=None, override=None):"""Main's session-info effort/tier fields, from the built agent or (lazy) what the policy's next turnresolves (a following session's current profile): a resumed Desktop slice holds its reasoning pillpending until ``reasoning_effort`` arrives."""@@ -265,7 +265,7 @@ def _reasoning_fields(agent, policy, model, authority=None):effective, next_model = policy.effective(authority, secrets=False)route = effective.get('model') or {}config = (getattr(view, 'reasoning_config', None) if view is not None- else resolve_reasoning_config(effective, next_model or ''))+ else override if override is not None else resolve_reasoning_config(effective, next_model or ''))tier = (getattr(view, 'service_tier', None) if view is not Noneelse parse_service_tier((effective.get('agent') or {}).get('service_tier'))) or ''provider = getattr(view, 'provider', None) if view is not None else route.get('provider')@@ -299,7 +299,10 @@ def local_session_info(authority, ref):# Main's TUI labels a named profile's composer (``alpha ❯``) from this field.'profile_name': served_profile_name(authority.profile_id),**({'cwd': policy.cwd} if policy else {})}- info.update(_reasoning_fields(agent, policy, info['model'], authority))+ peek = getattr(authority.runner, '_peek_session_state', None)+ state = peek(live.route) if peek is not None else None+ override = state.conversation.reasoning_override if state is not None else None # a typed /reasoning+ info.update(_reasoning_fields(agent, policy, info['model'], authority, override))if policy:# The creation request the route was frozen with (secrets already extracted), so a# resuming client can tell "same flags again" from a real override attempt.diff --git a/gateway/session_mutations.py b/gateway/session_mutations.pyindex 6f944a8a1f3..f3e6aae83df 100644--- a/gateway/session_mutations.py+++ b/gateway/session_mutations.py@@ -209,6 +209,9 @@ def _project_committed(authority, ref, operation, result):# the old live one and paused; with both now equal, queued input must run, not wait for# the next submit or restart.authority._schedule(ref)+ if operation == 'reasoning':+ # The picked level is the policy's now; a typed /reasoning override must not shadow it.+ authority.runner._set_session_reasoning_override(authority.sessions[ref.session_id].route, None)if operation in {'reasoning', 'workspace'}:# Every viewer repaints its reasoning pill / workspace from the published policy, as main's# _emit_session_info did after the live change.diff --git a/gateway/session_policy.py b/gateway/session_policy.pyindex 4971445a020..032f8619af7 100644--- a/gateway/session_policy.py+++ b/gateway/session_policy.py@@ -131,8 +131,13 @@ class LocalSessionPolicy:return self.toolsetsreturn tuple(sorted(_resolve_toolsets({}, config, self.source, self.safe_mode)))- def current_reasoning_config(self, runner):- """The next turn's reasoning: the profile's current effort when following, else the frozen one."""+ def current_reasoning_config(self, runner, session_key=None):+ """The next turn's reasoning: a typed session /reasoning (the messaging handler's override), else+ the profile's current effort when following, else the frozen one."""+ peek = getattr(runner, '_peek_session_state', None)+ state = peek(session_key) if session_key and peek is not None else None+ if state is not None and state.conversation.reasoning_override is not None:+ return dict(state.conversation.reasoning_override)if not self.follows_profile:return self.reasoning_configfrom gateway.session_authorities import active_authoritydiff --git a/gateway/session_setting_commands.py b/gateway/session_setting_commands.pynew file mode 100644index 00000000000..60271d6e2b6--- /dev/null+++ b/gateway/session_setting_commands.py@@ -0,0 +1,59 @@+"""The messaging setting handlers (``/reasoning`` ``/busy`` ``/verbose`` ``/fast`` ...) on a LOCAL session.++``slash.exec`` runs the same ``_handle_<name>_command`` a messaging chat runs. A local session's+next turn reads its settings from its live session and frozen policy, not from the runner's+per-platform snapshot, so a handler that changes a setting also applies it here: one behaviour+for every surface, held by the gateway.+"""+++def local_live(runner, source):+ """The ``LiveSession`` of the local session ``source`` belongs to, else None (messaging chats)."""+ from gateway.config import Platform+ if source is None or getattr(source, 'platform', None) != Platform.LOCAL:+ return None+ from gateway.session_authorities import all_authorities+ for authority in all_authorities(runner):+ live = getattr(authority, 'sessions', {}).get(source.chat_id)+ if live is not None and live.source.platform == Platform.LOCAL:+ return live+ return None+++def local_policy(runner, source):+ """The frozen policy of a local session, else None."""+ if local_live(runner, source) is None:+ return None+ from gateway.session_policy import policy_for_source+ return policy_for_source(runner, source)+++def session_busy_mode(runner, live):+ """The busy mode a local session's next input runs under (what ``config.get busy`` reports)."""+ value = getattr(live, 'busy_input_mode', None)+ if value in ('interrupt', 'steer', 'queue'):+ return value+ from gateway.session_policy import policy_for_source+ policy = policy_for_source(runner, live.source)+ # Main's TUI defaulted to ``queue`` (``ui-tui/src/app/useConfigSync.ts`` TUI_BUSY_DEFAULT): in a+ # full-screen composer the next prompt is authored while the agent streams, and an unintended+ # interrupt loses work. Only an explicit ``display.busy_input_mode`` overrides it; every other+ # surface keeps the framework default ``interrupt``.+ fallback = 'queue' if policy is not None and getattr(policy, 'source', None) == 'tui' else 'interrupt'+ if policy is None:+ return runner._effective_busy_input_mode(live.source)+ value = (policy.config().get('display') or {}).get('busy_input_mode') or fallback+ return value if value in ('interrupt', 'steer', 'queue') else fallback+++def local_live_for_route(runner, session_key):+ """The local ``LiveSession`` whose route is ``session_key``, else None."""+ if not session_key:+ return None+ from gateway.config import Platform+ from gateway.session_authorities import all_authorities+ for authority in all_authorities(runner):+ for live in list(getattr(authority, 'sessions', {}).values()):+ if live.route == session_key and live.source.platform == Platform.LOCAL:+ return live+ return Nonediff --git a/gateway/session_tui_side.py b/gateway/session_tui_side.pyindex 49613709cc9..01114820e48 100644--- a/gateway/session_tui_side.py+++ b/gateway/session_tui_side.py@@ -117,7 +117,7 @@ async def background(connection, ref, params):max_iterations=policy.max_turns, quiet_mode=True, verbose_logging=False,enabled_toolsets=list(policy.current_toolsets(config)),disabled_toolsets=parse_config_string_list((config.get('agent') or {}).get('disabled_toolsets')) or None,- reasoning_config=policy.current_reasoning_config(runner),+ reasoning_config=policy.current_reasoning_config(runner, live.route),service_tier=policy.current_service_tier(runner, live.route),request_overrides=dict(runtime.get('request_overrides') or {}),providers_allowed=pr.get('only'), providers_ignored=pr.get('ignore'), providers_order=pr.get('order'),diff --git a/gateway/slash_commands.py b/gateway/slash_commands.pyindex 8c92c1a5480..01861ec57b0 100644--- a/gateway/slash_commands.py+++ b/gateway/slash_commands.py@@ -954,20 +954,28 @@ class GatewaySlashCommandsMixin(*current platform*, saved to ``display.platforms.<platform>.tool_progress``. Gated by``display.tool_progress_command`` (default off)."""from gateway.run import _load_gateway_config+ from gateway.session_setting_commands import local_liveconfig_path, platform_key = self._display_config_target(event)+ live = local_live(self, event.source)try:user_config = _load_gateway_config()gate_enabled = is_truthy_value(cfg_get(user_config, "display", "tool_progress_command"),default=False)except Exception:- gate_enabled = False- if not gate_enabled:+ user_config, gate_enabled = {}, False+ # The opt-in gate is for messaging chats; a local session always owned /verbose.+ if not gate_enabled and live is None:return t("gateway.verbose.not_enabled")- # Cycle mode (per-platform), reading the current effective mode via the resolver.+ # Cycle mode (per-platform), reading the current effective mode via the resolver. ``log``+ # (tool calls to a log file instead of the chat) is a messaging mode: a local client renders+ # every tool event itself.from gateway.display_config import resolve_display_setting- cycle = ["off", "new", "all", "verbose", "log"]- current = resolve_display_setting(user_config, platform_key, "tool_progress", "all")+ cycle = ["off", "new", "all", "verbose"] + ([] if live is not None else ["log"])+ current = (getattr(live, "tool_progress_mode", None) if live is not None else None) or \+ resolve_display_setting(user_config, platform_key, "tool_progress", "all")new_mode = cycle[(cycle.index(current if current in cycle else "all") + 1) % len(cycle)]+ if live is not None:+ live.tool_progress_mode = new_mode # what ``config.get verbose`` and the next tool event readdescription = t(f"gateway.verbose.mode_{new_mode}")try:_write_raw_config_leaf(config_path, ("display", "platforms", platform_key, "tool_progress"), new_mode)@@ -978,9 +986,11 @@ class GatewaySlashCommandsMixin(async def _handle_busy_command(self, event: MessageEvent) -> str | EphemeralReply:"""Handle /busy — control what happens when messaging while Hermes is working."""+ from gateway.session_setting_commands import local_live, session_busy_modearg = event.get_command_args().strip().lower()+ live = local_live(self, event.source)if not arg or arg == "status":- mode = self._effective_busy_input_mode(event.source)+ mode = session_busy_mode(self, live) if live is not None else self._effective_busy_input_mode(event.source)behavior = t(_BUSY_MODE_BEHAVIOR.get(mode, _BUSY_MODE_BEHAVIOR["interrupt"])[0])return EphemeralReply(t("gateway.busy.status", mode=mode, behavior=behavior))if arg not in _BUSY_MODE_BEHAVIOR:@@ -990,6 +1000,8 @@ class GatewaySlashCommandsMixin(from cli import save_config_valueif not save_config_value("display.busy_input_mode", arg):return EphemeralReply(t("gateway.busy.save_failed"))+ if live is not None:+ live.busy_input_mode = arg # the frozen session does not re-read config.yamlprofile_name = self._busy_profile_name_for_source(event.source)if profile_name:from gateway.run import _load_gateway_config@@ -1010,14 +1022,7 @@ class GatewaySlashCommandsMixin(from gateway.run import _load_gateway_config, _resolve_gateway_modelfrom gateway.runtime_footer import format_runtime_footer, resolve_footer_configconfig_path, platform_key = self._display_config_target(event)- arg = ""- try:- text = (getattr(event, "message", None) or "").strip()- if text.startswith("/"):- parts = text.split(None, 1)- arg = parts[1].strip().lower() if len(parts) > 1 else ""- except Exception:- arg = ""+ arg = event.get_command_args().strip().lower()try:user_config: dict = _load_gateway_config()except Exception as e:diff --git a/gateway/slash_commands_model.py b/gateway/slash_commands_model.pyindex cea2c26781e..984f0feed2f 100644--- a/gateway/slash_commands_model.py+++ b/gateway/slash_commands_model.py@@ -688,9 +688,13 @@ class GatewayModelCommandsMixin:from hermes_constants import parse_reasoning_effortvalue = (value or "").strip().lower()+ from gateway.session_setting_commands import local_live_for_route+ live = local_live_for_route(self, session_key)show = _REASONING_DISPLAY_TOGGLES.get(value)if show is not None: # per-platform display toggleself._show_reasoning = show+ if live is not None:+ live.show_reasoning = show # what this local session's viewers stream (config.get show_reasoning)self._save_gateway_config_key(f"display.platforms.{platform_key}.show_reasoning", show)key = "gateway.reasoning.display_set_on" if show else "gateway.reasoning.display_set_off"return t(key, platform=platform_key)@@ -708,7 +712,8 @@ class GatewayModelCommandsMixin:self._reasoning_config = parsedif persist_global:if self._save_gateway_config_key("agent.reasoning_effort", value):- self._set_reasoning_override(session_key, None)+ # A local session runs its frozen level, not config.yaml's: it takes the level too.+ self._set_reasoning_override(session_key, parsed if live is not None else None)return t("gateway.reasoning.set_global", effort=value)self._set_reasoning_override(session_key, parsed)return t("gateway.reasoning.set_global_save_failed", effort=value)@@ -745,6 +750,9 @@ class GatewayModelCommandsMixin:_reasoning_source = await asyncio.to_thread(self._normalize_source_for_session_key, event.source)session_key = self._session_key_for_source(_reasoning_source)self._show_reasoning = self._load_show_reasoning()+ from gateway.session_setting_commands import local_live+ if (_live := local_live(self, event.source)) is not None:+ self._show_reasoning = getattr(_live, "show_reasoning", None) is True# Effective model (session /model override wins) so per-model reasoning_overrides display._session_model = str(((getattr(self, "_session_model_overrides", {}) or {}).get(session_key) or {}).get("model") or ""@@ -809,8 +817,13 @@ class GatewayModelCommandsMixin:tier, saved_value, label_key = selectionlabel = t(label_key) if label_key else value.upper()self._service_tier = tier+ from gateway.session_setting_commands import local_live_for_routeif persist and self._save_gateway_config_key("agent.service_tier", saved_value):- self._set_session_service_tier_override(session_key, None, clear=True) # global wins+ if local_live_for_route(self, session_key) is not None:+ # A local session runs its frozen tier, not config.yaml's: it takes the tier too.+ self._set_session_service_tier_override(session_key, tier)+ else:+ self._set_session_service_tier_override(session_key, None, clear=True) # global winsself._evict_cached_agent(session_key)return t("gateway.fast.saved", label=label)# Session override — also the fallback after a failed config write (as /reasoning --global).diff --git a/scripts/gen_gateway_command_parity.py b/scripts/gen_gateway_command_parity.pyindex c8317829387..5c58d43f6e5 100755--- a/scripts/gen_gateway_command_parity.py+++ b/scripts/gen_gateway_command_parity.py@@ -20,8 +20,8 @@ from pathlib import PathROOT = Path(__file__).resolve().parent.parentOUT = ROOT / "website" / "docs" / "developer-guide" / "gateway-command-parity.md"-# Per-session settings that write config.yaml / messaging-only state through their gateway handler:-# enabling them as-is would print success and change nothing for a local session.+# Per-session settings: slash.exec runs their messaging handler, which applies a setting to the local+# session it came from (gateway/session_setting_commands.py; tests/gateway/test_session_setting_commands.py).TOGGLES = frozenset({"fast", "reasoning", "yolo", "footer", "personality", "busy", "voice", "approvals","verbose", "codex-runtime"})# Why a command with a gateway handler is NOT a read for a local session (probe: the real handler@@ -74,7 +74,7 @@ def port_note(cmd):def _base_note(cmd):if cmd.name in TOGGLES:- return "port: per-session setting"+ return "per-session setting (gateway handler)"if cmd.name in NOT_A_LOCAL_READ:return NOT_A_LOCAL_READ[cmd.name]if cmd.gateway_only:@@ -220,9 +220,9 @@ the rest (`unsupported_command`). The classic CLI prints a refusal as**Gateway (`slash.exec`)**: `read` = the real handler runs for a local session (proved by`tests/gateway/test_session_read_commands.py`); `control` = admission-fenced write; `refused`.-**Notes**: `port: per-session setting` toggles write config.yaml or messaging-only state-through their gateway handler, so they stay refused until ported to the session's frozen-policy; `client-local (cli_only)` commands are terminal/UI features of a client.+**Notes**: `per-session setting (gateway handler)` = the messaging handler runs and applies the+setting to this local session (its next turn and `config.get`), saving config.yaml only where the+handler does; `client-local (cli_only)` commands are terminal/UI features of a client."""diff --git a/tests/gateway/test_session_read_commands.py b/tests/gateway/test_session_read_commands.pyindex 141ac94957f..97eb274b552 100644--- a/tests/gateway/test_session_read_commands.py+++ b/tests/gateway/test_session_read_commands.py@@ -54,7 +54,7 @@ def test_local_session_reads_report_this_session_and_refuse_their_write_forms(tmawait asyncio.sleep(.1)for command in ('usage', 'insights', 'profile', 'topup', 'diff', 'memory', 'kanban list','suggestions', 'bundles', 'usage reset', 'memory approval on', 'kanban create x',- 'suggestions catalog', 'agents', 'sessions', 'platform', 'fast'):+ 'suggestions catalog', 'agents', 'sessions', 'platform'):try:reply = await rpc(ws, 'slash.exec', session_id=sid, command=command)except TimeoutError:@@ -84,9 +84,10 @@ def test_local_session_reads_report_this_session_and_refuse_their_write_forms(tmassert out['kanban list'] == '(no matching tasks)', out['kanban list']assert 'No suggested automations' in out['suggestions'], out['suggestions']assert str(home / 'skill-bundles') in out['bundles'], out['bundles']- # Write forms, messaging-model state, gateway-wide views and toggles stay refused.+ # Write forms, messaging-model state and gateway-wide views stay refused (the per-session settings+ # run: tests/gateway/test_session_setting_commands.py).for command in ('usage reset', 'memory approval on', 'kanban create x', 'suggestions catalog',- 'agents', 'sessions', 'platform', 'fast'):+ 'agents', 'sessions', 'platform'):assert out[command] == 'unsupported_command', (command, out[command])assert (home / 'config.yaml').read_text() == configassert not os.path.exists(home / 'cron' / 'jobs.json') or 'catalog' not in (home / 'cron' / 'jobs.json').read_text()diff --git a/tests/gateway/test_session_setting_commands.py b/tests/gateway/test_session_setting_commands.pynew file mode 100644index 00000000000..96f054a207a--- /dev/null+++ b/tests/gateway/test_session_setting_commands.py@@ -0,0 +1,153 @@+"""Per-session setting commands run their real gateway handler for a LOCAL session.++``slash.exec`` dispatches the same ``_handle_<name>_command`` a messaging chat runs; for a local+session the setting lands where main's CLI/TUI put it (the session, or the profile's config.yaml+exactly where main wrote it), and ``config.get`` reads it back.+"""+import asyncio+import json+from http.server import ThreadingHTTPServer+from pathlib import Path+import signal+import threading+import time++import pytest++from tests.gateway.fixtures.local_recovery_probe import Model, child_env, daemon, rpc, websocket+++def _run(tmp_path, steps, extra_config=None):+ """``steps``: list of (label, method, params) run in order on one local session; returns+ ({label: result-or-error}, home)."""+ root = Path(__file__).resolve().parents[2]+ home, user, work = tmp_path / 'state', tmp_path / 'user', tmp_path / 'work'+ home.mkdir(mode=0o700)+ user.mkdir()+ work.mkdir()+ peer = ThreadingHTTPServer(('127.0.0.1', 0), Model)+ peer.requests = []+ peer.blocked, peer.release = threading.Event(), threading.Event()+ thread = threading.Thread(target=peer.serve_forever, daemon=True)+ thread.start()+ url = f'http://127.0.0.1:{peer.server_port}/v1'+ config = {'gateway': {'multiplex_profiles': False},+ 'model': {'provider': 'custom', 'default': 'settings-model', 'base_url': url},+ 'auxiliary': {'title_generation': {'enabled': False}}, **(extra_config or {})}+ (home / 'config.yaml').write_text(json.dumps(config))+ env = child_env()+ env.update(HOME=str(user), USERPROFILE=str(user), HERMES_HOME=str(home), PYTHONPATH=str(root),+ OPENAI_API_KEY='loopback-only', OPENAI_BASE_URL=url, PYTHONUNBUFFERED='1')+ out = {}++ async def probe(desc):+ async with websocket(home, desc) as ws:+ created = await rpc(ws, 'session.create', request_id='settings', source='cli', toolsets=[], cwd=str(work))+ sid = created['result']['session_id']+ out['sid'] = sid+ for label, method, params in steps:+ if method == 'turn':+ await rpc(ws, 'prompt.submit', session_id=sid, input_id=label, text=params['text'])+ deadline = time.monotonic() + 45+ while True:+ snap = (await rpc(ws, 'session.resume', session_id=sid))['result']+ if not snap['running'] and not snap['pending'] and (+ 'RECOVERY_ACK_' + params['text']) in json.dumps(snap['messages']):+ break+ assert time.monotonic() < deadline, ('turn never settled', snap)+ await asyncio.sleep(.1)+ out[label] = [r for r in peer.requests if params['text'] in json.dumps(r.get('messages'))][-1]+ continue+ try:+ reply = await rpc(ws, method, session_id=sid, **params)+ except TimeoutError:+ raise AssertionError(f'{method} {params!r} did not answer within the rpc bound') from None+ result = reply.get('result')+ out[label] = ((result.get('output') if method == 'slash.exec' else result)+ if result is not None else 'ERR:' + reply.get('error', {}).get('message', ''))+ try:+ with daemon(root, home, env, barrier=False) as (proc, desc):+ asyncio.run(probe(desc))+ proc.send_signal(signal.SIGINT)+ proc.wait(timeout=20)+ finally:+ peer.shutdown()+ peer.server_close()+ thread.join(timeout=5)+ return out, home, config+++def _exec(label, command):+ return (label, 'slash.exec', {'command': command})+++def _turn(label, text):+ return (label, 'turn', {'text': text})+++def _get(label, key):+ return (label, 'config.get', {'key': key})+++def _yaml(home):+ from hermes_yaml import safe_load+ return safe_load((home / 'config.yaml').read_text())++[email protected]("linux")+def test_local_session_settings_run_the_messaging_handlers_and_read_back_through_config_get(tmp_path):+ steps = [+ _exec('reasoning', 'reasoning'), _exec('reasoning high', 'reasoning high'), _get('get high', 'reasoning'),+ _exec('reasoning show', 'reasoning show'), _get('get show', 'show_reasoning'),+ _exec('reasoning status', 'reasoning'),+ _turn('turn high', 'TURN_HIGH'),+ _exec('reasoning --global low', 'reasoning --global low'), _get('get low', 'reasoning'),+ _turn('turn low', 'TURN_LOW'),+ _exec('reasoning reset', 'reasoning reset'), _get('get reset', 'reasoning'),+ _exec('busy queue', 'busy queue'), _get('get busy', 'busy'), _exec('busy', 'busy'),+ _get('verbose before', 'verbose'), _exec('verbose', 'verbose'), _get('get verbose', 'verbose'),+ _exec('verbose 2', 'verbose'), _get('get verbose 2', 'verbose'),+ _exec('yolo', 'yolo'), _get('get yolo', 'yolo'), _exec('yolo off', 'yolo'), _get('get yolo off', 'yolo'),+ _exec('footer status', 'footer status'), _exec('footer on', 'footer on'), _exec('footer status 2', 'footer status'),+ _exec('voice on', 'voice on'), _exec('voice status', 'voice status'), _exec('voice off', 'voice off'),+ _exec('approvals smart', 'approvals smart'), _get('get approvals', 'approvals.mode'),+ _exec('personality', 'personality'), _exec('personality concise', 'personality concise'),+ _exec('codex-runtime', 'codex-runtime'), _exec('fast', 'fast'),+ ]+ out, home, config = _run(tmp_path, steps)+ saved = _yaml(home)+ # /reasoning: a session level is this session's next turn, config.yaml untouched; --global saves+ # AND applies to this session (which never re-reads config.yaml); reset falls back to its policy.+ assert 'medium' in out['reasoning'] and 'Scope' in out['reasoning'], out['reasoning']+ assert 'session only' in out['reasoning high'] and out['get high']['value'] == 'high', out+ assert out['get show']['value'] == '1' and 'Display:** on' in out['reasoning status'], out+ assert 'high' in out['reasoning status'] and 'session override' in out['reasoning status'], out['reasoning status']+ # ...and the next turn's request carries it (the frozen session never re-reads config.yaml).+ assert out['turn high'].get('reasoning_effort') == 'high', out['turn high']+ assert out['turn low'].get('reasoning_effort') == 'low', out['turn low']+ assert 'saved to config' in out['reasoning --global low'] and out['get low']['value'] == 'low', out+ assert saved['agent']['reasoning_effort'] == 'low'+ assert out['get reset']['value'] == 'medium', out['get reset']+ # /busy: saved like the messaging handler and applied to this session.+ assert '`queue`' in out['busy queue'] and out['get busy']['value'] == 'queue', out+ assert '`queue`' in out['busy'] and saved['display']['busy_input_mode'] == 'queue', out['busy']+ # /verbose: no messaging opt-in gate; cycles this session's mode (all -> verbose -> off).+ assert out['verbose before']['value'] == 'all'+ assert 'VERBOSE' in out['verbose'] and out['get verbose']['value'] == 'verbose', out+ assert out['get verbose 2']['value'] == 'off', out+ # /yolo: this session's bypass, read back by config.get.+ assert 'ON' in out['yolo'] and out['get yolo']['value'] == '1', out+ assert 'OFF' in out['yolo off'] and out['get yolo off']['value'] == '0', out+ # /footer: `status` reports without toggling (the handler parsed its argument from a missing field).+ assert 'OFF' in out['footer status'] and 'ON' in out['footer on'] and 'ON' in out['footer status 2'], out+ assert saved['display']['runtime_footer']['enabled'] is True+ # /voice: the LOCAL chat's voice state (playback stays in the client).+ assert 'On' in out['voice status'] and out['voice off'], out+ # /approvals and /personality: profile settings, saved to config.yaml as on every surface.+ assert 'smart' in out['approvals smart'] and out['get approvals']['value'] == 'smart', out+ assert saved['approvals']['mode'] == 'smart' and saved['display']['personality'] == 'concise'+ assert 'concise' in out['personality'] and 'concise' in out['personality concise'], out+ assert 'openai_runtime' in out['codex-runtime'], out['codex-runtime']+ # /fast on a custom endpoint: the handler's own refusal, not unsupported_command.+ assert '/fast' in out['fast'] and not out['fast'].startswith('ERR:'), out['fast']+ assert saved['model'] == config['model']diff --git a/tests/hermes_cli/test_gateway_command_parity.py b/tests/hermes_cli/test_gateway_command_parity.pyindex 30dd65a5a68..cb4af27ba5d 100644--- a/tests/hermes_cli/test_gateway_command_parity.py+++ b/tests/hermes_cli/test_gateway_command_parity.py@@ -24,7 +24,8 @@ def test_committed_parity_table_matches_every_client_verdict():from hermes_cli.commands import COMMAND_REGISTRYrows = [line for line in rendered.splitlines() if line.startswith("| `/")]assert len(rows) == len(COMMAND_REGISTRY)- # Toggles stay refused on the gateway this round (they would print success and do nothing).+ # Per-session settings run their gateway handler for a local session (an admission-fenced control;+ # tests/gateway/test_session_setting_commands.py proves each lands on the session).for name in gen.TOGGLES:row = next(line for line in rows if line.startswith(f"| `/{name}`"))- assert "| refused |" in row and "port: per-session setting" in row, row+ assert row.split(" | ")[1] == "control" and "per-session setting (gateway handler)" in row, rowdiff --git a/website/docs/developer-guide/gateway-command-parity.md b/website/docs/developer-guide/gateway-command-parity.mdindex a2d1911c0e9..c0d0487ca89 100644--- a/website/docs/developer-guide/gateway-command-parity.md+++ b/website/docs/developer-guide/gateway-command-parity.md@@ -17,16 +17,16 @@ the rest (`unsupported_command`). The classic CLI prints a refusal as**Gateway (`slash.exec`)**: `read` = the real handler runs for a local session (proved by`tests/gateway/test_session_read_commands.py`); `control` = admission-fenced write; `refused`.-**Notes**: `port: per-session setting` toggles write config.yaml or messaging-only state-through their gateway handler, so they stay refused until ported to the session's frozen-policy; `client-local (cli_only)` commands are terminal/UI features of a client.+**Notes**: `per-session setting (gateway handler)` = the messaging handler runs and applies the+setting to this local session (its next turn and `config.get`), saving config.yaml only where the+handler does; `client-local (cli_only)` commands are terminal/UI features of a client.-103 registry commands: 17 control, 15 read, 71 refused.+103 registry commands: 27 control, 15 read, 61 refused.| Command | Gateway (`slash.exec`) | Classic CLI | Ink | Desktop | ACP | Notes ||---|---|---|---|---|---|---|| `/agents` (/tasks) | refused | refused: not available yet | delegation.pause | slash.exec: refused | refused | gateway-wide: lists every chat's running agents and the process's async jobs |-| `/approvals` | refused | refused: not available yet | slash.exec: refused | slash.exec: refused | refused | port: per-session setting |+| `/approvals` | control | slash.exec | slash.exec | slash.exec | refused | per-session setting (gateway handler) || `/approve` | refused | approval.respond (prompt id) | slash.exec: refused | unavailable: messaging | refused | messaging-only || `/battery` | refused | refused: not available yet | sidecar: system.battery (preference not saved) | slash.exec: refused | refused | client-local (cli_only) || `/bg` | refused | refused: not available yet | prompt.background | action: background | refused | |@@ -35,9 +35,9 @@ policy; `client-local (cli_only)` commands are terminal/UI features of a client.| `/browser` | refused | refused: not available yet | sidecar: browser.manage | action: browser | refused | client-local (cli_only) || `/btw` | refused | refused: not available yet | prompt.btw | action: btw | refused | || `/bundles` | read | slash.exec | slash.exec | slash.exec | refused | |-| `/busy` | refused | refused: not available yet | canonical route | unavailable: terminal | refused | port: per-session setting |+| `/busy` | control | slash.exec | canonical route | unavailable: terminal | refused | per-session setting (gateway handler) || `/clear` | refused | session.create | local | action: new | refused | client-local (cli_only) |-| `/codex-runtime` (/codex_runtime) | refused | refused: not available yet | slash.exec: refused | slash.exec: refused | refused | port: per-session setting |+| `/codex-runtime` (/codex_runtime) | control | slash.exec | slash.exec | slash.exec | refused | per-session setting (gateway handler) || `/commands` | read | slash.exec | slash.exec | action: help | refused | messaging-only || `/compress` (/compact) | refused | session.mutate compress | canonical route | action: compress | session.mutate compress | || `/config` | refused | refused: not available yet | slash.exec: refused | unavailable: terminal | refused | client-local (cli_only) |@@ -50,9 +50,9 @@ policy; `client-local (cli_only)` commands are terminal/UI features of a client.| `/diff` | read | slash.exec | slash.exec | slash.exec | refused | || `/egress` | control | slash.exec | slash.exec | slash.exec | refused | || `/export` | refused | refused: not available yet | slash.exec: refused | slash.exec: refused | refused | client-local (cli_only) |-| `/fast` | refused | refused: not available yet | config.get, config.set | unavailable: advanced | refused | port: per-session setting |+| `/fast` | control | slash.exec | config.get, config.set | unavailable: advanced | refused | per-session setting (gateway handler) || `/focus` | refused | refused: not available yet | local (preference not saved) | slash.exec: refused | refused | client-local (cli_only) |-| `/footer` | refused | refused: not available yet | slash.exec: refused | unavailable: terminal | refused | port: per-session setting |+| `/footer` | control | slash.exec | slash.exec | unavailable: terminal | refused | per-session setting (gateway handler) || `/goal` | control | slash.exec | slash.exec | slash.exec | refused | || `/handoff` | refused | refused: not available yet | slash.exec: refused | action: handoff | refused | client-local (cli_only) || `/hatch` (/generate-pet) | refused | refused: not available yet | slash.exec: refused | action: hatch | refused | client-local (cli_only) |@@ -77,7 +77,7 @@ policy; `client-local (cli_only)` commands are terminal/UI features of a client.| `/palette` | refused | refused: not available yet | slash.exec: refused | slash.exec: refused | refused | client-local (cli_only) || `/paste` | refused | refused: not available yet | local | unavailable: terminal | refused | client-local (cli_only) || `/pause` | refused | refused: not available yet | slash.exec: refused | slash.exec: refused | refused | messaging-only |-| `/personality` | refused | refused: not available yet | config.set | slash.exec: refused | refused | port: per-session setting |+| `/personality` | control | slash.exec | config.set | slash.exec | refused | per-session setting (gateway handler) || `/pet` | refused | refused: not available yet | slash.exec | action: pet | refused | client-local (cli_only) || `/plan` | control | slash.exec | slash.exec | slash.exec | refused | || `/platform` | refused | refused: not available yet | slash.exec: refused | slash.exec: refused | refused | messaging adapters; `pause`/`resume` mutate them |@@ -87,7 +87,7 @@ policy; `client-local (cli_only)` commands are terminal/UI features of a client.| `/prompt` (/compose) | refused | refused: not available yet | local | slash.exec: refused | refused | client-local (cli_only) || `/queue` (/q) | refused | refused: not available yet | local | slash.exec: refused | refused | || `/quit` (/exit) | refused | detach | local | unavailable: terminal | refused | client-local (cli_only) |-| `/reasoning` | refused | refused: not available yet | config.get; change refused: not available yet | action: reasoning | refused | port: per-session setting |+| `/reasoning` | control | slash.exec | config.get; change refused: not available yet | action: reasoning | refused | per-session setting (gateway handler) || `/redraw` | refused | refused: not available yet | local | unavailable: terminal | refused | client-local (cli_only) || `/refine` | control | slash.exec | slash.exec | slash.exec | refused | || `/reload` | refused | refused: not available yet | canonical route | unavailable: terminal | refused | client-local (cli_only) |@@ -121,10 +121,10 @@ policy; `client-local (cli_only)` commands are terminal/UI features of a client.| `/undo` | refused | session.mutate rewind | canonical route | slash.exec: refused | refused | || `/update` | refused | refused: not available yet | local | unavailable: terminal | refused | || `/usage` | read (bare only (`reset` refused)) | slash.exec + last-turn receipt | canonical route | slash.exec | refused | |-| `/verbose` | refused | refused: not available yet | config.set | unavailable: terminal | refused | port: per-session setting |+| `/verbose` | control | slash.exec | config.set | unavailable: terminal | refused | per-session setting (gateway handler) || `/version` (/v) | read | slash.exec | slash.exec | slash.exec | refused | |-| `/voice` | refused | refused: not available yet | sidecar: voice.toggle; `tts` refused | unavailable: composer-voice | refused | port: per-session setting |+| `/voice` | control | slash.exec | sidecar: voice.toggle; `tts` refused | unavailable: composer-voice | refused | per-session setting (gateway handler) || `/wake` | refused | refused: not available yet | local | action: wake | refused | client-local (cli_only) || `/whoami` | read | slash.exec | slash.exec | slash.exec | refused | || `/worktree` | refused | refused: not available yet | slash.exec: refused | slash.exec: refused | refused | client-local (cli_only) |-| `/yolo` | refused | config.set yolo | config.set | action: yolo | refused | port: per-session setting |+| `/yolo` | control | config.set yolo | config.set | action: yolo | refused | per-session setting (gateway handler) |