The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(hermes_cli): compact g7 misc cluster (pt_input_extras key tables, security audit, prompt_size, docstrings)
Teknium956c4b13e4b8
diff --git a/hermes_cli/prompt_size.py b/hermes_cli/prompt_size.pyindex ef0bf54255d..e44eab35a7c 100644--- a/hermes_cli/prompt_size.py+++ b/hermes_cli/prompt_size.py@@ -1,9 +1,8 @@"""Prompt-size diagnostic: ``hermes prompt-size``.-The diagnostic builds a real inspection agent (so the numbers match what actually ships on the wire)-but never makes a network call: it passes dummy credentials so ``AIAgent.__init__`` takes the-direct-construction path, then calls ``build_system_prompt_parts`` / inspects ``agent.tools``-offline.+Builds a real inspection agent (so the numbers match what ships on the wire) but never makes a+network call: dummy credentials force ``AIAgent.__init__`` down the direct-construction path, then+``build_system_prompt_parts`` / ``agent.tools`` are inspected offline."""from __future__ import annotations@@ -13,11 +12,9 @@ import refrom pathlib import Pathfrom typing import Any, Dict, List, Optional, Tuple-# The skills index is wrapped in this tag pair inside the stable tier._SKILLS_BLOCK_RE = re.compile(r"<available_skills>.*?</available_skills>", re.DOTALL)-# A rendered skill entry inside <available_skills> is `` - name: desc`` (or-# `` - name`` when the skill has no description). Category headers use two+# A rendered skill entry is `` - name: desc`` (or `` - name``); category headers use two# leading spaces, so the four-space + ``- `` prefix isolates skill lines._SKILL_LINE_PREFIX = " - "@@ -32,8 +29,16 @@ def _bytes(s: str) -> int:return len(s.encode("utf-8"))+def _size(text: str) -> Dict[str, int]:+ return {"chars": len(text), "bytes": _bytes(text)}+++def _fmt_kb(n: int) -> str:+ return f"{n / 1024:.1f} KB"++def _tool_name(tool: Any) -> str:- """Return the callable name of a tool schema (OpenAI ``function`` shape)."""+ """Callable name of a tool schema (OpenAI ``function`` shape)."""if not isinstance(tool, dict):return ""fn = tool.get("function")@@ -43,51 +48,36 @@ def _tool_name(tool: Any) -> str:def _build_inspection_agent(platform: str) -> Any:- """Construct an offline AIAgent for prompt inspection.-- Dummy ``api_key`` + ``base_url`` force the direct-construction path (no provider- auto-detection, no network). Toolsets and platform come from the caller so the breakdown- matches a real session.+ """Offline AIAgent for prompt inspection: dummy ``api_key`` + ``base_url`` force the+ direct-construction path (no provider auto-detection, no network); toolsets resolve the way+ the gateway does so the breakdown matches a real session."""from run_agent import AIAgentfrom hermes_cli.config import load_configfrom hermes_cli.tools_config import _get_platform_tools+ from agent.skill_utils import parse_config_string_listcfg = load_config()model_cfg = cfg.get("model", {}) if isinstance(cfg.get("model"), dict) else {}- model = model_cfg.get("default") or model_cfg.get("model") or ""-- # Resolve platform-specific toolsets the same way the gateway does.- enabled_toolsets = sorted(_get_platform_tools(cfg, platform))agent_cfg = cfg.get("agent") or {}- from agent.skill_utils import parse_config_string_list-- disabled_toolsets = parse_config_string_list(agent_cfg.get("disabled_toolsets")) or None-return AIAgent(- model=model,+ model=model_cfg.get("default") or model_cfg.get("model") or "",api_key="inspect-only",base_url="https://openrouter.ai/api/v1",quiet_mode=True,save_trajectories=False,platform=platform,- enabled_toolsets=enabled_toolsets,- disabled_toolsets=disabled_toolsets,+ enabled_toolsets=sorted(_get_platform_tools(cfg, platform)),+ disabled_toolsets=parse_config_string_list(agent_cfg.get("disabled_toolsets")) or None,)def _skill_md_paths_by_name() -> Dict[str, Path]:- """Map each installed skill's name to its ``SKILL.md`` path on disk.-- Keyed by both the frontmatter ``name`` (what the index renders) and the skill directory name, so- either resolves. Local skills win over external dirs (``get_all_skills_dirs`` yields local- first), matching the index's own precedence.+ """Map each installed skill's frontmatter ``name`` AND directory name to its ``SKILL.md``.+ Local skills win over external dirs (``get_all_skills_dirs`` yields local first), matching+ the index's own precedence."""- from agent.skill_utils import (- get_all_skills_dirs,- iter_skill_index_files,- parse_frontmatter,- )+ from agent.skill_utils import get_all_skills_dirs, iter_skill_index_files, parse_frontmattermapping: Dict[str, Path] = {}for skills_dir in get_all_skills_dirs():@@ -100,8 +90,7 @@ def _skill_md_paths_by_name() -> Dict[str, Path]:frontmatter_name = str(frontmatter.get("name") or dir_name)except Exception:frontmatter_name = dir_name- # setdefault keeps the first (local) occurrence on name collisions.- mapping.setdefault(frontmatter_name, skill_file)+ mapping.setdefault(frontmatter_name, skill_file) # first (local) occurrence winsmapping.setdefault(dir_name, skill_file)return mapping@@ -109,16 +98,14 @@ def _skill_md_paths_by_name() -> Dict[str, Path]:def _compute_skills_breakdown(skills_block: str) -> List[Dict[str, Any]]:"""Per-skill byte breakdown parsed from the rendered ``<available_skills>``.- * ``index_line_bytes`` — the skill's attributed bytes in the always-on index (the fixed per-call- cost of *listing* the skill). For a compact ``[names only]`` line, each name keeps its own bytes- and receives an even share of the category prefix and separators.+ ``index_line_bytes`` is the skill's attributed always-on index cost. For a compact+ ``[names only]`` line each name keeps its own bytes plus an even share of the shared prefix+ and separators."""name_to_path = _skill_md_paths_by_name()entries: List[Dict[str, Any]] = []- def append_entry(- name: str, *, attributed_bytes: int, total_bytes: int, shared_bytes: int, skill_count: int- ) -> None:+ def append_entry(name: str, *, attributed_bytes: int, total_bytes: int, shared_bytes: int, skill_count: int) -> None:path = name_to_path.get(name)md_bytes: Optional[int] = Noneif path is not None:@@ -137,9 +124,8 @@ def _compute_skills_breakdown(skills_block: str) -> List[Dict[str, Any]]:})for line in skills_block.splitlines():- compact_match = _NAMES_ONLY_LINE_RE.match(line)line_bytes = _bytes(line)- if compact_match is not None:+ if (compact_match := _NAMES_ONLY_LINE_RE.match(line)) is not None:names = [n.strip() for n in compact_match.group("names").split(",") if n.strip()]if not names:continue@@ -151,35 +137,25 @@ def _compute_skills_breakdown(skills_block: str) -> List[Dict[str, Any]]:name, attributed_bytes=name_bytes[index] + shared_bytes,total_bytes=line_bytes, shared_bytes=shared_bytes, skill_count=len(names),)- continue-- if not line.startswith(_SKILL_LINE_PREFIX):- continue- # ``name: desc`` — the first ``": "`` separates name from description.- # Namespaced names (``codex:rescue``) have no space after their colon,- # so partitioning on ``": "`` keeps the full name intact.- name = line[len(_SKILL_LINE_PREFIX):].partition(": ")[0].strip()- if name:- append_entry(name, attributed_bytes=line_bytes, total_bytes=line_bytes,- shared_bytes=0, skill_count=1)+ elif line.startswith(_SKILL_LINE_PREFIX):+ # Partition on ``": "`` (not ``:``) so namespaced names like ``codex:rescue`` stay intact.+ name = line[len(_SKILL_LINE_PREFIX):].partition(": ")[0].strip()+ if name:+ append_entry(name, attributed_bytes=line_bytes, total_bytes=line_bytes, shared_bytes=0, skill_count=1)entries.sort(key=lambda e: (-(e["skill_md_bytes"] or 0), e["name"]))return entriesdef _compute_toolsets_breakdown(tools: List[Any]) -> List[Dict[str, Any]]:- """Per-toolset schema-byte breakdown of the resolved tool list.-- Each tool is attributed to its single canonical toolset so ``json_bytes`` sums are fully- attributable (grand total = sum of per-tool serializations). Sorted largest-first, tie-broken- by toolset name.+ """Per-toolset schema-byte breakdown, largest-first (tie-broken by name). Each tool is+ attributed to its single canonical toolset so ``json_bytes`` sums to the grand total."""from tools.registry import registrytool_to_toolset = registry.get_tool_to_toolset_map()groups: Dict[str, Dict[str, Any]] = {}for tool in tools:- name = _tool_name(tool)- toolset = tool_to_toolset.get(name) or "(unknown)"+ toolset = tool_to_toolset.get(_tool_name(tool)) or "(unknown)"group = groups.setdefault(toolset, {"toolset": toolset, "tool_count": 0, "json_bytes": 0})group["tool_count"] += 1group["json_bytes"] += _bytes(json.dumps(tool, ensure_ascii=False))@@ -187,32 +163,26 @@ def _compute_toolsets_breakdown(tools: List[Any]) -> List[Dict[str, Any]]:def compute_prompt_breakdown(platform: str = "cli") -> Dict[str, Any]:- """Return a dict of prompt-size measurements for a fresh session.-- Keys: ``system_prompt``, ``skills_index``, ``memory``, ``user_profile``, ``tools``, ``sections``- (the three prompt tiers), ``skills_breakdown`` and ``toolsets_breakdown`` (largest-first); the- last two answer "what should I disable to cut tokens?".+ """Prompt-size measurements for a fresh session: ``system_prompt``, ``skills_index``,+ ``memory``, ``user_profile``, ``tools``, ``sections`` (the three prompt tiers), and the+ largest-first ``skills_breakdown`` / ``toolsets_breakdown`` ("what should I disable?")."""from agent.system_prompt import build_system_prompt, build_system_prompt_partsagent = _build_inspection_agent(platform)-parts = build_system_prompt_parts(agent)full = build_system_prompt(agent)-stable = parts.get("stable", "")context = parts.get("context", "")volatile = parts.get("volatile", "")- # Skills index — the <available_skills> block (the largest single block- # when many skills are installed). Lives in the volatile tier (moved from- # stable so skill edits don't invalidate the cached identity prefix).+ # The skills index lives in the volatile tier (moved from stable so skill edits don't+ # invalidate the cached identity prefix); fall back to stable for older layouts.skills_match = _SKILLS_BLOCK_RE.search(volatile) or _SKILLS_BLOCK_RE.search(stable)skills_index = skills_match.group(0) if skills_match else ""- # Memory + user profile live in the volatile tier. We re-derive their- # blocks directly from the memory store so the numbers are attributable- # even though they're joined into ``volatile``.+ # Memory + user profile are joined into ``volatile``; re-derive them from the store so the+ # numbers stay attributable.memory_block = ""user_block = ""store = getattr(agent, "_memory_store", None)@@ -225,18 +195,12 @@ def compute_prompt_breakdown(platform: str = "cli") -> Dict[str, Any]:except Exception:pass- # Tool-schema JSON — the other half of the fixed per-call payload.tools = getattr(agent, "tools", None) or []-- def _size(text: str) -> Dict[str, int]:- return {"chars": len(text), "bytes": _bytes(text)}-sections: List[Tuple[str, int, int]] = [("stable (identity/guidance/skills)", len(stable), _bytes(stable)),("context (AGENTS.md/cwd files)", len(context), _bytes(context)),("volatile (memory/profile/timestamp)", len(volatile), _bytes(volatile)),]-return {"platform": platform,"model": getattr(agent, "model", "") or "",@@ -251,10 +215,6 @@ def compute_prompt_breakdown(platform: str = "cli") -> Dict[str, Any]:}-def _fmt_kb(n: int) -> str:- return f"{n / 1024:.1f} KB"--def render_breakdown(data: Dict[str, Any]) -> str:"""Render the breakdown as plain text suitable for a terminal."""sp = data["system_prompt"]@@ -275,9 +235,7 @@ def render_breakdown(data: Dict[str, Any]) -> str:lines.append(f" {label:<36}: {byts:>8,} B ({_fmt_kb(byts)})")lines += ["", f" Tool schemas : {tools['json_bytes']:>8,} B ({_fmt_kb(tools['json_bytes'])}, {tools['count']} tools)"]- # Per-toolset schema cost — which toolset's tools cost the most to ship.- toolsets = data.get("toolsets_breakdown") or []- if toolsets:+ if toolsets := data.get("toolsets_breakdown") or []:lines += ["", " Toolsets by size (tool-schema JSON, largest first):",f" {'toolset':<22} {'tools':>5} {'schema':>10}"]for ts in toolsets:@@ -287,8 +245,7 @@ def render_breakdown(data: Dict[str, Any]) -> str:)# Per-skill cost — index line (always shipped) vs SKILL.md (read on load).- skills = data.get("skills_breakdown") or []- if skills:+ if skills := data.get("skills_breakdown") or []:lines += [""," Skills by size (SKILL.md on-disk = read cost; index cost = ""attributed always-on bytes, largest first):",@@ -310,13 +267,9 @@ def render_breakdown(data: Dict[str, Any]) -> str:def cmd_prompt_size(args: Any) -> None:"""Entry point for ``hermes prompt-size``."""platform = getattr(args, "platform", "cli") or "cli"- as_json = getattr(args, "json", False)try:data = compute_prompt_breakdown(platform)except Exception as e:print(f"Could not compute prompt-size breakdown: {e}")return- if as_json:- print(json.dumps(data, ensure_ascii=False, indent=2))- else:- print(render_breakdown(data))+ print(json.dumps(data, ensure_ascii=False, indent=2) if getattr(args, "json", False) else render_breakdown(data))diff --git a/hermes_cli/prompt_stash.py b/hermes_cli/prompt_stash.pyindex cacbbe4d7d4..6afc7791667 100644--- a/hermes_cli/prompt_stash.py+++ b/hermes_cli/prompt_stash.py@@ -1,10 +1,8 @@"""Ctrl+S prompt stash — pure state machine for the classic CLI composer.-The state machine lives here (no prompt_toolkit imports) so it can be unit tested directly;-``cli.py`` owns only the keybinding and the rendering.--Newest-first ordering: index 0 is always the most recently stashed draft, so the common "undo my-last Ctrl+S" case is a single keystroke.+No prompt_toolkit imports so it can be unit tested directly; ``cli.py`` owns only the keybinding+and the rendering. Newest-first: index 0 is always the most recently stashed draft, so "undo my+last Ctrl+S" is a single keystroke."""from __future__ import annotations@@ -42,7 +40,7 @@ class StashEntry:preview: str = ""def as_dict(self) -> dict:- """Render in the shape ``HermesCLI._render_stash_panel`` consumes."""+ """Shape ``HermesCLI._render_stash_panel`` consumes."""return {"text": self.text,"images": list(self.images),@@ -61,8 +59,6 @@ class PromptStash:self.panel_open = Falseself.panel_cursor = 0- # ---------------------------------------------------------------- queries-def __len__(self) -> int:return len(self._items)@@ -72,15 +68,10 @@ class PromptStash:return list(self._items)def panel_rows(self) -> List[dict]:- """Entries as plain dicts for the panel renderer."""return [e.as_dict() for e in self._items]def indicator(self) -> str:- """Status-bar indicator, or ``""`` when the stash is empty.-- ``📌 2`` when idle, ``📌 2 ▲`` while the browse panel is open, so the user can always tell a- parked draft exists without opening anything.- """+ """Status-bar indicator: ``📌 2`` idle, ``📌 2 ▲`` while browsing, ``""`` when empty."""n = len(self._items)return "" if not n else f"📌 {n} ▲" if self.panel_open else f"📌 {n}"@@ -93,14 +84,9 @@ class PromptStash:return f"Ctrl+S to restore: {self._items[0].preview}"return f"Ctrl+S to browse {n} stashed drafts"- # --------------------------------------------------------------- mutators-def stash(self, text: str, images: Optional[Sequence[Any]] = None) -> bool:- """Push a draft. Returns False (no-op) for a blank buffer.-- A buffer that is empty or whitespace-only is not worth parking and must stay a no-op,- otherwise Ctrl+S on an empty composer would push a junk entry instead of triggering the- restore half of the gesture.+ """Push a draft. A blank buffer with no images is a no-op (returns False) so Ctrl+S on an+ empty composer triggers the restore half of the gesture instead of pushing junk."""if not (text or "").strip() and not images:return False@@ -112,10 +98,8 @@ class PromptStash:preview=build_preview(text or "") or "(images only)",)self._items.insert(0, entry)- # Drop the oldest entries past the cap.- del self._items[self._max_items:]- # A push invalidates any open browse session.- self.close_panel()+ del self._items[self._max_items:] # drop the oldest past the cap+ self.close_panel() # a push invalidates any open browse sessionreturn Truedef pop(self, index: int = 0) -> Optional[Tuple[str, List[Any]]]:@@ -129,7 +113,6 @@ class PromptStash:return entry.text, list(entry.images)def peek(self, index: int = 0) -> Optional[StashEntry]:- """Return the entry at ``index`` without removing it."""return self._items[index] if 0 <= index < len(self._items) else Nonedef clear(self) -> None:@@ -181,8 +164,6 @@ class PromptStash:return result-# --------------------------------------------------------------------- gesture-# Outcomes of a single Ctrl+S press.ACTION_NOOP = "noop"ACTION_STASHED = "stashed"@@ -196,18 +177,15 @@ def resolve_ctrl_s(buffer_text: str,images: Optional[Sequence[Any]] = None,) -> Tuple[str, Optional[Tuple[str, List[Any]]]]:- """Decide what one Ctrl+S press does. Returns ``(action, payload)``.-- ``payload`` is ``(text, images)`` for :data:`ACTION_RESTORED`, else None. The whole decision- table lives in this pure function so the ``cli.py`` keybinding handler stays a thin adapter.+ """Decide what one Ctrl+S press does. Returns ``(action, payload)`` where ``payload`` is+ ``(text, images)`` for :data:`ACTION_RESTORED`, else None."""# Panel open → Ctrl+S is the "close it" escape hatch.if stash.panel_open:stash.close_panel()return ACTION_CLOSE_PANEL, None- # Something to park → park it. Never silently clobbers an existing stash:- # entries push onto a stack, so an earlier draft is still reachable.+ # Something to park → park it (onto a stack, so an earlier draft is still reachable).if (buffer_text or "").strip() or images:return (ACTION_STASHED if stash.stash(buffer_text, images) else ACTION_NOOP), Nonediff --git a/hermes_cli/pt_input_extras.py b/hermes_cli/pt_input_extras.pyindex b33de89b86b..9737b1cbb02 100644--- a/hermes_cli/pt_input_extras.py+++ b/hermes_cli/pt_input_extras.py@@ -2,22 +2,20 @@from __future__ import annotations-# kitty CSI-u ORs lock-key state into the modifier parameter of every key-# event while a lock is on: CapsLock=64, NumLock=128, both=192 (#88221,-# #89651). Every fixed-modifier CSI-u (and legacy CSI-tilde / CSI-letter)-# registration therefore needs lock-offset twins, or those events leak into-# the prompt as literal text. The xterm modifyOtherKeys ``ESC[27;N;CP~``-# encoding never carries lock bits, so it never gets the twins.+# kitty CSI-u ORs lock-key state into the modifier parameter of every key event while a lock is+# on: CapsLock=64, NumLock=128, both=192. Every fixed-modifier CSI-u (and legacy CSI-tilde /+# CSI-letter) registration therefore needs lock-offset twins, or those events leak into the prompt+# as literal text. The xterm modifyOtherKeys ``ESC[27;N;CP~`` encoding never carries lock bits._LOCK_BIT_OFFSETS = (0, 64, 128, 192)def _lock_variants(modifier: int) -> tuple[int, ...]:- """Return ``modifier`` plus its CapsLock/NumLock/both twins."""+ """``modifier`` plus its CapsLock/NumLock/both twins."""return tuple(modifier + off for off in _LOCK_BIT_OFFSETS)def _lock_twins(modifier: int) -> tuple[int, ...]:- """Return only the lock twins of ``modifier`` (never the base value)."""+ """Only the lock twins of ``modifier`` (never the base value)."""return tuple(modifier + off for off in _LOCK_BIT_OFFSETS[1:])@@ -28,16 +26,14 @@ def _clear_vt100_prefix_cache() -> None:would keep stale ``False`` answers and misparse newly registered sequences."""try:- from prompt_toolkit.input.vt100_parser import (- _IS_PREFIX_OF_LONGER_MATCH_CACHE,- )+ from prompt_toolkit.input.vt100_parser import _IS_PREFIX_OF_LONGER_MATCH_CACHE_IS_PREFIX_OF_LONGER_MATCH_CACHE.clear()except Exception:passdef _pt_tables():- """Return ``(ANSI_SEQUENCES, Keys)`` or ``None`` when prompt_toolkit is unavailable."""+ """``(ANSI_SEQUENCES, Keys)`` or ``None`` when prompt_toolkit is unavailable."""try:from prompt_toolkit.input.ansi_escape_sequences import ANSI_SEQUENCESfrom prompt_toolkit.keys import Keys@@ -50,8 +46,7 @@ def _register(table: dict, aliases: dict, *, overwrite: bool) -> int:"""Install ``aliases`` into ``table``; return the number of entries changed.``overwrite=True`` replaces differing entries; ``overwrite=False`` behaves like ``setdefault``- so existing/user registrations win. Clears the VT100 prefix cache when anything changed, since- new longer sequences can flip "is this a prefix of a longer match?" answers the parser cached.+ so existing/user registrations win. Clears the VT100 prefix cache when anything changed."""changed = 0for seq, key in aliases.items():@@ -65,8 +60,7 @@ def _register(table: dict, aliases: dict, *, overwrite: bool) -> int:def install_keypress_data_normalization() -> int:"""Normalize KeyPress data for extended-key aliases that map to a single plain character- (Shift+Space → ``' '``, Shift+letter → the uppercase letter, keypad digits → ``'0'``..``'9'``,- keypad operators).+ (Shift+Space → ``' '``, Shift+letter → uppercase, keypad digits/operators)."""try:import prompt_toolkit.input.vt100_parser as _vt100_mod@@ -74,17 +68,13 @@ def install_keypress_data_normalization() -> int:except Exception:return 0- if getattr(- _vt100_mod.Vt100Parser._call_handler, "_hermes_char_data_normalized", False- ):- return 0-_orig_call_handler = _vt100_mod.Vt100Parser._call_handler+ if getattr(_orig_call_handler, "_hermes_char_data_normalized", False):+ return 0def _patched_call_handler(self, key, insert_text):- # A single plain character (not a Keys member, not a tuple) mapped- # from an extended sequence must carry the mapped character as its- # data — self-insert inserts event.data and the raw CSI would leak.+ # A single plain character mapped from an extended sequence must carry the mapped+ # character as its data — self-insert inserts event.data and the raw CSI would leak.if (isinstance(key, str)and len(key) == 1@@ -101,12 +91,11 @@ def install_keypress_data_normalization() -> int:def _install_enter_alias(modifier: int) -> int:- """Map <modifier>+Enter (Kitty CSI-u ``ESC[13;<m>u`` plus lock-bit twins, xterm- ``ESC[27;<m>;13~`` / ``;13u``) to (Escape, ControlM) so the Alt+Enter newline handler fires.+ """Map <modifier>+Enter (Kitty CSI-u ``ESC[13;<m>u`` plus lock twins, xterm ``ESC[27;<m>;13~``+ / ``;13u``) to (Escape, ControlM) so the Alt+Enter newline handler fires.Stock prompt_toolkit maps the tilde form to plain ControlM (i.e. Shift+Enter == Enter, the very- bug this fixes), so those keys are overwritten unconditionally; other modifier variants are- untouched.+ bug this fixes), so these keys are overwritten unconditionally."""tables = _pt_tables()if tables is None:@@ -120,29 +109,22 @@ def _install_enter_alias(modifier: int) -> int:def install_shift_enter_alias() -> int:- """Map Shift+Enter sequences to (Escape, ControlM) so the Alt+Enter newline handler fires.-- macOS Terminal and stock Windows Terminal send the same byte for Enter and Shift+Enter, so- nothing can be done for them here.+ """Map Shift+Enter to (Escape, ControlM). macOS Terminal and stock Windows Terminal send the+ same byte for Enter and Shift+Enter, so nothing can be done for them here."""return _install_enter_alias(2)def install_ctrl_enter_alias() -> int:- """Map Ctrl+Enter sequences to (Escape, ControlM) so the Alt+Enter newline handler fires.-- Without the alias, Kitty/mintty/xterm users over SSH get a raw CSI sequence inserted as text.- """+ """Map Ctrl+Enter to (Escape, ControlM); otherwise Kitty/mintty/xterm over SSH insert raw CSI."""return _install_enter_alias(5)def install_cmd_backspace_alias() -> int:- """Map Cmd+Backspace / Cmd+ForwardDelete to prompt_toolkit's readline kill bindings.+ """Map Cmd+Backspace -> ControlU and Cmd+ForwardDelete -> ControlK.- Terminals that rewrite Cmd+Backspace to Ctrl+U already work; Kitty/modifyOtherKeys report Cmd- as the super bit (8), yielding unmapped sequences that insert literally. Cmd+Backspace ->- ControlU (``ESC[127;9u``, ``;10u``, ``ESC[27;9;127~``); Cmd+ForwardDelete -> ControlK via- the CSI tilde form ``ESC[3;9~`` / ``;10~`` since forward-delete is not a CSI-u codepoint.+ Kitty/modifyOtherKeys report Cmd as the super bit (8), yielding unmapped sequences that insert+ literally. Forward-delete is not a CSI-u codepoint, so it uses the CSI tilde form ``ESC[3;9~``."""tables = _pt_tables()if tables is None:@@ -157,102 +139,73 @@ def install_cmd_backspace_alias() -> int:return _register(seqs, aliases, overwrite=True)+# Kitty functional keys (Private Use Area codepoints) that have prompt_toolkit equivalents.+# kitty emits these CSI-u encodings even in LEGACY mode, so unmapped they leak as literal text.+_KITTY_FUNCTIONAL_NAMED = {+ 57409: ".", 57410: "/", 57411: "*", 57412: "-", 57413: "+", 57414: "ControlM", # KP ops+ 57415: "=", 57416: ",",+ 57417: "Left", 57418: "Right", 57419: "Up", 57420: "Down", 57421: "PageUp", # KP nav+ 57422: "PageDown", 57423: "Home", 57424: "End", 57425: "Insert", 57426: "Delete",+}+# No prompt_toolkit equivalent: locks/PrintScreen/Pause/Menu, F25-F35, KP_BEGIN, media keys and+# bare modifier events — consumed as Ignore instead of leaking literal text.+_KITTY_FUNCTIONAL_IGNORED = (*range(57358, 57364), *range(57388, 57399), 57427, *range(57428, 57455))+++def _kitty_functional_map(Keys) -> dict[int, object]:+ fm: dict[int, object] = {57399 + d: str(d) for d in range(10)} # KP_0..KP_9+ fm.update({cp: getattr(Keys, v) if v[0].isupper() else v for cp, v in _KITTY_FUNCTIONAL_NAMED.items()})+ fm.update({57376 + (n - 13): getattr(Keys, f"F{n}") for n in range(13, 25)}) # F13..F24+ for code in _KITTY_FUNCTIONAL_IGNORED:+ fm.setdefault(code, Keys.Ignore)+ return fm++def install_modify_other_keys_aliases() -> int:"""Map modifyOtherKeys-2 / Kitty CSI-u Ctrl/Alt+key sequences to their raw-byte ``Keys``.Once ``modifyOtherKeys=2`` is pushed (to distinguish Shift+Enter) the terminal re-encodesEVERY Ctrl combo as ``ESC[27;5;<cp>~``; stock prompt_toolkit maps only Ctrl+Enter, so- Ctrl+A/C/D/E/K/R/U/W/Z leak as text. Installs Ctrl/Alt/Shift letters, digits, symbols,- multi-modifier combos, CapsLock/NumLock lock-bit variants, CSI-u Esc, modified- Enter/Tab/Backspace/Space, and Kitty functional keys. Uses ``setdefault`` so existing- mappings (incl. the Shift/Ctrl+Enter aliases) are never overwritten.+ Ctrl+A/C/D/... leak as text. Installs Ctrl/Alt/Shift letters, digits, symbols, multi-modifier+ combos, lock-bit variants, CSI-u Esc, modified Enter/Tab/Backspace/Space and Kitty functional+ keys. ``setdefault`` semantics: existing mappings (incl. the Shift/Ctrl+Enter aliases) win."""tables = _pt_tables()if tables is None:return 0ANSI_SEQUENCES, Keys = tables- # Everything below is collected into ``aliases`` (first writer wins, matching setdefault- # order) and installed once at the end.+ # Collected first-writer-wins (matching setdefault order), installed once at the end.aliases: dict[str, object] = {}+ _put = aliases.setdefault- def _put(seq: str, key_val: object) -> None:- aliases.setdefault(seq, key_val)-- # -- Ctrl+letter / Ctrl+digit / Ctrl+symbol → Keys.Control* ----- # codepoint -> Keys value. The raw control byte for Ctrl+<ch> is- # chr(ord(ch) & 0x1f) (i.e. ord(ch) - 96 for lowercase). We map the- # *extended* sequence to the same Keys value that the raw byte maps to,- # so prompt_toolkit's existing key bindings fire identically.- ctrl_key_map: dict[int, object] = {}+ def _install_paired(modifier: int, mapping: dict) -> None:+ """Both modifyOtherKeys (ESC[27;N;CP~, never for mod 1) and CSI-u (ESC[CP;Nu + lock twins)."""+ for codepoint, key_val in mapping.items():+ if modifier != 1:+ _put(f"\x1b[27;{modifier};{codepoint}~", key_val)+ for mod in _lock_variants(modifier):+ _put(f"\x1b[{codepoint};{mod}u", key_val)- # a-z: Ctrl+A = \x01 = Keys.ControlA, ..., Ctrl+Z = \x1a = Keys.ControlZ- # Symbols that produce control chars:- # Ctrl+@ (64) = \x00 = Keys.ControlAt- # Ctrl+[ (91) = \x1b = Keys.Escape- # Ctrl+\ (92) = \x1c = Keys.ControlBackslash- # Ctrl+] (93) = \x1d = Keys.ControlSquareClose- # Ctrl+^ (94) = \x1e = Keys.ControlCircumflex- # Ctrl+_ (95) = \x1f = Keys.ControlUnderscore- # Ctrl+Space(32) = \x00 = Keys.ControlAt (prompt_toolkit maps \x00 → ControlAt)+ # Ctrl+<ch>: the extended sequence maps to whatever Keys value the raw control byte+ # chr(ord(ch) & 0x1f) already maps to, so existing bindings fire identically. Covers a-z and+ # the control-producing symbols @ [ \ ] ^ _ and Space (\x00 -> ControlAt).letters = range(ord('a'), ord('z') + 1)+ ctrl_key_map: dict[int, object] = {}for codepoint in (*letters, 64, 91, 92, 93, 94, 95, 32):existing = ANSI_SEQUENCES.get(chr(codepoint & 0x1F))if existing is not None:ctrl_key_map[codepoint] = existing-- # 0-9: Ctrl+digit codepoints don't have a useful raw-byte mapping- # (e.g. chr(ord('0') & 0x1F) = 0x10 = ControlP, not Control0), so map- # them directly to Keys.Control0..Keys.Control9.+ # Ctrl+digit has no useful raw byte (chr(ord('0') & 0x1F) is ControlP), so map directly.for d in range(10):ctrl_key_map[ord('0') + d] = getattr(Keys, f"Control{d}")-- # Kitty CSI-u encodes CapsLock/NumLock state as extra modifier bits- # (caps=64, num=128) ORed into the parameter: with NumLock on, Ctrl+C- # arrives as ESC[99;133u (5 + 128) instead of ESC[99;5u. Terminals- # that report these bits (kitty, ghostty) break every key combo while- # a lock is on (#89651) unless the lock variants are mapped too. The- # xterm modifyOtherKeys encoding never carries the lock bits, so only- # the CSI-u form needs them.- def _install_paired(modifier: int, mapping: dict) -> None:- """Install both modifyOtherKeys (ESC[27;N;CP~) and CSI-u (ESC[CP;Nu) mappings for the given- modifier and codepoint→key mapping.- """- for codepoint, key_val in mapping.items():- if modifier != 1:- _put(f"\x1b[27;{modifier};{codepoint}~", key_val)- for mod in _lock_variants(modifier):- _put(f"\x1b[{codepoint};{mod}u", key_val)-- # Ctrl+letter / Ctrl+digit / Ctrl+symbol (modifier 5)_install_paired(5, ctrl_key_map)- # -- Alt+letter → (Escape, <letter>) ----- # Under modifyOtherKeys, Alt+a = ESC[27;3;97~. Without mapping, this- # leaks as literal text. prompt_toolkit handles bare Alt+letter as- # (Escape, <letter>), so we map the extended sequences to the same tuple.- #- # -- Shift+letter → uppercase letter ----- # Under modifyOtherKeys=2, some terminals re-encode Shift+a as- # ESC[27;2;97~. Without mapping, this leaks as literal escape +- # "[27;2;97~" in the prompt buffer — the "caps locked" / "every key- # combo is broken" symptom (#87711).- # Map Shift+letter to the uppercase character so typing works normally.- # This is safe across all Latin keyboard layouts: Shift always uppercases- # letters. Shift+digit symbols are layout-specific (US: '!', AZERTY: '¹',- # etc.) so they are NOT mapped here — if the terminal sends those under- # modifyOtherKeys, they will leak, but that's better than wrong input.- # Map both the lowercase and uppercase codepoints — some terminals send- # the already-shifted codepoint (65 for 'A') with modifier=2.- #- # -- Multi-modifier letters: Shift+Alt (4), Ctrl+Shift (6),- # Ctrl+Alt (7), Ctrl+Alt+Shift (8) ----- # The Kitty protocol always reports the UNSHIFTED codepoint; some- # modifyOtherKeys emitters send the shifted one — map both cases.- # Ctrl-bearing combos normalize onto the Ctrl key (Alt adds an Escape- # prefix), Shift+Alt onto (Escape, UPPER) — the same normalization- # dte/kakoune apply to these protocols. Without these, Ctrl+Shift+R- # etc. leak as literal text under either protocol.+ # Letter combos. Alt+a -> (Escape, 'a') like bare Alt. Shift+a -> 'A' (safe on every Latin+ # layout; Shift+digit symbols are layout-specific and deliberately NOT mapped — leaking beats+ # wrong input). Kitty reports the UNSHIFTED codepoint, some modifyOtherKeys emitters the shifted+ # one — map both. Ctrl-bearing combos normalize onto the Ctrl key (Alt adds an Escape prefix),+ # Shift+Alt onto (Escape, UPPER) — the same normalization dte/kakoune apply.alt_map: dict[int, tuple] = {}shift_map: dict[int, str] = {}shift_alt_map: dict[int, tuple] = {}@@ -269,84 +222,46 @@ def install_modify_other_keys_aliases() -> int:if ctrl_key is not None:ctrl_shift_map[cp] = ctrl_keyctrl_alt_map[cp] = (Keys.Escape, ctrl_key)- _install_paired(3, alt_map)- _install_paired(2, shift_map)- _install_paired(4, shift_alt_map)- _install_paired(6, ctrl_shift_map)- _install_paired(7, ctrl_alt_map)- _install_paired(8, ctrl_alt_map) # Ctrl+Alt+Shift — same normalization-- # -- The Esc KEY under Kitty disambiguate mode: ESC[27u (+ modifiers) --- # Disambiguate mode reports the Esc key as CSI-u so it is- # distinguishable from the ESC byte that starts escape sequences- # (#56684 — previously leaked "[27u" as literal text into the prompt).- # Modifiers run from 1 to 16: kitty reports Cmd as the super bit- # (mod 9+) — same reason install_cmd_backspace_alias maps 9/10 — and- # the lock-bit variants of the modifier-less form (1+64/128/192) are- # how a lone Esc keypress arrives with a lock on. Lock bits (caps/num)- # get the same variant treatment as _install_paired.+ for modifier, mapping in (+ (3, alt_map), (2, shift_map), (4, shift_alt_map), (6, ctrl_shift_map),+ (7, ctrl_alt_map), (8, ctrl_alt_map), # Ctrl+Alt+Shift — same normalization+ ):+ _install_paired(modifier, mapping)++ # The Esc KEY under Kitty disambiguate mode: ESC[27u (+ modifiers 1-16 incl. super 9+, and+ # lock twins of the modifier-less form, which is how a lone Esc arrives with a lock on)._put("\x1b[27u", Keys.Escape)for m in range(1, 17):for mod in _lock_variants(m):_put(f"\x1b[27;{mod}u", Keys.Escape)- # -- Modified Enter / Tab / Backspace / Space ----- # Shift+Enter / Ctrl+Enter are installed by install_shift_enter_alias /- # install_ctrl_enter_alias (which run first and win via setdefault).- _install_paired(2, {- 9: Keys.BackTab, # Shift+Tab — same as the legacy ESC[Z- 127: Keys.ControlH, # Shift+Backspace — plain backspace- 32: " ", # Shift+Space — still a space (#86866)- })- _install_paired(3, {- 13: (Keys.Escape, Keys.ControlM), # Alt+Enter — newline tuple- 127: (Keys.Escape, Keys.ControlH), # Alt+Backspace — backward-kill-word- 32: (Keys.Escape, " "), # Alt+Space- })- _install_paired(5, {- 9: Keys.ControlI, # Ctrl+Tab — degrade to Tab- 127: (Keys.Escape, Keys.ControlH), # Ctrl+Backspace — backward-kill-word,- # matching Ink TUI + Desktop (#78285)- })-- # -- Unmodified keys with a lock bit set (kitty modifier 1 = "none") --- # With a lock on, kitty stamps the lock bit onto keys pressed with NO- # real modifier too, so plain Backspace arrives as ESC[127;129u- # (1 + 128) rather than \x7f. _install_paired(1, ...) registers the- # bare mod-1 spelling and its lock twins. Only keys kitty CSI-u-encodes- # on their own are listed; plain text characters are still delivered- # as UTF-8, lock bits or not.- _install_paired(1, {- 9: Keys.ControlI, # Tab- 13: Keys.ControlM, # Enter- 32: " ", # Space- 127: Keys.ControlH, # Backspace- })-- # -- Lock-key modifier bits (NumLock=128, CapsLock=64) on the legacy- # CSI-letter / CSI-tilde forms kitty keeps using under the disambiguate- # push: kitty encodes lock state into the modifier parameter, so a- # plain Down with NumLock on arrives as ESC[1;129B (NumLock), ESC[1;65B- # (CapsLock) or ESC[1;193B (both) instead of the legacy ESC[B — and a- # modified one shifts the same way (Alt+Left → ESC[1;131D). Those fall- # through the parser and leak as literal text ("[1;129B") in the input- # line. Derive the lock twins from whatever the table already maps for- # the base modifier (stock prompt_toolkit entries included), so every- # modifier the terminal can report keeps working under a lock.+ # Modified Enter/Tab/Backspace/Space (Shift/Ctrl+Enter are owned by the enter aliases, which run+ # first and win). Modifier 1 = unmodified keys kitty CSI-u-encodes on their own when a lock bit+ # is set (plain Backspace arrives as ESC[127;129u rather than \x7f).+ alt_enter = (Keys.Escape, Keys.ControlM)+ alt_backspace = (Keys.Escape, Keys.ControlH) # backward-kill-word, matching Ink TUI + Desktop+ for modifier, mapping in (+ (2, {9: Keys.BackTab, 127: Keys.ControlH, 32: " "}),+ (3, {13: alt_enter, 127: alt_backspace, 32: (Keys.Escape, " ")}),+ (5, {9: Keys.ControlI, 127: alt_backspace}), # Ctrl+Tab degrades to Tab+ (1, {9: Keys.ControlI, 13: Keys.ControlM, 32: " ", 127: Keys.ControlH}),+ ):+ _install_paired(modifier, mapping)++ # Lock twins for the legacy CSI-letter / CSI-tilde forms kitty keeps using under the+ # disambiguate push (Down with NumLock on = ESC[1;129B; Alt+Left = ESC[1;131D). Derived from+ # whatever the table already maps for the base modifier, stock entries included.for m in range(1, 17):- # CSI-letter navigation: Up/Down/Right/Left/End/Home + F1-F4- for trailer in "ABCDFHPQRS":+ for trailer in "ABCDFHPQRS": # Up/Down/Right/Left/End/Home + F1-F4base_seq = f"\x1b[1;{m}{trailer}" if m > 1 else f"\x1b[{trailer}"key = ANSI_SEQUENCES.get(base_seq)if key is None and m == 1:- # Plain F1-F4 live in the table as SS3 (ESC O P) forms.- key = ANSI_SEQUENCES.get(f"\x1bO{trailer}")+ key = ANSI_SEQUENCES.get(f"\x1bO{trailer}") # plain F1-F4 live as SS3 formsif key is None:continuefor mod in _lock_twins(m):_put(f"\x1b[1;{mod}{trailer}", key)- # CSI-tilde navigation: Insert/Delete/PageUp/PageDown/Home/End- for num in range(1, 9):+ for num in range(1, 9): # Insert/Delete/PageUp/PageDown/Home/Endbase_seq = f"\x1b[{num};{m}~" if m > 1 else f"\x1b[{num}~"key = ANSI_SEQUENCES.get(base_seq)if key is None:@@ -354,50 +269,18 @@ def install_modify_other_keys_aliases() -> int:for mod in _lock_twins(m):_put(f"\x1b[{num};{mod}~", key)- # -- Kitty functional keys (Private Use Area codepoints) ----- # kitty emits these CSI-u encodings even in LEGACY mode for keys that- # have no legacy encoding, so unmapped they leak as literal text in any- # kitty session regardless of which modes were pushed.- functional_map: dict[int, object] = {}- for d in range(10): # KP_0..KP_9 → digits- functional_map[57399 + d] = str(d)- functional_map.update({ # KP operators / punctuation- 57409: ".", 57410: "/", 57411: "*", 57412: "-",- 57413: "+", 57414: Keys.ControlM, 57415: "=", 57416: ",",- })- functional_map.update({ # KP navigation → non-keypad keys- 57417: Keys.Left, 57418: Keys.Right, 57419: Keys.Up,- 57420: Keys.Down, 57421: Keys.PageUp, 57422: Keys.PageDown,- 57423: Keys.Home, 57424: Keys.End, 57425: Keys.Insert,- 57426: Keys.Delete,- })- for n in range(13, 25): # F13..F24- functional_map[57376 + (n - 13)] = getattr(Keys, f"F{n}")- # No prompt_toolkit equivalent (lock keys, PrintScreen, Menu, F25-F35,- # KP_BEGIN, media keys, bare modifier events): consume as Ignore- # instead of leaking literal text.- for code in (- list(range(57358, 57364)) # locks, PrintScreen, Pause, Menu- + list(range(57388, 57399)) # F25..F35- + [57427] # KP_BEGIN- + list(range(57428, 57455)) # media keys + modifier key events- ):- functional_map.setdefault(code, Keys.Ignore)- for code, key_val in functional_map.items():+ for code, key_val in _kitty_functional_map(Keys).items():_put(f"\x1b[{code}u", key_val)- # Lock twins: with a lock on these arrive as ESC[<code>;129u etc.- for mod in _lock_twins(1):+ for mod in _lock_twins(1): # with a lock on these arrive as ESC[<code>;129u etc._put(f"\x1b[{code};{mod}u", key_val)return _register(ANSI_SEQUENCES, aliases, overwrite=False)def install_ignored_terminal_sequences() -> int:- """Map terminal noise sequences to ``Keys.Ignore`` so the VT100 parser consumes them.+ """Map focus reports ``ESC[I`` / ``ESC[O`` (Ghostty, iTerm2, some xterms) to ``Keys.Ignore``.- Covers focus reports ``ESC[I`` / ``ESC[O``, which Ghostty, iTerm2 and some xterms emit on- tab/window switches; unmapped, prompt_toolkit inserts ``[I``/``[O`` into the buffer. Parser-- level handling beats post-hoc regex stripping because the bytes never reach the buffer.+ Parser-level handling beats post-hoc regex stripping because the bytes never reach the buffer.``setdefault`` lets user/downstream registrations win."""tables = _pt_tables()diff --git a/hermes_cli/pty_bridge.py b/hermes_cli/pty_bridge.pyindex ac35d743282..53afad7a8b5 100644--- a/hermes_cli/pty_bridge.py+++ b/hermes_cli/pty_bridge.py@@ -1,13 +1,9 @@"""PTY bridge for `hermes dashboard` chat tab.-Wraps a child process behind a pseudo-terminal so its ANSI output can be streamed to a browser-side-terminal emulator (xterm.js) and typed keystrokes can be fed back in. The only caller today is the-``/api/pty`` WebSocket endpoint in ``hermes_cli.web_server``.--* **POSIX-only.** This module depends on ``fcntl``, ``termios``, and ``ptyprocess``, none of which-exist on native Windows Python. Native Windows ConPTY is a different API (Windows 10 build 17763+)-and would need a separate Windows implementation (``pywinpty``) — that's tracked as a future-enhancement.+Wraps a child process behind a pseudo-terminal so its ANSI output can be streamed to xterm.js and+keystrokes fed back in; the only caller is the ``/api/pty`` WebSocket endpoint in+``hermes_cli.web_server``. POSIX-only: depends on ``fcntl``, ``termios`` and ``ptyprocess`` (native+Windows would need a separate ConPTY/``pywinpty`` implementation)."""from __future__ import annotations@@ -34,21 +30,17 @@ except ImportError: # pragma: no cover - dev env without ptyprocess__all__ = ["PtyBridge", "PtyUnavailableError"]-# ``struct winsize`` packs rows/cols as unsigned short (0..65535). We clamp-# well below that ceiling: real terminals never exceed a couple thousand-# columns, and a value above this is a broken probe (WSL2 reports-# columns=131072) rather than a genuine ultrawide. Lower bound is 1 — a-# zero/negative dimension is the classic "no size yet" signal.+# ``struct winsize`` packs rows/cols as unsigned short; we clamp well below that ceiling because a+# value above it is a broken probe (WSL2 reports columns=131072), not a genuine ultrawide. Lower+# bound is 1 — a zero/negative dimension is the classic "no size yet" signal._MIN_DIMENSION = 1_MAX_COLS = 2000_MAX_ROWS = 1000def _clamp_dimension(value: int, maximum: int) -> int:- """Clamp a reported terminal dimension into ``[_MIN_DIMENSION, maximum]``.-- Non-integer / non-finite values fall back to ``_MIN_DIMENSION`` so a bad probe can never reach- ``struct.pack`` and raise ``struct.error``.+ """Clamp into ``[_MIN_DIMENSION, maximum]``; non-integer / non-finite values fall back to+ ``_MIN_DIMENSION`` so a bad probe can never reach ``struct.pack``."""try:n = int(value)@@ -58,18 +50,14 @@ def _clamp_dimension(value: int, maximum: int) -> int:class PtyUnavailableError(RuntimeError):- """Raised when a PTY cannot be created on this platform.-- Today this means native Windows (no ConPTY bindings) or a dev environment missing- ``ptyprocess``. The dashboard surfaces the message as a chat-tab banner.+ """PTY cannot be created here (native Windows, or ``ptyprocess`` missing); the dashboard+ surfaces the message as a chat-tab banner."""class PtyBridge:- """Thin wrapper around ``ptyprocess.PtyProcess`` for byte streaming.-- Not thread-safe. A single bridge is owned by the WebSocket handler that spawned it; the reader- runs in an executor thread while writes happen on the event-loop thread.+ """Thin wrapper around ``ptyprocess.PtyProcess`` for byte streaming. Not thread-safe: owned by+ the WebSocket handler that spawned it; reads run in an executor thread, writes on the loop."""def __init__(self, proc: "ptyprocess.PtyProcess"): # type: ignore[name-defined]@@ -77,8 +65,6 @@ class PtyBridge:self._fd: int = proc.fdself._closed = False- # -- lifecycle ---------------------------------------------------------@classmethoddef is_available(cls) -> bool:"""True if a PTY can be spawned on this platform."""@@ -107,14 +93,9 @@ class PtyBridge:"Install with: pip install ptyprocess (or pip install -e '.[pty]').")raise PtyUnavailableError("Pseudo-terminals are unavailable.")- # PTY-hosted programs expect TERM to describe the terminal type.- # CI often runs without TERM in the parent process, which makes- # simple terminal probes like `tput cols` fail before winsize reads.- # Preserve explicit caller overrides, but backfill a sensible default- # when TERM is missing or blank.- # env=None fallback: callers own env policy (process_registry already- # sanitizes). Build via the factory with exact preservation so the- # site stays findable without changing inherited content.+ # env=None: callers own env policy (process_registry already sanitizes), so inherit via the+ # factory with exact preservation. Backfill TERM when missing/blank — CI often lacks it and+ # probes like `tput cols` then fail before winsize reads; explicit overrides are kept.from tools.environments.local import build_subprocess_envspawn_env = (build_subprocess_env(scrub_secrets=False, inherit_profile_home=False)@@ -139,13 +120,10 @@ class PtyBridge:except Exception:return False- # -- I/O ---------------------------------------------------------------def read(self, timeout: float = 0.2) -> Optional[bytes]:- """Read up to 64 KiB of raw bytes from the PTY master.+ """Read up to 64 KiB from the PTY master, blocking at most ``timeout`` seconds.- Never blocks longer than ``timeout`` seconds. Safe to call after :meth:`close`; returns- ``None`` in that case.+ ``b""`` = nothing yet; ``None`` = EOF / closed (also after :meth:`close`)."""if self._closed:return None@@ -184,10 +162,9 @@ class PtyBridge:def resize(self, cols: int, rows: int) -> None:"""Forward a terminal resize to the child via ``TIOCSWINSZ``.- Dimensions are clamped first: some hosts (WSL2 via xterm.js) report garbage like- ``columns=131072, rows=1``, and ``struct winsize`` packs unsigned shorts, so an unclamped- value raises ``struct.error`` (not ``OSError``), breaks resizing and leaves the TUI laid out- for a one-row screen — the blank/disappearing-text symptom.+ Clamped first: WSL2 via xterm.js reports garbage like ``columns=131072, rows=1`` and an+ unclamped unsigned-short pack raises ``struct.error`` (not ``OSError``), leaving the TUI+ laid out for a one-row screen — the blank/disappearing-text symptom."""if self._closed:return@@ -200,13 +177,9 @@ class PtyBridge:except OSError:pass- # -- teardown ----------------------------------------------------------def close(self) -> None:- """Terminate the child (SIGTERM → 0.5s grace → SIGKILL) and close fds.-- Idempotent. Reaping the child is important so we don't leak zombies across the lifetime of- the dashboard process.+ """Terminate the child (SIGHUP → SIGTERM → SIGKILL, 0.5s grace each), reap it so the+ dashboard process never leaks zombies, and close fds. Idempotent."""if self._closed:return@@ -217,10 +190,8 @@ class PtyBridge:except Exception:pgid = None- # SIGHUP is the conventional "your terminal went away" signal.- # Send it to the whole foreground process group, not just the PTY- # leader: the dashboard TUI starts helper children such as the Python- # slash worker, and killing only the leader can strand those helpers.+ # Signal the whole process group, not just the PTY leader: the dashboard TUI starts helper+ # children (e.g. the Python slash worker) and killing only the leader strands them.for sig in (signal.SIGHUP, signal.SIGTERM, signal.SIGKILL): # windows-footgun: ok — POSIX-only module (imports fcntl/termios/ptyprocess at top)if not self._proc.isalive():break@@ -240,7 +211,6 @@ class PtyBridge:except Exception:pass- # Context-manager sugar — handy in tests and ad-hoc scripts.def __enter__(self) -> "PtyBridge":return selfdiff --git a/hermes_cli/pty_session.py b/hermes_cli/pty_session.pyindex 8382a4a283c..74e480cf18e 100644--- a/hermes_cli/pty_session.py+++ b/hermes_cli/pty_session.py@@ -84,9 +84,8 @@ class PtySession:async def attach(self, ws, *, force_redraw: bool = False) -> None:"""Attach a browser terminal and replay buffered PTY output.- The TUI uses an alternate screen and differential rendering, so a bounded ANSI tail is not- guaranteed to be a self-contained frame. Reattaching a fresh xterm therefore asks the live- TUI to emit one complete redraw after the replay.+ The TUI renders differentially on an alternate screen, so a bounded ANSI tail is not a+ self-contained frame; ``force_redraw`` asks the live TUI for one full redraw after replay."""if self._ws is not ws:await _close_ws(self._ws, WS_CLOSE_SUPERSEDED)@@ -100,11 +99,9 @@ class PtySession:self.bridge.write(TUI_FORCE_REDRAW)def detach(self, ws) -> None:- # Only the currently-attached socket may mark the session detached.- # A superseded socket's handler also calls detach on its way out- # (its ``finally`` runs after the new tab attached); flipping- # ``attached`` then would make a session with a live viewer look- # idle and reapable.+ # Only the currently-attached socket may mark the session detached: a superseded socket's+ # handler also calls detach on its way out (after the new tab attached), and flipping+ # ``attached`` then would make a session with a live viewer look idle and reapable.if self._ws is not ws:returnself._ws = None@@ -119,8 +116,7 @@ class PtySession:except (asyncio.CancelledError, Exception):passtry:- # bridge.close() joins the child — blocking; keep it off the- # event loop (#53227).+ # bridge.close() joins the child — blocking; keep it off the event loop.await asyncio.to_thread(self.bridge.close)except Exception:pass@@ -160,8 +156,7 @@ class PtySessionRegistry:self._sessions.pop(key, None)if len(self._sessions) >= self._max:self._reap_one_idle_or_raise()- # PTY spawn does blocking fork/exec work — keep it off the event- # loop (#53227).+ # PTY spawn does blocking fork/exec work — keep it off the event loop.bridge = await asyncio.to_thread(spawn)session = PtySession(key, bridge, buffer_cap=self._buffer_cap,read_timeout=self._read_timeout)diff --git a/hermes_cli/security_advisories.py b/hermes_cli/security_advisories.pyindex 171de7b83df..49717752048 100644--- a/hermes_cli/security_advisories.py+++ b/hermes_cli/security_advisories.py@@ -1,8 +1,7 @@"""Security advisory checker for Hermes Agent.-- **Cheap.** A single ``importlib.metadata.version()`` call per advisory package. Safe to run on-every CLI startup. - **Loud when it matters, silent otherwise.** If no compromised package is-installed, the user sees nothing.+Cheap (one ``importlib.metadata.version()`` call per advisory package, safe on every CLI startup)+and silent unless a compromised package is actually installed."""from __future__ import annotations@@ -17,33 +16,19 @@ from typing import Iterable, Optionallogger = logging.getLogger(__name__)-# =============================================================================-# Advisory catalog-#-# Each advisory is a community-facing security warning about one or more-# specific package versions that are known to be compromised. To add a new-# advisory:-#-# 1. Append a new ``Advisory`` to ``ADVISORIES`` below-# 2. Set ``compromised`` to a tuple of ``(pkg_name, frozenset_of_versions)``-# — version strings must match what ``importlib.metadata.version()``-# returns. Use an empty frozenset to flag *any installed version*-# (rare; only when the maintainer namespace itself is compromised).-# 3. Write 2-4 short ``remediation`` lines a non-expert can copy/paste.-#-# Do NOT remove old advisories. Once an advisory ships, leave it in place so-# users running an older release with the compromised package still get-# warned. Mark superseded ones via ``superseded_by`` if needed.-# =============================================================================+# Advisory catalog. To add one: append an ``Advisory`` to ``ADVISORIES`` with ``compromised`` as+# ``(pkg_name, frozenset_of_versions)`` pairs (versions exactly as ``importlib.metadata.version()``+# returns them; an empty frozenset flags ANY installed version — rare, namespace compromise only)+# and 2-4 copy/pasteable ``remediation`` lines. Never remove old advisories: users on an older+# release with the compromised package must still get warned.@dataclass(frozen=True)class Advisory:"""One security advisory entry.- ``id`` is lowercase-hyphen, stable and never reused (it is what acks key on). An empty version- frozenset in ``compromised`` means any version is suspect — use sparingly. ``remediation`` is- ordered: uninstall command first, then credential audit/rotation guidance.+ ``id`` is lowercase-hyphen, stable and never reused (it is what acks key on). ``remediation``+ is ordered: uninstall command first, then credential audit/rotation guidance."""id: str@@ -93,9 +78,7 @@ ADVISORIES: tuple[Advisory, ...] = ()-# =============================================================================-# Detection-# =============================================================================+# ─── Detection ────────────────────────────────────────────────────────────────@dataclass(frozen=True)@@ -108,10 +91,8 @@ class AdvisoryHit:def _installed_version(pkg_name: str) -> Optional[str]:- """Return the installed version of ``pkg_name``, or None if not installed.-- Uses ``importlib.metadata`` so we don't depend on pip being importable inside the active venv- (uv-created venvs may lack pip).+ """Installed version of ``pkg_name`` via ``importlib.metadata`` (uv venvs may lack pip), or+ None if not installed or metadata is corrupt — never crash the CLI startup path."""from importlib.metadata import PackageNotFoundError, versiontry:@@ -119,8 +100,6 @@ def _installed_version(pkg_name: str) -> Optional[str]:except PackageNotFoundError:return Noneexcept Exception:- # Some metadata corruption modes raise ValueError or OSError. Don't- # let advisory checking crash the CLI startup path.logger.debug("importlib.metadata.version(%s) raised", pkg_name, exc_info=True)return None@@ -128,11 +107,7 @@ def _installed_version(pkg_name: str) -> Optional[str]:def detect_compromised(advisories: Iterable[Advisory] = ADVISORIES,) -> list[AdvisoryHit]:- """Scan installed packages and return all advisory hits.-- A hit means the package is installed AND its version is in the compromised set (or the set is- empty, meaning any version is suspect).- """+ """All hits: package installed AND version in the compromised set (or the set is empty)."""return [AdvisoryHit(advisory, pkg_name, installed)for advisory in advisories@@ -141,22 +116,14 @@ def detect_compromised(]-# =============================================================================-# Acknowledgement persistence-#-# Acks live under ``security.acked_advisories`` in config.yaml as a list of-# advisory IDs. The list is the only state — no per-host data, no-# timestamps, no fingerprints. Users sharing a config.yaml across machines-# (rare but possible) get the same dismissal everywhere, which is the-# correct behavior for a global advisory.-# =============================================================================+# ─── Acknowledgement persistence ──────────────────────────────────────────────+# Acks live under ``security.acked_advisories`` in config.yaml as a list of advisory IDs — the only+# state (no per-host data or timestamps), so a shared config.yaml dismisses everywhere.def get_acked_ids() -> set[str]:- """Return the set of advisory IDs the user has dismissed.-- Returns an empty set if config can't be loaded (don't block startup just because config is- broken — the advisory will keep firing until config is repaired, which is fine).+ """Advisory IDs the user has dismissed; empty when config can't be loaded (never block startup —+ the advisory keeps firing until config is repaired)."""try:from hermes_cli.config import load_config@@ -193,14 +160,12 @@ def ack_advisory(advisory_id: str) -> bool:def filter_unacked(hits: list[AdvisoryHit]) -> list[AdvisoryHit]:- """Return only hits whose advisories the user has not dismissed."""+ """Only hits whose advisories the user has not dismissed."""acked = get_acked_ids() if hits else set()return [h for h in hits if h.advisory.id not in acked]-# =============================================================================-# Rendering helpers-# =============================================================================+# ─── Rendering ────────────────────────────────────────────────────────────────def _term_supports_color() -> bool:@@ -208,11 +173,7 @@ def _term_supports_color() -> bool:def short_banner_lines(hits: list[AdvisoryHit]) -> list[str]:- """Return 1-3 short lines suitable for a startup banner.-- Caller is responsible for color/styling. Always names the worst hit explicitly so the user knows- what's wrong without running doctor.- """+ """1-3 short unstyled lines for a startup banner; always names the worst hit explicitly."""if not hits:return []primary = hits[0]@@ -228,7 +189,7 @@ def short_banner_lines(hits: list[AdvisoryHit]) -> list[str]:def full_remediation_text(hit: AdvisoryHit) -> list[str]:- """Return a multi-line block describing the advisory + remediation."""+ """Multi-line block describing the advisory + remediation."""a = hit.advisoryreturn [f"=== {a.title} ===",@@ -243,17 +204,10 @@ def full_remediation_text(hit: AdvisoryHit) -> list[str]:]-# =============================================================================-# Startup-banner gating-#-# We do NOT want to hammer the user with the banner on every command. Once-# they've seen it inside a 24h window we cache that fact in-# ``~/.hermes/cache/advisory_banner_seen`` (a single line per advisory ID:-# ``<id> <iso8601_timestamp>``).-#-# Acked advisories never re-banner. Cached-but-not-acked advisories-# re-banner after 24h so the user doesn't fully forget.-# =============================================================================+# ─── Startup-banner gating ────────────────────────────────────────────────────+# Once the banner is seen we cache that in ``~/.hermes/cache/advisory_banner_seen`` (one+# ``<id> <timestamp>`` line per advisory). Acked advisories never re-banner; cached-but-not-acked+# ones re-banner after 24h so the user doesn't fully forget._BANNER_CACHE_FILE = "advisory_banner_seen"@@ -303,10 +257,8 @@ def hits_due_for_banner(*,repeat_hours: int = _BANNER_REPEAT_HOURS,) -> list[AdvisoryHit]:- """Return only hits whose banner is due (not acked, not recently shown).-- Side effect: stamps the banner cache for any hit that's about to be shown. Callers should- subsequently render the result.+ """Hits whose banner is due (not acked, not recently shown). Side effect: stamps the banner+ cache for every returned hit, so callers must render the result."""import time@@ -325,17 +277,11 @@ def hits_due_for_banner(return due-# =============================================================================-# Public entry points used by doctor / CLI / gateway-# =============================================================================+# ─── Public entry points used by doctor / CLI / gateway ───────────────────────def startup_banner(hits: list[AdvisoryHit]) -> Optional[str]:- """Return a printable startup banner, or None if nothing is due.-- Updates the banner cache as a side effect (so the next call within 24h returns None for the same- hit).- """+ """Printable startup banner, or None if nothing is due (updates the banner cache)."""due = hits_due_for_banner(hits)if not due:return None@@ -344,7 +290,7 @@ def startup_banner(hits: list[AdvisoryHit]) -> Optional[str]:def gateway_log_message(hits: list[AdvisoryHit]) -> Optional[str]:- """Return a one-line log message for gateway operators, or None."""+ """One-line log message for gateway operators, or None."""fresh = filter_unacked(hits)if not fresh:return Nonediff --git a/hermes_cli/security_audit.py b/hermes_cli/security_audit.pyindex ebc5ac769fb..c7b7671c99b 100644--- a/hermes_cli/security_audit.py+++ b/hermes_cli/security_audit.py@@ -1,8 +1,7 @@"""On-demand supply-chain audit for Hermes Agent installs.Vulnerabilities are looked up against OSV.dev (``api.osv.dev/v1/querybatch`` + ``/v1/vulns/{id}``).-Single-shot, on-demand, never daily — see the design notes in ``references/security-disclosure--triage.md``.+Single-shot, on-demand, never daily — see ``references/security-disclosure-triage.md``."""from __future__ import annotations@@ -26,20 +25,8 @@ OSV_BATCH_MAX = 1000 # OSV documented hard cap per requestHTTP_TIMEOUT = 20DETAIL_PARALLELISM = 8-# Severity ordering for --fail-on gating. UNKNOWN sits below LOW so it-# never blocks unless --fail-on is passed something even lower (we don't-# expose that).-SEVERITY_ORDER = {- "UNKNOWN": 0,- "LOW": 1,- "MODERATE": 2,- "MEDIUM": 2,- "HIGH": 3,- "CRITICAL": 4,-}---# ─── Data shapes ──────────────────────────────────────────────────────────────+# Severity ordering for --fail-on gating. UNKNOWN sits below LOW so it never blocks.+SEVERITY_ORDER = {"UNKNOWN": 0, "LOW": 1, "MODERATE": 2, "MEDIUM": 2, "HIGH": 3, "CRITICAL": 4}@dataclass(frozen=True)@@ -107,10 +94,8 @@ def _match_pins(specs: Iterable[str]) -> list[tuple[str, str]]:def _parse_requirements(text: str) -> list[tuple[str, str]]:- """Extract ``name==version`` pins. Everything else (>=, ~=, no pin) is skipped.-- A loose pin can't be mapped to a single OSV query, and getting it wrong is worse than missing a- finding for an audit tool — false positives train users to ignore output.+ """Extract ``name==version`` pins. Loose specs (>=, ~=, no pin) are skipped: they can't map to+ a single OSV query, and false positives train users to ignore an audit tool's output."""lines = (raw.strip() for raw in text.splitlines())return _match_pins(line for line in lines if line and not line.startswith(("#", "-")))@@ -120,9 +105,6 @@ def _parse_pyproject_pins(text: str) -> list[tuple[str, str]]:"""Pull ``name==version`` pins from a ``pyproject.toml`` ``dependencies`` list."""try:import tomllib- except ImportError: # pragma: no cover - 3.10 only- return []- try:data = tomllib.loads(text)except Exception:return []@@ -140,10 +122,8 @@ _PLUGIN_PIN_FILES = (def _discover_plugins(hermes_home: Path) -> list[Component]:- """Python deps declared by plugins under ``~/.hermes/plugins``.-- Plugins typically don't install into the venv (they're directory-based with relative imports),- so their stated requirements are useful audit surface even when the venv scan misses them.+ """Python deps declared by plugins under ``~/.hermes/plugins``. Plugins typically don't install+ into the venv, so their stated requirements are audit surface the venv scan misses."""plugins_dir = hermes_home / "plugins"if not plugins_dir.is_dir():@@ -163,26 +143,17 @@ def _discover_plugins(hermes_home: Path) -> list[Component]:return out-# npx forms we recognise:-# npx -y @scope/[email protected]-# npx --yes [email protected]-# npx [email protected] [...args]-# We deliberately don't try to resolve unversioned names — that maps to-# "latest" at runtime and isn't a stable audit subject.+# Recognised pinned refs: ``npx [-y|--yes] [@scope/][email protected]`` and ``uvx [--with] pkg==1.2.3``.+# Unversioned names map to "latest" at runtime and aren't a stable audit subject._NPX_PKG = re.compile(r"^(@[A-Za-z0-9._-]+/[A-Za-z0-9._-]+|[A-Za-z0-9._-]+)@([A-Za-z0-9._+-]+)$")-# uvx forms:-# uvx pkg==1.2.3-# uvx --with pkg==1.2.3 entrypoint_UVX_PKG = re.compile(r"^([A-Za-z0-9][A-Za-z0-9._-]*)==([A-Za-z0-9._+!-]+)$")# launcher basename -> (package-ref regex, OSV ecosystem)_MCP_LAUNCHERS = {"npx": (_NPX_PKG, "npm"), "uvx": (_UVX_PKG, "PyPI")}def _extract_mcp_component(server_name: str, command: str, args: list[str]) -> Optional[Component]:- """Best-effort: parse `command/args` into a (name, version, ecosystem).-- Returns None when the entry doesn't pin an auditable version (local paths, Docker images,- unversioned npx, ...); the audit stays silent rather than guess.+ """Parse `command/args` into a Component, or None when the entry doesn't pin an auditable+ version (local paths, Docker images, unversioned npx, ...) — stay silent rather than guess."""cmd = (command or "").strip().lower()launcher = next((k for k in _MCP_LAUNCHERS if cmd.endswith(k)), None) # any prefix path@@ -253,11 +224,11 @@ def _osv_query_batch(components: list[Component]) -> dict[Component, list[str]]:def _osv_severity_from_record(record: dict) -> str:- """Extract CVSS-derived severity tier from an OSV vuln record."""- # OSV puts CVSS in `severity` (top-level or per-affected) and a- # human-readable bucket in `database_specific.severity` for GHSAs.- # Top-level `severity` holds CVSS vector strings we can't tier without a lib; fall back to- # the per-affected ecosystem_specific bucket after the GHSA database_specific one.+ """CVSS-derived severity tier from an OSV vuln record.++ Top-level ``severity`` holds CVSS vector strings we can't tier without a lib, so use the GHSA+ ``database_specific`` bucket first, then the per-affected ``ecosystem_specific`` one.+ """candidates = [(record.get("database_specific") or {}).get("severity")] + [(entry.get("ecosystem_specific") or {}).get("severity") for entry in record.get("affected") or []]@@ -330,10 +301,8 @@ def run_audit(hermes_home: Optional[Path] = None,components: Optional[list[Component]] = None,) -> list[Finding]:- """Query OSV for the given (or freshly discovered) components.-- ``components`` lets callers that already ran discovery (e.g. for a count) reuse it instead- of scanning the venv/plugins/MCP config a second time.+ """Query OSV for the given (or freshly discovered) components; ``components`` lets callers+ that already ran discovery reuse it instead of scanning a second time."""if components is None:components = _discover_components(@@ -401,15 +370,9 @@ def _render_json(findings: list[Finding], total_components: int) -> str:return json.dumps(payload, indent=2)-# ─── CLI entrypoint ───────────────────────────────────────────────────────────--def cmd_security_audit(args: argparse.Namespace) -> int:"""Implementation of `hermes security audit`."""home = Path(get_hermes_home())- skip_venv = bool(getattr(args, "skip_venv", False))- skip_plugins = bool(getattr(args, "skip_plugins", False))- skip_mcp = bool(getattr(args, "skip_mcp", False))output_json = bool(getattr(args, "json", False))fail_on = (getattr(args, "fail_on", None) or "critical").upper()if fail_on not in SEVERITY_ORDER:@@ -421,7 +384,10 @@ def cmd_security_audit(args: argparse.Namespace) -> int:return 2components = _discover_components(- skip_venv=skip_venv, skip_plugins=skip_plugins, skip_mcp=skip_mcp, hermes_home=home+ skip_venv=bool(getattr(args, "skip_venv", False)),+ skip_plugins=bool(getattr(args, "skip_plugins", False)),+ skip_mcp=bool(getattr(args, "skip_mcp", False)),+ hermes_home=home,)total = len(components)if total == 0:diff --git a/hermes_cli/security_audit_startup.py b/hermes_cli/security_audit_startup.pyindex 059e6f89361..c55df33fdc3 100644--- a/hermes_cli/security_audit_startup.py+++ b/hermes_cli/security_audit_startup.py@@ -1,11 +1,8 @@"""Startup security posture audit (warn-on-load, never blocks).-Surfaces dangerous host / deployment posture at process start so operators get an at-a-glance-"you're exposed" signal. These checks are advisory: they emit ``logger.warning`` records and return-human-readable strings; they never raise or block startup.--Checks (each is independent and fail-safe — any internal error is swallowed and simply yields no-finding):+Surfaces dangerous host / deployment posture at process start. Checks are advisory and+independently fail-safe: they return human-readable strings, any internal error yields no finding,+and nothing here ever raises or blocks startup."""from __future__ import annotations@@ -17,8 +14,7 @@ from typing import Optionallogger = logging.getLogger("hermes.security_audit")-# Sentinel so the audit only runs once per process even if both the CLI and-# gateway startup paths call it.+# The audit runs once per process even if both the CLI and gateway startup paths call it._AUDIT_RAN = False@@ -43,7 +39,7 @@ def _running_as_root() -> Optional[str]:def _iter_sshd_config_lines() -> list[str]:- """Yield non-comment lines from sshd_config + its drop-in directory."""+ """Non-comment lines from sshd_config + its drop-in directory."""lines: list[str] = []paths: list[Path] = [Path("/etc/ssh/sshd_config")]try:@@ -62,11 +58,8 @@ def _iter_sshd_config_lines() -> list[str]:def _ssh_password_auth_enabled() -> Optional[str]:- """Warn when an SSH daemon has password authentication enabled.-- Password auth on a public SSH daemon is the classic brute-force surface and pairs badly with a- root-capable agent box. POSIX-only; returns None when there's no sshd config to read (e.g.- Windows, or SSH not installed).+ """Warn when sshd has password auth enabled — the classic brute-force surface, which pairs+ badly with a root-capable agent box. None when there is no sshd config to read."""lines = _iter_sshd_config_lines()if not lines:@@ -101,11 +94,8 @@ def _in_container() -> bool:def _path_is_mounted(path: Path) -> bool:- """True if *path* sits on (or under) a real mount point per /proc/mounts.-- Container overlay/root filesystems are ephemeral; a bind/volume mount over the data dir- shows up as a distinct mount entry. The path counts as persisted when a mountpoint at or- above it is NOT the container root overlay.+ """True if *path* sits on a persistent mount per /proc/mounts, i.e. the most specific+ mountpoint at or above it is NOT the ephemeral container root overlay/tmpfs."""try:target = path.resolve()@@ -115,8 +105,7 @@ def _path_is_mounted(path: Path) -> bool:mounts = Path("/proc/mounts").read_text(encoding="utf-8", errors="replace").splitlines()except Exception:return True # can't tell — fail safe (no warning)- # (mountpoint, fstype) entries at or above target; the longest (most specific) wins,- # first one on ties.+ # (mountpoint, fstype) entries at or above target; the longest wins, first one on ties.covering = [(Path(parts[1]), parts[2])for parts in (line.split() for line in mounts)@@ -125,7 +114,6 @@ def _path_is_mounted(path: Path) -> bool:if not covering:return Truebest_fstype = max(covering, key=lambda entry: len(str(entry[0])))[1]- # overlay / tmpfs over the data dir = ephemeral container storage.return best_fstype not in ("overlay", "tmpfs", "aufs")@@ -147,14 +135,10 @@ def _container_no_volume_mount(hermes_home: Optional[Path]) -> Optional[str]:def _network_listener_without_auth(config: Optional[dict]) -> list[str]:- """Warn about network-accessible gateway listeners with no auth.-- Covers the API server (no API_SERVER_KEY) and the dashboard (non-loopback bind with no auth- provider). Read-only against config + env; overlaps the hard fail-closed guards but surfaces the- posture proactively at startup.+ """Warn about a network-accessible API server with no API_SERVER_KEY. Read-only against+ config + env; overlaps the hard fail-closed guards but surfaces the posture at startup."""- # Any error (incl. an unimportable gateway package) propagates to run_security_audit,- # which treats it as "no finding".+ # Any error (incl. an unimportable gateway package) propagates to run_security_audit.from gateway.platforms.base import is_network_accessibleplats = (config or {}).get("platforms") or {}@@ -177,10 +161,8 @@ def _network_listener_without_auth(config: Optional[dict]) -> list[str]:def run_security_audit(*, hermes_home: Optional[Path] = None, config: Optional[dict] = None) -> list[str]:- """Run all checks and return a list of human-readable warning strings.-- Pure: no logging, no side effects. Each check is independently fail-safe. Used directly by- tests; the logging wrapper is :func:`log_startup_security_warnings`.+ """Run all checks and return human-readable warning strings. Pure (no logging); a check that+ raises simply contributes no finding."""findings: list[str] = []for check in (@@ -206,11 +188,7 @@ def log_startup_security_warnings(config: Optional[dict] = None,force: bool = False,) -> list[str]:- """Run the audit once per process and emit each finding via logger.warning.-- Returns the findings (also for tests). Never raises. Idempotent unless ``force=True`` (used by- tests).- """+ """Run the audit once per process (``force=True`` re-runs) and log each finding as a warning."""global _AUDIT_RANif _AUDIT_RAN and not force:return []