Skip to content

The agent that grows with you

feat(gateway): slash.exec runs the authoring and goal-family handlers for a local session

Tekniumb46c96428633
diff --git a/gateway/run_busy.py b/gateway/run_busy.py
index e25a32a08e0..bbf9a12a29b 100644
--- a/gateway/run_busy.py
+++ b/gateway/run_busy.py
@@ -924,7 +924,7 @@ class GatewayBusySessionMixin:
"approvals", "model", "codex-runtime", "personality", "suggestions", "save", "retry",
"sethome", "compress", "usage", "topup", "insights", "reload-mcp", "reload-skills",
"bundles", "debug", "title", "resume", "sessions", "branch", "rollback", "diff", "goal",
- "loop", "refine", "review", "voice",
+ "loop", "refine", "review", "voice", "curator",
)
def _command_handler_table(self, names) -> dict[str, Any]:
@@ -941,6 +941,10 @@ class GatewayBusySessionMixin:
async def _send_command_ack(self, source, text: str, label: str) -> None:
"""Best-effort acknowledgment for a slash command that falls through to agent processing."""
+ from gateway.session_command_sink import active_sink
+ if (sink := active_sink()) is not None:
+ sink.notices.append(text) # a local slash.exec: the ack rides the client's directive
+ return
try:
adapter = self._delivery_adapter_for(source)
if adapter:
diff --git a/gateway/session_automation.py b/gateway/session_automation.py
index 94d87bdf844..01ee23c7e78 100644
--- a/gateway/session_automation.py
+++ b/gateway/session_automation.py
@@ -298,8 +298,22 @@ async def admit_route_wake(runner, adapter, source, text, producer, metadata=Non
authority = active_authority(runner)
key = runner._session_key_for_source(source)
entry = runner.session_store.lookup_by_session_key(key) if authority is not None else None
- if entry is None or source.platform == Platform.LOCAL:
+ if authority is None or entry is None:
return False
+ import uuid
+ identity = json.dumps([producer, key, uuid.uuid4().hex], separators=(',', ':'))
+ if source.platform == Platform.LOCAL:
+ # A local route has no messaging provenance to borrow: its wake rides local_automation_v1 on
+ # the live session's own source object (``snapshot_local_automation`` checks identity).
+ live = authority.sessions.get(source.chat_id)
+ if live is None or live.route != key:
+ return False
+ event = MessageEvent(text=text, message_type=MessageType.TEXT, source=live.source, internal=True,
+ message_id=identity, metadata={'gateway_session_key': key,
+ 'gateway_session_id': entry.session_id,
+ **(metadata or {})})
+ await authority.admit_automation(adapter, event, identity)
+ return True
from gateway.session_envelope import restore_native
from hermes_state_runtime import list_session_admissions
prior = list_session_admissions(authority.db, session_id=authority.logical_owner(entry.session_id),
@@ -311,8 +325,6 @@ async def admit_route_wake(runner, adapter, source, text, producer, metadata=Non
# The route's committed source, which ``snapshot_automation`` re-derives and compares.
restored = restore_native({'text': text, 'native_text_v1': {
k: v for k, v in envelope.items() if k != 'media'}}, runner)
- import uuid
- identity = json.dumps([producer, key, uuid.uuid4().hex], separators=(',', ':'))
event = MessageEvent(text=text, message_type=MessageType.TEXT, source=restored.source, internal=True,
message_id=identity, metadata={'gateway_session_key': key,
'gateway_session_id': entry.session_id,
diff --git a/gateway/session_command_sink.py b/gateway/session_command_sink.py
new file mode 100644
index 00000000000..d1e343c6545
--- /dev/null
+++ b/gateway/session_command_sink.py
@@ -0,0 +1,37 @@
+"""What a messaging command handler would have SENT, captured for a local ``slash.exec``.
+
+The messaging gateway's handlers deliver two things outside their return value: an ack line
+(``_send_command_ack``) and a next turn pushed onto the adapter FIFO (``/goal``'s kickoff,
+``_enqueue_goal_turn``). A local session's adapter has no transport and no FIFO reader: its turns
+are client-submitted admissions with the client's own durable input id. So while ``slash.exec``
+runs a handler for a local session, both are captured here and returned to the client as one
+``send`` directive (``notice`` + ``message``); the client submits it, the gateway never does.
+"""
+from __future__ import annotations
+
+from contextlib import contextmanager
+from contextvars import ContextVar
+from dataclasses import dataclass, field
+
+_SINK: ContextVar = ContextVar('local_command_sink', default=None)
+
+
+@dataclass
+class CommandSink:
+ notices: list[str] = field(default_factory=list)
+ prompt: str | None = None
+ display: str | None = None
+
+
+def active_sink() -> CommandSink | None:
+ return _SINK.get()
+
+
+@contextmanager
+def capture():
+ sink = CommandSink()
+ token = _SINK.set(sink)
+ try:
+ yield sink
+ finally:
+ _SINK.reset(token)
diff --git a/gateway/session_commands.py b/gateway/session_commands.py
index cc2e49778d9..1789a9a8825 100644
--- a/gateway/session_commands.py
+++ b/gateway/session_commands.py
@@ -18,6 +18,14 @@ _READ_COMMANDS = frozenset({'help', 'commands', 'status', 'context', 'version',
'usage', 'insights', 'profile', 'diff', 'memory', 'kanban', 'topup',
'suggestions', 'bundles'})
_CONTROL_COMMANDS = frozenset({'title'})
+# Authoring/workflow commands whose messaging handler (``_command_handler_table``) runs as-is for a
+# local session: goal/loop/heartbeat state on the session's row, the review/refine forks of its
+# cached agent, the /debug summary upload, /blueprint's job creation. A turn the handler would have
+# pushed onto the adapter FIFO comes back as a ``send`` directive (gateway/session_command_sink.py).
+_HANDLER_CONTROLS = frozenset({'goal', 'subgoal', 'loop', 'heartbeat', 'review', 'refine', 'debug', 'curator'})
+# 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'})
# Kanban verbs that only read the board. ``create`` would also subscribe the LOCAL chat to
# messaging notifications, and every other verb mutates the board.
@@ -48,7 +56,7 @@ _READ_ARGUMENTS = {
def command_verdict(name, arg=''):
"""``read`` / ``control`` / ``refused`` for a canonical registry command on a local session."""
- if name in _CONTROL_COMMANDS:
+ if name in _CONTROL_COMMANDS or name in _HANDLER_CONTROLS or name in _PROMPT_COMMANDS:
return 'control'
if name in _READ_COMMANDS and _READ_ARGUMENTS.get(name, lambda _arg: True)(arg):
return 'read'
@@ -178,12 +186,32 @@ async def execute_command(connection, ref, params, *, dispatch=False):
return await asyncio.to_thread(build)
from gateway.platforms.base import MessageEvent
- event = MessageEvent(text='/' + canonical + (' ' + arg if arg else ''), source=live.source)
+ from gateway.session_command_sink import capture
+ typed = '/' + canonical + (' ' + arg if arg else '')
+ event = MessageEvent(text=typed, source=live.source)
+ runner = authority.runner
+ prompt = None
# Use the registry's existing busy contract, not a local approximation.
- with _profile_runtime_scope(home), _session_workspace(authority.runner, live.source):
+ with _profile_runtime_scope(home), _session_workspace(runner, live.source), capture() as sink:
if authority._handle(ref).execution_state != 'idle':
- output = await authority.runner._dispatch_busy_slash_command(event, definition, live.route, live.source)
+ output = await runner._dispatch_busy_slash_command(event, definition, live.route, live.source)
+ elif canonical in _PROMPT_COMMANDS:
+ handled, output = await getattr(runner, '_hm_cmd_' + canonical.replace('-', '_'))(
+ event, live.source, live.route)
+ if not handled:
+ prompt = event.text
else:
- handler = authority.runner._command_handler_table((canonical,))[canonical]
+ handler = runner._command_handler_table((canonical,))[canonical]
output = await handler(event)
- return {'type': 'exec', 'output': str(output or '')}
+ prompt = prompt if prompt is not None else sink.prompt
+ if prompt:
+ # The client submits the turn with its own durable input id; the gateway never does.
+ notice = '\n'.join(filter(None, [*sink.notices, str(output or '')]))
+ return {'type': 'send', 'message': prompt, 'display': sink.display or typed,
+ **({'notice': notice} if notice else {})}
+ return {'type': 'exec', 'output': '\n'.join(filter(None, [*sink.notices, _text(output)]))}
+
+
+def _text(output):
+ """A handler reply as text: ``/blueprint``'s result object carries it in ``.text``."""
+ return str(getattr(output, 'text', output) or '')
diff --git a/gateway/slash_commands.py b/gateway/slash_commands.py
index 4f1e5f20933..df96fef2da5 100644
--- a/gateway/slash_commands.py
+++ b/gateway/slash_commands.py
@@ -1235,6 +1235,28 @@ class GatewaySlashCommandsMixin(
confirmation_text = t(key, count=count, reason=reason)
return await self._deliver_approval_confirmation(event, confirmation_text, "deny")
+ async def _handle_curator_command(self, event: MessageEvent) -> str:
+ """Handle /curator — the ``hermes curator`` handler set (status by default), as main's CLI ran
+ it in-process; its printed report is the reply. Runs in the executor with the session's
+ context so the profile's skills tree and curator state are the ones read and written."""
+ import io
+ from contextlib import redirect_stderr, redirect_stdout
+ from hermes_cli.curator import cli_main
+ tokens = shlex.split(event.get_command_args() or "") or ["status"]
+
+ def _run() -> str:
+ out = io.StringIO()
+ with redirect_stdout(out), redirect_stderr(out):
+ try:
+ cli_main(tokens)
+ except SystemExit:
+ pass # argparse exits on --help/usage errors; its text is the reply
+ except Exception as exc:
+ print(t("cli.commands.curator.failed", error=exc))
+ return out.getvalue().rstrip()
+
+ return await self._run_in_executor_with_context(_run)
+
async def _handle_debug_command(self, event: MessageEvent) -> str:
"""Handle /debug — upload ONLY the summary (system info + log tails), never full logs, to
protect privacy; ``hermes debug share`` from the CLI does full uploads."""
diff --git a/gateway/slash_commands_goals.py b/gateway/slash_commands_goals.py
index 2aa7317c389..09f7a379ea5 100644
--- a/gateway/slash_commands_goals.py
+++ b/gateway/slash_commands_goals.py
@@ -73,8 +73,15 @@ class GatewayGoalCommandsMixin:
"""Enqueue *text* as the next turn through the adapter FIFO (the post-turn judge's path).
A kickoff keeps the triggering message id / channel prompt; a resume continuation carries
- none. Best-effort: failures only logged.
+ none. Best-effort: failures only logged. A local ``slash.exec`` returns the turn to the
+ client as its ``send`` directive instead (the client submits it with its own input id).
"""
+ from gateway.session_command_sink import active_sink
+ if (sink := active_sink()) is not None:
+ sink.prompt = text
+ if not kickoff:
+ sink.display = "/goal resume"
+ return
try:
adapter, quick_key = self._adapter_and_key_for(event)
if text and adapter and quick_key:
diff --git a/tests/gateway/test_session_authoring_commands.py b/tests/gateway/test_session_authoring_commands.py
new file mode 100644
index 00000000000..e5e14c0a633
--- /dev/null
+++ b/tests/gateway/test_session_authoring_commands.py
@@ -0,0 +1,137 @@
+"""Authoring/workflow slash commands run the messaging gateway's own handler for a LOCAL session.
+
+``slash.exec`` on a real daemon: /plan /learn /init /initiate-setup /moa /blueprint answer with
+the turn the messaging gateway would have rewritten (a ``send`` directive the client submits with
+its own input id; nothing is admitted by the gateway), /goal sets the session's goal row and
+returns its kickoff the same way, /subgoal /loop /heartbeat write the session's own row, /review
+/refine answer from the session's cached agent, /curator /egress print their report.
+"""
+import asyncio
+import json
+from http.server import ThreadingHTTPServer
+from pathlib import Path
+import signal
+import sqlite3
+import threading
+import time
+
+import pytest
+
+from tests.gateway.fixtures.local_recovery_probe import Model, child_env, daemon, rpc, websocket
+
+
+def test_local_session_authoring_commands_run_the_gateway_handler(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()
+ (work / 'AGENTS.md').write_text('# existing instructions\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': 'authoring-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, sid = {}, {}
+
+ def admissions():
+ with sqlite3.connect(f'file:{home / "state.db"}?mode=ro', uri=True) as db:
+ return [r[0] for r in db.execute('SELECT request_id FROM session_admissions')]
+
+ def meta(key):
+ with sqlite3.connect(f'file:{home / "state.db"}?mode=ro', uri=True) as db:
+ row = db.execute('SELECT value FROM state_meta WHERE key = ?', (key,)).fetchone()
+ return json.loads(row[0]) if row else None
+
+ async def probe(desc):
+ async with websocket(home, desc) as ws:
+ created = await rpc(ws, 'session.create', request_id='authoring', source='cli', toolsets=[],
+ cwd=str(work))
+ sid['id'] = created['result']['session_id']
+ info = (await rpc(ws, 'session.info', session_id=sid['id']))['result']
+ sid['row'] = info.get('stored_session_id') or sid['id']
+ # Before any turn: /review and /refine have no cached agent yet.
+ for command in ('review', 'refine'):
+ out['cold ' + command] = await exec_(ws, command)
+ await rpc(ws, 'prompt.submit', session_id=sid['id'], input_id='warm', text='WARM_AUTHORING')
+ deadline = time.monotonic() + 45
+ while True:
+ snap = (await rpc(ws, 'session.resume', session_id=sid['id']))['result']
+ if not snap['running'] and not snap['pending'] and 'RECOVERY_ACK_WARM_AUTHORING' in json.dumps(
+ snap['messages']):
+ break
+ assert time.monotonic() < deadline, ('warm turn never settled', snap)
+ await asyncio.sleep(.1)
+ out['admitted before'] = admissions()
+ # Before /moa: its one-shot model swap evicts the cached agent (messaging behaviour).
+ out['refine focus on naming'] = await exec_(ws, 'refine focus on naming')
+ for command in ('plan add a cache', 'learn', 'init', 'initiate-setup', 'moa', 'moa compare',
+ 'blueprint', 'egress', 'curator', 'goal ship the cache', 'subgoal add tests',
+ 'goal status', 'loop every 30m check the queue', 'loop', 'heartbeat every 10m ping',
+ 'heartbeat', 'goal clear', 'loop clear', 'heartbeat clear'):
+ out[command] = await exec_(ws, command)
+ out['admitted after'] = admissions()
+
+ async def exec_(ws, command):
+ try:
+ reply = await rpc(ws, 'slash.exec', session_id=sid['id'], command=command)
+ except TimeoutError:
+ raise AssertionError(f'slash.exec {command!r} did not answer within the rpc bound') from None
+ return reply.get('result') or reply.get('error')
+
+ 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)
+
+ def send(command):
+ reply = out[command]
+ assert reply.get('type') == 'send' and reply.get('message'), (command, reply)
+ return reply
+
+ # Prompt builders: the messaging gateway's rewritten turn, returned for the client to submit.
+ plan = send('plan add a cache')
+ assert 'add a cache' in plan['message'] and plan['display'] == '/plan add a cache', plan
+ assert 'add a cache' in plan.get('notice', ''), plan
+ assert send('learn')['notice'], out['learn']
+ init = send('init')
+ assert str(work) in init['message'] and 'UPDATE the existing AGENTS.md' in init['message'], init
+ assert send('initiate-setup')['notice'], out['initiate-setup']
+ assert send('moa compare')['message'] == 'compare', out['moa compare']
+ assert out['moa']['type'] == 'exec' and '/moa' in out['moa']['output'], out['moa']
+ assert out['blueprint']['type'] == 'exec' and out['blueprint']['output'], out['blueprint']
+ assert out['egress']['type'] == 'exec' and out['egress']['output'], out['egress']
+ assert out['curator']['type'] == 'exec' and 'curator' in out['curator']['output'].lower(), out['curator']
+ # /goal: the session's own goal row, and its kickoff returned (never self-admitted).
+ goal = send('goal ship the cache')
+ assert 'ship the cache' in goal['message'] and 'ship the cache' in goal['notice'], goal
+ assert 'add tests' in out['subgoal add tests']['output'], out['subgoal add tests']
+ assert 'ship the cache' in out['goal status']['output'], out['goal status']
+ assert out['admitted after'] == out['admitted before'], (out['admitted before'], out['admitted after'])
+ # /loop, /heartbeat: state on the session's row.
+ assert '30m' in out['loop every 30m check the queue']['output'], out['loop every 30m check the queue']
+ assert 'check the queue' in out['loop']['output'], out['loop']
+ assert 'ping' in out['heartbeat every 10m ping']['output'], out['heartbeat every 10m ping']
+ assert 'ping' in out['heartbeat']['output'], out['heartbeat']
+ # /review and /refine: the session's cached agent (none before the first turn).
+ for command in ('review', 'refine'):
+ assert out['cold ' + command]['type'] == 'exec', out['cold ' + command]
+ assert out['refine focus on naming']['type'] == 'exec', out['refine focus on naming']
+ assert 'naming' in out['refine focus on naming']['output'], out['refine focus on naming']
+ for command in ('goal clear', 'loop clear', 'heartbeat clear'):
+ assert out[command]['type'] == 'exec' and out[command]['output'], (command, out[command])
+ assert (home / 'config.yaml').read_text() == config