#!/usr/bin/env python3 """Install trusted HUX session context into the pinned Hermes WebUI routes.""" from __future__ import annotations import os from pathlib import Path PINNED_UPSTREAM_COMMIT = "7a94e34a6d639576576baa9131acf6765f6d2b98" ROOT = Path(os.environ.get("HERMES_WEBUI_PATCH_ROOT", "/opt/hermes-webui")) MODULE_SOURCE = Path(__file__).with_name("hermes-webui-hux-context.py") def _patched_routes(source: str) -> str: if "from api.hux_context import attach_hux_context" in source: raise SystemExit("Hermes HUX context patch is already installed") replacements = ( ( " redact = redact_session_data(raw)\n", " redact = redact_session_data(raw)\n" " from api.hux_context import attach_hux_context\n" " redact = attach_hux_context(handler, redact)\n", ), ( ' return j(handler, {"session": redact_session_data(sess)})\n', " from api.hux_context import attach_hux_context\n" ' return j(handler, {"session": attach_hux_context(\n' " handler, redact_session_data(sess)\n" " )})\n", ), ( ' payload = {"session": s.compact() | {"messages": s.messages}}\n', " from api.hux_context import attach_hux_context\n" ' payload = {"session": attach_hux_context(\n' ' handler, s.compact() | {"messages": s.messages}\n' " )}\n", ), ( " return j(handler, response, status=status)\n", " from api.hux_context import attach_hux_context\n" " response = attach_hux_context(handler, response)\n" " return j(handler, response, status=status)\n", ), ) for before, after in replacements: if source.count(before) != 1: raise SystemExit(f"Hermes HUX context patch changed: {before.strip()!r}") source = source.replace(before, after, 1) return source def apply(root: Path | None = None, module_source: Path | None = None) -> None: """Validate all pinned anchors, then install the module and route calls.""" root = root or ROOT routes = root / "api/routes.py" source_path = module_source or MODULE_SOURCE module = source_path.read_text(encoding="utf-8") if "def attach_hux_context(" not in module or "def build_hux_context(" not in module: raise SystemExit("Hermes HUX context module is invalid") patched = _patched_routes(routes.read_text(encoding="utf-8")) (root / "api/hux_context.py").write_text(module, encoding="utf-8") routes.write_text(patched, encoding="utf-8") if __name__ == "__main__": # pragma: no cover - image entry point apply()