Skip to content

The agent that grows with you

fix(gateway): local sessions run the read/report commands whose handler works for them

Teknium61dbb0f80536
diff --git a/gateway/session_commands.py b/gateway/session_commands.py
index 345df598f27..3aa7396ad53 100644
--- a/gateway/session_commands.py
+++ b/gateway/session_commands.py
@@ -4,15 +4,56 @@ Desktop and Ink both submit ``skill``/``send`` results with their own input ID.
Executing those here would double-submit and bypass their retry identity.
"""
import asyncio
+from contextlib import contextmanager
from pathlib import Path
+import shlex
from hermes_state_runtime import RuntimeStoreError
-# Reviewed gateway handlers only: listing a command is not permission to run it.
-_READ_COMMANDS = frozenset({'help', 'commands', 'status', 'context', 'version', 'whoami'})
+# Reviewed gateway handlers only: listing a command is not permission to run it. Each read was
+# run through its real handler against a local session (website/docs/developer-guide/
+# gateway-command-parity.md); a handler that reads messaging-only state or writes config is not here.
+_READ_COMMANDS = frozenset({'help', 'commands', 'status', 'context', 'version', 'whoami',
+ 'usage', 'insights', 'profile', 'diff', 'memory', 'kanban', 'topup',
+ 'suggestions', 'bundles'})
_CONTROL_COMMANDS = frozenset({'title'})
+# Kanban verbs that only read the board. ``create`` would also subscribe the LOCAL chat to
+# messaging notifications, and every other verb mutates the board.
+_KANBAN_READS = frozenset({'', 'help', '--help', '-h', '?', 'list', 'ls', 'show', 'stats', 'assignees',
+ 'context', 'runs', 'log', 'diagnostics', 'diag'})
+
+
+def _first_token(arg):
+ tokens = iter(shlex.split(arg) if arg.strip() else [])
+ for token in tokens:
+ if token == '--board':
+ next(tokens, None)
+ elif not token.startswith('--board='):
+ return token.lower()
+ return ''
+
+
+# The read-only argument forms of a read command whose other subcommands write: ``/usage reset``
+# redeems a credit, ``/memory approve|approval`` applies writes / edits config.yaml,
+# ``/suggestions accept|catalog`` schedules cron jobs delivering to this (non-messaging) chat.
+_READ_ARGUMENTS = {
+ 'usage': lambda arg: not arg.strip(),
+ 'memory': lambda arg: arg.strip().lower() in {'', 'pending'},
+ 'suggestions': lambda arg: not arg.strip(),
+ 'kanban': lambda arg: _first_token(arg) in _KANBAN_READS,
+}
+
+
+def command_verdict(name, arg=''):
+ """``read`` / ``control`` / ``refused`` for a canonical registry command on a local session."""
+ if name in _CONTROL_COMMANDS:
+ return 'control'
+ if name in _READ_COMMANDS and _READ_ARGUMENTS.get(name, lambda _arg: True)(arg):
+ return 'read'
+ return 'refused'
+
def _parse(params, dispatch):
allowed = {'session_id', 'profile', 'name', 'arg'} if dispatch else {'session_id', 'profile', 'command'}
@@ -62,6 +103,27 @@ def _skill_directive(name, arg, route):
'display': describe_skill_invocation(message, separator=' ')}
+@contextmanager
+def _session_workspace(runner, source):
+ """The session's frozen terminal policy (``TERMINAL_CWD`` = its launch cwd), so ``/diff``
+ reads the caller's checkout instead of the gateway process's configured directory."""
+ import json
+ from agent.runtime_cwd import reset_session_cwd, set_session_cwd
+ from gateway.session_policy import policy_for_source
+ from tools.terminal_scope import reset_terminal_scope, set_terminal_scope
+ policy = policy_for_source(runner, source)
+ if policy is None:
+ yield
+ return
+ cwd_token = set_session_cwd(policy.cwd)
+ terminal_token = set_terminal_scope(json.loads(policy.terminal_json))
+ try:
+ yield
+ finally:
+ reset_terminal_scope(terminal_token)
+ reset_session_cwd(cwd_token)
+
+
async def execute_command(connection, ref, params, *, dispatch=False):
authority, actor = connection.authority, connection.actor
authority.authorize(actor, ref, 'session:read')
@@ -79,10 +141,11 @@ async def execute_command(connection, ref, params, *, dispatch=False):
name, arg = await asyncio.to_thread(resolve)
definition = resolve_command(name)
canonical = definition.name if definition else name
- capability = ('session:read' if canonical in _READ_COMMANDS else
+ verdict = command_verdict(canonical, arg) if definition else None
+ capability = ('session:read' if verdict == 'read' else
'session:control' if definition else 'session:submit')
authority.authorize(actor, ref, capability)
- if definition and canonical not in _READ_COMMANDS | _CONTROL_COMMANDS:
+ if verdict == 'refused':
raise RuntimeStoreError('unsupported_command')
from gateway.session_local import authorize_local_source
live = authority.sessions[ref.session_id]
@@ -99,7 +162,7 @@ async def execute_command(connection, ref, params, *, dispatch=False):
from gateway.platforms.base import MessageEvent
event = MessageEvent(text='/' + canonical + (' ' + arg if arg else ''), source=live.source)
# Use the registry's existing busy contract, not a local approximation.
- with _profile_runtime_scope(home):
+ with _profile_runtime_scope(home), _session_workspace(authority.runner, live.source):
if authority._handle(ref).execution_state != 'idle':
output = await authority.runner._dispatch_busy_slash_command(event, definition, live.route, live.source)
else:
diff --git a/tests/gateway/test_session_read_commands.py b/tests/gateway/test_session_read_commands.py
new file mode 100644
index 00000000000..d12b2641341
--- /dev/null
+++ b/tests/gateway/test_session_read_commands.py
@@ -0,0 +1,86 @@
+"""Read/report slash commands run their real gateway handler for a LOCAL session (and only reads)."""
+import asyncio
+import json
+import os
+from http.server import ThreadingHTTPServer
+from pathlib import Path
+import signal
+import subprocess
+import threading
+
+import pytest
+
+from tests.gateway.fixtures.local_recovery_probe import Model, child_env, daemon, rpc, websocket
+
+
+def test_local_session_reads_report_this_session_and_refuse_their_write_forms(tmp_path):
+ 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()
+ # The session's own checkout: /diff must read THIS cwd, not the gateway's directory.
+ subprocess.run(['git', 'init', '-q', str(work)], check=True)
+ (work / 'SESSION_CWD_MARKER.txt').write_text('untracked in the session checkout\n')
+ 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 = json.dumps({'gateway': {'multiplex_profiles': False},
+ 'model': {'provider': 'custom', 'default': 'reads-model', 'base_url': url},
+ 'auxiliary': {'title_generation': {'enabled': False}}})
+ (home / 'config.yaml').write_text(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='reads', source='cli', toolsets=[], cwd=str(work))
+ sid = created['result']['session_id']
+ await rpc(ws, 'prompt.submit', session_id=sid, input_id='warm', text='WARM_READS')
+ async with asyncio.timeout(45):
+ while True:
+ snap = (await rpc(ws, 'session.resume', session_id=sid))['result']
+ if not snap['running'] and not snap['pending'] and 'RECOVERY_ACK_WARM_READS' in json.dumps(
+ snap['messages']):
+ break
+ await 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', 'debug', 'agents', 'sessions', 'platform', 'fast'):
+ reply = await rpc(ws, 'slash.exec', session_id=sid, command=command)
+ out[command] = reply.get('result', {}).get('output') or reply.get('error', {}).get('message')
+ dispatched = await rpc(ws, 'command.dispatch', session_id=sid, name='profile', arg='')
+ out['dispatch profile'] = dispatched['result']['output']
+ 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)
+ # Session/account reports: this session's live agent and this profile's store.
+ assert 'reads-model' in out['usage'] and 'API calls: 1' in out['usage'], out['usage']
+ assert '**Sessions:** 1' in out['insights'] and '**Messages:** 2' in out['insights'], out['insights']
+ assert str(home) in out['profile'] and out['dispatch profile'] == out['profile'], out['profile']
+ assert 'Nous' in out['topup'], out['topup']
+ # Workspace report: the session's frozen cwd.
+ assert 'SESSION_CWD_MARKER.txt' in out['diff'], out['diff']
+ # Review queues and boards, read-only views.
+ assert 'No pending memory writes' in out['memory'], out['memory']
+ assert 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.
+ for command in ('usage reset', 'memory approval on', 'kanban create x', 'suggestions catalog', 'debug',
+ 'agents', 'sessions', 'platform', 'fast'):
+ assert out[command] == 'unsupported_command', (command, out[command])
+ assert (home / 'config.yaml').read_text() == config
+ assert not os.path.exists(home / 'cron' / 'jobs.json') or 'catalog' not in (home / 'cron' / 'jobs.json').read_text()