The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat: route normal classic and one-shot launch through the gateway
Teknium355104590758
diff --git a/cli.py b/cli.pyindex feadecd07d8..3433a065924 100644--- a/cli.py+++ b/cli.py@@ -4485,6 +4485,10 @@ def main(python cli.py -w # Start in isolated git worktreepython cli.py -w -q "Fix issue #123" # Single query in worktree"""+ if not gateway:+ from hermes_cli.gateway_chat import launch_from_kwargs+ sys.exit(launch_from_kwargs(locals()))+# UTF-8 stdio on Windows before any print (Rich box-drawing would UnicodeEncodeError on cp1252).with suppress(Exception):from hermes_cli.stdio import configure_windows_stdiodiff --git a/docs/gateway-classic-cli.md b/docs/gateway-classic-cli.mdnew file mode 100644index 00000000000..6cffdc0d115--- /dev/null+++ b/docs/gateway-classic-cli.md@@ -0,0 +1,48 @@+# Classic gateway client (initial migration)++Normal `hermes --cli`, `hermes chat`, `hermes chat -q '…' -Q`, and top-level+`hermes -z '…'` use the gateway authority. Direct `cli.main` chat launches also+hand off before constructing a local agent. Local bootstrap uses the canonical+ensure lifecycle and a single-use private control ticket, not service installation.+An explicit `HERMES_TUI_GATEWAY_URL` remains remote-only: failed connection or+authentication never launches a local replacement.++The client prints the persisted `Session:` ID to stderr. Resume with+`hermes --cli chat --resume ID`. Input is admitted with a fresh `input_id`; events+and final replies come from the authority. `/quit`, `/exit`, `/detach`, EOF and+closing the terminal detach only. `/stop` sends an execution-generation-fenced+interrupt. Pending approvals display `/approve ID once|deny|…`; clarification+uses `/answer ID TEXT`. The client uses the displayed prompt ID and its captured+generation, not a locally reconstructed waiter. Other slash commands explicitly+reject instead of running local mutations.++One-shot stdout contains only the final reply. Exit status is 0 for a completed+admission, 1 for failed execution/connection, 2 for unsupported frontend options,+3 for a pending control that requires interactive reattachment, and 130 for a+keyboard detach. A pending control does not imply cancellation. `-z` no longer+implicitly bypasses approval policy.++## Current parity limits — not full classic CLI parity++The gateway advertises its accepted creation parameters through `runtime.describe`.+Model, provider, reasoning, toolsets and max-turns are sent only when advertised;+otherwise explicitly requested options reject. Caller cwd is sent when advertised;+an old gateway lacking cwd support prints a warning that it uses its configured+execution directory, while explicit `--in` rejects. Resume retains existing+session policy; creation overrides on resume reject.++Images, skills, worktrees, checkpoints, pass-session-id, safe mode, ignored rules+or user config, YOLO, hook acceptance, continue/latest/title selection,+create-if-missing, no-restore-cwd, usage reports, run budgets, direct API credentials,+verbose/compact display and local tool listing are not implemented in this client+and reject explicitly. Full legacy presentation, slash registry parity, interactive+history editing, auto-reconnect, lost-ACK durable client journals, remote login+bootstrap, cold-owner resume and native Windows/macOS QA remain outstanding.+The client preserves an explicit remote URL's existing authentication mechanism;+it does not acquire or mint remote credentials.++`tests/hermes_cli/test_gateway_chat_native.py` exercises native tmux/PTTY classic+fresh input, detach, persisted-ID resume and one-shot through the ordinary daemon+with a loopback model, isolated HOME/HERMES_HOME and caller cwd. Constructor+instrumentation records no client AIAgent, SessionDB or GatewayRunner. This is not+yet evidence of caller-cwd execution parity on an older gateway.diff --git a/hermes_cli/main.py b/hermes_cli/main.pyindex fe33710ff3f..1b1867e6c63 100644--- a/hermes_cli/main.py+++ b/hermes_cli/main.py@@ -1653,6 +1653,9 @@ _CHAT_PASSTHROUGH = (def cmd_chat(args):"""Run interactive chat CLI."""+ if not _resolve_use_tui(args):+ from hermes_cli.gateway_chat import launch_from_args+ sys.exit(launch_from_args(args))_apply_safe_mode(args)_apply_user_config_bypass(args)_guard_noninteractive_user_config(args)@@ -2878,15 +2881,8 @@ def _run_oneshot_from_args(args) -> None:Bypasses cli.py entirely; _run_and_exit_oneshot never returns."""- _confirm_startup_expensive_model_override(args)- _run_and_exit_oneshot(- args.oneshot,- model=getattr(args, "model", None),- provider=getattr(args, "provider", None),- toolsets=getattr(args, "toolsets", None),- skills=getattr(args, "skills", None),- usage_file=getattr(args, "usage_file", None),- )+ from hermes_cli.gateway_chat import launch_from_args+ sys.exit(launch_from_args(args))def _light_chat_parser():diff --git a/tests/hermes_cli/test_gateway_chat_native.py b/tests/hermes_cli/test_gateway_chat_native.pynew file mode 100644index 00000000000..b6bf56f1d1b--- /dev/null+++ b/tests/hermes_cli/test_gateway_chat_native.py@@ -0,0 +1,133 @@+"""Native PTY clients against an ordinary daemon and loopback model only."""+import json+import os+from pathlib import Path+import shlex+import signal+import subprocess+import sys+import time+import uuid++import pytest++from tests.gateway.test_normal_runtime_boot import control, model_peer # noqa: F401++[email protected]_only+def test_native_classic_fresh_resume_and_oneshot(tmp_path, model_peer):+ home = tmp_path / "state"+ home.mkdir(mode=0o700)+ user = tmp_path / "user"+ user.mkdir()+ cwd = tmp_path / "caller"+ cwd.mkdir()+ root = Path(__file__).resolve().parents[2]+ model_url = f"http://127.0.0.1:{model_peer.server_port}/v1"+ (home / "config.yaml").write_text(json.dumps({+ "gateway": {"multiplex_profiles": False},+ "model": {"provider": "custom", "default": "local-wire-stub", "base_url": model_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=model_url)+ # Instrument constructor calls without replacing runtime predicates or behavior.+ wrapper = tmp_path / "client.py"+ witness = tmp_path / "client-owner.json"+ wrapper.write_text('''import json, runpy, sys+from pathlib import Path+owners = []+def trace(frame, event, arg):+ if event == 'call' and frame.f_code.co_name == '__init__':+ obj = frame.f_locals.get('self')+ if type(obj).__name__ in {'AIAgent', 'SessionDB', 'GatewayRunner'}:+ owners.append(type(obj).__name__)+sys.setprofile(trace)+try:+ runpy.run_module('hermes_cli.main', run_name='__main__')+finally:+ sys.setprofile(None)+ Path(sys.argv[0]).with_name('client-owner.json').write_text(json.dumps(owners))+''')+ # argv[0] is replaced by runpy, so the witness path is explicitly bound.+ wrapper.write_text(wrapper.read_text().replace("Path(sys.argv[0]).with_name('client-owner.json')", repr(str(witness)) + " and Path(" + repr(str(witness)) + ")"))+ tmux_name = "hermes-cli-test-" + 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():+ result = tmux("capture-pane", "-p", "-S", "-1000", "-t", "chat")+ return result.stdout++ def until(text, timeout=45):+ deadline = time.monotonic() + timeout+ output = ""+ while time.monotonic() < deadline:+ output = screen()+ if text in output:+ return output+ time.sleep(.1)+ raise AssertionError((text, output, log_path.read_text()))++ def launch(*args):+ command = shlex.join([sys.executable, str(wrapper), *args])+ result = tmux("new-session", "-d", "-s", "chat", "-x", "160", "-y", "45", "-c", str(cwd),+ command + '; rc=$?; printf "\\nCLI_RC=%s\\n" "$rc"; sleep 120')+ assert result.returncode == 0, result.stderr++ log_path = tmp_path / "gateway.log"+ with log_path.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 = time.monotonic() + 40+ descriptor = {}+ while daemon.poll() is None and time.monotonic() < deadline:+ try:+ descriptor = control(home, "identify")+ if descriptor.get("state") == "ready":+ break+ except (OSError, ValueError):+ pass+ time.sleep(.1)+ assert descriptor.get("state") == "ready", log_path.read_text()+ launch("--cli", "chat")+ first = until("You>")+ sid = next(line.split("Session: ", 1)[1].strip() for line in first.splitlines() if "Session: " in line)+ tmux("send-keys", "-t", "chat", "WS_SHARED", "Enter")+ fresh = until("LOCAL_ACK_WS_SHARED")+ tmux("send-keys", "-t", "chat", "/quit", "Enter")+ detached = until("CLI_RC=0")+ assert json.loads(witness.read_text()) == [], witness.read_text()+ assert daemon.poll() is None+ tmux("kill-session", "-t", "chat")++ launch("--cli", "chat", "--resume", sid, "-q", "WS_SHARED resumed", "-Q")+ resumed = until("CLI_RC=0")+ assert "LOCAL_ACK_WS_SHARED" in resumed+ assert json.loads(witness.read_text()) == []+ tmux("kill-session", "-t", "chat")++ launch("-z", "WS_SHARED oneshot")+ oneshot = until("CLI_RC=0")+ assert "LOCAL_ACK_WS_SHARED" in oneshot+ assert json.loads(witness.read_text()) == []+ assert control(home, "identify")["instance_id"] == descriptor["instance_id"]+ assert len(model_peer.requests) == 3+ receipt = {"session_id": sid, "daemon_pid": daemon.pid,+ "same_instance": descriptor["instance_id"], "client_agent_db_owners": [],+ "fresh": fresh, "detach": detached, "resume": resumed, "oneshot": oneshot}+ print("CLI_PTY_RECEIPT=" + json.dumps(receipt))+ 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)