The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): local viewers see the agent's status lines and notices
Teknium2066edb40b71
diff --git a/gateway/run_turn_progress.py b/gateway/run_turn_progress.pyindex ef7aa5dcf11..f42d24e8cf4 100644--- a/gateway/run_turn_progress.py+++ b/gateway/run_turn_progress.py@@ -869,6 +869,17 @@ class GatewayTurnProgressMixin:except Exception as e:logger.debug("event_callback hook error: %s", e)+ def _local_notice_callback_sync(self, notice) -> None:+ """``AgentNotice`` -> ``notification.show`` for local viewers (the TUI's payload)."""+ from gateway.warning_notifications import is_diagnostic_notice, render_notification+ ctx = self._ctx+ if ctx.mute_notification_reply or not self._status_live() or not str(notice.text or "").strip():+ return+ render_notification(lambda: self._publish_execution("notification.show", {+ "text": str(notice.text).strip(), "level": notice.level, "kind": notice.kind,+ "ttl_ms": notice.ttl_ms, "key": notice.key, "id": notice.id}),+ platform=ctx.source.platform, user_config=ctx.user_config, diagnostic=is_diagnostic_notice(notice))+def _status_live(self) -> bool:"""Status adapter present and this run is still the current generation."""return bool(self._ctx._status_adapter) and self._ctx._run_still_current()@@ -923,6 +934,10 @@ class GatewayTurnProgressMixin:)returndef present():+ if local_viewer_turn(self):+ self._publish_execution("status.update", {"kind": _viewer_status_kind(event_type, prepared),+ "text": prepared})+ returnfut = self._schedule(_send_or_update_status_coro(ctx._status_adapter, ctx._status_chat_id, event_type, prepared, ctx._status_thread_metadata),f"status_callback ({event_type}) scheduling error",@@ -931,3 +946,15 @@ class GatewayTurnProgressMixin:fut.add_done_callback(self._track_future_cleanup_id)render_notification(present, platform=ctx.source.platform, user_config=ctx.user_config,diagnostic=is_warning_status(event_type, message))+++def local_viewer_turn(runner) -> bool:+ """A local route's viewers read the canonical event stream; ``LocalSessionAdapter.send``+ publishes nothing, so status and notices go to that stream instead."""+ return getattr(runner, "_approval_owner", None) is not None and runner._ctx.source.platform == Platform.LOCAL+++def _viewer_status_kind(kind, text):+ """The TUI's ``status.update`` kind: auto-compaction progress is re-tagged ``compacting``."""+ from agent.conversation_compression import is_compaction_progress_status+ return "compacting" if kind == "lifecycle" and is_compaction_progress_status(text) else str(kind)diff --git a/gateway/run_turn_runner.py b/gateway/run_turn_runner.pyindex 5f0c9fa32eb..19e9b48108b 100644--- a/gateway/run_turn_runner.py+++ b/gateway/run_turn_runner.py@@ -397,7 +397,9 @@ class TurnRunner(GatewayTurnProgressMixin, GatewaySessionAgentMixin):agent.step_callback = ctx._step_callback_sync if (ctx._hooks_ref.loaded_hooks or self._approval_owner is not None) else Noneagent.stream_delta_callback = stream_delta_cbagent.interim_assistant_callback = interim_assistant_cb if want_interim_messages else None- agent.status_callback, agent.notice_callback = ctx._status_callback_sync, self._notice_callback_sync+ from gateway.run_turn_progress import local_viewer_turn+ agent.status_callback, agent.notice_callback = ctx._status_callback_sync, (+ self._local_notice_callback_sync if local_viewer_turn(self) else self._notice_callback_sync)agent.reasoning_callback = None # per turn: a reused agent never keeps an earlier API turn's sinkif self._approval_owner is not None:from gateway.session_api_turn import api_execution, wire_api_observersdiff --git a/hermes_cli/gateway_chat_view.py b/hermes_cli/gateway_chat_view.pyindex 72a6db588d4..7ed52d546b2 100644--- a/hermes_cli/gateway_chat_view.py+++ b/hermes_cli/gateway_chat_view.py@@ -154,6 +154,7 @@ class GatewayChatView:"approval.request": self._request, "clarify.request": self._request,"approval.settled": self._settled, "clarify.settled": self._settled,"session.info": self._session_info,+ "status.update": self._notice, "notification.show": self._notice,}.get(kind)if handler:handler(admission, payload)@@ -162,6 +163,11 @@ class GatewayChatView:self.pending = payload.get("pending", self.pending)self.generation = payload.get("execution_generation", self.generation)+ def _notice(self, admission, payload):+ # The owner already applied display.warning_notifications; it publishes only what shows.+ if not self.quiet and str(payload.get("text") or "").strip():+ print(str(payload["text"]).strip(), file=sys.stderr, flush=True)+def _tool_start(self, admission, payload):# Deltas before a tool call are interim commentary the final reply does not repeat;# close that segment so `_complete` measures only the final's own stream.diff --git a/tests/gateway/fixtures/local_status_notice_peer.py b/tests/gateway/fixtures/local_status_notice_peer.pynew file mode 100644index 00000000000..1b3a880ee8b--- /dev/null+++ b/tests/gateway/fixtures/local_status_notice_peer.py@@ -0,0 +1,121 @@+"""Real owner, real AIAgent turn, authenticated local WS viewer: agent status and notices."""+import asyncio+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer+import json+import os+from pathlib import Path+import sys+import threading+import traceback+++class Peer(BaseHTTPRequestHandler):+ def log_message(self, *a):+ pass++ def do_GET(self):+ self.send_response(200); self.end_headers(); self.wfile.write(b'{"data": []}')++ def do_POST(self):+ request = json.loads(self.rfile.read(int(self.headers['Content-Length'])))+ self.send_response(200)+ if request.get('stream'):+ self.send_header('Content-Type', 'text/event-stream'); self.end_headers()+ for delta, fin in [({'role': 'assistant', 'content': 'DONE'}, None), ({}, 'stop')]:+ frame = {'id': 'x', 'object': 'chat.completion.chunk', 'created': 1, 'model': 'm',+ 'choices': [{'index': 0, 'delta': delta, 'finish_reason': fin}]}+ self.wfile.write(('data: ' + json.dumps(frame) + '\n\n').encode())+ self.wfile.write(b'data: [DONE]\n\n'); self.wfile.flush()+ return+ self.send_header('Content-Type', 'application/json')+ self.end_headers()+ self.wfile.write(json.dumps({'id': 'x', 'object': 'chat.completion', 'created': 1, 'model': 'm',+ 'choices': [{'index': 0, 'message': {'role': 'assistant', 'content': 'DONE'}, 'finish_reason': 'stop'}],+ 'usage': {'prompt_tokens': 1, 'completion_tokens': 1, 'total_tokens': 2}}).encode())+++async def probe():+ import websockets+ from gateway.run import GatewayRunner+ from gateway.session_authority import initialize_session_authority+ from gateway.run_api import start_gateway_api, stop_gateway_api+ from hermes_cli import web_server+ from hermes_cli.dashboard_auth.ws_tickets import mint_ticket+ import run_agent+ from agent.credits_tracker import AgentNotice++ original = run_agent.AIAgent.run_conversation++ def run_conversation(self, *args, **kwargs):+ self._emit_warning('PROBE_WARNING_STATUS')+ self._emit_status('PROBE_LIFECYCLE_STATUS')+ self._emit_notice(AgentNotice(text='PROBE_NOTICE', level='warn', key='probe', id='probe'))+ return original(self, *args, **kwargs)+ run_agent.AIAgent.run_conversation = run_conversation++ runner = GatewayRunner()+ await initialize_session_authority(runner, profile_id='fixture', instance_id='local')+ api = await start_gateway_api(runner)+ port = api.socket.getsockname()[1]+ web_server.app.state.auth_required = True+ ticket = mint_ticket(user_id='fixture-creator', provider='local-fixture')+ ws = await websockets.connect(f'ws://127.0.0.1:{port}/api/ws?ticket={ticket}')+ frames = []++ async def rpc(method, **params):+ await ws.send(json.dumps({'jsonrpc': '2.0', 'id': method, 'method': method, 'params': params}))+ async with asyncio.timeout(15):+ while True:+ frame = json.loads(await ws.recv())+ frames.append(frame)+ if frame.get('id') == method:+ return frame+ try:+ sid = (await rpc('session.create', request_id='fresh', source='cli'))['result']['session_id']+ await rpc('session.resume', session_id=sid)+ await rpc('prompt.submit', session_id=sid, input_id='first', text='hi')+ async with asyncio.timeout(30):+ while not any(f.get('params', {}).get('type') == 'message.complete' for f in frames):+ frames.append(json.loads(await ws.recv()))+ await asyncio.sleep(0.3)+ events = [f['params'] for f in frames if f.get('method') == 'event']+ # The classic `hermes chat` view renders what reached it on stderr.+ import contextlib+ import io+ from hermes_cli.gateway_chat_view import GatewayChatView+ view, printed = GatewayChatView(None, {'stored_session_id': sid}), io.StringIO()+ with contextlib.redirect_stderr(printed), contextlib.redirect_stdout(io.StringIO()):+ for params in events:+ view._dispatch_event(params['type'], params.get('admission_id'), params.get('payload', {}))+ Path(os.environ['HERMES_HOME'], 'receipt.json').write_text(json.dumps({+ 'events': [[p['type'], p.get('payload')] for p in events if p['type'] in (+ 'status.update', 'notification.show')], 'cli_stderr': printed.getvalue()}))+ finally:+ await ws.close()+ await stop_gateway_api(api)+++def main():+ suppress = len(sys.argv) > 1 and sys.argv[1] == 'suppress'+ peer = ThreadingHTTPServer(('127.0.0.1', 0), Peer)+ threading.Thread(target=peer.serve_forever, daemon=True).start()+ url = f'http://127.0.0.1:{peer.server_port}/v1'+ os.environ.update(OPENAI_API_KEY='loopback-only', OPENAI_BASE_URL=url, TERMINAL_ENV='local')+ Path(os.environ['HERMES_HOME'], 'config.yaml').write_text(+ f'model:\n default: local-control\n provider: custom\n base_url: {url}\n'+ 'streaming:\n enabled: false\nauxiliary:\n title_generation:\n enabled: false\n'+ + ('display:\n suppress_warning_notifications: true\n' if suppress else ''))+ try:+ asyncio.run(probe())+ finally:+ peer.shutdown()+++if __name__ == '__main__':+ status = 0+ try:+ main()+ except BaseException:+ traceback.print_exc()+ status = 1+ os._exit(status)diff --git a/tests/gateway/test_local_viewer_status_notice.py b/tests/gateway/test_local_viewer_status_notice.pynew file mode 100644index 00000000000..306290ce8f9--- /dev/null+++ b/tests/gateway/test_local_viewer_status_notice.py@@ -0,0 +1,37 @@+"""A local viewer sees the agent's status lines and notices, as main's TUI and CLI showed them.++On the shared owner a local route's ``LocalSessionAdapter.send`` publishes nothing, so a warning+status or an ``AgentNotice`` raised during a viewer's turn reached no viewer. Real owner, real+AIAgent turn over a loopback model, authenticated WebSocket viewer, in a disposable process.+"""+import json+import os+from pathlib import Path+import subprocess+import sys++import pytest++SHOWN = [['status.update', {'kind': 'warn', 'text': 'PROBE_WARNING_STATUS'}],+ ['status.update', {'kind': 'lifecycle', 'text': 'PROBE_LIFECYCLE_STATUS'}],+ ['notification.show', {'text': 'PROBE_NOTICE', 'level': 'warn', 'kind': 'sticky', 'ttl_ms': None,+ 'key': 'probe', 'id': 'probe'}]]++[email protected]('mode', ['default', 'suppress'])+def test_local_viewer_receives_agent_status_and_notices(tmp_path, mode):+ repo = Path(__file__).resolve().parents[2]+ home, state = tmp_path / 'home', tmp_path / 'state'+ home.mkdir()+ state.mkdir()+ env = {k: os.environ[k] for k in ('PATH', 'SYSTEMROOT', 'LANG', 'TZ') if k in os.environ}+ env.update(HOME=str(home), USERPROFILE=str(home), HERMES_HOME=str(state), PYTHONPATH=str(repo))+ result = subprocess.run(+ [sys.executable, str(Path(__file__).parent / 'fixtures' / 'local_status_notice_peer.py'), mode],+ cwd=repo, env=env, stdin=subprocess.DEVNULL, capture_output=True, text=True, timeout=100, check=False)+ assert result.returncode == 0, result.stdout + '\n' + result.stderr+ receipt = json.loads((state / 'receipt.json').read_text())+ # display.suppress_warning_notifications still hides the diagnostics (warn status, warn notice).+ expected = SHOWN if mode == 'default' else [SHOWN[1]]+ assert receipt['events'] == expected+ assert receipt['cli_stderr'].split() == [payload['text'] for _, payload in expected]