The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(cli,gateway): /context prints the gateway agent's breakdown (session.context_breakdown on the owner)
Teknium0dbd4c86ece2
diff --git a/gateway/session_tui_ops.py b/gateway/session_tui_ops.pyindex 12c00e49648..ea9a15a2ac3 100644--- a/gateway/session_tui_ops.py+++ b/gateway/session_tui_ops.py@@ -15,6 +15,7 @@ from functools import partialfrom pathlib import Pathfrom gateway.session_busy_controls import authorize+from gateway.session_tui_reads import context_breakdownfrom hermes_state_runtime import RuntimeStoreError@@ -24,7 +25,8 @@ def handlers(connection):'delegation.pause': partial(pause_delegation, connection),'rollback.list': partial(rollback, connection, kind='list'),'rollback.diff': partial(rollback, connection, kind='diff'),- 'rollback.restore': partial(rollback, connection, kind='restore')}+ 'rollback.restore': partial(rollback, connection, kind='restore'),+ 'session.context_breakdown': partial(context_breakdown, connection)}def _profile_home(authority):diff --git a/gateway/session_tui_reads.py b/gateway/session_tui_reads.pyindex be1b243e3c1..6ec610044d4 100644--- a/gateway/session_tui_reads.py+++ b/gateway/session_tui_reads.py@@ -128,3 +128,43 @@ async def run_tui_read(authority, ref, live, policy, render, arg) -> dict:with owner_scope(authority), _session_workspace(authority.runner, live.source):return render(authority, ref, live, policy, agent, arg)return {'type': 'exec', 'output': await asyncio.to_thread(build)}+++async def context_breakdown(connection, ref, params) -> dict:+ """``session.context_breakdown`` on the owner: the category estimate (``compute_session_context_+ breakdown``) and context-file manifest of this session's resident agent over its stored+ transcript, built in the session's workspace. Before the agent exists: empty categories plus the+ session's stored usage (the contract's pre-build shape)."""+ from gateway.session_busy_controls import authorize+ from hermes_state_runtime import RuntimeStoreError+ if set(params) - {'session_id', 'profile'} or not isinstance(ref.session_id, str) or not ref.session_id:+ raise RuntimeStoreError('invalid_params')+ authorize(connection, ref, params, 'session:read')+ authority = connection.authority+ live = authority.sessions.get(ref.session_id)+ if live is None:+ raise RuntimeStoreError('not_found')+ agent = authority.agent(ref)+ if agent is None:+ from gateway.session_usage import stats+ usage = await stats(connection, ref, {'session_id': ref.session_id})+ usage = usage.get('usage') if isinstance(usage.get('usage'), dict) else usage+ return {'categories': [], 'context_max': int(usage.get('context_max') or 0),+ 'context_percent': int(usage.get('context_percent') or 0),+ 'context_used': int(usage.get('context_used') or 0), 'estimated_total': 0,+ 'context_estimated': bool(usage.get('context_estimated', False)),+ 'context_source': str(usage.get('context_source') or 'provider_usage'),+ 'model': str(usage.get('model') or '')}+ from gateway.session_authorities import owner_scope+ from gateway.session_commands import _session_workspace+ stored = _stored_id(authority, ref)++ def build():+ from agent.context_breakdown import compute_session_context_breakdown+ from agent.context_file_sources import context_file_sources_for_agent+ with owner_scope(authority), _session_workspace(authority.runner, live.source):+ conversation = authority.db.get_messages_as_conversation(stored, include_ancestors=True)+ payload = compute_session_context_breakdown(agent, conversation)+ payload['context_files'] = context_file_sources_for_agent(agent)+ return payload+ return await asyncio.to_thread(build)diff --git a/hermes_cli/cli_info_mixin.py b/hermes_cli/cli_info_mixin.pyindex 582f66bd827..42ea3d90753 100644--- a/hermes_cli/cli_info_mixin.py+++ b/hermes_cli/cli_info_mixin.py@@ -630,6 +630,9 @@ class CLIInfoMixin:"""`/context [all]` — 5×20 glyph grid (cell ≈ 1% of the window) plus an estimatedper-category table; `all` appends per-skill / per-toolset costs. Read-only: same chars/4engine as the desktop popover (agent.context_breakdown) — no provider calls, no cache impact."""+ from hermes_cli.gateway_side import connection_for+ if (connection := connection_for(self)) is not None:+ return self._show_gateway_context_breakdown(connection)if not self.agent:print(f" {t('cli.shared.no_active_agent')}")return@@ -666,6 +669,28 @@ class CLIInfoMixin:print(f" {line}")print()+ def _show_gateway_context_breakdown(self, connection):+ """Main's ``/context`` grid and table over the gateway agent's own breakdown+ (``session.context_breakdown``): the session's prompt, tools and transcript live there."""+ from agent.context_breakdown import render_context_breakdown_lines+ from agent.context_file_sources import render_context_file_lines+ from hermes_cli.gateway_client import GatewayClientError+ try:+ payload = connection.call("session.context_breakdown", session_id=self.session_id)+ except GatewayClientError as e:+ print(f" {t('cli.context.compute_failed', error=str(e))}")+ return+ if not payload.get("categories"):+ print(f" {t('cli.shared.no_active_agent')}")+ return+ file_lines = render_context_file_lines(payload.get("context_files") or [])+ print()+ print(f" {t('cli.context.header', model=payload.get('model') or self.model)}")+ print()+ for line in render_context_breakdown_lines(payload, grid=True) + (["", *file_lines] if file_lines else []):+ print(f" {line}")+ print()+def _show_usage(self):"""Rate limits + session token usage (when a live agent exists) + Nous credits.diff --git a/tests/gateway/test_tui_session_reads.py b/tests/gateway/test_tui_session_reads.pyindex 040fa2d6465..c63b92a8b66 100644--- a/tests/gateway/test_tui_session_reads.py+++ b/tests/gateway/test_tui_session_reads.py@@ -118,3 +118,22 @@ async def test_other_surfaces_keep_the_gateway_handlers(owner):policy = SimpleNamespace(source=source)assert tui_read(policy, 'status', '') is None and tui_read(policy, 'context', '') is Noneassert tui_read(None, 'status', '') is None+++async def test_context_breakdown_verb_serves_the_owner_agents_categories(owner, monkeypatch):+ """The classic CLI's /context (and Desktop's popover) read the breakdown of the gateway's own+ agent through ``session.context_breakdown``; before the agent exists it is the empty shape."""+ sid = (await owner.call('session.create', request_id='c', source='cli', cwd=str(owner.workdir)))['session_id']+ empty = await owner.call('session.context_breakdown', session_id=sid)+ assert empty['categories'] == [] and empty['estimated_total'] == 0+ from agent import context_breakdown, context_file_sources+ agent = SimpleNamespace(model='fake-model', provider='custom')+ owner.authority.runner._cached_agent_for = lambda route: agent+ monkeypatch.setattr(context_breakdown, 'compute_session_context_breakdown', lambda a, m: {+ 'categories': [{'id': 'system', 'label': 'System prompt', 'tokens': 3000, 'color': '#fff'}],+ 'context_max': 128000, 'context_used': 120, 'context_percent': 0, 'estimated_total': 3000,+ 'context_estimated': False, 'context_source': 'provider_usage', 'model': 'fake-model'} if a is agent else {})+ monkeypatch.setattr(context_file_sources, 'context_file_sources_for_agent', lambda a: [])+ live = await owner.call('session.context_breakdown', session_id=sid)+ assert live['categories'][0]['tokens'] == 3000 and live['model'] == 'fake-model', live