Files
hermes-agent/gateway/response_filters.py
T
Teknium 2776813df3 compat(plugins): temporary import-path shims for external plugins — ONE commit, revert on schedule
The Sep 2026 decomposition (PR #102117) makes internal import paths a non-API: names now live in
the focused modules that define them. This commit is the ONLY thing keeping the old paths alive,
so external plugins have time to update. It is deliberately a single, unsquashed commit:

    git revert <this sha>

removes every shim, stub and manifest at once on the announced date. Nothing in-tree may depend on
these pointers: scripts/check_compat_pointers.py (wired into lint.yml) fails CI if it does.

What it adds (see COMPAT_MANIFEST.md, compat_manifest.json):
- 332 facade modules get one delimited `PLUGIN-COMPAT` block appended at the end of the file
- 1,172 moved names resolved lazily via a module `__getattr__` (PEP 562) — never a top-level import,
  so no import cycles; facades that already had `__getattr__` get a chained one
- 592 third-party/stdlib names the old modules used to expose, with their original import statements
- 266 public definitions that had been deleted as unused, restored byte-for-byte from the pre-decomposition
  tree (+40 private helpers and 16 imports pulled in only because a restored definition needs them)
- 3 deleted modules recreated as re-export stubs (gateway/startup_watchdog, hermes_cli/observability/
  relay_runtime, tools/environments/modal_utils)
- private names (`_x`) get no pointer: they were never API (3,792 skipped)

Verified: all 335 touched modules import under a fresh HERMES_HOME and every manifest name resolves;
the lint reports zero in-tree uses; ruff clean; targeted suites unchanged.
2026-09-03 17:13:22 -07:00

104 lines
4.4 KiB
Python

"""Gateway response filtering helpers.
These decide whether a completed agent turn should be delivered to the chat,
not what should be persisted in conversation history.
"""
from __future__ import annotations
import unicodedata
from typing import Any
# Exact whole-response markers meaning "the agent intentionally chose not to
# reply". Keep small and explicit; arbitrary empty output remains an
# error/empty-response path, not silence.
LIVE_GATEWAY_SILENT_MARKERS = frozenset({"[SILENT]", "SILENT", "NO_REPLY", "NO REPLY"})
# Longer than any marker could plausibly be, even with stray punctuation.
_MARKER_LENGTH_CAP = 64
def _canonical_silence_candidate(text: str) -> str:
return " ".join(text.strip().upper().split())
def _is_edge_punctuation(ch: str) -> bool:
# Square brackets stay structural so malformed ``[SILENT`` cannot become ``SILENT``.
return ch not in "[]" and unicodedata.category(ch).startswith("P")
def _strip_edge_silence_punctuation(text: str) -> str:
"""Strip stray edge punctuation (``.NO_REPLY``, ``*NO_REPLY*``) without erasing marker structure."""
start, end = 0, len(text)
while start < end and _is_edge_punctuation(text[start]):
start += 1
while end > start and _is_edge_punctuation(text[end - 1]):
end -= 1
return text[start:end].strip()
def _canonical_silence_candidates(text: Any) -> tuple[str, ...]:
"""Canonical forms of a short marker-sized response; ``()`` when not a candidate at all."""
stripped = text.strip() if isinstance(text, str) else ""
if not 0 < len(stripped) <= _MARKER_LENGTH_CAP:
return ()
depunctuated = _strip_edge_silence_punctuation(stripped)
forms = (stripped,) if depunctuated == stripped else (stripped, depunctuated)
return tuple(_canonical_silence_candidate(f) for f in forms)
def is_intentional_silence_response(response: Any) -> bool:
"""True only when ``response`` is exactly a silence marker.
Prose that merely mentions ``NO_REPLY`` must be delivered normally. A blank
response is not silence either — that is the empty-response failure path.
"""
return any(c in LIVE_GATEWAY_SILENT_MARKERS for c in _canonical_silence_candidates(response))
def is_autonomous_silence_response(response: Any) -> bool:
"""Loose silence matcher for autonomous lanes (cron, webhook).
Models reliably bracket ``[SILENT]`` with a short note, so unlike the
interactive EXACT rule this also suppresses when a marker sits on its own
first/last line or the bracketed sentinel opens the response (``[SILENT] No
changes detected``). A token buried mid-sentence is still delivered.
Shares :data:`LIVE_GATEWAY_SILENT_MARKERS` so the two sets cannot drift.
"""
stripped = response.strip() if isinstance(response, str) else ""
if not stripped:
return False
lines = [ln for ln in stripped.splitlines() if ln.strip()]
# Bracketed form only for the prefix rule, so a bare "Silent retry succeeded" is NOT swallowed.
return stripped.upper().startswith("[SILENT]") or any(
_canonical_silence_candidate(c) in LIVE_GATEWAY_SILENT_MARKERS for c in (stripped, lines[0], lines[-1])
)
def is_intentional_silence_agent_result(agent_result: dict | None, response: Any) -> bool:
"""Silence markers suppress delivery only for successful agent turns."""
return isinstance(agent_result, dict) and not agent_result.get("failed") and is_intentional_silence_response(response)
def is_partial_silence_marker(text: Any) -> bool:
"""True while streamed ``text`` could still resolve to a silence marker.
A buffer whose canonical form is a non-empty *prefix* of a marker (``"NO"`` on
the way to ``"NO_REPLY"``, or an exact marker not yet terminated by stream-end)
is held back so a raw marker is never shown and then retracted. Divergence
from every marker, or exceeding the cap, resumes normal streaming.
"""
return any(
c and any(marker.startswith(c) for marker in LIVE_GATEWAY_SILENT_MARKERS)
for c in _canonical_silence_candidates(text)
)
# ---- 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.
SILENT_REPLY_TOKEN = "NO_REPLY"
# ---- END PLUGIN-COMPAT ----