Skip to content

The agent that grows with you

fix(gateway): route the Ink and Desktop requests the shared gateway refused

unsupportedpastels84662a1c2d74
diff --git a/gateway/run_inbound_hooks.py b/gateway/run_inbound_hooks.py
index bccc2b5cd91..22d81e326fb 100644
--- a/gateway/run_inbound_hooks.py
+++ b/gateway/run_inbound_hooks.py
@@ -8,6 +8,7 @@ plugin-registered slash commands. Bound onto ``GatewayRunner`` through ``Gateway
from __future__ import annotations
import asyncio
+import contextlib
import dataclasses
import logging
from typing import Optional, Tuple
@@ -138,14 +139,16 @@ class GatewayInboundHooksMixin:
return False, None, event.get_command()
return False, None, None
- async def _hm_run_exec_quick_command(self, command: str, exec_cmd: str) -> str:
- """Run a ``type: exec`` quick command in the gateway process (30 s cap, sanitized env β€” the
- gateway process has every API key in os.environ; output is redacted too)."""
+ async def _hm_run_exec_quick_command(self, command: str, exec_cmd: str, cwd: Optional[str] = None) -> str:
+ """Run a ``type: exec`` quick command as a host shell of the gateway process: sanitized env
+ (the gateway process has every API key in os.environ), redacted output, killed after 30 s.
+ ``cwd`` is a local session's folder; None keeps the gateway's own (messaging)."""
+ proc = None
try:
from tools.environments.local import build_subprocess_env
proc = await asyncio.create_subprocess_shell(
exec_cmd, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE,
- env=build_subprocess_env(),
+ env=build_subprocess_env(), cwd=cwd,
)
stdout, stderr = await asyncio.wait_for(proc.communicate(), timeout=30)
output = (stdout or stderr).decode().strip()
@@ -154,6 +157,11 @@ class GatewayInboundHooksMixin:
output = redact_sensitive_text(output)
return output or t("gateway.quick_command.no_output")
except TimeoutError:
+ if proc is not None and proc.returncode is None:
+ with contextlib.suppress(ProcessLookupError):
+ proc.kill()
+ with contextlib.suppress(TimeoutError):
+ await asyncio.wait_for(proc.wait(), timeout=5)
return t("gateway.quick_command.timed_out")
except Exception as e: # health: allow BLE001 -- moved unchanged from run_inbound.py (main has the same handler): an operator quick command's failure is its reply
return t("gateway.quick_command.error", error=e)
diff --git a/gateway/session_commands.py b/gateway/session_commands.py
index 8954d279b23..0aa09127138 100644
--- a/gateway/session_commands.py
+++ b/gateway/session_commands.py
@@ -5,6 +5,7 @@ Executing those here would double-submit and bypass their retry identity.
"""
import asyncio
from contextlib import contextmanager
+import os
from pathlib import Path
import shlex
@@ -106,9 +107,10 @@ def _resolve_alias(name, arg):
raise RuntimeStoreError('invalid_params')
seen.add(name)
entry = quick[name]
- # Shell/plugin execution has no canonical approval or retry contract here.
- if not isinstance(entry, dict) or entry.get('type') != 'alias':
+ if not isinstance(entry, dict) or entry.get('type') not in {'alias', 'exec'}:
raise RuntimeStoreError('unsupported_command')
+ if entry['type'] == 'exec':
+ return name, arg
target = entry.get('target')
if not isinstance(target, str) or not target.strip():
raise RuntimeStoreError('invalid_params')
@@ -118,6 +120,45 @@ def _resolve_alias(name, arg):
return name, arg
+def _runner_command(name):
+ """``('exec', shell)`` for a ``type: exec`` quick command, ``('plugin', None)`` for a plugin
+ slash command, else None (read in the owning profile's scope)."""
+ from gateway.run import _load_gateway_config
+ from hermes_cli.plugins import get_plugin_command_handler
+ entry = (_load_gateway_config().get('quick_commands') or {}).get(name)
+ if isinstance(entry, dict) and entry.get('type') == 'exec':
+ return 'exec', str(entry.get('command') or '')
+ return ('plugin', None) if get_plugin_command_handler(name.replace('_', '-')) else None
+
+
+async def _run_runner_command(runner, live, name, arg, kind, shell):
+ """The messaging gateway's own quick-command / plugin-command dispatch for this session
+ (``run_inbound_hooks``): the operator's slash access policy, the 30 s sanitized-env exec with
+ redacted output, the plugin handler under this session's env scope."""
+ from agent.i18n import t
+ from gateway.platforms.base import MessageEvent
+ if kind == 'exec':
+ if not shell:
+ return t('gateway.quick_command.no_command', command=name)
+ refused = runner._check_slash_access(live.source, name)
+ if refused:
+ return refused
+ from gateway.session_policy import policy_for_source
+ policy = policy_for_source(runner, live.source)
+ cwd = getattr(policy, 'cwd', None) or None
+ if cwd is None or not await asyncio.to_thread(os.path.isdir, cwd):
+ # Never fall back to the gateway's own folder: a relative command would act there.
+ raise RuntimeStoreError('cwd_unavailable')
+ return await runner._hm_run_exec_quick_command(name, shell, cwd=cwd)
+ if runner._hm_quick_commands().get(name) is not None:
+ # The runner's quick commands come first in its dispatch; under multiplex they are the launch
+ # profile's, which must never answer for this session's profile.
+ raise RuntimeStoreError('unsupported_command')
+ event = MessageEvent(text='/' + name + (' ' + arg if arg else ''), source=live.source)
+ _handled, output, _command = await runner._hm_dispatch_quick_and_plugin_commands(event, live.source, name)
+ return output
+
+
def _skill_directive(name, arg, route):
from agent.skill_commands import (
build_skill_invocation_message, describe_skill_invocation, get_skill_commands,
@@ -190,9 +231,15 @@ async def execute_command(connection, ref, params, *, dispatch=False):
verdict = command_verdict(canonical, arg) if definition else None
if definition is not None and (tui := await _tui_read(authority, actor, ref, canonical, arg)) is not None:
return tui
+ runner_command = None
+ if definition is None:
+ def lookup():
+ with _profile_runtime_scope(home):
+ return _runner_command(name)
+ runner_command = await asyncio.to_thread(lookup)
capability = ('session:read' if verdict == 'read' else
'session:approve' if canonical in _APPROVAL_COMMANDS else
- 'session:control' if definition else 'session:submit')
+ 'session:control' if definition or runner_command else 'session:submit')
authority.authorize(actor, ref, capability)
if verdict == 'refused':
raise RuntimeStoreError('unsupported_command')
@@ -202,6 +249,10 @@ async def execute_command(connection, ref, params, *, dispatch=False):
raise RuntimeStoreError('permission_denied')
if capability != 'session:read':
authority._require_admission_open()
+ if runner_command is not None:
+ with _profile_runtime_scope(home), _session_workspace(authority.runner, live.source):
+ output = await _run_runner_command(authority.runner, live, name, arg, *runner_command)
+ return {'type': 'exec', 'output': _text(output)}
if definition is None:
def build():
with _profile_runtime_scope(home):
diff --git a/gateway/session_control_actions.py b/gateway/session_control_actions.py
new file mode 100644
index 00000000000..8723c9d69fd
--- /dev/null
+++ b/gateway/session_control_actions.py
@@ -0,0 +1,84 @@
+"""Desktop's goal / loop / heartbeat / subgoal card buttons (``session.control``) on the owner.
+
+``session.control.read`` was served, so the cards rendered as controllable, while every button
+answered -32601. Each action is the typed slash command the button stands for, run through
+``execute_command`` (the gateway's own /goal /loop /heartbeat /subgoal handlers, with their
+capability, local-source, admission and busy rules), answered with the owner's control snapshot.
+"""
+from hermes_state_runtime import RuntimeStoreError
+
+_ACTION_COMMANDS = {
+ 'goal.pause': ('goal', 'pause'), 'goal.resume': ('goal', 'resume'),
+ 'goal.clear': ('goal', 'clear'), 'goal.unwait': ('goal', 'unwait'),
+ 'loop.pause': ('loop', 'pause'), 'loop.resume': ('loop', 'resume'), 'loop.stop': ('loop', 'stop'),
+ 'heartbeat.pause': ('heartbeat', 'pause'), 'heartbeat.resume': ('heartbeat', 'resume'),
+ 'heartbeat.clear': ('heartbeat', 'clear'), 'subgoal.clear': ('subgoal', 'clear'),
+}
+_ENVELOPE = ('type', 'output', 'notice', 'message', 'display')
+
+
+def _command(action, args):
+ """``(name, arg)`` of the slash command for *action*, or ``('subgoal', None)`` for an add, whose
+ free text must not be parsed as a /subgoal verb ("clear the cache" is a criterion, not a clear)."""
+ if not isinstance(args, dict) or set(args) - {'text', 'index'}:
+ raise RuntimeStoreError('invalid_params')
+ if action in _ACTION_COMMANDS:
+ return _ACTION_COMMANDS[action]
+ if action == 'subgoal.remove':
+ index = args.get('index')
+ if type(index) is not int or index < 1:
+ raise RuntimeStoreError('invalid_params')
+ return 'subgoal', f'remove {index}'
+ if action == 'subgoal.add':
+ if not isinstance(args.get('text'), str) or not args['text'].strip():
+ raise RuntimeStoreError('invalid_params')
+ return 'subgoal', None
+ raise RuntimeStoreError('invalid_params')
+
+
+async def _add_subgoal(connection, ref, params, text):
+ """``/subgoal <text>``'s add branch (``slash_commands_goals``) on the session's goal manager."""
+ from pathlib import Path
+ from agent.i18n import t
+ from gateway.platforms.base import MessageEvent
+ from gateway.run import _profile_runtime_scope
+ from gateway.session_busy_controls import authorize
+ from gateway.session_local import authorize_local_source
+ from gateway.slash_commands_goals import _mgr_call
+ authority = connection.authority
+ authorize(connection, ref, params, 'session:control')
+ live = authority.sessions[ref.session_id]
+ if authorize_local_source(authority.runner, live.source) is not True:
+ raise RuntimeStoreError('permission_denied')
+ authority._require_admission_open()
+ with _profile_runtime_scope(Path(authority.profile_id)):
+ mgr, _entry = await authority.runner._get_goal_manager_for_event(
+ MessageEvent(text='/subgoal', source=live.source))
+ if mgr is None:
+ return {'type': 'exec', 'output': t('gateway.goal.unavailable')}
+ if not mgr.has_goal():
+ return {'type': 'exec', 'output': t('gateway.subgoal.no_goal')}
+ added, err = _mgr_call('/subgoal', mgr.add_subgoal, text)
+ index = len(mgr.state.subgoals) if mgr.state else 0
+ return {'type': 'exec', 'output': err or t('gateway.subgoal.added', index=index, text=added)}
+
+
+async def control(connection, ref, params):
+ if set(params) - {'session_id', 'profile', 'action', 'args'} or not ref.session_id:
+ raise RuntimeStoreError('invalid_params')
+ action = params.get('action')
+ if not isinstance(action, str):
+ raise RuntimeStoreError('invalid_params')
+ args = {} if params.get('args') is None else params['args']
+ name, arg = _command(action.strip(), args)
+ if ref.session_id not in connection.authority.sessions:
+ raise RuntimeStoreError('not_found')
+ scope = {key: params[key] for key in ('session_id', 'profile') if key in params}
+ if arg is None:
+ result = await _add_subgoal(connection, ref, scope, args['text'].strip())
+ else:
+ from gateway.session_commands import execute_command
+ result = await execute_command(connection, ref, {**scope, 'name': name, 'arg': arg}, dispatch=True)
+ from gateway.session_ancillary import read
+ snapshot = await read(connection, ref, scope, kind='control')
+ return {**snapshot, 'dispatch': {key: result.get(key) for key in _ENVELOPE}}
diff --git a/gateway/session_controls.py b/gateway/session_controls.py
index 46bd859e8e3..5e10995311a 100644
--- a/gateway/session_controls.py
+++ b/gateway/session_controls.py
@@ -130,6 +130,10 @@ class AuthorityConnection:
handlers['session.active_list'] = partial(active_list, self)
from gateway.session_viewer_automation import automation
handlers['session.automation'] = partial(automation, self)
+ from gateway.session_reactions import react
+ handlers['message.react'] = partial(react, self)
+ from gateway.session_control_actions import control
+ handlers['session.control'] = partial(control, self)
return handlers
async def dispatch(self, request):
diff --git a/gateway/session_reactions.py b/gateway/session_reactions.py
new file mode 100644
index 00000000000..a36e7ee4755
--- /dev/null
+++ b/gateway/session_reactions.py
@@ -0,0 +1,50 @@
+"""Desktop's message reactions (``message.react``) on the owner's transcript.
+
+The sidecar handler looked the session up in its own table, which never holds an authority
+session, and the ``message.*`` namespace never falls back to it, so every reaction was rolled back
+as "Could not react". The write is the same ``SessionDB.set_message_reaction`` (Tapback semantics,
+rows of the session's visible resume lineage only), on the conversation's current physical session.
+"""
+from functools import partial
+
+from gateway.session_busy_controls import authorize
+from hermes_state_runtime import RuntimeStoreError
+
+_FIELDS = frozenset({'session_id', 'profile', 'row_id', 'newest_role', 'emoji', 'author'})
+
+
+def _parse(params):
+ row_id, newest_role, emoji = params.get('row_id'), params.get('newest_role'), params.get('emoji')
+ author = params.get('author') or 'user'
+ if (set(params) - _FIELDS or (row_id is not None and type(row_id) is not int)
+ or (row_id is None and newest_role not in {'user', 'assistant'})
+ or (emoji is not None and (not isinstance(emoji, str) or not emoji.strip()))
+ or author not in {'user', 'agent'}):
+ raise RuntimeStoreError('invalid_params')
+ return row_id, newest_role, emoji.strip() if emoji else None, author
+
+
+def _write(db, target, row_id, newest_role, emoji, author):
+ if row_id is None:
+ row_id = db.latest_message_row_id(target, role=newest_role)
+ if row_id is None:
+ return None, None
+ return row_id, db.set_message_reaction(target, row_id, emoji, author=author)
+
+
+async def react(connection, ref, params):
+ row_id, newest_role, emoji, author = _parse(params)
+ authority = connection.authority
+ if not ref.session_id or ref.session_id not in authority.sessions:
+ raise RuntimeStoreError('not_found')
+ authorize(connection, ref, params, 'session:submit')
+ from gateway.session_ancillary import physical_target
+ from gateway.session_runtime_workers import tracked_write
+ # A reset or compression moves the conversation's rows onto a new physical session; the
+ # reaction lineage check runs from that tip, as the sidecar's submit-row target did.
+ target = physical_target(authority, ref)
+ row_id, reactions = await tracked_write(authority, partial(
+ _write, authority.db, target, row_id, newest_role, emoji, author))
+ if reactions is None:
+ raise RuntimeStoreError('not_found')
+ return {'row_id': row_id, 'reactions': reactions}
diff --git a/tests/gateway/fixtures/tui_desktop_routes_peer.py b/tests/gateway/fixtures/tui_desktop_routes_peer.py
new file mode 100644
index 00000000000..082535a55dd
--- /dev/null
+++ b/tests/gateway/fixtures/tui_desktop_routes_peer.py
@@ -0,0 +1,191 @@
+"""Authenticated TCP fixture for the Ink/Desktop verbs the owner serves itself; no inference."""
+import asyncio
+import json
+import os
+from pathlib import Path
+import sys
+import traceback
+
+_CONFIG = '''gateway:
+ multiplex_profiles: false
+model:
+ provider: custom
+ default: no-inference
+ base_url: http://127.0.0.1:1/v1
+auxiliary:
+ title_generation:
+ enabled: false
+quick_commands:
+ probe-exec:
+ type: exec
+ command: "touch {marker} && touch relative-exec-ran && echo QUICK_EXEC_OK"
+'''
+
+
+async def probe(mode):
+ from gateway.run import GatewayRunner
+ from gateway.session_authority import initialize_session_authority
+ from gateway.run_api import start_gateway_api, stop_gateway_api
+ from gateway.session_controls import AuthorityConnection
+ from hermes_cli import web_server
+ from hermes_cli.dashboard_auth.ws_tickets import mint_ticket
+ from tests.gateway.fixtures.local_recovery_probe import rpc
+ from websockets.asyncio.client import connect
+
+ home = Path(os.environ['HERMES_HOME'])
+ marker = home / 'quick-exec-ran'
+ (home / 'config.yaml').write_text(_CONFIG.format(marker=marker))
+ runner = GatewayRunner()
+ authority = await initialize_session_authority(runner, profile_id=str(home), instance_id='routes')
+ api = await start_gateway_api(runner)
+ web_server.app.state.auth_required = True
+
+ ticket = mint_ticket(user_id='owner', provider='fixture')
+ # The same operator with a read-only grant: control, submit and exec verbs must refuse it.
+ reader = AuthorityConnection(authority, object(), {'user_id': 'owner', 'provider': 'fixture',
+ 'capabilities': ['session:read']}, operator=True)
+ try:
+ async with connect(api.api_origin.replace('http:', 'ws:') + '/api/ws?ticket=' + ticket) as ws:
+ # The session's own folder, distinct from the gateway process's cwd.
+ work = home / 'session-work'
+ work.mkdir(exist_ok=True)
+ created = await rpc(ws, 'session.create', request_id='routes-owner', source='gui', toolsets=[],
+ cwd=str(work))
+ assert 'result' in created, created
+ sid = created['result']['session_id']
+ receipt = {'mode': mode, 'authenticated_ws': True}
+ await MODES[mode](authority, ws, reader, sid, marker, receipt)
+ (home / 'receipt.json').write_text(json.dumps(receipt))
+ finally:
+ await reader.close()
+ await stop_gateway_api(api)
+
+
+def _error(reply):
+ return reply.get('error', {}).get('message')
+
+
+async def _call(reader, method, **params):
+ return await reader.dispatch({'id': method, 'method': method, 'params': params})
+
+
+async def _react(authority, ws, reader, sid, marker, receipt):
+ from tests.gateway.fixtures.local_recovery_probe import rpc
+ from gateway.session_ancillary import physical_target
+ from gateway.session_contract import SessionRef
+ target = physical_target(authority, SessionRef(authority.profile_id, sid))
+ user_row = authority.db.append_message(target, 'user', 'REACT_USER_TEXT')
+ authority.db.append_message(target, 'assistant', 'REACT_ASSISTANT_TEXT')
+ added = await rpc(ws, 'message.react', session_id=sid, row_id=user_row, emoji='πŸ‘')
+ assert added.get('result', {}).get('row_id') == user_row, added
+ assert [r['emoji'] for r in added['result']['reactions']] == ['πŸ‘'], added
+ assert [r['emoji'] for r in authority.db.get_message_reactions(target, user_row)] == ['πŸ‘']
+ newest = await rpc(ws, 'message.react', session_id=sid, newest_role='assistant', emoji='❀️')
+ assert newest.get('result', {}).get('row_id') == authority.db.latest_message_row_id(target, role='assistant'), newest
+ cleared = await rpc(ws, 'message.react', session_id=sid, row_id=user_row, emoji=None)
+ assert cleared.get('result', {}).get('reactions') == [], cleared
+ for params, reason in [({'row_id': 999999, 'emoji': 'πŸ‘'}, 'not_found'),
+ ({'emoji': 'πŸ‘'}, 'invalid_params'),
+ ({'row_id': user_row, 'emoji': 'πŸ‘', 'profile': 'foreign'}, 'profile_mismatch')]:
+ denied = await rpc(ws, 'message.react', session_id=sid, **params)
+ assert _error(denied) == reason, (params, denied)
+ denied = await _call(reader, 'message.react', session_id=sid, row_id=user_row, emoji='πŸ‘Ž')
+ assert _error(denied) == 'permission_denied', denied
+ assert authority.db.get_message_reactions(target, user_row) == []
+ receipt['reacted'] = True
+
+
+async def _control(authority, ws, reader, sid, marker, receipt):
+ from tests.gateway.fixtures.local_recovery_probe import rpc
+
+ async def control(action, **args):
+ params = {'action': action, **({'args': args} if args else {})}
+ return await rpc(ws, 'session.control', session_id=sid, **params)
+
+ for command in ('goal ship the owned fixture', 'loop every 10m CHECK_LOOP', 'heartbeat every 10m PING_HEARTBEAT'):
+ typed = await rpc(ws, 'slash.exec', session_id=sid, command=command)
+ assert 'result' in typed, (command, typed)
+ denied = await _call(reader, 'session.control', session_id=sid, action='goal.pause')
+ assert _error(denied) == 'permission_denied', denied
+ for action, check in [
+ ('goal.pause', lambda c: c['goal']['status'] == 'paused'),
+ ('goal.resume', lambda c: c['goal']['status'] == 'active'),
+ ('loop.pause', lambda c: c['loop']['status'] == 'paused'),
+ ('loop.resume', lambda c: c['loop']['status'] == 'active'),
+ ('heartbeat.pause', lambda c: c['heartbeat']['status'] == 'paused'),
+ ('heartbeat.resume', lambda c: c['heartbeat']['status'] == 'active')]:
+ reply = await control(action)
+ assert 'result' in reply, (action, reply)
+ assert check(reply['result']['control']), (action, reply)
+ assert set(reply['result']['dispatch']) == {'type', 'output', 'notice', 'message', 'display'}, reply
+ read = await rpc(ws, 'session.control.read', session_id=sid)
+ assert read['result']['control'] == reply['result']['control'], (action, read, reply)
+ # Free subgoal text is a criterion, never a /subgoal verb.
+ added = await control('subgoal.add', text='clear the cache first')
+ assert added['result']['control']['goal']['subgoals'] == ['clear the cache first'], added
+ removed = await control('subgoal.remove', index=1)
+ assert removed['result']['control']['goal']['subgoals'] == [], removed
+ for action, args in [('goal.gate.add', {}), ('nonsense', {}), ('subgoal.remove', {'index': 0}),
+ ('subgoal.add', {'text': ' '})]:
+ rejected = await control(action, **args)
+ assert _error(rejected) == 'invalid_params', (action, rejected)
+ for action, field in [('heartbeat.clear', 'heartbeat'), ('loop.stop', None), ('goal.clear', 'goal')]:
+ reply = await control(action)
+ assert 'result' in reply, (action, reply)
+ if field:
+ assert reply['result']['control'][field] is None, (action, reply)
+ foreign = await rpc(ws, 'session.control', session_id=sid, action='goal.pause', profile='foreign')
+ assert _error(foreign) == 'profile_mismatch', foreign
+ receipt['controlled'] = True
+
+
+async def _commands(authority, ws, reader, sid, marker, receipt):
+ from tests.gateway.fixtures.local_recovery_probe import rpc
+ from hermes_cli.plugins import _ensure_plugins_discovered
+ calls = []
+
+ def plugin(args):
+ from gateway.session_context import get_session_env
+ calls.append(args)
+ return f'PLUGIN_OK {args} platform={get_session_env("HERMES_SESSION_PLATFORM")}'
+ _ensure_plugins_discovered()._plugin_commands['probe-plugin'] = {
+ 'handler': plugin, 'description': 'fixture command', 'plugin': 'fixture'}
+
+ for method, params in [('slash.exec', {'command': 'probe-exec'}),
+ ('command.dispatch', {'name': 'probe-plugin', 'arg': 'X'})]:
+ denied = await _call(reader, method, session_id=sid, **params)
+ assert _error(denied) == 'permission_denied', (method, denied)
+ assert not marker.exists() and not calls, 'a read-only socket ran an exec/plugin command'
+ (Path.cwd() / 'relative-exec-ran').unlink(missing_ok=True)
+ ran = await rpc(ws, 'slash.exec', session_id=sid, command='probe-exec')
+ assert ran.get('result') == {'type': 'exec', 'output': 'QUICK_EXEC_OK'}, ran
+ assert marker.exists()
+ # A relative path acts in the session's folder, never the gateway process's.
+ work = Path(os.environ['HERMES_HOME']) / 'session-work'
+ assert (work / 'relative-exec-ran').exists(), 'exec quick command ran outside the session folder'
+ assert not (Path.cwd() / 'relative-exec-ran').exists()
+ dispatched = await rpc(ws, 'command.dispatch', session_id=sid, name='probe-plugin', arg='ARG_ONE two')
+ assert dispatched.get('result', {}).get('type') == 'exec', dispatched
+ assert dispatched['result']['output'].startswith('PLUGIN_OK ARG_ONE two platform=local'), dispatched
+ typed = await rpc(ws, 'slash.exec', session_id=sid, command='probe_plugin THREE')
+ assert typed.get('result', {}).get('output', '').startswith('PLUGIN_OK THREE'), typed
+ assert calls == ['ARG_ONE two', 'THREE']
+ unknown = await rpc(ws, 'slash.exec', session_id=sid, command='no-such-command')
+ assert _error(unknown) == 'unsupported_command', unknown
+ assert not authority.db.get_messages(sid), 'a command started a turn'
+ receipt['commands'] = True
+
+
+MODES = {'react': _react, 'control': _control, 'commands': _commands}
+
+
+if __name__ == '__main__':
+ status = 0
+ try:
+ asyncio.run(probe(sys.argv[1]))
+ except BaseException:
+ traceback.print_exc()
+ status = 1
+ sys.stdout.flush()
+ sys.stderr.flush()
+ os._exit(status)
diff --git a/tests/gateway/test_canonical_tui_desktop_routes.py b/tests/gateway/test_canonical_tui_desktop_routes.py
new file mode 100644
index 00000000000..583e179c6bc
--- /dev/null
+++ b/tests/gateway/test_canonical_tui_desktop_routes.py
@@ -0,0 +1,38 @@
+"""Ink/Desktop verbs the owner answered -32601 or refused now run their gateway handlers."""
+import json
+from pathlib import Path
+import subprocess
+import sys
+
+import pytest
+
+from tests.gateway.fixtures.local_recovery_probe import child_env
+
+
+def probe(tmp_path, mode):
+ root = Path(__file__).resolve().parents[2]
+ home, user = tmp_path / 'state', tmp_path / 'user'
+ home.mkdir()
+ user.mkdir()
+ env = child_env()
+ env.update(HOME=str(user), USERPROFILE=str(user), HERMES_HOME=str(home),
+ PYTHONPATH=str(root), PYTHONUNBUFFERED='1')
+ result = subprocess.run([sys.executable, str(root / 'tests/gateway/fixtures/tui_desktop_routes_peer.py'), mode],
+ cwd=root, env=env, capture_output=True, text=True, timeout=120, check=False)
+ assert result.returncode == 0, result.stdout + result.stderr
+ receipt = json.loads((home / 'receipt.json').read_text())
+ assert receipt['mode'] == mode and receipt['authenticated_ws']
+ return receipt
+
+
+def test_message_react_writes_the_owned_transcript_row(tmp_path):
+ assert probe(tmp_path, 'react')['reacted']
+
+
+def test_session_control_buttons_run_the_typed_command_handlers(tmp_path):
+ assert probe(tmp_path, 'control')['controlled']
+
+
+def test_exec_quick_and_plugin_commands_run_for_a_controlling_viewer(tmp_path):
+ assert probe(tmp_path, 'commands')['commands']
diff --git a/tui_gateway/AGENTS.md b/tui_gateway/AGENTS.md
index 80c054af8a3..721bf5f1dac 100644
--- a/tui_gateway/AGENTS.md
+++ b/tui_gateway/AGENTS.md
@@ -166,9 +166,11 @@ that message through `prompt.submit`, retaining their own durable input identity
Resolution itself does not start a turn or change the cached system prompt; the
normal durable admission path owns FIFO, retries, approvals, and execution.
-All other commands return `unsupported_command`, including shell quick commands,
-plugin execution, bundles, runtime/config mutation, approval/secret slash shortcuts,
-and lifecycle commands. Use the existing generation-bound control RPCs where
+`type: exec` quick commands and plugin slash commands require `session:control` and
+run through the messaging gateway's own dispatch (`gateway/run_inbound_hooks.py`: slash
+access policy, 30 s sanitized-env exec with redacted output, plugin session env).
+All other commands return `unsupported_command`, including bundles, runtime/config
+mutation, approval/secret slash shortcuts, and lifecycle commands. Use the existing generation-bound control RPCs where
available. Catalog presence alone does not imply execution support. No legacy
fallback is installed on the canonical transport.
diff --git a/ui-tui/src/__tests__/canonicalPickerDelete.test.tsx b/ui-tui/src/__tests__/canonicalPickerDelete.test.tsx
new file mode 100644
index 00000000000..cf28cd845fc
--- /dev/null
+++ b/ui-tui/src/__tests__/canonicalPickerDelete.test.tsx
@@ -0,0 +1,122 @@
+import { PassThrough } from 'node:stream'
+
+import { renderSync } from '@hermes/ink'
+import React from 'react'
+import { expect, it, vi } from 'vitest'
+
+import { ActiveSessionSwitcher } from '../components/activeSessionSwitcher.js'
+import { DEFAULT_THEME } from '../theme.js'
+
+// The shared gateway has no `session.delete` (-32601): the picker's two-press delete is its
+// revision-fenced `session.mutate operation=delete`, and a refusal stays on screen.
+
+const stored = { id: 'old', session_id: 'old', title: 'Retained old conversation', source: 'cli', started_at: 1, message_count: 2 }
+const live = { id: 'live', session_id: 'live', title: 'Current conversation', started_at: 2, message_count: 1, running: false }
+
+function mount(mutate: (params: any) => Promise<unknown>) {
+ const request = vi.fn(async (method: string, params: any) => {
+ if (method === 'session.list') {
+ return { scope: params.scope ?? 'live', sessions: params.scope === 'stored' ? [stored] : [live] }
+ }
+
+ if (method === 'session.resume') {
+ return { session_id: params.session_id, revision: 4, execution_generation: 2, messages: [] }
+ }
+
+ if (method === 'session.mutate') {
+ return mutate(params)
+ }
+
+ throw Object.assign(new Error(`unknown method: ${method}`), { code: -32601 })
+ })
+
+ const stdin = Object.assign(new PassThrough(), { isTTY: true, setRawMode: vi.fn(), ref: vi.fn(), unref: vi.fn() })
+ const stdout = Object.assign(new PassThrough(), { columns: 100, rows: 30, isTTY: false })
+ const out = { text: '' }
+ stdout.on('data', chunk => {
+ out.text += chunk.toString()
+ })
+ const element = (
+ <ActiveSessionSwitcher
+ currentSessionId="live"
+ gw={{ isCanonical: true, request } as any}
+ onCancel={vi.fn()}
+ onClose={vi.fn()}
+ onNew={vi.fn()}
+ onNewPrompt={vi.fn()}
+ onResume={vi.fn()}
+ onSelect={vi.fn()}
+ t={DEFAULT_THEME}
+ />
+ )
+ const instance = renderSync(element, {
+ stdin: stdin as any,
+ stdout: stdout as any,
+ stderr: new PassThrough() as any,
+ patchConsole: false
+ })
+
+ const deleteStored = async () => {
+ await vi.waitFor(() => expect(request).toHaveBeenCalledWith('session.list', { limit: 200, scope: 'stored' }))
+ instance.rerender(element)
+ await vi.waitFor(() => expect(out.text).toContain('Retained old conversation'))
+ stdin.write('\u001B[B')
+ // Two-press delete: each retry renders between presses, so one arms and the next confirms.
+ await vi.waitFor(() => {
+ instance.rerender(React.cloneElement(element))
+ stdin.write('d')
+ expect(request.mock.calls.some(([method]) => method === 'session.mutate')).toBe(true)
+ })
+ }
+
+ return { deleteStored, element, instance, out, request }
+}
+
+it('deletes a stored session through session.mutate with the resume CAS tuple', async () => {
+ const { deleteStored, element, instance, out, request } = mount(async params => ({
+ session_id: params.session_id, operation: 'delete', revision: 5, deleted_ids: [params.session_id]
+ }))
+
+ try {
+ await deleteStored()
+ expect(request).toHaveBeenCalledWith('session.resume', { session_id: 'old' })
+ expect(request).toHaveBeenCalledWith('session.mutate', {
+ session_id: 'old',
+ request_id: expect.any(String),
+ expected_revision: 4,
+ expected_generation: 2,
+ operation: 'delete',
+ payload: {}
+ })
+ expect(request.mock.calls.map(([method]) => method)).not.toContain('session.delete')
+ await vi.waitFor(() => {
+ out.text = ''
+ instance.rerender(React.cloneElement(element))
+ expect(out.text).toContain('Current conversation')
+ expect(out.text).not.toContain('Retained old conversation')
+ })
+ } finally {
+ instance.unmount()
+ }
+})
+
+it('keeps a refused delete on screen past the live-status poll', async () => {
+ const { deleteStored, element, instance, out, request } = mount(async () => {
+ throw Object.assign(new Error('session_busy'), { data: { reason: 'session_busy' } })
+ })
+
+ try {
+ await deleteStored()
+ const polls = request.mock.calls.filter(([method]) => method === 'session.list').length
+ // The 1.5s quiet poll used to reset the error line to the (empty) history error.
+ await vi.waitFor(() => expect(request.mock.calls.filter(([m]) => m === 'session.list').length).toBeGreaterThan(polls + 1), {
+ timeout: 4000
+ })
+ out.text = ''
+ instance.rerender(React.cloneElement(element))
+ await vi.waitFor(() => expect(out.text).toContain('error: session_busy'))
+ expect(out.text).toContain('1 resumable')
+ } finally {
+ instance.unmount()
+ }
+})
diff --git a/ui-tui/src/__tests__/canonicalSlashCommands.test.ts b/ui-tui/src/__tests__/canonicalSlashCommands.test.ts
index 524d84dbaff..6a6a7e2aa05 100644
--- a/ui-tui/src/__tests__/canonicalSlashCommands.test.ts
+++ b/ui-tui/src/__tests__/canonicalSlashCommands.test.ts
@@ -196,6 +196,22 @@ it("/usage renders main's session totals from session.stats and /tools lists the
expect(request.mock.calls.some(([method]) => LEGACY.includes(method))).toBe(false)
})
+it('/tools enable|disable refuses on the shared gateway instead of listing the unchanged tools', async () => {
+ const { page, request, slash, sys } = harness()
+
+ slash('/tools disable web')
+ slash('/tools enable browser')
+ await flush()
+
+ expect(sys.mock.calls.map(([text]) => String(text))).toEqual([
+ '/tools disable is not available on the shared gateway yet',
+ '/tools enable is not available on the shared gateway yet'
+ ])
+ expect(page).not.toHaveBeenCalled()
+ expect(request.mock.calls.map(([method]) => method)).not.toContain('tools.show')
+ expect(request.mock.calls.some(([method]) => LEGACY.includes(method))).toBe(false)
+})
+
it('/status reads through the gateway', async () => {
const { page, request, slash } = harness()
diff --git a/ui-tui/src/app/slash/canonicalSessionControls.ts b/ui-tui/src/app/slash/canonicalSessionControls.ts
index cb3d0c55bfd..f3568dcd4fc 100644
--- a/ui-tui/src/app/slash/canonicalSessionControls.ts
+++ b/ui-tui/src/app/slash/canonicalSessionControls.ts
@@ -45,7 +45,7 @@ function modelPayload(arg: string) {
return payload
}
-export type CanonicalOperation = 'model' | 'branch' | 'compress' | 'rename' | 'rewind' | 'reasoning'
+export type CanonicalOperation = 'model' | 'branch' | 'compress' | 'delete' | 'rename' | 'rewind' | 'reasoning'
/** The snapshot a mutation's CAS tuple was read from; `payload` may derive its target from it. */
export interface MutationSnapshot {
diff --git a/ui-tui/src/app/slash/commands/ops.ts b/ui-tui/src/app/slash/commands/ops.ts
index 3aae87fa902..61805180bfe 100644
--- a/ui-tui/src/app/slash/commands/ops.ts
+++ b/ui-tui/src/app/slash/commands/ops.ts
@@ -779,12 +779,16 @@ export const opsCommands: SlashCommand[] = [
help: 'enable or disable tools (client-side history reset on change)',
name: 'tools',
run: (arg, ctx, cmd) => {
+ const [subcommand, ...names] = arg.trim().split(/\s+/).filter(Boolean)
+
if (ctx.sid && ctx.gateway.gw?.isCanonical) {
- return canonicalTools(ctx)
+ // The shared gateway freezes a session's toolsets at launch (the classic CLI refuses the
+ // same change): say so instead of answering enable/disable with the unchanged list.
+ return subcommand === 'disable' || subcommand === 'enable'
+ ? ctx.transcript.sys(t('canonical.controls.notAvailable', `tools ${subcommand}`))
+ : canonicalTools(ctx)
}
- const [subcommand, ...names] = arg.trim().split(/\s+/).filter(Boolean)
-
if (subcommand !== 'disable' && subcommand !== 'enable') {
ctx.gateway.gw
.request<SlashExecResponse>('slash.exec', { command: cmd.slice(1), session_id: ctx.sid })
diff --git a/ui-tui/src/components/activeSessionSwitcher.tsx b/ui-tui/src/components/activeSessionSwitcher.tsx
index 400053966d7..25895ababe6 100644
--- a/ui-tui/src/components/activeSessionSwitcher.tsx
+++ b/ui-tui/src/components/activeSessionSwitcher.tsx
@@ -2,6 +2,7 @@ import { Box, Text, useInput, useStdout } from '@hermes/ink'
import type { SessionListResult, SessionListRow } from '@hermes/shared/gateway-events'
import { useCallback, useEffect, useRef, useState } from 'react'
+import { mutateCanonical } from '../app/slash/canonicalSessionControls.js'
import { sessionScopedModelArg } from '../domain/slash.js'
import type { GatewayClient } from '../gatewayClient.js'
import type {
@@ -317,6 +318,8 @@ export function ActiveSessionSwitcher({
const [items, setItems] = useState<SessionActiveItem[]>([])
const [history, setHistory] = useState<SessionListRow[]>([])
const [err, setErr] = useState('')
+ // A close/delete failure: kept apart from `err`, which every quiet poll rewrites.
+ const [actionErr, setActionErr] = useState('')
const [sel, setSel] = useState(0)
const [loading, setLoading] = useState(true)
const [draft, setDraft] = useState('')
@@ -508,7 +511,7 @@ export function ActiveSessionSwitcher({
return
}
- setErr('')
+ setActionErr('')
setClosingId(target.id)
try {
@@ -516,7 +519,7 @@ export function ActiveSessionSwitcher({
const closed = Boolean(result?.closed ?? result?.ok)
if (!closed) {
- setErr(messages().pickers.session.errors.alreadyClosed)
+ setActionErr(messages().pickers.session.errors.alreadyClosed)
return
}
@@ -532,7 +535,7 @@ export function ActiveSessionSwitcher({
setSel(s => Math.max(0, Math.min(s, remaining.length + history.length)))
}
} catch (e: unknown) {
- setErr(rpcErrorMessage(e))
+ setActionErr(rpcErrorMessage(e))
} finally {
setClosingId('')
}
@@ -547,12 +550,21 @@ export function ActiveSessionSwitcher({
}
setDeleting(true)
- gw.request<SessionDeleteResponse>('session.delete', { session_id: target.id })
- .then(raw => {
- const r = asRpcResult<SessionDeleteResponse>(raw)
-
- if (!r || r.deleted !== target.id) {
- setErr(messages().pickers.common.invalidResponse('session.delete'))
+ setActionErr('')
+ // The shared gateway has no `session.delete`: its delete is the revision-fenced
+ // `session.mutate operation=delete` (the whole lineage), as the classic CLI sends it.
+ const deleted = gw.isCanonical
+ ? mutateCanonical(gw, target.id, 'delete', {}).then(mutation => Boolean(mutation?.result))
+ : gw
+ .request<SessionDeleteResponse>('session.delete', { session_id: target.id })
+ .then(raw => asRpcResult<SessionDeleteResponse>(raw)?.deleted === target.id)
+
+ deleted
+ .then(ok => {
+ if (!ok) {
+ setActionErr(
+ messages().pickers.common.invalidResponse(gw.isCanonical ? 'session.mutate' : 'session.delete')
+ )
setDeleting(false)
return
@@ -561,11 +573,10 @@ export function ActiveSessionSwitcher({
rawHistoryRef.current = rawHistoryRef.current.filter(h => h.id !== target.id)
setHistory(prev => prev.filter(h => h.id !== target.id))
setSel(s => Math.max(0, Math.min(s, items.length + history.length - 1)))
- setErr('')
setDeleting(false)
})
.catch((e: unknown) => {
- setErr(rpcErrorMessage(e))
+ setActionErr(rpcErrorMessage(e))
setDeleting(false)
})
},
@@ -732,7 +743,7 @@ export function ActiveSessionSwitcher({
</Text>
<Text color={t.color.muted}>{sessionsCountLabel(items.length, history.length)}</Text>
- {err && <Text color={t.color.label}>{C.error(err)}</Text>}
+ {(actionErr || err) && <Text color={t.color.label}>{C.error(actionErr || err)}</Text>}
<Box backgroundColor={newRowStyle?.backgroundColor} flexDirection="row" onClick={handleRowClick(0)} width="100%">
<Text bold={newSelectedRow} color={newRowTextColor ?? t.color.muted}>
diff --git a/website/docs/developer-guide/gateway-command-parity.md b/website/docs/developer-guide/gateway-command-parity.md
index 6e3891ee11a..c34d8f2876f 100644
--- a/website/docs/developer-guide/gateway-command-parity.md
+++ b/website/docs/developer-guide/gateway-command-parity.md
@@ -118,7 +118,7 @@ handler does; `client-local (cli_only)` commands are terminal/UI features of a c
| `/suggestions` (/suggest) | read (bare only) | HermesCLI._handle_suggestions_command | slash.exec | slash.exec | refused | |
| `/timestamps` (/ts) | refused | HermesCLI._handle_timestamps_command | slash.exec: refused | slash.exec: refused | refused | client-local (cli_only) |
| `/title` | control | HermesCLI._cmd_title | canonical route | action: title | refused | |
-| `/tools` | refused | HermesCLI._handle_tools_command | canonical route | slash.exec: refused | refused | client-local (cli_only) |
+| `/tools` | refused | HermesCLI._handle_tools_command | refused: not available yet | slash.exec: refused | refused | client-local (cli_only) |
| `/toolsets` | read | HermesCLI.show_toolsets | slash.exec | unavailable: terminal | refused | client-local (cli_only) |
| `/topic` | refused | messaging-only: unknown command | slash.exec: refused | slash.exec: refused | refused | messaging-only |
| `/topup` | read | HermesCLI._show_billing | sidecar: billing.state | slash.exec | refused | |
diff --git a/website/docs/developer-guide/gateway-internals.md b/website/docs/developer-guide/gateway-internals.md
index 013f338954d..2bbe9c975b3 100644
--- a/website/docs/developer-guide/gateway-internals.md
+++ b/website/docs/developer-guide/gateway-internals.md
@@ -148,9 +148,12 @@ message through their normal identified `prompt.submit`; resolution is not an
admission ACK. The authority's durable FIFO owns retries and execution, and skill
content remains a user message without changing the cached system prefix.
-Other commands return `unsupported_command`: shell quick commands, plugin execution,
-bundles, configuration/runtime changes, lifecycle commands, and approval/secret
-slash shortcuts are not exposed. Existing generation-bound approval and interrupt
+`type: exec` quick commands and plugin slash commands require `session:control` and run
+through the messaging gateway's own quick/plugin dispatch (slash access policy,
+sanitized-env exec with a 30 s cap and redacted output, plugin session env).
+
+Other commands return `unsupported_command`: bundles, configuration/runtime changes,
+lifecycle commands, and approval/secret slash shortcuts are not exposed. Existing generation-bound approval and interrupt
RPCs remain separate. Catalog discovery is broader than this reviewed execution set.
## Shared authority busy input and corrections