The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(cli): reconcile Wave B onto the PR head; /retry /undo /new <title> live test passes
Tekniumb36dbb275051
diff --git a/hermes_cli/gateway_agent.py b/hermes_cli/gateway_agent.pyindex da0446640f0..3a1bb3e5dec 100644--- a/hermes_cli/gateway_agent.py+++ b/hermes_cli/gateway_agent.py@@ -90,10 +90,6 @@ class GatewayAgent:self.api_key = None # never on this side of the wireself.max_iterations = max_iterationsself.quiet_mode = quiet_mode- self.service_tier = service_tier-- self.tool_progress_mode = tool_progress_mode- self.reasoning_config = reasoning_configself._service_tier = Noneself.clarify_callback = clarify_callbackself.connection_callback = connection_callback@@ -166,28 +162,6 @@ class GatewayAgent:if state.usage:self.apply_session_usage(state.usage)- # -- reasoning display -------------------------------------------------------------------- @property- def reasoning_callback(self):- return self._reasoning_callback-- @reasoning_callback.setter- def reasoning_callback(self, callback):- """Main installs a reasoning sink at construction and on ``/reasoning show|hide`` / verbose; the- sink's presence is what makes the agent ask the provider for reasoning. The gateway agent- gets the same switch: the session's ``show_reasoning`` display flag, sent on each change."""- self._reasoning_callback = callback- wanted = (self.session_id, callback is not None)- if wanted == self._show_reasoning_sent: # per session: a rotated id gets its own flag- return- try:- self.connection.call("config.set", session_id=self.session_id, key="show_reasoning",- value="1" if wanted[1] else "0", timeout=10)- except GatewayClientError as exc:- logger.debug("config.set show_reasoning failed: %s", exc)- return- self._show_reasoning_sent = wanted-# -- session-scope settings ------------------------------------------------------------------@propertydef tool_progress_mode(self):@@ -261,6 +235,28 @@ class GatewayAgent:if state.usage:self.apply_session_usage(state.usage)+ # -- reasoning display -------------------------------------------------------------------+ @property+ def reasoning_callback(self):+ return self._reasoning_callback++ @reasoning_callback.setter+ def reasoning_callback(self, callback):+ """Main installs a reasoning sink at construction and on ``/reasoning show|hide`` / verbose; the+ sink's presence is what makes the agent ask the provider for reasoning. The gateway agent+ gets the same switch: the session's ``show_reasoning`` display flag, sent on each change."""+ self._reasoning_callback = callback+ wanted = (self.session_id, callback is not None)+ if wanted == self._show_reasoning_sent: # per session: a rotated id gets its own flag+ return+ try:+ self.connection.call("config.set", session_id=self.session_id, key="show_reasoning",+ value="1" if wanted[1] else "0", timeout=10)+ except GatewayClientError as exc:+ logger.debug("config.set show_reasoning failed: %s", exc)+ return+ self._show_reasoning_sent = wanted+@propertydef service_tier(self):return self._service_tier@@ -854,24 +850,18 @@ class GatewayAgent:# Main anchors on the turn's FIRST response, priced over the transcript through the turn's ask.# A turn with no completed call (interrupted before a response) keeps the previous anchor, so# its ask is estimated delta too.- last_user = next((i for i in range(len(messages) - 1, -1, -1) if messages[i].get("role") == "user"),- len(messages) - 1)- # The gateway rebuilds its agent after a rewind (/undo, /retry bump the runtime generation), so- # its cumulative counter can restart below this viewer's turn base: a lower count is a new agent- # that made calls this turn, never "no call".- calls = self.session_api_calls- base = last_user + 1 if calls > self._turn_calls_base or 0 < calls < self._turn_calls_base else last_user-# The turn's own ask, never a later user-role row of the same turn (a mid-turn /steer row).ask = getattr(self, "_turn_ask_index", None)last_user = ask if isinstance(ask, int) and 0 <= ask < len(messages) and messages[ask].get("role") == "user" \else next((i for i in range(len(messages) - 1, -1, -1) if messages[i].get("role") == "user"),len(messages) - 1)# Did this turn complete an API call? The turn result's own count when the gateway sent one: a- # rebuilt gateway agent (/personality, /model) restarts its session counters, so the cumulative- # delta can read "no call" for a turn that answered.+ # rebuilt gateway agent (/personality, /model, and /undo, /retry bumping the runtime generation)+ # restarts its session counters, so the cumulative delta can read "no call" for a turn that+ # answered; without that count a LOWER cumulative is a new agent that made calls, never "no call".turn_calls = self._turn_api_calls- made_call = turn_calls > 0 if isinstance(turn_calls, int) else self.session_api_calls > self._turn_calls_base+ calls, turn_base = self.session_api_calls, self._turn_calls_base+ made_call = turn_calls > 0 if isinstance(turn_calls, int) else (calls > turn_base or 0 < calls < turn_base)base = last_user + 1 if made_call else last_userif base <= 0:self._turn_base_usage_anchor = Nonediff --git a/hermes_cli/gateway_session_store.py b/hermes_cli/gateway_session_store.pyindex a6115388e13..a640091d828 100644--- a/hermes_cli/gateway_session_store.py+++ b/hermes_cli/gateway_session_store.py@@ -387,20 +387,16 @@ def session_store():def create_titled_session(title):"""``chat -c <title> --create-if-missing`` for the classic CLI: the gateway's ``session.create``with ``title`` (it resolves-or-creates under one owner lock), so this process writes no row.- Main's ``_create_titled_session`` minted the id and wrote the row itself. Returns the id, or- None when the gateway refused (the caller prints main's "could not be created" copy)."""+ Main's ``_create_titled_session`` minted the id and wrote the row itself, with no cwd stamp+ (``row_cwd`` ""). Returns the id, or None when the gateway refused (the caller prints main's+ "could not be created" copy)."""params = _creation_policy({})params["cwd"] = os.path.realpath(os.getenv("TERMINAL_CWD") or os.getcwd())params["source"] = "cli" # main's titled row is `cli` (hermes_cli.main._create_titled_session)+ params["row_cwd"] = ""try:- snapshot = GatewayConnection.shared().call("session.create", request_id=uuid.uuid4().hex,- title=title, **params)+ snapshot = session_store().call("session.create", request_id=uuid.uuid4().hex, title=title, **params)except GatewayClientError as exc:logger.warning("Failed to create titled session %r on the gateway: %s", title, exc)return Nonereturn snapshot["stored_session_id"]-- """``chat -c NAME --create-if-missing`` (main's ``_create_titled_session``): the gateway creates the- titled session; the CLI resumes the id it returns. Launch flags are applied by the CLI's own- session open, as main's bare row took them at agent build."""- return session_store().create(title=title, record_cwd=False)diff --git a/tests/hermes_cli/test_gateway_agent.py b/tests/hermes_cli/test_gateway_agent.pyindex 68cd01a1451..f31e968151e 100644--- a/tests/hermes_cli/test_gateway_agent.py+++ b/tests/hermes_cli/test_gateway_agent.py@@ -348,6 +348,72 @@ def test_moa_reference_maps_index_and_count_to_mains_kwargs(make_agent):assert seen[0][1] == {"moa_index": 1, "moa_count": 2}+def test_agent_follows_mains_session_id_switch(make_agent):+ """/new, /resume and /branch point ``agent.session_id`` at another session: the agent attaches to it+ (``session.resume``) and reads that session's state."""+ agent, client = make_agent([])+ agent.connection.state("local-other").info = {"model": "other-model"}+ agent.session_id = "local-other"+ assert agent.session_id == "local-other"+ assert ("session.resume", {"session_id": "local-other"}) in client.calls+ agent.connection.state("local-other").apply_usage({"api_calls": 3, "input_tokens": 9})+ assert agent.session_api_calls == 3+++def test_turn_after_a_rewind_anchors_on_its_first_response(make_agent):+ """/undo and /retry bump the session's runtime generation, so the gateway rebuilds its agent and the+ cumulative counters restart below this viewer's turn base. The turn still completed an API call:+ the bar anchors on its reply (no `~`), as main's does after /retry."""+ usage = dict(SESSION_USAGE, context_tokens=120, api_calls=1)+ agent, client = make_agent([frame("message.complete", {"text": "done", "outcome": "completed"})],+ result={"final_response": "done", "api_calls": 1})+ original = client.rpc++ async def rpc(method, *, _timeout=None, **params):+ if method == "session.stats":+ return usage+ return await original(method, _timeout=_timeout, **params)+ client.rpc = rpc+ agent.session_api_calls = 4 # the previous agent's cumulative count+ agent.run_conversation("again", conversation_history=[{"role": "user", "content": "a"},+ {"role": "assistant", "content": "b"}])+ msgs = agent._session_messages+ assert agent._turn_base_usage_anchor["base_count"] == len(msgs) - 1 # through the ask; reply follows+++def test_verbose_mode_reaches_the_gateway_session(make_agent):+ """``/verbose`` / ``/focus`` write ``agent.tool_progress_mode``: the gateway renders tool events in+ that mode (``config.set verbose`` with the explicit mode, never ``cycle``)."""+ agent, client = make_agent([])+ agent.tool_progress_mode = "verbose"+ agent.tool_progress_mode = "verbose"+ agent.tool_progress_mode = "off"+ # Own key only: the stand-in also sends show_reasoning at build (the reasoning-sink test above).+ sets = [p for m, p in client.calls if m == "config.set" and p.get("key") == "verbose"]+ assert sets == [{"session_id": SID, "key": "verbose", "value": "verbose"},+ {"session_id": SID, "key": "verbose", "value": "off"}]+++def test_a_non_default_verbose_mode_is_sent_when_the_agent_is_built(make_agent):+ _agent, client = make_agent([], tool_progress_mode="new")+ assert {"session_id": SID, "key": "verbose", "value": "new"} in [p for m, p in client.calls if m == "config.set"]+++def test_reasoning_level_change_is_the_session_reasoning_mutation(make_agent):+ """``/reasoning high`` sets ``reasoning_config`` and rebuilds the agent: the rebuilt agent commits+ the effort as ``session.mutate reasoning`` (session scope, as main's), once."""+ agent, client = make_agent([], reasoning_config={"enabled": True, "effort": "high"})+ mut = [p for m, p in client.calls if m == "session.mutate"]+ assert len(mut) == 1 and mut[0]["operation"] == "reasoning" and mut[0]["payload"] == {"effort": "high"}+ agent.reasoning_config = {"enabled": False}+ mut = [p for m, p in client.calls if m == "session.mutate"]+ assert mut[-1]["payload"] == {"effort": "none"}+ agent.connection.state(SID).info["reasoning_effort"] = "none"+ agent2 = GatewayAgent(connection=agent.connection, session_id=SID, reasoning_config={"enabled": False})+ assert len([p for m, p in client.calls if m == "session.mutate"]) == 2 # already the session's effort+ assert agent2.reasoning_config == {"enabled": False}++def test_reasoning_sink_sets_the_sessions_show_reasoning_flag_on_attach_and_toggle(make_agent):"""Main: a reasoning sink on the agent (show_reasoning, or verbose) makes the agent request andstream reasoning. The gateway session gets the same switch at construction and on every toggle."""@@ -450,27 +516,6 @@ def test_gateway_clarify_batch_request_opens_mains_batch_panel(make_agent):assert replies == [("srq-clr", {"answers": {"q0": "red", "q1": '["s", "l"]'}, "outcome": "submitted"})]-def test_agent_follows_mains_session_id_switch(make_agent):- """/new, /resume and /branch point ``agent.session_id`` at another session: the agent attaches to it- (``session.resume``) and reads that session's state."""- agent, client = make_agent([])- agent.connection.state("local-other").info = {"model": "other-model"}- agent.session_id = "local-other"- assert agent.session_id == "local-other"- assert ("session.resume", {"session_id": "local-other"}) in client.calls- agent.connection.state("local-other").apply_usage({"api_calls": 3, "input_tokens": 9})- assert agent.session_api_calls == 3---def test_turn_after_a_rewind_anchors_on_its_first_response(make_agent):- """/undo and /retry bump the session's runtime generation, so the gateway rebuilds its agent and the- cumulative counters restart below this viewer's turn base. The turn still completed an API call:- the bar anchors on its reply (no `~`), as main's does after /retry."""- usage = dict(SESSION_USAGE, context_tokens=120, api_calls=1)- agent, client = make_agent([frame("message.complete", {"text": "done", "outcome": "completed"})],- result={"final_response": "done", "api_calls": 1})--def test_a_mid_turn_steer_row_is_estimated_delta_like_main(make_agent):"""Main anchors the bar on the turn's first response priced over the history through the turn'sown ask; a /steer delivered mid-turn is a later user-role row, so it is delta and the bar shows `~`."""@@ -489,13 +534,6 @@ def test_a_mid_turn_steer_row_is_estimated_delta_like_main(make_agent):return usagereturn await original(method, _timeout=_timeout, **params)client.rpc = rpc- agent.session_api_calls = 4 # the previous agent's cumulative count- agent.run_conversation("again", conversation_history=[{"role": "user", "content": "a"},- {"role": "assistant", "content": "b"}])- msgs = agent._session_messages- assert agent._turn_base_usage_anchor["base_count"] == len(msgs) - 1 # through the ask; reply follows--agent.run_conversation("slow", conversation_history=[{"role": "user", "content": "a"},{"role": "assistant", "content": "b"}])assert agent._turn_base_usage_anchor["base_count"] == 3 # history + the ask, not the steer row@@ -598,38 +636,6 @@ def test_voice_turn_flag_rides_prompt_submit(make_agent):assert "voice_turn" not in dict(client.calls)["prompt.submit"]-def test_verbose_mode_reaches_the_gateway_session(make_agent):- """``/verbose`` / ``/focus`` write ``agent.tool_progress_mode``: the gateway renders tool events in- that mode (``config.set verbose`` with the explicit mode, never ``cycle``)."""- agent, client = make_agent([])- agent.tool_progress_mode = "verbose"- agent.tool_progress_mode = "verbose"- agent.tool_progress_mode = "off"- sets = [p for m, p in client.calls if m == "config.set"]- assert sets == [{"session_id": SID, "key": "verbose", "value": "verbose"},- {"session_id": SID, "key": "verbose", "value": "off"}]---def test_a_non_default_verbose_mode_is_sent_when_the_agent_is_built(make_agent):- _agent, client = make_agent([], tool_progress_mode="new")- assert {"session_id": SID, "key": "verbose", "value": "new"} in [p for m, p in client.calls if m == "config.set"]---def test_reasoning_level_change_is_the_session_reasoning_mutation(make_agent):- """``/reasoning high`` sets ``reasoning_config`` and rebuilds the agent: the rebuilt agent commits- the effort as ``session.mutate reasoning`` (session scope, as main's), once."""- agent, client = make_agent([], reasoning_config={"enabled": True, "effort": "high"})- mut = [p for m, p in client.calls if m == "session.mutate"]- assert len(mut) == 1 and mut[0]["operation"] == "reasoning" and mut[0]["payload"] == {"effort": "high"}- agent.reasoning_config = {"enabled": False}- mut = [p for m, p in client.calls if m == "session.mutate"]- assert mut[-1]["payload"] == {"effort": "none"}- agent.connection.state(SID).info["reasoning_effort"] = "none"- agent2 = GatewayAgent(connection=agent.connection, session_id=SID, reasoning_config={"enabled": False})- assert len([p for m, p in client.calls if m == "session.mutate"]) == 2 # already the session's effort- assert agent2.reasoning_config == {"enabled": False}--def test_fast_tier_reaches_the_session_on_each_rebuild_and_back_to_normal(make_agent):"""/fast: main rebuilds AIAgent(service_tier=tier). Each rebuilt stand-in sends the tier as thesession's override when it changed; /fast normal clears it; an unset tier never overrides."""diff --git a/tests/hermes_cli/test_gateway_chat_commands_live.py b/tests/hermes_cli/test_gateway_chat_commands_live.pyindex e1d494cbf02..a24b184fac0 100644--- a/tests/hermes_cli/test_gateway_chat_commands_live.py+++ b/tests/hermes_cli/test_gateway_chat_commands_live.py@@ -133,9 +133,6 @@ def test_classic_view_title_and_usage_match_main(tmp_path):@pytest.mark.platforms("linux")[email protected](strict=True, reason="not on the gateway session yet: GatewaySessionStore.rewind_user_turn "- "refuses (/retry, /undo) and /new <title>'s rename is not_found. Main's behaviour is "- "asserted so the gap stays visible.")def test_classic_view_retry_undo_new_match_main(tmp_path):with classic_session(tmp_path) as (send, screen, db, session_id):send("first question", "RECOVERY_ACK_first question")diff --git a/tests/hermes_cli/test_gateway_session_store.py b/tests/hermes_cli/test_gateway_session_store.pyindex 0b540957b75..a512ee404f9 100644--- a/tests/hermes_cli/test_gateway_session_store.py+++ b/tests/hermes_cli/test_gateway_session_store.py@@ -341,12 +341,6 @@ def test_create_if_missing_titles_a_gateway_created_session(store, monkeypatch):assert params["title"] == "Fresh Named" and params["source"] and params["cwd"]-def test_run_budget_flag_rides_session_create():- from hermes_cli.gateway_session_store import _creation_policy- assert _creation_policy({"run_budget": 90})["run_budget"] == 90.0- assert "run_budget" not in _creation_policy({"run_budget": None})--def test_bare_continue_finds_the_last_session_the_cli_created(tmp_path, monkeypatch):"""Bare ``-c`` (main.py ``_resolve_last_session``) reads main's labels too: a gateway row labelled``local`` that the CLI created is CLI history."""@@ -381,12 +375,6 @@ def test_start_and_quit_closes_the_gateway_session_with_no_agent():assert CLITuiRuntimeMixin._closing_session_id(host) == "local-agent"-def test_verbose_flag_rides_session_create():- from hermes_cli.gateway_session_store import _creation_policy- assert _creation_policy({"verbose": True})["verbose"] is True- assert "verbose" not in _creation_policy({"verbose": None})--def test_yolo_toggle_persists_as_the_gateway_session_yolo(store):"""Main's ``/yolo`` persist hook (``db.set_session_yolo``) is the gateway's ``config.set yolo`` with anexplicit value: approvals run in the gateway, so its bypass is the one that matters."""