Skip to content

The agent that grows with you

refactor(hermes_cli): g7 code compaction — unified pt_input_extras installer, dict/comprehension collapses in security audit + prompt_size

Tekniumcfde68763fe6
diff --git a/hermes_cli/prompt_size.py b/hermes_cli/prompt_size.py
index e44eab35a7c..ca0b5f13f8c 100644
--- a/hermes_cli/prompt_size.py
+++ b/hermes_cli/prompt_size.py
@@ -42,9 +42,7 @@ def _tool_name(tool: Any) -> str:
if not isinstance(tool, dict):
return ""
fn = tool.get("function")
- if isinstance(fn, dict) and fn.get("name"):
- return str(fn["name"])
- return str(tool.get("name", ""))
+ return str(fn["name"]) if isinstance(fn, dict) and fn.get("name") else str(tool.get("name", ""))
def _build_inspection_agent(platform: str) -> Any:
@@ -62,12 +60,8 @@ def _build_inspection_agent(platform: str) -> Any:
agent_cfg = cfg.get("agent") or {}
return AIAgent(
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=sorted(_get_platform_tools(cfg, platform)),
+ api_key="inspect-only", base_url="https://openrouter.ai/api/v1", quiet_mode=True, save_trajectories=False,
+ platform=platform, enabled_toolsets=sorted(_get_platform_tools(cfg, platform)),
disabled_toolsets=parse_config_string_list(agent_cfg.get("disabled_toolsets")) or None,
)
@@ -105,43 +99,31 @@ def _compute_skills_breakdown(skills_block: str) -> List[Dict[str, Any]]:
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, **index_fields: int) -> None: # kwarg order == output key order
path = name_to_path.get(name)
md_bytes: Optional[int] = None
- if path is not None:
- try:
- md_bytes = path.stat().st_size
- except OSError:
- pass
- entries.append({
- "name": name,
- "index_line_bytes": attributed_bytes,
- "index_line_total_bytes": total_bytes,
- "index_line_shared_bytes": shared_bytes,
- "index_line_skill_count": skill_count,
- "skill_md_bytes": md_bytes,
- "path": str(path) if path is not None else "",
- })
+ try:
+ md_bytes = path.stat().st_size if path is not None else None
+ except OSError:
+ pass
+ entries.append({"name": name, **index_fields, "skill_md_bytes": md_bytes, "path": str(path) if path is not None else ""})
for line in skills_block.splitlines():
line_bytes = _bytes(line)
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
name_bytes = [_bytes(name) for name in names]
- shared_base, shared_remainder = divmod(line_bytes - sum(name_bytes), len(names))
+ shared_base, shared_remainder = divmod(line_bytes - sum(name_bytes), len(names)) if names else (0, 0)
for index, name in enumerate(names):
- shared_bytes = shared_base + (1 if index < shared_remainder else 0)
- append_entry(
- name, attributed_bytes=name_bytes[index] + shared_bytes,
- total_bytes=line_bytes, shared_bytes=shared_bytes, skill_count=len(names),
- )
+ shared = shared_base + (1 if index < shared_remainder else 0)
+ append_entry(name, index_line_bytes=name_bytes[index] + shared, index_line_total_bytes=line_bytes,
+ index_line_shared_bytes=shared, index_line_skill_count=len(names))
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)
+ append_entry(name, index_line_bytes=line_bytes, index_line_total_bytes=line_bytes,
+ index_line_shared_bytes=0, index_line_skill_count=1)
entries.sort(key=lambda e: (-(e["skill_md_bytes"] or 0), e["name"]))
return entries
@@ -172,9 +154,7 @@ def compute_prompt_breakdown(platform: str = "cli") -> Dict[str, Any]:
agent = _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", "")
+ stable, context, volatile = (parts.get(k, "") for k in ("stable", "context", "volatile"))
# 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.
@@ -183,8 +163,7 @@ def compute_prompt_breakdown(platform: str = "cli") -> Dict[str, Any]:
# Memory + user profile are joined into ``volatile``; re-derive them from the store so the
# numbers stay attributable.
- memory_block = ""
- user_block = ""
+ memory_block = user_block = ""
store = getattr(agent, "_memory_store", None)
if store is not None:
try:
@@ -197,9 +176,9 @@ def compute_prompt_breakdown(platform: str = "cli") -> Dict[str, Any]:
tools = getattr(agent, "tools", None) or []
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)),
+ (label, len(text), _bytes(text))
+ for label, text in (("stable (identity/guidance/skills)", stable), ("context (AGENTS.md/cwd files)", context),
+ ("volatile (memory/profile/timestamp)", volatile))
]
return {
"platform": platform,
@@ -220,55 +199,39 @@ def render_breakdown(data: Dict[str, Any]) -> str:
sp = data["system_prompt"]
tools = data["tools"]
lines: List[str] = [
- f"Prompt-size breakdown (platform={data['platform']}, model={data['model'] or 'unset'})",
- "",
- f" System prompt total : {sp['bytes']:>8,} B ({_fmt_kb(sp['bytes'])}, {sp['chars']:,} chars)",
- "",
+ f"Prompt-size breakdown (platform={data['platform']}, model={data['model'] or 'unset'})", "",
+ f" System prompt total : {sp['bytes']:>8,} B ({_fmt_kb(sp['bytes'])}, {sp['chars']:,} chars)", "",
" Major blocks:",
]
- for label, key in (("skills index", "skills_index"), ("memory", "memory"),
- ("user profile", "user_profile")):
+ for label, key in (("skills index", "skills_index"), ("memory", "memory"), ("user profile", "user_profile")):
byts = data[key]["bytes"]
lines.append(f" {label:<19}: {byts:>8,} B ({_fmt_kb(byts)})")
- lines += ["", " Prompt tiers:"]
- for label, chars, byts in data["sections"]:
- lines.append(f" {label:<36}: {byts:>8,} B ({_fmt_kb(byts)})")
+ lines += ["", " Prompt tiers:"] + [f" {label:<36}: {byts:>8,} B ({_fmt_kb(byts)})" for label, _chars, byts in data["sections"]]
lines += ["", f" Tool schemas : {tools['json_bytes']:>8,} B ({_fmt_kb(tools['json_bytes'])}, {tools['count']} tools)"]
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:
- lines.append(
- f" {ts['toolset']:<22} {ts['tool_count']:>5} "
- f"{ts['json_bytes']:>8,} B ({_fmt_kb(ts['json_bytes'])})"
- )
+ lines += ["", " Toolsets by size (tool-schema JSON, largest first):", f" {'toolset':<22} {'tools':>5} {'schema':>10}"]
+ lines += [f" {ts['toolset']:<22} {ts['tool_count']:>5} {ts['json_bytes']:>8,} B ({_fmt_kb(ts['json_bytes'])})" for ts in toolsets]
# Per-skill cost — index line (always shipped) vs SKILL.md (read on load).
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):",
+ lines += ["", " Skills by size (SKILL.md on-disk = read cost; index cost = attributed always-on bytes, largest first):",
f" {'skill':<28} {'SKILL.md':>10} {'index cost':>10}"]
shown = skills[:_SKILLS_TABLE_LIMIT]
for sk in shown:
md = sk["skill_md_bytes"]
md_str = f"{md:>8,} B" if md is not None else f"{'n/a':>10}"
- name = sk["name"]
- if len(name) > 28:
- name = name[:27] + "…"
+ name = sk["name"] if len(sk["name"]) <= 28 else sk["name"][:27] + "…"
lines.append(f" {name:<28} {md_str} {sk['index_line_bytes']:>8,} B")
- remaining = len(skills) - len(shown)
- if remaining > 0:
+ if (remaining := len(skills) - len(shown)) > 0:
lines.append(f" … and {remaining} more (use --json for the full list)")
return "\n".join(lines)
def cmd_prompt_size(args: Any) -> None:
"""Entry point for ``hermes prompt-size``."""
- platform = getattr(args, "platform", "cli") or "cli"
try:
- data = compute_prompt_breakdown(platform)
+ data = compute_prompt_breakdown(getattr(args, "platform", "cli") or "cli")
except Exception as e:
print(f"Could not compute prompt-size breakdown: {e}")
return
diff --git a/hermes_cli/prompt_stash.py b/hermes_cli/prompt_stash.py
index 6afc7791667..e56affcc7b0 100644
--- a/hermes_cli/prompt_stash.py
+++ b/hermes_cli/prompt_stash.py
@@ -41,12 +41,7 @@ class StashEntry:
def as_dict(self) -> dict:
"""Shape ``HermesCLI._render_stash_panel`` consumes."""
- return {
- "text": self.text,
- "images": list(self.images),
- "stashed_at": self.stashed_at,
- "preview": self.preview,
- }
+ return {"text": self.text, "images": list(self.images), "stashed_at": self.stashed_at, "preview": self.preview}
class PromptStash:
@@ -78,11 +73,9 @@ class PromptStash:
def placeholder_hint(self) -> str:
"""Composer placeholder text advertising the stashed draft."""
n = len(self._items)
- if not n:
- return ""
if n == 1:
return f"Ctrl+S to restore: {self._items[0].preview}"
- return f"Ctrl+S to browse {n} stashed drafts"
+ return f"Ctrl+S to browse {n} stashed drafts" if n else ""
def stash(self, text: str, images: Optional[Sequence[Any]] = None) -> bool:
"""Push a draft. A blank buffer with no images is a no-op (returns False) so Ctrl+S on an
@@ -91,12 +84,8 @@ class PromptStash:
if not (text or "").strip() and not images:
return False
- entry = StashEntry(
- text=text or "",
- images=list(images or []),
- stashed_at=self._clock(),
- preview=build_preview(text or "") or "(images only)",
- )
+ entry = StashEntry(text=text or "", images=list(images or []), stashed_at=self._clock(),
+ preview=build_preview(text or "") or "(images only)")
self._items.insert(0, entry)
del self._items[self._max_items:] # drop the oldest past the cap
self.close_panel() # a push invalidates any open browse session
@@ -122,9 +111,7 @@ class PromptStash:
# ------------------------------------------------------------ panel state
def _clamp_cursor(self, value: int) -> int:
- if not self._items:
- return 0
- return max(0, min(int(value), len(self._items) - 1))
+ return max(0, min(int(value), len(self._items) - 1)) if self._items else 0
def open_panel(self) -> bool:
"""Open the browse panel. False when there is nothing to browse."""
@@ -173,9 +160,7 @@ ACTION_CLOSE_PANEL = "close_panel"
def resolve_ctrl_s(
- stash: PromptStash,
- buffer_text: str,
- images: Optional[Sequence[Any]] = None,
+ stash: PromptStash, 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)`` where ``payload`` is
``(text, images)`` for :data:`ACTION_RESTORED`, else None.
diff --git a/hermes_cli/pt_input_extras.py b/hermes_cli/pt_input_extras.py
index 9737b1cbb02..120e28fa1b0 100644
--- a/hermes_cli/pt_input_extras.py
+++ b/hermes_cli/pt_input_extras.py
@@ -16,7 +16,7 @@ def _lock_variants(modifier: int) -> tuple[int, ...]:
def _lock_twins(modifier: int) -> tuple[int, ...]:
"""Only the lock twins of ``modifier`` (never the base value)."""
- return tuple(modifier + off for off in _LOCK_BIT_OFFSETS[1:])
+ return _lock_variants(modifier)[1:]
def _clear_vt100_prefix_cache() -> None:
@@ -32,26 +32,22 @@ def _clear_vt100_prefix_cache() -> None:
pass
-def _pt_tables():
- """``(ANSI_SEQUENCES, Keys)`` or ``None`` when prompt_toolkit is unavailable."""
- try:
- from prompt_toolkit.input.ansi_escape_sequences import ANSI_SEQUENCES
- from prompt_toolkit.keys import Keys
- except Exception:
- return None
- return ANSI_SEQUENCES, Keys
-
-
-def _register(table: dict, aliases: dict, *, overwrite: bool) -> int:
- """Install ``aliases`` into ``table``; return the number of entries changed.
+def _install(build, *, overwrite: bool) -> int:
+ """Install ``build(ANSI_SEQUENCES, Keys) -> {seq: key}`` into prompt_toolkit's table; return
+ the number of entries changed (0 when prompt_toolkit is unavailable).
``overwrite=True`` replaces differing entries; ``overwrite=False`` behaves like ``setdefault``
so existing/user registrations win. Clears the VT100 prefix cache when anything changed.
"""
+ try:
+ from prompt_toolkit.input.ansi_escape_sequences import ANSI_SEQUENCES
+ from prompt_toolkit.keys import Keys
+ except Exception:
+ return 0
changed = 0
- for seq, key in aliases.items():
- if (table.get(seq) != key) if overwrite else (seq not in table):
- table[seq] = key
+ for seq, key in build(ANSI_SEQUENCES, Keys).items():
+ if (ANSI_SEQUENCES.get(seq) != key) if overwrite else (seq not in ANSI_SEQUENCES):
+ ANSI_SEQUENCES[seq] = key
changed += 1
if changed:
_clear_vt100_prefix_cache()
@@ -75,13 +71,8 @@ def install_keypress_data_normalization() -> int:
def _patched_call_handler(self, key, insert_text):
# 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
- and not isinstance(key, _PtKeys)
- and isinstance(insert_text, str)
- and insert_text.startswith("\x1b")
- ):
+ if (isinstance(key, str) and len(key) == 1 and not isinstance(key, _PtKeys)
+ and isinstance(insert_text, str) and insert_text.startswith("\x1b")):
insert_text = key
return _orig_call_handler(self, key, insert_text)
@@ -97,15 +88,12 @@ def _install_enter_alias(modifier: int) -> int:
Stock prompt_toolkit maps the tilde form to plain ControlM (i.e. Shift+Enter == Enter, the very
bug this fixes), so these keys are overwritten unconditionally.
"""
- tables = _pt_tables()
- if tables is None:
- return 0
- seqs, keys = tables
- alt_enter = (keys.Escape, keys.ControlM)
- aliases = {f"\x1b[13;{m}u": alt_enter for m in _lock_variants(modifier)}
- aliases[f"\x1b[27;{modifier};13~"] = alt_enter
- aliases[f"\x1b[27;{modifier};13u"] = alt_enter
- return _register(seqs, aliases, overwrite=True)
+ def build(_seqs, keys):
+ alt_enter = (keys.Escape, keys.ControlM)
+ seqs = [f"\x1b[13;{m}u" for m in _lock_variants(modifier)] + [f"\x1b[27;{modifier};13~", f"\x1b[27;{modifier};13u"]
+ return dict.fromkeys(seqs, alt_enter)
+
+ return _install(build, overwrite=True)
def install_shift_enter_alias() -> int:
@@ -126,17 +114,14 @@ def install_cmd_backspace_alias() -> int:
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:
- return 0
- seqs, keys = tables
- aliases: dict[str, object] = {}
- for base in (9, 10): # super / super+shift
- for mod in _lock_variants(base):
- aliases[f"\x1b[127;{mod}u"] = keys.ControlU
- aliases[f"\x1b[3;{mod}~"] = keys.ControlK
- aliases["\x1b[27;9;127~"] = keys.ControlU
- return _register(seqs, aliases, overwrite=True)
+ def build(_seqs, keys):
+ mods = [mod for base in (9, 10) for mod in _lock_variants(base)] # super / super+shift
+ aliases = {f"\x1b[127;{mod}u": keys.ControlU for mod in mods}
+ aliases.update({f"\x1b[3;{mod}~": keys.ControlK for mod in mods})
+ aliases["\x1b[27;9;127~"] = keys.ControlU
+ return aliases
+
+ return _install(build, overwrite=True)
# Kitty functional keys (Private Use Area codepoints) that have prompt_toolkit equivalents.
@@ -170,11 +155,10 @@ def install_modify_other_keys_aliases() -> int:
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 0
- ANSI_SEQUENCES, Keys = tables
+ return _install(_modify_other_keys_aliases, overwrite=False)
+
+def _modify_other_keys_aliases(ANSI_SEQUENCES: dict, Keys) -> dict[str, object]:
# Collected first-writer-wins (matching setdefault order), installed once at the end.
aliases: dict[str, object] = {}
_put = aliases.setdefault
@@ -191,14 +175,12 @@ def install_modify_other_keys_aliases() -> int:
# 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
+ ctrl_key_map: dict[int, object] = {
+ cp: key for cp in (*letters, 64, 91, 92, 93, 94, 95, 32)
+ if (key := ANSI_SEQUENCES.get(chr(cp & 0x1F))) is not None
+ }
# 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}")
+ ctrl_key_map.update({ord('0') + d: getattr(Keys, f"Control{d}") for d in range(10)})
_install_paired(5, ctrl_key_map)
# Letter combos. Alt+a -> (Escape, 'a') like bare Alt. Shift+a -> 'A' (safe on every Latin
@@ -206,75 +188,51 @@ def install_modify_other_keys_aliases() -> int:
# 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] = {}
- ctrl_shift_map: dict[int, object] = {}
- ctrl_alt_map: dict[int, tuple] = {}
for ch in letters:
upper_char = chr(ch - 32)
- alt_map[ch] = (Keys.Escape, chr(ch))
- alt_map[ch - 32] = (Keys.Escape, upper_char)
ctrl_key = ctrl_key_map.get(ch)
+ _install_paired(3, {ch: (Keys.Escape, chr(ch)), ch - 32: (Keys.Escape, upper_char)})
for cp in (ch, ch - 32):
- shift_map[cp] = upper_char
- shift_alt_map[cp] = (Keys.Escape, upper_char)
+ _install_paired(2, {cp: upper_char})
+ _install_paired(4, {cp: (Keys.Escape, upper_char)})
if ctrl_key is not None:
- ctrl_shift_map[cp] = ctrl_key
- ctrl_alt_map[cp] = (Keys.Escape, ctrl_key)
- 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)
+ _install_paired(6, {cp: ctrl_key})
+ for modifier in (7, 8): # Ctrl+Alt and Ctrl+Alt+Shift — same normalization
+ _install_paired(modifier, {cp: (Keys.Escape, ctrl_key)})
# 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)
+ for mod in (mod 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/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)
+ _install_paired(2, {9: Keys.BackTab, 127: Keys.ControlH, 32: " "})
+ _install_paired(3, {13: (Keys.Escape, Keys.ControlM), 127: alt_backspace, 32: (Keys.Escape, " ")})
+ _install_paired(5, {9: Keys.ControlI, 127: alt_backspace}) # Ctrl+Tab degrades to Tab
+ _install_paired(1, {9: Keys.ControlI, 13: Keys.ControlM, 32: " ", 127: Keys.ControlH})
# 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):
- for trailer in "ABCDFHPQRS": # Up/Down/Right/Left/End/Home + F1-F4
- base_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:
- key = ANSI_SEQUENCES.get(f"\x1bO{trailer}") # plain F1-F4 live as SS3 forms
- if key is None:
- continue
- for mod in _lock_twins(m):
- _put(f"\x1b[1;{mod}{trailer}", key)
- for num in range(1, 9): # Insert/Delete/PageUp/PageDown/Home/End
- base_seq = f"\x1b[{num};{m}~" if m > 1 else f"\x1b[{num}~"
+ legacy = [(f"\x1b[1;{m}{t}" if m > 1 else f"\x1b[{t}", f"\x1b[1;{{mod}}{t}", f"\x1bO{t}") for t in "ABCDFHPQRS"]
+ legacy += [(f"\x1b[{n};{m}~" if m > 1 else f"\x1b[{n}~", f"\x1b[{n};{{mod}}~", None) for n in range(1, 9)]
+ for base_seq, twin_fmt, ss3_seq in legacy: # CSI-letter nav/F1-F4, then CSI-tilde nav keys
key = ANSI_SEQUENCES.get(base_seq)
- if key is None:
- continue
- for mod in _lock_twins(m):
- _put(f"\x1b[{num};{mod}~", key)
+ if key is None and m == 1 and ss3_seq:
+ key = ANSI_SEQUENCES.get(ss3_seq) # plain F1-F4 live as SS3 forms
+ for mod in _lock_twins(m) if key is not None else ():
+ _put(twin_fmt.format(mod=mod), key)
for code, key_val in _kitty_functional_map(Keys).items():
_put(f"\x1b[{code}u", key_val)
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)
+ return aliases
def install_ignored_terminal_sequences() -> int:
@@ -283,8 +241,4 @@ def install_ignored_terminal_sequences() -> int:
Parser-level handling beats post-hoc regex stripping because the bytes never reach the buffer.
``setdefault`` lets user/downstream registrations win.
"""
- tables = _pt_tables()
- if tables is None:
- return 0
- seqs, keys = tables
- return _register(seqs, {"\x1b[I": keys.Ignore, "\x1b[O": keys.Ignore}, overwrite=False)
+ return _install(lambda _seqs, keys: {"\x1b[I": keys.Ignore, "\x1b[O": keys.Ignore}, overwrite=False)
diff --git a/hermes_cli/pty_bridge.py b/hermes_cli/pty_bridge.py
index 53afad7a8b5..c681d729b26 100644
--- a/hermes_cli/pty_bridge.py
+++ b/hermes_cli/pty_bridge.py
@@ -72,40 +72,23 @@ class PtyBridge:
@classmethod
def spawn(
- cls,
- argv: Sequence[str],
- *,
- cwd: Optional[str] = None,
- env: Optional[dict] = None,
- cols: int = 80,
- rows: int = 24,
+ cls, argv: Sequence[str], *, cwd: Optional[str] = None, env: Optional[dict] = None, cols: int = 80, rows: int = 24
) -> "PtyBridge":
"""Spawn ``argv`` behind a new PTY and return a bridge."""
if not _PTY_AVAILABLE:
if sys.platform.startswith("win"):
- raise PtyUnavailableError(
- "Pseudo-terminals are unavailable on this platform. "
- "Hermes Agent supports Windows only via WSL."
- )
- if ptyprocess is None:
- raise PtyUnavailableError(
- "The `ptyprocess` package is missing. "
- "Install with: pip install ptyprocess (or pip install -e '.[pty]')."
- )
- raise PtyUnavailableError("Pseudo-terminals are unavailable.")
+ raise PtyUnavailableError("Pseudo-terminals are unavailable on this platform. "
+ "Hermes Agent supports Windows only via WSL.")
+ raise PtyUnavailableError("The `ptyprocess` package is missing. " # only other way _PTY_AVAILABLE is False
+ "Install with: pip install ptyprocess (or pip install -e '.[pty]').")
# 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_env
- spawn_env = (
- build_subprocess_env(scrub_secrets=False, inherit_profile_home=False)
- if env is None else env.copy()
- )
+ spawn_env = build_subprocess_env(scrub_secrets=False, inherit_profile_home=False) if env is None else env.copy()
if not spawn_env.get("TERM"):
spawn_env["TERM"] = "xterm-256color"
- proc = ptyprocess.PtyProcess.spawn( # type: ignore[union-attr]
- list(argv), cwd=cwd, env=spawn_env, dimensions=(rows, cols)
- )
+ proc = ptyprocess.PtyProcess.spawn(list(argv), cwd=cwd, env=spawn_env, dimensions=(rows, cols)) # type: ignore[union-attr]
return cls(proc)
@property
@@ -113,10 +96,8 @@ class PtyBridge:
return int(self._proc.pid)
def is_alive(self) -> bool:
- if self._closed:
- return False
try:
- return bool(self._proc.isalive())
+ return not self._closed and bool(self._proc.isalive())
except Exception:
return False
@@ -169,9 +150,7 @@ class PtyBridge:
if self._closed:
return
# struct winsize: rows, cols, xpixel, ypixel (all unsigned short)
- winsize = struct.pack(
- "HHHH", _clamp_dimension(rows, _MAX_ROWS), _clamp_dimension(cols, _MAX_COLS), 0, 0
- )
+ winsize = struct.pack("HHHH", _clamp_dimension(rows, _MAX_ROWS), _clamp_dimension(cols, _MAX_COLS), 0, 0)
try:
fcntl.ioctl(self._fd, termios.TIOCSWINSZ, winsize)
except OSError:
diff --git a/hermes_cli/pty_session.py b/hermes_cli/pty_session.py
index 74e480cf18e..4c2a606d07b 100644
--- a/hermes_cli/pty_session.py
+++ b/hermes_cli/pty_session.py
@@ -21,28 +21,23 @@ class RingBuffer:
def __init__(self, capacity: int) -> None:
self._cap = capacity
self._buf = bytearray()
- self._truncated = False
+ self.truncated = False
def append(self, data: bytes) -> None:
self._buf.extend(data)
overflow = len(self._buf) - self._cap
if overflow > 0:
del self._buf[:overflow]
- self._truncated = True
+ self.truncated = True
def snapshot(self) -> bytes:
return bytes(self._buf)
- @property
- def truncated(self) -> bool:
- return self._truncated
-
async def _close_ws(ws, code: int) -> None:
- if ws is None:
- return
try:
- await ws.close(code=code)
+ if ws is not None:
+ await ws.close(code=code)
except Exception:
pass
@@ -74,12 +69,11 @@ class PtySession:
await asyncio.sleep(0)
continue
self.buffer.append(chunk)
- ws = self._ws
- if ws is not None:
- try:
- await ws.send_bytes(chunk)
- except Exception:
- pass # detached mid-send; keep buffering
+ try:
+ if self._ws is not None:
+ await self._ws.send_bytes(chunk)
+ except Exception:
+ pass # detached mid-send; keep buffering
async def attach(self, ws, *, force_redraw: bool = False) -> None:
"""Attach a browser terminal and replay buffered PTY output.
@@ -92,8 +86,7 @@ class PtySession:
self._ws = ws
self.attached = True
self.last_detached_at = None
- snap = self.buffer.snapshot()
- if snap:
+ if snap := self.buffer.snapshot():
await ws.send_bytes(snap)
if force_redraw:
self.bridge.write(TUI_FORCE_REDRAW)
@@ -137,16 +130,14 @@ async def run_reaper(registry: "PtySessionRegistry", *, interval: float = 60.0)
class PtySessionRegistry:
- def __init__(self, *, ttl: float, max_sessions: int,
- buffer_cap: int, read_timeout: float) -> None:
+ def __init__(self, *, ttl: float, max_sessions: int, buffer_cap: int, read_timeout: float) -> None:
self._ttl = ttl
self._max = max_sessions
self._buffer_cap = buffer_cap
self._read_timeout = read_timeout
self._sessions: Dict[str, PtySession] = {}
- async def attach_or_spawn(self, key: str, *, spawn: Callable[[], object]
- ) -> Tuple[PtySession, bool]:
+ async def attach_or_spawn(self, key: str, *, spawn: Callable[[], object]) -> Tuple[PtySession, bool]:
await self.reap_idle()
existing = self._sessions.get(key)
if existing is not None and existing.alive:
@@ -158,8 +149,7 @@ class PtySessionRegistry:
self._reap_one_idle_or_raise()
# 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)
+ session = PtySession(key, bridge, buffer_cap=self._buffer_cap, read_timeout=self._read_timeout)
await session.start()
self._sessions[key] = session
return session, True
@@ -173,16 +163,13 @@ class PtySessionRegistry:
now = time.monotonic() if now is None else now
doomed = [
key for key, s in self._sessions.items()
- if (not s.alive)
- or (not s.attached and s.last_detached_at is not None
- and (now - s.last_detached_at) > self._ttl)
+ if not s.alive or (not s.attached and s.last_detached_at is not None and (now - s.last_detached_at) > self._ttl)
]
for key in doomed:
await self._sessions.pop(key).close()
def _reap_one_idle_or_raise(self) -> None:
- idle = [s for s in self._sessions.values()
- if not s.attached and s.last_detached_at is not None]
+ idle = [s for s in self._sessions.values() if not s.attached and s.last_detached_at is not None]
if not idle:
raise RegistryFull()
oldest = min(idle, key=lambda s: s.last_detached_at or 0.0)
diff --git a/hermes_cli/security_advisories.py b/hermes_cli/security_advisories.py
index 49717752048..1d807e99a43 100644
--- a/hermes_cli/security_advisories.py
+++ b/hermes_cli/security_advisories.py
@@ -25,9 +25,7 @@ logger = logging.getLogger(__name__)
@dataclass(frozen=True)
class Advisory:
- """One security advisory entry.
-
- ``id`` is lowercase-hyphen, stable and never reused (it is what acks key on). ``remediation``
+ """``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.
"""
@@ -58,9 +56,7 @@ ADVISORIES: tuple[Advisory, ...] = (
"the compromised 2.4.6 is still installed."
),
url="https://socket.dev/blog/mini-shai-hulud-worm-pypi",
- compromised=(
- ("mistralai", frozenset({"2.4.6"})),
- ),
+ compromised=(("mistralai", frozenset({"2.4.6"})),),
remediation=(
"Run: pip uninstall -y mistralai (or: uv pip uninstall mistralai)",
"Rotate API keys in ~/.hermes/.env (OpenRouter, Anthropic, OpenAI, "
@@ -78,9 +74,6 @@ ADVISORIES: tuple[Advisory, ...] = (
)
-# ─── Detection ────────────────────────────────────────────────────────────────
-
-
@dataclass(frozen=True)
class AdvisoryHit:
"""One package-version match against an advisory."""
@@ -104,9 +97,7 @@ def _installed_version(pkg_name: str) -> Optional[str]:
return None
-def detect_compromised(
- advisories: Iterable[Advisory] = ADVISORIES,
-) -> list[AdvisoryHit]:
+def detect_compromised(advisories: Iterable[Advisory] = ADVISORIES) -> list[AdvisoryHit]:
"""All hits: package installed AND version in the compromised set (or the set is empty)."""
return [
AdvisoryHit(advisory, pkg_name, installed)
@@ -120,18 +111,16 @@ def detect_compromised(
# 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]:
"""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
- cfg = load_config()
+ raw = (load_config().get("security") or {}).get("acked_advisories") or []
except Exception:
logger.debug("Could not load config for advisory acks", exc_info=True)
return set()
- raw = (cfg.get("security") or {}).get("acked_advisories") or []
return {str(x).strip() for x in raw if str(x).strip()} if isinstance(raw, list) else set()
@@ -149,7 +138,8 @@ def ack_advisory(advisory_id: str) -> bool:
cfg = load_config()
sec = cfg.setdefault("security", {})
existing = sec.get("acked_advisories") or []
- existing = existing if isinstance(existing, list) else []
+ if not isinstance(existing, list):
+ existing = []
if advisory_id not in existing:
sec["acked_advisories"] = existing + [advisory_id]
save_config(cfg)
@@ -165,9 +155,6 @@ def filter_unacked(hits: list[AdvisoryHit]) -> list[AdvisoryHit]:
return [h for h in hits if h.advisory.id not in acked]
-# ─── Rendering ────────────────────────────────────────────────────────────────
-
-
def _term_supports_color() -> bool:
return not os.environ.get("NO_COLOR") and sys.stdout.isatty()
@@ -183,8 +170,7 @@ def short_banner_lines(hits: list[AdvisoryHit]) -> list[str]:
" Run 'hermes doctor' for remediation steps.",
]
if len(hits) > 1:
- lines.insert(1, f" ({len(hits) - 1} additional advisor"
- f"{'ies' if len(hits) > 2 else 'y'} also active.)")
+ lines.insert(1, f" ({len(hits) - 1} additional advisor{'ies' if len(hits) > 2 else 'y'} also active.)")
return lines
@@ -209,7 +195,6 @@ def full_remediation_text(hit: AdvisoryHit) -> list[str]:
# ``<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"
_BANNER_REPEAT_HOURS = 24
@@ -226,37 +211,29 @@ def _banner_cache_path() -> Optional[Path]:
def _read_banner_cache() -> dict[str, float]:
p = _banner_cache_path()
- if p is None or not p.exists():
- return {}
- out: dict[str, float] = {}
try:
- for line in p.read_text(encoding="utf-8").splitlines():
- parts = line.split(None, 1)
- try:
- if len(parts) == 2:
- out[parts[0]] = float(parts[1])
- except ValueError:
- continue
+ lines = p.read_text(encoding="utf-8").splitlines() if p is not None and p.exists() else []
except Exception:
return {}
+ out: dict[str, float] = {}
+ for parts in (line.split(None, 1) for line in lines):
+ try:
+ if len(parts) == 2:
+ out[parts[0]] = float(parts[1])
+ except ValueError:
+ continue
return out
def _write_banner_cache(seen: dict[str, float]) -> None:
- p = _banner_cache_path()
- if p is None:
- return
try:
- p.write_text("\n".join(f"{aid} {ts}" for aid, ts in seen.items()) + "\n", encoding="utf-8")
+ if (p := _banner_cache_path()) is not None:
+ p.write_text("\n".join(f"{aid} {ts}" for aid, ts in seen.items()) + "\n", encoding="utf-8")
except Exception:
logger.debug("Could not write advisory banner cache", exc_info=True)
-def hits_due_for_banner(
- hits: list[AdvisoryHit],
- *,
- repeat_hours: int = _BANNER_REPEAT_HOURS,
-) -> list[AdvisoryHit]:
+def hits_due_for_banner(hits: list[AdvisoryHit], *, repeat_hours: int = _BANNER_REPEAT_HOURS) -> list[AdvisoryHit]:
"""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.
"""
@@ -268,7 +245,6 @@ def hits_due_for_banner(
now = time.time()
cache = _read_banner_cache()
cutoff = now - (repeat_hours * 3600)
-
due = [hit for hit in fresh if cache.get(hit.advisory.id, 0.0) < cutoff]
for hit in due:
cache[hit.advisory.id] = now
@@ -277,9 +253,6 @@ def hits_due_for_banner(
return due
-# ─── Public entry points used by doctor / CLI / gateway ───────────────────────
-
-
def startup_banner(hits: list[AdvisoryHit]) -> Optional[str]:
"""Printable startup banner, or None if nothing is due (updates the banner cache)."""
due = hits_due_for_banner(hits)
@@ -296,11 +269,7 @@ def gateway_log_message(hits: list[AdvisoryHit]) -> Optional[str]:
return None
if len(fresh) == 1:
h = fresh[0]
- return (
- f"Security advisory [{h.advisory.id}] active: {h.package}=={h.installed_version} "
- f"matches {h.advisory.title}. See {h.advisory.url}"
- )
- return (
- f"{len(fresh)} security advisories active (IDs: {', '.join(h.advisory.id for h in fresh)}). "
- "Run `hermes doctor` on the gateway host for details."
- )
+ return (f"Security advisory [{h.advisory.id}] active: {h.package}=={h.installed_version} "
+ f"matches {h.advisory.title}. See {h.advisory.url}")
+ return (f"{len(fresh)} security advisories active (IDs: {', '.join(h.advisory.id for h in fresh)}). "
+ "Run `hermes doctor` on the gateway host for details.")
diff --git a/hermes_cli/security_audit.py b/hermes_cli/security_audit.py
index c7b7671c99b..6358e5fc8c9 100644
--- a/hermes_cli/security_audit.py
+++ b/hermes_cli/security_audit.py
@@ -53,39 +53,24 @@ class Finding:
vuln: Vulnerability
-# ─── Component discovery ──────────────────────────────────────────────────────
-
-
def _discover_venv() -> list[Component]:
"""Every dist installed in the running Python's import path."""
from importlib.metadata import distributions
- out: list[Component] = []
- seen: set[tuple[str, str]] = set()
+ out: dict[tuple[str, str], Component] = {}
for dist in distributions():
try:
name = (dist.metadata["Name"] or "").strip()
except Exception:
continue
version = (dist.version or "").strip()
- key = (name.lower(), version)
- if name and version and key not in seen:
- seen.add(key)
- out.append(Component(name=name, version=version, ecosystem="PyPI", source="venv"))
- return out
+ if name and version:
+ out.setdefault((name.lower(), version), Component(name=name, version=version, ecosystem="PyPI", source="venv"))
+ return list(out.values())
-# requirements.txt line: drop comments, environment markers, options, extras
-_REQ_LINE = re.compile(
- r"""^\s*
- (?P<name>[A-Za-z0-9][A-Za-z0-9._-]*)
- (?:\[[^\]]+\])? # extras
- \s*==\s*
- (?P<version>[A-Za-z0-9._+!-]+)
- \s*(?:;.*)?$
- """,
- re.VERBOSE,
-)
+# ``name[extras]==version ; marker`` — an exact pin, optionally with extras and an environment marker.
+_REQ_LINE = re.compile(r"^\s*(?P<name>[A-Za-z0-9][A-Za-z0-9._-]*)(?:\[[^\]]+\])?\s*==\s*(?P<version>[A-Za-z0-9._+!-]+)\s*(?:;.*)?$")
def _match_pins(specs: Iterable[str]) -> list[tuple[str, str]]:
@@ -105,20 +90,16 @@ def _parse_pyproject_pins(text: str) -> list[tuple[str, str]]:
"""Pull ``name==version`` pins from a ``pyproject.toml`` ``dependencies`` list."""
try:
import tomllib
- data = tomllib.loads(text)
+ project = tomllib.loads(text).get("project") or {}
except Exception:
return []
- project = data.get("project") or {}
optional = project.get("optional-dependencies") or {}
groups = [project.get("dependencies")] + (list(optional.values()) if isinstance(optional, dict) else [])
return _match_pins(str(x) for group in groups if isinstance(group, list) for x in group)
-_PLUGIN_PIN_FILES = (
- ("requirements.txt", _parse_requirements),
- ("requirements-dev.txt", _parse_requirements),
- ("pyproject.toml", _parse_pyproject_pins),
-)
+_PLUGIN_PIN_FILES = (("requirements.txt", _parse_requirements), ("requirements-dev.txt", _parse_requirements),
+ ("pyproject.toml", _parse_pyproject_pins))
def _discover_plugins(hermes_home: Path) -> list[Component]:
@@ -128,7 +109,6 @@ def _discover_plugins(hermes_home: Path) -> list[Component]:
plugins_dir = hermes_home / "plugins"
if not plugins_dir.is_dir():
return []
-
out: list[Component] = []
for plugin_dir in sorted(plugins_dir.iterdir()):
if not plugin_dir.is_dir() or plugin_dir.name.startswith("."):
@@ -172,21 +152,15 @@ def _discover_mcp() -> list[Component]:
from hermes_cli.mcp_config import _get_mcp_servers
except Exception:
return []
-
servers = _get_mcp_servers()
if not isinstance(servers, dict):
return []
- out: list[Component] = []
- for name, cfg in servers.items():
- if not isinstance(cfg, dict) or not isinstance(cfg.get("args") or [], list):
- continue
- comp = _extract_mcp_component(name, cfg.get("command", "") or "", [str(a) for a in cfg.get("args") or []])
- if comp:
- out.append(comp)
- return out
-
-
-# ─── OSV client ───────────────────────────────────────────────────────────────
+ comps = (
+ _extract_mcp_component(name, cfg.get("command", "") or "", [str(a) for a in cfg.get("args") or []])
+ for name, cfg in servers.items()
+ if isinstance(cfg, dict) and isinstance(cfg.get("args") or [], list)
+ )
+ return [c for c in comps if c]
_HTTP_ERRORS = (urllib.error.URLError, TimeoutError, ConnectionError)
@@ -194,12 +168,8 @@ _HTTP_ERRORS = (urllib.error.URLError, TimeoutError, ConnectionError)
def _http_json(url: str, payload: Optional[dict] = None) -> dict:
"""GET ``url`` (or POST ``payload`` as JSON when given) and decode the JSON body."""
- if payload is None:
- req = urllib.request.Request(url, method="GET")
- else:
- req = urllib.request.Request(
- url, data=json.dumps(payload).encode("utf-8"), headers={"Content-Type": "application/json"}, method="POST"
- )
+ req = urllib.request.Request(url, method="GET") if payload is None else urllib.request.Request(
+ url, data=json.dumps(payload).encode("utf-8"), method="POST", headers={"Content-Type": "application/json"})
with urllib.request.urlopen(req, timeout=HTTP_TIMEOUT) as resp:
return json.loads(resp.read().decode("utf-8"))
@@ -209,16 +179,13 @@ def _osv_query_batch(components: list[Component]) -> dict[Component, list[str]]:
findings: dict[Component, list[str]] = {}
for chunk_start in range(0, len(components), OSV_BATCH_MAX):
chunk = components[chunk_start:chunk_start + OSV_BATCH_MAX]
- payload = {
- "queries": [{"package": {"name": c.name, "ecosystem": c.ecosystem}, "version": c.version} for c in chunk]
- }
+ payload = {"queries": [{"package": {"name": c.name, "ecosystem": c.ecosystem}, "version": c.version} for c in chunk]}
try:
resp = _http_json(OSV_BATCH_URL, payload)
except _HTTP_ERRORS as exc:
raise RuntimeError(f"OSV batch query failed: {exc}") from exc
for comp, result in zip(chunk, resp.get("results") or []):
- ids = [v.get("id") for v in (result or {}).get("vulns") or [] if v.get("id")]
- if ids:
+ if ids := [v.get("id") for v in (result or {}).get("vulns") or [] if v.get("id")]:
findings[comp] = ids
return findings
@@ -230,107 +197,59 @@ def _osv_severity_from_record(record: dict) -> str:
``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 []
- ]
- for sev in candidates:
- if isinstance(sev, str) and sev.strip().upper() in SEVERITY_ORDER:
- return sev.strip().upper()
- return "UNKNOWN"
+ (entry.get("ecosystem_specific") or {}).get("severity") for entry in record.get("affected") or []]
+ tiers = (sev.strip().upper() for sev in candidates if isinstance(sev, str))
+ return next((tier for tier in tiers if tier in SEVERITY_ORDER), "UNKNOWN")
def _osv_fixed_versions(record: dict) -> list[str]:
- fixes = [
- str(event["fixed"])
- for entry in record.get("affected") or []
- for rng in entry.get("ranges") or []
- for event in rng.get("events") or []
- if "fixed" in event
- ]
+ fixes = [str(event["fixed"]) for entry in record.get("affected") or [] for rng in entry.get("ranges") or []
+ for event in rng.get("events") or [] if "fixed" in event]
return list(dict.fromkeys(fixes)) # dedupe, preserve order
def _osv_fetch_details(vuln_ids: Iterable[str]) -> dict[str, Vulnerability]:
"""Fetch summary/severity for each unique vuln id, in parallel."""
- unique = sorted({vid for vid in vuln_ids if vid})
- if not unique:
- return {}
-
def _fetch_one(vid: str) -> Vulnerability:
try:
rec = _http_json(OSV_VULN_URL.format(vid=vid))
except _HTTP_ERRORS:
return Vulnerability(osv_id=vid)
- return Vulnerability(
- osv_id=vid,
- severity=_osv_severity_from_record(rec),
- summary=(rec.get("summary") or "").strip(),
- fixed_versions=_osv_fixed_versions(rec),
- )
+ return Vulnerability(vid, _osv_severity_from_record(rec), (rec.get("summary") or "").strip(), _osv_fixed_versions(rec))
+ unique = sorted({vid for vid in vuln_ids if vid})
+ if not unique:
+ return {}
with concurrent.futures.ThreadPoolExecutor(max_workers=DETAIL_PARALLELISM) as pool:
return {vuln.osv_id: vuln for vuln in pool.map(_fetch_one, unique)}
-# ─── Orchestration ────────────────────────────────────────────────────────────
-
-
def _discover_components(
- *,
- skip_venv: bool = False,
- skip_plugins: bool = False,
- skip_mcp: bool = False,
- hermes_home: Optional[Path] = None,
+ *, skip_venv: bool = False, skip_plugins: bool = False, skip_mcp: bool = False, hermes_home: Optional[Path] = None
) -> list[Component]:
"""Discover all scannable components across the enabled sources."""
home = hermes_home or Path(get_hermes_home())
- components: list[Component] = []
- if not skip_venv:
- components.extend(_discover_venv())
- if not skip_plugins:
- components.extend(_discover_plugins(home))
- if not skip_mcp:
- components.extend(_discover_mcp())
- return components
-
-
-def run_audit(
- *,
- skip_venv: bool = False,
- skip_plugins: bool = False,
- skip_mcp: bool = False,
- 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 reuse it instead of scanning a second time.
+ sources = ((skip_venv, _discover_venv), (skip_plugins, lambda: _discover_plugins(home)), (skip_mcp, _discover_mcp))
+ return [c for skip, discover in sources if not skip for c in discover()]
+
+
+def run_audit(*, components: Optional[list[Component]] = None, **discover_kwargs) -> list[Finding]:
+ """Query OSV for ``components`` (or discover them with ``discover_kwargs`` when None; passing
+ an already-discovered list avoids scanning the venv/plugins/MCP config a second time).
"""
if components is None:
- components = _discover_components(
- skip_venv=skip_venv, skip_plugins=skip_plugins, skip_mcp=skip_mcp, hermes_home=hermes_home
- )
+ components = _discover_components(**discover_kwargs)
raw = _osv_query_batch(components) if components else {}
if not raw:
return []
details = _osv_fetch_details(vid for ids in raw.values() for vid in ids)
- findings = [
- Finding(component=comp, vuln=details.get(vid) or Vulnerability(osv_id=vid))
- for comp, ids in raw.items()
- for vid in ids
- ]
- findings.sort(
- key=lambda f: (
- -SEVERITY_ORDER.get(f.vuln.severity, 0),
- f.component.source,
- f.component.name.lower(),
- f.vuln.osv_id,
- )
- )
+ findings = [Finding(comp, details.get(vid) or Vulnerability(osv_id=vid)) for comp, ids in raw.items() for vid in ids]
+ findings.sort(key=lambda f: (
+ -SEVERITY_ORDER.get(f.vuln.severity, 0), f.component.source, f.component.name.lower(), f.vuln.osv_id
+ ))
return findings
-# ─── Rendering ────────────────────────────────────────────────────────────────
-
-
def _render_human(findings: list[Finding], total_components: int) -> str:
if not findings:
return f"No known vulnerabilities found across {total_components} component(s)."
@@ -338,14 +257,15 @@ def _render_human(findings: list[Finding], total_components: int) -> str:
lines = [f"Found {len(findings)} known vulnerability finding(s) across {total_components} component(s):", ""]
last_source = None
for f in findings:
- if f.component.source != last_source:
- lines.append(f"[{f.component.source}]")
- last_source = f.component.source
- lines.append(f" {f.vuln.severity.ljust(8)} {f.component.name}=={f.component.version} {f.vuln.osv_id}")
- if summary := f.vuln.summary:
+ c, v = f.component, f.vuln
+ if c.source != last_source:
+ lines.append(f"[{c.source}]")
+ last_source = c.source
+ lines.append(f" {v.severity.ljust(8)} {c.name}=={c.version} {v.osv_id}")
+ if summary := v.summary:
lines.append(f" {summary if len(summary) <= 100 else summary[:97] + '...'}")
- if f.vuln.fixed_versions:
- lines.append(f" fixed in: {', '.join(f.vuln.fixed_versions[:3])}")
+ if v.fixed_versions:
+ lines.append(f" fixed in: {', '.join(v.fixed_versions[:3])}")
return "\n".join(lines)
@@ -353,19 +273,12 @@ def _render_json(findings: list[Finding], total_components: int) -> str:
payload = {
"total_components_scanned": total_components,
"finding_count": len(findings),
- "findings": [
- {
- "package": f.component.name,
- "version": f.component.version,
- "ecosystem": f.component.ecosystem,
- "source": f.component.source,
- "vuln_id": f.vuln.osv_id,
- "severity": f.vuln.severity,
- "summary": f.vuln.summary,
- "fixed_versions": f.vuln.fixed_versions,
- }
- for f in findings
- ],
+ "findings": [{
+ "package": f.component.name, "version": f.component.version,
+ "ecosystem": f.component.ecosystem, "source": f.component.source,
+ "vuln_id": f.vuln.osv_id, "severity": f.vuln.severity,
+ "summary": f.vuln.summary, "fixed_versions": f.vuln.fixed_versions,
+ } for f in findings],
}
return json.dumps(payload, indent=2)
@@ -376,26 +289,15 @@ def cmd_security_audit(args: argparse.Namespace) -> int:
output_json = bool(getattr(args, "json", False))
fail_on = (getattr(args, "fail_on", None) or "critical").upper()
if fail_on not in SEVERITY_ORDER:
- print(
- f"unknown --fail-on value: {fail_on.lower()} "
- f"(choose from: low, moderate, high, critical)",
- file=sys.stderr,
- )
+ print(f"unknown --fail-on value: {fail_on.lower()} (choose from: low, moderate, high, critical)", file=sys.stderr)
return 2
- components = _discover_components(
- 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,
- )
+ skips = {k: bool(getattr(args, k, False)) for k in ("skip_venv", "skip_plugins", "skip_mcp")}
+ components = _discover_components(hermes_home=home, **skips)
total = len(components)
if total == 0:
- print(
- json.dumps({"total_components_scanned": 0, "finding_count": 0, "findings": []})
- if output_json
- else "No components discovered (everything skipped, or empty environment)."
- )
+ print(json.dumps({"total_components_scanned": 0, "finding_count": 0, "findings": []}) if output_json
+ else "No components discovered (everything skipped, or empty environment).")
return 0
try:
diff --git a/hermes_cli/security_audit_startup.py b/hermes_cli/security_audit_startup.py
index c55df33fdc3..5f91aef8e6a 100644
--- a/hermes_cli/security_audit_startup.py
+++ b/hermes_cli/security_audit_startup.py
@@ -28,14 +28,10 @@ def _is_root() -> bool:
def _running_as_root() -> Optional[str]:
- if not _is_root():
- return None
- return (
- "Running as ROOT. The agent's terminal/file tools execute with full "
- "root privileges — a single prompt-injection or exposed endpoint is a "
- "full host compromise. Run Hermes as an unprivileged user (or in a "
- "sandboxed terminal backend / container with a non-root user)."
- )
+ return None if not _is_root() else (
+ "Running as ROOT. The agent's terminal/file tools execute with full root privileges — a single "
+ "prompt-injection or exposed endpoint is a full host compromise. Run Hermes as an unprivileged user "
+ "(or in a sandboxed terminal backend / container with a non-root user).")
def _iter_sshd_config_lines() -> list[str]:
@@ -43,9 +39,7 @@ def _iter_sshd_config_lines() -> list[str]:
lines: list[str] = []
paths: list[Path] = [Path("/etc/ssh/sshd_config")]
try:
- d = Path("/etc/ssh/sshd_config.d")
- if d.is_dir():
- paths.extend(sorted(d.glob("*.conf")))
+ paths.extend(sorted(Path("/etc/ssh/sshd_config.d").glob("*.conf")))
except Exception:
pass
for p in paths:
@@ -65,19 +59,12 @@ def _ssh_password_auth_enabled() -> Optional[str]:
if not lines:
return None
# Last directive wins in sshd_config. Default (no directive) is "yes".
- directives = [
- m.group(1).lower()
- for m in (re.match(r"(?i)^PasswordAuthentication\s+(\w+)", line) for line in lines)
- if m
- ]
+ directives = [m.group(1).lower() for m in map(re.compile(r"(?i)^PasswordAuthentication\s+(\w+)").match, lines) if m]
if directives and directives[-1] == "no":
return None
qualifier = "" if directives else " (default — no explicit directive)"
- return (
- f"SSH password authentication is ENABLED{qualifier}. Password auth is "
- "brute-forceable and dangerous on an internet-facing box. Set "
- "'PasswordAuthentication no' in sshd_config and use key-based auth."
- )
+ return (f"SSH password authentication is ENABLED{qualifier}. Password auth is brute-forceable and dangerous "
+ "on an internet-facing box. Set 'PasswordAuthentication no' in sshd_config and use key-based auth.")
def _in_container() -> bool:
@@ -126,12 +113,9 @@ def _container_no_volume_mount(hermes_home: Optional[Path]) -> Optional[str]:
hermes_home = get_hermes_home()
if _path_is_mounted(hermes_home): # any error propagates to run_security_audit (= no finding)
return None
- return (
- f"Running in a container but the data dir ({hermes_home}) is NOT on a "
- "persistent volume mount — sessions, memory, skills, and API keys are "
- "ephemeral and lost on container restart. Mount a host volume over the "
- "HERMES_HOME data directory."
- )
+ return (f"Running in a container but the data dir ({hermes_home}) is NOT on a persistent volume mount — "
+ "sessions, memory, skills, and API keys are ephemeral and lost on container restart. Mount a host "
+ "volume over the HERMES_HOME data directory.")
def _network_listener_without_auth(config: Optional[dict]) -> list[str]:
@@ -150,27 +134,18 @@ def _network_listener_without_auth(config: Optional[dict]) -> list[str]:
key = extra.get("key") or os.environ.get("API_SERVER_KEY", "")
if not is_network_accessible(str(host)) or str(key).strip():
return []
- return [
- f"OpenAI-compatible API server is network-accessible ({host}) "
- "with NO API_SERVER_KEY. It dispatches terminal-capable agent "
- "work — an unauthenticated network endpoint is remote code "
- "execution. Set a strong API_SERVER_KEY."
- ]
+ return [f"OpenAI-compatible API server is network-accessible ({host}) with NO API_SERVER_KEY. It dispatches "
+ "terminal-capable agent work — an unauthenticated network endpoint is remote code execution. "
+ "Set a strong API_SERVER_KEY."]
-def run_security_audit(
- *, hermes_home: Optional[Path] = None, config: Optional[dict] = None
-) -> list[str]:
+def run_security_audit(*, hermes_home: Optional[Path] = None, config: Optional[dict] = None) -> list[str]:
"""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 (
- _running_as_root,
- _ssh_password_auth_enabled,
- lambda: _container_no_volume_mount(hermes_home),
- lambda: _network_listener_without_auth(config),
- ):
+ for check in (_running_as_root, _ssh_password_auth_enabled, lambda: _container_no_volume_mount(hermes_home),
+ lambda: _network_listener_without_auth(config)):
try:
r = check()
except Exception:
@@ -183,10 +158,7 @@ def run_security_audit(
def log_startup_security_warnings(
- *,
- hermes_home: Optional[Path] = None,
- config: Optional[dict] = None,
- force: bool = False,
+ *, hermes_home: Optional[Path] = None, config: Optional[dict] = None, force: bool = False
) -> list[str]:
"""Run the audit once per process (``force=True`` re-runs) and log each finding as a warning."""
global _AUDIT_RAN
@@ -195,9 +167,7 @@ def log_startup_security_warnings(
_AUDIT_RAN = True
findings = run_security_audit(hermes_home=hermes_home, config=config)
if findings:
- logger.warning(
- "Security posture audit found %d issue(s) — review your deployment:", len(findings)
- )
+ logger.warning("Security posture audit found %d issue(s) — review your deployment:", len(findings))
for i, f in enumerate(findings, 1):
logger.warning(" [security %d/%d] %s", i, len(findings), f)
return findings