|
| 1 | +#!/usr/bin/env python3 |
| 2 | +"""Apply narrow, fail-fast PerkOS behavior patches to upstream Hermes.""" |
| 3 | + |
| 4 | +from pathlib import Path |
| 5 | + |
| 6 | + |
| 7 | +GATEWAY_RUN = Path("/opt/hermes/gateway/run.py") |
| 8 | +FIRST_MESSAGE_GUARD = ( |
| 9 | + "if not history and not await self.async_session_store.has_any_sessions():" |
| 10 | +) |
| 11 | +MANAGED_FIRST_MESSAGE_GUARD = """if ( |
| 12 | + not _perkos_env_flag_disabled("PERKOS_DISABLE_FIRST_MESSAGE_ONBOARDING") |
| 13 | + and not history |
| 14 | + and not await self.async_session_store.has_any_sessions() |
| 15 | + ):""" |
| 16 | +HELPER_ANCHOR = "logger = logging.getLogger(__name__)" |
| 17 | +HELPER = """ |
| 18 | +
|
| 19 | +def _perkos_env_flag_disabled(name: str) -> bool: |
| 20 | + \"\"\"Return true when a PerkOS-managed upstream behavior is disabled.\"\"\" |
| 21 | + return os.getenv(name, \"\").strip().lower() in {\"1\", \"true\", \"yes\", \"on\"} |
| 22 | +""" |
| 23 | + |
| 24 | + |
| 25 | +def replace_exactly_once(source: str, needle: str, replacement: str, label: str) -> str: |
| 26 | + count = source.count(needle) |
| 27 | + if count != 1: |
| 28 | + raise RuntimeError( |
| 29 | + f"{label}: expected exactly one upstream anchor, found {count}; " |
| 30 | + "review the Hermes update before publishing this image" |
| 31 | + ) |
| 32 | + return source.replace(needle, replacement, 1) |
| 33 | + |
| 34 | + |
| 35 | +source = GATEWAY_RUN.read_text(encoding="utf-8") |
| 36 | +source = replace_exactly_once( |
| 37 | + source, |
| 38 | + HELPER_ANCHOR, |
| 39 | + HELPER_ANCHOR + HELPER, |
| 40 | + "managed first-message helper", |
| 41 | +) |
| 42 | +source = replace_exactly_once( |
| 43 | + source, |
| 44 | + FIRST_MESSAGE_GUARD, |
| 45 | + MANAGED_FIRST_MESSAGE_GUARD, |
| 46 | + "managed first-message guard", |
| 47 | +) |
| 48 | +GATEWAY_RUN.write_text(source, encoding="utf-8") |
0 commit comments