The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat: dispatch bound local slash commands through gateway handlers
Tekniumb0377e929b48
diff --git a/gateway/session_commands.py b/gateway/session_commands.pynew file mode 100644index 00000000000..345df598f27--- /dev/null+++ b/gateway/session_commands.py@@ -0,0 +1,108 @@+"""Bound local slash commands; prompt directives use the client's durable submit.++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 pathlib import Path++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'})+_CONTROL_COMMANDS = frozenset({'title'})+++def _parse(params, dispatch):+ allowed = {'session_id', 'profile', 'name', 'arg'} if dispatch else {'session_id', 'profile', 'command'}+ if (set(params) - allowed or any(not isinstance(v, str) for v in params.values())):+ raise RuntimeStoreError('invalid_params')+ text = params.get('name', '') if dispatch else params.get('command', '')+ parts = text.strip().lstrip('/').split(None, 1)+ if not parts or (dispatch and len(parts) != 1):+ raise RuntimeStoreError('invalid_params')+ return parts[0], params.get('arg', '') if dispatch else (parts[1] if len(parts) > 1 else '')+++def _resolve_alias(name, arg):+ from gateway.run import _load_gateway_config+ from hermes_cli.commands import resolve_command+ quick = _load_gateway_config().get('quick_commands') or {}+ seen = set()+ while resolve_command(name) is None and name in quick:+ if name in seen:+ 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':+ raise RuntimeStoreError('unsupported_command')+ target = entry.get('target')+ if not isinstance(target, str) or not target.strip():+ raise RuntimeStoreError('invalid_params')+ parts = target.strip().lstrip('/').split(None, 1)+ name = parts[0]+ arg = ' '.join(p for p in (*parts[1:], arg) if p)+ return name, arg+++def _skill_directive(name, arg, route):+ from agent.skill_commands import (+ build_skill_invocation_message, describe_skill_invocation, get_skill_commands,+ )+ key = '/' + name+ skills = get_skill_commands()+ if key not in skills:+ raise RuntimeStoreError('unsupported_command')+ message = build_skill_invocation_message(key, arg, task_id=route)+ if not message:+ raise RuntimeStoreError('command_unavailable')+ return {'type': 'skill', 'name': skills[key]['name'], 'message': message,+ 'display': describe_skill_invocation(message, separator=' ')}+++async def execute_command(connection, ref, params, *, dispatch=False):+ authority, actor = connection.authority, connection.actor+ authority.authorize(actor, ref, 'session:read')+ name, arg = _parse(params, dispatch)+ from hermes_cli.commands import resolve_command+ from hermes_cli.profiles import profile_matches_home+ home = Path(authority.profile_id)+ if params.get('profile') and not profile_matches_home(params['profile'], home):+ raise RuntimeStoreError('profile_mismatch')++ from gateway.run import _profile_runtime_scope+ def resolve():+ with _profile_runtime_scope(home):+ return _resolve_alias(name, arg)+ 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+ 'session:control' if definition else 'session:submit')+ authority.authorize(actor, ref, capability)+ if definition and canonical not in _READ_COMMANDS | _CONTROL_COMMANDS:+ raise RuntimeStoreError('unsupported_command')+ from gateway.session_local import authorize_local_source+ live = authority.sessions[ref.session_id]+ if authorize_local_source(authority.runner, live.source) is not True:+ raise RuntimeStoreError('permission_denied')+ if capability != 'session:read':+ authority._require_admission_open()+ if definition is None:+ def build():+ with _profile_runtime_scope(home):+ return _skill_directive(name, arg, live.route)+ return await asyncio.to_thread(build)++ 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):+ if authority._handle(ref).execution_state != 'idle':+ output = await authority.runner._dispatch_busy_slash_command(event, definition, live.route, live.source)+ else:+ handler = authority.runner._command_handler_table((canonical,))[canonical]+ output = await handler(event)+ return {'type': 'exec', 'output': str(output or '')}diff --git a/gateway/session_controls.py b/gateway/session_controls.pyindex fe9755a566d..6ae2d479825 100644--- a/gateway/session_controls.py+++ b/gateway/session_controls.py@@ -33,6 +33,7 @@ class AuthorityConnection:ref = SessionRef(self.actor.profile_id, params.get('session_id', ''))handlers = {'session.create': self.create, 'ping': self.ping, 'runtime.describe': self.describe,'commands.catalog': self.command_catalog, 'complete.slash': self.slash_completions,+ 'slash.exec': self.slash_exec, 'command.dispatch': self.command_dispatch,'session.list': self.list_sessions, 'session.info': self.info,'session.mutate': self.mutate,'setup.status': self.setup_status, 'setup.runtime_check': self.setup_runtime_check,@@ -52,6 +53,14 @@ class AuthorityConnection:return {'jsonrpc': '2.0', 'id': rid, 'error': {'code': 5001, 'message': 'storage_unavailable', 'data': {'reason': 'storage_unavailable'}}}+ async def slash_exec(self, ref, params):+ from gateway.session_commands import execute_command+ return await execute_command(self, ref, params)++ async def command_dispatch(self, ref, params):+ from gateway.session_commands import execute_command+ return await execute_command(self, ref, params, dispatch=True)+async def command_catalog(self, ref, params):from gateway.session_discovery import discover_commandsreturn await discover_commands(self.authority, self.actor, params)diff --git a/tests/gateway/test_session_commands.py b/tests/gateway/test_session_commands.pynew file mode 100644index 00000000000..f6f434b4f91--- /dev/null+++ b/tests/gateway/test_session_commands.py@@ -0,0 +1,160 @@+"""Local slash resolution is not another execution owner."""+import asyncio+from http.server import ThreadingHTTPServer+import json+import os+from pathlib import Path+import signal+import sqlite3+import threading+from types import SimpleNamespace++import pytest+from websockets.asyncio.client import connect+from websockets.exceptions import InvalidStatus++from tests.gateway.fixtures.local_recovery_probe import Model, daemon, rpc, websocket++[email protected]_only+def test_ordinary_daemon_slash_skill_uses_durable_fifo(tmp_path):+ root = Path(__file__).resolve().parents[2]+ home, user = tmp_path / 'state', tmp_path / 'user'+ home.mkdir(mode=0o700)+ user.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'+ (home / 'config.yaml').write_text(json.dumps({+ 'gateway': {'multiplex_profiles': False},+ 'model': {'provider': 'custom', 'default': 'slash-fixture', 'base_url': url},+ 'auxiliary': {'title_generation': {'enabled': False}},+ 'quick_commands': {'probe-quick': {'type': 'alias', 'target': '/probe-skill'}},+ }))+ skill = home / 'skills' / 'probe-skill'+ skill.mkdir(parents=True)+ (skill / 'SKILL.md').write_text(+ '---\nname: probe-skill\ndescription: Disposable slash fixture\n---\n'+ '# Probe\nSLASH_SKILL_BODY: follow this owned fixture instruction.\n')+ env = {k: os.environ[k] for k in ('PATH', 'LANG', 'TZ') if k in os.environ}+ env.update(HOME=str(user), USERPROFILE=str(user), HERMES_HOME=str(home),+ PYTHONPATH=str(root), PYTHONUNBUFFERED='1',+ OPENAI_API_KEY='loopback-only', OPENAI_BASE_URL=url)+ receipts = []++ def rows():+ with sqlite3.connect(f'file:{home / "state.db"}?mode=ro', uri=True) as db:+ return list(db.execute('SELECT request_id,status,seq FROM session_admissions ORDER BY seq'))++ async def probe(desc):+ with pytest.raises(InvalidStatus):+ async with connect(desc['api_origin'].replace('http:', 'ws:') + '/api/ws'):+ pass+ async with websocket(home, desc) as ws:+ created = await rpc(ws, 'session.create', request_id='slash', source='gui', toolsets=[])+ sid = created['result']['session_id']++ async def command(method='slash.exec', **params):+ result = await rpc(ws, method, session_id=sid, **params)+ receipts.append(result)+ return result++ help_reply = await command(command='help')+ assert help_reply.get('result', {}).get('output'), help_reply+ status = await command(command='status')+ assert sid in status['result']['output'], status+ for method, params in [('slash.exec', {'command': 'probe-quick TASK_ONE'}),+ ('command.dispatch', {'name': 'probe-skill', 'arg': 'TASK_TWO'})]:+ result = await command(method, **params)+ assert result.get('result', {}).get('type') == 'skill', result+ assert 'SLASH_SKILL_BODY' in result['result']['message'], result+ assert 'SLASH_SKILL_BODY' not in result['result']['display'], result+ assert not peer.requests and not rows(), 'resolution executed a turn'+ await rpc(ws, 'prompt.submit', session_id=sid, input_id='warm', text='WARM_SLASH')+ async with asyncio.timeout(30):+ while not rows() or rows()[0][1] != 'terminal':+ await asyncio.sleep(.05)+ block = await rpc(ws, 'prompt.submit', session_id=sid, input_id='block', text='BLOCK_STARTED')+ assert block.get('result', {}).get('status') == 'queued', block+ assert await asyncio.to_thread(peer.blocked.wait, 25), ([m for r in peer.requests for m in r['messages'] if m['role'] == 'user'], rows())+ for index, marker in enumerate(('TASK_ONE', 'TASK_TWO')):+ directive = await command(command='probe-quick ' + marker)+ admitted = await rpc(ws, 'prompt.submit', session_id=sid,+ input_id=marker, text=directive['result']['message'])+ receipts.append(admitted)+ assert admitted['result']['status'] == 'queued', admitted+ retry = await rpc(ws, 'prompt.submit', session_id=sid,+ input_id=marker, text=directive['result']['message'])+ assert retry['result']['admission_id'] == admitted['result']['admission_id']+ assert [r[:2] for r in rows()] == [('warm', 'terminal'), ('block', 'started'), ('TASK_ONE', 'queued'), ('TASK_TWO', 'queued')]+ busy_title = await command(command='title forbidden-while-busy')+ assert 'mid-turn' in busy_title['result']['output'], busy_title+ for params, reason in [({'command': 'help', 'profile': 'foreign'}, 'profile_mismatch'),+ ({'command': 'help', 'source': 'telegram'}, 'invalid_params'),+ ({'command': 'restart'}, 'unsupported_command'),+ ({'command': 'approve'}, 'unsupported_command')]:+ denied = await command(**params)+ assert denied['error']['message'] == reason, denied+ peer.release.set()+ async with asyncio.timeout(45):+ while any(row[1] != 'terminal' for row in rows()):+ await asyncio.sleep(.05)+ title = await command(command='title Owned slash title')+ assert 'Owned slash title' in title['result']['output'], title+ listing = await rpc(ws, 'session.list')+ assert next(r for r in listing['result']['sessions'] if r['id'] == sid)['title'] == 'Owned slash title'+ snapshot = await rpc(ws, 'session.resume', session_id=sid)+ assert 'TASK_TWO' in json.dumps(snapshot['result']['messages']), snapshot+ receipts.append({'session_id': sid, 'ledger': rows(), 'history': snapshot['result']['messages']})+ try:+ with daemon(root, home, env, barrier=False) as (proc, desc):+ asyncio.run(probe(desc))+ texts = [next(m['content'] for m in reversed(r['messages']) if m['role'] == 'user') for r in peer.requests]+ assert len(texts) == 4 and texts[1] == 'BLOCK_STARTED', texts+ assert 'TASK_ONE' in texts[2] and 'TASK_TWO' in texts[3], texts+ systems = [[m for m in r['messages'] if m['role'] == 'system'] for r in peer.requests]+ assert systems[1] == systems[2] == systems[3], 'slash invalidated cached system prefix'+ proc.send_signal(signal.SIGINT)+ assert proc.wait(timeout=20) == 0+ print(json.dumps({'pid': proc.pid, 'exit': proc.returncode, 'descriptor': desc,+ 'wire_receipts': receipts, 'model_texts': texts,+ 'system_prefix_unchanged': True, 'unauthenticated_ws_rejected': True}))+ finally:+ peer.release.set()+ peer.shutdown()+ peer.server_close()+ thread.join(timeout=5)+++async def test_command_authority_precedes_resolution_and_mutation(tmp_path, monkeypatch):+ from gateway.config import Platform+ from gateway.session import SessionSource+ from gateway.session_authority import SessionAuthority, LiveSession+ from gateway.session_controls import AuthorityConnection+ from agent import skill_commands++ runner = SimpleNamespace(_draining=False)+ authority = SessionAuthority(runner, profile_id=str(tmp_path), instance_id='owned', db=None, epoch=1)+ source = SessionSource(platform=Platform.LOCAL, chat_id='local-test', user_id='owner')+ authority.sessions['local-test'] = LiveSession(source, 'route')+ def forbidden(*args, **kwargs):+ pytest.fail('unauthorized command reached skill resolution')+ monkeypatch.setattr(skill_commands, 'get_skill_commands', forbidden)+ for identity, command, reason in [+ ({'user_id': 'owner', 'capabilities': ['session:read']}, 'title mutated', 'permission_denied'),+ ({'user_id': 'owner', 'capabilities': ['session:read']}, 'private-skill', 'permission_denied'),+ ({'user_id': 'other'}, 'help', 'permission_denied'),+ ({'user_id': 'owner', 'profile_id': 'foreign'}, 'help', 'profile_mismatch'),+ ({'user_id': 'owner', 'instance_id': 'stale'}, 'help', 'permission_denied'),+ ]:+ connection = AuthorityConnection(authority, object(), identity)+ for method, payload in [('slash.exec', {'command': command}),+ ('command.dispatch', {'name': command.split()[0], 'arg': 'mutated'})]:+ result = await connection.dispatch({'id': 1, 'method': method,+ 'params': {'session_id': 'local-test', **payload}})+ assert result.get('error', {}).get('message') == reason, result+ await connection.close()diff --git a/tui_gateway/AGENTS.md b/tui_gateway/AGENTS.mdindex d48c5b18b52..2d18b440ad5 100644--- a/tui_gateway/AGENTS.md+++ b/tui_gateway/AGENTS.md@@ -86,6 +86,32 @@ legacy session or execution runtime. Catalog warnings, categories, aliases, deskskill usage/origin, and completion replacement offsets retain their legacy shapes. Discovery isnot an assertion that every listed slash execution command is implemented by the canonical RPCs.+## Canonical local slash execution++`gateway/session_commands.py` adapts both `slash.exec({session_id, command})` and+`command.dispatch({session_id, name, arg})` without loading the legacy server or+slash worker. Optional `profile` must name the authority's exact profile. Only+server-registered local sources belonging to the authenticated actor may dispatch;+caller-supplied source, routing, credentials, or platform fields are rejected.++Reviewed gateway handlers: `help`, `commands`, `status`, `context`, `version`,+`whoami` require `session:read`; `title` requires `session:control` (including its+query form). Registry aliases are accepted. Existing registry busy rejection and+mid-turn dispatch policies apply. Results are `{type: "exec", output}`.++Profile skills and configured quick-command aliases to these commands/skills are+supported. Skill resolution requires `session:submit` and returns the existing+`{type: "skill", name, message, display}` directive. Desktop and Ink already submit+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+available. Catalog presence alone does not imply execution support. No legacy+fallback is installed on the canonical transport.+## Dev commands```bash