The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(gateway,tui): the canonical session snapshot carries main's banner inventory
Tekniume2d7bb85e3fd
diff --git a/apps/shared/src/gateway-contract.generated.ts b/apps/shared/src/gateway-contract.generated.tsindex ddf57798dc6..38c16192ed9 100644--- a/apps/shared/src/gateway-contract.generated.ts+++ b/apps/shared/src/gateway-contract.generated.ts@@ -4510,8 +4510,22 @@ export interface SessionPruneResult {export interface CanonicalSessionInfoParams {session_id: string}-/** ``gateway/session_local.py::local_session_info``. */+/** ``gateway/session_local_inventory.py::snapshot_info``: ``local_session_info`` + the inventory. */export interface CanonicalSessionInfo {+ provider?: string | null+ tools?: Record<string, string[]> | null+ skills?: Record<string, string[]> | null+ mcp_servers?: McpServerStatus[] | null+ version?: string | null+ release_date?: string | null+ update_behind?: unknown | null+ update_command?: string | null+ branch?: string | null+ project?: ProjectRef | null+ system_prompt?: string | null+ context_length?: number | null+ enabled_toolsets?: string[] | null+ tool_availability?: Record<string, unknown> | nullsource: stringmodel?: string | nulllazy: boolean@@ -4776,6 +4790,20 @@ export interface CanonicalPendingPrompt {multi_select?: boolean | null}export interface CanonicalSnapshotInfo {+ provider?: string | null+ tools?: Record<string, string[]> | null+ skills?: Record<string, string[]> | null+ mcp_servers?: McpServerStatus[] | null+ version?: string | null+ release_date?: string | null+ update_behind?: unknown | null+ update_command?: string | null+ branch?: string | null+ project?: ProjectRef | null+ system_prompt?: string | null+ context_length?: number | null+ enabled_toolsets?: string[] | null+ tool_availability?: Record<string, unknown> | nulldesktop_protocol: 'hermes-gateway-v1'source?: string | nullmodel?: string | nulldiff --git a/apps/shared/src/gateway-contract.openrpc.json b/apps/shared/src/gateway-contract.openrpc.jsonindex 6b4c191c301..b01b8bc8789 100644--- a/apps/shared/src/gateway-contract.openrpc.json+++ b/apps/shared/src/gateway-contract.openrpc.json@@ -9672,8 +9672,192 @@},"CanonicalSessionInfo": {"additionalProperties": true,- "description": "``gateway/session_local.py::local_session_info``.",+ "description": "``gateway/session_local_inventory.py::snapshot_info``: ``local_session_info`` + the inventory.","properties": {+ "provider": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Provider"+ },+ "tools": {+ "anyOf": [+ {+ "additionalProperties": {+ "items": {+ "type": "string"+ },+ "type": "array"+ },+ "type": "object"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Tools"+ },+ "skills": {+ "anyOf": [+ {+ "additionalProperties": {+ "items": {+ "type": "string"+ },+ "type": "array"+ },+ "type": "object"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Skills"+ },+ "mcp_servers": {+ "anyOf": [+ {+ "items": {+ "$ref": "#/components/schemas/McpServerStatus"+ },+ "type": "array"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Mcp Servers"+ },+ "version": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Version"+ },+ "release_date": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Release Date"+ },+ "update_behind": {+ "anyOf": [+ {},+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Update Behind"+ },+ "update_command": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Update Command"+ },+ "branch": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Branch"+ },+ "project": {+ "anyOf": [+ {+ "$ref": "#/components/schemas/ProjectRef"+ },+ {+ "type": "null"+ }+ ],+ "default": null+ },+ "system_prompt": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "System Prompt"+ },+ "context_length": {+ "anyOf": [+ {+ "type": "integer"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Context Length"+ },+ "enabled_toolsets": {+ "anyOf": [+ {+ "items": {+ "type": "string"+ },+ "type": "array"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Enabled Toolsets"+ },+ "tool_availability": {+ "anyOf": [+ {+ "additionalProperties": true,+ "type": "object"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Tool Availability"+ },"source": {"title": "Source","type": "string"@@ -10026,6 +10210,190 @@"CanonicalSnapshotInfo": {"additionalProperties": false,"properties": {+ "provider": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Provider"+ },+ "tools": {+ "anyOf": [+ {+ "additionalProperties": {+ "items": {+ "type": "string"+ },+ "type": "array"+ },+ "type": "object"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Tools"+ },+ "skills": {+ "anyOf": [+ {+ "additionalProperties": {+ "items": {+ "type": "string"+ },+ "type": "array"+ },+ "type": "object"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Skills"+ },+ "mcp_servers": {+ "anyOf": [+ {+ "items": {+ "$ref": "#/components/schemas/McpServerStatus"+ },+ "type": "array"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Mcp Servers"+ },+ "version": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Version"+ },+ "release_date": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Release Date"+ },+ "update_behind": {+ "anyOf": [+ {},+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Update Behind"+ },+ "update_command": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Update Command"+ },+ "branch": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Branch"+ },+ "project": {+ "anyOf": [+ {+ "$ref": "#/components/schemas/ProjectRef"+ },+ {+ "type": "null"+ }+ ],+ "default": null+ },+ "system_prompt": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "System Prompt"+ },+ "context_length": {+ "anyOf": [+ {+ "type": "integer"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Context Length"+ },+ "enabled_toolsets": {+ "anyOf": [+ {+ "items": {+ "type": "string"+ },+ "type": "array"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Enabled Toolsets"+ },+ "tool_availability": {+ "anyOf": [+ {+ "additionalProperties": true,+ "type": "object"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Tool Availability"+ },"desktop_protocol": {"const": "hermes-gateway-v1","title": "Desktop Protocol",diff --git a/gateway/session_controls.py b/gateway/session_controls.pyindex 856dc8a0cdd..a5d2585f916 100644--- a/gateway/session_controls.py+++ b/gateway/session_controls.py@@ -316,11 +316,11 @@ class AuthorityConnection:'parameters': sorted(CREATE_FIELDS | {'title'})}}async def info(self, ref, params):- from gateway.session_local import local_session_info+ from gateway.session_local_inventory import snapshot_infoif set(params) != {'session_id'}:raise RuntimeStoreError('invalid_params')await self.authority.resolve(self.actor, ref)- return local_session_info(self.authority, ref)+ return await snapshot_info(self.authority, ref)async def list_sessions(self, ref, params):if 'session:read' not in self.actor.capabilities:@@ -370,7 +370,7 @@ class AuthorityConnection:return {'sessions': sessions[:limit], 'scope': 'live'}async def resume(self, ref, params):- from gateway.session_local import local_session_info+ from gateway.session_local_inventory import snapshot_infoif 'latest' in params:# Bare `-c` / `--resume latest`: the most recent session of that surface family the# actor may read (workspace first), resolved by the owner like a title.@@ -401,11 +401,12 @@ class AuthorityConnection:self.authority.authorize(self.actor, ref, 'session:read')snapshot = await self.authority.attach(self.actor, ref)self.subscriptions[ref.session_id] = snapshot.subscription_id- # Only local routes have a frozen local launch policy to project.+ # Only local routes have a frozen local launch policy to project; with it, main's banner and+ # status-bar inventory (tools, skills, MCP, version, branch) for that policy.info = {'desktop_protocol': CANONICAL_GATEWAY_PROTOCOL}source = self.authority.sessions[snapshot.handle.ref.session_id].sourceif source is not None and source.platform == Platform.LOCAL:- info = local_session_info(self.authority, snapshot.handle.ref)+ info = await snapshot_info(self.authority, snapshot.handle.ref)return {'session_id': ref.session_id, 'stored_session_id': ref.session_id,'messages': list(snapshot.history), 'message_count': len(snapshot.history),'running': snapshot.handle.execution_state == 'running',diff --git a/gateway/session_local_inventory.py b/gateway/session_local_inventory.pynew file mode 100644index 00000000000..af2725843b0--- /dev/null+++ b/gateway/session_local_inventory.py@@ -0,0 +1,138 @@+"""Main's banner / status-bar inventory for a canonical local session.++``tui_gateway/server.py::_session_info`` on main put the session's tools (by toolset), skills (by+category), MCP servers, version / release date, update notice, git branch, project and provider on+every ``session.info`` / create / resume ``info``; the Ink banner (``components/branding.tsx``) and+the classic CLI banner (``hermes_cli/banner.py::build_welcome_banner``) render them. A canonical+session's agent is built on its first turn, so the inventory is computed here from the session's+frozen policy (the toolsets that turn will run with), with main's own builders, in the owner+process. Every builder does I/O (skills tree walk, tool ``check_fn`` probes, git), so callers run+:func:`session_inventory` off the owner loop (:func:`snapshot_info`).+"""+from __future__ import annotations++import asyncio+import contextlib+import logging++logger = logging.getLogger(__name__)++_update_prefetch_started = False+++def _start_update_prefetch():+ """Main's TUI gateway started the passive update check at import; the owner starts it once,+ on the first snapshot, so ``update_behind`` reports like main's banner instead of staying null."""+ global _update_prefetch_started+ if _update_prefetch_started:+ return+ _update_prefetch_started = True+ from hermes_cli.banner import prefetch_update_check+ prefetch_update_check()+++def _grouped(tools):+ """``{toolset: [tool names]}`` exactly as main's ``_session_info`` grouped ``agent.tools``."""+ from model_tools import get_toolset_for_tool+ grouped: dict[str, list[str]] = {}+ for tool in tools or []:+ name = tool["function"]["name"]+ grouped.setdefault(get_toolset_for_tool(name) or "other", []).append(name)+ return grouped+++def _policy_tools(policy, config):+ """The tool list the session's next agent build loads (``agent/agent_init.py`` tool snapshot):+ the policy's toolsets minus the configured and platform-gated disabled ones, one-shot pruned."""+ import model_tools+ from agent.oneshot_footprint import ONESHOT_HIDDEN_TOOLS+ from agent.skill_utils import parse_config_string_list+ from toolsets import session_disabled_toolsets, session_platform_tool_drops+ enabled = list(policy.current_toolsets(config))+ disabled = session_disabled_toolsets(+ parse_config_string_list((config.get("agent") or {}).get("disabled_toolsets")) or None, policy.platform)+ tools = model_tools.get_tool_definitions(enabled_toolsets=enabled, disabled_toolsets=disabled, quiet_mode=True)+ drops = set(session_platform_tool_drops(policy.platform))+ if policy.source == "oneshot":+ drops |= ONESHOT_HIDDEN_TOOLS+ return enabled, [tool for tool in tools or [] if tool["function"]["name"] not in drops]+++def _project(cwd):+ """``tui_gateway/server.py::_project_info_for_cwd``: the named project owning *cwd*, or None."""+ if not str(cwd or "").strip():+ return None+ from hermes_cli import projects_db as pdb+ try:+ with pdb.connect_closing() as conn:+ project = pdb.project_for_path(conn, cwd)+ except Exception: # health: allow BLE001 -- main's resolver: an unreadable projects.db names no project+ logger.debug("failed to resolve project for cwd", exc_info=True)+ return None+ return None if project is None else {+ "id": project.id, "slug": project.slug, "name": project.name, "primary_path": project.primary_path}+++def session_inventory(authority, policy, agent, cwd):+ """Main's banner/status fields for one session. Each section degrades to main's empty value on+ its own, so one failing builder never blanks the others (main wrapped each in ``suppress``)."""+ from gateway.session_authorities import owner_scope+ from tui_gateway import git_probe+ info: dict = {"tools": {}, "skills": {}, "mcp_servers": [], "version": "", "release_date": "",+ "update_behind": None, "update_command": "",+ "branch": git_probe.branch(cwd) if cwd else "", "project": _project(cwd)}+ with owner_scope(authority):+ config = policy.config(authority, secrets=False) if policy is not None else {}+ if agent is not None:+ from agent.voice_turn_route import session_runtime_view+ view = session_runtime_view(agent)+ info["provider"] = getattr(view, "provider", "") or ""+ info["tools"] = _grouped(getattr(agent, "tools", None))+ info["system_prompt"] = getattr(agent, "_cached_system_prompt", "") or ""+ compressor = getattr(agent, "context_compressor", None)+ if compressor is not None and getattr(compressor, "context_length", None):+ info["context_length"] = compressor.context_length+ enabled = list(getattr(agent, "enabled_toolsets", None) or [])+ else:+ info["provider"] = str((config.get("model") or {}).get("provider") or "")+ enabled = []+ if policy is not None:+ try:+ enabled, tools = _policy_tools(policy, config)+ info["tools"] = _grouped(tools)+ except Exception: # health: allow BLE001 -- main's suppress: the banner shows no tools, not an error+ logger.warning("session inventory: tool snapshot failed", exc_info=True)+ info["enabled_toolsets"] = sorted(enabled)+ with contextlib.suppress(Exception):+ # The classic CLI banner colours lazy (yellow) / disabled (red) tools from this.+ from hermes_cli.banner import compute_toolset_availability+ info["tool_availability"] = compute_toolset_availability(enabled)+ with contextlib.suppress(Exception):+ from hermes_cli.banner import get_available_skills+ info["skills"] = get_available_skills()+ with contextlib.suppress(Exception):+ from tools.mcp_tool_discovery import get_mcp_status+ info["mcp_servers"] = get_mcp_status()+ with contextlib.suppress(Exception):+ from hermes_cli import __release_date__+ from hermes_cli.version_info import get_version_info+ info.update(version=get_version_info().base_version, release_date=__release_date__)+ with contextlib.suppress(Exception):+ from hermes_cli.banner import get_update_result+ from hermes_cli.config import recommended_update_command+ _start_update_prefetch()+ # Two assignments, as on main: a failing command lookup still reports update_behind.+ info["update_behind"] = get_update_result(timeout=0.5)+ info["update_command"] = recommended_update_command()+ return info+++async def snapshot_info(authority, ref):+ """``local_session_info`` plus main's inventory, the builders run off the owner loop."""+ from gateway.session_local import local_session_info+ from gateway.session_policy import policy_for_source+ info = local_session_info(authority, ref)+ policy = policy_for_source(authority.runner, authority.sessions[ref.session_id].source)+ agent = authority.agent(ref)+ inventory = await asyncio.to_thread(session_inventory, authority, policy, agent, info.get("cwd"))+ return {**inventory, **info}diff --git a/locales/_keys.tui.json b/locales/_keys.tui.jsonindex d11c07e3c4a..a17a59564e0 100644--- a/locales/_keys.tui.json+++ b/locales/_keys.tui.json@@ -104,7 +104,6 @@"canonical.images.tooLarge","canonical.images.unsupported","canonical.launch.invalidToolProgress",- "canonical.launch.inventoryUnavailable","canonical.launch.noTuiPolicy","canonical.launch.unsupportedOptions","canonical.queue.clipboardImageFailed",diff --git a/locales/af.tui.yaml b/locales/af.tui.yamlindex dacc8ca6395..0b37986a82b 100644--- a/locales/af.tui.yaml+++ b/locales/af.tui.yaml@@ -108,7 +108,6 @@ canonical.images.notFound: "Beeld nie gevind nie: {0}"canonical.images.tooLarge: "Beeld oorskry die oplaaigrens van 20 MiB"canonical.images.unsupported: "Nie-ondersteunde beeld: PNG-, JPEG-, GIF- of WebP-grepe verwag"canonical.launch.invalidToolProgress: "ongeldige HERMES_TUI_TOOL_PROGRESS: {0}"-canonical.launch.inventoryUnavailable: "Gereedskap- en vaardigheidsinventaris word nie deur hierdie looptyd blootgestel nie."canonical.launch.noTuiPolicy: "gateway ondersteun nie tui-sessiebeleid nie; werk die gateway by/herbegin dit"canonical.launch.unsupportedOptions: "gateway ondersteun nie TUI-beginopsies nie: {0}"canonical.queue.clipboardImageFailed: "knipbordbeeld het misluk: {0}"diff --git a/locales/ar.tui.yaml b/locales/ar.tui.yamlindex 2896b21ecce..1e46fd85c73 100644--- a/locales/ar.tui.yaml+++ b/locales/ar.tui.yaml@@ -108,7 +108,6 @@ canonical.images.notFound: "الصورة غير موجودة: {0}"canonical.images.tooLarge: "الصورة تتجاوز حد الرفع البالغ 20 MiB"canonical.images.unsupported: "صورة غير مدعومة: يُتوقَّع بايتات PNG أو JPEG أو GIF أو WebP"canonical.launch.invalidToolProgress: "قيمة HERMES_TUI_TOOL_PROGRESS غير صالحة: {0}"-canonical.launch.inventoryUnavailable: "مخزون الأدوات والمهارات غير مكشوف في بيئة التشغيل هذه."canonical.launch.noTuiPolicy: "البوّابة لا تدعم سياسة جلسة tui؛ حدّث البوّابة أو أعد تشغيلها"canonical.launch.unsupportedOptions: "البوّابة لا تدعم خيارات تشغيل TUI: {0}"canonical.queue.clipboardImageFailed: "فشلت صورة الحافظة: {0}"diff --git a/locales/de.tui.yaml b/locales/de.tui.yamlindex 21d3fadc6d9..da53e4af5df 100644--- a/locales/de.tui.yaml+++ b/locales/de.tui.yaml@@ -108,7 +108,6 @@ canonical.images.notFound: "Bild nicht gefunden: {0}"canonical.images.tooLarge: "Bild überschreitet das Upload-Limit von 20 MiB"canonical.images.unsupported: "Nicht unterstütztes Bild: PNG-, JPEG-, GIF- oder WebP-Bytes erwartet"canonical.launch.invalidToolProgress: "ungültiges HERMES_TUI_TOOL_PROGRESS: {0}"-canonical.launch.inventoryUnavailable: "Tool- und Skill-Inventar wird von dieser Laufzeit nicht bereitgestellt."canonical.launch.noTuiPolicy: "Gateway unterstützt keine tui-Sitzungsrichtlinie; Gateway aktualisieren/neu starten"canonical.launch.unsupportedOptions: "Gateway unterstützt keine TUI-Startoptionen: {0}"canonical.queue.clipboardImageFailed: "Bild aus Zwischenablage fehlgeschlagen: {0}"diff --git a/locales/es.tui.yaml b/locales/es.tui.yamlindex ad2bd34fdf8..16afc5cb1d0 100644--- a/locales/es.tui.yaml+++ b/locales/es.tui.yaml@@ -108,7 +108,6 @@ canonical.images.notFound: "Imagen no encontrada: {0}"canonical.images.tooLarge: "La imagen supera el límite de subida de 20 MiB"canonical.images.unsupported: "Imagen no admitida: se esperaban bytes PNG, JPEG, GIF o WebP"canonical.launch.invalidToolProgress: "HERMES_TUI_TOOL_PROGRESS no válido: {0}"-canonical.launch.inventoryUnavailable: "Este entorno de ejecución no expone el inventario de herramientas y skills."canonical.launch.noTuiPolicy: "el gateway no admite la política de sesión tui; actualiza/reinicia el gateway"canonical.launch.unsupportedOptions: "el gateway no admite opciones de inicio de TUI: {0}"canonical.queue.clipboardImageFailed: "falló la imagen del portapapeles: {0}"diff --git a/locales/fr.tui.yaml b/locales/fr.tui.yamlindex 114a83f29c4..eea839d41ab 100644--- a/locales/fr.tui.yaml+++ b/locales/fr.tui.yaml@@ -108,7 +108,6 @@ canonical.images.notFound: "Image introuvable : {0}"canonical.images.tooLarge: "L'image dépasse la limite d'envoi de 20 MiB"canonical.images.unsupported: "Image non prise en charge : PNG, JPEG, GIF ou WebP attendu"canonical.launch.invalidToolProgress: "HERMES_TUI_TOOL_PROGRESS invalide : {0}"-canonical.launch.inventoryUnavailable: "L'inventaire des outils et des skills n'est pas exposé par ce runtime."canonical.launch.noTuiPolicy: "le gateway ne prend pas en charge la politique de session tui ; mettez à jour/redémarrez le gateway"canonical.launch.unsupportedOptions: "le gateway ne prend pas en charge les options de lancement TUI : {0}"canonical.queue.clipboardImageFailed: "échec de l'image du presse-papiers : {0}"diff --git a/locales/ga.tui.yaml b/locales/ga.tui.yamlindex 38376f9c4ea..6c16624dd10 100644--- a/locales/ga.tui.yaml+++ b/locales/ga.tui.yaml@@ -108,7 +108,6 @@ canonical.images.notFound: "Íomhá gan aimsiú: {0}"canonical.images.tooLarge: "Sáraíonn an íomhá an teorainn uaslódála 20 MiB"canonical.images.unsupported: "Íomhá gan tacaíocht: bhíothas ag súil le PNG, JPEG, GIF nó WebP"canonical.launch.invalidToolProgress: "HERMES_TUI_TOOL_PROGRESS neamhbhailí: {0}"-canonical.launch.inventoryUnavailable: "Ní nochtann an runtime seo fardal na n-uirlisí agus na scileanna."canonical.launch.noTuiPolicy: "ní thacaíonn an gateway le polasaí seisiúin tui; nuashonraigh/atosaigh an gateway"canonical.launch.unsupportedOptions: "ní thacaíonn an gateway le roghanna tosaithe TUI: {0}"canonical.queue.clipboardImageFailed: "theip ar íomhá na gearrthaisce: {0}"diff --git a/locales/hu.tui.yaml b/locales/hu.tui.yamlindex 89611dfb076..1cb59080cb3 100644--- a/locales/hu.tui.yaml+++ b/locales/hu.tui.yaml@@ -108,7 +108,6 @@ canonical.images.notFound: "A kép nem található: {0}"canonical.images.tooLarge: "A kép meghaladja a 20 MiB-os feltöltési korlátot"canonical.images.unsupported: "Nem támogatott kép: PNG, JPEG, GIF vagy WebP adat várt"canonical.launch.invalidToolProgress: "érvénytelen HERMES_TUI_TOOL_PROGRESS: {0}"-canonical.launch.inventoryUnavailable: "Ez a futtatókörnyezet nem teszi elérhetővé az eszköz- és skill-leltárt."canonical.launch.noTuiPolicy: "az átjáró nem támogatja a tui munkamenet-szabályzatot; frissítsd/indítsd újra az átjárót"canonical.launch.unsupportedOptions: "az átjáró nem támogatja a TUI indítási beállításokat: {0}"canonical.queue.clipboardImageFailed: "vágólapkép sikertelen: {0}"diff --git a/locales/it.tui.yaml b/locales/it.tui.yamlindex b0e65ed2bb2..cdc572c54c5 100644--- a/locales/it.tui.yaml+++ b/locales/it.tui.yaml@@ -108,7 +108,6 @@ canonical.images.notFound: "Immagine non trovata: {0}"canonical.images.tooLarge: "L'immagine supera il limite di caricamento di 20 MiB"canonical.images.unsupported: "Immagine non supportata: attesi byte PNG, JPEG, GIF o WebP"canonical.launch.invalidToolProgress: "HERMES_TUI_TOOL_PROGRESS non valido: {0}"-canonical.launch.inventoryUnavailable: "L'inventario di strumenti e skill non è esposto da questo runtime."canonical.launch.noTuiPolicy: "il gateway non supporta la policy di sessione tui; aggiorna/riavvia il gateway"canonical.launch.unsupportedOptions: "il gateway non supporta le opzioni di avvio TUI: {0}"canonical.queue.clipboardImageFailed: "immagine dagli appunti non riuscita: {0}"diff --git a/locales/ja.tui.yaml b/locales/ja.tui.yamlindex ca070148afb..78b0a2a861a 100644--- a/locales/ja.tui.yaml+++ b/locales/ja.tui.yaml@@ -108,7 +108,6 @@ canonical.images.notFound: "画像が見つかりません: {0}"canonical.images.tooLarge: "画像が 20 MiB のアップロード上限を超えています"canonical.images.unsupported: "未対応の画像です: PNG、JPEG、GIF、WebP のいずれかが必要です"canonical.launch.invalidToolProgress: "HERMES_TUI_TOOL_PROGRESS が無効です: {0}"-canonical.launch.inventoryUnavailable: "このランタイムはツールとスキルの一覧を公開していません。"canonical.launch.noTuiPolicy: "ゲートウェイが tui セッションポリシーに対応していません。ゲートウェイを更新/再起動してください"canonical.launch.unsupportedOptions: "ゲートウェイが TUI 起動オプションに対応していません: {0}"canonical.queue.clipboardImageFailed: "クリップボード画像の取得に失敗しました: {0}"diff --git a/locales/ko.tui.yaml b/locales/ko.tui.yamlindex 03e2d6af578..4663bee2e46 100644--- a/locales/ko.tui.yaml+++ b/locales/ko.tui.yaml@@ -108,7 +108,6 @@ canonical.images.notFound: "이미지를 찾을 수 없어요: {0}"canonical.images.tooLarge: "이미지가 업로드 한도 20 MiB를 넘어요"canonical.images.unsupported: "지원하지 않는 이미지: PNG, JPEG, GIF 또는 WebP여야 해요"canonical.launch.invalidToolProgress: "잘못된 HERMES_TUI_TOOL_PROGRESS: {0}"-canonical.launch.inventoryUnavailable: "이 런타임은 도구 및 스킬 목록을 제공하지 않아요."canonical.launch.noTuiPolicy: "게이트웨이가 tui 세션 정책을 지원하지 않아요. 게이트웨이를 업데이트/재시작하세요"canonical.launch.unsupportedOptions: "게이트웨이가 TUI 시작 옵션을 지원하지 않아요: {0}"canonical.queue.clipboardImageFailed: "클립보드 이미지 실패: {0}"diff --git a/locales/pt.tui.yaml b/locales/pt.tui.yamlindex f2fff82597d..de957467780 100644--- a/locales/pt.tui.yaml+++ b/locales/pt.tui.yaml@@ -108,7 +108,6 @@ canonical.images.notFound: "Imagem não encontrada: {0}"canonical.images.tooLarge: "A imagem excede o limite de upload de 20 MiB"canonical.images.unsupported: "Imagem não suportada: esperados bytes PNG, JPEG, GIF ou WebP"canonical.launch.invalidToolProgress: "HERMES_TUI_TOOL_PROGRESS inválido: {0}"-canonical.launch.inventoryUnavailable: "O inventário de ferramentas e skills não é exposto por este runtime."canonical.launch.noTuiPolicy: "o gateway não suporta a política de sessão tui; atualize/reinicie o gateway"canonical.launch.unsupportedOptions: "o gateway não suporta opções de inicialização da TUI: {0}"canonical.queue.clipboardImageFailed: "falha na imagem da área de transferência: {0}"diff --git a/locales/ru.tui.yaml b/locales/ru.tui.yamlindex 38c088bd42f..279589b646b 100644--- a/locales/ru.tui.yaml+++ b/locales/ru.tui.yaml@@ -108,7 +108,6 @@ canonical.images.notFound: "Изображение не найдено: {0}"canonical.images.tooLarge: "Изображение превышает лимит загрузки 20 MiB"canonical.images.unsupported: "Неподдерживаемое изображение: ожидаются байты PNG, JPEG, GIF или WebP"canonical.launch.invalidToolProgress: "недопустимое значение HERMES_TUI_TOOL_PROGRESS: {0}"-canonical.launch.inventoryUnavailable: "Эта среда выполнения не предоставляет список инструментов и навыков."canonical.launch.noTuiPolicy: "шлюз не поддерживает политику сеанса tui; обновите/перезапустите шлюз"canonical.launch.unsupportedOptions: "шлюз не поддерживает параметры запуска TUI: {0}"canonical.queue.clipboardImageFailed: "ошибка изображения из буфера обмена: {0}"diff --git a/locales/tr.tui.yaml b/locales/tr.tui.yamlindex 6fbbfab83e7..4506d68fb31 100644--- a/locales/tr.tui.yaml+++ b/locales/tr.tui.yaml@@ -108,7 +108,6 @@ canonical.images.notFound: "Görsel bulunamadı: {0}"canonical.images.tooLarge: "Görsel 20 MiB yükleme sınırını aşıyor"canonical.images.unsupported: "Desteklenmeyen görsel: PNG, JPEG, GIF veya WebP baytları bekleniyordu"canonical.launch.invalidToolProgress: "geçersiz HERMES_TUI_TOOL_PROGRESS: {0}"-canonical.launch.inventoryUnavailable: "Araç ve skill envanteri bu çalışma ortamında sunulmuyor."canonical.launch.noTuiPolicy: "gateway tui oturum politikasını desteklemiyor; gateway'i güncelleyin/yeniden başlatın"canonical.launch.unsupportedOptions: "gateway TUI başlatma seçeneklerini desteklemiyor: {0}"canonical.queue.clipboardImageFailed: "pano görseli başarısız: {0}"diff --git a/locales/uk.tui.yaml b/locales/uk.tui.yamlindex 4986c7c8073..cf1c6c14661 100644--- a/locales/uk.tui.yaml+++ b/locales/uk.tui.yaml@@ -108,7 +108,6 @@ canonical.images.notFound: "Зображення не знайдено: {0}"canonical.images.tooLarge: "Зображення перевищує ліміт завантаження 20 MiB"canonical.images.unsupported: "Непідтримуване зображення: очікувалися байти PNG, JPEG, GIF або WebP"canonical.launch.invalidToolProgress: "недійсне HERMES_TUI_TOOL_PROGRESS: {0}"-canonical.launch.inventoryUnavailable: "Це середовище виконання не надає перелік інструментів і навичок."canonical.launch.noTuiPolicy: "шлюз не підтримує політику сеансу tui; оновіть/перезапустіть шлюз"canonical.launch.unsupportedOptions: "шлюз не підтримує параметри запуску TUI: {0}"canonical.queue.clipboardImageFailed: "збій зображення з буфера обміну: {0}"diff --git a/locales/zh-hant.tui.yaml b/locales/zh-hant.tui.yamlindex 1ff3abeed92..c4a59c8d855 100644--- a/locales/zh-hant.tui.yaml+++ b/locales/zh-hant.tui.yaml@@ -108,7 +108,6 @@ canonical.images.notFound: "找不到圖片:{0}"canonical.images.tooLarge: "圖片超過 20 MiB 上傳限制"canonical.images.unsupported: "不支援的圖片:應為 PNG、JPEG、GIF 或 WebP 位元組"canonical.launch.invalidToolProgress: "無效的 HERMES_TUI_TOOL_PROGRESS:{0}"-canonical.launch.inventoryUnavailable: "此執行環境未提供工具與技能清單。"canonical.launch.noTuiPolicy: "閘道不支援 tui 工作階段原則;請更新/重新啟動閘道"canonical.launch.unsupportedOptions: "閘道不支援 TUI 啟動選項:{0}"canonical.queue.clipboardImageFailed: "剪貼簿圖片失敗:{0}"diff --git a/locales/zh.tui.yaml b/locales/zh.tui.yamlindex 651cf478115..4027ca889a1 100644--- a/locales/zh.tui.yaml+++ b/locales/zh.tui.yaml@@ -108,7 +108,6 @@ canonical.images.notFound: "未找到图片:{0}"canonical.images.tooLarge: "图片超过 20 MiB 上传限制"canonical.images.unsupported: "不支持的图片:应为 PNG、JPEG、GIF 或 WebP 字节"canonical.launch.invalidToolProgress: "无效的 HERMES_TUI_TOOL_PROGRESS:{0}"-canonical.launch.inventoryUnavailable: "此运行时未提供工具和技能清单。"canonical.launch.noTuiPolicy: "网关不支持 tui 会话策略;请更新/重启网关"canonical.launch.unsupportedOptions: "网关不支持 TUI 启动选项:{0}"canonical.queue.clipboardImageFailed: "剪贴板图片失败:{0}"diff --git a/tests/gateway/test_canonical_session_inventory.py b/tests/gateway/test_canonical_session_inventory.pynew file mode 100644index 00000000000..2daa7377202--- /dev/null+++ b/tests/gateway/test_canonical_session_inventory.py@@ -0,0 +1,76 @@+"""A canonical session's snapshot carries main's banner/status inventory for its frozen policy.++Main's ``tui_gateway/server.py::_session_info`` put tools (by toolset), skills (by category), MCP+servers, version / release date, git branch and provider on every create / resume / ``session.info``+``info``; the Ink banner and the classic CLI banner render exactly those. A lazy canonical session+(agent built on the first turn) must report what that turn's agent WILL load: the toolsets frozen+at creation, never the owner process's whole registry."""+import subprocess+from types import SimpleNamespace++import pytest+++def repo(tmp_path):+ path = tmp_path / 'repo'+ path.mkdir()+ subprocess.run(['git', 'init', '-q', '-b', 'inventory-branch', str(path)], check=True, timeout=30)+ return path+++async def test_created_session_snapshot_carries_inventory_for_frozen_toolsets(tmp_path, monkeypatch, repo):+ 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 hermes_cli import banner+ from tui_gateway.contracts.registry import CANONICAL_METHODS++ home = tmp_path / 'home'+ skill = home / 'skills' / 'research' / 'arxiv'+ skill.mkdir(parents=True)+ (skill / 'SKILL.md').write_text('---\nname: arxiv\ndescription: Search papers.\n---\nBody.\n')+ (home / 'config.yaml').write_text(+ 'model: {default: gpt-5.4, provider: custom, base_url: "http://127.0.0.1:9/v1"}\n'+ 'platform_toolsets: {cli: [file, terminal]}\n')+ monkeypatch.setenv('HERMES_HOME', str(home))+ monkeypatch.setattr(run, '_hermes_home', home)+ monkeypatch.setattr(banner, '_available_skills_cache', None)+ store = SessionStore(tmp_path / 'sessions', GatewayConfig())+ runner = SimpleNamespace(session_store=store, _session_db=store._db, adapters={}, _draining=False,+ _cached_agent_for=lambda route: None)+ runner._adapter_for_source = lambda source: runner.adapters.get(source.platform)+ authority = await initialize_session_authority(runner, profile_id=str(home), instance_id='first')+ connection = AuthorityConnection(authority, object(), {'user_id': 'human'})++ async def call(method, **params):+ reply = await connection.dispatch({'id': 1, 'method': method, 'params': params})+ assert 'result' in reply, reply+ return reply['result']++ created = await call('session.create', request_id='inv', source='tui', cwd=str(repo))+ sid = created['session_id']+ CANONICAL_METHODS['session.create'].result.model_validate(created)+ info_reply = await call('session.info', session_id=sid)+ CANONICAL_METHODS['session.info'].result.model_validate(info_reply)+ for info in (created['info'], info_reply, (await call('session.resume', session_id=sid))['info']):+ assert info['lazy'] is True+ tools = info['tools']+ # The frozen policy's toolsets, grouped by toolset as main grouped ``agent.tools`` (deferrable+ # tools sit behind the tool_search bridge in both, under ``other``).+ assert 'read_file' in tools.get('file', []), tools+ assert tools.get('terminal') == ['terminal'], tools+ assert not ({'web', 'browser', 'image_gen'} & set(tools)), tools+ assert info['skills'].get('research') == ['arxiv'], info['skills']+ assert info['mcp_servers'] == []+ assert info['branch'] == 'inventory-branch'+ assert info['provider'] == 'custom'+ assert info['version'] and info['release_date'], info+ assert sorted(info['enabled_toolsets']) == info['enabled_toolsets']+ assert {'file', 'terminal'} <= set(info['enabled_toolsets'])++ narrowed = await call('session.create', request_id='narrow', source='cli', cwd=str(repo), toolsets=['terminal'])+ assert set(narrowed['info']['tools']) - {'other'} == {'terminal'}, narrowed['info']['tools']diff --git a/tui_gateway/contracts/canonical.py b/tui_gateway/contracts/canonical.pyindex c17992b66d2..cd9106ba087 100644--- a/tui_gateway/contracts/canonical.py+++ b/tui_gateway/contracts/canonical.py@@ -12,7 +12,7 @@ from __future__ import annotationsfrom typing import Literalfrom .base import JsonValue, Params, Result-from .common import OpenModel+from .common import McpServerStatus, OpenModel, ProjectReffrom .groups_bot_relay import RoomParams, RoomTaskReceiptfrom .registry import canonical_method@@ -129,8 +129,29 @@ class CanonicalSessionInfoParams(Params):session_id: str-class CanonicalSessionInfo(OpenModel):- """``gateway/session_local.py::local_session_info``."""+class SessionInventoryFields(Result):+ """Main's banner / status-bar inventory (``gateway/session_local_inventory.py::session_inventory``):+ the shapes ``tui_gateway/server.py::_session_info`` sent, computed for the session's frozen policy.+ ``enabled_toolsets`` / ``tool_availability`` / ``context_length`` feed the classic CLI banner."""++ provider: str | None = None+ tools: dict[str, list[str]] | None = None+ skills: dict[str, list[str]] | None = None+ mcp_servers: list[McpServerStatus] | None = None+ version: str | None = None+ release_date: str | None = None+ update_behind: JsonValue | None = None+ update_command: str | None = None+ branch: str | None = None+ project: ProjectRef | None = None+ system_prompt: str | None = None+ context_length: int | None = None+ enabled_toolsets: list[str] | None = None+ tool_availability: dict[str, JsonValue] | None = None+++class CanonicalSessionInfo(SessionInventoryFields, OpenModel):+ """``gateway/session_local_inventory.py::snapshot_info``: ``local_session_info`` + the inventory."""source: strmodel: str | None = Nonediff --git a/tui_gateway/contracts/canonical_sessions.py b/tui_gateway/contracts/canonical_sessions.pyindex e3967ef2b67..dbd988a83ab 100644--- a/tui_gateway/contracts/canonical_sessions.py+++ b/tui_gateway/contracts/canonical_sessions.py@@ -6,7 +6,7 @@ from typing import Literalfrom .base import JsonValue, Params, Resultfrom .common import ProfileParams, TranscriptMessage-from .canonical import AdmissionStatus, CanonicalSessionRef, PromptResponseResult+from .canonical import AdmissionStatus, CanonicalSessionRef, PromptResponseResult, SessionInventoryFieldsfrom .registry import canonical_method@@ -83,7 +83,7 @@ class CanonicalPendingPrompt(Result):multi_select: bool | None = None-class CanonicalSnapshotInfo(Result):+class CanonicalSnapshotInfo(SessionInventoryFields):desktop_protocol: Literal['hermes-gateway-v1']source: str | None = Nonemodel: str | None = Nonediff --git a/ui-tui/src/__tests__/brandingCanonicalSnapshot.test.ts b/ui-tui/src/__tests__/brandingCanonicalSnapshot.test.tsnew file mode 100644index 00000000000..b6cb85589e3--- /dev/null+++ b/ui-tui/src/__tests__/brandingCanonicalSnapshot.test.ts@@ -0,0 +1,119 @@+import { PassThrough } from 'stream'++import { renderSync } from '@hermes/ink'+import React from 'react'+import { describe, expect, it } from 'vitest'++import { canonicalResult } from '../canonicalGateway.js'+import { SessionPanel } from '../components/branding.js'+import { DEFAULT_THEME } from '../theme.js'+import type { SessionInfo } from '../types.js'++// A canonical gateway's create/resume snapshot carries main's banner inventory+// (gateway/session_local_inventory.py). The TUI renders main's banner from it+// unchanged: tools by toolset, skills by category, MCP servers, and the+// "N tools · M skills · K MCP" footer — never a narrow-snapshot placeholder.++const delay = (ms: number) => new Promise(resolve => setTimeout(resolve, ms))++const snapshot = {+ authority_epoch: 3,+ execution_generation: 0,+ info: {+ branch: 'main',+ cwd: '/work/repo',+ desktop_protocol: 'hermes-gateway-v1',+ lazy: true,+ mcp_servers: [+ { connected: true, name: 'nous-support', status: 'connected', tools: 6, transport: 'http' },+ { connected: false, disabled: true, name: 'linear', status: 'disabled', tools: 0, transport: 'stdio' }+ ],+ model: 'anthropic/claude-opus-5.5',+ profile_id: '/home/u/.hermes',+ profile_name: 'default',+ provider: 'nous',+ reasoning_effort: 'high',+ release_date: '2026.9.24',+ skills: { creative: ['ascii-art'], research: ['arxiv', 'blogwatcher'] },+ source: 'tui',+ tools: { file: ['patch', 'read_file', 'search_files', 'write_file'], terminal: ['process', 'terminal'] },+ version: '0.18.0'+ },+ last_sequence: 0,+ message_count: 0,+ messages: [],+ pending: [],+ prompts: [],+ replay_epoch: 'r',+ revision: 0,+ running: false,+ session_id: 'local-abc',+ stored_session_id: 'local-abc',+ subscription_id: 'sub'+}++async function render(info: SessionInfo): Promise<string> {+ const stdout = new PassThrough()+ const stdin = new PassThrough()+ const stderr = new PassThrough()++ Object.assign(stdout, { columns: 140, isTTY: false, rows: 60 })+ Object.assign(stdin, { isTTY: false })+ Object.assign(stderr, { isTTY: false })+ let captured = ''+ stdout.on('data', chunk => {+ captured += chunk.toString()+ })++ const instance = renderSync(React.createElement(SessionPanel, { info, sid: 'local-abc', t: DEFAULT_THEME }), {+ patchConsole: false,+ stderr: stderr as unknown as NodeJS.WriteStream,+ stdin: stdin as unknown as NodeJS.ReadStream,+ stdout: stdout as unknown as NodeJS.WriteStream+ })++ try {+ await delay(20)++ // eslint-disable-next-line no-control-regex+ return captured.replace(/\u001b\[[0-9;?]*[A-Za-z]/g, '')+ } finally {+ instance.unmount()+ instance.cleanup()+ }+}++describe('banner from a canonical session snapshot', () => {+ it('renders the tools, skills and MCP sections main showed', async () => {+ const { info } = canonicalResult('session.create', snapshot)+ const frame = await render(info)++ expect(frame).toContain('v0.18.0 (2026.9.24)')+ expect(frame).toContain('claude-opus-5.5')+ expect(frame).toContain('/work/repo')+ expect(frame).toMatch(/file: patch, read_file, search_files, write_file/)+ expect(frame).toMatch(/terminal: process, terminal/)+ expect(frame).toMatch(/Available Skills/)+ expect(frame).toMatch(/MCP Servers/)+ expect(frame).toMatch(/6 tools/)+ expect(frame).toMatch(/3 skills/)+ expect(frame).toMatch(/1 MCP/)+ expect(frame).not.toMatch(/not exposed by this runtime/)+ })++ it('renders main\'s banner, not a placeholder, before the inventory arrives', async () => {+ // A non-local route's snapshot info is `{ desktop_protocol }` only; main's banner still+ // draws its card (headings, version line slot, loading rows) rather than a one-line notice.+ const { info } = canonicalResult('session.resume', {+ ...snapshot,+ info: { desktop_protocol: 'hermes-gateway-v1', lazy: true, model: 'anthropic/claude-opus-5.5', version: '0.18.0' }+ })++ const frame = await render(info)++ expect(frame).toMatch(/Available Tools/)+ expect(frame).toMatch(/Available Skills/)+ expect(frame).toContain('v0.18.0')+ expect(frame).not.toMatch(/not exposed by this runtime/)+ })+})diff --git a/ui-tui/src/components/branding.tsx b/ui-tui/src/components/branding.tsxindex 6ad258bdebb..1c2e507349b 100644--- a/ui-tui/src/components/branding.tsx+++ b/ui-tui/src/components/branding.tsx@@ -213,8 +213,7 @@ const SKILLS_MAX = 8const TOOLSETS_MAX = 8export function SessionPanel({ info, maxWidth, sid, t }: SessionPanelProps) {- const tr = useT()- const T = tr.chatBits.branding+ const T = useT().chatBits.brandingconst term = useStdout().stdout?.columns ?? 100const cols = Math.max(20, Math.min(term, maxWidth ?? term))const heroLines = caduceus(t.color, t.bannerHero || undefined)@@ -254,23 +253,8 @@ export function SessionPanel({ info, maxWidth, sid, t }: SessionPanelProps) {return line}- // The canonical authority intentionally returns a narrow metadata snapshot.- // Do not invent tool/skill inventories or crash while rendering that session.- if (!info.skills || !info.tools) {- return (- <Box flexDirection="column">- <Text>- <Text color={t.color.sessionLabel}>{T.sessionLabel}</Text>- <Text color={t.color.sessionBorder}>{sid}</Text>- </Text>- <Text color={t.color.muted}>{tr.canonical.launch.inventoryUnavailable}</Text>- </Box>- )- }-// ── Collapsible skills section ──- // Non-null here: the narrow-snapshot guard above returned when either is missing.- const skills = info.skills+ const skills = info.skills ?? {}const skillEntries = Object.entries(skills).sort()const skillsTotal = flat(skills).lengthconst skillsCatCount = skillEntries.length@@ -297,7 +281,7 @@ export function SessionPanel({ info, maxWidth, sid, t }: SessionPanelProps) {}// ── Collapsible tools section ──- const tools = info.tools+ const tools = info.tools ?? {}const toolEntries = Object.entries(tools).sort()const toolsTotal = flat(tools).lengthdiff --git a/ui-tui/src/i18n/en/canonical.ts b/ui-tui/src/i18n/en/canonical.tsindex 953dde9a382..a3f40b79929 100644--- a/ui-tui/src/i18n/en/canonical.ts+++ b/ui-tui/src/i18n/en/canonical.ts@@ -62,12 +62,11 @@ export const canonicalEn = {notFound: (path: string) => `Image not found: ${path}`,noOwnerPath: 'Image upload did not return an owner path'},- // canonicalGateway.ts — launch-contract refusals; components/branding.tsx.+ // canonicalGateway.ts — launch-contract refusals.launch: {noTuiPolicy: 'gateway does not support tui session policy; update/restart the gateway',unsupportedOptions: (options: string) => `gateway does not support TUI launch options: ${options}`,- invalidToolProgress: (value: string) => `invalid HERMES_TUI_TOOL_PROGRESS: ${value}`,- inventoryUnavailable: 'Tool and skill inventory is not exposed by this runtime.'+ invalidToolProgress: (value: string) => `invalid HERMES_TUI_TOOL_PROGRESS: ${value}`}}}