The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(cli): bare -c, --resume latest, --list-tools(ets) and the resume footer on the gateway path
Teknium7b4a2c6ba175
diff --git a/apps/shared/src/gateway-contract.generated.ts b/apps/shared/src/gateway-contract.generated.tsindex 25836cafb4c..241040ace27 100644--- a/apps/shared/src/gateway-contract.generated.ts+++ b/apps/shared/src/gateway-contract.generated.ts@@ -4758,6 +4758,8 @@ export interface CanonicalResumeParams {profile?: string | nullsession_id?: stringtitle?: string | null+ latest?: 'cli' | 'tui' | null+ workspace?: string | nullsource?: string | nulleditor?: Record<string, unknown> | nulldefer_history?: booleandiff --git a/apps/shared/src/gateway-contract.openrpc.json b/apps/shared/src/gateway-contract.openrpc.jsonindex 97244adf0c6..d9354b7cbc7 100644--- a/apps/shared/src/gateway-contract.openrpc.json+++ b/apps/shared/src/gateway-contract.openrpc.json@@ -9357,6 +9357,34 @@"default": null,"title": "Title"},+ "latest": {+ "anyOf": [+ {+ "enum": [+ "cli",+ "tui"+ ],+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Latest"+ },+ "workspace": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Workspace"+ },"source": {"anyOf": [{diff --git a/cli.py b/cli.pyindex 3460d819308..ef6b673cc9b 100644--- a/cli.py+++ b/cli.py@@ -1686,7 +1686,7 @@ def main(q: Shorthand for --queryoneshot: With -q: force the legacy answer-and-exit single-query modeeven on a TTY.- image: Optional local image path to attach to a single query+ image: Not on the gateway path (refused; attach in `hermes --tui` or Desktop)toolsets: Comma-separated list of toolsets to enable (e.g., "web,terminal")skills: Comma-separated or repeated list of skills to preload for the sessionmodel: Model to use (default: anthropic/claude-opus-4-20250514)@@ -1695,24 +1695,25 @@ def main(api_key: API key for authenticationbase_url: Base URL for the APImax_turns: Maximum tool-calling iterations (default: 60)- verbose: Enable verbose logging- compact: Use compact display mode- list_tools: List available tools and exit- list_toolsets: List available toolsets and exit- resume: Resume a previous session by its ID (e.g., 20260225_143052_a1b2c3)- worktree: Run in an isolated git worktree (for parallel agents). Alias: -w+ verbose: Not on the gateway path (refused; `hermes logs --follow`)+ compact: Not on the gateway path (refused; `display.compact: true`)+ list_tools: List available tools and exit (no session, no gateway)+ list_toolsets: List available toolsets and exit (no session, no gateway)+ resume: Resume a previous session by id, title, or `latest`+ worktree: Not on the gateway path (refused; `hermes --tui -w`). Alias: -ww: Shorthand for --worktree-++ Every chat launch hands off to the shared gateway (hermes_cli/gateway_chat.py), which+ owns the session; the refused options are listed in+ website/docs/developer-guide/gateway-classic-cli.md.+Examples:python cli.py # Start interactive modepython cli.py --toolsets web,terminal # Use specific toolsets- python cli.py --skills hermes-agent-dev,github-authpython cli.py -q "What is Python?" # Single query mode- python cli.py -q "Describe this" --image ~/storage/shared/Pictures/cat.pngpython cli.py --list-tools # List tools and exit- python cli.py --resume 20260225_143052_a1b2c3 # Resume session- python cli.py -w # Start in isolated git worktree- python cli.py -w -q "Fix issue #123" # Single query in worktree+ python cli.py --resume latest # Resume the most recent CLI session+ python cli.py --resume local-<id> # Resume a session by the id it printed"""if not gateway:from hermes_cli.gateway_chat import launch_from_kwargsdiff --git a/gateway/session_controls.py b/gateway/session_controls.pyindex ffee7b01830..89a26dd870b 100644--- a/gateway/session_controls.py+++ b/gateway/session_controls.py@@ -346,10 +346,15 @@ class AuthorityConnection:async def resume(self, ref, params):from gateway.session_local import local_session_info- if 'title' in params:+ if 'latest' in params:+ # Bare `-c` / `--resume latest`: the most recent session of that surface family the+ # actor may read (workspace first), resolved by the owner like a title.+ from gateway.session_local_title import resolve_latest_session+ ref = resolve_latest_session(self.authority, self.actor, params['latest'], params.get('workspace'))+ elif 'title' in params:from gateway.session_local_title import resolve_titled_sessionref = resolve_titled_session(self.authority, self.actor, params['title'])- if 'title' not in params:+ else:from gateway.session_local_migration import resolve_local_targetfrom hermes_state_local_migration import LEGACY_LOCAL_SOURCESrow = self.authority.db.get_session(ref.session_id)diff --git a/gateway/session_local_title.py b/gateway/session_local_title.pyindex 3a97972f752..c175a1527b9 100644--- a/gateway/session_local_title.py+++ b/gateway/session_local_title.py@@ -34,6 +34,28 @@ def resolve_titled_session(authority, actor, name, *, missing_ok=False):return ref+def resolve_latest_session(authority, actor, family, workspace=None):+ """The most recently active session of a surface family (``cli`` = classic CLI incl. its finite+ one-shot runs, ``tui``), scoped to ``workspace`` (git root / cwd) first and then global: the+ classic ``hermes -c`` / ``--resume latest`` rule (``hermes_cli.main._resolve_last_session``),+ applied by the owner so the client opens no database. Only a local session the actor may read+ counts; another principal's sessions are skipped, never confirmed."""+ from agent.session_source import CLI_FAMILY_SOURCES+ families = {'cli': sorted(CLI_FAMILY_SOURCES), 'tui': ['tui']}+ if family not in families or (workspace is not None and (not isinstance(workspace, str) or not workspace)):+ raise RuntimeStoreError('invalid_params')+ from gateway.session_local_migration import resolve_local_target+ for scope in ([workspace] if workspace else []) + [None]:+ for row in authority.db.search_sessions(source=families[family], limit=50, workspace_key=scope):+ tip = authority.db.get_compression_tip(row['id']) or row['id']+ try:+ return resolve_local_target(authority, actor, tip)+ except RuntimeStoreError as exc:+ if exc.reason not in {'permission_denied', 'not_found', 'profile_mismatch'}:+ raise+ raise RuntimeStoreError('not_found')++def validate_title(title):from hermes_state import SessionDBtry:diff --git a/hermes_cli/gateway_chat.py b/hermes_cli/gateway_chat.pyindex 1727e033e62..17c782544b7 100644--- a/hermes_cli/gateway_chat.py+++ b/hermes_cli/gateway_chat.py@@ -17,7 +17,6 @@ _UNSUPPORTED = ("image", "worktree", "w","no_restore_cwd","run_budget", "verbose", "compact",- "list_tools", "list_toolsets",)_POLICY = ("model", "provider", "reasoning", "toolsets", "max_turns", "base_url", "ignore_rules", "api_key","yolo", "safe_mode", "ignore_user_config", "skills", "checkpoints", "accept_hooks", "pass_session_id")@@ -30,10 +29,6 @@ _RELOCATED = {"run_budget": "`agent.run_budget_seconds` in config.yaml","verbose": "`hermes logs --follow`, or `hermes chat --tui -v`","compact": "`display.compact: true` in config.yaml",- "list_tools": "`hermes tools list`",- "list_toolsets": "`hermes tools list`",- "resume latest": "`hermes --tui --resume latest`, or `hermes sessions list` then `--resume <id>`",- "continue": "`-c <name>` (or `hermes --tui -c` for the most recent session)","create-if-missing without -c <name>": "`-c <name> --create-if-missing`",}_SAFE_MODE_EXAMPLE = 'hermes chat --safe-mode --provider openrouter --model anthropic/claude-sonnet-4 -q "hello"'@@ -45,18 +40,22 @@ def bypass_launch(args) -> bool:def continue_title(args):- """``-c <name>`` (classic precedence: ignored when ``--resume`` is given). Bare ``-c`` needs the- breadcrumb/MRU lookup the authority does not expose, so it stays refused like ``--resume latest``."""+ """``-c <name>`` (classic precedence: ignored when ``--resume`` is given)."""name = getattr(args, "continue_last", None)return name if isinstance(name, str) and not getattr(args, "resume", None) else None+def wants_latest(args):+ """Bare ``-c`` or ``--resume latest`` (the keyword wins over a session titled "latest", which+ stays reachable by id or ``-c latest``)."""+ resume = getattr(args, "resume", None)+ if isinstance(resume, str):+ return resume.strip().lower() == "latest"+ return getattr(args, "continue_last", None) is True++def validate_options(args):unsupported = [name for name in _UNSUPPORTED if getattr(args, name, None)]- if getattr(args, "resume", None) == "latest":- unsupported.append("resume latest")- if getattr(args, "continue_last", None) is True:- unsupported.append("continue")if getattr(args, "create_if_missing", False) and not continue_title(args):unsupported.append("create-if-missing without -c <name>")if unsupported:@@ -76,6 +75,38 @@ def _caller_cwd(args) -> str:return str(Path(getattr(args, "in_dir", None) or os.getcwd()).expanduser().resolve())+def _workspace_key(cwd):+ """The classic CLI's workspace identity for ``-c`` (git root, else the cwd)."""+ from hermes_cli.main import _resolve_workspace_key+ previous = os.getcwd()+ try:+ os.chdir(cwd)+ return _resolve_workspace_key()+ finally:+ os.chdir(previous)+++async def _resume_latest(client, args):+ """Bare ``-c``: this terminal's breadcrumb session when the owner still has it, else (and for+ ``--resume latest``) the owner's most recent CLI session, this workspace first."""+ from hermes_cli.terminal_breadcrumbs import read_breadcrumb+ crumb = (read_breadcrumb() or {}).get("session_id") if getattr(args, "continue_last", None) is True else None+ if isinstance(crumb, str) and crumb:+ try:+ return await client.rpc("session.resume", session_id=crumb)+ except GatewayClientError as exc:+ if str(exc) not in {"not_found", "permission_denied"}:+ raise+ workspace = await asyncio.to_thread(_workspace_key, _caller_cwd(args))+ try:+ return await client.rpc("session.resume", latest="cli", **({"workspace": workspace} if workspace else {}))+ except GatewayClientError as exc:+ if str(exc) != "not_found":+ raise+ raise GatewayClientError("No previous CLI session to continue. Start a new one with `hermes`, "+ "or list sessions with `hermes sessions list`.") from None++async def run_gateway_chat(args, emitter=None):from hermes_cli.gateway_chat_view import GatewayChatViewquery = getattr(args, "query", None) or getattr(args, "q", None)@@ -90,7 +121,11 @@ async def run_gateway_chat(args, emitter=None):description = await client.rpc("runtime.describe")title = continue_title(args)create_if_missing = bool(title and getattr(args, "create_if_missing", False))- if getattr(args, "resume", None) or (title and not create_if_missing):+ latest = wants_latest(args)+ if latest:+ snapshot = await _resume_latest(client, args)+ check_resume_policy(args, snapshot)+ elif getattr(args, "resume", None) or (title and not create_if_missing):name = getattr(args, "resume", None) or titletry:# Exact id first, then title (latest lineage continuation), as the classic CLI did.@@ -136,12 +171,16 @@ async def run_gateway_chat(args, emitter=None):raise GatewayClientError("Gateway does not support creation options: " + ", ".join(missing))snapshot = await client.rpc("session.create", request_id=uuid.uuid4().hex, source=source, **policy)print("Session: " + snapshot["stored_session_id"], file=sys.stderr, flush=True)+ if not oneshot:+ from hermes_cli.terminal_breadcrumbs import write_breadcrumb+ await asyncio.to_thread(write_breadcrumb, snapshot["stored_session_id"])if emitter is not None:emitter.bind_session(snapshot["stored_session_id"])view = GatewayChatView(client, snapshot, quiet=quiet, emitter=emitter,usage_file=getattr(args, "usage_file", None))view.unattended = isinstance(oneshot_prompt, str)- if (getattr(args, "resume", None) or title) and not quiet:+ view.resume_footer = oneshot and not quiet+ if (getattr(args, "resume", None) or title or latest) and not quiet:for row in snapshot.get("messages", []):if row.get("role") in {"user", "assistant"} and isinstance(row.get("content"), str):print(f"{row['role']}: {row['content']}")@@ -221,6 +260,10 @@ def launch_from_args(args) -> int:try:validate_options(args)+ if getattr(args, "list_tools", False) or getattr(args, "list_toolsets", False):+ # A catalog listing needs no session and no gateway (main printed it and exited).+ from hermes_cli.gateway_chat_listing import print_tool_listing+ return print_tool_listing(args)_register_terminal_process()from hermes_cli.gateway_chat_startup import ensure_launch_providerif emitter is None:diff --git a/hermes_cli/gateway_chat_listing.py b/hermes_cli/gateway_chat_listing.pynew file mode 100644index 00000000000..2d0a1877c12--- /dev/null+++ b/hermes_cli/gateway_chat_listing.py@@ -0,0 +1,54 @@+"""``--list-tools`` / ``--list-toolsets`` on the gateway path: a catalog listing needs no session.++Main built a whole in-process CLI to print these and exit; the listing reads only the registry+and this profile's CLI toolset selection, so it runs in the client without an agent or a gateway.+"""+++def _selection(args):+ from hermes_cli.config import load_config+ from hermes_cli.tools_config import _get_platform_tools+ requested = getattr(args, "toolsets", None)+ if isinstance(requested, (list, tuple)):+ requested = ",".join(map(str, requested))+ if isinstance(requested, str) and requested.strip():+ return sorted({name.strip() for name in requested.split(",") if name.strip()}), []+ config = load_config()+ disabled = (config.get("agent") or {}).get("disabled_toolsets") or []+ return sorted(_get_platform_tools(config, "cli")), list(disabled)+++def print_tool_listing(args) -> int:+ from agent.i18n import t+ enabled, disabled = _selection(args)+ if getattr(args, "list_tools", False):+ from model_tools import get_tool_definitions, get_toolset_for_tool+ # Pre-assembly list, as main's /tools: deferred tool_search tools are shown too.+ tools = get_tool_definitions(enabled_toolsets=enabled, disabled_toolsets=disabled, quiet_mode=True,+ skip_tool_search_assembly=True)+ if not tools:+ print(t("cli.tools.none_available"))+ return 0+ grouped = {}+ for tool in sorted(tools, key=lambda item: item["function"]["name"]):+ name = tool["function"]["name"]+ desc = tool["function"].get("description", "").split("\n")[0]+ if ". " in desc:+ desc = desc[:desc.index(". ") + 1]+ grouped.setdefault(get_toolset_for_tool(name) or "unknown", []).append((name, desc))+ print(t("cli.tools.header"))+ for toolset in sorted(grouped):+ print(f"\n [{toolset}]")+ for name, desc in grouped[toolset]:+ print(f" * {name:<20} - {desc}")+ print(f"\n {t('cli.tools.total', count=str(len(tools)))}")+ return 0+ from toolsets import get_all_toolsets, get_toolset_info+ print(t("cli.toolsets.header"))+ for name in sorted(get_all_toolsets()):+ info = get_toolset_info(name)+ if info:+ marker = "(*)" if name in enabled else " "+ print(f" {marker} {name:<18} [{info['tool_count']:>2} tools] - {info['description']}")+ print(f"\n {t('cli.toolsets.currently_enabled_legend')}")+ return 0diff --git a/hermes_cli/gateway_chat_view.py b/hermes_cli/gateway_chat_view.pyindex 0e558270624..2608d6f896d 100644--- a/hermes_cli/gateway_chat_view.py+++ b/hermes_cli/gateway_chat_view.py@@ -31,6 +31,7 @@ class GatewayChatView:self.quiet = quiet or emitter is not Noneself.finite = Falseself.unattended = False # `-z`: the classic one-shot auto-approves; `-q` stays single-query+ self.resume_footer = False # `chat -q` without -Q: main's "Resume this session with:" blockself.finite_admission = Noneself._finite_events = []self.streams = {}@@ -406,6 +407,8 @@ class GatewayChatView:# durable id from this line, and it names the physical row (a compaction may have# advanced it past the row printed at start).print(f"\nsession_id: {self.session_id}", file=sys.stderr, flush=True)+ if self.resume_footer:+ print(resume_footer(self.session_id), flush=True)return exit_codefrom prompt_toolkit import PromptSessionfrom prompt_toolkit.patch_stdout import patch_stdout@@ -443,3 +446,13 @@ class GatewayChatView:renderer.cancel()with suppress(asyncio.CancelledError):await renderer+++def resume_footer(session_id):+ """The classic single-query exit block (``_print_exit_summary``): how to continue this session.+ A non-default profile needs ``-p`` because session ids are profile-scoped."""+ from agent.i18n import t+ from hermes_cli.profiles import get_active_profile_name+ profile = get_active_profile_name()+ flag = "" if profile in ("default", "custom") else f" -p {profile}"+ return f"\n{t('cli.session.exit_resume_hint')}\n hermes --resume {session_id}{flag}"diff --git a/tests/hermes_cli/test_gateway_chat.py b/tests/hermes_cli/test_gateway_chat.pyindex a53defd1829..df729c7569e 100644--- a/tests/hermes_cli/test_gateway_chat.py+++ b/tests/hermes_cli/test_gateway_chat.py@@ -12,10 +12,8 @@ def test_unsupported_launch_options_fail_before_connection(monkeypatch, capsys):args = argparse.Namespace(**{option: True})assert gateway_chat.launch_from_args(args) == 2assert option.replace("_", "-") in capsys.readouterr().err- # Bare -c (breadcrumb/MRU) and a nameless --create-if-missing stay refused; only a- # titled -c is a gateway-resolvable selector.- assert gateway_chat.launch_from_args(argparse.Namespace(continue_last=True)) == 2- assert "--continue" in capsys.readouterr().err+ # A nameless --create-if-missing stays refused (bare -c resolves on the owner, see+ # test_gateway_chat_flags_live.py).assert gateway_chat.launch_from_args(argparse.Namespace(create_if_missing=True)) == 2assert "create-if-missing" in capsys.readouterr().err# Creation flags on resume are judged against the frozen route: repeating the launchdiff --git a/tests/hermes_cli/test_gateway_chat_flags_live.py b/tests/hermes_cli/test_gateway_chat_flags_live.pynew file mode 100644index 00000000000..b2280a2b243--- /dev/null+++ b/tests/hermes_cli/test_gateway_chat_flags_live.py@@ -0,0 +1,91 @@+"""Gateway-path launch flags main supported: bare -c, --resume latest, --list-tools, resume footer."""+import json+from http.server import ThreadingHTTPServer+import os+from pathlib import Path+import signal+import subprocess+import sys+import threading+import time++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_continue_latest_footer_and_tool_listing(tmp_path):+ root = Path(__file__).resolve().parents[2]+ home, user = tmp_path / "state", tmp_path / "user"+ repo_a, repo_b = tmp_path / "repo-a", tmp_path / "repo-b"+ for path in (user, repo_a, repo_b):+ path.mkdir()+ home.mkdir(mode=0o700)+ for repo in (repo_a, repo_b):+ subprocess.run(["git", "init", "-q", str(repo)], check=True)+ 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": "flags-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)++ def hermes(*args, cwd, module="hermes_cli.main"):+ result = subprocess.run([sys.executable, "-m", module, *args], cwd=cwd, env=env,+ stdin=subprocess.DEVNULL, capture_output=True, text=True, timeout=120)+ sid = next((line.split("Session: ", 1)[1].strip() for line in result.stderr.splitlines()+ if line.startswith("Session: ")), None)+ return result, sid++ 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()++ empty, _ = hermes("chat", "-c", "-q", "nothing yet", "-Q", cwd=repo_a)+ assert empty.returncode == 1 and "No previous CLI session" in empty.stderr, empty++ first, sid_a = hermes("chat", "-q", "in repo a", cwd=repo_a)+ assert first.returncode == 0 and "RECOVERY_ACK_in repo a" in first.stdout, first+ # Main's single-query exit block: how to continue the session it just printed.+ assert f"Resume this session with:\n hermes --resume {sid_a}" in first.stdout, first.stdout+ quiet, sid_b = hermes("chat", "-q", "in repo b", "-Q", cwd=repo_b)+ assert quiet.returncode == 0 and "Resume this session" not in quiet.stdout, quiet++ # Bare -c continues THIS workspace's most recent CLI session, not the global newest.+ cont, cont_sid = hermes("chat", "-c", "-q", "again in a", "-Q", cwd=repo_a)+ assert cont.returncode == 0 and cont_sid == sid_a, (cont, sid_a, sid_b)+ history = json.dumps(peer.requests[-1]["messages"])+ assert "in repo a" in history and "in repo b" not in history+ latest, latest_sid = hermes("chat", "--resume", "latest", "-q", "latest in b", "-Q", cwd=repo_b)+ assert latest.returncode == 0 and latest_sid == sid_b, latest++ tools, _ = hermes("--list-toolsets", cwd=repo_a, module="cli")+ assert tools.returncode == 0 and "terminal" in tools.stdout, tools+ listing, _ = hermes("--list-tools", "--toolsets", "file", cwd=repo_a, module="cli")+ assert listing.returncode == 0 and "read_file" in listing.stdout and "[file]" in listing.stdout, listing+ finally:+ 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()diff --git a/tui_gateway/contracts/canonical_sessions.py b/tui_gateway/contracts/canonical_sessions.pyindex cc10f7e7a7b..11f90762d8d 100644--- a/tui_gateway/contracts/canonical_sessions.py+++ b/tui_gateway/contracts/canonical_sessions.py@@ -42,6 +42,10 @@ class CanonicalCreateParams(ProfileParams):class CanonicalResumeParams(ProfileParams):session_id: str = ''title: str | None = None+ # Bare `-c` / `--resume latest`: the owner resolves the most recent session of this surface+ # family (``workspace`` = the caller's git root / cwd, tried first).+ latest: Literal['cli', 'tui'] | None = None+ workspace: str | None = Nonesource: str | None = Noneeditor: dict[str, JsonValue] | None = Nonedefer_history: bool = False