The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(cli): the classic gateway view runs /title /undo /retry /new /reset /usage /tools and the gateway reads
Teknium782033bf53ef
diff --git a/hermes_cli/gateway_chat_commands.py b/hermes_cli/gateway_chat_commands.pynew file mode 100644index 00000000000..407ed8fa3ee--- /dev/null+++ b/hermes_cli/gateway_chat_commands.py@@ -0,0 +1,204 @@+"""Classic CLI slash commands on the shared gateway, beyond the view's own controls.++``GatewayChatView.command`` answers the controls it owns (/stop /approve /answer /discard+/branch /model /compress /yolo /quit). This module adds the session commands main's classic+CLI ran in-process, mapped onto what the owner serves -- the mapping Ink uses+(``ui-tui/src/app/slash/canonicalSessionCommands.ts``):++- ``/title <name>`` -> ``session.mutate rename``; bare ``/title`` -> the owner's report+- ``/undo [N]`` / ``/retry`` -> ``session.mutate rewind`` to the Nth-newest user turn+ (``/undo`` puts the removed text back in the composer, ``/retry`` resubmits it)+- ``/new [title]`` / ``/reset`` -> ``session.create`` with this session's frozen launch request+- ``/usage`` -> the owner's session report plus this view's last committed turn+- ``/tools`` -> the toolsets frozen at launch+- every other registry command -> ``slash.exec``: the owner runs its reviewed reads and+ refuses the rest, which prints where the command stands (the parity table below).+"""+import sys+import uuid++from hermes_cli.gateway_client import GatewayClientError++PARITY_DOC = "https://hermes-agent.nousresearch.com/docs/developer-guide/gateway-command-parity"++# Registry command (canonical name) -> how the classic view answers it itself. Every other+# registry command goes to the owner through ``slash.exec``. Read by the parity inventory+# (scripts/gen_gateway_command_parity.py).+VIEW_ROUTES = {+ "quit": "detach", "stop": "session.interrupt", "approve": "approval.respond (prompt id)",+ "branch": "session.mutate branch", "model": "session.mutate model", "compress": "session.mutate compress",+ "yolo": "config.set yolo", "help": "local",+ "title": "session.mutate rename", "undo": "session.mutate rewind", "retry": "session.mutate rewind + resubmit",+ "new": "session.create", "clear": "session.create", "usage": "slash.exec + last-turn receipt",+ "tools": "session.info launch toolsets",+}+++def refusal(name):+ return f"/{name} is not available on the shared gateway yet. Parity table: {PARITY_DOC}"+++def _user_turns(snapshot):+ """Human-authored user rows (``row_id`` = durable ``messages.id``), oldest first: no display-only+ kind other than a typed /steer, never a compaction handoff carrier."""+ from agent.context_compressor import is_user_originated_turn+ return [row for row in snapshot.get("messages", [])+ if type(row.get("row_id")) is int and row.get("display_kind") in (None, "", "steer")+ and is_user_originated_turn(row)]+++def _rewind_to(turns_back):+ def payload(snapshot):+ turns = _user_turns(snapshot)+ return {"target_message_id": turns[-turns_back]["row_id"]} if len(turns) >= turns_back else None+ return payload+++async def _mutate(view, operation, payload):+ result = await view.mutations.apply(view.client, view.session_id, operation, payload)+ view.mutations.acknowledge(view.session_id, operation, payload)+ return result+++async def _rewind(view, turns_back):+ """The rewound user turn's text, or None when there was nothing to rewind."""+ result = await _mutate(view, "rewind", _rewind_to(turns_back))+ if result.get("status") == "nothing" or not result.get("rewound_count"):+ return None+ snapshot = await view.client.rpc("session.resume", session_id=view.session_id)+ view.generation = snapshot["execution_generation"]+ content = (result.get("target_message") or {}).get("content")+ return content if isinstance(content, str) else "", result["rewound_count"]+++async def _title(view, rest):+ if not rest:+ return await forward(view, "title", "")+ result = await _mutate(view, "rename", {"title": rest})+ print(f"Session title set: {result.get('title') or rest}")+++async def _undo(view, rest):+ from agent.i18n import t+ if rest and not (rest.isdigit() and int(rest) > 0):+ raise GatewayClientError("Usage: /undo [N]")+ turns = int(rest or 1)+ rewound = await _rewind(view, turns)+ if rewound is None:+ print(t("cli.session.undo_no_user_message"))+ return+ text, count = rewound+ print(f"Undid {turns} turn{'s' if turns != 1 else ''} ({count} message(s)); the removed message is in the composer.")+ view.prefill = text+++async def _retry(view, rest):+ from agent.i18n import t+ rewound = await _rewind(view, 1)+ if rewound is None or not rewound[0].strip():+ print(t("cli.session.retry_no_user_message"))+ return+ print(f"\n{'─' * 40}\n● {rewound[0]}", flush=True)+ await view.submit(rewound[0])+++async def _new(view, rest):+ """A fresh session with this one's frozen launch request (model, toolsets, cwd, ...); the old+ session stays resumable by its id. A title is a separate rename so an existing title is a+ conflict, never a silent attach to that other session."""+ from agent.i18n import t+ info = await view.client.rpc("session.info", session_id=view.session_id)+ accepted = set((await view.client.rpc("runtime.describe")).get("session_create", {}).get("parameters", []))+ request = {key: value for key, value in (info.get("launch_request") or {}).items()+ if key in accepted and key not in {"request_id", "title"}}+ if info.get("cwd") and "cwd" in accepted:+ request["cwd"] = info["cwd"]+ snapshot = await view.client.rpc("session.create", request_id=uuid.uuid4().hex, **request)+ await view.adopt(snapshot)+ print(t("cli.session.new_session"))+ print(f"Session: {view.session_id}", file=sys.stderr, flush=True)+ if rest:+ await _title(view, rest)+++async def _usage(view, rest):+ if rest: # `/usage reset` redeems a credit: the owner decides (and refuses it for local sessions)+ return await forward(view, "usage", rest)+ await forward(view, "usage", "")+ admission = next(reversed(view.completions), None)+ if admission is None:+ return+ receipt = await view.client.rpc("prompt.receipt", session_id=view.session_id,+ admission_id=admission, include_result=True)+ result = receipt.get("result") or {}+ if not isinstance(result, dict) or not result:+ return+ lines = ["", "Last turn:", f" Model: {result.get('model') or view.model}"]+ for label, key in (("Input tokens", "input_tokens"), ("Output tokens", "output_tokens"),+ ("Total tokens", "total_tokens"), ("API calls", "api_calls")):+ lines.append(f" {label}: {int(result.get(key) or 0):,}")+ if isinstance(result.get("estimated_cost_usd"), (int, float)):+ lines.append(f" Cost: ${result['estimated_cost_usd']:.4f}")+ print("\n".join(lines))+++async def _tools(view, rest):+ info = await view.client.rpc("session.info", session_id=view.session_id)+ toolsets = (info.get("launch_request") or {}).get("toolsets")+ if isinstance(toolsets, list) and toolsets:+ print("Toolsets frozen at launch: " + ", ".join(map(str, toolsets)))+ else:+ print("This session runs the profile's CLI toolsets as they were at launch (`hermes tools list`).")+ print("Changing toolsets mid-session (/tools enable|disable) " + refusal("tools").split(" ", 1)[1])+++async def forward(view, name, rest):+ """Run a registry command (or a skill) on the owner; its refusal names where the command stands."""+ from hermes_cli.gateway_client import GatewayRPCError+ try:+ reply = await view.client.rpc("slash.exec", session_id=view.session_id,+ command=name + (" " + rest if rest else ""))+ except GatewayRPCError as exc:+ if str(exc) != "unsupported_command":+ raise+ from hermes_cli.commands import resolve_command+ print(refusal(name) if resolve_command(name) else f"Unknown command: /{name} (use /help)")+ return+ if reply.get("type") == "skill":+ # A skill directive is the client's durable submit (same contract as Ink and Desktop).+ print(f"\n{'─' * 40}\n● {reply.get('display') or '/' + name}", flush=True)+ await view.submit(reply["message"])+ else:+ print(reply.get("output") or f"/{name}: no output")+++_VIEW_CONTROLS = frozenset({"quit", "stop", "approve", "branch", "model", "compress", "yolo", "help"})+# /clear is main's "new session + clear screen"; the gateway view keeps scrollback and starts fresh.+_HANDLERS = {"title": _title, "undo": _undo, "retry": _retry, "new": _new, "clear": _new, "usage": _usage,+ "tools": _tools}+++async def run_command(view, command, rest):+ """Any slash command the view's own controls did not take."""+ from hermes_cli.commands import resolve_command+ name = command.lstrip("/")+ definition = resolve_command(name)+ canonical = definition.name if definition else name+ if canonical in _VIEW_CONTROLS and canonical != name:+ # An alias of a control the view owns (/fork, /compact, /exit): answer it as the canonical.+ return await view.command(f"/{canonical} {rest}".rstrip())+ handler = _HANDLERS.get(canonical)+ if handler is not None:+ await handler(view, rest.strip())+ else:+ await forward(view, canonical, rest.strip())+ return True+++def help_text():+ from gateway.session_commands import _READ_COMMANDS+ reports = " ".join(f"/{name}" for name in sorted(_READ_COMMANDS - {"help"}))+ return ("/stop, /approve <id> <choice>, /answer <id> <text>, /discard <admission_id> (turn lost during "+ "restart), /yolo [on|off], /quit (detach). /branch [title], /model <model> [--provider name], "+ "/compress [here [N] | <focus>] [--preview]. /title [name], /undo [N], /retry, /new [title] "+ f"(/reset), /usage, /tools.\nReports run by the gateway: {reports}.\nParity table: {PARITY_DOC}")diff --git a/hermes_cli/gateway_chat_view.py b/hermes_cli/gateway_chat_view.pyindex 3f42ce4fb7c..0e558270624 100644--- a/hermes_cli/gateway_chat_view.py+++ b/hermes_cli/gateway_chat_view.py@@ -45,6 +45,8 @@ class GatewayChatView:# The interactive composer (set by ``run``); None in one-shot / non-TTY runs, where a# guarded model switch stays a refusal instead of a prompt.self._composer = None+ # `/undo` puts the removed message back in the composer for the next prompt.+ self.prefill = ""def unknown_admissions(self):return [row["admission_id"] for row in self.pending if row["status"] == "unknown"]@@ -111,7 +113,8 @@ class GatewayChatView:"""The next composer line, or ``""`` once the event stream failed first (``self.failure``is then set). The pending read is cancelled (prompt_toolkit restores the terminal) so thecaller reports the unknown outcome without waiting for a keypress."""- reader = asyncio.ensure_future(prompt.prompt_async(symbol))+ default, self.prefill = self.prefill, ""+ reader = asyncio.ensure_future(prompt.prompt_async(symbol, **({"default": default} if default else {})))failed = asyncio.ensure_future(self.failed.wait())try:await asyncio.wait({reader, failed}, return_when=asyncio.FIRST_COMPLETED)@@ -248,10 +251,7 @@ class GatewayChatView:print('\n'.join(result['lines']))return Truetarget = result.get('branched_session_id', original)- snapshot = await self.client.rpc('session.resume', session_id=target)- self.session_id = target- self.generation = snapshot['execution_generation']- self.prompts = {p['prompt_id']: p for p in snapshot.get('prompts', [])}+ await self.adopt(await self.client.rpc('session.resume', session_id=target))self.mutations.acknowledge(original, operation, payload)if operation == 'model' and result.get('model'):self.model = str(result['model']).split('/')[-1]@@ -266,10 +266,19 @@ class GatewayChatView:**({"value": "1" if word == "on" else "0"} if word else {}))print(f"YOLO {'on' if result.get('value') == '1' else 'off'} for this session")return True+ from hermes_cli import gateway_chat_commandsif command == "/help":- print("/stop, /approve <id> <choice>, /answer <id> <text>, /discard <admission_id> (turn lost during restart), /yolo [on|off], /quit (detach). /branch [title], /model <model> [--provider name], /compress [here [N] | <focus>] [--preview].")+ print(gateway_chat_commands.help_text())return True- raise GatewayClientError("Unsupported gateway CLI command; use /help. No local command was run.")+ return await gateway_chat_commands.run_command(self, command, rest)++ async def adopt(self, snapshot):+ """Attach this view to another session's snapshot (a branch, /new)."""+ self.session_id = snapshot['stored_session_id']+ self.generation = snapshot['execution_generation']+ self.prompts = {p['prompt_id']: p for p in snapshot.get('prompts', [])}+ self.pending = snapshot.get('pending', [])+ self.model = str((snapshot.get('info') or {}).get('model') or self.model).split('/')[-1]async def _confirm_model_switch(self, refusal):"""The owner refused a guarded model target (cost / data policy / large context): ask asdiff --git a/hermes_cli/gateway_mutations.py b/hermes_cli/gateway_mutations.pyindex de2a15d4258..c3dbcbb0218 100644--- a/hermes_cli/gateway_mutations.py+++ b/hermes_cli/gateway_mutations.py@@ -16,14 +16,22 @@ class PreparedMutations:retained mutation once with ``payload.confirm`` = the owner's token (under the originalkey, so an ambiguous reply to the confirmed send retries that exact request); no answers``status: cancelled``. Without a prompt (non-interactive) the refusal is an error, and a- confirmed send refused again (another switch or a turn landed first) is never re-asked."""- encoded = json.dumps(payload, sort_keys=True)- key = (session_id, operation, encoded)+ confirmed send refused again (another switch or a turn landed first) is never re-asked.++ ``payload`` may be a function of the snapshot the CAS tuple is read from (a rewind names+ its target row from that same transcript); returning None means "nothing to do" and is+ answered ``status: nothing``. A derived payload is keyed by operation alone, so a lost-reply+ retry re-presents the original target instead of re-deriving one from an already-rewound+ transcript. Metadata edits (``rename``) carry no generation fence, as on Ink/Desktop."""+ key = _key(session_id, operation, payload)if key not in self.pending:snapshot = await client.rpc('session.resume', session_id=session_id)- self.pending[key] = {'params': dict(session_id=session_id, operation=operation,- payload=json.loads(encoded), request_id=uuid.uuid4().hex,- expected_revision=snapshot['revision'], expected_generation=snapshot['execution_generation'])}+ body = payload(snapshot) if callable(payload) else json.loads(key[2])+ if body is None:+ return {'status': 'nothing', 'session_id': session_id, 'operation': operation}+ fence = {} if operation in _METADATA else {'expected_generation': snapshot['execution_generation']}+ self.pending[key] = {'params': dict(session_id=session_id, operation=operation, payload=body,+ request_id=uuid.uuid4().hex, expected_revision=snapshot['revision'], **fence)}entry = self.pending[key]while 'result' not in entry:try:@@ -61,7 +69,14 @@ class PreparedMutations:return entry['result']def acknowledge(self, session_id, operation, payload):- self.pending.pop((session_id, operation, json.dumps(payload, sort_keys=True)), None)+ self.pending.pop(_key(session_id, operation, payload), None)+++_METADATA = frozenset({'rename'})+++def _key(session_id, operation, payload):+ return (session_id, operation, None if callable(payload) else json.dumps(payload, sort_keys=True))def model_refusal_text(refusal, *, confirmed=False):diff --git a/tests/hermes_cli/test_gateway_chat_commands_live.py b/tests/hermes_cli/test_gateway_chat_commands_live.pynew file mode 100644index 00000000000..6cadbb9fa9c--- /dev/null+++ b/tests/hermes_cli/test_gateway_chat_commands_live.py@@ -0,0 +1,116 @@+"""Classic `hermes --cli chat` session commands on the shared gateway, driven in a real PTY."""+import json+from http.server import ThreadingHTTPServer+import os+from pathlib import Path+import shlex+import signal+import sqlite3+import subprocess+import sys+import threading+import time+import uuid++import pytest++from tests.gateway.fixtures.local_recovery_probe import Model+from tests.gateway.test_normal_runtime_boot import control++[email protected]("linux")+def test_classic_view_title_undo_retry_new_usage_tools_and_reads(tmp_path):+ root = Path(__file__).resolve().parents[2]+ home, user, cwd = tmp_path / "state", tmp_path / "user", tmp_path / "caller"+ home.mkdir(mode=0o700)+ user.mkdir()+ cwd.mkdir()+ peer = ThreadingHTTPServer(("127.0.0.1", 0), Model)+ peer.requests = []+ peer.blocked, peer.release = threading.Event(), threading.Event()+ threading.Thread(target=peer.serve_forever, daemon=True).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": "view-model", "base_url": url},+ "auxiliary": {"title_generation": {"enabled": False}}}))+ 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)+ tmux_name = "hermes-cli-cmds-" + uuid.uuid4().hex++ def tmux(*args):+ return subprocess.run(["tmux", "-L", tmux_name, *args], env=env, stdin=subprocess.DEVNULL,+ capture_output=True, text=True, timeout=10)++ def screen():+ return tmux("capture-pane", "-p", "-J", "-S", "-3000", "-t", "chat").stdout++ def send(line, expect, timeout=45):+ # The pane is fixed-height (blank rows pad it), so a new answer is one more occurrence.+ seen = screen().count(expect)+ tmux("send-keys", "-t", "chat", "-l", line)+ tmux("send-keys", "-t", "chat", "Enter")+ deadline = time.monotonic() + timeout+ while time.monotonic() < deadline:+ current = screen()+ if current.count(expect) > seen:+ return current+ time.sleep(.1)+ raise AssertionError((line, expect, screen(), (home / "gw.log").read_text()))++ def db(sql, *args):+ with sqlite3.connect(f"file:{home / 'state.db'}?mode=ro", uri=True) as conn:+ return conn.execute(sql, args).fetchall()++ with (home / "gw.log").open("w") as log:+ daemon = subprocess.Popen([sys.executable, "-m", "gateway.run"], cwd=root, env=env,+ stdin=subprocess.DEVNULL, stdout=log, stderr=subprocess.STDOUT)+ try:+ deadline, desc = time.monotonic() + 60, {}+ while daemon.poll() is None and time.monotonic() < deadline and desc.get("state") != "ready":+ try:+ desc = control(home, "identify")+ except (OSError, ValueError):+ time.sleep(.1)+ assert desc.get("state") == "ready", (home / "gw.log").read_text()+ command = shlex.join([sys.executable, "-m", "hermes_cli.main", "--cli", "chat"])+ tmux("new-session", "-d", "-s", "chat", "-x", "200", "-y", "50", "-c", str(cwd),+ command + '; printf "\\nCLI_RC=%s\\n" "$?"; sleep 120')+ send("", "Welcome to Hermes", 60)+ sid = next(line.split("Session: ", 1)[1].strip() for line in screen().splitlines() if "Session: " in line)+ send("first question", "RECOVERY_ACK_first question")+ send("second question", "RECOVERY_ACK_second question")+ send("/title View Title", "Session title set: View Title")+ assert db("SELECT title FROM sessions WHERE id=?", sid) == [("View Title",)]+ send("/title", "**View Title**")+ send("/usage", "Last turn:")+ send("/tools", "not available on the shared gateway yet")+ send("/retry", "RECOVERY_ACK_second question")+ active = [r[0] for r in db("SELECT content FROM messages WHERE session_id=? AND active=1 AND role='user'", sid)]+ assert active == ["first question", "second question"], active+ send("/undo", "Undid 1 turn")+ # The removed message is back in the composer: Enter alone resubmits it.+ send("", "RECOVERY_ACK_second question")+ send("/memory", "No pending memory writes")+ send("/insights", "**Sessions:** 1")+ send("/fast", "/fast is not available on the shared gateway yet")+ send("/new Second Thread", "Session title set: Second Thread")+ second = [line.split("Session: ", 1)[1].strip() for line in screen().splitlines() if "Session: " in line][-1]+ assert second != sid+ assert db("SELECT title FROM sessions WHERE id=?", second) == [("Second Thread",)]+ send("third question", "RECOVERY_ACK_third question")+ assert db("SELECT COUNT(*) FROM messages WHERE session_id=? AND role='user'", second) == [(1,)]+ send("/quit", "CLI_RC=0")+ assert "Unsupported gateway CLI command" not in screen()+ finally:+ tmux("kill-server")+ if daemon.poll() is None:+ daemon.send_signal(signal.SIGINT)+ try:+ daemon.wait(timeout=20)+ except subprocess.TimeoutExpired:+ daemon.kill()+ daemon.wait(timeout=5)+ peer.shutdown()+ peer.server_close()