The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(cli): classic /retry validates the target turn before rewinding it
Teknium431cf9abdb7b
diff --git a/hermes_cli/gateway_chat_commands.py b/hermes_cli/gateway_chat_commands.pyindex dabe3e5a5f3..7135407a264 100644--- a/hermes_cli/gateway_chat_commands.py+++ b/hermes_cli/gateway_chat_commands.py@@ -14,6 +14,7 @@ CLI ran in-process, mapped onto what the owner serves -- the mapping Ink uses- every other registry command -> ``slash.exec``: the owner runs its reviewed reads andrefuses the rest, which prints where the command stands (the parity table below)."""+import contextlibimport sysimport uuid@@ -47,10 +48,21 @@ def _user_turns(snapshot):and is_user_originated_turn(row)]-def _rewind_to(turns_back):+def _rewind_to(turns_back, *, retry=False):def payload(snapshot):turns = _user_turns(snapshot)- return {"target_message_id": turns[-turns_back]["row_id"]} if len(turns) >= turns_back else None+ if len(turns) < turns_back:+ return None+ target = turns[-turns_back]+ if retry:+ # Main's retry_last order: a turn that cannot be resent losslessly as text (an image+ # turn) is refused on the CAS snapshot, before session.mutate archives it.+ from agent.context_compressor import retryable_user_text, user_originated_turn_view+ try:+ retryable_user_text((user_originated_turn_view(target) or {}).get("content"))+ except ValueError as exc:+ raise GatewayClientError(f"/retry: {exc}") from exc+ return {"target_message_id": target["row_id"]}return payload@@ -60,14 +72,19 @@ async def _mutate(view, 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))+async def _rewind(view, turns_back, *, retry=False):+ """The rewound user turn's text (``/retry``: its lossless resend text), or None when there was+ nothing to rewind."""+ result = await _mutate(view, "rewind", _rewind_to(turns_back, retry=retry))if result.get("status") == "nothing" or not result.get("rewound_count"):return Nonesnapshot = await view.client.rpc("session.resume", session_id=view.session_id)view.generation = snapshot["execution_generation"]content = (result.get("target_message") or {}).get("content")+ if retry:+ from agent.context_compressor import retryable_user_text+ with contextlib.suppress(ValueError):+ return retryable_user_text(content), result["rewound_count"]return content if isinstance(content, str) else "", result["rewound_count"]@@ -94,7 +111,7 @@ async def _undo(view, rest):async def _retry(view, rest):from agent.i18n import t- rewound = await _rewind(view, 1)+ rewound = await _rewind(view, 1, retry=True)if rewound is None or not rewound[0].strip():print(t("cli.session.retry_no_user_message"))returndiff --git a/tests/hermes_cli/test_gateway_chat_retry_validate.py b/tests/hermes_cli/test_gateway_chat_retry_validate.pynew file mode 100644index 00000000000..fdbd677fddb--- /dev/null+++ b/tests/hermes_cli/test_gateway_chat_retry_validate.py@@ -0,0 +1,68 @@+"""Classic /retry validates the target turn before rewinding it (dokterdok N92): real authority,+SQLite and AuthorityConnection.dispatch; an image turn is refused with nothing archived, a text-parts+turn is resubmitted as its lossless text."""+import asyncio+from types import SimpleNamespace+from unittest.mock import AsyncMock++import pytest+++class _Bridge:+ def __init__(self, connection):+ self.connection, self.events = connection, asyncio.Queue()++ async def rpc(self, method, **params):+ from hermes_cli.gateway_client import GatewayClientError+ reply = await self.connection.dispatch({'id': 1, 'method': method, 'params': params})+ if 'error' in reply:+ raise GatewayClientError(reply['error']['message'])+ return reply['result']+++IMAGE = {'type': 'image_url', 'image_url': {'url': 'data:image/png;base64,AA=='}}++[email protected]('content, submitted', [+ ([{'type': 'text', 'text': 'what is '}, {'type': 'text', 'text': 'this?'}], ['what is this?']),+ ([{'type': 'text', 'text': 'what is this?'}, IMAGE], None),+])+async def test_retry_refuses_an_unresendable_turn_before_rewinding(tmp_path, monkeypatch, content, submitted):+ from gateway import run+ from gateway.config import GatewayConfig+ from gateway.session import SessionStore+ from gateway.session_authority import initialize_session_authority+ from gateway.session_controls import AuthorityConnection+ from gateway.session_local import create_local_session+ from hermes_cli.gateway_chat_commands import run_command+ from hermes_cli.gateway_client import GatewayClientError+ from hermes_cli.gateway_mutations import PreparedMutations++ monkeypatch.setenv('HERMES_HOME', str(tmp_path))+ monkeypatch.setattr(run, '_load_gateway_config', lambda: {'platform_toolsets': {'cli': []}})+ store = SessionStore(tmp_path / 'sessions', GatewayConfig())+ runner = SimpleNamespace(session_store=store, _session_db=store._db, adapters={}, _draining=False,+ _cached_agent_for=lambda route: None, _evict_cached_agent=lambda route: None)+ runner._adapter_for_source = lambda source: runner.adapters.get(source.platform)+ authority = await initialize_session_authority(runner, profile_id='fixture', instance_id='owner')+ db = authority.db+ try:+ connection = AuthorityConnection(authority, object(), {'user_id': 'human', 'profile_id': 'fixture'})+ ref = create_local_session(authority, connection.actor, {+ 'request_id': 'cli', 'source': 'cli', 'cwd': str(tmp_path), 'model': 'frozen', 'toolsets': []})+ db.append_message(ref.session_id, 'user', content)+ db.append_message(ref.session_id, 'assistant', 'earlier answer')+ view = SimpleNamespace(client=_Bridge(connection), session_id=ref.session_id,+ mutations=PreparedMutations(), submit=AsyncMock(), generation=0)+ active = lambda: len(db.get_messages(ref.session_id)) # noqa: E731+ if submitted is None:+ with pytest.raises(GatewayClientError, match=r'^/retry: retry does not support media'):+ await run_command(view, '/retry', '')+ assert active() == 2 and not view.submit.called+ else:+ await run_command(view, '/retry', '')+ assert active() == 0+ assert [call.args[0] for call in view.submit.await_args_list] == submitted+ finally:+ store.close_all_db_handles()