Skip to content

The agent that grows with you

refactor(hermes_cli): small modules — default_soul scaffold constants, input_sanitize sub table, diagnostics_upload request helper, gui_uninstall/dep_ensure packing

Tekniumd8748847777e
diff --git a/hermes_cli/default_soul.py b/hermes_cli/default_soul.py
index 992a66b4647..0f4c13a217c 100644
--- a/hermes_cli/default_soul.py
+++ b/hermes_cli/default_soul.py
@@ -5,17 +5,22 @@
# "targeted and efficient exploration" line is deliberately absent (see DEFAULT_AGENT_IDENTITY) --
# never re-add it here either.
DEFAULT_SOUL_MD = (
- "You are Hermes Agent, built by Nous Research. Be direct: match the "
- "length of your reply to the weight of the ask — a one-line question "
- "gets a one-line answer, and finished work gets a short report of what "
- "changed, what's verified, and what's left, never a replay of the "
- "process. No filler (\"Great question,\" \"I'd be happy to\"), no "
- "restating the request back, no re-summarizing what you already said, "
- "no narrating tool calls the user can see. Plain claims over "
- "adjectives; when unsure, say so plainly. Agree because it's right, "
- "not because the user said it. Depth is earned — give it when the "
- "user asks for detail, teaches, or the stakes demand it, not by "
- "default."
+ "You are Hermes Agent, built by Nous Research. Be direct: match the length of your reply to the weight of "
+ "the ask — a one-line question gets a one-line answer, and finished work gets a short report of what "
+ "changed, what's verified, and what's left, never a replay of the process. No filler (\"Great question,\" "
+ "\"I'd be happy to\"), no restating the request back, no re-summarizing what you already said, no narrating "
+ "tool calls the user can see. Plain claims over adjectives; when unsure, say so plainly. Agree because it's "
+ "right, not because the user said it. Depth is earned — give it when the user asks for detail, teaches, or "
+ "the stakes demand it, not by default."
+)
+
+_SCAFFOLD_HEAD = (
+ "# Hermes Agent Persona\n\n<!--\nThis file defines the agent's personality and tone.\n"
+ "The agent will embody whatever you write here.\nEdit this to customize how Hermes communicates with you.\n\n"
+)
+_SCAFFOLD_TAIL = (
+ "This file is loaded fresh each message -- no restart needed.\n"
+ "Delete the contents (or this file) to use the default personality.\n-->"
)
# Auto-seeded SOUL.md content that carries zero user intent, so a matching file is safe to upgrade
@@ -24,46 +29,21 @@ DEFAULT_SOUL_MD = (
# normalized content (stripped, line endings unified). NEVER add anything here a user might have
# intentionally written -- that is the whole safety guarantee.
_LEGACY_TEMPLATE_SOULS = (
- (
- "# Hermes Agent Persona\n"
- "\n"
- "<!--\n"
- "This file defines the agent's personality and tone.\n"
- "The agent will embody whatever you write here.\n"
- "Edit this to customize how Hermes communicates with you.\n"
- "\n"
+ _SCAFFOLD_HEAD + (
"Examples:\n"
' - "You are a warm, playful assistant who uses kaomoji occasionally."\n'
' - "You are a concise technical expert. No fluff, just facts."\n'
- ' - "You speak like a friendly coworker who happens to know everything."\n'
- "\n"
- "This file is loaded fresh each message -- no restart needed.\n"
- "Delete the contents (or this file) to use the default personality.\n"
- "-->"
- ),
+ ' - "You speak like a friendly coworker who happens to know everything."\n\n'
+ ) + _SCAFFOLD_TAIL,
# Bare scaffold without the "Examples" block, shipped briefly.
- (
- "# Hermes Agent Persona\n"
- "\n"
- "<!--\n"
- "This file defines the agent's personality and tone.\n"
- "The agent will embody whatever you write here.\n"
- "Edit this to customize how Hermes communicates with you.\n"
- "\n"
- "This file is loaded fresh each message -- no restart needed.\n"
- "Delete the contents (or this file) to use the default personality.\n"
- "-->"
- ),
+ _SCAFFOLD_HEAD + _SCAFFOLD_TAIL,
# The previous generation of DEFAULT_SOUL_MD (same auto-seed mechanism, older string).
(
- "You are Hermes Agent, an intelligent AI assistant created by Nous "
- "Research. You are helpful, knowledgeable, and direct. You assist "
- "users with a wide range of tasks including answering questions, "
- "writing and editing code, analyzing information, creative work, "
- "and executing actions via your tools. You communicate clearly, "
- "admit uncertainty when appropriate, and prioritize being "
- "genuinely useful over being verbose unless otherwise directed "
- "below. Be targeted and efficient in your exploration and "
+ "You are Hermes Agent, an intelligent AI assistant created by Nous Research. You are helpful, "
+ "knowledgeable, and direct. You assist users with a wide range of tasks including answering questions, "
+ "writing and editing code, analyzing information, creative work, and executing actions via your tools. "
+ "You communicate clearly, admit uncertainty when appropriate, and prioritize being genuinely useful over "
+ "being verbose unless otherwise directed below. Be targeted and efficient in your exploration and "
"investigations."
),
# ASCII-dashed variant seeded by scripts/install.ps1 (must stay pure ASCII, see
diff --git a/hermes_cli/dep_ensure.py b/hermes_cli/dep_ensure.py
index a99296ee9b7..3464f4f6687 100644
--- a/hermes_cli/dep_ensure.py
+++ b/hermes_cli/dep_ensure.py
@@ -17,37 +17,27 @@ _DEP_CHECKS = {
# find_node_executable() rather than a bare which(): $HERMES_HOME/node is not on PATH, so
# which() would report Node missing on a managed install and trigger a redundant re-install.
"node": lambda: find_node_executable("node") is not None,
- "browser": lambda: (
- agent_browser_runnable(shutil.which("agent-browser"))
- or _has_system_browser()
- or _has_hermes_agent_browser()
- or _has_npx_agent_browser()
- ),
+ "browser": lambda: (agent_browser_runnable(shutil.which("agent-browser")) or _has_system_browser()
+ or _has_hermes_agent_browser() or _has_npx_agent_browser()),
"ripgrep": lambda: shutil.which("rg") is not None,
"ffmpeg": lambda: shutil.which("ffmpeg") is not None,
}
-_DEP_DESCRIPTIONS = {
- "node": "Node.js (required for browser tools and TUI)",
- "browser": "Browser engine (Chromium, for web browsing tools)",
- "ripgrep": "ripgrep (fast file search)",
- "ffmpeg": "ffmpeg (TTS voice messages)",
-}
+_DEP_DESCRIPTIONS = {"node": "Node.js (required for browser tools and TUI)",
+ "browser": "Browser engine (Chromium, for web browsing tools)",
+ "ripgrep": "ripgrep (fast file search)", "ffmpeg": "ffmpeg (TTS voice messages)"}
def _has_system_browser() -> bool:
- names = (
- ("chrome", "msedge", "chromium") if _IS_WINDOWS
- else ("google-chrome", "google-chrome-stable", "chromium", "chromium-browser", "chrome")
- )
+ names = ("chrome", "msedge", "chromium") if _IS_WINDOWS else (
+ "google-chrome", "google-chrome-stable", "chromium", "chromium-browser", "chrome")
return any(shutil.which(name) for name in names)
def _has_npx_agent_browser() -> bool:
"""agent-browser resolves lazily via npx on the default install, invisible to the PATH/managed-dir
probes above. Mirror tools.browser_tool.check_browser_requirements's Termux carve-out so this
- check can't diverge from what browser tools actually find.
- """
+ check can't diverge from what browser tools actually find."""
try:
from tools.browser_tool import _find_agent_browser, _is_npx_agent_browser_sentinel, _requires_real_termux_browser_install
browser_cmd = _find_agent_browser(validate=False)
@@ -61,12 +51,9 @@ def _has_hermes_agent_browser() -> bool:
home = get_hermes_home()
if _IS_WINDOWS: # npm -g --prefix puts .cmd shims directly in the prefix dir
return (home / "node" / "agent-browser.cmd").is_file()
- # install.sh installs into $HERMES_HOME/node/bin/ via npm -g --prefix; legacy git-clone
- # installs used node_modules/.bin/.
- return (
- (home / "node" / "bin" / "agent-browser").is_file()
- or (home / "node_modules" / ".bin" / "agent-browser").is_file()
- )
+ # install.sh installs into $HERMES_HOME/node/bin/ via npm -g --prefix; legacy git clones used node_modules/.bin/.
+ return ((home / "node" / "bin" / "agent-browser").is_file()
+ or (home / "node_modules" / ".bin" / "agent-browser").is_file())
def _find_install_script(package_dir: Path | None = None, repo_root: Path | None = None) -> tuple[Path | None, str | None]:
@@ -78,8 +65,7 @@ def _find_install_script(package_dir: Path | None = None, repo_root: Path | None
candidates.reverse()
for script_name, shell in candidates:
for base in (package_dir, repo_root):
- script = base / "scripts" / script_name
- if script.is_file():
+ if (script := base / "scripts" / script_name).is_file():
return script, shell
return None, None
diff --git a/hermes_cli/diagnostics_upload.py b/hermes_cli/diagnostics_upload.py
index 47d3d34afb4..6bfdc63f88c 100644
--- a/hermes_cli/diagnostics_upload.py
+++ b/hermes_cli/diagnostics_upload.py
@@ -1,9 +1,7 @@
"""Client for uploading ``hermes debug share`` bundles to Nous-internal S3.
-
1. POST {NAS_BASE}/api/diagnostics/upload-url → {uploadUrl, viewUrl, id, ...}; the body carries ``sizeBytes``,
which NAS signs into the presigned URL's ``ContentLength``, so the PUT must send exactly that many bytes.
-2. PUT <uploadUrl> (gzipped bundle, Content-Type application/gzip). NAS is stateless — no confirm step.
-"""
+2. PUT <uploadUrl> (gzipped bundle, Content-Type application/gzip). NAS is stateless — no confirm step."""
import json
import os
@@ -16,8 +14,9 @@ _UPLOAD_TIMEOUT = 120 # the PUT carries the gzipped log bundle, so a more gener
_USER_AGENT = "hermes-agent/debug-share"
-def _urlopen_checked(req: urllib.request.Request, *, timeout: int, what: str):
- """Open *req*; raise ``RuntimeError`` on non-2xx and return the response body bytes."""
+def _urlopen_checked(url: str, data: bytes, method: str, headers: dict, *, timeout: int, what: str):
+ """Send the request; raise ``RuntimeError`` on non-2xx and return the response body bytes."""
+ req = urllib.request.Request(url, data=data, method=method, headers={**headers, "User-Agent": _USER_AGENT})
with urllib.request.urlopen(req, timeout=timeout) as resp:
status = getattr(resp, "status", None)
status = resp.getcode() if status is None else status
@@ -27,21 +26,15 @@ def _urlopen_checked(req: urllib.request.Request, *, timeout: int, what: str):
def request_upload_url(content_type: str = "application/gzip", size_bytes: int | None = None) -> dict:
- """Ask NAS to mint a presigned PUT URL for a diagnostics bundle.
-
- Returns the parsed JSON, expected to carry at least ``uploadUrl``, ``viewUrl`` and ``id``.
- Raises on non-2xx responses or unparseable JSON.
- """
+ """Ask NAS to mint a presigned PUT URL for a diagnostics bundle. Returns the parsed JSON, expected to
+ carry at least ``uploadUrl``, ``viewUrl`` and ``id``. Raises on non-2xx responses or unparseable JSON."""
payload: dict = {"contentType": content_type}
if size_bytes is not None:
payload["sizeBytes"] = int(size_bytes)
- req = urllib.request.Request(
- f"{NAS_BASE}/api/diagnostics/upload-url",
- data=json.dumps(payload).encode("utf-8"),
- method="POST",
- headers={"Content-Type": "application/json", "Accept": "application/json", "User-Agent": _USER_AGENT},
- )
- body = _urlopen_checked(req, timeout=_REQUEST_TIMEOUT, what="diagnostics upload-url request").decode("utf-8")
+ body = _urlopen_checked(
+ f"{NAS_BASE}/api/diagnostics/upload-url", json.dumps(payload).encode("utf-8"), "POST",
+ {"Content-Type": "application/json", "Accept": "application/json"},
+ timeout=_REQUEST_TIMEOUT, what="diagnostics upload-url request").decode("utf-8")
try:
result = json.loads(body)
except (ValueError, json.JSONDecodeError) as exc:
@@ -53,13 +46,9 @@ def request_upload_url(content_type: str = "application/gzip", size_bytes: int |
def put_bundle(upload_url: str, data: bytes, content_type: str = "application/gzip") -> None:
"""PUT the gzipped *data* bundle to a presigned *upload_url*. Raises on non-2xx.
-
- ``Content-Type`` must match what NAS pinned when signing the URL, otherwise S3 rejects the signature.
- """
- req = urllib.request.Request(
- upload_url, data=data, method="PUT", headers={"Content-Type": content_type, "User-Agent": _USER_AGENT}
- )
- _urlopen_checked(req, timeout=_UPLOAD_TIMEOUT, what="diagnostics bundle PUT")
+ ``Content-Type`` must match what NAS pinned when signing the URL, otherwise S3 rejects the signature."""
+ _urlopen_checked(upload_url, data, "PUT", {"Content-Type": content_type}, timeout=_UPLOAD_TIMEOUT,
+ what="diagnostics bundle PUT")
def share_to_nous(report_bundle: bytes) -> dict:
diff --git a/hermes_cli/focus_view.py b/hermes_cli/focus_view.py
index 4d0d862cdf7..6bcd6201b3c 100644
--- a/hermes_cli/focus_view.py
+++ b/hermes_cli/focus_view.py
@@ -1,19 +1,16 @@
"""Focus view — display-only reduced output: "just my prompt and the answer, and tell me what you hid".
-
ON snaps ``tool_progress_mode`` to ``"off"`` and remembers the configured mode so the *existing* suppression
path does the hiding; OFF restores it verbatim. Focus adds a per-turn hidden-line count with a recovery
-hint and a persistent ``focus`` status-bar segment.
-"""
+hint and a persistent ``focus`` status-bar segment."""
from __future__ import annotations
from typing import Optional
FOCUS_CONFIG_KEY = "display.focus_view" # plain boolean under ``display``, like /battery /timestamps /footer
-#: The SAME value ``/verbose off`` uses so both features share one suppression path.
-FOCUS_TOOL_PROGRESS_MODE = "off"
-#: Modes in which the CLI commits a per-tool scrollback line. Mirrors the gate in
-#: ``HermesCLI._on_tool_progress`` so the hidden-line counter and the renderer never drift apart.
+FOCUS_TOOL_PROGRESS_MODE = "off" # the SAME value ``/verbose off`` uses so both features share one suppression path
+# Modes in which the CLI commits a per-tool scrollback line. Mirrors the gate in
+# ``HermesCLI._on_tool_progress`` so the hidden-line counter and the renderer never drift apart.
TOOL_PROGRESS_VISIBLE_MODES = frozenset({"new", "all", "verbose"})
TOOL_PROGRESS_MODES = ("off", "new", "all", "verbose") # ``log`` is a gateway-only extra step
FOCUS_STATUSBAR_LABEL = "◉ focus" # short on purpose — the bar is width-constrained
@@ -38,11 +35,8 @@ def normalize_tool_progress_mode(mode: object, default: str = "all") -> str:
def resolve_focus_arg(arg: str, current: bool) -> tuple[str, Optional[bool]]:
- """Map a ``/focus`` argument onto ``(action, target)``.
-
- ``action`` is ``"set"``, ``"status"`` or ``"usage"``; ``target`` is the requested enabled-state
- for ``"set"`` and ``None`` otherwise.
- """
+ """Map a ``/focus`` argument onto ``(action, target)``: action is ``"set"``, ``"status"`` or ``"usage"``;
+ target is the requested enabled-state for ``"set"`` and ``None`` otherwise."""
text = str(arg or "").strip().lower()
if text in ("", "toggle"):
return "set", not bool(current)
@@ -50,11 +44,9 @@ def resolve_focus_arg(arg: str, current: bool) -> tuple[str, Optional[bool]]:
def would_display_tool_line(mode: object, function_name: str, last_tool_name: Optional[str] = None) -> bool:
- """Would the CLI have committed a scrollback line for this tool call?
-
- Counts honestly: with ``/verbose off`` focus view hides nothing extra and must not claim
- otherwise. ``new`` mode skips consecutive repeats of the same tool, so the counter does too.
- """
+ """Would the CLI have committed a scrollback line for this tool call? Counts honestly: with ``/verbose off``
+ focus view hides nothing extra and must not claim otherwise. ``new`` mode skips consecutive repeats of the
+ same tool, so the counter does too."""
if not function_name:
return False
normalized = normalize_tool_progress_mode(mode)
diff --git a/hermes_cli/gui_uninstall.py b/hermes_cli/gui_uninstall.py
index bee8e52b96d..3c234374b7d 100644
--- a/hermes_cli/gui_uninstall.py
+++ b/hermes_cli/gui_uninstall.py
@@ -15,20 +15,13 @@ def _logger(mark: str, col: str):
return lambda msg: print(f"{color(mark, col)} {msg}")
-log_info = _logger("→", Colors.CYAN)
-log_success = _logger("✓", Colors.GREEN)
+log_info, log_success = _logger("→", Colors.CYAN), _logger("✓", Colors.GREEN)
log_warn = _logger("⚠", Colors.YELLOW)
def _env_dir(var: str, fallback: Path) -> Path:
"""``Path($var)`` when the env var is set, else *fallback*."""
- value = os.environ.get(var)
- return Path(value) if value else fallback
-
-
-def _agent_root(hermes_home: Path) -> Path:
- """The agent checkout root — same layout install.sh / install.ps1 use."""
- return hermes_home / "hermes-agent"
+ return Path(value) if (value := os.environ.get(var)) else fallback
def desktop_userdata_dir() -> Path:
@@ -42,34 +35,28 @@ def desktop_userdata_dir() -> Path:
def source_built_gui_artifacts(hermes_home: Path) -> "list[Path]":
- """GUI build artifacts produced by ``hermes desktop`` inside the checkout.
-
- The Python agent runs from ``hermes-agent/`` source + ``venv/`` and never needs the Electron
- build output or node_modules (the workspace-root node_modules only carries Electron, ~200MB).
- """
- agent_root = _agent_root(hermes_home)
+ """GUI build artifacts produced by ``hermes desktop`` inside the checkout (same ``hermes-agent/`` layout
+ install.sh uses). The Python agent runs from source + venv and never needs the Electron build output or
+ node_modules (the workspace-root node_modules only carries Electron, ~200MB)."""
+ agent_root = hermes_home / "hermes-agent"
desktop_dir = agent_root / "apps" / "desktop"
return [desktop_dir / "dist", desktop_dir / "release", desktop_dir / "node_modules",
agent_root / "node_modules", hermes_home / "desktop-build-stamp.json"]
def packaged_gui_app_paths() -> "list[Path]":
- """Standard install locations of the packaged desktop distributable for the current OS.
-
- Every candidate is returned; the caller filters to those that exist. Never globs system-wide —
- only the well-known electron-builder output locations for the "Hermes" product.
- """
+ """Standard install locations of the packaged desktop distributable for the current OS. Every candidate
+ is returned; the caller filters to those that exist. Never globs system-wide — only the well-known
+ electron-builder output locations for the "Hermes" product."""
home = Path.home()
if sys.platform == "darwin":
return [Path("/Applications/Hermes.app"), home / "Applications" / "Hermes.app"]
if sys.platform == "win32":
local_base = _env_dir("LOCALAPPDATA", home / "AppData" / "Local")
# NSIS per-user install (perMachine=false), an older/alternate layout, NSIS per-machine (needs admin).
- paths = [local_base / "Programs" / "Hermes", local_base / "hermes-desktop"]
program_files = os.environ.get("ProgramFiles")
- if program_files:
- paths.append(Path(program_files) / "Hermes")
- return paths
+ return [local_base / "Programs" / "Hermes", local_base / "hermes-desktop"] + (
+ [Path(program_files) / "Hermes"] if program_files else [])
# Linux: an AppImage lives wherever the user put it and deb/rpm files belong to the package manager
# (see the hint in ``uninstall_gui``), so only the desktop entry + hicolor icons are cleaned here.
from hermes_cli.linux_desktop_entry import desktop_entry_path
@@ -78,16 +65,13 @@ def packaged_gui_app_paths() -> "list[Path]":
# "scalable" plus every fixed-size dir the installer may have written (panel sizes + older native copies).
return [desktop_entry_path(), data_base / "applications" / "Hermes.desktop"] + [
icons / size / "apps" / "hermes.png"
- for size in ("scalable", "24x24", "32x32", "48x48", "256x256", "512x512", "1024x1024")
- ]
+ for size in ("scalable", "24x24", "32x32", "48x48", "256x256", "512x512", "1024x1024")]
def agent_is_installed(hermes_home: Path) -> bool:
"""True when a usable Python agent install exists under HERMES_HOME (gates the desktop UI's options).
-
- Package source or a venv alone is enough — a source checkout without a venv is still "the agent is here".
- """
- return any((_agent_root(hermes_home) / sub).is_dir() for sub in ("hermes_cli", "venv", ".venv"))
+ Package source or a venv alone is enough — a source checkout without a venv is still "the agent is here"."""
+ return any((hermes_home / "hermes-agent" / sub).is_dir() for sub in ("hermes_cli", "venv", ".venv"))
def gui_is_installed(hermes_home: Path) -> bool:
@@ -99,16 +83,11 @@ def gui_install_summary(hermes_home: "Path | None" = None) -> dict:
"""JSON-serializable snapshot of what's installed, for the desktop UI to render via IPC."""
home: Path = hermes_home if hermes_home is not None else get_hermes_home()
userdata = desktop_userdata_dir()
- return {
- "hermes_home": str(home),
- "agent_installed": agent_is_installed(home),
- "gui_installed": gui_is_installed(home),
- "source_built_artifacts": [str(p) for p in source_built_gui_artifacts(home) if p.exists()],
- "packaged_app_paths": [str(p) for p in packaged_gui_app_paths() if p.exists()],
- "userdata_dir": str(userdata),
- "userdata_exists": userdata.exists(),
- "platform": sys.platform,
- }
+ return {"hermes_home": str(home), "agent_installed": agent_is_installed(home),
+ "gui_installed": gui_is_installed(home),
+ "source_built_artifacts": [str(p) for p in source_built_gui_artifacts(home) if p.exists()],
+ "packaged_app_paths": [str(p) for p in packaged_gui_app_paths() if p.exists()],
+ "userdata_dir": str(userdata), "userdata_exists": userdata.exists(), "platform": sys.platform}
def _remove_path(path: Path) -> bool:
@@ -134,24 +113,20 @@ def uninstall_gui(hermes_home: "Path | None" = None, *, remove_userdata: bool =
def _remove_existing(paths) -> bool:
"""Remove every existing path; True when at least one existed."""
found = False
- for path in paths:
- if path.exists():
- found = True
- if _remove_path(path):
- log_success(f"Removed {path}")
- removed.append(path)
-
+ for path in (p for p in paths if p.exists()):
+ found = True
+ if _remove_path(path):
+ log_success(f"Removed {path}")
+ removed.append(path)
return found
log_info("Removing built GUI artifacts (renderer, release, node_modules)...")
_remove_existing(source_built_gui_artifacts(home))
log_info("Removing installed desktop app...")
if not _remove_existing(packaged_gui_app_paths()):
log_info("No packaged desktop app found in standard locations")
- if remove_userdata:
- userdata = desktop_userdata_dir()
- if userdata.exists():
- log_info("Removing desktop app data (Electron userData)...")
- _remove_existing([userdata])
+ if remove_userdata and (userdata := desktop_userdata_dir()).exists():
+ log_info("Removing desktop app data (Electron userData)...")
+ _remove_existing([userdata])
if not removed:
log_info("No desktop GUI artifacts found to remove")
if sys.platform.startswith("linux"):
@@ -165,10 +140,7 @@ def uninstall_gui(hermes_home: "Path | None" = None, *, remove_userdata: bool =
log_success(f"Refreshed the application menu cache ({tool})")
except Exception as e:
log_warn(f"Could not refresh the application menu cache: {e}")
- log_info(
- "If you installed the desktop via a .deb / .rpm package, remove it "
- "with your package manager (e.g. 'sudo apt remove hermes' or "
- "'sudo dnf remove hermes'). AppImage builds are a single file you "
- "can delete from wherever you saved it."
- )
+ log_info("If you installed the desktop via a .deb / .rpm package, remove it with your package manager "
+ "(e.g. 'sudo apt remove hermes' or 'sudo dnf remove hermes'). AppImage builds are a single "
+ "file you can delete from wherever you saved it.")
return removed
diff --git a/hermes_cli/image_provenance.py b/hermes_cli/image_provenance.py
index 07f751a885d..7d1f86295b3 100644
--- a/hermes_cli/image_provenance.py
+++ b/hermes_cli/image_provenance.py
@@ -3,8 +3,7 @@
The image bakes ``/etc/hermes/image-provenance.json`` outside ``$HERMES_HOME`` and the checkout, so a
bind-mounted checkout cannot hide the build fact and env/config cannot forge it. Absence preserves every
source/package install path. Presence fails closed: an unreadable, non-regular, or malformed marker still
-means image-managed — an integrity defect, never permission to mutate the image in place.
-"""
+means image-managed — an integrity defect, never permission to mutate the image in place."""
from __future__ import annotations
@@ -49,9 +48,7 @@ def _optional_string(payload: dict, name: str) -> Optional[str]:
def read_image_provenance(marker_path: Optional[Path] = None) -> Optional[ImageProvenance]:
"""Read the baked marker without consulting environment or config. Never raises.
-
- ``marker_path`` is a dependency-injection seam for tests and alternate image builders.
- """
+ ``marker_path`` is a dependency-injection seam for tests and alternate image builders."""
path = IMAGE_PROVENANCE_PATH
try:
path = Path(marker_path) if marker_path is not None else path
diff --git a/hermes_cli/input_sanitize.py b/hermes_cli/input_sanitize.py
index 56afe5e6389..e073f37b62d 100644
--- a/hermes_cli/input_sanitize.py
+++ b/hermes_cli/input_sanitize.py
@@ -4,30 +4,28 @@ from __future__ import annotations
import re
-_BRACKETED_PASTE_BOUNDARY_START = re.compile(r"(^|[\s\n>:\]\)])\[200~")
-_BRACKETED_PASTE_BOUNDARY_END = re.compile(r"\[201~(?=$|[\s\n<\[\(\):;.,!?])")
-_BRACKETED_PASTE_DEGRADED_START = re.compile(r"(^|[\s\n>:\]\)])00~")
-_BRACKETED_PASTE_DEGRADED_END = re.compile(r"01~(?=$|[\s\n<\[\(\):;.,!?])")
+# Degraded visible bracketed-paste forms, matched only at boundaries so embedded literals stay intact.
+_BOUNDARY_SUBS = (
+ (re.compile(r"(^|[\s\n>:\]\)])\[200~"), r"\1"),
+ (re.compile(r"\[201~(?=$|[\s\n<\[\(\):;.,!?])"), ""),
+ (re.compile(r"(^|[\s\n>:\]\)])00~"), r"\1"),
+ (re.compile(r"01~(?=$|[\s\n<\[\(\):;.,!?])"), ""),
+)
# Corruption signature from desktop bracketed-paste leaks (#62557).
_DESKTOP_PASTE_ARTIFACT = "~[[e"
def strip_leaked_bracketed_paste_wrappers(text: str) -> str:
- """Strip leaked bracketed-paste wrapper markers from user-visible text.
-
- Canonical wrappers are stripped unconditionally. Degraded visible forms like ``[200~`` /
- ``[201~`` and ``00~`` / ``01~`` are removed only at boundaries so embedded literals such as
- ``literal[200~tag`` stay intact.
- """
+ """Strip leaked bracketed-paste wrapper markers: canonical wrappers unconditionally, degraded visible forms
+ (``[200~`` / ``[201~`` and ``00~`` / ``01~``) only at boundaries so ``literal[200~tag`` stays intact."""
if not text:
return text
for wrapper in ("\x1b[200~", "\x1b[201~", "^[[200~", "^[[201~"):
text = text.replace(wrapper, "")
- text = _BRACKETED_PASTE_BOUNDARY_START.sub(r"\1", text)
- text = _BRACKETED_PASTE_BOUNDARY_END.sub("", text)
- text = _BRACKETED_PASTE_DEGRADED_START.sub(r"\1", text)
- return _BRACKETED_PASTE_DEGRADED_END.sub("", text)
+ for pattern, repl in _BOUNDARY_SUBS:
+ text = pattern.sub(repl, text)
+ return text
def collapse_repeated_input_artifacts(text: str, min_repeats: int = 4) -> str: