The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(gateway): local-viewer turns publish session.usage; session.stats returns the same dict
Tekniumd9e194ee018a
diff --git a/apps/shared/src/gateway-contract.generated.ts b/apps/shared/src/gateway-contract.generated.tsindex 3fc3af4a17a..b742e1b9b22 100644--- a/apps/shared/src/gateway-contract.generated.ts+++ b/apps/shared/src/gateway-contract.generated.ts@@ -4545,6 +4545,35 @@ export interface CanonicalSessionInfo {fast?: boolean | null[key: string]: unknown}+export interface SessionStatsParams {+ session_id: string+}+/** ``gateway/session_usage.py::usage_stats``: session-cumulative counters (the agent's ``session_*``), context / compressor figures, rolling latency and throughput, rate-limit state, live subagents. */+export interface SessionStats {+ input_tokens: number+ output_tokens: number+ cache_read_tokens: number+ cache_write_tokens: number+ prompt_tokens: number+ completion_tokens: number+ total_tokens: number+ reasoning_tokens: number+ api_calls: number+ last_prompt_tokens: number+ context_tokens: number+ context_length?: number | null+ config_context_length?: number | null+ context_source?: string | null+ compression_count: number+ avg_latency_s?: number | null+ tokens_per_s?: number | null+ last_turn_tokens: number+ rate_limit?: Record<string, unknown> | null+ active_subagents: number+ model: string+ provider: string+ fallback_model?: string | null+}export interface SessionDetachParams {session_id: stringsubscription_id: string@@ -5363,9 +5392,32 @@ export interface StatusUpdatePayload {kind: stringtext: string}-/** ``server._start_usage_ticker``. */+/** ``server._start_usage_ticker`` (``usage``), or a canonical local viewer's session-cumulative counters (``gateway/session_usage.py::usage_stats``, the ``session.stats`` dict) at the top level: published after every API call and at turn end, what main's classic CLI read off its agent. */export interface SessionUsagePayload {- usage: Usage+ usage?: Usage | null+ input_tokens?: number | null+ output_tokens?: number | null+ cache_read_tokens?: number | null+ cache_write_tokens?: number | null+ prompt_tokens?: number | null+ completion_tokens?: number | null+ total_tokens?: number | null+ reasoning_tokens?: number | null+ api_calls?: number | null+ last_prompt_tokens?: number | null+ context_tokens?: number | null+ context_length?: number | null+ config_context_length?: number | null+ context_source?: string | null+ compression_count?: number | null+ avg_latency_s?: number | null+ tokens_per_s?: number | null+ last_turn_tokens?: number | null+ rate_limit?: Record<string, unknown> | null+ active_subagents?: number | null+ model?: string | null+ provider?: string | null+ fallback_model?: string | null}/** ``prompt_turn._invoke_agent`` ``_on_session_title`` hook. */export interface SessionTitlePayload {@@ -6474,6 +6526,8 @@ export interface CanonicalRpcMethods {'session.prune': { params: SessionPruneParams; result: SessionPruneResult }'session.redirect': { params: CanonicalCorrectionParams; result: CanonicalCorrectionResult }'session.resume': { params: CanonicalResumeParams; result: CanonicalSnapshot }+ /** The session.usage dict on demand: what main's classic CLI read off its agent. */+ 'session.stats': { params: SessionStatsParams; result: SessionStats }'session.steer': { params: CanonicalCorrectionParams; result: CanonicalCorrectionResult }/** Ink ``!cmd`` / ``{!cmd}`` on the shared owner: one safe command for a local session, in its frozen launch cwd (``gateway/session_shell.py``). */'shell.exec': { params: CanonicalShellExecParams; result: ShellExecResult }@@ -6520,6 +6574,7 @@ export const CANONICAL_RPC_METHODS = ['session.prune','session.redirect','session.resume',+ 'session.stats','session.steer','shell.exec','worker.adopt',diff --git a/apps/shared/src/gateway-contract.openrpc.json b/apps/shared/src/gateway-contract.openrpc.jsonindex 2ed20389235..050946e1076 100644--- a/apps/shared/src/gateway-contract.openrpc.json+++ b/apps/shared/src/gateway-contract.openrpc.json@@ -36614,6 +36614,195 @@"title": "SessionStartChatResult","type": "object"},+ "SessionStats": {+ "additionalProperties": false,+ "description": "``gateway/session_usage.py::usage_stats``: session-cumulative counters (the agent's ``session_*``),\ncontext / compressor figures, rolling latency and throughput, rate-limit state, live subagents.",+ "properties": {+ "input_tokens": {+ "title": "Input Tokens",+ "type": "integer"+ },+ "output_tokens": {+ "title": "Output Tokens",+ "type": "integer"+ },+ "cache_read_tokens": {+ "title": "Cache Read Tokens",+ "type": "integer"+ },+ "cache_write_tokens": {+ "title": "Cache Write Tokens",+ "type": "integer"+ },+ "prompt_tokens": {+ "title": "Prompt Tokens",+ "type": "integer"+ },+ "completion_tokens": {+ "title": "Completion Tokens",+ "type": "integer"+ },+ "total_tokens": {+ "title": "Total Tokens",+ "type": "integer"+ },+ "reasoning_tokens": {+ "title": "Reasoning Tokens",+ "type": "integer"+ },+ "api_calls": {+ "title": "Api Calls",+ "type": "integer"+ },+ "last_prompt_tokens": {+ "title": "Last Prompt Tokens",+ "type": "integer"+ },+ "context_tokens": {+ "title": "Context Tokens",+ "type": "integer"+ },+ "context_length": {+ "anyOf": [+ {+ "type": "integer"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Context Length"+ },+ "config_context_length": {+ "anyOf": [+ {+ "type": "integer"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Config Context Length"+ },+ "context_source": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Context Source"+ },+ "compression_count": {+ "title": "Compression Count",+ "type": "integer"+ },+ "avg_latency_s": {+ "anyOf": [+ {+ "type": "number"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Avg Latency S"+ },+ "tokens_per_s": {+ "anyOf": [+ {+ "type": "number"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Tokens Per S"+ },+ "last_turn_tokens": {+ "title": "Last Turn Tokens",+ "type": "integer"+ },+ "rate_limit": {+ "anyOf": [+ {+ "additionalProperties": true,+ "type": "object"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Rate Limit"+ },+ "active_subagents": {+ "title": "Active Subagents",+ "type": "integer"+ },+ "model": {+ "title": "Model",+ "type": "string"+ },+ "provider": {+ "title": "Provider",+ "type": "string"+ },+ "fallback_model": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Fallback Model"+ }+ },+ "required": [+ "input_tokens",+ "output_tokens",+ "cache_read_tokens",+ "cache_write_tokens",+ "prompt_tokens",+ "completion_tokens",+ "total_tokens",+ "reasoning_tokens",+ "api_calls",+ "last_prompt_tokens",+ "context_tokens",+ "compression_count",+ "last_turn_tokens",+ "active_subagents",+ "model",+ "provider"+ ],+ "title": "SessionStats",+ "type": "object"+ },+ "SessionStatsParams": {+ "additionalProperties": false,+ "properties": {+ "session_id": {+ "title": "Session Id",+ "type": "string"+ }+ },+ "required": [+ "session_id"+ ],+ "title": "SessionStatsParams",+ "type": "object"+ },"SessionStatusParams": {"additionalProperties": false,"properties": {@@ -36829,15 +37018,297 @@},"SessionUsagePayload": {"additionalProperties": false,- "description": "``server._start_usage_ticker``.",+ "description": "``server._start_usage_ticker`` (``usage``), or a canonical local viewer's session-cumulative\ncounters (``gateway/session_usage.py::usage_stats``, the ``session.stats`` dict) at the top level:\npublished after every API call and at turn end, what main's classic CLI read off its agent.","properties": {"usage": {- "$ref": "#/components/schemas/Usage"+ "anyOf": [+ {+ "$ref": "#/components/schemas/Usage"+ },+ {+ "type": "null"+ }+ ],+ "default": null+ },+ "input_tokens": {+ "anyOf": [+ {+ "type": "integer"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Input Tokens"+ },+ "output_tokens": {+ "anyOf": [+ {+ "type": "integer"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Output Tokens"+ },+ "cache_read_tokens": {+ "anyOf": [+ {+ "type": "integer"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Cache Read Tokens"+ },+ "cache_write_tokens": {+ "anyOf": [+ {+ "type": "integer"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Cache Write Tokens"+ },+ "prompt_tokens": {+ "anyOf": [+ {+ "type": "integer"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Prompt Tokens"+ },+ "completion_tokens": {+ "anyOf": [+ {+ "type": "integer"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Completion Tokens"+ },+ "total_tokens": {+ "anyOf": [+ {+ "type": "integer"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Total Tokens"+ },+ "reasoning_tokens": {+ "anyOf": [+ {+ "type": "integer"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Reasoning Tokens"+ },+ "api_calls": {+ "anyOf": [+ {+ "type": "integer"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Api Calls"+ },+ "last_prompt_tokens": {+ "anyOf": [+ {+ "type": "integer"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Last Prompt Tokens"+ },+ "context_tokens": {+ "anyOf": [+ {+ "type": "integer"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Context Tokens"+ },+ "context_length": {+ "anyOf": [+ {+ "type": "integer"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Context Length"+ },+ "config_context_length": {+ "anyOf": [+ {+ "type": "integer"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Config Context Length"+ },+ "context_source": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Context Source"+ },+ "compression_count": {+ "anyOf": [+ {+ "type": "integer"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Compression Count"+ },+ "avg_latency_s": {+ "anyOf": [+ {+ "type": "number"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Avg Latency S"+ },+ "tokens_per_s": {+ "anyOf": [+ {+ "type": "number"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Tokens Per S"+ },+ "last_turn_tokens": {+ "anyOf": [+ {+ "type": "integer"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Last Turn Tokens"+ },+ "rate_limit": {+ "anyOf": [+ {+ "additionalProperties": true,+ "type": "object"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Rate Limit"+ },+ "active_subagents": {+ "anyOf": [+ {+ "type": "integer"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Active Subagents"+ },+ "model": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Model"+ },+ "provider": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Provider"+ },+ "fallback_model": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Fallback Model"}},- "required": [- "usage"- ],"title": "SessionUsagePayload","type": "object"},@@ -45225,6 +45696,24 @@}}},+ {+ "name": "session.stats",+ "summary": "The session.usage dict on demand: what main's classic CLI read off its agent.",+ "params": [+ {+ "name": "params",+ "schema": {+ "$ref": "#/components/schemas/SessionStatsParams"+ }+ }+ ],+ "result": {+ "name": "result",+ "schema": {+ "$ref": "#/components/schemas/SessionStats"+ }+ }+ },{"name": "session.steer","summary": "",diff --git a/gateway/run_turn_progress.py b/gateway/run_turn_progress.pyindex 3adb7277fa1..c603aa14b76 100644--- a/gateway/run_turn_progress.py+++ b/gateway/run_turn_progress.py@@ -860,6 +860,11 @@ class GatewayTurnProgressMixin:if not ctx._run_still_current():returnself._publish_execution("agent.step", {"iteration": iteration})+ if iteration > 1 and local_viewer_turn(self):+ # Each step after the first follows a finished API call: main's CLI repainted its status+ # bar from the agent's counters right then (the last call is covered at turn end).+ from gateway.session_usage import publish_usage+ publish_usage(self, ctx.agent_holder[0])if not ctx._hooks_ref.loaded_hooks:return# prev_tools may be list[str] or list[dict] with "name"/"result" keys. Normalise sodiff --git a/gateway/run_turn_runner.py b/gateway/run_turn_runner.pyindex d6dfc9abaeb..85f58b6810f 100644--- a/gateway/run_turn_runner.py+++ b/gateway/run_turn_runner.py@@ -1231,6 +1231,8 @@ class TurnRunner(GatewayTurnProgressMixin, GatewaySessionAgentMixin):# Per turn on the shared cached agent: installed here, restored when the run returns.from gateway import local_viewer_eventslocal_sinks = local_viewer_events.wire(self, agent)+ from gateway.session_usage import TURN_BASE_ATTR+ setattr(agent, TURN_BASE_ATTR, int(getattr(agent, "session_output_tokens", 0) or 0))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)@@ -1242,6 +1244,8 @@ class TurnRunner(GatewayTurnProgressMixin, GatewaySessionAgentMixin):if local_sinks is not None:from gateway import local_viewer_eventslocal_viewer_events.restore(agent, local_sinks)+ from gateway.session_usage import publish_usage+ publish_usage(self, agent) # turn end: the final API call's counterspersisted_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_controls.py b/gateway/session_controls.pyindex 2cb7937744d..5f049b5715a 100644--- a/gateway/session_controls.py+++ b/gateway/session_controls.py@@ -14,7 +14,7 @@ from hermes_state_runtime import RuntimeStoreError# Verbs whose param sets are closed and never carried a ``profile`` key._PROFILE_IMPLICIT = frozenset({'session.create', 'session.list', 'session.info', 'session.resume', 'session.detach','prompt.submit', 'prompt.receipt', 'prompt.cancel', 'prompt.resolve_unknown',- 'session.interrupt', 'session.events.since', 'session.mutate',+ 'session.interrupt', 'session.events.since', 'session.mutate', 'session.stats','approval.respond', 'clarify.respond'})@@ -104,6 +104,8 @@ class AuthorityConnection:handlers['image.attach_bytes'] = partial(attach_bytes, self)from gateway.session_prune import prunehandlers['session.prune'] = partial(prune, self)+ from gateway.session_usage import stats+ handlers['session.stats'] = partial(stats, self)return handlersasync def dispatch(self, request):diff --git a/gateway/session_usage.py b/gateway/session_usage.pynew file mode 100644index 00000000000..9a425a9c962--- /dev/null+++ b/gateway/session_usage.py@@ -0,0 +1,100 @@+"""Session-cumulative usage for a local viewer (wave A2 / CALLMAP W3).++Main's HermesCLI read its status bar (context, ``◷`` latency, ``t/s``, the spinner's ``↓ N tok``),+``/usage`` and the exit summary straight off the in-process agent's ``session_*`` counters,+``context_compressor`` and ``get_rate_limit_state()``. On the session authority the agent lives in+the gateway, so the same numbers are projected here: published as ``session.usage`` after every API+call and at turn end of a local-viewer turn, and returned by the ``session.stats`` verb.+"""+from __future__ import annotations++import contextlib+import dataclasses++_COUNTERS = (("input_tokens", "session_input_tokens"), ("output_tokens", "session_output_tokens"),+ ("cache_read_tokens", "session_cache_read_tokens"),+ ("cache_write_tokens", "session_cache_write_tokens"),+ ("prompt_tokens", "session_prompt_tokens"), ("completion_tokens", "session_completion_tokens"),+ ("total_tokens", "session_total_tokens"), ("reasoning_tokens", "session_reasoning_tokens"),+ ("api_calls", "session_api_calls"))+# The output-token count at the start of the viewer's current turn (``↓ N tok`` on main's spinner).+TURN_BASE_ATTR = "_viewer_turn_output_base"+++def _finite(value):+ return round(float(value), 2) if value is not None and value == value and 0 < value < 1e6 else None+++def _context(agent, compressor) -> dict:+ """Main's status-bar context figures (``_get_status_bar_snapshot``), clamped the same way."""+ if compressor is None:+ return {"last_prompt_tokens": 0, "context_tokens": 0, "context_length": None,+ "config_context_length": None, "context_source": None, "compression_count": 0}+ from agent.context_breakdown import context_display_source+ last = max(0, getattr(compressor, "last_prompt_tokens", 0) or 0)+ tokens = last+ with contextlib.suppress(Exception):+ from agent.usage_anchor import anchored_context_tokens+ messages = getattr(agent, "_session_messages", None)+ anchored = anchored_context_tokens(messages if isinstance(messages, list) else [],+ getattr(agent, "_turn_base_usage_anchor", None),+ charge_stale_thinking=False)+ if anchored is not None and anchored > 0:+ tokens = anchored+ length = max(0, getattr(compressor, "context_length", 0) or 0)+ return {"last_prompt_tokens": last, "context_tokens": min(tokens, length) if length else tokens,+ "context_length": length or None,+ "config_context_length": getattr(compressor, "_config_context_length", None),+ "context_source": context_display_source(compressor),+ "compression_count": getattr(compressor, "compression_count", 0) or 0}+++def _rate_limit(agent):+ with contextlib.suppress(Exception):+ state = agent.get_rate_limit_state()+ if state is not None and dataclasses.is_dataclass(state) and not isinstance(state, type):+ return dataclasses.asdict(state)+ return None+++def usage_stats(agent) -> dict:+ """The frozen ``session.usage`` / ``session.stats`` dict; zeros before the first turn built an agent."""+ stats: dict = {key: int(getattr(agent, attr, 0) or 0) for key, attr in _COUNTERS}+ stats.update(_context(agent, getattr(agent, "context_compressor", None)))+ avg_latency = tps = None+ with contextlib.suppress(Exception):+ latencies = list(getattr(agent, "_api_latency_history", None) or [])+ outputs = list(getattr(agent, "_api_output_history", None) or [])+ if n := min(len(latencies), len(outputs)):+ total = sum(latencies[-n:])+ avg_latency = _finite(total / n)+ tps = _finite(sum(outputs[-n:]) / total) if total > 0 else None+ active = 0+ with contextlib.suppress(Exception):+ from tools.async_delegation import active_count+ active = active_count()+ base = getattr(agent, TURN_BASE_ATTR, None)+ stats.update(avg_latency_s=avg_latency, tokens_per_s=tps,+ last_turn_tokens=max(0, stats["output_tokens"] - base) if isinstance(base, int) else 0,+ rate_limit=_rate_limit(agent) if agent is not None else None, active_subagents=active,+ model=str(getattr(agent, "model", "") or ""), provider=str(getattr(agent, "provider", "") or ""),+ fallback_model=(str(getattr(agent, "model", "") or "") or None)+ if getattr(agent, "_fallback_activated", False) is True else None)+ return stats+++def publish_usage(turn, agent) -> None:+ """One ``session.usage`` frame on the viewer's stream; never breaks the turn."""+ if agent is None:+ return+ with contextlib.suppress(Exception):+ turn._publish_execution("session.usage", usage_stats(agent))+++async def stats(connection, ref, params):+ """``session.stats {session_id}``: the same dict ``session.usage`` carries."""+ from hermes_state_runtime import RuntimeStoreError+ if set(params) - {"session_id", "profile"}:+ raise RuntimeStoreError("invalid_params")+ await connection.authority.resolve(connection.actor, ref)+ return usage_stats(connection.authority.agent(ref))diff --git a/tests/gateway/test_local_viewer_usage.py b/tests/gateway/test_local_viewer_usage.pynew file mode 100644index 00000000000..d7a6de3bbcb--- /dev/null+++ b/tests/gateway/test_local_viewer_usage.py@@ -0,0 +1,89 @@+"""``session.usage`` / ``session.stats``: the session-cumulative counters main's HermesCLI read off its+in-process agent (status bar, /usage, exit summary), published from the gateway (wave A2, CALLMAP W3)."""+from __future__ import annotations++from collections import deque+from types import SimpleNamespace++import pytest++from gateway.config import Platform++FIELDS = {'input_tokens', 'output_tokens', 'cache_read_tokens', 'cache_write_tokens', 'prompt_tokens',+ 'completion_tokens', 'total_tokens', 'reasoning_tokens', 'api_calls', 'last_prompt_tokens',+ 'context_tokens', 'context_length', 'config_context_length', 'context_source', 'compression_count',+ 'avg_latency_s', 'tokens_per_s', 'last_turn_tokens', 'rate_limit', 'active_subagents', 'model',+ 'provider', 'fallback_model'}+++def _agent():+ compressor = SimpleNamespace(last_prompt_tokens=900, context_length=128000, _config_context_length=128000,+ compression_count=1)+ return SimpleNamespace(+ model='fake-model', provider='custom', session_id='sid',+ session_input_tokens=100, session_output_tokens=40, session_cache_read_tokens=10,+ session_cache_write_tokens=5, session_prompt_tokens=115, session_completion_tokens=40,+ session_total_tokens=155, session_reasoning_tokens=3, session_api_calls=2,+ context_compressor=compressor, _api_latency_history=deque([1.0, 3.0]),+ _api_output_history=deque([10, 30]), get_rate_limit_state=lambda: None,+ _session_messages=[], _turn_base_usage_anchor=None)+++def test_usage_stats_is_exactly_the_frozen_field_list():+ from gateway.session_usage import usage_stats+ stats = usage_stats(_agent())+ assert set(stats) == FIELDS+ assert stats['input_tokens'] == 100 and stats['api_calls'] == 2 and stats['total_tokens'] == 155+ assert stats['avg_latency_s'] == 2.0 and stats['tokens_per_s'] == 10.0+ assert stats['context_length'] == 128000 and stats['compression_count'] == 1+ assert stats['rate_limit'] is None and stats['fallback_model'] is None+ from tui_gateway.contracts.registry import EVENTS+ EVENTS['session.usage'].payload.model_validate(stats)+++def _turn(platform, published, agent):+ from gateway.run_turn_runner import TurnRunner+ turn = object.__new__(TurnRunner)+ turn._ctx = SimpleNamespace(source=SimpleNamespace(platform=platform, chat_id='chat'), _step_callback_sync=None,+ _run_still_current=lambda: True, agent_holder=[agent],+ _hooks_ref=SimpleNamespace(loaded_hooks=[]))+ turn._runner = SimpleNamespace()+ turn._approval_owner = (SimpleNamespace(sessions={'s': SimpleNamespace()}), 's', 1)+ turn._publish_execution = lambda kind, payload: published.append((kind, payload)) or True+ return turn++[email protected]('platform', [Platform.LOCAL, Platform.TELEGRAM])+def test_each_api_step_publishes_usage_only_for_local_viewers(platform):+ published = []+ turn = _turn(platform, published, _agent())+ turn._step_callback_sync(2, [])+ kinds = [kind for kind, _ in published]+ if platform == Platform.LOCAL:+ usage = next(payload for kind, payload in published if kind == 'session.usage')+ assert set(usage) == FIELDS and usage['api_calls'] == 2+ else:+ assert 'session.usage' not in kinds+++async def test_session_stats_returns_the_same_dict(tmp_path, monkeypatch):+ from gateway.session_controls import AuthorityConnection+ from tests.gateway.test_surface_admission import _authority+ from tui_gateway.contracts.registry import CANONICAL_METHODS++ async def answer(event):+ return 'ok'+ authority = await _authority(tmp_path, monkeypatch, answer)+ agent = _agent()+ authority.runner._cached_agent_for = lambda route: agent+ connection = AuthorityConnection(authority, object(), {'user_id': 'owner'})+ try:+ await connection.dispatch({'id': 1, 'method': 'session.resume', 'params': {'session_id': 's'}})+ reply = await connection.dispatch({'id': 2, 'method': 'session.stats', 'params': {'session_id': 's'}})+ assert 'result' in reply, reply+ from gateway.session_usage import usage_stats+ assert reply['result'] == usage_stats(agent)+ CANONICAL_METHODS['session.stats'].result.model_validate(reply['result'])+ finally:+ await connection.close()diff --git a/tui_gateway/contracts/canonical.py b/tui_gateway/contracts/canonical.pyindex cd9106ba087..e43917e19f6 100644--- a/tui_gateway/contracts/canonical.py+++ b/tui_gateway/contracts/canonical.py@@ -171,6 +171,43 @@ canonical_method("session.info", params=CanonicalSessionInfoParams, result=Canondoc="Frozen launch policy projection of one local session.")+class SessionStatsParams(Params):+ session_id: str+++class SessionStats(Result):+ """``gateway/session_usage.py::usage_stats``: session-cumulative counters (the agent's ``session_*``),+ context / compressor figures, rolling latency and throughput, rate-limit state, live subagents."""++ input_tokens: int+ output_tokens: int+ cache_read_tokens: int+ cache_write_tokens: int+ prompt_tokens: int+ completion_tokens: int+ total_tokens: int+ reasoning_tokens: int+ api_calls: int+ last_prompt_tokens: int+ context_tokens: int+ context_length: int | None = None+ config_context_length: int | None = None+ context_source: str | None = None+ compression_count: int+ avg_latency_s: float | None = None+ tokens_per_s: float | None = None+ last_turn_tokens: int+ rate_limit: dict[str, JsonValue] | None = None+ active_subagents: int+ model: str+ provider: str+ fallback_model: str | None = None+++canonical_method("session.stats", params=SessionStatsParams, result=SessionStats,+ doc="The session.usage dict on demand: what main's classic CLI read off its agent.")++class SessionDetachParams(Params):session_id: strsubscription_id: strdiff --git a/tui_gateway/contracts/events.py b/tui_gateway/contracts/events.pyindex 8666d7f0d29..a6b65eac320 100644--- a/tui_gateway/contracts/events.py+++ b/tui_gateway/contracts/events.py@@ -240,9 +240,34 @@ event("status.update", StatusUpdatePayload, doc="Transient status line (kind: stclass SessionUsagePayload(Payload):- """``server._start_usage_ticker``."""+ """``server._start_usage_ticker`` (``usage``), or a canonical local viewer's session-cumulative+ counters (``gateway/session_usage.py::usage_stats``, the ``session.stats`` dict) at the top level:+ published after every API call and at turn end, what main's classic CLI read off its agent."""- usage: Usage+ usage: Usage | None = None+ input_tokens: int | None = None+ output_tokens: int | None = None+ cache_read_tokens: int | None = None+ cache_write_tokens: int | None = None+ prompt_tokens: int | None = None+ completion_tokens: int | None = None+ total_tokens: int | None = None+ reasoning_tokens: int | None = None+ api_calls: int | None = None+ last_prompt_tokens: int | None = None+ context_tokens: int | None = None+ context_length: int | None = None+ config_context_length: int | None = None+ context_source: str | None = None+ compression_count: int | None = None+ avg_latency_s: float | None = None+ tokens_per_s: float | None = None+ last_turn_tokens: int | None = None+ rate_limit: dict[str, JsonValue] | None = None+ active_subagents: int | None = None+ model: str | None = None+ provider: str | None = None+ fallback_model: str | None = Noneevent("session.usage", SessionUsagePayload, doc="Mid-turn usage tick; message.complete carries the authoritative final usage.")