The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(gateway): local-viewer turns publish the reply boundary, tool.generating, agent.print and tool duration
Tekniumb8a94975d48a
diff --git a/apps/shared/src/gateway-contract.generated.ts b/apps/shared/src/gateway-contract.generated.tsindex a35e7ecf991..cbcec019f5d 100644--- a/apps/shared/src/gateway-contract.generated.ts+++ b/apps/shared/src/gateway-contract.generated.ts@@ -5277,6 +5277,12 @@ export interface ErrorPayload {export interface NoticePayload {message: string}+/** ``message.delta``. A session-authority local-viewer turn also publishes ``text: null``: the reply segment boundary (the agent's ``stream_delta_callback(None)``, before tool lines) that closes the classic CLI's reply box. Every other viewer ignores an empty chunk. */+export interface MessageDeltaPayload {+ text: string | null+ rendered?: string | null+ verbose?: boolean | null+}/** ``prompt_turn._invoke_agent._stream`` (message.delta: ``text`` + optional ``rendered``), ``agent_callbacks._agent_cbs`` (reasoning.delta / thinking.delta), ``tool_progress._progress_reasoning`` (reasoning.available). ``verbose`` rides only when the session's verbose reasoning mode is on. */export interface StreamDeltaPayload {text: string@@ -5360,6 +5366,10 @@ export interface ReactionPayload {export interface ReviewSummaryPayload {text: string}+/** A session-authority local-viewer turn: one line the agent printed through ``_print_fn`` (subagent completion, compaction, errors, budget notices), which main's classic CLI rendered through ``_agent_status_print``. */+export interface AgentPrintPayload {+ text: string+}/** ``tool_progress._on_tool_start`` (+ ``agent_callbacks._mirror_subagent_to_child`` rows with ``preview`` and empty ``args``). ``todos``/``revision`` are NOT set by the emitter; kept optional because tool.start rows may pass through connector redaction unchanged. */export interface ToolStartPayload {tool_id: string@@ -6553,6 +6563,8 @@ export const SERVER_REQUEST_METHODS = [// ── Notifications (`event` frames) ──export interface BackendGatewayEventMap {+ /** A status line the agent printed during a local viewer's turn. */+ 'agent.print': AgentPrintPayload/** Output chunk from an agent-owned background process. */'agent.terminal.output': TerminalOutputPayload/** Pending gateway approvals were dropped by interrupt/reap/teardown; the wait resolved as deny (not a user refusal). */@@ -6595,8 +6607,8 @@ export interface BackendGatewayEventMap {'layout.apply': LayoutApplyPayload/** The turn ended: final text, usage and outcome. */'message.complete': MessageCompletePayload- /** One streamed chunk of the assistant reply. */- 'message.delta': StreamDeltaPayload+ /** One streamed chunk of the assistant reply (null text: segment boundary). */+ 'message.delta': MessageDeltaPayload/** Interim assistant commentary (text beside tool calls) sealed as its own segment. */'message.interim': MessageInterimPayload/** The agent reacted to a message; paint it live. */@@ -6710,6 +6722,7 @@ export interface BackendGatewayEventMap {}export type BackendGatewayEventName = keyof BackendGatewayEventMapexport const GATEWAY_EVENT_TYPES = [+ 'agent.print','agent.terminal.output','approval.cancelled','background.complete',diff --git a/apps/shared/src/gateway-contract.openrpc.json b/apps/shared/src/gateway-contract.openrpc.jsonindex 48e373f81a7..e7c7ac99d97 100644--- a/apps/shared/src/gateway-contract.openrpc.json+++ b/apps/shared/src/gateway-contract.openrpc.json@@ -5153,6 +5153,21 @@"title": "AgentPluginRow","type": "object"},+ "AgentPrintPayload": {+ "additionalProperties": false,+ "description": "A session-authority local-viewer turn: one line the agent printed through ``_print_fn``\n(subagent completion, compaction, errors, budget notices), which main's classic CLI rendered\nthrough ``_agent_status_print``.",+ "properties": {+ "text": {+ "title": "Text",+ "type": "string"+ }+ },+ "required": [+ "text"+ ],+ "title": "AgentPrintPayload",+ "type": "object"+ },"AgentProcessRow": {"additionalProperties": false,"properties": {@@ -22520,6 +22535,52 @@"title": "MessageCompletePayload","type": "object"},+ "MessageDeltaPayload": {+ "additionalProperties": false,+ "description": "``message.delta``. A session-authority local-viewer turn also publishes ``text: null``: the\nreply segment boundary (the agent's ``stream_delta_callback(None)``, before tool lines) that\ncloses the classic CLI's reply box. Every other viewer ignores an empty chunk.",+ "properties": {+ "text": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "title": "Text"+ },+ "rendered": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Rendered"+ },+ "verbose": {+ "anyOf": [+ {+ "type": "boolean"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Verbose"+ }+ },+ "required": [+ "text"+ ],+ "title": "MessageDeltaPayload",+ "type": "object"+ },"MessageInterimPayload": {"additionalProperties": false,"description": "``prompt_turn._interim_assistant_cb`` / ``agent_callbacks`` interim_assistant_callback.",@@ -45389,6 +45450,18 @@}],"x-notifications": [+ {+ "name": "agent.print",+ "summary": "A status line the agent printed during a local viewer's turn.",+ "params": [+ {+ "name": "payload",+ "schema": {+ "$ref": "#/components/schemas/AgentPrintPayload"+ }+ }+ ]+ },{"name": "agent.terminal.output","summary": "Output chunk from an agent-owned background process.",@@ -45643,12 +45716,12 @@},{"name": "message.delta",- "summary": "One streamed chunk of the assistant reply.",+ "summary": "One streamed chunk of the assistant reply (null text: segment boundary).","params": [{"name": "payload","schema": {- "$ref": "#/components/schemas/StreamDeltaPayload"+ "$ref": "#/components/schemas/MessageDeltaPayload"}}]diff --git a/gateway/local_viewer_events.py b/gateway/local_viewer_events.pynew file mode 100644index 00000000000..cb85645249b--- /dev/null+++ b/gateway/local_viewer_events.py@@ -0,0 +1,47 @@+"""Turn events a local viewer (the classic CLI, TUI, Desktop) reads from the canonical stream.++The classic CLI rendered every agent callback in process: the tool-generating line, the+kawaii thinking text, reasoning, MoA references, hearts, and every status line the agent printed+through ``_print_fn``. On the session authority the agent runs in the gateway, so each of those+callbacks is projected as an execution event (generation-fenced through+``TurnRunner._publish_execution``) and only for a local viewer's turn: a messaging route never+installs them, so its agent behaves exactly as before.++The cached agent is shared across turns. ``wire`` installs the sinks for one turn and returns the+previous values; ``restore`` puts them back when the turn's ``run_conversation`` returns.+"""+from __future__ import annotations++import time++# Attributes ``wire`` may overwrite on the cached agent for one local-viewer turn.+_TURN_ATTRS = ("tool_gen_callback", "_print_fn")+++def wire(turn, agent) -> dict:+ """Install this turn's local-viewer sinks on ``agent``; returns what ``restore`` needs."""+ previous = {name: getattr(agent, name, None) for name in _TURN_ATTRS}+ publish = turn._publish_execution+ agent.tool_gen_callback = lambda name: publish("tool.generating", {"name": str(name or "")})++ def print_fn(*args, **kwargs):+ publish("agent.print", {"text": str(kwargs.get("sep", " ")).join(str(a) for a in args)})+ agent._print_fn = print_fn+ return previous+++def restore(agent, previous: dict | None) -> None:+ if not previous:+ return+ for name, value in previous.items():+ setattr(agent, name, value)+++def note_tool_start(turn, call_id) -> None:+ """Monotonic start time of one call, for ``tool.complete.duration_s``."""+ turn.__dict__.setdefault("_local_tool_starts", {})[str(call_id or "")] = time.monotonic()+++def complete_fields(turn, call_id) -> dict:+ started = turn.__dict__.setdefault("_local_tool_starts", {}).pop(str(call_id or ""), None)+ return {"duration_s": (time.monotonic() - started) if started is not None else None}diff --git a/gateway/run_turn_progress.py b/gateway/run_turn_progress.pyindex ad0d9eb8147..61e817e6ab9 100644--- a/gateway/run_turn_progress.py+++ b/gateway/run_turn_progress.py@@ -821,6 +821,9 @@ class GatewayTurnProgressMixin:def combined_tool_start_callback(self, call_id, tool_name, args):"""Compose the voice ack + native task-card start consumers."""+ if local_viewer_turn(self):+ from gateway import local_viewer_events+ local_viewer_events.note_tool_start(self, call_id)self._publish_execution("tool.start", _tool_lifecycle_payload(call_id, tool_name, args))self._publish_api_tool("tool.start", call_id, tool_name, args)if self._ctx._voice_ack_guild[0] is not None:@@ -836,6 +839,9 @@ class GatewayTurnProgressMixin:# A session's /verbose (gateway/session_busy_controls.py) ships the Result block text.verbose = live is not None and (getattr(live, "tool_progress_mode", None) or self._ctx.progress_mode) == "verbose"payload = _tool_complete_payload(call_id, tool_name, args, result, is_error=is_error, verbose=verbose)+ if local_viewer_turn(self):+ from gateway import local_viewer_events+ payload.update(local_viewer_events.complete_fields(self, call_id))self._publish_execution("tool.complete", payload)self._publish_api_tool("tool.complete", call_id, tool_name, args, result)if self._ctx._native_slack_task_cards:diff --git a/gateway/run_turn_runner.py b/gateway/run_turn_runner.pyindex f6c8c8105c4..6aff1238055 100644--- a/gateway/run_turn_runner.py+++ b/gateway/run_turn_runner.py@@ -231,13 +231,18 @@ class TurnRunner(GatewayTurnProgressMixin, GatewaySessionAgentMixin):) if sc is not None]stream_delta_cb = None+ local_viewer_route = getattr(ctx.source, "platform", None) == Platform.LOCALif delta_sinks or self._approval_owner is not None:def stream_delta_cb(text: Optional[str]) -> None:if not ctx._run_still_current():returndelivered = bool(delta_sinks)- if text is not None: # None closes only the native stream segment.+ if text is not None:delivered = self._publish_execution("message.delta", {"text": text}) or delivered+ elif local_viewer_route:+ # The segment boundary (main's ``_stream_delta(None)`` closes the reply box+ # before tool lines); messaging routes only close their native stream.+ self._publish_execution("message.delta", {"text": None})for sink in delta_sinks:sink.on_delta(text)if text is not None and (not delivered or _finite_viewer_turn()):@@ -247,8 +252,6 @@ class TurnRunner(GatewayTurnProgressMixin, GatewaySessionAgentMixin):# stitched as a "partial delivery" nobody received (classic -q parity).raise _NoStreamConsumer()- local_viewer_route = getattr(ctx.source, "platform", None) == Platform.LOCAL-def interim_assistant_cb(text: str, *, already_streamed: bool = False) -> None:if not ctx._run_still_current():return@@ -1197,10 +1200,21 @@ class TurnRunner(GatewayTurnProgressMixin, GatewaySessionAgentMixin):# Reuse the in-agent one-shot notice so the pre-agent provider switch is user-visible too.agent._pending_fallback_notice = pending_fallback_noticeself._wire_turn_agent_callbacks(agent, turn_route, reasoning_config, stream_delta_cb, interim_cb, want_interim)- agent_history, observed_group_context, history_media_paths = self._load_turn_history(agent, reused_cached_agent)- persist_msg, persist_ts = self._prepare_turn_message(agent_history)- compressions = getattr(getattr(agent, "context_compressor", None), "compression_count", None)- result = self._run_conversation_with_approval(agent, agent_history, observed_group_context, persist_msg, persist_ts)+ from gateway.run_turn_progress import local_viewer_turn+ local_sinks = None+ if local_viewer_turn(self) and not ctx.mute_notification_reply:+ # Per turn on the shared cached agent: installed here, restored when the run returns.+ from gateway import local_viewer_events+ local_sinks = local_viewer_events.wire(self, agent)+ try:+ agent_history, observed_group_context, history_media_paths = self._load_turn_history(agent, reused_cached_agent)+ persist_msg, persist_ts = self._prepare_turn_message(agent_history)+ compressions = getattr(getattr(agent, "context_compressor", None), "compression_count", None)+ result = self._run_conversation_with_approval(agent, agent_history, observed_group_context, persist_msg, persist_ts)+ finally:+ if local_sinks is not None:+ from gateway import local_viewer_events+ local_viewer_events.restore(agent, local_sinks)persisted_turn = _persisted_turn(agent, agent_history, result, compressions)self._finish_stream_consumer(result, agent_history, stream_consumer)if _finite_viewer_turn() and getattr(agent, "_codex_session", None) is not None:diff --git a/gateway/session_api_turn.py b/gateway/session_api_turn.pyindex 5e82061001b..2d0c47144ec 100644--- a/gateway/session_api_turn.py+++ b/gateway/session_api_turn.py@@ -504,7 +504,7 @@ def wire_api_observers(agent, owner, want_interim):def publish_api_event(authority, session_id, event_type, payload):- if event_type == 'message.delta':+ if event_type == 'message.delta' and payload['text'] is not None: # a None segment boundary is viewer-onlyreturn _notify_observers(authority, session_id, 'stream_delta_callback', payload['text'])return Falsediff --git a/tests/gateway/test_local_viewer_events_turn.py b/tests/gateway/test_local_viewer_events_turn.pynew file mode 100644index 00000000000..fe7b76c3bec--- /dev/null+++ b/tests/gateway/test_local_viewer_events_turn.py@@ -0,0 +1,104 @@+"""Local-viewer turn events the classic CLI renders through its own callbacks (CALLMAP W1).++On the session authority the agent runs in the gateway, so every callback main's HermesCLI+passed to its in-process AIAgent must reach the viewer as an execution event: the reply-box+segment boundary, the tool-generating line, every ``_print_fn`` status line and the tool+duration. A messaging route must not see any of it.+"""+from __future__ import annotations++from types import SimpleNamespace++import pytest++from gateway.config import Platform+from gateway.run_turn_runner import TurnRunner+++def _turn(platform, published, *, live=None):+ turn = object.__new__(TurnRunner)+ turn._ctx = SimpleNamespace(+ source=SimpleNamespace(platform=platform, chat_id='chat'),+ mute_notification_reply=False, scheduled_heartbeat=False,+ streaming_tts_consumer_holder=[None], stream_consumer_holder=[None],+ interim_assistant_messages_enabled=False, user_config={},+ resolve_display_setting=lambda *a: None, _run_still_current=lambda: True,+ _voice_ack_guild=[None], _native_slack_task_cards=False, progress_mode='all',+ session_id='s', progress_queue=None,+ )+ turn._runner = SimpleNamespace(config=None, _delivery_adapter_for=lambda source: None)+ live = live or SimpleNamespace(tool_progress_mode=None)+ authority = SimpleNamespace(sessions={'s': live})+ turn._approval_owner = (authority, 's', 1)+ turn._publish_execution = lambda kind, payload: published.append((kind, payload)) or True+ turn._publish_api_tool = lambda *a, **k: None+ return turn+++def _delta_cb(turn):+ _consumer, delta_cb, _interim, _want = turn._setup_stream_consumer('cli')+ return delta_cb+++def test_local_viewer_gets_the_segment_boundary_as_null_delta():+ published = []+ delta_cb = _delta_cb(_turn(Platform.LOCAL, published))+ delta_cb('hello')+ delta_cb(None)+ assert published == [('message.delta', {'text': 'hello'}), ('message.delta', {'text': None})]+++def test_messaging_route_never_publishes_the_boundary():+ published = []+ delta_cb = _delta_cb(_turn(Platform.TELEGRAM, published))+ delta_cb('hello')+ delta_cb(None)+ assert published == [('message.delta', {'text': 'hello'})]+++def test_turn_sinks_publish_and_restore_on_the_shared_agent():+ from gateway import local_viewer_events+ published = []+ turn = _turn(Platform.LOCAL, published)+ sentinel = object()+ agent = SimpleNamespace(tool_gen_callback=sentinel, _print_fn=None)+ previous = local_viewer_events.wire(turn, agent)+ agent.tool_gen_callback('terminal')+ agent._print_fn(' ✓ [1/2]', 'done')+ assert published == [('tool.generating', {'name': 'terminal'}),+ ('agent.print', {'text': ' ✓ [1/2] done'})]+ local_viewer_events.restore(agent, previous)+ assert agent.tool_gen_callback is sentinel and agent._print_fn is None+++def test_status_lines_the_agent_prints_reach_the_viewer():+ """``_safe_print`` (subagent completion, compaction, errors) routes through ``_print_fn``."""+ from agent.status_output import StatusOutputMixin+ from gateway import local_viewer_events+ published = []+ agent = type('A', (StatusOutputMixin,), {})()+ agent._print_fn = None+ local_viewer_events.wire(_turn(Platform.LOCAL, published), agent)+ agent._safe_print('🗜️ compacted')+ assert published == [('agent.print', {'text': '🗜️ compacted'})]++[email protected]('platform', [Platform.LOCAL, Platform.TELEGRAM])+def test_tool_complete_carries_duration_only_for_local_viewers(platform):+ published = []+ turn = _turn(platform, published)+ turn.combined_tool_start_callback('c1', 'read_file', {'path': 'x'})+ turn.combined_tool_complete_callback('c1', 'read_file', {'path': 'x'}, '{"content": "hi"}')+ complete = next(payload for kind, payload in published if kind == 'tool.complete')+ if platform == Platform.LOCAL:+ assert isinstance(complete['duration_s'], float) and complete['duration_s'] >= 0+ else:+ assert 'duration_s' not in complete+++def test_wire_contract_accepts_the_boundary_frame():+ from tui_gateway.contracts.registry import EVENTS+ EVENTS['message.delta'].payload.model_validate({'text': None})+ EVENTS['tool.generating'].payload.model_validate({'name': 'terminal'})+ EVENTS['agent.print'].payload.model_validate({'text': 'line'})+ EVENTS['tool.complete'].payload.model_validate({'tool_id': 'c', 'name': 'n', 'duration_s': 0.1})diff --git a/tests/tui_gateway/contracts/test_generated.py b/tests/tui_gateway/contracts/test_generated.pyindex 263a4a225e1..0e449b0c123 100644--- a/tests/tui_gateway/contracts/test_generated.py+++ b/tests/tui_gateway/contracts/test_generated.py@@ -46,6 +46,8 @@ _DESKTOP_UI_EMIT = re.compile(r"desktop_ui\.(?:emit|emit_or_error)\(\s*\"([a-z_]_BROKER_FRAME = re.compile(r"^FRAME_[A-Z_]+ = \"(browser\.controller\.[a-z_]+)\"", re.MULTILINE)_SETUP_READY = re.compile(r"^SETUP_READY_EVENT = \"([a-z_.]+)\"", re.MULTILINE)_FREE_TIER_CHALLENGE = re.compile(r"^CHALLENGE_EVENT = \"([a-z_.]+)\"", re.MULTILINE)+# Session-authority local-viewer turn projections (gateway/local_viewer_events.py).+_LOCAL_VIEWER_PUBLISH = re.compile(r"\b(?:publish|_publish_execution)\(\s*\"([a-z_][a-z0-9_.]*)\"")def _read(path: Path) -> str:@@ -74,6 +76,7 @@ def emitted_event_names() -> set[str]:names.update(_BROKER_FRAME.findall(_read(REPO / "gateway" / "browser_control_broker.py")))names.update(_SETUP_READY.findall(_read(REPO / "hermes_cli" / "free_tier_bootstrap.py")))names.update(_FREE_TIER_CHALLENGE.findall(_read(REPO / "hermes_cli" / "anon_challenge.py")))+ names.update(_LOCAL_VIEWER_PUBLISH.findall(_read(REPO / "gateway" / "local_viewer_events.py")))return namesdiff --git a/tui_gateway/contracts/events.py b/tui_gateway/contracts/events.pyindex d7e79376cb4..8666d7f0d29 100644--- a/tui_gateway/contracts/events.py+++ b/tui_gateway/contracts/events.py@@ -126,7 +126,15 @@ class StreamDeltaPayload(Payload):verbose: bool | None = None-event("message.delta", StreamDeltaPayload, doc="One streamed chunk of the assistant reply.")+class MessageDeltaPayload(StreamDeltaPayload):+ """``message.delta``. A session-authority local-viewer turn also publishes ``text: null``: the+ reply segment boundary (the agent's ``stream_delta_callback(None)``, before tool lines) that+ closes the classic CLI's reply box. Every other viewer ignores an empty chunk."""++ text: str | None+++event("message.delta", MessageDeltaPayload, doc="One streamed chunk of the assistant reply (null text: segment boundary).")event("reasoning.delta", StreamDeltaPayload, doc="One streamed chunk of the model's reasoning.")event("reasoning.available", StreamDeltaPayload, doc="A completed reasoning block (non-streaming providers).")event("thinking.delta", StreamDeltaPayload, doc="Legacy thinking-text chunk (thinking_callback).")@@ -268,6 +276,17 @@ class ReviewSummaryPayload(Payload):event("review.summary", ReviewSummaryPayload, doc="Background review of the last turn finished.")+class AgentPrintPayload(Payload):+ """A session-authority local-viewer turn: one line the agent printed through ``_print_fn``+ (subagent completion, compaction, errors, budget notices), which main's classic CLI rendered+ through ``_agent_status_print``."""++ text: str+++event("agent.print", AgentPrintPayload, doc="A status line the agent printed during a local viewer's turn.")++# ── tools ─────────────────────────────────────────────────────────────────────────────────────diff --git a/ui-tui/src/app/createGatewayEventHandler.ts b/ui-tui/src/app/createGatewayEventHandler.tsindex 91cfac825e7..169fd5a2f85 100644--- a/ui-tui/src/app/createGatewayEventHandler.ts+++ b/ui-tui/src/app/createGatewayEventHandler.ts@@ -3,7 +3,7 @@ import { execFile } from 'child_process'import { forceRedraw, onTerminalBackground, onTerminalForeground } from '@hermes/ink'import { stripAnsi } from '@hermes/shared/ansi'import { relativeLuminance } from '@hermes/shared/color'-import type { StreamDeltaPayload, SubagentStatus, Usage } from '@hermes/shared/gateway-events'+import type { MessageDeltaPayload, SubagentStatus, Usage } from '@hermes/shared/gateway-events'import { STARTUP_IMAGE, STARTUP_QUERY } from '../config/env.js'import { STREAM_BATCH_MS } from '../config/timing.js'@@ -1676,7 +1676,7 @@ export function createGatewayEventHandler(ctx: GatewayEventHandlerContext): (ev:}case 'message.delta':- turnController.recordMessageDelta(ev.payload ?? ({} as StreamDeltaPayload))+ turnController.recordMessageDelta(ev.payload ?? ({} as MessageDeltaPayload))returncase 'message.interim': {diff --git a/ui-tui/src/app/turnController.ts b/ui-tui/src/app/turnController.tsindex 946f24aa560..99cc437ecb5 100644--- a/ui-tui/src/app/turnController.ts+++ b/ui-tui/src/app/turnController.ts@@ -791,7 +791,7 @@ class TurnController {return { finalMessages, finalText, interruptedReply, wasInterrupted }}- recordMessageDelta({ text }: { rendered?: string | null; text?: string }) {+ recordMessageDelta({ text }: { rendered?: string | null; text?: string | null }) {if (this.interrupted || !text) {return}