session_local_inventory.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270
  1. """Main's banner / status-bar inventory for a canonical local session.
  2. ``tui_gateway/server.py::_session_info`` on main put the session's tools (by toolset), skills (by
  3. category), MCP servers, version / release date, update notice, git branch, project and provider on
  4. every ``session.info`` / create / resume ``info``; the Ink banner (``components/branding.tsx``) and
  5. the classic CLI banner (``hermes_cli/banner.py::build_welcome_banner``) render them. A canonical
  6. session's agent is built on its first turn, so the inventory is computed here from the session's
  7. frozen policy (the toolsets that turn will run with), with main's own builders, in the owner
  8. process. Every builder does I/O (skills tree walk, tool ``check_fn`` probes, git), so callers run
  9. :func:`session_inventory` off the owner loop (:func:`snapshot_info`).
  10. """
  11. from __future__ import annotations
  12. import asyncio
  13. import contextlib
  14. import logging
  15. logger = logging.getLogger(__name__)
  16. _update_prefetch_started = False
  17. def _start_update_prefetch():
  18. """Main's TUI gateway started the passive update check at import; the owner starts it once,
  19. on the first snapshot, so ``update_behind`` reports like main's banner instead of staying null."""
  20. global _update_prefetch_started
  21. if _update_prefetch_started:
  22. return
  23. _update_prefetch_started = True
  24. from hermes_cli.banner import prefetch_update_check
  25. prefetch_update_check()
  26. def _grouped(tools):
  27. """``{toolset: [tool names]}`` exactly as main's ``_session_info`` grouped ``agent.tools``."""
  28. from model_tools import get_toolset_for_tool
  29. grouped: dict[str, list[str]] = {}
  30. for tool in tools or []:
  31. name = tool["function"]["name"]
  32. grouped.setdefault(get_toolset_for_tool(name) or "other", []).append(name)
  33. return grouped
  34. def _policy_tools(policy, config):
  35. """The tool list the session's next agent build loads (``agent/agent_init.py`` tool snapshot):
  36. the policy's toolsets minus the configured, platform-gated and one-shot disabled ones."""
  37. import model_tools
  38. from agent.skill_utils import parse_config_string_list
  39. from toolsets import session_disabled_toolsets, session_platform_tool_drops
  40. enabled = list(policy.current_toolsets(config))
  41. disabled = session_disabled_toolsets(
  42. parse_config_string_list((config.get("agent") or {}).get("disabled_toolsets")) or None, policy.platform,
  43. oneshot=policy.source == "oneshot")
  44. tools = model_tools.get_tool_definitions(enabled_toolsets=enabled, disabled_toolsets=disabled, quiet_mode=True)
  45. drops = set(session_platform_tool_drops(policy.platform))
  46. return enabled, [tool for tool in tools or [] if tool["function"]["name"] not in drops]
  47. def _project(cwd):
  48. """``tui_gateway/server.py::_project_info_for_cwd``: the named project owning *cwd*, or None."""
  49. if not str(cwd or "").strip():
  50. return None
  51. from hermes_cli import projects_db as pdb
  52. try:
  53. with pdb.connect_closing() as conn:
  54. project = pdb.project_for_path(conn, cwd)
  55. except Exception: # health: allow BLE001 -- main's resolver: an unreadable projects.db names no project
  56. logger.debug("failed to resolve project for cwd", exc_info=True)
  57. return None
  58. return None if project is None else {
  59. "id": project.id, "slug": project.slug, "name": project.name, "primary_path": project.primary_path}
  60. def _cli_startup_notices(enabled):
  61. """The lines main's HermesCLI printed under its banner, computed where the tools run: the toolset
  62. availability warning (``cli.py::_show_tool_availability_warnings``). The classic CLI renders them
  63. with its own console."""
  64. notices: dict = {"tool_availability_warnings": []}
  65. with contextlib.suppress(Exception):
  66. from hermes_cli.tool_availability_notices import (
  67. current_terminal_backend, filter_to_enabled_toolsets, tool_availability_warning_lines)
  68. from model_tools import check_tool_availability
  69. from tools.terminal_tool import terminal_backend_unavailable_reason
  70. from toolsets import resolve_toolset
  71. _, unavailable = check_tool_availability()
  72. unavailable = filter_to_enabled_toolsets(unavailable, enabled or [], resolve_toolset)
  73. notices["tool_availability_warnings"] = tool_availability_warning_lines(
  74. unavailable, terminal_reason=terminal_backend_unavailable_reason(),
  75. terminal_backend=current_terminal_backend())
  76. return notices
  77. def _unknown_toolsets(enabled, config):
  78. """Main's "Unknown toolsets" startup warning (``HermesCLI._init_toolsets``), judged where the plugins
  79. load: the session's toolset names the profile's registry, MCP servers, plugin toolsets and platform
  80. bundles cannot place (an uninstalled plugin's stale ``platform_toolsets`` entry)."""
  81. if "all" in enabled or "*" in enabled:
  82. return []
  83. with contextlib.suppress(Exception):
  84. from hermes_cli.toolset_validation import saved_toolset_resolver
  85. known = saved_toolset_resolver(config)
  86. return [name for name in enabled if not known(name)]
  87. return []
  88. def _cli_skills():
  89. """``hermes_cli.banner.get_available_skills`` as main's classic CLI computed it: ``cmd_chat`` pins
  90. ``HERMES_KANBAN_BOARD`` before HermesCLI starts, so ``environments: [kanban]`` skills are offered.
  91. The owner never sets that env; the kanban relevance is scoped to this scan (a ContextVar) and the
  92. catalog cache entry it would poison is restored, so other surfaces keep their own view."""
  93. from tools import skills_tool
  94. from tools.kanban_toolset_context import scoped_kanban_toolset_selection
  95. key = ("filtered", False)
  96. saved = skills_tool._SKILLS_CACHE.pop(key, None)
  97. try:
  98. with scoped_kanban_toolset_selection(["kanban"]):
  99. found = skills_tool.find_all_skills()
  100. finally:
  101. skills_tool._SKILLS_CACHE.pop(key, None)
  102. if saved is not None:
  103. skills_tool._SKILLS_CACHE[key] = saved
  104. grouped: dict[str, list[str]] = {}
  105. for skill in found:
  106. grouped.setdefault(skill.get("category") or "general", []).append(skill["name"])
  107. return grouped
  108. def _session_provider(view, config=None):
  109. from hermes_cli.runtime_provider_custom import session_provider_identity
  110. return session_provider_identity(getattr(view, "provider", None), getattr(view, "requested_provider", None),
  111. getattr(view, "base_url", None), getattr(view, "model", None), config=config)
  112. def session_inventory(authority, policy, agent, cwd):
  113. """Main's banner/status fields for one session. Each section degrades to main's empty value on
  114. its own, so one failing builder never blanks the others (main wrapped each in ``suppress``)."""
  115. from gateway.session_authorities import owner_scope
  116. from tui_gateway import git_probe
  117. info: dict = {"tools": {}, "skills": {}, "mcp_servers": [], "version": "", "release_date": "",
  118. "update_behind": None, "update_command": "",
  119. "branch": git_probe.branch(cwd) if cwd else "", "project": _project(cwd)}
  120. with owner_scope(authority):
  121. config = policy.config(authority, secrets=False) if policy is not None else {}
  122. if agent is not None:
  123. from agent.voice_turn_route import session_runtime_view
  124. info["provider"] = _session_provider(session_runtime_view(agent), config if policy is not None else None)
  125. info["tools"] = _grouped(getattr(agent, "tools", None))
  126. info["system_prompt"] = getattr(agent, "_cached_system_prompt", "") or ""
  127. compressor = getattr(agent, "context_compressor", None)
  128. if compressor is not None and getattr(compressor, "context_length", None):
  129. info["context_length"] = compressor.context_length
  130. enabled = list(getattr(agent, "enabled_toolsets", None) or [])
  131. else:
  132. info["provider"] = str((config.get("model") or {}).get("provider") or "")
  133. enabled = []
  134. if policy is not None:
  135. try:
  136. enabled, tools = _policy_tools(policy, config)
  137. info["tools"] = _grouped(tools)
  138. except Exception: # health: allow BLE001 -- main's suppress: the banner shows no tools, not an error
  139. logger.warning("session inventory: tool snapshot failed", exc_info=True)
  140. info["enabled_toolsets"] = sorted(enabled)
  141. with contextlib.suppress(Exception):
  142. # The classic CLI banner colours lazy (yellow) / disabled (red) tools from this.
  143. from hermes_cli.banner import compute_toolset_availability
  144. info["tool_availability"] = compute_toolset_availability(enabled)
  145. if policy is not None and policy.source == "cli":
  146. info.update(_cli_startup_notices(enabled), unknown_toolsets=_unknown_toolsets(enabled, config))
  147. with contextlib.suppress(Exception):
  148. if policy is not None and policy.source == "cli":
  149. info["skills"] = _cli_skills()
  150. else:
  151. from hermes_cli.banner import get_available_skills
  152. info["skills"] = get_available_skills()
  153. with contextlib.suppress(Exception):
  154. from tools.mcp_tool_discovery import get_mcp_status
  155. info["mcp_servers"] = get_mcp_status()
  156. with contextlib.suppress(Exception):
  157. from hermes_cli import __release_date__
  158. from hermes_cli.version_info import get_version_info
  159. info.update(version=get_version_info().base_version, release_date=__release_date__)
  160. with contextlib.suppress(Exception):
  161. from hermes_cli.banner import get_update_result
  162. from hermes_cli.config import recommended_update_command
  163. _start_update_prefetch()
  164. # Two assignments, as on main: a failing command lookup still reports update_behind.
  165. info["update_behind"] = get_update_result(timeout=0.5)
  166. info["update_command"] = recommended_update_command()
  167. return info
  168. async def snapshot_info(authority, ref):
  169. """``local_session_info`` plus main's inventory, the builders run off the owner loop."""
  170. from gateway.session_local import local_session_info
  171. from gateway.session_policy import policy_for_source
  172. info = local_session_info(authority, ref)
  173. policy = policy_for_source(authority.runner, authority.sessions[ref.session_id].source)
  174. agent = authority.agent(ref)
  175. inventory = await asyncio.to_thread(session_inventory, authority, policy, agent, info.get("cwd"))
  176. if info.get('tool_count') is None:
  177. # A lazy session: the tools its first turn loads (the banner's own count).
  178. info['tool_count'] = sum(len(names) for names in (inventory.get('tools') or {}).values())
  179. from gateway.session_usage import snapshot_usage
  180. if (usage := await asyncio.to_thread(snapshot_usage, authority, ref, agent)) is not None:
  181. info['usage'] = usage
  182. return {**inventory, **info}
  183. def agent_inventory(agent) -> dict:
  184. """The banner fields only a built agent knows (main's ``_session_info`` read them off it): the
  185. tools it loaded, its cached system prompt (the ``▸ System Prompt`` row), provider and context
  186. length. Cheap attribute reads, safe on the agent thread at turn end."""
  187. info: dict = {}
  188. with contextlib.suppress(Exception):
  189. from agent.voice_turn_route import session_runtime_view
  190. info["provider"] = _session_provider(session_runtime_view(agent))
  191. with contextlib.suppress(Exception):
  192. info["tools"] = _grouped(getattr(agent, "tools", None))
  193. info["system_prompt"] = getattr(agent, "_cached_system_prompt", "") or ""
  194. compressor = getattr(agent, "context_compressor", None)
  195. if compressor is not None and getattr(compressor, "context_length", None):
  196. info["context_length"] = compressor.context_length
  197. return info
  198. def publish_settled_info(turn, agent) -> None:
  199. """Main's end-of-turn ``session.info`` (``session_workdir._emit_settled_session_info``) for a local
  200. viewer: the first turn builds the agent, so this is when the banner's ``▸ System Prompt`` row, the
  201. agent's tool list and provider first become known. Never breaks the turn.
  202. A ``model_override`` admission (``/model --once``, ``/moa``) built its agent on the one-turn
  203. route. That agent must not become the route Desktop, the TUI, and resume read. Drop it from
  204. the cache (released once this turn's running slot clears) and publish the model and provider
  205. of the policy route, both from one read of the profile."""
  206. if agent is None:
  207. return
  208. with contextlib.suppress(Exception):
  209. from gateway.session_cli_turn import cli_turn
  210. from gateway.session_contract import SessionRef
  211. from gateway.session_local import local_session_info
  212. from gateway.session_policy import policy_for_source
  213. authority, session_id, _generation = turn._approval_owner
  214. message_id = getattr(getattr(turn, "_ctx", None), "inbound_message_id", None)
  215. one_turn = bool(cli_turn(message_id).get("model_override"))
  216. live = None
  217. if one_turn:
  218. sessions = getattr(authority, "sessions", None)
  219. live = sessions.get(session_id) if hasattr(sessions, "get") else None
  220. evict = getattr(getattr(turn, "_runner", None), "_evict_cached_agent", None)
  221. if live is not None and callable(evict):
  222. try:
  223. evict(live.route, release_after_turn=True)
  224. except Exception:
  225. logger.debug("one-turn agent cache drop failed", exc_info=True)
  226. ref = SessionRef(authority.profile_id, session_id)
  227. info = {**agent_inventory(agent), **local_session_info(authority, ref)}
  228. if one_turn and live is not None:
  229. try:
  230. runner = getattr(authority, "runner", None) or turn._runner
  231. policy = policy_for_source(runner, live.source)
  232. except Exception:
  233. logger.debug("one-turn policy route unavailable", exc_info=True)
  234. policy = None
  235. if policy is not None:
  236. config, info["model"] = policy.effective(authority, secrets=False)
  237. section = config.get("model")
  238. provider = section.get("provider") if isinstance(section, dict) else None
  239. if provider:
  240. info["provider"] = provider
  241. turn._publish_execution("session.info", info)