Files
hermes-agent/gateway/sticker_cache.py
srojk34 e70db09f51 fix(security): re-resolve checkpoint/sticker-cache paths per call
tools/checkpoint_manager.py's CHECKPOINT_BASE and gateway/sticker_cache.py's
CACHE_PATH are resolved once at import time via get_hermes_home(), which is
a context-local ContextVar under the multiplexed gateway (multiple profiles
sharing one process). Freezing the path at import time pins every later
checkpoint/cache read-write to whichever profile's HERMES_HOME was active
when the module was first imported -- the same bug class already fixed for
cache dirs, skills_hub, rich_sent_store, and (this session) the OAuth/auth.json/
sessions.json paths.

CheckpointManager is "owned by AIAgent" per-instance, but its methods read
the frozen module constant directly instead of taking the store root from
the instance, so a profile's CheckpointManager can read/write code-edit
checkpoints into a different profile's store.

Add a per-call resolver for each path, following the established "respect
an existing test monkeypatch of the constant, otherwise re-resolve through
get_hermes_home()" pattern so the extensive existing test seams in
tests/tools/test_checkpoint_manager.py and tests/gateway/test_sticker_cache.py
keep working unmodified.

(cherry picked from commit 03ae075d969094cb584e6ab38d2a773d15ff875c)
(cherry picked from commit b850c4b18e2ae2158a97c6cb87bd2057918b8170)
2026-09-11 15:44:00 -07:00

82 lines
3.1 KiB
Python

"""Sticker description cache for Telegram.
Stickers are described via the vision tool once and cached by file_unique_id
(``~/.hermes/sticker_cache.json``) so the same image is never re-analyzed.
"""
import json
import time
from pathlib import Path
from typing import Optional
from hermes_cli.config import get_hermes_home
from utils import atomic_json_write
CACHE_PATH = get_hermes_home() / "sticker_cache.json"
_CACHE_PATH_AT_IMPORT = CACHE_PATH
def _resolve_cache_path() -> Path:
"""Active profile's cache file at call time: the patched ``CACHE_PATH`` when a test changed
it, else live profile-scoped HERMES_HOME — under the multiplexed gateway one process serves
every profile, so the import-time constant would pin every profile to the launch home."""
return CACHE_PATH if CACHE_PATH != _CACHE_PATH_AT_IMPORT else get_hermes_home() / "sticker_cache.json"
# Kept concise to save tokens.
STICKER_VISION_PROMPT = (
"Describe this sticker in 1-2 sentences. Focus on what it depicts -- "
"character, action, emotion. Be concise and objective."
)
def _load_cache() -> dict:
try:
return json.loads(_resolve_cache_path().read_text(encoding="utf-8"))
except (FileNotFoundError, json.JSONDecodeError, OSError):
return {}
def _save_cache(cache: dict) -> None:
atomic_json_write(_resolve_cache_path(), cache)
def get_cached_description(file_unique_id: str) -> Optional[dict]:
"""Return ``{description, emoji, set_name, cached_at}`` or None."""
return _load_cache().get(file_unique_id)
def cache_sticker_description(
file_unique_id: str, description: str, emoji: str = "", set_name: str = ""
) -> None:
"""Store a vision-generated description under Telegram's stable sticker id."""
entry = {"description": description, "emoji": emoji, "set_name": set_name,
"cached_at": time.time()}
_save_cache({**_load_cache(), file_unique_id: entry})
def build_sticker_injection(description: str, emoji: str = "", set_name: str = "") -> str:
"""Warm-style injection text, e.g.
``[The user sent a sticker 😀 from "MyPack"~ It shows: "A cat waving" (=^.w.^=)]``.
``set_name`` is only shown together with an emoji."""
context = f" {emoji}" if emoji else ""
if set_name and emoji:
context += f' from "{set_name}"'
return f'[The user sent a sticker{context}~ It shows: "{description}" (=^.w.^=)]'
def build_animated_sticker_injection(emoji: str = "") -> str:
"""Injection text for animated/video stickers we can't analyze."""
if emoji:
return (f"[The user sent an animated sticker {emoji}~ "
f"I can't see animated ones yet, but the emoji suggests: {emoji}]")
return "[The user sent an animated sticker~ I can't see animated ones yet]"
# ---- BEGIN PLUGIN-COMPAT (revert-scheduled; see COMPAT_MANIFEST.md) ----
# Names external plugins imported from this module before the Sep 2026 decomposition.
# Internal code MUST NOT use these (scripts/check_compat_pointers.py fails CI if it does).
# The whole block is removed by reverting the commit that added it.
import os # noqa: F401,E402
import tempfile # noqa: F401,E402
# ---- END PLUGIN-COMPAT ----